{"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# \u2554\u2550\u2561 49e8e6f6-0483-11eb-0a74-d94aa536c9ab\nusing LinearAlgebra, Plots, Zygote, PlutoUI\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5e4eabba-0483-11eb-09a4-31ae6c582d3e\nf((x1, x2)) = 2x1^2 +1.4x1*x2 + x2^2 - 0.3x1 + x1 \n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5503c842-0591-11eb-0104-359b9ebd5e98\nmd\"Show the countour of $f(\\mathbf{x})$:\"\n\n# \u2554\u2550\u2561 47067fc8-058c-11eb-224c-6fe2e470107f\n@bind show_f_contour CheckBox()\n\n# \u2554\u2550\u2561 c369c65e-0598-11eb-0a90-dd4db070c99b\nshow_f_contour\n\n# \u2554\u2550\u2561 60328136-0591-11eb-1929-b7515a8c03d9\nmd\"Show the countour of $g(\\mathbf{x})$:\"\n\n# \u2554\u2550\u2561 d10b14c2-058c-11eb-3a43-7bca5d042969\n@bind show_g_contour CheckBox()\n\n# \u2554\u2550\u2561 ba835a96-0598-11eb-1d54-9365e3ea337f\nshow_g_contour\n\n# \u2554\u2550\u2561 681a031a-0591-11eb-2fec-8d94eca758f8\nmd\"Show the function $g(\\mathbf{x})=0$:\"\n\n# \u2554\u2550\u2561 13467b42-058d-11eb-3023-b9d3f145335b\n@bind show_g0_constraint CheckBox()\n\n# \u2554\u2550\u2561 ca227ac2-0598-11eb-3a39-f1a90769ac52\nshow_g0_constraint\n\n# \u2554\u2550\u2561 d8276f26-0598-11eb-1626-95f87cf6de22\nmd\"Show the gradients:\"\n\n# \u2554\u2550\u2561 60c41848-0592-11eb-39ef-7103ae834990\n@bind show_gradients CheckBox()\n\n# \u2554\u2550\u2561 d16723ca-0598-11eb-02f4-f1c5d45095a5\nshow_gradients\n\n# \u2554\u2550\u2561 95dc760a-058e-11eb-2149-898b2776079f\n@bind t Slider(0:0.01:2\u03c0, default=4.3)\n\n# \u2554\u2550\u2561 41d8c8d0-0591-11eb-2cd7-3b53f91ef589\nt\n\n# \u2554\u2550\u2561 aef30ee8-0597-11eb-2203-ed0f9b14f0e4\nt\n\n# \u2554\u2550\u2561 00a009a2-0599-11eb-341f-3364198e1753\nmd\"We plot the objective value on the equality constraint.\"\n\n# \u2554\u2550\u2561 13b4ad4a-0599-11eb-0043-6bfc0eb23389\nmd\"At the minimizer, the gradients are parallel.\"\n\n# \u2554\u2550\u2561 7e77e628-0707-11eb-1b2f-27b5c5819260\n# compute angle between two vectors\nangle(u, v) = acos(dot(u, v) / (norm(u) * norm(v)))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2d7ae208-0599-11eb-1a91-277b764ad45e\nmd\"Change the location of the constraint\"\n\n# \u2554\u2550\u2561 c98b4f9a-0592-11eb-2034-5f05e792cbd2\n@bind R Slider(10:0.5:25, default=16)\n\n# \u2554\u2550\u2561 bd7b55ae-0599-11eb-1056-ed3682fe8160\ng((x1, x2)) = (x1-10)^2 + (x2-17)^2 - R^2\n\n# \u2554\u2550\u2561 c10838a2-0599-11eb-32e3-1579a926f9b7\ng0(t) = [R*cos(t) + 10, R*sin(t) + 17]\n\n# \u2554\u2550\u2561 d2c4ffe2-0485-11eb-0e20-dd52446fa3a6\nx = g0(t)\n\n# \u2554\u2550\u2561 6e89822c-070b-11eb-06f3-8b8e20aaa57d\nf(x)\n\n# \u2554\u2550\u2561 e944567a-0596-11eb-2cf1-75f196bab4d1\nf'(x) / norm(f'(x))\n\n# \u2554\u2550\u2561 02673cec-0597-11eb-2db4-e9f7d9047ac0\ng'(x) / norm(g'(x))\n\n# \u2554\u2550\u2561 c04a0ffe-0707-11eb-2a74-b3b258b4aec6\nangle(f'(x), g'(x))  # close to 0 or pi if stationary point\n\n# \u2554\u2550\u2561 f47ce686-0485-11eb-2a33-4bd0b150b18b\ng(x)\n\n# \u2554\u2550\u2561 b0cf9a40-058f-11eb-13dc-b7c35328ef2a\nbegin\n\tplot(t -> f(g0(t)), 0:0.01:2\u03c0, 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# \u2554\u2550\u2561 be35a06c-0596-11eb-2988-61a79c7e6a87\nR\n\n# \u2554\u2550\u2561 a08e7230-0591-11eb-3956-fb6c2d756494\nfconstr(x) = g(x) \u2264 0.0 ? f(x) : NaN\n\n# \u2554\u2550\u2561 81629936-0593-11eb-3fca-afa68e2ace3d\n@bind t_approx Slider(0.1:0.05:10.0, default=1.0)\n\n# \u2554\u2550\u2561 a1402cbc-0593-11eb-33b4-09a0c654eefd\nt_approx\n\n# \u2554\u2550\u2561 cc4209ee-0593-11eb-3762-e76539e2a455\nI\u0302\u208b(u) = u < 0.0 ? -(1/t_approx)* log(-u) : Inf\n\n# \u2554\u2550\u2561 a398740e-0593-11eb-2f81-c92861e080b8\nbegin\n\tplot(-3:0.001:2, I\u0302\u208b, 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# \u2554\u2550\u2561 dce25666-0594-11eb-24f9-85eba4949d1e\nfsoft(x) = g(x) \u2264 0.0 ? t_approx * f(x) + I\u0302\u208b(g(x)) : NaN\n\n# \u2554\u2550\u2561 701efa2a-0596-11eb-2592-39eced2fb875\n@bind show_soft_grads CheckBox()\n\n# \u2554\u2550\u2561 7c5d381a-0596-11eb-1dfe-0b7074093cd6\nshow_soft_grads\n\n# \u2554\u2550\u2561 7c934678-0599-11eb-1e6b-1f2c9003509a\nmd\"## Utilities\"\n\n# \u2554\u2550\u2561 865bbb8e-0483-11eb-0622-b9a8a6ba5d4c\nx1min, x1max = -8.0, 15.0\n\n# \u2554\u2550\u2561 9736f388-0483-11eb-069a-0d5ed87efb73\nx2min, x2max = -8.0, 12.0\n\n# \u2554\u2550\u2561 f39f0106-0483-11eb-3617-5fb04388489e\ngrads(f, x) = 0.1f'(x) |> df -> Tuple([e] for e in df)\n\n# \u2554\u2550\u2561 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\u03c0], [g0(t)[2] for t in 0:0.01:2\u03c0], 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# \u2554\u2550\u2561 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\u03c0], [g0(t)[2] for t in 0:0.01:2\u03c0], 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# \u2554\u2550\u2561 52bacf14-0595-11eb-33c9-dd5c40125360\n\u2207fsoft(x) = g(x) \u2264 0.0 ? fsoft'(x) : [0.0, 0.0]\n\n# \u2554\u2550\u2561 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\u03c0], [g0(t)[2] for t in 0:0.01:2\u03c0], lw=2, color=:red, label=\"g(x)=0\")\n\tshow_soft_grads && quiver!(x1min:2:x1max, (x2min:2:x2max)', quiver=(x1, x2)->-0.05.*\u2207fsoft((x1, x2)), color=:pink)\n\txlims!(x1min, x1max)\n\tylims!(x2min, x2max)\nend\n\n# \u2554\u2550\u2561 0a5783e2-0596-11eb-1e38-a5da40325159\n\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u255049e8e6f6-0483-11eb-0a74-d94aa536c9ab\n# \u255f\u2500fccca5fc-0597-11eb-1033-a5cc3b71d854\n# \u2560\u25505e4eabba-0483-11eb-09a4-31ae6c582d3e\n# \u2560\u2550bd7b55ae-0599-11eb-1056-ed3682fe8160\n# \u255f\u2500470048ec-0598-11eb-0d48-67357ed1f12c\n# \u2560\u2550c10838a2-0599-11eb-32e3-1579a926f9b7\n# \u2560\u255041d8c8d0-0591-11eb-2cd7-3b53f91ef589\n# \u2560\u2550d2c4ffe2-0485-11eb-0e20-dd52446fa3a6\n# \u2560\u25506e89822c-070b-11eb-06f3-8b8e20aaa57d\n# \u2560\u2550f47ce686-0485-11eb-2a33-4bd0b150b18b\n# \u255f\u25005503c842-0591-11eb-0104-359b9ebd5e98\n# \u255f\u250047067fc8-058c-11eb-224c-6fe2e470107f\n# \u255f\u2500c369c65e-0598-11eb-0a90-dd4db070c99b\n# \u255f\u250060328136-0591-11eb-1929-b7515a8c03d9\n# \u255f\u2500d10b14c2-058c-11eb-3a43-7bca5d042969\n# \u255f\u2500ba835a96-0598-11eb-1d54-9365e3ea337f\n# \u255f\u2500681a031a-0591-11eb-2fec-8d94eca758f8\n# \u255f\u250013467b42-058d-11eb-3023-b9d3f145335b\n# \u255f\u2500ca227ac2-0598-11eb-3a39-f1a90769ac52\n# \u255f\u2500d8276f26-0598-11eb-1626-95f87cf6de22\n# \u255f\u250060c41848-0592-11eb-39ef-7103ae834990\n# \u255f\u2500d16723ca-0598-11eb-02f4-f1c5d45095a5\n# \u255f\u2500828cbe72-0483-11eb-33b2-7f4f37db889f\n# \u2560\u255095dc760a-058e-11eb-2149-898b2776079f\n# \u2560\u2550aef30ee8-0597-11eb-2203-ed0f9b14f0e4\n# \u255f\u250000a009a2-0599-11eb-341f-3364198e1753\n# \u255f\u2500b0cf9a40-058f-11eb-13dc-b7c35328ef2a\n# \u255f\u250013b4ad4a-0599-11eb-0043-6bfc0eb23389\n# \u2560\u2550e944567a-0596-11eb-2cf1-75f196bab4d1\n# \u2560\u255002673cec-0597-11eb-2db4-e9f7d9047ac0\n# \u2560\u25507e77e628-0707-11eb-1b2f-27b5c5819260\n# \u2560\u2550c04a0ffe-0707-11eb-2a74-b3b258b4aec6\n# \u255f\u2500358f21ca-0599-11eb-3bfb-0bb12a1465bb\n# \u255f\u25002d7ae208-0599-11eb-1a91-277b764ad45e\n# \u2560\u2550c98b4f9a-0592-11eb-2034-5f05e792cbd2\n# \u2560\u2550be35a06c-0596-11eb-2988-61a79c7e6a87\n# \u2560\u2550a08e7230-0591-11eb-3956-fb6c2d756494\n# \u255f\u2500c2640938-0591-11eb-058c-5949d1e316d3\n# \u255f\u250081629936-0593-11eb-3fca-afa68e2ace3d\n# \u2560\u2550a1402cbc-0593-11eb-33b4-09a0c654eefd\n# \u2560\u2550cc4209ee-0593-11eb-3762-e76539e2a455\n# \u255f\u2500a398740e-0593-11eb-2f81-c92861e080b8\n# \u2560\u2550dce25666-0594-11eb-24f9-85eba4949d1e\n# \u255f\u2500701efa2a-0596-11eb-2592-39eced2fb875\n# \u2560\u25507c5d381a-0596-11eb-1dfe-0b7074093cd6\n# \u255f\u25000b93638a-0595-11eb-3096-af3cc7202aa5\n# \u255f\u25007c934678-0599-11eb-1e6b-1f2c9003509a\n# \u2560\u2550865bbb8e-0483-11eb-0622-b9a8a6ba5d4c\n# \u2560\u25509736f388-0483-11eb-069a-0d5ed87efb73\n# \u2560\u2550f39f0106-0483-11eb-3617-5fb04388489e\n# \u2560\u255052bacf14-0595-11eb-33c9-dd5c40125360\n# \u2560\u25500a5783e2-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": "\nusing SafeTestsets\n\n@safetestset \"Harmonic Oscillator                                                             \" begin include(\"harmonic_oscillator_tests.jl\") end\n@safetestset \"Kubo Oscillator                                                                 \" begin include(\"kubo_oscillator_tests.jl\") end\n@safetestset \"Lorenz Attractor                                                                \" begin include(\"lorenz_attractor_tests.jl\") end\n@safetestset \"Lotka-Volterra 2D                                                               \" begin include(\"lotka_volterra_2d_tests.jl\") end\n@safetestset \"Lotka-Volterra 2D with singular Lagrangian                                      \" begin include(\"lotka_volterra_2d_singular_tests.jl\") end\n@safetestset \"Lotka-Volterra 2D with symmetric Lagrangian                                     \" begin include(\"lotka_volterra_2d_symmetric_tests.jl\") end\n@safetestset \"Lotka-Volterra 2D with symmetric Lagrangian with gauge terms                    \" begin include(\"lotka_volterra_2d_gauge_tests.jl\") end\n@safetestset \"Lotka-Volterra 3D                                                               \" begin include(\"lotka_volterra_3d_tests.jl\") end\n@safetestset \"Lotka-Volterra 4D                                                               \" begin include(\"lotka_volterra_4d_tests.jl\") end\n@safetestset \"Lotka-Volterra 4D (Lagrangian)                                                  \" begin include(\"lotka_volterra_4d_lagrangian_tests.jl\") end\n@safetestset \"Point Vortices                                                                  \" begin include(\"point_vortices_tests.jl\") end\n", "meta": {"hexsha": "2d83d00d93b82a075db55a8b67a2c43d79180ced", "size": 1637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 109.1333333333, "max_line_length": 154, "alphanum_fraction": 0.5296273671, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.7999857746423115}}
{"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\u2090 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    \u03bc = mean(x)\n    \u03c3\u00b2= 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] - \u03bc) * (x[t+i] - \u03bc)\n        end\n\n        R[i] = ( 1 / ( (length(x) - i) * \u03c3\u00b2 ) ) * 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    \u03bc = mean(x)\n    \u03c3\u00b2= var(x)\n\n    sum = 0.\n    for t in 1:(n-lag)\n        sum += (x[t] - \u03bc) * (x[t+lag] - \u03bc)\n    end\n\n    return (1 / ((n-lag) * \u03c3\u00b2)) * 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\u2096 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 = - \u2211\u1d50\u1d62\u208c\u2081 p\u1d62 * log(p\u1d62)\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 \u2265 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    \u03bc = mean(x)\n    r_sigma = r * std(x)\n\n    aux = map(abs, map(x -> x - \u03bc, 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 \u2264 n_chunks && n_chunks \u2264 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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.18\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.18\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550bfe8d6f0-2163-11eb-22e7-9b978bc1d407\n# \u255f\u250070182cd8-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(.)) \u2013 Assessed by Rmpfr**\" by Martin M\u00e4chler\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(.)) \u2013 Assessed by Rmpfr**\" by Martin M\u00e4chler\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(.)) \u2013 Assessed by Rmpfr**\" by Martin M\u00e4chler\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    \u03ba :: 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) |> \u03bb -> \u03bb./maximum(\u03bb)\n    a = (1 - 1/\u03ba)/(1 - minimum(sig))\n    b = 1 - a\n    \u03c3 =  a.*sig .+ b\n    (min(m, n) > r) && append!(\u03c3, zeros(min(m, n) - r))\n\n    #Return Matrix\n    return u*diagm(m, n, 0 => \u03c3)*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\u2080<h\u2081<h\u2082`.\n`h_1` is the minimum, `h_2` is the maximum of the wave.\nAs `h\u2080 -> h\u2081`, 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\u2080<h\u2081<h\u2082` and dimensionless parameters `\u03f5` and `\u03bc`, 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`(\u03b7,u,v,mesh,param)` with\n- `\u03b7 :: 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        \u03f5 = param.\u03f5\n        \u03bc = param.\u03bc\n\n        h\u2080=param.h\u2080\n        h\u2081=param.h\u2081\n        h\u2082=param.h\u2082\n        c = sqrt(h\u2080*h\u2081*h\u2082)\n        @info string(\"The velocity is c=\",c)\n        m = sqrt((h\u2082-h\u2081)/(h\u2082-h\u2080))\n        \u03ba = sqrt(3*(h\u2082-h\u2080))/(2*c)/sqrt(\u03bc)\n        \u03bb = Elliptic.K(m^2)/\u03ba\n        @info string(\"The period is 2*\u03bb=\",2*\u03bb)\n        mesh = Mesh((L=P*\u03bb,N=param.N))\n        formula = h\u2081 .-1 .+ (h\u2082-h\u2081)*(Jacobi.cn.(\u03ba*mesh.x,m^2).^2)\n\n        a\u2080 = h\u2080\n        a\u2081 = h\u2082 - h\u2080\n        formula2 = a\u2080 .-1 .+ a\u2081*(Jacobi.dn.(\u03ba*mesh.x,m^2).^2)\n        H\u2080= a\u2080+a\u2081*Elliptic.E(m^2)/Elliptic.K(m^2)\n        u2 = c*(1 ./ H\u2080 .- 1 ./(1 .+ formula2))\n        param = (h\u2080=h\u2080,h\u2081=h\u2081,h\u2082=h\u2082,a\u2080=a\u2080,a\u2081=a\u2081,H\u2080=H\u2080,c=c,\u03bb=\u03bb,m=m,\u03ba=\u03ba)\n\n\n        \u03b7 = formula/\u03f5\n        h = 1 .+ \u03f5*\u03b7\n        u = c*\u03b7./h\n\tk = mesh.k\n        Dx=  1im * k\n\tF\u2080 = sqrt(\u03bc)*Dx\n        DxF(v) = real.(ifft(F\u2080 .* fft(v)))\n\tv = u - 1/3 ./h .* (DxF(h.^3 .*DxF(u)))\n        #\n        # h2 = 1 .+ \u03f5*formula2\n        # v2 = u2 - 1/3 ./h2 .* (DxF(h2.^3 .*DxF(u2)))\n\n        return (\u03b7,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\u2080 by solving F(m) = 0 \"\nfunction mag(\u03b2, mass)\n    \n    F(m) = begin\n        g(x, n, m) = (1 / \u03c0) * (exp(\u03b2 * 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, \u03c0)[1] / quadgk(bessel0, 0, \u03c0)[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    \u03f5    :: Float64\n\n    function HMF( mass, T, \u03f5 )\n\n        b = 1 / T\n        m = mag(b, mass)\n        w = sqrt(m)\n        new( b, m, \u03f5 )\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+\u03f5*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": "# # The Passport Problem\n\n# Let's now apply what we have learnt to solve a real modelling problem.\n\n# The [Passport Index Dataset](https://github.com/ilyankou/passport-index-dataset)\n# lists travel visa requirements for 199 countries, in `.csv` format. Our task\n# is to find out the minimum number of passports required to visit all\n# countries without  requiring a visa.\n\n# ## Data handling\n\n# Read the following file into a dataframe:\n\nconst DATA_FILENAME = joinpath(@__DIR__, \"data\", \"passport-index-matrix.csv\")\n\npassport_data = nothing  # Replace this with Code\n\n# In this dataset, the first column represents a passport (=from) and each\n# remaining column represents a foreign country (=to).\n\n# The values in each cell are as follows:\n# * 3 = visa-free travel\n# * 2 = eTA is required\n# * 1 = visa can be obtained on arrival\n# * 0 = visa is required\n# * -1 is for all instances where passport and destination are the same\n\n# Extract the list of country names\n\ncountries = nothing  # Replace this with code\n\n# Let's check that you found all 199 countries\n\n@assert length(countries) == 199\n\n# The values we are interested in are -1 and 3. Modify the dataframe so that\n# the -1 and 3 are `1` (true), and all others are `0` (false).\n\nnothing  # Replace this with code\n\n# The values in the dataframe should now represent:\n#  * 1 = no visa required for travel\n#  * 0 = visa required for travel\n\n# ## Visualization\n\n# Produce a visualization of the passport data.  For example, you might want to\n# plot a histogram of the number of countries that have visa-free travel.\n\nnothing\n\n# ## Modelling\n\n# We can formulate the passport problem in math as follows:\n# ```math\n# \\begin{aligned}\n# \\min && \\sum_{i \\in I} x_i \\\\\n# \\text{s.t.} && \\sum_{i \\in I} a_{i,j} \\cdot x_i \\geq 1 && \\forall j \\in I \\\\\n# && x_i \\in \\{0,1\\} && \\forall i \\in I\n# \\end{aligned}\n# ```\n# where $x_i$ is a binary variable indicating if we want to select passport $i$,\n# and $a_{i,j}$ is 1 if there is visa-free travel between countries $i$ and $j$,\n# and 0 otherwise.\n\n# Formulate and solve this problem with JuMP.\n\nnothing\n", "meta": {"hexsha": "ec1135b5699acf9e49a806b71b5e7faa8a4ff3a7", "size": 2092, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/passport_travel.jl", "max_stars_repo_name": "blegat/jump-training-materials", "max_stars_repo_head_hexsha": "83dd747273ded55bb91be0288864ca6d4f742711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-08-31T05:32:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T08:33:50.000Z", "max_issues_repo_path": "src/passport_travel.jl", "max_issues_repo_name": "blegat/jump-training-materials", "max_issues_repo_head_hexsha": "83dd747273ded55bb91be0288864ca6d4f742711", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/passport_travel.jl", "max_forks_repo_name": "blegat/jump-training-materials", "max_forks_repo_head_hexsha": "83dd747273ded55bb91be0288864ca6d4f742711", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T05:37:06.000Z", "avg_line_length": 30.3188405797, "max_line_length": 82, "alphanum_fraction": 0.706500956, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7998596641271299}}
{"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\u00d7n 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 (\u03c0/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\u2081 \u2265 0)\n@variable(m, x\u2082 \u2265 0)\n\n@objective(m, Max, 3000x\u2081  + 5000x\u2082)\n@constraint(m, 3x\u2081 + 2x\u2082 \u2264 18)\n@constraint(m, x\u2081 \u2264 4)\n@constraint(m, x\u2082 \u2264 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\u2081 = \", value(x\u2081))\nprintln(\"x\u2082 = \", value(x\u2082))\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 \u2208 \u211c^{n\u00d7n}, 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(;\u03b1=0.001, \u03b2\u2081=0.9, \u03b2\u2082=0.999, \u03f5=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    \u03f5::Float64\n    \u03b1::Float64\n    \u03b2\u2081::Float64\n    \u03b2\u2082::Float64\n    m_t::AbstractArray\n    v_t::AbstractArray\nend\n\n\nfunction Adam(;\u03b1::Real=0.001, \u03b2\u2081::Real=0.9, \u03b2\u2082::Real=0.999, \u03f5::Real=10e-8)\n    @assert \u03b1 > 0.0 \"\u03b1 must be greater than 0\"\n    @assert \u03b2\u2081 > 0.0 \"\u03b2\u2081 must be greater than 0\"\n    @assert \u03b2\u2082 > 0.0 \"\u03b2\u2082 must be greater than 0\"\n    @assert \u03f5 > 0.0 \"\u03f5 must be greater than 0\"\n\n    Adam(\"Adam\", 0, \u03f5, \u03b1, \u03b2\u2081, \u03b2\u2082, [], [])\nend\n\nparams(opt::Adam) = \"\u03f5=$(opt.\u03f5), \u03b1=$(opt.\u03b1), \u03b2\u2081=$(opt.\u03b2\u2081), \u03b2\u2082=$(opt.\u03b2\u2082)\"\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.\u03b2\u2081 * opt.m_t + (one(T) - opt.\u03b2\u2081) * g_t\n\n    # update biased second raw moment estimate\n    opt.v_t = opt.\u03b2\u2082 * opt.v_t + (one(T) - opt.\u03b2\u2082) * ((g_t) .^2)\n\n    # compute bias corrected first moment estimate\n    m\u0302_t = opt.m_t / (one(T) - opt.\u03b2\u2081^opt.t)\n\n    # compute bias corrected second raw moment estimate\n    v\u0302_t = opt.v_t / (one(T) - opt.\u03b2\u2082^opt.t)\n\n    # apply update\n    \u03c1 = opt.\u03b1 * m\u0302_t ./ (sqrt.(v\u0302_t .+ opt.\u03f5))\n\n    return \u03c1\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``\u03c3(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``\u03c3(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": "# # Labelled Graphs\n# This example demonstrates how to define new C-Sets from existing C-Sets via the example of adding labels to a graph. We treat labels as members of an arbitrary FinSet of labels rather than a data attribute for pedagogical reasons. When you think of graphs where the labels are numbers, colors, or values of some kind, you would want to make them attributes. The motivation for this example is to be the simplest extension to the theory of graphs that you could possibly make. \n\nusing Catlab, Catlab.Theories\nusing Catlab.CategoricalAlgebra\nusing Catlab.Graphs\nusing Catlab.Graphics\nusing Catlab.Graphics.Graphviz\nusing Colors\ndraw(g) = to_graphviz(g, node_labels=true, edge_labels=true)\n\n# We start with the theory of graphs, which is copied from `Catlab.Graphs.BasicGraphs`. The two objects are the edges and vertices and we have two functions `src,tgt` that assign to every edge the source vertex and target vertex respectively. Functors from this category to Set (diagrams in Set of this shape) are category theoretic graphs (directed multigraphs).\n@present TheoryGraph(FreeSchema) begin\n  V::Ob\n  E::Ob\n  src::Hom(E,V)\n  tgt::Hom(E,V)\nend\n\nto_graphviz(Catlab.Graphs.BasicGraphs.TheoryGraph)\n\n# To the theory of graphs we want to add a set of labels `L` and map that assigns to every vertex to its label in `L`.\n@present TheoryLGraph <: TheoryGraph begin\n  L::Ob\n  label::Hom(V,L)\nend\n\n# Catlab will automatically generate all the data structure and algorithms (storing, mutating, serializing, etc.) our `LGraphs` for us. This snippet declares that the Julia type `LGraph` should be composed of objects of the functor category `TheoryLGraph \u2192 Skel(FinSet)`, where `Skel(FinSet)` is the subcategory of Set containing finite sets `1:n`. We want our Julia type `LGraph` to inherit from the Graphs.jl type `AbstractGraph` so that we can run graph algorithms on it. And we want the generated data structures to make an index of the maps `src`, `tgt`, and `label` so that looking up the in and outneighbors of vertex is fast and accessing all vertices by label is also fast.  \n\n@acset_type LGraph(TheoryLGraph, index=[:src,:tgt,:label]) <: AbstractGraph\n\n# We need to tell Catlab how to convert our `LGraph` type into the normal `Graph` type by taking just the edges and vertices. This could be computed with Functorial Data Migration, but that is left for another sketch.\nto_graph(g::LGraph) = begin\n  h = Graphs.Graph(nparts(g,:V))\n  for e in edges(g)\n    add_edge!(h, g[e, :src], g[e,:tgt])\n  end\n  return h\nend\n\n# Graphviz doesn't automatically know how we want to draw the labels, so we have to explicitly provide code that converts them to colors on the vertices. Note that we aren't calling these colored graphs, because that would imply some connectivity constraints on which vertices are allowed to be colored with the same colors. These labels are arbitrary, but we use color to visually encode them.\nGraphvizGraphs.to_graphviz(g::LGraph; kw...) =\n  to_graphviz(GraphvizGraphs.to_graphviz_property_graph(g; kw...))\n\nfunction GraphvizGraphs.to_graphviz_property_graph(g::LGraph; kw...)\n  h = to_graph(g)\n  pg = GraphvizGraphs.to_graphviz_property_graph(h; kw...)\n  vcolors = hex.(range(colorant\"#0021A5\", stop=colorant\"#FA4616\", length=nparts(g, :L)))\n  for v in vertices(g)\n    l = g[v, :label]\n    set_vprops!(pg, v, Dict(:color => \"#$(vcolors[l])\"))\n  end\n  pg\nend\n\ndraw(G::LGraph) = to_graphviz(G, node_labels=true, edge_labels=true)\n\n# Now we can start making some `LGraph` instances.\nG = @acset LGraph begin\n  V = 4\n  E = 4\n  L = 4\n  src = [1,1,2,3]\n  tgt = [2,3,4,4]\n  label = [1,2,3,4]\nend\n\ndraw(G)\n\n# The graph `G` has a 1-1 map between vertices and labels. That isn't necessary. \nH = @acset LGraph begin\n  V = 4\n  E = 4\n  L = 3\n  src = [1,1,2,3]\n  tgt = [2,3,4,4]\n  label = [1,2,2,3]\nend\n\ndraw(H)\n\n# We can look at some homomorphisms from G to H by their action on the labels or on the vertices.\nhoms\u1d65(G,H) = map(\u03b1 -> \u03b1[:V], homomorphisms(G, H))\nhoms\u2097(G,H) = map(\u03b1 -> \u03b1[:L], homomorphisms(G, H))\n\n# \u03b1\u2097: G\u2192 H\nhoms\u2097(G,H)\n\n# \u03b1\u1d65: G\u2192 H\nhoms\u1d65(G,H)\n\n# Note that if we reverse the direction of our homomorphism search, we get fewer matches even though the two `LGraph`s are isomorphic as graphs. The fact that in `H` vertex two and three are the same label means we have to send them to the same vertex in `G`.\nhoms\u1d65(H,G)\n\n# We can build some bigger examples like A.\nA = @acset LGraph begin\n  V = 6\n  E = 7\n  L = 3\n  src = [1,1,2,3,2,5,4]\n  tgt = [2,3,4,4,5,6,6]\n  label = [1,2,2,3,2,3]\nend\ndraw(A)\n\n# and B.\nB = @acset LGraph begin\n  V = 6\n  E = 7\n  L = 4\n  src = [1,1,2,3,2,5,4]\n  tgt = [2,3,4,4,5,6,6]\n  label = [1,2,4,3,2,3]\nend\ndraw(B)\n\n# The morphisms from A to B and B to A are also different, showing how the labels affect the structure in this category.\nhoms\u1d65(A,B)\n\n# There are more morphisms from B to A than A to B.\nhoms\u1d65(B,A)\n\n# There are two automorphisms on A\nhoms\u1d65(A,A)\n\n# And two automorphisms on B\nhoms\u1d65(B,B)\n\n# But if we forget about the labels and look at the automorphisms of the underlying graph, we get more automorphisms!\nA\u2080 = to_graph(A)\nhoms\u1d65(A\u2080, A\u2080)\n\n# ## Limits and Composition by Multiplication\n# Catlab has an implementation of limits for any C-Sets over any schema. So, we can just ask about labelled graphs. Notice that we get more distinct colors in the product than in either initial graph. This is because the labels of the product are pairs of labels from the factors. If `G` has `n` colors and `H` has `m` colors `G\u00d7H` will have `n\u00d7m` colors.\ndraw(apex(product(G,G)))\n\n# The graph above looks weirdly disconnected and probably wasn't what you expected to see as the product. When we compose with products, we often want to add the reflexive edges in order to get the expected notion of product.\nadd_loops!(G::LGraph) = begin\n  for v in parts(G,:V)\n    add_edge!(G, v,v)\n  end\n  return G\nend \nadd_loops(G::LGraph) = add_loops!(copy(G))\n\nG\u1d63 = add_loops(G)\nP = apex(product(G\u1d63, G))\ndraw(apex(product(G\u1d63, G)))\n\n# We can look at the shape of commuting triangle, which is our favorite 3-vertex graph.\nT = @acset LGraph begin\n  V = 3\n  E = 3\n  L = 3\n  src = [1,1,2]\n  tgt = [2,3,3]\n  label = [1,2,3]\nend\nT\u1d63 = add_loops(T)\ndraw(T\u1d63)\n\nE = @acset LGraph begin\n  V = 2\n  E = 1\n  L = 2\n  src = [1]\n  tgt = [2]\n  label = [1,2]\nend\nE\u1d63 = add_loops(E)\ndraw(E\u1d63)\n\n# We can draw the product of the edge graph and the triangle graph to get the shape of a triangular prism. You can view this product as extruding `T\u1d63` along `E\u1d63`. Catlab provides a `ReflexiveGraph` as a type that handles these self-loops more intelligently than we are here. Graphviz struggles with the layout here because the product graph will include edges that are a step in both directions. This [blog post](https://www.algebraicjulia.org/blog/post/2021/04/cset-graphs-3/) does a good job explaining products in differnt kinds of graph categories.\ndraw(apex(product(T\u1d63,E\u1d63)))\nlegs(product(T\u1d63, E\u1d63))[1][:V] |> collect\n\n# Another limit is the pullback. If you have a cospan, which is a diagram of the shape `X \u27f6 A \u27f5 Y`, you can pull back one arrow along the other by solving a system of equations. \nPB\u2082\u2082 = pullback(homomorphisms(T\u1d63,E\u1d63)[2],homomorphisms(T\u1d63,E\u1d63)[2]);\ndraw(apex(PB\u2082\u2082))\n\n# Note that the pullback depends not only on X,A,Y but also on the two arrows. You can play around with the choice of morphisms to gain an intuition of how the pullback depends on the morphisms.\nPB\u2082\u2083 = pullback(homomorphisms(T\u1d63,E\u1d63)[2],homomorphisms(T\u1d63,E\u1d63)[3]);\ndraw(apex(PB\u2082\u2083))\n\n# By constructions, the pullback is always a subobject (monic homomorphism) into the product. Catlab can enumerate all such monoic homs.\nhomomorphisms(apex(PB\u2082\u2082), apex(product(T\u1d63,T\u1d63)), monic=true) |> length\n\n# ## Colimits and Composition by Glueing\n# The dual concept to limits is colimits and if limits have vibes of taking all pairs that satisfy certain constraints, colimits have the vibes of designers just gluing stuff together to make it work. \n\n# In order to illustrate this we will be gluing triangles together to make a mesh. We start by defining the point `X`, which is the shape of the boundary along which we will glue and the morphism `\u2113\u2081`, which is the place in `T` that we consider as the boundary.\nX = @acset LGraph begin\n  E = 0\n  V = 1\n  L = 3\n  label=[2]\nend\n\u2113\u2081 = ACSetTransformation(X,T, V=[2],L=1:3)\ndraw(X)\n\n# We have to check that the morphism is valid before we go and compute out pushout.\nis_natural(\u2113\u2081)\nP = pushout(\u2113\u2081, \u2113\u2081)\ndraw(apex(P))\n\n# Now we want to repeat the gluing process to get a bigger mesh. So we are going to need a bigger interface.\nI = @acset LGraph begin\n  V = 2\n  L = 3\n  label = [1,1]\nend\ndraw(I)\n\n# We have to specify how this interface embeds into both of the things we want to glue. In this case we are gluing a copy of `P` onto itself.\nll = ACSetTransformation(I, apex(P), V=[3,5], L =[3,1,2])\nis_natural(ll)\nlr = ACSetTransformation(I, apex(P), V=[1,4], L =[1,3,2])\nis_natural(lr)\nP\u2082 = pushout(ll, lr);\ndraw(apex(P\u2082))\n", "meta": {"hexsha": "aa1a8718575d1e0f56c06609eacde8c51374745b", "size": 8941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/graphs/graphs_label.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_label.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_label.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": 40.4570135747, "max_line_length": 684, "alphanum_fraction": 0.7226261045, "num_tokens": 2757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7997628688946946}}
{"text": "@testset \"Group properties\" begin\n\n    \u03c31 = Permutation([1, 2, 3])\n    \u03c32 = Permutation([2, 3, 1])\n    \u03c33 = Permutation([3, 1, 2])\n    \u03c41 = Permutation([1, 3, 2])\n    \u03c42 = Permutation([3, 2, 1])\n    \u03c43 = Permutation([2, 1, 3])\n    cycles = [\u03c31, \u03c32, \u03c33]\n    transpositions = [\u03c41, \u03c42, \u03c43]\n    \n    @testset \"Existence of identity\" begin\n        for \u03c0 = [cycles..., transpositions...]\n            @test \u03c31 * \u03c0 == \u03c0 * \u03c31 == \u03c0\n        end\n    end\n\n    @testset \"Existence of the inverse\" begin\n        @test \u03c32 * \u03c33 == \u03c33 * \u03c32 == \u03c31\n        for \u03c4 = transpositions\n            @test \u03c4 * \u03c4 == \u03c31\n        end\n    end\n\n    @testset \"Closeness under multiplication\" begin\n        @test \u03c32 * \u03c32 == \u03c33\n        @test \u03c33 * \u03c33 == \u03c32\n        @test \u03c41 * \u03c42 == \u03c42 * \u03c43 == \u03c43 * \u03c41 == \u03c32\n        @test \u03c43 * \u03c42 == \u03c42 * \u03c41 == \u03c41 * \u03c43 == \u03c33\n    end\n    \n    @testset \"Associativity\" begin\n        p_group = [cycles..., transpositions...]\n        for \u03c01 = p_group, \u03c02 = p_group, \u03c03 = p_group\n            @test (\u03c01 * \u03c02) * \u03c03 == \u03c01 * (\u03c02 * \u03c03)\n        end\n    end \n\nend\n", "meta": {"hexsha": "d963b146aebf3cf98a2fd694c796102a0c028eb7", "size": 1045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/group_properties.jl", "max_stars_repo_name": "felipegssantos/Permutations.jl", "max_stars_repo_head_hexsha": "1ee79de27d2e30a3d65176355ca7024d5f7493ff", "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/group_properties.jl", "max_issues_repo_name": "felipegssantos/Permutations.jl", "max_issues_repo_head_hexsha": "1ee79de27d2e30a3d65176355ca7024d5f7493ff", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-26T18:48:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T18:50:14.000Z", "max_forks_repo_path": "test/group_properties.jl", "max_forks_repo_name": "felipegssantos/Permutations.jl", "max_forks_repo_head_hexsha": "1ee79de27d2e30a3d65176355ca7024d5f7493ff", "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.125, "max_line_length": 52, "alphanum_fraction": 0.4899521531, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7997628673951973}}
{"text": "#=\nCompute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.\n\nRecall that the median of an even-numbered list is the average of the two middle numbers.\n\nFor example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:\n\n2\n1.5\n2\n3.5\n2\n2\n2\n=#\n\nusing Test\ninclude(\"Solutions/problem33_running_median.jl\")\n\n@test print_running_median([2, 1, 5, 7, 2, 0, 5], store = true) == [2, 1.5, 2, 3.5, 2, 2.0, 2]\n", "meta": {"hexsha": "9c04ba64438330c9c491540a1aa05b480ee3aecc", "size": 512, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tests/problem33_running_median_test.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": "Tests/problem33_running_median_test.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": "Tests/problem33_running_median_test.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": 24.380952381, "max_line_length": 149, "alphanum_fraction": 0.701171875, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.7997466207365403}}
{"text": "using PyPlot\n\nL = 1.0\n\u03b30 = 0.5\n\u03b3L = -0.5\nx = range(0, stop=L, length=201)\nu(x, c) = ( ( L - x ) * \u03b30 + x * \u03b3L ) / 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. \u201cBI-LEVEL IMAGE THRESHOLDING - A Fast Method\u201d, 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\u209b = 1\r\n    I\u2091 = length(histogram)\r\n    I\u2098 = round(Int, (I\u209b + I\u2091) / 2)\r\n    W\u2097 = 0\r\n    W\u1d63 = 0\r\n    for i = 1:I\u2098\r\n        W\u2097 += histogram[i]\r\n    end\r\n    for i = I\u2098:I\u2091\r\n        W\u1d63 += histogram[i]\r\n    end\r\n    while I\u209b < I\u2091\r\n        if W\u2097 < W\u1d63\r\n            W\u1d63 -= histogram[I\u2091]\r\n            I\u2091 -= 1\r\n            if (I\u209b + I\u2091) / 2 < I\u2098\r\n                W\u2097 -= histogram[I\u2098]\r\n                W\u1d63 += histogram[I\u2098]\r\n                I\u2098 -= 1\r\n            end\r\n        else\r\n            W\u2097 -= histogram[I\u209b]\r\n            I\u209b += 1\r\n            if (I\u209b + I\u2091) / 2 > I\u2098\r\n                W\u2097 += histogram[I\u2098 + 1]\r\n                W\u1d63 -= histogram[I\u2098 + 1]\r\n                I\u2098 += 1\r\n            end\r\n        end\r\n    end\r\n    if I\u2098 == 1 || I\u2098 == 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\u2098]\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\u2202poly(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\u2081 + c\u2082x + c\u2083x\u00b2 + c\u2084x\u00b3 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] = \u2202poly(x1, c) - s1\n        F[4] = \u2202poly(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 \u2265 0)\n@variable(m, x12 \u2265 0)\n@variable(m, x21  \u2265 0)\n@variable(m, x22 \u2265 0)\n@variable(m, x31 \u2265 0)\n@variable(m, x32 \u2265 0)\n@objective(m, Min, 80x11 + 100x21 + 102x31 + 251x12 + 108x22 + 68x32)\n@constraint(m, x11 + x12 \u2264 1000)\n@constraint(m, x21 + x22 \u2264 1500)\n@constraint(m, x31 + x32 \u2264 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    \u03b8 = zeros(d); \u03b8\u2080 = 0;\n    for t in 1:T\n        \u03f5 = 0\n        for i in 1:n\n            x = set[i][1]; y = set[i][2]\n            if (y*(\u03b8' * x + \u03b8\u2080) <= 0)\n                \u03b8  = \u03b8 + y * x\n                \u03b8\u2080 = \u03b8\u2080 + y\n                \u03f5 += 1\n            end\n        end\n        if (\u03f5 == 0)\n            return (\u03b8,\u03b8\u2080,\u03f5,t)\n        end\n    end\n    return (\u03b8,\u03b8\u2080,\u03f5,T)\nend\n\nT = 5000\nset = [([7,8],-1),([4,2],-1),([2,7],1),([3,-2],1),([-3,-2],1)]\n(\u03b8,\u03b8\u2080,\u03f5,t) = perceptron(set,T)\n\nusing Plots, LinearAlgebra\n\n\u03b8\u2099 = \u03b8/norm(\u03b8)\n\u03b8\u2080\u2099 = \u03b8\u2080/norm(\u03b8) *  \u03b8\u2099\nx\u207a = vcat([([tuple[1][1] tuple[1][2]])  for tuple in set if tuple[2] == 1]...)\nx\u207b = vcat([([tuple[1][1] tuple[1][2]])  for tuple in set if tuple[2] == -1]...)\n\nscatter(x\u207a[:,1],x\u207a[:,2], label=\"+1\")\nscatter!(x\u207b[:,1],x\u207b[:,2], label=\"-1\")\n#plot!([0,\u03b8[1]],[0,\u03b8[2]])\nplot!([-\u03b8\u2080\u2099[1],\u03b8\u2099[1]-\u03b8\u2080\u2099[1]],[-\u03b8\u2080\u2099[2],\u03b8\u2099[2]-\u03b8\u2080\u2099[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    \u03b8  = zeros(d)\n    \u03f5t = 0\n    for t in 1:T\n        \u03f5 = 0\n        for i in 1:n\n            x = set[i][1]; y = set[i][2]\n            error = false\n            \u03b8pre = \u03b8\n            if (y*(\u03b8' * x) <= 0)\n                \u03b8  = \u03b8 + y * x\n                \u03f5 += 1; error = true; \u03f5t += 1\n            end\n            println(\"\u03b8pre: $\u03b8pre x: $x y: $y error: $error \u03b8post=$\u03b8\")\n        end\n        if (\u03f5 == 0)\n            return (\u03b8,\u03f5,t, \u03f5t)\n        end\n    end\n    return (\u03b8,\u03f5,T,\u03f5t)\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, \u03b8 = zeros(length(set[1])), \u03b8\u2080 = 0)\n    println(\"*** New Classifier Lookup ***\")\n    println(\"Data: $set\")\n    println(\"Parameters: T = $T, \u03b8=$\u03b8, \u03b8\u2080=$\u03b8\u2080\")\n    n = length(set); d = length(set[1][1])\n    for t in 1:T\n        \u03f5 = 0\n        for i in 1:n\n            x = set[i][1]; y = set[i][2]\n            error = false\n            \u03b8pre = \u03b8\n            \u03b8\u2080pre = \u03b8\u2080\n            if (y*(\u03b8' * x + \u03b8\u2080) <= 0)\n                \u03b8  = \u03b8 + y * x\n                \u03b8\u2080 = \u03b8\u2080 + y\n                \u03f5 += 1\n                error = true\n            end\n            println(\"\u03b8pre: $\u03b8pre \u03b8\u2080pre: $\u03b8\u2080pre x: $x y: $y error: $error \u03b8post=$\u03b8 \u03b8\u2080post=$\u03b8\u2080\")\n        end\n        if (\u03f5 == 0)\n            return (\u03b8,\u03b8\u2080,\u03f5,T)\n        end\n    end\n    return (\u03b8,\u03b8\u2080,\u03f5,T)\nend\n\nset = [([-4,2],1),([-2,1],1),([-1,-1],-1),([2,2],-1),([1,-2],-1)]\n(\u03b8,\u03b8\u2080,\u03f5,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\u03bb = 0.5\nx = [1,0]\ny = 1\n\n\u03b8 =\nloss(\u03b8,y=1,x=[1,0],\u03bb=0.5) = max(0,1-y*(\u03b8' * x)) + \u03bb/2 * norm(\u03b8)^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(\u03c0)\ncos(2*\u03c0)\ncos(3*\u03c0)\ncos(4*\u03c0)\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*\u03c0)\n      push!(out,(x,labels[i]))\n    end\n    return out\nend\n\nset = setFactory(20)\nusing Random\nshuffle!(set)\n(\u03b8,\u03f5,t,\u03f5t) = perceptronOrigin(set,400)\n\nrandLabel = rand(20)\nset = setFactory(20,randLabel)\n(\u03b8,\u03f5,t,\u03f5t) = perceptronOrigin(set,400)\nshuffle!(set)\n(\u03b8,\u03f5,t,\u03f5t) = perceptronOrigin(set,400)\n\nrandLabel = rand(3)\nset = setFactory(3,randLabel)\n(\u03b8,\u03f5,t,\u03f5t) = perceptronOrigin(set,400)\n\nset = setFactory(3)\n(\u03b8,\u03f5,t,\u03f5t) = perceptronOrigin(set,400)\n\nset=setFactory(2)\n(\u03b8,\u03f5,t,\u03f5t) = 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, \u03bc\u1d6a::Number, \u03bc\u1d67::Number)\n    # Calculate covariance\n    \u03c3\u1d6a\u1d67 = \u2205 = zero(promote_type(typeof(\u03bc\u1d6a), typeof(\u03bc\u1d67), Int))\n    n = 0\n    @turbo for i \u2208 indices((x,y))\n            \u03b4\u1d6a = x[i] - \u03bc\u1d6a\n            \u03b4\u1d67 = y[i] - \u03bc\u1d67\n            \u03b4\u00b2 = \u03b4\u1d6a * \u03b4\u1d67\n            notnan = \u03b4\u00b2==\u03b4\u00b2\n            n += notnan\n            \u03c3\u1d6a\u1d67 += ifelse(notnan, \u03b4\u00b2, \u2205)\n    end\n    \u03c3\u1d6a\u1d67 = \u03c3\u1d6a\u1d67 / (n-corrected)\n    return \u03c3\u1d6a\u1d67\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\u1d6a = length(x)\n    n\u1d67 = length(y)\n    @assert n\u1d6a == n\u1d67\n\n    \u03bc\u1d6a = _nanmean(x,:)\n    \u03bc\u1d67 = _nanmean(y,:)\n    \u03c3\u1d6a\u1d67 = _nancov(x, y, corrected, \u03bc\u1d6a, \u03bc\u1d67)\n    return \u03c3\u1d6a\u1d67\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\u2092 = Base.promote_op(/, eltype(X), Int)\n    n = size(X, dims)\n    m = size(X, mod(dims,2)+1)\n    \u03a3 = similar(X, T\u2092, (m, m))\n    # Only two dimensions are possible, so handle each manually\n    if dims == 1\n        # Precalculate means for each column\n        \u03bc = 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                \u03c3\u1d62\u2c7c = _nancov(view(X,:,i), view(X,:,j), corrected, \u03bc[i], \u03bc[j])\n                \u03a3[i,j] = \u03a3[j,i] = \u03c3\u1d62\u2c7c\n            end\n        end\n    elseif dims == 2\n        # Precalculate means for each row\n        \u03bc = 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                \u03c3\u1d62\u2c7c = _nancov(view(X,i,:), view(X,j,:), corrected, \u03bc[i], \u03bc[j])\n                \u03a3[i,j] = \u03a3[j,i] = \u03c3\u1d62\u2c7c\n            end\n        end\n    else\n        throw(\"Dimension not in range\")\n    end\n    return \u03a3\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\u1d6a = length(x)\n    n\u1d67 = length(y)\n    @assert n\u1d6a == n\u1d67\n\n    \u03bc\u1d6a = nanmean(x)\n    \u03bc\u1d67 = nanmean(y)\n    \u03c3\u1d6a = nanstd(x, mean=\u03bc\u1d6a, corrected=corrected)\n    \u03c3\u1d67 = nanstd(y, mean=\u03bc\u1d67, corrected=corrected)\n    \u03c3\u1d6a\u1d67 = _nancov(x, y, corrected, \u03bc\u1d6a, \u03bc\u1d67)\n    \u03c1\u1d6a\u1d67 = \u03c3\u1d6a\u1d67 / (\u03c3\u1d6a * \u03c3\u1d67)\n\n    return \u03c1\u1d6a\u1d67\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\u2092 = Base.promote_op(/, eltype(X), Int)\n    n = size(X, dims)\n    m = size(X, mod(dims,2)+1)\n    \u03a1 = similar(X, T\u2092, (m, m))\n    # Diagonal must be unity\n    @inbounds for i = 1:m\n        \u03a1[i,i] = one(T\u2092)\n    end\n    # Only two dimensions are possible, so handle each manually\n    if dims == 1\n        # Precalculate means and standard deviations\n        \u03bc = ntuple(m) do d\n            nanmean(view(X,:,d))\n        end\n        \u03c3 = ntuple(m) do d\n            nanstd(view(X,:,d), mean=\u03bc[d], corrected=corrected)\n        end\n        # Fill off-diagonals symmetrically\n        @inbounds for i = 1:m\n            for j = 1:i\n                \u03c3\u1d62\u2c7c = _nancov(view(X,:,i), view(X,:,j), corrected, \u03bc[i], \u03bc[j])\n                \u03a1[i,j] = \u03a1[j,i] = \u03c3\u1d62\u2c7c / (\u03c3[i] * \u03c3[j])\n            end\n        end\n    elseif dims == 2\n        # Precalculate means and standard deviations\n        \u03bc = ntuple(m) do d\n            nanmean(view(X,d,:))\n        end\n        \u03c3 = ntuple(m) do d\n            nanstd(view(X,d,:), mean=\u03bc[d], corrected=corrected)\n        end\n        @inbounds for i = 1:m\n            for j = 1:i-1\n                \u03c3\u1d62\u2c7c = _nancov(view(X,i,:), view(X,j,:), corrected, \u03bc[i], \u03bc[j])\n                \u03a1[i,j] = \u03a1[j,i] = \u03c3\u1d62\u2c7c / (\u03c3[i] * \u03c3[j])\n            end\n        end\n    else\n        throw(\"Dimension not in range\")\n    end\n    return \u03a1\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 \u2a7e 0, +\u221e 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 \u21a6 0 if all(0 \u2a7d x), +\u221e 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": "#   Unit examples of the FourierAnalysis Package for julia language\n#   v 0.0.1 - last update 24th of September 2019\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 example show hot to create and plot tapering window for FFT.\n\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n#                                                                             #\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n\n\n############ plot tapering windows #############\nusing FourierAnalysis, Plots\n\n# using the standard plot function\ntapers=[TaperKind(i) for i=1:8]\nX=zeros(t, 8)\nfor i=1:8 X[:, i] = taper(tapers[i], t).y end\nlabels=[string(tapers[i]) for i=1:8]\nplot(X; labels=labels)\n\n# discrete prolate spheroid sequences\nH=taper(slepian, t, \u03b1=4, n=7)\n# This is a special plot function declared in the `plots.jl unit`\nplot(H, title=\"Slepian multi-tapering (dpss)\")\n\n\n################################################\n", "meta": {"hexsha": "c115f172e164c48e9ca3d409253f70a5d054b405", "size": 1077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_taper.jl", "max_stars_repo_name": "laborg/FourierAnalysis.jl", "max_stars_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_stars_repo_licenses": ["MIT"], "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_taper.jl", "max_issues_repo_name": "laborg/FourierAnalysis.jl", "max_issues_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_issues_repo_licenses": ["MIT"], "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_taper.jl", "max_forks_repo_name": "laborg/FourierAnalysis.jl", "max_forks_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_forks_repo_licenses": ["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.6363636364, "max_line_length": 79, "alphanum_fraction": 0.5051067781, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7995057152855304}}
{"text": "\"\"\"\n    NeuralNetworkKernel()\n\nNeural network kernel function.\n\n```math\n    \u03ba(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 (\u03ba::NeuralNetworkKernel)(x, y)\n    return asin(dot(x, y) / sqrt((1 + sum(abs2, x)) * (1 + sum(abs2, y))))\nend\n\nBase.show(io::IO, \u03ba::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": "@add_problem sdp_and_exp function sdp_and_exp_log_det_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(2, 2)\n    p = maximize(logdet(x), [x[1, 1] == 1, x[2, 2] == 1])\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0 atol=10atol rtol=rtol\n        @test evaluate(logdet(x)) \u2248 0 atol=10atol rtol=rtol\n    end\nend\n", "meta": {"hexsha": "ef11c2a8f6a801b0efac9a79c7086ca69c79e069", "size": 427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem_depot/problems/sdp_and_exp.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": "src/problem_depot/problems/sdp_and_exp.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": "src/problem_depot/problems/sdp_and_exp.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": 32.8461538462, "max_line_length": 127, "alphanum_fraction": 0.6088992974, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.7994902329617793}}
{"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": "\"\"\"\n    Return an offset vector `p`, where p[i] is the prior \n    probability of any hypothesis such that sum_{j=1}^m \u03b3j = i,\n    according to Womack (2015)'s proposal\n\"\"\"\nfunction ph0(m, \u03b6)\n    p = OffsetArray([zeros(m); 1.0], 0:m)\n    for l = m-1:-1:0\n        for j = 1:m-l\n            p[l] += \u03b6 * p[l + j] * binomial(l + j, l)\n        end\n    end\n    p /= sum(p)\n    for l = 0:m-1\n        p[l] /= binomial(m, l)\n    end\n    return p    \nend\n\nfunction \u03b3code(\u03b3)\n    code = 1\n    @inbounds for j = 2:length(\u03b3)\n        code += \u03b3[j] * 2^(j - 2)\n    end\n    code\nend\n\nfunction \u03b3vector(J, code)\n    \u03b3 = zeros(Int, J)\n    code -= 1\n    for j = J:-1:2\n        if (code \u00f7 2^(j-2)) > 0\n            code -= 2^(j-2)\n            \u03b3[j] = 1\n        end\n    end\n    return \u03b3\nend\n\n\n\"Return the vector \u03b3 associated with code `code`, given `J`\"\n\u03b3vec(J, code) = \u03b3vector(J, code)[2:J]\n\n\"Return the vector \u03b3 associated with code `code`, given `J`, as a string\"\n\u03b3str(J, code) = string(\u03b3vec(J, code)...)\n", "meta": {"hexsha": "dbf9b6e4bfc6197e73ddbe0cd623b69231f414d4", "size": 981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/01-utils.jl", "max_stars_repo_name": "igutierrezm/MANOVABNPTest.jl", "max_stars_repo_head_hexsha": "ba28118a9a46c94ae4906bdd6bedad7d383d8789", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/01-utils.jl", "max_issues_repo_name": "igutierrezm/MANOVABNPTest.jl", "max_issues_repo_head_hexsha": "ba28118a9a46c94ae4906bdd6bedad7d383d8789", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/01-utils.jl", "max_forks_repo_name": "igutierrezm/MANOVABNPTest.jl", "max_forks_repo_head_hexsha": "ba28118a9a46c94ae4906bdd6bedad7d383d8789", "max_forks_repo_licenses": ["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.3260869565, "max_line_length": 73, "alphanum_fraction": 0.5117227319, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7994560199530842}}
{"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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    infection = \u03b2*c*I/N*S\n    recovery = \u03b3*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\u03b4t = 1.0\ntspan = (0.0,tmax)\nobstimes = 1.0:\u03b4t:tmax;\nu0 = [990.0,10.0,0.0,0.0]; # S,I.R,C\np = [0.05,10.0,0.25]; # \u03b2,c,\u03b3\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\nsol_ode_cumulative = solve(prob_ode,Tsit5(),saveat=\u03b4t);\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=\u03b4t,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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    infection = \u03b2*c*I/N*S\n    recovery = \u03b3*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.\u03bc)\")\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.\u03bc)\")\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.\u03bc, 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9f5f8730-0188-11eb-209f-e771579d35ce\nmd\"# Sequential Quadratic Programming\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4a460a20-018e-11eb-3da1-4d37893ead18\nx\u2080 = [2, 0]\n\n# \u2554\u2550\u2561 8df4e190-018b-11eb-2eae-1d8f6c4e6248\nlet x = x\u2080\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b9b7e250-018b-11eb-1eca-51dc8250a3eb\nsol\u2081 = let x = x\u2080\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ea6595a0-018b-11eb-07dc-f394137f59f4\n\u03b1\u2081, d\u2081 = let x = x\u2080\n\td = sol\u2081[1:2]\n\t\u03b1 = min(1.0, [(reshape(A[j,:], 1, 2) * d)[1,1] \u2264 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\u03b1, d\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ee702bf0-018c-11eb-1ec9-6b481c119add\nx\u2081 = x\u2080 + \u03b1\u2081 .* d\u2081\n\n# \u2554\u2550\u2561 2cb44400-018d-11eb-0138-c78f6a18b8f8\nsol\u2082 = let x = x\u2081\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 84712210-018f-11eb-0bef-53cdfb93e0e2\nx\u2082 = x\u2081\n\n# \u2554\u2550\u2561 96ecfeb2-018e-11eb-2dda-994575ee6011\nsol\u2083 = let x = x\u2082\n\tg = Q*x - c\n\tsol = Q \\ (-g)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c71e2f00-018e-11eb-1c30-a54d6d4d04ff\n\u03b1\u2083, d\u2083 = let x = x\u2082\n\td = sol\u2083[1:2]\n\t\u03b1 = min(1.0, [(reshape(A[j,:], 1, 2) * d)[1,1] \u2264 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\u03b1, d\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 596ba4f0-018f-11eb-321e-03ec8a6d18db\nx\u2083 = x\u2082 + \u03b1\u2083 .* d\u2083\n\n# \u2554\u2550\u2561 91ada700-018f-11eb-37d0-757a263bae99\nsol\u2084 = let x=x\u2083\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ba0f5450-018f-11eb-2188-4327aa9c02cc\n\u03b1\u2084, d\u2084 = let x = x\u2083\n\td = sol\u2084[1:2]\n\t\u03b1 = min(1.0, [(reshape(A[j,:], 1, 2) * d)[1,1] \u2264 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\u03b1, d\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e59a7c30-018f-11eb-2b94-7b8dff2a6383\nx\u2084 = x\u2083 + \u03b1\u2084 .* d\u2084\n\n# \u2554\u2550\u2561 f5f705d0-018f-11eb-2462-e7e2265b700c\nsol\u2085 = let x = x\u2084\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2080)`.\"\"\"\n\n# \u2554\u2550\u2561 f3007460-018a-11eb-3fa2-8753aceaf89a\nsol = GeneralQP.solve(Q, -c, A, b, Float64[2,0])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ffed97e2-dc07-48bb-870a-737a115e69dc\n# \u255f\u25009f5f8730-0188-11eb-209f-e771579d35ce\n# \u255f\u2500c30dbe90-0188-11eb-0c2b-ed5e93a86b0b\n# \u255f\u2500e0be4cbe-0188-11eb-1991-5b001cf2434a\n# \u2560\u255056fd4bc0-0189-11eb-04c2-0d000ded6e97\n# \u255f\u250080edfd80-0189-11eb-1687-01a14b31ad39\n# \u255f\u25008f340330-0189-11eb-27c8-7ba7c0954ac7\n# \u255f\u2500db088c90-0189-11eb-338d-81af9469d556\n# \u2560\u25506bdfb630-018a-11eb-1010-b3c332121581\n# \u255f\u250088c16630-018b-11eb-3ea1-a555d69b2e26\n# \u2560\u25504a460a20-018e-11eb-3da1-4d37893ead18\n# \u2560\u25508df4e190-018b-11eb-2eae-1d8f6c4e6248\n# \u255f\u2500a8042d20-018b-11eb-0f74-3b70e587f20d\n# \u2560\u2550b9b7e250-018b-11eb-1eca-51dc8250a3eb\n# \u255f\u2500e14bb850-018b-11eb-0bb0-15ebdb2f7fcf\n# \u2560\u2550ea6595a0-018b-11eb-07dc-f394137f59f4\n# \u255f\u25000d2eeb40-018c-11eb-0fdc-1b6668c5941f\n# \u2560\u2550ee702bf0-018c-11eb-1ec9-6b481c119add\n# \u2560\u25502cb44400-018d-11eb-0138-c78f6a18b8f8\n# \u255f\u2500456d9c82-018d-11eb-0e81-bf7346539a32\n# \u2560\u255084712210-018f-11eb-0bef-53cdfb93e0e2\n# \u2560\u255096ecfeb2-018e-11eb-2dda-994575ee6011\n# \u255f\u25002ddf0860-018d-11eb-2884-7dacdda18597\n# \u2560\u2550c71e2f00-018e-11eb-1c30-a54d6d4d04ff\n# \u255f\u2500e470e5c0-018e-11eb-229b-e521909f84e3\n# \u2560\u2550596ba4f0-018f-11eb-321e-03ec8a6d18db\n# \u2560\u255091ada700-018f-11eb-37d0-757a263bae99\n# \u255f\u2500abfbf760-018f-11eb-18dc-bd573cc8be06\n# \u2560\u2550ba0f5450-018f-11eb-2188-4327aa9c02cc\n# \u255f\u2500d8c62ef0-018f-11eb-21ce-ebe037f9d91d\n# \u2560\u2550e59a7c30-018f-11eb-2b94-7b8dff2a6383\n# \u2560\u2550f5f705d0-018f-11eb-2462-e7e2265b700c\n# \u255f\u25001254d540-0190-11eb-3066-b5a853eef0c0\n# \u2560\u255002787820-0190-11eb-24ed-c5296c91df6b\n# \u255f\u2500aa606210-018a-11eb-29bd-5d4f9ae0966e\n# \u2560\u2550f3007460-018a-11eb-3fa2-8753aceaf89a\n# \u255f\u250024c67580-018b-11eb-3eb7-47a2e2ae5251\n# \u2560\u2550a98c8890-0190-11eb-25a4-bfd18c42b749\n# \u2560\u2550acfea4e0-0190-11eb-07a9-a3f38d97ff80\n# \u2560\u2550a4824010-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\u22121 + Fn\u22122, 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, \ud835\udc56_real = findmax( real.(x) )\n    val_unused, \ud835\udc56_imag = findmax( imag.(x) )\n\n    a::Complex{T} = real(x[\ud835\udc56_real]) + im*imag(\ud835\udc56_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(\u03bb, \u03bc)\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    \u03bb::Float64\n    \u03bc::Float64\nend\n\n\nfunction (st::SourceTerm)(x::Float64,p::Float64)\n    return st.\u03bb*(p-x)*exp(-st.\u03bc*(p-x)^2)\nend\n\n# function (st::SourceTerm)(x::Float64,p::Float64)\n#     return st.\u03bb*tanh(st.\u03bc*(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 \u03b8 = d_y/d = fy/F\n                # F /| dy fy    -> fy = F*d_y/d\n                #  / |          cos \u03b8 = 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": "println(\"Test metrics\")\n\nimport Distributions.SpecialFunctions.logabsbeta\nimport Distributions.StatsBase.harmmean\nlbeta(a, b) = logabsbeta(a, b)[1]\n\n@testset \"metrics\" begin\n  @testset \"dic\" begin\n    x = randn(10000)\n    ll = normlogpdf.(x)\n    @test isfinite(dic(ll))\n  end\n\n  @testset \"logharmmean\" begin\n    Random.seed!(0)\n    x = randn(100)\n    @test log(harmmean(exp.(x))) \u2248 MCMC.logharmmeanexp(x) atol=1e-6\n  end\n\n  @testset \"log_bayes_factor\" begin\n    Random.seed!(0)\n    n = 100\n    y = rand(Bernoulli(.7), n)\n    sumy = sum(y)\n\n    m0 = Beta(70, 100)\n    m1 = Beta(100, 70)\n\n    compute_logc_true(m) = lbeta(m.\u03b1 + sumy, m.\u03b2 + n - sumy) - lbeta(m.\u03b1, m.\u03b2)\n    c0_true = compute_logc_true(m0)\n    c1_true = compute_logc_true(m1)\n\n    true_log_bf = c1_true - c0_true\n\n    post_samps_m0 = rand(Beta(m0.\u03b1 + sumy, m0.\u03b2 + n - sumy), 100_000)\n    post_samps_m1 = rand(Beta(m1.\u03b1 + sumy, m1.\u03b2 + n - sumy), 100_000)\n    ll0 = map(p -> sum(logpdf.(Bernoulli(p), y)), post_samps_m0)\n    ll1 = map(p -> sum(logpdf.(Bernoulli(p), y)), post_samps_m1)\n\n    approx_log_bf = log_bayes_factor(ll0, ll1)\n\n    @test c0_true \u2248 MCMC.logharmmeanexp(ll0)  atol=0.2\n    @test c1_true \u2248 MCMC.logharmmeanexp(ll1)  atol=0.2\n\n    @test true_log_bf \u2248 approx_log_bf atol=0.2\n  end\n\n  @testset \"logmeanexp\" begin\n    Random.seed!(0)\n    x = randn(10000)\n    @test logmeanexp(x) \u2248 log(mean(exp.(x)))\n  end\n\n  @testset \"hellinger\" begin\n    Random.seed!(0)\n    d1 = Normal(0, 1)\n    d2 = Normal(1, 1)\n    @test hellinger(d1, d2, Int(1e6)) \u2248 hellinger(d2, d1, Int(1e6))  atol=0.02\n    @test hellinger(d1, d2, Int(1e6)) \u2248 0.34 atol=0.01\n  end\nend\n", "meta": {"hexsha": "8ace53a3b37522a7e78c99519d2a3e360a2b7e0c", "size": 1620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/metrics.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": "test/metrics.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": "test/metrics.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": 26.1290322581, "max_line_length": 78, "alphanum_fraction": 0.6333333333, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067260443809, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7992153157398773}}
{"text": "struct PolynomialFeature\n    _degree::Int64\nend\n\nfunction transform(feature::PolynomialFeature, x::AbstractArray{Float64,1})\n    # return the design matrix [phi(x_1), phi(x_2), ,,, phi(x_N)]^T of size (n_samples, n_features)\n    n_samples = size(x)[1]\n    degree = feature._degree\n    Phi = zeros(Float64, n_samples, degree + 1)\n    for i = 1:n_samples\n        Phi[i, :] = [x[i]^j for j = 0:degree]\n    end\n\n    return Phi\nend\n", "meta": {"hexsha": "5df64fe4b6e0edcc25c2a634992464168498da0a", "size": 427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/feature/polynomial_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/polynomial_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/polynomial_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": 26.6875, "max_line_length": 99, "alphanum_fraction": 0.6533957845, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7992153088928668}}
{"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^\u03b1 noise\nfunction one_on_f_noise(T, \u03b1, f)\n    # 2\u03b1 needed to convert powers to amplitudes here\n    \u03f5 = sqrt(eps(real(T)))\n    A = randn(T)\n    return convert(T, A / (\u03f5 + norm(f))^2\u03b1)\nend\n\nN = 200\n\u03b1 = 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, \u03b1, 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    Sigmoid(x)\n\nSigmoid activation function.\n\n    Usage:\n```julia-repl\nSigmoid(x)\n```\nArguments:\n- `x` : Input value.\n\"\"\"\nfunction Sigmoid(x::Float64)\n    x\u2081 = 1.0 / (1.0 + exp(-x))\n    return x\u2081\nend", "meta": {"hexsha": "3e5686533efd549d74335b2e8d9a5015d19f4043", "size": 203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ActivationFunctions/Sigmoid.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/ActivationFunctions/Sigmoid.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/ActivationFunctions/Sigmoid.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": 12.6875, "max_line_length": 30, "alphanum_fraction": 0.5862068966, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7992153052716913}}
{"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# \u2554\u2550\u2561 9947a66a-7fe5-11eb-0955-87881a67fbea\nbegin\n\tusing PlutoUI\n\tusing Plots\n\t\n\t# plotly()\nend\n\n# \u2554\u2550\u2561 9872b1a8-7fe7-11eb-0b3b-cb6181515182\nusing SymPy\n\n# \u2554\u2550\u2561 84fc02d6-7fef-11eb-2e21-cb577c3974f0\n# Pkg.add(\"ForwardDiff)\nusing ForwardDiff\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7a9389a2-7fe5-11eb-06b8-c52b073c876a\nfunction babylonian(x; n = 10)\n    t = (1. + x) / 2.\n    for i \u2208 2:n\n        t = (t + x/t) / 2.\n    end\n    t\nend\n\n# \u2554\u2550\u2561 9091553e-7fe5-11eb-2131-9b1b1097c932\nbegin\n\t\u03b1 = \u03c0\n\tbabylonian(\u03b1), \u221a\u03b1\nend\n\n# \u2554\u2550\u2561 b9ccd308-7fe5-11eb-0b0c-efa652660cd5\nwith_terminal() do\n\tfor \u03b1 \u2208 2:3\n   \t\tprintln(babylonian(\u03b1), \" \", \u221a\u03b1)\n\tend\nend\n\n# \u2554\u2550\u2561 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 \u2208 1:5], \n    \tix, \n    \tlabel=[\"Iteration $jx\" for _ \u2208 1:1, jx \u2208 1:5])\n\n\tplot!(sqrt, \n    \tix, \n    \tc=\"darkslateblue\", \n    \tlabel=\"sqrt\", \n    \ttitle = \"Those Babylonian really knew about \u221a\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6e487e0e-7fe6-11eb-23a2-35a3a2ed7015\nx\u2081 = 49; babylonian(D((x\u2081, 1))), (\u221ax\u2081, .5 / \u221ax\u2081)\n\n# \u2554\u2550\u2561 a362fc86-7fe6-11eb-1b7a-03cd0549e790\nx\u2082 = \u03c0; babylonian(D((x\u2082, 1))), (\u221ax\u2082, .5 / \u221ax\u2082)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a312dfda-7fe6-11eb-0bae-37587f221888\nwith_terminal() do\n\t@code_native babylonian(D((2, 1)))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2208 1:5\n    \tprintln(simplify(babylonian(x, n=k)))\n\tend\nend\n\n# \u2554\u2550\u2561 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 \u2208 1:5\n    \tprintln(simplify(diff(simplify(babylonian(x, n=k)), x)))\n\tend\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d05af69e-7feb-11eb-3874-d1b05fb6434a\nfunction dbabylonian(x; n = 10)\n    t = (1. + x) / 2.\n    dt = 1. / 2.\n    \n    for i \u2208 2:n \n        t = (t + x/t) / 2.\n        dt = (dt + (t - x * dt) / t^2) / 2.\n    end\n    dt\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d01a58be-7feb-11eb-1f29-6d23db7914da\nx= \u03c0; dbabylonian(x), .5 / \u221ax\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d0ca45ac-7fec-11eb-202b-87ae22b66616\nbabylonian(D((x, 1)))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1818fb9c-7fed-11eb-0bd3-21411f08fcdf\nBase.show(io::IO, x::D) = print(io, x.f[1], \" + \", x.f[2], \" \u03f5\")\n\n# \u2554\u2550\u2561 14125e9c-7fef-11eb-3dc4-a75f84383d5d\nD((1, 0))\n\n# \u2554\u2550\u2561 13e452cc-7fef-11eb-2e1d-a5e3b9936a4c\nD((0, 2))^2 # should be zero!\n\n# \u2554\u2550\u2561 13ab59ea-7fef-11eb-2078-6d8ee11d1c90\nD((2, 1))^2\n\n# \u2554\u2550\u2561 2886e6c4-7fef-11eb-0fff-9b3033e4f943\nbegin\n\t\u03f5 = D((0, 1))\n\twith_terminal() do\n\t\t@code_native(\u03f5^2)\n\tend\nend\n\n# \u2554\u2550\u2561 3f1f4bba-7fef-11eb-2f39-cf906aec10ae\n\u03f5 * \u03f5\n\n# \u2554\u2550\u2561 3f037186-7fef-11eb-200f-3579d0ab8e1f\n\u03f5^2\n\n# \u2554\u2550\u2561 3eea0d36-7fef-11eb-3ede-c7d54243194c\n(1 + \u03f5)^5 # note it just works (we did not train powers)\n\n# \u2554\u2550\u2561 3ece19f8-7fef-11eb-3b91-ff25fd3ca8f4\nmd\"\"\"\n### Generalization to arbitrary roots\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5c9fbbc6-7fef-11eb-32ad-b986ca56aa9b\nnth_root(2, 3), \u221b2  # copied from https://www.alt-codes.net/root-symbols\n\n# \u2554\u2550\u2561 5c84a84c-7fef-11eb-3117-01f1842890f5\nnth_root(2 + \u03f5, 3)\n\n# \u2554\u2550\u2561 5c665cd4-7fef-11eb-2c89-e153a973b30e\nnth_root(7, 12), 7^(1/12)\n\n# \u2554\u2550\u2561 5c4f64ac-7fef-11eb-1864-13f293e85fc4\nlet x = 2.0\n\tnth_root( x + \u03f5), \u221bx, 1/x*(2/3)/3\nend\n\n# \u2554\u2550\u2561 5c33d6ce-7fef-11eb-12c1-29396395358d\nmd\"\"\"\n### Forward Diff\n\nNow that you understand it, you can use the official package.\n\"\"\"\n\n# \u2554\u2550\u2561 84ddd280-7fef-11eb-29cb-3fc8c8547134\nForwardDiff.derivative(sqrt, 2)\n\n# \u2554\u2550\u2561 916346b8-7fef-11eb-0d53-29bd11c34510\nForwardDiff.derivative(babylonian, 2)\n\n# \u2554\u2550\u2561 99672fe6-7fef-11eb-305e-d98ce4bc8dc1\nwith_terminal() do\n\tprintln(@which ForwardDiff.derivative(\u221a, 2))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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] - \u221aBigFloat(2))), 3)\n\tprintln(round.(Float64.(log10.([babylonian(BigFloat(2), n=k) - \u221aBigFloat(2.) for k=1:10])), sigdigits=6))\nend\n\n# \u2554\u2550\u2561 d59d0508-7fef-11eb-20a3-3f108b859670\nstruct D1{T} <: Number # D is a <function, derivative> pair\n    f::Tuple{T, T}\nend\n\n# \u2554\u2550\u2561 d57e75ac-7fef-11eb-1cc7-db506a7e4e2f\nbegin\n\tz = D((2., 1.))\n\tz\u2081 = D1((BigFloat(2.), BigFloat(1.)))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3e2da118-7ff0-11eb-36ca-e32af03b2a0c\nA = randn(3, 3)\n\n# \u2554\u2550\u2561 3e0a484e-7ff0-11eb-17be-e9e7aa66fb2c\nx\u2083= randn(3)\n\n# \u2554\u2550\u2561 3dd5c57e-7ff0-11eb-3330-cf7d02b5c632\nForwardDiff.gradient(x -> x'A*x, x\u2083)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500e529f550-7fe3-11eb-06f8-6beaa1506e66\n# \u2560\u25509947a66a-7fe5-11eb-0955-87881a67fbea\n# \u255f\u250028aa4e9c-7fe4-11eb-3d87-c5a10540c2c1\n# \u2560\u25507a9389a2-7fe5-11eb-06b8-c52b073c876a\n# \u2560\u25509091553e-7fe5-11eb-2131-9b1b1097c932\n# \u2560\u2550b9ccd308-7fe5-11eb-0b0c-efa652660cd5\n# \u2560\u2550ff570916-7fe5-11eb-35ab-e915308e7bfc\n# \u255f\u25001ecd40bc-7fe6-11eb-0a2f-cb9964fc5dbf\n# \u2560\u25504ac7200c-7fe6-11eb-259a-8d881d2f7e3e\n# \u255f\u250054f29be2-7fe6-11eb-38c5-d163b159730a\n# \u2560\u25506e7efe02-7fe6-11eb-19a7-8b72c0836c8b\n# \u255f\u25006e64c064-7fe6-11eb-1e6d-3dfeebace21b\n# \u2560\u25506e487e0e-7fe6-11eb-23a2-35a3a2ed7015\n# \u2560\u2550a362fc86-7fe6-11eb-1b7a-03cd0549e790\n# \u255f\u2500a348cb0e-7fe6-11eb-1c9d-4b4278a367aa\n# \u2560\u2550a32df540-7fe6-11eb-073f-1b34489aa4a0\n# \u2560\u2550a312dfda-7fe6-11eb-0bae-37587f221888\n# \u255f\u250037574936-7fe7-11eb-132a-2df44bf8d6bb\n# \u2560\u25509872b1a8-7fe7-11eb-0b3b-cb6181515182\n# \u2560\u255098544e52-7fe7-11eb-1094-9382f7126ce4\n# \u2560\u255098399af8-7fe7-11eb-1276-13c05fa36ed9\n# \u255f\u2500981ea264-7fe7-11eb-06ef-97ee66d5619b\n# \u2560\u2550d05af69e-7feb-11eb-3874-d1b05fb6434a\n# \u255f\u2500d0310bf4-7feb-11eb-2d05-c9531128eb4a\n# \u2560\u2550d01a58be-7feb-11eb-1f29-6d23db7914da\n# \u255f\u2500cffee818-7feb-11eb-079b-a7dbfdd8cdd6\n# \u2560\u2550d0ca45ac-7fec-11eb-202b-87ae22b66616\n# \u255f\u2500d0addd04-7fec-11eb-0213-53ef5d729159\n# \u255f\u2500d092a21e-7fec-11eb-0cc1-d1515675f521\n# \u2560\u25501818fb9c-7fed-11eb-0bd3-21411f08fcdf\n# \u2560\u255014125e9c-7fef-11eb-3dc4-a75f84383d5d\n# \u2560\u255013e452cc-7fef-11eb-2e1d-a5e3b9936a4c\n# \u2560\u255013ab59ea-7fef-11eb-2078-6d8ee11d1c90\n# \u2560\u25502886e6c4-7fef-11eb-0fff-9b3033e4f943\n# \u2560\u25503f1f4bba-7fef-11eb-2f39-cf906aec10ae\n# \u2560\u25503f037186-7fef-11eb-200f-3579d0ab8e1f\n# \u2560\u25503eea0d36-7fef-11eb-3ede-c7d54243194c\n# \u255f\u25003ece19f8-7fef-11eb-3b91-ff25fd3ca8f4\n# \u2560\u25503eb0843a-7fef-11eb-2c67-9ba2e4d1eefc\n# \u2560\u25505c9fbbc6-7fef-11eb-32ad-b986ca56aa9b\n# \u2560\u25505c84a84c-7fef-11eb-3117-01f1842890f5\n# \u2560\u25505c665cd4-7fef-11eb-2c89-e153a973b30e\n# \u2560\u25505c4f64ac-7fef-11eb-1864-13f293e85fc4\n# \u255f\u25005c33d6ce-7fef-11eb-12c1-29396395358d\n# \u2560\u255084fc02d6-7fef-11eb-2e21-cb577c3974f0\n# \u2560\u255084ddd280-7fef-11eb-29cb-3fc8c8547134\n# \u2560\u2550916346b8-7fef-11eb-0d53-29bd11c34510\n# \u2560\u255099672fe6-7fef-11eb-305e-d98ce4bc8dc1\n# \u255f\u2500be076e8a-7fef-11eb-0741-79beea838677\n# \u2560\u2550d5b96cac-7fef-11eb-0772-551e4d96efb2\n# \u2560\u2550d59d0508-7fef-11eb-20a3-3f108b859670\n# \u2560\u2550d57e75ac-7fef-11eb-1cc7-db506a7e4e2f\n# \u2560\u2550fbb04502-7fef-11eb-28fd-414c2f982855\n# \u2560\u25503e2da118-7ff0-11eb-36ca-e32af03b2a0c\n# \u2560\u25503e0a484e-7ff0-11eb-17be-e9e7aa66fb2c\n# \u2560\u25503dd5c57e-7ff0-11eb-3330-cf7d02b5c632\n# \u2560\u2550732679da-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": "using IntervalArithmetic\nif VERSION < v\"0.7.0-DEV.2004\"\n    using Base.Test\nelse\n    using Test\nend\n\n\n@testset \"Interval loop tests\" begin\n    i = 1\n\n    @test Interval(i,i).lo == 1\n    @test @interval(i).lo == 1\n\n\n    for i in 1:10\n        a = @interval(i)\n        @test a.lo == i\n    end\n\nend\n\n\n## Calculate pi by summing 1/i^2 to give pi^2/6:\n\nsetprecision(Interval, 53)\n\nfunction calc_pi1(N)\n    S1 = @interval(0)\n\n    for i in 1:N\n        S1 += @interval(1/i^2)\n    end\n    S1 += @interval(1/(N+1), 1/N)\n\n    sqrt(6*S1)\nend\n\n\nfunction calc_pi2(N)\n    S2 = @interval(0)\n\n    for i in 1:N\n        S2 += 1/i^2\n    end\n    S2 += @interval(1/(N+1), 1/N)\n\n    sqrt(6*S2)\nend\n\n\nfunction calc_pi3(N)\n    S3 = @floatinterval(0)\n\n    for i in 1:N\n        S3 += 1/i^2\n    end\n    S3 += @floatinterval(1/(N+1), 1/N)\n\n    sqrt(6*S3)\nend\n\nfunction calc_pi4(N)\n    S4 = @floatinterval(0)\n    II = @floatinterval(1)\n\n    for i in N:-1:1\n        S4 += II / (i^2)\n    end\n    S4 += II / @floatinterval(N, N+1)\n\n    sqrt(6*S4)\nend\n\nfunction calc_pi5(N)\n    S5 = @floatinterval(0)\n    II = @floatinterval(1)\n\n    for i in N:-1:1\n        S5 += 1 // (i^2)\n    end\n    S5 += 1 / @floatinterval(N, N+1)\n\n    sqrt(6*S5)\nend\n\n\n@testset \"Pi tests\" begin\n\n    big_pi = setprecision(256) do\n        big(pi)\n    end\n\n    N = 10000\n    pi1 = calc_pi1(N)\n    pi2 = calc_pi2(N)\n    pi3 = calc_pi3(N)\n    pi4 = calc_pi4(N)\n    pi5 = calc_pi5(N)\n\n\n    @test big_pi \u2208 pi1\n    @test big_pi \u2208 pi2\n    @test big_pi \u2208 pi3\n    @test big_pi \u2208 pi4\n    @test big_pi \u2208 pi5\n\n    @test pi1 == pi2\n    @test pi2 == pi3\n\nend\n\nsetprecision(Interval, Float64)\n", "meta": {"hexsha": "95be5dc0f8678e0c69a4fa0a38d958a355d002a9", "size": 1614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interval_tests/loops.jl", "max_stars_repo_name": "mewilhel/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "38a011b4f87eaa37bce97c0f2c38a526eb1e0841", "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/interval_tests/loops.jl", "max_issues_repo_name": "mewilhel/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "38a011b4f87eaa37bce97c0f2c38a526eb1e0841", "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/interval_tests/loops.jl", "max_forks_repo_name": "mewilhel/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "38a011b4f87eaa37bce97c0f2c38a526eb1e0841", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-06T06:15:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T06:15:24.000Z", "avg_line_length": 14.1578947368, "max_line_length": 48, "alphanum_fraction": 0.5402726146, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.7990997247586411}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.1\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 321b951c-9bea-11ec-0d10-31f76d44cc9e\nmd\"\"\"\n# HW 7\n\nEric Nguyen\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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} \u22c5 \\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\u0307 = \\sin{\\theta} \\cos{\\phi} \\, r\u0307 + r \\cos{\\theta} \\cos{\\phi} \\,\\dot{\\theta} - r \\sin{\\theta} \\sin{\\phi} \\,\\dot{\\phi} \\\\\nv_y &= y\u0307 = \\sin{\\theta} \\sin{\\phi} \\, r\u0307 + r \\cos{\\theta} \\sin{\\phi} \\,\\dot{\\theta} + r \\sin{\\theta} \\cos{\\phi} \\, \\dot{\\phi} \\\\\nv_z &= z\u0307 = \\cos{\\theta} \\,r\u0307 - 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\u0307 + r \\cos{\\theta} \\cos{\\phi} \\,\\dot{\\theta} - r \\sin{\\theta} \\sin{\\phi} \\,\\dot{\\phi})^2 \\\\\n&= \\sin{\\theta}^2 \\cos^2{\\phi} \\, r\u0307^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\u0307 \\,\\dot{\\theta} - 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,r\u0307 \\,\\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\u0307 + r \\cos{\\theta} \\sin{\\phi} \\,\\dot{\\theta} + r \\sin{\\theta} \\cos{\\phi} \\, \\dot{\\phi})^2 \\\\\n&= \\sin^2{\\theta} \\sin^2{\\phi} \\,r\u0307^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\u0307 \\,\\dot{\\theta} + 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,r\u0307 \\,\\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\u0307 - r \\sin{\\theta} \\,\\dot{\\theta})^2 \\\\\n&= \\cos^2{\\theta} \\,r\u0307^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 - 2r \\sin{\\theta} \\cos{\\theta} \\,r\u0307 \\,\\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\u0307^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\u0307 \\,\\dot{\\theta} - 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,r\u0307 \\,\\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\u0307^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\u0307 \\,\\dot{\\theta} + 2r \\sin^2{\\theta} \\sin{\\phi} \\cos{\\phi} \\,r\u0307 \\,\\dot{\\phi} \\\\\n&\\quad + 2r \\sin{\\theta} \\cos{\\theta} \\sin{\\phi} \\cos{\\phi} \\,\\dot{\\theta} \\,\\dot{\\phi} \\\\\n&\\quad + \\cos^2{\\theta} \\,r\u0307^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 - 2r \\sin{\\theta} \\cos{\\theta} \\,r\u0307 \\,\\dot{\\theta} \\\\\n\n&= \\sin{\\theta}^2 \\cos^2{\\phi} \\, r\u0307^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\u0307^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\u0307^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 \\\\\n\n&= \\sin^2{\\theta} \\,r\u0307^2 + r^2 \\cos^2{\\theta} \\,\\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\phi}^2 \\\\\n&\\quad + \\cos^2{\\theta} \\,r\u0307^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\theta}^2 \\\\\n\n&= r\u0307^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\u0307^2 + r^2 \\, \\dot{\\theta}^2 + r^2 \\sin^2{\\theta} \\,\\dot{\\phi}^2)$\n\"\"\"\n\n# \u2554\u2550\u2561 a1799513-6a61-4443-8ec7-428c0696bc5f\nmd\"\"\"\n### Problem 3\n\n**(a).**\nThe square of the magnitude of the cross product ``|\\vec{A} \u00d7 \\vec{B}|^2`` is\n\n$\\begin{align*}\n|\\vec{A} \u00d7 \\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} \u22c5 \\vec{B})^2`` is\n\n$\\begin{align*}\n(\\vec{A} \u22c5 \\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} \u22c5 \\vec{B})^2 = |\\vec{A} \u00d7 \\vec{B}|^2$\n\nThus,\n\n$|\\vec{A} \u00d7 \\vec{B}|^2 = |\\vec{A}|^2 |\\vec{B}|^2 - (\\vec{A} \u22c5 \\vec{B})^2$\n\"\"\"\n\n# \u2554\u2550\u2561 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} \u00d7 \\vec{B}|^2 &= (\\epsilon_{ijk} \\hat{e}_i A_j B_k) \u22c5 (\\epsilon_{\u2113mn} \\hat{e}_\u2113 A_m B_n) \\\\\n&= A_j B_k A_m B_n \\epsilon_{ijk} \\epsilon_{\u2113mn} \\delta_{i\u2113} \\\\\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} \u22c5 \\vec{A}) (\\vec{B} \u22c5 \\vec{B}) - (\\vec{A} \u22c5 \\vec{B}) (\\vec{A} \u22c5 \\vec{B}) \\\\\n&= |\\vec{A}|^2 |\\vec{B}|^2 - (\\vec{A} \u22c5 \\vec{B})^2\n\\end{align*}$\n\"\"\"\n\n# \u2554\u2550\u2561 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{\u2202}{\u2202r}``, in the ``\\theta``-direction, the derivative is ``\\frac{1}{r} \\frac{\u2202}{\u2202\\theta}``, and in the ``\\phi``-direction, the derivative is ``\\frac{1}{r \\sin{\\theta}} \\frac{\u2202}{\u2202\\phi}``.\nThe gradient in spherical coordinates is then\n\n$\\vec{\u2207} = \\hat{r} \\frac{\u2202}{\u2202r} + \\hat{\\theta} \\frac{1}{r} \\frac{\u2202}{\u2202\\theta} + \\hat{\\phi} \\frac{1}{r \\sin{\\theta}} \\frac{\u2202}{\u2202\\phi}$\n\"\"\"\n\n# \u2554\u2550\u2561 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{\u2202\\hat{r}}{\u2202\\phi} &= -\\hat{i} \\sin{\\phi} + \\hat{j} \\cos{\\phi} = \\hat{\\phi} \\\\\n\\frac{\u2202\\hat{\\phi}}{\u2202\\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{\u2207}^2 f(r,\\phi) &= \\vec{\u2207} \u22c5 \\vec{\u2207} f(r,\\phi) \\\\\n&= \\left(\\hat{r} \\frac{\u2202}{\u2202r} + \\hat{\\phi} \\frac{1}{r} \\frac{\u2202}{\u2202\\phi}\\right) \u22c5 \\left(\\hat{r} \\frac{\u2202f}{\u2202r} + \\hat{\\phi} \\frac{1}{r} \\frac{\u2202f}{\u2202\\phi}\\right) \\\\\n&= \\hat{r} \\frac{\u2202}{\u2202r} \\left(\\hat{r} \\frac{\u2202f}{\u2202r} + \\hat{\\phi} \\frac{1}{r} \\frac{\u2202f}{\u2202\\phi}\\right) + \\hat{\\phi} \\frac{1}{r} \\frac{\u2202}{\u2202\\phi} \\left(\\hat{r} \\frac{\u2202f}{\u2202r} + \\hat{\\phi} \\frac{1}{r} \\frac{\u2202f}{\u2202\\phi}\\right) \\\\\n&= \\hat{r} \\left(\\hat{r} \\frac{\u2202^2f}{\u2202r^2} - \\hat{\\phi} \\frac{1}{r^2} \\frac{\u2202f}{\u2202\\phi} + \\hat{\\phi} \\frac{1}{r} \\frac{\u2202f}{\u2202\\phi \u2202r}\\right) \\\\\n&\\quad + \\hat{\\phi} \\frac{1}{r} \\left(\\hat{\\phi} \\frac{\u2202f}{\u2202r} + \\hat{r} \\frac{\u2202f}{\u2202r \u2202\\phi} - \\hat{r} \\frac{1}{r} \\frac{\u2202f}{\u2202\\phi} + \\hat{\\phi} \\frac{1}{r} \\frac{\u2202^2 f}{\u2202\\phi^2}\\right) \\\\\n&= \\frac{\u2202^2f}{\u2202r^2} + \\frac{1}{r} \\frac{\u2202f}{\u2202r} + \\frac{1}{r^2} \\frac{\u2202^2 f}{\u2202\\phi^2} \\\\\n&= \\frac{1}{r} \\frac{\u2202}{\u2202r} \\left(r \\frac{\u2202f}{\u2202r}\\right) + \\frac{1}{r^2} \\frac{\u2202^2 f}{\u2202\\phi^2}\n\\end{align*}$\n\"\"\"\n\n# \u2554\u2550\u2561 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500321b951c-9bea-11ec-0d10-31f76d44cc9e\n# \u255f\u2500710b2cc8-45e7-4eee-9066-3fd4080aebc9\n# \u255f\u2500370b6a47-79b6-41e3-ad41-01544affa97d\n# \u255f\u2500a1799513-6a61-4443-8ec7-428c0696bc5f\n# \u255f\u250008ef5ce6-9d82-4758-ade2-4ea62b514451\n# \u255f\u2500c0971a8a-7d86-4cb6-aae9-5423beeb1da4\n# \u255f\u250074bea6fd-90e1-4aad-bb58-50b141eb0255\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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 \u03f5-algorithm corresponds to creating a diagonal sequence in the Pad\u00e9 table.\n\nEpsilon = \u03f5(cumsum(a))\n\nEpsilon(1:20)\n\n# Now we can see how the Pad\u00e9 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 \u03f5-algorithm to generate Pad\u00e9 approximants instead of a Poincar\u00e9-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\u03f5(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    \u0394t = 1.0 # Time step\r\n    \u0394P = [20.0; 5.0] # Process errors in process covariance matrix\r\n    \u0394 = [25.0; 6.0] # Observation errors\r\n    return X, a, \u0394, \u0394P, \u0394t\r\nend\r\n\r\n## Define the state space model\r\n\r\nfunction define_model(X, a, \u0394, \u0394P, \u0394t)\r\n    m, n = size(X)\r\n    Q = zeros(m, m) # Process noise covariance matrix\r\n    F = [1.0 \u0394t; 0.0 1.0] # Transition matrix\r\n    B = [\u0394t^2/2.0 \u0394t]' # Control-input matrix\r\n    u = 2.0 # # Control vector, acceleration\r\n    R = linalg.Diagonal([\u0394[1]^2 0.0; 0.0 \u0394[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([\u0394P[1]^2 \u0394P[1]*\u0394P[2]; \u0394P[2]*\u0394P[1] \u0394P[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, \u03a3)\r\n    k = length(Xk)\r\n    sm = Vector{kf.RTSSmoother}(undef, k)\r\n    sm[k] = kf.RTSSmoother(Xk[k], \u03a3[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], \u03a3[k-1], \u03a3[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, \u03b1; 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, \u03b1=\u03b1,\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, \u0394)\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=\u0394[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=\u0394[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, \u0394)\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=\u0394[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=\u0394[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, \u0394, \u0394P, \u0394t = get_data()\r\nP, Q, R, F, H, B, u, m, n = define_model(X, a, \u0394, \u0394P, \u0394t)\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, \u0394)\r\n\r\n## Rauch Tung Striebel Smoother\r\n\u03a3, Xkm = kf.unpack_matrix(skf, [:P, :xk])\r\nskm = run_smoothers_bts(Xkm, F, \u03a3)\r\nXkm = kf.unpack(skf, :xk)\r\np1m = plot_kf_smooth(Xp, Xk, X, Xkm, \u0394)\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  Name     : c7_17_optim_example.jl\n  Book     : Hands-on Data Science with Anaconda )\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan and James Yan\n  Date     : 3/15/2018\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n###\n\n\n\n\nusing Optim\nf(x) = (1.0 - x[1])^2 + 200.0 * (x[2] - x[1]^2)^2\noptimize(f, [0.0, 0.0])\n", "meta": {"hexsha": "4113734de02c659eeb92fa1d7ab7f13d7a32ebfe", "size": 346, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter07/c7_17_optim_example.jl", "max_stars_repo_name": "andrewjcoxon/Hands-On-Data-Science-with-Anaconda", "max_stars_repo_head_hexsha": "82504a059ecd284b3599fa9af2b3eb6bbd6e28f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-06-25T16:21:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T09:28:29.000Z", "max_issues_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter07/c7_17_optim_example.jl", "max_issues_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_issues_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter07/c7_17_optim_example.jl", "max_forks_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_forks_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-06-15T02:55:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T15:24:42.000Z", "avg_line_length": 20.3529411765, "max_line_length": 50, "alphanum_fraction": 0.5780346821, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.799006226749482}}
{"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 Polylogarithms\nusing SpecialFunctions\nusing Test\nusing DataFrames, CSV\nimport Base.MathConstants: \u03c0, pi, \u212f, e, \u03b3, eulergamma, catalan, \u03c6, golden\ninclude(\"test_defs.jl\")\n\n@testset \"Harmonic numbers\" begin\n\n    @testset \"    throws errors\" begin\n        @test_throws DomainError harmonic(-1)\n        @test_throws MethodError harmonic(Float32(1.0))\n    end\n    \n    @testset \"    types\" begin\n        @test typeof(harmonic(1)) == Float64\n        @test typeof(harmonic(1.0)) == Float64\n        @test typeof(harmonic(complex(1.0))) == Complex{Float64}\n    end\n\n    @testset \"    basics\" begin\n        @test harmonic(1) \u2245 1.0\n        @test harmonic(2) \u2245 1.5\n        @test harmonic(3) \u2245 11.0/6.0\n        @test harmonic(4) \u2245 25.0/12.0\n        @test harmonic(5) \u2245 137.0/60.0\n    end\n\n    @testset \"    identities\" begin\n        for n=4:10\n            @test harmonic(n) \u2245 1.0/n + harmonic(n-1)\n        end\n        \n        for n=20:30\n            @test harmonic(n) \u2245 sum( 1.0./(1:n) )\n        end\n    end\n\n    @testset \"    dataset 1 (integer arguments)\" begin\n        data1 = CSV.read(\"../data/harmonic_test_data_1.csv\", DataFrame)\n        m = size(data1,1)\n        H = Symbol(\"real(H_n)\")\n        for i=1:m\n            @test harmonic( data1[i,:n] ) \u2245  data1[i,H]\n        end\n    end\n \n    @testset \"    dataset 2 (real arguments)\" begin\n        data2 = CSV.read(\"../data/harmonic_test_data_2.csv\", DataFrame)\n        m = size(data2,1)\n        H = Symbol(\"real(H_n)\")\n        for i=1:m\n            @test harmonic( data2[i,:x] ) \u2248  data2[i,H] # note the lower accuracy requirement here\n        end\n    end\n\n    @testset \"    dataset 3 (complex arguments)\" begin\n        data3 = CSV.read(\"../data/harmonic_test_data_3.csv\", DataFrame)\n        m = size(data3,1)\n        zr = Symbol(\"Re(z)\")\n        zi = Symbol(\"Im(z)\")\n        Hr = Symbol(\"Re(H(z))\")\n        Hi = Symbol(\"Im(H(z))\")\n        for i=1:m\n            z = data3[i,zr] + im*data3[i,zi]\n            Hz = data3[i,Hr] + im*data3[i,Hi]\n            @test harmonic( z ) \u2248  Hz # note the lower accuracy requirement here\n        end\n    end\nend\n\n@testset \"Generalised Harmonic numbers\" begin\n      \n    @testset \"    throws errors\" begin\n        @test_throws DomainError harmonic(-1, 1.2)\n        @test_throws MethodError harmonic(1.0, 1)\n        @test_throws MethodError harmonic(1.0, 1.0)\n        @test_throws MethodError harmonic(complex(1.0), 1)\n    end\n\n    @testset \"    output types\" begin\n        @test typeof(harmonic(1, 1)) == Float64\n        @test typeof(harmonic(1, 1.0)) == Float64\n    end\n\n    @testset \"     identities\" begin\n        for n=1:10\n            @test harmonic(n,1.0) \u2245 harmonic(n)\n            @test harmonic(n,0.0) \u2245 n\n            \n            for r = 3:2:9\n                @test harmonic(n,r) \u2245 Float64(n)^(-r) + polygamma(r-1,n)/gamma(r) + zeta(r)\n            end\n        end\n    end\n\n    @testset \"    dataset 4 (integer arguments)\" begin\n        H = Symbol(\"real(H_{n,r})\")\n        data4 = CSV.read(\"../data/harmonic_test_data_4.csv\", DataFrame)\n        m = size(data4,1)\n        for i=1:m\n            @test harmonic( data4[i,:n], data4[i,:r] ) \u2245 data4[i,H]\n        end\n    end\n\n    @testset \"    dataset 5 (integer n, real r)\" begin\n        H = Symbol(\"real(H_{n,r})\")\n        data5 = CSV.read(\"../data/harmonic_test_data_5.csv\", DataFrame)\n        m = size(data5,1)\n        for i=1:m\n            @test harmonic( data5[i,:n], data5[i,:r] )  \u2245 data5[i,H]\n        end\n    end\nend\n", "meta": {"hexsha": "390d1b92d2713e955a03a042f4b83e8f1b4dffe4", "size": 3457, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/harmonic_test.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": "test/harmonic_test.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": "test/harmonic_test.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": 30.0608695652, "max_line_length": 98, "alphanum_fraction": 0.5420885161, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7989788311646531}}
{"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\u03f5 = 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 + \u03f5*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\u03bb = Float64[]\n\u03f5vec = .0:.0001:.025\nfor \u03f5 = \u03f5vec\n    append!(max\u03bb,maximum(abs.(eigvals(Matrix(I - dt*(Q + \u03f5*A))))))\nend\nscatter(\u03f5vec,max\u03bb,leg=false)\nplot!(title=\"Largest eigenvalue magnitude with \u03f5\")\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# Derivatives of f: R -> R\n#\n\n@assert norm(Calculus.finite_difference(x -> x^2, 1.0, :forward) - 2.0) < 10e-4\n@assert norm(Calculus.finite_difference(x -> x^2, 1.0, :central) - 2.0) < 10e-4\n@assert norm(Calculus.finite_difference(x -> x^2, 1.0) - 2.0) < 10e-4\n\n@assert norm(Calculus.finite_difference(x -> sin(x), 1.0, :forward) - cos(1.0)) < 10e-4\n@assert norm(Calculus.finite_difference(x -> sin(x), 1.0, :central) - cos(1.0)) < 10e-4\n@assert norm(Calculus.finite_difference(x -> sin(x), 1.0) - cos(1.0)) < 10e-4\n\n@assert norm(Calculus.finite_difference(x -> exp(-x), 1.0, :forward) - (-exp(-1.0))) < 10e-4\n@assert norm(Calculus.finite_difference(x -> exp(-x), 1.0, :central) - (-exp(-1.0))) < 10e-4\n@assert norm(Calculus.finite_difference(x -> exp(-x), 1.0) - (-exp(-1.0))) < 10e-4\n\n#\n# Gradients of f: R^n -> R\n#\n\n@assert norm(Calculus.finite_difference(x -> x[1]^2, [1.0], :forward) - [2.0]) < 10e-4\n@assert norm(Calculus.finite_difference(x -> x[1]^2, [1.0], :central) - [2.0]) < 10e-4\n@assert norm(Calculus.finite_difference(x -> x[1]^2, [1.0]) - [2.0]) < 10e-4\n\n@assert norm(Calculus.finite_difference(x -> sin(x[1]), [1.0], :forward) - [cos(1.0)]) < 10e-4\n@assert norm(Calculus.finite_difference(x -> sin(x[1]), [1.0], :central) - [cos(1.0)]) < 10e-4\n@assert norm(Calculus.finite_difference(x -> sin(x[1]), [1.0]) - [cos(1.0)]) < 10e-4\n\n@assert norm(Calculus.finite_difference(x -> exp(-x[1]), [1.0], :forward) - [-exp(-1.0)]) < 10e-4\n@assert norm(Calculus.finite_difference(x -> exp(-x[1]), [1.0], :central) - [-exp(-1.0)]) < 10e-4\n@assert norm(Calculus.finite_difference(x -> exp(-x[1]), [1.0]) - [-exp(-1.0)]) < 10e-4\n\n#\n# Second derivatives of f: R -> R\n#\n\n@assert norm(Calculus.finite_difference_hessian(x -> x^2, x -> 2 * x, 1.0, :forward) - 2.0) < 10e-4\n@assert norm(Calculus.finite_difference_hessian(x -> x^2, x -> 2 * x, 10.0, :forward) - 2.0) < 10e-4\n@assert norm(Calculus.finite_difference_hessian(x -> x^2, x -> 2 * x, 100.0, :forward) - 2.0) < 10e-4\n\n@assert norm(Calculus.finite_difference_hessian(x -> x^2, 1.0, :forward) - 2.0) < 10e-4\n@assert norm(Calculus.finite_difference_hessian(x -> x^2, 10.0, :forward) - 2.0) < 10e-4\n@assert norm(Calculus.finite_difference_hessian(x -> x^2, 100.0, :forward) - 2.0) < 10e-4\n\n#\n# Hessians of f: R^n -> R\n#\n\nfx(x) = sin(x[1]) + cos(x[2])\ngx = gradient(fx)\n@assert norm(gx([0.0, 0.0]) - [cos(0.0), -sin(0.0)]) < 10e-4\n@assert norm(Calculus.finite_difference_hessian(fx, gx, [0.0, 0.0], :central) - [-sin(0.0) 0.0; 0.0 -cos(0.0)]) < 10e-4\n\n#\n# Taylor Series first derivatives\n#\n\n@assert norm(Calculus.taylor_finite_difference(x -> x^2, 1.0, :forward) - 2.0) < 10e-4\n@assert norm(Calculus.taylor_finite_difference(x -> x^2, 1.0, :central) - 2.0) < 10e-4\n\n#\n# Taylor Series second derivatives\n#\n\n# TODO: Fill this in\n\n#\n# Speed comparisons\n#\n\n@elapsed Calculus.finite_difference(x -> x^2, 1.0, :forward)\n@elapsed Calculus.finite_difference(x -> x^2, 1.0, :central)\n@elapsed Calculus.finite_difference(x -> x^2, 1.0)\n@elapsed Calculus.taylor_finite_difference(x -> x^2, 1.0, 10e-4, :forward)\n@elapsed Calculus.taylor_finite_difference(x -> x^2, 1.0, 10e-4, :central)\n", "meta": {"hexsha": "af006223f7e323e3181010d60029674263408b13", "size": 3129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/finite_difference.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": "test/finite_difference.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": "test/finite_difference.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": 41.1710526316, "max_line_length": 119, "alphanum_fraction": 0.6398210291, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7989788178632632}}
{"text": "\n\"\"\"\n    Matern(ln\u2113::AbstractFloat, ln\ud835\udccb::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\u0301rn covariance function on Wikipedia](https://en.wikipedia.org/wiki/Mate\u0301rn_covariance_function)\n\n\"\"\"\nmutable struct Matern{\n    F<:AbstractFloat\n} <: RadialKernel{Euclidean}\n    dist::Euclidean\n    ln\u2113::F\n    ln\ud835\udccb::F\n    \n    \ud835\udccb::F\n    c::F # 2^(1 - \ud835\udccb) / \u0393(\ud835\udccb)\n    sqrttwo\ud835\udccb_\u2113::F\n    \n    function Matern(\n        dist::Euclidean,\n        ln\u2113::AbstractFloat,\n        ln\ud835\udccb::AbstractFloat\n    )\n        ln\u2113, ln\ud835\udccb = promote(ln\u2113, ln\ud835\udccb)\n        \ud835\udccb = exp(ln\ud835\udccb)\n        new{typeof(ln\u2113)}(\n            dist,\n            ln\u2113,\n            ln\ud835\udccb,\n            \ud835\udccb,\n            exp2(1 - \ud835\udccb) / gamma(\ud835\udccb),\n            exp((float(logtwo) + ln\ud835\udccb) / 2),\n        )\n    end\nend\n\nMatern(ln\u2113::AbstractFloat, ln\ud835\udccb::AbstractFloat) =\n    Matern(Euclidean(), ln\u2113, ln\ud835\udccb)\n\n@inline function (k::Matern)(\u03c4::AbstractFloat)\n    if \u03c4 == 0\n        return oneunit(promote(\u03c4, k.\ud835\udccb)[1])\n    end\n    t = k.sqrttwo\ud835\udccb_\u2113 * \u03c4\n    return k.c * (t^k.\ud835\udccb) * besselk(k.\ud835\udccb, t)\nend\n\nnumparams(::Matern) = (1, 1)\nparamtypes(::Matern{F}) where F = (F, F)\nparams(k::Matern) = (ln\u2113 = k.ln\u2113, ln\ud835\udccb = k.ln\ud835\udccb)\nfunction setparams!(k::Matern{F}, ln\u2113::F, ln\ud835\udccb::F) where F\n    \ud835\udccb = exp(ln\ud835\udccb)\n    k.ln\u2113 = ln\u2113\n    k.ln\ud835\udccb = ln\ud835\udccb\n    k.\ud835\udccb = \ud835\udccb\n    k.c = exp2(1 - \ud835\udccb) / gamma(\ud835\udccb)\n    k.sqrttwo\ud835\udccb_\u2113 = exp((float(logtwo) + ln\ud835\udccb) / 2 - ln\u2113)\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 Compat.Test\nimport Roots.newton, Roots.halley\n\n@test norm(newton(sin, cos, 0.5) - 0.0) <= 100*eps(1.0)\n@test newton(cos, x -> -sin(x), 1.0)  \u2248 pi/2 \n@test newton(x -> x^2 - 2x - 1, x -> 2x - 2, 3.0)  \u2248 2.414213562373095\n@test norm(newton(x -> exp(x) - cos(x), x -> exp(x) + sin(x), 3.0) - 0.0) <= 1e-14\n@test halley(x -> x^2 - 2x - 1,x -> 2x - 2,x -> 2, 3.0)  \u2248 2.414213562373095\na = halley(x -> exp(x) - cos(x),\n           x -> exp(x) + sin(x),\n           x -> exp(x) + cos(x), 3.0)\n@test norm(a - 0.0) <= 1e-14\n\n\n## tests with auto derivatives\n@test newton(sin, 3) \u2248 pi\n@test halley(sin, 3) \u2248 pi\n\n## More tests with autoderivaitves. Derivative of D operation:\nisdefined(ForwardDiff, :derivative) && @test newton(D(sin), 1.5) \u2248 pi/2\n\n## test with Complex input\n\n@test real(newton(x ->  x^3 - 1, x ->  3x^2, 1+im)) \u2248 1.0\n@test real(newton(x ->  x^3 - 1, x ->  3x^2, 1+10im)) \u2248 (-1/2)\n", "meta": {"hexsha": "9e08cbb0f4cdc2236ae911529028ade44515bd69", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 34.2307692308, "max_line_length": 82, "alphanum_fraction": 0.5595505618, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.798958918168871}}
{"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 \u2264 n \u2264 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        \u03d5 =  T(\u03c0/3)\n    elseif r >= 1\n        \u03d5 = zero(T)\n    else\n        \u03d5 = acos(r)/3\n    end\n  \n    # the eigenvalues satisfy eig.z >= eig.y >= eig.x\n    eig3 = q + 2*p*cos(\u03d5)\n    # cos(x+y) = cos(x)*cos(y) - sin(x)*sin(y)\n    eig1 = q + 2*p*cos(\u03d5+(2*\u03c0/3))  # q - 2*p*(cos(\u03d5)/2 + (\u221a3/2)sin(\u03d5))\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    \u03d5 = acos(r)/3\n  \n    # the eigenvalues satisfy eig.z >= eig.y >= eig.x\n    eig3 = q + 2*p*cos(\u03d5)\n    eig1 = q + 2*p*cos(\u03d5+(2*\u03c0/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        \u03d5 =  T(\u03c0/3)\n    elseif r >= 1\n        \u03d5 = zero(T)\n    else\n        \u03d5 = acos(r)/3\n    end  \n\n    # the eigenvalues satisfy eig.z >= eig.y >= eig.x\n    \u03bb3 = q + 2*p*cos(\u03d5)\n    \u03bb1 = q + 2*p*cos(\u03d5+(2*\u03c0/3))\n    \u03bb2 = 3*q - \u03bb1 - \u03bb3     # 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        (\u03bb1, \u03bb3) = (\u03bb3, \u03bb1)\n    end\n      # Calculate the first eigenvector\n        # This should be orthogonal to these three rows of A - \u03bb1*I\n        # Use all combinations of cross products and choose the \"best\" one\n    r\u2081 = Vec(S11 - \u03bb1, S12, S13)\n    r\u2082 = Vec(S12, S22 - \u03bb1, S23)\n    r\u2083 = Vec(S13, S23, S33 - \u03bb1)\n    n\u2081 = r\u2081 \u22c5 r\u2081\n    n\u2082 = r\u2082 \u22c5 r\u2082\n    n\u2083 = r\u2083 \u22c5 r\u2083\n\n    r\u2081\u2082 = r\u2081 \u00d7 r\u2082\n    r\u2082\u2083 = r\u2082 \u00d7 r\u2083\n    r\u2083\u2081 = r\u2083 \u00d7 r\u2081\n    n\u2081\u2082 = r\u2081\u2082 \u22c5 r\u2081\u2082\n    n\u2082\u2083 = r\u2082\u2083 \u22c5 r\u2082\u2083\n    n\u2083\u2081 = r\u2083\u2081 \u22c5 r\u2083\u2081\n\n    # we want best angle so we put all norms on same footing\n    # (cheaper to multiply by third n\u1d62 rather than divide by the two involved)\n    if n\u2081\u2082 * n\u2083 > n\u2082\u2083 * n\u2081\n        if n\u2081\u2082 * n\u2083 > n\u2083\u2081 * n\u2082\n            @fastmath \u03d51 = r\u2081\u2082 / sqrt(n\u2081\u2082)\n        else\n            @fastmath \u03d51 = r\u2083\u2081 / sqrt(n\u2083\u2081)\n        end\n    else\n        if n\u2082\u2083 * n\u2081 > n\u2083\u2081 * n\u2082\n            @fastmath \u03d51 = r\u2082\u2083 / sqrt(n\u2082\u2083)\n        else\n            @fastmath \u03d51 = r\u2083\u2081 / sqrt(n\u2083\u2081)\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 - \u03bb2*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(\u03d51.x) < abs(\u03d51.y) # safe to set one component to zero, depending on this\n        @fastmath orthogonal1 = Vec(-\u03d51.z, zero(T), \u03d51.x) / sqrt(abs2(\u03d51.x) + abs2(\u03d51.z))\n    else\n        @fastmath orthogonal1 = Vec(zero(T), \u03d51.z, -\u03d51.y) / sqrt(abs2(\u03d51.y) + abs2(\u03d51.z))\n    end\n    orthogonal2 = \u03d51 \u00d7 orthogonal1\n\n    # The projected 2x2 eigenvalue problem is C x = 0 where C is the projection\n    # of (A - \u03bb2*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 - \u03bb2\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 - \u03bb2\n\n    # Solve this robustly (some values might be small or zero)\n    c11\u00b2 = abs2(c11)\n    c12\u00b2 = abs2(c12)\n    c22\u00b2 = abs2(c22)\n    if c11\u00b2 >= c22\u00b2\n        if c11\u00b2 > 0 || c12\u00b2 > 0\n            if c11\u00b2 >= c12\u00b2\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            \u03d52 = p1*orthogonal1 - p2*orthogonal2\n        else # c11 == 0 && c12 == 0 && c22 == 0 (smaller than c11)\n            \u03d52 = orthogonal1\n        end\n    else\n        if c22\u00b2 >= c12\u00b2\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        \u03d52 = p1*orthogonal1 - p2*orthogonal2\n    end\n\n\n    # The third eigenvector is a simple cross product of the other two\n    \u03d53 = \u03d51 \u00d7 \u03d52 # should be normalized already\n\n    ###############################################################################################################################333\n    if r > 0\n        (\u03bb1, \u03bb3) = (\u03bb3, \u03bb1)\n        (\u03d51, \u03d53) = (-\u03d53, \u03d51) # - sign so e3 = cross(e1,e2) is always true\n    end\n\n    return (\u03bb1,\u03bb2,\u03bb3),(\u03d51,\u03d52,\u03d53)\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 '\u03d5', in arbitrary dimensions, 'd'.\"\nfunction radius_from_phi(d::Int64, \u03d5::Real, N::Int64, L::Real=1.0)::Float64\n    #d: dimension; \u03d5: packing fraction; N: number of particles; L: size of box\n    Vd = volume_d_ball(d)\n    return L*(\u03d5/(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 '\u03d5', in arbitrary dimensions, 'd'. It is assumed that R2/R1=c.\"\nfunction radii_from_phi(d::Int64, \u03d5::Real, N1::Int64, N2::Int64=N1, c::T=1.4, L::T=1.0) where T<:AbstractFloat\n    #d: dimension; \u03d5: 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*(\u03d5/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, \u03d5::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 '\u03d5' 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, \u03d5::T, L::T=1.0; max_tries::Int64=5000 ) where {T<:AbstractFloat}\n    r = radius_from_phi(d, \u03d5, 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 \u03c6= \", 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, \u03d5::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, \u03d5, 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    \u03c6 = packing_fraction(d, Rs, L)\n    verbose && println(\"Trying to generate a d-\", d, \" dimensional configuration of N = \", N, \" spheres with packing fraction \u03c6= \", \u03c6)\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 \u03c6, 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": "Using Checkers\nusing Math\nusing Test\n\nf(x) = x^2\n @test_formany -10<x<10, f(x) >= 0\n @test_forall x in -10:10, f(x) >= 0\n\n#based from the testing folder in Checkers\n\t@test_formany ntests = 100 maxtests = 100_000 0 < x < 10,  0 < y < 10,  x < y --> x^2 < y^2\n\n#1000 test will be run\n#Passes if 100 tests meet the crierea of holding true. Will fail becuase generating 100 pairs of x,y, some will bound to fail condition\n\n\n#100,000 tests will performed until 100 passing test\n\t@test_formany ntests = 100 maxtests = 100_000 0 < x < 10,  0 < y < 10,  x < y --> x^2 < y^2\n#Same as top but will pass because 100000test will be performed.\n\n\n#another test the conditional property of Julia\n\n\t@test_formany ntests = 100 maxtests = 100_000 0 < x < 7,  8 < y < 80,  x < y --> x^2 < y^2\n#Same as top but will pass because 100000test will be performed.\n\nf(x) = sin(x)\n\t@test_formany -100<x<100, f(x) >= -1\n\nf(x) = sin(x)*cos(x)\n @test_formany -100<x<100, -1< f(x) < 1\n\n#test if tan is right\nfunction tanTest(x)\n\tsin(x)/cos(x)\n\tend\n\n\t@test_forall -1000<x<1000, tanTest(x) == tan(x)\n\n#sin^2(x) + cos^2(x) = 1\nfunction pythagFormula(x)\n       sin(x)^2 + cos(x)^2\n       end\n\n       @test pythagFormula(1) == 1\n       @test_formany -10<x<20 , pythagFormula(x) == 1\n\n\n#test sin(-x) = -sin(x)\nfunction trigidentities(x)\n       sin(-x)\n       end\n\n       @test_formany 0<x<100, trigidentities(x) == -sin(x)\n\n\n#test cos(-x) = cos(x)\nfunction trigidentities2(x)\n       cos(-x)\n       end\n\n       @test_formany 0<x<100, trigidentities2(x) == cos(x)\n\n\n #test tan(-x) = -tan(x)\nfunction trigidentities3(x)\n       tan(-x)\n       end\n\n       @test_formany 0<x<100, trigidentities3(x) == -tan(x)\n\n\n#calculate volume function\nfunction sphere_vol(r)\nreturn 4/3*pi*r^3\nend\n\n#testing for all numbers between 1 and 100\n\t@test_formany 1<r<1000,sphere_vol(r) > 0\n#will pass\n\n\n#calculate quadratic formula/checkers cannot handle passing more than 1 variable\nfunction quadratic2(a::Float64, b::Float64, c::Float64)\n\n    sqr_term = sqrt(b^2-4a*c)\n    r1 = quadratic(a, sqr_term, b)\n    r2 = quadratic(a, -sqr_term, b)\nr1, r2\nend\n\n#Test Failed\n#Expression: (:((1 < a < 20,1 < b < 20,1 < c < 20,quad(a,b,c) > 0)),:(mode = test_formany))\n\n#function return input \nfunction stays(x)\n       return x\n       end\n\n\t@test_formany 1<x<10000, stays(x) == x\n\nfunction additiveProperty(x)\n       return x + 10\n       end\n\n\t@test_formany 1<x<10000, additiveProperty(x) == 10 + x\n\nfunction subtratProperty(x)\n       return x - 10\n       end\n\n\t@test_formany 1<x<10000, subtractProperty(x) == 10 - x\n\nfunction multiplyProperty(x)\n       return x * 10\n       end\n\n\t@test_formany 1<x<10000, multiplyProperty(x) == 10 * x\n\n\t#associative property\n\t#cannot do this with checkers since it is only able to generate tests for one variable at a time\n\t#using Base Test package\n\t@test (1+2)+3 == 1 + (2 + 3)\n\nfunction inverse(x)\n\tx + (-x)\n\tend\n\n\t@test_formany -1000<x<1000, inverse(x) == (-x) + x\n\nfunction identity(x)\n\tx + 0\n\tend\n\n\t@test_formany -1000<x<1000, identity(x) == 0 + x\n\nf(x) = 3x^6 - 7x + 1\n\t@test_exists 0<= x <=1, f(x) == 1\n\n\t#this gives an erro for some reason. What I am trying to test is that this test passes if at some point f(x) = 1 through 0<= x <=1.\n\n#testing Periodicity of trig functions\n\n @test sin(1 + 2pi) == sin(1)\n\t\tTest Failed\n  \t\tExpression: sin(1 + 2pi) == sin(1)\n  \t\t Evaluated: 0.8414709848078964 == 0.8414709848078965\nERROR: There was an error during testing\n\n\n@test tan(1 + pi) == tan(1)\n\t  Test Failed\n  \t  Expression: tan(1 + pi) == tan(1)\n   Evaluated: 1.5574077246549018 == 1.5574077246549023\nERROR: There was an error during testing\n\n\n@test cos(1+2pi) == cos(1)\n\t  Test Failed\n  \t  Expression: cos(1 + 2pi) == cos(1)\n   Evaluated: 0.5403023058681399 == 0.5403023058681398\n\n#testing the double angle formula for sin\n @test sin(2*1) == 2*sin(1)*cos(1)\nTest Failed\n  Expression: sin(2 * 1) == 2 * sin(1) * cos(1)\n   Evaluated: 0.9092974268256817 == 0.9092974268256818\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ba0628f6616855990c60226cbc348364a54ac55e", "size": 3953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/checkers_test.jl", "max_stars_repo_name": "CSUN-COMP587-F18/Julia", "max_stars_repo_head_hexsha": "1a84f432dc37a5f7a1da01b8110fd05d90f57cba", "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": "test/checkers_test.jl", "max_issues_repo_name": "CSUN-COMP587-F18/Julia", "max_issues_repo_head_hexsha": "1a84f432dc37a5f7a1da01b8110fd05d90f57cba", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-09-27T01:16:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T23:33:08.000Z", "max_forks_repo_path": "test/checkers_test.jl", "max_forks_repo_name": "CSUN-COMP587-F18/Julia", "max_forks_repo_head_hexsha": "1a84f432dc37a5f7a1da01b8110fd05d90f57cba", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-26T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T18:11:14.000Z", "avg_line_length": 21.9611111111, "max_line_length": 135, "alphanum_fraction": 0.6435618518, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7988778351199668}}
{"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\u03b3 = 0.303\n\u03b2 = 0.727\nN = 1e5\n\u03be_min = 0.1 \n\u03be_max = 0.6\n\n## Set the domain information\ni_max = 0.02\n\u03f5 = 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 \u2208 [t0, tf], num_supports = 51, \n                    derivative_method = OrthogonalCollocation(2))\n@infinite_parameter(model, \u03be ~ Uniform(\u03be_min, \u03be_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 \u2265 0, Infinite(t, \u03be))\n@variable(model, e \u2265 0, Infinite(t, \u03be))\n@variable(model, i \u2265 0, Infinite(t, \u03be))\n@variable(model, r \u2265 0, Infinite(t, \u03be))\n@variable(model, si, Infinite(t, \u03be))\n@variable(model, 0 \u2264 u \u2264 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, \u222b(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, \u2202(s, t) == -(1 - u) * \u03b2 * si)\n@constraint(model, e_constr, \u2202(e, t) == (1 - u) * \u03b2 * si - \u03be * e)\n@constraint(model, i_constr, \u2202(i, t) == \u03be * e - \u03b3 * i)\n@constraint(model, r_constr, \u2202(r, t) == \u03b3 * i)\n@constraint(model, si == s * i)\n\n## Define the infection rate limit\n@constraint(model, imax_constr, i \u2264 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\u03bes = value(\u03be);\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, \u03be)\", 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, \u03be)\", 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, \u03be)\", 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, \u03be)\", 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\u20131639. 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\u20131909. 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) \u00f7 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\u1d40C\u1d40 = 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\u03bc, \u03a3 = 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, [\u03bc[2:end, 1] \u03bc[2:end, 2] \u03bc[2:end, 3]], label = [\"filtred p\" \"filtered v\" \"filtered a\"])\nxlabel!(\"time step (t)\")\n\n##\n\n# parametrized matrix estimates\nAhat(\u03b8) = [\u03b8[1] dt 1/2*dt^2; 0.0 \u03b8[1] dt; 0.0 0.0 \u03b8[1]]\nBhat(\u03b8) = B\nQhat(\u03b8) = Q\nHhat(\u03b8) = H\nRhat(\u03b8) = R\n# define a parametrized kalman filter\nparam_kf = ParamKalmanFilter(Ahat, Bhat, Qhat, Hhat, Rhat)\n\n\n\u03b80 = [1.1]\npkf = ParamKalmanFilter(Ahat, Bhat, Qhat, Hhat, Rhat)\n\nloss = []\n\u03b8_range = 0.9:0.001:1.1\nfor i in \u03b8_range\n    \u03b8_i = [i]\n    states = run_param_kf(\u03b8_i, pkf, s0, action_sequence, sim_measurements)\n    l = kf_likelihood(\u03b8_i, param_kf, states, action_sequence, sim_measurements)\n    push!(loss, l)\nend\n\nplot(\u03b8_range, loss)\n\n##\n\n# parametrized matrix estimates\nAhat(\u03b8) = [\u03b8[1] \u03b8[2] \u03b8[3]; 0 \u03b8[1] \u03b8[2]; 0 0 \u03b8[1]]\n# Ahat(\u03b8) = [\u03b8[1, 1] \u03b8[1, 2] \u03b8[1, 3]; 0.0 \u03b8[2, 2] \u03b8[2, 3]; 0.0 0.0 \u03b8[3, 3]]\nBhat(\u03b8) = B\nQhat(\u03b8) = Q\nHhat(\u03b8) = H\nRhat(\u03b8) = R\n# define a parametrized kalman filter\nparam_kf = ParamKalmanFilter(Ahat, Bhat, Qhat, Hhat, Rhat)\n\n\u03b80 = [1.0 dt 1/2*dt^2] + 0.1*randn(1, 3)\nopt = ADAM(0.01)\nepochs = 200\nnew\u03b8, loss = run_kf_gradient(\u03b80, param_kf, s0, action_sequence, sim_measurements, opt, epochs)\n\ngrad_states = run_param_filter(new\u03b8, param_kf, s0, action_sequence, sim_measurements)\n\u03bcgrad, \u03a3grad = 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, [\u03bc[2:end, 1] \u03bc[2:end, 2] \u03bc[2:end, 3]], label = [\"filtered p\" \"filtered v\" \"filtered a\"], xlabel=\"time step (t)\")\np1 = plot!(time_step, [\u03bcgrad[2:end, 1] \u03bcgrad[2:end, 2] \u03bcgrad[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, :]-\u03bc[2:end, :]).^2, title=\"KF vs. sim error\", xlabel=\"time step (t)\")\np4 = plot(time_step, (x[2:end, :]-\u03bcgrad[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\u2081, x\u2082, x\u2083, ..., x\u2081^1 * x\u2082^(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\u2081, x\u2081^2, ... , x\u2081^c, x\u2082, x\u2082^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\u03c0)\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\u03c0)\n    return (b - a) .* collect(0:(N - 1)) / N .+ a\nend\n\n\"\"\"\nfourier_wavenumbers(N; L = 2\u03c0)\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\u03c0)\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\u03c0 / 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 \u2208 [0, 2\u03c0)\n# Return\n- 'D': Fourier differentiation matrix\n- 'x': Fourier grid points\n\"\"\"\nfunction fourier(N; a = 0, b = 2\u03c0)\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        \u2131 = fft(I + zeros(N, N), 1)\n        \u2131\u207b\u00b9 = ifft(I + zeros(N, N), 1)\n        D = real.(\u2131\u207b\u00b9 * Diagonal(im .* k) * \u2131)\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 \u2208 [-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 \u00d7 n \u00d7 ... \u00d7 n = n15\n\nBut using a \"binary\" method you can compute it in six multiplications:\n\nn \u00d7 n = n^2\nn^2 \u00d7 n^2 = n^4\nn^4 \u00d7 n^4 = n^8\nn^8 \u00d7 n^4 = n^12\nn^12 \u00d7 n^2 = n^14\nn^14 \u00d7 n = n^15\n\nHowever it is yet possible to compute it in only five multiplications:\n\nn \u00d7 n = n^2\nn^2 \u00d7 n = n^3\nn^3 \u00d7 n^3 = n^6\nn^6 \u00d7 n^6 = n^12\nn^12 \u00d7 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 \u2264 k \u2264 200, find \u2211 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 \u2264 limit && n \u2209 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}) = \u221a(2*\u03c0)*\u212f^(-(x'*x)/2)\n\n\n@doc \"\"\"\nFunction to return Parzen window estimation.\n\n# Examples\n```jldoctest\nfun = \u03a3(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 `\u03b1%` 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 `\u03b1`. 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- `\u03b1`:              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\u00e9d\u00e9e-Manesme, Charles-Olivier and Barth\u00e9l\u00e9my, Fabrice and Maillard, Didier (2017). Computation of the Corrected Cornish\u2013Fisher Expansion using the Response Surface Methodology: Application to VaR and CVaR. THEMA Working Paper n\u00b02017-21, Universit\u00e9 de Cergy-Pontoise, France.\n\"\"\"\nfunction expected_shortfall(returns, \u03b1, 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) * \u03b1)\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(), \u03b1)\n        \u03bc = mean(returns)\n        \u03c3 = std(returns; corrected=false)\n        return (\u03bc - \u03c3*pdf(Normal(), q)/\u03b1) * 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(), \u03b1)\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        \u03d5 = pdf(Normal(), g)\n        EG2 = -1/\u03b1*\u03d5 * (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        \u03bc = mean(returns)\n        \u03c3 = std(returns; corrected=false)\n        return (\u03bc + \u03c3*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": "function(a::Vector{Float64}, b::Vector{Float64}, c::Vector{Float64},\n         d::Vector{Float64}, soln::Vector{Float64})\n    # Setting initial elements\n    c[0] = c[0] / b[0]\n    d[0] = d[0] / b[0]\n\n    for i = 1:n\n        # Scale factor is for c and d\n        scale = 1 / (b[i] - c[i-1]*a[i])\n        c[i] = c[i] * scale\n        d[i] = (d[i] - a[i] * d[i-1]) * scale\n    end\n\n    # Set the last solution for back-substitution\n    soln[n-1] = d[n-1]\n\n    # Back-substitution\n    for i = n-2:0\n        soln[i] = d[i] - c[i] * soln[i+1]\n    end\n    \nend\n\n", "meta": {"hexsha": "2fc151274bfae9bd914f48739af7d94ea4e40dea", "size": 553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/matrix_methods/thomas/code/julia/thomas.jl", "max_stars_repo_name": "chrisb2244/algorithm-archive", "max_stars_repo_head_hexsha": "a30a088dc57f73c24724e9adcf45131c34ec2829", "max_stars_repo_licenses": ["MIT"], "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/matrix_methods/thomas/code/julia/thomas.jl", "max_issues_repo_name": "chrisb2244/algorithm-archive", "max_issues_repo_head_hexsha": "a30a088dc57f73c24724e9adcf45131c34ec2829", "max_issues_repo_licenses": ["MIT"], "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/matrix_methods/thomas/code/julia/thomas.jl", "max_forks_repo_name": "chrisb2244/algorithm-archive", "max_forks_repo_head_hexsha": "a30a088dc57f73c24724e9adcf45131c34ec2829", "max_forks_repo_licenses": ["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.0416666667, "max_line_length": 68, "alphanum_fraction": 0.4900542495, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172659321808, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7988228896987358}}
{"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# title: 1281. Subtract the Product and Sum of Digits of an Integer\n# id: problem1281\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/description/>\n# hidden: true\n# ---\n# \n# Given an integer number `n`, return the difference between the product of its\n# digits and the sum of its digits.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 234\n#     Output: 15 \n#     Explanation: \n#     Product of digits = 2 * 3 * 4 = 24 \n#     Sum of digits = 2 + 3 + 4 = 9 \n#     Result = 24 - 9 = 15\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 4421\n#     Output: 21\n#     Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 \n#     Sum of digits = 4 + 4 + 2 + 1 = 11 \n#     Result = 32 - 11 = 21\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": "1772ed7d1152eb82406fdad8b5c1a0575fccbe77", "size": 974, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1281.subtract-the-product-and-sum-of-digits-of-an-integer.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/1281.subtract-the-product-and-sum-of-digits-of-an-integer.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/1281.subtract-the-product-and-sum-of-digits-of-an-integer.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.7307692308, "max_line_length": 105, "alphanum_fraction": 0.545174538, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.7988084920070139}}
{"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": "using Test\nusing BenchmarkTools\nusing LinearAlgebra\ninclude(\"../src/Library.jl\")\n\n# Quadratic basis\n@testset \"quadratic\" begin\n    A = [1 2 3;4 5 6;7 8 10]\n    B = quadratic(A,3,3)\n    @test cond(A) < 1e6\n    @test cond(B) < 1e6\nend\n\n# Cubic basis\n@testset \"cubic\" begin\n    A = [1 2;3 4]\n    B = cubic(A,2,2)\n    @test cond(B) <1e6\n\n    A = [1 2 3;4 5 6;7 8 10]\n    B = cubic(A,3,3)\n    @test cond(B) < 1e6\nend\n\n# Test for a small unit matrix\n@testset \"ones\" begin\n    A = ones(3,3)\n    o = PolynomialBasis()\n    B = basis(A,o)\n    @test cond(B) == Inf\nend\n\n# Test for an identity matrix\n@testset \"identity\" begin\n    A = [1 0 0;0 1 0;0 0 1]\n    o = PolynomialBasis()\n    B = basis(A,o)\n    @test cond(B) < 1e6\nend\n\n# Condition number of a non square matrix\n@testset \"non square matrix\" begin\n    A = [1 0 0 0;0 1 0 0;0 0 0 1]\n    o = PolynomialBasis()\n    B = basis(A,o)\n    @test cond(B) < 1e6\nend\n\n# Condition number of random non square matrix\n@testset \"random non square matrix\" begin\n    A = 1.0 .+ randn(3,2)\n    o = PolynomialBasis()\n    B = basis(A,o)\n    @test cond(B) < 1e6\nend\n\n@testset \"basis 2 -  correctness\" begin\n    A = [1 2;3 4]\n    o = PolynomialBasis()\n    B = basis(A,o)\n    @test B[1,:] == [1,1]\n    @test B[2,:] == [1,2]\n    @test B[3,:] == [3,4]\nend\n\n@testset \"basis 3 - correctness\" begin\n    A = [1 2 3;4 5 6;7 8 10]\n    o = PolynomialBasis()\n    B = basis(A,o)\n    @test size(B,1) == 1 + 3 + 3*2 + 3*3\n    @test size(B,2) == 3\n    @test B[1,:] == [1,1,1]\n    @test B[2,:] == [1,2,3]\n    @test B[3,:] == [4,5,6]\n    @test B[end,:] == [343,512,1000]\nend\n\n@testset \"trig\" begin\n    A = [1 2;3 4]\n    B = trig(A,2,2)\n    B[1,:] \u2248 [sin(1),sin(2)]\n    B[2,:] \u2248 [sin(3),sin(4)]\n    B[3,:] \u2248 [cos(1),cos(2)]\n    B[4,:] \u2248 [cos(3),cos(4)]\nend\n\n\n@testset \"trig\" begin\n    A = [1 2 3; 4 5 6; 7 8 9]\n    o = TrigBasis()\n    B = basis(A,o)\n    @test size(B,1) == 9\n    @test size(B,2) == 3\n    @test cond(B) < 1e6\nend\n\n\n@testset \"PolyTrig basis\" begin\n    A = [1 2 3; 4 5 6; 7 8 9]\n    o = PolyTrigBasis()\n    B = basis(A,o)\n    @test cond(B) < 1e6\nend\n", "meta": {"hexsha": "19234e3626a3bf7873333106e8e52d5605331592", "size": 2068, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Library.jl", "max_stars_repo_name": "dynamic-queries/SINDY.jl", "max_stars_repo_head_hexsha": "cfa09ad191aed59ca872eacf6a2a96c95502a333", "max_stars_repo_licenses": ["MIT"], "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/Library.jl", "max_issues_repo_name": "dynamic-queries/SINDY.jl", "max_issues_repo_head_hexsha": "cfa09ad191aed59ca872eacf6a2a96c95502a333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-30T09:34:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T00:04:27.000Z", "max_forks_repo_path": "test/Library.jl", "max_forks_repo_name": "dynamic-queries/SINDY.jl", "max_forks_repo_head_hexsha": "cfa09ad191aed59ca872eacf6a2a96c95502a333", "max_forks_repo_licenses": ["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.8846153846, "max_line_length": 46, "alphanum_fraction": 0.5304642166, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485394, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7987192840547755}}
{"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\u2080   = 0.5*randn(rg, 2)\n    P\u2080   = 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\u2080, P\u2080))\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\u2080, P\u2080\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": "using Test\n\ninclude(\"../scripts/JuliaDSP.jl\")\nusing .JuliaDSP\n\n\n@testset \"Convolution\" begin\n    a1 = [1, 5, 0, 3]\n    a2 = [5, -3, -2, 5]\n    a3 = [100, 200]\n\n    @testset \"Arrays of length 1\" begin\n        @test JuliaDSP.convolve([1], [1]) == reshape([1], 1, 1)\n        @test JuliaDSP.convolve([100], [13]) == reshape([1300], 1, 1)\n        @test JuliaDSP.convolve([90], [100]) == reshape([9000], 1, 1)\n    end\n    \n    @testset \"Commutative property\" begin\n        @test JuliaDSP.convolve(a1, a2) == [5 22 -17 10 16 -6 15]\n        @test JuliaDSP.convolve(a2, a1) == [5 22 -17 10 16 -6 15]        \n    end\n\n    @testset \"Arrays are different sizes\" begin\n        @test JuliaDSP.convolve([1, 8, 6], [78]) == [78 624 468]\n        @test JuliaDSP.convolve([1, 2], [1, 2, 3]) == [1 4 7 6]\n        @test JuliaDSP.convolve(a1, a3) == [100  700 1000 300 600]\n    end\nend\n\n\n@testset \"Matrix multiplication\" begin\n    m1 = [1 2 3; 4 5 6]\n    m2 = [7 8; 9 10; 11 12]\n    m3 = [11 12; 4 5]\n    m4 = [12 13; 1000 1000]\n\n    @testset \"0 case\" begin\n        @test JuliaDSP.matrixMultiply([], []) == reshape([], 0, 0)\n        @test JuliaDSP.matrixMultiply([88], []) == reshape([], 0, 0)\n        @test JuliaDSP.matrixMultiply([], [4]) == reshape([], 0, 0)\n    end\n\n    @testset \"1 case\" begin\n        @test JuliaDSP.matrixMultiply([1], [3]) == reshape([3], 1, 1)\n        @test JuliaDSP.matrixMultiply([45], [3]) == reshape([135], 1, 1)\n        @test JuliaDSP.matrixMultiply([100], [100]) == reshape([10000], 1, 1)\n\n    end\n\n    @testset \"Matrices are both square and the same size\" begin\n        @test JuliaDSP.matrixMultiply(m3, m4) == [12132 12143; 5048 5052]\n    end\n\n    @testset \"Matrices are different sizes\" begin\n        @test JuliaDSP.matrixMultiply(m1, m2) == [58 64; 139 154]\n    end\nend\n", "meta": {"hexsha": "9aa8049827b5ec61b68c72ccbe0865221b950132", "size": 1783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/unit_tests.jl", "max_stars_repo_name": "leeway64/JuliaDSP", "max_stars_repo_head_hexsha": "315aaf7f4df9e7da37ccafe139f2146e0d8eb455", "max_stars_repo_licenses": ["MIT"], "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/unit_tests.jl", "max_issues_repo_name": "leeway64/JuliaDSP", "max_issues_repo_head_hexsha": "315aaf7f4df9e7da37ccafe139f2146e0d8eb455", "max_issues_repo_licenses": ["MIT"], "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/unit_tests.jl", "max_forks_repo_name": "leeway64/JuliaDSP", "max_forks_repo_head_hexsha": "315aaf7f4df9e7da37ccafe139f2146e0d8eb455", "max_forks_repo_licenses": ["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.7413793103, "max_line_length": 77, "alphanum_fraction": 0.5625350533, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7987192727341091}}
{"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 \u00a31 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 \u00a310 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\u00a31 paid to play the game, so in the example given the player actually wins \u00a39.\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\u2264n\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 \u2208 [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": "using RDatasets, Distributions, Random, LinearAlgebra\nRandom.seed!(0)\n\nK = 3\ndf = dataset(\"cluster\", \"xclara\")\nn,_ = size(df)\ndataPoints = [convert(Array{Float64,1},df[i,:]) for i in 1:n]\nshuffle!(dataPoints)\n\nxMin,xMax = minimum(first.(dataPoints)),maximum(first.(dataPoints))\nyMin,yMax = minimum(last.(dataPoints)),maximum(last.(dataPoints))\n\nmeans = [[rand(Uniform(xMin,xMax)),rand(Uniform(yMin,yMax))]  for _ in 1:K]\nlabels = rand(1:K,n)\nprevMeans = -means\n\nwhile norm(prevMeans - means) > 0.001\n    prevMeans = means\n    labels = [argmin([norm(means[i]-x) for i in 1:K]) for x in dataPoints]\n    means = [sum(dataPoints[labels .== i])/sum(labels .==i) for i in 1:K]\nend\n\ncountResult = [sum(labels .== i) for i in 1:K]\nprintln(\"Counts of clusters (manual implementation): \", countResult)", "meta": {"hexsha": "626ced91212315759d3e6fa347528f61b7c75c26", "size": 791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/kMeansManual.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "lang/Julia/kMeansManual.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "lang/Julia/kMeansManual.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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.9583333333, "max_line_length": 75, "alphanum_fraction": 0.6877370417, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813476288299, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.798706681637882}}
{"text": "function exponential_fg!(\u2207f, x)\n\n    if !(\u2207f==nothing)\n        \u2207f[1] = -2.0 * (2.0 - x[1]) * exp((2.0 - x[1])^2)\n        \u2207f[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": "function ABCDQR_em1(y,u,nx::Int;max_iter::Int=100,tol::Float64=1e-6,txo::Bool=true)\r\n\t#=\r\n\testimate A, C, Q, R, m1, P1 using the EM algorithm\r\n\tand the subspace algorithm for the starting point\r\n\tfor model\r\n\t\r\n\tx_{t+1} = A*x_{t} + B*u_{t} + w_{t}\r\n\ty_{t}   = C*x_{t} + D*u_{t} + v_{t}\r\n\t\r\n\tcov(w_{t},v_{t}) = [Q 0;0 R]\r\n\tx1 -> N(m1,P1)\r\n\t\r\n\tjavier.cara@upm.es, 2017-01\r\n\t\r\n\tss=true : estationary algorithm\r\n\t\r\n\t=#\t\r\n\t\t\r\n\t# data as a matrix and by rows\r\n\ty,ny,nt = byrow(y)\r\n\tu,nu,aux = byrow(u)\r\n\t\r\n\t# starting values from the ssi algorithm\r\n\ti = nx+1\r\n\tAi,Ci,Qi,Ri,Si = ACQRS_sub(y,nx,i)\r\n\tBi = zeros(nx,nu)\r\n\tDi = zeros(ny,nu)\t\r\n\t\r\n\t# x11 = C^{-1}(y_1 - v_1)\r\n\tm1i = Ci\\y[:,1:1]\r\n\tP1i = zeros(nx,nx)\r\n\r\n\tA,B,C,D,Q,R,m1,P1,loglikv,aic = ABCDQR_em(y,u,Ai,Bi,Ci,Di,Qi,Ri,m1i,P1i,max_iter,tol,txo)\r\n\t\r\n\t# output\r\n\treturn ABCDQR(A,B,C,D,Q,R,m1,P1,loglikv[end],aic)\r\n\r\nend\r\n\r\n", "meta": {"hexsha": "bf86eacb0fe8a7c9ce6de3e0a3593531bdca5121", "size": 872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ABCDQR_em1.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_em1.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_em1.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": 21.8, "max_line_length": 91, "alphanum_fraction": 0.5837155963, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.798706669889771}}
{"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\u00b2f_exact = 2(2x.^2 .- 1).*exp.(-x.^2);\n\njulia> d\u00b2f_approx = laplacian(length(x), step(x)) * exp.(-x.^2);\n\njulia> isapprox(d\u00b2f_exact, d\u00b2f_approx, atol = 1e-10)\ntrue\n```\n\"\"\"\nfunction laplacian(n, h)\n  \u0394 = zeros(n, n)\n  \u0394[diagind(\u0394, 0)] .= -1/3*\u03c0^2 / h^2\n  for i=2:n\n    @inbounds \u0394[diagind(\u0394, i-1)] = \n      \u0394[diagind(\u0394, 1-i)] .= 2*(-1)^i / (i-1)^2 / h^2\n  end\n  return \u0394\nend\nlaplacian(x::AbstractRange) = laplacian(length(x), step(x))\n\nfunction FGH(x::AbstractRange)\n  N, \u0394x = 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 \u225d i - j\n    K[diagind(K, d)] = K[diagind(K, -d)] .= \n    -2/N*(2\u03c0/N)^2 / \u0394x^2 * sum(l -> cos(2\u03c0*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  \u2207 = zeros(n, n)\n  \u2207[diagind(\u2207, 0)] .= 0\n  for i = 2:n\n      @inbounds \u2207[diagind(\u2207, i - 1)] .= (-1)^i / (i - 1) / dx\n      @inbounds \u2207[diagind(\u2207, 1 - i)] .= (-1)^(i - 1) / (i - 1) / dx\n  end\n  return \u2207\nend\n\nfunction \u2202r(f, x, r = exp.(x), D = sincdiff(x) - I, r\u2098\u1d62\u2099 = 5e-5)\n  df = D * (f .* r)\n  @. df /= r^2\n  extrapolate_left!(df, r, r\u2098\u1d62\u2099)\n  return df\nend\n\n#=\n \u03c1 = similar(r)\n\u2207\u03c1 = similar(r)\n\n@. \u03c1 = (2/27*r^2 - 2/3*r + 1)^2 * exp(-2/3*r) / 27\u03c0\n@. \u2207\u03c1 = -(8*r^4 - 192*r^3 + 1512*r^2 - 4536r + 4374)*exp(-2/3*r) / 59049\u03c0\n\nnorm(\u2202r(\u03c1, x) .- \u2207\u03c1)\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 = \u212f.^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\u00e8 Giordano.\n\nfunction _lsf_rotate{T<:AbstractFloat}(\u0394::T, vsini::T, \u025b::T)\n    n_2 = floor(ceil(2*vsini/\u0394)/2)\n    vel = collect(-n_2:n_2)*\u0394\n    e1 = 2*(1.0 - \u025b)\n    e2 = pi*\u025b/2.0\n    e3 = pi*(1.0 - \u025b/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(\u0394::Real, v::Real, \u025b::Real=0.6) =\n    _lsf_rotate(promote(float(\u0394), float(v), float(\u025b))...)\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 \u2208 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": "using OptionsMod\n\ndispflags = 0\n# dispflags = Optim.FINAL | Optim.ITER #| Optim.LINESEARCH | Optim.BRACKET | Optim.BISECT\nops = @options display=dispflags\n\ngtol = 1e-5\n\n# Quadratic objective function\nfunction quadratic(g, x, A, b)\n    calc_grad = !(g === nothing)\n    v = x'*A*x/2 + b'*x\n    if calc_grad\n        A_mul_B(g, A, x)\n        for i = 1:length(g)\n            g[i] += b[i]\n        end\n    end\n    return v[1]\nend\n\n\n# Matlab objective function in objfun.m\n# Minimum value is 0, which is tricky\nfunction mobjfun(g, x)\n    calc_grad = !(g === nothing)\n    x1 = x[1]\n    x2 = x[2]\n    ex1 = exp(x1)\n    v = ex1*(4x1^2 + 2x2^2 + 4x1*x2 + 2x2 + 1)\n    if calc_grad\n        g[1] = v + ex1*(8x1 + 4x2)\n        g[2] = ex1*(4x2 + 4x1 + 2)\n    end\n    return v\nend\n\n# driver1 problem in CG_DESCENT\nfunction driver1{T}(g, x::Array{T})\n    calc_grad = !(g === nothing)\n    f = zero(T)\n    n = length(x)\n    for i = 1:n\n        t = sqrt(convert(T, i))\n        ex = exp(x[i])\n        f += ex - t*x[i]\n        if calc_grad\n            g[i] = ex-t\n        end\n    end\n    return f\nend\n\n# Quadratic\nN = 8\nA = randn(N,N)\nA = A'*A\nb = randn(N)\nx0 = randn(N)\nfunc = (g, x) -> quadratic(g, x, A, b)\nx, fval, fcount, converged = cgdescent(func, x0, ops)\n@assert converged\n@assert all(abs(A*x + b) .< gtol)\n\nl = fill(-2.0, N)\nu = fill(2.0, N)\nx0 = rand(N)-0.5\nx, fval, fcount, converged = fminbox(func, x0, l, u, ops)\n@assert converged\n\n# Matlab objective function\nx0 = Float64[-1,1]\ng = Array(Float64, 2)\nmobjfun(g, x0)\nfun = x->mobjfun(nothing, x)\nd = Calculus.finite_difference(fun, x0)\n@assert all(abs(d-g) .< 1e-8)\nfunc = (g, x) -> mobjfun(g, x)\nx, fval, fcount, converged = cgdescent(func, x0, ops)\n@assert converged\n\n# cgdescent driver1\nn = 100\nx0 = ones(n)\nfunc = (g,x) -> driver1(g, x)\nx, fval, fcount, converged = cgdescent(func, x0, ops)\n@assert converged\n\n# Check nnls\nA = randn(50,30)\nb = randn(size(A, 1))\nxnn, fval, fcount, converged = nnls(A, b)\n@assert converged\n", "meta": {"hexsha": "e94c5c59c1f97fec10073a0a627e97a1bf3af245", "size": 1966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cgdescent.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/cgdescent.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/cgdescent.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": 20.914893617, "max_line_length": 89, "alphanum_fraction": 0.5808748728, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.798635706325861}}
{"text": "#Pkg.add(\"Plots\")\nusing Plots\n\nx = -3:0.1:3\nf(x) = x^2\n\ny = f.(x)\n\ngr()\n\nplot(x, y, label=\"linea\")  \nscatter!(x, y, label=\"puntos\") \n\nplotlyjs()\n\nplot(x, y, label=\"line\")  \nscatter!(x, y, label=\"points\") \n\nglobaltemperatures = [14.4, 14.5, 14.8, 15.2, 15.5, 15.8]\nnumpirates = [45000, 20000, 15000, 5000, 400, 17]\n\n# Primero plotteamos los datos\nplot(numpirates, globaltemperatures, legend=false)\nscatter!(numpirates, globaltemperatures, legend=false)\n\n# Agregamos T\u00edtulos y etiquetas/labels.\nxlabel!(\"N\u00famero de piratas [Apr\u00f3x.]\")\nylabel!(\"Temperatura Global (C)\")\ntitle!(\"Influencia de poblaci\u00f3n de piratas en calentamiento global\")\n\n# Primero graficamos datos\nplot(numpirates, globaltemperatures, legend=false)\nscatter!(numpirates, globaltemperatures, legend=false)\n\n# Este comando invierte el eje x para que podamos ver los cambios hacia adelante en el tiempo, de 1860 a 2000\nxflip!()\n\n# Add titles and labels\nxlabel!(\"Number of Pirates [Approximate]\")\nylabel!(\"Global Temperature (C)\")\ntitle!(\"Influence of pirate population on global warming\")\n\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", "meta": {"hexsha": "a9dfffe4390422f24a19945b0c62bf0cf7eda6f3", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "es-es/intro-to-julia-ES/plutos/8. Graficas.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/8. Graficas.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/8. Graficas.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": 23.38, "max_line_length": 109, "alphanum_fraction": 0.7057313944, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8740772450055544, "lm_q1q2_score": 0.7986238666300124}}
{"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    \u03bb::AbstractVector{T}\n    proj::Projection{T}\n\n    LLE{T}(k::Int, \u03bb::AbstractVector{T}, proj::Projection{T})  where T = new(k, \u03bb, proj)\nend\n\n## properties\noutdim(R::LLE) = size(R.proj, 1)\neigvals(R::LLE) = R.\u03bb\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        \u03bb, V = decompose(M, maxoutdim)\n    else\n        \u03bb, V = specDecompose(M, tol, maxoutdim, use_naive)\n    end\n    return LLE{T}(k, \u03bb, 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 (\u03b8,\u03d5,r)\n \u03b8, \u03d5 are in radians\n \u03d5 is the latitude, i.e., the angle from the equator.\n\"\"\"\nfunction xyz2\u03b8\u03d5r(x)\n  r = sqrt(x[1]^2 + x[2]^2 + x[3]^2)\n  \u03b8 = atan(x[2], x[1])\n  \u03d5 = asin(x[3]/r)\n  VectorValue(\u03b8,\u03d5,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) \u21a6 (\u03b8,\u03d5)\n\"\"\"\nfunction xyz2\u03b8\u03d5(x)\n  \u03b8 = atan(x[2], x[1])\n  \u03d5 = asin(x[3])\n  VectorValue(\u03b8,\u03d5)\nend\n\n\"\"\"\n  Map point on the parametric space of the unit sphere to the ambient space\n  (\u03b8,\u03d5) \u21a6 (x,y,z)\n\"\"\"\nfunction \u03b8\u03d52xyz(\u03b8\u03d5)\n  \u03b8,\u03d5 = \u03b8\u03d5\n  x = cos(\u03b8)*cos(\u03d5)\n  y = sin(\u03b8)*cos(\u03d5)\n  z = sin(\u03d5)\n  VectorValue(x,y,z)\nend\n\n\n\"\"\"\nMatrix transformation from spherical vector field to Cartesian vector field.\n  \u03b8\u2208(0,2\u03c0)\n  \u03d5\u2208(-\u03c0/2,\u03c0/2)\n  r=constant for the sphere\n\"\"\"\nfunction spherical_to_cartesian_matrix(\u03b8\u03d5r)\n  \u03b8,\u03d5,r = \u03b8\u03d5r\n  TensorValue(-sin(\u03b8)       , cos(\u03b8)       ,      0,\n              -sin(\u03d5)*cos(\u03b8),-sin(\u03d5)*sin(\u03b8), cos(\u03d5),\n               cos(\u03d5)*cos(\u03b8), cos(\u03d5)*sin(\u03b8), sin(\u03d5))\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\u03c6 = MathConstants.\u03c6\nn=(c-a)/(10^-3*log(\u03c6))\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": "export ROC, auc\n\nstruct ROC{T <: Real} <: AbstractBinaryMetric\n  labels::BitVector\n  scores::Vector{T}\n  AUC::T\n  FPR::Vector{T}\n  TPR::Vector{T}\n  OP::Vector{T}\n  function ROC(labels,scores)\n    B = BinaryMetrics(labels, scores)\n    OP = op(B)\n    FPR = fpr(B, OP)\n    TPR = tpr(B, OP)\n    AUC = get_auc([0.0;FPR], [0.0;TPR])\n    new{eltype(FPR)}(B.labels, B.scores, AUC, FPR, TPR, OP)\n  end\nend\n\nfunction Base.show(io::IO, B::ROC) \n  println(io,\"Receiver Operating Characteristic (ROC) curve\")\n  AUC = round(auc(B),digits=2)\n  print(io,\"Samples:$(length(B)), P:$(positives(B)), N:$(negatives(B)), AUC:$(AUC)\")\nend\n\n\"\"\"\n  ROC(labels, scores)\n\nGenerates data for plotting a Receiver Operating Characteristic (ROC) curve.\n\n* `labels` must be a boolean array e.g. either containing `true`,`false` or `0`,`1`.\n* `scores` must be an array with the same length of `labels` containing the scores of the binary classifier.\n\nYou can generate a plot automatically using the following commands:\n```julia\nroc = ROC(labels, scores)\n\nusing Plots\nplot(roc)\n```\n\nThe Area Under Curve (AUC) FPR and TPR can be accessed by `auc(roc)`, `fpr(roc)` and `tpr(roc)` respectively.\n\n\"\"\"\nROC(B::BinaryMetrics) = ROC(B.labels, B.scores)\n\n\nauc(curve::ROC) = curve.AUC\nfpr(curve::ROC) = curve.FPR\ntpr(curve::ROC) = curve.TPR\nop(curve::ROC) = curve.OP\n\nfunction get_curve(curve::ROC)\n  return [0.0;curve.FPR], [0.0;curve.TPR]\nend\n", "meta": {"hexsha": "5b8ef3987e3d1d57c8f711468694b90a12a51672", "size": 1401, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/roc.jl", "max_stars_repo_name": "nantonel/ROC.jl", "max_stars_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/roc.jl", "max_issues_repo_name": "nantonel/ROC.jl", "max_issues_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/roc.jl", "max_forks_repo_name": "nantonel/ROC.jl", "max_forks_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_forks_repo_licenses": ["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.0178571429, "max_line_length": 109, "alphanum_fraction": 0.6709493219, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7984923644742201}}
{"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) .\u00f7 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": "import RowEchelon\nimport LinearAlgebra\n\n#=\nHomework 7\nSection 3.2\nProblems 9\n=#\n\nA = [1 -1 -3 0 ;\n     0 1 5 4 ;\n     -1 2 8 5;\n     3 -1 -2 3]\n\ndetA = LinearAlgebra.det(A)\n\nprintln(\"Original Matrix:\")\nprintln(A)\nprintln(\"Determinate:\")\nprintln(detA)\n", "meta": {"hexsha": "d50da5de2b24132d147d659b80a4876cc9905f4b", "size": 251, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW7_S3.2_P9.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": "HW7_S3.2_P9.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": "HW7_S3.2_P9.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": 11.9523809524, "max_line_length": 27, "alphanum_fraction": 0.6294820717, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7984822066057924}}
{"text": "# Utilities for tests.\n\nusing Distributions\nusing LinearAlgebra: norm\nusing Random\nusing Test: @test\n\n# Add noise on top of one factorisation WH\nfunction add_matrix_noise(;WH::Matrix{T},\n                        dist_E::Distribution=Uniform(0,1), \n                        rng::AbstractRNG=MersenneTwister(1234)) where T <: Real\n    max.(WH + rand(rng, dist_E, size(WH,1), size(WH, 2)), 0)\nend\n\n# Simulate one matrix factorisation V = W*H + E\nfunction get_one_simulated_V()\n    F, K, N, rng = 10, 5, 25, MersenneTwister(1234)\n    W, H = rand(rng, Uniform(0,1), F, K), rand(rng, Uniform(0,1), K, N)\n\n    add_matrix_noise(WH=W*H, dist_E=Uniform(0,0.1), rng=rng)\nend\n\n# Simulate different noises on top of one factorisation WH\nfunction get_many_simulated_V()\n    F, K, N = 10, 5, 25\n    rng = MersenneTwister(1234)\n    W, H = rand(rng, Uniform(0,1), F, K), rand(rng, Uniform(0,1), K, N)\n\n    #### simulate different factorisation\n    noise_Vs = Matrix{Float64}[] \n    noise_names = String[] \n\n    push!(noise_Vs, add_matrix_noise(WH=W*H, dist_E=Uniform(0,0.01), rng=rng))\n    push!(noise_names, \"uniform_small\")\n    push!(noise_Vs, add_matrix_noise(WH=W*H, dist_E=Uniform(0,0.2), rng=rng))\n    push!(noise_names, \"uniform_large\")\n    push!(noise_Vs, add_matrix_noise(WH=W*H, dist_E=Normal(0,0.01), rng=rng))\n    push!(noise_names, \"normal_small\")\n    push!(noise_Vs, add_matrix_noise(WH=W*H, dist_E=Normal(0,0.2), rng=rng))\n    push!(noise_names, \"normal_large\")\n    push!(noise_Vs, add_matrix_noise(WH=W*H, dist_E=Gamma(0.05,1), rng=rng))\n    push!(noise_names, \"gamma_small\")\n    push!(noise_Vs, add_matrix_noise(WH=W*H, dist_E=Gamma(0.05,4), rng=rng))\n    push!(noise_names, \"gamma_large\")\n\n    noise_Vs, noise_names\nend\n\n\n# Simulate V, W and H.\nfunction simulate_VWH(;F::Integer, \n                      N::Integer,\n                      K::Integer,\n                      dist_W::Distribution=Uniform(0,1), \n                      dist_H::Distribution=Uniform(0,1), \n                      dist_E::Distribution=Uniform(0,0.1), \n                      rng::AbstractRNG=MersenneTwister(1234))\n    W = rand(rng, dist_W, F, K)\n    H = rand(rng, dist_H, K, N)\n    E = rand(rng, dist_E, F, N)\n\n    W*H+E, W, H\nend\n", "meta": {"hexsha": "cb2f957a05b023c98a172f59a3f3b72bee32afba", "size": 2203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testutils.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": "test/testutils.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": "test/testutils.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": 34.421875, "max_line_length": 79, "alphanum_fraction": 0.6236949614, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.798459369537449}}
{"text": "using LinearAlgebra\n\nfunction swap_rows(i::T, nlinha::T) where {T<:Integer}\n    for n \u2208 (i+1):nlinha        # iterate over lines above to check if could be swap\n        if A[n,i] \u2260 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) \u2260 0.0 \"Must insert a non-singular matrix\"\n    else\n        @assert det(A[:,1:end-1]) \u2260 0.0 \"Must insert a non-singular matrix or a system matrix [A b]\"\n    end\n\n    for i \u2208 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 \u2208 axes(A, 1)                          # iterate each line for each pivot column, except pivot line\n            if j \u2260 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": "module test\nfunction sir_ode(du, u, p, t)  \n    #Infected per-Capita Rate\n    \u03b2 = p[1]\n    #Recover per-capita rate\n    \u03b3 = p[2]\n    \n    #Susceptible Individuals\n    S = u[1]\n    #Infected by Infected Individuals\n    I = u[2]\n   \n    du[1] = -\u03b2 * S * I\n    du[2] = \u03b2 * S * I - \u03b3 * I\n    du[3] = \u03b3 * I\nend\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\n\nusing DifferentialEquations\n\nfunction main()\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\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\nend", "meta": {"hexsha": "c2eb84bff3fd8ee09de1fed3eaa17f47efeda4e1", "size": 920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/typing/sir.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/typing/sir.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/typing/sir.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": 20.0, "max_line_length": 76, "alphanum_fraction": 0.6076086957, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7984591621993601}}
{"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 \u2208 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 \u2208 1:1000\r\n        for x \u2208 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 \u2208 1:1000, y \u2208 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 _ \u2208 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\u2081, v\u2081) = perpbisector(p,q)\r\n    (x\u2082, v\u2082) = perpbisector(p,r)\r\n    det([v\u2081 v\u2082]) == 0 && return [Inf, Inf]\r\n    M = [v\u2081 v\u2082]^-1\r\n    t\u2081 = (M * (x\u2082 - x\u2081))[1]\r\n    return x\u2081 + t\u2081*v\u2081\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 \u2208 q.neighbours\r\n        r \u2208 [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 \u2208 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 \u2208 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 \u2208 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) \u2208 [0,1000]\u00b2.\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 \u2208 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\u2081, v\u2081 = perpbisector(p.neighbours[n-1],p)\r\n            x\u2081, v\u2081 = Rational{Int64}.(x\u2081), Rational{Int64}.(v\u2081)\r\n            # Values of t\u2081 where the line x\u2081 + t\u2081v\u2081 intersects the borders\r\n            t\u2081vals = [-x\u2081[2]/v\u2081[2], (1000-x\u2081[1])/v\u2081[1], (1000-x\u2081[2])/v\u2081[2], -x\u2081[1]/v\u2081[1]]\r\n            t\u2081 = minimum(t\u2081vals[t\u2081vals .> 0])\r\n            push!(vertices,Tuple(x\u2081 + t\u2081*v\u2081))\r\n\r\n            x\u2082, v\u2082 = perpbisector(p,p.neighbours[2])\r\n            x\u2082, v\u2082 = Rational{Int64}.(x\u2082), Rational{Int64}.(v\u2082)\r\n            t\u2082vals = [-x\u2082[2]/v\u2082[2], (1000-x\u2082[1])/v\u2082[1], (1000-x\u2082[2])/v\u2082[2], -x\u2082[1]/v\u2082[1]]\r\n            t\u2082 = minimum(t\u2082vals[t\u2082vals .> 0])\r\n\r\n            t\u2081index = findfirst(==(t\u2081),t\u2081vals)\r\n            t\u2082index = findfirst(==(t\u2082),t\u2082vals)\r\n            indexdifference = mod(t\u2082index - t\u2081index,4)\r\n            corners = [(0,0), (1000,0), (1000,1000), (0,1000)]\r\n            for j \u2208 1:indexdifference\r\n                push!(vertices,corners[mod(t\u2081index+j, 1:4)])\r\n            end\r\n\r\n            push!(vertices,Tuple(x\u2082 + t\u2082*v\u2082))\r\n\r\n        else\r\n            startindex, endindex = 1, n\r\n        end\r\n\r\n        for j \u2208 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 \u2208 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, \u03c3::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 `\u03c3`.\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, \u03c3::Rational{Int64})\r\n\tif shape == :square\r\n\t\tcoords = [(x,y) for x \u2208 1:n, y \u2208 1:n]\r\n\telseif shape == :hexagonal\r\n\t\tcoords = hcat([(x,(6//7)*y) for x \u2208 1:n, y \u2208 1:2:n],\r\n\t\t\t[(x+1//2,(6//7)*y) for x \u2208 1:n, y \u2208 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 \u2208 coords[:]], [xy[2] for xy \u2208 coords[:]]\r\n\trandxs = xs .+ \u03c3 * round.(Int64, n * randn(n^2))//n\r\n\trandys = ys .+ \u03c3 * 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": "using Test\nimport Geometry\n\n@testset \"volume\" begin\n\n    solids = [\n        (Geometry.Cylinder(1, 2), pi),\n        (Geometry.Cone(1, [2]), 1.04720),\n        (Geometry.Cube(4), 64.0),\n        (Geometry.RectangularPrism(3, 5, 7), 105.0)\n    ]\n\n    for i in solids\n        @test round(Geometry.volume(i[1]), digits=5) === round(i[2], digits=5)\n    end\n\n    # @test_throws MethodError foo(x, y)\nend\n\n@testset \"lateralarea\" begin\n\n    solids = [\n        (Geometry.Cylinder(1, 2), 6.28319),\n        (Geometry.Cone(1, [2]), 4.44288),\n        (Geometry.Cube(4), 64.0),\n        (Geometry.RectangularPrism(3, 5, 7), 72)\n    ]\n\n    for i in solids\n        @test round(Geometry.lateralarea(i[1]), digits=5) === round(i[2], digits=5)\n    end\n\n    # @test_throws MethodError foo(x, y)\nend\n\n@testset \"surfacearea\" begin\n\n    solids = [\n        (Geometry.Cylinder(1, 2), 12.56637),\n        (Geometry.Cone(1, [2]), 7.58448),\n        (Geometry.Cube(4), 6*4^2),\n        (Geometry.RectangularPrism(3, 5, 7), 142.0)\n    ]\n\n    for i in solids\n        @test round(Geometry.surfacearea(i[1]), digits=5) === round(i[2], digits=5)\n    end\n\n    # @test_throws MethodError foo(x, y)\nend\n\n# @testset \"methods\" begin\n#     ms = [x.sig for x in Geometry.methods(Geometry.volume)]\n#     for i in ms\n#         println(i.parameters[2])\n#     end\n# end\n\n# @testset \"bar\" begin\n#     z = 4.\n#     @test bar(z) == 1.\n# end\n", "meta": {"hexsha": "78d1d183ed0f4d6c153e864d9cc11b521fed9f4e", "size": 1387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 22.0158730159, "max_line_length": 83, "alphanum_fraction": 0.5609228551, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7983575765569676}}
{"text": "ENV[\"GKSwstype\"]=\"100\" #src\n\n# ### Optimizing Julia code is often done at the expense of transparency\n\nusing Random, LinearAlgebra, BenchmarkTools\n\nfunction test(A, B, C)\n    C = C - A * B\n    return C\nend\n\nA = rand(1024, 256); B = rand(256, 1024); C = rand(1024, 1024)\n@btime test(A, B, C); #C, A and B are matrices. \n#md nothing # hide\n\n#md # --\n\nfunction test_opt(A, B, C)\n    BLAS.gemm!('N','N', -1., A, B, 1., C)\n    return C\nend\n@btime test_opt(A, B, C) # avoids taking two unnecessary copies of the matrix C.\n#md nothing # hide\n\n#md # --\n\nC = rand(1024, 1024)\nall(test(A, B, C) .== test_opt(A, B, C))\n\n#md # ---\n\n# ### Derivative computation with FFT\n\nusing FFTW\n\nxmin, xmax, nx = 0, 4\u03c0, 1024\nymin, ymax, ny = 0, 4\u03c0, 1024\n\nx = range(xmin, stop=xmax, length=nx+1)[1:end-1]\ny = range(ymin, stop=ymax, length=ny+1)[1:end-1]\n\nky  = 2\u03c0 ./ (ymax-ymin) .* [0:ny\u00f72-1;ny\u00f72-ny:-1]\nexky = exp.( 1im .* ky' .* x)\n\nfunction df_dy( f, exky )\n    ifft(exky .* fft(f, 2), 2)\nend\n\nf = sin.(x) .* cos.(y') # f is a 2d array created by broadcasting\n\n@btime df_dy(f, exky)\n#md nothing # hide\n\n#md # ---\n\n# ### Memory alignement, and inplace computation.\n\nf  = zeros(ComplexF64, (nx,ny)) \nf\u1d57 = zeros(ComplexF64, reverse(size(f)))\nf\u0302\u1d57 = zeros(ComplexF64, reverse(size(f)))\n\nf .= sin.(x) .* cos.(y')\n\nfft_plan = plan_fft(f\u1d57, 1, flags=FFTW.PATIENT)\n\nfunction df_dy!( f, f\u1d57, f\u0302\u1d57, exky )\n    transpose!(f\u1d57,f)\n    mul!(f\u0302\u1d57,  fft_plan, f\u1d57)\n    f\u0302\u1d57 .= f\u0302\u1d57 .* exky\n    ldiv!(f\u1d57, fft_plan, f\u0302\u1d57)\n    transpose!(f, f\u1d57)\nend\n\n@btime df_dy!(f, f\u1d57, f\u0302\u1d57, exky )\n#md nothing # hide\n\n#md # ---\n\n#md # # Why use Julia language!\n#md #\n#md # - **You develop in the same language in which you optimize.**\n#md # - Packaging system is very efficient (3173 registered packages)\n#md # - PyPi (198,360 projects) R (14993 packages)\n#md # - It is very easy to create a package (easier than R and Python)\n#md # - It is very easy to use GPU device.\n#md # - Nice interface for Linear Algebra and Differential Equations\n#md # - Easy access to BLAS and LAPACK\n#md # - Julia talks to all major Languages - mostly without overhead!\n\n#md # ---\n\n#md # # What's bad\n#md #\n#md # - It is still hard to build shared library or executable from Julia code.\n#md # - Compilation times can be unbearable.\n#md # - Plotting takes time (20 seconds for the first plot)\n#md # - OpenMP is better than the Julia multithreading library but it is progressing.\n#md # - There is a MPI and PETSc package but they are not very active. \n#md # - For parallelization, The Julia community seems to prefer the ditributed processing approach. \n#md # - Does not work well with vectorized code, you need to do a lot of inplace computation to avoid memory allocations and use explicit views to avoid copy.\n#md # - Julia website proclaims that it is faster than Fortran but this is not true. But it is very close and it is progressing.\n#md \n#md # [What's Bad About Julia by Jeff Bezanson](https://www.youtube.com/watch?v=TPuJsgyu87U)\n\n#md # ---\n\n#md # ## So when should i use Julia?\n#md # \n#md # - Now! If you need performance and plan to write your own libraries.\n#md # - In ~1-2 Years if you want a smooth deploy.\n#md # - In ~3-5 Years if you want a 100% smooth experience.\n#md \n#md # ## Julia Munich Meetup \n#md # Every two months, poll for the next meeting that\n#md # will take place at Garching Campus : https://doodle.com/poll/z3ft2dytnaebyhh7.\n#md #\n#md # ## Python-Julia benchmarks by Thierry Dumont\n#md #\n#md # https://github.com/Thierry-Dumont/BenchmarksPythonJuliaAndCo/wiki\n#md \n#md # ---\n#md \n#md # # Julia is a language made for Science.\n#md #\n#md #  [Some State of the Art Packages](http://www.stochasticlifestyle.com/some-state-of-the-art-packages-in-julia-v1-0)\n#md #\n#md #  * JuliaDiffEq \u2013 Differential equation solving and analysis.\n#md #  * JuliaDiff \u2013 Differentiation tools.\n#md #  * JuliaGeometry \u2013 Computational Geometry.\n#md #  * JuliaGraphs \u2013 Graph Theory and Implementation.\n#md #  * JuliaIntervals - Rigorous numerics with interval arithmetic & applications.\n#md #  * JuliaMath \u2013 Mathematics made easy in Julia.\n#md #  * JuliaOpt \u2013 Optimization.\n#md #  * JuliaPolyhedra \u2013 Polyhedral computation.\n#md #  * JuliaSparse \u2013 Sparse matrix solvers.\n#md #  * JuliaStats \u2013 Statistics and Machine Learning.\n#md #  * JuliaPlots - powerful convenience for visualization.\n#md #  * JuliaGPU - GPU Computing for Julia.\n#md #  * FluxML - The Elegant Machine Learning Stack.\n#md #\n\n@test true #src\n", "meta": {"hexsha": "6e5f9e8d4d458f6559259fe365ac25cb889650ad", "size": 4423, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/06.Conclusions.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/06.Conclusions.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/06.Conclusions.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": 30.9300699301, "max_line_length": 158, "alphanum_fraction": 0.6746552114, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8824278741843883, "lm_q1q2_score": 0.7982888463004021}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend;\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.03\"\n\n# \u2554\u2550\u2561 fa68607e-22e5-11eb-0558-c9a4d9f77426\nfunction statPair(dist,n)\n    sample = rand(dist,n)\n    [mean(sample),var(sample)]\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.03\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u25501111d8c4-252c-11eb-3813-81de856f7fba\n# \u2560\u255011120d28-252c-11eb-1c1e-0dba64d8ae5c\n# \u255f\u2500475ff888-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": "using Symata, NumericalMethodsforEngineers\nusing Test\n\n@sym begin\n  ClearAll(xi, yi, Y, Ydot, Ydotdot, ytilde1, ytilde2, R)\n  xi = [0, 1//3, 2//3, 1]\n  yi = [0, a, b, 1]\n  Y(x_) := LagrangePolynomial(xi, yi)\n  #\n  # Can be re-formulated as Y(x) = F(x) + C1(a) * \u03a81(x) + C2(a) * \u03a82(x)\n  #\n  # F(x_) := (1/2)*(9x^3 - 9x^2 + 2x)\n  # C1(a_) := (27/2)*(a-b)\n  \u03a81(x_) := x^3 - x^2\n  # C2(a_) := -(9/2)*(2a-b)\n  \u03a82(x_) := x^2 - x\n  #\n  # Y(x_) := F(x) + C1(a)*\u03a81(x) + C2(a)*\u03a82(x)\n  #\n  R(x_) = Simplify(D(Y(x), x, 2) - 3*x - 4*Y(x))\n  SetJ(r, ToString(Simplify(R(x))))\nend\n\nprintln(\"\\n\\nExample 7.14: y'' = 3x + 4y, y(0)=0, y(1)=1\")\nprintln(\"Residual for Weighted Residual Method using 2 point Lagragian Polynomial\")\n@sym Println(\"\\nY(x): \", Expand(Y(x)), \"\\n\")\nprintln(\"( Example 7.14 gives: ytilde = 1/2*x^3*(27a-27b+9)-x^2*(45a-36b+9)+x*(18a-9b+2) )\")\n@sym Println(\"\\nR(x) = \", R(x), \"\\n\")\n\n@test r == \"-9 - 45a + 36b + 20x - 63b*x + 45a*x + 18*x^2 - 72b*x^2 + 90a*x^2 - 18x^3 - 54a*x^3 + 54b*x^3\"", "meta": {"hexsha": "38c9272348db813bfbff2a7ddeb46628add5dc76", "size": 993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/WRM/Ex.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/Ex.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/Ex.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": 33.1, "max_line_length": 106, "alphanum_fraction": 0.5266868077, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8333245911726381, "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 \u03b2) / (1 -0.5 \u03b2)(1 - \u03b2)\n# w[2] = -1/(1-\u03b2)\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 * \u03c0) - 100\n    t\u0332, t\u0304 = 0, (B + 100) / A\n    \u03b5 = 1e-6\n\n    t = (t\u0304 + t\u0332) / 2\n    while abs(g(t)) > \u03b5\n        if g(t) > 0\n            t\u0304 = t\n        else\n            t\u0332 = t\n        end\n        t = (t\u0304 + t\u0332) / 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": "using Gadfly\n\nfunction lossDemo()\n    qs = [.2, 1, 2]\n    loss(x, q) = abs(x).^q\n\n    x = -2:0.01:2\n\n    function lossPlot(q)\n        plot(x=x, y=loss(x, q), Geom.line, Theme(default_color=colorant\"black\", line_width=1px))\n    end\n\n    [lossPlot(q) for q in qs]\nend\n\nfunction hingeLossDemo(\u03b5)\n    hinge(x) = (abs(x)-\u03b5).*(abs(x).>=\u03b5)\n\n    x = -2:0.01:2\n    plot(x=x, y=hinge(x), Geom.line, Theme(default_color=colorant\"black\", line_width=1px))\nend\n\n", "meta": {"hexsha": "e692907ebed49e18aec93baddd713b3d9244f66d", "size": 448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BayesianStatistics/lossFunctionDemo.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/lossFunctionDemo.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/lossFunctionDemo.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": 19.4782608696, "max_line_length": 96, "alphanum_fraction": 0.59375, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7981808061986205}}
{"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\u2081 = atan2(G,F)\n    a\u2082 = atan2(H,E)\n    \u03b8 = (a\u2082 - a\u2081) / 2\n    \u03d5 = (a\u2082 + a\u2081) / 2\n    s = sign(sy)\n    U = SMatrix{2,2,Float64}(cos(\u03d5), sin(\u03d5), -s*sin(\u03d5), s*cos(\u03d5))\n    S = SMatrix{2,2,Float64}(sx, 0.0, 0.0, abs(sy))\n    V = SMatrix{2,2,Float64}(cos(\u03b8), -sin(\u03b8), sin(\u03b8), cos(\u03b8))\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": "# functions definition\n\nfunction continued_fraction(x, terms)\n    val = x\n    for i = 1:terms\n        if i==terms\n            val = 1/(1-val)\n        else\n            val = x/(1-val)\n        end\n    end\n    return val\n   end\n   \n   \nfunction continued_exp(x, terms)\n    val = 1\n    for i = 1:terms\n        val = exp(val*x)\n    end\n    return val\nend\n\n\n# continued fraction call section\n\nN = 200\nconv = 100\ndf = 0.01\ns = zeros(N, N)\npt = zeros(Complex{Float64},conv)\nfor x = 1:N , y = 1:N\n  dx = df * x - N * df/2\n  dy = df * y - N * df/2\n  for i = 1:conv\n    pt[i] = continued_fraction(dx+dy*im,i)\n  end\n  s[x,y] = length(Set(pt))\nend\n\n\nusing ImageView\nusing Images\nImageView.imshow(s)\n\n\n# continued exponential call section\n\nN = 2000\nconv = 100\ndf = 0.01\ns = zeros(N, N)\npt = zeros(Complex{Float64},conv)\nfor x = 1:N , y = 1:N\n  dx = df * x - N * df/2\n  dy = df * y - N * df/2\n  for i = 1:conv\n    pt[i] = continued_exp(dx+dy*im,i)\n  end\n  s[x,y] = length(Set(pt))\nend\n\n\nusing ImageView\nusing Images\nImageView.imshow(s)\n", "meta": {"hexsha": "6309db3151bf32e58496192e349bfaca6478d605", "size": 1021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/julia/continued_functions.jl", "max_stars_repo_name": "seyedalirezamanavi/Continued_functions", "max_stars_repo_head_hexsha": "8520dc81e68a0b734a4774b0fc6610051b887944", "max_stars_repo_licenses": ["MIT"], "max_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/continued_functions.jl", "max_issues_repo_name": "seyedalirezamanavi/Continued_functions", "max_issues_repo_head_hexsha": "8520dc81e68a0b734a4774b0fc6610051b887944", "max_issues_repo_licenses": ["MIT"], "max_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/continued_functions.jl", "max_forks_repo_name": "seyedalirezamanavi/Continued_functions", "max_forks_repo_head_hexsha": "8520dc81e68a0b734a4774b0fc6610051b887944", "max_forks_repo_licenses": ["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.2388059701, "max_line_length": 42, "alphanum_fraction": 0.5680705191, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7981807962696187}}
{"text": "# define macro for statically AD-ing through activation function\n#macro frule()\n\n# Define activation functions\n@inline \u21122(x::T) where T = T(2)*cosh(x)\n@inline \u2202log\u21122(x) = tanh(x)\n@inline log\u21122(x::T) where T<:Real =\n    (abs(x)<= T(12.0) ? log(cosh(x)) : abs(x) - log(2one(x)))\n@inline log\u21122(x::Complex{T}) where T<:Real =\n    log\u21122(real(x)) + log(cos(imag(x)) + im * tanh(real(x)) * sin(imag(x)))\n\n\n\n@inline \u2112(x) = one(x) + exp(x)\n@inline \u2202log\u2112(x) = one(x)/(one(x)+exp(-x))\n#const \u2202log\u2112 = NNlib.\u03c3\n#NNlib.\u03c3(x::Complex) = one(x)/(one(x)+exp(-x))\n@inline log\u2112(x) = log1p(exp(x))#log(one(x) + exp(x))\n#const log\u2112 = NNlib.softplus\n#NNlib.softplus(x::Complex) = log1p(exp(x))#log(one(x) + exp(x))\n\n@inline fwd_der(f::typeof(log\u2112)) = \u2202log\u2112\n@inline fwd_der(f::typeof(log\u2112), x) = \u2202log\u2112(x)\n\n@inline fwd_der(f::typeof(log\u21122)) = \u2202log\u2112\n@inline fwd_der(f::typeof(log\u21122), x) = \u2202log\u21122(x)\n\n@inline fwd_der(f::typeof(identity)) = identity\n@inline fwd_der(f::typeof(identity), x::T) where T = one(T)\n\nexport af_softplus, af_logcosh\n\"\"\"\n    af_softplus(x) = log( 1 + exp(x) )\n\nClassic softplus (https://en.wikipedia.org/wiki/Sigmoid_function) activation function.\n\"\"\"\nconst af_softplus = log\u2112\n\n# TODO use NNlib implementation\n\"\"\"\n  logcosh(x)\n\n  Return log(cosh(x)) which is computed in a (somewhat) numerically stable way.\n\"\"\"\nconst af_logcosh = log\u21122\n", "meta": {"hexsha": "b5f6dbc85049d8127ee657216de5d08f095c3a71", "size": 1333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Networks/activation.jl", "max_stars_repo_name": "PhilipVinc/NeuralQuantumBase.jl", "max_stars_repo_head_hexsha": "cdf6a244c94eeeaa5cbde9c99327380be9ba6242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2019-06-29T09:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T00:12:06.000Z", "max_issues_repo_path": "src/Networks/activation.jl", "max_issues_repo_name": "PhilipVinc/NeuralQuantumBase.jl", "max_issues_repo_head_hexsha": "cdf6a244c94eeeaa5cbde9c99327380be9ba6242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-28T14:13:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-06T17:45:54.000Z", "max_forks_repo_path": "src/Networks/activation.jl", "max_forks_repo_name": "PhilipVinc/NeuralQuantum.jl", "max_forks_repo_head_hexsha": "cdf6a244c94eeeaa5cbde9c99327380be9ba6242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-10-25T06:38:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T04:10:20.000Z", "avg_line_length": 28.9782608696, "max_line_length": 86, "alphanum_fraction": 0.6541635409, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7981570656163726}}
{"text": "let\n    n = mean_motion(R_EARTH + 500e3, use_degrees=false)\n    @test isapprox(n, 0.0011067836148773837, atol=1e-12)\n\n    n = mean_motion(R_EARTH + 500e3, use_degrees=true)\n    @test isapprox(n, 0.0634140299667068, atol=1e-12)\nend\n\nlet\n    a = semimajor_axis(0.0011067836148773837, use_degrees=false)\n    @test isapprox(a, R_EARTH + 500e3, atol=1e-6)\n\n    a = semimajor_axis(0.0634140299667068, use_degrees=true)\n    @test isapprox(a, R_EARTH + 500e3, atol=1e-6)\nend\n\nlet \n    T = orbit_period(R_EARTH + 500e3)\n    @test isapprox(T, 5676.977164028288, atol=1e-9)\nend\n\nlet\n    iss = sun_sync_inclination(R_EARTH + 574e3, 0.0, use_degrees=false)\n    @test isapprox(iss, 97.685*pi/180, atol=1.0e-3)\n\n    iss = sun_sync_inclination(R_EARTH + 574e3, 0.0, use_degrees=true)\n    @test isapprox(iss, 97.685, atol=1.0e-3)\nend\n\nlet\n    # 0 \n    M = anomaly_eccentric_to_mean(0.0, 0.0, use_degrees=false)\n    @test M == 0\n\n    M = anomaly_eccentric_to_mean(0.0, 0.0, use_degrees=true)\n    @test M == 0\n\n    # 180\n    M = anomaly_eccentric_to_mean(pi/2, 0.1, use_degrees=false)\n    @test isapprox(M, 1.4707, atol=1e-3)\n\n    M = anomaly_eccentric_to_mean(90.0, 0.1, use_degrees=true)\n    @test isapprox(M, 84.270, atol=1e-3)\n\n    # 180\n    M = anomaly_eccentric_to_mean(pi, 0.0, use_degrees=false)\n    @test isapprox(M, pi, atol=1e-12)\n\n    M = anomaly_eccentric_to_mean(180.0, 0.0, use_degrees=true)\n    @test M == 180.0\nend\n\nlet\n    # 0 \n    E = anomaly_mean_to_eccentric(0.0, 0.0, use_degrees=false)\n    @test E == 0\n\n    E = anomaly_mean_to_eccentric(0.0, 0.0, use_degrees=true)\n    @test E == 0\n\n    # 180\n    E = anomaly_mean_to_eccentric(1.4707, 0.1, use_degrees=false)\n    @test isapprox(E, pi/2, atol=1e-3)\n\n    E = anomaly_mean_to_eccentric(84.270, 0.1, use_degrees=true)\n    @test isapprox(E, 90.0, atol=1e-3)\n\n    # 180\n    E = anomaly_mean_to_eccentric(pi, 0.0, use_degrees=false)\n    @test isapprox(E, pi, atol=1e-12)\n\n    E = anomaly_mean_to_eccentric(180.0, 0.0, use_degrees=true)\n    @test E == 180.0\n\n    # Large Eccentricities\n    E = anomaly_mean_to_eccentric(180.0, 0.9, use_degrees=true)\n    @test E == 180.0\n\n    # Max Iteration exit on hyperbolic trajectory\n    # @test_throws ErrorException anomaly_mean_to_eccentric(pi, 2.0)\nend\n\nlet\n    oe  = [R_EARTH + 500e3, 0, 90.0, 0, 0, 0]\n    eci = sOSCtoCART(oe, use_degrees=true)\n\n    tol = 1e-6\n    @test isapprox(eci[1], R_EARTH + 500e3, atol=tol)\n    @test isapprox(eci[2], 0.0, atol=tol)\n    @test isapprox(eci[3], 0.0, atol=tol)\n    @test isapprox(eci[4], 0.0, atol=tol)\n    @test isapprox(eci[5], 0.0, atol=tol)\n    @test isapprox(eci[6], sqrt(GM_EARTH/(R_EARTH + 500e3)), atol=tol)\nend\n\nlet \n    # Using radians\n    oe   = [R_EARTH + 500e3, 0, pi/2.0, 0, 0, 0]\n    eci  = sOSCtoCART(oe, use_degrees=false)\n    eci2 = sOSCtoCART(oe, use_degrees=false)\n\n    tol = 1e-6\n    @test isapprox(eci[1], eci2[1], atol=tol)\n    @test isapprox(eci[2], eci2[2], atol=tol)\n    @test isapprox(eci[3], eci2[3], atol=tol)\n    @test isapprox(eci[4], eci2[4], atol=tol)\n    @test isapprox(eci[5], eci2[5], atol=tol)\n    @test isapprox(eci[6], eci2[6], atol=tol)  \n\n    # Using degrees\n    oe   = [R_EARTH + 500e3, 0, 90.0, 0, 0, 0]\n    eci  = sOSCtoCART(oe, use_degrees=true)\n    eci2 = sOSCtoCART(oe, use_degrees=true)\n\n    tol = 1e-6\n    @test isapprox(eci[1], eci2[1], atol=tol)\n    @test isapprox(eci[2], eci2[2], atol=tol)\n    @test isapprox(eci[3], eci2[3], atol=tol)\n    @test isapprox(eci[4], eci2[4], atol=tol)\n    @test isapprox(eci[5], eci2[5], atol=tol)\n    @test isapprox(eci[6], eci2[6], atol=tol)\nend\n\nlet \n    eci   = [R_EARTH + 500e3, 100e3, 575e3, 0, 0, 7300]\n    eci2  = sOSCtoCART(sCARTtoOSC(eci))\n\n    tol = 1e-6\n    @test isapprox(eci[1], eci2[1], atol=tol)\n    @test isapprox(eci[2], eci2[2], atol=tol)\n    @test isapprox(eci[3], eci2[3], atol=tol)\n    @test isapprox(eci[4], eci2[4], atol=tol)\n    @test isapprox(eci[5], eci2[5], atol=tol)\n    @test isapprox(eci[6], eci2[6], atol=tol)\n\n    # Equatorial circulator\n    a   = R_EARTH + 1000e3\n    e   = 0.0\n    eci = [a, 0, 0, 0, 0, sqrt(GM_EARTH/a)]\n    oe  = sCARTtoOSC(eci, use_degrees=true)\n\n    tol = 1e-6\n    @test isapprox(oe[1], a,     atol=tol)\n    @test isapprox(oe[2], e,     atol=tol)\n    @test isapprox(oe[3], 90.0,  atol=tol)\nend\n\nlet\n    # Test near-circular conversions\n    a   = R_EARTH + 500e3\n    eci = [a, 0.0, 0.0, 0.0, 0.0, sqrt(GM_EARTH/a)]\n    oe  = sCARTtoOSC(eci, use_degrees=true)\n\n    tol = 1e-6\n    @test isapprox(oe[1], a, atol=tol)\n    @test isapprox(oe[2], 0.0, atol=tol)\n    @test isapprox(oe[3], 90.0, atol=tol)\n    @test isapprox(oe[4], 0.0, atol=tol)\n    @test isapprox(oe[5], 0.0, atol=tol)\n    @test isapprox(oe[6], 0.0, atol=tol)\nend", "meta": {"hexsha": "e359d345036d142e7b0146dfd511caa2d265e54e", "size": 4689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_astrodynamics.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": "test/test_astrodynamics.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": "test/test_astrodynamics.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": 29.1242236025, "max_line_length": 71, "alphanum_fraction": 0.6291320111, "num_tokens": 2001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659995, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7981570547351927}}
{"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    \u03b1 = dot( r, z ) / dot( p, L_x )\n    #\n    x[:] = x[:] + \u03b1 * p[:]  # FIXME use x[:] to force x to be copied, not referenced\n    r[:] = r[:] - \u03b1 * 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    \u03b2 = dot( z, r - r_old ) / dot( z_old, r_old )\n    p = z[:] + \u03b2 * 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\u03c6 = MathConstants.\u03c6\nfunction golden_section_search(f, a, b, n)\n    \u03c1 = \u03c6-1\n    d = \u03c1 * b + (1 - \u03c1)*a\n    yd = f(d)\n    for i = 1 : n-1\n        c = \u03c1*a + (1 - \u03c1)*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(\u03c6))\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, \u03bb1, \u03bb2, S = I; \u0394Fmin = 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* \u03bb1:   Influences the sparsity of the estimated outliers `x`. As a reasonable heuristic is \u03bb1 = 3\u03c3, where \u03c3 is the standard deviation of the noise. \n* \u03bb2:   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* \u0394Fmin:    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, \u03bb1, \u03bb2, S = I(length(y)); \u0394Fmin = 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    \u03bb2DDn = \u03bb2 .* Dn' * Dn\n    \n    # Objective function\n    F(f, x) = 0.5norm2(S * y .- S * f .- x)^2 + 0.5\u03bb1 * norm1(x) + .5\u03bb2 *  norm2(Dn * f)^2\n\n    # Iterate\n    iter = 1\n    fRes = similar(y)\n    Fold = \u0394F = Inf\n    while \u0394F > \u0394Fmin && iter <= maxiter\n        A = Diagonal(\u03bb1 ./ (abs.(xRes) .+ \u03bb1))\n        # B = Matrix(S' * A * S .+ \u03bb2 .* Dn' * Dn) # faster for low N but more Memory gets allocated\n        B = BandedMatrix(S' * A * S .+ \u03bb2DDn) # less Memory but apparently slower\n        fRes = inv(B) * S' * A * S * y\n        xRes = abs.(xRes) .* (S * (y .- fRes)) ./ (abs.(xRes) .+ \u03bb1)\n        Fnow = F(fRes, xRes)\n        verbose && @info \"Iteration: $iter with F = $Fnow\"\n        \u0394F = 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": "n = rand(2: 10)\n\n# test Hessenberg\n\nA = matrixdepot(\"rohess\", n)\n\nB = tril(A) - diagm(diag(A)) - diagm(diag(A, -1), -1)\n\n@test_approx_eq_eps B zeros(n,n) 1.0e-7\n\n# test orithogonality\n\n@test_approx_eq_eps A'*A eye(n) 1.0e-7\n\nprintln(\"'rohess' passed test...\")\n", "meta": {"hexsha": "7febb7573ab0152407e3784b3a964512a007a0e1", "size": 260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_rohess.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": "test/test_rohess.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": "test/test_rohess.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": 16.25, "max_line_length": 53, "alphanum_fraction": 0.6461538462, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7981193983033279}}
{"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) \u00f7 (2 * Factorial(m - 1))\n        a2 = _get(Menage, m - 2) \u00f7 (2 * Factorial(m - 2))\n\n        am = m * a1 + (m * a2 + 4s) \u00f7 (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 BenchmarkTools\nusing Test\n\nimport Random\nRandom.seed!(321)\n\n# Distance function, considering PBC\nfunction r(x,y,side)\n  d = 0.\n  for i in 1:2\n    dx = (x[i]-y[i])%side\n    if dx > side/2\n      dx = dx - side\n    elseif  dx < -side/2\n      dx = dx + side\n    end\n    d = d + dx^2\n  end\n  return sqrt(d)\nend\n\n# Potential energy function\nU(r,eps,sig) = 4*eps*((sig/r)^12 - (sig/r)^6)\n\n# Compute total potential energy for all pairs\nfunction UT1(x,eps,sig,side)\n  ut = 0.\n  for i in 1:length(x)-1, j in i+1:length(x)\n    rij = r(x[i],x[j],side)\n    ut += U(rij,eps,sig)\n  end\n  return ut\nend\n\n# Compute total potential energy, but do not compute u if rij > 2.\nfunction UT2(x,eps,sig,side)\n  ut = 0.\n  for i in 1:length(x)-1, j in i+1:length(x)\n    rij = r(x[i],x[j],side)\n    if rij <= 2.\n      ut += U(rij,eps,sig)\n    end\n  end\n  return ut\nend\n\n# Generate 100 points\nx = [ 10*rand(2) for i in 1:100 ]\n# Test if UT1 provides the same result as UT2\neps = 2.0\nsig = 0.5\nside = 10.\n@test UT1(x,eps,sig,side) \u2248 UT2(x,eps,sig,side)\n\n# Evaluate code speed\nprint(\"UT1: \"); @btime UT1($x,$eps,$sig,$side)\nprint(\"UT2: \"); @btime UT2($x,$eps,$sig,$side)\n\n\n", "meta": {"hexsha": "26fb7e2c1dd3b72e92803f6ac862253cc3ac0712", "size": 1149, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "disciplina/codes/cutoff2.jl", "max_stars_repo_name": "m3g/kinetics", "max_stars_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-27T19:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T09:24:24.000Z", "max_issues_repo_path": "disciplina/codes/cutoff2.jl", "max_issues_repo_name": "m3g/kinetics", "max_issues_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "disciplina/codes/cutoff2.jl", "max_forks_repo_name": "m3g/kinetics", "max_forks_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T17:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:20:58.000Z", "avg_line_length": 19.15, "max_line_length": 66, "alphanum_fraction": 0.6022628372, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.798119393093217}}
{"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 \u2208 [t0, tf], num_supports = 101)\n\n# variable\n@variable(model, x \u2265 0, Infinite(t))\n\n@variable(model, u, Infinite(t), start = 0)\n\n# objective\n@objective(model, Min, x(1)^2 + \u222b(u^2, t))\n\n# constraint\n@constraint(model, x(0) == x1)\n@constraint(model, x_constr, \u2202(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\u03b8 = 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, \u03b8)\nsol_init = solveeq(prob, Vern9(), abstol = 1e-10, reltol = 1e-10)\nplot(sol_init)\nfunction predict_adjoint(\u03b8)\n    Array(solveeq(prob, Vern9(), p = \u03b8, saveat = ts, sensealg = InterpolatingAdjoint(autojacvec = ReverseDiffVJP(true))))\nend\nfunction loss_adjoint(\u03b8)\n    x = predict_adjoint(\u03b8)\n    x[1, end]^2 + 0.01 * sum(abs2, [first(ann([t], \u03b8)) for t in ts])\nend\nl = loss_adjoint(\u03b8)\n\nconst losses = []\ncallback(\u03b8, l, pred) = begin\n    push!(losses, l)\n    if length(losses) % 50 == 0\n        println(losses[end])\n        p = plot(solveeq(remake(prob, p = \u03b8), Tsit5(), saveat = ts), lw = 3)\n        #plot!(p, ts, [first(ann([t], \u03b8)) for t in ts], label = \"u(t)\", lw = 3)\n        display(p)\n    end\n    false\nend\n# cb = function (\u03b8, l)\n#     println(l)\n#     p = plot(solveeq(remake(prob, p = \u03b8), Tsit5(), saveat = ts), lw = 3)\n#     #plot!(p, ts, [first(ann([t], \u03b8)) 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(\u03b8, l)\nloss1 = loss_adjoint(\u03b8)\nres1 = DiffEqFlux.sciml_train(loss_adjoint, \u03b8, 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\u2013396.\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, \u03d5::Number, ph_term::Bool = false, n_max::Integer = -1, m_max::Integer = -1)\n\nCompute the associated Legendre function `P_n,m[cos(\u03d5)]`. 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)\u1d50` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n\"\"\"\nlegendre!(P::AbstractMatrix, \u03d5::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_fully_normalized!(P, float(\u03d5), ph_term, n_max, m_max)\n\nlegendre!(::Val{:full}, P::AbstractMatrix, \u03d5::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_fully_normalized!(P, float(\u03d5), ph_term, n_max, m_max)\n\nlegendre!(::Val{:schmidt}, P::AbstractMatrix, \u03d5::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_schmidt_quasi_normalized!(P, float(\u03d5), ph_term, n_max, m_max)\n\nlegendre!(::Val{:conv}, P::AbstractMatrix, \u03d5::Number, ph_term::Bool = false,\n          n_max::Integer = -1, m_max::Integer = -1) =\n    legendre_conventional!(P, float(\u03d5), ph_term, n_max, m_max)\n\n\"\"\"\n    legendre([N,] \u03d5::Number, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false)\n\nCompute the associated Legendre function `P_n,m[cos(\u03d5)]`. 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)\u1d50` 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(\u03d5)]`.\n\n\"\"\"\nlegendre(\u03d5::Number, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false) =\n    legendre_fully_normalized(float(\u03d5), n_max, m_max, ph_term)\n\nlegendre(::Val{:full}, \u03d5::Number, n_max::Integer, m_max::Integer = -1,\n         ph_term::Bool = false) =\n    legendre_fully_normalized(float(\u03d5), n_max, m_max, ph_term)\n\nlegendre(::Val{:schmidt}, \u03d5::Number, n_max::Integer, m_max::Integer = -1,\n         ph_term::Bool = false) =\n    legendre_schmidt_quasi_normalized(float(\u03d5), n_max, m_max, ph_term)\n\nlegendre(::Val{:conv}, \u03d5::Number, n_max::Integer, m_max::Integer = -1,\n         ph_term::Bool = false) =\n    legendre_conventional(float(\u03d5), n_max, m_max, ph_term)\n\n################################################################################\n#                Fully Normalized Associated Legendre Functions\n################################################################################\n\n\"\"\"\n    legendre_fully_normalized!(P::AbstractMatrix, \u03d5::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(\u03d5)]`. 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)\u1d50` 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, \u03d5::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(\u03d5)\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(\u03d5::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(\u03d5)]`. 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)\u1d50` 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(\u03d5)]`.\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(\u03d5::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, \u03d5, 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, \u03d5::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(\u03d5)]` [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)\u1d50` 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, \u03d5::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(\u03d5)\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(\u03d5::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(\u03d5)]`. 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)\u1d50` 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(\u03d5)]`.\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(\u03d5::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, \u03d5, ph_term)\n    return P\nend\n\n################################################################################\n#                  Conventional Associated Legendre Function\n################################################################################\n\n\"\"\"\n    legendre_conventional!(P::AbstractMatrix, \u03d5::Number, ph_term::Bool = false, n_max::Integer = -1, m_max::Integer = -1)\n\nCompute the conventional associated Legendre function `P_n,m[cos(\u03d5)]`. 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)\u1d50` will\nbe included. If `ph_term` is not present, then it defaults to `false`.\n\n\"\"\"\nfunction legendre_conventional!(P::AbstractMatrix, \u03d5::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(\u03d5)\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(\u03d5::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(\u03d5)]`. 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)\u1d50` 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(\u03d5)]`.\n\n\"\"\"\nfunction legendre_conventional(\u03d5::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, \u03d5, 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\u2013Bashforth 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\u2013Bashforth 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\u2013Bashforth 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 \u03c3 for f1..f3 with bin around b=$b\");\n\n\u03c3f1jack = Float64[];\n\u03c3f2jack = Float64[];\n\u03c3f3jack = Float64[];\n\nfor bb in bvals\n    jestb = jacknife(v, N2, bb);\n    push!(\u03c3f1jack, jacknife\u03c3(f1, jestb));\n    push!(\u03c3f2jack, jacknife\u03c3(f2, jestb));\n    push!(\u03c3f3jack, jacknife\u03c3(f3, jestb));\nend\n\n\u03c3fjack = cat(2, \u03c3f1jack, \u03c3f2jack, \u03c3f3jack);\n\nprintln(\"\\n\\tGenerating plots in \u03c3fvsb to show \u03c3f dependence on b.\");\nusing Gadfly\n\u03c3fvsb = Plot[];\nfor i in [1:3]\n    push!(\u03c3fvsb, Gadfly.plot(\n        x = bvals,\n        y = \u03c3fjack[:,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 \u03c3fjack to naive \u03c3\u0302 from part 1:\\n\")\nprintln(\"\\t\\t\u03c3\u0302f1N2/\u03c3fjack[4,1] = $(\u03c3\u0302f1N2/\u03c3fjack[4,1])\");\nprintln(\"\\t\\t\u03c3\u0302f2N2/\u03c3fjack[4,2] = $(\u03c3\u0302f2N2/\u03c3fjack[4,2])\");\nprintln(\"\\t\\t\u03c3\u0302f3N2/\u03c3fjack[4,3] = $(\u03c3\u0302f3N2/\u03c3fjack[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": "using Minpack: hybrd\nusing Base.Test\n\n@testset \"analytic\" begin\n\nfunction residual(xvec, arg1, arg2)\n\n    fvec = zeros(xvec)\n\n    fvec[1] = xvec[1] - arg1\n    fvec[2] = xvec[1] + xvec[2] - arg2\n\n    return fvec\nend\n\nx0 = [1.0, 0.0]\nargs = (3.0, 1.0)\ntol = 1e-8\n\nx, f = hybrd(residual, x0, args, tol)\n\n\n@test isapprox(x[1], 3.0; atol=1e-8)\n@test isapprox(x[2], -2.0; atol=1e-8)\n@test isapprox(f[1], 0.0; atol=1e-8)\n@test isapprox(f[2], 0.0; atol=1e-8)\n\n\nfunction residual2(xvec)\n\n    fvec = zeros(xvec)\n\n    fvec[1] = exp(-exp(-(xvec[1]+xvec[2]))) - xvec[2]*(1+xvec[1]^2)\n    fvec[2] = xvec[1]*cos(xvec[2]) + xvec[2]*sin(xvec[1]) - 0.5\n\n    return fvec\nend\n\nx0 = [0.0, 0.0]\nargs = ()\ntol = 1e-8\n\nx, f = hybrd(residual2, x0, args, tol)\n\n\n@test isapprox(x[1], 0.3532; atol=1e-4)\n@test isapprox(x[2], 0.6061; atol=1e-4)\n@test isapprox(f[1], 0.0; atol=1e-8)\n@test isapprox(f[2], 0.0; atol=1e-8)\n\nend  # test set\n", "meta": {"hexsha": "d15241c7e56b15e2930657755041c256b9a88ece", "size": 907, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "byuflowlab/Minpack.jl", "max_stars_repo_head_hexsha": "a930fc8a58f3e38cc2eaa5b4ce4261214edbfe63", "max_stars_repo_licenses": ["MIT"], "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": "byuflowlab/Minpack.jl", "max_issues_repo_head_hexsha": "a930fc8a58f3e38cc2eaa5b4ce4261214edbfe63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-20T19:22:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T21:42:21.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "byuflowlab/Minpack.jl", "max_forks_repo_head_hexsha": "a930fc8a58f3e38cc2eaa5b4ce4261214edbfe63", "max_forks_repo_licenses": ["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.4423076923, "max_line_length": 67, "alphanum_fraction": 0.5898566703, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8723473630627234, "lm_q1q2_score": 0.7981114294793041}}
{"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\u2080 = OpenCPortGraph()\nadd_parts!(d\u2080, :Box, 1)\nd\u2081 = barbell(2)\nF = ACSetTransformation((Box=[2],), d\u2080, d\u2081)\nG = ACSetTransformation((Box=[1],), d\u2080, d\u2081)\nd\u2082 = apex(pushout(F,G))\n\n## Define the primitive systems\n\u03b2, \u03bc, \u03b1\u2081, \u03b1\u2082 = 0.4, 0.4, 0.01, 0.01\n\nsirfuncb = (u,x,p,t)->[-\u03b2*u[1]*u[2] - \u03b1\u2081*(u[1]-x[1]), # S\u0307\n                        \u03b2*u[1]*u[2] - \u03bc*u[2] - \u03b1\u2082*(u[2]-x[2]), #I\u0307\n                        \u03bc*u[2] # R\u0307\n                        ]\nsirfuncm = (u,x,p,t)->[-\u03b2*u[1]*u[2] - \u03b1\u2081*(u[1]-(x[1]+x[3])/2),\n                        \u03b2*u[1]*u[2] - \u03bc*u[2] - \u03b1\u2082*(u[2]-(x[2]+x[4])/2),\n                        \u03bc*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\u2082, [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    \u03b2hat = X\\y\n    \u03c3hat = std(y-X*\u03b2hat)     \n    vcat(\u03b2hat,\u03c3hat)\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    \u03d5 = HAR(y)\n    vcat(m, s, clusters, \u03d5)\nend\n\n# the dgp: simple discrete time stochastic volatility (SV) model\nfunction SVmodel(\u03c3e, \u03c1, \u03c3u, n, shocks_u, shocks_e)\n    burnin = size(shocks_u,1) - n\n    hlag = 0.0\n    h = \u03c1.*hlag .+ \u03c3u.*shocks_u[1] # figure out type\n    y = \u03c3e.*exp(h./2.0).*shocks_e[1]\n    ys = zeros(eltype(y),n)\n    for t = 1:burnin+n\n        h = \u03c1.*hlag .+ \u03c3u.*shocks_u[t]\n        y = \u03c3e.*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 \u21a6 0 if ||x|| \u2a7d r, +\u221e 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 \u21a6 0 if rank(x) \u2a7d r, +\u221e 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    \u03b1::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.\u03b1 * _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": "const madsen = let res_init=zeros(3), jac_init=zeros(3,2), x_init=[3.0, 1.0]\n\n    function res(x, r)\n        r[1] = x[1] ^ 2 + x[2] ^ 2 + x[1] * x[2]\n        r[2] = sin(x[1])\n        r[3] = cos(x[2])\n        return r\n    end\n\n    function jac(x, j)\n        j[1,1] = 2.e0 * x[1] + x[2]\n        j[1,2] = 2.e0*x[2] + x[1]\n        j[2,1] = cos(x[1])\n        j[2,2] = 0.e0\n        j[3,1] = 0.e0\n        j[3,2] = -sin(x[2])\n        return j\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"madsen\", res, jac,\n                                                   res_init, jac_init, x_init;\n                                                   scale=scale, verbose=verbose,\n                                                   print_steps=print_steps)\nend\n", "meta": {"hexsha": "5615eb59c5c6afba8452df83c08920056be2689f", "size": 764, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/madsen.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/madsen.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/madsen.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": 30.56, "max_line_length": 80, "alphanum_fraction": 0.390052356, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7980412338815647}}
{"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, \u00d7, 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    \u00d7(a::Vec, b::Vec)::Vec\n\nCompute the cross product of two vectors.\n\"\"\"\nfunction \u00d7(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    \u221a(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\u00b0 counterclockwise rotation around the (1, 1, 1) axis\njulia> Quat(2\u03c0/3, Vec(1, 1, 1))\nQuat(0.5, 0.5, 0.5, 0.5)\n\njulia> # 45\u00b0 clockwise rotation around the (1, 0, 0) axis\njulia> Quat(-\u03c0/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(\u03c0, 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    \u221a(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(\u03c0/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) * \u03c0 / 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) * \u03c0 / 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": "# ---\n# title: 312. Burst Balloons\n# id: problem312\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Divide and Conquer, Dynamic Programming\n# link: <https://leetcode.com/problems/burst-balloons/description/>\n# hidden: true\n# ---\n# \n# Given `n` balloons, indexed from `0` to `n-1`. Each balloon is painted with a\n# number on it represented by array `nums`. You are asked to burst all the\n# balloons. If the you burst balloon `i` you will get `nums[left] * nums[i] *\n# nums[right]` coins. Here `left` and `right` are adjacent indices of `i`. After\n# the burst, the `left` and `right` then becomes adjacent.\n# \n# Find the maximum coins you can collect by bursting the balloons wisely.\n# \n# **Note:**\n# \n#   * You may imagine `nums[-1] = nums[n] = 1`. They are not real therefore you can not burst them.\n#   * 0 \u2264 `n` \u2264 500, 0 \u2264 `nums[i]` \u2264 100\n# \n# **Example:**\n# \n#     \n#     \n#     Input: [3,1,5,8]\n#     Output: 167 \n#     Explanation:nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []\n#                  coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "d52a49ea36a573ac9f26bd38e24b1ecf4189e030", "size": 1186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/312.burst-balloons.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/312.burst-balloons.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/312.burst-balloons.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.9268292683, "max_line_length": 99, "alphanum_fraction": 0.589376054, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7980002395715852}}
{"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\u030c = paduatransform(f.(x , y));\n\n# and use the coefficients to create an approximation to the function $f$:\nf\u0303 = (x,y) -> begin\n    j = 1\n    ret = 0.0\n    for n in 0:N, k in 0:n\n        ret += f\u030c[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\u0303(0.1,0.2) \u2248 f(0.1,0.2)\n\n# Does the inverse transform bring us back to the grid?\nipaduatransform(f\u030c) \u2248 f\u0303.(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": "using LogExpFunctions, Test\n\n@testset \"xlogx & xlogy\" begin\n    @test iszero(xlogx(0))\n    @test xlogx(2) \u2248 2.0 * log(2.0)\n\n    @test iszero(xlogy(0, 1))\n    @test xlogy(2, 3) \u2248 2.0 * log(3.0)\n    @test xlogy(2, 3.0) \u2248 2.0 * log(3.0) # promoted\nend\n\n@testset \"logistic & logit\" begin\n    @test logistic(2)        \u2248 1.0 / (1.0 + exp(-2.0))\n    @test iszero(logit(0.5))\n    @test logit(logistic(2)) \u2248 2.0\nend\n\n@testset \"log1psq\" begin\n    @test iszero(log1psq(0.0))\n    @test log1psq(1.0) \u2248 log1p(1.0)\n    @test log1psq(2.0) \u2248 log1p(4.0)\n    @test log1psq(Float16(0.1)) \u2248 log1p(0.01)\nend\n\n# log1pexp, log1mexp, log2mexp & logexpm1\n\n@testset \"log1pexp\" begin\n    @test log1pexp(2.0)    \u2248 log(1.0 + exp(2.0))\n    @test log1pexp(-2.0)   \u2248 log(1.0 + exp(-2.0))\n    @test log1pexp(10000)  \u2248 10000.0\n    @test log1pexp(-10000) \u2248 0.0\n\n    @test log1pexp(2f0)      \u2248 log(1f0 + exp(2f0))\n    @test log1pexp(-2f0)     \u2248 log(1f0 + exp(-2f0))\n    @test log1pexp(10000f0)  \u2248 10000f0\n    @test log1pexp(-10000f0) \u2248 0f0\nend\n\n@testset \"log1mexp\" begin\n    @test log1mexp(-1.0)  \u2248 log1p(- exp(-1.0))\n    @test log1mexp(-10.0) \u2248 log1p(- exp(-10.0))\nend\n\n@testset \"log2mexp\" begin\n    @test log2mexp(0.0)  \u2248 0.0\n    @test log2mexp(-1.0) \u2248 log(2.0 - exp(-1.0))\nend\n\n@testset \"logexpm1\" begin\n    @test logexpm1(2.0)            \u2248  log(exp(2.0) - 1.0)\n    @test logexpm1(log1pexp(2.0))  \u2248  2.0\n    @test logexpm1(log1pexp(-2.0)) \u2248 -2.0\n\n    @test logexpm1(2f0)            \u2248  log(exp(2f0) - 1f0)\n    @test logexpm1(log1pexp(2f0))  \u2248  2f0\n    @test logexpm1(log1pexp(-2f0)) \u2248 -2f0\nend\n\n@testset \"log1pmx\" begin\n    @test iszero(log1pmx(0.0))\n    for x in [-0.65, -0.5, -0.3, -0.1, 0.4, 1.0, 2.0]\n        z = BigFloat(x)\n        @test log1pmx(x) \u2248 Float64(log(1 + x) - x)\n    end\nend\n\n@testset \"logmxp1\" begin\n    @test iszero(logmxp1(1.0))\n    for x in [0.1, 0.35, 0.5, 2.0, 3.0]\n        z = BigFloat(x)\n        @test logmxp1(x) \u2248 Float64(log(z) - z + 1)\n    end\nend\n\n@testset \"logsumexp\" begin\n    @test logaddexp(2.0, 3.0)     \u2248 log(exp(2.0) + exp(3.0))\n    @test logaddexp(10002, 10003) \u2248 10000 + logaddexp(2.0, 3.0)\n    @test logaddexp(2, 3.0)     \u2248 log(exp(2.0) + exp(3.0)) # promotion\n\n    @test logsumexp([1.0, 2.0, 3.0])          \u2248 3.40760596444438\n    @test logsumexp((1.0, 2.0, 3.0))          \u2248 3.40760596444438\n    @test logsumexp([1.0, 2.0, 3.0] .+ 1000.) \u2248 1003.40760596444438\n\n    let cases = [([-Inf, -Inf], -Inf),   # correct handling of all -Inf\n                 ([-Inf, -Inf32], -Inf), # promotion\n                 ([-Inf32, -Inf32], -Inf32), # Float32\n                 ([-Inf, Inf], Inf),\n                 ([-Inf, 9.0], 9.0),\n                 ([Inf, 9.0], Inf),\n                 ([NaN, 9.0], NaN),  # NaN propagation\n                 ([NaN, Inf], NaN),  # NaN propagation\n                 ([NaN, -Inf], NaN), # NaN propagation\n                 ([0, 0], log(2.0))] # non-float arguments\n        for (arguments, result) in cases\n            @test logaddexp(arguments...) \u2261 result\n            @test logsumexp(arguments) \u2261 result\n        end\n    end\nend\n\n@testset \"softmax\" begin\n    x = [1.0, 2.0, 3.0]\n    r = exp.(x) ./ sum(exp.(x))\n    @test softmax([1.0, 2.0, 3.0]) \u2248 r\n    softmax!(x)\n    @test x \u2248 r\nend\n", "meta": {"hexsha": "df49c3294010ba74027d8c3975f56961aa66ab92", "size": 3200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "devmotion/LogExpFunctions.jl", "max_stars_repo_head_hexsha": "1c09480be0e696d8059ddca0b38002e1762c3d0e", "max_stars_repo_licenses": ["MIT"], "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": "devmotion/LogExpFunctions.jl", "max_issues_repo_head_hexsha": "1c09480be0e696d8059ddca0b38002e1762c3d0e", "max_issues_repo_licenses": ["MIT"], "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": "devmotion/LogExpFunctions.jl", "max_forks_repo_head_hexsha": "1c09480be0e696d8059ddca0b38002e1762c3d0e", "max_forks_repo_licenses": ["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.6296296296, "max_line_length": 71, "alphanum_fraction": 0.5290625, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.7979931676062952}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.3\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7242a33b-ec37-48d6-afca-8c8387a45a83\nPlutoUI.TableOfContents(aside=true, indent=true, depth=3)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 abc828f1-fd14-4329-8b47-f4135300f937\nmd\"\"\"\n# \ud83d\udcca 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 63420679-9b77-4412-ba1c-fc471da6b1e9\ndata = dataset(\"datasets\", \"faithful\")\n\n# \u2554\u2550\u2561 9d56b2cc-c4c6-4ce2-8d9c-33174fe5bc33\nmd\"\"\"\nWe can use the `describe` function to get some stats from our data...\n\"\"\"\n\n# \u2554\u2550\u2561 67ac4a1d-eb15-473f-a548-07425fd627d8\ndescribe(data)\n\n# \u2554\u2550\u2561 5ee886cc-2730-40cf-8497-507dcdc08c5f\nmd\"\"\"\nLet's call each column (feature) separately...\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6e093fbb-1e3a-4131-b3c2-b5891e734fa7\nmd\"\"\"\nNow, we can plot both variables in the same scatter plot...\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ff9d63e7-808a-4465-a68d-659a222afbae\nmd\"\"\"\n### Boxplot\n\"\"\"\n\n# \u2554\u2550\u2561 c3672771-248a-47f9-a019-2de03cdd79f4\nboxplot([\"Eruption Length\"], eruption, legend=false,\n\t\tsize=(200,400), whisker_width=1, ylabel=\"Time (minutes)\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 943c8862-b909-4750-96da-7bda62c5fc8c\nhistogram(eruption, bins=:sqrt, label=\"Eruption\", color=:orange,\n\t\t  xlabel=\"Eruption Length (minutes)\", ylabel=\"Frequency\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ed58e41f-3f73-40c1-92ec-5f2845c62b97\n\u03c1 = kde(eruption)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3ea44987-7ba7-4df6-a82a-c11a98ea784d\n# the range of density data (x-axis)\n\u03c1.x\n\n# \u2554\u2550\u2561 31274ae3-20da-4f52-9153-6f6b4d4472cb\n# density data (y-axis)\n\u03c1.density\n\n# \u2554\u2550\u2561 53f3e80a-2c88-405f-9131-21d07b132389\n# density * nb of elements * bin width\nscaled_density = \u03c1.density .* length(eruption) .* 0.2\n\n# \u2554\u2550\u2561 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!(\u03c1.x, scaled_density, linewidth=1.5, color=:black, label=\"KDE fit\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 914412a4-69d4-4d9f-b575-03cfa03a7873\n# generating random normal data\nnormaldata = randn(100_000)\n\n# \u2554\u2550\u2561 86c9cf10-2ade-45de-8649-a8dd5b2ae586\nbegin\n\t# generating the KDE\n\t\u03c1\u2099 = kde(normaldata)\n\n\t# scaling density estimates\n\tscaled_\u03c1\u2099 = \u03c1\u2099.density .* length(normaldata) * 0.1\nend\n\n# \u2554\u2550\u2561 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!(\u03c1\u2099.x, scaled_\u03c1\u2099, linewidth=3, color=:black, label=\"KDE fit\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 98301aae-61ca-46ab-936a-fbb310854778\n# note that `fitted_distrib` is a `Distribution`\nfitted_distrib\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ef651442-e846-4a5e-9f3b-0da63afeca16\nbegin\n\terup_distrib = fit(Normal, eruption)\n\tnormal_erup = rand(erup_distrib, 1000)\nend\n\n# \u2554\u2550\u2561 a5a54536-4b60-4a9c-b423-2804cce37382\nerup_distrib\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 af54608d-209f-4d16-9573-b4b8634d2acf\n# generating 1000 random normal values\nhypdata = randn(1000)\n\n# \u2554\u2550\u2561 867dab59-1c8d-44d9-9add-9f3999f1b86c\n# performing one sample t-test\nOneSampleTTest(hypdata)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6555c2a2-227f-419b-9b8b-d563767f3ea5\nOneSampleTTest(eruption)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fcb84ac7-3bca-4284-8939-a55bd78a02fa\nbegin\n\tspearman_r = corspearman(eruption, waittime)\n\t\"r(Spearman) = $spearman_r\"\nend\n\n# \u2554\u2550\u2561 960b8739-10d1-490d-ac49-e51527386161\nbegin\n\tpearson_r = cor(eruption, waittime)\n\t\"r(Pearson) = $pearson_r\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d1ef6cd2-fda1-47f6-af12-8492ea70a539\nscipy_stats = pyimport(\"scipy.stats\");\n\n# \u2554\u2550\u2561 c5f77715-02cb-437a-a45f-3f3a4dfba67b\nbegin\n\tr\u209b, pvalue\u209b = scipy_stats.spearmanr(eruption, waittime)\n\t\"r(Spearman) = $(r\u209b) || p-value = $(pvalue\u209b)\"\nend\n\n# \u2554\u2550\u2561 615e7c40-bafe-475f-959d-29c5f5e845e9\nbegin\n\tr\u209a, pvalue\u209a = scipy_stats.pearsonr(eruption, waittime)\n\t\"r(Pearson) = $(r\u209a) || p-value = $(pvalue\u209a)\"\nend\n\n# \u2554\u2550\u2561 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\u2081` and a prediction vector `y\u0302\u2081`...\n\"\"\"\n\n# \u2554\u2550\u2561 838a8a32-95f6-48c0-b87d-28a66ef431c5\nbegin\n\t# generating target and prediction vectors\n\ty\u2081 = [1, 1, 1, 1, 1, 1, 1, 2]\n\tyhat\u2081 = [1, 1, 2, 2, 1, 1, 1, 1]\nend;\n\n# \u2554\u2550\u2561 68d7cd6c-bd76-406b-a3d7-4528ee9671fd\n# compute default confusion matrix\nC = confusmat(2, y\u2081, yhat\u2081)\n\n# \u2554\u2550\u2561 2bcf8647-368d-4b74-8e1a-4a4b1a577fdc\nmd\"\"\"\nWe may normalize cell values per class...\n\"\"\"\n\n# \u2554\u2550\u2561 86ad3850-f631-42b2-8d19-bf20cba89c6b\nC ./ sum(C, dims=2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ea2c50c6-9404-4ba4-8fe7-4d1e1b3246ff\nacc = sum(diag(C)) / length(y\u2081)\n\n# \u2554\u2550\u2561 70cbc1f9-171e-4664-87d1-6e73f0bc841c\nmd\"\"\"\nInstead of calculating accuracy manually, we could use the `correctrate` function...\n\"\"\"\n\n# \u2554\u2550\u2561 188c0219-8a54-4f28-95fd-9f2f525c12be\nacc == correctrate(y\u2081, yhat\u2081)\n\n# \u2554\u2550\u2561 063d30ad-0ac4-4d50-b66b-9b06bf155fd8\nmd\"\"\"\nNow, we can use the `roc` function to calculate ROC scores...\n\"\"\"\n\n# \u2554\u2550\u2561 f3cca2ef-17ec-44e0-996d-8a0cb2f2fcb1\nbegin\n\t# generating target and prediction vectors\n\ty\u2082 = [1, 1, 1, 1, 1, 1, 1, 0]\n\tyhat\u2082 = [1, 1, 0, 0, 1, 1, 1, 1]\nend;\n\n# \u2554\u2550\u2561 9af05d0f-5daf-48f4-9949-79db70ae4bbc\nROC = MLBase.roc(y\u2082, yhat\u2082)\n\n# \u2554\u2550\u2561 92f98fe2-9154-4029-8282-45dee3f11d31\nmd\"\"\"\nWe may also use both `recall` and `precision` functions to compute these metrics...\n\"\"\"\n\n# \u2554\u2550\u2561 0cfa5643-b65b-4374-a227-8f036ce32bbf\nbegin\n\trec = recall(ROC)\n\t\"Recall = $rec\"\nend\n\n# \u2554\u2550\u2561 93ea2a29-bac3-4629-bac5-5d03e8e45d80\nbegin\n\tprec = precision(ROC)\n\t\"Precision = $prec\"\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25001c630e40-628c-11ec-1793-05688dabf6c9\n# \u255f\u25007242a33b-ec37-48d6-afca-8c8387a45a83\n# \u255f\u2500dd2aa8b3-9da3-418d-bf31-74574483360d\n# \u255f\u2500abc828f1-fd14-4329-8b47-f4135300f937\n# \u255f\u2500a8aae3d4-198c-482f-a972-05be31be39c1\n# \u2560\u255063420679-9b77-4412-ba1c-fc471da6b1e9\n# \u255f\u25009d56b2cc-c4c6-4ce2-8d9c-33174fe5bc33\n# \u2560\u255067ac4a1d-eb15-473f-a548-07425fd627d8\n# \u255f\u25005ee886cc-2730-40cf-8497-507dcdc08c5f\n# \u2560\u2550110fda28-1b77-44d6-8485-a4ec6e012011\n# \u255f\u25006e093fbb-1e3a-4131-b3c2-b5891e734fa7\n# \u2560\u2550ed9da9c2-53e4-45d6-9ec1-02c8bf54c1a5\n# \u255f\u250013137e30-cfde-459a-adb4-1ddc07e626e8\n# \u255f\u2500ff9d63e7-808a-4465-a68d-659a222afbae\n# \u2560\u2550c3672771-248a-47f9-a019-2de03cdd79f4\n# \u255f\u250046b55947-428a-483f-a00f-a232e5329fbd\n# \u255f\u2500e0933f5c-50b5-47cf-bae8-7a45a219fefb\n# \u2560\u2550943c8862-b909-4750-96da-7bda62c5fc8c\n# \u255f\u2500ed480ae6-3302-4d0e-b83e-53a9c395d5ce\n# \u2560\u2550ed58e41f-3f73-40c1-92ec-5f2845c62b97\n# \u255f\u2500952506dc-6cd8-4ecd-ace8-b9d914560289\n# \u2560\u25503ea44987-7ba7-4df6-a82a-c11a98ea784d\n# \u2560\u255031274ae3-20da-4f52-9153-6f6b4d4472cb\n# \u2560\u255053f3e80a-2c88-405f-9131-21d07b132389\n# \u2560\u2550ccfe5310-cc85-457c-bfbc-9671062b9088\n# \u255f\u2500cbf471e5-523c-4550-835b-5c45b9648d8c\n# \u2560\u2550914412a4-69d4-4d9f-b575-03cfa03a7873\n# \u2560\u255086c9cf10-2ade-45de-8649-a8dd5b2ae586\n# \u2560\u2550e137810d-9e3c-43c8-905c-4efc2213a130\n# \u255f\u2500f6430d83-a92b-4c03-a07e-8a6146cc9e1c\n# \u255f\u25004ffd9a7a-c62c-40a4-8ec1-4e2351a2a66a\n# \u2560\u2550978e2f4c-b411-459c-8024-4f6205484f63\n# \u2560\u2550d1483a5e-0b7e-4317-adb0-8f024fad21eb\n# \u255f\u250062470113-95dc-4b92-9e1d-3118efa0bd08\n# \u2560\u25507749b6b5-cf01-4812-b1ce-6fe3204b0bcf\n# \u2560\u2550ff68a550-9cc6-416e-96b8-07de164e5fc4\n# \u255f\u2500693de4f8-88b1-476f-9319-64edafb049af\n# \u2560\u25507f9949d9-22e2-4d4e-92ec-6e52e01d10aa\n# \u2560\u255098301aae-61ca-46ab-936a-fbb310854778\n# \u2560\u2550f270c785-3a7a-4e43-9f21-b9a6e199383b\n# \u255f\u25002d5e5740-a3c6-4448-b79f-f231a0ac9d96\n# \u2560\u2550ef651442-e846-4a5e-9f3b-0da63afeca16\n# \u2560\u2550a5a54536-4b60-4a9c-b423-2804cce37382\n# \u2560\u255025b15bda-9bb4-4ed9-90e4-c1f937051314\n# \u255f\u2500b82db811-d97d-4efd-81bc-a48780b23dcb\n# \u2560\u2550af54608d-209f-4d16-9573-b4b8634d2acf\n# \u2560\u2550867dab59-1c8d-44d9-9add-9f3999f1b86c\n# \u255f\u250047c7f6df-0696-4b1e-b6c2-7eb8e782eb82\n# \u2560\u25506555c2a2-227f-419b-9b8b-d563767f3ea5\n# \u255f\u250078585d9d-5696-41dd-80f0-abab1585b008\n# \u2560\u2550650a1af5-b413-4794-bf51-77fa34cfb820\n# \u255f\u250080db913d-faa8-43d5-9794-e17b02823cc5\n# \u2560\u2550fcb84ac7-3bca-4284-8939-a55bd78a02fa\n# \u2560\u2550960b8739-10d1-490d-ac49-e51527386161\n# \u255f\u25005bd50a69-4edb-435a-9263-e0b5d47851aa\n# \u2560\u2550d1ef6cd2-fda1-47f6-af12-8492ea70a539\n# \u2560\u2550c5f77715-02cb-437a-a45f-3f3a4dfba67b\n# \u2560\u2550615e7c40-bafe-475f-959d-29c5f5e845e9\n# \u255f\u250032bc5a24-638e-43bc-a5c1-bd0a85db7849\n# \u2560\u2550838a8a32-95f6-48c0-b87d-28a66ef431c5\n# \u2560\u255068d7cd6c-bd76-406b-a3d7-4528ee9671fd\n# \u255f\u25002bcf8647-368d-4b74-8e1a-4a4b1a577fdc\n# \u2560\u255086ad3850-f631-42b2-8d19-bf20cba89c6b\n# \u255f\u250038a2bb94-1d8f-4e1a-a07f-3bc1332301fd\n# \u2560\u2550ea2c50c6-9404-4ba4-8fe7-4d1e1b3246ff\n# \u255f\u250070cbc1f9-171e-4664-87d1-6e73f0bc841c\n# \u2560\u2550188c0219-8a54-4f28-95fd-9f2f525c12be\n# \u255f\u2500063d30ad-0ac4-4d50-b66b-9b06bf155fd8\n# \u2560\u2550f3cca2ef-17ec-44e0-996d-8a0cb2f2fcb1\n# \u2560\u25509af05d0f-5daf-48f4-9949-79db70ae4bbc\n# \u255f\u250092f98fe2-9154-4029-8282-45dee3f11d31\n# \u2560\u25500cfa5643-b65b-4374-a227-8f036ce32bbf\n# \u2560\u255093ea2a29-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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \ud83d\ude42. 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# \u2554\u2550\u2561 70ef11be-81b9-4e4d-b83a-f7a225a9001b\nfunction exact_prob_upset(frac_early)\n\treturn (1/\u03c0) * atan(sqrt(frac_early / (1 - frac_early)))\nend\n\n# \u2554\u2550\u2561 24e2efe2-f6f2-4648-8c28-bffedf98095b\nexact_prob_upset(0.2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2122. 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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! \ud83d\ude42\n\"\"\"\n\n# \u2554\u2550\u2561 4a8020c4-b9f4-4c22-8919-eb0f135b1725\nsavefig(\"election_upset_probability.png\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e55c8934-7268-4c5f-af6c-2098a48cc094\nbegin\n\tRandom.seed!(2021)\n\tsimulate_election(0.2, 100_000_000, n_pop)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500d79fcb85-28ca-4e32-bc4d-8c442b771cd6\n# \u255f\u25007c4713bb-7e75-4c0b-815c-e817b71e2f8b\n# \u2560\u255070ef11be-81b9-4e4d-b83a-f7a225a9001b\n# \u2560\u255024e2efe2-f6f2-4648-8c28-bffedf98095b\n# \u255f\u25002383b70b-0693-4adf-99d4-9bcedec5d6cb\n# \u2560\u2550562b2637-ec4f-4be2-a525-09e83c6458fa\n# \u2560\u25505f82ec16-38a7-4c44-aa5a-f76d18d521dd\n# \u2560\u2550b2346518-43b5-4c4d-9536-244514a4d5a3\n# \u255f\u250006cdba4f-426d-47e5-a4c0-c35f9a41d547\n# \u255f\u25004a8020c4-b9f4-4c22-8919-eb0f135b1725\n# \u255f\u2500e1bfd335-b818-4931-8e71-03b46c90c9ec\n# \u2560\u2550e55c8934-7268-4c5f-af6c-2098a48cc094\n# \u255f\u2500537e2e5d-378b-4676-8ba4-3a50f54eb84c\n# \u2560\u255017ada06e-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\u03bd = 0.5\nK = \u03bd*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 \u00d7 n \u00d7 ... \u00d7 n = n15\n\nBut using a \"binary\" method you can compute it in six multiplications:\n\nn \u00d7 n = n^2\nn^2 \u00d7 n^2 = n^4\nn^4 \u00d7 n^4 = n^8\nn^8 \u00d7 n^4 = n^12\nn^12 \u00d7 n^2 = n^14\nn^14 \u00d7 n = n^15\n\nHowever it is yet possible to compute it in only five multiplications:\n\nn \u00d7 n = n^2\nn^2 \u00d7 n = n^3\nn^3 \u00d7 n^3 = n^6\nn^6 \u00d7 n^6 = n^12\nn^12 \u00d7 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 \u2264 k \u2264 200, find \u2211 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": "using NLopt, Test\n\ncount = 0 # keep track of # function evaluations\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\n    global count\n    count::Int += 1\n    println(\"f_$count($x)\")\n\n    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_MMA, 2)\nopt.lower_bounds = [-Inf, 0.]\nopt.xtol_rel = 1e-4\nopt.min_objective = myfunc\nopt.inequality_constraint = (x,g) -> myconstraint(x,g,2,0)\nopt.inequality_constraint = (x,g) -> myconstraint(x,g,-1,1)\n\n(minf,minx,ret) = optimize(opt, [1.234, 5.678])\nprintln(\"got $minf at $minx after $count iterations (returned $ret)\")\n\n@test minx[1] \u2248 1/3 rtol=1e-5\n@test minx[2] \u2248 8/27 rtol=1e-5\n@test minf \u2248 sqrt(8/27) rtol=1e-5\n@test ret == :XTOL_REACHED\n@test opt.numevals == count\n", "meta": {"hexsha": "61da921f1e76cb40d0afdfb56c96b3e4a6582362", "size": 945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tutorial.jl", "max_stars_repo_name": "JeffBezanson/NLopt.jl", "max_stars_repo_head_hexsha": "6824bbc259bc74faa0d97a838b447900e13002d3", "max_stars_repo_licenses": ["MIT"], "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/tutorial.jl", "max_issues_repo_name": "JeffBezanson/NLopt.jl", "max_issues_repo_head_hexsha": "6824bbc259bc74faa0d97a838b447900e13002d3", "max_issues_repo_licenses": ["MIT"], "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/tutorial.jl", "max_forks_repo_name": "JeffBezanson/NLopt.jl", "max_forks_repo_head_hexsha": "6824bbc259bc74faa0d97a838b447900e13002d3", "max_forks_repo_licenses": ["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.0487804878, "max_line_length": 69, "alphanum_fraction": 0.6074074074, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7978919487101205}}
{"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([\u03b1=1 [,p=\u03c0]])\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}(\u03b1::Real) where {T<:AbstractFloat} = new{T}(\n        HyperParameter(convert(T,\u03b1), interval(OpenBound(zero(T)), nothing))\n    )\nend\nPeriodicKernel(\u03b1::T1 = 1.0) where {T1<:Real} = PeriodicKernel{floattype(T1)}(\u03b1)\n\n@inline basefunction(::PeriodicKernel) = SineSquared()\n@inline kappa(\u03ba::PeriodicKernel{T}, z::T) where {T} = squaredexponentialkernel(z, getvalue(\u03ba.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 HyperGraphs\nusing LinearAlgebra: Diagonal\n\n## matrices ##\n\n# incidence matrix of undirected graph from https://en.wikipedia.org/wiki/Incidence_matrix\nes = [HyperEdge([1, 2]), HyperEdge([1, 3]), HyperEdge([1, 4]), HyperEdge([3, 4])]\n@test incidence_matrix(HyperGraph(es)) == [1 1 1 0; 1 0 0 0; 0 1 0 1; 0 0 1 1]\n\n# incidence matrix and properties of undirected hypergraph from Fig. 1 of Konstantinova, E. V., & Skorobogatov, V. A. (2001). Application of hypergraph theory in chemistry. Discrete Mathematics, 235(1\u20133), 365\u2013383.\nx = HyperGraph([HyperEdge([1]), HyperEdge([2, 3]), HyperEdge([1, 2, 4])])\n@test incidence_matrix(x) == [1 0 1; 0 1 1; 0 1 0; 0 0 1]\n@test cardinalities(x) == [1, 2, 3]\n@test degree(x, 2) == 2\n@test degree(x, 4) == 1\n\n# example from: Chen, G., Liu, V., Robinson, E., Rusnak, L. J., & Wang, K. (2018). A characterization of oriented hypergraphic Laplacian and adjacency matrix coefficients. Linear Algebra and Its Applications, 556, 323\u2013341.\nsrcs = [[2], [1, 2], Int[]]; tgts = [[1], [2, 3], [3, 3]]\nchen2018_es = [ChemicalHyperEdge(src, tgt) for (src, tgt) in zip(srcs, tgts)]\nchen2018_x = ChemicalHyperGraph([1, 2, 3], chen2018_es)\nref_degree = [2; 3; 3]\nref_incidence = [1 -1 0; -1 0 0; 0 1 2]\nref_adjacency = [0 1 1; 1 2 0; 1 0 -2]\n@test ref_incidence * transpose(ref_incidence) == Diagonal(ref_degree) - ref_adjacency # II^T = D - A\n@test degrees(chen2018_x) == ref_degree\n@test degree_matrix(chen2018_x) == Diagonal(ref_degree)\n@test incidence_matrix(chen2018_x) == ref_incidence\n\n# undirected graph from https://en.wikipedia.org/wiki/Laplacian_matrix\nwikipedia_edges = HyperEdge.([[1, 2], [2, 3], [3, 4], [4, 5], [5, 1], [5, 2], [6, 4]])\nwikipedia_graph = HyperGraph(wikipedia_edges)\n@test degree_matrix(wikipedia_graph) == Diagonal([2; 3; 2; 3; 3; 1])\n\n## loops ##\n\n# NOTES\n# loops should always have degree 2\n\n# unoriented loop\nunoriented_loop = HyperGraph(HyperEdge([1, 1]))\n@test incidence_matrix(unoriented_loop) == 2*ones(Int, 1, 1)\n@test degrees(unoriented_loop) == [2]\n\n# oriented loops\npositive_loop = ChemicalHyperGraph(ChemicalHyperEdge([1], [1]))\n@test incidence_matrix(positive_loop) == zeros(Int, 1, 1)\n@test degrees(positive_loop) == [2]\nnegative_loop = ChemicalHyperGraph(ChemicalHyperEdge(Int[], [1, 1]))\n@test incidence_matrix(negative_loop) == 2*ones(Int, 1, 1)\n@test degrees(negative_loop) == [2]\n", "meta": {"hexsha": "c721fdeb988da786dd0d37986fc3699564bac0ef", "size": 2354, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/graph-theory.jl", "max_stars_repo_name": "lpmdiaz/HyperGraphs.jl", "max_stars_repo_head_hexsha": "ab6c682afbd292fb02e41f8e7fe9590e3462729d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-05T03:09:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T00:33:01.000Z", "max_issues_repo_path": "test/graph-theory.jl", "max_issues_repo_name": "lpmdiaz/HyperGraphs.jl", "max_issues_repo_head_hexsha": "ab6c682afbd292fb02e41f8e7fe9590e3462729d", "max_issues_repo_licenses": ["MIT"], "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/graph-theory.jl", "max_forks_repo_name": "lpmdiaz/HyperGraphs.jl", "max_forks_repo_head_hexsha": "ab6c682afbd292fb02e41f8e7fe9590e3462729d", "max_forks_repo_licenses": ["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.1568627451, "max_line_length": 222, "alphanum_fraction": 0.6932880204, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7977593717777758}}
{"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\u03b1,\u03b2 = 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] += \u03b1/h^2\nb[m] += \u03b2/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": "# functions for scaling features\n\n\"\"\"\n    standardization!(data::Matrix)\n\nIn-place standardization of the features in the matrix `data`.\n\"\"\"\nfunction standardization!(data::Matrix)\n\n  # find dim. for data\n  dim = minimum(size(data))\n\n  # standardize data\n  if size(data)[1] > size(data)[2]\n    for i = 1:dim\n        data[:,i] = (data[:,i] - mean(data[:,i]))/std(data[:,i])\n    end\n  else\n    for i = 1:dim\n        data[i,:] = (data[i,:] - mean(data[i,:]))/std(data[i,:])\n    end\n  end\n\nend\n\n\n\"\"\"\n    standardization(data::Matrix, return_column_major_order::Bool=true)\n\nStandardization of the features in the matrix `data`.\n\"\"\"\nfunction standardization(data::Matrix, return_column_major_order::Bool=true)\n\n  # find dim. for data\n  dim = minimum(size(data))\n\n  # transform data to column-major order if necessary\n  if size(data)[1] > size(data)[2]\n      data = data'\n  end\n  data_standardized = copy(data)\n\n  # standadize data\n  for i = 1:dim\n      data_standardized[i,:] = (data[i,:] - mean(data[i,:]))/std(data[i,:])\n  end\n\n  # return data in column major order\n  if !return_column_major_order\n      data_standardized = data_standardized'\n  end\n\n  return data_standardized\n\nend\n\n\"\"\"\n    standardization!(data::Vector)\n\nStandardization of the vector `data`.\n\"\"\"\nfunction standardization(data::Vector)\n  data_standardized = (data - mean(data))/std(data)\n  return data_standardized\nend\n\n\n\"\"\"\n    standardization!(data::Vector)\n\nIn-place standardization of the vector `data`.\n\"\"\"\nfunction standardization!(data::Vector)\n  data[:] = (data - mean(data))/std(data)\nend\n", "meta": {"hexsha": "bec6a2ba8375ba0127dd9a1b51e168b85dab3816", "size": 1562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "utilities/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/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/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": 20.5526315789, "max_line_length": 76, "alphanum_fraction": 0.6651728553, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8872046011730965, "lm_q1q2_score": 0.7977046253252184}}
{"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 \u2202vandermonde_1d(N, r)\n    DVr = zeros(length(r), N+1)\n    for i in 0:N\n        @. DVr[:, i+1] = \u2202jacobi(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 = \u2202vandermonde_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\u00fcr 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\u03c0 * dx * sum(TF.(r, 18) .* r .^3), 18, atol=1e-10)\ntrue\n```\n\"\"\"\nfunction TF(r, Z)\n  b = 1/2*(3\u03c0/4)^(2/3)*Z^(-1/3)\n  x = r/b\n\n  B\u2081, B\u2082, B\u2083 = 0.1, 0.55, 0.35\n  \u03b2\u2081, \u03b2\u2082, \u03b2\u2083 = 6.0, 1.20, 0.30\n\n  Z/(4\u03c0*b^3*x)*(B\u2081*\u03b2\u2081^2*exp(-\u03b2\u2081*x) + B\u2082*\u03b2\u2082^2*exp(-\u03b2\u2082*x) + B\u2083*\u03b2\u2083^2*exp(-\u03b2\u2083*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#' title: Sudoku\n#' ---\n\n#' **Originally Contributed by**: Iain Dunning\n\n#' <img src=\"img/partialsudoku.svg\" style=\"width: 300px; height: auto\" alt=\"Partially Solved Sudoku\">\n#' <p style=\"text-align: center\"><i>A partially solved Sudoku puzzle</i></p>\n\n#' \n#' [Sudoku](http://en.wikipedia.org/wiki/Sudoku) is a popular number puzzle. The goal is to place the digits 1,...,9 on a nine-by-nine grid, with some of the digits already filled in. Your solution must satisfy the following rules:\n#' \n#' * The numbers 1 to 9 must appear in each 3x3 square\n#' * The numbers 1 to 9 must appear in each row\n#' * The numbers 1 to 9 must appear in each column\n#' \n#' This isn't an optimization problem, its actually a *feasibility* problem: we wish to find a feasible solution that satsifies these rules. You can think of it as an optimization problem with an objective of 0.\n#' \n#' We can model this problem using 0-1 integer programming: a problem where all the decision variables are binary. We'll use JuMP to create the model, and then we can solve it with any integer programming solver.\n\nusing JuMP\nusing GLPK\n\n#' We will define a binary variable (a variable that is either 0 or 1) for each possible number in each possible cell. The meaning of each variable is as follows:\n#' \n#'     x[i,j,k] = 1  if and only if cell (i,j) has number k\n#' \n#' where `i` is the row and `j` is the column. \n\n# Create a model\nsudoku = Model(with_optimizer(GLPK.Optimizer))\n\n# Create our variables\n@variable(sudoku, x[i=1:9, j=1:9, k=1:9], Bin);\n\n#' Now we can begin to add our constraints. We'll actually start with something obvious to us as humans, but what we need to enforce: that there can be only one number per cell.\n\nfor i = 1:9, j = 1:9  # Each row and each column\n    # Sum across all the possible digits\n    # One and only one of the digits can be in this cell, \n    # so the sum must be equal to one\n    @constraint(sudoku, sum(x[i,j,k] for k in 1:9) == 1)\nend\n\n#' Next we'll add the constraints for the rows and the columns. These constraints are all very similar, so much so that we can actually add them at the same time.\n\nfor ind = 1:9  # Each row, OR each column\n    for k = 1:9  # Each digit\n        # Sum across columns (j) - row constraint\n        @constraint(sudoku, sum(x[ind,j,k] for j in 1:9) == 1)\n        # Sum across rows (i) - column constraint\n            @constraint(sudoku, sum(x[i,ind,k] for i in 1:9) == 1)\n    end\nend\n\n#' Finally, we have the to enforce the constraint that each digit appears once in each of the nine 3x3 sub-grids. Our strategy will be to index over the top-left corners of each 3x3 square with `for` loops, then sum over the squares.\n\nfor i = 1:3:7, j = 1:3:7, k = 1:9\n    # i is the top left row, j is the top left column\n    # We'll sum from i to i+2, e.g. i=4, r=4, 5, 6\n    @constraint(sudoku, sum(x[r,c,k] for  r in i:i+2, c in j:j+2) == 1)\nend\n\n#' The final step is to add the initial solution as a set of constraints. We'll solve the problem that is in the picture at the start of the notebook. We'll put a `0` if there is no digit in that location.\n\n# The given digits\ninit_sol = [ 5 3 0 0 7 0 0 0 0;\n             6 0 0 1 9 5 0 0 0;\n             0 9 8 0 0 0 0 6 0;\n             8 0 0 0 6 0 0 0 3;\n             4 0 0 8 0 3 0 0 1;\n             7 0 0 0 2 0 0 0 6;\n             0 6 0 0 0 0 2 8 0;\n             0 0 0 4 1 9 0 0 5;\n             0 0 0 0 8 0 0 7 9]\nfor i = 1:9, j = 1:9\n    # If the space isn't empty\n    if init_sol[i,j] != 0\n        # Then the corresponding variable for that digit\n        # and location must be 1\n        @constraint(sudoku, x[i,j,init_sol[i,j]] == 1)\n    end\nend\n\n# solve problem\noptimize!(sudoku)\n\n# Extract the values of x\nx_val = value.(x)\n# Create a matrix to store the solution\nsol = zeros(Int,9,9)  # 9x9 matrix of integers\nfor i in 1:9, j in 1:9, k in 1:9\n    # Integer programs are solved as a series of linear programs\n    # so the values might not be precisely 0 and 1. We can just\n    # round them to the nearest integer to make it easier\n    if round(Int,x_val[i,j,k]) == 1\n        sol[i,j] = k\n    end\nend\n# Display the solution\nsol\n\n#' Which is the correct solution:\n#' <img src=\"img/fullsudoku.svg\" style=\"width: 300px; height: auto\" alt=\"Fully Solved Sudoku\">", "meta": {"hexsha": "4cb6b31f7af43f33df789ba85761a884a7f9797c", "size": 4247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/sudoku.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/sudoku.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/sudoku.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": 40.8365384615, "max_line_length": 233, "alphanum_fraction": 0.6564633859, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816424, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7976706403916574}}
{"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 \u03bb.\n    tortoise = f(x0) # f(x0) is the element/node next to x0.\n    hare = (f \u2218 f)(x0)\n    while tortoise \u2260 hare\n        tortoise = f(tortoise)\n        hare = (f \u2218 f)(hare)\n    end\n\n    # At this point the tortoise position, \u03bd, which is also equal\n    # to the distance between hare and tortoise, is divisible by\n    # the period \u03bb. 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\u03bd, a multiple of \u03bb,\n    # they will agree as soon as the tortoise reaches index \u03bc.\n\n    # Find the position \u03bc of first repetition.    \n    \u03bc = 0\n    tortoise = x0\n    while tortoise \u2260 hare\n        tortoise = f(tortoise)\n        hare = f(hare)   # Hare and tortoise move at same speed\n        \u03bc += 1\n    end\n\n    # Find the length of the shortest cycle starting from x_\u03bc\n    # The hare moves one step at a time while tortoise is still.\n    # \u03bb is incremented until \u03bb is found.\n    \u03bb = 1\n    hare = f(tortoise)\n    while tortoise \u2260 hare\n        hare = f(hare)\n        \u03bb += 1\n    end\n\n    \u03bb, \u03bc\nend\n\ncycle_detection_brent(f, x0) = begin\n    # main phase: search successive powers of two\n    power = \u03bb = 1\n    tortoise = x0\n    hare = f(x0)  # f(x0) is the element/node next to x0.\n    while tortoise \u2260 hare\n        if power == \u03bb  # time to start a new power of two?\n            tortoise = hare\n            power *= 2\n            \u03bb = 0\n        end\n        hare = f(hare)\n        \u03bb += 1\n    end\n\n    # Find the position of the first repetition of length \u03bb\n    \u03bc = 0\n    tortoise = hare = x0\n    for i in 0:\u03bb-1\n        hare = f(hare)\n    end\n    # The distance between the hare and tortoise is now \u03bb.\n\n    # Next, the hare and tortoise move at same speed until they agree\n    while tortoise \u2260 hare\n        tortoise = f(tortoise)\n        hare = f(hare)\n        \u03bc += 1\n    end\n\n    \u03bb, \u03bc\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 * \u03c0 * 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 * \u03c0 * 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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, Measures\nend;\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.09\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7e99af3e-3b27-11eb-2b94-051fc56f27cf\ncover(p,ci) = ci[1] <= p && p <= ci[2]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.09\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u25507e997ce4-3b27-11eb-167a-f74a6dff6b1c\n# \u2560\u25507e99af3e-3b27-11eb-2b94-051fc56f27cf\n# \u2560\u25507e9a284c-3b27-11eb-37b2-6fcc5cbb3adb\n# \u2560\u25507ea98df0-3b27-11eb-292f-4d1335c99239\n# \u255f\u2500475ff888-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    \u03bb::T\n    \u03c3::T\n    p::T\n\n    function Spherical{T}(\u03bb::T, \u03c3::T, p::T) where T\n        \u03bb > 0 || throw(DomainError(\u03bb, \"correlation length \u03bb of spherical covariance cannot be negative or zero\"))\n        \u03c3 > 0 || throw(DomainError(\u03c3, \"marginal standard deviation \u03c3 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}(\u03bb, \u03c3, p)\n    end\nend\n\n\"\"\"\n    Spherical(\u03bb, [\u03c3 = 1], [p = 2])\n\nSpherical covariance structure with correlation length `\u03bb`, (optional) marginal standard deviation `\u03c3` and (optional) `p`-norm, defined as\n\n``C(x, y) = \\\\begin{cases} \u03c3 \\\\left(1 - \\\\displaystyle\\\\frac{3}{2}\\\\frac{\u03c1}{\u03bb} + \\\\frac{1}{2}\\\\left(\\\\frac{\u03c1}{\u03bb}\\\\right)^3\\\\right) & \\\\text{for }\u03c1\u2264\u03bb\\\\\\\\0 & \\\\text{for }\u03c1>\u03bb\\\\end{cases}``\n\nwith ``\u03c1 = ||x - y||_p``.\n\n# Examples\n```jldoctest\njulia> Spherical(0.1)\nspherical (\u03bb=0.1, \u03c3=1.0, p=2.0)\n\njulia> Spherical(1.0, \u03c3=2)\nspherical (\u03bb=1.0, \u03c3=2.0, p=2.0)\n\n```\nSee also: [`Exponential`](@ref), [`Linear`](@ref), [`Whittle`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nSpherical(\u03bb::Real; \u03c3::Real=1.0, p::Real=2) = Spherical{promote_type(typeof(\u03bb),typeof(\u03c3),typeof(p))}(promote(\u03bb, \u03c3, p)...)\n\n# evaluate spherical covariance\napply(s::Spherical, x::Real) = max(zero(x), 1 - 3/2 * x/s.\u03bb + 1/2 * (x/s.\u03bb)^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}, \u03b1::Float32)\n    ind = sortperm(x[1:length(x)])\n    x = x[ind]; f = f[ind];\n    i = findfirst(p -> p\u2265\u03b1, 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}, \u03b1::Float32)\n    x = -x; \u03b1 = 1-\u03b1;\n    x_\u03b1 = VaR(x, f, \u03b1)\n    if iszero(\u03b1)\n        return -x_\u03b1\n    else\n        tail = x .\u2264 x_\u03b1\n        result = (sum(x[tail] .* f[tail]) - (sum(f[tail]) - \u03b1) * x_\u03b1) / \u03b1\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\u00fctkepohl (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": "# This does simple Poisson estimation using the meps1996.data\n\n# The MEPS data\n\n# Define dep and expl vbls\n#\n# \tThe dep. vbls, in corresponding column\n# \tOffice based doctor visits\t1\n# \tOutpatient doctor visits\t2\n# \tEmergency room visits\t\t3\n# \tInpatient visits\t\t4\n# \tDental visits\t\t\t5\n# \tPrescriptions\t\t\t6\n#\nusing Econometrics, DelimitedFiles\nwhich_dep = 1\nif (which_dep == 1) dep = \"OBDV\"   end\nif (which_dep == 2) dep = \"OPV\"    end\nif (which_dep == 3) dep = \"IPV\"    end\nif (which_dep == 4) dep = \"ERV\"    end\nif (which_dep == 5) dep = \"DV\"     end\nif (which_dep == 6) dep = \"PRESCR\" end\ndata = readdlm(\"../Data/meps1996.data\")\ny = data[:,which_dep]\nx = data[:,7:12]\nn = size(x,1)\nx = [ones(n,1) x]\n# to check effects of poor scaling, try commenting the next line\nx[:,end] = x[:,end]/1000.0 # put income in thousands\nnames = [\"constant\", \"pub. ins.\",\"priv. ins.\", \"sex\", \"age\",\"edu\",\"inc\"]\ntitle = \"Poisson model, \"*dep* \",  MEPS 1996 full data set\"\nmodel = theta -> poisson(theta, y, x)\ntheta = zeros(size(x,2)) # start values for estimation\n# try adding the option vc=2 for \"Hessian\" or vc=3 for OPG\nthetahat, objvalue, V, converged = mleresults(model, theta, title, names, vc=1)\nnothing\n", "meta": {"hexsha": "b77010b23d42d75ff6f65c896b1105ef2b4313ab", "size": 1193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/MEPS-I/EstimatePoisson.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/MEPS-I/EstimatePoisson.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/MEPS-I/EstimatePoisson.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": 32.2432432432, "max_line_length": 79, "alphanum_fraction": 0.6621961442, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7974764112159247}}
{"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(\u222a, variables.(elements(es))) : Set{LogicalSymbol}()\noperations(es::ExtensionalSet) = length(es) > 0 ? reduce(\u222a, operations.(elements(es))) : Set{LogicalOperation}()\n\nfunction Base.show(io::IO, es::ExtensionalSet)\n    if isempty(es)\n        print(io, \"\u2205\")\n        return\n    end\n\n    print(io, \"{\")\n    i = 1\n    truncated_elements = truncate([elements(es)...], 5)\n    for el \u2208 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 \u2205\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(\u2227, 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\u00b2]\n\n#function to compute ODE\nfunction pendulum!(du,u,p,t)\n    du[1] = u[2]                    # \u03b8'(t) = \u03c9(t)\n    du[2] = -(g\\l)*sin(u[1])  # \u03c9'(t) = -(g/l) sin \u03b8(t)\nend\n\n#initial conditions\n\u03b8\u2080 = \u03c0/6                         # initial angular deflection [rad]\n\u03c9\u2080 = 0.0                            # initial angular velocity [rad/s]\nu\u2080 = [\u03b8\u2080, \u03c9\u2080]                       # initial state vector\ntspan = (0.0,100.0)                  # time interval\n\n#defining the problem and solving\nprob = ODEProblem(pendulum!,u\u2080,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=[\"\u03b8 [rad]\" \"\u03c9 [rad/s]\"],layout=(2,1)))\nsavefig(\"./plots/simple pendulum-plot.png\")\n\n# trajectory\nt=sol.t\nU=sol[1:end,:]\n(\u03b8,\u03c9)=[U[x,:] for x in 1:size(U,1)]\nx=l.*sin.(\u03c0.-\u03b8)\ny=zeros(size(t))\nz=l.*cos.(\u03c0.-\u03b8)\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\u03c0step(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\u03c0(a, g, s) = 4a ^ 2 / (1 - s)\n\nfunction testmakepi()\n\tsetprecision(512)\n\ta, g, s, k = BigFloat(1.0), 1 / \u221aBigFloat(2.0), BigFloat(0.0), 0\n\told\u03c0 = BigFloat(0.0)\n\tprintln(\"Approximating \u03c0 using \", precision(BigFloat), \"-bit floats.\")\n\tprintln(\"   k     Error  Result\")\n\tfor i in 1:100\n\t\ta, g, s, k = approx\u03c0step(a, g, s, k)\n\t\test\u03c0 = approx\u03c0(a, g, s)\n\t\tif abs(est\u03c0 - old\u03c0) < 2eps(est\u03c0) break end\n\t\told\u03c0 = est\u03c0\n\t\terr = abs(\u03c0 - est\u03c0)\n\t\t@printf(\"%4d%10.1e%68.60e\\n\", i, err, est\u03c0)\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\u2080, y\u2080, 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\u2080) = y\u2080 and x\u2080 = x\u2080.\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\u2080: initial x value condition\n    y\u2080: 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\u2080::Real, y\u2080::Real, step::Real, n::Real=100.0)\n\n    y =[y\u2080] #initialize y array with intiial condition\n    x = [x for x in range(x\u2080, 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": "using Test, FinancialMonteCarlo;\n@show \"LogNormalMixture Model\"\nS0 = 100.0;\nK = 100.0;\nr = 0.02;\nT = 1.0;\nd = 0.01;\nD = 90.0;\n\nNsim = 10000;\nNstep = 30;\nsigma = [0.2, 0.2];\nlam = Float64[0.999999999];\nmc = MonteCarloConfiguration(Nsim, Nstep);\nmc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());\ntoll = 0.8\n\nrfCurve = ZeroRate(r);\n\nFwdData = Forward(T)\nEUData = EuropeanOption(T, K)\nAMData = AmericanOption(T, K)\nBarrierData = BarrierOptionDownOut(T, K, D)\nAsianFloatingStrikeData = AsianFloatingStrikeOption(T)\nAsianFixedStrikeData = AsianFixedStrikeOption(T, K)\nModel = LogNormalMixture(sigma, lam, Underlying(S0, d));\nparam_ = FinancialMonteCarlo.get_parameters(Model)\n\nFinancialMonteCarlo.set_parameters!(Model, param_)\ndisplay(Model)\n\n@test_throws(ErrorException, FinancialMonteCarlo.set_parameters!(Model, [1, 4]))\n\n@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);\n@show EuPrice = pricer(Model, rfCurve, mc, EUData);\n@show AmPrice = pricer(Model, rfCurve, mc, AMData);\n@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);\n@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);\n@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);\n\n@test abs(FwdPrice - 99.1078451563562) < toll\n@test abs(EuPrice - 8.43005524824866) < toll\n@test abs(AmPrice - 8.450489415187354) < toll\n@test abs(BarrierPrice - 7.5008664470880735) < toll\n@test abs(AsianPrice1 - 4.774451704549382) < toll\n\n@show \"Test LogNormalMixture Parameters\"\neta = [0.2, 0.2]\nlam11 = [0.9999]\n@test_throws(ErrorException, LogNormalMixture(-0.2 * ones(3), 0.1 * ones(2), Underlying(S0, d)))\n@test_throws(ErrorException, LogNormalMixture(0.2 * ones(3), -0.1 * ones(2), Underlying(S0, d)))\n@test_throws(ErrorException, LogNormalMixture(0.2 * ones(3), ones(2), Underlying(S0, d)))\n@test_throws(ErrorException, LogNormalMixture(0.2 * ones(3), 0.2 * ones(3), Underlying(S0, d)))\n", "meta": {"hexsha": "5fef3902858420f9addf3b984bafdfe85c871547", "size": 1909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_lognormal_mixture.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": "test/test_lognormal_mixture.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": "test/test_lognormal_mixture.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": 35.3518518519, "max_line_length": 96, "alphanum_fraction": 0.7396542693, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7973783698566749}}
{"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": "using BenchmarkTools\nusing Random\nusing Test\n\n@testset \"algorithmic order\" begin\n    ##\n    ## The goal of this problem is to get you thinking about algorithmic order.\n    ##\n    # There's no src/ code for this problem, write everything here.\n    # Note that `@elapsed` is like time and is simple in that it just runs your operation once.\n    # You may need to execute this file more than once in case compilation time complicates the interpretation.\n\n    str = randstring(10^6)\n    d = Dict{Char,Int}()\n    t = @elapsed for c in ['a':'z'; 'A':'Z'; '0':'9']\n        d[c] = count(==(c), str)\n    end\n\n    d2 = Dict{Char,Int}()\n    t2 = @elapsed begin\n        for ch in ['a':'z'; 'A':'Z'; '0':'9']\n            d2[ch] = 0\n        end\n        for ch in str\n            d2[ch] += 1 \n        end# ...\n    end\n    @test t2 < t\n    # Since it's a discrete list of values, can you do even better with an array?\n    # Hint: try `Int('z')` for ideas.\n    \"\"\"So comparison between integers are faster than comparisons between str or chars. \"\"\"\n    counter = zeros(Int, 26*2+10)\n    t3 = @elapsed begin\n        chint_list = Int.(collect(str))\n        for (i, ch) in enumerate(['a':'z'; 'A':'Z'; '0':'9'])\n            counter[i] = sum(chint_list==Int(ch))\n        end\n    end\n    @test t3 < t2\n    println(\"t1 $t;\\t t2 $t2;\\t t3 $t3\")\nend\n", "meta": {"hexsha": "6cb38ce1afe4b7c7b5be060066bfd4336eb62193", "size": 1325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/algorithm_order.jl", "max_stars_repo_name": "Animadversio/Performance_exercise.jl", "max_stars_repo_head_hexsha": "f4aa2d4f68df203f49550da739c21ec2854db41e", "max_stars_repo_licenses": ["MIT"], "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/algorithm_order.jl", "max_issues_repo_name": "Animadversio/Performance_exercise.jl", "max_issues_repo_head_hexsha": "f4aa2d4f68df203f49550da739c21ec2854db41e", "max_issues_repo_licenses": ["MIT"], "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/algorithm_order.jl", "max_forks_repo_name": "Animadversio/Performance_exercise.jl", "max_forks_repo_head_hexsha": "f4aa2d4f68df203f49550da739c21ec2854db41e", "max_forks_repo_licenses": ["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.5476190476, "max_line_length": 111, "alphanum_fraction": 0.5713207547, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7973629702451235}}
{"text": "using PyCall, PyPlot, Random\nRandom.seed!(5)\nsp = pyimport(\"scipy.interpolate\")\nx = LinRange(0,1,50)\ny = (0.9 .+ 0.1rand(length(x))).*sin.(2*pi*(x.-0.5))\nt = collect(x[2:2:end-1])\ns1 = sp.LSQUnivariateSpline(x, y, t)\nx2 = LinRange(0, 1, 201) # new x-grid\ny2 = s1(x2) # evaluate spline on that new grid\nfigure()\nplot(x,y,label=\"original\")\nplot(x2,y2,label=\"interp\", color=\"k\")\nknots = s1.get_knots()\nc = s1.get_coeffs()\nnewknots(knots, k) = vcat(fill(knots[1],k),knots,fill(knots[end],k))\nforscipyknots = newknots(knots, 3)\ns2 = sp.BSpline(forscipyknots, c, 3)\ny3 = s2(x2)\nplot(x2,y3,\"--r\", label=\"reconstructed \\nfrom knots and coeff\")\nlegend()\n##\nknots = [0,.4,.4,.4,.4,.7,1]\nc = [2,-5,5,2,-3,-1,2,1.5]\nforscipyknots = newknots(knots, 3)\ns2 = sp.BSpline(forscipyknots, c, 3)\nfigure()\nplot(x2, s2(x2))\n##\nusing Images\nimg = convert(Array{Float64, 2}, Gray.(load(\"func.png\")))\n", "meta": {"hexsha": "4c6be4d67e471509ceebae65136fa01ce1d57202", "size": 876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "misc/dospline.jl", "max_stars_repo_name": "a2ray/transD_GP", "max_stars_repo_head_hexsha": "44238b66ba5b9adb7a93f4759e92d2bff702c9b7", "max_stars_repo_licenses": ["MIT"], "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/dospline.jl", "max_issues_repo_name": "a2ray/transD_GP", "max_issues_repo_head_hexsha": "44238b66ba5b9adb7a93f4759e92d2bff702c9b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-28T04:14:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T05:47:34.000Z", "max_forks_repo_path": "misc/dospline.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": 28.2580645161, "max_line_length": 68, "alphanum_fraction": 0.651826484, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.797362966755735}}
{"text": "\n\nfunction RouwenNormalize!(A)\n    A[2:end-1, :] ./= 2\n    nothing\nend\n\nfunction rouwenupdate!(\u03a0old, \u03a0new, p, q)\n    Nold = size(\u03a0old, 1)\n    \u03a0new[1:Nold, 1:Nold] = p*\u03a0old\n    \u03a0new[1:Nold, 2:(Nold+1)] .+= (1-p)*\u03a0old\n    \u03a0new[2:(Nold+1), 1:Nold] .+= (1-q)*\u03a0old\n    \u03a0new[2:(Nold+1), 2:(Nold+1)] .+= q*\u03a0old\n    nothing\nend\n\nfunction rouwenmat(N, \u03c1, 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(\u03c1), (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, \u03c1, \u03c3)\n\nDiscretizes AR(1) process `y\u2032 = \u03c1 y +  \u03c3 \u03f5`.\n\n\n# Example\n\nnpts = 10\nrho = 0.9\nsig = 0.01\npoints, \u03a0 = rouwenhorst(npts, rho, sig)\n\n\"\"\"\nfunction rouwenhorst(npts, \u03c1, \u03c3)\n    \u03c9 = \u03c3/sqrt(1-\u03c1^2) # long run std dev\n    # println(\"long run variance: $\u03c9\")\n    q = (1+\u03c1)/2\n\n    points = range(-\u03c9*sqrt(npts - 1),\n                   \u03c9*sqrt(npts-1),\n                   length=npts)\n\n    # points = GenGrid(uniform(npts, bds))\n    \u03a0 = (npts > 1) ? rouwenmat(npts, \u03c1, q, q) : fill(one(\u03c1), (1,1))\n\n    return points, \u03a0\nend\n\n\n\"Returns a MarkovChain with discretized AR(1) from applying `rouwenhorst`\"\nrouwenhorst_mc(npts, \u03c1, \u03c3)=MarkovChain(rouwenhorst(npts, \u03c1, \u03c3)...)\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\u0304, b\u0304 = tab.p.a, tab.p.b\n    ([isapprox(b[i] * a\u0304[i,j] + b\u0304[j] * a[j,i], b[i] * b\u0304[j]; atol=atol, rtol=rtol) for i in axes(a,1), j in axes(a,2)],\n     [isapprox(b[i], b\u0304[i]; atol=atol, rtol=rtol) for i in eachindex(b,b\u0304)])\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\u0305::AbstractMatrix{T}, a::AbstractMatrix{T}, b::AbstractVector{T}) where {T}\n    @assert size(a) == size(a\u0305)\n    @assert length(b) == size(a,1) == size(a,2)\n\n    for i in axes(a\u0305, 1)\n        for j in axes(a\u0305, 2)\n            a\u0305[i,j] = b[j] / b[i] * ( b[i] - a[j,i] )\n        end\n    end\n\n    return a\u0305\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\u0305 = get_symplectic_conjugate_coefficients(tab.a, tab.b)\n    Tableau{T}(name === nothing ? Symbol(tab.name, \"S\") : name, tab.o, (tab.a .+ a\u0305) ./ 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": "using NumericalMethodsforEngineers, IterativeSolvers\n\na = [16. 4. 8.; 4. 5. -4.; 8. -4. 22.]\nb = [4., 2., 5.]\n\nupper = chol(a)\nlower = upper'\ny = lower \\ b\nc = upper \\ y\n\ntol = 1.0e-10\niters = 20\nx,ch = cg(a, b;tol=tol,maxiter=iters);\n\nprintln(\"\\nSolution Vector: $x\")\nprintln(\"Converged: $(ch.isconverged)\")\nprintln(\"Number of iters: $(ch.mvps)\")\n\n@test round(x, 9) == round(c, 9)", "meta": {"hexsha": "2b39a5f4cccf3abc980b1bfad803d218817df6d7", "size": 381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/j_02_12.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/ch02/j_02_12.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/ch02/j_02_12.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": 20.0526315789, "max_line_length": 52, "alphanum_fraction": 0.6167979003, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785412932606, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7973470275645714}}
{"text": "# Problem from https://exercism.io/my/tracks/julia#exercise-binary-search\n# Based on my published solution https://exercism.io/tracks/julia/exercises/binary-search/solutions/5dcd7f36433245a28484889c42a957c0\n\n# Problem Instructions:\n\n\"\"\"\n    binary_search(list, query; rev=false, lt=<, by=identity)\n\nImplement a binary search algorithm.\nSearching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and telephone numbers. Knowing someone's name allows one to quickly find their telephone number and address.\n\nIf the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted.\n\nIn computer science, a binary search or half-interval search algorithm finds the position of a specified input value (the search \"key\") within an array sorted by key value.\n\nIn each step, the algorithm compares the search key value with the key value of the middle element of the array.\n\nIf the keys match, then a matching element has been found and the range of indices that equal the search key value are returned.\n\nOtherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.\n\nIf the remaining array to be searched is empty, then the key cannot be found in the array and a special \"not found\" indication is returned. Search methods in Julia typically return an empty range located at the insertion point in this case.\n\nA binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.\n\nBonus task:\nImplement keyword arguments by, lt and rev so that by specifies a transformation applied to all elements of the list, lt specifies a comparison and rev specifies if the list is ordered in reverse.\n\nContributed By:- [Soc Virnyl Estela](https://github.com/uncomfyhalomacro)\n\"\"\"\nfunction binary_search(list, query; rev = false, lt = <, by = identity)\n    if issorted(list) || issorted(list; rev = true)\n        low = !rev ? 1 : length(list)\n        high = !rev ? length(list) : 1\n        middle(l, h) = round(Int, (l + h) // 2)\n        query = by(query)\n\n        while !rev ? low <= high : high <= low\n            mid = middle(low, high)\n            by(list[mid]) === query && return mid:mid\n            if lt(by(list[mid]), query)\n                low = !rev ? mid + 1 : mid - 1\n            else\n                high = !rev ? mid - 1 : mid + 1\n            end\n        end\n        return !rev ? (low:high) : (high:low)\n\n    else\n        throw(error(\"List not sorted, unable to search value\"))\n    end\nend\n\n# See Issue https://github.com/TheAlgorithms/Julia/issues/34\n\"\"\"\n    binary_search(arr::AbstractArray{T,1}, l::T, r::T, x::T) where {T<:Real}\n\nThe implementation of this binary Search is recursive and requires O(Log n) space. With iterative Binary Search, we need only O(1) space. Useful for the implementation of `exponential_search`.\n\nContributed By:- [Ash](https://github.com/ashwani-rathee)\n\"\"\"\nfunction binary_search(\n    arr::AbstractArray{T,1},\n    l::T,\n    r::T,\n    x::T,\n) where {T<:Real}\n    if (r >= l)\n        mid = Int(ceil(l + (r - l) / 2))\n        # println(mid)\n        if (arr[mid] == x)\n            return \"Element present at index $mid\"\n        elseif (arr[mid] > x)\n            binary_search(arr, l, mid - 1, x)\n        else\n            binary_search(arr, mid + 1, r, x)\n        end\n    else\n        return \"Element not present in array\"\n    end\nend\n", "meta": {"hexsha": "6928c28677544e3840a311f52c923fdab5bcef15", "size": 3840, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/searches/binary_search.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/searches/binary_search.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/searches/binary_search.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": 46.8292682927, "max_line_length": 314, "alphanum_fraction": 0.6877604167, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.7973333051653767}}
{"text": "using RiskAdjustedLinearizations, FastGaussQuadrature, Test\n\n@testset \"Gauss-Hermite Quadrature for Expectations of Functions of Independent Normally Distributed Random Variables/Vectors\" begin\n    f(x) = x  # calculate the expected value\n    g(x) = 1. # calculate the probability\n\n    \u03f5\u1d62, w\u1d62 = RiskAdjustedLinearizations.standard_normal_gausshermite(3)\n    true_eps, true_wts = gausshermite(3)\n    @test \u03f5\u1d62 == true_eps .* sqrt(2.)\n    @test w\u1d62 == true_wts ./ sqrt(\u03c0)\n\n    mean51 = gausshermite_expectation(f, 5., 1., 5)\n    mean01 = gausshermite_expectation(f, 0., 1., 5)\n    mean53 = gausshermite_expectation(f, 5., 3., 5)\n    mean03 = gausshermite_expectation(f, 0., 3., 5)\n    prob   = gausshermite_expectation(g, -5., .1)\n\n    @test mean51 \u2248 5.\n    @test mean53 \u2248 5.\n    @test isapprox(mean01, 0., atol = 1e-14)\n    @test isapprox(mean03, 0., atol = 1e-14)\n    @test prob \u2248 1.\n\n    h1(x) = x[1]\n    h2(x) = x[2]\n\n    prob1 = gausshermite_expectation(g, [.5, 5.], [1., 1.], 5)\n    mean11 = gausshermite_expectation(h1, [.5, 5.], [1., 1.], 5)\n    mean21 = gausshermite_expectation(h2, [.5, 5.], [1., 1.], 5)\n    prob2 = gausshermite_expectation(g, [5., -1.], [1., 1.], (5, 5))\n    mean12 = gausshermite_expectation(h1, [.5, 5.], [1., 1.], (5, 5))\n    mean22 = gausshermite_expectation(h2, [.5, 5.], [1., 1.], (5, 5))\n    prob3 = gausshermite_expectation(g, [5., -1., 2.], [1., 1., 2.], [5, 5, 3])\n    mean13 = gausshermite_expectation(h1, [.5, 5., 2.], [1., 1., 1.], [5, 5, 3])\n    mean23 = gausshermite_expectation(h2, [.5, 5., 2.], [1., 1., 1.], [5, 5, 3])\n\n    @test prob1 \u2248 prob2 \u2248 prob3 \u2248 1.\n    @test mean11 \u2248 mean12 \u2248 mean13 \u2248 .5\n    @test mean21 \u2248 mean22 \u2248 mean23 \u2248 5.\nend\n\nnothing\n", "meta": {"hexsha": "b6599ab9ba33f49d38f6e4ee1944ccb54524a037", "size": 1693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 39.3720930233, "max_line_length": 132, "alphanum_fraction": 0.6072061429, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7973064438667606}}
{"text": "# ## Standard line colors\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\n## ref https://jp.mathworks.com/matlabcentral/fileexchange/35229-matlab-plot-gallery-standard-line-colors?focused=6792895&tab=example\n\nusing SpecialFunctions\n\nx = 0:0.2:10;\ny0 = besselj.(0,x);\ny1 = besselj.(1,x);\ny2 = besselj.(2,x);\ny3 = besselj.(3,x);\ny4 = besselj.(4,x);\ny5 = besselj.(5,x);\ny6 = besselj.(6,x);\n\nplot(x, y0, c=:red)\nplot!(x, y1, c=:green)\nplot!(x, y2, c=:blue)\nplot!(x, y3, c=:cyan)\nplot!(x, y4, c=:magenta)\nplot!(x, y5, c=:yellow)\nplot!(x, y6, c=:black)\n", "meta": {"hexsha": "38ba9d66ea3eea1ad13bcce8fd1e9b8e086ff777", "size": 546, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/standard_line_colors.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/standard_line_colors.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/standard_line_colors.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": 21.84, "max_line_length": 133, "alphanum_fraction": 0.6501831502, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7973064306431898}}
{"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": "using Test, Plots, Parameters, LaTeXStrings\n# transform to cartesian => polar coordinates for angular integrals\n# https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2858241/\n\nNx = 200\nxm = 10.\nx = LinRange(-xm,xm,Nx); y = x\n\n# create some test data\npsi = @. 10*exp(-.1*(x^2+y'^2)) + 15*exp(-(x^2+(y-5)'^2)) # + randn()+im*randn()\nheatmap(x,y,abs2.(psi),transpose=true)\nxlabel!(L\"x\");ylabel!(L\"y\")\n\nabstract type Basis end\nstruct Oscillator <: Basis\n    n::Int64\n    \u03c9::Float64\nend\n\nOscillator(n::Int64) = Oscillator(n,1.0)\nindex(b::Oscillator) = 1:b.n\nspectrum(b::Oscillator) = (0:b.n-1)*b.\u03c9\nqnumbers(b::Oscillator) = 0:b.n-1\n\nfunction hermite(x,n)\n    @assert n >= 1\n    h1 = exp(-x^2 / 2) * (1 / \u03c0)^(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 \u2208 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,\u03c9) = hermite(\u221a\u03c9 * x,n) * \u03c9 ^ ( 1 / 4 )\n\nfunction (b::Oscillator)(x::Array{Float64,1})\n    @unpack \u03c9,n = b\n    T = x * ones(1, n) |> zero\n    T[:,1] = @. hermite(x,1,\u03c9)\n    n >= 2 && (T[:,2] = @. sqrt(2 * \u03c9) * x * T[:,1])\n    for j \u2208 index(b)[3:end]\n        m = qnumbers(b)[j]\n        T[:,j] = @. sqrt(2 / m) * (\u221a\u03c9 * 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.\u03c9)\n\nfunction hermite_polar(x,n,\u03c9)\n    T = zeros(size(x)...,n)\n    T[:,:,1] = @. hermite(x,1,\u03c9)\n    n >= 2 && (T[:,:,2] = @. sqrt(2 * \u03c9) * x * T[:,:,1])\n    for j in 3:n\n        T[:,:,j] = @. sqrt(2 / (j-1)) * (\u221a\u03c9 * x) * T[:,:,j-1] - sqrt((j-2) / (j-1)) * T[:,:,j-2]\n    end\n    return T\nend\nhermite_polar(x,n) = hermite_polar(x,n,1.)\n\n# test that we can create the basis, or any one of oscillator modes\nN = 30\nNv = 1:N\nb1 = Oscillator(N,2.)\n@time b1.(x,Nv')\nplot(x,hermite.(x,Nv'),legend=false,grid=false)\nn = 30\nb1 = Oscillator(n)\n@time b1(x)\nplot(x,b1(x),legend=false,grid=false)\n\n# broadcast over any input parameters\nplot(x,hermite.(x,2,[1. .5 .2 .1]),legend=false,grid=false)\n\n# filtering cartesian data\nfunction filterH(psi,x,N)\n    H = Oscillator(N)(x)\n    T = inv(H'*H)\n    F\u0302 = T*H'*psi*H*T\n    psiF = zero(psi)\n        for m = 1:N, n = 1:(N+1-m)\n            @. psiF += H[:,m]*F\u0302[m,n]*H[:,n]'\n        end\n    return psiF\nend\n\n\n# filter data by projecting onto n oscillator modes\nn = 30\n@time psiF = filterH(psi,x,n)\nheatmap(x,y,abs2.(psiF),transpose=true)\nxlabel!(L\"x\");ylabel!(L\"y\")\n\n# coversion to polar coords\nfunction slowpolar(psi,x,N)\n    H = Oscillator(N)(x)\n    T = inv(H'*H)\n    F\u0302 = T*H'*psi*H*T\n\n    Nx = length(x)\n    \u03b8 = LinRange(0,2*pi,2*Nx)\n    r = LinRange(0,last(x),Nx/2 |> Int)'\n\n    psiP = zero(\u03b8*r)\n    for m = 1:N, n = 1:(N + 1 - m)\n        @. psiP += hermite(r*cos(\u03b8),m) * F\u0302[m,n] * hermite(r*sin(\u03b8),n)\n    end\n    return psiP\nend\n\nfunction init_polar(x,N)\n    \u03b8 = LinRange(0,2*pi,2*Nx)\n    r = LinRange(0,last(x),Nx/2 |> Int)'\n    hx = hermite_polar((@. r*cos(\u03b8)),N)\n    hy = hermite_polar((@. r*sin(\u03b8)),N)\n    return hx,hy\nend\n\n@time hx,hy = init_polar(x,n)\n\nfunction polar(psi,x,hx,hy)\n    N = size(hx)[3]\n    H = Oscillator(N)(x)\n    T = inv(H'*H)\n    F\u0302 = T*H'*psi*H*T\n\n    Nx = length(x)\n    \u03b8 = LinRange(0,2*pi,2*Nx)\n    r = LinRange(0,last(x),Nx/2 |> Int)'\n\n    psiFP = zero(\u03b8*r)\n    for m = 1:N, n = 1:(N + 1 - m)\n        Hx = @view hx[:,:,m]\n        Hy = @view hy[:,:,n]\n        @. psiFP += Hx * F\u0302[m,n] * Hy\n    end\n    return psiFP\nend\n\n# convert to polar coords\nr = LinRange(0,last(x),Nx/2 |> Int)'\n\u03b8 = LinRange(0,2*pi,2*Nx)\n\n@time psiP = slowpolar(psi,x,30)\n@time psifp = polar(psi,x,hx,hy)\n\n# plot in polar coordinates\nheatmap(\u03b8,r',abs2.(psiP),transpose=true)\nxlabel!(L\"\\theta\");ylabel!(L\"r\")\n\nheatmap(\u03b8,r',abs2.(psifp),transpose=true)\nxlabel!(L\"\\theta\");ylabel!(L\"r\")\n\nd\u03b8 = \u03b8[2]-\u03b8[1]\ndr = r[2]-r[1]\ndx = x[2]-x[1]\npsiPth = sum(psiP,dims=1)*d\u03b8\nplot(r',psiPth'.*r')\nxlabel!(L\"r\")\n\n# check total integral preserved (< 1%)\nsum(psiPth.*r)*dr\nsum(psiF)*dx^2\n\n# ===================================\n# ==== Now a more realistic example for trapped BEC\nusing FourierGPE, VortexDistributions\ngr(titlefontsize=12,size=(500,300),transpose=true,colorbar=false)\n\n# ==== Initialize simulation\nL = (25.0,25.0)\nN = (256,256)\nsim = Sim(L,N)\n@unpack_Sim sim\n\n# ==== set simulation parameters\n\u03bc = 25.0\n\n# Time dependent potential function (here trivial t dep)\nimport FourierGPE.V\nV(x,y,t) = 0.5*(x^2 + y^2)\n\u03c80(x,y,\u03bc,g) = sqrt(\u03bc/g)*sqrt(max(1.0-V(x,y,0.0)/\u03bc,0.0)+im*0.0)\n\n# ==== make initial state\nx,y = X\n\u03c8i = \u03c80.(x,y',\u03bc,g)\n\u03d5i = kspace(\u03c8i,sim)\n@pack_Sim! sim\n\n# ==== evolve\n@time sol = runsim(sim)\n\n# speed regression after here?\n# ==== ground state\n\u03d5g = sol[end]\n\u03c8g = xspace(\u03d5g,sim)\nshowpsi(x,y,\u03c8g)\n\n# ==== set simulation parameters\n\u03b3 = 0.0\nt = LinRange(ti,tf,Nt)\n\u03d5i = kspace(\u03c8g,sim)\n# reltol = 1e-7\n# alg = DP5()\n\n# TF parameters\nR(w) = sqrt(2*\u03bc/w^2)\nR(1)\nrv = 3.\nhealinglength(x,y,\u03bc,g) = 1/sqrt(g*abs2(\u03c80(x,y,\u03bc,g)))\n\u03be0 = healinglength.(0.,0.,\u03bc,g)\n\u03be = healinglength(rv,0.,\u03bc,g)\n\n# vcore = Exact(VortexDistributions.\u03c8i,\u03be)\nvcore = Exact(\u03be)\npv = PointVortex(rv,0.,1)\nvi = ScalarVortex(vcore,pv)\npsi = Torus(copy(\u03c8g),x,y)\nvortex!(psi,vi)\nshowpsi(x,y,psi.\u03c8)\n\u03c8i .= psi.\u03c8\n\u03d5i = kspace(\u03c8i,sim)\n\n\n\n# ===== compare with Fetter JLTP 2010\n\u03be = 1/sqrt(\u03bc)\nRtf = R(1)\n\u03a9m = 3*log(Rtf/\u03be/sqrt(2))/2/Rtf^2\n\u03a9v = \u03a9m/(1-rv^2/Rtf^2)\n\n# or a precession period\nTv = 2*pi/\u03a9v\n\nti = 0.; tf = Tv\nt = LinRange(ti,tf,Nt)\n\n@pack_Sim! sim\n\n# ==== evolve\nsolv = runsim(sim)\n\n# ===================================\n\u03d5f = solv[end]\n\u03c8f = xspace(\u03d5f,sim)\nshowpsi(x,y,\u03c8f)\n\n\nanim = @animate for i in eachindex(t)\n    \u03c8 = xspace(solv[i],sim)\n    showpsi(x,y,\u03c8)\nend\n\ngif(anim,\"./examples/vortexprecession.gif\",fps=25)\n", "meta": {"hexsha": "5e922c0c25befbd08f1345f4f0469543a7580f99", "size": 5739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_research/polar.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": "_research/polar.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": "_research/polar.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": 22.0730769231, "max_line_length": 96, "alphanum_fraction": 0.5624673288, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7972911175675568}}
{"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\u00d75 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\u03c4\u2080=0.1      # Stress\n\u03c1=1000      # density\nf=1.e-4     # Coriolis\n\u03b2=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\u03b4_m=(Ah/\u03b2)^(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*\u03b4_m))+(1)/(3^0.5)*sin((3^0.5*x)/(2*\u03b4_m)) )\ndisplay(latexify(t1))\nt2=:( 1-exp((-x)/(2*\u03b4_m) ) * $t1 )\ndisplay(latexify(t2))\nt3=:( \u03c0*sin(\u03c0*y/L_y) )\ndisplay(latexify(t3))\nt4=:( \u03c4\u2080/(\u03c1*g*H)*(f/\u03b2)*(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\u03b7fun(x,y)=(((\u03c4\u2080 / (\u03c1 * g * H)) * (f / \u03b2) * (1 - x / L_x)) * (\u03c0 * sin((\u03c0 * y) / L_y)) * (1 - exp(-x / (2\u03b4_m)) * (cos((3 ^ 0.5 * x) / (2\u03b4_m)) + (1 / 3 ^ 0.5) * sin((3 ^ 0.5 * x) / (2\u03b4_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\u03b7=zeros(nx,ny)\nfor j=1:ny\n for i=1:nx\n  \u03b7[i,j]=\u03b7fun(xvals[i],yvals[j])\n end\nend\n\n\np2 = contour(xvals, yvals, \u03b7')\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, \u03c3 = 0.1)\n    # x = rand(n) .* (3.0 * \u03c0) .+ (1.5 * \u03c0)\n    # y = rand(n) .* (30.0 * \u03c0)\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) .* \u03c3\n    # res[:, 2] .= f2.(x, y) .+ randn(n) .* \u03c3\n    # res[:, 3] .= f3.(x, y) .+ randn(n) .* \u03c3\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 * \u03c0) .+ (1.5 * \u03c0)\n    yy() = rand() .* (30.0 * \u03c0)\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, \u03c3 = 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 * \u03c0, length = n)) .* ff\n    res[:, 2] .= sin.(range(0, stop = 2 * \u03c0, length = n)) .* ff\n\n    res .+= randn(size(res)...) .* \u03c3\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": "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\n\nChebyT(x,deg) = cos(acos(x)*deg)\nunitmap(x,lb,ub) = 2 .* (x .- lb) ./ (ub .- lb) .- 1\t#[a,b] -> [-1,1]\n\nfunction q1(n)\n\tf(x) = x .+ 2x.^2 - exp.(-x)\n\n\t# without using PyPlot, just erase the `PyPlot.` part\n\tPyPlot.savefig(joinpath(dirname(@__FILE__),\"..\",\"q1.png\"))\n\treturn Dict(:error=>maximum(abs,err))\nend\n\nfunction q2(b::Number)\n\t@assert b > 0\n\t# use ApproxFun.jl to do the same:\n\n\tPlots.savefig(p,joinpath(dirname(@__FILE__),\"..\",\"q2.png\"))\nend\n\nfunction q3(b::Number)\n\n\t# p is your plot\n\treturn (p,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} #\u00a0evaluation 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\t\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\n\n\tPyPlot.savefig(joinpath(dirname(@__FILE__),\"..\",\"q7.png\"))\nend\n\n\n\t#\u00a0function 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": "732fe3f863903fe54248961b73b46cd4b974a27a", "size": 2630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HWfuncapp.jl", "max_stars_repo_name": "ScPo-CompEcon/HWfuncapp.jl", "max_stars_repo_head_hexsha": "8ee36c6983ee04c5ad26b2e0b01a6d332984b839", "max_stars_repo_licenses": ["MIT"], "max_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": "ScPo-CompEcon/HWfuncapp.jl", "max_issues_repo_head_hexsha": "8ee36c6983ee04c5ad26b2e0b01a6d332984b839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-11T15:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-15T08:25:33.000Z", "max_forks_repo_path": "src/HWfuncapp.jl", "max_forks_repo_name": "ScPo-CompEcon/HWfuncapp.jl", "max_forks_repo_head_hexsha": "8ee36c6983ee04c5ad26b2e0b01a6d332984b839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-04-08T10:16:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-13T12:17:36.000Z", "avg_line_length": 22.1008403361, "max_line_length": 141, "alphanum_fraction": 0.6942965779, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.797220612331098}}
{"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\u03c3(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->\u03c3(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 `\u03c3(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 $\u03c3(x_1,w, b)$ for our apple. So, we want the difference $0 - \u03c3(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 - \u03c3(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 - \u03c3(x_1, w, b))^2 + (1 - \u03c3(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 - \u03c3(apple_green_amount,w,b))^2 + (1 - \u03c3(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->\u03c3(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    \u03b1=0.85, \n    n=100::Integer, \n    \u03f5=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    \u03b1_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        \u03b1_div_outdegree[v] = (\u03b1/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 - \u03b1 + \u03b1 * 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] * \u03b1_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 * \u03f5)\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 \u03b7 are parameters to be estimated\n\n# literature suggests over 100 years the maximum level is:\nQ(k, A, \u03b7) = k * A^(\u03b7 - 1)\n\n# Take the log to linearlize\nlogQ(k, A, \u03b7) = log(k) + (\u03b7 - 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\u2081 which is smaller than subset\n# X\u2082 which is smaller than the full set X\u2081\u2080\u2080 is going to have the following property:\n# E(max(X\u2081)) < E(max(X\u2082)) < E(max(X\u2081\u2080\u2080))\n\n# What we would like to know is max(X\u2081\u2080\u2080)\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 \u2264 t) = P(X_1 \u2264, ... X_100 \u2264 t) = \u03a0 P(X_i < t) = [F(t)]^100\n# by iid P(X_100 \u2264 t) => [F(t)]^100\n\n# P(X_100 \u2264 t) = [F(t)]^100 = 1/2\n# \u2192 P(X_100 \u2264 t) = F(t\u2080) = (1/2)^.01 \u2192 t\u2080 = .993\n\n\n# Using Extreme value function\n# P(X_i <= t) = exp(-exp(-(t-\u03bc)/\u03c3))\n\nQ993(\u03bc, \u03c3) = \u03c3*(-log(-log(.993))) + \u03bc\n\n# The Authors suggest that we can estimate \u03bc and \u03c3 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\u03bchat = mean(waterlevel[observe .== 1])\n\u03c3hat = var(waterlevel[observe .== 1])^.5\n\nQ993(\u03bchat, \u03c3hat)\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\u211cD(x::Float64, y::Float64, v::Float64, w::Float64, \u03b2::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 \u03b1 Frohlich coupling. \u03b2 is the reduced thermodynamical beta = \u0127\u03c9/kT with k being Boltzman's constant.\n\"\"\"\nfunction \u211cD(x, y, v, w, \u03b2)\n    x = BigFloat(x)\n    y = BigFloat(y)\n    \u03b2 = BigFloat(\u03b2)\n    v = BigFloat(v)\n    w = BigFloat(w)\n\n    R = (v^2 - w^2) / (w^2 * v)\n    a_squared = \u03b2^2 / 4 + R * \u03b2 * coth(\u03b2 * v / 2)\n    b = R * \u03b2 / sinh(\u03b2 * v / 2)\n\n    w^2 * (a_squared - \u03b2^2 / 4 - b * cos(v * x) * cosh(v * (y - \u03b2 / 2)) + x^2 + y * (\u03b2 - y)) / (\u03b2 * v^2)\nend\n\n\"\"\"\n\u2111D(x::Float64, y::Float64, v::Float64, w::Float64, \u03b2::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 \u03b1 Frohlich coupling. \u03b2 is the reduced thermodynamical beta = \u0127\u03c9/kT with k being Boltzman's constant.\n\"\"\"\nfunction \u2111D(x, y, v, w, \u03b2)\n    x = BigFloat(x)\n    y = BigFloat(y)\n    \u03b2 = BigFloat(\u03b2)\n    v = BigFloat(v)\n    w = BigFloat(w)\n\n    R = (v^2 - w^2) / (w^2 * v)\n    a_squared = \u03b2^2 / 4 + R * \u03b2 * coth(\u03b2 * v / 2)\n    b = R * \u03b2 / sinh(\u03b2 * v / 2)\n\n    w^2 * (b * sin(v * x) * sinh(v * (y - \u03b2 / 2)) + 2 * x * (y - \u03b2 / 2)) / (\u03b2 * v^2)\nend\n\n# Create a complex number from the real and imaginary parts of D(u).\n\nD(x, y, v, w, \u03b2) = \u211cD(x, y, v, w, \u03b2) + 1im * \u2111D(x, y, v, w, \u03b2)\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 \u03c3 <: actFun end\n\n\"\"\"\n    return the Sigmoid output\n    inputs must be matices\n\"\"\"\n\u03c3(X, W, B) = 1 ./ (1 .+ exp.(.-(W * X .+ B)))\n\u03c3(Z) = 1 ./ (1 .+ exp.(.-Z))\n\nexport \u03c3\n\n\"\"\"\n    return the derivative of Sigmoid function\n\"\"\"\nd\u03c3(Z) = \u03c3(Z) .* (1 .- \u03c3(Z))\n\nexport d\u03c3\n\n@doc raw\"\"\"\n    function probToValue(\n        actFun::Type{\u03c3},\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\u0302_bool` := Boolean valuse of the probabilites\n\n- `acc` := Accuracy when `labels` provided\n\"\"\"\nfunction probToValue(\n    actFun::Type{\u03c3},\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\u0302_bool = probs .> T(evalConst)\n    acc = nothing\n    if labels isa AbstractArray\n        acc = sum(Y\u0302_bool .== labels) / (s[end-1] * s[end])\n        # println(\"Accuracy = $acc\")\n    end\n    return Y\u0302_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\u0302::AbstractArray{T,N}) where {T,N}\n    Y\u0302_exp = exp.(Y\u0302)\n    sumofexp = sum(Y\u0302_exp, dims = N - 1)\n    return Y\u0302_exp ./ sumofexp\nend #softmax\n\nfunction dsoftmax(Y\u0302, dim = 1)\n    sY\u0302 = softmax(Y\u0302)\n    T = eltype(Y\u0302)\n    softMat = AbstractArray{T,3}(undef, 0, 0, 0)\n    sSize = size(Y\u0302)[dim]\n    for c in eachcol(sY\u0302)\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\u0302_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\u0302_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\u0302_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\u0302_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#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n#                                                                             #\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n\n\"\"\"\n```\nfunction sinusoidal(a :: IntOrReal,\n                    f :: IntOrReal,\n                   sr :: Int,\n                    t :: Int,\n                    \u03b8 :: 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 `\u03b8`\n(\u03b8=0 makes a sine, \u03b8=\u03c0/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=\u03c0/2\nv=sinusoidal(1., 12, 64, 128, \u03c0/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                    \u03b8  :: IntOrReal =0.;\n                DC = 0.)\n    \u0394i = inv(sr)\n    f2\u03c0 = f * 2\u03c0\n    \u03bd=Vector([DC+(a*sin(f2\u03c0 * i * \u0394i + \u03b8)) 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 \ud83d\udccc*\", 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#\u00a4 if DC is true the first frequency is the DC level, hence !DC*fres(sr, wl)\n#\u00a4 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\u00f72+DC ? (return (bin-DC)*(sr/wl) ) :\n    @error \ud83d\udccc*\", 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#\u00a4 if DC is true there are wl\u00f72+1 bins, otherwise there are wl\u00f72 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\u00f72`` (integer division), otherwise the DC level is at position 1.\nand the length of the vector is ``(wl\u00f72)+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\u00f72]\n#\u00a4 if DC is true !DC=0, hence !DC:wl\u00f72 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\u00f72)`` (integer division),\notherwise it is ``1:(wl\u00f72)+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\u00f72+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\u00f72`` (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 \ud83d\udccc*\", 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\u00f72))\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(\ud835\udc00::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 \ud835\udc00\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\u03d5=phase(y, func=x->(x+\u03c0)/2\u03c0*50)\nplot([x, a, \u03d5]; 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\u03d5=phase(y, func=x->(x+\u03c0)/2\u03c0*50)\nplot([x, a, \u03d5]; labels=[\"signal\", \"amplitude\", \"phase\"])\n\n# unwrapped phase\n# the line below will do nothing as argument `unwrapdims` is 0 by default\n\u03d52=unwrapPhase(phase(y))\n# this will do the job\n\u03d52=unwrapPhase(phase(y); unwrapdims=1)\nplot([x, a, \u03d52./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\ud835\udef7=phase(Y)\nplot(\ud835\udef7[:, 1:1])\n\n# unwrapped phase\n\ud835\udef72=unwrapPhase(\ud835\udef7; unwrapdims=1)\nplot(\ud835\udef72)\n\n# phase represented in [-1, 1]\n\ud835\udef7=phase(Y, func=x->(x+\u03c0)/2\u03c0)\nplot(\ud835\udef7[:, 1:1])\n\n# sine of the phase\n\ud835\udef7=phase(Y, func=sin)\nplot(\ud835\udef7[:, 1:1])\n\n# get Amplitude and phase from analytic Signal\nA, \ud835\udef7=polar(Y)\nA\n\ud835\udef7\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(\ud835\udc00::TFAnalyticSignalVector;\n                    func::Function=identity) = [amplitude(A.y, func) for A \u2208 \ud835\udc00]\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(\ud835\udc19::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 \ud835\udeaf.\n\n~\n\nIn all methods by default the phase is returned in [\u2212\u03c0, \u03c0].\nIf a function is provided by the optional keyword argument `func`,\nit is applied to the phase. For example\n- passing `func=x->x+\u03c0` will return the phase in [0, 2\u03c0],\n- passing `func=x->x/\u03c0` 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(\ud835\udc19::TFAnalyticSignalVector; unwrapped::Bool=false, func::Function=identity) =\n    [phase(Z; unwrapped=unwrapped, func=func) for Z \u2208 \ud835\udc19]\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 [\u2212\u03c0, \u03c0].\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\u03c0 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(\u03f4::AbstractArray{T};\n                                unwrapdims::Int=0) where T<:Real\n\n(3)\nunwrapPhase(\u03f4::TFPhase) [constructor of a TFPhase object]\n\n(4)\nunwrapPhase(\ud835\udeaf::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 [\u2212\u03c0, \u03c0],\notherwise return `\u03f4`.\n\n(3)\n\nConstruct a [TFPhase](@ref) object by unwrapping its phase along the time\ndimension and copying all other fields from the `\u03f4` object. If `\u03f4.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 \ud835\udeaf with the phase unwrapped.\n`\u03f4.func` must be the identity function for all \u03f4 \u2208 \ud835\udeaf.\n\nThe unwrapped phase is defined as the cumulative sum\nof the phase (along the relevant dimension)\nonce this is represented in [0, 2\u03c0].\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)).+\u03c0; dims=unwrapdims) : Z\n\nunwrapPhase(\u03f4::AbstractArray{T}; unwrapdims::Int=0) where T<:Real =\n    unwrapdims>0 ? accumulate(+, \u03f4.+\u03c0; dims=unwrapdims) : \u03f4\n\nunwrapPhase(\u03f4::TFPhase) =\n    \u03f4.func==identity ? TFPhase(unwrapPhase(\u03f4.y; unwrapdims=2), \u03f4.bandwidth,\n                               \u03f4.flabels, \u03f4.nonlinear,\n                               \u03f4.fsmoothing, \u03f4.tsmoothing, true, \u03f4.func) :\n   @error \ud83d\udccc*\", 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.)\" \u03f4.func\n\n\nunwrapPhase(\ud835\udeaf::TFPhaseVector) =\n   sum(\u03f4.func==identity for \u03f4 \u2208 \ud835\udeaf)==length(\ud835\udeaf) ? TFPhaseVector([\n                    TFPhase(unwrapPhase(\u03f4.y; unwrapdims=2), \u03f4.bandwidth,\n                    \u03f4.flabels, \u03f4.nonlinear, \u03f4.fsmoothing, \u03f4.tsmoothing,\n                    true, \u03f4.func) for \u03f4 \u2208 \ud835\udeaf]) :\n  @error \ud83d\udccc*\", 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.)\" \u03f4.func\n\n\n\n\"\"\"\n```\nfunction sameParams(\ud835\udc12        :: FDobjectsVector,\n                    funcname :: String)\n```\n\n\nReturn true if all objects in \ud835\udc12 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(\ud835\udc12        :: FDobjectsVector,\n           funcname :: String = \"unknown\") =\n   if      !_allsame([S.sr for S \u2208 \ud835\udc12])\n               @error \ud83d\udccc*\", \"*funcname*\" function. All objects in argument of type $typeof(\ud835\udc12) must have the same sampling rate (.sr field)\"\n   elseif  !_allsame([S.wl for S \u2208 \ud835\udc12])\n               @error \ud83d\udccc*\", \"*funcname*\" function. All objects in argument of type $typeof(\ud835\udc12) must have the same window length (.wl field)\"\n   elseif  !_allsame([S.DC for S \u2208 \ud835\udc12])\n               @error \ud83d\udccc*\", \"*funcname*\" function. All objects in argument of type $typeof(\ud835\udc12) must all hold or not hold DC level (.DC field)\"\n   elseif  !_allsame([S.taper for S \u2208 \ud835\udc12])\n               @error \ud83d\udccc*\", \"*funcname*\". All objects in argument of type $typeof(\ud835\udc12) must have the same taper (.taper field)\"\n   elseif  \ud835\udc12 isa SpectraVector && !_allsame([S.func for S \u2208 \ud835\udc12])\n               @error \ud83d\udccc*\", \"*funcname*\". All objects in argument of type $typeof(\ud835\udc12) must have been subjected to the same function (.func field)\"\n   elseif  (\ud835\udc12 isa CrossSpectraVector || \ud835\udc12 isa CoherenceVector) && !_allsame([S.nonlinear for S \u2208 \ud835\udc12])\n               @error \ud83d\udccc*\", \"*funcname*\". The objects in argument of type $typeof(\ud835\udc12) must be either all linear or all non-linear (.nonlinear field)\"\n   elseif  !_allsame([S.smoothing for S \u2208 \ud835\udc12])\n               @error \ud83d\udccc*\", \"*funcname*\". All the objects in argument of type $typeof(\ud835\udc12) must have been subjected to the same smoother (.smoothing field)\"\n   elseif      return true\n   end\n\n\n\"\"\"\n```\nfunction sameParams(\ud835\udc80        :: TFobjectsVector,\n                    funcname :: String) =\n```\nReturn true if all objects in \ud835\udc80 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(\ud835\udc80        :: TFobjectsVector,\n           funcname :: String = \"unknown\") =\n   if      !_allsame([Y.bandwidth for Y \u2208 \ud835\udc80])\n               @error \ud83d\udccc*\", \"*funcname*\" function. All the objects in argument of type $typeof(\ud835\udc80) must all be definied with the same bandwidth\"\n   elseif  !isa(\ud835\udc80, TFAmplitudeVector) && !_allsame([Y.nonlinear for Y \u2208 \ud835\udc80])\n               @error \ud83d\udccc*\", \"*funcname*\" function. All the objects in argument of type $typeof(\ud835\udc80) must be definied as either all nonlinear or all linear\"\n   elseif  !_allsame([Y.fsmoothing for Y \u2208 \ud835\udc80])\n               @error \ud83d\udccc*\", \"*funcname*\" function. All the objects in argument of type $typeof(\ud835\udc80) must be definied with the same frequency smoother\"\n   elseif  !_allsame([Y.tsmoothing for Y \u2208 \ud835\udc80])\n               @error \ud83d\udccc*\", \"*funcname*\" function. All the objects in argument of type $typeof(\ud835\udc80) must be definied with the same time smoother\"\n   elseif      return true\n   end\n\n\n\"\"\"\n```\nfunction isLinear(\ud835\udc80::Union{FDobjectsVector, TFobjectsVector})\n```\nReturn true if all objects in `\ud835\udc80` 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(\ud835\udc80::FDobjectsVector) =\n   \ud835\udc80 isa SpectraVector ? true : sum(Y.nonlinear for Y \u2208 \ud835\udc80)==0\n\nisLinear(\ud835\udc80::TFobjectsVector) =\n   \ud835\udc80 isa TFAmplitudeVector ? true : sum(Y.nonlinear for Y \u2208 \ud835\udc80)==0\n\n\"\"\"\n```\nfunction isNonLinear(\ud835\udc80::Union{FDobjectsVector, TFobjectsVector})\n```\nReturn true if all objects in `\ud835\udc80` 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(\ud835\udc80::FDobjectsVector) =\n   \ud835\udc80 isa SpectraVector ? false : sum(Y.nonlinear for Y \u2208 \ud835\udc80)==length(\ud835\udc80)\n\nisNonLinear(\ud835\udc80::TFobjectsVector) =\n   \ud835\udc80 isa TFAmplitudeVector ? false : sum(Y.nonlinear for Y \u2208 \ud835\udc80)==length(\ud835\udc80)\n\n\"\"\"\n```\n(1)\nfunction isUnwrapped(\u03f4::TFPhase)\n\n(2)\nfunction isUnwrapped(\ud835\udeaf::TFPhaseVector)\n```\n(1)\nReturn true if the TFPhase objects \u03f4 have the phase unwrapped.\n\n(2)\nReturn true if all TFPhase objects in \ud835\udeaf have the phase unwrapped.\n\n**See**: [`unwrapPhase`](@ref), [TFPhase](@ref), [TFPhaseVector](@ref).\n\"\"\"\nisUnwrapped(\u03f4::TFPhase) =  \u03f4.unwrapped\n\nisUnwrapped(\ud835\udeaf::TFPhaseVector) =  sum(\u03f4.unwrapped for \u03f4 \u2208 \ud835\udeaf)==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, \u03b3, c1, c2)\n    Y=similar(S.y)\n    @inbounds for i=1:size(S.y, 2) Y[:, i]=__smooth(S.y[:, i], \u03b3, 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, \ud835\udc12::SpectraVector, \u03b3, c1, c2) =\n    SpectraVector([_smooth(smoother, S, \u03b3, c1, c2) for S \u2208 \ud835\udc12])\n\n# Internal function: smooth the output of `cross-spectra` or `coherence` function\n_smooth(smoother::Smoother, \ud835\ude4e::Union{CrossSpectra, Coherence}, \u03b3, c1, c2) =\n    typeof(\ud835\ude4e)(__smooth(\ud835\ude4e.y, \u03b3, c1, c2), \ud835\ude4e.sr, \ud835\ude4e.wl, \ud835\ude4e.DC, \ud835\ude4e.taper, \ud835\ude4e.flabels, \ud835\ude4e.nonlinear, smoother, \ud835\ude4e.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, \ud835\udce2::Union{CrossSpectraVector, CoherenceVector}, \u03b3, c1, c2) =\n    typeof(\ud835\udce2)([_smooth(smoother, \ud835\udc12, \u03b3, c1, c2) for \ud835\udc12 \u2208 \ud835\udce2])\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\u03a3=spectra(v, sr, t; func=\u221a)\nbar(\u03a3.y, labels=\"raw amplitude spectra\")\n\n#smooth spectra\n\u03a32=smooth(blackmanSmoother, \u03a3)\nbar!(\u03a32.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                 \u03b3, 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, :], \u03b3, 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], \u03b3, 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], \u03b3, 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, :], \u03b3, 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 \ud83d\udccc*\", 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\u2260noSmoother, tsmoothing\u2260noSmoother, _getSmoothCoeff(smoother)...)\n    else\n        @error \ud83d\udccc*\", 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       \ud835\udc19          :: TFobjectsVector,\n       funcname   :: String=\"\") =\n   if \ud835\udc19 isa TFPhaseVector && isUnwrapped(\ud835\udc19)\n       @error \ud83d\udccc*\", 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 \ud835\udc19\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(\ud835\udc19)([_smooth(smoother, Z, fsmoothing\u2260noSmoother, tsmoothing\u2260noSmoother, _getSmoothCoeff(smoother)...) for Z \u2208 \ud835\udc19])\n   else\n       @error \ud83d\udccc*\", 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 ? \ud835\udc19 :\n#           typeof(\ud835\udc19)([_smooth(smoother, Z, frequency, time, _getSmoothCoeff(smoother)...) for Z \u2208 \ud835\udc19])\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 \ud83d\udccc*\", \"*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 \ud83d\udccc*\", \"*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 \ud83d\udccc*\", \"*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(\ud835\udc12::FDobjectsVector, frange::fInterval, funcname::String; check::Bool=true) =\n    check ? (sameParams(\ud835\udc12, funcname) ? _getfrange(\ud835\udc12[1], frange, funcname) : 0) :\n    _getfrange(\ud835\udc12[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(\ud835\udc12::SpectraVector, frange::UnitRange{Int64}) =\n    _isnull(frange) && size(\ud835\udc12[1].y, 2)==1 ? [S[first(frange), 1] for S \u2208 \ud835\udc12] :\n                                            [S[frange, :] for S \u2208 \ud835\udc12]\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\u2208frange])\nend\n\nfunction _extract(\ud835\udc12::Union{CrossSpectraVector, CoherenceVector}, frange::UnitRange{Int64})\n    mattype = \ud835\udc12[1].tril ? LowerTriangular : Hermitian\n    _isnull(frange) ? typeof(\ud835\udc12[1].y)([mattype(S.y[first(frange)]) for S \u2208 \ud835\udc12]) :\n                      [typeof(\ud835\udc12[1].y)([mattype(S.y[i]) for i\u2208frange]) for S \u2208 \ud835\udc12]\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\u2208frange))\n\n_mean(\ud835\udc12::SpectraVector, frange::UnitRange{Int64}) =\n    size(\ud835\udc12[1].y, 2)==1 ? [mean(view(S.y, frange, 1)) for S \u2208 \ud835\udc12] :\n                         [[mean(view(S.y, frange, k)) for k=1:size(S.y, 2)] for S \u2208 \ud835\udc12]\n\n_mean(\ud835\udc12::Union{CrossSpectraVector, CoherenceVector}, frange::UnitRange{Int64}) =\n    typeof(\ud835\udc12[1].y)([_mean(S, frange) for S \u2208 \ud835\udc12])\n\n\"\"\"\n```\n(1)\nfunction extract(S :: FDobjects,\n            frange :: fInterval)\n\n(2)\nfunction extract(\ud835\udc12 :: 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(\ud835\udc80 :: 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\u00b9|\n|(1.2)| [CrossSpectra](@ref)          | a vector of complex matrices holding the cross-spectra in `frange`\u00b2|\n|(1.3)| [Coherence](@ref)             | a vector of real matrices holding the coherence in `frange`\u00b2|\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: \u00b9 *each column refers to a time-series on which the spectra have been computed.*\n\u00b2 *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\u03a3=spectra(v, sr, t)\n# spectra in between 8Hz and 12Hz\ns=extract(\u03a3, (8, 12))\n# spectra in between 8Hz and 12.5Hz\ns=extract(\u03a3, (8, 12.5))\n# spectra at 10Hz\ns=extract(\u03a3, 10) # or s=extract(S, (10, 10))\n# these two expressions are equivalent: s=extract(\u03a3, :), s=\u03a3.y\n\n# example with multivariate spectra (several series -> several spectra)\n\u03a3=spectra(hcat(v, v+randn(t*16)), sr, t)\n# spectra in between 8Hz and 12Hz\nS=extract(\u03a3, (8, 12))\n# spectra at 10Hz\nS=extract(\u03a3, 10)\n\n# example with CrossSpectra objects (the same goes for Coherence objects)\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\n\u03a3=crossSpectra(X, sr, t)\n# cross-spectra in between 8Hz and 12Hz (Hermitian matrices)\nS=extract(\u03a3, (8, 12))\n\u03a3=crossSpectra(X, sr, t; tril=true)\n# cross-spectra in between 8Hz and 12Hz (LowerTriangular matrices)\nS=extract(\u03a3, (8, 12))\n\n# example with multiple cross-spectra\nX2=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\n\u03a3=crossSpectra([X, X2], sr, t) # this is a CrossSpectraVector\nS=extract(\u03a3, (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\")) \u2260 0\n        return _extract(S, _frange)\n    end\n\nextract(\ud835\udc12::FDobjectsVector, frange::fInterval;\n        w::Vector=[], check::Bool=true) =\n    if (_frange=_getfrange(\ud835\udc12, frange, \"extract\"; check=check)) \u2260 0\n        return isempty(w) ? [_extract(S, _frange) for S \u2208 \ud835\udc12] :\n                            [\u03c9*_extract(S, _frange) for (\u03c9, S) \u2208 zip(w, \ud835\udc12)]\n    end\n\n\n\"\"\"\n```\n(1)\nfunction mean(S :: FDobjects,\n         frange :: fInterval)\n\n(2)\nfunction mean(\ud835\udc12 :: 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(\ud835\udc80 :: 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`\u00b9|\n|(1.2)| [CrossSpectra](@ref)           | a complex matrix holding the mean cross-spectra in `frange`\u00b2|\n|(1.3)| [Coherence](@ref)              | a real matrix holding the mean coherence in `frange`\u00b2|\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: \u00b9*each element of the vector refers to a time-series on which the spectra have been computed.*\n\u00b2 *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\u03a3=spectra(v, sr, t)\n# mean spectrum in between 8Hz and 12Hz\ns=mean(\u03a3, (8, 12))\n# mean spectrum in between 8Hz and 12.5Hz\ns=mean(\u03a3, (8, 12.5))\n\n# example with multivariate spectra (several series -> several spectra)\n\u03a3=spectra(hcat(v, v+randn(t*16)), sr, t)\n# mean spectra in between 8Hz and 12Hz\nS=mean(\u03a3, (8, 12))\n# mean spectra at 10Hz, i.e., the spectra at 10Hz\nS=mean(\u03a3, 10)\n\n# example with CrossSpectra objects (the same goes for Coherence objects)\nX=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\n\u03a3=crossSpectra(X, sr, t)\n# mean cross-spectra in between 8Hz and 12Hz (an Hermitian matrix)\nS=mean(\u03a3, (8, 12))\n\u03a3=crossSpectra(X, sr, t; tril=true)\n# mean cross-spectra in between 8Hz and 12Hz (a LowerTriangular matrix)\nS=mean(\u03a3, (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\u03a3=crossSpectra([X, X2], sr, t) # this is a CrossSpectraVector\nS=mean(\u03a3, (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(\u03a3, (8, 12), (1, 64))\n# mean analytic signal within frequencies 8Hz and 12Hz.\nas=mean(\u03a3, (8, 12), :)\n# mean analytic signal within time samples 1 to 64.\nas=mean(\u03a3, :, (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\")) \u2260 0\n        return _mean(S, _frange)\n    end\n\nmean(\ud835\udc12::FDobjectsVector, frange::fInterval;\n     w::Vector=[], check::Bool=true) =\n    if (_frange=_getfrange(\ud835\udc12, frange, \"mean\"; check=check)) \u2260 0\n        return isempty(w) ? [_mean(S, _frange) for S \u2208 \ud835\udc12] :\n                            [\u03c9*_mean(S, _frange) for (\u03c9, S) \u2208 zip(w, \ud835\udc12)]\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\u2208Y.flabels])[2])):min(length(Y.flabels), (findmin([abs(f-frange)  for f\u2208Y.flabels])[2]))) :\n            @error \ud83d\udccc*\", \"*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 \ud83d\udccc*\", \"*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 \ud83d\udccc*\", \"*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\u2208Y.flabels])[2])):min(length(Y.flabels), (findmin([abs(f-frange[2])  for f\u2208Y.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 \ud83d\udccc*\", \"*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 \ud83d\udccc*\", \"*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 \ud83d\udccc*\", \"*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 \u2260 0 && _trange \u2260 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 \u2260 0 && _trange \u2260 0\n        return mean(view(Y.y, _frange, _trange))\n    end\nend\n\n_getftrange(\ud835\udc80::TFobjectsVector, frange::fInterval, trange::tInterval, funcname::String;\n            check::Bool=true) =\n    check ? (sameParams(\ud835\udc80, funcname) ? _getftrange(\ud835\udc80[1], frange, trange, funcname) : 0) :\n    _getftrange(\ud835\udc80[1], frange, trange, funcname)\n\nextract(\ud835\udc80::TFobjectsVector, frange::fInterval, trange::tInterval;\n        w::Vector=[], check::Bool=true) =\n    if      check && frange isa Colon && !_allsame([size(Y.y, 1) for Y \u2208 \ud835\udc80])\n            @error \ud83d\udccc*\", 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 \u2208 \ud835\udc80])\n            @error \ud83d\udccc*\", 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(\ud835\udc80, frange, trange, \"extract\"; check=check)) \u2260 (0, 0)\n            if _isnull(_frange, _trange)\n                isempty(w) ? [Y.y[first(_frange), first(_trange)] for Y \u2208 \ud835\udc80] :\n                             [\u03c9*Y.y[first(_frange), first(_trange)] for (\u03c9, Y) \u2208 zip(w, \ud835\udc80)]\n            else\n                isempty(w) ? [Y.y[_frange, _trange] for Y \u2208 \ud835\udc80] :\n                             [\u03c9*Y.y[_frange, _trange] for (\u03c9, Y) \u2208 zip(w, \ud835\udc80)]\n            end\n    end\n\n\nmean(\ud835\udc80::TFobjectsVector, frange::fInterval, trange::tInterval;\n     w::Vector=[], check::Bool=true) =\n    if      check && frange isa Colon && !_allsame([size(Y.y, 1) for Y \u2208 \ud835\udc80])\n            @error \ud83d\udccc*\", 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 \u2208 \ud835\udc80])\n            @error \ud83d\udccc*\", 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(\ud835\udc80, frange, trange, \"mean\"; check=check)) \u2260 (0, 0)\n            return isempty(w) ? [mean(view(Y.y, _frange, _trange)) for Y \u2208 \ud835\udc80] :\n                                [\u03c9*mean(view(Y.y, _frange, _trange)) for (\u03c9, Y) \u2208 zip(w, \ud835\udc80)]\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\u03a3=spectra(v, sr, t)\n# mean spectra in 2Hz-band-pass regions\nb=bands(\u03a3, 2)\nplot(b)\n\n# example with multivariate spectra (several series -> several spectra)\n\u03a3=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(\u03a3, 2)\nplot(b)\n# plot mean spectra in 2Hz-band-pass regions for time-series 2 and 3 only\nplot(bands(\u03a3, 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\u03a3=crossSpectra(X, sr, t)\n# mean cross-spectra in 4Hz-band-pass regions\nB=bands(\u03a3, 4)\n\n# example with multiple CrossSpectra objects\nX2=broadcast(+, v, randn(t*16, 3))*randn(3, 3)\n\u03a3=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(\u03a3, 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(\ud835\udc12::SpectraVector, bandwidth::IntOrReal) =\n    [bands(S, bandwidth) for S \u2208 \ud835\udc12] # 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(\ud835\udc12::Union{CrossSpectraVector, CoherenceVector}, bandwidth::IntOrReal) =\n    [bands(S, bandwidth) for S \u2208 \ud835\udc12] # 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(\u23e9, n)\n    thr = nthreads() # of threads Julia is instructed to use\n    \u23e9 && 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    \u03b1 = zeros(T, n-1)\n    for i = 2:n-1\n        \u03b1[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    \u03bc = 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]*\u03bc[i-1]\n        \u03bc[i] = h[i]/l[i]\n        z[i] = (\u03b1[i] - h[i-1]*z[i-1])/l[i]\n    end\n    for j = n-1:-1:1\n        c[j] = z[j] - \u03bc[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\u2081, dy\u2099, 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\u2081` and `dy\u2099`.\n\"\"\"\nfunction CubicSplineInterpolator(x,\n                                 y,\n                                 dy\u2081::Real,\n                                 dy\u2099::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    \u03b1 = zeros(T, n)\n    \u03b1[1] = 3*(a[2] - a[1])/h[1] - 3*dy\u2081\n    for i = 2:n-1\n        \u03b1[i] = 3*(a[i+1] - a[i])/h[i] - 3*(a[i] - a[i-1])/h[i-1]\n    end\n    \u03b1[n] = 3*dy\u2099 - 3*(a[n] - a[n - 1])/h[n-1]\n    c = zeros(T, n)\n    l = zeros(T, n)\n    \u03bc = zeros(T, n)\n    z = zeros(T, n)\n    l[1] = 2*h[1]\n    \u03bc[1] = 0.5\n    z[1] = \u03b1[1]/l[1]\n    for i = 2:n-1\n        l[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*\u03bc[i-1]\n        \u03bc[i] = h[i]/l[i]\n        z[i] = (\u03b1[i] - h[i-1]*z[i-1])/l[i]\n    end\n    l[n] = h[n-1]*(2 - \u03bc[n-1])\n    z[n] = (\u03b1[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] - \u03bc[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 (\u03d5::CubicSplineInterpolator)(x)\n    #enforce boundaries if desired\n    \u03d5.boundaries(x, \u03d5.r.xa, \u03d5.r.xb)\n    #find the interpolation point\n    i = findcell(x, \u03d5)\n    #offset from the nearest lower point\n    @inbounds \u03be = x - \u03d5.r.x[i]\n    #evaluate polynomial\n    @inbounds \u03d5.coef[i][1] + \u03d5.coef[i][2]*\u03be + \u03d5.coef[i][3]*\u03be^2 + \u03d5.coef[i][4]*\u03be^3\nend\n\nBase.getindex(\u03d5::CubicSplineInterpolator, i) = \u03d5.r.y[i]\nfunction Base.copy(\u03d5::CubicSplineInterpolator)\n    CubicSplineInterpolator(\u03d5.r, \u03d5.coef, \u03d5.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] \u2ab0 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": "using RDatasets, Clustering, Random, LinearAlgebra, Plots; pyplot()\nRandom.seed!(0)\n\ndf = dataset(\"cluster\", \"xclara\")\nn,_ = size(df)\ndataPoints = [convert(Array{Float64,1},df[i,:]) for i in 1:n]\nshuffle!(dataPoints)\nD = [norm(pt1 - pt2) for pt1 in dataPoints, pt2 in dataPoints]\n\nresult = hclust(D)\nfor K in 1:30\n    clusters = cutree(result,k=K)\n    println(\"K=$(K): \",[sum(clusters .== i) for i in 1:K])\nend\n\ncluster(ell,K) = (1:n)[cutree(result,k=K) .== ell]\n\nC1, C2, C3 = cluster(1,30),cluster(2,30),cluster(3,30)\n\nplt = scatter( first.(dataPoints[C1]),last.(dataPoints[C1]),c=:blue, msw=0)\n      scatter!( first.(dataPoints[C2]),last.(dataPoints[C2]), c=:red, msw=0)\n      scatter!( first.(dataPoints[C3]),last.(dataPoints[C3]), c=:green, msw=0)\nfor ell in 4:30\n    clst = cluster(ell,30)\n    scatter!(first.(dataPoints[clst]),last.(dataPoints[clst]), \n        ms=10, c=:purple, shape=:xcross, ratio=:equal, legend=:none,\n        xlabel=\"V1\", ylabel=\"V2\")\nend\nplot(plt)", "meta": {"hexsha": "5626130b7c5b6f032dd2f1f7ba3761f11bd56a45", "size": 975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "9_chapter/hClustering.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": "9_chapter/hClustering.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": "9_chapter/hClustering.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.6206896552, "max_line_length": 78, "alphanum_fraction": 0.6441025641, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862454, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7970526907765365}}
{"text": "T = 250\n\u03a3 = [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(\u03a3).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, \u03a3, 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.\u03bc[:, 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.\u03bc[:, 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\u03b2: 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                           \u03b2::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) - \u03b2 * 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                          \u03b2::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, \u03b2, 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": "## Test discretize given edges\nfunction discretize_test()\n\t@testset \"Discretize\" begin\n        n = 55;\n        inV = collect(range(1, 10, length = n));\n        edgeV = [0.0, 6.0, 11.0];\n        outV = discretize(inV, edgeV);\n\t\t@test all(outV[inV .< edgeV[1]] .== 0)\n\t\t@test all(outV[inV .> edgeV[end]] .== 0)\n\n\t\tfor ix = 1 : n\n\t\t\tiCl = outV[ix];\n\t\t\tif iCl > 0\n\t\t\t\t@test inV[ix] >= edgeV[iCl]  &&  inV[ix] <= edgeV[iCl+1]\n\t\t\telse\n\t\t\t\t@test inV[ix] <= edgeV[1]  ||  inV[ix] >= edgeV[end]\n\t\t\tend\n\t\tend\n\tend\nend\n\n\n## Test bin edges (unweighted)\nfunction bin_edges_test()\n    @testset \"Bin edges\" begin\n        n = 450;\n        inV = collect(range(-4.0, 3.0, length = n));\n        pctV = [0.25, 0.4, 0.85];\n        edgeV = bin_edges_from_percentiles(inV, pctV);\n        @test length(edgeV) == (length(pctV) + 1)\n        \n        # test that fractions match target\n        cntV = count_bins(inV, edgeV);\n        @test sum(cntV) == round(n * pctV[end])\n        fracV = cntV ./ n;\n        tgFracV = diff(vcat(0.0, pctV));\n        @test isapprox(fracV, tgFracV, atol = 2/n)\n    end\nend\n\n\n## Test bin edges (weighted)\nfunction bin_edges_weighted_test()\n    @testset \"Bin edges weighted\" begin\n        n = 450;\n        inV = collect(range(-4.0, 3.0, length = n));\n        # FrequencyWeights must be integers\n        wtV = collect(range(0.2, 0.8, length = n));\n        pctV = [0.25, 0.4, 0.85];\n        edgeV = bin_edges_from_percentiles(inV, wtV, pctV);\n        @test length(edgeV) == (length(pctV) + 1)\n\n        # test that fractions below edges match target \n        massV = count_bins(inV, wtV, edgeV);\n        @test sum(massV) \u2248 sum(wtV[inV .<= edgeV[end]])\n        fracV = massV ./ sum(wtV);\n        tgFracV = diff(vcat(0.0, pctV));\n        @test isapprox(fracV, tgFracV, atol = 2/n)\n    end\nend\n\n\n## Discretize given percentiles\nfunction discretize_given_percentiles_test()\n\t@testset \"discretize_given_percentiles\" begin\n        n = 38;\n        inV = collect(range(1.0, 5.0, length = n));\n        pctV = [0.25, 0.4, 0.85, 1.0];\n        classV = discretize_given_percentiles(inV, pctV);\n\t\t@test all(classV .>= 1);\n\t\t@test all(classV .<= length(pctV));\n\tend\nend\n\n\n## Discretize (weighted)\nfunction discretize_given_pct_weighted_test()\n    @testset \"discretize pct weighted\" begin\n        n = 38;\n        inV = collect(range(1.0, 5.0, length = n));\n        wtV = collect(range(0.1, 0.5, length = n));\n        pctV = [0.25, 0.4, 0.85, 1.0];\n        classV = discretize_given_percentiles(inV, wtV, pctV);\n\t    @test all(classV .>= 1);\n\t    @test all(classV .<= length(pctV));\n    end\nend\n\n\n@testset \"Discretize\" begin\n   discretize_test()\n   discretize_given_pct_weighted_test();\n   bin_edges_test();\n   bin_edges_weighted_test();\n   discretize_given_percentiles_test()\nend\n\n\n# ----------------", "meta": {"hexsha": "01a25d6a5de7a8984ace9dc270840f4cf2a08361", "size": 2784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/statistics/discretize_test.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": "test/statistics/discretize_test.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": "test/statistics/discretize_test.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.1212121212, "max_line_length": 62, "alphanum_fraction": 0.5818965517, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.7970433184685242}}
{"text": "function MapFeature(X1,X2,d)\r\n\r\n    m=size(X1,1)\r\n    n=((d+d^2)/2)+d\r\n\r\n    p=zeros(m,round(Int,n))\r\n    count=0\r\n    for i =1:d\r\n        for j=0:i\r\n            count=count+1\r\n            p[:,count]=(X1.^(i-j)).*(X2.^j)\r\n        end\r\n    end\r\n\r\n    return p\r\nend\r\n\r\n\r\nfunction PolyFeature(X,d)\r\n\r\n    m=size(X,1)\r\n    n=size(X,2)\r\n    p=zeros(m,d*n)\r\nc=0\r\nfor j=1:n\r\n    for i=1:d\r\n        c=c+1\r\n        p[:,c]=X[:,j].^i\r\n    end\r\nend\r\n    return p\r\n\r\nend\r\n", "meta": {"hexsha": "34fe0c4cbac11690742cc91578a1763400b124fd", "size": 459, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PolyFeatures.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/PolyFeatures.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/PolyFeatures.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": 13.5, "max_line_length": 44, "alphanum_fraction": 0.4204793028, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.872347369700144, "lm_q1q2_score": 0.7970433160577501}}
{"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    \u03b1 ~ Normal(0, 10)\n    \u03b2p ~ Normal(0, 1)\n\n    # Separate \u03c3 priors for each society\n    \u03c3_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    \u03b1_society = Vector{Real}(undef, N_society)\n\n    # For each society [1,..,10] set a prior N(0, \u03c3_society)\n    \u03b1_society ~ [Normal(0, \u03c3_society)]\n\n    for i \u2208 1:N\n        \u03bb = exp(\u03b1 + \u03b1_society[society[i]] + \u03b2p*log_pop[i])\n        total_tools[i] ~ Poisson(\u03bb)\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\u0302 = calc_b_hat(A, c)\n    else\n        b\u0302 = zeros(BigFloat, s + 1) .+ NaN\n    end\n    return A, b, c, bi, b\u0302\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    \u03ba(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(\u03ba::MahalanobisKernel, d::T) where {T<:Real} = exp(-d)\n\nmetric(\u03ba::MahalanobisKernel) = SqMahalanobis(\u03ba.P)\n\nBase.show(io::IO, \u03ba::MahalanobisKernel) = print(io, \"Mahalanobis Kernel (size(P) = \", size(\u03ba.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, \u03b7)\n    @showprogress for idx in 1:1000\n        grads = ForwardDiff.gradient(s -> loss(s), vel_opt) # Magic\n        vel_opt .-= \u03b7*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, \u03b7)\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 .-= \u03b7*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# \u222b erf(b-y)/(sqrt(2)*\u2113), y\u2208[c,d]\n#\n# Wolfram code: Integrate[erf(b-y)/(sqrt(2)*\u2113), {y, c, d}]\n#\n\nfunction sub_1(; b = b, c = c, d = d, \u2113 = \u2113)\n\n    @assert(c < d)\n\n    sqrt(2/\u03c0) * \u2113 * ( exp(-(b - c)^2/(2 * \u2113^2)) - exp(-(b - d)^2/(2 * \u2113^2))) +\n        (b - c) * erf((b - c)/(sqrt(2) * \u2113)) +\n        (d - b) * erf((b - d)/(sqrt(2) * \u2113))\n\n\nend\n\n\nfunction verify_sub_1(; b = b, c = c, d = d, \u2113 = \u2113)\n\n    # integrand\n    f(y) = erf((b-y)/(sqrt(2)*\u2113))\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, \u2113 = \u2113),\n    h.integral[1],\n    hc[1],\n    num\n\nend\n\n\n\n\n#\n# Evaluates definite integral\n# \u222b\u222b exp(- (x-y)\u00b2 / (2\u2113\u00b2) ) dx dy, x\u2208[a,b], y\u2208[c,d]\n#\n# Wolfram code: Integrate[E^(-(x - y)^2/(2 (\u2113^2))), {x, a, b}]\n#\n\nfunction integralfunction_1(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, \u2113 = \u2113)\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 \u222b exp(- (x-y)\u00b2 / (2\u2113\u00b2) ) dx  x\u2208[a,b] is:\n    # sqrt(\u03c0/2) r (erf((b - y)/(sqrt(2) \u2113)) - erf((a - y)/(sqrt(2) \u2113)))\n    # We need to carry out the second integral over y.\n    # The result of this second integral over y is:\n\n    sqrt(\u03c0/2) * \u2113 * (sub_1(b=b, c=c, d=d, \u2113=\u2113) - sub_1(b=a, c=c, d=d, \u2113=\u2113))\n\nend\n\n\n#\n# Verification: numerical evaluation for definite integral\n# \u222b\u222b exp(- (x-y)\u00b2 / (2\u2113\u00b2) ) dx dy, x\u2208[a, b], y\u2208[c, d]\n#\n\nfunction verify_1(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, \u2113 = \u2113)\n\n    @assert(lowerx < upperx)\n    @assert(lowery < uppery)\n\n    # intergrand\n    f(x,y) =  exp(-(x-y)^2 / (2*(\u2113^2)))\n\n\n    # numerical verification on regular grid\n    \u0394x = 1e-3\n    X  = lowerx:\u0394x:upperx\n    Y  = lowery:\u0394x: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 *= \u0394x^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, \u2113 = \u2113), num, h.integral[1]\n\nend\n\n\n\n################################################################################\n################################################################################\n################################################################################\n\n\n\n#\n# Evaluates definite integral\n# \u222b exp(- (a-y)\u00b2 / (2\u2113\u00b2) ) dy,  y \u2208 [c, d]\n#\nfunction sub_2a(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    # Wolfram code: Integrate[E^(-(a - y)^2/(2 \u2113^2)), {y, c, d}]\n    # Solution returned in plain text:\n    # integral_c^d e^(-(a - y)^2/(2 \u2113^2)) dy = sqrt(\u03c0/2) r (erf((a - c)/(sqrt(2) \u2113)) - erf((a - d)/(sqrt(2) \u2113)))\n\n    sqrt(\u03c0/2) * \u2113 * (erf((a - c)/(sqrt(2) * \u2113)) - erf((a - d)/(sqrt(2) * \u2113)))\n\nend\n\n\n#\n# Verifies definite integral\n# \u222b exp(- (a-y)\u00b2 / (2\u2113\u00b2) ) dy,  y \u2208 [c, d]\n#\nfunction verify_sub_2a(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    f(y) = exp(-(a-y)^2/(2*\u2113^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, \u2113 = \u2113),\n    h.integral[1],\n    num\n\nend\n\n\n#\n# Evaluates definite integral\n# \u222b y erf((a-y)/(sqrt(2)\u2113) dy,  y \u2208 [c, d]\n#\nfunction sub_2b(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    # Wolfram code: Integrate[y Erf[(a - y)/(Sqrt[2] \u2113)], {y, c, d}]\n    # Solution returned in plain text:\n    # integral_c^d y erf((a - y)/(sqrt(2) \u2113)) dy = 1/2 (a^2 - c^2 + \u2113^2) erf((a - c)/(sqrt(2) \u2113)) - 1/2 (a^2 - d^2 + \u2113^2) erf((a - d)/(sqrt(2) \u2113)) + (\u2113 (a + c) e^(-(a - c)^2/(2 \u2113^2)))/sqrt(2 \u03c0) - (\u2113 (a + d) e^(-(a - d)^2/(2 \u2113^2)))/sqrt(2 \u03c0)\n\n    1/2 * (a^2 - c^2 + \u2113^2) * erf((a - c)/(sqrt(2) * \u2113)) -\n    1/2 * (a^2 - d^2 + \u2113^2) * erf((a - d)/(sqrt(2) * \u2113)) +\n    (\u2113 * (a + c) * exp(-(a - c)^2/(2 * \u2113^2)))/sqrt(2*\u03c0) - (\u2113*(a + d) * exp(-(a - d)^2/(2*\u2113^2)))/sqrt(2\u03c0)\n\n\nend\n\n\n#\n# Verifies definite integral\n# \u222b y erf((a-y)/(sqrt(2)\u2113) dy,  y \u2208 [c, d]\n#\nfunction verify_sub_2b(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    f(y) = y * erf((a-y)/(sqrt(2)*\u2113))\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, \u2113 = \u2113),\n    h.integral[1],\n    num\n\n\nend\n\n\n\n#\n# Evaluates definite integral\n# \u222b\u222b x exp(- (x-y)\u00b2 / (2\u2113\u00b2) ) dx dy, x\u2208[a, b], y\u2208[c, d]\n#\nfunction integralfunction_2(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, \u2113 = \u2113)\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 \u222b\u1d47\u2090 x exp(-(x-y)^2 / (2\u2113\u00b2)) dx is\n    # integral_a^b x e^(-(x - y)^2/(2 \u2113^2)) dx = 1/2 \u2113 (2 \u2113 (e^(-(a - y)^2/(2 \u2113^2)) - e^(-(b - y)^2/(2 \u2113^2))) - sqrt(2 \u03c0) y erf((a - y)/(sqrt(2) \u2113)) + sqrt(2 \u03c0) y erf((b - y)/(sqrt(2) \u2113)))\n    # (Wolfram code: Integrate[x * E^(-((x - y)^2)/(2*\u2113^2)), {x, a, b}]\n    #\n\n    #1/2 * \u2113 *(2*\u2113 * (exp(-(a - y)^2/(2*\u2113^2)) - exp(-(b - y)^2/(2*\u2113^2))) -\n    #          sqrt(2\u03c0) * y * erf((a - y)/(sqrt(2)*\u2113)) + sqrt(2\u03c0) * y * erf((b - y) /(sqrt(2)*\u2113)))\n\n    1/2 * \u2113 *(2*\u2113 * (sub_2a(a=a, c=c, d=d, \u2113=\u2113) - sub_2a(a=b, c=c, d=d, \u2113=\u2113)) -\n              sqrt(2\u03c0) * (sub_2b(a = a, c = c, d = d, \u2113 = \u2113) -  sub_2b(a = b, c = c, d = d, \u2113 = \u2113)))\n\n\nend\n\n\n\nfunction verify_2(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, \u2113 = \u2113)\n\n    f(x,y) =  x * exp(- (x-y)^2 / (2*\u2113^2) )\n\n    # numerical verification on regular grid\n    \u0394x = 1e-3\n    X  = lowerx:\u0394x:upperx\n    Y  = lowery:\u0394x: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 *= \u0394x^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, \u2113 = \u2113), num, h.integral[1]\n\nend\n\n\n\n################################################################################\n################################################################################\n################################################################################\n\n#\n# Evaluate integral:\n# \u222b y\u00b2 erf( (a-y) / (sqrt(2) \u2113) ) dy\n#\n\nfunction sub_3a(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    # Wolram code: Integrate[y^2 Erf[(a - y)/(Sqrt[2] \u2113)], {y, c, d}]\n    #\n    # solution:\n    # integral_c^d y y erf((a - y)/(sqrt(2) \u2113)) dy = 1/3 (-(a^3 + 3 a \u2113^2) erf((c - a)/(sqrt(2) \u2113)) + (a^3 + 3 a \u2113^2) erf((d - a)/(sqrt(2) \u2113)) + sqrt(2/\u03c0) \u2113 e^(-(a - c)^2/(2 \u2113^2)) (a^2 + a c + c^2 + 2 \u2113^2) - sqrt(2/\u03c0) \u2113 e^(-(a - d)^2/(2 \u2113^2)) (a^2 + a d + d^2 + 2 \u2113^2) + c^3 (-erf((a - c)/(sqrt(2) \u2113))) + d^3 erf((a - d)/(sqrt(2) \u2113)))\n\n    1/3 * (-(a^3 + 3*a*\u2113^2) * (erf((c - a)/(sqrt(2)*\u2113)) - erf((d - a)/(sqrt(2)*\u2113))) +\n              sqrt(2/\u03c0) * \u2113 * (exp(-(a - c)^2/(2 * \u2113^2)) * (a^2 + a * c + c^2 + 2 * \u2113^2) -\n                               exp(-(a - d)^2/(2 * \u2113^2)) * (a^2 + a * d + d^2 + 2 * \u2113^2)) +\n          c^3 * (-erf((a - c)/(sqrt(2) * \u2113))) + d^3 * erf((a - d)/(sqrt(2) * \u2113)))\n\nend\n\n#\n# Verify integral:\n# \u222b y\u00b2 erf( (a-y) / (sqrt(2) \u2113) ) dy\n#\n\nfunction verify_sub_3a(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    f(y) = y^2 * erf( (a-y) / (sqrt(2) * \u2113) )\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, \u2113 = \u2113),\n    h.integral[1],\n    num\n\nend\n\n\n\n\n#\n# Evaluate integral:\n# \u222b y exp( -(a-y)\u00b2 / (2 \u2113\u00b2) ) dy\n#\n\nfunction sub_3b(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    # Wolram code: Integrate[y/E^((a - y)^2/(2 \u2113^2)), {y, c, d}]\n    #\n    # solution:\n    # integral_c^d y e^(-(a - y)^2/(2 \u2113^2)) dy = 1/2 \u2113 (2 \u2113 (e^(-(a - c)^2/(2 \u2113^2)) - e^(-(a - d)^2/(2 \u2113^2))) + sqrt(2 \u03c0) a erf((a - c)/(sqrt(2) \u2113)) - sqrt(2 \u03c0) a erf((a - d)/(sqrt(2) \u2113)))\n\n    1/2 * \u2113 * (2 * \u2113 * (exp(-(a - c)^2/(2*\u2113^2)) - exp(-(a - d)^2/(2*\u2113^2))) +\n            sqrt(2*\u03c0) * a * erf((a - c)/(sqrt(2)*\u2113)) - sqrt(2*\u03c0) * a * erf((a - d)/(sqrt(2)*\u2113)))\n\n\nend\n\n#\n# Verify integral:\n# \u222b y exp( -(a-y)\u00b2 / (2 \u2113\u00b2) ) dy\n#\n\nfunction verify_sub_3b(; a = a, c = c, d = d, \u2113 = \u2113)\n\n    f(y) = y * exp( -(a-y)^2 / (2 * \u2113^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, \u2113 = \u2113),\n    h.integral[1],\n    num\n\nend\n\n\n\n\n#\n# Evaluate integral:\n# \u222b\u222b y x exp(- (x-y)\u00b2 / (2\u2113\u00b2) ) dx dy, x\u2208[a, b], y\u2208[c, d]\n#\nfunction integralfunction_3(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, \u2113 = \u2113)\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: \u222b y x exp(- (x-y)\u00b2 / (2\u2113\u00b2) ) dx dy, x\u2208[a, b]\n    # Wolfram code: Integrate[(x y)/E^((x - y)^2/(2 \u2113^2)), {x, a, b}]\n    # solution:\n    # integral_a^b y x e^(-(x - y)^2/(2 \u2113^2)) dx = 1/2 \u2113 y (2 \u2113 (e^(-(a - y)^2/(2 \u2113^2)) - e^(-(b - y)^2/(2 \u2113^2))) - sqrt(2 \u03c0) y erf((a - y)/(sqrt(2) \u2113)) + sqrt(2 \u03c0) y erf((b - y)/(sqrt(2) \u2113)))\n    #\n    # We need to integrate the above solution over y y\u2208[c, d]\n\n    1/2 * \u2113 * (2 * \u2113 * (sub_3b(; a = a, c = c, d = d, \u2113 = \u2113) - sub_3b(; a = b, c = c, d = d, \u2113 = \u2113)) -\n                    sqrt(2*\u03c0) * sub_3a(; a = a, c = c, d = d, \u2113 = \u2113) +\n                    sqrt(2*\u03c0) * sub_3a(; a = b, c = c, d = d, \u2113 = \u2113))\n\nend\n\n\nfunction verify_3(; lowerx = lowerx, upperx = upperx, lowery = lowery, uppery = uppery, \u2113 = \u2113)\n\n    # integrand\n    f(x,y) =  y * x * exp(- (x-y)^2 / (2\u2113^2) )\n\n    # numerical verification on regular grid\n    \u0394x = 1e-3\n    X  = lowerx:\u0394x:upperx\n    Y  = lowery:\u0394x: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 *= \u0394x^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, \u2113 = \u2113), 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, \u22c5, \u00d7\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\u03c0 * floor((angle + \u03c0 - center) / 2\u03c0)\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 \u22c5 v2\n        threshold = normprod * 0.9999\n        if v1v2 >= -threshold && v1v2 <= threshold\n            return acos(v1v2 / normprod)\n        else\n            v3n = norm(v1 \u00d7 v2)\n            return v1v2 >= 0.0 ? (v3n / normprod) : \u03c0 - 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(\u03c8, \u03b4\u03c8, \u03b8, \u03b4\u03b8, \u03d5, \u03b4\u03d5)\n    \u03a9\u2081 = \u03b4\u03c8 * sin(\u03b8) * sin(\u03d5) - \u03b4\u03b8 * cos(\u03d5)\n    \u03a9\u2082 = \u03b4\u03c8 * sin(\u03b8) * cos(\u03d5) + \u03b4\u03b8 * sin(\u03d5)\n    \u03a9\u2083 = \u03b4\u03c8 * cos(\u03b8) + \u03b4\u03d5\n    [\u03a9\u2081, \u03a9\u2082, \u03a9\u2083]\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 \u2013 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": "using LightGraphs\nusing LinearAlgebra\nusing SparseArrays\nusing IterativeSolvers\nusing Plots\nusing GraphPlot\nusing ColorSchemes\n\nfunction network_automorphism_classes(g::SimpleGraph{<:Integer}; tol=1e-4)\n    r = lobpcg(float(adjacency_matrix((g))), true, 1, tol = 1e-10)\n    x = copy(r.X[:,1]) # get the dominant eigenvector\n    p = sortperm(x)\n    x .= x[p]\n    k = 1\n    classes = [[p[1]]]\n    for i in 2:length(x)\n        if abs(x[i]-x[i-1]) < tol\n            push!(classes[k], p[i])\n        else\n            k += 1\n            push!(classes, [p[i]])\n        end\n    end\n    return classes, r.X[:,1]\nend\n\nA = [0 1 1 0 0 0 0 0;\n     1 0 1 0 0 0 0 0;\n     1 1 0 1 1 1 0 0;\n     0 0 1 0 0 0 1 1;\n     0 0 1 0 0 0 1 1;\n     0 0 1 0 0 0 1 1;\n     0 0 0 1 1 1 0 0;\n     0 0 0 1 1 1 0 0\n    ]\n\ng = SimpleGraph(A)\ngplot(g)\n\ncs = network_automorphism_classes(g)\n\nfunction pairpermutation_matrix(n,i,j)\n    P = spzeros(Int64, n,n)\n    for k in 1:n\n        if k != i || k != j\n            P[k,k] = 1\n        end\n    end\n    P[i,j] = 1\n    P[j,i] = 1\n    return P\nend\n\nfunction checkclasses(g::SimpleGraph{<:Integer}, cs)\n    A = adjacency_matrix(g)\n    N = nv(g)\n    for c in cs\n        n = length(c)\n        if n > 1\n            for i in 2:n # NB incorrect test\n                P = pairpermutation_matrix(N,c[1],c[i])\n                if A != P*A*P\n                    return false\n                end\n            end\n        end\n    end\n    return true\nend\n\ncheckclasses(g, cs)\n\ng = graphfamous(\"karate\")\ncs, v = network_automorphism_classes(g)\nclasses = filter(c->length(c)>1, cs)\nallclasses = vcat(classes...)\nps = [(k,v[k]) for k in allclasses]\ncolors = ColorSchemes.Set1_4.colors;\nnodecols = fill(colorant\"lightgray\", nv(g));\nfor i in 1:length(classes), v in classes[i]\n    nodecols[v] = colors[i];\nend\ngplot(g, nodelabel=1:34, nodefillc = nodecols)\n\nA = float(adjacency_matrix(g))\n\u03bb, V = eigen(Array(A))\n[V[allclasses,i] for i in 1:34 if any(abs.(V[:,i]) .< 1e-6) ]\n\n", "meta": {"hexsha": "11a478a9826e1131835be6bcf25494b17f8dd797", "size": 1964, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "quotient_network.jl", "max_stars_repo_name": "csimal/GraphMorphisms.jl", "max_stars_repo_head_hexsha": "fdd5e9172dd58865be5502a014598b636187f007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quotient_network.jl", "max_issues_repo_name": "csimal/GraphMorphisms.jl", "max_issues_repo_head_hexsha": "fdd5e9172dd58865be5502a014598b636187f007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quotient_network.jl", "max_forks_repo_name": "csimal/GraphMorphisms.jl", "max_forks_repo_head_hexsha": "fdd5e9172dd58865be5502a014598b636187f007", "max_forks_repo_licenses": ["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.0674157303, "max_line_length": 74, "alphanum_fraction": 0.5529531568, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7968710800932967}}
{"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) \u2248 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\u03b1, \u03b2 = logweight_coefs(Float64, n+1, r)\nq = orthonormal_poly(x, \u03b1[1:n], \u03b2)\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\u00e9zout 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\u00fcrgen 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\u00fcrgen 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(\u03bb::Number, A::AbstractArray{T, N}, B::AbstractArray{T, N}, tol=0) where {T<:Number, N}\n    A = A - \u03bb*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(\u03bb::Number, P::AbstractArray, tol=0)\n    _, _, Ar, Br = colNullities(P, tol)\n    _, _, Ar, Br = rowNullities(Ar, Br, tol)\n    return eigNullities(\u03bb, 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": "using NumericalMethodsforEngineers\n\nA = [10. 1. -5.; -20. 3. 20.; 5. 3. 5.]\nb = [1., 2., 6.]\nn = size(A, 1)\nx = 0.0\n\n# Convert to upper triang;e\nfor k in 1:n-1\n  if abs(A[k, k]) > 1.0e-6\n    for i in k+1:n\n      x = A[i, k] / A[k, k]\n      A[i, k] = 0.0\n      for j in k+1:n\n        A[i, j] -= A[k, j] * x\n      end\n      b[i] -= b[k] * x\n    end\n  else\n    println(\"Zero pivot found in row $k\")\n  end\nend\n\nprintln(\"Modified Matrix\")\nA |> display\nprintln()\n\nfor i in n:-1:1\n  x = b[i]\n  if i < n\n    for j in i+1:n\n      x -= A[i, j] * b[j]\n    end\n  end\n  b[i] = x / A[i, i]\nend\n\nprintln(\"Solution vector:\")\nb |> display\nd = copy(b)\n\n# Restore A and b\nA = [10. 1. -5.; -20. 3. 20.; 5. 3. 5.]\nb = [1., 2., 6.]\n\nc = A\\b\n\nprintln()\n@test round(c, 14) == d\n@test round(A * c, 14) == b\n", "meta": {"hexsha": "ff75f2cbd24d151c505f99e5ced0c468bfa85688", "size": 782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/f_02_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/ch02/f_02_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/ch02/f_02_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.3333333333, "max_line_length": 41, "alphanum_fraction": 0.4731457801, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7968380527454864}}
{"text": "using ReverseDiffOverload\n\nconst v1 = randn(2)\nconst v2 = randn(2)\nconst v3 = randn(2)\nconst M  = randn(2, 2)\n\nimport ReverseDiffOverload.testdiff\ntestdiff(f::String, x) = begin\n    println(f)\n    testdiff(eval(parse(\"x -> $f\")), x)\nend\ntestdiff(f::String, x, y) = begin\n    println(f)\n    testdiff(eval(parse(\"(x, y) -> $f\")), x, y)\nend\n#dot\ntestdiff(\"dot(v1, x)\", v2)\ntestdiff(\"dot(x, y)\", [1., 2.], [3., 4.])\n\n#+\ntestdiff(\"x+y\", 1., 2.)\ntestdiff(\"dot(v1, x+y)\", v2, v3)\ntestdiff(\"dot(v1, x+y)\", 1., v2)\n\n#-\ntestdiff(\"x+(-y)\", 1., 2.)\ntestdiff(\"x-y\", 1., 2.)\ntestdiff(\"dot(v1, x-y)\", v2, v3)\ntestdiff(\"dot(v1, x-y)\", 1., v2)\ntestdiff(\"dot(v1, -x)\", v2)\n\n#*\ntestdiff(\"x*y\", 3., 4.)\ntestdiff(\"dot(v1, x'*y)\", M, v2)\ntestdiff(\"sum(x*y)\", v1', M)\ntestdiff(\"dot(v1, x*y)\", M, v2)\ntestdiff(\"dot(v1, x*y)\", randn(), v2)\n\n#/\ntestdiff(\"dot(v1, x\\\\y)\", M, v2)\ntestdiff(\"dot(v1, vec(x/y))\", v2', M)\ntestdiff(\"x+x*x*exp(x)\", 2.)\n\n#.^\ntestdiff(\"x .^ y\", 2.5, 3.5)\ntestdiff(\"x .^ y\", 2.5, -3.5)\ntestdiff(\"dot(v1, x .* y)\", v2, v3)\ntestdiff(\"dot(v1, x .^ y)\", [1., 2.], [3., 4.])\n\n#'\ntestdiff(\"first(y'*x*y)\", [1. 2;3 4], [5.,6]'')\n#matrix funcs\ntestdiff(\"det(x)\", [1. 2;3 4])\ntestdiff(\"trace(x)\", [1. 2;3 4])\ntestdiff(\"det(inv(x))\", [1. 2;3 4])\ntestdiff(\"sum(x)\", [1., 2., 3.])\ntestdiff(\"dot([1.1, 2.1], vec(x))\", [5. 6])\n\ntestdiff(\"dot(v1, exp(x))\", v2)\ntestdiff(\"dot(v1, sin(x))\", v2)\ntestdiff(\"dot(v1, cos(x))\", v2)\n\ntestdiff(\"sum(exp(x.*v1))\", v2)\n\ntestdiff(\"sum(x./y)\", v2, v3)\n\ntestdiff(\"sum(rectlin(M*x))\", v1)\ntestdiff(\"log\u0393(x)\", 3)\ntestdiff(\"log\u0393(x)\", 3)\ntestdiff(\"getindex(x, 2)\", ones(3))\ntestdiff(\"first(v1'*sum(x, 2))\", randn(2,2))\ntestdiff(\"first(sum(x, 1)*v1)\", randn(2,2))\n", "meta": {"hexsha": "0101b38eea961794ac11c6ffc9dfceb29df3d0e5", "size": 1677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test.jl", "max_stars_repo_name": "JuliaPackageMirrors/ReverseDiffOverload.jl", "max_stars_repo_head_hexsha": "15a1fdd167a4a441a948e4e2914de08565fe37cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-11-03T21:24:22.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-28T12:59:05.000Z", "max_issues_repo_path": "test/test.jl", "max_issues_repo_name": "JuliaPackageMirrors/ReverseDiffOverload.jl", "max_issues_repo_head_hexsha": "15a1fdd167a4a441a948e4e2914de08565fe37cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-04T18:46:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:26:27.000Z", "max_forks_repo_path": "test/test.jl", "max_forks_repo_name": "JuliaPackageMirrors/ReverseDiffOverload.jl", "max_forks_repo_head_hexsha": "15a1fdd167a4a441a948e4e2914de08565fe37cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:16:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:20:01.000Z", "avg_line_length": 22.6621621622, "max_line_length": 47, "alphanum_fraction": 0.5527728086, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.7967862305788466}}
{"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        \u03a9 = 1/sqrt(n) * randn(n, r)\n        Y = A * \u03a9\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 (\u03b8) cos (\u03b8)\n\n\n#Makie\nusing CairoMakie\nlet\n    x = -2\u03c0:0.1:2\u03c0\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 \u03b8\",\n      color = :paleturquoise4)\n    lines!(x, sin.(x); linewidth = 3, linestyle = :dot, label = L\"sin \u03b8\",\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\u03c0), ylims = (-1, 1), c=[:black, :magenta], marker=:circle, linewidth= 2, label = \"sin \u03b8\")\np = Plots.plot!([cos], zeros(0), xlims = (0, 2\u03c0), ylims = (-1, 1), c=[:cyan, :black], marker=:hexagon, linewidth= 2,  label = \"cos \u03b8\")\nfor x = range(0, stop = 2\u03c0, 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": "import GreyDecision.GreyNumbers: GreyNumber\nimport GreyDecision.Utility: makeminmax\nimport LinearAlgebra: det\n\n\n@testset \"Transpose\" begin\n    x = [\n        GreyNumber(5.0) GreyNumber(3.0) GreyNumber(-2.0);\n        GreyNumber(-8.0) GreyNumber(6.0) GreyNumber(1.0);\n        GreyNumber(10.0) GreyNumber(7.0) GreyNumber(13.0)\n    ]\n    xt = transpose(x)\n\n    @test size(xt) == size(x)\n    @test xt[1, 2] == x[2, 1]\n    @test xt[1, 3] == x[3, 1]\n    @test xt[1, 1] == x[1, 1]\n    @test xt[2, 2] == x[2, 2]\n    @test xt[3, 3] == x[3, 3]\nend\n\n@testset \"det(x)\" begin\n    x = [\n        GreyNumber(5.0) GreyNumber(3.0) GreyNumber(-2.0);\n        GreyNumber(-8.0) GreyNumber(6.0) GreyNumber(1.0);\n        GreyNumber(10.0) GreyNumber(7.0) GreyNumber(13.0)\n    ]\n    y = [\n        5.0 3.0 -2.0;\n        -8.0 6.0 1.0;\n        10.0 7.0 13.0\n    ]\n    xdet = det(transpose(x) * x) \n    ydet = det(transpose(y) * y)\n    \n    @test ydet == xdet.a \n    @test ydet == xdet.b\nend\n\n@testset \"inv(x)\" begin\n    atol = 0.001\n     x = [\n        GreyNumber(5.0) GreyNumber(3.0) GreyNumber(-2.0);\n        GreyNumber(-8.0) GreyNumber(6.0) GreyNumber(1.0);\n        GreyNumber(10.0) GreyNumber(7.0) GreyNumber(13.0)\n    ]\n    xtx = transpose(x) * x \n    invxyx = inv(xtx)\n    result = invxyx * xtx\n    \n    @test isapprox(result[1,1].a, 1.0, atol = atol)\n    @test isapprox(result[2,2].a, 1.0, atol = atol)\n    @test isapprox(result[3,3].a, 1.0, atol = atol)\n    @test isapprox(result[1,2].a, 0.0, atol = atol)\n    @test isapprox(result[1,3].a, 0.0, atol = atol)\n    @test isapprox(result[2,1].a, 0.0, atol = atol)\n    @test isapprox(result[2,3].a, 0.0, atol = atol)\n    @test isapprox(result[3,1].a, 0.0, atol = atol)\n    @test isapprox(result[3,2].a, 0.0, atol = atol)\n    \nend", "meta": {"hexsha": "2d6f903451976585b08fb49905a0f31bc81b5d9b", "size": 1750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testlinearalgebra.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": "test/testlinearalgebra.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": "test/testlinearalgebra.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": 28.6885245902, "max_line_length": 57, "alphanum_fraction": 0.5622857143, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7966957152906393}}
{"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\u2113::AbstractFloat, ln\u03b3::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\u2113::F\n    ln\u03b3::F\n    \n    \u2113\u1d5e::F\n    \u03b3::F\n    function GammaExponential(\n        dist::Euclidean,\n        ln\u2113::AbstractFloat,\n        ln\u03b3::AbstractFloat\n    )\n        ln\u2113, ln\u03b3 = promote(ln\u2113, ln\u03b3)\n        \u03b3 = exp(ln\u03b3)\n        new{typeof(ln\u2113)}(dist, ln\u2113, ln\u03b3, exp(\u03b3 * ln\u2113), \u03b3)\n    end\nend\n\nGammaExponential(ln\u2113::AbstractFloat, ln\u03b3::AbstractFloat) =\n    GammaExponential(Euclidean(), ln\u2113, ln\u03b3)\n\n@inline (k::GammaExponential)(\u03c4::AbstractFloat) = exp(-\u03c4^k.\u03b3 / k.\u2113\u1d5e)\n\nnumparams(::GammaExponential) = (1, 1)\nparamtypes(::GammaExponential{F}) where F = (F, F)\nparams(k::GammaExponential) = (ln\u2113 = k.ln\u2113, ln\u03b3 = k.ln\u03b3)\nfunction setparams!(k::GammaExponential{F}, ln\u2113::F, ln\u03b3::F) where F\n    ln\u2113, ln\u03b3 = promote(ln\u2113, ln\u03b3)\n    \u03b3 = exp(ln\u03b3)\n    k.ln\u2113 = ln\u2113\n    k.ln\u03b3 = ln\u03b3\n    k.\u2113\u1d5e = exp(\u03b3 * ln\u2113)\n    k.\u03b3 = \u03b3\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 `\u03c7(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 [, \u03b5 = 10.0-5])\n\nReturn a rational approximation of x with an error tolerance of \u03b5 (default value of 10^-5).\n\nUsing notation from Bremner (pg 146).\n\njulia> diophantine(float(\u03c0))\n355//113\n\"\"\"\nfunction diophantine(x, \u03b5 = 10.0^-5)\n    st = Stack(Int)\n\n    # step i=2\n    \u03b3 = x\n    qi = floor(Int, \u03b3)\n    push!(st, qi)\n\n    # step i=3,4,...\n    while (abs(stack_to_rational(st) - x) > \u03b5)\n        \u03b3 = 1 / (\u03b3 - qi)\n        qi = floor(Int, \u03b3)\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\u00e2n ph\u1ed1i d\u1eebng c\u1ee7a qu\u00e1 tr\u00ecnh 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\u00edch Markov nh\u00fang c\u1ee7a m\u1ed9t qu\u00e1 tr\u00ecnh Markov\n\"\"\"\nfunction imbeddedchain(m::MarkovProcess)\n\t\u03bb = -diag(m.G)\n\tp = m.G ./ \u03bb - 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\u1ea1o ma tr\u1eadn chuy\u1ec3n t\u1ea1i th\u1eddi \u0111i\u1ec3m 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\u00e1 tr\u00ecnh Markov v\u1edbi ma tr\u1eadn 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 DynamicHMCModels\n\nRandom.seed!(1)\n\ncd(@__DIR__)\ninclude(\"simulateLR.jl\")\n\n struct RegressionProb\n    x::Array{Float64,2}\n    y::Array{Float64,1}\n    Nd::Int64\n    Nc::Int64\nend\n\nfunction (problem::RegressionProb)(\u03b8)\n    @unpack x,y,Nd,Nc = problem   # extract the data\n    @unpack B0,B,sigma = \u03b8\n    \u03bc = B0 .+x*B\n    sum(logpdf.(Normal.(\u03bc,sigma),y)) + logpdf(Normal(0,10),B0) +\n    loglikelihood(Normal(0,10),B) + logpdf(Truncated(Cauchy(0,5),0,Inf),sigma)\nend\n\n# Define problem with data and inits.\n\nx, y, Nd, Nc = simulateLR()\np = RegressionProb(x, y, Nd, Nc)\np((B0 = 0.0, B = fill(0.0, Nc), sigma = 1.0))\n\n# Write a function to return properly dimensioned transformation.\n\nproblem_transformation(p::RegressionProb) =\n    as((B0=as\u211d, B=as(Array, as\u211d, Nc), sigma = as\u211d\u208a))\n    \n# Use Flux for the gradient.\n\nP = TransformedLogDensity(problem_transformation(p), p)\n\u2207P = ADgradient(:ForwardDiff, P)\n\n#import Zygote\n#\u2207P = ADgradient(:Zygote, P)\n\n# Sample from the posterior.\n\nchain, NUTS_tuned = NUTS_init_tune_mcmc(\u2207P, 4000);\n\n# Undo the transformation to obtain the posterior from the chain.\n\nposterior = TransformVariables.transform.(Ref(problem_transformation(p)), get_position.(chain));\n\nchns = nptochain(posterior,NUTS_tuned)\n", "meta": {"hexsha": "49a61297d1032d372ca3cf8774cf83be6d61ab83", "size": 1235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/Linear_regression/linear_regression.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": "benchmarks/Linear_regression/linear_regression.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": "benchmarks/Linear_regression/linear_regression.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": 24.2156862745, "max_line_length": 96, "alphanum_fraction": 0.6939271255, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8499711737573763, "lm_q1q2_score": 0.7966021579174969}}
{"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    \u2111f = interpolate((xs,), ys, Gridded(Linear()))\n\n    numerators = [quadgk(x -> \u2111f(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\u2032(x) = sum(cs[n] * ops[n](x) for n in 1:N)\n\n    return cs, f\u2032\nend\n\n@info \"Decomposing into Fourier series...\"\n\nxs = range(-\u03c0, \u03c0, length=101)\nf(x) = x/\u03c0 + 2exp(-3(x+2)^2) -  3exp(-6(x-1)^2)\n\ncs_even, \u2111f_even = Dict(), Dict()\ncs_odd,  \u2111f_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], \u2111f_even[N] = polynomial_decomposition(f, xs, ops_cos)\n    cs_odd[N],  \u2111f_odd[N]  = polynomial_decomposition(f, xs, ops_sin)\n    plot(xs, f.(xs), label=\"\", linewidth=2, xlim=(-\u03c0, \u03c0), title=\"Fourier series decomposition (N=$N)\")\n    plot!(xs, \u2111f_even[N].(xs) .+ \u2111f_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\u03c0*(x+2/\u03c0)^2) -  3exp(-6\u03c0*(x-1/\u03c0)^2)\n\ncs, \u2111f = Dict(), Dict()\nanim = @animate for N in 0:32\n    ops = [x -> legendre(x, n) for n in 0:N]\n    cs[N], \u2111f[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, \u2111f[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, \u2111f = Dict(), Dict()\nanim = @animate for N in 0:16\n    w(x) = 1 / \u221a(1 - x^2)\n    ops = [x -> chebyshev(x, n) for n in 0:N]\n    cs[N], \u2111f[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, \u2111f[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\u2032;x\u2080,tol=1E-7,maxiter=1000)\n    println(\"the first dispach\")\n    x=zeros(maxiter+1)\n    x_old=x\u2080\n    i=1\n    norm_dif=Inf\n    while i <= maxiter &&  norm_dif>=tol \n        x_new=x_old - f(x_old)/f\u2032(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\u2080,tol = 1E-7,maxiter = 1000)\n    println(\"the second dispach\")\n    x=zeros(maxiter+1)\n    x_old=x\u2080\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\u03f5(x2,x1,l) = (x2 - x1)/l\r\n\r\n#Strain Vector\r\n\u03f5M = [\u03f5(u[2],u[1],l)\r\n      \u03f5(u[3],u[2],l2345) \r\n      \u03f5(u[3],u[2],l2345) \r\n      \u03f5(u[3],u[2],l2345) \r\n      \u03f5(u[3],u[2],l2345)\r\n      \u03f5(u[4],u[3],l)]\r\n\r\n# Stress Function\r\n\u03c3(E,\u03f5) = E*\u03f5\r\n\r\n# Stress Vector\r\n\u03c3M = [\u03c3(E,\u03f5M[1])\r\n      \u03c3(E,\u03f5M[2])\r\n      \u03c3(E,\u03f5M[3])\r\n      \u03c3(E,\u03f5M[4])\r\n      \u03c3(E,\u03f5M[5])\r\n      \u03c3(E,\u03f5M[6])]\r\nprintln(\"Element Stress Vector (psi)\")\r\ndisplay(\u03c3M)\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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, StatsBase, DataFrames\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 2.2\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 2.2\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u25506ffea8a0-1ea1-11eb-1991-61c054bcac44\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u255f\u250070182cd8-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": "export merge_sort\n\nfunction merge_sort(array::Vector)\n    if length(array) > 1\n        divided = divide(array)\n        merged1 = merge_sort(divided[1])\n        merged2 = merge_sort(divided[2])\n        merged = merge(merged1, merged2)\n\n        return merged\n    end\n\n    return array\nend\n\nfunction divide(array::Vector)\n    split = trunc(Int64, length(array)/2)\n    arr1 = array[1:split]\n    arr2 = array[split+1:end]\n\n    return (arr1, arr2)\nend\n\nfunction merge(arr1::Vector, arr2::Vector)\n    merged = []\n\n    while !(isempty(arr1) || isempty(arr2))\n        if arr1[1] <= arr2[1]\n            push!(merged, popfirst!(arr1))\n        else\n            push!(merged, popfirst!(arr2))\n        end\n    end\n\n    if !isempty(arr1)\n        append!(merged, arr1)\n    end\n    if !isempty(arr2)\n        append!(merged, arr2)\n    end\n\n    return merged\nend\n", "meta": {"hexsha": "83debf6a2193c8ab8d5f9ae94fb9c456777d9c86", "size": 844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/merge_sort.jl", "max_stars_repo_name": "yuehhua/Algorithm101", "max_stars_repo_head_hexsha": "98591f7f9da98db1942e1b87b43caa555aba3f98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-05T01:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-21T22:22:46.000Z", "max_issues_repo_path": "src/merge_sort.jl", "max_issues_repo_name": "yuehhua/Algorithm101", "max_issues_repo_head_hexsha": "98591f7f9da98db1942e1b87b43caa555aba3f98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-04T12:29:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-12T07:04:51.000Z", "max_forks_repo_path": "src/merge_sort.jl", "max_forks_repo_name": "foldfelis/Algorithm101", "max_forks_repo_head_hexsha": "46b9038a6b479cad95fc09803e08ed7c837cc5a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-04T14:13:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T14:21:57.000Z", "avg_line_length": 19.1818181818, "max_line_length": 43, "alphanum_fraction": 0.5853080569, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.8962513835254865, "lm_q1q2_score": 0.796551295647293}}
{"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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    infection = \u03b2*c*I/N*S\n    recovery = \u03b3*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\u03b4t = 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]; # \u03b2,c,\u03b3\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\nsol_ode = solve(prob_ode,Tsit5(),saveat=\u03b4t);\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(\u03b2)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[\u03b2,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=\u03b4t)\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(\u03b2)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[\u03b2,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=\u03b4t)\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,\u03b2) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000.0-I,I,0.0,0.0],p=[\u03b2,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=\u03b4t)\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,\u03b2) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000.0-I,I,0.0,0.0],p=[\u03b2,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=\u03b4t)\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=\u03b4t,\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6ff4cfec-ba3e-4937-bc3a-bf2d22f1a8f6\nPlutoUI.TableOfContents(aside=true, indent=true, depth=3)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a3ead5b3-0251-4054-b6f7-63bf51b5ff71\nmd\"\"\"\n# \ud83d\udcd0 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# \u2554\u2550\u2561 1fe44825-0933-4fb8-9b36-511f0e7ffeea\nmd\"\"\"\n## Getting started\n\nWe will get started with creating a random (2D) matrix...\n\"\"\"\n\n# \u2554\u2550\u2561 cd961076-6baf-4626-9089-d33b9dbc94ce\nA = rand(10, 10)\n\n# \u2554\u2550\u2561 eaaffef2-903c-49cf-80b4-bb5adf7d8e92\nmd\"\"\"\nWe can transpose the matrix with the `'` operator...\n\"\"\"\n\n# \u2554\u2550\u2561 92c1a395-bd96-477a-95dc-294a2ac99784\nA\u1d57 = A'\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 de94c2dc-b4b0-42a2-aff0-e54543df82e1\ntypeof(A\u1d57)\n\n# \u2554\u2550\u2561 4770ca47-71ea-4fe1-a5ad-52c4e31f3bdd\n\"Adjoint = $(sizeof(A\u1d57)) bytes\"\n\n# \u2554\u2550\u2561 eccced3e-5898-4d93-8950-58aa77fc4c0b\n\"Matrix = $(sizeof(copy(A\u1d57))) bytes\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 89fb6b4c-911b-4a39-bdef-b70dbe17f14f\nisposdef(A)\n\n# \u2554\u2550\u2561 2082cb17-c373-459d-abc1-abe41cfa023a\nmd\"\"\"\nWe can do matrix multiplication with the `*` operator.\n\"\"\"\n\n# \u2554\u2550\u2561 efc88903-189b-48f4-8cde-17bb2c407010\nA * A\u1d57\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bb678a13-b45d-410b-b8d5-6346eb839c56\nA[11]\n\n# \u2554\u2550\u2561 41e22cf0-2448-4643-89ea-7315fb8b0b32\nmd\"\"\"\nOr we can intuitively access matrix elements with a 2D indexing syntax...\n\"\"\"\n\n# \u2554\u2550\u2561 e759d9a1-29cb-4e15-b629-a913ce721b6f\nA[1,2]\n\n# \u2554\u2550\u2561 f662e8dd-d998-4e8c-8924-aee9fe633129\nmd\"\"\"\nBoth methods are equivalent, but the first one is faster...\n\"\"\"\n\n# \u2554\u2550\u2561 39797209-2206-495f-b517-2ed219ff47ca\nA[13] == A[3,2]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 157971c4-04d9-41de-b378-4a9e998725e9\nA[i,j]\n\n# \u2554\u2550\u2561 d82db838-5ba6-456d-bdeb-cb75a20e081c\nmd\"\"\"\nNow, we can create a (1D) vector of random values...\n\"\"\"\n\n# \u2554\u2550\u2561 5dc61a15-48e9-46a2-b893-9fb97ecc8b55\nb = rand(10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 10474148-5a43-4cc1-8e9f-de57bd3019bc\nx = A \\ b\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9f56f781-5abe-407c-b449-0d917dfa2767\nMatrix{Float64} == Array{Float64, 2}\n\n# \u2554\u2550\u2561 32b59524-9b72-40a2-828f-96f20b0dd924\nVector{Float64} == Array{Float64, 1}\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b4b29ad0-8573-40ea-a2d8-c25183825149\nnorm(A*x - b)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 11bc3a82-19d2-453f-b40b-1eb488ebb323\nmd\"\"\"\n### LU factorization\n\nThe **Lower\u2013Upper (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# \u2554\u2550\u2561 983aeaea-a556-49ba-aedf-898c1b71407d\n# LU factorization\nLU\u2090 = lu(A)\n\n# \u2554\u2550\u2561 c8d51d21-ec99-4451-a87e-b51d8f118e24\nmd\"\"\"\nWe can access lower, upper and permutation matrices...\n\"\"\"\n\n# \u2554\u2550\u2561 b2b6c7d0-8abb-415e-b668-1fe089b42b04\n# lower triangular matrix\nL\u2090 = LU\u2090.L\n\n# \u2554\u2550\u2561 790d0305-216f-4335-ab37-acff2de0f18f\n# upper triangular matrix\nU\u2090 = LU\u2090.U\n\n# \u2554\u2550\u2561 8bb9722c-9cb6-4316-831b-26cb64f93619\n# permutation matrix\nP\u2090 = LU\u2090.P\n\n# \u2554\u2550\u2561 e3571e13-1fa6-44d6-8a31-f810c11cd1f4\n# check if LU = PA\nL\u2090*U\u2090 \u2248 P\u2090*A\n\n# \u2554\u2550\u2561 311b85d4-6509-4945-a451-41020cac465e\n# norm should be near zero\nnorm(L\u2090*U\u2090 - P\u2090*A)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ada5e3a2-b801-4d2b-8ed8-0b9d8e0cf132\n# QR factorization\nQR\u2090 = qr(A)\n\n# \u2554\u2550\u2561 930c8f5d-a05b-4623-84c3-9b58fe59a721\nmd\"\"\"\nWe can access both orthogonal and upper triangular matrices...\n\"\"\"\n\n# \u2554\u2550\u2561 c03c19b1-ec14-4215-9b54-f6cc6b5a2e5c\n# orthogonal matrix\nQ\u2090 = QR\u2090.Q\n\n# \u2554\u2550\u2561 7371a76e-ae89-4138-a614-fa41bfb2dfb0\n# upper triangular matrix\nR\u2090 = QR\u2090.R\n\n# \u2554\u2550\u2561 da750f88-e883-4bec-8e2e-79a91da23f9b\n# check if A = QR\nA \u2248 Q\u2090*R\u2090\n\n# \u2554\u2550\u2561 2669897d-cd5a-45c6-afe0-7a91153e3686\n# norm should be near zero\nnorm(A - Q\u2090*R\u2090)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b1ebbd9d-01d5-4eed-85c3-732491322582\n# make a positive definite matrix\nA\u1d56 = A * A\u1d57\n\n# \u2554\u2550\u2561 6cea7788-57a1-426b-8ede-0a424970e2e3\n# check if A\u02e2 is positive definite\nisposdef(A\u1d56)\n\n# \u2554\u2550\u2561 f7a4fffa-a633-45c9-98a5-b25a047a8a3f\n# Cholesky factorization\ncho\u2090 = cholesky(A\u1d56)\n\n# \u2554\u2550\u2561 c64cf987-9329-4139-b7e3-0fc21e6f0d92\nmd\"\"\"\nWe can access both lower triangular matrix and its conjugate transpose... \n\"\"\"\n\n# \u2554\u2550\u2561 aa195042-2f7e-4881-9d01-834085dccc11\n# lower triangular matrix\nL = cho\u2090.L\n\n# \u2554\u2550\u2561 503192fc-8384-4116-b389-38f04015953c\n# lower triangular conjugate transpose\nL\u1d57 = cho\u2090.U\n\n# \u2554\u2550\u2561 61ea5d3c-63aa-480d-8252-0762f586232f\n# check A = LL\u1d57\nA\u1d56 \u2248 L*L\u1d57\n\n# \u2554\u2550\u2561 49803952-b650-4e5b-9b65-a0d84b21134b\n# norm should be near zero\nnorm(A\u1d56 - L*L\u1d57)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 433c016e-334a-43fa-b315-608b4bbdef51\nfactorize(A)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1755c27b-b170-4b5f-acf9-87e722fd6fad\nD = diagm([1,2,3,4,5])\n\n# \u2554\u2550\u2561 10f4304f-06da-4f0a-bfa9-a148169b531f\ntypeof(D)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d86cf3cc-0490-4144-b732-41e40f380813\nDiagonal(D)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9980569d-ca11-432e-afb5-33001dea3746\nI(3)\n\n# \u2554\u2550\u2561 a31e0b0d-159f-43f3-aed8-a3b7a33bb73b\ntypeof(I(3))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fee37f40-b39d-4cfa-8f25-882a723d5874\nA + I\n\n# \u2554\u2550\u2561 83ba1696-9345-49d8-993a-78517d4ffecb\nA + 2I\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 512da58a-f8d5-4e0c-8c12-de12cc2a4ba5\nS = sprand(5, 8, 0.2)\n\n# \u2554\u2550\u2561 0293d061-05bc-484f-abcb-76dd4b54fd30\nmd\"\"\"\nWe can convert it into a regular `Matrix`...\n\"\"\"\n\n# \u2554\u2550\u2561 f051a1cc-cd3d-465d-9ec0-cb711ad691d7\nM = Matrix(S)\n\n# \u2554\u2550\u2561 ab47cafa-3d00-4e7a-8af9-103241fc68c1\nmd\"\"\"\nLet's compare the memory allocation of both `SparseMatrixCSC` and `Matrix` types...\n\"\"\"\n\n# \u2554\u2550\u2561 8ebe9e1d-981b-4f96-9598-91c8893b8818\n\"Regular matrix = $(sizeof(M)) bytes.\"\n\n# \u2554\u2550\u2561 223cca30-9c72-4ae3-aa51-85c54a362cf4\n\"Sparse matrix = $(sizeof(S)) bytes.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3a5c505a-0620-4cf4-a546-0a01c191b512\nS.nzval\n\n# \u2554\u2550\u2561 6b140d76-a5c3-4b86-9cbd-116a724851af\nmd\"\"\"\nWe can access the number of rows with the `m` attribute...\n\"\"\"\n\n# \u2554\u2550\u2561 12bdbf11-c352-4243-b080-b28c34527e3b\n\"There are $(S.m) rows in the matrix.\"\n\n# \u2554\u2550\u2561 6d53f3e5-66d1-433f-ad4e-0800b0ecb70f\nmd\"\"\"\nAnd we can also access the number of columns with the `n` attribute...\n\"\"\"\n\n# \u2554\u2550\u2561 17764c04-a202-4563-98a4-eddb9f432e6d\n\"There are $(S.n) columns in the matrix.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0f82de90-1a24-49a6-9673-3abf01283817\nX\u2081 = load(\"data/khiam-small.jpg\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3dc31e0a-194c-4ed2-ae6f-c258170aba1a\ntypeof(X\u2081)\n\n# \u2554\u2550\u2561 83c6b744-750c-4c74-8b79-a3d78e5b2c12\nmd\"\"\"\nThus, we can access pixels by slicing an image...\n\"\"\"\n\n# \u2554\u2550\u2561 b61a2c57-6443-4e8a-b48a-28e2ad1fca4f\n# the first pixel\nX\u2081[1,1]\n\n# \u2554\u2550\u2561 7f003ee7-6958-48e1-a3d8-11876cfa1dbd\n# a random chosen pixel\nX\u2081[100,20]\n\n# \u2554\u2550\u2561 c2d97352-fb67-4d66-a999-a8362e41ee84\n# first row of pixels\nX\u2081[1,:]\n\n# \u2554\u2550\u2561 45f5c9ac-d450-49d6-af9d-28704161f360\n# first column of pixels\nX\u2081[:,1]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 69c75582-f4a1-443e-bda2-385681712821\nXgray = Gray.(X\u2081)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ff77b413-a905-44d6-973d-f7d1193dbb25\nbegin\n\t# red layer\n\tr_arr = map(i -> X\u2081[i].r, 1:length(X\u2081))\n\tr_mtx = Float64.(reshape(r_arr, size(X\u2081)))\n\n\t# red.(X\u2081)\nend\n\n# \u2554\u2550\u2561 f98fdf05-e6e8-4d0e-b6a6-d3398c2d1ab5\nbegin\n\t# green layer\n\tg_arr = map(i -> X\u2081[i].g, 1:length(X\u2081))\n\tg_mtx = Float64.(reshape(g_arr, size(X\u2081)))\n\n\t# green.(X\u2081)\nend\n\n# \u2554\u2550\u2561 34b5d940-7d9a-40fb-a38f-16b267130026\nbegin\n\tb_arr = map(i -> X\u2081[i].b, 1:length(X\u2081))\n\tb_mtx = Float64.(reshape(b_arr, size(X\u2081)))\n\n\t# blue.(X\u2081)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c071dc2a-e53e-402b-b800-6601025b62c7\nZ_mtx = zeros(size(r_mtx)...)\n\n# \u2554\u2550\u2561 5e54ac09-2276-4760-adc9-a05082a5c17f\n# red layer\nRGB.(r_mtx, Z_mtx, Z_mtx)\n\n# \u2554\u2550\u2561 33b3de91-010a-4bd2-863d-199bfbfb8ed8\n# green layer\nRGB.(Z_mtx, g_mtx, Z_mtx)\n\n# \u2554\u2550\u2561 ac394a4c-f983-487c-9d90-1cada3b9e398\n# blue layer\nRGB.(Z_mtx, Z_mtx, b_mtx)\n\n# \u2554\u2550\u2561 59daefac-6e47-4ecc-9f4a-033faa55fc59\nmd\"\"\"\nWe can easily obtain the `Float64` values of the grayscale image.\n\"\"\"\n\n# \u2554\u2550\u2561 9d1fa923-e20a-44cc-b0b6-0656f85178fc\nXgrayvalues = Float64.(Xgray)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d66ae839-2d03-40f6-a82e-1e8a063e27f0\nSVD = svd(Xgrayvalues)\n\n# \u2554\u2550\u2561 54caef76-2f0d-4e9f-a3a1-725ab3d64648\nmd\"\"\"\nWe may access $U$, $\\Sigma$ and $V$...\n\"\"\"\n\n# \u2554\u2550\u2561 a28364a5-5c03-4b42-b354-2cdb1880ca1d\n# rectangular unitary matrix\nU = SVD.U\n\n# \u2554\u2550\u2561 0a30e77d-8770-4b75-9c7d-e45f6d301022\n# diagonal matrix with singular values\n\u03a3 = diagm(SVD.S)\n\n# \u2554\u2550\u2561 ac8e9a63-708c-408f-bc91-a57356dae648\n# transposed square unitary matrix\nV\u1d57 = SVD.V'\n\n# \u2554\u2550\u2561 96766fac-6950-4554-b89a-32143f120f04\n# check if A = U\u03a3V\u1d57\nXgrayvalues \u2248 U*\u03a3*V\u1d57\n\n# \u2554\u2550\u2561 1de26f9d-89eb-4397-adba-ed566cd054d6\n# norm should be near zero\nnorm(Xgrayvalues - U*\u03a3*V\u1d57)\n\n# \u2554\u2550\u2561 90922832-4ed1-4fa6-bb61-1242c17e1cd8\nmd\"\"\"\nAccording to the Eckart\u2013Young 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# \u2554\u2550\u2561 8fc6ee4b-5abc-45e5-a642-6570af32a492\nbegin\n\t# range of singular values\n\tr\u2084 = 1:4\n\t# first 4 columns of U \n\tu\u2084 = U[:,r\u2084]\n\t# first 4 columns of V\n\tv\u2084 = SVD.V[:,r\u2084]\n\t# \u03a3 with the top 4 singular values\n\t\u03c3\u2084 = spdiagm(\u03a3[r\u2084])\n\n\t# downsampled image\n\timg\u2084 = u\u2084*\u03c3\u2084*v\u2084'\n\n\t# grayscale final image\n\tGray.(img\u2084)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u03a3 with the top 50 singular values\n\t\u03c3 = spdiagm(0 => SVD.S[r])\n\n\t# downsampled image\n\timg = u*\u03c3*v'\n\n\t# grayscale final image\n\tGray.(img)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 eb0f7a49-c6b9-4b94-9fb1-f9cdcf6c8ee6\nnorm(Xgrayvalues - img)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 716fec98-ef10-465a-a216-beceb4057a91\ndata = matread(\"data/face_recog_qr.mat\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 194a229c-0a2f-46a4-bdbe-678df9dae106\nbegin\n\tfig\u2081 = reshape(data[\"V2\"][:,1], 192, 168)\n\tGray.(fig\u2081)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70338fd5-570d-4c71-becd-b30a768554cc\nb\u00b9 = fig\u2081[:]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dfbaf736-ccb1-4e7c-a2eb-b432e1498008\nbegin\n\tA\u00b9 = data[\"V2\"][:,2:end]\n\tx\u00b9 = A\u00b9\\b\u00b9\n\n\t# display image\n\tGray.(reshape(A\u00b9*x\u00b9, 192, 168))\nend\n\n# \u2554\u2550\u2561 383a0be3-ce45-43e6-9fe9-d925a40ad9f5\nmd\"\"\"\nNow, let's check the norm difference...\n\"\"\"\n\n# \u2554\u2550\u2561 dd60c14e-d157-48a7-955f-845656636beb\nnorm(A\u00b9*x\u00b9-b\u00b9)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 50c8a7f4-b620-441f-b941-ece127899ce0\nbegin\n\tfig_temp = fig\u2081 + rand(size(fig\u2081,1), size(fig\u2081,2)) * 0.5\n\tfig\u2082 = fig_temp ./ maximum(fig_temp)\n\n\t# display noisy image\n\tGray.(fig\u2082)\nend\n\n# \u2554\u2550\u2561 6aee282e-e19d-4e8f-bc45-bf20474d41b9\nmd\"\"\"\nLet's define $b$ by vectorizing the matrix `fig\u2082` and then get $A$...\n\"\"\"\n\n# \u2554\u2550\u2561 29e803bd-402e-484e-acb7-9053fc8f6a70\nb\u00b2 = fig\u2082[:]\n\n# \u2554\u2550\u2561 5511fbe1-901b-4c0f-b354-21795f3316dc\nA\u00b2 = A\u00b9\n\n# \u2554\u2550\u2561 bec4214d-6cbe-43d1-a02a-82d4245bdd27\nmd\"\"\"\nNow, let's find the solution $x$ and check the norm difference...\n\"\"\"\n\n# \u2554\u2550\u2561 798f5b17-48b4-4349-b850-e3e2e62418de\nbegin\n\tx\u00b2 = A\u00b2\\b\u00b2\n\tnorm(A\u00b2*x\u00b2 - b\u00b2)\nend\n\n# \u2554\u2550\u2561 ea16d6a3-34ac-4c36-b916-47439fbcd0fa\nmd\"\"\"\nThe error is so much bigger this time. Finally, let's check the resulting image...\n\"\"\"\n\n# \u2554\u2550\u2561 64f6dd6a-0cbf-4f05-b780-c4b2c74ce839\nGray.(reshape(A\u00b2*x\u00b2, 192, 168))\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25006c3082f0-6196-11ec-1d58-03f55d178603\n# \u255f\u25006ff4cfec-ba3e-4937-bc3a-bf2d22f1a8f6\n# \u255f\u250063f2a85b-a426-4c37-a1a0-049d00cfed23\n# \u255f\u2500a3ead5b3-0251-4054-b6f7-63bf51b5ff71\n# \u255f\u25001fe44825-0933-4fb8-9b36-511f0e7ffeea\n# \u2560\u2550cd961076-6baf-4626-9089-d33b9dbc94ce\n# \u255f\u2500eaaffef2-903c-49cf-80b4-bb5adf7d8e92\n# \u2560\u255092c1a395-bd96-477a-95dc-294a2ac99784\n# \u255f\u25005c852935-3055-4178-8ac3-3a6f1d6e8de9\n# \u2560\u2550de94c2dc-b4b0-42a2-aff0-e54543df82e1\n# \u2560\u25504770ca47-71ea-4fe1-a5ad-52c4e31f3bdd\n# \u2560\u2550eccced3e-5898-4d93-8950-58aa77fc4c0b\n# \u255f\u250002cbd31b-bd62-48f4-be5e-242279e215d9\n# \u2560\u255089fb6b4c-911b-4a39-bdef-b70dbe17f14f\n# \u255f\u25002082cb17-c373-459d-abc1-abe41cfa023a\n# \u2560\u2550efc88903-189b-48f4-8cde-17bb2c407010\n# \u255f\u2500e6c8e66b-f9a3-4b93-b5a4-97c030d381d4\n# \u2560\u2550bb678a13-b45d-410b-b8d5-6346eb839c56\n# \u255f\u250041e22cf0-2448-4643-89ea-7315fb8b0b32\n# \u2560\u2550e759d9a1-29cb-4e15-b629-a913ce721b6f\n# \u255f\u2500f662e8dd-d998-4e8c-8924-aee9fe633129\n# \u2560\u255039797209-2206-495f-b517-2ed219ff47ca\n# \u255f\u2500f9e97b10-4908-4811-a255-c76c0eaed01c\n# \u2560\u2550157971c4-04d9-41de-b378-4a9e998725e9\n# \u255f\u2500d82db838-5ba6-456d-bdeb-cb75a20e081c\n# \u2560\u25505dc61a15-48e9-46a2-b893-9fb97ecc8b55\n# \u255f\u25000ec44c81-40d5-4b3f-bdec-d3e0cab7de74\n# \u2560\u255010474148-5a43-4cc1-8e9f-de57bd3019bc\n# \u255f\u2500859cb7ee-d9d8-4bd7-b7c9-5777867297b7\n# \u2560\u25509f56f781-5abe-407c-b449-0d917dfa2767\n# \u2560\u255032b59524-9b72-40a2-828f-96f20b0dd924\n# \u255f\u25004732c64c-c957-4bdb-9332-7ccb8f40f655\n# \u2560\u2550b4b29ad0-8573-40ea-a2d8-c25183825149\n# \u255f\u25008c19fd6c-2f71-480d-8fd0-2241b6f3debe\n# \u255f\u250011bc3a82-19d2-453f-b40b-1eb488ebb323\n# \u2560\u2550983aeaea-a556-49ba-aedf-898c1b71407d\n# \u255f\u2500c8d51d21-ec99-4451-a87e-b51d8f118e24\n# \u2560\u2550b2b6c7d0-8abb-415e-b668-1fe089b42b04\n# \u2560\u2550790d0305-216f-4335-ab37-acff2de0f18f\n# \u2560\u25508bb9722c-9cb6-4316-831b-26cb64f93619\n# \u2560\u2550e3571e13-1fa6-44d6-8a31-f810c11cd1f4\n# \u2560\u2550311b85d4-6509-4945-a451-41020cac465e\n# \u255f\u2500ea01ba90-0b30-4998-b1a5-e7fa17e53679\n# \u2560\u2550ada5e3a2-b801-4d2b-8ed8-0b9d8e0cf132\n# \u255f\u2500930c8f5d-a05b-4623-84c3-9b58fe59a721\n# \u2560\u2550c03c19b1-ec14-4215-9b54-f6cc6b5a2e5c\n# \u2560\u25507371a76e-ae89-4138-a614-fa41bfb2dfb0\n# \u2560\u2550da750f88-e883-4bec-8e2e-79a91da23f9b\n# \u2560\u25502669897d-cd5a-45c6-afe0-7a91153e3686\n# \u255f\u2500737762ba-b142-4fd9-9862-af69f7415030\n# \u2560\u2550b1ebbd9d-01d5-4eed-85c3-732491322582\n# \u2560\u25506cea7788-57a1-426b-8ede-0a424970e2e3\n# \u2560\u2550f7a4fffa-a633-45c9-98a5-b25a047a8a3f\n# \u255f\u2500c64cf987-9329-4139-b7e3-0fc21e6f0d92\n# \u2560\u2550aa195042-2f7e-4881-9d01-834085dccc11\n# \u2560\u2550503192fc-8384-4116-b389-38f04015953c\n# \u2560\u255061ea5d3c-63aa-480d-8252-0762f586232f\n# \u2560\u255049803952-b650-4e5b-9b65-a0d84b21134b\n# \u255f\u25003f0a1c9f-8b8a-4886-97bd-3810dfa0263b\n# \u2560\u2550433c016e-334a-43fa-b315-608b4bbdef51\n# \u255f\u25001d9e27be-c21b-4b45-be25-dd1f5b954cb2\n# \u255f\u2500d806f387-587a-438c-bb22-f6f14b4d4509\n# \u2560\u25501755c27b-b170-4b5f-acf9-87e722fd6fad\n# \u2560\u255010f4304f-06da-4f0a-bfa9-a148169b531f\n# \u255f\u2500926cb115-c47f-44e3-bb40-53533d0a1354\n# \u2560\u2550d86cf3cc-0490-4144-b732-41e40f380813\n# \u255f\u25007a7002b3-2523-4b33-8dde-511728dfaf0e\n# \u2560\u25509980569d-ca11-432e-afb5-33001dea3746\n# \u2560\u2550a31e0b0d-159f-43f3-aed8-a3b7a33bb73b\n# \u255f\u250005bd36f7-b0db-4a58-a591-4cde55139ade\n# \u2560\u2550fee37f40-b39d-4cfa-8f25-882a723d5874\n# \u2560\u255083ba1696-9345-49d8-993a-78517d4ffecb\n# \u255f\u25001d8970d9-7fae-4fef-b4e0-a92aa3e911a7\n# \u2560\u2550512da58a-f8d5-4e0c-8c12-de12cc2a4ba5\n# \u255f\u25000293d061-05bc-484f-abcb-76dd4b54fd30\n# \u2560\u2550f051a1cc-cd3d-465d-9ec0-cb711ad691d7\n# \u255f\u2500ab47cafa-3d00-4e7a-8af9-103241fc68c1\n# \u2560\u25508ebe9e1d-981b-4f96-9598-91c8893b8818\n# \u2560\u2550223cca30-9c72-4ae3-aa51-85c54a362cf4\n# \u255f\u2500640da366-e78b-4a62-aedc-2668ae69ae95\n# \u2560\u25503a5c505a-0620-4cf4-a546-0a01c191b512\n# \u255f\u25006b140d76-a5c3-4b86-9cbd-116a724851af\n# \u2560\u255012bdbf11-c352-4243-b080-b28c34527e3b\n# \u255f\u25006d53f3e5-66d1-433f-ad4e-0800b0ecb70f\n# \u2560\u255017764c04-a202-4563-98a4-eddb9f432e6d\n# \u255f\u2500a441d0b6-9a18-46e4-899d-f3ea2642c7b7\n# \u2560\u25500f82de90-1a24-49a6-9673-3abf01283817\n# \u255f\u25004eb22f0f-b287-4be2-b013-824371a44c26\n# \u2560\u25503dc31e0a-194c-4ed2-ae6f-c258170aba1a\n# \u255f\u250083c6b744-750c-4c74-8b79-a3d78e5b2c12\n# \u2560\u2550b61a2c57-6443-4e8a-b48a-28e2ad1fca4f\n# \u2560\u25507f003ee7-6958-48e1-a3d8-11876cfa1dbd\n# \u2560\u2550c2d97352-fb67-4d66-a999-a8362e41ee84\n# \u2560\u255045f5c9ac-d450-49d6-af9d-28704161f360\n# \u255f\u2500946bf2e5-51e4-4b8b-a316-27e29f15c2e3\n# \u2560\u255069c75582-f4a1-443e-bda2-385681712821\n# \u255f\u250042a1ee17-86ab-41d8-8b89-5064700e2e64\n# \u2560\u2550ff77b413-a905-44d6-973d-f7d1193dbb25\n# \u2560\u2550f98fdf05-e6e8-4d0e-b6a6-d3398c2d1ab5\n# \u2560\u255034b5d940-7d9a-40fb-a38f-16b267130026\n# \u255f\u25003b2724d7-f429-447d-948c-e11a8fc20572\n# \u2560\u2550c071dc2a-e53e-402b-b800-6601025b62c7\n# \u2560\u25505e54ac09-2276-4760-adc9-a05082a5c17f\n# \u2560\u255033b3de91-010a-4bd2-863d-199bfbfb8ed8\n# \u2560\u2550ac394a4c-f983-487c-9d90-1cada3b9e398\n# \u255f\u250059daefac-6e47-4ecc-9f4a-033faa55fc59\n# \u2560\u25509d1fa923-e20a-44cc-b0b6-0656f85178fc\n# \u255f\u2500a551a1cb-0d7d-4c82-8f7b-9d92274516f3\n# \u2560\u2550d66ae839-2d03-40f6-a82e-1e8a063e27f0\n# \u255f\u250054caef76-2f0d-4e9f-a3a1-725ab3d64648\n# \u2560\u2550a28364a5-5c03-4b42-b354-2cdb1880ca1d\n# \u2560\u25500a30e77d-8770-4b75-9c7d-e45f6d301022\n# \u2560\u2550ac8e9a63-708c-408f-bc91-a57356dae648\n# \u2560\u255096766fac-6950-4554-b89a-32143f120f04\n# \u2560\u25501de26f9d-89eb-4397-adba-ed566cd054d6\n# \u255f\u250090922832-4ed1-4fa6-bb61-1242c17e1cd8\n# \u2560\u25508fc6ee4b-5abc-45e5-a642-6570af32a492\n# \u255f\u2500ddf9e602-ae0a-43c3-a4b9-c052c513ffc5\n# \u2560\u255091575c63-16b5-4b30-8f50-392c058218c9\n# \u255f\u25004113a8aa-af35-40fa-836a-f9e347431b5b\n# \u2560\u2550eb0f7a49-c6b9-4b94-9fb1-f9cdcf6c8ee6\n# \u255f\u2500bb25ecf5-b4ed-42a7-8ccd-b67d6d8b8bf0\n# \u2560\u2550716fec98-ef10-465a-a216-beceb4057a91\n# \u255f\u2500a9dd7d9e-c91e-4a35-ba77-b765161b58b5\n# \u2560\u2550194a229c-0a2f-46a4-bdbe-678df9dae106\n# \u255f\u2500049cf246-8dbf-4af8-a60d-01e162097272\n# \u2560\u255070338fd5-570d-4c71-becd-b30a768554cc\n# \u255f\u2500f1704b39-f48d-49ce-9ec2-77b1fa2af0f8\n# \u2560\u2550dfbaf736-ccb1-4e7c-a2eb-b432e1498008\n# \u255f\u2500383a0be3-ce45-43e6-9fe9-d925a40ad9f5\n# \u2560\u2550dd60c14e-d157-48a7-955f-845656636beb\n# \u255f\u25003f20fcb5-6e94-48e0-b2c3-9ff828269e23\n# \u2560\u255050c8a7f4-b620-441f-b941-ece127899ce0\n# \u255f\u25006aee282e-e19d-4e8f-bc45-bf20474d41b9\n# \u2560\u255029e803bd-402e-484e-acb7-9053fc8f6a70\n# \u2560\u25505511fbe1-901b-4c0f-b354-21795f3316dc\n# \u255f\u2500bec4214d-6cbe-43d1-a02a-82d4245bdd27\n# \u2560\u2550798f5b17-48b4-4349-b850-e3e2e62418de\n# \u255f\u2500ea16d6a3-34ac-4c36-b916-47439fbcd0fa\n# \u2560\u255064f6dd6a-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] # \u2207\u00d7VF\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 \u2207 = 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 = \u03bb 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 = \u03bb 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\u0304, y\u0304 = mean(xs), mean(ys)\n    \u03c3x\u00b2, \u03c3y\u00b2 = var(xs), var(ys)\n    \u03c3 = sqrt(0.5*(\u03c3x\u00b2 + \u03c3y\u00b2))\n    abs(x\u0304 - y\u0304)/\u03c3\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, \u03b1::Float64=0.05)\n    \u03b4 = d*sqrt(n/2)\n    tc = quantile(TDist(dof), 1 - \u03b1/2)\n    ccdf(NoncentralT(dof, \u03b4), tc) + cdf(NoncentralT(dof, \u03b4), -tc)\nend\n\nfunction power(d::Float64, n::Float64=length(xs), dof=2n-2, \u03b1::Float64=0.05)\n    \u03b4 = d*sqrt(n/2)\n    tc = quantile(TDist(dof), 1 - \u03b1/2)\n    ccdf(NoncentralT(dof, \u03b4), tc) + cdf(NoncentralT(dof, \u03b4), -tc)\nend\n\nfunction solvepower(d::Float64, dof::Float64, \u03b2::Float64=0.8, \u03b1::Float64=0.05)\n    first(nlsolve((F,x) -> F[1] = power(d, x[1], dof, \u03b1) - \u03b2, [2.0]).zero)\nend\n\nfunction solvepower(xs::AbstractVector, ys::AbstractVector, \u03b2::Float64=0.8, \u03b1::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, \u03b2, \u03b1)\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": "using Printf\n\ninclude(\"gen_rmesh_exp.jl\")\ninclude(\"gen_drmesh_exp.jl\")\ninclude(\"integrate.jl\")\n\nfunction my_func(r)\n    return exp(-0.2*r)\n    #return exp(-0.2*r*r)\nend\n\nfunction main()\n    r_min = 0.0\n    r_max = 200.0\n    a = 1e9\n    N = 500\n    \n    rmesh = gen_rmesh_exp(r_min, r_max, a, N)\n    drmesh = gen_drmesh_exp(r_min, r_max, a, N)\n\n    f = my_func.(rmesh)\n    s = integrate_trapz_7(f, drmesh)\n\n    println(\"s = \", s)\n\nend\n\nmain()", "meta": {"hexsha": "8c20aeddbf892f1144813a67dbe66d6c5338d266", "size": 441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dftatom/test_integrate.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/test_integrate.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/test_integrate.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": 15.75, "max_line_length": 47, "alphanum_fraction": 0.612244898, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024820841433, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7962627741939483}}
{"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": "@testset \"Kronecker sums\" begin\n\n\n    A = rand(4,4); IA = oneunit(A)\n    B = rand(3,3); IB = oneunit(B)\n\n    KS = A \u2295 B\n    kronsum = kron(A, IB) + kron(IA, B)\n\n    @test collect(KS) \u2248 kronsum\n    @test collect(KS) isa SparseMatrixCSC\n\n    @test issquare(KS)\n\n    C = rand(5,5); IC = oneunit(C)\n    KS3 = A \u2295 B \u2295 C\n    kronsum3 = kron(A,IB,IC) + kron(IA,B,IC) + kron(IA,IB,C)\n\n    @test collect(KS3) \u2248 kronsum3\n    @test collect(KS3) isa SparseMatrixCSC\n\n    @test order(KS) == 2\n    @test order(KS3) == 3\n\n    @test getmatrices(KS) == (A,B)\n\n    @test getindex(KS,2,3) == kronsum[2,3]\n    @test getindex(KS3,2,3) == kronsum3[2,3]\n\n    D = rand(ComplexF64,6,6); ID = oneunit(D)\n\n    @testset \"Structure of sums\" begin\n        @test size(A \u2295 D) == size(A) .* size(D,1)\n        @test size(B \u2295 C \u2295 D) == size(B) .* size(C) .* size(D)\n        @test eltype(A \u2295 B) == Float64\n        @test eltype(C \u2295 D) == ComplexF64\n    end\n\n    @testset \"Basic linear algebra for sums\" begin\n        @test tr(KS) \u2248 tr(kronsum)\n        @test KS' == kronsum'\n        @test transpose(KS) == transpose(kronsum)\n        @test conj(KS) == conj(kronsum)\n    end\n\n    A = rand(10,10); B = rand(10,10); V = Diagonal(rand(10))\n    @testset \"Vec trick for sums\" begin\n        @test (A \u2295 B) * vec(V) == vec(B*V + V*transpose(A))\n    end\n\n    A = rand(3, 3); IA = oneunit(A)\n    B = rand(4, 4); IB = oneunit(B)\n    @testset \"exp for Kronecker sum\" begin\n        EKS = exp(A \u2295 B)\n        @test EKS isa AbstractKroneckerProduct\n        @test EKS \u2248 exp(kron(A, IB) + kron(IA, B))\n    end\n\n    @testset \"sum over Kronecker sum\" begin\n        @test sum(KS) \u2248 sum(kronsum)\n        @test sum(KS3) \u2248 sum(kronsum3)\n\n        for dims in 1:2\n            @test sum(KS, dims=dims) \u2248 sum(kronsum, dims=dims)\n            @test sum(KS3, dims=dims) \u2248 sum(kronsum3, dims=dims)\n        end\n\n        @test_throws ArgumentError sum(KS, dims=-1)\n        @test_throws ArgumentError sum(KS3, dims=3)\n    end\n\nend\n", "meta": {"hexsha": "923240e89b99a55a966e49a123e6de9e32b51eb1", "size": 1956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testkroneckersum.jl", "max_stars_repo_name": "mcabbott/Kronecker.jl", "max_stars_repo_head_hexsha": "970b801b919670a6fd273a43d3dc18496b95b899", "max_stars_repo_licenses": ["MIT"], "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/testkroneckersum.jl", "max_issues_repo_name": "mcabbott/Kronecker.jl", "max_issues_repo_head_hexsha": "970b801b919670a6fd273a43d3dc18496b95b899", "max_issues_repo_licenses": ["MIT"], "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/testkroneckersum.jl", "max_forks_repo_name": "mcabbott/Kronecker.jl", "max_forks_repo_head_hexsha": "970b801b919670a6fd273a43d3dc18496b95b899", "max_forks_repo_licenses": ["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.7945205479, "max_line_length": 64, "alphanum_fraction": 0.5511247444, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7962627720331206}}
{"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": "function test_mod_multiplicativeorder()\n    @test multiplicativeorder(1, 11) == 1\n    @test multiplicativeorder(2, 7) == 3\n    @test multiplicativeorder(3, 7) == 6\n    @test multiplicativeorder(7, 5) == 4\n    @test multiplicativeorder(37, 1000) == 100\n\n    @test_throws ErrorException multiplicativeorder(3, -6)\nend\n\nfunction test_mod_linearmod()\n    @test linearmod(3, 5, 6) == []\n    @test linearmod(3, 4, 5) == [3]\n    @test linearmod(3, 6, 9) == [2, 5, 8]\n    @test linearmod(-14, 30, 100) == [5, 55]\n\n    @test_throws ErrorException linearmod(3, 4, 1)\nend\n\nfunction test_mod_primitiveroot()\n    @test primitiveroot(2) == 1\n    @test primitiveroot(17) == 3\n    @test primitiveroot(71) == 7\n    @test primitiveroot(101) == 2\n\n    @test_throws ErrorException primitiveroot(4)\nend\n\nfunction test_mod_all()\n    print(rpad(\"Math.NumberTheory.Mod...\", 50, ' '))\n\n    test_mod_multiplicativeorder()\n    test_mod_linearmod()\n    test_mod_primitiveroot()\n\n    println(\"PASS\")\nend\n", "meta": {"hexsha": "efc0e9f8571939208e3596655f641529f215bf0e", "size": 975, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Math/NumberTheory/mod.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": "test/Math/NumberTheory/mod.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": "test/Math/NumberTheory/mod.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": 25.6578947368, "max_line_length": 58, "alphanum_fraction": 0.6635897436, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7961997683145803}}
{"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(\ud835\udc9e([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(\ud835\udc9e, 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, \u03b1, 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, \u03b1, p2, c, h, T, ::MatrixDiscrete)\n    n=Int64(floor(\u03b1))\n    rows=collect(1:n)\n    N=Int64(T/h+1)\n    equation = p1*B(N, \u03b1, 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\u2096 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 \u2260 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) / \u221a(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 = \u221a(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    \u03a6 = 1 ./sqrt.(W).*F.U\n    \n    POD = PODBasis(a, \u03a6)\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) \u2192 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 `\u03c3x` and `\u03c3y`.\n\"\"\"\nfunction eom_ar1_bidir(x, p, n)\n    a\u2081, b\u2081, c_xy, c_yx, \u03c3x, \u03c3y = (p...,)\n    x, y = (x...,)\n\n    \u03f5x = rand(Normal(0, \u03c3x))\n    \u03f5y = rand(Normal(0, \u03c3y))\n\n    dx = a\u2081*x + c_yx*y + \u03f5x\n    dy = b\u2081*y + c_xy*x + \u03f5y\n    return SVector{2}(dx, dy)\nend\n\nfunction ar1_bidir(u\u2080,a\u2081, b\u2081, c_xy, c_yx, \u03c3x, \u03c3y)\n    p = @LArray [a\u2081, b\u2081, c_xy, c_yx, \u03c3x, \u03c3y] (:a\u2081, :b\u2081, :c_xy, :c_yx, :\u03c3x, :\u03c3y)\n    logistic_system = DiscreteDynamicalSystem(eom_ar1_bidir, u\u2080, p)\n\n    return logistic_system\nend\n\n\"\"\"\n    ar1_bidir(;u\u2080 = rand(2), a\u2081 = 0.5, b\u2081 = 0.7, c_xy = 0, c_yx = 0.2, \n        \u03c3x = 0.3, \u03c3y = 0.3) \u2192 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 `\u03c3x` and `\u03c3y`.\n\"\"\"\nar1_bidir(;a\u2081 = 0.5, b\u2081 = 0.7, u\u2080 = rand(2), c_xy = 0, c_yx = 0.2, \u03c3x = 0.3, \u03c3y = 0.3) =\n    ar1_bidir(u\u2080, a\u2081, b\u2081, c_xy, c_yx, \u03c3x, \u03c3y)\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\u03b8 = [0,1,2]\nz = y - (\u03b8' * 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\u1d56) = exp(-1/2 * norm(x-x\u1d56)^2)\n\nx = [1,0,0]\n\nx\u1d56 = [0,1,0]\n\nk = radial_kernel(x,x\u1d56)\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": "@testset \"Test linear solvers\" begin\n    As = @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    bs = @SVector [-2..4, 1..8, -4..10, 2..12]\n\n    Am = Matrix(As)\n    bm = Vector(bs)\n    jac = Jacobi()\n    gs = GaussSeidel()\n    hbr = HansenBliekRohn()\n    kra = LinearKrawczyk()\n\n    for (A, b) in zip([As, Am], [bs, bm])\n        xgs = solve(A, b, gs)\n        xjac = solve(A, b, jac)\n        xhbr = solve(A, b, hbr)\n        xkra = solve(A, b, kra)\n\n        @test all(interval_isapprox.(xgs, [-2.6..3.1, -3.9..1.65, -1.48..2.15, -2.35..0.79]; atol=0.01))\n        @test all(interval_isapprox.(xjac, [-2.6..3.1, -3.9..1.65, -1.48..2.15, -2.35..0.79]; atol=0.01))\n\n        @test all(interval_isapprox.(xhbr, [-2.5..3.1, -3.9..1.2, -1.4..2.15, -2.35..0.6]; atol=0.01))\n\n        @test all(interval_isapprox.(xkra, [-8..8, -8..8, -8..8, -8..8]; atol=0.01))\n    end\n\n    ge = GaussianElimination()\n    xge = solve(Am, bm, ge)\n    @test all(interval_isapprox.(xge, [-2.6..3.1, -3.9..1.5, -1.43..2.15, -2.35..0.6]; atol=0.01))\n\n    xdef = solve(Am, bm)\n    @test all(interval_isapprox.(xdef, [-2.6..3.1, -3.9..1.5, -1.43..2.15, -2.35..0.6]; atol=0.01))\n\n    A = [2..4 -2..1; -1..2 2..4]\n    b = [-2..2, -2..2]\n\n    x1 = solve(A, b)\n    @test all(interval_isapprox.(x1, [-14..14, -14..14]))\n    x2 = solve(A, b, HansenBliekRohn())\n    @test all(interval_isapprox.(x2, [-14..14, -14..14]))\n\n    # test exceptions\n    @test_throws DimensionMismatch solve(Am, bm[1:end-1])\n    @test_throws DimensionMismatch solve(Am[:, 1:end-1], bm, hbr)\n    @test_throws DimensionMismatch solve(Am, bm, gs, NoPrecondition(), [1..2, 3..4])\nend\n\n@testset \"Reduced Row Echelon Form\" begin\n    A1 = [1..2 1..2;2..2 3..3]\n    @test rref(A1) == [2..2 3..3; 0..0 -2..0.5]\n\n    A2 = fill(0..0, 2, 2)\n    @test_throws ArgumentError rref(A2)\nend\n", "meta": {"hexsha": "1de6eed06272e46192a967fd0df885d2e2687cc0", "size": 1870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_solvers/test_enclosures.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": "test/test_solvers/test_enclosures.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": "test/test_solvers/test_enclosures.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": 34.6296296296, "max_line_length": 119, "alphanum_fraction": 0.5272727273, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7960863984683757}}
{"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": "function fibonacci_sum(limit)\n    sequence = [1, 2]; total = 0\n    while sequence[end] <= limit\n        if iseven(sequence[end])\n            total += sequence[end]\n        end\n        push!(sequence, sequence[end] + sequence[end-1])\n    end\n    println(total)\nend\n\nfibonacci_sum(4000000)\n", "meta": {"hexsha": "eed2f8c625da54191ab5b17cbc49feaae6935df7", "size": 288, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/problem_2.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_2.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_2.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": 22.1538461538, "max_line_length": 56, "alphanum_fraction": 0.6041666667, "num_tokens": 74, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7960831972349159}}
{"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 ``\u03f5`` 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    \u03c1 = algorithm.albedo\n    I = algorithm.illumination_direction\n    smoothness = algorithm.smoothness\n    iterations = algorithm.iterations\n\n    if \u03c1 == Inf || I == [Inf, Inf, Inf]\n        \u03c1,I,\u03c3,\u03c4 = 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(\u03c1, 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": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    ZScore()\n\nApplies the z-score transform (a.k.a. normal score) to all columns of the table.\nThe z-score transform of the column `x`, with mean `\u03bc` and standard deviation `\u03c3`,\nis defined by `(x .- \u03bc) ./ \u03c3`.\n\"\"\"\nstruct ZScore <: Colwise end\n\nassertions(::Type{ZScore}) = [assert_continuous]\n\nisrevertible(::Type{ZScore}) = true\n\nfunction colcache(::ZScore, x)\n  \u03bc = mean(x)\n  \u03c3 = std(x, mean=\u03bc)\n  (\u03bc=\u03bc, \u03c3=\u03c3)\nend\n\ncolapply(::ZScore, x, c)  = @. (x - c.\u03bc) / c.\u03c3\n\ncolrevert(::ZScore, y, c) = @. c.\u03c3 * y + c.\u03bc\n", "meta": {"hexsha": "463d8a68be7a9e4154375b0e7d4eb4efdfdb51df", "size": 717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/zscore.jl", "max_stars_repo_name": "ceferisbarov/TableTransforms.jl", "max_stars_repo_head_hexsha": "988265e6c7460e1d08c8f79fccd8301a840ba5c7", "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/zscore.jl", "max_issues_repo_name": "ceferisbarov/TableTransforms.jl", "max_issues_repo_head_hexsha": "988265e6c7460e1d08c8f79fccd8301a840ba5c7", "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/zscore.jl", "max_forks_repo_name": "ceferisbarov/TableTransforms.jl", "max_forks_repo_head_hexsha": "988265e6c7460e1d08c8f79fccd8301a840ba5c7", "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": 26.5555555556, "max_line_length": 82, "alphanum_fraction": 0.5118549512, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7960806283052926}}
{"text": "# Rational Example\n\nstruct RationalNumber\n    n::Integer\n    d::Integer\n    function RationalNumber(n, d)\n        (n, d) = _normalize(n, d)\n        return new(n, d)\n    end\nend\n\nfunction _normalize(n::Integer, d::Integer)\n    g = gcd(n, d)\n    m = d < 0 ? -1 : 1\n    (m * n \u00f7 g, m * d \u00f7 g)\nend\n\nBase.:+(r1::RationalNumber, r2::RationalNumber) = RationalNumber(r1.n+r2.n, r1.d+r2.d)\nBase.:-(r1::RationalNumber, r2::RationalNumber) = RationalNumber(r1.n-r2.n, r1.d-r2.d)\nBase.:*(r1::RationalNumber, r2::RationalNumber) = RationalNumber(r1.n*r2.n, r1.d*r2.d)\nBase.:/(r1::RationalNumber, r2::RationalNumber) = RationalNumber(r1.n*r2.d, r1.d*r2.n)\n\nstr(r::RationalNumber) = \"$(r.n)/$(r.d)\"\n\n# Demonstration\n\nx = half = RationalNumber(5, 10)\nprintln(\"One half can be expressed as $(half.n)/$(half.d)\")\n\ny = two_thirds = RationalNumber(2,3)\n\nystr = str(y)\nprintln(\"two thirds is $(ystr)\")\nprintln(\"two thirds is $(str(y))\")\n\nprintln(\"x+y = $(str(x+y))\")\nprintln(\"x-y = $(str(x-y))\")\nprintln(\"x*y = $(str(x*y))\")\nprintln(\"x/y = $(str(x/y))\")\n", "meta": {"hexsha": "352a5b4c4329fe70850f84447fef324d74990a85", "size": 1034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rational.jl", "max_stars_repo_name": "AdamVStephen/learning-julia", "max_stars_repo_head_hexsha": "442e0dfab5c3e224927e1ca96516af87d8e81319", "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": "rational.jl", "max_issues_repo_name": "AdamVStephen/learning-julia", "max_issues_repo_head_hexsha": "442e0dfab5c3e224927e1ca96516af87d8e81319", "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": "rational.jl", "max_forks_repo_name": "AdamVStephen/learning-julia", "max_forks_repo_head_hexsha": "442e0dfab5c3e224927e1ca96516af87d8e81319", "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.85, "max_line_length": 86, "alphanum_fraction": 0.6189555126, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7960605751162114}}
{"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 \u00d7 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\u00d74 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\u00d74 DataFrame\n Row \u2502 Crt1     Crt2     Crt3     Crt4     \n     \u2502 Float64  Float64  Float64  Float64  \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502 12.9918   0.7264  -1.1009  1.59814\n   2 \u2502  4.1201   5.8824   3.4483  1.02156\n   3 \u2502  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\u2013770. doi:10.1016/0305-0548(94)00059-h \nAk\u00e7akanat, \u00d6., Aksoy, E., Teker, T. (2018). CRITIC ve MDL Temelli EDAS Y\u00f6ntemi ile TR-61 B\u00f6lgesi Bankalar\u0131n\u0131n Performans De\u011ferlendirmesi. S\u00fcleyman Demirel \u00dcniversitesi Sosyal Bilimler Enstit\u00fcs\u00fc 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(\u03f5::Ellipsoid)\n    n = size(\u03f5.H, 1)\n    return (n^(n / 2) * _unit_ball_volume(n)) / sqrt(det(\u03f5.H))\nend\n\nfunction _unit_ball_volume(n::Integer)\n    return \u03c0^(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": "using NLopt\nusing Base.Test\n\ncount = 0 # keep track of # function evaluations\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\n    global count\n    count::Int += 1\n    println(\"f_$count($x)\")\n\n    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_MMA, 2)\nlower_bounds!(opt, [-Inf, 0.])\nxtol_rel!(opt,1e-4)\n\nmin_objective!(opt, myfunc)\ninequality_constraint!(opt, (x,g) -> myconstraint(x,g,2,0), 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])\nprintln(\"got $minf at $minx after $count iterations (returned $ret)\")\n\n@test_approx_eq_eps minx[1] 1/3 1e-5\n@test_approx_eq_eps minx[2] 8/27 1e-5\n@test_approx_eq_eps minf sqrt(8/27) 1e-5\n@test ret == :XTOL_REACHED\n", "meta": {"hexsha": "8fe420b61256ab4420c35cf864c3998c67316389", "size": 965, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tutorial.jl", "max_stars_repo_name": "abelsiqueira/NLopt.jl", "max_stars_repo_head_hexsha": "befd716a8ad61778aa60f08a0ab9513d67e80735", "max_stars_repo_licenses": ["MIT"], "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/tutorial.jl", "max_issues_repo_name": "abelsiqueira/NLopt.jl", "max_issues_repo_head_hexsha": "befd716a8ad61778aa60f08a0ab9513d67e80735", "max_issues_repo_licenses": ["MIT"], "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/tutorial.jl", "max_forks_repo_name": "abelsiqueira/NLopt.jl", "max_forks_repo_head_hexsha": "befd716a8ad61778aa60f08a0ab9513d67e80735", "max_forks_repo_licenses": ["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.9761904762, "max_line_length": 69, "alphanum_fraction": 0.6207253886, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7959795777291996}}
{"text": "\"\"\"\n    struct CartesianSpace <: EuclideanSpace{\u211d}\n\nA real euclidean space `\u211d^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{\u211d}\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\u2295(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, \"\u211d^$(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 \u2248 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] \u2248 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": "# assert file to test polynomial implementation\nusing Base.Test\nusing Polynomial\n\npNULL = Poly(Float32[])\np0 = Poly([0])\np1 = Poly([0,0,0,0,0,0,0,0,0,0,0,0,0,1])\np2 = Poly([0,0,1,1])\np3 = Poly([0,0,0,0,1,2,1])\np4 = Poly([0,1,3,3,1])\np5 = Poly([0,0,0,0,0,0,0,0,0,0,0,0,0,1,4,6,4,1])\npN = Poly([0,24,15,87,3,276])\npR = Poly([1//1, -2//1, 3//4])\np1000 = Poly(randn(1000))\n\n@test length(pNULL) == 0\n@test length(p1000) == 1000\nsprint(show, p1000)\nsprint(show, pNULL)\n\n@test p3 == Poly([1,2,1])\n@test pN*10 == Poly([240, 150, 870, 30, 2760])\n@test pN/10 == Poly([2.4, 1.5, 8.7, 0.3, 27.6])\n@test 10*pNULL + pN == pN\n@test 10*p0 + pN == pN\n@test p5 + 2*p1 == Poly([1,4,6,4,3])\n@test 10*pNULL - pN == -pN\n@test p0 - pN == -pN\n@test p5 - 2*p1 == Poly([1,4,6,4,-1])\n@test p2*p2*p2 == p4\n@test p2^4 == p5\n@test pNULL^3 == pNULL\n@test pNULL*pNULL == pNULL\n\n@test polyval(pN, -.125) == 276.9609375\n@test polyval(pNULL, 10) == 0\n@test polyval(p0, -10) == 0\n@test polyval(poly([1//2, 3//2]), 1//2) == 0//1\n@test polyder(polyint(pN)) == pN\n@test polyder(pR) == Poly([2//1, -2//1])\n@test polyint(pNULL,1) == p1\n@test polyint(Poly(Rational[3, 2, 1])) == Poly(Rational[1, 1, 1, 0])\n@test polyder(p3) == Poly([2,2])\n@test polyder(p1) == polyder(p0) == polyder(pNULL) == pNULL\n\n@test poly([-1,-1]) == p3\n@test roots(p0)==roots(p1)==roots(pNULL)==[] \n@test roots(p2) == [-1]\na_roots = copy(pN.a)\n@test all(abs(sort(roots(poly(a_roots))) - sort(a_roots)) .< 1e6)\n@test length(roots(p5)) == 4\n@test roots(pNULL) == []\n@test roots(pR) == [1//2, 3//2]\n\n@test pNULL + 2 == p0 + 2 == 2 + p0 == Poly([2])\n@test p2 - 2 == -2 + p2 == Poly([1,-1])\n@test 2 - p2 == Poly([-1,1])\n\np0 = Poly([0])\np1 = Poly([1])\np2 = Poly([4, 2, -3, 6, 5])\np3 = Poly([6, 2, -3, 7])\np4 = p2 * p3\n@test divrem(p4, p2) == (p3, zero(p3))\n@test p3%p2 == p3\n@test all((abs((p2/p3 - Poly([2/3,1/9])).a)) .< eps())\n@test divrem(p0,p1) == (p0,p0)\n@test divrem(p1,p1) == (p1,p0)\n@test divrem(p2,p2) == (p1,p0)\n@test divrem(pR, pR) == (one(pR), zero(pR))\n@test_throws p1/p0\n@test_throws divrem(p0,p0)\n\n@test_throws gcd(p1, p2)\np1 = Poly([0,0,1.0,1.0])\np2 = Poly([0,0,0,1.0,2.0,1.0])\n@test gcd(p1, p2) == p1\n@test gcd(p2, p1) == p1\n\n#Tests for multivariable support\npX = Poly([1, 2, 3, 4, 5])\npS1 = Poly([1, 2, 3, 4, 5], \"s\")\npS2 = Poly([1, 2, 3, 4, 5], 's')\npS3 = Poly([1, 2, 3, 4, 5], :s)\n@test pX != pS1\n@test pS1 == pS2\n@test pS1 == pS3\n@test_throws pS1 + pX\n@test_throws pS1 - pX\n@test_throws pS1 * pX\n@test_throws pS1 / pX\n@test_throws pS1 % pX\n", "meta": {"hexsha": "ae18b47cbbcaac096b57026abe65511d4b82aa28", "size": 2487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tests.jl", "max_stars_repo_name": "JuliaPackageMirrors/Polynomial.jl", "max_stars_repo_head_hexsha": "48c164d2b7d1704d2bc272797dbbaecac212ebfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-02-19T16:41:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-03T09:35:57.000Z", "max_issues_repo_path": "test/tests.jl", "max_issues_repo_name": "JuliaPackageMirrors/Polynomial.jl", "max_issues_repo_head_hexsha": "48c164d2b7d1704d2bc272797dbbaecac212ebfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-03-16T00:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:30:56.000Z", "max_forks_repo_path": "test/tests.jl", "max_forks_repo_name": "JuliaPackageMirrors/Polynomial.jl", "max_forks_repo_head_hexsha": "48c164d2b7d1704d2bc272797dbbaecac212ebfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-02-19T16:41:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:22:02.000Z", "avg_line_length": 26.7419354839, "max_line_length": 68, "alphanum_fraction": 0.567752312, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7959612774289566}}
{"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{\u2202\u03b8}{\u2202t} = \u03bd \\frac{\u2202^2 \u03b8}{\u2202x^2},\n# ```\n#\n# in a bounded domain ``x \u2208 [-1, 1]`` with homogeneous Neumann boundary\n# conditions, ``\u2202_x \u03b8(\u00b11, 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, \u2026, N \\}``, such\n# that the solution at a given time $t$ is approximated by\n#\n# ```math\n# \u03b8(x, t) = \u2211_{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# ``\u03d5_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\"\u03d5_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\"\u03d5_i^\u2032(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 ``\u03d5_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# \u03d5_j(x) = \u2211_{i = 1}^N T_{ij} b_i(x)\n# \\quad \\text{for } j = 1, 2, \u2026, M,\n# ```\n#\n# where ``N`` is the number of B-splines ``b_i``, and ``M < N`` is the number of\n# ``\u03d5_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# \u03d5_1(x) = b_1(x) + b_2(x),\n# \\qquad\n# \u03d5_M(x) = b_{N - 1}(x) + b_N(x).\n# ```\n\n# ### Representation of the solution\n#\n# Note that the solution ``\u03b8(x, t)`` can be represented in the original and in\n# the recombined B-spline bases as\n#\n# ```math\n# \u03b8(x, t) = \u2211_{i = 1}^N v_i(t) b_i(x) = \u2211_{j = 1}^M u_j(t) \u03d5_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# \u03b8(x, 0) = \u03b8_0(x) = 1 + \\cos(\u03c0 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\u03b8\u2080(x) = 1 + cos(\u03c0 * x)\n\u03b8\u2080_spline = approximate(\u03b8\u2080, 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, \u03b8\u2080; label = L\"\u03b8_0(x)\", color = :blue)\n    lines!(ax, -1..1, x -> \u03b8\u2080_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 -> \u03b8\u2080(x) - \u03b8\u2080_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(\u03b8\u2080_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# \u03b8(x, t) = \\sum_{j = 1}^M u_j(t) \\, \u03d5_j(x).\n# ```\n#\n# Plugging this representation into the heat equation, we find\n#\n# ```math\n# \\newcommand{\\dd}{\\mathrm{d}}\n# \u2211_j \\frac{\\dd u_j}{\\dd t} \\, \u03d5_j(x) = \u03bd \u2211_j u_j \\, \u03d5_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 ``\u03c6_i``:\n#\n# ```math\n# \u2211_j \\frac{\\mathrm{d} u_j}{\\mathrm{d} t} \\, \u27e8\u03c6_i, \u03d5_j\u27e9 = \u03bd \u2211_j u_j \\, \u27e8\u03c6_i, \u03d5_j''\u27e9,\n# ```\n#\n# where ``\u27e8 f, g \u27e9 = \u222b_{-1}^1 f(x) \\, g(x) \\, \\mathrm{d} x`` is the inner product\n# between functions.\n#\n# By choosing ``M`` different test functions ``\u03c6_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# \u03bd \\mathbf{L} \\bm{u}(t),\n# ```\n#\n# where the matrices are defined by ``A_{ij} = \u27e8 \u03c6_i, \u03d5_j \u27e9`` and\n# ``L_{ij} = \u27e8 \u03c6_i, \u03d5_j'' \u27e9``.\n#\n# Two of the most common choices of test functions ``\u03c6_i`` are:\n#\n# - ``\u03c6_i(x) = \u03b4(x - x_i)``, where ``\u03b4`` 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# - ``\u03c6_i(x) = \u03d5_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 ``\u03d5_j`` and their derivatives at the collocation points:\n# ``A_{ij} = \u03d5_j(x_i)`` and ``L_{ij} = \u03d5_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 ``\u03bd``\n# in the ``\\mathbf{L}`` matrix:\n\n\u03bd = 0.01\nLcol *= \u03bd\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 = \u03bd * L * u\n    ldiv!(du, params.A, du)  # du = A \\ (\u03bd * 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\"\u03b8(x, t)\")\n    colormap = cgrad(:viridis)\n    tspan = sol.prob.tspan\n    \u0394t = tspan[2] - tspan[1]\n    for (u, t) in tuples(sol)\n        S = Spline(R, u)\n        color = colormap[(t - tspan[1]) / \u0394t]\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} = \u27e8 \u03d5_i, \u03d5_j \u27e9``, 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} = \u27e8 \u03d5_i, \u03d5_j'' \u27e9\n# = -\u27e8 \u03d5_i', \u03d5_j' \u27e9 + \\left[ \u03d5_i \u03d5_j' \\right]_{-1}^1  = -R_{ij},\n# ```\n#\n# where ``R_{ij} = \u27e8 \u03d5_i', \u03d5_j' \u27e9`` 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, ``\u03d5_i'(\u00b11) = 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 ``\u03bd`` in the\n# ``\\mathbf{R}`` matrix:\n\nparent(Rgal) .*= -\u03bd  # 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(\"\u03b8(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    \u03b8\u2080_spline = approximate(\u03b8\u2080, R)\n    u_init = coefficients(\u03b8\u2080_spline)\n    xcol = collocation_points(R)\n    Acol = collocation_matrix(R, xcol)\n    Lcol = \u03bd .* 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(\"\u03b8(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\u00d720 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 \u00d7 63 \u00d7 78 \u00d7 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\u00d720 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    \u03c9 = ones(n+1)\n    for m in 0:n-1\n        d = tc[1:m+1] .- tc[m+2]    # vector of node differences\n        @. \u03c9[1:m+1] *= d            # update previous\n        \u03c9[m+2] = prod( -d )         # compute the new one\n    end\n    w = 1 ./ \u03c9                      # 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 \u03c4(x)\n        if x==0\n            return 1.0\n        else\n            denom = isodd(N) ? N*sin(\u03c0*x/2) : N*tan(\u03c0*x/2)\n            return sin(N*\u03c0*x/2)/denom\n        end\n    end\n\n    return function (x)\n        sum( y[k]*\u03c4(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    \u03b8 = [ i*\u03c0/n for i in 0:n ]\n    x = -cos.(\u03b8)\n\n    # Compute the C-C weights.\n    c = similar(\u03b8)\n    c[[1,n+1]] .= 1/(n^2-1)\n    s = sum( cos.(2k*\u03b8[2:n])/(4k^2-1) for k in 1:n/2-1 )\n    v = @. 1 - 2s - cos(n*\u03b8[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    \u03b2 = @. 0.5/sqrt(1-(2*(1:n-1))^(-2))\n    T = diagm(-1=>\u03b2,1=>\u03b2)\n    \u03bb,V = eigen(T)\n    p = sortperm(\u03bb)\n    x = \u03bb[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": "using IntervalWavelets\nusing OffsetArrays\nusing Test\n\n\n@testset \"Interior scaling functions\" begin\n    @testset \"Dyadic dilation matrix has the expected form\" begin\n        h1 = interior_filter(3, :min)\n        H1 = IntervalWavelets.dyadic_dilation_matrix(h1)\n\n        @test size(H1) == (length(h1) - 2, length(h1) - 2)\n\n        @test H1 == sqrt(2) * \n        [ h1[1] h1[0]    0     0  ;\n          h1[3] h1[2] h1[1] h1[0] ;\n          h1[5] h1[4] h1[3] h1[2] ;\n             0     0  h1[5] h1[4] ]\n\n\n        h2 = interior_filter(3, :symmlet)\n        H2 = IntervalWavelets.dyadic_dilation_matrix(h2)\n\n        @test H2 == sqrt(2) * \n        [ h2[-1] h2[-2]      0      0  ;\n          h2[1]  h2[0]   h2[-1] h2[-2] ;\n          h2[3]  h2[2]   h2[1]  h2[0] ;\n             0      0    h2[3]  h2[2] ]\n    end\n\n\n    @testset \"Construct interior scaling function\" begin\n        h = interior_filter(2)\n        phi = interior_scaling_function(h)\n\n        @test collect(support(h)) == Integer.(support(phi))\n        @test vanishing_moments(phi) == 2\n        @test resolution(phi) == 0\n\n\n        phi = interior_scaling_function(h, 1)\n\n        @test vanishing_moments(phi) == 2\n        @test resolution(phi) == 1\n\n\n        @test_throws DomainError interior_scaling_function(h, -1)\n    end\n\n\n    @testset \"Specific interior scaling functions\" begin\n        h = interior_filter(2)\n        phi = interior_scaling_function(h, 1)\n\n        @test phi.(support(phi)) \u2248 [0.0 ; 0.93301 ; 1.36602 ; 0.0 ; -0.36602 ; 0.06698 ; 0.0] atol = 10.0^-4\n    end\n\n\n    @testset \"Haar scaling functions\" begin\n        haar_filter = interior_filter(1, :min)\n\n        haar = interior_scaling_function(haar_filter)\n        @test haar.(support(haar)) == [1.0 ; 0.0]\n\n        haar = interior_scaling_function(haar_filter, 1)\n        @test haar.(support(haar)) \u2248 [1.0 ; 1.0 ; 0.0]\n    end\n\n\n    @testset \"Increase resolution of interior scaling function\" begin\n        h = interior_filter(2)\n        phi0 = interior_scaling_function(h)\n\n        phi0_support = support(phi0)\n        @test phi0_support == IntervalWavelets.all_dyadic_rationals(-1, 2, 0)\n\n        phi1 = IntervalWavelets.increase_resolution(phi0)\n        @test support(phi1) == IntervalWavelets.all_dyadic_rationals(-1, 2, 1)\n\n        @test phi1.(phi0_support) == phi0.(phi0_support)\n    end\nend\n\n", "meta": {"hexsha": "0665113d12b3f80b0f3286b94c3caa943df0405b", "size": 2317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/InteriorScalingFunction.jl", "max_stars_repo_name": "robertdj/IntervalWavelets.jl", "max_stars_repo_head_hexsha": "93c52c0e0f65d106ade6879355d8d11fd3081bd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-12T11:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-12T11:47:44.000Z", "max_issues_repo_path": "test/InteriorScalingFunction.jl", "max_issues_repo_name": "robertdj/IntervalWavelets.jl", "max_issues_repo_head_hexsha": "93c52c0e0f65d106ade6879355d8d11fd3081bd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-09-04T16:44:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-21T21:22:55.000Z", "max_forks_repo_path": "test/InteriorScalingFunction.jl", "max_forks_repo_name": "robertdj/IntervalWavelets.jl", "max_forks_repo_head_hexsha": "93c52c0e0f65d106ade6879355d8d11fd3081bd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:14:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:15.000Z", "avg_line_length": 27.9156626506, "max_line_length": 108, "alphanum_fraction": 0.5835131636, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8688267677469951, "lm_q1q2_score": 0.7959405524868909}}
{"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, '\u2170' + (r.n - 1) % 10 )  # nice display; '\u2170' 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 \"\ud83d\ude04\"^ (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) = \"\ud83d\ude04\"^ (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*(\u03b1::Number,   g::Function) = x -> \u03b1 * g(x)   # Scalar times function\n\n*(f::Function, \u03bb::Number)   = x -> f(\u03bb * 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\u03c0, \u03b1=[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 \u2248 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\u2207u_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\u03bb1(r,s) = -(r+s)/2\n\u03bb2(r,s) = (1+r)/2\n\u03bb3(r,s) = (1+s)/2\n\u03bb(r,s) = [\u03bb1.(r,s) \u03bb2.(r,s) \u03bb3.(r,s)]\nd\u03bbr() = [-.5 .5 0.0]\nd\u03bbs() = [-.5 0.0 .5]\n\n# x,y = lists of vertices\nfunction compute_geometric_terms(x,y)\n    # dx(r,s)/dr = d\u03bb1/dr*x1 + d\u03bb2/dr*x2 + d\u03bb3/dr*x3 = [d\u03bb1/dr d\u03bb2/dr d\u03bb3/dr] * [x1; x2; x3]\n    dxdr,dydr = d\u03bbr()*x, d\u03bbr()*y\n    dxds,dyds = d\u03bbs()*x, d\u03bbs()*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\u03bbdx = drdx*d\u03bbr() + dsdx*d\u03bbs() # d\u03bbr() = [d\u03bb1/dr d\u03bb2/dr d\u03bb3/dr]\n        d\u03bbdy = drdy*d\u03bbr() + dsdy*d\u03bbs() # d\u03bbs() = [d\u03bb1/ds d\u03bb2/ds d\u03bb3/ds]\n        reference_elem_area = 2.0\n        @. A[ids,ids] += J*reference_elem_area*(d\u03bbdx'*d\u03bbdx + d\u03bbdy'*d\u03bbdy) # (d\u03bbdx'*d\u03bbdx)_ij = d\u03bbj/dx * d\u03bbi/dx\n\n        # assemble mass matrix using quadrature: \u222b\u03d5_j * \u03d5_i = integrals of quadratic\n        M[ids,ids] .+= J*reference_elem_area*(\u03bb(rq,sq)'*Diagonal(wq)*\u03bb(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*\u03bb(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,\u2207u_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(\u03bb(r_mid,s_mid)) * w_mid * \u2207u_dot_n(x_mid,y_mid) # \u222b \u2207u\u22c5n \u03d5_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\u0394t = .001\nT = .5\n\n# create/prefactor Crank-Nicolson matrix\nC = (M + .5*\u0394t*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,\u2207u_dot_n)\nb_Dirichlet = compute_Dirichlet_BCs(M+.5*\u0394t*A,mesh,ref_elem_info,on_Dirichlet,u_Dirichlet)\n\nNsteps = ceil(T/\u0394t)\n\u0394t = 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*\u0394t*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\u03f5(x2,x1,l) = (x2 - x1)/l\r\n\r\n#Strain Vector\r\n\u03f5M = [\u03f5(u[2],u[1],l)\r\n      \u03f5(u[3],u[2],l) \r\n      \u03f5(u[4],u[3],l) ]\r\nprintln(\"Element strain vector (inch/inch):\")\r\ndisplay(\u03f5M)\r\n\r\n# Stress Function\r\n\u03c3(E,\u03f5) = E*\u03f5\r\n\r\n# Stress Vector\r\n\u03c3M = [\u03c3(E,\u03f5M[1])\r\n      \u03c3(E,\u03f5M[2])\r\n      \u03c3(E,\u03f5M[3])]\r\nprintln(\"Element Stress vector (psi):\")\r\ndisplay(\u03c3M)\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": "using Test, SineWaves, FFTW\n\n@testset \"SineWave constructor tests\" begin\n    frequency = 440.0\n    samplerate = 48000.0\n    delta = 2*pi*frequency/samplerate\n    sinewave = SineWave(frequency, samplerate)\n\n    @test sinewave.current \u2248 0.0\n    @test sinewave.previous \u2248 -sin(delta)\n    @test sinewave.cosine \u2248 cos(delta)\n\n    too_hi_frequency = 40000.0\n    \n    @test_throws ErrorException SineWave(too_hi_frequency, samplerate)\nend\n\n@testset \"fill! function tests\" begin\n    frequency = 440.0\n    samplerate = 48000.0\n    delta = 2*pi*frequency/samplerate\n    N = 512\n\n    sinewave = SineWave(frequency, samplerate)\n    buffer = zeros(Float64, N)\n    fill!(buffer, sinewave)\n    \n    @test buffer \u2248 sin.(range(delta; step=delta, length = N))\nend\n\n@testset \"spectrum function tests\" begin\n    frequency = 440.0\n    samplerate = 48000.0\n    delta = 2*pi*frequency/samplerate\n    N = 512\n\n    sinewave = SineWave(frequency, samplerate)\n    buffer = zeros(Float64, N)\n    fill!(buffer, sinewave)\n    \n    buffer_ft = FFTW.rfft(buffer)\n    expected = abs.(buffer_ft)\n\n    @test spectrum(buffer) \u2248 expected\nend\n", "meta": {"hexsha": "e7d2e5cecad9757407167bdd90bce23f773e3cb0", "size": 1105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "338rajesh/SineWaves.jl", "max_stars_repo_head_hexsha": "18e4d627ae3e38a8e0fcd5e59cb534d228251a12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-02-07T16:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T07:57:11.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "jakubwro/SineWave.jl", "max_issues_repo_head_hexsha": "18e4d627ae3e38a8e0fcd5e59cb534d228251a12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-04T20:57:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-04T21:01:37.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "jakubwro/SineWave.jl", "max_forks_repo_head_hexsha": "18e4d627ae3e38a8e0fcd5e59cb534d228251a12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-09T00:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T16:31:47.000Z", "avg_line_length": 24.0217391304, "max_line_length": 70, "alphanum_fraction": 0.6769230769, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7958539680018083}}
{"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    \u03b1 ~ Uniform(-4.0,6.0)\n    \u03b2 ~ Uniform(-5.0,50)\n\tfor i in 1:length(dose)\n\t\t\u0398 = invlogit(\u03b1+\u03b2*dose[i])\n\t\tdeaths[i] ~ Binomial(n[i],\u0398)\n\tend\nend\n    \nmodel1 = ld50_fit(dose,nd,n)\nchain = Turing.sample(model1,NUTS(0.65),1000)\n\nalpha = vec(chain[:\u03b1])\nbeta = vec(chain[:\u03b2])\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": "using Gurobi\nfunction sudoku_gurobi(X)\n# SUDOKU_GUROBI Solve a sedoku puzzle using Gurobi for an Binary LP\n#\n# S=sudoku_gurobi(X)\n#   X has a set of initial conditions where anything ~= 1 ... 9 is an\n#   unknown\n# S is the solved sudoku puzzle\n\n    assert(all(size(X) == (9, 9)))\n    # create variables\n    nvars = 9*9*9\n\n    # index the variables for easier access\n    vars = zeros(Int64, 9, 9, 9)\n    ind = 1\n    for i = 1:9\n        for j = 1:9\n            for v = 1:9\n                vars[i, j, v] = ind\n                ind = ind + 1\n            end\n        end\n    end\n\n    #obj = ones(Int64, 1, nvars) # no objective, just constraints\n\n    # add known cells as constraints\n\n    A = spzeros(nvars, 0)\n    b = ones(1, 0)\n\n    for i = 1:9\n        for j = 1:9\n            if X[i, j] < 1 || X[i, j] > 9\n                # this is a free variable, ignore\n            else\n                # this is a constraint, add it\n                cons = zeros(nvars)\n                cons[vars[i, j, X[i, j]]] = 1\n                A = [A sparse(cons)] # append a row\n                b = [b 1]\n            end\n        end\n    end\n\n    #\n    # add sudoku constraints\n    #\n\n    # each cell only has one value\n    for i = 1:9\n        for j = 1:9\n            cons = zeros(Int64, nvars)\n            for v = 1:9\n                cons[vars[i, j, v]] = 1\n            end\n            A = [A sparse(cons)]\n            b = [b 1]\n        end\n    end\n\n    # each row has 1-9\n    for i = 1:9\n        for v = 1:9\n            cons = zeros(nvars)\n            # the value v only appears in each row once\n            for j = 1:9\n                cons[vars[i, j, v]] = 1\n            end\n            A = [A sparse(cons)]\n            b = [b 1]\n        end\n    end\n\n    # each column has 1-9\n    for j = 1:9\n        for v = 1:9\n            cons = zeros(nvars)\n            # the value v only appears in each row once\n            for i = 1:9\n                cons[vars[i, j, v]] = 1\n            end\n            A = [A sparse(cons)]\n            b = [b 1]\n        end\n    end\n\n    # subgrid has 1-9\n    for v = 1:9\n        for i0 = 0:2\n            for j0 = 0:2\n                cons = zeros(nvars)\n                for i = 1:3\n                    for j = 1:3\n                        cons[vars[i+3*i0, j+3*j0, v]] = 1\n                    end\n                end\n                A = [A sparse(cons)]\n                b = [b 1]\n            end\n        end\n    end\n\n    # setup Gurobi call\n    env = Gurobi.Env()\n\n    model = Gurobi.Model(env, \"sudoku_blp\", :minimize)\n\n    # add binary variables\n    add_bvars!(model, zeros(nvars))\n\n    # have the variables incorporated into the model\n    update_model!(model)\n\n    add_constrs_t!(model, A, '=', vec(b))\n\n    # run optimization\n    optimize(model)\n\n    # get results\n    x = get_solution(model)\n\n    # assign solution\n    S = zeros(Int64, 9 ,9)\n    for i = 1:9\n        for j = 1:9\n            for v = 1:9\n                if x[vars[i, j, v]] > 0\n                    S[i, j] = v\n                end\n            end\n        end\n    end\n    return S\nend\n\n##\nX = [0 0 8 0 0 0 6 0 0;\n     0 2 0 0 0 0 0 1 0;\n     5 0 0 6 0 0 0 0 9;\n     0 0 7 0 4 0 0 0 3;\n     0 4 0 2 0 9 0 6 0;\n     6 0 0 0 1 0 8 0 0;\n     9 0 0 0 0 7 0 0 4;\n     0 5 0 0 0 0 0 7 0;\n     0 0 1 0 0 0 5 0 0];\nS = sudoku_gurobi(X)\n\n##\n\nX = [0 0 4 9 3 0 0 0 5\n     2 8 0 0 0 0 0 6 0\n     0 1 0 0 2 0 0 4 0\n     0 0 5 0 4 0 0 0 7\n     0 2 0 0 0 5 0 0 0\n     0 0 0 0 0 6 0 0 0\n     0 0 0 1 0 0 0 8 2\n     8 0 0 0 9 0 0 0 1\n     0 7 0 0 0 0 0 0 0];\nS = sudoku_gurobi(X)\n\n##\nX = [0 6 0 0 0 0 9 0 0;\n     1 7 0 0 0 0 0 0 0;\n     0 0 5 0 1 0 0 8 6;\n     0 0 0 0 0 0 7 0 0;\n     0 0 0 0 8 6 0 9 0;\n     0 4 0 0 9 0 0 0 2;\n     0 3 8 0 0 0 0 1 0;\n     6 0 0 0 0 5 0 2 0;\n     0 0 0 0 0 0 3 0 0];\nS = sudoku_gurobi(X)\n\n##\n# http://www.nytimes.com/crosswords/game/sudoku/hard\n", "meta": {"hexsha": "bf309cdcd0798636aaa79294494a6bea9a97fa33", "size": 3824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lecture-3-sudoku-gurobi.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-sudoku-gurobi.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-sudoku-gurobi.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": 21.604519774, "max_line_length": 69, "alphanum_fraction": 0.4312238494, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7958152668182263}}
{"text": "doc\"\"\"\n    Cauchy(\u03bc, \u03c3)\n\nThe *Cauchy distribution* with location `\u03bc` and scale `\u03c3` 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    \u03bc::Float64\n    \u03c3::Float64\n\n    Cauchy(\u03bc::Real, \u03c3::Real) = (@check_args(Cauchy, \u03c3 > zero(\u03c3)); new(\u03bc, \u03c3))\n    Cauchy(\u03bc::Real) = new(\u03bc, 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.\u03bc\nscale(d::Cauchy) = d.\u03c3\n\nparams(d::Cauchy) = (d.\u03bc, d.\u03c3)\n\n\n#### Statistics\n\nmean(d::Cauchy) = NaN\nmedian(d::Cauchy) = d.\u03bc\nmode(d::Cauchy) = d.\u03bc\n\nvar(d::Cauchy) = NaN\nskewness(d::Cauchy) = NaN\nkurtosis(d::Cauchy) = NaN\n\nentropy(d::Cauchy) = log4\u03c0 + log(d.\u03c3)\n\n\n#### Functions\n\nzval(d::Cauchy, x::Float64) = (x - d.\u03bc) / d.\u03c3\nxval(d::Cauchy, z::Float64) = d.\u03bc + z * d.\u03c3\n\npdf(d::Cauchy, x::Float64) = 1.0 / (\u03c0 * scale(d) * (1.0 + zval(d, x)^2))\nlogpdf(d::Cauchy, x::Float64) = - (log1psq(zval(d, x)) + log\u03c0 + log(d.\u03c3))\n\nfunction cdf(d::Cauchy, x::Float64)\n    \u03bc, \u03c3 = params(d)\n    inv\u03c0 * atan2(x - \u03bc, \u03c3) + 0.5\nend\n\nfunction ccdf(d::Cauchy, x::Float64)\n    \u03bc, \u03c3 = params(d)\n    inv\u03c0 * atan2(\u03bc - x, \u03c3) + 0.5\nend\n\nfunction quantile(d::Cauchy, p::Float64)\n    \u03bc, \u03c3 = params(d)\n    \u03bc + \u03c3 * tan(\u03c0 * (p - 0.5))\nend\n\nfunction cquantile(d::Cauchy, p::Float64)\n    \u03bc, \u03c3 = params(d)\n    \u03bc + \u03c3 * tan(\u03c0 * (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.\u03bc) - d.\u03c3 * 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, \"\u03c3\u00b2 = $(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    \u03f5 = randn(p) .* sqrt.(sem.err_var)\n    return (I - sem.B) \\ \u03f5\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    \u03f5 = randn(p) .* sqrt.(sem.err_var)\n    \u03f5[do_variables] .= do_values\n    B = copy(sem.B)\n    B[do_variables, :] .= 0\n    return (I - B) \\ \u03f5\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 ``\u03c7_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\u03c7_k = \\\\frac{\\\\sum{\\\\left(x^{(k)}_i - \u03bc_{x^{(k)}}\\\\right) \n\\\\left(y_i - \u03bc_y\\\\right)}}{N \u03c3_{x^{(k)}} \u03c3_y} \\\\, ,\n``\n\nwhere ``\u03bc`` and ``\u03c3`` 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+\u221a2, 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)] = \"\u22ee\"\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": "\n# Demonstrate/test functions in cornerfeatures\n\nusing ImageProjectiveGeometry\nusing FileIO\nusing PyPlot\n\nrad = 6\n\n#img = PyPlot.imread(\"../sampleimages/lena.tif\");\nimg = load(\"../sampleimages/lena.tif\");\n\n# Convert image from Gray Fixed Point Numbers to a simple array of floats\nimg = float(img);   \nfigure(10), PyPlot.imshow(img);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"Input image\")\n\nprintln(\"Harris corner detector\")\n(cimg, r, c) = ImageProjectiveGeometry.harris(img, 1,k= 0.04, radius=rad, N=100, subpixel=false, img=img, fig=12)\nfigure(12); PyPlot.title(\"Harris corners\")\ncimg[cimg .< 0] .= 0;   # eliminate -ve values\nfigure(2); PyPlot.imshow(cimg.^0.25);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"Harris corner strength image\")\nImageProjectiveGeometry.keypause()\n\nprintln(\"Noble corner detector\")\n(cimg, r, c) = ImageProjectiveGeometry.noble(img, 1, radius=rad, N=100, subpixel=false, img=img, fig=12);\nfigure(12); PyPlot.title(\"Noble corners\")\nfigure(2); PyPlot.imshow(cimg.^0.25);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"Noble corner strength image\")\nImageProjectiveGeometry.keypause()\n\nprintln(\"Shi-Tomasi corner detector\")\n(cimg, r, c) = ImageProjectiveGeometry.shi_tomasi(img, 1, radius=rad, N=100, subpixel=false, img=img, fig=12);\nfigure(12); PyPlot.title(\"Shi_Tomasi corners\")\nfigure(2); PyPlot.imshow(cimg.^0.25);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"Shi-Tomasi corner strength image\")\nImageProjectiveGeometry.keypause()\n\nprintln(\"-ve Hessian features\")\nhdet = ImageProjectiveGeometry.hessianfeatures(img, 1)\n(r, c) = ImageProjectiveGeometry.nonmaxsuppts(-hdet, N=100, img=img, fig=12)\nfigure(12); PyPlot.title(\"-ve Hessian features\")\nfigure(2); PyPlot.imshow(-hdet);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"-ve Hessian image\")\nImageProjectiveGeometry.keypause()\n\nprintln(\"+ve Hessian features\")\nhdet = ImageProjectiveGeometry.hessianfeatures(img, 1)\n(r, c) = ImageProjectiveGeometry.nonmaxsuppts(+hdet, N=100, img=img, fig=12)\nfigure(12); PyPlot.title(\"+ve Hessian features\")\nfigure(2); PyPlot.imshow(hdet);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"+ve Hessian image\")\nImageProjectiveGeometry.keypause()\n\nprintln(\"Coherence\")\ncimg = ImageProjectiveGeometry.coherence(img, 2)\n(r, c) = ImageProjectiveGeometry.nonmaxsuppts(cimg, N=10, img=img, fig=12)\nfigure(2); PyPlot.imshow(cimg);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"Coherence image\")\nImageProjectiveGeometry.keypause()\n\nprintln(\"Fast radial\")\n(S, So) = ImageProjectiveGeometry.fastradial(img, [1, 3, 5, 7])\n(r, c) = ImageProjectiveGeometry.nonmaxsuppts(-S, N=10, img=img, fig=12)\nfigure(12); PyPlot.title(\"Fast radial features\")\nfigure(2); PyPlot.imshow(-S);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"Fast radial image: orientation and gradient magnitude image\")\n\nfigure(3); PyPlot.imshow(-So);\nPyPlot.set_cmap(PyPlot.ColorMap(\"gray\"))\nPyPlot.title(\"Fast radial image: orientation only image\")\n\nnothing\n\n\n", "meta": {"hexsha": "4eed27eda16dc3553b00646eacec567fe8cd7e87", "size": 2998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cornerdemo.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_stars_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cornerdemo.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_issues_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cornerdemo.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_forks_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_forks_repo_licenses": ["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.2705882353, "max_line_length": 113, "alphanum_fraction": 0.7531687792, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7955480383127059}}
{"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    \u03c4 = (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] - \u03c4, 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, \u0394M = 0.0266, 0.0001\nL, \u0394L = 0.380, 0.001\nL1,\u0394L1= 0.025, 0.001\nL2,\u0394L2= 0.190, 0.001\nd,\u0394d= 0.008,0.001\n\nm,\u0394m = 0.0753, 0.0001\nh,\u0394h = 0.02, 0.001\nde,\u0394de = 0.025, 0.001\ndi,\u0394di = 0.008, 0.001\n\n# Barra\n\nIh = (1/12)*M*L^2 + (1/16)*M*de^2\n\u0394Ih = (1/12)*(\u0394M*L^2 + 2*M*L*\u0394L) + (1/16)*(\u0394M*d + 2*M*d*\u0394d)\n\nIh_eixo = Ih + M*(L2 - L1)^2\n\u0394Ih_eixo = \u0394Ih + \u0394M*(L2-L1)^2 + 2*M*(L2-L1)*(\u0394L2+\u0394L1)\n\n\n\n# Cilindro\n\nIcl = (1/16)*m*(de^2 + di^2) +  (1/12)*m*h^2\n\u0394Icl = (1/16)*(\u0394m*(de^2+di^2) + 2*m*(de*\u0394de+di*\u0394di)) + (1/12)*(\u0394m*h^2 + 2*m*h*\u0394h)\n\nIcl_cm = Icl + m*(L2 - h/2)^2\n\u0394Icl_cm = \u0394Icl + \u0394m*(L2- h/2)^2 + 2*m*(L2-h/2)*(\u0394L2+ \u0394h/2)\n\nIcl_eixo = Icl + m*(L - L1 - h/2)^2\n\u0394Icl_eixo = \u0394Icl + \u0394m*(L - L1 - h/2)^2 + 2*m*(L-L1-h/2)*(\u0394L +\u0394L1 + \u0394h/2)\n\nprintln(\"\\n Sistema no centro de massa\\n\")\nprintln(\"======================\")\nprintln(\"Ih \u00b1 \u0394Ih =\" , round(Ih,digits=8), \" \u00b1 \", round(\u0394Ih,digits=8))\nprintln(\"Icl_cm \u00b1 \u0394Icl_cm =\" , round(Icl_cm,digits=8), \" \u00b1 \", round(\u0394Icl_cm,digits=8))\n\nprintln(\"\\n Sistema no eixo \\n \")\nprintln(\"======================\")\nprintln(\"Ih_eixo \u00b1 \u0394Ih_eixo =\" , round(Ih_eixo,digits=8), \" \u00b1 \", round(\u0394Ih_eixo,digits=8))\nprintln(\"Icl_eixo \u00b1 \u0394Ih_eixo =\" , round(Icl_eixo,digits=8), \" \u00b1 \",round(\u0394Icl_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": "using Graphics\nusing Base.Test\n\n# Part 1. Geometry\n\n## Point-vector identity (typealias)\n@test Point(2, 1) == Vec2(2, 1)\n\n## Vector operators\n@test Vec2(1, 2) + Vec2(3, 4) == Vec2(4, 6)\n@test Vec2(1, 2) - Vec2(3, 4) == Vec2(-2, -2)\n@test Vec2(1, 2) * 1 == Vec2(1, 2) # identity\n@test Vec2(1, 2) * 0 == Vec2(0, 0) # null\n@test Vec2(1, 2) * 2 == Vec2(2, 4) # scalar multiplication\n@test Vec2(1, 2) / 2 == Vec2(0.5, 1)\n\n\n## rotation: rotate()\n@test_approx_eq rotate(Vec2(1, 2), \u03c0, Vec2(1, 1)).x 1\n@test_approx_eq rotate(Vec2(1, 2), \u03c0, Vec2(1, 1)).y 0\n@test_approx_eq rotate(Vec2(1, 2), 2\u03c0).x 1\n@test_approx_eq rotate(Vec2(1, 2), 2\u03c0).y 2\n\n## Euclidean norm/magnitude: norm()\n@test norm(Vec2(1, 2)) == sqrt(5)\n@test norm(Vec2(0, 0)) == 0\n\n## Bounding boxes: BoundingBox\nBBT_point_1 = Vec2(1, 1)\nBBT_point_2 = Vec2(2, 3)\nBBT_point_3 = Vec2(4, 5)\nBBT = BoundingBox(BBT_point_1, BBT_point_2, BBT_point_3)\n\n### BoundingBox attributes\n@test BBT == BoundingBox(1, 4, 1, 5)\n@test height(BBT) == 4\n@test width(BBT) == 3\n@test diagonal(BBT) == 5\n@test_approx_eq aspect_ratio(BBT) 1.333333333333\n@test xmin(BBT) == 1\n@test xmax(BBT) == 4\n@test center(BBT) == Vec2(2.5, 3)\n@test xrange(BBT) == (1, 4)\n@test yrange(BBT) == (1, 5)\n\n### BoundingBox operations\nBBT_1 = BoundingBox(2, 3, 4, 5)\nBBT_2 = BoundingBox(6, 7, 8, 9)\n\n#### BoundingBox (+)\n@test BBT_1 + BBT_2 == BoundingBox(2, 7, 4, 9)\n\n#### BoundingBox (&)\n@test BBT_1 & BBT_2 == BoundingBox(6, 3, 8, 5)\n\n#### deform()\n@test deform(BBT_1, -1, 2, -3, 4) == BoundingBox(1, 5, 1, 9)\n\n#### shift()\n@test shift(BBT_1, -1, 2) == BoundingBox(1, 2, 6, 7)\n\n#### scale()\n@test BBT_1 * 3 == BoundingBox(1, 4, 3, 6)\n\n#### rotate()\nBBT_3 = rotate(BBT_1, \u03c0, Point(0, 1))\n@test_approx_eq BBT_3.xmin -3\n@test_approx_eq BBT_3.ymin -3\n@test_approx_eq BBT_3.xmax -2\n@test_approx_eq BBT_3.ymax -2\n\n#### with_aspect_ratio()\n@test with_aspect_ratio(BBT_1, 2) == BoundingBox(2.25, 2.75, 4, 5)\n@test with_aspect_ratio(BBT_1, 0.5) == BoundingBox(2, 3, 4.25, 4.75)\n\n#### isinside()\n@test isinside(BBT_1, Point(2.5, 4.5))\n@test isinside(BBT_1, Point(2, 4))\n@test isinside(BBT_1, Point(1, 3)) == false\n", "meta": {"hexsha": "1727d99302fd2478a2c40c26473e409c16b59eef", "size": 2113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaPackageMirrors/Graphics.jl", "max_stars_repo_head_hexsha": "0b74596ad3e353534d6b819f784be23041d13bff", "max_stars_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Graphics.jl", "max_issues_repo_head_hexsha": "0b74596ad3e353534d6b819f784be23041d13bff", "max_issues_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Graphics.jl", "max_forks_repo_head_hexsha": "0b74596ad3e353534d6b819f784be23041d13bff", "max_forks_repo_licenses": ["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.4125, "max_line_length": 68, "alphanum_fraction": 0.6351159489, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.7954626585022843}}
{"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), \" \u2260 $m \u00d7 $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": "\"\"\"\n`X = DataUtils.expand_poly(x; degree = 5)`\n\nPerforms a polynomial basis expansion of the given `degree`\nfor the vector `x`.\nThe return value `X` is a matrix of size `(degree, length(x))`.\n\nNote: all the features of `X` are centered and rescaled.\n\"\"\"\nfunction expand_poly(x::AbstractVector{T}; degree::Int = 5) where T<:Number\n    n = length(x)\n    x_vec = convert(Vector{Float64}, copy(collect(x)))\n    X = zeros(Float64, (degree, n))\n    @inbounds for i = 1:n\n        for d = 1:degree\n            X[d, i] += x_vec[i]^(d)\n        end\n    end\n    X\nend\n", "meta": {"hexsha": "ebc926e0e4e8bc4e9a3aeaaf590058f856287be2", "size": 556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis_expansion.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MLDataUtils.jl-cc2ba9b6-d476-5e6d-8eaf-a92d5412d41d", "max_stars_repo_head_hexsha": "2f845c6482e821d56f75353318a8c3bd507f5b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2016-03-14T19:43:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:24:41.000Z", "max_issues_repo_path": "src/basis_expansion.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MLDataUtils.jl-cc2ba9b6-d476-5e6d-8eaf-a92d5412d41d", "max_issues_repo_head_hexsha": "2f845c6482e821d56f75353318a8c3bd507f5b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2016-02-12T22:06:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T08:46:23.000Z", "max_forks_repo_path": "src/basis_expansion.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MLDataUtils.jl-cc2ba9b6-d476-5e6d-8eaf-a92d5412d41d", "max_forks_repo_head_hexsha": "2f845c6482e821d56f75353318a8c3bd507f5b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2016-03-14T19:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T21:39:17.000Z", "avg_line_length": 26.4761904762, "max_line_length": 75, "alphanum_fraction": 0.618705036, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7954626549141323}}
{"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# \u2554\u2550\u2561 e6bbe0a2-3f9c-431a-894d-32279bef9e73\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(title = \"Contents\")\nend\n\n# \u2554\u2550\u2561 73a77da6-7ec7-4460-9542-bb994676a375\nusing Plots\n\n# \u2554\u2550\u2561 25afb2d2-f437-11eb-327c-496dc439ccfa\nmd\"\"\"\n# Primes and Matters of Efficiency\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u0308ve 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a3d579fc-b5d9-4662-9823-b171e4a29fab\nfindPrimes(100)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a346aa06-7db4-4d7a-aad8-bf005c294c67\n@time findPrimes(100000)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 656b291e-f430-4e32-a3c9-87553cf2b1a5\nplotTime(findPrimes, 5000, 20)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9e76abdc-ddf9-4edd-a40d-059706f556d0\n@time findPrimesV2(100_000)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bc2831a1-f808-4bc7-afaf-994abefb5286\n@time findPrimesV3(100000)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 54c591db-16c9-4c9e-9d01-444558af9c6e\nfindPrimesV3(1_000_000)\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e9cdb8d0-3daa-4ada-9344-45099f184a64\nfindPrimesV4(100000);\n\n# \u2554\u2550\u2561 86076221-f0eb-4434-b15e-abcc7fc54384\nfindPrimesV4(1000000);\n\n# \u2554\u2550\u2561 998e600b-6933-48a9-bcf4-f7c1f981411e\nfindPrimesV4(10000000);\n\n# \u2554\u2550\u2561 bf89a580-d02c-4c14-af67-f249071b4d5e\nfindPrimesV4(100000000);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cdefc0aa-aefa-4c62-b8a9-692331c9bf50\nprimes = findPrimesV4(10_000_000);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1455bae3-7b50-4f0f-b521-b5aa5b9ba926\nplotPNT(primes)\n\n# \u2554\u2550\u2561 54f33702-08e9-439f-9d28-c783d7c27547\nmd\"\"\"\nAs predicted, the ratio does seem to tend towards $1$, be that very slowly.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6d322108-fa1b-41ad-81d6-5f36b6ef2fb1\nverifyGoldbach(100000, primes)\n\n# \u2554\u2550\u2561 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\u2013Mertens constant, as $n$ tends to infinity. Let us verify that this result is consistent with our data:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 00484f64-99c0-43b0-97aa-2c2d3ed98318\nplotReciprocal(primes)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250025afb2d2-f437-11eb-327c-496dc439ccfa\n# \u255f\u2500b735e72f-1498-4bf7-9f30-93a46aa46392\n# \u255f\u2500480b1c62-9a1d-4504-8872-c388403bec0b\n# \u255f\u25006164b325-44b8-478e-a122-a871c44d7ab1\n# \u255f\u250024f264de-60d8-463b-8907-0a43f8297e52\n# \u2560\u255053cd01c6-0090-47a0-ad59-63950fe471c1\n# \u2560\u2550e3525717-d598-4730-9ee0-b65ea09f7ce0\n# \u2560\u25509f7705cb-775b-4e86-bc70-70b2e852fbc2\n# \u255f\u250048e8d826-a81c-42fa-910b-abd3d80a230d\n# \u2560\u2550a3d579fc-b5d9-4662-9823-b171e4a29fab\n# \u255f\u2500dc109446-aa32-4fb7-8f74-edc0c6f98c6a\n# \u2560\u2550a346aa06-7db4-4d7a-aad8-bf005c294c67\n# \u255f\u2500ba0eae87-4eec-4387-a210-64e0f2126f87\n# \u255f\u2500e5293427-7721-4a89-ab7b-0c8fb4a618cf\n# \u255f\u2500af8fa992-1bc8-4896-8f6c-8edf3f19c475\n# \u2560\u2550aa777745-618a-4681-b73a-1a1ca978d165\n# \u2560\u2550656b291e-f430-4e32-a3c9-87553cf2b1a5\n# \u255f\u25007c8670bf-85f6-438c-b9d7-a9b1ca4a6c01\n# \u255f\u2500a4232c06-eb44-4f7c-a8eb-09aa524cc1a7\n# \u2560\u2550f4b38f40-6c51-430a-a7fd-5029e3b6ab0f\n# \u255f\u250017fa50b7-afee-42f9-b622-d18ef1060720\n# \u2560\u2550519ce97d-fde8-49c7-8b92-56185bd02333\n# \u2560\u25509e76abdc-ddf9-4edd-a40d-059706f556d0\n# \u255f\u2500ae3c3fa7-0581-46e1-a3f3-abe49173ed1c\n# \u255f\u25002b4873be-3cb7-4c2a-b8a0-451baddf428f\n# \u255f\u2500c28f9636-7d0c-4bd2-9c4d-bfc127ea06bc\n# \u255f\u2500ce2733ab-10a6-4e87-aae4-ed30fa346823\n# \u255f\u2500aa396120-1a8d-4d13-9558-1faad05f76c7\n# \u2560\u25505f99ba92-7c35-4e6b-a3fc-f42178c43cad\n# \u2560\u25503b53142b-d6bd-49e3-91b5-689cdb1cac01\n# \u2560\u2550bc2831a1-f808-4bc7-afaf-994abefb5286\n# \u255f\u2500157a17af-eb12-4d6d-be12-37a1b609005d\n# \u2560\u255054c591db-16c9-4c9e-9d01-444558af9c6e\n# \u255f\u25006e319277-a897-49aa-9e78-7a905a11dc89\n# \u255f\u25003ed289cd-6ace-442f-a9b4-7fe109af5e49\n# \u2560\u2550acda705d-1e1a-4b5f-ba15-0c7d3bdbd5d4\n# \u255f\u25007ccb1dea-7a69-47f4-964b-fc7799c58b8a\n# \u2560\u25508f73a313-e31d-4087-beb9-1f5c43f44ea1\n# \u2560\u2550e9cdb8d0-3daa-4ada-9344-45099f184a64\n# \u2560\u255086076221-f0eb-4434-b15e-abcc7fc54384\n# \u2560\u2550998e600b-6933-48a9-bcf4-f7c1f981411e\n# \u2560\u2550bf89a580-d02c-4c14-af67-f249071b4d5e\n# \u255f\u2500d1edf66f-856b-463a-af27-775507ee70f2\n# \u255f\u2500d22ec8ae-e5de-4b8d-85ac-17c7844f667b\n# \u255f\u25008eae3bb0-4fa5-4e0f-8336-d28b199ef229\n# \u255f\u2500ae8373e9-347d-4d2c-b988-6170ec2040a2\n# \u2560\u2550cdefc0aa-aefa-4c62-b8a9-692331c9bf50\n# \u255f\u2500ba871ee3-125d-402c-aef0-fe7046bf2bde\n# \u2560\u2550ed0a598c-84a5-4062-bb7a-1d00added226\n# \u2560\u25501455bae3-7b50-4f0f-b521-b5aa5b9ba926\n# \u255f\u250054f33702-08e9-439f-9d28-c783d7c27547\n# \u255f\u250003116ef9-39b9-459e-95cc-c367dedd7896\n# \u255f\u25006e66626d-7660-45d6-88c5-497ffce7c81e\n# \u255f\u2500166c0bb7-e75b-4e32-b3f3-0568e9e3d2b3\n# \u255f\u2500e5bc63bc-751e-4faa-81ce-db37343baf19\n# \u255f\u25009d56672c-f3a0-4705-8e04-6bd2776d46b5\n# \u2560\u2550b0ba2f26-291f-4204-942f-2b87cd5ba8a8\n# \u255f\u25005c1b3bac-98d2-4d5b-b8ef-85ca8e2a4f80\n# \u2560\u25506d322108-fa1b-41ad-81d6-5f36b6ef2fb1\n# \u255f\u25006ee5e9b2-2d38-4a92-9e71-660f06bbc7a5\n# \u2560\u255039b108b3-b41e-44c4-9565-d199c5831746\n# \u2560\u255000484f64-99c0-43b0-97aa-2c2d3ed98318\n# \u255f\u25002eff73ca-34ba-4a86-bc98-8543003fa46f\n# \u255f\u2500e6bbe0a2-3f9c-431a-894d-32279bef9e73\n# \u255f\u250073a77da6-7ec7-4460-9542-bb994676a375\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "module MovcolNTests\n\nusing MovcolN\nusing FactCheck\n\n# write your own tests here\n\nfacts(\"Generating Q\") do\n    kmax  = 4; nder = 3;\n    Ql,Qr,x = MovcolN.generateQats(nder,1//2,kmax=kmax)\n\n    @fact x => 1//2\n\n    @fact size(Ql) => (kmax,nder)\n\n    @fact Ql => [[1//2,5//32,1//64] [-15//8,-7//16,-1//32] [0//1,-3//2,-1//4] [30//1,15//1,3//2]]'\n\n    @fact Qr => [[1//2,-5//32,1//64] [15//8,-7//16,1//32] [0//1,3//2,-1//4] [-30//1,15//1,-3//2]]'\n\n\nend\n\nfacts(\"Computing derivatives\") do\n    kmax    = 4; nder = 3;\n    Ql,Qr,_ = MovcolN.generateQats(nder,0.5,kmax=kmax)\n\n    ul = hcat(Float64[ 0, 0, 2   ])\n    ur = hcat(Float64[ 4, 4, 2   ])\n    utl= hcat(Float64[ 0, 0, 2   ])\n    utr= hcat(Float64[12, 8, 2   ])\n    uc = hcat(Float64[ 1, 2, 2, 0])\n    utc=      Float64[ 1, 2, 2   ]\n    h  = 2.; ht = 2.\n    H  = [h^j for j = 0:kmax]\n    Ht = [j*ht*h^(j-1) for j = 0:kmax]\n\n    uc1 = Array(Float64,kmax,1)\n    utc1 = Array(Float64,kmax,1)\n\n    MovcolN.computeux!(uc1,(Ql,Qr,0.5),H,ul,ur)\n    MovcolN.computeutx!(utc1,(Ql,Qr,0.5),H,Ht,0.,utl,utr,uc,ul,ur)\n\n    @fact uc1  => uc\n    @fact utc1[1:3] => utc\nend\n\nfacts(\"Generating AB matrix\") do\n    relerr = Array(Float64,0)\n    abserr = Array(Float64,0)\n\n    # for Float64 this method converges for up to 8 collocatin points\n    nconv = 8\n    for n = 2:nconv\n        AB  =MovcolN.generateAB(n)\n        sl,_=MovcolN.lobatto(n+1)\n        sg,_=MovcolN.gauss(n)\n\n        @fact size(AB) => (n,n+1)\n\n        push!(abserr,norm((AB*sin(sl)-cos(sg)),         Inf))\n        push!(relerr,norm((AB*sin(sl)-cos(sg))./sin(sg),Inf))\n    end\n\n    relconv = exp(diff(log(relerr)))\n    absconv = exp(diff(log(abserr)))\n\n    @fact relconv.<0.2 => all  # relative error is at most ~O(0.2^n)\n    @fact absconv.<0.1 => all  # absolute error is at most ~O(0.1^n)\nend\n\nend\n", "meta": {"hexsha": "ea0346a3ed2a0b8df3b347451fcc7402bb847da3", "size": 1796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "pwl/MovcolN.jl", "max_stars_repo_head_hexsha": "06449ebd8fc531ea4c088033226d0b853100a6c4", "max_stars_repo_licenses": ["MIT"], "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": "pwl/MovcolN.jl", "max_issues_repo_head_hexsha": "06449ebd8fc531ea4c088033226d0b853100a6c4", "max_issues_repo_licenses": ["MIT"], "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": "pwl/MovcolN.jl", "max_forks_repo_head_hexsha": "06449ebd8fc531ea4c088033226d0b853100a6c4", "max_forks_repo_licenses": ["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.9444444444, "max_line_length": 98, "alphanum_fraction": 0.5445434298, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8705972801594707, "lm_q1q2_score": 0.7954442880439861}}
{"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 \u5f53\u671f\u4ef7\u683c\r\n    K::Float64 #strike price \u884c\u6743\u4ef7\r\n    T::Float64 #maturity time \u5230\u671f\u65f6\u95f4\r\n    t::Float64 #valuation date \u6709\u6548\u65e5\u671f\r\n    r::Float64 #risk_less rate \u65e0\u98ce\u9669\u6536\u76ca\u7387\r\n    \u03c3::Float64 #volatility \u6ce2\u52a8\u7387\r\n    type::String #option type(call,put) \u770b\u6da8\u3001\u770b\u8dcc\r\n    # EuropeanOtion(St,K,T,t,r,\u03c3,type)=new(St,K,T,t,r,\u03c3,type)\r\nend\r\n\r\n\r\n#\u6b63\u6001\u5206\u5e03\uff0c\u6570\u503c\u7d2f\u8ba1\u79ef\u5206\u7b97\u6cd5\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 * \u03c0) * 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\u516c\u5f0f\u5b9a\u4ef7\r\n#dN(x)\u6807\u51c6\u6b63\u592a\u51fd\u6570\u663e\u793a\u8868\u8fbe\uff08\u5373\u9ad8\u65af\u51fd\u6570\uff09\r\n#CDF_dn(x)\u9ad8\u65af\u51fd\u6570\u79ef\u5206\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.\u03c3^2/2)*o.T)/(o.\u03c3*\u221ao.T)\r\n    d2=d1-o.\u03c3*\u221ao.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)*\u221ao.T\r\n        \u03b4=CDF_dn(d1)\r\n        \u03b3=dN(d1)/(o.St*o.\u03c3*\u221ao.T)\r\n        \u03c1=o.K*o.T*exp(-o.r*o.T)*CDF_dn(d2)\r\n        \u03b8=-(o.St*dN(d1)*o.\u03c3/(2*\u221ao.T)+o.r*o.K*exp(-o.r*o.T)*CDF_dn(d2))\r\n        return [option_value,vega,\u03b4,\u03b3,\u03c1,\u03b8]\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#\u683c\u5f0f\u5316\u51fd\u6570\u4e3a\uff0cfind_zero\u63d0\u4f9b\u6807\u51c6\u8f93\u5165\r\nfunction formatfun(o::EuropeanOption,x)\r\n    o.\u03c3=x\r\n    z=BSM_value(option)[1]\r\nend\r\n\r\n\r\n#\u9690\u542b\u6ce2\u52a8\u7387\u8ba1\u7b97\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 \u2208 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\u03c0, 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u201cview\u201d 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# \u2554\u2550\u2561 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 \u03c0/2; -\u03c0/2 \u03c0/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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 247b2cf8-8ed3-11eb-19ee-fd0f17cec519\n#= md\"\"\"\n##### Solution:\n\n```julia\nfunction H(;N,h)\n\tid = [1 0; 0 1]\n\t\u03c3\u02e3 = [0 1; 1 0]\n    \u03c3\u1dbb = [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, \u03c3\u1dbb will be at position k and k+1\n\t\tmat(k) = k == i || k == (i + 1) ? \u03c3\u1dbb : 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, \u03c3\u1d9c will be at position k\n\t\tmat(k) = k == i ? \u03c3\u02e3 : 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 \u03c3\u02e3 (equal super-position of eigenstates)\n```\n\"\"\" =#\n\n# \u2554\u2550\u2561 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 \u2218 abs \u2218 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# \u2554\u2550\u2561 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 `\u2218` for _unary_ functions\n- a reverse pipe `<|`\n\nNote: infix operators such as `\u2218` need to be wrapped around `()` in method definitions for parsing reasons.\n\"\"\"\n\n# \u2554\u2550\u2561 44b9eb9c-8980-11eb-17b8-1937532d3a28\nmd\"\"\"\n##### Solution:\n```julia\n(\u2218)(f::Function, g::Function) = (x...) -> f(g(x...))\n\n(<|)(f::Function, args...) = f(args...)\n```\n\"\"\"\n\n# \u2554\u2550\u2561 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\u00d7N\u00d7...` (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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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^\u2020``\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# \u2554\u2550\u2561 45c45594-8ca4-11eb-1db9-6187459bf306\n#= md\"\"\"\n##### Solution:\n\n```julia\nusing LinearAlgebra\n\nconst id = [1 0; 0 1]\nconst \u03c3\u1dbb = [1 0; 0 -1]\n\n# Wilson chain Hamiltonian\nfunction H(N, \u03b1)\n\tT(i) = -\u03b1^(-i) * mapreduce(j -> j == i || j == i + 1 ? \u03c3\u1dbb : 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, \u03b1)\n\t# truncates half of the highest eigenvalues\n\t\u03bb\u0303, U\u0303 = let\n\t\t\u03bb, U = eigen(H)\n\t\tN\u2082 = length(\u03bb) \u00f7 2\n\t\t\u03bb[1:N\u2082], U[1:N\u2082, 1:N\u2082]\n\tend\n\n\t\u03c3\u1dbb\u2099 = let\n\t\tn = ceil(Int, log2(length(\u03bb\u0303))) # number of sites in H\u0303\n\t\tmapreduce(i -> i == n ? \u03c3\u1dbb : id, kron, 1:n)\n\tend\n\t\n\t# Rotate \u03c3\u1dbb \u2192 \u03c3\u0303\u1dbb\u2099 and add chain\n\treturn kron(diagm(\u03bb\u0303), id) - \u03b1^(-(n+1)) * kron(\u0168 * \u03c3\u1dbb\u2099 * \u0168', \u03c3\u1dbb)\nend\n\n# Numerical renormalization group\nrg(;N,\u03b1,steps=0) = foldl((h, i) -> add_chain(h, N+i, \u03b1), 1:steps; init=H(N, \u03b1))\n```\n\"\"\" =#\n\n# \u2554\u2550\u2561 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 \u26b0\ufe0f\u26b0\ufe0f\u26b0\ufe0f\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 \ud83e\udea6\ud83e\udea6\ud83e\udea6\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u03bcs (2 allocations: 78.20 KiB)\n@btime fcomprehension($x);\n# > 7.890 \u03bcs (2 allocations: 78.20 KiB)\n@btime fdot($x);\n# > 8.238 \u03bcs (2 allocations: 78.20 KiB)\n@btime floop($x);\n# > 9.495 \u03bcs (2 allocations: 78.20 KiB)\n```\n\"\"\" =#\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u03bcs | 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 \u03bcs (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 \u03bcs (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# \u2554\u2550\u2561 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` \u2013> `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 `\u2248` (`\\approx`) operator, since the `==` may be too strict given the shenanigans we encountered with float arithmetics.\n\"\"\"\n\n# \u2554\u2550\u2561 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() \u2248 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) \u2248 sin(x)*sin(x)-cos(x)*cos(x)\n\t@test -cos(2*x) \u2248 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() \u2248 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() \u2248 work3(B, v, N)\n@test work() \u2248 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() \u2248 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() \u2248 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() \u2248 work7(B, v)\n\n@btime work7($B, $v, $N)\n# 2.019 ms (3 allocations: 7.64 MiB)\n```\n\"\"\" =#\n\n# \u2554\u2550\u2561 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\u1d62) in enumerate(a)\n\tprintln(\"The $i-th entry of a is $a\u1d62)\nend\n```\n\"\"\"\n\n# \u2554\u2550\u2561 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 \u2218 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\u1d62)\n\t\tx\u1d62\u208a\u2081 = f(x\u1d62)\n\t\tif x\u1d62\u208a\u2081 == x\u1d62\n\t\t\treturn x\u1d62\n\t\telse\n\t\t\treturn fix(x\u1d62\u208a\u2081)\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\u1d62) = (x\u1d62\u208a\u2081 = f(x\u1d62)) \u2248 x\u1d62 ? x\u1d62 : fix(x\u1d62\u208a\u2081)\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\u1d62=10^4) = fix(x\u1d62, i=1) = (x\u1d62\u208a\u2081 = f(x\u1d62)) \u2248 x\u1d62 || i == max\u1d62 ? x\u1d62 : fix(x\u1d62\u208a\u2081, 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\u208a] ; kondo_rg([jz, j\u208a])] for j\u208a in 0.0:dj:1.0 for jz in -dj-j\u208a:-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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250059afc220-9195-11eb-2384-29ae6f4aa263\n# \u255f\u2500e5c840d8-8978-11eb-37fa-77fb05a3d821\n# \u255f\u25008636e926-8b38-11eb-3f98-f58135f3d02e\n# \u255f\u2500540516aa-8b38-11eb-26f8-d31b72022689\n# \u255f\u250053f03512-8b38-11eb-031b-55d81ef5aeac\n# \u255f\u2500533f5a58-8b38-11eb-1c75-61000cf8394f\n# \u255f\u2500e6cc166a-8ed2-11eb-23be-2d657eb00795\n# \u255f\u2500247b2cf8-8ed3-11eb-19ee-fd0f17cec519\n# \u255f\u25009ba8170a-7b50-11eb-0aac-adc493e1f386\n# \u255f\u2500c9862c2a-897e-11eb-3592-ada39cc0637b\n# \u255f\u250044b9eb9c-8980-11eb-17b8-1937532d3a28\n# \u255f\u2500af38a46c-8981-11eb-26de-35f9e487423c\n# \u255f\u2500afc5f13c-8ee2-11eb-2dfe-0dcbc74c120e\n# \u255f\u2500bded83c2-8ee2-11eb-3b00-a7681ba476dc\n# \u255f\u25000d6a34a4-8ee3-11eb-08ae-2763ca230fd5\n# \u255f\u250059e7aaf0-8cac-11eb-0ea8-3fb87d36ad90\n# \u255f\u250045c45594-8ca4-11eb-1db9-6187459bf306\n# \u255f\u25004bee5324-8eeb-11eb-326b-efba53215f34\n# \u255f\u250028f63950-8eef-11eb-0481-55fad44619d5\n# \u255f\u25008ac22e72-8978-11eb-1674-e1b95403e215\n# \u255f\u25008d9f2162-8f07-11eb-1c1d-b994b88811e1\n# \u255f\u2500bff46124-8f08-11eb-1140-d78145e2fe05\n# \u255f\u2500fdfddce2-919d-11eb-1b48-5d31c8d4b250\n# \u255f\u25008a97bcb8-91a3-11eb-37b4-4f9004e01e0b\n# \u255f\u25000ae35bf0-91a6-11eb-1a75-235aaf78d346\n# \u255f\u2500700b1240-9197-11eb-0cfd-1bb3d7393084\n# \u255f\u2500a3346d6a-919a-11eb-13e9-59293be49654\n# \u255f\u2500fd81c0c0-91fd-11eb-1ddb-1546f52626af\n# \u255f\u25004eb2573e-8998-11eb-2274-379a03bed49c\n# \u255f\u2500b58a861c-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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b9c02010-5e9b-11eb-1e5d-9358c778cbba\n# set seed for random # generator\nseed!(1234)\n\n# \u2554\u2550\u2561 b9a85250-5e9b-11eb-1787-6b671b235984\nbegin\n\tnobs = 1_000\n\t\u03b2 = [1.0, -2.0, 1.0, 0.5]\n\tk = length(\u03b2)\n\tX = randn(nobs, k);\n\n\t# choice utilities\n\tu0 = zeros(nobs)\n\tu1 = X*\u03b2\n\tu = hcat(u0, u1)\nend\n\n# \u2554\u2550\u2561 b976e210-5e9b-11eb-0b18-e95537e1d64f\n# multinomial logit probabilities\nprob_actions = mapslices(softmax, u; dims=2)\n\n# \u2554\u2550\u2561 dc8270d0-5e9b-11eb-02cb-1faa58ce2656\ncum_prob = cumsum(prob_actions; dims=2)\n\n# \u2554\u2550\u2561 dc82bef0-5e9b-11eb-20f5-0d1ed55e9bb5\n# will throw an error if we goof\n@assert all(cum_prob[:,2] .\u2248 1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 694cc4c0-5e9c-11eb-3d00-458ca8c8fa28\ncountmap(y)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 90b963b0-5e9c-11eb-0dea-81d683f42601\n# wrapper to allocate gradient vector\ndloglik(y, X, theta) = dloglik!(similar(theta), y, X, theta)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ba5f02b0-5e9c-11eb-30cc-fbb3e2d4b6e2\n# initial guess\ntheta0 = zeros(k)\n\n# \u2554\u2550\u2561 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 \u2248 dloglik(y,X,theta0)\n\tfdgrad .- dloglik(y,X,theta0)\nend\n\n# \u2554\u2550\u2561 ba614ca0-5e9c-11eb-3619-0507168a18d6\nres = optimize(f, g!, theta0, BFGS(), Optim.Options(;show_trace=true))\n\n# \u2554\u2550\u2561 61327d20-5e9c-11eb-3704-bf5055d67bb0\nbegin\n\ttheta1 = res.minimizer  # should be about \u03b2\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 = \u03b2, betahat = theta1, tstat=tstats, se = stderr, pval=pvals)\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u25500ece0030-5e9d-11eb-0092-254fc6e72e83\n# \u2560\u2550b7910ac0-5ffe-11eb-3925-13fbd88d3f67\n# \u2560\u2550e2248c2e-5ffe-11eb-189c-85dbf7703168\n# \u2560\u25501508d920-6000-11eb-34bf-81e7d3ceb9bc\n# \u2560\u25508595f030-5e9b-11eb-3bd7-ef8250cd1fab\n# \u2560\u2550b9c02010-5e9b-11eb-1e5d-9358c778cbba\n# \u2560\u2550b9a85250-5e9b-11eb-1787-6b671b235984\n# \u2560\u2550b976e210-5e9b-11eb-0b18-e95537e1d64f\n# \u2560\u2550dc8270d0-5e9b-11eb-02cb-1faa58ce2656\n# \u2560\u2550dc82bef0-5e9b-11eb-20f5-0d1ed55e9bb5\n# \u2560\u2550dc87c800-5e9b-11eb-194c-4f7f0e83a5c5\n# \u2560\u2550694cc4c0-5e9c-11eb-3d00-458ca8c8fa28\n# \u2560\u255090b963b0-5e9c-11eb-3e39-bdf160b8655e\n# \u2560\u255090b963b0-5e9c-11eb-1d75-25729dfb57ee\n# \u2560\u255090b963b0-5e9c-11eb-0dea-81d683f42601\n# \u2560\u255090c65c02-5e9c-11eb-032a-7d600b60b9c4\n# \u2560\u2550640b3fa2-5e9c-11eb-19d3-97ebb410851a\n# \u2560\u2550ba5f02b0-5e9c-11eb-30cc-fbb3e2d4b6e2\n# \u2560\u2550ba5f02b0-5e9c-11eb-2221-4b0d5e525673\n# \u2560\u2550ba614ca0-5e9c-11eb-3619-0507168a18d6\n# \u2560\u255061327d20-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": "# PS7 Dayuan Xie\r\n\r\n# using Pkg\r\n# Pkg.add(\"SMM\")\r\n\r\nusing SMM\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 CSV\r\n\r\n# Question 1\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 gmm(beta, X, y)\r\n    g = y .-X*beta\r\n    J = g'*I*g\r\n    return J\r\nend\r\noptim_gmm = optimize(beta ->gmm(beta, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-8, iterations=100_000))\r\nprintln(optim_gmm.minimizer)\r\n\r\nbeta_ols = inv(X'*X)*X'*y\r\nprintln(beta_ols)\r\n\r\n# Question 2a\r\nfreqtable(df, :occupation) \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)\r\n\r\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\ny = df.occupation\r\n\r\nfunction logit_ml(alpha, X, y)    \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    num = zeros(N,J)\r\n    dem = zeros(N)\r\n        for j=1:J\r\n            num[:,j] = exp.(X*bigAlpha[:,j])\r\n            dem .+= num[:,j]\r\n        end\r\n        \r\n    P = num./repeat(dem,1,J)\r\n        \r\n    loglike = -sum( bigY.*log.(P) )\r\n        \r\n    return loglike\r\nend\r\n\r\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]\r\nalpha_start = alpha_true.*rand(size(alpha_true))\r\nprintln(size(alpha_true))\r\nalpha_hat_optim = optimize(a -> logit_ml(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\noptim_ml = alpha_hat_optim.minimizer\r\nprintln(optim_ml)\r\n\r\n# Question 2b\r\nfunction logit_gmm(alpha, X, y)\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    num = zeros(N,J)\r\n    dem = zeros(N)\r\n        for j=1:J\r\n            num[:,j] = exp.(X*bigAlpha[:,j])\r\n            dem .+= num[:,j]\r\n        end\r\n        \r\n    P = num./repeat(dem,1,J)\r\n    g = bigY .- P\r\n    gmm = sum(g'*I*g)\r\n    return gmm\r\nend\r\noptim_logit_gmm_b = optimize(a -> logit_gmm(a, X, y), optim_ml, LBFGS(), Optim.Options(g_tol=1e-8, iterations=100_000))\r\nprintln(optim_logit_gmm_b.minimizer)\r\n\r\n# Question 2c\r\noptim_logit_gmm_c = optimize(a -> logit_gmm(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol=1e-8, iterations=100_000))\r\nprintln(optim_logit_gmm_c.minimizer)\r\n\r\n# We get different estimates from part (b) and (c). The objective function is not globally concave.\r\n\r\n# Question 3\r\nfunction simulate()\r\nK = 2\r\nN = 10000\r\nJ = 3\r\nX=rand(N,J)\r\n\u03b2=[1 2;3 4]\r\nnum = zeros(N,J)\r\ndem = zeros(N)\r\n    for j=1:J\r\n        num[:,j] = exp.(X*\u03b2[:,j])\r\n        dem .+= num[:,j]\r\n    end\r\n    \r\nP = num./repeat(dem,1,J)\r\n\u03b5 = randn(N,1)\r\nY=zeros(N,1)\r\n   for i= 1: N\r\n    Y[i,1]=sum(sum(P[i,:])>\u03b5[i,1]) + sum((P[i,2]+P[i,3])>\u03b5[i,1]) + sum(P[i,3]>\u03b5[i,1])\r\n   end\r\nend\r\nsimulate()\r\n\r\n# Question 4\r\nMA = SMM.parallelNormal()\r\ndc = SMM.history(MA.chains[1])\r\ndc = dc[dc[:accepted].==true, :]\r\nprintln(describe(dc))\r\n\r\n# Question 5\r\nfunction mlogit_smm(\u03b8, X, y, D)\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    \u03b2 = \u03b8[1:end-1]\r\n    \u03c3 = \u03b8[end]\r\n    if length(\u03b2)==1\r\n        \u03b2 = \u03b2[1]\r\n    end  \r\n    num = zeros(N,J)\r\n    dem = zeros(N)\r\n        for j=1:J\r\n            num[:,j] = exp.(X*bigAlpha[:,j])\r\n            dem .+= num[:,j]\r\n        end\r\n        \r\n    P = num./repeat(dem,1,J)\r\n\r\n    gmodel = zeros(N+1,J,D)\r\n    gdata  = vcat(bigY,var(bigY))\r\n\r\n    Random.seed!(1234)  \r\n    for d=1:D\r\n        \u03b5 = \u03c3*randn(N,J)\r\n        y\u0303 = P .+ \u03b5\r\n        gmodel[1:end-1,1:J,d] = y\u0303\r\n        gmodel[  end  ,1:J,d] = var(y\u0303)\r\n    end\r\n\r\n    err = vec(gdata .- mean(gmodel; dims=2))\r\n\r\n    J = err'*I*err\r\n    return J\r\nend\r\n", "meta": {"hexsha": "80bf351ea4f0cb0d2af34b3ee77b59b9ea3e32cd", "size": 4569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS7-smm/PS7_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/PS7-smm/PS7_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/PS7-smm/PS7_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": 25.2430939227, "max_line_length": 243, "alphanum_fraction": 0.5583278617, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7953866654139602}}
{"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    \u0394 = b^2 - 4*a*c\n\n    \u0394.hi < 0 && return\n\n    \u0394 = sqrt(\u0394)\n\n    if (b.lo >= 0)\n        x0 = -0.5 * (b + \u0394)\n\n    else\n        x0 = -0.5 * (b - \u0394)\n    end\n\n    if (0 \u2208 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\u00b2`, `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 \u2212\u221e and another extends to +\u221e.\nThis algorithm finds the set of points where `F.lo(x) \u2265 0` and the set\nof points where `F.hi(x) \u2264 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 \u2264 0))\n        push!(L, Interval(-\u221e))\n    end\n\n    if (a.lo < 0 || (a.lo == 0 && b.lo == 0) || (a.lo == 0 && b.lo == 0 && c.lo \u2264 0))\n        push!(L, Interval(\u221e))\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": "# Test of Min-Cut and maximum adjacency visit\n\nusing Graphs\nusing Base.Test\n\ng = simple_inclist(8, is_directed=false)\n\n# Original example by Stoer\n\nwedges = [\n    (1, 2, 2.),\n    (1, 5, 3.),\n    (2, 3, 3.),\n    (2, 5, 2.),\n    (2, 6, 2.),\n    (3, 4, 4.),\n    (3, 7, 2.),\n    (4, 7, 2.),\n    (4, 8, 2.),\n    (5, 6, 3.),\n    (6, 7, 1.),\n    (7, 8, 3.) ]\n\n\nm = length(wedges)\neweights = zeros(m)\n\nfor i = 1 : m\n    we = wedges[i]\n    add_edge!(g, we[1], we[2])\n    eweights[i] = we[3]\nend\n\n\n\n@assert num_vertices(g) == 8\n@assert num_edges(g) == m\n\nparity, bestcut = min_cut(g, eweights)\n\n@test length(parity) == 8\n@test parity == Bool[ true, true, false, false, true, true, false, false ]\n@test bestcut == 4.0\n\nparity, bestcut = min_cut(g)\n\n@test length(parity) == 8\n@test parity == Bool[ true, false, false, false, false, false, false, false ]\n@test bestcut == 2.0\n\nvertices = maximum_adjacency_visit(g)\n\n@test vertices == Int64[1, 2, 5, 6, 3, 7, 4, 8]\n", "meta": {"hexsha": "76e89f9ada71c8b1900c40180e8597aaad6d7695", "size": 951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/maximum_adjacency_visit.jl", "max_stars_repo_name": "JuliaPackageMirrors/Graphs.jl", "max_stars_repo_head_hexsha": "f3462013e14ef3c482abebc26095304934dd25fc", "max_stars_repo_licenses": ["MIT"], "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/maximum_adjacency_visit.jl", "max_issues_repo_name": "JuliaPackageMirrors/Graphs.jl", "max_issues_repo_head_hexsha": "f3462013e14ef3c482abebc26095304934dd25fc", "max_issues_repo_licenses": ["MIT"], "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/maximum_adjacency_visit.jl", "max_forks_repo_name": "JuliaPackageMirrors/Graphs.jl", "max_forks_repo_head_hexsha": "f3462013e14ef3c482abebc26095304934dd25fc", "max_forks_repo_licenses": ["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.6111111111, "max_line_length": 77, "alphanum_fraction": 0.5625657203, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7953866513440321}}
{"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\u00e9 Fern\u00e1ndez-N\u00fan\u0303ez,\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    \u03d1\u2081(t, q) = + log(q[2]) / q[1] / 2\n    \u03d1\u2082(t, q) = - log(q[1]) / q[2] / 2\n\n    d\u03d1\u2081dx\u2081(t, q) = - log(q[2]) / q[1]^2 / 2\n    d\u03d1\u2081dx\u2082(t, q) = + 1 / (q[1] * q[2]) / 2\n\n    d\u03d1\u2082dx\u2081(t, q) = - 1 / (q[2] * q[1]) / 2\n    d\u03d1\u2082dx\u2082(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    \u03b1 = 0.3\n    \u03b4 = 0.1\n    \u03b2 = 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]^\u03b1 + (1-\u03b4)*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) .+ \u03b2*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 \u03b1 = M\u2082/(M\u2081+M\u2082) where the Lagrange points will be found\r\n\u03b1vals = 0.001:0.001:0.5\r\n# The number of values of \u03b1\r\nn\u03b1vals = length(\u03b1vals)\r\n# Will store the positions of the Lagrange points\r\nlagrangepoints = zeros(Float64, n\u03b1vals, 10);\r\n\r\nfor i \u2208 1:n\u03b1vals\r\n    # Set the value of \u03b1 = M\u2082/(M\u2081+M\u2082)\r\n\t\u03b1 = \u03b1vals[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 - \u03b1)*(x + \u03b1)/\u221a((x + \u03b1)^2 + y^2)^3 -\r\n\t\t\t\u03b1*(x + \u03b1 - 1)/\u221a((x + \u03b1 - 1)^2 + y^2)^3\r\n\t\tF[2] = y -\r\n\t\t\t(1 - \u03b1)*y/\u221a((x + \u03b1)^2 + y^2)^3 -\r\n\t\t\t\u03b1*y/\u221a((x + \u03b1 - 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 \u03b1 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(\u03b1vals, [lagrangepoints[:,1 ], \u03b1 -> 1 - \u221b(\u03b1/3)]),\r\n        plot(\u03b1vals, [lagrangepoints[:,2 ], \u03b1 -> 0]),\r\n        plot(\u03b1vals, [lagrangepoints[:,3 ], \u03b1 -> 1 + \u221b(\u03b1/3)]),\r\n        plot(\u03b1vals, [lagrangepoints[:,4 ], \u03b1 -> 0]),\r\n        plot(\u03b1vals, [lagrangepoints[:,5 ], \u03b1 -> - 1 - 5\u03b1/12]),\r\n        plot(\u03b1vals, [lagrangepoints[:,6 ], \u03b1 -> 0]),\r\n        plot(\u03b1vals, [lagrangepoints[:,7 ], \u03b1 -> 1/2 - \u03b1]),\r\n        plot(\u03b1vals, [lagrangepoints[:,8 ], \u03b1 -> (\u221a3)/2]),\r\n        plot(\u03b1vals, [lagrangepoints[:,9 ], \u03b1 -> 1/2 - \u03b1]),\r\n        plot(\u03b1vals, [lagrangepoints[:,10], \u03b1 -> -(\u221a3)/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\u2081 x\" \"L\u2081 y\" \"L\u2082 x\" \"L\u2082 y\" \"L\u2083 x\" \"L\u2083 y\" \"L\u2084 x\" \"L\u2084 y\" \"L\u2085 x\" \"L\u2085 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\u2081, M\u2082, r\u2081, r\u2082, \u03a9 = p\r\n\r\n    # The four forces (including fictitious) acting on m\r\n    gravitational\u2081 = - ( G * M\u2081 / hypot((r - r\u2081)...)^3 ) .* (r - r\u2081)\r\n    gravitational\u2082 = - ( G * M\u2082 / hypot((r - r\u2082)...)^3 ) .* (r - r\u2082)\r\n    coriolis = - 2\u03a9 .* [[0, -1] [1, 0]] * v\r\n    centrifugal = (\u03a9^2) .* r\r\n    return gravitational\u2081 + gravitational\u2082 + 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\u2080 and v\u2080, and parameters \u03b1 and M\u2081\r\nfunction simulate(\u03b1, G, r\u2080, v\u2080, T)\r\n    # M\u2082 is the mass of the other large stationary body\r\n    M\u2082 = M\u2081 * \u03b1/(1-\u03b1)\r\n\r\n    # r\u2081 and r\u2082 are the positions of M\u2081 and M\u2082\r\n    r\u2081 = [-\u03b1, 0]\r\n    r\u2082 = [1-\u03b1, 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    # \u03a9 is the magnitude of the angular velocity of the rotating frame of reference\r\n    \u03a9 = \u221a(G * (M\u2081 + M\u2082))\r\n\r\n    # DifferentialEquations simulates the mass for time T\r\n    return solve(ODEProblem(derivative!, vcat(r\u2080, v\u2080), (0.0, float(T)), [G, M\u2081, M\u2082, r\u2081, r\u2082, \u03a9]))\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\u2099 up to time T, with parameters \u03b1 and M\u2081\r\nfunction trajectory(\u03b1, M\u2081, n, T, lims = [2,1])\r\n\ti = findfirst(\u2265(\u03b1), \u03b1vals)\r\n    simulatedtrajectory = simulate(\u03b1vals[i], M\u2081, 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]), (-\u03b1,0), (1-\u03b1, 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(\u03b8, \u03c6)\n\nReturn the 3D direction given polar angle `\u03b8` and\nazimuthal angle `\u03c6` in degrees according to the ISO\nconvention.\n\"\"\"\nfunction spheredir(theta, phi)\n  \u03b8, \u03c6 = deg2rad(theta), deg2rad(phi)\n  Vec(sin(\u03b8)*cos(\u03c6), sin(\u03b8)*sin(\u03c6), cos(\u03b8))\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(\u03bd)\n\nThe *Chi squared distribution* (typically written \u03c7\u00b2) with `\u03bd` 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 `\u03bd` is an integer, then it is the distribution of the sum of squares of `\u03bd` 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    \u03bd::Float64\n\n    Chisq(\u03bd::Real) = (@check_args(Chisq, \u03bd > zero(\u03bd)); new(\u03bd))\nend\n\n@distr_support Chisq 0.0 Inf\n\n#### Parameters\n\ndof(d::Chisq) = d.\u03bd\nparams(d::Chisq) = (d.\u03bd,)\n\n\n#### Statistics\n\nmean(d::Chisq) = d.\u03bd\n\nvar(d::Chisq) = 2.0 * d.\u03bd\n\nskewness(d::Chisq) = sqrt(8.0 / d.\u03bd)\n\nkurtosis(d::Chisq) = 12.0 / d.\u03bd\n\nmode(d::Chisq) = d.\u03bd > 2.0 ? d.\u03bd - 2.0 : 0.0\n\nfunction median(d::Chisq; approx::Bool=false)\n    if approx\n        return d.\u03bd * (1.0 - 2.0 / (9.0 * d.\u03bd))^3\n    else\n        return quantile(d, 0.5)\n    end\nend\n\nfunction entropy(d::Chisq)\n    h\u03bd = 0.5 * d.\u03bd\n    h\u03bd + logtwo + lgamma(h\u03bd) + (1.0 - h\u03bd) * digamma(h\u03bd)\nend\n\n\n#### Evaluation\n\n@_delegate_statsfuns Chisq chisq \u03bd\n\nmgf(d::Chisq, t::Real) = (1.0 - 2.0 * t)^(-d.\u03bd * 0.5)\n\ncf(d::Chisq, t::Real) = (1.0 - 2.0 * im * t)^(-d.\u03bd * 0.5)\n\ngradlogpdf(d::Chisq, x::Float64) =  x > 0.0 ? (d.\u03bd * 0.5 - 1) / x - 0.5 : 0.0\n\n\n#### Sampling\n\n_chisq_rand(\u03bd::Float64) = StatsFuns.Rmath.chisqrand(\u03bd)\nrand(d::Chisq) = _chisq_rand(d.\u03bd)\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\u00d73 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  \u22ee\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) \u00f7 3\n        midB = high - (high - low) \u00f7 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\u0394 = p - m\\,.\n```\n```\n       +--------+\np(t) --|  diff  |-- \u0394(t)\nm(t) --|        |\n       +--------+\n```\n=#\n@parameters p(t) m(t)\n@variables \u0394(t)\ndiff = IOBlock([\u0394 ~ p - m], [p, m], [\u0394], 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.\u0394 => 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.\u0394`). 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.\u0394 => 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 \ud83e\udd37\u200d\u2642\ufe0f\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.\u0394 => 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 \u03a3(t) altitude(t)\nint = IOBlock([D(o) ~ 1/T * i - o], [i], [o], name=:int)\nadder = IOBlock([\u03a3 ~ a1 + a2], [a1, a2], [\u03a3], name=:add)\n\npi_c = IOSystem([diff.\u0394 => 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.\u03a3 => 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)(\u03b8)\n    y = problem.y\n    X = problem.X\n\n    \u03b2 = \u03b8.\u03b2\n    \u03c3 = \u03b8.\u03c3\n\n    \u03b7 = X * \u03b2\n    \u03bc = \u03b7\n    \u03b5 = y - \u03bc\n\n    ## these two lines are equivalent:\n    ## log_likelihood = Distributions.loglikelihood(Distributions.Normal(0, \u03c3), \u03b5)\n    ## log_likelihood = sum(Distributions.logpdf.(Distributions.Normal(0, \u03c3), \u03b5))\n\n    log_likelihood = sum(Distributions.logpdf.(Distributions.Normal(0, \u03c3), \u03b5))\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_\u03b2 = (3,)\n\u03b2_true = [1.0, 2.0, -1.0]\n\u03c3_true = 0.5\n\u03b7_true = X * \u03b2_true\n\u03bc_true = \u03b7_true\n\u03b5_true = randn(N) .* \u03c3_true\ny = \u03bc_true + \u03b5_true\n\nfunction generate_problem_transformation(p::LinearRegression)\n    return TransformVariables.as((\u03b2 = TransformVariables.as(Array, size(p.X, 2)),\n                                  \u03c3 = TransformVariables.as\u211d\u208a))\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\u03b2_hat_initial_guess = zeros(size_\u03b2)\n\u03c3_hat_initial_guess = 1.0\n\n\u03b8_hat_initial = (; \u03b2 = \u03b2_hat_initial_guess,\n                   \u03c3 = \u03c3_hat_initial_guess)\n\n# \u03b8_hat:\n\n\u03b8_hat = MaximumLikelihoodProblems.fit(transformed_gradient_problem,\n                                      \u03b8_hat_initial;\n                                      learning_rate = 1e-6)\n\n# \u03b2_hat:\n\n\u03b2_hat = \u03b8_hat[:\u03b2]\n\n# \u03c3_hat:\n\n\u03c3_hat = \u03b8_hat[:\u03c3]\n\n# Value of the log likelihood function evaluated at \u03b8_hat:\n\nMaximumLikelihoodProblems.loglikelihood(transformed_gradient_problem, \u03b8_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": "function part1()\n\n    line1, line2 = readlines(\"input13.txt\")\n    timestamp = parse(Int, line1)\n    bus_ids = parse.(Int, filter( x-> !occursin(\"x\",x), split(line2,\",\")))\n    \n    flag = true\n    wait = 0\n    \n    while flag\n        for bus_id in bus_ids\n            if (timestamp+wait) % bus_id == 0\n                return wait * bus_id\n            end\n        end\n        wait += 1\n    end\n       \nend\n\nfunction check( timestamp, departs ) \n\n   for (bus_id,t) in departs\n      if (timestamp+t) % bus_id !== 0\n         return false\n      end\n   end\n   return true\nend\n\n# Three days to find the solution\n# This page helps me https://www.geeksforgeeks.org/chinese-remainder-theorem-set-1-introduction/\n\nfunction part2(departs)\n\n    bus_ids = split(departs,\",\")\n    \n    departs = Tuple{Int,Int}[]\n    for (minute,bus_id) in enumerate(bus_ids)\n        if !occursin( \"x\", bus_id) \n            push!(departs, (parse(Int,bus_id),minute-1))\n        end\n    end\n\n    timestamp = 1\n    increment = timestamp\n\n    for (bus, offset) in departs\n        while (timestamp + offset) % bus != 0\n            timestamp += increment\n        end\n        increment = lcm(increment, bus)\n    end\n\n    return timestamp\n\nend\n\n\nprintln(part1())\n@assert part2(\"17,x,13,19\") == 3417\n@assert part2(\"67,7,59,61\") == 754018\n@assert part2(\"67,x,7,59,61\") == 779210\n@assert part2(\"7,13,x,x,59,x,31,19\") == 1068781\n@assert part2(\"67,7,x,59,61\") == 1261476\n@time @assert part2(1, \"1789,37,47,1889\") == 1202161486\n_, departs = readlines(\"input13.txt\")\n@time println(part2(departs))\n", "meta": {"hexsha": "12e6aa1f9b1b69548a230555d28960aeeb1ee342", "size": 1548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day13.jl", "max_stars_repo_name": "pnavaro/AdventOfCode", "max_stars_repo_head_hexsha": "1045423c08b5398beab094249a8a373f6b42dea6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day13.jl", "max_issues_repo_name": "pnavaro/AdventOfCode", "max_issues_repo_head_hexsha": "1045423c08b5398beab094249a8a373f6b42dea6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day13.jl", "max_forks_repo_name": "pnavaro/AdventOfCode", "max_forks_repo_head_hexsha": "1045423c08b5398beab094249a8a373f6b42dea6", "max_forks_repo_licenses": ["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.4347826087, "max_line_length": 96, "alphanum_fraction": 0.5897932817, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7952389952534721}}
{"text": "\r\nusing LinearAlgebra, Plots, Statistics, TaylorSeries, Printf\r\n# if !(pwd() in LOAD_PATH) push!(LOAD_PATH, pwd()) end\r\n# using TaylorBigF\r\n\r\npath1=realpath(dirname(@__FILE__)*\"/..\")\r\ninclude(string(path1,\"/src/TaylorBigF.jl\"))\r\n\r\n# 3.4 Numerical Integration\r\np=50;setprecision(p); setrounding(BigFloat, RoundUp);\r\nL=BigFloat(\"1\"); n=BigInt(201); iN=convert(Int64,n); dx=BigFloat(\"2\")*L/(n-1); x=-L:dx:L;\r\nI=zeros(BigFloat, n, n);for i=1:n I[i,i]=BigFloat(\"1\") end\r\nV=TaylorBigF.calc_Vandermonde(x,n,n)\r\n\r\nf=sin.(x); a=V\\f;\r\n\r\nL_n=zeros(BigFloat,n)\r\nfor i=1:n\r\n    L_n[i]=(L^i)/i\r\n    if iseven(i) L_n[i]=-L_n[i] end\r\nend\r\nc=a'*L_n\r\n\r\nVintegral=TaylorBigF.calc_Vandermonde_int(x,n,n)\r\nF_all_x=Vintegral*a.+c\r\n\r\nF_comp=F_all_x[end]\r\n@sprintf(\"F_comp=%1.3e\",F_comp)\r\n", "meta": {"hexsha": "32739acbad362bc5954bca50d9ed0f971da6a9cd", "size": 765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/__3_num_integration.jl", "max_stars_repo_name": "nbakas/TaylorBigF.jl", "max_stars_repo_head_hexsha": "3196052b43ec73d40db91539fd11abd30473b84c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-05T21:13:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-05T21:13:55.000Z", "max_issues_repo_path": "test/__3_num_integration.jl", "max_issues_repo_name": "nbakas/TaylorBigF.jl", "max_issues_repo_head_hexsha": "3196052b43ec73d40db91539fd11abd30473b84c", "max_issues_repo_licenses": ["MIT"], "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/__3_num_integration.jl", "max_forks_repo_name": "nbakas/TaylorBigF.jl", "max_forks_repo_head_hexsha": "3196052b43ec73d40db91539fd11abd30473b84c", "max_forks_repo_licenses": ["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": 90, "alphanum_fraction": 0.6679738562, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7952335145042332}}
{"text": "module SquareLatticeModel\n##export ParamDict, getNeighbors, genPoly\n\nmutable struct ParamDict\n    nrows::Int\n    ncols::Int\n    N::Int\nend\n\nfunction genFunctor(d)\n    d = d\n    \n    function roundN(n, N)\n        m = (n - 1 + N) % N\n        m + 1\n    end\n\n    function getXY(k, d=d)\n        x = roundN(k, d.ncols)\n        y = roundN(div(k-1, d.ncols)+1, d.nrows)\n        (x, y)\n    end\n\n    function getK( x, y, d=d)\n        # must round each x, y\n        xn = (x - 1 + d.ncols) % d.ncols + 1\n        yn = (y - 1 + d.nrows) % d.nrows + 1\n        #\n        k = (yn - 1) * d.ncols + xn\n    end\n\n    function getNeighbors( k, d=d)\n        (x, y) = getXY(k,d)\n        [getK(x-1, y, d), getK(x, y-1, d), getK(x+1, y, d), getK(x, y+1, d)]\n    end\n\n    # polygon for each cell\n    function genPoly(k, d)\n        (x, y) = getXY(k, d)\n        w = 0.5\n        h = 0.5\n        (x .+ [-w,  w, w, -w, -w],\n         y .+ [-h, -h, h,  h, -h])\n    end\n\n    return (getNeighbors, genPoly)\nend # of functor\n\nend # of module", "meta": {"hexsha": "fc6690189847384821293d018ae291975518e462", "size": 1004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src.02a/SquareLatticeModel02a.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.02a/SquareLatticeModel02a.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.02a/SquareLatticeModel02a.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": 20.4897959184, "max_line_length": 76, "alphanum_fraction": 0.46812749, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7952335137714412}}
{"text": "@testset \"Moving max-min functions\" begin\n\n    len = 1000\n    Random.seed!(0)\n    T = Float64\n    vec = rand(T, len)\n    window = 15\n\n    mx_ref = similar(vec)\n    mn_ref = similar(vec)\n\n    for i = 1:len\n        mx_ref[i] = maximum(vec[max(1, i-window+1) : i])\n        mn_ref[i] = minimum(vec[max(1, i-window+1) : i])\n    end\n    range_ref = mx_ref .- mn_ref\n\n\n    @testset \"movmaxmin\" begin\n        mx, mn = movmaxmin(vec, window)\n        @test mx == mx_ref\n        @test mn == mn_ref\n        fill!(mx, 0)\n        fill!(mn, 0)\n        movmaxmin!(mx, mn, vec, window)\n        @test mx == mx_ref\n        @test mn == mn_ref\n    end\n\n    @testset \"movrange\" begin\n        range = movrange(vec, window)\n        @test range == range_ref\n        fill!(range, 0)\n        movrange!(range, vec, window)\n        @test range == range_ref\n        fill!(range, 0)\n    end\n\n    @testset \"movmax\" begin\n        mx = movmax(vec, window)\n        @test mx == mx_ref\n        fill!(mx, 0)\n        movmax!(mx, vec, window)\n        @test mx == mx_ref\n    end\n\n    @testset \"movmin\" begin\n        mn = movmin(vec, window)\n        @test mn == mn_ref\n        fill!(mn, 0)\n        movmin!(mn, vec, window)\n        @test mn == mn_ref\n    end\n\nend\n# @test_throws BoundsError first(buf)\n", "meta": {"hexsha": "e0bea18d7cf6c2855dd89f8030fce40a0ea9c56d", "size": 1259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_movmaxmin.jl", "max_stars_repo_name": "sairus7/MaxMinFilters.jl", "max_stars_repo_head_hexsha": "337614a9b08c657b1441f83978953cce1fe3c2a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-10-22T17:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T10:58:41.000Z", "max_issues_repo_path": "test/test_movmaxmin.jl", "max_issues_repo_name": "jakubwro/MaxMinFilters.jl", "max_issues_repo_head_hexsha": "ad1cf371d854e6ff401bb6e259ddf4c375af752b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-29T16:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T23:53:35.000Z", "max_forks_repo_path": "test/test_movmaxmin.jl", "max_forks_repo_name": "jakubwro/MaxMinFilters.jl", "max_forks_repo_head_hexsha": "ad1cf371d854e6ff401bb6e259ddf4c375af752b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-31T23:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-06T08:59:06.000Z", "avg_line_length": 22.0877192982, "max_line_length": 56, "alphanum_fraction": 0.5242255759, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7951583317887211}}
{"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.\u03bc, copy!(m_tmp.\u03a3, measurement.\u03a3)\n    m_p, P_p = x_pred.\u03bc, x_pred.\u03a3\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.\u03bc .= m_p .+ K * (0 .- z)\n    x_out.\u03bc .= m_p .- _matmul!(x_out.\u03bc, 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.\u03a3, 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# \u2554\u2550\u2561 10b19f7a-1f8b-11eb-128e-11743ce72ef5\nusing PlutoUI, Plots\n\n# \u2554\u2550\u2561 e5a688ac-1f91-11eb-104a-2753c9263f14\nmd\"\"\"\n # Floating Point Arithmetic\n\"\"\"\n\n# \u2554\u2550\u2561 2df31082-1f8b-11eb-145a-93fa6e01e345\n@bind f Slider(1:100)\n\n# \u2554\u2550\u2561 37c0afe8-1f8b-11eb-1154-31f5954ca4ff\nf\n\n# \u2554\u2550\u2561 8d2203e8-1f8a-11eb-0332-7d512d831ec1\nbitstring(f)\n\n# \u2554\u2550\u2561 4aa7bc3c-1f8b-11eb-30dd-89d64f42fc27\nlength(bitstring(f))\n\n# \u2554\u2550\u2561 c90f7b06-1f8a-11eb-17d7-35a09af858f1\nfloat(f)\n\n# \u2554\u2550\u2561 d4cd33f2-1f8a-11eb-1af7-bdbc1fb236da\nbitstring(float(f))\n\n# \u2554\u2550\u2561 4f354440-1f8b-11eb-225a-f55552bc9e29\nlength(bitstring(float(f)))\n\n# \u2554\u2550\u2561 b7eb6210-1f9e-11eb-2a57-95b4fab4187f\nmd\"\"\"\nIEEE 64 bit representation (double precision) (64 bits0\n\"\"\"\n\n# \u2554\u2550\u2561 2ee2a8ec-1f8e-11eb-23e6-9d5e2bb00d1e\nieee0(x::Float64) = [bitstring(x)[1:1], bitstring(x)[2:12], bitstring(x)[13:64]] \n\n# \u2554\u2550\u2561 d6b5d1f6-1f9e-11eb-0c32-9b9cb51352a0\nmd\"\"\"\n## Let me work with numbers from 1 to 2\n\"\"\"\n\n# \u2554\u2550\u2561 e0cd119a-1f9e-11eb-1181-3d3fa6e0653f\n nextfloat(1.0)-1.0\n\n# \u2554\u2550\u2561 f3357c5a-1f9e-11eb-270d-d3b5fd6bd542\n2.0 ^(-52)\n\n# \u2554\u2550\u2561 fbe68df8-1f9e-11eb-1278-a102df99c88c\n\n\n# \u2554\u2550\u2561 0bf5f86a-1f8f-11eb-17fd-75f4b45f16d5\n@bind j Slider(1: 2^(52), show_value = true)\n\n# \u2554\u2550\u2561 2ff48c68-1f8f-11eb-0bd0-cde93f2cc18b\ng = 1 + j/2^52\n\n# \u2554\u2550\u2561 316b7dd0-1f8e-11eb-0da9-9fc5b63a4e80\nieee0(g)\n\n\n# \u2554\u2550\u2561 56e8258a-1f8f-11eb-3249-6592feed84b3\nieee0(1.0)\n\n# \u2554\u2550\u2561 5d7dcbe0-1f8f-11eb-05e9-1b2ae35cf681\nieee0(-1.0)\n\n# \u2554\u2550\u2561 bf3bd13c-1f95-11eb-3187-a7311125be18\nnextfloat(1.0)-1\n\n# \u2554\u2550\u2561 d3a6bbaa-1f95-11eb-27de-e99b0e230d21\neps(1.0)\n\n# \u2554\u2550\u2561 c6d813ba-1f95-11eb-1be6-55cb3ffeb358\nnextfloat(1.0f0)-1\n\n# \u2554\u2550\u2561 d66f2a16-1f95-11eb-3edc-4182c1a4b8ad\neps(1.0f0)\n\n# \u2554\u2550\u2561 d31baed4-1f95-11eb-19df-15ff5c378487\neps(1.0f0) * 2^23\n\n# \u2554\u2550\u2561 81a7921c-1f8f-11eb-33c6-397d38b57a75\nieee(x) = [ parse.(Int,ieee0(x),base=2)      ieee0(x)]\n\n# \u2554\u2550\u2561 85c8f822-1f8f-11eb-15a1-7956d269779a\nieee(g)\n\n# \u2554\u2550\u2561 dd3031d8-1f9f-11eb-39b2-cb7ac57c6bdf\nieee(1.0)\n\n# \u2554\u2550\u2561 e4b2733a-1f9f-11eb-30ac-0dc5305b8938\nieee(-1.0)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3f36e4a8-1fa0-11eb-1c46-97ff95905b41\nieee(prevfloat(1.0))\n\n# \u2554\u2550\u2561 f8612fa6-1f91-11eb-36d6-cbd0f9b5b0ea\nfloat2ieee(x::Float64) =  parse.(Int,ieee0(x),base=2)\n\n# \u2554\u2550\u2561 66f85a94-1fa0-11eb-32bd-178184d8aef9\n2^52-1\n\n# \u2554\u2550\u2561 0a44c782-1f92-11eb-1b67-eb93f1dfe1ff\nfloat2ieee(1.0)\n\n# \u2554\u2550\u2561 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\u2208x\n\t   \n\t\n\t\t\n\t\tz = (1+1/16):(1/16):(2-1/16)\n\t\tfor zz\u2208 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# \u2554\u2550\u2561 c51ad4de-1fa1-11eb-3e01-fb46ed72f493\n(1 + 1.000001*eps(1.0)/2)-1\n\n# \u2554\u2550\u2561 79e5e5ca-1fa0-11eb-087f-9fad526c1b0e\nieee(0.0) ## does not follow the same rule\n\n# \u2554\u2550\u2561 8fd89a82-1fa0-11eb-2921-0d3c31c93cbc\nieee(-0.0) ## is this the same as 0.0?\n\n# \u2554\u2550\u2561 a207d416-1fa0-11eb-3bf0-bdc40925736e\n1.0 / 0.0\n\n# \u2554\u2550\u2561 c7473096-1fa0-11eb-39fd-31c4c4b1eb04\nieee(Inf)\n\n# \u2554\u2550\u2561 d08a02dc-1fa0-11eb-3369-a7c84dad581a\nieee(1.0/-0.0)\n\n# \u2554\u2550\u2561 f072cf66-1fa0-11eb-0789-733f904d41d0\n0.0 / 0.0\n\n# \u2554\u2550\u2561 ff8975cc-1fa0-11eb-1fa6-514db7898e52\nmd\"\"\"\n# Not a Number\n\"\"\"\n\n# \u2554\u2550\u2561 0b340f86-1fa1-11eb-37bd-839bd7525dc9\nNaN == NaN\n\n# \u2554\u2550\u2561 0d1c1902-1f96-11eb-0734-1bb3dda2aa7d\nmd\"\"\"\nWhy do we need this floating point representation?\n\"\"\"\n\n# \u2554\u2550\u2561 a40c4352-1f94-11eb-263e-632828cb6079\nfloat2ieee(0.0)\n\n# \u2554\u2550\u2561 b7b6a198-1f94-11eb-0093-8f3ab007d770\nfloat2ieee(-0.0)\n\n# \u2554\u2550\u2561 bb04eb2c-1f94-11eb-0a4a-3d2765531e94\nfloat2ieee(Inf)\n\n# \u2554\u2550\u2561 c0e4f8f2-1f94-11eb-1305-d9028395ab2f\nfloat2ieee(-Inf)\n\n# \u2554\u2550\u2561 c500ec66-1f94-11eb-079a-1b5b4befade2\n1/-0.0\n\n# \u2554\u2550\u2561 1e37c20a-1f95-11eb-37f9-11c5a6041e1b\nInf - Inf\n\n# \u2554\u2550\u2561 25be9fbc-1f95-11eb-294a-1dd62a135bfa\n0.0/0.0\n\n# \u2554\u2550\u2561 7345c08e-1f96-11eb-0bf1-c50d0108facd\nmd\"\"\"\n$$\\begin{matrix}   \\text{exponent\\\\mantissa} & 0 & \u22600  \\\\ \\hline 0 & \u00b10  &  \\text{denormal} \\\\ \n\\text{regular} &  2^k & \\text{general} \\\\ \\text{max} &  \\pm\\infty &  \\text{NaN} \\end{matrix}$$\n\"\"\"\n\n# \u2554\u2550\u2561 b22dc266-1f9a-11eb-199b-170ef50b702c\nmd\"\"\"\nRules of IEEE arithmetic\n\"\"\"\n\n# \u2554\u2550\u2561 3f2943c6-1f95-11eb-0342-6569169f32ca\nFloat32(1.0)\n\n# \u2554\u2550\u2561 47153ebe-1f95-11eb-2224-716d2e152db0\nbitstring(Float32(1.0))\n\n# \u2554\u2550\u2561 60135b2e-1f95-11eb-293d-4f8a96a677b2\nfloat32ieee0(x::Float32) = [bitstring(x)[1:1], bitstring(x)[2:9], bitstring(x)[10:32]]\n\n# \u2554\u2550\u2561 77de76f8-1f95-11eb-00bc-915dd7977c75\nfloat32ieee0(1.0f0)\n\n# \u2554\u2550\u2561 65ef756c-1f96-11eb-2546-35b37cb7f54c\n## The rules of +, -, / , * and \u221a\n\n# \u2554\u2550\u2561 f707de2e-1fa1-11eb-0147-3fca8c03ab5f\n\n\n# \u2554\u2550\u2561 2b0265d4-1f96-11eb-1553-ef2ecb7d451b\nmd\"\"\"\nWhat precision do you need? \n - Small absolute precision?\n - Small relative precision?\n - Neither?\n\"\"\"\n\n# \u2554\u2550\u2561 c5f5c97c-1f97-11eb-3683-55c16be8274e\nmd\"\"\"\nWhat is displayed? What can you represent?\n\"\"\"\n\n# \u2554\u2550\u2561 b86c366c-1f95-11eb-0a18-a52cdf00da4c\n1/5\n\n# \u2554\u2550\u2561 d400e394-1f97-11eb-0f74-476c32bdd9d0\nbitstring(1/5)\n\n# \u2554\u2550\u2561 f5e3b162-1f97-11eb-2879-f7c7954143a0\nbig(1/5)\n\n# \u2554\u2550\u2561 000c656c-1f98-11eb-0f0e-657b9651f0bd\nbig(1)/5\n\n# \u2554\u2550\u2561 149b4c9e-1f98-11eb-19b7-eb9988c9333a\nBigFloat(1//5,precision=1000)\n\n# \u2554\u2550\u2561 3aae6bac-1f98-11eb-22a5-bdc5e5de3f4c\nBigFloat(\u03c0,precision=1000)\n\n# \u2554\u2550\u2561 43bed31c-1f98-11eb-1131-f5dd8dd27086\nBigFloat(float(pi),precision=1000)\n\n# \u2554\u2550\u2561 56fb9c94-1f98-11eb-216e-f9e6e04d6f45\nmd\"\"\"\nNote that every IEEE number terminates (is not a repeating expansion)\n\"\"\"\n\n# \u2554\u2550\u2561 32cf8afa-1f99-11eb-0193-e969cca12f86\nmd\"\"\"\nFind the first floating point number bigger than 1 such that x * (1/x) \u2260 1\n\"\"\"\n\n# \u2554\u2550\u2561 51baa858-1f99-11eb-3329-4d9bf850b1c0\nbegin\n\tt = 1+rand()\n\tt,ieee(t*1/t)\nend\n\n# \u2554\u2550\u2561 64c9235e-1f99-11eb-24f3-d940be06c7c8\nlet\n\t \u03b1 = 1.0\n     while( \u03b1 * (1/\u03b1) == 1.0)\n\t\t\u03b1 = nextfloat(\u03b1)\n\t end\n\t Int((\u03b1-1)/eps(1.0))\nend\n\n# \u2554\u2550\u2561 ecc5c55a-1f99-11eb-3f44-4161850426cc\n\u03b1= 1 + 257736490*eps()\n\n# \u2554\u2550\u2561 40575ec2-1f9a-11eb-2d29-5b517d1f3b18\n\u03b1*(1/\u03b1)\n\n# \u2554\u2550\u2561 0b0719c2-1f9c-11eb-3ed6-6927c927145d\n\n\n# \u2554\u2550\u2561 11ebb920-1f9c-11eb-061a-8df3899e8945\n\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500e5a688ac-1f91-11eb-104a-2753c9263f14\n# \u2560\u25502df31082-1f8b-11eb-145a-93fa6e01e345\n# \u2560\u255037c0afe8-1f8b-11eb-1154-31f5954ca4ff\n# \u2560\u25508d2203e8-1f8a-11eb-0332-7d512d831ec1\n# \u2560\u25504aa7bc3c-1f8b-11eb-30dd-89d64f42fc27\n# \u2560\u2550c90f7b06-1f8a-11eb-17d7-35a09af858f1\n# \u2560\u2550d4cd33f2-1f8a-11eb-1af7-bdbc1fb236da\n# \u2560\u25504f354440-1f8b-11eb-225a-f55552bc9e29\n# \u255f\u2500b7eb6210-1f9e-11eb-2a57-95b4fab4187f\n# \u2560\u25502ee2a8ec-1f8e-11eb-23e6-9d5e2bb00d1e\n# \u255f\u2500d6b5d1f6-1f9e-11eb-0c32-9b9cb51352a0\n# \u2560\u2550e0cd119a-1f9e-11eb-1181-3d3fa6e0653f\n# \u2560\u2550f3357c5a-1f9e-11eb-270d-d3b5fd6bd542\n# \u2560\u2550fbe68df8-1f9e-11eb-1278-a102df99c88c\n# \u2560\u25500bf5f86a-1f8f-11eb-17fd-75f4b45f16d5\n# \u2560\u25502ff48c68-1f8f-11eb-0bd0-cde93f2cc18b\n# \u2560\u2550316b7dd0-1f8e-11eb-0da9-9fc5b63a4e80\n# \u2560\u255056e8258a-1f8f-11eb-3249-6592feed84b3\n# \u2560\u25505d7dcbe0-1f8f-11eb-05e9-1b2ae35cf681\n# \u2560\u2550bf3bd13c-1f95-11eb-3187-a7311125be18\n# \u2560\u2550d3a6bbaa-1f95-11eb-27de-e99b0e230d21\n# \u2560\u2550c6d813ba-1f95-11eb-1be6-55cb3ffeb358\n# \u2560\u2550d66f2a16-1f95-11eb-3edc-4182c1a4b8ad\n# \u2560\u2550d31baed4-1f95-11eb-19df-15ff5c378487\n# \u2560\u255081a7921c-1f8f-11eb-33c6-397d38b57a75\n# \u2560\u255085c8f822-1f8f-11eb-15a1-7956d269779a\n# \u2560\u2550dd3031d8-1f9f-11eb-39b2-cb7ac57c6bdf\n# \u2560\u2550e4b2733a-1f9f-11eb-30ac-0dc5305b8938\n# \u2560\u2550ff15233a-1f9f-11eb-0012-f198e05abaf9\n# \u2560\u25503f36e4a8-1fa0-11eb-1c46-97ff95905b41\n# \u2560\u2550f8612fa6-1f91-11eb-36d6-cbd0f9b5b0ea\n# \u2560\u255066f85a94-1fa0-11eb-32bd-178184d8aef9\n# \u2560\u25500a44c782-1f92-11eb-1b67-eb93f1dfe1ff\n# \u2560\u255037039e06-1f92-11eb-192e-e59ffb46a368\n# \u2560\u2550c51ad4de-1fa1-11eb-3e01-fb46ed72f493\n# \u2560\u255079e5e5ca-1fa0-11eb-087f-9fad526c1b0e\n# \u2560\u25508fd89a82-1fa0-11eb-2921-0d3c31c93cbc\n# \u2560\u2550a207d416-1fa0-11eb-3bf0-bdc40925736e\n# \u2560\u2550c7473096-1fa0-11eb-39fd-31c4c4b1eb04\n# \u2560\u2550d08a02dc-1fa0-11eb-3369-a7c84dad581a\n# \u2560\u2550f072cf66-1fa0-11eb-0789-733f904d41d0\n# \u255f\u2500ff8975cc-1fa0-11eb-1fa6-514db7898e52\n# \u2560\u25500b340f86-1fa1-11eb-37bd-839bd7525dc9\n# \u255f\u25000d1c1902-1f96-11eb-0734-1bb3dda2aa7d\n# \u2560\u2550a40c4352-1f94-11eb-263e-632828cb6079\n# \u2560\u2550b7b6a198-1f94-11eb-0093-8f3ab007d770\n# \u2560\u2550bb04eb2c-1f94-11eb-0a4a-3d2765531e94\n# \u2560\u2550c0e4f8f2-1f94-11eb-1305-d9028395ab2f\n# \u2560\u2550c500ec66-1f94-11eb-079a-1b5b4befade2\n# \u2560\u25501e37c20a-1f95-11eb-37f9-11c5a6041e1b\n# \u2560\u255025be9fbc-1f95-11eb-294a-1dd62a135bfa\n# \u2560\u25507345c08e-1f96-11eb-0bf1-c50d0108facd\n# \u255f\u2500b22dc266-1f9a-11eb-199b-170ef50b702c\n# \u2560\u25503f2943c6-1f95-11eb-0342-6569169f32ca\n# \u2560\u255047153ebe-1f95-11eb-2224-716d2e152db0\n# \u2560\u255060135b2e-1f95-11eb-293d-4f8a96a677b2\n# \u2560\u255077de76f8-1f95-11eb-00bc-915dd7977c75\n# \u2560\u255065ef756c-1f96-11eb-2546-35b37cb7f54c\n# \u2560\u2550f707de2e-1fa1-11eb-0147-3fca8c03ab5f\n# \u2560\u25502b0265d4-1f96-11eb-1553-ef2ecb7d451b\n# \u255f\u2500c5f5c97c-1f97-11eb-3683-55c16be8274e\n# \u2560\u2550b86c366c-1f95-11eb-0a18-a52cdf00da4c\n# \u2560\u2550d400e394-1f97-11eb-0f74-476c32bdd9d0\n# \u2560\u2550f5e3b162-1f97-11eb-2879-f7c7954143a0\n# \u2560\u2550000c656c-1f98-11eb-0f0e-657b9651f0bd\n# \u2560\u2550149b4c9e-1f98-11eb-19b7-eb9988c9333a\n# \u2560\u25503aae6bac-1f98-11eb-22a5-bdc5e5de3f4c\n# \u2560\u255043bed31c-1f98-11eb-1131-f5dd8dd27086\n# \u255f\u250056fb9c94-1f98-11eb-216e-f9e6e04d6f45\n# \u255f\u250032cf8afa-1f99-11eb-0193-e969cca12f86\n# \u2560\u255051baa858-1f99-11eb-3329-4d9bf850b1c0\n# \u2560\u255064c9235e-1f99-11eb-24f3-d940be06c7c8\n# \u2560\u2550ecc5c55a-1f99-11eb-3f44-4161850426cc\n# \u2560\u255040575ec2-1f9a-11eb-2d29-5b517d1f3b18\n# \u2560\u25500b0719c2-1f9c-11eb-3ed6-6927c927145d\n# \u2560\u255011ebb920-1f9c-11eb-061a-8df3899e8945\n# \u2560\u255010b19f7a-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": "@testset \"Test Circle\" begin\n    M = Circle()\n    x = S1Point(0.)\n    y = opposite(M,x)\n    z = randomMPoint(M)\n    \u03b7 = randomTVector(M,x)\n    @test getValue(x) == 0.\n    \u03be = S1TVector(2*\u03c0/3)\n    @test getValue(\u03be) == 2*\u03c0/3\n    @test distance(M, x, exp(M,x,\u03be)) \u2248 2*\u03c0/3\n    @test dot(M,x,\u03be, S1TVector(0.5)) \u2248 \u03c0/3\n    @test embed(M,x) == SnPoint([1., 0.])\n    @test exp(M,x,\u03be) == S1Point(2*\u03c0/3)\n    @test distance(M, exp(M,x,2*\u03be), S1Point(-2*\u03c0/3) ) \u2248 0 atol=10^(-15)\n    @test log(M,x,exp(M,x,\u03be)) == \u03be\n    @test manifoldDimension(x) == 1\n    @test manifoldDimension(M) == 1\n    @test norm(M,x,\u03be) \u2248 2*\u03c0/3\n    @test distance(M, opposite(M,S1Point(\u03c0/2)), S1Point(-\u03c0/2) ) \u2248 0 atol=10^(-15)\n    @test parallelTransport(M,x,S1Point(\u03c0/2),\u03be) == \u03be\n    @test validateMPoint(M,randomMPoint(M))\n    @test validateTVector(M,x,randomTVector(M,x))\n    @test typeofTVector(typeof(x)) == S1TVector\n    @test typeofMPoint(typeof(\u03be)) == S1Point\n    @test typeofTVector(x) == S1TVector\n    @test typeofMPoint(\u03be) == S1Point\n    @test typicalDistance(M) == \u03c0/2\n    @test zeroTVector(M,x) == S1TVector(0.)\n    @test \"$M\" == \"The manifold S1 consisting of angles\"\n    @test \"$x\" == \"S1(0.0)\"\n    @test \"$(S1TVector(0.))\" == \"S1T(0.0)\"\n    @test_throws ErrorException validateMPoint(M,S1Point(2*\u03c0))\n    @test_throws ErrorException validateMPoint(M,S1Point(-2*\u03c0))\n\n    # Test manifoldDimension\n    @test manifoldDimension(M) == 1\n    @test manifoldDimension(x) == 1\n    # Test norm\n    @test norm(M,x,\u03be) == 2*\u03c0/3\n    # Test opposite\n    @test getValue(y) - pi \u2248 0 atol = 10.0^(-16)\n    # Test parallelTransport\n    @test getValue(parallelTransport(M,x,y,\u03be)) - getValue(\u03be) \u2248 0 atol = 10.0^(-16)\n    # Test typicalDistance\n    @test typicalDistance(M) == pi/2\n    # Test validateMPoint and validateTVector\n    xnot = S1Point(3.15)\n    @test_throws ErrorException validateMPoint(M,xnot)\nend\n", "meta": {"hexsha": "a6deb5d89b8541d799b237823941a65a594ac6b6", "size": 1859, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/manifolds/testS1.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": "test/manifolds/testS1.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": "test/manifolds/testS1.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": 37.18, "max_line_length": 82, "alphanum_fraction": 0.6116191501, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7951125881853209}}
{"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\u030c = paduatransform(f.(x , y))\nf\u0303 = (x,y) -> begin\n    j = 1\n    ret = 0.0\n    for n in 0:N, k in 0:n\n        ret += f\u030c[j]*cos((n-k)*acos(x)) * cos(k*acos(y))\n        j += 1\n    end\n    ret\nend\n\nf\u0303(0.1,0.2) \u2248 f(0.1,0.2)\n\nipaduatransform(f\u030c) \u2248 f\u0303.(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": "using SymFEL\nusing Test\nusing SymPy\nusing LinearAlgebra\n\n\n# Testing Lagrange elements\nprintln(\"# Testing Lagrange elements\")\np1 = SymFEL.get_lagrange_basis()\n@test SymPy.degree(p1[1], gen=x) == 1\n@test SymPy.degree(p1[2], gen=x) == 1\n@test SymPy.subs(p1[1], x, 0) == 1\n@test SymPy.subs(p1[1], x, h) == 0\n@test SymPy.subs(p1[2], x, h) == 1\n@test SymPy.subs(p1[2], x, 0) == 0\n\np4 = SymFEL.get_lagrange_basis(4)\nE = Matrix(1I, 5, 5)\nfor i = 1:4\n    @test SymPy.degree(p4[i], gen=x) == 4\n    for j = 1:5\n        @test SymPy.subs(p4[i], x, (j - 1) * h / 4) == E[i, j]\n    end\nend\n\nM = SymFEL.get_lagrange_em()\n@test (M[1, 1] == h / 3) && ((M[1, 2] == h / 6)) &&\n    (M[2, 1] == h / 6) && ((M[2, 2] == h / 3))\n\nMVC = SymFEL.get_lagrange_em_varcoeff()\nMVC = MVC.subs([(xa, 0), (xb, h)])\n@test (MVC[1, 1] == h / 3) && (MVC[1, 2] == h / 6) &&\n    (MVC[2, 1] == h / 6) && (MVC[2, 2] == h / 3)\n\n# Testing Hermite elements\nprintln(\"# Testing Hermite elements\")\np3 = SymFEL.get_hermite_basis()\n@test SymPy.subs(p3[1], x, 0) == 1\n@test SymPy.subs(p3[1], x, h) == 0\n@test SymPy.subs(SymPy.diff(p3[1], x), x, 0) == 0\n@test SymPy.subs(SymPy.diff(p3[1], x), x, h) == 0\n\n@test SymPy.subs(p3[2], x, 0) == 0\n@test SymPy.subs(p3[2], x, h) == 0\n@test SymPy.subs(SymPy.diff(p3[2], x), x, 0) == 1\n@test SymPy.subs(SymPy.diff(p3[2], x), x, h) == 0\n\n@test SymPy.subs(p3[3], x, 0) == 0\n@test SymPy.subs(p3[3], x, h) == 1\n@test SymPy.subs(SymPy.diff(p3[3], x), x, 0) == 0\n@test SymPy.subs(SymPy.diff(p3[3], x), x, h) == 0\n\n@test SymPy.subs(p3[4], x, 0) == 0\n@test SymPy.subs(p3[4], x, h) == 0\n@test SymPy.subs(SymPy.diff(p3[4], x), x, 0) == 0\n@test SymPy.subs(SymPy.diff(p3[4], x), x, h) == 1\n\nMH = SymFEL.get_hermite_em()\nMH_hc = [13*h/35 11*h^2/210 9*h/70 -13*h^2/420;\n         11*h^2/210 h^3/105 13*h^2/420 -h^3/140;\n         9*h/70 13*h^2/420 13*h/35 -11*h^2/210;\n         -13*h^2/420 -h^3/140 -11*h^2/210 h^3/105]\n@test MH == MH_hc\n\nMHVC = SymFEL.get_hermite_em_varcoeff()\nMHVC = MHVC.subs([(xa, 0), (xb, h)])\n@test MHVC == MH_hc\n\ntry\n    SymFEL.get_hermite_basis(2)\ncatch y\n    println(y)\nend\n\n##\nt = range(0, stop=1,length=11)\nt = convert(Array{Float64}, t)\nti = range(0, stop=1, length=101)\nxv = sin.(pi * t')\nyv = pi * cos.(pi * t')\nfdf = [xv; yv]\nf = SymFEL.interpolate(fdf, t, ti)\n@test norm(f[1:10:101]' - xv) <= 1e-15\n\n## Testing get_em() function.\nprintln(\"Testing get_em() function.\")\n@test SymFEL.get_em(1, 1, 0, 0) == SymFEL.get_lagrange_em(1, 0, 0)\n@test SymFEL.get_em(3, 3, 1, 0; fe1 = \"Hermite\", fe2 = \"Hermite\") == SymFEL.get_hermite_em(3, 1, 0)\ntry\n    SymFEL.get_em(1, 1, 0, 0; fe1 = \"a\", fe2 = \"Lagrange\")\ncatch er\n    println(er)\nend\n\ntry\n    SymFEL.get_em(1, 1, 2, 0)\ncatch er\n    println(er)\nend\n\ntry\n    SymFEL.get_em(1, 1, 1, 2)\ncatch er\n    println(er)\nend\n\ntry\n    SymFEL.get_em(3, 3, 3, 0; fe1 = \"Hermite\", fe2=\"Hermite\")\ncatch er\n    println(er)\nend\n\ntry\n    SymFEL.get_em(3, 3, 2, -1; fe1 = \"Hermite\", fe2=\"Hermite\")\ncatch er\n    println(er)\nend\n\n##\nn = 1001\nxv = range(0, stop=1, length=2*n-1).^2\ndx = 1 / (n - 1)\n\nelem_M = SymFEL.get_lagrange_em(2, 0, 0)\nelem_M = elem_M.subs(h, dx)\nelem_M = convert(Matrix{Float64}, elem_M)\nM = SymFEL.assemble_1d_FE_matrix(elem_M, n, intNodes1 = 1, intNodes2 = 1, dof1 = 1, dof2 = 1)\n@test abs(convert(Float64, (xv' * M * xv)[1]) - 1 / 5) < 1e-15\n\nelem_M_p1 = SymFEL.get_lagrange_em(1, 0, 0)\nelem_M_p1 = elem_M_p1.subs(h, dx)\nelem_M_p1 = convert(Matrix{Float64}, elem_M_p1)\nM_p1 = SymFEL.assemble_1d_FE_matrix(elem_M_p1, n)\nxv = range(0, stop=1, length=n).^2\n@test abs(convert(Float64, (xv' * M_p1 * xv)[1]) - 1 / 5) < 1e-6\n\nelem_M_h3 = SymFEL.get_hermite_em(3, 0, 0)\nelem_M_h3 = elem_M_h3.subs(h, dx)\nelem_M_h3 = convert(Matrix{Float64}, elem_M_h3)\nM_h3 = SymFEL.assemble_1d_FE_matrix(elem_M_h3, n, intNodes1 = 0, intNodes2 = 0, dof1 = 2, dof2 = 2)\nxv = zeros(2 * n, 1)\nxv[1:2:(2*(n-1)+1)] = convert(Array{Float64}, range(0, stop=1, length=n).^3)\nxv[2:2:(2*(n-1)+2)] = 3*convert(Array{Float64}, range(0, stop=1, length=n).^2)\n@test abs(convert(Float64, (xv' * M_h3 * xv)[1]) - 1 / 7) < 1e-15\n\nnodes = convert(Array{Float64, 1}, range(0, stop=1, length=n))\nelem_M_p1 = SymFEL.get_lagrange_em(1, 0, 0)\nM_p1_nu = SymFEL.assemble_1d_nu_FE_matrix(elem_M_p1, nodes; intNodes1 = 0, intNodes2 = 0, dof1 = 1, dof2 = 1)\nA = M_p1 - M_p1_nu\n@test norm(A[:]) < 1e-15\n##\n\nnodes = [convert(Array{Float64}, range(0, stop=0.99, length=100));\n         convert(Array{Float64}, range(0.99, stop=1, length=101))]\nM_p1_nu2 = SymFEL.assemble_1d_nu_FE_matrix(elem_M_p1, nodes; intNodes1 = 0, intNodes2=0, dof1 = 1, dof2 = 1)\nxv = nodes.^2\n@test abs((xv' * M_p1_nu2 * xv)[1] - 1 / 5) < 1e-4\n\n\n# lagrange - hermite\nn = 1001\nxv = range(0, stop=1, length=2*n-1).^4\ndx = 1 / (n - 1)\n\nelem_M = SymFEL.get_em(2, 3, 1, 0, fe1=\"Lagrange\", fe2=\"Hermite\")\nelem_M = elem_M.subs(h, dx)\nelem_M = convert(Matrix{Float64}, elem_M)\nM = SymFEL.assemble_1d_FE_matrix(elem_M, n, intNodes1 = 1, intNodes2 = 0, dof1 = 1, dof2 = 2)\n\nxr = zeros(2*n)\nxvr2 = range(0, stop=1, length=n)\ni = 1:n\nxr[2*(i .- 1) .+ 1] = xvr2\nxr[2*(i .- 1) .+ 2] = ones(n)\n\n@test abs((xv' * M * xr)[1] - 4 / 5) < 1e-14\nprintln(\"All tests passed.\")\n\n\n", "meta": {"hexsha": "e64edac9a79a31cc288d967ee5f8126daaeaa8ac", "size": 5121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 28.45, "max_line_length": 109, "alphanum_fraction": 0.6071079867, "num_tokens": 2359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451595, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7950998607812286}}
{"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    \u03bc = shuffle(MersenneTwister(888888), 1:len)[1:k] .|> x -> matrix[x]\n    C::Vector{Vector{Vector{T}}} = 1:k .|> _ -> []\n    for _ \u2208 1:max\n        for x \u2208 matrix\n            distances = \u03bc .|> \u03f5 -> distance(x, \u03f5)\n            min = argmin(distances)\n            C[min] = C[min] \u222a [x]\n        end\n        \u03b4 = C .|> x -> mean(x)\n        \u03bc == \u03b4 && break\n        \u03bc = \u03b4\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 \u2248 3\u03c0/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 \u2248 \u03c0/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 \u2248 3\u03c0/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 \u2248 3\u03c0/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) * \u03c0 / (2 * n)) for k = n:-1:1], fill(\u03c0 / n, n))\n    elseif kind == 2\n        # Gauss-ChebyshevU quadrature, i.e., w(x) = sqrt(1-x^2)\n        return ([cos(k * \u03c0 / (n + 1)) for k = n:-1:1],\n                [\u03c0/(n + 1) * sin(k / (n + 1) * \u03c0)^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) * \u03c0 / (n + .5)) for k = n:-1:1],\n                [2\u03c0 / (n + .5) * cos((k - .5) * \u03c0 / (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 * \u03c0 / (n + .5)) for k = n:-1:1],\n                [2\u03c0 / (n + .5) * sin(k * \u03c0 / (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\u00e9chet mean](https://en.wikipedia.org/wiki/Fr\u00e9chet_mean):\n# For given points ``p_i \u2208\\mathcal M``, ``i=1,\u2026,N`` this optimization problem reads\n#\n# ```math\n# \\operatorname*{arg\\,min}_{x\u2208\\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\u03c3 = \u03c0 / 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), \u03c3)) 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) + \u2211(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, \u03b1scheme, \u03b1scheme_time, \n    \u03b1scheme_atime, TR_BDF2, ExplicitNewmark, Newmark\n\nfunction runge_kutta_one_step(f::Function, t::PyObject, y::PyObject, \u0394t::PyObject, \u03b8::Union{PyObject, Missing})\n    k1 = \u0394t*f(t, y, \u03b8)\n    k2 = \u0394t*f(t+\u0394t/2, y+k1/2, \u03b8)\n    k3 = \u0394t*f(t+\u0394t/2, y+k2/2, \u03b8)\n    k4 = \u0394t*f(t+\u0394t, y+k3, \u03b8)\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, \u03b8::Union{PyObject, Missing})\n    k1 = h * f(t, y, \u03b8);\n    k2 = h * f(t + (1/5)*h, y + (1/5)*k1, \u03b8);\n    k3 = h * f(t + (3/10)*h, y + (3/40)*k1 + (9/40)*k2, \u03b8);\n    k4 = h * f(t + (4/5)*h, y + (44/45)*k1 + (-56/15)*k2 + (32/9)*k3, \u03b8);\n    k5 = h * f(t + (8/9)*h, y + (19372/6561)*k1 + (-25360/2187)*k2 + (64448/6561)*k3 + (-212/729)*k4, \u03b8);\n    k6 = h * f(t + h, y + (9017/3168)*k1 + (-355/33)*k2 + (46732/5247 )*k3 + (49/176)*k4 + (-5103/18656)*k5, \u03b8);\n    k7 = h * f(t + h, y + (35/384)*k1 + (500/1113)*k3 + (125/192)*k4 + (-2187/6784)*k5 + (11/84)*k6, \u03b8);\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}}, \u03b8::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}}, \u03b8::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    \u0394t = 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(\u0394t), i)-1)*\u0394t, y, \u0394t, \u03b8)\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, \u03b8::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, \u03b8::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    \u03b1scheme(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        \u0394t::Array{Float64}; \n        solve::Union{Missing, Function} = missing,\n        extsolve::Union{Missing, Function} = missing, \n        \u03c1::Float64 = 1.0)\n\nGeneralized \u03b1-scheme. \n$$M u_{tt} + C u_{t} + K u = F$$\n\n`Force` must be an array of size `n`\u00d7`p`, where `d0`, `v0`, and `a0` have a size `p`\n`\u0394t` is an array (variable time step). \n\nThe generalized \u03b1 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\u2218 `solve`: users can provide a solver function, `solve(A, rhs)` for solving `Ax = rhs`\n\u2218 `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 \u03b1 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 \u03b1scheme(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                      \u0394t::Array{Float64, 1}; \n                      solve::Union{Missing, Function} = missing,\n                      extsolve::Union{Missing, Function} = missing, \n                      \u03c1::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(\u0394t)\n    \u03b1m = (2\u03c1-1)/(\u03c1+1)\n    \u03b1f = \u03c1/(1+\u03c1)\n    \u03b3 = 1/2-\u03b1m+\u03b1f \n    \u03b2 = 0.25*(1-\u03b1m+\u03b1f)^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, \u0394t = convert_to_tensor([Force, d0, v0, a0, \u0394t], [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\u03b2)*ac \n        vn = vc + dt*((1-\u03b3)*ac)\n\n        df = (1-\u03b1f)*dn + \u03b1f*dc\n        vf = (1-\u03b1f)*vn + \u03b1f*vc \n        am = \u03b1m*ac \n\n        rhs = Force - (M*am + C*vf + K*df)\n        A = (1-\u03b1m)*M + (1-\u03b1f)*C*dt*\u03b3 + (1-\u03b1f)*K*\u03b2*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, \u0394t[i], Force[i], i)\n        dn = dc + \u0394t[i]*vc + \u0394t[i]^2/2*((1-2\u03b2)*ac+2\u03b2*y)\n        vn = vc + \u0394t[i]*((1-\u03b3)*ac+\u03b3*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    \u03b1scheme_time(\u0394t::Array{Float64}; \u03c1::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 \u03b1scheme_time(\u0394t::Array{Float64}; \u03c1::Float64 = 1.0)\n    n = length(\u0394t)\n    \u03b1m = (2\u03c1-1)/(\u03c1+1)\n    \u03b1f = \u03c1/(1+\u03c1)\n    \u03b3 = 1/2-\u03b1m+\u03b1f \n    \u03b2 = 0.25*(1-\u03b1m+\u03b1f)^2\n    function equ(tc, dt)\n        tf1 = (1-\u03b1f)*(tc+dt) + \u03b1f*tc\n        return tf1\n    end\n\n    tcf = Float64[]\n    tc = 0.0\n    for i = 1:n\n        t1 = equ(tc, \u0394t[i])\n        push!(tcf, t1)\n        tc += \u0394t[i]\n    end\n    return tcf\nend\n\n@doc raw\"\"\"\n    TR_BDF2(D0::Union{SparseTensor, SparseMatrixCSC}, \n        D1::Union{SparseTensor, SparseMatrixCSC}, \n        \u0394t::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) \u00d7 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) \u00d7 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    \u0394t::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            \u0394t::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 + \u0394t/4 * D0 \n        _D1 = 1/(\u0394t/2) * 3/2 * D1  + D0 \n        new(D0, D1, \u0394t, _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.\u0394t)\nend\n\nfunction Base.:show(io::IO, tr::TR_BDF2)\n    print(\"\"\"TR_BDF2 (DOF = $(size(tr.D0, 1)), \u0394t = $(tr.\u0394t)$(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.\u0394t/4 * (f2 + f1) - tr.\u0394t/4 * (tr.D0 * y) + tr.D1 * y\n    yn = tr._D0\\r1\n    r2 = f3 + 1/(tr.\u0394t/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)\u00f72\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.\u0394t/4 * (f2 + f1) - tr.\u0394t/4 * (tr.D0 * y) + tr.D1 * y\n    yn = tr._D0\\r1\n    r2 = f3 + 1/(tr.\u0394t/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)\u00f72+1, 2)\n    y[1,:] = y0\n    for i = 1:size(F, 1)\u00f72\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) \u0394t\n\n@doc raw\"\"\"\n    ExplicitNewmark(M::Union{SparseTensor, SparseMatrixCSC}, Z1::Union{Missing, SparseTensor, SparseMatrixCSC}, Z2::Union{Missing, SparseTensor, SparseMatrixCSC}, \u0394t::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, \u0394t)\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}, \u0394t::Float64;\n            factorize_A::Bool = true)\n        M = constant(M)\n        if ismissing(Z1)\n            A = 1/\u0394t^2 * M\n            C = -1/\u0394t^2 * M \n        else\n            Z1 = constant(Z1)\n            A = (1/\u0394t^2 * M + 1/(2\u0394t) * Z1)\n            C = -(1/\u0394t^2 * M - 1/(2\u0394t) * Z1)\n        end\n        if isa(A, SparseTensor) && factorize_A\n            A = factorize(A)\n        end\n        if ismissing(Z2)\n            B = 2/\u0394t^2 * M\n        else\n            Z2 = constant(Z2)\n            B = (2/\u0394t^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                        \u0394t::Float64; \u03b2::Float64 = 1/4, \u03b3::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    \u03b2::Float64\n    \u03b3::Float64\n    \u0394t::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            \u0394t::Float64; \u03b2::Float64 = 1/4, \u03b3::Float64 = 1/2, factorize_S::Bool = true)\n        M = SparseTensor(M)\n        C = SparseTensor(C)\n        K = SparseTensor(K)\n        S = M + \u03b3*\u0394t*C + \u03b2*\u0394t^2*K\n        if factorize_S\n            S = factorize(S)\n        end\n        new(M, C, K, S, \u03b2, \u03b3, \u0394t)\n    end\nend\n\nfunction Base.:show(io::IO, en::Newmark)\n    print(\"Newmark(DOF=$(size(en.S, 1)), \u03b3=$(en.\u03b3), \u03b2=$(en.\u03b2))\")\nend\n\n\nfunction Base.:step(nm::Newmark, d::PyObject, v::PyObject, a::PyObject, \n        F::Union{Array{Float64, 1}, PyObject})\n    \u03b2, \u03b3, \u0394t = nm.\u03b2, nm.\u03b3, nm.\u0394t\n    td = d + \u0394t * v + \u0394t^2/2*(1-2\u03b2)*a \n    tv = v + (1-\u03b3)*\u0394t*a     \n    a_ = nm.S\\(-F - nm.C*tv - nm.K*td)\n    d_ = td + \u03b2*\u0394t^2*a_\n    v_ = tv + \u03b3*\u0394t*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 \u2264 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# \u2554\u2550\u2561 ceff6126-51fc-11eb-3cf5-dd30d637e267\nbegin\n\tusing Dates \n\tusing MortalityTables \n\tusing DifferentialEquations \n\tusing Plots \n\tusing ActuaryUtilities\nend\n\n# \u2554\u2550\u2561 cd5e7080-5348-11eb-2c22-455a3556cab0\nmd\"\n# Universal Life Policy Account Mechanics as a Differential Equation\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ef26ffb6-5348-11eb-04a8-c5cbfdcab72a\nmd\"\"\"\nLet's use the 2001 CSO table as the basis for cost of insurance charges:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500cd5e7080-5348-11eb-2c22-455a3556cab0\n# \u255f\u2500de0ace1a-5348-11eb-35c9-5f0ff4009d97\n# \u2560\u2550ceff6126-51fc-11eb-3cf5-dd30d637e267\n# \u255f\u2500ef26ffb6-5348-11eb-04a8-c5cbfdcab72a\n# \u2560\u255045dab59c-528d-11eb-357d-af3664466910\n# \u255f\u2500ffe9b6e0-5348-11eb-2d38-a5613eb24383\n# \u2560\u2550da199644-51fc-11eb-0aab-dd68b1fcddc6\n# \u255f\u25008a227236-5349-11eb-353d-1d3f94a968d0\n# \u2560\u2550956811e4-5349-11eb-2b34-b5441def32a1\n# \u255f\u25009ee35710-5349-11eb-0d45-23bc292d8a3d\n# \u2560\u2550b65ef28c-5349-11eb-1baa-6575ad7fb946\n# \u255f\u2500c4637664-5349-11eb-0e81-59e39974f02e\n# \u2560\u255002cc352a-5409-11eb-0fda-336d5fa42fa9\n# \u255f\u250021e53f60-5409-11eb-291d-d903da8e16b4\n# \u2560\u2550280d25a6-5409-11eb-17d9-674f218f4351\n# \u255f\u2500684f7efc-5409-11eb-0757-19b40c5d418e\n# \u255f\u25007e80faf0-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": "# ---\n# title: 1137. N-th Tribonacci Number\n# id: problem1137\n# author: zhwang\n# date: 2022-02-10\n# difficulty: Easy\n# categories: Recursion\n# link: <https://leetcode.com/problems/n-th-tribonacci-number/description/>\n# hidden: true\n# ---\n# \n# The Tribonacci sequence Tn is defined as follows:\n# \n# T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn \\+ Tn+1 \\+ Tn+2 for n >= 0.\n# \n# Given `n`, return the value of Tn.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 4\n#     Output: 4\n#     Explanation:\n#     T_3 = 0 + 1 + 1 = 2\n#     T_4 = 1 + 1 + 2 = 4\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 25\n#     Output: 1389537\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `0 <= n <= 37`\n#   * The answer is guaranteed to fit within a 32-bit integer, ie. `answer <= 2^31 - 1`.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction tribonacci_1137(n::Int)::Int\n    n <= 1 && return n\n    a, b, c = 0, 1, 1\n    for _ in 1:(n - 2)\n        a, b, c = b, c, a + b + c\n    end\n    c\nend\n## @lc code=end\n\n## @lc test=start\n@testset \"1137.n-th-tribonacci-number.jl\" begin\n    @test tribonacci_1137(0) == 0\n    @test tribonacci_1137(3) == 2\n    @test tribonacci_1137(4) == 4\n    @test tribonacci_1137(37) == 2082876103\nend\n## @lc test=end\n# link: [solution to 1137](https://leetcode-cn.com/problems/n-th-tribonacci-number/solution/1137-di-n-ge-tai-bo-na-qi-shu-by-rex-rs-ilwr/)\n## @lc info=start\n\n## @lc info=end", "meta": {"hexsha": "70738ce403412b803fca2fab84438b8322aad68a", "size": 1407, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/submited/date-02/1137.n-th-tribonacci-number.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-02/1137.n-th-tribonacci-number.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-02/1137.n-th-tribonacci-number.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": 19.8169014085, "max_line_length": 138, "alphanum_fraction": 0.5586353945, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.7949850517963449}}
{"text": "using NumericalMethodsforEngineers\n\nab = SymmetricBandedMatrix(2, Float64[0 0 16; 0 4 5; 8 -4 22])\nbb = SymmetricBandedMatrix(3, Float64[0 0 0 16; 0 0 4 2; 0 8 -4 22; 13 5 9 1])\ncb = SymmetricBandedMatrix(4, Float64[0 0 0 0 1; 0 0 0 2 3; 0 0 4 5 6; 0 7 8 9 10; 11 12 13 14 15])\ndb = SymmetricBandedMatrix(2, Float64[0 0 16; 0 4 5; 8 -4 22; 1 2 3; 0 7 6 ; 11 0 15])\neb = SymmetricBandedMatrix(3, Float32[0 0 0 16; 0 0 4 5; 0 8 -4 22; 1 2 3 4; 0 0 7 6 ; 0 11 0 15; 0 0 0 20])\nebi = SymmetricBandedMatrix(3, [0 0 0 16; 0 0 4 5; 0 8 -4 22; 1 2 3 4; 0 0 7 6; 0 11 0 15; 0 0 0 20])\nebf = SymmetricBandedMatrix(3, [0 0 0 16+0.1im; 0 0 4 5; 0 8 -4+9im 22; 1 2 3 4; 0 0 7 6 ; 0 11 0 15; 0 0 0 20])\nebif = SymmetricBandedMatrix(3, [0 0 0 16; 0 0 4+im 5; 0 8 -4 22; 1 2 3 4; 0 0 7 6; 0 11 0 15; 0 0 0 20])\nebif32 = SymmetricBandedMatrix(3, Complex{Float32}[0 0 0 16; 0 0 4+im 5; 0 8 -4 22; 1 2 3 4; 0 0 7 6; 0 11 0 15; 0 0 0 20])\n\na = full(ab)\nres = tosymmetricbandedmatrix(2, a)\n@test res == ab\n\nb = full(bb)\nres = tosymmetricbandedmatrix(3, b,)\n@test res == bb\n\nc = full(cb)\nres = tosymmetricbandedmatrix(4, c)\n@test res == cb\n\nd = full(db)\nres = tosymmetricbandedmatrix(2, d)\n@test res == db\n\ne = full(eb)\nres = tosymmetricbandedmatrix(3, e)\n@test res == eb\nres2 = tosymmetricbandedmatrix(e)\n@test res2 == res\n\nei = full(ebi)\nres = tosymmetricbandedmatrix(3, ei)\n@test res == ebi\nres2 = tosymmetricbandedmatrix(ei)\n@test res2 == res\n\nef = full(ebf)\nres = tosymmetricbandedmatrix(3, ef)\n@test res == ebf\n\neif = full(ebif)\nres = tosymmetricbandedmatrix(3, eif)\n@test res == ebif\n\neif32 = full(ebif32)\nres = tosymmetricbandedmatrix(3, eif32)\n@test res == ebif32\n\nres2 = copy(res)\n@test res == res2\n@test res !== res2\n\nres2.bmat[4, 3] = 8.0+9im\n@test res != res2\n@test res !== res2\n\nres3 = res2\n@test res3 == res2\n@test res3 === res2\n\nf=sprand(6, 6, 0.3)\nff = Matrix(f)\nffs=ff.+ff'\nbm = tosymmetricbandedmatrix(ffs)\n@test full(bm) == ffs\n\nms = sprand(5, 5, 0.1)\n# Make sure it is symmetric\nsms = issymmetric(ms) ? ms : ms .+ ms'\nbms = issymmetric(sms) ? convert(SymmetricBandedMatrix, sms) : convert(SymmetricBandedMatrix, round(sms, 8))\n@test full(bms) == sms\n\n", "meta": {"hexsha": "3d9d9e117583d58f174ad7d88855c283cda9c37e", "size": 2150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch02_SymmetricBandedMatrix.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/ch02_SymmetricBandedMatrix.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/ch02_SymmetricBandedMatrix.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.9220779221, "max_line_length": 123, "alphanum_fraction": 0.6493023256, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.7949850487931259}}
{"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(\u03b8) = pdf(Normal(\u03b8, sqrt(obsVar)), x)\n    prior(\u03b8) = pdf(cprior, \u03b8)\n    post(\u03b8) = lik(\u03b8).*prior(\u03b8)\n    \n    \u221e=10\n    \n    Z, err = hquadrature(post, -\u221e, \u221e; reltol=1e-4)\n    \n    f(\u03b8) = \u03b8.*post(\u03b8)/Z\n    \n    postMeanCauchy, err = hquadrature(f, -\u221e, \u221e; 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 nlp_cvx_107_012(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    model = Model(optimizer)\n\n    @variable(model, x, start = 1.5)\n    @variable(model, y, start = 0.5)\n\n    @objective(model, Min, (x - 1.0)^2 + (y - 1.0)^2)\n    @NLconstraint(model, x^2 + y^2 <= 1)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, 0.17157287363083387, tol = objective_tol)\n    return check_solution([x, y], [1 / sqrt(2), 1 / sqrt(2)], tol = primal_tol)\nend\n", "meta": {"hexsha": "64a45e8cddde8da057056e28ade31da307ff161d", "size": 637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/107_012.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/107_012.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/107_012.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 27.6956521739, "max_line_length": 79, "alphanum_fraction": 0.6687598116, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8333245911726381, "lm_q1q2_score": 0.7949634115475818}}
{"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": "using Test\n\nfunction naive!(C, A, B)\n    row, col  = size(C)\n    colA = size(A)[2]\n    for i in 1:row\n        for j in 1:col\n            for k in 1:colA\n                C[i, j] = C[i, j] + A[i, k] * B[k, j]\n            end\n        end\n    end\n    C\nend\n\n\n\"\"\"\ninner-product-form\n\"\"\"\nfunction ipform!(C, A, B)\n    row, col  = size(C)\n    colA = size(A)[2]\n    for i in 1:row\n        for j in 1:col\n            dataC = 0.0\n            for k in 1:colA\n                dataC = dataC + A[i, k] * B[k, j]\n            end\n            C[i, j] = dataC\n        end\n    end\nend\n\n\n\"\"\"\nouter-product-form\n\"\"\"\nfunction opform!(C, A, B)\n    row, col  = size(C)\n    colA = size(A)[2]\n    for k in 1:colA\n        for j in 1:col\n            dataB = B[k, j]\n            for i in 1:row\n                C[i, j] = C[i, j] + A[i, k] * dataB\n            end\n        end\n    end\nend\n\n\n\"\"\"\nmiddle-product-form\n\"\"\"\nfunction mpform!(C, A, B)\n    row, col  = size(C)\n    colA = size(A)[2]\n    for j in 1:col\n        for k in 1:colA \n            dataB = B[k, j]\n            for i in 1:row\n                C[i, j] = C[i, j] + A[i, k] * dataB\n            end\n        end\n    end\nend\n\n\nfunction main(N)\n    A = reshape(collect(1:1.0:N^2), N, N)\n    B = reshape(collect(1:1.0:N^2), N, N)\n    C = zeros(N, N)\n    @time naive!(C, A, B)\n    # copy result\n    refC = copy(C)\n\n    C = zeros(N, N)\n    @time ipform!(C, A, B)\n    @test C \u2248 refC\n\n    C = zeros(N, N)\n    @time opform!(C, A, B)\n    @test C \u2248 refC\n\n    C = zeros(N, N)\n    @time mpform!(C, A, B)\n    @test C \u2248 refC\nend\n", "meta": {"hexsha": "c6652a925a15cc3b8dbfaed61fe544747341c346", "size": 1541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "matrixProd/exchange_product_form.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": "matrixProd/exchange_product_form.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": "matrixProd/exchange_product_form.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": 17.3146067416, "max_line_length": 53, "alphanum_fraction": 0.4269954575, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.8688267745399466, "lm_q1q2_score": 0.7948904517979494}}
{"text": "module  DifferentiableFunctionsTests\n\nusing Test\nusing ProximalBase\nusing Random\nusing LinearAlgebra\n\nRandom.seed!(1)\n\n@testset \"L2Loss\" begin\n\n  x = randn(5)\n  y = randn(5)\n  f1 = L2Loss()\n  f2 = L2Loss(y)\n\n  @test value(f1, x) \u2248 sum(abs2,x)/2.\n  @test value(f2, x) \u2248 sum(abs2,x-y)/2.\n\n  hat_x = similar(x)\n  @test value_and_gradient!(f1, hat_x, x) \u2248 sum(abs2,x)/2.\n  @test hat_x \u2248 x\n  hat_x = similar(x)\n  @test value_and_gradient!(f2, hat_x, x) \u2248 sum(abs2,x-y)/2.\n  @test hat_x \u2248 x-y\n\nend\n\n@testset \"Quadratic Function\" begin\n\n  A = randn(10, 10)\n  A = A + A'\n  b = randn(10)\n  c = 1.\n\n  x = randn(10)\n\n  q1 = QuadraticFunction(A)\n  q2 = QuadraticFunction(A, b)\n  q3 = QuadraticFunction(A, b, c)\n\n  @test value(q1, x) \u2248 dot(x, A*x)/2.\n  @test value(q2, x) \u2248 dot(x, A*x)/2. + dot(x, b)\n  @test value(q3, x) \u2248 dot(x, A*x)/2. + dot(x, b) + c\n\n  hat_x = similar(x)\n  @test value_and_gradient!(q1, hat_x, x) \u2248 dot(x, A*x)/2.\n  @test hat_x \u2248 A*x\n\n  @test value_and_gradient!(q2, hat_x, x) \u2248 dot(x, A*x)/2. + dot(x, b)\n  @test hat_x \u2248 A*x + b\n\n  @test value_and_gradient!(q3, hat_x, x) \u2248 dot(x, A*x)/2. + dot(x, b) + c\n  @test hat_x \u2248 A*x + b\nend\n\n\n@testset \"Least Squares Loss\" begin\n\n  y = randn(10)\n  X = randn(10, 5)\n  b = rand(5)\n  f = LeastSquaresLoss(y, X)\n\n  @test value(f, b) \u2248 norm(y-X*b)^2 / 2.\n  grad_out = zeros(5)\n  @test value_and_gradient!(f, grad_out, b) \u2248 norm(y-X*b)^2 / 2.\n  @test grad_out \u2248 -X'*(y - X*b)\n\nend\n\n\nend # module\n", "meta": {"hexsha": "7406167ee72b20b68d4b16f4429218329930bcb0", "size": 1442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/differentiable_functions.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ProximalBase.jl-0a755509-c5b1-5d6f-9b24-59bcda3c37a3", "max_stars_repo_head_hexsha": "e293163def2a029619184236e1eda4dacfaf3fe6", "max_stars_repo_licenses": ["MIT"], "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/differentiable_functions.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ProximalBase.jl-0a755509-c5b1-5d6f-9b24-59bcda3c37a3", "max_issues_repo_head_hexsha": "e293163def2a029619184236e1eda4dacfaf3fe6", "max_issues_repo_licenses": ["MIT"], "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/differentiable_functions.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ProximalBase.jl-0a755509-c5b1-5d6f-9b24-59bcda3c37a3", "max_forks_repo_head_hexsha": "e293163def2a029619184236e1eda4dacfaf3fe6", "max_forks_repo_licenses": ["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.4864864865, "max_line_length": 74, "alphanum_fraction": 0.5950069348, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7948652342645609}}
{"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) =  \u2211  X(j) cos (\u03c0*(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) =  \u2211  X(j) cos (\u03c0*(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) * \u03c0 * (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 \u00f7 2\n\n    xL, xR = x \u00f7 10^m, x % 10^m\n    yL, yR = y \u00f7 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 \u00f7 2\n\n    xL, xR = x \u00f7 2^m, x % 2^m\n    yL, yR = y \u00f7 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, \u03c0])\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) \u00f7 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 \u2208 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 \u2208 1:length(A)\n        for j \u2208 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, \u03c9)\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(\u03b1, m, weights)\n\nReconstruct mathematical entropy from Legendre dual\n\"\"\"\nfunction kinetic_entropy(\u03b1::AbstractArray, m::AbstractArray, weights::AbstractVector)\n    B = KitBase.maxwell_boltzmann_dual_prime.(\u03b1' * 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": "@testset \"factorial_ij\" begin\n    @test all(\n        QSB.factorial_div(i, j) == factorial(big(i)) / factorial(big(j))\n        for i in 0:40, j in 0:40\n    )\nend\n\n@testset \"z\" begin\n    x_range = -10:0.01:10\n    p_range = -6:0.01:6\n    @test all(\n        QSB.z(x, p) == sqrt(2.)*(x + p*im)\n        for x in x_range, p in p_range\n    )\n\n    xs = collect(x_range)\n    ps = collect(p_range)\n    @test QSB.z(xs, ps) == sqrt(2.).*(xs .+ ps' .* im)\nend\n\n@testset \"gaussian_function\" begin\n    tol = 1e-14\n    x_range = -10:0.01:10\n    p_range = -6:0.01:6\n    @test all(\n        isapprox(QSB.gaussian_function(x, p), exp(-(x^2 + p^2)) / \u03c0, atol=tol)\n        for x in x_range, p in p_range\n    )\n\n    xs = collect(x_range)\n    ps = collect(p_range)\n    @test isapprox(\n        QSB.gaussian_function(xs, ps),\n        exp.(-(xs.^2 .+ (ps').^2)) ./ \u03c0,\n        atol=tol\n    )\nend\n\n@testset \"(-1)^i\" begin\n    @test all(\n        QSB.neg_one_to_power_of(i) == (-1)^i\n        for i in 1:50\n    )\nend\n\n@testset \"coefficient_of_wave_function\" begin\n    tol = 1e-14\n    @test all(\n        isapprox(\n            QSB.coefficient_of_wave_function(m, n),\n            ((n \u2265 m) ? (-1)^(m-1) : (-1)^(n-1)) *\n            sqrt(factorial(big(min(m, n))) / factorial(big(max(m, n)))),\n            atol=tol\n        )\n        for m in 1:70, n in 1:70\n    )\nend\n\n@testset \"z_to_power\" begin\n    tol = 1e-14\n\n    m_range = n_range = 1:70\n    x_range = -1:0.1:1\n    p_range = -0.6:0.1:0.6\n    @test all(\n        QSB.z_to_power(m, n, x, p) == (\n            (n >= m) ? sqrt(2.)*(x - p*im) : sqrt(2.)*(x + p*im)\n        )^(max(m, n) - min(m, n))\n        for m in m_range, n in n_range, x in x_range, p in p_range\n    )\n\n    xs = collect(x_range)\n    ps = collect(p_range)\n    @test all(\n        QSB.z_to_power(m, n, xs, ps) == QSB.z_to_power.(m, n, xs, ps')\n        for m in m_range, n in n_range\n    )\nend\n\n@testset \"laguerre\" begin\n    m_range = n_range = 1:70\n    x_range = -1:0.1:1\n    p_range = -0.6:0.1:0.6\n\n    result = Bool[]\n    # n >= m\n    for m in m_range, n in m:n_range.stop, x in x_range, p in p_range\n        push!(\n            result,\n            abs(laguerre(m, n, x, p) - laguerre(m-1, n-m, abs2(sqrt(2.)*(x+p*im)))) < 1e-7\n        )\n    end\n    # n < m\n    for n in n_range, m in n:m_range.stop, x in x_range, p in p_range\n        push!(\n            result,\n            abs(laguerre(m, n, x, p) - laguerre(n-1, m-n, abs2(sqrt(2.)*(x+p*im)))) < 1e-7\n        )\n    end\n    @test all(result)\n\n    xs = collect(x_range)\n    ps = collect(p_range)\n    @test all(\n        laguerre(m, n, xs, ps) == laguerre.(m, n, xs, ps')\n        for m in m_range, n in n_range\n    )\nend\n", "meta": {"hexsha": "2669ad10c4ceb0a1023c0af6752dd7ae3f6df05a", "size": 2647, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/wigner_util.jl", "max_stars_repo_name": "meerkat321/QuantumStateBase.jl", "max_stars_repo_head_hexsha": "476506f342cba0102832d25e1d36a2afdc61aa65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-06T15:00:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T03:14:47.000Z", "max_issues_repo_path": "test/wigner_util.jl", "max_issues_repo_name": "meerkat321/QuantumStateBase.jl", "max_issues_repo_head_hexsha": "476506f342cba0102832d25e1d36a2afdc61aa65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-07-06T08:58:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T00:33:07.000Z", "max_forks_repo_path": "test/wigner_util.jl", "max_forks_repo_name": "meerkat321/QuantumStateBase.jl", "max_forks_repo_head_hexsha": "476506f342cba0102832d25e1d36a2afdc61aa65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-07-06T07:47:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T03:17:01.000Z", "avg_line_length": 24.2844036697, "max_line_length": 90, "alphanum_fraction": 0.5073668304, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7948320469227912}}
{"text": "# Example 0: Solve 1D Burgers Equation\n# u(x,t)_t+(0.5*u\u00b2(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*\u03c0*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 calcSim(duals, dist, S)\r\n    if dist == \"L1\"\r\n        # Measures L1 distance - Minkowski with p=1\r\n        # https://juliahub.com/docs/LSHFunctions/nLuMy/0.1.2/similarities/lp_distance/\r\n        Sim = collect(\u21131(duals[i,:],duals[j,:]) for i in S, j in S)\r\n    elseif dist == \"L2\"\r\n        # Measures L2 distance - Minkowski with p=1\r\n        # https://juliahub.com/docs/LSHFunctions/nLuMy/0.1.2/similarities/lp_distance/\r\n        Sim = collect(\u21132(duals[i,:],duals[j,:]) for i in S, j in S)\r\n    elseif dist == \"jaccard\"\r\n        # Measures Jaccard similarity\r\n        # https://juliahub.com/docs/LSHFunctions/nLuMy/0.1.2/similarities/jaccard/\r\n        Sim = collect(LSHFunctions.jaccard(duals[i,:],duals[j,:]) for i in S, j in S)\r\n    elseif dist in [\"wcityblock\" \"weuclidean\" \"whamming\" \"wsqeuclidean\"]\r\n        # Weighted metrics with equal weights\r\n        W = ones(length(T))\r\n        Sim = collect(Distances.eval(Symbol(dist))(duals[i,:],duals[j,:],W)+0. for i in S, j in S)\r\n    elseif dist in [\"wcityblockvar\" \"weuclideanvar\" \"whammingvar\" \"wsqeuclideanvar\"]\r\n        # Weighted metrics with weights proportional to variance\r\n        dist = dist[1:end-3] # Renaming to use proper function\r\n        W = var(duals, dims=1)\r\n        Sim = collect(Distances.eval(Symbol(dist))(duals[i,:],duals[j,:],W)+0. for i in S, j in S)\r\n    elseif dist in [\"wcityblockinv\" \"weuclideaninv\" \"whamminginv\" \"wsqeuclideaninv\"]\r\n        dist = dist[1:end-3] # Renaming to use proper function\r\n        # Weighted metrics with weights inverse to variance\r\n        VAR = var(duals, dims=1)\r\n        W = 1  .- VAR./maximum(VAR)\r\n        Sim = collect(Distances.eval(Symbol(dist))(duals[i,:],duals[j,:],W)+0. for i in S, j in S)\r\n    else\r\n        Sim = collect(Distances.eval(Symbol(dist))(duals[i,:],duals[j,:])+0. for i in S, j in S)\r\n    end\r\n    return Sim\r\nend\r\n", "meta": {"hexsha": "87735dc4d369f804d05726941c839190afd0876a", "size": 1858, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/calcSim.jl", "max_stars_repo_name": "gonzalez-alvaro/MultidimensionalGAPM", "max_stars_repo_head_hexsha": "605ca8f13feb189b5932ac72a77504e65bbd02c7", "max_stars_repo_licenses": ["MIT"], "max_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/calcSim.jl", "max_issues_repo_name": "gonzalez-alvaro/MultidimensionalGAPM", "max_issues_repo_head_hexsha": "605ca8f13feb189b5932ac72a77504e65bbd02c7", "max_issues_repo_licenses": ["MIT"], "max_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/calcSim.jl", "max_forks_repo_name": "gonzalez-alvaro/MultidimensionalGAPM", "max_forks_repo_head_hexsha": "605ca8f13feb189b5932ac72a77504e65bbd02c7", "max_forks_repo_licenses": ["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.6470588235, "max_line_length": 99, "alphanum_fraction": 0.6184068891, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.794832044999575}}
{"text": "using MomentClosure\r\nusing MomentClosure: expected_coeff\r\nusing ModelingToolkit: value, simplify\r\nusing SymbolicUtils: expand\r\nusing Test\r\n\r\n@parameters b\r\nb = b.val\r\n@test expected_coeff(2, 3) == 8\r\n@test isequal(expected_coeff(b, 3), b*(1 + (6b) + (6(b^2))))\r\nexpr = ((b*((1 + b)^-1)) + ((b^6)*((1 + b)^-6)) + (57(b^2)*((1 + b)^-2)) + (302(b^3)*((1 + b)^-3)) + (302(b^4)*((1 + b)^-4)) + (57(b^5)*((1 + b)^-5)))*((1 + b)^6)\r\n@test isequal(expected_coeff(b, 6), expr)\r\n\r\n@parameters t, c\u2081, c\u2082, c\u2083, c\u2084, \u03a9\r\n@variables X(t), Y(t)\r\n\r\nS_mat = [ 1 -1  1 -1;\r\n         -1  1  0  0]\r\na = [c\u2081*X*Y*(X-1)/\u03a9^2, c\u2082*X, c\u2083*\u03a9, c\u2084*X]\r\nrn = ReactionSystemMod(t, [X, Y], [c\u2081, c\u2082, c\u2083, c\u2084, \u03a9], a, S_mat)\r\n\r\nsys = generate_central_moment_eqs(rn, 2, 4)\r\nexpr1 = sys.odes.eqs[2].rhs\r\n@test isequal(MomentClosure.Differential(t)(sys.\u03bc[1,0]), sys.odes.eqs[1].lhs)\r\n\u03bc = sys.\u03bc\r\nM = sys.M\r\n# simplify(value()) is needed due to diffs between ModelingToolkit Num type and SymbolicUtils types\r\nexpr2 = c\u2082*\u03bc[1,0] + c\u2081*M[1,1]*(\u03a9^-2) + c\u2081*\u03bc[0,1]*\u03bc[1,0]*\u03a9^-2 - c\u2081*M[2,1]*\u03a9^-2 -\r\n        2*c\u2081*M[1,1]*\u03bc[1,0]*\u03a9^-2 - c\u2081*M[2,0]*\u03bc[0,1]*\u03a9^-2 - c\u2081*\u03bc[0,1]*\u03a9^-2*\u03bc[1,0]^2\r\nexpr2 = simplify(value.(expr2))\r\n@test isequal(expand(expr1), expr2)\r\n\r\nsys = generate_central_moment_eqs(rn, 2)\r\nexpr1 = sys.odes.eqs[2].rhs\r\n@test isequal(MomentClosure.Differential(t)(sys.\u03bc[1,0]), sys.odes.eqs[1].lhs)\r\n@test isequal(expand(expr1), expr2)\r\n\r\nsys = generate_raw_moment_eqs(rn, 2)\r\n\u03bc = sys.\u03bc\r\nexpr1 = sys.odes.eqs[4].rhs\r\nexpr2 = c\u2082*\u03bc[2,0] + c\u2081*\u03bc[1,1]/\u03a9^2 - c\u2081*\u03bc[3,1]/\u03a9^2 -c\u2082*(\u03bc[1,0] + \u03bc[1,1]) +\r\n        c\u2083*\u03bc[0,1]*\u03a9 - c\u2084*\u03bc[1,1] - c\u2081*\u03bc[1,2]/\u03a9^2 + c\u2081*\u03bc[2,2]/\u03a9^2\r\nexpr2 = simplify(value.(expr2))\r\n@test isequal(expand(expr1), expand(expr2))\r\n", "meta": {"hexsha": "678f95184c113ba24c478f1c4a06a47aa3619c5f", "size": 1683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/moment_equations_tests.jl", "max_stars_repo_name": "palmtree2013/MomentClosure.jl", "max_stars_repo_head_hexsha": "171d18818657bf1e93240e4b24d393fac3eea72d", "max_stars_repo_licenses": ["MIT"], "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/moment_equations_tests.jl", "max_issues_repo_name": "palmtree2013/MomentClosure.jl", "max_issues_repo_head_hexsha": "171d18818657bf1e93240e4b24d393fac3eea72d", "max_issues_repo_licenses": ["MIT"], "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/moment_equations_tests.jl", "max_forks_repo_name": "palmtree2013/MomentClosure.jl", "max_forks_repo_head_hexsha": "171d18818657bf1e93240e4b24d393fac3eea72d", "max_forks_repo_licenses": ["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.4, "max_line_length": 163, "alphanum_fraction": 0.5846702317, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537142, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7948320445027117}}
{"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": "using GridCreation\n\n\n@testset \"zernike zero separation\" begin\n    for i in 1:100\n        sep = zernike_zero_separation(i)\n        @test 1/sep \u2248 Float64(i)^2\n    end\nend\n\n@testset \"zernike fringe and nm round trip\" begin\n    for i in 1:100\n        n, m = zernike_fringe_to_nm(i)\n        j = zernike_nm_to_fringe(n,m)\n        @test j == i\n    end\nend\n\n@testset \"zernike ANSI round trips\" begin\n    for i in 1:100\n        n, m = zernike_ansi_j_to_nm(i)\n        j = zernike_nm_to_ansi_j(n,m)\n        @test j == i\n    end\nend\n\n\n@testset \"zernike gives correct values\" begin\n    for i in 1:100\n        # a visual test proves the correctness of the zernike function in\n        # general.  The values could only really be tested in a regression\n        # fashion, generally, which is undesireable and assumes another\n        # implementation is de-facto correct.\n\n        # the test here, therefore, verifies only the analytic value of one\n        # at the edge for the maxima of the azumithal term.\n        n, m = zernike_noll_to_nm(i)\n        out = zernike(n, m, [1.], [0.], norm=false)\n        @test (out \u2248 [1.]) || (out \u2248 [0.])\n        out = zernike(n, m, [1.], [0], norm=true)\n        norm = [zernike_norm(n,m)]\n        @test (out \u2248 norm) || (out \u2248 [0.])\n    end\nend\n\n@testset \"zernike series contains proper modes\" begin\n    x, y = mkCartVecs(1/8, 16)\n    r, t = cartVecsToPolarGrid(x,y)\n    modes = 1:11\n    nms = zernike_noll_to_nm.(modes)\n    out = zernike_series(nms, r, t)\n    for mode in modes\n        n, m = zernike_noll_to_nm(mode)\n        truth = zernike(n, m, r, t)\n        @test out[:, :, mode] \u2248 truth\n    end\nend\n\n\n@testset \"zernike sum contains proper modes\" begin\n    x, y = mkCartVecs(1/8, 16)\n    r, t = cartVecsToPolarGrid(x,y)\n    nms = zernike_noll_to_nm.(1:11)\n    weights = zeros(11)\n    weights[5]=1.\n    out = zernike_sum(nms, weights, r, t)\n    truth = zernike(2, -2, r, t)\n    @test out \u2248 truth\nend\n", "meta": {"hexsha": "0f3fb4cc273f91b4d858c236688ef67b5e044c94", "size": 1923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/zernike.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": "test/zernike.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": "test/zernike.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": 27.4714285714, "max_line_length": 75, "alphanum_fraction": 0.603224129, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7948320392299264}}
{"text": "using ChaosTools\nusing Test\nusing Distances: Cityblock, Euclidean\n\ntest_value = (val, vmin, vmax) -> @test vmin <= val <= vmax\n\nprintln(\"\\nTesting nonlinear timeseries analysis...\")\n@testset \"Henon reconstruct\" begin\n    ds = Systems.henon()\n    data = trajectory(ds, 100000)\n    x = data[:, 1] # some \"recorded\" timeseries\n\n    @testset \"Dimension\" begin\n        \u03c4 = 1; D = 2\n        R = reconstruct(x, D-1, \u03c4)\n        D2 = information_dim(R)\n        test_value(D2, 1.1, 1.3)\n    end\n    @testset \"Numerical Lyapunov\" begin\n        ks = 1:20\n        @testset \"meth = $meth\" for meth in\n            [FixedMassNeighborhood(1), FixedMassNeighborhood(4),\n            FixedSizeNeighborhood(0.01)]\n            @testset \"distance = $di\" for di in [Euclidean(), Cityblock()]\n                for D in [2, 4]\n                    R = reconstruct(x, D-1, 1)\n                    E = numericallyapunov(R, ks,\n                    refstates = 1:1000, distance=di, ntype=meth)\n                    \u03bb = linear_region(ks, E)[2]\n                    test_value(\u03bb, 0.3, 0.5)\n                end\n            end\n        end\n    end\nend\n@testset \"Multidim Multitime R\" begin\n    ds = Systems.towel()\n    data = trajectory(ds, 10000)\n\n    taus = [2 3; 4 6; 6 8]\n    data2 = data[:, 1:2]\n    R = reconstruct(data2, 3, taus)\n\n    ks = 1:20\n    E = numericallyapunov(R, ks,\n    refstates = 1:1000, distance=Cityblock(), ntype=FixedMassNeighborhood(1))\n    \u03bb = linear_region(ks, E)[2]\n    test_value(\u03bb, 0.3, 0.6)\nend\n\n@testset \"Broomhead-King\" begin\n    using Random\n    Random.seed!(1234);\n    ds = Systems.gissinger(ones(3)) # standard initial condition\n\n    data = trajectory(ds, 1000.0, dt = 0.05)\n    x = data[1:end-1, 1] # \"exactly\" 20000 points\n    s = x .+ 0.01rand(length(x))\n\n    Ux, \u03a3x = broomhead_king(x, 40)\n    Us, \u03a3s = broomhead_king(s, 40)\n    R = reconstruct(x, 1, 30)\n\n    for j in 10:40\n        @test \u03a3x[j] < \u03a3s[j]\n    end\n\n    newcoords = Dataset(Us[:, 1], Us[:, 2])\n    newcoordsclean = Dataset(Ux[:, 1], Ux[:, 2])\n\n    Dnew = information_dim(newcoords)\n    DR = information_dim(R)\n    DC = information_dim(newcoordsclean)\n    @test abs(Dnew - 0.1 - DR) < 0.2 # subtract 0.1 for \"added dimensionality\"\n    @test abs(DC - DR) < 0.2\nend\n", "meta": {"hexsha": "00d26c5c6830cdf094e62dcda447fa29f5b42300", "size": 2227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/nlts_tests.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": "test/nlts_tests.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": "test/nlts_tests.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": 28.9220779221, "max_line_length": 78, "alphanum_fraction": 0.5684777728, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7948320375230231}}
{"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\u03c6 = MathConstants.\u03c6\nfunction golden_section_search(f, a, b, n)\n    \u03c1 = \u03c6-1\n    d = \u03c1 * b + (1 - \u03c1)*a\n    yd = f(d)\n    for i = 1 : n-1\n        c = \u03c1*a + (1 - \u03c1)*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 = \u03b1 -> f(x + \u03b1*d)\n    a, b,c = bracket_minimum(objective)\n    \n    #numero de iteracoes\n    n=(c-a)/(10^-3*log(\u03c6))\n    \n    #pelo metodo golden section search\n    \u03b1,beta = golden_section_search(objective, a, c,n)\n\n    #pelo metodo quadratic fit search\n    #\u03b1,beta,gamma = quadratic_fit_search(objective, a, b, c,n)\n    return (x + \u03b1*d,\u03b1)\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,\u03b1) = 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    \u03bc = mean(X)\n\n    @simd for xi in X\n        s += (xi - \u03bc)^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    \u03bc = mean(X)\n\n    @simd for xi in X\n        s += abs(xi - \u03bc)\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": "using Test\nusing RiemannComplexNumbers\n\na = 2+3IM\nb = 4-5IM\n\n@test a+b == 6-2im\n@test a/0 == ComplexInf\n@test isinf(a/0)\n@test Complex(a)==a\n@test hash(a) == hash(Complex(a))\n@test isnan((a-a)/(b-b))\n@test Inf + IM == Inf + 2*im\n@test ComplexInf * ComplexInf == ComplexInf\n@test isnan(ComplexInf + ComplexInf)\n@test isnan(0*ComplexInf)\n\n@test 1/a == inv(a)\n@test a' == conj(a)\n\n@test one(RC) == 1\n@test zero(RC) == 0\n\nz = RC(2+3im)\n@test z*z == -5 + 12im\n@test z/z == 1\n@test z^3 == z*z*z\n@test z^(-1) == 1/z\n@test sqrt(RC(-1)) == IM\n@test exp(2+3im) == exp(2+3IM)\n@test angle(IM) == pi/2\nz = 3 - 4IM\n@test abs(z*z) == 25\n@test abs(z*z) == z'*z\n\n@test abs(exp(log(-1+0IM)) + 1) < 1e-10\n@test abs(log(exp(-1+2IM)) - (-1+2IM)) < 1e-10\n\na = RC(3.0 + 0.0im)\nb = a'\n@test a==b\n@test !isequal(a,b)\n\n@test ComplexNaN != NaN\n@test isequal(ComplexNaN,NaN)\n", "meta": {"hexsha": "89cab1d433d9e99faeb666c9c15cf0a8e69f2d02", "size": 847, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannComplexNumbers.jl-3f3442c8-4998-5f9a-b6f6-804928b92bc1", "max_stars_repo_head_hexsha": "c5d306c08770ebfab6b11477649914d9d2ce87e3", "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": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannComplexNumbers.jl-3f3442c8-4998-5f9a-b6f6-804928b92bc1", "max_issues_repo_head_hexsha": "c5d306c08770ebfab6b11477649914d9d2ce87e3", "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": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannComplexNumbers.jl-3f3442c8-4998-5f9a-b6f6-804928b92bc1", "max_forks_repo_head_hexsha": "c5d306c08770ebfab6b11477649914d9d2ce87e3", "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.4130434783, "max_line_length": 46, "alphanum_fraction": 0.5903187721, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7947245363404296}}
{"text": "using JuMP\nusing Ipopt\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 = 10\n    n_constraints = 1\n\n    @variable(model, -3.0 <= x[1:n_variables] <= 5.0)\n    @NLconstraint(model, sum((x[i]^2 for i in 1:n_variables)) >= 5.0)\n\n    constraints_f = []\n    push!(constraints_f, (v) -> sum(v.^2) >= 5.0)\n\n    @NLobjective(model, Min, sum(x[i]^2 for i in 1:n_variables))\n    obj_f(v) = sum(v.^2)\n\n    starting_point = zeros(Float64, n_variables) .+ 3.0\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\n            println(f, \"$(x[i]): $(value(x[i]))\")\n            solution_point[i] = value(x[i])\n        end\n    end\n\n    variable_names = vcat([\"x[$(string(i))]\" for i in 1:n_variables])\n    constraint_names = [\"c1\"]\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\noptimizers = [Ipopt.Optimizer]\nopt_names = [\"ipopt\"]\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, \"sphere_$(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]]\nvariable_domains = convert(Array{Tuple{Float64,Float64},1}, [])\n\nfor i in 1:length(variable_names)\n    push!(variable_domains, (-4.0,5.0))\nend\n\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; line_width=3.0)\n    save_all(O, \"sphere_$(opt_name)\", \".\")\nend\n\n", "meta": {"hexsha": "6e4d40e2febca2ce0b745eb98bcba6abc86bccc3", "size": 3014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/nonlinear_sphere.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/nonlinear_sphere.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/nonlinear_sphere.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": 32.7608695652, "max_line_length": 150, "alphanum_fraction": 0.6141340411, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7947245339134664}}
{"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\u03c3 = 0.2\nt = range(0, 20, length = T)\ns = sin.(t)\ny = s + randn(T) * \u03c3\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), \u03c3^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.\u03bc, label = \"Prediction\", linewidth = 2, color = \"blue\")\nplot!(kf.posteriors.\u03bc, label = \"Filter\", linewidth = 2, color = \"red\")\nplot!(ks.\u03bc, 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": "function nlp_cvx_102_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - linear and nonlinear constraints\n    # Variants\n    #   010 - constraint intersection\n    #   011 - one binding constraint (linear)\n    #   012 - one binding constraint (nonlienar)\n    #   013 - one binding constraint (quadratic objective)\n    #   014 - no binding constraints (quadratic objective)\n\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n\n    @objective(model, Min, -x)\n    @NLconstraint(model, x^2 + y^2 <= 1.0)\n    @constraint(model, x + y >= 1.2)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -0.974165743715913, tol = objective_tol)\n    return check_solution(\n        [x, y],\n        [0.974165743715913, 0.2258342542139504],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "0ea5bfc1d74a1645db668568f199352545c13252", "size": 996, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/102_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/102_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/102_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 26.9189189189, "max_line_length": 76, "alphanum_fraction": 0.6606425703, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7946636608286975}}
{"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, \u03bb) = N*exp(-t/\u03bb)\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([\u03b1 [,\u03b3]])\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}(\u03b1::Real, \u03b3::Real) where {T<:AbstractFloat} = new{T}(\n        HyperParameter(convert(T,\u03b1), interval(OpenBound(zero(T)), nothing)),\n        HyperParameter(convert(T,\u03b3), interval(OpenBound(zero(T)), ClosedBound(one(T))))\n    )\nend\nfunction LogKernel(\u03b1::T1 = 1.0, \u03b3::T2 = one(T1)) where {T1<:Real,T2<:Real}\n    LogKernel{floattype(T1,T2)}(\u03b1, \u03b3)\nend\n\n@inline logkernel(z::T, \u03b1::T, \u03b3::T) where {T<:AbstractFloat} = log(\u03b1*z^\u03b3+1)\n\n@inline basefunction(::LogKernel) = SquaredEuclidean()\n@inline function kappa(\u03ba::LogKernel{T}, z::T) where {T}\n    logkernel(z, getvalue(\u03ba.alpha), getvalue(\u03ba.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, \u03b4 = defaulttol(a))\n     U, S, V = svd(a)\n     Sinv = inv.(hypot.(S, \u03b4))\n     return  V * Diagonal(Sinv) * U'\n end\n\n function posreginv(a::AbstractMatrix, \u03b4 = defaulttol(a))\n     # assumes a is positive definite (or close to)\n     D, V = eigen(Hermitian(a))\n     Dinv = inv.(hypot.(D, \u03b4))\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, \u03b4 = zero(eltype(A)))\n      n = LinearAlgebra.checksquare(A)\n      \u039b, U = eigen(Hermitian(A))\n      UdCU = U' * B * U\n      for j = 1:n\n          for i = 1:n\n              UdCU[i,j] /= sqrt((\u039b[i] + \u039b[j])^2 + \u03b4^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": "using IntelVectorMath, SpecialFunctions\nusing AcuteBenchmark\n\ncd(@__DIR__)\nrootPath = pwd()\n################################################################\n# Dimensions\noneArgDims = [10 20 50 100 200 500 700 1000 5000 10000]\n\ntwoArgDims = [10 20 50 100 200 500 700 1000 5000 10000; # arg1\n              10 20 50 100 200 500 700 1000 5000 10000] # arg2\n\n################################################################\n## Real Functions\n\ntypesReal=[Float32, Float64]\n\nconfigsRealBase = FunbArray([\n\n    # oneArgDims\n    Funb(acos, [(-1, 1)], typesReal, oneArgDims),\n    Funb(asin, [(-1, 1)], typesReal, oneArgDims),\n    Funb(atan, [(-50, 50)], typesReal, oneArgDims),\n    Funb(cos, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(sin, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(tan, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(acosh, [(1, 1000)], typesReal, oneArgDims),\n    Funb(asinh, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(atanh, [(-1, 1)], typesReal, oneArgDims),\n    Funb(cosh, [(0, 89.415985f0)], typesReal, oneArgDims),\n    Funb(sinh, [(-89.415985f0, 89.415985f0)], typesReal, oneArgDims),\n    Funb(tanh, [(-8.66434f0, 8.66434f0)], typesReal, oneArgDims),\n    Funb(cbrt, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(sqrt, [(0, 1000)], typesReal, oneArgDims),\n    Funb(exp, [(-88.72284f0, 88.72284f0)], typesReal, oneArgDims),\n    Funb(expm1, [(-88.72284f0, 88.72284f0)], typesReal, oneArgDims),\n    Funb(log, [(0, 1000)], typesReal, oneArgDims),\n    # Funb(log10, [(0, 1000)], typesReal, oneArgDims), # faulty\n    Funb(abs, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(abs2, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(ceil, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(floor, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(round, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(trunc, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(cis, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(SpecialFunctions.erf, [(-3.8325067f0, 3.8325067f0)], typesReal, oneArgDims),\n    Funb(SpecialFunctions.erfc, [(-3.7439213f0, 10.019834f0)], typesReal, oneArgDims),\n    Funb(SpecialFunctions.erfinv, [(-1, 1)], typesReal, oneArgDims),\n    Funb(SpecialFunctions.erfcinv, [(0, 2)], typesReal, oneArgDims),\n    # Funb(SpecialFunctions.lgamma, [(0, 1000)], typesReal, oneArgDims),\n    Funb(SpecialFunctions.gamma, [(0, 36)], typesReal, oneArgDims),\n\n    # twoArgDims\n    Funb(atan, [(-1, 1), (-1, 1)], typesReal, twoArgDims),\n    Funb(hypot, [(-1000, 1000), (-1000, 1000)], typesReal, twoArgDims),\n    # Funb(/, [(-1000, 1000), (-1000, 1000)], typesReal, twoArgDims),\n    # Funb(^, [(0, 100), (-5, 20)], typesReal, twoArgDims),\n])\n\nconfigsRealIVM = FunbArray([\n\n    # oneArgDims\n    Funb(IVM.acos, [(-1, 1)], typesReal, oneArgDims),\n    Funb(IVM.asin, [(-1, 1)], typesReal, oneArgDims),\n    Funb(IVM.atan, [(-50, 50)], typesReal, oneArgDims),\n    Funb(IVM.cos, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.sin, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.tan, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.acosh, [(1, 1000)], typesReal, oneArgDims),\n    Funb(IVM.asinh, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.atanh, [(-1, 1)], typesReal, oneArgDims),\n    Funb(IVM.cosh, [(0, 89.415985f0)], typesReal, oneArgDims),\n    Funb(IVM.sinh, [(-89.415985f0, 89.415985f0)], typesReal, oneArgDims),\n    Funb(IVM.tanh, [(-8.66434f0, 8.66434f0)], typesReal, oneArgDims),\n    Funb(IVM.cbrt, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.sqrt, [(0, 1000)], typesReal, oneArgDims),\n    Funb(IVM.exp, [(-88.72284f0, 88.72284f0)], typesReal, oneArgDims),\n    Funb(IVM.expm1, [(-88.72284f0, 88.72284f0)], typesReal, oneArgDims),\n    Funb(IVM.log, [(0, 1000)], typesReal, oneArgDims),\n    # Funb(IVM.log10, [(0, 1000)], typesReal, oneArgDims), # faulty\n    Funb(IVM.abs, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.abs2, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.ceil, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.floor, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.round, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.trunc, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.cis, [(-1000, 1000)], typesReal, oneArgDims),\n    Funb(IVM.erf, [(-3.8325067f0, 3.8325067f0)], typesReal, oneArgDims),\n    Funb(IVM.erfc, [(-3.7439213f0, 10.019834f0)], typesReal, oneArgDims),\n    Funb(IVM.erfinv, [(-1, 1)], typesReal, oneArgDims),\n    Funb(IVM.erfcinv, [(0, 2)], typesReal, oneArgDims),\n    # Funb(IVM.lgamma, [(0, 1000)], typesReal, oneArgDims), # faulty\n    Funb(IVM.gamma, [(0, 36)], typesReal, oneArgDims),\n\n    # twoArgDims\n    Funb(IVM.atan, [(-1, 1), (-1, 1)], typesReal, twoArgDims),\n    Funb(IVM.hypot, [(-1000, 1000), (-1000, 1000)], typesReal, twoArgDims),\n    # Funb(IVM.(/), [(-1000, 1000), (-1000, 1000)], typesReal, twoArgDims),\n    # Funb(IVM.(^), [(0, 100), (-5, 20)], typesReal, twoArgDims),\n])\n\n################################################################\n# Complex Functions\n\ntypesComplex=[Complex{Float32}, Complex{Float64}]\n\nconfigsComplexBase = FunbArray([\n    # oneArgDims\n    Funb(acos, [(-1, 1)], typesComplex, oneArgDims),\n    Funb(asin, [(-1, 1)], typesComplex, oneArgDims),\n    # Funb(atan, [(-50, 50)], typesComplex, oneArgDims),\n    # Funb(cos, [(-10, 10)], typesComplex, oneArgDims),\n    # Funb(sin, [(-10, 10)], typesComplex, oneArgDims),\n    # Funb(tan, [(-10, 10)], typesComplex, oneArgDims),\n    Funb(acosh, [(1, 1000)], typesComplex, oneArgDims),\n    Funb(asinh, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(atanh, [(-1, 1)], typesComplex, oneArgDims),\n    # Funb(cosh, [(0, 89.415985f0)], typesComplex, oneArgDims),\n    # Funb(sinh, [(-89.415985f0, 89.415985f0)], typesComplex, oneArgDims),\n    # Funb(tanh, [(-8.66434f0, 8.66434f0)], typesComplex, oneArgDims),\n    Funb(sqrt, [(0, 1000)], typesComplex, oneArgDims),\n    Funb(exp, [(-88.72284f0, 88.72284f0)], typesComplex, oneArgDims),\n    Funb(log, [(0, 1000)], typesComplex, oneArgDims),\n    # Funb(log10, [(0, 1000)], typesComplex, oneArgDims),\n    Funb(abs, [(-1000, 1000)], typesComplex, oneArgDims),\n    Funb(angle, [(-1000, 1000)], typesComplex, oneArgDims),\n    Funb(conj, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(cis, [(-1000, 1000)], typesComplex, oneArgDims),\n\n    # twoArgDims\n    # Funb(/, [(-1000, 1000), (-1000, 1000)], typesComplex, twoArgDims),\n    # Funb(^, [(0, 100), (-2, 10)], typesComplex, twoArgDims),\n\n    # missing?\n    ## oneArgDims\n\n    # Funb(cbrt, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(expm1, [(-88.72284f0, 88.72284f0)], typesComplex, oneArgDims),\n    # Funb(abs2, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(ceil, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(SpecialFunctions.erf, [(-3.8325067f0, 3.8325067f0)], typesComplex, oneArgDims),\n    # Funb(SpecialFunctions.erfc, [(-3.7439213f0, 10.019834f0)], typesComplex, oneArgDims),\n    # Funb(SpecialFunctions.erfinv, [(-1, 1)], typesComplex, oneArgDims),\n    # Funb(SpecialFunctions.erfcinv, [(0, 2)], typesComplex, oneArgDims),\n    # Funb(SpecialFunctions.lgamma, [(0, 1000)], typesComplex, oneArgDims),\n    # Funb(SpecialFunctions.gamma, [(0, 36)], typesComplex, oneArgDims),\n    # Funb(floor, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(round, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(trunc, [(-1000, 1000)], typesComplex, oneArgDims),\n\n    ## twoArgDims\n    # Funb(atan, [(-1, 1), (-1, 1)], typesComplex, twoArgDims),\n    # Funb(hypot, [(-1000, 1000), (-1000, 1000)], typesComplex, twoArgDims),\n])\n\nconfigsComplexIVM = FunbArray([\n    # oneArgDims\n    Funb(IVM.acos, [(-1, 1)], typesComplex, oneArgDims),\n    Funb(IVM.asin, [(-1, 1)], typesComplex, oneArgDims),\n    # Funb(IVM.atan, [(-50, 50)], typesComplex, oneArgDims),\n    # Funb(IVM.cos, [(-10, 10)], typesComplex, oneArgDims),\n    # Funb(IVM.sin, [(-10, 10)], typesComplex, oneArgDims),\n    # Funb(IVM.tan, [(-10, 10)], typesComplex, oneArgDims),\n    Funb(IVM.acosh, [(1, 1000)], typesComplex, oneArgDims),\n    Funb(IVM.asinh, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.atanh, [(-1, 1)], typesComplex, oneArgDims),\n    # Funb(IVM.cosh, [(0, 89.415985f0)], typesComplex, oneArgDims),\n    # Funb(IVM.sinh, [(-89.415985f0, 89.415985f0)], typesComplex, oneArgDims),\n    # Funb(IVM.tanh, [(-8.66434f0, 8.66434f0)], typesComplex, oneArgDims),\n    Funb(IVM.sqrt, [(0, 1000)], typesComplex, oneArgDims),\n    Funb(IVM.exp, [(-88.72284f0, 88.72284f0)], typesComplex, oneArgDims),\n    Funb(IVM.log, [(0, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.log10, [(0, 1000)], typesComplex, oneArgDims),\n    Funb(IVM.abs, [(-1000, 1000)], typesComplex, oneArgDims),\n    Funb(IVM.angle, [(-1000, 1000)], typesComplex, oneArgDims),\n    Funb(IVM.conj, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.cis, [(-1000, 1000)], typesComplex, oneArgDims),\n\n    # twoArgDims\n    # Funb(IVM.(/), [(-1000, 1000), (-1000, 1000)], typesComplex, twoArgDims),\n    # Funb(IVM.(^), [(0, 100), (-2, 10)], typesComplex, twoArgDims),\n\n    # missing?\n    ## oneArgDims\n\n    # Funb(IVM.cbrt, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.expm1, [(-88.72284f0, 88.72284f0)], typesComplex, oneArgDims),\n    # Funb(IVM.abs2, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.ceil, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.erf, [(-3.8325067f0, 3.8325067f0)], typesComplex, oneArgDims),\n    # Funb(IVM.erfc, [(-3.7439213f0, 10.019834f0)], typesComplex, oneArgDims),\n    # Funb(IVM.erfinv, [(-1, 1)], typesComplex, oneArgDims),\n    # Funb(IVM.erfcinv, [(0, 2)], typesComplex, oneArgDims),\n    # Funb(IVM.lgamma, [(0, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.gamma, [(0, 36)], typesComplex, oneArgDims),\n    # Funb(IVM.floor, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.round, [(-1000, 1000)], typesComplex, oneArgDims),\n    # Funb(IVM.trunc, [(-1000, 1000)], typesComplex, oneArgDims),\n\n    ## twoArgDims\n    # Funb(IVM.atan, [(-1, 1), (-1, 1)], typesComplex, twoArgDims),\n    # Funb(IVM.hypot, [(-1000, 1000), (-1000, 1000)], typesComplex, twoArgDims),\n])\n\n################################################################\n# Performing Benchmarks\n# Real\nprintln(\"\\nBenchmarking Base Real Functions\\n\")\nbenchmark!(configsRealBase)\n\nprintln(\"\\nBenchmarking IntelVectorMath Real Functions\\n\")\nbenchmark!(configsRealIVM)\n\ncd(joinpath(rootPath,\"Real\"))\n\nbar(configsRealBase => configsRealIVM, uniqueType = true, dimAnnotation = false, uniqueDim = true, configName =  \"Base\" => \"IntelVectorMath\")\n\ndimplot([configsRealBase,configsRealIVM],[\"Base\", \"IntelVectorMath\"])\n################################################################\n# Complex\nprintln(\"\\nBenchmarking Base Complex Functions\\n\")\nbenchmark!(configsComplexBase)\n\nprintln(\"\\nBenchmarking IntelVectorMath Complex Functions\\n\")\nbenchmark!(configsComplexIVM)\n\ncd(joinpath(rootPath,\"Complex\"))\n\nbar(configsComplexBase => configsComplexIVM, uniqueType = true, dimAnnotation = false, uniqueDim = true, configName = \"Base\" => \"IntelVectorMath\")\n\ndimplot([configsComplexBase,configsComplexIVM],[\"Base\", \"IntelVectorMath\"])\n", "meta": {"hexsha": "2c8d5c1d5d1b185a8e65ae6e1eab6f6e0d78ebef", "size": 11159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark/benchmark.jl", "max_stars_repo_name": "JuliaTagBot/IntelVectorMath.jl-1", "max_stars_repo_head_hexsha": "156dd92ef029c3af4c48a80b0bf3dcaf25a3d894", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-01-14T05:47:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T15:56:07.000Z", "max_issues_repo_path": "benchmark/benchmark.jl", "max_issues_repo_name": "JuliaTagBot/IntelVectorMath.jl-1", "max_issues_repo_head_hexsha": "156dd92ef029c3af4c48a80b0bf3dcaf25a3d894", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-01-10T21:08:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-05T17:03:03.000Z", "max_forks_repo_path": "benchmark/benchmark.jl", "max_forks_repo_name": "JuliaTagBot/IntelVectorMath.jl-1", "max_forks_repo_head_hexsha": "156dd92ef029c3af4c48a80b0bf3dcaf25a3d894", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-01-11T23:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:26:04.000Z", "avg_line_length": 48.099137931, "max_line_length": 146, "alphanum_fraction": 0.6264002151, "num_tokens": 4143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7945998613938628}}
{"text": "doc\"\"\"\n    Pareto(\u03b1,\u03b8)\n\nThe *Pareto distribution* with shape `\u03b1` and scale `\u03b8` 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    \u03b1::Float64\n    \u03b8::Float64\n\n    function Pareto(\u03b1::Real, \u03b8::Real)\n        @check_args(Pareto, \u03b1 > zero(\u03b1) && \u03b8 > zero(\u03b8))\n        new(\u03b1, \u03b8)\n    end\n    Pareto(\u03b1::Real) = Pareto(\u03b1, 1.0)\n    Pareto() = new(1.0, 1.0)\nend\n\n@distr_support Pareto d.\u03b8 Inf\n\n\n#### Parameters\n\nshape(d::Pareto) = d.\u03b1\nscale(d::Pareto) = d.\u03b8\n\nparams(d::Pareto) = (d.\u03b1, d.\u03b8)\n\n\n#### Statistics\n\nmean(d::Pareto) = ((\u03b1, \u03b8) = params(d); \u03b1 > 1.0 ? \u03b1 * \u03b8 / (\u03b1 - 1.0) : Inf)\nmedian(d::Pareto) = ((\u03b1, \u03b8) = params(d); \u03b8 * 2.0 ^ (1.0 / \u03b1))\nmode(d::Pareto) = d.\u03b8\n\nfunction var(d::Pareto)\n    (\u03b1, \u03b8) = params(d)\n    \u03b1 > 2.0 ? (\u03b8^2 * \u03b1) / ((\u03b1 - 1.0)^2 * (\u03b1 - 2.0)) : Inf\nend\n\nfunction skewness(d::Pareto)\n    \u03b1 = shape(d)\n    \u03b1 > 3.0 ? ((2.0 * (1.0 + \u03b1)) / (\u03b1 - 3.0)) * sqrt((\u03b1 - 2.0) / \u03b1) : NaN\nend\n\nfunction kurtosis(d::Pareto)\n    \u03b1 = shape(d)\n    \u03b1 > 4.0 ? (6.0 * (\u03b1^3 + \u03b1^2 - 6.0 * \u03b1 - 2.0)) / (\u03b1 * (\u03b1 - 3.0) * (\u03b1 - 4.0)) : NaN\nend\n\nentropy(d::Pareto) = ((\u03b1, \u03b8) = params(d); log(\u03b8 / \u03b1) + 1.0 / \u03b1 + 1.0)\n\n\n#### Evaluation\n\nfunction pdf(d::Pareto, x::Float64)\n    (\u03b1, \u03b8) = params(d)\n    x >= \u03b8 ? \u03b1 * (\u03b8 / x)^\u03b1 * (1.0 / x) : 0.0\nend\n\nfunction logpdf(d::Pareto, x::Float64)\n    (\u03b1, \u03b8) = params(d)\n    x >= \u03b8 ? log(\u03b1) + \u03b1 * log(\u03b8) - (\u03b1 + 1.0) * log(x) : -Inf\nend\n\nfunction ccdf(d::Pareto, x::Float64)\n    (\u03b1, \u03b8) = params(d)\n    x >= \u03b8 ? (\u03b8 / x)^\u03b1 : 1.0\nend\n\ncdf(d::Pareto, x::Float64) = 1.0 - ccdf(d, x)\n\nfunction logccdf(d::Pareto, x::Float64)\n    (\u03b1, \u03b8) = params(d)\n    x >= \u03b8 ? \u03b1 * log(\u03b8 / x) : 0.0\nend\n\nlogcdf(d::Pareto, x::Float64) = log1p(-ccdf(d, x))\n\ncquantile(d::Pareto, p::Float64) = d.\u03b8 / p^(1.0 / d.\u03b1)\nquantile(d::Pareto, p::Float64) = cquantile(d, 1.0 - p)\n\n\n#### Sampling\n\nrand(d::Pareto) = d.\u03b8 * exp(randexp() / d.\u03b1)\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    \u03b8 = minimum(x)\n\n    n = length(x)\n    l\u03b8 = log(\u03b8)\n    temp1 = zero(T)\n    for i=1:n\n        temp1 += log(x[i]) - l\u03b8\n    end\n    \u03b1 = n/temp1\n\n    return Pareto(\u03b1, \u03b8)\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 `\u03f5\u1d62\u2c7c\u2096 = (i-j) (j-k) (k-i) / 2`\n\n# Examples\n```julia\njulia> \u03b5 = LeviCivita(Sym)\n3\u00d73\u00d73 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    \ud835\udc1e(i::Integer, dim::Int = 3, T::Type{<:Number} = Sym)\n\nVector of the canonical basis\n\n# Examples\n```julia\njulia> \ud835\udc1e(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\u00d73 Tensor{2, 3, Sym, 9}:\n 1  0  0\n 0  1  0\n 0  0  1\n``` \n\"\"\"\n\ud835\udc1e(::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, \u212c = init_cartesian() ; x, y, z = coords ; \ud835\udc1e\u2081, \ud835\udc1e\u2082, \ud835\udc1e\u2083 = vectors ;\n``` \n\"\"\"\ninit_cartesian(coords = symbols(\"x y z\", real = true)) = Tuple(coords),\nntuple(i -> \ud835\udc1e(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    \ud835\udc1e\u1d56(i::Integer, \u03b8::T = zero(Sym); canonical = false)\n\nVector of the polar basis\n\n# Examples\n```julia\njulia> \u03b8 = symbols(\"\u03b8\", real = true) ;\n\njulia> \ud835\udc1e\u1d56(1, \u03b8)\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\u00d72 Tensor{2, 2, Sym, 4}:\n cos(\u03b8)  -sin(\u03b8)\n sin(\u03b8)   cos(\u03b8)\n``` \n\"\"\"\n\ud835\udc1e\u1d56(::Val{1}, \u03b8::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{2}([cos(\u03b8), sin(\u03b8)])) :\n    Tens(Vec{2}([one(T), zero(T)]), Basis(\u03b8))\n\ud835\udc1e\u1d56(::Val{2}, \u03b8::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{2}([-sin(\u03b8), cos(\u03b8)])) :\n    Tens(Vec{2}([zero(T), one(T)]), Basis(\u03b8))\n\n\"\"\"\n    init_polar(coords = (symbols(\"r\", positive = true), symbols(\"\u03b8\", real = true)); canonical = false)\n\nReturns the coordinates, base vectors and basis of the polar basis\n\n# Examples\n```julia\njulia> coords, vectors, \u212c\u1d56 = init_polar() ; r, \u03b8 = coords ; \ud835\udc1e\u02b3, \ud835\udc1e\u1dbf = vectors ;\n``` \n\"\"\"\ninit_polar(\n    coords = (symbols(\"r\", positive = true), symbols(\"\u03b8\", real = true));\n    canonical = false,\n) = Tuple(coords),\nntuple(i -> \ud835\udc1e\u1d56(Val(i), coords[2]; canonical = canonical), 2),\nBasis(coords[2])\n\n\"\"\"\n    \ud835\udc1e\u1d9c(i::Integer, \u03b8::T = zero(Sym); canonical = false)\n\nVector of the cylindrical basis\n\n# Examples\n```julia\njulia> \u03b8 = symbols(\"\u03b8\", real = true) ;\n\njulia> \ud835\udc1e\u1d9c(1, \u03b8)\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\u00d73 Tensor{2, 3, Sym, 9}:\n cos(\u03b8)  -sin(\u03b8)  0\n sin(\u03b8)   cos(\u03b8)  0\n      0        0  1\n``` \n\"\"\"\n\ud835\udc1e\u1d9c(::Val{1}, \u03b8::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{3}([cos(\u03b8), sin(\u03b8), zero(T)])) :\n    Tens(Vec{3}([one(T), zero(T), zero(T)]), CylindricalBasis(\u03b8))\n\ud835\udc1e\u1d9c(::Val{2}, \u03b8::T = zero(Sym); canonical = false) where {T<:Number} =\n    canonical ? Tens(Vec{3}([-sin(\u03b8), cos(\u03b8), zero(T)])) :\n    Tens(Vec{3}([zero(T), one(T), zero(T)]), CylindricalBasis(\u03b8))\n\ud835\udc1e\u1d9c(::Val{3}, \u03b8::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(\u03b8))\n\n\"\"\"\n    init_cylindrical(coords = (symbols(\"r\", positive = true), symbols(\"\u03b8\", 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, \u212c\u1d9c = init_cylindrical() ; r, \u03b8, z = coords ; \ud835\udc1e\u02b3, \ud835\udc1e\u1dbf, \ud835\udc1e\u1dbb = vectors ;\n``` \n\"\"\"\ninit_cylindrical(\n    coords = (\n        symbols(\"r\", positive = true),\n        symbols(\"\u03b8\", real = true),\n        symbols(\"z\", real = true),\n    );\n    canonical = false,\n) = Tuple(coords),\nntuple(i -> \ud835\udc1e\u1d9c(Val(i), coords[2]; canonical = canonical), 3),\nCylindricalBasis(coords[2])\n\n\"\"\"\n    \ud835\udc1e\u02e2(i::Integer, \u03b8::T = zero(Sym), \u03d5::T = zero(Sym), \u03c8::T = zero(Sym); canonical = false)\n\nVector of the basis rotated with the 3 Euler angles `\u03b8, \u03d5, \u03c8` (spherical if `\u03c8=0`)\n\n# Examples\n```julia\njulia> \u03b8, \u03d5, \u03c8 = symbols(\"\u03b8, \u03d5, \u03c8\", 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\u00d73 Tensor{2, 3, Sym, 9}:\n -sin(\u03c8)\u22c5sin(\u03d5) + cos(\u03b8)\u22c5cos(\u03c8)\u22c5cos(\u03d5)  -sin(\u03c8)\u22c5cos(\u03b8)\u22c5cos(\u03d5) - sin(\u03d5)\u22c5cos(\u03c8)  sin(\u03b8)\u22c5cos(\u03d5)\n  sin(\u03c8)\u22c5cos(\u03d5) + sin(\u03d5)\u22c5cos(\u03b8)\u22c5cos(\u03c8)  -sin(\u03c8)\u22c5sin(\u03d5)\u22c5cos(\u03b8) + cos(\u03c8)\u22c5cos(\u03d5)  sin(\u03b8)\u22c5sin(\u03d5)\n                        -sin(\u03b8)\u22c5cos(\u03c8)                          sin(\u03b8)\u22c5sin(\u03c8)         cos(\u03b8)\n``` \n\"\"\"\nfunction \ud835\udc1e\u02e2(\n    ::Val{1},\n    \u03b8::T1 = 0,\n    \u03d5::T2 = 0,\n    \u03c8::T3 = 0;\n    canonical = false,\n) where {T1<:Number,T2<:Number,T3<:Number}\n    if canonical\n        return Tens(\n            Vec{3}([\n                -sin(\u03c8) * sin(\u03d5) + cos(\u03b8) * cos(\u03c8) * cos(\u03d5),\n                sin(\u03c8) * cos(\u03d5) + sin(\u03d5) * cos(\u03b8) * cos(\u03c8),\n                -sin(\u03b8) * cos(\u03c8),\n            ]),\n        )\n    else\n        T = promote_type(T1, T2, T3)\n        return Tens(Vec{3}([one(T), zero(T), zero(T)]), Basis(\u03b8, \u03d5, \u03c8))\n    end\nend\nfunction \ud835\udc1e\u02e2(\n    ::Val{2},\n    \u03b8::T1 = 0,\n    \u03d5::T2 = 0,\n    \u03c8::T3 = 0;\n    canonical = false,\n) where {T1<:Number,T2<:Number,T3<:Number}\n    if canonical\n        return Tens(\n            Vec{3}([\n                -sin(\u03c8) * cos(\u03b8) * cos(\u03d5) - sin(\u03d5) * cos(\u03c8),\n                -sin(\u03c8) * sin(\u03d5) * cos(\u03b8) + cos(\u03c8) * cos(\u03d5),\n                sin(\u03b8) * sin(\u03c8),\n            ]),\n        )\n    else\n        T = promote_type(T1, T2, T3)\n        return Tens(Vec{3}([zero(T), one(T), zero(T)]), Basis(\u03b8, \u03d5, \u03c8))\n    end\nend\nfunction \ud835\udc1e\u02e2(\n    ::Val{3},\n    \u03b8::T1 = 0,\n    \u03d5::T2 = 0,\n    \u03c8::T3 = 0;\n    canonical = false,\n) where {T1<:Number,T2<:Number,T3<:Number}\n    if canonical\n        return Tens(Vec{3}([sin(\u03b8) * cos(\u03d5), sin(\u03b8) * sin(\u03d5), cos(\u03b8)]))\n    else\n        T = promote_type(T1, T2, T3)\n        return Tens(Vec{3}([zero(T), zero(T), one(T)]), Basis(\u03b8, \u03d5, \u03c8))\n    end\nend\n\nfor eb in (:\ud835\udc1e, :\ud835\udc1e\u1d56, :\ud835\udc1e\u1d9c, :\ud835\udc1e\u02e2)\n    @eval $eb(i::Integer, args...; kwargs...) = $eb(Val(i), args...; kwargs...)\nend\n\n\"\"\"\n    init_spherical(coords = (symbols(\"\u03b8\", real = true), symbols(\"\u03d5\", 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 `\ud835\udc1e\u1dbf, \ud835\udc1e\u1d60, \ud835\udc1e\u02b3` so that\nthe basis coincides with the canonical one when the angles are null and in consistency\nthe coordinates are ordered as `\u03b8, \u03d5, r`.\n\n# Examples\n```julia\njulia> coords, vectors, \u212c\u02e2 = init_spherical() ; \u03b8, \u03d5, r = coords ; \ud835\udc1e\u1dbf, \ud835\udc1e\u1d60, \ud835\udc1e\u02b3  = vectors ;\n``` \n\"\"\"\ninit_spherical(\n    coords = (\n        symbols(\"\u03b8\", real = true),\n        symbols(\"\u03d5\", real = true),\n        symbols(\"r\", positive = true),\n    );\n    canonical = false,\n) = Tuple(coords),\nntuple(i -> \ud835\udc1e\u02e2(Val(i), coords[1:2]...; canonical = canonical), 3),\nSphericalBasis(coords[1:2]...)\n\n\"\"\"\n    init_rotated(coords = symbols(\"\u03b8 \u03d5 \u03c8\", 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 `\u211d\u00b3`\n\n# Examples\n```julia\njulia> angles, vectors, \u212c\u02b3 = init_rotated() ; \u03b8, \u03d5, \u03c8 = angles ; \ud835\udc1e\u1dbf, \ud835\udc1e\u1d60, \ud835\udc1e\u02b3 = vectors ;\n```\n\"\"\"\ninit_rotated(angles = symbols(\"\u03b8 \u03d5 \u03c8\", real = true); canonical = false) = Tuple(angles),\nntuple(i -> \ud835\udc1e\u02e2(Val(i), angles...; canonical = canonical), 3),\nBasis(angles...)\n\n\"\"\"\n    rot3(\u03b8, \u03d5 = 0, \u03c8 = 0)\n\nReturns a rotation matrix with respect to the 3 Euler angles `\u03b8, \u03d5, \u03c8`\n\n# Examples\n```julia\njulia> c\u03b8, c\u03d5, c\u03c8, s\u03b8, s\u03d5, s\u03c8 = symbols(\"c\u03b8 c\u03d5 c\u03c8 s\u03b8 s\u03d5 s\u03c8\", real = true) ;\n\njulia> d = Dict(cos(\u03b8) => c\u03b8, cos(\u03d5) => c\u03d5, cos(\u03c8) => c\u03c8, sin(\u03b8) => s\u03b8, sin(\u03d5) => s\u03d5, sin(\u03c8) => s\u03c8) ;\n\njulia> subs.(rot3(\u03b8, \u03d5, \u03c8),d...)\n3\u00d73 StaticArrays.SMatrix{3, 3, Sym, 9} with indices SOneTo(3)\u00d7SOneTo(3):\n c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5  -c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5  c\u03d5\u22c5s\u03b8\n c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8  -c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5  s\u03b8\u22c5s\u03d5\n           -c\u03c8\u22c5s\u03b8              s\u03b8\u22c5s\u03c8     c\u03b8\n```\n\"\"\"\nrot3(\u03b8, \u03d5 = 0, \u03c8 = 0) = RotZYZ(\u03d5, \u03b8, \u03c8)\n\n\"\"\"\n    rot2(\u03b8)\n\nReturns a 2D rotation matrix with respect to the angle `\u03b8`\n\n# Examples\n```julia\njulia> rot2(\u03b8)\n2\u00d72 Tensor{2, 2, Sym, 4}:\n cos(\u03b8)  -sin(\u03b8)\n sin(\u03b8)   cos(\u03b8)\n```\n\"\"\"\nrot2(\u03b8) = Tensor{2,2}((cos(\u03b8), sin(\u03b8), -sin(\u03b8), cos(\u03b8)))\n\n\n\"\"\"\n    rot6(\u03b8, \u03d5 = 0, \u03c8 = 0)\n\nReturns a rotation matrix with respect to the 3 Euler angles `\u03b8, \u03d5, \u03c8`\n\n# Examples\n```julia\njulia> c\u03b8, c\u03d5, c\u03c8, s\u03b8, s\u03d5, s\u03c8 = symbols(\"c\u03b8 c\u03d5 c\u03c8 s\u03b8 s\u03d5 s\u03c8\", real = true) ;\n\njulia> d = Dict(cos(\u03b8) => c\u03b8, cos(\u03d5) => c\u03d5, cos(\u03c8) => c\u03c8, sin(\u03b8) => s\u03b8, sin(\u03d5) => s\u03d5, sin(\u03c8) => s\u03c8) ;\n\njulia> R = Tens(subs.(rot3(\u03b8, \u03d5, \u03c8),d...))\nTens.TensCanonical{2, 3, Sym, Tensor{2, 3, Sym, 9}}\n# data: 3\u00d73 Tensor{2, 3, Sym, 9}:\n c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5  -c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5  c\u03d5\u22c5s\u03b8\n c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8  -c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5  s\u03b8\u22c5s\u03d5\n           -c\u03c8\u22c5s\u03b8              s\u03b8\u22c5s\u03c8     c\u03b8\n# var: (:cont, :cont)\n# basis: 3\u00d73 Tens.LazyIdentity{3, Sym}:\n 1  0  0\n 0  1  0\n 0  0  1\n\njulia> RR = R \u22a0\u02e2 R\nTens.TensCanonical{4, 3, Sym, SymmetricTensor{4, 3, Sym, 36}}\n# data: 6\u00d76 Matrix{Sym}:\n                          (c\u03b8*c\u03c8*c\u03d5 - s\u03c8*s\u03d5)^2                            (-c\u03b8*c\u03d5*s\u03c8 - c\u03c8*s\u03d5)^2           c\u03d5^2*s\u03b8^2                      \u221a2\u22c5c\u03d5\u22c5s\u03b8\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)                     \u221a2\u22c5c\u03d5\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)                                   \u221a2\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)\n                          (c\u03b8*c\u03c8*s\u03d5 + c\u03d5*s\u03c8)^2                            (-c\u03b8*s\u03c8*s\u03d5 + c\u03c8*c\u03d5)^2           s\u03b8^2*s\u03d5^2                      \u221a2\u22c5s\u03b8\u22c5s\u03d5\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)                     \u221a2\u22c5s\u03b8\u22c5s\u03d5\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)                                   \u221a2\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)\n                                     c\u03c8^2*s\u03b8^2                                        s\u03b8^2*s\u03c8^2                c\u03b8^2                                       \u221a2\u22c5c\u03b8\u22c5s\u03b8\u22c5s\u03c8                                    -\u221a2\u22c5c\u03b8\u22c5c\u03c8\u22c5s\u03b8                                                              -sqrt(2)*c\u03c8*s\u03b8^2*s\u03c8\n             -\u221a2\u22c5c\u03c8\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)                \u221a2\u22c5s\u03b8\u22c5s\u03c8\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)    \u221a2\u22c5c\u03b8\u22c5s\u03b8\u22c5s\u03d5                    c\u03b8*(-c\u03b8*s\u03c8*s\u03d5 + c\u03c8*c\u03d5) + s\u03b8^2*s\u03c8*s\u03d5                   c\u03b8*(c\u03b8*c\u03c8*s\u03d5 + c\u03d5*s\u03c8) - c\u03c8*s\u03b8^2*s\u03d5                            -c\u03c8\u22c5s\u03b8\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5) + s\u03b8\u22c5s\u03c8\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)\n             -\u221a2\u22c5c\u03c8\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)                \u221a2\u22c5s\u03b8\u22c5s\u03c8\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)    \u221a2\u22c5c\u03b8\u22c5c\u03d5\u22c5s\u03b8                    c\u03b8*(-c\u03b8*c\u03d5*s\u03c8 - c\u03c8*s\u03d5) + c\u03d5*s\u03b8^2*s\u03c8                   c\u03b8*(c\u03b8*c\u03c8*c\u03d5 - s\u03c8*s\u03d5) - c\u03c8*c\u03d5*s\u03b8^2                            -c\u03c8\u22c5s\u03b8\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5) + s\u03b8\u22c5s\u03c8\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)\n \u221a2\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)  \u221a2\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)  sqrt(2)*c\u03d5*s\u03b8^2*s\u03d5  c\u03d5\u22c5s\u03b8\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5) + s\u03b8\u22c5s\u03d5\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)  c\u03d5\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8) + s\u03b8\u22c5s\u03d5\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)  (c\u03b8*c\u03c8*c\u03d5 - s\u03c8*s\u03d5)*(-c\u03b8*s\u03c8*s\u03d5 + c\u03c8*c\u03d5) + (c\u03b8*c\u03c8*s\u03d5 + c\u03d5*s\u03c8)*(-c\u03b8*c\u03d5*s\u03c8 - c\u03c8*s\u03d5)\n# var: (:cont, :cont, :cont, :cont)\n# basis: 3\u00d73 Tens.LazyIdentity{3, Sym}:\n 1  0  0\n 0  1  0\n 0  0  1\n\njulia> R6 = invKM(subs.(KM(rot6(\u03b8, \u03d5, \u03c8)),d...))\nTens.TensCanonical{4, 3, Sym, SymmetricTensor{4, 3, Sym, 36}}\n# data: 6\u00d76 Matrix{Sym}:\n                          (c\u03b8*c\u03c8*c\u03d5 - s\u03c8*s\u03d5)^2                            (-c\u03b8*c\u03d5*s\u03c8 - c\u03c8*s\u03d5)^2           c\u03d5^2*s\u03b8^2                      \u221a2\u22c5c\u03d5\u22c5s\u03b8\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)                     \u221a2\u22c5c\u03d5\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)                                   \u221a2\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)\n                          (c\u03b8*c\u03c8*s\u03d5 + c\u03d5*s\u03c8)^2                            (-c\u03b8*s\u03c8*s\u03d5 + c\u03c8*c\u03d5)^2           s\u03b8^2*s\u03d5^2                      \u221a2\u22c5s\u03b8\u22c5s\u03d5\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)                     \u221a2\u22c5s\u03b8\u22c5s\u03d5\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)                                   \u221a2\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)\n                                     c\u03c8^2*s\u03b8^2                                        s\u03b8^2*s\u03c8^2                c\u03b8^2                                       \u221a2\u22c5c\u03b8\u22c5s\u03b8\u22c5s\u03c8                                    -\u221a2\u22c5c\u03b8\u22c5c\u03c8\u22c5s\u03b8                                                              -sqrt(2)*c\u03c8*s\u03b8^2*s\u03c8\n             -\u221a2\u22c5c\u03c8\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)                \u221a2\u22c5s\u03b8\u22c5s\u03c8\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)    \u221a2\u22c5c\u03b8\u22c5s\u03b8\u22c5s\u03d5                    c\u03b8*(-c\u03b8*s\u03c8*s\u03d5 + c\u03c8*c\u03d5) + s\u03b8^2*s\u03c8*s\u03d5                   c\u03b8*(c\u03b8*c\u03c8*s\u03d5 + c\u03d5*s\u03c8) - c\u03c8*s\u03b8^2*s\u03d5                            -c\u03c8\u22c5s\u03b8\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5) + s\u03b8\u22c5s\u03c8\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)\n             -\u221a2\u22c5c\u03c8\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)                \u221a2\u22c5s\u03b8\u22c5s\u03c8\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)    \u221a2\u22c5c\u03b8\u22c5c\u03d5\u22c5s\u03b8                    c\u03b8*(-c\u03b8*c\u03d5*s\u03c8 - c\u03c8*s\u03d5) + c\u03d5*s\u03b8^2*s\u03c8                   c\u03b8*(c\u03b8*c\u03c8*c\u03d5 - s\u03c8*s\u03d5) - c\u03c8*c\u03d5*s\u03b8^2                            -c\u03c8\u22c5s\u03b8\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5) + s\u03b8\u22c5s\u03c8\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)\n \u221a2\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8)  \u221a2\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5)  sqrt(2)*cde Liv Lehn \u03d5*s\u03b8^2*s\u03d5  c\u03d5\u22c5s\u03b8\u22c5(-c\u03b8\u22c5s\u03c8\u22c5s\u03d5 + c\u03c8\u22c5c\u03d5) + s\u03b8\u22c5s\u03d5\u22c5(-c\u03b8\u22c5c\u03d5\u22c5s\u03c8 - c\u03c8\u22c5s\u03d5)  c\u03d5\u22c5s\u03b8\u22c5(c\u03b8\u22c5c\u03c8\u22c5s\u03d5 + c\u03d5\u22c5s\u03c8) + s\u03b8\u22c5s\u03d5\u22c5(c\u03b8\u22c5c\u03c8\u22c5c\u03d5 - s\u03c8\u22c5s\u03d5)  (c\u03b8*c\u03c8*c\u03d5 - s\u03c8*s\u03d5)*(-c\u03b8*s\u03c8*s\u03d5 + c\u03c8*c\u03d5) + (c\u03b8*c\u03c8*s\u03d5 + c\u03d5*s\u03c8)*(-c\u03b8*c\u03d5*s\u03c8 - c\u03c8*s\u03d5)\n# var: (:cont, :cont, :cont, :cont)\n# basis: 3\u00d73 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(\u03b8, \u03d5 = 0, \u03c8 = 0)\n    R = TensCanonical(rot3(\u03b8, \u03d5, \u03c8))\n    return sboxtimes(R, R)\nend\n\nexport LeviCivita\nexport \ud835\udc1e, \ud835\udc1e\u1d56, \ud835\udc1e\u1d9c, \ud835\udc1e\u02e2\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\u03c0``.\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": "function ACQR_bench(bench,nt,seed=1)\n\t#\n\t# benchmark models to test the functions\n\t#\n\t\n\t# random seed for the simulations\n\tsrand(seed)\n    \n\tif bench==1\n\t\t# \n\t\tA = 0.6\n\t\tC = 1\n\t\tQ = 2\n\t\tR = 4\n\t\t\n\t\tv = sqrt(R)*randn(nt)\n\t\tw = sqrt(Q)*randn(nt)\n\t\t\n\t\tx = zeros(nt)\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 + v\n\t\t\n\t\tsalida = y,A,C,Q,R\n\t\t\n\telseif bench==2\n\t\t#\n\t\t# Based on: \n\t\t# \"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\tC = [0.7831 0.5351 0.9701]\n\t\tR = 6.0\n\t\tQ = [3 0.5 0.2;0.5 2 0.3;0.2 0.3 1]\n\t\tU = chol(Q)\n        \n\t\tv = sqrt(R)*randn(1,nt)\n\t\tns = size(A,1)\n\t\tw = U'*randn(ns,nt)\n        \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 + v\n        \n\t\tsalida = y,A,C,Q,R\n\t\t  \n\tend\n    \n\treturn salida\n    \nend\n", "meta": {"hexsha": "03eea935e7c4f420609aa48ca3eecc888ff7edf9", "size": 879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ACQR/ACQR_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/ACQR/ACQR_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/ACQR/ACQR_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": 15.4210526316, "max_line_length": 48, "alphanum_fraction": 0.4880546075, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7945301756444342}}
{"text": "# Atkinson.jl\n\n\n###### atkinson #####\n\"\"\"\n    atkinson(v, \u03f5)\n\nCompute the Atkinson Index of a vector `v` at a specified inequality \naversion parameter `\u03f5`.\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}, \u03f5::Real)::Float64\n\n    \u03f5 >= 0 ? nothing : throw(ArgumentError(\"`\u03f5` must be larger or equal than 0\"))\n\n    if \u03f5 == 1\n        v = v[v .!= 0]\n        return 1 - (exp.(mean(log.(v)))/mean(v))\n    elseif \u03f5 < 1\n        return 1 - mean( (v./mean(v)).^(1-\u03f5) ).^(1/(1-\u03f5))\n    else\n        v = v[v .!= 0]\n        return 1 - mean( (v./mean(v)).^(1-\u03f5) ).^(1/(1-\u03f5))\n    end \nend\n\n\n###### weighted atkinson #####\n\"\"\"\n    atkinson(v, w, \u03f5)\n\nCompute the weighted Atkinson Index of a vector `v` at a specified inequality \naversion parameter `\u03f5`, 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}, \u03f5::Real)::Float64\n\n    \u03f5 >= 0 ? nothing : throw(ArgumentError(\"`\u03f5` 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 \u03f5 == 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 \u03f5 < 1\n        return 1-(sum(((v/sum(v.* w)).^(1-\u03f5)).*w)).^(1/(1-\u03f5))\n    else \n        w = w[v .!= 0]\n        v = v[v .!= 0]\n        \n        return 1-(sum(((v/sum(v.* w)).^(1-\u03f5)).*w)).^(1/(1-\u03f5))\n    end\nend\n\n\n\n\nfunction atkinson(v::AbstractVector{<:Real}, w::AbstractWeights, \u03f5::Real)::Float64\n\n    \u03f5 >= 0 ? nothing : throw(ArgumentError(\"`\u03f5` 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 \u03f5 == 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 \u03f5 < 1\n        return 1-(sum(((v/sum(v.* w)).^(1-\u03f5)).*w)).^(1/(1-\u03f5))\n    else \n        w = w[v .!= 0]\n        v = v[v .!= 0]\n        \n        return 1-(sum(((v/sum(v.* w)).^(1-\u03f5)).*w)).^(1/(1-\u03f5))\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 '\u03f5'. See also [`atkinson`](@atkinson)\n\"\"\"\nwatkinson(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, \u03f5::Real) = atkinson(v, w, \u03f5)\n\nwatkinson(v::AbstractVector{<:Real}, w::AbstractWeights, \u03f5::Real) = atkinson(v, w, \u03f5)", "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] == -\u221e ? popfirst!(vLo) : pushfirst!(vHi, -\u221e)\n    vHi[end] == \u221e ? pop!(vHi) : push!(vLo, \u221e)\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 \u03b1\nfunction bisect( x :: IntervalU, \u03b1 = 0)\n\n    v = deepcopy(x.v)\n\n    \u03b1In = \u03b1 .\u2208 v\n    these = findall(\u03b1In .== 1)\n\n    if isempty(these); return x ; end\n\n    this = popat!(v, these[1])\n\n    \u03b2 = (\u03b1 - this.lo) /(this.hi - this.lo)\n\n    bs = bisect(this, \u03b2)\n\n    new = IntervalU(v \u222a bs[1] \u222a 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 \u2282(x :: IntervalU, y :: IntervalU)\n    issubs = [xv .\u2282 y.v for xv in x.v]\n    return all(any.(issubs))\nend\n\nfunction \u2282(x :: Interval, y :: IntervalU)\n    if length(y.v) == 1; return x \u2282 y; end\n    issubs = x .\u2286 y.v\n    return any(issubs)\nend\n\nfunction \u2282( x::IntervalU, y :: Interval)\n    issubs = x.v .\u2282 y\n    return all(issubs)\nend\n\nfunction \u2286(x :: IntervalU, y :: IntervalU)\n    issubs = [xv .\u2286 y.v for xv in x.v]\n    return all(any.(issubs))\nend\n\nfunction \u2286(x :: Interval, y :: IntervalU)\n    issubs = x .\u2286 y.v\n    return any(issubs)\nend\n\nfunction \u2286( x::IntervalU, y :: Interval)\n    issubs = x.v .\u2286 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\u0304)\n    return v\u0304[:,1] ./ v\u0304[:,2];\nend\n\nfunction f2(v\u0304)\n    return exp( v\u0304[:,3] - v\u0304[:,4] );\nend\n\nfunction f3(v\u0304)\n    logs = Float64[];\n    for vv in v\u0304[:,5]\n        push!(logs,log(vv));\n    end\n    return ( v\u0304[:,1]./v\u0304[:,2] + v\u0304[:,3]./v\u0304[:,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\u03041);\nf2N1 = f2(v\u03041);\nf3N1 = f3(v\u03041);\n\nf1N2 = f1(v\u03042);\nf2N2 = f2(v\u03042);\nf3N2 = f3(v\u03042);\n\n# Find standard deviations\nprintln(\"\\n\\tCalculating standard deviations of the functions\");\n\u03c3\u0302truef1N1 = std(f1N1);\n\u03c3\u0302truef2N1 = std(f2N1);\n\u03c3\u0302truef3N1 = std(f3N1);\n\n\u03c3\u0302truef1N2 = std(f1N2);\n\u03c3\u0302truef2N2 = std(f2N2);\n\u03c3\u0302truef3N2 = 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": "@testset \"Testing quadsums.jl\" begin\n    rough_kwargs = Dict(:atol => 1e-10, :rtol => 1e-10)\n    \n    @testset \"test simple var sum\" begin\n        beta = .95\n        A = 1.\n        C = 0.\n        H = 1.\n        x0 = 1.\n\n        val = var_quadratic_sum(A, C, H, beta, x0)\n\n        @test isapprox(val, 20.0; rough_kwargs...)\n    end\n\n    @testset \"test identity var sum\" begin\n        beta = .95\n        A = eye(3)\n        C = zeros(3, 3)\n        H = eye(3)\n        x0 = ones(3)\n\n        val = var_quadratic_sum(A, C, H, beta, x0)\n\n        @test isapprox(val, 60.0; rough_kwargs...)\n    end\n\nend  # facts\n", "meta": {"hexsha": "67c60aeb171682bef34556ca71627ede351ef4ca", "size": 603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_quadsum.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-27T14:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-27T14:34:24.000Z", "max_issues_repo_path": "test/test_quadsum.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": "test/test_quadsum.jl", "max_forks_repo_name": "ranjanan/QuantEcon.jl", "max_forks_repo_head_hexsha": "fe2be6b95b517414b810089c49f295746d93f3eb", "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": 20.7931034483, "max_line_length": 55, "alphanum_fraction": 0.4925373134, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7945301586802299}}
{"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\u03b1, \u03b2, \u03bb = equioscillation!(f, x, supp_pt, clamp)\nnew_r = RationalFunc(\u03b1, \u03b2, supp_pt)\nfigure(4)\nplot(S, f.(S) - new_r.(S),\n     [-1.0, 1.0, NaN, -1.0, 1.0], [\u03bb, \u03bb, NaN, -\u03bb, -\u03bb], \":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": "# Testing precomposition by nonlinear operator\n\nb = randn(10)\ng = ProximalOperators.SqrNormL2(3.0)\nG = AffineAdd(AbstractOperators.Sigmoid((10,), 1.0),b,false)\nf = StructuredOptimization.PrecomposeNonlinear(g, G)\n\nx = randn(10)\n\ngrad_f_x, f_x = ProximalOperators.gradient(f, x)\n\n@test size(grad_f_x) == size(x)\n@test abs(f_x - 3.0/2 * norm(1.0 ./ (1.0 .+ exp.(-x)) - b)^2) <= 1e-10\nexpx = exp.(x)\nexpmx = 1.0./expx\ngrad_f_x_ref = 3.0 * ( expx ./ (1 .+ expx).^2 ) .* (1.0 ./ (1.0 .+ expmx) - b)\n@test norm(grad_f_x - grad_f_x_ref) <= 1e-10\n\n## with compose\n#with vectors\nl,m1,m2,n1,n2 = 2,3,4,5,6\nx = (randn(m1,m2),randn(n1,n2))\nA = randn(l,m1)\nB = randn(m2,n1)\nr = randn(l,n2)\n\nb = randn(l,n2)\nG = AffineAdd(NonLinearCompose( MatrixOp(A,m2), MatrixOp(B,n2) ),b,false)\n\ng = ProximalOperators.SqrNormL2(3.0)\nf = StructuredOptimization.PrecomposeNonlinear(g, G)\n\nx = (randn(m1,m2),randn(n1,n2))\n\ngrad_f_x, f_x = ProximalOperators.gradient(f, x)\n\nr = G*x \ngrad_f_x2, f_x2 = ProximalOperators.gradient(g, r)\ngrad_f_x2 = jacobian(G,x)'*grad_f_x2\n\n@test norm(f_x-f_x2) < 1e-8\n@test blockvecnorm(grad_f_x2.-grad_f_x2) < 1e-8\n", "meta": {"hexsha": "abe9fd95c8b1d64d59d3d1b32af5d354fdf80a0d", "size": 1117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_proxstuff.jl", "max_stars_repo_name": "JuliaDocsForks/StructuredOptimization.jl", "max_stars_repo_head_hexsha": "0c9295c23e30e26940c84eaaf499cc8722698635", "max_stars_repo_licenses": ["MIT"], "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_proxstuff.jl", "max_issues_repo_name": "JuliaDocsForks/StructuredOptimization.jl", "max_issues_repo_head_hexsha": "0c9295c23e30e26940c84eaaf499cc8722698635", "max_issues_repo_licenses": ["MIT"], "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_proxstuff.jl", "max_forks_repo_name": "JuliaDocsForks/StructuredOptimization.jl", "max_forks_repo_head_hexsha": "0c9295c23e30e26940c84eaaf499cc8722698635", "max_forks_repo_licenses": ["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.976744186, "max_line_length": 78, "alphanum_fraction": 0.6714413608, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7944512178472725}}
{"text": "# Undergraduate Student: Arturo Burgos\n# Professor: Jo\u00e3o Rodrigo Andrade\n# Federal University of Uberl\u00e2ndia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberl\u00e2ndia, 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, -\u03c0, \u03c0, -\u03c0, \u03c0, 2\u03c0/128, 2\u03c0/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(-\u03c0, \u03c0, 128, -\u03c0, \u03c0, 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(-\u03c0, stop=\u03c0, length=40)\n    n = 100\n    \n    prog = Progress(n,1) ## progress bar\n    \n    @gif for t in range(0, stop=2\u03c0, 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\u03c0/(mesh.xmax-mesh.xmin)*[0:mesh.nx\u00f72-1;mesh.nx\u00f72-mesh.nx:-1]\n    ky = 2\u03c0/(mesh.ymax-mesh.ymin)*[0:mesh.ny\u00f72-1;mesh.ny\u00f72-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\u03c0/(mesh.xmax-mesh.xmin)*[0:mesh.nx\u00f72-1;mesh.nx\u00f72-mesh.nx:-1]\n    ky = 2\u03c0/(mesh.ymax-mesh.ymin)*[0:mesh.ny\u00f72-1;mesh.ny\u00f72-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\u03c0/(mesh.xmax-mesh.xmin)*[0:mesh.nx\u00f72-1;mesh.nx\u00f72-mesh.nx:-1]\n    ky = 2\u03c0/(mesh.ymax-mesh.ymin)*[0:mesh.ny\u00f72-1;mesh.ny\u00f72-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\u03c0/(mesh.xmax-mesh.xmin)*[0:mesh.nx\u00f72-1;mesh.nx\u00f72-mesh.nx:-1]\n    ky = 2\u03c0/(mesh.ymax-mesh.ymin)*[0:mesh.ny\u00f72-1;mesh.ny\u00f72-mesh.ny:-1]\n    \n    f  = zeros(Complex{Float64},(mesh.nx,mesh.ny))\n    f .= exact(0.0, mesh)\n    f\u0302  = 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\u0302 .= Py * f\n        f\u0302 .= f\u0302  .* exky\n        f .= Py \\ f\u0302\n        \n        f\u0302 .= Px * f\n        f\u0302 .= f\u0302  .* ekxy \n        f .= Px \\ f\u0302\n        \n        f\u0302 .= Py * f\n        f\u0302 .= f\u0302  .* exky\n        f .= Py \\ f\u0302\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 \u00c2 by calling `mul!(\u00c2, plan, A)`. \n# The input array A must be a complex floating-point array like the output \u00c2.\n# The inverse-transform is computed inplace by applying `inv(P)` with `ldiv!(A, P, \u00c2)`.\n\nfunction with_fft_plans_inplace(tf, nt, mesh::Mesh)\n\n    dt = tf/nt\n\n    kx = 2\u03c0/(mesh.xmax-mesh.xmin)*[0:mesh.nx\u00f72-1;mesh.nx\u00f72-mesh.nx:-1]\n    ky = 2\u03c0/(mesh.ymax-mesh.ymin)*[0:mesh.ny\u00f72-1;mesh.ny\u00f72-mesh.ny:-1]\n    \n    f  = zeros(Complex{Float64},(mesh.nx,mesh.ny))\n    f .= exact(0.0, mesh)\n    f\u0302  = 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\u0302, Py, f)\n        f\u0302 .= f\u0302 .* exky\n        ldiv!(f, Py, f\u0302)\n        \n        mul!(f\u0302, Px, f)\n        f\u0302 .= f\u0302 .* ekxy \n        ldiv!(f, Px, f\u0302)\n        \n        mul!(f\u0302, Py, f)\n        f\u0302 .= f\u0302 .* exky\n        ldiv!(f, Py, f\u0302)\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\u03c0/(mesh.xmax-mesh.xmin)*[0:mesh.nx\u00f72-1;mesh.nx\u00f72-mesh.nx:-1]\n    ky = 2\u03c0/(mesh.ymax-mesh.ymin)*[0:mesh.ny\u00f72-1;mesh.ny\u00f72-mesh.ny:-1]\n    \n    f  = zeros(Complex{Float64},(mesh.nx,mesh.ny))\n    f\u0302  = similar(f)\n    f\u1d57 = zeros(Complex{Float64},(mesh.ny,mesh.nx))\n    f\u0302\u1d57 = similar(f\u1d57)\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\u1d57, 1, flags=FFTW.PATIENT)\n    \n    f .= exact(0.0, mesh)\n    \n    for n = 1:nt\n        transpose!(f\u1d57,f)\n        mul!(f\u0302\u1d57, Py, f\u1d57)\n        f\u0302\u1d57 .= f\u0302\u1d57 .* exky\n        ldiv!(f\u1d57, Py, f\u0302\u1d57)\n        transpose!(f,f\u1d57)\n        \n        mul!(f\u0302, Px, f)\n        f\u0302 .= f\u0302 .* ekxy \n        ldiv!(f, Px, f\u0302)\n        \n        transpose!(f\u1d57,f)\n        mul!(f\u0302\u1d57, Py, f\u1d57)\n        f\u0302\u1d57 .= f\u0302\u1d57 .* exky\n        ldiv!(f\u1d57, Py, f\u0302\u1d57)\n        transpose!(f,f\u1d57)\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\u03c0, 1000\nmesh = Mesh(-\u03c0, \u03c0, 512, -\u03c0, \u03c0, 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": "import RowEchelon\nimport LinearAlgebra\n\n#=\nHomework 7\nSection 3.2\nProblems 29\n=#\n\n# Create B\nB = [1 0 1 ; 1 1 2 ; 1 2 1]\n# Create B^5\nB5 = B^5\n# Get detB5\ndetB5 = LinearAlgebra.det(B5)\n\nprintln(\"Original Matrix, B:\")\nprintln(B)\nprintln(\"B^5:\")\nprintln(B5)\nprintln(\"Determinate of B^5\")\nprintln(detB5)\n", "meta": {"hexsha": "dc09c830a9526afe5468a455caf5887b49570fb7", "size": 301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW7_S3.2_P29.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": "HW7_S3.2_P29.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": "HW7_S3.2_P29.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.0869565217, "max_line_length": 30, "alphanum_fraction": 0.6810631229, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7944301142406953}}
{"text": "using LsqFit\n\nmodel(t, p) = p[1] * exp.(-p[2] * t)\n\ntdata = range(0,10, length=20)\nydata = model(tdata, [1.0, 2.0]) + 0.01*randn(length(tdata))\n\np0 = [0.5, 0.5]\n\nfit = curve_fit(model, tdata, ydata, p0)\n\nusing Plots\nplotly()\n\npt = plot(title=\"Nonlinear Regression\", size=(600,400))\nplot!(pt, tdata, ydata, seriestype=:scatter)\n\na = fit.param[1]\nb = fit.param[2]\nfitmodel(t) = a * exp.(-b*t)\n#plot!(pt, fitmodel, extrema(tdata)..., seriestype=:line)\nx = range(0,10,length=100)\ny = @. fitmodel(x)\nplot!(pt, x, y, seriestype=:line)\ngui(pt)\nnothing", "meta": {"hexsha": "40f19e49cfc5203bbe2f1370149c2a26459b3007", "size": 544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "learn/learn_LsqFit.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": "learn/learn_LsqFit.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": "learn/learn_LsqFit.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": 20.9230769231, "max_line_length": 60, "alphanum_fraction": 0.6360294118, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7944301065549622}}
{"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 \u03b3 \u03b3_text 1/14\n@capture \u03b2 \u03b2_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 + \u03b3) / 990 * (1-contact_rate) # calculate rate of infection\nend\n\nsir_cset= LabelledReactionNet{Function, Float64}((:S=>990, :I=>10, :R=>0), (:inf, \u03b2)=>((:S, :I)=>(:I,:I)), (:rec, t->\u03b3)=>(: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, \u03b2_text)=>((:S, :I)=>(:I,:I)), (:rec, \u03b3_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": "\"\"\"\n    `generatePoint(dims::Int, range::AbstractFloat, offset::AbstractFloat = 0)`\n\nGenerates a random `dims`-dimensional point represented as an array.\n\nd \u2208 (offset - range / 2, offset + range / 2) for each dimension of the point.\n\"\"\"\nfunction generatePoint(dims::Int, range::AbstractFloat, offset::AbstractFloat = 0.0)\n  return range * rand(dims) - range / 2 + offset \nend\n\n\"\"\"\nGenerates `n` random points without outputs. The rest of parameters are same as parameters for `generatePoint`.\n\"\"\"\nfunction generatePoints(n::Int, dims::Int, range::AbstractFloat, offset::AbstractFloat = 0.0)\n  return [generatePoint(dims, range, offset) for i in 1:n]\nend\n\n\"\"\"\n# Arguments\n- `amount`: the amount of points to be generated,\n- `polyDegree`: the degree of polynomial used for data generation,\n- `polyDim`: the spatial dimension of each term in the polynomial used for data generation,\n- `ptRange` and `ptOffset`: the same as `generatePoint`,\n- `polyRange` and `polyOffset`: the same as `generatePoint`, but for each term in the polynomial used for data generation,\n- `outputFile`: name of the output file\n\"\"\"\nfunction generateRandomData(amount::Int, polyDegree::Int, polyDim::Int, ptRange::Float64, ptOffset::Float64, polyRange::Float64, polyOffset::Float64, outputFile::String)\n  vars, mons = generateMonomials(polyDegree, polyDim)\n  coeffs = polyRange * rand(length(mons)) - (polyRange / 2 + polyOffset)\n  poly = polynomial(coeffs, mons)\n  res = generatePoints(amount, polyDegree, ptRange, ptOffset)\n  for p in res\n    push!(p, poly(vars => p))\n  end\n  writecsv(outputFile, res)\n  println(\"Polynomial '$poly' was used for data generation\")\n  println(\"Done\")\nend\n\n", "meta": {"hexsha": "26e4625397c6a580d788bb87df026c4af0629384", "size": 1660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sample-generator.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MovingWeightedLeastSquares.jl-b76c21c2-e830-5776-beb5-6c1142ec24db", "max_stars_repo_head_hexsha": "e752333dc6a852d1b42cef47c788c4e880fdc082", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-09T18:04:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-09T18:04:19.000Z", "max_issues_repo_path": "test/sample-generator.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MovingWeightedLeastSquares.jl-b76c21c2-e830-5776-beb5-6c1142ec24db", "max_issues_repo_head_hexsha": "e752333dc6a852d1b42cef47c788c4e880fdc082", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-04T17:23:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:32:06.000Z", "max_forks_repo_path": "test/sample-generator.jl", "max_forks_repo_name": "vutunganh/MovingWeightedLeastSquares.jl", "max_forks_repo_head_hexsha": "a925404df69f5a06e7defcde34504836cc707991", "max_forks_repo_licenses": ["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.487804878, "max_line_length": 169, "alphanum_fraction": 0.7289156627, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.7943644223320556}}
{"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 \u03bb\u2081 \u2265 \u03bb\u2082 \u2265 \u03bb\u2083 are 3 eigenvalues of the constructed matrix M, then a good\nindicator of nice fitting LMN coordinate system should have \u03bb\u2082/\u03bb\u2083 > 5. Set \n`verbose=true` to turn on the check.\n\"\"\"\nfunction mva(Bx, By, Bz; verbose=false)\n\n   B\u03041 = mean(Bx)\n   B\u03042 = mean(By)\n   B\u03043 = mean(Bz)\n   B\u030411= mean(Bx.*Bx) - B\u03041*B\u03041\n   B\u030422= mean(By.*By) - B\u03042*B\u03042\n   B\u030433= mean(Bz.*Bz) - B\u03043*B\u03043\n   B\u030412= mean(Bx.*By) - B\u03041*B\u03042\n   B\u030423= mean(By.*Bz) - B\u03042*B\u03043\n   B\u030431= mean(Bz.*Bx) - B\u03043*B\u03041\n   # Construct the matrix\n   M = [B\u030411 B\u030412 B\u030431; B\u030412 B\u030422 B\u030423; B\u030431 B\u030423 B\u030433]\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 \u2265 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}; \u03b2::Real)\n    (\u03b2 >= 0) || throw(ArgumentError(\"\u03b2 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_\u03b2 = (1 + \u03b2)*h*c/(\u03b2*h + c)\n    return V_\u03b2\nend\n\n\"\"\"\n    vmeasure(assign1, assign2; \u03b2 = 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 `\u03b2` parameter defines trade-off between _homogeneity_ and _completeness_:\n * if `\u03b2` is greater than 1, _completeness_ is weighted more strongly,\n * if `\u03b2` 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                  \u03b2::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))), \u03b2=\u03b2)\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": "using KrylovMethods\nusing Base.Test\nusing MatrixDepot\n\n\nprintln(\"=== Testing Lanczos helpers ===\")\nsymOrth = KrylovMethods.symOrtho\n\nv     = ([0;randn()],[randn();0],randn(2))\nfor k=1:3\n\tprintln(\"Givens rotation for v=[$(v[k][1]),$(v[k][2])]\")\n\tc,s,r = symOrth(v[k][1],v[k][2])\n\t@test abs(c.^2 + s.^2 - 1) < 1e-14\n\tQ = [c s; -s c]\n\tw = [norm(v[k]);0]\n\t@test norm(Q*v[k]-w) < 1e-13\nend\n\nprintln(\"=== Testing Lanczos Bidiagonalization ===\")\nA = sprandn(10,10,.4) + speye(10)\np = randn(10)\nk = 9\n\nU,B,V = lanczosBidiag(A,p,k)\n\n@test norm(full(U'*A*V-B))/norm(full(A)) < 1e-15\n\n\nprintln(\"=== Testing Lanczos Tridiagonalization ===\")\n\n# test stopping for low-rank matrix\nA = randn(100,10)\nH = A*A'\nT,V = lanczosTridiag(H,ones(100),100,doReorth=true)\n@test size(T,1)==11\n@test size(V,2)==11\n\nA   = matrixdepot(\"rosser\",4)\nAff  = x -> A*x\nT1,V1 = lanczosTridiag(A,ones(size(A,1)),size(A,1),tol=1e-10,doReorth=true)\nT2,V2 = lanczosTridiag(Aff,ones(size(A,1)),size(A,1),tol=1e-10,doReorth=false)\nsT1  = svd(full(T1))[2]\nsT2  = svd(full(T2))[2]\nsA   = svd(full(A))[2]\n\n@test abs(sT1[1]-sA[1])/sA[1] < 1e-4\n@test abs(sT2[1]-sA[1])/sA[1] < 1e-4\nB = V1'*V1\n@test norm(B - diagm(diag(B))) < 1e-10\n@test norm(diag(B)- ones(size(B,1))) < 1e-10\nprintln(\"=== Lanczos: All tests passed. ===\")\n", "meta": {"hexsha": "ab6290e2ff2340bcae7a501ada52be6bd420e0a4", "size": 1274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testLANCZOS.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": "test/testLANCZOS.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": "test/testLANCZOS.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": 24.5, "max_line_length": 78, "alphanum_fraction": 0.6114599686, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.794360943128814}}
{"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\"\"\"\n  Compute the nth Pernicious number\n\"\"\"\n\nusing BenchmarkTools\nusing Printf\nusing Primes\n\n# Get the value of of an integer from the command line.\nn, = size(ARGS)\nif n < 1\n    println(\"Usage: test_pernicious_numbers.jl max_num\")\n    println(\"       --->      Please specify a positive integer.\")\n    exit()\nend\n\nmax_num = parse(Int64, ARGS[1])\n\n \nispernicious(n::Int64) = isprime(count_ones(n))\n\nnextpernicious(n::Int64) = begin n += 1; while !ispernicious(n) n += 1 end; return n end\n\nfunction perniciouses(n::Int64)\n    rst = Vector{Int64}(undef, n)\n    old_p = 3\n    for i in 2:n\n        new_p = nextpernicious(old_p)\n        old_p = new_p\n    end\n    return old_p\nend\n\nperniciouses(a::Integer, b::Integer) = filter(ispernicious, a:b)\n\nprintln(\"Pernicious number of order: \", max_num)\n\n@btime perniciouses(max_num)\n \n#println(\"Pernicious number of order \", max_num, \": \", perniciouses(max_num))\n", "meta": {"hexsha": "28e6cb1317bbea4f0ac3e24e5cb99aec363cabf9", "size": 901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/test_pernicious_numbers.jl", "max_stars_repo_name": "cometscome/basic_language_comparison", "max_stars_repo_head_hexsha": "f29a1075f9740ea9074d2bc520d25ae0e6841093", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2019-11-06T12:07:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T09:09:49.000Z", "max_issues_repo_path": "Julia/test_pernicious_numbers.jl", "max_issues_repo_name": "cometscome/basic_language_comparison", "max_issues_repo_head_hexsha": "f29a1075f9740ea9074d2bc520d25ae0e6841093", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2019-11-10T20:28:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T11:24:08.000Z", "max_forks_repo_path": "Julia/test_pernicious_numbers.jl", "max_forks_repo_name": "cometscome/basic_language_comparison", "max_forks_repo_head_hexsha": "f29a1075f9740ea9074d2bc520d25ae0e6841093", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-11-10T19:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T21:15:08.000Z", "avg_line_length": 21.4523809524, "max_line_length": 88, "alphanum_fraction": 0.6725860155, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7942708870458186}}
{"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_\u03b2(\u03b2, \u03b7, D, R)\n    \u03b1 = 2.0 .- \u03b2 .^ (-  \u03b7 - 1.0 )\n    mask = R .<= 1.0 ./ \u03b1\n    s = 1.0 / (\u03b7 + 1.0)\n    \u03b2q = [ mask[i] ?  (R[i] * \u03b1[i])^s : (1.0 / (2.0 - R[i]*\u03b1[i]))^s for i in 1:D]\n    \u03b2q\nend\n\n\"\"\"\n    SBX_crossover(vector1, vector2, bounds, \u03b7=15, p_variable = 0.9)\n\nSimulated binomial crossover for given two `Vectors{Real}`.\n\"\"\"\nfunction SBX_crossover(vector1, vector2, bounds, \u03b7=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    \u0394 = max.(eps(), y2 - y1)\n\n\n    R = rand(D)\n\n    \u03b2 = @. 1.0 + (2.0 * (y1 - xl) / \u0394)\n    \u03b2q = gen_\u03b2(\u03b2, \u03b7, D, R) \n    c1 = @. 0.5*(y1 + y2 -  \u03b2q*\u0394)\n\n    \u03b2 = @. 1.0 + (2.0 * (y1 - xl) / \u0394)\n    \u03b2q = gen_\u03b2(\u03b2, \u03b7, D, R) \n    c2 = @. 0.5*(y1 + y2 +  \u03b2q*\u0394)\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    `\u2211(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, \u03c4, r, \u03c3, q)\n    return (log(S / K) + (r - q + \u03c3^2 / 2) * \u03c4) / (\u03c3 * \u221a(\u03c4))\nend\n\nfunction d2(S, K, \u03c4, r, \u03c3, q)\n    return d1(S, K, \u03c4, r, \u03c3, q) - \u03c3 * \u221a(\u03c4)\nend\n\n\"\"\"\n    eurocall(;S=1.,K=1.,\u03c4=1,r,\u03c3,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- `\u03c4` is the time remaining to maturity (can be typed with \\\\tau[tab])\n- `r` is the continuously compounded risk free rate\n- `\u03c3` 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, \u03c4 = 1, r, \u03c3, q = 0.0)\n    d\u2081 = d1(S, K, \u03c4, r, \u03c3, q)\n    d\u2082 = d2(S, K, \u03c4, r, \u03c3, q)\n    return (N(d\u2081) * S * exp(\u03c4 * (r - q)) - N(d\u2082) * K) * exp(-r * \u03c4)\nend\n\n\"\"\"\n    europut(;S=1.,K=1.,\u03c4=1,r,\u03c3,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- `\u03c4` is the time remaining to maturity (can be typed with \\\\tau[tab])\n- `r` is the continuously compounded risk free rate\n- `\u03c3` 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, \u03c4 = 1, r, \u03c3, q = 0.0)\n    d\u2081 = d1(S, K, \u03c4, r, \u03c3, q)\n    d\u2082 = d2(S, K, \u03c4, r, \u03c3, q)\n    return (N(-d\u2082) * K - N(-d\u2081) * S * exp(\u03c4 * (r - q))) * exp(-r * \u03c4)\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, \u03b10, y)\n    \n    # Initialize state variables\n    \u03b1hat = repeat([zeros(size(\u03b10))], n);\n    \u03b1hat[1] = T*\u03b10;\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 * \u03b1hat[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        \u03b1hat[i + 1] = T * \u03b1hat[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 * \u03b1hat[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 \u03b1hat, 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\u03b1 = 0.25\nx_grad = [x x.+\u03b1.*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, \u03b1; max_iter=100)\n    xs = zeros(length(x), max_iter+1)\n    xs[:,1] = x\n    for i in 1:max_iter\n        x -= \u03b1*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    \u03b1::Float64\nend\n\n#### Gradient descent\n\noptim_step(s::GD, f, g, x) = -s.\u03b1*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    \u03b1_max::Float64\nend\n\nfunction optim_step(s::Armijo, f, g, x)\n    fun = f(x)\n    grad = g(x)\n    \u03b1 = s.\u03b1_max\n    while f(x .- \u03b1*grad) > fun - s.c*\u03b1*(grad'*grad)\n        \u03b1 /= 2\n        if \u03b1 <= 1e-6\n            warning(\"Armijo line search failed.\")\n            break\n        end\n    end\n    return -\u03b1*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, \u03b1; 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] - \u03b1*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    \u03b6(k) = - (h + cospi((2k + 1) / L))\n    u(k) = sqrt((1 + \u03b6(k) / E(k)) / 2)\n    v(k) = sqrt((1 - \u03b6(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": "using Element\nusing Base.Test\n\n\nusing Element: lingrid, integrate, findsteps, eig, loggrid\nusing Element: SphericalHarmonicTable, radschrod1, cart2sph, realsphharm, enumeratelm, randp, radpoisson\n\n\n\n\n# findsteps\n\nf = (x,c) -> round(Int,x^2+c)\nintervals = findsteps(f,0.0,2.0,args=1.0)\n@test intervals == [(0.0,1.0),(1.0,1.5),(1.5,1.75),(1.75,2.0)]\n\n\n\n\n\n# eig\n\nx = lingrid(0,1,1000)\ndx = x[2]-x[1]\nv = 0*x\naE = E -> 2*(E-v)\nqmin, qmax = 0,10\n\nevs,efs,q = eig(aE,dx,qmin,qmax,Emin=0.0,Emax=20.0)\nn = length(evs)\nefs ./= sqrt(integrate(x, efs.^2))'  # normalization\n\nexact_evs = [j^2*pi^2/2 for j in 1:n]\nexact_efs = hcat([sqrt(2)*sin(j*pi*x) for j in 1:length(evs)]...)\n\n@test q == collect(qmin:qmax)\n@test_approx_eq integrate(x,efs.^2) fill(1.0,n)\n@test_approx_eq_eps integrate(x, efs.^2 - exact_efs.^2) fill(0.0,n) 1e-12\n@test_approx_eq_eps evs exact_evs 1e-5\n\n\n\n# radschrod1\n\n\nr = loggrid(-22,4,1000)\nv = -1./r\n\nn,l = 1,0\nev,ef = radschrod1(r,v,n,l)\n@test_approx_eq_eps ev -1/(2*n^2) 1e-8\n@test_approx_eq_eps integrate(r, (ef.^2 - (2r.*exp(-1*r)).^2).^2) 0.0 1e-12\n\nn,l = 2,0\nev,ef = radschrod1(r,v,n,l)\n@test_approx_eq_eps ev -1/(2*n^2) 1e-8\n@test_approx_eq_eps integrate(r, (ef.^2 - (-1*r/sqrt(2).*(1-0.5*r).*exp(-0.5*r)).^2).^2) 0.0 1e-12\n\nn,l = 2,1\nev,ef = radschrod1(r,v,n,l)\n@test_approx_eq_eps ev -1/(2*n^2) 1e-8\n@test_approx_eq_eps integrate(r, (ef.^2 - (r/3^0.5/2^(3./2).*r.*exp(-0.5*r)).^2).^2) 0.0 1e-12\n\nn,l = 3,1\nev,ef = radschrod1(r,v,n,l)\n@test_approx_eq_eps ev -1/(2*n^2) 1e-8\n@test_approx_eq_eps integrate(r, (ef.^2 - (r*8./27/sqrt(6).*(1-r/6).*r.*exp(-1.*r/3)).^2).^2) 0.0 1e-12\n\n\n\n\n\n\n# radpoisson\nr = loggrid(-13,5,500)\nrho = exp(-2r)\n\nl = 0\nvh_exact = 1/4*exp(-2r).*(1 + 2r) + (1 + exp(-2r).*(-1 - 2r.*(1 + r)))./(4r)  # l = 0\nvh = radpoisson(r,rho,l)\n\n@test_approx_eq_eps vh vh_exact 1e-5\n@test_approx_eq_eps integrate(r, rho.*vh_exact/2) integrate(r, rho.*vh/2) 1e-6\n\nl = 1\nvh_exact = (3*exp(-2r).*(-1 + exp(2r) - 2r - 2r.^2))./(8r.^2)  # l = 1\nvh = radpoisson(r,rho,l)\n\n@test_approx_eq_eps vh vh_exact 1e-5\n@test_approx_eq_eps integrate(r, rho.*vh_exact/2) integrate(r, rho.*vh/2) 1e-6\n\n\n\n\n\n\n\n# spherical harmonics table\n\np = randp(3)[]\np = p/norm(p)\nr,\u03b8,\u03d5 = cart2sph(p)\n\nlmax = 8\nY = SphericalHarmonicTable(lmax)\nY(p)  # precompute spherical harmonics\n\na = [realsphharm(l,m,\u03b8,\u03d5) for (l,m) in enumeratelm(lmax)]\nb = [Y[l,m] for (l,m) in enumeratelm(lmax)]\n\n@test_approx_eq a b\n\n\n\n\n\n", "meta": {"hexsha": "27c0701ce7e7715dd3292773b15413e03a4f1821", "size": 2406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "johncsnyder/Element", "max_stars_repo_head_hexsha": "92d917e3285cdc7073a359ef076eca7d426ec30e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-28T23:13:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-28T23:13:46.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "johncsnyder/Element.jl", "max_issues_repo_head_hexsha": "92d917e3285cdc7073a359ef076eca7d426ec30e", "max_issues_repo_licenses": ["MIT"], "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": "johncsnyder/Element.jl", "max_forks_repo_head_hexsha": "92d917e3285cdc7073a359ef076eca7d426ec30e", "max_forks_repo_licenses": ["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.5641025641, "max_line_length": 104, "alphanum_fraction": 0.6284289277, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7941341887945549}}
{"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, \u03c3, 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* `\u03c3`     `[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    (_, \u03c3, 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, \u03c3, Vr)\nend\n\n\n\"\"\"\n    snr2sigma(db, yb)\nconvert SNR in dB to noise \u03c3 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(\u03c6::Vector [, cs, N0]) -> chaotic?\nPerform the so called \"0-1\" test for chaos introduced by Gottwald and\nMelbourne [1] on the timeseries `\u03c6`.\nReturn `true` if `\u03c6` 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(\u03c6))`,\nwhile it stays constant if the timeseries is regular.\nThe implementation here computes `K`, the correlation coefficient (median\nof `Kc for c \u2208 cs`), and simply checks if `K > 0.5`.\n\nIf you want to access the various `Kc` you should call the method\n`testchaos01(\u03c6, c::Real, N0)` which returns `Kc`.\n\n`cs` defaults to `3\u03c0/5*rand(10) + \u03c0/4` and `N0`, the length\nof the two-dimensional process, is `N0 = length(\u03c6)/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, \u201cThe 0-1 test for chaos: A review\u201d\n[Lect. Notes Phys., vol. 915, pp. 221\u2013247, 2016.](www.doi.org/10.1007/978-3-662-48410-4_7)\n\"\"\"\nfunction testchaos01(\u03c6::Vector, cs = 3\u03c0/5*rand(10) .+ \u03c0/4, N0 = Int(length(\u03c6)\u00f710))\n    K = median(testchaos01(\u03c6, c, N0) for c in cs)\n    return K > 0.5\nend\n\nfunction testchaos01(\u03c6::Vector, c::Real, N0 = Int(length(\u03c6)\u00f710))\n    N, E = length(\u03c6), mean(\u03c6)\n    @assert N0 \u2264 N/10\n    pc, qc = trigonometric_decomposition(\u03c6, c)\n    Dc = mmsd(E, pc, qc, N0, c)\n    Kc = cor(Dc, 1:N0)\n    return Kc\nend\n\nfunction trigonometric_decomposition(\u03c6, c)\n    X = promote_type(eltype(\u03c6), typeof(c))\n    N = length(\u03c6)\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] + \u03c6[n]*co\n        qc[n+1] = qc[n] + \u03c6[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": "#=\n@author Alvaro Lucas Castillo Calabacero\ncontact alvarolucascc96@gmail.com\n=#\n\n#=\nRecursive algorithm for resolve MergeSort\n=#\nfunction mergeSort!(array, start = 1, finish = length(array))\n    if start < finish\n        middle = div(start+finish, 2)\n        mergeSort!(array, start, middle)\n        mergeSort!(array, middle+1, finish)\n        merge(array, start, middle, finish)\n    end\n    return array\nend\n\n#=\nalgorithm for merge\n =#\nfunction merge(array, start, half, finish)\n    ward = typemax(eltype(array))\n    leftSubArray = array[start:half]\n    rightSubArray = array[(half+1):finish]\n    push!(leftSubArray, ward)\n    push!(rightSubArray, ward)\n    auxLeft=1\n    auxRight = 1\n    for i in start:finish\n      if leftSubArray[auxLeft] <= rightSubArray[auxRight]\n          array[i] = leftSubArray[auxLeft]\n          auxLeft += 1\n      else\n          array[i] = rightSubArray[auxRight]\n          auxRight += 1\n      end\n    end\nend\n#can change this total numbers for process of sort\ntotalNumbers = 10000000;\nlist = [rem(rand(Int128),100000) for i =1:totalNumbers]\n\nprint(\"Sorted List in :\")\n#get time to solve whit secuencial algorithm\n@time mergeSort!(list)\nprint(list)\n", "meta": {"hexsha": "5de688f69d624f2fb10154af7b798ed3a5137c14", "size": 1178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mergesort.jl", "max_stars_repo_name": "AlvaroCC96/MergeSort-Julia", "max_stars_repo_head_hexsha": "4ce53e39de97014dc91b70c910c84047151da0a6", "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": "mergesort.jl", "max_issues_repo_name": "AlvaroCC96/MergeSort-Julia", "max_issues_repo_head_hexsha": "4ce53e39de97014dc91b70c910c84047151da0a6", "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": "mergesort.jl", "max_forks_repo_name": "AlvaroCC96/MergeSort-Julia", "max_forks_repo_head_hexsha": "4ce53e39de97014dc91b70c910c84047151da0a6", "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.5416666667, "max_line_length": 61, "alphanum_fraction": 0.6655348048, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.9032942014971871, "lm_q1q2_score": 0.7941281716359193}}
{"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": "function gss(arr::Vector{<:Number})\n    smax = hmax = tmax = 0\n    for head in eachindex(arr), tail in head:length(arr)\n        s = sum(arr[head:tail])\n        if s > smax\n            smax = s\n            hmax, tmax = head, tail\n        end\n    end\n    return arr[hmax:tmax]\nend\n\narr = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]\nsubseq = gss(arr)\ns = sum(subseq)\n\nprintln(\"Greatest subsequential sum of $arr:\\n \u2192 $subseq with sum $s\")\n", "meta": {"hexsha": "54be7166f1129b18d2804e4aafca010da9d0a7a0", "size": 432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/greatest-subsequential-sum.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/greatest-subsequential-sum.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/greatest-subsequential-sum.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.0, "max_line_length": 70, "alphanum_fraction": 0.5439814815, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7940527306190625}}
{"text": "\"\"\"\n    fresnels(x)\n\nCompute the Fresnel S integral of type 0 (integral of `sin(\u03c0t\u00b2/2)`).\n\"\"\"\nfresnels(x) = (1 + im) / 4 * (erf((1 + im)\u221a\u03c0 / 2 * x) - im * erf((1 - im)\u221a\u03c0 / 2 * x))\n\n\"\"\"\n    fresnelc(x)\n\nCompute the Fresnel C integral of type 0 (integral of `cos(\u03c0t\u00b2/2)`).\n\"\"\"\nfresnelc(x) = (1 - im) / 4 * (erf((1 + im)\u221a\u03c0 / 2 * x) + im * erf((1 - im)\u221a\u03c0 / 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\u00e7\u00e3o 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\u00e1rias 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\u00e3o\ny = zeros(Int64 , n , n)\n\n# dados do exemplo do slide da prof(trabalho -  material auxiliar)\n# \u00e9 o exemplo das cidades que est\u00e1 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\u00e7\u00e3o 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# \u2554\u2550\u2561 77489ff6-bd82-11ea-2d09-8737634cc579\nusing Random\n\n# \u2554\u2550\u2561 e9b93d52-bd82-11ea-15c9-699eeebaa243\nusing Plots\n\n# \u2554\u2550\u2561 7eab739e-bdba-11ea-3ff3-fd88b08946d3\nusing LaTeXStrings\n\n# \u2554\u2550\u2561 508fed7e-bdbe-11ea-1d75-8935a47d06d8\nusing Statistics\n\n# \u2554\u2550\u2561 fc08751c-bd79-11ea-072b-33a239fa0605\nmd\"# Stochastic Thinking\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 65f53264-bd7d-11ea-03cc-9513654c222c\nfunction run_infection(I\u2080, \u03bb, T=20)\n\tI = zeros(T)\n\tI[1] = I\u2080\n\t\n\tfor n \u2208 1:T-1\n\t\tI[n+1] = \u03bb * I[n]\n\tend\n\t\n\treturn I\nend\n\n# \u2554\u2550\u2561 2dce78b0-bd7e-11ea-0381-d16883397ebd\nrun_infection(1.0, 0.1)\n\n# \u2554\u2550\u2561 38ad903e-bd7e-11ea-08b6-f9a9a086260f\nmd\"## Adding new data to extend a vector\"\n\n# \u2554\u2550\u2561 c7c0a170-bd7f-11ea-3b68-a9ae0c8ccfde\nv = [1.0]\n\n# \u2554\u2550\u2561 e40b10e0-bd7f-11ea-2883-bf485b88d6ad\npush!(v, 7.0) # ! means the function modifies its first argument\n\n# \u2554\u2550\u2561 b9db886e-bd80-11ea-1347-5d5415a22dd5\nv\n\n# \u2554\u2550\u2561 c427a4fc-bd80-11ea-365a-59fd43802b47\n[v; 10]\n\n# \u2554\u2550\u2561 92666d14-bd81-11ea-2ba7-e181ffa9f476\npushfirst!(v, 8) # deque - double endedn queue\n\n# \u2554\u2550\u2561 0f3c4b1c-bd80-11ea-0fd0-df1c82c3ed1c\nfunction run_infection_vectorized(I\u2080, \u03bb, T=20)\n\tIs = [I\u2080]\n\tI = I\u2080\n\t\n\tfor n \u2208 1:T-1\n\t\tI_next = \u03bb * 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# \u2554\u2550\u2561 71759792-bd81-11ea-1cbe-35ca8456b6a1\nrun_infection_vectorized(1.0, 1.1)\n\n# \u2554\u2550\u2561 7a610d46-bd81-11ea-0ff9-5b97563bce1e\nmd\"## Randomness\"\n\n# \u2554\u2550\u2561 29e900e6-bd82-11ea-0344-2b2276b99422\nrand()\n\n# \u2554\u2550\u2561 8cec500a-bd82-11ea-2fbb-03dec9457d7e\nRandom.seed!(3);\n\n# \u2554\u2550\u2561 a1c76a96-bd82-11ea-22a0-d9110840ecf3\nrand()\n\n# \u2554\u2550\u2561 d39e0c64-bd82-11ea-188d-6f762d4dd688\nrand(10)\n\n# \u2554\u2550\u2561 ed82a2b8-bd82-11ea-1d5c-8759b29ce1cc\nscatter(rand(50))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 be2d6b30-bd83-11ea-2683-49e64cbccb3c\n@bind num_points html\"<input type='range' min=1 max=100>\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 89984d06-bdab-11ea-3ff4-55786243da18\nmd\"## Event with probability $p$\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cfac1f86-bdac-11ea-316c-a9abea7ed509\nmd\"Bernoulli Trial\"\n\n# \u2554\u2550\u2561 46de61a4-bdad-11ea-3aaf-a5f9b96e533f\nfunction bernoulli(p)\n\tr = rand()\n\t\n\treturn r < p\nend\n\n# \u2554\u2550\u2561 8a20f6b6-bdad-11ea-0ef5-af788315bd82\n2 < 3 ? true : false # ternary operator\n\n# \u2554\u2550\u2561 bc82b248-bdad-11ea-3ad5-019463cf2ef1\n2 < 3\n\n# \u2554\u2550\u2561 c7552f0e-bdad-11ea-3fe8-fd3cf143ff30\nbegin\n\tlocal p = 0.25\n\t\n\ttrials = [bernoulli(p) for i \u2208 1:100]\nend\n\n# \u2554\u2550\u2561 fe9569d2-bdad-11ea-0f72-09084f78f692\nscatter(trials)\n\n# \u2554\u2550\u2561 38c6f580-bdae-11ea-2cbe-935e598ee04c\ntrials\n\n# \u2554\u2550\u2561 3a406aea-bdae-11ea-0c69-b13a4340a01a\ncount(trials)\n\n# \u2554\u2550\u2561 1b778d18-bdaf-11ea-3ee4-0f3a16536b9f\nfunction bernoulli_experiment(p, N=100)\n\ttrials = [bernoulli(p) for i \u2208 1:N]\n\treturn count(trials)\nend\n\n# \u2554\u2550\u2561 45a5c6a4-bdaf-11ea-1812-359502135397\ncount(trials .== false) + count(trials)\n\n# \u2554\u2550\u2561 65bf3b8a-bdaf-11ea-1878-bb69724e1a7b\ncount(.!(trials)) # ! is \"not\" in Julia\n\n# \u2554\u2550\u2561 84062240-bdaf-11ea-3494-8d49391f642a\nbernoulli_experiment(0.25)\n\n# \u2554\u2550\u2561 a9b7c836-bdaf-11ea-1691-9d38af43f16a\nbernoulli_experiment(0.25)\n\n# \u2554\u2550\u2561 be407118-bdaf-11ea-2973-853fc1a266e1\nmd\"A quantity that has different **outcomes** in different runs is called a **random variable**\"\n\n# \u2554\u2550\u2561 de5398ea-bdaf-11ea-1d81-5df4eb22e68b\nmd\"## Monte Carlo simulation\"\n\n# \u2554\u2550\u2561 73e79708-bdb0-11ea-123f-9fbb2c18dc12\nmd\"Run the same random process a lot of times and look at the results\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 af9e25e6-bdb0-11ea-23aa-7db6e35a4447\nscatter(results, zcolor=results)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 976c1838-bdb1-11ea-30b1-f5c5eb8e2360\nmd\"Probability that $X = x$ = proportion of time that the result was $x$\"\n\n# \u2554\u2550\u2561 f411c49a-bdb2-11ea-00b9-dfcc68181d37\nmd\"## Counting\"\n\n# \u2554\u2550\u2561 0922211a-bdb3-11ea-1e49-3518de406ace\nmd\"Need to count how many of the trials come out as 5\"\n\n# \u2554\u2550\u2561 286acb30-bdb3-11ea-1be2-c51955c53ab8\nmd\"Need data structure where we store the counts:\n\n- `Dict` (dictionary)\n- `Vector`\"\n\n# \u2554\u2550\u2561 50d0c656-bdb3-11ea-0a32-f7d63d08f64a\nresults\n\n# \u2554\u2550\u2561 99aab29c-bdb3-11ea-3dd0-57d1e619f762\nmaximum(results) #not 'max': max(1, 2, 3)\n\n# \u2554\u2550\u2561 2beb3cb0-bdb6-11ea-1451-05c1e3087165\nminimum(results)\n\n# \u2554\u2550\u2561 6e8a4d8a-bdb7-11ea-0fd5-6d942ceb5283\nl = maximum(results) + 1\n\n# \u2554\u2550\u2561 8e80e7fc-bdb7-11ea-1967-bbff2030d913\ncounts = zeros(Int, l)\n\n# \u2554\u2550\u2561 9b648744-bdb7-11ea-3e0e-7307a4084f9a\nfor score \u2208 results\n\tcounts[score + 1] += 1\nend\n\n# \u2554\u2550\u2561 e2635850-bdb7-11ea-21bc-5beadadfa675\ncounts\n\n# \u2554\u2550\u2561 7aecb5b0-bdba-11ea-026f-09ebc21a36a6\nimport Pkg; Pkg.add(\"LaTeXStrings\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7090316e-bdba-11ea-27a6-dbc5ec194d02\nfunction count_them(results)\n\tcounts = zeros(Int, maximum(results) + 1)\n\t\n\tfor score \u2208 results\n\t\tcounts[score + 1] += 1\n\tend\n\t\n\treturn counts\nend\n\n# \u2554\u2550\u2561 c56f3320-bdbb-11ea-2904-6197a97efbbf\nfunction run_experiments(p, N, num_expts=1000)\n\tresults = [bernoulli_experiment(p, N) for i \u2208 1:num_expts]\n\t\n\treturn results\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8c2374a2-bdbc-11ea-12a9-eda80a7e4e21\nmd\"## Probability distribution\"\n\n# \u2554\u2550\u2561 a00fa58a-bdbc-11ea-14a2-fd43cfedf7bb\nmd\"Probability = relative frequency\n\nDivide by the number of experiments\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cb4d967a-bdbd-11ea-35c8-ad831d395195\nsum(probs)\n\n# \u2554\u2550\u2561 cf802b2c-bdbd-11ea-0d10-390f5ea9fe19\nx = 3 // 4\n\n# \u2554\u2550\u2561 fb862028-bdbd-11ea-3c26-e5e8ebd9630d\ntypeof(x)\n\n# \u2554\u2550\u2561 04180cb0-bdbe-11ea-2a64-a33a4f778d68\nx + x\n\n# \u2554\u2550\u2561 08a5bf84-bdbe-11ea-18d4-dd7255a35b56\ndata\n\n# \u2554\u2550\u2561 741484a8-bdbe-11ea-3fd8-e55fe46723f8\nbegin\n\tlocal results = run_experiments(0.25, 20, 10^5)\n\tmean(results)\nend\n\n# \u2554\u2550\u2561 5d7c00b8-bdbe-11ea-2b46-6d1117a42368\nmd\"Expected mean value = N * p\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500fc08751c-bd79-11ea-072b-33a239fa0605\n# \u255f\u2500f895f5da-bd7c-11ea-2250-efdcd9d49a38\n# \u2560\u255065f53264-bd7d-11ea-03cc-9513654c222c\n# \u2560\u25502dce78b0-bd7e-11ea-0381-d16883397ebd\n# \u255f\u250038ad903e-bd7e-11ea-08b6-f9a9a086260f\n# \u2560\u2550c7c0a170-bd7f-11ea-3b68-a9ae0c8ccfde\n# \u2560\u2550e40b10e0-bd7f-11ea-2883-bf485b88d6ad\n# \u2560\u2550b9db886e-bd80-11ea-1347-5d5415a22dd5\n# \u2560\u2550c427a4fc-bd80-11ea-365a-59fd43802b47\n# \u2560\u255092666d14-bd81-11ea-2ba7-e181ffa9f476\n# \u2560\u25500f3c4b1c-bd80-11ea-0fd0-df1c82c3ed1c\n# \u2560\u255071759792-bd81-11ea-1cbe-35ca8456b6a1\n# \u255f\u25007a610d46-bd81-11ea-0ff9-5b97563bce1e\n# \u2560\u255029e900e6-bd82-11ea-0344-2b2276b99422\n# \u2560\u255077489ff6-bd82-11ea-2d09-8737634cc579\n# \u2560\u25508cec500a-bd82-11ea-2fbb-03dec9457d7e\n# \u2560\u2550a1c76a96-bd82-11ea-22a0-d9110840ecf3\n# \u2560\u2550d39e0c64-bd82-11ea-188d-6f762d4dd688\n# \u2560\u2550e9b93d52-bd82-11ea-15c9-699eeebaa243\n# \u2560\u2550ed82a2b8-bd82-11ea-1d5c-8759b29ce1cc\n# \u2560\u25500682ca0c-bd83-11ea-0afa-8794eb7bd9b8\n# \u255f\u2500be2d6b30-bd83-11ea-2683-49e64cbccb3c\n# \u2560\u2550811488a0-bdab-11ea-0f9d-b1bc9f854e07\n# \u255f\u250089984d06-bdab-11ea-3ff4-55786243da18\n# \u2560\u2550a8196c14-bdac-11ea-3b3d-f744310c289d\n# \u255f\u2500cfac1f86-bdac-11ea-316c-a9abea7ed509\n# \u2560\u255046de61a4-bdad-11ea-3aaf-a5f9b96e533f\n# \u2560\u25508a20f6b6-bdad-11ea-0ef5-af788315bd82\n# \u2560\u2550bc82b248-bdad-11ea-3ad5-019463cf2ef1\n# \u2560\u2550c7552f0e-bdad-11ea-3fe8-fd3cf143ff30\n# \u2560\u2550fe9569d2-bdad-11ea-0f72-09084f78f692\n# \u2560\u255038c6f580-bdae-11ea-2cbe-935e598ee04c\n# \u2560\u25503a406aea-bdae-11ea-0c69-b13a4340a01a\n# \u2560\u25501b778d18-bdaf-11ea-3ee4-0f3a16536b9f\n# \u2560\u255045a5c6a4-bdaf-11ea-1812-359502135397\n# \u2560\u255065bf3b8a-bdaf-11ea-1878-bb69724e1a7b\n# \u2560\u255084062240-bdaf-11ea-3494-8d49391f642a\n# \u2560\u2550a9b7c836-bdaf-11ea-1691-9d38af43f16a\n# \u255f\u2500be407118-bdaf-11ea-2973-853fc1a266e1\n# \u255f\u2500de5398ea-bdaf-11ea-1d81-5df4eb22e68b\n# \u255f\u250073e79708-bdb0-11ea-123f-9fbb2c18dc12\n# \u2560\u255085f366ac-bdb0-11ea-16b7-2bec6b2f5356\n# \u2560\u2550af9e25e6-bdb0-11ea-23aa-7db6e35a4447\n# \u255f\u250087eaac94-bdb1-11ea-117a-ffa693e0b098\n# \u255f\u2500976c1838-bdb1-11ea-30b1-f5c5eb8e2360\n# \u255f\u2500f411c49a-bdb2-11ea-00b9-dfcc68181d37\n# \u255f\u25000922211a-bdb3-11ea-1e49-3518de406ace\n# \u255f\u2500286acb30-bdb3-11ea-1be2-c51955c53ab8\n# \u2560\u255050d0c656-bdb3-11ea-0a32-f7d63d08f64a\n# \u2560\u255099aab29c-bdb3-11ea-3dd0-57d1e619f762\n# \u2560\u25502beb3cb0-bdb6-11ea-1451-05c1e3087165\n# \u2560\u25506e8a4d8a-bdb7-11ea-0fd5-6d942ceb5283\n# \u2560\u25508e80e7fc-bdb7-11ea-1967-bbff2030d913\n# \u2560\u25509b648744-bdb7-11ea-3e0e-7307a4084f9a\n# \u2560\u2550e2635850-bdb7-11ea-21bc-5beadadfa675\n# \u2560\u25507aecb5b0-bdba-11ea-026f-09ebc21a36a6\n# \u2560\u25507eab739e-bdba-11ea-3ff3-fd88b08946d3\n# \u2560\u255096b1bbb2-bdb8-11ea-3e81-1bca33878a99\n# \u2560\u25507090316e-bdba-11ea-27a6-dbc5ec194d02\n# \u2560\u2550c56f3320-bdbb-11ea-2904-6197a97efbbf\n# \u2560\u25504c85f43c-bdbc-11ea-1ba1-810cadb75f6e\n# \u255f\u25008c2374a2-bdbc-11ea-12a9-eda80a7e4e21\n# \u255f\u2500a00fa58a-bdbc-11ea-14a2-fd43cfedf7bb\n# \u2560\u2550bc8cf4ec-bdbc-11ea-33f3-d9aa8f26cd60\n# \u2560\u25500839ca58-bdbd-11ea-2a3e-c99ad45c7121\n# \u2560\u2550cb4d967a-bdbd-11ea-35c8-ad831d395195\n# \u2560\u2550cf802b2c-bdbd-11ea-0d10-390f5ea9fe19\n# \u2560\u2550fb862028-bdbd-11ea-3c26-e5e8ebd9630d\n# \u2560\u255004180cb0-bdbe-11ea-2a64-a33a4f778d68\n# \u2560\u255008a5bf84-bdbe-11ea-18d4-dd7255a35b56\n# \u2560\u2550508fed7e-bdbe-11ea-1d75-8935a47d06d8\n# \u2560\u2550741484a8-bdbe-11ea-3fd8-e55fe46723f8\n# \u255f\u25005d7c00b8-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    \u03b2 = m/n\n    \u03c9 = (8*\u03b2) / (\u03b2+1+sqrt(\u03b2^2+14\u03b2+1))\n    c = sqrt(2*(\u03b2+1)+\u03c9)\n\n    if known_noise\n        return c\n    else\n        median = median_marcenko_pastur(\u03b2)\n        return c / sqrt(median)\n    end\nend\n\nfunction marcenko_pastur_density(t, lower, upper, beta)\n    sqrt((upper-t).*(t-lower))./(2\u03c0*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 \u2248 zero(eltype(gamma))\n        i, \u03f5 = quadgk(x->(x^gamma)*marcenko_pastur(x), x, upper)\n        return i\n    else\n        i, \u03f5 = 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    \u03c4 = optimal_svht(m,n)\n    inds = S .>= \u03c4*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    \u03c4 = optimal_svht(m,n)\n    inds = S .>= \u03c4*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\u2080 = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y\u2080[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\u2080 = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y\u2080[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    (\u03b2,c,\u03b3,\u03b4t) = p\n    N = S+I+R\n    infection = rate_to_proportion(\u03b2*c*I/N,\u03b4t)*S\n    recovery = rate_to_proportion(\u03b3,\u03b4t)*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\u03b4t = 0.1\nnsteps = 400\ntmax = nsteps*\u03b4t\ntspan = (0.0,nsteps)\nt = 0.0:\u03b4t:tmax;\n\n\nu0 = [990.0,10.0,0.0];\n\n\np = [0.05,10.0,0.25,\u03b4t]; # \u03b2,c,\u03b3,\u03b4t\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    \u03b8::Float64\n    \u03bb::Float64\nend\n\nfunction Distributions.pdf(G::GeneralizedPoisson, x::Int64)\n    G.\u03b8*(G.\u03b8+G.\u03bb*x)^(x-1)*exp(-G.\u03b8 - G.\u03bb*x)/factorial(x)\nend\n\nfunction Distributions.logpdf(G::GeneralizedPoisson, x::Int64)\n    a = log(G.\u03b8)\n    a += (x-1)*log(G.\u03b8+G.\u03bb*x)\n    a -= G.\u03b8\n    a -= G.\u03bb*x\n    a -= lgamma(x+1)\n    a\nend\n\nDistributions.mean(G::GeneralizedPoisson) = G.\u03b8/(1-G.\u03bb)\nDistributions.var(G::GeneralizedPoisson) = G.\u03b8/(1-G.\u03bb)^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(; \u03bd = 1.0)\n\nThe matern kernel is a Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = 2^{1-\u03bd}/\u0393(\u03bd)*(\u221a(2\u03bd)\u2016x-y\u2016)^\u03bd K_\u03bd(\u221a(2\u03bd)\u2016x-y\u2016)\n```\nFor `\u03bd=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=\u221e`.\n\"\"\"\nstruct MaternKernel{T\u03bd<:Real} <: SimpleKernel\n    \u03bd::Vector{T\u03bd}\n    function MaternKernel(;nu::T=1.5, \u03bd::T=nu) where {T<:Real}\n        @check_args(MaternKernel, \u03bd, \u03bd > zero(T), \"\u03bd > 0\")\n        return new{T}([\u03bd])\n    end\nend\n\n@functor MaternKernel\n\n@inline function kappa(\u03ba::MaternKernel, d::Real)\n    result = _matern(first(\u03ba.\u03bd), d)\n    return ifelse(iszero(d), one(result), result)\nend\n\nfunction _matern(\u03bd::Real, d::Real)\n    y = sqrt(2\u03bd) * d\n    return exp((one(d) - \u03bd) * logtwo - loggamma(\u03bd) + \u03bd * log(y) + log(besselk(\u03bd, y)))\nend\n\nmetric(::MaternKernel) = Euclidean()\n\nBase.show(io::IO, \u03ba::MaternKernel) = print(io, \"Matern Kernel (\u03bd = \", first(\u03ba.\u03bd), \")\")\n\n\"\"\"\n    Matern32Kernel()\n\nThe matern 3/2 kernel is a Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = (1+\u221a(3)\u2016x-y\u2016)exp(-\u221a(3)\u2016x-y\u2016)\n```\n\"\"\"\nstruct Matern32Kernel <: SimpleKernel end\n\nkappa(\u03ba::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    \u03ba(x,y) = (1+\u221a(5)\u2016x-y\u2016 + 5/3\u2016x-y\u2016^2)exp(-\u221a(5)\u2016x-y\u2016)\n```\n\"\"\"\nstruct Matern52Kernel <: SimpleKernel end\n\nkappa(\u03ba::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} \u2192 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 \u2192 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 \u21a6 -\u03bc * sum( log(a*x_i+b), i=1,...,n )\"\nfun_params(f::LogBarrier) = \"a = $(f.a), b = $(f.b), \u03bc = $(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": "module problem124\n\ndescription = \"\"\"\nOrdered radicals\nThe radical of n, rad(n), is the product of the distinct prime factors of n. For example, 504 = 23 \u00d7 32 \u00d7 7, so rad(504) = 2 \u00d7 3 \u00d7 7 = 42.\nLet E(k) be the kth element in the sorted n column; for example, E(4) = 8 and E(6) = 9.\n\nIf rad(n) is sorted for 1 \u2264 n \u2264 100000, find E(10000).\n\"\"\n\n# Calculate rad for all values between 1 and n using algorithm similar to sieve of eratosthenes \nfunction radsieve(n)\n  rad = ones(Int, n)\n  for i = 2:n \n    if rad[i] == 1\n      for j = i:i:n\n        rad[j] *= i\n      end\n    end\n  end\n  return rad\nend\n\nfunction solve(n=100000, k=10000)\n  radsorted = sort(collect(enumerate(radsieve(n))), by = pr -> pr[2], alg=MergeSort)\n  return radsorted[k][1]\nend\n\nusing Base.Test\n\n@test radsieve(10) == [1, 2, 3, 2, 5, 6, 7, 2, 3, 10]\n@test solve(10, 4) == 8\n@test solve(10, 6) == 9\n\nend", "meta": {"hexsha": "f90dd95a0145107fed337e9f55c8abaa9a304b22", "size": 868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem124.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/problem124.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/problem124.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": 24.8, "max_line_length": 138, "alphanum_fraction": 0.6267281106, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7939394999599622}}
{"text": "using ModelingToolkit, MethodOfLines, LinearAlgebra, OrdinaryDiffEq\nusing ModelingToolkit: operation, istree, arguments\nusing DomainSets\nusing NonlinearSolve\n\n# # Define some variables\n@testset \"Heat Equation 1D 2 variables\" begin\n    @parameters t x\n    @variables u(..) v(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n    eqs = [Dt(u(t, x)) ~ Dxx(u(t, x)),\n        Dt(v(t, x)) ~ Dxx(v(t, x))]\n    bcs = [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\n    domains = [t \u2208 Interval(0.0, 1.0),\n        x \u2208 Interval(0.0, 1.0)]\n\n    @named pdesys = PDESystem(eqs, bcs, domains, [t, x], [u(t, x), v(t, x)])\n    discretization = MOLFiniteDifference([x => 0.1], t; grid_align=edge_align)\n    prob = discretize(pdesys, discretization) # This gives an ODEProblem since it's time-dependent\n    sol = solve(prob, Tsit5())\nend\n\n@testset \"Heat Equation 2D 1 variable\" begin\n    @parameters t x y\n    @variables u(..)\n    Dxx = Differential(x)^2\n    Dyy = Differential(y)^2\n    Dt = Differential(t)\n    t_min = 0.0\n    t_max = 2.0\n    x_min = 0.0\n    x_max = 2.0\n    y_min = 0.0\n    y_max = 2.0\n\n    # 3D PDE\n    eq = Dt(u(t, x, y)) ~ Dxx(u(t, x, y)) + Dyy(u(t, x, y))\n\n    analytic_sol_func(t, x, y) = exp(x + y) * cos(x + y + 4t)\n    # Initial and boundary conditions\n    bcs = [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\n    domains = [t \u2208 Interval(t_min, t_max),\n        x \u2208 Interval(x_min, x_max),\n        y \u2208 Interval(y_min, y_max)]\n    @named pdesys = PDESystem([eq], bcs, domains, [t, x, y], [u(t, x, y)])\n    # Method of lines discretization\n    dx = 0.1\n    dy = 0.2\n    discretization = MOLFiniteDifference([x => dx, y => dy], t)\n    prob = ModelingToolkit.discretize(pdesys, discretization)\n    sol = solve(prob, Tsit5())\nend\n\n# Diffusion in a sphere\n@testset \"Spherical Diffusion\" begin\n\n    @parameters t r\n    @variables u(..)\n    Dt = Differential(t)\n    Dr = Differential(r)\n    Drr = Dr^2\n    eq = Dt(u(t, r)) ~ 1 / r^2 * Dr(r^2 * Dr(u(t, r)))\n    bcs = [u(0, r) ~ -r * (r - 1) * sin(r),\n        Dr(u(t, 0)) ~ 0.0, u(t, 1) ~ sin(1)]\n\n    domains = [t \u2208 Interval(0.0, 1.0),\n        r \u2208 Interval(0.0, 1.0)]\n\n    @named pdesys = PDESystem(eq, bcs, domains, [t, r], [u(t, r)])\n    discretization = MOLFiniteDifference([r => 0.1], t)\n    prob = discretize(pdesys, discretization) # This gives an ODEProblem since it's time-dependent\n    sol = solve(prob, Tsit5())\nend\n\n@testset \"RHS = 0\" begin\n    @parameters x, t\n    @variables u(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dx2 = Differential(x)^2\n    Dx3 = Differential(x)^3\n    Dx4 = Differential(x)^4\n\n    \u03b1 = 1\n    \u03b2 = 4\n    \u03b3 = 1\n    eq = Dt(u(x, t)) + u(x, t) * Dx(u(x, t)) + \u03b1 * Dx2(u(x, t)) + \u03b2 * Dx3(u(x, t)) + \u03b3 * Dx4(u(x, t)) ~ 0\n\n    du(x, t; z=-x / 2 + t) = 15 / 2 * (tanh(z) + 1) * (3 * tanh(z) - 1) * sech(z)^2\n\n    bcs = [u(x, 0) ~ x^2,\n        Dx(u(-10, t)) ~ du(-10, t),\n        Dx(u(10, t)) ~ du(10, t)]\n\n    # Space and time domains\n    domains = [x \u2208 Interval(-10.0, 10.0),\n        t \u2208 Interval(0.0, 0.5)]\n    # Discretization\n    dx = 0.4\n    dt = 0.2\n\n    discretization = MOLFiniteDifference([x => dx], t; approx_order=4)\n    @named pdesys = PDESystem(eq, bcs, domains, [x, t], [u(x, t)])\n    prob = discretize(pdesys, discretization)\nend\n\n@testset \"Wave Equation\" begin\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)             # Required in ICs and equation\n    Dtt = Differential(t)^2           # required in equation\n    Dxxxx = Differential(x)^4       # required in equation\n    Dxx = Differential(x)^2         # required in BCs\n    # some parameters\n    EI = 291.6667\n    m = 1.3850\n    c = 1.0\n    p = 0.01\n    L = 2.0\n\n    # 1D PDE and boundaru conditions\n    eq = m * Dtt(u(t, x)) + c * Dt(u(t, x)) + EI * Dxxxx(u(t, x)) ~ 0\n\n    ic_bc = [u(0, x) ~ (p * x * (x^3 + L^3 - 2 * L * x^2) / (24 * EI)), #for all 0 < u < L\n        Dt(u(0, x)) ~ 0.0,        # for all 0 < u < L\n        u(t, 0) ~ 0.0,            # for all t > 0,, displacement zero at u=0\n        u(t, 2) ~ 0.0,            # for all t > 0,, displacement zero at u=L\n        Dxx(u(t, 0)) ~ 0.0,       # for all t > 0,, curvature zero at u=0\n        Dxx(u(t, 2)) ~ 0.0]       # for all t > 0,, curvature zero at u=L\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0, 2.0),\n        x \u2208 Interval(0.0, L)]\n\n    dt = 0.1   # dt related to saving the data.. not actual dt\n    # PDE sustem\n    @named pdesys = PDESystem(eq, ic_bc, domains, [t, x], [u(t, x)])\n\n    # Method of lines discretization\n    dx = 0.1\n    order = 2\n    discretization = MOLFiniteDifference([x => dx, t => dt], approx_order=order)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys, discretization)\n\n    # Solve the ODE problem\n    sol = NonlinearSolve.solve(prob, NewtonRaphson())\nend\n\n@testset \"Rearranged Robin\" begin\n    @parameters x t\n\n    @variables c(..)\n\n    \u2202t = Differential(t)\n    \u2202x = Differential(x)\n    \u2202\u00b2x = Differential(x)^2\n\n    D\u2080 = 1.0\n    R = 0.5\n    c\u2091 = 2.5\n    \u2113 = 2.0\n    \u03b1 = 1 / 3\n\n    diff_eq = \u2202t(c(x, t)) ~ \u2202x((D\u2080 + \u03b1 * c(x, t)) * \u2202x(c(x, t)))\n\n    bcs = [c(x, 0) ~ 0.0,         # initial condition\n        R * (D\u2080 + \u03b1 * c(0, t)) * \u2202x(c(0, t)) ~ c(0, t) - c\u2091, # Robin\n        \u2202x(c(\u2113, t)) ~ 0.0]   # no flux\n\n    domains = [t \u2208 Interval(0.0, 10.0),\n        x \u2208 Interval(0.0, \u2113)]\n\n    @named pdesys = PDESystem(diff_eq, bcs, domains, [t, x], [c(x, t)])\n\n    # Method of lines discretization\n    dx = 0.1\n    order = 2\n    discretization = MOLFiniteDifference([x => dx], t, approx_order=order)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys, discretization)\n\n    sol = solve(prob, Rodas4())\nend\n\n@testset \"Array u\" begin\n    # Dependencies\n    N = 6 # number of dependent variables\n\n    # Variables, parameters, and derivatives\n    @parameters x\n    @variables u[1:N](..)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    # Domain edges\n    x_min = 0.0\n    x_max = 1.0\n\n    # Discretization parameters\n    dx = 0.1\n    order = 2\n\n    #u = collect(u)\n\n    # Equations\n    eqs = Vector{ModelingToolkit.Equation}(undef, N)\n    for i = 1:N\n        eqs[i] = Dxx(u[i](x)) ~ u[i](x)\n    end\n\n    # Initial and boundary conditions\n    bcs = Vector{ModelingToolkit.Equation}(undef, 2 * N)\n    for i = 1:N\n        bcs[i] = Dx(u[i](x_min)) ~ 0.0\n    end\n\n    for i = 1:N\n        bcs[i+N] = u[i](x_max) ~ rand()\n    end\n\n    # Space and time domains\n    domains = [x \u2208 Interval(x_min, x_max)]\n\n    # PDE system\n    @named pdesys = PDESystem(eqs, bcs, domains, [x], collect([u[i](x) for i = 1:N]))\n\n    # Method of lines discretization\n    discretization = MOLFiniteDifference([x => dx], nothing, approx_order=order)\n    prob = ModelingToolkit.discretize(pdesys, discretization)\n\n    # # Solution of the ODE system\n    sol = NonlinearSolve.solve(prob, NewtonRaphson())\nend\n\n@testset \"Non-Uniform Grid\" 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    \u2207\u00b2(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.0\n\n    x_min = y_min = t_min = 0.0\n    x_max = y_max = 1.0\n    t_max = 11.5\n\n    \u03b1 = 10.0\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.0 + Dy(v(x, y, t)) * u(x, y, t)^2 - 4.4 * u(x, y, t) + \u03b1 * \u2207\u00b2(u(x, y, t)) + brusselator_f(x, y, t),\n        Dt(v(x, y, t)) ~ -3.4 * Dx(u(x, y, t)) - v(x, y, t) * u(x, y, t)^2 + \u03b1 * \u2207\u00b2(v(x, y, t))]\n\n    domains = [x \u2208 Interval(x_min, x_max),\n        y \u2208 Interval(y_min, y_max),\n        t \u2208 Interval(t_min, t_max)]\n\n    bcs = [u(x, y, 0) ~ u0(x, y, 0),\n        u(0, y, t) ~ 0.0,\n        u(1, y, t) ~ 0.0,\n        u(x, 0, t) ~ 0.0,\n        u(x, 1, t) ~ 0.0,\n        v(x, y, 0) ~ v0(x, y, 0),\n        v(0, y, t) ~ 0.0,\n        v(1, y, t) ~ 0.0,\n        v(x, 0, t) ~ 0.0,\n        v(x, 1, t) ~ 0.0]\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 = 5\n\n    dx = [0.0, cumsum(rand(0.05:0.01:0.2, 5))...]\n    if dx[end] < 1.0\n        push!(dx, 1.0)\n    end\n\n    dy = [0.0, cumsum(rand(0.05:0.01:0.2, 5))...]\n    if dy[end] < 1.0\n        push!(dy, 1.0)\n    end\n\n    order = 2\n\n    discretization = MOLFiniteDifference([x => dx, y => dy], t, approx_order=order)\n\n    prob = discretize(pdesys, discretization)\n\n    sol = solve(prob, TRBDF2())\n\nend\n\n@testset \"2D variable connected to 1D variable at boundary #33\" begin\n    @parameters t x r\n    @variables u(..) v(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n    Dr = Differential(r)\n    Drr = Differential(r)^2\n\n    s = u(t, x) + v(t, x, 1)\n\n    eqs = [Dt(u(t, x)) ~ Dxx(u(t, x)) + s,\n        Dt(v(t, x, r)) ~ Drr(v(t, x, r))]\n    bcs = [u(0, x) ~ 1,\n        v(0, x, r) ~ 1,\n        Dx(u(t, 0)) ~ 0.0, Dx(u(t, 1)) ~ 0.0,\n        Dr(v(t, x, 0)) ~ 0.0, Dr(v(t, x, 1)) ~ s]\n\n    domains = [t \u2208 Interval(0.0, 1.0),\n        x \u2208 Interval(0.0, 1.0),\n        r \u2208 Interval(0.0, 1.0)]\n\n    @named pdesys = PDESystem(eqs, bcs, domains, [t, x, r], [u(t, x), v(t, x, r)])\n\n    # Method of lines discretization\n    dx = 0.1\n    dr = 0.1\n    order = 2\n    discretization = MOLFiniteDifference([x => dx, r => dr], t, approx_order=order)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys, discretization)\n\n    sol = solve(prob, Tsit5())\nend\n\n\n\n\n@testset \"Testing discretization of varied systems\" begin\n    @parameters x t\n\n    @variables c(..)\n\n    \u2202t = Differential(t)\n    \u2202x = Differential(x)\n    \u2202\u00b2x = Differential(x)^2\n\n    D\u2080 = 1.5\n    \u03b1 = 0.15\n    \u03c7 = 1.2\n    R = 0.1\n    c\u2091 = 2.0\n    \u2113 = 1.0\n    \u0394x = 0.1\n\n    bcs = [\n        # initial condition\n        c(x, 0) ~ 0.0,\n        # Robin BC\n        \u2202x(c(0.0, t)) / (1 + exp(\u03b1 * (c(0.0, t) - \u03c7))) * R * D\u2080 + c\u2091 - c(0.0, t) ~ 0.0,\n        # no flux BC\n        \u2202x(c(\u2113, t)) ~ 0.0]\n\n\n    # define space-time plane\n    domains = [x \u2208 Interval(0.0, \u2113), t \u2208 Interval(0.0, 5.0)]\n\n    @testset \"Test 01: \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\" begin\n        D = D\u2080 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7)))\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 02: \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\" begin\n        D = 1.0 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7)))\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 03: \u2202t(c(x, t)) ~ \u2202x(1.0 / (1.0/D\u2080 + exp(\u03b1 * (c(x, t) - \u03c7))/D\u2080) * \u2202x(c(x, t)))\" begin\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(1.0 / (1.0 / D\u2080 + exp(\u03b1 * (c(x, t) - \u03c7)) / D\u2080) * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 04: \u2202t(c(x, t)) ~ \u2202x(D\u2080 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7))) * \u2202x(c(x, t)))\" begin\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(D\u2080 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7))) * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 05: \u2202t(c(x, t)) ~ \u2202x(1/x * \u2202x(c(x, t)))\" begin\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(1 / x * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 06: \u2202t(c(x, t)) ~ \u2202x(x*\u2202x(c(x, t)))/c(x,t)\" begin\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(x * \u2202x(c(x, t))) / c(x, t)\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 07: \u2202t(c(x, t)) ~ \u2202x(1/(1+c(x,t)) \u2202x(c(x, t)))\" begin\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(1 / (1 + c(x, t)) * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 08: \u2202t(c(x, t)) ~ c(x, t) * \u2202x(c(x,t) * \u2202x(c(x, t)))\" begin\n        diff_eq = \u2202t(c(x, t)) ~ c(x, t) * \u2202x(c(x, t) * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 09: \u2202t(c(x, t)) ~ c(x, t) * \u2202x(c(x,t) * \u2202x(c(x, t)))/(1+c(x,t))\" begin\n        diff_eq = c(x, t) * \u2202x(c(x, t) * \u2202x(c(x, t))) / (1 + c(x, t))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 10: \u2202t(c(x, t)) ~ c(x, t) * \u2202x(c(x,t) * \u2202x(c(x, t)))/(1+c(x,t))\" begin\n        diff_eq = c(x, t) * \u2202x(c(x, t)^(-1) * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\n    @testset \"Test 11: \u2202t(c(x, t)) ~ \u2202x(1/(1+c(x,t)^2) \u2202x(c(x, t)))\" begin\n        diff_eq = \u2202t(c(x, t)) ~ \u2202x(1 / (1 + c(x, t)^2) * \u2202x(c(x, t)))\n        @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)])\n        discretization = MOLFiniteDifference([x => \u0394x], t)\n    end\n\nend\n", "meta": {"hexsha": "20910f05902e94da507b9e6f6f0a5af26072eb2b", "size": 13790, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pde_systems/MOLtest.jl", "max_stars_repo_name": "SciML/MethodOfLines.jl", "max_stars_repo_head_hexsha": "60018ac8d4e52d27ea810d05687765fff5f983d4", "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/MOLtest.jl", "max_issues_repo_name": "xtalax/MethodOfLines.jl", "max_issues_repo_head_hexsha": "855edcd693b05feec2de6a6fff2f1c9f8364da50", "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/MOLtest.jl", "max_forks_repo_name": "xtalax/MethodOfLines.jl", "max_forks_repo_head_hexsha": "855edcd693b05feec2de6a6fff2f1c9f8364da50", "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": 30.4415011038, "max_line_length": 128, "alphanum_fraction": 0.5102248006, "num_tokens": 5521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7939394990345066}}
{"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\u03bc\u2080 = 0.0 # => \u03bc\n\u03ba\u2080 = 1.0 # => \u03bd, which scales the precision of the Normal\n\u03b1\u2080 = 2.0 # => \"shape\"\n\u03b2\u2080 = 3.0 # => \"rate\", which is 1 / \u03b8, where \u03b8 is \"scale\"\n\n# prior\npri = NormalGamma(\u03bc\u2080, \u03ba\u2080, \u03b1\u2080, \u03b2\u2080)\n\n# posterior\npost = posterior(pri, Normal, x)\n\n# marginal distribution of \u03c4 = 1 / \u03c3\u00b2\n# Eq. (90) in \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy\n# `scale(post)` = \u03b8\np_\u03c4 = Gamma(post.shape, scale(post))\np_\u03c3\u00b2_pdf = z -> pdf(p_\u03c4, 1 / z) # \u03c4 => 1 / \u03c3\u00b2 \n\n# marginal of \u03bc\n# Eq. (91) in \"Conjugate Bayesian analysis of the Gaussian distribution\" by Murphy\np_\u03bc = TDist(2 * post.shape)\n\n\u03bc\u2099 = post.mu    # \u03bc \u2192 \u03bc\n\u03ba\u2099 = post.nu    # \u03ba \u2192 \u03bd\n\u03b1\u2099 = post.shape # \u03b1 \u2192 shape\n\u03b2\u2099 = post.rate  # \u03b2 \u2192 rate\n\n# numerically more stable but doesn't seem to have effect; issue is probably internal to\n# `pdf` which needs to compute \u2248 \u0393(1000) \np_\u03bc_pdf = z -> exp(logpdf(p_\u03bc, (z - \u03bc\u2099) * exp(- 0.5 * log(\u03b2\u2099) + 0.5 * log(\u03b1\u2099) + 0.5 * log(\u03ba\u2099))))\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\u0394 = 0.001\nr = 0.75:0.001:1.50\nnorm_const = sum(p_\u03c3\u00b2_pdf.(r) .* \u0394)\nplot!(r, p_\u03c3\u00b2_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\u0394 = 0.0001\nr = -0.1 + mean(x):\u0394:0.1 + mean(x)\nnorm_const = sum(p_\u03bc_pdf.(r) .* \u0394)\nplot!(r, z -> p_\u03bc_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    \u03c3\u2082 ~ 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, \u03c3\u2082)\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[:\u03c3\u2082]...)]\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[:\u03c3\u2082]...)...]]\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    \u03b1 = mean(p.intercept)\n    \u03b2 = collect(mean.(p.coefficients))\n    return  \u03b1 .+ x * \u03b2\nend\n\n\n# Make a prediction using samples from the variational posterior given an input vector.\nfunction prediction(samples::AbstractVector, sym2ranges, x)\n    \u03b1 = mean(samples[union(sym2ranges[:intercept]...)])\n    \u03b2 = vec(mean(samples[union(sym2ranges[:coefficients]...)]; dims = 2))\n    return  \u03b1 .+ x * \u03b2\nend\n\nfunction prediction(samples::AbstractMatrix, sym2ranges, x)\n    \u03b1 = mean(samples[union(sym2ranges[:intercept]...), :])\n    \u03b2 = vec(mean(samples[union(sym2ranges[:coefficients]...), :]; dims = 2))\n    return  \u03b1 .+ x * \u03b2\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 \u00b1 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 \u00b1 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(\u03b8)\n    d = length(\u03b8) \u00f7 2\n    A = @inbounds \u03b8[1:d]\n    b = @inbounds \u03b8[d + 1: 2 * d]\n    \n    b = to_constrained \u2218 Shift(b; dim = Val(1)) \u2218 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(\u03b8)\n    L, b = begin\n        @unpack L, b = ComponentArray(\u03b8, 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 \u2218 Shift(b; dim = Val(1)) \u2218 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 \u00b1 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 \u00b1 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 \u00b1 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\u03b8 = \u03c0/8        # 8 angular bins hardwired\n        \u03b8_l = d\u03b8*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        \u03b8  = mod.(atan.(sy, sx).+\u03c0 .-\u03b8_l,2*\u03c0)\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.(\u03b8.-\u03c0).<= d\u03b8) .& (abs.(r.-jrad) .<= 1)\n        # -------- angular part\n        ang = cos.((\u03b8.-\u03c0).*4)\n        # -------- radial part\n        rad = cos.((r.-jrad).*\u03c0./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\u03b8   = \u03c0/8        # 8 angular bins hardwired\n        dx   = nx\u00f72-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        \u03b8    = zeros(Float64, nx, nx)\n\n        for l = 0:L-1\n            \u03b8_l = d\u03b8*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                    \u03b8_pix  = mod(atan(sy, sx)+\u03c0 -\u03b8_l, 2*\u03c0)\n                    \u03b8_good = abs(\u03b8_pix-\u03c0) <= (d\u03b8*wid)\n\n                    # If this is a pixel we might use, calculate log2(r)\n                    if \u03b8_good\n                        anggood[y, x] = \u03b8_good\n                        \u03b8[y, x]       = \u03b8_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.((\u03b8[angmask].-\u03c0).*(4/wid))\n\n        # -------- loop over j for the radial part\n            for j = 0:J-1\n                jrad  = 7-j\n                \u0394j    = abs.(logr[angmask].-jrad)\n                rmask = (\u0394j .<= 1)\n\n        # -------- radial part\n                F_radial = cos.(\u0394j[rmask] .* (\u03c0/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": "#=\nGiven a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.\n\nFor example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.\n\nFollow-up: Can you do this in O(N) time and constant space?\n=#\n\nusing Test\ninclude(\"Solutions/problem9_sum_notadjacentnumbers.jl\")\n@test sum_notadjacent([2, 4, 6, 2, 5]) == 13\n@test sum_notadjacent([5, 1, 1, 5]) == 10\n@test sum_notadjacent([-3, -4, -7, 1, 0, 1]) == 2\n", "meta": {"hexsha": "17fe5ba084488e4f3379169051c3150f1d539107", "size": 528, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tests/problem9_sum_notadjacentnumbers_test.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": "Tests/problem9_sum_notadjacentnumbers_test.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": "Tests/problem9_sum_notadjacentnumbers_test.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": 37.7142857143, "max_line_length": 127, "alphanum_fraction": 0.6818181818, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.8933093975331751, "lm_q1q2_score": 0.7939365718386766}}
{"text": "function rand_candecomp{N}(r::Int64, dims::NTuple{N, Int};\n                           lambdas_nonneg::Bool=false, factors_nonneg::Bool=false)\n    rnd_factor = factors_nonneg ? x -> abs.(randn(x...)) : randn\n    rnd_lambda = lambdas_nonneg ? x -> abs.(randn(x...)) : randn\n    return CANDECOMP((Matrix{Float64}[rnd_factor((s, r)) for s in dims]...),\n                     rnd_lambda(r))\nend\n\nrand_kruskal3{N}(r::Int64, dims::NTuple{N, Int}, nonnegative::Bool) =\n    compose(rand_candecomp(r, dims, lambdas_nonneg=nonnegative, factors_nonneg=nonnegative))\n\nfunction rand_tucker{N}(core_dims::NTuple{N, Int}, dims::NTuple{N, Int};\n                        core_nonneg::Bool=false, factors_nonneg::Bool=false)\n    rnd_factor = factors_nonneg ? x -> abs.(randn(x...)) : randn\n    rnd_core = core_nonneg ? x -> abs.(randn(x...)) : randn\n    return Tucker((Matrix{Float64}[rnd_factor((dims[i], core_dims[i])) for i in 1:N]...),\n                  rnd_core(core_dims))\nend\n\nfunction add_noise{T, N}(tnsr::Array{T,N}, sn_ratio = 0.6, nonnegative::Bool = false)\n    tnsr_noise = randn(size(tnsr)...)\n    if nonnegative\n        map!(x -> max(0.0, x), tnsr_noise, tnsr_noise)\n    end\n    tnsr + 10^(-sn_ratio/0.2)*vecnorm(tnsr)/vecnorm(tnsr)*tnsr_noise\nend\n", "meta": {"hexsha": "5451b05e5706e791c9eb280a52c84d209d7a0df9", "size": 1242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/helpers.jl", "max_stars_repo_name": "TensorFactorization/TensorDecompositions.jl", "max_stars_repo_head_hexsha": "7e4766cd878905534c7b7295ce9d91dd7dc1bd71", "max_stars_repo_licenses": ["MIT"], "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/helpers.jl", "max_issues_repo_name": "TensorFactorization/TensorDecompositions.jl", "max_issues_repo_head_hexsha": "7e4766cd878905534c7b7295ce9d91dd7dc1bd71", "max_issues_repo_licenses": ["MIT"], "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/helpers.jl", "max_forks_repo_name": "TensorFactorization/TensorDecompositions.jl", "max_forks_repo_head_hexsha": "7e4766cd878905534c7b7295ce9d91dd7dc1bd71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-26T23:43:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-26T23:43:37.000Z", "avg_line_length": 46.0, "max_line_length": 92, "alphanum_fraction": 0.6304347826, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8438951025545427, "lm_q1q2_score": 0.793927861932945}}
{"text": "using Random, Distributions, StatsPlots, Plots; pyplot()\nRandom.seed!(0)\n \nmu = 20\nd1, d2 = Normal(mu,mu), Exponential(mu)\n \nn = 100\ndata1 = rand(d1,n)\ndata2 = rand(d2,n)\n \nqqnorm(data1, c=:blue, ms=3, msw=0, label=\"Normal Data\")\nqqnorm!(data2, c=:red, ms=3, msw=0, label=\"Exponential Data\",\n        xlabel=\"Normal Theoretical Quantiles\",\n        ylabel=\"Data Quantiles\", legend=true)", "meta": {"hexsha": "a83a71610ccfd1fa646fed20d9792e32761cc4d9", "size": 384, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4_chapter/normalProbabilityPlot.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": "4_chapter/normalProbabilityPlot.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": "4_chapter/normalProbabilityPlot.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.4285714286, "max_line_length": 61, "alphanum_fraction": 0.6666666667, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7939278609778007}}
{"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\u2080, P\u2080 = zeros(2), diagm(ones(2))\n\n    x\u2080 = rand(rg, MvNormal(m\u2080, P\u2080))\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\u2080\n\n    y[1]      = rand(rg, MvNormal(H * x[1], R))\n\n    yclean[1] = H * x\u2080\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\u2080, P\u2080\n\nend\n\n\nfunction runExample_4_2(seed = 1)\n\n    # Simulate data\n\n    yclean, y, x, A, H, Q, R, m\u2080, P\u2080 = Example_4_2(seed=seed)\n\n\n    # Inference\n\n    \u03bcfilter, \u03a3filter = filteringrecursion(y; A = A, H = H, Q = Q, R = R, m\u2080 = m\u2080, P\u2080 = P\u2080)\n\n    \u03bcsmooth, \u03a3smooth = smoothingrecursion(y; A = A, H = H, Q = Q, R = R, m = \u03bcfilter, P = \u03a3filter)\n\n\n    # collect positions\n\n    truepositions = reduce(hcat, [x\u2096[1:2] for x\u2096 in x])\n\n    filtpositions = reduce(hcat, [x\u2096[1:2] for x\u2096 in \u03bcfilter])\n\n    smoopositions = reduce(hcat, [x\u2096[1:2] for x\u2096 in \u03bcsmooth])\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\u03c0; -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 \u2208 1:3\n    for j \u2208 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\u03a8 = SInDy(sol[:,:], DX, basis, \u03f5 = 1e-10)\n\n# Transform into ODE System\nsys = ODESystem(\u03a8)\n\n# Simulate\nestimator = ODEProblem(dynamics(\u03a8), 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_) # \u2248 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": "import FastTransforms\nimport QuadratureRules: chebyshev_points, shift_nodes\n\n@testset \"$(rpad(\"Gau\u00df-Chebyshev\",80))\" begin\n\n    for s in 2:10\n        @test GaussChebyshevQuadrature(s) == ChebyshevQuadrature(s, 1)\n        @test GaussChebyshevQuadrature(s) == ChebyshevQuadrature(Float64, s, Val(1))\n        \n        @test sum(weights(GaussChebyshevQuadrature(s))) \u2248 1\n\n        c = shift_nodes(reverse(FastTransforms.chebyshevpoints(Float64, s, Val(1))))\n\n        @test chebyshev_points(Float64, s, Val(1)) \u2248 c\n        @test nodes(GaussChebyshevQuadrature(s))   \u2248 c\n\n        # TODO test weights\n\n    end\n\nend\n", "meta": {"hexsha": "8cd0201bae23b1a91c3dfc841b77168c1d846b1a", "size": 607, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gauss_chebyshev.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": "test/test_gauss_chebyshev.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": "test/test_gauss_chebyshev.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": 27.5909090909, "max_line_length": 84, "alphanum_fraction": 0.6705107084, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7938034501333606}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Wave equation\n# ## Solving the wave equation\n\nstruct Wave\n    f\n    g\n    c\nend\n\n# ### Exercise:\n# \n# Write the function `solve_wave(T, L, wave::Wave; n_t=100, n_x=100)` that solves the wave \n# equation.\n# \n# **Hint**: Follow the procedure from the previous exercise. Discretize time and space, \n# initialize the solution, add the boundary conditions, add the initial conditions and \n# finally, iterate over time.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n\nusing Plots\n\nfunction plot_wave(y, file_name; fps = 60, kwargs...)\n    anim = @animate for (i, y_row) in enumerate(eachrow(y))\n        plot(\n            y_row;\n            title = \"t = $(i-1)\u0394t\",\n            xlabel = \"x\",\n            ylabel = \"y(t, x)\",\n            legend = false,\n            linewidth = 2,\n            kwargs...\n        )\n    end\n    gif(anim, file_name; fps, show_msg = false)\n    \n    return nothing\nend\n\n# ### Exercise:\n# \n# Solve the wave equation for $L=\\frac32\\pi$, $T=240$, $c=0.02$ and the initial \n# conditions\n# \n# $$\n# \\begin{aligned}\n# f(x) &= 2e^{-(x-\\frac L2)^2} + \\frac{x}{L}, \\\\\n# g(x) &= 0.\n# \\end{aligned}\n# $$\n# \n# Use time discretization with stepsize $\\Delta t=1$ and the space discretization with \n# number of points $n_x=101$ and $n_x=7$ steps. Plot two graphs.\n# \n# ---\n# ### Solution:\n", "meta": {"hexsha": "d17884d4f4e3857976141d6d8b428cd8e2fb0550", "size": 1313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_13/01-ode.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_13/01-ode.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_13/01-ode.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": 20.2, "max_line_length": 91, "alphanum_fraction": 0.5765422696, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7937550006188286}}
{"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": "using JLD\nusing PyPlot\nusing StatsBase\nusing Distributions\nusing VBMatrixFactorization\n\nfunction toy_matrix(L, M, H, std)\n    # B is a random matrix whose columns we select from\n    B = randn(L, H) \n    # A is the sparse matrix that selects the columns from A\n    A = zeros(M, H)\n    for m in 1:M\n        A[m, rand(1:H)] = 1\n    end\n    \n    Y = B*A' + rand(Normal(0, std), L, M)\n    return Y, A, B\nend\n\nL = 10\nM = 20\nH = 2\nY_toy, A_toy, B_toy = toy_matrix(L, M, H, 0.05);\n\n# first, initialize a variable of the vbmf_parameters type\n# then use it to run the basic vbmf algorithm\n# here, the whole run is saved into the data_path folder\n# if desc is not specified, then the subfolder with the actual data \n# is named using date and time\n\nprintln(\" ----------- Basic VB Matrix factorization ---------------- \")\nprintln(\"\")\nparams_init = VBMatrixFactorization.vbmf_init(Y_toy, H, ca = 0.1, cb = 0.1, sigma2 = 0.1);\ndata_path = \"./data\"\nres_vbmf = VBMatrixFactorization.vbmf(Y_toy, params_init, 100, est_covs = true, est_var = true, verb = true, \n    logdir = data_path, desc = \"vbmf_test\");\nerr = norm(Y_toy - res_vbmf.YHat)\nprintln(\"||Y - Yhat|| = $err\")\n\n# this is how the log is loaded and used\nvbmf_log, data, priors = VBMatrixFactorization.load_log(string(data_path,\"/vbmf_test\"));\nparams_vbmf = VBMatrixFactorization.vbmf_parameters(); # dummy variable to store individual step data\n\niter = 3\ntime_slice = VBMatrixFactorization.extract_params!(vbmf_log, iter, params_vbmf);\nerr = norm(Y_toy - time_slice.YHat)\nprintln(\"in iteration number $iter, the error was ||Y - Yhat|| = $err\")\nprintln(\"\")\n\n# vbmf_sparse usage\nprintln(\" ----------- VB Matrix factorization with sparse A ---------------- \")\nprintln(\"\")\nparams_sparse_init = VBMatrixFactorization.vbmf_sparse_init(Y_toy, H, ca = 0.1, cb = 0.1, sigma = 0.1);\nparams_sparse_init.AHat = A_toy\nsparse_vbmf = VBMatrixFactorization.vbmf_sparse(Y_toy, params_sparse_init, 100, diag_var = false, verb = true, \n    logdir = data_path, desc = \"sparse_test\", full_cov = true);\nerr = norm(Y_toy - sparse_vbmf.YHat)\nprintln(\"||Y - Yhat|| = $err\")\nprintln(\"\")\n# compare the results\n\nprintln(\" original A          basic reconstruction          sparse reconstruction with true start\")\nfor m in 1:M\n    println(A_toy[m,:],\"   \", res_vbmf.AHat[m,:], \"   \", sparse_vbmf.AHat[m,:])\nend\n", "meta": {"hexsha": "3e3b33c0c49668a897b81ede41c44cc1bf1ea819", "size": 2322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/toy_data.jl", "max_stars_repo_name": "vitskvara/VBMatrixFactorization.jl", "max_stars_repo_head_hexsha": "b73fcc63e3a164749a07fa93bc39ba3365946b72", "max_stars_repo_licenses": ["MIT"], "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/toy_data.jl", "max_issues_repo_name": "vitskvara/VBMatrixFactorization.jl", "max_issues_repo_head_hexsha": "b73fcc63e3a164749a07fa93bc39ba3365946b72", "max_issues_repo_licenses": ["MIT"], "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/toy_data.jl", "max_forks_repo_name": "vitskvara/VBMatrixFactorization.jl", "max_forks_repo_head_hexsha": "b73fcc63e3a164749a07fa93bc39ba3365946b72", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 111, "alphanum_fraction": 0.6817398794, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8723473763375644, "lm_q1q2_score": 0.7937549915596763}}
{"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": "using Plots\n\n\n\nfunction michalewicz(x; m=10)\n    return -sum(sin(v)*sin(i*v^2/\u03c0)^(2m) for\n        (i,v) in enumerate(x));\nend\n\n# plot\n\nheatmap(0:0.1:4, 0:0.1:4, (x, y)->michalewicz([x, y]))\n", "meta": {"hexsha": "f7838147cb83d1614be62c4df3401b0d3bf64e0f", "size": 190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_function/michalewicz_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/michalewicz_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/michalewicz_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": 14.6153846154, "max_line_length": 54, "alphanum_fraction": 0.5736842105, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9653811621568289, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7937259004390401}}
{"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\u2020\nJOURNAL OF COMPUTATIONAL PHYSICS 124, 93\u2013114 (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, \u03be, \u03b7)\n        X, Y = tan(\u03c0 * \u03be / 4), tan(\u03c0 * \u03b7 / 4)\n        \u03b61 = sR / sqrt(X^2 + Y^2 + 1)\n        \u03b62, \u03b63 = X * \u03b61, Y * \u03b61\n        \u03b61, \u03b62, \u03b63\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\u2020\nJOURNAL OF COMPUTATIONAL PHYSICS 124, 93\u2013114 (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\u03b1    =  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) + \u03b1\n\t\t\u03b1    =   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# \u03b1    =  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) + \u03b1\n\t# \t\u03b1    =   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": "# ------------------------------------------------------------------------------------------\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\n# beyond using a single neuron and use *multiple* neurons to get multiple outputs. We can\n# 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\n# between bananas, grapes, **and** apples. To do this properly, we'll need to add more\n# 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\n# neural network takes in data and then spits out `0` or `1` predictions that together\n# declare what kind of fruit the picture is. However, what if we instead put the output of\n# 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: 500px;\"/>\n#\n# On the left we have 3 data points in blue. Those 3 data points each get fed into 4 neurons\n# in purple. Each of those 4 neurons produces a single output, but those output are each fed\n# into three neurons (the second layer of purple). Each of those 3 neurons spits out a\n# single value, and those values are fed as inputs into the last layer of 6 neurons. The 6\n# values that those final neurons produce are the output of the neural network. This is a\n# 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\n# before: why would sticking the output from neurons into other neurons help us fit the data\n# better? The answer can be understood by drawing pictures. Geometrically, the matrix\n# multiplication inside of a layer of neurons is streching and rotating the axis that we can\n# vary:\n#\n# [Show linear transformation of axis, with data]\n#\n# A nonlinear transformation, such as the sigmoid function, then adds a bump to the line:\n#\n# [Show the linear transformed axis with data, and then a bumped version that fits the data\n# better]\n#\n# Now let's repeat this process. When we send the data through another layer of neurons, we\n# get another rotation and another bump:\n#\n# [Show another rotation, then another bump]\n#\n# Visually, we see that if we keep doing this process we can make the axis line up with any\n# data. What this means is that **if we have enough layers, then our neural network can\n# approximate any model**.\n#\n# The trade-off is that with more layers we have more parameters, so it may be harder (i.e.\n# computationally intensive) to train the neural network. But we have the guarantee that the\n# 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\n# gradient descent method on this much larger model (but more efficiently!) and we can make\n# it classify our data correctly. This is the power of deep learning.\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "d9ad789b4a6ab846e0a23468fbd9454eec49d5a3", "size": 3464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/17. ML - Introduction to deep 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/17. ML - Introduction to deep 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/17. ML - Introduction to deep 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": 55.8709677419, "max_line_length": 92, "alphanum_fraction": 0.6769630485, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7936723545491947}}
{"text": "\"\"\"\n`smooth(y, span=5)`\n\nSmooth a vector using a moving average filter. Endpoints are handled by\ncollapsing the length of the filter as showed below.\n```\nyy[1] = y[1]\nyy[2] = (y[1] + y[2] + y[3]) / 3\nyy[3] = (y[1] + y[2] + y[3] + y[4] + y[5]) / 5\nyy[4] = (y[2] + y[3] + y[4] + y[4] + y[6]) / 5\n```\n\n**Arguments**\n- `y`: Array of values.\n\n**Optional Arguments**\n- `span`: Filter length.\n\n**Returns**\n- `yy`: Smoothed array of values.\n\"\"\"\nfunction smooth(y, span=5)\n\n    halfspan = floor(span/2)\n    n = length(y)\n    yy = fill(NaN, n)\n\n    for i = 1:n\n\n        ispan = min(i-1, n-i, halfspan)\n        ileft = convert(Int, i-ispan)\n        iright = convert(Int, i+ispan)\n\n        yy[i] = mean(y[ileft:iright])\n\n    end\n\n    return yy\n\nend\n", "meta": {"hexsha": "c387d0e602a8868a0956a5b0f176298bf1ffef3f", "size": 737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MiscFunctions/smooth.jl", "max_stars_repo_name": "vkumpost/stoosc", "max_stars_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MiscFunctions/smooth.jl", "max_issues_repo_name": "vkumpost/stoosc", "max_issues_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MiscFunctions/smooth.jl", "max_forks_repo_name": "vkumpost/stoosc", "max_forks_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_forks_repo_licenses": ["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.9756097561, "max_line_length": 71, "alphanum_fraction": 0.5440976934, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.7936723483900487}}
{"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 \u2208 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": "#############################################################################\n#############################################################################\n#\n# This file contains units tests for polynomial factorization\n#                                                                               \n#############################################################################\n#############################################################################\n\n\n\"\"\"\nTest factorization of polynomials.\n\"\"\"\nfunction factor_test_poly(;N::Int = 25, seed::Int = 0, primes::Vector{Int} = [3,5,7,17,19])\n    Random.seed!(seed)\n    for prime in primes\n        print(\"\\ndoing prime = $prime \\t\")\n        for _ in 1:N\n            print(\".\")\n            p = rand(Polynomial)\n            factorization = factor(p, prime)\n            pr = mod(expand_factorization(factorization),prime)\n            @assert mod(p-pr,prime) == 0 \n        end\n    end\n\n    println(\"\\nfactor_test_poly - PASSED\")\nend\n\n\"\"\"\nTest factorization of polynomials modulo p.\n\"\"\"\nfunction factor_test_poly_mod_p(;N::Int = 10, seed::Int = 0, primes::Vector{Int} = primes(3,25))\n    Random.seed!(seed)\n    x = x_poly()\n    for prime in primes\n        print(\"\\ndoing prime = $prime \\t\")\n        for _ in 1:N\n            print(\".\")\n            # Limiting to a polynomial of degree 6 since the ddfactor function scales poorly with an increase in the degree of the input polynomial\n            p = rand(Polynomial, degree = rand(1:6))\n            pmod = PolynomialModP(p, prime)\n            factorization = factor(pmod)\n            pr = mod(expand_factorization(factorization),prime)\n            @assert mod(pmod.terms-pr,prime) == 0 \n        end\n    end\n\n    println(\"\\nfactor_test_poly_mod_p - PASSED\")\nend", "meta": {"hexsha": "53081888120104e70ec0779c96aaffb1668474cf", "size": 1755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/factorization_test.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": "test/factorization_test.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": "test/factorization_test.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": 35.8163265306, "max_line_length": 147, "alphanum_fraction": 0.4689458689, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7936610241141677}}
{"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 - \u03bc}\\\\right)^2 }\n```\nwhere ``n`` is the length of the input and ``\u03bc`` 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 - \u03bc}\\\\right)^2 }}\n```\nwhere ``n`` is the length of the input and ``\u03bc`` 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        \u03b8\u2081::T\r\n        C::T\r\n        to_power::AbstractVector{T}\r\n        \u03b3::AbstractVector{T}\r\n        \u03c1::T\r\n        \u03b4::AbstractVector{T}\r\nend\r\nfunction MoschopoulosParameters(\u03b1,\u03b8)\r\n    T = Base.promote_eltype(\u03b1,\u03b8,[1.0])\r\n    \u03b1 = T.(\u03b1)\r\n    \u03b8 = T.(\u03b8)\r\n    \u03b4 = T.([1])\r\n    \u03b8\u2081 = Base.minimum(\u03b8)\r\n    C = exp(sum(\u03b1 .* log.(\u03b8\u2081 ./ \u03b8)))\r\n    \u03c1 = sum(\u03b1)\r\n    to_power = (-\u03b8\u2081 ./ \u03b8) .+1\r\n    \u03b3 = [sum(\u03b1 .* to_power)] # gamma1\r\n    return MoschopoulosParameters(\u03b8\u2081,C,to_power,\u03b3,\u03c1,\u03b4)\r\nend\r\nBase.eltype(::MoschopoulosParameters{T}) where T = T\r\n\r\n\r\n\r\n\"\"\"\r\n    UnivariateGammaConvolution(\u03b1,\u03b8)\r\n\r\nConstructs a distribution that corresponds to the convolutions of Gamma(\u03b1[i],\u03b8[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    \u03b1::AbstractVector{T}\r\n    \u03b8::AbstractVector{T}\r\n    P::MoschopoulosParameters{T}\r\nend\r\n\r\nn(x::UnivariateGammaConvolution) = length(x.\u03b1)\r\n\r\nfunction Base.show(io::IO, m::UnivariateGammaConvolution) \r\n    println(\"Univariate Gamma Convolutions with parametrisation:\")\r\n    display([Text.([\"\u03b1\" \"\u03b8\"]); [m.\u03b1 m.\u03b8]])\r\nend\r\n\r\n# Constructors :\r\nUnivariateGammaConvolution(\u03b1::Real,\u03b8::Real) = Distributions.Gamma(\u03b1,\u03b8)\r\nfunction UnivariateGammaConvolution(\u03b1::AbstractVector{T1},\u03b8::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(\u03b1,\u03b8,[1.0]) # At least float.\r\n    \u03b1 = T.(\u03b1)\r\n    \u03b8 = T.(\u03b8)\r\n    tol = eps(T) # Arbitrary fixed tolerence ! \r\n    \r\n    order = sortperm(\u03b8)\r\n    n = length(\u03b8)\r\n    \u03b8 = \u03b8[order]\r\n    \u03b1 = \u03b1[order]\r\n    for i in 1:n\r\n        if i < length(\u03b8)\r\n            for j in (i+1):n\r\n                if j <= length(\u03b8)\r\n                    if abs(\u03b8[i] - \u03b8[j]) <= tol\r\n                        new_\u03b1 = \u03b1[i]+\u03b1[j]\r\n                        new_\u03b8 = (\u03b1[i]*\u03b8[i]+\u03b1[j]*\u03b8[j])/(new_\u03b1)\r\n                        \u03b1[i] = new_\u03b1\r\n                        \u03b8[i] = new_\u03b8\r\n                        deleteat!(\u03b1,j)\r\n                        deleteat!(\u03b8,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 = (\u03b1 .> tol) .& (\u03b8 .> tol) .* (\u03b1.*\u03b8 .> tol)\r\n    \u03b1 = \u03b1[to_be_kept]\r\n    \u03b8 = \u03b8[to_be_kept]\r\n\r\n    if length(\u03b1) == 1\r\n        return Distributions.Gamma(\u03b1[1],\u03b8[1])\r\n    end\r\n    return UnivariateGammaConvolution(\u03b1,\u03b8,MoschopoulosParameters(\u03b1,\u03b8))\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.\u03b1[1])\r\nBase.convert(::Type{UnivariateGammaConvolution{T}}, d::UnivariateGammaConvolution{S}) where {T <: Real, S <: Real} = UnivariateGammaConvolution(T.(d.\u03b1), T.(d.\u03b8))\r\n\r\n#### parameters\r\nshapes(d::UnivariateGammaConvolution) = d.\u03b1\r\nscales(d::UnivariateGammaConvolution) = d.\u03b8\r\nrates(d::UnivariateGammaConvolution) = 1 / d.\u03b8\r\n\r\n\r\n#### Statistics\r\nmean(d::UnivariateGammaConvolution) = sum(d.\u03b1 .* d.\u03b8)\r\nvar(d::UnivariateGammaConvolution) = sum(d.\u03b1 .* d.\u03b8 .^ 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.\u03b1,d.\u03b8)))\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.\u03b4) < k+1\r\n            # then compute the new deltas:\r\n            n = length(d.P.\u03b4)\r\n            for k in n:(k+1)\r\n                pushfirst!(d.P.\u03b3, sum(d.\u03b1 .* d.P.to_power .^ (k+1)))\r\n                push!(d.P.\u03b4,sum(d.P.\u03b3[2:end] .* d.P.\u03b4)/(k))\r\n            end\r\n        end\r\n        dist = Distributions.Gamma(T(d.P.\u03c1 + k),T(d.P.\u03b8\u2081))\r\n        if which == \"pdf\"\r\n            step = d.P.\u03b4[k+1] * Distributions.pdf(dist,x)\r\n        elseif which == \"cdf\"\r\n            step = d.P.\u03b4[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.\u03b8) .^ (-d.\u03b1))\r\nDistributions.cf(d::UnivariateGammaConvolution, t::Real) = prod((1 - (im * t) .* d.\u03b8) .^ (-d.\u03b1))\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 \u03c0(q)\nfunction \u03c0_q(q)\n    q\u2081 = q[1]\n    q\u2082 = q[2]\n    in_bound = (-\u03c0/2 < q\u2081 < \u03c0/2) & (-\u03c0/2 < q\u2082 < \u03c0/2)\n    return in_bound*(2/\u03c0 * exp(-2*(q\u2081^2 + q\u2082^2)) + (sin(q\u2081*q\u2082)*sin(q\u2081)*cos(q\u2082))^2)\nend\n\n# Evaluates conditional probability \u03c0(p|q)\nfunction \u03c0_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(\u03c0_pq(p,q))\nend\n\n# Evaluates Potential energy V(q)\nfunction V(q)\n    return -log(\u03c0_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    \u03f5 = 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        \u03c8 = p_trajectory[j-1,:] - \u03f5/2 * dV_dq(q_trajectory[j-1,:])\n        q_trajectory[j,:] = q_trajectory[j-1,:] + \u03f5*\u03c8\n        p_trajectory[j,:] = \u03c8 - \u03f5/2*dV_dq(q_trajectory[j,:])\n    end\n\n    return q_trajectory, p_trajectory\nend\n\nfunction hmc_alg(q\u2080, p\u2080)\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\u2080\n    p_samples[1,:] = p\u2080\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)\u00f72,:]\n        p_L = p_proposal_trajectory[lastindex(p_proposal_trajectory)\u00f72,:]\n\n        # Compute acceptance probabilty\n        \u03b1 = min(1, exp(H(p,q) - H(-p_L,q_L)))\n\n        if rand() < \u03b1\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\u2081=>samples[:,1], :q\u2082=>samples[:,2]))\nrc(\"axes\",facecolor = \"#f7ece2\")\nrc(\"figure\",facecolor = \"#f7ece2\")\nrc(\"savefig\",facecolor = \"#f7ece2\")\nsns.jointplot(x = \"q\u2081\", y = \"q\u2082\", data = data, s = 1, alpha = 0.18)\n\nusing SpecialFunctions\nq_values = -\u03c0/2:0.01:\u03c0/2\n\n# Plot of q\u2081 marginal\nfunction q\u2081_marginal(q)\n    return \u221a(2/\u03c0)*erf(\u03c0/\u221a2)*exp(-2q^2) +\n    sin(q)^2*(-\u03c0*q+\u03c0*q^3+sin(\u03c0*q))/(4*q^3-4*q)\nend\n\nq\u2081_values = [q\u2081_marginal(q) for q in q_values]\n\nPlots.plot(q_values, q\u2081_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\u2082 marginal\nfunction q\u2082_marginal(q)\n    return \u221a(2/\u03c0)*erf(\u03c0/\u221a2)*exp(-2q^2) +\n    1/4*cos(q)^2*(\u03c0 + (1-2*q^2)*sin(\u03c0*q)/(q^3-q))\nend\n\nq\u2082_values = [q\u2082_marginal(q) for q in q_values]\n\nPlots.plot(q_values, q\u2082_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": "# # N queens\n\nusing Convex, GLPK, LinearAlgebra, SparseArrays, Test\naux(str) = joinpath(@__DIR__, \"aux_files\", str) # path to auxiliary files\ninclude(aux(\"antidiag.jl\"))\n\nn = 8\n# We encode the locations of the queens with a matrix of binary random variables.\nx = Variable((n, n), :Bin)\n\n# Now we impose the constraints: at most one queen on any anti-diagonal, at most one queen on any diagonal, and we must have exactly one queen per row and per column.\n## At most one queen on any anti-diagonal\nconstr = Constraint[sum(antidiag(x, k)) <= 1 for k = -n+2:n-2]\n## At most one queen on any diagonal\nconstr += Constraint[sum(diag(x, k)) <= 1 for k = -n+2:n-2]\n## Exactly one queen per row and one queen per column\nconstr += Constraint[sum(x, dims=1) == 1, sum(x, dims=2) == 1]\np = satisfy(constr)\nsolve!(p, GLPK.Optimizer)\n\n# Let us test the results:\nfor k = -n+2:n-2\n\t@test evaluate(sum(antidiag(x, k))) <= 1\n\t@test evaluate(sum(diag(x, k))) <= 1\nend\n@test all(evaluate(sum(x, dims=1)) .\u2248 1)\n@test all(evaluate(sum(x, dims=2)) .\u2248 1)\n", "meta": {"hexsha": "045848db7e4d732b88d61e8cbe5fc23ea0aea81c", "size": 1030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/mixed_integer/n_queens.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/n_queens.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/n_queens.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": 36.7857142857, "max_line_length": 166, "alphanum_fraction": 0.6815533981, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877717925422, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.793609540098932}}
{"text": "\nusing GeometricIntegrators.BasisFunctions\nusing GeometricIntegrators.CommonFunctions\nusing Test\n\ninclude(\"vandermonde_tests.jl\")\ninclude(\"lagrange_basis_tests.jl\")\ninclude(\"lagrange_polynomials_tests.jl\")\ninclude(\"legendre_basis_tests.jl\")\n", "meta": {"hexsha": "758a7540a06fb3934338cf6d4cf7e1cbac2b6199", "size": 241, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basis_functions/basis_functions_tests.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": "test/basis_functions/basis_functions_tests.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": "test/basis_functions/basis_functions_tests.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": 24.1, "max_line_length": 42, "alphanum_fraction": 0.8589211618, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7935989129244801}}
{"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        \u03c3 = sign(beta)\n        if \u03c3 == 0.0\n            break\n        end\n\n        x = v[1] - \u03c3 * ldexp(v[2], -i)\n        y = \u03c3 * ldexp(v[1], -i) + v[2]\n        v = [x, y]\n        beta -= \u03c3 * 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\u2013Seidel\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\u00b2 = BandedMatrix(0 => Fill(-2,n), 1 => Fill(1,n-1), -1 => Fill(1,n-1))/h^2\n    D_xx = kron(D\u00b2, Eye(n))\n    D_yy = kron(Eye(n), D\u00b2)\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\u0394t = (1/n^2)/4; \u0394 = finitedifference_2d(n); A = I - \u0394t*\u0394  # 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": "\nusing DataFrames\nusing CSV\n\ninclude(\"btgDerivatives.jl\")\ninclude(\"integration.jl\")    \nusing Polynomials\n\n#f = x -> sin(x^2)\n#df = x -> 2*x*cos(x^2)\n#df2 = x -> 2*cos(x^2)-4*x^2*sin(x^2)\n\n#f = x -> x^14\n#df = x-> 14 * x^13\n#df2 = x -> 182 * x^12\n\nf =  x -> x .^47 + x.^24\ndf = x -> 47 * x .^46 + 24*x.^23\ndf2 = x -> 2162*x .^45 + 552*x.^22\n\n#f = x -> sin.(exp.(3 .-x))\n#df = x -> -exp.(3 .-x) .* cos.(exp.(3 .-x))\n#df2 = x -> exp.(3 .-2*x) .*(exp.(x) .* cos.(exp.(3 .-x)).-exp(3) .* sin.(exp.(3 .-x)))\n\n#f = x-> sin.(x .+pi/2)\n#df = x-> cos.(x .+pi/2)\n#df2 = x -> -sin.(x .+pi/2)\n\n(nodes, weights) = getTuranData()\n\n(h, A) = checkDerivative(df, df2, .5)\nprintln(polyfit(h, A, 1))\n\nfunction eval_Gauss_Turan(f, df, df2, nodes, weights)\n    fn = f.(nodes)\n    dfn = df.(nodes)\n    df2n = df2.(nodes)\n    return fn'*weights[:, 1] + dfn'*weights[:, 2] + df2n'*weights[:, 3]\nend\n\nres1 = int1D(f, [-1, 1.1])\nprintln(\"Gauss error: \", abs(res1 - 2.47375))\n\nF = x -> [f(x); df(x); df2(x)]\nres = Gauss_Turan(F, [-1, 1.1], nodes, weights)\nprintln(\"Turan error: \", abs(res - 2.47375))\n\n", "meta": {"hexsha": "2aadb0bc75f64f303133b00f7e0006004a135c9e", "size": 1075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "individual_implementations/btg julia/driver_turan.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/driver_turan.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/driver_turan.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": 22.3958333333, "max_line_length": 87, "alphanum_fraction": 0.52, "num_tokens": 476, "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\u2081(r, \u03b8, \u03d5, \u03c8)\n\nDefine a coordinate chart from 3-hyperspherical coordinates into Cartesian coordinates in \u211d\u2074\nwith the given radius `r`, and angles: `\u03b8`, `\u03d5` and `\u03c8`. f\u2081: S\u00b3 \u27fc \u211d\u2074.\n\"\"\"\nfunction f\u2081(r::Real, \u03b8::Real, \u03d5::Real, \u03c8::Real)\n    x\u2081 = r * cos(\u03b8)\n    x\u2082 = r * sin(\u03b8) * cos(\u03d5)\n    x\u2083 = r * sin(\u03b8) * sin(\u03d5) * cos(\u03c8)\n    x\u2084 = r * sin(\u03b8) * sin(\u03d5) * sin(\u03c8)\n    \u211d\u2074(x\u2081, x\u2082, x\u2083, x\u2084)\nend\n\n\n\"\"\"\n    f\u2082(\u03b1, \u03d5\u2081, \u03d5\u2082)\n\nDefine a coordinate chart from Hopf coordinates on 3-sphere into Cartesian coordinates in \u211d\u2074\nwith the given angles `\u03b1`, `\u03d5\u2081` and `\u03d5\u2082`. f\u2082: S\u00b3 \u27fc \u211d\u2074.\n\"\"\"\nfunction f\u2082(\u03b1::Real, \u03d5\u2081::Real, \u03d5\u2082::Real)\n    @assert(0 < \u03b1 < \u03c0 / 2, \"\u03b1 \u2208 (0, \u03c0/2)\")\n    @assert(0 \u2264 \u03d5\u2081 \u2264 2\u03c0, \"\u03d5\u2081 \u2208 [0, 2\u03c0]\")\n    @assert(0 \u2264 \u03d5\u2082 \u2264 2\u03c0, \"\u03d5\u2082 \u2208 [0, 2\u03c0]\")\n    x\u2081 = cos(\u03d5\u2081) * sin(\u03b1)\n    x\u2082 = sin(\u03d5\u2081) * sin(\u03b1)\n    x\u2083 = cos(\u03d5\u2082) * cos(\u03b1)\n    x\u2084 = sin(\u03d5\u2082) * cos(\u03b1)\n    \u211d\u2074(x\u2081, x\u2082, x\u2083, x\u2084)\nend\n\n\n\"\"\"\n    f\u2083(\u03b1, \u03d5\u2081, \u03d5\u2082)\n\nDefine a coordinate chart from Hopf coordinates on 3-sphere into Cartesian coordinates in \u211d\u2074\nwith the given angles `\u03b1`, `\u03d5\u2081` and `\u03d5\u2082`. f\u2083: S\u00b3 \u27fc \u211d\u2074.\n\"\"\"\nfunction f\u2083(\u03b1::Real, \u03d5\u2081::Real, \u03d5\u2082::Real)\n    @assert(0 < \u03b1 < \u03c0 / 2, \"\u03b1 \u2208 (0, \u03c0/2)\")\n    @assert(0 \u2264 \u03d5\u2081 \u2264 2\u03c0, \"\u03d5\u2081 \u2208 [0, 2\u03c0]\")\n    @assert(0 \u2264 \u03d5\u2082 \u2264 4\u03c0, \"\u03d5\u2082 \u2208 [0, 4\u03c0]\")\n    x\u2081 = cos((\u03d5\u2081 + \u03d5\u2082) / 2) * sin(\u03b1)\n    x\u2082 = sin((\u03d5\u2081 + \u03d5\u2082) / 2) * sin(\u03b1)\n    x\u2083 = cos((\u03d5\u2082 - \u03d5\u2081) / 2) * cos(\u03b1)\n    x\u2084 = sin((\u03d5\u2082 - \u03d5\u2081) / 2) * cos(\u03b1)\n    \u211d\u2074(x\u2081, x\u2082, x\u2083, x\u2084)\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(\u03bc) = length(\u03bc) > 1 ? FFTW.plan_r2r!(\u03bc, FFTW.REDFT00) : ones(\u03bc)'\n\n\"\"\"\nCompute nodes and weights of the Clenshaw\u2014Curtis quadrature rule with a Jacobi weight.\n\"\"\"\nclenshawcurtis{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T) = clenshawcurtis(N,\u03b1,\u03b2,clenshawcurtis_plan(zeros(T,N)))\nclenshawcurtis{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T,plan) = T[cospi(k/(N-one(T))) for k=0:N-1],clenshawcurtisweights(N,\u03b1,\u03b2,plan)\n\n\"\"\"\nCompute weights of the Clenshaw\u2014Curtis quadrature rule with a Jacobi weight.\n\"\"\"\nclenshawcurtisweights{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T) = clenshawcurtisweights(N,\u03b1,\u03b2,clenshawcurtis_plan(zeros(T,N)))\nfunction clenshawcurtisweights{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T,plan)\n    \u03bc = chebyshevjacobimoments1(N,\u03b1,\u03b2)\n    scale!(\u03bc,inv(N-one(T)))\n    plan*\u03bc\n    \u03bc[1]/=2;\u03bc[N]/=2\n    return \u03bc\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\u03b8) coefficients to values at Clenshaw-Curtis nodes except \u00b11\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": "module TestGroupGenerics\n\nusing Test\nusing RLEVectors\n\n@testset begin\n\n# compare group\nvec = [1,1,2,2,4,4]\nx = RLEVector(vec)\n@test (x .< 3) == RLEVector([true,false],[4,6])\n\n# math group\nvec = [1,1,2,2,4,4]\nx = RLEVector(vec)\n@test x .+ 5 == 5 .+ x\n@test x .+ 4 == RLEVector([5,5,6,6,8,8])\n@test div.(vec,2) == collect(div.(x,2))\n@test median(RLEVector([1,2,3,2,1,5,4])) == median([1,2,3,2,1,5,4])\n@test median(RLEVector([1,2,3,2,1,5])) == median([1,2,3,2,1,5])\n@test median(RLEVector([3,2,1])) == 2.0\n@test median(RLEVector([2, 2, 2, 3, 3, 3])) == 2.5 # median is average of end of run and next value\n@test sum(RLEVector([4, 4, 5, 5, 6, 6])) == 30\n@test mean(RLEVector([4, 4, 5, 5, 6, 6])) == 5.0\n@test x .^ 2 == RLEVector( [1, 1, 4, 4, 16, 16] )\n@test x .^ 3 == RLEVector( [1, 1, 8, 8, 64, 64] )\n@test x + x == RLEVector( [2, 2, 4, 4, 8, 8] )\n@test x - x == RLEVector( [0, 0, 0, 0, 0, 0] )\nrle = RLEVector( [4, 4, 9, 9, 16, 16] )\n@test sqrt.(rle) == RLEVector( [2, 2, 3, 3, 4, 4] )\n\n# math on bools\nvec = [1,1,2,2,4,4]\nx = RLEVector(vec)\n@test x .+ true == x .+ 1\n@test x .+ false == x\nvec = [1,1,2,2,4,4]\nx = RLEVector(vec)\n@test x .+ true == x .+ 1\n@test x .+ false == x\n\n# broadcast with different sizes\nx = RLEVector([1,1,3])\n@test x .+ 4 == RLEVector([5,5,7])\n@test x .+ [4 5 6] == [[5 6 7] ; [5 6 7] ; [7 8 9]]\n@test x .+ [4, 5, 6] == RLEVector([5, 6, 9])\n@test x .+ [[2 2 2] ; [4 4 4]]' == [[3 3 5] ; [ 5 5 7]]'\n\n# findmax, findmin\n@test findmin(RLEVector([1,2,3,4,1,1])) == findmin([1,2,3,4,1,1])\n@test findmax(RLEVector([1,2,3,4,1,1])) == findmax([1,2,3,4,1,1])\n\n# indexin\nfoo = IntegerRle( collect(1:1000), collect(5:5:5000))\nx = RLEVector([2,2,4,4,3,3])\ny = RLEVector([0,0,0,3,3,3,4,4])\n@test indexin(x,y) == indexin(collect(x), collect(y))\n@test indexin(x,collect(3:11)) == indexin(collect(x),collect(3:11))\n@test indexin([200,200,1,1,5,5],foo) == indexin([200,200,1,1,5,5],foo)\n\n@test findall(in(RLEVector(collect(3:10))), RLEVector([1,1,2,2,3,3])) == collect(5:6)\n@test findall(in(3:10), RLEVector([1,1,2,2,3,3])) == collect(5:6)\n@test findall(in(collect(3:10)), RLEVector([1,1,2,2,3,3])) == collect(5:6)\n@test findall(in(RLEVector(collect(1:4))), [3,4,5]) == [1,2]\n\n# in\n@test in(3, RLEVector( [ 1,2,2,3 ] )) == true\n@test in(4, RLEVector( [ 1,2,2,3 ] )) == false\n@test setdiff( Set([1,2,3,4,5]), RLEVector([1,1,2,2,4,4,5,5]) ) == Set([3])\n\nend # testset\n\nend # module\n", "meta": {"hexsha": "f82a00732214902b67164a8cc0855f2cdc29adab", "size": 2387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_group_generics.jl", "max_stars_repo_name": "UnofficialJuliaMirror/RLEVectors.jl-17b45ede-fd0d-54ef-b825-8cf9fc64da95", "max_stars_repo_head_hexsha": "7da814b997125657eed10a9f233af8b661e66bdc", "max_stars_repo_licenses": ["MIT"], "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_group_generics.jl", "max_issues_repo_name": "UnofficialJuliaMirror/RLEVectors.jl-17b45ede-fd0d-54ef-b825-8cf9fc64da95", "max_issues_repo_head_hexsha": "7da814b997125657eed10a9f233af8b661e66bdc", "max_issues_repo_licenses": ["MIT"], "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_group_generics.jl", "max_forks_repo_name": "UnofficialJuliaMirror/RLEVectors.jl-17b45ede-fd0d-54ef-b825-8cf9fc64da95", "max_forks_repo_head_hexsha": "7da814b997125657eed10a9f233af8b661e66bdc", "max_forks_repo_licenses": ["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.2567567568, "max_line_length": 99, "alphanum_fraction": 0.5643066611, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7935441624808265}}
{"text": "\"\"\"\n**Inversedecay constructor**\n```julia\n    Inversedecay(; t0::Real=1, \u03ba::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 \u03ba \u2208 (0.5,1]\n\"\"\"\nmutable struct Inversedecay <: Optimizer\n    opt_type::String\n    t::Int64\n    t\u2080::Float64\n    \u03ba::Float64\nend\n\nfunction Inversedecay(; t0::Real=1, \u03ba::Real=0.51)\n    @assert t0 > 0.0 \"t0 must be greater than 0\"\n    @assert (\u03ba > 0.5 || \u03ba <= 1.0) \"\u03ba argument is in (0.5,1]\"\n\n    Inversedecay(\"Inversedecay\", 0, t0, \u03ba)\nend\n\nparams(opt::Inversedecay) = \"t\u2080=$(opt.t\u2080), \u03ba=$(opt.\u03ba)\"\n\nfunction update(opt::Inversedecay, g_t::AbstractArray{T}) where {T<:Real}\n    # update timestep\n    opt.t += 1\n    return (opt.t\u2080+opt.t)^(-opt.\u03ba) * 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": "@testset \"simple models\" begin\n    y  = [0,1,0,1,1,0]\n    x0 = ones(length(y))\n    x1 = [2.5,1.7,4,2.3,3.7,4.8]\n    x2 = [3,3,2,2,4,1]\n    x3 = [0,0,0,0,1,1]\n    X_0 = x0\n    X_1 = hcat(x0, x1)\n    X_2 = hcat(X_1, x2)\n    X_3 = hcat(X_2, x3)\n\n    @testset \"model X_0\" begin\n        model_0 = logreg(y, X_0)\n\n        @test model_0.num_obs == 6\n        @test model_0.dof_log == 0\n        @test model_0.dof_resid == 5\n        @test model_0.dof_total == 5\n        @test model_0.beta_hat \u2248 [0.0000] atol = 1e-5\n        @test model_0.llk \u2248 -4.158883 atol = 1e-5\n        @test model_0.dev_residuals \u2248 [-1.17741, 1.17741, -1.17741, 1.17741,  1.17741, -1.17741] atol = 1e-5\n        @test model_0.aic \u2248 10.318 atol = 1e-3\n        @test model_0.bic \u2248 10.10953 atol = 1e-4\n        @test model_0.pi_hat \u2248 [0.5, 0.5, 0.5, 0.5, 0.5, 0.5] atol = 1e-2\n        @test model_0.y_hat == ones(Int64, 6)\n        @test model_0.std_error \u2248 [0.8165] atol = 1e-3\n    end\n\n    @testset \"model X_1\" begin\n        model_1 = logreg(y, X_1) \n        @test model_1.num_obs == 6\n        @test model_1.beta_hat \u2248 [3.971,-1.260]  atol = 1e-3\n        @test model_1.dof_log == 1\n        @test model_1.dof_resid == 4\n        @test model_1.dof_total == 5\n        @test model_1.pi_hat \u2248 [0.6940996, 0.8614932, 0.2551409, 0.7448733, 0.3333144, 0.1110785] atol = 1e-3\n        @test model_1.y_hat \u2248 [1, 1 , 0, 1, 0, 0] atol = 1e-3\n        @test model_1.llk \u2248 -3.1391 atol = 1e-3 \n        @test model_1.aic \u2248  10.2782 atol = 1e-3 \n        @test model_1.bic \u2248 9.86172 atol = 1e-3 \n        @test model_1.dev_residuals \u2248  [-1.5391528,  0.5460551, -0.7675418,  0.7675169,  1.4823421, -0.4852760] atol = 1e-3\n        @test model_1.std_error \u2248 [3.353, 1.026] atol = 1e-3\n    end\n\n    @testset \"model X_2\" begin\n        model_2 = logreg(y, X_2)\n\n        @test model_2.num_obs == 6\n        @test model_2.dof_log == 2\n        @test model_2.dof_resid == 3\n        @test model_2.dof_total == 5\n        @test model_2.beta_hat \u2248 [0.7187, -1.2929, 1.2082] atol = 1e-4\n        @test model_2.llk \u2248 -2.639604 atol = 1e-5\n        @test model_2.dev_residuals \u2248 [-1.6707271, 0.4704612, -0.4952902, 1.1096542, 0.8731406, -0.1659078] atol = 1e-7\n        @test model_2.aic \u2248 11.279 atol = 1e-3\n        @test model_2.bic \u2248 10.65449 atol = 1e-4\n        @test model_2.pi_hat \u2248 [0.75233160, 0.89523692, 0.11543226, 0.54028085, 0.68304996, 0.01366843] atol = 1e-7\n        @test model_2.y_hat == [1, 1, 0, 1, 1, 0]\n        @test model_2.std_error \u2248 [4.8242, 1.3811, 1.3498] atol = 1e-3\n    end\nend", "meta": {"hexsha": "9225d08c7a69d8a1386ca5acd46c57c03b40054e", "size": 2523, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/simple_models.jl", "max_stars_repo_name": "LAMPSPUC/LogisticRegression.jl", "max_stars_repo_head_hexsha": "462c2420346f9f8000f719aea8c1bc8cf7705812", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T17:29:11.000Z", "max_issues_repo_path": "test/simple_models.jl", "max_issues_repo_name": "LAMPSPUC/LogisticRegression.jl", "max_issues_repo_head_hexsha": "462c2420346f9f8000f719aea8c1bc8cf7705812", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-03T15:52:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-07T16:31:04.000Z", "max_forks_repo_path": "test/simple_models.jl", "max_forks_repo_name": "LAMPSPUC/LogisticRegression.jl", "max_forks_repo_head_hexsha": "462c2420346f9f8000f719aea8c1bc8cf7705812", "max_forks_repo_licenses": ["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.3606557377, "max_line_length": 123, "alphanum_fraction": 0.5640110979, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7935441549004166}}
{"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\u00e1rik, 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": "nthroots(n::Integer) = [ cospi(2k/n)+sinpi(2k/n)im for k = 0:n-1 ]\n", "meta": {"hexsha": "51dbc9d7b4be3ec6aca1e9c84c3e10b087be3244", "size": 67, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/roots-of-unity.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/roots-of-unity.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/roots-of-unity.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.5, "max_line_length": 66, "alphanum_fraction": 0.6119402985, "num_tokens": 32, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572778012346835, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7935247116972124}}
{"text": "export solve\n\nfunction possible(p::Puzzle, x::Int, y::Int, n::Int)::Bool\n    for j in 1:9\n        if p[x,j] == n\n            return false;\n        end\n    end\n    for i in 1:9\n        if p[i,y] == n\n            return false;\n        end\n    end\n    # get sub-grid coordinates\n    xs = Int.(3 * ceil(x / 3 - 1) .+ collect(1:3))\n    ys = Int.(3 * ceil(y / 3 - 1) .+ collect(1:3))\n    for i in xs\n        for j in ys\n            if p[i,j] == n\n                return false;\n            end\n        end\n    end\n    return true;\nend\n\nfunction solve(p::Puzzle)::Bool\n    for i in 1:9\n        for j in 1:9\n            if p[i,j] == 0\n                for n in 1:9\n                    if possible(p, i, j, n)\n                        p[i,j] = n\n                        # recursion\n                        if solve(p)\n                            return true;\n                        else\n                            # backtracking\n                            p[i,j] = 0\n                        end\n                    end\n                end\n                return false;\n            end\n        end\n    end\n    return true;\nend\n", "meta": {"hexsha": "3591442f9aeaa6ac099567be225c9650277ff147", "size": 1117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver.jl", "max_stars_repo_name": "Joshua-Robison/Sudoku", "max_stars_repo_head_hexsha": "98ea8e66f8cd084143511003b368ef30ce989394", "max_stars_repo_licenses": ["MIT"], "max_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": "Joshua-Robison/Sudoku", "max_issues_repo_head_hexsha": "98ea8e66f8cd084143511003b368ef30ce989394", "max_issues_repo_licenses": ["MIT"], "max_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": "Joshua-Robison/Sudoku", "max_forks_repo_head_hexsha": "98ea8e66f8cd084143511003b368ef30ce989394", "max_forks_repo_licenses": ["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.7959183673, "max_line_length": 58, "alphanum_fraction": 0.3518352731, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7935033081937407}}
{"text": "using ModelingToolkit\nusing Test\n\n# Derivatives\n@parameters t \u03c3 \u03c1 \u03b2\n@variables x(t) y(t) z(t)\n@derivatives D'~t D2''~t\n\n@test isequal(expand_derivatives(D(t)), 1)\n@test isequal(expand_derivatives(D(D(t))), 0)\n\ndsin = D(sin(t))\n@test isequal(expand_derivatives(dsin), cos(t))\n\ndcsch = D(csch(t))\n@test isequal(expand_derivatives(dcsch), simplify_constants(coth(t) * csch(t) * -1))\n\n@test isequal(expand_derivatives(D(-7)), 0)\n@test isequal(expand_derivatives(D(sin(2t))), simplify_constants(cos(2t) * 2))\n@test isequal(expand_derivatives(D2(sin(t))), simplify_constants(-sin(t)))\n@test isequal(expand_derivatives(D2(sin(2t))), simplify_constants(sin(2t) * -4))\n@test isequal(expand_derivatives(D2(t)), 0)\n@test isequal(expand_derivatives(D2(5)), 0)\n\n# Chain rule\ndsinsin = D(sin(sin(t)))\n@test isequal(expand_derivatives(dsinsin), cos(sin(t))*cos(t))\n\nd1 = D(sin(t)*t)\nd2 = D(sin(t)*cos(t))\n@test isequal(expand_derivatives(d1), t*cos(t)+sin(t))\n@test isequal(expand_derivatives(d2), simplify_constants(cos(t)*cos(t)+sin(t)*(-1*sin(t))))\n\neqs = [0 ~ \u03c3*(y-x),\n       0 ~ x*(\u03c1-z)-y,\n       0 ~ x*y - \u03b2*z]\nsys = NonlinearSystem(eqs,[x,y,z],[\u03c3,\u03c1,\u03b2])\njac = calculate_jacobian(sys)\n@test isequal(jac[1,1], \u03c3*-1)\n@test isequal(jac[1,2], \u03c3)\n@test isequal(jac[1,3], 0)\n@test isequal(jac[2,1], \u03c1-z)\n@test isequal(jac[2,2], -1)\n@test isequal(jac[2,3], x*-1)\n@test isequal(jac[3,1], y)\n@test isequal(jac[3,2], x)\n@test isequal(jac[3,3], -1*\u03b2)\n\n# Variable dependence checking in differentiation\n@variables a(t) b(a)\n@test !isequal(D(b), 0)\n\n@test isequal(expand_derivatives(D(x * y)), simplify_constants(y*D(x) + x*D(y)))\n@test_broken isequal(expand_derivatives(D(x * y)), simplify_constants(D(x)*y + x*D(y)))\n\n@test isequal(expand_derivatives(D(2t)), 2)\n@test isequal(expand_derivatives(D(2x)), 2D(x))\n", "meta": {"hexsha": "999cad9a70a7be178f16ff89a0287b5f13203aed", "size": 1789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/derivatives.jl", "max_stars_repo_name": "dpsanders/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "6450e3b1995f9e4e7ab54842544e077543588a46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-12T02:35:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T02:35:58.000Z", "max_issues_repo_path": "test/derivatives.jl", "max_issues_repo_name": "dpsanders/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "6450e3b1995f9e4e7ab54842544e077543588a46", "max_issues_repo_licenses": ["MIT"], "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/derivatives.jl", "max_forks_repo_name": "dpsanders/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "6450e3b1995f9e4e7ab54842544e077543588a46", "max_forks_repo_licenses": ["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.8448275862, "max_line_length": 91, "alphanum_fraction": 0.6830631638, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7935033028944111}}
{"text": "\"\"\"\n## rod_mm!\n\nThis subroutine forms the consistent mass matrix of a 1-d \"rod\" fin_el.\n\n### Function\n```julia\nrod_mm!(km, ell)\n```\n\n### Arguments\n```julia\n* mm::Matrix{Float64}       : Element mass matrix (Updated)\n* ell::Float64              : Element length\n```\n\"\"\"\nfunction rod_mm!(mm::Matrix{Float64}, ell::Float64)\n  #\n  # This subroutine forms the consistent mass matrix of a 1-d \"rod\" fin_el.\n  #\n mm = [1.0/3.0 1.0/6.0; 1.0/6.0 1.0/3.0]\n mm *= ell\nend", "meta": {"hexsha": "fae778535cd5632233ea5176b30afb9b34ce2e45", "size": 460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PtFEM/Main/rod_mm.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/rod_mm.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/rod_mm.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": 20.0, "max_line_length": 75, "alphanum_fraction": 0.6152173913, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7934485761072514}}
{"text": "###############################################################################\n## Logistic Problem\n#    min_x  1/m * \u2211_{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    \u03bb\u2082::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            \u03bb\u2082::Float64\n        ) where {Tr, Tm, Txman}\n        @assert Set(y) \u2286 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, \u03bb\u2082)\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.\u03bb\u2082 * norm(x, 2)^2\nend\n\n# 1st order\n\u03c3(x) = 1/(1+exp(-x))\nfunction \u2207f!(pb::LogisticPb, res, x)\n    m = size(pb.A, 1)\n\n    \u03c3yAx = pb.A * x\n    \u03c3yAx .*= -pb.y\n    \u03c3yAx .= \u03c3.(\u03c3yAx)\n    res .= transpose(pb.A) * (\u03c3yAx .* pb.y)\n    res ./= -m\n    res .+= pb.\u03bb\u2082 .* x\n\n    return res\nend\n\n# 2nd order\n\u2207\u03c3(x) = \u03c3(x) * \u03c3(-x)\nfunction \u2207\u00b2f_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 .* \u2207\u03c3.(yAx))\n    res ./= m\n    res .+= pb.\u03bb\u2082 .* 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.\u03bb\u2082\nend\n# get_\u03bc_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 \u03b1, \u03b2, \u03b3 (in degrees) from a cell.\"\"\"\ncell_angles(cell) = tuple((ang(cell[p[1],:], cell[p[2],:])*180.0/\u03c0 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": "puzzleinput = readlines(\"inputs/day13.txt\")\n\nearliesttimestamp = parse(Int, puzzleinput[1])\n\ntimetable = map(x -> tryparse(Int64, x), split(puzzleinput[2], \",\"))\n\n\n# Firt Half\n\ndt(id::Nothing, ets) = typemax(Int64)\ndt(id::Int64, ets) = ((ets \u00f7 id + 1) * id) - ets\n# Calculates the time to next bus id from an earliest time stamp ets\n\n\nwaittimes = [[t dt(t, earliesttimestamp)] for t in timetable]\nwaittimes = reduce(vcat, waittimes)\n# Matrix with in first column bus ids and\n# in second colums wait times from the earliest time stamp\n\nwaittimes = waittimes[sortperm(waittimes[:, 2]), :]\n# Sort by wait times\n\nwaittimes[1, 1] * waittimes[1, 2]\n\n\n# Second Half\n\n#= =======================================================================\nThis solution cames from an original idea of a friend of mines, \nMatteo Bernardini:\n\nhttps://github.com/matteberna/advent-of-code-2020/blob/master/Solutions/Day13.cs\n\nThx Whiskee!\n======================================================================== =#\n\n\nfunction findets(tt)\n    ids = filter((!) \u2218 isnothing, tt)\n\n    departs = [i - 1 for i = 1:length(tt) if !isnothing(tt[i])]\n    # Minutes after 0 at which each bus in the time table has to depart\n\n    dt = 1\n    t = ids[1]\n\n    for (i, id) in enumerate(ids)\n        while true\n            if (t + departs[i]) % id == 0\n                dt *= id\n                # Given the fact that ids are all prime numbers:\n                # if the depart of bus ids[i] is ok a this time stamp t\n                # then the times stamp for the subsequent in\n                # the time table (eg. ids[i+1]) has to be necessarily\n                # t + n * ids[i] * ids[i+1] + departs[i],\n                # if we want it to be ok also for the previous ids\n\n                break\n            else\n                t += dt\n            end\n        end\n    end\n\n    return t\nend\n\n@time findets(timetable)\n\n# With input:\n# 17,x,x,x,x,x,x,41,x,x,x,37,x,x,x,x,x,367,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,19,x,x,x,23,x,x,x,x,x,29,x,613,x,x,x,x,x,x,x,x,x,x,x,x,13\n# in Wolfram Alpha you could type this to obtain the solution\n#  {41x_2-17x_1=7;37x_3-17x_1=11;367x_4-17 x_1=17;19x_5- 17x_1=36;23x_6-17x_1=40;29x_7-17 x_1=46;613 x_8-17x_1=48;13 x_9-17x_1=61} integer solution\n", "meta": {"hexsha": "ecf71f69cb2d67ffe2af313f08ee6342c03f23d0", "size": 2236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day13.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": "day13.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": "day13.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": 30.2162162162, "max_line_length": 147, "alphanum_fraction": 0.5733452594, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8418256492357359, "lm_q1q2_score": 0.7934263311234269}}
{"text": "\"\"\"\n`LinearKernel([\u03c1=1.0,[c=0.0]])`\nThe linear kernel is a Mercer kernel given by\n```\n    \u03ba(x,y) = \u03c1\u00b2x\u1d40y + 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(\u03c1::T=1.0, c::Real=zero(T)) where {T<:Real}\n    LinearKernel(ScaleTransform(\u03c1), c)\nend\n\nfunction LinearKernel(\u03c1::AbstractVector{T}, c::Real=zero(T)) where {T<:Real}\n    LinearKernel(ARDTransform(\u03c1), 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(\u03ba::LinearKernel, x\u1d40y::T) where {T<:Real} = x\u1d40y + \u03ba.c\n\nmetric(::LinearKernel) = DotProduct()\n\n\"\"\"\n`PolynomialKernel([\u03c1=1.0[,d=2.0[,c=0.0]]])`\nThe polynomial kernel is a Mercer kernel given by\n```\n    \u03ba(x,y) = (\u03c1\u00b2x\u1d40y + 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(\u03c1::Real=1.0, d::Td=2.0, c::Real=zero(Td)) where {Td<:Real}\n    PolynomialKernel(ScaleTransform(\u03c1), d, c)\nend\n\nfunction PolynomialKernel(\u03c1::AbstractVector{T}, d::Real=2.0, c::Real=zero(T\u2081)) where {T<:Real}\n    PolynomialKernel(ARDTransform(\u03c1), 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(\u03ba::PolynomialKernel, x\u1d40y::T) where {T<:Real} = (x\u1d40y + \u03ba.c)^(\u03ba.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": "x = randn(10000000)\ny = randn(10000000)\n\nfunction inner(x, y)\n    result = 0.0\n    for i=1:length(x)\n        result += x[i] * y[i]\n    end\n    result\nend\n\n# gc_disable()\n# tic()\n@time for i=1:50 result = sum(x .* y); end\n# timing = toc();\n# println(\"Array operations took \", (timing / 50) * 1000, \" ms\")\n# with 1 processor: Array operations took 89.43973046 ms - avg: 90 ms\n# with 9 processors: elapsed time: 5.358992903 seconds (4000026400 bytes allocated, 34.95% gc time)\n\n@time for i=1:50 result = inner(x, y) end \n# elapsed time: 1.126870943 seconds (800 bytes allocated)\n\nx = randn(1, 10000000)\ny = randn(10000000, 1)\n#tic()\n@time for i=1:50 result = x * y end\n# elapsed time: 2.401834172 seconds (4800 bytes allocated)\n#timing = toc();\n#println(\"BLAS took \", (timing / 50) * 1000, \"ms\")\n", "meta": {"hexsha": "6b1b5357cf0e70b663ecadc19ca35fe3c6496efb", "size": 793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 1/Chapter09/Old/array_product_benchmark.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/Chapter09/Old/array_product_benchmark.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/Chapter09/Old/array_product_benchmark.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.4333333333, "max_line_length": 99, "alphanum_fraction": 0.6456494325, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7934263209240957}}
{"text": "# ---\n# title: 441. Arranging Coins\n# id: problem441\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math, Binary Search\n# link: <https://leetcode.com/problems/arranging-coins/description/>\n# hidden: true\n# ---\n# \n# You have a total of _n_ coins that you want to form in a staircase shape,\n# where every _k_ -th row must have exactly _k_ coins.\n# \n# Given _n_ , find the total number of **full** staircase rows that can be\n# formed.\n# \n# _n_ is a non-negative integer and fits within the range of a 32-bit signed\n# integer.\n# \n# **Example 1:**\n# \n#     \n#     \n#     n = 5\n#     \n#     The coins can form the following rows:\n#     \u00a4\n#     \u00a4 \u00a4\n#     \u00a4 \u00a4\n#     \n#     Because the 3rd row is incomplete, we return 2.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     n = 8\n#     \n#     The coins can form the following rows:\n#     \u00a4\n#     \u00a4 \u00a4\n#     \u00a4 \u00a4 \u00a4\n#     \u00a4 \u00a4\n#     \n#     Because the 4th row is incomplete, we return 3.\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "323e33b73ff4b350234f41a933c301a83f22ce19", "size": 1032, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/441.arranging-coins.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/441.arranging-coins.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/441.arranging-coins.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.4285714286, "max_line_length": 76, "alphanum_fraction": 0.5717054264, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.7934097612191062}}
{"text": "# DBSCAN Clustering\r\n#\r\n#   References:\r\n#\r\n#       Martin Ester, Hans-peter Kriegel, J\u00f6rg 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 \u00f7 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": "using KrylovMethods\nusing Base.Test\nusing LinearOperators\ninclude(\"getDivGrad.jl\")\n\n\nprintln(\"=== Testing CG ===\")\n# small full system\nA = [4.0 1; 1 4]\nrhs = [2.0;2]\nx,flag,relres,iter,resvec = cg(A,rhs,tol=1e-15,out=2,storeInterm=true)\n@test norm(A*x[:,end]-rhs)/norm(rhs) <= 1e-15\n\n# test message and flag when stopping early\nx,flag,relres,iter,resvec = cg(A,randn(2),tol=1e-15,out=2,maxIter=1)\n@test flag==-1\n\n# test for zero right hand-side\nx,flag = cg(A,zeros(2),out=2)\n@test flag == -9\n@test all(x.==0)\n\n# negative definite matrix\nb = [1 -1.0]\nKKT = [A b'; b 0]\nx,flag, = cg(KKT,randn(3),out=1)\n@test flag==-2\n\n\n# CG: test sparse Laplacian\nA = getDivGrad(8,8,8)\nAlinop = LinearOperator(A)\nL = tril(A)\nD = diag(A)\nU = triu(A)\nn = size(A,1)\nJAC = (x) -> D.\\x\nSGS = (x) -> L\\(D.*(U\\x))\n\nrhs = randn(size(A,1))\ntolCG = 1e-5\n# tests with A being matrix\nxCG,flagCG,relresCG,iterCG,resvecCG       = cg(A,rhs,tol=tolCG,maxIter=100)\nxJAC,flagJAC,relresJAC,iterJAC,resvecJAC  = cg(A,rhs,tol=tolCG,maxIter=100,M=JAC,out=1)\nxSGS,flagSGS,relresSGS,iterSGS,resvecSGS  = cg(A,rhs,tol=tolCG,maxIter=100,M=SGS)\n# tests with A being function\nxCGmf,flagCG,relresCG,iterCG,resvecCG       = cg(Alinop,rhs,tol=tolCG,maxIter=100)\nxJACmf,flagJAC,relresJAC,iterJAC,resvecJAC  = cg(Alinop,rhs,tol=tolCG,maxIter=100,M=JAC)\nxSGSmf,flagSGS,relresSGS,iterSGS,resvecSGS  = cg(Alinop,rhs,tol=tolCG,maxIter=100,M=SGS)\n# tests with random starting guess\nxCGr,flagCGr,relresCGr,iterCGr,resvecCGr       = cg(Alinop,rhs,tol=tolCG,maxIter=100,x=randn(size(rhs)))\nxJACr,flagJACr,relresJACr,iterJACr,resvecJACr  = cg(Alinop,rhs,tol=tolCG,maxIter=100,M=JAC,x=randn(size(rhs)))\nxSGSr,flagSGSr,relresSGSr,iterSGSr,resvecSGSr  = cg(A,rhs,tol=tolCG,maxIter=100,x=randn(size(rhs)))\n\n# test relative residuals\n@test norm(A*xCG-rhs)/norm(rhs) <= tolCG\n@test norm(A*xSGS-rhs)/norm(rhs) <= tolCG\n@test norm(A*xJAC-rhs)/norm(rhs) <= tolCG\n@test norm(A*xCGmf-rhs)/norm(rhs) <= tolCG\n@test norm(A*xSGSmf-rhs)/norm(rhs) <= tolCG\n@test norm(A*xJACmf-rhs)/norm(rhs) <= tolCG\n@test norm(A*xCGr-rhs)/norm(rhs) <= tolCG*10\n@test norm(A*xSGSr-rhs)/norm(rhs) <= tolCG*10\n@test norm(A*xJACr-rhs)/norm(rhs) <= tolCG*10\n# preconditioners should at least not increase number of iter\n@test iterJAC==iterCG\n@test iterSGS<=iterJAC\n\nprintln(\"=== CG : All tests passed. ====\")\n", "meta": {"hexsha": "ee7225f6b12119fed80607a14a55c3985318a7c1", "size": 2313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testCG.jl", "max_stars_repo_name": "Pbellive/KrylovMethods.jl", "max_stars_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_stars_repo_licenses": ["MIT"], "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/testCG.jl", "max_issues_repo_name": "Pbellive/KrylovMethods.jl", "max_issues_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_issues_repo_licenses": ["MIT"], "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/testCG.jl", "max_forks_repo_name": "Pbellive/KrylovMethods.jl", "max_forks_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_forks_repo_licenses": ["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.0428571429, "max_line_length": 110, "alphanum_fraction": 0.7025507998, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7933892810970818}}
{"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    \u03bb = Vector{Float64}(undef, n+1)\n    \u03bb[n+1] = d[p[n]]\n    for i in n:-1:2\n        \u03bb[i] = d[p[i-1]] - d[p[i]]\n    end\n    \u03bb[1] = 1.0 - sum(\u03bb[2:end])\n    return \u03bb\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}}, \u03bb::Vector{Float64})\nFills `V` and `\u03bb` 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}}, \u03bb::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    \u03bb[n+1] = d[p[n]]\n    for i in n:-1:2\n        \u03bb[i] = d[p[i-1]] - d[p[i]]\n    end\n    \u03bb[1] = 1.0 - sum(\u03bb[2:end])\n    return V, \u03bb\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-\u03c3)`` for a Poisson ratio ``\u03c3``.\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/\u03c0 * ( eval_r.vec[1] * eval_r.vec[2] / magnitude2(eval_r) ) * (bob \u22c5 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-\u03c3)`` for a Poisson ratio ``\u03c3``.\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*\u03c0) * ( ( eval_r.vec[1]^2 - eval_r.vec[2]^2 ) / magnitude2(eval_r) ) * (bob \u22c5 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\u03bb = 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  + \u03bb * 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 * \u03bb * 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\u03b1 = 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\u039b(x) = forward_logs(M, x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x, rep(d)...), \u039b(x)), 1)\n#\n# Setup and Optimize\ncost(x) = fidelity(x) + \u03b1 * prior(x)\nproxes = [(\u03bb, x) -> prox_distance(M, \u03bb, f, x, 2), (\u03bb, x) -> prox_TV(M, \u03b1 * \u03bb, 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)-\u03b1$(replace(string(\u03b1), \".\" => \"-\")).asy\";\n        data = y,\n        scaleAxes = (7.5, 7.5, 7.5),\n    )\n    render_asymptote(\n        resultsFolder *\n        experimentName *\n        \"-result-$(maxIterations)-\u03b1$(replace(string(\u03b1), \".\" => \"-\")).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\u2019s 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\u2014a, b, c and n\u2014and checks to see if Fermat\u2019s theorem holds. If n is greater than 2 and a^n + b^n == c^n the program should print, \u201cHoly smokes, Fermat was wrong!\u201d Otherwise the program should print, \u201cNo, that doesn\u2019t work.\u201d\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\u2019t 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\u2019s 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\u00d7n` 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\u00f72)*(m\u00f72), n*m)\n    linearj = LinearIndices((1:m, 1:n))\n    lineari = LinearIndices((1:m\u00f72, 1:n\u00f72))\n\n    for i in 2:2:m\n        for j in 2:2:n\n            S[lineari[i\u00f72,j\u00f72], linearj[i, j]] = 1/4\n            S[lineari[i\u00f72,j\u00f72], linearj[i-1, j]] = 1/4\n            S[lineari[i\u00f72,j\u00f72], linearj[i, j-1]] = 1/4\n            S[lineari[i\u00f72,j\u00f72], linearj[i-1, j-1]] = 1/4\n        end\n    end\n    S\nend\n#=\nm = n = 8\nL = downop(F0, m, n); \u039b = gridlaplacian(F0, m, n); \u039b2 = gridlaplacian(F0, m\u00f72, n\u00f72)\nheatmap([Matrix(8L*\u039b*L') Matrix(\u039b2) Matrix(8L*\u039b*L' - \u039b2)])\nL = downop(F0, m, n); \u039b = gridlaplacian(F0, m, n) + I/2; \u039b2 = gridlaplacian(F0, m\u00f72, n\u00f72) + I\ninvm(x) = inv(Matrix(x))\nF = Float64\nL = downop(F, m, n); \u039b = gridlaplacian(F, m, n)/2 + I/4; \u039b2 = gridlaplacian(F, m\u00f72, n\u00f72) + I\nheatmap([Matrix(L*invm(\u039b)*L') Matrix(invm(\u039b2)) Matrix(L*invm(\u039b)*L' - invm(\u039b2))])\nmean(diag(L*invm(\u039b)*L') - diag(invm(\u039b2)))\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": "function maximumGap(nums)\n    length(nums) < 2 && return 0\n\n    sort!(nums)\n    largest = 0;\n    last = nums[1]\n    for c in nums\n        (c - last) > largest && begin largest = (c - last) end\n        last = c\n    end\n\n    largest\nend\n\nusing Test\n@test maximumGap([3,6,9,1]) == 3\n@test maximumGap([10]) == 0\n", "meta": {"hexsha": "636389c112c19f12f9b30faa9f1ff9839781b337", "size": 308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Maximum-Gap/MG.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": "Maximum-Gap/MG.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": "Maximum-Gap/MG.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.1111111111, "max_line_length": 62, "alphanum_fraction": 0.5519480519, "num_tokens": 102, "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 = \u03c3(y-x),\n  dy/dt = x(\u03c1-z) -y,\n  dz/dt = xy - \u03b2z\n``\nwhere t\u2208[0,100] and u\u2080= [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    \u03c3, \u03c1, \u03b2 = p\n    du[1] = \u03c3*(y-x)\n    du[2] = x*(\u03c1-z) - y\n    du[3] = x*y - \u03b2*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 ``\u0393_{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_{\u03b1\u03b2}``\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 \u2261 g^{\u03bc\u03bd}R_{\u03bc\u03bd}``\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^{\u03bc\u03bd} \u2261 R^{\u03bc\u03bd} - \\frac{1}{2}\u22c5 g^{\u03bc\u03bd}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, \u03b5::Real)\n    z = x\n    t = 1\n    y = 0\n    while z > a || z < 1/a || t > \u03b5   \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": "using RationalApproximations\nusing PyPlot\n\nS = range(-1, 1, length=100)\nF = exp.(S)\nmax_m = 5\ntol = 1e-6\nr_v1, err = aaa_v1(F, S, max_m, tol)\n\nfigure(1)\nt = range(-1, 1, length=201)\ny = exp.(t)\nfor m = 2:4\n    semilogy(t, abs.(y-r_v1[m].(t)), label=\"m=$m\")\nend\nlegend(loc=\"lower left\")\ngrid(true)\ntitle(\"AAA Version 1: absolute errors\")\n\nr_v2, err = aaa_v2(F, S, max_m, tol)\n\nfigure(2)\nfor m = 2:4\n    semilogy(t, abs.(y-r_v2[m].(t)), label=\"m=$m\")\nend\nlegend(loc=\"lower left\")\ngrid(true)\ntitle(\"AAA Version 2: absolute errors\")\n\nfigure(3)\nplot(t, y-r_v1[4].(t), label=\"V1\")\nplot(t, y-r_v2[4].(t), label=\"V2\")\nlegend()\ngrid(true)\ntitle(\"Comparison of errors when m=4\")\n", "meta": {"hexsha": "40777a9f0b96d0c532afd9af523024f23512b4f8", "size": 669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/exp_aaa.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_aaa.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_aaa.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": 18.5833333333, "max_line_length": 50, "alphanum_fraction": 0.6337817638, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7931882811197593}}
{"text": "using MDP\nusing Test\nusing SparseArrays\n\n# Puterman, Example 3.1\n\nP_01 = Matrix[ [ 0.5  0.5 \n                 0.0  1.0 ],\n               [ 0.0  1.0\n                 0.5  0.5 ] ]\n\nr_01 = [ 5  10\n        -1  -Inf ]\n\nmodel_01 = ProbModel(r_01, P_01; objective = :Max)\n\ndiscount_01  = 0.95\ntolerance_01 = 1e-3\n\n(v_01, g_01) = valueIteration(model_01; discount=discount_01, tolerance=tolerance_01)\n\nv_opt_01 = [ (5.0 - 5.5 * discount_01)/( (1.0 - 0.5 * discount_01) * (1.0 - discount_01) ), \n            -1.0 / ( 1 - discount_01 ) ]\n\n@test isapprox(v_01, v_opt_01; atol=tolerance_01)\n\n# Test for sparse matrices\nP_02 = SparseMatrixCSC[sparse([0.5 0.5; 0.0 1.0]),\n                       sparse([0.0 1.0; 0.5 0.5]) ]\n\nr_02 = [ 5  10\n        -1  -Inf ]\n\nmodel_02 = ProbModel(r_02, P_02; objective = :Max)\n\ndiscount_02  = 0.95\ntolerance_02 = 1e-3\n\n(v_02, g_02) = valueIteration(model_02; discount=discount_02, tolerance=tolerance_02)\n\n@test isapprox(v_02, v_opt_01; atol=tolerance_02) \n", "meta": {"hexsha": "70f8fbe8af588a6350535f1bf0448369785cdf48", "size": 977, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/valueIteration.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": "test/valueIteration.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": "test/valueIteration.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": 23.2619047619, "max_line_length": 92, "alphanum_fraction": 0.5977482088, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7931882811197593}}
{"text": "module Utility\n\nusing LinearAlgebra\nusing Statistics, StatsBase\n\nexport sinkhorn\n\n\"\"\"\n    sinkhorn(A; r=[], c=[], maxit=1000, \u03b4=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 `\u03b4` 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, \u03b4=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 \u2208 1:maxit\n        \u03b4r = maximum(abs.(x.*(A*y)  .- r))\n        \u03b4c = 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, \u03b4r, \u03b4c\n        end\n\n        (isnan(\u03b4r) || isnan(\u03b4c)) && return x, y, false\n        (\u03b4r < \u03b4 && \u03b4c < \u03b4) \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, \u03d5; maxit=1000, \u03b4=1e-6, verbose=false)\n    nrow = size(N,1)\n    ncol = size(N,2)\n\n    N\u00b2 = N.^2\n    u, v = ones(size(N,1)), ones(size(N,2))\n    for i \u2208 1:maxit\n        \u03c3\u00b2 = ((Diagonal(u.^2 ./ (1 .+ \u03d5))*N\u00b2*Diagonal(v.^2)) .+ (Diagonal(u.*\u03d5 ./ (1 .+ \u03d5))*N*Diagonal(v)))\n        \u03b4r = maximum(abs.(sum(\u03c3\u00b2, dims=1) .- nrow))\n        \u03b4c = maximum(abs.(sum(\u03c3\u00b2, dims=2) .- ncol))\n\n        if verbose\n            @show i, \u03b4r, \u03b4c\n        end\n\n        (isnan(\u03b4r) || isnan(\u03b4c)) && return u, v, false\n        (\u03b4r < \u03b4 && \u03b4c < \u03b4) \t\t && return u, v, true\n\n        A = vec(sum(Diagonal(u.^2 ./ (1 .+ \u03d5)) * N\u00b2, dims=1))\n        B = vec(sum(Diagonal(u.*\u03d5 ./ (1 .+ \u03d5)) * N , dims=1))\n\n        v = @. (sqrt(B^2 + 4*A*nrow) - B) / (2*A)\n\n        A = vec(sum(N\u00b2 * Diagonal(v.^2),           dims=2))\n        B = vec(sum(Diagonal(\u03d5) * N * Diagonal(v), dims=2))\n\n        u = @. (sqrt(B^2 + 4*A*ncol*(1+\u03d5)) - 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": "developing = false; # are you developing the package or just using?\nif developing\n\t# ] add Revise # if you don't have it\n    path = pwd()\n    if path[end-6:end] != \"MatLang\"\n        error(\"cd(to the MatLang path)\")\n    end\n    push!(LOAD_PATH, \".\")\n    using Revise\n    using MatLang\nelse\n    using MatLang\nend\n################################################################\n################################################################\nmzero0 = zerosM(:mat, 2) # same as zeros(2,2)\n\nmzero1 = zerosM(:mat, 2, like = zerosM(Int32, 2, 2)) # like method\n\nA=[2 1 2]\nmzero2 = zerosM(2, like=A) # same as zeros(Int64,2)\n\nmzero3 = zerosM(2) # same as zeros(2)\n\nmzero4 = zerosM(Int32, 2, 2) # same as zeros(Int32,2,2)\n\n# giving size as Tuple\nmzero5 = zerosM((2, 2)) # = zerosM(2,2)\n\nmzero6 = zerosM(Int32, (2, 2))\n\n# giving size as an Array\n## non-efficient Matlab way. Array should be Integer otherwise you will get errors.\n\nmzero7 = zerosM([2, 2])\n\nmzero8 = zerosM(Int32, [2, 2])\n\nmzero9 = zerosM([2, 2], like = [2.5 3.0])\n################################################################\nmone0 = onesM(:mat, 2) # same as ones(2,2)\n\nmone1 = onesM(:mat, 2, like = onesM(Int32, 2, 2)) # like method\n\nA=[2 1 2]\nmone2 = onesM(2, like=A) # same as ones(Int64,2)\n\nmone3 = onesM(2) # same as ones(2)\n\nmone4 = onesM(Int32, 2, 2) # same as ones(Int32,2,2)\n\n# giving size as Tuple\nmone5 = onesM((2, 2)) # = onesM(2,2)\n\nmone6 = onesM(Int32, (2, 2))\n\n# giving size as an Array\n## non-efficient Matlab way. Array should be Integer otherwise you will get errors.\n\nmone7 = onesM([2, 2])\n\nmone8 = onesM(Int32, [2, 2])\n\nmone9 = onesM([2, 2], like = [2.5 3.0])\n################################################################\nmrandom0 = randM(:mat, 2) # same as rand(2,2)\n\nmrandom1 = randM(:mat, 2, like = randM(Int32, 2, 2)) # like method\n\nA=[2 1 2]\nmrandom2 = randM(2, like=A) # same as rand(Int64,2)\n\nmrandom3 = randM(2) # same as rand(2)\n\nmrandom4 = randM(Int32, 2, 2) # same as rand(Int32,2,2)\n\n# giving size as Tuple\nmrandom5 = randM((2, 2)) # = randM(2,2)\n\nmrandom6 = randM(Int32, (2, 2))\n\n# giving size as an Array\n## non-efficient Matlab way. Array should be Integer otherwise you will get errors.\n\nmrandom7 = randM([2, 2])\n\nmrandom8 = randM(Int32, [2, 2])\n\nmrandom9 = randM([2, 2], like = [2.5 3.0])\n################################################################\nmtrue0 = trueM(:mat, 2) # same as trues(2,2)\n\nmtrue1 = trueM(2) # same as trues(2)\n\n# giving size as Tuple\nmtrue2 = trueM((2, 2)) # = trues(2,2)\n\n# giving size as an Array\n## non-efficient Matlab way. Array should be Integer otherwise you will get errors.\nmtrue3 = trueM([2, 2])\n################################################################\nmfalse0 = falseM(:mat, 2) # same as falses(2,2)\n\nmfalse1 = falseM(2) # same as falses(2)\n\n# giving size as Tuple\nmfalse2 = falseM((2, 2)) # = falses(2,2)\n\n# giving size as an Array\n## non-efficient Matlab way. Array should be Integer otherwise you will get errors.\nmfalse3 = falseM([2, 2])\n################################################################\nmEye0 = eyeM(2); # [1 0 0; 0 1 0]\n\nmEye1 = eyeM(2, 3); # [1 0 0; 0 1 0]\n\nmEye2 = eyeM(Int32, 2, 3); # [1 0 0; 0 1 0]\n\nmEye3 = eyeM(2, 3, like = zerosM(Int8, 2, 2))\n\nmEye4 = eyeM((2, 2))  # giving size as a Tuple. In Julia we use (2,2) instead of giving it as [2,2]\n\nmEye5 = eyeM(Int32, (2, 2))  # giving size as a Tuple. In Julia we use (2,2) instead of giving it as [2,2]\n\nmEye6 = eyeM([2, 2]) # non-efficient Matlab way\n\nmEye7 = eyeM(Int32, [2, 2]) # non-efficient Matlab way\n\ns1 = size(ones(2, 3)) # getting size from another matrix or calculation\nmEye8 = eyeM(s1)  # giving size as a variable (Tuple).\n################################################################\nmDiag = diagM([2, 3, 4]) # [0 2 0 ; 0 3 0; 0 4]\n\nmDiag2 = diagM([2, 3, 4], 1) # [0 2 3 0; 0 0 3 0; 0 0 0 4; 0 0 0 0]\n\nmDiag3 = diagM([1 2 3; 4 5 6; 7 8 9]) # [1;5;9]\n\nmDiag4 = diagM([1 2 3; 4 5 6; 7 8 9], 1) # [2;6]\n################################################################\nA1 = 3 * ones(2, 2);\nA2 = 4 * ones(2, 2);\nA3 = rand(3, 3);\nmBlkdiag1 = blkdiagM(A1, A2, A3)\n\nmBlkdiag2 = blkdiagM(ones(2, 2), 2 * ones(2, 2)) # [ones(2, 2) zeros(2, 2); zeros(2, 2)  2 * ones(2, 2)]\n\nA1 = ones(2, 4);\nA2 = 2 * ones(3, 2);\nmBlkdiag3 = blkdiagM(A1, A2) # [ones(2,4) zeros(2,2); zeros(3,4) 2*ones(3,2)]\n\nmBlkdiag1obj = blkdiagM(:obj, A1, A2, A3) # returning BlockDiagonal object\n\nmBlkdiag2obj = blkdiagM(:obj, ones(2, 2), 2 * ones(2, 2)) # returning BlockDiagonal object for [ones(2, 2) zeros(2, 2); zeros(2, 2)  2 * ones(2, 2)]\n################################################################\nmCat1 = catM(1, ones(3, 3), zeros(3, 3)) # [ones(3, 3); zeros(3, 3)]\n\nmCat2 = catM(2, ones(3, 3), zeros(3, 3)) # [ones(3, 3) zeros(3, 3)]\n\nmCat3 = catM(1, ones(3, 3), zeros(3, 3), 2 * ones(3, 3)) # [ones(3, 3); zeros(3, 3); 2 * ones(3, 3)]\n\nmCat4 = catM(3, ones(2, 2, 2), zeros(2, 2, 2)) # [ones(2, 2, 2) zeros(2, 2, 2)]\n################################################################\nmHCat1 = horzcatM(ones(3, 3), zeros(3, 3)) # [ones(3, 3) zeros(3, 3)]\n################################################################\nmVCat1 = vertcatM(ones(3, 3), zeros(3, 3)) # [ones(3, 3); zeros(3, 3)]\n################################################################\nV1 = [1 2 3 4];\nmRepelem1 = repelemM(V1, 3) # [1 1 1 2 2 2 3 3 3 4 4 4]\n\n# mRepelem2 = repelemM(V1, (3,2,1,1)) # [1 1 1 2 2 3 4]\n\n# mRepelem3 = repelemM(V1, vec([3 2 1 1])) # [1 1 1 2 2 3 4]\n################################################################\nmRempat1 = repmatM(10, 3, 2) # [10 10; 10 10; 10 10]\n\nV = [1; 2]\nmRempat2 = repmatM(V, 3, 2)   # [[1; 2] [1; 2]; [1; 2] [1; 2]; [1; 2] [1; 2]]\n\nmRempat3 = repmatM(V, [3, 2]) # [[1; 2] [1; 2]; [1; 2] [1; 2]; [1; 2] [1; 2]]\n\nmRempat4 = repmatM(V, (3, 2)) # [[1; 2] [1; 2]; [1; 2] [1; 2]; [1; 2] [1; 2]]\n\nmRempat5 = repmatM(V, 2) # [[1; 2] [1; 2]; [1; 2] [1; 2]]\n\nmRempat6 = repmatM(V, 1, 3) # [[1; 2] [1; 2] [1; 2]]\n################################################################\nmLinspace1 = linspaceM(1, 10) # 1:10\n\nmLinspace2 = linspaceM(1, 10, 2) # 1:2:10 == 1:2:9\n\nmLinspace3 = linspaceM(:arr, 1, 10) # collect(1:10)\n\nmLinspace4 = linspaceM(:arr, 1, 10, 2) # collect(1:2:10)\n################################################################\nmLogspace1 = logspaceM(1, 5) # 50 logarithmically spaced points between 10^1 and 10^5\n\nmLogspace2 = logspaceM(1, 5, 10) # 10 logarithmically spaced points between 10^1 and 10^5\n\nmLogspace3 = logspaceM(1, 5, :equal) # [10.0^1, 10.0^2, 10.0^3, 10.0^4, 10.0^5] == 10.0.^(1:5)\n################################################################\nm1Meshgrid0, m2Meshgrid0 = meshgridM(1:2:5) # a 2-D rectangle spanning 1:2:5 in x and y direction == [[1;1;1][3;3;3] [5;5;5]] and [1 1 1; 3 3 3; 5 5 5]\n\nm1Meshgrid1, m2Meshgrid1 = meshgridM(1:2:5, 1:2:5) #  a 2-D rectangle spanning 1:2:5 in x and y direction == ([1 3 5;1 3 5; 1 3 5],[1 1 1; 3 3 3; 5 5 5])\n\nm1Meshgrid2, m2Meshgrid2, m3Meshgrid2 = meshgridM(1:6, 20:25, 5:10) # a 3-D rectangle spanning 1:6 in x, 20:25 in y, and 5:10 in z\n################################################################\nm1Ndgrid0, m2Ndgrid0 = ndgridM(1:2:5, dim = 2) # a 2-D rectangle spanning 1:2:5 in x and y direction == [1 1 1; 3 3 3; 5 5 5] and [1 3 5;1 3 5; 1 3 5]\n\nm1Ndgrid1, m2Ndgrid1 = ndgridM(1:2:5, 1:2:5) #  a 2-D rectangle spanning 1:2:5 in x and y direction == ([1 1 1; 3 3 3; 5 5 5], [1 3 5;1 3 5; 1 3 5])\n\nm1Ndgrid2, m2Ndgrid2, m3Ndgrid2 = ndgridM(1:6, 20:25, 5:10) # a 3-D rectangle spanning 1:6 in x, 20:25 in y, and 5:10 in z\n################################################################\nmFreqspace1 = freqspaceM(10, dim = 1) # 0:0.2:1\n\nmFreqspace2 = freqspaceM(10, :whole, dim = 1) # 0:0.2:1.8\n\nm1Freqspace3, m2Freqspace3 = freqspaceM(10, dim = 2) # returns two -1:0.2:0.8\n\nm1Freqspace4, m2Freqspace4 = freqspaceM(10, :meshgrid, dim = 2) # returns mesgridM(-1:0.2:0.8, -1:0.2:0.8), which is two -1:0.2:0.8\n################################################################\nA1 = [2 3 4 5 6 7;\n      1 2 3 4 5 6]\nnLength1 = lengthM(A1); # 6\n\nA2 = [\"Hi\" 6;\n      \"Goodbye\" 5;\n      \"Hello\" 1]\nnLength2 = lengthM(A2); # 3\n################################################################\nA1 = [2 3 4 5 6 7;\n      1 2 3 4 5 6]\nmSize1 = sizeM(:arr, A1); # [2; 6]\ntSize1 = sizeM(A1); # (2, 6)\n\nnA1Size2 = sizeM(A1, 2); # 6\nsizeM(A1, 2) == 6 # true\nsizeM(:arr, A1, 2) == 6 # false\nsizeM(:arr, A1, 2) == [6] # true\n\nnA1Size1, nA1Size2 = sizeM(A1); # 2 and 6\n\nA2 = rand(3, 5, 4)\nmSize2 = sizeM(:arr, A2, 2, 3); # [5; 4]\ntSize2 = sizeM(A2, 2, 3); # (5, 4)\n################################################################\nA = rand(3,4,5);\nnDim1 = ndims(A) # 3\n################################################################\nnNumel1 = numelM(1:5) # 5\n\nnNumel2 = numelM([1, 2, 3, 4]) # 4\n\nnNumel3 = numelM([1 2; 3 4]) # 4\n################################################################\nbIsscalar1 = isscalarM(1) # true\n\nbIsscalar2 = isscalarM(5 * ones(1, 1, 1)) # false\n\n# bIsscalar3 = isscalarM(\"H\") # gives error\n#\n# bIsscalar4 = isscalarM(\"Hi\") # gives error\n\nbIsscalar5 = isscalarM([\"Hi\"]) # false\n\nbIsscalar6 = isscalarM([\"Hi\" \"Bye\"]) # false\n\nbIsscalar7 = isscalarM('H') # true # becareful that in Julia, chars are always singular.\n\nbIsscalar8 = isscalarM(true) # true\n\n# Matlab way:\nbIsscalarMat1 = isscalarM(:mat, 1) # true\n\nbIsscalarMat2 = isscalarM(:mat, [1]) # true\n\nbIsscalarMat3 = isscalarM(:mat, 5 * ones(1, 1, 1)) # true\n\nbIsscalarMat4 = isscalarM(:mat, \"H\") # true\n\nbIsscalarMat5 = isscalarM(:mat, \"Hi\") # false\n\nbIsscalarMat6 = isscalarM(:mat, [\"Hi\"]) # true\n\nbIsscalarMat7 = isscalarM(:mat, [\"Hi\" \"Bye\"]) # false\n\nbIsscalarMat8 = isscalarM(:mat, 'H') # true # becareful that in Julia, chars are always singular.\n\nbIsscalarMat9 = isscalarM(:mat, true) # true\n################################################################\nA1 = [1; 2; 3] # or [1, 2, 3]\nbIsvector1 = isvectorM(A1) # true\n\nA2 = [1 2 3]\nbIsvector2 = isvectorM(A2) # false\n\nbIsvector3 = isvectorM(ones(3, 1)) # false\n\nbIsvector4 = isvectorM(ones(1, 3)) # false\n\nbIsvector5 = isvectorM(ones(3)) # true\n\nbIsvector6 = isvectorM(1) # false\n\nbIsvector7 = isvectorM(\"Hi\") # false\n\nbIsvector8 = isvectorM([\"Hi\", \"Bye\"]) # true\n\nbIsMatrix9 = isvectorM([\"Hi\" \"Bye\"]) # false\n\n# Matlab Way:\nbIsvectorMat1 = isvectorM(:mat, A1) # true\n\nbIsvectorMat2 = isvectorM(:mat, A2) # true\n\nbIsvectorMat3 = isvectorM(:mat, ones(3, 1)) # true\n\nbIsvectorMat4 = isvectorM(:mat, ones(1, 3)) # true\n\nbIsvectorMat5 = isvectorM(:mat, ones(3)) # true\n\nbIsvectorMat6 = isvectorM(:mat, 1) # true\n\nbIsvectorMat7 = isvectorM(:mat, \"Hi\") # true\n\nbIsvectorMat8 = isvectorM(:mat, [\"Hi\", \"Bye\"]) # true\n################################################################\nA1 = [1 2 3; 3 5 6]\nbIsMatrix1 = ismatrixM(A1) # true\n\nA2 = [1;2;3] # or [1,2,3]\nbIsMatrix2 = ismatrixM(A2) # false\n\nbIsMatrix3 = ismatrixM(ones(3, 1)) # true\n\nbIsMatrix4 = ismatrixM(ones(1, 3)) # true\n\nbIsMatrix5 = ismatrixM(ones(3)) # false\n\nbIsMatrix6 = ismatrixM(\"Hi\") # false\n\nbIsMatrix7 = ismatrixM([\"Hi\", \"Bye\"]) # false\n\nbIsMatrix8 = ismatrixM([\"Hi\" \"Bye\"]) # true\n\n# Matlab Way:\n\nbIsMatrixMat1 = ismatrixM(:mat, A1) # true\n\nbIsMatrixMat2 = ismatrixM(:mat, A2) # true\n\nbIsMatrixMat3 = ismatrixM(:mat, ones(3, 1)) # true\n\nbIsMatrixMat4 = ismatrixM(:mat, ones(1, 3)) # true\n\nbIsMatrixMat5 = ismatrixM(:mat, ones(3)) # true\n\nbIsMatrixMat6 = ismatrixM(:mat, \"Hi\") # true\n\nbIsMatrixMat7 = ismatrixM(:mat, [\"Hi\", \"Bye\"]) # true\n################################################################\nA1 = [1; 2; 3] # or [1, 2, 3]\nbIsrow1 = isrowM(A1) # false\n\nA2 = [1 2 3]\nbIsrow2 = isrowM(A2) # true\n\nbIsrow3 = isrowM(ones(3, 1)) # false\n\nbIsrow4 = isrowM(ones(1, 3)) # true\n\nbIsrow5 = isrowM(ones(3)) # false\n\nbIsrow6 = isrowM(1) # false\n\nbIsrow7 = isrowM(\"Hi\") # false\n\nbIsrow8 = isrowM([\"Hi\", \"Bye\"]) # false\n\nbIsrow9 = isrowM([\"Hi\" \"Bye\"]) # true\n\n# Matlab Way:\nbIsrowMat1 = isrowM(:mat, A1) # false\n\nbIsrowMat2 = isrowM(:mat, A2) # true\n\nbIsrowMat3 = isrowM(:mat, ones(3, 1)) # false\n\nbIsrowMat4 = isrowM(:mat, ones(1, 3)) # true\n\nbIsrowMat5 = isrowM(:mat, ones(3)) # false\n\nbIsrowMat6 = isrowM(:mat, 1) # true\n\nbIsrowMat7 = isrowM(:mat, \"Hi\") # true\n\nbIsrowMat8 = isrowM(:mat, [\"Hi\", \"Bye\"]) # false\n################################################################\nA1 = [1; 2; 3] # or [1, 2, 3]\nbIscolumn1 = iscolumnM(A1) # false\n\nA2 = [1 2 3]\nbIscolumn2 = iscolumnM(A2) # false\n\nbIscolumn3 = iscolumnM(ones(3, 1)) # tue\n\nbIscolumn4 = iscolumnM(ones(1, 3)) #false\n\nbIscolumn5 = iscolumnM(ones(3)) # false\n\nbIscolumn6 = iscolumnM(1) # false\n\nbIscolumn7 = iscolumnM(\"Hi\") # false\n\nbIscolumn8 = iscolumnM([\"Hi\", \"Bye\"]) # false\n\nbIscolumn9 = iscolumnM([\"Hi\" \"Bye\"]) # false\n\n# Matlab Way:\nbIscolumnMat1 = iscolumnM(:mat, A1) # true\n\nbIscolumnMat2 = iscolumnM(:mat, A2) # false\n\nbIscolumnMat3 = iscolumnM(:mat, ones(3, 1)) # true\n\nbIscolumnMat4 = iscolumnM(:mat, ones(1, 3)) # false\n\nbIscolumnMat5 = iscolumnM(:mat, ones(3)) # true\n\nbIscolumnMat6 = iscolumnM(:mat, 1) # true\n\nbIscolumnMat7 = iscolumnM(:mat, \"Hi\") # true\n\nbIscolumnMat8 = iscolumnM(:mat, [\"Hi\", \"Bye\"]) # true\n################################################################\nmSort0 = sortM([5, 3, 19, 20, 1, 4]) # [1, 3, 4, 5, 19, 20]\n\nA = [5, 3, 19, 20, 1, 4]\nmSort1, iSort1 = sortM(A, I = true)  # returning sort index\nA[iSort1] == mSort1\n\nmSort2 = sortM([5, 3, 19, 20, 1, 4], :descend) # [20,19,5,4,3,1]\n\nmSort3 = sortM([1 5 3; 4 1 10]) # [1 1 3; 4 5 10]\n\nmSort4 = sortM([1 5 3; 4 1 10], 2, :ascend) # [1 3 5; 1 4 10]\n\nB = [1 5 3; 4 1 10]\nmSort5, iSort5 = sortM(B, 2, :ascend, I = true) # [1 3 5; 1 4 10]\nB[iSort5] == mSort5\n\nA = zerosM(Integer, 2, 2, 2)\nA[:, :, 1] = [2 3; 1 6]\nA[:, :, 2] = [-1 9; 0 12]\nmSort6 = sortM(A, 3) # 3D sort\n################################################################\nsFlip1 = flipM(\"Hi\") # \"iH\"\n\nmFlip2 = flipM([1; 2; 3; 4]) #[4;3;2;1]\n\nmFlip3 = flipM([1 2; 3 4]) # flips every column: # [3 4; 1 2]\n\nmFlip4 = flipM([1 2; 3 4], 2) # flip along dims 2: #[2 1; 4 3]\n################################################################\nmRot1 = rot90M([1 2; 3 4]) #[2 4; 1 3]\n\nmRot2 = rot90M([1 2; 3 4], 3) # [3 1; 4 2]\n################################################################\nA1 = [2 3 4 5 6 7;\n      1 2 3 4 5 6]\nmTranspose1 = transposeM(A1)\n\nmTranspose2 = transposeM(:arr, A1)\n################################################################\nA1 = ones(2, 1, 2); # 3 dimensional\nmSqueeze1 = squeezeM(A1) # [1 1; 1 1]\n\nA2 = zeros(1, 4, 1);\nA2[:, 1:4, ] = [5; 3; 6; 0]\nmSqueeze2 = squeezeM(A2) # When it gets one dimensional, it is vertical.\n\nmSqueeze2 == [5; 3; 6; 0] # true\nmSqueeze2 == [5 3 6 0] # false\n################################################################\n", "meta": {"hexsha": "9c52d9c7ab1d5a907277828083ba2874ede5ceeb", "size": 14681, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Language_Fundamentals/usage_Matrices_and_Arrays.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MatLang.jl-05b439c0-bb3c-11e9-1d8d-1f0a9ebca87a", "max_stars_repo_head_hexsha": "6b6d6b1ee0b5e126ce766ad0671103ff9e2d726a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-08-10T22:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T03:57:55.000Z", "max_issues_repo_path": "examples/Language_Fundamentals/usage_Matrices_and_Arrays.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MatLang.jl-05b439c0-bb3c-11e9-1d8d-1f0a9ebca87a", "max_issues_repo_head_hexsha": "6b6d6b1ee0b5e126ce766ad0671103ff9e2d726a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-08-15T07:56:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T08:04:54.000Z", "max_forks_repo_path": "examples/Language_Fundamentals/usage_Matrices_and_Arrays.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MatLang.jl-05b439c0-bb3c-11e9-1d8d-1f0a9ebca87a", "max_forks_repo_head_hexsha": "6b6d6b1ee0b5e126ce766ad0671103ff9e2d726a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:59:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T03:57:57.000Z", "avg_line_length": 30.3326446281, "max_line_length": 153, "alphanum_fraction": 0.5178802534, "num_tokens": 6080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.880797085800514, "lm_q1q2_score": 0.793184006586502}}
{"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,\u03b1,v)\n  @assert(0 \u2264 \u03b1 < 1, \"needs probably \u03b1\")\n  @assert(all(vi -> vi \u2265 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(\u03b1)) # upper bound on steps\n  for i=1:nsteps\n    x = \u03b1*(A'*(x./d)) .+ (1-\u03b1).*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": "using JuMP\n\n### Place optimization problem definition and solve in a function\nfunction solveOptProb1(a,b)\n\tm = Model()\n\t@variable(m, 0 <= x <= 2 )\n\t@variable(m, 0 <= y <= 30 )\n\n\t@objective(m, Max, a*x + 3*y )\n\t@constraint(m, 1x + 5y <= b )\n\t\n\tstatus = solve(m)\n\t\n\treturn getobjectivevalue(m), [getvalue(x); getvalue(y)], status\n\t\nend\n\n### Test function\n\n(obj, z, status) = solveOptProb1(1,1)\n\n\n### Iterate over possible values of a and b\naOpt = 0:5\nbOpt = 1:3\n\naN = length(aOpt)\nbN = length(bOpt)\n\nobjValues = zeros(aN,bN)\nzValues = zeros(2,aN,bN)\n\nfor i in 1:length(aOpt)\n\tfor j in 1:length(bOpt)\n\t\t(objValues[i,j], zValues[:,i,j], status) = solveOptProb1(aOpt[i],bOpt[j])\n\tend\nend\n\nprintln(\"objValues = \")\nprintln(objValues)\nprintln(\" \")\n\nprintln(\"zValues = \")\nprintln(zValues)\nprintln(\" \")", "meta": {"hexsha": "f54bb0afdbb0258b950114563ff1a7ed4c740c4f", "size": 792, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/basic_JuMP_ex2.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_ex2.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_ex2.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": 17.6, "max_line_length": 75, "alphanum_fraction": 0.6502525253, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482725, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7931436860447555}}
{"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# \u2554\u2550\u2561 6e58a278-ede3-440f-b5ad-c23d03833918\nusing LinearAlgebra\n\n# \u2554\u2550\u2561 81465bdf-4eb3-4dc5-8f60-2ccdca956e73\nmd\"#### Sigmoid\"\n\n# \u2554\u2550\u2561 78b943f0-ae7b-11eb-3de1-d5cfb31433c6\nfunction \u03c3(x)\n\tt = exp(-abs(x))\n\treturn ifelse(x \u2265 0, inv(1 + t), t / (1 + t))\nend\n\n# \u2554\u2550\u2561 6fe8d0a2-fd10-4097-95c8-fea57d2a32e8\nconst sigmoid = \u03c3\n\n# \u2554\u2550\u2561 112f4771-632e-4c35-81bd-ec7f09b40dc0\nmd\"#### ReLU\"\n\n# \u2554\u2550\u2561 257e3608-759e-49b2-aa9f-88211bba198b\nrelu(x) = max(zero(x), x)\n\n# \u2554\u2550\u2561 5b4291e3-1f67-46ac-89f5-d00aaefdac8a\nsigmoid(4) == \u03c3(4)\n\n# \u2554\u2550\u2561 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\u03c3(weights \u22c5 inputs + bias),\n\t\trelu(weights \u22c5 inputs + bias)\n\t)\nend\n\n# \u2554\u2550\u2561 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\u03c3.(weights_matrix * inputs + bias_vec), \n\t\trelu.(weights_matrix * inputs + bias_vec)\n\t)\nend\n\n# \u2554\u2550\u2561 0e4a6376-d3fa-47fc-b140-ddb65ee0c592\nmd\"#### Softmax\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u25506e58a278-ede3-440f-b5ad-c23d03833918\n# \u255f\u250081465bdf-4eb3-4dc5-8f60-2ccdca956e73\n# \u2560\u255078b943f0-ae7b-11eb-3de1-d5cfb31433c6\n# \u2560\u25506fe8d0a2-fd10-4097-95c8-fea57d2a32e8\n# \u255f\u2500112f4771-632e-4c35-81bd-ec7f09b40dc0\n# \u2560\u2550257e3608-759e-49b2-aa9f-88211bba198b\n# \u2560\u25505b4291e3-1f67-46ac-89f5-d00aaefdac8a\n# \u2560\u255045ba9913-5316-457e-9f97-2622661397e1\n# \u2560\u2550e2f8442b-5ccd-431a-8881-3e746b0eb047\n# \u255f\u25000e4a6376-d3fa-47fc-b140-ddb65ee0c592\n# \u2560\u2550afbe3c9c-6db4-415c-921d-cdc4033e9b06\n# \u2560\u2550662251f6-03ae-4ea6-8bd1-e90ec8a10805\n# \u2560\u2550383304f8-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    \u03c1 = sqrt(x^2 + y^2 + z^2) #distance\r\n    \u03b8 = atand(y,x) #horizontal angle\r\n    \u03d5 = acosd(z/\u03c1) #incidence angle\r\n    cart = (\u03c1,\u03b8,\u03d5)\r\n    return cart\r\nend\r\n\r\n\"Convert Spherical to Cartesian coordinates\"\r\nfunction pol2cart(\u03c1::Float64, \u03b8::Float64, \u03d5::Float64)\r\n    pol = Tuple{Float64,Float64,Float64}\r\n    x = (\u03c1 * sind(\u03d5) * cosd(\u03b8))\r\n    y = (\u03c1 * sind(\u03d5) * sind(\u03b8))\r\n    z = (\u03c1 * cosd(\u03d5))\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    \u0394x, \u0394y, \u0394z = (x1-x0), (y1-y0), (z1-z0)\r\n    ind = underwater[1]\r\n    #Calculate the distance of the two points (\u03c1), the vertical-incidence angle (\u03d5) and horizontal angle (\u03b8) between the two points\r\n    \u03c1,\u03b8,\u03d5 = cart2pol(\u0394x, \u0394y, \u0394z)\r\n\r\n    #Calculate the underwater angle due to the refraction effect.\r\n    #Using Snell's Law: n(air)*sin(\u03d5_air) = n(water)*sin(\u03d5_water),\r\n    #where \u03d5_air: the angle of incidence (I know that the angle of the scan is 20)\r\n    #      \u03d5_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        \u03d5_water = asind(n_air_water*sind(\u03d5)) #\u03d5_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, \u03c1 = c_air * t and \u03c1_water = c_water * t.\r\n    #So, by diving these two equations, the ratio (\u03c11/\u03c12) = n_air_water\r\n    \u03c1_water = (\u03c1*n_air_water)\r\n\r\n    #Calculate the correction in the 3d space using the pol2cart function\r\n    xcor, ycor, zcor = pol2cart(\u03c1_water, \u03b8, \u03d5_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\u03b81, \u03b82 = q\n\n\t[0.5 * model.l1 * sin(\u03b81);\n\t -0.5 * model.l1 * cos(\u03b81)]\nend\n\nfunction kinematics_2(model::DoublePendulum, q)\n\t\u03b81, \u03b82 = q\n\n\t[model.l1 * sin(\u03b81) + 0.5 * model.l2 * sin(\u03b81 + \u03b82);\n\t -model.l1 * cos(\u03b81) - 0.5 * model.l2 * cos(\u03b81 + \u03b82)]\nend\n\n# fast kinematics functions\n@variables q[1:n]\n@variables q\u0307[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\u0307)\n\tL = 0.0\n\n\t# mass 1\n\tv1 = j1_func(q) * q\u0307\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\u0307\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\u0307)\n\ndLq = Symbolics.gradient(L, q, simplify = true)\ndLq\u0307 = Symbolics.gradient(L, q\u0307, simplify = true)\nddL = Symbolics.hessian(L, [q; q\u0307], 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\u0307 - dLq\nC = simplify.(C)\n\n# dynamics\n# x\u0307 = [q\u0307; M \\ (-1.0 * C)]\nx\u0307 = [q\u0307; M \\ (-0.5 * q\u0307 -1.0 * C)]\nx\u0307 = simplify.(x\u0307)\n\nx\u0307_exp = Symbolics.build_function(x\u0307, q, q\u0307)\ndynamics = eval(x\u0307_exp[1])\n\n# save dynamics function\npath = joinpath(pwd(), \"dynamics.jld2\")\n# @save path x\u0307_exp\n# @load path x\u0307_exp\n\n# DifferentialEquations.jl\nfunction dynamics!(x\u0307, x, p, t)\n\tx\u0307 .= dynamics(view(x, 1:n), view(x, n .+ (1:n)))\nend\n\n# simulate\nx0 = [0.5 * \u03c0; 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, \u0394t = 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": "using Distributions\nusing Base.Test\n\n# Set location vector mu and scale matrix Sigma as in\n# Hofert M. On Sampling from the Multivariate t Distribution. The R Journal\nmu = [1., 2]\nSigma = [4. 2; 2 3]\n\n# LogPDF evaluation for varying degrees of freedom df\n# Julia's output is compared to R's corresponding values obtained via R's mvtnorm package\n# R code exemplifying how the R values (rvalues) were obtained:\n# options(digits=20)\n# library(\"mvtnorm\")\n# mu <- 1:2\n# Sigma <- matrix(c(4, 2, 2, 3), ncol=2)\n# dmvt(c(-2., 3.), delta=mu, sigma=Sigma, df=1)\nrvalues = [-5.6561739738159975133,\n  -5.4874952805811396672,\n  -5.4441948098568158088,\n  -5.432461875138580254,\n  -5.4585441614404803801]\ndf = [1., 2, 3, 5, 10]\nfor i = 1:length(df)\n  d = MvTDist(df[i], mu, Sigma)\n  @test_approx_eq_eps logpdf(d, [-2., 3]) rvalues[i] 1.0e-8\nend\n", "meta": {"hexsha": "ed4973f8635c567589f83c2c26100d74a426efa5", "size": 830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mvtdist.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": "test/mvtdist.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": "test/mvtdist.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": 30.7407407407, "max_line_length": 89, "alphanum_fraction": 0.6975903614, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7928882624802237}}
{"text": "mutable struct UncertaintyTrapEcon{TF<:AbstractFloat, TI<:Integer}\n    a::TF          # Risk aversion\n    \u03b3_x::TF        # Production shock precision\n    \u03c1::TF          # Correlation coefficient for \u03b8\n    \u03c3_\u03b8::TF        # Standard dev of \u03b8 shock\n    num_firms::TI  # Number of firms\n    \u03c3_F::TF        # Std dev of fixed costs\n    c::TF          # External opportunity cost\n    \u03bc::TF          # Initial value for \u03bc\n    \u03b3::TF          # Initial value for \u03b3\n    \u03b8::TF          # Initial value for \u03b8\n    \u03c3_x::TF        # Standard deviation of shock\nend\n\nfunction UncertaintyTrapEcon(;a::AbstractFloat=1.5, \u03b3_x::AbstractFloat=0.5,\n                             \u03c1::AbstractFloat=0.99, \u03c3_\u03b8::AbstractFloat=0.5,\n                             num_firms::Integer=100, \u03c3_F::AbstractFloat=1.5,\n                             c::AbstractFloat=-420.0, \u03bc_init::AbstractFloat=0.0,\n                             \u03b3_init::AbstractFloat=4.0,\n                             \u03b8_init::AbstractFloat=0.0)\n    \u03c3_x = sqrt(a / \u03b3_x)\n    UncertaintyTrapEcon(a, \u03b3_x, \u03c1, \u03c3_\u03b8, num_firms, \u03c3_F, c, \u03bc_init,\n                        \u03b3_init, \u03b8_init, \u03c3_x)\n\nend\n\nfunction \u03c8(uc::UncertaintyTrapEcon, F::Real)\n    temp1 = -uc.a * (uc.\u03bc - F)\n    temp2 = 0.5 * uc.a^2 * (1 / uc.\u03b3 + 1 / uc.\u03b3_x)\n    return (1 / uc.a) * (1 - exp(temp1 + temp2)) - uc.c\nend\n\n\"\"\"\nUpdate beliefs (\u03bc, \u03b3) based on aggregates X and M.\n\"\"\"\nfunction update_beliefs!(uc::UncertaintyTrapEcon, X::Real, M::Real)\n    # Simplify names\n    \u03b3_x, \u03c1, \u03c3_\u03b8 = uc.\u03b3_x, uc.\u03c1, uc.\u03c3_\u03b8\n\n    # Update \u03bc\n    temp1 = \u03c1 * (uc.\u03b3 * uc.\u03bc + M * \u03b3_x * X)\n    temp2 = uc.\u03b3 + M * \u03b3_x\n    uc.\u03bc =  temp1 / temp2\n\n    # Update \u03b3\n    uc.\u03b3 = 1 / (\u03c1^2 / (uc.\u03b3 + M * \u03b3_x) + \u03c3_\u03b8^2)\nend\n\nupdate_\u03b8!(uc::UncertaintyTrapEcon, w::Real) =\n    (uc.\u03b8 = uc.\u03c1 * uc.\u03b8 + uc.\u03c3_\u03b8 * w)\n\n\"\"\"\nGenerate aggregates based on current beliefs (\u03bc, \u03b3).  This\nis a simulation step that depends on the draws for F.\n\"\"\"\nfunction gen_aggregates(uc::UncertaintyTrapEcon)\n    F_vals = uc.\u03c3_F * randn(uc.num_firms)\n\n    M = sum(\u03c8.(uc, F_vals) .> 0)  # Counts number of active firms\n    if M > 0\n        x_vals = uc.\u03b8 + uc.\u03c3_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 ApproxFun, SingularIntegralEquations, Base.Test\n\n## quadratic\n\na=1+10*im;b=2-6*im\nd=Curve(Fun(x->1+a*x+b*x^2))\n\n\nx=Fun(d)\nw=sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x))\n\n@test_approx_eq cauchy(w,2.) (-4.722196879007759+2.347910413861846im)\n@test_approx_eq cauchy(w,2.) sum(w/(x-2.))/(2\u03c0*im)\n@test_approx_eq logkernel(w,2.) linesum(w*log(abs(x-2.)))/\u03c0\n\n\nw=1/(sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x)))\n\n@test_approx_eq cauchy(w,2.) sum(w/(x-2.))/(2\u03c0*im)\n@test_approx_eq logkernel(w,2.) linesum(w*log(abs(x-2.)))/\u03c0\n@test_approx_eq (SingularIntegral(0)*w)(fromcanonical(d,0.1)) logkernel(w,fromcanonical(d,0.1))\n@test_approx_eq (Hilbert()*w)(fromcanonical(d,0.1)) hilbert(w,fromcanonical(d,0.1))\n\n\n\n\n## cubic\n\na=1+10*im;b=2-6*im\nd=Curve(Fun(x->1+a*x+x^2+b*x^3))\n\n\nx=Fun(d)\nw=sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x))\n\n\n@test_approx_eq cauchy(w,2.) sum(w/(x-2.))/(2\u03c0*im)\n@test_approx_eq logkernel(w,2.) linesum(w*log(abs(x-2.)))/\u03c0\n\n\nw=1/(sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x)))\n\n@test_approx_eq cauchy(w,2.) sum(w/(x-2.))/(2\u03c0*im)\n@test_approx_eq logkernel(w,2.) linesum(w*log(abs(x-2.)))/\u03c0\n@test_approx_eq (SingularIntegral(0)*w)(fromcanonical(d,0.1)) logkernel(w,fromcanonical(d,0.1))\n@test_approx_eq (Hilbert()*w)(fromcanonical(d,0.1)) hilbert(w,fromcanonical(d,0.1))\n\n\n\n## quartic\n\na=1+10*im;b=2-6*im\nd=Curve(Fun(x->1+a*x+x^2+x^3+b*x^4))\n\n\nx=Fun(d)\nw=sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x))\n\n@test_approx_eq cauchy(w,2.) sum(w/(x-2.))/(2\u03c0*im)\n@test_approx_eq logkernel(w,2.) linesum(w*log(abs(x-2.)))/\u03c0\n\n\n\nw=1/(sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x)))\n\n@test_approx_eq cauchy(w,2.) sum(w/(x-2.))/(2\u03c0*im)\n@test_approx_eq logkernel(w,2.) linesum(w*log(abs(x-2.)))/\u03c0\n@test_approx_eq (SingularIntegral(0)*w)(fromcanonical(d,0.1)) logkernel(w,fromcanonical(d,0.1))\n@test_approx_eq (Hilbert()*w)(fromcanonical(d,0.1)) hilbert(w,fromcanonical(d,0.1))\n\n\n\n## Arc\n\nd=exp(im*Interval(0.1,0.2))\nx=Fun(d)\nw=sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x))\n\n\nz=10.;\n@test_approx_eq sum(w/(x-z))/(2\u03c0*im) cauchy(w,z)\n@test_approx_eq sum(w*log(z-x))/(-2\u03c0*im) cauchyintegral(w,z)\n@test_approx_eq linesum(w*log(abs(z-x)))/\u03c0 logkernel(w,z)\n\nw=1/(sqrt(abs(first(d)-x))*sqrt(abs(last(d)-x)))\n@test_approx_eq sum(w/(x-z))/(2\u03c0*im) cauchy(w,z)\n@test_approx_eq sum(w*log(z-x))/(-2\u03c0*im) cauchyintegral(w,z)\n@test_approx_eq linesum(w*log(abs(z-x)))/\u03c0 logkernel(w,z)\n@test_approx_eq (SingularIntegral(0)*w)(fromcanonical(d,0.1)) logkernel(w,fromcanonical(d,0.1))\n@test_approx_eq (Hilbert()*w)(fromcanonical(d,0.1)) hilbert(w,fromcanonical(d,0.1))\n", "meta": {"hexsha": "901697b3b1852e50a78a1d57fe9364bf574d2acf", "size": 2527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/CurveTest.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": "test/CurveTest.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": "test/CurveTest.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": 27.7692307692, "max_line_length": 95, "alphanum_fraction": 0.6747130985, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7928822928156758}}
{"text": "using Test, LinearAlgebra\nusing MethodOfLines\n\n@testset \"finite-difference weights from fornberg(1988) & fornberg(2020)\" begin\n    order = 2; z = 0.0; x = [-1, 0, 1.0];\n    @test MethodOfLines.calculate_weights(order, z, x) == [1,-2,1]  # central difference of second-derivative with unit-step\n\n    order = 1; z = 0.0; x = [-1., 1.0];\n    @test MethodOfLines.calculate_weights(order, z, x) == [-0.5,0.5] # central difference of first-derivative with unit step\n\n    order = 1; z = 0.0; x = [0, 1];\n    @test MethodOfLines.calculate_weights(order, z, x) == [-1, 1] # forward difference\n\n    order = 1; z = 1.0; x = [0, 1];\n    @test MethodOfLines.calculate_weights(order, z, x) == [-1, 1] # backward difference\n\n    # forward-diff of third derivative with order of accuracy == 3\n    order = 3; z = 0.0; x = [0,1,2,3,4,5]\n    @test MethodOfLines.calculate_weights(order, z, x) == [-17/4, 71/4, -59/2, 49/2, -41/4, 7/4]\n    \n    order = 3; z = 0.0; x = collect(-3:3)\n    d, e = MethodOfLines.calculate_weights(order, z, x;dfdx = true)\n    @test d \u2248 [-167/18000, -963/2000, -171/16,0,171/16,963/2000,167/18000]\n    @test e \u2248 [-1/600,-27/200,-27/8,-49/3,-27/8,-27/200,-1/600]\n    \n    order = 3; z = 0.0; x = collect(-4:4)\n    d, e = MethodOfLines.calculate_weights(order, z, x;dfdx = true)\n    @test d \u2248 [-2493/5488000, -12944/385875, -87/125 ,-1392/125,0,1392/125,87/125,12944/385875,2493/5488000]\n    @test e \u2248 [-3/39200,-32/3675,-6/25,-96/25,-205/12, -96/25, -6/25,-32/3675,-3/39200]\nend\n", "meta": {"hexsha": "126522cf103e27d424a07ecd91886cd3bd2a7321", "size": 1486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/components/MOLfornberg_weights.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/components/MOLfornberg_weights.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/components/MOLfornberg_weights.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": 47.935483871, "max_line_length": 124, "alphanum_fraction": 0.6150740242, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485394, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.79285738515552}}
{"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) \u2248 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) \u2248 fill(0., (dim, dim)) \nend\n    \n    \"\"\"\n    is_unitary(s)\n\nA unitary matrix U is defined by U\u2020U = UU\u2020 = 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) \u2248 Id\nend \n\n\"\"\"\n    is_hermitian(s)\n\nA hermitian matrix U is defined by U = \u2020U.\nreturns true if s is hermitian.\n\"\"\"\n# throws error if not hermitian\nfunction is_hermitian(s)\n    LinearAlgebra.checksquare(s);\n    s \u2248 conj_transpose(s)\nend\n\n\"\"\"\n    is_normed(s)\n\nif sum(s .^ 2)) \u2248 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 \u2248 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 \u22c5 b).\n\"\"\"\n# use \u22c5 ?\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    \u03b2_00 = Cgate(X) * kron(H * ket_0, ket_0)\n    \u03b2_01 = Cgate(X) * kron(H * ket_0, ket_1)\n    \u03b2_10 = Cgate(X) * kron(H * ket_1, ket_0)\n    \u03b2_11 = Cgate(X) * kron(H * ket_1, ket_1)\n    \u03b2_00, \u03b2_01, \u03b2_10, \u03b2_11\nend\n\n\n\"\"\"\n    cauchy_schwarz(u, v)\n\ngiven arbitrary column vectors `|u\u27e9, |v\u27e9`, we want to show that,\n\n\u27e8u|u\u27e9\u27e8v|v\u27e9 \u2265 |\u27e8u|v\u27e9|\u00b2\n\"\"\"\n\nfunction cauchy_schwarz(u, v)\n\nend\n# function eulerform(U)\n    # thm \n    # U single qubit unitary \u27f9 \u2203 \u03b1, \u03b2, \u03b3, \u03b4 \u2208 \u211d, st \n    # U = exp(i\u03b1) * [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 nlp_cvx_102_014(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n\n    @objective(model, Min, (x - 0.65)^2 + (y - 0.65)^2)\n    @NLconstraint(model, x^2 + y^2 <= 1.0)\n    @constraint(model, x + y >= 1.2)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, 0, tol = objective_tol)\n    return check_solution([x, y], [0.65, 0.65], tol = primal_tol)\nend\n", "meta": {"hexsha": "b19a47f992c185d58de8dece47bcbff7c2002ea3", "size": 620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/102_014.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/102_014.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/102_014.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 25.8333333333, "max_line_length": 76, "alphanum_fraction": 0.6629032258, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7928573746031639}}
{"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, \u03c40, \u03c41, \u03c3, \u03b8)\n    true_log_probs = map(p -> compute_log_joint(data, p, \u03c40, \u03c41, \u03c3, \u03b8), 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": "using LinearAlgebra\nusing Test\n\nfunction learn_dot()\n    x = [1.0, 2.0, 3.0]\n    y = [1.0, 2.0, 3.0]\n    @test 1+4+9 == dot(x,y)\n    x = [1.0, 2.0, 3.0]\n    y = [4.0, 5.0, 6.0]\n    @test 4+10+18 == dot(x,y)\nend\n\n@testset \"Base\" begin\n    learn_dot()\nend\n\nnothing\n", "meta": {"hexsha": "1da7bc35c2e856d666433f6f552bc27ff2a3c917", "size": 263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "learn/learn_LinearAlgebra.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": "learn/learn_LinearAlgebra.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": "learn/learn_LinearAlgebra.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.6111111111, "max_line_length": 29, "alphanum_fraction": 0.5171102662, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222694, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7928546116967674}}
{"text": "# Each new term in the Fibonacci sequence is generated by adding the previous two terms.\n# 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\nis_even(x) = ((x % 2) == 0)\nsum = 0\nfibonacci(n) = n < 2 ? n : fibonacci(n-1) + fibonacci(n-2)\ni = 2\ncurrent = fibonacci(i)\n\nwhile current < 4e6\n\n    println(current)\n    global current, i, sum\n    sum += is_even(current) ? current : 0\n\n    i += 1\n    current = fibonacci(i)\nend\nprintln()\nprintln(sum)\nprintln()\n", "meta": {"hexsha": "fc60e0b368aac4117e2de0aa5c01952568159bcd", "size": 636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_2.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_2.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_2.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": 23.5555555556, "max_line_length": 88, "alphanum_fraction": 0.6572327044, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.964321450147636, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7928546083383359}}
{"text": "# contours \n\nusing Plots\nx = 1:0.5:20\ny = 1:0.5:10\nf(x, y) = begin\n        (3x + y ^ 2) * abs(sin(x) + cos(y))\n    end\nX = repeat(reshape(x, 1, :), length(y), 1)\nY = repeat(y, 1, length(x))\nZ = map(f, X, Y)\np1 = contour(x, y, f, fill = true)\np2 = contour(x, y, Z)\nplot(p1, p2)\n\n\n\n#Makie\n\nusing CairoMakie\n\nf = Figure(backgroundcolor = :honeydew)\nAxis(f[1, 1])\n\nxs = LinRange(0, 10, 100)\nys = LinRange(0, 15, 100)\nzs = [cos(x) * sin(y) for x in xs, y in ys]\n\nCairoMakie.contour!(zs,levels=-1:0.1:1)\n\nf\n", "meta": {"hexsha": "a89c08127cab38271188e44b05b53dfe29c39e85", "size": 501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/contours/contours.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/contours/contours.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/contours/contours.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": 15.65625, "max_line_length": 43, "alphanum_fraction": 0.5688622754, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.7928263738710871}}
{"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 (\u03ba::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": "######### StanVariational Bernoulli example  ###########\n\nusing StanVariational, Test\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# Use tmpdir across multiple runs to prevent re-compilation\n#tmpdir = joinpath(@__DIR__, \"tmp\")\n\nsm = VariationalModel(\"variational\", bernoulli_model)\n\n(sample_file, log_file) = stan_variational(sm; data=bernoulli_data)\n\nif sample_file !== Nothing\n\n  (chns, cnames) = read_variational(sm)\n\n  # Show the same output in DataFrame format\n  sdf = read_summary(sm)\n\n  # Retrieve mean value of theta from the summary\n  sdf[:theta, :mean]\n  @test sdf[:theta, :mean][1] \u2248 0.33 atol=0.1\n\nend", "meta": {"hexsha": "7b48f5709152733ac0d6dc5af64378ebf57d6c47", "size": 827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Examples_Stan_Methods/Variational/variational.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Stan.jl-682df890-35be-576f-97d0-3d8c8b33a550", "max_stars_repo_head_hexsha": "9391a60eef08e6065240c0c46efe8e9851e151fa", "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/Examples_Stan_Methods/Variational/variational.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Stan.jl-682df890-35be-576f-97d0-3d8c8b33a550", "max_issues_repo_head_hexsha": "9391a60eef08e6065240c0c46efe8e9851e151fa", "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/Examples_Stan_Methods/Variational/variational.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Stan.jl-682df890-35be-576f-97d0-3d8c8b33a550", "max_forks_repo_head_hexsha": "9391a60eef08e6065240c0c46efe8e9851e151fa", "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.2051282051, "max_line_length": 71, "alphanum_fraction": 0.6590084643, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7928047435714338}}
{"text": "@testset \"Interval matrix methods\" begin\n    m = IntervalMatrix([-1.1..0.9 -4.1.. -3.9; 3.8..4.2 0.0..0.9])\n    @test opnorm(m) == opnorm(m, Inf) \u2248 5.2\n    @test opnorm(m, 1) \u2248 5.3\n\n    l = inf(m)\n    r = sup(m)\n    c = mid(m)\n    d = diam(m)\n    rad = radius(m)\n    m2 = copy(m)\n    @test m2 isa IntervalMatrix && m.mat == m2.mat\n    @test l == inf.(m) && r == sup.(m) && c == mid.(m)\n    @test d \u2248 r - l\n    @test rad \u2248 d/2\n\n    sm = scale(m, 2.0)\n    @test sm ==  2.0 .* m\n    @test sm \u2260 m\n    scale!(m, 2.0) # in-place\n    @test sm == m\n\n    m3 = IntervalMatrix([-2.0..2.0 -2.0..0.0; 0.0..2.0 -1.0..1.0])\n    m4 = IntervalMatrix([-1.0..1.0 -1.0..1.0; -1.0..1.0 -2.0..2.0])\n    @test m3 \u2229 m4 == IntervalMatrix([-1.0..1.0 -1.0..0.0; 0.0..1.0 -1.0..1.0])\n    @test m3 \u222a m4 == IntervalMatrix([-2.0..2.0 -2.0..1.0; -1.0..2.0 -2.0..2.0])\n    @test diam_norm(m3) \u2248 6.0 # default diameter p-norm is Inf\n    @test diam_norm(m3, 1) \u2248 6.0\nend\n\n@testset \"Interval matrix membership\" begin\n    m = IntervalMatrix([-1.1..0.9 -4.1.. -3.9; 3.9..4.1 -1.1..0.9])\n    a1 = [0. -4.;  4. 0.]\n    a2 = [0. -3.; 4. 0.]\n    @test a1 \u2208 m\n    @test a2 \u2209 m\nend\n\n@testset \"Interval matrix inclusion\" begin\n    m1 = IntervalMatrix([-1.1..0.9 -4.1.. -3.9; 3.9..4.1 -1.1..0.9])\n    m2 = IntervalMatrix([-1.2..1.0 -4.1.. -3.9; 3.9..4.2 -1.2..0.9])\n    @test m1 \u2286 m2 && !(m2 \u2286 m1)\n\nend\n\n@testset \"Interval matrix rand\" begin\n    m = IntervalMatrix([-1.1..0.9 -4.1.. -3.9; 3.9..4.1 -1.1..0.9])\n    for i in 1:3\n        @test rand(m) \u2208 m\n    end\nend\n", "meta": {"hexsha": "a289fa86b394b0d0d979965e599a75c020d033a4", "size": 1519, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 29.2115384615, "max_line_length": 79, "alphanum_fraction": 0.4950625411, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746095, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.792780116506987}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.8\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 86a927d5-0b05-4a7a-83c4-0f98fb15509e\nbegin\n\tusing PlutoUI\n\tusing Plots\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 435ece74-d26a-11eb-1bd1-5b65d058f3a1\nmd\"\"\"\n## 4.1\n\u30c8\u30ea\u30dc\u30ca\u30c3\u30c1\u6570\u5217\u306e\u7b2c$N$\u9805\u306e\u5024\u3092\u6c42\u3081\u308b\u518d\u8d77\u95a2\u6570\u3092\u8a2d\u8a08\u3057\u3066\u304f\u3060\u3055\u3044.\n\"\"\"\n\n# \u2554\u2550\u2561 4a01190f-1e0e-4371-9847-e66eeab849b9\nfunction f\u2081(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\u2081(n - 1) + f\u2081(n - 2) + f\u2081(n - 3)\nend\n\n# \u2554\u2550\u2561 0224c51b-3028-45f0-bf6c-7423aac643a6\nwith_terminal() do\n\tfor n \u2208 0:9\n\t\tprintln(\"n = $n: $(f\u2081(n))\")\n\tend\nend\n\n# \u2554\u2550\u2561 aa51aa81-b8be-4e65-b259-e816655d01c9\nplot(n -> (@timed f\u2081(n)).time, 1:33,\n\ttitle = \"Computational Time of Naive Tribonacci\",\n\txlabel = \"n\",\n\tylabel = \"Seconds\",\n\tlegend = false\n)\n\n# \u2554\u2550\u2561 5d8bedcf-6f20-4be3-961b-3b81ef486209\nmd\"\"\"\n## 4.2\n\u554f\u984c4.1\u3067\u8a2d\u8a08\u3057\u305f\u518d\u5e30\u95a2\u6570\u3092\u30e1\u30e2\u5316\u306b\u3088\u3063\u3066\u52b9\u7387\u5316\u3057\u3066\u304f\u3060\u3055\u3044.\n\u307e\u305f, \u30e1\u30e2\u5316\u3092\u5b9f\u65bd\u5f8c\u306e\u8a08\u7b97\u91cf\u3092\u8a55\u4fa1\u3057\u3066\u304f\u3060\u3055\u3044.\n\"\"\"\n\n# \u2554\u2550\u2561 1f806382-2995-4da2-b33d-c0403c530163\nfunction f\u2082(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\u2082(n - 1, memo) + f\u2082(n - 2, memo) + f\u2082(n - 3, memo)\n\tmemo[n] = res\n\treturn res\nend\n\n# \u2554\u2550\u2561 645cdd0a-97c5-4a90-a70e-09a3571142db\nwith_terminal() do\n\tfor n \u2208 0:9\n\t\tprintln(\"n = $n: $(f\u2082(n))\")\n\tend\nend\n\n# \u2554\u2550\u2561 d65730a4-ec5f-436f-876b-fc98eb203107\nmd\"\"\"\n\u8a08\u7b97\u91cf\u306f$T_0, \\dots, T_{N-1}$\u307e\u3067\u30e1\u30e2\u5316\u3055\u308c\u3066\u3044\u308b\u6642, $T_N$\u306e\u8a08\u7b97\u91cf\u304c$O(1)$\u3067\u3042\u308b\u3053\u3068\u304b\u3089, $O(N)$.\n\"\"\"\n\n# \u2554\u2550\u2561 3ac6e8f6-a3e9-4d81-a271-5457b20477bc\nplot(n -> median((@timed f\u2082(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# \u2554\u2550\u2561 f6e73830-ad09-4718-868d-26f6a2c11b16\nmd\"\"\"\n## 4.3\n\u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\u6570\u5217\u306e\u4e00\u822c\u9805\u304c\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\u3067\u8868\u3055\u308c\u308b\u3053\u3068\u3092\u793a\u3057\u3066\u304f\u3060\u3055\u3044.\n\"\"\"\n\n# \u2554\u2550\u2561 65503b27-14d4-42c8-abec-70060988d465\nmd\"\"\"\n**\u7b54**\n$F_0 = 1, F_1 = 1$\u306f\u81ea\u660e. \u4e00\u822c\u9805\u3092$F_{N-1}$\u307e\u3067\u4eee\u5b9a\u3057\u3066,\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\u3088\u3063\u3066,\n$F_N = F_{N - 1} + F_{N - 2}$.\n\u5e30\u7d0d\u6cd5\u304b\u3089, \u547d\u984c\u306f\u793a\u3055\u308c\u305f.\n\"\"\"\n\n# \u2554\u2550\u2561 ae54b3e7-e04c-457f-839d-8aeecb6eba0d\nmd\"\"\"\n## 4.4\n\u30b3\u30fc\u30c9 4.5\u3067\u793a\u3057\u305f\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u306e\u8a08\u7b97\u91cf\u304c $O\\left(\\left(\\frac{1 + \\sqrt{5}}{2}\\right)^N\\right)$ \u3067\u4e0e\u3048\u3089\u308c\u308b\u3053\u3068\u3092\u793a\u3057\u3066\u304f\u3060\u3055\u3044.\n\"\"\"\n\n# \u2554\u2550\u2561 e0cd89ce-9a49-4d51-9c36-1b467b3e4add\nmd\"\"\"\n**\u7b54** \u30b3\u30fc\u30c94.5\u306e\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u306e\u8a08\u7b97\u91cf\u304c$O(f(N))$\u3067\u3042\u308b\u3068\u4eee\u5b9a\u3059\u308b.\n\u5b9a\u7fa9\u304b\u3089, $f(0) = f(1) = 1$\u306f\u81ea\u660e. \u307e\u305f, Big O\u306e\u8a08\u7b97\u898f\u5247\u3068\u30b3\u30fc\u30c9\u306e\u5b9a\u7fa9\u304b\u3089,\n\n$f(N) = f(N - 1) + f(N - 2).$\n\n\u3053\u308c\u306f\u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\u6570\u5217\u3068\u4e00\u81f4\u3057, \u4e00\u822c\u9805\u306f\u554f4.3\u3067\u793a\u3055\u308c\u305f\u901a\u308a\u3067\u3042\u308b.\n\u652f\u914d\u9805\u306f$\\left(\\frac{1 + \\sqrt{5}}{2}\\right)^N$\u3067\u3042\u308b\u304b\u3089, \u547d\u984c\u306f\u793a\u3055\u308c\u305f.\n\"\"\"\n\n# \u2554\u2550\u2561 0303b656-d949-4365-b884-bf7bbc026a6d\nmd\"\"\"\n## 4.6\n\u90e8\u5206\u548c\u554f\u984c\u306b\u5bfe\u3059\u308b\u518d\u5e30\u95a2\u6570\u3092\u7528\u3044\u308b\u8a08\u7b97\u91cf$O(2^N)$\u306e\u30b3\u30fc\u30c94.9\u306b\u5bfe\u3057\u3066\u30e1\u30e2\u5316\u3057\u3066, $O(NW)$ \u306e\u8a08\u7b97\u91cf\u3067\u52d5\u4f5c\u3059\u308b\u3088\u3046\u306b\u3057\u3066\u304f\u3060\u3055\u3044.\n\"\"\"\n\n# \u2554\u2550\u2561 14bcda24-9431-468a-ac5b-4bf6feb1e8e8\nfunction f\u2086(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\u2086(as, w, i - 1, memo)\n\t\tmemo[i, w] = 1\n\t\treturn true\n\telseif f\u2086(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# \u2554\u2550\u2561 501824d0-017f-4d05-a477-cd7f4cef1df8\nwith_terminal() do\n\tprintln(\"Given a = [2, 4, 8]\")\n\tfor w \u2208 1:16\n\t\tprintln(\"w = $w: $(f\u2086([2, 4, 8], w))\")\n\tend\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25005d15bae3-d408-4f74-98a3-8b5e53562770\n# \u2560\u255086a927d5-0b05-4a7a-83c4-0f98fb15509e\n# \u255f\u2500435ece74-d26a-11eb-1bd1-5b65d058f3a1\n# \u2560\u25504a01190f-1e0e-4371-9847-e66eeab849b9\n# \u255f\u25000224c51b-3028-45f0-bf6c-7423aac643a6\n# \u255f\u2500aa51aa81-b8be-4e65-b259-e816655d01c9\n# \u255f\u25005d8bedcf-6f20-4be3-961b-3b81ef486209\n# \u2560\u25501f806382-2995-4da2-b33d-c0403c530163\n# \u255f\u2500645cdd0a-97c5-4a90-a70e-09a3571142db\n# \u255f\u2500d65730a4-ec5f-436f-876b-fc98eb203107\n# \u255f\u25003ac6e8f6-a3e9-4d81-a271-5457b20477bc\n# \u255f\u2500f6e73830-ad09-4718-868d-26f6a2c11b16\n# \u255f\u250065503b27-14d4-42c8-abec-70060988d465\n# \u255f\u2500ae54b3e7-e04c-457f-839d-8aeecb6eba0d\n# \u255f\u2500e0cd89ce-9a49-4d51-9c36-1b467b3e4add\n# \u255f\u25000303b656-d949-4365-b884-bf7bbc026a6d\n# \u2560\u255014bcda24-9431-468a-ac5b-4bf6feb1e8e8\n# \u255f\u2500501824d0-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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.17\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.17\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u25506b47d86c-2163-11eb-157b-136057260d22\n# \u2560\u25506b480968-2163-11eb-0f1c-d18166a51f5e\n# \u255f\u250070182cd8-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\u00d73 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\u00d74 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\u00d74 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\u03c0\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\u03c0 - (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\u2081, a\u2082, a\u2083, b\u2081, b\u2082, b\u2083 = (p...,)\n    x1, x2, x3, y1, y2, y3 = u[1], u[2], u[3], u[4], u[5], u[6] \n    \n    dx1 = -a\u2081*(x2 + x3)\n    dx2 = a\u2081*(x1 + a\u2082*x2)\n    dx3 = a\u2081*(a\u2082 + x3*(x1 - a\u2083))\n    dy1 = b\u2081*(-y1 + y2)\n    dy2 = b\u2082*y1 - y2 - y1*y3 + c_xy*(x2^2)\n    dy3 = y1*y2 - b\u2083*y3\n    \n    return SVector{6}(dx1, dx2, dx3, dy1, dy2, dy3)\nend\n\n\"\"\"\n    rossler_lorenz(;u\u2080 = rand(6), a\u2081 = -6, a\u2082 = 6, a\u2083 = 2.0, \n        b\u2081 = 10, b\u2082 = 28, b\u2083 = 8/3, c_xy = 1) \u2192 ContinuousDynamicalSystem\n\nInitialise a R\u00f6ssler-Lorenz system consisting of two independent 3D subsystems:\none R\u00f6ssler system and one Lorenz system. They are coupled such that the\nsecond component (`x\u2082`) of the R\u00f6ssler system unidirectionally forces the\nsecond component (`y\u2082`) 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\u2081`, `a\u2082`, `a\u2083`, `b\u2081`, `b\u2082`, `b\u2083`. 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\u00e1, 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\u2080 = rand(6), a\u2081 = -6, a\u2082 = 6, a\u2083 = 2.0, \n    b\u2081 = 10, b\u2082 = 28, b\u2083 = 8/3, c_xy = 1)\n\n    p = @LArray [c_xy, a\u2081, a\u2082, a\u2083, b\u2081, b\u2082, b\u2083] (:c_xy, :a\u2081, :a\u2082, :a\u2083, :b\u2081, :b\u2082, :b\u2083)\n    ContinuousDynamicalSystem(eom_rossler_lorenz, u\u2080, 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 \u03ba_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\u03ba_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, _ , _ , \u03c8 , d\u03c8 = 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(\u03c8, Nx*Ny)\n         vy = Dy * reshape(\u03c8, Nx*Ny)\n\n        #Potential term\n        v2 = Vpot * reshape(\u03c8, Nx*Ny)\n     \n        #Add all terms\n        for i in 1:(Nx*Ny) #length(\u03c8)\n            E+= vx[i]^2 + vy[i]^2 + d\u03c8[i]^2 + (p.\u03bc)^2*\u03c8[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, _ , _ , \u03c8 , d\u03c8 = 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(\u03c8, Nx*Ny)\n         vy = Dy * reshape(\u03c8, Nx*Ny)\n\n        #Potential term\n       # v2 = Vpot * reshape(\u03c8, Nx*Ny)\n     \n        #Add all terms\n        for i in 1:(Nx*Ny) #length(\u03c8)\n            E+= vx[i]^2 + vy[i]^2 + d\u03c8[i]^2 # + (p.\u03bc)^2*\u03c8[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  \u03b1, \u03b2, \u03b4, \u03b3 = p\n  du[1] = dx = \u03b1*x - \u03b2*x*y\n  du[2] = dy = -\u03b4*y + \u03b3*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\u03c3N=0.1\ndata+=\u03c3N*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(\u2207f::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 ``\u2207f=Q.x^\\star+q``\n\"\"\"\nfunction check_first_order(\u2207f::AbstractVector{<:Real},\n                           xstar::AbstractVector{<:Real},\n                           bc::BoundConstraints{<:Real,1})\n\n    # the condition assumes feasible constraints\n    @assert xstar \u2208 bc\n\n    @assert size(\u2207f)==size(xstar)\n\n    # TODO: refactoring to avoid mem alloc\n    # (-> inline computation of max(...sequence...)\n    v = xstar-\u2207f\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    \u2207f=Q*xstar+q\n    check_first_order(\u2207f,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# \u2554\u2550\u2561 f252364e-f2e3-11ea-09b5-ff1a685abd56\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 c126b36a-f2e3-11ea-1b0f-a7d38ecffcd8\nmd\"## Clip-03-01t.jl\"\n\n# \u2554\u2550\u2561 f2526f60-f2e3-11ea-2d32-276d0b91d917\n@quickactivate \"StatisticalRethinkingTuring\"\n\n# \u2554\u2550\u2561 f252ea76-f2e3-11ea-093a-01c585ee2ea1\nmd\"### snippet 3.1\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f25b24a2-f2e3-11ea-302d-f3e7f49f645b\nmd\"## End of clip-03-01t.jl\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500c126b36a-f2e3-11ea-1b0f-a7d38ecffcd8\n# \u2560\u2550f252364e-f2e3-11ea-09b5-ff1a685abd56\n# \u2560\u2550f2526f60-f2e3-11ea-2d32-276d0b91d917\n# \u255f\u2500f252ea76-f2e3-11ea-093a-01c585ee2ea1\n# \u2560\u2550f25a9eec-f2e3-11ea-1611-9129817fe7a6\n# \u255f\u2500f25b24a2-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 + \u03c0/2\n        elseif x > 0 && y < 0\n            -c\n        elseif x < 0 && y < 0\n            -c - \u03c0/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# \u2554\u2550\u2561 10c7a648-1488-11eb-0f9c-c3bfe711a449\nmd\" ### Nomenclatura\"\n\n# \u2554\u2550\u2561 10170496-1488-11eb-0882-df72e258d63c\nmd\"Seja $X$ uma matriz com dimens\u00f5es $n x m$ com $n$ linhas e $m$ colunas que cont\u00e9m nossos exemplos. $X_i^{(j)}$ corresponde ao elemento de $X$ em que $i$ \u00e9 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# \u2554\u2550\u2561 3996c40e-1489-11eb-266a-95abbb9cd199\nmd\"Seja $\\theta$ um vetor linha com $m$ elementos tal que $m$ corresponde ao n\u00famero de atributos mais um. $\\theta = [\\theta^{(0)},\\theta^{(1)}, ...,\\theta^{(m)}]$ em que cada elemento corresponde ao j-\u00e9simo par\u00e2metro associado ao j-\u00e9simo atributo. Na nossa lingugaem acessamos um elemento por $\\theta[i]$ e o vetor por $\\theta$\"\n\n# \u2554\u2550\u2561 391d5e2a-1489-11eb-15d4-77bf4828cfcd\nmd\"Seja $y$ nosso vetor alvo em que representamos o i-\u00e9simo elemento por $y_i$. Na nossa linguagem representamos por $y[i]$.\"\n\n# \u2554\u2550\u2561 794e1306-1487-11eb-203c-37766708b1a2\nmd\" ### Hip\u00f3tese e modelo linear\"\n\n# \u2554\u2550\u2561 7882a5fe-1487-11eb-3f45-fd54863cdfbd\nmd\"$H_{\\theta}(X_i) = \\sum_{j}^{m}{x_{i}^{(j)} \\theta^{(j)}} = X_i\\theta^{T}$\"\n\n# \u2554\u2550\u2561 272f710e-1f99-11eb-21f0-d98d7f2445c8\nmd\"Exemplificando o produto de vetores, nossa hip\u00f3tese faria o seguinte c\u00e1lculo para um exemplo $X_i = \\begin{bmatrix} 1 & 500 \\end{bmatrix}$ e um vetor de par\u00e2metros $\\theta = \\begin{bmatrix}\n    0.5 \\\\\n    1.0\n\\end{bmatrix}$:\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 295c3c20-1f99-11eb-20df-1b793c23e91f\nmd\"Note que o resultado \u00e9 um escalar, pois estamos estimando um valor cont\u00ednuo (problema de regress\u00e3o).\"\n\n# \u2554\u2550\u2561 f6213c24-1486-11eb-0981-ad6addc2a8ef\nmd\" ### Fun\u00e7\u00e3o de custo\"\n\n# \u2554\u2550\u2561 d8c3e0d8-1485-11eb-3eab-a11e3d31269f\n\nmd\"$J(\\theta)= \\frac{1}{2n}\\sum_{i=1}^{n}{(H_{\\theta}(X_i) - y_i)\u00b2} = \\frac{1}{2n}\\sum_{i=1}^{n}{(X_i\\theta^T - y_i)\u00b2} = J_2$\"\n\n\n# \u2554\u2550\u2561 be81b7b2-148b-11eb-222c-135499b083cf\nmd\"que pode ser expandido ainda mais na forma: \"\n\n# \u2554\u2550\u2561 d16ba126-148b-11eb-388b-ed88f5dc2099\nmd\"$= \\frac{1}{2n}\\sum_{i=1}^{n}{(\\sum_{j=1}^{m}X_{i}^{(j)}\\theta_{j} - y_i)\u00b2} = J_1$\"\n\n# \u2554\u2550\u2561 1980e48e-148d-11eb-282a-155aa6620659\nmd\"Podemos ainda calcular toda a fun\u00e7\u00e3o de custo apenas por opera\u00e7\u00f5es de matrizes e vetores sem um la\u00e7o de repeti\u00e7\u00e3o expl\u00edcito da seguinte forma:\"\n\n# \u2554\u2550\u2561 b3ed93fc-1406-11eb-34d4-31acb0c7d641\nbegin \n   import Statistics: mean\n   import BenchmarkTools: @benchmark, @btime\n   import StaticArrays: @SMatrix\t\n   \u03bc = mean\t\nend\n\n# \u2554\u2550\u2561 35a275a0-1402-11eb-3ce4-fba2f21b24d6\nfunction J\u2081(\u0398,\u03c7,\u03b3)\n     n,m = size(\u03c7)\n\t \u2211 = 0.0\n\t for i=1:n\n\t\th = 0.0\n\t\tfor j=1:m \n\t\t   h += \u0398[j] * \u03c7[i,j]\n\t\tend\n\t\t\u2211 += (h - \u03b3[i])^2\n\t end\n\t .5\u2211/n\nend \n\n# \u2554\u2550\u2561 1c4d435e-140d-11eb-1585-476688f1ec0c\nfunction J\u2082(\u0398,\u03c7,\u03b3)\n     n,m = size(\u03c7)\n\t \u2211 = 0.0\n\t for (x,y) in zip(eachrow(\u03c7),\u03b3)\n\t\t\u2211 += (\u0398*x .- y).^2 ...\n\t end\n\t .5\u2211/n\nend \n\n# \u2554\u2550\u2561 329221e4-1498-11eb-0569-d9bde9e62e1a\nmd\" \u00c9 poss\u00edvel ainda vetorizar todo o c\u00e1lculo sem precisar fazer um loop expl\u00edcito. Desta maneira, geramos em uma multiplica\u00e7\u00e3o de matrizes, um vetor de predi\u00e7\u00f5es com a mesma dimens\u00e3o da sa\u00edda. Ap\u00f3s isto, subtra\u00edmos elemento a elemento. Ap\u00f3s isto, elevamos cada elemento ao quadrado e depois tiramos uma m\u00e9dia.\"\n\n# \u2554\u2550\u2561 19392bd6-1405-11eb-3022-bbaecf23c544\nJ\u2083(\u0398,\u03c7,\u03b3) = .5\u03bc((\u03c7*\u0398' .- \u03b3).^2) \n\n# \u2554\u2550\u2561 7b5e9f88-1498-11eb-2acf-a139d4c8e8fb\nmd\" Abaixo temos um exemplo de teste da fun\u00e7\u00e3o de custo.\"\n\n# \u2554\u2550\u2561 48f06c34-1405-11eb-067e-cbe31a8e3cf3\nbegin\n\t\u0398 =  @SMatrix [0. 4.] \n\t\u03c7 =  @SMatrix [1 50.;1 60.;1 100.; 1 200.]\n\t\u03b3 =  @SMatrix [200  ;   240  ;   400; 800]\n\tJ\u2081(\u0398,\u03c7,\u03b3),J\u2082(\u0398,\u03c7,\u03b3),J\u2083(\u0398,\u03c7,\u03b3)\nend\t\n\n# \u2554\u2550\u2561 1c69de24-1499-11eb-1151-bbc0bf07a89c\nmd\"### Medindo o tempo computacional\"\n\n# \u2554\u2550\u2561 93db1528-1498-11eb-035d-efef99b051ed\nmd\"Podemos medir o tempo de cada fun\u00e7\u00e3o a partir de um benchmark. \u00c9 importante ressaltar que diversas otimiza\u00e7\u00f5es 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 \u00e0 compatibilidade com libs de fortran dierentemente de outras linguagens como C, C++, ... H\u00e1 ainda otimiza\u00e7\u00f5es com vetores est\u00e1ticos, macros como @inbounds, ... tudo isto pode acelerar ainda mais seu c\u00f3digo.\"\n\n# \u2554\u2550\u2561 cdfe994c-1415-11eb-01c0-13fd220aaa92\n@benchmark J\u2081(\u0398,\u03c7,\u03b3) seconds=1 gctrial=true\n#@benchmark J\u2082(\u0398,\u03c7,\u03b3) seconds=1 gctrial=true\n#@benchmark J\u2083(\u0398,\u03c7,\u03b3) seconds=1 gctrial=true\n\n# \u2554\u2550\u2561 7ee07dd4-149d-11eb-1f6d-2d565ee61a12\nmd\" ### E se fosse voc\u00ea escolhesse os valores de $\\theta$ ?\"\n\n# \u2554\u2550\u2561 7fff1162-149d-11eb-2ec6-c3ad197a6d4c\n\n\n# \u2554\u2550\u2561 6aa7e186-14a2-11eb-287d-35f60c88cc0b\n@bind \u03b8\u2080 html\"<input type='range' step='0.1' min='-10' max='10'>\"\n\n# \u2554\u2550\u2561 d357e744-14a2-11eb-2652-c35400acb3cf\n@bind \u03b8\u2081 html\"<input type='range' step='0.1' min='-10' max='10'>\"\n\n# \u2554\u2550\u2561 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] = \u03b8\u2080 + \u03b8\u2081*x[i]\n\t\t#y[i] = \u03b8\u2080 + \u03b8\u2081^2*x[i]\n\t\t#y[i] = \u03b8\u2080 + \u03b8\u2081*x[i]^2\n\t\t\n\tend\n\tplot(x,y,xlims = (0,300),ylims = (100,900),xlabel=\"Metros\",ylabel=\"Pre\u00e7o\",label=\"estimado\");\n\tscatter!(\u03c7[:,2],\u03b3[:],xlims = (0,300),ylims = (100,900),label=\"exemplo\");\nend\n\n# \u2554\u2550\u2561 8ef513d8-14a2-11eb-3f6e-5b2f0a09363e\n\u03b8 = [\u03b8\u2080 \u03b8\u2081]\n\n# \u2554\u2550\u2561 7c888c54-14a5-11eb-315f-3d32578eaf32\nmd\"##### Erro : $(J\u2081([\u03b8\u2080 \u03b8\u2081],\u03c7,\u03b3))\"\n\n# \u2554\u2550\u2561 bfd7693a-14a5-11eb-3479-057e03ef43f4\nmd\" ### Gr\u00e1fico do modelo linear\"\n\n# \u2554\u2550\u2561 f17bfc22-14b3-11eb-319a-47522cda243c\nmd\"### Curva de erro\"\n\n# \u2554\u2550\u2561 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\u2081([i j],\u03c7,\u03b3))\n\t\tend\n\tend\n\tprintln(\"e = \",e)\n\tscatter(1:1:10,e,xlabel=\"\u03b8\u2081\",ylabel=\"J\",label=\"erro\") # apenas com rela\u00e7\u00e3o \u00e0 \u03b8\u2081. para fazer com \u03b8\u2080 ter\u00edamos outro eixo e ter\u00edamos uma superf\u00edcie. \n\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u255010c7a648-1488-11eb-0f9c-c3bfe711a449\n# \u2560\u255010170496-1488-11eb-0882-df72e258d63c\n# \u2560\u25503996c40e-1489-11eb-266a-95abbb9cd199\n# \u2560\u2550391d5e2a-1489-11eb-15d4-77bf4828cfcd\n# \u255f\u2500794e1306-1487-11eb-203c-37766708b1a2\n# \u2560\u25507882a5fe-1487-11eb-3f45-fd54863cdfbd\n# \u255f\u2500272f710e-1f99-11eb-21f0-d98d7f2445c8\n# \u255f\u25002821e75e-1f99-11eb-2f10-831050151433\n# \u255f\u2500295c3c20-1f99-11eb-20df-1b793c23e91f\n# \u255f\u2500f6213c24-1486-11eb-0981-ad6addc2a8ef\n# \u255f\u2500d8c3e0d8-1485-11eb-3eab-a11e3d31269f\n# \u255f\u2500be81b7b2-148b-11eb-222c-135499b083cf\n# \u255f\u2500d16ba126-148b-11eb-388b-ed88f5dc2099\n# \u255f\u25001980e48e-148d-11eb-282a-155aa6620659\n# \u2560\u2550b3ed93fc-1406-11eb-34d4-31acb0c7d641\n# \u2560\u255035a275a0-1402-11eb-3ce4-fba2f21b24d6\n# \u2560\u25501c4d435e-140d-11eb-1585-476688f1ec0c\n# \u2560\u2550329221e4-1498-11eb-0569-d9bde9e62e1a\n# \u2560\u255019392bd6-1405-11eb-3022-bbaecf23c544\n# \u255f\u25007b5e9f88-1498-11eb-2acf-a139d4c8e8fb\n# \u2560\u255048f06c34-1405-11eb-067e-cbe31a8e3cf3\n# \u255f\u25001c69de24-1499-11eb-1151-bbc0bf07a89c\n# \u255f\u250093db1528-1498-11eb-035d-efef99b051ed\n# \u2560\u2550cdfe994c-1415-11eb-01c0-13fd220aaa92\n# \u2560\u25507ee07dd4-149d-11eb-1f6d-2d565ee61a12\n# \u255f\u25007fff1162-149d-11eb-2ec6-c3ad197a6d4c\n# \u2560\u25506aa7e186-14a2-11eb-287d-35f60c88cc0b\n# \u255f\u2500d357e744-14a2-11eb-2652-c35400acb3cf\n# \u2560\u25508ef513d8-14a2-11eb-3f6e-5b2f0a09363e\n# \u2560\u25507c888c54-14a5-11eb-315f-3d32578eaf32\n# \u2560\u2550bfd7693a-14a5-11eb-3479-057e03ef43f4\n# \u2560\u2550150cec5a-14aa-11eb-2be7-390b12287032\n# \u2560\u2550f17bfc22-14b3-11eb-319a-47522cda243c\n# \u2560\u25503ac52d04-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": "\nusing JuMP\nusing GLPK\n\n\n# Create a model\nsudoku = Model(with_optimizer(GLPK.Optimizer))\n\n# Create our variables\n@variable(sudoku, x[i=1:9, j=1:9, k=1:9], Bin);\n\n\nfor i = 1:9, j = 1:9  # Each row and each column\n    # Sum across all the possible digits\n    # One and only one of the digits can be in this cell, \n    # so the sum must be equal to one\n    @constraint(sudoku, sum(x[i,j,k] for k in 1:9) == 1)\nend\n\n\nfor ind = 1:9  # Each row, OR each column\n    for k = 1:9  # Each digit\n        # Sum across columns (j) - row constraint\n        @constraint(sudoku, sum(x[ind,j,k] for j in 1:9) == 1)\n        # Sum across rows (i) - column constraint\n            @constraint(sudoku, sum(x[i,ind,k] for i in 1:9) == 1)\n    end\nend\n\n\nfor i = 1:3:7, j = 1:3:7, k = 1:9\n    # i is the top left row, j is the top left column\n    # We'll sum from i to i+2, e.g. i=4, r=4, 5, 6\n    @constraint(sudoku, sum(x[r,c,k] for  r in i:i+2, c in j:j+2) == 1)\nend\n\n\n# The given digits\ninit_sol = [ 5 3 0 0 7 0 0 0 0;\n             6 0 0 1 9 5 0 0 0;\n             0 9 8 0 0 0 0 6 0;\n             8 0 0 0 6 0 0 0 3;\n             4 0 0 8 0 3 0 0 1;\n             7 0 0 0 2 0 0 0 6;\n             0 6 0 0 0 0 2 8 0;\n             0 0 0 4 1 9 0 0 5;\n             0 0 0 0 8 0 0 7 9]\nfor i = 1:9, j = 1:9\n    # If the space isn't empty\n    if init_sol[i,j] != 0\n        # Then the corresponding variable for that digit\n        # and location must be 1\n        @constraint(sudoku, x[i,j,init_sol[i,j]] == 1)\n    end\nend\n\n# solve problem\noptimize!(sudoku)\n\n# Extract the values of x\nx_val = value.(x)\n# Create a matrix to store the solution\nsol = zeros(Int,9,9)  # 9x9 matrix of integers\nfor i in 1:9, j in 1:9, k in 1:9\n    # Integer programs are solved as a series of linear programs\n    # so the values might not be precisely 0 and 1. We can just\n    # round them to the nearest integer to make it easier\n    if round(Int,x_val[i,j,k]) == 1\n        sol[i,j] = k\n    end\nend\n# Display the solution\nsol\n\n", "meta": {"hexsha": "2737bca7346e33af77c9afeb49a187527b42e15c", "size": 1972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modelling/sudoku.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": "test/modelling/sudoku.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": "test/modelling/sudoku.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": 26.2933333333, "max_line_length": 71, "alphanum_fraction": 0.5689655172, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7926102106509989}}
{"text": "\"\"\"\n```\n    sample_points_on_ellipse(A::Real, B::Real, H::Real, K::Real, \u03c4::Real, N::Integer, \u03b1\u2081::Real, \u03b1\u2082::Real)\n```\n    Samples N data points in the angle range [\u03b1\u2081, \u03b1\u2082] for an ellipse specified by  semi-major (A) semi-minor (B) axes,\n    centroid (H,K) and orientation (\u03c4). 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, \u03c4::Real, N::Integer, \u03b1\u2081::Real, \u03b1\u2082::Real)\n    \u2133 = [SVector(0.0,0.0) for n = 1:N]\n    for (n,\u03b1) in enumerate(range(\u03b1\u2081, stop = \u03b1\u2082, length = N))\n        x = H + A*cos(\u03b1)*cos(\u03c4) - B*sin(\u03b1)*sin(\u03c4)\n        y = K + A*cos(\u03b1)*sin(\u03c4) + B*sin(\u03b1)*cos(\u03c4)\n        \ud835\udc26 = SVector(x,y)\n        \u2133[n] = \ud835\udc26\n    end\n    data = tuple(\u2133)\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": "using NumericalMethodsforEngineers\n\nA = Float64[0 0 16; 0 4 5; 8 -4 22]\nb = Float64[4, 2, 5]\n\nprintln(\"\\nCholesky factorization using banded storage\\n\")\nprintln(\"\\nBanded Coefficient Matrix:\\n$A\\n\")\nprintln(\"\\nRight Hand side:\\n$b\\n\")\n\ncholin!(A)\nprintln(\"\\nL in Band Form:\\n$A\\n\")\n\nchobac!(A, b)\nprintln(\"\\nSolution Vector:\\n$b\")\n\nA = Float64[0 0 16; 0 4 5; 8 -4 22]\nb = Float64[4, 2, 5]\n\nc = A \\ b\n\n@test round(c, 14) == b\n", "meta": {"hexsha": "02f959701c21d171ba0121b0fa45a1af56d957f4", "size": 425, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/f_02_04.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/ch02/f_02_04.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/ch02/f_02_04.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": 19.3181818182, "max_line_length": 58, "alphanum_fraction": 0.6494117647, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230208, "lm_q2_score": 0.8333245932423309, "lm_q1q2_score": 0.7926102012829825}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.03\"\n\n# \u2554\u2550\u2561 fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tdata = CSV.read(datadir(\"machine1.csv\"), DataFrame; delim=\",\")[:, 1]\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c69d5eae-3b0c-11eb-38aa-b578cce81150\nText(\"Using confint() function: $(confint(OneSampleZTest(xBar,sig,n),alpha))\")\n\n# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.03\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u2550c69d5eae-3b0c-11eb-38aa-b578cce81150\n# \u255f\u2500475ff888-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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d141cf00-8352-11eb-2e51-f115e26e1570\nbegin\n\tmd\"\"\"\n# Popular discrete probability distributions \ud83e\udd73\nHere you can explore some of the most famous discrete probability distributions\n\"\"\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6196a940-8353-11eb-1a09-29cb2338d697\nmd\"\"\"\nVary the parameter of \ud83d\udc49 $\\lambda$: $(@bind lambda Slider(0:1:18, default=1, show_value = true))\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\ud83d\udc49 The function becomes discontinuous for values larger 14  $(@bind is_discontinuous CheckBox())\n\n\ud83d\udc49 There is no problem, the function should look like that  $(@bind is_no_problem CheckBox())\n\n\ud83d\udc49 There are numerical issues  $(@bind is_num CheckBox())\n\n\"\"\"\n\n# \u2554\u2550\u2561 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?_  \ud83e\udd14\n\n\n\"\"\"\n\n# \u2554\u2550\u2561 9acafce0-844b-11eb-331c-0186de214a59\nmd\"\"\"\nVary the parameters of the **the total number of experiments** \ud83d\udc49 N: $(@bind N_binom Scrubbable(0:1:20)) and of the **success probability** \ud83d\udc49 Q: $(@bind Q_binom Scrubbable(0:0.05:1)) \n\nCompare with **Gauss distribution** \ud83d\udc49 $(@bind check_gauss CheckBox())\nand with **Poisson distribution** \ud83d\udc49 $(@bind check_poisson CheckBox())\n\n_For which parameters do they match?_ \ud83e\udd14\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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?_  \ud83e\udd14\n\n\n\"\"\"\n\n# \u2554\u2550\u2561 08562f30-8453-11eb-36bd-7b55fcd4b82e\nbegin \nmd\"\"\"\nVary the **success probability** \ud83d\udc49 $Q_a$:  $(@bind q_a_aux Scrubbable(0.3:0.05:0.99,default = sqrt(1/6))) \n\"\"\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1cc62475-2dd3-488b-9647-9d5b2986d791\nmd\"\"\"\n# Popular continuous probability distributions \ud83d\udc31\u200d\ud83d\udc64\n\"\"\"\n\n# \u2554\u2550\u2561 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?_  \ud83e\udd14\n\n\"\"\"\n\n# \u2554\u2550\u2561 fb470501-cea4-4ac9-a652-d9874dbd7bdc\nmd\"\"\"\nChoose **parameters** $\\alpha$ \ud83d\udc49 $(@bind \u03b1 Scrubbable(0:0.1:5, default = 2)) and \n\n $\\beta$ \ud83d\udc49 $(@bind \u03b2 Scrubbable(0:0.1:5, default = 2))\n\"\"\"\n\n# \u2554\u2550\u2561 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?_  \ud83e\udd14\n\n\"\"\"\n\n# \u2554\u2550\u2561 8ced1f19-501a-47ff-8b0a-eee49816bd4a\nmd\"\"\"\nChoose **parameters** $\\alpha$ \ud83d\udc49 $(@bind \u03b1_b Scrubbable(0:0.1:5, default = 2)) and \n\n $\\rho$ \ud83d\udc49 $(@bind \u03c1 Scrubbable(0:0.1:5, default = 2))\n\n\n\"\"\"\n\n# \u2554\u2550\u2561 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?_  \ud83e\udd14\n\n\"\"\"\n\n# \u2554\u2550\u2561 ed6970b0-8f76-4490-aef6-7bdfba026c27\nmd\"\"\"\nChoose **parameters** $x_0$ \ud83d\udc49 $(@bind x_0 Scrubbable(-10:0.1:10, default = 0)) and \n\n $\\sigma$ \ud83d\udc49 $(@bind \u03c3 Scrubbable(0.1:0.1:5, default = 2))\n\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c3fad29d-ffa2-4bab-a164-6b53573b6050\nbegin\n\t\n\tmd\"\"\"asdf $asdf$ $(\u03b1)  as\"\"\"\n\tgamma_x = 0:0.1:10\n\t\n\t\n\tgamma_pdf = \u03b2^\u03b1 / gamma(\u03b1) .* gamma_x.^(\u03b1-1) .* exp.(-\u03b2 .* 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(\u03b1,2) * \", \\\\beta = \" * sr(\u03b2,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# \u2554\u2550\u2561 2ba5aa6f-cdb8-4a82-85c2-66820ceefd4b\nbegin\n\tbeta_x = 0:0.01:1\n\t\n\t\n\tbeta_pdf = 1 ./beta(\u03b1_b, \u03c1) .* beta_x.^(\u03b1_b-1) .* (1 .- beta_x).^(\u03c1-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(\u03b1_b,2) * \", \\\\rho = \" * sr(\u03c1,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# \u2554\u2550\u2561 49cbd69b-e140-422c-9c1e-e9dd2a0545d8\nbegin\n\td = -10:0.01:10\n\t\n\td1_pdf = 1 ./sqrt(2*pi*\u03c3^2) .* exp.(- (d .-x_0).^2 ./(2*\u03c3^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(\u03c3,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# \u2554\u2550\u2561 3554f46b-3a86-4e97-8c02-4911f8f0776a\n\tTableOfContents()\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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!** \u2728 You got the right answer! \ud83c\udf88\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500d141cf00-8352-11eb-2e51-f115e26e1570\n# \u255f\u2500e6d68ef0-8352-11eb-1999-0384c7ff8526\n# \u255f\u25006196a940-8353-11eb-1a09-29cb2338d697\n# \u255f\u2500a88ae050-8353-11eb-3eee-b7ee9b717fdb\n# \u255f\u250047882682-844f-11eb-335e-afc41d5498e1\n# \u255f\u250092552af0-844f-11eb-23fa-5711044ae250\n# \u255f\u25007799e4c0-844b-11eb-2484-051807211341\n# \u255f\u25009acafce0-844b-11eb-331c-0186de214a59\n# \u255f\u25003a1c82a0-844c-11eb-05a6-75924317db64\n# \u255f\u250073b7eb70-8452-11eb-0f2e-df6b5cd0da4a\n# \u255f\u250008562f30-8453-11eb-36bd-7b55fcd4b82e\n# \u255f\u2500b10c08c0-8453-11eb-1614-ef634e6929e5\n# \u255f\u250065567910-8453-11eb-1de3-d38bd5010350\n# \u255f\u25001cc62475-2dd3-488b-9647-9d5b2986d791\n# \u255f\u250048811336-16f6-496f-848d-54fd834bb0da\n# \u255f\u2500fb470501-cea4-4ac9-a652-d9874dbd7bdc\n# \u255f\u2500c3fad29d-ffa2-4bab-a164-6b53573b6050\n# \u255f\u25003d85408a-b356-4107-b604-b39fb5a6982e\n# \u255f\u25008ced1f19-501a-47ff-8b0a-eee49816bd4a\n# \u255f\u25002ba5aa6f-cdb8-4a82-85c2-66820ceefd4b\n# \u255f\u25008efc6cb4-23f3-4ff3-84ee-2cd7891dd1a8\n# \u255f\u2500ed6970b0-8f76-4490-aef6-7bdfba026c27\n# \u255f\u250049cbd69b-e140-422c-9c1e-e9dd2a0545d8\n# \u255f\u250044d4d19e-b0d2-4768-bc6b-eb63affc3898\n# \u255f\u250073555af0-8353-11eb-215d-d3578a6f1e2e\n# \u255f\u250002f9fccb-594a-4594-b3f1-900f0847e01e\n# \u255f\u25003554f46b-3a86-4e97-8c02-4911f8f0776a\n# \u255f\u25001bf9a33d-da46-4dec-8c17-75243c3b84a9\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "import Distributions: MvNormal, pdf, logpdf\nimport Plots: scatter, contour, contour!, xlabel!, ylabel!\nusing ColorSchemes\nusing LaTeXStrings\n\n\nfunction prob_cluster(x, y, \u03bc, \u03a3)\n    \"Probability under Gaussian\"\n\n    # Ensure matrix is Hermitian\n    \u03a3 = enforce_Hermitian!(\u03a3)\n\n    # Ensure matrix is non-negative\n    \u03a3 = enforce_nonneg!(\u03a3)\n\n    # Return weighted probability\n    return pdf(MvNormal(\u03bc, \u03a3), [x, y])\nend\n\nfunction enforce_nonneg!(M)\n    \"Enforce non-negative elements\"\n    M = max.(0, M)\nend\n\nfunction enforce_Hermitian!(M)\n    \"Enforce Hermitian\"\n    M = (M + M')/2\nend\n\nfunction plot_clusters(observations;\n                       \u03bc=[],\n                       \u03a3=[[1. 0.;0. 1.], [1. 0.;0. 1.]],\n                       x1=range(-5, stop=3),\n                       x2=range(-5, stop=4),\n                       colorlist=[\"reds\", \"blues\", \"greens\"],\n                       size=(500, 500))\n    \"Scatter data and overlay Gaussian clusters.\"\n\n    # Show the data\n    plt = scatter(observations[:,1],\n                  observations[:,2],\n                  label=\"\",\n                  color=\"black\",\n                  xlims=[x1[1] x1[end]],\n                  ylims=[x2[1] x2[end]],\n                  xlabel=L\"$x_1$\",\n                  ylabel=L\"$x_2$\",\n                  grid=false,\n                  size=size)\n\n    # Loop over clusters\n    for k = 1:length(\u03bc)\n\n        # Overlay the posterior probabilities for k-th cluster\n        contour!(plt, x1, x2,\n                 (x, y) -> prob_cluster(x, y, \u03bc[k], \u03a3[k]),\n                 color=colorlist[k],\n                 cbar=nothing)\n    end\n    plot(plt)\nend\n\n", "meta": {"hexsha": "25021addc2a9e3f8a08460818f80c90e5388a315", "size": 1614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessons/notebooks/scripts/clusters.jl", "max_stars_repo_name": "Yikeru/BMLIP", "max_stars_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "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/notebooks/scripts/clusters.jl", "max_issues_repo_name": "Yikeru/BMLIP", "max_issues_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "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/notebooks/scripts/clusters.jl", "max_forks_repo_name": "Yikeru/BMLIP", "max_forks_repo_head_hexsha": "296f5330210d387809b2c3ce7a6847f2bd69b24c", "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": 25.619047619, "max_line_length": 62, "alphanum_fraction": 0.5030978934, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7925584433315249}}
{"text": "using QuadratureRules\nusing Test\n\ninclude(\"test_utils.jl\")\ninclude(\"test_quadrature_rule.jl\")\ninclude(\"test_gauss_chebyshev.jl\")\ninclude(\"test_gauss_legendre.jl\")\ninclude(\"test_lobatto_chebyshev.jl\")\ninclude(\"test_lobatto_legendre.jl\")\ninclude(\"test_clenshaw_curtis.jl\")\ninclude(\"test_tabulated_quadratures.jl\")\n", "meta": {"hexsha": "35123b1661421230b65b30695f5d8187a963467b", "size": 312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 26.0, "max_line_length": 40, "alphanum_fraction": 0.8301282051, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7925584387215383}}
{"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; \u03bb=0)\n    ai = A[:, i]\n    return ai' * pinv(A * A' + \u03bb^2 * I) * ai\nend\n\n\nfunction ridge_weights(A, \u03bb)\n    _, n = size(A)\n    weights = zeros(n)\n    for i = 1:n\n        weights[i] = ell(A, i, \u03bb=\u03bb)\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, \u03bb)\n    return samplemat(A, ridge_weights(A, \u03bb), 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": "export bin_vector, bin_matrix, bin_value\nexport unbin_value, unbin_matrix, unbin_vector\nexport combine_binned_matrix, combine_binned_vector\nexport combine_and_relabel_binned_matrix\nexport unary_of_matrix\nexport relabel\n\nbin_value(v::Float64, bins::Int64, min=-1.0, max=1.0) = round(Int64, minimum([1+floor((v-min) / (max - min) * (bins-0.1)), bins]))\n\nbin_vector(vec::Vector{Float64}, min::Float64, max::Float64, bins::Int64) = map(v->bin_value(v, bins, min, max), vec)\n\nunbin_vector(vec::Vector{Float64}, min::Float64, max::Float64, bins::Int64; mode=\"centre\") = map(v->unbin_value(v, bins, min, max, mode=mode), vec)\n\nfunction unbin_value(v::Int64, bins::Int64, min=-1.0, max=1.0; mode=\"centre\")\n  known_mode = (mode == \"centre\" ||\n                mode == \"lower\"  ||\n                mode == \"upper\")\n  @assert known_mode \"Mode may be any of the following: [\\\"centre\\\", \\\"lower\\\", \\\"upper\\\"]\"\n\n  delta = (max - min) / Float64(bins)\n  u = (v - 1) * delta + min\n\n  if     mode == \"centre\"\n    return u + 0.5 * delta\n  elseif mode == \"upper\"\n    return u + delta\n  end\n  return u\nend\n\nfunction bin_matrix(m::Matrix{Float64}, min::Float64, max::Float64, bins::Int64)\n  r = zeros(size(m))\n  for i=1:size(m)[1]\n    r[i,:] = bin_vector(squeeze(m[i,:],2), min, max, bins)\n  end\n  convert(Matrix{Int64}, r)\nend\n\nfunction unbin_matrix(m::Matrix{Float64}, min::Float64, max::Float64, bins::Int64; mode=\"centre\")\n  r = zeros(size(m))\n  for i=1:size(m)[1]\n    r[i,:] = unbin_vector(squeeze(m[i,:],1), min, max, bins, mode=mode)\n  end\n  convert(Matrix{Int64}, r)\nend\n\nfunction combine_binned_vector(v::Vector{Int64}, bins::Int64)\n  convert(Int64, sum([v[i] * bins^(i-1) for i = 1:length(v)]))\nend\n\nfunction combine_binned_matrix(v::Matrix{Int64})\n  l = size(v)[1]\n  r = zeros(l)\n  m = maximum(v)\n  for i = 1:l\n    r[i] = combine_binned_vector(squeeze(v[i,:],1), m)\n  end\n  convert(Vector{Int64}, r)\nend\n\nrelabel(v::Vector{Int64}) = indexin(v, sort(unique(v)))\n\ncombine_and_relabel_binned_matrix(data::Matrix{Int64}) = relabel(combine_binned_matrix(data))\n\nunary_of_matrix(data::Matrix{Float64}, min::Float64, max::Float64, bins::Int64) = combine_and_relabel_binned_matrix(bin_matrix(data, min, max, bins))\n", "meta": {"hexsha": "936a5bdaaf755a2f9123bfb9b23719d5c22c1ea9", "size": 2194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/binning.jl", "max_stars_repo_name": "JuliaPackageMirrors/Shannon.jl", "max_stars_repo_head_hexsha": "91cf6088a009979ddbc63586d891abca6b508901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/binning.jl", "max_issues_repo_name": "JuliaPackageMirrors/Shannon.jl", "max_issues_repo_head_hexsha": "91cf6088a009979ddbc63586d891abca6b508901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/binning.jl", "max_forks_repo_name": "JuliaPackageMirrors/Shannon.jl", "max_forks_repo_head_hexsha": "91cf6088a009979ddbc63586d891abca6b508901", "max_forks_repo_licenses": ["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.2424242424, "max_line_length": 149, "alphanum_fraction": 0.6681859617, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7925584316341521}}
{"text": "using Test\nimport Bresenham\n\nfunction test_line(args...)\n  points = Vector{Tuple{Int, Int}}()\n  Bresenham.line(args...) do x, y\n    push!(points, (x, y))\n  end\n  points\nend\n\n# Low slope (X major)\n@test test_line(1, 1, 5, 3) == [ (1, 1), (2, 1), (3, 2), (4, 2), (5, 3) ]\n# Reverse low slope (X major)\n@test test_line(5, 3, 1, 1) == reverse!([ (1, 1), (2, 1), (3, 2), (4, 2), (5, 3) ])\n\n# Oblique slope (X major)\n@test test_line(1, 1, 5, 5) == [ (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) ]\n# Reverse oblique slope (X major)\n@test test_line(5, 5, 1, 1) == reverse!([ (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) ])\n\n# High slope (Y major)\n@test test_line(1, 1, 3, 5) == [ (1, 1), (1, 2), (2, 3), (2, 4), (3, 5) ]\n# Reverse high slope (Y major)\n@test test_line(3, 5, 1, 1) == reverse!([ (1, 1), (1, 2), (2, 3), (2, 4), (3, 5) ])\n\n# Horizontal\n@test test_line(1, 1, 5, 1) == [ (1, 1), (2, 1), (3, 1), (4, 1), (5, 1) ]\n# Reverse horizontal\n@test test_line(5, 1, 1, 1) == reverse!([ (1, 1), (2, 1), (3, 1), (4, 1), (5, 1) ])\n# Vertical\n@test test_line(1, 1, 1, 5) == [ (1, 1), (1, 2), (1, 3), (1, 4), (1, 5) ]\n# Reverse vertical\n@test test_line(1, 5, 1, 1) == reverse!([ (1, 1), (1, 2), (1, 3), (1, 4), (1, 5) ])\n", "meta": {"hexsha": "7e81f7610731e8b98c1e395d5b8377b1b4003968", "size": 1197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "vtavernier/Bresenham.jl", "max_stars_repo_head_hexsha": "ea5710d27ba87fd259ec909e471e8c8381b5016b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-21T04:34:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:44:19.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "vtavernier/Bresenham.jl", "max_issues_repo_head_hexsha": "ea5710d27ba87fd259ec909e471e8c8381b5016b", "max_issues_repo_licenses": ["MIT"], "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": "vtavernier/Bresenham.jl", "max_forks_repo_head_hexsha": "ea5710d27ba87fd259ec909e471e8c8381b5016b", "max_forks_repo_licenses": ["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.2, "max_line_length": 83, "alphanum_fraction": 0.4870509607, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8499711680567799, "lm_q1q2_score": 0.7925584280904587}}
{"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) = \u2211_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 \u21a6 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\u2013Tukey 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\u2013Tukey_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\u03c0 / n)\n\nCancellation lemma ([clrs] Lemma 30.3):\n\n    w_{n d}^{d k} = exp(-im * 2\u03c0 * (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) } \u222a { 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\u2013Lanczos(?) 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 \u2260 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 \u00f7 2), 1:2:end]\n    W_o = @view parent(W)[1:(n \u00f7 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\u03c0 * 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\u03c0)im * (i * j / n))\n                else\n                    # (!) Do not put `/ n` here.\n                    exp((2\u03c0)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\u03c0 * 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(\u03c0))im * i / n) for i in 0:(n \u00f7 2 - 1)]\n        else\n            # (!) Do not put `/ n` here as unlike `W`, `V[:, 0]` is not 0\n            [exp((2 * T(\u03c0))im * i / n) for i in 0:(n \u00f7 2 - 1)]\n        end\n    OffsetVector(w, 0:(n \u00f7 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 \u00f7 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                             \u03f5::Real;\n                             \u03b1::Real=0.01, \u03b2::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    \u2207 = A'*d\n    H = A'*Diagonal(d)^2*A\n    \u0394xnt = -H\\\u2207\n    \u03bb\u00b2 = -\u2207\u22c5\u0394xnt\n    \u03bb\u00b2/2 < \u03f5 && break\n    t = 1\n    xtest = x + t*\u0394xnt\n    while(any(A*xtest .\u2265 b)\n          || polytope_log(xtest) > polytope_log(x)-t*\u03b1*\u03bb\u00b2)\n      t *= \u03b2\n      xtest = x + t*\u0394xnt\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": "module SpecialVectors\nusing Test\n\nfunction constants(n=5)\n    return ones(n)\nend\n\n@test constants() == ones(5)\n@test constants(6) == ones(6)\n\nfunction linear(n=5)\n    return [1:n...]\nend\n\n@test linear() == [1:5...]\n@test linear(6) == [1:6...]\n\nfunction squares(n=5)\n    return [1:n...].^2\nend\n\n@test squares() == [1:5...].^2\n@test squares(6) == [1:6...].^2\n\nfunction checkDim(k::Int, n::Int)\n    if (k > n)\n        throw(DimensionMismatch(\"k must be less than n!\"))\n    end\n    return true\nend\n\n@test_throws DimensionMismatch checkDim(6, 1)\n@test checkDim(1, 5)\n\nfunction deltaAtK(k=1, n=5)\n    checkDim(k, n)\n    return [zeros(k - 1)..., 1, zeros(n - k)...]\nend\n\n@test_throws DimensionMismatch deltaAtK(6)\n@test deltaAtK() == [1, 0, 0, 0, 0]\n@test deltaAtK(3, 6) == [0, 0, 1, 0, 0, 0]\n\nfunction stepAtK(k=1, n=5)\n    checkDim(k, n)\n    return [zeros(k - 1)..., 1, ones(n - k)...]\nend\n\n@test_throws DimensionMismatch stepAtK(6)\n@test stepAtK() == [1, 1, 1, 1, 1]\n@test stepAtK(3) == [0, 0, 1, 1, 1]\n\nfunction rampAtK(k=1, n=5)\n    checkDim(k, n)\n    return [zeros(k - 1)..., 0:(n - k)...]\nend\n\n@test_throws DimensionMismatch rampAtK(6)\n@test rampAtK() == [0, 1, 2, 3, 4]\n@test rampAtK(2) == [0, 0, 1, 2, 3]\n@test rampAtK(3) == [0, 0, 0, 1, 2]\n\nfunction sines(t, n=5)\n    return sin.([1:n...] .* t)\nend\n\n@test round.(sines(\u03c0 / 2), digits=2) == [1, 0, -1, 0, 1]\n@test round.(sines(\u03c0 / 4), digits=2) == [.71, 1.0, .71, 0, -.71]\n\nfunction cosines(t, n=5)\n    return cos.([1:n...] .* t)\nend\n\n@test round.(cosines(\u03c0 / 2), digits=2) == [0, -1, 0, 1, 0]\n@test round.(cosines(\u03c0 / 4), digits=2) == [.71, 0.0, -.71, -1.0, -.71]\n\nfunction exponentials(t, n=5)\n    return exp.([1:n...] .* (im * t))\nend\n\n@test exponentials(0) == repeat([1.0 + 0.0im], 5)\n@test exponentials(1) == [\n  0.5403023058681398 + 0.8414709848078965im\n -0.4161468365471424 + 0.9092974268256817im\n -0.9899924966004454 + 0.1411200080598672im\n -0.6536436208636119 - 0.7568024953079282im\n 0.28366218546322625 - 0.9589242746631385im\n]\n\nexport constants, linear, squares, deltaAtK, stepAtK, rampAtK, sines, cosines, exponentials\n\nend", "meta": {"hexsha": "7f701efc2982d9a1a50c7dfadc35fe7552c68918", "size": 2087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lib/SpecialVectors.jl", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "lib/SpecialVectors.jl", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_issues_repo_licenses": ["MIT"], "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/SpecialVectors.jl", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 22.6847826087, "max_line_length": 91, "alphanum_fraction": 0.6037374221, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.7924537205902598}}
{"text": "# [test/rk4_tests.jl]\nusing Test \n\n@testset \"RK4 Tests\" begin\n    \n    using JLD2\n    import ODEHybrid.rk4, ODEHybrid.ODE_SET\n\n    @testset \"Sample from code description\" begin\n\n        # mat\"\"\"\n        # [$t_mat, $x_mat] = rk4(@(t, x) [-x(2); x(1)], [0 10], [1; 0], 0.1)\n        # \"\"\"\n        @load \"solutions/rk4_sample_from_code.jld2\" t_mat x_mat\n\n        t_jul, x_jul = rk4((t, x) -> [-x[2]; x[1]], [0 10], [1; 0], 0.1)\n\n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\n    @testset \"Simple function with time\" begin \n        ts = [0.25 10.0]\n        x0 = [1.0, -1.0]\n        dt = 0.25\n        # mat\"\"\"\n            # [$t_mat, $x_mat] = rk4(@(t, x) [-x(2) * t; x(1) / t], $ts, $x0, $dt);\n        # \"\"\"\n        @load \"solutions/rk4_simple_func_with_time.jld2\" t_mat x_mat\n\n        t_jul, x_jul = rk4( (t, x) -> [-x[2] * t, x[1] / t], ts, x0, dt);\n    \n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\n    @testset \"Negative time step\" begin \n        ts = [-0.25 -10.0]\n        x0 = [-1.0; 0.0; 1.0]\n        dt = -0.25 \n\n        # mat\"\"\"\n        #     ode = @(t, x) [(-x(1) * x(2) + x(3)) / (t*t*t); x(1) * t; x(2) - x(3)];\n        #     [$t_mat, $x_mat] = rk4(ode, $ts, $x0, $dt);\n        # \"\"\"\n        @load \"solutions/rk4_neg_time_step.jld2\" t_mat x_mat\n\n        t_jul, x_jul = rk4((t, x) -> [(-x[1] * x[2] + x[3]) / (t * t * t); x[1] * t; x[2] - x[3]], ts, x0, dt)\n    \n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\n    # Used to test plotting, but plotting is surpressed for now\n    @testset \"ODE_SET with output function!\" begin \n        ts = [2.5 7.5]\n        x0 = [1.1; 3.5; -7.9]\n        dt = 0.1\n\n        # mat\"\"\"\n        #     ode = @(t, x) [-x(2); x(3); -x(1)];\n        #     %options = odeset('OutputFcn', @odeplot); % Used to test plotting!\n        #     options = odeset();\n        #     options.MaxStep = $dt;\n        #     [$t_mat, $x_mat] = rk4(ode, $ts, $x0, options) \n        # \"\"\"\n\n        @load \"solutions/rk4_ode_with_output.jld2\" t_mat x_mat\n\n        options = ODE_SET()\n        # options.OutputFcn = odeplot\n        options.MaxStep = dt\n\n        t_jul, x_jul = rk4((t, x) -> [-x[2]; x[3]; -x[1]], ts, x0, options)\n\n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end\n\nend;\n\n", "meta": {"hexsha": "08330c15b11a35e53759395d41b87e0c0e95b551", "size": 2450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rk4_tests.jl", "max_stars_repo_name": "benjjensen/ODEHybrid.jl", "max_stars_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_stars_repo_licenses": ["MIT"], "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/rk4_tests.jl", "max_issues_repo_name": "benjjensen/ODEHybrid.jl", "max_issues_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-18T18:50:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T18:59:30.000Z", "max_forks_repo_path": "test/rk4_tests.jl", "max_forks_repo_name": "benjjensen/ODEHybrid.jl", "max_forks_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_forks_repo_licenses": ["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.8780487805, "max_line_length": 110, "alphanum_fraction": 0.4771428571, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.7924537171322292}}
{"text": "\r\ninclude(\"../src/numder_module.jl\")\r\ninclude(\"../../../../std/util/src/util_module.jl\")\r\n\r\n\r\n# =========================================================================== #\r\n# Test\r\n# =========================================================================== #\r\nmodule numdertest\r\nusing ..numder\r\nusing ..util\r\nusing LinearAlgebra\r\n\r\nusing PyPlot\r\nPyPlot.pygui(true)\r\n\r\nfunction test_step_size()\r\n    x0 = [0.0, 1e-15, 1e-16, 1, 2, 10]\r\n    h = map( numder.step_size, x0 )\r\nend\r\n\r\nfunction numdiff_fwbw()\r\n\r\n    f = sin\r\n    x0 = collect( -pi:0.1:pi )\r\n    g_theo = cos.(x0)\r\n\r\n    g_fw = map(x -> numder.numdiff_fw(f, x), x0)\r\n    g_bw = map(x -> numder.numdiff_bw(f, x), x0)\r\n\r\n    g_error_fw = g_fw .- g_theo\r\n    g_error_bw = g_bw .- g_theo\r\n\r\n\r\n    PyPlot.figure()\r\n    PyPlot.grid()\r\n    PyPlot.plot(x0, g_fw, marker=:o)\r\n    PyPlot.plot(x0, g_theo, marker=:*)\r\n\r\n    PyPlot.figure()\r\n    PyPlot.grid()\r\n    PyPlot.plot(x0, g_error_fw, marker=:o)\r\n    PyPlot.plot(x0, g_error_bw, marker=:o)\r\n\r\nend\r\n\r\n\r\nfunction numdiff_central()\r\n\r\n    f = sin\r\n    x0 = collect( -pi:0.1:pi )\r\n    g_theo = cos.(x0)\r\n\r\n    g_c = map(x -> numder.numdiff_central(f, x), x0)\r\n\r\n    g_error_c = g_c .- g_theo\r\n\r\n    PyPlot.figure()\r\n    PyPlot.grid()\r\n    PyPlot.plot(x0, g_c, marker=:o)\r\n    PyPlot.plot(x0, g_theo, marker=:*)\r\n\r\n    PyPlot.figure()\r\n    PyPlot.grid()\r\n    PyPlot.plot(x0, g_error_c, marker=:o)\r\n\r\nend\r\n\r\n\r\nfunction gradient_fw()\r\n\r\n    f(x) = x[1].^2 + x[2].^3\r\n\r\n    x_vec = collect( -pi:0.1:pi )\r\n    y_vec = collect( -pi:0.1:pi )\r\n    \r\n    (x_mat, y_mat) = util.meshgrid( x_vec, y_vec )\r\n    x0 = [x_mat[:] y_mat[:]]\r\n    g_theo_fcn(x) = [2 * x[1], 3 * x[2].^2]\r\n\r\n    g_theo = mapslices( g_theo_fcn, x0, dims = 2)\r\n    g_fw = mapslices( x -> numder.gradient_fw(f, x), x0, dims = 2)\r\n\r\n    g_error = mapslices( norm, g_fw - g_theo, dims = 2 )\r\n    g_error_mat = reshape(g_error, (length(x_vec), length(y_vec)) )\r\n\r\n    PyPlot.figure()\r\n    PyPlot.grid()\r\n    PyPlot.plot_surface(x_vec, y_vec, g_error_mat)\r\n    # PyPlot.plot(g_error)\r\n\r\nend\r\n\r\n\r\nfunction jacobian_fw()\r\n\r\n    # f(x) = [x[1].^2  x[2].^3]\r\n    f(x) = [cos(x[1])  x[1].^2 + x[2].^2   sin(x[2])] # R^2 -> R^3\r\n\r\n    x_vec = collect( -pi:0.1:pi )\r\n    y_vec = collect( -pi:0.1:pi )\r\n    (x_mat, y_mat) = util.meshgrid( x_vec, y_vec )\r\n    x0 = [x_mat[:] y_mat[:]]\r\n\r\n    idx = 2\r\n    #=\r\n    g_theo_fcn(x) = \r\n        [\r\n        2 * x[1]    0.0;\r\n        0.0         3 * x[2].^2\r\n        ]\r\n    =#\r\n    g_theo_fcn(x) = \r\n        [\r\n            -sin(x[1])      0.0\r\n            2 * x[1]        2 * x[2]\r\n            0.0             cos(x[2])\r\n        ]\r\n    g_theo = g_theo_fcn( x0[idx, :] )\r\n    g_fw = numder.jacobian_fw(f, x0[idx, :] )\r\n    g_error = g_fw - g_theo\r\n\r\nend\r\n\r\n\r\nfunction test_directional_diff_fw()\r\n\r\n    f(x) = x[1]^2 + x[2]^2\r\n\r\n    x0 = [1.0, 2]\r\n    d = [3.0, 6]\r\n    d = d ./ norm(d)\r\n\r\n    dfdd = numder.directional_diff_fw(f, x0, d)\r\n\r\n    g = numder.gradient_fw(f, x0)\r\n    df_theo = sum(g .* d)\r\n\r\n    println(dfdd)\r\n\r\n    println(df_theo)\r\n\r\nend\r\n\r\n\r\n\r\n\r\nend # numdertest\r\n\r\n\r\n", "meta": {"hexsha": "731aeabb32c92fcb84274a035435ab12b325c991", "size": 3077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/numder/test/test_numderical_derivates.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/test/test_numderical_derivates.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/test/test_numderical_derivates.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.3774834437, "max_line_length": 80, "alphanum_fraction": 0.4874878128, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7924500432392709}}
{"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\u2032 = zeros(n, 3)\n    Xmean = mean(X, 1)\n    for i in 1:n\n        X\u2032[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\u2032[i, 1] ^ 2\n        A[1, 2] += X\u2032[i, 1] * X\u2032[i, 2]\n        A[1, 3] += X\u2032[i, 1]\n        A[2, 2] += X\u2032[i, 2] ^ 2\n        A[2, 3] += X\u2032[i, 2]\n        A[3, 3] += 1.0\n        B[1] += X\u2032[i, 1] * X\u2032[i, 3]\n        B[2] += X\u2032[i, 2] * X\u2032[i, 3]\n        B[3] += X\u2032[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\u0304 = 0.0\n        L\u0304a = 0.0\n        L\u0304b = 0.0\n        L\u0304c = 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\u0304 += L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n            L\u0304a += (a - X[i, 1]) / L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n            L\u0304b += (b - X[i, 2]) / L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n            L\u0304c += (c - X[i, 3]) / L(X[i, 1], X[i, 2], X[i, 3], a, b, c)\n        end\n        L\u0304 /= n\n        L\u0304a /= n\n        L\u0304b /= n\n        L\u0304c /= n\n\n        return Xmean[1] + L\u0304 * L\u0304a, Xmean[2] + L\u0304 * L\u0304b, Xmean[3] + L\u0304 * L\u0304c, L\u0304\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    \u03b8\u2080::Float64\n    \u03b8\u2081::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\u03b8\u2080 = sin(params.\u03b8\u2080)\n        cos\u03b8\u2080 = cos(params.\u03b8\u2080)\n        sin\u03b8\u2081 = sin(params.\u03b8\u2081)\n        cos\u03b8\u2081 = cos(params.\u03b8\u2081)\n        W[1] = cos\u03b8\u2080 * sin\u03b8\u2081\n        W[2] = sin\u03b8\u2080 * sin\u03b8\u2081\n        W[3] = cos\u03b8\u2081\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    \u03b8\u2080 = 0.0\n    \u03b8\u2081 = 0.0\n    rSqr = 0.0\n    minError = Inf\n    for i in 1:iMax\n        params.\u03b8\u2080 = 2 * pi * (i / iMax)\n        for j in 1:jMax\n            params.\u03b8\u2081 = 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                \u03b8\u2080 = params.\u03b8\u2080\n                \u03b8\u2081 = params.\u03b8\u2081\n                rSqr = currentRSqr\n            end\n        end\n    end\n    return  W, C + vec(average), sqrt(rSqr), \u03b8\u2080, \u03b8\u2081\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\u1d62,\n        compute H\u207b\u00b9 b\u1d62 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\u03bd, n\u03bd)` where `n\u03bd` is the number of frequency bands.\n\"\"\"\nfunction ilc_weights(cij::Array{<:AbstractFloat,2})\n    if size(cij)[1] \u2260 size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    else\n        M = Symmetric(cij)\n    end\n    n\u03bd = size(cij)[1]\n    e = ones(n\u03bd) # 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\u03bd, n\u03bd)` where `n\u03bd` 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] \u2260 size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] \u2260 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\u2113[, \u2113id=3])\n\nThis function returns weights (a `n\u03bd`-by-`n\u2113` matrix) of the ILC method.\n\nHere, `n\u03bd` is the number of frequency channels and `n\u2113` 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\u2113::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(n\u2113, n\u03bd, n\u03bd)`, `(n\u03bd, n\u2113, n\u03bd)` or `(n\u03bd, n\u03bd, n\u2113)` (default).\n\n# Optional Arguments\n- `\u2113id::Integer=3`: location of the index for the `n\u2113` domain. `\u2113id=1` if `cij\u2113[n\u2113,n\u03bd,n\u03bd]`, `\u2113id=2` if `cij\u2113[n\u03bd,n\u2113,n\u03bd]`, and `\u2113id=3` (the default value) if `cij\u2113[n\u03bd,n\u03bd,n\u2113]`.\n\"\"\"\nfunction ilc_weights(\n    cij\u2113::Array{<:AbstractFloat,3},\n    \u2113id::Integer = 3,\n)\n    if \u2113id > 3 || \u2113id < 1\n        throw(DomainError(\u2113id, \"\u2113id must be 1, 2, or 3\"))\n    end\n    if (\u2113id == 3 && size(cij\u2113)[1] \u2260 size(cij\u2113)[2]) ||\n       (\u2113id == 2 && size(cij\u2113)[1] \u2260 size(cij\u2113)[3]) ||\n       (\u2113id == 1 && size(cij\u2113)[2] \u2260 size(cij\u2113)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    n\u2113 = size(cij\u2113)[\u2113id]\n    n\u03bd = ifelse(\u2113id == 3, size(cij\u2113)[1], size(cij\u2113)[3])\n    e = ones(n\u03bd)      # e = [1,...,1]\n    w\u2113 = zeros(n\u03bd, n\u2113) # ILC weights\n    for i\u2113 = 1:n\u2113\n        if \u2113id == 3\n            M = Symmetric(cij\u2113[:, :, i\u2113])\n        elseif \u2113id == 2\n            M = Symmetric(cij\u2113[:, i\u2113, :])\n        else\n            M = Symmetric(cij\u2113[i\u2113, :, :])\n        end\n        x = M \\ e\n        w\u2113[:, i\u2113] = x / e'x\n    end\n    return w\u2113\nend\n\n\"\"\"\n    ilc_weights(cij\u2113, e[, \u2113id=3])\n\nThis function returns weights (a `n\u03bd`-by-`n\u2113` matrix) of the ILC method.\n\nHere, `n\u03bd` is the number of frequency channels and `n\u2113` 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\u2113::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(n\u2113, n\u03bd, n\u03bd)`, `(n\u03bd, n\u2113, n\u03bd)` or `(n\u03bd, n\u03bd, n\u2113)` (default).\n- `e::Array{<:AbstractFloat,1}`: vector of the frequency response. E.g., `e = [1,...,1]` for CMB.\n\n# Optional Arguments\n- `\u2113id::Integer=3`: location of the index for the `n\u2113` domain. `\u2113id=1` if `cij\u2113[n\u2113,n\u03bd,n\u03bd]`, `\u2113id=2` if `cij\u2113[n\u03bd,n\u2113,n\u03bd]`, and `\u2113id=3` (the default value) if `cij\u2113[n\u03bd,n\u03bd,n\u2113]`.\n\"\"\"\nfunction ilc_weights(\n    cij\u2113::Array{T,3},\n    e::Array{T,1},\n    \u2113id::Integer = 3,\n) where {T<:AbstractFloat}\n    if \u2113id > 3 || \u2113id < 1\n        throw(DomainError(\u2113id, \"\u2113id must be 1, 2, or 3\"))\n    end\n    if (\u2113id == 3 && size(cij\u2113)[1] \u2260 size(cij\u2113)[2]) ||\n       (\u2113id == 2 && size(cij\u2113)[1] \u2260 size(cij\u2113)[3]) ||\n       (\u2113id == 1 && size(cij\u2113)[2] \u2260 size(cij\u2113)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    n\u2113 = size(cij\u2113)[\u2113id]\n    n\u03bd = ifelse(\u2113id == 3, size(cij\u2113)[1], size(cij\u2113)[3])\n    if length(e) \u2260 n\u03bd\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector do not match\"))\n    end\n    w\u2113 = zeros(n\u03bd, n\u2113) # ILC weights\n    for i\u2113 = 1:n\u2113\n        if \u2113id == 3\n            M = Symmetric(cij\u2113[:, :, i\u2113])\n        elseif \u2113id == 2\n            M = Symmetric(cij\u2113[:, i\u2113, :])\n        else\n            M = Symmetric(cij\u2113[i\u2113, :, :])\n        end\n        x = M \\ e\n        w\u2113[:, i\u2113] = x / e'x\n    end\n    return w\u2113\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\u03bd, n\u03bd)` where `n\u03bd` 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] \u2260 size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] \u2260 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\u2113, w\u2113[, \u2113id::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\u2113::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(n\u2113, n\u03bd, n\u03bd)`, `(n\u03bd, n\u2113, n\u03bd)` or `(n\u03bd, n\u03bd, n\u2113)` (default).\n- `w\u2113::Array{<:AbstractFloat,2}`: ILC weights (a `n\u03bd`-by-`n\u2113` matrix).\n    - Here, `n\u03bd` is the number of frequency bands and `n\u2113` is the number of elements in the relevant domain.\n\n# Optional Arguments\n- `\u2113id::Integer=3`: location of the index for the `n\u2113` domain. `\u2113id=1` if `cij\u2113[n\u2113,n\u03bd,n\u03bd]`, `\u2113id=2` if `cij\u2113[n\u03bd,n\u2113,n\u03bd]`, and `\u2113id=3` (the default value) if `cij\u2113[n\u03bd,n\u03bd,n\u2113]`.\n\"\"\"\nfunction ilc_clean_cij(\n    cij\u2113::Array{T,3},\n    w\u2113::Array{T,2},\n    \u2113id::Integer = 3,\n) where {T<:AbstractFloat}\n    if \u2113id > 3 || \u2113id < 1\n        throw(DomainError(\u2113id, \"\u2113id must be 1, 2, or 3\"))\n    end\n    if (\u2113id == 3 && size(cij\u2113)[1] \u2260 size(cij\u2113)[2]) ||\n       (\u2113id == 2 && size(cij\u2113)[1] \u2260 size(cij\u2113)[3]) ||\n       (\u2113id == 1 && size(cij\u2113)[2] \u2260 size(cij\u2113)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    n\u2113 = size(cij\u2113)[\u2113id]\n    n\u03bd = ifelse(\u2113id == 3, size(cij\u2113)[1], size(cij\u2113)[3])\n    if n\u2113 \u2260 size(w\u2113)[2] || n\u03bd \u2260 size(w\u2113)[1]\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the ILC weight do not match\"))\n    end\n    cl = zeros(n\u2113)\n    for i\u2113 = 1:n\u2113\n        if \u2113id == 3\n            M = Symmetric(cij\u2113[:, :, i\u2113])\n        elseif \u2113id == 2\n            M = Symmetric(cij\u2113[:, i\u2113, :])\n        else\n            M = Symmetric(cij\u2113[i\u2113, :, :])\n        end\n        cl[i\u2113] = w\u2113[:, i\u2113]' * M * w\u2113[:, i\u2113]\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": "using Polylogarithms\nusing SpecialFunctions\nusing Test\nusing DataFrames, CSV\nimport Base.MathConstants: \u03c0, pi, \u212f, e, \u03b3, eulergamma, catalan, \u03c6, golden\ninclude(\"test_defs.jl\")\n\n@testset \"Harmonic numbers\" begin\n\n    @testset \"    throws errors\" begin\n        @test_throws DomainError stieltjes(-1)\n        @test_throws DomainError stieltjes(11)\n        @test_throws MethodError stieltjes(1.5)\n    end\n    \n    @testset \"    types\" begin\n        @test typeof(stieltjes(1)) == Float64\n    end\n\n    @testset \"    values\" begin\n        @test stieltjes(0) \u2245 \u03b3\n        function gen_euler_calc(n::Integer)\n            m = 10000000 # just choose a big value for the moment\n            total = -log(m)^(n+1) / (n+1)\n            for k=1:m\n                total += log(k)^n / k\n            end\n            return total\n        end\n        @test abs(stieltjes(1) - gen_euler_calc(1)) < 1.0e-5 # this series is a little crude as a test\n        @test abs(stieltjes(2) - gen_euler_calc(2)) < 1.0e-4 # this series is a little crude as a test\n        @test abs(stieltjes(3) - gen_euler_calc(3)) < 1.0e-3 # this series is a little crude as a test\n    end\n\nend\n", "meta": {"hexsha": "97624de3a8d49768610fdbd2b309fba964ba5dcd", "size": 1141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/stieltjes_test.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": "test/stieltjes_test.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": "test/stieltjes_test.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": 31.6944444444, "max_line_length": 102, "alphanum_fraction": 0.6082383874, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7923369732139225}}
{"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\u1d9c = 1.0 - t\n    t\u1d62 = 1.0\n    c\u1d62 = 1.0\n    b\u1d62 = control[:, 1]*t\u1d9c\n    n = size(control, 2) - 1\n    for i in 1:n-1\n        t\u1d62 = t\u1d62*t\n        c\u1d62 = (n-i+1)*c\u1d62/i\n        b\u1d62 = (b\u1d62+ c\u1d62*control[:, i+1]*t\u1d62)*t\u1d9c\n    end\n    b\u1d62 + control[:, n+1]*t\u1d62*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) \u2208 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 \u2208 X, u \u2208 U, x(0) \u2208 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": "using Test, JLD2, LinearAlgebra\n#\n# gradient computation by parial automatic differentiation and adjoint merthods \n# of \n#           E(v) = \u222b |U(v)|\u00b2 dx \n# where \n# A(v) U(v) = F(v) the discrete version of - \u0394 u = f\n# and v are the vertices of the voronoi cells \n# \n\n# load polygonal mesh \nfilename, nc = \"squarepolmesh_coarse\", 100\nmesh_filename = \"$(@__DIR__)/data/$(filename)_$(nc).jld2\"\nprintln(\"read file $(mesh_filename)\")\nJLD2.@load(mesh_filename, pv, cellsb, cellsbt, t, pb, tb) \n # boundary points / rhs \n rhs, boundary_condition = if occursin(\"square\", mesh_filename)\n    PolygonalFem.rhs_sqr, PolygonalFem.boundary_condition_sqr\nelse\n    PolygonalFem.rhs_L, PolygonalFem.boundary_condition_L\nend\n\nnp, \u03b5 = size(pv, 1), 1e-4\nx, dp = pv, 2 * rand(size(pv)...) .- 1\nIb = unique(PolygonalFem.btri(t)[:])\nxp, xm = x .+ \u03b5 * dp, x .- \u03b5 * dp\n# finite differences\nf = x -> PolygonalFem.costnormU(x, cellsb, t, rhs, boundary_condition, Ib)\nfp, fm = f(xp), f(xm)\n@time g = PolygonalFem.\u2207costnormU(x, cellsb, t, rhs, boundary_condition, Ib)\n@time g = PolygonalFem.\u2207costnormU(x, cellsb, t, rhs, boundary_condition, Ib)\nprintln(\"\")\nprintln(fp)\nprintln(fm)\nprintln(\" \")\nprintln((fp - fm) / (2 * \u03b5))\nprintln(dot(g, dp))\nprintln(\"\")\n@testset \"test eval gradient dot function for polygonal costnormU\" begin \n    @test abs(dot(g, dp) - (fp - fm) / (2 * \u03b5)) < 1e-4\nend", "meta": {"hexsha": "3d3f380b18e0e4a92a3ea8c793cd6e141ce50f08", "size": 1358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_costnormU.jl", "max_stars_repo_name": "edljk/PolygonalFem.jl", "max_stars_repo_head_hexsha": "97c25ce56069ae1e4bfdacfe646896e3ca44611a", "max_stars_repo_licenses": ["MIT"], "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_costnormU.jl", "max_issues_repo_name": "edljk/PolygonalFem.jl", "max_issues_repo_head_hexsha": "97c25ce56069ae1e4bfdacfe646896e3ca44611a", "max_issues_repo_licenses": ["MIT"], "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_costnormU.jl", "max_forks_repo_name": "edljk/PolygonalFem.jl", "max_forks_repo_head_hexsha": "97c25ce56069ae1e4bfdacfe646896e3ca44611a", "max_forks_repo_licenses": ["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.1219512195, "max_line_length": 80, "alphanum_fraction": 0.676730486, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7923369616322717}}
{"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    \u2220(A, B, C)\n\nAngle \u2220ABC between rays BA and BC.\nSee https://en.wikipedia.org/wiki/Angle.\n\nUses the two-argument form of `atan` returning value in range [-\u03c0, \u03c0].\nSee https://en.wikipedia.org/wiki/Atan2.\n\n## Examples\n\n```julia\n\u2220(Point(1,0), Point(0,0), Point(0,1)) == \u03c0/2\n```\n\"\"\"\n\u2220(A::P, B::P, C::P) where {P<:Point{2}} = \u2220(A-B, C-B)\n\u2220(A::P, B::P, C::P) where {P<:Point{3}} = \u2220(A-B, C-B)\n\n\"\"\"\n    \u2220(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 [-\u03c0, \u03c0].\nSee https://en.wikipedia.org/wiki/Atan2.\n\n## Examples\n\n```julia\n\u2220(Vec(1,0), Vec(0,1)) == \u03c0/2\n```\n\"\"\"\n\u2220(u::V, v::V) where {V<:Vec{2}} = atan(u \u00d7 v, u \u22c5 v)  # preserve sign\n\u2220(u::V, v::V) where {V<:Vec{3}} = atan(norm(u \u00d7 v), u \u22c5 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 \u2264 i+di \u2264 n && 1 \u2264 j+dj \u2264 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# \u2554\u2550\u2561 57f367d6-025a-11eb-182a-773094da4307\nusing Yao, YaoPlots #calling the Yao and YaoPlots package\n\n# \u2554\u2550\u2561 3c9cf124-0257-11eb-16ce-0d857dce310f\nmd\"# Using Yao - The basics of quantum computing in Julia using Yao.jl\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 443afbfa-025a-11eb-03c6-e74bb5344e36\nlet\n\t##circuit = \n\t##plot(circuit)\nend\n\n# \u2554\u2550\u2561 686ec0a0-025b-11eb-339e-1158d9b25529\nmd\"What about multiqubit gates? We can use the control gate in Yao using the control\\( \\) parameter.\" \n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25003c9cf124-0257-11eb-16ce-0d857dce310f\n# \u255f\u25005d5644b2-0257-11eb-36e9-7f4803cb3558\n# \u255f\u25000f7d5bdc-0258-11eb-05bb-074d1b38c551\n# \u255f\u2500ee15c64e-025a-11eb-2158-bd9cbea5f262\n# \u2560\u255057f367d6-025a-11eb-182a-773094da4307\n# \u2560\u2550dcf63604-0258-11eb-1466-fb21170c2e1a\n# \u255f\u2500841aa488-0259-11eb-351a-c1f1770b3a51\n# \u2560\u2550af1aa2b4-0259-11eb-29fe-19ba9462deb9\n# \u255f\u25001efc3566-025a-11eb-2aae-fd953f22edfb\n# \u2560\u2550443afbfa-025a-11eb-03c6-e74bb5344e36\n# \u255f\u2500686ec0a0-025b-11eb-339e-1158d9b25529\n# \u2560\u255022f24af0-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\u00e9mence 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 \u2297 N\n        nomin+=length((times(s,v,u) \u2229 times(s,v,w)) \u2229 times(s,u,w))\n        denom+=length(times(s,v,u) \u2229 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\u00e9mence 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 \u2297 Nt if ((t \u2208 times(s,v,u)) & (t \u2208 times(s,v,w)) & (t \u2208 times(s,u,w)))])\n    denom=sum([1.0 for (u,w) in Nt \u2297 Nt if ((t \u2208 times(s,v,u)) & (t \u2208 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\u00e9mence 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\u00e9mence 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 \u2297 s.V\n            if ((t \u2208 times(s,v,u)) & (t \u2208 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\u00e9mence 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    \u03c4 = 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(\u03c4[1:end-1],\u03c4[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\u00e9mence 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    \u03c4 = times(s)\n    acc::Float64 = 0.0\n    for v in s.V\n        for t in zip(\u03c4[1:end-1],\u03c4[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\u03b3 = 0.57721\nfunction ll(\u03b1::Float64, \u03b2::Float64)\n    a = exp.(\u03b1 .+ \u03b2*temp)\n    return prod( (a ./ (1 .+ a) ).^failure .* (1 ./ (1 .+ a)).^(1 .- failure) )\nend\nfunction mh_logit(T::Int, \u03b1_hat::Float64, \u03b2_hat::Float64, \u03c3_hat::Float64)\n    \u03c6 = Normal(\u03b2_hat, \u03c3_hat)\n    \u03c0 = Exponential(exp(\u03b1_hat+\u03b3))\n    \u0391 = ones(T)\n    \u0392 = ones(T)\n    for t = 1:T-1\n        \u03b1 = log(rand(\u03c0))\n        \u03b2 = rand(\u03c6)\n        r = ( ll(\u03b1, \u03b2) / ll(\u0391[t], \u0392[t]) ) * ( pdf(\u03c6, \u0392[t]) / pdf(\u03c6, \u03b2) )\n        if rand() < r\n            \u0391[t+1] = \u03b1\n            \u0392[t+1] = \u03b2\n        else\n            \u0391[t+1] = \u0391[t]\n            \u0392[t+1] = \u0392[t]\n        end\n    end\n    return \u0391, \u0392\nend\n\n# trace plot\n\n\u0391, \u0392 = mh_logit(10000, 15.04, -0.233, 0.108)\n\np1 = plot(\u0391, legend = false, xlab = \"Intercept\")\nhline!([15.04])\n\np2 = plot(\u0392, legend = false, xlab = \"Slope\")\nhline!([-0.233])\n\nplot(p1, p2, layout = (1,2))\n\n# mean trace plot\n\n\u0391mean = cumsum(\u0391) ./ collect(1:length(\u0391))\n\u0392mean = cumsum(\u0392) ./ collect(1:length(\u0392))\n\np1 = plot(\u0391mean, legend = false, xlab = \"Intercept\")\nhline!([15.04])\n\np2 = plot(\u0392mean, 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    \u03bc = mean(mat; dims = 1);\r\n    \u03c3 = std(mat; dims = 1);\r\n    return (mat .- \u03bc) ./ \u03c3;\r\nend\r\n\r\nfunction func_favar(y\u2098, y\u209a, p, \u03b6)\r\n    # y\u2098: data - main block\r\n    # y\u209a: data - factor block - to be\r\n    # p: lag term for VAR\r\n    # \u03b6: Number of factors to be extracted\r\n\r\n    T, k\u2098 = size(y\u2098);\r\n\r\n    # For principal component analysis (PCA), always use standardized data.\r\n    res_pca = fit(PCA, func_std(y\u209a); maxoutdim = \u03b6);\r\n    \ud835\udd3d\u2092 = projection(res_pca);\r\n\r\n    Q = y\u209a';\r\n    Z = [y\u2098 \ud835\udd3d\u2092]';\r\n    \u213e\u2092 = (Q * Z')/(Z * Z');\r\n    \u213e\u2092\ud835\udc66 = \u213e\u2092[:, (1:k\u2098)];\r\n    x\u0303 = y\u209a - (\u213e\u2092\ud835\udc66 * y\u2098')';\r\n\r\n    ssr\u2092 = sum((Q - \u213e\u2092 * Z).^2, dims = 2)\r\n\r\n    # Start the iteraction process\r\n    \ud835\udd3d\u2081 = \ud835\udd3d\u2092;\r\n    \u213e\u2081 = \u213e\u2092; \u213e\u2081\ud835\udc66 = \u213e\u2092\ud835\udc66;\r\n    ssr\u2081 = ssr\u2092\r\n\r\n    n_\u03dd = 0; # Count iterations;\r\n    while sum(abs(ssr\u2081 .- ssr\u2092) > 10^(-6))\r\n        # If no convergence, repeat the process\r\n        # Update the criteria\r\n        \ud835\udd3d\u2092 = \ud835\udd3d\u2081;\r\n        ssr\u2092 = ssr\u2081;\r\n\r\n        # Redraw component\r\n        res_pca = fit(PCA, func_std(x\u0303); maxoutdim = \u03b6);\r\n        \ud835\udd3d\u2081 = projection(res_pca);\r\n\r\n        Q = y\u209a';\r\n        Z = [y\u2098 \ud835\udd3d\u2081]';\r\n        \u213e\u2081 = (Q * Z')/(Z * Z');\r\n        \u213e\u2081\ud835\udc66 = \u213e\u2081[:, (1:k\u2098)];\r\n        x\u0303 = y\u209a - (\u213e\u2081\ud835\udc66 * y\u2098')';\r\n\r\n        ssr\u2081 = sum((Q - \u213e\u2081 * Z).^2, dims = 2);\r\n\r\n        n_\u03dd = n_\u03dd + 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\u209a\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\u209a = (k\u2098 + 1):size(Gamma_final, 2)\r\n        if \u213e\u2081[1, i\u209a] < 0\r\n            \u213e\u2081[:, i\u209a] = -1 .* \u213e\u2081[:, i\u209a];\r\n            \ud835\udd3d\u2081[:, (i\u209a - k\u2098)] = -1 .* \ud835\udd3d\u2081[:, (i\u209a - k\u2098)];\r\n        end\r\n    end\r\n    =#\r\n\r\n    Q = y\u209a';\r\n    Z = [y\u2098 \ud835\udd3d\u2081]';\r\n    \u213e\u2081 = (Q * Z')/(Z * Z');\r\n    \u213e\u2081\ud835\udc66 = \u213e\u2081[:, (1:k\u2098)];\r\n    x\u0303 = y\u209a - (\u213e\u2081\ud835\udc66 * y\u2098')';\r\n\r\n    # compute VAR(p)\r\n    \ud835\udd07 = [y\u2098 \ud835\udd3d\u2081];\r\n\r\n    \ud835\udea9, \ud835\udf84, \ud835\udf68 = func_VAR(\ud835\udd07, p);\r\n\r\n    return \ud835\udea9, \ud835\udf84, \ud835\udf68, \ud835\udd3d\u2081, \u213e\u2081;\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": "using DataInterpolations, Test\nusing FiniteDifferences\nusing DataInterpolations: derivative\n\nfunction test_derivatives(func, tspan, name::String)\n  trange = range(minimum(tspan), maximum(tspan), length=32)[2:end-1]\n  @testset \"$name\" begin\n    for t in trange\n      # Linearly spaced points might lead to evaluations outside\n      # trange\n      cdiff = central_fdm(5, 1; geom=true)(_t -> func(_t), t)\n      adiff = derivative(func, t)\n      @test isapprox(cdiff, adiff, atol=1e-8)\n    end\n  end\nend\n\n# Linear Interpolation\nu = 2.0collect(1:10)\nt = 1.0collect(1:10)\nA = LinearInterpolation(u,t)\n\ntest_derivatives(A, t, \"Linear Interpolation (Vector)\")\n\nu = vcat(2.0collect(1:10)', 3.0collect(1:10)')\nA = LinearInterpolation(u,t)\n\ntest_derivatives(A, t, \"Linear Interpolation (Matrix)\")\n\n# Quadratic Interpolation\nu = [1.0, 4.0, 9.0, 16.0]\nt = [1.0, 2.0, 3.0, 4.0]\nA = QuadraticInterpolation(u,t)\n\ntest_derivatives(A, t, \"Quadratic Interpolation (Vector)\")\n\nu = [1.0 4.0 9.0 16.0; 1.0 4.0 9.0 16.0]\nA = QuadraticInterpolation(u,t)\n\ntest_derivatives(A, t, \"Quadratic Interpolation (Matrix)\")\n\n# Lagrange Interpolation\nu = [1.0, 4.0, 9.0]\nt = [1.0, 2.0, 3.0]\nA = LagrangeInterpolation(u,t)\n\ntest_derivatives(A, t, \"Lagrange Interpolation (Vector)\")\n\n# Lagrange Interpolation\nu = [1.0 4.0 9.0; 1.0 2.0 3.0]\nt = [1.0, 2.0, 3.0]\nA = LagrangeInterpolation(u,t)\n\ntest_derivatives(A, t, \"Lagrange Interpolation (Matrix)\")\n\n# Lagrange Interpolation\nu = [[1.0, 4.0, 9.0], [3.0, 7.0, 4.0], [5.0, 4.0, 1.0]]\nt = [1.0, 2.0, 3.0]\nA = LagrangeInterpolation(u,t)\n\ntest_derivatives(A, t, \"Lagrange Interpolation (Vector of Vectors)\")\n\n# Lagrange Interpolation\nu = [[3.0 1.0 4.0; 1.0 5.0 9.0], [2.0 6.0 5.0; 3.0 5.0 8.0], [9.0 7.0 9.0; 3.0 2.0 3.0]]\nt = [1.0, 2.0, 3.0]\nA = LagrangeInterpolation(u,t)\n\ntest_derivatives(A, t, \"Lagrange Interpolation (Vector of Matrices)\")\n\n# Akima Interpolation\nu = [0.0, 2.0, 1.0, 3.0, 2.0, 6.0, 5.5, 5.5, 2.7, 5.1, 3.0]\nt = collect(0.0:10.0)\nA = AkimaInterpolation(u, t)\n\ntest_derivatives(A, t, \"Akima Interpolation\")\n\n# QuadraticSpline Interpolation\nu = [0.0, 1.0, 3.0]\nt = [-1.0, 0.0, 1.0]\n\nA = QuadraticSpline(u,t)\n\ntest_derivatives(A, t, \"Quadratic Interpolation (Vector)\")\n\n# QuadraticSpline Interpolation\nu = [[1.0, 2.0, 9.0], [3.0, 7.0, 5.0], [5.0, 4.0, 1.0]]\nt = [-1.0, 0.0, 1.0]\n\nA = QuadraticSpline(u,t)\n\ntest_derivatives(A, t, \"Quadratic Interpolation (Vector of Vectors)\")\n\n# QuadraticSpline Interpolation\nu = [[1.0 4.0 9.0; 5.0 9.0 2.0], [3.0 7.0 4.0; 6.0 5.0 3.0], [5.0 4.0 1.0; 2.0 3.0 8.0]]\nt = [-1.0, 0.0, 1.0]\n\nA = QuadraticSpline(u,t)\n\ntest_derivatives(A, t, \"Quadratic Interpolation (Vector of Matrices)\")\n\n# CubicSpline Interpolation\nu = [0.0, 1.0, 3.0]\nt = [-1.0, 0.0, 1.0]\n\nA = CubicSpline(u,t)\n\ntest_derivatives(A, t, \"Cubic Spline Interpolation (Vector)\")\n\n# CubicSpline Interpolation\nu = [[1.0, 2.0, 9.0], [3.0, 7.0, 5.0], [5.0, 4.0, 1.0]]\nt = [-1.0, 0.0, 1.0]\n\nA = CubicSpline(u,t)\n\ntest_derivatives(A, t, \"Cubic Spline Interpolation (Vector of Vectors)\")\n\n# CubicSpline Interpolation\nu = [[1.0 4.0 9.0; 5.0 9.0 2.0], [3.0 7.0 4.0; 6.0 5.0 3.0], [5.0 4.0 1.0; 2.0 3.0 8.0]]\nt = [-1.0, 0.0, 1.0]\n\nA = CubicSpline(u,t)\n\ntest_derivatives(A, t, \"Cubic Spline Interpolation (Vector of Matrices)\")\n\n# BSpline Interpolation and Approximation\nt = [0,62.25,109.66,162.66,205.8,252.3]\nu = [14.7,11.51,10.41,14.95,12.24,11.22]\n\nA = BSplineInterpolation(u,t,2,:Uniform,:Uniform)\n\ntest_derivatives(A, t, \"BSpline Interpolation (Uniform, Uniform)\")\n\nA = BSplineInterpolation(u,t,2,:ArcLen,:Average)\n\ntest_derivatives(A, t, \"BSpline Interpolation (Arclen, Average)\")\n\nA = BSplineApprox(u,t,3,4,:Uniform,:Uniform)\n\ntest_derivatives(A, t, \"BSpline Approx (Uniform, Uniform)\")\n", "meta": {"hexsha": "b5eca146b5bf015318b31a7bf4e7f9c44687d329", "size": 3702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/derivative_tests.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": "test/derivative_tests.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": "test/derivative_tests.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": 26.4428571429, "max_line_length": 88, "alphanum_fraction": 0.6558616964, "num_tokens": 1608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.7921625588734015}}
{"text": "#Prezentacja wynik\u00f3w do sprawozdania: Zadanie P1.2\n#Kacper Kulczak 279079\n\n\n#Pomocnicza funkcja pomgaj\u0105ca. 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\u015bci mno\u017ce\u0144 i dziele\u0144 w zale\u017cnosci 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": "using MultivariateStats\nusing Base.Test\n\nsrand(34568)\n\n## data\n\nd = 3\nn = 5\n\nX = rand(d, n)\nmv = vec(mean(X, 2))\nC = cov(X, 2)\nC0 = copy(C)\n\nemax = maximum(eigvals(C))\nrc = 0.01\nCr = C + (emax * rc) * eye(d)\n\n## cov_whitening\n\ncf = cholfact(C, :U)\nW = cov_whitening(cf)\n@test istriu(W)\n@test W'C * W \u2248 eye(d)\n\ncf = cholfact(C, :L)\nW = cov_whitening(cf)\n@test istriu(W)\n@test W'C * W \u2248 eye(d)\n\nW = cov_whitening(C)\n@test C == C0\n@test istriu(W)\n@test W'C * W \u2248 eye(d)\n\nW = cov_whitening(C, 0.0)\n@test C == C0\n@test istriu(W)\n@test W'C * W \u2248 eye(d)\n\nW = cov_whitening(C, rc)\n@test istriu(W)\n@test W'Cr * W \u2248 eye(d)\n\n\n# Whitening from data\n\nf = fit(Whitening, X)\nW = f.W\n@test isa(f, Whitening{Float64})\n@test mean(f) === f.mean\n@test istriu(W)\n@test W'C * W \u2248 eye(d)\n@test transform(f, X) \u2248 W' * (X .- f.mean)\n\nf = fit(Whitening, X; regcoef=rc)\nW = f.W\n@test W'Cr * W \u2248 eye(d)\n\nf = fit(Whitening, X; mean=mv)\nW = f.W\n@test W'C * W \u2248 eye(d)\n\nf = fit(Whitening, X; mean=0)\nCx = (X * X') / (n - 1)\nW = f.W\n@test W'Cx * W \u2248 eye(d)\n\n# invsqrtm\n\nR = invsqrtm(C)\n@test C == C0\n@test R \u2248 inv(sqrtm(C))\n\n", "meta": {"hexsha": "9c89bedfd5c54df000efdb69d7b17a98a84a446a", "size": 1093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/whiten.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": "test/whiten.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": "test/whiten.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": 14.3815789474, "max_line_length": 42, "alphanum_fraction": 0.5773101555, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.792161007465517}}
{"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": "using ProgressBars, Plots, StatsBase, LaTeXStrings, JLD, Distributions, StatsPlots\n\nPlots.default(titlefontsize=12, tickfontsize=10, labelfontsize=16,\n    fontfamily=\"Computer Modern\")\n\nSampleNumber = 100000\nNList = [5, 10, 100, 1000]\nData = [[sum(rand(N)) for i in ProgressBar(1:SampleNumber)] for N \u2208 NList]\n\ncd(dirname(@__FILE__))\nsave(\"../../Data/Q1/Q1-samples.jld\",\"Samples\", Data)\n\nplots = []\ncolors = [:steelblue, :purple, :green, :brown]\nfor i \u2208 1:4\n    Plt = begin\n    histogram(Data[i],nbins = 60, normalize = true, c = colors[i], label = L\"Histogram\\ of\\ Samples\")\n    plot!(Normal(mean(Data[i]),std(Data[i])), c = :black, lineWidth = 10,\n        label = L\"\\mathcal{Normal}(\\mu = %$(round(mean(Data[i]),digits = 2)), \\sigma = %$(round(std(Data[i]),digits = 2)))\")\n    plot!(frame = :box, title = \"N = $(NList[i]), $SampleNumber Samples\",\n        xlabel = L\"X_N\", ylabel = L\"Counting\\ ratio\")\n    end\n    push!(plots,Plt)\nend\n\n\nplot(plots..., size = (1000,1000), plot_title = \"Normalized Distribution of Samples\")\nsavefig(\"../../Figs/Q1/Q1-Hist.pdf\")\n", "meta": {"hexsha": "d80180176ea17a2a828b2ddcc8d6912cd1878c89", "size": 1061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet6/Codes/Q1/Q1-NormRand.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": "ProblemSet6/Codes/Q1/Q1-NormRand.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": "ProblemSet6/Codes/Q1/Q1-NormRand.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": 36.5862068966, "max_line_length": 124, "alphanum_fraction": 0.6456173421, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7921609985608561}}
{"text": "# [1] M. R. Teague, \u201cImage analysis via the general theory of moments*,\u201d 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    \u2133\u2080\u2080 = zeros(N)\n    \u2133\u2081\u2080 = zeros(N)\n    \u2133\u2080\u2081 = zeros(N)\n    \u2133\u2081\u2081 = zeros(N)\n    \u2133\u2082\u2080 = zeros(N)\n    \u2133\u2080\u2082 = 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            \u2133\u2080\u2080[l] += 1\n            \u2133\u2081\u2080[l] += x\n            \u2133\u2080\u2081[l] += y\n            \u2133\u2081\u2081[l] += x*y\n            \u2133\u2082\u2080[l] += x^2 + 1/12\n            \u2133\u2080\u2082[l] += y^2 + 1/12\n        end\n    end\n    t = pushcol(t, :M\u2080\u2080 => \u2133\u2080\u2080, :M\u2081\u2080 => \u2133\u2081\u2080, :M\u2080\u2081 => \u2133\u2080\u2081, :M\u2081\u2081 => \u2133\u2081\u2081, :M\u2082\u2080 => \u2133\u2082\u2080, :M\u2080\u2082 => \u2133\u2080\u2082)\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\u2080\u2081 / :M\u2080\u2080, :M\u2081\u2080 / :M\u2080\u2080)}\nend\n\nfunction compute_semi_axes(t::IndexedTable)\n    semi_axes = select(t, (:M\u2080\u2080,  :M\u2081\u2080, :M\u2080\u2081, :M\u2081\u2081, :M\u2082\u2080, :M\u2080\u2082) => row -> compute_semi_axes(row...))\n    t = pushcol(t, :semi_axes => semi_axes)\nend\n\n\nfunction compute_semi_axes(M\u2080\u2080::Real, M\u2081\u2080::Real, M\u2080\u2081::Real, M\u2081\u2081::Real, M\u2082\u2080::Real, M\u2080\u2082::Real)\n    \u03bc\u2032\u2082\u2080 = (M\u2082\u2080 / M\u2080\u2080) - (M\u2081\u2080 / M\u2080\u2080)^2\n    \u03bc\u2032\u2080\u2082 = (M\u2080\u2082 / M\u2080\u2080) - (M\u2080\u2081 / M\u2080\u2080)^2\n    \u03bc\u2032\u2081\u2081 = (M\u2081\u2081 / M\u2080\u2080) - ((M\u2081\u2080 / M\u2080\u2080) * (M\u2080\u2081 / M\u2080\u2080))\n\n    # See Equations (7) and (8) in [1].\n    l\u2081 = sqrt((\u03bc\u2032\u2082\u2080 + \u03bc\u2032\u2080\u2082 + sqrt(4 * \u03bc\u2032\u2081\u2081^2 +  (\u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082)^2)) / (1 / 2))\n    l\u2082 = sqrt((\u03bc\u2032\u2082\u2080 + \u03bc\u2032\u2080\u2082 - sqrt(4 * \u03bc\u2032\u2081\u2081^2 +  (\u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082)^2)) / (1 / 2))\n    min(l\u2081, l\u2082), max(l\u2081, l\u2082)\nend\n\nfunction compute_orientation(t::IndexedTable)\n    orientation = select(t, (:M\u2080\u2080,  :M\u2081\u2080, :M\u2080\u2081, :M\u2081\u2081, :M\u2082\u2080, :M\u2080\u2082) => row -> compute_orientation(row...))\n    t = pushcol(t, :orientation => orientation)\nend\n\nfunction compute_eccentricity(t::IndexedTable)\n    eccentricity = select(t, (:M\u2080\u2080,  :M\u2081\u2080, :M\u2080\u2081, :M\u2081\u2081, :M\u2082\u2080, :M\u2080\u2082) => row -> compute_eccentricity(row...))\n    t = pushcol(t, :eccentricity => eccentricity)\nend\n\nfunction compute_eccentricity(M\u2080\u2080::Real, M\u2081\u2080::Real, M\u2080\u2081::Real, M\u2081\u2081::Real, M\u2082\u2080::Real, M\u2080\u2082::Real)\n    b, a = compute_semi_axes(M\u2080\u2080, M\u2081\u2080, M\u2080\u2081, M\u2081\u2081, M\u2082\u2080, M\u2080\u2082)\n    e = sqrt(1 - (b/a)^2)\nend\n\n# [1] M. R. Teague, \u201cImage analysis via the general theory of moments*,\u201d 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\u2080\u2080::Real, M\u2081\u2080::Real, M\u2080\u2081::Real, M\u2081\u2081::Real, M\u2082\u2080::Real, M\u2080\u2082::Real)\n    \u03bc\u2032\u2082\u2080 = M\u2082\u2080 / M\u2080\u2080 - (M\u2081\u2080 / M\u2080\u2080)^2\n    \u03bc\u2032\u2080\u2082 = M\u2080\u2082 / M\u2080\u2080 - (M\u2080\u2081 / M\u2080\u2080)^2\n    \u03bc\u2032\u2081\u2081 = M\u2081\u2081 / M\u2080\u2080 - (M\u2081\u2080 / M\u2080\u2080) * (M\u2080\u2081 / M\u2080\u2080)\n\n    # Ellipse tilt angle for various cases of signs of the second moments [1].\n    \u03b8 = 0.0\n    if \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 == 0 && \u03bc\u2032\u2081\u2081  == 0\n        \u03b8 = 0.0\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 == 0 && \u03bc\u2032\u2081\u2081  > 0\n        \u03b8 = 45.0\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 == 0 && \u03bc\u2032\u2081\u2081  < 0\n        \u03b8 = -45.0\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 > 0 && \u03bc\u2032\u2081\u2081 == 0\n        \u03b8 = 0.0\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 < 0 && \u03bc\u2032\u2081\u2081 == 0\n        \u03b8 = -90.0\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 > 0 && \u03bc\u2032\u2081\u2081 > 0\n        # 0 < \u03b8 < 45\n        \u03be = 2*\u03bc\u2032\u2081\u2081 / (\u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082)\n        \u03b8 = (1/2) * atand(\u03be)\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 > 0 && \u03bc\u2032\u2081\u2081 < 0\n        # -45 < \u03b8 < 0\n        \u03be = 2*\u03bc\u2032\u2081\u2081 / (\u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082)\n        \u03b8 = (1/2) * atand(\u03be)\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 < 0 && \u03bc\u2032\u2081\u2081 > 0\n        # 45 < \u03b8 < 90\n        \u03be = 2*\u03bc\u2032\u2081\u2081 / (\u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082)\n        \u03b8 = (1/2) * atand(\u03be) + 90.0\n    elseif \u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082 < 0 && \u03bc\u2032\u2081\u2081 < 0\n        # -90 < \u03b8 < -45\n        \u03be = 2*\u03bc\u2032\u2081\u2081 / (\u03bc\u2032\u2082\u2080 - \u03bc\u2032\u2080\u2082)\n        \u03b8 = (1/2) * atand(\u03be) - 90.0\n    end\n    \u03b8\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(\u03b7,c1,c2,q)\n    profit1=sum(q)^(-1/\u03b7)*q[1]-c1*q[1] # Firm 1's profit\n    profit2=sum(q)^(-1/\u03b7)*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(\u03b7,c1,c2,q)\n    q_prime11=(-1/\u03b7)*sum(q)^(-1/\u03b7-1)-(1/\u03b7)*sum(q)^(-1/\u03b7-1)+(1/\u03b7^2+1/\u03b7)*q[1]*sum(q)^(-1/\u03b7-2)-c1\n    q_prime12=(-1/\u03b7)*sum(q)^(-1/\u03b7-1)+(1/\u03b7^2+1/\u03b7)*sum(q)^(-1/\u03b7-2)*q[1]\n    q_prime21=(-1/\u03b7)*sum(q)^(-1/\u03b7-1)+(1/\u03b7^2+1/\u03b7)*sum(q)^(-1/\u03b7-2)*q[2]\n    q_prime22=(-1/\u03b7)*sum(q)^(-1/\u03b7-1)-(1/\u03b7)*sum(q)^(-1/\u03b7-1)+(1/\u03b7^2+1/\u03b7)*q[2]*sum(q)^(-1/\u03b7-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(\u03b7,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(\u03b7,c1,c2,q_old))*inv(q_prime(\u03b7,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\u03b7=1.6\nc1=0.15\nc2=0.2\ninitial_guess=[20;20]\ntolerance=[1e-5;1e-5]\n\n#   Optimization\nq_opt=cournot_newton(\u03b7,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": "using Base.Test\r\nusing Clustering\r\nusing Distances\r\n\r\nsrand(34568)\r\n\r\nX1 = randn(2, 200) .+ [0., 5.]\r\nX2 = randn(2, 200) .+ [-5., 0.]\r\nX3 = randn(2, 200) .+ [5., 0.]\r\nX = hcat(X1, X2, X3)\r\nn = size(X,2)\r\n\r\nD = pairwise(Euclidean(), X)\r\n\r\nR = dbscan(D, 1.0, 10)\r\n@test isa(R, DbscanResult)\r\nk = length(R.seeds)\r\n# println(\"k = $k\")\r\n@test k == 3\r\n@test all(R.assignments .<= k)\r\n@test length(R.assignments) == n\r\n@test length(R.counts) == k\r\nfor c = 1:k\r\n    @test countnz(R.assignments .== c) == R.counts[c]\r\nend\r\n@test all(R.counts .>= 180)\r\n\r\n", "meta": {"hexsha": "47c12985b7a8cfa24e110207db013514e7087644", "size": 545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 19.4642857143, "max_line_length": 54, "alphanum_fraction": 0.5633027523, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7920432209676156}}
{"text": "function nlp_cvx_202_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - linear objective\n    # - intersection convex quadratic constraints\n    # Variants\n    #   010 - one binding constraint (inflection point)\n    #   011 - one binding constraint (inflection point)\n    #   012 - one binding constraint (non-inflection point)\n    #   013 - one binding constraint (non-inflection point)\n    #   014 - intersection set\n\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n    @variable(model, z)\n\n    @objective(model, Min, -z)\n    @NLconstraint(model, x^2 + y^2 <= z)\n    @NLconstraint(model, x^2 + y^2 <= -z + 1)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -1, tol = objective_tol)\n    return check_solution([x, y, z], [0, 0, 1], tol = primal_tol)\nend\n", "meta": {"hexsha": "a5dad1efd780e2aa98f2a58a66fbf8d9006fd93b", "size": 999, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/202_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/202_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/202_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 28.5428571429, "max_line_length": 76, "alphanum_fraction": 0.6636636637, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7920008471099403}}
{"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# \u0394u + k^2u = 0,\n# \u2202u\u2202n|\u0393 = 0,\n# \u2202u^i/\u2202n = -im k d[2] e^{im k x\u22c5d},\n# u = u^i + u^s.\n# The normal derivative \u2202u/\u2202n 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\u03c9 = 2\u03c0\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\u22c5(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)/\u03c0) # For Re{Cauchy}\n\n\ndom = \u222a(Interval,[-2.,1.],[-1.,2.])\nsp = Space(dom)\ncwsp,cwsp2 = CauchyWeight(sp\u2297sp,0),CauchyWeight(sp\u2297sp,2)\n\u2202ui\u2202n\u0393,\u2a0d = 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\u2297sp;method=:Cholesky)\n\n@time u = \u2a0d[G]\\-\u2202ui\u2202n\u0393\nprintln(\"The length of u is: \",length(u))\nus(x,y) = linesum(g4,u,complex(x,y))+logkernel(g5,u,complex(x,y))+\u03c0*real(cauchy(g6,real(u),complex(x,y)))+\u03c0*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": "using AngleBetweenVectors\nusing Test\n\npoint1 = (1.0, 0.0)\npoint2 = (0.0, 1.0)\npoint3 = (-1.0, 0.0)\n\n@test angle(point1, point2) == angle(point2, point1)\n@test angle(point1, point3) == angle(point3, point1)\n@test angle(point3, point2) == angle(point2, point3)\n\n@test angle(point1, point2) == pi/2.0\n@test angle(point1, point3) == pi/1.0\n\npoint1 = (1.0, -1.0, 0.0,  0.0)\npoint2 = (0.0,  1.0, 0.0, -1.0)\n\n# note: 2pi/3 !== Float64(2*BigFloat(pi)/3)\n@test angle(point1, point2) == Float64(2*BigFloat(pi)/3)\n@test angle(point1, point2) == angle(point2, point1)\n\n@test (@inferred angle(0:1, -1:0)) == pi/2 # abstract vector\n@test (@inferred angle(0:1, -1.0:0.0)) == pi/2 # different eltype\n@test (@inferred angle(Real[0.0 1], Int16[-1 0])) == pi/2 # array\n@test (@inferred angle(0:1, (-1.0:0.0)*1im)) == pi/2 # complex\n\n@test isnan(@inferred angle(zeros(2), 1:2)) # zero point returns NaN\n", "meta": {"hexsha": "884ef89cf73932d6d4609ef3bcded68e1475f094", "size": 883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JeffFessler/AngleBetweenVectors.jl", "max_stars_repo_head_hexsha": "f9b89ccd1cd4469ab2698392f79b9a7698536577", "max_stars_repo_licenses": ["MIT"], "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": "JeffFessler/AngleBetweenVectors.jl", "max_issues_repo_head_hexsha": "f9b89ccd1cd4469ab2698392f79b9a7698536577", "max_issues_repo_licenses": ["MIT"], "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": "JeffFessler/AngleBetweenVectors.jl", "max_forks_repo_head_hexsha": "f9b89ccd1cd4469ab2698392f79b9a7698536577", "max_forks_repo_licenses": ["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.5357142857, "max_line_length": 68, "alphanum_fraction": 0.637599094, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.7919914268814559}}
{"text": "# # Foundations of Bilevel Programming: Example 2\n# This example is from the book _Foundations of Bilevel Programming_ by Stephan\n# Dempe, Chapter 3.2, Page 25. [url](https://www.springer.com/gp/book/9781402006319)\n# Moving the bound on x to lower level\n\n\n\n# Model of the problem\n# First level\n# ```math\n# \\min 3x + y,\\\\\n# \\notag s.t.\\\\\n# x \\leq 5,\\\\ \n# y \\leq 8,\\\\\n# y \\geq 0,\\\\\n# ```\n# Second level\n# ```math\n# \\min -x,\\\\\n# \\notag s.t.\\\\\n# x + y <= 8,\\\\\n# 4x + y >= 8,\\\\\n# 2x + y <= 13,\\\\\n# 2x - y <= 0,\\\\\n# x <= 5\\\\\n# ```\n\nusing BilevelJuMP\nusing Ipopt\nusing JuMP\nusing Test\n\nmodel = BilevelModel(Ipopt.Optimizer, mode = BilevelJuMP.ProductMode(1e-9))\n\n# First we need to define all of the variables in the upper and lower problems:\n\n@variable(Upper(model), y, start = 8 / 15)\n@variable(Lower(model), x, start = 3.5 * 8 / 15)\n\n# Then we can add the objective and constraints of the upper problem:\n# Upper level objective function\n@objective(Upper(model), Min, 3x + y)\n\n# Upper level constraints\n@constraints(Upper(model), begin\n    u1, x <= 5\n    u2, y <= 8\n    u3, y >= 0\nend)\n\n# Followed by the objective and constraints of the lower problem:\n# Lower level objective function\n@objective(Lower(model), Min, -x)\n\n# Lower level constraints\n@constraint(Lower(model), l1,  x +  y <= 8)\n@constraint(Lower(model), l2, 4x +  y >= 8)\n@constraint(Lower(model), l3, 2x +  y <= 13)\n@constraint(Lower(model), l4, 2x - 7y <= 0)\n\n# !!! tip\n#     You can use the singular `@constraint` macro or the plural `@constraints`!\n\n# We can also set hints for the variables associated with the problems.\n\n# In this example, we know the duals on the lower constraints are in\n# the set `[-15, 15]`:\nfor c in [l1, l2, l3, l4]\n    BilevelJuMP.set_dual_upper_bound(c, 15)\n    BilevelJuMP.set_dual_lower_bound(c, -15)\nend\n\n# While we think the primal variables are in `[-10, 6]` for `x` and `[-1, 9]`\n# for `y`. These hints are optional. But supplying them (e.g., from domain\n# knowledge) can be helpful for the solver.\n\nBilevelJuMP.set_primal_lower_bound_hint(x, -10)\nBilevelJuMP.set_primal_upper_bound_hint(x, 6)\nBilevelJuMP.set_primal_lower_bound_hint(y, -1)\nBilevelJuMP.set_primal_upper_bound_hint(y, 9)\n\n# Now we can solve the problem and verify the solution again that reported by\n# Dempe.\n\noptimize!(model)\n\n# Automated testing\n\n@test objective_value(model) \u2248 3 * (3.5 * 8 / 15) + (8 / 15) atol=1e-4\n@test BilevelJuMP.lower_objective_value(model) \u2248 -3.5 * 8 / 15 atol=1e-4\n@test objective_value(Lower(model)) \u2248 -3.5 * 8 / 15 atol=1e-4\n@test value(x) \u2248 3.5 * 8 / 15 atol=1e-4\n@test value(y) \u2248 8 / 15 atol=1e-4\n@test value(u1) \u2248 3.5 * 8 / 15 atol=1e-4\n@test value(l1) \u2248 4.5 * 8 / 15 atol=1e-4\n@test dual(l1) \u2248 [0] atol=1e-4\n@test dual(l3) \u2248 [0] atol=1e-4\n\n# TODO: why are these commented out?    #src\n# @test dual(l2) #\u2248 [0] atol=atol       #src\n# @test dual(l4) #\u2248 [0] atol=atol       #src\n", "meta": {"hexsha": "eb572559549c9f9e4d9e200979177011cd9546d9", "size": 2870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/FOBP_example2.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_example2.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_example2.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": 28.137254902, "max_line_length": 84, "alphanum_fraction": 0.6637630662, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.791991413304436}}
{"text": "# ----------\r\n# Geometry Module, providing Geometry convertion function\r\n# ----------\r\n\r\n\r\n# xyz Coordinetes -> r\u03b8z Coordinates\r\nfunction xy_to_polar(ux,uy;Lx=2\u03c0,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\u03b8 = xy_to_polar(ux,uy,grid;Lx=2\u03c0,Ly=Lx,T=Float32);\r\n  return Ur,U\u03b8;\r\nend\r\n\r\nfunction xy_to_polar(ux::Array,uy::Array,grid;Lx=2\u03c0,Ly=Lx,T=Float32)\r\n#=\r\n  Function for converting x-y vector to r-\u03b8 vector, using linear transform\r\n    [x']  =  [cos(\u03b8) -rsin(\u03b8)][r']\r\n    [y']     [sin(\u03b8)  rcos(\u03b8)][\u03b8']\r\n    So e_r =  cos\u03b8 \u0302i + sin\u03b8 \u0302j\r\n       e_\u03b8 = -sin\u03b8 \u0302j + cos\u03b8 \u0302j\r\n=#    \r\n  nx,ny,nz = size(ux);  \r\n  Ur = zeros(T,nx,ny,nz);\r\n  U\u03b8 = zeros(T,nx,ny,nz);\r\n  for j \u2208 1:ny, i \u2208 1:nx\r\n    r = sqrt(grid.x[i]^2+grid.y[j]^2);\r\n    \u03b8 = atan(grid.y[j],grid.x[i]) ;\r\n    \u03b8 = isnan(\u03b8) ? \u03c0/2 : \u03b8;\r\n    sin\u03b8 = sin(\u03b8);\r\n    cos\u03b8 = cos(\u03b8);    \r\n    U\u03b8[i,j,:] .= @. -sin\u03b8*ux[i,j,:] + cos\u03b8*uy[i,j,:];    \r\n    Ur[i,j,:] .= @.  cos\u03b8*ux[i,j,:] + sin\u03b8*uy[i,j,:];    \r\n  end\r\n  return Ur,U\u03b8;\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": "using Distributions\nusing LinearAlgebra\nusing Random\nusing Test\n\nusing EnsembleKalmanProcesses.EnsembleKalmanProcessModule\nusing EnsembleKalmanProcesses.ParameterDistributionStorage\n@testset \"EnsembleKalmanProcessModule\" begin\n\n    # Seed for pseudo-random number generator\n    rng_seed = 42\n    Random.seed!(rng_seed)\n\n    ### Generate data from a linear model: a regression problem with n_par parameters\n    ### and 1 observation of G(u) = A \\times u, where A : R^n_par -> R^n_obs\n    n_obs = 10                  # dimension of synthetic observation from G(u)\n    n_par = 2                  # Number of parameteres\n    u_star = [-1.0, 2.0]          # True parameters\n    noise_level = 0.05            # Defining the observation noise level (std) \n    \u0393y = noise_level^2 * Matrix(I, n_obs, n_obs) # Independent noise for synthetic observations\n    noise = MvNormal(zeros(n_obs), \u0393y)\n    C = [1 -.9; -.9 1]          # Correlation structure for linear operator\n    A = rand(MvNormal(zeros(2,), C), n_obs)'    # Linear operator in R^{n_par x n_obs}\n\n    @test size(A) == (n_obs, n_par)\n\n    #### Define linear model\n    function G(u)\n        A * u\n    end\n\n    y_star = G(u_star)\n    y_obs = y_star .+ rand(noise)\n\n    @test size(y_obs) == (n_obs,)\n\n\n    # sum(y-G)^2 ~ n_obs*noise_level^2\n    @test isapprox(norm(y_obs .- G(u_star))^2 - n_obs * noise_level^2, 0; atol = 0.05)\n\n    #### Define prior information on parameters\n    prior_distns = [Parameterized(Normal(0.0, 0.5)), Parameterized(Normal(3.0, 0.5))]\n    constraints = [[no_constraint()], [no_constraint()]]\n    prior_names = [\"u1\", \"u2\"]\n    prior = ParameterDistribution(prior_distns, constraints, prior_names)\n\n    prior_mean = get_mean(prior)\n\n    # Assuming independence of u1 and u2\n    prior_cov = get_cov(prior) #convert(Array, Diagonal([sqrt(2.), sqrt(2.)]))\n\n\n\n    ###\n    ###  Calibrate: Ensemble Kalman Sampler\n    ###\n    N_ens = 50 # number of ensemble members (NB for @test throws, make different to N_ens)\n    N_iter = 20\n\n    initial_ensemble = EnsembleKalmanProcessModule.construct_initial_ensemble(prior, N_ens; rng_seed = rng_seed)\n    @test size(initial_ensemble) == (n_par, N_ens)\n\n    eksobj =\n        EnsembleKalmanProcessModule.EnsembleKalmanProcess(initial_ensemble, y_obs, \u0393y, Sampler(prior_mean, prior_cov))\n\n    g_ens = G(get_u_final(eksobj))\n    @test size(g_ens) == (n_obs, N_ens)\n    # as the columns of g are the data, this should throw an error\n    g_ens_t = permutedims(g_ens, (2, 1))\n\n    # EKS iterations\n    for i in 1:N_iter\n        params_i = get_u_final(eksobj)\n        g_ens = G(params_i)\n        if i == 1\n            g_ens_t = permutedims(g_ens, (2, 1))\n            @test_throws DimensionMismatch EnsembleKalmanProcessModule.update_ensemble!(eksobj, g_ens_t)\n        end\n\n        EnsembleKalmanProcessModule.update_ensemble!(eksobj, g_ens)\n    end\n    # Plot evolution of the EKS particles\n    eks_final_result = vec(mean(get_u_final(eksobj), dims = 2))\n\n    if TEST_PLOT_OUTPUT\n        gr()\n        p = plot(\n            get_u_prior(eksobj)[1, :],\n            get_u_prior(eksobj)[2, :],\n            seriestype = :scatter,\n            label = \"Initial ensemble\",\n        )\n        plot!(get_u_final(eksobj)[1, :], get_u_final(eksobj)[2, :], seriestype = :scatter, label = \"Final ensemble\")\n        plot!(\n            [u_star[1]],\n            xaxis = \"u1\",\n            yaxis = \"u2\",\n            seriestype = \"vline\",\n            linestyle = :dash,\n            linecolor = :red,\n            label = :none,\n        )\n        plot!([u_star[2]], seriestype = \"hline\", linestyle = :dash, linecolor = :red, label = :none)\n        savefig(p, \"EKS_test.png\")\n    end\n\n\n    ###\n    ###  Calibrate: Ensemble Kalman Inversion\n    ###\n\n    #N_ens = 40 # number of ensemble members\n    # We will try to compare the EKI and EKS results, therefore we need comparable timesteps and iterations\n    #N_iter = 7 # number of EKI iterations\n    \u0394_vec = eksobj.\u0394t[2:end]\n\n    ekiobj = EnsembleKalmanProcessModule.EnsembleKalmanProcess(initial_ensemble, y_obs, \u0393y, Inversion())\n\n    # some checks \n    g_ens = G(get_u_final(ekiobj))\n    @test size(g_ens) == (n_obs, N_ens)\n    # as the columns of g are the data, this should throw an error\n    g_ens_t = permutedims(g_ens, (2, 1))\n    @test_throws DimensionMismatch find_ekp_stepsize(ekiobj, g_ens_t)\n    \u0394 = find_ekp_stepsize(ekiobj, g_ens)\n    # huge collapse for linear problem so should find timestep should < 1\n    @test \u0394 < 1\n    # NOTE We don't use this info, this is just for the test.\n\n    # EKI iterations\n    params_i_vec = []\n    g_ens_vec = []\n    for i in 1:N_iter\n        params_i = get_u_final(ekiobj)\n        push!(params_i_vec, params_i)\n        g_ens = G(params_i)\n        push!(g_ens_vec, g_ens)\n        if i == 1\n            g_ens_t = permutedims(g_ens, (2, 1))\n            @test_throws DimensionMismatch EnsembleKalmanProcessModule.update_ensemble!(ekiobj, g_ens_t)\n        end\n        \u0394 = \u0394_vec[i] # use the same timesteps as EKS (EKI is more stable, so this is fine to do)\n        EnsembleKalmanProcessModule.update_ensemble!(ekiobj, g_ens, \u0394t_new = \u0394)\n\n    end\n    @test isapprox(ekiobj.\u0394t - eksobj.\u0394t, zeros(N_iter + 1))\n\n    push!(params_i_vec, get_u_final(ekiobj))\n\n    @test get_u_prior(ekiobj) == params_i_vec[1]\n    @test get_u(ekiobj) == params_i_vec\n    @test get_g(ekiobj) == g_ens_vec\n    @test get_g_final(ekiobj) == g_ens_vec[end]\n    @test get_error(ekiobj) == ekiobj.err\n\n    # EKI results: Test if ensemble has collapsed toward the true parameter \n    # values\n    eki_final_result = vec(mean(get_u_final(ekiobj), dims = 2))\n\n    # kind of arbitrary tolerance here,\n    @test norm(u_star - eki_final_result) < 0.1\n\n    # Plot evolution of the EKI particles\n    #eki_final_result = vec(mean(get_u_final(ekiobj), dims = 2))\n    if TEST_PLOT_OUTPUT\n        gr()\n        p = plot(\n            get_u_prior(ekiobj)[1, :],\n            get_u_prior(ekiobj)[2, :],\n            seriestype = :scatter,\n            label = \"Initial ensemble\",\n        )\n        plot!(get_u_final(ekiobj)[1, :], get_u_final(ekiobj)[2, :], seriestype = :scatter, label = \"Final ensemble\")\n        plot!(\n            [u_star[1]],\n            xaxis = \"u1\",\n            yaxis = \"u2\",\n            seriestype = \"vline\",\n            linestyle = :dash,\n            linecolor = :red,\n            label = :none,\n        )\n        plot!([u_star[2]], seriestype = \"hline\", linestyle = :dash, linecolor = :red, label = :none)\n        savefig(p, \"EKI_test.png\")\n    end\n\n\n    posterior_cov_inv = (A' * (\u0393y \\ A) + 1 * Matrix(I, n_par, n_par) / prior_cov)\n    ols_mean = (A' * (\u0393y \\ A)) \\ (A' * (\u0393y \\ y_obs))\n    posterior_mean = posterior_cov_inv \\ ((A' * (\u0393y \\ A)) * ols_mean + (prior_cov \\ prior_mean))\n\n    #### This tests correspond to:\n    # NOTE THESE ARE VERY SENSITIVE TO THE CORRESPONDING N_iter\n    # EKI provides a solution closer to the ordinary Least Squares estimate\n    @test norm(ols_mean - eki_final_result) < norm(ols_mean - eks_final_result)\n    # EKS provides a solution closer to the posterior mean\n    @test norm(posterior_mean - eks_final_result) < norm(posterior_mean - eki_final_result)\n\n    ##### I expect this test to make sense:\n    # In words: the ensemble covariance is still a bit ill-dispersed since the\n    # algorithm employed still does not include the correction term for finite-sized\n    # ensembles.\n    @test abs(sum(diag(posterior_cov_inv \\ cov(get_u_final(eksobj), dims = 2))) - n_par) > 1e-5\n\n\n\n    ###\n    ###  Calibrate: Unscented Kalman Inversion\n    ###\n\n    N_iter = 20 # number of UKI iterations\n    \u03b1_reg = 1.0\n    update_freq = 0\n    process = Unscented(prior_mean, prior_cov; \u03b1_reg = \u03b1_reg, update_freq = update_freq)\n    ukiobj = EnsembleKalmanProcessModule.EnsembleKalmanProcess(y_star, \u0393y, process)\n\n    # UKI iterations\n    params_i_vec = []\n    g_ens_vec = []\n    for i in 1:N_iter\n        params_i = get_u_final(ukiobj)\n        push!(params_i_vec, params_i)\n        g_ens = G(params_i)\n        push!(g_ens_vec, g_ens)\n        if i == 1\n            g_ens_t = permutedims(g_ens, (2, 1))\n            @test_throws DimensionMismatch EnsembleKalmanProcessModule.update_ensemble!(ukiobj, g_ens_t)\n        end\n        EnsembleKalmanProcessModule.update_ensemble!(ukiobj, g_ens)\n    end\n    push!(params_i_vec, get_u_final(ukiobj))\n\n    @test get_u_prior(ukiobj) == params_i_vec[1]\n    @test get_u(ukiobj) == params_i_vec\n    @test get_g(ukiobj) == g_ens_vec\n    @test get_g_final(ukiobj) == g_ens_vec[end]\n    @test get_error(ukiobj) == ukiobj.err\n\n    # UKI results: Test if ensemble has collapsed toward the true parameter \n    # values\n    uki_final_result = get_u_mean_final(ukiobj)\n    @test norm(u_star - uki_final_result) < 0.5\n\n    if TEST_PLOT_OUTPUT\n        gr()\n        \u03b8_mean_arr = hcat(ukiobj.process.u_mean...)\n        N_\u03b8 = length(ukiobj.process.u_mean[1])\n        \u03b8\u03b8_std_arr = zeros(Float64, (N_\u03b8, N_iter + 1))\n        for i in 1:(N_iter + 1)\n            for j in 1:N_\u03b8\n                \u03b8\u03b8_std_arr[j, i] = sqrt(ukiobj.process.uu_cov[i][j, j])\n            end\n        end\n\n        ites = Array(LinRange(1, N_iter + 1, N_iter + 1))\n        p = plot(ites, grid = false, \u03b8_mean_arr[1, :], yerror = 3.0 * \u03b8\u03b8_std_arr[1, :], label = \"u1\")\n        plot!(ites, fill(u_star[1], N_iter + 1), linestyle = :dash, linecolor = :grey, label = :none)\n        plot!(ites, grid = false, \u03b8_mean_arr[2, :], yerror = 3.0 * \u03b8\u03b8_std_arr[2, :], label = \"u2\", xaxis = \"Iterations\")\n        plot!(ites, fill(u_star[2], N_iter + 1), linestyle = :dash, linecolor = :grey, label = :none)\n        savefig(p, \"UKI_test.png\")\n    end\n\n    ### Generate data from G\u2081(u) with a sparse u\n    n_obs = 1                  # Number of synthetic observations from G\u2081(u)\n    n_par = 2                  # Number of parameteres\n    u_star = [1.0, 0.0]          # True parameters\n    noise_level = 1e-3            # Defining the observation noise level\n    \u0393y = noise_level * Matrix(I, n_obs, n_obs) # Independent noise for synthetic observations\n    noise = MvNormal(zeros(n_obs), \u0393y)\n\n    #### Define model\n    function G\u2081(u)\n        [sqrt((u[1] - u_star[1])^2 + (u[2] - u_star[2])^2)]\n    end\n\n    y_star = G\u2081(u_star)\n    y_obs = y_star + rand(noise)\n\n    @test size(y_star) == (n_obs,)\n\n    #### Define prior information on parameters\n    prior_distributions = [Parameterized(Normal(0, 2)), Parameterized(Normal(0, 2))]\n    constraints = [[no_constraint()], [no_constraint()]]\n    prior_names = [\"u1\", \"u2\"]\n    prior = ParameterDistribution(prior_distns, constraints, prior_names)\n\n    ###\n    ###  Calibrate (4): Sparse Ensemble Kalman Inversion\n    ###\n\n    N_ens = 20 # number of ensemble members\n    N_iter = 5 # number of EKI iterations\n    initial_ensemble = EnsembleKalmanProcessModule.construct_initial_ensemble(prior, N_ens; rng_seed = rng_seed)\n    @test size(initial_ensemble) == (n_par, N_ens)\n\n    for (threshold_eki, threshold_value, test_name) in ((false, 1e-2, \"test\"), (true, 1e-2, \"test_thresholded\"))\n\n        # Sparse EKI parameters\n        \u03b3 = 1.0\n        reg = 1e-4\n        uc_idx = [1, 2]\n\n        process = SparseInversion(\u03b3, threshold_eki, threshold_value, reg, uc_idx)\n\n        ekiobj = EnsembleKalmanProcessModule.EnsembleKalmanProcess(initial_ensemble, y_obs, \u0393y, process)\n\n        # EKI iterations\n        params_i_vec = []\n        g_ens_vec = []\n        for i in 1:N_iter\n            params_i = get_u_final(ekiobj)\n            push!(params_i_vec, params_i)\n            g_ens = hcat([G\u2081(params_i[:, i]) for i in 1:N_ens]...)\n            push!(g_ens_vec, g_ens)\n            if i == 1\n                g_ens_t = permutedims(g_ens, (2, 1))\n                @test_throws DimensionMismatch EnsembleKalmanProcessModule.update_ensemble!(ekiobj, g_ens_t)\n                EnsembleKalmanProcessModule.update_ensemble!(ekiobj, g_ens)\n            else\n                EnsembleKalmanProcessModule.update_ensemble!(ekiobj, g_ens, \u0394t_new = ekiobj.\u0394t[1])\n            end\n        end\n        push!(params_i_vec, get_u_final(ekiobj))\n\n        @test get_u_prior(ekiobj) == params_i_vec[1]\n        @test get_u(ekiobj) == params_i_vec\n        @test get_g(ekiobj) == g_ens_vec\n        @test get_g_final(ekiobj) == g_ens_vec[end]\n        @test get_error(ekiobj) == ekiobj.err\n\n        # EKI results: Test if ensemble has collapsed toward the true parameter\n        # values\n        eki_final_result = vec(mean(get_u_final(ekiobj), dims = 2))\n        @test norm(u_star - eki_final_result) < 0.1\n        @test sum(eki_final_result .> 0.05) < size(eki_final_result)[1]\n\n        # Plot evolution of the EKI particles\n        eki_final_result = vec(mean(get_u_final(ekiobj), dims = 2))\n\n        if TEST_PLOT_OUTPUT\n            gr()\n            p = plot(get_u_prior(ekiobj)[1, :], get_u_prior(ekiobj)[2, :], seriestype = :scatter)\n            plot!(get_u_final(ekiobj)[1, :], get_u_final(ekiobj)[2, :], seriestype = :scatter)\n            plot!([u_star[1]], xaxis = \"u1\", yaxis = \"u2\", seriestype = \"vline\", linestyle = :dash, linecolor = :red)\n            plot!([u_star[2]], seriestype = \"hline\", linestyle = :dash, linecolor = :red)\n            savefig(p, string(\"SparseEKI_\", test_name, \".png\"))\n        end\n    end\nend\n", "meta": {"hexsha": "a8cf6c55fec71cd121ac102f489a036075826480", "size": 13165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/EnsembleKalmanProcessModule/runtests.jl", "max_stars_repo_name": "CliMA/EnsembleKalmanProcesses.jl", "max_stars_repo_head_hexsha": "f5dc42bfe5903ce211e6c59bc5816c20942a97a9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2021-03-02T08:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T18:50:04.000Z", "max_issues_repo_path": "test/EnsembleKalmanProcessModule/runtests.jl", "max_issues_repo_name": "CliMA/EnsembleKalmanProcesses.jl", "max_issues_repo_head_hexsha": "f5dc42bfe5903ce211e6c59bc5816c20942a97a9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 129, "max_issues_repo_issues_event_min_datetime": "2021-02-24T17:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:38:35.000Z", "max_forks_repo_path": "test/EnsembleKalmanProcessModule/runtests.jl", "max_forks_repo_name": "CliMA/EnsembleKalmanProcesses.jl", "max_forks_repo_head_hexsha": "f5dc42bfe5903ce211e6c59bc5816c20942a97a9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-05-21T20:46:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T20:53:46.000Z", "avg_line_length": 37.6142857143, "max_line_length": 120, "alphanum_fraction": 0.6225598177, "num_tokens": 3906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8418256393148981, "lm_q1q2_score": 0.7919809279380238}}
{"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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2e9ce2a9-217e-4910-b6ce-d174f2f2668e\nusing PlutoUI; PlutoUI.TableOfContents()\n\n# \u2554\u2550\u2561 78bdd11d-b6f9-4ba6-8b2e-6189c4005bf1\nmd\"# Ridge Regression (L2 Regularization)\n\"\n\n# \u2554\u2550\u2561 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 \u03b2\u2080. 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 \u03b2\u2081 and \u03b2\u2080 towards zero until there is not change anymore.\n\"\n\n# \u2554\u2550\u2561 8bd483cc-f490-11eb-38a1-b342dd2551fd\nbegin\n    function ridge_regression(x, y, \u03bb)\n       \u03b2\u2081 = (mean(x .* y) - mean(x) * mean(y)/(1 + \u03bb))/\n\t\t    (mean(x.^2) - mean(x)^2/(1 + \u03bb) + \u03bb)\n       \u03b2\u2080 = (mean(y) - \u03b2\u2081 * mean(x))/(1 + \u03bb)\n       (\u03b2\u2080 = \u03b2\u2080, \u03b2\u2081 = \u03b2\u2081)\n    end\n    function update\u03b2\u2080(x\u0304, y\u0304, \u03b2\u2081, l)\n        tmp = y\u0304 - \u03b2\u2081 * x\u0304\n        abs(tmp) > l ? tmp - sign(tmp) * l : 0.\n    end\n    function update\u03b2\u2081(x\u0304, y\u0304, x2, xy, \u03b2\u2080, l)\n        tmp = (x\u0304 * y\u0304 - xy - x\u0304 * sign(\u03b2\u2080) * l)\n        abs(tmp) > l ? (tmp - sign(tmp) * l)/(x\u0304^2 - x2) : 0\n    end\n    function lasso(x, y, \u03bb)\n        x\u0304 = mean(x)\n        y\u0304 = mean(y)\n        x2 = mean(x.^2)\n        xy = mean(x .* y)\n        \u03b2\u2081 = (x\u0304 * y\u0304 - xy)/(x\u0304^2 - x2)\n        \u03b2\u2080 = y\u0304 - \u03b2\u2081 * x\u0304\n        \u03b2\u2080old, \u03b2\u2081old = zero(\u03b2\u2080), zero(\u03b2\u2081)\n        while \u03b2\u2080old != \u03b2\u2080 || \u03b2\u2081old != \u03b2\u2081\n            \u03b2\u2080old, \u03b2\u2081old = \u03b2\u2080, \u03b2\u2081\n            \u03b2\u2081 = update\u03b2\u2081(x\u0304, y\u0304, x2, xy, \u03b2\u2080, \u03bb)\n            \u03b2\u2080 = update\u03b2\u2080(x\u0304, y\u0304, \u03b2\u2081, \u03bb)\n        end\n       (\u03b2\u2080 = \u03b2\u2080, \u03b2\u2081 = \u03b2\u2081)\n    end\nend;\n\n# \u2554\u2550\u2561 3a71618b-0d74-4480-b87b-c6ba87363b5d\nmd\"We generate now some data to observe the effect of regularization when fitting this data.\"\n\n# \u2554\u2550\u2561 9e1e8284-a8c1-47a9-83d0-2d8fbd8ce005\nn = 30; x = rand(n); y = 2.2x .+ .3 .+ .2randn(n);\n\n# \u2554\u2550\u2561 1009e251-59af-4f1a-9d0a-e96f4b696cad\nmd\"\u03bb\u2082 = $(@bind \u03bb\u2082 Slider(0:.01:5, show_value = true))\"\n\n# \u2554\u2550\u2561 50ac0b07-ffee-40c3-843e-984b3c628282\nl2coefs = ridge_regression(x, y, \u03bb\u2082)\n\n# \u2554\u2550\u2561 58746554-ca5a-4e8e-97e5-587a9c2aa44c\nlet r = \u03bb\u2082 == 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.\u03b2\u2080 + x * l2coefs.\u03b2\u2081, w = 3, label = \"ridge regression\")\n    p2 = contour(-1:.1:3, -1:.1:3, (\u03b2\u2080, \u03b2\u2081) -> mean((\u03b2\u2080 .+ \u03b2\u2081*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\u03c0,\n          fill = (0, ccol), label = \"constraint\", color = ccol)\n    plot!(path[1, :], path[2, :], label = \"path\", color = :blue, w = 3)\n    scatter!([l2coefs.\u03b2\u2080], [l2coefs.\u03b2\u2081], label = \"current fit\", markersize = 6, color = :red)\n    p3 = plot(0:.01:5, path[1, :], label = \"\u03b2\u2080\", xlabel = \"\u03bb\u2082\", ylabel = \"\")\n    plot!(0:.01:5, path[2, :], label = \"\u03b2\u2081\", ylims = (0, 2.4))\n    scatter!([\u03bb\u2082], [l2coefs.\u03b2\u2080], label = nothing, markersize = 6, color = :red)\n    scatter!([\u03bb\u2082], [l2coefs.\u03b2\u2081], label = nothing, markersize = 6, color = :red)\n    p4 = contour(-1:.1:3, -1:.1:3, (\u03b2\u2080, \u03b2\u2081) -> mean((\u03b2\u2080 .+ \u03b2\u2081*x .- y).^2) + \u03bb\u2082 * (\u03b2\u2080^2 + \u03b2\u2081^2),\n                 label = \"loss\", title = \"regularized loss\",\n                 levels = 100, aspect_ratio = 1, ylims = (-1, 3), xlims = (-1, 3))\n    scatter!([l2coefs.\u03b2\u2080], [l2coefs.\u03b2\u2081], markersize = 6, label = nothing, color = :red)\n    plot(p1, p4, p3, p2,\n         layout = (2, 2), size = (700, 600), cbar = false)\nend\n\n# \u2554\u2550\u2561 f43a82e2-1145-426d-8e0e-5363d1c38ccf\nmd\"# Lasso (L1 Regression)\"\n\n# \u2554\u2550\u2561 ff7cc2bf-2a38-46d2-8d11-529159b08c82\nmd\"\u03bb\u2081 = $(@bind \u03bb\u2081 Slider(0:.01:1, show_value = true))\"\n\n# \u2554\u2550\u2561 4841f9ba-f3d2-4c65-9225-bc8d0c0a9478\nl1coefs = lasso(x, y, \u03bb\u2081)\n\n# \u2554\u2550\u2561 ed2b7969-79cd-43c8-bcdb-34dab89c2cb0\nlet r = \u03bb\u2081 == 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.\u03b2\u2080 + x * l1coefs.\u03b2\u2081, w = 3, label = \"lasso\")\n    p2 = contour(-1:.1:3, -1:.1:3, (\u03b2\u2080, \u03b2\u2081) -> mean((\u03b2\u2080 .+ \u03b2\u2081*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.\u03b2\u2080], [l1coefs.\u03b2\u2081], label = \"current fit\", markersize = 6,\n\t\t     color = :red)\n    p3 = plot(0:.01:1, path[1, :], label = \"\u03b2\u2080\", xlabel = \"\u03bb\u2081\", ylabel = \"\")\n    plot!(0:.01:1, path[2, :], label = \"\u03b2\u2081\", ylims = (0, 2.4))\n    scatter!([\u03bb\u2081], [l1coefs.\u03b2\u2080], label = nothing, markersize = 6, color = :red)\n    scatter!([\u03bb\u2081], [l1coefs.\u03b2\u2081], label = nothing, markersize = 6, color = :red)\n    p4 = contour(-1:.1:3, -1:.1:3, (\u03b2\u2080, \u03b2\u2081) -> mean((\u03b2\u2080 .+ \u03b2\u2081*x .- y).^2)/2 + \u03bb\u2081 * (abs(\u03b2\u2080) + abs(\u03b2\u2081)),\n                 label = \"loss\", title = \"regularized loss\",\n                 levels = 100, aspect_ratio = 1, ylims = (-1, 3), xlims = (-1, 3))\n    scatter!([l1coefs.\u03b2\u2080], [l1coefs.\u03b2\u2081], 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1dae5378-f3eb-4598-a060-445bfd8afe5e\nmd\"Let us check that we get indeed the same result with our custom method.\"\n\n# \u2554\u2550\u2561 15a85810-ccbd-4aa3-98a5-fdcf68c97adb\nridge_regression(x, y, 3.82)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2ba5b965-1dce-4773-b6eb-fd838876674d\nlasso(x, y, .1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a54e3439-69b8-41c8-bfe0-4575795fb9b8\nmd\"\u03bb = $(lambda == -14 ? 0 : 10.0^lambda)\"\n\n# \u2554\u2550\u2561 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 \u2248 $(round(mean((pred .- f.(grid)).^2), sigdigits = 3))\")])\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f5057d4a-1103-4728-becc-287d93d682ba\nplot(self_tuning_mach)\n\n# \u2554\u2550\u2561 bd54bfcd-f682-4b74-8a44-35463d421491\nreport(self_tuning_mach)\n\n# \u2554\u2550\u2561 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 \u2248 $(round(mean((pred .- f.(grid)).^2), sigdigits = 3))\")])\nend\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1fa932c1-ce29-40ca-a8dc-e636aa2ecf66\nweather = CSV.read(joinpath(@__DIR__, \"..\", \"data\", \"weather2015-2018.csv\"), DataFrame);\n\n# \u2554\u2550\u2561 470dc7f4-04a9-4253-8125-9112778021eb\nimport GLMNet: glmnet\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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(\u03bb)\", size = (700, 400))\n    gr()\n    p\nend\n\n# \u2554\u2550\u2561 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(\u03bb)\")\n    plot(p1, p2, layout = (2, 1), legend = false)\nend\n\n# \u2554\u2550\u2561 c9ed011c-8d36-4926-9ec4-84be3b4878d7\nscatter(weather_input.BER_wind_peak, weather_output)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e04c5e8a-15f8-44a8-845d-60acaf795813\nMLCourse.list_notebooks(@__FILE__)\n\n# \u2554\u2550\u2561 c48dff95-8028-4e97-8ec6-705ea2b9c72e\nMLCourse.footer()\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25002e9ce2a9-217e-4910-b6ce-d174f2f2668e\n# \u2560\u2550150d58e7-0e73-4b36-836c-d81eef531a9c\n# \u255f\u250078bdd11d-b6f9-4ba6-8b2e-6189c4005bf1\n# \u255f\u250064b9cfa0-99f7-439b-b70e-f9266754ff74\n# \u2560\u25508bd483cc-f490-11eb-38a1-b342dd2551fd\n# \u255f\u25003a71618b-0d74-4480-b87b-c6ba87363b5d\n# \u2560\u25509e1e8284-a8c1-47a9-83d0-2d8fbd8ce005\n# \u255f\u25001009e251-59af-4f1a-9d0a-e96f4b696cad\n# \u2560\u255050ac0b07-ffee-40c3-843e-984b3c628282\n# \u255f\u250058746554-ca5a-4e8e-97e5-587a9c2aa44c\n# \u255f\u2500f43a82e2-1145-426d-8e0e-5363d1c38ccf\n# \u255f\u2500ff7cc2bf-2a38-46d2-8d11-529159b08c82\n# \u2560\u25504841f9ba-f3d2-4c65-9225-bc8d0c0a9478\n# \u255f\u2500ed2b7969-79cd-43c8-bcdb-34dab89c2cb0\n# \u255f\u25004c3c816c-e901-4931-a27c-632b60291ad7\n# \u2560\u2550c1033416-334e-4b0e-b81e-6f9137402730\n# \u255f\u25001dae5378-f3eb-4598-a060-445bfd8afe5e\n# \u2560\u255015a85810-ccbd-4aa3-98a5-fdcf68c97adb\n# \u2560\u25500429acfe-d31e-427a-96d9-deddfa2c30f8\n# \u2560\u25502ba5b965-1dce-4773-b6eb-fd838876674d\n# \u255f\u25006c87eb35-ddb3-44a3-b4ae-77a371e28960\n# \u255f\u2500ca394b88-06dc-4188-884a-50d7c180aa33\n# \u2560\u2550b45a9739-0f81-4c0c-a93b-434a5af91490\n# \u255f\u25003d50111b-3a08-4a41-96ce-d77a8e37275d\n# \u255f\u2500a54e3439-69b8-41c8-bfe0-4575795fb9b8\n# \u255f\u2500bdbf0dfd-8da5-4e54-89c4-ef4d6b3796ce\n# \u2560\u2550fe2fe54f-0163-4f5d-9fd1-3d1aa3580875\n# \u2560\u2550f5057d4a-1103-4728-becc-287d93d682ba\n# \u2560\u2550bd54bfcd-f682-4b74-8a44-35463d421491\n# \u255f\u2500596fd0f2-eee0-46ca-a203-e7cbac6f9788\n# \u255f\u25008e170a5a-9c46-413e-895d-796e178b69df\n# \u2560\u25508e542a48-ed28-4297-b2e8-d6a755a5fdf9\n# \u255f\u2500c5ef5d4e-200d-46d9-86fa-50af1896a6c3\n# \u2560\u2550d956613e-db32-488c-8ebb-fd61dfa31e59\n# \u2560\u2550552f14fc-06c7-4c2a-9515-e64f28828b70\n# \u2560\u2550ef701511-db7e-4dc0-8d31-ea14471943ab\n# \u255f\u250019bdd76c-4131-422d-983e-1b29cd9edd30\n# \u255f\u250013655a50-fbbb-46c7-bdf7-ed5644646966\n# \u2560\u25501fa932c1-ce29-40ca-a8dc-e636aa2ecf66\n# \u2560\u2550470dc7f4-04a9-4253-8125-9112778021eb\n# \u2560\u2550ecf80b6a-1946-46fd-b1b4-bcbe91848e3c\n# \u255f\u25004652a904-5edb-463c-a046-5c5d378f7cca\n# \u255f\u250040bb385f-1cbd-4555-a8ab-544a67f33595\n# \u2560\u2550c9ed011c-8d36-4926-9ec4-84be3b4878d7\n# \u255f\u25008262b948-6d54-4348-87d1-4c762c74db30\n# \u255f\u2500e04c5e8a-15f8-44a8-845d-60acaf795813\n# \u255f\u2500c48dff95-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": "# Beta distribution\n\nexport Beta\n\n@parameterized Beta(\u03b1,\u03b2) \u2243 Lebesgue(\ud835\udd40)\n\n@kwstruct Beta(\u03b1, \u03b2)\n\n@kwalias Beta [\n    a     => \u03b1\n    alpha => \u03b1\n    b     => \u03b2\n    beta  => \u03b2\n]\n\nTV.as(::Beta) = as\ud835\udd40\n\nfunction logdensity(d::Beta{(:\u03b1, :\u03b2)}, x)\n    return (d.\u03b1 - 1) * log(x) + (d.\u03b2 - 1) * log(1 - x) - logbeta(d.\u03b1, d.\u03b2)\nend\n\nBase.rand(rng::AbstractRNG, T::Type, \u03bc::Beta) = rand(rng, Dists.Beta(\u03bc.\u03b1, \u03bc.\u03b2))\n\ndistproxy(d::Beta{(:\u03b1, :\u03b2)}) = Dists.Beta(d.\u03b1, d.\u03b2)\n\nasparams(::Type{<:Beta}, ::Val{:\u03b1}) = as\u211d\u208a\nasparams(::Type{<:Beta}, ::Val{:\u03b2}) = as\u211d\u208a\n", "meta": {"hexsha": "c9c8fc855b1324249a599a2988602694e72a8e85", "size": 538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parameterized/beta.jl", "max_stars_repo_name": "jw3126/MeasureTheory.jl", "max_stars_repo_head_hexsha": "419d2f2fc3cb27c9b1d969d2e05022f3a4a01f66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parameterized/beta.jl", "max_issues_repo_name": "jw3126/MeasureTheory.jl", "max_issues_repo_head_hexsha": "419d2f2fc3cb27c9b1d969d2e05022f3a4a01f66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parameterized/beta.jl", "max_forks_repo_name": "jw3126/MeasureTheory.jl", "max_forks_repo_head_hexsha": "419d2f2fc3cb27c9b1d969d2e05022f3a4a01f66", "max_forks_repo_licenses": ["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.2142857143, "max_line_length": 79, "alphanum_fraction": 0.5446096654, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.791901096925713}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 0d696b90-14b9-11eb-19c6-7110e9eded9e\nusing PotentialFlow\n\n# \u2554\u2550\u2561 40e53300-14b9-11eb-28ca-c39ecf8c05ef\nusing Plots\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 27ebaaf0-14be-11eb-3b42-d3c031377d61\nbegin\n\t\n\tv2 = Vortex.Point(0.0, 2)\n    \n\t\u03c8 = streamfunction(Z,v2)\n\t\n\tcontour(X, Y, \u03c8,\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# \u2554\u2550\u2561 2e843420-1538-11eb-14b2-d9ab38fa091b\nbegin\n\t\n\tvs = Vortex.Point.(rand(ComplexF64, 10), \u03c0*rand(10))\n    fs = Freestreams.Freestream(rand(ComplexF64))\n\t\n\t\u03c8s = streamfunction(Z,(vs,fs))\n\t\n\tcontour(X, Y, \u03c8s,\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# \u2554\u2550\u2561 e0cf3580-1538-11eb-1ba8-1baff87ba9e1\nmd\"\"\" \n### Flow over a cylinder \n\"\"\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u25500d696b90-14b9-11eb-19c6-7110e9eded9e\n# \u2560\u255040e53300-14b9-11eb-28ca-c39ecf8c05ef\n# \u2560\u255059e4bc40-14b9-11eb-3670-cdc8fa8f0ded\n# \u2560\u255027ebaaf0-14be-11eb-3b42-d3c031377d61\n# \u2560\u25502e843420-1538-11eb-14b2-d9ab38fa091b\n# \u255f\u2500e0cf3580-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": "D = [\n\t-5  -9  -9   7   0;\n\t 7   0   4   0   9;\n\t 8   0   5   4  -6\n]\n\n\n# when data is representad as a vector\nY = [\n    -1;\n     0;\n     5\n]\n\nX = matching_pursuit(Y, D)\n@test norm(Y-D*X) < 1e-6\n\n\n# when data is representad as a matrix\nY = [\n    -1  2;\n     0  3;\n     5 -5\n]\n\nX = matching_pursuit(Y, D)\n@test norm(Y-D*X) < 1e-6\n\n\n# when max_iter < 0\n@test_throws ArgumentError matching_pursuit(Y, D; max_iter = 0)\n@test_throws ArgumentError matching_pursuit(Y, D; max_iter = -1)\n\n\n# when tolerance < 0\n@test_throws ArgumentError matching_pursuit(Y, D, tolerance = 0.)\n@test_throws ArgumentError matching_pursuit(Y, D; tolerance = -1.0)\n\n\n# when dimensions of data and atoms do not match\n\nY = [\n     2;\n    -5\n]\n\n@test_throws ArgumentError matching_pursuit(Y, D)\n", "meta": {"hexsha": "1c2b7a96722f926ad180df1832c74e07bdc66430", "size": 763, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 15.8958333333, "max_line_length": 67, "alphanum_fraction": 0.6159895151, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7918873465246975}}
{"text": "\n\"\"\"\nProblema de asignaci\u00f3n. (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\u00f3n 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\u00f3n lineal con enteros. Escriba una funci\u00f3n 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#   \u0398(z, \u03c9) = \u03a3\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    \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0    \u03a9::Matrix{ComplexF64};\n    \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0    eps::Float64=1e-8,\n    \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0    derivs::Vector{Vector{ComplexF64}}=Vector{ComplexF64}[],\n    \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0    accuracy_radius::Float64=5.)::Vector{ComplexF64}\n\nReturn the value of the oscillatory part of the Riemann theta function for \u03a9 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                          \u03a9::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.(\u03a9)\n    Y = imag.(\u03a9)\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    \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0    \u03a9::Matrix{ComplexF64})::Vector{Float64}\n\nReturn the value of the exponential part of the Riemann theta function for \u03a9 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                          \u03a9::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.(\u03a9))\n\n    # apply the quadratic form to each vector in z\n    map(y -> \u03c0 * dot(y, Yinv * y), y)\nend\n\n\n\"\"\"\n     riemanntheta(zs::Vector{Vector{ComplexF64}},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u03a9::Matrix{ComplexF64};\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0eps::Float64=1e-8,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0derivs::Vector{Vector{ComplexF64}}=Vector{ComplexF64}[],\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0accuracy_radius::Float64=5.)::Vector{ComplexF64}\n\nReturn the value of the Riemann theta function for \u03a9 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                      \u03a9::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, \u03a9)\n    v = oscillatory_part(zs, \u03a9, 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 \u03b1 = sqrt(2/3)\nconst \u03b2 = 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-\u03b1*h,m-X2*h,m-\u03b2*h,m-X3*h,m,m+X3*h,m+\u03b2*h,m+X2*h,m+\u03b1*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-\u03b1*h\n    ml = m-\u03b2*h\n    mr = m+\u03b2*h\n    mrr = m+\u03b1*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 \u2248(_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    \u03b1, \u03b2 = d.alpha, d.beta\n    (x^(\u03b1 - 1.0) * (1.0 + x)^(-(\u03b1 + \u03b2))) / beta(\u03b1, \u03b2)\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    \u03b1, \u03b2 = d.alpha, d.beta\n    \u03b2 > 3.0 ? (2.0 * (2.0 * \u03b1 + \u03b2 - 1))/(\u03b2 - 3.0) * sqrt((\u03b2 - 2.0)/(\u03b1 * (\u03b1 + \u03b2 - 1.0))) : NaN\nend\n\nfunction var(d::BetaPrime)\n    \u03b1, \u03b2 = d.alpha, d.beta\n    \u03b2 > 2.0 ? (\u03b1 * (\u03b1 + \u03b2 - 1.0)) / ((\u03b2 - 2.0) * (\u03b2 - 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 \u00d7 7\n15 = 3 \u00d7 5\n\nThe first three consecutive numbers to have three distinct prime factors are:\n\n644 = 2\u00b2 \u00d7 7 \u00d7 23\n645 = 3 \u00d7 5 \u00d7 43\n646 = 2 \u00d7 17 \u00d7 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`\u03b2` : 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                          \u03b2::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        \u03c3 = similar(w)\n    end\n\n    # == set Tw[i] = max_c { u(c) + \u03b2 E w(f(y  - c) z)} == #\n    for (i, y) in enumerate(grid)\n        objective(c) = - u(c) - \u03b2 * mean(w_func.(f(y - c) .* shocks))\n        res = optimize(objective, 1e-10, y)\n\n        if compute_policy\n            \u03c3[i] = res.minimizer\n        end\n        Tw[i] = - res.minimum\n    end\n\n    if compute_policy\n        return Tw, \u03c3\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!, \u2207softmax, \u2207softmax!,\n       logsoftmax, logsoftmax!, \u2207logsoftmax, \u2207logsoftmax!\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 \u2207softmax!(out::AbstractVecOrMat, \u0394::AbstractVecOrMat, xs::AbstractVecOrMat)\n    sf = softmax(xs)\n    out .= sf .* (\u0394 .- sum(\u0394 .* sf, dims = 1))\nend\nfunction \u2207softmax(\u0394, xs; dims=1)\n    sf = softmax(xs, dims=dims)\n    sf .* (\u0394 .- sum(\u0394 .* sf, dims=dims))\nend\n\u2207softmax!(\u0394, xs) = \u2207softmax!(\u0394, \u0394, 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\u2207logsoftmax(\u0394, xs; dims=1) = \u0394 .- sum(\u0394, dims=dims) .* softmax(xs, dims=dims)\n\u2207logsoftmax!(\u0394, xs) = \u2207softmax!(\u0394, \u0394, 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 IntroLinearAlgebra\nusing Test\n\n# write your own tests here\n@test rowswitch([1 2 3 4; 5 6 7 8],1,2) == [5 6 7 8; 1 2 3 4]\n\n@test rowscale([1 2 3; 4 5 6],2,-3//2) == [1 2 3; -6 -15//2 -9]\n\n@test rowadd([0.3 0.6; \u03c0 2\u03c0],2,1,-\u03c0/0.3) == [0.3 0.6; 0.0 0.0]\n\n@test rref([1 2 3 4 5; 6 7 8 9 10]) == [1 0 -1 -2 -3; 0 1 2 3 4]\n\n@test length(rref(randn(8,8))) == 64\n\nA = [1//1 2 3 4;\n        5 6 7 8]\n\nzerooutbelow!(A,1,1)\n\n@test A == [1 2 3 4; 0 -4 -8 -12]\n\n", "meta": {"hexsha": "064efc29983a76973a764e90f8fb06013a784d57", "size": 453, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 20.5909090909, "max_line_length": 64, "alphanum_fraction": 0.5165562914, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.79175355311861}}
{"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 = \u03c3 * (y - x)\n    dy = x * (\u03c1 - z) - y\n    dz = x * y - \u03b2 * z\n\n    \u03c3 = 10\n    \u03c1 = 28\n    \u03b2 = 8/3\nend\n\nTSUCS1 = @ODE quote\n    dx = \u03b1 * (y - x) + \u03b4 * x * z\n    dy = \u03b6 * y - x * z\n    dz = \u03b2 * z + x * y - \u03f5 * x * x\n\n    \u03b1 = 40\n    \u03b2 = 0.833\n    \u03b4 = 0.5\n    \u03f5 = 0.65\n    \u03b6 = 20\nend\n\nTSUCS2 = @ODE quote\n    dx = \u03b1 * (y - x) + \u03b4 * x * z\n    dy = (\u03c2 * x) - (x * z) + \u03b6 * y\n    dz = (\u03b2 * z) + (x * y) - (\u03f5 * x * x)\n\n    \u03b1 = 40\n    \u03b4 = 0.16\n    \u03c2 = 55\n    \u03b6 = 20\n    \u03b2 = 1.833\n    \u03f5 = 0.65\nend\n\nyuwang = @ODE quote\n    dx = \u03b1 * (y - x)\n    dy = \u03b2 * x - \u03c3 * x * z\n    dz = exp(x * y) - \u03b4 * z\n\n    \u03b1 = 10\n    \u03b2 = 40\n    \u03c3 = 2\n    \u03b4 = 2.5\nend\n\naizawa = @ODE quote\n    dx = (z - \u03b2) * x - \u03b4 * y\n    dy = \u03b4 * x + (z - \u03b2) * y\n    dz = \u03c3 + \u03b1 * z - (z^3)/3 - (x^2 + y^2)*(1 + \u03f5 * z) + \u03b6 * z * x^3\n\n    \u03b1 = 0.95\n    \u03b2 = 0.7\n    \u03c3 = 0.6\n    \u03b4 = 3.5\n    \u03f5 = 0.25\n    \u03b6 = 0.1\nend\n\nlorenz_mod_2 = @ODE quote\n    dx = -\u03b1*x + y^2 - z^2 + \u03b1*\u03c3\n    dy = x*(y-\u03b2*z) + \u03b4\n    dz = -z + x*(\u03b2 * y + z)\n\n    \u03b1 = 0.9\n    \u03b2 = 5\n    \u03c3 = 9.9\n    \u03b4 = 1\nend\n\nthomas = @ODE quote\n    dx = -\u03b2 * x + sin(y)\n    dy = -\u03b2 * y + sin(z)\n    dz = -\u03b2 * z + sin(x)\n\n    \u03b2 = 0.19\nend\n\nrucklidge = @ODE quote\n    dx = -\u03ba*x + \u03b1*y - y* z\n    dy = x\n    dz = -z + y^2\n\n    \u03ba = 2\n    \u03b1 = 6.7\nend\n\ngenesio_tesi = @ODE quote\n    dx = y\n    dy = z\n    dz = -\u03c3 * x - \u03b2 * y - \u03b1 * z + x^2\n\n    \u03b1 = 0.44\n    \u03b2 = 1.1\n    \u03c3 = 1.0\nend\n\nfinance = @ODE quote\n    dx = ((1/\u03b2) - \u03b1)*x + z + x*y\n    dy = -\u03b2*y - x^2\n    dz = -x - \u03c3*z\n\n    \u03b1 = 0.001\n    \u03b2 = 0.2\n    \u03c3 = 1.1\nend\n\nshimizu_morioka = @ODE quote\n    dx = y\n    dy = (1-z)*x - \u03b1*y\n    dz = x^2 - \u03b2*z\n\n    \u03b1 = 0.75\n    \u03b2 = 0.45\nend\n\nnoose_hoover = @ODE quote\n    dx = y\n    dy = -x + y*z\n    dz = \u03b1 - y^2\n\n    \u03b1 = 1.5\nend\n\nliu_chen = @ODE quote\n    dx = \u03b1*y + \u03b2*x + \u03c3*y*z\n    dy = \u03b4*y - z + \u03f5*x*z\n    dz = \u03b6*z + \u03b7*x*y\n\n    \u03b1 = 2.4\n    \u03b2 = -3.78\n    \u03c3 = 14\n    \u03b4 = -11\n    \u03f5 = 4\n    \u03b6 = 5.58\n    \u03b7 = 1\nend\n\narneodo = @ODE quote\n    dx = y\n    dy = z\n    dz = -\u03b1*x - \u03b2*y - z + \u03c3*x^3\n\n    \u03b1 = -5.5\n    \u03b2 = 3.5\n    \u03c3 = -1.0\nend\n\nbouali = @ODE quote\n    dx = x*(4-y) + \u03b1*z\n    dy = -y*(1-x^2)\n    dz = -x*(1.5 - \u03c3*z) - 0.05*z\n\n    \u03b1 = 0.3\n    \u03c3 = 1.0\nend\n\nburke_shaw = @ODE quote\n    dx = -\u03c3*(x+y)\n    dy = -y -\u03c3*x*z\n    dz = \u03c3*x*y + \u03bd\n\n    \u03c3 = 10\n    \u03bd = 4.272\nend\n\nchen_celikovsky = @ODE quote\n    dx = \u03b1*(y-x)\n    dy = -x*z + \u03c3*y\n    dz = x*y - \u03b2*z\n\n    \u03b1 = 36\n    \u03b2 = 3\n    \u03c3 = 20\nend\n\nchen_lee = @ODE quote\n    dx = \u03b1*x - y*z\n    dy = \u03b2*y + x*z\n    dz = \u03c3*z + x*(y/3)\n\n    \u03b1 = 5\n    \u03b2 = -10\n    \u03c3 = -0.38\nend\n\ndequan_li = TSUCS2\n\nhadley = @ODE quote\n    dx = -y^2 -z^2 -\u03b1*x + \u03b1*\u03b6\n    dy = x*y - \u03b2*x*z - y + \u03b7\n    dz = \u03b2*x*y + x*z - z\n\n    \u03b1 = 0.2\n    \u03b2 = 4\n    \u03b6 = 8\n    \u03b7 = 1\nend\n\nhalvorsen = @ODE quote\n    dx = -\u03b1*x -4*y -4*z - y^2\n    dy = -\u03b1*y - 4*z - 4*x - z^2\n    dz = -\u03b1*z - 4*x - 4*y - x^2\n\n    \u03b1 = 1.4\nend\n\nnewton_leipnik = @ODE quote\n    dx = -\u03b1*x + y + 10*y*z\n    dy = -x - 0.4*y + 5*x*z\n    dz = \u03b2*z -5*x*y\n\n    \u03b1 = 0.4\n    \u03b2 = 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": "function grav_potential_cartesian(u)\n    x,y,z = u\n    return -1.0/sqrt(x^2 + y^2 + z^2)\nend\n\nfunction grav_potential_cylindrical(u)\n    r,\u03b8,z = u\n    return -1.0/sqrt(r^2 + z^2)\nend\n\nfunction grav_potential_spherical(u)\n    r,\u03b8,\u03d5 = u\n    return -1.0/r\nend\n\nfunction grav_field(potential::Function, u::Coordinate)\n    return -grad(potential, u)\nend\n\n# Scalar Field Functions\nfunction scalar_field(u::Coordinate)\n    return u[3]*u[1]^2 + sin(u[1])*u[2]*u[3]^2\nend\n\nfunction grad_scalar_field_cartesian(u::Coordinate)\n    x,y,z = u\n    return [2*x*z + cos(x)*y*z^2, sin(x)*z^2, x^2 + 2*sin(x)*y*z]\nend\n\nfunction laplacian_scalar_field_cartesian(u::Coordinate)\n    x,y,z = u\n    return (2*z - sin(x)*y*z^2) + (0.0) + (2*sin(x)*y)\nend\n\nfunction grad_scalar_field_cylindrical(u::Coordinate)\n    r,\u03b8,z = u\n    return [2*r*z + cos(r)*\u03b8*z^2, (sin(r)*z^2)/r, r^2 + 2*sin(r)*\u03b8*z]\nend\n\nfunction laplacian_scalar_field_cylindrical(u::Coordinate)\n    r,\u03b8,z = u\n    return (4*z + (\u03b8*z^2)*(cos(r)/r - sin(r))) + 2*sin(r)*\u03b8\nend\n\nfunction grad_scalar_field_spherical(u::Coordinate)\n    r,\u03b8,\u03d5 = u\n    return [2*r*\u03d5 + cos(r)*\u03b8*\u03d5^2, (sin(r)*\u03d5^2)/(r*sin(\u03d5)), (r^2 + 2*sin(r)*\u03b8*\u03d5)/r]\nend\n\nfunction laplacian_scalar_field_spherical(u::Coordinate)\n    r,\u03b8,\u03d5 = u\n    return (6*\u03d5 + (\u03b8*\u03d5^2)*(2*cos(r)/r - sin(r))) + (cot(\u03d5) + (2*\u03b8*sin(r)/(r^2))*(cot(\u03d5)*\u03d5 + 1))\nend\n\n#Vector Field Functions\nfunction vector_field(u)\n    V = [u[2]*u[1]^2, u[1]*u[2]^2, u[1]*u[2]*u[3]]\n    return ContravariantVector(V, u, unit_basis=true)\nend\n\nfunction div_vector_field_cartesian(u)\n    x,y,z = u\n    return 5*x*y\nend\n\nfunction curl_vector_field_cartesian(u)\n    x,y,z = u\n    return [x*z, -y*z, y^2 - x^2]\nend\n\nfunction vector_laplacian_cartesian(u)\n    x,y,z = u\n    return [2*y , 2*x, 0.0]\nend\n\nfunction div_vector_field_cylindrical(u)\n    r,\u03b8,z = u\n    return 4*\u03b8*r + 2*\u03b8\nend\n\nfunction curl_vector_field_cylindrical(u)\n    r,\u03b8,z = u\n    return [z, -\u03b8*z, 2*\u03b8^2 - r]\nend\n\nfunction vector_laplacian_cylindrical(u)\n    r,\u03b8,z = u\n    return [ \u03b8*(3 - 4/r), 2*(1 + 1/r), \u03b8*z/r]\nend\n\nfunction div_vector_field_spherical(u)\n    r,\u03b8,\u03d5 = u\n    return 4*\u03b8*r + (2*\u03b8)/sin(\u03d5) + \u03b8*(1 + \u03d5*cot(\u03d5))\nend\n\nfunction curl_vector_field_spherical(u)\n    r,\u03b8,\u03d5 = u\n    return [cot(\u03d5)*\u03b8^2 - \u03d5/sin(\u03d5), 2*\u03b8*\u03d5, (r/sin(\u03d5)) - 2*\u03b8^2]\nend\n\nfunction vector_laplacian_spherical(u)\n    r,\u03b8,\u03d5 = u\n    return [4*\u03b8 - (2*\u03b8/r)*(1 + 2/sin(\u03d5) + \u03d5*cot(\u03d5)),\n            (2*\u03b8^2)/r + (2-\u03b8^2)/(r*sin(\u03d5)^2) + 2*(1+ \u03d5*cot(\u03d5)/r)/sin(\u03d5),\n            (\u03b8*\u03d5/r)*(2 - 1/sin(\u03d5)^2) + (\u03b8*cot(\u03d5)/r)*(1 - 4/sin(\u03d5))]\nend\n\nfunction \u03a61(c)\n    tan(prod(c))\nend\n\nfunction \u03a62(c)\n    c[1]*sin(c[2]/c[3])^2\nend\n\nfunction differential_identities(c)\n\n    grad_fg1 = grad(x->\u03a61(x)*\u03a62(x), c)\n    grad_fg2 = \u03a61(c)*grad(\u03a62,c) + grad(\u03a61,c)*\u03a62(c)\n    @test grad_fg1 \u2248 grad_fg2\n\n    div_fA1 = div(x->\u03a61(x)*vector_field(x), c)\n    div_fA2 = \u03a61(c)*div(vector_field,c) + dot(vector_field(c),grad(\u03a61,c))\n    @test div_fA1 \u2248 div_fA2\n\n    curl_fA1 = curl(x->\u03a61(x)*vector_field(x), c)\n    curl_fA2 = \u03a61(c)*curl(vector_field,c) + cross(grad(\u03a61,c),vector_field(c))\n    @test curl_fA1 \u2248 curl_fA2\n\nend\n\nfunction random_cartesian()\n    CartesianCoordinate(3*randn(3))\nend\n\nfunction random_cylindrical()\n    x = [0.0, 0.0, -3.0] + [3.0,2pi,6.0].*rand(3)\n    CylindricalCoordinate(x)\nend\n\nfunction random_spherical()\n    x = [0.0, 0.0, 0.0] + [3.0,2pi,pi].*rand(3)\n    SphericalCoordinate(x)\nend\n\nconst ubc = unit_basis_components\n\n@testset \"Differential Operations\" begin\n    x = CartesianCoordinate([2.0,-1.0,3.0])\n    cyl = CylindricalCoordinate([sqrt(x[1]^2 + x[2]^2), atan(x[2],x[1]), x[3]])\n    sph = SphericalCoordinate([norm(x), atan(x[2],x[1]), acos(x[3]/norm(x))])\n\n    f = norm(grav_field(grav_potential_cartesian, x))\n    @test f \u2248 norm(grav_field(grav_potential_cylindrical, cyl))\n    @test f \u2248 norm(grav_field(grav_potential_spherical, sph))\n\n    x = random_cartesian()\n    cyl = random_cylindrical()\n    sph = random_spherical()\n    println(\"Testing Gradient...\")\n    @testset \"Gradient\" begin\n        @test ubc(grad(scalar_field, x)) \u2248 grad_scalar_field_cartesian(x)\n        @test ubc(grad(scalar_field, cyl)) \u2248 grad_scalar_field_cylindrical(cyl)\n        @test ubc(grad(scalar_field, sph)) \u2248 grad_scalar_field_spherical(sph)\n    end\n\n    println(\"Testing Laplacian...\")\n    @testset \"Laplacian\" begin\n        @test laplacian(scalar_field, x) \u2248 laplacian_scalar_field_cartesian(x)\n        @test laplacian(scalar_field, cyl) \u2248 laplacian_scalar_field_cylindrical(cyl)\n        @test laplacian(scalar_field, sph) \u2248 laplacian_scalar_field_spherical(sph)\n    end\n\n    println(\"Testing Divergence...\")\n    @testset \"Divergence\" begin\n        @test div(vector_field, x) \u2248 div_vector_field_cartesian(x)\n        @test div(vector_field, cyl) \u2248 div_vector_field_cylindrical(cyl)\n        @test div(vector_field, sph) \u2248 div_vector_field_spherical(sph)\n    end\n\n    println(\"Testing Curl...\")\n    @testset \"Curl\" begin\n        @test ubc(curl(vector_field, x)) \u2248 curl_vector_field_cartesian(x)\n        @test ubc(curl(vector_field, cyl)) \u2248 curl_vector_field_cylindrical(cyl)\n        @test ubc(curl(vector_field, sph)) \u2248 curl_vector_field_spherical(sph)\n    end\n\n    println(\"Testing Vector Laplacian...\")\n    @testset \"Vector Laplacian\" begin\n        @test ubc(vector_laplacian(vector_field, x)) \u2248 vector_laplacian_cartesian(x)\n        @test ubc(vector_laplacian(vector_field, cyl)) \u2248 vector_laplacian_cylindrical(cyl)\n        @test ubc(vector_laplacian(vector_field, sph)) \u2248 vector_laplacian_spherical(sph)\n    end\n\n    println(\"Testing Differential Identities...\")\n    @testset \"Differential Identities\" begin\n        @testset \"Cartesian\" begin\n            differential_identities(x)\n        end\n        @testset \"Cylindrical\" begin\n            differential_identities(cyl)\n        end\n        @testset \"Spherical\" begin\n            differential_identities(sph)\n        end\n    end\nend\n", "meta": {"hexsha": "524b44a6b0de933de231121b28c7e31308daf98c", "size": 5850, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/differential.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": "test/differential.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": "test/differential.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.125, "max_line_length": 95, "alphanum_fraction": 0.6420512821, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7917253668164548}}
{"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') = \u03c3\u00b2(1+\u221a3*d/\u2113)exp(-\u221a3*d/\u2113), where d = |x-x'|\n# Arguments:\n* `ll::Float64`: Log of the length scale \u2113\n* `l\u03c3::Float64`: Log of the signal standard deviation \u03c3\n\"\"\" ->\ntype Mat32Iso <: Isotropic\n    \u2113::Float64       # Length scale \n    \u03c32::Float64      # Signal std\n    Mat32Iso(ll::Float64, l\u03c3::Float64) = new(exp(ll),exp(2*l\u03c3))\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.\u2113, mat.\u03c32 = exp(hyp[1]), exp(2.0*hyp[2])\nend\n\nget_params(mat::Mat32Iso) = Float64[log(mat.\u2113), log(mat.\u03c32)/2.0]\nget_param_names(mat::Mat32Iso) = [:ll, :l\u03c3]\nnum_params(mat::Mat32Iso) = 2\n\nmetric(mat::Mat32Iso) = Euclidean()\ncov(mat::Mat32Iso, r::Float64) = mat.\u03c32*(1+sqrt(3)*r/mat.\u2113)*exp(-sqrt(3)*r/mat.\u2113)\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.\u2113)\n\n    g1= mat.\u03c32*(sqrt(3)*r/mat.\u2113)^2*exp_r       #dK_d(log \u2113)\n    g2 = 2.0*mat.\u03c32*(1+sqrt(3)*r/mat.\u2113)*exp_r  #dK_d(log \u03c3)\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.\u2113)\n\n    for i in 1:nobsv, j in 1:i\n        @inbounds stack[i,j,1] = mat.\u03c32*(sqrt(3)*R[i,j]/mat.\u2113)^2*exp_R[i,j]       # dK_d\u2113\n        @inbounds stack[j,i,1] = stack[i,j,1] \n        @inbounds stack[i,j,2] = 2.0 *mat.\u03c32*(1+sqrt(3)*R[i,j]/mat.\u2113)*exp_R[i,j]  # dK_d\u03c3\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, \u03b1::Integer, x::Real)\n    # by Horner's method\n    laguerre_l = 1\n    bin = 1\n    for i in n:-1:1\n        bin *= (\u03b1 + 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, \u03b1::Integer) = x->laguerre_horner(n, \u03b1, x)\n\nfunction laguerre(n::Integer, \u03b1::Integer, x::T) where {T<:Real}\n    if n == 0\n        return one(T)\n    elseif n == 1\n        return one(T) + \u03b1 - x\n    else\n        L_prev = one(T)\n        L_k = one(T) + \u03b1 - x\n        for k = 1:(n-1)\n            L_next = ((2k + one(T) + \u03b1 - x) * L_k - (k+\u03b1) * 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, \u03b1::Integer) = x->laguerre(n, \u03b1, x)\n\nfunction laguerre(m::Integer, n::Integer, x::Real, p::Real)\n    if n \u2265 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 \u2265 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 \u2265 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# \u2554\u2550\u2561 7022d960-2901-11eb-2528-87791813b415\nusing OffsetArrays\n\n# \u2554\u2550\u2561 afa4a77e-28fc-11eb-1ab0-bbba1b653e46\ndata = reshape(rand(1:9,36),6,6)\n\n# \u2554\u2550\u2561 0019e726-28fd-11eb-0e86-31ec28b3c1a9\nI = CartesianIndices(data)\n\n# \u2554\u2550\u2561 15548ecc-28fd-11eb-1206-476c5f44efdf\n[ data[i] for i\u2208I]\n\n# \u2554\u2550\u2561 5fb6e7b6-2901-11eb-0e94-aba290fd0bae\nA = OffsetArray(zeros(Int,8,8), 0:7 ,0:7)\n\n# \u2554\u2550\u2561 87c260a2-2901-11eb-1060-b1e4b6b5b02b\nfor i \u2208 I\n\tA[i] = data[i]  # copy data\nend\n\n# \u2554\u2550\u2561 a5c7693a-2901-11eb-1083-0da8138a73c2\nA\n\n# \u2554\u2550\u2561 b6fde83c-2901-11eb-0e3b-4b3766579cc8\nneighborhood = CartesianIndices((-1:1, -1:1))\n\n# \u2554\u2550\u2561 babe3c24-2901-11eb-2d30-51256eb97e11\n[ A[i.+neighborhood] for i \u2208 I]\n\n# \u2554\u2550\u2561 e6bd9dea-2901-11eb-1100-ad10705f41cc\nstencil =  [ 0  -1   0\n            -1   4  -1\n            0  -1   0]\n\n# \u2554\u2550\u2561 fe4f6df0-2901-11eb-1945-27e3f041ed1f\n[  sum(A[i.+neighborhood].*stencil) for i \u2208 I]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4f342744-2902-11eb-1401-55e770d9d751\n\nfor i\u2208I\n\tB[i] = sum(A[i.+neighborhood].*stencil)\nend\n\n\n# \u2554\u2550\u2561 6223e374-2902-11eb-3bb2-4d2d0d352801\nB\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550afa4a77e-28fc-11eb-1ab0-bbba1b653e46\n# \u2560\u25500019e726-28fd-11eb-0e86-31ec28b3c1a9\n# \u2560\u255015548ecc-28fd-11eb-1206-476c5f44efdf\n# \u2560\u25507022d960-2901-11eb-2528-87791813b415\n# \u2560\u25505fb6e7b6-2901-11eb-0e94-aba290fd0bae\n# \u2560\u255087c260a2-2901-11eb-1060-b1e4b6b5b02b\n# \u2560\u2550a5c7693a-2901-11eb-1083-0da8138a73c2\n# \u2560\u2550b6fde83c-2901-11eb-0e3b-4b3766579cc8\n# \u2560\u2550babe3c24-2901-11eb-2d30-51256eb97e11\n# \u2560\u2550e6bd9dea-2901-11eb-1100-ad10705f41cc\n# \u2560\u2550fe4f6df0-2901-11eb-1945-27e3f041ed1f\n# \u2560\u255077c06ce6-2902-11eb-30a7-51f210dbd723\n# \u2560\u25504f342744-2902-11eb-1401-55e770d9d751\n# \u2560\u25506223e374-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\u00d72 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\u00e8 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( \u03bc, \u03b1, \u03b2 )\n\nThe \"Generalized Normal\" or \"Generalized Gaussian\" with shape parameter '\u03b2',\nscale '\u03b1', and location '\u03bc' 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 `\u03b2 = 1` incorporates the Laplacian distribution, `\u03b2 = 2` is the Normal distribution,\nand as `\u03b2 \u2192 \u221e`, the distribution approaches Uniform on `[\u03bc-\u03b1, \u03bc+\u03b1]`.\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 \u03b2 shape\nscale(d)                        # returns the scale parameter, \u03b1\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\u00edguez-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    \u03bc::T\n    \u03b1::T\n    \u03b2::T\n    function GeneralizedGaussian{T}(\u03bc::T, \u03b1::T, \u03b2::T) where T\n        \u03b1 > zero(\u03b1) || error(\"standard deviation must be positive.\")\n        \u03b2 > zero(\u03b2) || error(\"\u03b2 must be greater than zero.\")\n        new{T}(\u03bc, \u03b1, \u03b2)\n    end\nend\n\nGeneralizedGaussian(\u03bc::T, \u03b1::T, \u03b2::T) where {T<:Real} = GeneralizedGaussian{T}(\u03bc, \u03b1, \u03b2)\nGeneralizedGaussian(\u03bc::Real, \u03b1::Real, \u03b2::Real) = GeneralizedGaussian(promote(\u03bc, \u03b1, \u03b2)...)\nGeneralizedGaussian(\u03bc::Integer, \u03c3::Integer, \u03b2::Integer) = GeneralizedGaussian(Float64(\u03bc), Float64(\u03c3), Float64(\u03b2))\n\n\"\"\"\n    GeneralizedGaussian(\u03b2)\n\nBuilds a default distribution with shape `\u03b2` and `\u03bc=0, \u03b1=1`.\n\"\"\"\nGeneralizedGaussian(\u03b2::Real) = GeneralizedGaussian(zero(\u03b2), one(\u03b2), \u03b2)\n\n\"\"\"\n    GeneralizedGaussian()\n\nBuilds the Normal distribution case, where `\u03bc=0, \u03b1=\u221a2, \u03b2=2`, or N(0, 1).\n\"\"\"\nGeneralizedGaussian() = GeneralizedGaussian(0.0, \u221a2, 2)\n\n### Conversion\nfunction convert(::Type{GeneralizedGaussian{T}}, \u03bc::Real, \u03c3::Real, \u03b2::Real) where T <: Real\n    GeneralizedGaussian(T(\u03bc), T(\u03b1), T(\u03b2))\nend\nfunction convert(::Type{GeneralizedGaussian{T}}, d::GeneralizedGaussian{S}) where {T <: Real, S <: Real}\n    GeneralizedGaussian(T(d.\u03bc), T(d.\u03b1), T(d.\u03b2))\nend\n\n### Parameters\nparams(d::GeneralizedGaussian) = (d.\u03bc, d.\u03b1, d.\u03b2)\nlocation(d::GeneralizedGaussian) = d.\u03bc\nscale(d::GeneralizedGaussian) = d.\u03b1\nshape(d::GeneralizedGaussian) = d.\u03b2\n\nvar(d::GeneralizedGaussian) = (d.\u03b1^2) * (gamma(3.0 * inv(d.\u03b2)) / gamma(inv(d.\u03b2)))\nstd(d::GeneralizedGaussian) = (d.\u03b1) * sqrt(gamma(3.0 * inv(d.\u03b2)) / gamma(inv(d.\u03b2)))\n\nmean(d::GeneralizedGaussian) = d.\u03bc\nmedian(d::GeneralizedGaussian) = d.\u03bc\nmode(d::GeneralizedGaussian) = d.\u03bc\n\n### Statistics\nskewness(d::GeneralizedGaussian{T}) where T = zero(T)\nkurtosis(d::GeneralizedGaussian) = gamma(5.0 * inv(d.\u03b2)) * gamma(inv(d.\u03b2)) / (gamma(3.0 * inv(d.\u03b2))^2) - 3.0\nentropy(d::GeneralizedGaussian) = inv(d.\u03b2) - log( d.\u03b2 / (2.0 * d.\u03b1 * gamma(inv(d.\u03b2))))\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.\u03b2 / (2.0 * d.\u03b1 * gamma(1. / d.\u03b2) )\n        return A * exp( -(abs(x - d.\u03bc) / d.\u03b1)^d.\u03b2 )\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/\u0393(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.\u03b2), 1), (abs(x - \u03bc) / d.\u03b1)^d.\u03b2) * inv(2)\n        return typeof(v)(1/2) + sign(x - \u03bc) * 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.\u03b2), 1)\n    # random variable with value -1 or 1 with probability (1/2).\n    b = 2.0 * rand(Bernoulli()) - 1\n    return d.\u03bc + inv(sqrt(d.\u03b1)) * rand(rng, g)^inv(d.\u03b2) * 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, \u03b2::Real)\n    n = size(X,1)\n    S1 = 1/n * sum(abs.(X).^(2\u03b2))\n    S2 = 1/n * sum(abs.(X).^\u03b2)\n    return (S1/(S2^2)) - (\u03b2 + 1)\nend\n\nfunction Zn\u2032(X::AbstractArray, \u03b2::Real)\n    n = size(X,1)\n    S1 = sum(abs.(X).^\u03b2) # sum\n    S2 = sum(abs.(X).^(2\u03b2))\n    L1 = sum(abs.(X).^\u03b2 .* log.(abs.(X)))    # log\n    L2 = sum(abs.(X).^(2\u03b2) .* 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    \u03b2 = gcmsearch(X::AbstractArray, \u03b2i::Real)\n\nGlobally convergent method for \u03b2-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}, \u03b2i::Real) where T<:AbstractFloat\n    \u03f5 = \u221aeps(T)\n    N_MAX = 1_000\n    \u03b2p = copy(\u03b2i)\n    num, denom = Zn(X, \u03b2p), Zn\u2032(X, \u03b2p)\n    \u03b2n = \u03b2p - (num/denom)\n    \u03b2p = copy(\u03b2n)\n    for _ = 2:N_MAX\n        num, denom = Zn(X, \u03b2p), Zn\u2032(X, \u03b2p)\n        \u03b2n = \u03b2p - (num/denom)\n        if (abs(\u03b2n - \u03b2p) < \u03f5) # check if converged?\n            break\n        else\n            \u03b2p = copy(\u03b2n) # prep for next iteration.\n        end\n    end\n    \u03b2n\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 \u2248 A\n    @test Q'*Q \u2248 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 \u2248 Q\n    @test r \u2248 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": "@testset \"Utils\" begin\n\n    @testset \"Test soft_theta\" begin \n        x = -1:0.1:1\n        @test eltype(MicroscopyTools.soft_theta.(Float32.(x))) == Float32\n        @test MicroscopyTools.soft_theta.(x, Ref(13.1)) \u2248 1 ./ (1 .+exp.(-2 .*13.1 .*x))\n        @test MicroscopyTools.soft_theta_pw(0.01) == 1.0\n        @test typeof(MicroscopyTools.soft_theta_pw(0.01f0)) == Float32\n        @test MicroscopyTools.soft_theta_pw(-0.01) == 0.0\n        @test MicroscopyTools.soft_theta_pw(-0.0) \u2248 0.5\n        @test MicroscopyTools.soft_theta_pw(1/3.0, 1.0) \u2248 0.75\n    end\n    \n    @testset \"Test soft_delta\" begin \n        \n        T = Float64\n        f(x, k) = one(T) / (k * \u221a(T(\u03c0))) * exp(-abs2(x / k))\n\n        x = -1:0.1:1\n        @test eltype(MicroscopyTools.soft_delta.(Float32.(x))) == Float32\n        @test MicroscopyTools.soft_delta.(x, Ref(13.1)) \u2248 f.(x, 13.1) \n\n\n        @test typeof(MicroscopyTools.soft_delta_pw(0.01f0)) == Float32\n        @test MicroscopyTools.soft_delta_pw(0.01f0) == 0.0\n        @test MicroscopyTools.soft_delta_pw(-0.01) == 0.0\n        @test MicroscopyTools.soft_delta_pw(-0.0) \u2248 1.0\n        @test MicroscopyTools.soft_delta_pw(1/3.0, 1.0) \u2248 0.75\n    end\n\nend\n", "meta": {"hexsha": "ae3f66b13628b5f0c8aa74de7c6d182fd0cbc945", "size": 1181, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/utils.jl", "max_stars_repo_name": "JuliaMicroscopy/MicroscopyTools", "max_stars_repo_head_hexsha": "56e7c8a95e4cb67ca463984647d8421d234a6dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T19:46:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T19:46:00.000Z", "max_issues_repo_path": "test/utils.jl", "max_issues_repo_name": "JuliaMicroscopy/MicroscopyTools", "max_issues_repo_head_hexsha": "56e7c8a95e4cb67ca463984647d8421d234a6dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-26T21:37:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T02:28:47.000Z", "max_forks_repo_path": "test/utils.jl", "max_forks_repo_name": "JuliaMicroscopy/MicroscopyTools.jl", "max_forks_repo_head_hexsha": "56e7c8a95e4cb67ca463984647d8421d234a6dec", "max_forks_repo_licenses": ["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.90625, "max_line_length": 88, "alphanum_fraction": 0.5961049958, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7915464363253055}}
{"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": "function zeck(n)\n    n <= 0 && return 0\n    fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end\n    dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end\n    return dig[1] == 0 ? dig[2:end] : dig\nend\n", "meta": {"hexsha": "e20333799342628b9b4542f9adc18ecfac4e8714", "size": 235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/zeckendorf-number-representation.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/zeckendorf-number-representation.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/zeckendorf-number-representation.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.5714285714, "max_line_length": 82, "alphanum_fraction": 0.514893617, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7915212773867314}}
{"text": "# Algorithm 5.1\n# Euler's method\n\nfunction euler(f, a, b, N, \u03b1)\n\tresult = Tuple{Float64, Float64}[]\n\th = (b - a)/N\n\tt = \u03b1\n\t\u03c9 = \u03b1\n\tpush!(result, (t, \u03c9))\n\tfor i \u2208 1:N\n\t\t\u03c9 = \u03c9 + h*f(t, \u03c9)\n\t\tt = a + i*h\n\t\tpush!(result, (t, \u03c9))\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\u03c0\"\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    \u03ba(x,y) = exp(x\u1d40y)\n```\n\"\"\"\nstruct ExponentiatedKernel <: SimpleKernel end\n\nkappa(\u03ba::ExponentiatedKernel, x\u1d40y::Real) = exp(x\u1d40y)\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, \u03bc=1)\n\nReturns the function\n```math\nf(x) = \u03bc\u22c5\u2211_i log(1+exp(-y_i\u22c5x_i))\n```\nwhere `y` is an array and `\u03bc` 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(\u03b1=0.01))\n    AffineMean(dims::Int,features::Int;opt::Optimizer=Adam(\u03b1=0.01))\n```\nConstruct an affine operation on `X` : `\u03bc\u2080(X) = X*w + b` where `w` is a vector and `b` a scalar\nOptionally give an optimizer `opt` (`Adam(\u03b1=0.01)` by default)\n\"\"\"\nfunction AffineMean(w::V,b::T,;opt::Optimizer=Adam(\u03b1=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(\u03b1=0.01))\n    AffineMean{Float64,Vector{Float64}}(randn(dims),0.0,dims,opt)\nend\n\nfunction update!(\u03bc::AffineMean{T},grad::AbstractVector{T},X::AbstractMatrix) where {T<:Real}\n    \u0394 = vcat(X'*grad,sum(grad))\n    \u0394 = update(\u03bc.opt,\u0394)\n    \u03bc.w .+= \u0394[1:\u03bc.nDim]\n    \u03bc.b += \u0394[end]\nend\n\nfunction (\u03bc::AffineMean{T})(x::AbstractMatrix) where {T<:Real}\n    @assert \u03bc.nDim == size(x,2) \"Number of dimensions do not match\"\n    return x*\u03bc.w .+ \u03bc.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        \u03c3 = 1/(6k * h)\n\n        # Checking sign\n        sign = r == 0 ? 1 : r/abs(r)\n\n        # Kernel computation\n        W = (4cos(\u03c0/(2h) * r) + cos(\u03c0/h * r) + 3) * \u03c3\n\n        #\u00a0Derivatives computation\n        \u2202x_W = (4\u03c0/(2h) * sin(\u03c0/(2h) * r) + \u03c0/h * sin(\u03c0/h * r)) * -sign * \u03c3\n\n        return (W,\u2202x_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        \u03c3 = 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) * \u03c3\n\n            #\u00a0Derivatives computation\n            \u2202x_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 * \u03c3\n\n            #\u00a0Derivatives computation\n            \u2202x_W = (q-2)^2/2 * sign/h^2\n        end\n        return (W,\u2202x_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 Test, FinancialMonteCarlo;\n@show \"MertonProcess\"\nS0 = 100.0;\nK = 100.0;\nr = 0.02;\nT = 1.0;\nd = 0.01;\nD = 90.0;\n\nNsim = 10000;\nNstep = 30;\nsigma = 0.2;\nlam = 5.0;\nmu1 = 0.03;\nsigma1 = 0.02;\nmc = MonteCarloConfiguration(Nsim, Nstep);\nmc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());\ntoll = 0.8;\n\nrfCurve = ZeroRate(r);\n\nFwdData = Forward(T)\nEUData = EuropeanOption(T, K)\nAMData = AmericanOption(T, K)\nBarrierData = BarrierOptionDownOut(T, K, D)\nAsianData = AsianFloatingStrikeOption(T)\nModel = MertonProcess(sigma, lam, mu1, sigma1, Underlying(S0, d));\n\n@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);\n@show EuPrice = pricer(Model, rfCurve, mc, EUData);\n@show AmPrice = pricer(Model, rfCurve, mc, AMData);\n@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);\n@show AsianPrice = pricer(Model, rfCurve, mc, AsianData);\n\n@test abs(FwdPrice - 99.1188767166039) < toll\n@test abs(EuPrice - 9.084327245917533) < toll\n@test abs(BarrierPrice - 7.880881290426765) < toll\n@test abs(AsianPrice - 5.129020349580892) < toll\n\n@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);\n@show EuPrice = pricer(Model, rfCurve, mc1, EUData);\n@show AmPrice = pricer(Model, rfCurve, mc1, AMData);\n@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);\n@show AsianPrice = pricer(Model, rfCurve, mc1, AsianData);\ntollanti = 0.6;\n@test abs(FwdPrice - 99.1188767166039) < tollanti\n@test abs(EuPrice - 9.084327245917533) < tollanti\n@test abs(BarrierPrice - 7.880881290426765) < tollanti\n@test abs(AsianPrice - 5.129020349580892) < tollanti\n\n@show \"Test Merton Parameters\"\n\n@test_throws(ErrorException, MertonProcess(-sigma, lam, mu1, sigma1, Underlying(S0, d)))\n@test_throws(ErrorException, MertonProcess(sigma, lam, mu1, -sigma1, Underlying(S0, d)))\n@test_throws(ErrorException, MertonProcess(sigma, -lam, mu1, sigma1, Underlying(S0, d)))\n", "meta": {"hexsha": "5fbb0dd98015d15606eb9810d54242cd3d6941c8", "size": 1868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_merton.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": "test/test_merton.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": "test/test_merton.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": 33.3571428571, "max_line_length": 88, "alphanum_fraction": 0.7307280514, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7914549115088337}}
{"text": "function qap(n, W, D, ::Val{:JuMP})\n    model = JuMP.Model(CBLS.Optimizer)\n\n    @variable(model, 1 \u2264 X[1:n] \u2264 n, Int)\n    @constraint(model, X in AllDifferent())\n\n    \u03a3wd = p -> sum(sum(W[p[i], p[j]] * D[i, j] for j in 1:n) for i in 1:n)\n\n    @objective(model, Min, ScalarFunction(\u03a3wd))\n\n    return model, X\nend\n\n\"\"\"\n    qap(n, weigths, distances; modeler = :JuMP)\n\nModelize an instance of the Quadractic Assignment Problem with\n- `n`: number of both facilities and locations\n- `weights`: `Matrix` of the weights of each pair of facilities\n- `distances`: `Matrix` of distances between locations\n- `modeler`: Default to `:JuMP`. No other modeler available for now.\n\n# From Wikipedia\nThere are a set of `n` facilities and a set of `n` locations. For each pair of locations, a distance is specified and for each pair of facilities a `weight` or flow is specified (e.g., the amount of supplies transported between the two facilities). The problem is to assign all facilities to different locations with the goal of minimizing the sum of the `distances` multiplied by the corresponding flows.\n\"\"\"\nqap(n, weigths, distances; modeler = :JuMP) = qap(n, weigths, distances, Val(modeler))\n", "meta": {"hexsha": "6dcea05a9a35516e233c6164950f0b93d44a5ba7", "size": 1179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/assignment.jl", "max_stars_repo_name": "JuliaConstraints/ConstraintModels.jl", "max_stars_repo_head_hexsha": "90ec2346e256c4044d5dfb2c55546eb288e80290", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-29T05:43:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T10:01:08.000Z", "max_issues_repo_path": "src/assignment.jl", "max_issues_repo_name": "JuliaConstraints/ConstraintModels.jl", "max_issues_repo_head_hexsha": "90ec2346e256c4044d5dfb2c55546eb288e80290", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-03-21T02:36:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T00:57:03.000Z", "max_forks_repo_path": "src/assignment.jl", "max_forks_repo_name": "JuliaConstraints/ConstraintModels.jl", "max_forks_repo_head_hexsha": "90ec2346e256c4044d5dfb2c55546eb288e80290", "max_forks_repo_licenses": ["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": 405, "alphanum_fraction": 0.7073791349, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7914549058384946}}
{"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 \u2264 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) \u2192 (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) \u2192 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\u03b1(t) = 1.0\n\u03b2(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] += \u03b1(t)/h^2\n    b[end] += \u03b2(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([\u03b1 [,\u03b2 [,\u03b3]]])\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}(\u03b1::Real, \u03b2::Real, \u03b3::Real) where {T<:AbstractFloat} = new{T}(\n        HyperParameter(convert(T,\u03b1), interval(OpenBound(zero(T)), nothing)),\n        HyperParameter(convert(T,\u03b2), interval(OpenBound(zero(T)), nothing)),\n        HyperParameter(convert(T,\u03b3), interval(OpenBound(zero(T)), ClosedBound(one(T))))\n    )\nend\nfunction GammaRationalKernel(\n        \u03b1::T1 = 1.0,\n        \u03b2::T2 = one(T1),\n        \u03b3::T3 = one(floattype(T1,T2))\n    ) where {T1<:Real,T2<:Real,T3<:Real}\n    GammaRationalKernel{floattype(T1,T2,T3)}(\u03b1,\u03b2,\u03b3)\nend\n\n@inline gammarationalkernel(z::T, \u03b1::T, \u03b2::T, \u03b3::T) where {T<:AbstractFloat} = (1 + \u03b1*(z^\u03b3))^(-\u03b2)\n\n@inline basefunction(::GammaRationalKernel) = SquaredEuclidean()\n@inline function kappa(\u03ba::GammaRationalKernel{T}, z::T) where {T}\n    gammarationalkernel(z, getvalue(\u03ba.alpha), getvalue(\u03ba.beta), getvalue(\u03ba.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 \u2208 {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 \u2208 {false,true}\n    # x|y ~ \ud835\udcdd(x|\u03bc_y, \u03a3_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    \u03c0_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(\u03bc\u2081, \u03a3\u2081)\n    d2 = fit_mle(FullNormal, X_cls2)  # MLE density estimation d2 = N(\u03bc\u2082, \u03a3\u2082)\n    \u03a3 = \u03c0_hat[1] * cov(d1) + \u03c0_hat[2] * cov(d2) # Combine \u03a3\u2081 and \u03a3\u2082 into \u03a3\n\n    conditionals = [MvNormal(mean(d1), \u03a3); MvNormal(mean(d2), \u03a3)] # p(x|C)\n\n    # Discrimination boundary of the posterior (p(apple|x;D) = p(peach|x;D) = 0.5)\n    \u03b2(k) = inv(\u03a3)* mean(conditionals[k])\n    \u03b3(k) = -0.5 * mean(conditionals[k])' * inv(\u03a3) * mean(conditionals[k]) + log(\u03c0_hat[k])\n    function discriminant_x2(x1)\n        # Solve discriminant equation for x2\n        \n        \u03b212 = \u03b2(1) .- \u03b2(2)\n        \u03b312 = (\u03b3(1) .- \u03b3(2))[1,1]\n        return -1 ./ \u03b212[2]*(\u03b212[1]*x1 .+ \u03b312) \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": "compute(n::Int)::Int = n * (n + 1) * (3n ^ 2 - n - 2) \u00f7 12\n", "meta": {"hexsha": "6bf5d72d2e324de6a29fea636afd6f71dc055427", "size": 59, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/0006/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/0006/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/0006/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": 29.5, "max_line_length": 58, "alphanum_fraction": 0.406779661, "num_tokens": 33, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608886, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7913297599851774}}
{"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,\u03b3,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*\u03b3)/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,\u03b3,distribution)\n    tspan = (0.0,T)\n    u0 = getstartpoints_strogatz(N)\n    p = getparameters_strogatz(N,K,\u03b3,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# \u221a2=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    \u0394t \u2265 0, (start = 1/n) # Time step\n    # State variables\n    v[1:n] \u2265 0            # Velocity\n    h[1:n] \u2265 h_0          # Height\n    m_f \u2264 m[1:n] \u2264 m_0    # Mass\n    # Control\n    0 \u2264 T[1:n] \u2264 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, \u0394t * n)\n\n# Dynamics\nfor j in 2:n\n    # h' = v\n    \n    # Rectangular integration\n    # @NLconstraint(rocket, h[j] == h[j - 1] + \u0394t * v[j - 1])\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        h[j] == h[j - 1] + 0.5 * \u0394t * (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] + \u0394t *(\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 * \u0394t * (\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] - \u0394t * T[j - 1] / c)\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        m[j] == m[j - 1] - 0.5 * \u0394t * (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.(\u0394t), y = value.(h)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Altitude\"))\nm_plot = plot(x = (1:n) * value.(\u0394t), y = value.(m)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Mass\"))\nv_plot = plot(x = (1:n) * value.(\u0394t), y = value.(v)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Velocity\"))\nT_plot = plot(x = (1:n) * value.(\u0394t), 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": "using EmpiricalBayes\nusing Test\nusing Distributions\nusing QuadGK\n\n# Move these to other parts eventually\n\n# test if convolution matrix works for small n..\nA = convolution_matrix(DiscretizedNormalConvolutionProblem, range(-1, stop=1, length=4), range(-7, stop=7, length=2000))\nh = range(-7, stop=7, length=2000)[2] - range(-7, stop=7, length=2000)[1]\n@test isapprox(sum(A,1)*h, ones(4)'; atol=1e-4)\n\n\n# test discretization approach vs. properly integrating..\nn_marginal_grid = 1001\nmarginal_grid =  range(-3, stop=3, length=n_marginal_grid)\nmarginal_h = marginal_grid[2]-marginal_grid[1]\n\nn_prior_grid = 1001\nprior_grid = range(-6, stop=6, length=n_prior_grid)\n\nnormal_normal = DiscretizedNormalConvolutionProblem(Normal(0,0.5), \n                    prior_grid,\n                    marginal_grid)\n\nmarginal_dist = Normal(0,sqrt(1+0.5^2))\nmarginal_l = marginal_grid .- marginal_h/2\nmarginal_r = marginal_grid .+ marginal_h/2\n\nf_marginal = [QuadGK.quadgk(x->pdf.(marginal_dist,x),marginal_l[i],marginal_r[i])[1] for i=1:n_marginal_grid];\nf_marginal ./= sum(f_marginal);\n\n@test isapprox(f_marginal, normal_normal.marginal; atol= 1e-7)\n\n@test sum(normal_normal.prior) \u2248 1\n@test sum(normal_normal.marginal) \u2248 1\n\n# check if posterior mean calculated correctly (normal-normal conjugate we know this ofc)\npost_mean = posterior_stats(normal_normal, \u03bc -> \u03bc, 2)\n@test isapprox(post_mean[3], 2/1/(1+1/0.5^2))\n\n\n# now check for indicator \u03bc >= 0\n# actually tolerances here are rather bad...esp. for ground truth should do a better job.\n\ntrue_num = quadgk(\u03b2 ->  pdf(Normal(0,0.5), \u03b2)*pdf(Normal(), 2-\u03b2) , 0,100)[1]\ntrue_denom = quadgk(\u03b2 ->  pdf(Normal(0,0.5), \u03b2)*pdf(Normal(), 2-\u03b2) , -100,100)[1]\ntrue_ratio = true_num/true_denom\n\nposterior_positive = posterior_stats(normal_normal, \u03bc ->  (\u03bc >= 0).*1, 2)\n@test isapprox(true_num, posterior_positive[1]; atol=1e-3 )\n@test isapprox(true_denom, posterior_positive[2]; atol=1e-3 )\n@test isapprox(true_ratio, posterior_positive[3]; atol=1e-2)\n\n\n# again in this case we know exactly what the value is..\n\npost_Normal = Normal(2/1/(1+1/0.5^2), sqrt(1*0.5^2/(1+0.5^2)))\npost_positive_true = ccdf(post_Normal, 0 )\n\n@test isapprox(post_positive_true, true_ratio)\n@test isapprox(post_positive_true, posterior_positive[3]; atol=1e-2)\n\n\n## OK NOW let us check with the more exact object\n\nnormal_normal_exact = NormalConvolutionProblem(Normal(0,0.5), marginal_grid)\n@test isapprox(f_marginal, normal_normal_exact.marginal; atol= 1e-9)\n\n\nnon_disr_post_positive = posterior_stats(normal_normal_exact, \u03bc ->  (\u03bc >= 0).*1, 2)\n@test isapprox(post_positive_true, non_disr_post_positive[3]; atol=1e-8)\n", "meta": {"hexsha": "1e85915fcfb473abb7ec39143cc0e7fc48d5a89a", "size": 2613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "nignatiadis/EmpiricalBayes.jl", "max_stars_repo_head_hexsha": "b0ff1bd6498d52ad7fa18bb69ba918ec014017a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-04T11:48:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T13:47:06.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "nignatiadis/EmpiricalBayes.jl", "max_issues_repo_head_hexsha": "b0ff1bd6498d52ad7fa18bb69ba918ec014017a2", "max_issues_repo_licenses": ["MIT"], "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": "nignatiadis/EmpiricalBayes.jl", "max_forks_repo_head_hexsha": "b0ff1bd6498d52ad7fa18bb69ba918ec014017a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:53:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:53:54.000Z", "avg_line_length": 35.7945205479, "max_line_length": 120, "alphanum_fraction": 0.7336394948, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7912493120699245}}
{"text": "using Revise\nusing ADCME\nusing PyPlot\nusing AdFem\n\n\nm = 40\nn = 40\nh = 1/n\nbdnode = bcnode(\"all\", m, n, h)\nxy = gauss_nodes(m, n, h)\nxy_fem = fem_nodes(m, n, h)\n\nfunction poisson1d(\u03ba)\n    \u03ba = compute_space_varying_tangent_elasticity_matrix(\u03ba, m, n, h)\n    K = compute_fem_stiffness_matrix1(\u03ba, m, n, h)\n    K, _ = fem_impose_Dirichlet_boundary_condition1(K, bdnode, m, n, h)\n    rhs = compute_fem_source_term1(ones(4m*n), m, n, h)\n    rhs[bdnode] .= 0.0\n    sol = K\\rhs\nend\n\n\u03ba = @. 0.1 + sin(xy[:,1]) + (xy[:,2]-1)^2 * xy[:,1] + log(1+xy[:,2])\ny = poisson1d(\u03ba)\n\nsess = Session(); init(sess)\nSOL = run(sess, y)\n\n\n# inverse modeling \n\u03bann = squeeze(abs(ae(xy, [20,20,20,1])))\ny = poisson1d(\u03bann)\n\nusing Random; Random.seed!(233)\nidx = fem_randidx(100, m, n, h)\nobs = y[idx]\nOBS = SOL[idx]\nloss = sum((obs-OBS)^2)\n\ninit(sess)\nBFGS!(sess, loss, 200)\n\nfigure(figsize=(10,4))\nsubplot(121)\nvisualize_scalar_on_fem_points(SOL, m, n, h)\nsubplot(122)\nvisualize_scalar_on_fem_points(run(sess, y), m, n, h)\nplot(xy_fem[idx,1], xy_fem[idx,2], \"o\", c=\"red\", label=\"Observation\")\nlegend()\n\n\nfigure(figsize=(10,4))\nsubplot(121)\nvisualize_scalar_on_gauss_points(\u03ba, m, n, h)\ntitle(\"Exact \\$K(x, y)\\$\")\nsubplot(122)\nvisualize_scalar_on_gauss_points(run(sess, \u03bann), m, n, h)\ntitle(\"Estimated \\$K(x, y)\\$\")\n\n\nH = gradients(obs, \u03bann) \nH = run(sess, H)\ny = OBS \nhs = run(sess, obs)\nR = (1e-1)^2*diagm(0=>ones(length(obs)))\ns = run(sess, \u03bann)\nQ = (1e-2)^2*diagm(0=>ones(length(\u03bann)))\n\u03bc, \u03a3 = uqnlin(y, hs, H, R, s, Q)\n\n\u03c3 = diag(\u03a3)\nfigure(figsize=(10,4))\nsubplot(121)\nvisualize_scalar_on_gauss_points(\u03c3, m, n, h)\ntitle(\"Standard Deviation\")\nsubplot(122)\nvisualize_scalar_on_gauss_points(abs.(run(sess, \u03bann)-\u03ba), m, n, h)\ntitle(\"Absolute Error\")\n", "meta": {"hexsha": "fbad9f16878b4dfc9b6fdf5dc62663aed12ea1fb", "size": 1714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "AdFemResearch/flow-model/uq_nn1.jl", "max_stars_repo_name": "ADCMEMarket/ADCMEImages", "max_stars_repo_head_hexsha": "d89df7050f53e56f3c509ff737199068410dbbc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdFemResearch/flow-model/uq_nn1.jl", "max_issues_repo_name": "ADCMEMarket/ADCMEImages", "max_issues_repo_head_hexsha": "d89df7050f53e56f3c509ff737199068410dbbc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdFemResearch/flow-model/uq_nn1.jl", "max_forks_repo_name": "ADCMEMarket/ADCMEImages", "max_forks_repo_head_hexsha": "d89df7050f53e56f3c509ff737199068410dbbc2", "max_forks_repo_licenses": ["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": 71, "alphanum_fraction": 0.6557759627, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7912493069124847}}
{"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": "using Test, FinancialMonteCarlo, DualNumbers;\n@show \"HestonModel\"\nS0 = 100.0;\nK = 100.0;\nr = 0.02;\nT = 1.0;\nd = 0.01;\nD = 90.0;\n\nNsim = 10000;\nNstep = 30;\nsigma = 0.2;\nsigma_zero = dual(0.2, 1.0);\nkappa = 0.01;\ntheta = 0.03;\nlambda = 0.01;\nrho_ = 0.0;\nmc = MonteCarloConfiguration(Nsim, Nstep);\nmc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());\ntoll = 0.8;\n\nrfCurve = ZeroRate(r);\n\nFwdData = Forward(T)\nEUData = EuropeanOption(T, K)\nAMData = AmericanOption(T, K)\nBarrierData = BarrierOptionDownOut(T, K, D)\nAsianData1 = AsianFloatingStrikeOption(T)\nAsianData2 = AsianFixedStrikeOption(T, K)\nModel = HestonProcess(sigma, sigma_zero, lambda, kappa, rho_, theta, Underlying(S0, d));\n\n@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);\n@show EuPrice = pricer(Model, rfCurve, mc, EUData);\n@show AmPrice = pricer(Model, rfCurve, mc, AMData);\n@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);\n@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianData1);\n@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianData2);\n\n@test abs(FwdPrice - 98.8790717426047) < toll\n@test abs(EuPrice - 7.9813557592924) < toll\n@test abs(BarrierPrice - 7.006564636309922) < toll\n@test abs(AsianPrice1 - 4.242256952013707) < toll\n\n@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);\n@show EuPrice = pricer(Model, rfCurve, mc1, EUData);\n@show AmPrice = pricer(Model, rfCurve, mc1, AMData);\n@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);\n@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianData1);\n@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianData2);\ntollanti = 0.8\n@test abs(FwdPrice - 98.8790717426047) < tollanti\n@test abs(EuPrice - 7.9813557592924) < tollanti\n@test abs(BarrierPrice - 7.006564636309922) < tollanti\n@test abs(AsianPrice1 - 4.242256952013707) < tollanti\n", "meta": {"hexsha": "fd880acf834768b89b8ac44dd6e196c9eb60dd1f", "size": 1812, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_heston_dual.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": "test/test_heston_dual.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": "test/test_heston_dual.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": 32.9454545455, "max_line_length": 88, "alphanum_fraction": 0.7290286976, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7912431616919122}}
{"text": "using PyCall, PyPlot\n\n## Example 1\npy\"\"\"\nimport numpy as np\ndef func(x, y):\n    return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2\n\"\"\"\n\nnp = pyimport(\"numpy\")\nscipy = pyimport(\"scipy\")\ninterpolate = pyimport(\"scipy.interpolate\")\ngriddata = interpolate.griddata\n\ns = pybuiltin(:slice)\nXY = get(np.mgrid, (s(0,1,100im), s(0,1,200im)))\ngrid_x, grid_y = XY[1,:,:], XY[2,:,:]\n\npoints = np.random.rand(1000, 2)\nvalues = py\"func\"(points[:,1], points[:,2])\n\ngrid_z0 = griddata(points, values, (grid_x, grid_y), method=\"nearest\")\ngrid_z1 = griddata(points, values, (grid_x, grid_y), method=\"linear\")\ngrid_z2 = griddata(points, values, (grid_x, grid_y), method=\"cubic\")\n\nplt.subplot(221)\nplt.imshow(py\"func\"(grid_x, grid_y), extent=(0,1,0,1), origin=\"lower\")\nplt.plot(points[:,1], points[:,2], \"k.\", ms=1)\nplt.title(\"Original\")\nplt.subplot(222)\nplt.imshow(grid_z0, extent=(0,1,0,1), origin=\"lower\")\nplt.title(\"Nearest\")\nplt.subplot(223)\nplt.imshow(grid_z1, extent=(0,1,0,1), origin=\"lower\")\nplt.title(\"Linear\")\nplt.subplot(224)\nplt.imshow(grid_z2, extent=(0,1,0,1), origin=\"lower\")\nplt.title(\"Cubic\")\nplt.gcf().set_size_inches(6, 6)\nplt.show()\n\n\n\n## Example 2\npy\"\"\"\ndef func(x, y):\n    return x + y\n\"\"\"\n\ns = pybuiltin(:slice)\nXY = get(np.mgrid, (s(0,1,5im),s(0,1,5im)))\ngrid_x, grid_y = XY[1,:,:], XY[2,:,:]\npoints = np.random.rand(25, 2)\nvalues = py\"func\"(points[:, 1], points[:, 2])\n\ngriddata(points, values, (grid_x, grid_y), method=\"nearest\")\ngriddata(points, values, (grid_x, grid_y), method=\"cubic\")\n\nusing PyPlot\nplt.plot(points[:,1], points[:,2], \"k.\", ms=1)\n\n## test 1\npy\"\"\"\ndef func(x, y, z):\n    return x + y + z\n\"\"\"\nnp = pyimport(\"numpy\")\nscipy = pyimport(\"scipy\")\ninterpolate = pyimport(\"scipy.interpolate\")\ngriddata = interpolate.griddata\n\ns = pybuiltin(:slice)\nXYZ = get(np.mgrid, (s(0,1,10im), s(0,1,20im), s(0,1,10im)))\ngrid_x, grid_y, grid_z = XYZ[1,:,:,:], XYZ[2,:,:,:], XYZ[3,:,:,:]\n\npoints = np.random.rand(1000, 3)\nvalues = py\"func\"(points[:,1], points[:,2], points[:,3])\n\ngrid_z0 = griddata(points, values, (grid_x, grid_y, grid_z), method=\"nearest\")\ngrid_z1 = griddata(points, values, (grid_x, grid_y, grid_z), method=\"linear\")\ngrid_z2 = griddata(points, values, (grid_x, grid_y, grid_z), method=\"cubic\")\n", "meta": {"hexsha": "1ba44eca48384827f53024d5b8c6096038615fb1", "size": 2227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Python/test_griddata.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": "test/Python/test_griddata.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": "test/Python/test_griddata.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": 27.1585365854, "max_line_length": 78, "alphanum_fraction": 0.6502020656, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7912431616919121}}
{"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\u03c0, 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) \u00f7 2\n    n2 = N \u00f7 2\n    x = LinRange{T}(0, \u03c0, 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# \u2554\u2550\u2561 dcfde69e-20c7-11eb-0108-dbd2f5cb0098\nbegin\n\tusing Pkg\n    Pkg.activate(pwd())\n\tPkg.instantiate()\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b6ed7820-20ce-11eb-0584-9130387e39ef\nmd\"\"\"\n# Solution:\nFirst, let's create a dummy dataset.\n\"\"\"\n\n# \u2554\u2550\u2561 85bf8990-20d4-11eb-1a7b-e35d9e62f35a\ngr();\n\n# \u2554\u2550\u2561 f5d95832-20ea-11eb-2828-39ebb61c877f\nmd\"\"\"\n### Utility functions\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 85976820-20d4-11eb-2afa-47a833fdccc4\nmd\"\"\"\n## Input Data\nFor this example, we'll use **iris** dataset.\n\"\"\"\n\n# \u2554\u2550\u2561 dcce4b20-20c7-11eb-3cb1-852a46b75c31\niris = dataset(\"datasets\", \"iris\") # DataFrame(rand(100, 10))\n\n# \u2554\u2550\u2561 dcb4a8a2-20c7-11eb-3a1a-9fb620e84e57\nsize(iris)\n\n# \u2554\u2550\u2561 dc975ca0-20c7-11eb-0a2b-b9e470c6e311\ndescribe(iris)\n\n# \u2554\u2550\u2561 9241d120-20d2-11eb-0b30-25249995c00c\nmd\"\"\"\n#### Let's create separate train and test datasets.\n\"\"\"\n\n# \u2554\u2550\u2561 b2a8ccc0-20d2-11eb-28eb-87dc018ae352\nXtrain = Array(iris[1:2:end,1:4])';\n\n# \u2554\u2550\u2561 afb22c8e-20d3-11eb-339a-09f39705a02f\nYtrain = Array(iris[1:2:end,5]);\n\n# \u2554\u2550\u2561 afe6aa10-20d3-11eb-03a4-89a46ade9feb\nXtest = Array(iris[2:2:end,1:4])';\n\n# \u2554\u2550\u2561 b0004c90-20d3-11eb-2b38-452b177600d8\nYtest = Array(iris[2:2:end,5]);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 399f2a20-20d4-11eb-1c3a-e76ac9707e29\nmean_iris = vec(mean(Xtrain, dims=2))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 39b65ba2-20d4-11eb-11bd-7daa396810ac\nC_iris = covm(Xtrain, mean_iris, 2);\n\n# \u2554\u2550\u2561 6493e090-20e3-11eb-0dec-0bdef8eb1c6a\nDataFrame(C_iris)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 39e24da0-20d4-11eb-10e5-8320e876fb74\neg = eigen(Symmetric(C_iris));\n\n# \u2554\u2550\u2561 b04fa510-20d3-11eb-0d40-21f2bf50e115\neg_values = eg.values\n\n# \u2554\u2550\u2561 f010e210-20e5-11eb-1952-37e6ed84ea22\neg_vectors = eg.vectors\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b1d8dc20-20de-11eb-1364-59fc5f488736\nord = sortperm(eg_values; rev=true)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b211ed80-20de-11eb-3abc-7f0b887915a5\ntvar = sum(eg_values)\n\n# \u2554\u2550\u2561 9fefec80-20e6-11eb-3e16-e5f17e1d9560\neg_values[ord] ./ tvar * 100\n\n# \u2554\u2550\u2561 b25a1a10-20de-11eb-3bcb-fbe70a5b974d\nbar(eg_values[ord] ./ tvar * 100, title=\"Scree Plot\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d6429920-20cf-11eb-0bf1-8f74c17dc643\nv, P = extract_kv(eg, ord, 1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d628f6a0-20cf-11eb-11cc-01f1ca2b6f13\ntr_data = transform(P, Xtest, mean_iris)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1081c390-20f8-11eb-3e81-133df7444871\nrecon_data = reconstruct(P, tr_data, mean_iris);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d5e95590-20cf-11eb-0d5f-e3e5f2be14c0\nDataFrame(recon_data)\n\n# \u2554\u2550\u2561 d5b26710-20cf-11eb-0f4c-7f81055af3e3\nDataFrame(Xtest[:, 1:5])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 740d6e20-20ec-11eb-1b12-1d614d3efb08\nv3, P3 = extract_kv(eg, ord, 3)\n\n# \u2554\u2550\u2561 7466b1b2-20ec-11eb-1a71-e7061e6a7ad6\nmd\"\"\"\nAgain, let's first transform and reconstruct the data using `P3`.\n\"\"\"\n\n# \u2554\u2550\u2561 747f1bb0-20ec-11eb-3cbf-a3a8d7a64563\ntr3_data = transform(P3, Xtest, mean_iris);\n\n# \u2554\u2550\u2561 65ce7a10-20fc-11eb-1d02-f57de17db24e\nsize(tr3_data)\n\n# \u2554\u2550\u2561 7493b520-20ec-11eb-0e19-57cbd43d09af\nrecon3_data = reconstruct(P3, tr3_data, mean_iris);\n\n# \u2554\u2550\u2561 74a9ae20-20ec-11eb-1e5d-7984c0a399f3\nDataFrame(recon3_data)\n\n# \u2554\u2550\u2561 ff1b4e90-20f8-11eb-3924-2fa0c61677fd\nDataFrame(Xtest[:, 1:5])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2014 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500a33c14a0-20c2-11eb-0bf8-837173d9d91c\n# \u255f\u2500cf5c9eb0-20c2-11eb-05ba-2f5dd23fdaf4\n# \u255f\u2500dcfde69e-20c7-11eb-0108-dbd2f5cb0098\n# \u255f\u2500b6ed7820-20ce-11eb-0584-9130387e39ef\n# \u2560\u2550864115a0-20d4-11eb-16ff-71d198f9342e\n# \u255f\u250085bf8990-20d4-11eb-1a7b-e35d9e62f35a\n# \u255f\u2500f5d95832-20ea-11eb-2828-39ebb61c877f\n# \u2560\u25500024d7b0-20eb-11eb-2959-af3584eb7750\n# \u255f\u250085976820-20d4-11eb-2afa-47a833fdccc4\n# \u2560\u2550dcce4b20-20c7-11eb-3cb1-852a46b75c31\n# \u2560\u2550dcb4a8a2-20c7-11eb-3a1a-9fb620e84e57\n# \u2560\u2550dc975ca0-20c7-11eb-0a2b-b9e470c6e311\n# \u255f\u25009241d120-20d2-11eb-0b30-25249995c00c\n# \u2560\u2550b2a8ccc0-20d2-11eb-28eb-87dc018ae352\n# \u2560\u2550afb22c8e-20d3-11eb-339a-09f39705a02f\n# \u2560\u2550afe6aa10-20d3-11eb-03a4-89a46ade9feb\n# \u2560\u2550b0004c90-20d3-11eb-2b38-452b177600d8\n# \u255f\u2500b02fe810-20d3-11eb-21f4-f9939c117c12\n# \u2560\u2550399f2a20-20d4-11eb-1c3a-e76ac9707e29\n# \u255f\u2500c58d8a10-20e1-11eb-301a-eb715e5926d8\n# \u2560\u255039b65ba2-20d4-11eb-11bd-7daa396810ac\n# \u255f\u25006493e090-20e3-11eb-0dec-0bdef8eb1c6a\n# \u255f\u2500c308e590-20e2-11eb-0ddb-055f8bdedb85\n# \u2560\u255039e24da0-20d4-11eb-10e5-8320e876fb74\n# \u2560\u2550b04fa510-20d3-11eb-0d40-21f2bf50e115\n# \u2560\u2550f010e210-20e5-11eb-1952-37e6ed84ea22\n# \u255f\u250035710110-20e5-11eb-0ad2-ef911c8d78bc\n# \u2560\u2550b1d8dc20-20de-11eb-1364-59fc5f488736\n# \u255f\u25006f9d6dfe-20e5-11eb-2745-e95f930eaf88\n# \u2560\u2550b211ed80-20de-11eb-3abc-7f0b887915a5\n# \u255f\u25009fefec80-20e6-11eb-3e16-e5f17e1d9560\n# \u2560\u2550b25a1a10-20de-11eb-3bcb-fbe70a5b974d\n# \u255f\u2500b26da210-20de-11eb-026b-8fc4efce305c\n# \u2560\u2550d6429920-20cf-11eb-0bf1-8f74c17dc643\n# \u255f\u250072f60020-20eb-11eb-049a-d14c26e12ddb\n# \u2560\u2550d628f6a0-20cf-11eb-11cc-01f1ca2b6f13\n# \u255f\u25006ae889c0-20eb-11eb-3ecb-4f13647511c3\n# \u2560\u25501081c390-20f8-11eb-3e81-133df7444871\n# \u255f\u25003313dc90-20f8-11eb-27eb-e9ea7e6a3805\n# \u2560\u2550d5e95590-20cf-11eb-0d5f-e3e5f2be14c0\n# \u2560\u2550d5b26710-20cf-11eb-0f4c-7f81055af3e3\n# \u255f\u25004cd4fb30-20c3-11eb-0631-a9c8840a4cf9\n# \u2560\u2550740d6e20-20ec-11eb-1b12-1d614d3efb08\n# \u255f\u25007466b1b2-20ec-11eb-1a71-e7061e6a7ad6\n# \u2560\u2550747f1bb0-20ec-11eb-3cbf-a3a8d7a64563\n# \u2560\u255065ce7a10-20fc-11eb-1d02-f57de17db24e\n# \u2560\u25507493b520-20ec-11eb-0e19-57cbd43d09af\n# \u2560\u255074a9ae20-20ec-11eb-1e5d-7984c0a399f3\n# \u2560\u2550ff1b4e90-20f8-11eb-3924-2fa0c61677fd\n# \u255f\u2500053f9290-20f9-11eb-1cb6-6f5c7b26e279\n# \u255f\u25009599eb10-20f9-11eb-044b-cd71da0c30a3\n# \u255f\u2500645934a0-20fb-11eb-1750-cf7ca28ab9e6\n# \u255f\u25004d526890-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    \u03b8 = norm(x)\n    if \u03b8 > 0.0\n        r = x ./ \u03b8\n        q = Quaternion(cos(0.5 * \u03b8), sin(0.5 * \u03b8) * 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    \u03b8 = norm(x)\n    if \u03b8 > 0.0\n        r = x ./ \u03b8\n\n        \u2202qw\u2202x = -0.5 * sin(0.5 * \u03b8) * transpose(x) ./ \u03b8\n        \u2202qx\u2202x = 0.5 * cos(0.5 * \u03b8) * transpose(x) ./ \u03b8 * r[1] + [sin(0.5 * \u03b8) / \u03b8 0.0 0.0] - sin(0.5 * \u03b8) * x[1] / \u03b8^2 * transpose(x) ./ \u03b8\n        \u2202qy\u2202x = 0.5 * cos(0.5 * \u03b8) * transpose(x) ./ \u03b8 * r[2] + [0.0 sin(0.5 * \u03b8) / \u03b8 0.0] - sin(0.5 * \u03b8) * x[2] / \u03b8^2 * transpose(x) ./ \u03b8\n        \u2202qz\u2202x = 0.5 * cos(0.5 * \u03b8) * transpose(x) ./ \u03b8 * r[3] + [0.0 0.0 sin(0.5 * \u03b8) / \u03b8] - sin(0.5 * \u03b8) * x[3] / \u03b8^2 * transpose(x) ./ \u03b8\n\n        return [\n                \u2202qw\u2202x;\n                \u2202qx\u2202x;\n                \u2202qy\u2202x;\n                \u2202qz\u2202x;\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\u03b8 = n1' * n2 # cosine\n\ts\u03b8 = norm(n3) # sine\n\taxis = n3 ./ reg(s\u03b8)\n\ttan\u03b8half = s\u03b8 / reg(1 + c\u03b8)\n\tq = [1; tan\u03b8half * 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\u00f2 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": "# ---\n# title: 69. Sqrt(x)\n# id: problem69\n# author: Tian Jun\n# date: 2020-10-31\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\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "743b8cbe235e004755d939330e939898c63f5b4d", "size": 842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/69.sqrtx.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/69.sqrtx.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/69.sqrtx.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.914893617, "max_line_length": 110, "alphanum_fraction": 0.5795724466, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.791114787507364}}
{"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,\u03b1=0.01, \u03bb=0.5, MaxGenerations = 15)\n    cuckoos = initialize_population(total_cuckoos)\n    println(\"Initial population of Cuckoos: \", length(cuckoos))\n    L = Levy(\u03bb)\n    best = nothing\n    t=1\n    while t < MaxGenerations\n        r_cuckoo = rand(cuckoos)\n        new_best = r_cuckoo[2] + \u03b1 * 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) * \u03a8(x)\n      #\n      # F(x_) := 2*x^2 - x\n      # C(a_) := -4a\n      # \u03a8(x_) := x^2 - x\n      #\n      #Y(x_) := F(x) + C(a)*\u03a8(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": "@testset \"NTT 1D\" begin\n    g = 2\n    q = 31\n    x = [1:5;]\n    @test intt(ntt(x, g, q), g, q) == x\n\n    g = 3\n    q = 257\n    x = [1:256;]\n    @test intt(ntt(x, g, q), g, q) == x\nend\n\n@testset \"NTT 1D convolution\" begin\n    using DSP\n\n    g = 9\n    q = 271\n    # padding inputs with zeros to get non circular convolution\n    x = [1:8; zeros(Int64, 7);]\n    h = [1:8; zeros(Int64, 7);]\n\n    X = ntt(x, g, q)\n    H = ntt(h, g, q)\n    Y = X .* H\n\n    y = intt(Y, g, q)\n    \n    @test y == DSP.conv(1:8, 1:8)\nend\n\n@testset \"NTT 2D\" begin\n    g = 16\n    q = 257\n    x = reshape([1:16;] , (4,4))\n    y = ntt(x, g, q)\n    @test intt(y, g, q) == x\n\n    g = 4\n    q = 17\n    x = reshape([1:16;] , (4,4))\n    y = ntt(x, g, q)\n    @test intt(y, g, q) == x\n\n    g = 7\n    q = 19\n    x = reshape([1:9;] , (3,3))\n    y = ntt(x, g, q)\n    @test intt(y, g, q) == x\nend\n\n@testset \"NTT 2D convolution\" begin\n    using DSP\n\n    (g, q, n) = (7, 4733, 7)\n   \n    #zero padding to get non circular convolution\n    x = reshape([1:16;] , (4,4))\n    x_padded = zeros(Int64, 7, 7)\n    x_padded[1:4, 1:4] = x\n    \n    h = reshape([4 3 2 0; 4 1 0 0; 0 0 1 2; 0 0 2 3] , (4,4))\n    h_padded = zeros(Int64, 7, 7)\n    h_padded[1:4, 1:4] = h\n\n    X = ntt(x_padded, g, q)\n    H = ntt(h_padded, g, q)\n    Y = X .* H\n\n    y = intt(Y, g, q)\n    \n    @test y == DSP.conv(x, h)\nend", "meta": {"hexsha": "54ce5db6da01d3d501b69fa17e92529e61bdf1b8", "size": 1344, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 18.6666666667, "max_line_length": 63, "alphanum_fraction": 0.4553571429, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551566309688, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7910783087973529}}
{"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, \u03c0))\n\n  result |> display\n  \n  yres = ytot[1,:]\n  vres = ytot[2,:]\n\n  let t = linspace(0.0, \u03c0, 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, \u03c0, 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, \u03c0, 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 \u2248 A[perm.indices[:], :]\n\n        @test lu_det(LU, perm.n_pivots) \u2248 det(A)\n\n        x = lu_solve(LU, perm, b)\n        @test A * x \u2248 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    \u03bb::AbstractVector{T}\n    \u025b::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.\u03bb\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)), \u025b = $(R.\u025b))\")\n\n## interface functions\n\"\"\"\n    fit(LEM, data; k=12, maxoutdim=2, \u025b=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* `\u025b`: 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, \u025b::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,\u025b))\n    D = spdiagm(0=>vec(sum(W, dims=2)))\n    L = D - W\n\n    \u03bb, V = decompose(L, D, maxoutdim)\n    return LEM{nntype, T}(\u03bb, \u025b, 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 .\u2265 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": "@testset \"collatz\" begin\n\n# A little puzzle inspired by the collatz conjecture, reach one by using the collatz conjecture moves (3n + 1 can be used even if the number is even)\nneighbours(n) = n % 2 == 0 ? [n \u00f7 2, 3n + 1] : [3n + 1]\n\n# The best case is if the number is a power of 2, then the moves are just the log2, otherwise this is a very optimistic heuristic (it doesn't overestimate)\nheuristic(n, goal) = floor(Int64, log2(n))\n\n@testset \"12\" begin\n  start = 12\n  res = astar(neighbours, start, 1; heuristic)\n  @test res.status == :success\n  @test res.path == [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]\n  @test res.cost == 9\nend\n\n@testset \"12 with maxcost\" begin\n  start = 12\n  res = astar(neighbours, start, 1; heuristic, maxcost=3)\n  @test res.status == :nopath\n  @test res.path == [12, 6, 3]\n  @test res.cost == 2\nend\n\n@testset \"12 with cost function\" begin\n  start = 12\n\n  # dividing costs 1, multiplying costs 4\n  cost(state, neighbour) = state / neighbour == 2 ? 1 : 4\n\n  res = astar(neighbours, start, 1; heuristic, cost)\n  @test res.status == :success\n  @test res.path == [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]\n  @test res.cost == 15\nend\n\n@testset \"12 with maxdepth\" begin\n  start = 12\n  res = astar(neighbours, start, 1; heuristic, maxdepth=3)\n  @test res.status == :nopath\n  @test res.path == [12, 6, 3]\n  @test res.cost == 2\nend\n\nend", "meta": {"hexsha": "5eda9ecd8d5490933267ebd89d65fbd5113b6787", "size": 1334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/collatz.jl", "max_stars_repo_name": "PaoloSarti/AStarSearch.jl", "max_stars_repo_head_hexsha": "c08d58db52537b70d5dd85cc45495dc2db60de9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-01-05T02:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T17:06:12.000Z", "max_issues_repo_path": "test/collatz.jl", "max_issues_repo_name": "PaoloSarti/AStarSearch.jl", "max_issues_repo_head_hexsha": "c08d58db52537b70d5dd85cc45495dc2db60de9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-28T15:29:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-28T15:29:43.000Z", "max_forks_repo_path": "test/collatz.jl", "max_forks_repo_name": "PaoloSarti/AStarSearch.jl", "max_forks_repo_head_hexsha": "c08d58db52537b70d5dd85cc45495dc2db60de9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-29T08:31:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T08:31:02.000Z", "avg_line_length": 29.6444444444, "max_line_length": 155, "alphanum_fraction": 0.6506746627, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7909825683893563}}
{"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\u221a(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": "function maxadjacent(M, pattern)\n\tH, W = size(M)\n\th, w = size(pattern)\n\n\tbestprod = 0\n\n\tfor i = 1:H-h+1\n\t\tfor j = 1:W-w+1\n\t\t\tm = M[i:i+h-1,j:j+w-1] .* pattern\n\t\t\tprintln(m)\n\t\t\tp = prod(m[pattern.==1])\n\t\t\tif p > bestprod\n\t\t\t\tbestprod = p\n\t\t\tend\n\t\tend\n\tend\n\n\treturn bestprod\nend\n\nfunction main()\n\tM = [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\t\n\tN = 4\n\n\tpatterns = {}\n\tpush!(patterns, ones(eltype(M), N, 1))\n\tpush!(patterns, ones(eltype(M), 1, N))\n\tpush!(patterns, eye(eltype(M), N))\n\tpush!(patterns, rotr90(eye(eltype(M), N)))\n\n\tbestprod = 0\n\tfor pattern in patterns\n\t\tn = maxadjacent(M, pattern)\n\t\tif n > bestprod\n\t\t\tbestprod = n\n\t\tend\n\tend\n\n\tprintln(bestprod)\nend\n\nmain()\n", "meta": {"hexsha": "2ce6aad40f5d2b027b39c21d23caef65df83918a", "size": 1852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem11.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": "problem11.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": "problem11.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": 29.3968253968, "max_line_length": 66, "alphanum_fraction": 0.6366090713, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7909613533141382}}
{"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\u00e9non\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\u00e9non 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\u00e9non 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\u00e9non 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": "x =3965421\ny = 569705405152896\n#operadores\n+x\n-x\nx + y\nx - y\nx * y\nx / y\nx \u00f7 y\nx \\ y\nx ^ y\nx % y\n2 % 3\n#not\n!true\n3*2/12\n-x+2\n\n#Bitwise\n~x #bitwise not\nbitstring(x)\nbitstring(y)\n\nbitstring(a)\nbitstring(b)\nbitstring(c)\na = x & y #bitwise and\nb = x | y #bitwise or\nc = x \u22bb y #bitwise xor\nx >>> 5\nbitstring(x >>> 5)  #logical shift right\n(x >> 5) < x\nbitstring(x >> 5)#arithmetic shift right\n(x << 5) > x\n\nbitstring(x << 5) #log/arithm shift left\n\n123 \u22bb 234\nxor(123, 234)\n~UInt32(123)\n\n#updating operator\nx += 1\n# += -= /= \\= \u00f7= %= ^= &= |= \u22bb= >>>= >>= <<=\n\n#\"dot\" operators\n#elemento por elemento\n[1 2 3] ^ 3\n[1 2 3] .^3\n[1,2,3] .* [2,3,4]\n\u2297(A,B) = kron(A,B) #produto de Kronecker\n[1 2 ; 3 4] \u2297 [0 5 ; 6 7]\n[1 2 ; 3 4] .\u2297 [0 5 ; 6 7]\n#Compara\u00e7\u00f5es\n# ==  !=,\u2260  <  <=,\u2264  >  >=,\u2265\n1\u22642\nInf>NaN\nNaN == NaN\nNaN < NaN\n[1 NaN] == [1 NaN]\nisequal(NaN, NaN)\nisfinite(x)\nisinf(x)\nisnan(x)\n-0.0 == 0.0\nisequal(-0.0, 0.0)\n\nv(x) = (println(x); x)\nv(1) < v(2) \u2264 v(3)\n\n0 .< [0 .5 1.5 .8] .< 1\nsin.([1 2 3])\n\n#ordem de precedencia na pag 51(71)\nBase.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.)\nBase.operator_precedence(:(=))\nBase.operator_precedence(:sin)\n\nBase.operator_associativity(:-), Base.operator_associativity(:+)\nBase.operator_associativity(:^)\nBase.operator_associativity(:sin)\n\n#Note that symbols such as :sin return precedence 0.\n#This value represents invalid operators and not operators\n#of lowest precedence.\n#Similarly, such operators are assigned associativity :none.\n\n#Conversions\nInt8(127.0)\nInt8(128)\nInt8(3.14)\n127 % Int8\n128 % Int8\nround(Int8, 127.4)\nround(Int8, 127.6)\n #ver Conversion and Promotion\ntypeof(round(2.5))\nx=7.568\n\n#Divisions\nfloor(x)\nceil(x)\ntrunc(x)\ny=2.0\nx/y\ndiv(x,y) #truncated division\nfld(x,y)\ncld(x,y)\nrem(x,y)\nx == div(x,y)y + rem(x,y)\nmod(x,y)\nx == fld(x,y)y + mod(x,y)\nmod1(x,y)\nmod2pi(x)\n0 <= mod2pi(x) < 2\u03c0\ndivrem(x,y)\nfldmod(x,y)\nx=49;y=56\ngcd(x,y) #MDC\nlcm(x,y) #MMC\nx=-49\n#Sinal abs\nabs(x)\nabs2(x)\nsign(x)\nsignbit(x)\ncopysign(y,x)\nflipsign(x,y)\n#x com sinal de x*y\n\nsin(x)\ncos(x)\ntan(x)\ncot(x)\nsec(x)\ncsc(x)\n\nsqrt(abs(x))\n\u221aabs(x)\ncbrt(abs(x))\n\u221babs(x)\nhypot(3,4)\nexp(1)\nexpm1(1) #e^x - 1\nldexp(1.0,8)\nlog(2)\nlog(\u212f,2)\nlog2(2)\nlog10(10)\nlog1p(0.0052)\n#log(1+x) for x near zero\nexponent(128.0)\nsignificand(128.0)\n\n#sinh cosh tanh coth sech csch\n#asin acos atan acot asec acsc\n#asinh acosh atanh acoth asech acsch\n#sinc cosc\n#These are all single-argument functions, with atan also accepting two\n#arguments corresponding to a traditional atan2 function.\n\n#Additionally, sinpi(x) and cospi(x) are provided for more accurate\n#computations of sin(pi*x) and cos(pi*x) respectively.\n\n#In order to compute trigonometric functions with degrees instead of radians,\n#suffix the function with d. For example, sind(x) computes the sine of x\n#where x is specified in degrees.\n\n#Mais fun\u00e7\u00f5es matem\u00e0ticas especiais em SpecialFunctions.jl\n\n#endcap\n", "meta": {"hexsha": "a65f98c999b7589911ccfd30e37185d8045a55f1", "size": 2898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/cap12.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/cap12.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/cap12.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": 16.7514450867, "max_line_length": 88, "alphanum_fraction": 0.6583850932, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.7909613445288294}}
{"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 knapsack problem\n\n# Formulate and solve a simple knapsack problem:\n#\n#     max sum(p_j x_j)\n#      st sum(w_j x_j) <= C\n#         x binary\n\nusing JuMP\nimport GLPK\nimport Test\n\nfunction example_knapsack(; verbose = true)\n    profit = [5, 3, 2, 7, 4]\n    weight = [2, 8, 4, 2, 5]\n    capacity = 10\n    model = Model(GLPK.Optimizer)\n    @variable(model, x[1:5], Bin)\n    ## Objective: maximize profit\n    @objective(model, Max, profit' * x)\n    ## Constraint: can carry all\n    @constraint(model, weight' * x <= capacity)\n    ## Solve problem using MIP solver\n    optimize!(model)\n    if verbose\n        println(\"Objective is: \", objective_value(model))\n        println(\"Solution is:\")\n        for i in 1:5\n            print(\"x[$i] = \", value(x[i]))\n            println(\", p[$i]/w[$i] = \", profit[i] / weight[i])\n        end\n    end\n    Test.@test termination_status(model) == MOI.OPTIMAL\n    Test.@test primal_status(model) == MOI.FEASIBLE_POINT\n    Test.@test objective_value(model) == 16.0\n    return\nend\n\nexample_knapsack()\n", "meta": {"hexsha": "f00873d17f6cb0c38cd73b0aeb32ce661e3f41a1", "size": 1374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/knapsack.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.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.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.5333333333, "max_line_length": 84, "alphanum_fraction": 0.6106259098, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7909604876151679}}
{"text": "using Diagonalizations, LinearAlgebra, PosDefManifold, Test\n\n# Method (1) real\nn, t=10, 100\nX=genDataMatrix(n, t)\nY=genDataMatrix(n, t)\nCx=Symmetric((X*X')/t)\nCy=Symmetric((Y*Y')/t)\nCxy=(X*Y')/t\nmC=mca(Cxy, simple=true)\n@test Cxy\u2248mC.F[1]*mC.D*mC.F[2]'\nD=mC.F[1]'Cxy*mC.F[2]\n@test norm(D-Diagonal(D))+1. \u2248 1.\n\n# Method (1) complex\nXc=genDataMatrix(ComplexF64, n, t)\nYc=genDataMatrix(ComplexF64, n, t)\nCxc=Symmetric((Xc*Xc')/t)\nCyc=Symmetric((Yc*Yc')/t)\nCxyc=(Xc*Yc')/t\nmCc=mca(Cxyc, simple=true)\n@test Cxyc\u2248mCc.F[1]*mCc.D*mCc.F[2]'\nDc=mCc.F[1]'Cxyc*mCc.F[2]\n@test norm(Dc-Diagonal(Dc))+1. \u2248 1.\n\n\n# Method (2) real\nmXY=mca(X, Y, simple=true)\nD=mXY.F[1]'*Cxy*mXY.F[2]\n@test norm(D-Diagonal(D))+1\u22481.\n@test mXY==mC\n\n# Method (2) complex\nmXYc=mca(Xc, Yc, simple=true)\nDc=mXYc.F[1]'*Cxyc*mXYc.F[2]\n@test norm(Dc-Diagonal(Dc))+1. \u2248 1.\n@test mXYc==mCc\n\n\n# Method (3) real\n# maximum covariance analysis of the average covariance and cross-covariance\nk=10\nXset=[genDataMatrix(n, t) for i=1:k]\nYset=[genDataMatrix(n, t) for i=1:k]\n\nm=mca(Xset, Yset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.5\nm=mca(Xset, Yset; eVar=0.5)\n\n# ... subtracting the mean from the matrices in Xset and Yset\nm=mca(Xset, Yset; meanX=nothing, meanY=nothing, eVar=0.5)\n\n# mca on the average of the covariance and cross-covariance matrices\n# computed along dims 1\nm=mca(Xset, Yset; dims=1, eVar=0.5)\n\n# name of the filter\nm.name\n\nusing Plots\n# plot regularized accumulated eigenvalues\nplot(m.arev)\n\n# plot the original cross-covariance matrix and the rotated\n# cross-covariance matrix\n Cmax=maximum(abs.(Cxy));\n h1 = heatmap(Cxy, clim=(-Cmax, Cmax), yflip=true, c=:bluesreds, title=\"Cxy\");\n D=mC.F[1]'*Cxy*mC.F[2];\n Dmax=maximum(abs.(D));\n h2 = heatmap(D, clim=(0, Dmax), yflip=true, c=:amp, title=\"F[1]'*Cxy*F[2]\");\n \ud83d\udcc8=plot(h1, h2, size=(700,300))\n# savefig(\ud83d\udcc8, homedir()*\"\\\\Documents\\\\Code\\\\julia\\\\Diagonalizations\\\\docs\\\\src\\\\assets\\\\FigMCA.png\")\n\n# Method (3) complex\n# maximum covariance analysis of the average covariance and cross-covariance\n\nk=10\nXcset=[genDataMatrix(ComplexF64, n, t) for i=1:k]\nYcset=[genDataMatrix(ComplexF64, n, t) for i=1:k]\n\nmc=mca(Xcset, Ycset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.5\nmc=mca(Xcset, Ycset; eVar=0.5)\n\n# ... subtracting the mean from the matrices in Xset and Yset\nmc=mca(Xcset, Ycset; meanX=nothing, meanY=nothing, eVar=0.5)\n\n# mca on the average of the covariance and cross-covariance matrices\n# computed along dims 1\nmc=mca(Xcset, Ycset; dims=1, eVar=0.5)\n\n# name of the filter\nmc.name\n", "meta": {"hexsha": "8ade22f65542781c507d576fa40af9d7ba8e1b4a", "size": 2557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/MCA.jl", "max_stars_repo_name": "ericphanson/Diagonalizations.jl", "max_stars_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/MCA.jl", "max_issues_repo_name": "ericphanson/Diagonalizations.jl", "max_issues_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/MCA.jl", "max_forks_repo_name": "ericphanson/Diagonalizations.jl", "max_forks_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": 26.6354166667, "max_line_length": 99, "alphanum_fraction": 0.6969104419, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8519528094861981, "lm_q1q2_score": 0.790960485984925}}
{"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 # ``\u03b6(-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": "using NumericalMethodsforEngineers\nusing Test\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  function f3(x::Float64, y::Vector{Float64})\n    [y[2], -2y[2]/y[1]]\n  end\n\n  (iters, nsteps, converged, res) = shootingmethod(f3, [0.0, 1.0, 1.0, 2.0], [1.0, 3.0], \n    10, 0.000001, 80)\n\n  if !converged\n    println(\"No conversion achieved.\")\n  elseif iters > 50\n    println(\"Iter limit reached.\")\n  else\n    @test round.(res[:, 2], digits=4)' == \n      [1.0  1.1742  1.321  1.4471  1.5569  1.6534  1.7389  1.8151  1.8833  1.9446  2.0]\n    #println()\n    #res |> display\n  end\n\nend", "meta": {"hexsha": "5ca66934124443023e7e38bfcf046a00df102ed0", "size": 575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch07_bvp_ex7.4b.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_bvp_ex7.4b.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_bvp_ex7.4b.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.0, "max_line_length": 89, "alphanum_fraction": 0.6052173913, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.790960482552426}}
{"text": "module paqueteFourier\n\nimport Base: +, -, *, /\n\nimport Gadfly\n\n# Notar que los m\u00e9todos de +, -, *, / y diff se exportan solos\nexport trigPoly, innerProduct, nodes, vals, tpfplot\n\n# El objeto b\u00e1sico de este paquete es un trigPoly, cuyo campo coefs contiene\n# los coeficientes de la representaci\u00f3n de un polinomio trigonom\u00e9trico como\n# combinaci\u00f3n lineal de 1, exp(-im\u00a0\u03b8), exp(im\u00a0\u03b8), exp(-2im\u00a0\u03b8), exp(2im \u03b8), \u2026,\n# en ese orden.\n# Junto a la definici\u00f3n de este 'type' Julia autom\u00e1ticamente deja disponible un\n# constructor, que es una funci\u00f3n que recibe un vector de n\u00fameros complejos y\n# devuelve un trigPoly con ese vector en el campo coefs.\n# A continuaci\u00f3n justificar\u00e9 mi elecci\u00f3n de ordenamiento para los coeficientes\n# con la ayuda de una tabla.  Denoto al orden elegido (0, -1, 1, -2, 2, \u2026) por\n# A, al orden visto en clase (-N/2, -N/2+1, \u2026, -1, 0, 1, \u2026, N/2-2, N/2) por B y\n# al orden por defecto de la FFT (0, 1, \u2026, N/2-1, -N/2, -N/2+1, \u2026, -1) por C (B\n# y C son ligeramente distintos si N es impar, pero la tabla sigue valiendo).\n#                                 \u250c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2510\n#                                 \u2502 A \u2502 B \u2502 C \u2502\n# \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2524\n# \u2502                          Suma \u2502 \u2713 \u2502 \u2717 \u2502 \u2717 \u2502\n# \u2502Interpretaci\u00f3n de coeficientes \u2502 \u2713 \u2502 \u2717 \u2502 ~ \u2502\n# \u2502     Vector de n\u00fameros de onda \u2502 ~ \u2502 \u2713 \u2502 \u2717 \u2502\n# \u2502           Interpolaci\u00f3n (FFT) \u2502 \u2717 \u2502 ~ \u2502 \u2713 \u2502\n# \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2524\n# \u2502   \u2713 = F\u00e1cil, ~ = Moderado, \u2717 = Dif\u00edcil    \u2502\n# \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\"\"\"\n    trigPoly(x)\n\nPolinomio trigonom\u00e9trico que es combinaci\u00f3n lineal de 1,\u00a0exp(-im\u00a0\u03b8), exp(im\u00a0\u03b8), exp(-2im\u00a0\u03b8), \u2026 con los coeficientes indicados en `x`.\n\"\"\"\ntype trigPoly\n\tcoefs::Vector{Complex128}\nend\n\n\"\"\"\n    innerProduct(f,g)\n\nProducto interior L\u00b2 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\u03c0*ac\nend\n\n# Sin cargar ning\u00fan paquete Julia ya tiene una funci\u00f3n llamada norm; la nuestra\n# ser\u00e1 un m\u00e9todo m\u00e1s\n\"\"\"\n    norm(f::trigPoly)\n\nNorma L\u00b2 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\u03c0*(0:n-1)/n\nend\n\n# Funci\u00f3n que transforma un vector del orden C al orden A; Julia reemplazar\u00e1 T\n# con el tipo de n\u00famero que contenga el vector con el cual se alimente a esta\n# funci\u00f3n\nfunction reordering{T}(v::Vector{T})\n\tn = length(v)\n\tout = Vector{T}(n) # Reserva de memoria\n\tfloorhalfn = n\u00f72\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\u00f3n que transforma un vector del orden A al orden C\nfunction reverse_reordering{T}(v::Vector{T})\n\tn = length(v)\n\tfloorhalfn = n\u00f72\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\u00f3n\n# de una funci\u00f3n 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\u00e9trico que interpola a la funci\u00f3n `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\u00f3n del polinomio trigonom\u00e9trico `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\u00f3n del polinomio trigonom\u00e9trico `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\u00eda escribir exp(im*x), pero si x es escalar Julia emite una\n\t# advertencia (no un error) que invita a usar la versi\u00f3n 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\u00fan 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\u00e1sica 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\u00f3n y divisi\u00f3n 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\u00f3n\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#             \u2193     modo     \u2193\n\t\tretcoefs[k] = (-1)^(k+1)*(k\u00f72) * im * f.coefs[k]\n\tend\n\ttrigPoly(retcoefs)\nend\n\n\"\"\"\n    diff(f::trigPoly, k::Int64)\n\n`k`-\u00e9sima 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\u00e9trico (trigPoly) o funci\u00f3n (Function) `f` o a la colecci\u00f3n de polinomios trigonom\u00e9tricos 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\u03c0\n\t\t\tx = [x;2\u03c0]\n\t\t\tvfix = [vfix;vfix[1]]\n\t\t\t# Ahora los puntos con abscisas en la colecci\u00f3n 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\u03c0,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(\"\u03b8\"), Gadfly.Guide.YLabel(\"\"), Gadfly.Guide.Title(\"Real part\"), Gadfly.Coord.cartesian(xmin=0, xmax=2\u03c0), Gadfly.Theme(key_position=:bottom), labelSpecification),\n\t       Gadfly.plot(layersImag..., Gadfly.Guide.XLabel(\"\u03b8\"), Gadfly.Guide.YLabel(\"\"), Gadfly.Guide.Title(\"Imaginary part\"), Gadfly.Coord.cartesian(xmin=0, xmax=2\u03c0), 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": "# Test for GaussLobatto()\nn = 2\nx,w = gausslobatto(n)\n@test x[1] \u2248 -1.\n@test x[2] \u2248 1.\n@test w[1] \u2248 1.\n@test w[2] \u2248 1.\n\nn = 3\nx,w = gausslobatto(n)\n@test x[1] \u2248 -1.\n@test abs(x[2])<1e-15\n@test x[3] \u2248 1.\n@test w[1] \u2248 1/3\n@test w[2] \u2248 4/3\n@test w[3] \u2248 1/3\n\ntol = 1e-14\nn = 42\nx,w = gausslobatto(n)\n@test ( length(x) == n) && ( length(w) == n )\n@test abs(x[37] - 0.922259214258616) < tol\n@test abs(w[37] - 0.029306411216166) < tol\n@test ( x[1] == -1 && x[n] == 1 )\n\n@test dot( w,(x.^2)) \u2248 2/3\n@test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\n", "meta": {"hexsha": "af111aeb871dec088185f8d1774dee991f7de53a", "size": 529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gausslobatto.jl", "max_stars_repo_name": "timueh/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_stars_repo_licenses": ["MIT"], "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_gausslobatto.jl", "max_issues_repo_name": "timueh/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_issues_repo_licenses": ["MIT"], "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_gausslobatto.jl", "max_forks_repo_name": "timueh/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_forks_repo_licenses": ["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.8928571429, "max_line_length": 45, "alphanum_fraction": 0.5236294896, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.790927839987032}}
{"text": "using NURBS\nusing Base.Test\n\n@testset \"Rbsurfaces Building\" begin\n    \n\tvec = [-100.0 -100.0 -100.0 -100.0 -100.0 -50.0 -50.0 -50.0 -50.0 -50.0 0.0 0.0 0.0 0.0 0.0 50.0 50.0 50.0 50.0 50.0 100.0 100.0 100.0 100.0 100.0;-100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0;0.0 0.0 0.0 0.0 0.0 0.0 25.0 50.0 25.0 0.0 0.0 25.0 50.0 25.0 0.0 0.0 25.0 150.0 25.0 0.0 0.0 0.0 0.0 0.0 0.0; 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0]\n\n\tres = [-100.0 -100.0 -100.0 -100.0 -25.9259 -25.9259 -25.9259 -25.9259 25.9259 25.9259 25.9259 25.9259 100.0 100.0 100.0 100.0; -100.0 -25.9259 25.9259 100.0 -100.0 -25.9259 25.9259 100.0 -100.0 -25.9259 25.9259 100.0 -100.0 -25.9259 25.9259 100.0; 0.0 0.0 0.0 0.0 0.0 34.8422 34.8422 0.0 0.0 51.3032 51.3032 0.0 0.0 0.0 0.0 0.0]\n\n    @testset \"rational B-spline surface using an open uniform knot vector\" begin\n        @test typeof(rbspsurf(vec,4,4,5,5,100,100)) == Tuple{Array{Float64, 2}, Array{Array{Int64, 1}, 1}, Array{Array{Int64, 1}, 1}}\n        @test isapprox(rbspsurf(vec,4,4,5,5,4,4)[1], res; atol=1e-3)\n    end\nend\n", "meta": {"hexsha": "e1053ec4c24d088e94a567918a7be452493ae672", "size": 1200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rbsurfaces.jl", "max_stars_repo_name": "eOnofri04/IN480", "max_stars_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-06T17:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:30:18.000Z", "max_issues_repo_path": "test/rbsurfaces.jl", "max_issues_repo_name": "TheChoice04/IN480", "max_issues_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-11-22T18:10:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-07T16:32:36.000Z", "max_forks_repo_path": "test/rbsurfaces.jl", "max_forks_repo_name": "TheChoice04/IN480", "max_forks_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-13T14:02:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-13T14:02:03.000Z", "avg_line_length": 80.0, "max_line_length": 499, "alphanum_fraction": 0.6066666667, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7909278349795166}}
{"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\u03c0*\u03c0) .+ 5x[1]/\u03c0 .- 6).^2 + 10(1 - 1/(8\u03c0)).*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\u00d7n`` 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, \u03b1::Float64)\n\nApply alpha-transform with Helmert product to ``X``\n\"\"\"\nfunction alphaTransform(X::Matrix{Float64}, \u03b1::Float64)\n    D = size(X,2)\n    H = Helmert(D)[2:end,:]\n    X\u1d43 = X.^\u03b1\n    Xs = sum(X\u1d43, dims=2)    \n    U = (D*X\u1d43./Xs .- 1)./\u03b1\n    return U*transpose(H)    \nend\n\n\n\"\"\"\n    alpha(X::Matrix, \u03b1::Float64)\n\nApply alpha-transform without Helmert product\n\"\"\"\nfunction alpha(X::Matrix{Float64}, \u03b1::Float64)\n    D = size(X,2)\n#    H = Helmert(D)[2:end,:]\n    X\u1d43 = X.^\u03b1\n    Xs = sum(X\u1d43,dims=2)    \n    U = (D*X\u1d43./Xs .- 1)./\u03b1\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": "using Test\nusing StaticArrays, IntervalSets\nimport ClimaCore.DataLayouts: IJFH\nimport ClimaCore:\n    Fields, Domains, Meshes, Topologies, Spaces, Operators, Geometry\nusing StaticArrays, IntervalSets, LinearAlgebra\n\nFT = Float64\n\nradius = FT(1)\ndomain = Domains.SphereDomain(radius)\n\ngrad = Operators.Gradient()\nwgrad = Operators.WeakGradient()\n\n@testset \"gradient\" begin\n    Ne = 5\n    Nq = 6\n\n    mesh = Meshes.EquiangularCubedSphere(domain, Ne)\n    grid_topology = Topologies.Topology2D(mesh)\n\n    quad = Spaces.Quadratures.GLL{Nq}()\n    space = Spaces.SpectralElementSpace2D(grid_topology, quad)\n    coords = Fields.coordinate_field(space)\n\n    \u03b7 = @. sind(coords.long) * cosd(coords.lat)\n    \u2207\u03b7 = grad.(\u03b7)\n    \u2207\u03b7_w = wgrad.(\u03b7)\n    \u2207\u03b7_local = Geometry.transform.(Ref(Geometry.UVAxis()), \u2207\u03b7)\n    \u2207\u03b7w_local = Geometry.transform.(Ref(Geometry.UVAxis()), \u2207\u03b7_w)\n    Spaces.weighted_dss!(\u2207\u03b7_local)\n    Spaces.weighted_dss!(\u2207\u03b7w_local)\n\n    \u2207\u03b7_exact = @. Geometry.UVVector(\n        cosd(coords.long) / radius,\n        -sind(coords.long) * sind(coords.lat) / radius,\n    )\n\n    @test \u2207\u03b7_local \u2248 \u2207\u03b7_exact rtol = 1e-2\n    @test \u2207\u03b7w_local \u2248 \u2207\u03b7_exact rtol = 1e-2\n\nend\n\n\"\"\"\n    convergence_rate(err, \u0394h)\nEstimate convergence rate given vectors `err` and `\u0394h`\n    err = C \u0394h^p+ H.O.T\n    err_k \u2248 C \u0394h_k^p\n    err_k/err_m \u2248 \u0394h_k^p/\u0394h_m^p\n    log(err_k/err_m) \u2248 log((\u0394h_k/\u0394h_m)^p)\n    log(err_k/err_m) \u2248 p*log(\u0394h_k/\u0394h_m)\n    log(err_k/err_m)/log(\u0394h_k/\u0394h_m) \u2248 p\n\"\"\"\nconvergence_rate(err, \u0394h) =\n    [log(err[i] / err[i - 1]) / log(\u0394h[i] / \u0394h[i - 1]) for i in 2:length(\u0394h)]\n\n@testset \"convergence tests for the gradient operator on the sphere\" begin\n    Nes = [3, 9, 27]\n    Nqs = [4, 6]\n\n    for (Iq, Nq) in enumerate(Nqs)\n        err_sgrad = Array{FT}(undef, length(Nes))\n        err_wgrad = Array{FT}(undef, length(Nes))\n        \u0394h = Array{FT}(undef, length(Nes))\n\n        for (Ie, Ne) in enumerate(Nes)\n            mesh = Meshes.EquiangularCubedSphere(domain, Ne)\n            grid_topology = Topologies.Topology2D(mesh)\n\n            quad = Spaces.Quadratures.GLL{Nq}()\n            space = Spaces.SpectralElementSpace2D(grid_topology, quad)\n            coords = Fields.coordinate_field(space)\n\n            \u03b7 = @. sind(coords.long) * cosd(coords.lat)\n            \u2207\u03b7 = grad.(\u03b7)\n            \u2207\u03b7_w = wgrad.(\u03b7)\n            \u2207\u03b7_local = Geometry.transform.(Ref(Geometry.UVAxis()), \u2207\u03b7)\n            \u2207\u03b7w_local = Geometry.transform.(Ref(Geometry.UVAxis()), \u2207\u03b7_w)\n            Spaces.weighted_dss!(\u2207\u03b7_local)\n            Spaces.weighted_dss!(\u2207\u03b7w_local)\n\n            \u2207\u03b7_exact = @. Geometry.UVVector(\n                cosd(coords.long) / radius,\n                -sind(coords.long) * sind(coords.lat) / radius,\n            )\n\n            err_sgrad[Ie] = norm(\u2207\u03b7_local .- \u2207\u03b7_exact)\n            err_wgrad[Ie] = norm(\u2207\u03b7w_local .- \u2207\u03b7_exact)\n            \u0394h[Ie] = 1 / Ne\n\n        end\n\n        convergence_rate_sgrad = convergence_rate(err_sgrad, \u0394h)\n        convergence_rate_wgrad = convergence_rate(err_wgrad, \u0394h)\n\n        for Ie in range(1, length = length(Nes) - 1)\n            @test convergence_rate_sgrad[Ie] \u2248 (Nq - 1) atol = 0.1\n            @test convergence_rate_wgrad[Ie] \u2248 (Nq - 1) atol = 0.1\n        end\n\n    end\n\nend\n", "meta": {"hexsha": "00d347a99916c97ce3ccc337f70c1e69a797f717", "size": 3189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sphere_gradient.jl", "max_stars_repo_name": "CliMA/ClimaCore.jl", "max_stars_repo_head_hexsha": "e28309249a4c0dea0e8bb897b4dc9ebc376fa94e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-07-19T20:14:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T00:18:43.000Z", "max_issues_repo_path": "test/sphere_gradient.jl", "max_issues_repo_name": "CliMA/ClimaCore.jl", "max_issues_repo_head_hexsha": "e28309249a4c0dea0e8bb897b4dc9ebc376fa94e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 543, "max_issues_repo_issues_event_min_datetime": "2021-07-06T18:21:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:39:02.000Z", "max_forks_repo_path": "test/sphere_gradient.jl", "max_forks_repo_name": "CliMA/ClimateMachineCore.jl", "max_forks_repo_head_hexsha": "73dff5e125aa641b1560f3ca5163db472c1ed07a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-27T16:54:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T16:54:21.000Z", "avg_line_length": 30.3714285714, "max_line_length": 77, "alphanum_fraction": 0.6127312637, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7908659438216613}}
{"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, \u03bcp, \u03bcn)\n\nPerforms LDA given a covariance matrix `C` and both mean vectors `\u03bcp` & `\u03bcn`.  Returns a linear discriminant functional of type [`LinearDiscriminant`](@ref).\n\n*Parameters*\n- `C`: The pooled covariane matrix (*i.e* ``(Cp + Cn)/2``)\n- `\u03bcp`: The mean vector of the positive class.\n- `\u03bcn`: The mean vector of the negative class.\n\"\"\"\nfunction ldacov(C::DenseMatrix{T},\n                \u03bcp::DenseVector{T},\n                \u03bcn::DenseVector{T}) where T<:Real\n\n    w = cholesky(C) \\ (\u03bcp - \u03bcn)\n    ap = w \u22c5 \u03bcp\n    an = w \u22c5 \u03bcn\n    c = 2 / (ap - an)\n    LinearDiscriminant(rmul!(w, c), 1 - c * ap)\nend\n\n\"\"\"\n    ldacov(Cp, Cn, \u03bcp, \u03bcn)\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- `\u03bcp`: The mean vector of the positive class.\n- `\u03bcn`: The mean vector of the negative class.\n\n**Note:** The coefficient vector is scaled such that ``w'\u03bcp + b = 1`` and ``w'\u03bcn + b = -1``.\n\"\"\"\nldacov(Cp::DenseMatrix{T},\n       Cn::DenseMatrix{T},\n       \u03bcp::DenseVector{T},\n       \u03bcn::DenseVector{T}) where T<:Real = ldacov(Cp + Cn, \u03bcp, \u03bcn)\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    \u03bcp = vec(mean(Xp, dims=2))\n    \u03bcn = vec(mean(Xn, dims=2))\n    Zp = Xp .- \u03bcp\n    Zn = Xn .- \u03bcn\n    Cp = calcscattermat(covestimator, Zp)\n    Cn = calcscattermat(covestimator, Zn)\n    ldacov(Cp, Cn, \u03bcp, \u03bcn)\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 \u2265 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- `\u03bb`: 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    \u03bb::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.\u03bb\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 \u2265 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, \u03a3w, _ = svd(Hw, full=false)\n    keep = \u03a3w .> sqrt(eps(T)) * maximum(\u03a3w)\n    projw = Uw[:,keep]\n    pHb = projw' * Hb\n    pHw = projw' * Hw\n    \u03bb, G = lda_gsvd(pHb, pHw, cweights)\n    SubspaceLDA(projw, G, \u03bb, 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, \u03a3A, 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    \u03bb = diag(Gb * Gb')./diag(Gw * Gw')\n    \u03bb, 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}; \u03b5::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.+\u03b5), -g./(p.+\u03b5)\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": "test(\"BWS statistic\") do\n\n  test(\"a small hand-calculated BWS case with 2 elements in each sample\") do\n\n    x = [1.0, 2.0]\n    n = 2\n    y = [3.0, 4.0]\n    m = 2\n\n    r = [1, 2] # ranks for values in x\n    s = [3, 4] # ranks for values in y\n\n    mn = m+n\n    mp1 = m+1\n    np1 = n+1\n\n    b_x_part_for_i_1 = (r[1] - 1*mn/n)^2 / ( (1/np1) * (1 - 1/np1) * (m * mn / n) )\n    b_x_part_for_i_2 = (r[2] - 2*mn/n)^2 / ( (2/np1) * (1 - 2/np1) * (m * mn / n) )\n    b_x = (1 / n) * ( b_x_part_for_i_1 + b_x_part_for_i_2 )\n\n    b_y_part_for_i_1 = (s[1] - 1*mn/m)^2 / ( (1/mp1) * (1 - 1/mp1) * (n * mn / m) )\n    b_y_part_for_i_2 = (s[2] - 2*mn/m)^2 / ( (2/mp1) * (1 - 2/mp1) * (n * mn / m) )\n    b_y = (1 / m) * ( b_y_part_for_i_1 + b_y_part_for_i_2 )\n\n    b = (b_x + b_y) / 2\n\n    @t FeldtLib.bws_statistic(x, y) == b\n\n    bwst = FeldtLib.BWSTest(x, y)\n    @t bwst.b == FeldtLib.bws_statistic(x, y)\n    @t bwst.n == n\n    @t bwst.m == m\n\n  end\n\n  test(\"a small hand-calculated BWS case with 3+2 elements\") do\n\n    x = [1.0, 2.0, 5.0]\n    n = 3\n    y = [3.0, 4.0]\n    m = 2\n\n    r = [1, 2, 5] # ranks for values in x\n    s = [3, 4] # ranks for values in y\n\n    mn = m+n\n    mp1 = m+1\n    np1 = n+1\n\n    bx1 = (r[1] - 1*mn/n)^2 / ( (1/np1) * (1 - 1/np1) * (m * mn / n) )\n    bx2 = (r[2] - 2*mn/n)^2 / ( (2/np1) * (1 - 2/np1) * (m * mn / n) )\n    bx3 = (r[3] - 3*mn/n)^2 / ( (3/np1) * (1 - 3/np1) * (m * mn / n) )\n    bx = (1 / n) * ( bx1 + bx2 + bx3)\n\n    by1 = (s[1] - 1*mn/m)^2 / ( (1/mp1) * (1 - 1/mp1) * (n * mn / m) )\n    by2 = (s[2] - 2*mn/m)^2 / ( (2/mp1) * (1 - 2/mp1) * (n * mn / m) )\n    by = (1 / m) * ( by1 + by2 )\n\n    b = (bx + by) / 2\n\n    @t FeldtLib.bws_statistic(x, y) == b\n\n    bwst = FeldtLib.BWSTest(x, y)\n    @t bwst.b == FeldtLib.bws_statistic(x, y)\n    @t bwst.n == n\n    @t bwst.m == m\n\n  end\n\n  test(\"example from Neuhauser 2004 paper, in table 3\") do\n\n    control_group_ranks = [1, 2, 3, 4, 6, 7, 8]\n    experimental_group_ranks = [5, 9, 10, 11, 12, 13, 14]\n    rs = vcat(control_group_ranks, experimental_group_ranks)\n    n = length(control_group_ranks)\n    m = length(experimental_group_ranks)\n    @t isapprox(FeldtLib.bws_statistic_from_ranks(rs, n, m), 5.132; atol = 0.001)\n\n    b, pvalue, m, sd = r = FeldtLib.bws_test_sampled_from_ranks(rs, n, m, 10000) \n\n    # The exact p-value calculated by Neuhauser was 0.0029 so we should be close\n    # to that.\n    @t isapprox(pvalue, 0.0029; atol = 0.001)\n\n  end\n\nend", "meta": {"hexsha": "456e9238764f32d589c97c3a6cb89bd4aa95596d", "size": 2430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_baumgartner_weis_schindler.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": "test/test_baumgartner_weis_schindler.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": "test/test_baumgartner_weis_schindler.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": 27.9310344828, "max_line_length": 83, "alphanum_fraction": 0.5098765432, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7908613845872405}}
{"text": "using NumericalMethodsforEngineers\n\na = [16. 4. 8.; 4. 5. -4.; 8. -4. 22.]\nb = [16., 18., -22.]\n\na = sparse(a)\n\nF = cholfact(a)\nupper = F[:U]\nupper |> display\n\nlower = F[:L]\nlower |> display\n\ny = lower \\ b\n\nc = upper \\ y\nprintln(\"Solution Vector: \\n $c\")\n\n@test c == a \\ b", "meta": {"hexsha": "fb17888179d18dc7b23979e694c2b6c196f90c37", "size": 272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/p_02_06.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/ch02/p_02_06.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/ch02/p_02_06.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": 13.6, "max_line_length": 38, "alphanum_fraction": 0.5588235294, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7908607726848174}}
{"text": "\"\"\"\n    D\u1d9c(N, \u0394)\n\nReturns a discrete 1D derivative operator for taking the derivative of a face-centered field with `N+1` grid points and `\u0394` grid spacing and producing a cell-centered field with `N` grid points.\n\"\"\"\nfunction D\u1d9c(N, \u0394)\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/\u0394 * D\n    return D\nend\n\n\"\"\"\n    D\u1da0(N, \u0394)\n\nReturns a discrete 1D derivative operator for taking the derivative of a cell-centered field with `N` grid points and `\u0394` grid spacing and producing a face-centered field with `N+1` grid points.\n\"\"\"\nfunction D\u1da0(N, \u0394)\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/\u0394 * 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    - \u2211 x < v(N)\n    - \u2211\u209b x < v(S) \u2200 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\u2212(\\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 .* \u03c0 .* (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\u2081 = zeros(Float64, size(p))\n    Z\u2082 = zeros(Float64, size(p))\n\n    #path 1\n    for i = 2:R\n        Z\u2081[i,1] = Z\u2081[i-1,1] - q[i,1]\n    end\n    for i = 1:R\n        for j = 2:C\n            Z\u2081[i,j] = Z\u2081[i,j-1] + p[i,j]\n        end\n    end\n\n    #path 2\n    for i = 2:C\n        Z\u2082[1,i] = Z\u2082[1,i-1] + p[1,i]\n    end\n    for i = 2:R\n        for j = 1:C\n            Z\u2082[i,j] = Z\u2082[i-1,j] - q[i,j]\n        end\n    end\n    Z = (Z\u2081 .+ Z\u2082) / 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(\u03f5::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## `\u03f5`:\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(\u03f5 = 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    \u03f5 = copy(scheme.\u03f5)\n    Z = zeros(Float64, size(p))\n    Z\u1d4f\u207a\u00b9 = 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] = (\u03f5 / 4) * (h[i,j] - v[i,j])\n        end\n    end\n    for k = 1:iter\n        copyto!(Z\u1d4f\u207a\u00b9, Z)\n        for i = 2:(R-1)\n            for j = 2:(C-1)\n                Z\u1d4f\u207a\u00b9[i,j] = (Z[i-1,j] + Z[i+1,j] + Z[i,j-1] + Z[i,j+1]) / 4.0\n                Z\u1d4f\u207a\u00b9[i,j] = Z\u1d4f\u207a\u00b9[i,j] - hv[i,j]\n            end\n        end\n        Z = Z\u1d4f\u207a\u00b9\n    end\n    return Z\nend\n\n@doc raw\"\"\"\n```\nDurou(\u03f5::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## `\u03f5`:\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(\u03f5 = 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\u00e9au, 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    \u03f5 = copy(scheme.\u03f5)\n    Z = zeros(Float64, size(p))\n    Z\u1d4f\u207a\u00b9 = 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] = (\u03f5 / 2) * (h[i,j] - v[i,j])\n        end\n    end\n    for k = 1:iter\n        copyto!(Z\u1d4f\u207a\u00b9, Z)\n        for i = 1:(R-1)\n            for j = 1:(C-1)\n                Z\u1d4f\u207a\u00b9[i,j] = (Z[i+1,j] + Z[i,j+1]) / 2\n                Z\u1d4f\u207a\u00b9[i,j] = Z\u1d4f\u207a\u00b9[i,j] - hv[i,j]\n            end\n        end\n        Z = Z\u1d4f\u207a\u00b9\n    end\n    return Z\nend\n\n# Generates matricies D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a and D\u1d65\u207b as per eq 11, 12, 13, 14 and 17\nfunction gen_matrix(D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a, D\u1d65\u207b,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\u1d64\u207a[i[1]+(i[2]-1)*U, i[1]+(i[2]-1)*U] = -1.0\n            D\u1d64\u207a[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\u1d64\u207b[i[1]+(i[2]-1)*U, i[1]+(i[2]-1)*U] = 1.0\n            D\u1d64\u207b[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\u1d65\u207a[i[1]+(i[2]-1)*V, i[1]+(i[2]-1)*V] = -1.0\n            D\u1d65\u207a[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\u1d65\u207b[i[1]+(i[2]-1)*V, i[1]+(i[2]-1)*V] = 1.0\n            D\u1d65\u207b[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, \u03bb::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\u00e9au. 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## `\u03bb`:\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\u00e9au, 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\u2070 = copy(scheme.z)\n    \u03bb = copy(scheme.\u03bb)\n    mask = copy(scheme.mask)\n    z = copy(z\u2070)\n    mask = rotr90(mask)\n    \u03bb = rotr90(\u03bb)\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\u1d64\u207a = spzeros(Float64, T^2, T^2)\n    D\u1d64\u207b = spzeros(Float64, T^2, T^2)\n    D\u1d65\u207a = spzeros(Float64, T^2, T^2)\n    D\u1d65\u207b = spzeros(Float64, T^2, T^2)\n    gen_matrix(D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a, D\u1d65\u207b, T, mask)\n\n    # Calculate D\u1d64, D\u1d65 and L as per eq 23 and 24\n    D\u1d64 = 0.5*(transpose(D\u1d64\u207a) .+ transpose(D\u1d64\u207b))\n    D\u1d65 = 0.5*(transpose(D\u1d65\u207a) .+ transpose(D\u1d65\u207b))\n    L = 0.5*((transpose(D\u1d64\u207a) * D\u1d64\u207a) .+ (transpose(D\u1d64\u207b) * D\u1d64\u207b) .+ (transpose(D\u1d65\u207a) * D\u1d65\u207a) .+ (transpose(D\u1d65\u207b) * D\u1d65\u207b))\n\n    \u039b = 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\u2070 = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        \u039b[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(\u03bb[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z\u2070[j[1]+(j[2]-1)*T] = z\u2070[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 .+ (\u039b^2)\n    b = D\u1d64*P .+ D\u1d65*Q .+ (\u039b^2)*Z\u2070\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, \u03b1::Real = 1.0, \u03bb::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\u00e9au. 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 ``\u2207z(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## `\u03b1`:\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## `\u03bb`:\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)), \u03b1=1.0)\ntotalVariationMasked = TotalVariation(z=zeros(size(p)), \u03b1=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\u00e9au, 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\u2070 = copy(scheme.z)\n    \u03bb = copy(scheme.\u03bb)\n    mask = copy(scheme.mask)\n    \u03b1 = copy(scheme.\u03b1)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z\u2070)\n    mask = rotr90(mask)\n    \u03bb = rotr90(\u03bb)\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\u1d64\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d64\u207b = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207b = spzeros(Float64,T^2,T^2)\n    gen_matrix(D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a, D\u1d65\u207b, T, mask)\n    \u039b = 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\u2070 = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        \u039b[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(\u03bb[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z\u2070[j[1]+(j[2]-1)*T] = z\u2070[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n\n    # Calculate A as per eq 59\n    A = (\u03b1/8)*(((transpose(D\u1d64\u207a) * D\u1d64\u207a) .+ (transpose(D\u1d65\u207a) * D\u1d65\u207a)) .+ ((transpose(D\u1d64\u207b) * D\u1d64\u207b) .+ (transpose(D\u1d65\u207b) * D\u1d65\u207b)) .+ ((transpose(D\u1d64\u207b) * D\u1d64\u207b) .+ (transpose(D\u1d65\u207a) * D\u1d65\u207a)) .+ ((transpose(D\u1d64\u207a) * D\u1d64\u207a) .+ (transpose(D\u1d65\u207b) * D\u1d65\u207b))) .+ (\u039b^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\u1d64\u207a\u207a = zeros(Float64,T^2)\n    b\u1d65\u207a\u207a = zeros(Float64,T^2)\n    s\u1d64\u207a\u207a = D\u1d64\u207a*Z - P + b\u1d64\u207a\u207a\n    s\u1d65\u207a\u207a = D\u1d65\u207a*Z - Q + b\u1d65\u207a\u207a\n    r\u1d64\u207a\u207a = max(norm(s\u1d64\u207a\u207a) - (4/\u03b1),0)*(s\u1d64\u207a\u207a./(norm(s\u1d64\u207a\u207a)+eps(Float64)))\n    r\u1d65\u207a\u207a = max(norm(s\u1d65\u207a\u207a) - (4/\u03b1),0)*(s\u1d65\u207a\u207a./(norm(s\u1d65\u207a\u207a)+eps(Float64)))\n    b\u1d64\u207a\u207a = b\u1d64\u207a\u207a + D\u1d64\u207a*Z - P - r\u1d64\u207a\u207a\n    b\u1d65\u207a\u207a = b\u1d65\u207a\u207a + D\u1d65\u207a*Z - Q - r\u1d65\u207a\u207a\n    P\u207a\u207a = P + r\u1d64\u207a\u207a - b\u1d64\u207a\u207a\n    Q\u207a\u207a = Q + r\u1d65\u207a\u207a - b\u1d65\u207a\u207a\n\n    b\u1d64\u207a\u207b = zeros(Float64,T^2)\n    b\u1d65\u207a\u207b = zeros(Float64,T^2)\n    s\u1d64\u207a\u207b = D\u1d64\u207a*Z - P + b\u1d64\u207a\u207b\n    s\u1d65\u207a\u207b = D\u1d65\u207b*Z - Q + b\u1d65\u207a\u207b\n    r\u1d64\u207a\u207b = max(norm(s\u1d64\u207a\u207b) - (4/\u03b1),0)*(s\u1d64\u207a\u207b./(norm(s\u1d64\u207a\u207b)+eps(Float64)))\n    r\u1d65\u207a\u207b = max(norm(s\u1d65\u207a\u207b) - (4/\u03b1),0)*(s\u1d65\u207a\u207b./(norm(s\u1d65\u207a\u207b)+eps(Float64)))\n    b\u1d64\u207a\u207b = b\u1d64\u207a\u207b + D\u1d64\u207a*Z - P - r\u1d64\u207a\u207b\n    b\u1d65\u207a\u207b = b\u1d65\u207a\u207b + D\u1d65\u207b*Z - Q - r\u1d65\u207a\u207b\n    P\u207a\u207b = P + r\u1d64\u207a\u207b - b\u1d64\u207a\u207b\n    Q\u207a\u207b = Q + r\u1d65\u207a\u207b - b\u1d65\u207a\u207b\n\n    b\u1d64\u207b\u207a = zeros(Float64,T^2)\n    b\u1d65\u207b\u207a = zeros(Float64,T^2)\n    s\u1d64\u207b\u207a = D\u1d64\u207b*Z - P + b\u1d64\u207b\u207a\n    s\u1d65\u207b\u207a = D\u1d65\u207a*Z - Q + b\u1d65\u207b\u207a\n    r\u1d64\u207b\u207a = max(norm(s\u1d64\u207b\u207a) - (4/\u03b1),0)*(s\u1d64\u207b\u207a./(norm(s\u1d64\u207b\u207a)+eps(Float64)))\n    r\u1d65\u207b\u207a = max(norm(s\u1d65\u207b\u207a) - (4/\u03b1),0)*(s\u1d65\u207b\u207a./(norm(s\u1d65\u207b\u207a)+eps(Float64)))\n    b\u1d64\u207b\u207a = b\u1d64\u207b\u207a + D\u1d64\u207b*Z - P - r\u1d64\u207b\u207a\n    b\u1d65\u207b\u207a = b\u1d65\u207b\u207a + D\u1d65\u207a*Z - Q - r\u1d65\u207b\u207a\n    P\u207b\u207a = P + r\u1d64\u207b\u207a - b\u1d64\u207b\u207a\n    Q\u207b\u207a = Q + r\u1d65\u207b\u207a - b\u1d65\u207b\u207a\n\n    b\u1d64\u207b\u207b = zeros(Float64,T^2)\n    b\u1d65\u207b\u207b = zeros(Float64,T^2)\n    s\u1d64\u207b\u207b = D\u1d64\u207b*Z - P + b\u1d64\u207b\u207b\n    s\u1d65\u207b\u207b = D\u1d65\u207b*Z - Q + b\u1d65\u207b\u207b\n    r\u1d64\u207b\u207b = max(norm(s\u1d64\u207b\u207b) - (4/\u03b1),0)*(s\u1d64\u207b\u207b./(norm(s\u1d64\u207b\u207b)+eps(Float64)))\n    r\u1d65\u207b\u207b = max(norm(s\u1d65\u207b\u207b) - (4/\u03b1),0)*(s\u1d65\u207b\u207b./(norm(s\u1d65\u207b\u207b)+eps(Float64)))\n    b\u1d64\u207b\u207b = b\u1d64\u207b\u207b + D\u1d64\u207b*Z - P - r\u1d64\u207b\u207b\n    b\u1d65\u207b\u207b = b\u1d65\u207b\u207b + D\u1d65\u207b*Z - Q - r\u1d65\u207b\u207b\n    P\u207b\u207b = P + r\u1d64\u207b\u207b - b\u1d64\u207b\u207b\n    Q\u207b\u207b = Q + r\u1d65\u207b\u207b - b\u1d65\u207b\u207b\n\n    # Calculate b\u209c\u1d65 as per eq 60\n    b\u209c\u1d65 = (transpose(D\u1d64\u207a) * P\u207a\u207a) .+ (transpose(D\u1d65\u207a) * Q\u207a\u207a) .+ (transpose(D\u1d64\u207a) * P\u207a\u207b) .+ (transpose(D\u1d65\u207b) * Q\u207a\u207b) .+ (transpose(D\u1d64\u207b) * P\u207b\u207a) .+ (transpose(D\u1d65\u207a) * Q\u207b\u207a) .+ (transpose(D\u1d64\u207b) * P\u207b\u207b) .+ (transpose(D\u1d65\u207b) * Q\u207b\u207b) .+ (\u039b^2)*Z\u2070\n    for i = 1:max_iter\n        cg!(Z, A, b\u209c\u1d65, 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\u1d64\u207a\u207a = D\u1d64\u207a*Z - P + b\u1d64\u207a\u207a\n        s\u1d65\u207a\u207a = D\u1d65\u207a*Z - Q + b\u1d65\u207a\u207a\n        r\u1d64\u207a\u207a = max(norm(s\u1d64\u207a\u207a) - (4/\u03b1),0)*(s\u1d64\u207a\u207a./(norm(s\u1d64\u207a\u207a)+eps(Float64)))\n        r\u1d65\u207a\u207a = max(norm(s\u1d65\u207a\u207a) - (4/\u03b1),0)*(s\u1d65\u207a\u207a./(norm(s\u1d65\u207a\u207a)+eps(Float64)))\n        b\u1d64\u207a\u207a = b\u1d64\u207a\u207a + D\u1d64\u207a*Z - P - r\u1d64\u207a\u207a\n        b\u1d65\u207a\u207a = b\u1d65\u207a\u207a + D\u1d65\u207a*Z - Q - r\u1d65\u207a\u207a\n        P\u207a\u207a = P + r\u1d64\u207a\u207a - b\u1d64\u207a\u207a\n        Q\u207a\u207a = Q + r\u1d65\u207a\u207a - b\u1d65\u207a\u207a\n\n        s\u1d64\u207a\u207b = D\u1d64\u207a*Z - P + b\u1d64\u207a\u207b\n        s\u1d65\u207a\u207b = D\u1d65\u207b*Z - Q + b\u1d65\u207a\u207b\n        r\u1d64\u207a\u207b = max(norm(s\u1d64\u207a\u207b) - (4/\u03b1),0)*(s\u1d64\u207a\u207b./(norm(s\u1d64\u207a\u207b)+eps(Float64)))\n        r\u1d65\u207a\u207b = max(norm(s\u1d65\u207a\u207b) - (4/\u03b1),0)*(s\u1d65\u207a\u207b./(norm(s\u1d65\u207a\u207b)+eps(Float64)))\n        b\u1d64\u207a\u207b = b\u1d64\u207a\u207b + D\u1d64\u207a*Z - P - r\u1d64\u207a\u207b\n        b\u1d65\u207a\u207b = b\u1d65\u207a\u207b + D\u1d65\u207b*Z - Q - r\u1d65\u207a\u207b\n        P\u207a\u207b = P + r\u1d64\u207a\u207b - b\u1d64\u207a\u207b\n        Q\u207a\u207b = Q + r\u1d65\u207a\u207b - b\u1d65\u207a\u207b\n\n        s\u1d64\u207b\u207a = D\u1d64\u207b*Z - P + b\u1d64\u207b\u207a\n        s\u1d65\u207b\u207a = D\u1d65\u207a*Z - Q + b\u1d65\u207b\u207a\n        r\u1d64\u207b\u207a = max(norm(s\u1d64\u207b\u207a) - (4/\u03b1),0)*(s\u1d64\u207b\u207a./(norm(s\u1d64\u207b\u207a)+eps(Float64)))\n        r\u1d65\u207b\u207a = max(norm(s\u1d65\u207b\u207a) - (4/\u03b1),0)*(s\u1d65\u207b\u207a./(norm(s\u1d65\u207b\u207a)+eps(Float64)))\n        b\u1d64\u207b\u207a = b\u1d64\u207b\u207a + D\u1d64\u207b*Z - P - r\u1d64\u207b\u207a\n        b\u1d65\u207b\u207a = b\u1d65\u207b\u207a + D\u1d65\u207a*Z - Q - r\u1d65\u207b\u207a\n        P\u207b\u207a = P + r\u1d64\u207b\u207a - b\u1d64\u207b\u207a\n        Q\u207b\u207a = Q + r\u1d65\u207b\u207a - b\u1d65\u207b\u207a\n\n        s\u1d64\u207b\u207b = D\u1d64\u207b*Z - P + b\u1d64\u207b\u207b\n        s\u1d65\u207b\u207b = D\u1d65\u207b*Z - Q + b\u1d65\u207b\u207b\n        r\u1d64\u207b\u207b = max(norm(s\u1d64\u207b\u207b) - (4/\u03b1),0)*(s\u1d64\u207b\u207b./(norm(s\u1d64\u207b\u207b)+eps(Float64)))\n        r\u1d65\u207b\u207b = max(norm(s\u1d65\u207b\u207b) - (4/\u03b1),0)*(s\u1d65\u207b\u207b./(norm(s\u1d65\u207b\u207b)+eps(Float64)))\n        b\u1d64\u207b\u207b = b\u1d64\u207b\u207b + D\u1d64\u207b*Z - P - r\u1d64\u207b\u207b\n        b\u1d65\u207b\u207b = b\u1d65\u207b\u207b + D\u1d65\u207b*Z - Q - r\u1d65\u207b\u207b\n        P\u207b\u207b = P + r\u1d64\u207b\u207b - b\u1d64\u207b\u207b\n        Q\u207b\u207b = Q + r\u1d65\u207b\u207b - b\u1d65\u207b\u207b\n\n        # Recalculate b\u209c\u1d65 as per eq 60\n        b\u209c\u1d65 = (transpose(D\u1d64\u207a) * P\u207a\u207a) .+ (transpose(D\u1d65\u207a) * Q\u207a\u207a) .+ (transpose(D\u1d64\u207a) * P\u207a\u207b) .+ (transpose(D\u1d65\u207b) * Q\u207a\u207b) .+ (transpose(D\u1d64\u207b) * P\u207b\u207a) .+ (transpose(D\u1d65\u207a) * Q\u207b\u207a) .+ (transpose(D\u1d64\u207b) * P\u207b\u207b) .+ (transpose(D\u1d65\u207b) * Q\u207b\u207b) .+ (\u039b^2)*Z\u2070\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, \u03b2::Real = 0.5, \u03bb::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\u00e9au. 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## `\u03b2`:\nA `Real` which acts as a hyper-parameter to the function. Large values for \u03b2 will\nproduce smoother functions but loose discontinuities. Smaller value will preserve\ndiscontinuities but lead to staircassing in the solution. Defults to `0.5`.\n## `\u03bb`:\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)), \u03b2=0.5)\nnonConvex1Init = NonConvex1(z=Horn()(p,q), \u03b2=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\u00e9au, 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\u2070 = copy(scheme.z)\n    \u03bb = copy(scheme.\u03bb)\n    mask = copy(scheme.mask)\n    \u03b2 = copy(scheme.\u03b2)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z\u2070)\n    mask = rotr90(mask)\n    \u03bb = rotr90(\u03bb)\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\u1d64\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d64\u207b = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207b = spzeros(Float64,T^2,T^2)\n    gen_matrix(D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a, D\u1d65\u207b, T, mask)\n    \u039b = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z\u2070 = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        \u039b[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(\u03bb[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z\u2070[j[1]+(j[2]-1)*T] = z\u2070[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    \u039b = Diagonal(\u039b)\n    Zold = copy(Z)\n    Ztemp = copy(Z)\n    \u03b1\u2081 = 0.8\n    \u03b1\u2082 = 0.8\n\n    # Initialize L\u2099 (Lipschitz constant) such that lazy backtracking starts with \u03b1\u2081 = \u03b1\u2082.\n    # This is mostly arbitary and value will approach needed value over time.\n    L\u2099 = (18.0/\u03b1\u2081)*(1-\u03b1\u2082)\n    \u03b7 = 1.1\n    i = 1\n    while i <= max_iter && (norm(Z - Zold) > 10.0^-4.0 || i == 1)\n        # Calculate f\u2081, \u2207f\u2081 and previous f\u2081 (f\u2081\u207f\u207b\u00b9 )\n        \u2207f\u2081 = ((transpose(D\u1d64\u207a)*(D\u1d64\u207a*Z-P))/(norm(D\u1d64\u207a*Z-P)^2+\u03b2^2)) + ((transpose(D\u1d65\u207a)*(D\u1d65\u207a*Z-Q))/(norm(D\u1d65\u207a*Z-Q)^2+\u03b2^2)) + ((transpose(D\u1d64\u207b)*(D\u1d64\u207b*Z-P))/(norm(D\u1d64\u207b*Z-P)^2+\u03b2^2)) + ((transpose(D\u1d65\u207b)*(D\u1d65\u207b*Z-Q))/(norm(D\u1d65\u207b*Z-Q)^2+\u03b2^2))\n        f\u2081\u207f\u207b\u00b9 = log(norm(D\u1d64\u207a*Zold-P)^2+\u03b2^2) + log(norm(D\u1d65\u207a*Zold-Q)^2+\u03b2^2) + log(norm(D\u1d64\u207b*Zold-P)^2+\u03b2^2) + log(norm(D\u1d65\u207b*Zold-Q)^2+\u03b2^2)\n        f\u2081 = log(norm(D\u1d64\u207a*Z-P)^2+\u03b2^2) + log(norm(D\u1d65\u207a*Z-Q)^2+\u03b2^2) + log(norm(D\u1d64\u207b*Z-P)^2+\u03b2^2) + log(norm(D\u1d65\u207b*Z-Q)^2+\u03b2^2)\n\n        # Calculate lazy backtracking condition as per ipiano algortihm 4\n        while f\u2081 > f\u2081\u207f\u207b\u00b9  + dot(\u2207f\u2081, Z - Zold) + (L\u2099/2)*norm(Z - Zold)\n            L\u2099 = L\u2099*\u03b7\n        end\n\n        # Calculate new \u03b1\u2081 as per ipiano algortihm 4\n        \u03b1\u2081 = (2*(1-\u03b1\u2082)/L\u2099)*0.9\n\n        # Calcualte x\u0302 as per eq 69 then calculate new Z as per eq 71\n        x\u0302 = Z - \u03b1\u2081.*\u2207f\u2081 + \u03b1\u2082.*(Z-Zold)\n        Ztemp = inv(I+(2*\u03b1\u2081).*\u039b^2)*(x\u0302+(2*\u03b1\u2081).*\u039b*Z\u2070)\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, \u03b3::Real = 1.0, \u03bb::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\u00e9au. 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## `\u03b3`:\nA `Real` which acts as a hyper-parameter to the function. Large values for \u03b3 will\nproduce smoother functions but loose discontinuities. Smaller value will preserve\ndiscontinuities but lead to staircassing in the solution. Defults to `1.0`.\n## `\u03bb`:\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)), \u03b3=1.0)\nnonConvex2Init = NonConvex2(z=Horn()(p,q), \u03b3=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\u00e9au, 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\u2070 = copy(scheme.z)\n    \u03bb = copy(scheme.\u03bb)\n    mask = copy(scheme.mask)\n    \u03b3 = copy(scheme.\u03b3)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z\u2070)\n    mask = rotr90(mask)\n    \u03bb = rotr90(\u03bb)\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\u1d64\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d64\u207b = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207b = spzeros(Float64,T^2,T^2)\n    gen_matrix(D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a, D\u1d65\u207b, T, mask)\n    \u039b = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z\u2070 = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        \u039b[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(\u03bb[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z\u2070[j[1]+(j[2]-1)*T] = z\u2070[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    \u039b = Diagonal(\u039b)\n    Zold = copy(Z)\n    Ztemp = copy(Z)\n    \u03b1\u2081 = 0.8\n    \u03b1\u2082 = 0.8\n\n    # Initialize L\u2099 (Lipschitz constant) such that lazy backtracking starts with \u03b1\u2081 = \u03b1\u2082.\n    # This is mostly arbitary and value will approach needed value over time.\n    L\u2099 = (18.0/\u03b1\u2081)*(1-\u03b1\u2082)\n    \u03b7 = 1.1\n    i = 1\n    while i <= max_iter && (norm(Z - Zold) > 10.0^-4.0 || i == 1)\n        # Calculate f\u2081, \u2207f\u2081 and previous f\u2081 (f\u2081\u207f\u207b\u00b9 )\n        \u2207f\u2081 = (((\u03b3^2)*transpose(D\u1d64\u207a)*(D\u1d64\u207a*Z-P))/(norm(D\u1d64\u207a*Z-P)^2+\u03b3^2)^2) + (((\u03b3^2)*transpose(D\u1d65\u207a)*(D\u1d65\u207a*Z-Q))/(norm(D\u1d65\u207a*Z-Q)^2+\u03b3^2)^2) + (((\u03b3^2)*transpose(D\u1d64\u207b)*(D\u1d64\u207b*Z-P))/(norm(D\u1d64\u207b*Z-P)^2+\u03b3^2)^2) + (((\u03b3^2)*transpose(D\u1d65\u207b)*(D\u1d65\u207b*Z-Q))/(norm(D\u1d65\u207b*Z-Q)^2+\u03b3^2)^2)\n        f\u2081\u207f\u207b\u00b9 = (norm(D\u1d64\u207a*Zold-P)^2)/(norm(D\u1d64\u207a*Zold-P)^2+\u03b3^2) + (norm(D\u1d65\u207a*Zold-Q)^2)/(norm(D\u1d65\u207a*Zold-Q)^2+\u03b3^2) + (norm(D\u1d64\u207b*Zold-P)^2)/(norm(D\u1d64\u207b*Zold-P)^2+\u03b3^2) + (norm(D\u1d65\u207b*Zold-Q)^2)/(norm(D\u1d65\u207b*Zold-Q)^2+\u03b3^2)\n        f\u2081 = (norm(D\u1d64\u207a*Z-P)^2)/(norm(D\u1d64\u207a*Z-P)^2+\u03b3^2) + (norm(D\u1d65\u207a*Z-Q)^2)/(norm(D\u1d65\u207a*Z-Q)^2+\u03b3^2) + (norm(D\u1d64\u207b*Z-P)^2)/(norm(D\u1d64\u207b*Z-P)^2+\u03b3^2) + (norm(D\u1d65\u207b*Z-Q)^2)/(norm(D\u1d65\u207b*Z-Q)^2+\u03b3^2)\n\n        # Calculate lazy backtracking condition as per ipiano algortihm 4\n        while f\u2081 > f\u2081\u207f\u207b\u00b9 + dot(\u2207f\u2081, Z - Zold) + (L\u2099/2)*norm(Z - Zold)\n            L\u2099 = L\u2099*\u03b7\n        end\n\n        # Calculate new \u03b1\u2081 as per ipiano algortihm 4\n        \u03b1\u2081 = (2*(1-\u03b1\u2082)/L\u2099)*0.9\n\n        # Calcualte x\u0302 as per eq 69 then calculate new Z as per eq 71\n        x\u0302 = Z - \u03b1\u2081.*\u2207f\u2081 + \u03b1\u2082.*(Z-Zold)\n        Ztemp = inv(I+(2*\u03b1\u2081).*\u039b^2)*(x\u0302+(2*\u03b1\u2081).*\u039b*Z\u2070)\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, \u03bc::Real = 5.0, \u03bd::Real = 10., \u03bb::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\u00e9au.\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## `\u03bc`:\nA `Real` which acts as a hyper-parameter to the function. Allows for the tuning\nof discontinuities. Defults to `5.0`.\n## `\u03bd`:\nA `Real` which acts as a hyper-parameter to the function. Allows for the tuning\nof discontinuities. Unlike `\u03bc` is has a minimal impact on the solution and generally\ndoes not need adjusting unless an extreme value for `\u03bc` is used where it can help\nto balance out the two terms. Defults to `10.0`.\n## `\u03bb`:\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)), \u03b3=1.0)\nanisotropicDiffusionInit = AnisotropicDiffusion(z=Horn()(p,q), \u03b3=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\u00e9au, 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    \u03bb = copy(scheme.\u03bb)\n    z\u2070 = copy(scheme.z)\n    mask = copy(scheme.mask)\n    \u03bd = copy(scheme.\u03bd)\n    \u03bc = copy(scheme.\u03bc)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z\u2070)\n    mask = rotr90(mask)\n    \u03bb = rotr90(\u03bb)\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\u1d64\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d64\u207b = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207b = spzeros(Float64,T^2,T^2)\n    gen_matrix(D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a, D\u1d65\u207b,T,mask)\n    \u039b = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z\u2070 = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        \u039b[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(\u03bb[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z\u2070[j[1]+(j[2]-1)*T] = z\u2070[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    \u039b = sparse(Diagonal(\u039b))\n\n    # Calcualte A and B for each conination in {+,-} as per eq 90 and 91\n    A\u207a\u207a = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n    A\u207b\u207a = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n    A\u207a\u207b = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n    A\u207b\u207b = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n    B\u207a\u207a = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n    B\u207b\u207a = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n    B\u207a\u207b = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n    B\u207b\u207b = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n\n    # Calculate A and b as derived from eq 92 in form Az=b\n    A = (A\u207a\u207a*D\u1d64\u207a)*transpose(A\u207a\u207a*D\u1d64\u207a) + (B\u207a\u207a*D\u1d65\u207a)*transpose(B\u207a\u207a*D\u1d65\u207a) + (A\u207a\u207b*D\u1d64\u207a)*transpose(A\u207a\u207b*D\u1d64\u207a) + (B\u207a\u207b*D\u1d65\u207b)*transpose(B\u207a\u207b*D\u1d65\u207b) + (A\u207b\u207a*D\u1d64\u207b)*transpose( A\u207b\u207a*D\u1d64\u207b) + (B\u207b\u207a*D\u1d65\u207a)*transpose(B\u207b\u207a*D\u1d65\u207a) + (A\u207b\u207b*D\u1d64\u207b)*transpose(A\u207b\u207b*D\u1d64\u207b) + (B\u207b\u207b*D\u1d65\u207b)*transpose(B\u207b\u207b*D\u1d65\u207b)\n    A = A/4.0 + \u039b^2\n    b = (transpose(A\u207a\u207a*D\u1d64\u207a)*A\u207a\u207a)*P + (transpose(B\u207a\u207a*D\u1d65\u207a)*B\u207a\u207a)*Q + (transpose(A\u207a\u207b*D\u1d64\u207a)*A\u207a\u207b)*P + (transpose(B\u207a\u207b*D\u1d65\u207b)*B\u207a\u207b)*Q + (transpose(A\u207b\u207a*D\u1d64\u207b)*A\u207b\u207a)*P + (transpose(B\u207b\u207a*D\u1d65\u207a)*B\u207b\u207a)*Q + (transpose(A\u207b\u207b*D\u1d64\u207b)*A\u207b\u207b)*P + (transpose(B\u207b\u207b*D\u1d65\u207b)*B\u207b\u207b)*Q\n    b = b/4.0 + (\u039b^2)*Z\u2070\n    A\u2080 = factorize(A)\n    for i = 1:max_iter\n        # Solve system at iteration k\n        Z = A\u2080\\b\n\n        # Recalcualte A and B for each conination in {+,-} as per eq 90 and 91\n        A\u207a\u207a = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n        A\u207b\u207a = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n        A\u207a\u207b = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n        A\u207b\u207b = Diagonal(1.0./(sqrt.(1.0.+(P./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n        B\u207a\u207a = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n        B\u207b\u207a = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207a*Z).^2)./(\u03bc^2) .+ 1)))\n        B\u207a\u207b = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207a*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n        B\u207b\u207b = Diagonal(1.0./(sqrt.(1.0.+(Q./\u03bd).^2) .* sqrt.(((D\u1d64\u207b*Z).^2 .+ (D\u1d65\u207b*Z).^2)./(\u03bc^2) .+ 1)))\n\n        # Recalculate A and b as derived from eq 92 in form Az=b\n        A = (A\u207a\u207a*D\u1d64\u207a)*transpose(A\u207a\u207a*D\u1d64\u207a) + (B\u207a\u207a*D\u1d65\u207a)*transpose(B\u207a\u207a*D\u1d65\u207a) + (A\u207a\u207b*D\u1d64\u207a)*transpose(A\u207a\u207b*D\u1d64\u207a) + (B\u207a\u207b*D\u1d65\u207b)*transpose(B\u207a\u207b*D\u1d65\u207b) + (A\u207b\u207a*D\u1d64\u207b)*transpose( A\u207b\u207a*D\u1d64\u207b) + (B\u207b\u207a*D\u1d65\u207a)*transpose(B\u207b\u207a*D\u1d65\u207a) + (A\u207b\u207b*D\u1d64\u207b)*transpose(A\u207b\u207b*D\u1d64\u207b) + (B\u207b\u207b*D\u1d65\u207b)*transpose(B\u207b\u207b*D\u1d65\u207b)\n        A = A/4.0 + \u039b^2\n        b = (transpose(A\u207a\u207a*D\u1d64\u207a)*A\u207a\u207a)*P + (transpose(B\u207a\u207a*D\u1d65\u207a)*B\u207a\u207a)*Q + (transpose(A\u207a\u207b*D\u1d64\u207a)*A\u207a\u207b)*P + (transpose(B\u207a\u207b*D\u1d65\u207b)*B\u207a\u207b)*Q + (transpose(A\u207b\u207a*D\u1d64\u207b)*A\u207b\u207a)*P + (transpose(B\u207b\u207a*D\u1d65\u207a)*B\u207b\u207a)*Q + (transpose(A\u207b\u207b*D\u1d64\u207b)*A\u207b\u207b)*P + (transpose(B\u207b\u207b*D\u1d65\u207b)*B\u207b\u207b)*Q\n        b = b/4.0 + (\u039b^2)*Z\u2070\n        A\u2080 = 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, \u03bc::Real = 10.0, \u03f5::Real = 0.1, \u03bb::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\u00e9au. 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## `\u03f5`:\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## `\u03bc`:\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## `\u03bb`:\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)), \u03b3=1.0)\nmumfordShahInit = MumfordShah(z=Horn()(p,q), \u03b3=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\u00e9au, 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\u2070 = copy(scheme.z)\n    \u03bb = copy(scheme.\u03bb)\n    mask = copy(scheme.mask)\n    \u03f5 = copy(scheme.\u03f5)\n    \u03bc = copy(scheme.\u03bc)\n    max_iter = copy(scheme.max_iter)\n    z = copy(z\u2070)\n    mask = rotr90(mask)\n    \u03bb = rotr90(copy(\u03bb))\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\u1d64\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d64\u207b = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207a = spzeros(Float64,T^2,T^2)\n    D\u1d65\u207b = spzeros(Float64,T^2,T^2)\n    gen_matrix(D\u1d64\u207a, D\u1d64\u207b, D\u1d65\u207a, D\u1d65\u207b,T,mask)\n    \u039b = zeros(Float64,T^2,T^2)\n    P = zeros(Float64,T^2)\n    Q = zeros(Float64,T^2)\n    Z\u2070 = zeros(Float64,T^2)\n    Z = zeros(Float64,T^2)\n    # Vectorize inputs\n    for j in CartesianIndices(z)\n        \u039b[j[1]+(j[2]-1)*T,j[1]+(j[2]-1)*T] = sqrt(\u03bb[j])\n        P[j[1]+(j[2]-1)*T] = p[j]\n        Q[j[1]+(j[2]-1)*T] = q[j]\n        Z\u2070[j[1]+(j[2]-1)*T] = z\u2070[j]\n        Z[j[1]+(j[2]-1)*T] = z[j]\n    end\n    \u039b = sparse(Diagonal(\u039b))\n    w\u1d64\u207a = fill(1.0, T^2)\n    w\u1d64\u207b = fill(1.0, T^2)\n    w\u1d65\u207a = fill(1.0, T^2)\n    w\u1d65\u207b = fill(1.0, T^2)\n\n    W\u1d64\u207a = Diagonal(w\u1d64\u207a)\n    W\u1d64\u207b = Diagonal(w\u1d64\u207b)\n    W\u1d65\u207a = Diagonal(w\u1d65\u207a)\n    W\u1d65\u207b = Diagonal(w\u1d65\u207b)\n\n    A1 = \u03bc*(transpose(D\u1d64\u207a)*transpose(W\u1d64\u207a)*W\u1d64\u207a*D\u1d64\u207a + transpose(D\u1d64\u207b)*transpose(W\u1d64\u207b)*W\u1d64\u207b*D\u1d64\u207b + transpose(D\u1d65\u207a)*transpose(W\u1d65\u207a)*W\u1d65\u207a*D\u1d65\u207a + transpose(D\u1d65\u207b)*transpose(W\u1d65\u207b)*W\u1d65\u207b*D\u1d65\u207b)\n    A1 = A1 + \u039b^2\n    b = \u03bc*((transpose(D\u1d64\u207a)*transpose(W\u1d64\u207a)*W\u1d64\u207a)*P + (transpose(D\u1d64\u207b)*transpose(W\u1d64\u207b)*W\u1d64\u207b)*P + (transpose(D\u1d65\u207a)*transpose(W\u1d65\u207a)*W\u1d65\u207a)*Q + (transpose(D\u1d65\u207b)*transpose(W\u1d65\u207b)*W\u1d65\u207b)*Q)\n    b = b + (\u039b^2)*Z\u2070\n\n    b\u2080 =  Diagonal(fill(1.0/(4.0*\u03f5), T^2))\n    DD\u1d64\u207a = (\u03f5*transpose(D\u1d64\u207a)*D\u1d64\u207a+b\u2080)\n    DD\u1d64\u207b = (\u03f5*transpose(D\u1d64\u207b)*D\u1d64\u207b+b\u2080)\n    DD\u1d65\u207a = (\u03f5*transpose(D\u1d65\u207a)*D\u1d65\u207a+b\u2080)\n    DD\u1d65\u207b = (\u03f5*transpose(D\u1d65\u207b)*D\u1d65\u207b+b\u2080)\n    A2 = ((Diagonal(D\u1d64\u207b*Z-P)^2)*\u03bc) + DD\u1d64\u207b\n    b2 = fill(1.0/(4.0*\u03f5), T^2)\n    for i = 1:max_iter\n        cg!(Z, A1, b)\n\n        A2 = ((Diagonal(D\u1d64\u207a*Z-P)^2)*\u03bc) + DD\u1d64\u207a\n        cg!(w\u1d64\u207a, A2, b2)\n        W\u1d64\u207a = Diagonal(w\u1d64\u207a)\n\n        A2 = ((Diagonal(D\u1d64\u207b*Z-P)^2)*\u03bc) + DD\u1d64\u207b\n        cg!(w\u1d64\u207b, A2, b2)\n        W\u1d64\u207b = Diagonal(w\u1d64\u207b)\n\n        A2 = ((Diagonal(D\u1d65\u207a*Z-Q)^2)*\u03bc) + DD\u1d65\u207a\n        cg!(w\u1d65\u207a, A2, b2)\n        W\u1d65\u207a = Diagonal(w\u1d65\u207a)\n\n        A2 = ((Diagonal(D\u1d65\u207b*Z-Q)^2)*\u03bc) + DD\u1d65\u207b\n        cg!(w\u1d65\u207b, A2, b2)\n        W\u1d65\u207b = Diagonal(w\u1d65\u207b)\n\n        A1 = \u03bc*(transpose(D\u1d64\u207a)*transpose(W\u1d64\u207a)*W\u1d64\u207a*D\u1d64\u207a + transpose(D\u1d64\u207b)*transpose(W\u1d64\u207b)*W\u1d64\u207b*D\u1d64\u207b + transpose(D\u1d65\u207a)*transpose(W\u1d65\u207a)*W\u1d65\u207a*D\u1d65\u207a + transpose(D\u1d65\u207b)*transpose(W\u1d65\u207b)*W\u1d65\u207b*D\u1d65\u207b)\n        A1 = A1 + \u039b^2\n        b = \u03bc*((transpose(D\u1d64\u207a)*transpose(W\u1d64\u207a)*W\u1d64\u207a)*P + (transpose(D\u1d64\u207b)*transpose(W\u1d64\u207b)*W\u1d64\u207b)*P + (transpose(D\u1d65\u207a)*transpose(W\u1d65\u207a)*W\u1d65\u207a)*Q + (transpose(D\u1d65\u207b)*transpose(W\u1d65\u207b)*W\u1d65\u207b)*Q)\n        b = b + (\u039b^2)*Z\u2070\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, \u03bc, \u03bd)\n#     @show \"new\"\n#     iter = copy(scheme.max_iter)\n#     \u03f5 = copy(scheme.\u03f5)\n#     Z = zeros(Float64, size(p))\n#     Z\u1d4f\u207a\u00b9 = zeros(Float64, size(p))\n#     R, C = size(p)\n#     w\u1d64\u207a = zeros(Float64, size(p))\n#     w\u1d64\u207b = zeros(Float64, size(p))\n#     w\u1d65\u207a = zeros(Float64, size(p))\n#     w\u1d65\u207b = zeros(Float64, size(p))\n#     for i in CartesianIndices(p)\n#         u,v=i.I\n#         w\u1d64\u207a[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)]))/\u03bc)^2 + 1)*sqrt(((Z[min(u+1,R),v]-Z[u,v])^2/(\u03bd^2)+1)))\n#         w\u1d64\u207b[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)]))/\u03bc)^2 + 1)*sqrt(((Z[u,v]-Z[max(u-1,1),v])^2/(\u03bd^2)+1)))\n#         w\u1d65\u207a[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]))/\u03bc)^2 + 1)*sqrt(((Z[u,min(v+1,C)]-Z[u,v])^2/(\u03bd^2)+1)))\n#         w\u1d65\u207b[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)]))/\u03bc)^2 + 1)*sqrt(((Z[u,v]-Z[u,max(v-1,1)])^2/(\u03bd^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\u1d65\u207b[i,j+1]*(p[i,j+1]-p[i,j]) + w\u1d65\u207a[i,j-1]*(p[i,j]-p[i,j-1])) / 2\n#             V[i,j] = (w\u1d64\u207b[i+1,j]*(q[i+1,j]-q[i,j]) + w\u1d64\u207a[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] = \u03f5 * (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\u1d64\u207a[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)]))/\u03bc)^2 + 1)*sqrt(((Z[min(u+1,R),v]-Z[u,v])^2/(\u03bd^2)+1)))\n#             w\u1d64\u207b[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)]))/\u03bc)^2 + 1)*sqrt(((Z[u,v]-Z[max(u-1,1),v])^2/(\u03bd^2)+1)))\n#             w\u1d65\u207a[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]))/\u03bc)^2 + 1)*sqrt(((Z[u,min(v+1,C)]-Z[u,v])^2/(\u03bd^2)+1)))\n#             w\u1d65\u207b[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)]))/\u03bc)^2 + 1)*sqrt(((Z[u,v]-Z[u,max(v-1,1)])^2/(\u03bd^2)+1)))\n#         end\n#         copyto!(Z\u1d4f\u207a\u00b9, Z)\n#         for i = 2:(R-1)\n#             for j = 2:(C-1)\n#                 H[i,j] = (w\u1d65\u207b[i,j+1]*(p[i,j+1]-p[i,j]) + w\u1d65\u207a[i,j-1]*(p[i,j]-p[i,j-1])) / 2\n#                 V[i,j] = (w\u1d64\u207b[i+1,j]*(q[i+1,j]-q[i,j]) + w\u1d64\u207a[i-1,j]*(q[i,j]-q[i-1,j])) / 2\n#                 hv[i,j] = \u03f5 * (H[i,j] - V[i,j])\n#                 Z\u1d4f\u207a\u00b9[i,j] = (w\u1d64\u207a[i-1,j]*Z[i-1,j] + w\u1d64\u207b[i+1,j]*Z[i+1,j] + w\u1d65\u207a[i,j-1]*Z[i,j-1] + w\u1d65\u207b[i,j+1]*Z[i,j+1])\n#                 Z\u1d4f\u207a\u00b9[i,j] = Z\u1d4f\u207a\u00b9[i,j] - hv[i,j]\n#                 Z\u1d4f\u207a\u00b9[i,j] = Z\u1d4f\u207a\u00b9[i,j] / (w\u1d64\u207b[i+1,j] + w\u1d64\u207a[i-1,j] + w\u1d65\u207b[i,j+1] + w\u1d65\u207a[i,j-1])\n#             end\n#         end\n#         Z = Z\u1d4f\u207a\u00b9\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\u00f6s-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": "\n@testset \"normal distribution, integral normed to 1\" begin\n    @test 1 / \u221a(2\u03c0)^2 / 1 * exp.(.- rr2((5,5)) / 2 .* 1^2) \u2248 normal((5,5))\n    @test 1 / \u221a(2\u03c0)^2 / 1 * exp.(.- rr2((8,5)) / 2 .* 1^2) \u2248 normal((8,5))\n    @test 1 / \u221a(2\u03c0)^2 / 1 * exp.(.- rr2((8,5)) / 2 .* 1^2) \u2248 normal(zeros(8,5))\n    @test eltype(normal(Float32, (8,5))) === Float32\nend\n\n\n\n@testset \"Gaussian function, normed to 1\" begin\n    arr = 1 / \u221a(2\u03c0)^2 / 1 * exp.(.- rr2((5,5)) / 2 .* 1^2)\n    arr ./= maximum(arr)\n    @test arr \u2248 gaussian((5,5))\n    @test eltype(gaussian(Float32, (8,5))) === Float32\nend\n", "meta": {"hexsha": "4033dd9a9cec01cdf509e61104c06dbef6f3d7f0", "size": 573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/other_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": "test/other_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": "test/other_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": 33.7058823529, "max_line_length": 79, "alphanum_fraction": 0.5130890052, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7907389861881597}}
{"text": "## Exercise 5-2\n## The function time returns the current Greenwich Mean Time in seconds since \u201cthe epoch\u201d, 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 \u03c0. To make \u03c0 \r\n#' (and most other greek letters), type \\pi and then press [TAB].\r\n\r\n\u03c0\r\n\r\n#+\r\n\r\ntypeof(\u03c0)\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(\"\u03c0 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 \u221a (\\sqrt)\r\n\r\nsin(2\u03c0/3) == \u221a3/2\r\n\r\n#' Wait. What???\r\n\r\nsin(2\u03c0/3) - \u221a3/2\r\n\r\n#' Let's try again using \u2248 (\\approx).\r\n\r\nsin(2\u03c0/3) \u2248 \u221a3/2\r\n\r\n#' Note that this time we used \u2248 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": "#=\nPlot the dividend process and the state process for the Markov asset pricing\nlecture.\n\n=#\n\nusing QuantEcon\nusing Plots\nusing LaTeXStrings\n\npyplot()\n\nn = 25\nmc = tauchen(n, 0.96, 0.25)  \nsim_length = 80\n\nx_series = simulate(mc, sim_length; init=round(Int, n / 2))\nlambda_series = exp(x_series)\nd_series = cumprod(lambda_series) # assumes d_0 = 1\n\nseries = [x_series lambda_series d_series log(d_series)]\nlabels = [L\"$X_t$\" L\"$g_t$\" L\"$d_t$\" L\"$log (d_t)$\"]\nplot(series, layout=4, labels=labels)\n\n", "meta": {"hexsha": "3633ce2a15b136cf37aa04887ac4a46f4e650114", "size": 498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "markov_asset/dividend_plots.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": "markov_asset/dividend_plots.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": "markov_asset/dividend_plots.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": 19.92, "max_line_length": 76, "alphanum_fraction": 0.7108433735, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7906903456888649}}
{"text": "# \u0433\u0440\u0430\u043d\u0438\u0446\u0430 x\u044d\u043c\u043c\u0438\u043d\u0433\u0430 \u043f\u0440\u043e \u0443\u043f\u0430\u043a\u043e\u0432\u043a\u0443 \u0448\u0430\u0440\u0430\u043c\u0438\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]) \u2264 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# \u043d\u0430x\u043e\u0436\u0434\u0435\u043d\u0438\u0435 k \u043f\u043e n \u0438 d\n#\n# M, klog = hammingND(n, d)\n# println(\"\u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0425\u044d\u043c\u043c\u0438\u043d\u0433\u0430: M \u2264 $M, k \u2248 $(klog)\")\n\n# println(\"==============================\")\n\n# mink = varshamovGuilbertND(n, d)\n# println(\"\u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0412\u0430\u0440\u0448\u0430\u043c\u043e\u0432\u0430-\u0413\u0438\u043b\u0431\u0435\u0440\u0442\u0430: k \u2265 $mink\")\n\n# println(\"==============================\")\n# println(graismer(9, d))\n# println(\"###################################\")\n\n# \u043d\u0430x\u043e\u0436\u0434\u0435\u043d\u0438\u0435 d \u043f\u043e n \u0438 k\n#\nt = hammingNK(n, k)\nprintln(\"\u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0425\u044d\u043c\u043c\u0438\u043d\u0433\u0430: t \u2264 $t\")\n\nprintln(\"==============================\")\n\nmind = varshamovGuilbertNK(n, k)\nprintln(\"\u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0412\u0430\u0440\u0448\u0430\u043c\u043e\u0432\u0430-\u0413\u0438\u043b\u0431\u0435\u0440\u0442\u0430: d \u2265 $mind\")\n\nprintln(\"==============================\")\nprintln(\"\u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0413\u0440\u0430\u0439\u0441\u043c\u0435\u0440\u0430: $(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": "export RDFT\n\n\"\"\"\n`RDFT([domainType=Float64::Type,] dim_in::Tuple [,dims=1])`\n\n`RDFT(dim_in...)`\n\n`RDFT(x::AbstractArray [,dims=1])`\n\nCreates a `LinearOperator` which, when multiplied with a real array `x`, returns the DFT over the dimension `dims`, exploiting Hermitian symmetry. \n\n```julia\njulia> RDFT(Float64,(10,10))\n\u2131  \u211d^(10, 10) -> \u2102^(6, 10)\n\njulia> RDFT((10,10,10),2)\n\u2131  \u211d^(10, 10, 10) -> \u2102^(10, 6, 10)\n\n```\n\n\"\"\"\nstruct RDFT{T <:Number,\n\t       N,\n\t       T1<:AbstractFFTs.Plan,\n\t       T2<:AbstractFFTs.Plan,\n\t       T3<:AbstractArray{Complex{T},N}\n\t      } <: LinearOperator \n\tdim_in::NTuple{N,Int}\n\tdim_out::NTuple{N,Int}\n\tA::T1\n\tAt::T2\n\tb2::T3\n\ty2::T3\n\tZp::ZeroPad{Complex{T},N}\nend\n\n\n# Constructors\n#standard constructor\n\nfunction RDFT(x::AbstractArray{T,N}, dims::Int=1) where {T<:Real,N}\n\tA = plan_rfft(x,dims) \n\tb2 = zeros(complex(T),size(x))\n\ty2 = zeros(complex(T),size(x))\n\tAt = plan_bfft(y2,dims)\n\tdim_in = size(x)\n\tdim_out = ()\n\tfor i = 1:N\n\t\tdim_out = i == dims ? (dim_out...,div(dim_in[i],2)+1) : (dim_out...,dim_in[i])\n\tend\n\tZ = ZeroPad(Complex{T},dim_out,size(b2))\n\tRDFT{T,N,typeof(A),typeof(At),typeof(b2)}(dim_in,dim_out,A,At,b2,y2,Z)\nend\n\nRDFT(T::Type,dim_in::NTuple{N,Int},dims::Int=1) where {N} = RDFT(zeros(T,dim_in),dims)\nRDFT(dim_in::NTuple{N,Int},dims::Int=1) where {N} = RDFT(zeros(dim_in),dims)\nRDFT(dim_in::Vararg{Int}) = RDFT(dim_in)\nRDFT(T::Type,dim_in::Vararg{Int}) = RDFT(T,dim_in)\n\n\n# Mappings\n\nfunction mul!(y::T3,\n              L::RDFT{T,N,T1,T2,T3},\n              b::T4) where {N,T,T1,T2,T3,T4 <: AbstractArray{T,N}}\n\tmul!(y,L.A,b)\nend\n\nfunction mul!(y::T4,\n              L::AdjointOperator{RDFT{T,N,T1,T2,T3}},\n              b::T3) where {N,T,T1,T2,T3,T4 <: AbstractArray{T,N}}\n    A = L.A\n\tmul!(A.b2,A.Zp,b)\n\tmul!(A.y2,A.At,A.b2)\n\ty .= real.(A.y2)\n\treturn y\n\nend\n\n\n# Properties\n\nsize(L::RDFT) = (L.dim_out,L.dim_in)\n\nfun_name(A::RDFT) = \"\u2131\"\n\ndomainType(L::RDFT{T,N}) where {T,N} = T\ncodomainType(L::RDFT{T,N}) where {T,N} = Complex{T}\n\nis_AAc_diagonal(    L::RDFT) = false #TODO but might be true?\nis_invertible(      L::RDFT) = true\nis_full_row_rank(   L::RDFT) = true\n", "meta": {"hexsha": "97967e18a8622c8b42395126c35ca228226a57ca", "size": 2114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearoperators/RDFT.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/RDFT.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/RDFT.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": 22.7311827957, "max_line_length": 147, "alphanum_fraction": 0.614474929, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7906903387233423}}
{"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)\u00d7fy(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)\u00d7fy(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) \u00d7 fy(x) - fxy(x) \u00d7 fx(x)) \u22c5 (fx(x) \u00d7 fy(x)) / af(x)\n        (fxy(x) \u00d7 fy(x) - fyy(x) \u00d7 fx(x)) \u22c5 (fx(x) \u00d7 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) = \u221aa(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) = \u221aa(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) = \u221aa(x) * f(x)\n    Dq(x) = 1. / (2. * \u221aa(x)) * f(x) * Da(x)' + \u221aa(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) \u00f7 2 : (l - 1) \u00f7 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\u0394t = ts \n\u0394f = fs / (l - 1)\nEt = sum(abs.(x).^2) * \u0394t \nEf = sum(abs.(xf).^2) * \u0394f / (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    \u03b3 = dot(u, samp[1])\n    x .= x + u * ( res / \u03b3 )\n\n    #Update Projection matrix\n    type.S .= (I - (u/\u03b3)*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; \u03f5=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 .+ \u03f5))\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 .+ \u03f5)\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\u03b1 = 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 .-= \u03b1*grad_mean[2]\n    m.b1 .-= \u03b1*grad_mean[3]\n    m.W2 .-= \u03b1*grad_mean[4]\n    m.b2 .-= \u03b1*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    \u03b8::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, \u03b8, dt  = prob.f, prob.\u03b8, solver.dt\n    (u + dt*f(u,\u03b8), t+dt)\nend\nstruct RK2{T} <: ODESolver\n    dt::T\nend\nfunction (solver::RK2)(prob::AbstractODEProblem, u, t)\n    f, \u03b8, dt  = prob.f, prob.\u03b8, solver.dt\n    du = f(u,\u03b8)\n    uh = u + du*dt\n    u + dt/2*(du + f(uh,\u03b8)), 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(;\u03b7::Real=0.001, \u03b2\u2081::Real=0.9, \u03b2\u2082::Real=0.999, \u03f5::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    \u03f5::Float64\n    \u03b7::Float64\n    \u03b2\u2081::Float64\n    \u03b2\u2082::Float64\n    m_t::AbstractArray\n    v_t::AbstractArray\nend\n\n\"Construct Nadam optimizer\"\nfunction Nadam(;\u03b7::Real=0.001, \u03b2\u2081::Real=0.9, \u03b2\u2082::Real=0.999, \u03f5::Real=10e-8)\n    @assert \u03b7 > 0.0 \"\u03b7 must be greater than 0\"\n    @assert \u03b2\u2081 > 0.0 \"\u03b2\u2081 must be greater than 0\"\n    @assert \u03b2\u2082 > 0.0 \"\u03b2\u2082 must be greater than 0\"\n    @assert \u03f5 > 0.0 \"\u03f5 must be greater than 0\"\n\n    Nadam(\"Nadam\", 0, \u03f5, \u03b7, \u03b2\u2081, \u03b2\u2082, [], [])\nend\n\nparams(opt::Nadam) = \"\u03f5=$(opt.\u03f5), \u03b7=$(opt.\u03b7), \u03b2\u2081=$(opt.\u03b2\u2081), \u03b2\u2082=$(opt.\u03b2\u2082)\"\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.\u03b2\u2081 * opt.m_t + (one(T) - opt.\u03b2\u2081) * g_t\n\n    # update biased second raw moment estimate\n    opt.v_t = opt.\u03b2\u2082 * opt.v_t + (one(T) - opt.\u03b2\u2082) * ((g_t) .^2)\n\n    # compute bias corrected first moment estimate\n    m\u0302_t = opt.m_t / (one(T) - opt.\u03b2\u2081^opt.t)\n\n    # compute bias corrected second raw moment estimate\n    v\u0302_t = opt.v_t / (one(T) - opt.\u03b2\u2082^opt.t)\n\n    # apply update\n    \u03c1 = opt.\u03b7 ./ (sqrt.(v\u0302_t .+ opt.\u03f5))\n    \u03c1 .*= (opt.\u03b2\u2081 * m\u0302_t + (one(T) - opt.\u03b2\u2081) * g_t / (one(T) - opt.\u03b2\u2081^opt.t))\n\n    return \u03c1\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": "# catalan\n@test catalannum(5) == 42\n@test catalannum(30) == parse(BigInt,\"3814986502092304\")\n@test_throws DomainError catalannum(-1)\n\n# fibonacci\n@test fibonaccinum(5) == 5\n@test fibonaccinum(101) == parse(BigInt,\"573147844013817084101\")\n@test_throws DomainError fibonaccinum(-1)\n\n# lassalle\n@test lassallenum(14) == parse(BigInt,\"270316008395632253340\")\n\n# legendresymbol\n@test legendresymbol(1001,9907) == jacobisymbol(1001,9907) == -1\n\n# lucas\n@test lucasnum(10) == 123\n@test lucasnum(100) == parse(BigInt,\"792070839848372253127\")\n@test_throws DomainError lucasnum(-1)\n\n# stirlings1\n@test_throws DomainError stirlings1(-1, 1)\n@test typeof(stirlings1(6, 2)) == Int\n@test stirlings1(0, 0) == 1\n@test stirlings1(1, 1) == 1\n@test stirlings1(2, 6) == 0\n@test stirlings1(6, 0) == 0\n@test stirlings1(6, 0, true) == 0\n@test stirlings1(6, 1) == 120\n@test stirlings1(6, 1, true) == -120\n@test stirlings1(6, 2) == 274\n@test stirlings1(6, 2, true) == 274\n@test stirlings1(6, 3) == 225\n@test stirlings1(6, 3, true) == -225\n@test stirlings1(6, 4) == 85\n@test stirlings1(6, 4, true) == 85\n@test stirlings1(6, 5) == 15\n@test stirlings1(6, 5, true) == -15\n@test stirlings1(6, 6) == 1\n@test stirlings1(6, 6, true) == 1\n@test sum([abs(stirlings1(8, i, true)) for i = 0:8]) == factorial(8)\n\n# stirlings2\n@test_throws DomainError stirlings2(-1, 1)\n@test typeof(stirlings2(6, 2)) == Int\n@test stirlings2(0, 0) == 1\n@test stirlings2(1, 1) == 1\n@test stirlings2(2, 6) == 0\n@test stirlings2(6, 0) == 0\n@test stirlings2(6, 1) == 1\n@test stirlings2(6, 2) == 31\n@test stirlings2(6, 3) == 90\n@test stirlings2(6, 4) == 65\n@test stirlings2(6, 5) == 15\n@test stirlings2(6, 6) == 1\n\n# bell\n@test bellnum(7) == 877\n@test bellnum(42) == parse(BigInt,\"35742549198872617291353508656626642567\")\n@test_throws DomainError bellnum(-1)\n", "meta": {"hexsha": "893a041f264c38bd3327afb7ce52aa7e1650cd56", "size": 1797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/numbers.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": "test/numbers.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": "test/numbers.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": 28.9838709677, "max_line_length": 75, "alphanum_fraction": 0.6839176405, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7905626344543911}}
{"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            \u03b8 = left_bound == -Inf ? 2*left_bound : 2*right_bound\n            if \u03b8 == -Inf || \u03b8 == Inf\n                error(\"Inverse Iteration Igen Search failed, bound limit reached for half opened interval.  \")\n            end\n        else\n            \u03b8 = (left_bound + right_bound)/2\n        end\n        println(\"\u03b8: $\u03b8 \u2208 [$left_bound, $right_bound]\")\n        # Inverse Power iterations.\n        \u03bb = \u03b8\n        while \u03bb == \u03b8 || norm(Au - \u03bb*u, 1) > 1e-10\n            println(\u03bb)\n            t .= u\n            u .= (A - \u03bb*I)\\v\n            u ./= norm(u)\n            if norm(u) == NaN\n                u .= v\n                println(\"coverted to $\u03bb\")\n                break\n            else\n                v .= t\n                Au = A*u\n                \u03bb = dot(u, Au)\n            end\n        end\n        # Interval shrink.\n        if \u03bb > left_bound && \u03bb < right_bound\n            \n            return \u03bb, u\n        else\n            if \u03bb <= left_bound\n                left_bound = \u03b8\n                \n            else\n                right_bound = \u03b8\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\u03bb, v = InversePowerIterSearch(A, A[1, 1], A[3, 3])\nprint(\"\u03bb = $\u03bb\")\n# \u03bb, v = InversePowerIterSearch(A, -Inf, A[2, 2])\n# print(\"\u03bb = $\u03bb\")", "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), \u03c3 = 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- `\u03c3`: 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    \u03c3                  = 1.0,\n    amin               = 1.0,\n    amax               = 2.0,\n)\n    x = LinRange(xmin, xmax, nx)\n    \u03bc = 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], \u03bc[c], \u03c3, x)\n            labels[i] = c\n            i += 1\n        end\n    end\n\n    return data, labels\nend\n\ngauss_func(a, \u03bc, \u03c3, x) = a * exp((-(x - \u03bc) .^ 2) / (2 * \u03c3^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, \u03f5a, \u03f5r, 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, \u03f5a::Float64=1e-8, \u03f5r::Float64=1e-6, itmax::Int=0, \u03b5::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 \u2016x\u2016\n    r = -b # initial residual r = Ax-b = -b\n    d = b # first descent direction\n    rNorm = norm(r, 2)\n    \u03f5 = \u03f5a + \u03f5r * 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\", \"\u2016r\u2016\", \"q\"))\n        @info(loggerCGlin, @sprintf(\"    %d    %8.1e    %8.1e\", iter, rNorm, q))\n    end\n\n    solved = rNorm \u2264 \u03f5\n    tired = iter \u2265 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 \u2264 \u03b5 * 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        \u03b1 = rNorm^2 / dAd # step for x estimation\n        x = x + \u03b1 * d # new estimation\n        xNorm = norm(x, 2)\n        push!(xNorms, xNorm)\n        roldNorm = rNorm\n        r = r + \u03b1 * 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 \u2264 \u03f5\n        tired = iter \u2265 itmax\n\n        (solved || tired) && continue\n        \u03b2 = rNorm^2 / roldNorm^2 # step for the next descent direction\n        d = -r + \u03b2 * 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\u00e8me ``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\u00e9es\n * **gradfk** : (Array{Float,1}) le gradient de la fonction f appliqu\u00e9 au point ``x_k``\n * **hessfk** : (Array{Float,2}) la Hessienne de la fonction f appliqu\u00e9 au point ``x_k``\n * **delta**  : (Float) le rayon de la r\u00e9gion de confiance\n\n# Sorties\n * **s** : (Array{Float,1}) une approximation de la  solution du sous-probl\u00e8me\n * **e** : (Integer) indice indiquant l'\u00e9tat 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": "## Discretize given percentiles (unweighted)\nfunction discretize_given_percentiles(inV :: Vector{Float64}, pctV :: Vector{Float64}, dbg :: Bool = false)\n    edgeV = bin_edges_from_percentiles(inV, pctV, dbg);\n    return discretize(inV, edgeV, dbg);\nend\n\n\n## Discretize given percentiles (weighted)\n# function discretize_given_percentiles(inV :: Vector{Float64}, wtV :: AbstractWeights,\n#    pctV :: Vector{Float64}, dbg :: Bool = false)\n\n#    edgeV = bin_edges_from_percentiles(inV, wtV, pctV, dbg);\n#    return discretize(inV, edgeV, dbg);\n# end\n\n\n## Discretize given bounds\n# Equivalent to Discretizers LinearDiscretizer\nfunction discretize(inV :: Vector{Float64}, edgeV :: Vector{Float64}, dbg :: Bool = false)\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 :: Vector{Float64}, pctV :: Vector{Float64}, dbg :: Bool = false)\n    edgeV = quantile(inV, [0.0; pctV]);\n    # Ensure that lowest point is inside edges\n    edgeV[1] -= 1e-8;\n    if dbg\n        @assert (minimum(inV) >= edgeV[1])\n    end\n    return edgeV\nend\n\n\n# ------------", "meta": {"hexsha": "4e37a0ba905527f0fd24e97a4b3ee2c2b452edde", "size": 1301, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/discretize.jl", "max_stars_repo_name": "hendri54/OptimizationLH", "max_stars_repo_head_hexsha": "2d5780bfaa085bc0a64f09c026fbd6b7b28df2d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/discretize.jl", "max_issues_repo_name": "hendri54/OptimizationLH", "max_issues_repo_head_hexsha": "2d5780bfaa085bc0a64f09c026fbd6b7b28df2d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/discretize.jl", "max_forks_repo_name": "hendri54/OptimizationLH", "max_forks_repo_head_hexsha": "2d5780bfaa085bc0a64f09c026fbd6b7b28df2d9", "max_forks_repo_licenses": ["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.2826086957, "max_line_length": 107, "alphanum_fraction": 0.6602613374, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.7904596624019452}}
{"text": " function j(n,k)\n    p, i, seq=[0:n-1], 0, Int[]\n    while !isempty(p)\n        i=(i+k-1)%length(p)\n        push!(seq,splice!(p,i+1))\n    end\n    @sprintf(\"Prisoner killing order: %s.\\nSurvivor: %i\",replace(chomp(string(seq[1:end-1])),\"\\n\",\", \"),seq[end])\nend\n", "meta": {"hexsha": "f71db474adb1ce41c4b866bf7334efeff5867e4f", "size": 259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/josephus-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/josephus-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/josephus-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": 28.7777777778, "max_line_length": 113, "alphanum_fraction": 0.5405405405, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7904445243000776}}
{"text": "@doc raw\"\"\"\n    rigid_body_velocity(vel_P, \u03c9, 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 (\u03c9) 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, \u03c9, r_PQ)\n    vel_Q = vel_P + \u03c9 \u00d7 r_PQ\n    return vel_Q\nend\n\n\n@doc raw\"\"\"\n    rigid_body_acceleration(acc_P, \u03c9, \u03c9_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 (\u03c9), the rotational acceleration of the solid\n(\u03c9_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, \u03c9, \u03c9_dot, r_PQ)\n    acc_Q = acc_P + \u03c9 \u00d7 (\u03c9 \u00d7 r_PQ) + \u03c9_dot \u00d7 r_PQ\n    return acc_Q\nend\n\n\n\"\"\"\n    pqr_2_\u03c8\u03b8\u03d5_dot(p, q, r, \u03c8, \u03b8, \u03d5)\n\nTransform body angular velocity (p, q, r) [rad/s] to Euler angles rates (\u03c8_dot, \u03b8_dot,\n\u03d5_dot) [rad/s] given the euler angles (\u03b8, \u03d5) [rad] using kinematic angular equations.\n\n# See also\n\n[`\u03c8\u03b8\u03d5_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_\u03c8\u03b8\u03d5_dot(p, q, r, \u03b8, \u03d5)\n\n    s\u03b8, c\u03b8 = sin(\u03b8), cos(\u03b8)\n    s\u03d5, c\u03d5 = sin(\u03d5), cos(\u03d5)\n\n    \u03c8_dot = (q * s\u03d5 + r * c\u03d5) / c\u03b8\n    \u03b8_dot = q * c\u03d5 - r * s\u03d5\n    # \u03d5_dot = p + (q * s\u03d5 + r * c\u03d5) * tan(\u03b8)\n    \u03d5_dot = p + \u03c8_dot * s\u03b8\n\n    return [\u03c8_dot, \u03b8_dot, \u03d5_dot]\nend\n\n\n\"\"\"\n    \u03c8\u03b8\u03d5_dot_2_pqr(\u03c8_dot, \u03b8_dot, \u03d5_dot, \u03c8, \u03b8, \u03d5)\n\nTransform Euler angles rates (\u03c8_dot, \u03b8_dot, \u03d5_dot) [rad/s] to body angular velocity (p, q,\nr) [rad/s] given the euler angles (\u03b8, \u03d5) [rad] using kinematic angular equations.\n\n# See also\n\n[`pqr_2_\u03c8\u03b8\u03d5_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 \u03c8\u03b8\u03d5_dot_2_pqr(\u03c8_dot, \u03b8_dot, \u03d5_dot, \u03b8, \u03d5)\n\n    s\u03b8, c\u03b8 = sin(\u03b8), cos(\u03b8)\n    s\u03d5, c\u03d5 = sin(\u03d5), cos(\u03d5)\n\n    p = \u03d5_dot - s\u03b8 * \u03c8_dot\n    q = c\u03d5 * \u03b8_dot + s\u03d5*c\u03b8 * \u03c8_dot\n    r = -s\u03d5 * \u03b8_dot + c\u03d5*c\u03b8 * \u03c8_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_\u03c8\u03b8\u03d5_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    \u03a9 = [\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 * \u03a9 * q\n\n    return q_dot\nend\n\n\n\"\"\"\n    uvw_to_tas\u03b1\u03b2(u, v, w)\n\nCalculate true air speed (TAS), angle of attack (\u03b1) and angle of side slip (\u03b2) 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\u03b1\u03b2(u, v, w)\n\n    tas = sqrt(u*u + v*v + w*w)\n    \u03b1 = atan(w, u)\n    \u03b2 = asin(v / tas)\n    return [tas, \u03b1, \u03b2]\nend\n\n\n\"\"\"\n    uvw_dot_to_tas\u03b1\u03b2_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\u03b1\u03b2_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\u03b1\u03b2_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    \u03b2_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    # \u03b2_dot = (v_dot * tas - v * tas_dot) / (tas * sqrt(u*u + w*w))\n    # [1] 3.33c\n    \u03b1_dot = (w_dot * u - w * u_dot) / (u*u + w*w)\n\n    return [tas_dot, \u03b1_dot, \u03b2_dot]\nend\n\n\n\"\"\"\n    tas\u03b1\u03b2_dot_to_uvw_dot(tas, \u03b1, \u03b2, tas_dot, \u03b1_dot, \u03b2_dot)\n\nObatain body velocity derivatives given velocity in wind axis and its derivatives.\n\n# See also\n\n[`uvw_dot_to_tas\u03b1\u03b2_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\u03b1\u03b2_dot_to_uvw_dot(tas, \u03b1, \u03b2, tas_dot, \u03b1_dot, \u03b2_dot)\n    u_dot = tas_dot * cos(\u03b1) * cos(\u03b2) - tas * (\u03b1_dot * sin(\u03b1) * cos(\u03b2) + \u03b2_dot * cos(\u03b1) * sin(\u03b2))\n    v_dot = tas_dot * sin(\u03b2) + tas * \u03b2_dot * cos(\u03b2)\n    w_dot = tas_dot * sin(\u03b1) * cos(\u03b2) + tas * (\u03b1_dot * cos(\u03b1) * cos(\u03b2) - \u03b2_dot * sin(\u03b1) * sin(\u03b2))\n    return [u_dot, v_dot, w_dot]\nend\n\n\n@doc raw\"\"\"\n    rate_of_climb_constrain_no_wind(\u03b3, \u03b1, \u03b2, \u03d5)\n\nCalculate pitch angle (\u03b8 rad) to obtain a flight path angle (\u03b3 rad) at certain angle of\nattack (\u03b1 rad), angle of sideslip (\u03b2 rad) and roll (\u03d5 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(\u03b3, \u03b1, \u03b2, \u03d5)\n    a = cos(\u03b1) * cos(\u03b2)\n    b = sin(\u03d5) * sin(\u03b2) + cos(\u03d5) * sin(\u03b1) * cos(\u03b2)\n    sq = sqrt(a^2 - sin(\u03b3)^2 + b^2)\n    \u03b8 = (a * b + sin(\u03b3) * sq) / (a^2 - sin(\u03b3)^2)\n    \u03b8 = atan(\u03b8)\n    return \u03b8\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": "using OrthoPoly\nusing Polynomials\nusing Test\n\nfunction orthogonal_poly_test(F,Ps,num=[])\n    if num == []\n        num = ones(eltype(Ps[1]), length(Ps))\n    end\n    for n=0:length(Ps)-1\n        f = F(n)\n        p = Poly(Ps[n+1])/num[n+1]\n        @test f == p\n    end\nend\n\nprintln(\"Testing the first 11 Legendre polynomials\")\northogonal_poly_test(legendre, [[1],[0,1],[-1,0,3],[0,-3,0,5],[3,0,-30,0,35],[0,15,0,-70,0,63],[-5,0,105,0,-315,0,231],[0,-35,0,315,0,-693,0,429],[35,0,-1260,0,6930,0,-12012,0,6435],[0,315,0,-4620,0,18018,0,-25740,0,12155],[-63,0,3465,0,-30030,0,90090,0,-109395,0,46189]], [1 1 2 2 8 8 16 16 128 128 256])\n\nprintln(\"Testing the first 16 Chebyshev polynomials of the first kind\")\northogonal_poly_test(chebyshevT, [[1],[0,1],[-1,0,2],[0,-3,0,4],[1,0,-8,0,8],[0,5,0,-20,0,16],[-1,0,18,0,-48,0,32],[0,-7,0,56,0,-112,0,64],[1,0,-32,0,160,0,-256,0,128],[0,9,0,-120,0,432,0,-576,0,256],[-1,0,50,0,-400,0,1120,0,-1280,0,512],[0,-11,0,220,0,-1232,0,2816,0,-2816,0,1024],[1,0,-72,0,840,0,-3584,0,6912,0,-6144,0,2048],[0,13,0,-364,0,2912,0,-9984,0,16640,0,-13312,0,4096],[-1,0,98,0,-1568,0,9408,0,-26880,0,39424,0,-28672,0,8192],[0,-15,0,560,0,-6048,0,28800,0,-70400,0,92160,0,-61440,0,16384]])\n\nprintln(\"Testing the first 16 Chebyshev polynomials of the second kind\")\northogonal_poly_test(chebyshevU, [[1],[0,2],[-1,0,4],[0,-4,0,8],[1,0,-12,0,16],[0,6,0,-32,0,32],[-1,0,24,0,-80,0,64],[0,-8,0,80,0,-192,0,128],[1,0,-40,0,240,0,-448,0,256],[0,10,0,-160,0,672,0,-1024,0,512],[-1,0,60,0,-560,0,1792,0,-2304,0,1024],[0,-12,0,280,0,-1792,0,4608,0,-5120,0,2048],[1,0,-84,0,1120,0,-5376,0,11520,0,-11264,0,4096]])\n\nprintln(\"Testing the first 11 Hermite polynomials\")\northogonal_poly_test(hermite_prob, [[1],[0,1],[-1,0,1],[0,-3,0,1],[3,0,-6,0,1],[0,15,0,-10,0,1],[-15,0,45,0,-15,0,1],[0,-105,0,105,0,-21,0,1],[105,0,-420,0,210,0,-28,0,1],[0,945,0,-1260,0,378,0,-36,0,1],[-945,0,4725,0,-3150,0,630,0,-45,0,1]])\northogonal_poly_test(hermite, [[1],[0,2],[-2,0,4],[0,-12,0,8],[12,0,-48,0,16],[0,120,0,-160,0,32],[-120,0,720,0,-480,0,64],[0,-1680,0,3360,0,-1344,0,128],[1680,0,-13440,0,13440,0,-3584,0,256],[0,30240,0,-80640,0,48384,0,-9216,0,512],[-30240,0,302400,0,-403200,0,161280,0,-23040,0,1024]])\n\nprintln(\"Testing the first 9 Laguerre polynomials\")\northogonal_poly_test(n -> laguerre(n, Poly([0,1//1])), [[1],[1,-1],[2,-4,1],[6,-18,9,-1],[24,-96,72,-16,1],[120,-600,600,-200,25,-1],[720,-4320,5400,-2400,450,-36,1],[5040,-35280,52920,-29400,7350,-882,49,-1],[40320,-322560,564480,-376320,117600,-18816,1568,-64,1]], [1 1 2 6 24 120 720 5040 40320]//1)\n\nprintln(\"Testing the first 4 associated Laguerre polynomials\")\nfor \u03b1=[1,1.0,2,2.0,2.1]\n    orthogonal_poly_test(n -> laguerre_assoc(n,\u03b1,Poly([0,one(\u03b1)])),\n                         [[1],[1+\u03b1,-1],[(\u03b1+2)*(\u03b1+1),-2(\u03b1+2),1],[(\u03b1+1)*(\u03b1+2)*(\u03b1+3),-3(\u03b1+2)*(\u03b1+3),3(\u03b1+3),-1]], [1.0 1 2 6])\nend\n", "meta": {"hexsha": "2d69572b2707a7783185385aeb209639d1776628", "size": 2843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jagot/OrthoPoly.jl", "max_stars_repo_head_hexsha": "fbf3fa4da13676288805a90cd51c3ef85fa89bba", "max_stars_repo_licenses": ["MIT"], "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": "jagot/OrthoPoly.jl", "max_issues_repo_head_hexsha": "fbf3fa4da13676288805a90cd51c3ef85fa89bba", "max_issues_repo_licenses": ["MIT"], "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": "jagot/OrthoPoly.jl", "max_forks_repo_head_hexsha": "fbf3fa4da13676288805a90cd51c3ef85fa89bba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T09:36:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T09:36:58.000Z", "avg_line_length": 76.8378378378, "max_line_length": 504, "alphanum_fraction": 0.6021807949, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7904445175800139}}
{"text": "using Roots\nusing Polynomials\nusing Base.Test\nusing Primes\n\n## can use functions\nf = x -> (x-1)*(x-2)^2*(x-3)^3\nzs, mults = multroot(f)\n@test mults == [1,2,3]\n\nx = poly([0.0])\n\np = (x-1)*(x-2)^2*(x-3)^3\nzs, mults = multroot(p)\n@test mults == [1,2,3]\n\np = (x-1)^2*(x-2)^2*(x-3)^4\nzs, mults = multroot(p)\n@test mults == [2,2,4]\n\np = (x-1)^2\nzs, mults = multroot(p^14)\n@test mults == [28]\n\n## test for roots of polynomial functions\nroots(x -> x^5 - x + 1)\n\n## test for real roots of polynomial functions\nfzeros(x -> x^5 - 1.5x + 1)\n\n\n## for polynomials in Z[x], Q[x] can use algorithm to be accurate for higher degree\n\n@test fzeros(x -> x - 1)[1] == 1.0 # linear\nf = x -> (x-1)*(x-2)*(x-3)^3*(x^2+1)\nrts = fzeros(f)\nrts = Float64[r for r in rts]\n@test maximum(abs(sort(rts) - [1.0, 2.0, 3.0])) <= 1e-12\nx = poly([big(0)])\np = prod([x - i for i in 1:20])\nRoots.real_roots(p) ## can find this\nf = x -> (x-20)^5 - (x-20) + 1\na = fzeros(f)[1]\n@assert abs(f(a)) <= 1e-14\n\nx = poly([0.0])\n@test abs(fzeros((x-20)^5 - (x-20) + 1)[1] - (20 + fzeros(x^5 - x + 1)[1])) <= 1/2\n\nfzeros(x -> x^5 - 2x^4 + x^3)\n\n## factor\nfactor(x -> (x-2)^4*(x-3)^9)\nfactor(x -> (x-1)^3 * (x-2)^3 * (x^5 - x + 1))\nfactor(x -> x*(x-1)*(x-2)*(x^2 + x + 1))\n\nfactor(x -> (x-1)^2 * (x-.99)^2 * (x-1.01)^2) ## can have issue with nearby roots (or high powers)\n\nfactor(x -> (x-1//1)^2 * (x-99//100)^2 * (x-101//100)^2) ## conversion is to Float, not Rational{Int}\ndelta = 1//10\nVERSION >= v\"0.5.0-\" && Primes.factor(convert(Poly{Rational{Int}}, x -> (x-1//1)^2 * (x-1 - delta)^2 * (x-1 + delta)^2))\n\n\n## Test conversion of polynomials to Int\nf = x -> 3x^3 - 2x\nconvert(Polynomials.Poly{Int}, f)\nf = x -> (3x^3 - 2x)/3\nconvert(Polynomials.Poly{Int}, f)\nf = x ->  x^2 / x # rational functions fails\n@test_throws MethodError convert(Polynomials.Poly{Int64}, f)\nf = x ->  (x^2 + x)^2\nconvert(Polynomials.Poly{Int}, f)\nf = x ->  (x^2 + x)^(1/2)\n@test_throws MethodError convert(Polynomials.Poly{Int64}, f)\n\n\n## polynomial conversions from functions in practice\nfzeros(x -> 265 - 0.65x)\nfzeros(x -> -16x^2 + 200x)\n", "meta": {"hexsha": "4e458a3e4193389969d5f9480049800b07369984", "size": 2069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tests_multroot.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/tests_multroot.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/tests_multroot.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": 26.1898734177, "max_line_length": 120, "alphanum_fraction": 0.5766070565, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7904445129436379}}
{"text": "using LinearAlgebra\nfunction MSE(y, t; mean_f = true) # this is Mean Square Error\n    if size(y) != size(t)\n        y = y'\n    end\n    mse = sum((y - t) .^ 2)\n    if mean_f\n        mse /= length(y) #mse is Mean Square error \n    end\n    return mse\nend\nfunction CEE(p, t; mean_f = true, t_f = false) #this is Cross entropy Error\n    function safe_log(x, miniv = 0.00000000001)\n        return map(log, clamp.(x, miniv, Inf))\n    end\n    if t_f\n        loss = -sum(t .* safe_log(p) + (1 .- t) .* safe_log(1 .- p))\n    else\n        loss = -sum(t .* safe_log(p))\n    end\n    if mean_f\n        loss = loss / length(t)\n    end\n    return loss\nend", "meta": {"hexsha": "4a00fe2190dd1f95fae0910ddda89135accd57cd", "size": 639, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LossFunction/LossFunctions.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/LossFunction/LossFunctions.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/LossFunction/LossFunctions.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": 25.56, "max_line_length": 75, "alphanum_fraction": 0.5555555556, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018419665618, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.790380522378246}}
{"text": "using DelimitedFiles\nusing Test\n\n\n\"\"\"\n    get_seat_ids(data)\n\nGet all seat ids. Map to binary strings, parse as Int-base2, add.\n\"\"\"\nfunction get_seat_ids(data)\n    rowbin = Dict('F' => '0', 'B' => '1')\n    colbin = Dict('L' => '0', 'R' => '1')\n    rows = [parse(Int, join(rowbin[c] for c in row[1:7]), base=2) for row in data]\n    cols = [parse(Int, join(colbin[c] for c in row[8:10]), base=2) for row in data]\n    return [8*row + col for (row, col) in zip(rows, cols)]\n    end\n\ntest = readdlm(\"./data/day05_test.txt\")\n@test all(get_seat_ids(test) .== [567, 119, 820])\n\ndata = readdlm(\"./data/day05.txt\")\nseats = get_seat_ids(data)\nprintln(\"Part 1 max id: $(maximum(seats))\")\n\n\n\"\"\"\n    get_my-seat(data)\n\nFind missing id for which id-1 and id+1 are present.\nJust going to brute force this, there aren't that many.\n\"\"\"\nfunction get_my_seat(seats)\n    for s in 1:maximum(seats)\n        if s \u2209 seats && s-1 \u2208 seats && s+1 \u2208 seats\n            return s\n            end\n        end\n    end\n\nprintln(\"Part 2 my seat: $(get_my_seat(seats))\")\n", "meta": {"hexsha": "2f8b81ba2ac5f7fe137a99a4c54b03a007814470", "size": 1034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day05.jl", "max_stars_repo_name": "kwinkunks/aoc20", "max_stars_repo_head_hexsha": "25bf928d5a9f73f30c5e2c69dd75c92411e1e232", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-01T16:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T16:24:54.000Z", "max_issues_repo_path": "day05.jl", "max_issues_repo_name": "kwinkunks/aoc20", "max_issues_repo_head_hexsha": "25bf928d5a9f73f30c5e2c69dd75c92411e1e232", "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": "day05.jl", "max_forks_repo_name": "kwinkunks/aoc20", "max_forks_repo_head_hexsha": "25bf928d5a9f73f30c5e2c69dd75c92411e1e232", "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.2195121951, "max_line_length": 83, "alphanum_fraction": 0.6102514507, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.7903378368680521}}
{"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": "using TuringModels\n\nTuring.setadbackend(:reverse_diff);\nTuring.turnprogress(false);\n\n# In Rethinking the model actually has priors that are Uniform[-Inf, Inf], or as the Stan manual (2.17.0, pp. 127) tells us:\n\n# \"A parameter declared without constraints is thus given a uniform prior\n# on (\u2212\u221e, \u221e) ...\"\n\n# Setting -Inf and Inf in Turing doesn't work. So the below works of\n# course better since we've restrained it to [-1,1]\n\n@model m8_2(y) = begin\n    \u03c3 ~ Uniform(0, Inf)\n    \u03b1 ~ Uniform(-Inf, Inf)\n\n    for i \u2208 1:length(y)\n        y[i] ~ Normal(\u03b1, \u03c3)\n    end\nend\n\ny = [-1,1];\n\n# Sample\n\nchns = sample(m8_2(y), NUTS(0.65), 1000)\n\n# Results rethinking\n\nm82rethinking = \"\n       mean   sd  5.5% 94.5% n_eff Rhat\na      9.22 0.15  9.00  9.46   205    1\nbR    -0.20 0.08 -0.34 -0.07   192    1\nbA    -1.95 0.24 -2.36 -1.59   203    1\nbAR    0.40 0.14  0.19  0.63   186    1\nsigma  0.95 0.05  0.88  1.04   361    1\n\";\n\n# Describe the posterior samples\n\ndescribe(chns)\n\n# End of `08/m8.2t.jl`\n", "meta": {"hexsha": "9bba7c1e7d7765c31e360871a19b923dd9959d3f", "size": 988, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/08/m8.2t.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/08/m8.2t.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/08/m8.2t.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": 21.9555555556, "max_line_length": 124, "alphanum_fraction": 0.6163967611, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.7903378292697948}}
{"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(\u03a0y -> real(\u03a0y), povm_vars)) == Matrix{Float64}(I, d, d)\n    constraints += sum(map(\u03a0y -> imag(\u03a0y), povm_vars)) == zeros(Float64, d, d)\n\n    # apply channel to states\n    evolved_states = map(\u03c1 ->  sum(k -> k * \u03c1 * 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(\u03a0y -> \u03a0y.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(\u03a0 ->  sum(k -> k' * \u03a0 * 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(\u03d5)\n\nThe phase shift gate ``R_\u03d5``.\nThis is equivalent to qiskit's `u1` gate.\n\"\"\"\nfunction Rphi(\u03d5)\n    return [1 0; 0 cis(\u03d5)]\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_\u03d5`` gate for ``\u03d5 = z\u03c0``. 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(\u03d5, \u03bb)\n\nu2 gate. Need to put math definitions in here.\n\"\"\"\nfunction U2(\u03d5, \u03bb)\n    return [1 -cis(\u03bb); cis(\u03d5) cis(\u03d5 + \u03bb)] / sqrt(2)\nend\n\n# This does not appar any faster than computing each separately\n# function RXalt(\u03b8)\n#     (s, c) = sincos(\u03b8/2)\n#     si = - im * s\n#     return [c si; si c]\n# end\n\nfunction RX(\u03b8)\n    c = cos(\u03b8/2)\n    s = - im * sin(\u03b8/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(\u03b8)\n    c = cos(\u03b8/2)\n    s = sin(\u03b8/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(\u03b8)\n    return [cis(-\u03b8/2) 0; 0 cis(\u03b8/2)]\nend\n\nfunction RZpi(z)\n    return [_exp_ipi(-z/2) 0; 0 _exp_ipi(z/2)]\nend\n\n\"\"\"\n    Ualt(\u03b8, \u03d5, \u03bb)\n\nMatrix from SU(2).\nAlternative parameterization.\n\"\"\"\nfunction Ualt(\u03b8, \u03d5, \u03bb)\n    c = cos(\u03b8/2)\n    s = sin(\u03b8/2)\n    fpl =  (\u03d5 + \u03bb) / 2\n    cfpl = cos(fpl)\n    sfpl = sin(fpl)\n    fml =  (\u03d5 - \u03bb) / 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(\u03b8, \u03d5, \u03bb)\n\nMatrix from SU(2). This is\nthe same as qiskit's U or U3.\n\"\"\"\nfunction U(\u03b8, \u03d5, \u03bb)\n    c = cos(\u03b8/2)\n    s = sin(\u03b8/2)\n    fpl =  (\u03d5 + \u03bb)\n    cfpl = cos(fpl)\n    sfpl = sin(fpl)\n    f00 = c\n    f01 = -s * complex(cos(\u03bb), sin(\u03bb))\n    f10 = s * complex(cos(\u03d5), sin(\u03d5))\n    f11 = c * complex(cfpl, sfpl)\n    return [f00 f01; f10 f11]\nend\n\n\"\"\"\n    Ualtpi(\u03b8, \u03d5, \u03bb)\n\nMatrix from SU(2), with `\u03b8`, `\u03d5`, and `\u03bb` given as multiples of `\u03c0`.\nThis is more accurate than `Ualt`.\n\"\"\"\nfunction Ualtpi(\u03b8, \u03d5, \u03bb)\n    c = cospi(\u03b8/2)\n    s = sinpi(\u03b8/2)\n    fpl =  (\u03d5 + \u03bb) / 2\n    fml =  (\u03d5 - \u03bb) / 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(\u03b8, \u03d5)\n\nThe R gate.\n```math\nR(\\theta, \\phi) = e^{-i \\frac{\\theta}{2} (\\cos{\\phi} x + \\sin{\\phi} y)}\n```\n\"\"\"\nfunction R(\u03b8, \u03d5)\n    c = cos(\u03b8/2)\n    s = sin(\u03b8/2)\n    return [c -im*exp(-im*\u03d5)*s;\n            -im*exp(im*\u03d5)*s c]\nend\n\n@doc raw\"\"\"\n    Rpi(\u03b8, \u03d5)\n\nThe R gate with \u03b8 and \u03d5 reduced by \u03c0. This is may be more accurate,\nfor example with integral and half-integral multiples of \u03c0.\n```math\nRpi(\\theta, \\phi) = e^{-i \\frac{\\pi\\theta}{2} (\\cos{\\pi\\phi} x + \\sin{\\pi\\phi} y)}\n```\n\"\"\"\nfunction Rpi(\u03b8, \u03d5)\n    c = cospi(\u03b8/2)\n    s = sinpi(\u03b8/2)\n    return [c -im*cispi(-\u03d5)*s;\n            -im*cispi(\u03d5)*s c]\nend\n\n\"\"\"\n    RXXYY(\u03b8)\n\nThe R_XXYY gate, `exp(-im \u03b8 / 2 (X\u2297X + Y\u2297Y))`.\n\"\"\"\nfunction RXXYY(\u03b8)\n    _RXXYY(\u03b8, cos, sin)\nend\n\n\"\"\"\n    RXXYYpi(\u03b8)\n\nThe R_XXYY gate with `\u03b8` scaled by `\u03c0`. `exp(-im * pi * \u03b8 / 2 * (X\u2297X + Y\u2297Y))`\n\"\"\"\nfunction RXXYYpi(\u03b8)\n    _RXXYY(\u03b8, cospi, sinpi)\nend\n\n\nfunction _RXXYY(\u03b8, cfunc, sfunc)\n    II = I2 \u2297 I2 / 2\n    XX = X \u2297 X / 2\n    YY = Y \u2297 Y / 2\n    ZZ = Z \u2297 Z / 2\n    return II + ZZ + cfunc(\u03b8) * (II - ZZ) -im * sfunc(\u03b8) * (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": "# Copyright (c) 2022 Code Komali\n# \n# This software is released under the MIT License.\n# https://opensource.org/licenses/MIT\n\nusing Test, Printf, Memoize\n\n# A global variable just for simple benchmarking\ncalled = 0\n\n# Using the Memoize package\n@memoize Dict function knapsack(values, weights, MaxWieght)\n    global called += 1\n    if MaxWieght < 0\n        return -Inf\n    elseif isempty(values)\n        return 0\n    else\n        max(values[end] + knapsack(values[1:end-1], weights[1:end-1], MaxWieght - weights[end]),\n            knapsack(values[1:end-1], weights[1:end-1], MaxWieght))\n    end\nend\n\n# Non memoized bruteforce approach\nfunction knapsack_bruteforce(values, weights, MaxWieght)\n    global called += 1\n    if MaxWieght < 0\n        return -Inf\n    elseif isempty(values)\n        return 0\n    else\n        max(values[end] + knapsack_bruteforce(values[1:end-1], weights[1:end-1], MaxWieght - weights[end]),\n            knapsack_bruteforce(values[1:end-1], weights[1:end-1], MaxWieght))\n    end\nend\n\nfunction compute_knapsack(values, weights, MaxWieght; memoized = true)\n    empty!(memoize_cache(knapsack))\n    global called = 0\n    result = memoized ? knapsack(values, weights, MaxWieght) : knapsack_bruteforce(values, weights, MaxWieght)\n    #uncomment the below code for call count\n    #@printf \"\\n Function called: %d \\n\" called\n    return result\nend\n\n\n@testset \"0-1 knapsack problem tests\" begin\n    @test compute_knapsack([20, 5, 10, 40, 15, 25], [1, 2, 3, 8, 7, 4], 10, memoized = false) == 60\n    @test compute_knapsack([60, 100, 120], [10, 20, 30], 50, memoized = false) == 220\n    @test compute_knapsack([20, 5, 10, 40, 15, 25], [1, 2, 3, 8, 7, 4], 10) == 60\n    @test compute_knapsack([60, 100, 120], [10, 20, 30], 50) == 220\n    @test compute_knapsack([92, 57, 49, 68, 60, 43, 67, 84, 87, 72],\n        [23, 31, 29, 44, 53, 38, 63, 85, 89, 82], 165) == 309\nend\n\n\n@time compute_knapsack([92, 57, 49, 68, 60, 43, 67, 84, 87, 72],\n    [23, 31, 29, 44, 53, 38, 63, 85, 89, 82], 165)\n@time compute_knapsack([92, 57, 49, 68, 60, 43, 67, 84, 87, 72],\n    [23, 31, 29, 44, 53, 38, 63, 85, 89, 82], 165, memoized = false)\n\n#Note: \n# The memoized version is being called less number of times as expected.\n# But, it is taking more time to compute. Need to investigate more.", "meta": {"hexsha": "76bd079f5804338b72c180e1226f576fb03ca4cb", "size": 2281, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "knapsack.jl", "max_stars_repo_name": "codekomali/JuliaPractice", "max_stars_repo_head_hexsha": "68a11ad58f7e4617f4f5f2b30ffd2b00d87ab075", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knapsack.jl", "max_issues_repo_name": "codekomali/JuliaPractice", "max_issues_repo_head_hexsha": "68a11ad58f7e4617f4f5f2b30ffd2b00d87ab075", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knapsack.jl", "max_forks_repo_name": "codekomali/JuliaPractice", "max_forks_repo_head_hexsha": "68a11ad58f7e4617f4f5f2b30ffd2b00d87ab075", "max_forks_repo_licenses": ["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.640625, "max_line_length": 110, "alphanum_fraction": 0.6475230162, "num_tokens": 847, "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\u0394  = LVector(\n       inf=(LVector(S=1, I=1), LVector(I=2)),\n       rec=(LVector(I=1),      LVector(R=1)),\n     )\nsir = Petri.Model(S, \u0394)\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 `\u03b2`\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\u03b2 = 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: `\u03b2 = [.25]`\n#   - where the rate is specified by a value of type `Number`\n# - time dependent: `\u03b2 = [t->((3/1000)/(t+1))]`\n#   - where `t` is the current time step\n# - state and time dependent: `\u03b2 = [(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, \u03b2)\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, \u03b2)\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, \u03b2)\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\u0394 = 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, \u0394)\n\nGraph(seir)\n#-\nu0 = LVector(S=990.0, E=10.0, I=0.0, R=0.0)\ntspan = (0.0,40.0)\n\u03b2 = LVector(exp=0.7/sum(u0), inf=0.5, rec=0.25)\n\nprob, cb = SDEProblem(seir, u0, tspan, \u03b2)\nsol = StochasticDiffEq.solve(prob,LambaEM(),callback=cb)\n\nplot(sol)\n\n# ### SEIRD Model\n\nS = [:S,:E,:I,:R, :D]\n\u0394 = 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, \u0394)\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\u03b2 = LVector(exp=0.9/sum(u0), inf=0.9, rec=0.25, die=0.03)\n\nprob, cb = SDEProblem(seird, u0, tspan, \u03b2)\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, \u03d5b and \u03b2, for problem 2, \n# with N subdivisions\nfunction boundaryconditions3(N::Integer)\n    \u03d5b = zeros(N+1,N+1)                 # boundary conditions\n    \u03b2  = zeros(Int,N+1,N+1)             # boundary condition locations\n\n    # Conditions on the perimeter\n    \u03d5b[:,1] = \u03d5b[:,N+1] = \u03d5b[1,:] = \u03d5b[N+1,:] = 0.0\n    \u03b2[:,1]  = \u03b2[:,N+1]  = \u03b2[1,:]  = \u03b2[N+1,:]  = 1\n\n    # Conditions on the interior\n    # xmin < x < xmax  \u2192  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    \u03d5b[xs,ys] = 0.0\n    \u03b2[xs,ys]  = 1\n\n    return \u03d5b, \u03b2\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 ./ \u221a(a .+ b')\n\nend\n\nV(N::Integer, q::Real) = V(0.5, 0.25, N, q)\n\nfunction minor(A::Matrix, \u03b2::Vector)\n    \n    size(A)[1] == size(A)[2] || error(\"Matrix must be square\")\n\n    N = sum(1 .- \u03b2)             # 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        \u03b2[j] == 1 && continue\n        for i in 1:size(A)[2]\n            \u03b2[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, \u03b2::Vector)\n\n    vf = Array(typeof(v[1]),length(\u03b2))\n    ii = 1\n\n    length(v) == sum(1-\u03b2) || error(\"v and \u03b2 have different num free params\")\n\n    for i in 1:length(\u03b2)\n        if \u03b2[i] == 1\n            vf[i] = 0               # put zero for a fixed value\n        elseif \u03b2[i] == 0\n            vf[i] = v[ii]           # fill in the free value\n            ii += 1                 # prep the next free value\n        else\n            error(\"\u03b2 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 LinearAlgebra\n\nA = [1 2 3;\n     1 2 4;\n     0 2 1;]\n\nprintln(\"rank=\", rank(A))\nprintln(\"nullity=\", length(nullspace(A)))\nprintln(\"dim(V)=\", size(A)[2])", "meta": {"hexsha": "2bce91d9b0ab1deb85a3706de4097ec65944f505", "size": 157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_algebra/rank_nullity_theorem.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/rank_nullity_theorem.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/rank_nullity_theorem.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": 17.4444444444, "max_line_length": 41, "alphanum_fraction": 0.5796178344, "num_tokens": 59, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.790277869299459}}
{"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\u2080 = 1.0\ng(t) = t*NNODE(t) + u\u2080\n\n\n\n#Construct loss function to numericaly compute derivative and check against R.H.S.\n\u03f5 = sqrt(eps(Float32))\nloss() = mean(abs2(((g(t+\u03f5)-g(t))/\u03f5) - cos(2\u03c0*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\u2080 .+ sin.(2\u03c0.*t)/2\u03c0, 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 isdivisiblebyall(n, tab)\n\tfor v in tab\n\t\tif n % v != 0\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\n\nimport Base.factorize\nfunction factorize(n,F)\n\tf = zeros(eltype(n), F)\n\tf[1] = 1\n\ti = n\n\twhile i > 1\t\n\t\tif isprime(i) && n % i == 0\n\t\t\tf[i] += 1\n\t\t\tn = div(n,i)\n\t\t\ti = n\n\t\telse\n\t\t\ti -= 1\n\t\tend\n\tend\n\treturn f\nend\n\nfunction main()\n\tN = 20\n\tf = zeros(eltype(N), N, N)\n\tfor i = N:-1:1\n\t\tf[:,i] = factorize(i, N)\n\tend\n\tprintln(f)\n\tresf = maximum(f, 2)\n\tprintln(resf')\n\tn = 1\n\tfor i = 1:N\n\t\tfor j = 1:resf[i]\n\t\t\tn *= i\n\t\tend\n\tend\n\tprintln(n)\n\tassert(isdivisiblebyall(n, [1:N]))\nend\n\nmain()\n", "meta": {"hexsha": "9132f4c8228de7cbe690c374e39ee010c4111dc8", "size": 593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem5.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": "problem5.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": "problem5.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": 12.6170212766, "max_line_length": 35, "alphanum_fraction": 0.5615514334, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7902778520139587}}
{"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 OptimalTransport\nusing Distances\n\nimport LinearAlgebra\nimport Random\nusing Test\n\nRandom.seed!(1234)\n\n@testset \"Initial map\" begin\n    # example from \"Computational Optimal Transport\"\n    P = zeros(3, 3)\n    OptimalTransport.initialmap!(P, [0.2, 0.5, 0.3], [0.5, 0.1, 0.4])\n    @test P == [0.2 0 0; 0.3 0.1 0.1; 0 0 0.3]\nend\n\n# example taken from https://www.me.utexas.edu/~jensen/models/network/net8.html\n@testset \"Simple problem\" begin\n    C = [3 1 1000; 4 2 4; 1000 3 3]\n    P, f, g = earthmover([5, 7, 3], [7, 3, 5], C)\n\n    @test vec(sum(P; dims=1)) == [7, 3, 5]\n    @test vec(sum(P; dims=2)) == [5, 7, 3]\n    @test LinearAlgebra.dot(C, P) == 46\nend\n\n@testset \"Total variation\" begin\n    histogram1 = LinearAlgebra.normalize!(rand(20), 1)\n    histogram2 = LinearAlgebra.normalize!(rand(20), 1)\n\n    C = (!==).(1:20, (1:20)')\n    P, f, g = earthmover(histogram1, histogram2, C)\n\n    @test vec(sum(P; dims=1)) \u2248 histogram2\n    @test vec(sum(P; dims=2)) \u2248 histogram1\n    @test LinearAlgebra.dot(C, P) \u2248 totalvariation(histogram1, histogram2)\nend", "meta": {"hexsha": "df05df7a81026de1efc9ecc406c355520a27da6c", "size": 1052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 28.4324324324, "max_line_length": 79, "alphanum_fraction": 0.6311787072, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464605, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7902066736844177}}
{"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 * \u03c0 / 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\u03c0\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\u00d72 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 \u22ee\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": "module GlorotUniform\r\n    function GUMatrix(input_size::Int64, layer_size::Int64, shape::Any)\r\n        return rand(-sqrt(6/(input_size+layer_size)):0.00001:sqrt(6/(input_size+layer_size)), shape)\r\n    end\r\n    export GUMatrix\r\nend\r\n\r\n# Source: https://keras.io/api/layers/initializers/#glorotuniform-class\r\n", "meta": {"hexsha": "c54591c2087c5db540fe6fd3c220d88431c845dc", "size": 307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools/glorotuniform.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/tools/glorotuniform.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/tools/glorotuniform.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": 34.1111111111, "max_line_length": 101, "alphanum_fraction": 0.7198697068, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7902013970313263}}
{"text": "const jennrich_sampson = let res_init=zeros(10), jac_init=zeros(10,2), x_init=[0.3, 0.4]\n\n    function res(x, r)\n        for i = 1:10\n            ti = Float64(i)\n            r[i] = 2.0e0 + 2.0e0*ti - (exp(ti*x[1]) + exp(ti*x[2]))\n        end\n        return r\n    end\n\n    function jac(x, j)\n        for i = 1:10\n            ti = Float64(i)\n            j[i,1] = -ti * exp(ti*x[1])\n            j[i,2] = -ti * exp(ti*x[2])\n        end\n        return j\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"jennrich_sampson\", res, jac,\n                                                            res_init, jac_init, x_init;\n                                                            scale=scale, verbose=verbose,\n                                                            print_steps=print_steps)\nend\n", "meta": {"hexsha": "3c099002a6a391bca1954872564343e5f180179d", "size": 815, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/jennrich_sampson.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/jennrich_sampson.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/jennrich_sampson.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": 32.6, "max_line_length": 89, "alphanum_fraction": 0.4122699387, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.790201393772565}}
{"text": "@testset \"exponentiated\" begin\n    rng = MersenneTwister(123456)\n    x = rand(rng)*2\n    v1 = rand(rng, 3)\n    v2 = rand(rng, 3)\n\n    k = ExponentiatedKernel()\n    @test kappa(k,x) \u2248 exp(x)\n    @test kappa(k,-x) \u2248 exp(-x)\n    @test k(v1,v2) \u2248 exp(dot(v1,v2))\n    @test metric(ExponentiatedKernel()) == KernelFunctions.DotProduct()\n    @test repr(k) == \"Exponentiated Kernel\"\n    test_ADs(ExponentiatedKernel)\nend\n", "meta": {"hexsha": "a8c117b3b1562f8d3efafcfc56a91ce2ecd45f74", "size": 413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/exponentiated.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": "test/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": "test/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": 27.5333333333, "max_line_length": 71, "alphanum_fraction": 0.6271186441, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7902013822400019}}
{"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.:\u2248(l::ComplexNumber,r::ComplexNumber) = l.mat \u2248 r.mat # I had to make one of the division tests \u2248 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 \u03b9 will take off as the sensible symbol to use for the imaginary unit\nconst \u03b9 = 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": "\nusing LinAlgBigFloat.VectorSpaces\nusing Random\n\nRandom.seed!(1)\n\nl, n, m = 2, 6, 4\nA = randn(n, m)\nB = randn(l, n)\n\nvz = ZeroSpace(n)\n@test rank(vz) == 0 && dim(vz) == n\n\nvf = VectorSpace(n)\n@test rank(vf) == n && dim(vf) == n\n\nva = VectorSpace(A)\n@test rank(va) == min(m, n) && dim(va) == n\nvb = VectorSpace(B)\n@test rank(vb) == min(l, n) && dim(vb) == l\n\n@test va == image(A)\n@test vb == image(B)\n\n@test vz \u2286 va \u2286 vf\n\n@test kernel(A) == ZeroSpace(m)\n@test image(B) == VectorSpace(l)\n\n@test kernel(A) == preimage(A)\n\n\n", "meta": {"hexsha": "0a11c44e2a23ab2b76aae5a4f62656d9896b739d", "size": 520, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/spaces_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/spaces_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/spaces_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": 15.7575757576, "max_line_length": 43, "alphanum_fraction": 0.5807692308, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7901667681723973}}
{"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": "using SymPy\nusing Base.Test\nusing Compat\n\n## Symbol creation\nx = Sym(\"x\")\n#x = sym\"x\" # deprecated\nx = Sym(:x)\nx,y = Sym(:x, :y)\nx,y = symbols(\"x,y\")\n\n@syms u1 u2 u3\n@syms u positive=true\n@test length(solve(u+1)) == 0\n# make sure @syms defines in a local scope\nlet\n    @syms w\nend\n@test_throws UndefVarError isdefined(w)\n\n\n## extract symbols\nex = x*y\n@test isa(free_symbols(ex), Vector{Sym})\n\n## number conversions\nSym(2)\nSym(2.0)\nSym(2//1)\nSym(im)\nSym(2im)\nSym(1 + 2im)\nSym(pi)\nSym(e)\nSym(catalan)\n\n## function conversion\nf1 = convert(Function, x^2)\n@test f1(2) == Sym(4)\n\n### Subs\n## subs, |> (x == number)\nf(x) = x^2 - 2\ny = f(x)\n@assert float(subs(y, x, 1)) == f(1)\n@assert float( y |> subs(x,1) ) == f(1)\n\n## interfaces\nex = (x-1)*(y-2)\n@assert subs(ex, x, 1) == 0\n@assert subs(ex, (x,1)) == 0\n@assert subs(ex, (x,2),(y,2)) == 0\n\nif VERSION >= v\"0.4.0\"\n    @assert subs(ex, x=>1) == 0\n    @assert subs(ex, x=>2, y=>2) == 0\n    @assert subs(ex, Dict(x=>1)) == 0\n    @assert ex(x=>1) == 0\nend\n\n## match, replace, xreplace, rewrite\nx,y,z = symbols(\"x, y, z\")\na,b,c = map(Wild, (:a,:b,:c))\n## match: we have pattern, expression to follow `match`\nd = match(a^a, (x+y)^(x+y))\n@test d[a] == x+y\nd = match(a^b, (x+y)^(x+y))\n@test d[b] == x + y\nex = (2x)^2\npat = a*b^c\nd = match(pat, ex)\n@test d[a] == 4 && d[b] == x && d[c] == 2\n@test xreplace(pat, d) == 4x^2\n\n## replace\nif VERSION >= v\"0.4.0\"\nex = log(sin(x)) + tan(sin(x^2))\n@test replace(ex, func(sin(x)), func(cos(x))) == log(cos(x)) + tan(cos(x^2))\n@test replace(ex, func(sin(x)), u ->  sin(2u)) == log(sin(2x)) + tan(sin(2*x^2))\n@test replace(ex, sin(a), tan(a)) ==  log(tan(x)) + tan(tan(x^2))\n@test replace(ex, sin(a), a) == log(x) + tan(x^2)\n@test replace(x*y, a*x, a) == y\nend\n## xreplace\nif VERSION >= v\"0.4.0\"            \n@test xreplace(1 + x*y, x => PI) == 1 + PI*y\n@test xreplace(x*y + z, x*y => PI) == z + PI\n@test xreplace(x*y * z, x*y => PI) == x* y * z\n@test xreplace(x +2 + exp(x + 2), x+2=>y) == x + exp(y) + 2\nend\n            \n\n#Test subs for pars and dicts\nex = 1\ndict1 = Dict{Compat.String,Any}()\ndict2 = Dict{Any,Any}()\n#test subs\nfor i=1:4\n    x = Sym(\"x$i\")\n    ex=ex*x\n    dict2[x] = i\n    dict1[string(x)] = i\nend\nfor d in [dict1, dict2]\n    @test ex |> subs(d) == factorial(4) \n    @test subs(ex, d) == factorial(4)\n    @test subs(ex, d...) == factorial(4)\n    if VERSION >= v\"0.4.0\" \n        @test ex |> subs(d...) == factorial(4)\n        @test ex(d) == factorial(4)\n        @test ex(d...) == factorial(4)\n    end\nend\n\na = Sym(\"a\")\nb = Sym(\"b\")\nline = x -> a + b * x\nsol = solve([line(0)-1, line(1)-2],[a,b])\nex = line(10)\n@test ex |> subs(sol) == 11\nif VERSION >= v\"0.4.0\" \n    @test ex(sol) == ex(sol...) == 11\nend\n\n## Conversion\nx = Sym(\"x\")\np = subs(x,x,pi)\nq = subs(x,x,1//2)\nr = subs(x,x,1.2)\nz = subs(x,x,1)\n@assert isa(N(p), Float64)\n@assert isa(N(p, 60), BigFloat)\n@assert isa(evalf(p), Sym)\n@assert isa(N(q), Rational)\n@assert isa(N(r), Float64)\n@assert isa(N(z), Int)\n\n## method calls via getindex\np = (x-1)*(x-2)\np[:roots]()  # sympy.roots\np = Poly(p, x)\np[:coeffs]() # p.coeffs\n\n## algebra\nexpand((x + 1)*(x+2))\nx1 = (x + 1)*(x+2)\nexpand(x1)\nexpand_trig(sin(2x))\n\n## solve\nx,y,a = symbols(\"x,y,a\", real=true)\nsolve(x^2 - 2x)\nsolve(x^2 - 2a, x)\nsolve(x^2 - 2a, a)\nsolve(Lt(x-2, 0))\nsolve( x-2 \u226a 0)\nexs = [x-y-1, x+y-2]\nd = solve(exs)\n@assert d[x] == 3//2\n@assert map(ex -> subs(ex, d), exs) == [0,0]\nsolve([x-y-a, x+y], [x,y])\n\n\n\n## limits\n@assert limit(sin(x)/x, x, 0) |> float == 1\n(x, h) = @syms x h\nout = limit((sin(x+h) - sin(x))/h, h, 0)\n@assert (out |> replace(x, pi) |> float) == -1.0\n\n\n## diff\ndiff(sin(x), x)\nout = diff(sin(x), x, 2)\n@assert abs((out |> replace(x, pi/4) |> float) - - sin(pi/4)) < sqrt(eps())\n\n@syms x y\ndiff(x^2 + x*y^2, x, 1)         # partial derivatives\n\nt = symbols(\"t\", real=true)     # vector-valued functions\nr1(t) = [sin(t), cos(t), t]\nu = r1(t)\n#kappa = norm(diff(u) \u00d7 diff(u,t,2)) / norm(diff(u))^3 |> simplify\n#@assert convert(Rational,kappa) == 1//2\n\nu = SymFunction(\"u\")\neqn = Eq(x^2 + u(x)^2, x^3 - u(x))\ndiff(eqn, x)\n\n## integrate\nintegrate(sin(x))\nintegrate(sin(x), (x, 0, pi))\n@vars a b t\nintegrate(sin(x), (x, a, b))\nintegrate(sin(x), (x, a, b)) |> replace(a, 0) |> replace(b, pi)\nintegrate(sin(x) * DiracDelta(Sym(0))) # sin(0)\nintegrate(Heaviside(x), (x, -1, 1))\nC = Curve([exp(t)-1, exp(t)+1], (t, 0, log(Sym(2))))\nline_integrate(x + y, C, [x,y])\n\n\n\n## summation\nsummation(1/x^2, (x, 1, 10))\nout = summation(1/x^2, (x, 1, 10))\nout1 = sum([1//x^2 for  x in 1:10])\n@assert @compat round(Integer, out.x[:p]) == out1.num\n@assert @compat round(Integer, out.x[:q]) == out1.den\n\n## matrices\n## these can also be tested by matrix-tests.jl\n@syms x\nA = [x 1; 1 x]\nb = [x, 2]\n\n\n\n## Ops\ns = 3\nx = Sym(\"x\")\nv = [x, 1]\nrv = [x 1]\na = [x 1; 1 x]\nb = [x 1 2; 1 2 x]\n\nconst DIMERROR = VERSION < v\"0.4.0-dev\" ? ErrorException : DimensionMismatch\n\n## scalar, [vector, matrix]\ns + v\nv + s\ns + rv\nrv + s\ns + a\na + s\n\ns - v\nv - s\ns - rv\nrv - s\ns - a\na - s\n\n2v\n2rv\n2a\ns .* v\nv .* s\ns .* rv\nrv .* s\ns .* a\na .* s\n\n## s / v  ## broadcasts s Depreacated\ns ./ v\nv / s\nv .\\ s\ns \\ v\n## s / rv ## broadcasts s Deprecated\ns ./ rv\nrv / s\nrv .\\ s\ns \\ rv\n## s / a ## broadcasts s Deprecated\ns ./ a\na / s\na .\\ s\ns \\ a\n\n@test_throws MethodError  s ^ v ## error\ns .^ v\n@test_throws MethodError  v ^ s ## error\nv .^ s\n@test_throws MethodError  s ^ rv ## error\ns .^ rv\n@test_throws DimensionMismatch  rv ^ s ## error\nrv .^ s\n@test_throws MethodError  s ^ a ## error\ns .^ a\na ^ s\na .^ s\n\n\n## vector vector\nv .+ v\n##@test_throws MethodError  v .+ rv ##  no longer an error, broadcase\nv .- v\n@test_throws DIMERROR  v - rv\n@test_throws MethodError  v * v ## error\nv .* v\ndot(v, v)\nv * rv ## 2x1 1x2 == 2x2\nrv * v ## 1x2 2 x 1 == 1x1\nv .* rv ## XXX ?? should be what? -- not 2 x 2\nrv .* v ## XXX ditto\n## @test_throws MethodError  v / v ## error\nv ./ v ## ones()\nv .\\ v\n## @test_throws MethodError  v / rv ## error\nv ./ rv  ## ??\nrv .\\ v\n@test_throws MethodError  v ^ v ## error\nv .^ v\n@test_throws MethodError  v ^ rv ## error\nv .^ rv ## ??\n\n\n## vector matrix\n@test_throws DIMERROR v + a ## error (Broadcast?)\n@test_throws DIMERROR a + v ## error\nv .+ a ## broadcasts\na .+ v\n@test_throws DIMERROR  v - a ## error\nv .- a\n@test_throws DimensionMismatch  v * a ## error\nv .* a\n#@test_throws MethodError  v / a ## error\nv ./ a\na .\\ v\n@test_throws MethodError  v ^ a ## error\nv .^ a\nv\n## matrix matrix\na + a\n@test_throws DIMERROR  a + b ## error\na + 2a\na - a\n@test_throws DIMERROR  a - b ## error\na * a\na .* a\na * b ## 2x2 * 2*3 -- 2x3\n@test_throws DIMERROR  a .* b ## error -- wrong size\n#@test_throws MethodError  a / a\na ./ a ## ones\na .\\ a\n##@test_throws MethodError  a / b ## error\n@test_throws DIMERROR  a ./ b ## error\n@test_throws DIMERROR  b .\\ a ## error\n@test_throws MethodError  a ^ a ## error\na .^ a\n@test_throws MethodError  a ^ b ## error\n@test_throws DIMERROR  a .^ b ## error\n\n\n## Number theory\n#@test isprime(100) == isprime(Sym(100))\n#@test factorint(Sym(100)) == factor(100)\n@test prime(Sym(100)) == 541\n@test multiplicity(Sym(10), 100) == 2\n\n\n## polynomials\n@syms x y\nf1 = 5x^2  + 10x + 3\ng1 = 2x + 2\nq,r = polydiv(f1,g1, domain=\"QQ\") # not div, as can't disambiguate div(Sym(7), 5)) to do integer division\n@test r == Sym(-2)\n@test simplify(q*g1 + r - f1) == Sym(0)\n\n\n## piecewise\nx = Sym(\"x\")\np = piecewise((x, Ge(x,0)), (0, Lt(x,0)), (1, Eq(x,0)))\n## using infix \\ll<tab>, \\gt<tab>, \\Equal<tab>\np = piecewise((x, x \u2265 0), (0, x \u226a 0), (1, x \u2a75 0))\n@assert @compat Int(subs(p,x,2)) == 2\n@assert @compat Int(subs(p,x,-1)) == 0\n@assert @compat Int(subs(p,x,0)) == 0\n\nu = ifelse(Lt(x, 0), \"neg\", ifelse(Gt(x, 0), \"pos\", \"zero\"))\n@assert subs(u,x,-1) == Sym(\"neg\")\n@assert subs(u,x, 0) == Sym(\"zero\")\n@assert subs(u,x, 1) == Sym(\"pos\")\n\n\n## relations\nx,y=symbols(\"x, y\")\nex = Eq(x^2, x)\n@assert lhs(ex) == x^2\n@assert rhs(ex) == x\n@assert args(ex) == (x^2, x)\n\n## mpmath functions\nif isdefined(:mpmath)\n    x = Sym(\"x\")\n    Sym(big(2))\n    Sym(big(2.0))                   # may need mpmath (e.g., conda install mpmath)\n    \n    @assert limit(besselj(1,1/x), x, 0) == Sym(0)\n    complex(hankel2(2, pi))\n    bei(2, 3.5)\n    bei(1+im, 2+3im)\nend\n\n## Assumptions\n@assert ask(Q.even(Sym(2))) == true\n@assert ask(Q.even(Sym(3))) == false\n@assert ask(Q.nonzero(Sym(3))) == true\n\n## sets\ns = FiniteSet(\"H\",\"T\")\ns1 = powerset(s)\nVERSION >= v\"0.4.0\" && @assert length(collect(convert(Set, s1))) == length(collect(s1.x))\na, b = Interval(0,1), Interval(2,3)\n@assert is_disjoint(a, b) == true\n@assert measure(union(a, b)) == 2\n\n\n## Issue # 56\n@assert Sym(1+2im) == 1+2IM\n\n\n## Issue #59\ncse(sin(x)+sin(x)*cos(x))\ncse([sin(x), sin(x)*cos(x)])\ncse([sin(x) sin(x)*cos(x); cos(x) sin(x)*cos(x)])\n\n## Issue #60, lambidfy\nif VERSION >= v\"0.4.0\"\n    @vars x,y\n    lambdify(sin(x)*cos(2x) * exp(x^2/2))\n    lambdify(sin(x)*asin(x)*sinh(x))(0.25)\n    lambdify(real(x)*imag(x))\n#    @assert lambdify(Min(x,y))(3,2) == 2\n    \n    ex = 2*x^2/(3-x)*exp(x)*sin(x)*sind(x)\n    map(lambdify(ex), rand(10))\n    ex = x - y\n    @assert lambdify(ex)(3,2) == 1\n\n    i = Indicator(x, 0, 1)\n    u = lambdify(i)\n    @assert u(.5) == 1\n    @assert u(1.5) == 0\nend\n\n## issue #67\n@assert N(Sym(4//3)) == 4//3\n\n## issue #71\n@test log(Sym(3), Sym(4)) == log(Sym(4)) / log(Sym(3))\n", "meta": {"hexsha": "7e9e888dc3171ab9c516d41764883a5999424a10", "size": 9243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tests.jl", "max_stars_repo_name": "JuliaPackageMirrors/SymPy.jl", "max_stars_repo_head_hexsha": "a99bac82866a35bf9d61bd2c7802998c4efb3418", "max_stars_repo_licenses": ["MIT"], "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.jl", "max_issues_repo_name": "JuliaPackageMirrors/SymPy.jl", "max_issues_repo_head_hexsha": "a99bac82866a35bf9d61bd2c7802998c4efb3418", "max_issues_repo_licenses": ["MIT"], "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/tests.jl", "max_forks_repo_name": "JuliaPackageMirrors/SymPy.jl", "max_forks_repo_head_hexsha": "a99bac82866a35bf9d61bd2c7802998c4efb3418", "max_forks_repo_licenses": ["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.9591836735, "max_line_length": 105, "alphanum_fraction": 0.5597749648, "num_tokens": 3753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7901263317711279}}
{"text": "module TestHess\n    using Calculus2\n    using Base.Test\n\n    # multivariate test function\n    function f(x::Vector)\n        return sin(x[1]) + cos(x[2])\n    end\n    x = [0.0, 0.0]\n    n = length(x)\n    H = Array(eltype(x), n, n)\n\n    # Test in-place multivariate grad!\n    hess!(H, f, x)\n    @test Calculus2.maxdiff(\n        H,\n        [-sin(0.0) 0.0; 0.0 -cos(0.0)]\n    ) < 10e-8\n\n    # Test pure multivariate grad\n    @test Calculus2.maxdiff(\n        hess(f, x),\n        [-sin(0.0) 0.0; 0.0 -cos(0.0)]\n    ) < 10e-8\n\n    # Test in-place multivariate gradfunc!\n    fill!(H, 0.0)\n    h! = hessfunc!(f, x)\n    h!(H, x)\n    @test Calculus2.maxdiff(\n        H,\n        [-sin(0.0) 0.0; 0.0 -cos(0.0)]\n    ) < 10e-8\n\n    # Test pure multivariate gradfunc\n    h = hessfunc(f, x)\n    @test Calculus2.maxdiff(\n        h(x),\n        [-sin(0.0) 0.0; 0.0 -cos(0.0)]\n    ) < 10e-8\n\n    # Test pure univariate grad\n    @test isapprox(hess(sin, 1.0), -sin(1.0))\n\n    # Test pure univariate gradfunc\n    @test isapprox(hessfunc(sin, 0.0)(1.0), -sin(1.0))\n\n    # TODO: Test automatic differentation\n    # TODO: Test symbolic differentiation\n    # TODO: Test direction options\nend\n", "meta": {"hexsha": "82fd85cdca7b2ce18fd2ef3741c20c59ebafb2aa", "size": 1164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/api/hess.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": "test/api/hess.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": "test/api/hess.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": 22.3846153846, "max_line_length": 54, "alphanum_fraction": 0.5446735395, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7901263287704577}}
{"text": "#==============================================================================\n    Code for solving the Hamiltonian Jacboi Bellman for\n\t   an basic model: a neoclassical growth model: \u03c1V(k) = max_{c} U(c) + V'(k)[F(k)-\u03b4k - c]\n\t   Where s(k) = F(k) - \u03b4k - 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\u03c3= 2.0 #\n\u03c1 = 0.05 #the discount rate\n\u03b4 = 0.05 # the depreciation rate\nA = 1.0\n\u03b1= 0.3\n\nk_ss = (\u03b1*A/(\u03c1+\u03b4))^(1/(1-\u03b1))\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\u03b5 = 10e-6\n\ndVf, dVb = [zeros(H,1) for i=1:2]\n\n#initial guess for V\nv0 = (A.*k.^\u03b1).^(1-\u03c3)/(1-\u03c3)/\u03c1\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/\u03c3)\n    \u03bc_f = A.*k.^\u03b1 - \u03b4.*k -cf\n\n    # consumption and savings with backward difference\n    cb = dVb.^(-1/\u03c3)\n    \u03bc_b = A.*k.^\u03b1 - \u03b4.*k -cb\n\n\tc0 = A.*k.^\u03b1 - \u03b4.*k\n    dV0 = c0.^(-\u03c3)\n\n    # Now to make a choice between forward and backward difference\n    If = \u03bc_f .> 0\n    Ib = \u03bc_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/\u03c3)\n    V_change = c.^(1-\u03c3)/(1-\u03c3) + dV_Upwind.*(A.*k.^\u03b1 - \u03b4.*k-c) -\u03c1.*V\n\n\t# update\n\t\u0394 = .9*dk/(findmax(A.*k.^\u03b1- \u03b4.*k-c)[1])\n\tglobal v = v + \u0394*V_change\n\tpush!(dist,findmax(abs.(V_change))[1])\n\tif dist[n] .< \u03b5\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-\u03c3)/(1-\u03c3) + dV_Upwind.*(A.*k.^\u03b1 - \u03b4.*k -c) - \u03c1.*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.^\u03b1 - \u03b4.*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_\u03b1_sig = 1 - p_GC_sig\n    p_\u03b1_bkg = 1 - p_GC_bkg\n    return mean([Binom_sum(N, p_\u03b1_sig), Binom_sum(N, p_\u03b1_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, \u03c3::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- `\u03c3::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, \u03c3::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] / \u03c3^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": "using MadMax\nusing Test\n\n# BisectionEval\n# RegulaFalsiEval\n# NewtonEval\n# GaussJacobiEval\n# GaussSeidelEval\n# SOREval\n# SOREval2\n# EulerODE\n# ModifiedEulerODE\n# RK2ODE\n# RK4ODE\n\nX = [5 5 15 -40\n      5 15 35 -104\n      15 35 99 -290]\n    \nX2 = [3  2  0 -5\n      2  3 -1 -4\n      0 -1  2 -1]\n\nx, a = GaussSeidelEval(X2, [0.9;-3.1;0.9], N=3)\nx, a = GaussJacobiEval(X, [0;0;0], N=7)\nx, a = SOREval(X2, [0;0;0], 1.25, N=3)\nx, a = SOREval2(X2, [0;0;0], 0.8, N=7)\n\nf(x) = x^24-2.6x+1.6 \nRegulaFalsiEval(f, 0, 1, tol=0.5*10^-3)\nNewtonEval(f, 0.05, N=4, tol=0.5*10^-4)\n\nf(t, x) = -x*sin(t) + sin(t)\nModifiedEulerODE(f, 0, 2+\u212f, 2\u03c0, 2\u03c0/10)\nRK2ODE(f, 0, 2+\u212f, 2\u03c0, 2\u03c0/10)", "meta": {"hexsha": "5471edf129b1c76cee549a9563cc9f28ead8655a", "size": 658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "ParthPant/MadMax.jl", "max_stars_repo_head_hexsha": "abdfdac347690c8a6c1e6f615e79802eba41bdb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-15T07:31:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T07:31:50.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "ParthPant/MadMax.jl", "max_issues_repo_head_hexsha": "abdfdac347690c8a6c1e6f615e79802eba41bdb2", "max_issues_repo_licenses": ["MIT"], "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": "ParthPant/MadMax.jl", "max_forks_repo_head_hexsha": "abdfdac347690c8a6c1e6f615e79802eba41bdb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-17T08:09:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T08:09:29.000Z", "avg_line_length": 18.8, "max_line_length": 47, "alphanum_fraction": 0.5759878419, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7900840558766448}}
{"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 \u00f7 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# \u2554\u2550\u2561 0a5335e0-ab9e-11eb-0a85-139ff5cf0b1d\nmd\"# Chapter 02 from NNFS book\"\n\n# \u2554\u2550\u2561 0c5d667f-0ea5-4d21-80ad-58d144470a73\nmd\"### A Single Neuron (4 inputs, 1 output)\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a3acafe8-6a4b-4438-84d9-16a00cb21997\nmd\"### A Layer of 03 Neurons (4 inputs, 3 outputs)\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3613059e-501d-4cb0-bd73-8e42e6395e16\nmd\" with only one unique matrix of weights we use matrix multiplication from linear algebra\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d27568ac-934c-4408-880d-4bd34ccead72\nmd\"### A Layer of Neurons with multiple batch of Data\"\n\n# \u2554\u2550\u2561 91d6b3e6-5124-4963-b6c2-f2c65b67b045\nmd\"Now we are gonna need use transpose operation to match the right vectors in matrix multiplication\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000a5335e0-ab9e-11eb-0a85-139ff5cf0b1d\n# \u255f\u25000c5d667f-0ea5-4d21-80ad-58d144470a73\n# \u255f\u2500d85b097d-c7c7-439f-80ec-a1b75c696cb1\n# \u2560\u2550ef746509-f29b-42ae-b9ec-a2e18ad4b327\n# \u255f\u2500a3acafe8-6a4b-4438-84d9-16a00cb21997\n# \u2560\u25509fbc1e4c-52c0-4b99-92dc-4969b55f645d\n# \u255f\u25003613059e-501d-4cb0-bd73-8e42e6395e16\n# \u2560\u25500e309e2a-59e8-4fce-819d-afeec8c21ca8\n# \u255f\u2500d27568ac-934c-4408-880d-4bd34ccead72\n# \u255f\u250091d6b3e6-5124-4963-b6c2-f2c65b67b045\n# \u2560\u25507ae39d13-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": "using TuringModels, StatsFuns\n\nTuring.setadbackend(:reverse_diff)\n\n# outcome and predictor almost perfectly associated\n\nx = repeat([-1], 9); append!(x, repeat([1],11))\ny = repeat([0], 10); append!(y, repeat([1],10))\n\n@model m_good_stan(x,y) = begin\n    \u03b1 ~ Normal(0,10)\n    \u03b2 ~ Normal(0,10)\n\n    for i \u2208 1:length(y)\n        p = logistic(\u03b1 + \u03b2 * x[i])\n        y[i] ~ Binomial(1, p)\n    end\nend\n\nchns = sample(m_good_stan(x,y), Turing.NUTS(0.95), 1000)\n\n# Stan results\n\nm_10_x,_results = \"\n    mean   sd   5.5% 94.5% n_eff Rhat\n a -5.09 4.08 -12.62 -0.25   100 1.00\n b  7.86 4.09   2.96 15.75   104 1.01\n\";\n\n# Look at the proper draws (in corrected chn2)\n\ndescribe(chns)\n\n# End of 10/m10.xxt.jl\n", "meta": {"hexsha": "bbf29f1572f369390742f08c2b2afbdf82b4225f", "size": 693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/10/m10.xxt.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/10/m10.xxt.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/10/m10.xxt.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": 19.8, "max_line_length": 56, "alphanum_fraction": 0.6118326118, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7900656528130704}}
{"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\u03b1 = -2_500_000\n\u03b2 = 2_500_000\n\nfor i in 1:k\n    @constraint(model, (x' * cities.population)[i] - P <= \u03b2)\n    @constraint(model, (x' * cities.population)[i] - P >= \u03b1)\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{\u2124\u2082, Int64}\n\nGenerate and return a `k \u00d7 k` identity-matrix.\n\"\"\"\nfunction id(k::Int64)::SparseMatrixCSC{\u2124\u2082, Int64}\n    I = sparse(zeros(\u2124\u2082, k, k))\n    for i = 1:k\n        I[i,i] = one(\u2124\u2082)\n    end\n    return I\nend\n\n\n\n\"\"\"\n    anti_id(k::Int64) -> SparseMatrixCSC{\u2124\u2082, Int64}\n\nGenerate and return a `k \u00d7 k` anti-identity-matrix.\n\"\"\"\nfunction anti_id(k::Int64)::SparseMatrixCSC{\u2124\u2082, Int64}\n    antiid = ones(\u2124\u2082, k, k)\n    for i = 1:k\n        antiid[i,i] = zero(\u2124\u2082)\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, \u0394x::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    - \u0394x: search direction\n\nOutput:\n    - t: optimal step size\n\"\"\"\nfunction quadratic_ls(P::AbstractMatrix, q::AbstractVector, \u0394x::AbstractVector,\n                                    x::AbstractVector)\n    t = solve_quadratic(\u0394x' * P * \u0394x, \u0394x' * P * x + \u0394x \u22c5 q)\n    return t\nend\n\n\"\"\"\n    gradient_descent(P::AbstractArray, q::AbstractVector,\n            x\u2080::AbstractVector; \u03b2::Real=0.0, \u03f5::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\u2080: starting point\n    - \u03f5: convergence parameter\n    - \u03b2: 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\u2080::AbstractVector; \u03b2::Real=0.0, \u03f5::Real=1e-6,\n            tracker::Tracker=notrack)\n    @assert 0 \u2264 \u03b2 < 1\n    x = x\u2080  # initial value\n    \u0394x = zero(x)  # pre-allocate a vector for the gradient\n    while true\n        \u0394x .= (1.0 - \u03b2) * (- P * x .- q) .+ \u03b2 *  \u0394x\n        if norm(\u0394x) < \u03f5\n            break\n        end\n        # determine stepsize using exact line search\n        t = quadratic_ls(P, q, \u0394x, x)\n        # perform step\n        x .+= t * \u0394x\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; \u03c3=1.0)\n\nGenerate noisy measurements according to some function f\n\nInputs:\n    - m : number of observations\n    - n : dim of x\n    - \u03c3 : 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; \u03c3=1.0)\n    ind = rand(1:n, m)\n    y = signalfun.(ind, n) .+ randn(m) * \u03c3\n    return y, ind\nend\n\n\n\"\"\"\n    make_connection_matrix(n, \u03b3=100)\n\nGenerates the kernel matrix and the inverse kernel matrix\n\nUses \u03b3 as a characteristic length scale of the radial basis kernel,\nassumes periodic boundaries.\n\nInputs:\n    - n : number of points\n    - \u03b3 : length scale\n\nOutput:\n    - K\n    - Kinv\n\"\"\"\nfunction make_connection_matrix(n, \u03b3=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 / \u03b3^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": "import Random\nimport Test\n\nTest.@testset \"examples\" begin\n    Test.@testset \"linear regression\" begin\n        Random.seed!(123)\n        include(joinpath(examples_directory, \"linear_regression.jl\"))\n        include(joinpath(test_directory, \"examples\", \"linear_regression.jl\"))\n\n    end\n\n    Test.@testset \"logistic regression\" begin\n        Random.seed!(123)\n        include(joinpath(examples_directory, \"logistic_regression.jl\"))\n        include(joinpath(test_directory, \"examples\", \"logistic_regression.jl\"))\n    end\n\n    Test.@testset \"multinomial logistic regression\" begin\n        Random.seed!(123)\n        @info(\"This next test may go five to fifteen minutes without producing any output\")\n        include(joinpath(examples_directory, \"multinomial_logistic_regression.jl\"))\n        include(joinpath(test_directory, \"examples\", \"multinomial_logistic_regression.jl\"))\n    end\nend\n", "meta": {"hexsha": "b51f863dc2f4ce9e26a45d07285eb8d545c7d099", "size": 883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/examples.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": "test/examples.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": "test/examples.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": 35.32, "max_line_length": 91, "alphanum_fraction": 0.7134767837, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7899975560548145}}
{"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\u03c3(x) = 1 / (1 + exp(-x))\n\n## Order 0\nfunction f_naive(x, A, b)\n    z = A*x\n    tmp = \u03c3.(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 \u2207f_current(x, A, b)\n    m = size(A, 1)\n\n    \u03c3bAx = \u03c3.(-b .* (A * x))\n    res = transpose(A) * (\u03c3bAx .* -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 \u2207f_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 = [:\u2207f]\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 :\u2207f in mode\n        @show \u2207f_current(x, A, b)\n        @show \u2207f_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 :\u2207f in mode\n        \u2207f_cu = \u2207f_current(x, A, b)\n        \u2207f_pr = \u2207f_prop(x, A, b)\n\n        @show norm(\u2207f_cu - \u2207f_pr)\n\n        @btime \u2207f_current($x, $A, $b)\n        @btime \u2207f_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": "@testset \"basic interest rates\" begin\n\n\n    ## vector interest rate\n    @testset \"vector interest rate\" begin\n        i = InterestRate([0.05, 0.05, 0.05])\n\n        @test disc(i,0) == 1.0\n        @test disc(i,1) == 1 / 1.05\n        @test disc(i,2) == 1 / 1.05 ^ 2\n        @test disc(i,3) == 1 / 1.05 ^ 3\n        @test disc(i,1,2) == 1 / 1.05\n        @test rate(i,1) == 0.05\n        @test rate(i,2) == 0.05\n\n        @test disc.(i,1:3) == [1 / 1.05 ^ t for t in 1:3]\n    end\n\n    ## real interest rate\n    @testset \"constant interest rate\" begin\n        i = InterestRate(0.05)\n\n        @test disc(i,0) == 1.0\n        @test disc(i,1) == 1 / 1.05\n        @test disc(i,2) == 1 / 1.05 ^ 2\n        @test disc(i,3) == 1 / 1.05 ^ 3\n        @test disc(i,1,2) == 1 / 1.05\n        @test rate(i,1) == 0.05\n        @test rate(i,2) == 0.05\n        \n        @test disc.(i,1:3) == [1 / 1.05 ^ t for t in 1:3]\n    end\nend\n\n@testset \"DiscountFactor Iterator\" begin\n\n    target = [1 / 1.05 ^ t for t in 0:4 ]\n\n    @testset \"contsant\" begin\n        df = DiscountFactor(InterestRate(0.05),1)\n        \n        ds = Iterators.take(df,5) |> collect\n\n        @test all(ds .\u2248 target)\n\n        @test length(Iterators.take(df,100)) == 100\n\n        # can't collect an infinite series\n        @test_throws MethodError collect(df)\n\n        @test df == InterestRate(0.05)(1)\n    end\n\n    @testset \"vector\" begin\n    df = DiscountFactor(InterestRate(repeat([0.05],4)),1)\n\n        ds = Iterators.take(df,5) |> collect\n        @test all(ds .\u2248 target)\n        @test all(collect(df) .\u2248 target)\n        @test length(df) == 5\n\n        @test_broken InterestRate([0.05,0.05,0.05,0.05])(1) == df #https://stackoverflow.com/questions/62336686/struct-equality-with-arrays\n    end\n\nend\n\n@testset \"passthrough life contingency\" begin\n    ins = LifeContingency(\n        SingleLife(\n            mort = UltimateMortality([0.5]),\n            issue_age = 0\n        ),\n        InterestRate(0.05)\n    )\n\n    @test disc(ins,1) \u2248 1/1.05\n    @test disc(ins,1,2) \u2248 1/1.05\nend", "meta": {"hexsha": "479d21ce1fae401b22edc1a87138daa6335006ad", "size": 2016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interest_rates.jl", "max_stars_repo_name": "alecloudenback/ActSci.jl", "max_stars_repo_head_hexsha": "f23306cc681e4b91bdbac9f4cef4d9808e01632b", "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": "test/interest_rates.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": "test/interest_rates.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": 25.8461538462, "max_line_length": 139, "alphanum_fraction": 0.5267857143, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7899841313191748}}
{"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( \u03c0*(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( \u03c0*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)*\u03c0 / (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\u20131120\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\u2013214\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 \u00d7 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 * \u03c0) * RotX(0.0 * \u03c0))\nqa = [qa.w; qa.x; qa.y; qa.z]\n\nxb = [1.0; 0.0; 0.0]\nqb = Quaternion(RotZ(0.0 * \u03c0) * RotY(0.0 * \u03c0) * 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*\u03c0*(mx/Lx.*(xx.-xmid).+my/Ly.*(yy.-ymid)))\n                integrand_sin = 2/(Lx*Ly).*e.*sin.(2*\u03c0*(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 `\u00b1 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) \u00f7 8\n        # fanout = 3*3*8 = (3*3*16*8) \u00f7 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) \u00f7 8\n        # fanout = 3*3*8 = (3*3*16*8) \u00f7 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 NumericFuns\nusing Base.Test\n\n@test sqr(2) === 4\n@test sqr(2.0) === 4.0\n\n@test rcp(2) === 0.5\n@test rsqrt(4) === 0.5\n@test rcbrt(8) === 0.5\n\n@test xlogx(0) === 0.0\n@test_approx_eq xlogx(2) 2.0 * log(2.0)\n\n@test xlogy(0, 1) === 0.0\n@test_approx_eq xlogy(2, 3) 2.0 * log(3.0)\n\n@test_approx_eq logistic(2) 1.0 / (1.0 + exp(-2.0))\n@test_approx_eq logit(0.5) 0.0\n@test_approx_eq logit(sigmoid(2)) 2.0\n\n@test_approx_eq softplus(2.0) log(1.0 + exp(2.0))\n@test_approx_eq softplus(-2.0) log(1.0 + exp(-2.0))\n@test_approx_eq softplus(10000) 10000.0\n@test_approx_eq softplus(-10000) 0.0\n\n@test_approx_eq invsoftplus(softplus(2.0)) 2.0\n@test_approx_eq invsoftplus(softplus(-2.0)) -2.0\n\n@test_approx_eq logsumexp(2.0, 3.0) log(exp(2.0) + exp(3.0))\n@test_approx_eq logsumexp(10002, 10003) 10000 + logsumexp(2.0, 3.0)\n\n", "meta": {"hexsha": "749beacd09260b06a98028fd3b1f5e9785a659ba", "size": 809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 25.28125, "max_line_length": 67, "alphanum_fraction": 0.6699629172, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7899274705395191}}
{"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 \u2208 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 \u2208 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 \u2229 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 \u2216 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 \u2229 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 136cdd48-8835-11eb-0482-737cf7bd5a3e\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9b2a7694-881e-11eb-325c-f3edd9178641\nbegin\n\timport Base: +, -\n\n\tfunction +(v\u2081::Vector{T}, v\u2082::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\u2081) == length(v\u2082)\n\t\tv\u2081 .+ v\u2082\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\u2080 \u2208 vc\n\t\t\tv .+= v\u2080\n\t\tend\t\n\t\tv\n\tend\n\t\n\tfunction -(v\u2081::Vector{T}, v\u2082::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\u2081) == length(v\u2082)\t\n\t\tv\u2081 .- v\u2082\n\tend\nend\n\n# \u2554\u2550\u2561 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\u1d63 = [1.0, -1.0, \u03c0, \u212f]\n\t@test v\u1d63 + [-1.0, 1.0, -\u03c0, -\u212f] == zeros(eltype(v\u1d63), length(v\u1d63))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 _ \u2208 1:3]) == [3, 9, 6]\nend\n\n# \u2554\u2550\u2561 e9b7d526-8829-11eb-34d1-e317fdc7a1d0\nmd\"\"\"\n`Multiplication` by a scalar, `Mean` and `dot` product.\n\"\"\"\n\n# \u2554\u2550\u2561 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 \u03bc(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\u2081::Vector{T}, v\u2082::Vector{T})::T where T <: Number\n\t\t@assert length(v\u2081) == length(v\u2082)\n\t\tsum(v\u2081 .* v\u2082)\n\tend\nend\n\n# \u2554\u2550\u2561 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\u1d63 = [1.0, -1.0, \u03c0, \u212f]\n\t@test v\u1d63 - [-1.0, 1.0, -\u03c0, -\u212f] == [2.0, -2.0, 2\u03c0, 2\u212f]\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 50444c92-882b-11eb-2893-bf66b63ee595\nbegin\n\t\u03bc([[1, 2, 1, 2], [3, 4, 3, 4], [5, 6, 5, 6]]) == Float64[3., 4., 3., 4.]\nend\n\n# \u2554\u2550\u2561 d358476c-882d-11eb-26bd-c167cabd7b28\nbegin\n\t@test dot([1, 2, 3], [4, 5, 6]) == 32\nend\n\n# \u2554\u2550\u2561 d33d417e-882d-11eb-0aae-a1d10512920f\nfunction sum_of_square(v::Vector{T})::T where T <: Number\n\t\"\"\"\n\treturn v\u1d62 * v\u1d62 \u2200 i \u2208 1:length(v)\n\t\"\"\"\n\tdot(v, v)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9db8e630-882e-11eb-07e5-0d5036f7e8e2\nmd\"\"\"\nLet's now implement L\u2082 norm and euclidean distance.\n\"\"\"\n\n# \u2554\u2550\u2561 ba1d63da-882e-11eb-1736-37a246585172\nfunction norm(v::Vector{T})::AbstractFloat where T <: Number\n\t\u221a sum(v .* v)\nend\n\n# \u2554\u2550\u2561 9da1fcfc-882e-11eb-021f-1f89149817a9\nbegin\n\t@test norm([3, 4]) == 5\n\t@test norm([1, 0, 2]) \u2248 \u221a5\nend\n\n# \u2554\u2550\u2561 9d8634ae-882e-11eb-15ad-75b06c847379\nfunction distance(v\u2081::Vector{T}, v\u2082::Vector{T})::AbstractFloat where T <: Number\n\t\"\"\"\n\tdistance(v\u2081, v\u2082) \u2261 \u221a(\u03a3 (v\u2081\u1d62 - v\u2082\u1d62)\u00b2)\n\t\"\"\"\n\t@assert length(v\u2081) == length(v\u2082)\n\t\u221a sum((v\u2081 .- v\u2082).^2)  # == norm(v\u2081 .- v\u2082)\nend\n\n# \u2554\u2550\u2561 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]) \u2248 12.409673645990857\nend\n\n# \u2554\u2550\u2561 0539916a-8835-11eb-3407-41f17efc2ee4\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# \u2554\u2550\u2561 73e7de7a-8830-11eb-05ef-b93f6c774587\nmd\"\"\"\n### Matrices\n\nA two-dimensional collection of numbers.\n\"\"\"\n\n# \u2554\u2550\u2561 7f051430-8830-11eb-1e43-797df6b195ed\nfunction shape(m::Matrix{T})::Tuple{Integer, Integer} where T <: Number\n\tsize(m)\nend\n\n# \u2554\u2550\u2561 7ee4e642-8830-11eb-3d15-813c4dbb6420\n@test shape([1 2 3; 4 5 6]) == (2, 3) # 2 rows, 3 columns\n\n# \u2554\u2550\u2561 7ec91688-8830-11eb-18a0-d5a67e267f9b\nfunction get_row(m::Matrix{T}, r::Integer)::Vector{T}  where T <: Number\n\t@assert 1 \u2264 r \u2264 size(m)[1]\n\tview(m, r, :)  ## no copy!\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 648af952-8831-11eb-340b-5bc7ef7aaa73\nfunction get_column(m::Matrix{T}, c::Integer)::Vector{T}  where T <: Number\n\t@assert 1 \u2264 c \u2264 size(m)[2]\n\tview(m, :, c)  ## no copy!\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c832331c-8831-11eb-0b7c-9f978c82f890\nfunction make_matrix(nrows::Integer, ncols::Integer, fn::Function;\n\t\tDT::DataType=Float64)::Matrix\n\t@assert 1 \u2264 nrows && 1 \u2264 ncols\n\t\n\tm = zeros(DT, (nrows, ncols))\n\tfor c \u2208 1:ncols, r \u2208 1:nrows\n\t\tm[r, c] = fn(r, c)\n\tend\n\tm\nend\n\n# \u2554\u2550\u2561 be10ce56-8832-11eb-0742-d90fa7f6f669\nfunction identity_matrix(n::Integer; DT::DataType=Float64)::Matrix\n\t\"\"\"Returns the n \u00d7 n identity matrix\"\"\"\t\n\tmake_matrix(n, n, (i, j) -> i == j ? one(DT) : zero(DT); DT)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3c69e83a-8835-11eb-218e-0bb108ad7b9c\nhtml\"\"\"\n<hr />\n<sub><em>Mar 2021, Corto Inc</em></sub>\n\"\"\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500accc6f84-881d-11eb-3b49-e9cd25a3b6fd\n# \u255f\u2500136cdd48-8835-11eb-0482-737cf7bd5a3e\n# \u255f\u2500b22cf860-8834-11eb-02de-d3ad803d1db6\n# \u255f\u2500b1e26cfa-8834-11eb-16f5-85efb64c6a4c\n# \u2560\u2550c96551a0-881e-11eb-0d92-61edbb6c86e6\n# \u2560\u25509b2a7694-881e-11eb-325c-f3edd9178641\n# \u2560\u255021a74512-881f-11eb-31e6-974bcaf59141\n# \u2560\u2550b3f61d4e-881f-11eb-2dcb-4dd0fd7fba06\n# \u255f\u250011ff42a0-8828-11eb-3ba5-dbd12b5ffdda\n# \u2560\u25507dc3365c-8828-11eb-3c57-69dae41619cd\n# \u255f\u2500e9b7d526-8829-11eb-34d1-e317fdc7a1d0\n# \u2560\u25503a7741c2-882a-11eb-2ffd-65b97e75a0b2\n# \u2560\u255019f5b176-882b-11eb-3713-73c85f599be1\n# \u2560\u255050444c92-882b-11eb-2893-bf66b63ee595\n# \u2560\u2550d358476c-882d-11eb-26bd-c167cabd7b28\n# \u2560\u2550d33d417e-882d-11eb-0aae-a1d10512920f\n# \u2560\u2550d3202a62-882d-11eb-2e24-6d874dce773d\n# \u255f\u25009db8e630-882e-11eb-07e5-0d5036f7e8e2\n# \u2560\u2550ba1d63da-882e-11eb-1736-37a246585172\n# \u2560\u25509da1fcfc-882e-11eb-021f-1f89149817a9\n# \u2560\u25509d8634ae-882e-11eb-15ad-75b06c847379\n# \u2560\u25509d69ec22-882e-11eb-0637-d7e29f7b9f37\n# \u255f\u25000539916a-8835-11eb-3407-41f17efc2ee4\n# \u255f\u250073e7de7a-8830-11eb-05ef-b93f6c774587\n# \u2560\u25507f051430-8830-11eb-1e43-797df6b195ed\n# \u2560\u25507ee4e642-8830-11eb-3d15-813c4dbb6420\n# \u2560\u25507ec91688-8830-11eb-18a0-d5a67e267f9b\n# \u2560\u25507e9afe92-8830-11eb-3772-150255e27923\n# \u2560\u2550648af952-8831-11eb-340b-5bc7ef7aaa73\n# \u2560\u25506470ad90-8831-11eb-0413-5d016bf66536\n# \u255f\u25006458987c-8831-11eb-2b89-efac8fabf803\n# \u2560\u2550c832331c-8831-11eb-0b7c-9f978c82f890\n# \u2560\u2550be10ce56-8832-11eb-0742-d90fa7f6f669\n# \u2560\u2550c81a12dc-8831-11eb-27e9-07132c6310a1\n# \u255f\u25003c69e83a-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\u1d62\u208a\u2081 =  x\u1d62 - f(x\u1d62)/f'(x\u1d62)`.  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\u1d62 = x\u1d62 - \u03b1`, can be expressed as `e\u1d62\u208a\u2081 = f[x\u1d62,x\u1d62,\u03b1]/(2f[x\u1d62,x\u1d62])e\u1d62\u00b2` (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** \u0394 = fx1/f'(x1)\nstruct NewtonState{T,S} <: AbstractUnivariateZeroState{T,S}\n    xn1::T\n    xn0::T\n    \u0394::T\n    fxn1::S\n    fxn0::S\nend\n\n\nfunction init_state(M::Newton, F::Callable_Function, x)\n    x\u2080 = float(first(x))\n    fx\u2080, \u0394 = F(x\u2080)\n    x\u2081 = x\u2080 - \u0394\n    state = init_state(M, F, x\u2080, x\u2081, fx\u2080, fx\u2080)\nend\n\n# compute fx\u2081, \u0394\nfunction init_state(::Newton, F, x\u2080, x\u2081, fx\u2080, fx\u2081)\n    fx\u2081, \u0394 = F(x\u2081)\n    NewtonState(x\u2081, x\u2080, \u0394, fx\u2081, fx\u2080)\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    \u0394 = o.\u0394\n\n    if isissue(\u0394)\n        log_message(l, \"Issue with `f/f\u2032'\")\n        return o, true\n    end\n\n    xn0, xn1 = xn1, xn1-\u0394\n    fxn0 = fxn1\n    fxn1, \u0394 = F(xn1)\n    incfn(l,2)\n\n    @set! o.xn0 = xn0\n    @set! o.xn1 = xn1\n    @set! o.\u0394 = \u0394\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\u1d62\u208a\u2081 =  x\u1d62 - f(x\u1d62)/f'(x\u1d62)`.\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\u0394f, 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\u1d62\u208a\u2081 = x\u1d62 - (f/f')(x\u1d62) * (1 - (f/f')(x\u1d62) * (f''/f')(x\u1d62) * 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\u1d62 = x\u1d62 - \u03b1`, satisfies\n`e\u1d62\u208a\u2081 \u2248 -(2f'\u22c5f''' -3\u22c5(f'')\u00b2)/(12\u22c5(f'')\u00b2) \u22c5 e\u1d62\u00b3` (all evaluated at `\u03b1`).\n\n\"\"\"\nstruct Halley <: AbstractHalleyLikeMethod\nend\n\nstruct HalleyState{T,S} <: AbstractUnivariateZeroState{T,S}\n    xn1::T\n    xn0::T\n    \u0394::T\n    \u0394\u0394::T\n    fxn1::S\n    fxn0::S\nend\n\n# we compute one step here to get x\u2081\nfunction init_state(M::AbstractHalleyLikeMethod, F::Callable_Function, x)\n    x\u2080 = float(first(x))\n    fx\u2080, (\u0394, \u0394\u0394) = F(x\u2080)\n    x\u2081 = x\u2080 - 2\u0394\u0394/(2\u0394\u0394 - \u0394) * \u0394\n    state = init_state(M, F, x\u2080, x\u2081, fx\u2080, fx\u2080)\nend\n\nfunction init_state(::AbstractHalleyLikeMethod, F, x\u2080, x\u2081, fx\u2080, fx\u2081)\n    fx\u2081, (\u0394, \u0394\u0394) = F(x\u2081)\n    HalleyState(x\u2081, x\u2080, \u0394, \u0394\u0394, fx\u2081, fx\u2080)\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.\u0394, o.\u0394\u0394\n\n    \u0394 =  2*r2/(2r2 - r1) * r1\n    if isissue(\u0394)\n        log_message(l, \"Issue with computing `\u0394`\")\n        return (o, true)\n    end\n\n    xn1::T = xn - \u0394\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.\u0394 = r1\n    @set! o.\u0394\u0394 = 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.\u03b2*S_H*I_V)/p.N_H\n    host_mortality = p.\u03bc_H .* u[1:4] # include S_H, so easier to remove mortality\n    host_births = sum(host_mortality)\n    host_progression = p.\u03c3_H*E_H\n    recovery = p.\u03bb*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.\u03b2*S_V*I_H)/p.N_H\n    vec_mortality = p.\u03bc_V .* u[5:7] # include S_V, so easier to remove mortality\n    vec_births = sum(vec_mortality)\n    vec_progression = p.\u03c3_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  \u03bc_H=1/365, \u03bc_V=1/30, \u03c3_H=1/3, \u03c3_V=1/7, \u03bb=1/14,\n  \u03b2=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": "HOME_DIR = dirname(@__DIR__)\nPACKAGE_DIR = dirname(HOME_DIR)\npushfirst!(LOAD_PATH, PACKAGE_DIR)\nusing MPCHelper\n\n\nusing ControlSystems\nusing LinearAlgebra\nusing LazySets\n\nusing Test\n\nusing Plots\n\n## Initialization ---------------------------------------------------------------\n# Linear 2D System\nA = [1 -2; 0 1]\nB= Matrix([1 1]')\nR = 0.1*I\nQ = Matrix(I,size(A))/10\nK = dlqr(A,B,Q,R)\nA_stab = A - B*K; eigvals(A_stab)\nP = dlyap(A_stab, Q)\nl_x = [3,3]\nl_u = 1\nz = [0.0 ;0.0]; v = 0.0\n\n# # Linear 3D System\n# A = [0.8 -2 3; 0 0.5 0; 0 0 0.3]\n# B= [1 0; 0 1; 0 0.4]\n# R = 0.1*Matrix(I,size(B,2), size(B,2))\n# Q = 0.1*Matrix(I,size(A))\n# K = dlqr(A,B,Q,R)\n# A_stab = A - B*K; eigvals(A_stab)\n# P = dlyap(A_stab, Q)\n# l_x = [3,3,3]\n# l_u = [2,2]\n# z = [0.0 ;0.0; 0.0]; v = [0.0, 0.0]\n\n# Main Part\n\u03b1 = 2\nE = get_Ellipsoid(P, \u03b1)\nl(x,u) = dot(l_x,x) + dot(l_u,u)\n\u03b3 = l_x + K'*l_u\n\u03c9star = \u03c9_opt(\u03b3, P, \u03b1)\nh\u03a9 = h\u03a9_opt(\u03b3, P, \u03b1)\n# Scale \u03b3 -> vec_\u03b3, such that vec_\u03b3'*\u03b3 the same cost as \u03c9*\u03b3\nvec_\u03b3 = \u03b3*h\u03a9/norm(\u03b3)^2\n@test \u03c9star'*\u03b3 \u2248 vec_\u03b3'*\u03b3\n# lmax(z,v) for Ellispoid defined by P, \u03b1\nlmax(z,v) = lmax_mask(z,v, P, \u03b1, l_x, l_u, K)\n# lmax(z,v) for Ellispoid defined by Ellipsoid E (Type LazySet)\nlmax_lazy(z,v) = lmax_mask(z,v, E, l_x, l_u, K)\nlmax_opt = lmax(z,v)\nlmax2_opt = lmax_lazy(z,v)\n@test h\u03a9 \u2248 lmax_opt\nx_opt = z .+ \u03c9star\nu_opt = vec(v .+ K*\u03c9star)\n@test l(x_opt, u_opt) \u2248 lmax_opt\n\n## Plotting (only for 2D systems)\ngrid_res = -5:0.2:5\nplot(E,1e-3, alpha=0.5, lab=\"Omega\", size=(500,500))\nplot_vec!(\u03c9star, line=(3,:blue), lab=\"w_opt\")\nplot_vec!(vec_\u03b3, line=(2,:black, :dash), lab=\"lx + K'lu\")\n# plot_vec!([1,1], line=(2,:black, :dash), lab=\"lx + K'lu\")\nplot_lin_contour!(l_x, grid_res; color=:bluesreds, line=(1,:dash), colorbar=false)\nplot_lin_contour!(\u03b3, grid_res; color=:bluesreds, line=(1))#, contour_labels = true)\nl_opt(x) = (-\u03b3[1]*x + h\u03a9) / \u03b3[2] # \u03b3'x = h\u03b1\nplot!(grid_res, l_opt.(grid_res), line=(:red), lab=\"lopt\")\nxlims!(-5,5)\nylims!(-5,5)\n\n\n\n## PLotting Surfaces\ngrid_res = 0:0.1:10\nsurface(grid_res,grid_res, (x,y) -> lmax([x,y],0) )\nsurface!(grid_res,grid_res, (x,y) -> l([x,y],0))\n\n\n## Solve OP for lmax and compare to analytical solution\nusing JuMP\nusing Ipopt\nimport LazySets.Approximations.overapproximate\nn = size(A,2)\n\nfunction lmax_optimized(z,v)\n    HPolyrep_epsilon = overapproximate(E, 1e-5) # approximate ellipse by polytope\n    model = Model(with_optimizer(Ipopt.Optimizer))\n    JuMP.register(model, :l, 2, l, autodiff=true )\n    @variable(model, \u03c9[1:n])\n    constrain_variable_by_set2!(model, \u03c9, HPolyrep_epsilon)\n    @objective(model, Max, l(z+\u03c9, K*\u03c9 .+ v))\n    # print(model)\n    optimize!(model)\n    opt_val = objective_value(model)\n    opt_\u03c9 = value.(\u03c9)\n    @show opt_\u03c9, opt_val\n    return opt_val\nend\n\nlmax_optimized(z,v) - lmax(z,v)\n@test abs(lmax_optimized(z,v) - lmax(z,v)) <= 1e-4\n", "meta": {"hexsha": "e7b50ccb9167643adece986128649a236a3db5ca", "size": 2805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_analytical_solution_lmax.jl", "max_stars_repo_name": "ueliwechsler/MPCHelper.jl", "max_stars_repo_head_hexsha": "47612810337fb7e38695d4597d060b743ccb2f65", "max_stars_repo_licenses": ["MIT"], "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_analytical_solution_lmax.jl", "max_issues_repo_name": "ueliwechsler/MPCHelper.jl", "max_issues_repo_head_hexsha": "47612810337fb7e38695d4597d060b743ccb2f65", "max_issues_repo_licenses": ["MIT"], "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_analytical_solution_lmax.jl", "max_forks_repo_name": "ueliwechsler/MPCHelper.jl", "max_forks_repo_head_hexsha": "47612810337fb7e38695d4597d060b743ccb2f65", "max_forks_repo_licenses": ["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.7142857143, "max_line_length": 83, "alphanum_fraction": 0.6242424242, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.789850171905197}}
{"text": "using MathepiaModels\nusing DifferentialEquations\nusing Plots\nusing Test\nconst DE = DifferentialEquations\n@testset \"SIRbasic\" begin\n    u_0 = [1000, 0.1, 0]\n    p_data = (\u039b = 0, d = 0, \u03b1 = 0, N = 1000, \u03b2 = 0.2, \u03b3 = 0.1)\n    tspan_data = (0.0, 100.0)\n    prob_data = DE.ODEProblem(SIRbasic, u_0, tspan_data, p_data)\n    data_solve = DE.solve(prob_data, Tsit5(), abstol = 1e-12, reltol = 1e-12, saveat = 0.1)\n    data_withoutnois = Array(data_solve)\n    data = data_withoutnois #+ Float32(2e-1)*randn(eltype(data_withoutnois), size(data_withoutnois))\n    Plots.plot(data_solve.t, data[1, :], label = \"Train S\")\n    Plots.plot!(data_solve.t, data[2, :], label = \"Train I\")\n    @info \"SIRbasic succeed\"\nend\n\n@testset \"SEIRbasic\" begin\n    u_0 = [1000, 0, 1, 0]\n    p_data = (\u039b = 0, d = 0, \u03b1 = 0, N = 1000, \u03b2 = 0.2, \u03b3 = 0.1, \u03c3=1/5.2, ke = 0.3)\n    tspan_data = (0.0, 100.0)\n    prob_data = DE.ODEProblem(SEIRbasic, u_0, tspan_data, p_data)\n    data_solve = DE.solve(prob_data, Tsit5(), abstol = 1e-12, reltol = 1e-12, saveat = 0.1)\n    data_withoutnois = Array(data_solve)\n    data = data_withoutnois #+ Float32(2e-1)*randn(eltype(data_withoutnois), size(data_withoutnois))\n    Plots.plot(data_solve.t, data[1, :], label = \"Train S\")\n    Plots.plot!(data_solve.t, data[2, :], label = \"Train E\")\n    @info \"SEIRbasic succeed\"\nend\n\n@testset \"SEIARbasic\" begin\n    u_0 = [1000, 0, 1, 0, 0]\n    p_data = (\u039b = 0, d = 0, \u03b1 = 0, N = 1000, \u03b2 = 0.2, \u03b3 = 0.1, \u03c3=1/5.2, ke = 0.3, ka =0.3, \u03c1 =0.3, \u03b3A = 0.1)\n    tspan_data = (0.0, 100.0)\n    prob_data = DE.ODEProblem(SEIARbasic, u_0, tspan_data, p_data)\n    data_solve = DE.solve(prob_data, Tsit5(), abstol = 1e-12, reltol = 1e-12, saveat = 0.1)\n    data_withoutnois = Array(data_solve)\n    data = data_withoutnois #+ Float32(2e-1)*randn(eltype(data_withoutnois), size(data_withoutnois))\n    @show Plots.plot(data_solve.t, data[1, :], label = \"Train S\")\n    Plots.plot!(data_solve.t, data[2, :], label = \"Train E\")\n    @info \"SEIARbasic succeed\"\nend\n\n\n@testset \"SISbasic\" begin\n    u_0 = [1000,  1]\n    p_data = (N = 1000, \u03b2 = 0.2, \u03b3 = 0.1)\n    tspan_data = (0.0, 1000.0)\n    prob_data = DE.ODEProblem(SISbasic, u_0, tspan_data, p_data)\n    data_solve = DE.solve(prob_data, Tsit5(), abstol = 1e-12, reltol = 1e-12, saveat = 0.1)\n    data_withoutnois = Array(data_solve)\n    data = data_withoutnois #+ Float32(2e-1)*randn(eltype(data_withoutnois), size(data_withoutnois))\n    @show Plots.plot(data_solve.t, data[1, :], label = \"Train S\")\n    Plots.plot!(data_solve.t, data[2, :], label = \"Train E\")\n    @info \"SIS succeed\"\nend", "meta": {"hexsha": "e65e3b82738e46b2262f05c9c05b5c9cbedd2f4d", "size": 2558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Models/odecompartstest.jl", "max_stars_repo_name": "Song921012/MathepiaModels.jl", "max_stars_repo_head_hexsha": "d70d9c249534c1d0af00bb135ce62237e29cf260", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-22T13:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T13:16:34.000Z", "max_issues_repo_path": "test/Models/odecompartstest.jl", "max_issues_repo_name": "Song921012/MathepiaModels.jl", "max_issues_repo_head_hexsha": "d70d9c249534c1d0af00bb135ce62237e29cf260", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-19T20:40:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T23:12:27.000Z", "max_forks_repo_path": "test/Models/odecompartstest.jl", "max_forks_repo_name": "Song921012/MathepiaModels.jl", "max_forks_repo_head_hexsha": "d70d9c249534c1d0af00bb135ce62237e29cf260", "max_forks_repo_licenses": ["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.8771929825, "max_line_length": 108, "alphanum_fraction": 0.6399530884, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7898501706439521}}
{"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": "\n\"\"\"\nProblem 1: \n\nGiven an input array of integers, count the number of values which increase relatively \nto their precedent. \n\nProblem 2: \nSame, but using the convolution of the signal with a 3-position rectangular window.\n\n\"\"\"\n\nusing DSP\n\n\n# Read input\nf = open(\"./inputs/day1.txt\", \"r\")\ndata = map( x -> parse(Int,x), eachline(f))\n\n# Problem\nfunction countIncreasing(v::Vector{Int}) :: Int\n  counter = 0\n  for i in 2:length(v)\n    if v[i] > v[i-1]\n      counter += 1\n    end\n  end\n  return counter\nend\n\ncountIncreasingSums(v) = countIncreasing(conv(v,[1,1,1])[3:end-2])\n\nprintln(\"Problem 1: \")\nprintln(countIncreasing(data))\nprintln(\"Problem 2: \")\nprintln(countIncreasingSums(data))", "meta": {"hexsha": "320effcfe492270b98af9e6cadd6bca9f131858a", "size": 685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day01.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/day01.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/day01.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": 19.0277777778, "max_line_length": 87, "alphanum_fraction": 0.6861313869, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7898240205958915}}
{"text": "\r\nmodule stest\r\nusing LinearAlgebra\r\nusing BenchmarkTools\r\nusing ..sparse\r\n\r\nfunction test_create_sparse_vec()\r\n    data = [10, 20, 1e-11, -30, 1e-5, 50, 1e-50]\r\n    index = [1, 10, 15, 20]\r\n    # vec = sparse.SparseVector(data, index)\r\n\r\n    vec2 = sparse.create_sparse(data)\r\n\r\nend\r\n\r\nfunction test_create_sparse_mat()\r\n\r\n    n_row = 5\r\n    n_col = 3\r\n\r\n    data        = [10,  20, 30, 40, 50, 60, 70, 80, 90]\r\n    row_index   = [1,   2,  3,  4,  5,  1,  1,  4,  5, n_row]\r\n    col_index   = [1,   1,  1,  2,  2,  2,  3,  3,  3, n_col]\r\n    \r\n\r\n    spmat = sparse.SparseMatrixCOO(data, row_index, col_index)\r\n\r\nend\r\n\r\n\r\nfunction test_add()\r\n\r\n    data_x  = [3.3, 4, 5, 6, 10, 4,  5,  2,  3]\r\n    index_x = [3,   4, 6, 8, 12, 15, 16, 18, 20, 25]\r\n\r\n    sp_x = sparse.SparseVector(data_x, index_x)\r\n\r\n    data_y  = [5.0, 2, 3, 5, 2, 3,  5,  2,  3]\r\n    index_y = [4,   5, 6, 7, 8, 14, 15, 16, 18, 25]\r\n\r\n    sp_y = sparse.SparseVector(data_y, index_y)\r\n\r\n    sp_z = sparse.add(sp_x, sp_y)\r\n\r\n    show(sp_z)\r\n    \r\nend\r\n\r\n\r\nfunction test_matrix_vector_mult()\r\n\r\n    n_row = 5\r\n    n_col = 3\r\n\r\n    data        = [10,  20, 30, 40, 50, 60, 70, 80, 90]\r\n    row_index   = [1,   2,  3,  4,  5,  1,  1,  4,  5, n_row]\r\n    col_index   = [1,   1,  1,  2,  2,  2,  3,  3,  3, n_col]\r\n    \r\n\r\n    spmat = sparse.SparseMatrixCOO(data, row_index, col_index)\r\n\r\n    fvec = [10.0, 5, 6]\r\n\r\n    res = spmat * fvec # sparse.matrix_vector_prod(spmat, fvec)\r\n    show(res)\r\n\r\n    fmat = sparse.create_full(spmat)\r\n    res_theo = fmat * fvec\r\n    show(res_theo)\r\n\r\n    show(res_theo - res)\r\n\r\n\r\nend\r\n\r\n\r\n\r\nfunction create_matrix(n_dim = 8)\r\n\r\n    A = zeros(Float64, n_dim, n_dim)\r\n\r\n    main_diag = [1; 4 * ones(n_dim-2); 4]\r\n    side_diag = -ones(n_dim-1)\r\n    sideside_diag = -ones(n_dim-3)\r\n    \r\n    main_diag_idx = diagind(A, 0)\r\n    side_m1_diag_idx = diagind(A, 1)\r\n    side_p1_diag_idx = diagind(A, -1)\r\n    \r\n    side_m3_diag_idx = diagind(A, 3)\r\n    side_p3_diag_idx = diagind(A, -3)\r\n    \r\n    \r\n    \r\n    A[ main_diag_idx ] = main_diag\r\n    A[ side_m1_diag_idx ] = side_diag\r\n    A[ side_p1_diag_idx ] = side_diag\r\n    A[ side_m3_diag_idx ] = sideside_diag\r\n    A[ side_p3_diag_idx ] = sideside_diag\r\n\r\n    return A\r\nend\r\n\r\nfunction test_csc()\r\n    n_dim = 8\r\n    A = create_matrix(n_dim)\r\n    A[:,1] .= 0.0\r\n    A[:,4] .= 0.0\r\n    \r\n    spmat = sparse.create_sparse_csc(A)\r\n    \r\n    Af = sparse.create_full(spmat)\r\n    \r\n    vec = rand(n_dim) # ones(n_dim)\r\n    \r\n    res = sparse.matrix_vector_prod(spmat, vec)\r\n    \r\n    res_theo = A * vec\r\n    \r\n    println( \"$(norm(res - res_theo))\" )\r\n\r\nend\r\n\r\nfunction test_matmult(spmat, vec)\r\n    res = sparse.matrix_vector_prod(spmat, vec)\r\nend\r\n\r\nfunction benchmark_matmult()\r\n\r\n    n_dim = 25000 # 25_000\r\n    A = create_matrix(n_dim)\r\n    spmat = sparse.create_sparse_csc(A)\r\n    vec = rand(n_dim)\r\n\r\n\r\n    b = @benchmark test_matmult($spmat, $vec)\r\n    println(\"=== sparse matrix vec mult === \")\r\n    show(\r\n        stdout,\r\n        MIME(\"text/plain\"),\r\n        b)\r\n    println(\"\")\r\n    println(\"\")\r\n\r\n    b = @benchmark $A * $vec\r\n    println(\"=== default full matrix vec mult === \")\r\n    show(\r\n        stdout,\r\n        MIME(\"text/plain\"),\r\n        b)\r\n\r\n\r\n    # res_sp = test_matmult(spmat, vec)\r\n    # res_fu = A * vec;\r\n\r\n    # println(\"$(norm(res_sp - res_fu))\")\r\n\r\nend\r\n\r\n\r\n\r\nn_dim = 8\r\nA = create_matrix(n_dim)\r\nA[7, 6] = 3.14\r\nA[8,7] = 2.6\r\nspmat = sparse.create_sparse_csc(A)\r\n\r\n\r\n(L, d, U) = sparse.matrix_split(spmat)\r\n\r\nLf = sparse.create_full(L)\r\nUf = sparse.create_full(U)\r\nDf = diagm(d)\r\n\r\nprintln(\" $(norm( Lf + Uf + Df - A )) \")\r\n\r\n\r\n# stest.L[8,6]\r\n\r\n\r\n\r\nend # stest", "meta": {"hexsha": "8cd7a30633aa24e20d5473e2b926255218833061", "size": 3628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/sparse/test/sparse_test.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/sparse/test/sparse_test.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/sparse/test/sparse_test.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.9340659341, "max_line_length": 64, "alphanum_fraction": 0.5441014333, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7898240189219224}}
{"text": "#\n# Denoise an S2-valued image 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\nexperiment_name = \"S2_Whirl_CPPA\"\nresults_folder = joinpath(@__DIR__, \"S2_TV\")\nexport_result = true\nexport_orig = true\nexport_table = true\nexport_function_value = true\nasymptote_render_detail = 2\n!isdir(results_folder) && mkdir(results_folder)\n#\n# Manifold & Data\nf = artificial_S2_whirl_image(64)\npixelM = Sphere(2);\n\nif export_orig\n    orig_filename = joinpath(results_folder, experiment_name * \"-orig.asy\")\n    asymptote_export_S2_data(orig_filename; data=f)\n    render_asymptote(orig_filename; render=asymptote_render_detail)\nend\n#\n# Parameters\n\u03b1 = 1.5\nmaxIterations = 4000\n#\n# Build Problem for L2-TV\nM = PowerManifold(pixelM, NestedPowerRepresentation(), size(f)...)\nd = length(size(f))\niRep = [Integer.(ones(d))..., d]\nfidelity(M, x) = 1 / 2 * distance(M, x, f)^2\n\u039b(M, x) = forward_logs(M, x) # on T_xN\nprior(M, x) = norm(norm.(Ref(pixelM), repeat(x, iRep...), \u039b(M, x)), 1)\n#\n# Setup and Optimize\ncost(M, x) = fidelity(M, x) + \u03b1 * prior(M, x)\nproxes = ((M, \u03bb, x) -> prox_distance(M, \u03bb, f, x, 2), (M, \u03bb, x) -> prox_TV(M, \u03b1 * \u03bb, 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    \u03bb=i -> \u03c0 / (2 * i),\n    return_options=true,\n)\ny = get_solver_result(o)\nyRec = get_record(o)\n#\n# Results\nif export_result\n    result_filename = joinpath(\n        results_folder,\n        experiment_name * \"-result-$(maxIterations)-\u03b1$(replace(string(\u03b1), \".\" => \"-\")).asy\",\n    )\n    asymptote_export_S2_data(result_filename; data=y)\n    render_asymptote(result_filename; render=asymptote_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": "5e34bdeafda9e209eaf97bb24b5a4392b5b4405d", "size": 2575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/CyclicProximalPoint/S2_Whirl_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/S2_Whirl_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/S2_Whirl_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": 28.2967032967, "max_line_length": 92, "alphanum_fraction": 0.6691262136, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7898240172479533}}
{"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\u22121)/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 \u2212 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 \u2212 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 \u2208 (0,..,n) and \u2208 (-l,..l) m are the\n    order and degree of spherical harmonics respectively.\n    Pol_angle \u2208 (0,..pi) and az_angle \u2208 (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 \u2208 (0,..pi) and az_angle \u2208 (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": "using Plots\r\nusing Polynomials\r\n\r\nfunction main()\r\n\r\n    # legendre_poly()\r\n    spherical_harmonics()\r\n\r\nend\r\n\r\nfunction legendre_poly()\r\n\r\n    n = 5\r\n    xlin = range(-1, 1, length=100)\r\n\r\n    plot(xaxis=(\"x\", (-1,1)), yaxis=(\"y\", (-1,1)), title=\"Legendre Polynomials\",\r\n         framestyle=:origin, legend=:outertopright, dpi=300)\r\n    for i in 0:n\r\n\r\n        pn = Pn(i)\r\n        plot!(xlin, pn.(xlin), label=\"P\"*string(i))\r\n\r\n    end\r\n\r\n    savefig(\"lp.png\")\r\n\r\nend\r\n\r\nfunction Pn(n)\r\n    p0 = Polynomial([-1, 0, 1])\r\n\r\n    an = 1/(2^n * factorial(n))\r\n\r\n    dp = (p0)^n\r\n    for i in 1:n\r\n\r\n        dp = derivative(dp)\r\n\r\n    end\r\n\r\n    return an*dp\r\nend\r\n\r\nfunction spherical_harmonics()\r\n\r\n    theta = range(0, 2\u03c0, length=100)\r\n    phi = range(0, \u03c0/2, length=100)\r\n\r\n    n = 0\r\n    m = 0\r\n\r\n    plot3d(theta, phi, Ynm.(theta, phi, n, m))\r\n\r\nend\r\n\r\nfunction Ynm(\u03b8, \u03d5, n, m)\r\n\r\n    pn = Pn(n)\r\n    dp = pn\r\n    pm = abs(m)\r\n\r\n    for i in 0:pm\r\n        dp = derivative(dp)\r\n    end\r\n\r\n    ptheta = (-1)^pm * sin(\u03b8)^pm * dp(cos(\u03b8))\r\n\r\n    if m >= 0\r\n        return ptheta * cos(m*\u03d5)\r\n    else\r\n        return ptheta * sin(pm*\u03d5)\r\n    end\r\n\r\nend\r\n\r\nmain()", "meta": {"hexsha": "ea38eb5593002f733ffdd87a0865ccbc2bc9d701", "size": 1156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "math-topics/diff_polynomials.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": "math-topics/diff_polynomials.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": "math-topics/diff_polynomials.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": 15.2105263158, "max_line_length": 81, "alphanum_fraction": 0.4982698962, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347890464284, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7897588421663996}}
{"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\u2211 = 0\nfor i in 1:1000-1\n    global \u2211 += multiple_3_5(i) ? i : 0\nend\nprint(\u2211)\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": "\"\"\"\n    SigmoidDerivative(x)\n\nDerivative of the Sigmoid activation function.\n\n    Usage:\n```julia-repl\nSigmoidDerivative(x)\n```\nArguments:\n- `x` : Input value.\n\"\"\"\nfunction SigmoidDerivative(x::Float64)\n    x\u2081 = x * (1.0 - x)\n    return x\u2081\nend", "meta": {"hexsha": "cb49fc9b5f83fdfcfe2e6e949d2b82b88e66a1e8", "size": 243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ActivationFunctionDerivatives/SigmoidDerivative.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/ActivationFunctionDerivatives/SigmoidDerivative.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/ActivationFunctionDerivatives/SigmoidDerivative.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": 15.1875, "max_line_length": 46, "alphanum_fraction": 0.658436214, "num_tokens": 74, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240177362489, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7897368547102691}}
{"text": "using SpecialFunctions\n\n\n@doc raw\"\"\"\nEvaluates the Boys function ``F\u2098(x) = \u222b\u2080\u00b9 t\u00b2\u1d50 \\exp(-xt\u00b2) 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 \u0393 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    \u03be::Float64\nend\n\nLogUtility() = LogUtility(1.0)\n\n(u::LogUtility)(c::Float64) =\n    c > 1e-10 ? u.\u03be*log(c) : u.\u03be*(log(1e-10) + 1e10*(c - 1e-10))\nderivative(u::LogUtility, c::Float64) =\n    c > 1e-10 ? u.\u03be / c : u.\u03be*1e10\n\n\"\"\"\nType used to evaluate CRRA utility. CRRA utility takes the form\n\nu(c) = \u03be c^(1 - \u03b3) / (1 - \u03b3)\n\nAdditionally, this code assumes that if c < 1e-10 then\n\nu(c) = \u03be (1e-10^(1 - \u03b3) / (1 - \u03b3) + 1e-10^(-\u03b3) * (c - 1e-10))\n\"\"\"\nstruct CRRAUtility <: AbstractUtility\n    \u03b3::Float64\n    \u03be::Float64\n\n    function CRRAUtility(\u03b3, \u03be=1.0)\n        if abs(\u03b3 - 1.0) < 1e-8\n            error(\"Your value for \u03b3 is very close to 1... Consider using LogUtility\")\n        end\n\n        return new(\u03b3, \u03be)\n    end\nend\n\n(u::CRRAUtility)(c::Float64) =\n    c > 1e-10 ?\n           u.\u03be * (c^(1.0 - u.\u03b3) - 1.0) / (1.0 - u.\u03b3) :\n           u.\u03be * ((1e-10^(1.0 - u.\u03b3) - 1.0) / (1.0 - u.\u03b3) + 1e-10^(-u.\u03b3)*(c - 1e-10))\nderivative(u::CRRAUtility, c::Float64) =\n    c > 1e-10 ? u.\u03be * c^(-u.\u03b3) : u.\u03be*1e-10^(-u.\u03b3)\n\n\n# Labor Utility\n\n\"\"\"\nType used to evaluate constant Frisch elasticity (CFE) utility. CFE\nutility takes the form\n\nv(l) = \u03be l^(1 + 1/\u03d5) / (1 + 1/\u03d5)\n\nAdditionally, this code assumes that if l < 1e-10 then\n\nv(l) = \u03be (1e-10^(1 + 1/\u03d5) / (1 + 1/\u03d5) - 1e-10^(1/\u03d5) * (1e-10 - l))\n\"\"\"\nstruct CFEUtility <: AbstractUtility\n    \u03d5::Float64\n    \u03be::Float64\n\n    function CFEUtility(\u03d5, \u03be=1.0)\n        if abs(\u03d5 - 1.0) < 1e-8\n            error(\"Your value for \u03d5 is very close to 1... Consider using LogUtility\")\n        end\n\n        return new(\u03d5, \u03be)\n    end\nend\n\n(u::CFEUtility)(l::Float64) =\n    l > 1e-10 ?\n           -u.\u03be * l^(1.0 + 1.0/u.\u03d5)/(1.0 + 1.0/u.\u03d5) :\n           -u.\u03be * (1e-10^(1.0 + 1.0/u.\u03d5)/(1.0 + 1.0/u.\u03d5) + 1e-10^(1.0/u.\u03d5) * (l - 1e-10))\nderivative(u::CFEUtility, l::Float64) =\n    l > 1e-10 ? -u.\u03be * l^(1.0/u.\u03d5) : -u.\u03be * 1e-10^(1.0/u.\u03d5)\n\n\n\"\"\"\nType used to evaluate elliptical utility function. Elliptical utility takes form\n\nv(l) = b (1 - l^\u03bc)^(1 / \u03bc)\n\"\"\"\nstruct EllipticalUtility <: AbstractUtility\n    b::Float64\n    \u03bc::Float64\nend\n\n# These defaults are pulled straight from Evans Phillips 2017\nEllipticalUtility(;b=0.5223, \u03bc=2.2926) = EllipticalUtility(b, \u03bc)\n\n(u::EllipticalUtility)(l::Float64) =\n    u.b * (1.0 - l^u.\u03bc)^(1.0 / u.\u03bc)\nderivative(u::EllipticalUtility, l::Float64) =\n    -u.b * (1.0 - l^u.\u03bc)^(1.0/u.\u03bc - 1.0) * l^(u.\u03bc - 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": "######### CmdStan optimize program example  ###########\n\nusing Compat, CmdStan, Test, Statistics\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  bernoulli = \"\n  data { \n    int<lower=0> 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\" => 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  global stanmodel, rc, optim, cnames\n  stanmodel = Stanmodel(Optimize(), name=\"bernoulli\", model=bernoulli);\n\n  rc, optim, cnames = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME);\n\n  if rc == 0\n    println()\n    display(optim)\n    println()\n    println(\"Test round.(mean(optim[1][\\\"theta\\\"]), digits=1) \u2248 0.3\")\n    @test round.(mean(optim[\"theta\"]), digits=1) \u2248 0.3\n  end\nend # cd\n", "meta": {"hexsha": "3a2c37f72543e37473fd0576ecaa995bf866001b", "size": 1013, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Bernoulli/bernoulli_optimize.jl", "max_stars_repo_name": "blakeriley/CmdStan.jl", "max_stars_repo_head_hexsha": "7b2b5e4ba9d9293434de4e8d5ba99869a76ff6aa", "max_stars_repo_licenses": ["MIT"], "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_optimize.jl", "max_issues_repo_name": "blakeriley/CmdStan.jl", "max_issues_repo_head_hexsha": "7b2b5e4ba9d9293434de4e8d5ba99869a76ff6aa", "max_issues_repo_licenses": ["MIT"], "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_optimize.jl", "max_forks_repo_name": "blakeriley/CmdStan.jl", "max_forks_repo_head_hexsha": "7b2b5e4ba9d9293434de4e8d5ba99869a76ff6aa", "max_forks_repo_licenses": ["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.119047619, "max_line_length": 87, "alphanum_fraction": 0.5340572557, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760639, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.789625668460999}}
{"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 \u03b2 c \u03b3\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) ~ -\u03b2*c*I/N*S,\n       D(I) ~ \u03b2*c*I/N*S-\u03b3*I,\n       D(R) ~ \u03b3*I];\n\n\nsys = ODESystem(eqs)\nsys = ode_order_lowering(sys);\n\n\n\u03b4t = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:\u03b4t:tmax;\n\n\nu0 = [S => 990.0,\n      I => 10.0,\n      R => 0.0];\n\n\np = [\u03b2=>0.05,\n     c=>10.0,\n     \u03b3=>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": "\n@testset \"qraddcol with \u03b2 = 0\" begin\n    m = 100\n    A = randn(m,0)\n    R = zeros(0,0)\n\n    for i in 1:m\n        a = randn(m)\n        R = qraddcol(A, R, a)\n        A = [A a]\n        @test  norm( R'*R - A'*A ) <1e-5\n    end\nend\n\n@testset \"qraddcol with \u03b2 > 0\" begin\n    m = 100\n    A = randn(m,0)\n    R = zeros(0,0)\n    \u03b2 = 0.1\n    for i in 1:m\n        a = randn(m)\n        B = [A a]\n        R = qraddcol(A, R, a, \u03b2)\n        @test norm( R'*R - B'*B - \u03b2^2*I ) <1e-5\n    end\nend\n\n\n@testset \"qraddrow\" begin\n    m, n = 3, 3\n    A = randn(m,m)\n    Q, R = qr(A)\n    for i in 1:100\n        a = randn(m)'\n        A = [A; a]\n        R = qraddrow(R, a)\n        @test norm( R'R - A'*A ) <1e-5\n    end\n\nend\n\n@testset \"qrdelcol\" begin\n    m = 100\n    A = randn(m,m)\n    Q, R = qr(A)\n    for i in 100:-1:1\n        k = rand(1:i)\n        A = A[:,1:i .!= k]\n        R = qrdelcol(R, k)\n        @test norm( R'*R - A'*A ) <1e-5#--> less_than(1e-5)\n    end\nend\n", "meta": {"hexsha": "269fd59b05e7af97555ee7e833145b6858785a90", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/hermitemap/qr.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": "test/hermitemap/qr.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": "test/hermitemap/qr.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.7547169811, "max_line_length": 59, "alphanum_fraction": 0.4187035069, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7895841713480367}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 9af04825-842b-4794-a317-6f1b78a64fb5\nbegin\n\tusing Statistics, CSV, DataFrames\n\tusing ForwardDiff\nend\n\n# \u2554\u2550\u2561 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\u03c3::Function\n\t\n\t\tfunction Layer_dense(n_in::Int, n_out::Int; \u03c3::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, \u03c3)\n\t\tend\n\tend\n\n\tfunction (L::Layer_dense)(input) \n\t\tW, b, \u03c3 = L.w, L.b, L.\u03c3\n\t\t\u03c3( (input * W') .+ b )\n\tend\nend\n\n# \u2554\u2550\u2561 c4ea1432-abb4-11eb-1cf5-edac0735d67d\nmd\"# LayerDense\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dc76be1b-292e-4545-887e-1e62faf8e1b6\nmd\"\"\"\n### Struct by Column Orientation\n\"\"\"\n\n# \u2554\u2550\u2561 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\u03c3::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\u03c3::Function = identity) where {T<:Real}                \n\t\t\t@assert size(W, 1) == length(b)\n\n\t\t\tnew{T, typeof(\u03c3)}(W, b, \u03c3)\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\u03c3::Function = identity) where {T<:Real, S<:Real}\n\t\tR = promote_type(T, S)\n\t\treturn LayerDense(Matrix{R}(W), Vector{R}(b), \u03c3)\n\tend\n\n\tfunction LayerDense(W::Matrix{T}, \u03c3::Function = identity) where {T<:Real}\n\t\tb = zeros(T, size(W, 1))\n\t\treturn LayerDense(W, b, \u03c3)\n\tend\n\n\tfunction LayerDense(n_in::Int, n_out::Int, \u03c3::Function = identity)\n\t\tW = 0.01 * randn(n_out, n_in)\n\t\tb = zeros(n_out) \n\t\treturn LayerDense(W, b, \u03c3)\n\tend\n\n\tfunction (L::LayerDense)(input::AbstractVector{<:Real})\n\t\tW, b, \u03c3 = L.W, L.b, L.\u03c3\n\t\treturn \u03c3(W * input + b)\n\tend\n\n\tfunction (L::LayerDense)(input::AbstractMatrix{<:Real})\n\t\tW, b, \u03c3 = L.W, L.b, L.\u03c3\n\t\treturn \u03c3(W * input .+ b)\n\tend\nend\n\n# \u2554\u2550\u2561 4e6d165a-9707-4029-af4a-2356b0fe9c41\nmd\"#### Example using the struct LayerDense\"\n\n# \u2554\u2550\u2561 5d3ae0e6-7c5d-48b7-9845-d204a1df9934\nW = rand(3, 4)\n\n# \u2554\u2550\u2561 e85bc0f7-65ab-4a41-a4ba-e63c8b7c8184\nB = LayerDense(W) # Layer de 4 inputs e 3 outputs\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2377f014-0bd0-457b-b9e9-3ace1ad7c331\nB(input) # Each column is an output\n\n# \u2554\u2550\u2561 c99c7f4f-7e62-4036-ba08-4478e5480d19\nmd\"#### Adding sigmoid functions\"\n\n# \u2554\u2550\u2561 96ce3aa7-9261-4e60-93ce-4d9321657d85\nmd\"\"\"\nFun\u00e7\u00e3o **Log\u00edstica**: \\\n$$\\;\\;\\;\\;\\;$$ $$\\sigma(x) = {1 \\over 1 + e^{-x}}$$ \n\nNa implementa\u00e7\u00e3o via c\u00f3digo \u00e9 necess\u00e1rio fazer uma adapta\u00e7\u00e3o que evita problemas num\u00e9ricos de *Overflow* resultando na seguinte fun\u00e7\u00e3o: \\\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\u00f3dulo de $$x$$ na express\u00e3o $$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 \u00e9 positivo ou zero ($$x \u2265 0$$) a adapta\u00e7\u00e3o resulta na pr\u00f3pria fun\u00e7\u00e3o log\u00edstica, mas quando x \u00e9 negativo s\u00e3o necess\u00e1rios os seguintes passos: \\\n$$Se \\space x \\ge 0:$$  $$\\;\\;\\;\\;\\;$$  $$\\sigma(x) = {1 \\over 1 + e^{-|x|}}$$ \\\n$$Se \\space x < 0:$$ $$\\;\\;\\;\\;\\;$$ $$1 = e^{-x} \u22c5 e^x \u2192 {1 \\over 1 + e^{-x}} = {e^{-x} \u22c5 e^x \\over e^{-x} \u22c5 e^x + e^{-x}} = {e^{-x} \u22c5 e^x \\over e^{-x}(e^x + 1)} = {e^x \\over 1 + e^x} = {e^{-|x|} \\over 1 + e^{-|x|}}$$\n\"\"\"\n\n# \u2554\u2550\u2561 58265283-a36a-4c83-9101-3387165da021\nbegin\n\tfunction \u03c3(x::Real) \n\t\tt = exp(-abs(x))\n\t\treturn ifelse(x \u2265 0, inv(1 + t), t / (1 + t))\n\tend\t\n\t\n\t\u03c3(x::AbstractVecOrMat{T}) where {T<:Real} = \u03c3.(x)\n\t\n\tconst sigmoid = \u03c3\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c85cd202-7223-4c46-80ef-afd750f28ead\nmd\"\"\"\n$$softplus(x) = ln(1 + e^x)$$\n$$For \\space x > 0:$$\n$$1 = e^{-x} \u22c5 e^x \u2192 ln(1 + e^x) = ln(e^{-x} \u22c5 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c116a1e4-fd4d-446f-bdea-02301f43b2c0\nmd\"##### Example with sigmoid functions\"\n\n# \u2554\u2550\u2561 d0c91a1c-8798-4985-978b-4c47d1abc212\nC = LayerDense(2, 3, \u03c3)\n\n# \u2554\u2550\u2561 3de0841e-f0f3-436c-a891-dd4af32d2af6\n# C(randn(2, 3))\nC([[1, 4] [2, 3] [3, 5]])\n\n# \u2554\u2550\u2561 963f6276-2440-4bfe-ae0f-539d8bfae0a2\nD = LayerDense(2, 3, softmax)\n\n# \u2554\u2550\u2561 56191b0c-fe49-4ed4-9ca7-2e22e7b028ba\nmd\"\"\"\n#### Cost Function\n\"\"\"\n\n# \u2554\u2550\u2561 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\u0302::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\u0302), dims = dims))\n\tend\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8f3cbc01-53ba-4ff0-8245-564f8fee53f2\nmd\"##### Importing data from nnfs python package\"\n\n# \u2554\u2550\u2561 099f5fa8-6687-4c77-9f61-119d75377bab\ndata = CSV.read(\"spiral_data.csv\", DataFrame)\n\n# \u2554\u2550\u2561 b5981a68-16e7-451f-9e13-d74b2b78a958\nmd\"#### Chain type, params(), gradient()\"\n\n# \u2554\u2550\u2561 d2fa0422-7f39-4365-8f3b-bfa6997ae0ae\nbegin\n\tRandom.seed!(1998)\n\t\n\tL1 = LayerDense(10, 5, \u03c3)\n\tL2 = LayerDense(5, 2, softmax)\n\t\n\toutput = L2(L1(rand(10)))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e84cff98-1bea-42cb-8e8d-6f5ef08226f4\nbegin \n\t\u0398 = 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( \u0398[ 1:U[1] ], size(L1.W, 1), size(L1.W, 2))\n\t\n\tL1b = \u0398[ U[1]+1:U[2] ]\n\t\n\tL2w = reshape( \u0398[ U[2]+1:U[3] ], size(L2.W, 1), size(L2.W, 2))\n\t\n\tL2b = \u0398[ U[3]+1:U[4] ]\n\t\n\t( length(\u0398), U, (L1w, L1b, L2w, L2b) )\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 154e4560-0769-429e-89bd-3b0392209d6d\ntypeof( (1.3,2.12) )\n\n# \u2554\u2550\u2561 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 \u2218(reverse(L.layers)...)(input)\n\tend\nend\n\n# \u2554\u2550\u2561 4504eaff-0c86-4606-a410-c94a8e8a653e\nbegin\n\t#L1 = LayerDense(10, 5, \u03c3)\n\t#L2 = LayerDense(5, 2, softmax)\n\t\n\tC1 = Chain(L1, L2)\n\ttypeof(C1.layers)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4b019add-7eb4-496a-b0ef-3c3eee9d85bd\nbegin\n\tC1(rand(10,12))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500c4ea1432-abb4-11eb-1cf5-edac0735d67d\n# \u255f\u250045d31083-883b-4e84-913e-c040c6fdfd5f\n# \u255f\u2500dc76be1b-292e-4545-887e-1e62faf8e1b6\n# \u2560\u2550fe237f5f-8f90-429a-8ddc-e5933b8fd808\n# \u255f\u25004e6d165a-9707-4029-af4a-2356b0fe9c41\n# \u2560\u25505d3ae0e6-7c5d-48b7-9845-d204a1df9934\n# \u2560\u2550e85bc0f7-65ab-4a41-a4ba-e63c8b7c8184\n# \u2560\u2550142bb8f9-4188-46d2-94a2-8407d633c496\n# \u2560\u25502377f014-0bd0-457b-b9e9-3ace1ad7c331\n# \u255f\u2500c99c7f4f-7e62-4036-ba08-4478e5480d19\n# \u255f\u250096ce3aa7-9261-4e60-93ce-4d9321657d85\n# \u2560\u255058265283-a36a-4c83-9101-3387165da021\n# \u255f\u2500fc1ddc84-62dc-4af1-9b9e-9d37f581a252\n# \u2560\u255045bafada-34ec-4c41-b0a2-000f35ebffef\n# \u255f\u2500c85cd202-7223-4c46-80ef-afd750f28ead\n# \u2560\u2550d6fce490-1498-469d-8ecc-55d0a71d1565\n# \u2560\u255004cadf6a-4fd1-4b5f-aa4d-140ea6e5cff2\n# \u2560\u2550a7898ffd-1acb-4220-bbc8-3b428b95db85\n# \u255f\u2500c116a1e4-fd4d-446f-bdea-02301f43b2c0\n# \u2560\u2550d0c91a1c-8798-4985-978b-4c47d1abc212\n# \u2560\u25503de0841e-f0f3-436c-a891-dd4af32d2af6\n# \u2560\u2550963f6276-2440-4bfe-ae0f-539d8bfae0a2\n# \u255f\u250056191b0c-fe49-4ed4-9ca7-2e22e7b028ba\n# \u2560\u25507b5a6859-a9e1-48b1-a0fd-1cde06249d03\n# \u2560\u25504b070348-fdbc-46cd-85f0-29b64432ae21\n# \u2560\u2550e3ec0333-14ad-42a8-9cd3-4e3937dc5ff0\n# \u255f\u25008f3cbc01-53ba-4ff0-8245-564f8fee53f2\n# \u255f\u2500099f5fa8-6687-4c77-9f61-119d75377bab\n# \u2560\u25509af04825-842b-4794-a317-6f1b78a64fb5\n# \u255f\u2500b5981a68-16e7-451f-9e13-d74b2b78a958\n# \u2560\u2550d2fa0422-7f39-4365-8f3b-bfa6997ae0ae\n# \u2560\u2550ac678c79-a804-44e0-80d8-15a40dff327d\n# \u2560\u255072f68243-8ae1-465c-854d-a76c07c5e346\n# \u2560\u2550e84cff98-1bea-42cb-8e8d-6f5ef08226f4\n# \u2560\u2550a5a511f7-38f0-4074-9192-7f11d611bf42\n# \u2560\u2550154e4560-0769-429e-89bd-3b0392209d6d\n# \u2560\u255074ccd8c6-f513-4178-a41f-7b70835516e7\n# \u2560\u25504504eaff-0c86-4606-a410-c94a8e8a653e\n# \u2560\u25504b019add-7eb4-496a-b0ef-3c3eee9d85bd\n# \u255f\u2500be7baa4f-6871-4d74-b4d2-1c2534cdfa17\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "function defaultfcn(z)\n    f = 1e9\n    \u03f5\u1d63 = 5 - 2im\n    \u03bc\u1d63 = 1 - 2im\n    d = 1e-2\n    c = 3e8\n    \u03c9 = 2\u03c0*f\n    k\u2080 = \u03c9/c\n    cc = \u03f5\u1d63^2*(k\u2080*d)^2*(\u03f5\u1d63*\u03bc\u1d63 - 1)\n    w = \u03f5\u1d63^2*z^2 + z^2*tan(z)^2 - cc\nend\n\n# Analysis parameters\nxb = -2  # real part begin\nxe = 2  # real part end\nyb = -2  # imag part begin\nye = 2  # imag part end\nr = 0.1999  # initial mesh step\n\norigcoords = rectangulardomain(complex(xb, yb), complex(xe, ye), r)\n\n# matlab results from https://github.com/PioKow/GRPF for comparison\nmatlab_zroots = [-1.624715288135189 + 0.182095877702038im,\n                 -1.520192978034417 - 0.173670452237129im,\n                 -0.515113098919392 + 0.507111597359180im,\n                  0.515113098795215 - 0.507111597284675im,\n                  1.520192978034417 + 0.173670452237129im,\n                  1.624715288135189 - 0.182095877702037im]\n\nmatlab_zpoles = [-1.570796326699632 - 0.000000000206961im,\n                  1.570796326699632 - 0.000000000206961im]\n\nzroots, zpoles = grpf(defaultfcn, origcoords)\n\n@test length(zroots) == 6\n@test length(zpoles) == 2\n\n@test approxmatch(zroots, matlab_zroots)\n@test approxmatch(zpoles, matlab_zpoles)\n\npzroots, pzpoles, quadrants, phasediffs, tess, g2f = grpf(defaultfcn, origcoords, PlotData())\n\n@test approxmatch(pzroots, matlab_zroots)\n@test approxmatch(pzpoles, matlab_zpoles)\n\ntmpr, tmpp = grpf(defaultfcn, origcoords, GRPFParams(8000, 1e-9))\n\n@test approxmatch(tmpr, zroots)\n@test approxmatch(tmpp, zpoles)\n\ntmpr, tmpp, quadrants, phasediffs, tess, g2f = grpf(defaultfcn, origcoords, PlotData(), GRPFParams(8000, 1e-9))\n\n@test approxmatch(tmpr, zroots)\n@test approxmatch(tmpp, zpoles)\n\ntmpr, tmpp = grpf(defaultfcn, origcoords, GRPFParams(8000, 1e-9, true))\n\n@test approxmatch(tmpr, zroots)\n@test approxmatch(tmpp, zpoles)\n\n# Test with very low maxnodes\nmaxnodes = 10\nparams = GRPFParams(100, maxnodes, 3, maxnodes-1, 1e-9, false)\n@test_logs (:warn,\"GRPFParams.maxnodes reached\") grpf(defaultfcn, origcoords, PlotData(), params)\n\n# Test with big origcoords\nxb = big(xb)  # real part begin\nxe = big(xe)  # real part end\nyb = big(yb)  # imag part begin\nye = big(ye)  # imag part end\nr = big(r)  # initial mesh step\n\norigcoords = rectangulardomain(complex(xb, yb), complex(xe, ye), r)\n\nbzroots, bzpoles = grpf(defaultfcn, origcoords)\n\n@test all(isa.(bzroots, Complex{BigFloat}))\n@test all(isa.(bzpoles, Complex{BigFloat}))\n\n@test approxmatch(bzroots, zroots)\n@test approxmatch(bzpoles, zpoles)\n\n# Test region with no roots or poles\nxb, xe = -1, 1\nyb, ye = -2, -1\norigcoords = rectangulardomain(complex(xb, yb), complex(xe, ye), r)\n\nnozroots, nozpoles = grpf(defaultfcn, origcoords)\n\n@test length(nozroots) == 0\n@test length(nozpoles) == 0\n\nnozroots, nozpoles, quadrants, phasediffs, tess, g2f = grpf(defaultfcn, origcoords, PlotData())\n\n@test length(nozroots) == 0\n@test length(nozpoles) == 0\n\nxb, xe = big\"-1\", big\"1\"\nyb, ye = big\"-2\", big\"-1\"\nr = big\"0.2\"\n\norigcoords = rectangulardomain(complex(xb, yb), complex(xe, ye), r)\n\nbnozroots, bnozpoles = grpf(defaultfcn, origcoords)\n\n@test eltype(bnozroots) == Complex{BigFloat}\n@test eltype(bnozpoles) == Complex{BigFloat}\n\n@test length(bnozroots) == 0\n@test length(bnozpoles) == 0\n", "meta": {"hexsha": "4c03def238d989d1ec5e80e42d9675603c45b298", "size": 3179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DefaultFunction.jl", "max_stars_repo_name": "fgasdia/RootsAndPoles.jl", "max_stars_repo_head_hexsha": "71012d4033c6a7dd2ca50a4a9492e2ebd87fb004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-09-09T12:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T04:06:52.000Z", "max_issues_repo_path": "test/DefaultFunction.jl", "max_issues_repo_name": "fgasdia/RootsAndPoles.jl", "max_issues_repo_head_hexsha": "71012d4033c6a7dd2ca50a4a9492e2ebd87fb004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-05-31T18:26:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T01:57:32.000Z", "max_forks_repo_path": "test/DefaultFunction.jl", "max_forks_repo_name": "fgasdia/RootsAndPoles.jl", "max_forks_repo_head_hexsha": "71012d4033c6a7dd2ca50a4a9492e2ebd87fb004", "max_forks_repo_licenses": ["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.6396396396, "max_line_length": 111, "alphanum_fraction": 0.6882667506, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7895275281516593}}
{"text": "#A deck with 52 cards - 4 suites and 13 ranks - A,2,...,10,J,Q,K\ndeck = [(suite,r) for suite in [\"\u2661\",\"\u2662\", \"\u2663\", \"\u2660\"]  for r in range(1,13)]\n\nfunction simulate_pair(n = 100, verbose=false)\n    pairs = 0\n    for i in 1:n\n        hand = shuffle(deck)[1:2]\n        if length(unique([r for (s,r) in hand])) == 1\n                if verbose\n                    println(hand)\n                end\n                pairs += 1\n        end\n    end\n    100.*pairs/n\nend\ngood_pairs(len_deck = 52) = (len_deck*3)/2\nall_pairs(len_deck = 52) = binomial(len_deck, 2)\n\nfunction simulate_disjoint_triplet(n = 100, verbose=false)\n    triplets = 0\n    for i in 1:n\n        hand = shuffle(deck)[1:3]\n        if length(unique([r for (s,r) in hand])) == 3 \n                if verbose\n                    println(hand)\n                end\n                triplets += 1\n        end\n    end\n    100.*triplets/n\nend\ndisjoint_triplets(len_deck = 52) = (len_deck*(len_deck-4)*(len_deck-8))/factorial(3)\nall_triplets(len_deck = 52) = binomial(len_deck, 3)\n\n\nfunction simulate_one_pair_hand(n = 100, verbose=false)\n    pairs = 0\n    for i in 1:n\n        hand = shuffle(deck)[1:5]\n        if length(unique([r for (s,r) in hand])) == 4\n                if verbose\n                    println(hand)\n                end\n                pairs += 1\n        end\n    end\n    100.*pairs/n\nend\nprob_one_pair_hand = 100.* good_pairs(52) * disjoint_triplets(48) / binomial(52,5)\n\n\n", "meta": {"hexsha": "eb9c5284bbd578572042f891ddd2f3106d853d83", "size": 1433, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "counting.jl", "max_stars_repo_name": "sbebo/prob", "max_stars_repo_head_hexsha": "d3af3871645c8ec1f7a3e961a48dffaf9d69cf72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "counting.jl", "max_issues_repo_name": "sbebo/prob", "max_issues_repo_head_hexsha": "d3af3871645c8ec1f7a3e961a48dffaf9d69cf72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "counting.jl", "max_forks_repo_name": "sbebo/prob", "max_forks_repo_head_hexsha": "d3af3871645c8ec1f7a3e961a48dffaf9d69cf72", "max_forks_repo_licenses": ["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.0377358491, "max_line_length": 84, "alphanum_fraction": 0.5310537334, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7895275262161435}}
{"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 \u03bb\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_\u03bb_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 \u00f7 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\u03bc, \u03c3 = rescale!(train_features; obsdim = 1)\nrescale!(test_features, \u03bc, \u03c3; obsdim = 1);\n\n\n# Bayesian multinomial logistic regression\n@model function logistic_regression(x, y, \u03c3)\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, \u03c3)\n    intercept_virginica ~ Normal(0, \u03c3)\n    coefficients_versicolor ~ MvNormal(4, \u03c3)\n    coefficients_virginica ~ MvNormal(4, \u03c3)\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#   - \u03bb = 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\u00f2 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             # \u2200 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           # \u2200 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 \u2242\u0338 0: \u2203 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            # \u2200 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       # \u2200 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      # \u2200 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 \u2208 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# - \u03b8_k: The vector parameters in the form [q, \u03c3\u00b2]\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, \u03b8_k, k)\n    # Extract density parameters\n    q, \u03c3\u00b2 = \u03b8_k\n    \u03c3 = sqrt(\u03c3\u00b2)\n\n    n = length(x)\n\n    \ud835\udca9\u2081 = Normal(1, \u03c3)\n    \ud835\udca9\u2080 = Normal(0, \u03c3)\n\n    if k == 1\n        joint = (q*(y[k+1] == 1) + (1-q)*(y[k+1] == 0))*pdf(\ud835\udca9\u2081, x[k])\n\n        marginal = joint + (q*(y[k+1] == 0) + (1-q)*(y[k+1] == 1))*pdf(\ud835\udca9\u2080,x[k])\n    elseif k == n\n        joint = (q*(y[k-1] == 1) + (1-q)*(y[k-1] == 0))*pdf(\ud835\udca9\u2081, x[k])\n\n        marginal = joint + (q*(y[k-1] == 0) + (1-q)*(y[k-1] == 1))*pdf(\ud835\udca9\u2080,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(\ud835\udca9\u2081,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(\ud835\udca9\u2080, 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# - \u03b8_k: The vector parameters in the form [q, \u03c3\u00b2]\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, \u03b8_k)\n    n = length(x)\n\n    for k = 1:n\n        y[k] = rand() < conditional_probability(x, y, \u03b8_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# - \u03b8_k: The vector parameters in the form [q, \u03c3\u00b2]\n# Outputs\n# A Y sample where Y ~ P(Y|X = x)\nfunction gibbs_sampler(x, \u03b8_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, \u03b8_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# - \u03b8_k: The vector parameters in the form [q, \u03c3^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, \u03b8_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, \u03b8_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 \u03b8\n# Inputs\n# - x: The vector of (observed) X variables\n# Outputs\n# An estimate of \u03b8 = [q, \u03c3\u00b2]\nfunction em_algorithm(x)\n    # Initialize theta parameter [q, \u03c3\u00b2]\n    \u03b8_k = [0.5, 1]\n    @printf(\"k = 0: [%f, %f]\\n\", \u03b8_k[1], \u03b8_k[2])\n\n    num_iterations = 500\n\n    for i = 1:num_iterations\n        a, b, c = estimate_a_b_c(x, \u03b8_k)\n        q_1 = a/(a+b)\n        \u03c3\u00b2_1 = c/(a+b+1)\n        \u03b8_k = [q_1, \u03c3\u00b2_1]\n\n        @printf(\"k = %d: [%f, %f]\\n\", i, \u03b8_k[1], \u03b8_k[2])\n    end\n\n    return \u03b8_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)/\u221a(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": "using RollingFunctions\nusing Statistics\nusing StatsBase\nusing LinearAlgebra\nusing Test\n\ndatavec = collect(1.0f0:5.0f0)\nweighting = normalize([1.0f0, 2.0f0, 4.0f0])\n\nwindowsize = 3\n\n@test rollmean(datavec, windowsize) == Float32[2.0, 3.0, 4.0]\n\nexpected = [2.0f0, 3.0f0, 4.0f0]\nobtained = rolling(mean, datavec, 3)\n@test Float32(eps(Float64)) > abs(sum(expected .- obtained))\n\nexpected = [1.236568f0, 1.7457432f0, 2.254918f0]\nobtained = rollmean(datavec, windowsize, weighting)\n@test Float32(eps(Float32)) > abs(sum(expected .- obtained))\n\nexpected = [1.0f0, 1.1180339f0, 1.236568f0, 1.7457432f0, 2.254918f0]\nobtained = running(mean, datavec, 3, weighting)\n@test Float32(eps(Float32)) > abs(sum(expected .- obtained))\n\ndata1=[1,2,3,4,5,6,7];data2=[1,4,6,16,25,36,49];\nweighting = normalize([1.0, 2.0, 1.0, 2.0]);\n\nexpected = [2.5, 6.0, 9.5, 10.0, 12.0]\nobtained = rolling(cov, data1, data2, 3)\n@test eps(Float32) > abs(sum(expected .- obtained))\n\nexpected = [0.9751641759537001, 0.9283031155706918, 0.9749534026403799, 0.9732162133211492]\nobtained = rollcor(data1, data2, 4, weighting)\n@test eps(Float32) > abs(sum(expected .- obtained))\n\nexpected = [0.0, 1.5, 2.5, 7.833333333333333, 15.0, 20.75, 26.5]\nobtained = runcov(data1, data2, 5)\n@test eps(Float32) > abs(sum(expected .- obtained))\n", "meta": {"hexsha": "cd49088dd53be1815c117424c38a4d775908d84e", "size": 1290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/RollingFunctions.jl-b0e4dd01-7b14-53d8-9b45-175a3e362653", "max_stars_repo_head_hexsha": "f42c3e28668d63191daf93e4b62f81d9f98c1b40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2017-04-19T22:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T17:53:03.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirror/RollingFunctions.jl-b0e4dd01-7b14-53d8-9b45-175a3e362653", "max_issues_repo_head_hexsha": "f42c3e28668d63191daf93e4b62f81d9f98c1b40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-03-29T09:02:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:16:10.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirror/RollingFunctions.jl-b0e4dd01-7b14-53d8-9b45-175a3e362653", "max_forks_repo_head_hexsha": "f42c3e28668d63191daf93e4b62f81d9f98c1b40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-04-09T10:30:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T19:54:46.000Z", "avg_line_length": 32.25, "max_line_length": 91, "alphanum_fraction": 0.7046511628, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8652240964782011, "lm_q1q2_score": 0.7894617504825165}}
{"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 \u03bc and \u03c3\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        \u03bc = mean(data, 1)\n        \u03c3 = std(data, 1)\n        X_out = copy(X)\n        for i = 1:length(subset)\n            X_out[:, subset[i]] = (X_out[:, subset[i]] .- \u03bc[i]) ./ \u03c3[i]\n        end\n        return X_out, \u03bc, \u03c3\n\n    # Normalise each row\n    elseif dim == 1\n        data = X[subset, :]\n        \u03bc = mean(data, 2)\n        \u03c3 = std(data, 2)\n        X_out = copy(X)\n        for i = 1:length(subset)\n            X_out[subset[i], :] = (X_out[subset[i], :] .- \u03bc[i]) ./ \u03c3[i]\n        end\n        return X_out, \u03bc, \u03c3\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 \u03bc and \u03c3\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        \u03bc = mean(data, 1)\n        \u03c3 = std(data, 1)\n        for i = 1:length(subset)\n            X[:, subset[i]] = (X[:, subset[i]] .- \u03bc[i]) ./ \u03c3[i]\n        end\n        return \u03bc, \u03c3\n\n    # Normalise each row\n    elseif dim == 1\n        data = X[subset, :]\n        \u03bc = mean(data, 2)\n        \u03c3 = std(data, 2)\n        for i = 1:length(subset)\n            X[subset[i], :] = (X[subset[i], :] .- \u03bc[i]) ./ \u03c3[i]\n        end\n        return \u03bc, \u03c3\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 \u03bc (mean) and \u03c3 (standard deviation)\n# Same options as above for dimension and subset of features\nfunction normalise(X::Array, \u03bc::Array, \u03c3::Array; dim::Int=2, subset::Vector=collect(1:size(X, dim)))\n\n    # Check lengths\n    length(\u03bc) != length(\u03c3) && throw(\"\u03bc and \u03c3 must be same length\")\n    length(\u03bc) != length(subset) && throw(\"\u03bc 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]] .- \u03bc[i]) ./ \u03c3[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], :] .- \u03bc[i]) ./ \u03c3[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 \u03bc (mean) and \u03c3 (standard deviation)\n# Same options as above for dimension and subset of features\nfunction normalise!(X::Array, \u03bc::Array, \u03c3::Array; dim::Int=2, subset::Vector=collect(1:size(X, dim)))\n\n    # Check lengths\n    length(\u03bc) != length(\u03c3) && throw(\"\u03bc and \u03c3 must be same length\")\n    length(\u03bc) != length(subset) && throw(\"\u03bc 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]] .- \u03bc[i]) ./ \u03c3[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], :] .- \u03bc[i]) ./ \u03c3[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 (\u5c11\u3057\u6642\u9593\u3092\u53d6\u3089\u308c\u308b\u3002\u305d\u306e\u9593\u306b\u4e0b\u306e\u30bb\u30eb\u3067\u30b3\u30fc\u30c9\u3092\u5165\u529b\u3059\u308b)\nhistogram(randn(10^5); norm=true, alpha=0.3, size=(300, 200))\nplot!(Normal())\n\n# %%\n# \u30b3\u30a4\u30f3\u309220\u56de\u6295\u3052\u305f\u3068\u304d\u306e\u8868\u304c\u51fa\u308b\u56de\u6570\u306e\u5206\u5e03\u306f\u6b63\u898f\u5206\u5e03\u3067\u8fd1\u4f3c\u3055\u308c\u308b\u3002\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, \u221a(n*p*(1-p))), 0, 20; label=\"normal approx.\", lw=2)\n\n# %%\n# \u56de\u6570n\u3001\u78ba\u7387\u30d1\u30e9\u30e1\u30fc\u30bfp\u306e\u4e8c\u9805\u5206\u5e03\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3092\u6b21\u306e\u3088\u3046\u306b\u4f5c\u308c\u308b\u3002\n\nbin = Binomial(n, p)\n\n# %%\n# \u78ba\u7387\u5206\u5e03\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u4e71\u6570\n\nrand(bin)\n\n# %%\n# \u78ba\u7387\u5206\u5e03\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u4e71\u6570\u3092\u8907\u6570\u500b\u751f\u6210\n\n@show rand(bin, 20);\n\n# %%\n# \u30b5\u30f3\u30d7\u30eb\u306e\u30d2\u30b9\u30c8\u30b0\u30e9\u30e0\n# norm = true \u3067\u78ba\u7387\u5bc6\u5ea6\u51fd\u6570\u3068\u6bd4\u8f03\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\u3002\n# alpha = 0.3 \u3067\u534a\u900f\u660e\u5316pp\n# bin = -0.5:n+0.5 \u3067 1 \u523b\u307f\u306e\u9069\u5207\u306a\u30d3\u30f3\u3092\u8a2d\u5b9a\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 \u306f [-0.5, 0.5, 1.5, 2.5, ..., 19.5, 20.5] \u3068\u307b\u307c\u7b49\u4fa1\n\n-0.5:n+0.5\n\n# %%\n@show collect(-0.5:n+0.5);\n\n# %%\n# \u5e73\u5747\u03bc\u3001\u6a19\u6e96\u504f\u5dee\u03c3\u306e\u6b63\u898f\u5206\u5e03\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306f\u6b21\u306b\u3088\u3046\u306b\u3057\u3066\u4f5c\u308c\u308b\u3002\n\nnormal = Normal(n*p, \u221a(n*p*(1-p)))\n\n# %%\n# \u78ba\u7387\u5206\u5e03\u30aa\u30d6\u30b8\u30a7\u30af\u30c8 dist \u306f plot(dist) \u3067\u30d7\u30ed\u30c3\u30c8\u3067\u304d\u308b\u3002\n# lw = 2 \u30672\u500d\u306e\u592a\u3055\u3067\u30d7\u30ed\u30c3\u30c8\n\nplot(normal, 0, 20; label=\"normal dist.\", lw=2)\n\n# %%\n# \u4ee5\u4e0a\u3092\u91cd\u306d\u3066\u30d7\u30ed\u30c3\u30c8\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, \u221a(n*p*(1-p))), 0, 20; label=\"normal approx.\", lw=2)\n\n# %%\n# \u30b5\u30a4\u30b3\u30ed\u309210\u56de\u632f\u3063\u3066\u51fa\u305f\u76ee\u306e\u5e73\u5747\u5024\u306e\u5206\u5e03\u306f\u6b63\u898f\u5206\u5e03\u3067\u3088\u304f\u8fd1\u4f3c\u3055\u308c\u308b\u3002\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)/\u221an), 1, 6; label=\"normal approx.\", lw=2)\n\n# %%\n# 2\u3064\u306e\u78ba\u7387\u30d1\u30e9\u30e1\u30fc\u30bf(\u6bd4\u7387\u30d1\u30e9\u30e1\u30fc\u30bf)\u304c\u7b49\u3057\u3044\u4e8c\u9805\u5206\u5e03\u3067\u751f\u6210\u3055\u308c\u305f\u30b5\u30f3\u30d7\u30eb\u306eZ\u7d71\u8a08\u91cf\u306f\n# \u8fd1\u4f3c\u7684\u306b\u6a19\u6e96\u6b63\u898f\u5206\u5e03\u306b\u5f93\u3046\u3002\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\u00d72 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) / \u221a(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# \u6570\u5f0f\u51e6\u7406\u3092\u4f7f\u3063\u3066\u3001Z\u7d71\u8a08\u91cf\u306e2\u4e57\u304cPearson\u306e\u03c7\u00b2\u7d71\u8a08\u91cf\u306b\u4e00\u81f4\u3059\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3002\n# \u4e0a\u306e\u6570\u5024\u8a08\u7b97\u3067\u4f7f\u3063\u305fzstat\u51fd\u6570\u3092\u305d\u306e\u307e\u307e\u6570\u5f0f\u51e6\u7406\u3067\u5229\u7528\u3059\u308b\u3002\n\nusing SymPy\n\n@syms a b c d\nZ = zstat(a, b, c, d)\n\n# %%\n# Z^2 |> factor \u306f factor(Z^2) \u306b\u7b49\u4fa1\n# \u4ee5\u4e0b\u306e\u8a08\u7b97\u7d50\u679c\u306fPearson\u306e\u03c7\u00b2\u7d71\u8a08\u91cf\u306e\u6709\u540d\u306a\u8868\u793a\u306b\u4e00\u81f4\n\nZ^2 |> factor\n\n# %%\n# (O - E)\u00b2/E \u306e\u548c\u3067\u5b9a\u7fa9\u3055\u308c\u305fPearson\u306e\u03c7\u00b2\u7d71\u8a08\u91cf\n\n\"\"\"Pearson's \u03c7\u00b2 statistic of 2\u00d72 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\u00b2 = (a - Ea)^2/Ea + (b - Eb)^2/Eb + (c - Ec)^2/Ec + (d - Ed)^2/Ed\nend\n\nX\u00b2 = chisqstat(a, b, c, d)\n\n# %%\n# \u4ee5\u4e0b\u306e\u8a08\u7b97\u7d50\u679c\u306f2\u00d72\u306e\u5206\u5272\u8868\u306ePearson \u03c7\u00b2\u7d71\u8a08\u91cf\u306b\u95a2\u3059\u308b\u6709\u540d\u306a\u516c\u5f0f\n\nX\u00b2 |> factor\n\n# %%\n# \u6b63\u78ba\u4e8c\u9805\u691c\u5b9a\u306eP\u5024\u306e\u5b9a\u7fa9\n\n# \\lessapprox TAB \u2192 \u2a85\n# \\approx TAB \u2192 \u2248\nx \u2a85 y = x < y || x \u2248 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) \u2a85 pdf(dist, k))\n\n# %%\n# \u6b63\u78ba\u4e8c\u9805\u691c\u5b9a\u306eP\u5024\u306e\u4f8b\u3000(\u30d1\u30e9\u30e1\u30fc\u30bfp\u3092\u56fa\u5b9a\u3057\u305f\u5834\u5408(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# \u6b63\u78ba\u4e8c\u9805\u691c\u5b9a\u306eP\u5024\u306e\u4f8b\u3000(\u30c7\u30fc\u30bfk\u3092\u56fa\u5b9a\u3057\u305f\u5834\u5408)\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# \u4fe1\u983c\u533a\u9593\u51fd\u6570\u306e\u5b9a\u7fa9\n\nusing Roots\n\n\"\"\"generic confidence interval function\"\"\"\nfunction confint(pvalfunc, mlefunc, n, k, pmin, pmax; \u03b1 = 0.05)\n    f(p) = pvalfunc(n, p, k) - \u03b1\n    ci = find_zeros(f, pmin, pmax)\n    length(ci) \u2265 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; \u03b1 = 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; \u03b1)\nend\n\n# %%\n# \u6b63\u78ba\u4e8c\u9805\u691c\u5b9a\u306e\u30c7\u30fc\u30bfk\u3092\u56fa\u5b9a\u3057\u305f\u5834\u5408\u306eP\u5024\u51fd\u6570\u306e\u30d7\u30ed\u30c3\u30c8\u306b\n# 95%\u4fe1\u983c\u533a\u9593\u306e\u30d7\u30ed\u30c3\u30c8\u3092\u8ffd\u52a0\n\nn, k = 20, 6\n\u03b1 = 0.05\nci = confint_bin(n, k; \u03b1)\n\np = 0:0.002:1\ny = @. pval_exact(Binomial(n, p), k)\nplot(p, y; label=\"\")\nplot!(ci, [\u03b1, \u03b1]; label=\"$(100(1 - \u03b1))% 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# \u30c7\u30fc\u30bfk\u3092\u52d5\u304b\u3057\u3066\u4fe1\u983c\u533a\u9593\u3092\u30d7\u30ed\u30c3\u30c8 (1)\n\nn = 20\nk = 0:n\n\u03b1 = 0.05\nci = confint_bin.(n, k; \u03b1)\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 - \u03b1))% 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# \u30c7\u30fc\u30bfk\u3092\u52d5\u304b\u3057\u3066\u4fe1\u983c\u533a\u9593\u3092\u30d7\u30ed\u30c3\u30c8 (2)\n\nn = 20\nk = 0:n\n\u03b1 = 0.05\nci = confint_bin.(n, k; \u03b1)\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 - \u03b1))% confidence intervals (n = $n)\"; titlefontsize=12)\n\n# %% tags=[]\n# \u30c7\u30fc\u30bfk\u3092\u52d5\u304b\u3057\u3066\u4fe1\u983c\u533a\u9593\u3092\u30d7\u30ed\u30c3\u30c8 (3)\n\nn = 20\nk = 0:n\n\u03b1 = 0.05\nci = confint_bin.(n, k; \u03b1)\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 - \u03b1))% confidence intervals (n = $n)\"; titlefontsize=12)\n\n# %%\n# P\u5024\u51fd\u6570\u306e\u30d2\u30fc\u30c8\u30de\u30c3\u30d7\n\nn = 20\np = 0:0.002:1\nk = 0:n\n\u03b1 = 0.05\nci = confint_bin.(n, k; \u03b1)\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\u5024\u51fd\u6570\u306e\u30d2\u30fc\u30c8\u30de\u30c3\u30d7\u3068\u4fe1\u983c\u533a\u9593\n\nn = 20\np = 0:0.002:1\nk = 0:n\n\u03b1 = 0.05\nci = confint_bin.(n, k; \u03b1)\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 - \u03b1))% 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# \u2554\u2550\u2561 9d286b46-73ae-49f7-b834-791b9ef95420\nbegin\n\tusing PlutoUI\nend\n\n# \u2554\u2550\u2561 4abf8eda-2c36-11ec-3cdb-4104751a59ad\nmd\"\"\"\n\n#### Solution: Flash Practice Problem\n\n\"\"\"\n\n# \u2554\u2550\u2561 c017ef4d-a828-4f46-922a-453d72636c39\nmd\"\"\"$(PlutoUI.LocalResource(\"./figs/Fig-VLE-Ideal-Pxy-P2-F19.png\"))\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e86e41b3-d39b-4986-b1cd-4ed34eaabae5\nbegin\n\t\n\t# what are the A, B, and C for component 1?\n\tA\u2081 = 4.45 \t\t# units: AU\n\tB\u2081 = 718.1 \t\t# units: 1/K\n\tC\u2081 = -22.01 \t# units: K\n\t\n\tA\u2082 = 3.98 \t\t# units: AU\n\tB\u2082 = 677.1 \t\t# units: 1/K\n\tC\u2082 = -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\u2081 + B\u2081/(log10(P1sat) - A\u2081))\n\t\n\twith_terminal() do\n\t\tprintln(\"T = $(round(T; digits=2)) K\")\n\tend\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f167be1a-2801-4cc6-b036-6d6688dddb44\nbegin\n\t\n\t# 1) compute the saturation pressures -\n\tP1sat_aeq = 10^(A\u2081 - (B\u2081/(C\u2081 + T)))\n\tP2sat_aeq = 10^(A\u2082 - (B\u2082/(C\u2082 + 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25004abf8eda-2c36-11ec-3cdb-4104751a59ad\n# \u255f\u2500c017ef4d-a828-4f46-922a-453d72636c39\n# \u2560\u2550d5b781d8-6e6a-4bc9-9b45-1272e1b86e61\n# \u2560\u2550e86e41b3-d39b-4986-b1cd-4ed34eaabae5\n# \u255f\u2500796fd591-bf7f-4b94-af8f-f5b7ab25e563\n# \u2560\u2550453aba4c-fc32-46a7-ad1c-0c360a5dc886\n# \u255f\u2500c4f4a653-cd23-4c9a-9b3d-10da27ca9d79\n# \u2560\u25502c1378b9-08e3-42ef-9239-fd86fd85cd38\n# \u255f\u250091f257b4-b480-4179-b68a-760824600949\n# \u2560\u2550f167be1a-2801-4cc6-b036-6d6688dddb44\n# \u2560\u2550b8002941-f892-46b8-9c27-1cb08cc3c71b\n# \u2560\u255052fba159-cafc-4293-ab32-6b965ca957b8\n# \u2560\u2550ed9fe0d8-0d9b-4ad2-b327-44d9798cc666\n# \u255f\u2500dbfacc23-773b-49bb-a531-f460aacf5f98\n# \u255f\u25009d286b46-73ae-49f7-b834-791b9ef95420\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "const SEATCODES = Dict('F' => '0', 'B' => '1', 'L' => '0', 'R' => '1')\n\nfunction seatid(line)\n  parse(Int, map(c -> SEATCODES[c], line); base=2)\nend\n\nseatids = BitSet(seatid.(eachline(\"a5.txt\")))\n\nmaxseatid = maximum(seatids)\n#part1\nprintln(\"$maxseatid\")\n\n#part2\nprintln(\"$(maximum(setdiff(BitSet(1:maxseatid), seatids)))\")\n", "meta": {"hexsha": "f8bfe9fda387721866f4d47e23f662259210b705", "size": 324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a5.jl", "max_stars_repo_name": "tobega/aoc2020", "max_stars_repo_head_hexsha": "ea5cecc5d77adf440b1ac35ae9f68a37d76ac2c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a5.jl", "max_issues_repo_name": "tobega/aoc2020", "max_issues_repo_head_hexsha": "ea5cecc5d77adf440b1ac35ae9f68a37d76ac2c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a5.jl", "max_forks_repo_name": "tobega/aoc2020", "max_forks_repo_head_hexsha": "ea5cecc5d77adf440b1ac35ae9f68a37d76ac2c3", "max_forks_repo_licenses": ["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": 70, "alphanum_fraction": 0.6265432099, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178870347124, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.7894315372803254}}
{"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 \u2218 UInt)(n) : (isprime \u2218 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 \u2218 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\u2218log)(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 \u2248 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\u2207u_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\u03bb1(r,s) = -(r+s)/2\n\u03bb2(r,s) = (1+r)/2\n\u03bb3(r,s) = (1+s)/2\n\u03bb(r,s) = [\u03bb1.(r,s) \u03bb2.(r,s) \u03bb3.(r,s)]\nd\u03bbr() = [-.5 .5 0.0]\nd\u03bbs() = [-.5 0.0 .5]\n\n# x,y = lists of vertices\nfunction compute_geometric_terms(x,y)\n    # dx(r,s)/dr = d\u03bb1/dr*x1 + d\u03bb2/dr*x2 + d\u03bb3/dr*x3 = [d\u03bb1/dr d\u03bb2/dr d\u03bb3/dr] * [x1; x2; x3]\n    dxdr,dydr = d\u03bbr()*x, d\u03bbr()*y\n    dxds,dyds = d\u03bbs()*x, d\u03bbs()*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\u03bbdx = drdx*d\u03bbr() + dsdx*d\u03bbs() # d\u03bbr() = [d\u03bb1/dr d\u03bb2/dr d\u03bb3/dr]\n        d\u03bbdy = drdy*d\u03bbr() + dsdy*d\u03bbs() # d\u03bbs() = [d\u03bb1/ds d\u03bb2/ds d\u03bb3/ds]\n        reference_elem_area = 2.0\n        @. A[ids,ids] += J*reference_elem_area*(d\u03bbdx'*d\u03bbdx + d\u03bbdy'*d\u03bbdy) # (d\u03bbdx'*d\u03bbdx)_ij = d\u03bbj/dx * d\u03bbi/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(\u03bb(-1/3,-1/3))*(w_mid.*f(x_mid,y_mid)) # \u03bb 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(\u03bb(r_mid,s_mid)) * w_mid * \u2207u_dot_n(x_mid,y_mid) # \u222b \u2207u\u22c5n \u03d5_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'' (\u2248 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,\u221e)),  0 => Vcat(a, Fill(0,\u221e)), 1 => Vcat([1/4], Fill(1/4,\u221e)))\n\u2113 = \u03bb -> ql(A-\u03bb*I).L[1,1]\nx,y = range(-2,2; length=200),range(-2,2;length=200)\n    z = abs.(\u2113.(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,\u221e)),  0 => Vcat(a, Fill(0,\u221e)), 1 => Vcat([1/4], Fill(1/4,\u221e)))\n\u2113 = \u03bb -> ql(A-\u03bb*I).L[1,1]\nx,y = range(-2,2; length=200),range(-2,2;length=200)\n    z = abs.(\u2113.(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,\u221e)),  0 => Vcat(a, Fill(0,\u221e)), 1 => Vcat([1/4], Fill(1/4,\u221e)))\n\u2113 = \u03bb -> ql(A-\u03bb*I).L[1,1]\nx,y = range(-2,2; length=200),range(-2,2;length=200)\n    z = abs.(\u2113.(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.(\u2113.(x.+eps()im)); label=\"abs(L[1,1])\")    \n\na = [-0.1,0.2,0.3]\nA = BandedMatrix(-2 => Vcat([1], Fill(1,\u221e)),  0 => Vcat(a, Fill(0,\u221e)), 1 => Vcat([1/4], Fill(1/4,\u221e)))\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\u2113(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": "type Dimension\n\tname::Symbol # the column name in dataframe\n\taccessor::ASCIIString #var paymentsByTotal = payments.dimension(function(d) { return d.total; });\n\tbin_width::Float64 # discretization width, NaN if unused\n\n\tDimension(name::Symbol, accessor::ASCIIString, bin_width::Float64=NaN) = new(name, accessor, bin_width)\nend\n\n\n\"\"\"\n    round_to_nearest_half_order_of_magnitude\n\nRounds a number to the nearest half order of magnitude, {...0.1,0.5,1,5,10,50,100,500...}\n\"\"\"\nfunction round_to_nearest_half_order_of_magnitude(w::Real)\n  a = round(Int, log(w)/log(10))\n  x_mid = 10.0^a\n  x_lo = x_mid*0.5\n  x_hi = 0.5*10.0^(a+1)\n  i = indmin([abs(x_mid-w), abs(x_lo-w), abs(x_hi-w)])\n  i == 1 ? x_mid : i ==2 ? x_lo : x_hi\nend\n\n\n\"\"\"\n\tinfer_dimension\n\nConstructs a Dimension suitable for the type in arr.\n\"\"\"\nfunction infer_dimension{I<:Integer}(arr::AbstractDataArray{I}, name::Symbol)\n\taccessor = @sprintf(\"function(d){return d.%s; }\", name)\n\tDimension(name, accessor)\nend\nfunction infer_dimension{F<:AbstractFloat}(arr::AbstractDataArray{F}, name::Symbol, desired_bincount::Int=10)\n\n    lo,hi = extrema(arr)\n    bin_width = round_to_nearest_half_order_of_magnitude((hi-lo)/desired_bincount)\n\n\taccessor = @sprintf(\"function(d){return Math.round(d.%s / %f)*%f; }\", name, bin_width, bin_width)\n\tDimension(name, accessor, bin_width)\nend\nfunction infer_dimension{S<:AbstractString}(arr::AbstractDataArray{S}, name::Symbol)\n\taccessor = @sprintf(\"function(d){return d.%s; }\", name)\n\tDimension(name, accessor)\nend\n\n\nBase.write(io::IO, dim::Dimension) = print(io, \"var \", dim.name, \" = cf.dimension(\", dim.accessor, \");\")\n", "meta": {"hexsha": "928387adb7b0641468adf35361fc7f19d6f55df4", "size": 1611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dimensions.jl", "max_stars_repo_name": "JuliaPackageMirrors/CrossfilterCharts.jl", "max_stars_repo_head_hexsha": "7f18b54450bf4018c32c60a5fdc6e96ba9177e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dimensions.jl", "max_issues_repo_name": "JuliaPackageMirrors/CrossfilterCharts.jl", "max_issues_repo_head_hexsha": "7f18b54450bf4018c32c60a5fdc6e96ba9177e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dimensions.jl", "max_forks_repo_name": "JuliaPackageMirrors/CrossfilterCharts.jl", "max_forks_repo_head_hexsha": "7f18b54450bf4018c32c60a5fdc6e96ba9177e9a", "max_forks_repo_licenses": ["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.8775510204, "max_line_length": 109, "alphanum_fraction": 0.713842334, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133430934989, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7892771627488949}}
{"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([\"\u30c7\u30fc\u30bf\u751f\u6210\u5206\u5e03\", \"\u4e8b\u524d\u5206\u5e03\", \"\u4e8b\u5f8c\u5206\u5e03\", \"\u8fd1\u4f3c\u5206\u5e03\", \"\u30c7\u30fc\u30bf\"], 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": "module FractionalCalculus\n\nusing QuadGK\nusing SpecialFunctions: gamma\nusing LinearAlgebra, InvertedIndices\n\ninclude(\"./Derivative/Derivative.jl\")\ninclude(\"./Integral/Integral.jl\")\n\nexport FracDiffAlg, FracIntAlg\nexport fracdiff, fracint\n\n#Export fractional derivative releating API\nexport Caputo, GL, RLDiff\nexport Caputo_Direct, Caputo_Direct_First_Diff_Known, Caputo_Direct_First_Second_Diff_Known\nexport Caputo_Piecewise\nexport Caputo_Diethelm\nexport GL_Direct\n\nexport GL_Multiplicative_Additive, GL_Lagrange_Three_Point_Interp\nexport RLDiff_Approx\nexport RLDiff_Matrix\n\n#Export fractional integral relating API\nexport RLInt\nexport RL_Direct, RL_Direct_First_Diff_Known, RL_Piecewise\nexport RLInt_Approx, RL_LinearInterp, RLInt_Matrix\nend", "meta": {"hexsha": "db6de986c3dfec412610a36006b6a9ee858908fd", "size": 741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FractionalCalculus.jl", "max_stars_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FractionalCalculus.jl", "max_issues_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FractionalCalculus.jl", "max_forks_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "max_forks_repo_licenses": ["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.4642857143, "max_line_length": 91, "alphanum_fraction": 0.8704453441, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7892709993087889}}
{"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 StatsBase\nusing Test\nusing DelimitedFiles\nusing Statistics\n\n##### Location\n\n## geomean\n\n@test geomean([1, 2, 3])    \u2248 cbrt(6.0)\n@test geomean(1:3)          \u2248 cbrt(6.0)\n@test geomean([2, 8])       \u2248 4.0\n@test geomean([4, 1, 1/32]) \u2248 0.5\n@test geomean([1, 0, 2]) == 0.0\n\n## harmmean\n\n@test harmmean([1, 2, 3]) \u2248 3 / (1 + 1/2 + 1/3)\n@test harmmean(1:3)       \u2248 3 / (1 + 1/2 + 1/3)\n@test harmmean([1, 2, 4]) \u2248 12 / 7\n\n## genmean\n@test genmean([1,1,2,3], 1)         \u2248 7/4\n@test genmean([1,4,2], -1)          \u2248 12/7\n@test genmean([1,1,2,3], 0)         \u2248 (6.0)^(1/4)\n@test genmean([1.2,-0.5,0], 2)      \u2248 sqrt(169/300)\n@test genmean([16/9,0.25,1.0], 1.5) \u2248 (755/648)^(2/3)\n# Test numerical stability for `p` close to 0 (genmean should be close to geometric mean).\n@test isapprox(genmean([1,1,2,3], -1e-8), (6.0)^(1/4), atol=1e-8)\n# Test numerical stability for large `p` (genmean should be close to max).\n@test isapprox(genmean([0.98,1.02], 1e4), 1.02, atol=1e-4)\n\n## mode & modes\n\n@test mode([1, 2, 3, 3, 2, 2, 1], 1:3) == 2\n@test modes([1, 2, 3, 3, 2, 2, 1], 1:3) == [2]\n@test modes([1, 3, 2, 3, 3, 2, 2, 1], 1:3) == [2, 3]\n\n@test mode([1, 2, 3, 3, 2, 2, 1]) == 2\n@test modes([1, 2, 3, 3, 2, 2, 1]) == [2]\n@test sort(modes([1, 3, 2, 3, 3, 2, 2, 1])) == [2, 3]\n\n@test mode(skipmissing([1, missing, missing, 3, 2, 2, missing])) == 2\n@test modes(skipmissing([1, missing, missing, 3, 2, 2, missing])) == [2]\n@test sort(modes(skipmissing([1, missing, 3, 3, 2, 2, missing]))) == [2, 3]\n\nd1 = [1, 2, 3, 3, 4, 5, 5, 3]\nd2 = ['a', 'b', 'c', 'c', 'd', 'e', 'e', 'c']\nwv = weights([0.1:0.1:0.7; 0.1])\n@test mode(d1) == 3\n@test mode(d2) == 'c'\n@test mode(d1, wv) == 5\n@test mode(d2, wv) == 'e'\n@test sort(modes(d1[1:end-1], weights(ones(7)))) == [3, 5]\n@test sort(modes(d1, weights([.9, .1, .1, .1, .9, .1, .1, .1]))) == [1, 4]\n\n@test_throws ArgumentError mode(Int[])\n@test_throws ArgumentError modes(Int[])\n@test_throws ArgumentError mode(Any[])\n@test_throws ArgumentError modes(Any[])\n@test_throws ArgumentError mode([], weights(Float64[]))\n@test_throws ArgumentError modes([], weights(Float64[]))\n@test_throws ArgumentError mode([1, 2, 3], weights([0.1, 0.3]))\n@test_throws ArgumentError modes([1, 2, 3], weights([0.1, 0.3]))\n\n## zscores\n\n@test zscore([-3:3;], 1.5, 0.5) == [-9.0:2.0:3.0;]\n\na = [3 4 5 6; 7 8 1 2; 6 9 3 0]\nz1 = [4. 6. 8. 10.; 5. 6. -1. 0.; 1.5 3.0 0.0 -1.5]\nz2 = [8. 2. 3. 1.; 24. 10. -1. -1.; 20. 12. 1. -2.]\n\n@test zscore(a, [1, 2, 3], [0.5, 1.0, 2.0])    \u2248 z1\n@test zscore(a, [1 3 2 4], [0.25 0.5 1.0 2.0]) \u2248 z2\n\n@test zscore!(collect(-3.0:3.0), 1.5, 0.5) == [-9.0:2.0:3.0;]\n@test zscore!(float(a), [1, 2, 3], [0.5, 1.0, 2.0])    \u2248 z1\n@test zscore!(float(a), [1 3 2 4], [0.25 0.5 1.0 2.0]) \u2248 z2\n\n@test zscore!(zeros(7), [-3:3;], 1.5, 0.5) == [-9.0:2.0:3.0;]\n@test zscore!(zeros(size(a)), a, [1, 2, 3], [0.5, 1.0, 2.0])    \u2248 z1\n@test zscore!(zeros(size(a)), a, [1 3 2 4], [0.25 0.5 1.0 2.0]) \u2248 z2\n\n@test zscore(a)    \u2248 zscore(a, mean(a), std(a))\n@test zscore(a, 1) \u2248 zscore(a, mean(a, dims=1), std(a, dims=1))\n@test zscore(a, 2) \u2248 zscore(a, mean(a, dims=2), std(a, dims=2))\n\n\n###### quantile & friends\n\n@test nquantile(1:5, 2) \u2248 [1, 3, 5]\n@test nquantile(1:5, 4) \u2248 [1:5;]\n@test nquantile(skipmissing([missing, 2, 5, missing]), 2) \u2248 [2.0, 3.5, 5.0]\n\n@test percentile([1:5;], 25)           \u2248  2.0\n@test percentile([1:5;], [25, 50, 75]) \u2248 [2.0, 3.0, 4.0]\n@test percentile(skipmissing([missing, 2, 5, missing]), 25) \u2248 2.75\n@test percentile(skipmissing([missing, 2, 5, missing]), [25, 50, 75]) \u2248 [2.75, 3.5, 4.25]\n\n@testset \"quantilerank and percentilerank\" begin\n     @testset \"value as number and array\" begin\n         @testset \":inc and :exc\" begin\n             v1 = [1, 1, 1, 2, 3, 4, 8, 11, 12, 13]\n             v2 = [1, 2, 3, 6, 6, 6, 7, 8, 9]\n             v3 = [1, 2, 4, 3, 4]\n             v4 = [1, 2, 1, 3, 4]\n             @test quantilerank(v1, 2, method=:inc)    == 1/3\n             @test quantilerank(v1, 4, method=:inc)    == 5/9\n             @test quantilerank(v1, 8, method=:inc)    == 2/3\n             @test quantilerank(v1, 5, method=:inc)    == 7/12        \n             @test quantilerank(v2, 7, method=:exc)    == 0.7\n             @test quantilerank(v2, 5.43, method=:exc) == 0.381\n             @test quantilerank(v3, 4, method=:exc)    == 6/9\n             @test quantilerank(v3, 4, method=:inc)    == 3/4\n             @test quantilerank(v4, 1, method=:exc)    == 1/6\n             @test quantilerank(v4, -100, method=:inc) == 0.0\n             @test quantilerank(v4,  100, method=:inc) == 1.0\n             @test quantilerank(v4, -100, method=:exc) == 0.0\n             @test quantilerank(v4,  100, method=:exc) == 1.0\n             @test percentilerank(v1, 2)               == 100 * quantilerank(v1, 2)\n             @test percentilerank(v2, 7, method=:exc)  == 100 * quantilerank(v2, 7, method=:exc)\n         end\n         @testset \":compete\" begin\n             v = [0, 0, 1, 1, 2, 2, 2, 2, 4, 4]\n             @test quantilerank(v, 1, method=:compete)    == 2/9\n             @test quantilerank(v, 2, method=:compete)    == 4/9\n             @test quantilerank(v, 4, method=:compete)    == 8/9\n             @test quantilerank(v, -100, method=:compete) == 0.0\n             @test quantilerank(v,  100, method=:compete) == 1.0\n         end\n         @testset \":strict, :weak and :tied\" begin\n             v = [7, 8, 2, 1, 3, 4, 5, 4, 6, 9]\n             for (method, res1, res2) in [(:tied, .4, [.4, .85]),\n                                          (:strict, .3, [.3, .8]),\n                                          (:weak, .5, [.5, .9])]\n                 @test quantilerank(v, 4, method=method) == res1\n             end\n         end\n     end\n     @testset \"errors\" begin\n         v1 = [1, 2, 3, 5, 6, missing, 8]\n         v2 = [missing, missing]\n         v3 = [1, 2, 3, 5, 6, NaN, 8]\n         v4 = [1, 2, 3, 3, 4]\n         for method in (:tied, :strict, :weak)\n             @test_throws ArgumentError quantilerank(v1, 4, method=method)\n             @test_throws ArgumentError quantilerank(v2, 4, method=method)\n             @test_throws ArgumentError quantilerank(v3, 4, method=method)\n         end\n         @test_throws ArgumentError quantilerank(v4, 3, method=:wrongargument)\n         @test_throws ArgumentError quantilerank(v4, NaN)\n         @test_throws ArgumentError quantilerank(v4, missing)\n         @test_throws ArgumentError quantilerank([], 3)\n         @test_throws ArgumentError quantilerank([1], 3)\n     end\n end\n \n##### Dispersion\n\n@test span([3, 4, 5, 6, 2]) == (2:6)\n@test span(skipmissing([1, missing, 5, missing])) == 1:5\n\n@test variation([1:5;]) \u2248 0.527046276694730\n@test variation(skipmissing([missing; 1:5; missing])) \u2248 0.527046276694730\n\n@test @inferred(sem([1:5;])) \u2248 0.707106781186548\n@test @inferred(sem(skipmissing([missing; 1:5; missing]))) \u2248 0.707106781186548\n@test @inferred(sem(skipmissing([missing; 1:5; missing]), mean=3.0)) \u2248 0.707106781186548\n@test @inferred(sem([1:5;], UnitWeights{Int}(5))) \u2248 0.707106781186548\n@test @inferred(sem([1:5;], UnitWeights{Int}(5); mean=mean(1:5))) \u2248 0.707106781186548\n@test_throws DimensionMismatch sem(1:5, UnitWeights{Int}(4))\n@test @inferred(sem([1:5;], ProbabilityWeights([1:5;]))) \u2248 0.6166 rtol=.001\n\u03bc = mean(1:5, ProbabilityWeights([1:5;]))\n@test @inferred(sem([1:5;], ProbabilityWeights([1:5;]); mean=\u03bc)) \u2248 0.6166 rtol=.001\n@test @inferred(sem([10; 1:5;], ProbabilityWeights([0; 1:5;]); mean=\u03bc)) \u2248 0.6166 rtol=.001\nx = sort!(vcat([5:-1:i for i in 1:5]...))\n\u03bc = mean(x)\n@test @inferred(sem([1:5;], FrequencyWeights([1:5;]))) \u2248 sem(x)\n@test @inferred(sem([1:5;], FrequencyWeights([1:5;]); mean=\u03bc)) \u2248 sem(x)\n\n@inferred sem([1:5f0;]; mean=\u03bc) \u2248 sem(x)\n@inferred sem([1:5f0;], ProbabilityWeights([1:5;]); mean=\u03bc)\n@inferred sem([1:5f0;], FrequencyWeights([1:5;]); mean=\u03bc)\n# Broken: Bug to do with Statistics.jl's implementation of `var`\n# @inferred sem([1:5f0;], UnitWeights{Int}(5); mean=\u03bc)\n\n@test @inferred(isnan(sem(Int[])))\n@test @inferred(isnan(sem(Int[], FrequencyWeights(Int[]))))\n@test @inferred(isnan(sem(Int[], ProbabilityWeights(Int[]))))\n\n@test @inferred(isnan(sem(Int[]; mean=0f0)))\n@test @inferred(isnan(sem(Int[], FrequencyWeights(Int[]); mean=0f0)))\n@test @inferred(isnan(sem(Int[], ProbabilityWeights(Int[]); mean=0f0)))\n\n@test @inferred(isnan(sem(skipmissing(Union{Int,Missing}[missing, missing]))))\n@test_throws MethodError sem(Any[])\n@test_throws MethodError sem(skipmissing([missing]))\n\n@test mad(1:5; center=3, normalize=true) \u2248 1.4826022185056018\n@test mad(skipmissing([missing; 1:5; missing]); center=3, normalize=true) \u2248 1.4826022185056018\n@test StatsBase.mad!([1:5;]; center=3, normalize=true) \u2248 1.4826022185056018\n@test mad(1:5, normalize=true) \u2248 1.4826022185056018\n@test mad(1:5, normalize=false) \u2248 1.0\n@test mad(skipmissing([missing; 1:5; missing]), normalize=true) \u2248 1.4826022185056018\n@test mad(skipmissing([missing; 1:5; missing]), normalize=false) \u2248 1.0\n@test StatsBase.mad!([1:5;], normalize=false) \u2248 1.0\n@test mad(1:5, center=3, normalize=false) \u2248 1.0\n@test mad(skipmissing([missing; 1:5; missing]), center=3, normalize=false) \u2248 1.0\n@test StatsBase.mad!([1:5;], center=3, normalize=false) \u2248 1.0\n@test mad((x for x in (1, 2.1)), normalize=false) \u2248 0.55\n@test mad(Any[1, 2.1], normalize=false) \u2248 0.55\n@test mad(Union{Int,Missing}[1, 2], normalize=false) \u2248 0.5\n@test_throws ArgumentError mad(Int[], normalize = true)\n\n# Issue 197\n@test mad(1:2, normalize=true) \u2248 0.7413011092528009\n\n@test iqr(1:5) \u2248 2.0\n\nnutrient = readdlm(joinpath(@__DIR__, \"data\", \"nutrient.txt\"))[:,2:end]\n@test @inferred(genvar(nutrient)) \u2248 2.8310418e19 rtol=1e-6\n@test @inferred(totalvar(nutrient)) \u2248 2.83266877e6 rtol=1e-6\n\nX = [1 2 5\n     4 1 6\n     4 0 4]\n@test @inferred(genvar(X)) \u2248 0.0\n@test @inferred(totalvar(X)) \u2248 5.0\n\nx = rand(Float32, 10)\n@test genvar(x) == totalvar(x) == var(x)\n\nit = (x\u1d62 for x\u1d62 in x)\n@test genvar(it) == totalvar(it) == var(it)\n\n\n##### entropy\n\n@test @inferred(entropy([0.5, 0.5]))      \u2248 0.6931471805599453\n@test @inferred(entropy([1//2, 1//2]))    \u2248 0.6931471805599453\n@test @inferred(entropy([0.5f0, 0.5f0])) isa Float32\n@test @inferred(entropy([0.2, 0.3, 0.5])) \u2248 1.0296530140645737\n@test iszero(@inferred(entropy([0, 1])))\n@test iszero(@inferred(entropy([0.0, 1.0])))\n\n@test @inferred(entropy([0.5, 0.5], 2))      \u2248 1.0\n@test @inferred(entropy([1//2, 1//2], 2))    \u2248 1.0\n@test @inferred(entropy([0.2, 0.3, 0.5], 2)) \u2248 1.4854752972273344\n\n@test_throws ArgumentError @inferred(entropy(Float64[]))\n@test_throws ArgumentError @inferred(entropy(Int[]))\n\n##### Renyi entropies\n# Generate a random probability distribution\nnindiv = 50\ndist = rand(nindiv)\ndist /= sum(dist)\n\n# Check Shannon entropy against Renyi entropy of order 1\n@test entropy(dist)         \u2248 renyientropy(dist, 1)\n@test renyientropy(dist, 1) \u2248 renyientropy(dist, 1.0)\n\n# Check Renyi entropy of order 0 is the natural log of the count of non-zeros\n@test renyientropy(dist, 0) \u2248 log(mapreduce(x -> x > 0 ? 1 : 0, +, dist))\n\n# And is therefore not affected by the addition of non-zeros\nzdist = dist\nzdist = append!(dist, zeros(50))\n@test renyientropy(dist, 0) \u2248 renyientropy(zdist, 0)\n\n# Indeed no Renyi entropy should be\nloworder = rand() # Between 0 and 1\n@test renyientropy(dist, loworder) \u2248 renyientropy(zdist, loworder)\norder = rand() * 49 + 1 # And over 1\n@test renyientropy(dist, order) \u2248 renyientropy(zdist, order)\n\n# Renyi entropy of order infinity is -log(maximum(dist))\n@test renyientropy(dist, Inf) \u2248 -log(maximum(dist))\n\n# And all Renyi entropies of uniform probabilities should be log n, where n is the length\nudist = ones(nindiv) / nindiv\n@test renyientropy(udist, order) \u2248 log(nindiv)\n\n# And test generalised probability distributions (sum(p) != 1)\nscale = rand()\n@test renyientropy(udist * scale, 0)     \u2248 renyientropy(udist, 0) - log(scale)\n@test renyientropy(udist * scale, 1)     \u2248 renyientropy(udist, 1) - log(scale)\n@test renyientropy(udist * scale, Inf)   \u2248 renyientropy(udist, Inf) - log(scale)\n@test renyientropy(udist * scale, order) \u2248 renyientropy(udist, order) - log(scale)\n\n##### Cross entropy\n@test @inferred(crossentropy([0.2, 0.3, 0.5], [0.3, 0.4, 0.3]))     \u2248 1.1176681825904018\n@test @inferred(crossentropy([1//5, 3//10, 1//2], [0.3, 0.4, 0.3])) \u2248 1.1176681825904018\n@test @inferred(crossentropy([1//5, 3//10, 1//2], [0.3f0, 0.4f0, 0.3f0])) isa Float32\n@test @inferred(crossentropy([0.2, 0.3, 0.5], [0.3, 0.4, 0.3], 2))     \u2248 1.6124543443825532\n@test @inferred(crossentropy([1//5, 3//10, 1//2], [0.3, 0.4, 0.3], 2)) \u2248 1.6124543443825532\n@test @inferred(crossentropy([1//5, 3//10, 1//2], [0.3f0, 0.4f0, 0.3f0], 2f0)) isa Float32\n\n# deprecated, should throw an `ArgumentError` at some point\nlogpattern = (:warn, \"support for empty collections will be removed since they do not represent proper probability distributions\")\n@test iszero(@test_logs logpattern @inferred(crossentropy(Float64[], Float64[])))\n@test iszero(@test_logs logpattern @inferred(crossentropy(Int[], Int[])))\n\n##### KL divergence\n@test @inferred(kldivergence([0.2, 0.3, 0.5], [0.3, 0.4, 0.3]))     \u2248 0.08801516852582819\n@test @inferred(kldivergence([1//5, 3//10, 1//2], [0.3, 0.4, 0.3])) \u2248 0.08801516852582819\n@test @inferred(kldivergence([1//5, 3//10, 1//2], [0.3f0, 0.4f0, 0.3f0])) isa Float32\n@test @inferred(kldivergence([0.2, 0.3, 0.5], [0.3, 0.4, 0.3], 2))     \u2248 0.12697904715521868\n@test @inferred(kldivergence([1//5, 3//10, 1//2], [0.3, 0.4, 0.3], 2)) \u2248 0.12697904715521868\n@test @inferred(kldivergence([1//5, 3//10, 1//2], [0.3f0, 0.4f0, 0.3f0], 2f0)) isa Float32\n@test iszero(@inferred(kldivergence([0, 1], [0f0, 1f0])))\n\n# deprecated, should throw an `ArgumentError` at some point\nlogpattern = (:warn, \"support for empty collections will be removed since they do not represent proper probability distributions\")\n@test iszero(@test_logs logpattern @inferred(kldivergence(Float64[], Float64[])))\n@test iszero(@test_logs logpattern @inferred(kldivergence(Int[], Int[])))\n\n##### summarystats\n\ns = summarystats(1:5)\n@test isa(s, StatsBase.SummaryStats)\n@test s.min == 1.0\n@test s.max == 5.0\n@test s.mean   \u2248 3.0\n@test s.median \u2248 3.0\n@test s.q25    \u2248 2.0\n@test s.q75    \u2248 4.0\n\n# Issue #631\ns = summarystats([-2, -1, 0, 1, 2, missing])\n@test isa(s, StatsBase.SummaryStats)\n@test s.min == -2.0\n@test s.max == 2.0\n@test s.mean   \u2248 0.0\n@test s.median \u2248 0.0\n@test s.q25    \u2248 -1.0\n@test s.q75    \u2248 +1.0\n\n# Issue #631\ns = summarystats(zeros(10))\n@test isa(s, StatsBase.SummaryStats)\n@test s.min == 0.0\n@test s.max == 0.0\n@test s.mean   \u2248 0.0\n@test s.median \u2248 0.0\n@test s.q25    \u2248 0.0\n@test s.q75    \u2248 0.0\n\n# Issue #631\ns = summarystats(Union{Float64,Missing}[missing, missing])\n@test isa(s, StatsBase.SummaryStats)\n@test s.nobs == 2\n@test s.nmiss == 2\n@test isnan(s.mean)\n@test isnan(s.median)\n", "meta": {"hexsha": "48c64ff0f778d80220cef96d617c5fa2b066f49c", "size": 14671, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/scalarstats.jl", "max_stars_repo_name": "kirklong/StatsBase.jl", "max_stars_repo_head_hexsha": "0ce4286c67b03d5bbfc92b57ca2154f82f70ab30", "max_stars_repo_licenses": ["MIT"], "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/scalarstats.jl", "max_issues_repo_name": "kirklong/StatsBase.jl", "max_issues_repo_head_hexsha": "0ce4286c67b03d5bbfc92b57ca2154f82f70ab30", "max_issues_repo_licenses": ["MIT"], "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/scalarstats.jl", "max_forks_repo_name": "kirklong/StatsBase.jl", "max_forks_repo_head_hexsha": "0ce4286c67b03d5bbfc92b57ca2154f82f70ab30", "max_forks_repo_licenses": ["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.0952380952, "max_line_length": 130, "alphanum_fraction": 0.6064344625, "num_tokens": 5972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535094, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7892391052172093}}
{"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\u2218solve)(dp)\n    ips =  (sort\u2218solve)(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         \u03b4 = minimum(diff(ips))/2\n         Ints =  []\n         l =  -Inf\n         for r in ips\n         if  ddex(r-\u03b4) <  0\n         push!(Ints, Interval(l,r))\n         end\n         l = r\n         end\n         if ddex(l + \u03b4) < 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\u2080; \u03b5=1e-6, maxiter=1000, \u03bb=10.0^4, \u03b1=2)\n    x = x\u2080\n    fx = f(x)\n    for i in 1:maxiter\n        g = ForwardDiff.gradient(f, x)\n        norm(g) \u2264 \u03b5 && return (x=x, converged=true, iters=i)\n        x\u2032 = x .- (ForwardDiff.hessian(f, x) + \u03bb*I) \\ g\n        fx\u2032 = f(x\u2032)\n        if fx\u2032 < fx\n            \u03bb *= 0.5\n            fx = fx\u2032\n            x = x\u2032\n        else\n            \u03bb *= 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\u2096, kInds)\n\nCreate a 'AMFMmodel' by specifiying components drawn from a Fourier Series\n  where 'T' is the fundemental period, 'a\u2096' 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\u2096(k) = 1.0\nkInds = collect(-25:25)\nz = fourierSeries(T, a\u2096, kInds)\nplot(z; timeaxis=-1.0:0.001:1.0)\n```\n\"\"\"\nfunction fourierSeries(T::Real, a\u2096::Function, kInds::Array{Int,1}=Vector(-100:100))\n  function getIA(k)\n    function a(t::Real)\n      ia = abs(a\u2096(k))\n      return ia::Real\n    end\n    return a\n  end\n  function getIF(k)\n      function \u03c9(t::Real)\n        omega = 2*\u03c0*k/T\n        return omega::Real\n      end\n    return \u03c9\n  end\n  function getPh(k)\n    ph = angle(a\u2096(k))\n    return ph\n  end\n  S = [ AMFMcomp( getIA(k), getIF(k), getPh(k) ) for k \u2208 kInds]\n  return compSet(S)\nend\n\n# CONSTRUCTIONS\nfourierSeries(T::Real, a\u2096::Function, kInds::StepRangeLen) = fourierSeries(T, a\u2096, collect(kInds))\nfourierSeries(T::Real, a\u2096::Function, kInds::UnitRange) = fourierSeries(T, a\u2096, 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": "\ninclude(\"poly_factorization_project.jl\")\nprintln(\"For this repository, a new type was made for polynomials.\")\nprintln(\"The following are tests for the different functions that can be done with this new type\")\n\n\nx = x_poly()\n@show p1 = 2x^3 + 4x^2 - 3x\n@show p2 = 2x^4 - 4x^2 - 3x + 3\n\nprintln(\"The first test is for polynomial mutliplication\")\n@show p1*p2\nprintln(\"The following is a test for polynomial power\")\n@show p1^3\n\nprintln(\"In the following 2 lines, it can be seen that the derivative function works on the polynomial class\")\nprintln(\"The first line is the derivative function on the polynomials multiplied togeher\")\nprintln(\"The second line is using the product rule\")\nd1 = derivative(p1*p2)\nd2 = derivative(p1)*p2 + p1*derivative(p2);\nprintln(\"Derivative of multiplied function: \", d1)\nprintln(\"Derivative with product rule: \", d2)\n\nprime = 17\np = mod((7x^3 + 2x^2 + 8x + 1)*(x^2+x+1),prime)\nprintln(\"Will factor this polynomial (mod $prime): \", p)\nfactorization = factor(p,prime)\nprintln(\"Here is the factorization: \", factorization)\n\npr = mod(expand_factorization(factorization),prime)\nprintln(\"Reconstructing: \", pr)\n\nprintln(\"The following is a test for polynomial addition\")\nx = x_poly()\n@show p1 = 2x^2+3x +(-5) #Note we need +(-5)... try later without... how to fix?\n@show p2 = -3x^2 - 4x +6\n@show p1+p2\n\nextended_euclid_alg(p1*p2,p2,101)", "meta": {"hexsha": "846975542a9bbc2bd9ddaf74e4e024ab06e86367", "size": 1357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example_script_2.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": "example_script_2.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": "example_script_2.jl", "max_forks_repo_name": "s4642266/2504_2021_project1", "max_forks_repo_head_hexsha": "41948baa4fc9d069980697df0b5ba8b022978699", "max_forks_repo_licenses": ["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.7948717949, "max_line_length": 110, "alphanum_fraction": 0.7243920413, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7891670619487596}}
{"text": "\"\"\"\n`SqExponentialKernel([\u03c1=1.0])`\n\nThe squared exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = exp(-\u03c1\u00b2\u2016x-y\u2016\u00b2)\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(\u03ba::SqExponentialKernel, d\u00b2::Real) = exp(-d\u00b2)\n@inline iskroncompatible(::SqExponentialKernel) = true\n\nmetric(::SqExponentialKernel) = SqEuclidean()\n\n## Aliases ##\nconst RBFKernel = SqExponentialKernel\nconst GaussianKernel = SqExponentialKernel\n\n\"\"\"\n`ExponentialKernel([\u03c1=1.0])`\nThe exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = exp(-\u03c1\u2016x-y\u2016)\n```\n\"\"\"\nstruct ExponentialKernel{Tr} <: Kernel{Tr}\n    transform::Tr\nend\n\n@inline kappa(\u03ba::ExponentialKernel, d::Real) = exp(-d)\n@inline iskroncompatible(::ExponentialKernel) = true\nmetric(::ExponentialKernel) = Euclidean()\n\n## Alias ##\nconst LaplacianKernel = ExponentialKernel\n\n\"\"\"\n`GammaExponentialKernel([\u03c1=1.0, [\u03b3=2.0]])`\nThe \u03b3-exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = exp(-\u03c1^(2\u03b3)\u2016x-y\u2016^(2\u03b3))\n```\n\"\"\"\nstruct GammaExponentialKernel{Tr, T\u03b3<:Real} <: Kernel{Tr}\n    transform::Tr\n    \u03b3::T\u03b3\n    function GammaExponentialKernel{Tr,T\u03b3}(t::Tr, \u03b3::T\u03b3) where {Tr<:Transform,T\u03b3<:Real}\n        @check_args(GammaExponentialKernel, \u03b3, \u03b3 >= zero(T\u03b3), \"\u03b3 > 0\")\n        return new{Tr, T\u03b3}(t, \u03b3)\n    end\nend\n\nparams(k::GammaExponentialKernel) = (params(transform),\u03b3)\nopt_params(k::GammaExponentialKernel) = (opt_params(transform),\u03b3)\n\nfunction GammaExponentialKernel(\u03c1::Real=1.0, \u03b3::Real=2.0)\n    GammaExponentialKernel(ScaleTransform(\u03c1), \u03b3)\nend\n\nfunction GammaExponentialKernel(\u03c1::AbstractVector{<:Real}, \u03b3::Real=2.0)\n    GammaExponentialKernel(ARDTransform(\u03c1), \u03b3)\nend\n\nfunction GammaExponentialKernel(t::Tr, \u03b3::T\u03b3=2.0) where {Tr<:Transform, T\u03b3<:Real}\n    GammaExponentialKernel{Tr, T\u03b3}(t, \u03b3)\nend\n\n@inline kappa(\u03ba::GammaExponentialKernel, d\u00b2::Real) = exp(-d\u00b2^\u03ba.\u03b3)\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\u2081) + f(x\u2082))\n```\nwhere\n```\nx\u2081 = (b - a) / 2 * sqrt(3) / 3 + (b + a) / 2\nx\u2082 = -(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\u2081 = (b + a) / 2 to begin with\n    x\u2081 = b + a\n    Arblib.mul_2exp!(x\u2081, x\u2081, -1)\n\n    # x\u2082 = (b + a) / 2 - v = x\u2081 - v\n    x\u2082 = Arblib.sub!(zero(bma), x\u2081, v)\n\n    # x\u2081 = (b + a) / 2 - v = x\u2081 - v\n    Arblib.add!(x\u2081, x\u2081, v)\n\n    # approximation = (b - a) / 2 * (f(x\u2081) + f(x\u2082))\n    approximation = f(x\u2081)\n    Arblib.add!(approximation, approximation, f(x\u2082))\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": "\nusing JuMP\nusing GLPK\n\n\nmodel_auto = Model(GLPK.Optimizer)\n@variable(model_auto, 0 <= x <= 1)\n@variable(model_auto, 0 <= y <= 1)\n@constraint(model_auto, x + y <= 1)\n@objective(model_auto, Max, x + 2y)\noptimize!(model_auto)\nobjective_value(model_auto)\n\n\nmodel_auto_no = Model()\n@variable(model_auto_no, 0 <= x <= 1)\n@variable(model_auto_no, 0 <= y <= 1)\n@constraint(model_auto_no, x + y <= 1)\n@objective(model_auto_no, Max, x + 2y)\nset_optimizer(model_auto_no, GLPK.Optimizer)\noptimize!(model_auto_no)\nobjective_value(model_auto_no)\n\n\nmodel_manual = Model(GLPK.Optimizer, caching_mode = MOIU.MANUAL)\n@variable(model_manual, 0 <= x <= 1)\n@variable(model_manual, 0 <= y <= 1)\n@constraint(model_manual, x + y <= 1)\n@objective(model_manual, Max, x + 2y)\nMOIU.attach_optimizer(model_manual)\noptimize!(model_manual)\nobjective_value(model_manual)\n\n\nmodel_direct = direct_model(GLPK.Optimizer())\n@variable(model_direct, 0 <= x <= 1)\n@variable(model_direct, 0 <= y <= 1)\n@constraint(model_direct, x + y <= 1)\n@objective(model_direct, Max, x + 2y)\noptimize!(model_direct)\nobjective_value(model_direct)\n\n\nusing Cbc\n\n\nmodel = Model(optimizer_with_attributes(Cbc.Optimizer, \"logLevel\" => 0));\n\n\nmodel = Model(optimizer_with_attributes(Cbc.Optimizer, \"max_iters\" => 10000));\n\n\nmodel = Model(optimizer_with_attributes(Cbc.Optimizer, \"seconds\" => 5));\n\n\ntermination_status(model_auto)\n\n\ndisplay(typeof(MOI.OPTIMAL))\n\n\nprimal_status(model_auto)\n\n\ndual_status(model_auto)\n\n\ndisplay(typeof(MOI.FEASIBLE_POINT))\n\n\n@show value(x)\n@show value(y)\n@show objective_value(model_auto)\n\n", "meta": {"hexsha": "ac4868d0ccb7c948eff7d4e14a092fc197b0a2b4", "size": 1559, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/introduction/solvers_and_solutions.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/solvers_and_solutions.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/solvers_and_solutions.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": 20.7866666667, "max_line_length": 78, "alphanum_fraction": 0.7389352149, "num_tokens": 437, "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": "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": "# Test for solving div-grad system both complex and real and single and multiple rhs\r\nusing MUMPSjInv\r\nusing Test\r\nusing LinearAlgebra\r\nusing SparseArrays\r\n\r\ninclude(\"getDivGrad.jl\");\r\n\r\nA = getDivGrad(32,32,16);\r\nn = size(A,1);\r\n\r\n# REAL: test for single rhs\r\nprintln(\"Test for real SPD matrix: one rhs\");\r\nrhs = randn(n);\r\n\r\nx = solveMUMPS(A,rhs,1);\r\nerr  =  norm(A*x-rhs) / norm(rhs);\r\n@test err < 1e-14\r\n\r\n# REAL: test for multiple rhs\r\nprintln(\"Test for real SPD matrix: multiple rhs\");\r\nnrhs = 10;\r\nrhs = randn(n,nrhs);\r\n\r\nx = solveMUMPS(A,rhs,1);\r\n\r\nerr = zeros(nrhs)\r\nfor i=1:nrhs\r\n        err[i] =  norm(A*x[:,i]-rhs[:,i]) / norm(rhs[:,i]);\r\nend\r\n@test eltype(x) == Float64\r\n@test maximum(err) < 1e-14\r\n\r\n# COMPLEX: test for multiple rhs\r\nprintln(\"Test for complex symmetric matrix: one rhs\");\r\nr = rand(n);\r\nA = A + im*spdiagm(0=>r);\r\n\r\nrhs = randn(n) + im*randn(n);\r\n\r\nx = solveMUMPS(A,rhs,1);\r\n\r\nerr=  norm(A*x-rhs) / norm(rhs);\r\n@test eltype(x) == ComplexF64\r\n@test err < 1e-14\r\n\r\n# COMPLEX : test for multiple rhs\r\nprintln(\"Test for complex symmetric matrix: multiple rhs\");\r\nnrhs = 10;\r\nrhs = randn(n,nrhs) + im*randn(n,nrhs);\r\n\r\nx = solveMUMPS(A,rhs,2);\r\nerr = zeros(nrhs)\r\nfor i=1:nrhs\r\n        err[i] =  norm(A*x[:,i]-rhs[:,i]) / norm(rhs[:,i]);\r\nend\r\n@test eltype(x) == ComplexF64\r\n@test maximum(err) < 1e-14\r\n\r\nprintln(\"DONE!\")\r\n\r\n", "meta": {"hexsha": "e611c11d982568bbef64eb0f96c9f362e99c7204", "size": 1351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testDivGrad.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MUMPS.jl-bf6389e2-cca1-5e17-ac22-36425c4ccbb4", "max_stars_repo_head_hexsha": "735cc81f194c220dc8305ca19897453f4ddb1c17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-02-08T09:19:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T12:41:30.000Z", "max_issues_repo_path": "test/testDivGrad.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MUMPS.jl-bf6389e2-cca1-5e17-ac22-36425c4ccbb4", "max_issues_repo_head_hexsha": "735cc81f194c220dc8305ca19897453f4ddb1c17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-01-18T15:34:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-28T03:33:09.000Z", "max_forks_repo_path": "test/testDivGrad.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MUMPS.jl-bf6389e2-cca1-5e17-ac22-36425c4ccbb4", "max_forks_repo_head_hexsha": "735cc81f194c220dc8305ca19897453f4ddb1c17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2015-02-26T22:46:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-16T09:41:42.000Z", "avg_line_length": 21.7903225806, "max_line_length": 85, "alphanum_fraction": 0.6225018505, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7891207267555973}}
{"text": "using LinearAlgebra\nusing Random\nusing ForwardDiff\nusing DataFrames\nusing GLM\n\nfunction marquardt(f, x\u2080; \u03b5=1e-6, maxiter=1000, \u03bb=10.0^4, \u03b1=2)\n    x = x\u2080\n    fx = f(x)\n    converged = false\n    i = 0\n    while i < maxiter\n        i += 1\n        \u2207f = ForwardDiff.gradient(f, x)\n        if norm(\u2207f) \u2264 \u03b5\n            converged = true\n            break\n        end\n        \u2207\u00b2f = ForwardDiff.hessian(f, x)\n        x\u2032 = x - (\u2207\u00b2f + \u03bb*I) \\ \u2207f\n        fx\u2032 = f(x\u2032)\n        if fx\u2032 < fx\n            \u03bb *= 0.5\n            fx = fx\u2032\n            x = x\u2032\n        else\n            \u03bb *= 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": "using VectorPartitions\nusing Test\n\n@testset \"VectorPartitions.jl\" begin\nusing Combinatorics\n\nfunction count_partition_iterator(n,k)\n  P = all_vector_partitions(n,k)\n  x = zeros(Int,n)\n  count = 0\n  for partition in P \n    x .= partition\n    count += 1\n  end\n  return count\nend\n\nfunction count_partitions_raw(n,k)\n  P = all_vector_partitions(n,k)\n  x = zeros(Int,n)\n  next = iterate(P)\n  count = 0\n  while next !== nothing\n      (x, state) = next\n      next = iterate(P, state)\n      count += 1\n  end\n  return count\nend\n\nfunction count_partitions_stateful(n,k)\n  P = all_vector_partitions(n,k)\n  next = iterate(P)\n  if next !== nothing\n    (_,state) = next\n  else\n    return nothing\n  end\n  count = 0\n  while !state.done\n    increment_vector_partition_state!(P,state)\n    count += 1\n  end\n  return count\nend\n\n# some spot checks that we get the right number of partitions\n@test count_partition_iterator(5,2) == stirlings2(5,2)\n@test count_partitions_raw(5,2) == stirlings2(5,2)\n@test count_partitions_stateful(5,2) == stirlings2(5,2)\n\n@test count_partition_iterator(5,3) == stirlings2(5,3)\n@test count_partitions_raw(5,3) == stirlings2(5,3)\n@test count_partitions_stateful(5,3) == stirlings2(5,3)\n\n# do we produce the right list of partitions in this case?\nthree_two_partitions = [[1,1,2],[1,2,1],[1,2,2]]\nfor (p1, p2) in zip(all_vector_partitions(3,2),three_two_partitions)\n  @test all(p1 .== p2)\nend\n\n\n# test increment_vector_partition_state!\nI = all_vector_partitions(7,3)\n_, state = iterate(I)\nstate.partition .= [1, 1, 2, 3, 3, 3, 3]\nstate.upper_bound .= [1, 1, 2, 3, 3, 3, 3] \nstate.first_index .= [1, 3, 4]\nincrement_vector_partition_state!(I,state)\n@test all(state.partition .== [1,2,1,3,1,1,1])\n@test all(state.upper_bound .== [1,2,2,3,3,3,3])\n@test all(state.first_index .== [1,2,4])\n\nincrement_vector_partition_state!(I,state)\n@test all(state.partition .== [1,2,2,3,1,1,1])\n@test all(state.upper_bound .== [1,2,2,3,3,3,3])\n@test all(state.first_index .== [1,2,4])\n\n\n# test increment_surjective_monotone_sequence!\nseq = [1, 2, 2, 3, 4]\nstep_locations = [1,2,4,5]\nstop = VectorPartitions.increment_surjective_monotone_sequence!(seq,4,step_locations)\n@test all(seq .== [1, 2, 3, 3, 4])\n@test all(step_locations .== [1,2,3,5])\n@test stop == false\n\nseq = [1,2,3,4,4]\nstep_locations = [1,2,3,4]\nstop = VectorPartitions.increment_surjective_monotone_sequence!(seq,4,step_locations)\n@test all(seq .== [1, 2, 3, 4, 4])\n@test all(step_locations .== [1,2,3,4])\n@test stop == true\n\n\nend\n", "meta": {"hexsha": "9f2648267b853ebf3cdec8b8c9a462477e3ae0b4", "size": 2484, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "hansenjakob/VectorPartitions.jl", "max_stars_repo_head_hexsha": "79bfa9699a6b8d3f758bcd25e12cd63d32a5c138", "max_stars_repo_licenses": ["MIT"], "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": "hansenjakob/VectorPartitions.jl", "max_issues_repo_head_hexsha": "79bfa9699a6b8d3f758bcd25e12cd63d32a5c138", "max_issues_repo_licenses": ["MIT"], "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": "hansenjakob/VectorPartitions.jl", "max_forks_repo_head_hexsha": "79bfa9699a6b8d3f758bcd25e12cd63d32a5c138", "max_forks_repo_licenses": ["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.6082474227, "max_line_length": 85, "alphanum_fraction": 0.690821256, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7891207198599642}}
{"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    \u03b1 = .05\n    \u03b2 = Beta(a, b)\n    CI = quantile(\u03b2, [\u03b1/2, 1-\u03b1/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 - \u6570\u5b66\u306e\u304a\u3055\u3089\u3044\n\n\n## #src\n# ## 3.1 \u7dda\u5f62\u4ee3\u6570\n# ### 3.1.1 \u30b9\u30ab\u30e9\u30fc\u3068\u30d9\u30af\u30c8\u30eb\n## \u5217\u30d9\u30af\u30c8\u30eb: 2\u884c1\u5217\u306eArray\u3092\u5b9a\u7fa9\n## Julia\u306fcolumn-major\nw = [5.0, 3.0]\n\n\n## #src\n## \u884c\u30d9\u30af\u30c8\u30eb\n#-\n## \u884c\u30d9\u30af\u30c8\u30eb: 1\u884c2\u5217\nx = [5.0 3.0]\n\n\n## #src\n#-\n## \u3059\u3079\u3066\u306e\u8981\u7d20\u304c0\u306e1\u884c5\u5217\u306eArray\u3092\u751f\u6210\nx_zeros = zeros(1, 5)\n\n\n## #src\n#-\n## \u3059\u3079\u3066\u306e\u8981\u7d20\u304c1\u306e1\u884c5\u5217\u306eArray\u3092\u751f\u6210\nx_ones = ones(1, 5)\n\n\n## #src\n#-\n## \u4e00\u69d8\u5206\u5e03\u307e\u305f\u306f\u6b63\u898f\u5206\u5e03\u306b\u3057\u305f\u304c\u3063\u3066\u30e9\u30f3\u30c0\u30e0\u306b1\u884c5\u5217\u306eArray\u3092\u751f\u6210\nusing Random\nRandom.seed!(1234)\n\n## \u4e00\u69d8\u5206\u5e03\nuniform = rand(1, 5)\n\n\n## #src\n#-\n## \u6b63\u898f\u5206\u5e03\nnormal = randn(1, 5)\n\n\n## #src\n#-\n## \u6a19\u6e96\u51fa\u529b\nfor s in (:w, :x, :x_zeros, :x_ones, :uniform, :normal)\n    y = eval(s)\n    println(\"\u30d9\u30af\u30c8\u30eb $(s)) \u5f62: $(size(y)), \u8981\u7d20\u306e\u578b:$(eltype(y))\\n$(y)\\n\")\nend\n\n\n## #src\n### 3.1.2 \u30d9\u30af\u30c8\u30eb\u306e\u5185\u7a4d\n## \u5217\u30d9\u30af\u30c8\u30eb: 2\u884c1\u5217\u306eArray\u3092\u5b9a\u7fa9\nw = [5.0, 3.0]\n\n## \u884c\u30d9\u30af\u30c8\u30eb: 1\u884c2\u5217\nx = [1.0 5.0]\n\n## \u5185\u7a4d\u306e\u8a08\u7b97\n## \\cdot\nusing LinearAlgebra\nxw = x \u22c5 w\n\n\n## #src\n#-\n## w\u306e\u30ce\u30eb\u30e0\u306e\u8a08\u7b97: w\u306e\u8ee2\u7f6e(\u884c\u30d9\u30af\u30c8\u30eb)\u3068w(\u5217\u30d9\u30af\u30c8\u30eb)\u306e\u639b\u3051\u7b97\nww = transpose(w) \u22c5 w\n\n\n## #src\n#-\n## \u30ce\u30eb\u30e0\u3092\u8a08\u7b97\u3059\u308b\u95a2\u6570\u304c\u7528\u610f\u3055\u308c\u3066\u3044\u308b\nnorm(w)\n\n\n## #src\n#-\nprintln(\"x\u3068w\u306e\u5185\u7a4d) \u5f62: $(size(xw)), \u578b:$(typeof(xw))\\n$(xw)\\n\")\nprintln(\"w\u306e\u30ce\u30eb\u30e0) \u5f62: $(size(ww)), \u578b:$(typeof(ww))\\n$(ww)\\n\")\n\n\n## #src\n# ### 3.1.5 \u884c\u5217\u3068\u30d9\u30af\u30c8\u30eb\u306e\u95a2\u4fc2\n## \u884c\u5217: 3\u884c2\u5217\u306eArray\u3092\u5b9a\u7fa9\nX = [1.0 2.0; 2.0 4.0; 3.0 6.0]\n\n\n## #src\n#-\n## 1\u884c\u76ee\u306e\u884c\u30d9\u30af\u30c8\u30eb(1\u884c2\u5217)\u306e\u53d6\u308a\u51fa\u3057\nXrow1 = X[[1], :]\n\n\n## #src\n#-\n## 2\u5217\u76ee\u306e\u5217\u30d9\u30af\u30c8\u30eb(3\u884c1\u5217)\u306e\u53d6\u308a\u51fa\u3057\nXcol2 = X[:, [2]]\n\n\n## #src\n#-\n## \u6a19\u6e96\u51fa\u529b\nprintln(\"\u884c\u5217X) \u5f62:$(size(X)), \u8981\u7d20\u306e\u578b:$(eltype(X))\\n$(X)\\n\")\nprintln(\"1\u884c\u76ee) \u5f62:$(size(Xrow1)), \u8981\u7d20\u306e\u578b:$(eltype(Xrow1))\\n$(Xrow1)\\n\")\nprintln(\"2\u5217\u76ee) \u5f62:$(size(Xcol2)), \u8981\u7d20\u306e\u578b:$(eltype(Xcol2))\\n$(Xcol2)\\n\")\n\n\n## #src\n#-\n## \u30ea\u30b9\u30c8\u306a\u3057\u306e\u5834\u5408\nX[1, :]\n\n\n## #src\n#-\n## \u30ea\u30b9\u30c8\u3042\u308a\u306e\u5834\u5408\nX[[1], :]\n\n\n## #src\n# ### 3.1.6 \u884c\u5217\u306e\u7a4d\u3068\u548c\n## \u884c\u5217 X: 3\u884c2\u5217\u306eArray\u3092\u5b9a\u7fa9\nX = [1.0 2.0; 2.0 4.0; 3.0 6.0]\n\n## \u5217\u30d9\u30af\u30c8\u30eb b: 2\u884c1\u5217\u306eArray\u3092\u5b9a\u7fa9\nw = [5.0, 3.0]\n\n## \u5217\u30d9\u30af\u30c8\u30eb b: 3\u884c1\u5217\u306eArray\u3092\u5b9a\u7fa9\nb = [1.0, 1.0, 1.0]\n\n## \u884c\u5217\u3068\u30d9\u30af\u30c8\u30eb\u306e\u7a4d\u3068\u548c\nres = X * w .+ b\nprintln(\"\u7a4d\u548c\u306e\u7d50\u679c \\n$(res)\")\n\n\n## #src\n# ### 3.1.8 \u884c\u5217\u306e\u968e\u6570\n## \u884c\u5217: 2\u884c2\u5217\u306eArray\u3092\u5b9a\u7fa9\nA = [6.0 2.0; 2.0 5.0]\nB = [6.0 3.0; 2.0 1.0]\n\n## \u884c\u5217\u306e\u30e9\u30f3\u30af\u306e\u8a08\u7b97\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(\"\u884c\u5217:\\n$(mat)\\n\u30e9\u30f3\u30af$(rank(mat))\\n\u9006\u884c\u5217:\\n$(inv(mat))\\n\")\n    else\n        println(\"\u884c\u5217:\\n$(mat)\\n\u30e9\u30f3\u30af$(rank(mat))\\n\u7279\u7570\u884c\u5217\")\n    end\nend\n\nfind_inv(A)\nfind_inv(B)\n\n\n## #src\n# ### 3.1.10 \u884c\u5217\u3068\u884c\u5217\u5f0f\u306e\u95a2\u4fc2\n## \u884c\u5217: 2\u884c2\u5217\u306eArray\u3092\u5b9a\u7fa9\nA = [6.0 2.0; 2.0 5.0]\nB = [6.0 3.0; 2.0 1.0]\n\n## \u884c\u5217\u5f0f\u306e\u8a08\u7b97\nprintln(\"\u884c\u5217A\u306e\u884c\u5217\u5f0f: $(det(A))\")\nprintln(\"\u884c\u5217B\u306e\u884c\u5217\u5f0f: $(det(B))\")\n\n\n## #src\n# ### 3.1.12 \u56fa\u6709\u5024\u554f\u984c\u306e\u89e3\u6cd5\n## \u884c\u5217A\u306e\u5b9a\u7fa9\nA = [3 2; 4 1]\n\n## \u56fa\u6709\u5024\u554f\u984c\u306e\u89e3\neig_A = eigen(A)\n\n\n## #src\n# ### 3.1.13 \u56fa\u6709\u5024\u3068\u56fa\u6709\u30d9\u30af\u30c8\u30eb\u306e\u6027\u8cea\n## \u884c\u5217A\u306e\u5b9a\u7fa9\nA = [3 1; 1 3]\n\n## \u56fa\u6709\u5024\u30fb\u56fa\u6709\u30d9\u30af\u30c8\u30eb\neig_A = eigen(A)\n\nprintln(\"\u884c\u5217A\u306e\u56fa\u6709\u5024:\\n$(eig_A.values)\")\nprintln(\"\u884c\u5217A\u306e\u56fa\u6709\u30d9\u30af\u30c8\u30eb:\\n$(eig_A.vectors)\")\nprintln(\"\u56fa\u6709\u30d9\u30af\u30c8\u30eb\u306e\u5185\u7a4d:$(eig_A.vectors[:, 1] \u22c5 eig_A.vectors[:, 2])\")\nprintln(\"\u56fa\u6709\u5024\u306e\u548c:$(sum(eig_A.values))\")\nprintln(\"\u884c\u5217A\u306e\u30c8\u30ec\u30fc\u30b9(\u5bfe\u89d2\u6210\u5206\u306e\u548c):$(tr(A))\")\nprintln(\"\u56fa\u6709\u5024\u306e\u7a4d:$(prod(eig_A.values))\")\nprintln(\"\u884c\u5217A\u306e\u884c\u5217\u5f0f:$(det(A))\")\nprintln(\"\u56fa\u6709\u30d9\u30af\u30c8\u30eb\u304c\u306a\u3059\u884c\u5217\u306e\u9006\u884c\u5217:\\n$(eig_A.vectors)\")\nprintln(\"\u56fa\u6709\u30d9\u30af\u30c8\u30eb\u304c\u306a\u3059\u884c\u5217\u306e\u8ee2\u7f6e\u884c\u5217:\\n$(eig_A.vectors')\")\n\n\n## #src\n# ## 3.2 \u6700\u9069\u5316\n## \u884c\u5217A\u306e\u5b9a\u7fa9\nA = [2 -3; 4 1]\n\n## \u5217\u30d9\u30af\u30c8\u30ebb\u306e\u5b9a\u7fa9\nb = [5, -2]\n\n\n## #src\n#-\n## \u884c\u5217\u304c\u975e\u30bc\u30ed\u304b\u5426\u304b\u3092\u78ba\u8a8d\nif det(A) != 0\n    ## A\u306e\u9006\u884c\u5217\u3068\u30d9\u30af\u30c8\u30ebb\u306e\u7a4d\u304b\u3089\u89e3\u3092\u6c42\u3081\u308b\n    w = inv(A) * b\n    println(\"w\u306e\u89e3\\n$(w)\")\nelse\n    ## \u89e3\u304c\u5b58\u5728\u3057\u306a\u3044\n    println(\"\u89e3\u304c\u5b58\u5728\u3057\u307e\u305b\u3093.\")\nend\n\n\n## #src\n#-\n# ### 3.2.2 \u5fae\u5206\u3092\u7528\u3044\u305f\u89e3\u653e\n## \u6700\u6025\u964d\u4e0b\u6cd5\u306b\u3088\u308b\u6700\u9069\u5316\n## \u5b66\u7fd2\u7387\u306e\u8a2d\u5b9a\n\u03b1 = 0.2\n\n## \u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u306e\u521d\u671f\u5316\nw = 1\n\nfor ite in 1:50\n    println(\"\u53cd\u5fa9$(ite), w=$(round(w; digits = 2))\")\n    ## \u6700\u6025\u964d\u4e0b\u6cd5\u306b\u3088\u308b\u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u306e\u66f4\u65b0\n    global w-= \u03b1 * 3 * w^2\nend\n\n\n## #src\n#-\n### 3.3.2 \u30d9\u30eb\u30cc\u30fc\u30a4\u5206\u5e03\n## p=6/13(\u9752\u8272\u306e\u30dc\u30fc\u30eb\u306e\u78ba\u7387)\u306e\u30d9\u30eb\u30cc\u30fc\u30a4\u5206\u5e03\u306b\u5f93\u3063\u306610\u56de\u8a66\u884c\u3092\u884c\u3046\nusing Distributions\n\nb = Bernoulli(6/13)\n\nX1 = rand(b, 10)\nX2 = rand(b, 10)\nX3 = rand(b, 10)\n\n## \u6a19\u6e96\u51fa\u529b\nprintln(\"\u30c7\u30fc\u30bf X1:\\n$(X1)\")\nprintln(\"\u30c7\u30fc\u30bf X2:\\n$(X2)\")\nprintln(\"\u30c7\u30fc\u30bf X3:\\n$(X3)\")\n\n\n## #src\n### 3.3.9 \u6b63\u898f\u5206\u5e03\n## \u5e73\u57470, \u5206\u65631\u306e\u6b63\u898f\u5206\u5e03\u306b\u5f93\u3063\u306610\u56de\u8a66\u884c\u3092\u884c\u3046\nX1 = rand(Normal(0, 1), 10)\n## \u5e73\u57473, \u5206\u65631\u306e\u6b63\u898f\u5206\u5e03\u306b\u5f93\u3063\u306610\u56de\u8a66\u884c\u3092\u884c\u3046\nX2 = rand(Normal(3, 1), 10)\n## \u5e73\u5747-3, \u5206\u65631\u306e\u6b63\u898f\u5206\u5e03\u306b\u5f93\u3063\u306610\u56de\u8a66\u884c\u3092\u884c\u3046\nX3 = rand(Normal(-3, 1), 10)\n\n## \u6a19\u6e96\u51fa\u529b\nprintln(\"\u30c7\u30fc\u30bf X1:\\n$(X1)\")\nprintln(\"\u30c7\u30fc\u30bf X2:\\n$(X2)\")\nprintln(\"\u30c7\u30fc\u30bf X3:\\n$(X3)\")\n\n\n## #src\n# ## 3.4 \u7d71\u8a08\n# ### 3.4.1 \u4e2d\u5fc3\u306e\u7d71\u8a08\u91cf\n## 3\u7a2e\u985e(\u8eab\u9577\u3001\u4f53\u91cd\u3001\u80f8\u56f2)\u306e\u30c7\u30fc\u30bf\u3092\u683c\u7d0d\u3059\u308b8\u884c3\u5217\u306e\u884c\u5217\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## \u884c\u65b9\u5411(dims=1)\u306b\u5bfe\u3057\u3066\u3001\u5e73\u5747\u5024\u3092\u8a08\u7b97\nmeans = mean(X; dims=1)\n\n## \u884c\u65b9\u5411(dims=1)\u306b\u5bfe\u3057\u3066\u3001\u4e2d\u592e\u5024\u3092\u8a08\u7b97\nmedians = median(X; dims=1)\n\n## \u6a19\u6e96\u51fa\u529b\nprintln(\"\u30c7\u30fc\u30bf X:\\n$X\")\nprintln(\"\u8eab\u9577\u306e\u5e73\u5747\u5024: $(means[1]), \u4f53\u91cd\u306e\u5e73\u5747\u5024:$(means[2]), \u80f8\u56f2\u306e\u5e73\u5747\u5024$(means[3])\")\nprintln(\"\u8eab\u9577\u306e\u4e2d\u592e\u5024: $(medians[1]), \u4f53\u91cd\u306e\u4e2d\u592e\u5024:$(medians[2]), \u80f8\u56f2\u306e\u4e2d\u592e\u5024$(medians[3])\")\n\n\n## src\n#-\n## \u5206\u6563\u5171\u5206\u6563\u884c\u5217\u306e\u8a08\u7b97\n## 3\u7a2e\u985e(\u8eab\u9577\u3001\u4f53\u91cd\u3001\u80f8\u56f2)\u306e\u30c7\u30fc\u30bf\u3092\u683c\u7d0d\u3059\u308b8\u884c3\u5217\u306e\u884c\u5217\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(\"\u30c7\u30fc\u30bf X:\\n$X\")\nprintln(\"\u5206\u6563) \u8eab\u9577:$(vars[1]), \u4f53\u91cd:$(vars[2]), \u80f8\u56f2:$(vars[3])\")\nprintln(\"\u6a19\u6e96\u504f\u5dee) \u8eab\u9577:$(stds[1]), \u4f53\u91cd:$(stds[2]), \u80f8\u56f2:$(stds[3])\")\nprintln(\"\u5206\u6563\u5171\u5206\u6563\u884c\u5217 \u30d0\u30a4\u30a2\u30b9\u3042\u308a:\\n$(cov_bias)\")\nprintln(\"\u5206\u6563\u5171\u5206\u6563\u884c\u5217 \u30d0\u30a4\u30a2\u30b9\u306a\u3057:\\n$(cov_nobias)\")\n\n\n## #src\n# ### 3.4.7 \u76f8\u95a2\u4fc2\u6570\u3068\u76f8\u95a2\u884c\u5217\n## 3\u7a2e\u985e(\u8eab\u9577\u3001\u4f53\u91cd\u3001\u80f8\u56f2)\u306e\u30c7\u30fc\u30bf\u3092\u683c\u7d0d\u3059\u308b8\u884c3\u5217\u306e\u884c\u5217\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(\"\u30c7\u30fc\u30bf X:\\n$X\")\nprintln(\"\u76f8\u95a2\u884c\u5217:\\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": "include(\"prime.jl\")\r\nfunction count_consecutive_primes(a::Int,b::Int)\r\n\tindex=0\r\n\twhile true\r\n\t\tn=index^2+index*a+b \r\n\t\tif !is_prime(n)\r\n\t\t\treturn index\r\n\t\tend\r\n\t\tindex+=1\r\n\tend\r\nend\r\n\r\n\r\nfunction compute()\r\n\tlen=0;\r\n\tans=0;\r\n\tfor i=-999:1000\r\n\t\tfor j=2:1000\r\n\t\t\tif( count_consecutive_primes(i,j)>len)\r\n\t\t\t\tlen=count_consecutive_primes(i,j)\r\n\t\t\t\tans=i*j \r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\treturn ans\r\n\r\nend\r\n\r\n\r\nprintln(compute())", "meta": {"hexsha": "0adc49e158f9731b4fcd21a1cbff669aec6f84a2", "size": 419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p027.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/p027.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/p027.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": 13.9666666667, "max_line_length": 49, "alphanum_fraction": 0.6276849642, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7890363688769112}}
{"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\u00b0,0) and `z` is\nthrough lat = 90\u00b0.\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\u00b0\u201390\u00b0 (-\u03c0\u2013\u03c0).  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],\"\u03f5\")\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\u03f5 = D((0,1))\n\n@show \u03f5 * \u03f5, \u03f5^2\n@show 1/(1+\u03f5)\n@show (1+\u03f5)^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), \u221b2\n@show nthroot(7,12), 7^(1/12)\nx=17.0; @show nthroot(x+\u03f5, 3), \u221bx, 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(\u03f5 * \u03f5, \u03f5 ^ 2) = (0.0 + 0.0\u03f5, 0.0 + 0.0\u03f5)\n1 / (1 + \u03f5) = 1.0 + -1.0\u03f5\n(1 + \u03f5) ^ 10 = 1.0 + 10.0\u03f5\n(nthroot(2, 3), \u221b2) = (1.2599210498948732, 1.2599210498948732)\n(nthroot(7, 12), 7 ^ (1 / 12)) = (1.1760474285795146, 1.1760474285795146)\n(nthroot(x + \u03f5, 3), \u221bx, (1 / x ^ (2 / 3)) / 3) = (2.571281590658235 + 0.05041728609133794\u03f5, 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": "using HypothesisTests\nusing Test\nusing StatsBase\nusing Statistics\nusing DelimitedFiles\n\n@testset \"Equality of Variances\" begin\n\n    # https://en.wikipedia.org/wiki/One-way_analysis_of_variance#Example\n    groups = [\n        [6, 8, 4, 5, 3, 4],\n        [8, 12, 9, 11, 6, 8],\n        [13, 9, 11, 8, 7, 12]\n    ]\n    t = OneWayANOVATest(groups...)\n    @test nobs(t) == fill(6, 3)\n    @test dof(t) == (2,15)\n    @test pvalue(t) \u2248 0.002 atol=1e-3\n    @test occursin(\"reject h_0\", sprint(show, t))\n\n    show(IOContext(IOBuffer(), :table => true), t)\n    show(IOBuffer(), t)\n\n    # http://www.real-statistics.com/one-way-analysis-of-variance-anova/confidence-interval-anova/\n    groups = [\n        [51, 87, 50, 48, 79, 61, 53],\n        [82, 91, 92, 80, 52, 79, 73, 74],\n        [79, 84, 74, 98, 63, 83, 85, 58],\n        [85, 80, 65, 71, 67, 51],\n    ]\n    t = OneWayANOVATest(groups...)\n    @test nobs(t) == [7, 8, 8, 6]\n    @test dof(t) == (3,25)\n    @test pvalue(t) \u2248 0.072 atol=1e-3\n    @test occursin(\"reject h_0\", sprint(show, t))\n\n    # http://www.real-statistics.com/one-way-analysis-of-variance-anova/homogeneity-variances/levenes-test/\n    groups = [\n        [51, 87, 50, 48, 79, 61, 53, 54],\n        [82, 91, 92, 80, 52, 79, 73, 74],\n        [79, 84, 74, 98, 63, 83, 85, 58],\n        [85, 80, 65, 71, 67, 51, 63, 93],\n    ]\n    # with means\n    l = LeveneTest(groups...; statistic=mean)\n    @test nobs(l) == fill(8, 4)\n    @test dof(l) == (3,28)\n    @test pvalue(l) \u2248 0.90357 atol=1e-4\n    # with medians\n    l = LeveneTest(groups...; statistic=median)\n    @test pvalue(l) \u2248 0.97971 atol=1e-4\n    # with 10% trimmed means\n    l = LeveneTest(groups...; statistic=v->mean(trim(v, prop=0.1)))\n    @test pvalue(l) \u2248 0.90357 atol=1e-4\n\n    # Fligner-Killeen Test\n    t = FlignerKilleenTest(groups...)\n    @test nobs(t) == fill(8, 4)\n    @test dof(t) == 3\n    @test pvalue(t) \u2248 0.9878 atol=1e-4\n    @test HypothesisTests.teststatistic(t) \u2248 0.1311 atol=1e-5\n    @test occursin(\"reject h_0\", sprint(show, t))\n\n    # https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm\n\n    # Columns are gear diameter and batch number\n    gear = readdlm(joinpath(@__DIR__, \"data\", \"gear.txt\"))\n    samples = reshape(gear[:,1],:,10)\n    groups2 = tuple((samples[:,i] for i in 1:size(samples,1))...)\n\n    # Brown-Forsythe Test\n    l = BrownForsytheTest(groups2...)\n    @test nobs(l) == fill(10, 10)\n    @test dof(l) == (9,90)\n    @test HypothesisTests.teststatistic(l) \u2248 1.705910 atol=1e-5\n    @test pvalue(l) \u2248 0.0991 atol=1e-4\n    @test occursin(\"reject h_0\", sprint(show, l))\nend\n", "meta": {"hexsha": "e58383cea879e0721516a78ed064c05bac8bfb37", "size": 2572, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/var_equality.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": "test/var_equality.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": "test/var_equality.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": 32.5569620253, "max_line_length": 107, "alphanum_fraction": 0.583592535, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7890278594924998}}
{"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\u0307 = dHdp\n    p\u0307 = - dHdq\n\n    return q\u0307, p\u0307\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\u0307 = []\nP\u0307 = []\n\nfor q \u2208 qs[1:2:end], p \u2208 ps[1:2:end]\n    q\u0307, p\u0307 = H_vec_field(q, p)\n    push!(Q, q)\n    push!(P, p)\n    push!(Q\u0307, q\u0307)\n    push!(P\u0307, p\u0307)\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\u03b1=0.1\nquiver!(p1, Q, P, quiver=(\u03b1 .* Q\u0307, \u03b1 .* P\u0307), 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\u2080=$(q0), p\u2080=$(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\u2080=$(q0), p\u2080=$(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\u03c6_train = 2\u03c0.*rand(1, Npoints)\ndata = vcat(r_train .* cos.(\u03c6_train), r_train .* sin.(\u03c6_train))\n\n\n# set up target data: here we use analytic result for time derivatives\ntarget = zero(data)\n# i.e. q\u0307= dHdp, p\u0307 = -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) \u00f7 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.\u03b1 + heads, prior_belief.\u03b2 + 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, \u03b1=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\u03f5 = 0.05\n\u03c4 = 10\n\n# Start sampling.\nchain = sample(coinflip(data), HMC(\u03f5, \u03c4), 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.\u03b1 + heads, prior_belief.\u03b2 + 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, \u03b1=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": "\"\"\"\n## glob_to_axial\n\nThis subroutine transforms the global end reactions\ninto an axial force for rod fin_els (2- or 3-d).\n\n### Function\n```julia\nglob_to_axial(glob, coord)\n```\n\n### Arguments\n```julia\n* glob::Vector{Float64}      : Globale forces and moments\n* coord::Matrix{Float64}     : Nodal coordinates\n```\n\n### REturn value\n```julia\n* ::Float64                  : Axial force\n```\n\"\"\"\nfunction glob_to_axial(glob::Vector{Float64}, coord::LinearAlgebra.Adjoint{Float64,Array{Float64,2}})\n  #\n  # This subroutine transforms the global end reactions\n  # into an axial force for rod fin_els (2- or 3-d).\n  #\n  local axial = 0.0\n  local ndim = size(coord,2)\n  local add = 0.0\n  for i in 1:ndim\n    add = add+(coord[2,i]-coord[1,i])^2\n  end\n  ell = sqrt(add)\n  for i in 1:ndim\n    axial = axial+(coord[2,i]-coord[1,i])/ell*glob[ndim+i]\n  end\n  axial\nend", "meta": {"hexsha": "e77fdf3c4711d81b7046ce3bb0ad24735c214a6e", "size": 852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PtFEM/Main/global_to_axial.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/global_to_axial.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/global_to_axial.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.8461538462, "max_line_length": 101, "alphanum_fraction": 0.6502347418, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7889985998448079}}
{"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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.4\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0b18657a-1f96-11eb-0dbe-614426f96594\n(\"Mean: $(mean(yData)), Variance: $(var(data))\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.4\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u25500b18657a-1f96-11eb-0dbe-614426f96594\n# \u2560\u25500b18a3f0-1f96-11eb-1f2b-0f12d42055fa\n# \u255f\u250070182cd8-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": "using GSL, SpecialFunctions\nusing Test, LinearAlgebra\n\n@testset \"Special functions\" begin\n\n    @testset \"bessel functions\" begin\n\n        x = rand() - 0.5 + (rand() - 0.5) * im\n\n        @test diffbessel(besselj,2,x,2) \u2248 diffbesselj(2,x,2)\n        @test diffbessel(hankelh1,2,x,2) \u2248 diffhankelh1(2,x,2)\n\n        @test diffbessel(besselj,4,x,3) \u2248 diffbesselj(4,x,3)\n        @test diffbessel(hankelh1,4,x,3) \u2248 diffhankelh1(4,x,3)\n\n        # spherical bessel functions\n        @test shankelh1(1, x) \u2248 - exp(im*x) * (x + im) / (x^2)\n        @test sbesselj(1, x) \u2248 sin(x)/x^2 - cos(x)/x\n\n        @test sbesselj(1, eps(zero(Float64))) \u2248 0.0\n        @test sbesselj(0, eps(zero(Float64))) \u2248 1.0\n\n        n = 1\n        @test 2 * diffsbessel(shankelh1,n,x) \u2248 shankelh1(n-1, x) - (shankelh1(n, x) + x*shankelh1(n+1, x))/x\n\n        @test diffsbessel(shankelh1,n,x) \u2248 diffshankelh1(n,x)\n        @test diffsbessel(sbesselj,n,x) \u2248 diffsbesselj(n,x)\n\n        n = 2\n        @test 2 * diffsbessel(shankelh1,n,x) \u2248 shankelh1(n-1, x) - (shankelh1(n, x) + x*shankelh1(n+1, x))/x\n\n        xs = 0.01:0.9:11.0;\n        n = 15; ns = 0:n\n\n        # Compare with spherical bessel from GSL, which can only accept real arguments..\n        errs = map(xs) do x\n            maximum(abs.(sf_bessel_jl_array(n,x) - [sbesselj(n,x) for n in ns]))\n        end;\n        @test maximum(errs) < 20*eps(Float64)\n\n        errs = map(xs) do x\n            maximum(\n                abs.(\n                    im .* sf_bessel_yl_array(n,x) -\n                    [shankelh1(n,x) for n in ns] +\n                    sf_bessel_jl_array(n,x)\n                ) ./ abs.(sf_bessel_yl_array(n,x))\n            )\n        end;\n        @test maximum(errs) < 1e4*eps(Float64)\n\n    end\n\n    @testset \"Associated legendre functions\" begin\n        x = rand(1)[1] * 0.99\n        l_max = 2\n\n        # a few associated legendre functions without the Condon-Shortly factor\n        Plm_arr = [1,x,sqrt(1-x^2),(3x^2-1)/2, 3x*sqrt(1-x^2),3*(1-x^2)]\n\n        ls, ms = associated_legendre_indices(l_max)\n\n        @test sf_legendre_array(GSL_SF_LEGENDRE_NONE, l_max, x)[1:length(ls)] \u2248 Plm_arr\n\n        sph_factors = (-1).^ms .* sqrt.((2 .* ls .+ 1) ./ (4pi) .* factorial.(ls-ms) ./ factorial.(ls+ms))\n\n        condon_phase = (-1).^ms\n\n        @test condon_phase .* sf_legendre_array(GSL_SF_LEGENDRE_SPHARM, l_max, x)[1:length(ls)] \u2248 sph_factors .* Plm_arr\n\n    end\n\n    @testset \"Spherical harmonics\" begin\n        \u03b8 = rand(1)[1] * 0.99\n        \u03c6 = rand(1)[1] * 0.99\n\n        l_max = 8 # small l_max due to factorial formula below\n\n        ls, ms = spherical_harmonics_indices(l_max)\n        sphs = spherical_harmonics(l_max, \u03b8, \u03c6)\n\n        @test maximum(i - lm_to_spherical_harmonic_index(ls[i],ms[i]) for i in eachindex(ls)) == 0\n\n        # check special case l == abs(m)\n        is = findall(ls .== abs.(ms))\n\n        for i in is\n            @test sphs[i] \u2248 (- sign(ms[i]))^ls[i] / (2^ls[i] * factorial(ls[i])) *\n                sqrt(factorial(2*ls[i] + 1) / (4pi)) * sin(\u03b8)^ls[i] * exp(im * ms[i] * \u03c6)\n        end\n\n        l_max = 30\n        ls, ms = spherical_harmonics_indices(l_max)\n        sphs = spherical_harmonics(l_max, \u03b8, \u03c6)\n\n        # special case m == 0, reduce to just Legendre polynomials\n        Ps = sf_legendre_Pl_array(l_max, cos(\u03b8))\n        is = findall(ms .== 0)\n\n        for l in 0:l_max\n            @test sphs[is][l+1] \u2248 sqrt((2l+1)/(4pi)) * Ps[l+1]\n        end\n\n        #sphs[inds] .\u2248 sqrt.((2 .* (0:l_max) .+ 1) ./ (4pi)) .* Ps\n\n        # special case, north pole\n        \u03b8 = 0.0\n        sphs = spherical_harmonics(l_max, \u03b8, \u03c6)\n\n        for i in eachindex(sphs)\n            if ms[i] == 0\n                @test sphs[i] \u2248 sqrt((2*ls[i] + 1)/(4pi))\n            else\n                @test sphs[i] \u2248 0.0\n            end\n            i += 1\n        end\n\n    end\n\n    @testset \"Gaunt and Wigner symbols\" begin\n        l1 = rand(1:100)\n        l2 = rand(1:100)\n        l3 = rand(abs(l1-l2):2:(l1+l2)) # guarantees that iseven(l1+l2+l3)\n\n        @test iseven(l1+l2+l3)\n\n        m1 = rand(-l1:l1)\n        m2 = rand(-l2:l2)\n        m3 = m1-m2\n\n        @test_throws(DomainError,gaunt_coefficient(l1,2*l1,l2,m2,l3,m3))\n        @test_throws(MethodError,gaunt_coefficient(l1,m1,l2,m2,0.1,m3))\n\n        # the spherical harmonics linearisation formula\n        \u03b8, \u03c6 = rand(2) .* pi\n\n        l_small = 6\n        l_max = 2*l_small # needs to be larger than l_small\n\n        ls, ms = spherical_harmonics_indices(l_max);\n        Ys = spherical_harmonics(l_max, \u03b8, \u03c6);\n\n        cs = reshape(\n            [\n                gaunt_coefficient(l1,m1,l2,m2,l3,m3)\n\n                    for l3 = 0:l_max for m3 = -l3:l3\n                for l2 = 0:l_small for m2 = -l2:l2\n            for l1 = 0:l_small for m1 = -l1:l1]\n        , ((l_small + 1)^2,(l_small + 1)^2,(l_max+1)^2));\n\n        for n2 in 1:(l_small + 1)^2, n3 in 1:(l_small + 1)^2\n            @test 4pi * (-1)^(ms[n3]+ms[n2]) * (1.0im)^(ls[n3]-ls[n2]) * Ys[n3] * conj(Ys[n2]) \u2248\n                sum( (1.0im).^(-ls) .* (-1.0).^ms .* conj.(Ys) .* cs[n2,n3,:]) atol = 1e-12\n        end\n\n    end\n\n    @testset \"complex radial coordinates\" begin\n\n    # Test 3-dimensional transforms\n        xs = [rand(-1.01:0.1:1.0,3) + rand(-1.01:0.1:1.0,3)*im for i = 1:100]\n        r\u03b8\u03c6s = cartesian_to_radial_coordinates.(xs)\n        @test maximum(norm.(xs - radial_to_cartesian_coordinates.(r\u03b8\u03c6s))) < 2e-14\n\n        xs = [rand(-1.01:0.1:1.0,3) for i = 1:100]\n        r\u03b8\u03c6s = cartesian_to_radial_coordinates.(xs)\n\n        @test maximum(r\u03b8\u03c6[2] for r\u03b8\u03c6 in r\u03b8\u03c6s) <= pi\n        @test minimum(r\u03b8\u03c6[2] for r\u03b8\u03c6 in r\u03b8\u03c6s) >= 0.0\n\n        @test pi/2 < maximum(r\u03b8\u03c6[3] for r\u03b8\u03c6 in r\u03b8\u03c6s) <= pi\n        @test -pi <= minimum(r\u03b8\u03c6[3] for r\u03b8\u03c6 in r\u03b8\u03c6s) < -pi/2\n\n    # Test 2-dimensional transforms\n        xs = [rand(-1.01:0.1:1.0,2) + rand(-1.01:0.1:1.0,2)*im for i = 1:100]\n        r\u03b8s = cartesian_to_radial_coordinates.(xs)\n\n        @test maximum(norm.(xs - radial_to_cartesian_coordinates.(r\u03b8s))) < 1e-14\n    end\nend\n", "meta": {"hexsha": "a6c03f93f2dc10c9fd3e4f60144aa0ffdcb15f4a", "size": 5959, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 32.5628415301, "max_line_length": 120, "alphanum_fraction": 0.5368350394, "num_tokens": 2178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7888442269455365}}
{"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    \u03c6_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*\u03c6_jl).*besselh.(2,r_jl)\n    Hp[diagind(Hp)] .= 0\n    Hm = exp.(-2*1im*\u03c6_jl).*besselh.(2,r_jl)\n    Hm[diagind(Hm)] .= 0\n\n    K = [H0 Hp; Hm H0]\n    K .\u2248 K_exact\nend\n\n\n\n\n#=\n        Creating matrices generically\n=#\nlet\n    N = 2\n    r = [1 2; 3 5]\n    \u03b4(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    \u03c6_jl = atan.(Dy, Dx)\n\n    H0 = besselh.(0,r_jl)\n    H2 = besselh.(2,r_jl)\n\n    A = []\n    \u03b1_range = \u03b2_range = [-1, +1]\n    for (\u03b1_idx, \u03b1) \u2208 enumerate(\u03b1_range)\n        B = []\n        for (\u03b2_idx, \u03b2) \u2208 enumerate(\u03b2_range)\n            term1 = I(N)*\u03b4(\u03b1,\u03b2)\n            term2 = ones(N, N) - I(N)\n            \n            term3 = \u03b4(\u03b1,\u03b2)*H0\n            term3[findall(isnan.(term3))] .= 0\n            term3[findall(isinf.(term3))] .= 0\n\n            term4 = (1 - \u03b4(\u03b1,\u03b2))*exp.(2*\u03b1*im*\u03c6_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(\u03b2_range)]...)  )\n    end\n\n    K = hcat(A[1:length(\u03b1_range)]...)\n    K .\u2248 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\u03b2 = [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    \u03b11 = par[1]      # growth rate of the prey population\n    \u03b21 = par[2]      # rate of shrinkage relative to the product of the population sizes\n    \u03b3 = par[3]       # shrinkage rate of the predator population\n    \u03b4 = 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 = \u03b11 .* u .- \u03b21 .* u .* v\n    F2 = - \u03b3 .* v .+ \u03b4 .* u .* v\n\n    [F1, F2]\n\nend\n\n## Solution\nt, Yapp = FDEsolver(F, tSpan, y0, \u03b2, 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": "#solve linear equation\n\n#Example1\na=float([0 4 5 2\n         1 0 2 -6;\n         4 1 0 -2;\n         1 7 1 0])::Array{Float64,2}\nb=float([9,-3, 1, -3])::Array{Float64,1}\nx=float([0, 0, 0, 0])::Array{Float64,1}\n\nfunction main(a,b,x)\n    ori_a=a\n    a=hcat(a,b)\n    row,col=size(a)\n    for j in 1:row\n        #search pivot\n        maxidx=j-1+indmax(abs.(a[j:end,j]))\n        #swap\n        a[j,:],a[maxidx,:]=a[maxidx,:],a[j,:]\n        #push foward\n        for i in j+1:row\n            p=-a[i,j]/a[j,j]\n            a[i,:]+=p*a[j,:]\n        end\n    end\n    #back foward\n    for i in row:-1:1\n        x[i]=(a[i,col]-dot(a[i,i+1:row],x[i+1:row]))/a[i,i]\n    end\n    println(\"answer=\",x)\n    println(\"check ax-b=\",ori_a*x-b)\nend \n\nmain(a,b,x)", "meta": {"hexsha": "f13777042ac9c700d9c3940910214b6ec2f9b658", "size": 732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "solveLinearEquation/gausspivot.jl", "max_stars_repo_name": "terasakisatoshi/pythonCodes", "max_stars_repo_head_hexsha": "baee095ecee96f6b5ec6431267cdc6c40512a542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solveLinearEquation/gausspivot.jl", "max_issues_repo_name": "terasakisatoshi/pythonCodes", "max_issues_repo_head_hexsha": "baee095ecee96f6b5ec6431267cdc6c40512a542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solveLinearEquation/gausspivot.jl", "max_forks_repo_name": "terasakisatoshi/pythonCodes", "max_forks_repo_head_hexsha": "baee095ecee96f6b5ec6431267cdc6c40512a542", "max_forks_repo_licenses": ["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.5294117647, "max_line_length": 59, "alphanum_fraction": 0.4754098361, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203814, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7888409463147223}}
{"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) \u223c \ud835\udca9(\u03bc, \u03c3\u00b2) ,\n```\n\nwhere ``\ud835\udca9(\u03bc, \u03c3\u00b2)`` is the `Normal` distribution with mean ``\u03bc``\nand variance ``\u03c3\u00b2``.\n\nThe `mean` and variance ``s\u00b2`` (where ``s`` is the standard\ndeviation or `std`) are related to the parameters ``\u03bc``\nand ``\u03c3\u00b2`` via\n\n```math\n m = \\\\exp(\u03bc + \u03c3\u00b2 / 2),\n```\n```math\ns\u00b2 = [\\\\exp(\u03c3\u00b2) - 1] m\u00b2.\n```\n\nThese formula allow us to calculate ``\u03bc`` and ``\u03c3`` given\n``m`` and ``s\u00b2``, since rearranging the formula for ``s\u00b2``\ngives\n\n```math\n\\\\exp(\u03c3\u00b2) = m\u00b2 / s\u00b2 + 1\n```\n\nwhich then yields\n\n```math\n\u03c3 = \\\\sqrt{\\\\log(m\u00b2 / s\u00b2 + 1)}.\n```\n\nWe then find that\n\n```math\n\u03bc = \\\\log(m) - \u03c3\u00b2 / 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    \u03c3 = sqrt(log(k))\n    \u03bc = log(mean) - \u03c3^2 / 2\n    return LogNormal(\u03bc, \u03c3)\nend\n\nstruct ScaledLogitNormal{T} <: ContinuousUnivariateDistribution\n    \u03bc :: T\n    \u03c3 :: T\n    lower_bound :: T\n    upper_bound :: T\n\n    ScaledLogitNormal{T}(\u03bc, \u03c3, L, U) where T = new{T}(T(\u03bc), T(\u03c3), 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.\u03bc, d.\u03c3)))\n\nunit_normal_std(mass) = 1 / (2 * \u221a2 * erfinv(mass))\n\n\"\"\"\n    ScaledLogitNormal([FT=Float64;] bounds=(0, 1), mass=0.5, interval=nothing, \u03bc=nothing, \u03c3=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 `\u03bc` and `\u03c3` 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 `\u03bc=0` and `\u03c3=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 \u223c \ud835\udca9(\u03bc, \u03c3)``. 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- ``\u03bc``:  mean of the underlying `Normal` distribution\n- ``\u03c3\u00b2``: variance of the underlying `Normal` distribution\n\"\"\"\nfunction ScaledLogitNormal(FT=Float64; bounds=(0, 1), mass=0.5, interval=nothing, \u03bc=nothing, \u03c3=nothing)\n    L, U = bounds\n\n    if isnothing(interval) # use default \u03bc=0 and \u03c3=1 if not set\n        isnothing(\u03bc) && (\u03bc = 0)\n        isnothing(\u03c3) && (\u03c3 = 1)\n\n    elseif !isnothing(interval) # try to compute \u03bc and \u03c3\n\n        Li, Ui = interval\n\n        # User friendliness\n        (!isnothing(\u03bc) || !isnothing(\u03c3)) && @warn \"Using interval and mass to determine \u03bc and \u03c3.\"\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\u0303i = scaled_logit_normal_to_normal(L, U, Ui)\n        U\u0303i = scaled_logit_normal_to_normal(L, U, Li)\n        \n        \u03bc = (U\u0303i + L\u0303i) / 2\n\n        # Note that the mass beneath a half-width `\u03b4` of the\n        # standard Normal distribution is\n        #\n        # mass = 2 / \u221a(2\u03c0) \u222b\u2080\u1d5f exp(-x^2 / 2) dx\n        #      = erf(\u03b4 / \u221a2)\n        #\n        # For an `interval = (U\u0303i, L\u0303i)` of the normal distribution,\n        # the non-dimensional half-width is\n        #\n        # \u03b4 = (U\u0303i - L\u0303i) / 2\u03c3\n        #\n        # where \u03c3 is the distribution's standard deviation.\n        # We then find\n        #\n        # erfinv(mass) = (U\u0303i - L\u0303i) / (2 * \u221a2 * \u03c3) ,\n        #\n        # and rearranging to solve for \u03c3 yields\n        # \n        \u03c3 = (U\u0303i - L\u0303i) / (2 * \u221a2 * erfinv(mass))\n    end\n\n    return ScaledLogitNormal{FT}(\u03bc, \u03c3, L, U)\nend\n\n# Calculate the prior in unconstrained space given a prior in constrained space\nunconstrained_prior(\u03a0::LogNormal)         = Normal(\u03a0.\u03bc / abs(\u03a0.\u03bc), \u03a0.\u03c3 / abs(\u03a0.\u03bc))\nunconstrained_prior(\u03a0::Normal)            = Normal(0, 1)\nunconstrained_prior(\u03a0::ScaledLogitNormal) = Normal(\u03a0.\u03bc, \u03a0.\u03c3)\n\n\"\"\"\n    transform_to_unconstrained(\u03a0, Y)\n\nTransform the \"constrained\" (physical) variate `Y` into it's\nunconstrained (normally-distributed) counterpart `X` through the\nforward map associated with `\u03a0`.\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 `\u03a0` of `Y`.\n\nExample\n=======\n\nThe logarithm of a `LogNormal(\u03bc, \u03c3)` distributed variate is normally-distributed,\nsuch that the forward trasform ``f \u2261 \\\\exp``,\n\n```math\nY = \\\\exp(X),\n```\n\nand the inverse trasnform is the natural logarithm ``f^{-1} \u2261 \\\\log``,\n\n```math\n\\\\log(Y) = X \u223c \ud835\udca9(\u03bc, \u03c3).\n```\n\"\"\"\ntransform_to_unconstrained(\u03a0::Normal,    Y) = (Y - \u03a0.\u03bc) / \u03a0.\u03c3\ntransform_to_unconstrained(\u03a0::LogNormal, Y) = log(Y^(1 / abs(\u03a0.\u03bc))) # log(Y) / abs(\u03a0.\u03bc)\n\ntransform_to_unconstrained(\u03a0::ScaledLogitNormal, Y) =\n    scaled_logit_normal_to_normal(\u03a0.lower_bound, \u03a0.upper_bound, Y)\n\n\"\"\"\n    transform_to_constrained(\u03a0, X)\n\nTransform an \"unconstrained\", normally-distributed variate `X`\nto \"constrained\" (physical) space via the map associated with\nthe distribution `\u03a0` of `Y`.\n\"\"\"\ntransform_to_constrained(\u03a0::Normal, X)    = X * \u03a0.\u03c3 + \u03a0.\u03bc\ntransform_to_constrained(\u03a0::LogNormal, X) = exp(X * abs(\u03a0.\u03bc))\ntransform_to_constrained(\u03a0::ScaledLogitNormal, X) =\n    normal_to_scaled_logit_normal(\u03a0.lower_bound, \u03a0.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(\u03a0, X, covariance)\n    diag = [covariance_transform_diagonal(\u03a0[i], X[i]) for i=1:length(\u03a0)]\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(\u03a0::ScaledLogitNormal, X) = - (\u03a0.upper_bound - \u03a0.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 = (\u03bd = Normal(1e-4, 1e-5), \u03ba = Normal(1e-3, 1e-5))\n(\u03bd = Normal{Float64}(\u03bc=0.0001, \u03c3=1.0e-5), \u03ba = Normal{Float64}(\u03bc=0.001, \u03c3=1.0e-5))\n\njulia> free_parameters = FreeParameters(priors)\nFreeParameters with 2 parameters\n\u251c\u2500\u2500 names: (:\u03bd, :\u03ba)\n\u251c\u2500\u2500 priors: Dict{Symbol, Any}\n\u2502   \u251c\u2500\u2500 \u03bd => Normal{Float64}(\u03bc=0.0001, \u03c3=1.0e-5)\n\u2502   \u2514\u2500\u2500 \u03ba => Normal{Float64}(\u03bc=0.001, \u03c3=1.0e-5)\n\u2514\u2500\u2500 dependent parameters: Dict{Symbol, Any}\n\njulia> c(p) = p.\u03bd + p.\u03ba # compute a third dependent parameter `c` as a function of `\u03bd` and `\u03ba`\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\u251c\u2500\u2500 names: (:\u03bd, :\u03ba)\n\u251c\u2500\u2500 priors: Dict{Symbol, Any}\n\u2502   \u251c\u2500\u2500 \u03bd => Normal{Float64}(\u03bc=0.0001, \u03c3=1.0e-5)\n\u2502   \u2514\u2500\u2500 \u03ba => Normal{Float64}(\u03bc=0.001, \u03c3=1.0e-5)\n\u2514\u2500\u2500 dependent parameters: Dict{Symbol, Any}\n    \u2514\u2500\u2500 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              \"\u251c\u2500\u2500 names: $(p.names)\", '\\n',\n              \"\u251c\u2500\u2500 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) ? \"\u2502   \u2514\u2500\u2500\" : \"\u2502   \u251c\u2500\u2500\"\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, \"\u2514\u2500\u2500 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) ? \"    \u2514\u2500\u2500\" : \"    \u251c\u2500\u2500\"\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_\u03b8)\n    if free_\u03b8 isa Dict # convert to NamedTuple with\n        free_\u03b8 = NamedTuple(name => free_\u03b8[name] for name in p.names)\n    elseif !(free_\u03b8 isa NamedTuple) # mostly likely a Vector: convert to NamedTuple with\n        free_\u03b8 = NamedTuple{p.names}(Tuple(free_\u03b8))\n    end\n\n    # Compute dependent parameters\n    dependent_names = keys(p.dependent_parameters) \n    maps = values(p.dependent_parameters)\n    dependent_\u03b8 = NamedTuple(name => maps[name](free_\u03b8) for name in dependent_names)\n\n    return merge(dependent_\u03b8, free_\u03b8) # prioritize free_\u03b8\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=\u03c0, c=2\u03c0))\nClosure(ClosureSubModel(1, \u03c0), 6.283185307179586)\n```\n\"\"\"\nconstruct_object(d::ParameterValue, parameters; name=nothing) =\n    name \u2208 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, \u03b8, 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, \u03b8, arch)\n    cpu_closures = arch_array(CPU(), closures)\n\n    for (p, \u03b8p) in enumerate(\u03b8)\n        update_closure_ensemble_member!(cpu_closures, p, \u03b8p)\n    end\n\n    return arch_array(arch, cpu_closures)\nend\nnew_closure_ensemble(closures::Tuple, \u03b8, arch) = \n    Tuple(new_closure_ensemble(closure, \u03b8, arch) for closure in closures)\n\nnew_closure_ensemble(closure, \u03b8, 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\u03c9p = 0.8\nkp,ki,C = loopshapingPI(P,\u03c9p,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\u03c9p = 2\nkp,ki,C60 = loopshapingPI(P,\u03c9p,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\u03b6 = 0.2\n\u03c9 = 1\nB = [1]\nA   = [1, 2\u03b6*\u03c9, \u03c9^2]\nP  = tf(B,A)\n# Control design\n\u03b60 = 0.7\n\u03c90 = 2\nAm = [1, 2\u03b60*\u03c90, \u03c90^2]\nAo = conv(2Am, [1/2, 1]) # Observer polynomial\nAR = [1,0] # Force the controller to contain an integrator\n\nB\u207a  = [1] # The process numerator polynomial can be facored as B = B\u207aB\u207b where B\u207b contains the zeros we do not want to cancel (non-minimum phase and poorly damped zeros)\nB\u207b  = [1]\nBm  = conv(B\u207a, B\u207b) # In this case, keep the entire numerator polynomial of the process\n\nR,S,T = rstc(B\u207a,B\u207b,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\u03b6 = 0.5 # Desired damping\nws = logspace(-1,2,8) # A vector of closed-loop bandwidths\nkp = 2*\u03b6*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, \u03c9= logspace(-2,2,500))\nPlots.savefig(plotsDir*\"/pidplotsnyquist1.svg\")\npidplots(P,:gof,;kps=kp,kis=ki, \u03c9= 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\u207a  = [1]\n#B\u207b  = [1]\n#Bm  = conv(B\u207a, B\u207b)\n#R,S,T = rstc(B\u207a,B\u207b,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\u00d7n) 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\u00d7n) 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, \u03c0, 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    \u00b5 = 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    \u03a3 = map(1:Nk) do k\n        num = zeros(size(X, 2), size(X, 2))\n        for i in 1:n\n            r = X[i,:] .- \u00b5[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(\u00b5[k], \u03a3[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\u03c0\ndomain = PeriodicIntervalDomain(a, b)\n# domain = ClosedIntervalDomain(a, b)\n\n\n## Discretization\nN = 100\nM = N\nx = discretize(domain, M)\n\u03be = discretize(domain, N)\n\u0394x = (b - a) / N\n\n\n## Filter\nh\u2080 = 2.1\u0394x\nh(x) = h\u2080 * (1 - 1 / 2 * cos(x))\ndh(x) = h\u2080 / 2 * sin(x)\n\u03b1(x) = 1 / 3 * dh(x) * h(x)\nf = TopHatFilter(h)\n\n# h\u2080 = 5.1\u0394x\n# h(x) = h\u2080 # * (1 - 1 / 2 * cos(x))\n# dh(x) = 0.0 # h\u2080 / 2 * sin(x)\n# \u03b1(x) = 1 / 3 * dh(x) * h(x)\n# f = GaussianFilter(h, \u0394x / 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(\u03b1.(\u03be))\n\n## Inspect matrices\nspy(W)\nspy(R)\n\n\n## Exact solutions\nu(\u03be, t) = sin(\u03be - t) + 3 / 5 * cos(5(\u03be - t)) + 1 / 25 * sin(20(\u03be - 1 - t))\nu_int(\u03be, t) = -cos(\u03be - t) + 3 / 25 * sin(5(\u03be - t)) - 1 / 25 / 20 * cos(20(\u03be - 1 - t))\n\u016b(x, t) = 1 / 2h(x) * (u_int(x + h(x), t) - u_int(x - h(x), t))\n\n\n## Discrete initial conditions\nu\u2095 = u.(\u03be, 0.0)\n\u016b\u2095 = \u016b.(x, 0.0)\nu\u2095_allbar = W * u\u2095\n\nplot(x, u\u2095, label = \"Discretized\")\nplot!(x, u\u0304\u2095, label = \"Filtered-then-discretized\")\nplot!(x, u\u2095_allbar, label = \"Discretized-then-filtered\")\n\n\n## Solve discretized problem\ndu\u2095(u\u2095, p, t) = -C * u\u2095\nprob = ODEProblem(du\u2095, u\u2095, (0, T))\nsol = solve(prob, Tsit5(), abstol = 1e-6, reltol = 1e-4)\n\nplot(x, u\u2095, 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\u016b\u2095(\u016b\u2095, p, t) = (-C + A * D) * \u016b\u2095\nprob_bar = ODEProblem(d\u016b\u2095, \u016b\u2095, (0, T))\nsol_bar = solve(prob_bar, Tsit5(), abstol = 1e-6, reltol = 1e-4)\n\nplot(x, u\u2095, label = \"Initial\")\nplot!(x, \u016b\u2095, label = \"Initial filtered\")\nplot!(x, sol_bar(t), label = \"Filtered-then-discretized\")\nplot!(x, \u016b.(x, t), label = \"Filtered exact\")\n# plot!(x, 500*\u03b1.(\u03be))\n\n\n## Solve discretized-and-then-filtered problem\ndu\u2095_allbar(u\u2095_allbar, p, t) = -W * (C * (R * u\u2095_allbar))\n# du\u2095_allbar(u\u2095_allbar, p, t) = -W * (C * (W \\ u\u2095_allbar))\nprob_allbar = ODEProblem(du\u2095_allbar, W * u\u2095, (0, T))\nsol_allbar = solve(prob_allbar, Tsit5(), abstol = 1e-6, reltol = 1e-4)\n\nplot(x, u\u2095, label = \"Initial\")\nplot!(x, u\u2095_allbar, label = \"Initial discretized-then-filtered\")\nplot!(x, sol_allbar(t), label = \"Discretized-then-filtered\")\nplot!(x, W * u.(\u03be, 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\u2095, label = \"\\$u(x, t = 0.0)\\$\")\n# plot!(p, x, \u016b\u2095, 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), \u016b.(x, t)], label = \"Exact\")\nplot!(p, x, u.(x, t), label = \"\\$u(x, t = $t)\\$\")\nplot!(p, x, u\u0304.(x, t), label = \"\\$u(x, t = $t)\\$\")\n# ylims!(p, minimum(u\u2095), maximum(u\u2095))\ndisplay(p)\nsavefig(p, \"output/advection/solution.tikz\")\n\n\n## Relative error\nu_exact = u.(\u03be, t)\nu\u0304_exact = \u016b.(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!(\u03be, 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\u00e9, Gabriel, and Marco Cuturi. \"Computational optimal transport: With applications to data science.\" Foundations and Trends\u00ae 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\u00e9, Gabriel. \"Entropic approximation of Wasserstein gradient flows.\" SIAM Journal on Imaging Sciences 8.4 (2015): 2323-2351.\nfunction E(\u03c1; m=1)\n    if m == 1\n        return sum(xlogx.(\u03c1)) - sum(\u03c1)\n    elseif m > 1\n        return dot(\u03c1, @. (\u03c1^(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 = \u00b1 0.5$. \n\u03c8(x) = 10 * (x - 0.5)^2 * (x + 0.5)^2;\nplot(support, \u03c8.(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\u03a8 = \u03c8.(support);\n\n# Define the time step $\\tau$ and entropic regularisation level $\\varepsilon$, and form the associated Gibbs kernel $K = e^{-C/\\varepsilon}$. \n\u03c4 = 0.05\n\u03b5 = 0.01\nK = @. exp(-C / \u03b5)\n\n# We define the (non-smooth) initial condition $\\rho_0$ in terms of step functions. \nH(x) = x > 0\n\u03c10 = @. H(support + 0.25) - H(support - 0.25)\n\u03c10 = \u03c10 / sum(\u03c10)\nplot(support, \u03c10; label=\"Initial condition \u03c10\", 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(\u03c1, \u03c10, \u03c4, \u03b5, C)\n    return sinkhorn2(\u03c1, \u03c10, C, \u03b5; regularization=true, maxiter=250) + \u03c4 * (dot(\u03a8, \u03c1) + E(\u03c1))\nend;\n\n# `step` solves the implicit step problem to produce $\\rho_{t + \\tau}$ from $\\rho_t$. \nfunction step(\u03c10, \u03c4, \u03b5, C, G)\n    ## only print error messages\n    opt = with_logger(SimpleLogger(stderr, Logging.Error)) do\n        optimize(\n            u -> G(softmax(u), \u03c10, \u03c4, \u03b5, C),\n            ones(size(\u03c10)),\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\u03c1 = similar(\u03c10, size(\u03c10, 1), N)\n\u03c1[:, 1] = \u03c10\nfor i in 2:N\n    \u03c1[:, i] = step(\u03c1[:, i - 1], \u03c4, \u03b5, C, G_fpe)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    \u03c1;\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(\u03c1, \u03c10, \u03c4, \u03b5, C)\n    return sinkhorn2(\u03c1, \u03c10, C, \u03b5; regularization=true, maxiter=250) +\n           \u03c4 * (dot(\u03a8, \u03c1) + E(\u03c1; m=2))\nend;\n\n# set up as previously \nN = 10\n\u03c1 = similar(\u03c10, size(\u03c10, 1), N)\n\u03c1[:, 1] = \u03c10\nfor i in 2:N\n    \u03c1[:, i] = step(\u03c1[:, i - 1], \u03c4, \u03b5, C, G_pme)\nend\nplot(\n    support,\n    \u03c1;\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    \u03c8 = angle(u[1])\n    # Oscillators\n    for i in 1:N\n    \tdu[i+1] = w[i] + K*r*sin(\u03c8-u[i+1])\n    end\nend\n\nfunction getparameters_kuramoto(N,K,\u03b3,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*\u03b3)/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,\u03b3,distribution)\n    tspan = (0.0,T)\n    u0 = getstartpoints_kuramoto(N)\n    p = getparameters_kuramoto(N,K,\u03b3,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": "# 2D diffusion problem\n\n# Packages and inclusions\nusing ModelingToolkit,DiffEqOperators,LinearAlgebra,Test,OrdinaryDiffEq\nusing ModelingToolkit: Differential\n\n# Tests\n@testset \"Test 00: Dt(u(t,x)) ~ Dxx(u(t,x,y)) + Dyy(u(t,x,y))\" begin\n    @parameters t x y\n    @variables u(..)\n    Dxx = Differential(x)^2\n    Dyy = Differential(y)^2\n    Dt = Differential(t)\n    t_min= 0.\n    t_max = 2.0\n    x_min = 0.\n    x_max = 2.\n    y_min = 0.\n    y_max = 2.\n\n    # 3D PDE\n    eq  = Dt(u(t,x,y)) ~ Dxx(u(t,x,y)) + Dyy(u(t,x,y))\n\n    analytic_sol_func(t,x,y) = exp(x+y)*cos(x+y+4t)\n    # Initial and boundary conditions\n    bcs = [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\n    domains = [t \u2208 IntervalDomain(t_min,t_max),\n            x \u2208 IntervalDomain(x_min,x_max),\n            y \u2208 IntervalDomain(y_min,y_max)]\n    pdesys = PDESystem([eq],bcs,domains,[t,x,y],[u(t,x,y)])\n\n    # Method of lines discretization\n    dx = 0.1; dy = 0.2\n    for order in [2,4,6]\n        discretization = MOLFiniteDifference([x=>dx,y=>dy],t;centered_order=order)\n        prob = ModelingToolkit.discretize(pdesys,discretization)\n        sol = solve(prob,Tsit5())\n\n        # Test against exact solution\n        # TODO: do this properly when sol[u] with reshape etc works\n        @test sol.u[1][1] \u2248 analytic_sol_func(sol.t[1],0.1,0.2)\n        @test sol.u[1][2] \u2248 analytic_sol_func(sol.t[1],0.2,0.2)\n\n    end\nend\n", "meta": {"hexsha": "2c7e23271b1c0bb2bd98bbe494f87ad34cdaccf2", "size": 1622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MOL/MOL_2D_Diffusion.jl", "max_stars_repo_name": "briochemc/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "max_stars_repo_licenses": ["MIT"], "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/MOL_2D_Diffusion.jl", "max_issues_repo_name": "briochemc/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "max_issues_repo_licenses": ["MIT"], "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/MOL_2D_Diffusion.jl", "max_forks_repo_name": "briochemc/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "max_forks_repo_licenses": ["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.1923076923, "max_line_length": 82, "alphanum_fraction": 0.6122071517, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870767, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7888222865665447}}
{"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": "function nlp_cvx_103_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - linear objective\n    # - intersection convex quadratic constraints\n    # Variants\n    #   010 - one binding constraint (inflection point)\n    #   011 - one binding constraint (inflection point)\n    #   012 - one binding constraint (non-inflection point)\n    #   013 - one binding constraint (non-inflection point)\n    #   014 - intersection point\n\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n\n    @objective(model, Min, y)\n    @NLconstraint(model, x^2 <= y)\n    @NLconstraint(model, -x^2 + 1 >= y)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, 0, tol = objective_tol)\n    return check_solution([x, y], [0, 0], tol = primal_tol)\nend\n", "meta": {"hexsha": "40c526f16b2aa242a2e87c28ee3629aae7d89401", "size": 957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/103_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/103_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/103_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 28.1470588235, "max_line_length": 76, "alphanum_fraction": 0.6739811912, "num_tokens": 250, "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": "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\u209c(D,N) = sum(D .^2)/N # given a triangular dist matrix\nfunction SS_W(D,N,n)\n    return  SS\u209c(D,N)/n\nend\n\nfunction F(D,W,N,n,a)\n    SST = SS\u209c(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": "function nlp_cvx_106_011(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    model = Model(optimizer)\n\n    @variable(model, -3 <= x <= 3)\n    @variable(model, -1 <= y <= 1)\n\n    @objective(model, Min, x + y)\n    @NLconstraint(model, sin(-x - 1.0) + x / 2 + 0.5 <= y)\n    @NLconstraint(model, cos(x - 0.5) + x / 4 - 0.5 >= y)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -0.7868226265935826, tol = objective_tol)\n    return check_solution(\n        [x, y],\n        [-0.5955231764562057, -0.1912994501373769],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "0c73087e75b0b2a2933125f9ee8a0a13b5f7e5d1", "size": 736, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/106_011.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/106_011.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/106_011.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 26.2857142857, "max_line_length": 76, "alphanum_fraction": 0.6317934783, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7888222742598345}}
{"text": "using Test\r\ninclude(\"Wasserstein.jl\")\r\n\r\n\r\n#\ttest Wasserstein\r\nprintln(\"\\n____________ Test Wasserstein.jl\")\r\np1= [.3, 0.7]\r\ns1= [-.7, 1.1]\r\np2= [0.2, 0.3, 0.2, 0.1, 0.2]\r\ns2= [-.3, .9, 1.7, 3.2, 1.9]\r\nd= distFunction(s1, s2)\r\n\r\n@show A= Wasserstein(p1, p2, distFunction(s1, s2), 2.)\r\n\r\n@test A.distance \u2248 0.9679876032264049\r\n@test A.\u03c0 \u2248 [0.2 0.1 0.0 0.0 0.0; 0.0 0.2 0.2 0.1 0.2]\r\n\r\nprintln()\r\n@show A= Sinkhorn(p1, p2, distFunction(s1, s2), 2., 4.3)\r\n@test A.distance \u2248 0.967988 atol= 1e-4\r\n@test A.\u03c0 \u2248 [0.2 0.1 0.0 0.0 0.0; 0.0 0.2 0.2 0.1 0.2] atol = 1e-6\r\n\r\nprintln()\r\n@show A= Sinkhorn(p1, p2, distFunction(s1, s2), 2., 1.)\r\n@test A.distance \u2248 0.9923876770989377 atol = .01\r\n@test A.\u03c0 \u2248 [0.2 0.1 0.0 0.0 0.0; 0.0 0.2 0.2 0.1 0.2] atol = 0.02\r\n", "meta": {"hexsha": "28f21ca8be41d8355d8381bef53e897347789ad3", "size": 749, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/WassersteinScript.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/WassersteinScript.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/WassersteinScript.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": 27.7407407407, "max_line_length": 67, "alphanum_fraction": 0.5834445928, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.788801831571128}}
{"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": "\"\"\"\nSolve the heat equation \u2202\u209cu = \u0394u on [0,1] using OrdinaryDiffEq for time stepping.\nBoundary conditions are such that an analytic solution is given by:\n    sin(2\u03c0*x) * exp(-(2*\u03c0)^2*t)\n\nThis example demonstrates how to solve time dependent PDE's combining `fenics` and `DiffEq`.\n\n\"\"\"\nmodule HeatEquationExample\n\nusing Test\nusing OrdinaryDiffEq\nusing FEniCS\n\nmesh = UnitIntervalMesh(50)\nV = FunctionSpace(mesh,\"P\",1)\nu_str = \"sin(2*pi*x[0]) * exp(-t*pow(2*pi, 2))\"\n\ntspan = (0.0, 0.1)\nu = interpolate(Expression(u_str, degree=2, pi=Float64(pi), t=tspan[1]), V)\n\nbc = DirichletBC(V, 0.0, \"on_boundary\")\ndudt = TrialFunction(V)\nv = TestFunction(V)\nDudt = FeFunction(V)\nF = dot(dudt, v)*dx + dot(grad(u), grad(v))*dx\na = lhs(F)\nL = rhs(F)\np = (u=u, Dudt=Dudt, bc=bc, a=a, L=L)\n\nfunction f!(dudt_vec, u_vec, p, t)\n    assign(p.u, u_vec)\n    lvsolve(p.a, p.L, p.Dudt, p.bc)\n    copy!(dudt_vec, get_array(p.Dudt))\nend\n\nu0_vec = get_array(u)\nt_final = 0.1\nprob = ODEProblem(f!, u0_vec, tspan, p)\nu_true = interpolate(Expression(u_str, degree=2, pi=Float64(pi), t=tspan[2]), V)\n\n# some algorithms to try:\n# alg = ImplicitEuler(autodiff=false)\n# alg = Rosenbrock23(autodiff=false)\n# alg = Rodas5(autodiff=false)\n\nalg = KenCarp4(autodiff=false)\nsol = OrdinaryDiffEq.solve(prob, alg, reltol=1e-6, abstol=1e-6)\n\nvec_sol = get_array(p.u)\nvec_true = get_array(u_true)\n@test vec_sol \u2248 vec_true rtol=1e-2\n\nend#module\n", "meta": {"hexsha": "ca977dc3bc71b4d3359dce02fc27e31e540cc095", "size": 1401, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/heat_equation.jl", "max_stars_repo_name": "mfkiwl/FEniCS.jl", "max_stars_repo_head_hexsha": "c949c46f723b6d16661a9f37fcb8fe51fdc1e559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2017-05-08T20:31:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-23T21:46:18.000Z", "max_issues_repo_path": "examples/heat_equation.jl", "max_issues_repo_name": "mfkiwl/FEniCS.jl", "max_issues_repo_head_hexsha": "c949c46f723b6d16661a9f37fcb8fe51fdc1e559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 65, "max_issues_repo_issues_event_min_datetime": "2017-06-14T15:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-22T11:29:33.000Z", "max_forks_repo_path": "examples/heat_equation.jl", "max_forks_repo_name": "mfkiwl/FEniCS.jl", "max_forks_repo_head_hexsha": "c949c46f723b6d16661a9f37fcb8fe51fdc1e559", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2017-04-02T18:35:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:57.000Z", "avg_line_length": 25.4727272727, "max_line_length": 92, "alphanum_fraction": 0.6895074946, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.788801828841148}}
{"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(\u03bc,\u03c9*(x-y))\ng(x) = besselj(\u03bc+\u03bd,\u03c9*x)+1/(2*x^2)*((\u03bd-1)*(\u03bd-2)*besselj(\u03bd-1,\u03c9*x)+(\u03bd+1)*(\u03bd+2)*besselj(\u03bd+1,\u03c9*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,\u03bd,\u03bc,\u03c9)\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]+\u03c9^2*Conversion(Jacobi(0,1,0..1),Jacobi(2,3,0..1))[1:n+2,1:n+2]+\u03c9*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\u03bd = 3\n\u03bc = 2\n\u03c9 = 20\nu = solveSec54(2000,g,Kfun,\u03bd,\u03bc,\u03c9)\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,\u03bd,\u03bc,\u03c9)-u),minimum(solveSec54(n,g,Kfun,\u03bd,\u03bc,\u03c9)-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\u00e9vitch, B., Le Bouquin-Jeann\u00e8s, R., & Faucon, G. (2006). Linear and\nnonlinear causality between signals: methods, examples and neurophysiological\napplications. Biological Cybernetics, 95(4), 349\u2013369.\n\"\"\"\nfunction eom_linear3d_nonlinearcoupling(x, p, n)\n    x\u2081, x\u2082, x\u2083 = (x...,)\n    a\u2081, a\u2082, a\u2083, b, c, d, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083 = (p...,)\n    \u03be\u2081 = rand(Normal(0, \u03c3\u2081))\n    \u03be\u2082 = rand(Normal(0, \u03c3\u2082))\n    \u03be\u2083 = rand(Normal(0, \u03c3\u2083))\n\n    dx\u2081 = a\u2081*x\u2081*(1-x\u2081)^2 * exp(-x\u2081^2) + 0.4*\u03be\u2081\n    dx\u2082 = a\u2082*x\u2082*(1-x\u2082)^2 * exp(-x\u2082^2) + 0.4*\u03be\u2082 + b*x\u2081*x\u2082\n    dx\u2083 = a\u2083*x\u2083*(1-x\u2083)^2 * exp(-x\u2083^2) + 0.4*\u03be\u2083 + c*x\u2082 + d*x\u2081^2\n\n    return SVector{3}(dx\u2081, dx\u2082, dx\u2083)\nend\n\n\nfunction linear3d_nonlinearcoupling(u\u1d62, a\u2081, a\u2082, a\u2083, b, c, d, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083)\n    p = [a\u2081, a\u2082, a\u2083, b, c, d, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083]\n    s = DiscreteDynamicalSystem(eom_linear3d_nonlinearcoupling, u\u1d62, p)\n    return s\nend\n\n\"\"\"\n    linear3d_nonlinearcoupling(;u\u1d62 = rand(3), \u03c3\u2081 = 1.0, \u03c3\u2082 = 1.0, \u03c3\u2083 = 1.0,\n        a\u2081 = 3.4, a\u2082 = 3.4, a\u2083 = 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\u00e9vitch, B., Le Bouquin-Jeann\u00e8s, R., & Faucon, G. (2006). Linear and\nnonlinear causality between signals: methods, examples and neurophysiological\napplications. Biological Cybernetics, 95(4), 349\u2013369.\n\"\"\"\nlinear3d_nonlinearcoupling(;u\u1d62 = rand(3), \u03c3\u2081 = 1.0, \u03c3\u2082 = 1.0, \u03c3\u2083 = 1.0,\n        a\u2081 = 3.4, a\u2082 = 3.4, a\u2083 = 3.4, b = 0.5, c = 0.3, d = 0.5) =\n    linear3d_nonlinearcoupling(u\u1d62, a\u2081, a\u2082, a\u2083, b, c, d, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083)\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, \u03c0))\n    if -one(T) \u2264 y \u2264 -one(T) + eps(T)\n        return ( 1 / two - 1 / rootpi )\n    elseif one(T) - eps(T) \u2264 y \u2264 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\u03b2 = 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, \u03b2, 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, \u03b2, 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(\u03b1, 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\u03b1 = [reshape(\u03b1,K,J-1) zeros(K)]\r\n\t\t\t\r\n\t\t\tP = exp.(X*big\u03b1) ./ sum.(eachrow(exp.(X*big\u03b1)))\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\u03b1_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(\u03b1_hat_gmm.minimizer)\r\n\r\n\ttd = TwiceDifferentiable(b -> mlogit_gmm(b, X, y), alpha_hat.minimizer; autodiff = :forward)\r\n\t\u03b1_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(\u03b1_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": "using ChaosTools\nusing ChaosTools.DynamicalSystemsBase\nusing Test\nusing StatsBase\nusing Statistics\nusing Entropies\n\ntest_value = (val, vmin, vmax) -> @test vmin <= val <= vmax\n\nprintln(\"\\nTesting generalized entropy (genentropy) & linear scaling...\")\n@testset \"Generalized Dimensions\" begin\n    @testset \"Henon Map\" begin\n        ds = Systems.henon()\n        ts = trajectory(ds, 200000)\n        es = 10 .^ range(-0, stop = -3, length = 7)\n        dd = zero(es)\n        for q in [0,2,1, 2.56]\n            for (i, ee) in enumerate(es)\n                dd[i] = genentropy(ts, ee; q)\n            end\n            linr, dim = linear_region(-log.(es), dd)\n            test_value(dim, 1.1, 1.3)\n        end\n    end\n    @testset \"Lorenz System\" begin\n        ds = Systems.lorenz()\n        ts = trajectory(ds, 5000)\n        es = 10 .^ range(1, stop = -3, length = 11)\n        dd = zero(es)\n        for q in [0,1,2]\n            for (i, ee) in enumerate(es)\n                dd[i] = genentropy(ts, ee; q)\n            end\n            linr, dim = linear_region(-log.(es), dd)\n            if q == 0\n                test_value(dim, 1.7, 1.9)\n            else\n                test_value(dim, 1.85, 2.0)\n            end\n        end\n    end\nend\n\nprintln(\"\\nTesting generalized entropy using Molteno's boxing method...\")\n@testset \"Molteno's boxing method\" begin\n    @testset \"Henon Map\" begin\n        ds = Systems.henon()\n        ts = trajectory(ds, 200000)\n        boxes, \u03f5s = molteno_boxing(ts)\n        boxes = Probabilities.(boxes)\n        for q in [0,2,1, 2.56]\n            dd = genentropy.(boxes; q)\n            linr, dim = linear_region(-log.(\u03f5s), dd)\n            test_value(dim, 1.1, 1.3)\n        end\n    end\n    @testset \"Lorenz System\" begin\n        ds = Systems.lorenz()\n        ts = trajectory(ds, 5000)\n        boxes, \u03f5s = molteno_boxing(ts)\n        boxes = Probabilities.(boxes)\n        for q in [0,2,1, 2.56]\n            dd = genentropy.(boxes; q)\n            linr, dim = linear_region(-log.(\u03f5s), dd)\n            test_value(dim, 1.85, 2.2)\n        end\n    end\nend\n\nprintln(\"\\nTesting dimension calls (all names)...\")\n@testset \"Dimension calls\" begin\n    ds = Systems.henon()\n    ts = trajectory(ds, 50000)\n    test_value(generalized_dim(ts; q = 1.32), 1.0, 1.3)\n    test_value(generalized_dim(ts; base = 2, q = 1.32), 1.0, 1.3)\nend\n", "meta": {"hexsha": "bb16fbc74d75aa01ddbd48c3db3b5a6de9ea39c9", "size": 2324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dimensions/dims.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": "test/dimensions/dims.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": "test/dimensions/dims.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": 30.1818181818, "max_line_length": 73, "alphanum_fraction": 0.5434595525, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7886859921242788}}
{"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": "#  Note:  evalVolume is tested under test_linearFFD.jl since it is needed\n#         everytime a control point is perturbed to compute the new location of\n#         the geometric point\n\n\n@testset \"--- Checking B-spline Formulation ---\" begin\n\n  U = [0,0,0,0,2/5,3/5,3/5,1,1,1,1]\n  order = 4\n  p = order - 1\n  u = 0.42\n  nctl = length(U) - order\n\n  @test ( nctl )== 7\n\n  @testset \"Checking knot span index evaluation\" begin\n    span = FFD.findSpan(u, U, order, nctl)\n    @test ( span )== 5\n  end\n\n  @testset \"Checking basis function evaluations\" begin\n    N = zeros(order)\n    span = FFD.findSpan(u, U, order, nctl)\n    FFD.basisFunctions(U, order, u, span, N)\n    @test isapprox( N[1], 0.081) atol= 1e-15\n    @test isapprox( N[2], 0.405) atol= 1e-15\n    @test isapprox( N[3], 0.5136666666666666) atol= 1e-15\n    @test isapprox( N[4], 0.00033333333333333153) atol= 1e-15\n  end\n\n  @testset \"Checking curve point evaluation\" begin\n    P = 0:1/(nctl-1):1\n    C = [0.0]\n    FFD.evalCurve([u], U, order, P, C)\n    @test isapprox( C[1], 0.40555555555555556) atol= 1e-16\n  end\n\nend  # End facts(\"--- Check Basis Function Calculations ---\")\n\n@testset \"--- Checking B-spline Derivatives ---\" begin\n\n  @testset \"Checking Basis Function Derivatives\" begin\n\n    U = [0,0,0,0,2/5,3/5,3/5,1,1,1,1]\n    order = 4\n    p = order - 1\n    u = 0.42\n    nctl = length(U) - order\n    N = zeros(AbstractFloat, order)\n    Nderiv = zeros(AbstractFloat, order)\n    span = FFD.findSpan(u, U, order, nctl)\n    FFD.derivBasisFunctions(u, U, order, span, N, Nderiv)\n\n    @test isapprox( N[1], 0.081) atol= 1e-15\n    @test isapprox( N[2], 0.405) atol= 1e-15\n    @test isapprox( N[3], 0.5136666666666666) atol= 1e-15\n    @test isapprox( N[4], 0.00033333333333333153) atol= 1e-15\n    @test isapprox( Nderiv[1], -1.3500000000000003) atol= 1e-15\n    @test isapprox( Nderiv[2], -2.25) atol= 1e-15\n    @test isapprox( Nderiv[3], 3.55) atol= 1e-15\n    @test isapprox( Nderiv[4], 0.04999999999999982) atol= 1e-15\n\n  end  # End context(\"Checking Basis Function Derivatives\")\n\nend  # End facts(\"--- Checking B-spline Derivatives ---\")\n", "meta": {"hexsha": "205630dacc03bd88232eb8b600fbf5870cc574e5", "size": 2092, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_b-splines.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": "test/test_b-splines.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": "test/test_b-splines.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": 31.696969697, "max_line_length": 79, "alphanum_fraction": 0.6343212237, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214137, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.788685987004692}}
{"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(\u03bcstar,\u03bc,\u03a3)\n\nCalculate the std and weights of a portfolio (with mean return \u03bcstar) on MVF of risky assets.\n\n# Remark\n- Only (\u03bb,\u03b4) and thus (w,stdRp) depend on \u03bcstar. We could therefore speed up the computations a bit\nby doing the loop over different \u03bcstar values inside the function (and thus not recalculate \u03a3_1,a,b,c).\n\"\"\"\nfunction MVCalc(\u03bcstar,\u03bc,\u03a3)\n    n    = length(\u03bc)\n    \u03a3_1  = inv(\u03a3)\n    a    = \u03bc'\u03a3_1*\u03bc\n    b    = \u03bc'\u03a3_1*ones(n)\n    c    = ones(n)'\u03a3_1*ones(n)\n    \u03bb    = (c*\u03bcstar - b)/(a*c-b^2)\n    \u03b4    = (a-b*\u03bcstar)/(a*c-b^2)\n    w    = \u03a3_1 *(\u03bc*\u03bb.+\u03b4)\n    StdRp = sqrt(w'\u03a3*w)\n    return StdRp,w\nend\n\n\n\"\"\"\n    MVCalcRf(\u03bcstar,\u03bc,\u03a3,Rf)\n\nCalculate the std and portfolio weights of a portfolio (with a given mean, \u03bcstar) on MVF of (risky assets,riskfree)\n\"\"\"\nfunction MVCalcRf(\u03bcstar,\u03bc,\u03a3,Rf)\n    \u03bce    = \u03bc .- Rf\n    \u03a3_1   = inv(\u03a3)\n    w     = (\u03bcstar-Rf)/(\u03bce'\u03a3_1*\u03bce) * \u03a3_1*\u03bce\n    StdRp = sqrt(w'\u03a3*w)\n    return StdRp,w                    #std and portfolio weights\nend\n\n\n\"\"\"\n    MVTangencyP(\u03bc,\u03a3,Rf)\n\nCalculate the tangency portfolio\n\"\"\"\nfunction MVTangencyP(\u03bc,\u03a3,Rf)           #calculates the tangency portfolio\n    n    = length(\u03bc)\n    \u03bce   = \u03bc .- Rf                    #expected excess returns\n    \u03a3_1  = inv(\u03a3)\n    w    = \u03a3_1 *\u03bce/(ones(n)'\u03a3_1*\u03bce)\n    muT  = w'\u03bc + (1-sum(w))*Rf\n    StdT = sqrt(w'\u03a3*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\u03c6, 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\u03c6(N) = length(Z_star(N))\n\n\"\"\"\n    continued_fraction(\u03d5, niter::Int) -> Rational\n\nobtain `s` and `r` from `\u03d5` that satisfies `|s/r - \u03d5| \u2266 1/2r\u00b2`\n\"\"\"\ncontinued_fraction(\u03d5, niter::Int) = niter==0 ? floor(Int, \u03d5) : floor(Int, \u03d5) + 1//continued_fraction(1/mod(\u03d5, 1), niter-1)\ncontinued_fraction(\u03d5::Rational, niter::Int) = niter==0 || \u03d5.den==1 ? floor(Int, \u03d5) : floor(Int, \u03d5) + 1//continued_fraction(1/mod(\u03d5, 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 \u2266 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(\u03d5, x, L) -> Int\n\nEstimate the order of `x` to `L`, `r`, from a floating point number `\u03d5 \u223c s/r` using the continued fraction method.\n\"\"\"\nfunction order_from_float(\u03d5, x, L)\n    k = 1\n    rnum = continued_fraction(\u03d5, 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(\u03d5, 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\u03f5 = 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=\u03f5) 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=\u03f5) 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=\u03f5) 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    \u039ba = A\n    \u039bb = 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, -\u03c0/4, \u03c0/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(\u039ba,\u039bb) > tol) && (n < maxiter))\n        for j=1:m-1\n            for k=j+1:m\n                (c, s) = minims_lsq(\u039ba, \u039bb, j, k)\n                \u0393 = LinearAlgebra.Givens(j, k, c, s)\n                U = U*\u0393\n                \u039ba = \u0393'*\u039ba*\u0393\n                \u039bb = \u0393'*\u039bb*\u0393\n            end\n        end\n    end\n        \n    final_cost = cost(\u039ba,\u039bb)\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(\u039ba), Diagonal(\u039bb), 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 `\u03a4` of the `table` such that:\n\n- `\u03a4[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 `\u03a3` of the `table` such that:\n\n- `\u03a3[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  \u03a3 = cov(Tables.matrix(alrtable), dims=1)\n\n  vars = Tables.columnnames(alrtable) |> collect\n  AxisArray(\u03a3, row=vars, col=vars)\nend\n\n\"\"\"\n    clrcov(table)\n\nReturn the centered log-ratio covariance matrix `\u0393` of the `table` such that:\n\n- `\u0393[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  \u0393 = cov(Tables.matrix(clrtable), dims=1)\n\n  vars = Tables.columnnames(clrtable) |> collect\n  AxisArray(\u0393, 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": "using HypothesisTests\nusing Test\nusing DelimitedFiles\nusing StatsBase\n\n@testset \"Correlation\" begin\n    # Columns are line number, calcium, iron\n    nutrient = readdlm(joinpath(@__DIR__, \"data\", \"nutrient.txt\"))[:, 1:3]\n    w = CorrelationTest(nutrient[:,2], nutrient[:,3])\n    let out = sprint(show, w)\n        @test occursin(\"reject h_0\", out) && !occursin(\"fail to\", out)\n    end\n    let ci = confint(w)\n        @test first(ci) \u2248 0.3327138 atol=1e-6\n        @test last(ci) \u2248 0.4546639 atol=1e-6\n    end\n    @test nobs(w) == 737\n    @test dof(w) == 735\n    @test pvalue(w) < 1e-25\n\n    x = CorrelationTest(nutrient[:,1], nutrient[:,2])\n    @test occursin(\"fail to reject\", sprint(show, x))\n    let ci = confint(x)\n        @test first(ci) \u2248 -0.1105478 atol=1e-6\n        @test last(ci) \u2248 0.0336730 atol=1e-6\n    end\n    @test pvalue(x) \u2248 0.2948405 atol=1e-6\nend\n\n@testset \"Partial correlation\" begin\n    # Columns are information, similarities, arithmetic, picture completion\n    wechsler = readdlm(joinpath(@__DIR__, \"data\", \"wechsler.txt\"))[:,2:end]\n    w = CorrelationTest(wechsler[:,1], wechsler[:,2], wechsler[:,3:4])\n    let out = sprint(show, w)\n        @test occursin(\"reject h_0\", out) && !occursin(\"fail to\", out)\n    end\n    let ci = confint(w)\n        @test first(ci) \u2248 0.4963917 atol=1e-6\n        @test last(ci) \u2248 0.8447292 atol=1e-6\n    end\n    @test nobs(w) == 37\n    @test dof(w) == 33\n    @test pvalue(w) < 0.00001\n\n    X = [ 2 1 0\n          4 2 0\n         15 3 1\n         20 4 1]\n    x = CorrelationTest(view(X,:,1), view(X,:,2), view(X,:,3))\n    @test occursin(\"fail to reject\", sprint(show, x))\n    @test confint(x) == (-1.0, 1.0)\n    @test nobs(x) == 4\n    @test dof(x) == 1\n    @test pvalue(x) \u2248 0.25776212 atol=1e-6\nend\n", "meta": {"hexsha": "d268637881416eeeae59c1a241628d9aba6a9501", "size": 1743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/correlation.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": "test/correlation.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": "test/correlation.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": 31.125, "max_line_length": 75, "alphanum_fraction": 0.5886402754, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7885718355636231}}
{"text": "\nusing DifferentialEquations\n\nfunction parameterized_lorenz(du,u,p,t)\n  x,y,z = u\n  \u03c3,\u03c1,\u03b2 = p\n  du[1] = dx = \u03c3*(y-x)\n  du[2] = dy = x*(\u03c1-z) - y\n  du[3] = dz = x*y - \u03b2*z\nend\n\nusing ParameterizedFunctions\ng = @ode_def begin\n  dx = \u03c3*(y-x)\n  dy = x*(\u03c1-z) - y\n  dz = x*y - \u03b2*z\nend \u03c3 \u03c1 \u03b2\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 \u03ba = 1; const tau = 2 * pi\nconst out = zeros(2) # Define a cache variable\nfunction delay_mathieu_model(du,u,h,p,t)\n  \u03b4, \u03f5, b, \u03ba = p\n  h(out, p, t-tau)\n  du[1] = - \u03ba *u[1] - (\u03b4+\u03f5*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 \u03bcm)\",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": "n = 10 #rand(1:10)\nm = n \u00f7 2 # rand(1:n)\n@test matrixdepot(\"vand\", Int, n) == matrixdepot(\"vand\", [1:n;])\n\nA = matrixdepot(\"vand\", Int, n)\n@test A[:, m] == [1:n;].^(m-1)\nprintln(\"'vand' passed test...\")\n", "meta": {"hexsha": "c1ea0278c4c5164fb24d560c0d0e74cd6a8985b5", "size": 203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_vand.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_vand.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_vand.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-02-19T22:47:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:02:00.000Z", "avg_line_length": 25.375, "max_line_length": 64, "alphanum_fraction": 0.5418719212, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7885315009339077}}
{"text": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) \u2209 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 ``\u230a log[2](n) \u230b + 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 ``\u230a log[2](n) \u230b + 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) + \u230a a(n-1)/(n-1) \u230b + 2`` for ``m \u2265 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 \u2264 k \u2264 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 \u2264 k \u2264 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 ``\u230a log[2](n) \u230b``.\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 \u2112 = prod(f)\n@show ln\u2112 = sum(log.(f)) \n@show avgln\u2112 = (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 `.\u03c6` 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    \u03c6::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 \u2209 method.fs\r\n    fs = [0, method.fs...]\r\n    \u03c7, = ls_spectral(s, t, fs)\r\n    As = abs.(\u03c7) ./ sqrt(2*length(fs))\r\n    \u03c6s = angle.(\u03c7)\r\n    method.A .= As\r\n    method.\u03c6 .= \u03c6s\r\n    x = fill(As[1], length(s))\r\n    for i in 2:length(fs)\r\n        @. x += As[i]*cos(2\u03c0*fs[i]*t + \u03c6s[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') = \u03c3\u00b2(x\u1d40x' + c)\u1d48\n```\nwith signal standard deviation ``\u03c3``, additive constant ``c``, and degree ``d``.\n\"\"\"\nmutable struct Poly{T<:Real} <: Kernel\n    \"Constant\"\n    c::T\n    \"Signal variance\"\n    \u03c32::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\u03c3::Real, deg::Int)\n\n# Arguments\n  - `lc::Real`: additive constant (given on log scale)\n  - `l\u03c3::Real`: signal standard deviation (given on log scale)\n  - `deg::Int`: degree of polynomial  \n\"\"\"\nPoly(lc::T, l\u03c3::T, deg::Int) where T = Poly{T}(exp(lc), exp(2 * l\u03c3), 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.\u03c32*(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.\u03c32) / 2]\nget_param_names(poly::Poly) = [:lc, :l\u03c3]\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.\u03c32 = exp(2 * hyp[2])\nend\n\n@inline dk_dlc(poly::Poly, xTy::Real) = poly.c*poly.deg*poly.\u03c32*(poly.c+xTy).^(poly.deg-1)\n@inline dk_dl\u03c3(poly::Poly, xTy::Real) = 2 * _cov(poly,xTy)\n@inline function dKij_d\u03b8p(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\u03c3(poly, dotij(X1, X2,i,j,dim))\n    end\nend\n@inline function dKij_d\u03b8p(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\u03c3(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\u00falio 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\u1d52 with the horizontal axis:\n\n```julia\njulia> Ellipsoidal([1.0,0.5], [\u03c0/2])\n```\n\n3D ellipsoid rotated by 45\u1d52 in the xy plane:\n\n```julia\njulia> Ellipsoidal([1.0,0.5,0.5], [\u03c0/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 \u2208 [2,3] \"dimension must be either 2 or 3\"\n\n    # scaling matrix\n    \u039b = Diagonal(one(T)./semiaxes.^2)\n\n    # rotation matrix\n    if N == 2\n      \u03b8 = angles[1]\n\n      cos\u03b8 = cos(\u03b8)\n      sin\u03b8 = sin(\u03b8)\n\n      P = [cos\u03b8 -sin\u03b8\n           sin\u03b8  cos\u03b8]\n    end\n    if N == 3\n      \u03b8xy, \u03b8yz, \u03b8zx = angles\n\n      cosxy = cos(\u03b8xy)\n      sinxy = sin(\u03b8xy)\n      cosyz = cos(\u03b8yz)\n      sinyz = sin(\u03b8yz)\n      coszx = cos(\u03b8zx)\n      sinzx = sin(\u03b8zx)\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*\u039b*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              = (\u03a3 2^di)/2\n\nThe division by 2 results from the fact the 0 is not allowed, so \u03a3 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)\u00f72] != 0\n                p[(k*k+1).\u00f72: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#   -\u0394_S(u) = f on \\Omega\n# Where \u0394_S is the spherical Laplacian defined as \u0394_S = \u2207_S\u22c5(\u2207_S(u)),\n# with \u2207_S() and  \u2207_S\u22c5 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 -\u0394_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(\u03c0*x[1])*cos(\u03c0*x[2])*exp(x[3])\nend\nfunction u\u03b8\u03d5(\u03b8\u03d5)\n  u(\u03b8\u03d52xyz(\u03b8\u03d5))\nend\nfunction f(x)\n  -(laplacian_unit_sphere(u\u03b8\u03d5)(xyz2\u03b8\u03d5(x)))\nend\nfunction Gridap.\u2207(::typeof(u))\n  gradient_unit_sphere(u\u03b8\u03d5)\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    \u03a9 = Triangulation(model)\n    d\u03a9 = Measure(\u03a9,degree)\n\n    a(u,v) = \u222b(\u2207(v)\u22c5\u2207(u))d\u03a9\n    b(v)   = \u222b(v*f)d\u03a9\n\n    op = AffineFEOperator(a,b,U,V)\n    fels = LinearFESolver(ls)\n    uh = solve(fels,op)\n\n    e=u-uh\n    \u2207e = \u2207(uh)-\u2207(u)\u2218xyz2\u03b8\u03d5\n\n    # H1-norm\n    # sqrt(sum(\u222b( e*e + (\u2207e)\u22c5(\u2207e) )d\u03a9))\n    sqrt(sum(\u222b( (\u2207e)\u22c5(\u2207e) )d\u03a9))#,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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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": "using Pkg\nPkg.activate(pwd())\n\n# # Linear regression\n# ## Loading and preparing data\n\nusing Plots\nusing StatsPlots\nusing RDatasets\n\niris = dataset(\"datasets\", \"iris\")\niris[1:5,:]\n\n# ### Exercise:\n# We will simplify the goal and estimate the dependence of petal width on petal length. # Create the data $X$ (do not forget to add the bias) and the labels $y$.\n# \n# Make a graph of the dependence of petal width on petal length.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Training the classifier\n# ### Exercise:\n# Use the closed-form formula to get the coefficients $w$ for the linear regression. Then\n# use the `optim` method derived in the previous lecture to solve the optimization problem \n# via gradient descent. The results should be identical.\n#\n#---\n#### Solution:\n\nabstract type Step end\n\nstruct GD <: Step\n    \u03b1::Real\nend\n\noptim_step(s::GD, f, g, x) = -s.\u03b1*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\n# ---\n# \n# ### Exercise:\n# Write the dependence on the petal width on the petal length. Plot it in the previous\n# graph.\n# \n# ---\n# ### Solution:\n", "meta": {"hexsha": "6d471083f43ce7e4fd886c1735483be0751f1344", "size": 1150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_09/01-linear.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_09/01-linear.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_09/01-linear.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": 19.1666666667, "max_line_length": 161, "alphanum_fraction": 0.6634782609, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.788252254356976}}
{"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    \u03f5=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]=(\u03f5+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) \u2248 testval && main(unknown_storage=:dense) \u2248 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\u03bb::T\nend\n\nfunction logpdf(lp::LogPoisson, k::Int)\n    return k * lp.log\u03bb - exp(lp.log\u03bb) - 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 \u2208 1:N\n    \u03bb = a0 + a0s[idx[i]] + a1 * x[i]\n    y[i] ~ LogPoisson(\u03bb)\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    \u03bb = 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(\u03bb))\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)(\u03b8)\n  @unpack y, x, idx, N, Ns = problem   # extract the data\n  @unpack a0, a1, a0s, a0_sig = \u03b8\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    \u03bb = a0 + a0s[idx[i]] + a1 * x[i]\n    LL += logpdf(LogPoisson(\u03bb), 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\u211d, a1=as\u211d, a0s=as(Array, Ns), a0_sig=as\u211d\u208a))\n  P = TransformedLogDensity(trans, p)\n  \u2207P = ADgradient(autodiff, P)\n  # Sample from the posterior.\n  results = mcmc_with_warmup(Random.GLOBAL_RNG, \u2207P, 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": "####################################################################################\n#               Constains activation functions and its derivatives \n####################################################################################\nexport CosineSquasher\nexport HardTanh\nexport @IndicatorFunction\nexport @LReLU\nexport RampFunction\nexport ReLU\nexport Sigmoid\nexport @ThresholdFunction\n# derivatives\nexport derivativeRampFunction\nexport derivativeReLU\n\"\"\"\nThreshold(polynomial, t)\nReturn a Threshold Function defined by `polynomial`and `t`.\nOutput in {-1,1}\n\n# Arguments\n- `polynomial`: A functions from real to real numbers\n- `t`: A real number\n\"\"\"\nmacro ThresholdFunction(polynomial, t::Real)\n    return :( f(x)=sign($(esc(polynomial))(x) - $(esc(t))) )\nend\n\n\"\"\"\n    CosineSquasher(x::Real) :: Real\nReturn activation function Cosine Squasher\n\"\"\"\nfunction CosineSquasher(x::Real) :: Real\n    salida = 1\n    if x < - pi/2 \n        salida =  0\n    elseif x <=  pi/2 \n        salida =  1/2 * (1 + cos( x - pi/2))\n    end\n    return salida\nend\n\n\"\"\"\n    IndicatorFunction(t::Real)\nReturn an indicator function giving its threshold `t`.\n\"\"\"\nmacro IndicatorFunction(t::Real)\n    return :( f(x)=(($(esc(t)) < x) ? 1 : 0 ) )\nend\n\n\"\"\"\n    RampFunction(x::Real)\nReturn Ramp  function a bounded ReLU function \n\"\"\"\nfunction RampFunction(x::Real)\n    return min(1,max(0,x))\nend\n\"\"\"\n    derivateveRampFunction(x::Real)\nReturn the derivate of the Ramp function\n\"\"\"\nfunction derivativeRampFunction(x::Real)\n    return (0<=x<=1) ? 1 : 0\nend\n\n\"\"\"\n    ReLU(x::Real)\nReLU function \n\"\"\"\nfunction ReLU(x::Real)\n    return max(0,x)\nend\n\"\"\"\n    derivativeReLU(x::Real)\nReLU function \n\"\"\"\nfunction derivativeReLU(x::Real)\n    return (x<0) ? 0 : 1\nend\n\n\"\"\"\n    Sigmoid(x::Real)\nSigmoid activation function\n\"\"\"\nfunction Sigmoid(x::Real)\n    return 1/(1+ exp(-x))\nend\n\n\"\"\"\n    HardTanh(x::Real)\nHard Hyperbolic Function \n\"\"\"\nfunction HardTanh(x::Real)\n    if x <= -1\n        return -1\n    elseif x <= 1\n        return x\n    else\n        return 1 \n    end\nend\n\n\"\"\"\n    LReLU(a::Real)\nLeaky ReLU\n\"\"\"\nmacro LReLU(a::Real)\n    return :( f(x::Real)=(x<0) ? $(esc(a))*x : x )\nend \n\n\n", "meta": {"hexsha": "1140e1490bc6e6153464cff1a24482994141ad51", "size": 2152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "OptimizedNeuralNetwork.jl/src/activation_functions.jl", "max_stars_repo_name": "BlancaCC/TFG-Estudio-de-las-redes-neuronales", "max_stars_repo_head_hexsha": "e16d039ba972c6f2fb4eeed899b3abfa6e121d07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-09T18:56:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T17:05:44.000Z", "max_issues_repo_path": "OptimizedNeuralNetwork.jl/src/activation_functions.jl", "max_issues_repo_name": "BlancaCC/TFG-Estudio-de-las-redes-neuronales", "max_issues_repo_head_hexsha": "e16d039ba972c6f2fb4eeed899b3abfa6e121d07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2021-11-27T06:47:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T17:38:01.000Z", "max_forks_repo_path": "OptimizedNeuralNetwork.jl/src/activation_functions.jl", "max_forks_repo_name": "BlancaCC/TFG-Estudio-de-las-redes-neuronales", "max_forks_repo_head_hexsha": "e16d039ba972c6f2fb4eeed899b3abfa6e121d07", "max_forks_repo_licenses": ["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.3873873874, "max_line_length": 84, "alphanum_fraction": 0.5906133829, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7881949192964858}}
{"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": "using Random, Distributions, StatsPlots; pyplot()\nRandom.seed!(0)\n\nmu1, sigma1 = 10, 5\nmu2, sigma2 = 40, 12\ndist1, dist2 = Normal(mu1,sigma1), Normal(mu2,sigma2)\np = 0.3\nmixRv() = (rand() <= p) ? rand(dist1) : rand(dist2)\n\nn = 2000\ndata = [mixRv() for _ in 1:n]\n\ndensity(data, c=:blue, label=\"Density via StatsPlots\", \n        xlims=(-20,80), ylims=(0,0.035))\nstephist!(data, bins=50, c=:black, norm=true, \n    label=\"Histogram\", xlabel=\"x\", ylabel = \"Density\")", "meta": {"hexsha": "12ae000a378c5a90e803de8ece61a1bf17396781", "size": 461, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4_chapter/statsPlotsDensity.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": "4_chapter/statsPlotsDensity.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": "4_chapter/statsPlotsDensity.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.8125, "max_line_length": 55, "alphanum_fraction": 0.6399132321, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7881949137810313}}
{"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": "using Test\nusing LinearAlgebra\nusing NonNegLeastSquares\nusing PyCall\n\n# wrapper functions for convienence\nnnls(A,b) = nonneg_lsq(A,b;alg=:nnls)\npivot(A,b) = nonneg_lsq(A,b;alg=:pivot)\n\n# Solve A*x = b for x, subject to x >=0\nA = [ 0.53879488  0.65816267\n      0.12873446  0.98669198\n      0.24555042  0.00598804\n      0.80491791  0.32793762 ]\n\nb = [0.888,  0.562,  0.255,  0.077]\n\n# Test that nnls produces the same solution as scipy\nx = [0.15512102, 0.69328985] # approx solution from scipy\n@test norm(pivot(A,b)-x) < 1e-5\n\n\n## A second test case\nA2 = [ -0.24  -0.82   1.35   0.36   0.35\n       -0.53  -0.20  -0.76   0.98  -0.54\n        0.22   1.25  -1.60  -1.37  -1.94\n       -0.51  -0.56  -0.08   0.96   0.46\n        0.48  -2.25   0.38   0.06  -1.29 ]\nb2 = [-1.6,  0.19,  0.17,  0.31, -1.27]\nx2 = [2.2010416, 1.19009924, 0.0, 1.55001345, 0.0]\n@test norm(pivot(A2,b2)-x2) < 1e-5\n\n## Test a bunch of random cases against python\n\nfor i = 1:100\n  \tm,n = rand(1:10),rand(1:10)\n  \tA3 = randn(m,n)\n  \tb3 = randn(m)\n  \tx3,resid = pyopt.nnls(A3,b3)\n    resid = norm(b3-A3*pivot(A3,b3))\n    if resid > 1e-5\n        @test norm(pivot(A3,b3)-x3) < 1e-5\n    end\nend\n\n## Test a bunch of random cases against nnls\nfor i = 1:100\n    m,n = rand(1:10),rand(1:10)\n    A4 = randn(m,n)\n    b4 = randn(m)\n    x4 = nnls(A4,b4)\n    resid = norm(b4-A4*pivot(A4,b4))\n    if resid > 1e-5\n        @test norm(pivot(A4,b4)-x4) < 1e-5\n    end\nend\n", "meta": {"hexsha": "7b29025207a519702881d3b39f024cb556163f87", "size": 1418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pivot_test.jl", "max_stars_repo_name": "jondeuce/NonNegLeastSquares.jl", "max_stars_repo_head_hexsha": "a122bf7acb498efcaf140b719133691e7c4cd03d", "max_stars_repo_licenses": ["MIT"], "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/pivot_test.jl", "max_issues_repo_name": "jondeuce/NonNegLeastSquares.jl", "max_issues_repo_head_hexsha": "a122bf7acb498efcaf140b719133691e7c4cd03d", "max_issues_repo_licenses": ["MIT"], "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/pivot_test.jl", "max_forks_repo_name": "jondeuce/NonNegLeastSquares.jl", "max_forks_repo_head_hexsha": "a122bf7acb498efcaf140b719133691e7c4cd03d", "max_forks_repo_licenses": ["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.8771929825, "max_line_length": 57, "alphanum_fraction": 0.5803949224, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7881949100733894}}
{"text": "#__precompile__()\nmodule AnalyticDomains\n\n# Curve parametrization\nstruct CurveDesc\n    tau\n    dtau\n    d2tau\n    normal\n    tangent\nend\n\nexport starfish, CurveDesc\n\nusing SymPy\n\n# Use any curve parametrized in t in [0, 2 pi), described as string\n# Ex. desc = paramcurve(\"(1 + 0.3*cos(5*t))*exp(I*t)\")\n# !Note that imaginary unit is I\nfunction paramcurve(str::String)\n    desc = Sym(str)\n    t = symbols(\"t\")\n    # Differentiate curve\n    diff1 = diff(desc, t)\n    diff2 = diff(diff1, t)\n    tang = diff1 / abs(diff1)\n    normal = 1im*tang    \n    return CurveDesc(\n        lambdify(desc),\n        lambdify(diff1),\n        lambdify(diff2),\n        lambdify(normal),\n        lambdify(tang)\n    )\nend\n\nfunction starfish(;n_arms = 5, amplitude = 0.3, radius = 1.0, center=(0,0), rotation=0.0, interior=false)\n    if interior\n        s = -1.0\n    else\n        s = 1.0\n    end\n    R = exp(1im*rotation)\n    desc(t) = R*radius*((1 + amplitude*cos(n_arms*t)).*exp(1im*s*t)) + (center[1] + 1im*center[2])\n    diff1(t) = R*radius*(exp(t*1im*s)*(amplitude*cos(n_arms*t) + 1)*1im*s - amplitude*n_arms*exp(t*1im*s)*sin(n_arms*t))\n    diff2(t) = R*radius*(- exp(t*1im*s)*(amplitude*cos(n_arms*t) + 1) - amplitude*n_arms*exp(t*1im*s)*sin(n_arms*t)*2*1im*s - amplitude*n_arms^2*exp(t*1im*s)*cos(n_arms*t))\n    tang(t) = diff1(t) / abs(diff1(t))\n    normal(t) = 1im*tang(t)\n    return CurveDesc(\n        desc,\n        diff1,\n        diff2,\n        normal,\n        tang\n    )\nend\n\nfunction rectangle(;width = 1, height = 1, order = 10, interior=false)\n    @assert iseven(order)\n    a = width\n    b = height\n    p = order;\n    desc(t) = (a*cos(t) + b*sin(t)*1im)/(cos(t)^p + sin(t)^p)^(1/p)\n    _diff1(t) = -(a*cos(t)*sin(t)^p - b*cos(t)^p*sin(t)*1im)/(cos(t)*sin(t)*(cos(t)^p + sin(t)^p)^((p + 1)/p))    \n    _diff2(t) = (-(a*cos(t)^(p + 1)*sin(t)^p + b*cos(t)^(2*p + 2)*sin(t)*2im - 2*a*cos(t)^3*sin(t)^(2*p) - 2*a*cos(t)^(p + 3)*sin(t)^p - b*cos(t)^p*sin(t)^(p + 1)*1im - b*cos(t)^(2*p)*sin(t)*2im + b*cos(t)^(p + 2)*sin(t)^(p + 1)*2im + a*p*cos(t)^(p + 1)*sin(t)^p + b*p*cos(t)^p*sin(t)^(p + 1)*1im)/(cos(t)^2*sin(t)^2*(cos(t)^p + sin(t)^p)^((2*p + 1)/p)))\n\n    # Fudge because derivative expression is NaN at t=0\n    diff1(t) = _diff1(t + eps(t))\n    diff2(t) = _diff2(t + eps(t))\n\n    \n    tang(t) = diff1(t) / abs(diff1(t))\n    normal(t) = 1im*tang(t)\n    \n    return CurveDesc(\n        desc,\n        diff1,\n        diff2,\n        normal,\n        tang\n    )\nend\n\nend\n", "meta": {"hexsha": "37bdfb51b740dab2732823eb6ae2c4b5d962e1c8", "size": 2456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/AnalyticDomains.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/AnalyticDomains.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/AnalyticDomains.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": 28.8941176471, "max_line_length": 354, "alphanum_fraction": 0.5513029316, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7881887350523604}}
{"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\u03c0   \n    xeval = collect(range(pi/2., stop=pi*1.5, length=neval)) # from \u03c0/2 to 3\u03c0/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": "using LinearAlgebra\nusing Random\n\nRandom.seed!(843)\n\ninclude(\"feast.jl\")\nusing ..feastLinear\nusing IterativeSolvers\n\nn=100\n\n#generate B-matrix eigenvectors and eigenvalues\n#vectors:\nR=rand(n,n)\n(Xb,R)=qr(R)\n#values:\nLb=rand(n)*0.5 .+ 0.5 #random positive numbers\n\n#generate A-matrix eigenvectors:\nR=rand(n,n)\n(X1,R)=qr(R)\n\n#generate A-matrix eigenvalues\nL1=zeros(n)\nfor i in 1:n\n    L1[i]=i\nend\n\n#generate eigenvalue problem matrices\nA=Xb*diagm(0 => sqrt.(Lb))*X1*diagm(0 => L1)*X1'*diagm(0 => sqrt.(Lb))*Xb'\nB=Xb*diagm(0 => Lb)*Xb'\n\n#FEAST parameters\nemid=1.0+0.0*im #contour center\nra=0.5 #contour radius 1\nrb=0.5 #contour radius 2\nnc=6 #number of contour points\nm0=2 #subspace dimension\neps=1e-5 #residual convergence tolerance\nmaxit=100 #maximum FEAST iterations\nx0=rand(n,m0) #eigenvector initial guess\n\nprintln(\"Standard FEAST\")\n(lf,xf)=feast_linear(A,B,x0,nc,emid,ra,rb,eps,maxit)\np=sortperm(real(lf))\nprintln(lf[p])\n\nprintln(\"Iterative FEAST BiCGSTAB\")\nalpha=0.01 #relative accuracy of linear system solves\nisMaxit=220  #maximum number of linear system iterations per FEAST iteration\n(lf,xf,data)=ifeast_linear(A,B,x0,alpha,isMaxit,nc,emid,ra,rb,eps,maxit;log=true)\np=sortperm(real(lf))\nprintln(lf[p])\n", "meta": {"hexsha": "c0df6589a4ec1582f04ac70860fe8110e2601761", "size": 1210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "feast_testLinear.jl", "max_stars_repo_name": "rleegates/feastjl", "max_stars_repo_head_hexsha": "5fc0c1957435e5e13670b280f896d0f9a70d14c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-05-02T16:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T11:49:03.000Z", "max_issues_repo_path": "feast_testLinear.jl", "max_issues_repo_name": "rleegates/feastjl", "max_issues_repo_head_hexsha": "5fc0c1957435e5e13670b280f896d0f9a70d14c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-24T16:48:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-24T16:48:00.000Z", "max_forks_repo_path": "feast_testLinear.jl", "max_forks_repo_name": "rleegates/feastjl", "max_forks_repo_head_hexsha": "5fc0c1957435e5e13670b280f896d0f9a70d14c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-07T19:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T20:58:09.000Z", "avg_line_length": 22.4074074074, "max_line_length": 81, "alphanum_fraction": 0.7380165289, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747181, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7881702306587015}}
{"text": "module TestIntegrate\n    using Calculus2\n    using Base.Test\n\n    @test isapprox(\n        integrate(x -> 1 / x, 1.0, 2.0),\n        log(2) - log(1)\n    )\n\n    @test isapprox(\n        integrate(x -> -sin(x), 0.0, pi),\n        (cos(pi) - cos(0.0))\n    )\n\n    @test isapprox(\n        integrate(x -> 1, 0, 1),\n        1.0 - 0.0,\n    )\n\n    @test isapprox(\n        integrate(x -> x, 0, 1),\n        1//2 * 1.0^2 - 1//2 * 0.0^2\n    )\n\n    @test isapprox(\n        integrate(x -> x * x, 0, 1),\n        1//3 * 1.0^3 - 1//3 * 0.0^3 \n    )\n\n    @test isapprox(\n        integrate(sin, 0, pi),\n        -cos(pi) - (-cos(0))\n    )\n\n    @test isapprox(\n        integrate(cos, 0, pi),\n        sin(pi) - sin(0)\n    )\n\n    @test isapprox(\n        integrate(x -> sin(x)^2 + sin(x)^2, 0, pi),\n        pi\n    )\n\n    @test isapprox(\n        integrate(x -> 1 / x, 0.01, 1),\n        4.60517\n    )\n\n    @test isapprox(\n        integrate(x -> cos(x)^8, 0, 2 * pi),\n        35 * pi / 64\n    )\n\n    @test isapprox(\n        integrate(x -> sin(x) - sin(x^2) + sin(x^3), pi, 2 * pi),\n        -1.830467\n    )\n\n    @test isapprox(\n        integrate(sin, 0.0, pi, method = :quadrature),\n        sqrt(2),\n        atol = 10e-1\n    )\n\n    @test isapprox(\n        integrate(sin, 0.0, pi, method = :simpsons),\n        sqrt(2),\n        atol = 10e-1\n    )\n\n    @test isapprox(\n        integrate(sin, 0.0, pi, method = :monte_carlo),\n        sqrt(2),\n        atol = 10e-1\n    )\n\n    @test isapprox(\n        \u222b(cos, 0.0, 1.0),\n        sin(1.0) - sin(0.0)\n    )\nend\n", "meta": {"hexsha": "101c5e88dec94fa9ec6ec173bfbc8b7e6b80f4e3", "size": 1518, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 18.2891566265, "max_line_length": 65, "alphanum_fraction": 0.4295125165, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7881594664924282}}
{"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(\u03c0::AbstractFloat, S::Integer, a1::AbstractFloat, e1::AbstractFloat, e2::AbstractFloat)\n    return (\u03c0 - S / a1) / sqrt(e1 * S + e2 * S * (S - 1))\nend\n\n\"\"\"\n    tajimad(\u03c0::AbstractFloat, S::Integer, n::Integer)\n\nCompute Tajima's D from:\n\n* `\u03c0`: 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(\u03c0::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(\u03c0, 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 `\u03c0`, `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    \u03c0 = avg_mut(seqs)\n    S = count(Segregating, seqs)\n    n = length(seqs)\n    return tajimad(\u03c0, 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\u2032\n    w = view(u,22:28) # y\u2032\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\u2032\n  w = view(u,22:28) # y\u2032\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\u2032\n  vy = view(v,8:14)  # y\u2032\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\u2032\n  vy = view(v,8:14)  # y\u2032\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\u2032\n  vy = view(du,8:14) # y\u2032\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#     \u2202\u00b2g/\u2202x\u00b2 - g - \u2202g/\u2202t = 0\n#\n# on [0, L] \u00d7 [0,\u221e), subject to:\n#\n#     g(x, 0) = 0\n#     \u2202g/\u2202x (0, t) = 1\n#     \u2202g/\u2202x (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\u22601\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#     \u03bb\u00b2\u2202\u00b2f/\u2202x\u00b2 - f - \u03c4\u2202f/\u2202t = 0\n#\n# on [0, L] x [0, \u221e), subject to:\n#\n#     f(x, 0) = V\n#     \u2202f/\u2202x (0, t) = I\u00b7r\n#     \u2202f/\u2202x (L, t) = 0\n#\n# where:\n#\n#     \u03bb\u00b2 = 1/(r\u00b7g)   length constant\n#     \u03c4  = r\u00b7c       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 \u1e21 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 = \u1e21\u00b7f\n#     c = c_m\u00b7f\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 \u2126\u00b7m    bulk axial resistivity\n#     RM = 4 \u2126\u00b7m\u00b2   areal membrane resistivity\n#     CM = 0.01 F/m\u00b2  areal membrane capacitance\n#     d  = 1 \u00b5m     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(\u03c0), 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\u03c7 = Lar.euler_characteristic(V, copEV, copFE)\nprintln(\"\u03c7 = $\u03c7 ; 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\u2081,r\u2082,\u03bc)\r\n#[dV1,dV2,T] = circHohmann(r1,r2,\u03bc)\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\u209c   = 0.5(r\u2081 + r\u2082) #transfer semi-major axis\r\nv1 = sqrt(\u03bc/r\u2081)\r\nv2 = sqrt(\u03bc/r\u2082)\r\nvt1 = sqrt(\u03bc*(2/r\u2081-1/a\u209c))\r\nvt2 = sqrt(\u03bc*(2/r\u2082-1/a\u209c))\r\ndV1 = vt1 - v1\r\ndV2 = v2 - vt2\r\nT = 2pi*sqrt(a\u209c^3/\u03bc)\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\u03c3::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; \u03c3::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) + \u03c3^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, \u03c3, 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\u2080::Float64, y\u2080::Float64, x\u2081::Float64, n)\n    vx = Vector{Float64}(n + 1)\n    vy = Vector{Float64}(n + 1)\n    vx[1] = x = x\u2080\n    vy[1] = y = y\u2080\n    h = (x\u2081 - x\u2080) / n\n    for i in 1:n\n        k\u2081 = h * f(x, y)\n        k\u2082 = h * f(x + 0.5h, y + 0.5k\u2081)\n        k\u2083 = h * f(x + 0.5h, y + 0.5k\u2082)\n        k\u2084 = h * f(x + h, y + k\u2083)\n        vx[i + 1] = x = x\u2080 + i * h\n        vy[i + 1] = y = y + (k\u2081 + 2k\u2082 + 2k\u2083 + k\u2084) / 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                    \u03f5::Real;\n                    t0::Real=1., \n                    \u03bc::Real=100.,\n                    \u03b1::Real=0.01, \u03b2::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  \u2207f(x) = [x[1: size(w, 1)]; C*ones(Y)]\n  Hf(x) = Diagonal([ones(wsize); zeros(Y)])\n  x, \u03b1dual, numstepsarray = barriermethod(\n    f, \u2207f, Hf, A, b, x0; \u03f5=\u03f5, t0=t0, \u03bc=\u03bc, \u03b1=\u03b1, \u03b2=\u03b2)\n  x[1: wsize], \u03b1dual[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 \u2264 b.\nfunction barriermethod(f, \u2207f, Hf,\n                       A::AbstractMatrix,\n                       b::AbstractVector,\n                       x0::AbstractVector;\n                       \u03f5::Real=1e-3,\n                       t0::Real=1.,\n                       \u03bc::Real=100.,\n                       \u03b1::Real=0.01, \u03b2::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, \u2207f, Hf, A, b, x, t; \u03b1=\u03b1, \u03b2=\u03b2)\n    push!(numstepsarray, numsteps)\n    m/t < \u03f5 && break\n    t *= \u03bc\n  end\n  \u03b1dual = 1./(t*(b-A*x))\n  x, \u03b1dual, 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 \u2264 b.\nfunction centeringstep(f, \u2207f, Hf,\n                       A::AbstractMatrix,\n                       b::AbstractVector,\n                       x0::AbstractVector,\n                       t::Real;\n                       \u03f5::Real=1e-8,\n                       \u03b1::Real=0.01, \u03b2::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    \u2207 = t*\u2207f(x)+A'*d\n    H = t*Hf(x)+A'*Diagonal(d)^2*A\n    \u0394xnt = -H\\\u2207\n    \u03bb\u00b2 = -\u2207\u22c5\u0394xnt\n    \u03bb\u00b2/2 < \u03f5 && break\n    tbacktrace = 1\n    xtest = x + tbacktrace*\u0394xnt\n    while(any(A*xtest .\u2265 b) || obj(xtest) > obj(x)-tbacktrace*\u03b1*\u03bb\u00b2)\n      tbacktrace *= \u03b2\n      xtest = x + tbacktrace*\u0394xnt\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": "function isPalindrome(n)\n    s = string(n)\n    s == reverse(s)\nend\n\nmax = 0\nfor i in collect(999:-1:100)\n    for j in collect(999:-1:100)\n        n = i*j\n        if (isPalindrome(n) && n > max) \n            max = n\n        end\n    end\nend\n\nprintln(max)", "meta": {"hexsha": "f535f58c076102e9e8d5bc0faeeb1601e134fc79", "size": 252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "004 - Largest Palindrome Product/004 - Largest_Palindrome_Product.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": "004 - Largest Palindrome Product/004 - Largest_Palindrome_Product.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": "004 - Largest Palindrome Product/004 - Largest_Palindrome_Product.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": 15.75, "max_line_length": 40, "alphanum_fraction": 0.5158730159, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7880837196970186}}
{"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    \u0394r = 0.01\n    r1 = 0.0335\n    r2 = 0.06\n\n    m = 2.2429\n    \u0394m = 0.0001 \n\n    I1 = (1/2)*m*(r1^2 + r2^2)\n    \u0394I1 = (1/2)*((\u0394m*(r1^2 + r2^2) + 2*m*(r1*\u0394r + r2*\u0394r)))\n    println(\" Ig \u00b1 \u0394 Ig = \", I1, \" \u00b1 \", \u0394I1)\n#    return [I1,\u0394I1]\nend\n\nfunction I2(\u03c91, \u03c9)\n   \u0394\u03c9=1e-3\n   I2 = I1()[1]*( \u03c91/(\u03c91 - \u03c9))\n   \u0394I2   =  (I1()[2]  + (I1()[2]*\u03c9 +  \u0394\u03c9*I1()[1])/(\u03c9^2))\n    println(\"I2 \u00b1 \u0394 I2 = \", I2, \" \u00b1 \", \u0394I2)\n    return [I2, \u0394I2]\nend\n\nfunction equivalencia(v1,v2,\u03c31, \u03c32)\n    abs(v1-v2) < 2*(\u03c31 + \u03c32)\nend\n\nfunction \u0394E(\u03c91, \u03c9,I1, I2)\n    \u0394\u03c9 = 0.001\n    Ef = (1/2)*(I1[1] + I2[1])*\u03c9^2\n    Ei = (1/2)*(I1[1])*\u03c91^2\n\n    \u03b4E = ((1/2)*(I1[2] + I2[2])*\u03c9^2 + (I1[1] + I2[1])*\u03c9*\u0394\u03c9) + (1/2)*(I1[2]*\u03c91^2 + 2*\u03c91*\u0394\u03c9*I1[1])          \n    \n    println(\"E \u00b1 \u0394E = \", Ef - Ei, \" \u00b1 \", \u03b4E)\nend\n\nfunction results()\n\u03c91 = [14.444, 22.765,24.353]\n\u03c9   = [7.453,12.777,13.629]\nprint(\"(1) : \")\nI2_1 = I2(\u03c91[1], \u03c9[1])\nprint(\"(2) : \")\nI2_2 = I2(\u03c91[2],\u03c9[2])\nprint(\"(3) : \")\nI2_3 = I2(\u03c91[3],\u03c9[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 = \u0394E(\u03c91[1], \u03c9[1], I1(), I2_1)\nE2 = \u0394E(\u03c91[2], \u03c9[2], I1(), I2_2)\nE3 = \u0394E(\u03c91[3], \u03c9[3], I1(), I2_3)\n#println(\"\u0394E1 \u00b1 \u03b4 E1 = \", E1[1], \" \u00b1 \", E1[2])\n#println(\"\u0394E2 \u00b1 \u03b4 E2 =\",  E2[1], \" \u00b1 \", E2[2])\n#println(\"\u0394E3 \u00b1 \u03b4 E3 = \", E3[1] , \" \u00b1 \", 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": "module StokesTaylorHoodTests\n\nusing Test\nusing Gridap\nimport Gridap: \u2207\n\n#using LinearAlgebra: tr, \u22c5\n\n# Using automatic differentiation\nu(x) = VectorValue( x[1]^2 + 2*x[2]^2, -x[1]^2 )\np(x) = x[1] + 3*x[2]\nf(x) = -\u0394(u)(x) + \u2207(p)(x)\ng(x) = (\u2207\u22c5u)(x)\n\u2207u(x) = \u2207(u)(x)\n\n#u(x) = VectorValue( x[1]^2 + 2*x[2]^2, -x[1]^2 )\n#\u2207u(x) = TensorValue( 2*x[1], 4*x[2], -2*x[1], zero(x[1]) )\n#\u0394u(x) = VectorValue( 6, -2 )\n#\n#p(x) = x[1] + 3*x[2]\n#\u2207p(x) = VectorValue(1,3)\n#\n#f(x) = -\u0394u(x) + \u2207p(x)\n#g(x) = tr(\u2207u(x))\n#\n#\u2207(::typeof(u)) = \u2207u\n#\u2207(::typeof(p)) = \u2207p\n\ndomain = (0,2,0,2)\npartition = (3,3)\nmodel = CartesianDiscreteModel(domain,partition)\n\nlabels = get_face_labeling(model)\nadd_tag_from_tags!(labels,\"dirichlet\",[1,2,5])\nadd_tag_from_tags!(labels,\"neumann\",[6,7,8])\n\norder = 2\n\nreffe_u = ReferenceFE(lagrangian,VectorValue{2,Float64},order)\nreffe_p = ReferenceFE(lagrangian,Float64,order-1)\n\nV = TestFESpace(model,reffe_u,labels=labels,dirichlet_tags=\"dirichlet\",conformity=:H1)\nQ = TestFESpace(model,reffe_p,labels=labels,conformity=:H1)\n\nU = TrialFESpace(V,u)\nP = TrialFESpace(Q)\n\nY = MultiFieldFESpace([V,Q])\nX = MultiFieldFESpace([U,P])\n\n\u03a9 = Triangulation(model)\n\u0393 = BoundaryTriangulation(model,labels,tags=\"neumann\")\nn_\u0393 = get_normal_vector(\u0393)\n\ndegree = order\nd\u03a9 = Measure(\u03a9,degree)\nd\u0393 = Measure(\u0393,degree)\n\na((u,p),(v,q)) = \u222b( \u2207(v)\u2299\u2207(u) - (\u2207\u22c5v)*p + q*(\u2207\u22c5u) )*d\u03a9\n\nl((v,q)) = \u222b( v\u22c5f + q*g )*d\u03a9 + \u222b( v\u22c5(n_\u0393\u22c5\u2207u) - (n_\u0393\u22c5v)*p )*d\u0393\n\nop = AffineFEOperator(a,l,X,Y)\n\nuh, ph = solve(op)\n\neu = u - uh\nep = p - ph\n\nl2(u) = sqrt(sum( \u222b( u\u2299u )*d\u03a9 ))\nh1(u) = sqrt(sum( \u222b( u\u2299u + \u2207(u)\u2299\u2207(u) )*d\u03a9 ))\n\neu_l2 = l2(eu)\neu_h1 = h1(eu)\nep_l2 = l2(ep)\n\ntol = 1.0e-9\n@test eu_l2 < tol\n@test eu_h1 < tol\n@test ep_l2 < tol\n\nend # module\n", "meta": {"hexsha": "b3b72c156ad4f2f5ab61c91ae8a432e9adb03fc9", "size": 1703, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/GridapTests/StokesTaylorHoodTests.jl", "max_stars_repo_name": "aerappa/Gridap.jl", "max_stars_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 390, "max_stars_repo_stars_event_min_datetime": "2019-05-16T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:17.000Z", "max_issues_repo_path": "test/GridapTests/StokesTaylorHoodTests.jl", "max_issues_repo_name": "aerappa/Gridap.jl", "max_issues_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 576, "max_issues_repo_issues_event_min_datetime": "2019-05-16T20:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:21:35.000Z", "max_forks_repo_path": "test/GridapTests/StokesTaylorHoodTests.jl", "max_forks_repo_name": "aerappa/Gridap.jl", "max_forks_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2019-12-30T23:35:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:56:24.000Z", "avg_line_length": 20.5180722892, "max_line_length": 86, "alphanum_fraction": 0.6048150323, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7880588946459048}}
{"text": "using Diagonalizations, LinearAlgebra, PosDefManifold, Test\n\n# Method (1) real\nt, n, k=10, 20, 10\nXset = [genDataMatrix(t, n) for i = 1:k]\nXfixed=randn(t, n)./1\nfor i=1:length(Xset) Xset[i]+=Xfixed end\nC1=Hermitian( mean((X'*X)/t for X\u2208Xset) )\nC2=Hermitian( mean((X*X')/n for X\u2208Xset) )\nXbar=mean(Xset)\nc=cstp(Xbar, C1, C2; simple=true)\n@test c.F[1]'*C2*c.F[1]\u2248I\n@test c.F[2]'*C1*c.F[2]\u2248I\nZ=c.F[1]'*Xbar*c.F[2]\nn=minimum(size(Z))\n@test norm(Z[1:n, 1:n]-Diagonal(Z[1:n, 1:n]))+1. \u2248 1.\ncX=cstp(Xset; simple=true)\n@test c==cX\n\n# Method (1) complex\nt, n, k=10, 20, 10\nXcset = [genDataMatrix(ComplexF64, t, n) for i = 1:k]\nXcfixed=randn(ComplexF64, t, n)./1\nfor i=1:length(Xcset) Xcset[i]+=Xcfixed end\nC1c=Hermitian( mean((Xc'*Xc)/t for Xc\u2208Xcset) )\nC2c=Hermitian( mean((Xc*Xc')/n for Xc\u2208Xcset) )\nXcbar=mean(Xcset)\ncc=cstp(Xcbar, C1c, C2c; simple=true)\n@test cc.F[1]'*C2c*cc.F[1]\u2248I\n@test cc.F[2]'*C1c*cc.F[2]\u2248I\nZc=cc.F[1]'*Xcbar*cc.F[2]\nn=minimum(size(Zc))\n@test norm(Zc[1:n, 1:n]-Diagonal(Zc[1:n, 1:n]))+1. \u2248 1.\ncXc=cstp(Xcset; simple=true)\n@test cc==cXc\n\n# Method (2) real\nc=cstp(Xset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.9\nc=cstp(Xset; eVar=0.9)\n\n# ... giving weights `w` to the covariance matrices\nc=cstp(Xset; w=abs2.(randn(k)), eVar=0.9)\n\n# ... subtracting the means\nc=cstp(Xset; meanXd\u2081=nothing, meanXd\u2082=nothing, w=abs2.(randn(k)), eVar=0.9)\n\n# explained variance\nc.eVar\n\n# name of the filter\nc.name\n\nusing Plots\n# plot the original covariance matrices and the transformed counterpart\nc=cstp(Xset)\n\nC1Max=maximum(abs.(C1));\n h1 = heatmap(C1, clim=(-C1Max, C1Max), title=\"C1\", yflip=true, c=:bluesreds);\n D1=c.F[1]'*C2*c.F[1];\n D1Max=maximum(abs.(D1));\n h2 = heatmap(D1, clim=(0, D1Max), title=\"F[1]'*C2*F[1]\", yflip=true, c=:amp);\n C2Max=maximum(abs.(C2));\n h3 = heatmap(C2, clim=(-C2Max, C2Max), title=\"C2\", yflip=true, c=:bluesreds);\n D2=c.F[2]'*C1*c.F[2];\n D2Max=maximum(abs.(D2));\n h4 = heatmap(D2, clim=(0, D2Max), title=\"F[2]'*C1*F[2]\", yflip=true, c=:amp);\n\nXbarMax=maximum(abs.(Xbar));\n h5 = heatmap(Xbar, clim=(-XbarMax, XbarMax), title=\"Xbar\", yflip=true, c=:bluesreds);\n DX=c.F[1]'*Xbar*c.F[2];\n DXMax=maximum(abs.(DX));\n h6 = heatmap(DX, clim=(0, DXMax), title=\"F[1]'*Xbar*F[2]\", yflip=true, c=:amp);\n \ud83d\udcc8=plot(h1, h3, h5, h2, h4, h6, size=(800,400))\n# savefig(\ud83d\udcc8, homedir()*\"\\\\Documents\\\\Code\\\\julia\\\\Diagonalizations\\\\docs\\\\src\\\\assets\\\\FigCSTP.png\")\n\n# Method (2) complex\ncc=cstp(Xcset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.9\ncc=cstp(Xcset; eVar=0.9)\n\n# ... giving weights `w` to the covariance matrices\ncc=cstp(Xcset; w=abs2.(randn(k)), eVar=0.9)\n\n# ... subtracting the mean\ncc=cstp(Xcset; meanXd\u2081=nothing, meanXd\u2082=nothing,\n        w=abs2.(randn(k)), eVar=0.9)\n\n# explained variance\nc.eVar\n\n# name of the filter\nc.name\n", "meta": {"hexsha": "ed1195383fbeafe72cb99a4cc834be75ad8c81e3", "size": 2801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/CSTP.jl", "max_stars_repo_name": "ericphanson/Diagonalizations.jl", "max_stars_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/CSTP.jl", "max_issues_repo_name": "ericphanson/Diagonalizations.jl", "max_issues_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/CSTP.jl", "max_forks_repo_name": "ericphanson/Diagonalizations.jl", "max_forks_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": 29.1770833333, "max_line_length": 100, "alphanum_fraction": 0.6540521242, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.788058887874949}}
{"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\u00f2 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 \u201cnumber_of_cheaters\u201d\n    2.) p_skewed = p*(0.5) + (0.25) (deterministic value)\n    3.) with model:\n    yes_responses = pm.Binomial(\u201cnumber_of_cheaters\u201d, 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": "\r\ninclude(\"testfunctions.jl\")\r\n\r\n\r\n\r\nmodule opti\r\nusing LinearAlgebra\r\n\r\n# include(\"line_search.jl\")\r\ninclude(\"opti_1d.jl\")\r\n\r\n\r\nfunction bracketing_line_search(fcn, x0, step_direction; max_iter = 100, alpha = 1.0, x_tol = 1e-2)\r\n\r\n    obj_fcn(alpha) = fcn( x0 + step_direction * alpha )\r\n    x_lo = 0.0\r\n    x_hi = alpha\r\n    bracketing_interval = bracket_min(obj_fcn, x_lo, x_hi, max_iter = max_iter)\r\n\r\n\r\n    stat = golden_section_search(\r\n        obj_fcn,\r\n        bracketing_interval.x_lo,\r\n        bracketing_interval.x_hi,\r\n        max_iter = max_iter,\r\n        x_tol = x_tol)\r\n\r\n    x_sol = x0 + stat.x_sol * step_direction\r\n    return (x_sol, stat.y_sol)\r\nend\r\n\r\n\r\nfunction basis(n_dim::Int, ii::Int)\r\n    e_i = zeros(n_dim)\r\n    e_i[ii] = 1.0\r\n    return e_i\r\nend\r\n\r\nstruct DirectMethodToleranceOptions\r\n    f_abs_tol::Float64\r\n    f_rel_tol::Float64\r\nend\r\nfunction DirectMethodToleranceOptions()\r\n    f_abs_tol = 1e-10\r\n    f_rel_tol = 1e-10\r\n    return DirectMethodToleranceOptions(f_abs_tol, f_rel_tol)\r\nend\r\n\r\n\r\nfunction powell(\r\n    fcn, \r\n    x0;\r\n    max_iter = 100,\r\n    step_size_tol = 1e-10,\r\n    line_search_x_tol = 1e-2,\r\n    reset_iter = 5 * length(x0),\r\n    tol_options = DirectMethodToleranceOptions()\r\n    )\r\n    \r\n    x = copy(x0)\r\n    mach_eps = tol_options.f_abs_tol * 1e-5\r\n\r\n    n_dim = length(x0)\r\n    U = Matrix( one(eltype(x0)) * I , n_dim, n_dim )\r\n\r\n    break_flag = false\r\n\r\n    f_prev = fcn(x0)\r\n    iter = 0\r\n    for outer iter = 1:max_iter\r\n\r\n        for ii = 1:n_dim\r\n            (x, f_act) = bracketing_line_search(\r\n                fcn, \r\n                x, \r\n                U[:, ii]; \r\n                max_iter = max_iter, \r\n                x_tol = line_search_x_tol)\r\n            \r\n                # stopping criteria for function value\r\n            if abs(f_act - f_prev) <= tol_options.f_abs_tol || abs(f_act - f_prev) / ( abs(f_prev) == 0 ? mach_eps : abs(f_prev)) < tol_options.f_rel_tol\r\n                break_flag = true\r\n                break\r\n            end\r\n            \r\n            println(\" x = $(x) \")\r\n        end\r\n\r\n        if break_flag\r\n            break\r\n        end\r\n\r\n        for ii = 2:n_dim\r\n            U[:, ii-1] = U[:, ii]\r\n        end\r\n        d = x - U[:,n_dim]\r\n        U[:,n_dim] = d\r\n        (x_hat, f_act) = bracketing_line_search(\r\n                fcn, \r\n                x, \r\n                U[:, n_dim]; \r\n                max_iter = max_iter, \r\n                x_tol = line_search_x_tol)\r\n        println(\" x_hat = $(x_hat) \")\r\n        step = x_hat - x\r\n        if norm(step) <= step_size_tol\r\n            break\r\n        end\r\n\r\n\r\n        if iter % reset_iter == 0\r\n            U = Matrix( one(eltype(x0)) * I , n_dim, n_dim )\r\n        end\r\n\r\n    end\r\n\r\n    return (x, iter)\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 exponential_annealing_schedule(iter, start_value = 1.0, gamma = 1.0)\r\n    return gamma * start_value^iter\r\nend\r\n\r\nfunction fast_annealing_schedule(iter, start_value = 1.0)\r\n    return start_value / iter\r\nend\r\n\r\nfunction logarithmic_annealing_schedule(iter, gamma = 1.0)\r\n    return log( gamma * iter )\r\nend \r\n\r\n\r\nfunction simulated_annealing(\r\n    fcn,\r\n    x0,\r\n    rand_fcn;\r\n    max_iter = 100,\r\n    annealing_schedule = exponential_annealing_schedule\r\n    )\r\n\r\n    # gamma = 10\r\n    # annealing_schedule(iter) = gamma * iter\r\n\r\n    n_dim = length(x0)\r\n    x_path = zeros(n_dim, max_iter)\r\n\r\n    f_old = fcn(x0)\r\n    x_best = x0\r\n    f_best = f_old\r\n\r\n    x_old = copy(x0)\r\n    iter = 0\r\n    for outer iter = 1:max_iter\r\n        \r\n        x_new = x_old + rand_fcn(x_old, iter)\r\n        x_path[:, iter] = x_new\r\n\r\n        f_new = fcn(x_new)\r\n        df = f_new - f_old\r\n\r\n        if df <= 0\r\n            x_old = x_new\r\n            f_old = f_new\r\n        elseif rand() < exp( -df / annealing_schedule(iter) )\r\n            x_old = x_new\r\n            f_old = f_new\r\n        end\r\n\r\n\r\n        if f_new <= f_best\r\n            x_best = x_new\r\n            f_best = f_new\r\n        end\r\n    end\r\n\r\n\r\n    return (x_best, f_best, iter, x_path)\r\n\r\nend\r\n\r\nfunction corana_update!(v, a, c, n_crit_cycles)\r\n    for ii = 1:length(v)\r\n        \r\n        if a[ii] > 0.6 * n_crit_cycles\r\n            v[ii] *= (1 + c[ii] / 0.4 * ( a[ii]/n_crit_cycles - 0.6 )  )\r\n        elseif a[ii] < 0.4 * n_crit_cycles\r\n            v[ii] /= (1 + c[ii] / 0.4 * (0.4 - a[ii]/n_crit_cycles))\r\n        end\r\n\r\n    end\r\n    return v\r\nend\r\n\r\n\r\nfunction adaptive_simulated_annealing(\r\n    fcn,\r\n    x0,\r\n    v,\r\n    temperature,\r\n    eps;\r\n    n_crit_cycles = 20,\r\n    neps = 4,\r\n    n_crit_resets = max( 100, 5 * length(x0) ),\r\n    gamma = 0.85,\r\n    c = fill(2, length(x0)),\r\n    max_iter = 100\r\n    )\r\n\r\n    \r\n\r\n\r\n\r\n    x_best = copy(x0)\r\n    x_old  = copy(x0)\r\n\r\n    f_old  = fcn(x0)\r\n    f_best = f_old\r\n\r\n   \r\n    \r\n\r\n    y_arr = []\r\n    n_dim = length(x0)\r\n    uniform_random() = 2 * (rand() - 0.5)\r\n\r\n    a = zeros(n_dim)\r\n    counts_cycles = 0\r\n    counts_resets = 0\r\n\r\n    basis_vectors = Matrix{eltype(x0)}( one(eltype(x0)) * I, n_dim, n_dim )\r\n    \r\n    iter = 0\r\n    for outer iter = 1:max_iter\r\n\r\n        for ii = 1:n_dim\r\n            x_new = x_old + basis_vectors[:,ii] * uniform_random() * v[ii]\r\n            f_new = fcn(x_new)\r\n\r\n            df = f_new - f_old\r\n            if df < 0 || rand() < exp( df / temperature )\r\n                x_old = x_new\r\n                f_old = f_new\r\n                a[ii] += 1\r\n                if f_new < f_best\r\n                    x_best = x_new\r\n                    f_best = f_new\r\n                end\r\n            end\r\n        end\r\n\r\n        counts_cycles += 1\r\n        # counts_cycles >= n_crit_cycles || continue\r\n        if counts_cycles < n_crit_cycles\r\n            continue\r\n        end\r\n\r\n        counts_cycles = 0\r\n        corana_update!(v, a, c, n_crit_cycles)\r\n        fill!(a, 0)\r\n        counts_resets += 1\r\n        if counts_resets < n_crit_resets\r\n            continue\r\n        end\r\n\r\n        temperature *= gamma\r\n        counts_resets = 0\r\n        push!(y_arr, f_old)\r\n\r\n        \r\n        Ly = length(y_arr)\r\n        cond = Ly > neps && y_arr[end] - y_best <= eps &&\r\n         (all(abs(y_arr[end] - y_arr[end-u])) <= eps for u in 1:neps)\r\n         \r\n        if cond\r\n            x_old = x_best\r\n            f_old = f_best\r\n        else\r\n            break\r\n        end\r\n\r\n    end\r\n\r\n\r\n    return (x_best, f_best)\r\nend\r\n\r\n\r\n\r\nend # opti\r\n\r\n\r\nmodule otest\r\nusing ..optitestfun\r\nusing ..opti\r\nusing PyPlot\r\nPyPlot.pygui(true)\r\n\r\n\r\n\r\n\r\nfcn = optitestfun.rosenbrock # optitestfun.quadratic\r\nx0 = [-1.8, -2.0] # [10, 8.0]\r\n\r\nrand_fcn(x, iter) = 1 / log(iter+1) * randn( length(x) )\r\n\r\n# (x_best, y_best, iter, x_path) = opti.simulated_annealing(\r\n#     fcn,\r\n#     x0,\r\n#     rand_fcn;\r\n#     max_iter = 300,\r\n#     annealing_schedule = opti.fast_annealing_schedule) # opti.exponential_annealing_schedule)\r\n    \r\nv = [1.0, 1.0]\r\ntemp = 1.0\r\neps = 1e-1\r\n(x_best, f_best) = opti.adaptive_simulated_annealing(\r\n    fcn,\r\n    x0,\r\n    v,\r\n    temp,\r\n    eps;\r\n    max_iter = 1000)\r\n\r\n    \r\n\r\n\r\n# PyPlot.figure()\r\n# PyPlot.grid()\r\n# PyPlot.plot(\r\n#     x_path[1,:], x_path[2,:], linestyle = :none, marker = :.)\r\n# PyPlot.plot( x_best[1], x_best[2], linestyle = :none, marker = :., color = :r, markersize = 15)\r\n\r\n\r\n\r\n\r\n\r\nfunction test_powell()\r\n    # fcn = optitestfun.quadratic\r\n    # x0 = [10, 8.0]\r\n\r\n    fcn(x) = optitestfun.rosenbrock(x, 2)\r\n    x0 = [-1.8, -2.0]\r\n\r\n    (x_sol, iter) = opti.powell( fcn, x0, step_size_tol = 1e-2, line_search_x_tol = 1e-3 )\r\n\r\n\r\n    # xs = collect( range(-1.0, 10, 30) )\r\n    # ys = collect( range(-1.0, 10, 30) )\r\n\r\n\r\n    # zs = zeros( length(xs), length(ys) )\r\n    # ii = 0\r\n    # for xx in xs\r\n    #     for yy in ys\r\n    #         ii += 1\r\n    #         zs[ii] = fcn([xx, yy]) \r\n    #     end\r\n    # end\r\n\r\n\r\n\r\n    # PyPlot.figure()\r\n    # PyPlot.grid()\r\n    # PyPlot.contour(xs, ys, zs, [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 0.2, 0.5, 1, 2, 5, 10, 20, 30, 50, 100])\r\nend\r\n\r\n\r\nend\r\n\r\n", "meta": {"hexsha": "089a3b1cf96802088512ed37c0a297e39301e160", "size": 7927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/opti/src/direct_methods.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/direct_methods.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/direct_methods.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.8605263158, "max_line_length": 154, "alphanum_fraction": 0.5071275388, "num_tokens": 2400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7879636686332497}}
{"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\u03c6 = (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 = (\u03c6 ^ 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 = \u03c6 .^ 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 = \u03c6 .^ (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": "#*******************************************************/\n#* Copyright(c) 2018 by Artelys                        */\n#* This source code is subject to the terms of the     */\n#* MIT Expat License (see LICENSE.md)                  */\n#*******************************************************/\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# This example demonstrates how to use Knitro to solve the following\n# mixed-integer nonlinear optimization problem(MINLP).  This model\n# is test problem 1(Synthesis of processing system) in\n# M. Duran & I.E. Grossmann,  \"An outer approximation algorithm for\n# a class of mixed integer nonlinear programs\", Mathematical\n# Programming 36, pp. 307-339, 1986.  The problem also appears as\n# problem synthes1 in the MacMINLP test set.\n#\n# min   5 x3 + 6 x4 + 8 x5 + 10 x0 - 7 x2 -18 log(x1 + 1)\n#      - 19.2 log(x0 - x1 + 1) + 10\n# s.t.  0.8 log(x1 + 1) + 0.96 log(x0 - x1 + 1) - 0.8 x2 >= 0\n#       log(x1 + 1) + 1.2 log(x0 - x1 + 1) - x2 - 2 x5 >= -2\n#       x1 - x0 <= 0\n#       x1 - 2 x3 <= 0\n#       x0 - x1 - 2 x4 <= 0\n#       x3 + x4 <= 1\n#       0 <= x0 <= 2\n#       0 <= x1 <= 2\n#       0 <= x2 <= 1\n#       x0, x1, x2 continuous\n#       x3, x4, x5 binary\n#\n# The solution is(1.30098, 0, 1, 0, 1, 0).\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\nusing KNITRO\nusing Test\n\nfunction example_minlp1(; verbose=true)\n    #*------------------------------------------------------------------*\n    #*     FUNCTION callbackEvalFC                                      *\n    #*------------------------------------------------------------------*\n    # The signature of this function matches KNITRO.KN_eval_callback in knitro.h.\n    # Only \"obj\" and \"c\" are set in the KNITRO.KN_eval_result structure.\n    function callbackEvalFC(kc, cb, evalRequest, evalResult, userParams)\n        x = evalRequest.x\n\n        # Evaluate nonlinear objective structure\n        dTmp1 = x[1] - x[2] + 1.0\n        dTmp2 = x[2] + 1.0\n        evalResult.obj[1] = -18.0 * log(dTmp2) - 19.2 * log(dTmp1)\n\n        # Evaluate nonlinear constraint structure\n        evalResult.c[1] = 0.8 * log(dTmp2) + 0.96 * log(dTmp1)\n        evalResult.c[2] = log(dTmp2) + 1.2 * log(dTmp1)\n\n        return 0\n    end\n\n    #*------------------------------------------------------------------*\n    #*     FUNCTION callbackEvalGA                                      *\n    #*------------------------------------------------------------------*\n    # The signature of this function matches KNITRO.KN_eval_callback in knitro.h.\n    # Only \"objGrad\" and \"jac\" are set in the KNITRO.KN_eval_result structure.\n    function callbackEvalGA(kc, cb, evalRequest, evalResult, userParams)\n        x = evalRequest.x\n\n        # Evaluate gradient of nonlinear objective structure\n        dTmp1 = x[1] - x[2] + 1.0\n        dTmp2 = x[2] + 1.0\n        evalResult.objGrad[1] = -(19.2 / dTmp1)\n        evalResult.objGrad[2] = (-18.0 / dTmp2) + (19.2 / dTmp1)\n\n        # Gradient of nonlinear structure in constraint 0.\n        evalResult.jac[1] = 0.96 / dTmp1                      # wrt x0\n        evalResult.jac[2] = (-0.96 / dTmp1) + (0.8 / dTmp2)   # wrt x1\n        # Gradient of nonlinear structure in constraint 1.\n        evalResult.jac[3] = 1.2 / dTmp1                       # wrt x0\n        evalResult.jac[4] = (-1.2 / dTmp1) + (1.0 / dTmp2)    # wrt x1\n\n        return 0\n    end\n\n    #*------------------------------------------------------------------*\n    #*     FUNCTION callbackEvalH                                       *\n    #*------------------------------------------------------------------*\n    # The signature of this function matches KNITRO.KN_eval_callback in knitro.h.\n    # Only \"hess\" or \"hessVec\" are set in the KNITRO.KN_eval_result structure.\n    function callbackEvalH(kc, cb, evalRequest, evalResult, userParams)\n        x = evalRequest.x\n        lambda_ = evalRequest.lambda\n        # Scale objective component of hessian by sigma\n        sigma = evalRequest.sigma\n\n        # Evaluate the non-zero components in the Hessian of the Lagrangian.\n        # Note: Since the Hessian is symmetric, we only provide the\n        #       nonzero elements in the upper triangle(plus diagonal).\n        dTmp1 = x[1] - x[2] + 1.0\n        dTmp2 = x[2] + 1.0\n        evalResult.hess[1] = sigma * (19.2 /(dTmp1 * dTmp1)) +\n                                lambda_[1] * (-0.96 / (dTmp1 * dTmp1)) + lambda_[2] * (-1.2 / (dTmp1 * dTmp1))\n        evalResult.hess[2] = sigma * (-19.2 /(dTmp1 * dTmp1)) +\n                                lambda_[1] * (0.96 / (dTmp1 * dTmp1)) + lambda_[2] * (1.2 / (dTmp1 * dTmp1))\n        evalResult.hess[3] = sigma * ((19.2 / (dTmp1 * dTmp1)) +(18.0 / (dTmp2 * dTmp2))) +\n                                lambda_[1] * ((-0.96 / (dTmp1 * dTmp1)) -(0.8 / (dTmp2 * dTmp2))) +\n                                lambda_[2] * ((-1.2 / (dTmp1 * dTmp1)) -(1.0 / (dTmp2 * dTmp2)))\n\n        return 0\n    end\n\n    #*------------------------------------------------------------------*\n    #*     FUNCTION callbackProcessNode                                 *\n    #*------------------------------------------------------------------*\n    # The signature of this function matches KNITRO.KN_user_callback in knitro.h.\n    # Argument \"kcSub\" is the context pointer for the last node\n    # subproblem solved inside Knitro.  The application level context\n    # pointer is passed in through \"userParams\".\n    function callbackProcessNode(kc, x, lambda_, userParams)\n        # The Knitro context pointer was passed in through \"userParams\".\n\n        # Print info about the status of the MIP solution.\n        numNodes = KNITRO.KN_get_mip_number_nodes(kc)\n        relaxBound = KNITRO.KN_get_mip_relaxation_bnd(kc)\n        # Note: To retrieve solution information about the node subproblem\n        # we need to pass in \"kcSub\" here.\n        nodeObj = KNITRO.KN_get_obj_value(kc)\n        mip_io = KNITRO.KN_get_mip_incumbent_obj(kc)\n        mip_ag = KNITRO.KN_get_mip_abs_gap(kc)\n        mip_rg = KNITRO.KN_get_mip_rel_gap(kc)\n\n        if verbose\n            println(\"callbackProcessNode:\")\n            println(\"    Node number    = \", numNodes)\n            println(\"    Node objective = \", nodeObj)\n            println(\"    Current relaxation bound = \", relaxBound)\n            println(\"    Current incumbent bound  = \", mip_io)\n            println(\"    Absolute integrality gap = \", mip_ag)\n            println(\"    Relative integrality gap = \", mip_rg)\n        end\n\n        # User defined termination example.\n        # Uncomment below to force termination after 3 nodes.\n        #if(numNodes == 3)\n        #    return KNITRO.KN_RC_USER_TERMINATION\n\n        return 0\n    end\n\n    #*------------------------------------------------------------------*\n    #*     main                                                         *\n    #*------------------------------------------------------------------*\n\n    # Create a new Knitro solver instance.\n    kc = KNITRO.KN_new()\n\n    # Illustrate how to override default options.\n    KNITRO.KN_set_param(kc, \"mip_method\", KNITRO.KN_MIP_METHOD_BB)\n    KNITRO.KN_set_param(kc, \"algorithm\", KNITRO.KN_ALG_ACT_CG)\n    KNITRO.KN_set_param(kc, \"outmode\", KNITRO.KN_OUTMODE_SCREEN)\n    KNITRO.KN_set_param(kc, KNITRO.KN_PARAM_OUTLEV, KNITRO.KN_OUTLEV_ALL)\n    KNITRO.KN_set_param(kc, KNITRO.KN_PARAM_MIP_OUTINTERVAL, 1)\n    KNITRO.KN_set_param(kc, KNITRO.KN_PARAM_MIP_MAXNODES, 10000)\n\n    # Initialize Knitro with the problem definition.\n\n    # Add the variables and set their bounds and types.\n    # Note: any unset lower bounds are assumed to be\n    # unbounded below and any unset upper bounds are\n    # assumed to be unbounded above.\n    n = 6\n    KNITRO.KN_add_vars(kc, n)\n    KNITRO.KN_set_var_lobnds(kc, zeros(Float64, n))\n    KNITRO.KN_set_var_upbnds(kc, [2., 2., 1., 1., 1., 1.])\n    KNITRO.KN_set_var_types(kc, [KNITRO.KN_VARTYPE_CONTINUOUS,\n                                KNITRO.KN_VARTYPE_CONTINUOUS,\n                                KNITRO.KN_VARTYPE_CONTINUOUS,\n                                KNITRO.KN_VARTYPE_BINARY,\n                                KNITRO.KN_VARTYPE_BINARY,\n                                KNITRO.KN_VARTYPE_BINARY])\n\n    # Note that variables x2..x5 only appear linearly in the\n    # problem.  We mark them as linear variables, which may\n    # help Knitro do more extensive presolving resulting in\n    # faster solves.\n    for i in 2:(n-1)\n        KNITRO.KN_set_var_property(kc, i, KNITRO.KN_VAR_LINEAR)\n    end\n\n    # Add the constraints and set their bounds\n    KNITRO.KN_add_cons(kc, 6)\n    KNITRO.KN_set_con_lobnds(kc,  [0, -2,\n                                -KNITRO.KN_INFINITY,\n                                -KNITRO.KN_INFINITY,\n                                -KNITRO.KN_INFINITY,\n                                -KNITRO.KN_INFINITY])\n    KNITRO.KN_set_con_upbnds(kc, [KNITRO.KN_INFINITY, KNITRO.KN_INFINITY, 0, 0, 0, 1])\n\n    # Add the linear structure in the objective function.\n    objGradIndexVars = Int32[3, 4, 5, 0, 2]\n    objGradCoefs = [5.0, 6.0, 8.0, 10.0, -7.0]\n    KNITRO.KN_add_obj_linear_struct(kc, objGradIndexVars, objGradCoefs)\n\n    # Add the constant in the objective function.\n    KNITRO.KN_add_obj_constant(kc, 10.0)\n\n    # Load the linear structure for all constraints at once.\n    jacIndexCons = Int32[0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5]\n    jacIndexVars = Int32[2, 2, 5, 1, 0, 1, 3, 0, 1, 4, 3, 4]\n    jacCoefs = [-0.8, -1.0, -2.0, 1.0, -1.0, 1.0, -2.0, 1.0, -1.0, -2.0, 1.0, 1.0]\n    KNITRO.KN_add_con_linear_struct(kc, jacIndexCons, jacIndexVars, jacCoefs)\n\n    # Add a callback function \"callbackEvalFC\" to evaluate the nonlinear\n    # structure in the objective and first two constraints.  Note that\n    # the linear terms in the objective and first two constraints were\n    # added above in \"KNITRO.KN_add_obj_linear_struct()\" and\n    # \"KNITRO.KN_add_con_linear_struct()\" and will not be specified in the\n    # callback.\n    cIndices = Int32[0, 1] # Constraint indices for callback\n    cb = KNITRO.KN_add_eval_callback(kc, true, cIndices, callbackEvalFC)\n\n    # Also add a callback function \"callbackEvalGA\" to evaluate the\n    # gradients of all nonlinear terms specified in the callback.  If\n    # not provided, Knitro will approximate the gradients using finite-\n    # differencing.  However, we recommend providing callbacks to\n    # evaluate the exact gradients whenever possible as this can\n    # drastically improve the performance of Knitro.\n    # Objective gradient non-zero structure for callback\n    objGradIndexVarsCB = Int32[0, 1]\n    # Constraint Jacobian non-zero structure for callback\n    jacIndexConsCB = Int32[0, 0, 1, 1]\n    jacIndexVarsCB = Int32[0, 1, 0, 1]\n    KNITRO.KN_set_cb_grad(kc, cb, callbackEvalGA,\n                        nV=length(objGradIndexVarsCB),\n                        objGradIndexVars=objGradIndexVarsCB,\n                        jacIndexCons=jacIndexConsCB,\n                        jacIndexVars=jacIndexVarsCB)\n\n    hessIndexVars1CB = Int32[0, 0, 1]\n    hessIndexVars2CB = Int32[0, 1, 1]\n    # Add a callback function \"callbackEvalH\" to evaluate the Hessian\n    #(i.e. second derivative matrix) of the objective.  If not specified,\n    # Knitro will approximate the Hessian. However, providing a callback\n    # for the exact Hessian(as well as the non-zero sparsity structure)\n    # can greatly improve Knitro performance and is recommended if possible.\n    # Since the Hessian is symmetric, only the upper triangle is provided.\n    KNITRO.KN_set_cb_hess(kc, cb, length(hessIndexVars1CB), callbackEvalH,\n                        hessIndexVars1=hessIndexVars1CB,\n                        hessIndexVars2=hessIndexVars2CB)\n\n    # Specify that the user is able to provide evaluations\n    #  of the Hessian matrix without the objective component.\n    #  turned off by default but should be enabled if possible.\n    KNITRO.KN_set_param(kc, KNITRO.KN_PARAM_HESSIAN_NO_F, KNITRO.KN_HESSIAN_NO_F_ALLOW)\n\n    # Set minimize or maximize(if not set, assumed minimize)\n    KNITRO.KN_set_obj_goal(kc, KNITRO.KN_OBJGOAL_MINIMIZE)\n\n    # Set a callback function that performs some user-defined task\n    # after completion of each node in the branch-and-bound tree.\n    KNITRO.KN_set_mip_node_callback(kc, callbackProcessNode)\n\n    kn_outlev = verbose ? KNITRO.KN_OUTLEV_ALL : KNITRO.KN_OUTLEV_NONE\n    KNITRO.KN_set_param(kc, KNITRO.KN_PARAM_OUTLEV, kn_outlev)\n\n    # Solve the problem.\n    #\n    # Return status codes are defined in \"knitro.h\" and described\n    # in the Knitro manual.\n\n    nStatus = KNITRO.KN_solve(kc)\n    # An example of obtaining solution information.\n    nSTatus, objSol, x, lambda_ = KNITRO.KN_get_solution(kc)\n\n    if verbose\n        println(\"Optimal objective value  = \", objSol)\n        println(\"Optimal x\")\n        for i in 1:n\n            println(\"  x[$i] = \", x[i])\n        end\n    end\n\n    # Delete the Knitro solver instance.\n    KNITRO.KN_free(kc)\n\n    @testset \"Example minlp1\" begin\n        @test nStatus == 0\n        @test objSol \u2248 6.0097589\n        @test x \u2248 [1.30097589, 0., 1., 0., 1., 0.] atol=1e-5\n    end\nend\n\nexample_minlp1(; verbose=isdefined(Main, :KN_VERBOSE) ? KN_VERBOSE : true)\n\n", "meta": {"hexsha": "257e305880571d8fa4c4c4ebdbce7008771367e2", "size": 13187, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/minlp1.jl", "max_stars_repo_name": "jump-dev/KNITRO.jl", "max_stars_repo_head_hexsha": "fa540b7311af788cc8b625525aebda196361efc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-07-10T16:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:58:45.000Z", "max_issues_repo_path": "examples/minlp1.jl", "max_issues_repo_name": "jump-dev/KNITRO.jl", "max_issues_repo_head_hexsha": "fa540b7311af788cc8b625525aebda196361efc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-08-04T17:01:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:10:31.000Z", "max_forks_repo_path": "examples/minlp1.jl", "max_forks_repo_name": "jump-dev/KNITRO.jl", "max_forks_repo_head_hexsha": "fa540b7311af788cc8b625525aebda196361efc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-07-27T15:33:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:32:34.000Z", "avg_line_length": 45.1609589041, "max_line_length": 110, "alphanum_fraction": 0.570258588, "num_tokens": 3782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7878430543160415}}
{"text": "# ---\n# title: 1137. N-th Tribonacci Number\n# id: problem1137\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Recursion\n# link: <https://leetcode.com/problems/n-th-tribonacci-number/description/>\n# hidden: true\n# ---\n# \n# The Tribonacci sequence Tn is defined as follows:\n# \n# T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn \\+ Tn+1 \\+ Tn+2 for n >= 0.\n# \n# Given `n`, return the value of Tn.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 4\n#     Output: 4\n#     Explanation:\n#     T_3 = 0 + 1 + 1 = 2\n#     T_4 = 1 + 1 + 2 = 4\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 25\n#     Output: 1389537\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `0 <= n <= 37`\n#   * The answer is guaranteed to fit within a 32-bit integer, ie. `answer <= 2^31 - 1`.\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "fa430472a6636720193100da558ed332bdc8cbee", "size": 868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1137.n-th-tribonacci-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/1137.n-th-tribonacci-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/1137.n-th-tribonacci-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": 16.6923076923, "max_line_length": 88, "alphanum_fraction": 0.5253456221, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7878042244388813}}
{"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, \u03b1; 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] - \u03b1*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  \u03c3::Float64\n  Measure(x::Real) = new(Float64(x), 0)\n  Measure(x::Real, \u03c3::Real) = new(Float64(x), \u03c3)\nend\n\nBase.show(io::IO, x::Measure) = print(io, string(x.x, \" \u00b1 \", x.\u03c3))\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.\u03c3 ^ 2 + b.\u03c3 ^ 2))\n-(a::Measure, b::Measure) = Measure(a.x - b.x, sqrt(a.\u03c3 ^ 2 + b.\u03c3 ^ 2))\n-(a::Measure) = Measure(-a.x, a.\u03c3)\n\n*(a::Measure, b::Measure) = begin\n  x = a.x * b.x\n  \u03c3 = sqrt(x ^ 2 * ((a.\u03c3 / a.x) ^ 2 + (b.\u03c3 / b.x) ^ 2))\n  Measure(x, \u03c3)\nend\n/(a::Measure, b::Measure) = begin\n  x = a.x / b.x\n  \u03c3 = sqrt(x ^ 2 * ((a.\u03c3 / a.x) ^ 2 + (b.\u03c3 / b.x) ^ 2))\n  Measure(x, \u03c3)\nend\n\n^(a::Measure, b::Float64) = begin\n  x = a.x ^ b\n  \u03c3 = abs(x * b * a.\u03c3 / a.x)\n  Measure(x, \u03c3)\nend\n\nBase.sqrt(a::Measure) = a ^ .5\n\nend  # module NumericError\n\nusing NumericError\n\n# x1 = 100 \u00b1 1.1\n# y1 = 50 \u00b1 1.2\n# x2 = 200 \u00b1 2.2\n# y2 = 100 \u00b1 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    \u03c3 ~ Uniform(0, 50)\n    \u03bc = f_parabola.(weight_s, a, b1, b2)\n    height ~ MvNormal(\u03bc, \u03c3)\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\u2082 * x\u00b2 + b\u2081 * x + a\nf'(x) = 2b\u2082 * x + b\u2081\n\nf(2) - f(-2) = 100\nf'(3) = 0\nb\u2082 < 0\n\nf(2) - f(-2) = (b\u2082 * 4 + b\u2081 * 2 + a) - (b\u2082 * 4 + b\u2081 * -2 + a)\n             = 4b\u2081 = 100\n            =>  b\u2081 =  25\nf'(3) = 2b\u2082 * 3 + b\u2081 = 0 => -b\u2081 = 6b\u2082\n     => b\u2082 = -25 / 6 \u2248 -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    \u03c3 ~ Exponential(5)\n    \u03bc = f_parabola.(weight_s, a, b1, b2)\n    height ~ MvNormal(\u03bc, \u03c3)\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": "using FourierTools, FFTW, PGFPlotsX\n\n\nN_low = 64\nx_min = 0.0\nx_max = 8*2\u03c0\n\nxs_low = range(x_min, x_max, length=N_low+1)[1:N_low]\nxs_high = range(x_min, x_max, length=5000)[1:end-1]\nf(x) = sin(0.5*x) + cos(x) + cos(2 * x) + sin(0.25*x)\narr_low = f.(xs_low)\narr_high = f.(xs_high)\n\nN = 1000\nxs_interp = range(x_min, x_max, length=N+1)[1:N]\narr_interp = resample(arr_low, N)\n\n\n\n\nplt1 = @pgf PGFPlotsX.Axis(\n    { \n        xmin=0, xmax=50, ymin=-3, ymax=4.5, \n        legend_pos=\"north east\", legend_entries={\"low sampling\", \"sinc interpolated\", \"high sampling\"},\n        width = \"10cm\",\n        height= \"6cm\",\n    },\n    \n    Plot({mark=\"x\", style=\"only marks\", color=\"green\",mark_options = {scale=1.3},\n        },\n        Table([xs_low, arr_low])\n    ),\n    \n    Plot({\"sharp plot\", color=\"red\"\n        },\n        Table([xs_interp, arr_interp])\n    ),\n    \n\n    Plot({\"sharp plot\", style=\"dashed\", color=\"blue\"\n        },\n        Table([xs_high, arr_high])\n    ),\n)\npgfsave(\"../../paper/figures/resampling.pdf\", plt1)\n", "meta": {"hexsha": "56c0faf626fab821424cec2e5daf8fd2d2b2e3da", "size": 1016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/paper/sinc_interpolation.jl", "max_stars_repo_name": "bionanoimaging/FourierTools.jl", "max_stars_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2021-03-30T23:15:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:20:15.000Z", "max_issues_repo_path": "examples/paper/sinc_interpolation.jl", "max_issues_repo_name": "bionanoimaging/FourierTools.jl", "max_issues_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-03-28T13:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T09:43:02.000Z", "max_forks_repo_path": "examples/paper/sinc_interpolation.jl", "max_forks_repo_name": "bionanoimaging/FourierTools.jl", "max_forks_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_forks_repo_licenses": ["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.0869565217, "max_line_length": 103, "alphanum_fraction": 0.5738188976, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7877176894621504}}
{"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  # \u6c42\u76ee\u6807\u51fd\u6570\u5bfc\u6570\n  \u0394f = x -> ForwardDiff.derivative(f, x);\n\n  xk = Base.float(x0);\n  xk_1 = Base.float(x0);\n\n  # \u6bd4\u673a\u5668\u7cbe\u5ea6\u5c11\u4e00\u4e2a\u6570\u91cf\u7ea7\n  epsilon = Base.eps(xk) * 10;\n\n  while true\n    xk_1 = xk - f(xk)/\u0394f(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\u03b2(p) = collect(range(-1, stop=1, length=p))\n\nfunction linregdata(n, p; \u03b2 = default\u03b2(p), V = eye(p), \u03bc = zeros(p), \u03c3 = 1.0)\n\tx = rand(D.MvNormal(\u03bc, V), n)'\n\ty = x * \u03b2 + \u03c3 * randn(n)\n\treturn x, y, \u03b2\nend\n\nfunction logregdata(n, p, sgn = true; \u03b2 = default\u03b2(p), V = eye(p), \u03bc = zeros(p))\n\tx = rand(D.MvNormal(\u03bc, V), n)'\n\ty = Float64[rand(D.Bernoulli(1 / (1 + exp(-\u03b7)))) for \u03b7 in x * \u03b2]\n\tif sgn\n\t\ty = 2y .- 1\n\tend\n\treturn x, y, \u03b2\nend\n\nfunction poissonregdata(n, p, \u03b2 = default\u03b2(p), V = eye(p), \u03bc = zeros(p))\n\tx = rand(D.MvNormal(\u03bc, V), n)'\n\ty = Float64[rand(D.Poisson(exp(\u03b7))) for \u03b7 in x * \u03b2]\n\treturn x, y, \u03b2\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 `\u03b3` from `\u03c1`\"\ngammasoc(\u03c1::Float64) = sqrt(1 - \u03c1^2) / \u03c1\n\n\"Computes `\u03c1` from `\u03b3`\"\nrhosoc(\u03b3::Float64)   = 1/ sqrt(1 + \u03b3^2)\n\n\"Computes `\u03f5` from `\u03bc` and `s^2`\"\nepssoc(\u03bc::Float64, s2::Float64) = phi(\u03bc/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\u03f5\"\nfunction modfunc(h\u03c31\u03b3::Float64, \u03bc1sqs2::Float64)\n    phi\u03f5 = phi(\u03bc1sqs2)\n    phiw = phi(h\u03c31\u03b3)\n    Z    = phi\u03f5 + phiw - 2*phi\u03f5*phiw\n    \n    Fw = (1 - 2phi\u03f5) * G(h\u03c31\u03b3) / Z \n    F\u03f5 = (1 - 2phiw) * G(\u03bc1sqs2) / Z\n\n    return (Fw, F\u03f5)\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": "# Find a stationary solution to the Gross-Pitaevskii equation by\n# minimizing the energy of a normalised wave function in a rotating\n# frame\n\n@testset \"Gross-Pitaveskii vortex\" begin\n    C = 10\n    \u03bc = 10\n    \u03a9 = 2*0.575\n    h = 0.2\n    N = 40\n\n    # Finite difference matrices.  \u2202 on left is \u2202y, \u2202' on right is \u2202x\n    \n    function op(stencil)\n        mid = (length(stencil)+1)\u00f72\n        diags = [i-mid=>fill(stencil[i],N-abs(i-mid)) for i = keys(stencil)]\n        BandedMatrix(Tuple(diags), (N,N))\n    end\n    \n    \u2202 = (1/h).*op([-1/60, 3/20, -3/4, 0, 3/4, -3/20, 1/60])\n    \u2202\u00b2 = (1/h^2).*op([1/90, -3/20, 3/2, -49/18, 3/2, -3/20, 1/90])\n\n    y = h/2*(1-N:2:N-1)\n    x = y'\n    z = Complex.(x,y)\n    V = r\u00b2 = abs2.(z)\n    \n    init = Complex.(exp.(-r\u00b2/2)/\u221a\u03c0)\n    init = conj.(z).*init./sqrt(1 .+ r\u00b2)\n    init ./= norm(init)\n    \n    # The energy that the steady state minimizes\n    function E(\u03c8)\n        L\u03c8 = -\u2202\u00b2*\u03c8-\u03c8*\u2202\u00b2+V.*\u03c8+C*abs2.(\u03c8).*\u03c8-1im*\u03a9*(y.*(\u03c8*\u2202')-x.*(\u2202*\u03c8))\n        sum(conj.(\u03c8).*L\u03c8)/norm(\u03c8)^2 |> real\n    end\n    \n    # The residual for the GPE, zero in a steady state\n    function rdl(\u03c8)\n        L\u03c8 = -\u2202\u00b2*\u03c8-\u03c8*\u2202\u00b2+V.*\u03c8+C*abs2.(\u03c8).*\u03c8-1im*\u03a9*(y.*(\u03c8*\u2202')-x.*(\u2202*\u03c8))\n        E = sum(conj.(\u03c8).*L\u03c8)/norm(\u03c8)^2 |> real\n        norm(L\u03c8-E*\u03c8)/norm(\u03c8)\n    end\n    \n    # break out real and imaginary parts, constraint is unit sphere\n    function reconstruct(xy)\n        n = length(xy) \u00f7 2\n        \u03c8 = xy[1:n] + 1im*xy[n+1:end]\n        m = sqrt(n) |> Int\n        \u03c8 = reshape(\u03c8,m,m)\n    end\n    \n    # norm taken from SOR solution\n    cost(xy) = E(20.31*reconstruct(xy))\n    \n    result = optimize(cost, [real.(init[:]); imag.(init[:])], NelderMead(manifold=Sphere()))\n    \u03c8\u2082 = 20.31*reconstruct(result.minimizer)\n    \n    # 3000 steps of successive over-relaxation gets a residual of 1e-3.\n    # The default settings in Optim should beat that.\n    \n    @test_broken rdl(\u03c8\u2082) < 1e-3\n\nend", "meta": {"hexsha": "1ba9fd4f615bd5365593c2c05bdfbade4dd920ff", "size": 1879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/multivariate/vortex.jl", "max_stars_repo_name": "thisrod/Optim.jl", "max_stars_repo_head_hexsha": "fced4d0873e2b5b279ac3b7b10f257c96c2edab4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-18T14:17:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T14:17:24.000Z", "max_issues_repo_path": "test/multivariate/vortex.jl", "max_issues_repo_name": "thisrod/Optim.jl", "max_issues_repo_head_hexsha": "fced4d0873e2b5b279ac3b7b10f257c96c2edab4", "max_issues_repo_licenses": ["MIT"], "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/multivariate/vortex.jl", "max_forks_repo_name": "thisrod/Optim.jl", "max_forks_repo_head_hexsha": "fced4d0873e2b5b279ac3b7b10f257c96c2edab4", "max_forks_repo_licenses": ["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.359375, "max_line_length": 92, "alphanum_fraction": 0.5385843534, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7875850590892407}}
{"text": "\nusing Dataframes, StatsBase\naapl = readtable(\"AAPL-Short,csv\");\n\nnaapl = size(aapl)[1]\nm1 = int(mean((aapl[:Volume]))); # => 6306547\n\nusing Match\nwts = zeros(naapl);\nfor i in 1:naapl\n    dt = aapl[:Date][i]\n    wts[i] = @match dt begin\n         r\"^2000\" => 1.0\n         r\"^2001\" => 2.0\n         r\"^2002\" => 4.0\n         _        => 0.0\n    end\nend;\n\nwv = WeightVec(wts);\nm2 = int(mean(aapl[:Volume], wv))\nmean(aapl[:Close])\nmean(aapl[:Close], wv)\ntrimmean(aapl[:Close], 0.1)\n\nstd(aapl[:Close])\nskewness(aapl[:Close])\nkurtosis(aapl[:Close])       \n", "meta": {"hexsha": "5bd8f2db0cb4b41692814304c341d34d05ce2ec5", "size": 548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 3/Chapter05/aapl-stats.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/Chapter05/aapl-stats.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/aapl-stats.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": 18.8965517241, "max_line_length": 45, "alphanum_fraction": 0.5638686131, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7875850583234059}}
{"text": "# L0 pseudo-norm (times a constant)\n\nexport NormL0\n\n\"\"\"\n**``L_0`` pseudo-norm**\n\n    NormL0(\u03bb=1)\n\nReturns the function\n```math\nf(x) = \u03bb\\\\cdot\\\\mathrm{nnz}(x)\n```\nfor a nonnegative parameter `\u03bb`.\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 \u03bb 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 \u21a6 \u03bb countnz(x)\"\nfun_params(f::NormL0) = \"\u03bb = $(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": "#################################################################\n#\n#    1st order derivation testing (loops)\n#\n#################################################################\n\n### vector setting\n    ex = quote\n        a = zeros(2)\n        for i in 1:2\n            a[i] = x\n        end\n        sum(a)\n    end\n    compare(ex, 1.)\n\n    b = [1,2,4,5]\n    ex = quote\n        a=zeros(1+4)\n        for i in 1:4\n            t = 4+3+2\n            a[i] = b[i]+t-x\n        end\n        sum(a)\n    end\n    compare(ex, 1.)\n\n    ex = quote\n        a=zeros(1+3)\n        for i in 1:4\n            t = 4+3+2\n            a[i] = b[i]*x+t\n        end\n        sum(a)\n    end\n    compare(ex, 1.)\n\n### vector accumulation\n    ex = quote\n        a = zeros(2)\n        for i in 1:2\n            a[i] += x\n        end\n        sum(a)\n    end\n    compare(ex, 1.)\n\n    ex = quote\n        a=zeros(1+3)\n        for i in 1:4\n            t = 4+3+2\n            a[i] += b[i]*x+t\n        end\n        sum(a)\n    end\n    compare(ex, 1.)\n\n### same var setting (vector)\n    ex = quote\n        a = zeros(2)\n        for i in 1:2\n            a[1] = x\n        end\n        sum(a)\n    end\n    compare(ex, 2.) \n\n    m.@deriv_rule %(x,y)      x     0\n    m.@deriv_rule %(x,y)      y     0\n    ex = quote\n        a = zeros(2)\n        for i in 1:4\n            a[1 + i % 2] = x\n        end\n        sum(a)\n    end\n    compare(ex, 1.)\n\n### same var accumulator (vector)\n    ex = quote\n        a = zeros(2)\n        for i in 1:2\n            a[1] += x\n        end\n        sum(a)\n    end\n    compare(ex, 2.)\n\n### same var setting (scalar)\n    ex = quote\n        a = 0.\n        for i in 1:4\n            a = 4*x\n        end\n        a\n    end\n    compare(ex, 3.)  \n\n    ex = quote\n        a = 0.\n        for i in 1:4\n            a = x\n        end\n        a\n    end\n    compare(ex, 3.) \n\n    ex = quote\n        a = 0.\n        for i in 1:length(x)\n            a = x[i]\n        end\n        a\n    end\n    compare(ex, [3., 2.]) \n    compare(ex, [1.])      \n    compare(ex, ones(10)) \n\n### same var accumulator (scalar)\n    ex = quote\n        a = 0.\n        for i in 1:4\n            a += x\n        end\n        a\n    end\n    compare(ex, 2.) \n\n    ex = quote\n        a = 0.\n        for i in 1:4\n            a += 2+x\n        end\n        a\n    end\n    compare(ex, 2.)\n\n    ex = quote\n        a = 0.\n        for i in 1:3\n            a += x^i\n        end\n        a\n    end\n    compare(ex, 2.) \n\n    ex = quote\n        a = 0.\n        for i in 1:length(x)\n            a += x[i]\n        end\n        a\n    end\n    compare(ex, [3., 2.]) \n    compare(ex, [1.])      \n    compare(ex, ones(10)) \n\n    ex = quote\n        a = 0.\n        for i in 1:length(x)\n            a += x[1]^i\n        end\n        a+1\n    end\n    compare(ex, [3., 2.])  \n    compare(ex, [1.])      \n    compare(ex, ones(10)) \n\n### nested loops\n    ex = quote\n        a=0\n        for i in 1:10\n            for j in 1:10\n                a += x\n            end\n        end\n        a\n    end\n    compare(ex, 0.1) \n\n    ex = quote\n        a=0\n        for i in 1:10\n            for j in 1:10\n                a += log(x) * sin(j)\n            end\n        end\n        a\n    end\n    compare(ex, 0.1)\n\n    ex = quote\n        a=0\n        for i in 1:10\n            for j in 1:10\n                a += (j < 4) * log(x) * sin(j)\n            end\n        end\n        a\n    end\n    compare(ex, 0.1) \n", "meta": {"hexsha": "f90047c1b09c04126e37cb239820511a6c0201b9", "size": 3369, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/loops.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ReverseDiffSource.jl-7f35dd7d-48ac-53c4-b315-575add349fcc", "max_stars_repo_head_hexsha": "429eb99c6d0e667ee64ee4c4310b3f73079b2ab2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2015-01-21T03:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-25T04:58:19.000Z", "max_issues_repo_path": "test/loops.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ReverseDiffSource.jl-7f35dd7d-48ac-53c4-b315-575add349fcc", "max_issues_repo_head_hexsha": "429eb99c6d0e667ee64ee4c4310b3f73079b2ab2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2015-01-05T08:18:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-13T15:01:14.000Z", "max_forks_repo_path": "test/loops.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ReverseDiffSource.jl-7f35dd7d-48ac-53c4-b315-575add349fcc", "max_forks_repo_head_hexsha": "429eb99c6d0e667ee64ee4c4310b3f73079b2ab2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2015-01-05T08:07:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-30T15:50:21.000Z", "avg_line_length": 16.6782178218, "max_line_length": 65, "alphanum_fraction": 0.3380825171, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7875462309150866}}
{"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": "using NumericalMethodsforEngineers, Test\n\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  )\n  xi = [0, 1//2, 1]\n  yi = [0, a, 1]\n  Y(x_) := LagrangePolynomial(xi, yi)\n  Println(Y(x))\nend\n=#\n\n@sym begin\n  ClearAll(xi, yi, Y, R, sol, ytilde)\n  xi = [0, 1//2, 1]\n  yi = [0, a, 1]\n  Y(x_) := LagrangePolynomial(xi, yi)\n  #\n  # Can be formulated as ytile(x) = F(x) + C1(a) * \u03a8(x)\n  #\n  # F(x_) := 2*x^2 - x\n  # C(a_) := -4a\n  # \u03a8(x_) := x^2 - x\n  #\n  #Y(x_) := F(x) + C(a)*\u03a8(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  SetJ(r, ToString(Simplify(R(x))))\nend\n\nprintln(\"\\n\\nExample 7.13: y'' = 3x + 4y, y(0)=0, y(1)=1\")\nprintln(\"Residual for Weighted Residual Method using 1 point Lagragian Polynomial\")\n@sym Println(\"\\nY(x) = \", Y(x), \"\\n\")\n@sym Println(\"R(x) = \", R(x), \"\\n\")\nprintln(\"( Example 7.13 gives: R = -4x^2*(2 + C1) + x*(1 + 4C1) + 2*(2 + C1) )\", \"\\n\")\n\nprintln(r)\n\n@eval f713(x, C1) = $(Meta.parse(r))\n\n@test f713(1, 2) == 4.0 + 2.0*2 - 3 - 4*(-1.0 + 2.0*1 + 2*(-1 + 1))\n", "meta": {"hexsha": "791689ac050213a74ddaa6f4bbf1d8c4d5732577", "size": 1461, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/WRM/Ex.7.13.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.13.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.13.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.564516129, "max_line_length": 86, "alphanum_fraction": 0.4633812457, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.787546226977153}}
{"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] \u2265 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\u03c0   6.2831853071795864769 big(\u03c0) * 2.0\n@irrational four\u03c0  12.566370614359172954 big(\u03c0) * 4.0\n@irrational half\u03c0  1.5707963267948966192 big(\u03c0) * 0.5\n@irrational quart\u03c0 0.7853981633974483096 big(\u03c0) * 0.25\n\n@irrational inv\u03c0     0.31830988618379067154 inv(big(\u03c0))\n@irrational twoinv\u03c0  0.63661977236758134308 big(inv\u03c0) * 2.0\n@irrational fourinv\u03c0 1.27323954473516268615 big(inv\u03c0) * 4.0\n@irrational inv2\u03c0    0.159154943091895335769 big(inv\u03c0) * 0.5\n@irrational inv4\u03c0    0.079577471545947667884 big(inv\u03c0) * 0.25\n\n@irrational sqrt2     1.4142135623730950488 sqrt(big(2.0))\n@irrational sqrt3     1.7320508075688772935 sqrt(big(3.0))\n@irrational sqrt\u03c0     1.7724538509055160273 sqrt(big(\u03c0))\n@irrational sqrt2\u03c0    2.5066282746310005024 sqrt(big(\u03c0) * 2.0)\n@irrational sqrt4\u03c0    3.5449077018110320546 sqrt(big(\u03c0) * 4.0)\n@irrational sqrthalf\u03c0 1.2533141373155002512 sqrt(big(0.5)*\u03c0)\n\n@irrational invsqrt2  0.7071067811865475244 inv(big(sqrt2))\n@irrational invsqrt2\u03c0 0.3989422804014326779 inv(big(sqrt2\u03c0))\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": "module GetSpectrum\n\nusing DSP \nusing FFTW \n\nexport getSpectrum\nexport getWaterfall \n#greet() = print(\"Hello World!\")\n\nfunction getSpectrum(fs,sig;N=nothing)\n\tif isnothing(N) \n\t\tN = length(sig);\n\tend\n    freqAx = collect(((0:N-1)./N .- 0.5)*fs);\n\tss\t   = @view sig[1:N];\n\ty\t   = 10*log10.(abs2.(fftshift(fft(ss))));\n\treturn (freqAx,y);\nend\ngetSpectrum(sig) = getSpectrum(1,sig);\n\n\n\nfunction getWaterfall(fe,sig;sizeFFT=1024)\n    nbSeg   = length(sig) \u00f7 sizeFFT;\n    ss      =  @views sig[1:nbSeg*sizeFFT];\n    ss      = reshape(ss,sizeFFT,nbSeg)\n    sMatrix = zeros(Float64,sizeFFT,nbSeg);\n    for iN = 1 : 1 : nbSeg \n        sMatrix[:,iN] = abs2.(fftshift(fft(ss[:,iN])));\n    end\n    fAx = collect(((0:1:sizeFFT-1)./sizeFFT .- 0.5) .* fe);\n    tAx = (0:nbSeg-1) * (sizeFFT/fe);\n    return tAx,fAx,sMatrix;\nend\ngetWaterfall(sig;sizeFFT=1024) = getWaterfall(1,sig;sizeFFT=sizeFFT);\nend # module\n", "meta": {"hexsha": "ecad9745251c33a354e085572a2f30fe705df158", "size": 894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GetSpectrum.jl", "max_stars_repo_name": "JuliaTelecom/AbstractSDRsFMReceiver.jl", "max_stars_repo_head_hexsha": "2e10a86ee50c766dd303ffec6fbd64ab8be3bafb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GetSpectrum.jl", "max_issues_repo_name": "JuliaTelecom/AbstractSDRsFMReceiver.jl", "max_issues_repo_head_hexsha": "2e10a86ee50c766dd303ffec6fbd64ab8be3bafb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GetSpectrum.jl", "max_forks_repo_name": "JuliaTelecom/AbstractSDRsFMReceiver.jl", "max_forks_repo_head_hexsha": "2e10a86ee50c766dd303ffec6fbd64ab8be3bafb", "max_forks_repo_licenses": ["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.1621621622, "max_line_length": 69, "alphanum_fraction": 0.6286353468, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369555, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.787504258884951}}
{"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 \u2208 IntervalDomain(0.0,1.0),\n               x \u2208 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] \u2248 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 \u2208 IntervalDomain(0.0,1.0),\n               x \u2208 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] \u2248 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 \u2208 IntervalDomain(0.0,1.0),\n               x \u2208 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] \u2248 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) \u2265 degree(g) \n            h = Polynomial( (leading(f) \u00f7 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) \u2265 degree(g) \n        h = (leading(f) \u00f7 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\u00f7(num::Polynomial, den::Polynomial)  = (p::Int) -> first(divide(num,den)(p)) \n\u00f7(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    \u03f5_abs\n    \u03f5_rel\n    \u03f5_grad\n    Termination(;\n        max_iter = 10_000,\n        \u03f5_abs = eps(),\n        \u03f5_rel = eps(),\n        \u03f5_grad = eps()) =\n        new(max_iter, \u03f5_abs, \u03f5_rel, \u03f5_grad)\n    Termination(\u03f5;\n        max_iter = 10_000) =\n        new(max_iter, \u03f5, \u03f5, \u03f5)\nend\n\nmutable struct TerminationConditions\n    abs\n    rel\n    grad\n    TerminationConditions(term::Termination) = \n    new((fx, fx_next)->fx - fx_next < term.\u03f5_abs,\n        (fx, fx_next)->fx - fx_next < term.\u03f5_abs * abs(fx),\n        \u2207fx_next->norm(\u2207fx_next) < term.\u03f5_grad)\nend\n\nfunction descent_until(term::Termination, descent_method, f, \u2207f, X, trace)\n    term_cond = TerminationConditions(term)\n    for _ = 1:term.max_iter\n        x = X[:, end]\n        x_next = descent_method(f, \u2207f, x)\n        if trace\n            X = hcat(X, x_next)\n        else\n            X = x_next\n        end\n        fx, fx_next, \u2207fx_next = f(x), f(x_next), \u2207f(x_next)\n        if term_cond.abs(fx, fx_next) ||\n            term_cond.rel(fx, fx_next) ||\n            term_cond.grad(\u2207fx_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, \u2207f, x_0; term = Termination(), trace = false)\n    descent_until(term, descent_step_maxgd, f, \u2207f, x_0, trace)\nend\n\nfunction descent_step_maxgd(f, \u2207f, 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 = \u2207f(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    \u03b1\n    GradientDescent(; \u03b1 = 0.001) = new(\u03b1)\nend\n\nfunction search(params::GradientDescent, f, \u2207f, x_0; term = Termination(), trace = false)\n    descent_step = (f, \u2207f, x)->descent_step_gd(params.\u03b1, f, \u2207f, x)\n    descent_until(term, descent_step, f, \u2207f, x_0, trace)\nend\n\nfunction descent_step_gd(\u03b1, f, \u2207f, x)\n    \"\"\"\n    Gradient Descent\n    Algorithm 5.1\n\n    A step of a gradient descent algorithm with fixed learning rate \u03b1.\n    \"\"\"\n    g = \u2207f(x)\n    x - \u03b1 * 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, \u2207f, x_0; term = Termination(), trace = false)\n    state = CGDProblemState(size(x_0))\n    descent_step = (f, \u2207f, x)->descent_step_cgd!(state, f, \u2207f, x)\n    descent_until(term, descent_step, f, \u2207f, x_0, trace)\nend\n\nfunction descent_step_cgd!(state, f, \u2207f, x)\n    \"\"\"\n    Conjugate Gradient Descent\n    Algorithm 5.2\n\n    https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient_method\n    \"\"\"\n    g = \u2207f(x)\n    d = direction_cgd(g, state.g, state.d)\n    state.g = g\n    state.d = d\n    search(StrongBacktracking(), f, \u2207f, 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    \u03b2_PR = (g' * (g - gm1)) / (gm1'gm1)\n    \u03b2 = max(\u03b2_PR, 0)\n    -g + \u03b2 * 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": "export read_resp_from_sacpz\n\n# Set the response to acceleration\nconst flag = 2\n\nfunction read_resp_from_sacpz(input_sacpz::String, sampling_rate::Float64, N::Int)\n    read_zeros = false\n    read_poles = false\n    zeros = Array{Complex{Float64}}(undef, 1)\n    poles = Array{Complex{Float64}}(undef, 1)\n    zeros_cnt, poles_cnt = 1, 1\n    constant = .0\n    \n    lines = readlines(input_sacpz)    \n    for line in lines\n        contents = split(line, \" \")\n        if contents[1] == \"CONSTANT\"\n            constant = parse(Float64, contents[2])\n        elseif contents[1] == \"ZEROS\"\n            zeros_size = parse(Int64, contents[2])\n            zeros = Base.zeros(Complex{Float64}, zeros_size)\n            read_zeros = true\n            read_poles = false\n        elseif contents[1] == \"POLES\"\n            poles_size = parse(Int64, contents[2])\n            poles = Base.zeros(Complex{Float64}, poles_size)\n            read_zeros = false\n            read_poles = true\n        else\n            # Seems that some SACPZ file will let Julia pase as follows:\n            # \"<real>\", \"\", \"<imag>\"\n            num = parse(Float64, contents[1]) + parse(Float64, contents[3]) * im \n            if read_zeros == true\n                zeros[zeros_cnt] = num \n                zeros_cnt += 1\n            elseif read_poles == true\n                poles[poles_cnt] = num\n                poles_cnt += 1\n            end\n        end\n    end\n  \n    return create_resp(poles, zeros, constant, sampling_rate, N)\nend\n\nfunction create_resp(poles::Vector{Complex{Float64}}, \n                     zeros::Vector{Complex{Float64}},\n                     constant::Float64,\n                     sampling_rate::Float64,\n                     N::Int)\n    freqs = Vector{Float64}(undef, N)\n    delta = 1. / sampling_rate\n    total_duration = delta * N\n    for i = 1:(div(N, 2) + 1)\n        freqs[i] = i / total_duration\n    end\n    for i = (div(N, 2) + 1):N\n        freqs[i] = -(N - i) / total_duration\n    end\n\n    instrument_response = Vector{Complex{Float64}}(undef, N)\n    for i = 1:N\n        numerator = 1. + 0. * im\n        denominator = 1. + 0. * im\n        omega = 2 * \u03c0 * freqs[i]\n        i_omega = 0. + omega * im\n\n        for j = 1:(size(zeros, 1) - flag)\n            numerator *= (i_omega - zeros[j])\n        end\n        for j = 1:size(poles, 1)\n            denominator *= (i_omega - poles[j])\n        end\n\n        instrument_response[i] = constant * numerator / denominator\n    end\n\n    return instrument_response\nend\n", "meta": {"hexsha": "af5e8569f2dc858f946e4d52c657740905b5fe70", "size": 2492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/read_response.jl", "max_stars_repo_name": "Cuda-Chen/SeisPDF.jl", "max_stars_repo_head_hexsha": "fd8a865c19ea1b9caef71ef7bae900d3cc99b070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-29T08:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:18:49.000Z", "max_issues_repo_path": "src/read_response.jl", "max_issues_repo_name": "Cuda-Chen/SeisPDF.jl", "max_issues_repo_head_hexsha": "fd8a865c19ea1b9caef71ef7bae900d3cc99b070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/read_response.jl", "max_forks_repo_name": "Cuda-Chen/SeisPDF.jl", "max_forks_repo_head_hexsha": "fd8a865c19ea1b9caef71ef7bae900d3cc99b070", "max_forks_repo_licenses": ["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.15, "max_line_length": 82, "alphanum_fraction": 0.5453451043, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7874488511020366}}
{"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    \u0394 = laplacian_matrix(g)[2:nv(g),2:nv(g)]\n    return round(det(\u0394))\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": "using PlainLinearAlgebra\nimport LinearAlgebra\nusing Test\n\n@testset \"diagonal\" begin\n    for d in (0, 1, 2, 3, 10)\n        m = rand(d, d)\n        mdiagonal = diagonal(m)\n        mdiag = LinearAlgebra.diag(m)\n        @test mdiagonal == mdiag\n        @test sum(mdiagonal) \u2248 sum(mdiag)\n        @test Base.mightalias(mdiagonal, m)\n        d0 = d - 1\n        for k in -d0:d0\n            @test diagonal(m, k) == LinearAlgebra.diag(m, k)\n        end\n    end\nend\n\n@testset \"properties\" begin\n    for d in (1, 2, 3, 10)\n        for T in (Int, Float64, ComplexF64)\n            m = rand(T, d, d)\n            dm = diagonal(m)\n            @test eltype(dm) == T\n            @test Base.elsize(dm) == sizeof(T)\n            @test size(dm) == (d,)\n            @test size(dm, 1) == d\n            @test size(dm, 2) == 1\n        end\n    end\nend\n\n@testset \"diagonal setindex!\" begin\n    for d in (1, 2, 3, 10)\n        m = rand(d, d)\n        md = diagonal(m)\n        md[1] = md[1] * 2\n        @test md[1] == m[1,1]\n    end\nend\n\n@testset \"identity matrix\" begin\n    for d in (0, 1, 2, 3, 10)\n        @test idmat(d) == idmat(Float64, d)\n        for T in (Int, Rational{Int})\n            @test isa(idmat(T, d), Matrix{T})\n        end\n    end\nend\n", "meta": {"hexsha": "638d6045af298445b2d3282af2aaab3be330634f", "size": 1219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaTagBot/PlainLinearAlgebra.jl", "max_stars_repo_head_hexsha": "7306ccfc2b2b12ad9de7b7189863f62799a9680b", "max_stars_repo_licenses": ["MIT"], "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": "JuliaTagBot/PlainLinearAlgebra.jl", "max_issues_repo_head_hexsha": "7306ccfc2b2b12ad9de7b7189863f62799a9680b", "max_issues_repo_licenses": ["MIT"], "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": "JuliaTagBot/PlainLinearAlgebra.jl", "max_forks_repo_head_hexsha": "7306ccfc2b2b12ad9de7b7189863f62799a9680b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:41:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:41:45.000Z", "avg_line_length": 23.9019607843, "max_line_length": 60, "alphanum_fraction": 0.4971287941, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.7874388210627339}}
{"text": "using AlphaShapes\ninclude(\"../src/utils.jl\")\nusing Plots\nusing Main.AlphaShapes\nusing LinearAlgebra\nusing Random\nRandom.seed!(31415926535897)\n\nN = 1000\nr1 = 0.75\nr2 = 2.0\nX = randn(N,2)\nind = [((norm(X[i,:])>r1) + (norm(X[i,:])<r2)) == 2 for i in 1:size(X,1)]\nX = X[ind.==true,:]\n# normally distributed points with a whole in the middle\np1 = scatter(X[:,1],X[:,2],label=\"\",aspect_ratio=:equal)\n\nT = AlphaShapes.GetDelaunayTriangulation(X);\np1 = scatter(X[:,1],X[:,2],label=\"\",aspect_ratio=:equal)\n[DrawTri!(T[i,:,:]) for i in 1:size(T,1)]\nplot!(title=\"Delaunay Triangulation\")\n\nA = AlphaShape(X);\np2 = scatter(X[:,1],X[:,2],label=\"\",aspect_ratio=:equal)\n[DrawTri!(A[i,:,:]) for i in 1:size(A,1)]\nplot!(title=\"Optimum Alpha Shape Triangulation\")\n\np = plot(p1,p2,size=(900,300))\nsavefig(p,\"Example.png\")\n", "meta": {"hexsha": "d8afb1943f9e58aacfe16263eaca2ea936021a76", "size": 802, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/examples.jl", "max_stars_repo_name": "itsdfish/AlphaShapes.jl", "max_stars_repo_head_hexsha": "4ff0bbaeca2d8f8da82580020a6fd8b37d6316df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-08-28T16:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T04:08:22.000Z", "max_issues_repo_path": "examples/examples.jl", "max_issues_repo_name": "itsdfish/AlphaShapes.jl", "max_issues_repo_head_hexsha": "4ff0bbaeca2d8f8da82580020a6fd8b37d6316df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-08-27T17:26:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T12:16:58.000Z", "max_forks_repo_path": "examples/examples.jl", "max_forks_repo_name": "itsdfish/AlphaShapes.jl", "max_forks_repo_head_hexsha": "4ff0bbaeca2d8f8da82580020a6fd8b37d6316df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T09:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T09:37:37.000Z", "avg_line_length": 26.7333333333, "max_line_length": 73, "alphanum_fraction": 0.6608478803, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7874327087068365}}
{"text": "\"\"\"\n    gpw(\u03b6, \u03c6; k=1)\n    \nClosure that defines a generalized plane wave in polar coordinates.\n\nThe closure captures the values of the evanescence parameter ``\u03b6``, the\nangle ``\u03c6`` and the wavenumber ``k``.\nIt does not include any normalization.\nThe function can then be evaluated at any ``(r,\u03b8)`` point.\n\nThe generalized plane wave in polar coordinates is defined by\n```math\n\u03d5 := (r,\u03b8) \u21a6 e^{\u0131 k \\\\mathbf{d} \u22c5 \\\\mathbf{x}},\n```\nwhere\n```math\n\\\\mathbf{d} = (\\\\cos[\u03c6+\u0131\u03b6], \\\\sin[\u03c6+\u0131\u03b6]),\n\\\\qquad\\\\text{and}\\\\qquad\n\\\\mathbf{x} = (r \\\\cos \u03b8, r\\\\sin \u03b8).\n```\n\"\"\"\nfunction gpw(\u03b6,\u03c6;k=1)\n    d = [cos(\u03c6+im*\u03b6), sin(\u03c6+im*\u03b6)] # Direction\n    return (r,\u03b8) -> exp(im * k * [r*cos(\u03b8), r*sin(\u03b8)] \u22c5 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``(\u03b6_j,\u03c6_j)`` and associated weights ``\u03c9_j`` corresponding to the generalized\nplane waves, see [`gpw`](@ref)\n```math\n\u03d5_j := (r,\u03b8) \u21a6 e^{\u0131 k \\\\mathbf{d}_j \u22c5 \\\\mathbf{x}},\n```\nwhere\n```math\n\\\\mathbf{d}_j = (\\\\cos[\u03c6_j+\u0131\u03b6_j], \\\\sin[\u03c6_j+\u0131\u03b6_j]),\n\\\\qquad\\\\text{and}\\\\qquad\n\\\\mathbf{x} = (r \\\\cos \u03b8, r\\\\sin \u03b8).\n```\nApproximations are constructed in the form of\n```math\n(r, \u03b8) \u21a6 \\\\sum_j \u03be_j \u03c9_j \u03d5_j(r, \u03b8),\n```\nwhere ``(\u03be_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, \u03b8) -> w * gpw(y...;k=k)(r, \u03b8) 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\u03b8_n := 2\u03c0 s / R, \\\\qquad n = 0,\u2026,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\u03c0 * 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": "# code for Video 4.3:\r\nfname = \"iris.csv\"\r\nusing DataFrames\r\ndata = readtable(fname, separator = ',')\r\n\r\n### scatter plots:\r\nusing Gadfly\r\nset_default_plot_size(15cm, 15cm/golden)\r\np = plot(data, x=\"sepal_width\", y=\"sepal_length\", Geom.point,\r\n         Guide.xlabel(\"Sepal Width\"),  \r\n         Guide.ylabel(\"Sepal Length\"), \r\n         Guide.title(\"Scatterplot of Sepal Length versus Width\") )\r\ndraw(PDF(\"Length_versus_Width.pdf\", 14cm, 10cm), p)\r\n\r\ncor(data[:sepal_width], data[:sepal_length]) # -0.10936924995064931\r\n\r\n# add colour dimension:\r\np = plot(data, x=\"sepal_width\", y=\"sepal_length\", color=\"species\",\r\n         Guide.xlabel(\"Sepal Width\"),  \r\n         Guide.ylabel(\"Sepal Length\"), \r\n         Guide.title(\"Scatterplot of Sepal Length versus Width\") )\r\ndraw(PDF(\"Length_versus_Width_Color.pdf\", 14cm, 10cm), p)\r\n\r\ncor(data[1:50, :sepal_width], data[1:50, :sepal_length]) # 0.7467803732639265\r\ncor(data[51:100, :sepal_width], data[51:100, :sepal_length]) # 0.5259107172828241\r\ncor(data[101:150, :sepal_width], data[101:150, :sepal_length]) # 0.4572278163941129\r\n\r\n### linear regression:\r\nx = convert(Array, data[1:50, :sepal_width])\r\ny = convert(Array, data[1:50, :sepal_length])\r\na, b = linreg(x, y)\r\n# 2-element Array{Float64,1}:\r\n#  2.64466\r\n#  0.690854\r\n# sepal_length = 2.64466 + 0.690854 * sepal_width\r\n\r\n# adding a linear regression fit to the plot:\r\nusing Winston\r\npl = plot(data[1:50, :sepal_width], data[1:50, :sepal_length], \"g^\") # use the symbol for green triangles\r\ns = Slope(0.690854, (0, 2.64466), colorant=\"blue\", linekind=\"dashed\") # this is the linear fit\r\nadd(pl, s)\r\ndisplay(pl) # not necessary in the REPL\r\nsavefig(pl, \"Winston_Linreg.png\")\r\n\r\nusing PyPlot\r\nx = convert(Array, data[1:50, :petal_width])\r\ny = convert(Array, data[1:50, :petal_length])\r\na, b = linreg(x, y)\r\n# 2-element Array{Float64,1}:\r\n#  1.34304\r\n#  0.495739\r\ncor(x, y) # correlation = 0.30630821115803575 \r\nplot(x, y, \"o\")\r\nplot(x, [a+b*i for i in x])\r\n\r\n### histogram:\r\nGadfly.plot(data, x=\"petal_width\", Geom.histogram(bincount=30))\r\n\r\n### boxplot with Gadfly:\r\nGadfly.plot(data, x = \"species\", y = \"sepal_length\", Geom.boxplot)", "meta": {"hexsha": "716fc9215a926918f201aedc6c621ec52135444a", "size": 2130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Section 4/4_3.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_3.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_3.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": 35.5, "max_line_length": 106, "alphanum_fraction": 0.6685446009, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7874091609496626}}
{"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 \u211d\u1d3a. In abstract terms, an *element* \u03c4 is a subset of \u211d\u1d3a described\n# by \n# * a reference element ``\\tau \\subset \\mathbb{R}^N``\n# * a *push-forward map* \u03c7 : \u03c4\u0302 \u2192 \u03c4 \u2282 \u211d\u1d3a.\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 \u2208 domain(el)`.\n# - `jacobian(u)` : evaluate the jacobian of the parametrization at (parametric)\n#   coordinate `u \u2208 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\u2080, \u03d5, fs)\r\n    s = A.*sin.(2\u03c0*f\u2080*t .+ \u03d5)\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\u2080 = 1.0\r\n    \u03d5 = 0.0\r\n\r\n    # Do initial plot with default values\r\n    doplots(t, A, f\u2080, \u03d5, 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\u2080, \u03d5, fs)\r\n        end\r\n        # Frequency slider.\r\n        if event == sliF\r\n            f\u2080_g = gtk_send(\"gtk_range_get_value $sliF\")\r\n            f\u2080 = parse(Float32, f\u2080_g)\r\n            P = doplots(t, A, f\u2080, \u03d5, fs)\r\n        end\r\n        # \u03d5 slider.\r\n        if event == sliP\r\n            \u03d5_g = gtk_send(\"gtk_range_get_value $sliP\")\r\n            \u03d5 = parse(Float32, \u03d5_g)\r\n            P = doplots(t, A, f\u2080, \u03d5, 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, \u03bc and \u03c3\nfunction featureNormalize(x)\nrows = size(x,1)\ncols = size(x,2)\n\n\u03bc = mean(x,1)\n\u03c3 = 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] - \u03bc[i]) / \u03c3[i];\n\tend\nend\n\n(xNorm, \u03bc, \u03c3)\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, \u03bc, \u03c3) = featureNormalize(x);\n\n# Add intercept term to x\nx = [ones(m,1) x]\n\n#### Run Gradient Descent\n\u03b1 = 0.001\nnumIter = 4000\n\u03b8 = zeros(3,1)\njHist = zeros(numIter, 1)\n\nfor i in 1:numIter\n  # next theta\n  \u03b8 = \u03b8 - (\u03b1/m) * (x' * ((x*\u03b8)-y))\n  # compute cost\n  jHist[i] = sum((x*\u03b8-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-\u03bc[1])/\u03c3[1], (3-\u03bc[2])/\u03c3[2]]' * \u03b8\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, \u03a8::AbstractMatrix, \n    K::Int = 2, S::Int = 1; \n    max_iter::Int = 100, \u03f5::Real = eps())\n\n\t# Get the dimensions\n\tm = length(y0)\n\tm_psi, n = size(\u03a8)\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\u03c8 = deepcopy(\u03a8)\n    # Inplace\n\tnormalize!.(eachcol(\u03c8), 2)\n\t\n\t\n\t# Preconditioning\n\tP = \u03c8'pinv(\u03c8*\u03c8')\n\t# New matrix\n\t\u03c8 = P*\u03c8\n\ty = P*y0\n\t# Iteration\n\titers = 0\n\t\n\t# Support\n\t\u039b = 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 .= \u03c8'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\u039b[idx] .= true\n\t\t# Update the coefficients\n\t\tu[\u039b] .= (y' / \u03c8')[1, \u039b]\n\t\t# Update r\n\t\tr .= y - \u03c8*u\n\t\t# Convergence\n\t\t(norm(r,2) < \u03f5 || sum(\u039b) >= K) && break\n\tend\n\t\n    # Last time to get the right coefficients\n\tu[\u039b] .= (y0' / \u03a8')[1, \u039b]\n    \n\treturn u\nend\n\n## Test data\nRandom.seed!(1111) # Lucky\nx\u0302 = sprandn(Float64, 100, 0.1)\nk_opt = Int(norm(x\u0302, 0))\nA = randn(Float64, 300, 100)\ny = A*x\u0302\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\u0303 = sprandn(Float64, 100, i)\n\ty\u0303 = A*x\u0303\n\tnorm(gomp(y\u0303, A, 50, 1, \u03f5 = 0.01), 0), norm(x\u0303, 0)\nend\n\ngr()\npl_1 = scatter(x\u0302, 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 ReachabilityAnalysis: logarithmic_norm\n\n@testset \"Logarithmic norm\" begin\n\n    # Example 1\n    A = [1 2; 3 -4]\n\n    @test logarithmic_norm(A, 1) == 4\n    @test logarithmic_norm(A, Inf) == 3\n\n    # Example 2 (see Example 2 in \"Explicit Error Bounds for Carleman Linearization.\n    # Marcelo Forets and Amaury Pouly (2018)\").\n    A = [0 1; -1 -2]\n    Aop2 = kron(A, A)\n\n    @test logarithmic_norm(A, Inf) == 1\n    @test logarithmic_norm(Aop2, Inf) == 9;\n\n    @test logarithmic_norm(A, 1) == 1\n    @test logarithmic_norm(Aop2, 1) == 9\n\n    @test logarithmic_norm(A, 2) == 0\n    @test logarithmic_norm(Aop2, 2) \u2248 4.23606797749979\nend\n", "meta": {"hexsha": "9148fad83180538b0f6c3a6b7ec6460d7f9944ab", "size": 636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 25.44, "max_line_length": 84, "alphanum_fraction": 0.6399371069, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8418256393148981, "lm_q1q2_score": 0.7873986721111239}}
{"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": "# Test for GaussRadau()\n\nn = 1\nx, w = gaussradau(n)\n@test x[1] \u2248 -1.\n@test w[1] \u2248 2.\n\nn = 2\nx, w = gaussradau(n)\n@test x[1] \u2248 -1.\n@test x[2] \u2248 1/3\n@test w[1] \u2248 .5\n@test w[2] \u2248 1.5\n\ntol = 1e-14\nn = 42\nntests = 4\nx, w = gaussradau(n)\n@test length(x) == n && length(w) == n\n@test abs(x[37] - 0.908847278001044) < tol\n@test abs(w[37] - 0.031190846817016) < tol\n@test x[1] == -1\n\n@test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\n", "meta": {"hexsha": "c6c8bd6c73fa48852f1a12159e8ed1312321792e", "size": 414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gaussradau.jl", "max_stars_repo_name": "timueh/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_stars_repo_licenses": ["MIT"], "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_gaussradau.jl", "max_issues_repo_name": "timueh/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_issues_repo_licenses": ["MIT"], "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_gaussradau.jl", "max_forks_repo_name": "timueh/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_forks_repo_licenses": ["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.56, "max_line_length": 42, "alphanum_fraction": 0.5458937198, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.787331475872572}}
{"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\u03b7  = 0.58\n\u03bb = 0.93\n\u03b1 = 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\u039b(x) = forward_logs(M,x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x,rep(d)...), \u039b(x)),1)\n#\n# Setup & Optimize\nprint(\"--- Douglas\u2013Rachford with \u03b7: $(\u03b7) and \u03bb: $(\u03bb) ---\\n\")\ncost(x) = fidelity(x) + \u03b1*prior(x)\nN = PowerManifold(pixelM, NestedPowerRepresentation(),5)\nprox1 = (\u03b7,x) -> cat( prox_distance(M,\u03b7,f,get_component(N,x,1)), prox_parallel_TV(M,\u03b1*\u03b7,get_component(N,x,2:5)), dims=1)\nprox2 = (\u03b7,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    \u03bb = i -> \u03b7, \u03b1 = i -> \u03bb, # 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)-\u03b1$(replace(string(\u03b1), \".\" => \"-\")).asy\"; data=y, render=4, scaleAxes=(7.5,7.5,7.5) )\n    render_asymptote(resultsFolder * experimentName * \"img-result-$(numIter)-\u03b1$(replace(string(\u03b1), \".\" => \"-\")).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, \u03b1=0.85, n=100, \u03f5=1.0e-6)\n\nCalculate the [PageRank](https://en.wikipedia.org/wiki/PageRank) of the\ngraph `g` parameterized by damping factor `\u03b1`, number of iterations \n`n`, and convergence threshold `\u03f5`. 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    \u03b1=0.85, \n    n::Integer=100,\n    \u03f5=1.0e-6\n    ) where U <: Integer\n    \u03b1_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        \u03b1_div_outdegree[v] = (\u03b1/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 - \u03b1 + \u03b1 * 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] * \u03b1_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 * \u03f5)\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": "# One dimensional wave equation\n# Test systems of conservation laws\n\n@testset \"1D Sytems Algorithms\" begin\n\nusing ConservationLawsDiffEq\nusing OrdinaryDiffEq\nCL = ConservationLawsDiffEq\n\nCFL = 0.45\nTend = 1.0\ncc = 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*\u03c0*x), 0.0]\n\nNflux(\u03d5l, \u03d5r) = 0.5*(f(\u03d5l)+f(\u03d5r))\nexact_sol(x::Float64, t::Float64) = hcat(0.5*(sin.(4*\u03c0*(-t+x))+sin.(4*\u03c0*(t+x))),\n0.5*(sin.(4*\u03c0*(-t+x))-sin.(4*\u03c0*(t+x))))\n\nmesh = Uniform1DFVMesh(20, [-1.0, 1.0])\n\nfunction get_problem(alg::CL.AbstractFVAlgorithm, use_threads, mesh, Tend,CFL)\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 = use_threads,numvars = 2)\n\n  #Compute discrete initial data\n  u0 = getInitialState(mesh,f0,use_threads = true)\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\nfunction test_scheme(alg, maxerror, threaded_mode=true)\n  println(\"Testing \",split(\"$alg\",\"(\")[1],\": \")\n  prob,cb,dt = get_problem(alg, false, mesh, Tend,CFL)\n  @time sol = solve(prob,SSPRK22(); dt = dt, callback = cb, save_everystep = false)\n  @test get_L1_error(exact_sol, fv_solution(sol,mesh)) < maxerror\n  if threaded_mode\n    println(\"in threaded mode: \")\n    prob,cb,dt = get_problem(alg, true, mesh, Tend,CFL)\n    @time sol1 = solve(prob,SSPRK22(); dt = dt, callback = cb, save_everystep = false)\n    @test get_L1_error(exact_sol, fv_solution(sol1,mesh)) \u2248 get_L1_error(exact_sol, fv_solution(sol,mesh))\n  end\nend\n\n# Test Schemes error\ntest_scheme(FVSKTScheme(), 1.16)\ntest_scheme(FVTecnoScheme(Nflux;order=2), 1.152, false) \ntest_scheme(FVTecnoScheme(Nflux;order=3), 1.14, false) \ntest_scheme(FVTecnoScheme(Nflux;order=5), 0.92, false)\ntest_scheme(LaxFriedrichsScheme(), 1.16)\ntest_scheme(LocalLaxFriedrichsScheme(), 1.16, false)\ntest_scheme(GlobalLaxFriedrichsScheme(), 1.16)\ntest_scheme(LaxWendroffScheme(), 37.0)    #way off\ntest_scheme(LaxWendroff2sScheme(), 1.152)\ntest_scheme(FVCompWENOScheme(), 0.94)\ntest_scheme(FVCompMWENOScheme(), 0.68)\ntest_scheme(FVSpecMWENOScheme(), 0.68, false)\ntest_scheme(FVCUScheme(), 1.16)\ntest_scheme(FVDRCUScheme(), 1.17)\ntest_scheme(FVDRCU5Scheme(), 0.48)\n\nend\n", "meta": {"hexsha": "aba4283dba509e8d33c103c3df6ebe26dd217647", "size": 2459, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test2.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": "test/test2.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": "test/test2.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": 33.6849315068, "max_line_length": 106, "alphanum_fraction": 0.7132980887, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7872901880178341}}
{"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 `\u0192`, also called the Coriolis parameter or Coriolis\n# coefficient, is equal to twice the rotation rate `\u03a9` of the Earth multiplied\n# by the `sine` of the latitude `\u03c6`.\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\u03c0, kappa=1e-2, nsteps=1000, dev=CPU())\n   \u03c4 = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * \u03c4 # 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, \u03c3 = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2\u03c3^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant \u03ba\n  tfinal = nsteps*dt\n  \u03c3t = sqrt(2*kappa*tfinal + \u03c3^2)\n  cfinal = @. c0ampl*\u03c3/\u03c3t * exp(-g.x^2/(2*\u03c3t^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\u03c0, Ly=4\u03c0, kappa=1e-2, nsteps=1000, dev=CPU())\n    \u03c4 = 1/kappa  # time-scale for diffusive decay\n    dt = 1e-9 * \u03c4 # 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, \u03c30 = 0.1, 0.2\nc1, \u03c31 = 0.1, 0.2\n\nc0_x_func(x) = @. c0*exp(-x^2/(2*(\u03c30)^2))\nc0_y_func(y) = @. c1*exp(-y^2/(2*(\u03c31)^2))\n\nc0_val = c0_x_func.(g.x) .* c0_y_func.(g.y)\n\n#Analytic Solution\ntfinal = nsteps*dt\n\n\u03c30t = sqrt(2*kappa*tfinal + (\u03c30)^2)\n\u03c31t = sqrt(2*kappa*tfinal + (\u03c31)^2)\n\ncfinal_x = @. c0 * (\u03c30/\u03c30t) * exp(-g.x^2/(2*(\u03c30t)^2))\ncfinal_y = @. c1 * (\u03c31/\u03c31t) * exp(-g.y^2/(2*(\u03c31t)^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\u03c0, kappa=1e-2, nsteps=1000, dev=CPU())\n   \u03c4 = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * \u03c4 # 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, \u03c3 = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2\u03c3^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant \u03ba\n  tfinal = nsteps*dt\n  \u03c3t = sqrt(2*kappa[1]*tfinal + \u03c3^2)\n  cfinal = @. c0ampl*\u03c3/\u03c3t * exp(-g.x^2/(2*\u03c3t^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\u03c3(x) = 1 / (1 + exp(-x))\nf(x, w) = \u03c3(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_\u221e`` norm**\n\n    NormLinf(\u03bb=1.0)\n\nReturns the function\n```math\nf(x) = \u03bb\u22c5\\\\max\\\\{|x_1|, \u2026, |x_n|\\\\},\n```\nfor a nonnegative parameter `\u03bb`.\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 \u21a6 \u03bb||x||_\u221e = \u03bb\u22c5max(abs(x))\"\nfun_params(f::Postcompose{Conjugate{IndBallL1{R}}, R}) where {R <: Real} = \"\u03bb = $(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 Test, LinearAlgebra\nusing BellScenario: stirling2, stirling2_partitions, stirling2_matrices, permutation_matrices, base_n_val, n_choose_k_matrices\n\n@testset \"./src/combinatorics.jl\" begin\n\n@testset \"stirling2()\" begin\n    @testset \"domain errors\" begin\n        @test_throws DomainError stirling2(1,0)\n        @test_throws DomainError stirling2(1,2)\n    end\n\n    @test stirling2(1,1) == 1\n\n    @testset \"n = 2\" begin\n        @test stirling2(2,1) == 1\n        @test stirling2(2,2) == 1\n    end\n\n    @testset \"n = 3\" begin\n        @test stirling2(3,1) == 1\n        @test stirling2(3,2) == 3\n        @test stirling2(3,3) == 1\n    end\n\n    @testset \"n = 4\" begin\n        @test stirling2(4,1) == 1\n        @test stirling2(4,2) == 7\n        @test stirling2(4,3) == 6\n        @test stirling2(4,4) == 1\n    end\n\n    @testset \"n = 5\" begin\n        @test stirling2(5,1) == 1\n        @test stirling2(5,2) == 15\n        @test stirling2(5,3) == 25\n        @test stirling2(5,4) == 10\n        @test stirling2(5,5) == 1\n    end\n\n    @testset \"n = 6\" begin\n        @test stirling2(6,1) == 1\n        @test stirling2(6,2) == 31\n        @test stirling2(6,3) == 90\n        @test stirling2(6,4) == 65\n        @test stirling2(6,5) == 15\n        @test stirling2(6,6) == 1\n    end\n\n    @testset \"n = 10\" begin\n        @test stirling2(10,1) == 1\n        @test stirling2(10,2) == 511\n        @test stirling2(10,3) == 9330\n        @test stirling2(10,4) == 34105\n        @test stirling2(10,5) == 42525\n        @test stirling2(10,6) == 22827\n        @test stirling2(10,7) == 5880\n        @test stirling2(10,8) == 750\n        @test stirling2(10,9) == 45\n        @test stirling2(10,10) == 1\n    end\nend\n\n@testset \"stirling2_partitions()\" begin\n    @testset \"base cases\" begin\n        @test stirling2_partitions(0,0) == []\n        @test stirling2_partitions(1,0) == []\n        @test stirling2_partitions(1,2) == []\n        @test stirling2_partitions(5,1) == [[[1,2,3,4,5]]]\n    end\n\n    @testset \"simple cases\" begin\n        @test stirling2_partitions(3,2) == [[[1,2],[3]],[[2],[1,3]],[[1],[2,3]]]\n\n        @test stirling2_partitions(4,2) == [\n            [[1, 2, 3], [4]],\n            [[3], [1, 2, 4]],\n            [[1, 2], [3, 4]],\n            [[1, 3], [2, 4]],\n            [[2], [1, 3, 4]],\n            [[2, 3], [1, 4]],\n            [[1], [2, 3, 4]],\n        ]\n\n        @test stirling2_partitions(4,4) == [[[1],[2],[3],[4]]]\n    end\n\n    @testset \"general partitions\" begin\n        for n in 2:7\n            for k in 1:n\n                partitions = stirling2_partitions(n,k)\n                @test length(partitions) == stirling2(n,k)\n                @test length(unique(partitions)) == stirling2(n,k)\n                @test all(s -> length(s) == k, partitions)\n                @test all(s -> sort(cat(s...,dims=1)) == [1:n...], partitions)\n            end\n        end\n    end\nend\n\n@testset \"stirling2_matrices()\" begin\n    @testset \"domain errors\" begin\n        @test_throws DomainError n_choose_k_matrices(2,3)\n        @test_throws DomainError n_choose_k_matrices(2,0)\n    end\n\n    @testset \"simple cases\" begin\n        @test stirling2_matrices(4,1) == [\n            [1 1 1 1]\n        ]\n        @test stirling2_matrices(3,2) == [\n            [1 1 0;0 0 1],[0 1 0;1 0 1],[1 0 0;0 1 1]\n        ]\n    end\n\n    @testset \"general cases\" begin\n        for n in 2:7\n            for k in 1:n\n                matrices = stirling2_matrices(n,k)\n\n                @test length(matrices) == stirling2(n,k)\n                @test length(unique(matrices)) == stirling2(n,k)\n            end\n        end\n    end\nend\n\n@testset \"permutation_matrices()\" begin\n    @testset \"dim = 2\" begin\n        @test permutation_matrices(2) == [[1 0; 0 1], [0 1; 1 0]]\n    end\n\n    @testset \"dim = 3\" begin\n        @test issetequal(permutation_matrices(3), [\n            [1 0 0; 0 1 0; 0 0 1],\n            [1 0 0; 0 0 1; 0 1 0],\n            [0 1 0; 1 0 0; 0 0 1],\n            [0 1 0; 0 0 1; 1 0 0],\n            [0 0 1; 1 0 0; 0 1 0],\n            [0 0 1; 0 1 0; 1 0 0],\n        ])\n    end\n\n    @testset \"permtutation map validity\" for N in 4:5\n        perms = permutation_matrices(N)\n\n        @testset \"maps are unique\" begin\n            @test size(perms) == (factorial(N),)\n            @test size(perms) == size(unique(perms))\n        end\n\n        @testset \"matrix dimension, determinant, and invertibility\" for perm in perms\n            # dimension\n            @test size(perm) == (N,N)\n\n            # parity\n            parity = det(perm)\n            @test (parity == -1) || (parity == 1)\n\n            # invertibility\n            @test perm*perm' == Matrix{Int64}(I,N,N)\n        end\n    end\nend\n\n@testset \"n_choose_k_matrices()\" begin\n    @testset \"Domain Errors\" begin\n        @test_throws DomainError n_choose_k_matrices(2,3)\n        @test_throws DomainError n_choose_k_matrices(2,0)\n    end\n\n    @testset \"simple testcases\" begin\n        @test n_choose_k_matrices(3,3) == [[1 0 0;0 1 0;0 0 1]]\n\n        @test n_choose_k_matrices(3,2) == [\n            [1 0;0 1;0 0],[1 0;0 0;0 1],[0 0;1 0;0 1]\n        ]\n\n        @test n_choose_k_matrices(4,2) == [\n            [1 0;0 1;0 0;0 0],[1 0;0 0;0 1;0 0],[1 0;0 0;0 0;0 1],\n            [0 0;1 0;0 1;0 0],[0 0;1 0;0 0;0 1],[0 0;0 0;1 0;0 1]\n        ]\n    end\n\n    @testset \"general tests\" begin\n        for n in 2:5\n            for k in 1:n\n                matrices = n_choose_k_matrices(n,k)\n\n                @test length(matrices) == binomial(n,k)\n                @test length(unique(matrices)) == binomial(n,k)\n            end\n        end\n    end\nend\n\n@testset \"base_n_val()\" begin\n    @testset \"little endian\" begin\n        @test 1 == base_n_val(digits(1,base=2,pad=2), 2, big_endian = false)\n        @test 57 == base_n_val(digits(57,base=3,pad=5), 3, big_endian = false)\n    end\n\n    @testset \"big endian\" begin\n        @test 12 == base_n_val([1,1,0,0],2)\n        @test 974 == base_n_val([1,2,3,4,4],5)\n    end\n\n    @testset \"argument errors\" begin\n        @test_throws ArgumentError base_n_val([1,2,0,5],5)\n        @test_throws ArgumentError base_n_val([1,2,0,5],4)\n        @test_throws ArgumentError base_n_val([-1,0,1],2)\n    end\nend\n\nend\n", "meta": {"hexsha": "b018e0e5966c3de16995a56d524accca45e16032", "size": 6132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit/combinatorics.jl", "max_stars_repo_name": "ChitambarLab/BellScenario.jl", "max_stars_repo_head_hexsha": "74932c1d6efa5960ce8ded00599d73f914fa2281", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-01T00:02:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T18:38:27.000Z", "max_issues_repo_path": "test/unit/combinatorics.jl", "max_issues_repo_name": "ChitambarLab/BellScenario.jl", "max_issues_repo_head_hexsha": "74932c1d6efa5960ce8ded00599d73f914fa2281", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-08-01T12:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T00:49:45.000Z", "max_forks_repo_path": "test/unit/combinatorics.jl", "max_forks_repo_name": "ChitambarLab/BellScenario.jl", "max_forks_repo_head_hexsha": "74932c1d6efa5960ce8ded00599d73f914fa2281", "max_forks_repo_licenses": ["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.5209302326, "max_line_length": 126, "alphanum_fraction": 0.5166340509, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002789, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7872408086980386}}
{"text": "# Tested in Julia 1.5.1\nusing DelimitedFiles\ndata = readdlm(\"./data/adventInput05.txt\")\nfunction findRowColumn(string; first = 0, last = 127, upStr = 'B', lowStr = 'F')\n    planeRows = first:last\n    cStr = string[1]\n    for s in string\n        if s == upStr\n            first = planeRows.start + Int(length(planeRows)/2)\n            last = planeRows.stop\n            planeRows = first:last\n        elseif s == lowStr\n            first = planeRows.start\n            last = first + Int(length(planeRows)/2-1)\n            planeRows = first:last\n        end\n        cStr = s\n    end\n    cStr == lowStr ? planeRows.start : planeRows.stop\nend\nfunction maxIdBoardingPass(data)\n    idBoardingPass = 0\n    for s in data\n        posRow = findRowColumn(s)\n        posCol = findRowColumn(s; first=0, last = 7, upStr = 'R', lowStr = 'L')\n        idBoadPass = posRow *8 + posCol\n        idBoardingPass =  idBoadPass > idBoardingPass ? idBoadPass : idBoardingPass\n    end\n    idBoardingPass\nend\nfunction IdsBoardingPass(data)\n    idsBPass = []\n    for s in data\n        posRow = findRowColumn(s)\n        posCol = findRowColumn(s; first=0, last = 7, upStr = 'R', lowStr = 'L')\n        idBoadPass = posRow *8 + posCol\n        push!(idsBPass, idBoadPass)\n    end\n    idsBPass\nend\nfunction findSeat(IdsBP)\n    for s_id in 1:maximum(IdsBP)\n        ismyseat = s_id \u2209 IdsBP\n        isplus1  = s_id + 1 \u2208 IdsBP\n        isminus1 = s_id - 1 \u2208 IdsBP\n        if ismyseat && isplus1 && isminus1\n            return s_id\n        end\n    end\nend\nmaximum(IdsBoardingPass(data))\nfindSeat(IdsBoardingPass(data))\n", "meta": {"hexsha": "2f4e7afd69afaa924cdca7a1a934cfd9c4365d64", "size": 1579, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day5.jl", "max_stars_repo_name": "lazarusA/Advent_of_Code2020", "max_stars_repo_head_hexsha": "a800017da98bcee691f546835269e3acf8808fea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day5.jl", "max_issues_repo_name": "lazarusA/Advent_of_Code2020", "max_issues_repo_head_hexsha": "a800017da98bcee691f546835269e3acf8808fea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day5.jl", "max_forks_repo_name": "lazarusA/Advent_of_Code2020", "max_forks_repo_head_hexsha": "a800017da98bcee691f546835269e3acf8808fea", "max_forks_repo_licenses": ["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.7924528302, "max_line_length": 83, "alphanum_fraction": 0.6041798607, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7872408085799203}}
{"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 \u0393 = gamma\n\n# Coefficients in the Jacobi polynomial recurrence relations.\na\u1d3e(\u03b1, \u03b2, n) = 2/(2n+\u03b1+\u03b2) * \u221a(n * (n+\u03b1+\u03b2) * (n+\u03b1) * (n+\u03b2) / (2n+\u03b1+\u03b2-1) / (2n+\u03b1+\u03b2+1))\nb\u1d3e(\u03b1, \u03b2, n) = -(\u03b1^2 - \u03b2^2) / (2n+\u03b1+\u03b2) / (2n+\u03b1+\u03b2+2)\n\n# code checked against the matlab code\n\"\"\"\njacobi(x, \u03b1, \u03b2, 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- `\u03b1`: first parameter for Jacobi polynomials\n- `\u03b2`: second parameter for Jacobi polynomials\n- `n` : order\n# Return\n-  `y`: the value of the of the Jacobi polynomial\n\"\"\"\nfunction jacobi(x, \u03b1, \u03b2, n::Int)\n    P\u1d45\u1d5d = n <= 1 ? OffsetArray(zeros(2), 0:1) : OffsetArray(zeros(n+1), 0:n)\n    P\u1d45\u1d5d[0] = \u221a(2.0^-(\u03b1+\u03b2+1) * \u0393(\u03b1+\u03b2+2) / \u0393(\u03b1+1) / \u0393(\u03b2+1))\n    P\u1d45\u1d5d[1] = P\u1d45\u1d5d[0]/2 * \u221a((\u03b1+\u03b2+3) / (\u03b1+1) / (\u03b2+1)) * ((\u03b1+\u03b2+2)*x + \u03b1 - \u03b2)\n    for n\u2032 in 1:n-1\n        P\u1d45\u1d5d[n\u2032+1] = ((x - b\u1d3e(\u03b1,\u03b2,n\u2032)) * P\u1d45\u1d5d[n\u2032] - a\u1d3e(\u03b1,\u03b2,n\u2032) * P\u1d45\u1d5d[n\u2032-1]) / a\u1d3e(\u03b1, \u03b2, n\u2032+1)\n    end\n    return P\u1d45\u1d5d[n]\nend\n\n\"\"\"\ndjacobi(x, \u03b1, \u03b2, 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- `\u03b1`: first parameter for Jacobi polynomials\n- `\u03b2`: second parameter for Jacobi polynomials\n- `n` : order\n# Return\n-  `y`: the derivative of the of the Jacobi polynomial\n\"\"\"\ndjacobi(x, \u03b1, \u03b2, n::Int) = \u221a(n * (n+\u03b1+\u03b2+1)) * jacobi(x, \u03b1+1, \u03b2+1, n-1)\n\n\"\"\"\nvandermonde(x, \u03b1, \u03b2, 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-   `\u03b1`: first parameter for Jacobi polynomials\n-   `\u03b2`: 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, \u03b1, \u03b2, N)\n    # compute first two coefficients\n    \u03b30 = 2^(\u03b1 + \u03b2 + 1) * factorial(\u03b1) * factorial(\u03b2) / ((\u03b1 + \u03b2 + 1) * factorial(\u03b1 + \u03b2))\n    \u03b31 = (\u03b1 + 1) * (\u03b2 + 1) / (\u03b1 + \u03b2 + 3) * \u03b30\n\n    # create view to assign values\n    v = zeros(length(x), N+1)\n    v1 = view(v, :, 1)\n    @. v1 = 1 / sqrt(\u03b30)\n\n    # explicitly compute second coefficient\n    if N == 0\n        return v\n    end\n\n    v2 = view(v, :, 2)\n    @. v2 = ( (\u03b1 + \u03b2 + 2) * x/2 + (\u03b1 - \u03b2)/2) / sqrt(\u03b31)\n\n    if N == 1\n        return v\n    end\n\n    a\u02b2 = 2 / (2 + \u03b1 + \u03b2) * sqrt((\u03b1+1) * (\u03b2+1) / (\u03b1 + \u03b2 + 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) + \u03b1 + \u03b2\n        a\u2071 = 2 / (h1 + 2) * sqrt((i-1) * (i-1 + \u03b1 + \u03b2) * (i-1 + \u03b1) * (i-1 + \u03b2) / ((h1 + 1) * (h1 + 3)))\n        b\u2071 = - (\u03b1^2 - \u03b2^2) / (h1 * (h1 + 2))\n\n        # compute coefficients for ith column\n        @. vi = 1 / a\u2071 * (-a\u02b2 * vM2 + (x - b\u2071) * vM1)\n\n        # save a coefficient for next iteration\n        a\u02b2 = a\u2071\n    end\n\n    return v\nend\n\n\"\"\"\ndvandermonde(x, \u03b1, \u03b2, 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-   `\u03b1`: first parameter for Jacobi polynomials\n-   `\u03b2`: 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, \u03b1, \u03b2, 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, \u03b1+1, \u03b2+1, N)\n    for i in 1:N\n        vi = view(v, :, i)\n        vrP1 = view(vr, :, i+1)\n        @. vrP1 = sqrt(i * (\u03b1 + \u03b2 + i+1)) * vi\n    end\n\n    return vr\nend\n\n\"\"\"\ndmatrix(x, \u03b1, \u03b2, 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-   `\u03b1`: first parameter for Jacobi polynomials\n-   `\u03b2`: 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, \u03b1, \u03b2, N)\n    # calculate vandermonde matrix and grad of vandermonde matrix\n    vr = dvandermonde(x, \u03b1, \u03b2, N)\n    v  =  vandermonde(x, \u03b1, \u03b2, 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(\u03b1, \u03b2, N)\n# Description\n    Guass Quadrature points and weights for the Jacobi Polynomial (\u03b1,\u03b2)\n# Input\n\u03b1, \u03b2: 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\u03b1 = 0\n\u03b2 = 0\nN = 4\nx, w = jacobiGQ(\u03b1, \u03b2, N)\n\"\"\"\nfunction jacobiGQ(\u03b1, \u03b2, N)\n    N == 0 && return [(\u03b1-\u03b2) / (\u03b1+\u03b2+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\u1d3e(\u03b1, \u03b2, n)\n        ev[n] = a\u1d3e(\u03b1, \u03b2, 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    (\u03b1 + \u03b2) \u2248 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^(\u03b1+\u03b2+1) / (\u03b1+\u03b2+1)\n    @. w *= factorial(\u03b1) * factorial(\u03b2) / factorial(\u03b1+\u03b2)\n\n    return x, w\nend\n\n\"\"\"\njacobiGL(\u03b1, \u03b2, N)\n# Description\n    Guass Labatto quadrature points for the Jacobi Polynomial (\u03b1,\u03b2)\n    The quadrature weights are computed as well (but not returned)\n# Arguments\n- `\u03b1, \u03b2`: 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(\u03b1, \u03b2, 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(\u03b1+1, \u03b2+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\u03c0\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\u02b3)\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\u02b3:\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\u02b3)\n    J = D\u02b3 * 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; \u03b1 = 0; \u03b2 = 0; xmin = 0; xmax = 2\u03c0;\nnGL = n + 1\nnFP = 1\nnFaces = 2\n\nr = jacobiGL(\u03b1, \u03b2, 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    \u03b1 = 0; \u03b2 = 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(\u03b1, \u03b2, 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, \u03b1, \u03b2, n)\n\n    # build surface integral terms\n    V = vandermonde(r, \u03b1, \u03b2, 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, \ud835\udca2::Mesh)\n    diffs = reshape( (data[\ud835\udca2.vmapM] - data[\ud835\udca2.vmapP]), (\ud835\udca2.nFP * \ud835\udca2.nFaces, \ud835\udca2.K ))\n    # Include factor of 2 for the weak-strong form\n    @. diffs *= 1.0 / 2.0\n    # Compute Lift Operator\n    lifted = - \ud835\udca2.lift * (\ud835\udca2.fscale .* \ud835\udca2.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    \u03b5::Float64\n    \u03c3::Float64\nend\n\n\"\"\"\n    LennardJones(params::Dict)\n    \nCreates the LennardJones potential.\n\"\"\"\nfunction LennardJones(params::Dict)\n    # Creates the LennardJones model\n    \u03b5 = params[\"\u03b5\"]\n    \u03c3 = params[\"\u03c3\"]\n    return LennardJones(\u03b5, \u03c3)\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.\u03b5 * ((p.\u03c3 / norm(r))^12 - (p.\u03c3 / 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) = \u2211\u1d62\u2c7c \u03b2\u1d62\u2c7cx\u1d62\u02b2\n```\nwith polynomial coefficients ``\u03b2\u1d62\u2c7c`` of shape ``d \u00d7 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    \u03b2::Matrix{Float64}\n    \"Priors for mean parameters\"\n    priors::Array\n\n    \"\"\"\n        MeanPoly(\u03b2::Matrix{Float64})\n\n    Create `MeanPoly` with polynomial coefficients `\u03b2`.\n    \"\"\"\n    MeanPoly(\u03b2::Matrix{Float64}) = new(\u03b2, [])\nend\n\nfunction mean(mPoly::MeanPoly, x::AbstractVector)\n    dim = length(x)\n    deg = size(mPoly.\u03b2, 2)\n    dim == size(mPoly.\u03b2, 1) || throw(ArgumentError(\"Observations and mean function have inconsistent dimensions\"))\n    return sum(dot(x.^j, mPoly.\u03b2[:,j]) for j in 1:deg)\nend\n\n\nget_params(mPoly::MeanPoly) = vec(mPoly.\u03b2)\nget_param_names(mPoly::MeanPoly) = get_param_names(vec(mPoly.\u03b2), :\u03b2)\nnum_params(mPoly::MeanPoly) = length(mPoly.\u03b2)\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.\u03b2, hyp)\nend\n\n\nfunction grad_mean(mPoly::MeanPoly, x::AbstractVector)\n    dim = length(x)\n    deg = size(mPoly.\u03b2, 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 \u2202G_ij/\u2202p^k: (i, j, k)\n# indexing convention \u0393^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    \u2202G_\u2202xn_matrix = ForwardDiff.jacobian(pn -> reshape(metric_chart(pn, task, C), Size(n^2)), pn)\n    \u2202G_\u2202xn_matrix == (@SMatrix zeros(n^2,n)) && return @SArray zeros(n,n,n)\n    \u2202G_\u2202xn = reshape(\u2202G_\u2202xn_matrix, Size(n,n,n))\n    inds = static(1):static(n)\n    \u0393 = SArray{Tuple{n,n,n},S}([0.5*sum(Tuple(Ginv[k,l]*(\u2202G_\u2202xn[j,l,i]+\u2202G_\u2202xn[i,l,j]-\u2202G_\u2202xn[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    \u2202G_\u2202xn_matrix = ForwardDiff.jacobian(pn -> reshape(metric_chart(pn, task, CN), Size(n^2)), pn)\n    \u2202G_\u2202xn_matrix == (@SMatrix zeros(n^2,n)) && return @SArray zeros(n,n,n)\n    \u2202G_\u2202xn = reshape(\u2202G_\u2202xn_matrix, Size(n,n,n))\n    inds = static(1):static(n)\n    \u0393 = SArray{Tuple{n,n,n},S}([0.5*sum(Tuple(Ginv[k,l]*(\u2202G_\u2202xn[j,l,i]+\u2202G_\u2202xn[i,l,j]-\u2202G_\u2202xn[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, \u03931, C1::Chart{I,N},\n        C2::Chart{J,N}) where {N,I,J}\n    n, S = dim(N), eltype(pn1)\n    \u03931 == (@SArray zeros(n,n,n)) && return @SArray zeros(n,n,n)\n    pn2 = chart_transition(pn1, C1, C2)\n    \u2202pn1_\u2202pn2 = chart_transition_jacobian(pn2, C2, C1)\n    \u2202pn2_\u2202pn1 = inv(\u2202pn1_\u2202pn2)\n    Hpn2_pn1 = chart_transition_hessian(pn2, C2, C1)\n    inds = static(1):static(n)\n    \u03932 = SArray{Tuple{n,n,n},S}([sum(Tuple(\u2202pn2_\u2202pn1[k,l]*\u2202pn1_\u2202pn2[r,i]*\u2202pn1_\u2202pn2[s,j]*\u03931[r,s,l] \n        for l in inds, r in inds, s in inds)) + sum(Hpn2_pn1[l,i,j]*\u2202pn2_\u2202pn1[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 \u22c5 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 \u2208 eachindex(a,b)\n        s += a[i] * b[i]\n    end\n    return s\nend\n\n#Dot product using LoopVectorization (real \u22c5 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 \u2208 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 \u22c5 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 \u2208 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 \u22c5 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 \u2208 axes(a,2) #Conjugate(a) \u00d7 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 \u2208 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 \u2208 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 \u2208 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 \u2208 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": "#   Unit examples of the FourierAnalysis Package for julia language\n#   v 0.0.1 - last update 24th of September 2019\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 example show how to use Goertzel's algorithms.\n\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n#                                                                             #\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n\n\n########## Test goertzel algorithms #############\nusing FourierAnalysis\nsr, t, f, a = 128, 128, 5, 10\nv=sinusoidal(a, f, sr, t, 0)\nc=goertzel(v, f, sr, t) # should be 0+aim\nd=goertzel2(v, f, sr, t) # should be 0+aim\nabs2(c) # power, should be a\u00b2\nabs2(d) # power, should be a\u00b2\n\nftrue=f+0.15\nv=sinusoidal(a, ftrue, sr, t, 0 )\nc=goertzel(v, f, sr, t) # should be 0+aim\nd=goertzel2(v, ftrue, sr, t) # should be 0+aim\nabs2(c) # power, should be a\u00b2\nabs2(d) # power, should be a\u00b2\n#################################################\n", "meta": {"hexsha": "915a4140a098e38d539cfecfcd625ff47615ae78", "size": 1087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_goertzel.jl", "max_stars_repo_name": "laborg/FourierAnalysis.jl", "max_stars_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_stars_repo_licenses": ["MIT"], "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_goertzel.jl", "max_issues_repo_name": "laborg/FourierAnalysis.jl", "max_issues_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_issues_repo_licenses": ["MIT"], "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_goertzel.jl", "max_forks_repo_name": "laborg/FourierAnalysis.jl", "max_forks_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_forks_repo_licenses": ["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.96875, "max_line_length": 79, "alphanum_fraction": 0.4811407544, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7871141295360929}}
{"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)\u00f72):((nx_psf-1)\u00f72)\n        \u03c3 = fwhm[iy] / sqrt(log(256))\n        r2 = abs2.(r / \u03c3)\n        tmp = @. exp(-\u03c0 * (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)*\u03c0)\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": "### A Pluto.jl notebook ###\n# v0.17.2\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 38fdd4ef-c383-4f97-8451-c6f602307e7d\nusing BenchmarkTools, Images, InteractiveUtils, LinearAlgebra, StaticArrays\n\n# \u2554\u2550\u2561 9114285c-4c5a-482c-94d8-21c3e4cc79e4\nusing LoopVectorization: @turbo\n\n# \u2554\u2550\u2561 c58754e4-26b6-4b1d-be61-447496332757\nbegin # Instantiate separate RNGs for each thread\n\tusing Random, RandomNumbers.Xorshifts\n\tconst TRNG = [Xoroshiro128Plus(i) for i = 1:Threads.nthreads()]\n\t\n\treseed!() = for (i,rng) in enumerate(TRNG) Random.seed!(rng, i) end # reset seeds\n\n\t@inline function trand() # thread-local rand()\n\t    @inbounds rng = TRNG[Threads.threadid()]\n\t    rand(rng)\n\tend\n\t\n\t@inline function trand(::Type{T}) where T # thread-local rand()\n\t    @inbounds rng = TRNG[Threads.threadid()]\n\t    rand(rng, T)\n\tend\nend\n\n# \u2554\u2550\u2561 0866add2-9b95-45e7-8081-c01cd2a66911\nmd\"\"\"# Chapter 1: Overview\"\"\"\n\n# \u2554\u2550\u2561 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\nOptimized with the help of many fellow Julia enthusiasts... please see [discussion](https://discourse.julialang.org/t/ray-tracing-in-a-week-end-julia-vs-simd-optimized-c). (On my PC, this code runs ~6% faster than the equivalent C++ code!)\"\"\"\n\n# \u2554\u2550\u2561 97bb4432-ed41-423b-b4d9-bafc519de641\nmd\"# Chapter 2 - Manipulating images\"\n\n# \u2554\u2550\u2561 84d29423-cf11-41c3-af4d-c5f63b1ef23e\nimg = rand(4, 3)\n\n# \u2554\u2550\u2561 7d26fef0-9a06-479a-ae08-e9d04e455767\nimg_rgb = rand(RGB{Float32}, 4, 4)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 538d1aa5-07f9-4fca-8410-ef63b8a6857b\n# TODO: save as image, e.g. PNG\n\n# \u2554\u2550\u2561 8aeb7373-6bb0-4544-8655-fa941561688c\n# The \"Hello World\" of graphics\n@fastmath function gradient(nx::Int, ny::Int)\n\timg = zeros(RGB, ny, nx)\n\t@inbounds @simd for j in 1:nx\n\t\tfor i in 1:ny # Julia is column-major, i.e. iterate 1 column at a time\n\t\t\tx = j; y = (ny-i);\n\t\t\tr = x/nx\n\t\t\tg = y/ny\n\t\t\tb = 0.2\n\t\t\timg[i,j] = RGB(r,g,b)\n\t\tend\n\tend\n\timg\nend\n\n# \u2554\u2550\u2561 154d736b-8fdc-44af-ae2a-9e5ba6d2c92e\ngradient(200,100)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 961fd749-d439-4dfa-ae21-b1659dc54511\nmd\"# Chapter 3: Linear Algebra\"\n\n# \u2554\u2550\u2561 f8007c75-9487-414a-9592-138a696c2957\n# Examples follow:\n# Dot product (\\cdot) is defined by LinearAlgebra...\n[1; 1] \u22c5 [2; 3]\n\n# \u2554\u2550\u2561 668030c8-24a7-4aa6-b858-cedf8ac5f988\n# Cross product (\\times)\n[0;1;0] \u00d7 [0;0;1]\n\n# \u2554\u2550\u2561 71cee0d1-ff0a-4234-b393-8f20834f6415\n# Adapted from @Christ_Foster's: https://discourse.julialang.org/t/ray-tracing-in-a-week-end-julia-vs-simd-optimized-c/72958/40\nbegin\n\tconst Vec3{T<:AbstractFloat} = SVector{3, T}\n\t@inline @inbounds function Base.getproperty(v::SVector{3}, name::Symbol)\n\t    name === :x || name === :r ? getfield(v, :data)[1] :\n\t    name === :y || name === :g ? getfield(v, :data)[2] :\n\t    name === :z || name === :b ? getfield(v, :data)[3] : getfield(v, name)\n\tend\n\t\n\t@inline @inbounds function Base.getproperty(v::SVector{2}, name::Symbol)\n\t    name === :x || name === :r ? getfield(v, :data)[1] :\n\t    name === :y || name === :g ? getfield(v, :data)[2] : getfield(v, name)\n\tend\nend\n\n# \u2554\u2550\u2561 3eb50f44-9091-45e8-a7e1-92d25b4b2090\nbegin\n\tOption{T} = Union{Missing, T}\n\t\n\t@inline squared_length(v::Vec3) = v \u22c5 v\n\t@inline near_zero(v::Vec3) = squared_length(v) < 1e-5\nend\n\n# \u2554\u2550\u2561 78f209df-d176-4711-80fc-a8054771f105\nt_col = SA[0.4, 0.5, 0.1] # test color. See StaticArrays.jl\n\n# \u2554\u2550\u2561 e88de775-6904-4182-8209-06db22758470\nt_col.r # first, i.e. red, component\n\n# \u2554\u2550\u2561 5fd1ec87-3616-448a-ab4d-fede804b26d5\nsquared_length(t_col)\n\n# \u2554\u2550\u2561 a0893bf4-9607-4853-8162-9f34d3337060\n@inline rgb(v::Vec3) = RGB(v...)\n\n# \u2554\u2550\u2561 cfbcb883-d12e-4ad3-a084-064749bddcdb\nrgb(t_col)\n\n# \u2554\u2550\u2561 6348c03d-e8ec-4dbb-9f8a-8e4a48bb1cb3\n@inline rgb_gamma2(v::Vec3) = RGB(sqrt.(v)...)\n\n# \u2554\u2550\u2561 dbc8fc2d-39c2-4ec9-b82d-7c6a8b12dde7\nrgb_gamma2(t_col)\n\n# \u2554\u2550\u2561 53832af1-a9be-4e02-8b71-a70dae63c233\nstruct Ray{T}\n\torigin::Vec3{T} # Point \n\tdir::Vec3{T} # Vec3 # direction (unit vector)\nend\n\n# \u2554\u2550\u2561 81b4c9e4-9f93-45ca-9fa0-7e9686a55e9a\n# equivalent to C++'s ray.at()\n#\"3D Point of ray `r` evaluated at parameter t\"\n@inline point(r::Ray{T}, t::T) where T <: AbstractFloat = r.origin .+ t .* r.dir\n\n# \u2554\u2550\u2561 772674b0-5c40-4457-9526-5b4e81cca711\nmd\"\"\"# Random vectors\nC++'s section 8.1\"\"\"\n\n# \u2554\u2550\u2561 cdf96967-6790-4bd5-8890-40de9365a05a\nThreads.nthreads()\n\n# \u2554\u2550\u2561 709861a3-202a-4bff-a46d-b46c6e14b334\n# equiv to random_double()\n@inline random_between(min::T=0, max::T=1) where T = trand(T)*(max-min) + min\n\n# \u2554\u2550\u2561 135000d6-a675-4d8b-9385-50853bf9a169\n@inline random_vec3(min::T, max::T) where T = \n\t@inbounds @SVector[random_between(min, max) for i \u2208 1:3]\n\n# \u2554\u2550\u2561 7d1146d7-74da-42e6-92c2-1312ed03f70d\n@inline random_vec2(min::T, max::T) where T = \n\t@inbounds @SVector[random_between(min, max) for i \u2208 1:2]\n\n# \u2554\u2550\u2561 46a4aa4b-82c1-4941-b36d-dc8c977af2bc\n# equiv to random_in_unit_sphere()\n@inline function random_vec3_in_sphere(::Type{T}) where T\n\twhile true\n\t\tp = random_vec3(T(-1), T(1))\n\t\tif p\u22c5p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend\n\n# \u2554\u2550\u2561 203a9b25-742a-4d8b-adee-862ce4c67670\nrandom_vec3_in_sphere(Float64)\n\n# \u2554\u2550\u2561 2e98c6bd-0289-4105-ad25-24414ecf2750\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# \u2554\u2550\u2561 b5407efd-8071-43e7-b9f4-de1bd9de7311\nrandom_vec3_on_sphere(Float32)\n\n# \u2554\u2550\u2561 c0c23cb3-6a57-487d-943a-af4330a94ffe\n# equiv to random_in_unit_disk()\n@inline function random_vec2_in_disk(::Type{T}) where T \n\twhile true\n\t\tp = random_vec2(T(-1), T(1))\n\t\tif p\u22c5p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend\n\n# \u2554\u2550\u2561 3851fa56-2c73-45eb-9089-65eec0237f14\nrandom_vec2_in_disk(Float64)\n\n# \u2554\u2550\u2561 678214c5-de81-489f-b002-c343d48071c9\nmd\"# Chapter 4: Rays, simple camera, and background\"\n\n# \u2554\u2550\u2561 cbb6418c-79e9-4359-80a6-40a8fa40679e\n@inline function skycolor(ray::Ray{T}) where T\n\twhite = SA[1.0, 1.0, 1.0]\n\tskyblue = SA[0.5, 0.7, 1.0]\n\tt = T(0.5)*(ray.dir.y + one(T))\n    (one(T)-t)*white + t*skyblue\nend\n\n# \u2554\u2550\u2561 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, ::Type{T}) where T\n\tlower_left_corner = SA[-2,-1,-1]\n\thorizontal = SA[4,0,0]\n\tvertical = SA[T(0),T(2),T(0)]\n\torigin = SA[T(0),T(0),T(0)]\n\t\n\timg = zeros(RGB{T}, ny, nx)\n\tThreads.@threads for j in 1:nx\n\t\t# Julia is column-major, i.e. iterate 1 column at a time\n\t\t@inbounds for i in 1:ny \n\t\t\tu = T(j/nx)\n\t\t\tv = T((ny-i)/ny) # Y-up!\n\t\t\tray = Ray(origin, normalize(lower_left_corner + u*horizontal +\n\t\t\t\t\t\t\t\t\t\tv*vertical))\n\t\t\t#r = x/nx\n\t\t\t#g = y/ny\n\t\t\t#b = 0.2\n\t\t\timg[i,j] = rgb(scene(ray))\n\t\tend\n\tend\n\timg\nend\n\n\n# \u2554\u2550\u2561 655ffa6c-f1e9-4149-8f1d-51145c5a51e4\nmain(200, 100, skycolor, Float32)\n\n# \u2554\u2550\u2561 9075f8ed-f319-486d-94b2-486806aba3fd\nmd\"# Chapter 5: Add a sphere\"\n\n# \u2554\u2550\u2561 c00e2004-2002-4dd2-98ed-f898ef2c14f1\n@inline @fastmath function hit_sphere1(center::Vec3{T}, radius::T, r::Ray{T}) where T\n\toc = r.origin - center\n\t#a = r.dir \u22c5 r.dir # unnecessary since `r.dir` is normalized\n\ta = 1\n\tb = 2oc \u22c5 r.dir\n\tc = (oc \u22c5 oc) - radius*radius\n\tdiscriminant = b*b - 4a*c\n\tdiscriminant > 0\nend\n\n# \u2554\u2550\u2561 b7399fb8-6205-41ea-9c70-eb62daedcefb\n@inline function sphere_scene1(r::Ray{T}) where T\n\t# sphere of radius 0.5 centered at z=-1\n\tif hit_sphere1(SA[T(0), T(0), T(-1)], T(0.5), r) \n\t\treturn SA[T(1),T(0),T(0)] # red\n\telse\n\t\tskycolor(r)\n\tend\nend\n\n# \u2554\u2550\u2561 1d04159d-87bd-4cf8-a73c-817f20ca1026\nmain(200, 100, sphere_scene1, Float64) \n\n# \u2554\u2550\u2561 fed81f09-e4a0-433f-99e8-261096114b7b\nmd\"# Chapter 6: Surface normals and multiple objects\"\n\n# \u2554\u2550\u2561 24e8740a-8e44-4206-b2b6-c4a55002dad8\n@inline function hit_sphere2(center::Vec3{T}, radius::T, r::Ray{T}) where T\n\toc = r.origin - center\n\t#a = r.dir \u22c5 r.dir # unnecessary since `r.dir` is normalized\n\ta = 1\n\tb = 2oc \u22c5 r.dir\n\tc = (oc \u22c5 oc) - radius^2\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# \u2554\u2550\u2561 359832af-7598-4c45-8033-c28cb0d86772\n@inline function sphere_scene2(r::Ray{T}) where T\n\tsphere_center = SA[T(0),T(0),T(-1)]\n\tt = hit_sphere2(sphere_center, T(0.5), r) # sphere of radius 0.5 centered at z=-1\n\tif t > T(0)\n\t\tn\u20d7 = normalize(point(r, t) - sphere_center) # normal vector. typed n\\vec\n\t\treturn T(0.5)*n\u20d7 + SA[T(0.5),T(0.5),T(0.5)] # remap normal to rgb\n\telse\n\t\tskycolor(r)\n\tend\nend\n\n# \u2554\u2550\u2561 ed6ab8be-587c-4cb6-8172-618c74d3f9cc\nmain(200,100,sphere_scene2, Float32)\n\n# \u2554\u2550\u2561 a65c68c9-e489-465a-9687-93ae9da14a5e\n#\"An object that can be hit by Ray\"\nabstract type Hittable end\n\n# \u2554\u2550\u2561 2c4b4453-1a46-4889-9a14-16b18cc8c240\n#\"\"\"Materials tell us how rays interact with a surface\"\"\"\nabstract type Material{T <: AbstractFloat} end\n\n# \u2554\u2550\u2561 3b570d37-f407-41d8-b8a0-a0af4d85b14d\n#\"Record a hit between a ray and an object's surface\"\nstruct HitRecord{T <: AbstractFloat}\n\tt::T # distance from the ray's origin to the intersection with a surface. \n\t\n\tp::Vec3{T} # point of the intersection between an object's surface and a ray\n\tn\u20d7::Vec3{T} # surface's outward normal vector, points towards outside of object?\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\t\n\tmat::Material{T}\n\n\t@inline HitRecord(t::T,p,n\u20d7,front_face,mat) where T = new{T}(t,p,n\u20d7,front_face,mat)\nend\n\n# \u2554\u2550\u2561 138bb5b6-0f45-4f13-8339-5110eb7cd1ff\nstruct Sphere{T <: AbstractFloat} <: Hittable\n\tcenter::Vec3{T}\n\tradius::T\n\tmat::Material{T}\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4a396b3f-f920-4ec2-91f6-7d61fe2b9699\n#\"\"\"Equivalent to `hit_record.set_face_normal()`\"\"\"\n@inline @fastmath function ray_to_HitRecord(t::T, p, outward_n\u20d7, r_dir::Vec3{T}, mat::Material{T})::Union{HitRecord,Nothing} where T\n\tfront_face = r_dir \u22c5 outward_n\u20d7 < 0\n\tn\u20d7 = front_face ? outward_n\u20d7 : -outward_n\u20d7\n\tHitRecord(t,p,n\u20d7,front_face,mat)\nend\n\n# \u2554\u2550\u2561 427f247c-055c-459e-9862-26e9f6f3e24f\nstruct Scatter{T<: AbstractFloat}\n\tr::Ray{T}\n\tattenuation::Vec3{T}\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\t@inline Scatter(r::Ray{T},a::Vec3{T},reflected=true) where T = \n\t\tnew{T}(r,a,reflected)\nend\n\n# \u2554\u2550\u2561 88e51c27-0f28-4dcc-b9e9-ac44eeb876f5\n#\"Diffuse material\"\nstruct Lambertian{T} <: Material{T}\n\talbedo::Vec3{T}\nend\n\n# \u2554\u2550\u2561 7c4a67b2-8208-4cd4-b1ea-16f6f50adfe8\n# \"\"\"Compute reflection vector for v (pointing to surface) and normal n\u20d7.\n\n# \tSee [diagram](https://raytracing.github.io/books/RayTracingInOneWeekend.html#metal/mirroredlightreflection)\"\"\"\n@inline @fastmath reflect(v::Vec3{T}, n\u20d7::Vec3{T}) where T = v - (2v\u22c5n\u20d7)*n\u20d7\n\n# \u2554\u2550\u2561 87de4e8e-f7a2-4b47-991c-9b2988782ef4\n# diagram's example\n@assert reflect(SA[0.6,-0.8,0.0], SA[0.0,1.0,0.0]) == SA[0.6,0.8,0.0]\n\n# \u2554\u2550\u2561 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. \"\"\"\n@inline @fastmath function scatter(mat::Lambertian{T}, r::Ray{T}, \n\t\t\t\t\t\t\t\t   rec::HitRecord{T})::Scatter{T} where T\n\tscatter_dir = rec.n\u20d7 + random_vec3_on_sphere(T)\n\tif near_zero(scatter_dir) # Catch degenerate scatter direction\n\t\tscatter_dir = rec.n\u20d7 \n\telse\n\t\tscatter_dir = normalize(scatter_dir)\n\tend\n\tscattered_r = Ray{T}(rec.p, scatter_dir)\n\tattenuation = mat.albedo\n\treturn Scatter(scattered_r, attenuation)\nend\n\n# \u2554\u2550\u2561 78efebc5-53fd-417d-bd9e-667fd504e3fd\n@inline @fastmath function hit(s::Sphere{T}, r::Ray{T}, tmin::T, \n\t\t\t\t\t\t\t   tmax::T)::Union{HitRecord,Nothing} where T\n    oc = r.origin - s.center\n    a = 1 # r.dir \u22c5 r.dir is unnecessary since r.dir is normalized\n\thalf_b = oc \u22c5 r.dir\n    c = oc\u22c5oc - s.radius^2\n    discriminant = half_b^2 - a*c\n\tif discriminant < 0 return nothing end\n\tsqrtd = \u221adiscriminant\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 nothing\n\t\tend\n\tend\n\t\n\tt = root\n\tp = point(r, t)\n\tn\u20d7 = (p - s.center) / s.radius\n\tray_to_HitRecord(t, p, n\u20d7, r.dir, s.mat)\nend\n\n# \u2554\u2550\u2561 05e57afd-6eb9-42c5-9666-7be3771fa6b8\nconst HittableList = Vector{Hittable}\n\n# \u2554\u2550\u2561 08e18ae5-9927-485e-9644-552f03e06f27\n#\"Find closest hit between `Ray r` and a list of Hittable objects `h`, within distance `tmin` < `tmax`\"\n@inline function hit(hittables::HittableList, r::Ray{T}, tmin::T,\n\t\t\t\t\t tmax::T)::Union{HitRecord,Nothing} where T\n    closest = tmax # closest t so far\n    best_rec::Union{HitRecord,Nothing} = nothing # by default, no hit\n    @inbounds for i in eachindex(hittables)\n\t\th = hittables[i]\n        rec = hit(h, r, tmin, closest)\n        if rec !== nothing\n            best_rec = rec\n            closest = best_rec.t # i.e. ignore any further hit > this one's.\n        end\n    end\n    best_rec\nend\n\n# \u2554\u2550\u2561 737e2f87-82f5-45b6-a76c-4f560c29f5b9\n@inline color_vec3_in_rgb(v::Vec3{T}) where T = 0.5normalize(v) + SA{T}[0.5,0.5,0.5]\n\n# \u2554\u2550\u2561 0bf88264-d4c5-4d5a-babe-d2433e46024d\nmd\"# Metal material\"\n\n# \u2554\u2550\u2561 555bea1d-5178-48dd-87e6-4e2a2471a5dd\nstruct Metal{T} <: Material{T}\n\talbedo::Vec3{T}\n\tfuzz::T # how big the sphere used to generate fuzzy reflection rays. 0=none\n\t@inline Metal(a::Vec3{T}, f::T=0.0) where T = new{T}(a,f)\nend\n\n# \u2554\u2550\u2561 c299ca47-46c4-42da-9f8b-ae3abbeb6e51\n@inline @fastmath function scatter(mat::Metal{T}, r_in::Ray{T},\n\t\t\t\t\t\t\t\t   rec::HitRecord)::Scatter{T} where T\n\treflected = normalize(reflect(r_in.dir, rec.n\u20d7) + \n\t\t\t\t\t\t  mat.fuzz*random_vec3_on_sphere(T))\n\tScatter(Ray(rec.p, reflected), mat.albedo)\nend\n\n# \u2554\u2550\u2561 851c002c-dc23-4999-b28c-a716c5d2d42c\nmd\"# Scenes\"\n\n# \u2554\u2550\u2561 70530f8e-1b29-4588-927f-d38d5d12d5c9\n#\"Scene with 2 Lambertian spheres\"\nfunction scene_2_spheres(; elem_type::Type{T}) where T\n\tspheres = Sphere[]\n\t\n\t# small center sphere\n\tpush!(spheres, Sphere((SA{T}[0,0,-1]), T(0.5), Lambertian(SA{T}[0.7,0.3,0.3])))\n\t\n\t# ground sphere\n\tpush!(spheres, Sphere((SA{T}[0,-100.5,-1]), T(100), \n\t\t\t\t\t\t   Lambertian(SA{T}[0.8,0.8,0.0])))\n\tHittableList(spheres)\nend\n\n# \u2554\u2550\u2561 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(; elem_type::Type{T}) where T\n\tscene = scene_2_spheres(; elem_type=elem_type)\n\n\t# left and right Metal spheres\n\tpush!(scene, Sphere((SA{T}[-1,0,-1]), T(0.5), \n\t\tMetal((SA{T}[0.8,0.8,0.8]), T(0.3)))) \n\tpush!(scene, Sphere((SA{T}[ 1,0,-1]), T(0.5), \n\t\tMetal((SA{T}[0.8,0.6,0.2]), T(0.8))))\n\treturn scene\nend\n\n# \u2554\u2550\u2561 282a4912-7a6e-44ae-90eb-f2f7c8f3d0f4\nmd\"\"\"# Camera\n\nAdapted from C++'s sections 7.2, 11.1 \"\"\"\n\n# \u2554\u2550\u2561 a0e5a1f3-244f-427b-a335-7e233af1d9d8\nstruct 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# \u2554\u2550\u2561 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::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 \u00d7 w)\n\tv = w \u00d7 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\n# \u2554\u2550\u2561 eda07d5f-ab0a-41ba-a411-577be0d7e56e\ndefault_camera(lookfrom, lookat, vup, vfov, aspect_ratio, aperture, focus_dist;\n\t\t\t   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# \u2554\u2550\u2561 c1aef1be-79d4-4417-be36-ae8416465986\ndefault_camera(SA[0f0,0f0,0f0]) # Float32 camera\n\n# \u2554\u2550\u2561 94081092-afc6-4359-bd2c-15e8407bf70e\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\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# \u2554\u2550\u2561 813eaa13-2eb2-4302-9e4d-5d1dab0ac7c4\n# example with Float32:\nget_ray(default_camera(SA[0f0,0f0,0f0]), 0.0f0, 0.0f0)\n\n# \u2554\u2550\u2561 90dbe8e5-139d-404a-bfed-177776dc5401\nELEM_TYPE = Float64 # default Element type\n\n# \u2554\u2550\u2561 e4e74dd4-7f0d-4af7-9cf1-a615a0304293\nt_default_cam = default_camera(SA{ELEM_TYPE}[0,0,0]);\n\n# \u2554\u2550\u2561 891ce2c8-f8b2-472b-a8d9-389dafddcf22\nmd\"# Render\"\n\n# \u2554\u2550\u2561 5f1bae02-d425-4a73-8668-d6383faba79d\nmd\"\"\"# Dielectrics\n\nfrom Section 10.2 Snell's Law:\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fbba5135-7ea3-4471-938a-be13c764feff\nmd\"\"\"\nRefracted angle `sin\u03b8\u2032 = (\u03b7/\u03b7\u2032)\u22c5sin\u03b8`, where \u03b7 (\\eta) are the refractive indices.\n\nSplit the parts of the ray into `R\u2032=R\u2032\u22a5+R\u2032\u2225` (perpendicular and parallel to n\u20d7\u2032).\"\"\"\n\n# \u2554\u2550\u2561 9dc64353-c41c-45b4-aacd-12d5d6117c58\n@inline @fastmath function refract(dir::Vec3{T}, n\u20d7::Vec3{T}, \n\t\t\t\t\t\t\t\t   refraction_ratio::T) where T\n\tcos\u03b8 = min(-dir \u22c5 n\u20d7, one(T))\n\tr_out_perp = refraction_ratio * (dir + cos\u03b8*n\u20d7)\n\tr_out_parallel = -\u221a(abs(one(T)-squared_length(r_out_perp))) * n\u20d7\n\tnormalize(r_out_perp + r_out_parallel)\nend;\n\n# \u2554\u2550\u2561 bbfd4db5-3650-4f27-9777-2ff981c3d28b\nbegin # optional tests\n\t# unchanged angle\n\t@assert refract((@SVector[0.6,-0.8,0]), (@SVector[0.0,1.0,0.0]), 1.0) == \n\t\t\t\t@SVector[0.6,-0.8,0.0] \n\n\t# wider angle\n\tt_refract_wider\u03b8 = refract(@SVector[0.6,-0.8,0.0], @SVector[0.0,1.0,0.0], 2.0)\n\t@assert isapprox(t_refract_wider\u03b8, @SVector[0.87519,-0.483779,0.0]; atol=1e-3)\n\n\t# narrower angle\n\tt_refract_narrower\u03b8 = refract(@SVector[0.6,-0.8,0.0], @SVector[0.0,1.0,0.0], 0.5)\n\t@assert isapprox(t_refract_narrower\u03b8, @SVector[0.3,-0.953939,0.0]; atol=1e-3)\nend\n\n# \u2554\u2550\u2561 f5c4e502-048c-4fcd-879f-eaeb4430c012\nstruct Dielectric{T} <: Material{T}\n\tir::T # index of refraction, i.e. \u03b7.\nend\n\n# \u2554\u2550\u2561 167cc207-7be6-4624-8425-2df81b3f6c3b\n@inline @fastmath function reflectance(cos\u03b8, refraction_ratio)\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 = (1-refraction_ratio) / (1+refraction_ratio)\n\tr0 = r0^2\n\tr0 + (1-r0)*((1-cos\u03b8)^5)\nend\n\n# \u2554\u2550\u2561 ae3b8f15-985d-4f74-ac8c-86a3ffc3b8b1\n@inline @fastmath function scatter(mat::Dielectric{T}, r_in::Ray{T},\n\t\t\t\t\t\t\t\t   rec::HitRecord{T}) where T\n\tattenuation = SA{T}[1,1,1]\n\trefraction_ratio = rec.front_face ? (one(T)/mat.ir) : mat.ir # i.e. \u03b7\u1d62/\u03b7\u209c\n\tcos\u03b8 = min(-r_in.dir\u22c5rec.n\u20d7, one(T))\n\tsin\u03b8 = \u221a(one(T) - cos\u03b8^2)\n\tcannot_refract = refraction_ratio * sin\u03b8 > one(T)\n\tif cannot_refract || reflectance(cos\u03b8, refraction_ratio) > trand(T)\n\t\tdir = reflect(r_in.dir, rec.n\u20d7)\n\telse\n\t\tdir = refract(r_in.dir, rec.n\u20d7, refraction_ratio)\n\tend\n\tScatter(Ray{T}(rec.p, dir), attenuation) # TODO: rename reflected -> !absorbed?\nend\n\n# \u2554\u2550\u2561 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?\"\"\"\n@inline @fastmath function ray_color(r::Ray{T}, world::HittableList, \n\t\t\t\t\t\t\t\t     depth=16) where T\n    if depth <= 0\n\t\treturn SA{T}[0,0,0]\n\tend\n\t\t\n\trec::Union{HitRecord,Nothing} = hit(world, r, T(1e-4), typemax(T))\n    if rec !== nothing\n\t\t# For debugging, represent vectors as RGB:\n\t\t# claforte TODO: adapt to latest code!\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\u20d7) # show the normal in RGB\n\t\t# return color_vec3_in_rgb(rec.p + rec.n\u20d7)\n\t\t# return color_vec3_in_rgb(random_vec3_in_sphere())\n\t\t#return color_vec3_in_rgb(rec.n\u20d7 + 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 SA{T}[0,0,0]\n\t\tend\n    else\n        skycolor(r)\n    end\nend\n\n\n# \u2554\u2550\u2561 64104df6-4b79-4329-bfed-14619aa73e3c\nfunction render(scene::HittableList, cam::Camera{T}, image_width=400,\n\t\t\t\tn_samples=1) where T\n\t# Image\n\taspect_ratio = T(16.0/9.0)\n\timage_height = convert(Int64, floor(image_width / aspect_ratio))\n\n\t# Render\n\timg = zeros(RGB{T}, image_height, image_width)\n\tf32_image_width = convert(Float32, image_width)\n\tf32_image_height = convert(Float32, image_height)\n\t\n\treseed!() # Reset the random seeds, to get same images... easier to compare perf!\n\n\tThreads.@threads for i in 1:image_height # Use every allowed thread\n\t\t@inbounds for j in 1:image_width\n\t\t\taccum_color = SA{T}[0,0,0]\n\t\t\tu = convert(T, j/image_width)\n\t\t\tv = convert(T, (image_height-i)/image_height) # i is Y-down, v is Y-up!\n\t\t\t\n\t\t\tfor s in 1:n_samples\n\t\t\t\tif s == 1 # 1st sample is always centered\n\t\t\t\t\t\u03b4u = \u03b4v = T(0)\n\t\t\t\telse # Supersampling antialiasing.\n\t\t\t\t\t\u03b4u = trand(T) / f32_image_width\n\t\t\t\t\t\u03b4v = trand(T) / f32_image_height\n\t\t\t\tend\n\t\t\t\tray = get_ray(cam, u+\u03b4u, v+\u03b4v)\n\t\t\t\taccum_color += ray_color(ray, scene)\n\t\t\tend\n\t\t\timg[i,j] = rgb_gamma2(accum_color / n_samples)\n\t\tend\n\tend\n\timg\nend;\n\n# \u2554\u2550\u2561 aa38117f-45e8-4070-a412-958f0ce19aa5\nrender(scene_2_spheres(; elem_type=ELEM_TYPE), t_default_cam, 200, 64) # took 247ms\n\n# \u2554\u2550\u2561 a2221922-31be-42f3-8f70-845fae385d2c\nrender(scene_4_spheres(; elem_type=ELEM_TYPE), t_default_cam, 200, 256)\n\n# \u2554\u2550\u2561 ddf5883c-036a-4a21-908d-bb7cec731f7f\n#\"From C++: Image 15: Glass sphere that sometimes refracts\"\n# dielectric spheres\n@inline function scene_diel_spheres(left_radius=0.5; elem_type::Type{T}) where T\n\tspheres = Sphere[]\n\t\n\t# small center sphere\n\tpush!(spheres, Sphere((SA{T}[0,0,-1]), T(0.5), Lambertian(SA{T}[0.1,0.2,0.5])))\n\t\n\t# ground sphere (planet?)\n\tpush!(spheres, Sphere((SA{T}[0,-100.5,-1]), T(100), \n\t\tLambertian(SA{T}[0.8,0.8,0.0])))\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((SA{T}[-1,0,-1]), T(left_radius), Dielectric(T(1.5)))) \n\tpush!(spheres, Sphere((SA{T}[1,0,-1]), T(0.5), \n\t\tMetal((SA{T}[0.8,0.6,0.2]), T(0))))\n\tHittableList(spheres)\nend\n\n# \u2554\u2550\u2561 a1564d79-3628-4121-99a9-d3674e16eb04\nrender(scene_diel_spheres(; elem_type=ELEM_TYPE), t_default_cam, 320, 64)\n\n# \u2554\u2550\u2561 2e9672e3-f2b8-439e-b1f3-3cc60a459885\n# Hollow Glass sphere using a negative radius\nrender(scene_diel_spheres(; elem_type=ELEM_TYPE), \n\tdefault_camera((SA{ELEM_TYPE}[-2,2,1]), (SA{ELEM_TYPE}[0,0,-1]),\n\t\t(SA{ELEM_TYPE}[0,1,0]), ELEM_TYPE(20)), 320, 128)\n\n# \u2554\u2550\u2561 0587d381-b957-4c40-b6b7-e5e0fd46267b\nmd\"# Positioning camera\"\n\n# \u2554\u2550\u2561 7c75b0d8-578d-4ca9-8d74-935c1ac582b9\nfunction scene_blue_red_spheres(; elem_type::Type{T}) where T\n\tspheres = Sphere[]\n\tR = cos(\u03c0/4)\n\tpush!(spheres, Sphere((SA{T}[-R,0,-1]), R, Lambertian(SA{T}[0,0,1]))) \n\tpush!(spheres, Sphere((SA{T}[ R,0,-1]), R, Lambertian(SA{T}[1,0,0]))) \n\tHittableList(spheres)\nend\n\n# \u2554\u2550\u2561 dcde1539-23af-4abf-96d3-6a903add3ea8\nrender(scene_blue_red_spheres(; elem_type=ELEM_TYPE), t_default_cam, 200, 64)\n\n# \u2554\u2550\u2561 e3ef265c-1911-429d-84be-5d5174d55fa1\nmd\"# Spheres with depth-of-field\"\n\n# \u2554\u2550\u2561 f49ac345-c19c-4fe5-9dee-dbfeff3ff646\nt_cam2 = default_camera([3,3,2], [0,0,-1], [0,1,0], 20, 16/9, 2.0, \n\tnorm([3,3,2]-[0,0,-1]); elem_type=ELEM_TYPE)\n\n# \u2554\u2550\u2561 90bb20e4-4afa-46aa-a7b7-5de446efa439\nrender(scene_diel_spheres(; elem_type=ELEM_TYPE), t_cam2, 320, 128)\n\n# \u2554\u2550\u2561 3c54cde0-6509-45e1-a4a0-26c6aa840b8e\nmd\"# Random spheres\"\n\n# \u2554\u2550\u2561 a7d95d91-6571-4696-bad3-2979296d5f84\nfunction scene_random_spheres(; elem_type::Type{T}) where T \n\tspheres = Sphere[]\n\n\t# ground \n\tpush!(spheres, Sphere((SA{T}[0,-1000,-1]), T(1000), \n\t\t\t\t\t\t  Lambertian(SA{T}[0.5,0.5,0.5])))\n\n\tfor a in -11:10, b in -11:10\n\t\tchoose_mat = trand(T)\n\t\tcenter = SA[a + T(0.9)*trand(T), T(0.2), b + T(0.9)*trand(T)]\n\n\t\t# skip spheres too close?\n\t\tif norm(center - SA{T}[4,0.2,0]) < T(0.9) continue end \n\t\t\t\n\t\tif choose_mat < T(0.8)\n\t\t\t# diffuse\n\t\t\talbedo = @SVector[trand(T) for i \u2208 1:3] .* @SVector[trand(T) for i \u2208 1:3]\n\t\t\tpush!(spheres, Sphere(center, T(0.2), Lambertian(albedo)))\n\t\telseif choose_mat < T(0.95)\n\t\t\t# metal\n\t\t\talbedo = @SVector[random_between(T(0.5),T(1.0)) for i \u2208 1:3]\n\t\t\tfuzz = random_between(T(0.0), T(5.0))\n\t\t\tpush!(spheres, Sphere(center, T(0.2), Metal(albedo, fuzz)))\n\t\telse\n\t\t\t# glass\n\t\t\tpush!(spheres, Sphere(center, T(0.2), Dielectric(T(1.5))))\n\t\tend\n\tend\n\n\tpush!(spheres, Sphere((SA{T}[0,1,0]), T(1), Dielectric(T(1.5))))\n\tpush!(spheres, Sphere((SA{T}[-4,1,0]), T(1), \n\t\t\t\t\t\t  Lambertian(SA{T}[0.4,0.2,0.1])))\n\tpush!(spheres, Sphere((SA{T}[4,1,0]), T(1), \n\t\t\t\t\t\t  Metal((SA{T}[0.7,0.6,0.5]), T(0))))\n\tHittableList(spheres)\nend\n\n# \u2554\u2550\u2561 a4b5d575-de27-4b44-a448-bd20be7d73ad\nt_cam1 = default_camera([13,2,3], [0,0,0], [0,1,0], 20, 16/9, 0.1, 10.0; \n\t\t\t\t\t\telem_type=ELEM_TYPE);\n\n# \u2554\u2550\u2561 da047747-1845-4c2b-b3cb-eaa6534ce5ff\nrender(scene_random_spheres(; elem_type=ELEM_TYPE), t_cam1, 320, 32) # 1.1s\n\n# \u2554\u2550\u2561 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nImages = \"916415d5-f1e6-5110-898d-aaa5f9f070e0\"\nInteractiveUtils = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nLoopVectorization = \"bdcacae8-1622-11e9-2a5c-532679323890\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nRandomNumbers = \"e6cf234a-135c-5ec9-84dd-332b85af5143\"\nStaticArrays = \"90137ffa-7385-5640-81b9-e52037218182\"\n\n[compat]\nBenchmarkTools = \"~1.2.2\"\nImages = \"~0.25.0\"\nLoopVectorization = \"~0.12.99\"\nRandomNumbers = \"~1.5.3\"\nStaticArrays = \"~1.2.13\"\n\"\"\"\n\n# \u2554\u2550\u2561 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[[BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Profile\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"940001114a0147b6e4d10624276d56d531dd9b49\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.2.2\"\n\n[[BitTwiddlingConvenienceFunctions]]\ndeps = [\"Static\"]\ngit-tree-sha1 = \"bc1317f71de8dce26ea67fcdf7eccc0d0693b75b\"\nuuid = \"62783981-4cbd-42fc-bca8-16325de8dc4b\"\nversion = \"0.1.1\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[CPUSummary]]\ndeps = [\"Hwloc\", \"IfElse\", \"Static\"]\ngit-tree-sha1 = \"87b0c9c6ee0124d6c1f4ce8cb035dcaf9f90b803\"\nuuid = \"2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9\"\nversion = \"0.1.6\"\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[[CloseOpenIntervals]]\ndeps = [\"ArrayInterface\", \"Static\"]\ngit-tree-sha1 = \"7b8f09d58294dc8aa13d91a8544b37c8a1dcbc06\"\nuuid = \"fb6a15b2-703c-40df-9091-08a04967cfa9\"\nversion = \"0.1.4\"\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[[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[[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[[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 = \"9bc5dac3c8b6706b58ad5ce24cffd9861f07c94f\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.9.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[[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[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"2b72a5624e289ee18256111657663721d59c143e\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.24\"\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[[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[[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[[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[[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[[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[[LoopVectorization]]\ndeps = [\"ArrayInterface\", \"CPUSummary\", \"CloseOpenIntervals\", \"DocStringExtensions\", \"HostCPUFeatures\", \"IfElse\", \"LayoutPointers\", \"LinearAlgebra\", \"OffsetArrays\", \"PolyesterWeave\", \"Requires\", \"SIMDDualNumbers\", \"SLEEFPirates\", \"Static\", \"ThreadingUtilities\", \"UnPack\", \"VectorizationBase\"]\ngit-tree-sha1 = \"9e10579c154f785b911d9ceb96c33fcc1a661171\"\nuuid = \"bdcacae8-1622-11e9-2a5c-532679323890\"\nversion = \"0.12.99\"\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[[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_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[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"d7fa6237da8004be601e19bd6666083056649918\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.1.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[[PolyesterWeave]]\ndeps = [\"BitTwiddlingConvenienceFunctions\", \"CPUSummary\", \"IfElse\", \"Static\", \"ThreadingUtilities\"]\ngit-tree-sha1 = \"a3ff99bf561183ee20386aec98ab8f4a12dc724a\"\nuuid = \"1d0040c9-8b98-4ee7-8388-3f51789ca0ad\"\nversion = \"0.1.2\"\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[[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[[RandomNumbers]]\ndeps = [\"Random\", \"Requires\"]\ngit-tree-sha1 = \"043da614cc7e95c703498a491e2c21f58a2b8111\"\nuuid = \"e6cf234a-135c-5ec9-84dd-332b85af5143\"\nversion = \"1.5.3\"\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[[SIMDDualNumbers]]\ndeps = [\"ForwardDiff\", \"IfElse\", \"SLEEFPirates\", \"VectorizationBase\"]\ngit-tree-sha1 = \"62c2da6eb66de8bb88081d20528647140d4daa0e\"\nuuid = \"3cdde19b-5bb0-4aaf-8931-af3e248e098b\"\nversion = \"0.1.0\"\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[[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[[ThreadingUtilities]]\ndeps = [\"ManualMemory\"]\ngit-tree-sha1 = \"03013c6ae7f1824131b2ae2fc1d49793b51e8394\"\nuuid = \"8290d209-cae3-49c0-8002-c8c24d57dab5\"\nversion = \"0.4.6\"\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[[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[[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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000866add2-9b95-45e7-8081-c01cd2a66911\n# \u255f\u2500611d5eae-4b09-11ec-27bf-ef4a1ecdcc41\n# \u255f\u250097bb4432-ed41-423b-b4d9-bafc519de641\n# \u2560\u255038fdd4ef-c383-4f97-8451-c6f602307e7d\n# \u2560\u25509114285c-4c5a-482c-94d8-21c3e4cc79e4\n# \u2560\u255084d29423-cf11-41c3-af4d-c5f63b1ef23e\n# \u2560\u25507d26fef0-9a06-479a-ae08-e9d04e455767\n# \u2560\u2550f29ad2c0-c3ff-484d-8fdd-dff34d2bb863\n# \u2560\u25502192e695-4378-4b47-8ce0-353636cd2cd1\n# \u2560\u2550538d1aa5-07f9-4fca-8410-ef63b8a6857b\n# \u2560\u25508aeb7373-6bb0-4544-8655-fa941561688c\n# \u2560\u2550154d736b-8fdc-44af-ae2a-9e5ba6d2c92e\n# \u255f\u2500216922d8-613a-4ac1-9559-40878e6587e2\n# \u2560\u2550961fd749-d439-4dfa-ae21-b1659dc54511\n# \u2560\u2550f8007c75-9487-414a-9592-138a696c2957\n# \u2560\u2550668030c8-24a7-4aa6-b858-cedf8ac5f988\n# \u2560\u255071cee0d1-ff0a-4234-b393-8f20834f6415\n# \u2560\u25503eb50f44-9091-45e8-a7e1-92d25b4b2090\n# \u2560\u255078f209df-d176-4711-80fc-a8054771f105\n# \u2560\u2550e88de775-6904-4182-8209-06db22758470\n# \u2560\u25505fd1ec87-3616-448a-ab4d-fede804b26d5\n# \u2560\u2550a0893bf4-9607-4853-8162-9f34d3337060\n# \u2560\u2550cfbcb883-d12e-4ad3-a084-064749bddcdb\n# \u2560\u25506348c03d-e8ec-4dbb-9f8a-8e4a48bb1cb3\n# \u2560\u2550dbc8fc2d-39c2-4ec9-b82d-7c6a8b12dde7\n# \u2560\u255053832af1-a9be-4e02-8b71-a70dae63c233\n# \u2560\u255081b4c9e4-9f93-45ca-9fa0-7e9686a55e9a\n# \u255f\u2500772674b0-5c40-4457-9526-5b4e81cca711\n# \u2560\u2550cdf96967-6790-4bd5-8890-40de9365a05a\n# \u2560\u2550c58754e4-26b6-4b1d-be61-447496332757\n# \u2560\u2550709861a3-202a-4bff-a46d-b46c6e14b334\n# \u2560\u2550135000d6-a675-4d8b-9385-50853bf9a169\n# \u2560\u25507d1146d7-74da-42e6-92c2-1312ed03f70d\n# \u2560\u255046a4aa4b-82c1-4941-b36d-dc8c977af2bc\n# \u2560\u2550203a9b25-742a-4d8b-adee-862ce4c67670\n# \u2560\u25502e98c6bd-0289-4105-ad25-24414ecf2750\n# \u2560\u2550b5407efd-8071-43e7-b9f4-de1bd9de7311\n# \u2560\u2550c0c23cb3-6a57-487d-943a-af4330a94ffe\n# \u2560\u25503851fa56-2c73-45eb-9089-65eec0237f14\n# \u255f\u2500678214c5-de81-489f-b002-c343d48071c9\n# \u2560\u2550cbb6418c-79e9-4359-80a6-40a8fa40679e\n# \u2560\u2550971777a6-f269-4344-8dba-7a55118396e5\n# \u2560\u2550655ffa6c-f1e9-4149-8f1d-51145c5a51e4\n# \u255f\u25009075f8ed-f319-486d-94b2-486806aba3fd\n# \u2560\u2550c00e2004-2002-4dd2-98ed-f898ef2c14f1\n# \u2560\u2550b7399fb8-6205-41ea-9c70-eb62daedcefb\n# \u2560\u25501d04159d-87bd-4cf8-a73c-817f20ca1026\n# \u255f\u2500fed81f09-e4a0-433f-99e8-261096114b7b\n# \u2560\u255024e8740a-8e44-4206-b2b6-c4a55002dad8\n# \u2560\u2550359832af-7598-4c45-8033-c28cb0d86772\n# \u2560\u2550ed6ab8be-587c-4cb6-8172-618c74d3f9cc\n# \u2560\u2550a65c68c9-e489-465a-9687-93ae9da14a5e\n# \u2560\u25502c4b4453-1a46-4889-9a14-16b18cc8c240\n# \u2560\u25503b570d37-f407-41d8-b8a0-a0af4d85b14d\n# \u2560\u2550138bb5b6-0f45-4f13-8339-5110eb7cd1ff\n# \u255f\u25006b36d245-bf01-45a7-b119-8315226dd4a3\n# \u2560\u25504a396b3f-f920-4ec2-91f6-7d61fe2b9699\n# \u2560\u2550427f247c-055c-459e-9862-26e9f6f3e24f\n# \u2560\u255088e51c27-0f28-4dcc-b9e9-ac44eeb876f5\n# \u2560\u25507c4a67b2-8208-4cd4-b1ea-16f6f50adfe8\n# \u2560\u255087de4e8e-f7a2-4b47-991c-9b2988782ef4\n# \u2560\u2550485f9c5b-4c5d-453c-b190-e84ae0cd1a21\n# \u2560\u255078efebc5-53fd-417d-bd9e-667fd504e3fd\n# \u2560\u255005e57afd-6eb9-42c5-9666-7be3771fa6b8\n# \u2560\u255008e18ae5-9927-485e-9644-552f03e06f27\n# \u2560\u2550737e2f87-82f5-45b6-a76c-4f560c29f5b9\n# \u2560\u2550f72214f9-03c4-4ba3-bb84-069256446b31\n# \u2560\u25500bf88264-d4c5-4d5a-babe-d2433e46024d\n# \u2560\u2550555bea1d-5178-48dd-87e6-4e2a2471a5dd\n# \u2560\u2550c299ca47-46c4-42da-9f8b-ae3abbeb6e51\n# \u255f\u2500851c002c-dc23-4999-b28c-a716c5d2d42c\n# \u2560\u255070530f8e-1b29-4588-927f-d38d5d12d5c9\n# \u2560\u2550c5349670-4df4-421f-9d5a-b28c1b9040c2\n# \u255f\u2500282a4912-7a6e-44ae-90eb-f2f7c8f3d0f4\n# \u2560\u2550a0e5a1f3-244f-427b-a335-7e233af1d9d8\n# \u2560\u25505d00f26b-35f2-4071-8e04-227ffc25f184\n# \u2560\u2550eda07d5f-ab0a-41ba-a411-577be0d7e56e\n# \u2560\u2550c1aef1be-79d4-4417-be36-ae8416465986\n# \u2560\u255094081092-afc6-4359-bd2c-15e8407bf70e\n# \u2560\u2550813eaa13-2eb2-4302-9e4d-5d1dab0ac7c4\n# \u2560\u255090dbe8e5-139d-404a-bfed-177776dc5401\n# \u2560\u2550e4e74dd4-7f0d-4af7-9cf1-a615a0304293\n# \u255f\u2500891ce2c8-f8b2-472b-a8d9-389dafddcf22\n# \u2560\u255064104df6-4b79-4329-bfed-14619aa73e3c\n# \u2560\u2550aa38117f-45e8-4070-a412-958f0ce19aa5\n# \u2560\u2550a2221922-31be-42f3-8f70-845fae385d2c\n# \u255f\u25005f1bae02-d425-4a73-8668-d6383faba79d\n# \u255f\u250071f3626c-e61d-4838-82b9-ac8a978c0cb4\n# \u255f\u2500fbba5135-7ea3-4471-938a-be13c764feff\n# \u2560\u25509dc64353-c41c-45b4-aacd-12d5d6117c58\n# \u2560\u2550bbfd4db5-3650-4f27-9777-2ff981c3d28b\n# \u2560\u2550f5c4e502-048c-4fcd-879f-eaeb4430c012\n# \u2560\u2550167cc207-7be6-4624-8425-2df81b3f6c3b\n# \u2560\u2550ae3b8f15-985d-4f74-ac8c-86a3ffc3b8b1\n# \u2560\u2550ddf5883c-036a-4a21-908d-bb7cec731f7f\n# \u2560\u2550a1564d79-3628-4121-99a9-d3674e16eb04\n# \u2560\u25502e9672e3-f2b8-439e-b1f3-3cc60a459885\n# \u255f\u25000587d381-b957-4c40-b6b7-e5e0fd46267b\n# \u2560\u25507c75b0d8-578d-4ca9-8d74-935c1ac582b9\n# \u2560\u2550dcde1539-23af-4abf-96d3-6a903add3ea8\n# \u255f\u2500e3ef265c-1911-429d-84be-5d5174d55fa1\n# \u2560\u2550f49ac345-c19c-4fe5-9dee-dbfeff3ff646\n# \u2560\u255090bb20e4-4afa-46aa-a7b7-5de446efa439\n# \u255f\u25003c54cde0-6509-45e1-a4a0-26c6aa840b8e\n# \u2560\u2550a7d95d91-6571-4696-bad3-2979296d5f84\n# \u2560\u2550a4b5d575-de27-4b44-a448-bd20be7d73ad\n# \u2560\u2550da047747-1845-4c2b-b3cb-eaa6534ce5ff\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "4df3d304754de0d2a037c0f5171bbc688ebf0450", "size": 60816, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pluto_RayTracingWeekend.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/pluto_RayTracingWeekend.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/pluto_RayTracingWeekend.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.5916398714, "max_line_length": 419, "alphanum_fraction": 0.7181827151, "num_tokens": 27299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.7871127591016215}}
{"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 = [\u03b1, \u03b2, \u03b4, \u03b3]\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": "using OrdinaryDiffEq, ModelingToolkit, Test\r\n@parameters t\r\n@variables y[1:3](t)\r\n@parameters k[1:3]\r\n@derivatives D'~t\r\n\r\neqs = [D(y[1]) ~ -k[1]*y[1] + k[3]*y[2]*y[3],\r\n       D(y[2]) ~  k[1]*y[1] - k[3]*y[2]*y[3] - k[2]*y[2]^2,\r\n       0 ~  y[1] + y[2] + y[3] - 1]\r\n\r\nsys = ODESystem(eqs,t,y,k)\r\nM = calculate_massmatrix(sys)\r\n@test M == [1 0 0\r\n            0 1 0\r\n            0 0 0]\r\n\r\nf = ODEFunction(sys)\r\nprob_mm = ODEProblem(f,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))\r\nsol = solve(prob_mm,Rodas5(),reltol=1e-8,abstol=1e-8)\r\n\r\nfunction rober(du,u,p,t)\r\n  y\u2081,y\u2082,y\u2083 = u\r\n  k\u2081,k\u2082,k\u2083 = p\r\n  du[1] = -k\u2081*y\u2081 + k\u2083*y\u2082*y\u2083\r\n  du[2] =  k\u2081*y\u2081 - k\u2083*y\u2082*y\u2083 - k\u2082*y\u2082^2\r\n  du[3] =  y\u2081 + y\u2082 + y\u2083 - 1\r\n  nothing\r\nend\r\nf = ODEFunction(rober,mass_matrix=M)\r\nprob_mm2 = ODEProblem(f,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))\r\nsol2 = solve(prob_mm2,Rodas5(),reltol=1e-8,abstol=1e-8)\r\n\r\n@test Array(sol) == Array(sol2)\r\n", "meta": {"hexsha": "f292c89061be7570acce3bca556b12a2f957a5c0", "size": 898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mass_matrix.jl", "max_stars_repo_name": "ranjanan/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "c3d4cbe1de502c28c0d1f250f1bb87c2e799e3cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-10T16:03:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-10T16:03:43.000Z", "max_issues_repo_path": "test/mass_matrix.jl", "max_issues_repo_name": "ranjanan/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "c3d4cbe1de502c28c0d1f250f1bb87c2e799e3cd", "max_issues_repo_licenses": ["MIT"], "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/mass_matrix.jl", "max_forks_repo_name": "ranjanan/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "c3d4cbe1de502c28c0d1f250f1bb87c2e799e3cd", "max_forks_repo_licenses": ["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.4117647059, "max_line_length": 64, "alphanum_fraction": 0.5467706013, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.787077123950124}}
{"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}; \u03c3::Float64=1.0) = kernel(GaussianKernel(\u03c3), x, y)\n\nfunction train_model(Fs::Array{Float64,1}, X::Array{Float64,2}; k::Kernel = GaussianKernel(1.0), \u03bb::Float64 = 0.0 )\n    \"\"\"\n    X is a N\u00d7D, 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] += \u03bb\n    end\n\n    A[N+1, N+1] = 0.0\n\n    # y = Ab\n    # b = A\u207b\u00b9 \u22c5 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), \u03bb::Float64 = 0.0 )\n    train_model(Fs, reshape(X_train, length(X_train), 1), k = k)\nend\n\n\nF\u0302(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(\u03b1::Array{Float64,1}, X::Array{Float64,2}, X_train::Array{Float64,2}; k::Kernel = GaussianKernel()) = [F\u0302(X[i,:], \u03b1, 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\u00d7D matrix, that contains N row vectors in R^D\n    \"\"\"\n\n    \u03b1 = train_model(Fs, X_train, k = k)\n\n    return approx_values(\u03b1, X_test, X_train, k = k), \u03b1\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\u00d71 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": "using JITrench \nusing Random\nusing Printf\nusing Plots\n\n\n\nRandom.seed!(10)\n\nfunction generate_datset(N)\n    x = rand(N) * 10\n    y = 2x .+ 3 .+ (rand(N) .* 5)\n    return x, y\nend\n\nfunction predict(x, W, b)\n    y = JITrench.matmul(x, W) .+ b\n    return y\nend\n\nfunction mse(y_true, y_pred)\n    diff = y_true .- y_pred\n    return JITrench.sum(diff .^ 2) / length(diff.values)\nend\n\n\nfunction train(x, y, W_init, b_init, n_iter; lr=0.01)\n    x = Variable(x)\n    y = Variable(y)\n    W = Variable(W_init)\n    b = Variable(b_init)\n    history = []\n    for iter in 1:n_iter\n        y_pred = predict(x, W, b)\n        loss = mse(y, y_pred)\n        JITrench.cleargrad!(W)\n        JITrench.cleargrad!(b)\n        backward!(loss)\n        W.values -= W.grad.values * lr\n        b.values -= b.grad.values * lr\n        push!(history, loss.values)\n        @printf \"iters %4i [loss] %.2f [W] %.2f [b] %.2f\\n\" iter loss.values W.values b.values\n    end\n    return W, b, history\nend\n\n\n\n\nx, y = generate_datset(100)\nW = rand()\nb = rand()\nn_iters = 100\n\nW_trained, b_trained, history = train(x, y, W, b, n_iters)\n\n\nprintln(\"finish train.\")\n@show W_trained\n@show b_trained\n\nplt = scatter(x, y, label=[\"data\"])\nplot!(plt, 1:0.1:10, predict(Variable(collect(1:0.1:10)), W_trained, b_trained).values, label=[\"predict\"])\nsavefig(\"predict.png\")\n\nplot(history, title=\"learning curve\", yaxis=:log10)\nsavefig(\"history.png\")", "meta": {"hexsha": "75f3f85e430963b545b8ba141ca7b251f1879504", "size": 1389, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/linear_model/linear_regression.jl", "max_stars_repo_name": "abap34/JITrench.jl", "max_stars_repo_head_hexsha": "38a065a674428cb0760eee4b03f54bdbbf0af06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-06-19T05:32:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T14:33:11.000Z", "max_issues_repo_path": "example/linear_model/linear_regression.jl", "max_issues_repo_name": "abap34/JITrench.jl", "max_issues_repo_head_hexsha": "38a065a674428cb0760eee4b03f54bdbbf0af06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-28T16:17:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T15:33:01.000Z", "max_forks_repo_path": "example/linear_model/linear_regression.jl", "max_forks_repo_name": "abap34/JITrench.jl", "max_forks_repo_head_hexsha": "38a065a674428cb0760eee4b03f54bdbbf0af06a", "max_forks_repo_licenses": ["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.7313432836, "max_line_length": 106, "alphanum_fraction": 0.6155507559, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7870771096479112}}
{"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    \u03bb = xLon * 0.017453292519943295    # \u03bb = xLon * \u03c0 / 180\r\n    \u03d5 = yLat * 0.017453292519943295    # \u03d5 = yLat * \u03c0 / 180\r\n\r\n    # Convert to Web Mercator\r\n    # Note that:\r\n    # atanh(sin(\u03d5)) = log(tan(\u03c0/4 + \u03d5/2)) = 1/2 * log((1 + sin(\u03d5)) / (1 - sin(\u03d5)))\r\n    x = a * \u03bb\r\n    y = a * atanh(sin(\u03d5))\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    \u03bb = xLon * 0.017453292519943295    # \u03bb = xLon * \u03c0 / 180\r\n    \u03d5 = yLat * 0.017453292519943295    # \u03d5 = yLat * \u03c0 / 180\r\n\r\n    # Convert to Web Mercator projection pixel number\r\n    # E.g. world coordinate range x \u2208 (0,256) and y \u2208 (0,256) at zoom level 0\r\n    # Note that:\r\n    # atanh(sin(\u03d5)) = log(tan(\u03c0/4 + \u03d5/2)) = 1/2 * log((1 + sin(\u03d5)) / (1 - sin(\u03d5)))\r\n    # 256/2\u03c0 = 40.74366543152521\r\n    px = 40.74366543152521 * 2^zoom * (\u03bb + \u03c0)\r\n    py = 40.74366543152521 * 2^zoom * (\u03c0 - atanh(sin(\u03d5)))\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 / \u03c0 * asin(tanh(\u03c0 - py * \u03c0 / (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) = \u03b8\u1d4f (1 - \u03b8)^{1-k}\n```\nfor ``k \u2208 \\\\{0,1\\\\}``, where ``\u03b8 = \u03a6(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(\u03a6(fi)) : log(1.0 - \u03a6(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 ? \u03c6(fi)/\u03a6(fi) : -\u03c6(fi)/(1.0 - \u03a6(fi)) for (fi,yi) in zip(f,y)]\nend\n\n#mean and variance under the likelihood\nmean_lik(bernoulli::BernLik, f::VecF64) = Float64[\u03a6(fi) for fi in f]\nvar_lik(bernoulli::BernLik, f::VecF64) = Float64[\u03a6(fi)*(1-\u03a6(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[\u03a6(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\u03b30 = 0.0\n\u03b3L = 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, [\u03b3L])\nF .+= G\nufix = [\u03b30]\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#\u00a0The following code generates three objects:\n    # 1) A \"TypeScale\" type that transforms ranges into a type of scaled ranges\n    #\u00a02) A \"TypeRange\" type that foroms scaled ranges of a given type.\n    #\u00a0  These ranges behave \"just as\" normal ranges\n    #\u00a03) A ScaledInterpolations function that wraps \"interpolations.jl\" to be used\n    #\u00a0  with TypeRange ranges\n#\u00a0Types of Scales: parameters bounds for grid (a,b) and curvature (\u03b8)\n    #\u00a0p = PolyScale(a,b,\u03b8)\n        #\u00a0Maps a number x\u2208[0,1] to a polynomial grid with curvature \u03b8: p(x)\u2208[a,b]\n        #\u00a0Usage: p(x), where x is a number, or p.(x) where x is vector/range\n        # p(x) = a + (b - a) * x^\u03b8\n    #\u00a0p = InvPolyScale(a,b,\u03b8)\n        #\u00a0Maps a number y\u2208[a,b] from a polynomial grid with curvature \u03b8 to the unit interval: p(x)\u2208[0,1]\n        #\u00a0Usage: p(y), where x is a number, or p.(y) where y is vector/range\n        # p(y) = ((y-a) / (b-a) )^(1/\u03b8)\n    #\u00a0p = ExpScale(a,b,\u03b8)\n        #\u00a0Maps a number x\u2208[0,1] to a exponential grid with curvature \u03b8: p(x)\u2208[a,b]\n        #\u00a0Usage: p(x), where x is a number, or p.(x) where x is vector/range\n        # p(x) = a + (b - a) * ( (exp(\u03b8*x) - 1)/(exp(\u03b8) - 1) )\n    #\u00a0p = LogScale(a,b,\u03b8)\n        #\u00a0Maps a number y\u2208[a,b] from an exponential grid with curvature \u03b8 to the unit interval: p(x)\u2208[0,1]\n        #\u00a0Usage: p(y), where x is a number, or p.(y) where y is vector/range\n        # p(y) = log( (y-a)*(exp(\u03b8) - 1)/(b - a) + 1 ) / \u03b8\n#\u00a0Types of Scaled Ranges\n    #\u00a0grid = PolyRange(a,b,\u03b8=t,N=n) = PolyScale(a,b,t)(range(0,1,length=n))\n    #\u00a0grid =  ExpRange(a,b,\u03b8=t,N=n) =  ExpScale(a,b,t)(range(0,1,length=n))\n# ScaledInterpolations\n    #\u00a0itp = ScaledInterpolations(grid,f_grid,Itp_Type)\n        # grid is either a PolyRange or ExpRange type\n        #\u00a0f_grid is a vector with the values of the function at the grid nodes\n        #\u00a0Itp_Type is a type from the interpolations.jl package\n            # Examples: BSpline(Cubic(Line(OnGrid()))) // shortcut: CubicSpline\n            #\u00a0          BSpline(Cubic(Flat(OnGrid())))\n            #           FritschButlandMonotonicInterpolation()\u00a0// shortcut: MonotoneSpline\n            #\u00a0          BSpline(Linear()) // shortcut: LinearInterp\n# ScaledInterpolations with multiple dimensions\n    #\u00a0itp_md = ScaledInterpolations( (grid_1,...,grid_N) , (f_grid_1,...,f_grid_N) , (Type_1,...,Type_N)  )\u00a0    \n#\u00a0Jacob Adenbaum, 2020\n\n\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\n#\u00a0Define 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            \u03b8::TF\n        end\n\n        @eval function $Foo(a, b, \u03b8 = 1)\n            T = reduce(promote_type, map(typeof, (a,b)))\n            $Foo(convert(T, a), convert(T, b), \u03b8)\n        end\n    end\n\n\n    (p::PolyScale)(x)           = p.a + (p.b - p.a) * x^p.\u03b8\n    (p::InvPolyScale)(y)        = ((y-p.a) / (p.b-p.a) )^(1/p.\u03b8)\n    Base.inv(p::PolyScale)      = InvPolyScale(p.a, p.b, p.\u03b8)\n    Base.inv(p::InvPolyScale)   = PolyScale(p.a, p.b, p.\u03b8)\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            \u03b8::TF\n            et::T\n            s::T\n        end\n\n        @eval function $Foo(a, b, \u03b8 = 1)\n            s = (exp(\u03b8) - 1)/(b - a)\n            et= exp(\u03b8)\n            T = reduce(promote_type, map(typeof, (a,b,\u03b8, et,s)))\n            $Foo(convert(T, a), convert(T, b), \u03b8, et,s)\n        end\n    end\n\n    function (p::ExpScale)(x)\n        t  = (exp(p.\u03b8 * x) - 1)/(p.et - 1)\n        return p.a + (p.b - p.a) * t\n    end\n\n    function (p::LogScale)(y)\n        \u03b8  = p.\u03b8\n        log( (y-p.a)*p.s + 1 ) / p.\u03b8\n    end\n\n    Base.inv(p::ExpScale)       = LogScale(p.a, p.b, p.\u03b8)\n    Base.inv(p::LogScale)       = ExpScale(p.a, p.b, p.\u03b8)\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#\u00a0Define 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            \u03b8::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; \u03b8 = 1, N = 100)\n            T       = reduce(promote_type, map(typeof, (a,b,\u03b8, 1.0)))\n            Ta      = convert(T, a)\n            Tb      = convert(T, b)\n\n            vals    = domscale($Typ)(Ta,Tb,\u03b8).(LinRange(0, 1, N))\n            scale   = $(scales[Typ])(Ta, Tb, \u03b8)\n            invscale= inv($(scales[Typ])(Ta, Tb, \u03b8))\n            $Typ(convert(T, a), convert(T, b), \u03b8, 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.\u03b8), $(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            \u03b8::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; \u03b8 = 1, N = 100)\n            vals    = domscale($Typ)(a,b,\u03b8).(LinRange(0, 1, N))\n            scale   = $(scales[Typ])(a, b, \u03b8)\n            invscale= inv($(scales[Typ])(a, b, \u03b8))\n            T       = reduce(promote_type, map(typeof, (a,b,\u03b8,scale.s)))\n            $Typ(convert(T, a), convert(T, b), \u03b8, 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.\u03b8), $(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#\u00a0Scaled 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#\u00a0Scaled 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    \u0394x = x2 - x1\n    \u0394y = y2 - y1\n    \u0394z = z2 - z1\n\n    return hypot(hypot(\u0394x,  \u0394y), \u0394z)\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    \u03d5\u2081, \u03bb\u2081 = deg2rad(a.lat), deg2rad(a.lon)\n    \u03d5\u2082, \u03bb\u2082 = deg2rad(b.lat), deg2rad(b.lon)\n\n    h\u03d5 = haversin(\u03d5\u2082 - \u03d5\u2081)\n    h\u03bb = haversin(\u03bb\u2082 - \u03bb\u2081)\n\n    h = h\u03d5 + cos(\u03d5\u2081)*cos(\u03d5\u2082)*h\u03bb\n\n    return 2r * asin(sqrt(h))\nend\n\nfunction haversin(\u03b8)\n    s = sin(\u03b8/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 = -\u03c0\nxmax = \u03c0\ndx = 0.02\n\nc = \u03c0/2 # celerity\n\u03bb\u00b2 = (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\u03c3 = 1/sqrt(2pi)\nU(x,t) = 0.5*(1/(sqrt(2pi)\u03c3))*exp(-(x-c*t)^2/(2\u03c3^2)) + 0.5*(1/(sqrt(2pi)\u03c3))*exp(-(x+c*t)^2/(2\u03c3^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)\u03c3)*exp(-x^2/(2\u03c3^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-\u03bb\u00b2)*u[x,1] -u[x,1] +\u03bb\u00b2*(u[x-1,1]+u[x+1,1])\n    #u[x,2] = u[x,1] + \u03bb\u00b2*(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-\u03bb\u00b2)*u[x,t-1] -u[x,t-2] +\u03bb\u00b2*(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# \u8ef8\u76ee\u76db\u308a\nxt = -\u03c0:\u03c0/2:\u03c0\nxtl = [\"-\u03c0\",\"-\u03c0/2\",\"0\",\"\u03c0/2\",\"\u03c0\"]\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( \u03c0*(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( \u03c0*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 \u03c0 * (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 \u03c0 * 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)*\u03c0 / (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\u2297predator,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 \u2297 id(wolves)) \u22c5 predation \u22c5 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\u2297Predator,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": "\nusing XDiff\nimport ReverseDiffSource\n\nfunction ann(w1, w2, w3, x1)\n    x2 = w1 * x1\n    # x2 = log.(1. + exp.(_x2))   # soft RELU unit\n    x3 = w2 * x2\n    # x3 = log.(1. + exp.(_x3))   # soft RELU unit\n    x4 = sum.(w3 * x3)\n    # return 1. ./ (1. + exp.(-x4))  # sigmoid output\n    return x4\nend\n\n# function ann(w1, w2, w3, x1)\n#     _x2 = w1 * x1\n#     x2 = log.(1. + exp.(_x2))   # soft RELU unit\n#     _x3 = w2 * x2\n#     x3 = log.(1. + exp.(_x3))   # soft RELU unit\n#     x4 = sum.(w3 * x3)\n#     return 1. ./ (1. + exp.(-x4))  # sigmoid output\n# end\n\n\n# ANN input parameter types\ntypes = (Matrix{Float64}, Matrix{Float64}, Matrix{Float64}, Vector{Float64})\n\n# generate example input\nw1, w2, w3 = randn(10,10), randn(10,10), randn(1,10)\nx1 = randn(10)\n\ndann = ReverseDiffSource.rdiff(ann, types)\n_, rds_dw1_val, _, _, _ = dann(w1, w2, w3, x1)\n\ndw1, _, _, _ = fdiff(ann, types)\ndw1_val = dw1(w1, w2, w3, x1)\n\nif isapprox(dw1_val, rds_dw1_val)\n    println(\"Equal!\")\nelse\n    error(\"Not equal!\")\nend\n", "meta": {"hexsha": "0e1262a6d890345bd54ae1206ac36ee4eda36ef9", "size": 1004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ann_reversediffsource.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": "examples/ann_reversediffsource.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": "examples/ann_reversediffsource.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": 23.3488372093, "max_line_length": 76, "alphanum_fraction": 0.5727091633, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.7868927927819089}}
{"text": "using QuasiGeostrophy, LinearAlgebra, Test\n# Polynomial Order\nn = 16\n\n# Domain [a b]\n\u03a9 = [-1.0 1.0]\nb = \u03a9[end]\na = \u03a9[1]\nL = b - a\n\nD, cx = cheb(n)\n\nx =  (b-a) .* (cx .+ 1) ./ 2 .+ a\n\n\u2202\u02e3 = 2 / L .* D\n\n# Equation Dy = y, y[x=-1] = 1\nA = \u2202\u02e3 - I\n\n# Boundary Conditions\nA[end, :] .= 0.0\nA[end, end] = 1.0\n\n# Solve\nrhs = 0.0 * x\nrhs[end] = 1.0\ny = A \\ rhs\n\n# Exact solution\nsolution = exp.( x .+ 1)\n\n@testset \"ODE Test 1\" begin\n    bool = norm(y - solution) < eps(1.0) * 100\n    @test bool\nend\n\n\n# Polynomial Order\nn = 32\n\n# Domain [a b]\n\u03a9 = [-1.0 0.0]\nb = \u03a9[end]\na = \u03a9[1]\nL = b - a\n\nD, cx = cheb(n)\n\nx =  (b-a) .* (cx .+ 1) ./ 2 .+ a\n\n\u2202\u02e3 = 2 / L .* D\n\n# Equation Dy = y, y[x=-1] = 1\nA = \u2202\u02e3 - I\n\n# Boundary Conditions\nA[end, :] .= 0.0\nA[end, end] = 1.0\n\n# Solve\nrhs = 0.0 * x\nrhs[end] = 1.0\ny = A \\ rhs\n\n# Exact solution\nsolution = exp.( x .+ 1)\n\n@testset \"ODE Test 2\" begin\n    bool = norm(y - solution) < eps(1.0) * 100\n    @test bool\nend\n", "meta": {"hexsha": "9b0298f43086fe89e5d8d9008119bb160e1961e0", "size": 935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ode_solution.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": "test/ode_solution.jl", "max_issues_repo_name": "sandreza/QuasiGeostrophy", "max_issues_repo_head_hexsha": "05b6e622e981afebf880e4890d24e2b813087e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-13T17:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-13T17:29:21.000Z", "max_forks_repo_path": "test/ode_solution.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": 12.9861111111, "max_line_length": 46, "alphanum_fraction": 0.5080213904, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7868927768008198}}
{"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\u03bb = 1e-4\n\nerrors = zeros(maxk, repeats, 3)\n\nmethods = [\n    ridge_weights(A, \u03bb),\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    \u0394x = (b-a)/n\n    nodes = a:\u0394x:b\n    weights = repeat(2:2:4, outer=Int(n/2))\n    weights[1] = 1\n    push!(weights,1)\n    weights *= \u0394x/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    \u0394x = (b-a)/n\n    nodes = a+\u0394x/2:\u0394x:b-\u0394x/2\n    weights = \u0394x*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    \u0394x = (b-a)/n\n    nodes = a:\u0394x:b\n    weights = \u0394x*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": "#!/usr/bin/env julia\n\n\"\"\"\nTests for the [`Primes`](@ref) common module.\n\"\"\"\nmodule TestPrimes\n\ninclude(joinpath(\"..\", \"src\", \"Primes.jl\"))\n\nusing Test\n\n@testset \"Primes\" begin\n    @testset \"prime_factorization\" begin\n        @test Primes.prime_factorization(2) == [(2, 1)]\n        @test Primes.prime_factorization(3) == [(3, 1)]\n        @test Primes.prime_factorization(4) == [(2, 2)]\n        @test Primes.prime_factorization(5) == [(5, 1)]\n        @test Primes.prime_factorization(6) == [(2, 1), (3, 1)]\n        @test Primes.prime_factorization(12) == [(2, 2), (3, 1)]\n        @test Primes.prime_factorization(600) == [(2, 3), (3, 1), (5, 2)]\n        @test Primes.prime_factorization(2903) == [(2903, 1)]\n        @test(\n            Primes.prime_factorization(61740)\n                == [(2, 2), (3, 2), (5, 1), (7, 3)]\n        )\n        @test(\n            Primes.prime_factorization(4928693)\n                == [(7, 1), (11, 3), (23, 2)]\n        )\n        @test(\n            Primes.prime_factorization(169165232)\n                == [(2, 4), (17, 1), (313, 1), (1987, 1)]\n        )\n        @test(\n            Primes.prime_factorization(74435892358158)\n                == [(2, 1), (3, 3), (29, 1), (3049, 2), (5113, 1)]\n        )\n    end\nend\n\nend\n", "meta": {"hexsha": "664fb26e816c935a9e13af8ccf9d53a84f7eb26f", "size": 1245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/test/TestPrimes.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/test/TestPrimes.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/test/TestPrimes.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": 29.6428571429, "max_line_length": 73, "alphanum_fraction": 0.502811245, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7868329664975869}}
{"text": "# to create vector, put comma\nV = [1, 2, 3, 4, 5, 6]\n\n#\u00a0to create matrix just add space\nV1 = [1 2 3 4 5 6]\n\n#\u00a0to declare an array just put semicolon\nM1 = [1 2 3; 4 5 6; 7 8 9]\n\n# to resahepe vector or matrix just use resahepe()\n\nV3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nreshape(V3, 3,3) #\u00a0for vector\n\nM2 = [1 2 3; 4 5 6] \nreshape(M2, 3, 2) # for matrix 2x3 to 3x2\n\n# to create identitiy matirx \nusing LinearAlgebra\nMatrix{Int}(I, 4, 4)\n\n# for dimensions and size of matrix use ndims() and size(), and to see type of elements in matrix using eltype()\nndims(M2)\nsize(M2)\neltype(M1)\n\n#\u00a0to concatenate two vector use vcat (similar to cbind() in R) and use hcat similar to (rbind() in R)\n\nd1 = [1 2 3; 4 5 6]\nd2 = [6 7 8; 9 10 11]\n\nhcat(d1, d2)\nvcat(d1, d2)\n\n# functions in julia\n\nfunction f(x, y, z)\n    x + y + z\nend\n\n# or just assign\n\ng(a, b, c) = a + b + c\n\n# function with return\n\nfunction \u03b2(a, b, c)\n    result = a + b + c\n    return result\nend\n\n\u03b2(2,\u03c0,3)\n\n# we can use opetator as function\n\n2 * 3 * 4\n*(2,3,4)\n\n#\u00a0function with default parameters\n\nz(x, y, a = 1, b = 2) = a*x + b*y\nz(3,5)\n\n # Anonymous function\n\nx -> x + 1 # or\n\nfunction (x)\n    x +1\nend\n\n#\u00a0Anonymous function generally useing with other first class function\nmap(x -> x + 1, [1, 2])\n\n#\u00a0multiple return values\n\nfunction ff( a, b, c)\n    a * b * c, a + b + c\nend;\n\nff(1, 2, 3)\n\nx, y  = ff(1, 2, 3);\n\ndisplay(x)\ndisplay(y)\n\nfunction fff(a, b, c)\n    multi = a * b * c\n    add = a + b + c\n\n    return multi, add\nend\n\n\nfff(1, 2, 3)\n\n\n# using Anonymous function with multiple piece of code, do-blocks will help\n\nmap(x -> x + 1, [1, 2, 3, 4]) #\u00a0basic way\n\nmap([1, 2, 3, 4]) do x #\u00a0other way \n     x + 1\nend \n\n\n#\u00a0control flow\n#\u00a0compound expression\n\nx = (a = 5; b = 6; a*b)\n\n# other way\n\nx = begin\n    a = 5\n    b = 6\n    a * b\nend\n\n\n# conditional evaluation\n\nfunction ineq(x, y)\n    if x > y\n        x = 2\n    elseif x < y\n        x = 1\n    else\n        x = 0\n    end    \nend\n\nineq(1, 2)\n\n# repeated evaluatins: loops\n\nj = 3;\n\nwhile j > 0\n    println(j^2)\n    global  j -= 1\nend\n\n\n# for loops\n\nfor j in [1, 2, 3]\n    println(j)\nend\n\n#\u00a0we can add \u2208 to loops\n\nfor j \u2208 [1, 2, 3]\n    println(j)\nend\n\n\n#\u00a0warning and informational messages\n\nfunction f(x)\n    if x<1\n        @warn \"x must be positive!\"\n        else\n            return x^2\n    end\nend\n\n\nf(2)\n\nfunction g(x)\n    if x < 1\n        @info \"X must be positive!\"\n    else\n        return x^2\n    end    \nend\n\ng(-2)\n\n\n# Plotting \n\nusing PyPlot\nx = 1:100\ny = rand(100)\ndisplay(gcf())\nplot(x,y, color = \"tomato\")\ntitle(\"basic graphs in PyPlot\")\n", "meta": {"hexsha": "c1d521d634e94a5dfd3b461e6b64a72abb087b7f", "size": 2545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaBasics.jl", "max_stars_repo_name": "fmyilmaz/DSGE", "max_stars_repo_head_hexsha": "9afe37887f4f24b4fb3b1e86d0c218f1de300721", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JuliaBasics.jl", "max_issues_repo_name": "fmyilmaz/DSGE", "max_issues_repo_head_hexsha": "9afe37887f4f24b4fb3b1e86d0c218f1de300721", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JuliaBasics.jl", "max_forks_repo_name": "fmyilmaz/DSGE", "max_forks_repo_head_hexsha": "9afe37887f4f24b4fb3b1e86d0c218f1de300721", "max_forks_repo_licenses": ["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.3246073298, "max_line_length": 112, "alphanum_fraction": 0.5697445972, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8807970795424088, "lm_q1q2_score": 0.7868243209840505}}
{"text": "using LowRankApprox\n\n@testset \"Truncation with standard SVD works correctly\" begin\n    D = 100\n    Dcut = D - 1\n    tol = 1E-8\n\n    a = rand(D, D)\n\n    U1, \u03a31, V1 = svd(a)\n\n    \u03b4 = min(Dcut, size(\u03a31)...)\n    U1 = U1[:, 1:\u03b4]\n    \u03a31 = \u03a31[1:\u03b4] \n    V1 = V1[:, 1:\u03b4]\n\n    U2, \u03a32, V2 = svd(a)\n\n    \u03b4 = min(Dcut, size(\u03a32)...)\n    U2 = U2[:, 1:\u03b4]\n    \u03a32 = \u03a32[1:\u03b4] \n    V2 = V2[:, 1:\u03b4]\n    \n    r1 = U1 * Diagonal(\u03a31) * V1'\n    r2 = U2 * Diagonal(\u03a32) * V2'\n\n    @test norm(r1-r2) < tol\nend\n\n\n@testset \"Truncation with with random SVD works correctly\" begin\n\n    D = 100\n    Dcut = D - 1\n    tol = 1E-8\n\n    a = rand(D, D)\n\n    U1, \u03a31, V1 = psvd(a, rank=Dcut, atol=1E-16, rtol=1E-16)\n    U2, \u03a32, V2 = psvd(a, rank=Dcut, atol=1E-16, rtol=1E-16)\n\n    r1 = U1 * Diagonal(\u03a31) * V1'\n    r2 = U2 * Diagonal(\u03a32) * V2'\n\n    println(norm(a-r2))\n    println(norm(a-r1))\n\n    @test norm(r1-r2) < tol\nend", "meta": {"hexsha": "02c2baefe7d36792168d4ae6a7e5731d0d690f79", "size": 882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/linear_algebra_ext.jl", "max_stars_repo_name": "euro-hpc-pl/SpinGlassTensors.jl", "max_stars_repo_head_hexsha": "7e20e8d6a34ed7533bf872df62a17a18090ecd65", "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/linear_algebra_ext.jl", "max_issues_repo_name": "euro-hpc-pl/SpinGlassTensors.jl", "max_issues_repo_head_hexsha": "7e20e8d6a34ed7533bf872df62a17a18090ecd65", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-08-10T09:35:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T21:44:18.000Z", "max_forks_repo_path": "test/linear_algebra_ext.jl", "max_forks_repo_name": "euro-hpc-pl/SpinGlassTensors.jl", "max_forks_repo_head_hexsha": "7e20e8d6a34ed7533bf872df62a17a18090ecd65", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-17T18:01:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T18:01:46.000Z", "avg_line_length": 18.0, "max_line_length": 64, "alphanum_fraction": 0.5102040816, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.786805803389084}}
{"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=\"\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f\"; 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 \u2190-\u2192 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),\" \u2190-\u2192 \",round(x.u,digits=6))\n\n\"\"\"\n\n\t+(x\u2081::Interval, x\u2082::Interval)\n\nAdds two intervals\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) + Interval(-2,4)\n-3.0 \u2190-\u2192 5.0\n```\n\"\"\"\nfunction Base.:+(x\u2081::Interval, x\u2082::Interval)\n\tInterval(x\u2081.l + x\u2082.l,x\u2081.u + x\u2082.u)\n    end\n\n\n\nfunction Base.:+(x\u2081::Real, x\u2082::Interval)\n\tInterval(x\u2081 + x\u2082.l,x\u2081 + x\u2082.u)\n    end\n\nfunction Base.:+(x\u2081::Interval, x\u2082::Real)\n\tInterval(x\u2081.l + x\u2082,x\u2081.u + x\u2082)\n    end\n\n \"\"\"\n\n\t-(x\u2081::Interval, x\u2082::Interval)\n\nSubtracts one interval from another\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) - Interval(-2,4)\n-5.0 \u2190-\u2192 3.0\n```\n\"\"\"\nfunction Base.:-(x\u2081::Interval, x\u2082::Interval)\n\tInterval(x\u2081.l - x\u2082.u,x\u2081.u - x\u2082.l)\n    end\n\nfunction Base.:-(x::Interval)\n\tInterval(-x.l,-x.u)\n    end\n\nfunction Base.:-(x\u2081::Interval, x\u2082::Real)\n\tInterval(x\u2081.l - x\u2082,x\u2081.u - x\u2082)\n    end\n\n    function Base.:-(x\u2081::Real, x\u2082::Interval)\n\tInterval(x\u2081 - x\u2082.l,x\u2081 - x\u2082.u)\n    end\n\n\"\"\"\n\n\t*(x\u2081::Interval, x\u2082::Interval)\n\nMultiplies two intervals\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) * Interval(-2,4)\n-4.0 \u2190-\u2192 4.0\n```\n\"\"\"\nfunction Base.:*(x\u2081::Interval, x\u2082::Interval)\n\tif 0 \u2264 x\u2081.l \n\t\tif 0 \u2264 x\u2082.l \n\t\t\treturn Interval(x\u2081.l*x\u2082.l,x\u2081.u*x\u2082.u)\n\t\telseif x\u2082.l < 0 < x\u2082.u \n\t\t\treturn Interval(x\u2081.u*x\u2082.l,x\u2081.u*x\u2082.u)\n\t\telseif x\u2082.u \u2264 0 \n\t\t\treturn Interval(x\u2081.u*x\u2082.l,x\u2081.l*x\u2082.u)\n\t\tend\n\telseif x\u2081.l < 0 < x\u2081.u\n\t\tif 0 \u2264 x\u2082.l \n\t\t\treturn Interval(x\u2081.l*x\u2082.u,x\u2081.u*x\u2082.u)\n\t\telseif x\u2082.u \u2264 0 \n\t\t\treturn Interval(x\u2081.u*x\u2082.l,x\u2081.l*x\u2082.l)\n\t\telseif x\u2082.l < 0 < x\u2082.u \n\t\t\treturn Interval(min(x\u2081.l*x\u2082.u,x\u2081.u*x\u2082.l),max(x\u2081.l*x\u2082.l,x\u2081.u*x\u2082.u))\n\t\tend\n\telseif x\u2081.u \u2264 0\n\t\tif 0 \u2264 x\u2082.l \n\t\t\treturn Interval(x\u2081.l*x\u2082.u,x\u2081.u*x\u2082.l)\n\t\telseif x\u2082.l < 0 < x\u2082.u \n\t\t\treturn Interval(x\u2081.l*x\u2082.u,x\u2081.l*x\u2082.l)\n\t\telseif x\u2082.u \u2264 0 \n\t\t\treturn Interval(x\u2081.u*x\u2082.u,x\u2081.l*x\u2082.l)\n\t\tend\n\tend\nend\n\nfunction Base.:*(x\u2081::Interval,x\u2082::Real)\n\tInterval(x\u2081.l*x\u2082,x\u2081.u*x\u2082)\nend\n\nfunction Base.:*(x\u2081::Real,x\u2082::Interval)\n\tInterval(x\u2081*x\u2082.l,x\u2081*x\u2082.u)\nend\n\n\"\"\"\n\n\t/(x\u2081::Interval, x\u2082::Interval)\n\nDivides two intervals\n\n# Examples\n```jldoctest\njulia> Interval(-1,1) / Interval(-2,4)\n-0.5 \u2190-\u2192 0.5\n```\n\"\"\"\nfunction Base.:/(x\u2081::Interval, x\u2082::Interval)\n\tx\u2081 * Interval(1/x\u2082.u,1/x\u2082.l)\n    end\n\nfunction Base.:/(x\u2081::Real, x\u2082::Interval)\n\tInterval(x\u2081/x\u2082.u,x\u2081/x\u2082.l)\n    end\n\nfunction Base.:/(x\u2081::Interval, x\u2082::Real)\n\tInterval(x\u2081.l/x\u2082,x\u2081.u/x\u2082)\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 \u2265 -(\u03c0/2) && x.u \u2264 \u03c0/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 \u2265 0 && x.u \u2264 \u03c0\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\u2081::Interval,x\u2082::Interval)\n\tmax(abs(x\u2081.l-x\u2082.l),abs(x\u2081.u-x\u2082.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 \u2190-\u2192 0.2, 0.2 \u2190-\u2192 0.4, 0.4 \u2190-\u2192 0.6, 0.6 \u2190-\u2192 0.8, 0.8 \u2190-\u2192 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 \u2208 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 \u2208 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\u2081 = copy(X)\n\tX\u2081[i] = X_s[1]\n\tX\u2082 = copy(X)\n\tX\u2082[i] = X_s[2]\n\treturn X\u2081,X\u2082\nend\n\n\nfunction hull(X::Vector{Interval})\n\tl = [x.l for x \u2208 X]\n\tu = [x.u for x \u2208 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,\u2207f,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\u2098\u1d65 = mean_value_form.(f,\u2207f,X)\n\tfor i \u2208 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\u2098\u1d65[i].l,Y\u2098\u1d65[i].l],fillrange=[Y\u2098\u1d65[i].u,Y\u2098\u1d65[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\u2098\u1d65[i].l,Y\u2098\u1d65[i].l],fillrange=[Y\u2098\u1d65[i].u,Y\u2098\u1d65[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\u1d64 = 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\u1d63 = []\n\tit_count = 0 \n\n\t# until tolerance...\n\tfor it \u2208 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\u1d64\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 \u2208 del_index\n\t\t\tpush!(L\u1d63,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 \u2208 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 \u2208 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\u1d64\n\t\t\t\tf\u1d64 = 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\u1d63\nend\n\n\nfunction plot_boxes(L,L\u1d63)\n\tfor l \u2208 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 \u2208 L\u1d63\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,\u2207f,X)\n\tif typeof(X) == Interval\n\t\tD = \u2207f(X)[1]\n\telse\n\t\tD = \u2207f(X)\n\tend\n\tmean = m(X)\n\tf\u2098 = f(mean)\n\tif typeof(X) == Interval\n\t\treturn f\u2098 + D*(X-mean)\n\telse\n\t\treturn f\u2098 + sum(D[i]*(X[i]-mean[i]) for i \u2208 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\u2207f = Symbolics.gradient(f(x),[x[i] for i \u2208 1:len_x])\n\t\t\u2207f_expr = build_function(\u2207f, x)\n\t\t\u2207f = eval(\u2207f_expr[1])\n\t\treturn \u2207f\n\telse\n\t\t@variables x\n\t\t\u2207f = Symbolics.gradient(f(x),[x])\n\t\t\u2207f_expr = build_function(\u2207f, x)\n\t\t\u2207f = eval(\u2207f_expr[1])\n\t\treturn \u2207f\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# \u2207f = build_gradient(f,1)\n# plot_refinement(Interval(0,1),f,\u2207f,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": "using DiffEqFlux, OrdinaryDiffEq, Flux, Optim, Test\n\n# General loss function to compare single shooting and multiple shooting predictions\nfunction general_loss_function(result_neuralode)\n\treturn sum(abs2, (ode_data[:,:] .- Array(prob_neuralode(u0, result_neuralode.minimizer)) ))\nend\n\n# Define initial conditions and timesteps\ndatasize = 30\nu0 = Float32[2.0, 0.0]\ntspan = (0.0f0, 5.0f0)\ntsteps = range(tspan[1], tspan[2], length = datasize)\n\n# Get the data\nfunction trueODEfunc(du, u, p, t)\n    true_A = [-0.1 2.0; -2.0 -0.1]\n    du .= ((u.^3)'true_A)'\nend\nprob_trueode = ODEProblem(trueODEfunc, u0, tspan)\node_data = Array(solve(prob_trueode, Tsit5(), saveat = tsteps))\n\n# Define the Neural Network\ndudt2 = FastChain((x, p) -> x.^3,\n                  FastDense(2, 16, tanh),\n                  FastDense(16, 2))\nprob_neuralode = NeuralODE(dudt2, (0.0,5.0), Tsit5(), saveat = tsteps)\n\nfunction loss_neuralode(p)\n    pred = Array(prob_neuralode(u0, p))\n    loss = sum(abs2, (ode_data[:,1:size(pred,2)] .- pred))\n    return loss, pred\nend\n\n\nresult_neuralode = DiffEqFlux.sciml_train(loss_neuralode, prob_neuralode.p,\n                                          ADAM(0.05),\n\t\t\t\t\t\t\t\t\t\t  maxiters = 300)\n\nsingle_shoot_loss = general_loss_function(result_neuralode)\nprintln(\"single_shoot_loss: \",single_shoot_loss)\n\n# Define parameters for Multiple Shooting\ngrp_size_param = 1\nloss_multiplier_param = 100\n\nneural_ode_f(u,p,t) = dudt2(u,p)\nprob_param = ODEProblem(neural_ode_f, u0, tspan, initial_params(dudt2))\n\nfunction loss_function_param(ode_data, pred):: Float32\n\treturn sum(abs2, (ode_data .- pred))^2\nend\n\nfunction loss_neuralode_param(p)\n\treturn multiple_shoot(p, ode_data, tsteps, prob_param, loss_function_param, grp_size_param, loss_multiplier_param)\nend\n\n\nmultiple_shoot_result_neuralode_1 = DiffEqFlux.sciml_train(loss_neuralode_param, prob_neuralode.p,\n                                          ADAM(0.05),\n                                          maxiters = 300)\n\nmultiple_shoot_loss_1 = general_loss_function(multiple_shoot_result_neuralode_1)\nprintln(\"multiple_shoot_loss_1: \",multiple_shoot_loss_1)\n\n\n# test for grp_size = 1\n@test multiple_shoot_loss_1 < single_shoot_loss\n\n# test for grp_size = 5\ngrp_size_param = 5\nmultiple_shoot_result_neuralode_2 = DiffEqFlux.sciml_train(loss_neuralode_param, prob_neuralode.p,\n                                          ADAM(0.05),\n                                          maxiters = 300)\n\nmultiple_shoot_loss_2 = general_loss_function(multiple_shoot_result_neuralode_2)\nprintln(\"multiple_shoot_loss_2: \",multiple_shoot_loss_2)\n\n@test multiple_shoot_loss_2 < single_shoot_loss\n", "meta": {"hexsha": "31f3f714e61cde8ad3683e3fac872a166a6b42fb", "size": 2625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/multiple_shoot.jl", "max_stars_repo_name": "adrhill/DiffEqFlux.jl", "max_stars_repo_head_hexsha": "ee4937f33148dfeb7b71914763b9b8b86c4dc094", "max_stars_repo_licenses": ["MIT"], "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/multiple_shoot.jl", "max_issues_repo_name": "adrhill/DiffEqFlux.jl", "max_issues_repo_head_hexsha": "ee4937f33148dfeb7b71914763b9b8b86c4dc094", "max_issues_repo_licenses": ["MIT"], "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/multiple_shoot.jl", "max_forks_repo_name": "adrhill/DiffEqFlux.jl", "max_forks_repo_head_hexsha": "ee4937f33148dfeb7b71914763b9b8b86c4dc094", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-04T16:38:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T16:38:02.000Z", "avg_line_length": 33.2278481013, "max_line_length": 115, "alphanum_fraction": 0.6982857143, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.872347369700144, "lm_q1q2_score": 0.7867881298487186}}
{"text": "using LinearAlgebra\nusing ForwardDiff\nusing Test\n\nexport newton_raphson\nexport test_newton_raphson\n\n\u2207(f, x) = ForwardDiff.jacobian(f, x)\n\nfunction newton_raphson(f::Function, x0::Vector{Float64}, \u03f5::Float64)\n    xs = [x0]\n    d = inv(-\u2207(f, x0)) * f(x0)\n    while norm(d) > \u03f5\n        x = xs[end] + d\n        d = inv(-\u2207(f, x)) * f(x)\n        push!(xs, x)\n    end\n    return xs\nend\n\nfunction test_newton_raphson()\n    f(x) = [x[1]^2 + x[2]^2 - 4*x[3] - 0;\n            x[1]^2 + x[3]^2 + 0*x[3] - (1/4);\n            x[1]^2 + x[2]^2 + x[3]^2 - 1]\n    x0 = [1.0, 1.0, 1.0]\n    \u03f5 = 0.001\n    x = newton_raphson(f, x0, \u03f5)\n    @info \"Newton-Raphson iterations:\"\n    @info x\n    @test isapprox(norm(f(x[end])), 0; atol=\u03f5)\nend\n", "meta": {"hexsha": "1035c797879acb8537a3bfb1f2addc1420d79a3a", "size": 715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton_raphson.jl", "max_stars_repo_name": "JuliaLearning/Assignments.jl", "max_stars_repo_head_hexsha": "2513b775ac926c4b0a3fd5d8a3087152ce4dfb79", "max_stars_repo_licenses": ["MIT"], "max_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_raphson.jl", "max_issues_repo_name": "JuliaLearning/Assignments.jl", "max_issues_repo_head_hexsha": "2513b775ac926c4b0a3fd5d8a3087152ce4dfb79", "max_issues_repo_licenses": ["MIT"], "max_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_raphson.jl", "max_forks_repo_name": "JuliaLearning/Assignments.jl", "max_forks_repo_head_hexsha": "2513b775ac926c4b0a3fd5d8a3087152ce4dfb79", "max_forks_repo_licenses": ["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.34375, "max_line_length": 69, "alphanum_fraction": 0.5314685315, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829917, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7867737068556562}}
{"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, \u03bb, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Erlang_{`k`}(`\u03bb`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe pdf of an Erlang_{k}(\u03bb) distribution is given as:\n\n``f(x, k, \u03bb) = \\\\frac{\u03bb^k e^{-\u03bbx} x^{k-1}}{(k-1)!} \\\\quad x \u2265 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\u00d72\u00d71 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 \u03b1 \u2265 1. 2013.\n\"\"\"\nfunction erlang_rng(k::Int, \u03bb::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/\u03bb) .* log.(prod(U, dims=k_dim))  # Here (-1/\u03bb) 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,\u03b1,v)\n  @assert(0 \u2264 \u03b1 < 1, \"needs probably \u03b1\")\n  @assert(all(vi -> vi \u2265 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(\u03b1)) # upper bound on steps\n  for i=1:nsteps\n    x = \u03b1*(A'*(x./d)) .+ (1-\u03b1).*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,\u03b1,nsteps)\n  n = size(A,1)\n  v = ones(n)/n\n  @assert(0 \u2264 \u03b1 < 1, \"needs probably \u03b1\")\n  @assert(all(vi -> vi \u2265 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 = \u03b1*(A'*(x./d)) .+ (1-\u03b1).*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,\u03b1,nsteps)\n  n = size(A,1)\n  v = ones(n)/n\n  @assert(0 \u2264 \u03b1 < 1, \"needs probably \u03b1\")\n  @assert(all(vi -> vi \u2265 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 = \u03b1*(A'*(x./d)) .+ (1-\u03b1).*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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, StatsBase, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.16\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.16\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u2550a80f7e58-3af9-11eb-04b3-57fcb9ee857c\n# \u255f\u2500475ff888-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": "using Concorde\nusing Test\n\n@testset \"Concorde.jl\" begin\n    @testset \"Symmetric TSP\" begin\n        M = [\n             0  16   7  14\n            16   0   3   5\n             7   3   0  16\n            14   5  16   0 \n        ]\n        opt_tour, opt_len = solve_tsp(M)\n        @show opt_tour, opt_len\n        @test opt_len == 29\n    end\n\n    @testset \"Asymmetric TSP\" begin\n        M = [\n             0   1   7  14\n            16   0   1   5\n             7   5   0   1\n             1   3  16   0 \n        ]\n        @test_throws ErrorException solve_tsp(M)\n    end\n\n    @testset \"Coordinates\" begin\n        n_nodes = 10\n        x = rand(n_nodes) .* 10000\n        y = rand(n_nodes) .* 10000\n        opt_tour, opt_len = solve_tsp(x, y; dist=\"EUC_2D\")\n        opt_tour, opt_len = solve_tsp(x, y; dist=\"MAN_2D\")\n        opt_tour, opt_len = solve_tsp(x, y; dist=\"MAX_2D\")\n        opt_tour, opt_len = solve_tsp(x, y; dist=\"GEO\")        \n    end\n\n    @testset \"Input File\" begin\n        opt_tour, opt_len = solve_tsp(\"gr17.tsp\")\n        # @test opt_len == -1\n        @test opt_len == 2085\n    end    \nend\n", "meta": {"hexsha": "9d5102415656709f0a9d00454d86c2a2fe3fd961", "size": 1093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 25.4186046512, "max_line_length": 63, "alphanum_fraction": 0.483989021, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7867365522319276}}
{"text": "#\"Read\" data for parametric sinusoidal \"simulation\" & parameter extraction\n#-------------------------------------------------------------------------------\n\nusing CMDimData\nusing CMDimData.MDDatasets\n\nconst \u03c0 = MathConstants.\u03c0\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 \ud835\udf19, A, and \ud835\udc53 parameters of `signal = A * sin(\ud835\udf14*t + \ud835\udf19); \ud835\udf14 = 2\u03c0*\ud835\udc53` are varied.\n\nThe parametric signal can therefore be fully represented as:\n\tsignal(\ud835\udf19, A, \ud835\udc53, t)\n=#\n\n#But really construct multidimensional DataRS dataset manually:\nsignal = fill(DataRS, PSweep(\"phi\", [0, 0.5, 1] .* (\u03c0/4))) do \ud835\udf19\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 \ud835\udc53\n\t\t\ud835\udf14 = 2\u03c0*\ud835\udc53\n\t\tT = 1/\ud835\udc53\n\t\t\u0394t = T/100 #Define resolution from # of samples per period\n\t\tTsim = 4T #Simulated time\n\n\t\tt = DataF1(0:\u0394t:Tsim) #DataF1 creates a t:{y, x} container with y == x\n\t\tsig = A * sin(\ud835\udf14*t + \ud835\udf19) #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(\u03b1::FT, nr::FT) where {FT<:AbstractFloat}\n\nReturn the average transmittance of isotropic radiation across an interface between two dielectrics, given\n- `\u03b1` 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(\u03b1::FT, nr::FT) where {FT<:AbstractFloat}\n    @assert 0 < \u03b1 <= 90;\n\n    # some shortcuts to avoid overly comlicated equation\n    _a     = (nr + 1) ^ 2 / 2;\n    _a\u00b3    = _a ^ 3;\n    _n\u00b2    = nr ^ 2;\n    _n\u2074    = nr ^ 4;\n    _n\u2076    = nr ^ 6;\n    _n\u00b2p   = _n\u00b2 + 1;\n    _n\u00b2p\u00b2  = _n\u00b2p ^ 2;\n    _n\u00b2p\u00b3  = _n\u00b2p ^ 3;\n    _n\u00b2m\u00b2  = (_n\u00b2 - 1) ^ 2;\n    _k     = -1 * _n\u00b2m\u00b2 / 4;\n    _k\u00b2    = _k ^ 2;\n    _sin\u00b2\u03b1 = sind(\u03b1) ^ 2;\n    _b\u2082    = _sin\u00b2\u03b1 - _n\u00b2p/2;\n    _b\u2081    = (\u03b1==90 ? 0 : sqrt(_b\u2082 ^ 2 + _k));\n    _b     = _b\u2081 - _b\u2082;\n    _b\u00b3    = _b ^ 3;\n    _npanm = 2 * _n\u00b2p * _a - _n\u00b2m\u00b2;\n    _npbnm = 2 * _n\u00b2p * _b - _n\u00b2m\u00b2;\n\n    # S polarization\n    _ts  = ( _k\u00b2 / (6*_b\u00b3) + _k/_b - _b/2 ) - ( _k\u00b2 / (6*_a\u00b3) + _k/_a - _a/2 );\n\n    # P polarization\n    _tp\u2081 = -2 * _n\u00b2 * (_b - _a) / _n\u00b2p\u00b2;\n    _tp\u2082 = -2 * _n\u00b2 * _n\u00b2p * log(_b / _a) / _n\u00b2m\u00b2;\n    _tp\u2083 = _n\u00b2 * (1/_b - 1/_a) / 2;\n    _tp\u2084 = 16 * _n\u2074 * (_n\u2074 + 1) * log(_npbnm / _npanm) / (_n\u00b2p\u00b3 * _n\u00b2m\u00b2);\n    _tp\u2085 = 16 * _n\u2076 * (1/_npbnm - 1/_npanm) / _n\u00b2p\u00b3;\n    _tp  = _tp\u2081 + _tp\u2082 + _tp\u2083 + _tp\u2084 + _tp\u2085;\n\n    return  (_ts + _tp) / (2 * _sin\u00b2\u03b1)\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 \u2264 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 \u2265 0\"\nfunction log1mexp(x)\n    # https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf, Eq. 7\n    x \u2265 0 || throw(DomainError())\n    if x \u2264 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 \u2264 -37\n        exp(x)\n    elseif -37 < x \u2264 18\n        log1p(exp(x))\n    elseif 18 < x \u2264 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": "using Test\nusing Flux: onehotbatch, mse, crossentropy, logitcrossentropy,\n            \u03c3, binarycrossentropy, logitbinarycrossentropy, flatten,\n            xlogx, xlogy\n\nconst \u03f5 = 1e-7\n\n@testset \"xlogx & xlogy\" begin\n  @test iszero(xlogx(0))\n  @test isnan(xlogx(NaN))\n  @test xlogx(2) \u2248 2.0 * log(2.0)\n  @inferred xlogx(2)\n  @inferred xlogx(0)\n\n  @test iszero(xlogy(0, 1))\n  @test isnan(xlogy(NaN, 1))\n  @test isnan(xlogy(1, NaN))\n  @test isnan(xlogy(NaN, NaN))\n  @test xlogy(2, 3) \u2248 2.0 * log(3.0)\n  @inferred xlogy(2, 3)\n  @inferred xlogy(0, 1)\nend\n\n@testset \"losses\" begin\n  # First, regression-style y's\n  y = [1, 1, 0, 0]\n  \u0177 = [.9, .1, .1, .9]\n\n  @testset \"mse\" begin\n    @test mse(\u0177, y) \u2248 (.1^2 + .9^2)/2\n  end\n\n  @testset \"mae\" begin\n    @test Flux.mae(\u0177, y) \u2248 1/2\n  end\n\n  @testset \"huber_loss\" begin\n    @test Flux.huber_loss(\u0177, y) \u2248 0.20500000000000002\n  end\n\n  y = [123.0,456.0,789.0]\n  \u0177 = [345.0,332.0,789.0]\n  @testset \"msle\" begin\n    @test Flux.msle(\u0177, y) \u2248 0.38813985859136585\n  end\n\n  # Now onehot y's\n  y = onehotbatch([1, 1, 0, 0], 0:1)\n  \u0177 = [.1 .9; .9 .1; .9 .1; .1 .9]'\n  v = log(.1 / .9)\n  logy\u0302 = [v 0.0; 0.0 v; 0.0 v; v 0.0]'\n  lossvalue = 1.203972804325936\n\n  @testset \"crossentropy\" begin\n    @test crossentropy([0.1,0.0,0.9], [0.1,0.0,0.9]) \u2248 crossentropy([0.1,0.9], [0.1,0.9])\n    @test crossentropy(\u0177, y) \u2248 lossvalue\n  end\n\n  @testset \"logitcrossentropy\" begin\n    @test logitcrossentropy(log\u0177, y) \u2248 lossvalue\n  end\n\n  @testset \"weighted_crossentropy\" begin\n    @test crossentropy(\u0177, y, weight = ones(2)) \u2248 lossvalue\n    @test crossentropy(\u0177, y, weight = [.5, .5]) \u2248 lossvalue/2\n    @test crossentropy(\u0177, y, weight = [2, .5]) \u2248 1.5049660054074199\n  end\n\n  @testset \"weighted_logitcrossentropy\" begin\n    @test logitcrossentropy(log\u0177, y, weight = ones(2)) \u2248 lossvalue\n    @test logitcrossentropy(log\u0177, y, weight = [.5, .5]) \u2248 lossvalue/2\n    @test logitcrossentropy(log\u0177, y, weight = [2, .5]) \u2248 1.5049660054074199\n  end\n\n  logy\u0302, y = randn(3), rand(3)\n  @testset \"binarycrossentropy\" begin\n    @test binarycrossentropy.(\u03c3.(logy\u0302), y; \u03f5=0) \u2248 -y.*log.(\u03c3.(logy\u0302)) - (1 .- y).*log.(1 .- \u03c3.(logy\u0302))\n    @test binarycrossentropy.(\u03c3.(logy\u0302), y) \u2248 -y.*log.(\u03c3.(logy\u0302) .+ eps.(\u03c3.(logy\u0302))) - (1 .- y).*log.(1 .- \u03c3.(logy\u0302) .+ eps.(\u03c3.(logy\u0302)))\n  end\n\n  @testset \"logitbinarycrossentropy\" begin\n    @test logitbinarycrossentropy.(logy\u0302, y) \u2248 binarycrossentropy.(\u03c3.(logy\u0302), y; \u03f5=0)\n  end\n\n  y = [1 2 3]\n  \u0177 = [4.0 5.0 6.0]\n  @testset \"kldivergence\" begin\n    @test Flux.kldivergence([0.1,0.0,0.9], [0.1,0.0,0.9]) \u2248 Flux.kldivergence([0.1,0.9], [0.1,0.9])\n    @test Flux.kldivergence(\u0177, y) \u2248 -1.7661057888493457\n    @test Flux.kldivergence(y, y) \u2248 0\n  end\n\n  y = [1 2 3 4]\n  \u0177 = [5.0 6.0 7.0 8.0]\n  @testset \"hinge\" begin\n    @test Flux.hinge(\u0177, y) \u2248 0\n    @test Flux.hinge(y, 0.5 .* y) \u2248 0.125\n  end\n\n  @testset \"squared_hinge\" begin\n    @test Flux.squared_hinge(\u0177, y) \u2248 0\n    @test Flux.squared_hinge(y, 0.5 .* y) \u2248 0.0625\n  end\n\n  y = [0.1 0.2 0.3]\n  \u0177 = [0.4 0.5 0.6]\n  @testset \"poisson\" begin\n    @test Flux.poisson(\u0177, y) \u2248 0.6278353988097339\n    @test Flux.poisson(y, y) \u2248 0.5044459776946685\n  end\n\n  y = [1.0 0.5 0.3 2.4]\n  \u0177 = [0 1.4 0.5 1.2]\n  @testset \"dice_coeff_loss\" begin\n    @test Flux.dice_coeff_loss(\u0177, y) \u2248 0.2799999999999999\n    @test Flux.dice_coeff_loss(y, y) \u2248 0.0\n  end\n\n  @testset \"tversky_loss\" begin\n    @test Flux.tversky_loss(\u0177, y) \u2248 -0.06772009029345383\n    @test Flux.tversky_loss(\u0177, y, \u03b2 = 0.8) \u2248 -0.09490740740740744\n    @test Flux.tversky_loss(y, y) \u2248 -0.5576923076923075\n  end\n\n  @testset \"no spurious promotions\" begin\n    for T in (Float32, Float64)\n      y = rand(T, 2)\n      \u0177 = rand(T, 2)\n      for f in (mse, crossentropy, logitcrossentropy, Flux.kldivergence, Flux.hinge, Flux.poisson,\n              Flux.mae, Flux.huber_loss, Flux.msle, Flux.squared_hinge, Flux.dice_coeff_loss, Flux.tversky_loss)\n        fwd, back = Flux.pullback(f, y\u0302, y)\n        @test fwd isa T\n        @test eltype(back(one(T))[1]) == T\n      end\n    end\n  end\nend\n\n@testset \"helpers\" begin\n  @testset \"flatten\" begin\n    x = randn(Float32, 10, 10, 3, 2)\n    @test size(flatten(x)) == (300, 2)\n  end\nend\n", "meta": {"hexsha": "a61e912a1442384c776732ccbafc2443b506c02c", "size": 4133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/layers/stateless.jl", "max_stars_repo_name": "saswatpp/Flux.jl", "max_stars_repo_head_hexsha": "99ec30c8c2050f3c35f3e800b492c6e822c2bb68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-25T23:57:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T17:18:37.000Z", "max_issues_repo_path": "test/layers/stateless.jl", "max_issues_repo_name": "saswatpp/Flux.jl", "max_issues_repo_head_hexsha": "99ec30c8c2050f3c35f3e800b492c6e822c2bb68", "max_issues_repo_licenses": ["MIT"], "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/layers/stateless.jl", "max_forks_repo_name": "saswatpp/Flux.jl", "max_forks_repo_head_hexsha": "99ec30c8c2050f3c35f3e800b492c6e822c2bb68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-03T02:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T02:30:04.000Z", "avg_line_length": 28.5034482759, "max_line_length": 136, "alphanum_fraction": 0.6056133559, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.7867049268921724}}
{"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": "\nfunction swap(array, i, j)\n  tmp = array[i]\n  array[i] = array[j]\n  array[j] = tmp\nend\n\nfunction partition(array, left, right)\n  pivotIndex = rand(left:right)\n  pivot = array[pivotIndex]\n  swap(array, pivotIndex, right)\n\n  pos = left\n  for i = left:right-1\n    if array[i] < pivot\n      swap(array, i, pos)\n      pos = pos+1\n    end\n  end\n  \n  swap(array, pos, right)\n\n  return pos\nend\n\nfunction quick_sort(array, left, right)\n  if left < right\n    pivotIndex = partition(array, left, right)\n    quick_sort(array, left, pivotIndex-1)\n    quick_sort(array, pivotIndex+1, right)\n  end\nend\n\n\nfunction is_sorted(array)\n  max = 0\n  i = 1\n  while i < length(array)\n    if array[i] < max\n      return false\n    end\n    max = array[i]\n    i = i+1\n  end\n  return true\nend\n\nfunction generate_random_array(length)\n  rand(0:length, length)\nend\n\n\nfor i = 1:100\n  array = generate_random_array(1000)\n  quick_sort(array, 1, length(array))\n  if !is_sorted(array)\n    println(\"Error! Array is not sorted!\")\n    exit()\n  end\nend\n\nprintln(\"Quick sort works fine!\")\n", "meta": {"hexsha": "eda160efd320dcad8aa98607dfd73357c0065ef0", "size": 1047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sort/quick_sort/julia/quick_sort.jl", "max_stars_repo_name": "avi-pal/al-go-rithms", "max_stars_repo_head_hexsha": "5167a20f1db7b366ff19f2962c1746a02e4f5067", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1253, "max_stars_repo_stars_event_min_datetime": "2017-06-06T07:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:07:58.000Z", "max_issues_repo_path": "sort/quick_sort/julia/quick_sort.jl", "max_issues_repo_name": "rishabh99-rc/al-go-rithms", "max_issues_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 554, "max_issues_repo_issues_event_min_datetime": "2017-09-29T18:56:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:48:13.000Z", "max_forks_repo_path": "sort/quick_sort/julia/quick_sort.jl", "max_forks_repo_name": "rishabh99-rc/al-go-rithms", "max_forks_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2226, "max_forks_repo_forks_event_min_datetime": "2017-09-29T19:59:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:59:55.000Z", "avg_line_length": 16.619047619, "max_line_length": 46, "alphanum_fraction": 0.6485195798, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7866721608278892}}
{"text": "## @lc code=start\nusing LeetCode\n\nfunction count_operations(num1::Int, num2::Int)::Int\n    if num2 > num1\n        num1, num2 = num2, num1\n    end\n    res = 0\n    while num1 > 0\n        res += num2 \u00f7 num1\n        num1, num2 = num2 % num1, num1\n    end\n    res\nend\n## @lc code=end\n\n## @lc test=start\n@testset \"2169.count-operations-to-obtain-zero.jl\" begin\n    @test count_operations(2, 3) == 3\n    @test count_operations(10, 10) == 1\n    @test count_operations(2022, 1077) == 20\nend\n## @lc test=end\n\n\n## @lc info=start\n# link: [solution to 2169](https://leetcode-cn.com/problems/count-operations-to-obtain-zero/solution/6004-zhan-zhuan-xiang-chu-de-ci-shu-juli-23oc/)\n## @lc info=end", "meta": {"hexsha": "e51845058ea3bca04ca512d953922152d01888d5", "size": 682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/exceed_1681/2169.count-operations-to-obtain-zero.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/exceed_1681/2169.count-operations-to-obtain-zero.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/exceed_1681/2169.count-operations-to-obtain-zero.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.3571428571, "max_line_length": 148, "alphanum_fraction": 0.642228739, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857379, "lm_q2_score": 0.8670357512127873, "lm_q1q2_score": 0.7866721421240835}}
{"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 `\u03c3(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 $\u03c3(x_1,w, b)$ for our apple.\n#' So, we want the difference $0 - \u03c3(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 - \u03c3(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 - \u03c3(x_1, w, b))^2 + (1 - \u03c3(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} = \u03b1u\n```\n\nwith initial condition ``u0=1/2``, ``\u03b1=1.01``, and solution\n\n```math\nu(t) = u0e^{\u03b1t}\n```\n\nwith Float64s. The parameter is ``\u03b1``\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} = \u03b1u\n```\n\nwith initial condition ``u0=1/2``, ``\u03b1=1.01``, and solution\n\n```math\nu(t) = u0e^{\u03b1t}\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} = \u03b1u\n```\n\nwith initial condition ``u0=1/2``, ``\u03b1=1.01``, and solution\n\n```math\nu(t) = u0e^{\u03b1t}\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} = \u03b1u\n```\n\nwith initial condition ``u0=1/2``, ``\u03b1=1.01``, and solution\n\n```math\nu(t) = u0e^{\u03b1t}\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} = \u03b1u\n```\n\nwith initial condition ``u0=1/2``, ``\u03b1=1.01``, and solution\n\n```math\nu(t) = u0e^{\u03b1t}\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} = \u03b1u\n```\n\nwith initial condition ``u0=1/2``, ``\u03b1=1.01``, and solution\n\n```math\nu(t) = u0e^{\u03b1t}\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": "@testset \"Testing sampler.jl\" begin\r\n\r\n    n = 4\r\n    mu = collect(range(0.2, stop=0.6, length=n))\r\n    @testset \"check positive definite\" begin\r\n        Sigma = [3.0 1.0 1.0 1.0;\r\n                 1.0 2.0 1.0 1.0;\r\n                 1.0 1.0 2.0 1.0;\r\n                 1.0 1.0 1.0 1.0]\r\n        mvns = MVNSampler(mu, Sigma)\r\n        @test isapprox(mvns.Q * mvns.Q', mvns.Sigma)\r\n    end\r\n\r\n    @testset \"check positive semi-definite zeros\" begin\r\n        mvns = MVNSampler(mu, zeros(n, n))\r\n        @test rand(mvns) == mu\r\n    end\r\n\r\n    @testset \"check positive semi-definite ones\" begin\r\n        mvns = MVNSampler(mu, ones(n, n))\r\n        c = rand(mvns)-mvns.mu\r\n        @test all(broadcast(isapprox,c[1],c))\r\n    end\r\n\r\n    @testset \"check positive semi-definite 1 and -1/(n-1)\" begin\r\n        Sigma = -1/(n-1)*ones(n, n) + n/(n-1)*Matrix(Matrix(I, n, n))\r\n        mvns = MVNSampler(mu, Sigma)\r\n        @test isapprox(sum(rand(mvns)) , sum(mu), atol=1e-4, rtol=1e-4)\r\n    end\r\n\r\n    @testset \"check non-positive definite\" begin\r\n        Sigma = [2.0 1.0 3.0 1.0;\r\n                 1.0 2.0 1.0 1.0;\r\n                 3.0 1.0 2.0 1.0;\r\n                 1.0 1.0 1.0 1.0]\r\n        @test_throws ArgumentError MVNSampler(mu, Sigma)\r\n    end\r\n\r\n    @testset \"check availability of rank deficient matrix\" begin\r\n        A = randn(n,n)\r\n        for r=1:n-2\r\n            r=2\r\n            for i = 1:r\r\n                A[:, end+1-i] = sum(A[:, 1:end-r], dims = 2)\r\n            end\r\n            Sigma = A * A'\r\n            @test typeof(MVNSampler(mu,Sigma)) <: MVNSampler\r\n        end\r\n    end\r\n\r\n    @testset \"test covariance matrices of Int and Rational\" begin\r\n        n = 2\r\n        mu = zeros(2)\r\n        for T in [Int, Rational{Int}]\r\n            Sigma = Matrix{T}(I, n, n)\r\n            @test typeof(MVNSampler(mu, Sigma)) <: MVNSampler\r\n        end\r\n    end\r\n\r\nend  # @testset\r\n", "meta": {"hexsha": "5f72e5542aa257b1c6f1fa20cd6111f221e8c355", "size": 1874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_sampler.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": "test/test_sampler.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": "test/test_sampler.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": 30.7213114754, "max_line_length": 72, "alphanum_fraction": 0.4946638207, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.7866512600091372}}
{"text": "using BenchmarkTools\nBenchmarkTools.DEFAULT_PARAMETERS.samples = 100\n\nfunction compute(path::String)::Int\n    base_exp = map(x -> parse.(Int, split(x, \",\")), split(read(path, String), \"\\n\"))\n    max_exponent = 0\n    result = 0\n    for i \u2208 1:length(base_exp)\n        base, exponent = base_exp[i]\n        exponent = log10(base) * exponent\n        if exponent > max_exponent\n            max_exponent = exponent\n            result = i\n        end\n    end\n    return result\nend\n\ncompute(\"problems/0099/p099_base_exp.txt\")\n\n@benchmark compute(\"problems/0099/p099_base_exp.txt\")", "meta": {"hexsha": "8bb3f498deb13ec1c9861ace26cda32fb2cceb8e", "size": 571, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/0099/solution.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/0099/solution.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/0099/solution.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": 27.1904761905, "max_line_length": 84, "alphanum_fraction": 0.646234676, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7865978195946804}}
{"text": "using DataFrames\n\nA = readdlm(\"u1.base\",'\\t';header=false)\nfile = \"u1.base\"\n\nfunction pearsonCorrelation(x,y)\n        @assert(length(x) == length(y))\n        n = length(x)\n        @assert(n>0)\n        avg_x = mean(x)\n        avg_y = mean(y)\n        prod_diff = 0\n        xdiff2 = 0\n        ydiff2 = 0\n        for id = 1:n\n                xdiff = x[id] - avg_x\n                ydiff = y[id] - avg_y\n                prod_diff += xdiff*ydiff\n                xdiff2 += xdiff^2\n                ydiff2 += ydiff^2\n        end\n        return prod_diff/sqrt(xdiff2*ydiff2)\nend\n\nfunction PearsonCorrelationHelper(file)\n     df = readtable(file,separator = '\\t',header = false);\n     rename!(df,:x1,:userId)\n     rename!(df,:x2,:itemId)\n     rename!(df,:x3,:rating)\n     #rename!(df,:x4,:timestamp)\n     M1 =Set(df[df[:userId] .== 1, :itemId])\n     CorrelationArray = Float64[] \n     (N,ind) = findmax(df[:,1])\n     for(i = 2:N)\n            M_i = Set(df[df[:userId] .== i, :itemId])\n            if(length(intersect(M1,M_i)) == 0) push!( CorrelationArray , NA)\n            else\n                  X = Float64[]\n                  Y = Float64[]\n                  for(movie in intersect(M1,M_i))\n                      push!(X , (df[(df[:userId]   .== 1)  & (df[:itemId] .== movie), :rating])[1])\n                      push!(Y , (df[(df[:userId]   .== i)  & (df[:itemId] .== movie), :rating])[1])\n                  end\n                  push!( CorrelationArray , pearsonCorrelation(X,Y))\n            end\n     end\nend\n", "meta": {"hexsha": "18cd9cc3d0c1ca5947e49e0b3ccc2290b77fa457", "size": 1500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "playground/PearsonCoefficient.jl", "max_stars_repo_name": "nkottary/RecSys.jl", "max_stars_repo_head_hexsha": "c33e06f37bd8c327380944226b3c33cbd7544339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-10-09T07:01:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:08:40.000Z", "max_issues_repo_path": "playground/PearsonCoefficient.jl", "max_issues_repo_name": "nkottary/RecSys.jl", "max_issues_repo_head_hexsha": "c33e06f37bd8c327380944226b3c33cbd7544339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2015-06-05T09:26:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-14T08:12:00.000Z", "max_forks_repo_path": "playground/PearsonCoefficient.jl", "max_forks_repo_name": "nkottary/RecSys.jl", "max_forks_repo_head_hexsha": "c33e06f37bd8c327380944226b3c33cbd7544339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-09-28T12:25:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-05T08:27:40.000Z", "avg_line_length": 31.25, "max_line_length": 99, "alphanum_fraction": 0.4746666667, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7865978124947534}}
{"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\u03b2 = 5.0;\n\u03b3 = 1.5;\n# M = Float64[2.1];\nM = 2.1;\nq\u2080 = [0.0];\np\u2080 = [0.0];\n\u0394t = 1e-1;\nn_iters = 10^4;\n\nV = x->Harmonic(x);\ncfg = ForwardDiff.GradientConfig(V, q\u2080);\ngradV! = (gradV, x)-> ForwardDiff.gradient!(gradV, V, x, cfg);\n\nsampler = GJF(gradV!, \u03b2, \u03b3, M, \u0394t)\n\nRandom.seed!(100);\nQ\u2080 = copy(q\u2080);\nP\u2080 = copy(p\u2080);\nsample_trajectory!([Q\u2080, P\u2080], sampler, options=MDOptions(n_iters=n_iters));\n@printf(\"In Place (Q,P) after %d iterations: (%g,%g)\\n\",n_iters, Q\u2080[1], P\u2080[1]);\n#\nRandom.seed!(100);\nXvals = sample_trajectory([q\u2080, p\u2080], 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\u2080, p\u2080], 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((\u03b2)/(2*\u03c0))*exp.(-0.5 * \u03b2 * 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 \u03d5_k, defined by \u03d5_0\u22611, and if k\u22651 and k is odd, by\r\n\u03d5_k(x)=sqrt(2)sin((k+1)*\u03c0*x) and if k\u22651 and even, by \u03d5_k(x)=sqrt(2)cos(\u03c0*k*x).\r\nThis function is defined for k\u22650.\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 \u2265 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\u2264x\u22641/2 and\r\n-1+2x for 0.5\u2264x\u22641, and is 1-periodically extended to all x\u2208R.\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\u2264y\u22640.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\u22650 and 1\u2264k\u22642^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)\u2264x\u2264(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 \u2265 0 || throw(AssertionError(\"j should be a nonnegative integer.\"))\r\n  1\u2264k\u22642^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 \u2264 ldexp(float(k-1), -j) || y \u2265 ldexp(float(k), -j)\r\n      return 0.0\r\n    elseif ldexp(float(k-1), -j) < y \u2264 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": "# 1D diffusion problem\n\n# Packages and inclusions\nusing ModelingToolkit,DiffEqOperators,LinearAlgebra,Test,OrdinaryDiffEq\nusing ModelingToolkit: Differential\n\n# Beam Equation\n@test_broken begin\n    @parameters x, t\n    @variables u(..)\n    Dt = Differential(t)\n    Dtt = Differential(t)^2\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n    Dx3 = Differential(x)^3\n    Dx4 = Differential(x)^4\n\n    g = -9.81\n    EI = 1\n    mu = 1\n    L = 10.0\n    dx = 0.4\n\n    eq = Dtt(u(t,x)) ~ -mu*EI*Dx4(u(t,x)) + mu*g\n\n    bcs = [u(0, x) ~ 0,\n           u(t,0) ~ 0,\n           Dx(u(t,0)) ~ 0,\n           Dxx(u(t, L)) ~ 0,\n           Dx3(u(t, L)) ~ 0]\n\n    # Space and time domains\n    domains = [t \u2208 IntervalDomain(0.0,1.0),\n               x \u2208 IntervalDomain(0.0,L)]\n\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n    discretization = MOLFiniteDifference([x=>dx],t, centered_order=4)\n    prob = discretize(pdesys,discretization)\nend\n\n# Beam Equation with Velocity\n@test_broken begin\n    @parameters x, t\n    @variables u(..), v(..)\n    Dt = Differential(t)\n    Dtt = Differential(t)^2\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n    Dx3 = Differential(x)^3\n    Dx4 = Differential(x)^4\n\n    g = -9.81\n    EI = 1\n    mu = 1\n    L = 10.0\n    dx = 0.4\n\n    eqs = [v(t, x) ~ Dt(u(t,x)),\n           Dt(v(t,x)) ~ -mu*EI*Dx4(u(t,x)) + mu*g]\n\n    bcs = [u(0, x) ~ 0,\n           v(0, x) ~ 0,\n           u(t,0) ~ 0,\n           v(t,0) ~ 0,\n           Dxx(u(t, L)) ~ 0,\n           Dx3(u(t, L)) ~ 0]\n\n    # Space and time domains\n    domains = [t \u2208 IntervalDomain(0.0,1.0),\n               x \u2208 IntervalDomain(0.0,L)]\n\n    pdesys = PDESystem(eqs,bcs,domains,[t,x],[u(t,x),v(t,x)])\n    discretization = MOLFiniteDifference([x=>dx],t, centered_order=4)\n    prob = discretize(pdesys,discretization)\nend\n\n@testset \"Kuramoto\u2013Sivashinsky equation\" begin\n    @parameters x, t\n    @variables u(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dx2 = Differential(x)^2\n    Dx3 = Differential(x)^3\n    Dx4 = Differential(x)^4\n\n    \u03b1 = 1\n    \u03b2 = 4\n    \u03b3 = 1\n    eq = Dt(u(x,t)) ~ -u(x,t)*Dx(u(x,t)) - \u03b1*Dx2(u(x,t)) - \u03b2*Dx3(u(x,t)) - \u03b3*Dx4(u(x,t))\n\n    u_analytic(x,t;z = -x/2+t) = 11 + 15*tanh(z) -15*tanh(z)^2 - 15*tanh(z)^3\n    du(x,t;z = -x/2+t) = 15/2*(tanh(z) + 1)*(3*tanh(z) - 1)*sech(z)^2\n\n    bcs = [u(x,0) ~ u_analytic(x,0),\n           u(-10,t) ~ u_analytic(-10,t),\n           u(10,t) ~ u_analytic(10,t),\n           Dx(u(-10,t)) ~ du(-10,t),\n           Dx(u(10,t)) ~ du(10,t)]\n\n    # Space and time domains\n    domains = [x \u2208 IntervalDomain(-10.0,10.0),\n               t \u2208 IntervalDomain(0.0,1.0)]\n    # Discretization\n    dx = 0.4; dt = 0.2\n\n    discretization = MOLFiniteDifference([x=>dx],t;centered_order=4,grid_align=center_align)\n    pdesys = PDESystem(eq,bcs,domains,[x,t],[u(x,t)])\n    prob = discretize(pdesys,discretization)\n\n    sol = solve(prob,Tsit5(),saveat=0.1,dt=dt)\n\n    @test sol.retcode == :Success\n\n    xs = domains[1].domain.lower+dx+dx:dx:domains[1].domain.upper-dx-dx\n    ts = sol.t\n\n    u_predict = sol.u\n    u_real = [[u_analytic(x, t) for x in xs] for t in ts]\n    u_diff = u_real - u_predict\n    @test_broken u_diff[:] \u2248 zeros(length(u_diff)) atol=0.01;\n    #plot(xs, u_diff)\nend\n", "meta": {"hexsha": "62b51b085c64584e538283b91787272f73b71f86", "size": 3207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MOL/MOL_1D_HigherOrder.jl", "max_stars_repo_name": "JordiBolibar/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "4913718c9ff2c0fe1613b7274e63e7bf048221d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-12T01:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T01:22:23.000Z", "max_issues_repo_path": "test/MOL/MOL_1D_HigherOrder.jl", "max_issues_repo_name": "emmanuellujan/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "fa8fc4bb59fd194d2ba4de87def26bffdd2176c0", "max_issues_repo_licenses": ["MIT"], "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/MOL_1D_HigherOrder.jl", "max_forks_repo_name": "emmanuellujan/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "fa8fc4bb59fd194d2ba4de87def26bffdd2176c0", "max_forks_repo_licenses": ["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.0731707317, "max_line_length": 92, "alphanum_fraction": 0.5472404116, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.78659459659019}}
{"text": "export cellvolume\n\n\"\"\"\n    cellvolume(a, b, c, \u03b1, \u03b2, \u03b3)\n\nCalculates the cell volume from 6 cell parameters.\n\"\"\"\ncellvolume(a, b, c, \u03b1, \u03b2, \u03b3) =\n    a * b * c * sqrt(sind(\u03b1)^2 - cosd(\u03b2)^2 - cosd(\u03b3)^2 + 2 * cosd(\u03b1) * cosd(\u03b2) * cosd(\u03b3))\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": "# # Example 2 on MibS\n\n\n# Model of the problem\n# First level\n# ```math\n# \\min_{x} 2x -4y + 10z,\\\\\n# \\notag s.t.\\\\\n# -3x + 2y + 2z \\leq 12,\\\\ \n# x + 2y \\leq 20,\\\\\n# x \\leq 10,\\\\\n# x \\in \\mathbb{Z}, z \\in \\mathbb{B},\\\\\n# ```\n# Second level\n# ```math\n# \\min_{y} y,\\\\\n# \\notag s.t.\\\\\n# 2x - y + 3z<= 7,\\\\\n# -2x + 4y <= 16,\\\\\n# y <= 5\\\\\n# y \\in \\mathbb{Z}\\\\\n# ```\n\nusing BilevelJuMP\nusing JuMP\nusing Test\n\nmodel = BilevelModel()\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, Int)\n@variable(Upper(model), z, Bin)\n\n#Lower level variables\n@variable(Lower(model), y, Int)\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, 2x - 4y + 10z)\n\n# Upper constraints\n@constraints(Upper(model), begin\n    u1, -3x + 2y + 5z  <= 12\n    u2, x + 2y <= 20\n    u3, x <= 10\nend)\n\n# Followed by the objective and constraints of the lower problem:\n\n# Lower objective function\n@objective(Lower(model), Min, y)\n\n# Lower constraints\n@constraint(Lower(model), l1,  2x -  y + 3z <= 7)\n@constraint(Lower(model), l2, -2x +  4y <= 16)\n@constraint(Lower(model), l3, y <= 5)\n\n# Using MibS Solver\nsolution = BilevelJuMP.solve_with_MibS(model, silent = true)\n\n# Auto testing\n@test solution.status == true\n@test solution.objective \u2248 -8.0\n@test solution.nonzero_upper == Dict(0 => 6.0)\n@test solution.nonzero_lower == Dict(0 => 5.0)\n@test solution.all_upper[\"x\"] == 6.0\n@test solution.all_upper[\"z\"] == 0\n@test solution.all_lower[\"y\"] == 5.0\n", "meta": {"hexsha": "f4d5048cb71de97b2441f8ae8fe9653830f4c38a", "size": 1571, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/MibS_example2.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/MibS_example2.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/MibS_example2.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": 21.8194444444, "max_line_length": 79, "alphanum_fraction": 0.6390833864, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7865943392073286}}
{"text": "\nusing LinearAlgebra\n\nconst companion = CommutativeRings.companion\n\n@testset \"vector spaces\" begin\n    \n    Z = ZZ/7\n\n    xnull = VectorSpace(Matrix{Z}(undef, 5, 0))\n    xall = VectorSpace(diagm(ones(Z, 5)))\n    @test intersect(xnull, xnull) == xnull\n    @test intersect(xnull, xall) == xnull\n    @test intersect(xall, xall) == xall\n    @test sum(xnull, xnull) == xnull\n    @test sum(xall, xnull) == xall\n    @test sum(xall, xall) == xall\n\n    va = VectorSpace(Z[1 0; 0 1; 0 0; 0 0; 0 0])\n    vb = VectorSpace(Z[0 0; 0 0; 0 0; 0 1; 1 0])\n\n    vc = sum(va, vb)\n    @test Matrix(vc) == [1 0 0 0; 0 1 0 0; 0 0 0 0; 0 0 0 1; 0 0 1 0]\n\n    vc = intersect(va, vb)\n    @test Matrix(vc) == Matrix{Z}(undef,5,0)\n\n    vc = complement(vb)\n    @test Matrix(vc) == Z[0 0 1; 0 1 0; 1 0 0; 0 0 0; 0 0 0]\n\n    wa = VectorSpace(Z[1, 2, 3, 4, 5])\n    wb = VectorSpace(Z[1, 2, 4, 4, 0])\n    wc = VectorSpace(Z[0, 0, 2, 1, 0])\n    xa = sum(wa, wc)\n    xb = sum(wb, wc)\n\n    @test intersect(wa, xa) == wa\n    @test intersect(xa, wc) == wc\n    @test intersect(wc, xb) == wc\n    @test intersect(xb, wb) == wb\n\n    xint = intersect(xa, xb)\n    @test xint == wc\n\n    xsum = sum(xa, xb)\n    @test issubset(wa, xsum)\n    @test issubset(wb, xsum)\n    @test issubset(wc, xsum)\n    @test issubset(xa, xsum)\n    @test issubset(xb, xsum)\n\n    @test intersect(xnull, xsum) == xnull\n    @test intersect(xall, xsum) == xsum\n    @test sum(xnull, xsum) == xsum\n    @test sum(xall, xsum) == xall\nend\n\n@testset \"determinant\" begin\n    G = ZZ/89\n    A = G.([1 2 3; 4 5 6; 7 8 9])\n    B = G.([1 2 3; 4 5 6; 7 8 8])\n    @test iszero(det(A))\n    @test iszero(adjugate(A) * A)\n    @test !iszero(det(B))\n    @test adjugate(B) ./ det(B) == inv(B)\n\n    p = characteristic_polynomial(B)\n    @test iszero(p(B))\n    @test characteristic_polynomial(companion(p)) == p\nend\n", "meta": {"hexsha": "0d641d7a95cc689b0e33fc84c9410e2e1a40968a", "size": 1821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/linearalgebra.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": "test/linearalgebra.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": "test/linearalgebra.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": 25.6478873239, "max_line_length": 69, "alphanum_fraction": 0.5645249863, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7865943383997901}}
{"text": "using Pkg\nPkg.activate(\".\")\nPkg.instantiate()\n\nusing BenchmarkTools\nusing Distributions\nusing GLM\nusing HypothesisTests\nusing LinearAlgebra\nusing Plots\nusing Random\nusing RDatasets\nusing SpecialFunctions\nusing Statistics\n\nRandom.seed!(666)\n\nplot(0:0.1:10, gamma;\n    xlabel=\"x\",\n    ylabel=\"gamma(x): log scale\",\n    label=\"\",\n    yscale=:log10,\n)\n\nxs_aux = rand(Uniform(-1, 1), 100)\n\nhistogram(xs_aux)\n\nd_aux = Normal()\npdf(d_aux, 1)\ncdf(TDist(10), 1)\nfit(Normal, xs_aux)\n\nOneSampleTTest(xs_aux)\n\nwages_aux = dataset(\"plm\", \"Snmesp\")\nmodel_aux = lm(@formula(W ~ 1 + N + Y + I + K + F), wages_aux)\nmodel_aux = glm(@formula(W ~ 1 + N + Y + I + K + F), wages_aux, Normal(), IdentityLink())\n\nX_aux = randn(10, 4)\neigen_aux = eigen(X_aux'*X_aux)\n\n@time eigen(X_aux'*X_aux);\n", "meta": {"hexsha": "9e1a08d8f9ba84712f2c8f37fe0cddd6bf65474e", "size": 770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/lecture_11/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_11/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_11/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": 17.5, "max_line_length": 89, "alphanum_fraction": 0.6857142857, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551576415562, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7865812785252079}}
{"text": "using TensorOperations\nusing KrylovKit\nusing LinearAlgebra\nusing Random\n\nfunction init_random_MPS(d,m,N)\n\n    MPS=Dict()\n    MPS[1] = im*rand(1,d,m)\n    for i in 2:N-1\n        MPS[i]= im*rand(m,d,m)\n    end\n    MPS[N] = im*rand(m,d,1)\n    return MPS\nend\n\nfunction Construct_Ising_MPO(h,J,N)\n    d=2\n    D=3\n    id = [ 1 0 ; 0 1 ]\n    sp = [ 0 1 ; 0 0 ]\n    sm = [ 0 0 ; 1 0 ]\n    sz = [ 1 0 ; 0 -1 ]\n    sx = [ 0 1 ; 1 0 ]\n    id = [ 1 0 ; 0 1 ]\n    W = im *  zeros(D,D,d,d)\n    W1 = im *  zeros(1,D,d,d)\n    W2 = im *  zeros(D,1,d,d)\n    W[1,1,:,:]=id\n    W[2,1,:,:]=sz\n    W[3,1,:,:]=-h*sx\n    W[3,2,:,:]=-J*sz\n    W[3,3,:,:]=id;\n\n    W1[1,1,:,:]=-h*sx\n    W1[1,2,:,:]=-J*sz\n    W1[1,3,:,:]=id\n\n    W2[1,1,:,:]=id\n    W2[2,1,:,:]=sz\n    W2[3,1,:,:]=-h*sx\n\n\n    MPO = Dict()\n    MPO[1] = W1\n    for i in 2:(N-1)\n        MPO[i] = W\n    end\n    MPO[N] = W2\n\n    return MPO\nend\n\nfunction Normalize(MPS)\n    norm = MPS_dot(MPS,MPS)\n    for i in 1:length(MPS)\n        MPS[i] = MPS[i]/norm^(1/(2*length(MPS)))\n    end\n    return MPS\nend\n\n\nfunction MPS_dot(A,B)\n    E=ones(1,1)\n    for i in 1:length(A)\n        E = contract_from_left_MPS( A[i] , E , B[i] )\n    end\n    return E[1]\nend\n\n## initial E and F matrices for the left and right vacuum states\nfunction initial_L(W,N)\n    sW=size(W)\n    L = ones(sW[1],1,1)#im*zeros(sW[1],1,1)\n    #L[1] = 1\n    #println(size(L))\n    return L\nend\n\nfunction initial_R(W,N)\n    sW=size(W)\n    R = ones(sW[2],1,1)#im*zeros(sW[2],1,1)\n    #R[end] = 1\n    #println(size(R))\n    return R\nend\n\nfunction construct_R(MPS, MPO, Blist, N)\n    R = Dict()\n    R[N] = initial_R(MPO[N],N)\n    for i in N:-1:2\n        R[i-1] = contract_from_right(R[i], MPS[i], MPO[i])\n    end\n    return R\nend\n\nfunction construct_L(Alist, MPO, Blist,N)\n    L = Dict()\n    L[1] = initial_L(MPO[1],N)\n    return L\nend\n", "meta": {"hexsha": "16d8fdd921323b5237b4e2e867217e8ac1282a50", "size": 1818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old/utils.jl", "max_stars_repo_name": "aanniikkeettr/Tensor-Networks", "max_stars_repo_head_hexsha": "888acc3194073b7782e73ccea9b2246b3f877d0f", "max_stars_repo_licenses": ["MIT"], "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.jl", "max_issues_repo_name": "aanniikkeettr/Tensor-Networks", "max_issues_repo_head_hexsha": "888acc3194073b7782e73ccea9b2246b3f877d0f", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "aanniikkeettr/Tensor-Networks", "max_forks_repo_head_hexsha": "888acc3194073b7782e73ccea9b2246b3f877d0f", "max_forks_repo_licenses": ["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.8235294118, "max_line_length": 64, "alphanum_fraction": 0.5066006601, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7865459274341235}}
{"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\u03b1 = min(-u0 * \u230a\u03c0\u230b, a + v0 * \u230a\u03c0\u230b) \n```\nwhere ``\u03c0 = -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    \u03c0 = -a / (u0 + v0)\n    return min(\n        -u0 * floor(\u03c0),\n        a + v0 * ceil(\u03c0)\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\u03b1 = min(-u0 * \u230a\u03c0\u230b, a + v0 * \u230a\u03c0\u230b) \n```\nwhere ``\u03c0 = -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    \u03c0 = -a / (u0 + v0)\n    return max(\n        -u0 * ceil(\u03c0),\n        a + v0 * floor(\u03c0)\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\u2080, w) = exp(-((t - t\u2080) / w)^2)\n\nconst KDM = 4.148808e3 # MHz^2 pc^-1 cm^3 s\n\n\"\"\"\n\u0394t(DM, \u03bd\u2081, \u03bd\u2082)\nCalculates the time delay corresponding to a dispersed pulse at dispersion measure `DM` in pc/cc between\nfrequencies `\u03bd\u2081` and `\u03bd\u2082`\n\"\"\"\n\u0394t(DM, \u03bd\u2081, \u03bd\u2082) = KDM * DM * (\u03bd\u2081^-2 - \u03bd\u2082^-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- '\u03b4t`: 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- `\u03b1`: 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                    \u03b4t=1e-3,\n                    w=8,\n                    A=2,\n                    \u03b1=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) \u00f7 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=\u03b4t, length=samples)\n\n    t_start = start * \u03b4t\n\n    # Caclulate shifts\n    shifts = @. \u0394t(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 * \u03b4t) * A * noise_floor * (freqs' / f_high)^\u03b1\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\" => \u03b4t,\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\u20131398. DOI: 10.1002/jcc.23935\n\"\"\"\nfunction boys_rec_largex(x, n::Int)\n    if n == 0\n        return \u221a\u03c0 / (2\u221ax)\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": "@testset \"Searches\" begin\n\n    @testset \"Searches: Binary\" begin\n        sample = [0, 23, 52, 552, 555, 602, 1004]\n        reversed_sample = reverse(sample)\n        unsorted_sample = [124, 53, 21, 163]\n        binary_search(sample, 52)\n        binary_search(reversed_sample, 52, rev=true)\n        @test_throws ErrorException binary_search(unsorted_sample, 21)  # throws an error\n    end\n\n    @testset \"Searches: Linear\" begin\n        array = [1,3,4,7,8,11]\n        linear_search(array, 3)\n        linear_search(array, 8)\n        linear_search(array, 12)\n    end\n\n    @testset \"Searches: Exponential\" begin\n        arr = [1, 2, 3, 4, 13, 15, 20];\n        x = 4;\n        n = size(arr)[1]\n        l = 1;\n        r = n;\n\n        exponential_search(arr, x)\n    end\n\n    @testset \"Searches: Interpolation\" begin\n        arr = [1, 2, 3, 4, 13, 15, 20];\n        x = 15;\n        n = size(arr)[1]\n        l = 1;\n        r = n;\n\n        interpolation_search(arr, l, r, x)\n    end\n\n    @testset \"Searches: Jump\" begin\n        arr = [1, 2, 3, 31, 4, 13];\n        x = 31;\n        jump = 2; # optimum is sqroot(n)\n        n = size(arr)[1];\n\n        jump_search(arr, x, jump)\n    end\n\nend\n", "meta": {"hexsha": "c68d36d1d92030e9e938e74b6168990e3099dae0", "size": 1173, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/searches.jl", "max_stars_repo_name": "ashwani-rathee/Julia", "max_stars_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-22T18:32:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-22T18:32:05.000Z", "max_issues_repo_path": "test/searches.jl", "max_issues_repo_name": "ashwani-rathee/Julia", "max_issues_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_issues_repo_licenses": ["MIT"], "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/searches.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-07-26T11:15:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T11:15:24.000Z", "avg_line_length": 23.9387755102, "max_line_length": 89, "alphanum_fraction": 0.5277067349, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8596637577007393, "lm_q1q2_score": 0.7865071889038607}}
{"text": "using MLDatasets, LightGraphs, Plots, LaTeXStrings, NGWP, MTSG\n# Load local module\npush!(LOAD_PATH, @__DIR__)\nusing pSGWT\n\nexample, label = MNIST.traindata(Float64, 28)\ndigit_img = example[4:26, 26:-1:5]\n# heatmap(digit_img', ratio = 1, c=:viridis, frame = :none, xlim = [1, 22])\n\nNx, Ny = size(digit_img)\nG = LightGraphs.grid([Nx, Ny]); N = nv(G);\nW = Matrix(adjacency_matrix(G))\nL = Matrix(laplacian_matrix(G))\nQ = incidence_matrix(G; oriented = true)\n\ud835\udecc, \ud835\udebd = eigen(L); \ud835\udebd = \ud835\udebd .* sign.(\ud835\udebd[1, :])';\n\nD = natural_eigdist(\ud835\udebd, \ud835\udecc, Q; distance = :DAG)\n\nfunction grid_eigenvector_plot(l)\n    heatmap(reshape(\ud835\udebd[:, l], (Nx, Ny))', c = :viridis, ratio = 1, frame = :none,\n        xlim = [1, Nx], size = (500, 400), cbar = true)\nend\n\nfunction grid_NGWFvector_plot(l, x, D, \ud835\udebd; \u03c3 = 0.2 * maximum(D))\n    heatmap(reshape(ngwf_vector(D, l, x, \ud835\udebd; \u03c3 = \u03c3)', (Nx, Ny))',\n        c = :viridis, ratio = 1, frame = :none, xlim = [1, Nx], size = (500, 400))\nend\n\nfunction plot_edge!(A, B; style = :solid, subplot = 1)\n    plot!([A[1], B[1], NaN], [A[2], B[2], NaN], c = :red, legend = false,\n        width = 10, style = style, subplot = subplot)\nend\n\nfunction plot_square!(Nx, Ny; subplot = 1)\n    plot_edge!([-0.33, 0], [Nx + 1.24, 0]; subplot = subplot)\n    plot_edge!([0, 0], [0, Ny + 1]; subplot = subplot)\n    plot_edge!([-0.33, Ny + 1], [Nx + 1.24, Ny + 1]; subplot = subplot)\n    plot_edge!([Nx + 0.92, 0], [Nx + 0.92, Ny + 1]; subplot = subplot)\nend\n\nfunction grid_vector_plot!(l, i, VECs)\n    v = deepcopy(VECs[:, l])\n    v ./= norm(v, 1)\n    heatmap!(reshape(v, (Nx, Ny))', c = :viridis, ratio = 1, frame = :none,\n        xlim = [-0.5, Nx+1.5], cbar = false, subplot = i)\nend\n\nfunction grid_vec_heatmap(VEC, Nx, Ny; l = 1)\n    v = VEC[:, l]\n    heatmap(reshape(v, (Nx, Ny))', c = :viridis, ratio = 1, frame = :none,\n        xlim = [1, Nx], size = (500, 400), cbar = true)\nend\n", "meta": {"hexsha": "8541bd3e3abe5b2ce4b94e6f236d79d747b50d36", "size": 1861, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dissertation/scripts/setups/grid23x22.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": "dissertation/scripts/setups/grid23x22.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": "dissertation/scripts/setups/grid23x22.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": 35.1132075472, "max_line_length": 82, "alphanum_fraction": 0.5867813004, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7865071777407793}}
{"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\u00d75 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\u00d75 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\u00d73 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": "using LinearAlgebra\n# Testing the following distribution: WishartGaussian, DirichletMultinomial, GammaNormal, NormalNormal, BetaBernoulli\n\n@testset \"testing posterior paramters\" begin\n\n  @testset \"Normal-Inverse-Wishart\" begin\n\n    # prior\n    \u03bc0 = zeros(2)\n    \u03ba0 = 5.0\n    \u03bd0 = 9.0\n    \u03a30 = Matrix{Float64}(I, 2, 2) \n\n    # data\n    x = [0.2 0.1; 0.1 0.0; 0.2 0.05]\n    (N, D) = size(x)\n\n    # distribution\n    d = WishartGaussian(\u03bc0, \u03ba0, \u03bd0, \u03a30)\n\n    # test prior\n    (\u03bc, \u03ba, \u03bd, \u03a3) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03ba == \u03ba0\n    @test \u03bd == \u03bd0\n    @test all( \u03bc .== \u03bc0 )\n    @test all( \u03a3 .== \u03a30 )\n\n    # add data\n    BayesianNonparametrics.add!(d, x)\n\n    # test posterior parameters\n    (\u03bc, \u03ba, \u03bd, \u03a3) = BayesianNonparametrics.posteriorParameters(d)\n\n    mu = vec(mean(x, dims=1))\n    SS = x' * x\n\n    @test \u03ba == \u03ba0 + N\n    @test \u03bd == \u03bd0 + N\n    @test all( \u03bc .\u2248 (\u03ba0 * \u03bc0 .+ mu * N) ./ \u03ba )\n    @test all( \u03a3 .== \u03a30 + SS - \u03ba * (\u03bc * \u03bc') + \u03ba0 * (\u03bc0 * \u03bc0') )\n\n    # remove data\n    BayesianNonparametrics.remove!(d, x)\n\n    # test prior\n    (\u03bc, \u03ba, \u03bd, \u03a3) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03ba == \u03ba0\n    @test \u03bd == \u03bd0\n    @test all( \u03bc .== \u03bc0 )\n    @test all( \u03a3 .== \u03a30 )\n  end\n\n  @testset \"Normal-Gamma\" begin\n\n    # prior\n    \u03bc0 = 0.0\n    \u03bb0 = 1.0\n    \u03b10 = 1.0\n    \u03b20 = 1.0\n\n    # data\n    x = [0.1, 0.0, 0.05]\n    N = length(x)\n\n    # distribution\n    d = GammaNormal(\u03bc0 = \u03bc0, \u03bb0 = \u03bb0, \u03b10 = \u03b10, \u03b20 = \u03b20)\n\n    # test prior\n    (\u03bc, \u03bb, \u03b1, \u03b2) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03bc == \u03bc0\n    @test \u03bb == \u03bb0\n    @test \u03b1 == \u03b10\n    @test \u03b2 == \u03b20\n\n    # add data\n    BayesianNonparametrics.add!(d, x)\n\n    # test posterior paramters\n    # see: https://www.cs.ubc.ca/~murphyk/Papers/bayesGauss.pdf page 8.\n    (\u03bc, \u03bb, \u03b1, \u03b2) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03bb == \u03bb0 + N\n    @test \u03b1 == \u03b10 + (N / 2)\n    @test \u03bc == (\u03bb0 * \u03bc0 + N * mean(x)) / (\u03bb0 + N)\n    @test \u03b2 == \u03b20 + 1/2 * sum( (x .- mean(x)).^2 ) + ( \u03bb0 * N * (mean(x) - \u03bc0)^2 ) / (2 * \u03bb)\n    \n    # remove data\n    BayesianNonparametrics.remove!(d, x)\n\n    # test prior\n    (\u03bc, \u03bb, \u03b1, \u03b2) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03bc == \u03bc0\n    @test \u03bb == \u03bb0\n    @test \u03b1 == \u03b10\n    @test \u03b2 == \u03b20\n  end\n\n  @testset \"Beta-Bernoulli\" begin\n    \n    # prior\n    \u03b10 = 1.0\n    \u03b20 = 1.0\n\n    # data\n    x = Bool[0, 1, 0, 0, 1]\n    N = length(x)\n\n    # distribution\n    d = BetaBernoulli(\u03b10 = \u03b10, \u03b20 = \u03b20)\n\n    # test prior\n    (\u03b1, \u03b2) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03b1 == \u03b10\n    @test \u03b2 == \u03b20\n\n    # add data\n    BayesianNonparametrics.add!(d, x)\n\n    # test posterior paramters\n    (\u03b1, \u03b2) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03b1 == \u03b10 + sum(x)\n    @test \u03b2 == \u03b20 + (N - sum(x)) \n\n    # remove data\n    BayesianNonparametrics.remove!(d, x)\n\n    # test prior\n    (\u03b1, \u03b2) = BayesianNonparametrics.posteriorParameters(d)\n\n    @test \u03b1 == \u03b10\n    @test \u03b2 == \u03b20\n  end\n\nend\n", "meta": {"hexsha": "4b7a595cd775500d18da9df9a2d1292d5f066fd2", "size": 2944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/distributionTests.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": "test/distributionTests.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": "test/distributionTests.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": 20.8794326241, "max_line_length": 117, "alphanum_fraction": 0.5478940217, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7864042085102139}}
{"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    \u03c3::T\nend\n    \n\"\"\"\n    AnisotropicExponential(A, \u03c3=1)\n\nCreate an anisotropic exponential covariance structure with anisotropy matrix A and (optional) marginal standard deviation `\u03c3`.\n\n# Examples\n```jldoctest\njulia> A = [1 0.5; 0.5 1]\n2\u00d72 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], \u03c3=1.0)\n\n```\n\"\"\"\nfunction AnisotropicExponential(A::Matrix{T} where {T<:Real}; \u03c3=1.0::T where {T<:Real}) \n\tisposdef(A) || throw(ArgumentError(\"anisotropy matrix A must be positive definite\"))\n    \u03c3 > 0 || throw(ArgumentError(\"marginal standard deviation \u03c3 of exponential covariance cannot be negative or zero\"))\n\tT = promote_type(eltype(A),typeof(\u03c3))\n\tAnisotropicExponential{T,typeof(A)}(A,convert(T,\u03c3)) \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), \u03c3=$(a.\u03c3))\")\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": "using Test \n\n# This function takes \n#     - v: value in register\n#     - a: a  scaling value for the logarithm based on Morris's paper\n# It returns n(v,a), the approximate count\nfunction n(v, a)\n    a*((1+1/a)^v-1)  \nend\n\n# This function takes\n#    - v: value in register\n#    - a: a scaling value for the logarithm based on Morris's paper\n# It returns a new value for v\nfunction increment(v, a)\n    # delta is the probability of incrementing our counter\n    delta = 1/(n(v+1, a)-n(v, a))\n\n    if rand() <= delta\n        return v += 1\n    else\n        return v\n    end\nend\n\n# This simulates counting and takes\n#     - n_items: number of items to count and loop over\n#     - a: a scaling value for the logarithm based on Morris's paper\n# It returns n(v,a), the approximate count\nfunction approximate_count(n_items, a)\n    v = 0\n    for i = 1:n_items\n        v = increment(v, a)\n    end\n\n    return n(v, a)\nend\n\n# This function takes\n#     - n_trials: the number of counting trials\n#     - n_items: the number of items to count to\n#     - a: a scaling value for the logarithm based on Morris's paper\n#     - threshold: the maximum percent error allowed\n# It returns a true / false test value\nfunction test_approximate_count(n_trials, n_items, a, threshold)\n    samples = [approximate_count(n_items, a) for i = 1:n_trials]\n\n    avg = sum(samples)/n_trials\n\n    @test ((avg - n_items) / n_items < threshold)\nend\n\n@testset \"Counting Tests, 100 trials\" begin\n    println(\"testing 1,000, a = 30, 1% error\")\n        test_approximate_count(100, 1000, 30, 0.1)\n    println(\"testing 12,345, a = 10, 1% error\")\n        test_approximate_count(100, 12345, 10, 0.1)\n    # Note: with a lower a, we need more trials, so a higher % error here.\n    println(\"testing 222,222, a = 0.5, 10% error\")\n        test_approximate_count(100, 222222, 0.5, 0.2)\nend\n", "meta": {"hexsha": "5e1fa86c348837255f9460058034ddd4cabc0736", "size": 1835, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/approximate_counting/code/julia/approximate_counting.jl", "max_stars_repo_name": "Ridham177/algorithm-archive", "max_stars_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-29T19:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T15:58:17.000Z", "max_issues_repo_path": "contents/approximate_counting/code/julia/approximate_counting.jl", "max_issues_repo_name": "Ridham177/algorithm-archive", "max_issues_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contents/approximate_counting/code/julia/approximate_counting.jl", "max_forks_repo_name": "Ridham177/algorithm-archive", "max_forks_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_forks_repo_licenses": ["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.5967741935, "max_line_length": 74, "alphanum_fraction": 0.6539509537, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7863858039524093}}
{"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": "using ModelingToolkit\nusing Test\n\n# Define some variables\n@Param t \u03c3 \u03c1 \u03b2\n@Unknown x(t) y(t) z(t)\n@Deriv D'~t # Default of first derivative, Derivative(t,1)\n@Const c=0\n\n# Define a differential equation\neqs = [D(x) ~ \u03c3*(y-x),\n       D(y) ~ x*(\u03c1-z)-y,\n       D(z) ~ x*y - \u03b2*z]\nde = DiffEqSystem(eqs,[t],[x,y,z],[\u03c3,\u03c1,\u03b2])\nModelingToolkit.generate_ode_function(de)\nModelingToolkit.generate_ode_function(de;version=ModelingToolkit.SArrayFunction)\njac_expr = ModelingToolkit.generate_ode_jacobian(de)\njac = ModelingToolkit.calculate_jacobian(de)\nf = ODEFunction(de)\nModelingToolkit.generate_ode_iW(de)\n\n# Differential equation with automatic extraction of variables\nde2 = DiffEqSystem(eqs, [t])\n\nfunction test_vars_extraction(de, de2)\n    for el in (:ivs, :dvs, :ps)\n        names2 = sort(collect(var.name for var in getfield(de2,el)))\n        names = sort(collect(var.name for var in getfield(de,el)))\n        @test names2 == names\n    end\nend\ntest_vars_extraction(de, de2)\n\n# Conversion to first-order ODEs #17\n@Deriv D3'''~t\n@Deriv D2''~t\n@Unknown u(t) u_tt(t) u_t(t) x_t(t)\neqs = [D3(u) ~ 2(D2(u)) + D(u) + D(x) + 1\n       D2(x) ~ D(x) + 2]\nde = DiffEqSystem(eqs, [t])\nde1 = ode_order_lowering(de)\nlowered_eqs = [D(u_tt) ~ 2u_tt + u_t + x_t + 1\n               D(x_t)  ~ x_t + 2\n               D(u_t)  ~ u_tt\n               D(u)    ~ u_t\n               D(x)    ~ x_t]\nfunction test_eqs(eqs1, eqs2)\n    length(eqs1) == length(eqs2) || return false\n    eq = true\n    for (eq1, eq2) in zip(eqs1, eqs2)\n        lhs1, lhs2 = eq1.lhs, eq2.lhs\n        typeof(lhs1) === typeof(lhs2) || return false\n        for f in fieldnames(typeof(lhs1))\n            eq = eq & isequal(getfield(lhs1, f), getfield(lhs2, f))\n        end\n        eq = eq & isequal(eq1.rhs, eq2.rhs)\n    end\n    eq\nend\n@test_broken test_eqs(de1.eqs, lowered_eqs)\n\n# Internal calculations\na = y - x\neqs = [D(x) ~ \u03c3*a,\n       D(y) ~ x*(\u03c1-z)-y,\n       D(z) ~ x*y - \u03b2*z]\nde = DiffEqSystem(eqs,[t],[x,y,z],[\u03c3,\u03c1,\u03b2])\nModelingToolkit.generate_ode_function(de)\njac = ModelingToolkit.calculate_jacobian(de)\nf = ODEFunction(de)\n\n# Define a nonlinear system\neqs = [0 ~ \u03c3*(y-x),\n       0 ~ x*(\u03c1-z)-y,\n       0 ~ x*y - \u03b2*z]\nns = NonlinearSystem(eqs,[x,y,z],[t,\u03c3,\u03c1,\u03b2])\nns2 = NonlinearSystem(eqs)\nfor el in (:vs, :ps)\n    names2 = sort(collect(var.name for var in getfield(ns2,el)))\n    names = sort(collect(var.name for var in getfield(ns,el)))\n    @test names2 == names\nend\n\nModelingToolkit.generate_nlsys_function(ns)\n\n@Deriv D'~t\n@Param A B C\n_x = y / C\neqs = [D(x) ~ -A*x,\n       D(y) ~ A*x - B*_x]\nde = DiffEqSystem(eqs,[t],[x,y],[A,B,C])\ntest_vars_extraction(de, DiffEqSystem(eqs,[t]))\ntest_vars_extraction(de, DiffEqSystem(eqs))\n@test eval(ModelingToolkit.generate_ode_function(de))([0.0,0.0],[1.0,2.0],[1,2,3],0.0) \u2248 -1/3\n\n# Now nonlinear system with only variables\n@Unknown x y z\n@Param \u03c3 \u03c1 \u03b2\n\n# Define a nonlinear system\neqs = [0 ~ \u03c3*(y-x),\n       0 ~ x*(\u03c1-z)-y,\n       0 ~ x*y - \u03b2*z]\nns = NonlinearSystem(eqs)\nnlsys_func = ModelingToolkit.generate_nlsys_function(ns)\njac = ModelingToolkit.generate_nlsys_jacobian(ns)\nf = @eval eval(nlsys_func)\n\n# Intermediate calculations\n# Define a nonlinear system\neqs = [a ~ y-x,\n       0 ~ \u03c3*a,\n       0 ~ x*(\u03c1-z)-y,\n       0 ~ x*y - \u03b2*z]\nns = NonlinearSystem(eqs,[x,y,z],[\u03c3,\u03c1,\u03b2])\nnlsys_func = ModelingToolkit.generate_nlsys_function(ns)\njac = ModelingToolkit.calculate_jacobian(ns)\njac = ModelingToolkit.generate_nlsys_jacobian(ns)\n", "meta": {"hexsha": "752a935697cdfab50b6ea2ee2ecd52c6e7d457f7", "size": 3419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/system_construction.jl", "max_stars_repo_name": "jpfairbanks/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "8b7b7ae4836ec3f1eaf243e56cbe1c4b53971d09", "max_stars_repo_licenses": ["MIT"], "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/system_construction.jl", "max_issues_repo_name": "jpfairbanks/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "8b7b7ae4836ec3f1eaf243e56cbe1c4b53971d09", "max_issues_repo_licenses": ["MIT"], "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/system_construction.jl", "max_forks_repo_name": "jpfairbanks/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "8b7b7ae4836ec3f1eaf243e56cbe1c4b53971d09", "max_forks_repo_licenses": ["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.731092437, "max_line_length": 93, "alphanum_fraction": 0.6361509213, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.786374166341532}}
{"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": "using OrdinaryDiffEq, Test, DiffEqDevTools, DiffEqOperators\nu0 = rand(2)\nA = DiffEqArrayOperator([2.0 -1.0; -1.0 2.0])\nfunction (p::typeof(A))(::Type{Val{:analytic}},u0,p,t)\n    exp(p.A*t)*u0\nend\n\nprob = ODEProblem(A,u0,(0.0,1.0))\n\nx = rand(2)\n@test A(0.0,x) == A*x\n\nsol = solve(prob,LinearImplicitEuler())\n\ndts = 1./2.^(8:-1:4) #14->7 good plot\nsim  = test_convergence(dts,prob,LinearImplicitEuler())\n@test abs(sim.\ud835\udcaaest[:l2]-1) < 0.2\n\n# using Plots; pyplot(); plot(sim)\n\nB = ones(2)\nL = AffineDiffEqOperator{Float64}((A,),(B,),rand(2))\nprob = ODEProblem(L,u0,(0.0,1.0))\nsol = solve(prob,LinearImplicitEuler())\n\nB = DiffEqArrayOperator(ones(2,2))\nL = AffineDiffEqOperator{Float64}((A,B),(),rand(2))\nfunction (p::typeof(L))(::Type{Val{:analytic}},u0,p,t)\n    exp((p.As[1].A+p.As[2].A)*t)*u0\nend\n\n# Midpoint splitting\n\nprob = ODEProblem(L,u0,(0.0,1.0))\nsol = solve(prob,MidpointSplitting(),dt=1/10)\n# using Plots; pyplot; plot(sol)\n\n\n## Midpoint splitting convergence\n##\n## We use the inhomogeneous Lorentz equation for an electron in a\n## time-dependent field. To write this on matrix form and simplify\n## comparison with the analytic solution, we introduce two dummy\n## variables:\n## 1) As the third component, a one is stored to allow the\n##    inhomogeneous part to be expressed on matrix form.\n## 2) As the fourth component, the initial time t_i is stored,\n##    for use by the analytical formula.\n## This wastes a lot of space, but simplifies the error analysis.\n##\n## We can then write the Lorentz equation as q\u0307 = [A + f(t)B]q.\n\nf = t -> -sin(2pi*t)\nF = t -> cos(2pi*t)/2pi # Primitive function of f(t)\n\nA = DiffEqArrayOperator([0 1 0 0\n                         0 0 0 0\n                         0 0 0 0\n                         0 0 0 0])\n\nB = DiffEqArrayOperator([0 0 0 0\n                         0 0 1 0\n                         0 0 0 0\n                         0 0 0 0], f)\n\nH = AffineDiffEqOperator{Float64}((A,B),(),rand(4))\nfunction (p::typeof(H))(::Type{Val{:analytic}},u0,p,t)\n    x0,v0 = u0[1:2]\n    ti = u0[end]\n    x = x0 + (t-ti)*v0 - (f.(t)-f(ti))/(2pi)^2 - (t-ti)*F(ti)\n    v = v0 + (F.(t)-F(ti))\n    [x, v, 1, ti]\nend\n\nx0,v0,ti = rand(3)\nprob = ODEProblem(H, [x0, v0, 1, ti], (ti, 5.))\ndts = 1./2.^(10:-1:1)\nsim  = test_convergence(dts,prob,MidpointSplitting())\n@test abs(sim.\ud835\udcaaest[:l2]-2) < 0.2\n", "meta": {"hexsha": "b819541163f8c62ee0eafa7a464847802349195f", "size": 2315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/linear_method_tests.jl", "max_stars_repo_name": "feanor12/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "269794e622e9ded087a29bf8f671cfad29a32f50", "max_stars_repo_licenses": ["MIT"], "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/linear_method_tests.jl", "max_issues_repo_name": "feanor12/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "269794e622e9ded087a29bf8f671cfad29a32f50", "max_issues_repo_licenses": ["MIT"], "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/linear_method_tests.jl", "max_forks_repo_name": "feanor12/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "269794e622e9ded087a29bf8f671cfad29a32f50", "max_forks_repo_licenses": ["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.9375, "max_line_length": 66, "alphanum_fraction": 0.6034557235, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7862740507418088}}
{"text": "@testset \"Bitpattern entropy\" begin\n    for N in [100,1000,10000,100000]\n        # every bitpattern is only hit once, hence entropy = log2(N)\n        @test isapprox(log2(N),bitpattern_entropy(rand(Float32,N)),atol=1e-1)\n        @test isapprox(log2(N),bitpattern_entropy(rand(Float64,N)),atol=1e-1)\n    end\n\n    N = 1000_000   # more bitpattern than there are in 8 or 16-bit\n    @test isapprox(16.0,bitpattern_entropy(rand(UInt16,N)),atol=1e-1)\n    @test isapprox(16.0,bitpattern_entropy(rand(Int16,N)),atol=1e-1)\n\n    @test isapprox(8.0,bitpattern_entropy(rand(UInt8,N)),atol=1e-1)\n    @test isapprox(8.0,bitpattern_entropy(rand(Int8,N)),atol=1e-1)\nend\n\n@testset \"Bitcount\" begin\n    @test bitcount(UInt8[1,2,4,8,16,32,64,128]) == ones(8)\n    @test bitcount(collect(0x0000:0xffff)) == 2^15*ones(16)\n\n    N = 100_000\n    c = bitcount(rand(N))\n    @test c[1] == 0         # sign always 0\n    @test c[2] == 0         # first expbit always 0, i.e. U(0,1) < 1\n    @test c[3] == N         # second expont always 1\n\n    @test all(isapprox.(c[15:50],N/2,rtol=1e-1))\nend\n\n@testset \"Bitcountentropy\" begin\n\n    # test the PRNG on uniformity\n    N = 100_000\n    H = bitcount_entropy(rand(UInt8,N))\n    @test all(isapprox.(H,ones(8),rtol=5e-4))\n\n    H = bitcount_entropy(rand(UInt16,N))\n    @test all(isapprox.(H,ones(16),rtol=5e-4))\n\n    H = bitcount_entropy(rand(UInt32,N))\n    @test all(isapprox.(H,ones(32),rtol=5e-4))\n\n    H = bitcount_entropy(rand(UInt64,N))\n    @test all(isapprox.(H,ones(64),rtol=5e-4))\n\n    # also for random floats\n    H = bitcount_entropy(rand(N))\n    @test H[1:5] == zeros(5)    # first bits never change\n    @test all(isapprox.(H[16:55],ones(40),rtol=1e-4))\nend\n\n@testset \"Bitinformation random\" begin\n    N = 100_000\n    A = rand(UInt64,N)\n    @test all(bitinformation(A) .< 1e-3)\n\n    A = rand(Float32,N)\n    bi = bitinformation(A)\n    @test all(bi[1:4] .== 0.0) #\u00a0the first bits are always 0011\n    sort!(A)\n    @test sum(bitinformation(A)) > 12\nend\n\n@testset \"Bitinformation in chunks\" begin\n    N = 1000\n    Nhalf = N \u00f7 2\n    A = rand(UInt32,N)\n    n11,npair1,N1 = bitcount(A[1:Nhalf-1]),bitpaircount(A[1:Nhalf]),Nhalf\n    n12,npair2,N2 = bitcount(A[Nhalf:end-1]),bitpaircount(A[Nhalf:end]),Nhalf-1\n    @test bitinformation(n11+n12,npair1+npair2,N1+N2) == bitinformation(A)\nend\n\n@testset \"Bitinformation dimensions\" begin\n    A = rand(Float32,30,40,50)\n    @test bitinformation(A) == bitinformation(A,dims=1)\n    \n    # check that the :all_dimensions flag is \n    bi1 = bitinformation(A,dims=1)\n    bi2 = bitinformation(A,dims=2)\n    bi3 = bitinformation(A,dims=3)\n    @test bitinformation(A,:all_dimensions) == ((bi1 .+ bi2 .+ bi3)/3)\n\n    # check that there is indeed more information in the sorted dimensions\n    sort!(A,dims=2)\n    @test sum(bitinformation(A,dims=1)) < sum(bitinformation(A,dims=2))\nend\n\n@testset \"Mutual information\" begin\n    N = 10_000\n\n    # equal probabilities for 00|01|10|11\n    @test 0.0 == mutual_information([0.25 0.25;0.25 0.25])\n\n    # every 0 or 1 in A is also a 0 or 1 in B\n    @test 1.0 == mutual_information([0.5 0.0;0.0 0.5])\n\n    # as before but more 1s means a lower entropy\n    @test entropy([0.25,0.75],2) == mutual_information([0.25 0.0;0.0 0.75])\n\n    # every bit is inverted\n    @test 1.0 == mutual_information([0.0 0.5;0.5 0.0])\n\n    # two independent arrays\n    for T in [UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64]\n        mutinf = bitinformation(rand(T,N),rand(T,N))\n        for m in mutinf\n            @test isapprox(0,m,atol=1e-3)\n        end\n    end\n\n    # mutual information of identical arrays\n    # for 0,1 occuring exactly 50/50 this is 1bit\n    # but so in practice slightly lower for rand(UInt),\n    # or clearly lower for low entropy bits in Float16/32/64\n    # but identical to the bitcount_entropy (up to rounding errors)\n    for T in [UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64]\n        R = rand(T,N)\n        mutinf = bitinformation(R,R)\n        @test mutinf \u2248 bitcount_entropy(R)\n    end\nend\n\n@testset \"Redundancy\" begin\n    N = 100_000\n\n    # No redundancy in independent arrays\n    for T in [UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64]\n        redun = redundancy(rand(T,N),rand(T,N))\n        for r in redun\n            @test isapprox(0,r,atol=2e-3)\n        end\n    end\n\n    # Full redundancy in identical arrays\n    for T in [UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64]\n        A = rand(T,N)\n        H = bitcount_entropy(A)\n        R = redundancy(A,A)\n        for (r,h) in zip(R,H)\n            if iszero(h)\n                @test iszero(r)\n            else\n                @test isapprox(1,r,atol=2e-3)\n            end\n        end\n    end\nend\n\n@testset \"Mutual information with round to nearest\" begin\n    N = 100_000\n\n    # compare shaving to round to nearest\n    # for round to nearest take m more bits into account for the\n    # joint probability\n    m = 8\n\n    for T in [Float32,Float64]\n        R = rand(T,N)\n        for keepbit in [5,10,15]\n            mutinf_shave = bitinformation(R,shave(R,keepbit))\n            mutinf_round = bitinformation(R,round(R,keepbit),m)\n            for (s,r) in zip(mutinf_shave,mutinf_round)\n                @test isapprox(s,r,atol=1e-2)\n            end\n        end\n    end\n\n    # shaving shouldn't change\n    for T in [Float32,Float64]\n        R = rand(T,N)\n        for keepbit in [5,10,15]\n            mutinf_shave = bitinformation(R,shave(R,keepbit))\n            mutinf_round = bitinformation(R,shave(R,keepbit),m)\n            for (s,r) in zip(mutinf_shave,mutinf_round)\n                @test isapprox(s,r,atol=1e-2)\n            end\n        end\n    end\nend\n\n@testset \"Information of random set to zero\" begin\n    for T in (UInt32,UInt64,Float32,Float64)\n        for N in [10_000,100_000]\n            A = rand(T,N)\n            # increase confidence here from the default 0.99 to avoid test failures\n            # from false positives\n            b = bitinformation(A,confidence=0.9999)\n            for ib in b\n                @test 0 == ib\n            end\n\n            m = bitinformation(A[1:end-1],A[2:end],confidence=0.9999)\n            for im in m\n                @test 0 == im\n            end\n        end\n    end\nend", "meta": {"hexsha": "d3177bd7ec4310e17df720d741816a616d4a3ed9", "size": 6178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/information.jl", "max_stars_repo_name": "esowc/BitInformation.jl", "max_stars_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-16T20:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:36:23.000Z", "max_issues_repo_path": "test/information.jl", "max_issues_repo_name": "esowc/BitInformation.jl", "max_issues_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-04-13T16:06:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:39:57.000Z", "max_forks_repo_path": "test/information.jl", "max_forks_repo_name": "esowc/BitInformation.jl", "max_forks_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T03:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T03:28:55.000Z", "avg_line_length": 31.3604060914, "max_line_length": 83, "alphanum_fraction": 0.6123340887, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7862740491746955}}
{"text": "# basis functions\nlinear(x::Number) = vcat(1, x)\nlinear(x::AbstractArray{T, 1}) where {T} = hcat(linear.(x)...)'\n\ngaussian(x::Number, \u03bc, \u03c3=0.1) = vcat(1, exp.(-0.5*(x .- \u03bc).^2/\u03c3^2))\ngaussian(x::AbstractArray{T, 1}, \u03bc, \u03c3=0.1) where {T} = hcat(gaussian.(x, Ref(\u03bc), Ref(\u03c3))...)'\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, \u03d5X, \u03b1, \u03b2)\n\nCompute the posterior mean and variance given the observations Y,\nregressor matrix \u03d5X, prior precision \u03b1, and the additive noise precision \u03b2.\n\"\"\"\nfunction posterior(Y, \u03d5X, \u03b1, \u03b2)\n    \u03a3 = inv(\u03b1*I + \u03b2*\u03d5X'*\u03d5X)\n    \u03bc = \u03b2*\u03a3*\u03d5X'*Y\n    return \u03bc, \u03a3\nend\n\n\"\"\"\n    predict(\u03d5x, \u03bc, \u03a3, \u03b2)\n\nCompute the predictive distribution and standard deviation given the\nregressed test point \u03d5x, posterior mean \u03bc, posterior variance \u03a3, and\nthe additive noise precision \u03b2.\n\"\"\"\nfunction predict(\u03d5x, \u03bc, \u03a3, \u03b2)\n    \u03bcy = \u03bc'*\u03d5x\n    \u03a3y = 1/\u03b2 + \u03d5x'*\u03a3*\u03d5x\n    return \u03bcy, \u221a\u03a3y\nend\n\n\"\"\"\n    regress(Xo, Yo, Xt, Yt, \u03d5, \u03b1, \u03b2)\n\nPlot the point predictions given the observed data (Xo, Yo), test data (Xt, Yt),\nbasis functions \u03d5, prior precision \u03b1, and the additive noise precision \u03b2.\n\"\"\"\nfunction regress(Xo, Yo, Xt, Yt, \u03d5, \u03b1, \u03b2, \u03d5args...)\n    \u03bc, \u03a3 = posterior(Yo, \u03d5(Xo, \u03d5args...), \u03b1, \u03b2)\n\n    # predictions\n    Y\u03bc = similar(Xt); Y\u03c3 = similar(Xt)\n    for (i, xt) in enumerate(Xt)\n        y\u03bc, y\u03c3 = predict(\u03d5(xt, \u03d5args...), \u03bc, \u03a3, \u03b2)\n        Y\u03bc[i] = y\u03bc; Y\u03c3[i] = y\u03c3\n    end\n\n    Prediction1D(Xo, Yo, Xt, Yt, Y\u03bc, Y\u03c3)\nend\n\nstruct Prediction1D{T}\n    Xo::T\n    Yo::T\n    Xt::T\n    Yt::T\n    \u03bc::T\n    \u03c3::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.\u03c3\n        (p.Xt, p.\u03bc)\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, \u03b1=2.0, \u03b2=25.0; seeded=false)\n    f(x, \u03b2=Inf) = -0.3 + 0.5*x + 1/\u03b2*randn()\n    if seeded\n        seed!(1729)\n    end\n    Xo = 2.0*rand(N) .- 1.0\n    Yo = f.(Xo, \u03b2)\n    Xt = collect(-1.0:0.01:1.0)\n    Yt = f.(Xt)\n    regress(Xo, Yo, Xt, Yt, linear, \u03b1, \u03b2)\nend\n\nfunction gaussfit(N, \u03b1=1.0, \u03b2=25.0, \u03bc=0:0.1:3; seeded=false)\n    f(x, \u03b2=Inf) = 0.5 + x*sin(2*\u03c0*x) + 1/\u03b2*randn()\n    if seeded\n        seed!(1729)\n    end\n    Xo = rand(N)*3.0\n    Yo = f.(Xo, \u03b2)\n    Xt = collect(0.0:0.01:3.0)\n    Yt = f.(Xt)\n    regress(Xo, Yo, Xt, Yt, gaussian, \u03b1, \u03b2, \u03bc)\nend\n\nfunction polyfit(N, \u03b1=0.005, \u03b2=1/(0.3^2), r=0:5; seeded=false)\n    f(x, \u03b2=Inf) = 0.5 + sin(2*\u03c0*x) + 1/\u03b2*randn()\n    if seeded\n        seed!(1729)\n    end\n    Xo = rand(N)\n    Yo = f.(Xo, \u03b2)\n    Xt = collect(0.0:0.005:1.0)\n    Yt = f.(Xt)\n    regress(Xo, Yo, Xt, Yt, polynomial, \u03b1, \u03b2, 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    \u03c3(x) = 1 / (1 + exp(-x))\n\nClassic [sigmoid](https://en.wikipedia.org/wiki/Sigmoid_function) activation\nfunction.\n\"\"\"\n\u03c3(x) = one(x) / (one(x) + exp(-x))\n\nconst sigmoid = \u03c3\n\n# ForwardDiff numerical stability hack\n\u03c3_stable(x) = ifelse(x < -80, zero(x), one(x) / (one(x) + exp(-x)))\n\n\u03c3(x::Float32) = \u03c3_stable(x)\n\n@require ForwardDiff begin\n  import ForwardDiff: Dual\n  \u03c3(x::Dual{T,Float32}) where T = \u03c3_stable(x)\nend\n\n\"\"\"\n    log\u03c3(x)\n\nReturn `log(\u03c3(x))` which is computed in a numerically stable way.\n\n    julia> log\u03c3(0.)\n    -0.6931471805599453\n    julia> log\u03c3.([-100, -10, 100.])\n    3-element Array{Float64,1}:\n     -100.0\n      -10.0\n       -0.0\n\"\"\"\nfunction log\u03c3(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\u03c3\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, \u03b1 = 1) =\n      x > 0 ? x : \u03b1 * (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, \u03b1 = one(x)) = ifelse(x \u2265 0, x/1, \u03b1 * (exp(x) - one(x)))\n\n\"\"\"\n    swish(x) = x * \u03c3(x)\n\nSelf-gated actvation function.\nSee [Swish: a Self-Gated Activation Function](https://arxiv.org/pdf/1710.05941.pdf).\n\"\"\"\nswish(x) = x * \u03c3(x)\n\n\"\"\"\n    selu(x) = \u03bb * (x \u2265 0 ? x : \u03b1 * (exp(x) - 1))\n\n    \u03bb \u2248 1.0507\n    \u03b1 \u2248 1.6733\n\nScaled exponential linear units.\nSee [Self-Normalizing Neural Networks](https://arxiv.org/pdf/1706.02515.pdf).\n\"\"\"\nfunction selu(x)\n  \u03bb = oftype(x/1, 1.0507009873554804934193349852946)\n  \u03b1 = oftype(x/1, 1.6732632423543772848170429916717)\n  \u03bb * ifelse(x > 0, x/1, \u03b1 * (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  \u03c6: xrange x yrange --> \u211d\u00b2,\n    # \u03c6(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 \u2208 [-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 \u2248 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 \u2248 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\u00d73 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(\u03b1)\r\n\r\nSimulate left-handed rotation about the x-axis.\r\n\r\n# Arguments\r\n- `\u03b1::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3\u00d73 matrix that describes rotation about the x-axis by angle `\u03b1`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatex(\u03c0/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(\u03b1::Real)\r\n\r\n    return [1 0 0; 0 cos(\u03b1) sin(\u03b1); 0 -sin(\u03b1) cos(\u03b1)]\r\n\r\nend\r\n\r\n\"\"\"\r\n    rotatey(\u03b1)\r\n\r\nSimulate left-handed rotation about the y-axis.\r\n\r\n# Arguments\r\n- `\u03b1::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3\u00d73 matrix that describes rotation about the y-axis by angle `\u03b1`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatey(\u03c0/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(\u03b1::Real)\r\n\r\n    return [cos(\u03b1) 0 -sin(\u03b1); 0 1 0; sin(\u03b1) 0 cos(\u03b1)]\r\n\r\nend\r\n\r\n\"\"\"\r\n    rotatez(\u03d5)\r\n\r\nSimulate left-handed rotation about the z-axis.\r\n\r\n# Arguments\r\n- `\u03d5::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3\u00d73 matrix that describes rotation about the z-axis by angle `\u03d5`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatez(\u03c0/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(\u03d5::Real)\r\n\r\n    return [cos(\u03d5) sin(\u03d5) 0; -sin(\u03d5) cos(\u03d5) 0; 0 0 1]\r\n\r\nend\r\n\r\n\"\"\"\r\n    rotatetheta(\u03b8, \u03b1)\r\n\r\nSimulate left-handed rotation about an axis in the x-y plane that makes angle\r\n`\u03b8` with the negative y-axis.\r\n\r\n# Arguments\r\n- `\u03b8::Real`: Orientation of the axis about which to rotate (rad)\r\n- `\u03b1::Real`: Rotation angle (rad)\r\n\r\n# Return\r\n- `R::Matrix`: 3\u00d73 matrix that describes rotation by angle `\u03b1` about an axis in\r\n    the x-y plane that makes angle `\u03b8` with the negative y-axis\r\n\r\n## Note\r\n`rotatetheta(\u03b8, \u03b1) == rotatez(\u03b8) * rotatey(-\u03b1) * rotatez(-\u03b8)`\r\n\r\n# Examples\r\n```jldoctest\r\njulia> R = rotatetheta(\u03c0/4, \u03c0/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(\u03b8::Real, \u03b1::Real)\r\n\r\n    return [ sin(\u03b8)^2+cos(\u03b1)*cos(\u03b8)^2           sin(\u03b8)*cos(\u03b8)-cos(\u03b1)*sin(\u03b8)*cos(\u03b8)  sin(\u03b1)*cos(\u03b8);\r\n             sin(\u03b8)*cos(\u03b8)-cos(\u03b1)*sin(\u03b8)*cos(\u03b8) cos(\u03b8)^2+cos(\u03b1)*sin(\u03b8)^2           -sin(\u03b1)*sin(\u03b8);\r\n            -sin(\u03b1)*cos(\u03b8)                      sin(\u03b1)*sin(\u03b8)                       cos(\u03b1)]\r\n\r\nend\r\n\r\n\"\"\"\r\n    freeprecess(t, M0, T1, T2, \u0394f)\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- `\u0394f::Real`: Off-resonance frequency (Hz)\r\n\r\n# Return\r\n- `A::Matrix`: 3\u00d73 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, \u0394f::Real)\r\n\r\n    (A, B) = relax(t, M0, T1, T2)\r\n    C = rotatez(2\u03c0 * \u0394f * 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": "### General constraint Jacobians match known solutions\npI = 6\nn = 3\nm = 3\n\nfunction cI(cdot,x,u)\n    cdot[1] = x[1]^3 + u[1]^2\n    cdot[2] = x[2]*u[2]\n    cdot[3] = x[3]\n    cdot[4] = u[1]^2\n    cdot[5] = u[2]^3\n    cdot[6] = u[3]\nend\n\nc_jac = TrajectoryOptimization.generate_general_constraint_jacobian(cI,pI,n,m)\n\nx = [1;2;3]\nu = [4;5;6]\n\nA = zeros(6,3)\nB = zeros(6,3)\n\n# cx, cu = c_jac(x,u)\nc_jac(A,B,x,u)\ncx_known = [3 0 0; 0 5 0; 0 0 1; 0 0 0; 0 0 0; 0 0 0]\ncu_known = [8 0 0; 0 2 0; 0 0 0; 8 0 0; 0 75 0; 0 0 1]\n\n@test all(A .== cx_known)\n@test all(B .== cu_known)\n###\n\n# ### Custom equality constraint on quadrotor quaternion state: sqrt(q1^2 + q2^2 + q3^2 + q4^2) == 1\n# opts = TrajectoryOptimization.SolverOptions()\n# opts.verbose = false\n# opts.constraint_tolerance = 1e-3\n# opts.cost_tolerance_intermediate = 1e-3\n# opts.cost_tolerance = 1e-3\n# ######################\n#\n# ### Set up model, objective, solver ###\n# # Model\n# n = 13 # states (quadrotor w/ quaternions)\n# m = 4 # controls\n# dt = 0.05\n# model, obj_uncon = TrajectoryOptimization.Dynamics.quadrotor\n#\n# # -control limits\n# u_min = -50.0\n# u_max = 50.0\n#\n# # -constraint that quaternion should be unit\n# function cE(cdot,x,u)\n#     cdot[1] = sqrt(x[4]^2 + x[5]^2 + x[6]^2 + x[7]^2) - 1.0\n# end\n#\n# obj_con = TrajectoryOptimization.ConstrainedObjective(obj_uncon, u_min=u_min, u_max=u_max, cE=cE)#,cI=cI)\n# # Solver\n# # - Initial control and state trajectories\n# solver = TrajectoryOptimization.Solver(model,obj_con,integration=:rk4,dt=dt,opts=opts)\n# U = 10.0*ones(solver.model.m, solver.N)\n#\n# ##################\n#\n# ### Solve ###\n# results, stats = TrajectoryOptimization.solve(solver,U)\n# #############\n# @test stats[\"c_max\"][end] < opts.constraint_tolerance\n", "meta": {"hexsha": "5ef7e709a56508aad24bc612132e7fc30da15877", "size": 1734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/jacobian_tests.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": "test/jacobian_tests.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": "test/jacobian_tests.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": 25.5, "max_line_length": 107, "alphanum_fraction": 0.6199538639, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7862303197629479}}
{"text": "using LinearAlgebra: I, diagm, norm, tr\nusing Unitful: @u_str\n\n# Example from https://www.continuummechanics.org/hydrodeviatoricstrain.html\n@testset \"Test `hydrostatic` and `deviatoric`\" begin\n    E = TensorStrain([\n        0.5 0.3 0.2\n        0.3 -0.2 -0.1\n        0.2 -0.1 0.1\n    ])\n    @test hydrostatic(E) == TensorStrain(diagm(0 => [2, 2, 2] / 15))\n    @test deviatoric(E) == TensorStrain(E - diagm(0 => [2, 2, 2] / 15))\n    @test TensorStrain(hydrostatic(E) + deviatoric(E)) \u2248 E\nend\n\n@testset \"Test unitary transformation\" begin\n    E = TensorStrain([\n        0.5 0.3 0.2\n        0.3 -0.2 -0.1\n        0.2 -0.1 0.1\n    ])\n    evecs = principal_axes(E)\n    @test transpose(evecs) * evecs \u2248 evecs * transpose(evecs) \u2248 I\n    normal_strains = transpose(evecs) * E * evecs\n    @test norm(normal_strains - [\n        -0.370577 0 0\n        0 0.115308 0\n        0 0 0.655269\n    ]) < 1e-6\n    @test isapprox(principal_values(E), [-0.370577, 0.115308, 0.655269]; atol = 1e-6)\n    @test tr(normal_strains) \u2248 tr(E) \u2248 2 / 5\nend\n\n# Example from https://www.continuummechanics.org/principalstrain.html\n@testset \"Test principal invariants\" begin\n    E = TensorStrain([\n        0.5 0.3 0.2\n        0.3 -0.2 -0.1\n        0.2 -0.1 0.1\n    ])\n    @test length(principal_invariants(E)) == 3\n    @test principal_invariants(E)[1] == 0.4\n    @test principal_invariants(E)[2] \u2248 -0.21\n    @test principal_invariants(E)[3] == -0.028\nend\n\n@testset \"Tests from homework 1\" begin\n    \u03c3 = TensorStress([\n        300 100 0\n        100 100 0\n        0 0 0\n    ] * u\"MPa\")\n    @test length(principal_invariants(\u03c3)) == 3\n    @test principal_invariants(\u03c3) == (400u\"MPa\", 2e4u\"MPa^2\", 0u\"MPa^3\")\n    @test maximum(principal_values(\u03c3)) \u2248 (200 + 100 * sqrt(2))u\"MPa\"\n    @test sort(principal_values(\u03c3))[2] \u2248 (200 - 100 * sqrt(2))u\"MPa\"\n    @test hydrostatic(\u03c3) == TensorStress(diagm(0 => [400, 400, 400] * u\"MPa\" / 3))\n    @test hydrostatic(\u03c3) + deviatoric(\u03c3) == \u03c3\nend\n\n@testset \"Tests from homework 2\" begin\n    \u03c3\u2082\u2082 = Int64(200)u\"MPa\"\n    \u03c3\u2081\u2082 = \u03c3\u2082\u2083 = Int64(141)u\"MPa\"\n    \u03c3 = TensorStress(\n        [\n            Int64(0)u\"MPa\" \u03c3\u2081\u2082 Int64(0)u\"MPa\"\n            \u03c3\u2081\u2082 \u03c3\u2082\u2082 \u03c3\u2082\u2083\n            Int64(0)u\"MPa\" \u03c3\u2082\u2083 Int64(0)u\"MPa\"\n        ],\n    )\n    @test minimum(principal_values(\u03c3)) \u2248 -123.07397876041034u\"MPa\"\n    @test isapprox(sort(principal_values(\u03c3))[2], 0u\"MPa\"; atol = 1e-12u\"MPa\")\n    @test maximum(principal_values(\u03c3)) == 323.07397876041034u\"MPa\"\n    @test norm(\n        principal_axes(\u03c3) - Float64[\n            0.601723 0.707107 0.371389\n            -0.525223 0 0.850965\n            0.601723 -0.707107 0.371389\n        ],\n    ) < 1e-6\nend\n", "meta": {"hexsha": "fb08b5c77aa7f0175b56862b555440b42208f478", "size": 2607, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/invariants.jl", "max_stars_repo_name": "singularitti/LinearElasticity.jl", "max_stars_repo_head_hexsha": "4a7521c849728a69133e2d4ea5bbbdfd52988515", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-01T10:40:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T10:40:00.000Z", "max_issues_repo_path": "test/invariants.jl", "max_issues_repo_name": "MineralsCloud/LinearElasticity.jl", "max_issues_repo_head_hexsha": "351d7df008063d9445193cc1038840ac64c9b8bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-08-10T00:12:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T00:30:44.000Z", "max_forks_repo_path": "test/invariants.jl", "max_forks_repo_name": "MineralsCloud/LinearElasticity.jl", "max_forks_repo_head_hexsha": "351d7df008063d9445193cc1038840ac64c9b8bf", "max_forks_repo_licenses": ["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.7926829268, "max_line_length": 85, "alphanum_fraction": 0.5872650556, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7862303156229775}}
{"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\u03c9 = trap_weights(x)\nf(x) = x^2\ndot(f.(x), \u03c9)\n\nstruct UniformTrapezoidal\n    count::Int\n    \u0394::Float64\nend\n\nBase.iterate(S::UniformTrapezoidal, state=1) = state > S.count ? nothing : (if state == 1 || state == count; \u0394*0.5 else \u0394*1.0 end, state+1)\n\nfunction integration(f, x::AbstractArray; count = 10)\n    \u0394 = step(x)\n    int = similar(x)\n    for (i,value) in enumerate(UniformTrapezoidal(count,\u0394))\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 \u0394 = 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 \u03be \u2208  [-1, 1]\n\nParameters\n----------\nn :: Int\n    order of polynomial\n\nReturns\n-------\nfunction\n    Legendgre polynomial of order n in interval \u03be \u2208 [-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 \u03be \u2208  [-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 \u03be \u2208 [1, 1].\n\nParameters\n----------\nn :: Int\n    order of polynomial\n\nReturns\n-------\nfunction\n    Legendgre polynomial of order n in interval \u03be \u2208 [-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 \u03be \u2208  [-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": "using Base.Test\nusing Quaternions\n\nqx = qrotation([1,0,0], pi/4)\n@test_approx_eq qx*qx qrotation([1,0,0], pi/2)\n@test_approx_eq qx^2 qrotation([1,0,0], pi/2)\ntheta = pi/8\nqx = qrotation([1,0,0], theta)\nc = cos(theta); s = sin(theta)\nRx = [1 0 0; 0 c -s; 0 s c]\n@test_approx_eq rotationmatrix(qx) Rx\ntheta = pi/6\nqy = qrotation([0,1,0], theta)\nc = cos(theta); s = sin(theta)\nRy = [c 0 s; 0 1 0; -s 0 c]\n@test_approx_eq rotationmatrix(qy) Ry\ntheta = 4pi/3\nqz = qrotation([0,0,1], theta)\nc = cos(theta); s = sin(theta)\nRz = [c -s 0; s c 0; 0 0 1]\n@test_approx_eq rotationmatrix(qz) Rz\n\n@test_approx_eq rotationmatrix(qx*qy*qz) Rx*Ry*Rz\n@test_approx_eq rotationmatrix(qy*qx*qz) Ry*Rx*Rz\n@test_approx_eq rotationmatrix(qz*qx*qy) Rz*Rx*Ry\n\na, b = qrotation([0,0,1], deg2rad(0)), qrotation([0,0,1], deg2rad(180))\n@test_approx_eq slerp(a,b,0.0) a\n@test_approx_eq slerp(a,b,1.0) b\n@test_approx_eq slerp(a,b,0.5) qrotation([0,0,1], deg2rad(90))\n\n@test_approx_eq angle(qrotation([1,0,0], 0)) 0\n@test_approx_eq angle(qrotation([0,1,0], pi/4)) pi/4\n@test_approx_eq angle(qrotation([0,0,1], pi/2)) pi/2\n", "meta": {"hexsha": "f8f24e31cd010ef65ba1b518a4ccc46c855cde80", "size": 1089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaPackageMirrors/Quaternions.jl", "max_stars_repo_head_hexsha": "ac488e96c852e1c4cb4ae69abb12d7e12aeab154", "max_stars_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Quaternions.jl", "max_issues_repo_head_hexsha": "ac488e96c852e1c4cb4ae69abb12d7e12aeab154", "max_issues_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Quaternions.jl", "max_forks_repo_head_hexsha": "ac488e96c852e1c4cb4ae69abb12d7e12aeab154", "max_forks_repo_licenses": ["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.1142857143, "max_line_length": 71, "alphanum_fraction": 0.6786042241, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7861147417761296}}
{"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\u2081*X'+ c\u2082*Y'  \u27f9 c\u2081 * [1,1] + c\u2082 * [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\u2081*X'+ c\u2082*Y'  \u27f9 c\u2081 * [1,1] + c\u2082 * [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": "using MultipleViewGeometry, Test, LinearAlgebra\nusing MultipleViewGeometry.ModuleTypes\nusing StaticArrays, Calculus, GeometryTypes\nusing MultipleViewGeometry.ModuleMove\n\n# Tests for fundamental matrix estimation\n\n\ud835\udcb3 = [Point3D(x,y,rand(50:100)) for x = -100:5:100 for y = -100:5:100]\n\ud835\udcb3 = \ud835\udcb3[1:50:end]\n\n\n# Specify the coordinate systems of the world, the camera frame and the picture\n# plane.\nworld_basis = (Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0), Vec(0.0, 0.0, 1.0))\ncamera_basis = (Point(0.0, 0.0, 0.0), Vec(-1.0, 0.0, 0.0), Vec(0.0, -1.0, 0.0), Vec(0.0, 0.0, 1.0))\npicture_basis = (Point(0.0, 0.0), Vec(-1.0, 0.0), Vec(0.0, -1.0))\n\n# The focal length for both cameras is one.\nf = 1\nimage_width = 640 / 10\nimage_height = 480 / 10\n\ncamera\u2081 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\ncamera\u2082 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\n\n# Rotate and translate camera one.\n\ud835\udc11\u2081 = Matrix{Float64}(I,3,3)\n\ud835\udc2d\u2081 = [-50.0, -2.0, 0.0]\nrelocate!(camera\u2081, \ud835\udc11\u2081, \ud835\udc2d\u2081)\n\n# Rotate and translate camera two.\n\ud835\udc11\u2082 = Matrix{Float64}(I,3,3)\n\ud835\udc2d\u2082 = [50.0, 2.0, 0.0]\nrelocate!(camera\u2082, \ud835\udc11\u2082, \ud835\udc2d\u2082)\n\n\n\ud835\udc11\u2081\u2032, \ud835\udc2d\u2081\u2032 = ascertain_pose(camera\u2081, world_basis... )\n\ud835\udc0a\u2081\u2032 = obtain_intrinsics(camera\u2081, CartesianSystem())\n\ud835\udc11\u2082\u2032, \ud835\udc2d\u2082\u2032 = ascertain_pose(camera\u2082, world_basis... )\n\ud835\udc0a\u2082\u2032 = obtain_intrinsics(camera\u2082, CartesianSystem())\n\n# Camera projection matrices.\n\ud835\udc0f\u2081 = construct(ProjectionMatrix(),\ud835\udc0a\u2081\u2032,\ud835\udc11\u2081\u2032,\ud835\udc2d\u2081\u2032)\n\ud835\udc0f\u2082 = construct(ProjectionMatrix(),\ud835\udc0a\u2082\u2032,\ud835\udc11\u2082\u2032,\ud835\udc2d\u2082\u2032)\n\n\n# Set of corresponding points.\n\u2133 = project(camera\u2081,\ud835\udc0f\u2081,\ud835\udcb3)\n\u2133\u02b9 = project(camera\u2082,\ud835\udc0f\u2082,\ud835\udcb3)\n\n# Estimate of the fundamental matrix and the true fundamental matrix.\n\ud835\udc05 = estimate(FundamentalMatrix(), DirectLinearTransform(), (\u2133, \u2133\u02b9))\n\n#\ud835\udc05\u209c = construct(FundamentalMatrix(), \ud835\udc0f\u2081, \ud835\udc0f\u2082)\n\ud835\udc05\u209c = construct(FundamentalMatrix(), \ud835\udc0a\u2081\u2032,\ud835\udc11\u2081\u2032,-\ud835\udc2d\u2081\u2032,\ud835\udc0a\u2082\u2032,\ud835\udc11\u2082\u2032,-\ud835\udc2d\u2082\u2032)\n\n# Ensure the estimated and true matrix have the same scale and sign.\n\ud835\udc05 = \ud835\udc05 / norm(\ud835\udc05)\n\ud835\udc05 = \ud835\udc05 / sign(\ud835\udc05[3,1])\n\ud835\udc05\u209c = \ud835\udc05\u209c / norm(\ud835\udc05\u209c)\n\ud835\udc05\u209c = \ud835\udc05\u209c / sign(\ud835\udc05\u209c[3,1])\n\n@test \ud835\udc05 \u2248 \ud835\udc05\u209c\n\n# Check that the fundamental matrix satisfies the corresponding point equation.\nnpts = length(\u2133)\nresidual = zeros(Float64,npts,1)\nfor correspondence in zip(1:length(\u2133),\u2133, \u2133\u02b9)\n    i, m , m\u02b9 = correspondence\n    \ud835\udc26  = hom(m)\n    \ud835\udc26\u02b9 = hom(m\u02b9)\n    residual[i] = (\ud835\udc26\u02b9'*\ud835\udc05*\ud835\udc26)\nend\n\n@test isapprox(sum(residual), 0.0; atol = 1e-7)\n\n\n# Test the Fundamental Numerical Scheme on the Fundamental matrix problem.\n\u039b\u2081 =  [SMatrix{3,3}(Matrix(Diagonal([1.0,1.0,0.0]))) for i = 1:length(\u2133)]\n\u039b\u2082 =  [SMatrix{3,3}(Matrix(Diagonal([1.0,1.0,0.0]))) for i = 1:length(\u2133)]\n\ud835\udc05\u2080 = estimate(FundamentalMatrix(),DirectLinearTransform(),  (\u2133, \u2133\u02b9))\n\ud835\udc05 = estimate(FundamentalMatrix(),\n              FundamentalNumericalScheme(vec(\ud835\udc05\u2080), 5, 1e-10),\n               (\u039b\u2081,\u039b\u2082), (\u2133, \u2133\u02b9))\n\n\n# Ensure the estimated and true matrix have the same scale and sign.\n\ud835\udc05 = \ud835\udc05 / norm(\ud835\udc05)\n\ud835\udc05 = \ud835\udc05 / sign(\ud835\udc05[3,1])\n\n@test \ud835\udc05 \u2248 \ud835\udc05\u209c\n\n# Test the Bundle Adjustment estimator on the Fundamental matrix problem.\n\ud835\udc05, lsqFit = estimate(FundamentalMatrix(),\n                      BundleAdjustment(vec(\ud835\udc05\u2080), 5, 1e-10),\n                        (\u2133, \u2133\u02b9))\n\ud835\udc05 = \ud835\udc05 / norm(\ud835\udc05)\n\ud835\udc05 = \ud835\udc05 / sign(\ud835\udc05[3,1])\n@test \ud835\udc05 \u2248 \ud835\udc05\u209c\n", "meta": {"hexsha": "67efe71cc6f6161259e7a843917ef585a74f53c2", "size": 3081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/estimate_fundamental_tests.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": "test/estimate_fundamental_tests.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": "test/estimate_fundamental_tests.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": 30.81, "max_line_length": 99, "alphanum_fraction": 0.6669912366, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7861147274069819}}
{"text": "d1 = float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])\nd2 = sparse(float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]))\n\ny = dijkstra_shortest_paths(g4, 2, d1)\nz = dijkstra_shortest_paths(g4, 2, d2)\n\n@test y.parents == z.parents == [0, 0, 2, 3, 4]\n@test y.dists == z.dists == [Inf, 0, 6, 17, 33]\n\ny = dijkstra_shortest_paths(g4, 2, d1; allpaths=true)\nz = dijkstra_shortest_paths(g4, 2, d2; allpaths=true)\n@test z.predecessors[3] == y.predecessors[3] == [2]\n\n@test enumerate_paths(z) == enumerate_paths(y)\n@test enumerate_paths(z)[4] ==\n    enumerate_paths(z,4) ==\n    enumerate_paths(y,4) == [2,3,4]\n\ng = PathGraph(5)\nadd_edge!(g,2,4)\nd = ones(Int, 5,5)\nd[2,3] = 100\nz = dijkstra_shortest_paths(g,1,d)\n@test z.dists == [0, 1, 3, 2, 3]\n@test z.parents == [0, 1, 4, 2, 4]\n", "meta": {"hexsha": "78dafce1e75e8e39da4a23b84f1d6a23562a2697", "size": 818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/shortestpaths/dijkstra.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": "test/shortestpaths/dijkstra.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": "test/shortestpaths/dijkstra.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": 31.4615384615, "max_line_length": 87, "alphanum_fraction": 0.6185819071, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7860986183983367}}
{"text": "\nusing Test\nimport Vol\nimport LinearAlgebra, DelimitedFiles\n\nreturn_series = 0.01 * collect(1:50)\nlambda = 0.94\n\n@test isapprox(Vol.ewma(return_series, lambda), sqrt(Vol.ewma_canonical(return_series.^2, lambda)))\n@test isapprox(Vol.ewma(0.01 * ones(100), lambda), 0.01)\n\nr = [ 1. 2. 3.;\n      3. 4. 5.;\n      5. 6. 7.;\n      10. 20. 30.]\n\n@test LinearAlgebra.issymmetric(Vol.ewma(r, lambda))\n@test LinearAlgebra.issymmetric(Vol.ewma_cov(r, lambda))\n\n# the diagonal of the correlation matrix should be ones.\n@test isapprox(LinearAlgebra.diag(Vol.ewma(r, lambda)), ones(3))\n\nsingle_serie = [1.0, 3.0, 10.0]\nsingle_discrete_returns = zeros(2)\nsingle_discrete_returns[1] = (3.0-1.0)/1.0\nsingle_discrete_returns[2] = (10.0-3.0)/3.0\n@test isapprox(Vol.discrete_returns(single_serie), single_discrete_returns)\n\nsingle_log_returns = zeros(2)\nsingle_log_returns[1] = log(3.0) - log(1.0)\nsingle_log_returns[2] = log(10.0) - log(3.0)\n@test isapprox(Vol.log_returns(single_serie), single_log_returns)\n\ntwo_series = [ 1.0 10.0;\n               3.0 5.0;\n               2.0 15.0]\n\ntwo_discrete_returns=zeros(2,2)\ntwo_discrete_returns[1,1] = (3.0-1.0)/1.0\ntwo_discrete_returns[2,1] = (2.0-3.0)/3.0\ntwo_discrete_returns[1,2] = (5.0-10.0)/10.0\ntwo_discrete_returns[2,2] = (15.0-5.0)/5.0\n@test isapprox(Vol.discrete_returns(two_series), two_discrete_returns)\n\ntwo_log_returns=zeros(2,2)\ntwo_log_returns[1,1] = log(3.0) - log(1.0)\ntwo_log_returns[2,1] = log(2.0) - log(3.0)\ntwo_log_returns[1,2] = log(5.0) - log(10.0)\ntwo_log_returns[2,2] = log(15.0) - log(5.0)\n@test isapprox(Vol.log_returns(two_series), two_log_returns)\n\n@test isapprox(Vol.discrete_returns(r)[1:end, 1], Vol.discrete_returns(r[1:end, 1]))\n@test isapprox(Vol.log_returns(r)[1:end, 1], Vol.log_returns(r[1:end, 1]))\n\nsingle_return = [0.05, 0.01, 0.10, -0.02, -0.10, 0.0]\nlambda = 0.94\newma_canonical_single_return = (0.0 * 1 + (-0.10)*lambda + (-0.02)*(lambda^2) + 0.10*(lambda^3) + 0.01*(lambda^4) + 0.05*(lambda^5)) / (1 + lambda + lambda^2 + lambda^3 + lambda^4 + lambda^5)\n@test isapprox(Vol.ewma_canonical(single_return, lambda), ewma_canonical_single_return)\n\newma_single_return = sqrt( ((0.0^2) * 1 + ((-0.10)^2)*lambda + ((-0.02)^2)*(lambda^2) + (0.10^2)*(lambda^3) + (0.01^2)*(lambda^4) + (0.05^2)*(lambda^5)) / (1 + lambda + lambda^2 + lambda^3 + lambda^4 + lambda^5))\n@test isapprox(Vol.ewma(single_return, lambda), ewma_single_return)\n\n# tests cov -> correl\nthree_returns = [ 0.1 0.3 0.2 ;\n                  0.02 0.03 0.0;\n                  0.3  0.3  0.3;\n                  0.2  0.0  0.1]\n\nlambda = 0.94\n\ncovmatrix = Vol.ewma_cov(three_returns, lambda)\nvol_array = Vector{Float64}()\nfor i in 1:3\n    push!(vol_array, Vol.ewma(three_returns[:, i], lambda))\nend\n\ncorrmatrix = Vol.ewma(three_returns, lambda)\nfor i in 1:3\n    for j in 1:3\n        @test isapprox(corrmatrix[i,j], covmatrix[i,j]/(vol_array[i]*vol_array[j]))\n    end\nend\n\n# Diagonal of the covmatrix should be squared volatilities\n@test isapprox(sqrt.(LinearAlgebra.diag(covmatrix)), [Vol.ewma(three_returns[:,i], lambda) for i in 1:3 ])\n\n# market prices\nlambda = 0.94\n(raw_data, table_header) = DelimitedFiles.readdlm(\"prices.csv\", ',', header=true)\nprices = raw_data[:, 4:end]\n(rows, cols) = size(prices)\nreturns = Vol.log_returns(prices)\ncovmatrix = Vol.ewma_cov(returns, lambda)\ncorrmatrix = Vol.ewma(returns, lambda)\n\n@test LinearAlgebra.issymmetric(covmatrix)\n@test LinearAlgebra.issymmetric(corrmatrix)\n@test isapprox(sqrt.(LinearAlgebra.diag(covmatrix)), [Vol.ewma(returns[:,i], lambda) for i in 1:cols ])\n@test isapprox(LinearAlgebra.diag(corrmatrix), ones(cols))\n", "meta": {"hexsha": "16eb5d223215d595f2aa325b001351f1d60906f2", "size": 3593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "felipenoris/Vol.jl", "max_stars_repo_head_hexsha": "6666fda9c36668176c0ec0780ed6f5fbf8a438fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-29T23:55:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-29T23:55:20.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "felipenoris/Vol.jl", "max_issues_repo_head_hexsha": "6666fda9c36668176c0ec0780ed6f5fbf8a438fa", "max_issues_repo_licenses": ["MIT"], "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": "felipenoris/Vol.jl", "max_forks_repo_head_hexsha": "6666fda9c36668176c0ec0780ed6f5fbf8a438fa", "max_forks_repo_licenses": ["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": 212, "alphanum_fraction": 0.6832730309, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.786098614295522}}
{"text": "#--------------------------------------------------------------------\n# Spacetime Discretization methods in Julia\n# Soham 01-2018\n#--------------------------------------------------------------------\n\nfunction testchebx(N::Int)\n\tx  = chebx(5, N)\n\tTx = cos(N*acos(x))\n\treturn abs(Tx)\nend\n\nfunction testchebd(N::Int)\n\tDR = Float64[chebd(fld(N, 3), j, N) for j in 1:N+1]\n\treturn sum(DR)\nend\n\nfunction testchebdpoly(N::Int)::Float64\n    x     = chebgrid(N)\n    fx    = x.^5\n    edfx  = 5.*x.^4\n    chebD = Float64[chebd(i,j,N) for i in 1:N+1, j in 1:N+1]\n    ndfx  = chebD*fx\n    return maximum(abs.(ndfx - edfx))\nend\n\nfunction testchebw(N::Int)\n\tw = Float64[chebw(i, N) for i in 1:N+1]\n\treturn sum(w)\nend\n\n@test chebx(3, 10) \u2248 0.8090169943749475\n@test chebw(9, 12) \u2248 0.2258075258075258\n@test vandermonde(10)[2,5] == cheb(4, chebx(2,10))\n@test pseudovandermonde(10, chebgrid(14))[3,7] == cheb(6, chebx(3,14)) \n@test chebgrid(23)[7] == chebx(7,23)\n@test chebweights(12)[8] == chebw(8,12)\n\n@test testchebx(rand(10:20)) \u2248 1.0\n@test testchebd(rand(10:20)) < 1e-14\n@test testchebw(rand(2:20)) \u2248 2.0\n@test chebgrid(4, 2, 1) == (chebgrid(4) + 1)/2\n@test chebgrid(4, 2, 2) == (chebgrid(4) - 1)/2\n@test chebgrid(2, 2, 1)[end] == chebgrid(2, 2, 2)[1]\n@test testchebdpoly(10) < 1e-13\n", "meta": {"hexsha": "d27add4352c812f85fe83dc5dfb2e425c8ecadc1", "size": 1269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SpecCalculusTest.jl", "max_stars_repo_name": "mukherjeesoham/ScalarWave.jl", "max_stars_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_stars_repo_licenses": ["MIT"], "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/SpecCalculusTest.jl", "max_issues_repo_name": "mukherjeesoham/ScalarWave.jl", "max_issues_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_issues_repo_licenses": ["MIT"], "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/SpecCalculusTest.jl", "max_forks_repo_name": "mukherjeesoham/ScalarWave.jl", "max_forks_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_forks_repo_licenses": ["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.2, "max_line_length": 71, "alphanum_fraction": 0.5618597321, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7860961541722455}}
{"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    \u03c3y = [0 -1im; 1im 0];\n    mt = kron(\u03c3y,\u03c3y)*ms*kron(\u03c3y,\u03c3y)\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(\u03c1::AbstractMatrix, cutoff=1e-3)\n    r = Dict{Pauli,Float64}()\n    d2 = size(\u03c1, 1)\n    d = round(Int, sqrt(d2))\n    for p in allpaulis(d)\n        val = real(tr(\u03c1 * 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\u03b2 = ones(nvar) * 3.0                # True coefficients\nx = [ones(n) randn(n, nvar - 1)]    # X matrix of explanatory variables plus constant\n\u03b5 = randn(n) * 0.5                  # Error variance\ny = x * \u03b2 + \u03b5;                      # 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, \u03b2, log_\u03c3)\n    \u03c3 = exp(log_\u03c3)\n    llike = -n/2*log(2\u03c0) - n/2* log(\u03c3^2) - (sum((Y - X * \u03b2).^2) / (2\u03c3^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 \u03b2'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 \u03b2's and the error variance.  The\n# `vars[1:nvar]` is how we pass the vector of \u03b2'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 \u03b2'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 \u2248 [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\u03b2 = parameters[1:nvar]\n@test \u03b2 \u2248 [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 = \u03b2./sqrt.(temp1)\n@test t_stats \u2248 [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    \u03b8 = \u03c0*rand(rng)\n    \u03d5 = 2.0*\u03c0*rand(rng)\n    return Vector([\n        cos(\u03d5)*sin(\u03b8),\n        sin(\u03d5)*sin(\u03b8),\n        cos(\u03b8)\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    \u03b1::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    \u03be = rand(rng)\n    \u03b3 = 1.0-s.\u03b1\n    e0\u03b3= s.domain[1]^(\u03b3)\n    ef\u03b3 = s.domain[2]^(\u03b3)\n    out = (ef\u03b3-e0\u03b3)*\u03be+e0\u03b3\n    return out^(1/\u03b3)\nend\n\n\"\"\"\n    BrokenPowerLaw\n\nSampler for a broken power law distribution\n\"\"\"\nstruct BrokenPowerLaw <: Sampleable{Univariate, Continuous}\n    \u03b1::Array{T} where {T<:Real}\n    domain::Array{T} where {T<:Real}\n    function BrokenPowerLaw(\u03b1::Array{T}, domain::Array{T}) where {T<:Real}\n        @assert length(\u03b1)+1 == length(domain) \"Requires length(\u03b1) == 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(\u03b1, 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\u03be = rand(rng)\n\t\u03b3 = 1 .- s.\u03b1\n\n\n\tcx = ones(length(s.\u03b1))\n\tfor i = 1:(length(cx)-1)\n\t\t\u03b2 = s.\u03b1[i]/s.\u03b1[i+1]\n\t\tcx[i+1] = cx[i]^\u03b2*s.domain[i+1]^(\u03b2-1)\n\tend\n\tcx = map(/,cx,\u03b3)\n\n\n\tarts = [\n\t\tbegin\n\t\t\t(s.domain[i+1]^\u03b3[i] - s.domain[i]^\u03b3[i])*cx[i]\n\t\tend for i=1:length(\u03b3)\n\t\t\t]\n\n\tparts = vcat([0],arts)\n\tsumParts = cumsum(parts)\n\n\tnorm = sumParts[end]\n\tcnorm = \u03be*norm\n\n\tsupIndex = afterIndex(cnorm,sumParts)\n\n\tout = cnorm - sumParts[supIndex]\n\tout /= cx[supIndex]\n\tout += s.domain[supIndex]^\u03b3[supIndex]\n\tout = out^(1/\u03b3[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 \u2202\u2093y and \u2202\u2093\u2093y 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        \u2202\u2093y = /( y[i+1] - y[i-1] , x[i+1] - x[i-1] )\n        \n        \u2202\u2093\u2093y = /(+ *(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        \u2202\u2093y = /( y[i+1] - y[i] , x[i+1] - x[i] )\n        \n        \u2202\u2093\u2093y = /(+ *(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        \u2202\u2093y = /( y[i] - y[i-1] , x[i] - x[i-1] )\n        \n        \u2202\u2093\u2093y = /(+ *(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 \u2202\u2093y, \u2202\u2093\u2093y\nend \n\n\n\n# Compute the finite difference approximation of \u2202\u2093y and \u2202\u2093\u2093y at all nodes on an even/uneven grid\nfunction fntdiff1d!(\u2202\u2093y::AbstractArray{T,1}, \u2202\u2093\u2093y::AbstractArray{T,1}, x::StaticVector{N,T}, y::AbstractArray{T,1}) where {T<:Union{Float64, BigFloat}, N}\n    length(y) == length(\u2202\u2093y) == length(\u2202\u2093\u2093y) == N || throw(DimensionMismatch(\"x, y, \u2202\u2093y, and \u2202\u2093\u2093y in fntdiff1d!\"))\n    \n    for i in 1:N\n        \u2202\u2093y[i], \u2202\u2093\u2093y[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} #\u00a0evaluation 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#\u00a0function 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 * \u03c0 * 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 \u03a6(n::Int64)\n\n    for p in keys(factor(n))\n        n -= div(n, p)\n    end\n\n    n\nend\n\n# \u03a6(240) = \u03a6(2^4 * 3^1 * 5^1)\n# \u03a6(240) = (2^4 - 2^3) * (3^1 - 3^0) * (5^1 - 5^0)\n# \u03a6(240) = 64\n\nprintln(\u03a6(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 \u2ab0 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) \u2ab0 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    binary_pivot_search(array::Array{Int64,1}, target::Int64)\n\nThe idea is to find the pivot point for finding the target in an unsorted array. For this\nreason, the array has to be divided into two subarrays; a binary search is performed on\nthe subarrays.\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array of integers\n- `target::Int64`: Target-value to find the position\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr = [2, 5, 4, 7, 2, 8, 9, 3, 10, 2]\njulia> target = 3\njulia> ClassicAlgorithmsCollections.binary_pivot_search(arr, target)\n8\n```\n\"\"\"\nfunction binary_pivot_search(array::Array{Int64,1}, target::Int64)\n    left = 1\n    right = length(array)\n\n\n    while left <= right\n        # Generating the middle element position\n        mid = fld((left + right), 2)\n\n        # Check if target is hit\n        if array[mid] == target\n            return mid\n            # Check if array is sorted from left to mid\n        elseif array[left] <= array[mid]\n            # Check if key lies in the left or right half\n            if target >= array[left] && target <= array[mid]\n                right = mid - 1\n            else\n                left = mid + 1\n            end\n            # Check if array is sorted from mid to the right\n        elseif array[right] >= array[mid]\n            # If array from left to mid is not sorted, array from mid to right is sorted\n            if target >= array[mid] && target <= array[right]\n                left = mid + 1\n            else\n                right = mid - 1\n            end\n        end\n    end\n    return nothing\nend\n", "meta": {"hexsha": "b92cd94bb3ebe365134e6452e48b1c5d38fed598", "size": 1605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SortingAndSearching/BinaryPivotSearch.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/BinaryPivotSearch.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/BinaryPivotSearch.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": 29.1818181818, "max_line_length": 89, "alphanum_fraction": 0.5975077882, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7859846143210731}}
{"text": "using ThreeBodyProblem\nusing Test\n\n@test AP2a(1e6,1e5) == 5.5e5\n@test AP2a(1e6,1e6) == 1e6\n\np = [1;0;0]\nrv = [1;3;4]\n@test_broken findrP(rv,p) == 5\nrv = [rv,rv]\n@test_broken findrP(rv,p) == 5\nrv = [1;3;4;5;5;7]\n@test_broken findrP(rv,p) == 5\nrv = [rv,rv]\n@test_broken findrP(rv,p) == 5\n\n# @test_broken M2e\n\nrv = [1,0,0,0,1,0]\n\u03bc = 1\na, e, i, \u03a9, \u03c9, \u03bd, \u03a0, u, l, \u2130 = cart2oe(rv, \u03bc, ang_unit=:rad)\n@test a == 1.0\n@test e == 0.0\n@test i == 0.0\n@test isnan(\u03a9)\n@test isnan(\u03c9)\n@test isnan(\u03bd)\n@test isnan(\u03a0)\n@test isnan(u)\n@test l == 0.0\n@test \u2130 == -0.5\n\nrv = [1,0,0,0,0,1]\n\u03bc = 1\na, e, i, \u03a9, \u03c9, \u03bd, \u03a0, u, l, \u2130 = cart2oe(rv, \u03bc, ang_unit=:rad)\n@test a == 1.0\n@test e == 0.0\n@test i == \u03c0/2\n@test \u03a9 == 0.0\n@test isnan(\u03c9)\n@test isnan(\u03bd)\n@test isnan(\u03a0)\n@test u == 0.0\n@test isnan(l)\n@test \u2130 == -0.5\n\nrv = [1,0,0,0,2,0]\n\u03bc = 1\na, e, i, \u03a9, \u03c9, \u03bd, \u03a0, u, l, \u2130 = cart2oe(rv, \u03bc, ang_unit=:rad)\n@test a == -0.5\n@test e == 3.0\n@test i == 0.0\n@test isnan(\u03a9)\n@test isnan(\u03c9)\n@test \u03bd == 0.0\n@test \u03a0 == 0.0\n@test isnan(u)\n@test isnan(l)\n@test \u2130 == 1.0\n\n@test_throws ErrorException(\"ang_unit should be :rad or :deg\") cart2oe(rv, \u03bc, ang_unit=:foo)\n\nrv = [1,0,0,0,\u221a2,\u221a2]\n\u03bc = 1\na, e, i, \u03a9, \u03c9, \u03bd, \u03a0, u, l, \u2130 = cart2oe(rv, \u03bc, ang_unit=:deg)\n@test oe2cart(a, e, i, \u03a9, \u03c9, \u03bd, \u03bc, ang_unit=:deg) == rv\na, e, i, \u03a9, \u03c9, \u03bd, \u03a0, u, l, \u2130 = cart2oe(rv, \u03bc, ang_unit=:rad)\n@test oe2cart(a, e, i, \u03a9, \u03c9, \u03bd, \u03bc, ang_unit=:rad) == rv\n@test_throws ErrorException(\"ang_unit should be :rad or :deg\") oe2cart(a, e, i, \u03a9, \u03c9, \u03bd, \u03bc, ang_unit=:foo)\n", "meta": {"hexsha": "f6c15b9448575a1b09598cc83989e523626f84cb", "size": 1483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/orbitalelements_tests.jl", "max_stars_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_stars_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-28T01:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-28T22:34:55.000Z", "max_issues_repo_path": "test/orbitalelements_tests.jl", "max_issues_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_issues_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_issues_repo_licenses": ["MIT"], "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/orbitalelements_tests.jl", "max_forks_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_forks_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_forks_repo_licenses": ["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.1857142857, "max_line_length": 106, "alphanum_fraction": 0.5677680378, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.868826771143471, "lm_q1q2_score": 0.7859846078918833}}
{"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\u03c0 / 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->\u221e)Sn = \u03c0^2/6 \u2248 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\u2026\u2026\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(\u03bd)\n    if \u03bd == 0\n        return Polynomial([1])\n    elseif \u03bd == 1\n        return Polynomial([0, 2])\n    else\n        p1 = Polynomial([0,2])*hermite_polynomial(\u03bd-1)\n        p2 = 2(\u03bd-1)*hermite_polynomial(\u03bd-2)\n        return p1 - p2\n    end\nend\n\n\nstruct HarmonicEigenstate\n    \u03bd::Int\n    \u03b1::Float64\n    \u03c9::Float64\n    N::Float64\n    hp::Polynomial{Int}\n    function HarmonicEigenstate(\u03bd::Int; \u03c9=1)\n        \u03b1 = 1/sqrt(\u03c9)\n        hp = hermite_polynomial(\u03bd)\n        N = (2^\u03bd*factorial(\u03bd)*sqrt(\u03c0)*\u03b1)^(-1//2)\n        new(\u03bd, \u03b1, \u03c9, 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.\u03b1\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    \u03c8 = map(r-> hx(r[1])*hy(r[2])*hz(r[3]), ceg)\n    return QuantumState(ceg, \u03c8)\nend\n\nfunction energy(he::HarmonicEigenstate)\n    return he.\u03c9*(he.\u03bd+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\u00b13.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       (\u2243), (\u2244), (\u227a), (\u2aaf), (\u227b), (\u2ab0),           #    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, (\u224a),\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": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 c4381b3c-6b8f-11eb-34c1-9760c2fc6d87\nbegin\n\tusing Test\nend\n\n# \u2554\u2550\u2561 968a3130-6b8e-11eb-1d6c-1317dbf89bc8\nmd\"\"\"\n## \\#7\n\"\"\"\n\n# \u2554\u2550\u2561 b4d8b1a2-6b8e-11eb-3273-bd06e5e16a9b\nbegin\n\tb = [\n\t\t4\n\t\t1\n\t\t0\n\t\t1\n\t]\n\t\n\tx = [\n\t\t0\n\t\t1\n\t\t2\n\t\t3\n\t]\n\t\n\tA = [\n\t\tones(4, 1) x\n\t]\n\t\n\tu = round.(Int, inv(A' * A) * A' * b)\n\t\n\t@test u == [\n\t\t3\n\t\t-1\n\t]\nend\n\n# \u2554\u2550\u2561 d2278240-6b90-11eb-0bc3-df340513edd4\nmd\"\"\"\n## \\#8\n\"\"\"\n\n# \u2554\u2550\u2561 e6c51852-6b90-11eb-1e64-1b29b65808fd\nbegin\n\tp = A * u\n\t\n\te = b - p\n\t\n\t@test A' * e == [\n\t\t0\n\t\t0\n\t]\nend\n\n# \u2554\u2550\u2561 00970928-6b93-11eb-1707-f157198becdd\nmd\"\"\"\n## \\#12\n\"\"\"\n\n# \u2554\u2550\u2561 09012d82-6b93-11eb-00ab-41d5b7a8615e\nbegin\n\tA\u2082 = [\n\t\tA x.^2\n\t]\n\t\n\tu\u2082 = round.(Int, inv(A\u2082' * A\u2082) * A\u2082' * b)\n\t\n\t@test u\u2082 == [\n\t\t4\n\t\t-4\n\t\t1\n\t]\n\t\n\tp\u2082 = A\u2082 * u\u2082\n\t\n\te\u2082 = b - p\u2082\n\t\n\t# Exact solution\n\te\u2082 == [\n\t\t0.0\n\t\t0.0\n\t\t0.0\n\t\t0.0\n\t]\n\t\n\tA\u2083 = [\n\t\tA\u2082 x.^3\n\t]\n\t\n\tu\u2083 = round.(Int, inv(A\u2083' * A\u2083) * A\u2083' * b)\n\t\n\tp\u2083 = A\u2083 * u\u2083\n\t\n\te\u2083 = b - p\u2083\n\t\n\t# Exact solution for cubic\n\te\u2083 == [\n\t\t0.0\n\t\t0.0\n\t\t0.0\n\t\t0.0\n\t]\nend\n\n# \u2554\u2550\u2561 a50a2640-6ba0-11eb-1247-2388f1b38906\nmd\"\"\"\n## \\#22\n\"\"\"\n\n# \u2554\u2550\u2561 aa83f89c-6ba0-11eb-32ae-8ba9f30015eb\nbegin\n\tA\u2084 = [\n\t\t1 -1\n\t\t1 1\n\t\t1 2\n\t]\n\t\n\tb\u2084 = [\n\t\t5\n\t\t13\n\t\t17\n\t]\n\t\n\tu\u2084 = round.(Int, inv(A\u2084' * A\u2084) * A\u2084' * b\u2084)\n\t\n\t@test u\u2084 == [\n\t\t9\n\t\t4\n\t]\n\t\n\te\u2084 = A\u2084 * u\u2084 - b\u2084\n\t\n\t@test e\u2084 == [\n\t\t0\n\t\t0\n\t\t0\n\t]\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550c4381b3c-6b8f-11eb-34c1-9760c2fc6d87\n# \u255f\u2500968a3130-6b8e-11eb-1d6c-1317dbf89bc8\n# \u2560\u2550b4d8b1a2-6b8e-11eb-3273-bd06e5e16a9b\n# \u255f\u2500d2278240-6b90-11eb-0bc3-df340513edd4\n# \u2560\u2550e6c51852-6b90-11eb-1e64-1b29b65808fd\n# \u255f\u250000970928-6b93-11eb-1707-f157198becdd\n# \u2560\u255009012d82-6b93-11eb-00ab-41d5b7a8615e\n# \u2560\u2550a50a2640-6ba0-11eb-1247-2388f1b38906\n# \u2560\u2550aa83f89c-6ba0-11eb-32ae-8ba9f30015eb\n", "meta": {"hexsha": "8e043935e9179c965051e51b99a154dd5899c2b1", "size": 1734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2.FrameworkForAppliedMath/3.LeastSquaresForRectangularMatrix/ProblemSet.jl", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "2.FrameworkForAppliedMath/3.LeastSquaresForRectangularMatrix/ProblemSet.jl", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_issues_repo_licenses": ["MIT"], "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.FrameworkForAppliedMath/3.LeastSquaresForRectangularMatrix/ProblemSet.jl", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 11.0445859873, "max_line_length": 43, "alphanum_fraction": 0.5513264129, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7858095976878522}}
{"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                  \u03f5::Real,\n                  droppingstrategy::Symbol=:None;\n                  \u03b1::Real=0.01, \u03b2::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  \u2207f(x) = [x[1: size(w, 1)]; C*ones(Y)]\n  x, optdistances, numconstraints = accpm(\n    f, \u2207f, A, b, x0, \u03f5, droppingstrategy; \u03b1=\u03b1, \u03b2=\u03b2)\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 = \u221a(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 \u2264 b exists for the original problem.\nfunction accpm(f, \u2207f,\n               A::AbstractMatrix,\n               b::AbstractVector, \n               x0::AbstractVector,\n               \u03f5::Real,\n               droppingstrategy::Symbol=:None;\n               \u03b1::Real=0.01, \u03b2::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; \u03b1=\u03b1, \u03b2=\u03b2)\n    \u2207, fx = \u2207f(x), f(x)\n    u = min(u, fx)\n    l = max(l, fx - ms[end]*\u221a(\u2207'*(H\\\u2207)))\n    push!(optdistances, u - l)\n    u - l < \u03f5 && break\n    if droppingstrategy \u2260 :None\n      A, b = dropconstraint(A, b, x, H, droppingstrategy)\n    end\n    A, b = [A; \u2207'], [b; \u2207'*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 \u2264 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' \u2264 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  \u03b4 = minimum(upperbound./lowerbound)\n  x - \u03b4*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)./[\u221a((A*Hinv)[i, :]\u22c5A[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": "using MUMPSjInv\nusing Test\nusing LinearAlgebra\nusing SparseArrays\n\ninclude(\"getDivGrad.jl\");\n\nA = getDivGrad(32,32,16);\nn = size(A,1);\n\n# REAL: test for single rhs\nprintln(\"Test for real SPD matrix: one sparse random rhs\");\nrhs = sprandn(n,1,0.05);\n\nx = solveMUMPS(A,rhs,1);\nerr  =  norm(A*x-Matrix(rhs)) / norm(Matrix(rhs));\n@test err < 1e-14\n\n# rhs as sparse vector instead of n X 1 sparse matrix\nrhs = SparseVector(rhs)\n\nx = solveMUMPS(A,rhs,1);\nerr  =  norm(A*x-Vector(rhs)) / norm(Vector(rhs));\n@test err < 1e-14\n\n# REAL: test for multiple rhs\nprintln(\"Test for real SPD matrix: multiple sparse random rhs\");\nnrhs = 10;\nrhs = sprandn(n,nrhs,0.03);\n\nx = solveMUMPS(A,rhs,1);\n\nerr = zeros(nrhs)\nfor i=1:nrhs\n        err[i] =  norm(A*x[:,i]-Vector(rhs[:,i])) / norm(Vector(rhs[:,i]));\nend\n@test eltype(x) == Float64\n@test maximum(err) < 1e-14\n\nprintln(\"Test for real SPD matrix: multiple sparse delta function rhs\");\nrhs = sparse(1.0*I,n,n)\nrhs = rhs[:,1:nrhs]\n\nx = solveMUMPS(A,rhs,1);\n\nerr = zeros(nrhs)\nfor i=1:nrhs\n        err[i] =  norm(A*x[:,i]-Vector(rhs[:,i])) / norm(Vector(rhs[:,i]));\nend\n@test eltype(x) == Float64\n@test maximum(err) < 1e-14\n\n# COMPLEX: test for one rhs\nprintln(\"Test for complex SPD matrix: one rhs\");\nr = rand(n);\nA = A + im*spdiagm(0=>r);\n\nrhs = sprandn(n,1,0.03) + im*sprandn(n,1,0.03)\n\nx = solveMUMPS(A,rhs,2);\n\nerr=  norm(A*x-Matrix(rhs)) / norm(Matrix(rhs))\n@test eltype(x) == ComplexF64\n@test err < 1e-14\n\n# sparse vector rhs\nrhs = SparseVector(sprandn(n,1,0.03) + im*sprandn(n,1,0.03))\n\nx = solveMUMPS(A,rhs,2);\n\nerr=  norm(A*x-Vector(rhs)) / norm(Vector(rhs))\n@test eltype(x) == ComplexF64\n@test err < 1e-14\n\n# COMPLEX : test for multiple rhs\nprintln(\"Test for complex SPD matrix: multiple sparse random rhs\");\nnrhs = 10;\nrhs = sprandn(n,nrhs,0.03) + im*sprandn(n,nrhs,0.03);\n\nx = solveMUMPS(A,rhs,2);\nerr = zeros(nrhs)\nfor i=1:nrhs\n        err[i] =  norm(A*x[:,i]-Vector(rhs[:,i])) / norm(Vector(rhs[:,i]));\nend\n@test eltype(x) == ComplexF64\n@test maximum(err) < 1e-14\n\nprintln(\"DONE!\")\n", "meta": {"hexsha": "3ebe6c4bc7ba982acfa1acb80590121aacf2d1a7", "size": 2028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testSparseRHS.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MUMPS.jl-bf6389e2-cca1-5e17-ac22-36425c4ccbb4", "max_stars_repo_head_hexsha": "735cc81f194c220dc8305ca19897453f4ddb1c17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-02-08T09:19:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T12:41:30.000Z", "max_issues_repo_path": "test/testSparseRHS.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MUMPS.jl-bf6389e2-cca1-5e17-ac22-36425c4ccbb4", "max_issues_repo_head_hexsha": "735cc81f194c220dc8305ca19897453f4ddb1c17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-01-18T15:34:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-28T03:33:09.000Z", "max_forks_repo_path": "test/testSparseRHS.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MUMPS.jl-bf6389e2-cca1-5e17-ac22-36425c4ccbb4", "max_forks_repo_head_hexsha": "735cc81f194c220dc8305ca19897453f4ddb1c17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2015-02-26T22:46:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-16T09:41:42.000Z", "avg_line_length": 22.7865168539, "max_line_length": 75, "alphanum_fraction": 0.6499013807, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7857914072396557}}
{"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# \u2554\u2550\u2561 bbd5a62e-fbcd-11ea-2bbd-e7be1b736f9f\nusing Plots\n\n# \u2554\u2550\u2561 afa5cbc0-fbcc-11ea-0dd2-35821062dd18\nc = 3\n\n# \u2554\u2550\u2561 59ddff8e-fbcd-11ea-1124-d308b43c24d9\nacr =10\n\n# \u2554\u2550\u2561 d8f55b7e-fbcc-11ea-1881-15dbeb706e20\nxvars = [float(c) - i for i in 0:acr]\n\n# \u2554\u2550\u2561 1c685b10-fbcd-11ea-1ecd-75e8c03e7f87\nbegin\n\tfunction f(x)\n\t\treturn cos(x)\n\tend\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 358ecd40-fbcd-11ea-00fe-755c43fd372e\nyvals = [f(xvars[i]) for i in 1:acr]\n\n# \u2554\u2550\u2561 55799400-fbcd-11ea-05dc-85c5e87f6f63\nsecs = [(yvals[i]-f(c))/(xvars[i]-c) for i in 1:acr]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 12bbbe30-fbce-11ea-289f-ff4eeafbdcbf\ncd(#= type where you want the images to save on your machine=#)\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550bbd5a62e-fbcd-11ea-2bbd-e7be1b736f9f\n# \u2560\u2550afa5cbc0-fbcc-11ea-0dd2-35821062dd18\n# \u2560\u255059ddff8e-fbcd-11ea-1124-d308b43c24d9\n# \u2560\u2550d8f55b7e-fbcc-11ea-1881-15dbeb706e20\n# \u2560\u25501c685b10-fbcd-11ea-1ecd-75e8c03e7f87\n# \u2560\u255029568700-fbcf-11ea-3096-7f18898aeba0\n# \u2560\u2550358ecd40-fbcd-11ea-00fe-755c43fd372e\n# \u2560\u255055799400-fbcd-11ea-05dc-85c5e87f6f63\n# \u2560\u2550ae19b810-fbcd-11ea-2ee7-a9f08af0abaf\n# \u2560\u255012bbbe30-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": "using JuMP\nusing Stat31020\nusing Base.Test\n\nx0 = ones(2); x1 = x0[1]; x2=x0[2]\n\n# testing:\n## -----------------------------------------------------------------------------\n## min:  f = sum(x[1]^4 - 2.0*x[1]^2*x[2] + x[1]^2 + x[2]^2 - 2*x[1] for i=I)\n## s.t.: -(x[1] + 0.25)^2 + 0.75*x[2] >= 0)\n##       -(x[1] + 0.25) + 0.75*x[2]^2 >= 0)\n## -----------------------------------------------------------------------------\nf, g, h, j, kkt = Stat31020.constrained_wrap(x0, 2; kkt=true, \u03bc=1.0, \u03bb=ones(2))\n\nfunction h_analytic(x1, x2)\n    h = [[(12.0*x1^2 - 4.0*x2 + 2.) (-4.0*x1)];[(-4.0*x1) (2.)]] +\n        [[-2. 0.];[0. 0.]] + [[0. 0.];[0. 1.5]]\n    return h\nend\nfunction j_analytic(x1, x2)\n    j = [[(-2.0*(x1 + 0.25)) 0.75];[-1.0 (1.5*x2)]]\n    return j\nend\n\nh_a = h_analytic(x1, x2)\nj_a = j_analytic(x1, x2)\nz = zeros(2, 2)\nkkt_a = [h_a j_a'; j_a z]\n\ndisplay(full(kkt))\nprintln();\ndisplay(full(kkt_a))\nprintln();\n@test full(kkt) == full(kkt_a)\n", "meta": {"hexsha": "8f0895dd2655f3e13a4553e4636232ab4cc30bf0", "size": 944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jacob-roth/Stat31020", "max_stars_repo_head_hexsha": "7767c5575856aa3da83f14dbb962e4b2e6f02cfd", "max_stars_repo_licenses": ["MIT"], "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": "jacob-roth/Stat31020", "max_issues_repo_head_hexsha": "7767c5575856aa3da83f14dbb962e4b2e6f02cfd", "max_issues_repo_licenses": ["MIT"], "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": "jacob-roth/Stat31020", "max_forks_repo_head_hexsha": "7767c5575856aa3da83f14dbb962e4b2e6f02cfd", "max_forks_repo_licenses": ["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.9714285714, "max_line_length": 80, "alphanum_fraction": 0.4237288136, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7857860019225636}}
{"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 (\u2264) := Leq\n\n  # Preorder axioms are lifted to term constructors in the GAT.\n  reflexive(A::El)::(A\u2264A) # \u2200 A there is a term reflexive(A) which implies A\u2264A\n  transitive(f::(A\u2264B), g::(B\u2264C))::(A\u2264C) \u22a3 (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 \u22a3 (A::El, B::El, f::(A\u2264B), g::(A\u2264B))\n  # Read as (f\u27f9 A\u2264B \u2227 g\u27f9 A\u2264B) \u27f9 f \u2261 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 \u22a3 (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  (\u2192) := Hom\n  (\u22c5) := 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 \u2192 A)\n  compose(f::(A \u2192 B), g::(B \u2192 C))::(A \u2192 C) \u22a3 (A::Ob, B::Ob, C::Ob)\n\n  # Category axioms.\n  ((f \u22c5 g) \u22c5 h == f \u22c5 (g \u22c5 h)\n  \u22a3 (A::Ob, B::Ob, C::Ob, D::Ob, f::(A \u2192 B), g::(B \u2192 C), h::(C \u2192 D)))\n  f \u22c5 id(B) == f \u22a3 (A::Ob, B::Ob, f::(A \u2192 B))\n  id(A) \u22c5 f == f \u22a3 (A::Ob, B::Ob, f::(A \u2192 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 \u2264 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\u2032::Ob\n  f\u2032::Hom(X,Y\u2032)\n  g\u2032::Hom(Y\u2032,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\u2081::Hom(X,Y) \u2227 ex\u2082::Hom(X,Y) \u27f9 ex\u2081 == ex\u2082\n\nfunction thinequal(ex\u2081::FreeThinCategory.Hom, ex\u2082::FreeThinCategory.Hom)\n  dom(ex\u2081) == dom(ex\u2082) && codom(ex\u2081) == codom(ex\u2082)\nend\n\n@test thinequal(ex, compose(P, [:f,:g])\u22c5id(generator(P,:Z)))\n\n# Thinking in terms of preorders, the composite f\u22c5g::Hom(X,Z) is a proof that X \u2264 Z\n# in logical notation you would say f::Hom(X,Y) and g::Hom(Y,Z) \u22a2 f\u22c5g::Hom(X,Z)\n# given a proof that X\u2264Y and a proof of Y\u2264Z then \u22c5 will create a proof of X\u2264Z\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\u2264Z, we name that proof by adding it as a generator\n@present P\u2082(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\u2082, [:f, :g])\n\n# Now that we have a name for h, we can see that thinequal knows that f\u22c5g == 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\u2082, :h))\n\n# There is an imperative interface to manipulating presentations by mutating them for this purpose\nP\u2082\u2032 = copy(P)\nadd_generator!(P\u2082\u2032, Hom(:h, P[:X], P[:Z]))\ngenerators(P\u2082\u2032)\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 \u2264.\n@present R(FreeThinCategory) begin\n  (x,y,z)::Ob\n  (\u2264)::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  (\u2264)::Hom(x,y)\n  (\u2264)::Hom(y,z)\n  (\u2264)::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\u1d62->in_homs(f\u1d62, 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\u2092 = map(ob_generators(dom(F))) do X\n    F(X) in ob_generators(codom(F))\n  end |> all\n\n  p\u2095 = map(hom_generators(dom(F))) do f\n    in_homs(F(f), codom(F))\n  end |> all\n\n  p\u1d69 = 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\u2092 && p\u2095 && p\u1d69\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\u2092 = Dict(:X=>:a, :Y=>:b, :Z=>:c)\nF\u2095 = Dict(:f=>:ab, :g=>:bc)\nF = FinFunctor(F\u2092, F\u2095, P, Q)\n@test is_functorial(F)\n\nF\u2092 = Dict(:X=>:a, :Y=>:b, :Z=>:d)\nF\u2095 = Dict(:f=>:ab, :g=>[:bc, :cd])\nF = FinFunctor(F\u2092, F\u2095, P, Q)\n@test is_functorial(F)\n\n\nF\u2092 = Dict(:X=>:a, :Y=>:b, :Z=>:c)\nF\u2095 = Dict(:f=>:ab, :g=>[:bc, :cd])\nF = FinFunctor(F\u2092, F\u2095, 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{\ud835\udd3d} <: Manifold{\ud835\udd3d}\n\nThe circle $\ud835\udd4a^1$ is a manifold here represented by\nreal-valued points in $[-\u03c0,\u03c0)$ or complex-valued points $z \u2208 \u2102$ of absolute value\n$\\lvert z\\rvert = 1$.\n# Constructor\n\n    Circle(\ud835\udd3d=\u211d)\n\nGenerate the `\u211d`-valued Circle represented by angles, which\nalternatively can be set to use the [`AbstractNumbers`](@ref) `\ud835\udd3d=\u2102` to obtain the circle\nrepresented by `\u2102`-valued circle of unit numbers.\n\"\"\"\nstruct Circle{\ud835\udd3d} <: Manifold{\ud835\udd3d} end\n\nCircle(\ud835\udd3d::AbstractNumbers = \u211d) = Circle{\ud835\udd3d}()\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  \u2208 [-\u03c0,\u03c0)$.\nfor the complex-valued case, it is a unit number, $p \u2208 \u2102$ with $\\lvert p \\rvert = 1$.\n\"\"\"\ncheck_manifold_point(::Circle, ::Any...)\n\nfunction check_manifold_point(M::Circle{\u211d}, 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 [-\u03c0,\u03c0).\",\n        )\n    end\n    return nothing\nend\nfunction check_manifold_point(M::Circle{\u2102}, 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{\u211d}, ::Any...; ::Any...)\n\nfunction check_tangent_vector(M::Circle{\u211d}, 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{\u2102}, 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{\u211d}, p::Real, q::Real) = abs(sym_rem(p - q))\ndistance(::Circle{\u211d}, p, q) = abs(sum(sym_rem.(p - q)))\ndistance(::Circle{\u2102}, 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\u03c0},\n````\nwhere $(\\cdot)_{2\u03c0}$ is the (symmetric) remainder with respect to division by $2\u03c0$, i.e. in $[-\u03c0,\u03c0)$.\n\nFor the complex-valued case, the same formula as for the [`Sphere`](@ref) $\ud835\udd4a^1$ is applied to values in the\ncomplex plane.\n\"\"\"\nexp(::Circle, ::Any...)\nBase.exp(::Circle{\u211d}, p::Real, X::Real) = sym_rem(p + X)\nfunction Base.exp(M::Circle{\u2102}, x::Number, v::Number)\n    \u03b8 = norm(M, x, v)\n    return cos(\u03b8) * x + usinc(\u03b8) * v\nend\n\nexp!(::Circle{\u211d}, q, p, X) = (q .= sym_rem(p + X))\nfunction exp!(M::Circle{\u2102}, q, p, X)\n    \u03b8 = norm(M, p, X)\n    q .= cos(\u03b8) * p + usinc(\u03b8) * X\n    return q\nend\n\nflat(::Circle, ::Number, X::TFVector) = FVector(CotangentSpace, X.data)\n\nflat!(::Circle, \u03be::CoTFVector, p, X::TFVector) = copyto!(\u03be, X)\n\nfunction get_basis(M::Circle{\u211d}, 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{\u211d}, p, X, B::DefaultOrthonormalBasis) = X\nfunction get_coordinates(M::Circle{\u211d}, p, X, B::DiagonalizingOrthonormalBasis)\n    sbv = sign(B.frame_direction[])\n    return X .* (sbv == 0 ? 1 : sbv)\nend\n\"\"\"\n    get_coordinates(M::Circle{\u2102}, p, X, B::DefaultOrthonormalBasis)\n\nReturn tangent vector coordinates in the Lie algebra of the [`Circle`](@ref).\n\"\"\"\nfunction get_coordinates(M::Circle{\u2102}, p, X, B::DefaultOrthonormalBasis)\n    X, p = X[1], p[1]\n    X\u2071 = imag(X) * real(p) - real(X) * imag(p)\n    return @SVector [X\u2071]\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{\u211d}, p, X, ::AbstractBasis) = X\nfunction get_vector(M::Circle{\u211d}, p, X, B::DiagonalizingOrthonormalBasis)\n    sbv = sign(B.frame_direction[])\n    return X .* (sbv == 0 ? 1 : sbv)\nend\n\"\"\"\n    get_vector(M::Circle{\u2102}, p, X, B::DefaultOrthonormalBasis)\n\nReturn tangent vector from the coordinates in the Lie algebra of the [`Circle`](@ref).\n\"\"\"\nget_vector(M::Circle{\u2102}, 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. $\u03c0$.\n\"\"\"\ninjectivity_radius(::Circle) = \u03c0\ninjectivity_radius(::Circle, ::ExponentialRetraction) = \u03c0\ninjectivity_radius(::Circle, ::Any) = \u03c0\ninjectivity_radius(::Circle, ::Any, ::ExponentialRetraction) = \u03c0\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{\u211d}, p, X, Y) = dot(X, Y)\n@inline inner(::Circle{\u211d}, p::Real, X::Real, Y::Real) = X * Y\n@inline inner(::Circle{\u2102}, 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\u03c0},\n````\nwhere $(\\cdot)_{2\u03c0}$ is the (symmetric) remainder with respect to division by $2\u03c0$, i.e. in $[-\u03c0,\u03c0)$.\n\nFor the complex-valued case, the same formula as for the [`Sphere`](@ref) $\ud835\udd4a^1$ is applied to values in the\ncomplex plane.\n\"\"\"\nlog(::Circle, ::Any...)\nBase.log(::Circle{\u211d}, p::Real, q::Real) = sym_rem(q - p)\nfunction Base.log(M::Circle{\u2102}, p::Number, q::Number)\n    cos\u03b8 = complex_dot(p, q)\n    if cos\u03b8 \u2248 -1  # appr. opposing points, return deterministic choice from set-valued log\n        X = real(p) \u2248 1 ? 1im : 1 + 0im\n        X = X - complex_dot(p, X) * p\n        X *= \u03c0 / norm(X)\n    else\n        cos\u03b8 = cos\u03b8 > 1 ? one(cos\u03b8) : cos\u03b8\n        \u03b8 = acos(cos\u03b8)\n        X = (q - cos\u03b8 * p) / usinc(\u03b8)\n    end\n    return project(M, p, X)\nend\n\nlog!(::Circle{\u211d}, X, p, q) = (X .= sym_rem(q - p))\nfunction log!(M::Circle{\u2102}, X, p, q)\n    cos\u03b8 = complex_dot(p, q)\n    if cos\u03b8 \u2248 -1\n        X .= sum(real.(p)) \u2248 1 ? 1.0im : 1.0 + 0.0im\n        X .= X - complex_dot(p, X) * p\n        X .*= \u03c0 / norm(X)\n    else\n        cos\u03b8 = cos\u03b8 > 1 ? one(cos\u03b8) : cos\u03b8\n        \u03b8 = acos(cos\u03b8)\n        X .= (q - cos\u03b8 * p) / usinc(\u03b8)\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(\ud835\udd4a^1) = 1$.\n\"\"\"\nmanifold_dimension(::Circle) = 1\n\n@doc raw\"\"\"\n    mean(M::Circle{\u211d}, x::AbstractVector[, w::AbstractWeights])\n\nCompute the Riemannian [`mean`](@ref mean(M::Manifold, args...)) of `x` of points on\nthe [`Circle`](@ref) $\ud835\udd4a^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{\u211d}, ::Any)\nfunction Statistics.mean(::Circle{\u211d}, 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{\u211d},\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{\u2102}, x::AbstractVector[, w::AbstractWeights])\n\nCompute the Riemannian [`mean`](@ref mean(M::Manifold, args...)) of `x` of points on\nthe [`Circle`](@ref) $\ud835\udd4a^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{\u2102}, ::Any)\nfunction Statistics.mean(M::Circle{\u2102}, 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{\u2102},\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{\u211d}, p1, p2) = exp(M, p1, 0.5 * log(M, p1, p2))\nmid_point(::Circle{\u2102}, p1::Complex, p2::Complex) = exp(im * (angle(p1) + angle(p2)) / 2)\nmid_point(M::Circle{\u2102}, 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\u03c0$.\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{\u211d}, p::Real) = sym_rem(p)\nproject(::Circle{\u2102}, p::Number) = p / abs(p)\n\nproject!(::Circle{\u211d}, q, p) = copyto!(q, sym_rem(p))\nproject!(::Circle{\u2102}, 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{\u211d}, p::Real, X::Real) = X\nproject(::Circle{\u2102}, p::Number, X::Number) = X - complex_dot(p, X) * p\n\nproject!(::Circle{\u211d}, Y, p, X) = (Y .= X)\nproject!(::Circle{\u2102}, 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, \u03be::CoTFVector) = FVector(TangentSpace, \u03be.data)\n\nsharp!(::Circle, X::TFVector, p, \u03be::CoTFVector) = copyto!(X, \u03be)\n\nBase.show(io::IO, ::Circle{\ud835\udd3d}) where {\ud835\udd3d} = print(io, \"Circle($(\ud835\udd3d))\")\n\n@doc raw\"\"\"\n    sym_rem(x,[T=\u03c0])\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 $\u03c0$\n\"\"\"\nfunction sym_rem(x::N, T = \u03c0) where {N<:Number}\n    return (x \u2248 T ? convert(N, -T) : rem(x, convert(N, 2 * T), RoundNearest))\nend\nsym_rem(x, T = \u03c0) 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\u2190p} X = X - \\frac{\u27e8\\log_p q,X\u27e9_p}{d^2_{\u2102}(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{\u211d}, p::Real, X::Real, q::Real, ::ParallelTransport) = X\nfunction vector_transport_to(\n    M::Circle{\u2102},\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{\u211d}, Y, p, X, q, ::ParallelTransport) = (Y .= X)\nfunction vector_transport_to!(M::Circle{\u2102}, 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.\u0394x, 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": "# ---\n# title: 367. Valid Perfect Square\n# id: problem367\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math, Binary Search\n# link: <https://leetcode.com/problems/valid-perfect-square/description/>\n# hidden: true\n# ---\n# \n# Given a **positive** integer _num_ , write a function which returns True if\n# _num_ is a perfect square else False.\n# \n# **Follow up:** **Do not** use any built-in library function such as `sqrt`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: num = 16\n#     Output: true\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: num = 14\n#     Output: false\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= num <= 2^31 - 1`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "0d861ddd54c32657ba34cfbfc2663e93305e9ecf", "size": 762, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/367.valid-perfect-square.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/367.valid-perfect-square.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/367.valid-perfect-square.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.2127659574, "max_line_length": 77, "alphanum_fraction": 0.5682414698, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8723473846343394, "lm_q1q2_score": 0.7855748106916407}}
{"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\u0142 Nowak\n#\n# Instytut Informatyki\n# Uniwersytet Wroc\u0142awski\n#\n#\n# Pomocniczne materia\u0142y do wyk\u0142adu 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\u0142adny  = %.16f\\n\", x);\n  y = algorytm(n);\n  @printf(\"Wynik obliczony = %.16f   b\u0142\u0105d wzgl\u0119dny = %.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": "function rms(A)\n   s = 0.0\n   for a in A\n      s += a*a\n   end\n   return sqrt(s / length(A))\nend\n", "meta": {"hexsha": "1eeb684f1448ff76065e2320c1fad4e4018005dd", "size": 97, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/averages-root-mean-square-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/averages-root-mean-square-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/averages-root-mean-square-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": 12.125, "max_line_length": 29, "alphanum_fraction": 0.5051546392, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104953173167, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7855635072586681}}
{"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 \u00f7 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, \u03bb=1e-3), n = nfft, noverlap = nfft\u00f72)\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, \u03b2 = 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, \ud835\udcaa(t\u00b2) 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 \ud835\udcaa(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, \u03b2=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# \u2554\u2550\u2561 06240e71-df45-4f63-b797-4042432e6716\nusing FFTW, Plots, SampledSignals\n\n# \u2554\u2550\u2561 f8ba933c-a1e3-11eb-2263-17f14870c1fa\nmd\"# Basic Waveforms\nFirst let's see what basic waveforms can be made directly.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 664b9502-13de-4fdf-971c-66cf0ea47c3b\nplot(t, sin.(t))\n\n# \u2554\u2550\u2561 5e805acc-c6b1-4de5-8bc1-5bdcbd84ca04\nsine_tone = sin.(freqs)\n\n# \u2554\u2550\u2561 2a51d397-322b-414b-9d9f-a1e8ba6b2364\nplotfreqs(sine_tone, \"Sine Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a2357e48-116a-4df1-a52d-100533bad25d\nfunction saw(t)\n\tt/pi % 2 - 1\nend\n\n# \u2554\u2550\u2561 50824ffc-622d-4a00-acce-558cecf79e55\nplot(t, saw.(t))\n\n# \u2554\u2550\u2561 3ae066cb-b5f2-4913-8a73-20348a401026\nsaw_tone = saw.(freqs)\n\n# \u2554\u2550\u2561 7bd89cfd-9894-4644-b0e4-cae8a63cda9a\nplotfreqs(saw_tone, \"Aliased Saw Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a9f4a512-c8b4-474a-a93c-2cef99db534c\nfunction tri(t)\n\tabs(t/pi%2-1)*2-1\nend\n\n# \u2554\u2550\u2561 f6f28913-cbfa-48f8-98ab-0d5ed267b350\nplot(t, tri.(t))\n\n# \u2554\u2550\u2561 231185ea-8913-490d-8fe8-261983552457\ntri_tone = tri.(freqs)\n\n# \u2554\u2550\u2561 b627d7af-55d1-4d97-8f15-7f0d172f9b5a\nplotfreqs(tri_tone, \"Triangle Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 99f21cb1-b50f-4e8b-9d97-8bf5297afbec\npoly2_tone = poly2.(freqs)\n\n# \u2554\u2550\u2561 8802e5fe-8416-4c67-a1f0-b99bb6af3e3f\nplot(t, poly2.(t))\n\n# \u2554\u2550\u2561 b561d76e-e2a7-4c3d-9677-42f8b5661b7c\n# Kind of like a triangle wave but with even harmonics\nplotfreqs(poly2_tone, \"Poly2 Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e91b624c-cef9-4f74-8bf0-76a484c9c895\npoly3_tone = poly3.(freqs)\n\n# \u2554\u2550\u2561 6880cf94-23ee-4a96-8b9f-0417fc239374\nplot(t, poly3.(t))\n\n# \u2554\u2550\u2561 4caa26e8-c5ce-4d30-b80b-d3ed7659efa0\n# Here there is no aliasing >-40db\nplotfreqs(poly3_tone, \"Poly3 Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f1a60f5c-53c6-4533-b3ed-e715fb67d7ba\npoly4_tone = normalize(poly4.(freqs, 0))\n\n# \u2554\u2550\u2561 788ec89e-c1d0-498b-8e8c-82de0bc4eda6\nplot(t, normalize(poly4.(t, 0)))\n\n# \u2554\u2550\u2561 e24388fa-d474-4770-95a0-d34627ae7a04\n# No overtones reach the niquist rate, no aliasing at all\nplotfreqs(poly4_tone, \"Poly4 Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 076a215e-1335-4974-b61e-06fa4c9e9295\nbegin\n\tplot(t, -normalize(poly5.(t)))\n\tplot!(t, sin.(t))\nend\n\n# \u2554\u2550\u2561 e5ac5d3e-1240-4a3c-bc9a-d8e8e6fec60f\npoly5_tone = normalize(poly5.(freqs))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 97ec7198-36e8-410b-9602-d6b61f31db6b\nbegin\n\tplot(t, para.(t))\n\tplot!(t, sin.(t))\nend\n\n# \u2554\u2550\u2561 2765c9be-3636-45de-9804-7fecb69f4a7b\npara_tone = para.(freqs)\n\n# \u2554\u2550\u2561 52f4cba9-6eb4-42fe-bef5-8ea1a0f4e18a\nplotfreqs(para_tone, \"Parabola Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f116f443-0643-4cbb-8da8-4f9a312fd82f\nplot(t, ecubic)\n\n# \u2554\u2550\u2561 35acdceb-34f5-4a39-aa06-569ab6f16205\necubic_tone = ecubic.(freqs)\n\n# \u2554\u2550\u2561 d7f37c37-a912-4324-8ca2-063f7c1f3ebc\nplotfreqs(ecubic_tone, \"Even Cubic Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 89fee0e4-7e7f-400b-9cc2-8b3186ab0384\nplot(t, quart.(t))\n\n# \u2554\u2550\u2561 b649ead1-acf8-4390-bb9e-ae876a1c7f48\nquart_tone = quart.(freqs)\n\n# \u2554\u2550\u2561 c492d40f-fc0d-4b06-a925-7c75bff32503\nplotfreqs(quart_tone, \"Quartic Spectrum\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500f8ba933c-a1e3-11eb-2263-17f14870c1fa\n# \u2560\u255006240e71-df45-4f63-b797-4042432e6716\n# \u2560\u2550bfacded1-6007-4e18-aba1-1b7325878dd2\n# \u2560\u255065dbcdfe-2dbd-4b28-ab59-fb12425913ca\n# \u255f\u25004bd75a55-4457-4625-a184-a2f7490cbf0e\n# \u2560\u2550664b9502-13de-4fdf-971c-66cf0ea47c3b\n# \u2560\u25505e805acc-c6b1-4de5-8bc1-5bdcbd84ca04\n# \u2560\u25502a51d397-322b-414b-9d9f-a1e8ba6b2364\n# \u2560\u2550dd813478-66a1-4d3e-9872-322e7b521e11\n# \u2560\u2550a2357e48-116a-4df1-a52d-100533bad25d\n# \u2560\u255050824ffc-622d-4a00-acce-558cecf79e55\n# \u2560\u25503ae066cb-b5f2-4913-8a73-20348a401026\n# \u2560\u25507bd89cfd-9894-4644-b0e4-cae8a63cda9a\n# \u2560\u2550dfa8eb03-2955-4bb6-b9ca-eb7cd6583e57\n# \u2560\u2550a9f4a512-c8b4-474a-a93c-2cef99db534c\n# \u2560\u2550f6f28913-cbfa-48f8-98ab-0d5ed267b350\n# \u2560\u2550231185ea-8913-490d-8fe8-261983552457\n# \u2560\u2550b627d7af-55d1-4d97-8f15-7f0d172f9b5a\n# \u255f\u250099708158-d74e-4311-a10f-d0ac4f79d4f2\n# \u2560\u25501f127661-47b0-4498-9fc2-857f314b6869\n# \u2560\u255099f21cb1-b50f-4e8b-9d97-8bf5297afbec\n# \u2560\u25508802e5fe-8416-4c67-a1f0-b99bb6af3e3f\n# \u2560\u2550b561d76e-e2a7-4c3d-9677-42f8b5661b7c\n# \u2560\u255009d7e4f3-fed8-4fc8-b598-03ecc8e75d6f\n# \u2560\u2550aff77549-c6da-4329-8e92-5f1fb561ece6\n# \u2560\u2550e91b624c-cef9-4f74-8bf0-76a484c9c895\n# \u2560\u25506880cf94-23ee-4a96-8b9f-0417fc239374\n# \u2560\u25504caa26e8-c5ce-4d30-b80b-d3ed7659efa0\n# \u2560\u25501701a11b-b17b-499a-bf5f-0d721c026590\n# \u2560\u2550e060b886-4af2-4692-8882-79ceabe64ff1\n# \u2560\u255085236c40-9c9c-4e00-b8e8-54787a5760af\n# \u2560\u2550f1a60f5c-53c6-4533-b3ed-e715fb67d7ba\n# \u2560\u2550788ec89e-c1d0-498b-8e8c-82de0bc4eda6\n# \u2560\u2550e24388fa-d474-4770-95a0-d34627ae7a04\n# \u2560\u2550bf89825a-944b-4771-a619-e4c5d1220f61\n# \u2560\u2550076a215e-1335-4974-b61e-06fa4c9e9295\n# \u2560\u2550e5ac5d3e-1240-4a3c-bc9a-d8e8e6fec60f\n# \u2560\u255082c3a459-0944-4637-a481-cafd15402afe\n# \u2560\u255036e284d1-a982-45c2-a0cc-dae1cc355362\n# \u2560\u25503e73b73b-79a3-4ba6-bfc5-94f39816680f\n# \u2560\u255097ec7198-36e8-410b-9602-d6b61f31db6b\n# \u2560\u25502765c9be-3636-45de-9804-7fecb69f4a7b\n# \u2560\u255052f4cba9-6eb4-42fe-bef5-8ea1a0f4e18a\n# \u2560\u25500ade700b-6193-4518-8470-bb787f87ba47\n# \u2560\u2550f116f443-0643-4cbb-8da8-4f9a312fd82f\n# \u2560\u255035acdceb-34f5-4a39-aa06-569ab6f16205\n# \u2560\u2550d7f37c37-a912-4324-8ca2-063f7c1f3ebc\n# \u2560\u2550f86cda73-edd8-4905-81e0-83a6529daacc\n# \u2560\u255089fee0e4-7e7f-400b-9cc2-8b3186ab0384\n# \u2560\u2550b649ead1-acf8-4390-bb9e-ae876a1c7f48\n# \u2560\u2550c492d40f-fc0d-4b06-a925-7c75bff32503\n# \u255f\u2500d5e54701-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 \u03b6(N::Int64,a::Int64)\n  s = 0.0\n  @simd for i \u2208 1:N\n    s+=(1.0/i)^a\n  end\n  s\nend\n\nN = 16000000000\n@time \u03b6_2 = \u03b6(N,2)\n\u03c0_squared_over_6 = \u03c0^2 / 6.0;\n\n@printf \"      \u03b6(2) = %18.16f\\n\" \u03b6_2\n@printf \"\u03c0^2 / 6.0  = %18.16f\\n\" \u03c0_squared_over_6\n@printf \"     error = %18.16f\\n\" \u03c0_squared_over_6 - \u03b6_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\u2032, 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\u2032(a)*f\u2032(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\u03b2 = 0.9;\n\u03c3 = 2;\n\u03b3 = 2;\n\n## Utility functions\nu(x) = x^(1 - \u03c3) / (1 - \u03c3);\nv(x) = x^(1 + \u03b3) / (1 + \u03b3);\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\u03b8 = 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 \u03a6 and initial state s0 \nfunction RamseyAllocation(\u03a6::Real, s0::Tuple)\n\n    function time1_allocation(s::Tuple)\n        \u03b8, g = s[1], s[2];\n        n(c::Real) = (g + c) / \u03b8;\n        res1(c::Real) = (1 + \u03a6) * (Uc(c) * \u03b8 + Un(n(c))) + \u03a6 * (c * Ucc(c) * \u03b8 + 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        \u03b8, g = s[1], s[2];\n        n(c::Real) = (g + c) / \u03b8;\n        b0(c::Real) = 1.0;\n        res0(c::Real) = (1 + \u03a6) * (Uc(c) * \u03b8 + Un(n(c))) + \u03a6 * (c * Ucc(c) * \u03b8 + n(c) * Unn(n(c))) - \u03a6 * Ucc(c) * b0(c) * \u03b8\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 - \u03b2 * 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 - \u03b2 * 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\u03c4_time1 = [1.0 + Un(n_time1[i]) / Uc(c_time1[i]) for i in 1:length(s)];\n\n\n\n\nfunction search_\u03a6(\u03a6::Real, s0::Tuple)\n    c_time1, n_time1, c_time0, n_time0 = RamseyAllocation(\u03a6, s0);\n    \n    i_s0 = findfirst(isequal(s0), s);\n\n    sum_mat = inv(1.0I - \u03b2 * 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 - \u03b2 * sum([Ps[i_s0,i] * sum_mat[i] for i in 1:length(sum_mat)]);\n\n    return implementCons\n\nend\n\n\u03a6_est = NewtonRoot(x -> search_\u03a6(x, s[1]), 0.1); # 0.06175628494006816\n\n\u03c4_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\u03c4_sim_h = [\u03c4_time1[i] for i in sHist_h];\n\u03c4_sim_l = [\u03c4_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\u03c4_plot_h = vcat(\u03c4_time0, \u03c4_sim_h)\n\u03c4_plot_l = vcat(\u03c4_time0, \u03c4_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(\u03c4_plot_l, label=\"g high\")\nplot!(\u03c4_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\u00e1s A. Arias, and Steven T. Smith\n# SIAM. J. Matrix Anal. & Appl., 20(2), 303\u2013353. (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 \u2208 m1, x2 \u2208 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.\u228a, Base.\u2287, Base.\u228b\n\nimport AbstractLattices: \u2228, \u2227\n\nexport ClosedInterval, EmptyInterval, \u2287, \u228b\nexport show, left, right, .., \u00b1, \u2228, \u2227\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\u00b1(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 \u2227 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 \u2227 K` is the largest `ClosedInterval` contained in both.\nSee also `*`.\n\"\"\"\n(\u2227)(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 \u2228 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 \u2228 K` is the smalles `ClosedInterval` containing both. See also `+`.\n\"\"\"\n(\u2228)(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(\u2287)(J::ClosedInterval,K::ClosedInterval) = issubset(K,J)\n\n(\u228a)(J::ClosedInterval,K::ClosedInterval) = issubset(J,K) && !(J==K)\n(\u228b)(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\u03bb::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\u03bb), 2)\n        LLs[1] = log(d.w)\n        LLs[2] = log(1 - d.w) - exp(d.log\u03bb)\n        LL = logsumexp(LLs)\n    else\n        LL = log(1 - d.w) + logpdf(LogPoisson(d.log\u03bb), y)\n    end\n    return LL\nend\n\nfunction rand(d::ZIPoisson)\n    return rand() <= d.w ? 0 : rand(Poisson(exp(d.log\u03bb)))\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\u03bb ~ Normal(-1.5, 1)\n    w = inv_logit(a1)\n    data .~ ZIPoisson(log\u03bb, 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(\u03bb)\n\nProbability density function of distance ``d``.\n\n```math\ny = e^{-d/\u03bb}\n```\n\nwhere \u03bb is a shape parameter.\n\"\"\"\nBase.@kwdef struct ExponentialKernel{P} <: KernelFormulation\n    \u03bb::P = Param(1.0, bounds=(0.0, 2.0))\nend\n(f::ExponentialKernel)(d) = exp(-d / f.\u03bb)\n\n\"\"\"\n    GeometricKernel <: KernelFormulation\n\n    GeometricKernel(\u03b1)\n\nProbability density function of distance ``d``.\n\nThe Geometric kernel has a power-law decrease.\n\n```math\ny = (1+d)^\u03b1 (\u03b1+1)(\u03b1+2) / (2 \u03c0)\n```\n\nwhere \u03b1 is a shape parameter.\n\"\"\"\nBase.@kwdef struct GeometricKernel{P} <: KernelFormulation\n    \u03b1::P = Param(1.0, bounds=(-1000.0, 1000.0))\nend\n(f::GeometricKernel)(d) = (1 + d)^f.\u03b1 * ((f.\u03b1 + 1)*(f.\u03b1 + 2)) / (2 * \u03c0)\n\n\"\"\"\n    GaussianKernel <: KernelFormulation\n\n    GaussianKernel(\u03b1)\n\nProbability density function of distance ``d``.\n\n```math\ny = 1/ (\u03c0 \u03b1^2) e^{-d^2/\u03b1^2} \n```\n\nwhere \u03b1 is a positive parameter.\n\"\"\"\nBase.@kwdef struct GaussianKernel{P} <: KernelFormulation\n    \u03b1::P = Param(1.0, bounds=(0.0, 1000.0))\nend\n(f::GaussianKernel)(d) = 1 / (\u03c0 * f.\u03b1^2) * exp(- d^2 / f.\u03b1^2)\n\n\"\"\"\n    WeibullKernel <: KernelFormulation\n\n    WeibullKernel(\u03b1,\u03b2)\n\nProbability density function of distance ``d``.\n\n```math\ny =\u03b2 /(2 \u03c0 \u03b1^2) d^{\u03b2-2} e^{ -d^\u03b2/\u03b1^\u03b2} \n```\n\nwhere \u03b1 and \u03b2 are positive parameters.\n\"\"\"\nBase.@kwdef struct WeibullKernel{A,B} <: KernelFormulation\n    \u03b1::A = Param(1.0, bounds=(0.0, 1000.0))\n    \u03b2::B = Param(2.0, bounds=(0.0, 1000.0))\nend\n(f::WeibullKernel)(d) = f.\u03b2 / (2 * \u03c0 * f.\u03b1^2) * d^(f.\u03b2 - 2) * exp(- d^f.\u03b2 / f.\u03b1^f.\u03b2)", "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  \u0398(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) + \u03b3*n + 1/2 for this expected number gives in this case \n   \u2248 195.6011 + 28.8608 + 0.5 \u2248 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": "module FEOperatorsFromWeakForm\n\nusing Test\nusing Gridap.Helpers\nusing Gridap.Arrays\nusing Gridap.Algebra\nusing Gridap.TensorValues\nusing Gridap.ReferenceFEs\nusing Gridap.Geometry\nusing Gridap.Integration\nusing Gridap.Fields\nusing Gridap.FESpaces\nusing Gridap.CellData\n\nu(x) = x[1] + x[2]\nf(x) = -(3.0*x[1]+x[2]+1.0)\n\u03bd(u,x) = (u+1.0)*x[1]\nd\u03bd(du,x) = x[1]*du\n\ndomain = (0,1,0,1)\npartition = (4,4)\nmodel = CartesianDiscreteModel(domain,partition)\n\norder = 2\nreffe = ReferenceFE(lagrangian,Float64,order)\nV = FESpace(model,reffe,dirichlet_tags=\"boundary\")\nU = TrialFESpace(V,u)\n\ndegree = 3*order-1\ntrian = get_triangulation(model)\nd\u03a9 = Measure(trian,degree)\n\na(u,du,v) = \u222b( \u2207(v)\u22c5(\u03bd\u2218(u,identity)*\u2207(du)) )*d\u03a9\nres(u,v) = a(u,v,u) - \u222b(v*f)*d\u03a9\njac(u,du,v) = a(u,du,v) + \u222b( \u2207(v)\u22c5(d\u03bd\u2218(du,identity)*\u2207(u)) )*d\u03a9\n\nv = get_cell_shapefuns(V)\ndu = get_cell_shapefuns_trial(U)\nuh = zero(U)\n\nop = FEOperator(res,jac,U,V)\n\nuh = solve(op)\ne = u - uh\n\nel2 = sqrt(sum(\u222b( e*e )*d\u03a9))\neh1 = sqrt(sum(\u222b( e*e + \u2207(e)\u22c5\u2207(e) )*d\u03a9))\n\n@test el2 < 1.e-8\n@test eh1 < 1.e-7\n\ny = ones(num_free_dofs(U))\nuh = FEFunction(U,y)\nr = residual(op,uh)\nA = jacobian(op,uh)\ntest_fe_operator(op,y,r,\u2248,jac=A)\n\n#using Gridap.Visualization\n#writevtk(trian,\"trian\",celldata=[\"e\"=>cont])\n\n# Now with autodiff\n\nop = FEOperator(res,U,V)\ntest_fe_operator(op,y,r,\u2248,jac=A)\n\nuh = solve(op)\ne = u - uh\n\nel2 = sqrt(sum(\u222b( e*e )*d\u03a9))\neh1 = sqrt(sum(\u222b( e*e + \u2207(e)\u22c5\u2207(e) )*d\u03a9))\n\n@test el2 < 1.e-8\n@test eh1 < 1.e-7\n\nend # module\n", "meta": {"hexsha": "2c517db921761ee81f1b95271ca1b8f8fb7c270b", "size": 1462, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FESpacesTests/FEOperatorsFromWeakFormTests.jl", "max_stars_repo_name": "Paulms/Gridap.jl", "max_stars_repo_head_hexsha": "962da3b03647a3017fb2684f88106eae49db9051", "max_stars_repo_licenses": ["MIT"], "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/FESpacesTests/FEOperatorsFromWeakFormTests.jl", "max_issues_repo_name": "Paulms/Gridap.jl", "max_issues_repo_head_hexsha": "962da3b03647a3017fb2684f88106eae49db9051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T08:20:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T08:20:09.000Z", "max_forks_repo_path": "test/FESpacesTests/FEOperatorsFromWeakFormTests.jl", "max_forks_repo_name": "Paulms/Gridap.jl", "max_forks_repo_head_hexsha": "962da3b03647a3017fb2684f88106eae49db9051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-10T06:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T07:54:42.000Z", "avg_line_length": 19.2368421053, "max_line_length": 62, "alphanum_fraction": 0.6511627907, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7854140228739793}}
{"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]\u2019*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 \u2248 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": "using KroneckerProducts\nusing LinearAlgebra\nusing Test\n\na = rand(ComplexF64, 3, 2)\nb = rand(ComplexF64, 4, 5)\n\nk_big = kron(a,b)\n\nk = a \u2297 b\n\n@test k[1] == a[1]*b[1]\n@test k[end] == a[end]*b[end]\n@test k[1,1] == a[1,1]*b[1,1]\n@test k[end,end] == a[end,end]*b[end,end]\n\n@test k == k_big\n\n@test k' == k_big'\n@test transpose(k) == transpose(k_big)\n\n@test size(k) == size(k_big)\n\n@test eltype(k) == eltype(k_big)\n\ny = rand(ComplexF64, size(k,2))\nyr = rand(ComplexF64, size(k,1))\n\n@test k*y \u2248 k_big*y\n@test yr'*k \u2248 yr'*k_big\n\na = rand(ComplexF64, 3, 2)\nb = rand(ComplexF64, 2, 3)\nk_big = kron(a,b)\nk = KroneckerProduct(a,b)\n\n@test det(k) == 0\n@test abs(det(k_big)) < eps()\n\n@test tr(k) \u2248 tr(k_big)\n\na = rand(ComplexF64, 3, 3)\nb = rand(ComplexF64, 2, 2)\nk_big = kron(a,b)\nk = KroneckerProduct(a,b)\n\n@test det(k) \u2248 det(k_big)\n\n@test tr(k) \u2248 tr(k_big)\n\nyr = rand(ComplexF64, size(k,1))\n@test k\\yr \u2248 k_big\\yr\n", "meta": {"hexsha": "866f6483ecdf61cfa7bb405fc1d10ba89265b719", "size": 899, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "perrutquist/KroneckerProducts.jl", "max_stars_repo_head_hexsha": "8c0104caf1f17729eb067259ba1473986121d032", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-26T15:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T04:16:45.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "perrutquist/KroneckerProducts.jl", "max_issues_repo_head_hexsha": "8c0104caf1f17729eb067259ba1473986121d032", "max_issues_repo_licenses": ["MIT"], "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": "perrutquist/KroneckerProducts.jl", "max_forks_repo_head_hexsha": "8c0104caf1f17729eb067259ba1473986121d032", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:21:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:21:35.000Z", "avg_line_length": 16.9622641509, "max_line_length": 41, "alphanum_fraction": 0.6151279199, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.785380410517796}}
{"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": "\nusing ApproxFun\nusing PoincareInvariants: compute_integral, compute_derivative1, compute_derivative2\n\n\n### Test parameters ###\n\n# nx  = 20\n# ny  = 20\n# dtol = 1E-12\n# itol = 1E-11\n\nnx  = 100\nny  = 100\ndtol = 1E-10\nitol = 1E-16\n\nscale = 1E-00\n# scale = 1E-15\n\n\n### Set up ApproxFun spaces ###\n\nSC = Chebyshev(0..1)^2\nSU = Ultraspherical(1, 0..1)^2\nCU = Conversion(SC, SU)\n\n\n### check derivatives ###\n\n# compute x=(cos(2\u03c0\u03c4)cos(2\u03c0\u03c3)) on SC\npc = points(SC, nx*ny)\nxc = [scale * cos(2\u03c0*pc[i][1]) * cos(2\u03c0*pc[i][2]) for i in eachindex(pc)]\n\n# compute x=(cos(2\u03c0\u03c4)cos(2\u03c0\u03c3)) on SU\npu = points(SU, nx*ny)\nxu = [scale * cos(2\u03c0*pu[i][1]) * cos(2\u03c0*pu[i][2]) for i in eachindex(pu)]\n\n# create Fun and compute derivatives\nfun_xc = Fun(SC, transform(SC, xc))\nfun_xu = Fun(SU, transform(SU, xu))\n\nfx1 = compute_derivative1(fun_xc)\nfx2 = compute_derivative2(fun_xc)\n\n# compute \u03c4-derivative of x (-2\u03c0sin(2\u03c0\u03c4)cos(2\u03c0\u03c3))\npu = points(SU, length(fx1))\nx1 = [- 2\u03c0 * scale * sin(2\u03c0*pu[i][1]) * cos(2\u03c0*pu[i][2]) for i in eachindex(pu)]\n\n# compute \u03c3-derivative of x (-2\u03c0cos(2\u03c0\u03c4)sin(2\u03c0\u03c3))\npu = points(SU, length(fx2))\nx2 = [- 2\u03c0 * scale * cos(2\u03c0*pu[i][1]) * sin(2\u03c0*pu[i][2]) for i in eachindex(pu)]\n\n# compare Fun derivative and analytical derivative\n# println(maximum(abs.(fx1 .- x1)))\n# println(maximum(abs.(fx2 .- x2)))\n\n# the following test should fail but for some reason does not\n# (with nx=ny=20 success is expected for atol=5E-13 or larger)\n# @test fx1 \u2248 x1 atol=1E-15\n# @test fx2 \u2248 x2 atol=1E-15\n\n# this works, but is less compact\n@test (fx1 .- x1) \u2248 zero(fx1) atol=dtol*scale\n@test (fx2 .- x2) \u2248 zero(fx2) atol=dtol*scale\n\n\n### check integral ###\n\n# compute x=(cos(2\u03c0\u03c4)cos(2\u03c0\u03c3))\npu = points(SU, nx*ny)\nx  = zeros(length(pu))\n\nfor i in eachindex(x,pu)\n    x[i] = scale * cos(2\u03c0*pu[i][1]) * cos(2\u03c0*pu[i][2])\nend\n\n@test compute_integral(x) \u2248 0.0 atol=itol*scale\n", "meta": {"hexsha": "e9cbc5ed68a36d253f5751b892f610aff756a898", "size": 1841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/poincare_invariant_2nd_unittests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PoincareInvariants.jl-26663084-47d3-540f-bd97-40ca743aafa4", "max_stars_repo_head_hexsha": "6ffd319bc052a99cecde88b87b4b72f593eff73f", "max_stars_repo_licenses": ["MIT"], "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/poincare_invariant_2nd_unittests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PoincareInvariants.jl-26663084-47d3-540f-bd97-40ca743aafa4", "max_issues_repo_head_hexsha": "6ffd319bc052a99cecde88b87b4b72f593eff73f", "max_issues_repo_licenses": ["MIT"], "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/poincare_invariant_2nd_unittests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PoincareInvariants.jl-26663084-47d3-540f-bd97-40ca743aafa4", "max_forks_repo_head_hexsha": "6ffd319bc052a99cecde88b87b4b72f593eff73f", "max_forks_repo_licenses": ["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.3037974684, "max_line_length": 84, "alphanum_fraction": 0.6469310158, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7853803984062516}}
{"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\u00d7N` 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 (\u2264 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, \u03bc::AbstractVector, \u03a3::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, \u03bc::AbstractVector, \u03a3::AbstractMatrix; ncontours=2, color=\"blue\", label=\"\", args...)\n    \u03bb, U = eigen(\u03a3)\n    for i in 1:ncontours\n        B = U * diagm(i * sqrt.(\u03bb))\n        \u03b8 = range(0, stop=2 * pi, length=1000)\n        circle = hcat(sin.(\u03b8), cos.(\u03b8))'\n        contour = B * circle .+ \u03bc\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": "using NHST\n\n@assert isapprox(p_value(BinomialTest, 0, 10, 0.5), 0.001953125)\n@assert isapprox(p_value(BinomialTest, 5, 10, 0.5), 1.0)\n@assert isapprox(p_value(BinomialTest, 10, 10, 0.5), 0.001953125)\n@assert isapprox(p_value(BinomialTest, 4, 10, 0.2), 0.1208739)\n@assert isapprox(p_value(BinomialTest, 2, 10, 0.8), 7.79264e-05)\n@assert isapprox(p_value(BinomialTest, 3, 100, 0.5), 2.630867e-25)\n@assert isapprox(p_value(BinomialTest, 97, 100, 0.5), 2.630867e-25)\n@assert isapprox(p_value(BinomialTest, 3, 10, 0.79), 0.001178273)\n@assert isapprox(p_value(BinomialTest, 9, 10, 0.79), 0.6989298)\n\np_value(BinomialTest, 0, 10, 0.5)\np_value(BinomialTest, 0.0, 10, 0.5)\np_value(BinomialTest, 0, 10.0, 0.5)\np_value(BinomialTest, 0.0, 10.0, 0.5)\np_value(BinomialTest, zeros(10), 0.5)\n\nrun(BinomialTest, 0, 10, p = 0.5)\nrun(BinomialTest, 0.0, 10, p = 0.5)\nrun(BinomialTest, 0, 10.0, p = 0.5)\nrun(BinomialTest, 0.0, 10.0, p = 0.5)\nrun(BinomialTest, zeros(10), p = 0.5)\n\n@assert isapprox(p_value(run(BinomialTest, 0, 10, p = 0.5)), 0.001953125)\n@assert isapprox(p_value(run(BinomialTest, 5, 10, p = 0.5)), 1.0)\n@assert isapprox(p_value(run(BinomialTest, 10, 10, p = 0.5)), 0.001953125)\n@assert isapprox(p_value(run(BinomialTest, 4, 10, p = 0.2)), 0.1208739)\n@assert isapprox(p_value(run(BinomialTest, 2, 10, p = 0.8)), 7.79264e-05)\n", "meta": {"hexsha": "c5d88d469b229245e1c78239d8acb0e0997ca1c9", "size": 1321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/binomial.jl", "max_stars_repo_name": "UnofficialJuliaMirror/NHST.jl-be8ae513-ad44-5dbc-aa0f-d9cd1b2c73a9", "max_stars_repo_head_hexsha": "19cf35539ed8292abe400abc9a930c2f6050d3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-06-15T14:12:35.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-18T10:58:44.000Z", "max_issues_repo_path": "test/binomial.jl", "max_issues_repo_name": "UnofficialJuliaMirror/NHST.jl-be8ae513-ad44-5dbc-aa0f-d9cd1b2c73a9", "max_issues_repo_head_hexsha": "19cf35539ed8292abe400abc9a930c2f6050d3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-04T17:27:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:31:30.000Z", "max_forks_repo_path": "test/binomial.jl", "max_forks_repo_name": "UnofficialJuliaMirror/NHST.jl-be8ae513-ad44-5dbc-aa0f-d9cd1b2c73a9", "max_forks_repo_head_hexsha": "19cf35539ed8292abe400abc9a930c2f6050d3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-06-15T14:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:31:23.000Z", "avg_line_length": 44.0333333333, "max_line_length": 74, "alphanum_fraction": 0.7002271007, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7853209126049361}}
{"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\u00b2\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 OrdinaryDiffEq, LinearAlgebra, Test\r\n\r\nfunction dynamics!(dx,x,\u03b8,t)\r\n    zmin, zmax, M, g = \u03b8\r\n    z, dz, p = x\r\n\r\n    dx[1] = dz  \r\n    dx[2] = -M*g -z + p\r\n    dx[3] = p-w(t) # the last state (algebraic) p has to be equal to w\r\n\r\n    if z <= zmin\r\n        dx[2] = max(dx[2], 0.0)\r\n    elseif z >= zmax\r\n        dx[2] = min(dx[2], 0.0)\r\n    end\r\nend\r\n\r\nw(t) = .1*(7.0+3.0sin(t))\r\nzmin_cond(x,t,integrator) =  x[1]-zmin\r\nzmax_cond(x,t,integrator) =  zmax-x[1]\r\n\r\nfunction zmin_affect_neg!(integrator)\r\n    integrator.u[1] = zmin\r\n    integrator.u[2] = 0.0\r\nend\r\n\r\nfunction zmax_affect_neg!(integrator)\r\n    integrator.u[1] = zmax\r\n    integrator.u[2] = 0.0\r\nend\r\n\r\ncbs = CallbackSet(\r\n    ContinuousCallback(zmin_cond,zmin_affect_neg!),\r\n    ContinuousCallback(zmax_cond,zmax_affect_neg!)\r\n)\r\n\r\ntf = 20.0\r\ntspan = (0.0,tf)\r\n\r\nzmin = 1.0e-3\r\nzmax = 2.0e-2\r\nM = 0.05\r\ng = 9.81\r\n\u03b8 = zmin, zmax, M, g\r\n\r\nx0 = [(zmin+zmax)/2,0.0,w(0.0)]\r\n\r\nE = diagm([1.0,M,0.0])\r\n\r\nf = ODEFunction(dynamics!,mass_matrix=E)\r\nprob = ODEProblem(f,x0,tspan,\u03b8)\r\n\r\nsol1 = solve(prob,Rodas4(), callback = cbs, reltol=1e-6)\r\n@test sol1(0.06692341688237893)[3] \u2248 0.72 atol=1e-2\r\nsol1 = solve(prob,Rodas5(), callback = cbs, reltol=1e-6)\r\n@test sol1(0.06692341688237893)[3] \u2248 0.72 atol=1e-2\r\nsol1 = solve(prob,Rodas5P(), callback = cbs, reltol=1e-6)\r\n@test sol1(0.06692341688237893)[3] \u2248 0.72 atol=1e-2\r\n\r\n#=\r\nsol1 = solve(prob,Rosenbrock23(),callback=cbs, reltol=1e-6)\r\n@test sol1(1.0)[3] \u2248 0.95 atol=1e-2\r\n=#\r\n", "meta": {"hexsha": "987baeb052a66cfa46de40bafe7766d1caf866ca", "size": 1486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interface/event_dae_addsteps.jl", "max_stars_repo_name": "JuliaDiffEq/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "627bed066f476aeedb429c27e8b96ad856c39946", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 133, "max_stars_repo_stars_event_min_datetime": "2016-11-08T01:13:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T10:24:54.000Z", "max_issues_repo_path": "test/interface/event_dae_addsteps.jl", "max_issues_repo_name": "JuliaDiffEq/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "627bed066f476aeedb429c27e8b96ad856c39946", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 989, "max_issues_repo_issues_event_min_datetime": "2016-10-28T08:06:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-24T21:58:37.000Z", "max_forks_repo_path": "test/interface/event_dae_addsteps.jl", "max_forks_repo_name": "JuliaDiffEq/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "627bed066f476aeedb429c27e8b96ad856c39946", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 109, "max_forks_repo_forks_event_min_datetime": "2016-10-27T18:21:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-21T10:38:08.000Z", "avg_line_length": 23.21875, "max_line_length": 71, "alphanum_fraction": 0.6022880215, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642533380189, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7852944874101568}}
{"text": "using PyPlot\nusing LinearAlgebra\n\na = [ 0.5  -1.0   0.25\n      1.0   0.5  -1.0 ]\n\nfunction points(\u03bb, offset)\n    x = zeros(2,3)\n    x[:,1] .= (1-2\u03bb) * a[:,1] +      \u03bb * a[:,2] +      \u03bb * a[:,3]\n    x[:,2] .=      \u03bb * a[:,1] + (1-2\u03bb) * a[:,2] +      \u03bb * a[:,3]\n    x[:,3] .=      \u03bb * a[:,1] +      \u03bb * a[:,2] + (1-2\u03bb) * 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\u0303(t) supported on\n# [-1,1]\n# such that\n#       1. H*w\u0303 == V'(b*t)\n#       2. sum(w\u0303) == 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\u0303 = U \\H*W\n    [1/(b*sum(W[:,1])); 2H\u0303[:,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 \u00b1b accurate\n    Weighted(U)[affine(-b..b,axes(T,1)),:] * ((Weighted(T) \\ Weighted(U))[3:end,:] \\ equilibriumcoefficients(T,b)[3:end])\nend\n\n\u03bc = equilibrium(sqrt(2))\n\nT = Chebyshev()\nb = sqrt(2)\n\u03bc = Weighted(T) * equilibriumcoefficients(T, b)\nx = axes(\u03bc,1)\n\nplot(\u03bc)\n\nxx = 0.7; 2b*(log.(abs.(x .- x'))*\u03bc)[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#\u00a0with two intervals of support consists of finding \n# a measure w(x) supported on\n# [-b,-a] \u222a [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\u0303(t) supported on\n# [-1,-a/b] \u222a [a/b,1]\n# such that\n#       1. H*w\u0303 == V'(b*t)\n#       2. sum(w\u0303) == 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\u0303 = Q \\ H*W\n    [1/(b*sum(W[:,1])); 2H\u0303[:,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 - \u03c1^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\u03bc = equilibrium(ab)\n\u03bcx = x -> a < abs(x) < b ? \u03bc[x/b] : 0.0\nplot!(xx, \u03bcx.(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 \u2208 [-5, 10], for all i = 1, \u2026, 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": "\"\"\"\n    CircularArc2(c::Circle2)\n\nConstructs an arc from a full circle.\n\"\"\"\nCircularArc2(c::Circle2)\n\n\"\"\"\n    CircularArc2(c::Circle2, p::Point2, q::Point2)\n\nConstructs the circular arc supported by `c`, whose source is `p` and whose\ntarget is `q` when traversing the circle in counterclockwise direction.\n\nIf `p` and `q` are the same, the arc is in fact a full circle.\n\n!!! info \"Precondition\"\n\n    `p` and `q` lie on `c`.\n\"\"\"\nCircularArc2(c::Circle2, p::Point2, q::Point2)\n\n\"\"\"\n    CircularArc2(p::Point2, q::Point2, r::Point2)\n\nConstructs an arc that is supported by the circle of type [`Circle2`](@ref)\npassing through points `p`, `q` and `r`.\n\nThe source and target are respectively `p` and `r`, when traversing the\nsupporting circle in the counterclockwise direction.  Note that, depending on\nthe orientation of the point triple `(p,q,r)`, `q` may not lie on the arc.\n\n!!! info \"Precondition\"\n\n    `p`, `q`, and `r` are not collinear.\n\"\"\"\nCircularArc2(p::Point2, q::Point2, r::Point2)\n\n\"\"\"\n    supporting_circle(ca::CircularArc2)\n\nReturns the supporting circle of `ca`.\n\"\"\"\nsupporting_circle(ca::CircularArc2)\n\n\"\"\"\n    center(ca::CircularArc2)\n\nReturns the center of `ca`'s supporting circle.\n\"\"\"\ncenter(ca::CircularArc2)\n\n\"\"\"\n    squared_radius(ca::CircularArc2)\n\nReturns the squared radius of `ca`'s supporting circle.\n\"\"\"\nsquared_radius(ca::CircularArc2)\n\n\"\"\"\n    source(ca::CircularArc2)\n\nReturns the arc's starting point, supposing its supporting circle is\ntraversed in counterclockwise direction.\n\"\"\"\nsource(ca::CircularArc2)\n\n\"\"\"\n    target(ca::CircularArc2)\n\nReturns the arc's ending point, supposing its supporting circle is traversed\nin counterclockwise direction.\n\"\"\"\ntarget(ca::CircularArc2)\n\n\"\"\"\n    left(ca::CircularArc2)\n\nReturns the arc's leftmost point.\n\n!!! info \"Precondition\"\n\n    `is_x_monotone(ca)`\n\"\"\"\nleft(ca::CircularArc2)\n\n\"\"\"\n    right(ca::CircularArc2)\n\nReturns the arc's rightmost point.\n\n!!! info \"Precondition\"\n\n    `is_x_monotone(ca)`\n\"\"\"\nright(ca::CircularArc2)\n\n\"\"\"\n    bbox(ca::CircularArc2)\n\nReturns a bounding box containing the arc.\n\"\"\"\nbbox(ca::CircularArc2)\n\n\"\"\"\n    is_x_monotone(ca::CircularArc2)\n\nTests whether the arc is x-monotone.\n\"\"\"\nis_x_monotone(ca::CircularArc2)\n\n\"\"\"\n    is_y_monotone(ca::CircularArc2)\n\nTests whether the arc is y-monotone.\n\"\"\"\nis_y_monotone(ca::CircularArc2)\n\n\"\"\"\n==(ca\u2081::CircularArc2, ca\u2082::CircularArc2)\n\nTest for equality.\n\nTwo arcs are equal, iff their non-oriented supporting circles are equal (i.e.\nthey have the same center and same squared radius) and their endpoints are\nequal.\n\"\"\"\n==(ca\u2081::CircularArc2, ca\u2082::CircularArc2)\n", "meta": {"hexsha": "027464275296d84d27ab557393570d844de3ff1c", "size": 2606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/circular_arc_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/circular_arc_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/circular_arc_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": 20.359375, "max_line_length": 77, "alphanum_fraction": 0.7075978511, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7852821214955912}}
{"text": "function toCartesian(lon, lat; r = 1, cxyz = (0,0,0) )\n    lat, lon = lat*\u03c0/180, lon*\u03c0/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    \u0398 = LinRange(0, 2\u03c0, 500) # 50\n    \u03a6 = LinRange(0, \u03c0, 500)\n    x0 = [cxyz[1] + r * cos(\u03b8) * sin(\u03d5)      for \u03b8 in \u0398, \u03d5 in \u03a6]\n    y0 = [cxyz[2] + r * sin(\u03b8) * sin(\u03d5)      for \u03b8 in \u0398, \u03d5 in \u03a6]\n    z0 = [cxyz[3] + r * cos(\u03d5) for \u03b8 in \u0398, \u03d5 in \u03a6]\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 EngEconomics\n\n# Given\naInit = 680\nbInit = 1100\naAnnualSavings = 245\nbAnnualSavings = 440\naAnnualMaintenance = 35\naAnnualMaintenanceg = 10\nbAnnualMaintenance = 60\naServiceLife = 4\nbServiceLife = 6\naScrapValue = 100\nbScrapValue = 250\n\n# Find\n# a.) Use PW Method to determine which is better\nMARR = 0.1\nyears = 12 # Just knew b/c it's the least common multiple of 4 and 6s\naPeriods = years / aServiceLife\nbPeriods = years / bServiceLife\n\n# Product A\naMultiplicand = 1 + presentWorthFactor(MARR, aServiceLife) + presentWorthFactor(MARR, 2 * aServiceLife)\naInitPW = -aInit * aMultiplicand\naAnnualSavingsPW = aAnnualSavings *\n\t\tseriesPresentAmountFactor(MARR, years)\naAnnualMaintenancePW = -aAnnualMaintenance *\n\t\taAnnualMaintenanceg * sinkingFundPaymentArithmetic(MARR, aServiceLife) *\n\t\taMultiplicand\naScrapValuePW = aScrapValue *\n\t\t(presentWorthFactor(MARR, aServiceLife) +\n\t\tpresentWorthFactor(MARR, 2 * aServiceLife) +\n\t\tpresentWorthFactor(MARR, 3 * aServiceLife))\naPW = aInitPW + aAnnualSavingsPW + aAnnualMaintenancePW + aScrapValuePW\n\n# Product B\n\n\nif aPW > bPW\n\tprintln(\"CR1000 is better\")\nelse\n\tprintln(\"CRX is better\")\nend\n", "meta": {"hexsha": "590bff54fa0d748f6310886a1532ce77041e5113", "size": 1134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps4/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/ps4/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/ps4/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": 25.2, "max_line_length": 103, "alphanum_fraction": 0.7733686067, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561703644737, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7852374938330834}}
{"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\u1d63,n\u2093,n\u2083 = u\r\n#     k\u2081,k\u208b\u2081,k\u2082,k\u208b\u2082 = cons\r\n#     m\u1d63,m\u2097,m\u2093,A = dens\r\n#     z = L(u,p)\r\n#     # model\r\n#     du[1] = dn\u1d63 = A*k\u2081*m\u1d63*m\u2097 - k\u208b\u2081*n\u1d63 + z[1]\r\n#     du[2] = dn\u2093 = A*k\u2082*m\u2093*m\u2097 - k\u208b\u2082*n\u2093 + z[2]\r\n#     du[3] = dn\u2083 = 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\u1d63 = u[1]\r\n    k\u2081,k\u208b\u2081  = p\r\n    m\u1d63,m\u2097,A = dens\r\n    # model\r\n    du[1] = dn\u1d63 = A*k\u2081*m\u1d63*m\u2097 - k\u208b\u2081*n\u1d63\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\u2099 = 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\u1d63 = u[1]\r\n    k\u2081,k\u208b\u2081  = p\r\n    m\u1d63,m\u2097,A = dens\r\n    z = L(u,p)\r\n    # model\r\n    du[1] = dn\u1d63 = 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(\u03b8)\r\n\r\n    tmp_prob = remake(prob_nn,u0=u0,p=\u03b8)\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    # \u03a3_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(\u03b8)\r\n    pred = predict(\u03b8)\r\n    sum(abs2, X\u2099 .- pred), pred\r\nend\r\n\r\n# Test\r\n@time loss(p)\r\n\r\nconst losses = []\r\n\r\ncallback(\u03b8,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\u2099')\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\u2099')\r\nsavefig(\"fit\")\r\n\r\n\r\nL\u0302 = L(X\u2099,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 \u2208 1:2\r\n#     push!(polys, u[1]^i)\r\n#     push!(polys, u[2]^i)\r\n#     for j \u2208 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# \u03bb = 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# # \u03a8 = SINDy(X\u2099[:, :], DX[:, :], basis, \u03bb, opt, g = g, maxiter = 10000) # Fail\r\n# # println(\u03a8)\r\n# # print_equations(\u03a8)\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# # \u03a8 = SINDy(X\u2099[:, 1:end], L\u0304[:, 1:end], basis, \u03bb,opt, g = g, maxiter = 10000) # Succeed\r\n# # println(\u03a8)\r\n# # print_equations(\u03a8)\r\n#\r\n# # Test on uode derivative data\r\n# println(\"SINDy on learned, partial, available data\")\r\n# \u03a8 = SINDy(X\u2099[:, 2:end], L\u0302[:, 2:end], basis, \u03bb,  opt, g = g, maxiter = 100000, normalize = true, denoise = true) # Succeed\r\n# println(\u03a8)\r\n# print_equations(\u03a8)\r\n#\r\n# # Extract the parameter\r\n# p\u0302 = parameters(\u03a8)\r\n# println(\"First parameter guess : $(p\u0302)\")\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\u03bb = 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# \u03a8 = SInDy(X[:, 1:1000], DX[:, 1:1000], basis, maxiter = 10000, opt = opt, normalize = true)\r\n\u03a8 = SINDy(X\u2099[:, 2:end], L\u0302[:, 2:end], basis, \u03bb,  opt, g = g, maxiter = 10000, normalize = true) # Succeed\r\n# \u03a8 = SINDy(X\u2099[:, 2:end], L\u0302[:, 2:end], basis, maxiter = 10000, opt = opt, normalize = true,denoise = true)\r\nprintln(\u03a8)\r\nprint_equations(\u03a8)\r\n\r\nsys = ODESystem(\u03a8)\r\np = parameters(\u03a8)\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\u2099,Tsit5(),maxiters=10000)\r\n\r\ncost_function = build_loss_objective(estimator,Tsit5(),L2Loss(solution.t,X\u2099),\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(\u03a8)\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# \u03a8f = SINDy(X\u2099[:, 2:end], L\u0302[:, 2:end], b, STRRidge(0.01), maxiter = 100, convergence_error = 1e-18) # Succeed\r\n# println(\u03a8f)\r\n# p\u0302 = parameters(\u03a8f)\r\n# println(\"Second parameter guess : $(p\u0302)\")\r\n#\r\n# # Create function\r\n# recovered_sys = ODESystem(\u03a8f)\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(\u03be::Vector{T}) where {T}\n        Bernstein(ScatteredGrid(\u03be, 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(\u03be, a::Number, b::Number) = rescale(Bernstein(\u03be), 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}, \u03be::Vector{T}) where {T} = Bernstein(\u03be)\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": "const score_table = (1 => 10, 5 => 5, 10 => 1)\n\n\"\"\"\n    score(x, y)\n\nReturn the score earned by a dart landing at coordinates (x, y).\n\"\"\"\nfunction score(x, y)\n    z = hypot(x, y)\n    for (radius, points) in score_table\n        z <= radius && return points\n    end\n    return 0\nend\n", "meta": {"hexsha": "eef8e08a800c1b2922c41a9cffdc93a05c335750", "size": 281, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/darts/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/darts/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/darts/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": 18.7333333333, "max_line_length": 64, "alphanum_fraction": 0.5800711744, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7851667685307459}}
{"text": "\"\"\"\n   shi(x) \n   \n   hyperbolic sine integral function \n   \n   shi(x) = \u2080\u222b\u02e3 (sinh(t) / t) \u03b4t \n\"\"\" shi\n\n\"\"\"\n    chi(x)\n    \n    hyperbolic cosine integral\n    \nchi(x) = \u03b3 + ln(x) + \u2080\u222b\u02e3 ((cosh(t) - 1) / t) \u03b4t \nwhere \u03b3 == 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) =  \u1d64\u222b\u02e3 (\u03b4t / 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) = \u2080\u222b\u02e3 (sin(t) / t) \u03b4t\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": "include(\"util.jl\")\ninclude(\"../../src/CGPO.jl\")  \n\nfunction PerformCGFor(\n    A::AbstractMatrix, \n    b::AbstractVecOrMat;\n    epsilon=1e-2,\n    exact::Bool=true, \n    partial_ortho=nothing,\n)\n    cg = CGPO(A, b)\n    \n    if exact\n        \n    else\n        if partial_ortho === nothing\n            cg |> TurnOffReorthgonalize!\n        else\n            StorageLimit!(cg, partial_ortho)\n        end\n    end\n\n    x\u0307 = A\\b\n    e\u0307 = x\u0307 - cg.x\n    e\u0307Ae\u0307 = dot(e\u0307, A*e\u0307)\n    E = Vector{Float64}()\n    push!(E, 1)\n    RelErr = 1\n    while RelErr > epsilon\n        cg()\n        e = x\u0307 - cg.x\n        RelErr = (dot(e, A*e)/e\u0307Ae\u0307)|>sqrt\n        push!(E, RelErr)\n    end\n    return E\nend\n\nE = PerformCGFor(Diagonal(rand(10)), rand(10))\n\nfunction PerformExperiment1(filename, p=0.9)\n    N = 256\n    A = GetNastyPSDMatrix(N, p)\n    b = rand(N)\n    A = convert(Matrix{Float16}, A)\n    b = convert(Vector{Float16}, b)\n    # TODO: Make the plot distinguishable without colors. \n\n    # ==========================================================================\n    # The exact computations\n    # ==========================================================================\n\n    RelErr = PerformCGFor(A, b, epsilon=1e-3, exact=true)\n    k = length(RelErr)\n    fig1 = plot(\n        RelErr, \n        label=\"Relative Energy (exact)\", \n        legend=:bottomleft,\n        yaxis=:log10, \n        xlabel=\"iterations: k\", \n        ylabel=\"\\$\\\\frac{\\\\Vert e_k \\\\Vert_A}{\\\\Vert e_0\\\\Vert_A}\\$\",\n        title=\"CG Rel Energy Error \\$\\\\rho = $(p)\\$\",\n        size=(750, 500), dpi=300, \n        left_margin = 10Plots.mm\n    )\n\n    # ==========================================================================\n    # No-Orthogonalizations\n    # ==========================================================================\n\n    RelErr = PerformCGFor(A, b, exact=false, epsilon=1e-3)\n    k = length(RelErr)\n    plot!(\n        fig1, \n        RelErr, \n        label=\"Relative Energy (floats)\",\n        linestyle=:dash#, markershape=:+\n    )\n\n    # ==========================================================================\n    # Theoretical Bounds\n    # ==========================================================================\n    ErrorsBound = [TheoreticalErrorBound(A, idx) for idx in 1: k]\n    plot!(\n        fig1, \n        ErrorsBound, \n        label=\"Theoretical Bound (exact)\",\n        linestyle=:dot\n    )\n\n    # ==========================================================================\n    # Floating Points Partially Orthogonalized\n    # ==========================================================================\n    RelErr = PerformCGFor(A, b, exact=false, epsilon=1e-3, partial_ortho=div(N, 8))\n    k = length(RelErr)\n    plot!(\n        fig1, \n        RelErr, \n        label=\"Relative Energy (partial)\",\n        legend=:bottomleft, \n        linestyle=:dashdot # ,  markershape=:x\n    )\n\n    display(fig1)\n    SaveFigToCurrentScriptDir(fig1, \"$(filename).png\")\n\n    \nreturn end\n\nPerformExperiment1(\"cg_convergence_0.9\")\nPerformExperiment1(\"cg_convergence_1\", 1)\n", "meta": {"hexsha": "198f89143961d7ffa40940678a697efe5352dd31", "size": 3033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "numerical_experiments/CG_Convergence2/experiments.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_Convergence2/experiments.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_Convergence2/experiments.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": 27.3243243243, "max_line_length": 83, "alphanum_fraction": 0.4457632707, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.7851569751254297}}
{"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, \u03bc::Real, \u03c3::Real)\n    # Z and X are assumed to have the same size\n    i\u03c3 = inv(\u03c3)\n    if \u03bc == zero(\u03bc)\n        for i = 1 : length(X)\n            @inbounds Z[i] = X[i] * i\u03c3\n        end\n    else\n        for i = 1 : length(X)\n            @inbounds Z[i] = (X[i] - \u03bc) * i\u03c3\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}, \u03bc::AbstractArray, \u03c3::AbstractArray)\n    # Z and X are assumed to have the same size\n    # \u03bc and \u03c3 are assumed to have the same size, that is compatible with size(X)\n    siz1 = size(X, 1)\n    @nextract N ud d->size(\u03bc, d)\n    if size(\u03bc, 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 \u03bc j)\n            c = inv(@nref N \u03c3 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 \u03bc j)) / (@nref N \u03c3 j)\n        end\n    end\n    return Z\nend\n\nfunction _zscore_chksize(X::AbstractArray, \u03bc::AbstractArray, \u03c3::AbstractArray)\n    size(\u03bc) == size(\u03c3) || throw(DimensionMismatch(\"\u03bc and \u03c3 should have the same size.\"))\n    for i=1:ndims(X)\n        d\u03bc_i = size(\u03bc,i)\n        (d\u03bc_i == 1 || d\u03bc_i == size(X,i)) || throw(DimensionMismatch(\"X and \u03bc have incompatible sizes.\"))\n    end\nend\n\nfunction zscore!{ZT<:FloatingPoint,T<:Real}(Z::AbstractArray{ZT}, X::AbstractArray{T}, \u03bc::Real, \u03c3::Real)\n    size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n    _zscore!(Z, X, \u03bc, \u03c3)\nend\n\nfunction zscore!{ZT<:FloatingPoint,T<:Real,U<:Real,S<:Real}(Z::AbstractArray{ZT}, X::AbstractArray{T}, \n                                                            \u03bc::AbstractArray{U}, \u03c3::AbstractArray{S})\n    size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n    _zscore_chksize(X, \u03bc, \u03c3)\n    _zscore!(Z, X, \u03bc, \u03c3)\nend\n\nzscore!{T<:FloatingPoint}(X::AbstractArray{T}, \u03bc::Real, \u03c3::Real) = _zscore!(X, X, \u03bc, \u03c3)\n\nzscore!{T<:FloatingPoint,U<:Real,S<:Real}(X::AbstractArray{T}, \u03bc::AbstractArray{U}, \u03c3::AbstractArray{S}) = \n    (_zscore_chksize(X, \u03bc, \u03c3); _zscore!(X, X, \u03bc, \u03c3))\n\nfunction zscore{T<:Real}(X::AbstractArray{T}, \u03bc::Real, \u03c3::Real)\n    ZT = typeof((zero(T) - zero(\u03bc)) / one(\u03c3))\n    _zscore!(Array(ZT, size(X)), X, \u03bc, \u03c3)\nend\n\nfunction zscore{T<:Real,U<:Real,S<:Real}(X::AbstractArray{T}, \u03bc::AbstractArray{U}, \u03c3::AbstractArray{S})\n    _zscore_chksize(X, \u03bc, \u03c3)\n    ZT = typeof((zero(T) - zero(U)) / one(S))\n    _zscore!(Array(ZT, size(X)), X, \u03bc, \u03c3)\nend\n\nzscore{T<:Real}(X::AbstractArray{T}) = ((\u03bc, \u03c3) = mean_and_std(X); zscore(X, \u03bc, \u03c3))\nzscore{T<:Real}(X::AbstractArray{T}, dim::Int) = ((\u03bc, \u03c3) = mean_and_std(X, dim); zscore(X, \u03bc, \u03c3))\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": "function division(a, b)\n\tk=0\n    while a*k<b\n        k = k+1\n    end\n    return k\nend\n\nfunction syra(n::Int64)\n\tif n==1\n        return 0\n    elseif n%2 == 0\n        return 1 + syra(division(2,n))\n    else\n        return 1 + syra(3*n+1)\n    end\nend\n\nprintln(syra(42))\n\n", "meta": {"hexsha": "266ea658f4f449280ec2abf8176afc506330b91e", "size": 268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/exec/syracuse.jl", "max_stars_repo_name": "gabriel-doriath-dohler/pjulia", "max_stars_repo_head_hexsha": "14325f282b711c979091ec259aefb0f1e89ec1be", "max_stars_repo_licenses": ["MIT"], "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/exec/syracuse.jl", "max_issues_repo_name": "gabriel-doriath-dohler/pjulia", "max_issues_repo_head_hexsha": "14325f282b711c979091ec259aefb0f1e89ec1be", "max_issues_repo_licenses": ["MIT"], "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/exec/syracuse.jl", "max_forks_repo_name": "gabriel-doriath-dohler/pjulia", "max_forks_repo_head_hexsha": "14325f282b711c979091ec259aefb0f1e89ec1be", "max_forks_repo_licenses": ["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.7619047619, "max_line_length": 38, "alphanum_fraction": 0.5223880597, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7851028644720124}}
{"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 \u03bcs (526 allocations: 155.34 KiB)\n\njulia> @btime contiguous(25, list);\n  503.429 \u03bcs (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": "# doubly periodic dipole\n# https://dx.doi.org/10.1103/PhysRevLett.112.145301\n# should be eigenstate of Hamiltonian evolution\n\nusing Test, Plots, Revise, VortexDistributions\n\n# test dipole\nxp = 20\nyp = 3\nvp = PointVortex(xp,yp,1)\n\nxn = 1.1\nyn = -3\nvn = PointVortex(xn,yn,-1)\n\n\n\nThetad(.12,.11,xp,yp,xn,yn)\n\nx = LinRange(-\u03c0,\u03c0,300)\ny = x\n\n#TODO add missing method for Thetad(x,y,dipole::Array{PointVortex})\n# test double periodicity\ntestpsi = exp.(im*Thetad(x,y,xp,yp,xn,yn))\n@test testpsi[end,:] \u2248 testpsi[1,:]\n@test testpsi[:,1] \u2248 testpsi[:,end]\nheatmap(x,y,angle.(testpsi),transpose=true)\n\n# test domain\nx = LinRange(-3\u03c0,3\u03c0,300)\ny = LinRange(-4\u03c0,4\u03c0,300)\n\n# test dipole\nxp = 2.1*pi\nyp = 2*pi\n\nxn = -2*pi\nyn = -2.4*pi\n\ntestphase3 = Thetad(x,y,xp,yp,xn,yn)\nheatmap(x,y,testphase3,transpose=true)\n\npsivort = Torus(exp.(im*testphase3),x,y)\nvortices = findvortices(psivort)\n\nvraw = rawData(vortices)\n\ntestpsi = exp.(im*testphase3)\n@test testpsi[:,1] \u2248 testpsi[:,end]\n@test testpsi[1,:] \u2248 testpsi[end,:]\n\n\n#--- add new method for making periodic dipoles\nusing Test, Plots, Revise, VortexDistributions\n\nx = LinRange(-50,50,300)\ny = x\n\n# test dipole\nxp = 20\nyp = 3\nvp = PointVortex(xp,yp,1)\n\nxn = 1.1\nyn = -3\nvn = PointVortex(xn,yn,-1)\n\ndip = ScalarVortex([vp;vn])\n\nfunction periodic_dipole!(psi::F,dip::Array{ScalarVortex{T},1}) where {T <: CoreShape, F<:Field}\n    @assert length(dip) == 2\n    @assert dip[1].vort.qv + dip[2].vort.qv == 0\n    @assert hypot(dip[1].vort.xv-dip[2].vort.xv,dip[1].vort.yv-dip[2].vort.yv) >= 2*pi\n    @unpack \u03c8,x,y = psi\n    (dip[1].vort.qv > 0) ? (jp = 1;jn = 2) : (jp = 2;jn = 1)\n    vp = rawData(dip[jp].vort)[1:2]\n    vn = rawData(dip[jn].vort)[1:2]\n    @. \u03c8 *= abs(dip[jn](x,y')*dip[jp](x,y'))\n    \u03c8 .*= exp.(im*Thetad(x,y,vp...,vn...))\n    @pack! psi = \u03c8\nend\n\npsivort = Torus(one.(x.*y'),x,y)\n\nheatmap(abs2.(psivort.\u03c8))\n\nperiodic_dipole!(psivort,dip)\n\nheatmap(x,y,abs2.(psivort.\u03c8))\n\nheatmap(x,y,angle.(psivort.\u03c8))\n\n#check that phase is periodic (note we don't enforce periodic density)\n\ntestpsi = angle.(psivort.\u03c8)\n@test testpsi[:,1] \u2248 testpsi[:,end]\n@test testpsi[1,:] \u2248 testpsi[end,:]\n", "meta": {"hexsha": "1e0c12e8dd3f9e52b24797d90c26cc0ee48cf6d9", "size": 2115, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dipole_periodic.jl", "max_stars_repo_name": "mcawte/VortexDistributions.jl", "max_stars_repo_head_hexsha": "6b67e5fad661c196f887a0a15069582617a8ecc5", "max_stars_repo_licenses": ["MIT"], "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/dipole_periodic.jl", "max_issues_repo_name": "mcawte/VortexDistributions.jl", "max_issues_repo_head_hexsha": "6b67e5fad661c196f887a0a15069582617a8ecc5", "max_issues_repo_licenses": ["MIT"], "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/dipole_periodic.jl", "max_forks_repo_name": "mcawte/VortexDistributions.jl", "max_forks_repo_head_hexsha": "6b67e5fad661c196f887a0a15069582617a8ecc5", "max_forks_repo_licenses": ["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.3636363636, "max_line_length": 96, "alphanum_fraction": 0.6486997636, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7850745333225563}}
{"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\u03c7 = Lar.euler_characteristic(W, copEV, copFE)\nprintln(\"\u03c7 = $\u03c7 ; 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    \u03b2::Float64 # drift parameter (also known as inverse relaxation time)\n    \u03c3::Float64 # diffusion parameter\n    function OrnsteinUhlenbeck(\u03b2::Float64, \u03c3::Float64)\n        isnan(\u03b2) || \u03b2 > 0. || error(\"Parameter \u03bb must be positive.\")\n        isnan(\u03c3) || \u03c3 > 0. || error(\"Parameter \u03c3 must be positive.\")\n        new(\u03b2, \u03c3)\n    end\nend\n\n# define drift and sigma of OrnsteinUhlenbeck\nimport Bridge: b, \u03c3, a, transitionprob\nBridge.b(t,x, P::OrnsteinUhlenbeck) = -P.\u03b2*x\nBridge.\u03c3(t, x, P::OrnsteinUhlenbeck) = P.\u03c3\nBridge.a(t, x, P::OrnsteinUhlenbeck) = P.\u03c3^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.\u03b2*(t-s)), sqrt((0.5P.\u03c3^2/P.\u03b2) *(1-exp(-2*P.\u03b2*(t-s)))))\n\n# plot likelihood of \u03b2 \nLL = [(\u03b2, llikelihood(X, OrnsteinUhlenbeck(\u03b2, 1.))) for \u03b2 in 1.:30.]\nfor (\u03b2, ll) in LL\n    println(\"\u03b2 $\u03b2 loglikelihood \", ll )\nend\nplot(Float64[\u03b2 for (\u03b2, ll) in LL], Float64[ll for (\u03b2, 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    \u03b2 # drift parameter (also known as inverse relaxation time)\n    \u03c3 # diffusion parameter\n    function VOrnsteinUhlenbeck{d}(\u03b2, \u03c3) where d\n           new(\u03b2, \u03c3)\n    end\nend\n\n# define drift and sigma of VOrnsteinUhlenbeck\n \nBridge.b(t, x, P::VOrnsteinUhlenbeck) = -P.\u03b2*x\nBridge.\u03c3(t, x, P::VOrnsteinUhlenbeck) = P.\u03c3*I\nBridge.a(t, x, P::VOrnsteinUhlenbeck) = P.\u03c3*P.\u03c3'*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 \u03b8estimation_()\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    \u03bcBar = mean(x)\n    V    = sumabs2(x - \u03bcBar)\n    d    = length(x)\n    s2   = V/d\n    # by construction of the arcsin transform\n    \u03c32   = 1\n    B    = \u03c32/(\u03c32 + max(0, s2-\u03c32))\n    \u03bcShrunk = \u03bcBar + (1-B).*(x-\u03bcBar)\n    \n    # back transform\n    \u03b8Shrunk = 0.5*(sin(\u03bcShrunk/sqrt(n))+1)\n    \u03b8MLE    = y\n    (ytest, \u03b8Shrunk, \u03b8MLE)\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    \u03b8true, \u03b8Shrunk, \u03b8MLE = \u03b8estimation_()\n    # plot Shrinkage Estimates\n    p1 = plot([layer(x=[\u03b8MLE[i] \u03b8Shrunk[i]], y=[1 0], Geom.line) for i=1:d]...,\n              layer(x=\u03b8MLE, y=ones(1, d), Geom.point),\n              layer(x=\u03b8Shrunk, 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, \u03b8Shrunk, \u03b8MLE], 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    \u03b8true, \u03b8Shrunk, \u03b8MLE = \u03b8estimation_()\n    mseMLE = mean((\u03b8true-\u03b8MLE).^2)\n    mseShrink = mean((\u03b8true-\u03b8Shrunk).^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 \u00d7 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": "using CSV, DataFrames, CategoricalArrays\n\ndata = CSV.read(\"../data/purchaseData.csv\", copycols = true)\nprintln(\"Levels of Grade: \", levels(data.Grade))\nprintln(\"Data points: \", nrow(data))\n\nn = sum(.!(ismissing.(data.Grade)))\nprintln(\"Non-missing data points: \", n)\ndata2 = dropmissing(data[:,[:Grade]],:Grade)\n\ngradeInQuestion = \"E\"\nindicatorVector = data2.Grade .== gradeInQuestion\nnumSuccess = sum(indicatorVector)\nphat = numSuccess/n\nserr = sqrt(phat*(1-phat)/n)\n\nalpha = 0.05\nconfidencePercent = 100*(1-alpha)\nzVal = quantile(Normal(),1-alpha/2)\nconfInt = (phat - zVal*serr, phat + zVal*serr)\n\nprintln(\"\\nOut of $n non-missing observations, \"*\n        \"$numSuccess are at level $gradeInQuestion.\")\nprintln(\"Hence a point estimate for the proportion \"*\n        \"of grades at level $gradeInQuestion is $phat.\")\nprintln(\"A $confidencePercent% confidence interval for \"*\n        \"the proprotion of level $gradeInQuestion is:\\n$confInt.\")", "meta": {"hexsha": "485e97e25bbd7d682628251b0137afdf461be4f1", "size": 938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/proportionCI.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/proportionCI.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/proportionCI.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.7407407407, "max_line_length": 66, "alphanum_fraction": 0.7078891258, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7850161411508081}}
{"text": "export RandomizedKaczmarz, RandomizedBlockKaczmarz\n\n\"\"\"\nRandomized Kaczmarz\n\nSection 3.3 in Gower, R. M., & Richt\u00e1rik, 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\u00e1rik, 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,\u03c3=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`\u03c3`: 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,\u03c3=1.0)\n    erfcx(abs(k)*\u03c3/sqrt(2))/sqrt(8*\u03c0*\u03c3^2)\nend\nfunction Skernel2(k,\u03c3=1.0)\n    k==0.0 ? 0.0 : exp(abs(k*\u03c3/2)^2)*besselk(0,abs(k*\u03c3/2)^2)/(2*\u03c0)\nend\nfunction Skernel3(k)\n    k==0.0 ? 0.0 : 1/abs(k)\nend\n\nSkernel(k::Array{Float64,1},\u03c3=1.0) = Skernel1.(k,\u03c3)\nSkernel(k::Array{Float64,2},\u03c3=1.0) = Skernel2.(k,\u03c3)\nSkernel(k::Array{Float64,3},\u03c3=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) = \u2211_y p(y) DKL( p(x|z,y)||p(x|z) )\n    #I(X;Y|Z) = \u2211_y p(y) \u2211_z p(z|y) \u2211_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] = \u2211_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] = \u2211_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 \u2211_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 = \u2211_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 \u0394F)\nfunction RDobjective(EU,I,\u03b2)\n    return EU-I/\u03b2\nend\n\n#Objective-value for the three-variable general case\nfunction ThreeVArRDobjective(EU, I_ow, I_ao, I_awgo, \u03b21, \u03b22, \u03b23)\n    if(\u03b23==0)\n        #sequential case - I(A;W|O) should be zero and since \u03b23=Inf \u2192 \u221e * 0 = NaN\n        #handle this by using a tiny \u03b23 - if I(A;W|O) is nonzero, this should be easily detectable through the huge\n        #value of the objective\n        \u03b23 = eps()\n    end\n    return EU - (1/\u03b21)*I_ow - (1/\u03b22)*I_ao - (1/\u03b23)*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)/\u03b2\nfunction analyzeBAsolution(pw::Vector, pa::Vector, pagw::Matrix, U_pre::Matrix, \u03b2)\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,\u03b2)\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, \u03b21, \u03b22, \u03b23)\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: \u2211p(o) = $(sum(po))\")\n    Ho = entropybits(po)\n    \n    #compute H(A)\n    #println(\"2: \u2211p(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, \u03b21, \u03b22, \u03b23)\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(\u03bc, \u03b8)\n\nThe *Gumbel distribution*  with location `\u03bc` and scale `\u03b8` 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    \u03bc::T  # location\n    \u03b8::T  # scale\n\n    Gumbel(\u03bc::T, \u03b8::T) = (@check_args(Gumbel, \u03b8 > zero(\u03b8)); new(\u03bc, \u03b8))\nend\n\nGumbel{T<:Real}(\u03bc::T, \u03b8::T) = Gumbel{T}(\u03bc, \u03b8)\nGumbel(\u03bc::Real, \u03b8::Real) = Gumbel(promote(\u03bc, \u03b8)...)\nGumbel(\u03bc::Integer, \u03b8::Integer) = Gumbel(Float64(\u03bc), Float64(\u03b8))\nGumbel(\u03bc::Real) = Gumbel(\u03bc, 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}}, \u03bc::S, \u03b8::S) = Gumbel(T(\u03bc), T(\u03b8))\nconvert{T <: Real, S <: Real}(::Type{Gumbel{T}}, d::Gumbel{S}) = Gumbel(T(d.\u03bc), T(d.\u03b8))\n\n#### Parameters\n\nlocation(d::Gumbel) = d.\u03bc\nscale(d::Gumbel) = d.\u03b8\nparams(d::Gumbel) = (d.\u03bc, d.\u03b8)\n@inline partype{T<:Real}(d::Gumbel{T}) = T\n\n\n#### Statistics\n\nmean(d::Gumbel) = d.\u03bc + d.\u03b8 * \u03b3\n\nmedian{T<:Real}(d::Gumbel{T}) = d.\u03bc - d.\u03b8 * log(T(logtwo))\n\nmode(d::Gumbel) = d.\u03bc\n\nvar{T<:Real}(d::Gumbel{T}) = T(\u03c0)^2/6 * d.\u03b8^2\n\nskewness{T<:Real}(d::Gumbel{T}) = 112*sqrt(T(6))*zeta(T(3))/\u03c0/\u03c0/\u03c0\n\nkurtosis{T<:Real}(d::Gumbel{T}) = T(12)/5\n\nentropy(d::Gumbel) = log(d.\u03b8) + 1 + \u03b3\n\n\n#### Evaluation\n\nzval(d::Gumbel, x::Real) = (x - d.\u03bc) / d.\u03b8\nxval(d::Gumbel, z::Real) = x * d.\u03b8 + d.\u03bc\n\nfunction pdf(d::Gumbel, x::Real)\n    z = zval(d, x)\n    exp(-z - exp(-z)) / d.\u03b8\nend\n\nfunction logpdf(d::Gumbel, x::Real)\n    z = zval(d, x)\n    - (z + exp(-z) + log(d.\u03b8))\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.\u03bc - d.\u03b8 * log(-log(p))\n\ngradlogpdf(d::Gumbel, x::Real) = - (1 + exp((d.\u03bc - x) / d.\u03b8)) / d.\u03b8\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\u00fctze, 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\u2013333. 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\u03b8: a vector whose length is (N+1); each element can also be vector,\ne.g., \u03b8 = [[1, 2, 3], [2, 3, 4]]\n\"\"\"\nstruct Bezier <: AbstractTrajectory\n    \u03b8::AbstractVector\n    t0::Real\n    tf::Real\nend\n\nfunction (bezier::Bezier)(t::Real)\n    @unpack t0, tf, \u03b8 = bezier\n    N = length(\u03b8) -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 .* \u03b8 |> sum  # sum of N_C_i * s^(N-i) * (1-s)^i * \u03b8_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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.12\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.12\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550b690890a-2135-11eb-1abc-933c757a93f8\n# \u255f\u250070182cd8-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) \u2208 [0, \u03c0]\n\nCalculate smaller angle between two vectors ``AB`` and ``BC`` meeting at ``B``.\n\"\"\"\nfunction anglespan(a, b, c)\n    \u03941 = a - b; n1 = norm(\u03941)\n    \u03942 = c - b; n2 = norm(\u03942)\n    (n1 == 0 || n2 == 0) && error(\"two positions overlap\")\n    cos_ = \u03941\u22c5\u03942 / norm(\u03941) / norm(\u03942)\n    cos_ >= 1 && return 0        ## handle \"overflow?\" cases where cos_ \u2209 [-1,1]\n    cos_ <= -1 && return \u03c0\n    acos(cos_)\nend\n\n\"\"\"\n    dihedral(a, b, c, d) \u2208 [-\u03c0, \u03c0]\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    \u03941 = a - b\n    \u03942 = b - c; n2 = norm(\u03942)\n    \u03943 = d - c\n    n2 == 0 && error(\"torque axis is undefined; `b`, `c` overlap\")\n\n    \u039423 = \u03942\u00d7\u03943\n    \u039421 = \u03942\u00d7\u03941\n    (norm(\u039423) == 0 || norm(\u039421) == 0) && error(\"some points overlap/colinear\")\n    \n    atan(\u039423\u22c5(\u039421\u00d7\u03942) / n2, \u039423\u22c5\u039421)\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| \u2265 |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| \u2265 |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| \u2265 |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| \u2265 |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\u00b2\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": "\n\nfunction step!(x,bkhs)\n       n\u03b5 = size(bkhs.D)[2]\n       \u03b5  = rand(Normal(),n\u03b5)\n       x .= bkhs.C*x + bkhs.D*\u03b5\n       return x\nend\n\nfunction timeseries(bkhs,n)\n       m  = size(bkhs.C)[1] # number of equations\n       x  = zeros(m)\n       ts = zeros(n,m)\n       for \u03c4 in 1:n\n           ts[\u03c4,:] = step!(x,bkhs)\n       end\n       return ts\nend\n\nfunction impulse_response(bkhs,n,i\u03b5)\n       m  = size(bkhs.C)[1] # number of equations\n       x  = zeros(m)\n       ts = zeros(n,m)\n       n\u03b5 = size(bkhs.D)[2]\n       \u03b5  = I(n\u03b5)[:,i\u03b5]\n       x .= bkhs.C*x + bkhs.D*\u03b5\n       for \u03c4 in 1:n\n           ts[\u03c4,:] = x\n           x      .= bkhs.C*x\n       end\n       return ts\nend\n", "meta": {"hexsha": "05681fe33c314f9460b84f7254ca76c5f08607fb", "size": 666, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/timeseries.jl", "max_stars_repo_name": "alfredjmduncan/ReverseDiffDSGE.jl", "max_stars_repo_head_hexsha": "e593a0a6d31eef7d475d0d32038b77c14bd3f9e7", "max_stars_repo_licenses": ["MIT"], "max_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/timeseries.jl", "max_issues_repo_name": "alfredjmduncan/ReverseDiffDSGE.jl", "max_issues_repo_head_hexsha": "e593a0a6d31eef7d475d0d32038b77c14bd3f9e7", "max_issues_repo_licenses": ["MIT"], "max_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/timeseries.jl", "max_forks_repo_name": "alfredjmduncan/ReverseDiffDSGE.jl", "max_forks_repo_head_hexsha": "e593a0a6d31eef7d475d0d32038b77c14bd3f9e7", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 49, "alphanum_fraction": 0.457957958, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632329799586, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7847749967624396}}
{"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, \u03b3)\n\nCompute the latitude of the substellar point for a given solar longitude `f` (true anomaly) and obliquity `\u03b3`\n\"\"\"\nsubstellarlatitude(f, \u03b3) = asin(cos(f)*sin(\u03b3))\n\n\"\"\"\n    hourangle(\u03b8, \u03b8\u209b)\n\nCompute the [hour angle](https://en.wikipedia.org/wiki/Hour_angle)\n\"\"\"\nfunction hourangle(\u03b8, \u03b8\u209b)\n    x = -sin(\u03b8)*sin(\u03b8\u209b)/(cos(\u03b8)*cos(\u03b8\u209b))\n    if x <= -1\n        return \u03c0\n    elseif x >= 1\n        return 0.0\n    end\n    return acos(x)\nend\n\n#\u03b8 - latitude\n#\u03b8\u209b - substellar latitude\n\"\"\"\n    diurnalfluxfactor(\u03b8, \u03b8\u209b)\n\nCompute the diurnally averaged fraction of incoming stellar flux received by a point at latitude `\u03b8` when the substellar latitude is `\u03b8\u209b`\n\"\"\"\nfunction diurnalfluxfactor(\u03b8, \u03b8\u209b)\n    h = hourangle(\u03b8, \u03b8\u209b)\n    return (sin(h)*cos(\u03b8)*cos(\u03b8\u209b) + h*sin(\u03b8)*sin(\u03b8\u209b))/\u03c0\nend\n\n#\u03b8 - latitude\n#f - solar longitude\n#\u03b3 - obliquity\n\"\"\"\n    diurnalfluxfactor(\u03b8, f, \u03b3)\n\nCompute the diurnally averaged fraction of incoming stellar flux received by a point at latitude `\u03b8` when the planet is at solar longitude (true anomaly) `f`, with obliquity `\u03b3`\n\"\"\"\ndiurnalfluxfactor(\u03b8, f, \u03b3) = diurnalfluxfactor(\u03b8, substellarlatitude(f, \u03b3))\n\n\"\"\"\n    diurnalfluxfactor(t, a, m, e, \u03b8, \u03b3, p)\n\nCompute the diurnally averaged fraction of incoming stellar flux received by a point at latitude `\u03b8` for a general elliptical orbit\n\"\"\"\nfunction diurnalfluxfactor(t, a, m, e, \u03b8, \u03b3, p)\n    f = trueanomaly(t, a, m, e)\n    r = orbitaldistance(a, f, e)\n    return diurnalfluxfactor(\u03b8, f - p, \u03b3)*(a/r)^2\nend\n\n\"\"\"\n    diurnalfluxfactors(\u03b3; nf=251, n\u03b8=181)\n\nCompute a grid of diurnally averaged fractions of incoming stellar flux received by a point at latitude `\u03b8` for a planet with obliquity `\u03b3` 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\u03b8` indicates the number of latitudes.\n\"\"\"\nfunction diurnalfluxfactors(\u03b3; nf::Int=251, n\u03b8::Int=181)\n    \u03b8 = LinRange(-\u03c0/2, \u03c0/2, n\u03b8)\n    f = LinRange(0, 2\u03c0, nf)\n    F, \u0398 = meshgrid(f, \u03b8)\n    return (f, \u03b8, diurnalfluxfactor.(\u0398, F, \u03b3))\nend\n\n\"\"\"\n    diurnalfluxfactors(a, m, e, \u03b3, p; nt=251, n\u03b8=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\u03b8` indicates the number of latitudes.\n\"\"\"\nfunction diurnalfluxfactors(a, m, e, \u03b3, p; nt::Int=251, n\u03b8::Int=181)\n    t = LinRange(0, orbitalperiod(a, m), nt)\n    \u03b8 = LinRange(-\u03c0/2, \u03c0/2, n\u03b8)\n    T, \u0398 = meshgrid(t, \u03b8)\n    return (t, \u03b8, diurnalfluxfactor.(T, a, m, e, \u0398, \u03b3, p))\nend\n\n\"\"\"\n    annualfluxfactor(e, \u03b8, \u03b3, p)\n\nCompute the annually averaged flux factor for a latitude `\u03b8` on a planet in a general elliptical orbit.\n\"\"\"\nfunction annualfluxfactor(e, \u03b8, \u03b3, p; tol::Float64=1e-4)\n    T = orbitalperiod(1.0, 1.0)\n    f(t) = diurnalfluxfactor(t, 1.0, 1.0, e, \u03b8, \u03b3, p)\n    F, _ = hquadrature(f, 0, T, reltol=tol, abstol=tol)\n    return F/T\nend\n\n\"\"\"\n    annualfluxfactors(e, \u03b3, p; n\u03b8=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\u03b8` indicates the number of latitude samples.\n\"\"\"\nfunction annualfluxfactors(e, \u03b3, p; n\u03b8::Int=181)\n    \u03b8 = LinRange(-\u03c0/2, \u03c0/2, n\u03b8)\n    F = annualfluxfactor.(e, \u03b8, \u03b3, p)\n    return \u03b8, 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    \u03b8::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,\u03b8)\n    \u03b1, \u03b2, \u03b3, \u03b4 = \u03b8\n    x\u2081, x\u2082 = x\n\n    dx\u2081 = \u03b1*x\u2081 - \u03b2*x\u2081*x\u2082\n    dx\u2082 = \u03b4*x\u2081*x\u2082 - \u03b3*x\u2082\n\n    [dx\u2081, dx\u2082]\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, \u03b8, dt  = prob.f, prob.\u03b8, solver.dt\n    (u + dt*f(u,\u03b8), t+dt)\nend\n\nfunction (solver::RK2)(prob::ODEProblem, u, t)\n    f, \u03b8, dt  = prob.f, prob.\u03b8, solver.dt\n    uh = u + f(u,\u03b8)*dt\n    u + dt/2*(f(u,\u03b8) + f(uh,\u03b8)), t+dt\nend\n\n\n\u03b8 = [0.1,0.2,0.3,0.2]\nu0 = [1.0,1.0]\ntspan = (0.,100.)\ndt = 0.1\nprob = ODEProblem(f,tspan,u0,\u03b8)\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\u03b8 = [0.2,0.2,0.3,0.2]\nu0 = [1.0,1.0]\ntspan = (0.,100.)\ndt = 0.1\nprob2 = ODEProblem(f,tspan,u0,\u03b8)\n\nt,X2=solve(prob2, RK2(0.2))\n\nusing Optim\n\nfunction loss(\u03b8in,prob::ODEProblem,Y)\n    prob.\u03b8.=\u03b8in\n    t,Xn=solve(prob,RK2(0.2))\n    sum((Y.-Xn).^2)\nend\n\u03b8opt = copy(\u03b8)\nO=Optim.optimize(\u03b8->loss(\u03b8,prob,X),\u03b8opt)\nO=Optim.optimize(\u03b8->loss(\u03b8,prob,X),\u03b8opt,LBFGS())\n\nusing DiffEqFlux\nnn=FastDense(2,2)\np = initial_params(nn)\nnn([1,2],p)\n\n\nfunction fy(x,\u03b8)\n    \u03b1, \u03b2, \u03b3, \u03b4, \u03c9 = \u03b8\n    x\u2081, x\u2082 = x\n\n    dx\u2081 = \u03b1*x\u2081 - \u03b2*x\u2081*x\u2082 + \u03c9*x\u2082\n    dx\u2082 = \u03b4*x\u2081*x\u2082 - \u03b3*x\u2082\n\n    [dx\u2081, dx\u2082]\nend\n\n#\n\u03b8y = [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,\u03b8y)\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,\u03b8)\n    \u03b1, \u03b2, \u03b3, \u03b4 = \u03b8[1:4]\n    x\u2081, x\u2082 = x\n\n    dx\u2081 = \u03b1*x\u2081 - \u03b2*x\u2081*x\u2082 \n    dx\u2082 = \u03b4*x\u2081*x\u2082 - \u03b3*x\u2082\n\n    [dx\u2081, dx\u2082]+nn(x,@view \u03b8[5:end])\nend\n\n\u03b8nn = [0.2,0.2,0.3,0.2,0.01*initial_params(nn)...]\nprobnn = ODEProblem(fnn,tspan,u0,\u03b8nn)\n\n\u03b8opt = copy(\u03b8nn)\nO=Optim.optimize(\u03b8->loss(\u03b8,probnn,Xy),\u03b8opt,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(\u03c4)]=W*\u03b4(t-\u03c4)` (\u03b4 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\u221e 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\u221e norm of the LTI system `sys`.\nThe H\u221e norm is the same as the H\u221e 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\u221e norms.\nIt represents the desired relative accuracy for the computed L\u221e 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, \u03c9_peak) = hinfnorm(sys; tol=1e-6)`\n\nCompute the H\u221e norm `Ninf` of the LTI system `sys`, together with a frequency\n`\u03c9_peak` at which the gain Ninf is achieved.\n\n`Ninf := sup_\u03c9 \u03c3_max[sys(i\u03c9)]`  if `G` is stable (\u03c3_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\u221e norm (not an absolute certificate).\n\n`sys` is first converted to a state space model if needed.\n\nThe continuous-time L\u221e norm computation implements the 'two-step algorithm' in:\\\\\n**N.A. Bruinsma and M. Steinbuch**, 'A fast algorithm to compute the H\u221e-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\u221e-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, \u03c9_peak) = linfnorm(sys; tol=1e-6)`\n\nCompute the L\u221e norm `Ninf` of the LTI system `sys`, together with a frequency\n`\u03c9_peak` at which the gain `Ninf` is achieved.\n\n`Ninf := sup_\u03c9 \u03c3_max[sys(i\u03c9)]` (\u03c3_max denotes the largest singular value)\n\n`tol` is an optional keyword argument representing the desired relative accuracy for\nthe computed L\u221e 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\u221e norm computation implements the 'two-step algorithm' in:\\\\\n**N.A. Bruinsma and M. Steinbuch**, 'A fast algorithm to compute the H\u221e-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\u221e-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\u221e norm and the frequency \u03c9_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        \u03c9_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        \u03c9_p = abs(pole_vec[maxidx])\n    end\n\n    m_vec_init = [0, \u03c9_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    \u03c9_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        \u039b = 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, \u039b)\n        end\n\n        # Find eigenvalues on the imaginary axis\n        \u039b_on_imag_axis = filter(on_imag_axis, \u039b)\n\n        \u03c9_vec = imag.(\u039b_on_imag_axis)\n\n        sort!(\u03c9_vec)\n\n        if isempty(\u03c9_vec)\n            return (1+T(tol))*lb, \u03c9_peak\n        end\n\n        # Improve the lower bound\n        # if not empty, \u03c9_vec contains at least two values\n        for k=1:length(\u03c9_vec)-1\n            mk = (\u03c9_vec[k] + \u03c9_vec[k+1])/2\n            sigmamax_mk = opnorm(evalfr(sys,mk*1im))\n            if sigmamax_mk > lb\n                lb = sigmamax_mk\n                \u03c9_peak = mk\n            end\n        end\n    end\n    error(\"In _infnorm_two_steps_dt: The computation of the H\u221e/L\u221e 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 \u03b8\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\u00f4le closest to unit circle\n        \u03b8_p = angle(pole_vec[argmin(abs.(abs.(pole_vec).-1))])\n    else\n        \u03b8_p = T(pi)/2\n    end\n\n    if isreal(pole_vec)  # only real poles\n        \u03c9_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        \u03c9_p = abs(pole_vec[maxidx])\n    end\n\n    m_vec_init = [0, \u03b8_p, pi]\n\n    (lb, idx) = findmax([opnorm(evalfr(sys, exp(im*m))) for m in m_vec_init])\n    \u03b8_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        \u039b = 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, \u039b)\n        end\n\n        # Find eigenvalues on the unit circle\n        \u039b_on_unit_cirlce = filter(on_unit_circle, \u039b)\n\n        \u03b8_vec = angle.(\u039b_on_unit_cirlce)\n\n        sort!(\u03b8_vec)\n\n        if isempty(\u03b8_vec)\n            return (1+T(tol))*lb, \u03b8_peak/T(sys.Ts)\n        end\n\n        # Improve the lower bound\n        # if not empty, \u03b8_vec contains at least two values\n        for k=1:length(\u03b8_vec)-1\n            mk = (\u03b8_vec[k] + \u03b8_vec[k+1])/2\n            sigmamax_mk = opnorm(evalfr(sys,exp(mk*1im)))\n            if sigmamax_mk > lb\n                lb = sigmamax_mk\n                \u03b8_peak = mk\n            end\n        end\n    end\n    error(\"In _infnorm_two_steps_dt: The computation of the L\u221e 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\u00e4ra 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,\u03a3,V = svd(Q1*P*Q1')\n    \u03a3 .= sqrt.(\u03a3)\n    \u03a31 = diagm(0 => sqrt.(\u03a3))\n    T = \u03a31\\(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(\u03a3)\n    end\n\n    sysr = ST(T*sys.A/T, T*sys.B, sys.C/T, sys.D, sys.Ts), diagm(0 => \u03a3)\nend\n\n\n\"\"\"\n`sysr, G = baltrunc(sys::StateSpace, atol = \u221a\u03f5, 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 \u03c3max` 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\u00e4ra 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\u0303 = x` on `sys` such that\n```\nA\u0303 = T\u207b\u00b9AT\nB\u0303 = T\u207b\u00b9 B\nC\u0303 = CT\nD\u0303 = 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, \u00c5str\u00f6m\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 \u2248 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*\u03c0)^(-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\u2099 = 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\u2099, dims =2)\nX\u2099 .= 1f0 ./ xscale .* X\u2099\n# Time from 0 -> n\ntspan = (t[1], t[end])\n\n# Plot the data\nscatter(t, transpose(X\u2099), xlabel = \"t\", ylabel = \"x(t), y(t)\")\nplot!(t, transpose(X\u2099), 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\u2099, 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\u03bb = Float32.(exp10.(-7:0.1:5))\n# Create an optimizer for the SINDy problem\nopt = STLSQ(\u03bb)\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\u0302 = 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\u0302[1]\n    # We assume a linear decay rate for the predator\n    du[2] = -p[2]*u[2] + u\u0302[2]\nend\n\n# Define the problem\nprob_nn = ODEProblem(ude_dynamics!,X\u2099[:, 1], tspan, p)\n\n## Function to train the network\n# Define a predictor\nfunction predict(\u03b8, X = X\u2099[:,1], T = t)\n    Array(solve(prob_nn, Vern7(), u0 = X, p=\u03b8,\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\u2099, t, prob_nn, loss, Vern7(),\n                          group_size; continuity_term)\nend\n\nfunction loss(\u03b8)\n    X\u0302 = predict(\u03b8)\n    sum(abs2, X\u2099 - X\u0302) / size(X\u2099, 2) + convert(eltype(\u03b8), 1e-3)*sum(abs2, \u03b8[3:end]) ./ length(\u03b8[3:end])\nend\n\n# Container to track the losses\nlosses = Float32[]\n\n# Callback to show the loss during training\ncallback(\u03b8,args...) = begin\n\tl = loss(\u03b8) # 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\u0302 = predict(p_trained, X\u2099[:,1], tsample)\n# Trained on noisy data vs real solution\npl_trajectory = scatter(t, transpose(X\u2099), color = :black, label = [\"Measurements\" nothing], xlabel = \"t\", ylabel = \"x(t), y(t)\")\nplot!(tsample, transpose(X\u0302), color = :red, label = [\"UDE Approximation\" nothing])\nsavefig(pl_trajectory, joinpath(pwd(), \"plots\", \"$(svname)_trajectory_reconstruction.pdf\"))\n\n# Neural network guess\nY\u0302 = U(X\u0302,p_trained[3:end])\n\npl_reconstruction = scatter(tsample, transpose(Y\u0302), xlabel = \"t\", ylabel =\"U(x,y)\", color = :red, label = [\"UDE Approximation\" nothing])\nplot!(tsample, transpose(Y\u0302), 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\u0302, tsample, DX = Y\u0302)\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\u0302 = nn_res(u, p[3:end]) # Network prediction\n    du[1] = p[1]*u[1] + u\u0302[1]\n    du[2] = -p[2]*u[2] + u\u0302[2]\nend\n\n\np_model = [p_trained[1:2];parameters(nn_res)]\n\nestimation_prob = ODEProblem(recovered_dynamics!, X\u2099[:, 1], tspan, p_model)\n# Convert for reuse\nsys = modelingtoolkitize(estimation_prob);\ndudt = ODEFunction(sys);\nestimation_prob = ODEProblem(dudt,X\u2099[:, 1], tspan, p_model)\nestimate = solve(estimation_prob, Tsit5(), saveat = t)\n\n##  Fit the found model\nfunction loss_fit(\u03b8)\n    X\u0302 = Array(solve(estimation_prob, Tsit5(), p = \u03b8, saveat = t))\n    sum(abs2, X\u0302 .- X\u2099)\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\u2099), 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\u2099, \"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\u2099), 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\u2099)*1.25],lw=1,color=:black, label = nothing)\nannotate!([(10.0,maximum(X\u2099)*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": "include(\"../src/Curvelet.jl\")\n#using Curvelet\nusing PyPlot\n\nPyPlot.close(\"all\")\n\n# Load sample data\n\ninput = imread(\"test/peppers.gif\")\n#input = imread(\"test/lena.jpg\")\n#input = input[:,:,1]\nsample_data = input*1.0\nN = size(sample_data,1)\n\n# Display unmodified data\nfigure(1)\ngray()\nimshow(sample_data)\ntitle(\"Unmodified Data\")\n\n\nprintln(\"Performing Conversion...\")\nplan        = Curvelet.planCurveletTransform(N, Curvelet.C1)\ntmp         = Curvelet.curveletTransform(sample_data, plan)\nsample_hat  = Curvelet.inverseCurveletTransform(tmp, plan)\nprintln(\"Done\")\nprintln()\nprintln(\"(Small) Error from transform was: \", norm(sample_data-sample_hat))\nprintln()\n\n# Display a subset of coefficients\ncombo = zeros(size(tmp.HP[1]))\nN = length(tmp.HP)\nfor i=1:N\n    combo += abs.(tmp.HP[i])\nend\nfigure(10)\ntitle(\"High Frequency Curves\")\nimshow(log.(combo))\n\nfigure(11)\ntitle(\"A Single Curvelet Band\")\nimshow(log.(abs.(tmp.HP[5])))\n\n#\n##Create an approximation\n#\nfunction vectorize_curvelet(cc::Matrix{Complex{Float64}})\n    vec(cc)\nend\n\nfunction vectorize_curvelet(cc::Curvelet.CurveletCoeff)\n    data = vectorize_curvelet(cc.LP)\n    for i = cc.HP\n        data = [data,vec(i)]\n    end\n    data\nend\n\nfunction build_sparse(image, plan, sparsity)\n    tmp = Curvelet.curveletTransform(sample_data, plan)\n    data = vectorize_curvelet(tmp)\n    ordered = reverse(sort(abs.(data)))\n    curvelet_threshold(tmp, ordered[sparsity])\n    Curvelet.inverseCurveletTransform(tmp, plan)\nend\ndata = Float64[0.0]\nfor i=tmp.HP\n    data = vcat(data, vec(i))\nend\n#\ndata = vec(data)\nordered = reverse(sort(abs.(data)))\n\n#threshold = ordered[30000]\nthreshold = ordered[300]\n\nfunction curvelet_threshold(cc::Matrix{Complex{Float64}}, threshold)\n    #cc[abs(cc) .< threshold] = 0\nend\n\nfunction curvelet_threshold(cc::Curvelet.CurveletCoeff, threshold)\n    curvelet_threshold(cc.LP, threshold)\n    for i = 1:length(cc.HP)\n        cc.HP[i][abs.(cc.HP[i]) .< threshold] = 0\n    end\nend\n\nfunction reconstruction_step(observation, sparsity)\n    tmp = Curvelet.curveletTransform(observation, plan)\n    data = Float64[0.0]\n    for i=tmp.HP\n        data = vcat(data, vec(i))\n    end\n    #\n    data = vec(data)\n    ordered = reverse(sort(abs.(data)))\n    threshold = ordered[sparsity]\n\n    curvelet_threshold(tmp, threshold)\n    sample_hat  = Curvelet.inverseCurveletTransform(tmp, plan)\nend\n\nbegin# reconstruction_example()\n    #attempt a reconstruction problem\n    #grab around 30% of the points\n    px_rate = 0.30\n\n    N = size(sample_data,1)\n    good_px = zeros(size(sample_data))\n    for i=1:N, j=1:N\n        good_px[i,j] = (rand() < px_rate) ? 1 : 0\n    end\n\n    observation = sample_data.*good_px\n    sample_hat  = copy(observation)\n    \n    figure(100)\n    title(\"Approximation Under Missing Data - Missing\")\n    gray()\n    imshow(abs.(observation))\n\n    for iters=1:40\n        tr = 1000\n\n        if(iters > 10)\n            tr = 10000\n        elseif(iters > 20)\n            tr = 40000\n        end\n\n        smp_next = reconstruction_step(sample_hat, tr)\n        println(\"Appx error  was: \", norm(sample_data-smp_next), \" @ iter \",\n        iters)\n        sample_hat[good_px.==0] = smp_next[good_px.==0]\n        if(iters in [1, 5, 10])\n            figure(iters+100)\n            title(\"Intermediate Denoising Stage\")\n            imshow(sample_hat)\n        end\n    end\n\n    println(\"Denoising Missing Data Example\")\n    println()\n    println(\"Obs  error  was: \", norm(sample_data-observation))\n    println(\"Appx error  was: \", norm(sample_data-sample_hat))\n    println(\"Orig energy was: \", norm(sample_data))\n\n    figure(151)\n    title(\"Approximation Under Missing Data - Reconstruction\")\n    gray()\n    imshow(abs.(sample_hat))\n    figure(152)\n    title(\"Approximation Under Missing Data - Diff\")\n    gray()\n    imshow(abs.(sample_hat).-sample_data)\nend\n\n\ntmp = Curvelet.curveletTransform(sample_data, plan)\nK = round(Int,length(sample_data)*0.10)\nthreshold = ordered[K]\ncurvelet_threshold(tmp,threshold)\n\n\nsample_hat  = Curvelet.inverseCurveletTransform(tmp, plan)\nprintln()\nprintln()\nprintln(\"Creating a sparse represntation\")\nprintln()\nprintln(\"Sparsity:       \", 100*K/length(sample_data), \"%\")\nprintln(\"total energy:   \", norm(sample_data))\nprintln(\"Appx error was: \", norm(sample_data-sample_hat))\n\nfigure(200)\ntitle(\"Approximation Under Sparsity - Original\")\ngray()\nimshow(abs.(sample_data))\nfigure(201)\ntitle(string(\"Approximation Under Sparsity - \",K,\" sparse\"))\ngray()\nimshow(abs.(sample_hat))\n", "meta": {"hexsha": "03a7329f4003c55b4d871a4c85ca631f1d4576ae", "size": 4466, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/example.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Curvelet.jl-71625603-7594-5154-9703-a50705a89aca", "max_stars_repo_head_hexsha": "2079434971dcac73d92edd4ba913ffd28e08d313", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-04-22T16:49:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T02:53:41.000Z", "max_issues_repo_path": "test/example.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Curvelet.jl-71625603-7594-5154-9703-a50705a89aca", "max_issues_repo_head_hexsha": "2079434971dcac73d92edd4ba913ffd28e08d313", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-04T15:36:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-09T18:56:31.000Z", "max_forks_repo_path": "test/example.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Curvelet.jl-71625603-7594-5154-9703-a50705a89aca", "max_forks_repo_head_hexsha": "2079434971dcac73d92edd4ba913ffd28e08d313", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-08-27T13:46:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T16:53:43.000Z", "avg_line_length": 24.4043715847, "max_line_length": 76, "alphanum_fraction": 0.6751007613, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320035, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.784772852447061}}
{"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": "function nlp_008_011(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - dual values\n\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n    @variable(model, z)\n\n    @NLobjective(model, Min, x + y^2 + z^3)\n    c1 = @NLconstraint(model, y >= exp(-x - 2) + exp(-z - 2) - 2)\n    c2 = @constraint(model, x^2 <= y^2 + z^2)\n    c3 = @constraint(model, y >= x / 2 + z)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -0.3755859312158738, tol = objective_tol)\n    check_solution(\n        [x, y, z],\n        [-0.593158583913523, 0.2440479041672795, 0.5406271556211383],\n        tol = primal_tol,\n    )\n    return check_dual(\n        [c1, c2, c3],\n        [0.0, -0.8697415278248679, 0.06357861274725801],\n        tol = dual_tol,\n    )\nend\n", "meta": {"hexsha": "ca99e86f4e26aa8d36e7f3621f7b9ddd49be4051", "size": 968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp/008_011.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp/008_011.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp/008_011.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 25.4736842105, "max_line_length": 76, "alphanum_fraction": 0.6146694215, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485396, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7847460314932174}}
{"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\u2208{0,1}  and  w\u2032x <= 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": "using Polynomials\r\nusing Plots\r\n\r\nfunction main()\r\n\r\n    xlin = range(-5, 5, length=200)\r\n\r\n    # creating polynomials\r\n    p = Polynomial([1, 3, 5])   # generating by coefficients\r\n    q = fromroots([1, -4, 4])   # generating by roots\r\n\r\n    # evaluating\r\n    println(p)\r\n    println(q)\r\n\r\n\r\n    # math operations\r\n    println(p(2))\r\n    println(p + q)\r\n    println(2*p - q)\r\n\r\n    # derivatives and integrals\r\n    println(derivative(p))\r\n    println(integrate(p))\r\n\r\n    # roots\r\n    println(roots(q))\r\n\r\n    # what are the roots and extrema of q?\r\n    xq = roots(q)\r\n\r\n    qprime = derivative(q)\r\n    xqq = roots(qprime)\r\n\r\n    plot(xlin, q.(xlin), label=string(q), legend=:bottomright, framestyle=:zerolines, dpi=150)\r\n    plot!(xlin, qprime.(xlin), label=string(qprime))\r\n    scatter!(xq, q.(xq), label=\"roots\")\r\n    scatter!(xqq, q.(xqq), label=\"extrema\")\r\n\r\nend\r\n\r\n\r\nmain()\r\n\r\n\r\n    # xq = roots(q)\r\n    # qprime = derivative(q)\r\n    # xqq = roots(qprime)", "meta": {"hexsha": "c2e2859bdddc7a3ba06e525e1d91a1b099b96f0b", "size": 962, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-learning-src/advance/08-polynomials.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/08-polynomials.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/08-polynomials.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": 20.0416666667, "max_line_length": 95, "alphanum_fraction": 0.5738045738, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426473232578, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7847201146697124}}
{"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": "\"\"\"\n    NormalInverseGamma{T<:Real} <: ContinuousUnivariateDistribution\n\nNormal Inverse Gamma distribution. Adapted from the `NormalInverseGamma` in the\n[ConjugatePriors.jl](https://github.com/JuliaStats/ConjugatePriors.jl/blob/master/src/normalinversegamma.jl)\npackage.\n\"\"\"\nstruct NormalInverseGamma{T <: Real} <: ContinuousUnivariateDistribution\n    \u03bc::T\n    v::T \n    \u03b1::T # shape \n    \u03b8::T # scale\n    function NormalInverseGamma(\u03bc::Real, v::Real, \u03b1::Real, \u03b8::Real)\n    \tv > zero(v) && \u03b1 > zero(\u03b1) && \u03b8 > zero(\u03b8) || error(\"v, \u03b1 and \u03b8 must be positive\")\n        T = promote_type(typeof(\u03bc), typeof(v), typeof(\u03b1), typeof(\u03b8))\n    \treturn new{T}(T(\u03bc), T(v), T(\u03b1), T(\u03b8))\n    end\nend\n\nfunction rand(d::NormalInverseGamma, numsamples::Int)\n    sig2_list = rand(InverseGamma(d.\u03b1, d.\u03b8), numsamples)\n    mu_list = [rand(Normal(d.\u03bc, sqrt(sig2 * d.v))) for sig2 in sig2_list]\n    return mu_list, sig2_list\nend", "meta": {"hexsha": "795bf4c67c1b8987949e0b455046751d442d325a", "size": 900, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distribution.jl", "max_stars_repo_name": "rakutentech/BayesianExperiments.jl", "max_stars_repo_head_hexsha": "de53295e977d6b5ff006e367ba95718702dfcd3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-03-09T04:28:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:19:45.000Z", "max_issues_repo_path": "src/distribution.jl", "max_issues_repo_name": "rakutentech/BayesianExperiments.jl", "max_issues_repo_head_hexsha": "de53295e977d6b5ff006e367ba95718702dfcd3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-03-11T14:23:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-28T16:05:58.000Z", "max_forks_repo_path": "src/distribution.jl", "max_forks_repo_name": "rakutentech/BayesianExperiments.jl", "max_forks_repo_head_hexsha": "de53295e977d6b5ff006e367ba95718702dfcd3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-11T07:05:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T07:05:12.000Z", "avg_line_length": 37.5, "max_line_length": 108, "alphanum_fraction": 0.6755555556, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7847035751940236}}
{"text": "using ReachabilityAnalysis\n\n@taylorize function lotkavolterra!(dx, x, params, t)\n    local \u03b1, \u03b2, \u03b3, \u03b4 = 1.5, 1., 3., 1.\n    dx[1] = \u03b1 * x[1] - \u03b2 * x[1] * x[2]\n    dx[2] = \u03b4 * x[1] * x[2] - \u03b3 * 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) \u2208 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) \u00d7 (0.99..1.01) \u00d7 (2.99..3.01) \u00d7 (0.99..1.01) \u00d7 (0.099..0.101)\nU0 = Singleton([1.0, 1.0]) \u00d7 convert(Hyperrectangle, p_int)\nprob = @ivp(u' = f(u), dim: 7, u(0) \u2208 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\u25a1(\u03f5) = BallInf(zeros(2), \u03f5)\nU0 = (u0 \u2295 \u25a1(0.05)) \u00d7 convert(Hyperrectangle, p_int)\n\nprob = @ivp(u' = f(u), dim: 7, u(0) \u2208 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 \u2295 \u25a1(0.01)) \u00d7 convert(Hyperrectangle, p_int)\nprob = @ivp(u' = f(u), dim: 7, u(0) \u2208 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 \u00d7 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\u00d76 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\u00d76 DataFrame\n Row \u2502 Crt1     Crt2     Crt3     Crt4     Crt5     Crt6    \n     \u2502 Float64  Float64  Float64  Float64  Float64  Float64 \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502     3.0     12.5      2.0    120.0     14.0      3.0\n   2 \u2502     5.0     15.0      3.0    110.0     38.0      4.0\n   3 \u2502     3.0     13.0      2.0    120.0     19.0      3.0\n   4 \u2502     4.0     14.0      2.0    100.0     31.0      4.0\n   5 \u2502     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\u20d7, b\u20d7, [w])\n\nSolve [Wahba's problem](https://en.wikipedia.org/wiki/Wahba%27s_problem),\nfinding a rotation that aligns the set of points `a\u20d7` to a corresponding set of\npoints `b\u20d7` by minimizing the distance between the first set and the rotated\nsecond set.\n\nHere, `a\u20d7` and `b\u20d7` 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(\u211b) \u2254 \u03a3\u1d62 w\u1d62 \u2016a\u20d7\u1d62 - \u211b b\u20d7\u1d62\u2016\u00b2\n```\nwhere ``\u211b`` is a rotation operator, and return the quaternion corresponding to\nthe optimal ``\u211b`` that minimizes this function.\n\nNote that it is possible that the points do not uniquely determine a rotation \u2014\nas when one or both sets of points is rotationally symmetric.  In that case, the\nloss function ``L(\u211b)`` 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\u2019s method remains the best method for solving Wahba\u2019s 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 \u2254 \u03a3\u1d62 w\u1d62 a\u20d7\u1d62 b\u20d7\u1d62\u1d40\n```\nand vector\n```math\ns\u20d7 \u2254 \\begin{bmatrix}\nS\u2082\u2083-S\u2083\u2082 \\\\\nS\u2083\u2081-S\u2081\u2083 \\\\\nS\u2081\u2082-S\u2082\u2081\n\\end{bmatrix}.\n```\nThen the key matrix is\n```math\nM \u2254 \\begin{bmatrix}\nS + S\u1d40 - (\\mathrm{tr}S)\\, I\u2083 & s\u20d7 \\\\\ns\u20d7\u1d40 & \\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\u20d7::AbstractArray{<:QuatVec}, b\u20d7::AbstractArray{<:QuatVec}, w::AbstractArray{<:Real})\n    # This is Eq. (5.11) from Markley and Crassidis\n    S = sum(w[i] * a\u20d7[i].vec * b\u20d7[i].vec' for i in eachindex(a\u20d7, b\u20d7, w))\n    return _align_Wahba(S)\nend\n\nfunction align(a\u20d7::AbstractArray{<:QuatVec}, b\u20d7::AbstractArray{<:QuatVec})\n    # This is Eq. (5.11) from Markley and Crassidis\n    S = sum(a\u20d7[i].vec * b\u20d7[i].vec' for i in eachindex(a\u20d7, b\u20d7))\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) \u2254 \u03a3\u1d62 w\u1d62 |A\u1d62 - R B\u1d62|\u00b2\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 \u2014\nbut not exactly \u2014 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\u2202\u2c7c \u03a3\u1d62 w\u1d62 |A\u1d62 - \\exp[v\u2c7c] R B\u1d62|\u00b2  \u2192  2 \u27e8 e\u2c7c R \u03a3\u1d62 w\u1d62 B\u1d62 A\u0304\u1d62 \u27e9\u2080\n```\nwhere \u2192 denotes taking ``v\u2c7c\u21920``, the symbol ``\u27e8\u27e9\u2080`` denotes taking the scalar\npart, and ``e\u2c7c`` 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 \u03a3\u1d62 w\u1d62 B\u1d62 A\u0304\u1d62\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 \u221d \u03a3\u1d62 w\u1d62 A\u1d62 B\u0304\u1d62\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": "#\n# This example assumes below packages are available in your environment\n#\n\nusing StatsModelComparisons, StanSample\nusing StatsFuns, CSV, Random\n\nProjDir = @__DIR__\n\ndf = CSV.read(joinpath(ProjDir, \"..\", \"..\", \"data\", \"cars.csv\"), DataFrame)\n\ncars_stan = \"\ndata {\n    int N;\n    vector[N] speed;\n    vector[N] dist;\n}\nparameters {\n    real a;\n    real b;\n    real sigma;\n}\ntransformed parameters{\n    vector[N] mu;\n    mu = a + b * speed;\n}\nmodel {\n    a ~ normal(0, 100);\n    b ~ normal(0, 10);\n    sigma ~ exponential(1);\n    dist ~ normal(mu, sigma)    ;\n}\ngenerated quantities {\n    vector[N] log_lik;\n    for (i in 1:N)\n        log_lik[i] = normal_lpdf(dist[i] | mu[i], sigma);\n}\n\"\n\nRandom.seed!(1)\ncars_stan_model = SampleModel(\"cars.model\", cars_stan)\ndata = (N = size(df, 1), speed = df.Speed, dist = df.Dist)\nrc = stan_sample(cars_stan_model; data)\nprintln()\n\nif success(rc)\n    #stan_summary(cars_stan_model, true)\n    nt_cars = read_samples(cars_stan_model);\nend\n\nlog_lik = nt_cars.log_lik'\nn_sam, n_obs = size(log_lik)\nlppd = reshape(logsumexp(log_lik .- log(n_sam); dims=1), n_obs)\n\npwaic = [var(log_lik[:, i]) for i in 1:n_obs]\n@show -2(sum(lppd) - sum(pwaic))\nprintln()\n\n@show waic(log_lik)\nprintln()\n\nloo, loos, pk = psisloo(log_lik)\n@show -2loo\n\n", "meta": {"hexsha": "1d2ca606d134ead22f7ad3db9d69d515d9ae9039", "size": 1264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/cars_waic/cars.jl", "max_stars_repo_name": "itsdfish/StatsModelComparisons.jl", "max_stars_repo_head_hexsha": "e8683a97bc4cdc57b465fdec245300d691d59240", "max_stars_repo_licenses": ["MIT"], "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/cars_waic/cars.jl", "max_issues_repo_name": "itsdfish/StatsModelComparisons.jl", "max_issues_repo_head_hexsha": "e8683a97bc4cdc57b465fdec245300d691d59240", "max_issues_repo_licenses": ["MIT"], "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/cars_waic/cars.jl", "max_forks_repo_name": "itsdfish/StatsModelComparisons.jl", "max_forks_repo_head_hexsha": "e8683a97bc4cdc57b465fdec245300d691d59240", "max_forks_repo_licenses": ["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.4461538462, "max_line_length": 75, "alphanum_fraction": 0.6487341772, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.784670721757155}}
{"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": "using GalerkinSparseGrids\nusing Base.Test\nusing Cubature\n\n#--------------------------------------\n# Testing Differentiation\n#--------------------------------------\n\nprint(\"Testing differentiation 1-D DG basis... \")\n\nk=3\nfor l in 2:5\n    frefVD = V2Dref(1, k, l);\n    frefDV = D2Vref(1, k, l);\n    D_op = D_matrix(1, k, l, frefVD, frefDV; scheme=\"full\")\n    vcoeffs = vcoeffs_DG(1, k, l, x->cos(2*pi*x[1]); scheme=\"full\")\n    dvcoeffs = *(D_op,vcoeffs)\n    dict= V2D(1, k, l, vcoeffs; scheme=\"full\")\n    ddict = V2D(1, k, l, dvcoeffs; scheme=\"full\")\n    err = x->(reconstruct_DG(ddict,[x[1]])+2*pi*sin(2*pi*x[1]))^2\n    @test hquadrature(err, 0, 1, abstol=1.0e-10, maxevals=500)[1] < 1/(1<<(k+l-2))\nend\n\nprintln(\"Test Passed.\")\n\nprint(\"Testing differentiation 2-D full DG basis... \")\n\nD = 2\nk = 3\nfor l in 2:5\n    D_op = D_matrix(D, 1, k, l; scheme=\"full\")\n    vcoeffs = vcoeffs_DG(D, k, l, x->cos(2*pi*x[1])*cos(2*pi*x[2]); scheme=\"full\")\n    dvcoeffs = *(D_op, vcoeffs)\n    dict= V2D(D, k, l, vcoeffs; scheme=\"full\")\n    ddict = V2D(D, k, l, dvcoeffs; scheme=\"full\")\n    err = x->(reconstruct_DG(ddict,[x[1],x[2]])+2*pi*sin(2*pi*x[1])*cos(2*pi*x[2]))^2\n    @test hcubature(err, [0,0], [1,1], abstol=1.0e-10, maxevals=500)[1] < 1/(1<<(k+l-2))\nend\n\nprintln(\"Test Passed.\")\n\n", "meta": {"hexsha": "3653b280dd00f70879fddc4d29cb183a545fd447", "size": 1273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/differentiation.jl", "max_stars_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_stars_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_stars_repo_licenses": ["MIT"], "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/differentiation.jl", "max_issues_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_issues_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_issues_repo_licenses": ["MIT"], "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/differentiation.jl", "max_forks_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_forks_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_forks_repo_licenses": ["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.3095238095, "max_line_length": 88, "alphanum_fraction": 0.5648075412, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7846707165080503}}
{"text": "module Sudoku\n\n# package code goes here\n\nusing JuMP, Cbc, ChooseOptimizer\n\nexport sudoku, sudoku_check\n\n\"\"\"\n`sudoku(A::Matrix)` solves the Sudoku puzzle given by the matrix `A`.\nHere `A` is a 9-by-9 integer matrix whose nonzero entries are the\ngiven values of a Sudoku puzzle and whose zero values are the blanks.\n\"\"\"\nfunction sudoku(A::Matrix{Int})::Matrix{Int}\n    nn = size(A)[1] # number of items per row/column/block\n    n = Int(sqrt(nn)) # size of the problem: normal sudoku n = 3\n    # MOD = Model(JuMP.optimizer_with_attributes(Cbc.Optimizer, \"logLevel\" => 0))\n    set_solver_verbose(false)\n    MOD = Model(get_solver())\n\n    # variable X[i,j,k] = 1 means there's a k in cell (i,j)\n    @variable(MOD, X[1:nn, 1:nn, 1:nn], Bin)\n\n    ########### model constraints ##################\n    @constraints(\n        MOD,\n        begin\n            oneKPerCell, sum(X[1:nn, 1:nn, k] for k \u2208 1:nn) .== 1\n            oneKPerRow, sum(X[1:nn, j, 1:nn] for j \u2208 1:nn) .== 1\n            oneKPerCol, sum(X[i, 1:nn, 1:nn] for i \u2208 1:nn) .== 1\n            oneKPerBlock,\n            sum.(X[i:i+n-1, j:j+n-1, k] for k \u2208 1:nn, i \u2208 1:n:nn, j \u2208 1:n:nn) .== 1\n        end\n    )\n\n    # Process values in A\n    nonZeroIndices = findall(i -> i != 0, A)\n    for i in nonZeroIndices\n        @constraint(MOD, X[i, A[i]] == 1)\n    end\n\n    # now solve and extract the solution\n    optimize!(MOD)\n    status = Int(termination_status(MOD))\n    if status != 1\n        error(\"No solution to this Sudoku puzzle\")\n    end\n\n    return Int.(sum(value.(X[:, :, k]) * k for k = 1:nn))\nend\n\n\n\"\"\"\n`sudoku_check(A)` checks if a 9x9 matrix is a valid solution to a Sudoku\npuzzle. That is, we check that every row, column, and 3x3 submatrix contains\nthe values 1 through 9 exactly once each.\n\"\"\"\nfunction sudoku_check(A::Matrix{Int})::Bool\n    nn = size(A)[1] # number of items per row/column/block\n    n = Int(sqrt(nn)) # size of the problem: normal sudoku n = 3\n\n    # All items in a row are 1:9\n    if !all(mapslices(aux -> sort(aux) == 1:nn, A, dims = 1))\n        return false\n    end\n\n    # All items in a column are 1:9\n    if !all(mapslices(aux -> sort(aux) == 1:nn, A, dims = 2))\n        return false\n    end\n\n    # Finally we check each block, if we get this far, the sucoku will be correct\n    # or not decided by this condition\n    return all(\n        aux -> sort(aux) == 1:nn,\n        vec.([A[i:i+n-1, j:j+n-1] for i \u2208 1:n:nn, j \u2208 1:n:nn]),\n    )\nend\n\ninclude(\"sudoku_print.jl\")\ninclude(\"examples.jl\")\n\nend # module\n", "meta": {"hexsha": "26efac7fa911c6820c59e391e6ffe851ed8df613", "size": 2486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Sudoku.jl", "max_stars_repo_name": "scheinerman/Sudoku.jl", "max_stars_repo_head_hexsha": "ff57d5dcce7737aef16c329b79bc29f9c2ce59bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T15:40:41.000Z", "max_issues_repo_path": "src/Sudoku.jl", "max_issues_repo_name": "scheinerman/Sudoku.jl", "max_issues_repo_head_hexsha": "ff57d5dcce7737aef16c329b79bc29f9c2ce59bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-14T17:17:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T15:25:20.000Z", "max_forks_repo_path": "src/Sudoku.jl", "max_forks_repo_name": "scheinerman/Sudoku.jl", "max_forks_repo_head_hexsha": "ff57d5dcce7737aef16c329b79bc29f9c2ce59bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-14T15:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T15:24:25.000Z", "avg_line_length": 29.5952380952, "max_line_length": 83, "alphanum_fraction": 0.5961383749, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7846707132590789}}
{"text": "using Test, DiscreteExteriorCalculus, DiscretePDEs\nusing UniqueVectors: UniqueVector\nusing LinearAlgebra: eigen\n\nfile_name = joinpath(@__DIR__, \"sphere.geo\")\ngeo_write!(file_name, characteristic_length_factor=.3,\n    footer=\"\"\"\n    Sphere(1) = {0, 0, 0, 1, -Pi/2, Pi/2, 2*Pi};\n    \"\"\")\ninitialize!()\ngmsh_open!(file_name)\nN, K = 3, 3\nmesh!(K)\n\nnode_tags, points, tcomp = get_triangulated_complex(N, K)\n@test typeof(tcomp) <: TriangulatedComplex{N, K}\ncomp = tcomp.complex\norient!(comp)\nm = Metric(N)\nmesh = Mesh(tcomp, circumcenter(m))\n\nlaplacian = differential_operator(m, mesh, \"\u0394\", 1, true)\n\nvals, vects = eigen(collect(laplacian))\ninds = sortperm(vals)\nvals, vects = vals[inds], vects[:, inds]\n\n# solutions are spherical harmonics (or combinations of them since they\n# are degenerate)\ncorrect_modes = vcat([[l*(l+1) for _ in -l:l] for l in 0:3]...)\n\n@testset \"laplacian on a sphere\" begin\n    @test isapprox(vals[1:length(correct_modes)], correct_modes, rtol=1e-2)\nend\n\nif false # set to true to display plots with Gmsh\n    comp_points = UniqueVector([c.points[1] for c in comp.cells[1]])\n    ordering = [findfirst(isequal(p), comp_points) for p in points]\n    for i in 1:length(correct_modes)\n        v = vects[:,i]\n        add_field!(\"Eigenvector\", node_tags, v[ordering])\n    end\n    gui!()\nend\nrm(file_name)\n", "meta": {"hexsha": "232eb34d674a8aae43b237c928a0ba4b1becdee6", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_laplacian_sphere.jl", "max_stars_repo_name": "mgscheer/DiscretePDEs.jl", "max_stars_repo_head_hexsha": "362030b2fecd7989a14d91459ed014c0c86963df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-06-26T08:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T21:35:27.000Z", "max_issues_repo_path": "test/test_laplacian_sphere.jl", "max_issues_repo_name": "mgscheer/DiscretePDEs.jl", "max_issues_repo_head_hexsha": "362030b2fecd7989a14d91459ed014c0c86963df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-11T20:45:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T03:14:10.000Z", "max_forks_repo_path": "test/test_laplacian_sphere.jl", "max_forks_repo_name": "mgscheer/DiscretePDEs.jl", "max_forks_repo_head_hexsha": "362030b2fecd7989a14d91459ed014c0c86963df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-06-26T04:18:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T14:28:05.000Z", "avg_line_length": 28.6086956522, "max_line_length": 75, "alphanum_fraction": 0.6968085106, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7846707127515675}}
{"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, \u03f5=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": "#!/usr/bin/env julia\n\nmodule PE14\n\n# collatz(n::Int) = iseven(n) ? collatz(n\u00f72)+1 : collatz(3n+1)+1\n\nfunction collatz(n::Integer)\n    local len=0;\n    while n>1\n        n = iseven(n) ? n\u00f72 : 3n+1;\n        len += 1;\n    end\n    len\nend\n\nend\n\nexport pe14\n\npe14(n::Integer=10^6)=PE14.collatz.(1:n)|>findmax|>last\n\nif !haskey(ENV,\"PROJECT_EULER_WITHOUT_RESULT\")\n    pe14()|>print\nend\n", "meta": {"hexsha": "b36686e1c1e1173c8e6d4c1b24eeff7b9e9660fa", "size": 380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "14. Longest Collatz sequence/14.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": "14. Longest Collatz sequence/14.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": "14. Longest Collatz sequence/14.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": 15.2, "max_line_length": 64, "alphanum_fraction": 0.6078947368, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.7846550281473745}}
{"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\u2019s Iterated Interpolation\n- Newton\u2019s 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\u2080::Real; tab::Bool=false)\n\ninput two vector, x and y. satisfy the function `y=f(x)`, then input x\u2080, which you want\nto  approximate f(x\u2080). 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\u2080::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\u2080 - x[i-j+1])*res[i, j-1] - (x\u2080 - 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\u2013Difference 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, \u03b1 = 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        \u03b1[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    \u03bc = 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]*\u03bc[i-1]\n        \u03bc[i] = h[i]/l[i]\n        z[i] = (\u03b1[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] - \u03bc[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 \u2208\",\"[$(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    \u03b1 = 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    \u03b1[1] = 3(y[2] - y[1])/h[1] - 3*endpoint[1]\n    \u03b1[n] = 3*endpoint[2] - 3*(y[n] - y[n-1])/h[n-1]\n    for i in 2:n-1\n        \u03b1[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    \u03bc = fill(0.5, n)\n    z = fill(\u03b1[1]/l[1], n)\n    for i in 2:n-1\n        l[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*\u03bc[i-1]\n        \u03bc[i] = h[i]/l[i]\n        z[i] = (\u03b1[i] - h[i-1]*z[i-1])/l[i]\n    end\n    l[n] = h[n-1]*(2 - \u03bc[n-1])\n    z[n] = (\u03b1[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] - \u03bc[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 \u2208\",\"[$(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": "using ITensors\n\n# Text visualization, prints to screen\nusing ITensorUnicodePlots\n\n# Visualization in an interactive window\nusing ITensorGLMakie\n\nusing LinearAlgebra\n\nITensorVisualizationBase.set_backend!(\"UnicodePlots\")\n\nprintln(\"\n#######################################################\n# Tutorial 1                                          #\n#                                                     #\n# 1-site state basics                                 #\n#######################################################\n\")\n\ni = Index(2)\n\n#\n# Making states\n#\n\n# Make an \"up\" state (+1 eigenvalue of `Z`),\n# denoted as `|Z+\u27e9`.\n\n# Define through setting elements\nZp = ITensor(i)\nZp[i => 1] = 1.0\n\n# Alternative syntax, construct from a Vector\nZp = ITensor([1 0], i)\n\n# Make an \"down\" state (-1 eigenvalue of `Z`),\n# denoted as `|Z-\u27e9`.\n\n# Define through setting elements\nZm = ITensor(i)\nZm[i => 2] = 1.0\n\n# Alternative syntax, construct from a Vector\nZm = ITensor([0 1], i)\n\n@visualize Zm\n\n# Can do algebra, inner products, etc:\n@show (Zp + Zm) / \u221a2\n@show dag(Zp) * Zm\n", "meta": {"hexsha": "0d2b647f62ed49de60be22537cf3acae8196de39", "size": 1056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/01_one_site_state_basics.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/01_one_site_state_basics.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/01_one_site_state_basics.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.3076923077, "max_line_length": 55, "alphanum_fraction": 0.5284090909, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7846433633507074}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.18\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.18\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u25502bd08a88-3afb-11eb-03e1-c3af32635947\n# \u2560\u25502bd0c412-3afb-11eb-1e28-27323df7bbe6\n# \u2560\u25502bd13636-3afb-11eb-3c12-2d5a0c0e4b13\n# \u255f\u2500475ff888-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(; \u03b7::Real=0.001, \u03b3::Real=0.01, \u03f5::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    \u03f5::Float64\n    \u03b7::Float64\n    \u03b3::Float64\n    E_g\u00b2_t::AbstractArray\nend\n\nfunction RMSprop(; \u03b7::Real=0.001, \u03b3::Real=0.01, \u03f5::Real=1e-8)\n    @assert \u03b7 > 0.0 \"\u03b7 must be greater than 0\"\n    @assert \u03b3 > 0.0 \"\u03b3 must be greater than 0\"\n    @assert \u03f5 > 0.0 \"\u03f5 must be greater than 0\"\n\n    RMSprop(\"RMSprop\", 0, \u03f5, \u03b7, \u03b3, [])\nend\n\nparams(opt::RMSprop) = \"\u03f5=$(opt.\u03f5), \u03b7=$(opt.\u03b7), \u03b3=$(opt.\u03b3)\"\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\u00b2_t = zero(g_t)\n    end\n\n    # accumulate gradient\n    opt.E_g\u00b2_t = opt.\u03b3 * opt.E_g\u00b2_t + (one(T) - opt.\u03b3) * (g_t .^ 2)\n\n    # compute update\n    RMS_g_t = sqrt.(opt.E_g\u00b2_t .+ opt.\u03f5)\n    \u03b4 = opt.\u03b7 * g_t ./ RMS_g_t\n\n    return \u03b4\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\u03b1SS    = [20, 20]\n\u03b2SS    = [10, 10]\n\u03b1Prior = [20, 30]\n\u03b2Prior = [20, 10]\nM = 2\nmixprior = [0.5, 0.5]\n\u03b1Post      = \u03b1Prior + \u03b1SS\n\u03b2Post      = \u03b2Prior + \u03b2SS\n\nfunction mixBetaPost_()\n    logmarglik  = lbeta(\u03b1Prior+\u03b1SS, \u03b2Prior+\u03b2SS)-lbeta(\u03b1Prior, \u03b2Prior)\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(\u03b8, Z, \u03b1, \u03b2)\n        sum([Z[i].*pdf(Beta(\u03b1[i], \u03b2[i]), \u03b8) for i=1:length(Z)])\n    end\n    \n    prior = evalpdf(grid, mixprior, \u03b1Prior, \u03b2Prior)\n    post  = evalpdf(grid, mixpost, \u03b1Post, \u03b2Post)\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(\u03b1Post[i], \u03b2Post[i], .5) for i=1:length(\u03b1Post)]))\n    pbiasedSimple = 1-sf_beta_inc(\u03b1Post[1], \u03b2Post[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": "using Test\nusing MatrixLM\n\nusing DataFrames\nusing Random\nusing LinearAlgebra\nusing GLM\n\n@testset \"GLM compatible\" begin \n\n    # Tolerance for tests\n    tol = 10.0^(-7)\n    \n    # Dimensions of matrices \n    n = 100\n    m = 200\n    p = 10\n    q = 20\n    \n    # Generate some matrices.\n    Random.seed!(4)\n    X = rand(n,p)\n    Z = rand(m,q)\n    B = rand(1:20,p,q)\n    E = randn(n,m)\n    Y = X*B*transpose(Z)+E\n    \n    # Data frame to be passed into lm\n    GLMData = DataFrame(hcat(vec(Y), kron(Z,X)), :auto)\n    # lm estimate\n    GLMEst = lm(Matrix(GLMData[:,2:end]), Vector(GLMData[:,1]))\n    \n    # Put together RawData object for MLM\n    MLMData = RawData(Response(Y), Predictors(X, Z))\n    # mlm estimate\n    # MLMEst = mlm(MLMData, hasXIntercept = false, hasZIntercept = false)\n    MLMEst = mlm(MLMData, hasXIntercept = false, hasZIntercept = false)\n    \n    @test isapprox(GLM.coef(GLMEst), vec(MatrixLM.coef(MLMEst)), atol=tol)\n    @test isapprox(GLM.predict(GLMEst), vec(MatrixLM.predict(MLMEst).Y), atol=tol)\n    @test LinearAlgebra.issymmetric(round.(MLMEst.sigma, digits=10)) # and also positive semi-definite?\n\nend\n\n\n# Tests for variance shrinkage, WLS\n# Contrasts\n# Permutations\n", "meta": {"hexsha": "4a801a0e803aa81558b2d968ab526c1c5352a5ae", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 24.3265306122, "max_line_length": 103, "alphanum_fraction": 0.6426174497, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7846433561950531}}
{"text": "\"\"\"\n    HyperSphere{N, T}\n\nA `HyperSphere` is a generalization of a sphere into N-dimensions.\nA `center` and radius, `r`, must be specified.\n\"\"\"\nstruct HyperSphere{N,T} <: GeometryPrimitive{N,T}\n    center::Point{N,T}\n    r::T\nend\n\n\"\"\"\n    Circle{T}\n\nAn alias for a HyperSphere of dimension 2. (i.e. `HyperSphere{2, T}`)\n\"\"\"\nconst Circle{T} = HyperSphere{2,T}\n\n\"\"\"\n    Sphere{T}\n\nAn alias for a HyperSphere of dimension 3. (i.e. `HyperSphere{3, T}`)\n\"\"\"\nconst Sphere{T} = HyperSphere{3,T}\n\nHyperSphere{N}(p::Point{N,T}, number) where {N,T} = HyperSphere{N,T}(p, convert(T, number))\n\nwidths(c::HyperSphere{N,T}) where {N,T} = Vec{N,T}(radius(c) * 2)\nradius(c::HyperSphere) = c.r\norigin(c::HyperSphere) = c.center\n\nBase.minimum(c::HyperSphere{N,T}) where {N,T} = Vec{N,T}(origin(c)) - Vec{N,T}(radius(c))\nBase.maximum(c::HyperSphere{N,T}) where {N,T} = Vec{N,T}(origin(c)) + Vec{N,T}(radius(c))\n\nfunction Base.in(x::AbstractPoint, c::HyperSphere)\n    return norm(origin(c) - x) \u2264 radius(c)\nend\n\ncentered(S::Type{HyperSphere{N,T}}) where {N,T} = S(Vec{N,T}(0), T(0.5))\nfunction centered(::Type{T}) where {T<:HyperSphere}\n    return centered(HyperSphere{ndims_or(T, 3),eltype_or(T, Float32)})\nend\n\nfunction coordinates(s::Circle, nvertices=64)\n    rad = radius(s)\n    inner(fi) = Point(rad * sin(fi + pi), rad * cos(fi + pi)) .+ origin(s)\n    return (inner(fi) for fi in LinRange(0, 2pi, nvertices))\nend\n\nfunction texturecoordinates(s::Circle, nvertices=64)\n    return coordinates(Circle(Point2f(0.5), 0.5f0), nvertices)\nend\n\nfunction coordinates(s::Sphere, nvertices=24)\n    \u03b8 = LinRange(0, pi, nvertices)\n    \u03c6 = LinRange(0, 2pi, nvertices)\n    inner(\u03b8, \u03c6) = Point(cos(\u03c6) * sin(\u03b8), sin(\u03c6) * sin(\u03b8), cos(\u03b8)) .* s.r .+ s.center\n    return ivec((inner(\u03b8, \u03c6) for \u03b8 in \u03b8, \u03c6 in \u03c6))\nend\n\nfunction texturecoordinates(s::Sphere, nvertices=24)\n    ux = LinRange(0, 1, nvertices)\n    return ivec(((\u03c6, \u03b8) for \u03b8 in reverse(ux), \u03c6 in ux))\nend\n\nfunction faces(sphere::Sphere, nvertices=24)\n    return faces(Rect(0, 0, 1, 1), (nvertices, nvertices))\nend\n\nfunction normals(s::Sphere{T}, nvertices=24) where {T}\n    return coordinates(Sphere(Point{3,T}(0), 1), nvertices)\nend\n", "meta": {"hexsha": "de7c59b6f77f0a390c5b3465c4f9a4ea2d08a5df", "size": 2156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/primitives/spheres.jl", "max_stars_repo_name": "alhirzel/GeometryBasics.jl", "max_stars_repo_head_hexsha": "c4b7cb5fb7a9f5c7d693d0726ae76f2a78a5d0ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 111, "max_stars_repo_stars_event_min_datetime": "2019-08-29T15:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:17:29.000Z", "max_issues_repo_path": "src/primitives/spheres.jl", "max_issues_repo_name": "alhirzel/GeometryBasics.jl", "max_issues_repo_head_hexsha": "c4b7cb5fb7a9f5c7d693d0726ae76f2a78a5d0ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 129, "max_issues_repo_issues_event_min_datetime": "2019-10-24T23:30:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T09:40:50.000Z", "max_forks_repo_path": "src/primitives/spheres.jl", "max_forks_repo_name": "alhirzel/GeometryBasics.jl", "max_forks_repo_head_hexsha": "c4b7cb5fb7a9f5c7d693d0726ae76f2a78a5d0ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:00:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T01:28:10.000Z", "avg_line_length": 29.5342465753, "max_line_length": 91, "alphanum_fraction": 0.6549165121, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7846433544857399}}
{"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, [\u03b5::Real])\r\n\r\nUse the binary search algorithm to find a root of `f` between `a` and `b` with maximum trucation error `\u03b5`.\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] - \u03c0) < 5e-6\r\ntrue\r\n```\r\n\"\"\"\r\nfunction binarysearch(f::Function, a::Real, b::Real, \u03b5::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\u03b5\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 \u03b5 of the root\r\n    return ((a+b)/2,N)\r\n\r\nend\r\n\r\n\"\"\"\r\n    fixedpointiteration(f::Function, x\u2080::Real, N\u2098\u2090\u2093::Int, [\u03b5::Real])\r\n\r\nUse the fixed point iteration algorithm to converge on a fixed point of `f`, with starting value `x\u2080`.\r\n\r\nTerminate if consecutive iterations differ by less than `\u03b5`, or after `N\u2098\u2090\u2093` 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\u2080::Real, N\u2098\u2090\u2093::Int, \u03b5::Real = eps(Float64))\r\n\r\n    # Sets up the initial values for the algorithm\r\n    n = 1\r\n    x\u2099\u208b\u2081 = convert(Float64,x\u2080)\r\n    x\u2099 = f(x\u2099\u208b\u2081)\r\n    xvalues = [x\u2099\u208b\u2081, x\u2099]\r\n\r\n    # Iteratively advances the algorithm by evaluating f at the previous result and storing it\r\n    while abs(x\u2099\u208b\u2081 - x\u2099) \u2265 \u03b5 && n < N\u2098\u2090\u2093\r\n        n += 1\r\n        x\u2099\u208b\u2081, x\u2099 = x\u2099, f(x\u2099)\r\n        push!(xvalues,x\u2099)\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    \u03b4 = (maxx - minx)/100\r\n    xticks = (minx - 10\u03b4):\u03b4:(maxx + 10\u03b4)\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    \u03b1 = rLr / dot( L_p, L_p )  # ???\n    #\n    x_old = x[:]\n    x[:] = x[:] + \u03b1 * p[:]  # FIXME use x[:] to force x to be copied, not referenced\n    #\n    r_old = r[:]\n    rLr_old = rLr\n    r[:] = r[:] - \u03b1 * L_p[:]\n    #\n    norm_res = sqrt( dot( r, r ) )\n    norm_p   = sqrt( dot( p, p ) )\n    \u0394x = abs(x-x_old)\n    norm_\u0394x = sqrt( dot( \u0394x, \u0394x ) )\n    if showprogress\n      @printf(\"%8d %18.10e %18.10e %18.10e\\n\", iter, norm_res, norm_p, norm_\u0394x)\n    end\n    #\n    if norm_res < TOL || norm_p < TOL || norm_\u0394x < 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    \u03b2 = dot( r, L_r ) / rLr_old\n    #\n    p_old = p[:]\n    p = r[:] + \u03b2 * p[:]\n    #\n    L_p = L_r[:] + \u03b2 * 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": "function partition!(A, p, r)\n\tx = A[r]\n\ti = p-1\n\tfor j in p:(r-1)\n\t    if A[j] <= x\n\t        i += 1\n\t        tmp = A[i]\n\t        A[i] = A[j]\n\t        A[j] = tmp\n\t    end\n\tend\n\ttmp = A[r]\n\tA[r] = A[i+1]\n\tA[i+1] = tmp\n\treturn i+1\nend\n\nfunction quick_sort!(A, p, r)\n    if p < r\n        q = partition!(A, p, r)\n        quick_sort!(A, p, q-1)\n        quick_sort!(A, q+1, r)\n    end\n    return A\nend\n\nfunction algdat_sort!(A)\n    return quick_sort!(A, 1, length(A))\nend\n\n\nfunction bisect_left(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_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\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\n\nfunction find_median(A, lower, upper)\n    min_index = bisect_left(A, 1, length(A)+1, lower)\n    max_index = bisect_right(A, 1, length(A)+1, upper) - 1\n\n    if (max_index-min_index+1)%2 == 0\n        i = floor(Int, (max_index-min_index)/2) \n        i += min_index\n        return (A[i] + A[i+1])/2\n    else\n        return A[min_index + floor(Int, (max_index - min_index)/2)]\n    end\nend\n", "meta": {"hexsha": "6d342ed30cdbde2c02a23c57d63b51b91d2e4954", "size": 1338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "O3/O3-median.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-median.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-median.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": 18.8450704225, "max_line_length": 67, "alphanum_fraction": 0.4820627803, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7845651709802204}}
{"text": "using JuMP\nusing GLPK\ninclude(\"Data.jl\")\n\n\n# Int8: -128 -> 127\n# Int16 : -32.768 -> 32.767\n# Int32 : -2.147.483.648 -> 2.147.483.647\n# Int64 : - 2^63 -> 2^63 - 1\n# Float32, Float64, UINT8, UInt16, etccdddd\n\nfile = map(file->string(file), ARGS)\n\nif(length(file) != 1)\n  println(\"Wrong Pattern\")\n  println(\"julia main.jl instances/questao2.txt\")\nend\n\nfilepath = file[1]\n\nfunction solver(filepath)\n  capacity = Array{Int64,2}\n  d1 = Main.DataReader.Data(0,0,0,0,[],[])\n\n  capacity, d1 = Main.DataReader.readData(filepath)\n\n  costs = zeros(Int64,(d1.N_vertex, d1.N_vertex))\n\n  for i in 1:d1.N_vertex\n    if i in d1.start_nodes\n      costs[i,d1.end_node] = 1\n    end\n  end\n\n  mcfp = Model(GLPK.Optimizer)\n\n  n = d1.N_vertex\n\n  @variable(mcfp, x[1:n,1:n] >= 0) #ok\n\n  # capacity  --------- taok\n  for i in 1:n\n    for j in 1:n\n      cap = capacity[i,j]\n      @constraint(mcfp, x[i,j] - capacity[i,j] <= 0)\n    end\n  end\n\n  #sum 0 // demand / offer\n  for i in 1:n\n    if i in d1.start_nodes\n      @constraint(mcfp, sum(x[i,j] - x[j,i] for j in 1:n) == d1.max_possible_flow[i])\n    elseif i == d1.end_node\n      global max_end_flow = 0\n      for node in d1.start_nodes\n        max_end_flow += d1.max_possible_flow[node]\n      end\n      @constraint(mcfp, sum(x[i,j] - x[j,i] for j in 1:n) == max_end_flow * -1)\n    else\n      @constraint(mcfp, sum(x[i,j] - x[j,i] for j in 1:n) == 0) \n    end\n  end\n\n\n  @objective(mcfp, Min, sum(costs[i,j] * x[i,j] for i in 1:n, j in 1:n))\n\n  #println(mcfp)\n  function solve_mcfp(mcfp)\n    JuMP.optimize!(mcfp)\n    @show JuMP.termination_status(mcfp)\n    println(\"Max Flow = \", max_end_flow - objective_value(mcfp))\n\n  end\n  @time solve_mcfp(mcfp)\nend\n\n# run 3 times to compile the func in the first one\nsolver(filepath)\nsolver(filepath)\nsolver(filepath)", "meta": {"hexsha": "3f24f7162ca544ac1b9ead6f09d0e48ddeae768b", "size": 1779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PO_class/assignment_1/JuMP/main.jl", "max_stars_repo_name": "ItamarRocha/Operations-Research", "max_stars_repo_head_hexsha": "55c4d54959555c3b9d54641e76eb6cfb2c011a2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-04T01:50:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T21:54:52.000Z", "max_issues_repo_path": "PO_class/assignment_1/JuMP/main.jl", "max_issues_repo_name": "ItamarRocha/Operations-Research", "max_issues_repo_head_hexsha": "55c4d54959555c3b9d54641e76eb6cfb2c011a2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PO_class/assignment_1/JuMP/main.jl", "max_forks_repo_name": "ItamarRocha/Operations-Research", "max_forks_repo_head_hexsha": "55c4d54959555c3b9d54641e76eb6cfb2c011a2c", "max_forks_repo_licenses": ["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.2375, "max_line_length": 85, "alphanum_fraction": 0.6222596965, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7845566907682864}}
{"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\u03b1 = [150, 230, 260] # land cost\n\u03b2 = [238, 210, 0]   # purchasing cost\n\u03bb = [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\u039e = [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, \u03be[c in C] ~ \u039e[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(\u03be)\n    0 <= w[C], Infinite(\u03be)\nend)\n\n# Next, the objective is defined using `@objective` and [`\ud835\udd3c`](@ref):\n@objective(model, Min, sum(\u03b1[c] * x[c] for c in C) +\n                       \ud835\udd3c(sum(\u03b2[c] * y[c] - \u03bb[c] * w[c] for c in C), \u03be))\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], \u03be[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(\u03be)\nend)\n\n# Redefine the objective:\n@objective(model, Min, sum(\u03b1[c] * x[c] for c in C) + t + 1 / (1 - 0.95) * \ud835\udd3c(q, \u03be))\n\n# Add the max constraint:\n@constraint(model, q >= sum(\u03b2[c] * y[c] - \u03bb[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(\u03b1[c] * x_opt[c] for c in C) - 1 / num_scenarios *\n            sum(\u03b2[c] * y_opt[c][k] - \u03bb[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": "using HypothesisTests, Distributions, Test, Random\nusing HypothesisTests: default_tail\n\n@testset \"Anderson-Darling\" begin\n@testset \"One sample test\" begin\n    n = 1000\n    Random.seed!(1984948)\n\n    x = rand(Normal(), n)\n    t = OneSampleADTest(x, Normal())\n    @test t.A\u00b2 \u2248 0.2013 atol=0.1^4\n    @test pvalue(t) \u2248 0.99 atol=0.1^4\n    @test default_tail(t) == :right\n\n    x = rand(DoubleExponential(), n)\n    t = OneSampleADTest(x, Normal())\n    @test t.A\u00b2 \u2248 10.7439 atol=0.1^4\n    @test pvalue(t) \u2248 0.0 atol=0.1^4\n\n    x = rand(Cauchy(), n)\n    t = OneSampleADTest(x, Normal())\n    @test pvalue(t) \u2248 0.0 atol=0.1^4\n\n    x = rand(LogNormal(), n)\n    t = OneSampleADTest(x, Normal())\n    @test pvalue(t) \u2248 0.0 atol=0.1^4\n\n    x = rand(Uniform(), n)\n    t = OneSampleADTest(x, Uniform())\n    @test pvalue(t) \u2248 0.145 atol=0.1^4\n\n    x = rand(Uniform(0, 1.8), n)\n    t = OneSampleADTest(x, Uniform())\n    @test pvalue(t) \u2248 0.5112 atol=0.1^4\n\n    x = rand(Exponential(), n)\n    t = OneSampleADTest(x, Exponential())\n    @test pvalue(t) \u2248 0.9427 atol=0.1^4\nend\n\n@testset \"k-sample test\" begin\n    Random.seed!(948574875)\n    samples = Any[\n        [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0],\n        [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8],\n        [34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0],\n        [34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]\n    ]\n\n    t = KSampleADTest(samples...)\n    @test t.A\u00b2k \u2248 8.3926 atol=0.1^4\n    @test t.\u03c3 \u2248 1.2038 atol=0.1^4\n    @test pvalue(t) \u2248 0.0022 atol=0.1^4\n    @test default_tail(t) == :right\n\n    ts = KSampleADTest(samples..., nsim = 20000);\n    @test pvalue(ts) \u2248 0.00155 atol=0.1^3\n\n    t = KSampleADTest(samples..., modified = false)\n    @test t.A\u00b2k \u2248 8.3559 atol=0.1^4\n    @test t.\u03c3 \u2248 1.2038 atol=0.1^4\n    @test pvalue(t) \u2248 0.0023 atol=0.1^4\n\n    ts = KSampleADTest(samples..., modified = false, nsim = 20000);\n    @test pvalue(ts) \u2248 0.00150 atol=0.1^3\nend\n\n@testset \"more tests\" begin\n    Random.seed!(31412455)\n    samples = Any[rand(Normal(), 50), rand(Normal(0.5), 30)]\n    t = KSampleADTest(samples...)\n    @test pvalue(t) < 0.05\n\n    samples = Any[rand(Normal(), 50), rand(Normal(), 30), rand(Normal(), 20)]\n    t = KSampleADTest(samples...)\n    @test pvalue(t) > 0.05\n\n    @test pvalue(OneSampleADTest(vcat(rand(Normal(),500), rand(Beta(2,2),500)), Beta(2,2))) \u2248 0.0 atol=0.1^4\n\n    n = 1000\n    x = rand(Exponential(), n)\n    @test pvalue(KSampleADTest(rand(1000),randn(1000))) \u2248 0.0 atol=eps()\n    @test pvalue(KSampleADTest(x,x,x,x,x,x)) \u2248 1.0\nend\n\nend\n", "meta": {"hexsha": "f082366060a7d201450b286f75b0b0c0781c33a0", "size": 2529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/anderson_darling.jl", "max_stars_repo_name": "bkamins/HypothesisTests.jl", "max_stars_repo_head_hexsha": "283bdeb947ae99c634deaec93291615a22100077", "max_stars_repo_licenses": ["MIT"], "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/anderson_darling.jl", "max_issues_repo_name": "bkamins/HypothesisTests.jl", "max_issues_repo_head_hexsha": "283bdeb947ae99c634deaec93291615a22100077", "max_issues_repo_licenses": ["MIT"], "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/anderson_darling.jl", "max_forks_repo_name": "bkamins/HypothesisTests.jl", "max_forks_repo_head_hexsha": "283bdeb947ae99c634deaec93291615a22100077", "max_forks_repo_licenses": ["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.0689655172, "max_line_length": 108, "alphanum_fraction": 0.5860023725, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7845566855974335}}
{"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\u03f5 = 0.2\nL = -6\u03f5^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\u03f5*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), \u201cA New Criterion for Automatic Multilevel Thresholding\u201d, 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\u209b = 0\r\n    G\u209b = 0\r\n    G\u2032\u209b = 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\u209b += p[s]\r\n        G\u209b += p[s]^2\r\n        G\u2032\u209b -= p[s]^2\r\n\r\n        # Calculate total correlation.\r\n        TC = -log(G\u209b * G\u2032\u209b) + 2 * log(P\u209b * (1 - P\u209b))\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 \u03c1 = 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\u03b1(t) = 1.0\n\u03b2(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] += \u03b1(t)/h^2\n    b[end] += \u03b2(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": "# Example for building JOLI operator having functions\n# defining action for forward and transpose mapping\n#\n# we will use plain matrix to fake the actions\n\nusing JOLI\n\n# forward function\nfunction fwd(A::AbstractMatrix,vin::AbstractVector,RDT::DataType)\n    vout=A*vin\n    return jo_convert(RDT,vout)\nend\n\n# transpose function\nfunction fwdT(A::AbstractMatrix,vin::AbstractVector,RDT::DataType)\n    vout=A.'*vin\n    return jo_convert(RDT,vout)\nend\n\n# define matrix for mapping functions\na=rand(ComplexF32,3,3)\n\n# define JOLI operator with desired domain and range using\n# using joLinearFunctionFwdT constructor\n# note forced dropping imaginary part for transpose/adjoint operators\nA=joLinearFunctionFwdT(3,3,\n    v->fwd(a,v,ComplexF64),v->fwdT(a,v,Float32),\n    Float32,ComplexF64;name=\"my_A\")\nshow(A)\n\n# disable warining for implicit inacurate conversions - use only after debugging your code\njo_convert_warn_set(false)\n\n# display elements of the operator\nprintln(\"forward: A\")\nshow(A); display(elements(A)); println()\nprintln(\"transpose: A.'\")\nshow(A.'); display(elements(A.')); println()\nprintln(\"adjoint: A'\")\nshow(A'); display(elements(A')); println()\nprintln(\"conjugate: conj(A)\")\nshow(conj(A)); display(elements(conj(A))); println()\n\n# multiply by vector\nx=rand(Float32,3)\ny=A*x\nprintln(\"y: \",y)\nxx=A'*y\nprintln(\"xx: \",xx)\n\n", "meta": {"hexsha": "4ebbbef5b2b687d3e8766b28a0f8ff4842ea49de", "size": 1329, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LinearFunction_ForwardAndTranspose.jl", "max_stars_repo_name": "slimgroup/JOLI.jl", "max_stars_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-02-28T21:50:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T16:03:45.000Z", "max_issues_repo_path": "examples/LinearFunction_ForwardAndTranspose.jl", "max_issues_repo_name": "slimgroup/JOLI.jl", "max_issues_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-08-03T21:02:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T20:17:27.000Z", "max_forks_repo_path": "examples/LinearFunction_ForwardAndTranspose.jl", "max_forks_repo_name": "slimgroup/JOLI.jl", "max_forks_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-11-11T02:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T16:06:20.000Z", "avg_line_length": 26.0588235294, "max_line_length": 90, "alphanum_fraction": 0.7426636569, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7844959646862357}}
{"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(\u03b1,\u03b2,\u03b3) yields a function f\n    which calculates the ode rule\n\n        \u03b1x'' + \u03b2x' + \u03b3x = 0\n\n    using the substitution\n\n        y = [x; x']\n\n        y[1]' = y[2]\n\n        y[2]' = -\u03b1^-1 (\u03b2y[2] + \u03b3y[1])\n\n\"\"\"\nfunction secondorder(\u03b1, \u03b2, \u03b3)\n        return (t, y) -> [y[2]; -(\u03b2*y[2] + \u03b3*y[1])/\u03b1]\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) = \u221a(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\u2080,t\u2080) 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\u2081, c\u2082): the solution at t when the coefficients are c\u2081, c\u2082\n   - deriv(t, c\u2081, c\u2082): the derivative at t when the coefficients are c\u2081, c\u2082\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\u2081, r\u2082 = roots(a,b,c)\n    if real(d) == d\n        info(\"characteristic polynomial has real roots\")\n        return (t, c\u2081, c\u2082) -> c\u2081 * exp(r\u2081*t) + c\u2082*exp(r\u2082*t),\n               (t, c\u2081, c\u2082) -> c\u2081*r\u2081*exp(r\u2081*t) + c\u2082*r\u2082*exp(r\u2082*t)\n               \n    end\n    if imag(d) != 0.0\n        info(\"characteristic polynomial has complex roots\")\n        @show \u03b1, \u03b2 = -b/2a, imag(d/2a)\n        func(t, c\u2081, c) = begin\n            return (c\u2081*exp(\u03b1*t)*cos(\u03b2*t) + c*exp(\u03b1*t)*sin(\u03b2*t))\n        end\n        deriv(t,c\u2081,c\u2082) = begin\n            exp\u03b1 = exp(\u03b1*t)\n            cos\u03b2 = cos(\u03b2*t)\n            sin\u03b2 = sin(\u03b2*t)\n            return (-\u03b2*c\u2081*exp\u03b1*sin\u03b2 +\n                    \u03b1*c\u2082*exp\u03b1*sin\u03b2 +\n                    \u03b1*c\u2081*exp\u03b1*cos\u03b2 +\n                    \u03b2*c\u2082*exp\u03b1*cos\u03b2\n                    )\n            end\n        return func, deriv\n    end\nend\n\n\"\"\"ivp(a,b,c,y\u2080,t\u2080) solves second order linear homogenous initial value problem\n\nArguments:\n   - a,b,c::Real the coeffients of the ODE\n   - y\u2080 the initial value as a vector\n   - t\u2080 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\u2080, t\u2080)\n    x\u2080 = y\u2080[1]\n    v\u2080 = y\u2080[2]\n    general, deriv = solution(a,b,c)\n    \n    function f!(params, fvec)\n        fvec[1] = x\u2080 - general(t\u2080, params...)\n        fvec[2] = v\u2080 - deriv(t\u2080, 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)) \u2260 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    \ud835\udcd5 = 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        \ud835\udcd5[i] = 0.0\r\n    end\r\n    inv_\ud835\udcd5 = isnothing(method.inverse) ? irfft(\ud835\udcd5, length(s)) : method.inverse*\ud835\udcd5\r\n    residual = inv_\ud835\udcd5\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 `\u2264 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    \ud835\udcd5 = isnothing(method.forward) ? rfft(s .- m) : method.forward*(s .- m)\r\n    fs = rfftfreq(length(s))\r\n    i = findlast(f -> f \u2264 method.f, fs)\r\n    \ud835\udcd5[1:i+1] .= 0.0\r\n    inv_\ud835\udcd5 = isnothing(method.inverse) ? irfft(\ud835\udcd5, length(s)) : method.inverse*\ud835\udcd5\r\n    residual = inv_\ud835\udcd5\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(\u03bd1,\u03bd2)\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    \u03bd1::Float64\n    \u03bd2::Float64\n\n    function FDist(\u03bd1::Real, \u03bd2::Real)\n        @check_args(FDist, \u03bd1 > zero(\u03bd1) && \u03bd2 > zero(\u03bd2))\n        new(\u03bd1, \u03bd2)\n    end\nend\n\n@distr_support FDist 0.0 Inf\n\n\n#### Parameters\n\nparams(d::FDist) = (d.\u03bd1, d.\u03bd2)\n\n\n#### Statistics\n\nmean(d::FDist) = (\u03bd2 = d.\u03bd2; \u03bd2 > 2.0 ? \u03bd2 / (\u03bd2 - 2.0) : NaN)\n\nmode(d::FDist) = ((\u03bd1, \u03bd2) = params(d); \u03bd1 > 2.0 ? ((\u03bd1 - 2.0)/\u03bd1) * (\u03bd2 / (\u03bd2 + 2.0)) : 0.0)\n\nfunction var(d::FDist)\n    (\u03bd1, \u03bd2) = params(d)\n    \u03bd2 > 4.0 ? 2.0 * \u03bd2^2 * (\u03bd1 + \u03bd2 - 2.0) / (\u03bd1 * (\u03bd2 - 2.0)^2 * (\u03bd2 - 4.0)) : NaN\nend\n\nfunction skewness(d::FDist)\n    (\u03bd1, \u03bd2) = params(d)\n    if \u03bd2 > 6.0\n        return (2.0 * \u03bd1 + \u03bd2 - 2.0) * sqrt(8.0 * (\u03bd2 - 4.0)) / ((\u03bd2 - 6.0) * sqrt(\u03bd1 * (\u03bd1 + \u03bd2 - 2.0)))\n    else\n        return NaN\n    end\nend\n\nfunction kurtosis(d::FDist)\n    (\u03bd1, \u03bd2) = params(d)\n    if \u03bd2 > 8.0\n        a = \u03bd1 * (5. * \u03bd2 - 22.) * (\u03bd1 + \u03bd2 - 2.) + (\u03bd2 - 4.) * (\u03bd2 - 2.)^2\n        b = \u03bd1 * (\u03bd2 - 6.) * (\u03bd2 - 8.) * (\u03bd2 - 2.)\n        return 12. * a / b\n    else\n        return NaN\n    end\nend\n\nfunction entropy(d::FDist)\n    (\u03bd1, \u03bd2) = params(d)\n    h\u03bd1 = \u03bd1 * 0.5\n    h\u03bd2 = \u03bd2 * 0.5\n    hs = (\u03bd1 + \u03bd2) * 0.5\n    return log(\u03bd2 / \u03bd1) + lgamma(h\u03bd1) + lgamma(h\u03bd2) - lgamma(hs) +\n        (1.0 - h\u03bd1) * digamma(h\u03bd1) + (-1.0 - h\u03bd2) * digamma(h\u03bd2) +\n        hs * digamma(hs)\nend\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns FDist fdist \u03bd1 \u03bd2\n\nrand(d::FDist) = StatsFuns.Rmath.fdistrand(d.\u03bd1, d.\u03bd2)\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\u03c1old = one(T)\n\t\u03b1 =one(T)\n\t\u03c9old = one(T)\n\tv=zeros(T,n)\n\tp=zeros(T,n)\n\tTR = typeof(real(\u03b1))\n\tfor i=1:n\n\t\t\u03c1new = dot(rhat,r)\n\t\t\u03b2 = (\u03c1new/\u03c1old)*(\u03b1/\u03c9old)\n\t\tp = r + \u03b2*(p-\u03c9old*v)\n\t\tv = A*p\n\t\t\u03b1 = \u03c1new/dot(rhat,v)\n\t\ts = r - \u03b1*v\n\t\tt = A*s\n\t\t\u03c9new = dot(t,s)/dot(t,t)\n\t\tupd = \u03b1*p + \u03c9new*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 - \u03c9new*t\n\t\t\u03c1old = \u03c1new\n\t\t\u03c9old = \u03c9new\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\u03c1old = one(T)\n\t\u03b1 =one(T)\n\t\u03c9old = one(T)\n\tv=zeros(T,n)\n\tp=zeros(T,n)\n\tTR = typeof(real(\u03b1))\n\tfor i=1:n\n\t\t\u03c1new = dot(rhat,r)\n\t\t\u03b2 = (\u03c1new/\u03c1old)*(\u03b1/\u03c9old)\n\t\tp = r + \u03b2*(p-\u03c9old*v)\n\t\ty = P\\p\n\t\tv = A*y\n\t\t\u03b1 = \u03c1new/dot(rhat,v)\n\t\ts = r - \u03b1*v\n\t\tz = P\\s\n\t\tt = A*z\n\t\tzt = P\\t\n\t\t\u03c9new = dot(zt,z)/dot(zt,zt)\n\t\tupd = \u03b1*y + \u03c9new*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 - \u03c9new*t\n\t\t\u03c1old = \u03c1new\n\t\t\u03c9old = \u03c9new\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, \u03b4 = defaulttol(a))\n     U, S, V = svd(a)\n     Sinv = inv.(hypot.(S, \u03b4))\n     return  V * Diagonal(Sinv) * U'\n end\n\n function posreginv(a::AbstractMatrix, \u03b4 = defaulttol(a))\n     # assumes a is positive definite (or close to)\n     D, V = eigen(Hermitian(a))\n     Dinv = inv.(hypot.(D, \u03b4))\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": "c\r\nc gcvspl.for, 1986 - 05 - 12\r\nc (c) copyright 1985, 1986: h.j. woltring\r\nc this software is copyrighted, and may be  copied  for  exercise,\r\nc study  and  use  without authorization from the copyright owner(s), in\r\nc compliance with paragraph 16b of  the  dutch  copyright  act  of  1912\r\nc (\"auteurswet  1912\").  within the constraints of this legislation, all\r\nc forms of academic and research - oriented excercise, study, and use  are\r\nc allowed,  including  any  necessary modifications.  copying and use as\r\nc object for commercial exploitation are not allowed without  permission\r\nc of  the  copyright owners, including those upon whose work the package\r\nc is based.\r\nc\r\nc code initially published in:\r\nc woltring, 1986, a fortran package for generalized, cross - validatory spline smoothing and differentiation. adv. eng. softw. 8:104 - 113.0 \r\nc ####\r\nc note of charles le losq: \r\nc code available on www.netlib.org, other versions are available on https: / / isbweb.org / software / sigproc.html\r\nc this is a fortran 77 version downloaded on https: / / isbweb.org / software / sigproc.html\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc subroutine gcvspl (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       natural b - spline data smoothing subroutine, using the generali - \r\nc       zed cross - validation and mean - squared prediction error criteria\r\nc       of cravenwahba (1979). alternatively, the amount of smoothing\r\nc       can be given explicitly, or it can be based on the effective\r\nc       number of degrees of freedom in the smoothing process as defined\r\nc       by wahba (1980). the model assumes uncorrelated, additive noise\r\nc       and essentially smooth, underlying functions. the noise may be\r\nc       non - stationary, and the independent co - ordinates may be spaced\r\nc       non - equidistantly. multiple datasets, with common independent\r\nc       variables and weight factors are accomodated.\r\nc\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       gcvspl ( x, y, ny, wx, wy, m, n, k, md, val, c, nc, wk, ier\r\nc )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       x(n)    ( i )   independent variables: strictly increasing knot\r\nc                       sequence, with x(i - 1) < x(i), i = 2, ..., n.\r\nc       y(ny, k) ( i )   input data to be smoothed (or interpolated).\r\nc       ny      ( i )   first dimension of array y(ny, k), with ny >= n.\r\nc       wx(n)   ( i )   weight factor array; wx(i) corresponds with\r\nc                       the relative inverse variance of point y(i, * ).\r\nc                       if no relative weighting information is\r\nc                       available, the wx(i) should be set to one.\r\nc                       all wx(i) > zero, i = 1, ..., n.\r\nc       wy(k)   ( i )   weight factor array; wy(j) corresponds with\r\nc                       the relative inverse variance of point y( * , j).\r\nc                       if no relative weighting information is\r\nc                       available, the wy(j) should be set to one.\r\nc                       all wy(j) > zero, j = 1, ..., k.\r\nc                       nb: the effective weight for point y(i, j) is\r\nc                       equal to wx(i) * wy(j).\r\nc       m       ( i )   half order of the required b - splines (spline\r\nc                       degree 2 * m - 1), with m > 0.0 the values m =\r\nc                       1, 2, 3, 4 correspond to linear, cubic, quintic,\r\nc                       and heptic splines, respectively.\r\nc       n       ( i )   number of observations per dataset, with n >= 2 *\r\ncm.\r\nc       k       ( i )   number of datasets, with k >= 1.0\r\nc       md      ( i )   optimization mode switch:\r\nc                       |md| = 1: prior given value for p in val\r\nc                                 (val >= zero). this is the fastest\r\nc                                 use of gcvspl, since no iteration\r\nc                                 is performed in p.\r\nc                       |md| = 2: generalized cross validation.\r\nc                       |md| = 3: true predicted mean - squared error,\r\nc                                 with prior given variance in val.\r\nc                       |md| = 4: prior given number of degrees of\r\nc                                 freedom in val (zero <= val <= n - m).\r\nc                        md  < 0: it is assumed that the contents of\r\nc                                 x, w, m, n, and wk have not been\r\nc                                 modified since the previous invoca - \r\nc                                 tion of gcvspl. if md < - 1, wk(4)\r\nc                                 is used as an initial estimate for\r\nc                                 the smoothing parameter p.  at the\r\nc                                 first to gcvspl, md must be > 0.0\r\nc                       other values for |md|, and inappropriate values\r\nc                       for val will result in an error condition, or\r\nc                       cause a default value for val to be selected.\r\nc                       after return from md != 1, the same number of\r\nc                       degrees of freedom can be obtained, for identica\r\ncl\r\nc                       weight factors and knot positions, by selecting\r\nc                       |md| = 1, and by copying the value of p from wk(4)\r\nc                       into val. in this way, no iterative optimization\r\nc                       is required when processing other data in y.\r\nc       val     ( i )   mode value, as described above under md.\r\nc       c(nc, k) ( o )   spline coefficients, to be used in conjunction\r\nc                       with function splder. nb: the dimensions of c\r\nc                       in gcvspl and in splder are different# In SPLDER\r\nc,\r\nc                       only a single column of c(n, k) is needed, and th\r\nce\r\nc                       proper column c(1, j), with j = 1.0..k should be use\r\ncd\r\nc                       when calling splder.\r\nc       nc       ( i )  first dimension of array c(nc, k), nc >= n.\r\nc       wk(iwk) (i / w / o) work vector, with length iwk >= 6 * (n * m + 1) + n.\r\nc                       on normal exit, the first 6 values of wk are\r\nc                       assigned as follows:\r\nc\r\nc                       wk(1) = generalized cross validation value\r\nc                       wk(2) = mean squared residual.\r\nc                       wk(3) = estimate of the number of degrees of\r\nc                               freedom of the residual sum of squares\r\nc                               per dataset, with 0 < wk(3) < n - m.\r\nc                       wk(4) = smoothing parameter p, multiplicative\r\nc                               with the splines\" derivative constraint.\r\nc                       wk(5) = estimate of the true mean squared error\r\nc                               (dif ferent formula for |md| = 3).\r end\nc                       wk(6) = gauss - markov error variance.\r\nc\r\nc                       if wk(4) -  - >  0 , wk(3) -  - >  0 , and an inter - \r\nc                       polating spline is fitted to the data (p -  - > 0).\r\nc                       a very small value > 0 is used for p, in order\r\nc                       to avoid division by zero in the gcv function.\r\nc\r\nc                       if wk(4) -  - > inf, wk(3) -  - > n - m, and a least - \r\nc                       squares polynomial of order m (degree m - 1) is\r\nc                       fitted to the data (p -  - > inf). for numerical\r\nc                       reasons, a very high value is used for p.\r\nc\r\nc                       upon return, the contents of wk can be used for\r\nc                       covariance propagation in terms of the matrices\r\nc                       b and we: see the source listings. the variance\r\nc                       estimate for dataset j follows as wk(6) / wy(j).\r\nc\r\nc       ier     ( o )   error parameter:\r\nc\r\nc                       ier = 0:        normal exit\r\nc                       ier = 1:        m <= 0 || n < 2 * m\r\nc                       ier = 2:        knot sequence is not strictly\r\nc                                       increasing, or some weight\r\nc                                       factor is not positive.\r\nc                       ier = 3:        wrong mode  parameter or value.\r\nc\r\nc remarks:\r\nc ^^^ *\r\nc\r\nc       (1) gcvspl calculates a natural spline of order 2 * m (degree\r\nc       2 * m - 1) which smoothes or interpolates a given set of data\r\nc       points, using statistical considerations to determine the\r\nc       amount of smoothing required (cravenwahba, 1979). if the\r\nc       error variance is a priori known, it should be supplied to\r\nc       the routine in val, for |md| = 3.0 the degree of smoothing is\r\nc        determined to minimize an unbiased estimate of the true\r\nc       mean squared error. on the other hand, if the error variance\r\nc       is not known, one may select |md| = 2.0 the routine  deter - \r\nc       mines the degree of smoothing to minimize the generalized\r\nc       cross validation function. this is asymptotically the same\r\nc       as minimizing the true predicted mean squared error (cravenc       wahba, 1979). if the estimates from |md| = 2 or 3 do not appear\r end\nc       suitable to the user (as apparent from the smoothness of the\r\nc       m - th derivative or from the effective number of degrees of\r\nc       freedom returned in wk(3) ), the user may select an other\r\nc       value for the noise variance if |md| = 3, or a reasonably large\r end\nc       number of degrees of freedom if |md| = 4.0 if |md| = 1, the proce - \r end\nc       dure is non - iterative, and returns a spline for the given\r\nc       value of the smoothing parameter p as entered in val.\r\nc\r\nc       (2) the number of arithmetic operations and the amount of\r\nc       storage required are both proportional to n, so very large\r\nc       datasets may be accomodated. the data points do not have\r\nc       to be equidistant in the independant variable x or uniformly\r\nc       weighted in the dependant variable y. however, the data\r\nc       points in x must be strictly increasing. multiple dataset\r\nc       processing (k > 1) is numerically more efficient dan\r\nc       separate processing of the individual datasets (k == 1).\r\nc\r\nc       (3) if |md| = 3 (a priori known noise variance), any value of\r end\nc       n >= 2 * m is acceptable. however, it is advisable for n - 2 * m\r\nc       be rather large (at least 20) if |md| = 2 (gcv).\r end\nc\r\nc       (4) for |md| > 1, gcvspl tries to iteratively minimize the\r\nc       selected criterion function. this minimum is unique for |md|\r\nc       = 4, but not necessarily for |md| = 2 or 3.0 consequently,\r\nc       local optima rather that the global optimum might be found,\r\nc       and some actual findings suggest that local optima might\r\nc       yield more meaningful results than the global optimum if n\r\nc       is small. therefore, the user has some control over the\r\nc       search procedure. if md > 1, the iterative search starts\r\nc       from a value which yields a number of degrees of freedom\r\nc       which is approximately equal to n / 2, until the first (local)\r\nc       minimum is found via a golden section search procedure\r\nc       (utreras, 1980). if md < - 1, the value for p contained in\r\nc       wk(4) is used instead. thus, if md = 2 or 3 yield too noisy\r end\nc       an estimate, the user might try |md| = 1 or 4, for suitably\r\nc       selected values for p or for the number of degrees of\r\nc       freedom, and  run gcvspl with md = - 2 or - 3.0 the con - \r\nc       tents of n, m, k, x, wx, wy, and wk are assumed unchanged\r\nc       since the last to gcvspl if md < 0.0\r\nc\r\nc       (5) gcvspl calculates the spline coefficient array c(n, k);\r\nc       this array can be used to calculate the spline function\r\nc       value and any of its derivatives up to the degree 2 * m - 1\r\nc       at any argument t within the knot range, using subrou - \r\nc       tines splder and search, and the knot array x(n). since\r\nc       the splines are constrained at their mth derivative, only\r\nc       the lower spline derivatives will tend to be reliable\r\nc       estimates of the underlying, true signal derivatives.\r\nc\r\nc       (6) gcvspl combines elements of subroutine crvo5 by utre - \r\nc       ras (1980), subroutine smooth by lyche et al. (1983), and\r\nc       subroutine cubgcv by hutchinson (1985). the trace of the\r\nc       influence matrix is assessed in a similar way as described\r\nc       by hutchinsonde hoog (1985). the major difference is\r\nc       that the present approach utilizes non - symmetrical b - spline\r\nc       design matrices as described by lyche et al. (1983); there - \r\nc       fore, the original algorithm by erismantinney (1975) has\r\nc       been used, rather than the symmetrical version adopted by\r\nc       hutchinsonde hoog.\r\nc\r\nc references:\r\nc ^^^^^\r\nc\r\nc       p. craveng. wahba (1979), smoothing noisy data with\r\nc       spline functions. numerische mathematik 31, 377 - 403.0\r\nc\r\nc       a.m. erismanw.f. tinney (1975), on computing certain\r\nc       elements of the inverse of a sparse matrix. communications\r\nc       of the acm 18(3), 177 - 179.0\r\nc\r\nc       m.f. hutchinsonf.r. de hoog (1985), smoothing noisy data\r\nc       with spline functions. numerische mathematik 47(1), 99 - 106.0\r\nc\r\nc       m.f. hutchinson (1985), subroutine cubgcv. csiro division of\r\nc       mathematics and statistics, p.o. box 1965, canberra, act 2601,\r\nc       australia.\r\nc\r\nc       t. lyche, l.l. schumaker, k. sepehrnoori (1983), fortran\r\nc       subroutines for computing smoothing and interpolating natural\r\nc       splines. advances in engineering software 5(1), 2 - 5.0\r\nc\r\nc       f. utreras (1980), un paquete de programas para ajustar curvas\r\nc       mediante funciones spline. informe tecnico ma - 80 - b - 209, depar - \r\nc       tamento de matematicas, faculdad de ciencias fisicas y matema - \r\nc       ticas, universidad de chile, santiago.\r\nc\r\nc       wahba, g. (1980). numerical and statistical methods for mildly,\r\nc       moderately and severely ill - posed problems with noisy data.\r\nc       technical report nr. 595 (february 1980). department of statis - \r\nc       tics, university of madison (wi), u.s.a.\r\nc\r\nc subprograms required:\r\nc ^^^^^^^^^^\r\nc\r\nc       basis, prep, splc, bandet, bansol, trinv\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc\r\n      subroutine gcvspl(x, y, ny, wx, wy, m, n, k, md, val, c, nc, wk, ier)\r\n      implicit double precision (o - z, a - h)\r\n      parameter (ratio = 2d0, tau = 1.618033983d0, ibwe = 7, zero = 0d0, half = 5d - 1, one = 1d0, tol = 1d - 6, eps = 1d - 15, epsinv = one / eps)\r\n      dimension x(n), y(ny, k), wx(n), wy(k), c(nc, k), wk(n + (6 * ((n * m) + 1)))\r\n      save el, nm1, m2\r\nc\r\nc^ *  parameter check and work array initialization\r\nc\r\nc^ *  check on mode parameter\r\n      data m2 / 0 /\r\n      data nm1 / 0 /\r\n      data el / 0d0 /\r\n      ier = 0\r\n      if (((((iabs(md) > 4) || (md == 0)) || ((iabs(md) == 1) && (val < zero))) || ((iabs(md) == 3) && (val < zero))) || ((iabs(md) == 4) && ((val < zero) || (val > (n - m))))) \r\ncwrong mode value                                 \r\n      ier = 3\r\n      return \r\nc^ *  check on m and n\r\n      end\n      if (md > 0) \r\n      m2 = 2 * m\r\n      nm1 = n - 1\r\n      else\r\n      if ((m2 != (2 * m)) || (nm1 != (n - 1))) \r\ncm or n modified since previous \r\n      ier = 3\r\n      return \r\n      end\n      end\n      if ((m <= 0) || (n < m2)) \r\ncm or n invalid                                   \r\n      ier = 1\r\n      return \r\nc^ *  check on knot sequence and weights\r\n      end\n      if (wx(1) <= zero) ier = 2\r end\n      for 10 i = 2: n\r\n      if ((wx(i) <= zero) || (x(i - 1) >= x(i))) ier = 2\r end\n      if (ier != 0) return \r\n   10 continue\r\n      for 15 j = 1: k\r\n      if (wy(j) <= zero) ier = 2\r end\n      if (ier != 0) return \r\nc\r\nc^ *  work array parameters (address information for covariance\r\nc^ *  propagation by means of the matrices stat, b, and we). nb:\r\nc^ *  bwe cannot be used since it is modified by function trinv.\r\nc\r\n   15 continue\r\n      nm2p1 = n * (m2 + 1)\r\nc     istat = 1            #Statistics array STAT(6)\r\nc     ibwe  = istat + 6      #Smoothing matrix BWE( - M:M  , N)\r\n      nm2m1 = n * (m2 - 1)\r\ncdesign matrix    b  (1 - m:m - 1, n)       \r\n      ib = ibwe + nm2p1\r\nc     iwk   = iwe   + nm2p1      #Total work array length N + 6 * (N * M + 1)\r\nc\r\nc^ *  compute the design matrices b and we, the ratio\r\nc^ *  of their l1 - norms, and check for iterative mode.\r\nc\r\ncdesign matrix    we ( - m:m  , n)       \r\n      iwe = ib + nm2m1\r\n      if (md > 0) \r\n      basis(m, n, x, wk(ib), r1, wk(ibwe))\r\n      prep(m, n, x, wx, wk(iwe), el)\r\ncl1 - norms ratio (saved upon return)          \r\n      el = el / r1\r\n      end\nc^ *     prior given value for p\r\n      if (iabs(md) != 1) #FIXME goto 20\r\n      r1 = val\r\nc\r\nc^ *  iterate to minimize the gcv function (|md| = 2),\r\nc^ *  the mse function (|md| = 3), or to obtain the prior\r\nc^ *  given number of degrees of freedom (|md| = 4).\r\nc\r\n      #FIXME goto 100\r\n   20 if (md < ( - 1)) \r\ncuser - determined starting value                \r\n      r1 = wk(4)\r\n      else\r\ncdefault (dof ~ 0.5)                        \r\n      r1 = one / el\r\n      end\n      r2 = r1 * ratio\r\n      gf2 = splc(m, n, k, y, ny, wx, wy, md, val, r2, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n   40 gf1 = splc(m, n, k, y, ny, wx, wy, md, val, r1, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n      if (gf1 > gf2) #FIXME goto 50\r\ncinterpolation         \r\n      if (wk(4) <= zero) #FIXME goto 100\r\n      r2 = r1\r\n      gf2 = gf1\r\n      r1 = r1 / ratio\r\n      #FIXME goto 40\r\n   50 r3 = r2 * ratio\r\n   60 gf3 = splc(m, n, k, y, ny, wx, wy, md, val, r3, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n      if (gf3 > gf2) #FIXME goto 70\r\ncleast - squares polynomial  \r\n      if (wk(4) >= epsinv) #FIXME goto 100\r\n      r2 = r3\r\n      gf2 = gf3\r\n      r3 = r3 * ratio\r\n      #FIXME goto 60\r\n   70 r2 = r3\r\n      gf2 = gf3\r\n      \u03b1 = (r2 - r1) / tau\r\n      r4 = r1 + \u03b1\r\n      r3 = r2 - \u03b1\r\n      gf3 = splc(m, n, k, y, ny, wx, wy, md, val, r3, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n      gf4 = splc(m, n, k, y, ny, wx, wy, md, val, r4, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n   80 if (gf3 <= gf4) \r\n      r2 = r4\r\n      gf2 = gf4\r\n      err = (r2 - r1) / (r1 + r2)\r\n      if ((((err * err) + one) == one) || (err <= tol)) #FIXME goto 90\r\n      r4 = r3\r\n      gf4 = gf3\r\n      \u03b1 = \u03b1 / tau\r\n      r3 = r2 - \u03b1\r\n      gf3 = splc(m, n, k, y, ny, wx, wy, md, val, r3, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n      else\r\n      r1 = r3\r\n      gf1 = gf3\r\n      err = (r2 - r1) / (r1 + r2)\r\n      if ((((err * err) + one) == one) || (err <= tol)) #FIXME goto 90\r\n      r3 = r4\r\n      gf3 = gf4\r\n      \u03b1 = \u03b1 / tau\r\n      r4 = r1 + \u03b1\r\n      gf4 = splc(m, n, k, y, ny, wx, wy, md, val, r4, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n      end\n      #FIXME goto 80\r\nc\r\nc^ *  calculate final spline coefficients\r\nc\r\n   90 r1 = half * (r1 + r2)\r\nc\r\nc^ *  ready\r\nc\r\n  100 gf1 = splc(m, n, k, y, ny, wx, wy, md, val, r1, eps, c, nc, wk, wk(ib), wk(iwe), el, wk(ibwe))\r\n      return \r\nc basis.for, 1985 - 06 - 03\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc subroutine basis (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       subroutine to assess a b - spline tableau, stored in vectorized\r\nc       form.\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       basis ( m, n, x, b, bl, q )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       m               ( i )   half order of the spline (degree 2 * m - 1),\r\nc                               m > 0.0\r\nc       n               ( i )   number of knots, n > = 2 * m.\r\nc       x(n)            ( i )   knot sequence, x(i - 1) < x(i), i = 2, n.\r\nc       b(1 - m:m - 1, n)    ( o )   output tableau. element b(j, i) of array\r\nc                               b corresponds with element b(i, i + j) of\r\nc                               the tableau matrix b.\r\nc       bl              ( o )   l1 - norm of b.\r\nc       q(1 - m:m)        ( w )   internal work array.\r\nc\r\nc remark:\r\nc ^^^\r\nc\r\nc       this subroutine is an adaptation of subroutine basis from the\r\nc       paper by lyche et al. (1983). no checking is performed on the\r\nc       validity of m and n. if the knot sequence is not strictly in - \r\nc       creasing, division by zero may occur.\r\nc\r\nc reference:\r\nc ^^^^ *\r\nc\r\nc       t. lyche, l.l. schumaker, k. sepehrnoori, fortran subroutines\r\nc       for computing smoothing and interpolating natural splines.\r\nc       advances in engineering software 5(1983)1, pp. 2 - 5.0\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      subroutine basis(m, n, x, b, bl, q)\r\n      implicit double precision (o - z, a - h)\r\n      parameter (zero = 0d0, one = 1d0)\r\nc\r\n      dimension x(n), b(1 - m:m - 1, n), q(1 - m:m)\r\nc^ *         linear spline\r\n      if (m == 1) \r\n      for 3 i = 1: n\r\n      b(0, i) = one\r\n    3 continue\r\n      bl = one\r\n      return \r\nc\r\nc^ *  general splines\r\nc\r\n      end\n      mm1 = m - 1\r\n      mp1 = m + 1\r\n      m2 = 2 * m\r\nc^ *     1st row\r\n      for 15 l = 1: n\r\n      for 5 j = - mm1: m\r\n      q(j) = zero\r\n    5 continue\r\n      q(mm1) = one\r\nc^ *     successive rows\r\n      if ((l != 1) && (l != n)) q(mm1) = one / (x(l + 1) - x(l - 1))\r end\n      arg = x(l)\r\n      for 13 i = 3: m2\r\n      ir = mp1 - i\r\n      v = q(ir)\r\nc^ *               left - hand b - splines\r\n      if (l < i) \r\n      for 6 j = l + 1: i\r\n      u = v\r\n      v = q(ir + 1)\r\n      q(ir) = u + ((x(j) - arg) * v)\r\n      ir = ir + 1\r\n    6 continue\r\n      end\n      j1 = max0((l - i) + 1, 1)\r\n      j2 = min0(l - 1, n - i)\r\nc^ *               ordinary b - splines\r\n      if (j1 <= j2) \r\n      if (i < m2) \r\n      for 8 j = j1: j2\r\n      y = x(i + j)\r\n      u = v\r\n      v = q(ir + 1)\r\n      q(ir) = u + (((v - u) * (y - arg)) / (y - x(j)))\r\n      ir = ir + 1\r\n    8 continue\r\n      else\r\n      for 10 j = j1: j2\r\n      u = v\r\n      v = q(ir + 1)\r\n      q(ir) = ((arg - x(j)) * u) + ((x(i + j) - arg) * v)\r\n      ir = ir + 1\r\n   10 continue\r\n      end\n      end\n      nmip1 = (n - i) + 1\r\nc^ *           right - hand b - splines\r\n      if (nmip1 < l) \r\n      for 12 j = nmip1: l - 1\r\n      u = v\r\n      v = q(ir + 1)\r\n      q(ir) = ((arg - x(j)) * u) + v\r\n      ir = ir + 1\r\n   12 continue\r\n      end\n   13 continue\r\n      for 14 j = - mm1: mm1\r\n      b(j, l) = q(j)\r\n   14 continue\r\nc\r\nc^ *  zero unused parts of b\r\nc\r\n   15 continue\r\n      for 17 i = 1: mm1\r\n      for 16 k = i: mm1\r\n      b( - k, i) = zero\r\n      b(k, (n + 1) - i) = zero\r\n   16 continue\r\nc\r\nc^ *  assess l1 - norm of b\r\nc\r\n   17 continue\r\n      bl = 0d0\r\n      for 19 i = 1: n\r\n      for 18 k = - mm1: mm1\r\n      bl = bl + abs(b(k, i))\r\n   18 continue\r\n   19 continue\r\nc\r\nc^ *  ready\r\nc\r\n      bl = bl / n\r\n      return \r\nc prep.for, 1985 - 07 - 04\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc subroutine prep (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       to compute the matrix we of weighted divided difference coeffi - \r\nc       cients needed to set up a linear system of equations for sol - \r\nc       ving b - spline smoothing problems, and its l1 - norm el. the matrix\r\nc       we is stored in vectorized form.\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       prep ( m, n, x, w, we, el )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       m               ( i )   half order of the b - spline (degree\r\nc                               2 * m - 1), with m > 0.0\r\nc       n               ( i )   number of knots, with n > = 2 * m.\r\nc       x(n)            ( i )   strictly increasing knot array, with\r\nc                               x(i - 1) < x(i), i = 2, n.\r\nc       w(n)            ( i )   weight matrix (diagonal), with\r\nc                               w(i) > 0.0, i = 1, n.\r\nc       we( - m:m, n)      ( o )   array containing the weighted divided\r\nc                               difference terms in vectorized format.\r\nc                               element we(j, i) of array e corresponds\r\nc                               with element e(i, i + j) of the matrix\r\nc                               w^ - 1 * e.\r\nc       el              ( o )   l1 - norm of we.\r\nc\r\nc remark:\r\nc ^^^\r\nc\r\nc       this subroutine is an adaptation of subroutine prep from the pap\r\ncer\r\nc       by lyche et al. (1983). no checking is performed on the validity\r\nc       of m and n. division by zero may occur if the knot sequence is\r\nc       not strictly increasing.\r\nc\r\nc reference:\r\nc ^^^^ *\r\nc\r\nc       t. lyche, l.l. schumaker, k. sepehrnoori, fortran subroutines\r\nc       for computing smoothing and interpolating natural splines.\r\nc       advances in engineering software 5(1983)1, pp. 2 - 5.0\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      subroutine prep(m, n, x, w, we, el)\r\n      implicit double precision (o - z, a - h)\r\n      parameter (zero = 0d0, one = 1d0)\r\nc\r\nc^ *  calculate the factor f1\r\nc\r\ncwe( - m:m, n)              \r\n      dimension x(n), w(n), we(((2 * m) + 1) * n)\r\n      m2 = 2 * m\r\n      mp1 = m + 1\r\n      m2m1 = m2 - 1\r\n      m2p1 = m2 + 1\r\n      nm = n - m\r\n      f1 = - one\r\n      if (m != 1) \r\n      for 5 i = 2: m\r\n      f1 = - (f1 * i)\r\n    5 continue\r\n      for 6 i = mp1: m2m1\r\n      f1 = f1 * i\r\n    6 continue\r\nc\r\nc^ *  columnwise evaluation of the unweighted design matrix e\r\nc\r\n      end\n      i1 = 1\r\n      i2 = m\r\n      jm = mp1\r\n      for 17 j = 1: n\r\n      inc = m2p1\r\n      if (j > nm) \r\n      f1 = - f1\r\n      f = f1\r\n      else\r\n      if (j < mp1) \r\n      inc = 1\r\n      f = f1\r\n      else\r\n      f = f1 * (x(j + m) - x(j - m))\r\n      end\n      end\n      if (j > mp1) i1 = i1 + 1\r end\n      if (i2 < n) i2 = i2 + 1\r end\nc^ *     loop for divided difference coefficients\r\n      jj = jm\r\n      ff = f\r\n      y = x(i1)\r\n      i1p1 = i1 + 1\r\n      for 11 i = i1p1: i2\r\n      ff = ff / (y - x(i))\r\n   11 continue\r\n      we(jj) = ff\r\n      jj = jj + m2\r\n      i2m1 = i2 - 1\r\n      if (i1p1 <= i2m1) \r\n      for 14 l = i1p1: i2m1\r\n      ff = f\r\n      y = x(l)\r\n      for 12 i = i1: l - 1\r\n      ff = ff / (y - x(i))\r\n   12 continue\r\n      for 13 i = l + 1: i2\r\n      ff = ff / (y - x(i))\r\n   13 continue\r\n      we(jj) = ff\r\n      jj = jj + m2\r\n   14 continue\r\n      end\n      ff = f\r\n      y = x(i2)\r\n      for 16 i = i1: i2m1\r\n      ff = ff / (y - x(i))\r\n   16 continue\r\n      we(jj) = ff\r\n      jj = jj + m2\r\n      jm = jm + inc\r\nc\r\nc^ *  zero the upper left and lower right corners of e\r\nc\r\n   17 continue\r\n      kl = 1\r\n      n2m = (m2p1 * n) + 1\r\n      for 19 i = 1: m\r\n      ku = (kl + m) - i\r\n      for 18 k = kl: ku\r\n      we(k) = zero\r\n      we(n2m - k) = zero\r\n   18 continue\r\n      kl = kl + m2p1\r\nc\r\nc^ *  weighted matrix we = w^ - 1 * e and its l1 - norm\r\nc\r\n   19 continue\r\n   20 jj = 0\r\n      el = 0d0\r\n      for 22 i = 1: n\r\n      wi = w(i)\r\n      for 21 j = 1: m2p1\r\n      jj = jj + 1\r\n      we(jj) = we(jj) / wi\r\n      el = el + abs(we(jj))\r\n   21 continue\r\n   22 continue\r\nc\r\nc^ *  ready\r\nc\r\n      el = el / n\r\n      return \r\nc splc.for, 1985 - 12 - 12\r\nc\r\nc author: h.j. woltring\r\nc\r\nc organizations: university of nijmegen, and\r\nc                philips medical systems, eindhoven\r\nc                (the netherlands)\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc function splc (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       to assess the coefficients of a b - spline and various statistical\r\nc       parameters, for a given value of the regularization parameter p.\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       fv = splc ( m, n, k, y, ny, wx, wy, mode, val, p, eps, c, nc,\r\nc       1           stat, b, we, el, bwe)\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       splc            ( o )   gcv function value if |mode| == 2,\r\nc                               mse value if |mode| == 3, and absolute\r\nc                               difference with the prior given number o\r\ncf\r\nc                               degrees of freedom if |mode| == 4.0\r\nc       m               ( i )   half order of the b - spline (degree 2 * m - 1\r\nc),\r\nc                               with m > 0.0\r\nc       n               ( i )   number of observations, with n > = 2 * m.\r\nc       k               ( i )   number of datasets, with k > = 1.0\r\nc       y(ny, k)         ( i )   observed measurements.\r\nc       ny              ( i )   first dimension of y(ny, k), with ny >= n\r\nc.\r\nc       wx(n)           ( i )   weight factors, corresponding to the\r\nc                               relative inverse variance of each measur\r\nce - \r\nc                               ment, with wx(i) > 0.0.0\r\nc       wy(k)           ( i )   weight factors, corresponding to the\r\nc                               relative inverse variance of each datase\r\nct,\r\nc                               with wy(j) > 0.0.0\r\nc       mode            ( i )   mode switch, as described in gcvspl.\r\nc       val             ( i )   prior variance if |mode| == 3, and\r\nc                               prior number of degrees of freedom if\r\nc                               |mode| == 4.0 for other values of mode,\r\nc                               val is not used.\r\nc       p               ( i )   smoothing parameter, with p > = 0.0.0 if\r\nc                               p == 0.0, an interpolating spline is\r\nc                               calculated.\r\nc       eps             ( i )   relative rounding tolerance * 10.0.0 eps is\r\nc                               the smallest positive number such that\r\nc                               eps / 10.0 + 1.0 != 1.0.0\r\nc       c(nc, k)         ( o )   calculated spline coefficient arrays. nb\r\nc:\r\nc                               the dimensions of in gcvspl and in splde\r\ncr\r\nc                               are different# In SPLDER, only a single\r\nc                               column of c(n, k) is needed, and the prop\r\ncer\r\nc                               column c(1, j), with j = 1.0..k, should be u\r\ncsed\r\nc                               when calling splder.\r\nc       nc              ( i )   first dimension of c(nc, k), with nc >= n\r\nc.\r\nc       stat(6)         ( o )   statistics array. see the description in\r\nc                               subroutine gcvspl.\r\nc       b (1 - m:m - 1, n)   ( i )   b - spline tableau as evaluated by subrout\r\ncine\r\nc                               basis.\r\nc       we( - m:m  , n)   ( i )   weighted b - spline tableau (w^ - 1 * e) as\r\nc                               evaluated by subroutine prep.\r\nc       el              ( i )   l1 - norm of the matrix we as evaluated by\r\nc                               subroutine prep.\r\nc       bwe( - m:m, n)     ( o )   central 2 * m + 1 bands of the inverted\r\nc                               matrix ( b  +  p * w^ - 1 * e )^ - 1\r\nc\r\nc remarks:\r\nc ^^^ *\r\nc\r\nc       this subroutine combines elements of subroutine splc0 from the\r\nc       paper by lyche et al. (1983), and of subroutine spfit1 by\r\nc       hutchinson (1985).\r\nc\r\nc references:\r\nc ^^^^^\r\nc\r\nc       m.f. hutchinson (1985), subroutine cubgcv. csiro division of\r\nc       mathematics and statistics, p.o. box 1965, canberra, act 2601,\r\nc       australia.\r\nc\r\nc       t. lyche, l.l. schumaker, k. sepehrnoori, fortran subroutines\r\nc       for computing smoothing and interpolating natural splines.\r\nc       advances in engineering software 5(1983)1, pp. 2 - 5.0\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      function splc(m, n, k, y, ny, wx, wy, mode, val, p, eps, c, nc, stat, b, we, el, bwe)\r\n      implicit double precision (o - z, a - h)\r\n      parameter (zero = 0d0, one = 1d0, two = 2d0)\r\nc\r\nc^ *  check on p - value\r\nc\r\n      dimension y(ny, k), wx(n), wy(k), c(nc, k), stat(6), b(1 - m:m - 1, n), we( - m:m, n), bwe( - m:m, n)\r\n      dp = p\r\n      stat(4) = p\r\nc^ *  pseudo - interpolation if p is too small\r\n      pel = p * el\r\n      if (pel < eps) \r\n      dp = eps / el\r\n      stat(4) = zero\r\nc^ *  pseudo least - squares polynomial if p is too large\r\n      end\n      if ((pel * eps) > one) \r\n      dp = one / (el * eps)\r\n      stat(4) = dp\r\nc\r\nc^ *  calculate  bwe  =  b  +  p * w^ - 1 * e\r\nc\r\n      end\n      for 40 i = 1: n\r\n      km = - min0(m, i - 1)\r\n      kp = min0(m, n - i)\r\n      for 30 l = km: kp\r\n      if (iabs(l) == m) \r\n      bwe(l, i) = dp * we(l, i)\r\n      else\r\n      bwe(l, i) = b(l, i) + (dp * we(l, i))\r\n      end\n   30 continue\r\nc\r\nc^ *  solve bwe * c = y, and assess trace [ b * bwe^ - 1 ]\r\nc\r\n   40 continue\r\n      bandet(bwe, m, n)\r\n      bansol(bwe, y, ny, c, nc, m, n, k)\r\nctrace * p = res. d.o.\r\n      stat(3) = trinv(we, bwe, m, n) * dp\r\nc\r\nc^ *  compute mean - squared weighted residual\r\nc\r\n      trn = stat(3) / n\r\n      esn = zero\r\n      for 70 j = 1: k\r\n      for 60 i = 1: n\r\n      dt = - y(i, j)\r\n      km = - min0(m - 1, i - 1)\r\n      kp = min0(m - 1, n - i)\r\n      for 50 l = km: kp\r\n      dt = dt + (b(l, i) * c(i + l, j))\r\n   50 continue\r\n      esn = esn + (((dt * dt) * wx(i)) * wy(j))\r\n   60 continue\r\n   70 continue\r\nc\r\nc^ *  calculate statistics and function value\r\nc\r\n      esn = esn / (n * k)\r\ncestimated variance               \r\n      stat(6) = esn / trn\r\ncgcv function value               \r\n      stat(1) = stat(6) / trn\r\nc     stat(3) = trace [p * b * bwe^ - 1] #Estimated residuals\" d.o.f.\r\nc     stat(4) = p                     #Normalized smoothing factor\r\ncmean squared residual            \r\n      stat(2) = esn\r\nc^ *     unknown variance: gcv\r\n      if (iabs(mode) != 3) \r\n      stat(5) = stat(6) - esn\r\n      if (iabs(mode) == 1) splc = zero\r end\n      if (iabs(mode) == 2) splc = stat(1)\r end\n      if (iabs(mode) == 4) splc = dabs(stat(3) - val)\r end\nc^ *     known variance: estimated mean squared error\r\n      else\r\n      stat(5) = esn - (val * ((two * trn) - one))\r\n      splc = stat(5)\r\nc\r\n      end\n      return \r\nc bandet.for, 1985 - 06 - 03\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc subroutine bandet (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       this subroutine computes the lu decomposition of an n * n matrix\r\nc       e. it is assumed that e has m bands above and m bands below the\r\nc       diagonal. the decomposition is returned in e. it is assumed that\r\nc       e can be decomposed without pivoting. the matrix e is stored in\r\nc       vectorized form in the array e( - m:m, n), where element e(j, i) of\r\nc       the array e corresponds with element e(i, i + j) of the matrix e.\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       bandet ( e, m, n )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       e( - m:m, n)       (i / o)   matrix to be decomposed.\r\nc       m, n            ( i )   matrix dimensioning parameters,\r\nc                               m > = 0, n > = 2 * m.\r\nc\r\nc remark:\r\nc ^^^\r\nc\r\nc       no checking on the validity of the input data is performed.\r\nc       if (m <= 0), no action is taken.\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      subroutine bandet(e, m, n)\r\n      implicit double precision (o - z, a - h)\r\nc\r\n      dimension e( - m:m, n)\r\n      if (m <= 0) return \r\n      for 40 i = 1: n\r\n      di = e(0, i)\r\n      mi = min0(m, i - 1)\r\n      if (mi >= 1) \r\n      for 10 k = 1: mi\r\n      di = di - (e( - k, i) * e(k, i - k))\r\n   10 continue\r\n      e(0, i) = di\r\n      end\n      lm = min0(m, n - i)\r\n      if (lm >= 1) \r\n      for 30 l = 1: lm\r\n      dl = e( - l, i + l)\r\n      km = min0(m - l, i - 1)\r\n      if (km >= 1) \r\n      du = e(l, i)\r\n      for 20 k = 1: km\r\n      du = du - (e( - k, i) * e(l + k, i - k))\r\n      dl = dl - (e(( - l) - k, l + i) * e(k, i - k))\r\n   20 continue\r\n      e(l, i) = du\r\n      end\n      e( - l, i + l) = dl / di\r\n   30 continue\r\n      end\nc\r\nc^ *  ready\r\nc\r\n   40 continue\r\n      return \r\nc bansol.for, 1985 - 12 - 12\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc subroutine bansol (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       this subroutine solves systems of linear equations given an lu\r\nc       decomposition of the design matrix. such a decomposition is pro - \r\nc       vided by subroutine bandet, in vectorized form. it is assumed\r\nc       that the design matrix is not singular.\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       bansol ( e, y, ny, c, nc, m, n, k )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       e( - m:m, n)       ( i )   input design matrix, in lu - decomposed,\r\nc                               vectorized form. element e(j, i) of the\r\nc                               array e corresponds with element\r\nc                               e(i, i + j) of the n * n design matrix e.\r\nc       y(ny, k)         ( i )   right hand side vectors.\r\nc       c(nc, k)         ( o )   solution vectors.\r\nc       ny, nc, m, n, k ( i )   dimensioning parameters, with m > = 0,\r\nc                               n > 2 * m, and k > = 1.0\r\nc\r\nc remark:\r\nc ^^^\r\nc\r\nc       this subroutine is an adaptation of subroutine bansol from the\r\nc       paper by lyche et al. (1983). no checking is performed on the\r\nc       validity of the input parameters and data. division by zero may\r\nc       occur if the system is singular.\r\nc\r\nc reference:\r\nc ^^^^ *\r\nc\r\nc       t. lyche, l.l. schumaker, k. sepehrnoori, fortran subroutines\r\nc       for computing smoothing and interpolating natural splines.\r\nc       advances in engineering software 5(1983)1, pp. 2 - 5.0\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      subroutine bansol(e, y, ny, c, nc, m, n, k)\r\n      implicit double precision (o - z, a - h)\r\nc\r\nc^ *  check on special cases: m = 0, m = 1, m>1\r\nc\r\n      dimension e( - m:m, n), y(ny, k), c(nc, k)\r\n      nm1 = n - 1\r\nc\r\nc^ *  m = 0: diagonal system\r\nc\r\n      if (m - 1) 10, 40, 80\r\n   10 for 30 i = 1: n\r\n      for 20 j = 1: k\r\n      c(i, j) = y(i, j) / e(0, i)\r\n   20 continue\r\n   30 continue\r\nc\r\nc^ *  m = 1: tridiagonal system\r\nc\r\n      return \r\n   40 for 70 j = 1: k\r\n      c(1, j) = y(1, j)\r\ncforward sweep                          \r\n      for 50 i = 2: n\r\n      c(i, j) = y(i, j) - (e( - 1, i) * c(i - 1, j))\r\n   50 continue\r\n      c(n, j) = c(n, j) / e(0, n)\r\ncbackward sweep                          \r\n      for 60 i = nm1, 1: - 1\r\n      c(i, j) = (c(i, j) - (e(1, i) * c(i + 1, j))) / e(0, i)\r\n   60 continue\r\n   70 continue\r\nc\r\nc^ *  m > 1: general system\r\nc\r\n      return \r\n   80 for 130 j = 1: k\r\n      c(1, j) = y(1, j)\r\ncforward sweep                         \r\n      for 100 i = 2: n\r\n      mi = min0(m, i - 1)\r\n      d = y(i, j)\r\n      for 90 l = 1: mi\r\n      d = d - (e( - l, i) * c(i - l, j))\r\n   90 continue\r\n      c(i, j) = d\r\n  100 continue\r\n      c(n, j) = c(n, j) / e(0, n)\r\ncbackward sweep                         \r\n      for 120 i = nm1, 1: - 1\r\n      mi = min0(m, n - i)\r\n      d = c(i, j)\r\n      for 110 l = 1: mi\r\n      d = d - (e(l, i) * c(i + l, j))\r\n  110 continue\r\n      c(i, j) = d / e(0, i)\r\n  120 continue\r\n  130 continue\r\nc\r\n      return \r\nc trinv.for, 1985 - 06 - 03\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc function trinv (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       to calculate trace [ b * e^ - 1 ], where b and e are n * n\r\nc       matrices with bandwidth 2 * m + 1, and where e is a regular matrix\r\nc       in lu - decomposed form. b and e are stored in vectorized form,\r\nc       compatible with subroutines bandet and bansol.\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       trace = trinv ( b, e, m, n )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       b( - m:m, n)       ( i ) input array for matrix b. element b(j, i)\r\nc                             corresponds with element b(i, i + j) of the\r\nc                             matrix b.\r\nc       e( - m:m, n)       (i / o) input array for matrix e. element e(j, i)\r\nc                             corresponds with element e(i, i + j) of the\r\nc                             matrix e. this matrix is stored in lu - \r\nc                             decomposed form, with l unit lower tri - \r\nc                             angular, and u upper triangular. the unit\r\nc                             diagonal of l is not stored. upon return,\r\nc                             the array e holds the central 2 * m + 1 bands\r\nc                             of the inverse e^ - 1, in similar ordering.\r\nc       m, n            ( i ) array and matrix dimensioning parameters\r\nc                             (m > 0, n >= 2 * m + 1).\r\nc       trinv           ( o ) output function value trace [ b * e^ - 1 ]\r\nc\r\nc reference:\r\nc ^^^^ *\r\nc\r\nc       a.m. erismanw.f. tinney, on computing certain elements of the\r\nc       inverse of a sparse matrix. communications of the acm 18(1975),\r\nc       nr. 3, pp. 177 - 179.0\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      double precision function trinv(b, e, m, n)\r\n      implicit double precision (o - z, a - h)\r\n      parameter (zero = 0d0, one = 1d0)\r\nc\r\nc^ *  assess central 2 * m + 1 bands of e^ - 1 and store in array e\r\nc\r\n      dimension b( - m:m, n), e( - m:m, n)\r\ncnth pivot                             \r\n      e(0, n) = one / e(0, n)\r\n      for 40 i = n - 1, 1: - 1\r\n      mi = min0(m, n - i)\r\nc^ *     save ith column of l and ith row of u, and normalize u row\r\ncith pivot                             \r\n      dd = one / e(0, i)\r\n      for 10 k = 1: mi\r\ncith row of u (normalized)    \r\n      e(k, n) = e(k, i) * dd\r\ncith column of l                   \r\n      e( - k, 1) = e( - k, k + i)\r\n   10 continue\r\nc^ *     invert around ith pivot\r\n      dd = dd + dd\r\n      for 30 j = mi, 1: - 1\r\n      du = zero\r\n      dl = zero\r\n      for 20 k = 1: mi\r\n      du = du - (e(k, n) * e(j - k, i + k))\r\n      dl = dl - (e( - k, 1) * e(k - j, i + j))\r\n   20 continue\r\n      e(j, i) = du\r\n      e( - j, j + i) = dl\r\n      dd = dd - ((e(j, n) * dl) + (e( - j, 1) * du))\r\n   30 continue\r\n      e(0, i) = 5d - 1 * dd\r\nc\r\nc^ *  assess trace [ b * e^ - 1 ] and clear working storage\r\nc\r\n   40 continue\r\n      dd = zero\r\n      for 60 i = 1: n\r\n      mn = - min0(m, i - 1)\r\n      mp = min0(m, n - i)\r\n      for 50 k = mn: mp\r\n      dd = dd + (b(k, i) * e( - k, k + i))\r\n   50 continue\r\n   60 continue\r\n      trinv = dd\r\n      for 70 k = 1: m\r\n      e(k, n) = zero\r\n      e( - k, 1) = zero\r\nc\r\nc^ *  ready\r\nc\r\n   70 continue\r\n      return \r\nc splder.for, 1985 - 06 - 11\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc function splder (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       to produce the value of the function (ider == 0) or of the\r\nc       iderth derivative (ider > 0) of a 2m - th order b - spline at\r\nc       the point t. the spline is described in terms of the half\r\nc       order m, the knot sequence x(n), n >= 2 * m, and the spline\r\nc       coefficients c(n).\r\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       svider = splder ( ider, m, n, t, x, c, l, q )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       splder  ( o )   function or derivative value.\r\nc       ider    ( i )   derivative order required, with 0 <= ider\r\nc                       and ider <= 2 * m. if ider == 0, the function\r\nc                       value is returned; otherwise, the ider - th\r\nc                       derivative of the spline is returned.\r\nc       m       ( i )   half order of the spline, with m > 0.0\r\nc       n       ( i )   number of knots and spline coefficients,\r\nc                       with n >= 2 * m.\r\nc       t       ( i )   argument at which the spline or its deri - \r\nc                       vative is to be evaluated, with x(1) <= t\r\nc                       and t <= x(n).\r\nc       x(n)    ( i )   strictly increasing knot sequence array,\r\nc                       x(i - 1) < x(i), i = 2, ..., n.\r\nc       c(n)    ( i )   spline coefficients, as evaluated by\r\nc                       subroutine gvcspl.\r\nc       l       (i / o)   l contains an integer such that:\r\nc                       x(l) <= t and t < x(l + 1) if t is within\r\nc                       the range x(1) <= t and t < x(n). if\r\nc                       t < x(1), l is set to 0, and if t >= x(n),\r\nc                       l is set to n. the search for l is facili - \r\nc                       tated if l has approximately the right\r\nc                       value on entry.\r\nc       q(2 * m)  ( w )   internal work array.\r\nc\r\nc remark:\r\nc ^^^\r\nc\r\nc       this subroutine is an adaptation of subroutine splder of\r\nc       the paper by lyche et al. (1983). no checking is performed\r\nc       on the validity of the input parameters.\r\nc\r\nc reference:\r\nc ^^^^ *\r\nc\r\nc       t. lyche, l.l. schumaker, k. sepehrnoori, fortran subroutines\r\nc       for computing smoothing and interpolating natural splines.\r\nc       advances in engineering software 5(1983)1, pp. 2 - 5.0\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      double precision function splder(ider, m, n, t, x, c, l, q)\r\n      implicit double precision (o - z, a - h)\r\n      parameter (zero = 0d0, one = 1d0)\r\ncf2py intent(out) :: splder\r\ncf2py intent(hide) :: q\r\nc\r\nc^ *  derivatives of ider >= 2 * m are alway zero\r\nc\r\n      dimension x(n), c(n), q(2 * m)\r\n      m2 = 2 * m\r\n      k = m2 - ider\r\n      if (k < 1) \r\n      splder = zero\r\n      return \r\nc\r\nc^ *  search for the interval value l\r\nc\r\n      end\nc\r\nc^ *  initialize parameters and the 1st row of the b - spline\r\nc^ *  coefficients tableau\r\nc\r\n      search(n, x, t, l)\r\n      tt = t\r\n      mp1 = m + 1\r\n      npm = n + m\r\n      m2m1 = m2 - 1\r\n      k1 = k - 1\r\n      nk = n - k\r\n      lk = l - k\r\n      lk1 = lk + 1\r\n      lm = l - m\r\n      jl = l + 1\r\n      ju = l + m2\r\n      ii = n - m2\r\n      ml = - l\r\n      for 2 j = jl: ju\r\n      if ((j >= mp1) && (j <= npm)) \r\n      q(j + ml) = c(j - m)\r\n      else\r\n      q(j + ml) = zero\r\n      end\nc\r\nc^ *  the following loop computes differences of the b - spline\r\nc^ *  coefficients. if the value of the spline is required,\r\nc^ *  differencing is not necessary.\r\nc\r\n    2 continue\r\n      if (ider > 0) \r\n      jl = jl - m2\r\n      ml = ml + m2\r\n      for 6 i = 1: ider\r\n      jl = jl + 1\r\n      ii = ii + 1\r\n      j1 = max0(1, jl)\r\n      j2 = min0(l, ii)\r\n      mi = m2 - i\r\n      j = j2 + 1\r\n      if (j1 <= j2) \r\n      for 3 jin = j1: j2\r\n      j = j - 1\r\n      jm = ml + j\r\n      q(jm) = (q(jm) - q(jm - 1)) / (x(j + mi) - x(j))\r\n    3 continue\r\n      end\n      if (jl >= 1) #FIXME goto 6\r\n      i1 = i + 1\r\n      j = ml + 1\r\n      if (i1 <= ml) \r\n      for 5 jin = i1: ml\r\n      j = j - 1\r\n      q(j) = - q(j - 1)\r\n    5 continue\r\n      end\n    6 continue\r\n      for 7 j = 1: k\r\n      q(j) = q(j + ider)\r\n    7 continue\r\nc\r\nc^ *  compute lower half of the evaluation tableau\r\nc\r\n      end\nctableau ready if ider == 2 * m - 1            \r\n      if (k1 >= 1) \r\n      for 14 i = 1: k1\r\n      nki = nk + i\r\n      ir = k\r\n      jj = l\r\n      ki = k - i\r\nc^ *        right - hand b - splines\r\n      nki1 = nki + 1\r\n      if (l >= nki1) \r\n      for 9 j = nki1: l\r\n      q(ir) = q(ir - 1) + ((tt - x(jj)) * q(ir))\r\n      jj = jj - 1\r\n      ir = ir - 1\r\n    9 continue\r\nc^ *        middle b - splines\r\n      end\n      lk1i = lk1 + i\r\n      j1 = max0(1, lk1i)\r\n      j2 = min0(l, nki)\r\n      if (j1 <= j2) \r\n      for 11 j = j1: j2\r\n      xjki = x(jj + ki)\r\n      z = q(ir)\r\n      q(ir) = z + (((xjki - tt) * (q(ir - 1) - z)) / (xjki - x(jj)))\r\n      ir = ir - 1\r\n      jj = jj - 1\r\n   11 continue\r\nc^ *        left - hand b - splines\r\n      end\n      if (lk1i <= 0) \r\n      jj = ki\r\n      lk1i1 = 1 - lk1i\r\n      for 13 j = 1: lk1i1\r\n      q(ir) = q(ir) + ((x(jj) - tt) * q(ir - 1))\r\n      jj = jj - 1\r\n      ir = ir - 1\r\n   13 continue\r\n      end\n   14 continue\r\nc\r\nc^ *  compute the return value\r\nc\r\n      end\nc^ *  multiply with factorial if ider > 0\r\n      z = q(k)\r\n      if (ider > 0) \r\n      for 16 j = k: m2m1\r\n      z = z * j\r\n   16 continue\r\n      end\nc\r\nc^ *  ready\r\nc\r\n      splder = z\r\n      return \r\nc search.for, 1985 - 06 - 03\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\nc subroutine search (real * 8)\r\nc\r\nc purpose:\r\nc ^^^ *\r\nc\r\nc       given a strictly increasing knot sequence x(1) < ... < x(n),\r\nc       where n > = 1, and a real number t, this subroutine finds the\r\nc       value l such that x(l) < = t < x(l + 1).  if t < x(1), l = 0;\r end\nc       if x(n) < = t, l = n.\r end\nc\r\nc calling convention:\r\nc ^^^^^^^^^\r\nc\r\nc       search ( n, x, t, l )\r\nc\r\nc meaning of parameters:\r\nc ^^^^^^^^^^ *\r\nc\r\nc       n       ( i )   knot array dimensioning parameter.\r\nc       x(n)    ( i )   stricly increasing knot array.\r\nc       t       ( i )   input argument whose knot interval is to\r\nc                       be found.\r\nc       l       (i / o)   knot interval parameter. the search procedure\r\nc                       is facilitated if l has approximately the\r\nc                       right value on entry.\r\nc\r\nc remark:\r\nc ^^^\r\nc\r\nc       this subroutine is an adaptation of subroutine search from\r\nc       the paper by lyche et al. (1983). no checking is performed\r\nc       on the input parameters and data; the algorithm may fail if\r\nc       the input sequence is not strictly increasing.\r\nc\r\nc reference:\r\nc ^^^^ *\r\nc\r\nc       t. lyche, l.l. schumaker, k. sepehrnoori, fortran subroutines\r\nc       for computing smoothing and interpolating natural splines.\r\nc       advances in engineering software 5(1983)1, pp. 2 - 5.0\r\nc\r\nc^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *\r\nc\r\n      end\nc\r\n      subroutine search(n, x, t, l)\r\n      implicit double precision (o - z, a - h)\r\nc\r\n      dimension x(n)\r\nc^ *     out of range to the left\r\n      if (t < x(1)) \r\n      l = 0\r\n      return \r\n      end\nc^ *     out of range to the right\r\n      if (t >= x(n)) \r\n      l = n\r\n      return \r\nc^ *  validate input value of l\r\n      end\n      l = max0(l, 1)\r\nc\r\nc^ *  often l will be in an interval adjoining the interval found\r\nc^ *  in a previous to search\r\nc\r\n      if (l >= n) l = n - 1\r end\n      if (t >= x(l)) #FIXME goto 5\r\n      l = l - 1\r\nc\r\nc^ *  perform bisection\r\nc\r\n      if (t >= x(l)) return \r\n      il = 1\r\n    3 iu = l\r\n    4 l = (il + iu) / 2\r\n      if ((iu - il) <= 1) return \r\n      if (t < x(l)) #FIXME goto 3\r\n      il = l\r\n      #FIXME goto 4\r\n    5 if (t < x(l + 1)) return \r\n      l = l + 1\r\n      if (t < x(l + 1)) return \r\n      il = l + 1\r\n      iu = n\r\nc\r\n      #FIXME goto 4\r\n      end\n", "meta": {"hexsha": "9a708f803d3c7fefebcdcd7a5e955d32be00a825", "size": 49817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deps/src/gcvspline/gcvspl.jl", "max_stars_repo_name": "charlesll/gcvspl", "max_stars_repo_head_hexsha": "708ef035b2388107d9e1e802fc97e5738103d0c7", "max_stars_repo_licenses": ["MIT"], "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/src/gcvspline/gcvspl.jl", "max_issues_repo_name": "charlesll/gcvspl", "max_issues_repo_head_hexsha": "708ef035b2388107d9e1e802fc97e5738103d0c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T11:07:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T13:44:18.000Z", "max_forks_repo_path": "deps/src/gcvspline/gcvspl.jl", "max_forks_repo_name": "charlesll/gcvspl", "max_forks_repo_head_hexsha": "708ef035b2388107d9e1e802fc97e5738103d0c7", "max_forks_repo_licenses": ["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.6147098516, "max_line_length": 178, "alphanum_fraction": 0.4862998575, "num_tokens": 15768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7844810917605866}}
{"text": "function nlp_cvx_105_013(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    model = Model(optimizer)\n\n    @variable(model, x, start = 0.1)\n    @variable(model, y)\n\n    @objective(model, Min, -x + y)\n    @NLconstraint(model, exp(x - 2.0) - 0.5 <= y)\n    @NLconstraint(model, log(x) + 0.5 >= y)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -3 / 2, tol = objective_tol)\n    return check_solution([x, y], [2, 1 / 2], tol = primal_tol)\nend\n", "meta": {"hexsha": "3a3151849c83c89dc037ca55a740f1fb7618ad5a", "size": 629, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/105_013.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/105_013.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/105_013.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 26.2083333333, "max_line_length": 76, "alphanum_fraction": 0.6613672496, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321806, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7844810912920643}}
{"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=\u221e`)\n- `\u03bb` is the length of spatial localization (default is none)\n\nThe initial data `(\u03b7,v)` are generated through randomly chosen Fourier coefficients,\nmultiplied with weigth `w=10^(-|k|L/(2\u03c0))` if `s=\u221e`, or `w=1/(1+9(|k|L/(2\u03c0))^(s+1/2))` otherwise.\nIf `\u03bb` is provided, the function in spatial variables is multiplied by `exp(-|x/\u03bb|^2)`,\nand in any case normalized to have maximum absolute value 1.\n\n\n\"\"\"\nstruct Random <: InitialData\n\n    \u03b7\n    v\n\n    function Random(;L=1,s=Inf,\u03bb=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*\u03c0)))\n            else\n                w = 1 ./( 1 .+ 9*abs.(k*L/(2*\u03c0)).^(s+1/2) )\n            end\n            if \u03bb == nothing\n                \u03c6 = zero(x).+1\n            else\n                \u03c6 = exp.(-abs.((x/\u03bb).^2))\n            end\n\n            \u03b8 = 2*\u03c0*rand(Float64,length(x))\n            r = rand(Float64,length(x))\n            Fourier = r.*exp.(-1im.*\u03b8).*w\n            Physic = real.(ifft(Fourier)).*\u03c6\n            return Physic./maximum(abs.(Physic))\n        end\n        \u03b7( x ) = generate( x )\n        v( x ) = generate( x )\n\n\n    \tnew( \u03b7,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 \u2208 [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    \u0394::T = b-a\n    return (x-a)/\u0394*convert(T,2) - one(T)\nend\n\n# scale y \u2208 [-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    \u0394::T = b-a\n    return (y+1)/2*\u0394 + 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( \ud835\udf4b[j](y[i]) for j = 1:n+1 for i = 1:m+1 ), but transposed.\nfunction getunivariateChebyVmatrix(\ud835\udce7::Vector{T}, L::Int) where T\n    p = length(\ud835\udce7)\n    V = Matrix{T}(undef,L+1,p)\n\n    for j = 1:p\n        V[:,j] = Chebyshev1stall(\ud835\udce7[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(\u03c0)/BigFloat(L+1) ) for i = 0:L+1 )\nend\n\n\nfunction Chebyshev2ndnodes(L::Int)::Vector{BigFloat}\n    return collect( cos( (L-i)*BigFloat(\u03c0)/BigFloat(L) ) for i = 0:L+1 )\nend\n\nfunction Chebyshev2ndnode(i::Int, L::Int)::BigFloat\n    return cos( (L-i)*BigFloat(\u03c0)/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    \ud835\udc67 = convert(Vector{T}, real.(C_eig.values))\n    unique!(\ud835\udc67)\n    filter!(xx->isnumericallyin(xx,-one(T),one(T)), \ud835\udc67)\n    clamp!(\ud835\udc67,-one(T),one(T))\n\n    return \ud835\udc67\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    \ud835\udc51itp_X = evalunivariateChebyshevpolynomialderivative(a,X)\n\n    remove_list = Vector{Int}(undef,0)\n    for i = 1:length(X)\n        if !isnumericallyclose(\ud835\udc51itp_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# \ud835\udce7 is the set of reference positions.\nfunction findChebyitpextremainterval(  \ud835\udc52::Function,\n                                    L::Int,\n                                    \ud835\udcdf_in::Vector{T},\n                                    tol_\ud835\udce7_spacing, # was defaulted to convert(T,1e-6/length(\ud835\udcdf_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(\ud835\udc52, L, \ud835\udcdf_in,\n                                            sample_position_template,\n                                            tol_\ud835\udce7_spacing, tol_derivative_zero)\n\n    # check each point in out to see if its a stationary point.\n    chkfunc = xx->numericalchkextrema(\ud835\udc52, 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    \u03bd = collect( Chebyshev2ndnode(k,L) for k = 0:L )\n\n    term1 = 1/2 * f(\u03bd[1]) * g(\u03bd[1])\n\n    term2 = BigFloat(\"0\")\n    for l = 1:L-1\n        term2 += f(\u03bd[l+1]) * g(\u03bd[l+1])\n    end\n\n    term3 = 1/2 * f(\u03bd[L+1]) * g(\u03bd[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\u00d7(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\u00d7n 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\u00d7n {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\u22c5t + c\u22c5t\u00b2 + d\u22c5t\u00b3\n        spline_coeffs[1,:] = pts[k,1:n] # x\u2080\n        spline_coeffs[2,:] = D[1:n]     # x'\u2080\n        spline_coeffs[3,:] = 3*(pts[k,2:n+1]' - pts[k,1:n]') -2*D[1:n] - D[2:n+1] # -3x\u2080 + 3x\u2081 - 2x'\u2080 - x'\u2081\n        spline_coeffs[4,:] = 2*(pts[k,1:n]' - pts[k,2:n+1]') +  D[1:n] + D[2:n+1] #  2x\u2080 - 2x\u2081 +  x'\u2080 + x'\u2081\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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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    \u03ba_hi = sample_spline_curvature(spline_coeffs_x, spline_coeffs_y, t_hi)\n    \u03ba_lo = sample_spline_curvature(spline_coeffs_x, spline_coeffs_y, t_lo)\n\n    (\u03ba_hi - \u03ba_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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2208 [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 \u2208 (-\u221e,1] we use spline_coeffs[:,1]\n    # for t \u2208 [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 \u2192 $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 \u2264 0.0 and t=1 if s > L\n    if s \u2264 0.0\n        return 0.0\n    elseif s \u2265 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 \u2264 lo ? 0.5*(lo+hi) : tCandidate\n        else\n            lo = t\n            t = tCandidate \u2265 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 \u2264 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 \u2264 0.0\n        return 0.0\n    elseif s \u2265 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 \u2264 lo ? 0.5*(lo+hi) : tCandidate\n        else\n            lo = t\n            t = tCandidate \u2265 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 \u2264 0.0\n        t = 0.0\n    elseif s \u2265 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 \u2264 0.0\n            t = 0.0\n            t_arr[i], lo = t, t\n            continue\n        elseif s \u2265 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 \u2264 lo ? 0.5*(lo+hi) : tCandidate\n            else\n                lo = t\n                t = tCandidate \u2265 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 \u2264 0.0\n        t = 0.0\n    elseif s \u2265 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 \u2264 0.0\n            t = 0.0\n            t_arr[i] = lo = t\n            continue\n        elseif s \u2265 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 \u2264 lo ? 0.5*(lo+hi) : tCandidate\n            else\n                lo = t\n                t = tCandidate \u2265 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": "n = rand(1:10)\n\nA = rand(n, n)\n\nr = polarfact(A, alg = :halley);\n\n\n# Test unitary matrix U\n\nU = r.U\nH = r.H\n\n@test_approx_eq_eps U'*U eye(n) 1e-7\n\n# Test Hermitian positive semifefinite matrix H\n\n@test issym(H)\n \nfor i in eigvals(H)\n    @test i >= 0.\nend\n\n@test_approx_eq A U*H\n\nprintln(\"Halley method passed test...\")\n\n##########################################################\n\nm = rand(1:10)\n\nB = rand(m, m)\n\nr2 = polarfact(B, alg = :qdwh);\n\n# Test unitary matrix U\n\nU2 = r2.U\nH2 = r2.H\n\n@test_approx_eq_eps U2'*U2 eye(m) 1e-7\n\n# Test Hermitian positive semifefinite matrix H\n\n@test issym(H2)\n \nfor i in eigvals(H2)\n    @test i >= 0.\nend\n\n@test_approx_eq B U2*H2\n\nprintln(\"QDWH method passed test...\")\n", "meta": {"hexsha": "e9068c89305a254c37673c5989f1efc85ab89988", "size": 705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_halley.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_stars_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_stars_repo_licenses": ["MIT"], "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_halley.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_issues_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_issues_repo_licenses": ["MIT"], "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_halley.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_forks_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_forks_repo_licenses": ["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.3018867925, "max_line_length": 58, "alphanum_fraction": 0.5914893617, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7844693427894712}}
{"text": "list = readlines(\"day1_input.txt\")\n\nfunction get_two(list)\n    years = parse.(Int, list)\n    for i in years\n        for j in years\n            if i+j == 2020\n                return i*j\n            end\n        end\n    end\n    return \"Not found\"    \nend\n\nfunction get_two_ind(list)\n    years = parse.(Int, list)\n    for i in 1:length(years)\n        for j in (i+1):length(years)\n            if years[i]+years[j] == 2020\n                return years[i]*years[j]\n            end\n        end\n    end\n    return \"Not found\"\nend\n\nfunction get_two_comprehension(list)\n    years = parse.(Int, list)\n    prod = [a*b for a in years for b in years if a+b==2020]\n    if length(prod) > 1\n        return prod[1]\n    else\n        return \"Not found\"\n    end\nend\n\nfunction get_two_sorting(list)\n    years = parse.(Int, list)\n    list_inc = sort(years)\n    list_dec = sort(years, rev = true)\n    for a in list_inc\n        for b in list_dec\n            if a + b == 2020\n                return a*b\n            end\n        end\n    end\n    return \"Not found\"\nend\n\nfunction findsol(list)\n    years = parse.(Int, list)\n    sorted=sort(years)\n    sm,la=1,length(sorted)\n    while sm<la\n        cur=sorted[sm]+sorted[la]\n        if cur<2020\n            sm+=1\n        elseif cur>2020\n            la-=1\n        else\n            return sorted[sm]*sorted[la]\n        end\n    end\n    error(\"dead end\")\nend\n\n\nfunction get_three(list)\n    years = parse.(Int, list)\n    for i in years\n        for j in years\n            for k in years\n                if i+j+k == 2020\n                    return i*j*k\n                end\n            end\n        end\n    end\n    return \"Not found\"    \nend\n\n@show get_two(list) == 355875\n@show get_two_ind(list) == 355875\n@show get_two_comprehension(list) == 355875\n@show get_two_sorting(list) == 355875\n@show findsol(list) == 355875\n@show get_three(list) == 140379120\n\n#= \n```julia\njulia> @btime get_two(list)\n  19.653 \u03bcs (2 allocations: 1.78 KiB)\n\njulia> @btime get_two_ind(list);\n  18.567 \u03bcs (2 allocations: 1.78 KiB)\n\njulia> @btime get_two_comprehension(list);\n  42.493 \u03bcs (5 allocations: 1.98 KiB)\n\njulia> @btime get_two_sorting(list);\n  14.270 \u03bcs (4 allocations: 5.31 KiB)\n\njulia> @btime findsol(list);\n  12.201 \u03bcs (3 allocations: 3.55 KiB)\n\njulia> @btime get_three(list);\n  437.935 \u03bcs (2 allocations: 1.78 KiB)\n```\n =#\n \nnothing\n", "meta": {"hexsha": "782c33aeb00776c377ee207adddc5bf9f10885fd", "size": 2331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aoc2020/day01_sum2020.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/day01_sum2020.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/day01_sum2020.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": 20.6283185841, "max_line_length": 59, "alphanum_fraction": 0.564993565, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7843882955037116}}
{"text": "using CayleyDickson\nusing Base.Test: @test, @test_throws\n\n@test begin\n    a = CayleyDickson.randomBigFloat()\n    isreal(Sedenion(Octonion(a)))\nend\n\n@test begin\n    a = 1\n    !isreal(Sedenion(Octonion(a, a, a, a)))\nend\n\n@test begin\n    z = random(Sedenion{Int})\n    z == +(z)\nend\n\n@test begin\n    a = CayleyDickson.randomBigFloat()\n    real(Sedenion(Octonion(a))) == a\nend\n\n@test begin\n    io = IOBuffer()\n    show(io, Sedenion(Octonion(1.0, 2, 3, 4, 5, 6, 7, 8)))\n    l = String(take!(io))\n    r = \"[1: 1.0, i: 2.0, j: 3.0, ij: 4.0, k: 5.0, ik: 6.0, jk: 7.0, (ij)k: 8.0, m: 0.0, im: 0.0, jm: 0.0, (ij)m: 0.0, km: 0.0, (ik)m: 0.0, (jk)m: 0.0, ((ij)k)m: 0.0]\"\n    l == r\nend\n\n@test begin\n    a = CayleyDickson.randomBigInt()\n    b = CayleyDickson.randomBigInt()\n    c = CayleyDickson.randomBigInt()\n    d = CayleyDickson.randomBigInt()\n    l = Sedenion(Octonion(a, b, c, d))\n    r = Sedenion(Quaternion(a, b, c, d))\n    l == r\nend\n\n@test begin\n    a = CayleyDickson.randomBigInt()\n    b = CayleyDickson.randomBigInt()\n    l = Sedenion(Binion(a, b))\n    r = Sedenion(Octonion(a, b))\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigFloat})\n    y = random(Sedenion{BigFloat})\n    x != y\nend\n\n@test begin\n    a = CayleyDickson.randomBigInt()\n    z = random(Sedenion{BigInt})\n    l = a + z\n    r = z + a\n    l == r\nend\n\n@test begin\n    a = random(Octonion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = a + z\n    r = z + a\n    l == r\nend\n\n@test begin\n    a = CayleyDickson.randomBigInt()\n    z = random(Sedenion{BigInt})\n    l = a - z\n    r = -(z - a)\n    l == r\nend\n\n@test begin\n    a = random(Octonion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = a - z\n    r = -(z - a)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = x + y\n    r = y + x\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = x * y\n    r = y * x\n    l != r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = x - y\n    r = -(y - x)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = (x + y) + z\n    r = x + (y + z)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = (x * y) * z\n    r = x * (y * z)\n    l != r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = alternatorL(x, y)\n    r = zero(Sedenion{BigInt})\n    l != r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = alternatorR(x, y)\n    r = zero(Sedenion{BigInt})\n    l != r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = flexator(x, y)\n    r = zero(Sedenion{BigInt})\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    conj(conj(x)) == x\nend\n\n@test begin\n    x = random(Sedenion{Rational{BigInt}})\n    inv(inv(x)) == x\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = conj(x * y)\n    r = conj(y) * conj(x)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = conj(x + y)\n    r = conj(x) + conj(y)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = conj(x - y)\n    r = conj(x) - conj(y)\n    l == r\nend\n\n# @test begin\n#     x = random(Sedenion{Rational{BigInt}})\n#     y = random(Sedenion{Rational{BigInt}})\n#     z = x * y\n#     z / y == x\n# end\n\n# @test begin\n#     x = random(Sedenion{Rational{BigInt}})\n#     y = random(Sedenion{Rational{BigInt}})\n#     z = x * y\n#     x \\ z == y\n# end\n\n# @test begin\n#     x = random(Sedenion{Rational{BigInt}})\n#     y = random(Sedenion{Rational{BigInt}})\n#     l = inv(x * y)\n#     r = inv(y) * inv(x)\n#     l == r\n# end\n\n# @test begin\n#     x = random(Sedenion{Rational{BigInt}})\n#     y = random(Sedenion{Rational{BigInt}})\n#     l = inv(x / y)\n#     r = y / x\n#     l == r\n# end\n\n# @test begin\n#     x = random(Sedenion{Rational{BigInt}})\n#     y = random(Sedenion{Rational{BigInt}})\n#     l = inv(x \\ y)\n#     r = y \\ x\n#     l == r\n# end\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = x * (y + z)\n    r = (x * y) + (x * z)\n    l == r\nend\n\n@test begin\n    a = CayleyDickson.randomBigInt()\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = a * (x + y)\n    r = (a * x) + (a * y)\n    l == r\nend\n\n@test begin\n    a = CayleyDickson.randomBigInt()\n    x = random(Sedenion{BigInt})\n    l = a * x\n    r = x * a\n    l == r\nend\n\n@test begin\n    a = random(Octonion{BigInt})\n    x = random(Sedenion{BigInt})\n    l = commutator(a, x)\n    r = zero(Sedenion{BigInt})\n    l != r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = (x + y) * z\n    r = (x * z) + (y * z)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = x * (y - z)\n    r = (x * y) - (x * z)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    z = random(Sedenion{BigInt})\n    l = (x - y) * z\n    r = (x * z) - (y * z)\n    l == r\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    quadrance(x) > big(0) || quadrance(x) == big(0)\nend\n\n@test begin\n    x = random(Sedenion{BigInt})\n    y = random(Sedenion{BigInt})\n    l = quadrance(x * y)\n    r = quadrance(x) * quadrance(y)\n    l != r\nend\n\n@test_throws ErrorException begin\n    inv(Sedenion(Octonion(0)))\nend\n\n@test_throws ErrorException begin\n    random(Sedenion{Int}) / 0\nend\n\n@test_throws ErrorException begin\n    0 \\ random(Sedenion{Int})\nend\n\n@test begin\n    a = CayleyDickson.randomBigRational()\n    z = random(Sedenion{Rational{BigInt}})\n    l = z / a\n    r = a \\ z\n    l == r\nend\n\n@test begin\n    a = CayleyDickson.randomBigRational()\n    z = random(Sedenion{Rational{BigInt}})\n    l = a / z\n    r = z \\ a\n    l == r\nend\n\n@test begin\n    z = random(Sedenion{BigInt})\n    z == z + zero(Sedenion{BigInt})\nend\n\n@test begin\n    z = random(Sedenion{BigInt})\n    z == z * one(Sedenion{BigInt})\nend\n\n@test begin\n    z = random(Sedenion{BigInt})\n    z == z + zero(z)\nend\n\n@test begin\n    z = random(Sedenion{BigInt})\n    z == z * one(z)\nend\n\n@test begin\n    i = Sedenion{Int}(Octonion(0,1), zero(Octonion{Int}))\n    m = Sedenion{Int}(zero(Octonion{Int}), one(Octonion{Int}))\n    anti_alternatorL(i, m) != zero(Sedenion{Int})\nend\n\n@test begin\n    i = Sedenion{Int}(Octonion(0,1), zero(Octonion{Int}))\n    m = Sedenion{Int}(zero(Octonion{Int}), one(Octonion{Int}))\n    anti_alternatorR(i, m) != zero(Sedenion{Int})\nend\n\n@test begin\n    i = Sedenion{Int}(Octonion(0,1), zero(Octonion{Int}))\n    m = Sedenion{Int}(zero(Octonion{Int}), one(Octonion{Int}))\n    anti_flexator(i, m) != zero(Sedenion{Int})\nend\n\n@test begin\n    l = Sedenion(1,2,3,4)\n    r = Sedenion(Quaternion(1,2,3,4))\n    l == r\nend\n\n@test begin\n    l = Sedenion(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17)\n    r = Sedenion(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)\n    l == r\nend\n", "meta": {"hexsha": "b4e39b8fc36c89458c575f3c7c4da183ae95c1ad", "size": 7205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sedenion_test.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": "test/sedenion_test.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": "test/sedenion_test.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": 19.1114058355, "max_line_length": 167, "alphanum_fraction": 0.5591950035, "num_tokens": 2664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7843882840353511}}
{"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(\ud83d\udc22, 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 * \u03c0 * 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 \u03b1\n@variables x(t) y(t)\nD = Differential(t)\n\neqs = [D(x) ~ y * x,\n       D(y) ~ -\u03b1 * x]\n\n@named sys = ODESystem(eqs)\n\nu0 = [ x => 1.0, y => 2.0]\ntspan = (0.0, 1.0)\np = [\u03b1 => 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": "using Distributions\nusing SpecialFunctions\nimport Base.convert\n# this is a file defining the half-Cauchy Distribution\n\nstruct HalfCauchy{T <: Real} <: Distributions.ContinuousDistribution\n    a :: T # Beta(a, b) shape\u2081\n    b :: T # Beta(a, b) shape\u2082\n\n    function HalfCauchy{T}(a :: T, b :: T) where T\n        Distributions.@check_args(HalfCauchy, a > zero(a), b > zero(b))\n        new{T}(a, b)\n    end\nend\n\nHalfCauchy(a :: T, b :: T) where{T <: Real} = HalfCauchy{T}(a, b)\nHalfCauchy(a :: Real, b :: Real) =  HalfCauchy(promote(a, b)...)\nHalfCauchy(a :: Integer, b :: Integer) = HalfCauchy(Float64(a), Float64(b))\nHalfCauchy() = HalfCauchy(0.5, 0.5)\n\nDistributions.@distr_support HalfCauchy 0 Inf\n\n#### Conversions\n\nfunction convert(:: Type{HalfCauchy{T}}, a :: Real, b :: Real) where T<: Real\n    HalfCauchy(T(a), T(b))\nend\nfunction convert(:: Type{HalfCauchy{T}}, d :: HalfCauchy{S}) where {T <: Real, S <: Real}\n    HalfCauchy(T(d.a), T(d.b))\nend\n\n#### Parameters\nparams(d :: HalfCauchy) = (d.a, d.b)\n\n#### Statistics\n# I skipped this part\n\n#### Functions\npdf(d :: HalfCauchy, x :: Real) = (x ^(b - 1) /(1 + x)^(d.a + d.b)) / beta(d.a, d.b)\n", "meta": {"hexsha": "e15dd639c19869cd61340ee921a00fbdc7a62904", "size": 1145, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "halfCauchy.jl", "max_stars_repo_name": "YinpuLi/SparsityBoosting", "max_stars_repo_head_hexsha": "8e14500cf9ef339ed87a5c5637e1844ffcce1bed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "halfCauchy.jl", "max_issues_repo_name": "YinpuLi/SparsityBoosting", "max_issues_repo_head_hexsha": "8e14500cf9ef339ed87a5c5637e1844ffcce1bed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "halfCauchy.jl", "max_forks_repo_name": "YinpuLi/SparsityBoosting", "max_forks_repo_head_hexsha": "8e14500cf9ef339ed87a5c5637e1844ffcce1bed", "max_forks_repo_licenses": ["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.625, "max_line_length": 89, "alphanum_fraction": 0.6270742358, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7843502017702828}}
{"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": "cd(@__DIR__); runapprox = true; allNGWPs = false; include(\"setups/sunflower.jl\")\ngr(dpi = 200)\n\n##\nVM_NGWP = vm_ngwp(\ud835\udebd, GP_dual)\nf = matread(\"../datasets/sunflower_barbara_voronoi.mat\")[\"f_trouser_voronoi\"]\nG_Sig.f = reshape(f, (N, 1))\ndmatrix_VM = ngwp_analysis(G_Sig, VM_NGWP)\ndvec_vm_ngwp, BS_vm_ngwp = ngwp_bestbasis(dmatrix_VM, GP_dual)\nimportant_idx = sortperm(dvec_vm_ngwp[:].^2; rev = true)\nprintln(\"================ftrouser-VM-NGWP-top-basis-vectors=================\")\nfor i in 2:17\n    dr, dc = BS_vm_ngwp.levlist[important_idx[i]]\n    w = VM_NGWP[dr, dc, :]\n    j, k, l = NGWP_jkl(GP_dual, dr, dc)\n    print(\"(j, k, l) = ($(j), $(k), $(l))  \")\n    if j == jmax\n        print(\"\u03c6_{$(GP_dual.ind[dr]-1)}\")\n    end\n    println()\n    scatter_gplot(X; marker = w, ms = LinRange(4.0, 14.0, N), c = :greys)\n    plt = plot!(xlim = [-1.2, 1.2], ylim = [-1.2, 1.2], frame = :none,\n                cbar = false, clims = (-0.15, 0.15))\n    savefig(plt,\n        \"../figs/SunFlower_ftrouser_DAG_VM_NGWP_ibv$(lpad(i,2,\"0\"))_j$(j)_k$(k)_l$(l).png\")\nend\n", "meta": {"hexsha": "aeee40939aa3c25ea540e921aff7738771a881b8", "size": 1047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dissertations/htli/scripts/Figure9.5.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/dissertations/htli/scripts/Figure9.5.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/dissertations/htli/scripts/Figure9.5.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": 38.7777777778, "max_line_length": 91, "alphanum_fraction": 0.594078319, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671712, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7843502010696874}}
{"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\u03c0\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": "#\n# Heap Sort\n#\n\nfunction heapSort(A)\n\n  buildHeap(A)\n\n  n = length(A)\n  i = n\n  while i > 0\n\n    tmp = A[1]\n    A[1] = A[i]\n    A[i] = tmp\n\n    heapify(A, 1, i)\n\n    i = i - 1\n  end\n\nend\n\nfunction buildHeap(A)\n\n  n = length(A)\n  i = Int(n/2)\n  while i > 0\n\n    heapify(A, i, n)\n\n    i = i - 1\n  end\n\nend\n\nfunction heapify(A, idx, idx_max)\n  largest = idx\n  left = 2 * (idx-1) + 1\n  right = 2 * (idx-1) + 2\n\n  if left < idx_max && A[left] > A[idx]\n    largest = left\n  end\n  if right < idx_max && A[right] > A[largest]\n    largest = right\n  end\n  if largest != idx\n    tmp = A[idx]\n    A[idx] = A[largest]\n    A[largest] = tmp\n    heapify(A,  largest,  idx_max)\n  end\nend\n\nfunction main()\n\n  # list to be sorted\n  rng = MersenneTwister(1234);\n  A = shuffle(rng, Vector(1:100))\n  Aorigin = copy(A)\n\n  # sorting\n  @time heapSort(A)\n\n  print(\"The original list: \")\n  println(Aorigin)\n\n  print(\"The sorted list: \")\n  println(A)\n\nend\n\n\n\nif contains(@__FILE__, PROGRAM_FILE)\n    main()\nend\n", "meta": {"hexsha": "95a673058d126222a17c19d48dcf616c955f0c4c", "size": 984, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chap4/heapSort.jl", "max_stars_repo_name": "szmlb/algorithmsInJulia", "max_stars_repo_head_hexsha": "eedd244fc82f20c481448524934e200597f5fe53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chap4/heapSort.jl", "max_issues_repo_name": "szmlb/algorithmsInJulia", "max_issues_repo_head_hexsha": "eedd244fc82f20c481448524934e200597f5fe53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chap4/heapSort.jl", "max_forks_repo_name": "szmlb/algorithmsInJulia", "max_forks_repo_head_hexsha": "eedd244fc82f20c481448524934e200597f5fe53", "max_forks_repo_licenses": ["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.4556962025, "max_line_length": 45, "alphanum_fraction": 0.5589430894, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7843461655186827}}
{"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\u2080 = u0 * ones(1); V\u2080 = v0 * ones(1);\n\nivp_free = InitialValueProblem(sys, (U\u2080, V\u2080))\n\nNSTEPS = 1000 ;\n\u0394t = 0.005 ;\n\n#-\n\nalg = Bathe(\u0394t = \u0394t )\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(\u03c9_f \\cdot t)$\n#\n\u03c9N = sqrt(k/m)\n\u03c9f = \u03c9N * 2\nAf = 10.0\nR  = [ [ Af * sin(\u03c9f * \u0394t * (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\u2080, V\u2080))\n\nalg = Bathe(\u0394t = \u0394t )\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      -\u03c9N^2 0     1/m 0 ;\n          0 0     0 1 ;\n          0 0 -\u03c9f^2 0 ] ;\n\nC = -Diagonal(ones(4))\nM = zeros(4,4)\nR = zeros(4)\n\nsys = SecondOrderAffineContinuousSystem(M, C, K, R)\n\nU\u2080 = [u0; v0; 0; \u03c9f*Af ] ;\n\nivp_forced_firOrder = InitialValueProblem(sys, (U\u2080, U\u2080) )\n\nalg = BackwardEuler(\u0394t = \u0394t )\nsol_firOrderA = solve(ivp_forced_firOrder, alg, NSTEPS=NSTEPS);\n\nNSTEPS = NSTEPS*3 ; alg = BackwardEuler(\u0394t = \u0394t/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": "#========================================================================================#\n#\tLaboratory 4\n#\n# Tuples, Pairs, Dict, Symbol, files, Dates, Random numbers and downloading.\n# Files and Dates are available in Julia Programming Cookbook\n#\n# Author: Niall Palfreyman, 13/01/2022\n#========================================================================================#\n[\n\tActivity(\n\t\t\"\"\"\n\t\tIn this laboratory we introduce several helpful Julia tools that make life a\n\t\tlittle easier: Tuples, Pairs, Dicts, Symbols, Files, DateTimes, Random and downloading.\n\n\t\tA Tuple is an immutable container that can contain several different types. We\n\t\tconstruct Tuples using round brackets, for example:\n\n\t\t\tmy_tuple = (5, 2.718, \"Niall\")\n\n\t\tWhat is my_tuple[2]?\n\t\t\"\"\",\n\t\t\"my_tuple[2]\",\n\t\tx -> x==Main.my_tuple[2]\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tYou have already seen that size() returns a Tuple. Enter the following code:\n\n\t\t\tret_size = size(zeros(3,4))\n\n\t\tWhat is the value of ret_size[1]? Try changing the value of ret_size[2].\n\t\tFinally, what is the type of ret_size? \n\t\t\"\"\",\n\t\t\"typeof(ret_size)\",\n\t\tx -> x==typeof(size(zeros(3,4)))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tTuples are especially useful when we want to define anonymous functions with\n\t\tmore than one argument:\n\n\t\t\tmap((x,y)->3x+2y,4,5)\n\n\t\tConstruct a single line mapping that calculates sin(x*y) for corresponding\n\t\telements in the two ranges x = 1:5 and y = 5:-1:1\n\t\t\"\"\",\n\t\t\"map((x,y)->sin(x*y),1:5,5:-1:1)\",\n\t\tx -> x==map((x,y)->sin(x*y),1:5,5:-1:1)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tA Pair is a structure that contains two objects - typically a key and its\n\t\tentry in a dictionary. We construct a Pair like this:\n\n\t\t\tmy_pair = \"Yellow Submarine\" => \"Beatles\"\n\n\t\tConstruct my_pair and then find the value of last(my_pair):\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==last(\"Yellow Submarine\" => \"Beatles\")\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tA Dict(ionary) is a hashed database of Pairs. Dicts are very lightweight, so\n\t\twe can easily use them in everyday code. We construct a Dict by passing a\n\t\tsequence of Pairs to the constructor:\n\n\t\t\tmy_dict = Dict( \"pi\" => 3.142, \"e\" => 2.718)\n\n\t\tConstruct my_dict, and notice that the Pairs are not necessarily in the same\n\t\torder that you entered them. Now look up the value of \"pi\" in my_dict:\n\t\t\"\"\",\n\t\t\"my_dict[\\\"pi\\\"]\",\n\t\tx -> x==3.142\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can find out whether our Dict contains the key \"e\" by using the keys() function:\n\n\t\t\t\"e\" in keys(my_dict)\n\n\t\tDelete the entry for \"e\" from my_dict using the delete!() function. What word do\n\t\tyou now see in red if you enter my_dict[\"e\"]?\n\t\t\"\"\",\n\t\t\"delete!(my_dict,\\\"e\\\")\",\n\t\tx -> x==\"ERROR\"\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow add two extra entries to my_dict:\n\n\t\t\tmy_dict[\"root2\"] = 1.414\n\t\t\tmy_dict[\"epsilon0\"] = 8.854e-12\n\n\t\tWhat is the result of calling haskey(my_dict,\"root2\")?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe have already met Symbols - they define components of the Julia language, and\n\t\twe use them to extend the language with new components. We construct Symbols\n\t\tusing the colon ':'. Enter the following lines:\n\n\t\t\ta,b = 2,3\n\t\t\texpr = :(a+b)\n\t\t\tdump(expr)\n\n\t\tWhat is the value of expr.args?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==Main.expr.args\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tYou can see that the arguments of expr are Symbols waiting to be evaluated. Try:\n\n\t\t\ttypeof(expr.args[2])\n\n\t\tWhat do you get if you enter string(expr)?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> occursin(\"a+b\",replace(x,\" \"=>\"\"))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tSymbols and Strings are very similar to each other. You will see that graphics\n\t\tfunctions often use Symbols to define special switches such as :red or :filled.\n\t\t\n\t\tIn fact, a Symbol is a String that has been prepared for being evaluated.\n\t\tWhat do you get if you apply the function eval() to expr?\n\t\t\"\"\",\n\t\t\"eval(expr)\",\n\t\tx -> x==5\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe use the \"splat\" operator (...) to convert a collection into a set of\n\t\targuments for a function. Define this function and test it with a few numbers:\n\t\t\n\t\t\tmy_function(x,y,z) = x * (y+z)\n\t\t\n\t\tNow define this vector: v = [2,3,4]. Suppose we want to use the three numbers\n\t\tin v as arguments for my_function. First try it like this: my_function(v), and\n\t\tsee what happens ...\n\n\t\tIt didn't work, did it? Now tell me what you get when you enter this:\n\n\t\t\tmy_function(v...)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==14\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tFiles are an important part of everyday data science. First of all, we need to\n\t\tbe able to find files in the background filesystem. Enter: pwd() at the Julia\n\t\tprompt. This stands for Present Working Directory ...\n\n\t\tWhat you get back is the path of the current folder. Now enter: readdir() ...\n\n\t\tThis gives you a list of filenames in the current folder. Choose a filname in\n\t\tthis list - for example maybe \"filename.ext\". Ask whether your file is in the\n\t\tcurrent folder. What answer do you get back?\n\t\t\"\"\",\n\t\t\"\\\"filename.ext\\\" in readdir()\",\n\t\tx -> x==true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tpwd() gives us the path of the current folder, and readdir() gives us a vector\n\t\tof filenames in it. We can put these together using joinpath(). Find out the\n\t\tanswer returned by the following function call:\n\n\t\t\tisfile(joinpath(pwd(),\"filename.ext\"))\n\n\t\twhere filename.ext is the file you previously found in the current directory.\n\t\t\"\"\",\n\t\t\"Investigate the value returned by the joinpath() call\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow let's create a new file. The following command creates a file named\n\t\t\"my_data.txt\", and sets up a FILESTREAM named \"file\" for \"w\"riting to it:\n\n\t\t\tfile = open(\"my_data.txt\",\"w\")\n\n\t\tNow write some information to the file:\n\n\t\t\twrite( file, \"This is my file\\nIt belongs to me!\\n\")\n\n\t\tThe value returned by write() is the number of bytes you have written to the\n\t\tfile. We can also us the print() and println() functions, for example:\n\n\t\t\tprintln( file, \"It really does!\")\n\n\t\tFinally, close() file and tell me the result of isfile(\"my_data.txt\"):\n\t\t\"\"\",\n\t\t\"close(file)\",\n\t\tx -> x==true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tCongratulations! You have created your first file! Now let's trying\n\t\tr(eading) from the file:\n\n\t\t\tfile = open(\"my_data.txt\",\"r\")\n\n\t\tNow enter: readline(file) several times to read the lines of the file.\n\t\tOnce you have read all the lines, the file is in an end-of-file state:\n\n\t\t\teof(file)\n\n\t\tWhat value does readline() return if you continue to read lines after\n\t\tthe end-of-file?\n\t\t\"\"\",\n\t\t\"readline(file)\",\n\t\tx -> isempty(x)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow close() the file, then reopen it again to start reading at the\n\t\tbeginning of the file. We can read all lines of the file at once.\n\t\tWhat is the type of the structure returned by the following code?\n\n\t\t\tfile = open(\"my_data.txt\",\"r\")\n\t\t\treadlines( file)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x <: Vector\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tIf our file contained binary data, it would not be possible to read\n\t\tit in separate lines - in this case we use the read() function.\n\n\t\tRewind the file to the beginning using: seekstart(file).\n\t\tEnter read(file) to see the characters in the file, and tell me the\n\t\tfirst character:\n\t\t\"\"\",\n\t\t\"0x54: Scroll the Julia console back up to see the beginning\",\n\t\tx -> x==0x54\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWell, that wasn't very pleasant, was it, with all those characters\n\t\tscreaming across the screen? Let's do it in a more civilised way this time...\n\n\t\tRewind the file to the beginning using seekstart().\n\t\tNow enter:\n\n\t\t\tdata = read(file);\n\n\t\tDid you remember to write ';' at the end of the line? If not, you\n\t\thad the \"screaming characters\" problem. ';' at the end of a line\n\t\tstops the return value being written to the console. Now tell me\n\t\tthe value of the fifth element of data:\n\t\t\"\"\",\n\t\t\"data[5]\",\n\t\tx -> x==0x20\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tThis hex code represents a character. Can you convert the code to\n\t\ta character?\n\t\t\"\"\",\n\t\t\"Char(data[5])\",\n\t\tx -> x==' '\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can even convert the data entirely to a String like this:\n\n\t\t\tstr = String(data)\n\n\t\tHowever, this conversion uses up the data values. What value is\n\t\tnow returned by the function call isempty(data)?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tFinally, we must always close a filestream after we have finished\n\t\twith it: close(file).\n\t\tAlso, we should clean up afterwards, so now remove the file we have\n\t\tcreated using rm(\"my_data.txt\"), and tell me the return type of rm():\n\t\t\"\"\",\n\t\t\"First call rm(), and then ask: typeof(ans)\",\n\t\tx -> x==Nothing\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNow we investigate DateTimes in Julia. Support for date and time\n\t\thandling is provided by the Dates package, which we must first load:\n\n\t\t\tusing Dates\n\n\t\tWe can access the current time using the now() function:\n\n\t\t\tdatim = Dates.now()\n\n\t\tWhat is the type of datim?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==Main.DateTime\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tTo create a new date, we pass year, month and day to the constructor:\n\n\t\t\tDate( 1996, 7, 16)\n\t\t\tDate( 2020, 6)\n\n\t\tWhat Date value is constructed by the call Date(2022)?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==Main.Date(2022)\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWe can also create times. Use the minute() function to find the number\n\t\tof minutes past the hour in this time:\n\n\t\t\tDateTime(1992,10,13,6,18)\n\t\t\"\"\",\n\t\t\"minute(ans)\",\n\t\tx -> x==Main.minute(Main.DateTime(1992,10,13,6,18))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tThe module Dates also makes available Periods of time. Use the subtypes()\n\t\tfunction to find the subtypes of Period and also the subtypes of these\n\t\tsubtypes. How many subtypes does the type TimePeriod have?\n\t\t\"\"\",\n\t\t\"subtypes(TimePeriod)\",\n\t\tx -> x==length(Main.subtypes(Main.TimePeriod))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tHowever, we don't just want to construct dates and times - we usually\n\t\twant to PARSE (i.e., analyse) them. We can construct a Date from a\n\t\tString by passing a DateTime format argument:\n\n\t\t\tDate(\"19760915\",\"yyyymmdd\")\n\n\t\tFor DateTimes, this format gets a little more complicated, so you may\n\t\twish to define your own format:\n\n\t\t\tformat = DateFormat(\"HH:MM, dd.mm.yyyy\")\n\n\t\tUse this format to parse the DateTime \"06:18, 13.10.1992\". What\n\t\tcharacter separates the date from the time in the result?\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x=='T'\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tDateTimes contains many useful functions that you can look up at\n\t\tdocs.julialang.org. For example, use the function dayname() to find\n\t\tout the day on which you were born ...\n\n\t\tWhen you've finished experimenting, just enter reply() to move on\n\t\tto the next activity.\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tFind out your age in days by subtracting your birthday Date from\n\t\ttoday(), then move on with reply():\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> true\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tForm a list of the past 8 days by collecting this Range into a Vector:\n\n\t\t\ttoday()-Week(1):Day(1):today()\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==Main.eval(:(collect((today()-Week(1)):Day(1):today())))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tNext we'll look at a very important tool of data science: Random numbers.\n\t\tFirst load the functions that we'll be using:\n\n\t\t\tusing Random: rand, randn, seed!\n\n\t\tBy itself, the rand() function returns a pseudo-random Float64 number in the\n\t\thalf-open interval [0.0,1.0). Try this now.\n\t\t\n\t\tIf you pass rand() a range as its first argument, it returns a random element\n\t\tfrom that range. If you pass it a tuple of integers, it returns an array with\n\t\tthe size specified by those integers. Use rand() to produce a (2,3) array of\n\t\tinteger values between -1 and +1:\n\t\t\"\"\",\n\t\t\"rand(Range,Size)\",\n\t\tx -> (typeof(x) <: Matrix{Int}) && size(x) == (2,3) && all(map(y->in(y,-1:1),x))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\trandn() works just the same as rand(), but returns normally distributed values\n\t\twith mean 0.0 and standard deviation 1.0. Create a (5,7) array of such normally\n\t\tdistributed numbers:\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> size(x) == (5,7) && sum(x)/length(x) < 0.5\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tWhen we perform simulations with random numbers, we never know in advance how\n\t\tour program will behave. On the one hand, this is certainly good, because many\n\t\tbiological processes are essentially random. On the other hand, it can be very\n\t\tfrustrating if you observe some special problem or phenomenon, because you may\n\t\tnever again be able to reproduce that special situation. Because of this, we\n\t\tneed to be able to make random-number generation REPRODUCIBLE. We do this by\n\t\tSEEDING the random-number generator (rng).\n\n\t\tTo do this, we use the function seed!() at the beginning of our program to make\n\t\tsure all random numbers follow an identical pattern across separate runs of the\n\t\tprogram. Run the following code several times, then tell me what result you get:\n\n\t\t\tseed!(123); rand(5)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> x==(Main.seed!(123); Main.rand(5))\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tOK, and fi-inally at the end of this very long (phew!) laboratory, we look\n\t\tbriefly at how to download resources from the internet. First, we load the\n\t\tdownload() function from the package Downloads:\n\n\t\t\tusing Downloads: download\n\n\t\tNext we define the url of our resource:\n\t\t\n\t\t\turl = \"https://raw.githubusercontent.com/NiallPalfreyman/Ingolstadt.jl/main/src/Ingolstadt.jl\"\n\n\t\tNext, we download this page into a local file:\n\n\t\t\tfile = download(url)\n\t\t\n\t\tUse readlines() (don't forget the ';'!) to discover the Date on which Niall\n\t\tPalfreyman started writing the Ingolstadt project:\n\t\t\"\"\",\n\t\t\"data = readlines(file);\",\n\t\tx -> x == Main.Date(\"7/12/2021\",\"d/mm/yyyy\")\n\t),\n\tActivity(\n\t\t\"\"\"\n\t\tOK, that's the end of this laboratory. The resource we have downloaded is my\n\t\tsource code - feel free to explore it and use it as much as you like. Bye! :-)\n\t\t\"\"\",\n\t\t\"\",\n\t\tx -> true\n\t),\n]", "meta": {"hexsha": "6ed621658f58d62d0bb254af8086d0f33c1e6bc5", "size": 13398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Labs/INLab004.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/INLab004.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/INLab004.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": 28.8129032258, "max_line_length": 97, "alphanum_fraction": 0.6605463502, "num_tokens": 3826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.7843431034072855}}
{"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": "## sigmoidal functions\n\nexport logistic, logistic_prime\n\nlogistic(x) = 1/(1 + exp(-x))\nlogistic_prime(x) = exp(-x)/(1 + exp(-x))^2   ", "meta": {"hexsha": "8fe8daa3aaf272f90d451ef3ba37cc311e5e451a", "size": 133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "JuliaPackageMirrors/SigmoidalProgramming.jl", "max_stars_repo_head_hexsha": "3a2ad969bb90b5a247c23d07168215de4d8e3f7d", "max_stars_repo_licenses": ["MIT"], "max_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": "JuliaPackageMirrors/SigmoidalProgramming.jl", "max_issues_repo_head_hexsha": "3a2ad969bb90b5a247c23d07168215de4d8e3f7d", "max_issues_repo_licenses": ["MIT"], "max_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": "JuliaPackageMirrors/SigmoidalProgramming.jl", "max_forks_repo_head_hexsha": "3a2ad969bb90b5a247c23d07168215de4d8e3f7d", "max_forks_repo_licenses": ["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": 46, "alphanum_fraction": 0.6466165414, "num_tokens": 43, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7843413515654167}}
{"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 \u2208 (0,1)\n# Here a0(x)=1, a1(x)=0, f(x)=4*\u03c0^2*sin(2*\u03c0*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*\u03c0^2)*sin(2*\u03c0*x)\nexact_sol(x) = sin(2*\u03c0*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\u03bb = 45.0                            # Conductivity\r\nc = 460.0                           # Specific heat capacitivity\r\n\u03c1 = 7800.0                          # Material density\r\nL = 0.1                             #Length and width of body are assumed equivalent\r\n\u03b1 = \u03bb / (c*\u03c1)                       # Diffusivity\r\nN = 11                              # Number of Discretization points N_x = N_y\r\nh = L / (N - 1)                     #\u0394x = \u0394y = h\r\n\r\n\r\n#System , input and output matrices: \u03b8' = A\u03b8(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 *= \u03b1 / (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 * \u03c1 * h));\r\n#y(t) = C\u03b8(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 \u0394t\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,\u03b8[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\u03b8init = 273.0                           #initial temperature of the body\r\n\u03b8ref = 500.0                            #Reference temperature\r\n\r\n@constraint(mod, \u03b8[:,1] .== \u03b8init)      #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,\u03b8[i,k + 1] .==  \u03b8[i,k] + dt * ((A[:,i]' * \u03b8[:,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] *(\u03b8ref - \u03b8[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_\u03b8start1 = zeros(steps)\r\nstates_\u03b8start2 = zeros(steps)\r\nstates_\u03b8start3 = zeros(steps)\r\nstates_\u03b8end3 = zeros(steps)\r\nstates_\u03b8end2 = zeros(steps)\r\nstates_\u03b8end1 = 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_\u03b8start1[i] = JuMP.value(\u03b8[1,i])\r\n    states_\u03b8start2[i] = JuMP.value(\u03b8[6,i])\r\n    states_\u03b8start3[i] = JuMP.value(\u03b8[11,i])\r\n    states_\u03b8end3[i] = JuMP.value(\u03b8[115,i])\r\n    states_\u03b8end2[i] = JuMP.value(\u03b8[85,i])\r\n    states_\u03b8end1[i] = JuMP.value(\u03b8[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_\u03b8end3[end] = JuMP.value(\u03b8[end,end])\r\nstates_\u03b8end2[end] = JuMP.value(\u03b8[end-5,end])\r\nstates_\u03b8end1[end] = JuMP.value(\u03b8[end-10,end])\r\nstates_\u03b8start1[end] = JuMP.value(\u03b8[1,end])\r\nstates_\u03b8start2[end] = JuMP.value(\u03b8[6,end])\r\nstates_\u03b8start3[end] = JuMP.value(\u03b8[11,end])\r\n#Plotting temperatures at the input nodes\r\np2 = plot(states_\u03b8start1, label = \"\u03b8_in1\",legend = false)\r\np2 = plot!(states_\u03b8start2,label = \"\u03b8_in2\",legend = false)\r\np2 = plot!(states_\u03b8start3,label = \"\u03b8_in3\",legend = false)\r\nsavefig(\"lq_optimal_2D.png\")\r\n#Plotting temperatures at the output\r\np1 = plot(states_\u03b8end3,label = \"output-3\",legend = false)\r\np1 = plot!(states_\u03b8end2,label = \"output-2\",legend = false)\r\np1 = plot!(states_\u03b8end1,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 * \u221axc - 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    \u03bb::AbstractVector{T}\n    t::T\n    proj::Projection{T}\n    component::Vector{Int}\n\n    LEM{T}(k::Int, \u03bb::AbstractVector{T}, t::T, proj::Projection{T})  where T = new(k, \u03bb, t, proj)\n    LEM{T}(k::Int, \u03bb::AbstractVector{T}, t::Float64, proj::Projection{T}, cc::Vector{Int})  where T = new(k, \u03bb, t, proj, cc)\nend\n\n## properties\noutdim(R::LEM) = size(R.proj, 1)\neigvals(R::LEM) = R.\u03bb\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    \u03bb, V = decompose(L, D, maxoutdim)\n    return LEM{T}(k, \u03bb, 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": "\nprintln(\"*******************************************************\")\n@testset \"qmr\" begin\n\t@testset \"real matrix\" begin\n\t\tA  = sprandn(100,100,.1)\n\t\tA  = A + SparseMatrixCSC(100.0I, 100, 100)\n\t\tn  = size(A,2)\n\t\tD  = diag(A)\n\t\tM2 = x -> Vector(D.\\x)\n\t\trhs = randn(100)\n\t\ttol = 1e-2;\n\t\t\n\t\t# test printing and behaviour for early stopping\n\t\txtt = qmr(A,rhs,tol=1e-12,maxIter=3,out=2)\n\t\t@test xtt[2]==-1\n\t\t\n\t\t# test behaviour for zero rhs\n\t\txtt = qmr(A,0*rhs,tol=tol,maxIter=10,out=2)\n\t\t@test xtt[2]==-9\n\t\t@test all(xtt[1].==0)\n\t\t@test length(xtt[1])==100\n\t\t@test eltype(xtt[1])==eltype(rhs)\n\n\t\t\n\t\tx1 = qmr(A,rhs ,tol=tol,maxIter=100,out=1)\n\t\tx3 = qmr(A,rhs,tol=tol,maxIter=100,x=randn(size(rhs)))\n\t\tx4 = qmr(A,rhs,tol=tol,maxIter=100,M=M2)\n\t\t\n\t\t@test norm(A*x1[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(A*x3[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(A*x4[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(x3[1]-x1[1])/norm(x1[1]) < 1e-2\n\tend\n\n\t@testset \"complex matrix\" begin\n\t\tA = sprandn(100,100,.1) + 1im*(sprandn(100,100,.1));\n\t\tA  = A + SparseMatrixCSC(100.0I, 100, 100)\n\t\tD  = Vector(diag(A))\n\t\tM3 = x -> x./D\n\t\trhs = complex(randn(100))\n\t\ttol = 1e-3;\n\t\t\n\t\t# test behaviour for zero rhs\n\n\t\txtt = qmr(A,0.0*rhs,tol=tol,maxIter=10,out=2)\n\t\t# @test xtt[2]==-9\n\t\t# @test all(xtt[1].==0)\n\t\t# @test length(xtt[1])==100\n\t\t# @test eltype(xtt[1])==eltype(rhs)\n\t\t\n\t\t\n\t\tx1 = qmr(A,rhs,tol=tol,maxIter=100)\n\t\tx3 = qmr(A,rhs,tol=tol,maxIter=100,x=randn(size(rhs)))\n\t\tx4 = qmr(A,rhs,tol=tol,maxIter=100,M=M3)\n\t\t\n\t\t@test norm(A*x1[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(A*x3[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(x3[1]-x1[1])/norm(x1[1]) < 1e-2\n\tend\nend", "meta": {"hexsha": "1a8e3e83ad333294140ccf66eb254158c7813852", "size": 1614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testQMR.jl", "max_stars_repo_name": "JuliaInv/KrylovMethods.jl", "max_stars_repo_head_hexsha": "930b67d2f7299858dfdbac9f193c144a6627d4e1", "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": "test/testQMR.jl", "max_issues_repo_name": "JuliaInv/KrylovMethods.jl", "max_issues_repo_head_hexsha": "930b67d2f7299858dfdbac9f193c144a6627d4e1", "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": "test/testQMR.jl", "max_forks_repo_name": "JuliaInv/KrylovMethods.jl", "max_forks_repo_head_hexsha": "930b67d2f7299858dfdbac9f193c144a6627d4e1", "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": 26.9, "max_line_length": 66, "alphanum_fraction": 0.5755885998, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7843020045456836}}
{"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 < -\u03c0/2\n            x = -\u03c0/2 + abs(x+\u03c0/2);\n            return -cos_taylor(x);\n        elseif \u03c0/2 < x\n            x = \u03c0/2 - abs(x-\u03c0/2);\n            return -cos_taylor(x)\n        else\n            return cos_taylor(x)\n        end\nend\n\nx = LinRange(-\u03c0, \u03c0, 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 -\u03c0 =< sample < \u03c0 range.\n\"\"\"\nfunction wrap_phase( sample::Float64 )\n    while \u03c0 <= sample\n        sample = sample - 2\u03c0;\n    end\n    while sample < -\u03c0\n        sample = sample + 2\u03c0;\n    end\n    return sample;\nend\n\n# Frequency domain analysis\nx = LinRange(0, 1024\u03c0, 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": "#using TensorToolbox, Test, LinearAlgebra\n\nT1=dimtree([8,9,5,6,7])\nT2=dimtree([2,4,6,8,9])\nT3=dimtree(7)\n\nX=float(reshape(collect(1:32),(2,2,2,2,2)))\nprintln(\"\\n\\nTesting truncation of tensor X of size \",size(X),\" to htensor.\")\nH1=htrunc(X,T1);\nerr=norm(full(H1)-X)\nprintln(\"norm(full(H)-X) = \",err)\n@test err \u2248 0 atol=1e-10\n\nH2=htrunc(X,T2)\nerr=norm(full(H2)-X)\nprintln(\"norm(full(H)-X) = \",err)\n@test err \u2248 0 atol=1e-10\n\nY=float(reshape(collect(1:2^7),(2,2,2,2,2,2,2)));\nH3=htrunc(Y,T3);\n@test norm(full(H3)-Y) \u2248 0 atol=1e-10\n\nX=rand(5,4,3,2,4,2);\nH=htrunc(X,dimtree(ndims(X)),maxrank=20);\n@test norm(full(H)-X) \u2248 0 atol=1e-10\n\nprintln(\"\\n\\n...Testing size of htensor H : \", size(H))\n@test size(H) == size(X)\nprintln(\"\\n...Testing ndims of htensor H : \", ndims(H))\n@test ndims(H) == ndims(X)\n\n\nA=MatrixCell(undef,ndims(H))\nfor n=1:ndims(H)\n  A[n]=rand(rand(1:10),size(H,n))\nend\nerr=norm(full(ttm(H,A)) - ttm(full(H),A))\nprintln(\"\\n...Testing ttm for ttensor H and array of matrices A : norm(full(ttm(H,A))-ttm(full(H),A)) = \", err)\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n\\n...Testing norm of htensor H.\")\nerr=abs(norm(H) - norm(full(H)))\nprintln(\"|norm(H) - norm(full(H))| = \", err)\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n\\n...Testing scalar multiplication 3*H.\")\nerr=norm(full(3*H) - 3*full(H))\nprintln(\"norm(full(3*H) - 3*full(H)) = \", err )\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n\\nTesting functions plus and minus for htensors H1 and H2.\")\nT=dimtree(3)\nH1=htrunc(rand(5,4,3),T)\nH2=htrunc(rand(5,4,3),T)\nH=H1+H2\nF=full(H1)+full(H2);\nerr=norm(full(H) - F)\nprintln(\"norm(full(H1+H2) - (full(H1)+full(H2))) = \",err )\n@test err \u2248 0 atol=1e-10\nH=H1-H2\nF=full(H1)-full(H2);\nerr=norm(full(H) - F)\nprintln(\"norm(full(H1+H2) - (full(H1)+full(H2))) = \",err )\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n\\n...Testing inner product.\")\nH=innerprod(H1,H2)\nerr=abs(H - innerprod(full(H1),full(H2)))\nprintln(\"|innerprod(H1,H2) - innerprod(full(H1),full(H2))| = \",err )\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n\\nTesting function dropdims for squeezed tensor X and squeezed htensor Y.\")\nX=rand(1,2,4,3,2)\nH=htrunc(X)\nY=dropdims(H)\nerr = norm(full(Y)-dropdims(X,dims=1))\nprintln(\"norm(full(Y)-dropdims(X,dims=1)) = \",err)\n@test err \u2248 0 atol=1e-10\nX=rand(2,1,4,3,2)\nH=htrunc(X)\nY=dropdims(H)\nerr = norm(full(Y)-dropdims(X,dims=2))\nprintln(\"norm(full(Y)-dropdims(X,dims=2)) = \",err)\n@test err \u2248 0 atol=1e-10\nX=rand(2,4,1,3,2)\nH=htrunc(X)\nY=dropdims(H)\nerr = norm(full(Y)-dropdims(X,dims=3))\nprintln(\"norm(full(Y)-dropdims(X,dims=3)) = \",err)\n@test err \u2248 0 atol=1e-10\nX=rand(2,4,3,1,2)\nH=htrunc(X)\nY=dropdims(H)\nerr = norm(full(Y)-dropdims(X,dims=4))\nprintln(\"norm(full(Y)-dropdims(X,dims=4)) = \",err)\n@test err \u2248 0 atol=1e-10\nX=rand(2,4,3,2,1)\nH=htrunc(X)\nY=dropdims(H)\nerr = norm(full(Y)-dropdims(X,dims=5))\nprintln(\"norm(full(Y)-dropdims(X,dims=5)) = \",err)\n@test err \u2248 0 atol=1e-10\n\nH=randhtensor([4,5,2])\nprintln(\"\\n\\n...Testing reorthogonalization for random htensor H of size \", size(H),\".\")\nprintln(\"Has orthogonal factor matrices: \", H.isorth)\nprintln(\"After reorthogonalization: \", reorth!(H).isorth)\n@test H.isorth\n\nH=htrunc(rand(5,5,5),dimtree(3),maxrank=2);\nprintln(\"Testing hrank: \",hrank(H))\n@test hrank(H)==[1, 2, 2, 2, 2]\n", "meta": {"hexsha": "405431a1bc7e402815774f61a490b12fce090390", "size": 3206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/htensorTest.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/TensorToolbox.jl-9c690861-8ade-587a-897e-15364bc6f718", "max_stars_repo_head_hexsha": "969a1a9f20b236fbd90dd47d8d01679ee75afe56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2017-05-25T14:02:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:46:13.000Z", "max_issues_repo_path": "test/htensorTest.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/TensorToolbox.jl-9c690861-8ade-587a-897e-15364bc6f718", "max_issues_repo_head_hexsha": "969a1a9f20b236fbd90dd47d8d01679ee75afe56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-08-04T00:20:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T20:05:19.000Z", "max_forks_repo_path": "test/htensorTest.jl", "max_forks_repo_name": "bovine3dom/TensorToolbox.jl", "max_forks_repo_head_hexsha": "fe96333d5d6ce4a03150f10f2ef5f191954b8efb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-05-25T10:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-10T12:18:38.000Z", "avg_line_length": 28.3716814159, "max_line_length": 111, "alphanum_fraction": 0.6494073612, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8539127492339907, "lm_q1q2_score": 0.784301992198179}}
{"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) \u2248 0.014566189535134827 &&\n        main(unknown_storage=:dense) \u2248 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": "@testset \"Quaternions\" begin\n\n    qx = qrotation(Vec(1, 0, 0), pi / 4)\n    @test qx * qx \u2248 qrotation(SVector(1.0, 0.0, 0.0), pi / 2)\n    @test Base.power_by_squaring(qx, 2) \u2248 qrotation(SVector(1.0, 0.0, 0.0), pi / 2)\n    theta = pi / 8\n    qx = qrotation(SVector(1.0, 0.0, 0.0), theta)\n    c = cos(theta); s = sin(theta)\n    Rx = [1 0 0; 0 c -s; 0 s c]\n\n    @test Mat3f0(qx) \u2248 Rx\n    theta = pi / 6\n    qy = qrotation(SVector(0.0, 1.0, 0.0), theta)\n    c = cos(theta); s = sin(theta)\n    Ry = [c 0 s; 0 1 0; -s 0 c]\n    @test Mat3f0(qy) \u2248 Ry\n    theta = 4pi / 3\n    qz = qrotation(SVector(0.0, 0.0, 1.0), theta)\n    c = cos(theta); s = sin(theta)\n    Rz = [c -s 0; s c 0; 0 0 1]\n    @test Mat3f0(qz) \u2248 Rz\n\n    @test Mat3f0(qx * qy * qz) \u2248 Rx * Ry * Rz\n    @test Mat3f0(qy * qx * qz) \u2248 Ry * Rx * Rz\n    @test Mat3f0(qz * qx * qy) \u2248 Rz * Rx * Ry\n\n    a, b = qrotation(SVector(0.0, 0.0, 1.0), deg2rad(0)), qrotation(SVector(0.0, 0.0, 1.0), deg2rad(180))\n    # @test slerp(a, b, 0.0) \u2248 a\n    # @test slerp(a, b, 1.0) \u2248 b\n    # @test slerp(a, b, 0.5) \u2248 qrotation([0, 0, 1], deg2rad(90))\n    #\n    # @test angle(qrotation(SVector(1.0, 0.0, 0.0), 0)) \u2248 0\n    # @test angle(qrotation([0, 1, 0], pi / 4)) \u2248 pi / 4\n    # @test angle(qrotation([0, 0, 1], pi / 2)) \u2248 pi / 2\n    #\n    # let # test numerical stability of angle\n    #     ax = randn(3)\n    #     for \u03b8 in [1e-9, \u03c0 - 1e-9]\n    #         q = qrotation(ax, \u03b8)\n    #         @test angle(q) \u2248 \u03b8\n    #     end\n    # end\nend\n", "meta": {"hexsha": "869081adbd7948b5a6d76380148e3dbd8f516ecd", "size": 1470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/quaternions.jl", "max_stars_repo_name": "blegat/AbstractPlotting.jl", "max_stars_repo_head_hexsha": "9a18377da7ffae21b6193de802a065924e2d02c2", "max_stars_repo_licenses": ["MIT"], "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/quaternions.jl", "max_issues_repo_name": "blegat/AbstractPlotting.jl", "max_issues_repo_head_hexsha": "9a18377da7ffae21b6193de802a065924e2d02c2", "max_issues_repo_licenses": ["MIT"], "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/quaternions.jl", "max_forks_repo_name": "blegat/AbstractPlotting.jl", "max_forks_repo_head_hexsha": "9a18377da7ffae21b6193de802a065924e2d02c2", "max_forks_repo_licenses": ["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.4090909091, "max_line_length": 105, "alphanum_fraction": 0.5, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7842510193661973}}
{"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(\u03c9, \u03be, \u03c3)\n\nCalculate the Fourier transform of a gabor wavelet.\n\n# Arguments\n - `\u03c9::Vector{Float64}`: Frequencies over which to calculate the filter.\n - `\u03c3::Float64`: Bandwidth of the filter\n - `\u03be::Float64`: Central frequency\n\"\"\"\nfunction gabor1d(\u03c9::Vector{Float64}, \u03c3::Float64, \u03be::Float64)\n    return exp.(-(\u03c9.-\u03be).^2 ./ (2*\u03c3^2))\nend\n\"\"\"\n    gabor1d(N, \u03be, \u03c3)\n\nConvenience method for calculating the Fourier transform of a gabor wavelet.\n\n# Arguments\n - `\u03c9::Vector{Float64}`: Frequencies over which to calculate the filter.\n - `\u03c3::Float64`: Bandwidth of the filter\n - `\u03be::Float64`: Central frequency\n\"\"\"\nfunction gabor1d(N::Int64, \u03c3::Float64, \u03be::Float64)\n    \u03c9 = FFTW.fftfreq(N)\n    return gabor1d(\u03c9[:], \u03c3, \u03be)\nend\n\n\"\"\"\n    gauss1d(\u03c9, \u03c3)\n\nReturn a Fourier transformed Gaussian lowpass filter.\n\n# Arguments\n - `\u03c9::Vector{Float64}`: Frequencies over which to calculate the filter.\n - `\u03c3::Float64`: Bandwidth of lowpass filter.\n\"\"\"\nfunction gauss1d(\u03c9::Vector{Float64}, \u03c3::Float64)\n    return exp.(-(\u03c9.^2)./(2*\u03c3^2))\nend\n\"\"\"\n    gauss1d(N, \u03c3)\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 - `\u03c3::Float64`: Bandwidth of the lowpass filter.\n\"\"\"\nfunction gauss1d(N::Int64, \u03c3::Float64)\n    \u03c9 = collect(0.0:N-1)./N\n    return gauss1d(\u03c9[:], \u03c3)\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    \u03ba = gab[1]/lowpass[1]\n    return gab .- \u03ba.*lowpass\nend\n\"\"\"\n    morlet1d(N, \u03be, \u03c3)\n\nCalculate the Fourier transform of a Morlet wavelet.\n\n# Arguments\n - `N::Int64`: Length of filter in the time domain.\n - `\u03c3::Float64`: Bandwidth of the lowpass filter.\n - `\u03be::Float64`: Central frequency.\n\"\"\"\nfunction morlet1d(N::Int64, \u03c3::Float64, \u03be::Float64)\n    gab = gabor1d(N, \u03c3, \u03be)\n    lowpass = gauss1d(N, \u03c3)\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 | :\u03c3        | Filter Bandwidth |\n | :\u03d5        | Fourier-transformed Gaussian lowpass filter |\n\"\"\"\nstruct GaussianFilter <: AbstractFilter\n    \u03c3::Float64 # filter bandwidth\n\n    \u03d5::Vector{Float64} # Fourier-transformed lowpass Gaussian filter\n\n    function GaussianFilter(N::Int64, \u03c3::Float64)\n        \u03d5 = gauss1d(N, \u03c3)\n        return new(\u03c3, \u03d5)\n    end\nend\n\n\"\"\"\n    GaborWavelet\n\nA structure for Fourier transformed Gabor Wavelets\n\n## Fields: GaborWavelet\n | **Field** | **Description** |\n |:----------|:----------------|\n | :\u03c3        | Filter Bandwidth |\n | :\u03be        | Central Frequency |\n | :j        | Maximal subsampling |\n | :\u03b3        | Fourier-transformed Gabor wavelet |\n\"\"\"\nstruct GaborWavelet <: AbstractFilter\n    \u03c3::Float64 # filter bandwidth\n    \u03be::Float64 # central frequency\n    j::Int64 # 2^j is the maximal subsampling possible without aliasing\n\n    \u03b3::Vector{Float64} # Fourier-transformed Gabor wavelet\n\n    function GaborWavelet(N::Int64, \u03c3::Float64, \u03be::Float64, j::Int64)\n        \u03b3 = gabor1d(N, \u03c3, \u03be)\n        return new(\u03c3, \u03be, j, \u03b3)\n    end\nend\n\n\"\"\"\n    MorletWavelet\n\nA structure for Fourier transformed Morlet Wavelets\n\n## Fields: MorletWavelet\n | **Field** | **Description** |\n |:----------|:----------------|\n | :\u03c3        | Filter Bandwidth |\n | :\u03be        | Central Frequency |\n | :j        | Maximal subsampling |\n | :\u03c8        | Fourier-transformed Morlet wavelet |\n\"\"\"\nstruct MorletWavelet <: AbstractFilter\n    \u03c3::Float64 # filter bandwidth\n    \u03be::Float64 # central frequency\n    j::Int64 # 2^j is the maximal subsampling possible without aliasing\n\n    \u03c8::Vector{Float64} # Fourier-transformed Morlet wavelet\n\n    function MorletWavelet(N::Int64, \u03c3::Float64, \u03be::Float64, j::Int64)\n        \u03c8 = morlet1d(N, \u03c3, \u03be)\n        return new(\u03c3, \u03be, j, \u03c8)\n    end\n    function MorletWavelet(\u03b3::GaborWavelet, \u03d5::GaussianFilter)\n        \u03c8 = morlet1d(\u03b3.\u03b3, \u03d5.\u03d5)\n        return new(\u03b3.\u03c3, \u03b3.\u03be, \u03b3.j, \u03c8)\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": "#transform tests\n\n# test Parseval's theorem for wavefunctions\nfunction parsevaltest(L,N)\n    X,K,dX,dK = makearrays(L,N)\n    T = makeT(X,K)\n\n    \u03c8 = randn(N...) + im*randn(N...)\n\n    n1 = sum(abs2.(\u03c8))*prod(dX)\n    \u03d5 = T.Txk*\u03c8\n\n    n2 = sum(abs2.(\u03d5))*prod(dK)\n    return n1,n2\nend\n\nL = (88.,)\nN = (128,)\n# X,K,dX,dK = makearrays(L,N)\n# T = makeT(X,K) # TODO: norm problem in makeT for 2,3 dims\n\nn1,n2 = parsevaltest(L,N)\n@test n1 \u2248 n2\n\n## debug offending test\nL = (30.,20.)\nN = (30,34)\n\n# X,K,dX,dK = makearrays(L,N)\n# T = makeT(X,K) # TODO: norm problem in makeT for 2,3 dims\n\n# \u03c8 = randn(N...) + im*randn(N...)\n\n# n1 = sum(abs2.(\u03c8))*prod(dX)\n# \u03d5 = T.Txk*\u03c8\n\n# n2 = sum(abs2.(\u03d5))*prod(dK)\n\nn1,n2 = parsevaltest(L,N)\n@test n1 \u2248 n2\n\nL = (30.,20.,10)\nN = (30,34,24)\nn1,n2 = parsevaltest(L,N)\n@test n1 \u2248 n2\n\nL = (30.,20.,10,50.)\nN = (30,34,24,22)\nn1,n2 = parsevaltest(L,N)\n@test n1 \u2248 n2\n", "meta": {"hexsha": "a03f6ba52c83e624f12d651b962cfdfc1fc041c0", "size": 883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_parseval.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": "test/test_parseval.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": "test/test_parseval.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": 17.3137254902, "max_line_length": 59, "alphanum_fraction": 0.5685164213, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7842510100226893}}
{"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\u03b8avg, cos\u03b8Zavg, 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 \u03b4 of the day `n`, in radians.\n\n\u03b4 is the angle between the Sun-Earth direction and the equatorial plane.\nIt varies between \u221223.45\u00b0 on December 21-22 and +23.45\u00b0 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> \u03b4 = declination(n)\n0.40924559967108437\n\njulia> round(rad2deg(\u03b4); 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\u03c0*(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\u03c0*(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 \u03c9 (in rad) a civil hour `tc` on day `n`, at longitude `lon` (\u00b0). \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 \u00e0 son point culminant de la journ\u00e9e, est n\u00e9gatif avant ce point et positif apr\u00e8s 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, \u03c9, lon)\n\nCompute the civil hour `tc` of an hour angle of the Sun `\u03c9` (in rad) on day `n`,\nat longitude `lon` (\u00b0). \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, \u03c9, lon) = \u03c9/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\u00b0]) and `azimuth` (in [-90\u00b0, 90\u00b0])\nand is located at latitude `lat` (\u00b0).\n\nReturn `\u03c9u`, `\u03c9d` (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 \u03b8 the angle of incidence of the Sun on the panel,\nthis means that cos\u03b8=0 at hour angle `\u03c9u` and `\u03c9d` and cos\u03b8 \u2265 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\u03b4=sin(delta)\n    cos\u03b4=cos(delta)\n    sin\u03d5=sin(phi) \n    cos\u03d5=cos(phi)\n    cos\u03b2=cos(beta)\n    sin\u03b2=sin(beta)\n    cos\u03b3=cos(gamma)\n    \n    A = sin\u03b4*sin\u03d5*cos\u03b2 - sin\u03b4*cos\u03d5*sin\u03b2*cos\u03b3\n    B = cos\u03b4*cos\u03d5*cos\u03b2 + cos\u03b4*sin\u03d5*sin\u03b2*cos\u03b3\n    C = cos\u03b4*sin\u03b2*sin(gamma)\n\n    D = C^2+B^2-A^2\n    E = A-B\n    if D >= 0\n        \u03c9u = 2*atan((-C+sqrt(D))/E)\n        \u03c9d = 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        \u03c9u = 0.0\n        \u03c9d = 0.0\n    end\n    \n    return \u03c9u, \u03c9d\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` (\u00b0).\n\nReturn `\u03c9u`, `\u03c9d` (in rad) which are respectively the hour angles of sunrise and sunset.\n\nMathematically, with \u03b8z the solar zenith angle (angle of incidence of the Sun on the ground),\nthis means that cos\u03b8z=0 at hour angle `\u03c9u` and `\u03c9d` and cos\u03b8z \u2265 0 in between.\n\"\"\"\nfunction day_bounds(n, lat)\n    phi=deg2rad(lat)\n    \n    # Sunset\n    \u03c9d = acos(-tan(phi)*tan(declination(n)))\n    # Sunrise\n    \u03c9u = -\u03c9d\n    \n    return \u03c9u, \u03c9d\nend\n\n\n\"\"\"\n    cos\u03b8avg(n, tcini, dt, slope, azimuth, lat, lon)\n\nCosine of \u03b8, the angle of incidence of the sun on a tilted panel.\n\nPanel has orientation (`slope`, `azimuth` \u00b0) and is located at (`lon`, `lat` \u00b0).\nValue is computed on day `n`, averaged on a time interval `dt`\nstarting at civil hour `tcini`.\n\nSee also: [`cos\u03b8Zavg`](@ref) for the incidence on the _ground_.\n\"\"\"\nfunction cos\u03b8avg(n, tcini, dt, slope, azimuth, lat, lon)\n    beta=deg2rad(slope)\n    gamma=deg2rad(azimuth)\n    phi=deg2rad(lat)\n    \n    \u03c91=hour_angle(n, tcini, lon)\n    \u03c92=hour_angle(n, tcini+dt, lon)\n    \n    \u03c9up, \u03c9down = day_bounds(n, slope, azimuth, lat)\n    \n    if \u03c91<\u03c9up && \u03c92<\u03c9up\n        return 0.0\n    elseif \u03c91>\u03c9down && \u03c92>\u03c9down\n        return 0.0\n    elseif \u03c91<\u03c9up && \u03c92>\u03c9up\n        \u03c91 = \u03c9up\n        tdebut = time_hour_angle(n, \u03c9up, lon)\n        tfin = tcini+dt\n        dt = tfin-tdebut # TODO: check that the change of `dt` is correct\n    elseif \u03c91<\u03c9down && \u03c92>\u03c9down\n        \u03c92 = \u03c9down\n        tdebut = tcini\n        tfin = time_hour_angle(n, \u03c9down, lon)\n        dt = tfin-tdebut # TODO: check that the change of `dt` is correct\n    end\n    \n    delta = declination(n)\n\n    sin\u03b4 = sin(delta)\n    cos\u03b4 = cos(delta)\n    sin\u03d5 = sin(phi)\n    cos\u03d5 = cos(phi)\n    cos\u03b2 = cos(beta)\n    sin\u03b2 = sin(beta)\n    cos\u03b3 = cos(gamma)\n    \n    a = sin\u03b4*sin\u03d5*cos\u03b2 - sin\u03b4*cos\u03d5*sin\u03b2*cos\u03b3\n    b = cos\u03b4*cos\u03d5*cos\u03b2 + cos\u03b4*sin\u03d5*sin\u03b2*cos\u03b3\n    c = cos\u03b4*sin\u03b2*sin(gamma)\n    f = \u03c92 - \u03c91\n    g = sin(\u03c92) - sin(\u03c91)\n    h = cos(\u03c92) - cos(\u03c91)\n    x = (a*f + b*g - c*h)*12/(pi*dt)\n    \n    return x\nend\n\n\"\"\"\n    cos\u03b8Zavg(n, tcini, dt, lat, lon)\n\nCosine of ``\u03b8_Z``, the solar zenith angle, i.e. the angle of incidence of the sun on the ground.\n\nLocation is (`lon`, `lat` \u00b0).\nValue is computed on day `n`, averaged on a time interval `dt`\nstarting at civil hour `tcini`.\n\nSee also: [`cos\u03b8avg`](@ref) for the incidence on a _tilted panel_.\n\"\"\"\nfunction cos\u03b8Zavg(n, tcini, dt, lat, lon)\n    phi=deg2rad(lat)\n    \n    \u03c91=hour_angle(n, tcini, lon)\n    \u03c92=hour_angle(n, tcini+dt, lon)\n    \n    \u03c9up, \u03c9down = day_bounds(n, lat)\n    \n    if \u03c91<\u03c9up && \u03c92<\u03c9up\n        return 0.0\n    elseif \u03c91>\u03c9down && \u03c92>\u03c9down\n        return 0.0\n    elseif \u03c91<\u03c9up && \u03c92>\u03c9up\n        \u03c91 = \u03c9up\n        tdebut = time_hour_angle(n, \u03c9up, lon)\n        tfin = tcini+dt\n        dt = tfin-tdebut # TODO: check that the change of `dt` is correct\n    elseif \u03c91<\u03c9down && \u03c92>\u03c9down\n        \u03c92 = \u03c9down\n        tdebut = tcini\n        tfin = time_hour_angle(n, \u03c9down, 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 = \u03c92 - \u03c91\n    g = sin(\u03c92) - sin(\u03c91)\n    x = (d*g + e*f)*12/(pi*dt)\n    \n    return x\nend\n\n\"\"\"\n    Rb(cos\u03b8, cos\u03b8Z, Rbsat=5)\n\nRb = cos\u03b8/cos\u03b8Z with special care of zeros and saturation at `Rbsat`\n\"\"\"\nfunction Rb(cos\u03b8, cos\u03b8Z, Rbsat=5.)\n    if cos\u03b8==0. || cos\u03b8Z==0.\n        return 0.0\n    else\n        x = cos\u03b8/cos\u03b8Z\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\u00e9 d'un angle `slope`, orient\u00e9 d'un angle `azimuth`, situ\u00e9 \u00e0 une latitude `lat` et une longitude `lon` (\u00b0). Elle le calcule pour un jour n donn\u00e9, sur un intervalle donn\u00e9 de dur\u00e9e dt \u00e0 partir d'un instant initial tcini.\n\n\u26a0\ufe0f Fonction avec encore quelques probl\u00e8mes. Des pics apparaissent dans certaines conditions, une saturation a \u00e9t\u00e9 mise en place afin que ces pics n'impactent pas les calculs utilisant cette fonction. Cette saturation, choisie empiriquement, emp\u00eache le terme de redressement de d\u00e9passer la valeur de 5.\n\"\"\"\nfunction Rb(n, tcini, dt, slope, azimuth, lat, lon, Rbsat=5.)\n    cos\u03b8 = cos\u03b8avg(n, tcini, dt, slope, azimuth, lat, lon)\n    cos\u03b8Z = cos\u03b8Zavg(n, tcini, dt, lat, lon)\n    \n    return Rb(cos\u03b8, cos\u03b8Z, 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\u2013302.\n- `:OH77`: Orgill & Hollands (1977). Correlation equation for hourly diffuse radiation\n  on a horizontal surface. Sol. Energy 19, 357\u2013359.\n- `:CR79`: Collares-Pereira & Rabl (1979), The average distribution of solar radiation\n  \u2014correlations 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    \u03c91 = hour_angle(n, tcini, lon)\n    \u03c92 = hour_angle(n, tcini+dt, lon)\n    \n    # TODO: use the cos\u03b8Zavg function here instead:\n    # Goavg = Gon*cos\u03b8Zavg, I believe\n    a = cos(phi)*cos(delta) * (sin(\u03c92) - sin(\u03c91))\n    b = sin(phi)*sin(delta) * (\u03c92 - \u03c91)\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(\u03b8) and cos(\u03b8z)\n    cos\u03b8 = cos\u03b8avg(n, tcini, dt, slope, azimuth, lat, lon)\n    cos\u03b8Z = cos\u03b8Zavg(n, tcini, dt, lat, lon)\n    RB=Rb(cos\u03b8, cos\u03b8Z)\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\u03b8 <= 0\n            AW = 0.0\n            BW = 1.0115-0.20293*beta-0.080823*beta^2\n        else\n            AW = Gdirect*RB/(1367*cos\u03b8)\n            BW = (1.0115-0.20293*beta-0.080823*beta^2)*(1-(Gdirect/(1367*cos\u03b8)))\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\u03b8Z <= 0\n            CB = cos\u03b8\n        else\n            CB = cos\u03b8 - (1+cos(beta))/(2*cos\u03b8Z)\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\u03b8^2)*(sqrt(1-cos\u03b8Z^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\u03b8^2)*(sqrt(1-cos\u03b8Z^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 \u00e9galement en argument une cha\u00eene de caract\u00e8res `fonctionGHI`, qui permet de choisir l'interpolation des donn\u00e9es du GHI. Cette cha\u00eene de caract\u00e8re peut donc \u00eatre : \"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\u00b2::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\u00b2 = 1 - var(a + b * x - y) / var(y)\n    return a, b, r\u00b2\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": "using ProximalOperators\nusing LinearAlgebra\n\n# Nonsmooth + regularization\n\nmu, lam = 2.0, 3.0\n\nf = NormL1(mu)\ng = Regularize(f, lam)\nh = ElasticNet(mu, lam)\n\nx = randn(10)\n\ngx = call_test(g, x)\nhx = call_test(h, x)\n\n@test abs(gx - hx)/(1+abs(gx)) <= 1e-12\n\nyg, gy = prox_test(g, x, 0.5)\nyh, hy = prox_test(h, x, 0.5)\n\n@test abs(gy - hy)/(1+abs(gy)) <= 1e-12\n@test norm(yg - yh, Inf)/(1+norm(yg, Inf)) <= 1e-12\n\n# Smooth + regularization (test also gradient)\n\nm, n = 10, 20\nlam = 1.5\n\nA = randn(m, n)\nb = randn(m)\n\nf = LeastSquares(A, b)\ng = Regularize(f, lam)\n\nx = randn(n)\nres = A*x-b\n\ngx = call_test(g, x)\n\n@test abs(0.5*norm(res)^2 + (0.5*lam)*norm(x)^2 - gx)/(1+abs(gx)) <= 1e-12\n\nprox_test(g, x, 0.7)\ngrad_gx, gx1 = gradient_test(g, x)\n\n@test abs(gx - gx1)/(1+abs(gx)) <= 1e-12\n@test norm(grad_gx - A'*(A*x - b) - lam*x, Inf)/(1+norm(grad_gx, Inf)) <= 1e-12\n", "meta": {"hexsha": "359c734d92158903863d588fa4a95b4fa9ccee3b", "size": 863, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_regularize.jl", "max_stars_repo_name": "kul-forbes/ProximalOperators.jl", "max_stars_repo_head_hexsha": "fcd3d987f6af7d701cd32c61e6c14594baa6289e", "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": "test/test_regularize.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": "test/test_regularize.jl", "max_forks_repo_name": "kul-forbes/ProximalOperators.jl", "max_forks_repo_head_hexsha": "fcd3d987f6af7d701cd32c61e6c14594baa6289e", "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": 17.9791666667, "max_line_length": 79, "alphanum_fraction": 0.5955967555, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928905, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7841805387486358}}
{"text": "##########################################################\n# Rafa\u0142 Nowak\n#\n# Instytut Informatyki\n# Uniwersytet Wroc\u0142awski\n#\n#\n# Pomocniczne materia\u0142y do wyk\u0142adu z analizy numerycznej\n#\n##########################################################\ntwo = Float32(2.0);\n\nd = 32-1;\nt = 23;\n\n#\n# Obliczanie najwi\u0119kszej liczby dodatniej w arytmetyce Float32\n#\ncmax = 2^(d-t-1)-1; # najwi\u0119ksza cecha\n\nx1 = two^cmax * ( two - two^(-t) )\n@printf(\"najw. dod. liczba w arytm. Float32 = %.1f =\\n\", x1);\n\n# alternatywny spos\u00f3b\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\u0119ksza cecha\ncmin = -2^(d-t-1)+2; # niestety jedna liczba -128 i -127 s\u0105 ju\u017c zarezerwowane na (\u00b1Inf+NaN i Subnorm)\nx1 = two^cmin * two^(-t)\n@printf(\"najm. dod. liczba subnormalna w arytm. Float32 = %.16e\\n\", x1);\n# alternatywny spos\u00f3b\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": "\u03b4(i, j) = Int64(==(i, j))\n\ndiagm(x::Vector) = [\u03b4(i, j)*x[i] for i in 1:length(x), j in 1:length(x)]\n\nI(n) = [\u03b4(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, \u03c4)\n\nconstruct a first-order transfer function with gain `K` and time constant `\u03c4`:\n\n$$g(s)=\\frac{K}{\\tau s+1}$$\n\n# example\n```jldoctest\nK = 1.0\n\u03c4 = 3.0\ng = first_order_system(K, \u03c4)\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, \u03c4::Float64) = K / (\u03c4 * s + 1)\n\n@doc raw\"\"\"\n    g = second_order_system(K, \u03c4, \u03be)\n\nconstruct a second-order transfer function with gain `K`, time constant `\u03c4`, and damping coefficient `\u03be`:\n\n$$g(s)=\\frac{K}{\\tau^2 s^2 + 2\\tau \\xi s +1}$$\n\n# example\n```jldoctest\nK = 1.0\n\u03c4 = 2.0\n\u03be = 0.1\ng = second_order_system(K, \u03c4, \u03be)\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, \u03c4::Float64, \u03be::Float64) = K / (\u03c4^2 * s^2 + 2 * \u03c4 * \u03be * s + 1)\n\n@doc raw\"\"\"\n    \u03c4 = time_constant(g)\n\ncompute the time constant \u03c4 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`\u03c4::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) ==> \u03c4 = 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) ==> \u03c4 = 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    \u03be = damping_coefficient(g)\n\ncompute the damping coefficient \u03be 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`\u03be::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    \u03c4 = time_constant(g)\n    # xx / (a s\u00b2 + b s + c) then 2\u03c4\u03be = b / c\n    \u03c4\u03be2 = g.denominator[1] / g.denominator[0]\n    return \u03c4\u03be2 / (2 * \u03c4)\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) \u2260 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 \u03b2 is the rotation angle from (1,0)\n\tcos\u03b2 = (F2-F1)[1]/norm(F2-F1,2)\n\tsin\u03b2 = sqrt(1.0-cos\u03b2)\n\t\n\tcenter = 0.5*(F1+F2)\n\trng = MersenneTwister(1234)\n\tx = zeros(ntot)\n\ty = zeros(ntot)\n\t\u03b8 = shuffle(rng,[0:(2*\u03c0)/npun:2*\u03c0;])\n\t\n\tfor i=1:p\n\t\tx[i] = center[1]*cos\u03b2+b*cos(\u03b8[i])*cos\u03b2+center[2]*sin\u03b2+a*sin(\u03b8[i])*sin\u03b2\n\t\ty[i] = -center[1]*sin\u03b2 -b*cos(\u03b8[i])*sin\u03b2+center[2]*cos\u03b2+a*sin(\u03b8[i])*cos\u03b2\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\u03b2+bnoise*cos(\u03b8[i])*cos\u03b2+center[2]*sin\u03b2+anoise*sin(\u03b8[i])*sin\u03b2\n\t\ty[i] = -center[1]*sin\u03b2 -bnoise*cos(\u03b8[i])*sin\u03b2+center[2]*cos\u03b2+anoise*sin(\u03b8[i])*cos\u03b2\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 Test, Plots, Parameters\n\nNx = 500\nxm = 10.\nx = LinRange(-xm,xm,Nx); y = x\n\n# create some test data\npsi = @. 10*exp(-.1*(x^2+y'^2)) + 15*exp(-((x-5)^2+y'^2)) # + randn()+im*randn()\nheatmap(x,y,abs2.(psi))\n\nabstract type Basis end\nstruct Oscillator <: Basis\n    \u03c9::Float64\n    n::Int64\nend\nOscillator(n::Int64) = Oscillator(1.0,n)\nfunction (b::Oscillator)(x)\n    @unpack \u03c9,n = b\n    T = x * ones(1, n) |> zero\n    T[:,1] = @. exp(-(\u221a\u03c9 * x)^2 / 2) * (\u03c9 / \u03c0)^(1 / 4)\n    n >= 2 && (T[:,2] = @. sqrt(2 * \u03c9) * x * T[:,1])\n    for j \u2208 index(b)[3:end]\n        m = qnumbers(b)[j]\n        T[:,j] = @. sqrt(2 / m) * (\u221a\u03c9 * x) * T[:,j-1] - sqrt((m-1) / m) * T[:,j-2]\n    end\n    return T\nend\nindex(b::Oscillator) = 1:b.n\nspectrum(b::Oscillator) = (0:b.n-1)*b.\u03c9\nqnumbers(b::Oscillator) = 0:b.n-1\n\nfunction hermite(x,n)\n    @assert n >= 1\n    h1 = exp(-x^2 / 2) * (1 / \u03c0)^(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 \u2208 3:n\n        m = j - 1\n        h3 = sqrt(2/m) * x * h2 - sqrt((m-1)/m) * h1\n        h1 = h2; h2 = h3\n    end\n    n > 2 && (return h3)\nend\nhermite(x,n,\u03c9) = hermite(\u221a\u03c9 * x,n) * \u03c9 ^ ( 1 / 4 )\n\n# test that we can create the basis, or any one of oscillator modes\nNv = 1:20\n@time hermite.(x,Nv')\nplot(x,hermite.(x,Nv'),legend=false,grid=false)\nn = 20\nb1 = Oscillator(n)\n@time b1(x)\nplot(x,b1(x),legend=false,grid=false)\n\nplot(x,hermite.(x,1,[1. .5 .2 .1]))\n\n# filtering cartesian data\nfunction filterH(psi,x,N)\n    H = Oscillator(1.0,N)(x)\n    T = inv(H'*H)\n    F\u0302 = T*H'*psi*H*T\n    psiF = zero(psi)\n        for m = 1:N, n = 1:(N+1-m)\n            @. psiF += H[:,m]*F\u0302[m,n]*H[:,n]'\n        end\n    return psiF\nend\n\nn = 30\npsiF = filterH(psi,x,n)\nheatmap(x,y,abs2.(psiF))\n\n# coversion to polar coords\nfunction polar(psi,x,N)\n    Nx = length(x)\n    H = Oscillator(1.0,N)(x)\n    T = inv(H'*H)\n    F\u0302 = T*H'*psi*H*T\n    r = LinRange(0,last(x),Nx/2 |> Int)\n    \u03b8 = LinRange(0,2*pi,2*Nx)'\n    psiP = zero(r*\u03b8)\n    for m = 1:N, n = 1:(N + 1 - m)\n        @. psiP += hermite(r*cos(\u03b8),n) * F\u0302[m,n] * hermite(r*sin(\u03b8),m)\n    end\n    return psiP\nend\n\nr = LinRange(0,last(x),Nx/2 |> Int)\n\u03b8 = LinRange(0,2*pi,2*Nx)'\npsiP = polar(psi,x,30)\n\n# plot in polar coordinates\nheatmap(\u03b8',r,abs2.(psiP))\nd\u03b8 = \u03b8[2]-\u03b8[1]\ndr = r[2]-r[1]\ndx = x[2]-x[1]\npsiPth = sum(psiP,dims=2)*d\u03b8\nplot(r,psiPth.*r)\n\n# check total integral preserved (< 1%)\nsum(psiPth.*r)*dr\nsum(psiF)*dx^2\n\n# ======== ideas for cfields\n# CField:\n\n#= something like this?\nfunction transform(b::Oscillator)\n    x,w = gausshermite(b.n)\n    T = b(x)\n    return x,w,T\nend\n\nxk,wk,Tk = transform(b1)\nc = randn(n)\nf = Tk*c\n@test sum(@. wk*exp(xk^2)*abs2(f)) \u2248 sum(abs2.(c))\n\nabstract type CField end\nstruct YField{N} <: CField\n    basis::Basis\n    psi::Array{Complex{Float64},N}\nend\n\nf1 = YField(b1,randn(b1.n)+im*randn(b1.n))\n\n=#\n", "meta": {"hexsha": "87a7fb2d099b69fab7713060d75cfd700bd488e2", "size": 2830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_research/polar_long.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": "_research/polar_long.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": "_research/polar_long.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.7692307692, "max_line_length": 82, "alphanum_fraction": 0.5342756184, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625145783428, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7841290305291315}}
{"text": "function readInput(filename::String)::Vector{Int}\n\topen(filename) do file\n\t\treturn parse.(Int, split(readline(file), \",\"))\n\tend\nend\n\nfunction centroid(vec::Vector{<:Real}; weight_fun::Function)::Int\n\tmin_ = typemax(Int)\n\tfor i in minimum(vec):maximum(vec)\n\t\tmin_ = min(min_, sum(weight_fun.(abs.(vec .- i))))\n\tend\n\treturn min_\nend\n\npart1(vec) = sum(abs.(vec .- round(Int, mean(vec))))\npart2(vec) = centroid(vec, weight_fun=n -> sum(1:n))\n\nvec = readInput(\"input.txt\")\nprintln(part1(vec))\nprintln(part2(vec))\n", "meta": {"hexsha": "7a64b44cd818839eb9fc16bbcb197886a3751500", "size": 508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "07/07.jl", "max_stars_repo_name": "Steve2608/AoC-2021", "max_stars_repo_head_hexsha": "2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-01T23:29:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T23:29:46.000Z", "max_issues_repo_path": "07/07.jl", "max_issues_repo_name": "Steve2608/AoC-2021", "max_issues_repo_head_hexsha": "2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "07/07.jl", "max_forks_repo_name": "Steve2608/AoC-2021", "max_forks_repo_head_hexsha": "2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6", "max_forks_repo_licenses": ["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.1904761905, "max_line_length": 65, "alphanum_fraction": 0.687007874, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7841290296670909}}
{"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 \ud835\udc32 = \ud835\udc17\u03b2 + \u03f5, with \u03b2 = \ud835\udc17\u1d57\ud835\udc17\u207b\u00b9\ud835\udc17\u1d57\ud835\udc32\n\"\"\"\nmutable struct SecondOrderPolynomialSurrogate{X,Y,B,L,U} <: AbstractSurrogate\n    x::X\n    y::Y\n    \u03b2::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    \u03b2 = X\\y\n    return SecondOrderPolynomialSurrogate(x,y,\u03b2,lb,ub)\nend\n\nfunction (sec_ord::SecondOrderPolynomialSurrogate)(val::Number)\n    return sec_ord.\u03b2[1] + sec_ord.\u03b2[2]*val + sec_ord.\u03b2[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    \u03b2 = X\\y\n    return SecondOrderPolynomialSurrogate(x,y,\u03b2,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.\u03b2'*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.\u03b2 = 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.\u03b2 = 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": "@testset \"basic predicate tests\" begin\n    pred1 = Predicate((x,y) -> x == y)\n    pred2 = Predicate((x,y) -> x != y)\n    pred3 = Predicate((x,y) -> all(x .== -y)) \n    @test pred1(1,1) \n    @test !pred1(1,2) \n    @test !pred2(1,1) \n    @test pred2(1,2) \n    @test pred3([1,2],[-1,-2])\n    @test !pred3([1,2],[2,3])\nend\n\n@testset \"is predicate equivalence relation\" begin\n    pred1 = Predicate((x,y) -> x == y)\n    pred2 = Predicate((x,y) -> x != y)\n    pred3 = Predicate((x,y) -> all(x .== -y)) \n    pred4 = Predicate((x,y) -> x == y+3) \n    @test check_for_equivalence_relation(pred1, -11:10)\n    @test check_for_equivalence_relation(pred2, -7:10)\n    @test check_for_equivalence_relation(pred3, [[i,j] for i in -7:10 for j in -2:8])\n    @test !check_for_equivalence_relation(pred4, -7:10)\nend\n\n@testset \"mappings\" begin\n    m1 = Mapping(x -> [x])\n    m2 = Mapping(x -> [-x])\n    sol2 = Dict(-4 => 1, -3 => 2, 3 => 2, -2 => 3, 2 => 3, -1 => 4, 1 => 4, 0 => 5)\n    m3 = Mapping(x -> [x+3,x-3])\n    m5 = Mapping(x -> [x-3])\n    sol3 = Dict(-4 => 1, -1 => 1, 2 => 1, -3 => 2, 0 => 2, 3 => 2, -2 => 3, 1 => 3)\n    @test find_classes(m1, 1:5) == Dict(zip(1:5,collect(1:5)))\n    @test find_classes(m2, -4:3) == sol2\n    @test find_classes(m3, -4:3) == sol3\n    @test !(find_classes(m5, -4:3) == sol3)\nend\n", "meta": {"hexsha": "64ae02920b59e09b47f00b2a8ed9ce404ba78e5f", "size": 1300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Mappings.jl", "max_stars_repo_name": "gitter-badger/EquivalenceClassesConstructor.jl", "max_stars_repo_head_hexsha": "40fd2809b8b5f44ec169c4235f057f8b2387a891", "max_stars_repo_licenses": ["MIT"], "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/Mappings.jl", "max_issues_repo_name": "gitter-badger/EquivalenceClassesConstructor.jl", "max_issues_repo_head_hexsha": "40fd2809b8b5f44ec169c4235f057f8b2387a891", "max_issues_repo_licenses": ["MIT"], "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/Mappings.jl", "max_forks_repo_name": "gitter-badger/EquivalenceClassesConstructor.jl", "max_forks_repo_head_hexsha": "40fd2809b8b5f44ec169c4235f057f8b2387a891", "max_forks_repo_licenses": ["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.1111111111, "max_line_length": 85, "alphanum_fraction": 0.5353846154, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.7840567850124758}}
{"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# title: 1524. Number of Sub-arrays With Odd Sum\n# id: problem1524\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Array, Math\n# link: <https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/description/>\n# hidden: true\n# ---\n# \n# Given an array of integers `arr`. Return _the number of sub-arrays_ with\n# **odd** sum.\n# \n# As the answer may grow large, the answer  **must be**  computed modulo `10^9 +\n# 7`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: arr = [1,3,5]\n#     Output: 4\n#     Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\n#     All sub-arrays sum are [1,4,9,3,8,5].\n#     Odd sums are [1,9,3,5] so the answer is 4.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: arr = [2,4,6]\n#     Output: 0\n#     Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\n#     All sub-arrays sum are [2,6,12,4,10,6].\n#     All sub-arrays have even sum and the answer is 0.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: arr = [1,2,3,4,5,6,7]\n#     Output: 16\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: arr = [100,100,99,99]\n#     Output: 4\n#     \n# \n# **Example 5:**\n# \n#     \n#     \n#     Input: arr = [7]\n#     Output: 1\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= arr.length <= 10^5`\n#   * `1 <= arr[i] <= 100`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "3a7f567385bd4f1dbc999e8c2866d86218264caa", "size": 1411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1524.number-of-sub-arrays-with-odd-sum.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/1524.number-of-sub-arrays-with-odd-sum.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/1524.number-of-sub-arrays-with-odd-sum.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.8607594937, "max_line_length": 86, "alphanum_fraction": 0.5046066619, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.916109614162018, "lm_q1q2_score": 0.7840534707648377}}
{"text": "\nusing MLBase\nusing Base.Test\n\n# standardize\n\nX = rand(5, 8)\n\n(Y, t) = standardize(X; center=false, scale=false)\n@test isa(t, Standardize)\n@test isempty(t.mean)\n@test isempty(t.scale)\n@test isequal(X, Y)\n@test_approx_eq transform(t, X[:,1]) Y[:,1]\n\n(Y, t) = standardize(X; center=false, scale=true)\n@test isa(t, Standardize)\n@test isempty(t.mean)\n@test length(t.scale) == 5\ns = sqrt(sum(abs2(X), 2) ./ (8 - 1))\n@test_approx_eq Y X ./ s\n@test_approx_eq transform(t, X[:,1]) Y[:,1]\n\n(Y, t) = standardize(X; center=true, scale=false)\n@test isa(t, Standardize)\n@test length(t.mean) == 5\n@test isempty(t.scale)\n@test_approx_eq Y X .- mean(X, 2)\n@test_approx_eq transform(t, X[:,1]) Y[:,1]\n\n(Y, t) = standardize(X; center=true, scale=true)\n@test isa(t, Standardize)\n@test length(t.mean) == 5\n@test length(t.scale) == 5\n@test_approx_eq Y (X .- mean(X, 2)) ./ std(X, 2)\n@test_approx_eq transform(t, X[:,1]) Y[:,1]\n", "meta": {"hexsha": "7f4a37e5d35a7a3a73e38587aa078a13b7674b13", "size": 906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/datapre.jl", "max_stars_repo_name": "lendle/MLBase.jl", "max_stars_repo_head_hexsha": "2d360e6f236e813f2276cc6aaaf65bb01d66c4ba", "max_stars_repo_licenses": ["MIT"], "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/datapre.jl", "max_issues_repo_name": "lendle/MLBase.jl", "max_issues_repo_head_hexsha": "2d360e6f236e813f2276cc6aaaf65bb01d66c4ba", "max_issues_repo_licenses": ["MIT"], "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/datapre.jl", "max_forks_repo_name": "lendle/MLBase.jl", "max_forks_repo_head_hexsha": "2d360e6f236e813f2276cc6aaaf65bb01d66c4ba", "max_forks_repo_licenses": ["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.4864864865, "max_line_length": 50, "alphanum_fraction": 0.6545253863, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7840534702747791}}
{"text": "\n##Univariate kerneldensity and regression\nusing Distributions\nRandom.seed!(2017);\n\nlinreg(x, y) = hcat(fill!(similar(x), 1), x) \\ y\n\nx=rand(Normal(10), 500)\nxeval=range(minimum(x), stop=maximum(x), length=100)\nh = bwlscv(x, gaussiankernel)\n@test h>0\ndenvalues=kerneldensity(x, xeval=xeval)\n@test all(denvalues .>= 0)\n\ny=2 .* x.^2 .+ rand(Normal(0,5),500)\nb0, b1 = linreg(x, y)\nregfit = b0 .+ b1 .* x\nyfit0=localconstant(x, y, xeval=x)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit0.-y)\n\nyfit1=locallinear(x, y, xeval=x)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit1.-y)\n\nyfit0=npr(x, y, xeval=x, reg=localconstant)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit0.-y)\n\nyfit1=npr(x, y, xeval=x, reg=locallinear)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit1.-y)\n\n#confidence band\nyfit1=npr(x, y, xeval=xeval, reg=locallinear)\ncb=bootstrapCB(x, y, xeval=xeval)\n@test mean(vec(cb[1,:]) .<= yfit1 .<= vec(cb[2,:])) > .8\n\n#multivariate density estimation\nx = rand(Normal(10), 500, 3)\ndenvalues = kerneldensity(x, h = [1.0, 1.0, 1.0])\n@test all(denvalues .>= 0)\n\n#multivariate regression\nx = rand(Normal(10), 500, 3)\ny = x * ones(3) .+ x.^2 *ones(3)\nyfit1 = localconstant(x, y, xeval=x)\nregfit = x*inv(x'*x)*x'*y\n@test sum(abs2, regfit .- y) > sum(abs2, yfit1.-y)\n\n\n###Bounded gamma kernel density and regression\nx = rand(Gamma(4,2), 500)\nxeval = range(0.01, stop=20, length=100)\nh = bwlscv(x, gammakernel)\n@test h>0\ndenvalues = kerneldensity(x, xeval=xeval, kernel=gammakernel, lb=0.0)\n@test all(denvalues .> 0)\n\ny=2 .* x.^2 + x.*rand(Normal(0, 5), 500)\nb0, b1 = linreg(x, y)\nregfit = b0 .+ b1 .* x\nyfit0=npr(x, y, xeval=x, reg=localconstant, kernel=gammakernel,lb=0.0)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit0.-y)\n\nyfit1=npr(x, y, xeval=x, reg=locallinear, kernel=gammakernel, lb=0.0)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit1.-y)\n\n#bounded beta kernel density and regression\nx = rand(Beta(4,2), 500) * 10\nxeval = range(0, stop=10, length=100)\nh = bwlscv(x./10, betakernel)\n@test h>0\ndenvalues=kerneldensity(x, xeval=xeval, kernel=betakernel,h=h, lb=0.0,ub=10.0)\n@test all(denvalues .> 0)\n\n\n##Bounded local regression\ny=2 .* x.^2 + x.*rand(Normal(0, 5), 500)\nb0, b1 = linreg(x, y)\nregfit = b0 .+ b1 .* x\nyfit0=npr(x, y, xeval=x, reg=localconstant, kernel=betakernel,lb=0.0, ub=10.0)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit0.-y)\n\nyfit1=npr(x, y, xeval=x, reg=locallinear, kernel=betakernel, lb=0.0,ub=10.0)\n@test sum(abs2, regfit .- y) > sum(abs2, yfit1.-y)\n\nyfit1=npr(x, y, xeval=xeval, reg=locallinear, kernel=betakernel, lb=0.0,ub=10.0)\ncb=bootstrapCB(x, y, xeval=xeval,reg=locallinear, kernel=betakernel, lb=0.0,ub=10.0)\n@test mean(vec(cb[1,:]) .<= yfit1 .<= vec(cb[2,:])) > .8\n", "meta": {"hexsha": "c2aee6150db446eb03677e7b53e14a51cef2f258", "size": 2695, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testreg.jl", "max_stars_repo_name": "UnofficialJuliaMirror/KernelEstimator.jl-857edff2-01a9-55ba-8bc9-13e46c0ddbb2", "max_stars_repo_head_hexsha": "e691cc04422fb98e6aae4a06017fc803b9ca555d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-05-17T04:54:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T13:01:32.000Z", "max_issues_repo_path": "test/testreg.jl", "max_issues_repo_name": "UnofficialJuliaMirror/KernelEstimator.jl-857edff2-01a9-55ba-8bc9-13e46c0ddbb2", "max_issues_repo_head_hexsha": "e691cc04422fb98e6aae4a06017fc803b9ca555d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-08-10T05:40:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-13T13:22:11.000Z", "max_forks_repo_path": "test/testreg.jl", "max_forks_repo_name": "UnofficialJuliaMirror/KernelEstimator.jl-857edff2-01a9-55ba-8bc9-13e46c0ddbb2", "max_forks_repo_head_hexsha": "e691cc04422fb98e6aae4a06017fc803b9ca555d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-08-10T00:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T21:58:57.000Z", "avg_line_length": 30.9770114943, "max_line_length": 84, "alphanum_fraction": 0.6597402597, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7840113850709819}}
{"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# \u2554\u2550\u2561 1eb34f10-b4b3-11ec-19f5-c7f26108d374\nbegin\n\tusing LinearAlgebra\n\tusing StatsPlots\nmd\"\"\"\n# HW 11\n\nEric Nguyen\n\"\"\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 = \u00b11$\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$\u27e8v \\vert u\u27e9 = 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u0308_1 &= -kx_1 + k(x_2 - x_1) = -2kx_1 + kx_2 \\\\\nmx\u0308_2 &= -k(x_2 - x_1) + k(x_3 - x_2) = kx_1 - 2kx_2 + kx_3 \\\\\nmx\u0308_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\u0308_1 &= -2{\\omega_0}^2 x_1 + {\\omega_0}^2 x_2 \\\\\nx\u0308_2 &= {\\omega_0}^2 x_1 - 2{\\omega_0}^2 x_2 + {\\omega_0}^2 x_3 \\\\\nx\u0308_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\u0308}(t) = -{\\omega_0}^2 \\underline{\\underline{\u03a9}} \\,\\underline{x}(t)$\n\nwhere\n\n$\\underline{x} = \\begin{bmatrix} x_1 \\\\ x_2 \\\\ x_3 \\end{bmatrix} \\qquad \u03a9 = \\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# \u2554\u2550\u2561 7387c353-51b7-402b-a500-adec0a34b059\nlet\n\t\u03a9 = [-2 1 0; 1 -2 1; 0 1 -2]\n\teigen(\u03a9)\nend\n\n# \u2554\u2550\u2561 b40838d0-8391-4f1e-a3fc-a4be028b7bc7\n(2 - sqrt(2))\n\n# \u2554\u2550\u2561 ec26fefb-18d1-4ac7-b0c1-0d3c71ae1305\nbegin\n\t\u03c9\u2081 = sqrt(2 - sqrt(2))\n\t\u03c9\u2082 = sqrt(2)\n\t\u03c9\u2083 = 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, \u03d5) = A .* a1 .* cos(\u03c9\u2081 * t + \u03d5)\n\ts2(t, A, \u03d5) = A .* a2 .* cos(\u03c9\u2082 * t + \u03d5)\n\ts3(t, A, \u03d5) = A .* a3 .* cos(\u03c9\u2083 * t + \u03d5)\nend;\n\n# \u2554\u2550\u2561 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\u2081\")\n\tplot!(x2, label=\"x\u2082\")\n\tplot!(x3, label=\"x\u2083\")\n\ttitle!(\"Eigenmode 1\")\nend\n\n# \u2554\u2550\u2561 de44b0c7-eee4-49ed-9264-40a5339e7d6c\nmd\"\"\"\nEigenmode 1: x1 and x3 oscillate with each other, opposite to x2\n\"\"\"\n\n# \u2554\u2550\u2561 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\u2081\")\n\tplot!(x2, label=\"x\u2082\")\n\tplot!(x3, label=\"x\u2083\")\n\ttitle!(\"Eigenmode 2\")\nend\n\n# \u2554\u2550\u2561 5500a012-48fd-4227-a70f-515425c5122a\nmd\"\"\"\nEigenmode 2: x1 and x3 oscillate against each other while x2 remains in place\n\"\"\"\n\n# \u2554\u2550\u2561 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\u2081\")\n\tplot!(x2, label=\"x\u2082\")\n\tplot!(x3, label=\"x\u2083\")\n\ttitle!(\"Eigenmode 3\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25001eb34f10-b4b3-11ec-19f5-c7f26108d374\n# \u255f\u25006c4b3bf7-26e9-4d6f-9305-65fbc851818f\n# \u255f\u25002743185f-b0d7-4195-8e8e-a1bfcf132934\n# \u2560\u2550982fab25-1414-4789-bc16-343ab29b4514\n# \u255f\u25007e53c83c-ead7-484f-8762-4a0956ba7210\n# \u255f\u2500c8977146-1409-4eb1-bede-13436fd7214b\n# \u255f\u2500201fb421-39b1-47db-8dec-609706461dca\n# \u255f\u2500e12e34c7-90db-4f31-8792-ce2a39acc435\n# \u255f\u25001aaa8364-b72e-4128-b26a-82d4d4601634\n# \u2560\u25507387c353-51b7-402b-a500-adec0a34b059\n# \u2560\u2550b40838d0-8391-4f1e-a3fc-a4be028b7bc7\n# \u255f\u2500ec26fefb-18d1-4ac7-b0c1-0d3c71ae1305\n# \u255f\u2500355540ec-db9b-4ce5-a5d2-0c10497da934\n# \u255f\u2500de44b0c7-eee4-49ed-9264-40a5339e7d6c\n# \u255f\u25006f073f29-39b5-496e-b644-45051c81ab54\n# \u255f\u25005500a012-48fd-4227-a70f-515425c5122a\n# \u255f\u2500e0a8d8ea-e5bd-48ca-b44f-4b6625181a17\n# \u255f\u2500cc32c2a5-d377-4a77-8477-b3acc63cca3b\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "#=\nday7:\n- Julia version: 1.7.0\n- Author: Paul.Mealor\n- Date: 2021-12-07\n=#\n\nusing AoC, Test\n\nparsePositions(line) = parse.(Int, split(line, \",\"))\n@test parsePositions(\"5,34,3\") == [5,34,3]\n\ntotalDistance(candidate, positions) = sum(p -> abs(candidate - p), positions)\n@test totalDistance(4,[4,4]) == 0\n@test totalDistance(1,[16,1,2,0,4,2,7,1,2,14]) == 41\n@test totalDistance(2,[16,1,2,0,4,2,7,1,2,14]) == 37\n@test totalDistance(3,[16,1,2,0,4,2,7,1,2,14]) == 39\n@test totalDistance(10,[16,1,2,0,4,2,7,1,2,14]) == 71\n\ntotalDistance2(candidate, positions) = sum(positions) do p\n    distance = abs(candidate - p)\n    return distance * (distance + 1) \u00f7 2\nend\n@test totalDistance2(4,[4,4]) == 0\n@test totalDistance2(5,[16,1,2,0,4,2,7,1,2,14]) == 168\n@test totalDistance2(2,[16,1,2,0,4,2,7,1,2,14]) == 206\n\nfunction bestPosition(positions)\n    bestDistance = typemax(eltype(positions))\n    result = -1\n    for candidate = min(positions...):max(positions...)\n        thisDistance = totalDistance(candidate, positions)\n        if thisDistance < bestDistance\n            bestDistance = thisDistance\n            result = candidate\n        end\n    end\n    return result\nend\n\nfunction bestPosition2(positions)\n    bestDistance = typemax(eltype(positions))\n    result = -1\n    for candidate = min(positions...):max(positions...)\n        thisDistance = totalDistance2(candidate, positions)\n        if thisDistance < bestDistance\n            bestDistance = thisDistance\n            result = candidate\n        end\n    end\n    return result\nend\n\n@test bestPosition([16,1,2,0,4,2,7,1,2,14]) == 2\n@test bestPosition2([16,1,2,0,4,2,7,1,2,14]) == 5\n\nfunction part1(line)\n    positions = parsePositions(line)\n    position = bestPosition(positions)\n    return totalDistance(position, positions)\nend\n\n@test part1(firstExampleLine(7,1)) == 37\n\nfunction part2(line)\n    positions = parsePositions(line)\n    position = bestPosition2(positions)\n    return totalDistance2(position, positions)\nend\n\n@test part2(firstExampleLine(7,1)) == 168\n\nfirstLine(7) |> l -> @time part1(l) |> show\nfirstLine(7) |> l -> @time part1(l) |> show\nfirstLine(7) |> l -> @time part2(l) |> show\nfirstLine(7) |> l -> @time part2(l) |> show\n", "meta": {"hexsha": "5f604edbaaec5a11e9d9cbb923bdf15a051a178c", "size": 2188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day7.jl", "max_stars_repo_name": "jelaby/advent-of-code-2021-julia", "max_stars_repo_head_hexsha": "9601efbc44741c1e9178dcedbcd8ebc8bb2041e0", "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/day7.jl", "max_issues_repo_name": "jelaby/advent-of-code-2021-julia", "max_issues_repo_head_hexsha": "9601efbc44741c1e9178dcedbcd8ebc8bb2041e0", "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/day7.jl", "max_forks_repo_name": "jelaby/advent-of-code-2021-julia", "max_forks_repo_head_hexsha": "9601efbc44741c1e9178dcedbcd8ebc8bb2041e0", "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.4155844156, "max_line_length": 77, "alphanum_fraction": 0.6526508227, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.7839987659806177}}
{"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\nusing CSV\nusing DataFrames\n\n# selecting the index combination from given range\nfunction getIndexes(i,j,d)\n    if i == j\n        return [i]\n    elseif i > j && i > 2\n        return 0\n    else\n        niz1 = []\n        niz2 = collect(i:j-1)\n        for k in 1:d\n            if !(k in niz2)\n                push!(niz1,k)\n            end\n        end\n        return length(niz1) == 0 ? 0 : niz1\n    end\nend\n\n#selecting columns from indexes as matrix\nfunction getSelectedColumns(selectedColumns,X)\n    if selectedColumns != 0\n        localX = ones(size(X)[1],1)\n        for i in selectedColumns\n            localX = [localX X[:,i]]\n        end\n        return localX\n    else \n        return 0\n    end\nend\n\n#load data\nDiabete_Data = CSV.read(\"diabetes.data\",DataFrame)\n\nn,d = size(Diabete_Data)\nd = d-1\n\n# compute the optimal theta\n\nX = zeros(n,d)\ny = zeros(n,1)\n\nfor i=1:d\n    X[:,i] = Diabete_Data[:,i]\nend\n\ny = Diabete_Data[:,end]\n\n# for storing MSEs\nsavedMSE = []\n\n#for  storing top contender colums\nsavedIndexes = []\n\n#  age \n#  sex \n#  bmi \n#  map\t   mean arterial pressure\t\n#  s1  tc :   total cholesterol \n#  s2  ldl    low density lipoprotein \n#  s3  hdl    high density lipoprotein \n#  s4  tch \n#  s5  ltg \n#  s6  glu\n\n# string representation of said colums\nnameByIndex = [\"AGE\" \"SEX\" \"BMI\" \"MAP\" \"TC\" \"LDL\" \"HDL\" \"TCH\" \"LTG\" \"GLU\"]\n\n\n#Calculating all possible solutions\nfor i in 1:d-1\n    for j in 1:d\n        localX = []\n        temp = getIndexes(i,j,d)\n        selectedColumns = temp == 0 ? continue : temp\n        localX = getSelectedColumns(selectedColumns,X)\n        localX = localX == 0 ? continue : localX\n        theta_opt = localX\\y\n        # achieved loss\n        MSE = norm(localX*theta_opt-y,2)^2/n\n        push!(savedMSE,MSE)\n        push!(savedIndexes,selectedColumns)\n    end\nend\n\n# Number of top results\nnumOfBests = 10\n\n\n#Finding top results\nfor i in 1:numOfBests\n   bestIndex = argmin(savedMSE)\n    bestMSE = savedMSE[bestIndex]\n    leastColums = savedIndexes[bestIndex]\n    println(\"\\n [$i] BEST SOLUTION\")\n    println(\"Best MSE of: $(bestMSE) with \")\n    for j in leastColums\n        println(\"$(nameByIndex[j]) \") \n    end\n    println(\"parameters as most impactful\")\n    deleteat!(savedMSE,bestIndex)\n    deleteat!(savedIndexes,bestIndex)\nend\n\n", "meta": {"hexsha": "528afdb95a6b2ab53bceb205f21fe376a93a1fb0", "size": 2288, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Primer Predavanje/analyse.jl", "max_stars_repo_name": "pikacxe/Primenjeni-Algoritmi", "max_stars_repo_head_hexsha": "b2d87d06881bb499c9ae56ca7f889c9d0daefe70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Primer Predavanje/analyse.jl", "max_issues_repo_name": "pikacxe/Primenjeni-Algoritmi", "max_issues_repo_head_hexsha": "b2d87d06881bb499c9ae56ca7f889c9d0daefe70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Primer Predavanje/analyse.jl", "max_forks_repo_name": "pikacxe/Primenjeni-Algoritmi", "max_forks_repo_head_hexsha": "b2d87d06881bb499c9ae56ca7f889c9d0daefe70", "max_forks_repo_licenses": ["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.9908256881, "max_line_length": 74, "alphanum_fraction": 0.6070804196, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7839832373306841}}
{"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 / (\u03c0 * 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 / (\u03c0 * half_bandwidth)\n    time_delay::Float64 = 6 * half_width\nend\n\n(s::GaussianPulse)(t) = cos(2\u03c0 * 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    \u03b4t = 1 / (s.fc + s.half_bandwidth) / nsamples\n    t_samples = range(s.time_delay - 20s.half_width, s.time_delay + 20s.half_width, step = \u03b4t)\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\u00e9, Gabriel, and Marco Cuturi. \"Computational optimal transport: With applications to data science.\" Foundations and Trends\u00ae 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\u00e9, Gabriel. \"Entropic approximation of Wasserstein gradient flows.\" SIAM Journal on Imaging Sciences 8.4 (2015): 2323-2351.\nfunction E(\u03c1; m=1)\n    if m == 1\n        return sum(xlogx.(\u03c1)) - sum(\u03c1)\n    elseif m > 1\n        return dot(\u03c1, @. (\u03c1^(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 = \u00b1 0.5$. \n\u03c8(x) = 10 * (x - 0.5)^2 * (x + 0.5)^2;\nplot(support, \u03c8.(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\u03a8 = \u03c8.(support);\n\n# Define the time step $\\tau$ and entropic regularisation level $\\varepsilon$, and form the associated Gibbs kernel $K = e^{-C/\\varepsilon}$. \n\u03c4 = 0.05\n\u03b5 = 0.01\nK = @. exp(-C / \u03b5);\n\n# We define the (non-smooth) initial condition $\\rho_0$ in terms of step functions. \nH(x) = x > 0\n\u03c10 = @. H(support + 0.25) - H(support - 0.25)\n\u03c10 = \u03c10 / sum(\u03c10)\nplot(support, \u03c10; label=\"Initial condition \u03c10\", 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(\u03c1, \u03c10, \u03c4, \u03b5, C)\n    return sinkhorn2(\u03c1, \u03c10, C, \u03b5; regularization=true, maxiter=250) + \u03c4 * (dot(\u03a8, \u03c1) + E(\u03c1))\nend;\n\n# `step` solves the implicit step problem to produce $\\rho_{t + \\tau}$ from $\\rho_t$. \nfunction step(\u03c10, \u03c4, \u03b5, C, G)\n    ## only print error messages\n    obj = u -> G(softmax(u), \u03c10, \u03c4, \u03b5, C)\n    opt = with_logger(SimpleLogger(stderr, Logging.Error)) do\n        optimize(\n            obj,\n            ones(size(\u03c10)),\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\u03c1 = similar(\u03c10, size(\u03c10, 1), N)\n\u03c1[:, 1] = \u03c10\nfor i in 2:N\n    @info i\n    \u03c1[:, i] = step(\u03c1[:, i - 1], \u03c4, \u03b5, C, G_fpe)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    \u03c1;\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(\u03c1, \u03c10, \u03c4, \u03b5, C)\n    return sinkhorn2(\u03c1, \u03c10, C, \u03b5; regularization=true, maxiter=250) +\n           \u03c4 * (dot(\u03a8, \u03c1) + E(\u03c1; m=2))\nend;\n\n# set up as previously \nN = 10\n\u03c1 = similar(\u03c10, size(\u03c10, 1), N)\n\u03c1[:, 1] = \u03c10\nfor i in 2:N\n    \u03c1[:, i] = step(\u03c1[:, i - 1], \u03c4, \u03b5, C, G_pme)\nend\nplot(\n    support,\n    \u03c1;\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\u00e9. \u201cSemi-Dual Regularized Optimal Transport.\u201d ArXiv: Learning, 2018.\n#\n# The formulas we state below are lifted from statements in [^Z21]. \n#\n# [^Z21]: Zhang, Stephen Y. \u201cA Unified Framework for Non-Negative Matrix and Tensor Factorisations with a Smoothed Wasserstein Loss.\u201d 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, \u03c10, \u03c4, \u03b5, K)\n    return OptimalTransport.Dual.ot_entropic_semidual(\u03c10, u, \u03b5, K) +\n           \u03c4 * E_dual(-u / \u03c4 - \u03a8, 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(\u03c10, \u03c4, \u03b5, K, G)\n    obj = u -> G(u, \u03c10, \u03c4, \u03b5, K)\n    opt = optimize(\n        obj,\n        (\u2207, u) -> ReverseDiff.gradient!(\u2207, obj, u),\n        zeros(size(\u03c10)),\n        LBFGS(),\n        Optim.Options(; iterations=250, g_tol=1e-6),\n    )\n    return OptimalTransport.Dual.getprimal_ot_entropic_semidual(\n        \u03c10, Optim.minimizer(opt), \u03b5, 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\u03c1 = similar(\u03c10, size(\u03c10, 1), N)\n\u03c1[:, 1] = \u03c10\nfor i in 2:N\n    \u03c1[:, i] = step(\u03c1[:, i - 1], \u03c4, \u03b5, K, G_dual_fpe)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    \u03c1;\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, \u03c10, \u03c4, \u03b5, K)\n    return OptimalTransport.Dual.ot_entropic_semidual(\u03c10, u, \u03b5, K) +\n           \u03c4 * E_dual(-u / \u03c4 - \u03a8, Val(2))\nend\n\u03c1 = similar(\u03c10, size(\u03c10, 1), N)\n\u03c1[:, 1] = \u03c10\nfor i in 2:N\n    @info i\n    \u03c1[:, i] = step(\u03c1[:, i - 1], \u03c4, \u03b5, K, G_dual_pme)\nend\ncolors = range(colorant\"red\"; stop=colorant\"blue\", length=N)\nplot(\n    support,\n    \u03c1;\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\u2013953, 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\u201319, 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\u2013379. [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\u2013265, 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\u2013467, 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\u2013679, 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\u201342, 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\u03c0/Lx .* [0:nx\u00f72-1;-nx\u00f72:-1]\n\n        nv  = meshv.len\n        dv  = meshv.step\n        Lv  = meshv.stop - meshv.start\n        kv  = 2\u03c0/Lv .* [0:nv\u00f72-1;-nv\u00f72:-1]\n\n        new( kx, kv)\n\n    end\n  \nend\n\n\nfunction advection_v!(f\u1d57  :: Array{ComplexF64,2}, \n                      adv :: Fourier,\n\t\t      e   :: Vector{ComplexF64}, \n\t\t      dt  :: Float64 )\n    fft!(f\u1d57, 1)\n    @. f\u1d57 *= exp(-1im * dt * adv.kv * $transpose(e))\n    ifft!(f\u1d57, 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    \u03c1 = dv * vec(sum(f,dims=2))  \n    for i in 2:length(e)\n        e[i] = -1im * \u03c1[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,\u03c1::Number)\n\nScale the univariate polynomial `a` with the variable `s` given by ``a(s) = a\u2080 + a\u2081 s + a\u2082 s\u00b2 + \u2026 + a\u2099 s\u207f`` by the scalar positive real number `\u03c1`. This amounts to replacing the original variable `s` with a new scaled variable `\u03c1s`.\n\n# Examples\n\n```julia\njulia> a = Polynomial(1:5,:s)\njulia> \u03c1=10\njulia> scale(a,\u03c1)\nPolynomial(1 + 20*s + 300*s^2 + 4000*s^3 + 50000*s^4)\n```\n\"\"\"\nfunction scale(a::Polynomial,\u03c1::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] *= \u03c1^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\u2080 + a\u2081 s + a\u2082 s\u00b2 + \u2026 + a\u2099 s\u207f`` with respect to the imaginary axis, that is, return the polynomial ``a\u0303(s) = \u0304a\u0304(-s)=a\u0304\u2080 - \u0304a\u0304\u2081s + a\u0304\u2082 s\u00b2 + \u2026 \u00b1 \u0304a\u0304\u2099 s\u207f``.\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\u2080 + a\u2081 s + a\u2082 s\u00b2 + \u2026 + a\u2099 s\u207f``, return the polynomial ``r(s) = \u0304a\u0304\u2099 + \u0304a\u0304\u2099\u208b\u2081 s + \u0304a\u0304\u2099\u208b\u2082 s\u00b2 + \u2026 + \u0304a\u0304\u2080 s\u207f``.\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\u2080 + a\u2081 z + a\u2082 z\u00b2 + ... + a\u2099 z\u207f`` with respect to the unit circle in the complex plane, that is, return the Laurent polynomial ``a\u0303(z) = a\u0304\u2099 z\u207b\u207f + a\u0304\u2099\u208b\u2081 z\u207b\u207f\u207a\u00b9 + a\u0304\u2099\u208b\u2082 z\u207b\u207f\u207a\u00b2 + \u2026 + a\u0304\u2080``.\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\u00b2 + 4*z\u00b3 + 5*z\u2074)\n\njulia> p = dconj(a)\nLaurentPolynomial(5*z\u207b\u2074 + 4*z\u207b\u00b3 + 3*z\u207b\u00b2 + 2*z\u207b\u00b9 + 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\u00b2 + (4 + 4im)*z\u00b3 + (5 + 5im)*z\u2074)\n\njulia> p = dconj(c)\nLaurentPolynomial((5 - 5im)*z\u207b\u2074 + (4 - 4im)*z\u207b\u00b3 + (3 - 3im)*z\u207b\u00b2 + (2 - 2im)*z\u207b\u00b9 + (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\u2098 z\u1d50 + p\u208b\u2081 z\u207b\u00b9 +  p\u2080 + p\u2081 z + \u2026 + p\u2099 z\u207f` and a given integer `k`, return a Laurent polynomial  `p(z) = p\u2098 z\u1d50\u207a\u1d4f + p\u208b\u2081 z\u207b\u00b9\u207a\u1d4f +  p\u2080 z\u1d4f + p\u2081 z\u1d4f\u207a\u00b9 + \u2026 + p\u2099 z\u207f\u207a\u1d4f`. 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\u207b\u00b2 + 2*z\u207b\u00b9 + 3 + 4*z)\n\njulia> shift(p)\nLaurentPolynomial(z\u207b\u00b9 + 2 + 3*z + 4*z\u00b2)\n\njulia> shift(p,-3)\nLaurentPolynomial(z\u207b\u2075 + 2*z\u207b\u2074 + 3*z\u207b\u00b3 + 4*z\u207b\u00b2)\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    \u03b1\nend\n\n# init! function does nothing.\ninit!(M::GradientDescent, f, \u2207f, x) = M;\n\nfunction step!(M::GradientDescent, f, \u2207f, x)\n    \u03b1, g = M.\u03b1, \u2207f(x);\n    return x - \u03b1*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\u2207f = (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, \u2207f, x);\nx_res = [];\ny_res = [];\n\nfor i in 1:100\n    x = step!(m, f, \u2207f, 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, \u03c3f, \u03c3y)\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- `\u03c3f`: vertical scale \n- `\u03c3y`: observation noise\n\"\"\"\nmutable struct SquaredExponentialKernel <: Kernel \n    l::Float64\n    \u03c3f::Float64\n    \u03c3y::Float64\nend\n\nfunction (kernel::SquaredExponentialKernel)(xp, xq, \u03b4pq)\n    \u03c3f = kernel.\u03c3f\n    \u03c3y = kernel.\u03c3y\n    M = lengthscalematrix(kernel.l, length(xp))\n    return \u03c3f^2 * exp(-0.5 * (xp - xq)' * M * (xp - xq)) + \u03c3y^2*\u03b4pq\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    \u03b80::Float64\n    \u03b81::Float64\n\n    function MixtureKernel(l, \u03c3f, \u03c3y, \u03b80, \u03b81)\n        sekernel = SquaredExponentialKernel(l, \u03c3f, \u03c3y)\n        new(sekernel, \u03b80, \u03b81)\n    end\n\nend\n\nfunction (kernel::MixtureKernel)(xp, xq, \u03b4pq)\n    sekernel = kernel.sekernel\n    \u03b80 = kernel.\u03b80\n    \u03b81 = kernel.\u03b81\n    return sekernel(xp, xq, \u03b4pq) + \u03b80 + \u03b81 * (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, \u03c3f, \u03c3y = kernel.l, kernel.\u03c3f, kernel.\u03c3y\n    N = size(X, 1)\n    euclideandist = X.^2 .+ (X.^2)' .- 2*X*X'\n    return \u03c3f^2 * exp.(-0.5/l^2 .* euclideandist) + Diagonal(fill(\u03c3y^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": "using RegularizedRegression: ape, medape, describe_goodness_of_fit\n\n@testset \"Loss functions\" begin\n\n@testset \"APE (Absolute Percentage Error)\" begin\n    @test ape([1.5, 2.0], [1.0, 1.0]) == [0.50, 1.0]\n    @test ape([1.5, 2.0, 3.0], [1.0, 1.0, 1.0]) == [0.50, 1.0, 2.0]\nend\n\n@testset \"MAPE (Mean Absolute Percentage Error)\" begin\n    @test mape([1.5, 2.0], [1.0, 1.0]) == mean([50.0, 100.0])\n    @test mape([1.5, 2.0, 3.0], [1.0, 1.0, 1.0]) == mean([50.0, 100.0, 200.0])\n    @test isapprox(mape([1.5, 2.0, 3.0], [1.0, 1.5, 2.0]), mean([50.0, 100.0/3, 50.0]))\nend\n\n@testset \"MEDAPE (Median Absolute Percentage Error)\" begin\n    @test medape([1.5, 2.0], [1.0, 1.0]) == median([50.0, 100.0])\n    @test medape([1.5, 2.0, 3.0], [1.0, 1.0, 1.0]) == median([50.0, 100.0, 200.0])\nend\n\n@testset \"MASE (Mean Absolute Scaled Error)\" begin\n    @test mase([1.5, 2.0, 3.0], [1.0, 1.5, 2.0]) == (0.5+0.5+1.0)/(3.0/2.0 * (0.5 + 0.5))\nend\n\n#@testset \"R2\" begin\n#    @test r2([1.5, 2.0, 3.0], [1.0, 1.5, 2.0]) == (1.0 - ()\n#end\n\n@testset \"describe_goodness_of_fit\" begin\n    str = describe_goodness_of_fit([1.5, 2.0, 3.0], [1.0, 1.5, 2.0])\n    @test typeof(str) <: AbstractString\n    @test ismatch(r\"MAPE = 44.44%\", str)\n    @test ismatch(r\"MASE = 1.33\", str)\n    @test ismatch(r\"R2 = \", str)\n\n    str_w_adj = describe_goodness_of_fit([1.5, 2.0, 3.0], [1.0, 1.5, 2.0], 1)\n    @test ismatch(r\"R2adj = \", str_w_adj)\nend\n\nend", "meta": {"hexsha": "bd342bc3b95eead31aceedf6b9ae1263fb63f7d0", "size": 1405, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_loss_functions.jl", "max_stars_repo_name": "robertfeldt/RegularizedRegression.jl", "max_stars_repo_head_hexsha": "a354793c6c9d6d02b75c300fe3c395cb04d3bc91", "max_stars_repo_licenses": ["MIT"], "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_loss_functions.jl", "max_issues_repo_name": "robertfeldt/RegularizedRegression.jl", "max_issues_repo_head_hexsha": "a354793c6c9d6d02b75c300fe3c395cb04d3bc91", "max_issues_repo_licenses": ["MIT"], "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_loss_functions.jl", "max_forks_repo_name": "robertfeldt/RegularizedRegression.jl", "max_forks_repo_head_hexsha": "a354793c6c9d6d02b75c300fe3c395cb04d3bc91", "max_forks_repo_licenses": ["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.125, "max_line_length": 89, "alphanum_fraction": 0.5672597865, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7838335669023216}}
{"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, \u03c0, n_samples_out))\n    outer_circ_y = sin.(LinRange(0, \u03c0, n_samples_out))\n    inner_circ_x = 1 .- cos.(LinRange(0, \u03c0, n_samples_in))\n    inner_circ_y = 1 .- sin.(LinRange(0, \u03c0, 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, :\u03c3)]\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(\u03b8::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(\u03b8[index:last_index_w], rows, cols))\n        push!(biases, reshape(\u03b8[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, \u03b8::AbstractVector, network_shape::AbstractVector)\n    weights, biases = unpack(\u03b8, 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    \u03b8 ~ MvNormal(zeros(num_params), sig .* ones(num_params))\n    preds = nn_forward(xs, \u03b8, 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 \u03b8 parameters from the sampled chain.\nparams2 = MCMCChains.group(ch2, :\u03b8).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\u010di\u0107 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\u010di\u0107.\n\n[1] http://wwwcvs.mitgcm.org/viewvc/MITgcm/MITgcm_contrib/high_res_cube/matlab-grid-generator/map_xy2xyz.m?view=markup\n\nRan\u010di\u0107 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\u1d9c = abs(x)\n    Y = y\u1d9c = abs(y)\n\n    kxy = y\u1d9c > x\u1d9c\n\n    x\u1d9c = 1 - x\u1d9c\n    y\u1d9c = 1 - y\u1d9c\n\n    kxy && (x\u1d9c = 1 - Y)\n    kxy && (y\u1d9c = 1 - X)\n\n    Z = ((x\u1d9c + im * y\u1d9c) / 2)^4\n    W = W_Rancic(Z)\n\n    im\u00b3 = im^(1/3)\n    ra = \u221a3 - 1\n    cb = -1 + im\n    cc = ra * cb / 2\n\n    W = im\u00b3 * (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 = (\u221a2,0)\nC = (\u221a3/3,\u221a3/3)\nD = (0,\u221a2)\n\n\"\"\"\nfunction conformal_cubed_sphere_inverse_mapping(X, Y, Z)\n    H  = Z + 1\n    X\u02e2 = X/H\n    Y\u02e2 = Y/H\n    \u03c9  = X\u02e2 + im*Y\u02e2\n\n    ra = \u221a3 - 1\n    cb = -1 + im\n    cc = ra * cb / 2\n    \u03c9\u2070 = (\u03c9*cb + ra)/(1-\u03c9*cc)\n    W\u2070 = im*\u03c9\u2070^3*im\n    Z  = Z_Rancic(W\u2070)\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": "using Base.Test\nimport Roots.newton, Roots.halley\n\n@test_approx_eq_eps newton(sin, cos, 0.5) 0.0 100*eps(1.0)\n@test_approx_eq newton(cos, x -> -sin(x), 1.0) pi/2 \n@test_approx_eq newton(x -> x^2 - 2x - 1, x -> 2x - 2, 3.0) 2.414213562373095\n@test_approx_eq_eps newton(x -> exp(x) - cos(x),\n                           x -> exp(x) + sin(x), 3.0) 0.0 eps(1.0) \n@test_approx_eq halley(x -> x^2 - 2x - 1,\n                       x -> 2x - 2,\n                       x -> 2, 3.0) 2.414213562373095\n@test_approx_eq_eps halley(x -> exp(x) - cos(x),\n                           x -> exp(x) + sin(x),\n                           x -> exp(x) + cos(x), 3.0) 0.0 eps(1.0)\n\n\n## tests with auto derivatives\n@test_approx_eq newton(sin, 3) float(pi)\n@test_approx_eq halley(sin, 3) float(pi)\n\n## More tests with autoderivaitves. Derivative of D operation:\nisdefined(ForwardDiff, :derivative) && @test_approx_eq newton(D(sin), 1.5) pi/2\n\n## test with Complex input\n\nf = x ->  x^3 - 1; fp = x ->  3x^2\n@test_approx_eq real(newton(f, fp, 1+im)) 1\n@test_approx_eq real(newton(f, fp, 1+10im)) (-1/2)\n", "meta": {"hexsha": "097e10140b36cebf6b963173716419c0a17b1ddc", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_newton.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/test_newton.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/test_newton.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": 37.0, "max_line_length": 79, "alphanum_fraction": 0.5740913327, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7838335584933168}}
{"text": "n = 9 # rand(1:10)\n\nA = matrixdepot(\"companion\", Float32, n)\n@test diag(A, -1) == ones(Float32, n-1)\n\nv = [3., 4, 2, 10]\nB = matrixdepot(\"companion\", v)\n@test B[:,end] == v\n\nprintln(\"'companion' passed test...\")\n", "meta": {"hexsha": "cc285100a3231a1f30648819b032e81e2396f152", "size": 212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_companion.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_companion.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_companion.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 19.2727272727, "max_line_length": 40, "alphanum_fraction": 0.5849056604, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.783833556304553}}
{"text": "module MultiFieldFEAutodiffTests\n\nusing Test\n\nusing Gridap.Algebra\nusing Gridap.Geometry\nusing Gridap.CellData\nusing Gridap.ReferenceFEs\nusing Gridap.FESpaces\nusing Gridap.MultiField\n\ndomain = (0,1,0,1)\npartition = (2,2)\nmodel = CartesianDiscreteModel(domain,partition)\n\n\u03a9 = Triangulation(model)\nd\u03a9 = Measure(\u03a9,2)\n\nV1 = FESpace(model,ReferenceFE(lagrangian,Float64,1))\nV2 = FESpace(model,ReferenceFE(lagrangian,Float64,1))\nY = MultiFieldFESpace([V1,V2])\n\nr((uh,ph),(v,q)) = \u222b( v*uh + uh*q + ph*q )d\u03a9\nj(xh,dx,dy) = jacobian(xh->r(xh,dy),xh)\n\ne((uh,ph)) = \u222b( uh*uh + uh*ph + ph*ph )d\u03a9\ng(xh,dy) = gradient(xh->e(xh),xh)\n#h(xh,dx,dy) = hessian(xh->e(xh),xh)\n\ndx = get_trial_fe_basis(Y)\ndy = get_fe_basis(Y)\nxh = FEFunction(Y,rand(num_free_dofs(Y)))\n\n#display(r(xh,dy)[\u03a9][end])\n#display(j(xh,dx,dy)[\u03a9][end])\n#display(e(xh)[\u03a9][end])\n#display(g(xh,dy)[\u03a9][end])\n##display(h(xh,dx,dy)[\u03a9][end])\n\n@test j(xh,dx,dy)[\u03a9][end][1,1] != nothing\n@test j(xh,dx,dy)[\u03a9][end][2,1] != nothing\n@test j(xh,dx,dy)[\u03a9][end][1,2] != nothing\n@test j(xh,dx,dy)[\u03a9][end][2,2] != nothing\n@test g(xh,dy)[\u03a9][end][1] != nothing\n@test g(xh,dy)[\u03a9][end][2] != nothing\n\nV1 = FESpace(model,ReferenceFE(lagrangian,Float64,2))\nV2 = FESpace(model,ReferenceFE(lagrangian,Float64,1))\nY = MultiFieldFESpace([V1,V2])\n\ndx = get_trial_fe_basis(Y)\ndy = get_fe_basis(Y)\nxh = FEFunction(Y,rand(num_free_dofs(Y)))\n\n@test j(xh,dx,dy)[\u03a9][end][1,1] != nothing\n@test j(xh,dx,dy)[\u03a9][end][2,1] != nothing\n@test j(xh,dx,dy)[\u03a9][end][1,2] != nothing\n@test j(xh,dx,dy)[\u03a9][end][2,2] != nothing\n@test g(xh,dy)[\u03a9][end][1] != nothing\n@test g(xh,dy)[\u03a9][end][2] != nothing\n\neu(uh) = \u222b( uh*uh )d\u03a9\nep(ph) = \u222b( ph*ph )d\u03a9\neup((uh,ph)) = \u222b( uh*uh + ph*ph )d\u03a9\ngeu(xh,dy) = gradient(xh->eu(xh),xh)\ngep(xh,dy) = gradient(xh->ep(xh),xh)\ngeup(xh,dy) = gradient(xh->eup(xh),xh)\n\nuh,ph=xh\ngeu_uh=geu(uh,dy)\ngep_ph=gep(ph,dy)\ngeup_uh_ph=geup(xh,dy)\n\na=geu_uh[\u03a9]\nb=gep_ph[\u03a9]\nc=geup_uh_ph[\u03a9]\n\n@test all(a .== map(x->x.array[1],c))\n@test all(b .== map(x->x.array[2],c))\n\n\nru(uh,v) = \u222b( v*uh*uh )d\u03a9\nrp(ph,q) = \u222b( q*ph*ph )d\u03a9\nrup((uh,ph),(v,q)) = \u222b( v*uh*uh + q*ph*ph )d\u03a9\nju(xh,dx,dy) = jacobian(xh->ru(xh,dy),xh)\njp(xh,dx,dy) = jacobian(xh->rp(xh,dy),xh)\njup(xh,dx,dy) = jacobian(xh->rup(xh,dy),xh)\n\nuh=FEFunction(V1,get_free_dof_values(xh[1]))\nph=FEFunction(V2,get_free_dof_values(xh[2]))\ndu = get_trial_fe_basis(V1)\ndv = get_fe_basis(V1)\ndp = get_trial_fe_basis(V2)\ndq = get_fe_basis(V2)\n\n\nju_uh=ju(uh,du,dv)\njp_ph=jp(ph,dp,dq)\njup_uh_ph=jup(xh,dx,dy)\n\na=ju_uh[\u03a9]\nb=jp_ph[\u03a9]\nc=jup_uh_ph[\u03a9]\n\n@test all(a .== map(x->x.array[1,1],c))\n@test all(b .== map(x->x.array[2,2],c))\n\nend # module\n", "meta": {"hexsha": "930b3dcbb13ba4fa7d9102fae3b8a5db003f958f", "size": 2599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MultiFieldTests/MultiFieldFEAutodiffTests.jl", "max_stars_repo_name": "davelee2804/Gridap.jl", "max_stars_repo_head_hexsha": "6082973440241759b15cc9cbbdc132d83153cf8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 390, "max_stars_repo_stars_event_min_datetime": "2019-05-16T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:17.000Z", "max_issues_repo_path": "test/MultiFieldTests/MultiFieldFEAutodiffTests.jl", "max_issues_repo_name": "davelee2804/Gridap.jl", "max_issues_repo_head_hexsha": "6082973440241759b15cc9cbbdc132d83153cf8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 576, "max_issues_repo_issues_event_min_datetime": "2019-05-16T20:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:21:35.000Z", "max_forks_repo_path": "test/MultiFieldTests/MultiFieldFEAutodiffTests.jl", "max_forks_repo_name": "davelee2804/Gridap.jl", "max_forks_repo_head_hexsha": "6082973440241759b15cc9cbbdc132d83153cf8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2019-12-30T23:35:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:56:24.000Z", "avg_line_length": 23.8440366972, "max_line_length": 53, "alphanum_fraction": 0.6467872259, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7838335560168996}}
{"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(\u03c0 * 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 / (\u03c0 * 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) / \u03c0) - 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)) / \u03c0 + 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": "using ModelingToolkit\nusing LinearAlgebra\nusing Test\n\nA = [0 1 1 2 2 1 1 2 1 2\n     0 1 -1 -3 -2 2 1 -5 0 -5\n     0 1 2 2 1 1 2 1 1 2\n     0 1 1 1 2 1 1 2 2 1\n     0 2 1 2 2 2 2 1 1 1\n     0 1 1 1 2 2 1 1 2 1\n     0 2 1 2 2 1 2 1 1 2\n     0 1 7 17 14 2 1 19 4 23\n     0 1 -1 -3 -2 1 1 -4 0 -5\n     0 1 1 2 2 1 1 2 2 2]\nN = ModelingToolkit.nullspace(A)\n@test size(N, 2) == 3\n@test rank(N) == 3\n@test iszero(A * N)\n\nA = [0 1 2 0 1 0;\n     0 0 0 0 0 1;\n     0 0 0 0 0 1;\n     1 0 1 2 0 1;\n     0 0 0 2 1 0]\ncol_order = Int[]\nN = ModelingToolkit.nullspace(A; col_order)\ncolspan = A[:, col_order[1:4]]   # rank is 4\n@test iszero(ModelingToolkit.nullspace(colspan))\n@test !iszero(ModelingToolkit.nullspace(A[:, col_order[1:5]]))\n@test !iszero(ModelingToolkit.nullspace(A[:, [col_order[1:4]..., col_order[6]]]))\n", "meta": {"hexsha": "be6fb39b1bfc5e904d08f5b8c658a25d1a9f8b15", "size": 805, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/linalg.jl", "max_stars_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146, "max_stars_repo_stars_event_min_datetime": "2018-03-18T19:25:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-21T16:11:30.000Z", "max_issues_repo_path": "test/linalg.jl", "max_issues_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 198, "max_issues_repo_issues_event_min_datetime": "2018-03-18T17:03:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T08:15:41.000Z", "max_forks_repo_path": "test/linalg.jl", "max_forks_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-03-26T14:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T18:41:19.000Z", "avg_line_length": 25.9677419355, "max_line_length": 81, "alphanum_fraction": 0.5689440994, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7838335504011634}}
{"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 \u2264 low \u2264 high \u2264 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*\u03c0\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\u03b2 = [0.5, 0.2, 0.6]    # Order of derivation\n\n# Definition of the System\nfunction F(t, n, \u03b2, 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, \u03b2, 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 \u2ab0 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) \u2ab0 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": "@testset \"Knapsack\" begin\n    mass    = [1, 5, 3, 7, 2, 10, 5]\n    utility = [1, 3, 5, 2, 5,  8, 3]\n\n    function fitness(n::AbstractVector)\n        total_mass = sum(mass .* n)\n        return (total_mass <= 20) ? sum(utility .* n) : 0\n    end\n\n    initpop = collect(rand(Bool,length(mass)))\n\n    best, invbestfit, generations, tolerance, history = ga(\n        x -> 1 / fitness(x),                    # Function to MINIMISE\n        length(initpop),                        # Length of chromosome\n        initPopulation = initpop,\n        selection = roulette,                   # Options: sus\n        mutation = inversion,                   # Options:\n        crossover = singlepoint,                # Options:\n        mutationRate = 0.2,\n        crossoverRate = 0.5,\n        \u025b = 0.1,                                # Elitism\n        iterations = 20,\n        populationSize = 50,\n        interim = true);\n\n    @test fitness(best) == 21.\n    @test 1. /invbestfit == 21.\n    @test sum(mass .* best) <= 20\nend\n", "meta": {"hexsha": "db24ed236bc098d8fcdc0f76a21c1e5f4462a73f", "size": 1005, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/knapsack.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Evolutionary.jl-e16808c0-8298-5c79-b0aa-b155392dc629", "max_stars_repo_head_hexsha": "4e5ad335d55a109a4d829ac2c7fca73483d52b59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-02T00:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T17:36:27.000Z", "max_issues_repo_path": "test/knapsack.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Evolutionary.jl-e16808c0-8298-5c79-b0aa-b155392dc629", "max_issues_repo_head_hexsha": "4e5ad335d55a109a4d829ac2c7fca73483d52b59", "max_issues_repo_licenses": ["MIT"], "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/knapsack.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Evolutionary.jl-e16808c0-8298-5c79-b0aa-b155392dc629", "max_forks_repo_head_hexsha": "4e5ad335d55a109a4d829ac2c7fca73483d52b59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-02T00:39:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-02T00:39:43.000Z", "avg_line_length": 33.5, "max_line_length": 70, "alphanum_fraction": 0.4895522388, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7837871745014119}}
{"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": "using Sundials, Plots\nusing Test\n\npyplot(size=(700,700))\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  function sysfn(y, fy)\n      fy[1] = y[1]^2 + y[2]^2 - 1.0\n      fy[2] = y[2] - y[1]^2\n  end\n\n  res = Sundials.kinsol(sysfn, ones(2))\n  res |> display\n  println()\n\n  @test round(res, 4) == round([0.786153, 0.618035], 4)\n\nend", "meta": {"hexsha": "e500dfb13070db23f0f7d36eeb39f91ecf2a0cda", "size": 328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/IVP/Sundials01C.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/Sundials01C.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/Sundials01C.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": 16.4, "max_line_length": 55, "alphanum_fraction": 0.5914634146, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.8221891370573386, "lm_q1q2_score": 0.7837723869197497}}
{"text": "function voigt(x, \u03c3, \u03b3)\n    faddeeva(z) = erfcx(-im * z)\n    z = (x + im * \u03b3) / \u03c3 / sqrt(2)\n    return real(faddeeva(z)) / (\u03c3 * 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(\u03c3, \u03b3)\n    @assert \u03c3 > 0\n    @assert \u03b3 > 0\n    fg = \u03c3 * 2.355\n    fl = \u03b3 * 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_\u03c3\u03b3(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((\u03b3 * 2) / (\u03c3 * 2.355));  QSFit.voigt_\u03c3\u03b3(QSFit.voigt_fwhm(\u03c3, \u03b3), log_a), (\u03c3, \u03b3)\n\n\nfunction voigt_\u03b3(fwhm, \u03c3)\n    A = 0.5346\n    B = 0.2166\n    C = (\u03c3 * 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    \u03b3 = fl / 2\n    @assert (fwhm - voigt_fwhm(\u03c3, \u03b3)) / fwhm < 1e-5\n    return \u03b3\nend\n# QSFit.voigt_\u03b3(QSFit.voigt_fwhm(\u03c3, \u03b3), \u03c3), \u03b3\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": "using Quadrature\nusing Base.Test\n\nxsamp = linspace(0.0, 10.0, 11)\nysamp = map(x->x^3, xsamp)\n@test simps(ysamp, xsamp) == 2500.0\n\nxsamp = linspace(0.0, 10.0, 1001)\nysamp = map(x->x^4, xsamp)\n@test_approx_eq simps(ysamp, xsamp) 20000.0\n\n# make sure we give errors for wrong input shape\n# input ans samples are not the same length\n@test_throws ArgumentError simps([0.5, 0.5, 0.3], [0.1, 0.2])\n# simpsons rule needs odd input length\n@test_throws ArgumentError simps([0.5, 0.5, 0.3, 0.2], [0.1, 0.2, 0.3, 0.4])\n", "meta": {"hexsha": "58110b1fac6ac4d07158fd28a288d2d38f72588b", "size": 507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "gabrielgellner/Quadrature", "max_stars_repo_head_hexsha": "0e1858b51fb961f233656c43834996c674fa6e56", "max_stars_repo_licenses": ["MIT"], "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": "gabrielgellner/Quadrature", "max_issues_repo_head_hexsha": "0e1858b51fb961f233656c43834996c674fa6e56", "max_issues_repo_licenses": ["MIT"], "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": "gabrielgellner/Quadrature", "max_forks_repo_head_hexsha": "0e1858b51fb961f233656c43834996c674fa6e56", "max_forks_repo_licenses": ["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.8235294118, "max_line_length": 76, "alphanum_fraction": 0.6863905325, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7837723741412512}}
{"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 \u00f7= 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": "## Julia 1.1.0\n\n# Integer: (min, max)\nprintln(\"\\n\\n---------------- Integer: (min, max) ----------------\")\nfor T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128]\n    println(\"$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]\") \nend\n\n# Integer: overflow\nprintln(\"\\n\\n---------------- Integer: overflow ----------------\")\nmax = typemax(Int64)\nif (max + 1 == typemin(Int64))\n    println(\"Int64 overflow detected \", max, \" + 1 = \", max + 1)\nend\nprintln(\"BigInt(typemax(Int64) + 1) is $(BigInt(typemax(Int64)))\")\n\n# Float: zero\nprintln(\"\\n\\n---------------- Float: zero ----------------\")\nprintln(\"0.0 == 0.0 is \", 0.0 == 0.0)\nprintln(\"bitstring(0.0) is \", bitstring(0.0))\nprintln(\"bitstring(-0.0) is \", bitstring(-0.0))\nprintln(\"1/Inf is \", 1/Inf)\n\n# Float: (min, max)\nprintln(\"\\n\\n---------------- Float: (min, max) ----------------\")\nfor T in [Float32, Float64]\n    println(\"$(lpad(T,7)): [$(typemin(T)), $(typemax(T))], eps: $(eps(T))\")\nend\n\n# Float: eps, nextfloat\nprintln(\"\\n\\n---------------- Float: eps, nextfloat ----------------\")\nfor V in [1e-10, 1e-5, 1.0, 2.0, 10.0, 100.0, 1000.0]\n    println(\"eps($(V)) is $(eps(V)), nextfloat is $(nextfloat(V))\")\nend\n\n# Operator: exponential\nx = 3\nprintln(\"\\n\\n---------------- Operator: exponential ----------------\")\nprintln(\"x = $(x), 2(x-1)^2 - 3(x-1) + 1 = $(2(x-1)^2 - 3(x-1) + 1)\")\nprintln(\"x = $(x), 2^2x = $(2^2x)\")\n", "meta": {"hexsha": "02f002482ad12d93c193a2d8bd94ca547a63a969", "size": 1385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "snippets/integer.jl", "max_stars_repo_name": "fengyfei/sapphire", "max_stars_repo_head_hexsha": "67867fd2746ab4ebe618d088b274fba100ee4a6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-07T04:18:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:18:18.000Z", "max_issues_repo_path": "snippets/integer.jl", "max_issues_repo_name": "fengyfei/sapphire", "max_issues_repo_head_hexsha": "67867fd2746ab4ebe618d088b274fba100ee4a6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippets/integer.jl", "max_forks_repo_name": "fengyfei/sapphire", "max_forks_repo_head_hexsha": "67867fd2746ab4ebe618d088b274fba100ee4a6b", "max_forks_repo_licenses": ["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.7804878049, "max_line_length": 75, "alphanum_fraction": 0.5111913357, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7837225776911063}}
{"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": "## Figures for the Quadratic Equation slides\nusing Plots\nusing LaTeXStrings\npyplot() # nicer output\ntheme(:dark)\n\n##\nquadratic1(a,b,c) = x-> a*x^2 + b*x + c\nplot(-10:0.01:5, quadratic1(0.5, 3, -2.0),\n  linewidth=2,\n  legend=false, framestyle = :origin,\n  xlabel=L\"$x$\", ylabel=L\"$f(x)$\",\n  title=L\"f(x) = $0.5x^2 + 3x -2$\",\n  size=(350,350))e\nsavefig(\"quadratic1.pdf\")\n\n##\nezcontour(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\nquadratic2(A,b) = x -> x'*A*x + x'*b\nezcontour(-3:0.1:3,-3:0.1:3,\n  quadratic2([1 0;0 1],[0,0]))\nplot!(colorbar=false,size=(500,450))\n##\nanim = @animate for i=1:180\n  plot!(camera=(i,30))\nend\ngif(anim, \"quadratic2a.gif\")\n##\nezcontour(-4:0.1:4,-4:0.1:4,\n  quadratic2([1 0.5;0.5 1],[-1,-1.5]))\nplot!(colorbar=false)\n##\nanim = @animate for i=1:180\n  plot!(camera=(i,30))\nend\ngif(anim, \"quadratic2b.gif\")\n##\nQ = [1 0.5; 0.5 1]\ns = [-1,-1.5]\nx = -Q\\(s/2)\n@show x\n##\nusing LinearAlgebra\nQ = [1 0.5; 0.5 1]\ns = [-1,-1.5]\nlam,V = eigen(Q)\np1 = ezcontour(-4:0.1:4,-4:0.1:4,\n  quadratic2(Q,s))\ntitle!(p1, L\"$f(\\mathbf{x})$\")\np2 = ezcontour(-4:0.1:4,-4:0.1:4,\n  quadratic2(Diagonal(lam),V'*s))\ntitle!(p2, L\"$g(\\mathbf{y})$\")\nplot(p1,p2,layout=(2,1), colorbar=false)\n\n##\nplot(p1,p2,layout=(2,1), colorbar=false,size=(300,650))\nsavefig(\"quadratic2b-diag.pdf\")\n\n##\nusing LinearAlgebra\nQ = [1 2; 2 1]\ns = [-1,-1.5]\nlam,V = eigen(Q)\np1 = ezcontour(-4:0.1:4,-4:0.1:4,\n  quadratic2(Q,s))\ntitle!(p1, L\"$f(\\mathbf{x})$\")\np2 = ezcontour(-4:0.1:4,-4:0.1:4,\n  quadratic2(Diagonal(lam),V'*s))\ntitle!(p2, L\"$g(\\mathbf{y})$\")\nplot(p1,p2,layout=(2,1), colorbar=false)\n\n##\n", "meta": {"hexsha": "f4658de111efef6b67b864929b9fa4eeef801a45", "size": 1710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/quadratic-equations.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/quadratic-equations.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/quadratic-equations.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": 21.6455696203, "max_line_length": 55, "alphanum_fraction": 0.5842105263, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7837225734183904}}
{"text": "#=\nfrom \"Error-free transformations in real and complex floating point arithmetics\"\nby Stef Graillat and Val\u00e9rie M\u00e9nissier-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\u00e9rie M\u00e9nissier-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, \u03b4 = 0.0, \u03f5 = 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, \u03b4 = 0.0, \u03f5 = 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(\u03b4=\u03b4, \u03f5=\u03f5, K=K)\n    return ERK(tableau, h, adaptive)\nend\n\n\"\"\"\n    Fehlberg45(; h = 0.0, \u03b4 = 0.0, \u03f5 = 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, \u03b4 = 0.0, \u03f5 = 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(\u03b4=\u03b4, \u03f5=\u03f5, 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, \u03b4 = 0.0, \u03f5 = 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, \u03b4 = 0.0, \u03f5 = 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(\u03b4=\u03b4, \u03f5=\u03f5, 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, \u03b4 = 0.0, \u03f5 = 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, \u03b4 = 0.0, \u03f5 = 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(\u03b4=\u03b4, \u03f5=\u03f5, 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, \u03f5 = 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, \u03f5 = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1 1;\n        1 1;\n    ])\n    newton = NewtonParameters(\u03f5=\u03f5, 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, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order implicit midpoint method.\n\"\"\"\nfunction ImplicitMidpoint(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    CrankNicolson(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order Crank-Nicolson method.\n\"\"\"\nfunction CrankNicolson(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    SDIRK3(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 3rd-order SDIRK method.\n\"\"\"\nfunction SDIRK3(; h = 0.0, \u03f5 = 1e-3, K = 10)\n    \u03b3 = 1/2 + \u221a3/6\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n         \u03b3    \u03b3   0 ;\n        1-\u03b3 1-2\u03b3  \u03b3 ;\n         3   1/2 1/2;\n    ])\n    newton = NewtonParameters(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    GaussLegendre4(; h = 0.0, \u03f5 = 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, \u03f5 = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1/2-\u221a3/6   1/4    1/4-\u221a3/6;\n        1/2+\u221a3/6 1/4+\u221a3/6   1/4   ;\n           4       1/2      1/2   ;\n    ])\n    newton = NewtonParameters(\u03f5=\u03f5, 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, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n    GL6(args...; kwargs...) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 6th-order Gauss\u2013Legendre method.\n\"\"\"\nfunction GaussLegendre6(; h = 0.0, \u03f5 = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        1/2-\u221a15/10     5/36    2/9-\u221a15/15 5/36-\u221a15/30;\n           1/2     5/36+\u221a15/24    2/9     5/36-\u221a15/24;\n        1/2+\u221a15/10 5/36+\u221a15/30 2/9+\u221a15/15     5/36   ;\n            6          5/18       4/9         5/18   ;\n    ])\n    newton = NewtonParameters(\u03f5=\u03f5, 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, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 4th-order Lobatto IIIA method.\n\"\"\"\nfunction LobattoIIIA4(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIB2(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order Lobatto IIIB method.\n\"\"\"\nfunction LobattoIIIB2(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIB4(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 4th-order Lobatto IIIB method.\n\"\"\"\nfunction LobattoIIIB4(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIC2(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 2nd-order Lobatto IIIC method.\n\"\"\"\nfunction LobattoIIIC2(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    LobattoIIIC4(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 4th-order Lobatto IIIC method.\n\"\"\"\nfunction LobattoIIIC4(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIA3(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 3rd-order Radau IA method.\n\"\"\"\nfunction RadauIA3(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIA5(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 5th-order Radau IA method.\n\"\"\"\nfunction RadauIA5(; h = 0.0, \u03f5 = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n            0     1/9   -1/18-\u221a6/18     -1/18+\u221a6/18  ;\n        3/5-\u221a6/10 1/9  11/45+7*\u221a6/360 11/45-43*\u221a6/360;\n        3/5+\u221a6/10 1/9 11/45+43*\u221a6/360  11/45-7*\u221a6/360;\n            5     1/9    4/9+\u221a6/36       4/9-\u221a6/36   ;\n    ])\n    newton = NewtonParameters(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIIA3(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 3rd-order Radau IIA method.\n\"\"\"\nfunction RadauIIA3(; h = 0.0, \u03f5 = 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(\u03f5=\u03f5, K=K)\n    return IRK(tableau, h, newton)\nend\n\n\"\"\"\n    RadauIIA5(; h = 0.0, \u03f5 = 1e-3, K = 10) :: ImplicitRungeKuttaSolver\n\nreturns an [`ImplicitRungeKuttaSolver`](@ref) for the 5th-order Radau IIA method.\n\"\"\"\nfunction RadauIIA5(; h = 0.0, \u03f5 = 1e-3, K = 10)\n    h_T = typeof(h)\n    tableau = ButcherTableau(h_T[\n        2/5-\u221a6/10   11/45-7*\u221a6/360   37/225-169*\u221a6/1800 -2/225+\u221a6/75;\n        2/5+\u221a6/10 37/225+169*\u221a6/1800   11/45+7*\u221a6/360   -2/225-\u221a6/75;\n           1           4/9-\u221a6/36          4/9+\u221a6/36          1/9    ;\n           5           4/9-\u221a6/36          4/9+\u221a6/36          1/9    ;\n    ])\n    newton = NewtonParameters(\u03f5=\u03f5, 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 PyCall\r\nusing Plots\r\n\r\nnp = pyimport(\"numpy\")\r\n\r\n\r\nfunction main()\r\n\r\n    # x = 5\r\n    # x = [\u03c0 3.0 0 12312;\r\n    #      5 12. 1 3412.]\r\n    # display(np.sin(x))\r\n\r\n    x = [1, 2, 3, 4, 5]\r\n    y = [5, 3, 1, 3, 5]\r\n\r\n    p = np.polyfit(x, y, 2)\r\n    # display(p)\r\n\r\n    x1 = 1:0.1:5\r\n    p1 = np.polyval(p, x1)\r\n\r\n    scatter(x, y, label=\"data\")\r\n    plot!(x1, p1, label=\"fit\")\r\n\r\nend\r\n\r\n\r\nmain()\r\n\r\n\r\n", "meta": {"hexsha": "1254ded6d79fb5978bacbe7c5580f0e8b211d2c6", "size": 408, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-learning-src/advance/15-calling_python.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/15-calling_python.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/15-calling_python.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": 12.75, "max_line_length": 32, "alphanum_fraction": 0.4289215686, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7836424763797544}}
{"text": "using Test, PolynomialBases\nimport SymPy\n\ntol = 5.e-15\n\nfor p in 0:6\n    basis_sympy = LobattoLegendre(p, SymPy.Sym)\n    basis_float = LobattoLegendre(p, Float64)\n    @test maximum(abs.( float.(basis_sympy.nodes) - basis_float.nodes )) < tol\n    @test maximum(abs.( float.(basis_sympy.weights) - basis_float.weights )) < tol\n    @test maximum(abs.( float.(basis_sympy.baryweights) - basis_float.baryweights )) < tol\n    @test maximum(abs.( float.(basis_sympy.D) - basis_float.D, )) < 2tol\nend\n@test_throws ArgumentError LobattoLegendre(7, SymPy.Sym)\n\nfor p in 0:4\n    basis_sympy = GaussLegendre(p, SymPy.Sym)\n    basis_float = GaussLegendre(p, Float64)\n    @test maximum(abs.( float.(basis_sympy.nodes) - basis_float.nodes )) < tol\n    @test maximum(abs.( float.(basis_sympy.weights) - basis_float.weights )) < tol\n    @test maximum(abs.( float.(basis_sympy.baryweights) - basis_float.baryweights )) < tol\n    @test maximum(abs.( float.(basis_sympy.D) - basis_float.D, )) < 2tol\nend\n@test_throws ArgumentError GaussLegendre(5, SymPy.Sym)\n\ninterpolation_matrix([-1, 1], LobattoLegendre(4, SymPy.Sym))\ninterpolation_matrix([-1, 1], GaussLegendre(4, SymPy.Sym))\n", "meta": {"hexsha": "d83dbfe26e4dee50306408b0d73e267f4cc35e51", "size": 1160, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sympy_test.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/sympy_test.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/sympy_test.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4285714286, "max_line_length": 90, "alphanum_fraction": 0.7172413793, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7836424763797543}}
{"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.\u03b1')/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": "@testset \"Construction\" begin\n\n    # basic constructor\n    xs = rand(5)\n    ys = rand(5)\n    p = Lagrange(xs, ys)\n    @test all(p.(xs) .\u2248  ys)\n\n    # test weights\n    @test all(p.ws .\u2248  SP.lagrange_barycentric_weights(xs))\n    zs = rand(5)\n    q = Lagrange(xs, p.ws, zs)\n    @test all(q.(xs) .\u2248  zs)\n\n    # fit is alternate\n    q = fit(Lagrange, xs, ys)\n    us = rand(5)\n    @test all(p.(us) .\u2248 q.(us))\n\n    # test one, zero, variable\n    x = variable()\n    q = fit(Lagrange, [1,2,3],[2,3,1])\n    @test iszero(zero(q))\n    @test convert(Polynomial, one(q)) == one(x)\n    @test convert(Polynomial, variable(q)) == x\n\n\nend\n\n@testset \"Conversion\" begin\n\n    xs = [1,2,3]\n    ys = xs.^2\n    p = fit(Lagrange, xs, ys)\n    q = convert(Polynomial, p)\n    @test coeffs(q)  == [0,0,1]\n\n    pp = fit(Lagrange, xs, q)\n    @test coeffs(pp) == coeffs(p)\n\n\nend\n\n@testset \"Evaluation\" begin\n\n    xs = rand(5)\n    ys = sin.(xs)\n    p = Lagrange(xs, ys)\n    @test all(p.(xs) == ys)   # shortcuts  for xs\n    us = rand(5)\n    @test all(abs.(p.(us) - sin.(us)) .<= 1e-1)\n\n    xs, ws = SP.lagrange_barycentric_nodes_weights(Chebyshev, 64)\n    ys = sin.(xs)\n    p = Lagrange(xs, ws, ys)\n    us = 0.1 .+ 0.8*rand(5) # avoid edges...\n    @test all(abs.(sin.(us) - p.(us)) .<=  1e-3)\n\nend\n\n\n@testset \"Arithmetic\" begin\n\n    p = fit(Lagrange, [1,2,3], x -> x^2)\n    q = fit(Lagrange, [2,3,4,5], x -> x^3)\n\n    us = rand(5)\n\n    @test maximum(abs, p.(us) + q.(us) - (p + q).(us)) <= 1e-5\n    @test maximum(abs, p.(us) .* q.(us) - (p * q).(us)) <= 1e-2  # this  can  be way  off for even moderate sized polynomials.\n\n\nend\n\n@testset \"Elementwise operations\" begin\n\n    p = fit(Lagrange, [1,2,3], x -> x^2)\n    p + 1\n    -p\n    2p\n\nend\n\n\n\n\n@testset \"roots\" begin\n\n    q = fit(Lagrange, [2,3,4,5], x -> (x-1)*(x-1/2)*(x+1/2))\n    @test all(roots(q) .\u2248 [-1/2, 1/2, 1])\n\nend\n", "meta": {"hexsha": "d0385fe3771d91f91b38b5de26688a5776cc8bff", "size": 1843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Lagrange.jl", "max_stars_repo_name": "rurz/SpecialPolynomials.jl", "max_stars_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_stars_repo_licenses": ["MIT"], "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/Lagrange.jl", "max_issues_repo_name": "rurz/SpecialPolynomials.jl", "max_issues_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_issues_repo_licenses": ["MIT"], "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/Lagrange.jl", "max_forks_repo_name": "rurz/SpecialPolynomials.jl", "max_forks_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_forks_repo_licenses": ["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.8172043011, "max_line_length": 126, "alphanum_fraction": 0.5274009767, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7836069983136233}}
{"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": "# example copied from th0br0 with modifications\nusing CmdStan\n\ny = collect(1:100);\nx = [3:3:300 5:5:500];\n\nmodel = \"\"\"\ndata {\n  int<lower = 0> N;\n  int<lower = 0> k;\n  matrix[N, k] x;\n  real<lower=0> y[N];\n}\nparameters {\n  vector[k] beta; \n  real<lower=0> sigma;\n}\nmodel {\n  y ~ normal(x * beta, sigma);\n}\n\"\"\";\n\n# beta parameters are accessed using beta.[1-9+] syntax\ndata = Dict(\"N\"=>100, \"k\" => 2, \"x\" => x, \"y\" => y);\nstanmodel = Stanmodel(monitors = [\"beta.1\", \"beta.2\", \"sigma\"], model=model,\n          output_format=:mcmcchains);\n\nrc, sim, cnames = stan(stanmodel, data; diagnostics = false);\n\ncnames |> display\n# 3-element Array{String,1}: \"beta.1\", \"beta.2\" ,\"sigma\" \nprintln()\n\ndescribe(sim)\n", "meta": {"hexsha": "985df6df75483b434f8e48c1bc96dd4d875c3e39", "size": 701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Monitors_example/normal_monitors.jl", "max_stars_repo_name": "UnofficialJuliaMirror/CmdStan.jl-593b3428-ca2f-500c-ae53-031589ec8ddd", "max_stars_repo_head_hexsha": "c8f6404e11637b3cfd57950f5b18416c862da798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2018-11-17T10:38:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T17:23:55.000Z", "max_issues_repo_path": "examples/Monitors_example/normal_monitors.jl", "max_issues_repo_name": "UnofficialJuliaMirror/CmdStan.jl-593b3428-ca2f-500c-ae53-031589ec8ddd", "max_issues_repo_head_hexsha": "c8f6404e11637b3cfd57950f5b18416c862da798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 93, "max_issues_repo_issues_event_min_datetime": "2018-05-17T04:41:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T15:07:20.000Z", "max_forks_repo_path": "examples/Monitors_example/normal_monitors.jl", "max_forks_repo_name": "UnofficialJuliaMirror/CmdStan.jl-593b3428-ca2f-500c-ae53-031589ec8ddd", "max_forks_repo_head_hexsha": "c8f6404e11637b3cfd57950f5b18416c862da798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:34:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-26T20:46:07.000Z", "avg_line_length": 20.0285714286, "max_line_length": 76, "alphanum_fraction": 0.6091298146, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7836069948815028}}
{"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\u00d74 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": "include(\"../aimajulia.jl\");\n\nusing Test;\n\nusing Main.aimajulia;\n\n#The following mdp tests are from the aima-python doctests\n\ntm = Dict([Pair(\"A\", Dict([Pair(\"a1\", (0.3, \"B\")), Pair(\"a2\", (0.7, \"C\"))])),\n            Pair(\"B\", Dict([Pair(\"a1\", (0.5, \"B\")), Pair(\"a2\", (0.5, \"A\"))])),\n            Pair(\"C\", Dict([Pair(\"a1\", (0.9, \"A\")), Pair(\"a2\", (0.1, \"B\"))]))]);\n\nmdp = MarkovDecisionProcess(\"A\", Set([\"a1\", \"a2\"]), Set([\"C\"]), tm, states=Set([\"A\",\"B\",\"C\"]));\n\n@test (transition_model(mdp, \"A\", \"a1\") == (0.3, \"B\"));\n\n@test (transition_model(mdp, \"B\", \"a2\") == (0.5, \"A\"));\n\n@test (transition_model(mdp, \"C\", \"a1\") == (0.9, \"A\"));\n\n@test (repr(value_iteration(aimajulia.sequential_decision_environment, epsilon=0.01)) == \n        \"Dict((2, 3)=>0.486437,(2, 1)=>0.398102,(3, 1)=>0.509285,(1, 4)=>0.129589,(3, 3)=>0.795361,(1, 3)=>0.344613,(3, 2)=>0.649581,(2, 4)=>-1.0,(1, 1)=>0.295435,(1, 2)=>0.253487,(3, 4)=>1.0)\");\n\npi = optimal_policy(aimajulia.sequential_decision_environment, value_iteration(aimajulia.sequential_decision_environment, epsilon=0.01));\n\n@test (repr(pi) == \"Dict{Any,Any}((2, 3)=>(1, 0),(2, 1)=>(1, 0),(3, 1)=>(0, 1),(1, 4)=>(0, -1),(3, 3)=>(0, 1),(1, 3)=>(1, 0),(3, 2)=>(0, 1),(2, 4)=>nothing,(1, 1)=>(1, 0),(1, 2)=>(0, 1),(3, 4)=>nothing)\");\n\n@test (repr(to_arrows(aimajulia.sequential_decision_environment, pi)) == \"Union{Nothing, String}[\\\"v\\\" \\\">\\\" \\\"v\\\" \\\"<\\\"; \\\"v\\\" nothing \\\"v\\\" \\\".\\\"; \\\">\\\" \\\">\\\" \\\">\\\" \\\".\\\"]\");\n\n@test (policy_iteration(aimajulia.sequential_decision_environment) == \n        Dict([Pair((2,3),(1,0)),\n            Pair((2,1),(1,0)),\n            Pair((3,1),(0,1)),\n            Pair((1,4),(0,-1)),\n            Pair((3,3),(0,1)),\n            Pair((1,3),(1,0)),\n            Pair((3,2),(0,1)),\n            Pair((2,4),nothing),\n            Pair((1,1),(1,0)),\n            Pair((1,2),(0,1)),\n            Pair((3,4),nothing)]));\n\n", "meta": {"hexsha": "dbed6b3717c26f4000e6ad7892ea28bf7f603563", "size": 1866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/run_mdp_tests.jl", "max_stars_repo_name": "mikhail-j/aima-julia-aimacode-fork", "max_stars_repo_head_hexsha": "07ea7acd534266fd2b10ee0d4aeb847a88225ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 131, "max_stars_repo_stars_event_min_datetime": "2016-07-23T14:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:49:47.000Z", "max_issues_repo_path": "tests/run_mdp_tests.jl", "max_issues_repo_name": "mikhail-j/aima-julia-aimacode-fork", "max_issues_repo_head_hexsha": "07ea7acd534266fd2b10ee0d4aeb847a88225ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-03-30T19:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-08T16:35:26.000Z", "max_forks_repo_path": "tests/run_mdp_tests.jl", "max_forks_repo_name": "mikhail-j/aima-julia-aimacode-fork", "max_forks_repo_head_hexsha": "07ea7acd534266fd2b10ee0d4aeb847a88225ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 65, "max_forks_repo_forks_event_min_datetime": "2016-09-24T17:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:49:50.000Z", "avg_line_length": 43.3953488372, "max_line_length": 205, "alphanum_fraction": 0.4973204716, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7835996334161498}}
{"text": "\"Square the sum of the first `n` positive integers\"\nfunction square_of_sum(n::Int)\n\nend\n\n\"Sum the squares of the first `n` positive integers\"\nfunction sum_of_squares(n::Int)\n\nend\n\n\"Subtract the sum of squares from square of the sum of the first `n` positive ints\"\nfunction difference(n::Int)\n\nend\n", "meta": {"hexsha": "1b7d15405c147523319cb45201c7aa753fbf651d", "size": 297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/difference-of-squares/difference-of-squares.jl", "max_stars_repo_name": "Wikunia/julia-1", "max_stars_repo_head_hexsha": "689acea0966793aee10f95394337ffe3ec439364", "max_stars_repo_licenses": ["MIT"], "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/difference-of-squares/difference-of-squares.jl", "max_issues_repo_name": "Wikunia/julia-1", "max_issues_repo_head_hexsha": "689acea0966793aee10f95394337ffe3ec439364", "max_issues_repo_licenses": ["MIT"], "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/difference-of-squares/difference-of-squares.jl", "max_forks_repo_name": "Wikunia/julia-1", "max_forks_repo_head_hexsha": "689acea0966793aee10f95394337ffe3ec439364", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-11T20:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-11T20:28:18.000Z", "avg_line_length": 19.8, "max_line_length": 83, "alphanum_fraction": 0.7575757576, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7835996333383252}}
{"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    \u03a3::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    \u03a3 = TRANSITION * s.\u03a3 * TRANSITION' + noise\n    State(p, v, \u03a3)\nend\n\nfunction update(predicted::State, observed::State)\n    K = predicted.\u03a3 / (predicted.\u03a3 + observed.\u03a3)\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    \u03a3 = predicted.\u03a3 - K * predicted.\u03a3\n    State(p, v, \u03a3)\nend\n\nfunction smoothed_velocity_estimate(old::State, new::State, \u03bb)\n    diff = new.p - old.p\n    scale = \u03bb\n    #scale = 1.0 - 0.5 * (1 - \u03bb) * (1 + 1.0 / sqrt(2\u03c0 * old.\u03a3[2, 2]^2))\n    return scale * diff + (1 - scale) * old.v\nend\n\nfunction pdf(s::State, p::Float64)\n    \u03c3 = s.\u03a3[1, 1]\n    exp(-((s.p - p)^2) / (2\u03c3^2)) / (sqrt(2\u03c0 * \u03c3^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\u03bb = 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/\u03bb\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\u00e9zout 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\u03ba = @. sin(xy[:,1]) * (1+xy[:,2]^2) + 1.0\nf = 1e5 * @. xy[:,1] + xy[:,2]\nK = compute_fem_laplace_matrix1(\u03ba, 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_\u03ba = squeeze(fc(xy, [20,20,20,1])) + 1\nK = compute_fem_laplace_matrix1(nn_\u03ba, 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_\u03ba)\nclose(\"all\")\nfigure(figsize=(18,5))\nsubplot(131)\nvisualize_scalar_on_gauss_points(\u03ba, mmesh)\ntitle(\"Reference\")\nsubplot(132)\nvisualize_scalar_on_gauss_points(nn_val, mmesh)\ntitle(\"DNN\")\nsubplot(133)\nvisualize_scalar_on_gauss_points(abs.(\u03ba-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": "\n@testset \"FNT 1D\" begin\n    for t in BigInt.(1:13)\n        @show t\n        x = [1:2^(t+1);] .|> BigInt\n        @show length(x)\n        g = 2 |> BigInt\n        q = 2^2^t + 1 |> BigInt\n        @time  @test ifnt(fnt(x, g, q), g, q) == x\n    end\nend\n\n@testset \"FNT and NTT coherence\" begin\n    # FNT is special case with faster implementation of general NTT and should\n    # give the same results \n    t = 2\n    F_t = 2^2^t + 1 #a Fermat number\n    x = [1:8;]\n\n    @test fnt(x, 2, F_t) == ntt(x, 2, F_t)\nend\n\n@testset \"FNT 1D convolution\" begin\n    using DSP\n\n    t = 3\n    q = 2^2^t + 1\n    g = 2\n    # padding inputs with zeros to get non circular convolution\n    x = [1:8; zeros(Int, 8);]\n    h = [1:8; zeros(Int, 8);]\n    X = fnt(x, g, q)\n    H = fnt(h, g, q)\n    Y = mod.(X .* H, q)\n    y = ifnt(Y, g, q)\n    \n    @test y[1:15] == DSP.conv(1:8, 1:8)\nend\n\n@testset \"FNT 2D\" begin\n    t = 2\n    q = 2^2^t + 1\n    g = 2\n    x = mod.(rand(Int, 8, 8), q)\n    @test ifnt(fnt(x, g, q), g, q) == x\n\n    t = 4\n    q = 2^2^t + 1\n    g = 314\n    x = mod.(rand(Int, 512, 512), q)\n    @test ifnt(fnt(x, g, q), g, q) == x\nend\n\n@testset \"FNT 2D convolution\" begin\n    using DSP\n\n    t = 3\n    q = 2^2^t + 1\n    g = 2\n    x = mod.(rand(Int, 8, 8), 5)\n    x_padded = zeros(Int64, 16, 16)\n    x_padded[1:8, 1:8] = x\n    h = mod.(rand(Int, 8, 8), 3)\n    h_padded = zeros(Int64, 16, 16)\n    h_padded[1:8, 1:8] = h\n    X = fnt(x_padded, g, q)\n    H = fnt(h_padded, g, q)\n    Y = mod.(X .* H, q)\n    y = ifnt(Y, g, q)\n    \n    @test y[1:15, 1:15] == DSP.conv(x, h)\nend\n\n@testset \"FNT in-place\" begin\n    t = 2\n    q = 2^2^t + 1\n    g = 2\n\n    x = mod.(rand(Int, 8), q)\n    y = fnt(x, g, q)\n    @test x != y\n    fnt!(x, g, q)\n    @test x == y\n\n    x = mod.(rand(Int, 8, 8), q)\n    y = fnt(x, g, q)\n    @test x != y\n    fnt!(x, g, q)\n    @test x == y\n\nend\n\n@testset \"FNT fails for non fermat modulus\" begin\n    (g, q, n) = (2, 31, 5)\n    x = [1:n;]\n    @test_throws AssertionError fnt(x, g, q)\n\n    (g, q, n) = (2, 33, 10)\n    x = [1:n;]\n    @test_throws AssertionError fnt(x, g, q)\nend\n\n@testset \"isfermat() tests\" begin\n    known = map(n->2^2^n+1, [0:4;])\n    expected = map(v -> v in known, [1:maximum(known);])\n    actual = isfermat.([1:maximum(known);])\n\n    @test expected == actual\nend\n\n@testset \"modfermat() tests\" begin\n   \n    for t in 0:3\n        q = 2^2^t+1\n        x = 0:(q-1)^2\n        @test mod.(x, q) == modfermat.(x, q)\n    end\n\n    for t in 0:10\n        q = BigInt(2)^2^t+1\n        limit = (q-1)^2\n        x = mod.(rand(0:limit, 1000), (q-1)^2)\n        @test mod.(x, q) == modfermat.(x, q)\n    end\nend", "meta": {"hexsha": "4d5beadf62d5c76dd479523cd74536250186e6aa", "size": 2597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fnt.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": "test/fnt.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": "test/fnt.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": 20.776, "max_line_length": 78, "alphanum_fraction": 0.4793993069, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.783577662643975}}
{"text": "\nusing SparseArrays\nusing StatsBase\nusing LinearAlgebra\nusing Random\nusing ProgressMeter\nusing LinearAlgebra\nusing Test\nusing ForwardDiff\nusing Calculus\n#include(\"core.jl\")\nJ=GeoPhyInv\n\n\nnx=5\nnz=5\nnznx=nz*nx\nddx=22.5\nddz=10.3\n\np=randn(nznx+1)\np[end]=0.0\nQ=abs.(randn(nz,nx))\n\u03c3=abs.(randn(nz,nx))\npsi0=randn(nznx)\n\n#paA=Param(nx,nz,\u03c3)\t\n#paB=Param(nx,nz,Q)\n#A=paA.A\n#B=paB.A\n\nfunction func_test(x,p)\n\tglobal psi0\n\tx=reshape(x,nz,nx)\n\tpaA=J.Poisson.Param(nx,nz,x)\t\n\n\tpsi=vec(J.Poisson.applyinvA(p,paA))\n\tf= sum(abs2,psi.-psi0)\n\treturn f\nend\n\n\nfunction grad_test(x,p)\n\tglobal psi0\n\tpaA=J.Poisson.Param(nx,nz,x)\t\n\n\tpsi=vec(J.Poisson.applyinvA(p,paA))\n\n\tadjsrc=-2.0*(psi.-psi0)\n\n\tlambda=vec(J.Poisson.applyinvAt(adjsrc,paA))\n\t#println(size(lambda))\n\t\n\treturn vec((lambda*psi'))'*hcat(vec.(paA.dAdx)...)\nend\n\nf = x->func_test(x, p);\n\ngcalc = Calculus.gradient(f);\ng3=reshape(gcalc(vec(\u03c3)),nz,nx);\n\ng2=reshape(grad_test(\u03c3,p),nz,nx)\n\n\n@test \u2248(g2,g3, rtol=1e-5)\n", "meta": {"hexsha": "c505b31901ee4980fbab97f5c1f0e2083ee61e74", "size": 952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Poisson/adj_state.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": "test/Poisson/adj_state.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": "test/Poisson/adj_state.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": 14.4242424242, "max_line_length": 51, "alphanum_fraction": 0.6995798319, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7835776614859504}}
{"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\u00e9rmica\\n\", color =:blue);\n\n# em gramas\n\u0394m = 0.01;\nmcopo = 51.82;\nmaq = 122.07;\nmaf = 125.02;\n\n# em graus celsius\n\u0394T = 0.1;\ntaf = 12.4;\ntaq = 53.2;\ntf = 31.4;\n\n# calor especifico da \u00e1gua\nca = 1; \n@printf(\"%.3f \u00b7 %.3f ( %.3f - %.3f) / (%.3f - %.3f) - %.3f \u00b7 %.3f \\n\", maq,ca,taq,tf,tf,taf,maf,ca);\nC = maq * ca * ( (taq - tf) / (tf - taf) ) - maf * ca;\n\n\u0394C = ((\u0394m * taq + \u0394T * maq) * (tf - taf) + (2 * \u0394T) * (maq * taq) ) / (tf - taf)^2\n\nprintln(\"\\nCapacidade t\u00e9rmica do calorimetro\");\n@printf(\"Ccal = %.2f \u00b1 %.2f \\n\", C, \u0394C);\n\n# em grama \nmcopo = 51.82 \u00b1  \u0394m;\ncAluminio = 0.218; \nCcopo =  mcopo * cAluminio;\n\nprintln(\"\\nCapacidade t\u00e9rmica do copo\");\n@printf(\"Ccopo = %.3f \u00b1 %0.3f \\n\", Ccopo.val, Ccopo.err);\n\n\nprintln(\"\\nRela\u00e7\u00e3o de equival\u00eancia\");\n@printf(\"| x1 - x2 | < 2 \u00b7 (\u03c31 + \u03c32) \\n\");\n@printf(\"| %.3f - %.3f| < 2 \u00b7 (%.3f + %.3f) \\n\", C,Ccopo.val,\u0394C,Ccopo.err);\nprintln(abs(C - Ccopo.val) < 2 * (\u0394C + Ccopo.err));\n\n\nprintstyled(\"\\nExperimento 2: Calor espec\u00edfico de um metal  \", color =:blue);\n\n# em gramas \nmobjeto = 205.75 \u00b1 \u0394m;\nma = 216.07 \u00b1 \u0394m;     \n\n# em graus celsius\nta = 13.1 \u00b1 \u0394T;\nto = 97.1 \u00b1 \u0394T;\ntf = 19.2 \u00b1 \u0394T;\n\n\nco = ((ma * ca + C ) * (ta - tf)) / (mobjeto * (tf - to));\n\nprintln(\"\\nCalor espec\u00edfico de um metal\");\n@printf(\"Co = %.4f \u00b1 %.4f \\n\", co.val, co.err);\n\n\nprintstyled(\"\\nExperimento 3: Calor latente de condensa\u00e7\u00e3o da \u00e1gua\\n\",color=:blue);\n\nta = 8.8  \u00b1 \u0394T;\ntf = 71.7  \u00b1 \u0394T;\ntc = 100  \u00b1 \u0394T;\n\nma = 167.479  \u00b1 \u0394m;\nmc = 187.02 - ma  \u00b1 \u0394m;\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 \u00b1 %.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": "@testset \"Type Stability\" begin\n    function rosenbrock(x::Vector{T}) where T\n        o = one(T)\n        c = convert(T,100)\n        return (o - x[1])^2 + c * (x[2] - x[1]^2)^2\n    end\n\n    function rosenbrock_gradient!(storage::Vector{T}, x::Vector{T}) where T\n        o = one(T)\n        c = convert(T,100)\n        storage[1] = (-2*o) * (o - x[1]) - (4*c) * (x[2] - x[1]^2) * x[1]\n        storage[2] = (2*c) * (x[2] - x[1]^2)\n    end\n\n    function rosenbrock_hessian!(storage::Matrix{T}, x::Vector{T}) where T\n        o = one(T)\n        c = convert(T,100)\n        f = 4*c\n        storage[1, 1] = (2*o) - f * x[2] + 3 * f * x[1]^2\n        storage[1, 2] = -f * x[1]\n        storage[2, 1] = -f * x[1]\n        storage[2, 2] = 2*c\n    end\n\n    for method in (NelderMead(),\n                   SimulatedAnnealing(),\n                   BFGS(),\n                   ConjugateGradient(),\n                   GradientDescent(),\n                   MomentumGradientDescent(),\n                   AcceleratedGradientDescent(),\n                   LBFGS(),\n                   Newton())\n        for T in (Float32, Float64)\n            result = optimize(rosenbrock, rosenbrock_gradient!, rosenbrock_hessian!, fill(zero(T), 2), method)\n            @test eltype(Optim.minimizer(result)) == T\n        end\n    end\nend\n", "meta": {"hexsha": "4ed9f8c2ffdb3219cda687265d92bb3942a64220", "size": 1292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/general/type_stability.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Optim.jl-429524aa-4258-5aef-a3af-852621145aeb", "max_stars_repo_head_hexsha": "312983bd17229a6486fc9a8f3a157e56deeee65a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 679, "max_stars_repo_stars_event_min_datetime": "2017-02-15T17:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:12:30.000Z", "max_issues_repo_path": "test/general/type_stability.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Optim.jl-429524aa-4258-5aef-a3af-852621145aeb", "max_issues_repo_head_hexsha": "312983bd17229a6486fc9a8f3a157e56deeee65a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 599, "max_issues_repo_issues_event_min_datetime": "2017-02-13T07:13:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T11:56:03.000Z", "max_forks_repo_path": "test/general/type_stability.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Optim.jl-429524aa-4258-5aef-a3af-852621145aeb", "max_forks_repo_head_hexsha": "312983bd17229a6486fc9a8f3a157e56deeee65a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 171, "max_forks_repo_forks_event_min_datetime": "2017-02-25T09:54:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T13:17:10.000Z", "avg_line_length": 32.3, "max_line_length": 110, "alphanum_fraction": 0.4713622291, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7834796296258271}}
{"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": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing DataFrames\nusing CSV\nusing StatsBase\nusing Distributions\nusing StatsPlots\n\n# %% 4.7 - 4.11\nd = DataFrame(CSV.File(datadir(\"exp_raw/Howell_1.csv\")))\n# precis(d)\nd.height\n\nd2 = filter(row -> row.age >= 18, d)    # either\nd2 = d[d.age .>= 18, :]                 # or\n\n# %% 4.12, 4.13\nplot(p -> pdf(Normal(178, 20), p), 100:250)\nplot(p -> pdf(Uniform(0, 50), p), -10:60)\n\n# %% 4.14\nN = 10_000\nd_\u03bc = Normal(178, 20)\nsample_mu = rand(d_\u03bc, N)\nd_\u03c3 = Uniform(0, 50)\nsample_sigma = rand(d_\u03c3, N)\n\nprior_h = rand.(Normal.(sample_mu, sample_sigma))\ndensity(prior_h)\n\n# %% 4.15\nd_\u03bc_100 = Normal(178, 100)\nsample_\u03bc_100 = rand(d_\u03bc_100, N)\n\nsample_height_100 = rand.(Normal.(sample_\u03bc_100, sample_sigma))\n# or is\n# mix = MixtureModel(Normal.(sample_\u03bc_100, sample_sigma))\n# sample_height_100 = rand(mix, N)\n# more correct?\ndensity(sample_height_100)\n\n# %% 4.16, 4.17\n\u03bc_grid = range(150, 160, length = 100)\n\u03c3_grid = range(7, 9, length = 100)\npost = [(; :\u03bc => \u03bc, :\u03c3 => \u03c3) for \u03bc in \u03bc_grid, \u03c3 in \u03c3_grid]  # this is `post`\n\nll = [loglikelihood(Normal(\u03bc, \u03c3), d2.height) for (\u03bc, \u03c3) in post]\nprior = [logpdf(d_\u03bc, \u03bc) + logpdf(d_\u03c3, \u03c3) for (\u03bc, \u03c3) in post]\nlposterior = ll .+ prior\nlposterior .-= maximum(lposterior)\nposterior = exp.(lposterior)\n\nwireframe(\u03bc_grid, \u03c3_grid, posterior)\n\n# %% 4.19 - 4.22\nsamples = sample(post, pweights(posterior), N) |> DataFrame\n\nscatter(samples.\u03bc, samples.\u03c3, alpha = 0.05, ms = 5, xlabel = \"\u03bc\", ylabel = \"\u03c3\")\n\ndensity(samples.\u03bc)\ndensity(samples.\u03c3)\n\nquantile(samples.\u03bc, (0.1, 0.9))\nquantile(samples.\u03c3, (0.1, 0.9))\n\n# %% 4.23 - 4.25\nd3_height = d2.height[1:20]\n\u03bc_grid = range(140, 160, length = 200)\n\u03c3_grid = range(4, 20, length = 200)\npost = [(\u03bc = \u03bc, \u03c3 = \u03c3) for \u03bc in \u03bc_grid, \u03c3 in \u03c3_grid]\n\nll = [loglikelihood(Normal(\u03bc, \u03c3), d3_height) for (\u03bc, \u03c3) in post]\nprior = [logpdf(d_\u03bc, \u03bc) + logpdf(d_\u03c3, \u03c3) for (\u03bc, \u03c3) in post]\nlposterior = ll .+ prior\nlposterior .-= maximum(lposterior)\nposterior = exp.(lposterior)\n\nwireframe(\u03bc_grid, \u03c3_grid, posterior)\n\nsamples2 = sample(post, pweights(posterior), N) |> DataFrame\n\nscatter(samples2.\u03bc, samples2.\u03c3, alpha = 0.05, ms = 5)\ndensity(samples2.\u03bc)\ndensity(samples2.\u03c3)\n", "meta": {"hexsha": "c6e2976a1791dd0a8127c2af40f81ee2bc5f0324", "size": 2154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/snippet_04_07.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_04_07.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_04_07.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.7586206897, "max_line_length": 79, "alphanum_fraction": 0.6573816156, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7834649088912679}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, KernelDensity, Plots\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.16\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.16\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u255045f535f0-250a-11eb-2a6b-03853e2d8eb1\n# \u2560\u255045f5722a-250a-11eb-2840-a7d3dd59711b\n# \u255f\u2500475ff888-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`\u00b2) 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`\u00b2) 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\u2070 = f(x[end])                # f(0)\n    x\u207b = x[1:end-1]                # the x < 0 Kronrod points\n    fx = f.(x\u207b) .+ f.((-).(x\u207b))    # f(x < 0) + f(x > 0)\n    I = sum(fx .* w[1:end-1]) + fx\u2070 * w[end]\n    if isodd(n)\n        E = abs(sum(fx[2:2:end] .* wg[1:end-1]) + fx\u2070*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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 853ac7d0-12f3-11eb-1b1c-993e336cf23a\nmd\"\"\"\n## How does indexing work?\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 314ba27a-12ec-11eb-12ce-67650c0020b7\narr = [34,45,67]\n\n# \u2554\u2550\u2561 ab3afe6e-12f3-11eb-196a-79d26b66f681\nmd\"\"\"\nWe know that we can index into it using square brackets:\n\"\"\"\n\n# \u2554\u2550\u2561 b32acfda-12f3-11eb-323d-ef91b9ff9f0d\narr[2]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3a202684-12ec-11eb-26fc-df7b7484e671\nMeta.@lower arr[2]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f10cf87a-12f3-11eb-1104-0186b9e43757\nmd\"\"\"\n## Example: A zero-based vector\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1ac0095e-12eb-11eb-3df2-e98d0ff66dd5\nstruct ZeroFirstVector{T} <: AbstractVector{T}\n\tarray::Vector{T}\nend\n\n# \u2554\u2550\u2561 a66afe14-12eb-11eb-3afc-fdac2325ff84\nBase.size(vec::ZeroFirstVector) = size(vec.array)\n\n# \u2554\u2550\u2561 e86c53fa-12eb-11eb-0ee4-41455a218d84\nBase.axes(vec::ZeroFirstVector) = (0:length(vec.array)-1,)\n\n# \u2554\u2550\u2561 69b10842-12eb-11eb-381a-0bda698a59ed\nBase.getindex(vec::ZeroFirstVector, i::Int) = vec.array[i+1]\n\n# \u2554\u2550\u2561 9c57e4aa-12eb-11eb-16fb-c7a18c238192\nzarr = ZeroFirstVector([1, 3, 4])\n\n# \u2554\u2550\u2561 3cf51826-12f4-11eb-2405-db9616fa3152\nmd\"\"\"\nNow we are able to use zero-based indexing!:\n\"\"\"\n\n# \u2554\u2550\u2561 fed5e2e4-12eb-11eb-169f-8b050f9eea4a\nzarr[0]\n\n# \u2554\u2550\u2561 464c22f2-12f4-11eb-0b3c-872621c385f6\nmd\"\"\"\n## Modifying elements: `setindex!`\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5b8f3508-12ec-11eb-0a31-61ddf796ac74\nMeta.@lower arr[2] = 3\n\n# \u2554\u2550\u2561 0c8ebad2-12ec-11eb-03f1-c5b9c79bb4da\nBase.setindex!(vec::ZeroFirstVector, val, i::Int) = (vec.array[i+1] = val)\n\n# \u2554\u2550\u2561 8438424c-12ec-11eb-1de2-0bb3924ec78c\nzarr[0] = 55\n\n# \u2554\u2550\u2561 9cee3206-12ec-11eb-09c7-1f0ebad11b8e\nzarr\n\n# \u2554\u2550\u2561 b0ab2844-12ec-11eb-1908-0318510b3292\nmd\"\"\"\n### Julia gives you added bonuses here:\n\"\"\"\n\n# \u2554\u2550\u2561 bc8154b8-12ec-11eb-1fcc-4765fcd0796d\nzarr[0:1]\n\n# \u2554\u2550\u2561 8c0c8188-12f4-11eb-1576-23958903a69a\n@which zarr[0:1]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c67fbbbc-12ec-11eb-32be-2ff720964fe6\nzarr[ [2, 1, 0] ]\n\n# \u2554\u2550\u2561 d13a65b6-12ec-11eb-2996-37987cfae782\nzarr[0:1] .= [7,8];\n\n# \u2554\u2550\u2561 dbb95f42-12ec-11eb-01d5-df2e21affd86\nzarr\n\n# \u2554\u2550\u2561 e6428aa6-12ec-11eb-06d0-95404a8a4039\nzarr[ [2, 1, 0] ] .= [1, 2, 3];\n\n# \u2554\u2550\u2561 e21658ec-12ef-11eb-06fd-b1d282edf7b6\nzarr\n\n# \u2554\u2550\u2561 b405b9ac-12f4-11eb-12fa-f7575ff1fa73\nmd\"\"\"\nVarious other functions also automatically work, e.g.:\n\"\"\"\n\n# \u2554\u2550\u2561 e57329a2-12ef-11eb-165d-51f080c73652\nsort!(zarr)\n\n# \u2554\u2550\u2561 e8b34188-12ef-11eb-2d7f-fde100b582d1\nmd\"\"\"\n### Some more examples\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f0d952da-12ef-11eb-2452-471b184bc529\nr = 53:83\n\n# \u2554\u2550\u2561 0fc7e3e6-12f0-11eb-1b49-e37196154ec6\nsize(r)\n\n# \u2554\u2550\u2561 03b23fe0-12f0-11eb-0970-33b3b973e902\nr[20]\n\n# \u2554\u2550\u2561 00088cda-12f0-11eb-36b7-9b900fa6d0bf\ntypeof(r)\n\n# \u2554\u2550\u2561 f6024924-12ef-11eb-1d6c-3ffff2546914\nsupertypes(typeof(r))\n\n# \u2554\u2550\u2561 cdf3e532-12f4-11eb-1ce0-873bcf0dea58\nmd\"\"\"\nLet's also look at what happens if we reshape an array:\n\"\"\"\n\n# \u2554\u2550\u2561 f9bf5200-12ef-11eb-30ee-9b3cbbccc886\nA = reshape(1:12, 3, 4)\n\n# \u2554\u2550\u2561 07c1cdb6-12f1-11eb-0b31-15b5c88caac6\ntypeof(A)\n\n# \u2554\u2550\u2561 09d69238-12f1-11eb-1d9f-f72e8c6c14d9\nsupertypes(typeof(A))\n\n# \u2554\u2550\u2561 ff598e1c-12f0-11eb-24f6-bdaa74db2ad7\nsize(A)\n\n# \u2554\u2550\u2561 2f23dd4e-12f0-11eb-01fc-53f66d2a55e4\nA\u1d40 = transpose(A)\n\n# \u2554\u2550\u2561 ea8e0794-12f0-11eb-2194-bdc46224dc69\nsize(A\u1d40)\n\n# \u2554\u2550\u2561 2a76a87a-12f1-11eb-3e58-e5f919ba81e8\n@which A\u1d40[2,3]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 da41895c-12f4-11eb-2ee4-f1ffc4344f61\nmd\"\"\"\n## Conclusions\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500e1a3f480-12e7-11eb-01db-71003ec47f08\n# \u255f\u250051a660b4-12f3-11eb-2b8a-f5544e650b1c\n# \u255f\u2500853ac7d0-12f3-11eb-1b1c-993e336cf23a\n# \u255f\u250094bb1e6c-12f3-11eb-2e18-bb232d2c9cfe\n# \u2560\u2550314ba27a-12ec-11eb-12ce-67650c0020b7\n# \u255f\u2500ab3afe6e-12f3-11eb-196a-79d26b66f681\n# \u2560\u2550b32acfda-12f3-11eb-323d-ef91b9ff9f0d\n# \u255f\u2500b53bc5ba-12f3-11eb-2b09-d38cc266b069\n# \u2560\u25503a202684-12ec-11eb-26fc-df7b7484e671\n# \u255f\u2500c225d324-12f3-11eb-23d7-45548e7b32b6\n# \u255f\u2500d92c5aa2-12f3-11eb-286e-8769ecdf03cb\n# \u255f\u2500f10cf87a-12f3-11eb-1104-0186b9e43757\n# \u255f\u2500f7cadd08-12f3-11eb-1882-8dd4ce8ee2c2\n# \u2560\u25501ac0095e-12eb-11eb-3df2-e98d0ff66dd5\n# \u2560\u2550a66afe14-12eb-11eb-3afc-fdac2325ff84\n# \u2560\u2550e86c53fa-12eb-11eb-0ee4-41455a218d84\n# \u2560\u255069b10842-12eb-11eb-381a-0bda698a59ed\n# \u2560\u25509c57e4aa-12eb-11eb-16fb-c7a18c238192\n# \u255f\u25003cf51826-12f4-11eb-2405-db9616fa3152\n# \u2560\u2550fed5e2e4-12eb-11eb-169f-8b050f9eea4a\n# \u255f\u2500464c22f2-12f4-11eb-0b3c-872621c385f6\n# \u255f\u25004dec992e-12f4-11eb-1f20-b96632769bed\n# \u2560\u25505b8f3508-12ec-11eb-0a31-61ddf796ac74\n# \u2560\u25500c8ebad2-12ec-11eb-03f1-c5b9c79bb4da\n# \u2560\u25508438424c-12ec-11eb-1de2-0bb3924ec78c\n# \u2560\u25509cee3206-12ec-11eb-09c7-1f0ebad11b8e\n# \u255f\u2500b0ab2844-12ec-11eb-1908-0318510b3292\n# \u2560\u2550bc8154b8-12ec-11eb-1fcc-4765fcd0796d\n# \u2560\u25508c0c8188-12f4-11eb-1576-23958903a69a\n# \u255f\u25007425ef6e-12f4-11eb-21c3-19c221c1ebdb\n# \u2560\u2550c67fbbbc-12ec-11eb-32be-2ff720964fe6\n# \u2560\u2550d13a65b6-12ec-11eb-2996-37987cfae782\n# \u2560\u2550dbb95f42-12ec-11eb-01d5-df2e21affd86\n# \u2560\u2550e6428aa6-12ec-11eb-06d0-95404a8a4039\n# \u2560\u2550e21658ec-12ef-11eb-06fd-b1d282edf7b6\n# \u255f\u2500b405b9ac-12f4-11eb-12fa-f7575ff1fa73\n# \u2560\u2550e57329a2-12ef-11eb-165d-51f080c73652\n# \u255f\u2500e8b34188-12ef-11eb-2d7f-fde100b582d1\n# \u255f\u2500bd6bfd10-12f4-11eb-17fe-6f9ce83f0ce8\n# \u2560\u2550f0d952da-12ef-11eb-2452-471b184bc529\n# \u2560\u25500fc7e3e6-12f0-11eb-1b49-e37196154ec6\n# \u2560\u255003b23fe0-12f0-11eb-0970-33b3b973e902\n# \u2560\u255000088cda-12f0-11eb-36b7-9b900fa6d0bf\n# \u2560\u2550f6024924-12ef-11eb-1d6c-3ffff2546914\n# \u255f\u2500cdf3e532-12f4-11eb-1ce0-873bcf0dea58\n# \u2560\u2550f9bf5200-12ef-11eb-30ee-9b3cbbccc886\n# \u2560\u255007c1cdb6-12f1-11eb-0b31-15b5c88caac6\n# \u2560\u255009d69238-12f1-11eb-1d9f-f72e8c6c14d9\n# \u2560\u2550ff598e1c-12f0-11eb-24f6-bdaa74db2ad7\n# \u2560\u25502f23dd4e-12f0-11eb-01fc-53f66d2a55e4\n# \u2560\u2550ea8e0794-12f0-11eb-2194-bdc46224dc69\n# \u2560\u25502a76a87a-12f1-11eb-3e58-e5f919ba81e8\n# \u255f\u2500892e7c40-12f0-11eb-2871-0d308063f025\n# \u255f\u2500da41895c-12f4-11eb-2ee4-f1ffc4344f61\n# \u255f\u2500dfac92ea-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 \u03c3\u00b2 = 0.49\nx = rand(Uniform(-sqrt(3.0), sqrt(3.0)), n, dim) # x generated from Uniform[-\u221a3, \u221a3]\nX = [ones(n) x] # dependent variable matrix with ones\n\u03b2 = Vector(1:1:dim+1) # true coefficients\ny = X*\u03b2 + 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\u03b20 = zeros(k)\n\u03c40 = 0.2\nA0 = \u03c40 * I # Identity matrix\n\u03bd0 = 5.0\n\u03bb0 = 7.0\n# H0 = (\u03bb0 / \u03bd0) * 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\u306e\u5bfe\u89d2\u6210\u5206\nsd0 = diag(sqrt(Matrix(A0, k, k))) # the parameter for conditional prior for \u03b2|\u03c3\u00b2 ~ N_k(\u03b20, \u03c3\u00b2*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    \u03c3\u00b2 ~ InverseGamma(\u03bd0/2, \u03bb0/2)\n\n    # Set the priors on our coefficients.\n    nfeatures = size(X, 2)\n    \u03b2 ~ MvNormal(\u03b20, \u03c3\u00b2 * inv(A0))\n\n    # Write likelihood.\n    y ~ MvNormal(X * \u03b2, \u03c3\u00b2 * 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\u03b21_chn = chn[\"\u03b2[1]\"]\n\u03b22_chn = chn[Symbol(\"\u03b2[2]\")]\n\u03c3\u00b2_chn = chn[:\u03c3\u00b2]\nall_\u03b2_chn = group(chn, :\u03b2) # get subset of all parameters include \"\u03b2\"\n\ntypeof(\u03b21_chn)\n\u03b21_chn[iter = 1000:5000, chain = 1]\nmean(\u03b21_chn)\nstd(\u03b21_chn)\n\n# Monte Carlo Standard Error\nmcse(\u03b8_chn) = sqrt((1 / (length(\u03b8_chn) * (length(\u03b8_chn) - 1))) * sum((\u03b8_chn .- mean(\u03b8_chn)).^2))\n\n[\u03b21_chn, \u03b22_chn, \u03c3\u00b2_chn]\n\nmcse.([\u03b21_chn, \u03b22_chn, \u03c3\u00b2_chn])\n\n# without burn-in\nmean(\u03b21_chn[iter = 1:5000])\n\nhistogram(\u03b21_chn[:, 1])\nhistogram!(\u03b21_chn[:, 2])\nhistogram!(\u03b21_chn[:, 3])\nhistogram!(\u03b21_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 \u2248 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    \u03c3 = zero(T)\n    @inbounds @simd for i in j+1:n\n        \u03c3 += 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 \u03c3 == zero(T)\n        \u03b2 = zero(T)\n    else\n        @inbounds begin\n            \u03bc = sqrt(X[j,k]^2 + \u03c3)\n            if X[j,k] <= zero(T)\n                h[j] = X[j,k] - \u03bc\n            else\n                h[j] = -\u03c3/(X[j,k] + \u03bc)\n            end\n            \u03b2 = 2*(h[j]^2) / (\u03c3 + 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    \u03b2\nend\n\n\"\"\"\naccumulate!(Q, A, \u03b2)\n\nQ: Matrix to be over-written with Q, gets returned\nA: Has the Householder vectors on the lower triangle\n\u03b2: Has the Householder coefficients\n\"\"\"\nfunction accumulate!(Q, A, \u03b2)\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] -= \u03b2[j]*dp\n            for i in j+1:m\n                Q[i,t] -= \u03b2[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, \u03b2, h=zeros(eltype(A), size(A,1)))\n\nA: Matrix to be QR factorized, returned by the function\n\u03b2: Empty buffer to store the Householder coefficients, returned by the function\nh: Empty buffer for in-place operations\n\"\"\"\nfunction qrfact!(A, \u03b2, h=zeros(eltype(A), size(A,1)))\n    m, n = size(A)\n    @inbounds for j in 1:n\n        \u03b2[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] -= (\u03b2[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, \u03b2  \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=\u221e\"\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 \u22c5 k) * k\n    v_perpendicular = v - v_parallel\n    v_parallel, v_perpendicular\nend\n\nfunction rotate_around(v::Vector3, k::Vector3, \u03c6::Real)\n    k = normalize(k)\n    v_parallel, v_perpendicular = decompose_vector(v, k)\n    \u03c9 = k \u00d7 v_perpendicular\n    v_parallel + v_perpendicular * cos(\u03c6) + \u03c9 * sin(\u03c6)\nend\n\n@_with_default_rng function random_3d_direction()\n    \u03b8 = 2\u03c0 * rand(rng)\n    z = 2 * rand(rng) - 1\n    r = \u221a(1 - z ^ 2)\n    Vector3(r * cos(\u03b8), r * sin(\u03b8), 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 \u03c6 = 2\u03c0 * rand(rng)\n    w = cos(\u03c6) * u + sin(\u03c6) * 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 \u00d7 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": "function find_closest_element(arr::Array{Int}, k::UInt, x::Int)\n    larger = findfirst(v -> v>=x, arr)\n    smaller = larger\n\n    #\n    len = lastindex(arr)\n    larger isa Nothing && begin\n        return arr[(len - k + 1):len]\n        end \n    smaller == 1 && return arr[1:k]\n\n    #\n    smaller -= 1\n    count = 0\n\n    while true\n        smaller < 1 && return arr[1:k]\n        larger > len && return arr[(len - k + 1):len]\n\n        count == k && break\n\n        if x - arr[smaller] <= arr[larger] - x\n            smaller -= 1\n        else\n            larger += 1\n        end\n        count += 1\n    end\n\n    arr[smaller+1:larger-1]\nend\n", "meta": {"hexsha": "e3787924d23bbe587376dfda681712bae5189fd5", "size": 633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Find-K-Closest-Elements/FKCE.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": "Find-K-Closest-Elements/FKCE.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": "Find-K-Closest-Elements/FKCE.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": 19.78125, "max_line_length": 63, "alphanum_fraction": 0.4913112164, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7833081635175727}}
{"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    \u03b1, \u03b2, \u03b3, \u03b4 = p\r\n    du[1] = \u03b1*u[1] - \u03b2*u[2]*u[1]\r\n    du[2] = \u03b3*u[1]*u[2]  - \u03b4*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\u2099 = X + Float32(1e-3)*randn(eltype(X), size(X))\r\n\r\n# Define the neueral network which learns L(x, y, y(t-\u03c4))\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(\u03b8)\r\n    Array(concrete_solve(prob_nn, Tsit5(), u0, \u03b8, 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, \u03b8, 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=\u03b8)\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(\u03b8)\r\n    pred = predict(\u03b8)\r\n    sum(abs2, X\u2099 .- pred), pred\r\nend\r\n\r\n# Test\r\nloss(p)\r\n\r\nconst losses = []\r\n\r\ncallback(\u03b8,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\u0304 = [-p_[2]*(X[1,:].*X[2,:])';p_[3]*(X[1,:].*X[2,:])']\r\n# Neural network guess\r\nL\u0302 = L(X\u2099,res2.minimizer)\r\n\r\nscatter(L\u0304')\r\nplot!(L\u0302')\r\n\r\n# Plot the error\r\nscatter(abs.(L\u0304-L\u0302)', 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 \u2208 1:5\r\n    push!(polys, u[1]^i)\r\n    push!(polys, u[2]^i)\r\n    for j \u2208 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\u03bb = 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\u03a8 = SINDy(X\u2099[:, :], DX[:, :], basis, \u03bb, opt, g = g, maxiter = 10000) # Fail\r\nprintln(\u03a8)\r\nprint_equations(\u03a8)\r\n\r\n# Test on ideal derivative data for unknown function ( not available )\r\nprintln(\"SINDy on partial ideal, unavailable data\")\r\n\u03a8 = SINDy(X\u2099[:, 1:end], L\u0304[:, 1:end], basis, \u03bb,opt, g = g, maxiter = 10000) # Succeed\r\nprintln(\u03a8)\r\nprint_equations(\u03a8)\r\n\r\n# Test on uode derivative data\r\nprintln(\"SINDy on learned, partial, available data\")\r\n\u03a8 = SINDy(X\u2099[:, 2:end], L\u0302[:, 2:end], basis, \u03bb,  opt, g = g, maxiter = 10000, normalize = true, denoise = true) # Succeed\r\nprintln(\u03a8)\r\nprint_equations(\u03a8)\r\n\r\n# Extract the parameter\r\np\u0302 = parameters(\u03a8)\r\nprintln(\"First parameter guess : $(p\u0302)\")\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(\u03a8)\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\u03a8f = SINDy(X\u2099[:, 2:end], L\u0302[:, 2:end], b, STRRidge(0.01), maxiter = 100, convergence_error = 1e-18) # Succeed\r\nprintln(\u03a8f)\r\np\u0302 = parameters(\u03a8f)\r\nprintln(\"Second parameter guess : $(p\u0302)\")\r\n\r\n# Create function\r\nrecovered_sys = ODESystem(\u03a8f)\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    \u03b1, \u03b4, \u03b2, \u03b3 = p\r\n    z = recovered_eq(u, [\u03b2; \u03b3], t)\r\n    du[1] = \u03b1*u[1] + z[1]\r\n    du[2] = -\u03b4*u[2] + z[2]\r\nend\r\n\r\n# Create the approximated problem and solution\r\nps = [p_[[1,4]]; p\u0302]\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\u2099 L\u0304 L\u0302\r\n@load \"knowledge_enhanced_NN.jld2\" solution recovered_sys approximate_solution_long NNsolution L true_solution_long X\u2099 L\u0304 L\u0302\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\u2082\r\np2 = plot(X[1,:], X[2,:], L\u0302[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\u0304[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": "using NumericalMethodsforEngineers, Test\n\na = [2. -3. 1.; 1. -1. -2.; 3. 1. -1.]\nb = [7., -2., 0.]\n\n(lower, upper) = lufac(a)\nprintln(\"NumericalMethodsforEngineers lufac(a) - lower:\")\nprintln(lower)\nprintln()\nprintln(\"NumericalMethodsforEngineers lufac(a) - upper:\")\nprintln(upper)\nprintln()\n@show lower * upper\nprintln()\n\nc1 = subfor(lower, b)\nc2 = subbac(upper, c1)\n\nsubfor!(lower, b)\nprintln(\"Updated RHS:\")\nprintln(b)\nprintln()\n\n@test \u2248(c1,  b, atol=1e-10)\nprintln()\n\nc3 = subbac(upper, c1)\n\nsubbac!(upper, b)\nprintln(\"Solution vector:\")\nprintln(b)\nprintln()\n\nc = a \\ [7., -2., 0.]\nc |> display\n@test \u2248(c2, c, atol=1e-10)\n@test \u2248(c3, c, atol=1e-10)\n\n@test \u2248(a * c, [7., -2., 0.], atol=1e-10)\nprintln()\n\nprintln(\"Julia lu(a):\")\nf = lu(a);\nf |> display\nprintln()\nf.U |> display\n", "meta": {"hexsha": "96deda26cc67ac06c99c6628b49a123eef68e802", "size": 780, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/f-02-02.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/f-02-02.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/f-02-02.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": 16.5957446809, "max_line_length": 57, "alphanum_fraction": 0.6230769231, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7832964444521651}}
{"text": "\"\"\"\n    norm1(v)\n\nNormalize `v` to sum 1.\n\"\"\"\nfunction norm1(v)\n    vs = sum(v)\n    if vs \u2248 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, \u221e].\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\u03d5 coefficient is \u221a(\u03c7\u00b2/n), bounded within [0, \u221amin(row-1,col-1)],\nCramer's V is \u03d5/\u221amin(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    \u03d5\u00b2 = sum((p .- ep) .^ 2 ./ ep)      # \u03d5\u00b2\n\n    sqrt(\u03d5\u00b2 / (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\u00e1, A., Jakub\u00edk, J., Chvostekov\u00e1, M., Coufal, D., Jajcay, N., & Palu\u0161, 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\u2081, x\u2082, y\u2081, y\u2082 = (x...,)\n    dx\u2081 = 1.4 - x\u2081^2 + 0.3*x\u2082\n    dx\u2082 = x\u2081\n    dy\u2081 = 1.4 - (c_xy * x\u2081 * y\u2081  +  (1 - c_xy)*y\u2081^2) + 0.3*y\u2082\n    dy\u2082 = y\u2081\n    return SVector{4}(dx\u2081, dx\u2082, dy\u2081, dy\u2082)\nend\n\nfunction henon2(u\u2080, c_xy)\n    p = [c_xy]\n    DiscreteDynamicalSystem(eom_henon2, u\u2080, p)\nend\n\n\"\"\"\n    henon2(;u\u2080 = 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\u00e1, A., Jakub\u00edk, J., Chvostekov\u00e1, M., Coufal, D., Jajcay, N., & Palu\u0161, 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\u2080 = rand(4), c_xy = 2.0) = henon2(u\u2080, 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": "@testset \"Test Spline Basis Evaluation\" begin\n\n    # constuct specific case that we can compute by hand\n\n    n = 5\n    a = 0\n    b = 1\n    params = SplineParams(range(a,stop=b,length=n), 0, 1)\n\n    x = rand(10000)\n\n    basestr = @inferred BasisMatrices.evalbase(params, x)\n    base = Array(basestr)\n\n    # vector of basis functions\n\n    function linBspline(u)\n        if u >= 0 && u < 0.25\n            return [1-4*u,4*u,0,0,0]\n\n        elseif u >= 0.25 && u < 0.5\n            return [0,2*(1 - 2*u),4*u-1,0,0]\n\n        elseif u >= 0.5 && u < 0.75\n            return [0,0,3 - 4*u,2*(2*u - 1),0]\n\n        else\n            return [0,0,0,4*(1 - u),4*u-3]\n        end\n    end\n\n    manualbase = Array{Float64}(undef, length(x), n)\n\n    for i in 1:length(x)\n        manualbase[i, :] = linBspline(x[i])\n    end\n\n    @testset \"test evalbase with linear B spline\" begin\n        @test all(manualbase .== base)\n    end\n\n    # test stuff that isn't implemented\n    params2 = SplineParams(10, 0, 1, 2)\n    @test_throws ErrorException evalbase(SplineSparse, params, nodes(params), -1)\n    @test_throws ErrorException evalbase(params, nodes(params), -1)\n\n    @test BasisMatrices.family(SplineParams) == Spline\n    @test BasisMatrices.family_name(SplineParams) == \"Spline\"\n    @test issparse(SplineParams)\n\n    @test BasisMatrices.family(params) == Spline\n    @test BasisMatrices.family_name(params) == \"Spline\"\n    @test issparse(params)\n\n\n    @testset \"non Float64 eltypes\" begin\n        p = SplineParams(Float32[0.1, 0.2, 0.3, 0.4, 0.5], 0, 3)\n        @test Float32 == eltype(@inferred BasisMatrices.evalbase(p, Float32[0.25, 0.35]))\n        @test Float32 == eltype(@inferred BasisMatrices.evalbase(p, Float32[0.25, 0.35], 1))\n        @test Float64 == eltype(@inferred BasisMatrices.evalbase(p, [0.25, 0.35]))\n    end\nend\n", "meta": {"hexsha": "1b96554460f91b38bc0d57aa6806381c1c627dbf", "size": 1807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/spline.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": "test/spline.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": "test/spline.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": 28.6825396825, "max_line_length": 92, "alphanum_fraction": 0.6026563365, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7832836287105015}}
{"text": "using LifeContingencies\nusing MortalityTables\nusing Dates\nusing DataFrames\n\nmort_table_name = \"2012 IAM Period Table \u2013 Male, ANB\"\nimprov_table = \"Projection Scale G2 \u2013 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\u0308(ins,55) * annual_income\nsum(LifeContingencies.APV.(ins,1:55) * 12000)\n\n\n\n\u2113\u2081 = [43302,42854,42081,41351,40050]\n\u2113\u2082 = [47260,47040,46755,46500,46227]\n\nps\u2081 =  \u2113\u2081 ./ \u2113\u2081[1]\nqs\u2081 = [1 - ps\u2081[t] / ps\u2081[t - 1] for t in 2:5 ] \n\nps\u2082 =  \u2113\u2082 ./ \u2113\u2082[1]\nqs\u2082 = [1 - ps\u2082[t] / ps\u2082[t - 1] for t in 2:5 ] \n\nm1 = UltimateMortality(qs\u2081, start_age=65)\nm2 = UltimateMortality(qs\u2082, 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": "\nusing LinearAlgebra\nusing DataFrames\nusing CSV\nusing Plots\n\nobs = CSV.File(\"../../DATA/ovariancancer_obs.csv\", header = false) |> Tables.matrix\ngrp = CSV.File(\"../../DATA/ovariancancer_grp.csv\", header = false) |> Tables.matrix\n\nU, S, V = svd(obs)\n\np1 = plot(S, yaxis = :log, legend = false)\np2 = plot(cumsum(S)./sum(S), legend = false)\n\ncancer = [[],[],[]]\nnormal = [[],[],[]]\n\nfor i = 1:size(obs)[1]\n    x = V[:,1]'*obs[i,:]\n    y = V[:,2]'*obs[i,:]\n    z = V[:,3]'*obs[i,:]\n    if (grp[i] == \"Cancer\")\n        append!.(cancer, [x, y, z])\n    else\n        append!.(normal, [x, y, z])\n    end\nend\n\np3 = scatter(cancer..., mc = :red, label = \"Cancer\")\nscatter!(normal..., mc = :blue, label = \"Normal\")", "meta": {"hexsha": "6cc9a5d18a0b6296abf28f659f5e6be6cb8bdded", "size": 702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH01/CH01_SEC05_2_OvarianCancer.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_SEC05_2_OvarianCancer.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_SEC05_2_OvarianCancer.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.4, "max_line_length": 83, "alphanum_fraction": 0.5512820513, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241947446617, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7832791077971796}}
{"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": "using ArgParse\n\ns=ArgParseSettings()\n@add_arg_table s begin\n    \"--part2\"\n        help=\"Do part 2\"\n        action=:store_true\nend\nparsed_args = parse_args(ARGS, s)\n\nfunction calculate_gamma(numbers, bitlen)\n    counts = zeros(bitlen)\n    for n in numbers\n        for idx in 1:bitlen\n            mask = 0x1000 >>> idx\n            if (n & mask) != 0\n                counts[idx] += 1\n            end\n        end\n    end\n    \n    l = div(length(numbers), 2)\n    gamma::UInt32 = 0\n    for idx in 1:bitlen\n        gamma <<= 1\n        if counts[idx] >= l\n            gamma |= 1\n        end\n    end\n    gamma\nend\n\nfunction part1(bits)\n    gamma = calculate_gamma(bits, 12)\n    epsilon = xor(gamma, 0x0fff)\n    epsilon * gamma\nend\n\nfunction filter_values(values, use_first)\n    bit = 0x0800\n    while bit != 0 && length(values) > 1\n        set = count(v -> (v & bit) != 0 , values)\n        if use_first\n            good = set >= (length(values) - set) ? bit : 0\n        else\n            good = set < (length(values)-set) ? bit : 0\n        end\n        values = filter(b -> (b & bit) == good, values)\n        bit >>>= 1\n    end\n    values[1]\nend\n\nfunction part2(values)\n    o2_rating = filter_values(values, true)\n    co2_rating = filter_values(values, false)\n    o2_rating * co2_rating\nend\n\nfunction parseLine(line)\n    parse(UInt32, line, base=2)\nend\n\nbits = [parseLine(line) for line in eachline(\"input/day_3.txt\")]\nif parsed_args[\"part2\"]\n    answer = part2(bits)\nelse\n    answer = part1(bits)\nend\nprintln(\"The answer is: $answer\")\n", "meta": {"hexsha": "26b4f1332dd12be0fa7233b0c8619d650dde1f4d", "size": 1525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day3.jl", "max_stars_repo_name": "ntwyman/aoc_2021", "max_stars_repo_head_hexsha": "34dc0af6efdabef216a7be3267a1736643a50545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day3.jl", "max_issues_repo_name": "ntwyman/aoc_2021", "max_issues_repo_head_hexsha": "34dc0af6efdabef216a7be3267a1736643a50545", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day3.jl", "max_forks_repo_name": "ntwyman/aoc_2021", "max_forks_repo_head_hexsha": "34dc0af6efdabef216a7be3267a1736643a50545", "max_forks_repo_licenses": ["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.4788732394, "max_line_length": 64, "alphanum_fraction": 0.571147541, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259925, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7832529040907867}}
{"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 \u03c4. This calculates the divided difference\nfrom \u03c4_i to \u03c4_j. The `dd` is a memoization.\n\"\"\"\nfunction divided_difference(i::Integer, j::Integer, \u03c4::Vector, f::Vector, dd::DividedDifference)\n    if (i, j) \u2208 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, \u03c4, f, dd) - divided_difference(i, j - 1, \u03c4, f, dd)) /\n            (\u03c4[j] - \u03c4[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, \u03c4::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 *= \u03c4[j] -\u03c4[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\u2217 = (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\u03b1(m::Integer, n::Integer) = n - m\n\u03b1(m::Vector{<:Integer}, n::Vector{<:Integer}) = \u03b1.(min.(m, n'), max.(m, n'))\n\ngaussian_function(x::Real, p::Real) = exp(-0.5 * abs2(z(x,p))) / \u03c0\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 \u2265 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 \u2265 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": "using Test\nusing Recommenders: \u03c3, Logloss, grad\n\n@testset \"Sigmoid.\" begin\n    @test \u03c3(0.0) == 0.5\n    @test \u03c3(100) \u2248 1.0\n    @test \u03c3(-100) < 1e-20\n    @test \u03c3(1.0) \u2248 1.0 / (1 + exp(-1))\n    @test \u03c3(0.1) > 0.5\n    @test \u03c3(-0.1) < 0.5\nend\n\n@testset \"Logloss.\" begin\n    logloss = Logloss()\n    @test logloss(100, 1) \u2248 0\n    @test logloss(-100, 1) > 20\n    @test logloss(3, 0) > 3\n    @test logloss(-100, 0) \u2248 0\n    @test logloss(0.0, 1) == logloss(0.0, 0)\nend\n\n@testset \"Grad of Logloss.\" begin\n    logloss = Logloss()\n\n    @test grad(logloss, 0.3243, 0) \u2248 \u03c3(0.3243)\n    @test grad(logloss, 0.3243, 1) \u2248 \u03c3(0.3243) - 1\n\n    # check sign\n    logit = 0.4\n    label = 1\n    loss = logloss(logit, label)\n    grad_logloss = grad(logloss, logit, label)\n    @test logloss(logit - 0.1 * grad_logloss, label) < loss\n\n    label = 0\n    loss = logloss(logit, label)\n    grad_logloss = grad(logloss, logit, label)\n    @test logloss(logit - 0.1 * grad_logloss, label) < loss\n\n\n    logit = -0.3\n    label = 1\n    loss = logloss(logit, label)\n    grad_logloss = grad(logloss, logit, label)\n    @test logloss(logit - 0.1 * grad_logloss, label) < loss\n\n    label = 0\n    loss = logloss(logit, label)\n    grad_logloss = grad(logloss, logit, label)\n    @test logloss(logit - 0.1 * grad_logloss, label) < loss\nend\n", "meta": {"hexsha": "9a8182a3dd6e7a38957e87eedf31e449bf19cefd", "size": 1292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/core/loss_function.jl", "max_stars_repo_name": "yng87/Recommender.jl", "max_stars_repo_head_hexsha": "0bc576c5cbfed4789d91d1e52ac74f929dd9a381", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-24T14:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T12:01:49.000Z", "max_issues_repo_path": "test/core/loss_function.jl", "max_issues_repo_name": "yng87/Recommender.jl", "max_issues_repo_head_hexsha": "0bc576c5cbfed4789d91d1e52ac74f929dd9a381", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-27T01:55:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T01:55:02.000Z", "max_forks_repo_path": "test/core/loss_function.jl", "max_forks_repo_name": "yng87/Recommenders.jl", "max_forks_repo_head_hexsha": "5531804e7ed0463cfff65f667abeb0789d0293fc", "max_forks_repo_licenses": ["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.8461538462, "max_line_length": 59, "alphanum_fraction": 0.5897832817, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7831960930898424}}
{"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 JuMP, BARON, Base.Test\n\nm = Model(solver=BaronSolver())\nub = [9.422, 5.9023, 267.417085245]\n@variable(m, 0 \u2264 x[i=1:3] \u2264 ub[i])\n\n@NLconstraints(m, begin\n    250 + 30x[1] -  6x[1]^2 == x[3]\n    300 + 20x[2] - 12x[2]^2 == x[3]\n    150 + 0.5*(x[1]+x[2])^2 == x[3]\nend)\n\n@NLobjective(m, Min, -x[3])\n\nsolve(m)\n\n@test isapprox(getvalue(x[1]), 6.2934300, rtol=1e-6)\n@test isapprox(getvalue(x[2]), 3.8218391, rtol=1e-6)\n@test isapprox(getvalue(x[3]), 201.1593341, rtol=1e-5)\n@test isapprox(getobjectivevalue(m), -201.1593341, rtol=1e-6)\n", "meta": {"hexsha": "8b8a62e981923c72189fa81d85f4e02a23d24c14", "size": 534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/nlp2.jl", "max_stars_repo_name": "dovahcrow/BARON.jl", "max_stars_repo_head_hexsha": "a2ce845c96c288d0cacc3278f50814de5645aab6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-21T03:05:47.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-21T03:05:47.000Z", "max_issues_repo_path": "test/nlp2.jl", "max_issues_repo_name": "dovahcrow/BARON.jl", "max_issues_repo_head_hexsha": "a2ce845c96c288d0cacc3278f50814de5645aab6", "max_issues_repo_licenses": ["MIT"], "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/nlp2.jl", "max_forks_repo_name": "dovahcrow/BARON.jl", "max_forks_repo_head_hexsha": "a2ce845c96c288d0cacc3278f50814de5645aab6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-06T06:14:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T06:14:49.000Z", "avg_line_length": 25.4285714286, "max_line_length": 61, "alphanum_fraction": 0.6161048689, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.783164615573182}}
{"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\u2112_\u03b4 u = \u222b_\ud835\udd4a\u00b2 \u03c1_\u03b4(|\ud835\udc31-\ud835\udc32|)[u(\ud835\udc31) - u(\ud835\udc32)] d\u03a9(\ud835\udc32),\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": "import RowEchelon\nimport LinearAlgebra\n\n#=\nHomework 6\nSection 2.5\nProblems 14\n=#\n\n# Create the matrix\nA = [ 1 3 1 5 ; 5 20 6 31 ; -2 -1 -1 -4 ; -1 7 1 7]\nLU = LinearAlgebra.lu(A)\nprint(\"L = \\t\")\nprintln(LU.L)\nprint(\"U = \\t\")\nprintln(LU.U)\n", "meta": {"hexsha": "0560a955c5e43fb728ddcaff9042bf5ea4490afe", "size": 239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW6_S2.5_P14.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": "HW6_S2.5_P14.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": "HW6_S2.5_P14.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": 14.0588235294, "max_line_length": 51, "alphanum_fraction": 0.6234309623, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9719924810166349, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7830684324227587}}
{"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": "using Test\nusing MultivariateBases\nusing DynamicPolynomials\n@polyvar x y\n\n@testset \"Linear\" begin\n    basis = MonomialBasis([x, y])\n    @test polynomialtype(basis, Int) == polynomialtype(x, Int)\n    @test polynomial(i -> i^2, basis) == x + 4y\n    @test coefficients(x + 4y, MonomialBasis) == [1, 4]\nend\n@testset \"Affine\" begin\n    # It will be sorted and 1 will be moved at the end\n    basis = MonomialBasis([1, x, y])\n    @test polynomialtype(basis, Int) == polynomialtype(x, Int)\n    @test polynomial(i -> i^2, basis) == x + 4y + 9\n    @test coefficients(9 + x + 4y, MonomialBasis) == [1, 4, 9]\nend\n@testset \"Quadratic\" begin\n    basis = MonomialBasis([x^2, x*y, y^2])\n    @test polynomialtype(basis, Int) == polynomialtype(x, Int)\n    @test polynomial(i -> i^2, basis) == x^2 + 4x*y + 9y^2\n    @test coefficients(x^2 + 4x*y + 9y^2, MonomialBasis) == [1, 4, 9]\nend\n@testset \"API degree = $degree\" for degree in 0:3\n    api_test(MonomialBasis, degree)\nend\n", "meta": {"hexsha": "d8b2ff3a27d15b725b58b16bcd4742660f09088e", "size": 957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/monomial.jl", "max_stars_repo_name": "JuliaAlgebra/PolynomialBases", "max_stars_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-24T07:15:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:13:46.000Z", "max_issues_repo_path": "test/monomial.jl", "max_issues_repo_name": "JuliaAlgebra/PolynomialBases", "max_issues_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-01-30T12:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T22:17:19.000Z", "max_forks_repo_path": "test/monomial.jl", "max_forks_repo_name": "JuliaAlgebra/PolynomialBases", "max_forks_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-01-15T15:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T15:10:30.000Z", "avg_line_length": 34.1785714286, "max_line_length": 69, "alphanum_fraction": 0.6468129572, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7830241909542541}}
{"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 \u00f7 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 \u00f7 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 \u00f7 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 \u00f7 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\u2032, y\u2032, d) = extendedeuclid(b, mod(a, b))\n    return (y\u2032, x\u2032 - a \u00f7 b * y\u2032, 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 \u2208 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\u03a3SE = 0.0\n\n\tfor i in 1:size(NeuralNetwork.y, 1)\n\t\t\u03a3SE += (NeuralNetwork.y[i] - NeuralNetwork.output[i]) ^ 2.0\n    end\n\t\n    loss = 1.0 / size(NeuralNetwork.y) * \u03a3SE\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 `\u03d5`.\n# `\u03d5` 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 `\u03d5`.\n# `s` indicates the total length of the series to be generated.\nfunction generate_process(\u03d5::AbstractVector{Float32}, s::Int)\n    @assert s > 0 \"s must be positive\"\n    # Generate white noise\n    \u03f5 = randn(Float32, s)\n    # Initialize time series\n    X = zeros(Float32, s)\n    p = length(\u03d5)\n    X[1] = \u03f5[1]\n    # Reverse the order of the coefficients for multiplication later on\n    \u03d5 = reverse(\u03d5) \n    # Fill first p observations\n    for t \u2208 1:p-1\n        X[t+1] = X[1:t]'\u03d5[1:t] + \u03f5[t+1]\n    end\n    # Compute values iteratively\n    for t \u2208 p+1:s\n        X[t] = X[t-p:t-1]'\u03d5 + \u03f5[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\u00d71, reshape it\n    if isa(X, AbstractVector)       \n        X = permutedims(X)\n    end\n    T = size(X, 2)\n    @assert s \u2264 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 \u2208 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\u2080, F\u2081) into FinSet, you need to provide some data. \n#     1. For every A:Ob(C), you need F\u2080(A):FinSet\n#     2. For every f:A\u2192B, you need to specify a FinFunction F\u2081(f):F\u2080(A)\u2192F\u2080(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\u03d5 = ACSetTransformation(e,w,E=[1], V=[1,2])\n\nis_natural(\u03d5)\n\n# The ACSetTransformation constructor does not automatically validate that the naturality squares commute!\n\n\u03d5\u1d66 = ACSetTransformation(e,w,E=[1], V=[3,2])\nis_natural(\u03d5\u1d66)\n\n# Our \u03d5\u1d66 in't natural because the edge map e\u2081 \u21a6 e\u2081 is not consistent with our vertex map, which sends v\u2081 \u21a6 v\u2083 and v\u2082 \u21a6 v\u2082. We can fix this by sending e\u2081 to e\u2082\n\n\u03d5\u1d66\u2032 = ACSetTransformation(e,w,E=[2], V=[3,2])\nis_natural(\u03d5\u1d66\u2032)\n\n\n# So how does Catlab store the data of the natural transformation? \n# the domain\n\u03d5.dom\n# the codomain\n\u03d5.codom\n# the components\n\u03d5.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\u03d5[:V]\n\u03d5[:E]\n# We can check the  naturality squares ourselves\n# The sources are preserved: `src \u22c5 \u03d5\u1d65 == \u03d5\u2091 \u22c5 src`\n\u03d5[:V](dom(\u03d5)[:,:src]) == codom(\u03d5)[collect(\u03d5[:E]), :src]\n# The targets are preserved: `tgt \u22c5 \u03d5\u1d65 == \u03d5\u2091 \u22c5 tgt`\n\u03d5[:V](dom(\u03d5)[:,:tgt]) == codom(\u03d5)[collect(\u03d5[:E]), :tgt]\n\n# This approach generalizes to the following: \n#\n# ```julia\n# function is_natural(\u03b1::ACSetTransformation{S}) where {S}\n#    X, Y = dom(\u03b1), codom(\u03b1)\n#    for (f, c, d) in zip(hom(S), dom(S), codom(S))\n#      Xf, Yf, \u03b1_c, \u03b1_d = subpart(X,f), subpart(Y,f), \u03b1[c], \u03b1[d]\n#      all(Yf[\u03b1_c(i)] == \u03b1_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[\u03b1_c(i)] == \u03b1_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\u2192B 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\u2192B 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 \u03d5:e\u2192G 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 \u03d5\n        collect(\u03d5[:V])\n    end\nend\n\ngraphhoms(t, T)\n\n# Homs \u03d5:t\u2192T are little triangles in T, but homs \u03d5:T\u2192t 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\u2192t.\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\u2096 the k-coloring classifier because homomorphims into \u03b1:G \u2192 K\u2096 are k-colorings of G.\n\nclique(k::Int) = begin\n    K\u2096 = Graphs.Graph(k)\n    for i in 1:k\n        for j in 1:k\n            if j \u2260 i\n                add_parts!(K\u2096, :E, 1, src=i, tgt=j)\n            end\n        end\n    end\n    return K\u2096\nend\n\nK\u2083 = clique(3)\ndraw(id(K\u2083))\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\u2083))\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(\u03b8, radius)\n\n    \u03b8_count = round(Int, 2\u03c0/\u03b8)\n    \u03b8 = 2\u03c0/\u03b8_count\n    angles = (0:\u03b8_count)*\u03b8\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 \u03b8, xoffs, yoffs\nend\n\n_discretize_angle(angle::AbstractFloat, inv\u03b8) =\n    angle < 0 ? round(Int, (angle + 2\u03c0)*inv\u03b8)+1 : round(Int, angle*inv\u03b8)+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    \u03b8, xoffs, yoffs = _calc_discrete_offsets(theta, radius)\n    i\u03b8 = 1/\u03b8\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\u03b8)   # 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` (`\u22c5`), `cross` (`\u00d7`), `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)), `\u2207` to find the gradient (`\u2207(f)`), the divergence (`\u2207\u22c5F`). and the curl (`\u2207\u00d7F`), 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, \u2207\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) \u00f7 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, \u03b1)\n    # two tail test\n    p = 2*(1-normcdf(abs(z)))  \n    h = abs(z) > norminvcdf(1-\u03b1/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\u03bc ~ Uniform(-10,10)\n\t\u03c3 ~ Uniform(0,20)\n    data ~ MvNormal(Fill(\u03bc,length(data)),\u03c3)\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\u03bc = 0\n\t\u03c3 ~ Uniform(0,20)\n\tfor i in 1:length(data)\n\t\tdata[i] ~ Normal(\u03bc,\u03c3)\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_\u03b2_\u03b3!\n\n\"\"\"\n    solve_tridiag!(x, B, a, b, c, n, xtemp, \u03b3, \u03b2)\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| \u03b3[1:n-1]     | temporary                 |\n| \u03b2[1:n]       | temporary                 |\n--------------------------------------------\n\"\"\"\nfunction solve_tridiag!(x, B, a, b, c, n, xtemp, \u03b3, \u03b2)\n  # Define coefficients:\n  \u03b2[1] = b[1]\n  \u03b3[1] = c[1]/\u03b2[1]\n  for i in 2:n-1\n    \u03b2[i] = b[i]-a[i-1]*\u03b3[i-1]\n    \u03b3[i] = c[i]/\u03b2[i]\n  end\n  \u03b2[n] = b[n]-a[n-1]*\u03b3[n-1]\n\n  # Forward substitution:\n  xtemp[1] = B[1]/\u03b2[1]\n  for i = 2:n\n    m = B[i] - a[i-1]*xtemp[i-1]\n    xtemp[i] = m/\u03b2[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]-\u03b3[i]*x[i+1]\n  end\nend\n\n\n\"\"\"\n    solve_tridiag_stored!(x, B, a, \u03b2, \u03b3, 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, \u03b2 and \u03b3, can be computed in init_\u03b2_\u03b3!.\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|  \u03b2[1]                                    | |  1  \u03b3[1]                               |\n|  \u03b1[1]  \u03b2[2]                              | |        1  \u03b3[2]                         |\n|        \u03b1[2]  \u03b2[3]                        | |              1  \u03b3[3]                   |\n|           *     *     *                  | |                 *     *                |\n|                 *     *                  | |                       *     *          |\n|                    \u03b1[n-2]  \u03b2[n-1]        | |                             1   \u03b3[n-1] |\n|_                           \u03b1[n-1]  \u03b2[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| \u03b2[1:n]       | temporary                 |\n| \u03b3[1:n-1]     | temporary                 |\n| n            | system size               |\n| xtemp[1:n]   | temporary                 |\n--------------------------------------------\n\"\"\"\nfunction solve_tridiag_stored!(x, B, a, \u03b2, \u03b3, n, xtemp)\n  # Forward substitution:\n  xtemp[1] = B[1]/\u03b2[1]\n  for i = 2:n\n    m = B[i] - a[i-1]*xtemp[i-1]\n    xtemp[i] = m/\u03b2[i]\n  end\n\n  # Backward substitution:\n  x[n] = xtemp[n]\n  for i = n-1:-1:1\n    x[i] = xtemp[i]-\u03b3[i]*x[i+1]\n  end\nend\n\n\"\"\"\n    init_\u03b2_\u03b3!(\u03b2, \u03b3, 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| \u03b2[1:n]       | temporary                 |\n| \u03b3[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_\u03b2_\u03b3!(\u03b2, \u03b3, a, b, c, n)\n  \u03b2[1] = b[1]\n  \u03b3[1] = c[1]/\u03b2[1]\n  for i = 2:n-1\n    \u03b2[i] = b[i]-a[i-1]*\u03b3[i-1]\n    \u03b3[i] = c[i]/\u03b2[i]\n  end\n  \u03b2[n] = b[n]-a[n-1]*\u03b3[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": "# # Basics: Arithmetic, Assignment, and Strings\n#\n# Topics:\n# 1. Infix arithmetic operators\n# 2. Numeric literals\n# 3. Comparisons\n# 4. Assignments\n# 5. Strings\n\n#-\n\n# ## Arithmetic should largely be familiar\n\n3 + 7 # addition\n\n#-\n\n10 - 3 # subtraction\n\n#-\n\n20 * 5 # multiplication\n\n#-\n\n100 / 10 # division\n\n#-\n\n10 ^ 2 # exponentiation\n\n#-\n\n101 % 2 # remainder (modulus)\n\n#-\n\nsqrt(2) # square root\n\n#-\n\n\u221a2 # Unicode to the rescue: \\sqrt + TAB\n\n# Note that dividing two integers yields a floating point number. There are two additional operators that may be helpful here:\n\n10 / 6\n\n#-\n\n10 \u00f7 6 # \\div TAB or the `div` function\n\n#-\n\ndiv(10, 6)\n\n#-\n\n10 // 6\n\n# ### Numbers: Many different ways to write the number forty-two\n\nfortytwos = (42, 42.0, 4.20e1, 4.20f1, 84//2, 0x2a)\n\n#-\n\nfor x in fortytwos\n    show(x)\n    println(\"\\tisa $(typeof(x))\")\nend\n\n# ### Bitwise arithmetic\n\n0x2a & 0x70 # AND\n\n#-\n\n0x2a | 0x70 # OR\n\n#-\n\n42 & 112\n\n#-\n\n0b0010 << 2 # == 0b1000\n\n# ### Logical operators\n\nfalse && true # AND\n\n#-\n\nfalse || true # OR\n\n# Note that they \"short-circuit!\"\n\nx = -42\nx > 0 || error(\"x must be positive\")\n\n# ### Comparisons\n\n1 == 1.0 # Equality\n\n#-\n\n1 === 1.0 # Programmatically identical\n\n#-\n\n3 < \u03c0\n\n#-\n\n1 <= 1\n\n#-\n\n.1 + .2\n\n#-\n\n.1 + .2 \u2248 .3 # \\approx + TAB\n\n# Comparisons \"chain\"\n#\n# Try inserting parentheses around one of these comparisons\n\n2 == 2.0 == 0x02\n\n#-\n\nx = 42\n0 < x < 100 || error(\"x must be between 0 and 100\")\n\n# ### Higher precision\n\nbig(2)^1000\n\nbig(pi)\n\nbig\"0.1\"\n\nbig(0.1)\n\n# # Assignment\n#\n# Assignment in Julia is done with the single `=`. All it does is associates a name (on the left) to a value (on the right).\n\nx = 1 # Use the name `x` for the value `1`\n\n#-\n\ny = x # Use the name `y` for the value that `x` refers to\n\n#-\n\nx = \"hello!\" # Decide you have a better use for the name `x`\n\n#-\n\ny # Is still the value 1\n\n#-\n\n# \"Simultaneous\" multiple assignment\n\nx, y = y, x  # swap x and y\nx, y = y, x  # swap back\n\n#-\n\n\u03f5 = eps(1.0) # You can make your own unicode names\n\n#-\n\n5\u03f5 # Juxtaposition is multiplication\n\n#-\n\n# We make use of juxtaposition for complex numbers\n\n(1 + 2im)^2\n\n# ## Updating operators\n#\n# All the infix arithmetic operators above can be used as \"updating\" operators in conjunction with an assignment:\n\ny += 1\n\n#-\n\n## This is exactly the same as:\ny = y + 1\n\n# Note that it's just re-purposing the _same name_ for a new value. This means that the type might even change:\n\ny /= 2\n\n# # Strings\n\ns1 = \"I am a string.\"\n\n#-\n\ns2 = \"\"\"I am also a string. \"\"\"\n\n#-\n\n\"Here, we get an \"error\" because it's ambiguous where this string ends \"\n\n#-\n\n\"\"\"Look, Mom, no \"errors\"!!! \"\"\"\n\n#-\n\n    println(\"\"\"The other nice thing about triple-quoted\n               string literals is that they ignore leading\n               indentation, which is nice for long strings\n               in real code. Try changing these quotes!\"\"\")\n\n# Strings are not written with single `'`s \u2014 that's used for a single character:\n\nfirst(s1)\n\n#-\n\n'\u2282'\n\n#-\n\n'If you try writing a string in single-quotes, you will get an error'\n\n# ## String interpolation\n\n#-\n\n# You can use the dollar sign inside a string to evaluate a Julia expression inside a string \u2014 either a single variable or a more complicated expression:\n\nname = \"Jane\"\nnum_fingers = 10\nnum_toes = 10\nprintln(\"Hello, my name is $name.\")\nprintln(\"I have $num_fingers fingers and $num_toes toes.\")\n\n#-\n\n println(\"That is $(num_fingers + num_toes) digits in all!!\")\n\n#-\n\n@assert days == 365\n@assert days_float == 365.0\n", "meta": {"hexsha": "10036d941f8e8dbc0e52d6657c903d9ed514597c", "size": 3472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Introduction to Julia/01. Arithmetic, Assignment, and Strings.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/01. Arithmetic, Assignment, and Strings.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/01. Arithmetic, Assignment, and Strings.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": 13.6692913386, "max_line_length": 153, "alphanum_fraction": 0.631624424, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.880797076413356, "lm_q1q2_score": 0.7828161547305025}}
{"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        \u03bbs, _ = eigen(T)\n        if II >= itr_offset\n            push!(FoundRitzValues, \u03bbs)\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# Testing normal form games #\n# ------------------------- #\n\n# NOTE: We include `@inferred` at least once for each function name. We do\n#       that multiple times for the same function if we have particular reason\n#       to believe there might be a type stability with that function.\n\nusing MathOptInterface\nconst MOI = MathOptInterface\nusing Clp\nusing CDDLib\n\n\n@testset \"Testing normal_form_game.jl\" begin\n\n    # Player #\n\n    @testset \"Player with 1 opponent\" begin\n        coordination_game_matrix = [4 0; 3 2]\n        player = Player(coordination_game_matrix)\n\n        @test @inferred(best_response(player, 2)) == 2\n        @test @inferred(best_response(player, [1/2, 1/2])) == 2\n        @test @inferred(best_response(player, [1/2, 1/2], BROptions())) == 2\n        @test sort(@inferred(best_responses(player, [2/3, 1/3]))) ==\n              sort([1, 2])\n        @test best_response(\n            player, [2/3, 1/3], tie_breaking=:random\n            ) in [1, 2]\n        @test best_response(\n            player, [2/3, 1/3], BROptions(tol=1e-5, tie_breaking=:random)\n            ) in [1, 2]\n        @test_throws ArgumentError best_response(\n            player, [2/3, 1/3], tie_breaking=:invalid_symbol\n            )\n        @test @inferred(is_best_response(player, 1, 1))\n        @test @inferred(is_best_response(player, [1/2, 1/2], [2/3, 1/3]))\n\n        # Perturbed best response\n        @test best_response(player, [2/3, 1/3], [0., 0.1]) == 2\n        @test best_response(player, [2, 1], [0., 0.1]) == 2\n\n        # Dominated actions\n        @test !(@inferred(is_dominated(player, 1)))\n        @test @inferred(dominated_actions(player)) == Int[]\n    end\n\n    @testset \"Player with 2 opponents\" begin\n        payoffs_2opponents = Array{Int}(undef, 2, 2, 2)\n        payoffs_2opponents[:, 1, 1] = [3, 1]\n        payoffs_2opponents[:, 1, 2] = [6, 0]\n        payoffs_2opponents[:, 2, 1] = [4, 5]\n        payoffs_2opponents[:, 2, 2] = [2, 7]\n        player = @inferred Player(payoffs_2opponents)\n\n        @test @inferred(payoff_vector(player, (1, 2))) == [6, 0]\n        @test !(@inferred(is_best_response(player, 1, (2, 1))))\n        @test @inferred(best_response(player, (2, 2))) == 2\n        @test sort(@inferred(best_responses(player, ([3/7, 4/7], [1/2, 1/2])))) ==\n              sort([1, 2])\n\n        @test_throws MethodError best_response(player, (1, [1/2, 1/2]))\n\n        @test !(@inferred(is_dominated(player, 1)))\n        @test @inferred(dominated_actions(player)) == Int[]\n    end\n\n    @testset \"convert for Player\" begin\n        T1 = Int\n        T2 = Float64\n        player = Player(T1[1 2; 3 4])\n        N = ndims(player.payoff_array)\n\n        for T in [T1, T2]\n            player_new = Player{N,T}(player)\n            @test eltype(player_new.payoff_array) == T\n            @test player_new.payoff_array == player.payoff_array\n\n            # Constructor always makes a copy\n            @test player_new.payoff_array !== player.payoff_array\n        end\n\n        for T in [T1, T2]\n            player_new = Player(T, player)\n            @test eltype(player_new.payoff_array) == T\n            @test player_new.payoff_array == player.payoff_array\n\n            # Constructor always makes a copy\n            @test player_new.payoff_array !== player.payoff_array\n        end\n\n        player_new = @inferred Player(player)\n        @test eltype(player_new.payoff_array) == T1\n        @test player_new.payoff_array == player.payoff_array\n\n        # Constructor always makes a copy\n        @test player_new.payoff_array !== player.payoff_array\n\n        for T in [T1, T2]\n            player_new = convert(Player{N,T}, player)\n            @test eltype(player_new.payoff_array) == T\n            @test player_new.payoff_array == player.payoff_array\n\n            @test (player_new.payoff_array === player.payoff_array) ==\n                  (T == T1)\n        end\n    end\n\n    @testset \"repr(Player)\" begin\n        A = [1 2; 3 4]\n        player = Player(A)\n        r = repr(\"text/plain\", A)\n        @test repr(player) ==\n            replace(r, string(typeof(A)) =>\n                       split(string(typeof(player)), \".\")[end])\n    end\n\n    @testset \"Tests on delete_action for Player\" begin\n        shapley_game = [0 1 0; 0 0 1; 1 0 0]\n        player = Player(shapley_game)\n\n        player_new_1 = @inferred delete_action(player, 1, 1)\n        player_new_2 = @inferred delete_action(player, [1, 2], 1)\n        @test player_new_1.payoff_array == Player([0 0 1; 1 0 0]).payoff_array\n        @test player_new_2.payoff_array == Player([1 0 0]).payoff_array\n    end\n\n    # NormalFormGame #\n\n    @testset \"symmetric NormalFormGame with 2 players\" begin\n        coordination_game_matrix = [4 0; 3 2]\n        g = @inferred(NormalFormGame(coordination_game_matrix))\n\n        # NOTE: getindex(g, 1, 2) is equivalent to `g[1, 2]`. I use the former\n        #       so we can test the type stability of the get index function\n        @test @inferred(getindex(g, 1, 2)) == [0, 3]\n        @test @inferred(getindex(g, CartesianIndex(1, 2))) == [0, 3]\n        @test @inferred is_nash(g, (1, 1))\n        @test @inferred is_nash(g, ([2/3, 1/3], [2/3, 1/3]))\n    end\n\n    @testset \"asymmetric NormalFormGame with 2 players\" begin\n        matching_pennies_bimatrix = Array{Float64}(undef, 2, 2, 2)\n        matching_pennies_bimatrix[:, 1, 1] = [1, -1]\n        matching_pennies_bimatrix[:, 1, 2] = [-1, 1]\n        matching_pennies_bimatrix[:, 2, 1] = [-1, 1]\n        matching_pennies_bimatrix[:, 2, 2] = [1, -1]\n        g = @inferred(NormalFormGame(matching_pennies_bimatrix))\n\n        @test g[2, 1] == [-1, 1]\n        @test !(is_nash(g, (1, 1)))\n        @test is_nash(g, ([1/2, 1/2], [1/2, 1/2]))\n    end\n\n    @testset \"asymmetric NormalFormGame with 3 players\" begin\n        payoffs_2opponents = Array{Int}(undef, 2, 2, 2)\n        payoffs_2opponents[:, 1, 1] = [3, 1]\n        payoffs_2opponents[:, 1, 2] = [6, 0]\n        payoffs_2opponents[:, 2, 1] = [4, 5]\n        payoffs_2opponents[:, 2, 2] = [2, 7]\n        player = @inferred Player(payoffs_2opponents)\n        g = @inferred NormalFormGame(tuple([player for i in 1:3]...))\n\n        @test @inferred(getindex(g, 1, 1, 2)) == [6, 4, 1]\n        @test @inferred(getindex(g, CartesianIndex(1, 1, 2))) == [6, 4, 1]\n        @test @inferred is_nash(g, (1, 1, 1))\n        @test @inferred !(is_nash(g, (1, 1, 2)))\n\n        p = (1 + sqrt(65)) / 16\n        @test is_nash(g, ([1-p, p], [1-p, p], [1-p, p]))\n    end\n\n    @testset \"NormalFormGame input action sizes\" begin\n        g = @inferred NormalFormGame((2, 3, 4))\n\n        @test @inferred(num_players(g)) == 3\n        @test g.players[1].payoff_array == zeros((2, 3, 4))\n        @test g.players[2].payoff_array == zeros((3, 4, 2))\n        @test g.players[3].payoff_array == zeros((4, 2, 3))\n    end\n\n    @testset \"NormalFormGame setindex\" begin\n        g = @inferred NormalFormGame((2, 2))\n        g[1, 1] = [0, 10]\n        g[1, 2] = [0, 10]\n        g[2, 1] = [3, 5]\n        g[CartesianIndex(2, 2)] = [-2, 0]\n\n        @test g.players[1].payoff_array == [0 0; 3 -2]\n        @test g.players[2].payoff_array == [10 5; 10 0]\n    end\n\n    @testset \"NormalFormGame constant payoffs\" begin\n        g = NormalFormGame((2, 2))\n\n        @test @inferred is_nash(g, (1, 1))\n        @test is_nash(g, (1, 2))\n        @test is_nash(g, (2, 1))\n        @test is_nash(g, (2, 2))\n    end\n\n    @testset \"convert for NormalFormGame\" begin\n        T1 = Int\n        T2 = Float64\n        players = (Player(T1[1 2 3; 4 5 6]), Player(T1[7 8; 9 10; 11 12]))\n        g = NormalFormGame(players)\n        N = num_players(g)\n\n        for T in [T1, T2]\n            g_new = @inferred NormalFormGame{N,T}(g)\n            for (player_new, player) in zip(g_new.players, players)\n                @test eltype(player_new.payoff_array) == T\n                @test player_new.payoff_array == player.payoff_array\n\n                # Constructor always makes a copy\n                @test player_new.payoff_array !== player.payoff_array\n            end\n        end\n\n        for T in [T1, T2]\n            g_new = @inferred NormalFormGame(T, g)\n            for (player_new, player) in zip(g_new.players, players)\n                @test eltype(player_new.payoff_array) == T\n                @test player_new.payoff_array == player.payoff_array\n\n                # Constructor always makes a copy\n                @test player_new.payoff_array !== player.payoff_array\n            end\n        end\n\n        g_new = @inferred NormalFormGame(g)\n        for (player_new, player) in zip(g_new.players, players)\n            @test eltype(player_new.payoff_array) == T1\n            @test player_new.payoff_array == player.payoff_array\n\n            # Constructor always makes a copy\n            @test player_new.payoff_array !== player.payoff_array\n        end\n\n        for T in [T1, T2]\n            g_new = @inferred convert(NormalFormGame{N,T}, g)\n            for (player_new, player) in zip(g_new.players, players)\n                @test eltype(player_new.payoff_array) == T\n                @test player_new.payoff_array == player.payoff_array\n\n                @test (player_new.payoff_array === player.payoff_array) ===\n                      (T == T1)\n            end\n        end\n    end\n\n    @testset \"Tests on delete_action for NormalFormGame\" begin\n        shapley_game = Array{Int}(undef, 3, 3, 2)\n        shapley_game[:, 1, 1] = [0, 0, 1]\n        shapley_game[:, 2, 1] = [1, 0, 0]\n        shapley_game[:, 3, 1] = [0, 1, 0]\n        shapley_game[:, 1, 2] = [0, 1, 0]\n        shapley_game[:, 2, 2] = [0, 0, 1]\n        shapley_game[:, 3, 2] = [1, 0, 0]\n        g = NormalFormGame(shapley_game)\n\n        deleted_game_1 = Array{Int}(undef, 2, 3, 2)\n        deleted_game_1[:, 1, 1] = [0, 1]\n        deleted_game_1[:, 2, 1] = [0, 0]\n        deleted_game_1[:, 3, 1] = [1, 0]\n        deleted_game_1[:, 1, 2] = [1, 0]\n        deleted_game_1[:, 2, 2] = [0, 1]\n        deleted_game_1[:, 3, 2] = [0, 0]\n\n        deleted_game_2 = Array{Int}(undef, 1, 3, 2)\n        deleted_game_2[1, 1, 1] = 1\n        deleted_game_2[1, 2, 1] = 0\n        deleted_game_2[1, 3, 1] = 0\n        deleted_game_2[1, 1, 2] = 0\n        deleted_game_2[1, 2, 2] = 1\n        deleted_game_2[1, 3, 2] = 0\n\n        g_new_1 = @inferred delete_action(g, 1, 1)\n        g_new_2 = @inferred delete_action(g, [1, 2], 1)\n        @test g_new_1.players[1].payoff_array ==\n            NormalFormGame(deleted_game_1).players[1].payoff_array\n        @test g_new_1.players[2].payoff_array ==\n            NormalFormGame(deleted_game_1).players[2].payoff_array\n        @test g_new_2.players[1].payoff_array ==\n            NormalFormGame(deleted_game_2).players[1].payoff_array\n        @test g_new_2.players[2].payoff_array ==\n            NormalFormGame(deleted_game_2).players[2].payoff_array\n    end\n\n    # Trivial cases with one player #\n\n    @testset \"Player with 0 opponents\" begin\n        payoffs = [0, 1]\n        player = Player(payoffs)\n\n        @test @inferred(payoff_vector(player, nothing)) == [0, 1]\n        @test @inferred is_best_response(player, 2, nothing)\n        @test @inferred(best_response(player, nothing)) == 2\n        @test @inferred is_dominated(player, 1)\n        @test !is_dominated(player, 2)\n\n        payoffs = [0, 1, -1]\n        player = Player(payoffs)\n        dom_actions = [1, 3]\n        @test @inferred(dominated_actions(player)) == dom_actions\n\n    end\n\n    @testset \"NormalFormGame with 1 player\" begin\n        payoffs = [0, 1, 1]\n        g = @inferred NormalFormGame(Player(payoffs))\n        @test num_players(g) == 1\n        @test g.players[1].payoff_array == [0, 1, 1]\n        @test g[1] == 0\n        @test is_nash(g, 2)\n        @test !(is_nash(g, 1))\n        @test is_nash(g, [0, 1/2, 1/2])\n\n        g = NormalFormGame((2,))\n        @test num_players(g) == 1\n        @test g.players[1].payoff_array == zeros(2)\n        g[1] = 10\n        @test g.players[1].payoff_array == [10, 0]\n    end\n\n    # Invalid inputs #\n\n    @testset \"Player 0 actions\" begin\n        @test_throws ArgumentError p = Player(Float64[])\n    end\n\n    @testset \"NormalFormGame invalid players shape inconsistent\" begin\n        p1 = Player(zeros((2, 3)))\n        p2 = Player(zeros((2, 3)))\n        @test_throws ArgumentError g = NormalFormGame((p1, p2))\n    end\n\n    @testset \"NormalFormGame invalid players number inconsistent\" begin\n        p1 = Player(zeros((2, 2, 2)))\n        p2 = Player(zeros((2, 2, 2)))\n        @test_throws MethodError g = NormalFormGame((p1, p2))\n    end\n\n    @testset \"NormalFormGame invalid nonsquare matrix\" begin\n        @test_throws ArgumentError g = NormalFormGame(zeros((2, 3)))\n\n        A = [0, 1, 1]\n        A = reshape(A, (size(A)..., 1))\n        @test_throws ArgumentError g = NormalFormGame(A)\n    end\n\n    @testset \"NormalFormGame invalid payoff profiles\" begin\n        @test_throws ArgumentError g = NormalFormGame(zeros((2, 2, 1)))\n    end\n\n    @testset \"NormalFormGame empty tuple\" begin\n        @test_throws ArgumentError g = NormalFormGame(tuple())\n    end\n\n    @testset \"NormalFormGame 0 actions\" begin\n        @test_throws ArgumentError g = NormalFormGame((0, 2))\n    end\n\n    @testset \"payoff_vector empty tuple\" begin\n        p1 = Player(zeros((2, 2, 2)))\n        @test_throws ArgumentError payoff_vector(p1, tuple())\n    end\n\n    @testset \"is_dominated linprog error\" begin\n        player = Player([1. 1.; 0. -1.; -1. 0.])\n\n        function clp_optimizer_silent_maxiter1()\n            optimizer = Clp.Optimizer()\n            MOI.set(optimizer, MOI.Silent(), true)\n            MOI.set(optimizer, MOI.RawParameter(\"MaximumIterations\"), 1)\n            return optimizer\n        end\n        lp_solver = clp_optimizer_silent_maxiter1\n        @test_throws ErrorException is_dominated(player, 1,\n                                                 lp_solver=lp_solver)\n    end\n\n    # Utility functions #\n\n    @testset \"pure2mixed\" begin\n        num_actions = 3\n        pure_action = 1\n        mixed_action = [1., 0., 0.]\n        @test @inferred(pure2mixed(num_actions, pure_action)) == mixed_action\n    end\n\n    # Pareto efficiency & Pareto dominance #\n\n    @testset \"Tests on Pareto efficiency and dominance\" begin\n        coordination_game_matrix = [4 0;\n                                    3 2]\n\n        equal_po_p1_bimatrix = Array{Float64}(undef, 2, 2, 2)\n        equal_po_p1_bimatrix[1, 1, :] = [1, -1]\n        equal_po_p1_bimatrix[1, 2, :] = [1, 1]\n        equal_po_p1_bimatrix[2, 1, :] = [1, 1]\n        equal_po_p1_bimatrix[2, 2, :] = [1, -1]\n\n        three_p_equal_po_array = Array{Int}(undef, 2, 2, 2)\n        three_p_equal_po_array[:, :, 1] = [2 0; 0 2]\n        three_p_equal_po_array[:, :, 2] = [2 0; 0 2]\n\n        p1 = p2 = p3 = Player(three_p_equal_po_array)\n\n        games_dict = [NormalFormGame(coordination_game_matrix),\n                      NormalFormGame(equal_po_p1_bimatrix),\n                      NormalFormGame((p1, p2, p3))]\n\n        act_prof_dict = [[(1, 1), (1, 2), (2, 1), (2, 2)],\n                         [(1, 1), (1, 2), (2, 1), (2, 2)],\n                         [(1, 1, 1), (2, 1, 1), (1, 2, 1), (2, 2, 1),\n                          (1, 1, 2), (2, 1, 2), (1, 2, 2), (2, 2, 2)]]\n\n        @testset \"Testing is_pareto_efficient\" begin\n            output_dict = [[true, false, false, false],\n                           [false, true, true, false],\n                           [true, false, false, false, false, false, false,\n                            true]]\n\n            for i = 1:length(games_dict)\n                for j in 1:length(act_prof_dict[i])\n                    @test @inferred is_pareto_efficient(games_dict[i],\n                                                       act_prof_dict[i][j]) ==\n                                    output_dict[i][j]\n                end\n            end\n        end\n\n        @testset \"Testing Pareto dominance\" begin\n            output_dict = [[true, false, false, false],\n                           [false, false, false, false],\n                           [false, false, false, false, false, false, false,\n                            false]]\n\n            for i = 1:length(games_dict)\n                for j in 1:length(act_prof_dict[i])\n                    @test @inferred is_pareto_dominant(games_dict[i],\n                                                       act_prof_dict[i][j]) ==\n                                    output_dict[i][j]\n                end\n            end\n        end\n\n        @testset \"Test is_dominated\" begin\n            coordination_game_matrix = [4 0; 3 2]\n            player = Player(coordination_game_matrix)\n            for action = 1:num_actions(player)\n                @test !is_dominated(player, action)\n            end\n\n            payoffs_2opponents = Array{Int}(undef, 2, 2, 2)\n            payoffs_2opponents[:, 1, 1] = [3, 1]\n            payoffs_2opponents[:, 1, 2] = [6, 0]\n            payoffs_2opponents[:, 2, 1] = [4, 5]\n            payoffs_2opponents[:, 2, 2] = [2, 7]\n            player = Player(payoffs_2opponents)\n\n            for i = 1:num_actions(player)\n                @test !is_dominated(player, i)\n            end\n\n        end\n\n        @testset \"Test player corner cases\" begin\n            n, m = 3, 4\n            player = Player(zeros((n, m)))\n            for action = 1:n\n                @test is_best_response(player, action, ones(m) * 1/m)\n                @test !is_dominated(player, action)\n            end\n\n            e = 1e-8\n            player = Player([-e -e;\n                             1 -1;\n                             -1 1])\n            action = 1\n            @test is_best_response(player, action, [1/2, 1/2], tol=e)\n            @test !is_best_response(player, action, [1/2, 1/2], tol=e/2)\n            @test !is_dominated(player, action, tol=e+1e-16)\n            @test dominated_actions(player, tol=e+1e-16) == Int[]\n            @test is_dominated(player, action, tol=e/2)\n            @test dominated_actions(player, tol=e/2) == [action]\n        end\n\n        @testset \"Test rational input game\" begin\n            T = Rational{BigInt}\n            lp_solver = CDDLib.Optimizer{T}\n\n            # Corner cases\n            e = 1//(2^25)\n            player = Player([-e -e;\n                             1//1 -1//1;\n                             -1//1 1//1])\n\n            action = 1\n            @test !is_dominated(T, player, action, tol=e, lp_solver=lp_solver)\n            @test is_dominated(T, player, action, tol=e//2, lp_solver=lp_solver)\n\n            player.payoff_array[1, 1:2] .= 0;\n\n            @test !is_dominated(T, player, action, tol=0, lp_solver=lp_solver)\n\n            # Simple game\n            game_matrix = [2//3 1//3;\n                           1//3 2//3]\n            player = Player(game_matrix)\n\n            @test dominated_actions(T, player, lp_solver=lp_solver) == Int[]\n        end\n    end\n\nend\n", "meta": {"hexsha": "5905632ada13360f62166d66902d2021a9105d88", "size": 18758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_normal_form_game.jl", "max_stars_repo_name": "QuantEcon/Games.jl", "max_stars_repo_head_hexsha": "f68c44c3c7ac7e8ae81b4890ac20e35562a6375c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2016-04-04T15:32:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T02:58:19.000Z", "max_issues_repo_path": "test/test_normal_form_game.jl", "max_issues_repo_name": "QuantEcon/Games.jl", "max_issues_repo_head_hexsha": "f68c44c3c7ac7e8ae81b4890ac20e35562a6375c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 120, "max_issues_repo_issues_event_min_datetime": "2016-02-17T20:48:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-15T16:04:19.000Z", "max_forks_repo_path": "test/test_normal_form_game.jl", "max_forks_repo_name": "QuantEcon/Games.jl", "max_forks_repo_head_hexsha": "f68c44c3c7ac7e8ae81b4890ac20e35562a6375c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2016-04-08T15:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T17:22:17.000Z", "avg_line_length": 36.1425818882, "max_line_length": 82, "alphanum_fraction": 0.5428084017, "num_tokens": 5747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.8705972549785201, "lm_q1q2_score": 0.7827725982370369}}
{"text": "# This file was generated, do not modify it.\n\nusing MLJ, RDatasets, Random\n\ndata = dataset(\"datasets\", \"USArrests\")\nnames(data)\n\ndescribe(data, :mean, :std)\n\nX = select(data, Not(:State))\nX = coerce(X, :UrbanPop=>Continuous);\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\nschema(W).names\n\nr = report(pca)\ncumsum(r.principalvars ./ r.tvar)\n\ndata = dataset(\"ISLR\", \"OJ\")\n\nX = select(data, [:PriceCH, :PriceMM, :DiscCH, :DiscMM, :SalePriceMM,\n                  :SalePriceCH, :PriceDiff, :PctDiscMM, :PctDiscCH]);\n\nRandom.seed!(1515)\n\n@pipeline SPCA(std = Standardizer(),\n               pca = PCA())\nspca_mdl = SPCA()\nspca = machine(spca_mdl, X)\nfit!(spca)\nW = transform(spca, X)\nnames(W)\n\nr = report(spca).reports[1]\ncumsum(r.principalvars ./ r.tvar)\n\nRandom.seed!(1515)\n\n@load KMeans\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\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(\"assets/literate/ISL-lab-10-cluster.svg\") # hide\n\n", "meta": {"hexsha": "2c7fcf0d77a4f8a58654b745c31d8b5dd3f91156", "size": 1506, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "assets/literate/ISL-lab-10_script.jl", "max_stars_repo_name": "vdayanand/MLJTutorials", "max_stars_repo_head_hexsha": "702effdcfadb44fb7c4fe61355f0c481595c95bf", "max_stars_repo_licenses": ["MIT"], "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/literate/ISL-lab-10_script.jl", "max_issues_repo_name": "vdayanand/MLJTutorials", "max_issues_repo_head_hexsha": "702effdcfadb44fb7c4fe61355f0c481595c95bf", "max_issues_repo_licenses": ["MIT"], "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/literate/ISL-lab-10_script.jl", "max_forks_repo_name": "vdayanand/MLJTutorials", "max_forks_repo_head_hexsha": "702effdcfadb44fb7c4fe61355f0c481595c95bf", "max_forks_repo_licenses": ["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.6301369863, "max_line_length": 73, "alphanum_fraction": 0.6420982736, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7827254201211744}}
{"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": "# Triangular decompostion with Partial Pivoting \n\np = collect (1:m)                                       # initialization of the permutation vector\n\nfor k=1:m\n    j = indmax(abs(A[k:m,k])); j = k-1+j                # pivot search\n    p[[k,j]] = p[[j,k]]; A[[k,j],:] = A[[j,k],:]        # row swap\n    A[k+1:m,k] /= A[k,k]\n    A[k+1:m,k+1:m]  -= A[k+1:m,k]*A[k:k,k+1:m]\nend", "meta": {"hexsha": "e8552d9301efa1edf92a99eb6044190f36330c10", "size": 373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/Numerical Analysis & Machine Learning/Numerical Linear Algebra/TriangularDecomposition.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/TriangularDecomposition.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/TriangularDecomposition.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": 37.3, "max_line_length": 98, "alphanum_fraction": 0.4557640751, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263197, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7827090636676832}}
{"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\u0394x = xv[2]-xv[1]\nx = xv[1:end-1] .+ \u0394x/2 # m+1 cell centers\n\n\u0394t = .9*\u0394x # 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/\u0394t)\n\u0394t = 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 .- \u0394t/\u0394x .* diff(pflux)\n    u .= u .- \u0394t/\u0394x .* diff(uflux)\n\n    if k % interval==0\n        plot(x,p,linewi\u0394th=2,legend=false,title=\"Solution at time $(k*\u0394t)\",ylims=(-1.5,1.5))\n        println(\"on timestep $k out of $Nsteps.\")\n    end\nend every interval\n# plot(x,u,linewi\u0394th=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') = \u03c3\u00b2\\\\exp(- (x - x')\u1d40(x - x')/(2\u2113\u00b2))\n```\nwith length scale ``\u2113`` and signal standard deviation ``\u03c3``.\n\"\"\"\nmutable struct SEIso <: Isotropic{SqEuclidean}\n    \"Squared length scale\"\n    \u21132::Float64\n    \"Signal variance\"\n    \u03c32::Float64\n    \"Priors for kernel parameters\"\n    priors::Array\n\n    \"\"\"\n        SEIso(ll::Float64, l\u03c3::Float64)\n\n    Create `SEIso` with length scale `exp(ll)` and signal standard deviation `exp(l\u03c3)`.\n    \"\"\"\n    SEIso(ll::Float64, l\u03c3::Float64) = new(exp(2 * ll), exp(2 * l\u03c3), [])\nend\n\nfunction set_params!(se::SEIso, hyp::VecF64)\n    length(hyp) == 2 || throw(ArgumentError(\"Squared exponential only has two parameters\"))\n    se.\u21132, se.\u03c32 = exp(2 * hyp[1]), exp(2 * hyp[2])\nend\n\nget_params(se::SEIso) = Float64[log(se.\u21132) / 2, log(se.\u03c32) / 2]\nget_param_names(se::SEIso) = [:ll, :l\u03c3]\nnum_params(se::SEIso) = 2\n\nStatistics.cov(se::SEIso, r::Float64) = se.\u03c32*exp(-0.5*r/se.\u21132)\n\n@inline dk_dll(se::SEIso, r::Float64) = r/se.\u21132*cov(se,r)\n@inline function dk_d\u03b8p(se::SEIso, r::Float64, p::Int)\n    if p==1\n        return dk_dll(se, r)\n    elseif p==2\n        return dk_dl\u03c3(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') - \u03b2 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(\u03bc::Float32, \u03c3::Float32, X)\n\n    f = -.5f0*((X .- \u03bc)/\u03c3).^2\n    f = f .+ -5f-1 * log(2f0\u03c0) .- log(\u03c3)\n\n    return f\nend\n\nfunction gradlogpdf(\u03bc::Float32, \u03c3::Float32, X)\n\n    g = -(X .- \u03bc)/\u03c3^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": "n = 10 # rand(1:10)\n@test matrixdepot(\"fiedler\", n) == matrixdepot(\"fiedler\", [1:n;])\n\nA = matrixdepot(\"fiedler\", n)\n\n@test issymmetric(A)\nfor i = 1:n, j =1:n\n    @test A[i,j] \u2248 abs(i-j)\nend\nprintln(\"'fiedler' passed test...\")\n", "meta": {"hexsha": "c24af6857a92a62a8d294be4d8d554d9e2a824fd", "size": 227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_fiedler.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_fiedler.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_fiedler.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 20.6363636364, "max_line_length": 65, "alphanum_fraction": 0.6035242291, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7826912868754408}}
{"text": "using MultipleViewGeometry, Test\nusing MultipleViewGeometry.ModuleCostFunction\nusing MultipleViewGeometry.ModuleTypes\nusing MultipleViewGeometry.ModuleConstraints\nusing StaticArrays, Random, LinearAlgebra\n\n# Fix random seed.\nRandom.seed!(1234)\n\n# Test for cost functions.\n\n\n# Test cost function on Fundamental matrix estimation.\n\n\ud835\udcb3 = [Point3D(x,y,rand(50:100)) for x = -100:5:100 for y = -100:5:100]\n\ud835\udcb3 = \ud835\udcb3[1:50:end]\n\n\n# Specify the coordinate systems of the world, the camera frame and the picture\n# plane.\nworld_basis = (Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0), Vec(0.0, 0.0, 1.0))\ncamera_basis = (Point(0.0, 0.0, 0.0), Vec(-1.0, 0.0, 0.0), Vec(0.0, -1.0, 0.0), Vec(0.0, 0.0, 1.0))\npicture_basis = (Point(0.0, 0.0), Vec(-1.0, 0.0), Vec(0.0, -1.0))\n\n# The focal length for both cameras is one.\nf = 1\nimage_width = 640 / 10\nimage_height = 480 / 10\n\ncamera\u2081 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\ncamera\u2082 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\n\n# Rotate and translate camera one.\n\ud835\udc11\u2081 = Matrix{Float64}(I,3,3)\n\ud835\udc2d\u2081 = [-50.0, -2.0, 0.0]\nrelocate!(camera\u2081, \ud835\udc11\u2081, \ud835\udc2d\u2081)\n\n# Rotate and translate camera two.\n\ud835\udc11\u2082 = Matrix{Float64}(I,3,3)\n\ud835\udc2d\u2082 = [50.0, 2.0, 0.0]\nrelocate!(camera\u2082, \ud835\udc11\u2082, \ud835\udc2d\u2082)\n\n\n\ud835\udc11\u2081\u2032, \ud835\udc2d\u2081\u2032 = ascertain_pose(camera\u2081, world_basis... )\n\ud835\udc0a\u2081\u2032 = obtain_intrinsics(camera\u2081, CartesianSystem())\n\ud835\udc11\u2082\u2032, \ud835\udc2d\u2082\u2032 = ascertain_pose(camera\u2082, world_basis... )\n\ud835\udc0a\u2082\u2032 = obtain_intrinsics(camera\u2082, CartesianSystem())\n\n# Camera projection matrices.\n\ud835\udc0f\u2081 = construct(ProjectionMatrix(),\ud835\udc0a\u2081\u2032,\ud835\udc11\u2081\u2032,\ud835\udc2d\u2081\u2032)\n\ud835\udc0f\u2082 = construct(ProjectionMatrix(),\ud835\udc0a\u2082\u2032,\ud835\udc11\u2082\u2032,\ud835\udc2d\u2082\u2032)\n\n# Set of corresponding points.\n\u2133 = project(camera\u2081,\ud835\udc0f\u2081,\ud835\udcb3)\n\u2133\u02b9 = project(camera\u2082,\ud835\udc0f\u2082,\ud835\udcb3)\n\n\ud835\udc05 = construct(FundamentalMatrix(),\ud835\udc0a\u2081\u2032,\ud835\udc11\u2081\u2032,-\ud835\udc2d\u2081\u2032,\ud835\udc0a\u2082\u2032,\ud835\udc11\u2082\u2032,-\ud835\udc2d\u2082\u2032)\n\n# Verify that the algorithm returns the correct answer when the\n# constraint is already satisfied.\n\ud835\udcaa,\ud835\udcaa\u02b9 = satisfy(FundamentalMatrix(), EpipolarConstraint(), \ud835\udc05, (\u2133, \u2133\u02b9))\n\n# Verify that the original corresponding points satisfy the epipolar constraint.\nN = length(\u2133)\nfor n = 1:N\n    \ud835\udc26 = hom(\u2133[n])\n    \ud835\udc26\u02b9 = hom(\u2133\u02b9[n])\n    @test  isapprox(\ud835\udc26'*\ud835\udc05*\ud835\udc26\u02b9, 0.0; atol = 1e-12)\nend\n\n# Verify that the 'corrected' points satisfy the epipolar constraint.\nN = length(\u2133)\nfor n = 1:N\n    \ud835\udc26 = hom(\ud835\udcaa[n])\n    \ud835\udc26\u02b9 = hom(\ud835\udcaa\u02b9[n])\n    @test  isapprox(\ud835\udc26'*\ud835\udc05*\ud835\udc26\u02b9, 0.0; atol = 1e-12)\nend\n\n# Perturb the original corresponding points slightly so that they no-longer\n# satisfy the epipolar constraint.\nN = length(\u2133)\n\u03c3 = 1e-7\nfor n = 1:N\n    \u2133[n] = \u2133[n] + SVector{2}(\u03c3 * rand(2,1))\n    \u2133\u02b9[n] = \u2133\u02b9[n] + SVector{2}(\u03c3 * rand(2,1))\n    \ud835\udc26 = hom(\u2133[n])\n    \ud835\udc26\u02b9 = hom(\u2133\u02b9[n])\n    @test abs(\ud835\udc26'*\ud835\udc05*\ud835\udc26\u02b9) > 1e-12\nend\n\n\n# Verify that the algorithm returns the correct answer when applied\n# to sets of correspondences that do not satisfy the epipolar constraint.\n\ud835\udcaa ,\ud835\udcaa\u02b9 = satisfy(FundamentalMatrix(), EpipolarConstraint(), \ud835\udc05, (\u2133, \u2133\u02b9))\n\n# Verify that the 'corrected' points satisfy the epipolar constraint.\nN = length(\u2133)\nfor n = 1:N\n    \ud835\udc26 = hom(\ud835\udcaa[n])\n    \ud835\udc26\u02b9 = hom(\ud835\udcaa\u02b9[n])\n    @test  isapprox(\ud835\udc26'*\ud835\udc05*\ud835\udc26\u02b9, 0.0; atol = 1e-12)\nend\n", "meta": {"hexsha": "47c8e0aba863a739c203495b6089ae086d564e00", "size": 2990, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/satisfy_epipolar_constraints_tests.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": "test/satisfy_epipolar_constraints_tests.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": "test/satisfy_epipolar_constraints_tests.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": 29.0291262136, "max_line_length": 99, "alphanum_fraction": 0.6789297659, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7826912868754408}}
{"text": "using Statistics\nusing Printf\nusing Flux\nusing Plots\n\n# Flux uses Float32 by default so let's just use that!\nconst FT = Float32\n\nfunction generate_training_data(f; N, domain)\n    x = range(domain[1], domain[2], length=N)\n    return @. FT(x), FT(f(x))\nend\n\nfunction generate_neural_network(; layers, nodes=1, activation=identity)\n    return Chain([Dense(l == 1 ? 1 : nodes, l == layers ? 1 : nodes, activation) for l in 1:layers]...)\nend\n\nfunction learn_scalar_function!(NN, f; N, domain, epochs, optimizers=[ADAM()])\n    xs, ys = generate_training_data(f; N, domain)\n    training_data = zip(xs, ys) |> collect\n\n    loss(x, y) = Flux.mse(NN([x]), y)\n    function callback()\n        \u03bc_loss = mean(loss(d...) for d in training_data)\n        @info @sprintf(\"mean squared error loss = %.16e\", \u03bc_loss)\n        return \u03bc_loss\n    end\n\n    for opt in optimizers, e in 1:epochs\n        @info \"Training with $(typeof(opt))(\u03b7=$(opt.eta)) [epoch $e/$epochs]...\"\n        Flux.train!(loss, Flux.params(NN), training_data, opt, cb=callback)\n    end\n\n    return NN\nend\n\nfunction test_learned_mapping(f, NN; N, domain)\n    xs, ys_truth = generate_training_data(f; N, domain)\n    ys_NN = [NN([x])[1] for x in xs]\n\n    kwargs = (linewidth=3, linealpha=0.8, xlims=extrema(xs),\n              grid=false, legend=:bottomright, framestyle=:box,\n              foreground_color_legend=nothing, background_color_legend=nothing)\n\n    fit_plot = plot(xs, ys_truth, label=\"truth\", title=\"Fit\", xlabel=\"x\", ylabel=\"y\"; kwargs...)\n    plot!(fit_plot, xs, ys_NN, label=\"neural network\"; kwargs...)\n\n    loss = @. abs(ys_NN - ys_truth) / abs(ys_truth)\n    ylims = (10^floor(log10(minimum(loss))), 10^ceil(log10(maximum(loss))))\n    loss_plot = plot(xs, loss, label=\"\", title=\"extrapolation accuracy\", xlabel=\"x\", ylabel=\"|y\u2032 - y| / y\", yaxis=:log, ylims=ylims; kwargs...)\n\n    return plot(fit_plot, loss_plot, layout=(2, 1))\nend\n\nlinear(x) = x\nNN = generate_neural_network(layers=1)\nlearn_scalar_function!(NN, linear, N=10, domain=(-1, 1), epochs=20, optimizers=[Descent()])\ntest_learned_mapping(linear, NN, N=100, domain=(-100, 100))\n\nquadratic(x) = x^2\nNN = generate_neural_network(layers=20, nodes=20)\nlearn_scalar_function!(NN, quadratic, N=10, domain=(0, 1), epochs=10, optimizers=[ADAM()])\ntest_learned_mapping(quadratic, NN, N=100, domain=(0, 2))\n", "meta": {"hexsha": "cfd15c1abc50d0264463dd4fa2496eb5150e7369", "size": 2319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "playground.jl", "max_stars_repo_name": "ali-ramadhan/UniversalApproximationTheorem.jl", "max_stars_repo_head_hexsha": "9fae98dc72c21e77ffe85a220488b720c47d180e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "playground.jl", "max_issues_repo_name": "ali-ramadhan/UniversalApproximationTheorem.jl", "max_issues_repo_head_hexsha": "9fae98dc72c21e77ffe85a220488b720c47d180e", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "ali-ramadhan/UniversalApproximationTheorem.jl", "max_forks_repo_head_hexsha": "9fae98dc72c21e77ffe85a220488b720c47d180e", "max_forks_repo_licenses": ["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.234375, "max_line_length": 143, "alphanum_fraction": 0.6640793445, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7826912796883421}}
{"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.(\u03c0*x)\n\n@inline function f(du,u,p,t)\n  du .= zero(eltype(u))\n  u\u2083 = @view u[3:end]\n  u\u2082 = @view u[2:end-1]\n  u\u2081 = @view u[1:end-2]\n  @. du[2:end-1] = p.k*((u\u2083 - 2*u\u2082 + u\u2081)/(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 \u2248 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": "using StatsBase\nusing Base.Test\n\nX = randn(3, 8)\n\nZ1 = X .- mean(X, 1)\nZ2 = X .- mean(X, 2)\n\nw1 = rand(3)\nw2 = rand(8)\n\nwv1 = weights(w1)\nwv2 = weights(w2)\n\nZ1w = X .- mean(X, wv1, 1)\nZ2w = X .- mean(X, wv2, 2)\n\n## reference results\n\nS1 = Z1'Z1\nS2 = Z2 * Z2'\n\nSz1 = X'X\nSz2 = X * X'\n\nS1w = Z1w' * diagm(w1) * Z1w\nS2w = Z2w * diagm(w2) * Z2w'\n\nSz1w = X' * diagm(w1) * X\nSz2w = X * diagm(w2) * X'\n\n## scattermat\n\n@test_approx_eq scattermat(X) S1\n@test_approx_eq scattermat(X; vardim=2) S2\n\n@test_approx_eq scattermat(X; mean=0) Sz1\n@test_approx_eq scattermat(X; mean=0, vardim=2) Sz2\n\n@test_approx_eq scattermat(X; mean=mean(X,1)) S1\n@test_approx_eq scattermat(X; mean=mean(X,2), vardim=2) S2\n\n@test_approx_eq scattermat(X; mean=zeros(1,8)) Sz1\n@test_approx_eq scattermat(X; mean=zeros(3), vardim=2) Sz2\n\n## weighted scatter mat\n\n@test_approx_eq scattermat(X, wv1) S1w\n@test_approx_eq scattermat(X, wv2; vardim=2) S2w\n\n@test_approx_eq scattermat(X, wv1; mean=0) Sz1w\n@test_approx_eq scattermat(X, wv2; mean=0, vardim=2) Sz2w\n\n@test_approx_eq scattermat(X, wv1; mean=mean(X, wv1, 1)) S1w\n@test_approx_eq scattermat(X, wv2; mean=mean(X, wv2, 2), vardim=2) S2w\n\n@test_approx_eq scattermat(X, wv1; mean=zeros(1,8)) Sz1w\n@test_approx_eq scattermat(X, wv2; mean=zeros(3), vardim=2) Sz2w\n\n# weighted covariance\n\n@test_approx_eq cov(X, wv1) S1w ./ sum(wv1)\n@test_approx_eq cov(X, wv2; vardim=2) S2w ./ sum(wv2)\n\n@test_approx_eq cov(X, wv1; mean=0) Sz1w ./ sum(wv1)\n@test_approx_eq cov(X, wv2; mean=0, vardim=2) Sz2w ./ sum(wv2)\n\n@test_approx_eq cov(X, wv1; mean=mean(X, wv1, 1)) S1w ./ sum(wv1)\n@test_approx_eq cov(X, wv2; mean=mean(X, wv2, 2), vardim=2) S2w ./ sum(wv2)\n\n@test_approx_eq cov(X, wv1; mean=zeros(1,8)) Sz1w ./ sum(wv1)\n@test_approx_eq cov(X, wv2; mean=zeros(3), vardim=2) Sz2w ./ sum(wv2)\n\n# mean_and_cov\n\n(m, C) = mean_and_cov(X; vardim=1)\n@test m == mean(X, 1)\n@test C == cov(X; vardim=1)\n\n(m, C) = mean_and_cov(X; vardim=2)\n@test m == mean(X, 2)\n@test C == cov(X; vardim=2)\n\n(m, C) = mean_and_cov(X, wv1; vardim=1)\n@test m == mean(X, wv1, 1)\n@test C == cov(X, wv1; vardim=1)\n\n(m, C) = mean_and_cov(X, wv2; vardim=2)\n@test m == mean(X, wv2, 2)\n@test C == cov(X, wv2; vardim=2)\n\n", "meta": {"hexsha": "2dee0f418c1c3d384bd07ff2a9efd125daa81e75", "size": 2185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cov.jl", "max_stars_repo_name": "wildart/StatsBase.jl", "max_stars_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_stars_repo_licenses": ["MIT"], "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/cov.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": "test/cov.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": 23.75, "max_line_length": 75, "alphanum_fraction": 0.6636155606, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7826648403163087}}
{"text": "using Luxor, Test\n\npi = \u03c0\n\nfunction paramCircle(t,r)\n    return Point(r*cos(t),r*sin(t)) \nend\n\nfunction drawCircle(radius)\n    start = 0\n    step = 0.001\n    endT = 2\u03c0\n    prevPoint = paramCircle(start, radius)\n    newpath()\n    for t in step:step:endT\n        currPoint = paramCircle(t,radius)\n        line(prevPoint,currPoint)\n        prevPoint = currPoint\n    end\n    strokepath()\nend\n\nfunction involuteCircle(t,r,a)\n    xOfT = r*(cos(t)+(t-a)*sin(t))\n    yOfT = r*(sin(t)-(t-a)*cos(t))\n    return Point(xOfT,yOfT) \nend\n\n\nfunction drawInvolute(startRadian, radius; clockwise= true)\n    start = startRadian\n    if clockwise == true\n        step = 0.001\n        endT = startRadian+2*pi\n    else\n        step = -0.01\n        endT = startRadian-2*pi\n    end\n    sethue(\"red\")\n    a = start\n    prevPoint = involuteCircle(start,radius,a)\n    newpath()\n    for t in start+step:step:endT\n        currPoint = involuteCircle(t,radius,a)\n        line(prevPoint,currPoint)\n        prevPoint = currPoint\n    end\n    strokepath()\nend\n\n\nfunction test_circleInvolute(fname)\n    pagewidth, pageheight = 1200, 1400\n    Drawing(pagewidth, pageheight, fname)\n\torigin()\n\tsethue(\"green\")\n\tradius = 200\n\tradiusOffset = 50\n\n\tdrawCircle(radius)\n\tsethue(\"blue\")\n\t#drawCircle(radius+radiusOffset)\n\n\trads = 0:pi/10:2*pi\n\n\tr = radius+radiusOffset+40\n\n\tfor myrad in rads\n\t\tdrawInvolute(myrad,radius)\n\t\tdrawInvolute(myrad,radius,clockwise=false)\n\t\t#newpath()\n\t\t#sethue(\"black\")\n\t\t#line(Point(0,0),Point(r*cos(myrad),r*sin(myrad)))\n\t\t#strokepath()\n\tend\n\n\t@test finish() == true\n\tprintln(\"...finished circle tangent test, saved in $(fname)\")\nend\n\nfname = \"circleInvolute_test.pdf\"\n\ntest_circleInvolute(fname)\npreview()\n", "meta": {"hexsha": "1b3c533666a731df548ea5a5a66097920fd1a4c9", "size": 1690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/circle-involute.jl", "max_stars_repo_name": "dietercastel/Luxor.jl", "max_stars_repo_head_hexsha": "c96fce741fe9d663756fafdc439385542293d466", "max_stars_repo_licenses": ["MIT"], "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/circle-involute.jl", "max_issues_repo_name": "dietercastel/Luxor.jl", "max_issues_repo_head_hexsha": "c96fce741fe9d663756fafdc439385542293d466", "max_issues_repo_licenses": ["MIT"], "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/circle-involute.jl", "max_forks_repo_name": "dietercastel/Luxor.jl", "max_forks_repo_head_hexsha": "c96fce741fe9d663756fafdc439385542293d466", "max_forks_repo_licenses": ["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.8823529412, "max_line_length": 62, "alphanum_fraction": 0.6526627219, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361742, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.782664839539597}}
{"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## \u4e8c\u53c9\u6811\u904d\u5386\n## \u5148\u5e8f\u904d\u5386 + \u4e2d\u5e8f\u904d\u5386\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) \u00f7 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` \u2208 [-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": "\u03b1 = 0.3\n\u03b4 = 0.1\n\u03b2 = 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]^\u03b1 + (1-\u03b4)*kgrid[i] - kgrid[j]\n    end\n    # vnew = maximum(log.(c) .+ \u03b2*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]^\u03b1 + (1-\u03b4)*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) .+ \u03b2*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]^\u03b1 + (1-\u03b4)*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) .+ \u03b2*v', dims = 2);\n        (vnew, cartesianindex) = findmax(log.(c) .+ \u03b2*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": "#= BINARY AND DECIMAL PREFIXES:\n2^10 ... kilo ... 10^3\n2^20 ... mega ... 10^6\n2^30 ... giga ... 10^9\n...\n2^(10*i) ... 10^(3*i)\n=#\n\nfunction simulate(multipliersOfInerest)\n    i = 0\n    for m in multipliersOfInerest\n        while (big(2)^big(10 * i) < m*big(10)^big(3 * i))\n            i +=1\n        end\n        println(\"Binary 2^$(10*i) is $m times larger than decimal 10^$(3*i) for i = $i\")\n    end\nend\n\n# Usage: simulate(multipliersOfInerest), where multipliersOfInerest ... range, array or something similar. \nprintln(\"Usage example: simulate(union(2:10, 100, 1000))\")", "meta": {"hexsha": "0be58669e842380dd1e271bf3264852f9cfd22da", "size": 571, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simulation.jl", "max_stars_repo_name": "zznidar/binary-vs-decimal-prefixes", "max_stars_repo_head_hexsha": "f534f00014c133667874dea61b41bece40f535d7", "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": "simulation.jl", "max_issues_repo_name": "zznidar/binary-vs-decimal-prefixes", "max_issues_repo_head_hexsha": "f534f00014c133667874dea61b41bece40f535d7", "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": "simulation.jl", "max_forks_repo_name": "zznidar/binary-vs-decimal-prefixes", "max_forks_repo_head_hexsha": "f534f00014c133667874dea61b41bece40f535d7", "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": 28.55, "max_line_length": 107, "alphanum_fraction": 0.5989492119, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7826493079183081}}
{"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    \u03c91Sol = [y1Sol -th1DotSol y1Sol]\n    \u03c92Sol = [y1Sol -th2DotSol y1Sol]\n    return r1Sol, r2Sol, v1Sol, v2Sol, \u03c91Sol, \u03c92Sol\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    \u2202lagrange(sp::T) where {T<:AbstractVector{<:Real}}\n    \u2202lagrange(V, Vr)\n    \u2202lagrange(V, Vr, Vs)\n\nCalculate derivatives of Lagrange polynomials dl\u2c7c(r\u1d62)\n\"\"\"\nfunction \u2202lagrange(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 \u2202lagrange(V, Vr)\n    Np = size(V, 1)\n\n    \u2202l = zeros(Np, Np)\n    for i = 1:Np\n        \u2202l[i, :] .= V' \\ Vr[i, :]\n    end\n\n    return \u2202l\nend\n\nfunction \u2202lagrange(V, Vr, Vs)\n    Np = size(V, 1)\n\n    \u2202l = zeros(Np, Np, 2)\n    for i = 1:Np\n        \u2202l[i, :, 1] .= V' \\ Vr[i, :]\n        \u2202l[i, :, 2] .= V' \\ Vs[i, :]\n    end\n\n    return \u2202l\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 = \u2202lagrange(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 \u00f7 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 \u00f7 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 \u00f7 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) \u2248 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 \u00f7 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\u22122789. 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, \u03b2)\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       \u03b2:     either 1 or 3\nOutput:\n       neff:  effective refractive index\n\"\"\"\nfunction gedf(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, p::S, \u03b2::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 + (\u03b2 * df2) + (\u03b2 * p * df1) - (\u03b2 * p * df2) ) ./ ( df1 + (\u03b2 * 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\u20132815. Here we used equation (3) and the parameters \u03d5, \u03d5c 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, \u03d5, \u03d5c, tp)\nInput:\n    n1:    refractive index of filling material (lower index)\n    n2:    refractive index of host material (higher index)\n    \u03d5:     porosity parameter (real number, 0<\u03d5<1), proportion of n1 over total\n    \u03d5c:    critical volume fraction at which the high-index phase first percolates\n    tp:    exponent related both to \u03d5c and to the shape of the grains\nOutput:\n    neff:  effective refractive index\n\"\"\"\nfunction gem(n1::AbstractArray{T,N}, n2::AbstractArray{T,N}, \u03d5::S, \u03d5c::S, tp::S) where {T<:Number, N, S<:Number}\n    # dielectric function of each media\n    \u03b1 = (1-\u03d5c)/\u03d5c\n    \u03b2 = 1/tp\n    df1 = (n1.^2).^\u03b2\n    df2 = (n2.^2).^\u03b2\n    deff = ((\u03b1*df1 - \u03d5*df1 - \u03b1*\u03d5*df1 - df2 + \u03d5*df2 + \u03b1*\u03d5*df2 + sqrt.(4*\u03b1*df1*df2 + ((\u03b1*(\u03d5-1) + \u03d5)*df1 + df2 - (1 + \u03b1)*\u03d5*df2).^2))/(2*\u03b1)).^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": "n = 5 # rand(1:5)\nA = matrixdepot(\"wathen\", n)\n\n@test typeof(A) <: SparseMatrixCSC\n@test issymmetric(Matrix(A))\n@test isposdef(Matrix(A))\n\nprintln(\"'wathen' passed test...\")\n", "meta": {"hexsha": "4877af24e96e03ecfd2783cd54274ba5db5bc7b1", "size": 174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_wathen.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_wathen.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_wathen.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-02-19T22:47:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:02:00.000Z", "avg_line_length": 19.3333333333, "max_line_length": 34, "alphanum_fraction": 0.6724137931, "num_tokens": 55, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632316144275, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7826115944824853}}
{"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    \u03a3 = fill(0.95, ndims, ndims)\n    \u03a3[diagind(\u03a3)] .= 1\n    cent_dist = MvNormal(\u03a3)\n    loglike(X) = logpdf(cent_dist, X)\n\n    model = NestedModel(loglike, priors)\n    true_lnZ = logpdf(MvNormal(fill(2, ndims), \u03a3 + 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": "using LinearAlgebra: I\n\n# Unit 2D square\nA = [[1 0];\n     [0 1];\n     [-1 0];\n     [0 -1]]\nb = [0, 0, -1, -1]\npoints, rays, bidrays = find_generators(A,b)\nP = Polytope(points, rays, bidrays)\nmins, maxs = min_max_projections(P)\nt_mins, t_maxs = Rational{Int}[0//1, 0//1], Rational{Int}[1//1, 1//1]\n@test t_mins == mins\n@test t_maxs == maxs\n\n# Single point\nA = [[1 1];\n     [-1 -1];\n     [1 -1];\n     [-1 1]]\nb = [1, -1, 0, 0]\npoints, rays, bidrays = find_generators(A,b)\nP = Polytope(points, rays, bidrays)\nmins, maxs = min_max_projections(P)\nt_mins, t_maxs = Rational{Int}[1//2, 1//2], Rational{Int}[1//2, 1//2]\n@test t_mins == mins\n@test t_maxs == maxs\n\n\n# The Fathomless Toblerone\nA = [[1 0 0];\n     [0 1 0];\n     [-1 -1 0];\n     [0 0 -1]]\nb = [0, 0, -2, 0]\npoints, rays, bidrays = find_generators(A,b)\nP = Polytope(points, rays, bidrays)\nmins, maxs = min_max_projections(P, [Array{Rational{Int}}(I, 3, 3) [1, 1, 0]])\nt_mins, t_maxs = Rational{Int}[0//1, 0//1, -1//0, 0//1], Rational{Int}[2//1, 2//1, 0//1, 2//1]\n@test t_mins == mins\n@test t_maxs == maxs\n\n# Half-space {(x,y,z): z \u2265 1}\nA = [0 0 1]\nb = [1]\npoints, rays, bidrays = find_generators(A,b)\nP = Polytope(points, rays, bidrays)\nmins, maxs = min_max_projections(P)\nt_mins, t_maxs = Rational{Int64}[-1//0,-1//0,1//1],Rational{Int64}[1//0,1//0,1//0]\n@test t_mins == mins\n@test t_maxs == maxs\n", "meta": {"hexsha": "f78fbe42ae7548d9533c8a4e6632cd2608a721a9", "size": 1350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 25.9615384615, "max_line_length": 94, "alphanum_fraction": 0.5925925926, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7825626380149368}}
{"text": "function calc_Energies( LF::LF3dGrid, Vpot, psi::Array{Float64,2} )\n  #\n  Ncol = size(psi)[2]\n  \u0394V = 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 ) * \u0394V\n    Epot = Epot + sum( Vpot .* psi[:,ic].^2 ) * \u0394V\n  end\n  Etot = Ekin + Epot\n  return EnergiesT( Etot, Ekin, Epot )\nend\n\n\nfunction calc_Energies( LF::LF3dGrid, \u22072::SparseMatrixCSC{Float64,Int64},\n                        Vpot, psi::Array{Float64,2} )\n  #\n  Ncol = size(psi)[2]\n  \u0394V = 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 = \u22072 * psi[:,ic]\n    Ekin = Ekin + -0.5*dot( psi[:,ic], nabla2_v ) * \u0394V\n    Epot = Epot + sum( Vpot .* psi[:,ic].^2 ) * \u0394V\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  \u03b1, \u03b2, \u03b4, \u03b3 = p\n  du[1] = dx = \u03b1*x - \u03b2*x*y\n  du[2] = dy = -\u03b4*y + \u03b3*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(\ud83d\udcd0\ufe0f)\n\nFind all three outer equilateral triangles of the triangle `\ud83d\udcd0\ufe0f`.\n\"\"\"\nfunction outer_equitriangles(\ud83d\udcd0\ufe0f)\n    pts = vertices(\ud83d\udcd0\ufe0f)\n    triangles = map(i->outer_equitri(circshift(pts, i)...), 0:2)\n    triangles\nend\n\n\n\"\"\"\n    isequilateral(\ud83d\udcd0\ufe0f)\n\nCheck if `\ud83d\udcd0\ufe0f` is equilateral, i.e., if the three edges of `\ud83d\udcd0\ufe0f` are of the same length.\n\"\"\"\nfunction isequilateral(\ud83d\udcd0\ufe0f)\n    dist = [squaredist(e.src, e.dst) for e in edges(\ud83d\udcd0\ufe0f)]\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": "\"\"\"\nfpatan is the derivative of atan\nused in the demo above\n\"\"\"\nfunction fpatan(x)\n    return 1 / (1 + x * x)\nend\n", "meta": {"hexsha": "3b577760c49689a0f187e4af8f2cdceae6733c68", "size": 114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestProblems/Scalars/fpatan.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/fpatan.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/fpatan.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": 14.25, "max_line_length": 32, "alphanum_fraction": 0.6403508772, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7825626279112881}}
{"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# \u2554\u2550\u2561 a3c276fe-30e3-11eb-3e4c-fb31d63eabf6\nusing ModelingToolkit, OrdinaryDiffEq, Plots, PlutoUI\n\n# \u2554\u2550\u2561 dc926c2c-30e4-11eb-0b88-05fc45844731\nimport Pkg; Pkg.add(\"OrdinaryDiffEq\")\n\n# \u2554\u2550\u2561 e0f36006-3ba1-11eb-3a47-193462d57302\nmd\"Enter a value for \u03b1 - natural exponential growth of the prey\n$(@bind \u03b1 Slider(1.0 : 1 : 10; default=1.0, show_value=true))\n\nEnter a value for \u03b2 - rate of decrease in prey from predators\n$(@bind \u03b2 Slider(1.0 : 1 : 10; default=2.0, show_value=true))\n\nEnter a value for \u03b4 - rate of predators growth by eating prey\n$(@bind \u03b4 Slider(0.5 : .05 : 5; default=1.5, show_value=true))\n\nEnter a value for \u03b3 - natural exponential decline of the predator\n$(@bind \u03b3 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# \u2554\u2550\u2561 7ebba51a-30e3-11eb-364e-f1255f41a963\nfunction fn_Lotka_Volterra(a,b,c,d,x0,y0)\n\t@parameters t \u03b1 \u03b2 \u03b4 \u03b3\n\t@variables x(t) y(t) \n\t@derivatives D'~t\n\n\teqs = [D(x) ~ \u03b1*x-\u03b2*x*y,\n\t\t   D(y) ~ \u03b4*x*y-\u03b3*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 = [\u03b1=>a, \u03b2=>b, \u03b4=>c, \u03b3=>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# \u2554\u2550\u2561 cb68360a-3b2f-11eb-3bef-b5e530f74f2e\nbegin\n\tsol1=fn_Lotka_Volterra(\u03b1,\u03b2,\u03b4,\u03b3,x0,y0)\n    plot(sol1)\nend\n\n# \u2554\u2550\u2561 5edf7256-3bbc-11eb-027d-a990de629754\nmd\"### Here are some specific scenarios.\n##### \u03b1=2.2,\u03b2=3.2,\u03b4=1.6,\u03b3=1.45  x0=2,y0=3 \"\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550dc926c2c-30e4-11eb-0b88-05fc45844731\n# \u2560\u2550a3c276fe-30e3-11eb-3e4c-fb31d63eabf6\n# \u2560\u25507ebba51a-30e3-11eb-364e-f1255f41a963\n# \u255f\u2500e0f36006-3ba1-11eb-3a47-193462d57302\n# \u2560\u2550cb68360a-3b2f-11eb-3bef-b5e530f74f2e\n# \u255f\u25005edf7256-3bbc-11eb-027d-a990de629754\n# \u2560\u2550c9c12e30-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": "using FundamentalsNumericalComputation,LinearAlgebra,DifferentialEquations\nusing Test\n\n@testset \"Chapter 1\" begin\n\t@test FNC.horner([-1,3,-3,1],1.6) \u2248 0.6^3\nend\n\n@testset \"Chapter 2\" begin\n\tA = [ 1 2 3 0; -1 1 2 -1; 3 1 2 4; 1 1 1 1 ]\n\tL,U = FNC.lufact(A)\n\t@test norm(L*U - A) < 100eps()\n\t@test norm(U - triu(U)) < 100eps()\n\t@test norm(L - tril(L)) < 100eps()\n\tb = [1,10,0,-1] / 5;\n\t@test norm(L\\b - FNC.forwardsub(L,b)) < 100eps()\n\t@test norm(U\\b - FNC.backsub(U,b)) < 100eps()\nend\n\n@testset \"Chapter 3\" begin\n\tA = [3 4 5;-1 0 1;4 2 0; 1 1 2; 3 -4 1]\n\tb = 5:-1:1\n\t@test FNC.lsnormal(A,b) \u2248 A\\b\n\t@test FNC.lsqrfact(A,b) \u2248 A\\b\n\tQ,R = qr(A)\n\tQQ,RR = FNC.qrfact(A)\n\t@test Q \u2248 QQ\n\t@test R \u2248 RR[1:3,:]\nend\n\n@testset \"Chapter 4\" begin\n\n\tfor c = [2,4,7.5,11]\n\t\tf = x -> exp(x) - x - c;\n\t\tdfdx = x -> exp(x) - 1;\n\t\tx = FNC.newton(f,dfdx,1.0);  r = x[end];\n\t\t@test abs(f(r)) < 100eps()\n\tend\n\n\tfor c = [2,4,7.5,11]\n\t\tf = x -> exp(x) - x - c;\n\t\tdfdx = x -> exp(x) - 1;\n\t\tx = FNC.secant(f,3,0.5);  r = x[end];\n\t\t@test abs(f(r)) < 100eps()\n\tend\n\n\tfunction nlfun(x)\n\t\tf = zeros(3)  \n\t\tf[1] = exp(x[2]-x[1]) - 2;\n\t\tf[2] = x[1]*x[2] + x[3];\n\t\tf[3] = x[2]*x[3] + x[1]^2 - x[2];\n\t\treturn f\n\tend\n\tfunction nljac(x)\n\t\tJ = zeros(3,3)\n\t\tJ[1,:] = [-exp(x[2]-x[1]),exp(x[2]-x[1]), 0]\n\t\tJ[2,:] = [x[2], x[1], 1]\n\t\tJ[3,:] = [2*x[1], x[3]-1, x[2]]\n\t\treturn J\n\tend\n\n\tx = FNC.newtonsys(nlfun,nljac,[0,0,0]);\n\t@test norm(nlfun(x[end])) < 100eps()\n\tx = FNC.newtonsys(nlfun,nljac,[1,2,3]);\n\t@test norm(nlfun(x[end])) < 100eps()\n\n\tx = FNC.levenberg(nlfun,[10,-4,-3])\n\t@test norm(nlfun(x[end])) < 1e-12\n\nend\n\n@testset \"Chapter 5\" begin\n\tf = t->cos(5t)\n\tQ,t = FNC.intadapt(f,-1,3,1e-8)\n\t@test Q \u2248 (sin(15)+sin(5))/5 rtol = 1e-5\n\tT,_ = FNC.trapezoid(f,-1,3,820)\n\t@test T \u2248 (sin(15)+sin(5))/5 rtol = 1e-4\n\t\n\tt = [-2,-0.5,0,1,1.5,3.5,4]/10\n\tS = FNC.spinterp(t,exp.(t))\n\t@test S(0.33) \u2248 exp(0.33) rtol = 1e-5\n\tw = FNC.fdweights(t.-0.12,2)\n\tf = x->cos(3x)\n\t@test dot(w,f.(t)) \u2248 -9cos(0.36) rtol = 1e-3\n\ty = FNC.hatfun(0.22,t,5)\n\t@test y \u2248 (0.22-t[5])/(t[6]-t[5])\n\t@test FNC.hatfun(0.6,t,5)==0\n\tp = FNC.plinterp(t,f.(t)) \n\t@test p(0.22) \u2248 f(t[5]) + (f(t[6])-f(t[5]))*(0.22-t[5])/(t[6]-t[5])\t\nend\n\n@testset \"Chapter 6\" begin\n\tf = (u,p,t) -> u + p*t^2\n\tu\u0302 = exp(1.5) - 2*(-2 + 2*exp(1.5) - 2*1.5 - 1.5^2)\n\tivp = ODEProblem(f,1,(0,1.5),-2)\n\tt,u = FNC.euler(ivp,4000)\n\t@test u\u0302 \u2248 u[end] rtol = 0.005\n\tt,u = FNC.am2(ivp,4000)\n\t@test u\u0302 \u2248 u[end] rtol = 0.005\n\n\tg = (u,p,t) -> [t+p-sin(u[2]),u[1]]\n\tivp = ODEProblem(g,[-1.,4],(1.,2.),-6)\n\tsol = solve(ivp)\n\tt,u = FNC.euler(ivp,4000)\n\t@test u[end] \u2248 sol.u[end] rtol=0.004\n\tt,u = FNC.ie2(ivp,4000)\n\t@test u[end] \u2248 sol.u[end] rtol=0.0005\n\tt,u = FNC.rk4(ivp,800)\n\t@test u[end] \u2248 sol.u[end] rtol=0.0005\n\tt,u = FNC.ab4(ivp,800)\n\t@test u[end] \u2248 sol.u[end] rtol=0.0005\n\tt,u = FNC.rk23(ivp,1e-4)\n\t@test u[end] \u2248 sol.u[end] rtol=0.0005\n\tt,u = FNC.am2(ivp,2000)\n\t@test u[end] \u2248 sol.u[end] rtol=0.0005\nend", "meta": {"hexsha": "52e813ffc1a14520f058bb173c1d3935a8520bc0", "size": 2895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "tobydriscoll/FundamentalsNumericalComputation.jl", "max_stars_repo_head_hexsha": "7e87402b8f9afdd5546a08d177e4e0e3f31ceb27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-05-29T03:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T19:50:53.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "tobydriscoll/FundamentalsNumericalComputation.jl", "max_issues_repo_head_hexsha": "7e87402b8f9afdd5546a08d177e4e0e3f31ceb27", "max_issues_repo_licenses": ["MIT"], "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": "tobydriscoll/FundamentalsNumericalComputation.jl", "max_forks_repo_head_hexsha": "7e87402b8f9afdd5546a08d177e4e0e3f31ceb27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-07T16:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T16:22:46.000Z", "avg_line_length": 25.1739130435, "max_line_length": 74, "alphanum_fraction": 0.5360967185, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.782512477393649}}
{"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": "@testset \"exponential\" begin\n    rng = MersenneTwister(123456)\n    x = rand(rng) * 2\n    v1 = rand(rng, 3)\n    v2 = rand(rng, 3)\n    @testset \"SqExponentialKernel\" begin\n        k = SqExponentialKernel()\n        @test kappa(k, x) \u2248 exp(-x / 2)\n        @test k(v1, v2) \u2248 exp(-norm(v1 - v2)^2 / 2)\n        @test kappa(SqExponentialKernel(), x) == kappa(k, x)\n        @test metric(SqExponentialKernel()) == SqEuclidean()\n        @test RBFKernel == SqExponentialKernel\n        @test GaussianKernel == SqExponentialKernel\n        @test SEKernel == SqExponentialKernel\n        @test repr(k) == \"Squared Exponential Kernel (metric = Euclidean(0.0))\"\n        @test KernelFunctions.iskroncompatible(k) == true\n\n        k2 = SqExponentialKernel(; metric=WeightedEuclidean(ones(3)))\n        @test metric(k2) isa WeightedEuclidean\n        @test k2(v1, v2) \u2248 k(v1, v2)\n\n        # Standardised tests.\n        TestUtils.test_interface(k)\n        test_ADs(SEKernel)\n    end\n    @testset \"ExponentialKernel\" begin\n        k = ExponentialKernel()\n        @test kappa(k, x) \u2248 exp(-x)\n        @test k(v1, v2) \u2248 exp(-norm(v1 - v2))\n        @test kappa(ExponentialKernel(), x) == kappa(k, x)\n        @test metric(ExponentialKernel()) == Euclidean()\n        @test repr(k) == \"Exponential Kernel (metric = Euclidean(0.0))\"\n        @test LaplacianKernel == ExponentialKernel\n        @test KernelFunctions.iskroncompatible(k) == true\n\n        k2 = ExponentialKernel(; metric=WeightedEuclidean(ones(3)))\n        @test metric(k2) isa WeightedEuclidean\n        @test k2(v1, v2) \u2248 k(v1, v2)\n\n        # Standardised tests.\n        TestUtils.test_interface(k)\n        test_ADs(ExponentialKernel)\n    end\n    @testset \"GammaExponentialKernel\" begin\n        \u03b3 = 1.0\n        k = GammaExponentialKernel(; \u03b3=\u03b3)\n        @test k(v1, v2) \u2248 exp(-norm(v1 - v2)^\u03b3)\n        @test kappa(GammaExponentialKernel(), x) == kappa(k, x)\n        @test GammaExponentialKernel(; gamma=\u03b3).\u03b3 == [\u03b3]\n        @test metric(GammaExponentialKernel()) == Euclidean()\n        @test metric(GammaExponentialKernel(; \u03b3=2.0)) == Euclidean()\n        @test repr(k) == \"Gamma Exponential Kernel (\u03b3 = $(\u03b3), metric = Euclidean(0.0))\"\n        @test KernelFunctions.iskroncompatible(k) == true\n\n        k2 = GammaExponentialKernel(; \u03b3=\u03b3, metric=WeightedEuclidean(ones(3)))\n        @test metric(k2) isa WeightedEuclidean\n        @test k2(v1, v2) \u2248 k(v1, v2)\n\n        test_ADs(\u03b3 -> GammaExponentialKernel(; gamma=only(\u03b3)), [1 + 0.5 * rand()])\n        test_params(k, ([\u03b3],))\n        TestUtils.test_interface(GammaExponentialKernel(; \u03b3=1.36))\n\n        #Coherence :\n        @test isapprox(\n            GammaExponentialKernel(; \u03b3=2.0)(sqrt(0.5) * v1, sqrt(0.5) * v2),\n            SqExponentialKernel()(v1, v2),\n        )\n        @test GammaExponentialKernel()(v1, v2) \u2248 ExponentialKernel()(v1, v2)\n    end\nend\n", "meta": {"hexsha": "21586cadd72e76340a277c72f9ed5259d19af5ed", "size": 2830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/exponential.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": "test/basekernels/exponential.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": "test/basekernels/exponential.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": 39.8591549296, "max_line_length": 87, "alphanum_fraction": 0.6024734982, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7825124729851543}}
{"text": "using Animated_CMA_ES, Plots, Revise\nfunction banana(a,b)\n  x->(a-x[1])^2+b*(x[2]-x[1]^2)^2\nend\nf = banana(1.0,1.0)\n#f(x)=x[1]^2+x[2]^2\n\nres=cma_es_animated(f,[0.0,6.0],xrange=[-2., 3.], yrange=[-3.,8.],tol=1e-3)\ngif(res[3], \"cma_es_banana.gif\", fps=2)\n\n\nres=cma_es_animated(f,[0.0,6.0],xrange=[-2., 3.], yrange=[-3.,8.],tol=1e-3)\n\ng(x)=x[1]^2+x[2]^2\nres=cma_es_animated(g,[-3.0,-3.0],xrange=[-5., 3.], yrange=[-5.,3.],tol=1e-3,maxiter=20)\n\ngif(res[3], \"cma_es_square.gif\", fps=2)\n", "meta": {"hexsha": "aa6e20b74ccbba43321aff1022cd76eb7fadec52", "size": 481, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CMA_ES_examples.jl", "max_stars_repo_name": "deivisangeli/Animated_CMA_ES.jl", "max_stars_repo_head_hexsha": "180c2f5601382a3250b2b11d9362115194601bc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CMA_ES_examples.jl", "max_issues_repo_name": "deivisangeli/Animated_CMA_ES.jl", "max_issues_repo_head_hexsha": "180c2f5601382a3250b2b11d9362115194601bc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CMA_ES_examples.jl", "max_forks_repo_name": "deivisangeli/Animated_CMA_ES.jl", "max_forks_repo_head_hexsha": "180c2f5601382a3250b2b11d9362115194601bc4", "max_forks_repo_licenses": ["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.7222222222, "max_line_length": 88, "alphanum_fraction": 0.5966735967, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7825124711842066}}
{"text": "using Test\nusing NumberTheory\n\n@testset \"Mersenne Numbers\" begin\n    # Tests for the isPowerOfTwoFunction\n    @test isPowerOfTwo(4) == true\n    @test isPowerOfTwo(256) == true\n    @test isPowerOfTwo(1024) == true\n    @test isPowerOfTwo(1073741824) == true\n    @test isPowerOfTwo(1073741825) == false\n    @test isPowerOfTwo(1073741823) == false\n    @test isPowerOfTwo(1) == true\n    @test isPowerOfTwo(0) == false\n    \n    # Tests for the isMersenneNumber\n    @test isMersenneNumber(2) == false\n    @test isMersenneNumber(1073741824) == false\n    @test isMersenneNumber(1073741823) == true\n    @test isMersenneNumber(131071) == true\n    \n    # Tests for the getMersenneNumber\n    @test getMersenneNumber(17) == 131071\t\n    @test getMersenneNumber(1) == 1\t\n    @test getMersenneNumber(5) == 31\t\nend\n", "meta": {"hexsha": "2b1b213a8cf5f3164b7e69864d6aa496b04053c1", "size": 797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mersenne.test.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": "test/mersenne.test.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": "test/mersenne.test.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": 30.6538461538, "max_line_length": 47, "alphanum_fraction": 0.6850690088, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7825124667757118}}
{"text": "\"\"\"\n    NormalInverseChisq(\u03bc, \u03c32, \u03ba, \u03bd)\n\nA Normal-\u03c7^-2 distribution is a conjugate prior for a Normal distribution with\nunknown mean and variance.  It has parameters:\n\n* \u03bc: expected mean\n* \u03c32 > 0: expected variance\n* \u03ba \u2265 0: mean confidence\n* \u03bd \u2265 0: variance confidence\n\nThe parameters have a natural interpretation when used as a prior for a Normal\ndistribution with unknown mean and variance: \u03bc and \u03c32 are the expected mean and\nvariance, while \u03ba and \u03bd 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 = \u03bc\n* v0 = 1/\u03ba\n* shape = \u03bd/2\n* scale = \u03bd\u03c32/2\n\nBased on Murphy \"Conjugate Bayesian analysis of the Gaussian distribution\".\n\"\"\"\nstruct NormalInverseChisq{T<:Real} <: ContinuousUnivariateDistribution\n    \u03bc::T\n    \u03c32::T\n    \u03ba::T\n    \u03bd::T\n\n    function NormalInverseChisq{T}(\u03bc::T, \u03c32::T, \u03ba::T, \u03bd::T) where T<:Real\n        if \u03bd < 0 || \u03ba < 0 || \u03c32 \u2264 0\n            throw(ArgumentError(\"Variance and confidence (\u03ba and \u03bd) must all be positive\"))\n        end\n        new{T}(\u03bc, \u03c32, \u03ba, \u03bd)\n    end\nend\n\nNormalInverseChisq() = NormalInverseChisq{Float64}(0.0, 1.0, 0.0, 0.0)\n\nfunction NormalInverseChisq(\u03bc::Real, \u03c32::Real, \u03ba::Real, \u03bd::Real)\n    T = promote_type(typeof(\u03bc), typeof(\u03c32), typeof(\u03ba), typeof(\u03bd))\n    NormalInverseChisq{T}(T(\u03bc), T(\u03c32), T(\u03ba), T(\u03bd))\nend\n\nBase.convert(::Type{NormalInverseGamma}, d::NormalInverseChisq) =\n    NormalInverseGamma(d.\u03bc, 1/d.\u03ba, d.\u03bd/2, d.\u03bd*d.\u03c32/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}, \u03bc::T, \u03c32::T) where T<:Real =\n    isfinite(\u03bc) && zero(\u03c32) <= \u03c32 < Inf\n\nparams(d::NormalInverseChisq) = d.\u03bc, d.\u03c32, d.\u03ba, d.\u03bd\n\nfunction pdf(d::NormalInverseChisq, \u03bc::T, \u03c32::T) where T<:Real\n    Zinv = sqrt(d.\u03ba / 2pi) / gamma(d.\u03bd*0.5) * (d.\u03bd * d.\u03c32 / 2)^(d.\u03bd*0.5)\n    Zinv * \u03c32^(-(d.\u03bd+3)*0.5) * exp( (d.\u03bd*d.\u03c32 + d.\u03ba*(d.\u03bc - \u03bc)^2) / (-2 * \u03c32))\nend\n\nfunction logpdf(d::NormalInverseChisq, \u03bc::T, \u03c32::T) where T<:Real\n    logZinv = (log(d.\u03ba) - log(2pi))*0.5 - lgamma(d.\u03bd*0.5) + (log(d.\u03bd) + log(d.\u03c32) - log(2)) * (d.\u03bd/2)\n    logZinv + log(\u03c32)*(-(d.\u03bd+3)*0.5) + (d.\u03bd*d.\u03c32 + d.\u03ba*(d.\u03bc - \u03bc)^2) / (-2 * \u03c32)\nend\n\nfunction mean(d::NormalInverseChisq)\n    \u03bc = d.\u03bc\n    \u03c32 = d.\u03bd/(d.\u03bd-2)*d.\u03c32\n    return \u03bc, \u03c32\nend\n\nfunction mode(d::NormalInverseChisq)\n    \u03bc = d.\u03bc\n    \u03c32 = d.\u03bd*d.\u03c32/(d.\u03bd + 3)\n    return \u03bc, \u03c32\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": "function nlp_mi_004_011(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - non-linear objective and linear, quadratic constraints as NL\n\n    model = Model(optimizer)\n\n    @variable(model, -1 <= x <= 1)\n    @variable(model, y)\n    @variable(model, z, Int)\n\n    @NLobjective(model, Min, tan(x) + y + x * z + 0.5 * abs(y))\n    @NLconstraint(model, x^2 + y^2 + z^2 <= 10)\n    @NLconstraint(model, -1.2 * x - y <= z / 1.35)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -4.5768813091909015, tol = objective_tol)\n    return check_solution(\n        [x, y, z],\n        [-0.9969558935432885, -0.07796881265504599, 3],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "7636934677d6d51c157a0454df6f0d80e9506bd0", "size": 860, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-mi/004_011.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-mi/004_011.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-mi/004_011.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 26.875, "max_line_length": 76, "alphanum_fraction": 0.638372093, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768048, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7824210733484189}}
{"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 `\u2264` instead of `<=`\n@variable(model, xmin \u2264 x \u2264 xmax)\n@variable(model, ymin \u2264 y \u2264 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\u0302 = value(x)\ny\u0302 = value(y)\n@assert f\u0302 = objective_value(model) \u2248 f(x\u0302, y\u0302)\n@show x\u0302, y\u0302\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\u0302], [y\u0302])\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] .\u2264 bs)\n# -\n\n# ## Optimize model\n\noptimize!(model)\n\nf\u0302=objective_value(model)\nx\u0302=value(x)\ny\u0302=value(y)\n@show x\u0302, y\u0302\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\u0302], [y\u0302], 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\u2102       = G(0,1)     # Complex numbers.\nDual    = G(0,0,1)   # Dual numbers.\n\u210d       = 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": "# avoid to unzip manually and save the storage\n# refer to https://stackoverflow.com/questions/44876852/julia-extract-zip-files-within-a-zip-file\nusing ZipFile\nusing DelimitedFiles\n\nusing GradientBoost\nusing GradientBoost.Util\nusing GradientBoost.ML\nusing Statistics\n\nr = ZipFile.Reader(\"houses.zip\")\n# the first 27 lines are description\ndata = readdlm(f, skipstart=27)\n# extract the 15-th line manually\nline15 = \"The file cadata.txt contains all the the variables. Specifically, it contains median house value, median income, housing median age, total rooms, total bedrooms, population, households, latitude, and longitude in that order. \"\ncolnames = split(line15, \", \")[2:end]\ncolnames[1] = split(colnames[1], \"contains \")[2]\ncolnames[end] = split(colnames[end])[2]\ncolnames = Array{String, 1}(colnames)\n\n# notice the unit is $100,000\nY = data[:, 1] / 100_000\nX = data[:, 2:end]\n\nfunction Housing_GB(X::Matrix{Float64}, Y::Vector{Float64}; maxdepth = 6, nsubfeatures = 0, sampling_rate = 0.8, \u03bd = 0.1)\n    # divide into training and test set\n    train_ind, test_ind = holdout(size(X, 1), 0.2)\n    train_X = X[train_ind, :]\n    train_Y = Y[train_ind]\n    test_X = X[test_ind, :]\n    test_Y = Y[test_ind]\n\n    err_train = Float64[]\n    err_test = Float64[]\n    # train under number of iterations\n    for niter in 100:100:800\n        println(\"current niter = $niter\")\n        # train\n        gbdt = GBDT(; loss_function=LeastSquares(),\n                      sampling_rate=sampling_rate,\n                      learning_rate=\u03bd,\n                      num_iterations=niter,\n                      tree_options = Dict(\n                        :maxdepth => maxdepth,\n                        :nsubfeatures => nsubfeatures\n                      ))\n        gbl = GBLearner(gbdt, :regression)\n        fit!(gbl, train_X, train_Y)\n\n        train_Y_hat = predict!(gbl, train_X)\n        test_Y_hat = predict!(gbl, test_X)\n        push!(err_train, mean(abs.(train_Y - train_Y_hat)))\n        push!(err_test, mean(abs.(test_Y - test_Y_hat)))\n    end\n    return err_train, err_test\nend\n\nerr_train, err_test = Housing_GB(X, Y)\n\nusing Plots\nniters = 100:100:800\nplot(niters, err_train, label=\"Train Error\", xlab = \"Iterations M\", ylab = \"Absolute Error\", title = \"Training and Test Absolute Error (with square loss)\")\nplot!(niters, err_test, label=\"Test Error\")\nsavefig(\"fig10.13_square_loss.png\")\n", "meta": {"hexsha": "787cf2952e90251cc8a9514fa5661216444666d9", "size": 2375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "data/data/Housing/gradient_boosting.jl", "max_stars_repo_name": "IanFla/Statistical-Learning", "max_stars_repo_head_hexsha": "60a38fbaf557d44bfda4f8b5cdf2d8ac54ec550f", "max_stars_repo_licenses": ["MIT"], "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/data/Housing/gradient_boosting.jl", "max_issues_repo_name": "IanFla/Statistical-Learning", "max_issues_repo_head_hexsha": "60a38fbaf557d44bfda4f8b5cdf2d8ac54ec550f", "max_issues_repo_licenses": ["MIT"], "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/data/Housing/gradient_boosting.jl", "max_forks_repo_name": "IanFla/Statistical-Learning", "max_forks_repo_head_hexsha": "60a38fbaf557d44bfda4f8b5cdf2d8ac54ec550f", "max_forks_repo_licenses": ["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.5384615385, "max_line_length": 236, "alphanum_fraction": 0.6568421053, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8757869900269367, "lm_q1q2_score": 0.7823487633538213}}
{"text": "using MathUtils\nusing Base.Test\n\n# Test log_sum_exp()\noriginal = log(sum(exp([1, 2])))\nours = log_sum_exp([1, 2])\n@test abs(ours - original) <= eps(original)\n\noriginal = log(sum(exp([1, 2, 3, 4, 5, 6])))\nours = log_sum_exp([1, 2, 3, 4, 5, 6])\n@test abs(ours - original) <= eps(original)\n\noriginal = log(sum(exp([1, 1, 1, 1, 1])))\nours = log_sum_exp([1, 1, 1, 1, 1])\n@test abs(ours - original) <= eps(original)\n\n# Test sample_discrete_logspace() by comparing with a simpler sampler\n# (given the same random input they should behave identically)\ndist = [0.1, 0.7, 0.2]\nlog_dist = log(dist)\nnum_test = 1000\nvals1 = zeros(num_test)\n# run sample_discrete_logspace\nsrand(1)\nfor i in 1:num_test\n  vals1[i] = sample_discrete_logspace(log_dist)\nend\n# run sample_discrete\nsrand(1)\nvals2 = zeros(num_test)\nfor i in 1:num_test\n  vals2[i] = sample_discrete(dist)\nend\n@test vals1 == vals2\n", "meta": {"hexsha": "929b2c2f5cc723fa3803c17d869fa71f0294c6d0", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "BelhalK/Julia", "max_stars_repo_head_hexsha": "5c61617115b3203a5ef221ae2cb8e7657e15fd03", "max_stars_repo_licenses": ["MIT"], "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": "BelhalK/Julia", "max_issues_repo_head_hexsha": "5c61617115b3203a5ef221ae2cb8e7657e15fd03", "max_issues_repo_licenses": ["MIT"], "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": "BelhalK/Julia", "max_forks_repo_head_hexsha": "5c61617115b3203a5ef221ae2cb8e7657e15fd03", "max_forks_repo_licenses": ["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.0, "max_line_length": 69, "alphanum_fraction": 0.6914285714, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7823461582334656}}
{"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": "using Test\nusing SumOfSquares\nusing DynamicPolynomials\n\n\"\"\"\n    choi_test(optimizer, config::MOIT.TestConfig)\n\nTest using the example of polynomial matrix that is not a Sum-of-Squares matrix\ngiven in [C15] as the following biquadratic form:\n\nF(x; y) = (x_1^2 + 2 x_3^2) * y_1^2\n        + (x_2^2 + 2 x_1^2) * y_2^2\n        + (x_3^2 + 2 x_2^2) * y_3^2\n        - 2 (x_1x_2 y_1y_2 + x_2x_3 y_2y_3 + x_3x_1 y_3y_1)\n\n[C15] Choi, M. D.\n*Positive semidefinite biquadratic forms*.\nLinear Algebra and its Applications, **1975**, 12(2), 95-100.\n\"\"\"\nfunction choi_test(optimizer, config::MOIT.TestConfig)\n    @polyvar x y z\n\n    model = _model(optimizer)\n    PolyJuMP.setpolymodule!(model, SumOfSquares)\n\n    C = [ x^2 + 2y^2 -x*y        -x*z\n         -x*y         y^2 + 2z^2 -y*z\n         -x*z        -y*z         z^2 + 2x^2]\n\n    @SDconstraint(model, C \u2ab0 0)\n\n    JuMP.optimize!(model)\n    @test JuMP.termination_status(model) == MOI.INFEASIBLE\n    @test JuMP.dual_status(model) == MOI.INFEASIBILITY_CERTIFICATE\nend\nsd_tests[\"choi_term\"] = choi_test\n", "meta": {"hexsha": "6939652e05d5df28e11e47d5124c6317edc13e68", "size": 1039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Tests/choi.jl", "max_stars_repo_name": "ericphanson/SumOfSquares.jl", "max_stars_repo_head_hexsha": "3f524f2f8dcf22a9e1c4e0ea549e7166736faeac", "max_stars_repo_licenses": ["MIT"], "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/choi.jl", "max_issues_repo_name": "ericphanson/SumOfSquares.jl", "max_issues_repo_head_hexsha": "3f524f2f8dcf22a9e1c4e0ea549e7166736faeac", "max_issues_repo_licenses": ["MIT"], "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/Tests/choi.jl", "max_forks_repo_name": "ericphanson/SumOfSquares.jl", "max_forks_repo_head_hexsha": "3f524f2f8dcf22a9e1c4e0ea549e7166736faeac", "max_forks_repo_licenses": ["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.0810810811, "max_line_length": 79, "alphanum_fraction": 0.6361886429, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.782346144948079}}
{"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=\"\u00ff - 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=\"\u00ff - 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": "# Test for GaussRadau()\n\nn = 1 \nx, w = gaussradau(n)\n@test_approx_eq x[1] -1.\n@test_approx_eq w[1] 2.\n\nn = 2 \nx, w = gaussradau(n)\n@test_approx_eq x[1] -1.\n@test_approx_eq x[2] 1./3.\n@test_approx_eq w[1] .5\n@test_approx_eq w[2] 1.5\n\ntol = 1e-14\nn = 42\nntests = 4\nx, w = gaussradau(n)\n@test length(x) == n && length(w) == n\n@test abs(x[37] - 0.908847278001044) < tol\n@test abs(w[37] - 0.031190846817016) < tol\n@test x[1] == -1\n\n@test_approx_eq dot( w,exp(x)) exp(1)-exp(-1)", "meta": {"hexsha": "629c1aac05c59eaf5337259e65bed19c02c61729", "size": 472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gaussradau.jl", "max_stars_repo_name": "JuliaPackageMirrors/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "ada3e7d2c56cebded0a99744f607845974454c74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-06T08:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T08:10:39.000Z", "max_issues_repo_path": "test/test_gaussradau.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": "test/test_gaussradau.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": 19.6666666667, "max_line_length": 45, "alphanum_fraction": 0.6271186441, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.782277673378203}}
{"text": "doc\"\"\"\n    Gumbel(\u03bc, \u03b8)\n\nThe *Gumbel distribution*  with location `\u03bc` and scale `\u03b8` 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    \u03bc::Float64  # location\n    \u03b8::Float64  # scale\n\n    Gumbel(\u03bc::Real, \u03b8::Real) = (@check_args(Gumbel, \u03b8 > zero(\u03b8)); new(\u03bc, \u03b8))\n    Gumbel(\u03bc::Real) = new(\u03bc, 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.\u03bc\nscale(d::Gumbel) = d.\u03b8\nparams(d::Gumbel) = (d.\u03bc, d.\u03b8)\n\n\n#### Statistics\n\nmean(d::Gumbel) = d.\u03bc + d.\u03b8 * 0.57721566490153286\n\nmedian(d::Gumbel) = d.\u03bc + d.\u03b8 * 0.366512920581664327\n\nmode(d::Gumbel) = d.\u03bc\n\nvar(d::Gumbel) = 1.6449340668482264 * d.\u03b8^2\n\nskewness(d::Gumbel) = 1.13954709940464866\n\nkurtosis(d::Gumbel) = 2.4\n\nentropy(d::Gumbel) = 1.57721566490153286 + log(d.\u03b8)\n\n\n#### Evaluation\n\nzval(d::Gumbel, x::Float64) = (x - d.\u03bc) / d.\u03b8\nxval(d::Gumbel, z::Float64) = x * d.\u03b8 + d.\u03bc\n\nfunction pdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    exp(-z - exp(-z)) / d.\u03b8\nend\n\nfunction logpdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    - (z + exp(-z) + log(d.\u03b8))\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.\u03bc - d.\u03b8 * log(-log(p))\n\ngradlogpdf(d::Gumbel, x::Float64) = - (1.0 + exp((d.\u03bc - x) / d.\u03b8)) / d.\u03b8\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] = \u03bb\u00b9V\u00b9 + \u03bb\u00b2V\u00b2 + \u03bb\u00b3V\u00b3\n\n\u03bbs are linear:  \n\u03bb\u00b9 =  -(r+s)/2  \n\u03bb\u00b2 = (r+1)/2\n\u03bb\u00b3 = (s+1)/2\n\nJacobian:  \n[xr xs  \n yr ys]\n\nX\u1d63 = -V\u00b9/2 + V\u00b2/2  \nX\u209b = -V\u00b9/2 + V\u00b3/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 = \u03bb\u00b9V\u00b9 + \u03bb\u00b2V\u00b2 + \u03bb\u00b3V\u00b3 + \u03bb\u2074V\u2074\n\n\u03bbs are bilinear rectangle shape functions:  \n\u03bb\u00b9 = (r-1)(s-1)/4  \n\u03bb\u00b2 = (r+1)(1-s)/4  \n\u03bb\u00b3 = (r+1)(s+1)/4  \n\u03bb\u2074 = (1-r)(s+1)/4\n\nJacobian:  \nX\u1d63 = (s-1)V\u00b9/4 + (1-s)V\u00b2/4 + (s+1)V\u00b3/4 - (s+1)V\u2074/4  \nX\u209b = (r-1)V\u00b9/4 - (r+1)V\u00b2/4 + (r+1)V\u00b3/4 + (1-r)V\u2074/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": "module TestBiCGStabl\n\nusing IterativeSolvers\nusing Test\nusing Random\nusing LinearAlgebra\n\n@testset (\"BiCGStab(l)\") begin\n\nRandom.seed!(1234321)\nn = 20\n\n@testset \"Matrix{$T}\" for T in (Float32, Float64, ComplexF32, ComplexF64)\n    A = rand(T, n, n) + 15I\n    x = ones(T, n)\n    b = A * x\n\n    reltol = \u221aeps(real(T))\n\n    @testset \"BiCGStab($l)\" for l = (2, 4)\n        # Solve without preconditioner\n        x1, his1 = bicgstabl(A, b, l, max_mv_products = 100, log = true, reltol = reltol)\n        @test isa(his1, ConvergenceHistory)\n        @test norm(A * x1 - b) / norm(b) \u2264 reltol\n\n        # With an initial guess\n        x_guess = rand(T, n)\n        x2, his2 = bicgstabl!(x_guess, A, b, l, max_mv_products = 100, log = true, reltol = reltol)\n        @test isa(his2, ConvergenceHistory)\n        @test x2 == x_guess\n        @test norm(A * x2 - b) / norm(b) \u2264 reltol\n\n        # The following tests fails CI on Windows and Ubuntu due to a\n        # `SingularException(4)`\n        if T == Float32 && (Sys.iswindows() || Sys.islinux())\n            continue\n        end\n        # Do an exact LU decomp of a nearby matrix\n        F = lu(A + rand(T, n, n))\n        x3, his3 = bicgstabl(A, b, Pl = F, l, max_mv_products = 100, log = true, reltol = reltol)\n        @test norm(A * x3 - b) / norm(b) \u2264 reltol\n    end\nend\n\n@testset \"Termination criterion\" begin\n    for T in (Float32, Float64, ComplexF32, ComplexF64)\n        A = T[ 2 -1  0\n              -1  2 -1\n               0 -1  2]\n        n = size(A, 2)\n        b = ones(T, n)\n        x0 = A \\ b\n        perturbation = 10 * sqrt(eps(real(T))) * T[(-1)^i for i in 1:n]\n\n        # If the initial residual is small and a small relative tolerance is used,\n        # many iterations are necessary\n        x = x0 + perturbation\n        initial_residual = norm(A * x - b)\n        x, ch = bicgstabl!(x, A, b, log=true)\n        @test 1 \u2264 niters(ch) \u2264 n\u00f72 # BiCGStab(2) makes more than one RHS evaluations per iteration\n\n        # If the initial residual is small and a large absolute tolerance is used,\n        # no iterations are necessary\n        x = x0 + perturbation\n        initial_residual = norm(A * x - b)\n        x, ch = bicgstabl!(x, A, b, abstol=2*initial_residual, reltol=zero(real(T)), log=true)\n        @test niters(ch) == 0\n    end\nend\nend\n\nend # module\n", "meta": {"hexsha": "31ebf09b1f950df516b8e35c90810a16faa32969", "size": 2305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bicgstabl.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": "test/bicgstabl.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": "test/bicgstabl.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": 31.5753424658, "max_line_length": 99, "alphanum_fraction": 0.5731019523, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367526, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7822240231839406}}
{"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 \u00d7 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\u00d77 DataFrame\n Row \u2502 Crt1     Crt2     Crt3     Crt4     Crt5     Crt6     Crt7    \n     \u2502 Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502     4.0      7.0      3.0      2.0      2.0      2.0      2.0\n   2 \u2502     4.0      4.0      6.0      4.0      4.0      3.0      7.0\n   3 \u2502     7.0      6.0      4.0      2.0      5.0      5.0      3.0\n   4 \u2502     3.0      2.0      5.0      3.0      3.0      2.0      5.0\n   5 \u2502     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# \u2554\u2550\u2561 7ccb2b9c-1ecd-11eb-205e-11296dd5bb76\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 855951b0-1ecd-11eb-0108-71f29ba2082f\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing StatsBase, Plots\nend\n\n# \u2554\u2550\u2561 54e90298-1ecd-11eb-01d6-714cdcc0e877\nmd\"## Listing 2.4\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f506085a-1ecd-11eb-1e55-db1a82f7bf85\nmd\"## End of listing 2.4\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u250054e90298-1ecd-11eb-01d6-714cdcc0e877\n# \u2560\u25507ccb2b9c-1ecd-11eb-205e-11296dd5bb76\n# \u2560\u2550855951b0-1ecd-11eb-0108-71f29ba2082f\n# \u2560\u255097360536-1ecd-11eb-36d6-038ba8a75dc5\n# \u2560\u2550f505b35c-1ecd-11eb-1eef-6fe09900d4be\n# \u255f\u2500f506085a-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": "export fact2, member, allequal\n\n\"\"\"\n    fact2(n)\n\nCompute the double factorial of `n`, i.e. the product of the odd (if `n` is odd) or even (if `n` is even) numbers up to `n`.\n\"\"\"\nfunction fact2(n::Int64)\n    if n == 1 || n==0\n        return 1;\n    else\n        if mod(n,2) == 0 # the number is even\n            return prod(2:2:n);\n        else # the number is odd\n            return prod(1:2:n);\n        end\n    end\nend\n\n\"\"\"\n    member(X, idx)\n\nExtract the `idx` ensemble member of the ensemble matrix `X`\n\"\"\"\nmember(X, idx) = X[:,idx]\n\n\"\"\"\n    allequal(x, r)\n\nA function to verify that all the entries of the vector `x` are equal to `r`\n\"\"\"\nallequal(x, r) = all(y->y==r, x)\n", "meta": {"hexsha": "22f33cb6780f722a8c1585d0474f0ff7511746b2", "size": 675, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools/tools.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/tools/tools.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/tools/tools.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": 20.4545454545, "max_line_length": 124, "alphanum_fraction": 0.5644444444, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7822140661544279}}
{"text": "using LinearAlgebra, Random\n\n\"\"\"\n    generate_procrustes_data(m, n, d, \u03c3=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- `\u03c3 :: 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- `\u0100 :: 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    \u03c3 :: Number   = 0.1, \n    T :: DataType = Float64\n    )\n    # true center image\n    \u0100 = 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] = \u0100 * transpose(O) + \u03c3 * 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, \u0100, 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": "######################################\n# Example of kpik function\n# Based on example_kpik.m on V. Simoncini's Website\n######################################\nworkspace()\ninclude(\"../src/LargeMatrixEquations.jl\")\nusing LargeMatrixEquations\n\nnh = 20\nn = nh^2\nT = diagm(ones(nh)*2)-diagm(ones(nh-1),-1)-diagm(ones(nh-1),1)\nI = eye(nh,nh)\nA = sparse(-(kron(T,I)+kron(I,T)))\n\nsrand(1234)\nB = randn(n,2)\nE = eye(n)#sparse(diagm(rand(n),0))\n\nm=100\ntol=1e-9\ntolY=1e-12\nZ,er2=kpik(A,B,tolY=tolY)\n\nprintln(norm(A*Z*Z'*E+E*Z*Z'*A'+B*B'))\n", "meta": {"hexsha": "9fc908cdd749820fbc45d416c8790069ce5e8c1e", "size": 526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_kpik.jl", "max_stars_repo_name": "garrettthomaskth/LargeMatrixEquations", "max_stars_repo_head_hexsha": "f0768f72e68e33bc4539c7c4867dd6c3ae48c8cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-06-17T07:12:47.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-17T07:12:47.000Z", "max_issues_repo_path": "examples/example_kpik.jl", "max_issues_repo_name": "garrettthomaskth/LargeMatrixEquations", "max_issues_repo_head_hexsha": "f0768f72e68e33bc4539c7c4867dd6c3ae48c8cf", "max_issues_repo_licenses": ["MIT"], "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_kpik.jl", "max_forks_repo_name": "garrettthomaskth/LargeMatrixEquations", "max_forks_repo_head_hexsha": "f0768f72e68e33bc4539c7c4867dd6c3ae48c8cf", "max_forks_repo_licenses": ["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.04, "max_line_length": 62, "alphanum_fraction": 0.5646387833, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539661015270469, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7821504430320388}}
{"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": "entropy(C::Array{T, 2} where T<:Real) = 0.5*logdet(2*\u03c0*\u212f*C*C')\n\nentropy(C::AbstractArray{T, 1} where T<:Real) = 0.5*sum(log.(C.^2)) + 0.5*log(2*\u03c0*\u212f) * length(C)\n\nentropy(\u03c3::Real) = 0.5*log(2*\u03c0*\u212f*\u03c3^2)\n", "meta": {"hexsha": "67229d0f4afdf9335746b64d2fbeb08a000834c8", "size": 200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util/entropy.jl", "max_stars_repo_name": "ngiann/ApproximateVI.jl", "max_stars_repo_head_hexsha": "61b08c374eb419aeb65ccb23706ac8352d0b46df", "max_stars_repo_licenses": ["MIT"], "max_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/entropy.jl", "max_issues_repo_name": "ngiann/ApproximateVI.jl", "max_issues_repo_head_hexsha": "61b08c374eb419aeb65ccb23706ac8352d0b46df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-26T23:23:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T08:10:48.000Z", "max_forks_repo_path": "src/util/entropy.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": 33.3333333333, "max_line_length": 96, "alphanum_fraction": 0.59, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566342061815148, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7821197121538509}}
{"text": "#= Sigmoid.jl\n\na quick script to perform a sigmoid transformation using the equation: \n\n\u03c3(X) = 1 /(1 + \u212f ^ 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\u00e7a 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 \u0394\u03b1 \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 .+ \u212f .^(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 \u221a((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+\u221a(B^2-4*A*C))/(2*A)\n    x2=(-B-\u221a(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 (\u03b1,k\u03b1+b),bottom_right is (\u03b4,k\u03b4+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-\u03b1)**2+(kx+b-k\u03b1-b)**2=((\u03b1-\u03b4)**2+(k\u03b1+b-k\u03b4-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/(\u221a(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/(\u221a(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/(\u221a(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/(\u221a(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 \u00f7 2 + 1):end-1]\n\nvar_freq = fft(var)\nvar_power = abs.(fftshift(var_freq))[(nPoints \u00f7 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)\u3000where {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 \u03bcm\n# Variance = 0.457766837 \u03bcm\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": "#!/usr/bin/julia\n\n# Trizen\n# 27 April 2017\n# https://github.com/trizen\n\n# Complex transform of an image, by mapping each pixel position to a complex function.\n\n# usage:\n#   julia complex_transform.jl [image]\n\nusing Images\n#using SpecialFunctions\n\nfunction map_val(value, in_min, in_max, out_min, out_max)\n    (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\nend\n\nfunction complex_transform(file)\n\n    img = load(file)\n    height, width = size(img)\n\n    function transform(x, y)\n\n        z = complex(\n            (2 * x - width ) / width,\n            (2 * y - height) / height\n        )\n\n        # Complex function\n        z = (cos(z) + sin(z)*im) / im\n\n        (real(z), imag(z))\n    end\n\n    matrix = zeros(height, width, 2)\n\n    min_x, min_y = (Inf, Inf)\n    max_x, max_y = (-Inf, -Inf)\n\n    for y in 1:height, x in 1:width\n        new_x, new_y = transform(x, y)\n\n        matrix[y,x,1] = new_x\n        matrix[y,x,2] = new_y\n\n        if (new_x < min_x)\n            min_x = new_x\n        end\n        if (new_y < min_y)\n            min_y = new_y\n        end\n        if (new_x > max_x)\n            max_x = new_x\n        end\n        if (new_y > max_y)\n            max_y = new_y\n        end\n    end\n\n    println(\"X: [$min_x, $max_x]\")\n    println(\"Y: [$min_y, $max_y]\")\n\n    out_img = zeros(RGB{N0f8}, height, width)\n\n    for y in 1:height, x in 1:width\n        out_img[y,x] = RGB{N0f8}(0,0,0)\n    end\n\n    for y in 1:height, x in 1:width\n\n        new_x = map_val(matrix[y,x,1], min_x, max_x, 1, width)\n        new_y = map_val(matrix[y,x,2], min_y, max_y, 1, height)\n\n        if (abs(new_x) == Inf || isnan(new_x) || abs(new_y) == Inf || isnan(new_y))\n            println(\"Skipping one pixel...\")\n            continue\n        end\n\n        new_x = round(Int64, new_x)\n        new_y = round(Int64, new_y)\n\n        out_img[new_y,new_x] = img[y,x]\n    end\n\n    return out_img\nend\n\ninputfile = length(ARGS) > 0 ? ARGS[1] : \"input.png\"\nsave(\"complex_transform.png\", complex_transform(inputfile))\n", "meta": {"hexsha": "b33c7f20b8fd92bd67743917172c4a2b7d081e99", "size": 2006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Image/complex_transform.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/complex_transform.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/complex_transform.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.8043478261, "max_line_length": 86, "alphanum_fraction": 0.5513459621, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7819774170386461}}
{"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\u0302)\n\nreturn the Absolute error of x and x\u0302\n\"\"\"\nabsolute_error(x, x\u0302) = abs(x .- x\u0302)\n\n\n\n\n\"\"\"\n    relative_error(x, x\u0302)\n\nThe relative error between X1 and X2\n\"\"\"\nrelative_error(x, x\u0302) = abs((x .- x\u0302) ./ x)\n\n\n\"\"\"\n    \u03be(x\u2080, x)\n\nreturn the number \u03be(x) bwteen x\u2080 and x.\n\"\"\"\n@inline \u03be(x\u2080, x) = rand(1)[1] * (x - x\u2080)/x + x\u2080\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\u2080::Real, n::Int)\n\nreturn the value of nth Taylor Ploynomial at x.\n\"\"\"\n@inline function TaylorPolynomials(f::Function, x::Real, x\u2080::Real, n::Int)\n    result = []\n    for i in 0:n\n        push!(result, NthDerivative(f, x\u2080, i)*(x - x\u2080)^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 \u2260 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 \u2260 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 \u2260 j\n            z = 1 / b.diffs[j,l]\n            for i in 1:nnodes(b)\n                i \u2260 j && i \u2260 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\u03c30 = 0.1\n\nFilterBank1, FilterBank2 = get_FilterBanks(N, Q, J, \u03c30)\n\n\u03c9 = FFTW.fftshift(FilterBank1.\u03c9)\nplot(\u03c9, FFTW.fftshift(FilterBank1.\u039b[1].\u03c8), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nfor \u03c8 in FilterBank1.\u039b[2:end]\n    plot!(\u03c9, FFTW.fftshift(\u03c8.\u03c8), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nend\nplot!(\u03c9, FFTW.fftshift(FilterBank1.\u03d5.\u03d5), 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\u03c9 = FFTW.fftshift(FilterBank2.\u03c9)\nplot(\u03c9, FFTW.fftshift(FilterBank2.\u039b[1].\u03c8), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nfor \u03c8 in FilterBank2.\u039b[2:end]\n    plot!(\u03c9, FFTW.fftshift(\u03c8.\u03c8), xlims=(0.0, 0.5), color=:steelblue, linewidth=2, legend=false)\nend\nplot!(\u03c9, FFTW.fftshift(FilterBank2.\u03d5.\u03d5), 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.\u039b[74].\u03c8))), linewidth=2, color=:steelblue, label=\"Real\", axis=nothing)\nplot!(imag.(FFTW.fftshift(FFTW.ifft(FilterBank1.\u039b[74].\u03c8))), 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": "@testset \"Multi-objective EA\" begin\n\n    rng = StableRNG(42)\n    opts = Evolutionary.Options(rng=rng, iterations=500)\n\n    # domination\n    P =[ [0,0,0], [0,1,0], [-1,0,0], [0,-1,0] ]\n    @test Evolutionary.dominate(P[1], P[2]) == 1\n    @test Evolutionary.dominate(P[1], P[1]) == 0\n    @test Evolutionary.dominate(P[1], P[3]) == -1\n    @test Evolutionary.dominate(P[3], P[4]) == 0\n    @test Evolutionary.dominations(P)[:, 1] == [0, -1, 1, 1]\n\n    # convergence\n    R = reshape([10,0,6,1,2,2,1,6,0,10],2,5)\n    A = reshape([4,2,3,3,2,4], 2, 3)\n    B = reshape([8,2,4,4,2,8], 2, 3)\n    @test Evolutionary.igd(A,R) \u2248 3.707092031609239\n    @test Evolutionary.igd(B,R) \u2248 2.59148346584763\n    @test Evolutionary.spread(R) \u2248 0.0\n    @test Evolutionary.spread(R[1:1,1:4]) \u2248 3.75\n\n    # Schaffer F2\n\n    schafferf2(x::AbstractVector) = [ x[1]^2,  (x[1]-2)^2 ]\n    Random.seed!(rng, 1)\n    result = Evolutionary.optimize(schafferf2, ()->100randn(rng,1), NSGA2(), opts)\n    println(\"NSGA2:2RLT:SBX:PLM => F: $(minimum(result)), C: $(Evolutionary.iterations(result))\")\n    @test isnan(Evolutionary.minimum(result))\n    mvs = vcat(Evolutionary.minimizer(result)...)\n    @test sum(0 .<= mvs .<= 2)/length(mvs) >= 0.8 # 80% in PO \u2208 [0,2]\n    #println(result)\n    #println(extrema(mvs))\n\n    function schafferf2!(F, x::AbstractVector) # in-place update\n        F[1] = x[1]^2\n        F[2] = (x[1]-2)^2\n        F\n    end\n    Random.seed!(rng, 42)\n    result = Evolutionary.optimize(schafferf2!, zeros(2), ()->10randn(rng,1), NSGA2(), opts)\n    println(\"NSGA2:2RLT:SBX:PLM => F: $(minimum(result)), C: $(Evolutionary.iterations(result))\")\n    @test isnan(Evolutionary.minimum(result))\n    mvs = vcat(Evolutionary.minimizer(result)...)\n    @test sum(0 .<= mvs .<= 2)/length(mvs) >= 0.8 # 80% in PO \u2208 [0,2]\n\nend\n", "meta": {"hexsha": "5c1d730c57e67399041233ba61c0a5d0d9514aaf", "size": 1791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 37.3125, "max_line_length": 97, "alphanum_fraction": 0.5929648241, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.781930861560216}}
{"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 \u2295 y := log( exp(x) + exp(y))\n    x \u2297 y := x + y\n    x \u2298 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 \u2295 y := max(x, y)\n    x \u2297 y := x + y\n    x \u2298 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": "using MyExample\nusing Test\n\n@testset \"MyExample.jl\" begin\n\n    # 2x + 3y\n  @test my_f(2,1) == 7\n  @test my_f(2,3) == 13\n  @test my_f(1,3) == 11\n \nend\n  \n@testset \"Derivative Tests\" begin\n  \n  # dx(2x +3y) = 2\n  @test derivative_of_my_f(2,1) == 2\n  @test derivative_of_my_f(20,1) == 2\n  @test derivative_of_my_f(20,10) == 2\n  \nend\n  ", "meta": {"hexsha": "b5d5bb5d322e0a51249aeff829398916f6ca0f3b", "size": 332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/my_f_tests.jl", "max_stars_repo_name": "vhorta73/MyExample.jl", "max_stars_repo_head_hexsha": "6cca6647a3fbb5a8bf0810c10a554ce939b0f276", "max_stars_repo_licenses": ["MIT"], "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/my_f_tests.jl", "max_issues_repo_name": "vhorta73/MyExample.jl", "max_issues_repo_head_hexsha": "6cca6647a3fbb5a8bf0810c10a554ce939b0f276", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-01T11:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-01T11:29:55.000Z", "max_forks_repo_path": "test/my_f_tests.jl", "max_forks_repo_name": "vhorta73/MyExample.jl", "max_forks_repo_head_hexsha": "6cca6647a3fbb5a8bf0810c10a554ce939b0f276", "max_forks_repo_licenses": ["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.8095238095, "max_line_length": 38, "alphanum_fraction": 0.6114457831, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7819308599759591}}
{"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=\u00acx::Bool`\n\n`Real`:  `z=\u00ac(x::\u211d \u2260 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=\u00acx`\n\"\"\"\nUnaryOps.BNOT\njuliaop(::typeof(UnaryOps.BNOT)) = ~\nUnaryOps.UnaryOp(::typeof(~)) = UnaryOps.BNOT\n\"\"\"\nSquare Root: `z=\u221a(x)`\n\"\"\"\nUnaryOps.SQRT\njuliaop(::typeof(UnaryOps.SQRT)) = sqrt\nUnaryOps.UnaryOp(::typeof(sqrt)) = UnaryOps.SQRT\n\"\"\"\nNatural Logarithm: `z=log\u2091(x)`\n\"\"\"\nUnaryOps.LOG\njuliaop(::typeof(UnaryOps.LOG)) = log\nUnaryOps.UnaryOp(::typeof(log)) = UnaryOps.LOG\n\"\"\"\nNatural Base Exponential: `z=e\u02e3`\n\"\"\"\nUnaryOps.EXP\njuliaop(::typeof(UnaryOps.EXP)) = exp\nUnaryOps.UnaryOp(::typeof(exp)) = UnaryOps.EXP\n\"\"\"\nLog Base 2: `z=log\u2082(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\u207b\u00b9(x)`\n\"\"\"\nUnaryOps.ACOS\njuliaop(::typeof(UnaryOps.ACOS)) = acos\nUnaryOps.UnaryOp(::typeof(acos)) = UnaryOps.ACOS\n\"\"\"\nInverse Sine: `z=sin\u207b\u00b9(x)`\n\"\"\"\nUnaryOps.ASIN\njuliaop(::typeof(UnaryOps.ASIN)) = asin\nUnaryOps.UnaryOp(::typeof(asin)) = UnaryOps.ASIN\n\"\"\"\nInverse Tangent: `z=tan\u207b\u00b9(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\u207b\u00b9(x)`\n\"\"\"\nUnaryOps.ASINH\njuliaop(::typeof(UnaryOps.ASINH)) = asinh\nUnaryOps.UnaryOp(::typeof(asinh)) = UnaryOps.ASINH\n\"\"\"\nInverse Hyperbolic Cosine: `z=cosh\u207b\u00b9(x)`\n\"\"\"\nUnaryOps.ACOSH\njuliaop(::typeof(UnaryOps.ACOSH)) = acosh\nUnaryOps.UnaryOp(::typeof(acosh)) = UnaryOps.ACOSH\n\"\"\"\nInverse Hyperbolic Tangent: `z=tanh\u207b\u00b9(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=\u2308x\u2309`\n\"\"\"\nUnaryOps.CEIL\njuliaop(::typeof(UnaryOps.CEIL)) = ceil\nUnaryOps.UnaryOp(::typeof(ceil)) = UnaryOps.CEIL\n\"\"\"\nFloor Function: `z=\u230ax\u230b`\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\u02e3`\n\"\"\"\nUnaryOps.EXP2\njuliaop(::typeof(UnaryOps.EXP2)) = exp2\nUnaryOps.UnaryOp(::typeof(exp2)) = UnaryOps.EXP2\n\"\"\"\nNatural Exponential - 1: `z=e\u02e3 - 1`\n\"\"\"\nUnaryOps.EXPM1\njuliaop(::typeof(UnaryOps.EXPM1)) = expm1\nUnaryOps.UnaryOp(::typeof(expm1)) = UnaryOps.EXPM1\n\"\"\"\nLog Base 10: `z=log\u2081\u2080(x)`\n\"\"\"\nUnaryOps.LOG10\njuliaop(::typeof(UnaryOps.LOG10)) = log10\nUnaryOps.UnaryOp(::typeof(log10)) = UnaryOps.LOG10\n\"\"\"\nNatural Log of x + 1: `z=log\u2091(x + 1)`\n\"\"\"\nUnaryOps.LOG1P\njuliaop(::typeof(UnaryOps.LOG1P)) = log1p\nUnaryOps.UnaryOp(::typeof(log1p)) = UnaryOps.LOG1P\n\"\"\"\nLog of Gamma Function: `z=log(|\u0393(x)|)`\n\"\"\"\nUnaryOps.LGAMMA\njuliaop(::typeof(UnaryOps.LGAMMA)) = lgamma\nUnaryOps.UnaryOp(::typeof(lgamma)) = UnaryOps.LGAMMA\n\"\"\"\nGamma Function: `z=\u0393(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\u0304`\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 == \u00b1\u221e)`\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\u02b8`\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 \u2260 y`\n\"\"\"\nBinaryOps.ISNE\nfunction isne end\njuliaop(::typeof(BinaryOps.ISNE)) = isne\nBinaryOps.BinaryOp(::typeof(isne)) = BinaryOps.ISNE\n\"\"\"\nGreater Than: `f(x::\u211d,y::\u211d)::\u211d = x > y`\n\"\"\"\nBinaryOps.ISGT\nfunction isgt end\njuliaop(::typeof(BinaryOps.ISGT)) = isgt\nBinaryOps.BinaryOp(::typeof(isgt)) = BinaryOps.ISGT\n\"\"\"\nLess Than: `f(x::\u211d,y::\u211d)::\u211d = 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::\u211d,y::\u211d)::\u211d = x \u2265 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::\u211d,y::\u211d)::\u211d = x \u2264 y`\n\"\"\"\nBinaryOps.ISLE\nfunction isle end\njuliaop(::typeof(BinaryOps.ISLE)) = isle\nBinaryOps.BinaryOp(::typeof(isle)) = BinaryOps.ISLE\n\"\"\"\nMinimum: `f(x::\u211d,y::\u211d)::\u211d = min(x, y)`\n\"\"\"\nBinaryOps.MIN\njuliaop(::typeof(BinaryOps.MIN)) = min\nBinaryOps.BinaryOp(::typeof(min)) = BinaryOps.MIN\n\"\"\"\nMaximum: `f(x::\u211d,y::\u211d)::\u211d = max(x, y)`\n\"\"\"\nBinaryOps.MAX\njuliaop(::typeof(BinaryOps.MAX)) = max\nBinaryOps.BinaryOp(::typeof(max)) = BinaryOps.MAX\n\"\"\"\nLogical OR: `f(x::\u211d,y::\u211d)::\u211d = (x \u2260 0) \u2228 (y \u2260 0)`\n\"\"\"\nBinaryOps.LOR\nfunction \u2228 end\njuliaop(::typeof(BinaryOps.LOR)) = \u2228\nBinaryOps.BinaryOp(::typeof(\u2228)) = BinaryOps.LOR\n\"\"\"\nLogical AND: `f(x::\u211d,y::\u211d)::\u211d = (x \u2260 0) \u2227 (y \u2260 0)`\n\"\"\"\nBinaryOps.LAND\nfunction \u2227 end\njuliaop(::typeof(BinaryOps.LAND)) = \u2227\nBinaryOps.BinaryOp(::typeof(\u2227)) = BinaryOps.LAND\n\"\"\"\nLogical AND: `f(x::\u211d,y::\u211d)::\u211d = (x \u2260 0) \u22bb (y \u2260 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\u207b\u00b9(y/x)`\n\"\"\"\nBinaryOps.ATAN2\njuliaop(::typeof(BinaryOps.ATAN2)) = atan\nBinaryOps.BinaryOp(::typeof(atan)) = BinaryOps.ATAN2\n\"\"\"\nHypotenuse: `f(x::F, y::F)::F = \u221a(x\u00b2 + y\u00b2)`\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 \u00d7 2\u207f`\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::\u2124, y::\u2124)::\u2124 = x | y`\n\"\"\"\nBinaryOps.BOR\njuliaop(::typeof(BinaryOps.BOR)) = |\nBinaryOps.BinaryOp(::typeof(|)) = BinaryOps.BOR\n\"\"\"\nBitwise AND: `f(x::\u2124, y::\u2124)::\u2124 = x & y`\n\"\"\"\nBinaryOps.BAND\njuliaop(::typeof(BinaryOps.BAND)) = &\nBinaryOps.BinaryOp(::typeof(&)) = BinaryOps.BAND\n\"\"\"\nBitwise XOR: `f(x::\u2124, y::\u2124)::\u2124 = x ^ y`\n\"\"\"\nBinaryOps.BXOR\njuliaop(::typeof(BinaryOps.BXOR)) = \u22bb\nBinaryOps.BinaryOp(::typeof(\u22bb)) = BinaryOps.BXOR\n\"\"\"\nBitwise XNOR: : `f(x::\u2124, y::\u2124)::\u2124 = ~(x ^ y)`\n\"\"\"\nBinaryOps.BXNOR\njuliaop(::typeof(BinaryOps.BXNOR)) = !\u22bb\nBinaryOps.BinaryOp(::typeof(!\u22bb)) = BinaryOps.BXNOR\n\"\"\"\nBGET: `f(x::\u2124, y::\u2124)::\u2124 = get bit y of x.`\n\"\"\"\nBinaryOps.BGET\n\"\"\"\nBSET: `f(x::\u2124, y::\u2124)::\u2124 = set bit y of x.`\n\"\"\"\nBinaryOps.BSET\n\"\"\"\nBCLR: `f(x::\u2124, y::\u2124)::\u2124 = clear bit y of x.`\n\"\"\"\nBinaryOps.BCLR\n\"\"\"\nBSHIFT: `f(x::\u2124, y::Int8)::\u2124 = 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 \u2260 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 \u2265 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 \u2264 y`\n\"\"\"\nBinaryOps.LE\njuliaop(::typeof(BinaryOps.LE)) = <=\nBinaryOps.BinaryOp(::typeof(<=)) = BinaryOps.LE\n\"\"\"\nComplex: `f(x::F, y::F)::Complex = x + y \u00d7 i`\n\"\"\"\nBinaryOps.CMPLX\njuliaop(::typeof(BinaryOps.CMPLX)) = complex\nBinaryOps.BinaryOp(::typeof(complex)) = BinaryOps.CMPLX\n\"\"\"\n0-Based row index of a: `f(a\u1d62\u2c7c::T, b\u2096\u2097::T)::Int64 = i`\n\"\"\"\nBinaryOps.FIRSTI\n\"\"\"\n1-Based row index of a: `f(a\u1d62\u2c7c::T, b\u2096\u2097::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\u1d62\u2c7c::T, b\u2096\u2097::T)::Int64 = j`\n\"\"\"\nBinaryOps.FIRSTJ\n\"\"\"\n1-Based column index of a: `f(a\u1d62\u2c7c::T, b\u2096\u2097::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\u1d62\u2c7c::T, b\u2096\u2097::T)::Int64 = k`\n\"\"\"\nBinaryOps.SECONDI\n\"\"\"\n0-Based row index of b: `f(a\u1d62\u2c7c::T, b\u2096\u2097::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\u1d62\u2c7c::T, b\u2096\u2097::T)::Int64 = l`\n\"\"\"\nBinaryOps.SECONDJ\n\"\"\"\n1-Based column index of b: `f(a\u1d62\u2c7c::T, b\u2096\u2097::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 \u2208 [\n    :+,\n    :\u2228,\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::\u211d, y::\u211d)::\u211d = min(x, y)`\n* Identity: +\u221e\n* Terminal: -\u221e\n\"\"\"\nMonoids.MIN_MONOID\nop(::typeof(Monoids.MIN_MONOID)) = BinaryOps.MIN\nMonoids.Monoid(::typeof(min)) = Monoids.MIN_MONOID\n\"\"\"\nMax monoid: `f(x::\u211d, y::\u211d)::\u211d = max(x, y)`\n* Identity: -\u221e\n* Terminal: +\u221e\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 \u2228 y`\n* Identity: false\n* Terminal: true\n\"\"\"\nMonoids.LOR_MONOID\nop(::typeof(Monoids.LOR_MONOID)) = BinaryOps.LOR\nMonoids.Monoid(::typeof(\u2228)) = Monoids.LOR_MONOID\n\"\"\"\nLogical AND monoid: `f(x::Bool, y::Bool)::Bool = x \u2227 y`\n* Identity: true\n* Terminal: false\n\"\"\"\nMonoids.LAND_MONOID\nop(::typeof(Monoids.LAND_MONOID)) = BinaryOps.LAND\nMonoids.Monoid(::typeof(\u2227)) = Monoids.LAND_MONOID\n\"\"\"\nLogical XOR monoid: `f(x::Bool, y::Bool)::Bool = x \u22bb 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::\u2124, y::\u2124)::\u2124 = 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::\u2124, y::\u2124)::\u2124 = 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::\u2124, y::\u2124)::\u2124 = x^y`\n* Identity: All bits `0`.\n* Terminal: nothing\n\"\"\"\nMonoids.BXOR_MONOID\nop(::typeof(Monoids.BXOR_MONOID)) = BinaryOps.BXOR\nMonoids.Monoid(::typeof(\u22bb)) = Monoids.BXOR_MONOID\n\"\"\"\nBitwise XNOR monoid: `f(x::\u2124, y::\u2124)::\u2124 = ~(x^y)`\n* Identity: All bits `1`.\n* Terminal: nothing\n\"\"\"\nMonoids.BXNOR_MONOID\nop(::typeof(Monoids.BXNOR_MONOID)) = BinaryOps.BXNOR\nMonoids.Monoid(::typeof(!\u22bb)) = 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 \u2208 [(:max, \"MAX\"), (:min, \"MIN\"), (:+, \"PLUS\"), (:*, \"TIMES\"), (:any, \"ANY\")]\n    for otimes \u2208 [\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        (:\u2227, \"LAND\"),\n        (:\u2228, \"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 \u2208 [(:(==), \"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 \u2208 [(:(==), \"EQ\"), (:\u2227, \"LAND\"), (:\u2228, \"LOR\"), (:lxor, \"LXOR\")]\n    for otimes \u2208 [\n        (:(==), \"EQ\"),\n        (:(>=), \"GE\"),\n        (:(>), \"GT\"),\n        (:(<=), \"LE\"),\n        (:(<), \"LT\"),\n        (:(!=), \"NE\"),\n        (:first, \"FIRST\"),\n        (:second, \"SECOND\"),\n        (:\u2227, \"LAND\"),\n        (:\u2228, \"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(\u03c4)\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(\u03c4::Array{<:Number})\n    R = RiemannMatrix(\u03c4, siegel=false, \u03f5=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        \u03c4 = random_siegel(4);\n        s = schottky_genus_4(\u03c4);\n        if abs(s) > t\n            t = abs(s)\n            max_matrix = \u03c4;\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": "using VoronoiCells\nimport VoronoiCells: LEFT, RIGHT, LOWER, UPPER\nusing Base.Test\n\nN = 100\nx = 1.0 + rand(N)\ny = 1.0 + rand(N)\n\nA = VoronoiCells.voronoiarea(x, y, [LEFT; RIGHT; LOWER; UPPER])\n# For most realizations |sum(A) - 1| is approx 10^{-15} and easily\n# passing the test. Occasionally it fails with sum(A) = 0.999x, where x != 9\n@test_approx_eq sum(A) 1.0\n\n\n# ------------------------------------------------------------\n# Compare with Deldir\n\nusing Deldir\nA2 = Deldir.voronoiarea(x, y; rw=[LEFT; RIGHT; LOWER; UPPER])\n@test_approx_eq A A2\n\n", "meta": {"hexsha": "86583897b29b53039e69c1312a38d455c11e151d", "size": 548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Voronoiarea.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": "test/Voronoiarea.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": "test/Voronoiarea.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": 24.9090909091, "max_line_length": 76, "alphanum_fraction": 0.6149635036, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7818602892760069}}
{"text": "# ---\n# title: 1553. Minimum Number of Days to Eat N Oranges\n# id: problem1553\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Dynamic Programming\n# link: <https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/description/>\n# hidden: true\n# ---\n# \n# There are `n` oranges in the kitchen and you decided to eat some of these\n# oranges every day as follows:\n# \n#   * Eat one orange.\n#   * If the number of remaining oranges (`n`) is divisible by 2 then you can eat  n/2 oranges.\n#   * If the number of remaining oranges (`n`) is divisible by 3 then you can eat  2*(n/3) oranges.\n# \n# You can only choose one of the actions per day.\n# \n# Return the minimum number of days to eat `n` oranges.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 10\n#     Output: 4\n#     Explanation: You have 10 oranges.\n#     Day 1: Eat 1 orange,  10 - 1 = 9.  \n#     Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\n#     Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \n#     Day 4: Eat the last orange  1 - 1  = 0.\n#     You need at least 4 days to eat the 10 oranges.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 6\n#     Output: 3\n#     Explanation: You have 6 oranges.\n#     Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\n#     Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\n#     Day 3: Eat the last orange  1 - 1  = 0.\n#     You need at least 3 days to eat the 6 oranges.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: n = 1\n#     Output: 1\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: n = 56\n#     Output: 6\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 2*10^9`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "9acabc87e14a586b4b8a8004a2e6b6fd52343669", "size": 1801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1553.minimum-number-of-days-to-eat-n-oranges.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/1553.minimum-number-of-days-to-eat-n-oranges.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/1553.minimum-number-of-days-to-eat-n-oranges.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": 22.5125, "max_line_length": 99, "alphanum_fraction": 0.5530260966, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.7818425381699085}}
{"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        \u03c9 = 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 = \u03c9 * price_value + (1.0 - \u03c9) * 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        \ud835\udf59 = max_value - min_value\n\n        # compute the levels -\n        for (index, level) in enumerate(fn_array)\n            tmp = max_value - \ud835\udf59 * 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": "@testset \"Gauss\u2013Radau\" begin\n    n = 1\n    x, w = gaussradau(n)\n    @test x[1] \u2248 -1.\n    @test w[1] \u2248 2.\n\n    n = 2\n    x, w = gaussradau(n)\n    @test x[1] \u2248 -1.\n    @test x[2] \u2248 1/3\n    @test w[1] \u2248 .5\n    @test w[2] \u2248 1.5\n\n    tol = 1e-14\n    n = 42\n    ntests = 4\n    x, w = gaussradau(n)\n    @test length(x) == n && length(w) == n\n    @test abs(x[37] - 0.908847278001044) < tol\n    @test abs(w[37] - 0.031190846817016) < tol\n    @test x[1] == -1\n\n    @test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\nend", "meta": {"hexsha": "45d19654b4a8db6ee397e2e0689c7bf5ae1f85fc", "size": 497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 20.7083333333, "max_line_length": 46, "alphanum_fraction": 0.4708249497, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7817707871463321}}
{"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     \u03b21 = (x2[2] - x1[2]) / (x2[1] - x1[1])\n     return x2[2] - \u03b21 * x2[1], \u03b21\nend\n \n# make a line \nmake_line(\u03b20, \u03b21, x) = \u03b20 .+ \u03b21 .* 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) \u2264 sqrt(eps(real(zero(besselj_nuhalf_x))))\n        nu == 0 ? one(besselj_nuhalf_x) : zero(besselj_nuhalf_x)\n    else\n        \u221a((float(T))(\u03c0)/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 = \u221a((float(T))(\u03c0)/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*\u03c0*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, \u03b8::T, \u03c6::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, \u03b8::Complex{T}, \u03c6::Union{T,Complex{T}}) where T <: AbstractFloat\n\n    throw(DomainError(\u03b8, \"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, \u03b8::T, \u03c6::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(\u03b8))[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*\u03c6)) .* 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(\u03b8::Vector) = radial_to_cartesian_coordinates(SVector(\u03b8...))\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    \u03b8 = atan(sqrt(x[1]^2+x[2]^2),x[3])\n    \u03c6 = (!iszero(x[1]) || !iszero(x[2])) ? atan(x[2], x[1]) : zero(CT)\n    return [r,\u03b8,\u03c6]\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    \u03b8 = atan(x[2], x[1])\n    return [r,\u03b8]\nend\n\nfunction radial_to_cartesian_coordinates(r\u03b8\u03c6::SVector{3,CT}) where CT\n    r, \u03b8, \u03c6 = r\u03b8\u03c6\n    x = r * sin(\u03b8) * cos(\u03c6)\n    y = r * sin(\u03b8) * sin(\u03c6)\n    z = r * cos(\u03b8)\n\n    return [x,y,z]\nend\n\nfunction radial_to_cartesian_coordinates(r\u03b8::SVector{2,CT}) where CT\n    r, \u03b8 = r\u03b8\n    x = r * cos(\u03b8)\n    y = r * sin(\u03b8)\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(\u03c3,i,j,Nc)\r\n        \u03bb = zeros(ComplexF64,Nc,Nc)\r\n        \u03bb[i,i] = \u03c3[1,1]\r\n        \u03bb[i,j] = \u03c3[1,2] \r\n        \u03bb[j,i] = \u03c3[2,1]\r\n        \u03bb[j,j] = \u03c3[2,2]  \r\n        return \u03bb\r\n    end\r\n\r\n    function normalization(A)\r\n        Norm = sqrt(real(tr(A*A))/2)\r\n        #print(\"    Normalization = \u221a\",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        \u03b8 = (\u03c0:-\u03c0/(nx-1):-1e-14)\n        xk  .= ((cos.(\u03b8).+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\u0394, 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\u0394 = $dir\u0394\")\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 \u03b1 = 1. This is the \"learning rate\"\n\n    \u03b1 = 1\n    if verbose\n        print(\"Left side: \")\n        println(f(xInit + \u03b1 * dir\u0394))\n        print(\"Right side: \")\n        print(f(xInit))\n        print(\" + \")\n        print(paramA * \u03b1 * dir\u0394'dfdx(xInit))\n        print(\" = \")\n        println(f(xInit) + paramA * \u03b1 * dir\u0394'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 + \u03b1 * dir\u0394) > (f(xInit) + paramA * \u03b1 * (dir\u0394'dfdx(xInit))[1])\n        # If the condition passes, set \u03b1 to b * \u03b1\n        if verbose\n            print(\"Left side: \")\n            println(f(xInit + \u03b1 * dir\u0394))\n            print(\"Right side: \")\n            print(f(xInit))\n            print(\" + \")\n            print(paramA * \u03b1 * dir\u0394'dfdx(xInit))\n            print(\" = \")\n            println(f(xInit) + paramA * \u03b1 * dir\u0394'dfdx(xInit))\n        end\n\n        \u03b1 = paramB * \u03b1\n\n        if verbose\n            println(\u03b1)\n        end\n    end\n\n    # the updated x is xInit - alpha * gradf(xInit)\n    xUpdated = xInit + \u03b1 * dir\u0394\n    # Return updated x\n    return xUpdated, \u03b1\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\u0394x = b2.x - b1.x\n\t\u0394y = b2.y - b1.y\n\n\tazimuth = atan(\u0394y, \u0394x)\n\n\t# altitude is the angle from the x-y plane in the z axis\n\thyp = sqrt(\u0394x^2 + \u0394y^2)\n\t\u0394z = b2.z - b1.z\n\taltitude = atan(\u0394z, 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, \u0394t)\n\nApply forces between all Body objects in `bodies` over time step `\u0394t` seconds.\n\"\"\"\nfunction step!(bodies::Vector{Body}, \u0394t::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 \u27f9  F = m * (v - u)/t\n\t\t# \u27f9  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 * \u0394t) / 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 += \u0394t * b.v[1]\n\t\tb.y += \u0394t * b.v[2]\n\t\tb.z += \u0394t * b.v[3]\n\tend\nend\n\n\"\"\"\n    drawframes(bodies, framecount, \u0394t)\n\nReturn frame data for the list of Body objects `bodies` with time step `\u0394t`.\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, \u0394t::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, \u0394t)\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, \u0394t, 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 `\u0394t` 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, \u0394t::Float64, cube::Bool=false, bounds::Union{Nothing, Vector{Tuple{Float64, Float64}}}=nothing, filename::Union{String, Nothing}=nothing) = drawgif(drawframes(bodies, framecount, \u0394t), 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": "# In this exercise we will try to predict the average housing value in suburbs of Boston given some characteristics of the suburb.\n\n# These are the detailed attributes of the dataset:\n#   1. CRIM      per capita crime rate by town\n#   2. ZN        proportion of residential land zoned for lots over 25,000 sq.ft.\n#   3. INDUS     proportion of non-retail business acres per town\n#   4. CHAS      Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n#   5. NOX       nitric oxides concentration (parts per 10 million)\n#   6. RM        average number of rooms per dwelling\n#   7. AGE       proportion of owner-occupied units built prior to 1940\n#   8. DIS       weighted distances to five Boston employment centres\n#   9. RAD       index of accessibility to radial highways\n#   10. TAX      full-value property-tax rate per $10,000\n#   11. PTRATIO  pupil-teacher ratio by town\n#   12. B        1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\n#   13. LSTAT    % lower status of the population\n#   14. MEDV     Median value of owner-occupied homes in $1000's\n\n# Further information concerning this dataset can be found on [this file](https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.names)\n\n# Our prediction concern the median value (column 14 of the dataset)\n\n# 1) Start by setting the working directory to the directory of this file and activate it. If you have the provided `Manifest.toml` file in the directory, just run `Pkg.instantiate()`, otherwise manually add the packages Pipe, HTTP, CSV, DataFrames, Plots and BetaML.\n# Also, seed the random seed with the integer `123`.\n\n\n# 2) Load the packages/modules Pipe, HTTP, CSV, DataFrames, Plots, BetaML\n\n\n# 3) Load from internet or from local file the input data into a DataFrame or a Matrix.\n# You will need the CSV options `header=false` and `ignorerepeated=true``\ndataURL=\"https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data\"\n\n\n# 4) The 4th column is a dummy related to the information if the suburb bounds a certain Boston river. Use the BetaML function `oneHotEncoder` to encode this dummy into two separate vectors, one for each possible value. Note that you will need to transform the range {0,1} into {1,2} before running the oneHotEncoder function (this can be done by simply uinsg `data[:,4] .+1`)\n\n\n# 5) Now create the X matrix of features concatenating horizzontaly the 1st to 3rd column of `data`, the 5th to 13th columns and the two columns you created with the one hot encoding. Make sure you have a 506\u00d714 matrix.\n\n\n# 6) Similarly define Y to be the 14th column of data\n\n\n# 7) Partition the data in (`xtrain`,`xval`) and (`ytrain`,`yval`) keeping 80% of the data for training and reserving 20% for testing. Keep the default option to shuffle the data, as the input data isn't.\n\n\n# 8) Define a Neural Network model with the following characteristics:\n#   - 3 dense layers with respectively 14, 20 and 1 nodes and activation function `relu`\n#   - cost function `squaredCost` \n\n\n# 9) Train your model using `ytrain` and a scaled version of xtrain (where all columns have zero mean and 1 standard deviaiton) for 400 epochs and use a batch size of 6 records.\n# Save the output of your training function to `trainingLogs`\n\n\n# 10) Predict the training labels y\u0302train and the validation labels y\u0302val. Recall you did the training on the scaled features!\n\n\n# 11) Compute the train and test relative mean error using the function `meanRelError` with the parameter `normRec` set to `false`\n\n\n# 12) Run the following commands to plots the average loss per epoch and the true vs estimation validation values \nplot(trainingLogs.\u03f5_epochs)\nscatter(yval,y\u0302val,xlabel=\"true values\", ylabel=\"estimated values\", legend=nothing)\n\n\n# 13) (Optional) Run the same workflow without scaling the data. How this affect the quality of your predictions ? \n", "meta": {"hexsha": "0fb81768c1efdcfb30303276968f85dd9d9ab651", "size": 3876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessonsMaterial/04_NN/bostonHousing/BostonHousingValue.jl", "max_stars_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_stars_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-26T15:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T13:05:52.000Z", "max_issues_repo_path": "lessonsMaterial/04_NN/bostonHousing/BostonHousingValue.jl", "max_issues_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_issues_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "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": "lessonsMaterial/04_NN/bostonHousing/BostonHousingValue.jl", "max_forks_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_forks_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-26T08:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T08:06:40.000Z", "avg_line_length": 57.0, "max_line_length": 376, "alphanum_fraction": 0.7432920537, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7817599882075628}}
{"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 28042615-8f2b-41fa-9b14-28d69180debb\nusing Pkg; Pkg.develop(path=\"..\"); Pkg.activate(\"..\")\n\n# \u2554\u2550\u2561 3ec6aae0-c233-11eb-355d-3dfe780e33bc\nbegin\n\tusing DataFrames\n\tusing JuMP\n\tusing Ipopt\n\tusing StatsPlots\n\tplotly()\nend\n\n# \u2554\u2550\u2561 a6997248-aee3-4ebb-8a1e-f791ad503aa8\nbegin\n\tn = 100\n\t\u03bc1 = 10\n\t\u03bc2 = 15\n\n\tdf = append!(\n\t\tDataFrame(x1=randn(n).+\u03bc1, x2=randn(n).+\u03bc1, y=ones(n)),\n\t\tDataFrame(x1=randn(n).+\u03bc2, x2=randn(n).+\u03bc2, y=-ones(n))\n\t)\n\n\tp = @df df scatter(:x1, :x2, group=:y, legend=:topleft)\nend\n\n# \u2554\u2550\u2561 bf7d0459-4b47-4839-800d-01bdcd500633\nmd\"\n$arg\\ min_{\ud835\udc30, b}\\ \\frac{1}{2}\ud835\udc30^T\ud835\udc30$\n\n$\\text{subject to }\\forall i, y_i(\ud835\udc30^T\ud835\udc31_i+b) \\geq 1$\n\"\n\n# \u2554\u2550\u2561 27dfce4e-3ccd-4221-8eca-144ae87e2998\nmd\"\nrespect to\n\n$arg\\ min_{\ud835\udc30, b}\\ \\frac{1}{2}\ud835\udc2e^T \ud835\udc10 \ud835\udc2e + \ud835\udc0f^T \ud835\udc2e$\n\n$\\text{subject to }\\forall i, \ud835\udc1a_i^T \ud835\udc2e) \\geq c_i$\n\nTherefore,\n\n$\ud835\udc2e = \\begin{bmatrix}b \\\\ \ud835\udc30\\end{bmatrix}$\n$\ud835\udc10 = \\begin{bmatrix}0 & 0^T_d \\\\ 0^T_d & \ud835\udc08_d\\end{bmatrix}$\n$\ud835\udc0f = 0_{d+1}$\n$\ud835\udc1a^T_i = y_i\\begin{bmatrix}1 & \ud835\udc31^T_i\\end{bmatrix}$\n$c_i = 1$\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e5334dab-56b2-4dd0-a12c-e17f1c8e584b\ny\u0302(x1, x2) = sign([x1, x2]' * w + b)\n\n# \u2554\u2550\u2561 16448a5a-090f-4a6a-a9a0-55192a77dfb3\nheatmap!(p, 5:0.1:20, 5:0.1:20, y\u0302, color=:coolwarm)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u250028042615-8f2b-41fa-9b14-28d69180debb\n# \u2560\u25503ec6aae0-c233-11eb-355d-3dfe780e33bc\n# \u2560\u2550a6997248-aee3-4ebb-8a1e-f791ad503aa8\n# \u255f\u2500bf7d0459-4b47-4839-800d-01bdcd500633\n# \u255f\u250027dfce4e-3ccd-4221-8eca-144ae87e2998\n# \u2560\u25505056cc0a-f832-47b3-a6a5-f7ee2d7bc5ba\n# \u2560\u2550e5334dab-56b2-4dd0-a12c-e17f1c8e584b\n# \u2560\u255016448a5a-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": "using Findpeaks\nusing Test\n\ngaussian(x,\u03bc,\u03c3) = 1/sqrt(2*\u03c0)/\u03c3*exp(-((x-\u03bc)^2)/2/\u03c3^2)\nx = collect(range(1,stop=1000,length=1000))\n\u03bc = rand(x)\ndata = gaussian.(x,\u03bc,rand(x)/3)\n\np = findpeaks(data)\n@test length(p) == 1\n@test p[1] == \u03bc\np = findpeaks(data,x)\n@test length(p) == 1\n@test p[1] == \u03bc\n", "meta": {"hexsha": "ac0b1c22af477dab8d3fbc580ccd95e59c0b147b", "size": 287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "ymtoo/Findpeaks.jl", "max_stars_repo_head_hexsha": "9ae7ed7b06ff897383631c053465787a7984441f", "max_stars_repo_licenses": ["MIT"], "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": "ymtoo/Findpeaks.jl", "max_issues_repo_head_hexsha": "9ae7ed7b06ff897383631c053465787a7984441f", "max_issues_repo_licenses": ["MIT"], "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": "ymtoo/Findpeaks.jl", "max_forks_repo_head_hexsha": "9ae7ed7b06ff897383631c053465787a7984441f", "max_forks_repo_licenses": ["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.1333333333, "max_line_length": 53, "alphanum_fraction": 0.6132404181, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.94815453335022, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7817173192028642}}
{"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 find_energy(img)\n\n    energy_x = imfilter(brightness.(img), Kernel.sobel()[2])\n    energy_y = imfilter(brightness.(img), Kernel.sobel()[1])\n\n    return sqrt.(energy_x.^2 + energy_y.^2)\nend\n\nfunction find_energy_map(energy)\n\n    sz = size(energy)\n    energy_map = zeros(size(sz))\n    energy_map[end,:] = energy[end,:]\n\n    next_elements = zeros(Int, sz)\n    \n    for i in sz[1]-1:-1:1, j in sz[2]\n        left = max(1, j-1)\n        right = min(j+1, sz[2])\n        local_energy, next_element = findmin(@view energy_map[i+1, left:right])\n        \n        # Minimal energy to bottom\n        energy_map[i,j] += local_energy + energy[i,j]\n        \n        # Element that minimizes the energy\n        next_elements[i,j] = next_element - 2\n\n        if left == 1\n            next_elements[i,j] += 1\n        end\n    end\n\n    return energy_map, next_elements\nend\n\n\"\"\"\nJust looks up the minimal path from the `next_elements` array. \n\"\"\"\nfunction find_seam_at(next_elements, element)\n\n    seam = zeros(Int, size(next_elements)[1])\n    seam[1] = element\n    for i = 2:length(seam)\n        seam[i] = seam[i-1] + next_element[i, seam[i-1]]\n    end\n\n    return seam\nend\n\n\nfunction find_seam(energy)\n\n    energy_map, next_elements = find_energy_map(energy)\n\n    _, min_element = findmin(@view energy_map[1,:])\n\n    return find_seam_at(next_elements, min_element)\nend", "meta": {"hexsha": "dc9b98ca0db659fd0206e32522862127abeb39a8", "size": 1357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_notebooks/week2/seam_carving_live.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/week2/seam_carving_live.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/week2/seam_carving_live.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": 23.3965517241, "max_line_length": 79, "alphanum_fraction": 0.6256448047, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7817031903618731}}
{"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": "# TODO: limit types for arguments of f\nstruct Predicate\n  f::Function\nend\n\nstruct Mapping\n  f::Function\nend\n\n(p::Predicate)(x,y) = p.f(x,y)\n(m::Mapping)(x) = m.f(x)\n\n# ====================  Auxiliary functions ====================\n\n\"\"\"\n    check_for_equivalence_relation(f::Predicate, dom)\n\nGiven a Predicate `f` over a domain `dom`, return `true` if `f`\nis a equivalence relation, `false` otherwise.\nOne can create a symmetric equivalency relation with [`make_symmetric(f)`](@ref)\nTODO: check transitivity.\n\n# Examples\n```\njulia> check_for_equivalence_relation(Predicate((x,y) -> x == -y), -5:10)\ntrue\njulia> check_for_equivalence_relation(Predicate((x,y) -> x == y+2), -1:10)\nfalse\n```\n\"\"\"\nfunction check_for_equivalence_relation(f::Predicate, dom)\n  for (i,el1) in enumerate(dom)\n    for el2 in dom\n      !(f(el1,el2) == f(el2,el1)) && return false\n    end\n  end\n  #TODO: check transitivity\n  return true\nend\n", "meta": {"hexsha": "016bc732a80f6ed8385d85cc5589ec71136fba30", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Mappings.jl", "max_stars_repo_name": "gitter-badger/EquivalenceClassesConstructor.jl", "max_stars_repo_head_hexsha": "40fd2809b8b5f44ec169c4235f057f8b2387a891", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Mappings.jl", "max_issues_repo_name": "gitter-badger/EquivalenceClassesConstructor.jl", "max_issues_repo_head_hexsha": "40fd2809b8b5f44ec169c4235f057f8b2387a891", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mappings.jl", "max_forks_repo_name": "gitter-badger/EquivalenceClassesConstructor.jl", "max_forks_repo_head_hexsha": "40fd2809b8b5f44ec169c4235f057f8b2387a891", "max_forks_repo_licenses": ["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": 80, "alphanum_fraction": 0.6589912281, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7816841595149039}}
{"text": "#\n#\n#\n\nfunction run_dsatur_heuristc(infile_name::ASCIIString)\n\t# Read the graph from the disk (as adjacency list)\n\tG = simpleGraph(infile_name)\n\n\t# Apply the dsatur method\n\tnumber_color, vertex_color = dsatur(G.Graph)\n\n\t# Improve the coloring using Iterated Greedy techniques\n\n\t# Improve the coloring using min-conflicts local search\n\n\t# Return the coloring\n\nend\n\nfunction run_optdsatur_heuristc()\nend\n\n\n\nfunction dsatur(G::Array{Array{Int64},1})\n\tl = length(G)\n\tvertex_color = zeros(Int,l)\n\tdegrees = Array{Tuple{Int,Int}}(l)\n\tsatur = zeros(Int,l)\n\tuncolored = Set(collect(1:l))\n\tcolor_counter = 1\n\n\tfor i in 1:l\n\t\tdegrees[i] = (length(G[i]), i)\n\tend\n\n\t#coloring max degree vertex\n\n\tmax_deg_vertex = maximum(degrees)[2] \n\tvertex_color[max_deg_vertex] = color_counter\n\n\tdelete!(uncolored, max_deg_vertex)\n\n\t#Increase saturation of max_degree_vertex neighbours\n\tfor j in G[max_deg_vertex]\n\t\tsatur[j]+=1\n\tend\n\n\tcoloring = 0\n\twhile !isempty(uncolored)\n\t\t\n\t\tmax_satur_degree_vertices = []\n\t\taux = []\n\t\tfor i in uncolored\t\n\t\t\tpush!(aux, (satur[i], i))\n\t\tend\n\n\t\tmax_sat = findmax(aux)[1][1]\n\t\tfor i in aux\n\t\t\tif i[1] == max_sat\n\t\t\t\tpush!(max_satur_degree_vertices, i[2])\n\t\t\tend\n\t\tend\n\n\t\tcoloring = max_satur_degree_vertices[1]\n\n\t\t# If there are more than 1 vertex with max_satur, untie by max_degree\n\t\tif length(max_satur_degree_vertices) > 1\n\t\t\tmax_degree = -1\n\t\t\tnode_index = -1\n\t\t\tfor i in max_satur_degree_vertices\n\t\t\t\tdegree, node_index = degrees[i]\n\t\t\t\tif degree > max_degree\n\t\t\t\t\tcoloring = node_index\n\t\t\t\t\tmax_degree = degree\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\t# Closure to return how many vertex have some color.\n\t\tfunction amount_color(node_indexes, color_number, vertex_color)\n\t\t\tcolor_counter = 0\n\t\t\tfor i in node_indexes\n\t\t\t\tif vertex_color[i] == color_number\n\t\t\t\t\tcolor_counter +=1\n\t\t\t\tend\n\t\t\tend\n\t\t\treturn color_counter\n\t\tend\n\n\t\t# Coloring\n\t\tfor number_color in 1:color_counter\n\t\t\tif amount_color(G[coloring], number_color, vertex_color) == 0\n\t\t\t\tvertex_color[coloring] = number_color\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\t#In case it wasnt colored\n\t\tif vertex_color[coloring] == 0\n\t\t\tcolor_counter+=1\n\t\t\tvertex_color[coloring] = color_counter\n\t\tend\n\n\t\tdelete!(uncolored, coloring)\n\t\t\n\t\tfor j in G[coloring]\n\t\t\tif amount_color(G[j], vertex_color[coloring], vertex_color) == 1\n\t\t\t\tsatur[j] +=1\n\t\t\tend\n\t\tend\n\tend\n\treturn number_color, vertex_color\nend\n\nfunction optdsatur()\nend\n\nfunction iteratedGreedy()\n\t\nend\n\nfunction localSearch()\n\nend\n\ntype colorGraph\nend", "meta": {"hexsha": "bb1e3e1555ed216b32e0908b00b50d29b5fbe1a6", "size": 2444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dsatur.jl", "max_stars_repo_name": "Hguimaraes/graphtheoryufrj.jl", "max_stars_repo_head_hexsha": "cc5840f06c8b6965ae81958faf4bcfa6afe3d689", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-01T19:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-01T19:14:12.000Z", "max_issues_repo_path": "src/dsatur.jl", "max_issues_repo_name": "Hguimaraes/graphtheoryufrj.jl", "max_issues_repo_head_hexsha": "cc5840f06c8b6965ae81958faf4bcfa6afe3d689", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dsatur.jl", "max_forks_repo_name": "Hguimaraes/graphtheoryufrj.jl", "max_forks_repo_head_hexsha": "cc5840f06c8b6965ae81958faf4bcfa6afe3d689", "max_forks_repo_licenses": ["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.09375, "max_line_length": 71, "alphanum_fraction": 0.7115384615, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7816841481987306}}
{"text": "\"\"\"\n    \ud835\udc5b(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 = \ud835\udc5b(h)\n\n3-element Array{Float64,1}:\n 2.0\n 2.0\n 1.0\n```\n\n\n\"\"\"\nfunction \ud835\udc5b(v::AbstractArray)\n    if v[end] != 0 && v[end] != 1\n        v .= v ./ v[end]\n    else\n        v\n    end\nend\n\nfunction \ud835\udc5b(v::SVector)\n    if v[end] != 0 && v[end] != 1\n        v / v[end]\n    else\n        v\n    end\nend\n\nfunction hom\u207b\u00b9(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 \u2202hom\u207b\u00b9(\ud835\udc27::SVector)\n    k = length(\ud835\udc27)\n    \ud835\udc1e\u2096 = push(zeros(SVector{k-1}),1.0)\n    \ud835\udc08 = SMatrix{3,3}(1.0I)\n    1/\ud835\udc27[k]*\ud835\udc08 - 1/\ud835\udc27[k]^2 * \ud835\udc27 * \ud835\udc1e\u2096'\nend\n\nfunction \u2202\ud835\udc5b(\ud835\udc27::AbstractArray)\n    k = length(\ud835\udc27)\n    \ud835\udc1e\u2096 = fill(0.0,(k,1))\n    \ud835\udc1e\u2096[k] = 1\n    1/\ud835\udc27[k]*Matrix{Float64}(I, k, k) - 1/\ud835\udc27[k]^2 * \ud835\udc27 * \ud835\udc1e\u2096'\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    \ud835\udc12  = @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\u00d75 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(\u03bc::AbstractMatrix) -> Vector\n\nCalculates autocorrelation function using [Wiener-Khinchin Theorem](http://mathworld.wolfram.com/Wiener-KhinchinTheorem.html).\n\"\"\"\nfunction autocorrelation(\u03bc::AbstractMatrix)\n    tmp = [ fft(abs2.(ifft(r))) for r in eachrow(\u03bc)]\n    return real.(reduce(+,tmp))\nend\n\n\n\"\"\"\nspectrum(\u03bc::AbstractMatrix; tstep=0.5, maxfreq=4000) -> Dict\n\nCalculates spectrum from dipolemoment trajectory. Calculates autocorrelation function and\nits Fourier transform.\n\n# Arguments\n- `\u03bc::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(\u03bc::AbstractMatrix; tstep=0.5, maxfreq=4000)\n    l = size(\u03bc)[2]\n    lh = Int(floor(l/2))\n    acor = autocorrelation(\u03bc)\n    s = abs.(fft(acor))[1:lh]\n    # freq = n/N\u0394 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    \u03bc = read_cp2k_dipoles(fname)\n    return spectrum(\u03bc; 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": "function InverseLU(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    In=zeros(m,m)\r\n    B=Matrix{Float64}(I,m,m)\r\n    D=zeros(m)\r\n\r\n    L,U,P, p=DolittleLU(A)\r\n\r\n\r\n\r\n    for j=1:m\r\n\r\n        #Fordward Substitution\r\n        D=zeros(m)\r\n        D[1]=B[1,j]\r\n        for i=2:m\r\n           D[i]=(B[i,j] - (L[i,1:i-1]'*D[1:i-1]))\r\n        end\r\n\r\n        #Back substitution\r\n\r\n          In[m,j]=D[end]/U[end,end]\r\n\r\n    for i=m-1:-1:1\r\n       In[i,j]=(D[i] - (U[i,i+1:m]'*In[i+1:m,j]))/U[i,i]\r\n    end\r\n\r\n    end\r\n    return In, P\r\nend\r\n    \r\n", "meta": {"hexsha": "214051427a87f80fe22eca61dd007058efa5a7be", "size": 648, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InverseLU.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/InverseLU.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/InverseLU.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.2, "max_line_length": 57, "alphanum_fraction": 0.4398148148, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7815859515152275}}
{"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,\u03bd=beam.material.E,beam.material.\u03bd\n    A,I\u2082,I\u2083,J,l=beam.section.A,beam.section.I\u2082,beam.section.I\u2083,beam.section.J,beam.l\n    As\u2082,As\u2083=beam.section.As\u2082,beam.section.As\u2083\n    G=E/2/(1+\u03bd)\n    \u03d5\u2082,\u03d5\u2083=12E*I\u2083/(G*As\u2082*l^2),12E*I\u2082/(G*As\u2083*l^2)\n    K=zeros(12,12)\n    K[1,1]=E*A/l\n    K[2,2]=12E*I\u2083/l^3/(1+\u03d5\u2082)\n    K[3,3]=12E*I\u2082/l^3/(1+\u03d5\u2083)\n    K[4,4]=G*J/l\n    K[5,5]=(4+\u03d5\u2083)*E*I\u2082/l/(1+\u03d5\u2083)\n    K[6,6]=(4+\u03d5\u2082)*E*I\u2083/l/(1+\u03d5\u2082)\n    K[7,7]=E*A/l\n    K[8,8]=12E*I\u2083/l^3/(1+\u03d5\u2082)\n    K[9,9]=12E*I\u2082/l^3/(1+\u03d5\u2083)\n    K[10,10]=G*J/l\n    K[11,11]=(4+\u03d5\u2083)*E*I\u2082/l/(1+\u03d5\u2083)\n    K[12,12]=(4+\u03d5\u2082)*E*I\u2083/l/(1+\u03d5\u2082)\n\n    K[3,5]=K[5,3]=-6E*I\u2082/l^2/(1+\u03d5\u2083)\n    K[6,8]=K[8,6]=-6E*I\u2083/l^2/(1+\u03d5\u2082)\n    K[9,11]=K[11,9]=6E*I\u2082/l^2/(1+\u03d5\u2083)\n\n    K[2,6]=K[6,2]=6E*I\u2083/l^2/(1+\u03d5\u2082)\n    K[5,9]=K[9,5]=6E*I\u2082/l^2/(1+\u03d5\u2083)\n    K[8,12]=K[12,8]=-6E*I\u2083/l^2/(1+\u03d5\u2082)\n\n    K[7,1]=K[1,7]=-E*A/l\n    K[8,2]=K[2,8]=-12E*I\u2083/l^3/(1+\u03d5\u2082)\n    K[9,3]=K[3,9]=-12E*I\u2082/l^3/(1+\u03d5\u2083)\n    K[10,4]=K[4,10]=-G*J/l\n    K[11,5]=K[5,11]=(2-\u03d5\u2083)*E*I\u2082/l/(1+\u03d5\u2083)\n    K[12,6]=K[6,12]=(2-\u03d5\u2082)*E*I\u2083/l/(1+\u03d5\u2082)\n\n    K[3,11]=K[11,3]=-6E*I\u2082/l^2/(1+\u03d5\u2083)\n\n    K[2,12]=K[12,2]=6E*I\u2083/l^2/(1+\u03d5\u2082)\n\n    return K\nend\n\nfunction K2_eular_shear(beam::Beam)::Matrix{Float64}\n    E,\u03bd=beam.material.E,beam.material.\u03bd\n    A,I\u2082,I\u2083,J,l=beam.section.A,beam.section.I\u2082,beam.section.I\u2083,beam.section.J,beam.l\n    As\u2082,As\u2083=beam.section.As\u2082,beam.section.As\u2083\n    G=E/2/(1+\u03bd)\n    T=\u03c3*A\n    \u03d5\u2082,\u03d5\u2083=12E*I\u2083/(G*As\u2082*l^2),12E*I\u2082/(G*As\u2083*l^2)\n    K=zeros(12,12)\n\n    K[2,2]=(6/5+2\u03d5\u2082+\u03d5\u2082^2)/(1+\u03d5\u2082)^2\n    K[3,3]=(6/5+2\u03d5\u2083+\u03d5\u2083^2)/(1+\u03d5\u2083)^2\n    K[4,4]=J/A\n    K[5,5]=(2*l^2/15+l^2*\u03d5\u2083/6+l^2*\u03d5\u2083^2/12)/(1+\u03d5\u2083)^2\n    K[6,6]=(2*l^2/15+l^2*\u03d5\u2082/6+l^2*\u03d5\u2082^2/12)/(1+\u03d5\u2082)^2\n    K[8,8]=(6/5+2\u03d5\u2082+\u03d5\u2082^2)/(1+\u03d5\u2082)^2\n    K[9,9]=(6/5+2\u03d5\u2083+\u03d5\u2083^2)/(1+\u03d5\u2083)^2\n    K[10,10]=J/A\n    K[11,11]=(2*l^2/15+l^2*\u03d5\u2083/6+l^2*\u03d5\u2083^2/12)/(1+\u03d5\u2083)^2\n    K[12,12]=(2*l^2/15+l^2*\u03d5\u2082/6+l^2*\u03d5\u2082^2/12)/(1+\u03d5\u2082)^2\n\n    K[3,5]=K[5,3]=-(l/10)/(1+\u03d5\u2083)^2\n    K[6,8]=K[8,6]=-(l/10)/(1+\u03d5\u2082)^2\n    K[9,11]=K[11,9]=(l/10)/(1+\u03d5\u2083)^2\n\n    K[2,6]=K[6,2]=(l/10)/(1+\u03d5\u2082)^2\n    K[5,9]=K[9,5]=(l/10)/(1+\u03d5\u2083)^2\n\n    K[2,8]=K[8,2]=-(6/5+2\u03d5\u2082+\u03d5\u2082^2)/(1+\u03d5\u2082)^2\n    K[3,9]=K[9,3]=-(6/5+2\u03d5\u2083+\u03d5\u2083^2)/(1+\u03d5\u2083)^2\n    K[4,10]=K[10,4]=-J/A\n    K[5,11]=K[11,5]=-(l^2/30+l^2*\u03d5\u2083/6+l^2*\u03d5\u2083^2/12)/(1+\u03d5\u2083)^2\n    K[6,12]=K[12,6]=-(l^2/30+l^2*\u03d5\u2082/6+l^2*\u03d5\u2082^2/12)/(1+\u03d5\u2082)^2\n\n    K[3,11]=K[11,3]=-(l/10)/(1+\u03d5\u2083)^2\n\n    K[2,12]=K[12,2]=(l/10)/(1+\u03d5\u2082)^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": "\nusing Pkg, DrWatson, Random, Test\n\nRandom.seed!(123)\n\n@quickactivate \"StatisticalRethinkingTuring\"\nusing Turing \nusing StatisticalRethinking\n\n#=\nusing Turing, DataFrames\n=#\n\nTuring.setprogress!(false);\n\n@model function linear_reg(x, y)\n    \u03b2 ~ Normal(0, 1)\n    \u03b1 ~ Normal(0, 5)\n    \u03c3 ~ Exponential(1)\n\n    for i \u2208 eachindex(y)\n        y[i] ~ Normal(\u03b1 + \u03b2 * x[i], \u03c3)\n    end\n    return (\u03b1, \u03b2, \u03c3)\nend\n\nf(x) = 5 + 2 * x + 0.5 * randn()\n\n\u0394 = 1.0; xs_train = 0:\u0394:20; ys_train = f.(xs_train);\nxs_test = [10 + i * \u0394 for i in 1:4]; ys_test = f.(xs_test);\n\n# Infer\nm_train = linear_reg(xs_train, ys_train);\n#precis(m_train) |> display  # From StatisticalRethinking.precis\n\nchain_lin_reg = sample(m_train, NUTS(100, 0.65), 200);\nchain_lin_reg |> display\n\n#m_test = linear_reg(xs_test, fill(missing, length(ys_test)));\nm_test = linear_reg(xs_test, similar(xs_test, Missing));\n#m_test = linear_reg(xs_test, missing);\n\n# Use the new predict function!\npredictions = predict(m_test, chain_lin_reg)\npredictions |> display\n\n# Get the mean predicted values.\nys_mean_pred = vec(mean(Array(group(predictions, :y)); dims = 1))\nys_std_pred = vec(std(Array(group(predictions, :y)); dims = 1))\n\n\n# Get the prediction error:\nys_test - ys_mean_pred |> display\nys_test - ys_mean_pred2 |> display\n\n#@test sum(abs2, ys_test - ys_pred) \u2264 \u03c3\n", "meta": {"hexsha": "641b133e0679f37e4c70a17c81dc7314f3d0e4b5", "size": 1311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "research/predict.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/predict.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/predict.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": 23.0, "max_line_length": 65, "alphanum_fraction": 0.6849733028, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7815808935816124}}
{"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": "\"\"\"\ncssls!(AtA,AtB,X,P)\n\nSolve combinatorial subspace least squares (CSSLS) problem. Find X[P] that\nminimizes ||A*X[P] - B[P]|| in the least squares sense, where P is a\n1-bit matrix encoding the combinatorial subspace. Input X is overwritten\nwith the solution.\n\nIn the context of nonnegative least squares, each column of X has a passive\nset which is encoded by \"true\" entries in P, and an active set which is encoded\nby \"false\" entries in P.\n\nInputs:\n\tAtA = A' * A = (n x n) matrix\n\tAtB = A' * B = (n x k)\n\tP = 1-bit matrix of Bools = (? x ?) matrix\n\nReferences:\n\tJ. Kim and H. Park, Fast nonnegative matrix factorization: An\n\tactive-set-like method and comparisons, SIAM J. Sci. Comput., 33 (2011),\n\tpp. 3261\u20133281.\n\n\tM. H. Van Benthem and M. R. Keenan, Fast algorithm for the solution of\n\tlarge-scale non-negativity-constrained least squares problems. J.\n\tChemometrics 2004; 18: 441-450\n\"\"\"\nfunction cssls!(\n\tAtA::Matrix{Float64}, # (n x n) matrix\n\tAtB::Matrix{Float64}, # (n x p) matrix\n\tX::Matrix{Float64},   # (n x p) matrix\n\tP::AbstractArray{Bool}\n\t)\n\n\tn,p = size(AtB)\n\n\t# Find unique columns in P\n\tU = unique(P,dims=2)\n\tnum_unique = size(U,2)\n\n\t# Find indices associates with unique columns in P\n\tE = (Array{Int})[]\n\trp = collect(1:p)\n\tfor i = 1:num_unique\n\t\t# array of indices where P[:,e] == U[:,i]\n\t\te = (Int)[]\n\n\t\t# find columns of P that match U[:,i]\n\t\tj = 1\n\t\twhile j <= length(rp)\n\t\t\t# rp contains columns of P that haven't been assigned\n\t\t\tt = rp[j]\n\n\t\t\t# if column t matches U[:,i] store it, and delete it from rp (don't\n\t\t\t# revisit preiously assigned columns)\n\t\t\tif all(P[:,t] .== U[:,i])\n\t\t\t\tpush!(e,t)      # store column t\n\t\t\t\tdeleteat!(rp,j) # delete t from rp (stored at position j)\n\t\t\telse\n\t\t\t\t# column t didn't match, move to next column\n\t\t\t\tj += 1\n\t\t\tend\n\t\tend\n\n\t\t# store the set of columns matching U[:,i]\n\t\tpush!(E,e)\n\tend\n\n\t# Update X, solve each unique combinatorial subspace\n\tfor i = 1:num_unique\n\t\trr = U[:,i] # row mask (the passive set)\n\n\t\t# If the passive set is empty, these columns are already feasible.\n\t\t# So don't waste time updating them.\n\t\tif any(rr)\n\t\t\tcc = E[i]   # column mask (columns of P matching U[:,i])\n\t\t\tX[rr,cc] = pinv(AtA[rr,rr])*AtB[rr,cc]\n\t\tend\n\tend\nend\n", "meta": {"hexsha": "f7030d9af20b10e2635ce04570c82049f117b8e3", "size": 2210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cssls.jl", "max_stars_repo_name": "platawiec/NonNegLeastSquares.jl", "max_stars_repo_head_hexsha": "ad5ba12140820c2f8b65dbc312a5970e42d7502b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cssls.jl", "max_issues_repo_name": "platawiec/NonNegLeastSquares.jl", "max_issues_repo_head_hexsha": "ad5ba12140820c2f8b65dbc312a5970e42d7502b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cssls.jl", "max_forks_repo_name": "platawiec/NonNegLeastSquares.jl", "max_forks_repo_head_hexsha": "ad5ba12140820c2f8b65dbc312a5970e42d7502b", "max_forks_repo_licenses": ["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": 79, "alphanum_fraction": 0.6574660633, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7815583481284399}}
{"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, \u201cMinimum error thresholding,\u201d Pattern Recognition, vol. 19, no. 1, pp. 41\u201347, 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, \u201cOn minimum error thresholding and its implementations,\u201d Pattern Recognition Letters, vol. 7, no. 4, pp. 201\u2013206, 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# \u2554\u2550\u2561 ad96c6b4-add2-11eb-1a72-8993033e1259\nusing Plots, LaTeXStrings, QuadGK, Roots, DifferentialEquations\n\n# \u2554\u2550\u2561 5168971b-2b60-494c-a8d8-cdfa8e1b8102\nmd\"# 1D Bistable Example\"\n\n# \u2554\u2550\u2561 261580d9-f1a5-442c-8e7f-3479f993f9b2\nmd\"_Define separate production and degradation terms_\"\n\n# \u2554\u2550\u2561 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\u03b3 = 1\n\tks = 1e-4\n\t\u03bd0 = 12.5\n\t\u03bd1 = 200\n\tproduction(n) = (\u03bd0+ \u03bd1 * ks*n^2)/(1+ks*n^2)\n\tdegradation(n) = \u03b3*n\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 868ba091-d0d2-42a2-bca7-f9e996b3870d\nmd\"_Compute the fixed points to split up the 2 attractors into **Basins of Attractions**_\" \n\n# \u2554\u2550\u2561 348718a0-8e19-4911-8998-5de9689bce1d\nfixed_points = find_zeros(n-> production(n) - degradation(n), n_min, n_max)\n\n# \u2554\u2550\u2561 51d6af76-5ed3-41f8-9351-91e683c7bb57\nmd\"_Integrate to get the quasi-potential_\"\n\n# \u2554\u2550\u2561 acb0adcf-fc19-45cf-bf0f-eb5532743b1a\nbegin\n\tf = production\n\tg = degradation\n\t\n\t\u03d5(n) = quadgk(n -> -2*(f(n) -g(n))/(f(n) + g(n)), n_min, n)[1]\nend\n\n# \u2554\u2550\u2561 b4c511ea-fc96-475e-a5fc-1c9e282ca0e5\n\u03d5_vec = \u03d5.(n)\n\n# \u2554\u2550\u2561 3373f26d-a6a4-4378-a8e1-c011c2e9f7a9\np2 = plot(n, \u03d5_vec, ylabel=L\"\\phi(n)\", xlabel=L\"n\", label=\"\", title=\"Quasi-potential\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 178564ff-da53-4dd5-ba1f-b3e5db24b2ea\nbegin\n\tplot(n->log10.(f(n) + g(n)), n, label=L\"f + g\")\n\tplot!(n, log10.(\u212f.^(-\u03d5_vec)), label=L\"e^{-\\phi}\")\n\tp3 = plot!(xaxis=:log10, legend=:topleft)\nend\n\n# \u2554\u2550\u2561 33cf16fa-679d-4447-aa59-b6d48e8fd15a\nmd\"_Compute the normalized probability_\"\n\n# \u2554\u2550\u2561 a7e9be12-a1d4-4f1a-bbfc-d2642e5a9dd5\nbegin\n\tfn = f.(n)\n\tgn = g.(n)\n\tp_unnormal(n) =  \u212f^(-\u03d5(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# \u2554\u2550\u2561 f5b8a081-222f-4dd6-ae4c-af7060aa4223\nmd\"_Set up the jump process simulation_\"\n\n# \u2554\u2550\u2561 467386e3-2ee8-46d4-9b40-831ae2778a57\nrandom_count() = floor(Int, n_min + rand() * n_max)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4547d20c-dab1-4df2-aa54-b8c52b1b5eeb\nmd\"_Setup functions to do a longer time simulation and compare to integrated probability distribution_\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0e38a5c3-d970-4844-b560-fe4ed5452d85\ntotals, num_steps = big_sim()\n\n# \u2554\u2550\u2561 573a4914-b37e-4c2b-bd23-c10b58a6d4db\nbegin\n\tsim_frac = totals./sum(totals)\nend\n\n# \u2554\u2550\u2561 c62dd4a3-80ce-4b1f-b5a1-6142d30d0880\nmd\"Time fractions from simulations is $(sim_frac)\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5cabf565-b573-4446-b34d-8812986b25fe\nmd\"Time fractions from integration of probability is $(comp_frac)\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550ad96c6b4-add2-11eb-1a72-8993033e1259\n# \u255f\u25005168971b-2b60-494c-a8d8-cdfa8e1b8102\n# \u255f\u2500261580d9-f1a5-442c-8e7f-3479f993f9b2\n# \u2560\u255002d0fcf2-ca87-49ae-a8f3-f14310d0182a\n# \u2560\u255013ddc727-e9bd-44f2-ba5e-c6c311b41723\n# \u255f\u2500868ba091-d0d2-42a2-bca7-f9e996b3870d\n# \u2560\u2550348718a0-8e19-4911-8998-5de9689bce1d\n# \u255f\u250051d6af76-5ed3-41f8-9351-91e683c7bb57\n# \u2560\u2550acb0adcf-fc19-45cf-bf0f-eb5532743b1a\n# \u2560\u2550b4c511ea-fc96-475e-a5fc-1c9e282ca0e5\n# \u2560\u25503373f26d-a6a4-4378-a8e1-c011c2e9f7a9\n# \u255f\u2500e147802a-2cc5-4610-821b-bf351ed62f9f\n# \u2560\u2550178564ff-da53-4dd5-ba1f-b3e5db24b2ea\n# \u255f\u250033cf16fa-679d-4447-aa59-b6d48e8fd15a\n# \u2560\u2550a7e9be12-a1d4-4f1a-bbfc-d2642e5a9dd5\n# \u255f\u2500f5b8a081-222f-4dd6-ae4c-af7060aa4223\n# \u2560\u2550467386e3-2ee8-46d4-9b40-831ae2778a57\n# \u2560\u25506ae4ed84-80c2-4c06-b69a-c81e6485b78b\n# \u2560\u2550f32b2ab8-a941-463b-bb27-968c09e24777\n# \u2560\u255050c911b1-57cf-4de4-9d65-054318c445fe\n# \u255f\u25004547d20c-dab1-4df2-aa54-b8c52b1b5eeb\n# \u2560\u2550456090be-e1c0-452e-b0ad-98fbc9f0576f\n# \u2560\u255023494ad1-82e3-4eee-86e3-695511de502e\n# \u2560\u25500e38a5c3-d970-4844-b560-fe4ed5452d85\n# \u255f\u2500c62dd4a3-80ce-4b1f-b5a1-6142d30d0880\n# \u255f\u25005cabf565-b573-4446-b34d-8812986b25fe\n# \u2560\u2550573a4914-b37e-4c2b-bd23-c10b58a6d4db\n# \u2560\u255086ee8326-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": "using SparseArrays, DiffEqOperators, LinearAlgebra, Random,\n      Test, BandedMatrices, FillArrays\n\n\n# Analytic solutions to higher order operators.\n# Do not modify unless you are completely certain of the changes.\n\n# 4th derivative, 4th order\nfunction fourth_deriv_approx_stencil(N)\n    A = zeros(N,N+2)\n    A[1,1:8] = [3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3]\n    A[2,1:8] = [2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6]\n\n    A[N-1,N-5:end] = reverse([2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6], dims=2)\n    A[N,N-5:end] = reverse([3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3], dims=2)\n\n    for i in 3:N-2\n        A[i,i-2:i+4] = [-1/6 2.0 -13/2 28/3 -13/2 2.0 -1/6]\n    end\n    return A\nend\n\n\nfunction second_deriv_fourth_approx_stencil(N)\n    A = zeros(N,N+2)\n    A[1,1:6] = [5/6 -15/12 -1/3 7/6 -6/12 5/60]\n    A[N,N-3:end] = [1/12 -6/12 14/12 -4/12 -15/12 10/12]\n    for i in 2:N-1\n        A[i,i-1:i+3] = [-1/12 4/3 -5/2 4/3 -1/12]\n    end\n    return A\nend\n\nfunction second_derivative_stencil(N)\n  A = zeros(N,N+2)\n  for i in 1:N, j in 1:N+2\n      (j-i==0 || j-i==2) && (A[i,j]=1)\n      j-i==1 && (A[i,j]=-2)\n  end\n  A\nend\n\n# analytically derived central difference operators for the irregular grid:\n# [0.0, 0.08, 0.1, 0.15, 0.19, 0.26, 0.29], and spacing:\n# dx = [0.08, 0.02, 0.05, 0.04, 0.07, 0.03]\n# with convention that the first number is the derivative order\n# and the second is the approximation order\n\nfunction analyticCtrOneTwoIrr()\n    A = zeros(5,7)\n    A[1,1:3] = [-5. / 2., -75. / 2., 40.]\n    A[2,2:4] = [-250. / 7., 30., 40. / 7.]\n    A[3,3:5] = [-80. / 9., -5., 125. / 9.]\n    A[4,4:6] = [-1225. / 77., 825. / 77., 400. / 77.]\n    A[5,5:7] = [-30. / 7., -400. / 21., 70. / 3.]\n    A\nend\n\nfunction analyticCtrTwoTwoIrr()\n    A = zeros(5,7)\n    A[1,1:3] = [250., -1250., 1000.]\n    A[2,2:4] = [10000. / 7., -2000., 4000. / 7.]\n    A[3,3:5] = [4000. / 9., -1000., 5000. / 9.]\n    A[4,4:6] = [454. + 42. / 77., -5000. / 7., 20000. / 77.]\n    A[5,5:7] = [6000. / 21., -20000. / 21., 2000. / 3.]\n    A\nend\n\nfunction analyticCtrTwoFourIrr()\n    A = zeros(3,7)\n    A[1,1:5] = [14. + 12012. / 13167., 1542. + 2736. / 13167.,\n                -2288. - 11704. / 13167., 838. + 1254. / 13167.,\n                -106. - 4298. / 13167.]\n    A[2,2:6] = [-223. - 461. / 693., 847. + 154. / 693.,\n                -1311. - 477. / 693., 699. + 593. / 693.,\n                -11. - 502. / 693.]\n    A[3,3:7] = [2. + 12166. / 13167., 538. + 12654. / 13167.,\n                -912. - 9196. / 13167., 508. + 8664. / 13167.,\n                -137. - 11121. / 13167.]\n    A\nend\n\nfunction analyticCtrFourTwoIrr()\n    A = zeros(3,7)\n    A[1,1:5] = [462000000. / 4389.,\n                -8550000000. / 4389.,\n                11704000000. / 4389.,\n                -5016000000. / 4389.,\n                1400000000. / 4389.]\n    A[2,2:6] = [200000000. / 231.,\n                -385000000. / 231.,\n                360000000. / 231.,\n                -200000000. / 231.,\n                25000000. / 231.]\n    A[3,3:7] = [770000000. / 4389.,\n                -3420000000. / 4389.,\n                4180000000. / 4389.,\n                -2850000000. / 4389.,\n                1320000000 / 4389.]\n    A\nend\n\n\nfunction convert_by_multiplication(::Type{Array}, A::AbstractDerivativeOperator{T}, N::Int=A.dimension) where T\n    @assert N >= A.stencil_length # stencil must be able to fit in the matrix\n    mat = zeros(T, (N, N+2))\n    v = zeros(T, N+2)\n    for i=1:N+2\n        v[i] = one(T)\n        #=\n            calculating the effect on a unit vector to get the matrix of transformation\n            to get the vector in the new vector space.\n        =#\n        mul!(view(mat,:,i), A, v)\n        v[i] = zero(T)\n    end\n    return mat\nend\n\n# Tests the corrrectness of stencils, along with concretization.\n# Do not modify the following test-set unless you are completely certain of your changes.\n@testset \"Correctness of Uniform Stencils\" begin\n    N = 20\n    L = CenteredDifference(4,4, 1.0, N)\n    correct = fourth_deriv_approx_stencil(N)\n\n    # Check that stencils (according to convert_by_multiplication) agree with correct\n    @test convert_by_multiplication(Array, L, N) \u2248 correct\n\n    # Check that concretization agrees correct\n    @test Array(L) \u2248 correct\n    @test sparse(L) \u2248 correct\n    @test BandedMatrix(L) \u2248 correct\n\n    L = CenteredDifference(2,4, 1.0, N)\n    correct = second_deriv_fourth_approx_stencil(N)\n\n    # Check that stencils (according to convert_by_multiplication) agree with correct\n    @test convert_by_multiplication(Array, L, N) \u2248 correct\n\n    # Check that concretization agrees correct\n    @test Array(L) \u2248 correct\n    @test sparse(L) \u2248 correct\n    @test BandedMatrix(L) \u2248 correct\nend\n\n@testset \"Correctness of Non-Uniform Stencils\" begin\n    x = [0., 0.08, 0.1, 0.15, 0.19, 0.26, 0.29]\n    nx = length(x)\n    dx = diff(x)\n\n    # Second-Order First Derivative\n    L = CenteredDifference(1, 2, dx, nx-2)\n    correct = analyticCtrOneTwoIrr()\n\n    # Check that stencils agree with correct\n    for (i,coefs) in enumerate(L.stencil_coefs)\n        @test Array(coefs) \u2248 correct[i,correct[i,:] .!= 0.]\n    end\n    @test Array(L) \u2248 correct\n    @test sparse(L) \u2248 correct\n    @test BandedMatrix(L) \u2248 correct\n\n    # Second-Order Second Derivative\n    L = CenteredDifference(2, 2, dx, nx-2)\n    correct = analyticCtrTwoTwoIrr()\n\n    # Check that stencils agree with correct\n    for (i,coefs) in enumerate(L.stencil_coefs)\n        @test Array(coefs) \u2248 correct[i,correct[i,:] .!= 0.]\n    end\n    @test Array(L) \u2248 correct\n    @test sparse(L) \u2248 correct\n    @test BandedMatrix(L) \u2248 correct\n\n    # Fourth-Order Second Derivative\n    L = CenteredDifference(2, 4, dx, nx-2)\n    correct = analyticCtrTwoFourIrr()\n\n    # Check that stencils agree with correct\n    for (i,coefs) in enumerate(L.stencil_coefs)\n        @test Array(coefs) \u2248 correct[i,correct[i,:] .!= 0.]\n    end\n    @test Array(L)[2:end-1,:] \u2248 correct\n    @test sparse(L)[2:end-1,:] \u2248 correct\n    @test BandedMatrix(L)[2:end-1,:] \u2248 correct\n\n    # Second-Order Fourth Derivative\n    L = CenteredDifference(4, 2, dx, nx-2)\n    correct = analyticCtrFourTwoIrr()\n\n    # Check that stencils agree with correct\n    for (i,coefs) in enumerate(L.stencil_coefs)\n        @test Array(coefs) \u2248 correct[i,correct[i,:] .!= 0.]\n    end\n    @test Array(L)[2:end-1,:] \u2248 correct\n    @test sparse(L)[2:end-1,:] \u2248 correct\n    @test BandedMatrix(L)[2:end-1,:] \u2248 correct\nend\n\n# tests for full and sparse function\n@testset \"Full and Sparse functions:\" begin\n    N = 10\n    d_order = 2\n    approx_order = 2\n    correct = second_derivative_stencil(N)\n    A = CenteredDifference(d_order,approx_order,1.0,N)\n\n    @test convert_by_multiplication(Array,A,N) == correct\n    @test Array(A) == second_derivative_stencil(N)\n    @test sparse(A) == second_derivative_stencil(N)\n    @test BandedMatrix(A) == second_derivative_stencil(N)\n    @test opnorm(A, Inf) == opnorm(correct, Inf)\n\n\n    # testing higher derivative and approximation concretization\n    N = 20\n    d_order = 4\n    approx_order = 4\n    A = CenteredDifference(d_order,approx_order,1.0,N)\n    correct = convert_by_multiplication(Array,A,N)\n\n    @test Array(A) \u2248 correct\n    @test sparse(A) \u2248 correct\n    @test BandedMatrix(A) \u2248 correct\n\n    N = 26\n    d_order = 8\n    approx_order = 8\n    A = CenteredDifference(d_order,approx_order,1.0,N)\n    correct = convert_by_multiplication(Array,A,N)\n\n    @test Array(A) \u2248 correct\n    @test sparse(A) \u2248 correct\n    @test BandedMatrix(A) \u2248 correct\n\n    # testing correctness of multiplication\n    N = 1000\n    d_order = 4\n    approx_order = 10\n    y = collect(1:1.0:N+2).^4 - 2*collect(1:1.0:N+2).^3 + collect(1:1.0:N+2).^2;\n    y = convert(Array{BigFloat, 1}, y)\n\n    A = CenteredDifference(d_order,approx_order,one(BigFloat),N)\n    correct = convert_by_multiplication(Array,A,N)\n    @test Array(A) \u2248 correct\n    @test sparse(A) \u2248 correct\n    @test BandedMatrix(A) \u2248 correct\n    @test A*y \u2248 Array(A)*y\nend\n\n@testset \"Indexing tests\" begin\n    N = 1000\n    d_order = 4\n    approx_order = 10\n\n    A = CenteredDifference(d_order,approx_order,1.0,N)\n    @test A[1,1] == Array(A)[1,1]\n    @test A[10,20] == 0\n\n    correct = Array(A)\n    for i in 1:N\n        @test A[i,i] == correct[i,i]\n    end\n\n    # Indexing Tests\n    N = 1000\n    d_order = 2\n    approx_order = 2\n\n    A = CenteredDifference(d_order,approx_order,1.0,N)\n    M = Array(A,1000)\n    @test A[1,1] == M[1,1]\n    @test A[1:4,1] == M[1:4,1]\n    @test A[5,2:10] == M[5,2:10]\n    @test A[60:100,500:600] == M[60:100,500:600]\nend\n\n@testset \"Operations on matrices\" begin\n    N = 51\n    M = 101\n    d_order = 2\n    approx_order = 2\n\n    xarrs = Vector{Union{Array,StepRangeLen}}(undef,0)\n    yarrs = Vector{Union{Array,StepRangeLen}}(undef,0)\n    push!(xarrs, range(0,stop=1,length=N))\n    push!(yarrs, range(0,stop=1,length=M))\n    push!(xarrs, vcat(xarrs[1][1:floor(Int,N/2)].^0.2020, xarrs[1][ceil(Int,N/2):end].^2.015))\n    push!(yarrs, vcat(yarrs[1][1:floor(Int,M/2)].^1.793, yarrs[1][ceil(Int,M/2):end].^2.019))\n\n    for (i,xarr,yarr) in zip(1:2,xarrs,yarrs)\n        if i == 1\n            dx = xarr[2] - xarr[1]\n            dy = yarr[2] - yarr[1]\n        elseif i == 2\n            dx = diff(xarr)\n            dy = diff(yarr)\n        end\n        F = [x^2+y for x = xarr, y = yarr]\n\n        A = CenteredDifference(d_order,approx_order,dx,length(xarr)-2)\n        B = i == 1 ? CenteredDifference(d_order,approx_order,dy,length(yarr)) :\n            CenteredDifference(d_order,approx_order,dy,length(yarr)-2)\n\n        @test A*F \u2248 2*ones(N-2,M) atol=1e-9\n\n        # Operators are defined such that\n        # B must be applied to F from the left\n        @test all(abs.(B * F') .<= 1e-8)\n        @test all(abs.(A * (B * F')') .<= 1e-4)\n\n        G = [x^2+y^2 for x = xarr, y = yarr]\n\n        @test A*G \u2248 2*ones(N-2,M) atol=1e-9\n        @test B * G' \u2248 2 * ones(M-2,N) atol=1e-8\n        @test all(abs.(A * (B * G')') .<= 1e-4)\n    end\nend\n\n@testset \"Scalar multiplication with operators\" begin\n    A = CenteredDifference(2, 2, 10., 3)\n\n    scalar_ans = [0.033 -0.066 0.033  0.     0.;\n                  0.    0.033  -0.066 0.033  0.;\n                  0.    0.     0.033  -0.066 0.033]\n    @test Array(3.3 * A) \u2248 scalar_ans\nend\n\n@testset \"Left-multiplying operators with a vector of coefficients\" begin\n    A = CenteredDifference(2, 2, 1., 3)\n    B = UpwindDifference(1, 1, 1., 3, 1.)\n    C = UpwindDifference(1, 1, 1., 3, [2., 3., 4.])\n    c = [1., 1., 3.]\n    cA =  c * A\n    cB =  c * B\n    cC =  c * C\n\n    @test cA.coefficients == c\n    @test cB.coefficients == c\n    @test cC.coefficients == [2., 3., 12.]\n\n    x = [1., 2., 3., 4., 5.]\n    @test (A * x) .* c \u2248 cA * x\n    @test (B * x) .* c \u2248 cB * x\n    @test (C * x) .* c \u2248 cC * x\n\n    @test_throws DimensionMismatch ones(10) * A\n    @test_throws DimensionMismatch ones(10) * cA\n    @test_throws DimensionMismatch ones(10) * B\n    @test_throws DimensionMismatch ones(10) * C\nend\n\n# These tests are broken due to the implementation 2.2*LD creating a DerivativeOperator\n# rather than an Array\n#=\n@testset \"Linear combinations of operators\" begin\n    N = 10\n    Random.seed!(0); LA = DiffEqArrayOperator(rand(N,N+2))\n    LD = CenteredDifference(2,2,1.0,N)\n    L = 1.1*LA - 2.2*LD + 3.3*Eye(N,N+2)\n    # Builds convert(L) the brute-force way\n    fullL = zeros(N,N+2)\n    v = zeros(N+2)\n    for i = 1:N+2\n        v[i] = 1.0\n        fullL[:,i] = L*v\n        v[i] = 0.0\n    end\n    @test_broken convert(AbstractMatrix,L) \u2248 fullL\n    for p in [1,2,Inf]\n        @test_broken opnorm(L,p) \u2248 opnorm(fullL,p)\n    end\nend\n=#\n", "meta": {"hexsha": "63df393faaa13f063dc2dc6445f67eb3886657d6", "size": 11518, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DerivativeOperators/derivative_operators_interface.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": "test/DerivativeOperators/derivative_operators_interface.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": "test/DerivativeOperators/derivative_operators_interface.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": 30.6329787234, "max_line_length": 111, "alphanum_fraction": 0.5764021532, "num_tokens": 4332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8652240860523327, "lm_q1q2_score": 0.7815519066842075}}
{"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, \u0394t, stop_iteration, topo)\n    results = [run_and_analyze(Nx=N, \u0394t=\u0394t, stop_iteration=stop_iteration, topo=topo,\n                               output=false) for N in Nx]\n\n    L\u2081 = map(r -> r.L\u2081, results)\n    L\u221e = map(r -> r.L\u221e, results)\n\n    return (L\u2081=L\u2081, L\u221e=L\u221e)\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_\u0394x = 2\u03c0 / maximum(Nx)\n   proposal_\u0394t = 1e-3 * min_\u0394x^2 # proposal time-step\nstop_iteration = round(Int, stop_time / proposal_\u0394t)\n            \u0394t = 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, \u0394t, stop_iteration, topo) for topo in topologies]\n\nfig, axs = subplots()\n\nfor (itopo, topo) in enumerate(topologies)\n    L\u2081 = errors[itopo].L\u2081\n    L\u221e = errors[itopo].L\u221e\n    name =\"$(topo[1]), $(topo[2])\"\n\n    loglog(Nx, L\u2081, \"o\", basex=2, color=defaultcolors[itopo], mfc=\"None\", label=\"\\$L_1\\$-norm, $name\")\n    loglog(Nx, L\u221e, \"^\", basex=2, color=defaultcolors[itopo], mfc=\"None\", label=\"\\$L_\\\\infty\\$-norm, $name\")\nend\n\nL\u2081 = errors[1].L\u2081\nL\u221e = errors[1].L\u221e\nloglog(Nx, L\u2081[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\u2081 = errors[itopo].L\u2081\n    L\u221e = errors[itopo].L\u221e\n    test_rate_of_convergence(L\u2081, Nx, expected=-2.0, atol=0.01, name=\"2D diffusion $topo L\u2081\")\n    test_rate_of_convergence(L\u221e, Nx, expected=-2.0, atol=0.06, name=\"2D diffusion $topo L\u221e\")\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": "# ## \u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\n# \u307e\u305a\u7dda\u5f62\u56de\u5e30\u306e\u5834\u5408\u306e\u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u306e\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u307e\u3059\u3002\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#         \u03b2\u0302 = multiple_regression(X[train,:],y[train])\n#         y\u0302 = insert_ones(X[test,:])*\u03b2\u0302\n#         S += dot(y[test]-y\u0302,y[test]-y\u0302)\n#     end\n#     return S/n\n# end\n# ```\n# ### \u4f8b39\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\u03b2 = randn(p+1); \u03b2[2:3] .= 0\ny_39 = insert_ones(X_39)*\u03b2 + randn(n)\n@show cv_linear(X_39[:,[3,4,5]],y_39,10);\n@show cv_linear(X_39,y_39,10);\n# \u3042\u308c\uff1f\u5909\u6570\u9078\u629e\u3057\u305f\u65b9\u304c\u8aa4\u5dee\u3067\u304b\u3044\u305e\uff1f\u8a66\u884c\u56de\u6570\u3092\u5897\u3084\u3057\u3066\u5168\u5909\u6570\u3092\u7528\u3044\u305f\u5834\u5408\u306eCV\u5024\u3068\n# \u5909\u6570\u9078\u629e\u3092\u884c\u3063\u305f\u5834\u5408\u306eCV\u5024\u3092\u53ef\u8996\u5316\u3057\u307e\u3059\u3002\nusing Joe # hide\nU=Float64[]; V = Float64[] \nfor _ in 1:100\n    global U, V, X_39, \u03b2, n # hide\n    local y # hide\n    y = insert_ones(X_39)*\u03b2 + 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=\"\u5909\u65704,5,6\u3092\u9078\u3093\u3060\u6642\u306e\u4e8c\u4e57\u8aa4\u5dee\",\n                ylabel=\"\u5168\u5909\u6570\u3092\u9078\u3093\u3060\u6642\u306e\u4e8c\u4e57\u8aa4\u5dee\",\n                title=\"\u5909\u6570\u3092\u591a\u304f\u9078\u3073\u3059\u304e\u3066\u904e\u5b66\u7fd2\")\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$ \u306e\u76f4\u7dda\u306e\u4e0a\u5074\u306b\u5927\u591a\u6570\u306e\u70b9\u304c\u30d7\u30ed\u30c3\u30c8\u3055\u308c\u3066\u3044\u308b\u306e\u3067\u3001\n# \u5909\u6570\u9078\u629e\u3092\u3057\u305f\u65b9\u304c\u8aa4\u5dee\u304c\u5c11\u306a\u3044\u3053\u3068\u304c\u5206\u304b\u308a\u307e\u3057\u305f\u3002\n# \u305f\u3060\u3001\u3042\u307e\u308a\u4e8c\u4e57\u8aa4\u5dee\u306e\u9055\u3044\u306f\u5927\u304d\u304f\u306a\u3044\u3067\u3059\u3002\n# ### \u4f8b40\n# k\u306e\u5024\u3092\u5909\u3048\u305f\u3068\u304d\u306eCV\u306e\u4e88\u6e2c\u8aa4\u5dee\u306e\u5909\u5316\nn = 100; p = 5;\np40 = plot(ylims=(0.3,1.5),xlabel=\"k\",ylabel=\"CV\u306e\u5024\",\n            title=\"k-fold\u306ek\u3068CV\u306e\u5024\u306e\u95a2\u4fc2\",legend=false)\nRandom.seed!(1)\nfor _ in 1:10\n    global p40 # hide\n    local X, \u03b2, y, U, V # hide\n    X = randn(n,p)\n    \u03b2 = randn(p+1)\n    y = insert_ones(X) * \u03b2 + 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# ### \u4f8b41 (FInsher\u306e\u3042\u3084\u3081)\n# \u3042\u3084\u3081\u306e\u30c7\u30fc\u30bf\u30bb\u30c3\u30c8\u3067K\u8fd1\u508d\u6cd5\u306e\uff4b\u6bce\u306b\u8aa4\u308a\u7387\u3092\u8a55\u4fa1\u3057\u307e\u3059\u3002\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# \u30c7\u30fc\u30bf\u30bb\u30c3\u30c8\u3092\u30e9\u30f3\u30c0\u30e0\u306b\u4e26\u3079\u66ff\u3048\u3066\u304a\u304d\u307e\u3059\u3002\nRandom.seed!(1)\norder = StatsBase.sample(1:n,n,replace=false);\nX_41 = X_41[order,:];\ny_41 = y_41[order];\n# 10-fold\u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u306a\u306e\u3067\u3001\u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u309215\u6bce\u306b\u4ea4\u4ee3\u3055\u305b\u308b\u3053\u3068\u306b\u306a\u308a\u307e\u3059\u3002\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=\"\u8aa4\u308a\u7387\",\n            legend=false, title=\"CV\u306b\u3088\u308b\u8aa4\u308a\u7387\u306e\u8a55\u4fa1\")\nsavefig(p41,joinpath(@OUTPUT,\"fig3-3.svg\")) # hide\n# \\fig{fig3-3}\n# \\lineskip\n# $K \\ge 3$\u3067\u5927\u304d\u304f\u8aa4\u308a\u7387\u304c\u4f4e\u4e0b\u3059\u308b\u3053\u3068\u304c\u5206\u304b\u308a\u307e\u3057\u305f\u3002\n# python\u3067\u306f\u5b9f\u884c\u306b10\u5206\u7a0b\u5ea6\u304b\u304b\u3063\u305f\u3068\u3042\u308a\u307e\u3059\u304c\u3001\u3044\u304f\u3089\u306a\u3093\u3067\u3082\u9045\u3059\u304e\u3067\u306f\uff1f(julia\u306f\u77ac\u6bba)\n# ## \u7dda\u5f62\u56de\u5e30\u306e\u5834\u5408\u306e\u516c\u5f0f(CV\u306e\u516c\u5f0f)\n# \u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u3067\u306e\u8aa4\u5dee\u306e\u5206\u6790\u306f\u3001\u8a13\u7df4\u30c7\u30fc\u30bf\u6bce\u306b\u91cd\u56de\u5e30\u5206\u6790\u3092\u884c\u3046\u5fc5\u8981\u304c\u3042\u308b\u306e\u3067\u3001\n# \u51e6\u7406\u306b\u6642\u9593\u304c\u304b\u304b\u308a\u307e\u3059\u3002$\\hat{\\beta}_{-S}$\u3092\u3042\u3089\u308f\u306b\u6c42\u3081\u308b\u3053\u3068\u306a\u304f\u3001CV\u3092\n# \u697d\u3057\u3066\u8a55\u4fa1\u3067\u304d\u308b\u306e\u304c\u3053\u306e\u516c\u5f0f\u3067\u3059\u3002($S$\u306f\u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u306e\u96c6\u5408\u3001$-S$\u306f\u8a13\u7df4\u30c7\u30fc\u30bf\u306e\u96c6\u5408)\n# \\lineskip\n# $$\\sum_{S} || (I - H_S)^{-1}e_S||^2$$\n# \u305f\u3060\u3057\u3001$H_S = X_S(X^\\mathsf{T}X)^{-1}X_S^\\mathsf{T}$\u3001\n# $e_S = y_S - X_S\\hat{\\beta}$ \u3067\u3059\u3002\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u5b9f\u88c5\u3057\u3066\u3001\u30d9\u30f3\u30c1\u30de\u30fc\u30af\u3092\u3057\u3066\u307f\u307e\u3059\u3002\n# cv_fast\u95a2\u6570\u306f\u6b21\u306e\u3088\u3046\u306b\u5b9f\u88c5\u3057\u307e\u3057\u305f\u3002\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\u03b2 = randn(p+1); \u03b2[2:3] .= 0\ny = insert_ones(X)*\u03b2 + randn(n);\n# \u30eb\u30fc\u30d7\u306e\u30cd\u30b9\u30c8\u3092\u6d45\u304f\u3057\u305f\u3044\u306e\u3067\u3001K-fold\u306ek\u306e\u30ea\u30b9\u30c8\u3092\u4f5c\u3063\u3066\u3001\u30eb\u30fc\u30d7\u3059\u308b\u3053\u3068\u306b\u3057\u307e\u3059\u3002\nK = [i for i in 2:1000 if 1000%i ==0]\nt_linear = Vector{Float64}(undef,length(K));\nt_fast = similar(t_linear);\n# \u307e\u305a\u306f\u95a2\u6570\u306e\u6163\u3089\u3057\u904b\u8ee2\u3092\n@show cv_linear(X,y,10)\n@show cv_fast(X,y,10)\n# \u5024\u304c\u4e00\u81f4\u3059\u308b\u3053\u3068\u306f\u78ba\u8a8d\u3067\u304d\u307e\u3057\u305f\u3002\u305d\u308c\u3067\u306f\u3001\u3044\u3056\u672c\u756a!\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=\"\u5b9f\u884c\u6642\u9593\",\n           label=\"cv_linear\",title=\"cv_fast\u3068cv_linear\u306e\u6bd4\u8f03\",\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$\u3067\u306fcv_fast\u306e\u65b9\u304c\u5b9f\u884c\u6642\u9593\u304c\u77ed\u3044\u3053\u3068\u304c\u5206\u304b\u308a\u307e\u3059\u3002\n# \u539f\u8457\u3068\u6bd4\u3079\u308b\u3068\u3001\u30de\u30b7\u30f3\u306e\u9055\u3044\u304c\u3042\u308b\u3068\u306f\u3044\u3048\u3001julia\u306f\u901f\u3044\u3068\u3044\u3046\u3053\u3068\u3082\u3088\u304f\u308f\u304b\u308a\u307e\u3059\u3002\n# ## \u30d6\u30fc\u30c8\u30b9\u30c8\u30e9\u30c3\u30d7\n# \u4ee5\u4e0b\u306e\u3088\u3046\u306a\u8907\u5408\u578b\u3068bootstrap\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u307e\u3057\u305f\u3002\n# \u539f\u8457\u306e\u30b3\u30fc\u30c9\u3088\u308a\u306f\u53ef\u8aad\u6027\u304c\u5411\u4e0a\u3057\u305f\u304b\u306a\u3041\u3002\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# ### \u4f8b43\n# \u30c7\u30fc\u30bf\u306f[\u3053\u3053](https://bitbucket.org/prof-joe/statistical_learning_with_python/src/master/)\u304b\u3089\u30c0\u30a6\u30f3\u30ed\u30fc\u30c9\u3067\u304d\u307e\u3059\u3002\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# ### \u4f8b44\n# \u30c7\u30fc\u30bf\u306e\u8aad\u307f\u8fbc\u307f\nusing Joe,DelimitedFiles\ndf = readdlm(joinpath(\"_assets\",\"data\",\"crime.txt\"))\nX = df[:,3:4]; y =df[:,1]\n\u03b2 = multiple_regression(X,y)\n\n# \u56de\u5e30\u4fc2\u6570\u306e\u305d\u308c\u305e\u308c\u306b\u3064\u3044\u3066\u3001\u30d6\u30fc\u30c8\u30b9\u30c8\u30e9\u30c3\u30d7\u6cd5\u3092\u9069\u7528\u3057\u307e\u3059\u3002\u3053\u3053\u3067\u306f\u6a19\u6e96\u504f\u5dee\u3060\u3051\u3092\u51fa\u529b\u3057\u307e\u3059\u3002\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        \u03b2 = multiple_regression(X,y)\n        return \u03b2[j]\n    end\n    std_bt[j] = bootstrap(df,func_2,1000).stderr\nend\nstd_bt\n# GLM.jl\u3067\u56de\u5e30\u4fc2\u6570\u3092\u63a8\u5b9a\u3057\u305f\u3068\u304d\u306e\u6a19\u6e96\u504f\u5dee\u3068\u6bd4\u8f03\u3057\u3066\u307f\u307e\u3059\u3002\nusing GLM, DataFrames\ndata = DataFrame(df,:auto)\nols = lm(@formula(x1 ~ x3 + x4), data)\n# \u6a19\u6e96\u504f\u5dee\u304c\u307b\u307c\u4e00\u81f4\u3059\u308b\u3053\u3068\u304c\u5206\u304b\u308a\u307e\u3057\u305f\u3002", "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# \u2554\u2550\u2561 acd7da78-1d69-11eb-2517-e1bafdc14f4a\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 acd82a8c-1d69-11eb-10c9-0902b833d79e\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Plots, LaTeXStrings, Measures\nend\n\n# \u2554\u2550\u2561 2e6c02cc-1d69-11eb-283a-1bcf9e0044bf\nmd\"## Listing 1.10\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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,\u22c5)\", label=[\"f(x, 0)\" \"f(x, 2)\"])\n\tp1 = annotate!(-1, -0.2, text(\"Minimum = (0,0)\", :left, :top, 10))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ad012874-1d69-11eb-24a0-e936c7c266d5\nmd\"## End of listing 1.10\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25002e6c02cc-1d69-11eb-283a-1bcf9e0044bf\n# \u2560\u2550acd7da78-1d69-11eb-2517-e1bafdc14f4a\n# \u2560\u2550acd82a8c-1d69-11eb-10c9-0902b833d79e\n# \u2560\u2550acd8c1cc-1d69-11eb-3164-5b9e66fc3664\n# \u2560\u2550ace3c478-1d69-11eb-0a4d-f191cf032e78\n# \u2560\u2550ace462fa-1d69-11eb-2b31-c1c9efe2376f\n# \u2560\u2550acf332f0-1d69-11eb-09df-43d188f0b58d\n# \u255f\u2500ad012874-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": "# ---\n# title: 60. Permutation Sequence\n# id: problem60\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Math, Backtracking\n# link: <https://leetcode.com/problems/permutation-sequence/description/>\n# hidden: true\n# ---\n# \n# The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.\n# \n# By listing and labeling all of the permutations in order, we get the following\n# sequence for `n = 3`:\n# \n#   1. `\"123\"`\n#   2. `\"132\"`\n#   3. `\"213\"`\n#   4. `\"231\"`\n#   5. `\"312\"`\n#   6. `\"321\"`\n# \n# Given `n` and `k`, return the `kth` permutation sequence.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 3, k = 3\n#     Output: \"213\"\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 4, k = 9\n#     Output: \"2314\"\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: n = 3, k = 1\n#     Output: \"123\"\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 9`\n#   * `1 <= k <= n!`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "190e3573d7cb46f7ef1221f2e9fd6bc1a39fb5a8", "size": 1012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/60.permutation-sequence.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/60.permutation-sequence.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/60.permutation-sequence.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.5692307692, "max_line_length": 80, "alphanum_fraction": 0.4950592885, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.7815310514743128}}
{"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\u2019s score on the midterm exam is the sum of two components: the student\u2019s 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\u2019s 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    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    Coef.  Std. Error      t  Pr(>|t|)  Lower 95%  Upper 95%\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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\u2112::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\u2112::V\n    diag\u03a3::V\nend\n\nfunction SqExponentialARD(ln\u2112::AbstractVector)\n    diag\u03a3 = exp.(-2 .* ln\u2112)\n    SqExponentialARD(WeightedSqEuclidean(diag\u03a3), ln\u2112, diag\u03a3)\nend\n\n@inline (k::SqExponentialARD)(\u03c4::AbstractFloat) = exp(-\u03c4 / 2)\n\nGaussianARD = SqExponentialARD\n\nnumparams(k::SqExponentialARD) = (length(k.ln\u2112),)\nparamtypes(k::SqExponentialARD{F}) where F = (F,) \nparams(k::SqExponentialARD) = (ln\u2112 = k.ln\u2112,)\nfunction setparams!(k::SqExponentialARD{F}, ln\u2112::AbstractVector{F}) where F\n    diag\u03a3 = exp.(-2 .* ln\u2112)\n    copyto!(k.ln\u2112, ln\u2112)\n    copyto!(k.diag\u03a3, diag\u03a3)\n    k.dist = WeightedSqEuclidean(diag\u03a3)\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": "using TuringModels\n\nTuring.setadbackend(:reversediff)\n\n# Turing model\n@model m8_3(y) = begin\n    \u03b1 ~ Normal(1, 10)\n    \u03c3 ~ truncated(Cauchy(0, 1), 0, Inf)\n\n    y .~ Normal(\u03b1, \u03c3)\nend\n\ny = [-1,1]\n\n# Sample\n\nchns = sample(m8_3(y), NUTS(0.95), 1000);\n\n# Results rethinking\n\nm83rethinking = \"\n      mean   sd  5.5% 94.5% n_eff Rhat\nalpha 0.09 1.63 -2.13  2.39   959    1\nsigma 2.04 2.05  0.68  4.83  1090    1\n\";\n\n# Describe the posterior samples\n\ndescribe(chns)\n\n# End of `08/m8.3t.jl`\n", "meta": {"hexsha": "d643fedfbe60e4e7386c08d9780e4252c386dee2", "size": 482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/08/m8.3t.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/08/m8.3t.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/08/m8.3t.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": 15.0625, "max_line_length": 41, "alphanum_fraction": 0.6141078838, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7814666104597543}}
{"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\u03a9 = Circle(Point(0, 0), 1)\nmesh = generate_mesh(\u03a9, 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\u03b2 = 8\nR0 = 0.6\np = Expression(\"4*exp(-pow(beta, 2)*(pow(x[0], 2) + pow(x[1] - R0, 2)))\",\n               degree=1, beta=\u03b2, 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\u2032 = r / R\n    for _ = 1:n\n        retry_times = 0\n        new_point = rand_point()\n        while norm(new_point) + r\u2032 > 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\u2032 && retry_times < max_retry_times\n            retry_times += 1\n            new_point = rand_point()\n            while norm(new_point) + r\u2032 > 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\u2032\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\u2032 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\u03f5 = 0.05\n\u03c4 = 10\n\nchain = sample(ppca, HMC(\u03f5, \u03c4), 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": "### 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# \u2554\u2550\u2561 3dc78b1b-58d3-40eb-a1c5-a2fa58f15abf\nusing Distributions, StatsPlots, PlutoUI, StatsBase, KernelDensity\n\n# \u2554\u2550\u2561 535b43f0-2780-11ec-1444-d98d954f2508\nmd\"\"\" # Using the posterior distribution\n\nUsually samples from the posterior distribution are worked with rather than the disitrubtion itself, this for two reasons:\n1. Using the whole posterior distribution involves integral calculus, whereas working with samples is just data summary. For  complex problems with many parameters, these integrals become very complex whereas the data summary remains much easier.\n2. The most capable techniques for generating the posterior distribution, such as variants of the MCMC techniques, only produce samples. Using grid approximation will give you the whole posterior and will be very easy to work with but is impractical to work with for compelx problems.\n\"\"\"\n\n# \u2554\u2550\u2561 9993e805-7265-4c1d-b8a9-30c73f91bc37\nmd\"\"\" ## Sampling from a grid approximate posterior\n\nUsing the globe tossing model\n\"\"\"\n\n# \u2554\u2550\u2561 01914d0b-ba88-435f-8194-6acc5437c0e1\nmd\"\"\" Generate the grid approximated posterior distribution:\"\"\"\n\n# \u2554\u2550\u2561 a7667076-b719-46e6-8ef7-690019c176b6\nbegin \n\tN = 9\n\tS = 6\n\tn = 1001\n\tgrid = range(0, 1, length=n)\n\tprior = @. pdf(Uniform(0,1), grid)\n\tlikelihood = @. pdf(Binomial(N, grid), S)\n\tposterior = likelihood .* prior\n\tposterior /= sum(posterior)\nend;\n\n# \u2554\u2550\u2561 2e20bfcb-9633-4808-9f29-d3ec2ed472fe\nlet\n\tplot(grid, prior, st=:line, label=\"prior\", legend=:topright, xlims=(0,1.0), ylims=(0,2))\n\tplot!(grid, likelihood, st=:line, label=\"likelihood\")\n\tplot!(grid, posterior, st=:line, label=\"posterior\")\nend\n\n# \u2554\u2550\u2561 d63a4f5f-6274-40a6-90d9-b6933382e24d\nmd\"\"\" Sample 10,000 different parameter values ($P$) from the posterior:\"\"\"\n\n# \u2554\u2550\u2561 9356eb97-efae-47cb-a5a9-6676f00a5f1c\nn_samples = 10_000\n\n# \u2554\u2550\u2561 63fdfebf-d08f-438c-a69b-9db2200a61a6\nsamples = wsample(grid, posterior, n_samples)\n\n# \u2554\u2550\u2561 0072d892-1ede-4432-afca-9132c5695586\nmd\"\"\" See how the sample distribution approaches the actual posterior as the number of samples increases:\n\"\"\"\n\n# \u2554\u2550\u2561 d5d3b50b-01b9-4201-b01c-19cbe0c87bcf\n@bind _n Slider(10:10:2000, show_value=true)\n\n# \u2554\u2550\u2561 cf44ec9a-7c16-4ab4-b547-3b57263da109\nlet\n\tpost_true = Beta(1+S,(N-S)+1) # analytical density calculated from Beta dist.\n\tsamples = rand(post_true, _n)\n\tplot(post_true, lw=3, label=\"true\",title=\"posterior probability density\", xticks=0:0.2:1.0, xaxis=\"proportion of water\", legend=:topleft, xlims=(0.0,1.2), ylims=(0,4.0))\n\tdensity!(samples, lw=3, ls=:dash, label=\"sampled\")\nend\n\n# \u2554\u2550\u2561 f88a09e1-d3dc-4228-856e-f82725df693d\nmd\"\"\" Not very useful as the sampling has only approximated the posterior which we already had!\"\"\"\n\n# \u2554\u2550\u2561 6784239e-5595-471a-b4e8-348491e29e5e\nmd\"\"\" ## Sampling to summarise\nExactly how the posterior is summarised depends on the purpose, but common questions can be divided into three main groups:\n1. intervals of defined boundaries\n2. intervals of defined probability mass\n3. point estimates\n\"\"\"\n\n# \u2554\u2550\u2561 41688bf0-3188-4d31-897c-f864de97558f\nmd\"\"\" ### Intervals of defined boundaries\nFor example, what is the posterior probability that the proportion of water is below 0.5?\n\"\"\"\n\n# \u2554\u2550\u2561 9b4a897d-f0f2-42d9-a782-b47356065118\nmd\"\"\" For grid approximation it is simple:\"\"\"\n\n# \u2554\u2550\u2561 d9e160f8-e203-4f23-ad03-2c7bd3410c5b\nposterior[grid .< 0.5] |> sum\n\n# \u2554\u2550\u2561 3b2cca7a-3db1-4f08-af04-5d1df2955be4\nmd\"\"\"However, as has been said, grid approximation is not feasible for more complex problems whereas sampling from the posterior is:\"\"\"\n\n# \u2554\u2550\u2561 cc34c6a3-ae53-41f6-9934-dc789508883f\nsum(samples .< 0.5) / length(samples) \t# proportion of samples < 0.5\n\n# \u2554\u2550\u2561 0d0ed10d-78e3-4486-ab4e-bd0966be7cc5\nmd\"\"\" Similarly, how much of the distribution lies between two values, say 0.5 and 0.75:\"\"\"\n\n# \u2554\u2550\u2561 bf7367bc-2375-4942-abeb-7a756f5a1dc4\nsum(0.5 .< samples .< 0.75) / length(samples)\n\n# \u2554\u2550\u2561 1d838e46-53b6-45eb-ab56-c404773a6f94\nmd\"\"\" ### Intervals of defined mass\nWhat is commonly referred to as *confidence* intervals in Bayesian statistics (but will be called *compatibility* intervals here, as the confidence of the interval will depend on the model's ability to replicate the \"large\" world).\n\nThese intervals report two parameter values, between which will hold the specified probability mass.\n\"\"\"\n\n# \u2554\u2550\u2561 afedb578-664f-41bb-96f5-1b9f5eebfcfd\nmd\"\"\"The lower 80% of the distribution:\"\"\"\n\n# \u2554\u2550\u2561 5f549033-b925-438d-b56b-f5f18fa50613\nquantile(samples, 0.8)\n\n# \u2554\u2550\u2561 0da1daed-171f-4156-9247-21c2258d11c0\nmd\"\"\"Therefore 80% of the probability mass is contained between 0 and $(quantile(samples, 0.8)) \"\"\"\n\n# \u2554\u2550\u2561 661b6777-0991-4274-8443-d0f6f1e94051\nmd\"\"\"The middle 80%:\"\"\"\n\n# \u2554\u2550\u2561 f6c340ac-a923-4be5-b1ce-2a002d737cfc\nquantile(samples, [0.1, 0.9])\n\n# \u2554\u2550\u2561 a5beaffe-fa90-43a6-8efc-d9c0baa818e5\nmd\"\"\"These percentage intervals (PI) assume the distribution is symmetrical and give equal weight (and therefore chooses equal mass above and below the interval). Highest posterior density intervals (HPDI) provide the narrowest interval containing the specified amount of probability mass:\"\"\"\n\n# \u2554\u2550\u2561 8a037821-ec0f-4a4d-8292-21833f0c05f7\nfunction hpdi(x::Vector{T}; alpha=0.11) where {T<:Real}\n    n = length(x)\n    m = max(1, ceil(Int, alpha * n))\n\n    y = sort(x)\n    a = y[1:m]\n    b = y[(n - m + 1):n]\n    _, i = findmin(b - a)\n\n    return [a[i], b[i]]\nend\n\n# \u2554\u2550\u2561 3785acb9-4e2c-4299-a925-c6006ce46890\na,b = hpdi(samples)\n\n# \u2554\u2550\u2561 68884922-52cc-4a7f-8a9c-b0d5cde80875\nmd\"\"\"### Point estimates\nBayesian analysis gives you the entire probability distribution of possible parameter values so point estimates often pointless.\n\nChoice of estimate will depend on the question being answered.\n\"\"\"\n\n# \u2554\u2550\u2561 f594e927-1d66-4107-8fec-7f2b60617110\nmd\"\"\"The *maximum a posteriori* (MAP) estimate:\"\"\"\n\n# \u2554\u2550\u2561 7dfb3173-b7af-4546-bbcb-495cb7498a3b\nPmap = grid[argmax(posterior)]\n\n# \u2554\u2550\u2561 64635021-340b-4968-adc4-8ea3e9d7c5cf\nmd\"\"\"If you have samples from the posterior you can approximate this with the *mode* of the samples:\"\"\"\n\n# \u2554\u2550\u2561 82db866d-62af-412a-aeee-64940c64fa10\nbegin\n\td = Dict()\n\tfor x in samples\n\t\tp = round(x, digits=2)\n\t\tp in keys(d) ? d[p] += 1 : d[p] = 1\n\tend\n\tPmap_est = findmax(d)\nend\n\n# \u2554\u2550\u2561 fa055e68-a5d5-4ecd-970b-de20766e4a0a\nmd\"\"\"You could also report the *mean* or *median*:\"\"\"\n\n# \u2554\u2550\u2561 57a9acfa-6665-4936-8864-a54269e79a6b\nPmean = mean(samples)\n\n# \u2554\u2550\u2561 b5f28886-2239-4cb3-8248-00c4f32cfa91\nPmedian = median(samples)\n\n# \u2554\u2550\u2561 369febaa-8600-409e-9035-00e46483b70c\nbegin\n\tplot(grid, posterior, label=:none, legend=:topleft)\n\tvline!([Pmap], label=\"MAP\")\n\tvline!([Pmap_est], label=\"MAP estimate\")\n\tvline!([Pmean], label=\"mean\")\n\tvline!([Pmedian], label=\"median\")\nend\n\n# \u2554\u2550\u2561 ddf696bd-e6ac-48eb-b421-d5d778c2673b\nmd\"\"\" An alternative way would be to choose a loss function that tells you the loss associated with any particular estimate.\n\nFor example, using the distance from the true value:\n\n``loss = \\sum \\lvert x - P \\rvert``, where ``x`` is the estimate and ``P`` is the true value.\n\nThe true value will be unknown though, so weight the estimate by the posterior probability:\n\"\"\"\n\n# \u2554\u2550\u2561 b6b6fe45-e22f-4ca4-93f0-2ad1971d5339\nbegin\n\testimate = 0.5 # p=0.5\n\tposterior .* abs.(estimate .- grid) |> sum\nend\n\n# \u2554\u2550\u2561 455f6d2e-9abd-45ee-bd8d-83c3d92218ec\nmd\"\"\"Repeating over every possible ``P`` value and taking the minimum actually gives the median of the posterior:\"\"\"\n\n# \u2554\u2550\u2561 4ed753dc-44a8-48fc-82aa-80a95f40278b\nbegin\n\tloss = map(x -> sum(posterior.*abs.(x .- grid)), grid)\n\tplot(grid, loss, label=\"\", title=\"loss\", legend=:top)\n\tvline!([grid[argmin(loss)]], lw=2, label=\"minimum loss : $(round(grid[argmin(loss)], digits=3))\")\n\tvline!([Pmedian], lw=2, ls=:dash, label=\"median: $(round(Pmedian, digits=3))\")\n\tend\n\n# \u2554\u2550\u2561 02a8b42e-340e-4b2e-90f1-38db6f2aa03c\nmd\"\"\"Taking the square of the deviation (the quadratic loss) gives the mean.\n\nThe context in which you conduct your analysis may dictate a unique loss function, e.g. decision on whether to evacuate based on estimate of wind speed; the damage to property increases very steeply with wind speed, whereas ordering an evacuation when none needed will decrease slowly as wind speed falls below estimate - requiring a highly asymmetrical loss function.\n\"\"\"\n\n# \u2554\u2550\u2561 bdee2725-7fde-4548-afea-2b220cadf951\nmd\"\"\"## Sampling to simulate prediction\n\nA common use for samples of the posterior is to simulate the model's implied observations. Simluating implied obervations is useful for:\n\n- Model design: sampling from the prior to understand its implications and see what the model expects before the data.\n- After the model is updated with data, simulating implied observations and investigate model behaviour.\n- Software validation simulate observations under.\n- Research design and evaluating whether it will be effecttive or now. In a narrow sense, doing power analysis.\n- Forecasting and simulating new predictions.\n\"\"\"\n\n# \u2554\u2550\u2561 4c4b553d-4ba5-4fc4-9119-86f3b5a1849d\nmd\"\"\"### Generating dummy data\n\nUsing the globe tossing model, you can simulate the outcomes of the globe tossing under a value for the parameter ``P``:\n\"\"\"\n\n# \u2554\u2550\u2561 2b75ec16-9fd7-4d86-88e0-94240bdf9722\nmd\"\"\"Analytical likelihoods:\"\"\"\n\n# \u2554\u2550\u2561 288e009a-df1b-4c52-9bd6-1e7fc9040f43\n@. pdf(Binomial(9, 0.7), 0:9)\n\n# \u2554\u2550\u2561 3b35eaa3-e704-4ca7-a82b-ffa4bea195c8\nmd\"\"\"Estimated likelihoods from simulation:\"\"\"\n\n# \u2554\u2550\u2561 219e4064-12a6-4686-b181-8e99cc24cb38\nrand(Binomial(9, 0.7), 10_000) |> x -> counts(x) / 10_000\n\n# \u2554\u2550\u2561 2acc5752-5b3e-47d3-8e4c-f18d24bfa586\nbegin\n\tanalytical = @. pdf(Binomial(9, 0.7), 0:9)\n\testimated = rand(Binomial(9, 0.7), 10_000) |> x -> counts(x, 0:9) / 10_000\n\tgroupedbar([analytical estimated], labels=[\"true\" \"estimate\"], legend=:topleft, xaxis=\"number of water\", yaxis=\"proportion\")\nend\n\n# \u2554\u2550\u2561 5a2fa84f-457e-4839-81f2-633e92ee77a0\nmd\"\"\"### Posterior predicitive distribution\n\nThis is the distribution of possible predicitions from your model. It incorporates the uncertainty in the observation (if you know the true value of ``P`` you can't predict what will come next, unless ``P=0`` or ``P=1``), and uncertainty in the value of ``P``, i.e. the posterior distribution. The uncertainty in ``P`` is carried forward into the implied predictions by taking a weighted average of the predictions by the posterior distribution.\n\"\"\"\n\n# \u2554\u2550\u2561 a58923d4-090a-4c44-948d-90e163dc5a00\nmd\"\"\"Generating a prediction:\"\"\"\n\n# \u2554\u2550\u2561 d56fa818-a031-4fd5-a05c-f6fb1912be34\n@bind sampled_posterior Button(\"Sample a random value from the posterior\")\n\n# \u2554\u2550\u2561 b5d3fc06-1e64-4e47-9d46-a38a9c569a46\nlet\n\tsampled_posterior\n\tsampled_p = wsample(grid, posterior)\n\tsample = rand(Binomial(N, sampled_p), 10_000)\n\tproportions = counts(sample, 0:9) ./ 10_000\n\tp1 = plot(grid, posterior, label=\"\", title=\"posterior distribution\", xaxis=\"P\", legend=:none)\n\tvline!([sampled_p], ls=:dash, label=\"sampled P = $(round(sampled_p, digits=3))\")\n\tp2 = bar([0:9], proportions, title=\"sampling distribution for\\n P = $(round(sampled_p, digits=3))\", legend=:none, xticks=0:9, ylims=(0,0.5), xaxis=\"number of water\" )\n\t\n\tplot(p1,p2)\nend\n\n# \u2554\u2550\u2561 d91ad027-e086-4675-93fc-eec8f151191f\nmd\"\"\"Repeating over the whole posterior:\"\"\"\n\n# \u2554\u2550\u2561 7da185e4-9868-46ce-bac2-4e2ceda8f17b\nsimulated_samples = @. rand(Binomial(N,samples), n_samples)\n\n# \u2554\u2550\u2561 4e336b94-e9c2-47e3-8088-07eff6f02ecb\nmd\"\"\"**Taking values of P from `samples` means they will be in proportion to the posterior distribution, incorporating its uncertainty**\"\"\"\n\n# \u2554\u2550\u2561 c428d7c0-2073-4275-a50c-4a9d411b82f6\nsimulated_counts = map(x -> counts(x, 0:9), simulated_samples)\n\n# \u2554\u2550\u2561 35d9ec1c-f212-4d87-a70e-7d14f0956fed\nsimulated_proportions = sum(simulated_counts) ./ (n_samples*n_samples)\n\n# \u2554\u2550\u2561 2dc72b11-bdaf-4e03-869c-15abc6c5e048\nbar(0:9, simulated_proportions, title=\"posterior predictive distribution\", xticks=0:9, legend=:none, xaxis=\"number of water tosses\", yaxis=\"proportion of throws\")\n\n# \u2554\u2550\u2561 e50dd983-ac8a-4f6e-8b3f-e97b42b488e9\nmd\"\"\"## Practice problems\n\n### Hard\n#### Introduction\n\nThe data below indicates the gender (male=1, female=0) of reported first and second born children in 100 two-child families.\n\"\"\"\n\n# \u2554\u2550\u2561 995f788a-850b-4025-be00-02af762957de\nbirth1 = [1,0,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,1,1,0,1,0,1,1,1,0,1,1,1,1]\n\n# \u2554\u2550\u2561 b249b896-7165-45e4-b172-0e2ecc6b2b69\nbirth2 = [0,1,0,1,0,1,1,1,0,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0,1,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,0,0,0,1,1,1,0,0,0,0]\n\n# \u2554\u2550\u2561 84ff7ecc-97df-4532-b054-84520e8340f8\nmd\"\"\"##### 3H1\nUsing grid approximation, computer the posterior dsitribution of a birth being a boy. Assume uniform prior.\n\nWhich parameter value maximises the posterior probability?\n\n- The parameter of interest is the proportion of boys born ``P``.\n- Assume births are independent\n\n\"\"\"\n\n# \u2554\u2550\u2561 283d84a7-d8d8-419e-91f4-086e0e8a4b1d\nlet\n\tN = 200 \t# number of births, assumed independent\n\tNboys = sum(birth1) + sum(birth2) # number of boys\n\tn = 1001 \t# grid granularity\n\tgrid = range(0, 1, length=n)\n\tprior = @. pdf(Uniform(0,1), grid)\n\tlikelihood = @. pdf(Binomial(N, grid), Nboys)\n\tposterior = likelihood .* prior\n\tposterior /= sum(posterior)\n\tplot(grid, posterior, label=\"\", title=\"posterior distribution\")\n\tmap = grid[argmax(posterior)]\n\tvline!([map], label=\"MAP = $(round(map, digits=3))\")\nend\n\n# \u2554\u2550\u2561 9b155b0f-c605-46d0-9bd2-b69be3e21042\nmd\"\"\"##### 3H2\nDraw 10,000 random parameter values from the posterior dsitribution and use these to estimate the 50%, 89% and 97% HPDI.\n\"\"\"\n\n# \u2554\u2550\u2561 3c0ee869-a119-4f4c-89e9-9e57b2090505\nlet\n\t# the model\n\tN = 200 \t# number of births, assumed independent\n\tNboys = sum(birth1) + sum(birth2) # number of boys\n\tn = 101 \t# grid granularity\n\tgrid = range(0, 1, length=n)\n\tprior = @. pdf(Uniform(0,1), grid)\n\tlikelihood = @. pdf(Binomial(N, grid), Nboys)\n\tposterior = likelihood .* prior\n\tposterior /= sum(posterior)\n\tn_samples = 10_000\n\tsamples = wsample(grid, posterior, n_samples)\n\tde = kde(samples)\n\tplt = plot(de.x, de.density, label=\"\", lw=2, palette=palette([:gray], 10))\n\talpha = [0.5, 0.11, 0.03]\n\tas = Vector{Float64}(undef,3)\n\tbs = Vector{Float64}(undef, 3)\n\tfor i in 1:3\n\t\ta, b = hpdi(samples, alpha=alpha[i])\n\t\tas[i], bs[i] = a,b\n\t\tstart = argmin(abs.(a .- de.x))\n\t\tstop = argmin(abs.(b .- de.x))\n\t\t_x = de.x[start:stop]\n\t\t_y = de.density[start:stop]\n\t\tplot!(_x, zeros(length(_x)), fillrange=_y, fillalpha=0.3, label=\"\",linecolor=:white)\n\t\tplot!([a b; a b], [0 0; de.density[start] de.density[stop]], lw=3, lc=:black, label=\"\")\n\tend\n\tfor i in 1:3\n\t\ta, b = hpdi(samples, alpha=alpha[i])\n\t\tas[i], bs[i] = a,b\n\t\tstart = argmin(abs.(a .- de.x))\n\t\tstop = argmin(abs.(b .- de.x))\n\t\tplot!([a b; a b], [0 0; de.density[start] de.density[stop]], lw=3, lc=:black, label=[\"HPDI = $(1-alpha[i])\" \"\"])\n\tend\n\tplt\nend\n\n# \u2554\u2550\u2561 79cfd95f-0e98-4396-b5a3-35fabf5a6fd1\nmd\"\"\"##### 3H3\n\nSimulate 10,000, 200 births, giving the predictive psoterior distribution of the proportion of boys ``P``. Does the model fit the data well?\n\"\"\"\n\n# \u2554\u2550\u2561 382f2550-32b0-4ca8-92c5-3d04c29c5b83\nlet\n\t# the model\n\tN = 200 \t# number of births, assumed independent\n\tNboys = sum(birth1) + sum(birth2) # number of boys\n\tn = 101 \t# grid granularity\n\tgrid = range(0, 1, length=n)\n\tprior = @. pdf(Uniform(0,1), grid)\n\tlikelihood = @. pdf(Binomial(N, grid), Nboys)\n\tposterior = likelihood .* prior\n\tposterior /= sum(posterior)\n\t\n\t# sampled from the posterior\n\tn_samples = 1_000\n\tsamples = wsample(grid, posterior, n_samples)\n\n\t# simulated observations\n\tn_simulations = 10_000\n\tsimulated_samples = @. rand(Binomial(N, samples), n_simulations)\n\tsimulated_boys = sum(map(x -> counts(x, 0:N), simulated_samples)) ./ (n_simulations*n_samples)\n\tbar(0:N, simulated_boys, xticks=0:20:N, label=\"predicted distribution of P\")\n\tvline!([Nboys], lw=2, label=\"actual number of boys\")\nend\n\n# \u2554\u2550\u2561 b68063cd-d0d3-42a8-93e4-8eed50465d34\nmd\"\"\"##### 3H4\n\nNow compare 10,000 counts of boys from 100 simulated first borns only to the number of boys in the first births, `birth1`. How does the model compare now?\n\"\"\"\n\n# \u2554\u2550\u2561 88254a2d-af98-4c50-8d74-ca1a64245479\nlet\n\t# the model\n\tN = 200 \t# number of births, assumed independent\n\tNboys = sum(birth1) + sum(birth2)\n\tn = 101 \t# grid granularity\n\tgrid = range(0, 1, length=n)\n\tprior = @. pdf(Uniform(0,1), grid)\n\tlikelihood = @. pdf(Binomial(N, grid), Nboys)\n\tposterior = likelihood .* prior\n\tposterior /= sum(posterior) \n\t\n\t# sampled from posterior\n\tn_samples = 1_000\n\tsamples = wsample(grid, posterior, n_samples)\n\n\t# simulated observations\n\tn_simulations = 10_000\n\tsimulated_samples = @. rand(Binomial(100, samples), n_simulations)\n\tsimulated_boys = sum(map(x -> counts(x, 0:100), simulated_samples)) ./ (n_simulations*n_samples)\n\tbar(0:100, simulated_boys, xticks=0:20:100, label=\"predicted distribution of P\")\n\tvline!([sum(birth1)], lw=2, label=\"actual number of boys\")\nend\n\n# \u2554\u2550\u2561 bd502d36-7bf6-43a7-847a-8ce2986dd35e\nmd\"\"\"##### 3H5\n\nThe model assumes that sex of first and second borns are independent, check this assumption by focusing on second births that followed from female first borns. \n\nCompare 10,000 simulated counts of boys to only those second births that followed girls.\n\n\n\"\"\"\n\n\n# \u2554\u2550\u2561 dca7b0ac-6c94-469b-a438-645eb5d44e05\nlet\n\t# the model\n\tN = 200 \t# number of births, assumed independent\n\tNboys = sum(birth1) + sum(birth2) \n\tn = 101 \t# grid granularity\n\tgrid = range(0, 1, length=n)\n\tprior = @. pdf(Uniform(0,1), grid)\n\tlikelihood = @. pdf(Binomial(N, grid), Nboys)\n\tposterior = likelihood .* prior\n\tposterior /= sum(posterior) \n\t\n\t# sampled from posterior\n\tn_samples = 1_000\n\tsamples = wsample(grid, posterior, n_samples)\n\n\t# simulated observations\n\tn_simulations = 10_000\n\tn_girls1 = sum(birth1 .== 0) # number of first born girls\n\tsimulated_samples = @. rand(Binomial(n_girls1, samples), n_simulations)\n\tsimulated_boys2 = sum(map(x -> counts(x, 0:n_girls1), simulated_samples)) ./ (n_simulations*n_samples)\n\tbar(0:n_girls1, simulated_boys2, label=\"simulated boys\")\n\t\n\t# actual observations\n\tn_boys2 = sum(birth2[birth1 .== 0])\n\tvline!([n_boys2], lw=2, label=\"observed boys\")\nend\n\n# \u2554\u2550\u2561 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nKernelDensity = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nStatsBase = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\n\n[compat]\nDistributions = \"~0.25.18\"\nKernelDensity = \"~0.6.3\"\nPlutoUI = \"~0.7.15\"\nStatsBase = \"~0.33.10\"\nStatsPlots = \"~0.14.28\"\n\"\"\"\n\n# \u2554\u2550\u2561 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[[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[[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[[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 = \"a325370b9dd0e6bf5656a6f1a7ae80755f8ccc46\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.7.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 = \"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[[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[[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[[Distributions]]\ndeps = [\"ChainRulesCore\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\"]\ngit-tree-sha1 = \"ff7890c74e2eaffbc0b3741811e3816e64b6343d\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.18\"\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[[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[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"29890dfbc427afa59598b8cfcc10034719bd7744\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.6\"\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 = \"4c8c0719591e108a83fb933ac39e32731c7850ff\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.60.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[[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[[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[[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[[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[[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[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"8d958ff1854b166003238fe191ec34b9d592860a\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.8.0\"\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[[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[[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[[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[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"a8709b968a1ea6abc2dc1967cb1db6ac9a00dfb6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.5\"\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 = \"6841db754bd01a91d281370d9a0f8787e220ae08\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.4\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"633f8a37c47982bff23461db0076a33787b17ecd\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.15\"\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[[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[[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[[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[[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 = \"793793f1df98e3d7d554b65a107e9c9a6399a6ed\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.7.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 = \"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 = \"95072ef1a22b057b1e80f73c2a89ad238ae4cfff\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.12\"\n\n[[StatsPlots]]\ndeps = [\"Clustering\", \"DataStructures\", \"DataValues\", \"Distributions\", \"Interpolations\", \"KernelDensity\", \"LinearAlgebra\", \"MultivariateStats\", \"Observables\", \"Plots\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"StatsBase\", \"TableOperations\", \"Tables\", \"Widgets\"]\ngit-tree-sha1 = \"eb007bb78d8a46ab98cd14188e3cec139a4476cf\"\nuuid = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nversion = \"0.14.28\"\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[[TableOperations]]\ndeps = [\"SentinelArrays\", \"Tables\", \"Test\"]\ngit-tree-sha1 = \"019acfd5a4a6c5f0f38de69f2ff7ed527f1881da\"\nuuid = \"ab02a1b2-a7df-11e8-156e-fb1833f50b87\"\nversion = \"1.1.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[[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[[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 = \"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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500535b43f0-2780-11ec-1444-d98d954f2508\n# \u255f\u25009993e805-7265-4c1d-b8a9-30c73f91bc37\n# \u2560\u25503dc78b1b-58d3-40eb-a1c5-a2fa58f15abf\n# \u255f\u250001914d0b-ba88-435f-8194-6acc5437c0e1\n# \u2560\u2550a7667076-b719-46e6-8ef7-690019c176b6\n# \u255f\u25002e20bfcb-9633-4808-9f29-d3ec2ed472fe\n# \u255f\u2500d63a4f5f-6274-40a6-90d9-b6933382e24d\n# \u255f\u25009356eb97-efae-47cb-a5a9-6676f00a5f1c\n# \u2560\u255063fdfebf-d08f-438c-a69b-9db2200a61a6\n# \u255f\u25000072d892-1ede-4432-afca-9132c5695586\n# \u255f\u2500d5d3b50b-01b9-4201-b01c-19cbe0c87bcf\n# \u255f\u2500cf44ec9a-7c16-4ab4-b547-3b57263da109\n# \u255f\u2500f88a09e1-d3dc-4228-856e-f82725df693d\n# \u255f\u25006784239e-5595-471a-b4e8-348491e29e5e\n# \u255f\u250041688bf0-3188-4d31-897c-f864de97558f\n# \u255f\u25009b4a897d-f0f2-42d9-a782-b47356065118\n# \u2560\u2550d9e160f8-e203-4f23-ad03-2c7bd3410c5b\n# \u255f\u25003b2cca7a-3db1-4f08-af04-5d1df2955be4\n# \u2560\u2550cc34c6a3-ae53-41f6-9934-dc789508883f\n# \u255f\u25000d0ed10d-78e3-4486-ab4e-bd0966be7cc5\n# \u2560\u2550bf7367bc-2375-4942-abeb-7a756f5a1dc4\n# \u255f\u25001d838e46-53b6-45eb-ab56-c404773a6f94\n# \u255f\u2500afedb578-664f-41bb-96f5-1b9f5eebfcfd\n# \u2560\u25505f549033-b925-438d-b56b-f5f18fa50613\n# \u255f\u25000da1daed-171f-4156-9247-21c2258d11c0\n# \u255f\u2500661b6777-0991-4274-8443-d0f6f1e94051\n# \u2560\u2550f6c340ac-a923-4be5-b1ce-2a002d737cfc\n# \u255f\u2500a5beaffe-fa90-43a6-8efc-d9c0baa818e5\n# \u2560\u25508a037821-ec0f-4a4d-8292-21833f0c05f7\n# \u2560\u25503785acb9-4e2c-4299-a925-c6006ce46890\n# \u255f\u250068884922-52cc-4a7f-8a9c-b0d5cde80875\n# \u255f\u2500f594e927-1d66-4107-8fec-7f2b60617110\n# \u255f\u25007dfb3173-b7af-4546-bbcb-495cb7498a3b\n# \u255f\u250064635021-340b-4968-adc4-8ea3e9d7c5cf\n# \u2560\u255082db866d-62af-412a-aeee-64940c64fa10\n# \u255f\u2500fa055e68-a5d5-4ecd-970b-de20766e4a0a\n# \u255f\u250057a9acfa-6665-4936-8864-a54269e79a6b\n# \u255f\u2500b5f28886-2239-4cb3-8248-00c4f32cfa91\n# \u255f\u2500369febaa-8600-409e-9035-00e46483b70c\n# \u255f\u2500ddf696bd-e6ac-48eb-b421-d5d778c2673b\n# \u2560\u2550b6b6fe45-e22f-4ca4-93f0-2ad1971d5339\n# \u255f\u2500455f6d2e-9abd-45ee-bd8d-83c3d92218ec\n# \u255f\u25004ed753dc-44a8-48fc-82aa-80a95f40278b\n# \u255f\u250002a8b42e-340e-4b2e-90f1-38db6f2aa03c\n# \u255f\u2500bdee2725-7fde-4548-afea-2b220cadf951\n# \u255f\u25004c4b553d-4ba5-4fc4-9119-86f3b5a1849d\n# \u255f\u25002b75ec16-9fd7-4d86-88e0-94240bdf9722\n# \u2560\u2550288e009a-df1b-4c52-9bd6-1e7fc9040f43\n# \u255f\u25003b35eaa3-e704-4ca7-a82b-ffa4bea195c8\n# \u2560\u2550219e4064-12a6-4686-b181-8e99cc24cb38\n# \u255f\u25002acc5752-5b3e-47d3-8e4c-f18d24bfa586\n# \u255f\u25005a2fa84f-457e-4839-81f2-633e92ee77a0\n# \u255f\u2500a58923d4-090a-4c44-948d-90e163dc5a00\n# \u255f\u2500d56fa818-a031-4fd5-a05c-f6fb1912be34\n# \u255f\u2500b5d3fc06-1e64-4e47-9d46-a38a9c569a46\n# \u255f\u2500d91ad027-e086-4675-93fc-eec8f151191f\n# \u2560\u25507da185e4-9868-46ce-bac2-4e2ceda8f17b\n# \u255f\u25004e336b94-e9c2-47e3-8088-07eff6f02ecb\n# \u2560\u2550c428d7c0-2073-4275-a50c-4a9d411b82f6\n# \u2560\u255035d9ec1c-f212-4d87-a70e-7d14f0956fed\n# \u255f\u25002dc72b11-bdaf-4e03-869c-15abc6c5e048\n# \u255f\u2500e50dd983-ac8a-4f6e-8b3f-e97b42b488e9\n# \u255f\u2500995f788a-850b-4025-be00-02af762957de\n# \u255f\u2500b249b896-7165-45e4-b172-0e2ecc6b2b69\n# \u255f\u250084ff7ecc-97df-4532-b054-84520e8340f8\n# \u2560\u2550283d84a7-d8d8-419e-91f4-086e0e8a4b1d\n# \u255f\u25009b155b0f-c605-46d0-9bd2-b69be3e21042\n# \u2560\u25503c0ee869-a119-4f4c-89e9-9e57b2090505\n# \u255f\u250079cfd95f-0e98-4396-b5a3-35fabf5a6fd1\n# \u2560\u2550382f2550-32b0-4ca8-92c5-3d04c29c5b83\n# \u255f\u2500b68063cd-d0d3-42a8-93e4-8eed50465d34\n# \u2560\u255088254a2d-af98-4c50-8d74-ca1a64245479\n# \u255f\u2500bd502d36-7bf6-43a7-847a-8ce2986dd35e\n# \u2560\u2550dca7b0ac-6c94-469b-a438-645eb5d44e05\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "aeaa8fc35b28a8c3f03be2e3d86c8b6ca80d1f4f", "size": 58114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter_03.jl", "max_stars_repo_name": "TomRottier/statistical-rethinking", "max_stars_repo_head_hexsha": "3d5cfab3ec4f45797755f87e28fc5aa8feb640f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter_03.jl", "max_issues_repo_name": "TomRottier/statistical-rethinking", "max_issues_repo_head_hexsha": "3d5cfab3ec4f45797755f87e28fc5aa8feb640f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter_03.jl", "max_forks_repo_name": "TomRottier/statistical-rethinking", "max_forks_repo_head_hexsha": "3d5cfab3ec4f45797755f87e28fc5aa8feb640f5", "max_forks_repo_licenses": ["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.2419648272, "max_line_length": 445, "alphanum_fraction": 0.7321299515, "num_tokens": 25773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.7814472120280782}}
{"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\u00e8 Giordano.\n#\n# Maintainer: Mos\u00e8 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|\u00b2 / (|S|\u00b2 + |N|\u00b2)\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|\u00b2 + |N/S|\u00b2)\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": "@testset \"Laguerre integration\" begin\n    # forward transform\n    # this is just Lnh for n=2.\n    # need to get a2 = 1 and other coeffs 0.\n    f(x) = (x^2 - 4 * x + 2) * exp(-x / 2) / 2\n    N = 3\n    an = laguerre_transform(f, N)\n    anexact = [0; 0; 1; 0]\n    @test all(isapprox.(an, anexact, atol = 1e-8))\n\n    # now inverse transform\n    x = 0:0.1:10 |> collect\n    fv = inverse_laguerre_transform(an, x)\n    @test norm(fv - f.(x)) < 1e-10\n\n    # test integration using Laguerre-Gauss-Radau quadrature.\n    f1(x) = sin(x)^2 * exp(-x)  # -> 2/5\n    N = 30\n    @test isapprox(LGRquad(f1, N), 2 / 5, atol = 1e-3, rtol = 1e-4)\nend", "meta": {"hexsha": "1e170b2feebd1167fa51917bc7020be8ef29982e", "size": 629, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_integration.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": "test/test_integration.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": "test/test_integration.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": 31.45, "max_line_length": 67, "alphanum_fraction": 0.5659777424, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7814175725216121}}
{"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\u00d72 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 \u03a6(z, \u03bb, w0)\n    zR = pi*w0^2/\u03bb\n    return atan(z/zR)\nend\n\nfunction w(z, \u03bb, w0)\n    zR = pi*w0^2/\u03bb\n    return w0*sqrt(1+(z/zR)^2)\nend\n\nfunction R(z, \u03bb, w0)\n    zR = pi*w0^2/\u03bb\n    return z+zR^2/z\nend\n\nfunction q(z, \u03bb, w0)\n    zR = pi*w0^2/\u03bb\n    return z + zR*1im\nend\n\nfunction \u03c8(z, p, m, \u03bb, w0)\n    zR = pi*w0^2/\u03bb\n    N = abs(m) + 2p\n    return (N+1)*atan(z/zR)\nend\n\n\u03b4(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_\u03b8(x, y)\n    r = sqrt.(x.^2 .+ y'.^2)\n    \u03b8 = atan.(y', x)\n    return r, \u03b8\nend\n\n\n#Laguerre-Gaussian modes\nfunction LG(r, \u03b8, z, p, m; \u03bb=800e-9, w0=2e-2)\n    k = 2pi/\u03bb\n    _1 = @. sqrt(2*factorial(p)/(pi*factorial(abs(m)+p)))\n    _2 = @. w0/w(z, \u03bb, w0)*(sqrt(2)*r/w(z, \u03bb, w0))^abs(m)\n    _3 = @. exp(-r^2/w(z, \u03bb, w0)^2)\n    _4 = @. gLaguerre(2r^2/w(z, \u03bb, w0)^2,p,abs(m))\n    _5 = @. exp(-1im*k*r^2/(2*R(z, \u03bb, w0))-1im*\u03b8*m)\n    _6 = @. exp(1im*\u03c8(z, p, m, \u03bb, 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; \u03bb=800e-9, w0=2e-2)\n    k = 2pi/\u03bb\n    r, \u03b8 = r_and_\u03b8(x, y)\n    # outer product\n    _1 =  w0/w(z, \u03bb, w0).*H.(sqrt(2)*x/w(z, \u03bb, w0), l).*H.(sqrt(2)*y/w(z, \u03bb, w0), m)'\n    _2 = @. exp(-(r^2)/w(z, \u03bb, w0)^2)\n    _3 = @. exp(-1im*k*(r^2)/(2*R(z, \u03bb, w0)))\n    _4 = @. exp(1im*\u03c8(z, l, m, \u03bb, 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, \u03b8 = r_and_\u03b8(x, y)\n\n# heatmap(x,y,real.(LG(r,\u03b8,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    \u0394x::DT\n    xgrid::Vector{DT}\n    cells::Vector{DT}\n    L::DT\n    \u03c1::Vector{DT}\n    \u03d5::Vector{DT}\n\n    function PoissonSolverFFT{DT}(nx::Int, L::DT) where {DT}\n        \u0394x = L/(nx+1)\n        xgrid = LinRange(\u0394x/2, L-\u0394x/2, nx)\n        cells = LinRange(0, L, nx+1)\n        new(nx, \u0394x, 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.\u03c1 .= h.weights ./ length(x)\n    \u03c1\u0302 = rfft(p.\u03c1)\n    k\u00b2 = [(i-1)^2 for i in eachindex(\u03c1\u0302)]\n    \u03d5\u0302 = - \u03c1\u0302 ./ k\u00b2\n    \u03d5\u0302[1] = 0\n    p.\u03d5 .= irfft(\u03d5\u0302, length(p.\u03c1))\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.\u0394x)\n    i2 = mod( ceil(Int, y / p.\u0394x) - 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) \u2264 abs(p.xgrid[i2] - x) ? i1 : i2)\nend\n\n\nfunction eval_density(p::PoissonSolverFFT{DT}, x::DT) where {DT}\n    p.\u03c1[get_index(p, x)]\nend\n\nfunction eval_potential(p::PoissonSolverFFT{DT}, x::DT) where {DT}\n    p.\u03d5[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.\u03d5[i2] - p.\u03d5[i1]) / p.\u0394x\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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.20\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f9da4af4-3afb-11eb-3be6-c136b5d61c81\nbegin\n\tmcmcSamples = sampler(posteriorUpToK,foldedNormalPDF,foldedNormalRV)\n\tText(\"MCMC Bayes Estimate: $(mean(mcmcSamples))\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.20\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u2550f9da18ea-3afb-11eb-1c03-eb97ca5c6918\n# \u2560\u2550f9da4af4-3afb-11eb-3be6-c136b5d61c81\n# \u2560\u2550f9dae8a6-3afb-11eb-3b01-15befda98071\n# \u255f\u2500475ff888-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\u2113::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\u2113::F\n    ln\u03b1::F\n    \n    \u03b1::F\n    two\u03b1\u2113\u00b2::F\n    function RationalQuadratic(\n        dist::SqEuclidean,\n        ln\u2113::AbstractFloat,\n        ln\u03b1::AbstractFloat\n    )\n        ln\u2113, ln\u03b1 = promote(ln\u2113, ln\u03b1)\n        new{typeof(ln\u2113)}(\n            dist,\n            ln\u2113,\n            ln\u03b1,\n            exp(ln\u03b1),\n            exp(2 * ln\u2113 + ln\u03b1 + float(logtwo)),\n        )\n    end\nend\n\nRationalQuadratic(ln\u2113::AbstractFloat, ln\u03b1::AbstractFloat) =\n    RationalQuadratic(SqEuclidean(), ln\u2113, ln\u03b1)\n\n@inline (k::RationalQuadratic)(\u03c4::AbstractFloat) = (1 + \u03c4 / k.two\u03b1\u2113\u00b2)^(-k.\u03b1)\n\nnumparams(::RationalQuadratic) = (1, 1)\nparamtypes(::RationalQuadratic{F}) where F = (F, F)\nparams(k::RationalQuadratic) = (ln\u2113 = k.ln\u2113, ln\u03b1 = k.ln\u03b1)\nfunction setparams!(k::RationalQuadratic{F}, ln\u2113::F, ln\u03b1::F) where F\n    k.ln\u2113 = ln\u2113\n    k.ln\u03b1 = ln\u03b1\n    k.\u03b1 = exp(ln\u03b1)\n    k.two\u03b1\u2113\u00b2 = exp(2 * ln\u2113 + ln\u03b1 + 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 \u03bc = 4*pi*1e-7\n\nfunction Z_f(freqs, \u03c1, h, irxlayer=1)\n    n = length(\u03c1)\n    @assert length(h) == n - 1\n    [Z_f(f, \u03c1, h, n, irxlayer) for f in freqs]   \nend    \n\nfunction Z_f(f, \u03c1, h, n, irxlayer)\n    # from Kaufman & Keller 1981 \n    \u03c9 = 2pi*f\n    k = sqrt(im*\u03c9*\u03bc/\u03c1[end])\n    Z = \u03c9*\u03bc/k\n    for i = n-1:-1:irxlayer\n        k = sqrt(im*\u03c9*\u03bc/\u03c1[i])\n        \u03c9\u03bc_over_k = \u03c9*\u03bc/k\n        Z = \u03c9\u03bc_over_k*coth(-im*k*h[i] + acoth(Z/\u03c9\u03bc_over_k))\n    end\n    Z    \nend\n\n\u03c1app(freqs, Z) = abs2.(Z)./(2pi*freqs*\u03bc)\n\nphase(Z) = rad2deg.(angle.(Z))\n\nfunction twolayer_ex(h1, \u03c11, \u03c12::AbstractArray; ntimesperdecade=10)\n    X = 10 .^(-1:1/ntimesperdecade:5) # \u03bb\u2081/h\u2081\n    T = ((h1*X/(2pi*503)).^2)/\u03c11\n    Z = [twolayer_ex(h1, \u03c11, rho2, T) for rho2 in \u03c12]\n    fig, ax = plt.subplots(2,1, sharex=true, figsize=(6,10))\n    for ZZ in Z\n        ax[1].loglog(X, \u03c1app(1 ./T, ZZ)/\u03c11)\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, \u03c11, \u03c12::S, T) where S<:Number\n    \u03c1 = [\u03c11, \u03c12]\n    Z_f(1 ./T, \u03c1, [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    \u03c1\u2090 = \u03c1app(f, Z)\n    \u03d5  = 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.(\u03c1\u2090))\n        ax[iaxis+1].semilogx(abcissa, \u03d5)\n    else\n        ax[iaxis].semilogx(abcissa, log10.(\u03c1\u2090), alpha=modelalpha, color=lcolor)\n        ax[iaxis+1].semilogx(abcissa, \u03d5, 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, \u03c1, 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, \u03c1, z, fig, showfreq=showfreq, gridalpha=gridalpha, logscaledepth=logscaledepth, irxlayer=irxlayer)\n    fig\nend\n\nfunction plotmodelcurve(T, \u03c1, 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, \u03c1, h, irxlayer)\n    ax = fig.axes\n    zlast = diff(z)[end] + z[end]\n    if lcolor == \"nocolor\"\n        ax[1].step([\u03c1; \u03c1[end]], [z; zlast])\n    else\n        ax[1].step([\u03c1; \u03c1[end]], [z; zlast], color=lcolor, alpha=modelalpha)\n    end      \n    ax[1].set_xlabel(\"\u03c1 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\u2080`: initial time\n* `q\u2080`: initial condition for dynamical variable ``q``\n* `p\u2080`: 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": "using SampleProjectTest\nusing SampleProject\nusing Test\n\n@testset \"Sum of series\" begin\n    @bench @testset \"Geometric series\" begin\n        r = 0.9999\n        s = geometric_series(1, r, 1_000_000)\n        @test isapprox(s, 1 / (1 - r); atol = 1e-6)\n    end\n\n    @testset \"Pi\" begin\n        @bench @testset \"Gregory\u2013Leibniz\" begin\n            s = pi_gregory_leibniz(1_000_000)\n            @test isapprox(s, \u03c0; atol = 1e-6)\n        end\n\n        @bench @testset \"Nilakantha\" begin\n            s = pi_nilakantha(100)\n            @test isapprox(s, \u03c0; atol = 1e-6)\n        end\n    end\nend\n", "meta": {"hexsha": "8e8f9a3e7419010ab276d761a97797a141a21ec7", "size": 583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/series_test.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": "test/series_test.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": "test/series_test.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.2916666667, "max_line_length": 51, "alphanum_fraction": 0.5746140652, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7812804082966237}}
{"text": "@testset \"cosine\" begin\n    rng = MersenneTwister(123456)\n    x = rand(rng) * 2\n    v1 = rand(rng, 3)\n    v2 = rand(rng, 3)\n\n    k = CosineKernel()\n    @test eltype(k) == Any\n    @test kappa(k, 1.0) \u2248 -1.0 atol=1e-5\n    @test kappa(k, 2.0) \u2248 1.0 atol=1e-5\n    @test kappa(k, 1.5) \u2248 0.0 atol=1e-5\n    @test kappa(k, x) \u2248 cospi(x) atol=1e-5\n    @test k(v1, v2) \u2248 cospi(sqrt(sum(abs2.(v1 - v2)))) atol=1e-5\n    @test repr(k) == \"Cosine Kernel\"\n\n    # Standardised tests.\n    TestUtils.test_interface(k, Vector{Float64})\n    test_ADs(CosineKernel)\nend\n", "meta": {"hexsha": "0c6792767cae7ada696f3b42f525f3a946b982ad", "size": 548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/cosine.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": "test/basekernels/cosine.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": "test/basekernels/cosine.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.4, "max_line_length": 64, "alphanum_fraction": 0.5821167883, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7812804022891167}}
{"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:\u03c0/100:10pi) +  cos.( 5*(0.0:\u03c0/100:10pi))+  cos.( 20*(0.0:\u03c0/100:10pi))\r\n\u03c6\u2081 = SIFT(sig)\r\nplot(sig)\r\nplot!(\u03c6\u2081)\r\n\u03c6\u2082 = SIFT(sig-\u03c6\u2081)\r\nplot!(\u03c6\u2082)\r\nplot!(sig-\u03c6\u2081-\u03c6\u2082)\r\n\r\n\r\n#-------------------------------------------\r\n\r\nsig = cos.(0.0:\u03c0/100:10pi) +  cos.( 5*(0.0:\u03c0/100:10pi))+  cos.( 20*(0.0:\u03c0/100:10pi))\r\nIMF = EMD(sig)\r\nplot(sig)\r\nplot!(IMF)\r\n\r\n#-------------------------------------------\r\n\r\nsig = exp.( 1im*(0.0:\u03c0/100:10pi)) +  exp.( 5im*(0.0:\u03c0/100:10pi)) +  exp.( 20im*(0.0:\u03c0/100:10pi))\r\n\u03c6\u2081 = \u2102SIFT(sig)\r\nplot(real(sig))\r\nplot!(real(\u03c6\u2081))\r\n\u03c6\u2082 = \u2102SIFT(sig-\u03c6\u2081)\r\nplot!(real(\u03c6\u2082))\r\nplot!(real(sig-\u03c6\u2081-\u03c6\u2082))\r\n\r\n#-------------------------------------------\r\n\r\nsig = exp.( 1im*(0.0:\u03c0/100:10pi)) +  exp.( 5im*(0.0:\u03c0/100:10pi)) +  exp.( 20im*(0.0:\u03c0/100:10pi))\r\nIMF = \u2102EMD(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": "## Packages\nusing CSV, DataFrames, Plots, Distributions, Random, Optim, LinearAlgebra\n\n#### Question 1:\n\n## Load the data\nYdata = CSV.read(\"data/realGDP.csv\", DataFrame, types = [String, Float64]) # Specify types of each column\nnames(Ydata) # Get column names\nrename!(Ydata, \"    Gross domestic product \" => :GDP) # Rename GDP\n\n## Calculate growth rate of GDP\nnum_data = size(Ydata)[1];\nGDP_growth = repeat([reshape([0.0], 1, 1)], num_data);\n[GDP_growth[i] = [100.0] * ((reshape([log(Ydata[i, 2])], 1, 1)) - (reshape([log(Ydata[i - 1, 2])], 1, 1))) for i in 2:num_data]\nvec_GDP_growth = [GDP_growth[i][1, 1] for i in 1:num_data]\n## Plot the growth rate\nplot(Ydata[:, 1], vec_GDP_growth, xlabel = \"Year\", label = \"GDP Growth (%)\")\nsavefig(\"figs/GDP_growth.png\")\n\n#-----------------------------------------------------------------------------------------------------------------#\n\n#### Question 2\n\nRandom.seed!(456)\n\n# Parameters\n\u03c3_\u03f5 = 0.5;\n\u03c3_\u03bd = 0.5;\nn = length(GDP_growth);\n\n# Getting Matrices to apply kalman filter\nT = reshape([1.0], 1, 1);\nZ = reshape([1.0], 1, 1);\nQ = reshape([\u03c3_\u03bd^2], 1, 1);\nH = reshape([\u03c3_\u03f5^2], 1, 1);\n\u03bc0 = reshape([2.0], 1, 1);\n\n# Applying Kalman Filter on real data\ninclude(\"KalmanFilter.jl\")\n\u03bchat, v, yhat, P, F, G, K  = KalmanFilter(T, Z, Q, H, n, \u03bc0, GDP_growth)\n\n# Generate a \"test\" sample, 100 data points\nsample_size = 100;\n\n\u03bc_1 = 2.0;\n\u03bc_sim = repeat([reshape([\u03bc_1], 1, 1)], sample_size)\n[\u03bc_sim[i] = \u03bc_sim[i-1] + [\u03c3_\u03bd * rand(Normal(0.0, 1.0))] for i in 2:sample_size];\nsample_y = repeat([zeros(size(GDP_growth[1]))], sample_size);\n[sample_y[i] = \u03bc_sim[i] + [\u03c3_\u03bd * rand(Normal(0.0, 1.0))] for i in 1:sample_size];\n\n# Applying Kalman Filter on simulated data\n\u03bchat_sim  = KalmanFilter(T, Z, Q, H, sample_size, \u03bc0, sample_y)[1]\n\u03c3_\u03bc = sqrt.([KalmanFilter(T, Z, Q, H, sample_size, \u03bc0, sample_y)[4][i + 1][1, 1] for i in 1:sample_size - 1]);\n\n\n# Plot\nvec_\u03bc_sim = [\u03bc_sim[i][1, 1] for i in 1:sample_size]\nvec_\u03bchat_sim = [\u03bchat_sim[i + 1][1, 1] for i in 1:sample_size - 1]\n\u03bchat_sim_UCI = vec_\u03bchat_sim + 2 * \u03c3_\u03bc;\n\u03bchat_sim_LCI = vec_\u03bchat_sim - 2 * \u03c3_\u03bc;\n\nplot(vec_\u03bc_sim[1:end - 1], xlabel = \"time\", ylabel = \"\u03bc\", label = \"Simulated values\", legend=:topleft)\nplot!(vec_\u03bchat_sim, label = \"Estimated \u03bc from Kalman Filter\")\nplot!(\u03bchat_sim_UCI, label = \"\u03bc + 2*\u03c3\")\nplot!(\u03bchat_sim_LCI, label = \"\u03bc - 2*\u03c3\")\nsavefig(\"figs/Q2b.png\")\n\n#-----------------------------------------------------------------------------------------------------------------#\n\n#### Question 3\n## Writing the likelhood function\nfunction log_L_GDP(\u03b8::Vector)  # \u03b8 = [log(\u03c3_\u03f5), log(\u03c3_\u03bd)]\n    \u03c3_\u03bd1 = exp(\u03b8[1])\n    \u03c3_\u03f51 = exp(\u03b8[2])\n    Q1 = reshape([\u03c3_\u03bd1^2], 1, 1)\n    H1 = reshape([\u03c3_\u03f51^2], 1, 1)\n\n    v1 = [KalmanFilter(T, Z, Q1, H1, n, \u03bc0, GDP_growth)[2][i][1] for i in 1:n]\n    F1 = [KalmanFilter(T, Z, Q1, H1, n, \u03bc0, GDP_growth)[5][i][1] for i in 1:n]\n    Ft = abs.(det.(vec(F1))) # How about this?\n\n    return sum([-0.5 * log(Ft[i]) - 0.5 * v1[i]' * inv(Ft[i]) * v1[i] for i in 1:n])\nend\n\n\n## Optimization\nres = optimize(\u03b8 -> -log_L_GDP(\u03b8), [-2.0, -2.0])\n\u03c3_\u03bd_hat, \u03c3_\u03f5_hat = exp(Optim.minimizer(res)[1]), exp(Optim.minimizer(res)[2]) # (0.1717, 2.2575)\n\n## Plotting\n\u03c3_\u03bd = 0.1717;\n\u03c3_\u03f5 = 2.2575;\n\nn = length(GDP_growth);\n\nT = reshape([1.0], 1, 1);\nZ = reshape([1.0], 1, 1);\nQ = reshape([\u03c3_\u03bd^2], 1, 1);\nH = reshape([\u03c3_\u03f5^2], 1, 1);\n\u03bc0 = reshape([2.0], 1, 1);\n\n\u03bc_hat  = KalmanFilter(T, Z, Q, H, n, \u03bc0, GDP_growth)[1]\nvec_\u03bc_hat = [\u03bc_hat[i][1, 1] for i in 1:n]\n\nplot(Ydata[:, 1], vec_\u03bc_hat, xlabel = \"Year\", label = \"Hidden State\")\nsavefig(\"figs/Q3b\")\n\n#-----------------------------------------------------------------------------------------------------------------#\n\n#### Question 4", "meta": {"hexsha": "bea71814bbb12480c02af9f0960524a0c6d7ae2f", "size": 3658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Anmol/PS1/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/PS1/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/PS1/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": 33.2545454545, "max_line_length": 127, "alphanum_fraction": 0.5661563696, "num_tokens": 1375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.853912754810561, "lm_q1q2_score": 0.7812455948568684}}
{"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 \u2208 (: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 \u2208 (: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 ``\u2200p\\! \u2208\\! ps\\; e \u2265_{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 ``\u2200p\\! \u2208\\! ps\\; n \u2265_{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 ``\u2200p\\! \u2208\\! ps\\; n \u2265_{yx} p``, and the second\npoint ``s`` is such that ``\u2200p\\! \u2208\\! ps\\; s \u2264_{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 ``\u2200p\\! \u2208\\! ps\\; n \u2265_{yx} p``, the second\npoint ``s`` is such that ``\u2200p\\! \u2208\\! ps\\; s \u2264_{yx} p``, the third point ``w`` is\nsuch that ``\u2200p\\! \u2208\\! ps\\; w \u2264_{xy} p``, and the fourth point ``e`` is such that\n``\u2200p\\! \u2208\\! ps\\; e \u2265_{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 ``\u2200p\\! \u2208\\! ps\\; s \u2264_{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 ``\u2200p\\! \u2208\\! ps\\; w \u2264_{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 ``\u2200p\\! \u2208\\! ps\\; w \u2264_{xy} p``, and the second\npoint ``e`` is such that ``\u2200p\\! \u2208\\! ps\\; e \u2265_{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 \u2208 (: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": "\"\"\"\n    unitcircle(ndirection; half = false, normal = [0, 0, 1])\n\nCreate `ndirection` directions unformly distributed on the unit circle defined by `normal`.\n\nIf `half` is `true`, the directions lie on a half-circle instead of the whole circle. \n\"\"\"\nfunction unitcircle(n; half = false, normal = [0, 0, 1])\n    # Create directions (unformly distributed on unit circle)\n    \u03b8 = 2\u03c0 * collect(0:n-1)' / (1 + half)n\n    directions = [\n        cos.(\u03b8)\n        sin.(\u03b8)\n        zeros(1, ndirection)\n    ]\n\n    # Create rotation matrix to transform normal to e_z\n    normal = normal / norm(normal)\n    c = normal + [0, 0, 1]\n    R = 2(c * c') / c'c - I(3)\n    normal \u2248 [0, 0, 1] || (directions = R'directions)\n\n    directions\nend\n", "meta": {"hexsha": "a761ca5300d86fa54bb20496075b8ac9ab56902d", "size": 722, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/unitcircle.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/unitcircle.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/unitcircle.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": 28.88, "max_line_length": 91, "alphanum_fraction": 0.608033241, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947148047778, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.7812382841328019}}
{"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 \u00f7 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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.14\"\n\n# \u2554\u2550\u2561 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tfaces, N = 1:6, 10^6\n\tmcEstimate = counts(rand(faces,N), faces)/N\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.14\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550b93d18b8-2161-11eb-299b-0d801d262dd3\n# \u255f\u250070182cd8-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([\u03c1=1.0,[\u03bd=1.0]])`\nThe matern kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = 2^{1-\u03bd}/\u0393(\u03bd)*(\u221a(2\u03bd)\u2016x-y\u2016)^\u03bd K_\u03bd(\u221a(2\u03bd)\u2016x-y\u2016)\n```\nFor `\u03bd=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=\u221e`.\n\"\"\"\nstruct MaternKernel{T\u03bd<:Real} <: BaseKernel\n    \u03bd::Vector{T\u03bd}\n    function MaternKernel(;nu::T=1.5, \u03bd::T=nu) where {T<:Real}\n        @check_args(MaternKernel, \u03bd, \u03bd > zero(T), \"\u03bd > 0\")\n        return new{T}([\u03bd])\n    end\nend\n\n@inline function kappa(\u03ba::MaternKernel, d::Real)\n    \u03bd = first(\u03ba.\u03bd)\n    iszero(d) ? one(d) :\n    exp(\n        (one(d) - \u03bd) * logtwo - logabsgamma(\u03bd)[1] +\n        \u03bd * log(sqrt(2\u03bd) * d) +\n        log(besselk(\u03bd, sqrt(2\u03bd) * d))\n    )\nend\n\nmetric(::MaternKernel) = Euclidean()\n\n\"\"\"\n`Matern32Kernel([\u03c1=1.0])`\nThe matern 3/2 kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = (1+\u221a(3)\u03c1\u2016x-y\u2016)exp(-\u221a(3)\u03c1\u2016x-y\u2016)\n```\n\"\"\"\nstruct Matern32Kernel <: BaseKernel end\n\nkappa(\u03ba::Matern32Kernel, d::Real) = (1 + sqrt(3) * d) * exp(-sqrt(3) * d)\n\nmetric(::Matern32Kernel) = Euclidean()\n\n\"\"\"\n`Matern52Kernel([\u03c1=1.0])`\nThe matern 5/2 kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = (1+\u221a(5)\u03c1\u2016x-y\u2016 + 5\u03c1\u00b2\u2016x-y\u2016^2/3)exp(-\u221a(5)\u03c1\u2016x-y\u2016)\n```\n\"\"\"\nstruct Matern52Kernel <: BaseKernel end\n\nkappa(\u03ba::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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, NLsolve\n\tRandom.seed!(0)\nend;\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.08\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.08\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u2550d91f4766-3a9b-11eb-2892-7b7925b084b2\n# \u2560\u2550d91f7dd0-3a9b-11eb-313d-81f3bcee7e68\n# \u2560\u2550d9200de0-3a9b-11eb-2204-db202244e154\n# \u255f\u2500475ff888-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": "using NPFinancial\nusing Test\n\n@testset \"Tests\" begin\n\n    @test NPFinancial._convert_when(:begin) == 1\n    @test NPFinancial._convert_when(:end) == 0\n\n    @info \"Custom tests\"\n    @test fv(0.01, 1, 0, -100, :end) == 101.0\n    @test map(x -> fv(x, 10*12, -100, -100), [0.05, 0.06, 0.07]/12) \u2248 [15692.92889434,  16569.87435405,  17509.44688102]\n    @test pmt(0.075/12, 12*15, 200000) \u2248 -1854.0247200054619\n    @test nper(0.07/12, -150, 8000) \u2248 64.07334877066185\n    @test ipmt(0.01, 4, 10, -100.0) \u2248 0.7103767498422946\n    @test rate(1, 0, -100, 101) \u2248 0.01\n    @test isnan(rate(10, -10, 100, 102))\n\n    # unit tests borrowed from numpy\n\n    @info \"Testing irr\"\n    v = [-150000, 15000, 25000, 35000, 45000, 60000]\n    @test round(irr(v), digits = 4) == 0.0524\n\n    v = [-100, 0, 0, 74]\n    @test round(irr(v), digits = 4) == -0.0955\n\n    v = [-100, 39, 59, 55, 20]\n    @test round(irr(v), digits = 5) == 0.28095\n\n    v = [-100, 100, 0, -7]\n    @test round(irr(v), digits = 4) == -0.0833\n\n    v = [-100, 100, 0, 7]\n    @test round(irr(v), digits = 5) == 0.06206\n\n    v = [-5, 10.5, 1, -8, 1]\n    @test round(irr(v), digits = 4) == 0.0886\n\n    v = [-1, -2, -3]\n    @test isnan(irr(v))    # in Julia, we cannot compare NaN with NaN\n\n    @info \"Testing pv\"\n    @test round(pv(0.07, 20, 12000, 0), digits = 2) == -127128.17\n\n    @info \"Testing pmt\"\n    res = pmt(0.08 / 12, 5 * 12, 15000)\n    tgt = -304.145914\n    @test round(res, digits = 6) == round(tgt, digits = 6)\n\n    # Test the edge case where rate == 0.0\n    res = pmt(0.0, 5 * 12, 15000)\n    tgt = -250.0\n    @test round(res, digits = 6) == round(tgt, digits = 6)\n\n    # julia broadcast\n    res = pmt.([0.3, 0.8], [12, 3], [2000, 20000])\n    tgt = [-626.90814, -19311.258]\n    # @info \"res=$res\"\n    # @info \"tgt=$tgt\"\n    # @info \"result=$(round.(res,3) .== round.(tgt,3))\"\n    @test all(round.(res, digits = 3) .== round.(tgt, digits = 3)) == true\n\n    @info \"Testing ppmt\"\n    @test round(ppmt(0.1 / 12, 1, 60, 55000), digits = 2) == -710.25\n    @test round(ppmt(0.23 / 12, 1, 60, 10000000000), digits = 8) == -90238044.232277036\n\n    @info \"Testing ipmt\"\n    @test round(ipmt(0.1 / 12, 1, 24, 2000), digits = 2) == -16.67\n\n    @info \"Testing nper\"\n    @test round(nper(0.075, -2000, 0, 100000.), digits = 2) == 21.54\n    @test round(nper(0.0, -2000, 0, 100000.), digits = 1) == 50.0\n\n    @info \"Testing npv\"\n    @test round(npv(0.05, [-15000, 1500, 2500, 3500, 4500, 6000]), digits = 2) == 122.89\n\n    @info \"Testing mirr\"\n    val = [-4500, -800, 800, 800, 600, 600, 800, 800, 700, 3000]\n    @test round(mirr(val, 0.08, 0.055), digits = 4) == 0.0666\n\n    val = [-120000, 39000, 30000, 21000, 37000, 46000]\n    @test round(mirr(val, 0.10, 0.12), digits = 6) == 0.126094\n\n    val = [100, 200, -50, 300, -200]\n    @test round(mirr(val, 0.05, 0.06), digits = 4) == 0.3428\n\n    val = [39000, 30000, 21000, 37000, 46000]\n    @test isnan(mirr(val, 0.10, 0.12))\n    \n    @info \"Testing eir\"\n    @test round(eir(0.08, 2), digits = 3) == 0.082\n\n    @info \"All tests completed\"\nend\n", "meta": {"hexsha": "34812465565277c287193afb1c5da700833fa810", "size": 3029, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "r0cketr1kky/NPFinancial.jl", "max_stars_repo_head_hexsha": "dd7af8ba8494054a0f171a2e0e41aede7463664f", "max_stars_repo_licenses": ["MIT"], "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": "r0cketr1kky/NPFinancial.jl", "max_issues_repo_head_hexsha": "dd7af8ba8494054a0f171a2e0e41aede7463664f", "max_issues_repo_licenses": ["MIT"], "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": "r0cketr1kky/NPFinancial.jl", "max_forks_repo_head_hexsha": "dd7af8ba8494054a0f171a2e0e41aede7463664f", "max_forks_repo_licenses": ["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.8842105263, "max_line_length": 120, "alphanum_fraction": 0.5539782106, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7811807338843136}}
{"text": "#=\nThe Fibonacci sequence is defined by the recurrence relation:\n\nFn = Fn\u22121 + Fn\u22122, 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": "\"\"\"Calculate the bitpattern entropy in base `base` for all elements in array A.\"\"\"\nfunction bitpattern_entropy(A::AbstractArray,base::Real=2)\n    nbits = sizeof(eltype(A))*8\n    T = whichUInt(nbits)\n    return bitpattern_entropy(T,A,base)\nend\n\n\"\"\"Calculate the bitpattern entropy in base `base` for all elements in array A.\nIn place version that will sort the array.\"\"\"\nfunction bitpattern_entropy!(A::AbstractArray,base::Real=2)\n    nbits = sizeof(eltype(A))*8\n    T = whichUInt(nbits)\n    return bitpattern_entropy!(T,A,base)\nend\n\n\"\"\"Calculate the bitpattern entropy for an array A by reinterpreting the elements\nas UInts and sorting them to avoid creating a histogram.\"\"\"\nfunction bitpattern_entropy(::Type{T},A::AbstractArray,base::Real) where {T<:Unsigned}\n    return bitpattern_entropy!(T,copy(A),base)\nend\n\n\"\"\"Calculate the bitpattern entropy for an array A by reinterpreting the elements\nas UInts and sorting them to avoid creating a histogram.\nIn-place version of bitpattern_entropy.\"\"\"\nfunction bitpattern_entropy!(::Type{T},A::AbstractArray,base::Real) where {T<:Unsigned}\n\n    # reinterpret to UInt then sort to avoid allocating a histogram\n    # in-place ver\n    sort!(reinterpret(T,vec(A)))    # TODO maybe think of an inplace version?\n    n = length(A)\n\n    E = 0.0     # entropy\n    m = 1       # counter\n\n    for i in 1:n-1\n        @inbounds if A[i] == A[i+1]     # check whether next entry belongs to the same bin in histogram\n            m += 1\n        else\n            p = m/n\n            E -= p*log(p)\n            m = 1\n        end\n    end\n\n    p = m/n         # complete for last bin\n    E -= p*log(p)\n\n    # convert to given base, 2 i.e. [bit] by default\n    E /= log(base)\n\n    return E\nend", "meta": {"hexsha": "0ab2818e738bf89ecef4ecb9b54844de1475104b", "size": 1714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bitpattern_entropy.jl", "max_stars_repo_name": "esowc/BitInformation.jl", "max_stars_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-16T20:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:36:23.000Z", "max_issues_repo_path": "src/bitpattern_entropy.jl", "max_issues_repo_name": "esowc/BitInformation.jl", "max_issues_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-04-13T16:06:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:39:57.000Z", "max_forks_repo_path": "src/bitpattern_entropy.jl", "max_forks_repo_name": "esowc/BitInformation.jl", "max_forks_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T03:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T03:28:55.000Z", "avg_line_length": 32.9615384615, "max_line_length": 103, "alphanum_fraction": 0.6627771295, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7811058723245635}}
{"text": "# ---\n# title: 335. Self Crossing\n# id: problem335\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Math\n# link: <https://leetcode.com/problems/self-crossing/description/>\n# hidden: true\n# ---\n# \n# You are given an array _x_ of `n` positive numbers. You start at point `(0,0)`\n# and moves `x[0]` metres to the north, then `x[1]` metres to the west, `x[2]`\n# metres to the south, `x[3]` metres to the east and so on. In other words,\n# after each move your direction changes counter-clockwise.\n# \n# Write a one-pass algorithm with `O(1)` extra space to determine, if your path\n# crosses itself, or not.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     **\u250c\u2500\u2500\u2500\u2510\n#     \u2502   \u2502\n#     \u2514\u2500\u2500\u2500\u253c\u2500\u2500>\n#         \u2502\n#     \n#     Input: **[2,1,1,2]\n#     Output: true\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     **\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n#     \u2502      \u2502\n#     \u2502\n#     \u2502\n#     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\n#     \n#     Input:** [1,2,3,4]\n#     Output: false \n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     **\u250c\u2500\u2500\u2500\u2510\n#     \u2502   \u2502\n#     \u2514\u2500\u2500\u2500\u253c>\n#     \n#     Input:** [1,1,1,1]\n#     Output: true \n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "f0cf4f444c19d912adf0c854bc5c049147c7afac", "size": 1157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/335.self-crossing.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/335.self-crossing.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/335.self-crossing.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.2686567164, "max_line_length": 80, "alphanum_fraction": 0.4831460674, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8596637523076224, "lm_q1q2_score": 0.7811058664366101}}
{"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 \u2248 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": "\nlist_test_str = split(\n\"forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2\",\n'\\n'\n)\n\nlist_str = readlines(\"day2_input.txt\")\n\n# Part 1\n\nfunction part1(list)\n    depth = 0\n    pos = 0\n    for cmd in list\n        m, k = split(cmd)\n        k = parse(Int, k)\n        pos += m == \"forward\" ? k : 0\n        depth += m == \"up\" ? -k : m == \"down\" ? k : 0\n    end\n    return pos * depth\nend\n\n@info \"Part 1\"\n@info \"test:\"\n@show part1(list_test_str) == 150\n@info \"challenge:\" \n@show part1(list_str) == 1714680\n\n# Part 2\n\nfunction part2(list)\n    depth = 0\n    pos = 0\n    aim = 0\n    for cmd in list\n        m, k = split(cmd)\n        k = parse(Int, k)\n        pos += m == \"forward\" ? k : 0\n        depth += m == \"forward\" ? aim * k : 0\n        aim += m == \"up\" ? -k : m == \"down\" ? k : 0\n    end\n    return pos * depth\nend\n\n@info \"Part 2\"\n@info \"test:\"\n@show part2(list_test_str) == 900\n@info \"challenge:\"\n@show part2(list_str) == 1963088820\n\n# Alternative\n\n# Part 1\n\nforward(k) = [0, k] # depth and pos\nup(k) = [-k, 0]\ndown(k) = [k, 0]\n\nfunction part1_alt(list)\n    commands = [split(cmd) |> u -> (Symbol(first(u)), parse(Int, last(u))) for cmd in list]\n    return prod(mapreduce(u -> eval(first(u))(last(u)), +, commands))\nend\n\n@info \"Part 1 alt\"\n@info \"test:\"\n@show part1_alt(list_test_str) == 150\n@info \"challenge:\" \n@show part1_alt(list_str) == 1714680\n\n# Part 2\n\nfunction forward!(u, k)\n    u[1] += u[3] * k\n    u[2] += k\nend\nfunction up!(u, k)\n    u[3] -= k\nend\nfunction down!(u, k)\n    u[3] += k\nend\n\nfunction part2_alt2(list)\n    u = [0, 0, 0]\n    for l in list\n        cmd = l[1]\n        k = parse(Int, l[end])\n        if cmd == 'f'\n            forward!(u, k)\n        elseif cmd == 'u'\n            up!(u, k)\n        else\n            down!(u, k)\n        end\n    end\n    return u[1] * u[2]\nend\n\n@info \"Part 2 alt\"\n@info \"test:\"\n@show part2_alt2(list_test_str) == 900\n@info \"challenge:\" \n@show part2_alt2(list_str) == 1963088820\n\nnothing\n\n", "meta": {"hexsha": "0cd310cbf4e1950457b34881a2e7700d3f14e581", "size": 1933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aoc2021/day2_dive.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": "aoc2021/day2_dive.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": "aoc2021/day2_dive.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": 17.2589285714, "max_line_length": 91, "alphanum_fraction": 0.5369891361, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.7810676918028483}}
{"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\u0394x = 0.02\nLx = 4.0\nxlim = (-Lx/2,Lx/2)\nylim = (-Lx/2,Lx/2)\ng = PhysicalGrid(xlim,ylim,\u0394x);\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\u0394s = 2\u0394x\nbody = PotentialFlowBody(Circle(Rc,\u0394s))\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\u0393v = 1.0\nv = Vortex(Rv,0.0,\u0393v);\n\n# And we set an equal and opposite circulation about the body\nset\u0393(body,-\u0393v)\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 # \u03b81 = \u03c0.+atan.((body.points.y)./(body.points.x.-Rv)) # angle from vortex to points on circle\n#md # \u03b82 = atan.((body.points.y),(body.points.x.-Rc^2/Rv)) # angle from image vortex to points on circle\n#md # v1x = -v.\u0393./(2\u03c0*r1).*cos.(\u03b81.-\u03c0/2) # x velocity on circle induced by vortex\n#md # v1y = -v.\u0393./(2\u03c0*r1).*sin.(\u03b81.-\u03c0/2) # y velocity on circle induced by vortex\n#md # v2x = v.\u0393./(2\u03c0*r2).*cos.(\u03b82.-\u03c0/2) # x velocity on circle induced by image vortex\n#md # v2y = v.\u0393./(2\u03c0*r2).*sin.(\u03b82.-\u03c0/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 # \u03b3 = -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 \u03b81 = \u03c0.+atan.((body.points.y)./(body.points.x.-Rv)) # angle from vortex to points on circle\n#!md \u03b82 = atan.((body.points.y),(body.points.x.-Rc^2/Rv)) # angle from image vortex to points on circle\n#!md v1x = -v.\u0393./(2\u03c0*r1).*cos.(\u03b81.-\u03c0/2) # x velocity on circle induced by vortex\n#!md v1y = -v.\u0393./(2\u03c0*r1).*sin.(\u03b81.-\u03c0/2) # y velocity on circle induced by vortex\n#!md v2x = v.\u0393./(2\u03c0*r2).*cos.(\u03b82.-\u03c0/2) # x velocity on circle induced by image vortex\n#!md v2y = v.\u0393./(2\u03c0*r2).*sin.(\u03b82.-\u03c0/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 \u03b3 = -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.\u03c8,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./\u0394s,label=\"f/ds\",xlabel=\"body point index\")\nplot!(\u03b3,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 = \u0393v/(2\u03c0*(Rv-Rc^2/Rv))\nT = 2\u03c0*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\u0307 = vortexvelocities!(model)\n    return X\u0307\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\u03b8 = -v.\u0393/(2\u03c0*(Rv-Rc^2/Rv))\n#jl     Tv = 2\u03c0*Rv/abs(V\u03b8)\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\u0307 = vortexvelocities!(model)\n#jl         return X\u0307\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,\u0394s), 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 # \u03b8 = atan.(body.points.y,body.points.x)\n#md # \u03b3 = 2*sin.(\u03b8);\n#md # ```\n\n#!md # # Analytical solution\n#!md \u03b8 = atan.(body.points.y,body.points.x)\n#!md \u03b3 = 2*sin.(\u03b8);\n\nplot(sol.\u03c8,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./\u0394s,label=\"f/ds\",xlabel=\"body point index\")\nplot!(\u03b3,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(\u03b8)\n  # No ReverseDiff if using Flux\n  Array(concrete_solve(prob_nn,Tsit5(),rho0,\u03b8,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    \u03a9::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    \u03a9 = det(LatVecs)\n    R,G,G2 = init_grids( Ns, LatVecs, RecVecs )\n    return PWGrid( Ns, LatVecs, RecVecs, Npoints, \u03a9, 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\u207b\u00b9 = inv(V)\n@show V\u207b\u00b9 * 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": "include(\"Shor.jl\")\nusing Test\n\n\"\"\"Euler theorem states that the order is a devisor of Euler\u03c6 (or the size of Z* group of `N`)\"\"\"\nfunction check_Euler_theorem(N::Int)\n    Z = NumberTheory.Z_star(N)\n    Nz = length(Z)   # Euler\u03c6\n    for x in Z\n        @test powermod(x,Nz,N) == 1  # the order is a devisor of Euler\u03c6\n    end\nend\n\n@testset \"Euler\" begin\n    check_Euler_theorem(150)\nend\n\n@testset \"shor_classical\" begin\n    Random.seed!(129)\n    L = 35\n    f = shor(L, Val(:classical))\n    @test f == 5 || f == 7\n\n    L = 25\n    f = shor(L, Val(:classical))\n    @test f == 5\n\n    L = 7*11\n    f = shor(L, Val(:classical))\n    @test f == 7 || f == 11\n\n    L = 14\n    f = shor(L, Val(:classical))\n    @test f == 2 || f == 7\n\n    @test NumberTheory.factor_a_power_b(25) == (5, 2)\n    @test NumberTheory.factor_a_power_b(15) == nothing\nend\n\n@testset \"shor quantum\" begin\n    Random.seed!(129)\n    L = 15\n    f = shor(L, Val(:quantum))\n    @test f == 5 || f == 3\nend\n", "meta": {"hexsha": "8c0c104ab0ae9ef2735315e061dd2aafa0a8c16d", "size": 958, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Shor/tests.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": "examples/Shor/tests.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": "examples/Shor/tests.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": 21.2888888889, "max_line_length": 97, "alphanum_fraction": 0.5793319415, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7810445328382973}}
{"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": "# Meshgrid function (ndgrid)\r\nfunction meshgrid{T}(vx::Array{T}, vy::Array{T})\r\n    m, n = length(vy), length(vx)\r\n    vx = reshape(vx, 1, n)\r\n    vy = reshape(vy, m, 1)\r\n    (repmat(vx, m, 1), repmat(vy, 1, n))\r\nend\r\n\r\nfunction smart_innerY{T<:Signed, F<:AbstractFloat}(Y::Array{F}, N::T, U::Array{F}, L::Array{F}, \u03c31::F, \u03bc1::F)\r\n    ## Here, we assume that the vector Y is already normalized.\r\n\r\n    ## The computation of lambda max involves taking all inner products of Y.\r\n    ## The smart method allows for the computation of the i+1_th parcel based on\r\n    ## the result of the i_th parcel.\r\n\r\n    arraytype = typeof(Y[1])\r\n\r\n    ## Preallocating the vector IP_vector for speed\r\n    IP_vector = Array{arraytype}(zeros(N,1))\r\n\r\n    index_array = collect(1:N)'\r\n    IP_vector[1]= sum( Y.* (index_array'-\u03bc1) / \u03c31 )\r\n    sumY = 0\r\n\r\n    for i = 2:N\r\n        sumY = sumY + Y[i-1]\r\n        IP_vector[i] = sumY * ( U[i-1] - L[i-1] )\r\n    end\r\n\r\n    return IP_vector\r\nend\r\n\r\nfunction calculate_matrices{T<:Int}(N::T)\r\n    ## index\r\n    i = collect(1:N-1)'\r\n\r\n    ## calculate arrays mean and variance\r\n    array_\u03bc = (N-i')/N\r\n    array_\u03c3 = sqrt( (1/(N-1)) *( (i').*array_\u03bc .^2 + (N-i').*(1-array_\u03bc).^2 ) )\r\n\r\n    ## With these parameters, compose the Lower and Upper diagonal matrices\r\n    U = - array_\u03bc ./ array_\u03c3\r\n    L = (1 - array_\u03bc) ./ array_\u03c3\r\n\r\n    ## Calculate \u03bc1 and \u03c31\r\n    \u03bc1 = (N+1)/2\r\n    \u03c31 = sqrt( (1/6)*(N+1)*(2*N+1)-\u03bc1^2 )\r\n\r\n    ## Concatenate\r\n    array_\u03c32 = [\u03c31; array_\u03c3]\r\n\r\n    ## Build X\r\n    repU, repLtranspose = meshgrid(U, L)\r\n    #x1 = ( ((1:N)' - \u03bc1) / \u03c31 )'\r\n    #x2 = triu(repU) + tril(repLtranspose') - diagm(L[:])\r\n    #x3 = [x1 [x2; L']]\r\n    X = [( ((1:N)' - \u03bc1) / \u03c31 )' [triu(repU) + tril(repLtranspose') - diagm(L[:]); L']]\r\n\r\n    ## Calculate Gram Matrix (inner products matrix)\r\n    GMat = triu( GramMatrixTM(N, U, L, \u03c31, \u03bc1) );\r\n    GMat = GMat + GMat' - N*eye(N);\r\n\r\n    return U, L, \u03bc1, \u03c31, X, GMat, array_\u03c32\r\nend\r\n\r\nfunction GramMatrixTM{T<:Int, F<:AbstractFloat}(N::T, U::Array{F}, L::Array{F}, \u03c31::F, \u03bc1::F)\r\n    ## builds the inner products matrix in the smart way\r\n    ## (much faster than X'*X)\r\n    I, J = meshgrid(collect(1:(N-1)), collect(1:(N-1)))\r\n    Uaux, Laux = meshgrid(U, L)\r\n\r\n    minimo = min(I, J);\r\n    maximo = max(I, J);\r\n\r\n    GMat1 = minimo .* (U*U') + (maximo-minimo) .* (Laux.*Uaux) + (N-maximo) .* (L*L')\r\n\r\n    ## reduce the memory usage, since we don't need theses variables anymore...\r\n    I, J, minimo, maximo = 0, 0, 0, 0\r\n    gc()\r\n\r\n    j = collect(1:N-1)';\r\n    IP = (1/\u03c31) * ( j .* U' .* ((j+1)/2 - \u03bc1) + (N-j) .* L' .* ((j+1+N)/2 - \u03bc1) )\r\n\r\n    GMat = [[N; IP'] [IP; GMat1]]\r\nend\r\n\r\nfunction calculate_\u03bc{T<:Int}(N::T)\r\n    i = 1:N-1\r\n    (N-i')/(N)\r\nend\r\n\r\nfunction calculate_\u03bc1{T<:Int}(N::T)\r\n    (N+1)/2\r\nend\r\n\r\nfunction calculate_\u03c3{T<:Int, F<:AbstractFloat}(N::T,array_\u03bc::Array{F})\r\n    i = 1:N-1\r\n    sqrt( (1/(N- 1)) *( (i').*array_\u03bc .^2 + (N-i').*(1-array_\u03bc).^2 ) )\r\nend\r\n\r\nfunction calculate_\u03c31{T<:Int, F<:AbstractFloat}(N::T,\u03bc1::F)\r\n    sqrt( (1/6)*(N+1)*(2*N+1)-\u03bc1^2 )\r\nend\r\n\r\nfunction CoordinateDescentCore{T<:Signed, F<:AbstractFloat}(A_actual::Array{T}, GMat::Array{F, 2}, j::T, \u03b2_tilde::Array{F}, \u03b2_ols::Array{F}, N::T, arrayInnerY::Array{F}, \u03bb::F, array_\u03c32::Array{F})\r\n    # aux = 0\r\n    #\r\n    # if size(A_actual)[1] >= 1\r\n    #     aux = ( GMat[j,A_actual]' * \u03b2_tilde[A_actual] )[1]\r\n    # end\r\n    aux = sum(GMat[j,A_actual]' * \u03b2_tilde[A_actual])\r\n\r\n    ##  Computation of the OLS estimator as simple regression\r\n    \u03b2_ols[j] = 1 / N * (arrayInnerY[j] - aux) + \u03b2_tilde[j]\r\n\r\n    ##  Soft-thresholding operator\r\n    if j == 1\r\n        \u03bbEff = \u03bb\r\n    else\r\n        \u03bbEff = \u03bb * array_\u03c32[j]\r\n    end\r\n\r\n    return aux, \u03bbEff, \u03b2_ols\r\nend\r\n\r\nfunction updateCandidates{T<:Signed, F<:AbstractFloat}(\u03bbEff::F, \u03b2_ols::Array{F}, j::T, A_actual::Array{T}, lastchange::T, \u03b2_tilde::Array{F}; w = [])\r\n    breakThis = 0\r\n\r\n    if size(w,1) == 0\r\n        w = ones( size(\u03b2_ols) )\r\n    end\r\n\r\n    if \u03bbEff*w[j] >= abs(\u03b2_ols[j])\r\n        if in(j, A_actual) # any(j == A_actual)\r\n            splice!(A_actual,findin(A_actual,j)[1])\r\n            lastchange = j\r\n        elseif j == lastchange\r\n            breakThis = 1\r\n        end\r\n        \u03b2_tilde[j] = 0\r\n    else\r\n        \u03b2_tilde[j] = sign(\u03b2_ols[j]) * (abs(\u03b2_ols[j]) - \u03bbEff*w[j])\r\n        ## Includes an index\r\n        if !in(j, A_actual) #not(any(j==A_actual))\r\n            push!(A_actual, Int(j))\r\n            sort!(A_actual)\r\n            lastchange = j\r\n        elseif j == lastchange\r\n            breakThis = 1\r\n        end\r\n    end\r\n\r\n    return A_actual, \u03b2_tilde, lastchange, breakThis\r\nend\r\n\r\nfunction convCheck{T<:Signed}(A_reference::Array{T}, A_actual::Array{T})\r\n    if length(A_reference) != length(A_actual)\r\n        ##  Did not converge\r\n        convergenceFlag = 0\r\n    elseif A_reference == A_actual && length(A_reference) == length(A_actual)\r\n        ##  Converged!\r\n        convergenceFlag = 2\r\n    end\r\n\r\n    return convergenceFlag\r\nend\r\n\r\nfunction calcBestB{T<:Signed, F<:AbstractFloat}(N::T, Y::Array{F}, X::Array{F}, \u03b2_lasso::Array{F}, array_\u03c32::Array{F})\r\n    bestB = -1\r\n    BICold = 1000000\r\n\r\n    for i = 1:size(\u03b2_lasso, 2)\r\n        BICnew = N * ( log(var( Y - X*\u03b2_lasso[:,i] )) ) + sum( abs(\u03b2_lasso[:,i]./array_\u03c32) .> 1e-3 ) * log(N)\r\n        if BICnew < BICold\r\n            BICold = BICnew\r\n            bestB = i\r\n        end\r\n    end\r\n\r\n    return bestB\r\nend\r\n", "meta": {"hexsha": "68f941b66c80efed99302c54166b4924be32d688", "size": 5410, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "FelipeCalliari/adaLASSO-julia.jl", "max_stars_repo_head_hexsha": "bb00a355759da7c0afee56720bf91d419d35140a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-30T19:52:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-03T21:18:04.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "FelipeCalliari/adaLASSO-julia.jl", "max_issues_repo_head_hexsha": "bb00a355759da7c0afee56720bf91d419d35140a", "max_issues_repo_licenses": ["MIT"], "max_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": "FelipeCalliari/adaLASSO-julia.jl", "max_forks_repo_head_hexsha": "bb00a355759da7c0afee56720bf91d419d35140a", "max_forks_repo_licenses": ["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.7252747253, "max_line_length": 196, "alphanum_fraction": 0.5415896488, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7810415120471718}}
{"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, \u03c8, \u03c7, d=2)\n\nCompute the reduced density matrix ``tr_B[|\u03c8\u27e9\u27e8\u03c7|]``, 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}, \u03c8::Vector{T}, \u03c7::Vector{T}, d::Int=2) where {M,T}\n    M \u2265 1 || error(\"Need at least one wire to act on.\")\n    M \u2264 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) \u2265 1 || error(\"Wire index cannot be smaller than 1.\")\n    maximum(iwire) \u2264 N || error(\"Wire index cannot be larger than total number of wires.\")\n    length(\u03c8) == d^N || error(\"Input vector '\u03c8' has wrong length.\")\n    length(\u03c7) == d^N || error(\"Input vector '\u03c7' 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    \u03c1 = zeros(eltype(\u03c8), 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 \u03c1[i, j] += \u03c8[rowind] * conj(\u03c7[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 \u03c1[i, j] += \u03c8[rowind] * conj(\u03c7[colind])\n                end\n            end\n        end\n    else\n        error(\"d = $d not supported yet.\")\n    end\n\n    return \u03c1\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, \u03b1, 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, \u03b1, 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, \u03b1, end_point, h, ::RieszSymmetric)\n    N=floor(Int, end_point/h)\n\n    mat = RieszMatrix(\u03b1, N+1, h)\n    return mat*f.(collect(0:h:end_point))\nend\nfunction RieszMatrix(\u03b1, N, h)\n    caputo = B(N+1, \u03b1)\n    caputo = caputo[2:(N+1), 1:N]\n    result = 1/2*(caputo+caputo')\n    result = h^(-\u03b1)*result\n    return result\nend\n\n#FIXME: Values are changing when h become smaller?\nfunction fracdiff(f, \u03b1, point, h, ::RieszOrtigueira)\n    N = round(Int, point/h)\n    t = collect(0:h:point)\n    return ranort(\u03b1, 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*\u03c0*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": "gaussian_2d(x = -3:0.01:3, y = -7:0.01:3; x\u2080 = 0, y\u2080 = -2, \u03c3x = 1, \u03c3y = 2) = begin\n    X = repeat(x', length(y), 1)\n    Y = repeat(y, 1, length(x))\n    x, y, map((x, y) -> exp(-((x - x\u2080) / 2\u03c3x)^2 - ((y - y\u2080) / 2\u03c3y)^2), X, Y)\nend\n\n@testset \"arbitrary colormap\" begin\n    colormap = :cividis\n    p = @inferred contourplot(gaussian_2d()...; colormap = colormap)\n    test_ref(\"references/contourplot/gauss_$colormap.txt\", @show_col(p))\nend\n\n@testset \"number of levels\" begin\n    levels = 5\n    p = @inferred contourplot(gaussian_2d()...; levels = levels)\n    test_ref(\"references/contourplot/gauss_$(levels)levels.txt\", @show_col(p))\nend\n\n@testset \"update contourplot\" begin\n    p = @inferred contourplot(gaussian_2d()...; levels = 2)\n    contourplot!(p, gaussian_2d(; \u03c3x = 0.5, \u03c3y = 0.25)...; levels = 1, colormap = :magma)\n    test_ref(\"references/contourplot/gauss_nested.txt\", @show_col(p))\nend\n\n@testset \"function\" begin\n    p = @inferred contourplot(\n        -3:0.01:3,\n        -3:0.01:4,\n        (x, y) -> (exp(-x^2 - y^2) + exp(-(x - 1)^2 - 2(y - 2)^2))^2,\n    )\n    test_ref(\"references/contourplot/function_contour.txt\", @show_col(p))\nend\n", "meta": {"hexsha": "776803233cb401cf680671cf3f5bec09de1480dd", "size": 1145, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tst_contourplot.jl", "max_stars_repo_name": "Cvikli/UnicodePlots.jl", "max_stars_repo_head_hexsha": "fecf19a90a4d22a6784a68ff0f402fcb93936a80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89, "max_stars_repo_stars_event_min_datetime": "2021-09-07T14:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:35:35.000Z", "max_issues_repo_path": "test/tst_contourplot.jl", "max_issues_repo_name": "Cvikli/UnicodePlots.jl", "max_issues_repo_head_hexsha": "fecf19a90a4d22a6784a68ff0f402fcb93936a80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 92, "max_issues_repo_issues_event_min_datetime": "2021-09-02T08:47:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:18:56.000Z", "max_forks_repo_path": "test/tst_contourplot.jl", "max_forks_repo_name": "Cvikli/UnicodePlots.jl", "max_forks_repo_head_hexsha": "fecf19a90a4d22a6784a68ff0f402fcb93936a80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-09-09T18:21:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T07:51:36.000Z", "avg_line_length": 34.696969697, "max_line_length": 89, "alphanum_fraction": 0.6052401747, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.781041502597932}}
{"text": "#\n# Maneuver calculations for orbits within the Twobody Problem\n#\n\n\"\"\"\nProvides the radius of escape.\n\"\"\"\nescape_radius(r\u2080, v\u2080, a\u209c) = r\u2080 * v\u2080 / (20 * a\u209c^2 * r\u2080^2)^(1/4)\nescape_radius(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_radius(radius(orbit), velocity(orbit), m.a\u209c)\n\n\"\"\"\nProvides the velocity at escape.\n\"\"\"\nescape_velocity(r\u2080, v\u2080, a\u209c, \u03bc) = \u221a(2 * \u03bc / escape_radius(r\u2080, v\u2080, a\u209c))\nescape_velocity(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_velocity(radius(orbit), velocity(orbit), m.a\u209c, orbit.body.\u03bc)\n\n\"\"\"\nProvides time delta from the provided initial orbit to escape.\n\"\"\"\nescape_time(r\u2080, v\u2080, a\u209c) = upreferred(v\u2080 / a\u209c) * (1 - (upreferred(20a\u209c^2 * r\u2080^2) / upreferred(v\u2080^4))^(1/8))\nescape_time(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_time(radius(orbit), velocity(orbit), m.a\u209c)\n\n\"\"\"\nProvides the path length from the initial condition to escape.\n\"\"\"\nescape_path_length(r\u2080, v\u2080, a\u209c) = upreferred(v\u2080^2 / 2a\u209c) * (1 - upreferred((1/v\u2080) * (20a\u209c^2 * r\u2080^2)^(1/4)))\nescape_path_length(orbit::T, m::ConstantManeuver) where T <: RestrictedTwoBodySystem = escape_path_length(radius(orbit), velocity(orbit), m.a\u209c)", "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 \u2211 = sum\nconst N = 6\npotential(p, t, x, y, z, M) = -G*\u2211(i->\u2211(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": "\nfunction calc_seat_id(pass)\n    digits = map(c -> c == 'F' || c == 'L' ? '0' : '1', pass)\n    row = parse(Int64, digits[1:7]; base = 2)\n    column = parse(Int64, digits[8:end]; base = 2)\n    row * 8  + column\nend\n\n\nfunction calc_highest_id(boarding_passes)\n    function update(acc, pass)\n        id = calc_seat_id(pass)\n        id > acc ? id : acc\n    end\n\n    foldl(update, boarding_passes; init = 0)\nend\n\n\nfunction main()\n    lines = readlines(\"../resources/input_05.txt\")\n    result = calc_highest_id(lines)\n    println(result)\nend\n\n\nmain()\n", "meta": {"hexsha": "1ad6a512af1211318793d29771dab9b686d820a9", "size": 545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day_05a.jl", "max_stars_repo_name": "ghostrider77/adventOfCode-2020", "max_stars_repo_head_hexsha": "7298feeb1af3f64963b526b9c12119679a44bc43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day_05a.jl", "max_issues_repo_name": "ghostrider77/adventOfCode-2020", "max_issues_repo_head_hexsha": "7298feeb1af3f64963b526b9c12119679a44bc43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day_05a.jl", "max_forks_repo_name": "ghostrider77/adventOfCode-2020", "max_forks_repo_head_hexsha": "7298feeb1af3f64963b526b9c12119679a44bc43", "max_forks_repo_licenses": ["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.4642857143, "max_line_length": 61, "alphanum_fraction": 0.6055045872, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.781041499770957}}
{"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": "using NumericalMethodsforEngineers\nusing Test\n\nb = [16. -24. 18.; 3. -2. 0.; -9. 18. -17.]\nx0 = [1., 1., 1.]\n\ntol = 1.0e-5\nlimit = 100\n\n(iters, eigval, eigvec) = nmex(b, x0; show=5)\n\nprintln(\"\\nNo of iters:                    $iters\")\nprintln(\"Largest eigen value:            $eigval\")\nprintln(\"Corresponding eigen vector:     $eigvec\")\nprintln()\n\njeigval, jeigvec = eigen(b);\n\nprintln(\"\\nEigen values:                   $jeigval\")\nprintln(\"Corresponding eigen vectors:\")\njeigvec |> display\nprintln()\n\n@test round(minimum(jeigval), digits=3) == round(eigval, digits=3)", "meta": {"hexsha": "86938c73427458bdfa605440417cbeb426ae5326", "size": 568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch01/f_01_02.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/ch01/f_01_02.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/ch01/f_01_02.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.6666666667, "max_line_length": 66, "alphanum_fraction": 0.6144366197, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7810008073473996}}
{"text": "#using TensorToolbox, Test, LinearAlgebra\n\nprintln(\"\\n\\n**** Testing tensor.jl\")\n\nX=rand(20,10,50,5)\nN=ndims(X)\nprintln(\"\\n**Test tensor X of size: \", size(X))\n\nprintln(\"\\n...Testing functions matten and tenmat (by mode).\")\nfor n=1:N\n  Xn=tenmat(X,n);\n  M=setdiff(1:N,n);\n  println(\"Size of $n-mode matricization: \", [size(Xn)...])\n  @test size(Xn) == (size(X,n),prod([size(X,M[k]) for k=1:length(M)]))\n  println(\"Check if it folds back correctly: \",matten(Xn,n,[size(X)...]) == X)\n  @test matten(Xn,n,[size(X)...]) == X\nend\n\nprintln(\"\\n...Testing functions matten and tenmat (by rows and columns).\")\nR=[2,1];C=[4,3];\nXmat=tenmat(X,row=R,col=C);\nprintln(\"Size of R=$R and C=$C matricization: \", [size(Xmat)...])\nprintln(\"Check if it folds back correctly: \",matten(Xmat,R,C,[size(X)...]) == X)\n@test matten(Xmat,R,C,[size(X)...]) == X\n\nprintln(\"\\n...Testing function ttm.\")\nM=MatrixCell(undef,N)\nfor n=1:N\n  M[n]=rand(5,size(X,n))\nend\nprintln(\"Created $N matrices with 5 rows and appropriate number of columns.\")\nXprod=ttm(X,M)\nprintln(\"Size of tensor Y=ttm(X,M): \",size(Xprod))\nerr=norm(tenmat(Xprod,1) - M[1]*tenmat(X,1)*kron(M[end:-1:2])')\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n...Testing function ttv.\")\nXk=reshape(collect(1:24),(3,4,2))\nmode=2\nv=collect(1:4)\nprintln(\"Multiplying a tensor X by a vector v in mode $mode.\")\nXprod=ttv(Xk,v,mode)\nprintln(\"Size of tensor Y=ttv(X,v): \",size(Xprod))\nres=[70 190;80 200;90 210]\n@test Xprod==res\n\nprintln(\"\\n...Testing function krontm.\")\nX=rand(5,4,3)\nY=rand(2,5,4)\nprintln(\"Created two tensors X and Y of order \",ndims(X),\" and sizes \",size(X),\" and \",size(Y),\".\")\nmode=3\nM1=rand(20,10)\nM2=rand(20,20)\nM3=rand(20,12)\nprintln(\"Multiplying tkron(X,Y) by random matrix in mode $mode.\")\nZ=krontm(X,Y,M3,mode)\nerr= norm(Z-ttm(tkron(X,Y),M3,mode))\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\nmode=[3,2]\nM=[M3,M2]\nprintln(\"Multiplying tkron(X,Y) by random matrices in modes $mode.\")\nZ=krontm(X,Y,M,mode)\nerr = norm(Z-ttm(tkron(X,Y),M,mode))\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\nM=[M1,M2,M3]\nprintln(\"Multiplying tkron(X,Y) by random matrices in all modes.\")\nZ=krontm(X,Y,M)\nerr = norm(Z-ttm(tkron(X,Y),M))\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n...Testing function mkrontv.\")\nv=rand(240)\nmode=1\nprintln(\"Multiplying mode-$mode matricized tkron(X,Y) by a random vector.\")\nZ=mkrontv(X,Y,v,mode)\nerr = norm(Z-tenmat(tkron(X,Y),mode)*v)\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\nv=rand(10)\nZ=mkrontv(X,Y,v,mode,'t')\nerr = norm(Z-tenmat(tkron(X,Y),mode)'*v)\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n...Testing function mttkrp.\")\nX=rand(5,4,3)\nmode=1\nA1=rand(2,5);\nA2=rand(4,5);\nA3=rand(3,5);\nA=[A1,A2,A3]\nprintln(\"Multiplying mode-$mode matricized tensor X by Khatri-Rao product of matrices.\")\nZ=mttkrp(X,A,mode)\nerr = norm(Z-tenmat(X,mode)*khatrirao(A3,A2))\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\n\nprintln(\"\\n...Testing function dropdims.\")\nX=rand(5,4,1,3,6,1)\nXsq=dropdims(X)\nprintln(\"Tensor X of size :\",size(X),\" squeezed to size :\",size(Xsq),\".\")\n\nprintln(\"\\n...Testing contraction (contract).\")\nX=rand(5,4,3);\nY=rand(3,4,2);\nZ=contract(X,Y)\nfor i1=1:5, i2=1:4, j2=1:4,j3=1:2\n    s=0;\n    for i=1:3\n        s+=X[i1,i2,i]*Y[i,j2,j3];\n    end\n    @test Z[i1,i2,j2,j3] \u2248 s atol=1e-10\nend\nX=rand(5,4,3,2);\nY=rand(5,7,3,6);\nZ=contract(X,[1,3],Y,[1,3])\nerr=norm(Z-reshape(tenmat(X,row=[1,3])'*tenmat(Y,row=[1,3]),(4,2,7,6)))\nprintln(\"Error: \",err)\n@test err \u2248 0 atol=1e-10\n", "meta": {"hexsha": "9eebf9da55063c9aec1887d6d181d0d4b26a8542", "size": 3604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tensorTest.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/TensorToolbox.jl-9c690861-8ade-587a-897e-15364bc6f718", "max_stars_repo_head_hexsha": "969a1a9f20b236fbd90dd47d8d01679ee75afe56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2017-05-25T14:02:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:46:13.000Z", "max_issues_repo_path": "test/tensorTest.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/TensorToolbox.jl-9c690861-8ade-587a-897e-15364bc6f718", "max_issues_repo_head_hexsha": "969a1a9f20b236fbd90dd47d8d01679ee75afe56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-08-04T00:20:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T20:05:19.000Z", "max_forks_repo_path": "test/tensorTest.jl", "max_forks_repo_name": "bovine3dom/TensorToolbox.jl", "max_forks_repo_head_hexsha": "fe96333d5d6ce4a03150f10f2ef5f191954b8efb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-05-25T10:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-10T12:18:38.000Z", "avg_line_length": 29.064516129, "max_line_length": 99, "alphanum_fraction": 0.6570477248, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7810008063908409}}
{"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*\u0127/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/\u0127\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*\u0127/(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/\u0127)*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*\u0127/kb/T , wf*\u0127/kb/T ; rtol=rtol)\r\n\r\n    return val*kb^4/\u0127^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/\u0127;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/\u0127^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/\u0127; 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*\u0127/kb/T , wf*\u0127/kb/T ; rtol=rtol)\r\n\r\n    return val*kb^4/\u0127^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    \u03bcs = Ks'*invKy*y\n    \u03a3s = Kss - Ks'*invKy*Ks\n    return \u03bcs, \u03a3s\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        \u03b1 = invL'*invL*y \n        loglike = -0.5*y'*\u03b1 - sum(log.(diag(L))) - 0.5*N*log(2\u03c0)\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\u03c0)\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\u03c3f, log\u03c3y; stable=false)\n    l = exp(logl) \n    \u03c3f = exp(log\u03c3f)\n    \u03c3y = exp(log\u03c3y)\n    sekernel = SquaredExponentialKernel(l, \u03c3f, \u03c3y)\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, \u03c3f, \u03c3y; stable=false)\n    sekernel = SquaredExponentialKernel(l, \u03c3f, \u03c3y)\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\u03c3f, log\u03c3y, \u03b80, \u03b81)\n    l = exp(logl) \n    \u03c3f = exp(log\u03c3f)\n    \u03c3y = exp(log\u03c3y)\n    mixturekernel = MixtureKernel(l, \u03c3f, \u03c3y, \u03b80, \u03b81)\n    Ky = covariancematrix(mixturekernel, X)\n    return negloglike(X, y, Ky)\nend\n\n\"\"\"\n    logmarginalpartial(kernel, X, y, \u2202Ky\u2202\u03b8)\n\nPartial derivative of log marginal likelihood ``\\\\log{P(y|X)}`` wrt\nparameter ``\u03b8``.\n\n# Parameters\n- `X`: input matrix\n- `y`: labels\n- `\u2202Ky\u2202\u03b8`: partial derivative of covariance matrix ``K_y`` wrt ``\u03b8``.\n\n\"\"\"\nfunction logmarginalpartial(kernel, X, y, \u2202Ky\u2202\u03b8) \n    Ky = covariancematrix(kernel, X)\n    invKy = inv(Ky)\n    \u03b1 = invKy*y\n    return 0.5*tr((\u03b1*\u03b1' - invKy)*\u2202Ky\u2202\u03b8)\nend\n\n\"\"\"\n    logmarginalgradient(kernel, X, y)\n  \n``\u2207_\u03b8 \\\\log{P(y|X)}``: Analytic gradient of log marginal likelihood ``\\\\log{P(y|X)}`` \nwrt parameters. \n\nNotice because we are passing ``\\\\log\u03b8`` into the log marginal \nlikelihood function. \n    \nWe need to apply chain rule to the gradient we need is \n``\n\u2207_{\\\\log\u03b8} \\\\log{P(y|X)} = \\\\frac{\u2202log{P(y|X)}}{\u2202\u03b8^2} \n                         \\\\frac{\u2202\u03b8^2}{\u2202\u03b8} \n                         \\\\frac{\u2202\u03b8}{\u2202log\u03b8}  \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    \u03c3f = kernel.\u03c3f\n    \u03c3y = kernel.\u03c3y\n\n    funcs = Dict{String, Function}()\n    quad(xp, xq, M) = -0.5*(xp-xq)'*M*(xp-xq)\n    funcs[\"\u2202p\u2202logl\"] = (xp, xq, \u03b4pq, M) -> \n        \u03c3f^2*(-0.5*(xp-xq)'*(xp-xq))*exp.(quad(xp, xq, M))*(-1/l^4)*2*l*l\n    funcs[\"\u2202p\u2202log\u03c3f\"] = (xp, xq, \u03b4pq, M) -> exp.(quad(xp, xq, M))*2*\u03c3f*\u03c3f\n    funcs[\"\u2202p\u2202log\u03c3y\"] = (xp, xq, \u03b4pq, M) -> \u03b4pq*2*\u03c3y*\u03c3y\n\n    N = size(X, 1)\n    numparameters = 3\n    parameternames = [\"\u2202p\u2202logl\", \"\u2202p\u2202log\u03c3f\", \"\u2202p\u2202log\u03c3y\"]\n    marginalpartialderiv = zeros(numparameters)\n    for i = 1:numparameters\n        parametername = parameternames[i]\n        func = funcs[parametername]\n        \u2202Ky\u2202\u03b8 = 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            \u2202Ky\u2202\u03b8[p, q] = func(xp, xq, p==q, M)\n        end\n        marginalpartialderiv[i] = logmarginalpartial(kernel, X, y, \u2202Ky\u2202\u03b8)\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\u03b8/dt = \u03c9(t),``\n``d\u03c9/dt = -(3/2)(g/l)sin\u03b8 + (3/ml\u00b2)M(t)``\nfor mass m, length l, and where t\u2208[0,10], u\u2080= [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\u03b8\u2080 = 0.01\n\u03c9\u2080 = 0.0\nu0 = [\u03b8\u2080, \u03c9\u2080]\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=[\"\u03b8 [rad]\" \"\u03c9 [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": "using SemiIsomorphism, ProgressMeter, Permutations, SimpleDrawing\nusing LinearAlgebraX,\n    SimpleGraphs, ChooseOptimizer, Gurobi, SimpleGraphAlgorithms, SimpleTools\n\nuse_Gurobi()\n\n\n\"\"\"\n    cycle_pair(n::Int)\n\nFind the semi-isomorphism between 2C_n and C_{2n}.\n\"\"\"\nfunction cycle_pair(n::Int)\n    A = adjacency(Cycle(n))\n    A = dcat(A, A)\n    d = SemiIsomorphism.make_allow(A)\n    perms = RPG(2n, d)\n\n    np = length(perms)\n    @info \"There are $np row permutations to consider\"\n    PM = Progress(np)\n\n    good_p = Permutation(2n).data\n    for p in perms\n        B = A[:, p]\n        if SemiIsomorphism.is_adjacency(B)\n            H = SimpleGraph(B)\n            if is_connected(H)\n                good_p = p\n                break\n            end\n        end\n    end\n    if good_p == Permutation(2n).data\n        println(\"No semi-isormorphism found\")\n        return\n    end\n    println(\"Adjacency matrix for 2C_$n\")\n    display(A)\n    println()\n    println(\"Row permutation to make a $(2n) cycle: $(Permutation(good_p))\")\n    println()\n    println(\"Resulting matrix\")\n    B = A[:, good_p]\n    display(B)\n    my_spy(B)\nend\n\nfunction ez_cycle_pair(n::Int)\n    A = adjacency(Cycle(n))\n    Z = zeros(Int, n, n)\n    B = [Z A; A Z]\n    G = SimpleGraph(B)\n    embed(G, :combined)\n    return G\nend\n", "meta": {"hexsha": "672ce38fcf7b2fcfd13ebce88573b82e0e150c44", "size": 1289, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cycle_pair_text.jl", "max_stars_repo_name": "scheinerman/SemiIsomorphism.jl", "max_stars_repo_head_hexsha": "1bc4aa8769eb4b6e515862d66c9b2acfd384ea62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cycle_pair_text.jl", "max_issues_repo_name": "scheinerman/SemiIsomorphism.jl", "max_issues_repo_head_hexsha": "1bc4aa8769eb4b6e515862d66c9b2acfd384ea62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cycle_pair_text.jl", "max_forks_repo_name": "scheinerman/SemiIsomorphism.jl", "max_forks_repo_head_hexsha": "1bc4aa8769eb4b6e515862d66c9b2acfd384ea62", "max_forks_repo_licenses": ["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.6140350877, "max_line_length": 77, "alphanum_fraction": 0.6035686579, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7809212047905935}}
{"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/\u221a3\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) \u00f7 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) \u00f7 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": "using JuMP, CPLEX\n\n#Preparing optimization model\nm = Model(CPLEX.Optimizer)\nmodel = Model(CPLEX.Optimizer)\nset_optimizer_attribute(m, \"CPX_PARAM_EPINT\", 1e-8)\n\n\nc = [ 1; 2; 5]\nA = [-1  1  3;\n      1  3 -7]\nb = [-5; 10]\n\nprintln(\"Size of c: \", size(c))\nprintln(\"Size of A: \", size(A))\nprintln(\"Size of b: \", size(b))\n\n\n@variable(m, x[1:3] >= 0)\n@objective(m, Max, sum( c[i]*x[i] for i=1:3) )\n\n@constraint(m, constraint[j=1:2], sum( A[j,i]*x[i] for i=1:3 ) <= b[j] )\n\n#@constraint(m, constraint1, sum( A[1,i]*x[i] for i=1:3) <= b[1] )\n#@constraint(m, constraint2, sum( A[2,i]*x[i] for i=1:3) <= b[2] )\n\n@constraint(m, bound, x[1] <= 10)\n\noptimize!(m)\n\nprint(m)\n\nprintln(\"Optimal Solutions:\")\nfor i=1:3\n  println(\"x[$i] = \", JuMP.value(x[i]))\nend\n\nprintln(\"Dual Variables:\")\nfor j=1:2\n  println(\"dual[$j] = \", JuMP.dual(constraint[j]))\nend\n\nprintln(\"Size of x: \", size(x))\n", "meta": {"hexsha": "d589309f9ed34964036216cc54e2b6d3863b84b0", "size": 870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples_Julia/LP_CPLEX.jl", "max_stars_repo_name": "power-systems-op/grace-arpae", "max_stars_repo_head_hexsha": "f83500fe6d765de8ccb9fb181138c2f89e8c464e", "max_stars_repo_licenses": ["MIT"], "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_Julia/LP_CPLEX.jl", "max_issues_repo_name": "power-systems-op/grace-arpae", "max_issues_repo_head_hexsha": "f83500fe6d765de8ccb9fb181138c2f89e8c464e", "max_issues_repo_licenses": ["MIT"], "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_Julia/LP_CPLEX.jl", "max_forks_repo_name": "power-systems-op/grace-arpae", "max_forks_repo_head_hexsha": "f83500fe6d765de8ccb9fb181138c2f89e8c464e", "max_forks_repo_licenses": ["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.7727272727, "max_line_length": 72, "alphanum_fraction": 0.5965517241, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8221891392358014, "lm_q1q2_score": 0.7808078397432886}}
{"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\u03f5 = 0.2\nL = -6\u03f5^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\u03f5*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]       # \u211d\r\n########################################\r\n\r\n# J = 1/2 \u2211\u1d50 \u2211\u1d4f (h - y)\u00b2\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                            # \u211d^ 1 x num_obs\r\n########################################\r\n\r\n# Final layer delta function for regression\r\nfunction delta_linear!{F<:AbstractFloat}(\u0394::Array{F}, h::Array{F}, y::Vector{F},\r\n                                         num_obs::F)\r\n\r\n    # \u0394\u207d\u1d38\u207e = 1/m (h - y)               (recall: A\u207d\u1d38\u207e = h)\r\n    @simd for j in eachindex(y)\r\n        @inbounds \u0394[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                           # \u211d\r\n########################################\r\n\r\n# J = \u2211\u1d50 - 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                          # \u211d^ 1 x num_obs\r\n########################################\r\n\r\n# Final layer delta function for regression\r\nfunction delta_logistic!{F<:AbstractFloat, T<:Integer}(\u0394::Array{F}, h::Array{F},\r\n                                                       y::Vector{T}, num_obs::F)\r\n\r\n    # \u0394\u207d\u1d38\u207e = h - y               (recall: A\u207d\u1d38\u207e = h)\r\n    @simd for j in eachindex(y)\r\n        @inbounds \u0394[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                                # \u211d\r\n########################################\r\n\r\n# J = \u2211\u1d50 \u2211\u1d4f - 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                          # \u211d^ 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}(\u0394::Array{F}, H::Array{F},\r\n                                                      y::Vector{T}, num_obs::F)\r\n\r\n    # \u0394\u207d\u1d38\u207e = 1/m (H - Y)               (recall: A\u207d\u1d38\u207e = H)\r\n    copy!(\u0394, H)\r\n    for j in eachindex(y)\r\n        @inbounds \u0394[y[j], j] -= F(1)\r\n    end\r\n\r\n    # Divide by m\r\n    broadcast!(/, \u0394, \u0394, 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                              # \u211d\r\n########################################\r\n\r\n# J = 1/2 \u2211\u1d50 \u2211\u1d4f (h - y)\u00b2\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                     # \u211d^ num_outputs x num_obs\r\n########################################\r\n\r\n# Final layer delta function for regression\r\nfunction delta_linear!{F<:AbstractFloat}(\u0394::Array{F}, H::Array{F}, Y::Array{F},\r\n                                         num_obs::F)\r\n\r\n    # \u0394\u207d\u1d38\u207e = 1/m (h - y)               (recall: A\u207d\u1d38\u207e = h)\r\n\r\n    @simd for j in eachindex(Y)\r\n        @inbounds \u0394[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": "using MultipleViewGeometry, Test\nusing StaticArrays, LinearAlgebra\n\n# Tests for a set of two-dimensional Cartesian points represented by homogeneous\n# coordinates.\n\u2133 = map(Point2D, [(-10.0, -10.0),\n                   (-10.0,  10.0),\n                   ( 10.0, -10.0),\n                   ( 10.0,  10.0)])\n\n\u2133\u02b9, \ud835\udc13 = hartley_normalization(\u2133)\n\n@test \u2133\u02b9 == map(Point2D,  [(-1.0,-1.0),\n                            (-1.0, 1.0),\n                            (1.0, -1.0),\n                            (1.0,  1.0,)])\n\n @test \ud835\udc13 == [0.1 0.0 -0.0;\n             0.0 0.1 -0.0;\n             0.0 0.0 1.0]\n @test hartley_transformation(\u2133) == [0.1 0.0 -0.0;\n                                      0.0 0.1 -0.0;\n                                      0.0 0.0 1.0]\n\n\n# Tests for a set of three-dimensional Cartesian points represented by homogeneous\n# coordinates.\n\u2133 = map(Point3D,\n           [(-10.0, -10.0, -10.0),\n            (-10.0, -10.0,  10.0),\n            (-10.0,  10.0, -10.0),\n            (-10.0,  10.0,  10.0),\n            ( 10.0, -10.0, -10.0),\n            ( 10.0, -10.0,  10.0),\n            ( 10.0,  10.0, -10.0),\n            ( 10.0,  10.0,  10.0)])\n\n\u2133\u02b9, \ud835\udc13 = hartley_normalization(\u2133)\n@test \u2133\u02b9 == map(Point3D,  [(-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)])\n\n@test \ud835\udc13 == [0.1 0.0 0.0 -0.0;\n            0.0 0.1 0.0 -0.0;\n            0.0 0.0 0.1 -0.0;\n            0.0 0.0 0.0 1.0]\n@test hartley_transformation(\u2133) ==  [0.1 0.0 0.0 -0.0;\n                                      0.0 0.1 0.0 -0.0;\n                                      0.0 0.0 0.1 -0.0;\n                                      0.0 0.0 0.0 1.0]\n", "meta": {"hexsha": "916c049736a9f5a72338c3b930e51ce936ff53c8", "size": 1889, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/data_normalization_tests.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": "test/data_normalization_tests.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": "test/data_normalization_tests.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": 33.7321428571, "max_line_length": 82, "alphanum_fraction": 0.3414505029, "num_tokens": 746, "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": "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\u00d77- random numbers distributed U [\u22125,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\u00d77- random numbers distributed N (\u22122,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\u00d77- the \ufb01rst 5 rows and \ufb01rst 5 columns of A and the last two columns and \ufb01rst 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\u00d77- where D i,j= A i,jif A i,j\u2264 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 \u2018vec\u2019 operator applied to B.\n    ## Can you \ufb01nd 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 \ufb01rst 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\u00d710\u00d77 instead of F 10\u00d77\u00d72 . 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 \u2297 C (the Kronecker product of B and C). What happens when you try C \u2297 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 \ufb01le 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 \ufb01le called firstmatrix.\n    save(\"firstmatrix.jld\",\"A\",A,\"B\",B,\"C\",C,\"D\",D)\n\n    ## j. Export C as a .csv \ufb01le called Cmatrix. You will \ufb01rst need to transform C into a DataFrame.\n    CSV.write(\"Cmatrix.csv\",DataFrame(C))\n\n    ## k. Export D as a tab-delimited .dat \ufb01le called Dmatrix. You will \ufb01rst 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\ufb01nition 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([\u03b2^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 \u00d7 K \u00d7 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\u2217(6\u2212t)/5\n    ## - a continuous variable distributed normal with mean 15+t\u22121 and standard deviation 5(t\u22121)\n        ## GG: apparently (mean).+(sd).*randn(N,1) generates a normal rv with mean and sd\n    ## - a continuous variable distributed normal with mean \u03c0(6\u2212t)/3 and standard deviation 1/e\n    ## - a discrete variable distributed \u201cdiscrete normal\u201d 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\u2019s 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) (\u03c0*(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 \u03b2 which is K \u00d7 T and whose elements evolve across time in the following fashion:\n    ## - 1,1.25,1.5,...\n    ## - ln(t)\n    ## - \u2212\u221at\n    ## - exp{t}-exp{t+1}\n    ## - t\n    ## - t/3\n    \u03b2 = 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 \u00d7 T de\ufb01ned by Y_t= X_t \u03b2_t + \u03b5_t , where \u03b5_t \u223c iid N (0,\u03c3=.36)\n    Y = hcat([cat(X[:,:,t]*\u03b2[:,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\ufb01nition 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 \ufb01le 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 \ufb01rst subset the data frame to only include the columns industry, occupation and wage.\n    ## You should then follow the \u201csplit-apply-combine\u201d 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\ufb01nition 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 \u2032 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 \ufb01rst executable line of matrixops.m (i.e. right after the \ufb01rst-line comments),\n        ## write an if statement which gives an error if the two inputs are not the same size. Have the error say \u201cinputs must have the same size.\u201d\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\ufb01nition 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\u03c9=randn(rng,N)\nnorder=2 #OA=1, versus Hannay Ansatz=2\n\n#\u03c90,\u03b3,K,\u03b2\nmodel_params=[2\u03c0, 0.1,0.8,0.1]\nic=rand(rng,N)*2\u03c0;\n\ntend=20.0\ntstart=0.0\nsampling=0.05\n\n\nfunction full_model(d\u03d5,\u03d5,p,t)\n    \u03c90, \u03b3, K, \u03b2=p\n    \u03c8,R=OrderParameter(\u03d5)\n    for i in 1:N\n        d\u03d5[i]=\u03c90+\u03b3*\u03c9[i]+R*K*sin(\u03c8-\u03d5[i]+\u03b2)\n    end\nend\n\nfunction reduced_model(du,u,p,t)\n    \u03c90, \u03b3, K, \u03b2=p\n    \u03c8,R=u\n    n=norder\n    du[1]=\u03c90+K/2.0*sin(\u03b2)*(1+R^(2*norder))\n    du[2]=-\u03b3*R+K/2.0*cos(\u03b2)*R*(1-R^(2*norder))\nend\n\n\nfunction OrderParameter(\u03d5;m=1.0)\n    Z=1.0/N*sum(exp.(im.*\u03d5*m))\n    R=abs(Z)\n    \u03c8=angle(Z)\n    return \u03c8,R\nend\n\nfunction OrderParameterComplex(\u03d5;m=1.0)\n    Z=1.0/N*sum(exp.(im.*\u03d5*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    \u03c8=zeros(num_tps)\n    for tp in 1:num_tps\n        psi, rr=OrderParameter(sol[:,tp])\n        R[tp]=rr\n        \u03c8[tp]=psi\n    end\n\n    pl1=plot(\u03c8,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.(\u03c8), 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#\u03c3N=0.05\n#data+=\u03c3N*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        \u03b8p=prediction[1,k]\n        \u03b8d=data[1,k]\n        loss+=sqrt((Rp*cos(\u03b8p)-Rd*cos(\u03b8d))^2+(Rp*sin(\u03b8p)-Rd*sin(\u03b8d))^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    \u03c8=zeros(num_tps)\n    for tp in 1:num_tps\n        psi, rr=OrderParameter(sol[:,tp])\n        R[tp]=rr\n        \u03c8[tp]=psi\n    end\n\n    pl1=plot(\u03c8,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.(\u03c8), 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, \u03c0*rand(kuramoto_model.N))\nkuramoto_model.validationPlot(results_kuramoto.minimizer, 1.5*\u03c0*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": "\n\n# Test for gausslegendre().\n\n\nfor \u03bd=2:10  # check all special cases\n    let (x, w) = gausslegendre(\u03bd)\n        @test dot( w,(x.^2)) \u2248 2/3\n    end\nend\n\ntol = 1e-14\nn = 42\nx, w = gausslegendre(n)\n@test length(x) == n && length(w) == n\n@test \u2248(x[37],0.910959724904127;atol=tol)\n@test \u2248(w[37],0.030479240699603;atol=tol)\n\n@test dot( w,(x.^2)) \u2248 2/3\n@test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\n\n# Test a larger n (using ASY)\nn = 251\nx, w = gausslegendre(n)\n@test all(length(x) == n) && all(length(w) == n)\n@test abs(x[37] + 0.896467746955729) < tol\n@test abs(w[37] - 0.005535005742012) < tol\n\n@test dot( w,(x.^2)) \u2248 2/3\n@test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\n\nx, w = gausslegendre(1013)\n@test norm(x[2] - -0.999985167586110, Inf) < tol\n@test norm(x[13] - -0.999218995240887, Inf) < tol\n@test norm(w[2] - 1.681691163200592e-05, Inf) < tol\n@test norm(w[13] - 1.224755309137936e-04, Inf) < tol\n\n@test dot( w,(x.^2)) \u2248 2/3\n@test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\n\nx, w = gausslegendre(10013)\n@test norm(x[2] - -0.999999848054223, Inf) < tol\n@test norm(x[13] - -0.999991998242661, Inf) < tol\n@test norm(w[2] - 1.722757320118474e-07, Inf) < tol\n@test norm(w[13] - 1.254980540032470e-06, Inf) < tol\n\n@test dot( w,(x.^2)) \u2248 2/3\n@test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\n", "meta": {"hexsha": "f219bf57da89921e4036830b56001a51dfde0a5a", "size": 1249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gausslegendre.jl", "max_stars_repo_name": "timueh/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_stars_repo_licenses": ["MIT"], "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_gausslegendre.jl", "max_issues_repo_name": "timueh/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_issues_repo_licenses": ["MIT"], "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_gausslegendre.jl", "max_forks_repo_name": "timueh/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "cd84806df7e45239e5cc9ada5401af3466a21ad0", "max_forks_repo_licenses": ["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.4897959184, "max_line_length": 52, "alphanum_fraction": 0.6028823058, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7806817439096105}}
{"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": "\n# using Gadfly\nusing DataFrames\n\n\nusing QuadGK\nusing GeneralTools\n\n\nsigma = 0.01;\nmu = 0.0;\n# define the acceleration as a function of normal distribution:\nfn(x) = (sigma*sqrt(2*pi))^-1 * exp(-0.5*((x-mu)/sigma)^2)\n\n\nT = -1.0:0.01:3.0; # define x domain\nA = fn.(T);\n\n\nfunction rsign(v) # sign with tolerance\n\ttol = 10^-5\n\tif -tol < v < tol\n\t\tabsv = 0.0;\n\telse\n\t\tabsv = sign(v);\n\tend\n\treturn absv\nend\n\n# Define damping\nFc = 2.0;\nFv = 4.0; \n# Calculate integration of A\nI_E = quadgk.(fn,minimum(T),collect(T)[2:end]); # (I, E)\nv0 = 0.0;\nvc = copy(v0);\nvv = copy(v0);\nV = Float64[v0];\nVc = copy(V);\nVv = copy(V);\ndts = diff(T);\n\n\nfor (index, value) in enumerate(I_E)\n\tglobal vc, vv\n\tdt = dts[index];\n\tpush!(V, value[1]);\n\t\n\tvc = vc + A[index]*dt - Fc*rsign(vc)*dt;\n\tvv = vv + A[index]*dt - Fv*vv*dt;\n\tpush!(Vc, vc);\n\tpush!(Vv, vv);\nend\n(V, Vc, Vv)\n\n\ndf_wide = DataFrame(\"time\"=>T, \"acceleration\"=>A, \"velocity\"=>V, \"velocity (with damping)\"=> Vc);\n\n\nprintln(\"\"\"A \"wide\" dataframe: \"\"\");\npreview(df_wide,10);\n\n\n# a long dataframe where the three variables are grouped by their column name\ndf_long = stack(df_wide, [\"acceleration\", \"velocity\", \"velocity (with damping)\"]);\n\n\nprintln(\"\"\"The converted \"long\" dataframe: \"\"\");\npreview(df_long,10)\n\n\nplot(df_long, x = \"time\", y=\"value\", color=\"variable\", Geom.line)\n\n", "meta": {"hexsha": "d355ef6921777aa4c139e9042337905a460e5ae3", "size": 1309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/en/notes/julia/imageplot/gadfly/using_gadfly.jl", "max_stars_repo_name": "okatsn/UnpredictableLife", "max_stars_repo_head_hexsha": "8e4877dd10e47448ecd1037686dbbb7efea7a511", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T12:41:35.000Z", "max_issues_repo_path": "content/en/notes/julia/imageplot/gadfly/using_gadfly.jl", "max_issues_repo_name": "okatsn/UnpredictableLife", "max_issues_repo_head_hexsha": "8e4877dd10e47448ecd1037686dbbb7efea7a511", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-09-27T20:17:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T20:40:03.000Z", "max_forks_repo_path": "content/en/notes/julia/imageplot/gadfly/using_gadfly.jl", "max_forks_repo_name": "okatsn/UnpredictableLife", "max_forks_repo_head_hexsha": "8e4877dd10e47448ecd1037686dbbb7efea7a511", "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.6891891892, "max_line_length": 97, "alphanum_fraction": 0.6256684492, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7806817344263652}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.4\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 57c67334-a30d-11ec-3019-012043761a13\nbegin\n\tusing Plots\n\tusing Random\n\timport Distributions as di\n\tusing Statistics\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u201ctrue\u201d 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 \u0394y). 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u255057c67334-a30d-11ec-3019-012043761a13\n# \u255f\u2500287d1794-fe2c-49ba-ad5a-71a130ee14be\n# \u255f\u2500cb547e46-51fb-47ae-97ed-482d89d9c5e5\n# \u2560\u2550b93fcb5e-64b3-4bda-abd4-ade9cedf56ca\n# \u255f\u250061d7c512-c0a0-4341-b97c-ffaf26944b6a\n# \u2560\u25506aa0d42e-e778-48eb-a2a7-d923fa80daea\n# \u255f\u2500ab0da14c-2b52-44d6-a91d-795c669687fb\n# \u255f\u250068c4f411-d5a0-48f0-bbba-8e6901b0408f\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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 \u00d7 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\u00d78 DataFrame\n Row \u2502 Crt1     Crt2     Crt3     Crt4     Crt5     Crt6     Crt7     Crt8    \n     \u2502 Float64  Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502   100.0     92.0     10.0      2.0     80.0     70.0     95.0     80.0\n   2 \u2502    80.0     70.0      8.0      4.0    100.0     80.0     80.0     90.0\n   3 \u2502    90.0     85.0      5.0      0.0     75.0     95.0     70.0     70.0\n   4 \u2502    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": "# Adapted from:\n# SOSDEMO10 --- Set containment\n# Section 3.10 of SOSTOOLS User's Manual\n\nfunction sosdemo10_test(optimizer, config::MOIT.TestConfig)\n    @polyvar x[1:2]\n\n    eps = 1e-6\n    p = x[1]^2+x[2]^2\n    gamma = 1\n    g0 = 2*x[1]\n    theta = 1\n\n    model = _model(optimizer)\n    PolyJuMP.setpolymodule!(model, SumOfSquares)\n\n    # FIXME s should be sos ?\n    # in SOSTools doc it is said to be SOS\n    # but in the demo it is not constrained so\n    Z = monomials(x, 0:4)\n    @variable(model, s, Poly(Z))\n\n    Z = monomials(x, 2:3)\n    @variable(model, g1, Poly(Z))\n\n    Sc = [theta^2-s*(gamma-p) g0+g1; g0+g1 1]\n\n    @SDconstraint(model, Matrix(eps * I, 2, 2) \u2aaf Sc)\n\n    JuMP.optimize!(model)\n\n    # Program is feasible, that is, the set\n    # { x |((g0+g1) + theta)(theta - (g0+g1)) >=0 }\n    # contains the set\n    # { x | p <= gamma }\n\n    # ALMOST_OPTIMAL and NEARLY_FEASIBLE_POINT for CSDP\n    @test JuMP.termination_status(model) in [MOI.OPTIMAL, MOI.ALMOST_OPTIMAL]\n    @test JuMP.primal_status(model) in [MOI.FEASIBLE_POINT, MOI.NEARLY_FEASIBLE_POINT]\n\n    #@show JuMP.value(s)\n    #@show JuMP.value(g1)\nend\nsd_tests[\"sosdemo10\"] = sosdemo10_test\n", "meta": {"hexsha": "ea1df959e68f9bcf409efada7c3ecbecd1faf51d", "size": 1163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Tests/sosdemo10.jl", "max_stars_repo_name": "ericphanson/SumOfSquares.jl", "max_stars_repo_head_hexsha": "3f524f2f8dcf22a9e1c4e0ea549e7166736faeac", "max_stars_repo_licenses": ["MIT"], "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/sosdemo10.jl", "max_issues_repo_name": "ericphanson/SumOfSquares.jl", "max_issues_repo_head_hexsha": "3f524f2f8dcf22a9e1c4e0ea549e7166736faeac", "max_issues_repo_licenses": ["MIT"], "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/Tests/sosdemo10.jl", "max_forks_repo_name": "ericphanson/SumOfSquares.jl", "max_forks_repo_head_hexsha": "3f524f2f8dcf22a9e1c4e0ea549e7166736faeac", "max_forks_repo_licenses": ["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.8444444444, "max_line_length": 86, "alphanum_fraction": 0.6319862425, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7806782138052436}}
{"text": "# # [Nonlinear Time Continuous System](@id nonlinear_continuos)\n#\n# Similarly, we can use the [Extended Dynamic Mode Decomposition](https://link.springer.com/article/10.1007/s00332-015-9258-5) via a nonlinear [`Basis`](@ref) of observables. Here, we will look at a rather [famous example](https://arxiv.org/pdf/1510.03007.pdf) with a finite dimensional solution.\n    \nusing DataDrivenDiffEq\nusing LinearAlgebra\nusing ModelingToolkit\nusing OrdinaryDiffEq\n#md using Plots\n\nfunction slow_manifold(du, u, p, t)\n    du[1] = p[1] * u[1]\n    du[2] = p[2] * (u[2] - u[1]^2)\nend\n\nu0 = [3.0; -2.0]\ntspan = (0.0, 5.0)\np = [-0.8; -0.7]\n\nproblem = ODEProblem(slow_manifold, u0, tspan, p)\nsolution = solve(problem, Tsit5(), saveat = 0.01);\n#md plot(solution) \n\n# Since we are dealing with a continuous system in time, we define the associated [`DataDrivenProblem`](@ref) accordingly using the measured states `X`, their derivatives `DX` and the time `t`.\n    \nprob = ContinuousDataDrivenProblem(solution)\n\n# Additionally, we need to define the [`Basis`](@ref) for our lifting, before we `solve` the problem in the lifted space.\n    \n@parameters t\n@variables u[1:2](t)\n\u03a8 = Basis([u; u[1]^2], u, independent_variable = t)\nres = solve(prob, \u03a8, DMDPINV(), digits = 1)\nsystem = result(res)\n#md println(res) # hide\n#md println(system) # hide\n#md println(parameters(res)) # hide\n\n    \n# The underlying dynamics have been recovered correctly by the algorithm!\n# Similarly we could use sparse identification to solve the problem\n\nsparse_res = solve(prob, \u03a8, STLSQ(), digits = 1)\n#md println(sparse_res)\n\n# And the resulting system\n\nsparse_system = result(sparse_res)\n#md println(sparse_system)\n\n# We can also directly look at the parameters of each result\n\nparameter_map(res)\n\n# Note that we are using [`parameter_map`](@ref) instead of just `parameters`, which returns \n# a vector suitable to use with `ModelingToolkit`.\n\nparameter_map(sparse_res)\n\n# To simulate the system, we create an `ODESystem` from the result\n\n# Both results can be converted into an `ODESystem`\n\n@named sys = ODESystem(\n    equations(sparse_system), \n    get_iv(sparse_system),\n    states(sparse_system), \n    parameters(sparse_system)\n    );\n\n    \nx0 = [u[1] => u0[1], u[2] => u0[2]]\nps = parameter_map(sparse_res)\n    \n# And simulated using `OrdinaryDiffEq.jl` using the (known) initial conditions and the parameter mapping of the estimation.\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(solution, color = :black)\n#md plot!(estimate, color = :red, linestyle = :dash)\n\n#md # ## [Copy-Pasteable Code](@id linear_discrete_copy_paste)\n#md #\n#md # ```julia\n#md # @__CODE__\n#md # ```\n\n## Test #src\nfor r_ in [res, sparse_res] #src\n    @test all(l2error(r_) .< 1e-5) #src\n    @test all(aic(r_) .> 1e3) #src\n    @test all(determination(r_) .>= 0.96) #src\nend #src\n\n", "meta": {"hexsha": "24c46b2f00c5016530cea03f967a90f1f9eea405", "size": 2898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/4_nonlinear_continuous_system.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/4_nonlinear_continuous_system.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/4_nonlinear_continuous_system.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.8762886598, "max_line_length": 296, "alphanum_fraction": 0.7015182885, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.7806782098250017}}
{"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(\u03b1r=0.3, \u03b2rf=0.015, \u03b3rf=0.015, \u03b4f=0.7,                     \n                 \u03b2rh=0.01, \u03b3rh=0.01, \u03b4h=0.5, \n                 \u03b3fishh=0.001, \u03b2fishh=0.003, \n                 \u03b1fish=0.35, \u03b2fishF=0.015, \u03b3fishF=0.015, \n                 \u03b4F=0.7, \u03b2Fs=0.017, \u03b3Fs=0.017, \u03b4s=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.\u03b1r*u\ndotrf(u,p,t) = [-p.\u03b2rf*u[1]*u[2], p.\u03b3rf*u[1]*u[2]]\ndotf(u,p,t) = -p.\u03b4f*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.\u03b2rh*u[1]*u[2], p.\u03b3rh*u[1]*u[2]]\ndoth(u, p, t)  = -p.\u03b4h*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 \u2014- little fish, big fish, and sharks -\u2014 with two predation interactions \u2014- 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.\u03b1fish*f[1] - p.\u03b2fishF*x[1]*f[1]]\ndotFISH(F, x, p, t) = [p.\u03b3fishF*x[1]*F[1] - p.\u03b4F*F[1] - p.\u03b2Fs*x[2]*F[1]]\ndotsharks(s, x, p, t) = [p.\u03b3Fs*s[1]*x[1]-p.\u03b4s*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.\u03b3fishh*u[1]*u[2], -p.\u03b2fishh*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.\u03b2fishh = 0; params.\u03b3fishh = 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,    :(\u03c0*cos(\u03c0*x/180)/180),                :(-\u03c0^2*sin(\u03c0*x/180)/180^2))\n    (  :cosd,    :(-\u03c0*sin(\u03c0*x/180)/180),               :(-\u03c0^2*cos(\u03c0*x/180)/180^2))\n    (  :tand,    :(\u03c0*(tan(\u03c0*x/180)^2 + 1)/180),        :(2*\u03c0^2*(tan(\u03c0*x/180)^2 + 1)*tan(\u03c0*x/180)/180^2))\n    (  :secd,    :(\u03c0*sec(\u03c0*x/180)*tan(\u03c0*x/180)/180),   :(\u03c0^2*sec(\u03c0*x/180)*tan(\u03c0*x/180)^2/180^2 + \u03c0^2*(tan(\u03c0*x/180)^2 + 1)*sec(\u03c0*x/180)/180^2))\n    (  :cscd,    :(-\u03c0*cot(\u03c0*x/180)*csc(\u03c0*x/180)/180),  :(\u03c0^2*cot(\u03c0*x/180)^2*csc(\u03c0*x/180)/180^2 + \u03c0^2*(cot(\u03c0*x/180)^2 + 1)*csc(\u03c0*x/180)/180^2))\n    (  :cotd,    :(-\u03c0*(cot(\u03c0*x/180)^2 + 1)/180),       :(2*\u03c0^2*(cot(\u03c0*x/180)^2 + 1)*cot(\u03c0*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,   :(\u03c0/(sqrt(-\u03c0^2*x^2/180^2 + 1)*180)),  :(\u03c0^3*x/((-\u03c0^2*x^2/180^2 + 1)^(3/2)*180^3)))\n    (  :acosd,   :(-\u03c0/(sqrt(-\u03c0^2*x^2/180^2 + 1)*180)), :(-\u03c0^3*x/((-\u03c0^2*x^2/180^2 + 1)^(3/2)*180^3)))\n    (  :atand,   :(\u03c0/((\u03c0^2*x^2/180^2 + 1)*180)),       :(-2*\u03c0^3*x/((\u03c0^2*x^2/180^2 + 1)^2*180^3)))\n    (  :asecd,   :(1/(sqrt(\u03c0^2*x^2/180^2 - 1)*x)),     :(-\u03c0^2/((\u03c0^2*x^2/180^2 - 1)^(3/2)*180^2) - 1/(sqrt(\u03c0^2*x^2/180^2 - 1)*x^2)))\n    (  :acscd,   :(-1/(sqrt(\u03c0^2*x^2/180^2 - 1)*x)),    :(\u03c0^2/((\u03c0^2*x^2/180^2 - 1)^(3/2)*180^2) + 1/(sqrt(\u03c0^2*x^2/180^2 - 1)*x^2)))\n    (  :acotd,   :(-\u03c0/((\u03c0^2*x^2/180^2 + 1)*180)),      :(2*\u03c0^3*x/((\u03c0^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, :(\u03c0/180),                             :(0))\n    (  :rad2deg, :(180/\u03c0),                             :(0))\n  # ( :erf,     :(2*exp(-x^2)/sqrt(\u03c0)),               :(-4*x*exp(-x^2)/sqrt(\u03c0)))\n  # ( :erfinv,  :(1/2*sqrt(\u03c0)*exp(erfinv(x)^2)),      :(1/2*\u03c0*erfinv(x)*exp(2*erfinv(x)^2)))\n  # ( :erfc,    :(-2*exp(-x^2)/sqrt(\u03c0)),              :(4*x*exp(-x^2)/sqrt(\u03c0)))\n  # ( :erfi,    :(2*exp(x^2)/sqrt(\u03c0)),                :(4*x*exp(x^2)/sqrt(\u03c0)))\n    (  :cospi,   :(-\u03c0*sinpi(x)),                       :(-\u03c0^2*cospi(x)))\n    (  :sinpi,   :(\u03c0*cospi(x)),                        :(-\u03c0^2*sinpi(x)))\n]\n\nchangeprecision(x) = x\nchangeprecision(x::Integer) = :(T($x))\nfunction changeprecision(x::Symbol)\n    x == :\u03c0  ?  :(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\u2032 = changeprecision(rule[2])\n    prec_f\u2032\u2032 = changeprecision(rule[3])\n    DIFF_RULES[i] = (rule[1], prec_f\u2032, prec_f\u2032\u2032)\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\u0303 = sitp.(x)\ny = log.(x)\nplot(x, y\u0303)\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, \u03c60s, A0s [, ub, lb])\r\n\r\nThe quality of the fit depends dramatically on the initial guesses for the phases\r\nand amplitudes, `\u03c60s, 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 `\u03c60 = 0, A0 = abs(-(extrema(s)...))/2, ub = Inf, lb = -Inf` for\r\nall frequencies. (the bounds for the phases are always \u00b1 \u03c0)\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    \u03c60s::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    \u03c60s = 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, \u03c60s, A0s, ub, lb, zero(fs), zero(fs))\r\nend\r\n\r\nSinusoidalFit(fs, \u03c60s, A0s, ub=fill(Inf, length(fs)), lb=fill(-Inf, length(fs))) =\r\nSinusoidalFit{eltype(fs)}(fs, \u03c60s, 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\u03c0 * (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.\u03c60s)\r\n    ub = vcat(method.ub, fill( T(\u03c0), L))\r\n    lb = vcat(method.lb, fill(-T(\u03c0), 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\u20135596\n\nimport Combinatorics: combinations\n\n#### HLLE type\nstruct HLLE{T <: Real} <: AbstractDimensionalityReduction\n    k::Int\n    \u03bb::AbstractVector{T}\n    proj::Projection{T}\n\n    HLLE{T}(k::Int, \u03bb::AbstractVector{T}, proj::Projection{T}) where T = new(k, \u03bb, proj)\nend\n\n## properties\noutdim(R::HLLE) = size(R.proj, 1)\neigvals(R::HLLE) = R.\u03bb\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        \u03bc = mean(X[:, II], dims=2)\n        N = X[:, II] .- \u03bc\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    \u03bb, V = decompose(transpose(W)*W, maxoutdim)\n    return HLLE{T}(k, \u03bb, 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 \u2229 (-1..1)\n    y = y \u2229 (-2..2)\n\n    y = y \u2229 (2x)\n    x = x \u2229 (y/2)\n\n    return IntervalBox(x, y)\nend\n\n\nfunction constant_contractor(X, y_val)\n    x, y = X\n    y = y \u2229 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 \u2229 (x + 1)\n    x = x \u2229 (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 \u2229 (0..\u221e)\n\n    y = y \u2229 (x ^ 3)\n    x = x \u2229 Interval(y.lo ^ (1/3), y.hi^(1/3))   # not rigorous!\n\n    return x \u00d7 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 \u222a 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 \u2229 (a - b)  # y = a - b\n\n    a = a \u2229 (y + b)\n    b = b \u2229 (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": "function nlp_cvx_105_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - e and log expressions\n    # - convex constraint, only in given domains\n    # Variants\n    #   010 - intersection point\n    #   011 - intersection point\n    #   012 - one binding constraint\n    #   013 - one binding constraint\n\n    model = Model(optimizer)\n\n    @variable(model, x, start = 0.1)\n    @variable(model, y)\n\n    @objective(model, Min, -x - y)\n    @NLconstraint(model, exp(x - 2.0) - 0.5 <= y)\n    @NLconstraint(model, log(x) + 0.5 >= y)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -4.176004405036646, tol = objective_tol)\n    return check_solution(\n        [x, y],\n        [2.687422019398147, 1.488582385638499],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "dae3f5e44ab35acd25f9dfc92a535612801aa12e", "size": 953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/105_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/105_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/105_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 25.7567567568, "max_line_length": 76, "alphanum_fraction": 0.6442812172, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7806461917182892}}
{"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    \u03b1::Real\nend\n\noptim_step(s::GD, f, g, x) = -s.\u03b1*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\u03c3(z) = 1/(1+exp(-z))\nplot(-10:0.01:10, \u03c3)\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 = \u03c3.(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 = \u03c3.(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 = \u03c3.(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\u208a = [Knots(3.3, 4.2), Knots(3.8, 3.2, 5.3)]\nM\u2032 = refinement(M, k\u208a = k\u208a)\nsave_png(\"docs/src/img/2dim_h-refinement.png\", M\u2032, unitlength = 50)\n\n## p-Refinement\np\u208a = [1,2]\nM\u2032 = refinement(M, p\u208a = p\u208a)\nsave_png(\"docs/src/img/2dim_p-refinement.png\", M\u2032, 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\u03c0, 2\u03c0, length = 8)) + p * Knots(-2\u03c0, 2\u03c0)\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": "using Test\n\nusing ArnoldiMethod: eigvalues, local_schurfact!, backward_subst!, compute_shifts, initialize, iterate_arnoldi!\nusing LinearAlgebra\n\n@testset \"Shift computation\" begin\n    for j = 1:20\n        n = 20\n        # A = rand(ComplexF64, n,n)\n        A = triu(rand(ComplexF64, n,n))\n        for i = 1:n\n            A[i,i] = i\n        end\n        max = 10\n        arnoldi = initialize(ComplexF64, n, max)\n        iterate_arnoldi!(A, arnoldi, 1:max)\n\n        shifts = compute_shifts(arnoldi.H, 1, max)\n        vals, vecs = eigen(arnoldi.H[1:max, 1:max])\n\n        # Test whether the shifts are the eigenvalues of H\n        @test sort(vals, by=abs) \u2248 sort(shifts, by=abs)\n\n        res = Vector{Float64}(undef,max)\n        for i = 1:max\n            res[i] = norm(A * arnoldi.V[:,1:max] * vecs[:,i] - vals[i] * arnoldi.V[:,1:max] * vecs[:,i])\n        end\n        # @show res\n        perm = sortperm(res, by=abs)\n        vals = vals[perm]\n\n        # Test the order of the shifts\n        @test abs.(vals) \u2248 abs.(shifts)\n        @test vals \u2248 shifts\n    end\nend\n\n# AV = VH\n# A x = lambda x\n# VHV' x = lambda x + res\n# HV' x = lambda V' x + res\n\n# HQ = QR\n# H x = lambda x\n# QRQ' x = lambda x\n# RQ' x = lambda Q' x", "meta": {"hexsha": "031044a1130eeb5108c44cd332a44c4a952370a3", "size": 1208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/compute_shifts.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/compute_shifts.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/compute_shifts.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": 26.2608695652, "max_line_length": 111, "alphanum_fraction": 0.5529801325, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7805736726623755}}
{"text": "#saha function\nfunction fHI(T,ne)\n     \u03c7   = 13.60\n    temp = 15.6826 - log10(ne) + log10(2) + 1.5 * log10(T) - \u03c7 * (5040 / T)\n\n    return temp\nend\n\nfunction fHeI(T,ne)\n     \u03c7   = 24.58\n    temp = 15.6826 - log10(ne) + log10(2) + 1.5 * log10(T) - \u03c7 * (5040 / T)\n\n    return temp\nend\n\nfunction fHeII(T,ne)\n     \u03c7   = 54.41\n    temp = 15.6826 - log10(ne) + log10(2) + 1.5 * log10(T) - \u03c7 * (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    \u03b4   = 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) < \u03b4\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\u22c5x + 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\u22c5x + 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\u22c5P\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\u00d7v1\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\u22c5normal\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\u22c5A + 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, \u03b5::Float64=DUMMY_PRECISION)\n    signed_dist = get_signed_distance(plane, A)\n    if abs(signed_dist) < \u03b5\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_\u03a3_n_\u03bc(x,\u03a3,\u03bc,\u03f5,s_d,T)\r\n    \r\n    \u03bc_new = T*\u03bc/(T+1)+x/(T+1)\r\n    #\u03a3_new = Hermitian((T-1)/T*\u03a3+s_d/T*(T*\u03bc*transpose(\u03bc)-(T+1)*\u03bc_new*transpose(\u03bc_new)+x*transpose(x)+UniformScaling(\u03f5)))\r\n    \u03a3_new = (T-1)/T*\u03a3+s_d/T*(T*(\u03bc*transpose(\u03bc))-(T+1)*(\u03bc_new*transpose(\u03bc_new))+(x*transpose(x))+UniformScaling(\u03f5))   \r\n\r\n    return \u03a3_new,\u03bc_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,\u03a3,\u03bc,\u03f5,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],\u03a3[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            \u03a3[j],\u03bc[j] = mcmc_update_\u03a3_n_\u03bc(reshape(x_current[j],(length(x_current[j]),1)),\u03a3[j],\u03bc[j],\u03f5,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_\u03a3_n_\u03bc!(x_current,P_current,p,sig,n::Integer,n_chains::Integer)\r\n    \r\n    \u03bc = Array{Array{Float64,2},1}(undef,n_chains) #Sample mean\r\n    \u03a3 = 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        \u03bc[j] = transpose(mean(samples, dims=1))\r\n        \u03a3[j] = cov(samples)\r\n    end    \r\n    return \u03a3,\u03bc\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,\u03f5::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 \u03a3 and \u03bc\")\r\n    \u03a3,\u03bc = mcmc_create_\u03a3_n_\u03bc!(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 \u03a3 and \u03bc\")\r\n\r\n    #Run burn-in\r\n    println(\"Start: Burn-in\")\r\n    mcmc_run_ad!(x_current,P_current,p,\u03a3,\u03bc,\u03f5,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,\u03a3,\u03bc,\u03f5,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": "module TheAlgorithms\n\n# Usings/Imports (keep sorted)\nusing LinearAlgebra\nusing Random\n\n\n## Exports\n# Please keep the folders/functions sorted\n\n# Exports: data_structures\nexport AbstractBinaryTree\nexport AbstractBinaryTree_arr\nexport BinaryTree\nexport ch\nexport depth\nexport DisjointSet\nexport find\nexport height\nexport insert!\nexport isleaf\nexport left\nexport merge!\nexport right\n\n# Exports: knapsack\nexport complete_pack!\nexport zero_one_pack!\n\n# Exports: math\nexport SIR # TODO: make the name lowercase if possible\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\nexport collatz_sequence\nexport eratosthenes\nexport euler_method\nexport factorial_iterative\nexport factorial_recursive\nexport floor_val\nexport is_armstrong\nexport line_length\nexport krishnamurthy\nexport mean\nexport median\nexport mode\nexport monte_carlo_integration\nexport prime_check\nexport prime_factors\nexport perfect_cube\nexport perfect_number\nexport perfect_square\nexport prime_check\nexport prime_factors\nexport sum_ap\nexport sum_gp\nexport surfarea_cube\nexport surfarea_sphere\nexport trapazoidal_area\nexport verlet_integration\nexport vol_cube\nexport vol_cuboid\nexport vol_cone\nexport vol_right_circ_cone\nexport vol_prism\nexport vol_pyramid\nexport vol_sphere\nexport vol_circular_cylinder\n\n# Exports: matrix\nexport determinant\nexport lu_decompose\nexport rotation_matrix\n\n# Exports: project-rosalind\nexport count_nucleotides\nexport dna2rna\nexport reverse_complement\n\n# Exports: searches\nexport binary_search\nexport exponential_search\nexport interpolation_search\nexport jump_search\nexport linear_search\n\n# Exports: sorts\nexport BubbleSort!,InsertionSort!,SelectionSort!\n\n# Exports: statistics\nexport OLSbeta # TODO: make the name lowercase if possible\nexport pearson_correlation\nexport variance\n\n# Exports: strings\nexport is_palindrome\nexport detect_anagrams\n\n# Exports: scheduling\nexport fcfs\n\n# Exports: conversions\nexport celsius_to_fahrenheit\nexport celsius_to_kelvin\nexport fahrenheit_to_celsius\nexport fahrenheit_to_kelvin\nexport kelvin_to_celsius\nexport kelvin_to_fahrenheit\nexport weight_conversion\n\n## Includes\n# Please keep the folders/files sorted (by dependencies then alphabetical order)\n\n# Includes: data_structures\ninclude(\"data_structures/binary_tree/basic_binary_tree.jl\")\ninclude(\"data_structures/disjoint_set/disjoint_set.jl\")\n\n# Includes: knapsack\ninclude(\"knapsack/knapsack.jl\")\n\n# Includes: math\ninclude(\"math/abs.jl\")\ninclude(\"math/area.jl\")\ninclude(\"math/area_under_curve.jl\")\ninclude(\"math/armstrong_number.jl\")\ninclude(\"math/average_mean.jl\")\ninclude(\"math/average_median.jl\")\ninclude(\"math/average_mode.jl\")\ninclude(\"math/ceil_floor.jl\") # needed by average_median\ninclude(\"math/collatz_sequence.jl\")\ninclude(\"math/euler_method.jl\")\ninclude(\"math/factorial.jl\")\ninclude(\"math/krishnamurthy_number.jl\")\ninclude(\"math/line_length.jl\")\ninclude(\"math/krishnamurthy_number.jl\")\ninclude(\"math/monte_carlo_integration.jl\")\ninclude(\"math/prime_check.jl\")\ninclude(\"math/prime_factors.jl\")\ninclude(\"math/perfect_cube.jl\")\ninclude(\"math/perfect_number.jl\")\ninclude(\"math/perfect_square.jl\")\ninclude(\"math/prime_check.jl\")\ninclude(\"math/prime_factors.jl\")\ninclude(\"math/sieve_of_eratosthenes.jl\")\ninclude(\"math/sir_model.jl\")\ninclude(\"math/sum_of_arithmetic_series.jl\")\ninclude(\"math/sum_of_geometric_progression.jl\")\ninclude(\"math/verlet.jl\")\ninclude(\"math/volume.jl\")\n\n# Includes: matrix\ninclude(\"matrix/lu_decompose.jl\") # used by determinant.jl\ninclude(\"matrix/determinant.jl\")\ninclude(\"matrix/rotation-matrix.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: scheduling\ninclude(\"scheduling/fcfs.jl\")\n\n# Includes: search\ninclude(\"searches/binary_search.jl\")\ninclude(\"searches/exponential_search.jl\")\ninclude(\"searches/interpolation_search.jl\")\ninclude(\"searches/jump_search.jl\")\ninclude(\"searches/linear_search.jl\")\n\n# Includes: sorts\ninclude(\"sorts/bubble_sort.jl\")\ninclude(\"sorts/insertion_sort.jl\")\ninclude(\"sorts/selection_sort.jl\")\n\n# Includes: statistics\ninclude(\"statistics/ordinary_least_squares.jl\")\ninclude(\"statistics/pearson_correlation.jl\")\ninclude(\"statistics/variance.jl\")\n\n# Includes: strings\ninclude(\"strings/is_palindrome.jl\")\ninclude(\"strings/detect_anagrams.jl\")\n\n# Includes: scheduling\ninclude(\"scheduling/fcfs.jl\")\n\n# Includes: conversions\ninclude(\"conversions/weight_conversion.jl\")\ninclude(\"conversions/temparature_conversion.jl\")\n\nend\n", "meta": {"hexsha": "9f94ff01208792d36b8a34e8c1fb50ca913eb0fa", "size": 4687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TheAlgorithms.jl", "max_stars_repo_name": "mayurdahibhate/Julia", "max_stars_repo_head_hexsha": "577a80b2a39c60480059930de80fe5cfdedbffb4", "max_stars_repo_licenses": ["MIT"], "max_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": "mayurdahibhate/Julia", "max_issues_repo_head_hexsha": "577a80b2a39c60480059930de80fe5cfdedbffb4", "max_issues_repo_licenses": ["MIT"], "max_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": "mayurdahibhate/Julia", "max_forks_repo_head_hexsha": "577a80b2a39c60480059930de80fe5cfdedbffb4", "max_forks_repo_licenses": ["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.0886699507, "max_line_length": 80, "alphanum_fraction": 0.8312353318, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.780562138284309}}
{"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": "# ## polar plots\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\n## ref https://jp.mathworks.com/matlabcentral/fileexchange/35285-matlab-plot-gallery-function-polar-plot?focused=6793167&tab=example\nr(\u03b8) = 1 + cos(\u03b8) * sin(\u03b8)^2\nplot(r, 0, 2\u03c0, proj=:polar, lims=(0,1.5))\n\n#-\n\nr(\u03b8) = 1 + cos(\u03b8) * sin(\u03b8)^2\n\u03b8 = range(0, stop=2\u03c0, length=50)\nplot(\u03b8, r.(\u03b8), proj=:polar, lims=(0,1.5))\n", "meta": {"hexsha": "aea9290de9d189d6d65e9814eadafaadc3a95e43", "size": 377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/polar.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/polar.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/polar.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": 26.9285714286, "max_line_length": 132, "alphanum_fraction": 0.6472148541, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7805448368003348}}
{"text": "\nfunction main()\n\tN = 2_000_000\n\tres = 0\n\tfor i = 1:N\n\t\tif isprime(i)\n\t\t\tres += i\n\t\tend\n\tend\n\tprintln(res)\nend\n\nmain()\n", "meta": {"hexsha": "177f797daf8808d18dd7ffe9ec575166a37a603f", "size": 119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem10.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": "problem10.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": "problem10.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": 8.5, "max_line_length": 15, "alphanum_fraction": 0.5798319328, "num_tokens": 48, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9748211539104334, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7805315060462666}}
{"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=[\"\u03b1=0.1\" \"\u03b1=0.2\" \"\u03b1=0.3\" \"\u03b1=0.4\" \"\u03b1=0.5\" \"\u03b1=0.6\" \"\u03b1=0.7\" \"\u03b1=0.8\" \"\u03b1=0.9\" \"\u03b1=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,\u03bc=0,\u03c3=1) = a*exp(-0.5((x-\u03bc)/\u03c3)^2)\nfunction gaussianf(x,y;a=1,\u03bc\u2081=0,\u03c3\u2081=1,\u03bc\u2082=0,\u03c3\u2082=1,\u03b8=0)\n    sinv,cosv = sincos(\u03b8)\n    x\u2080 = x-\u03bc\u2081\n    y\u2080 = y-\u03bc\u2082\n    x\u2032 = cosv * x\u2080 + sinv * y\u2080\n    y\u2032 = cosv * y\u2080 - sinv * x\u2080\n    a*exp(-0.5((x\u2032/\u03c3\u2081)^2 + (y\u2032/\u03c3\u2082)^2))\nend\n\n\"\"\"\n`von Mises` function [^1]\n\n```math\nf(\u03b1) =  \u03b2e^{\u03ba(cos(n(\u03b1 - \u03bc)) - 1)}\n```\n\n[^1]\n\nSwindale, N.V. (1998). Orientation tuning curves: empirical description and estimation of parameters. Biol Cybern 78, 45\u201356.\n\n- \u03b2: amplitude at \u03bc\n- \u03bc: angle of peak\n- \u03ba: width parameter\n- n: frequency parameter\n\"\"\"\nvmf(\u03b1;\u03b2=1,\u03bc=0,\u03ba=1,n=1) = \u03b2*exp(\u03ba*(cos(n*(\u03b1-\u03bc))-1))\n\"\"\"\n`Generalized von Mises` function [^1]\n\n```math\nf(\u03b1) =  \u03b2e^{\u03ba\u2081(cos(\u03b1 - \u03bc\u2081) - 1) + \u03ba\u2082(cos2(\u03b1 - \u03bc\u2082) - 1)}\n```\n\n[^1]\n\nGatto, R., and Jammalamadaka, S.R. (2007). The generalized von Mises distribution. Statistical Methodology 4, 341\u2013353.\n\"\"\"\ngvmf(\u03b1;\u03b2=1,\u03bc\u2081=0,\u03ba\u2081=1,\u03bc\u2082=0,\u03ba\u2082=1) = \u03b2*exp(\u03ba\u2081*cos(\u03b1-\u03bc\u2081) + \u03ba\u2082*cos(2(\u03b1-\u03bc\u2082)))\n\n\"\"\"\n`Difference of Gaussians` function\n\"\"\"\ndogf(x;a\u2091=2,\u03bc\u2091=0,\u03c3\u2091=1,a\u1d62=1,\u03bc\u1d62=0,\u03c3\u1d62=2) = a\u2091*exp(-0.5((x-\u03bc\u2091)/\u03c3\u2091)^2) - a\u1d62*exp(-0.5((x-\u03bc\u1d62)/\u03c3\u1d62)^2)\nfunction dogf(x,y;a\u2091=2,\u03bc\u2091\u2081=0,\u03c3\u2091\u2081=1,\u03bc\u2091\u2082=0,\u03c3\u2091\u2082=1,\u03b8\u2091=0,a\u1d62=1,\u03bc\u1d62\u2081=0,\u03c3\u1d62\u2081=2,\u03bc\u1d62\u2082=0,\u03c3\u1d62\u2082=2,\u03b8\u1d62=0)\n    sinv\u2091,cosv\u2091 = sincos(\u03b8\u2091)\n    x\u2091\u2080 = x-\u03bc\u2091\u2081\n    y\u2091\u2080 = y-\u03bc\u2091\u2082\n    x\u2091\u2032 = cosv\u2091 * x\u2091\u2080 + sinv\u2091 * y\u2091\u2080\n    y\u2091\u2032 = cosv\u2091 * y\u2091\u2080 - sinv\u2091 * x\u2091\u2080\n    sinv\u1d62,cosv\u1d62 = sincos(\u03b8\u1d62)\n    x\u1d62\u2080 = x-\u03bc\u1d62\u2081\n    y\u1d62\u2080 = y-\u03bc\u1d62\u2082\n    x\u1d62\u2032 = cosv\u1d62 * x\u1d62\u2080 + sinv\u1d62 * y\u1d62\u2080\n    y\u1d62\u2032 = cosv\u1d62 * y\u1d62\u2080 - sinv\u1d62 * x\u1d62\u2080\n    a\u2091*exp(-0.5((x\u2091\u2032/\u03c3\u2091\u2081)^2 + (y\u2091\u2032/\u03c3\u2091\u2082)^2)) - a\u1d62*exp(-0.5((x\u1d62\u2032/\u03c3\u1d62\u2081)^2 + (y\u1d62\u2032/\u03c3\u1d62\u2082)^2))\nend\n\n\"\"\"\n`sin` grating function\n\n- \u03bc: x offset\n- f: Frequency in cycle/unit_x\n- phase: Phase of a cycle in [0, 1] scale\n\"\"\"\ngratingf(x;\u03bc=0, f=1, phase=0) = sin(2\u03c0 * (f * (x-\u03bc) + phase))\n\n\"\"\"\n2D `sin` grating function\n\n- \u03bc\u2081: x offset\n- \u03bc\u2082: y offset\n- \u03b8: 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;\u03bc\u2081=0,\u03bc\u2082=0,\u03b8=0,f=1,phase=0)\n    sin\u03b8,cos\u03b8 = sincos(\u03b8)\n    y\u2032 = cos\u03b8 * (y-\u03bc\u2082) - sin\u03b8 * (x-\u03bc\u2081)\n    sin(2\u03c0 * (f * y\u2032 + 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 [-\u221a2, \u221a2] to [-1, 1]\n\"\"\"\nfunction cas(x;f=1, phase=0, isnorm::Bool=true)\n    r = sum(sincos(2\u03c0 * (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 [-\u221a2, \u221a2] to [-1, 1]\n\"\"\"\nfunction cas(x,y;kx=1,ky=1, phase=0, isnorm::Bool=true)\n    r = sum(sincos(2\u03c0 * (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) = \u221a2 sin(x + \u03c0/4)``\n\"\"\"\ncas2sin(phase) = phase + 0.125\n\n\"\"\"\n2D `cas` to 2D sin `gratingf`\n\"\"\"\nfunction cas2sin(kx,ky,phase)\n    \u03b8 = atan(ky,kx) - \u03c0/2\n    f = sqrt(kx*kx + ky*ky)\n    return (\u03b8=\u03b8,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) = \u221a2 sin(x + \u03c0/4)``\n\"\"\"\nsin2cas(phase) = phase - 0.125\n\n\"\"\"\n2D sin `gratingf` to 2D `cas`\n\"\"\"\nfunction sin2cas(\u03b8,f,phase)\n    sin\u03b8,cos\u03b8 = sincos(\u03b8 + \u03c0/2)\n    kx = cos\u03b8*f\n    ky = sin\u03b8*f\n    return (kx=kx,ky=ky,phase=phase - 0.125)\nend\n\n\"`Gabor` function\"\ngaborf(x;a=1,\u03bc=0,\u03c3=1,f=1,phase=0) = a*exp(-0.5((x-\u03bc)/\u03c3)^2)*sin(2\u03c0*(f*(x-\u03bc)+phase))\nfunction gaborf(x,y;a=1,\u03bc\u2081=0,\u03c3\u2081=1,\u03bc\u2082=0,\u03c3\u2082=1,\u03b8=0,f=1,phase=0)\n    sinv,cosv = sincos(\u03b8)\n    x\u2080 = x-\u03bc\u2081\n    y\u2080 = y-\u03bc\u2082\n    x\u2032 = cosv * x\u2080 + sinv * y\u2080\n    y\u2032 = cosv * y\u2080 - sinv * x\u2080\n    a*exp(-0.5((x\u2032/\u03c3\u2081)^2 + (y\u2032/\u03c3\u2082)^2)) * sin(2\u03c0*(f * y\u2032 + phase))\nend\n\n\"Binary mask for gabor envelope\"\nfunction gaborenvelopemask(x,y;f\u03c3=2.5,\u03bc\u2081=0,\u03c3\u2081=1,\u03bc\u2082=0,\u03c3\u2082=1,\u03b8=0)\n    sinv,cosv = sincos(\u03b8)\n    x\u2080 = x-\u03bc\u2081\n    y\u2080 = y-\u03bc\u2082\n    x\u2032 = cosv * x\u2080 + sinv * y\u2080\n    y\u2032 = cosv * y\u2080 - sinv * x\u2080\n    (x\u2032/f\u03c3/\u03c3\u2081)^2 + (y\u2032/f\u03c3/\u03c3\u2082)^2 <= 1 ? true : false\nend\n\"Binary mask for concentric circular dog envelope\"\ndogenvelopemask(x,y;f\u03c3=2.5,\u03bc\u2081=0,\u03c3\u2091\u2081=1,\u03bc\u2082=0,r\u03c3\u1d62\u2091=2) = edogenvelopemask(x,y;f\u03c3,\u03bc\u2081,\u03c3\u2091\u2081,r\u03c3\u2082\u2081=1,\u03bc\u2082,r\u03c3\u1d62\u2091,\u03b8=0)\n\"Binary mask for concentric orientated elliptical dog envelope\"\nfunction edogenvelopemask(x,y;f\u03c3=2.5,\u03bc\u2081=0,\u03c3\u2091\u2081=1,r\u03c3\u2082\u2081=1,\u03bc\u2082=0,r\u03c3\u1d62\u2091=2,\u03b8=0)\n    sinv,cosv = sincos(\u03b8)\n    x\u2080 = x-\u03bc\u2081\n    y\u2080 = y-\u03bc\u2082\n    x\u2032 = cosv * x\u2080 + sinv * y\u2080\n    y\u2032 = cosv * y\u2080 - sinv * x\u2080\n    \u03c3\u2081 = max(\u03c3\u2091\u2081,r\u03c3\u1d62\u2091*\u03c3\u2091\u2081)\n    \u03c3\u2082 = \u03c3\u2081 * r\u03c3\u2082\u2081\n    (x\u2032/f\u03c3/\u03c3\u2081)^2 + (y\u2032/f\u03c3/\u03c3\u2082)^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,\u03b2=p[1],\u03bc=p[2],\u03ba=p[3],n=2)\n        ofun = (p;x=x,y=y) -> sum((y.-fun(x,p)).^2)\n\n        ub=[1.8ab,   prevfloat(float(\u03c0)),   200]\n        lb=[0.2ab,            0,              0]\n        p0=[ab,               0,              1]\n    elseif model == :gvm\n        # fun = (x,p) -> gvmf.(x,\u03b2=p[1],\u03bc\u2081=p[2],\u03ba\u2081=p[3],\u03bc\u2082=p[4],\u03ba\u2082=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\u03c0)),   40,    prevfloat(float(\u03c0)),     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\u2091=p[1],\u03bc\u2091=p[2],\u03c3\u2091=p[3],a\u1d62=p[4],\u03bc\u1d62=p[5],\u03c3\u1d62=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\u2091=p[1],\u03bc\u2091=p[2],\u03c3\u2091=p[3],a\u1d62=p[4],\u03bc\u1d62=p[5],\u03c3\u1d62=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],\u03bc=p[2],\u03c3=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,\u03b2=p[1],\u03bc\u2081=p[2],\u03ba\u2081=p[3],\u03bc\u2082=p[4],\u03ba\u2082=p[5])\nsfdogff(x,p) = dogf.(x,a\u2091=p[1],\u03bc\u2091=p[2],\u03c3\u2091=p[3],a\u1d62=p[4],\u03bc\u1d62=p[5],\u03c3\u1d62=p[6]) .+ p[7]\nsfgaussianff(x,p) = gaussianf.(log2.(x),a=p[1],\u03bc=p[2],\u03c3=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\u2091=p[1],\u03bc\u2091\u2081=p[2],\u03c3\u2091\u2081=p[3],\u03bc\u2091\u2082=p[4],\u03c3\u2091\u2082=p[3],\u03b8\u2091=0,a\u1d62=p[5],\u03bc\u1d62\u2081=p[2],\u03c3\u1d62\u2081=p[6]*p[3],\u03bc\u1d62\u2082=p[4],\u03c3\u1d62\u2082=p[6]*p[3],\u03b8\u1d62=0)\n        # mfun = (x,y,p) -> dogenvelopemask.(x,y;f\u03c3=2.5,\u03bc\u2081=p[2],\u03bc\u2082=p[4],\u03c3\u2091\u2081=p[3],r\u03c3\u1d62\u2091=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\u2091=p[1],\u03bc\u2091\u2081=p[2],\u03c3\u2091\u2081=p[3],\u03bc\u2091\u2082=p[4],\u03c3\u2091\u2082=p[5]*p[3],\u03b8\u2091=p[6],a\u1d62=p[7],\u03bc\u1d62\u2081=p[2],\u03c3\u1d62\u2081=p[8]*p[3],\u03bc\u1d62\u2082=p[4],\u03c3\u1d62\u2082=p[5]*p[8]*p[3],\u03b8\u1d62=p[6])\n        # mfun = (x,y,p) -> edogenvelopemask.(x,y;f\u03c3=2.5,\u03bc\u2081=p[2],\u03bc\u2082=p[4],\u03c3\u2091\u2081=p[3],r\u03c3\u2082\u2081=p[5],r\u03c3\u1d62\u2091=p[8],\u03b8=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(\u03c0)),    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],\u03bc\u2081=p[2],\u03c3\u2081=p[3],\u03bc\u2082=p[4],\u03c3\u2082=p[5]*p[3],\u03b8=p[6],f=p[7],phase=p[8])\n        # mfun = (x,y,p) -> gaborenvelopemask.(x,y;f\u03c3=2.5,\u03bc\u2081=p[2],\u03bc\u2082=p[4],\u03c3\u2081=p[3],\u03c3\u2082=p[5]*p[3],\u03b8=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(\u03c0)),     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\u2091=p[1],\u03bc\u2091\u2081=p[2],\u03c3\u2091\u2081=p[3],\u03bc\u2091\u2082=p[4],\u03c3\u2091\u2082=p[3],\u03b8\u2091=0,a\u1d62=p[5],\u03bc\u1d62\u2081=p[2],\u03c3\u1d62\u2081=p[6]*p[3],\u03bc\u1d62\u2082=p[4],\u03c3\u1d62\u2082=p[6]*p[3],\u03b8\u1d62=0)\nedogff(x,y,p) = dogf.(x,y,a\u2091=p[1],\u03bc\u2091\u2081=p[2],\u03c3\u2091\u2081=p[3],\u03bc\u2091\u2082=p[4],\u03c3\u2091\u2082=p[5]*p[3],\u03b8\u2091=p[6],a\u1d62=p[7],\u03bc\u1d62\u2081=p[2],\u03c3\u1d62\u2081=p[8]*p[3],\u03bc\u1d62\u2082=p[4],\u03c3\u1d62\u2082=p[5]*p[8]*p[3],\u03b8\u1d62=p[6])\ngaborff(x,y,p) = gaborf.(x,y,a=p[1],\u03bc\u2081=p[2],\u03c3\u2081=p[3],\u03bc\u2082=p[4],\u03c3\u2082=p[5]*p[3],\u03b8=p[6],f=p[7],phase=p[8])\ndogfmf(x,y,p) = dogenvelopemask.(x,y;f\u03c3=2.5,\u03bc\u2081=p[2],\u03bc\u2082=p[4],\u03c3\u2091\u2081=p[3],r\u03c3\u1d62\u2091=p[6])\nedogfmf(x,y,p) = edogenvelopemask.(x,y;f\u03c3=2.5,\u03bc\u2081=p[2],\u03bc\u2082=p[4],\u03c3\u2091\u2081=p[3],r\u03c3\u2082\u2081=p[5],r\u03c3\u1d62\u2091=p[8],\u03b8=p[6])\ngaborfmf(x,y,p) = gaborenvelopemask.(x,y;f\u03c3=2.5,\u03bc\u2081=p[2],\u03bc\u2082=p[4],\u03c3\u2081=p[3],\u03c3\u2082=p[5]*p[3],\u03b8=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\u00b2\n- s: Residual Standard Error\n- aic: Akaike Information Criterion\n- bic: Bayesian Information Criterion\n\n1. y: responses\n2. y\u0302: model predictions\n\n- n: sample size\n- e: errors(y - y\u0302)\n- k: number of predictors\n- df: degree of freedom(n - k - 1)\n\"\"\"\nfunction goodnessoffit(y,y\u0302;n = length(y),e = y .- y\u0302,k=missing,df = n-k-1)\n    r = cor(y,y\u0302)\n    ae = abs.(e)\n    e2 = e.^2\n    ss\u1d63 = sum(e2)\n    mae = mean(ae)\n    rmse = sqrt(mean(e2))\n    ydm = y .- mean(y)\n    ss\u209c = sum(ydm.^2)\n    rae = sum(ae)/sum(abs.(ydm))\n    fvu = ss\u1d63/ss\u209c\n    rse = sqrt(fvu)\n    r2 = 1 - fvu\n    s = ss\u1d63/df\n    s = s < 0 ? missing : sqrt(s)\n    adjr2 = 1 - fvu*(n-1)/df\n    aic = n*log(ss\u1d63) + 2k\n    bic = n*log(ss\u1d63/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=[\u03c0,0.5\u03c0],fn=:a,x = 0:0.002:2\u03c0) = circtuningfeature(x,predict(mfit,x);od,fn) # 0.002rad \u2248 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. \u03c0 for DSI, 0.5\u03c0 for OSI\n- fn: factor name\n\"\"\"\nfunction circtuningfeature(x,y;od=[\u03c0,0.5\u03c0],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 -/\u2192, 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 \u2191(90)\n        - when Direction is \u2192(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        \u03b8 = mod2pi.(deg2rad.(ls))\n        \u03b1 = mod2pi.(deg2rad.(fl))\n        d = mean(diff(sort(unique(\u03b1)))) # angle spacing\n        up, = circ_otest(\u03b1,w=fm) # Omnibus test for non-uniformity\n        # for orientation\n        o\u03b1 = mod.(\u03b1,\u03c0)\n        ocv, = circ_var(2o\u03b1,w=fm,d=2d)\n        ocm, = circ_mean(2o\u03b1,w=fm)\n        ocm = rad2deg(mod2pi(ocm)/2)\n        # for direction\n        dcv, = circ_var(\u03b1;w=fm,d)\n        dcm, = circ_mean(\u03b1,w=fm)\n        dcm = rad2deg(mod2pi(dcm+0.5\u03c0))\n        maxr,maxi = findmax(fm)\n        maxl = fl[maxi]\n\n        fit = ()\n        if isfit\n            try\n                mfit = fitmodel(:gvm,\u03b8,rs) # fit Generalized von Mises\n                fit = (;circtuningfeature(mfit,od=[\u03c0,0.5\u03c0],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        \u03b8 = deg2rad.(fl)\n        d = mean(diff(sort(unique(\u03b8)))) # angle spacing\n        # for orientation\n        o\u03b8 = mod.(\u03b8.-0.5\u03c0,\u03c0)\n        om, = circ_mean(2o\u03b8,w=fr)\n        oo = rad2deg(mod(angle(om),2\u03c0)/2)\n        ocv = circ_var(2o\u03b8,w=fr,d=2d)\n        # for direction\n        dm, = circ_mean(\u03b8,w=fr)\n        od = rad2deg(mod(angle(dm),2\u03c0))\n        dcv = circ_var(\u03b8;w=fr,d)\n        # fit Generalized von Mises for direction\n        fit = ()\n        if isfit\n            try\n                mfit = fitmodel(:gvm,\u03b8,fr)\n                fit = (circtuningfeature(mfit,od=\u03c0,fn=:d)...,gvm=mfit)\n            catch\n            end\n            # fit von Mises for orientation\n            try\n                mfit = fitmodel(:vmn2, \u03b8.-0.5\u03c0,fr)\n                fit =(fit...,circtuningfeature(mfit, od=0.5\u03c0,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,\u03b8,fr)\n                fit = (circtuningfeature(mfit,od=\u03c0,fn=:h)...,gvm=mfit)\n            catch\n            end\n            # fit von Mises for hue axis\n            try\n                mfit = fitmodel(:vmn2,\u03b8,fr)\n                fit = (fit...,circtuningfeature(mfit,od=0.5\u03c0,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        \u03b8 = mod2pi.(deg2rad.(ls))\n        \u03b1 = mod2pi.(deg2rad.(fl))\n        d = mean(diff(sort(unique(\u03b1)))) # angle spacing\n        up, = circ_otest(\u03b1,w=fm) # Omnibus test for non-uniformity\n        # for axis\n        a\u03b1 = mod.(\u03b1,\u03c0)\n        acv, = circ_var(2a\u03b1,w=fm,d=2d)\n        acm, = circ_mean(2a\u03b1,w=fm)\n        acm = rad2deg(mod2pi(acm)/2)\n        # for angle\n        cv, = circ_var(\u03b1;w=fm,d)\n        cm, = circ_mean(\u03b1,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,\u03b8,rs) # fit Generalized von Mises\n                fit = (;circtuningfeature(mfit,od=[\u03c0,0.5\u03c0],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\u1d40x)\u207b\u00b9`` 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*\u03c0*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,\u03c3=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\u20131697.)\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        \u03bb1 = mean(mean(bst1,dims=1))\n        \u03bb2 = mean(mean(bst2,dims=1))\n        gmsr = sqrt(\u03bb1*\u03bb2)\n        \u0398 = n.-abs.(x)\n        normfactor = 1 ./ \u0398 ./ 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\u03b1\", \"4C\u03b2\", \"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,\u03b1,v)\n  @assert(0 \u2264 \u03b1 < 1, \"needs probably \u03b1\")\n  @assert(all(vi -> vi \u2265 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(\u03b1)) # 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-\u03b1)*v[j]  + \u03b1*(A[:,j]'*idx)\n      gamma = rhs/(1 - \u03b1*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(\u03b1, \u03b2, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Gamma(`\u03b1`, `\u03b2`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Gamma distribution is given:\n\n``f(x,\u03b1,\u03b2) = \\\\frac{\u03b2^\u03b1 x^{\u03b1-1} e^{-\u03b2x}}{\u0393(\u03b1)} \\\\quad x \u2265 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\u00d72 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(\u03b1::Real, \u03b2::Real=1, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    seed_setter(seed)\n    X = \u03b2 .* get_gamma_rv(\u03b1, shape)\n    return X\nend\n\n\nfunction get_gamma_rv(\u03b1::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    seed_setter(seed)\n    if \u03b1 < 0\n        throw(ArgumentError(\"Not implemented for \u03b1 < 0.\"))\n    elseif \u03b1 == 1\n        return expon_rng(1, shape)\n    elseif \u03b1 < 1\n        X = zeros(shape)\n        X .= get_gamma_ad.(\u03b1)\n        return X\n    else \n        X = zeros(shape)\n        X .= get_gamma_gb.(\u03b1)\n        return X\n    end\nend\n\n\nfunction get_gamma_ad(\u03b1::Real; max_iter=300)\n    b = (\u212f + \u03b1)/\u212f\n    i = 0\n    while i < max_iter\n        U\u2081 = get_std_uniform()[1]\n        P = b*U\u2081\n        if P > 1\n            Y = -log((b-P)/\u03b1)\n            U\u2082 = get_std_uniform()[1]\n            if U\u2082 \u2264 Y^(\u03b1-1)\n                return Y\n            end\n        else\n            Y = P^(1/\u03b1)\n            U\u2082 = get_std_uniform()[1]\n            if U\u2082 \u2264 \u212f^(-Y)\n                return Y\n            end\n        end\n        i +=1\n    end\nend\n\n\nfunction get_gamma_gb(\u03b1::Real; max_iter=300)\n    a = 1 / sqrt(2*\u03b1 - 1)\n    b = \u03b1 - log(4)\n    q = \u03b1 + 1/a\n    \u03b8 = 4.5\n    d = 1 + log(\u03b8)\n    i = 0\n    while i < max_iter\n        U\u2081, U\u2082 = get_std_uniform(2)\n        V = a * log(U\u2081/(1-U\u2081))\n        Y = \u03b1 * \u212f^V\n        Z = U\u2081^2 * U\u2082\n        W = b + q * V - Y\n        if W + d - \u03b8 * Z \u2265 0\n            return Y\n        elseif W \u2265 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": "using NNlib, Test\n\n@testset \"NNlib\" begin\n\ninclude(\"activation.jl\")\ninclude(\"conv.jl\")\n\nxs = [-100_000, -100_000.]\n@test softmax(xs) \u2248 [0.5, 0.5]\n@test logsoftmax(xs) \u2248 log.([0.5, 0.5])\n\nxs = rand(5)\n@test softmax(xs) \u2248 exp.(xs) ./ sum(exp.(xs))\n@test logsoftmax(xs) \u2248 log.(softmax(xs))\n@test logsigmoid.(xs) \u2248 log.(sigmoid.(xs))\n\nxs = rand(5,10)\n@test softmax(xs) \u2248 exp.(xs) ./ sum(exp.(xs), dims = 1)\n@test logsoftmax(xs) \u2248 log.(softmax(xs))\n@test logsigmoid.(xs) \u2248 log.(sigmoid.(xs))\n\nfor T in [:Float32, :Float64]\n  @eval @test logsigmoid.($T[-100_000, 100_000.]) \u2248 $T[-100_000, 0.]\nend\n\n## compare the outputs with the PyTorch nn.LogSoftmax returns\nxs = Float32[1, 2, 3000.]\n@test logsoftmax(xs) \u2248 [-2999, -2998, 0]\n\nxs = Float32[1 2 3; 1000 2000 3000]\n@test logsoftmax(xs) \u2248 [-999 -1998 -2997; 0 0 0.]\n\n@test NNlib.\u2207logsoftmax(ones(size(xs)), xs) \u2248 zeros(Float32, size(xs))\n@test NNlib.\u2207softmax(ones(size(xs)), xs) \u2248 zeros(Float32, size(xs))\n\nxs = [-0.238639 0.748142 -0.283194 -0.525461 -1.5348 -0.797842; 0.690384 0.211427 0.254794 -0.213572 -0.314174 -0.372663; -1.14637 -0.577988 0.718952 0.91972 -0.620773 0.929977]\n@test isapprox(NNlib.\u2207logsoftmax(ones(size(xs)), xs), [0.237703 -0.621474 0.448193 0.546047 0.564185 0.632273; -0.930163 0.0519798 0.0549979 0.3799 -0.477112 0.437428; 0.69246 0.569494 -0.503191 -0.925947 -0.0870738 -1.0697]; rtol = 1e-6)\n@test isapprox(NNlib.\u2207softmax(ones(size(xs)), xs), zeros(size(xs)); atol = 1e-6)\nend\n", "meta": {"hexsha": "901c1e2c123cbc3d18d1506a2ba4f2f524283c17", "size": 1451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "thebhatman/NNlib.jl", "max_stars_repo_head_hexsha": "d07ac0bfd3c71c3a29bc9c22becbba19227bbeb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-02T21:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:42.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "MJ10/NNlib.jl", "max_issues_repo_head_hexsha": "d07ac0bfd3c71c3a29bc9c22becbba19227bbeb5", "max_issues_repo_licenses": ["MIT"], "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": "MJ10/NNlib.jl", "max_forks_repo_head_hexsha": "d07ac0bfd3c71c3a29bc9c22becbba19227bbeb5", "max_forks_repo_licenses": ["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.275, "max_line_length": 238, "alphanum_fraction": 0.660923501, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.7804892124776718}}
{"text": "# The following iterative sequence is defined for the set of positive integers:\n#\n# n \u2192 n/2 (n is even)\n# n \u2192 3n + 1 (n is odd)\n#\n# Using the rule above and starting with 13, we generate the following sequence:\n#\n# 13 \u2192 40 \u2192 20 \u2192 10 \u2192 5 \u2192 16 \u2192 8 \u2192 4 \u2192 2 \u2192 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": "@testset \"Gabor\" begin\n    v1 = rand(3)\n    v2 = rand(3)\n    ell = abs(rand())\n    p = abs(rand())\n    k = GaborKernel(; ell=ell, p=p)\n    @test k.ell \u2248 ell atol = 1e-5\n    @test k.p \u2248 p atol = 1e-5\n\n    k_manual = exp(-sqeuclidean(v1, v2) / (2 * k.ell^2)) * cospi(euclidean(v1, v2) / k.p)\n    @test k(v1, v2) \u2248 k_manual atol = 1e-5\n\n    lhs_manual = transform(SqExponentialKernel(), 1 / k.ell)(v1, v2)\n    rhs_manual = transform(CosineKernel(), 1 / k.p)(v1, v2)\n    @test k(v1, v2) \u2248 lhs_manual * rhs_manual atol = 1e-5\n\n    k = GaborKernel()\n    @test k.ell \u2248 1.0 atol = 1e-5\n    @test k.p \u2248 1.0 atol = 1e-5\n    @test repr(k) == \"Gabor Kernel (ell = 1.0, p = 1.0)\"\n\n    test_interface(k, Vector{Float64})\n\n    test_ADs(x -> GaborKernel(; ell=x[1], p=x[2]), [ell, p]; ADs=[:Zygote])\n\n    # Tests are also failing randomly for ForwardDiff and ReverseDiff but randomly\nend\n", "meta": {"hexsha": "472327d878d3e3df0aa69e307d69f27ff3a8f2eb", "size": 872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/gabor.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": "test/basekernels/gabor.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": "test/basekernels/gabor.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": 31.1428571429, "max_line_length": 89, "alphanum_fraction": 0.5825688073, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7804892091693023}}
{"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\u201313.\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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Statistics, Distributions, DataFrames, CSV\n\tusing HypothesisTests\nend;\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.10\"\n\n# \u2554\u2550\u2561 fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tdata = CSV.read(datadir(\"machine1.csv\"), DataFrame; delim=\",\")[:, 1]\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d0a56572-3b2a-11eb-383a-f94fe2f45a5b\nText(\"Confidence interval for the variance: $ci\")\n\n# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.10\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u2550d0a56572-3b2a-11eb-383a-f94fe2f45a5b\n# \u255f\u2500475ff888-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\u00e9e 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\u2080 = 0.35875\n    a\u2081 = 0.48829\n    a\u2082 = 0.14128\n    a\u2083 = 0.01168\n    return @. a\u2080 - a\u2081*cos(n) + a\u2082*cos(2n) - a\u2083*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/\u03c9\u2074\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\u2080 = 0.215578950\n    a\u2081 = 0.416631580\n    a\u2082 = 0.277263158\n    a\u2083 = 0.083578947\n    a\u2084 = 0.006947368\n    return @. a\u2080 - a\u2081*cos(n) + a\u2082*cos(2n) - a\u2083*cos(3n) + a\u2084*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\u2080 = 0.3635819\n    a\u2081 = 0.4891775\n    a\u2082 = 0.1365995\n    a\u2083 = 0.0106411\n    return @. a\u2080 - a\u2081*cos(n) + a\u2082*cos(2n) - a\u2083*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/\u03c9\u2074\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 \u00d7 `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- \u03c7^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\u00b2, fevals = evaluate_at_samples(func, \n                                            pts, \n                                            bpts,\n                                            M,\n                                            N, \n                                            grid, \n                                            batch\n                                           )\n\n\n        \u03c3\u00b2 = (S\u00b2 - S^2) / (M - 1) + eps() # When \u03c3\u00b2 = 0\n        nevals += M\n        push!(integrals, S)\n        push!(sigma_squares, \u03c3\u00b2)\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    \u03c7\u00b2 = sum(((integrals .- Itot).^2) ./ sigma_squares)\n    @show nevals\n\n\n    Itot, sd, \u03c7\u00b2/(iter-1)\nend\n\nfunction evaluate_at_samples(f, pts, bpts, M, N, grid, batch)\n\n    S = 0.\n    S\u00b2 = 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\u00b2 += (fp / prob)^2\n\n    end\n\n    S/M, S\u00b2/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\u0304 = 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\u0304 * 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": "using Test, PolynomialBases\n\nif !haskey(ENV, \"JULIA_PKGEVAL\") # sympy is not install on https://github.com/JuliaComputing/NewPkgEval.jl\n  import SymPy\n  x, \u03b1 = SymPy.symbols(\"x, alpha\")\n\n  @test 0 == SymPy.simplify( laguerre(x, 0) - 1 )\n  @test 0 == SymPy.simplify( laguerre(x, 1) - ( 1-x ) )\n  @test 0 == SymPy.simplify( laguerre(x, 2) - ( x^2 - 4x + 2 ) / 2 )\n  @test 0 == SymPy.simplify( laguerre(x, 3) - ( -x^3 + 9x^2 - 18x + 6 ) / 6 )\n  @test 0 == SymPy.simplify( laguerre(x, 4) - ( x^4 - 16x^3 + 72x^2 - 96x + 24 ) / 24 )\n  @test 0 == SymPy.simplify( laguerre(x, 5) - ( -x^5 + 25x^4 - 200x^3 + 600x^2 - 600x + 120 ) / 120 )\n  @test 0 == SymPy.simplify( laguerre(x, 6) - ( x^6 - 36x^5 + 450x^4 - 2400x^3 + 5400x^2 - 4320x + 720 ) / 720 )\n\n  @test 0 == SymPy.simplify( laguerre(x, 0, \u03b1) - 1 )\n  # https://www.wolframalpha.com/input/?i=LaguerreL%5B1,+alpha,+x%5D\n  @test 0 == SymPy.simplify( laguerre(x, 1, \u03b1) - ( \u03b1-x+1 ) )\n  # https://www.wolframalpha.com/input/?i=LaguerreL%5B2,+alpha,+x%5D\n  @test 0 == SymPy.simplify( laguerre(x, 2, \u03b1) - ( \u03b1^2 + 3\u03b1 + x^2 - 2\u03b1*x - 4x + 2 ) / 2 )\n  # https://www.wolframalpha.com/input/?i=LaguerreL%5B3,+alpha,+x%5D\n  @test 0 == SymPy.simplify( laguerre(x, 3, \u03b1) - ( \u03b1^3+6\u03b1^2+11\u03b1-x^3+3\u03b1*x^2+9x^2-3\u03b1^2*x-15\u03b1*x-18x+6 ) / 6 )\n  # https://www.wolframalpha.com/input/?i=LaguerreL%5B4,+alpha,+x%5D\n  @test 0 == SymPy.simplify( laguerre(x, 4, \u03b1) - ( \u03b1^4+10\u03b1^3+35\u03b1^2+50\u03b1+x^4-4\u03b1*x^3-16x^3+6\u03b1^2*x^2+42\u03b1*x^2+72x^2-4\u03b1^3*x-36\u03b1^2*x-104\u03b1*x-96x+24 ) / 24 )\n\n  @test_skip laguerre(x, 4)\n  @test_skip laguerre(x, 4, \u03b1)\n  @test_skip laguerre(x, 4, 2)\nend\n@inferred laguerre(10., 4)\n@inferred laguerre(10., 4, 2.)\n@inferred laguerre(10., 4, 2)\n", "meta": {"hexsha": "933fc6bf6900bce83c99e43dccda50151b5f231f", "size": 1663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/laguerre_test.jl", "max_stars_repo_name": "ranocha/PolynomialBases.jl", "max_stars_repo_head_hexsha": "845531c8eee63f2c1608badd980872796fabbfc9", "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": "test/laguerre_test.jl", "max_issues_repo_name": "ranocha/PolynomialBases.jl", "max_issues_repo_head_hexsha": "845531c8eee63f2c1608badd980872796fabbfc9", "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": "test/laguerre_test.jl", "max_forks_repo_name": "ranocha/PolynomialBases.jl", "max_forks_repo_head_hexsha": "845531c8eee63f2c1608badd980872796fabbfc9", "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": 51.96875, "max_line_length": 148, "alphanum_fraction": 0.5995189417, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7804821502563071}}
{"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\u03b8_nom = [0.; 60.; 10.]\ncovar = [80. 0 0; 0 80. 0; 0 0 120.]\n\n## Set the dimensions\nn_z = 3; n_\u03b8 = 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, \u03b8[i = 1:n_\u03b8] ~ MvNormal(\u03b8_nom, covar), \n                    num_supports = num_samples)\n\n## Initialize the variables\n@variable(m, 0 <= y <= 1, Infinite(\u03b8))\n@variable(m, z[1:n_z], Infinite(\u03b8))\n@variable(m, d[1:n_d] >= 0)\n\n## Set objective function\n@objective(m, Max, expect(1 - y, \u03b8))\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] - \u03b8[1] == 0)\n@constraint(m, h2, -z[1] -z[2] + z[3] - \u03b8[2] == 0)\n@constraint(m, h3, z[2] - \u03b8[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) \u2264 h \u2264 one(h), \"h \u2208 [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 (\u03ba::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(\u03ba.h)\n    return (modX^h + modY^h - modXY^h) / 2\nend\n\nfunction (\u03ba::FBMKernel)(x::Real, y::Real)\n    return (abs2(x)^first(\u03ba.h) + abs2(y)^first(\u03ba.h) - abs2(x - y)^first(\u03ba.h)) / 2\nend\n\nfunction Base.show(io::IO, \u03ba::FBMKernel)\n    return print(io, \"Fractional Brownian Motion Kernel (h = \", first(\u03ba.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(\u03ba::FBMKernel, x::AbstractVector)\n    modx = _mod(x)\n    modxx = pairwise(SqEuclidean(), x)\n    return _fbm.(modx, modx', modxx, \u03ba.h)\nend\n\nfunction kernelmatrix!(K::AbstractMatrix, \u03ba::FBMKernel, x::AbstractVector)\n    modx = _mod(x)\n    pairwise!(K, SqEuclidean(), x)\n    K .= _fbm.(modx, modx', K, \u03ba.h)\n    return K\nend\n\nfunction kernelmatrix(\u03ba::FBMKernel, x::AbstractVector, y::AbstractVector)\n    modxy = pairwise(SqEuclidean(), x, y)\n    return _fbm.(_mod(x), _mod(y)', modxy, \u03ba.h)\nend\n\nfunction kernelmatrix!(\n    K::AbstractMatrix, \u03ba::FBMKernel, x::AbstractVector, y::AbstractVector\n)\n    pairwise!(K, SqEuclidean(), x, y)\n    K .= _fbm.(_mod(x), _mod(y)', K, \u03ba.h)\n    return K\nend\n\nfunction kernelmatrix_diag(\u03ba::FBMKernel, x::AbstractVector)\n    modx = _mod(x)\n    modxx = colwise(SqEuclidean(), x)\n    return _fbm.(modx, modx, modxx, \u03ba.h)\nend\n\nfunction kernelmatrix_diag(\u03ba::FBMKernel, x::AbstractVector, y::AbstractVector)\n    modxy = colwise(SqEuclidean(), x, y)\n    return _fbm.(_mod(x), _mod(y), modxy, \u03ba.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 \u2218 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 \u2218 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 \u2218 fmpz)(n)\n\n##  Euler's Phi (or: totient) function\nNemo.eulerphi(n::T) where {T<:Integer} = convert(T, (eulerphi \u2218 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    \u03c3 = one(T)\n    for (p, k) in f\n        \u03c3 *= (p^((k + 1) * s) - 1) \u00f7 (p^s - 1)\n    end\n    \u03c3\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! \u2218 collect \u2218 keys \u2218 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 \u00f7 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": "@testset \"Multithread for solving steady states: single value ODE function\" begin\n\natol = 1e-10\n# Linear ODE which starts at 0.5 and solves from t=0.0 to t=1.0\nde_func(u,p,t) = 0.9u*p\n\nus = [1,2,3] # vec\np_ = 1\nu_ss_real = zeros(length(us))\n\nsim = solve_SSODE_threads(de_func, us, p_)\nres = FindSteadyStates.flatten(get_sol2array(sim))\n\n@test isapprox(res, u_ss_real; atol=atol)\n\nend\n\n@testset \"Multithread for solving steady states: 2D ODE functions\" begin\n\nfunction f(du,u,p,t)\n  du[1] = p[1] * u[1]\n  du[2] = p[2] * u[2]\nend\n\nus = [[1.,2.], [3.,4.], [5.,6.] ]\np = [0.9,0.8]\n\node = DEsteady(func=f, p = p , u0=us, method=SSRootfind())\n\n@time sim = solve_SSODE_threads(f, us, p; method= Tsit5())\n@time sim_ = solve_SSODE_threads(ode) #Rootfind method \n\n\n@testset \"compare solutions\" for us_ in sim.u\n      s = us_.u\n      @test isapprox(s, [0.,0.]; atol=1e-10)\n  end\n\n@testset \"compare solutions\" for us_ in sim_.u\n    s = us_.u\n    @test isapprox(s, [0.,0.]; atol=1e-10)\nend\n\nend\n", "meta": {"hexsha": "ccbb91e35424cce641a7a287c43baf1dd90b59e9", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/multithread_SteadyStateProblem.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/multithread_SteadyStateProblem.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/multithread_SteadyStateProblem.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": 21.8222222222, "max_line_length": 81, "alphanum_fraction": 0.650712831, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7804639498632674}}
{"text": "using QuasiGeostrophy, LinearAlgebra, Test, FFTW, BenchmarkTools\n\n# boiler plate definitions\n\u03a9xy = S\u00b9(0,2\u03c0) \u00d7 S\u00b9(0,4\u03c0)\nNx = 2^8; Ny = 2^8;\nfourier_grid = FourierGrid((Nx, Ny), \u03a9xy)\nx, y = fourier_grid.grid\nkx, ky = fourier_grid.wavenumbers\nf = @. 2 * sin(x) + sin(2*y) + 0im\n\u2202\u02e3f = @. 2 * cos(x) + 0im * y\n\u2202\u02b8f = @. 2 * cos(2*y) + 0im * x\n\u0394f = @. - 2 * sin(x) - 4 * sin(2*y)\nf\u0302 = copy(f)\nFFTW.set_num_threads(Threads.nthreads())\nP = plan_fft(f) # typeof(iP) <: AbstractFFTs.ScaledPlan\niP = plan_ifft(f)\nmul!(f\u0302, P, f)\n\u2202x = FourierOperator(im .* kx)\n\u2202y = FourierOperator(im .* ky)\n\u0394 = \u2202x^2 + \u2202y^2\n\u222b\ud835\udca2dxdy = inv(\u0394)\n\n@testset \"FourierTests\" begin\n    tolerance = eps(1.0) * 1e4\n    bool = norm(\u2202\u02e3f - iP * \u2202x(f\u0302)) ./ norm(\u2202\u02e3f ) < tolerance\n    @test bool \n    bool = norm(\u2202\u02b8f - iP * \u2202y(f\u0302)) ./ norm(\u2202\u02b8f ) < tolerance\n    @test bool \n    bool = norm(\u0394f  - iP * \u0394(f\u0302) ) ./ norm(\u0394f) < tolerance\n    @test bool \n    bool = norm(f - iP * \u222b\ud835\udca2dxdy(\u0394(f\u0302))) ./ norm(f) < tolerance\n    @test bool\nend\n", "meta": {"hexsha": "81abcea116b5c1d712ebad4548ef5e44a011227d", "size": 983, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fourier_tests.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": "test/fourier_tests.jl", "max_issues_repo_name": "sandreza/QuasiGeostrophy", "max_issues_repo_head_hexsha": "05b6e622e981afebf880e4890d24e2b813087e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-13T17:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-13T17:29:21.000Z", "max_forks_repo_path": "test/fourier_tests.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": 28.9117647059, "max_line_length": 64, "alphanum_fraction": 0.5798575788, "num_tokens": 455, "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": "#############################################################################\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 \u2265 b }\nthat is, calculate the following representation\n  P = { \u2211\u1d62 \u03bb\u1d62U\u1d62 + \u2211\u2c7c \u03bc\u2c7cV\u2c7c + \u2211\u2096 \u03bd\u2096W\u2096 : \u2211\u1d62\u03bb\u1d62 = 1, \u03bc \u2265 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 \u2208 P} T\u1d62x \n  max_{x \u2208 P} T\u1d62x\n\nwhere T\u1d62 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 CSV, Statistics, StatsBase\ndata = CSV.read(\"../data/temperatures.csv\")[:,4]\n\nprintln(\"Sample Mean: \", mean(data))\nprintln(\"Harmonic <= Geometric <= Arithmetic \", \n\t(harmmean(data), geomean(data), mean(data)))\nprintln(\"Sample Variance: \",var(data))\nprintln(\"Sample Standard Deviation: \",std(data))\nprintln(\"Minimum: \", minimum(data))\nprintln(\"Maximum: \", maximum(data))\nprintln(\"Median: \", median(data))\nprintln(\"95th percentile: \", percentile(data, 95))\nprintln(\"0.95 quantile: \", quantile(data, 0.95))\nprintln(\"Interquartile range: \", iqr(data),\"\\n\")\n\nsummarystats(data)", "meta": {"hexsha": "f3e00aaef706a0dc484ba41c7bb0966395e301da", "size": 577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4_chapter/summarizingData.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": "4_chapter/summarizingData.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": "4_chapter/summarizingData.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": 36.0625, "max_line_length": 50, "alphanum_fraction": 0.7019064125, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7804329211383707}}
{"text": "function GenDataSize(m,n,r)\r\n\r\n## This script creates an sxs data matrix consisting of a discrezation of 4 \r\n## 2-D Gaussian bumps. The resulting matrix is rank 4 (= number of bumps)\r\n\r\nsc = 1\r\n\r\n# Create regular grid\r\nst = 1/n\r\nX = 0:st:1-st\r\nX = sc*X\r\n\r\nsy = 1/m\r\nY = 0:sy:1-sy\r\nY = sc*Y\r\n\r\nc = 50/sc^2\r\n\r\nReg = zeros(m,n)\r\n\r\n# Bump 1\r\nfor j = 1:r \r\n\r\na = round(rand(1),2)\r\nb = round(rand(1),2)\r\n\r\n    for k = 1:m\r\n        for l = 1:n\r\n            Reg[k,l] += dot(exp((-c*([sc*a - X[l]].^2))[1]),exp((-c*([sc*b - Y[k]].^2))[1]))\r\n        end\r\n    end\r\nend\r\n\r\nreturn Reg\r\nend\r\nexport GenDataSize\r\n\r\n\r\n", "meta": {"hexsha": "c4d47919255550759a0a6abc346f5befef03b869", "size": 602, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "data/GenDataSize.jl", "max_stars_repo_name": "slimgroup/RCAM.jl", "max_stars_repo_head_hexsha": "54c4ff3891087300b3e46b5643b38e8eafa2234e", "max_stars_repo_licenses": ["MIT"], "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/GenDataSize.jl", "max_issues_repo_name": "slimgroup/RCAM.jl", "max_issues_repo_head_hexsha": "54c4ff3891087300b3e46b5643b38e8eafa2234e", "max_issues_repo_licenses": ["MIT"], "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/GenDataSize.jl", "max_forks_repo_name": "slimgroup/RCAM.jl", "max_forks_repo_head_hexsha": "54c4ff3891087300b3e46b5643b38e8eafa2234e", "max_forks_repo_licenses": ["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.4358974359, "max_line_length": 93, "alphanum_fraction": 0.5249169435, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.780432919183255}}
{"text": "using EconPDEs\n\nBase.@kwdef  struct CampbellCochraneModel\n    # consumption process parameters\n    \u03bc::Float64 = 0.0189\n    \u03c3::Float64 = 0.015\n    # utility\n    \u03b3::Float64 = 2.0\n    \u03c1::Float64 = 0.116\n    # habit\n    \u03bas::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# \u03c1 = 12 * (1 - 0.89^(1/12))\n# \u03bas = 12 * (1 - 0.87^(1/12))\n\nfunction initialize_stategrid(m::CampbellCochraneModel; sn = 1000)\n    \u03bc = m.\u03bc ; \u03c3 = m.\u03c3 ; \u03b3 = m.\u03b3 ; \u03c1 = m.\u03c1 ; \u03bas = m.\u03bas ; b = m.b\n    Sbar = \u03c3 * sqrt(\u03b3 / (\u03bas - b / \u03b3))\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    (; \u03bc, \u03c3, \u03b3, \u03c1, \u03bas, b) = m\n    (; s) = state\n    (; p, ps_up, ps_down, pss) = y\n    \n    # drift and volatility of  s and p\n    Sbar = \u03c3 * sqrt(\u03b3 / (\u03bas - b / \u03b3))\n    sbar = log(Sbar)\n    \u03bb = 1 / Sbar * sqrt(1 - 2 * (s - sbar)) - 1\n    \u03bcs = - \u03bas * (s - sbar)\n    ps = (\u03bcs >= 0) ? ps_up : ps_down\n    \u03c3s = \u03bb * \u03c3\n    \u03c3p = ps / p * \u03c3s\n    \u03bcp = ps / p * \u03bcs + 0.5 * pss / p * \u03c3s^2\n\n    # market price of risk \u03ba\n    \u03ba = \u03b3 * (\u03c3 + \u03c3s)\n\n    # risk free rate  r\n    r = \u03c1 + \u03b3 * \u03bc - (\u03b3 * \u03bas - b) / 2 + b * (sbar - s)\n\n    # PDE\n    pt = - p * (1 / p + \u03bc + \u03bcp + \u03c3p * \u03c3 - r - \u03ba * (\u03c3 + \u03c3p))\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(\u03bc = 0.022, \u03c3 = 0.0086, \u03b3 = 2.0, \u03c1 = 0.073, \u03bas = 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": "using Test\n\n@testset \"BIC\"  begin \n\n    using StatsModelComparisons\n\n    v1 = bic(-200.0, 10, 100)\n    v2 = bic(-200.0, 2, 100)\n    v3 = bic(-200.0, 2, 10)\n    v4 = bic(-100.0, 2, 10)\n    @test v2 < v1\n    @test v3 < v2\n    @test v4 < v3\nend\n\n@testset \"AIC\"  begin \n\n    using StatsModelComparisons\n\n    v1 = aic(-200.0, 10)\n    v2 = aic(-200.0, 2)\n    v3 = aic(-100.0, 2)\n    @test v2 < v1\n    @test v3 < v2\nend\n\n@testset \"DIC\"  begin \n\n    using StatsModelComparisons\n    x = randn(100)\n    LLs = x .- mean(x)\n    v1 = dic(LLs)\n    v2 = dic(LLs*2)\n    v3 = dic(LLs .+ 1)\n    @test v1 < v2\n    @test v3 < v1\nend\n\n\n@testset \"WAIC and LOO\" begin \n\n    using StatsModelComparisons, StanSample\n    using StatsFuns, RDatasets, Random, CSV\n    import StanSample: read_csv_files\n\n    cd(@__DIR__)\n    Random.seed!(89905)\n    # df = RDatasets.dataset(\"datasets\", \"cars\")\n\n    # stream = open(\"cars_model.stan\", \"r\")\n    # cars_stan = read(stream, String)\n    # close(stream)\n\n    # cars_stan_model = SampleModel(\"cars.model\", cars_stan)\n    # data = (N = size(df, 1), speed = df.Speed, dist = df.Dist)\n    # rc = stan_sample(cars_stan_model; data)\n\n    # stan_summary(cars_stan_model, true)\n    # nt_cars = read_samples(cars_stan_model);\n    # log_lik = nt_cars.log_lik'\n\n    # files = readdir(\"test_chains\")\n    # files = map(f->\"test_chains/\"*f, files)\n    # samples = read_csv_files(files, 2000, :namedtuple; include_internals=false)\n    # df = vcat(dfs...)\n\n    files = readdir(\"test_chains/\")\n\n    dfs = map(f->CSV.read(\"test_chains/\"*f, DataFrame), files)\n    dfs = map(x->x[1001:end,:], dfs)\n    df = vcat(dfs...)\n    \n    col_idx = findall(x->occursin(\"log_lik\", x), names(df))\n    pw_log_liks = Array(df[:,col_idx])\n    WAIC = waic(pw_log_liks)\n    loo,_,_ = psisloo(pw_log_liks)\n\n    @test WAIC.WAIC \u2248 421.0 rtol = .01\n    @test WAIC.std_err \u2248 16.3 rtol = .01\n    @test loo \u2248 -210.5 rtol = .05  \nend\n", "meta": {"hexsha": "6825af40e275e7ac62944c277180d61cf115e287", "size": 1903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/model_comparison_tests.jl", "max_stars_repo_name": "itsdfish/StatsModelComparisons.jl", "max_stars_repo_head_hexsha": "e8683a97bc4cdc57b465fdec245300d691d59240", "max_stars_repo_licenses": ["MIT"], "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/model_comparison_tests.jl", "max_issues_repo_name": "itsdfish/StatsModelComparisons.jl", "max_issues_repo_head_hexsha": "e8683a97bc4cdc57b465fdec245300d691d59240", "max_issues_repo_licenses": ["MIT"], "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/model_comparison_tests.jl", "max_forks_repo_name": "itsdfish/StatsModelComparisons.jl", "max_forks_repo_head_hexsha": "e8683a97bc4cdc57b465fdec245300d691d59240", "max_forks_repo_licenses": ["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.2073170732, "max_line_length": 81, "alphanum_fraction": 0.5964266947, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7804329146576746}}
{"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\u2297I, I)\n    exposure::Hom(S\u2297I, E\u2297I)\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, \u03ba=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\u03b8 = [[deepcopy(traj.\u03b8) for i = 1:N]...;]\n\n\trz = [LinearizedStep(s, z[t], \u03b8[t], \u03ba).rz for t = 1:N*H]\n\tr\u03b8 = [LinearizedStep(s, z[t], \u03b8[t], \u03ba).r\u03b8 for t = 1:N*H]\n\n\tidx_z = indices_z(s)\n\tidx_\u03b8 = indices_\u03b8(model, nf=1)\n\n\t\u2202z\u2202\u03b8 = [-rz[t] \\ r\u03b8[t] for t = 1:N*H]\n\n\t\u2202q2\u2202q1 = [zeros(model.nq, model.nq) for t = 1:N*H]\n\t\u2202q2\u2202q2 = [I(model.nq) for t = 1:N*H]\n\t\u2202q3\u2202q1 = [\u2202z\u2202\u03b8[t][idx_z.q, idx_\u03b8.q1] for t = 1:N*H]\n\t\u2202q3\u2202q2 = [\u2202z\u2202\u03b8[t][idx_z.q, idx_\u03b8.q2] for t = 1:N*H]\n\n\t\u2202q2\u2202u = [zeros(model.nq, model.nu) for t = 1:N*H]\n\t\u2202q3\u2202u = [\u2202z\u2202\u03b8[t][idx_z.q, idx_\u03b8.u] for t = 1:N*H]\n\n\tA = [[\u2202q2\u2202q1[t] \u2202q2\u2202q2[t]; \u2202q3\u2202q1[t] \u2202q3\u2202q2[t]] for t = 1:N*H]\n\tB = [[\u2202q2\u2202u[t]; \u2202q3\u2202u[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    \u0394 = tmax / N\n\n    t = collect(range(0.0, tmax, length = N))\n    \u03c9 = 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(\u03c9, real.(resFFTW), title = \"FFTW Real\", label = \"\");\n    p1im = plot(\u03c9, imag.(resFFTW), title = \"FFTW Imag\", label = \"\");\n    p1abs = plot(\u03c9, abs.(resFFTW) .^ 2 , title = \"FFTW Abs^2\", label = \"\");\n\n    p2re = plot(\u03c9, real.(resNaive), title = \"Naive Real\", label = \"\");\n    p2im = plot(\u03c9, imag.(resNaive), title = \"Naive Imag\", label = \"\");\n    p2abs = plot(\u03c9, abs.(resNaive) .^ 2 , title = \"Naive Abs^2\", label = \"\");\n\n    p3re = plot(\u03c9, real.(resSimple), title = \"Simple Real\", label = \"\");\n    p3im = plot(\u03c9, imag.(resSimple), title = \"Simple Imag\", label = \"\");\n    p3abs = plot(\u03c9, 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-\u03c1) \u03bc + \u03c1 x_{t-1} + sqrt{1 - \u03c1^2} \u03c3 \u03f5_t\n\u03f5_t \u223c iid N(0,1), x_0 \u223c N(\u03bc,\u03c3^2)\n\u03bb_t = \u03a6(x_t)\n```\nwhere \u03a6(\u22c5) is the cdf of a N(0,1) random variable, F_\u03f5 is the distribution of \u03f5_t,\nand F_\u03bb is the distribution of \u03bb(x_0).\n\"\"\"\nfunction transition(m::PoolModel{T}) where {T<:AbstractFloat}\n    @inline \u03a6(x::Vector{Float64}, \u03f5::Vector{Float64}) = abs.([0;1] .-\n                                                             (cdf.(Normal(), (1 - m[:\u03c1].value) .*\n                                                                   m[:\u03bc].value .+ m[:\u03c1].value .*\n                                                                   quantile(Normal(),x[1]) .+\n                                                                   sqrt(1 - m[:\u03c1].value^2) .*\n                                                                   m[:\u03c3].value .* \u03f5)))\n    F_\u03f5 = Normal(0.,1.)\n    F_\u03bb = Uniform(0.,1.)\n    return \u03a6, F_\u03f5, F_\u03bb\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# \u2554\u2550\u2561 0507f8ed-8b64-48af-a6c4-ff7c4211b9e9\nbegin\n\tusing Pkg\n\tPkg.activate(\".\")\nend\n\n# \u2554\u2550\u2561 3310d2f7-450a-4cd1-9c3a-46d02d23a7c6\nusing Revise\n\n# \u2554\u2550\u2561 d27b2d72-d264-11eb-0be5-13dcacfd2adc\nusing DeconvOptim, TestImages, ImageShow, Plots, LinearAlgebra, IndexFunArrays, Noise, FourierTools, SpecialFunctions, FFTW, LaTeXStrings, PlutoUI, Images, Tullio\n\n# \u2554\u2550\u2561 952b251c-207b-4412-b6e1-268fce1647d9\nbegin\n\timg = Float32.(testimage(\"fabio_gray\"));\n\timg_1D = img[:, 200]\nend;\n\n# \u2554\u2550\u2561 fa8cd9c9-a2fd-495c-8d22-ada7bb9c39f6\notf(x, \u0394x=1) = begin\n\tx = abs(x)\n\tif x <= \u0394x \n\t\tSpecialFunctions.jinc(x * \u0394x *(1-x/\u0394x)) .* 2 / \u03c0 * (acos(x/\u0394x) - x/\u0394x * sqrt(1-(x/\u0394x)^2))\n\telse\n\t\tzero(x)\n\tend\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 24fc86da-0b7c-493c-8977-2a19ef6dc133\nimg_n = Float32.(poisson(DeconvOptim.conv(img, psf), 1000));\n\n# \u2554\u2550\u2561 3bda922d-552b-42ec-9055-33a141b5841a\nblur(x, otf=otf_1D) = iffts(ffts(x) .* otf)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b542187a-3ae7-4430-a81d-f968d9000427\nimg_blurry = DeconvOptim.conv(img, psf);\n\n# \u2554\u2550\u2561 88d83629-f1b2-4d69-928f-d4acfbc76b70\nreg_1D = TV(num_dims=1);\n\n# \u2554\u2550\u2561 d6d0f436-48fd-4e8a-863c-3e9d3850cc91\nbegin\n\treg_tik = Tikhonov()\n\treg_TV = TV()\n\treg_GR = DeconvOptim.GR()\nend\n\n# \u2554\u2550\u2561 061faf49-662c-4508-83b4-ddcf0970ed0d\nmd\"### DeconvOptim.jl: Microscopy Image Deconvolution\n\"\n\n# \u2554\u2550\u2561 23829201-9756-4ef8-90c9-3917b761fe4b\nload(\"../docs/src/assets/logo.png\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 49686d9a-1683-428f-83ba-a9131c2ad432\n[Gray.(img) Gray.(DeconvOptim.conv(img, psf))]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e31f4704-5bce-4c8d-b3a7-873a3460d9f8\nplot(x, otf.(x), xlabel=\"frequency / maximum frequency\", ylabel=\"contrast\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e9ef5ba4-56c0-4595-bc28-e04882f44a9a\nload(\"../docs/src/assets/tex/pipeline.png\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 03139ac5-3525-4fad-abf1-84421492b763\nDeconvOptim.generate_TV(4, [1,2, 3], [1,1, 1], 1, 0)[1]\n\n# \u2554\u2550\u2561 4e84e739-9c59-4939-8b04-aec7dc069d67\nmd\"\n### Deconvolve with DeconvOptim.jl\n\n\"\n\n# \u2554\u2550\u2561 9d9a5da2-14df-46e6-b7e6-5a33aade1754\n@bind reg_list2 Select([\"1\" => (\"Tikhonov\"), \"2\" => (\"Total Variation TV\"), \"3\" => (\"Good's Roughness GR\")])\n\n# \u2554\u2550\u2561 5ae1a6a3-4505-4123-9f1e-8a1d4ac0b4e1\nreg = [reg_tik, reg_TV, reg_GR][parse(Int, reg_list2)]\n\n# \u2554\u2550\u2561 15d54e5e-64f4-4a1d-8cc8-9334b2e3784f\nmd\"\niterations = \n$(@bind iter Slider(0:50, show_value=true))\n\n\u03bb = $(@bind \u03bb Slider(0:0.001:0.3, show_value=true))\n\nregularizer = $(@bind reg_bool CheckBox())\"\n\n# \u2554\u2550\u2561 803368e6-53fd-4413-b3f5-ffe46ee8983e\nimg_deconv, res_img = deconvolution(img_blurry, psf, regularizer=reg_bool ? reg : nothing, iterations=iter, \u03bb=\u03bb);\n\n# \u2554\u2550\u2561 e58e1f63-2c81-48fb-866a-4bb70bd428a6\nGray.(img_deconv)\n\n# \u2554\u2550\u2561 438a6639-bd35-464f-a81d-d98eb65e006e\nres_1D, o = deconvolution(real(blur(img_1D)), psf_1D, iterations=iter, regularizer=reg_1D, \u03bb=0.01);\n\n# \u2554\u2550\u2561 7a16df73-95ad-47f5-907c-6fd23c6000cf\n[Gray.(img) Gray.(img_blurry) Gray.(img_deconv)]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ff9af79c-f06c-42ac-9c8d-6f09d2ff4056\n[Gray.(img_1D); Gray.(res_1D)];\n\n# \u2554\u2550\u2561 d8aee845-e922-41da-a17e-37ffa3e692f0\nmd\"### Real Microscopy Data\"\n\n# \u2554\u2550\u2561 fc93fa3d-8599-463b-b9e6-8043b90e9d63\nload(\"figures/real_data_large.png\")\n\n# \u2554\u2550\u2561 97c45bfd-d1ef-49ad-908d-7360c03b0170\nmd\"Image taken from [DeconvolutionLab2](http://bigwww.epfl.ch/deconvolution/deconvolutionlab2/).\"\n\n# \u2554\u2550\u2561 bf37664a-f726-46b6-9592-da419165af91\nmd\"## Conclusion - DeconvOptim.jl\n\"\n\n# \u2554\u2550\u2561 f8117250-bac8-43a1-aae4-5c8bab3a522d\n[Gray.(ones(130, 012)) load(\"../docs/src/assets/logo.png\")]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u25503310d2f7-450a-4cd1-9c3a-46d02d23a7c6\n# \u2560\u25500507f8ed-8b64-48af-a6c4-ff7c4211b9e9\n# \u2560\u2550d27b2d72-d264-11eb-0be5-13dcacfd2adc\n# \u2560\u2550952b251c-207b-4412-b6e1-268fce1647d9\n# \u2560\u255024fc86da-0b7c-493c-8977-2a19ef6dc133\n# \u2560\u25503bda922d-552b-42ec-9055-33a141b5841a\n# \u255f\u2500fa8cd9c9-a2fd-495c-8d22-ada7bb9c39f6\n# \u2560\u25509a07bc88-be76-4531-bc91-df0d20c3221c\n# \u255f\u2500308e2562-5a20-4082-8a6d-9fb135738c49\n# \u2560\u2550b542187a-3ae7-4430-a81d-f968d9000427\n# \u2560\u255088d83629-f1b2-4d69-928f-d4acfbc76b70\n# \u2560\u2550e58e1f63-2c81-48fb-866a-4bb70bd428a6\n# \u2560\u2550d6d0f436-48fd-4e8a-863c-3e9d3850cc91\n# \u2560\u2550803368e6-53fd-4413-b3f5-ffe46ee8983e\n# \u2560\u25505ae1a6a3-4505-4123-9f1e-8a1d4ac0b4e1\n# \u2560\u2550438a6639-bd35-464f-a81d-d98eb65e006e\n# \u255f\u2500061faf49-662c-4508-83b4-ddcf0970ed0d\n# \u255f\u250023829201-9756-4ef8-90c9-3917b761fe4b\n# \u255f\u250030f21bb8-6d09-4fce-9d2a-568bfaf3ff7a\n# \u255f\u25007a0a44c9-fb07-44e6-9a8b-8f720b84e6f6\n# \u255f\u250049686d9a-1683-428f-83ba-a9131c2ad432\n# \u255f\u2500491ec7cb-1663-4acf-b81f-9acafba2b63d\n# \u255f\u2500b6f9e42e-5a23-40ad-9e73-8f02da48f69c\n# \u255f\u2500e31f4704-5bce-4c8d-b3a7-873a3460d9f8\n# \u255f\u2500dc8cf4e2-a87c-47ea-8247-3ae772852241\n# \u255f\u2500f8033d13-faee-41f5-bdd6-ae8721e8b8a8\n# \u255f\u2500fe7e0292-31f6-43b5-83a5-a38698a87563\n# \u255f\u2500e9ef5ba4-56c0-4595-bc28-e04882f44a9a\n# \u2560\u255090e5708c-05a4-46e4-b1e4-9a61c96dae32\n# \u2560\u255003139ac5-3525-4fad-abf1-84421492b763\n# \u255f\u25004e84e739-9c59-4939-8b04-aec7dc069d67\n# \u255f\u25009d9a5da2-14df-46e6-b7e6-5a33aade1754\n# \u255f\u250015d54e5e-64f4-4a1d-8cc8-9334b2e3784f\n# \u255f\u25007a16df73-95ad-47f5-907c-6fd23c6000cf\n# \u255f\u25005c8030b7-8805-4771-9329-23abb2744544\n# \u255f\u2500ff9af79c-f06c-42ac-9c8d-6f09d2ff4056\n# \u255f\u2500d8aee845-e922-41da-a17e-37ffa3e692f0\n# \u255f\u2500fc93fa3d-8599-463b-b9e6-8043b90e9d63\n# \u255f\u250097c45bfd-d1ef-49ad-908d-7360c03b0170\n# \u255f\u2500bf37664a-f726-46b6-9592-da419165af91\n# \u255f\u2500f8117250-bac8-43a1-aae4-5c8bab3a522d\n# \u255f\u2500b5a70276-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": "# Test utililties.jl\n\nusing Test, Statistics\n\nprintln(\"testing utilites\")\n\ntol = 1e-2   # Fairly sloppy, needed for the derivative tests\n\n# nonmaxsuppts - tested in test_cornerfeatures.jl\n\n# derivative 3 5 7\n# Generate an image of constant gradient\nimg = [c for r=1:50, c=1:50]\n(gx,gy) = derivative3(img, (\"x\", \"y\"))\n\n# Test interior of derivatives matrix matches expected values\n@test all(abs.(gx[5:end-5,5:end-5] .- 1) .< tol)\n@test all(abs.(gy[5:end-5,5:end-5]) .< tol)\n\n(gx,gy, gxx, gyy, gxy) = derivative5(img, (\"x\", \"y\", \"xx\", \"yy\", \"xy\"))\n# Test interior of derivatives matrix matches expected values\n@test all(abs.(gx[5:end-5,5:end-5] .- 1) .< tol)\n@test all(abs.(gy[5:end-5,5:end-5]) .< tol)\n@test all(abs.(gxx[5:end-5,5:end-5]) .< tol)\n@test all(abs.(gyy[5:end-5,5:end-5]) .< tol)\n@test all(abs.(gxy[5:end-5,5:end-5]) .< tol)\n\n(gx,gy, gxx, gyy, gxy) = derivative7(img, (\"x\", \"y\", \"xx\", \"yy\", \"xy\"))\n# Test interior of derivatives matrix matches expected values\n@test all(abs.(gx[5:end-5,5:end-5] .- 1) .< tol)\n@test all(abs.(gy[5:end-5,5:end-5]) .< tol)\n@test all(abs.(gxx[5:end-5,5:end-5]) .< tol)\n@test all(abs.(gyy[5:end-5,5:end-5]) .< tol)\n@test all(abs.(gxy[5:end-5,5:end-5]) .< tol)\n\n\n# gaussfilt\nimg = zeros(100,100)\nimg[50,50] = 1\nsimg = gaussfilt(img,2)\n@test abs(sum(simg) - 1) < tol\n\n# dilate1d erode1d\n# Generate a 1D signal with a single spike\nv = zeros(20)\nv[10] = 1          \nk = 5\nvd = dilate1d(v,k)\n@test all(vd[8:12] .== 1) && all(vd[1:7] .== 0) && all(vd[13:end] .== 0)\n\nve = erode1d(vd,k)   # Erode back and check we reconstruct v\n@test all(ve .== v)\n\n# imdilate imerode\nimg = falses(100,100)\nimg[50,50] = true\ndimg = imdilate(img, \"rect\", [5, 3])\n@test all(dimg[47:47,48:52] .== [0 0 0 0 0])\n@test all(dimg[50:50,48:52] .== [0 1 1 1 0])\n@test all(dimg[53:53,48:52] .== [0 0 0 0 0])\n@test all(dimg[47:53,50] .== [0, 1, 1, 1, 1, 1, 0])\n\neimg = imerode(dimg, \"rect\", [5, 3])\n@test all(eimg[49:51,49:51] .== [0 0 0; 0 1 0; 0 0 0])\n\n# circularstruct\n\n# floatxy\n\n# matchbycorrelation\n\n# grey2census\n\n# imgnormalise\na = rand(5,3)\nan = imgnormalise(a)\n@test isapprox(minimum(an), 0)\n@test isapprox(maximum(an), 1)\n\nreqmean = 5\nreqvar = 7\nan = imgnormalise(a, reqmean, reqvar)\n@test isapprox(mean(an), reqmean)\n@test isapprox(var(an), reqvar)\n\n# histtruncate\nrows = 100;\ncols = 200;\nimg = rand(rows, cols)\nlHistCut = 2\nuHistCut = 4\nhtimg = histtruncate(img, lHistCut, uHistCut)\nminval = minimum(htimg)\nmaxval = maximum(htimg)\n# Check that the number of saturated pixels at each extreme is\n# approximately lHistCut and uHistCut. Note some integer rounding has\n# to occur.\nv = findall(abs.(htimg .- minval).<eps())\n@test abs(length(v)/(rows*cols) * 100 - lHistCut) < 1\n\nv = findall(abs.(htimg .- maxval).<eps())\n@test abs(length(v)/(rows*cols) * 100 - uHistCut) < 1\n\n", "meta": {"hexsha": "876c5060b6096cc70c9560ce88c783fd16491133", "size": 2787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_utilities.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_stars_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_stars_repo_licenses": ["MIT"], "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_utilities.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_issues_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_issues_repo_licenses": ["MIT"], "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_utilities.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_forks_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_forks_repo_licenses": ["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.7980769231, "max_line_length": 72, "alphanum_fraction": 0.6365267313, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7803634852058839}}
{"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": "using Alistair\nusing Base.Test\n\n# TEST OPTIONS\nconst TEST_SIZE_1 = 10\nconst PRINT_RESULTS = true\nRESULTS = Dict()\n\nbeta = [0.7; 0.45]\nX = hcat(ones(TEST_SIZE_1,1), collect(1.0:TEST_SIZE_1))\nY = X * beta + 0.1*randn(TEST_SIZE_1, 1)\n# Y = [1.0 2.0 1.3 3.75 2.25]'\n\n#=\nif false\n@__test issingletonarray(X) == false\n@__test isrowarray(X) == false\n@__test iscolumnarray(X) == true\n@__test hasintercept(X) == false\n\n@__test aprod(X, 1.0) == X\n@__test aprod(1, X) == X\n@__test aprod(X, [1]) == X\n@__test aprod([1], X) == X\n@__test aprod(X', Y) == X' * Y\nend\n=#\n\nif true\n# Test for all types\nRESULTS[\"TIME_OLS_INIT\"] = @elapsed OLSRegression = OLS(intercept=true, robust=false)\n\n# OLS test:\nRESULTS[\"TIME_OLS_SOLVE \"] = @elapsed res = linregress(X, Y, OLSRegression)\n#@__test squeeze(res.beta,2) == beta\n#println(\"OLSRegression\")\nPRINT_RESULTS ? println(res) : 0\n\nOLSRegression = OLS(intercept=true, robust=HCEVariance())\nRESULTS[\"TIME_OLS_SOLVE_HCE\"] = @elapsed res = solve(X, Y, OLSRegression)\n#@__test res.beta == [0.785; 0.425]\n#println(\"OLSRegression\")\nPRINT_RESULTS ? println(res) : 0\n\n# FGLS test\nRESULTS[\"TIME_FGLS_INIT\"] = @elapsed FGLSRegression = FGLS(intercept=true, robust=HCEVariance())\nRESULTS[\"TIME_FGLS_SOLVE\"] = @elapsed res = linregress(X, Y, FGLSRegression)\n#println(\"FGLSRegression\")\nPRINT_RESULTS ? println(res) : 0\n\n# IteratedFGLS test\nRESULTS[\"TIME_IFGLS_INIT\"] = @elapsed IteratedFGLSRegression = IteratedFGLS(10, intercept=true, robust=HCEVariance())\nRESULTS[\"TIME_IFGLS_SOLVE\"] = @elapsed res = linregress(X, Y, IteratedFGLSRegression)\n#println(\"IteratedFGLS\")\nPRINT_RESULTS ? println(res) : 0\nend\n\n# Non-Linear test\n# Optimize test\n\nf(X_, beta_) = exp.(beta_[1]*X_[:,1] + beta_[2]*log.(X_[:,2]))\n\nYnlin = f(X, beta) + 0.1*randn(TEST_SIZE_1, 1)\n\nRESULTS[\"TIME_OPTIM_INIT\"] = @elapsed OptimizeRegression = Optimize(f, [1.0, 1.0])\nRESULTS[\"TIME_OPTIM_SOLVE\"] = @elapsed res = nlinfit(X, Ynlin, OptimizeRegression)\nPRINT_RESULTS ? println(res) : 0\n\n# Print timing results:\nprintln(\"#-- TIMING RESULTS --#\")\npresent(RESULTS)\n", "meta": {"hexsha": "0199053d48728eba03f6e7a205372f3011fca24e", "size": 2040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/local/local_runtests.jl", "max_stars_repo_name": "giob1994/Alistair", "max_stars_repo_head_hexsha": "3a11c19150169695581b46e4d1895f0641a4c29d", "max_stars_repo_licenses": ["MIT"], "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/local/local_runtests.jl", "max_issues_repo_name": "giob1994/Alistair", "max_issues_repo_head_hexsha": "3a11c19150169695581b46e4d1895f0641a4c29d", "max_issues_repo_licenses": ["MIT"], "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/local/local_runtests.jl", "max_forks_repo_name": "giob1994/Alistair", "max_forks_repo_head_hexsha": "3a11c19150169695581b46e4d1895f0641a4c29d", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 117, "alphanum_fraction": 0.7058823529, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7802739999813845}}
{"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 \u2208 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": "using DReal\nusing Base.Test\n\n# Ackley's: bounds -5 <= x,y <= 5, min: f(0,0) = 0\nbegin\nprintln(\"Trying Ackleys\")\nackleys(x::Array) = -20*exp(-0.2*sqrt(0.5(x[1]*x[1] + x[2]*x[2]))) - exp(0.5(cos(2*\u03c0*x[1])+cos(2*\u03c0*x[2]))) + e + 20\nx = Var(Float64,\"x2\",-5.12,5.12)\ny = Var(Float64,\"y2\",-5.12,5.12)\nf = Var(Float64,\"f2\",-10.,10.)\nadd!(f == ackleys([x,y]))\ncost, optimal_model = minimize(f,x,y; lb=-10.,ub = 10.)\n\nreset_ctx!(default_global_context)\n\n# Commented out by Soonho Kong, 2016/06/09\n# The following optimization query returns UNSAT, which is wrong.\n# Until I fix the problem, we don't run this test\n#\n# # # Beales function\n# println(\"Trying Beales\")\n# beale(x::Array) =  (1.5 - x[1] + x[1]x[2])^2 +\n#                 (2.25 - x[1] + x[1]x[2]^2)^2 +\n#                 (2.625 - x[1] + x[1]x[2]^3)^2\n# x = Var(Float64,\"x3\",-5.12,5.12)\n# y = Var(Float64,\"y3\",-5.12,5.12)\n# f = Var(Float64,\"f3\",-10.,10.)\n# add!(f == beale([x,y]))\n# cost, optimal_model = minimize(f,x,y; lb=-10.,ub = 10.)\n# @show cost, optimal_model\n# \n# reset_global_ctx!()\n\n# # rastrigin\nprintln(\"Trying rastrigin\")\n\nrastrigin(x::Array) = 10 * length(x) + sum([xi*xi - 10*cos(2pi*xi) for xi in x])\nx = Var(Float64,\"x4\",-5.12,5.12)\ny = Var(Float64,\"y4\",-5.12,5.12)\nf = Var(Float64,\"f4\",-10.,10.)\nadd!(f == rastrigin([x,y]))\ncost, optimal_model = minimize(f,x,y; lb=-10.,ub = 10.)\n@show cost, optimal_model\n\nreset_global_ctx!()\n\nend\n", "meta": {"hexsha": "1d71e30614a0f41f7eda57e207a70e03f58a604f", "size": 1398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optimize.jl", "max_stars_repo_name": "Kelvyn88/DReal.jl", "max_stars_repo_head_hexsha": "9e42d06d653ced0b32b548088668b967955faadf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-07-09T20:38:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T02:18:43.000Z", "max_issues_repo_path": "test/optimize.jl", "max_issues_repo_name": "Kelvyn88/DReal.jl", "max_issues_repo_head_hexsha": "9e42d06d653ced0b32b548088668b967955faadf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-07-07T05:58:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T21:56:39.000Z", "max_forks_repo_path": "test/optimize.jl", "max_forks_repo_name": "Kelvyn88/DReal.jl", "max_forks_repo_head_hexsha": "9e42d06d653ced0b32b548088668b967955faadf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-07-24T05:11:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-01T08:14:54.000Z", "avg_line_length": 29.125, "max_line_length": 115, "alphanum_fraction": 0.5901287554, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7802115931149157}}
{"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": "__precompile__()\n# ----------------------------------------------------------------------------\nmodule Knapsack\n#=\n    see also:\n        - the walkthrough at http://vladium.com/tutorials/study_julia_with_me/knapsack_benchmark/\n        - https://en.wikipedia.org/wiki/Knapsack_problem#0/1_knapsack_problem\n\n    running this benchmark from command line:\n\n    >julia Knapsack.jl\n=#\n# ............................................................................\n\"\"\"\n    we need a couple of integers to describe a knapsack item, its value and weight.\n    a tuple would work, but a struct makes for more readable code\n\"\"\"\nstruct Item\n    value   ::Int64; # actually, being so type-specific is not necessary in Julia\n    weight  ::Int64;\nend\n# ............................................................................\n\"\"\"\n    first version of the knapsack solver; uses a full matrix for V and will\n    not scale to large problems\n\"\"\"\nfunction opt_value_BAD(W ::Int64, items ::Array{Item}) ::Int64\n    n = length(items)\n\n    # V[w,j] stores opt value achievable with capacity 'w' and using items '1..j':\n\n    V = Array{Int64}(undef, W, n) # Wxn matrix with uninitialized storage\n\n    # initialize first column v[:, 1] to trivial single-item solutions:\n    # (note \"broadcast assignment\" syntax)\n\n    V[:, 1] .= 0\n    V[items[1].weight:end, 1] .= items[1].value\n\n    # do a pass through remaining columns:\n\n    for j in 2 : n\n        item\u2c7c = items[j]\n        for w in 1 : W\n            V_without_item\u2c7c = V[w, j - 1]\n            V_allow_item\u2c7c = (w < item\u2c7c.weight\n                ? V_without_item\u2c7c\n                : (item\u2c7c.value + (w \u2260 item\u2c7c.weight ? V[w - item\u2c7c.weight, j - 1] : 0)))\n            V[w, j] = max(V_allow_item\u2c7c, V_without_item\u2c7c)\n        end\n    end\n\n    return V[W, n]\nend\n# ............................................................................\n\"\"\"\n    second version of the knapsack solver; uses two column buffers for V\n\"\"\"\nfunction opt_value(W ::Int64, items ::Array{Item}) ::Int64\n    n = length(items)\n\n    # V[w] stores opt value achievable with capacity 'w' and using items '1..j':\n\n    V = zeros(Int64, W) # single column of size W, zero-initialized\n    V_prev = Array{Int64}(undef, W) # single column of size W, uninitialized storage\n\n    # initialize 'v' to trivial single-item solutions:\n    # (note \"broadcast assignment\" syntax)\n\n    V[items[1].weight:end] .= items[1].value\n\n    # do a pass through remaining columns:\n\n    for j in 2 : n\n        V, V_prev = V_prev, V\n        item\u2c7c = items[j]\n        for w in 1 : W\n            V_without_item\u2c7c = V_prev[w]\n            V_allow_item\u2c7c = (w < item\u2c7c.weight\n                ? V_without_item\u2c7c\n                : (item\u2c7c.value + (w \u2260 item\u2c7c.weight ? V_prev[w - item\u2c7c.weight] : 0)))\n            V[w] = max(V_allow_item\u2c7c, V_without_item\u2c7c)\n        end\n    end\n\n    return V[W]\nend\n# ............................................................................\n\"\"\"\n    a simple but good quality [xorshift RNG](https://en.wikipedia.org/wiki/Xorshift)\n    that can be ported to all benchmark languages to ensure equivalent test problem\n    instances across all ports\n\"\"\"\nfunction xorshift_rand(seed)\n    @assert seed \u2260 0\n    x ::UInt64 = seed # want unsigned bit arithmetic\n\n    return function _next()\n        x \u22bb= (x << 13) # note that python would need 'nonlocal' here\n        x \u22bb= (x >>> 7)\n        x \u22bb= (x << 17)\n        return x\n    end\nend\n\nProblem = Tuple{Int64, Array{Item}} # use a type alias for less typing \n\n\"\"\"\n    generate a randomized knapsack problem definition of scale 'W'\n\"\"\"\nfunction make_random_data(W ::Int64, seed ::Int64) ::Problem\n    @assert W > 1000 # don't test on very small problems\n    n = W \u00f7 100\n    rng = xorshift_rand(seed)\n\n    items = Array{Item}(undef, n)\n    for i in 1 : n\n        v = rng() % 1000\n        w = 1 + rng() % 2W\n        items[i] = Item(v, w)\n    end\n\n    return W, items\nend\n# ............................................................................\n\"\"\"\n    you can use this function to load any knapsack problem defition from a file\n    instead of using make_random_data();\n    the format is:\n\n     1. first line: <W>\n     2. n subsequent lines: <value> <weight> (separated by spaces)\n\"\"\"\nfunction load_data(in_file ::String) ::Problem\n    W = -1\n    items = Item[]\n    open(in_file) do fd\n        for line in eachline(fd)\n            line = strip(line)\n            if isempty(line)\n                break\n            end\n            if W < 0 # reading first line\n                W = parse(Int, line)\n            else # reading items\n                tokens = split(line)\n                @assert length(tokens) == 2\n                item = Item(parse(Int, tokens[1]), parse(Int, tokens[2]))\n\n                push!(items, item)\n            end\n        end\n    end\n\n    return W, items\nend\n# ............................................................................\n\nfunction run(repeats = 5)\n    @assert repeats > 1\n\n    times = zeros(Float64, repeats)\n    seed = 12345\n\n    for W in [5_000, 10_000, 20_000, 40_000, 80_000]\n        for repeat in 1 : repeats\n            W, items = make_random_data(W, seed += 1)\n            times[repeat] = @elapsed V = opt_value(W, items)\n            # println(\"V = $(V), time = $(times[repeat])\")\n        end\n        sort!(times)\n        println(\"julia, \", W, \", \", times[(repeats + 1) \u00f7 2]) # report W and median time\n    end\nend\n\n# comment this out if you don't want to run the benchmark on module load:\n\nrun()\n\nend # of module\n# ----------------------------------------------------------------------------\n", "meta": {"hexsha": "6df8d500a8997757a69d0af51ad995317abf3695", "size": 5562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "knapsack_benchmark/Knapsack.jl", "max_stars_repo_name": "vladium/study_julia_with_me", "max_stars_repo_head_hexsha": "8c7a0b614098091ef284ebee1250c69f222fa126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-16T00:46:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T17:08:46.000Z", "max_issues_repo_path": "knapsack_benchmark/Knapsack.jl", "max_issues_repo_name": "vladium/study_julia_with_me", "max_issues_repo_head_hexsha": "8c7a0b614098091ef284ebee1250c69f222fa126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knapsack_benchmark/Knapsack.jl", "max_forks_repo_name": "vladium/study_julia_with_me", "max_forks_repo_head_hexsha": "8c7a0b614098091ef284ebee1250c69f222fa126", "max_forks_repo_licenses": ["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.5604395604, "max_line_length": 97, "alphanum_fraction": 0.5262495505, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7802000414370817}}
{"text": "# Jonas August 1/2022\n\n#=\n\nThis problem was asked by Google.\n\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=#\n\n#=\n\nThe possible subsets are equivalent to all possible binary indicator vectors, where each bit represents presence (1) or absence (0) of a given element.\n\nThus 2^n possibilities entries in the power set.\n\nWhat about repeated elements, and thus indistinguishable subsets?\n\nI will assume that we are to compute the power set _of a set_ (which has distinct elements, by definition), that the array representing the set has unique elements (no repeated elements).  I can test this.\n\n=#\n\n\n#=\n\nAnother approach (more complex, not implemented):\n\n- Let n be length of v.\n- Let p be the power set of v, initially empty.\n- Each entry in p will be a subset of the elements of v.\n- Generate all n-bit patterns, and for each bit pattern select the components of v based where there are 1's in the pattern, and add it to p.\n\nHow to generate bit pattern?\nCount from 0 through 2^n-1 in an (unsigned?) int of sufficient bits, or create a length n bit array, and \"count\".  If we use int representation, then counting is built-in.  If we make binary array, then we have to implement increment (with carry).\n\n=#\n\n\"Construct array of all subsets of v\"\nfunction powerset(v)\n   # TODO: assert that there are no repeated elements in v\n   p = [[]]\n   for item in v\n       n = []   # new sets with item appended\n       for set in p\n           push!(n, push!(copy(set), item))\n       end\n       push!(p, n...)   # combine p and n\n   end\n   p\nend\n\n\nusing Test\n@test powerset([]) == [[]]\n@test powerset([1]) == [[], [1]]\n@test powerset([1,2]) == [[],[1],[2],[1,2]]\n# Set needed because ordering in computed powerset is different than test case.\n@test Set(powerset([1,2,3])) == Set([[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]])\n", "meta": {"hexsha": "e71340c7c68cb4d54a387e50bf70012cdbb851a9", "size": 2046, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Power Set - Problem 37.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": "Power Set - Problem 37.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": "Power Set - Problem 37.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": 32.4761904762, "max_line_length": 247, "alphanum_fraction": 0.6730205279, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.9136765251766503, "lm_q1q2_score": 0.7802000369209406}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.06\"\n\n# \u2554\u2550\u2561 fa68607e-22e5-11eb-0558-c9a4d9f77426\nn, N = 30, 10^6\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.06\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u2550d599e1d4-3a99-11eb-1ab2-637caef1df0d\n# \u2560\u2550d59a153c-3a99-11eb-1cfe-f54834ffbc5c\n# \u255f\u2500475ff888-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 \u2208 nodes && v \u2264 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 \u2208 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": "\nusing MoreBasisFunctions: vandermonde_matrix, vandermonde_matrix_inverse\n\nn = 11\nx = collect(range(0., stop=1., length=n))\ny = rand(n)\n\nV = vandermonde_matrix(x)\nW = vandermonde_matrix_inverse(x)\n\nx = V\\y\na = W*y\n\n@test maximum(abs.((a .- x) ./ a)) < eps(Float32)\n", "meta": {"hexsha": "17bd990f1de7f2c9c8a15f873da3c7c0a16c6ad1", "size": 265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/vandermonde_tests.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": "test/vandermonde_tests.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": "test/vandermonde_tests.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": 17.6666666667, "max_line_length": 72, "alphanum_fraction": 0.6905660377, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126078, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7802000263060309}}
{"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  \u03bc=p[1]\n  u\u03bc=1-\u03bc\n  @inbounds begin\n  # 1 = y\u2081\n  # 2 = y\u2082\n  # 3 = y\u2081'\n  # 4 = y\u2082'\n  D\u2081 = ((u[1]+\u03bc)^2 + u[2]^2)^(3/2)\n  D\u2082 = ((u[1]-u\u03bc)^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\u03bc*(u[1]+\u03bc)/D\u2081 - \u03bc*(u[1]-u\u03bc)/D\u2082\n  du[4] = -u[3] - u\u03bc*u[2]/D\u2081 - \u03bc*u[2]/D\u2082\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": "#=\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\nusing Test\ninclude(\"Solutions/problem37_generate_powerset.jl\")\n\n@test get_powerset([1,2,3]) == [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]\n", "meta": {"hexsha": "c6b1934eeef8e94036ba6accb8802bffcdd58460", "size": 438, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tests/problem37_generate_powerset_test.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": "Tests/problem37_generate_powerset_test.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": "Tests/problem37_generate_powerset_test.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": 33.6923076923, "max_line_length": 114, "alphanum_fraction": 0.598173516, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8824278602705732, "lm_q1q2_score": 0.7801008917862865}}
{"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  \u03b1, \u03b2, \u03b4, \u03b3 = p\n  du[1] = dx = \u03b1 * x - \u03b2 * x * y\n  du[2] = dy = -\u03b4 * y + \u03b3 * 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# \u2554\u2550\u2561 166bbbb2-8f7a-11eb-19c6-19dfe8ee5123\nusing ChainRules\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 ``\u03f5`` to satisfy ``\u03f5^2 = 0``, then similar to a complex number we define dual number as ``x = a + b \u22c5 \u03f5``\n\nthen we can intermediately get the rule of multiplication\n\n```math\n(a + b\u22c5\u03f5)(c + d\u22c5\u03f5) = ac + (ad + bc)\u03f5\n```\n\nthus we can implement our own dual number as following\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d1522092-8f48-11eb-30f2-f9c3183ae364\nBase.show(io::IO, x::Dual) = print(io, x.a, \"+\", x.b, \"\u03f5\")\n\n# \u2554\u2550\u2561 e0a6fe78-8f48-11eb-152f-5b448f08fc49\nDual(2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 25669170-8f4b-11eb-1cae-a78fc79be709\nBase.:(+)(x::Dual, y::Dual) = Dual(x.a + y.a, x.b + y.b)\n\n# \u2554\u2550\u2561 0c7cdab8-8f49-11eb-3bac-2de9b80bb7d0\nDual(3, 1) * Dual(3, 1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 28b6ea34-8f49-11eb-2625-d58fbfba667f\nf(x) = x^3\n\n# \u2554\u2550\u2561 9f7849bc-8f49-11eb-0f59-1bdf987ecdfe\nf(Dual(2))\n\n# \u2554\u2550\u2561 a7d73bb6-8f49-11eb-2c45-99fbd3a2c248\nmd\"\"\"\nthe prefactor of \u03f5 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 + \u22ef + p_n x^n\n```\n\nif we put a dual number ``x = a + b \u03f5``, we have\n\n```math\n\\begin{aligned}\nP(a+b\u03f5) \n&= p_0 + p_1 a + p_2 a^2 + \u22ef + p_n a^n + p_1 b\u03f5 + 2p_2 ab\u03f5 + \u22ef + n p_n a^{n-1}b \u03f5\\\\\n&= P(a) + b P'(a)\u03f5\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# \u2554\u2550\u2561 8a4b5ec8-8f4a-11eb-1155-f358a173daa2\nsin(Dual(2))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cfdb25b6-8f4a-11eb-2248-3f7783956f35\nBase.sin(x::Dual) = Dual(sin(x.a), cos(x.a) * x.b)\n\n# \u2554\u2550\u2561 de6df808-8f4a-11eb-0f70-43400519fd6f\nsin(Dual(2))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0906c78e-8f4b-11eb-1d3b-dd8d6d891175\nA = [Dual(1.0) Dual(2.0); Dual(1.0) Dual(2.0)]\n\n# \u2554\u2550\u2561 149734d0-8f4b-11eb-0af4-6368d8bb34c0\nB = [Dual(1.0) Dual(2.0); Dual(1.0) Dual(3.0)]\n\n# \u2554\u2550\u2561 1a483212-8f4b-11eb-0fa5-5994548ea6b9\nA * B\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c6d79168-8f4f-11eb-1c4f-4bf4abbb2c72\nfunction foo(x)\n\tx1 = sin(x)\n\tx2 = sin(x1)\n\tx3 = cos(x2) + x2\nend\n\n# \u2554\u2550\u2561 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 \u03f5`` 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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&= \u22ef\\\\\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u22c5 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\uff0c 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# \u2554\u2550\u2561 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, \u22ef, x_m)``, and we have a function ``f: \\mathbf{M} \u2192 \\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 \u2208 \\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, \u22ef, dx_m`` form the basis of the cotangent space ``\\mathbf{T}^*_p \\mathbf{M}`` for ``p\u2208\\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 72b98a42-8ff8-11eb-17f3-6d14da3964be\nx = 3.0\n\n# \u2554\u2550\u2561 1a78b2be-8f7a-11eb-0470-e7febaac6272\ny, sin_pullback = rrule(sin, x)\n\n# \u2554\u2550\u2561 627f170a-8ff8-11eb-21eb-47796905e10b\nsin_pullback(1)\n\n# \u2554\u2550\u2561 67c7f3d0-8ff8-11eb-04dc-4f796cfb940e\ncos(x)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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(\u0394)\n\t\t_, \u2202y, \u2202x2_1 = x3_pullback(\u0394)\n\t\t_, \u2202x2_2 = y_pullback(\u2202y)\n\t\t_, \u2202x1 = x2_pullback(\u2202x2_1 + \u2202x2_2)\n\t\t_, \u2202x = x1_pullback(\u2202x1)\n\t\treturn Zero(), \u2202x\n\tend\nend\n\n# \u2554\u2550\u2561 8e593406-8ff9-11eb-101a-695b2b026a20\n_, foo_pullback = adjoint_foo(x)\n\n# \u2554\u2550\u2561 9e31a492-8ff9-11eb-108d-1b7bbd152170\nfoo_pullback(1)\n\n# \u2554\u2550\u2561 a21aa0c2-8ff9-11eb-1cc8-7b63a20d0791\n(foo(x+1e-10)-foo(x-1e-10))/2e-10\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500a8439cf0-8eab-11eb-3d6b-a3d65e46a635\n# \u255f\u250012cb96f8-8f48-11eb-212d-956d24e7a892\n# \u2560\u2550af43976a-8f48-11eb-1485-0b76c7ee1e79\n# \u2560\u2550d1522092-8f48-11eb-30f2-f9c3183ae364\n# \u2560\u2550e0a6fe78-8f48-11eb-152f-5b448f08fc49\n# \u2560\u2550e4fbb1f8-8f48-11eb-220e-f33784f6e617\n# \u2560\u255025669170-8f4b-11eb-1cae-a78fc79be709\n# \u2560\u25500c7cdab8-8f49-11eb-3bac-2de9b80bb7d0\n# \u255f\u250082b578de-8f49-11eb-13dd-aba04a2c196d\n# \u2560\u255028b6ea34-8f49-11eb-2625-d58fbfba667f\n# \u2560\u25509f7849bc-8f49-11eb-0f59-1bdf987ecdfe\n# \u255f\u2500a7d73bb6-8f49-11eb-2c45-99fbd3a2c248\n# \u2560\u25508a4b5ec8-8f4a-11eb-1155-f358a173daa2\n# \u255f\u250094bc3b16-8f4a-11eb-0871-59f5469f4c0e\n# \u2560\u2550cfdb25b6-8f4a-11eb-2248-3f7783956f35\n# \u2560\u2550de6df808-8f4a-11eb-0f70-43400519fd6f\n# \u255f\u2500f2b1a960-8f4a-11eb-1276-b333b086605c\n# \u2560\u25500906c78e-8f4b-11eb-1d3b-dd8d6d891175\n# \u2560\u2550149734d0-8f4b-11eb-0af4-6368d8bb34c0\n# \u2560\u25501a483212-8f4b-11eb-0fa5-5994548ea6b9\n# \u255f\u2500f4228cb2-8eab-11eb-1b98-fbb30f8eeac3\n# \u2560\u2550c6d79168-8f4f-11eb-1c4f-4bf4abbb2c72\n# \u255f\u2500d2f7c68e-8f4f-11eb-0d90-4f2f22bd87b6\n# \u255f\u2500f75c7e22-8f52-11eb-0b32-f9ed6267fb18\n# \u255f\u25009ef95826-8f53-11eb-11ed-a35e16d20083\n# \u255f\u25000e07a38e-8f55-11eb-0c46-ef5d11df07de\n# \u255f\u250013c539e8-8eac-11eb-35b0-61108d5f3c5f\n# \u255f\u250045826916-8f55-11eb-3f3c-95d6b601191b\n# \u255f\u2500e026ffa6-8f5f-11eb-0651-dfb9e28fcc4f\n# \u255f\u250010ba0d9c-8f5f-11eb-0744-6be46cfacebe\n# \u255f\u25004921f4f8-8f60-11eb-0e45-3f3034dbea83\n# \u255f\u250029fa38b6-8f61-11eb-118a-616fc647715a\n# \u255f\u25000580566c-8ff4-11eb-35a3-bf0505fe5a1c\n# \u255f\u2500eb4df5e4-8f79-11eb-2429-a31bd0009c4b\n# \u2560\u2550166bbbb2-8f7a-11eb-19c6-19dfe8ee5123\n# \u2560\u255072b98a42-8ff8-11eb-17f3-6d14da3964be\n# \u2560\u25501a78b2be-8f7a-11eb-0470-e7febaac6272\n# \u2560\u2550627f170a-8ff8-11eb-21eb-47796905e10b\n# \u2560\u255067c7f3d0-8ff8-11eb-04dc-4f796cfb940e\n# \u255f\u25007cffb62a-8ff8-11eb-0288-f55b0d333571\n# \u2560\u255098d147c4-8ff8-11eb-3ab8-21e26217e02a\n# \u2560\u25508e593406-8ff9-11eb-101a-695b2b026a20\n# \u2560\u25509e31a492-8ff9-11eb-108d-1b7bbd152170\n# \u2560\u2550a21aa0c2-8ff9-11eb-1cc8-7b63a20d0791\n# \u255f\u2500c5f14d48-8ff9-11eb-1350-790162aa8b34\n# \u255f\u25003fc036f8-8eac-11eb-15dc-017c0d5237bc\n# \u255f\u250035cfef70-8ffa-11eb-1a48-e906596eebe6\n# \u255f\u250073ffb3fe-8ffd-11eb-2b71-038543ea5093\n# \u255f\u2500bd69872c-8f78-11eb-2197-2f760c33b197\n# \u255f\u250046ad0fa2-8eac-11eb-28df-4f2c23f8d3ff\n# \u255f\u2500cbe1949e-8ffc-11eb-0747-e576545133b4\n# \u255f\u25006616ee24-8ffd-11eb-0d13-7f7ea01d3f73\n# \u255f\u2500df1d9e58-90de-11eb-341a-bb942e20e713\n# \u255f\u2500c5f18fe2-8ffe-11eb-0a96-1f3ce397e943\n# \u255f\u2500420d72f4-8ffe-11eb-1b0f-43bdc9edf955\n# \u255f\u250084e5fe6e-8eac-11eb-04f8-cf7499b2c218\n# \u255f\u25002e3fc494-90de-11eb-1c90-f9cc1357aab3\n# \u255f\u25008d13dbe0-90de-11eb-1bcf-dfbd8118e59d\n# \u255f\u25004c23d3bc-8eac-11eb-2870-a37dfc123bc5\n# \u255f\u2500619d6b8e-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": "#\u00a0In 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#\u00a0And keep only the corresponding features values.\ny = collect(skipmissing(y))\nX = X[no_miss, :]\n\n#\u00a0Let'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\u0302 = predict(pipe, rows=test)\nround(rms(y\u0302, 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\u0302 .- y[test]\nstem(res)\n\nxticks(fontsize=12); yticks(fontsize=12)\nxlabel(\"Index\", fontsize=14); ylabel(\"Residual (y\u0302 - 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\u0302 - 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\u0302 = predict(pipe, rows=test)\nround(rms(y\u0302, 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\u0302 = predict(mtm, rows=test)\nround(rms(y\u0302, y[test])^2, sigdigits=4)\n\n# Let's see:\n\nfigure(figsize=(8,6))\n\nres = \u0177 .- y[test]\nstem(res)\n\nxticks(fontsize=12); yticks(fontsize=12)\nxlabel(\"Index\", fontsize=14);\nylabel(\"Residual (\u0177 - 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\u0302 = predict(mtm, rows=test)\nround(rms(y\u0302, 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 .\u2248 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\u0302 = predict(mtm, rows=test)\nround(rms(y\u0302, 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": "using Base.Test\nusing Einsum\n\n## Test that vars in Main aren't overwritten by einsum\nlet\n  i = -1\n  y = randn(10)\n  @einsum x[i] := y[i] \n  @test i == -1\nend\n\n## Test that B is overwritten by := operator\nlet\n  B = randn(10,10)\n  A = randn(5,10)\n  @einsum B[i,j] := A[i,j] # this should run without a problem\n  @test size(B) == size(A)\nend\n\n## CP decomposition test case ##\nlet\n\n  # preallocated test case\n  A = zeros(5,6,7);\n  B = zeros(5,6,7);\n  X = randn(5,2);\n  Y = randn(6,2);\n  Z = randn(7,2);\n\n  @einsum A[i,j,k] = X[i,r]*Y[j,r]*Z[k,r]\n  @einsimd B[i,j,k] = X[i,r]*Y[j,r]*Z[k,r]\n\n  for i = 1:5\n    for j = 1:6\n      for k = 1:7\n        s = 0.0\n        for r = 1:2\n          s += X[i,r]*Y[j,r]*Z[k,r]\n        end\n        @test isapprox(A[i,j,k],s)\n        @test isapprox(B[i,j,k],s)\n      end\n    end\n  end\n\n  # without preallocation\n  @einsum A2[i,j,k] := X[i,r]*Y[j,r]*Z[k,r]\n  @test isapprox(A,A2)\n\nend\n\n# Interesting test case, can throw an error that\n# local vars are declared twice.\nlet \n  A = zeros(5,6,7);\n  X = randn(5,2);\n  Y = randn(6,2);\n  Z = randn(7,2);\n  if true\n    @einsum A[i,j,k] = X[i,r]*Y[j,r]*Z[k,r]\n  else\n    @einsum A[i,j,k] = X[i,r]*Y[j,r]*Z[k,r]\n  end\nend\n\n# At one point this threw an error because the lhs\n# had no indices/arguments\nlet\n  x = randn(10)\n  y = randn(10)\n  @einsum k := x[i]*y[i]\n  @test isapprox(k,dot(x,y))\nend\n\n# Elementwise multiplication (this should create nested loops with no\n# no summation.)\nlet\n  x = randn(10)\n  y = randn(10)\n  @einsum k[i] := x[i]*y[i]\n  @test isapprox(k,x.*y)\nend\n\n# Transpose a block matrix\nlet\n  z = Any[ rand(2,2) for i=1:2, j=1:2]\n  @einsum t[i,j] := transpose(z[j,i])\n  @test isapprox(z[1,1], t[1,1]')\n  @test isapprox(z[2,2], t[2,2]')\n  @test isapprox(z[1,2], t[2,1]')\n  @test isapprox(z[2,1], t[1,2]')\nend\n\n# Mapping functions\nlet\n  A = randn(10,10)\n  @einsum B[i,j] := exp(A[i,j])\n  @test isapprox(exp(A),B)\nend\n\n# Example from numpy\nlet\n  A = reshape(collect(1:25),5,5)\n  @einsum B[i] := A[i,i]\n  @test all(B .== [1,7,13,19,25])\nend\n\n# TODO: consider adding support for this:\n# @einsum A[i,j] = A[i,j] + 50\n\n## Test in-place operations ##\nlet\n  A = randn(5,6,7);\n  B = randn(5,6,7);\n  A1 = copy(A);\n  B1 = copy(B);\n\n  X = randn(5,2);\n  Y = randn(6,2);\n  Z = randn(7,2);\n\n  @einsum A[i,j,k] += X[i,r]*Y[j,r]*Z[k,r]\n  @einsimd B[i,j,k] += X[i,r]*Y[j,r]*Z[k,r]\n\n  for i = 1:5\n      for j = 1:6\n          for k = 1:7\n              s = 0.0\n              for r = 1:2\n                  s += X[i,r]*Y[j,r]*Z[k,r]\n              end\n              @test isapprox(A[i,j,k],A1[i,j,k]+s)\n              @test isapprox(B[i,j,k],B1[i,j,k]+s)\n          end\n      end\n  end\n\n  x = randn(10)\n  y = randn(10)\n  k0 = randn()\n  k = k0\n  @einsum k += x[i]*y[i]\n  @test isapprox(k,k0+dot(x,y))\n\n  # test multiplication\n\n  A1[:] = A[:]\n  B1[:] = B[:]\n\n  @einsum A[i,j,k] *= X[i,r]*Y[j,r]*Z[k,r]\n  @einsimd B[i,j,k] *= X[i,r]*Y[j,r]*Z[k,r]\n\n  for i = 1:5\n      for j = 1:6\n          for k = 1:7\n              s = 0.0\n              for r = 1:2\n                  s += X[i,r]*Y[j,r]*Z[k,r]\n              end\n              @test isapprox(A[i,j,k],A1[i,j,k]*s)\n              @test isapprox(B[i,j,k],B1[i,j,k]*s)\n          end\n      end\n  end\n\n  x = randn(10)\n  y = randn(10)\n  k0 = randn()\n  k = k0\n  @einsum k *= x[i]*y[i]\n  @test isapprox(k,k0*dot(x,y))\nend\n\n# Test offsets\nlet\n  X = randn(10)\n\n  # without preallocation\n  @einsum A[i] := X[i+5]\n  @test size(A) == (5,)\n  @test all(A .== X[6:end])\n\n  # with preallocation\n  B = zeros(10)\n  @einsum B[i] = X[i+5]\n  @test size(B) == (10,)\n  @test all(B[1:5] .== X[6:end])\nend\n\n# Test symbolic offsets\nlet\n  offset = 5\n  X = randn(10)\n\n  # without preallocation\n  @einsum A[i] := X[i+:offset]\n  @test size(A) == (5,)\n  @test all(A .== X[6:end])\n\n  # with preallocation\n  B = zeros(10)\n  @einsum B[i] = X[i+:offset]\n  @test size(B) == (10,)\n  @test all(B[1:5] .== X[6:end])\nend\n\n# Test adding/subtracting constants\nlet\n  k = 5\n  X = randn(10)\n\n  # without preallocation\n  @einsum A[i] := X[i] + k\n  @einsum B[i] := X[i] - k\n  @test isapprox(A,X+k)\n  @test isapprox(B,X-k)\n\n  # with preallocation\n  C,D = zeros(10),zeros(10)\n  @einsum C[i] = X[i] + k \n  @einsum D[i] = X[i] - k \n  @test isapprox(C,X+k)\n  @test isapprox(D,X-k)\nend\n\n# Test multiplying/dividing constants\nlet\n  k = 5\n  X = randn(10)\n\n  # without preallocation\n  @einsum A[i] := X[i]*k\n  @einsum B[i] := X[i]/k\n  @test isapprox(A,X.*k)\n  @test isapprox(B,X./k)\n\n  # with preallocation\n  C,D = zeros(10),zeros(10)\n  @einsum C[i] = X[i]*k \n  @einsum D[i] = X[i]/k \n  @test isapprox(C,X.*k)\n  @test isapprox(D,X./k)\nend\n\n# Test indexing with a constant\nlet\n  A = randn(10,2)\n  j = 2\n  @einsum B[i] := A[i,:j]\n  @test all(B .== A[:,j])\n  @einsum C[i] := A[i,1]\n  @test all(C .== A[:,1])\n  \n  D = zeros(10,3)\n  @einsum D[i,1] = A[i,:j]\n  @test isapprox(D[:,1],A[:,j])\n  @einsum D[i,:j] = A[i,:j]\n  @test isapprox(D[:,j],A[:,j])\nend\n\n# Better type inference on allocating arrays\nlet\n  B1 = ones(Int,5)\n  B2 = ones(Float32,5)\n  B3 = ones(5)\n  C = randn(5)\n  @einsum A1[i,j] := B1[i]*C[j]\n  @einsum A2[i,j] := B2[i]*C[j]\n  @einsum A3[i,j] := B3[i]*C[j]\n\n  @test eltype(A1) == Float64\n  @test eltype(A2) == Float64\n  @test eltype(A3) == Float64\n  @test isapprox(A1,A3)\n  @test isapprox(A2,A3)\nend\n", "meta": {"hexsha": "9e2b48a17db2484f95520ea861d488fd60e6ee81", "size": 5254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaPackageMirrors/Einsum.jl", "max_stars_repo_head_hexsha": "6b8fca1d1df60ea9a786e9f54825cbdd71f3fda2", "max_stars_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Einsum.jl", "max_issues_repo_head_hexsha": "6b8fca1d1df60ea9a786e9f54825cbdd71f3fda2", "max_issues_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Einsum.jl", "max_forks_repo_head_hexsha": "6b8fca1d1df60ea9a786e9f54825cbdd71f3fda2", "max_forks_repo_licenses": ["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.9675090253, "max_line_length": 69, "alphanum_fraction": 0.5216977541, "num_tokens": 2166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.8688267898240861, "lm_q1q2_score": 0.7799417260157561}}
{"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\u03c4 = estimate_delay(w, \"mi_min\")\nR = embed(w, 3, \u03c4)\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+\u03c4)\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=$(\u03b3),\\\\tau=$(\u03c4))\\$\")\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\u0144ski (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\u2084 and x\u2085 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 NewtonsMethod\nusing Test\n\n@testset \"NewtonsMethod.jl\" begin\n    # Write your tests here.\n    f_1(x) = x^2 - 3x + 2\n    f_2(x) = sin(x)\n    f_3(x) = log(x)\n    f_4(x) = 1/x - 4\n    f_5(x) = x+3\n    f_6(x) = 3\n    f_7(x) = 0\n    f_8(x) = exp(x) - 5\n    f_prime_1(x) = 2x - 3\n    f_prime_2(x) = cos(x)\n    f_prime_3(x) = 1/x\n    f_prime_4(x) = -1/(x^2)\n    f_prime_5(x) = 1\n    f_prime_6(x) = 0\n    f_prime_7(x) = 0\n    f_prime_8(x) = exp(x)\n    @test newtonroot(f_1, f_prime_1; x_0 = 0) \u2248 1\n    @test newtonroot(f_2, f_prime_2; x_0 = 3) \u2248 \u03c0\n    @test newtonroot(f_3, f_prime_3; x_0 = 0.7) \u2248 1\n    @test newtonroot(f_4, f_prime_4; x_0 = 0.4) \u2248 0.25\n    @test newtonroot(f_5, f_prime_5; x_0 = 0) \u2248 -3\n    @test newtonroot(f_6, f_prime_6; x_0 = 1) === nothing\n    @test newtonroot(f_7, f_prime_7; x_0 = 4) == 4 \n    @test newtonroot(f_8, f_prime_8; x_0 = 3) \u2248 log(5)\n    @test newtonroot(f_1; x_0 = 0) \u2248 1\n    @test newtonroot(f_2; x_0 = 3) \u2248 \u03c0\n    @test newtonroot(f_3; x_0 = 0.7) \u2248 1\n    @test newtonroot(f_4; x_0 = 0.4) \u2248 0.25\n    @test newtonroot(f_5; x_0 = 0) \u2248 -3\n    @test newtonroot(f_6; x_0 = 1) === nothing\n    @test newtonroot(f_7; x_0 = 4) == 4\n    @test newtonroot(f_8; x_0 = 3) \u2248 log(5)\nend\n\n@testset \"non convergence\" begin\n    f(x) = x^2+2\n    f_prime(x) = 2x\n    @test newtonroot(f, f_prime; x_0 = 0) === nothing\n    @test newtonroot(f, f_prime; x_0 = 0.5) === nothing\n    @test newtonroot(f;x_0 = 0) === nothing\n    @test newtonroot(f;x_0 = 0.5) === nothing\nend\n\n@testset \"Big Float\" begin\n    f(x) = x^2 - 3x + 2\n    f_prime(x) = 2x - 3\n    x_0 = parse(BigFloat, \"0.34\")\n    @test convert(Float64, newtonroot(f, f_prime; x_0 = x_0)) \u2248 1\n    @test convert(Float64, newtonroot(f; x_0 = x_0)) \u2248 1\nend\n\n@testset \"max iter\" begin\n    f(x) = exp(x) - 5\n    f_prime(x) = exp(x)\n    @test newtonroot(f, f_prime; x_0 = 0, maxiter = 5) === nothing\n    @test newtonroot(f; x_0 = 0, maxiter = 5) === nothing\nend\n\n@testset \"tolerance\" begin\n    f(x) = 3\n    f_prime(x) = 3\n    @test newtonroot(f, f_prime; x_0 = 4, tol = 3) == 4\n    @test newtonroot(f; x_0 = 4, tol = 3) == 4\nend", "meta": {"hexsha": "9e4a0f7f858cdda846288233cb540195927aa38c", "size": 2086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 30.231884058, "max_line_length": 66, "alphanum_fraction": 0.570949185, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.7799417017474083}}
{"text": "using StatsBase\nusing RDatasets\na = [123,4234,23423,1231231,1432432423,1341413413]\nvar(a)\nvar(a, 2)\nstd(a)\nmean_and_var(a)\nmean_and_std(a)\nskewness(a)\nkurtosis(a)\nmoment(a,3)\nspan(a)\nvariation(a)\n", "meta": {"hexsha": "1133e12d458b7484cc1e3275315814f4bc7e892e", "size": 196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter 3/5.jl", "max_stars_repo_name": "PacktPublishing/Julia-for-data-science", "max_stars_repo_head_hexsha": "dbdb53aa9294324ef982f1189acbcb78fbd2cb80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2017-01-22T13:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T21:45:32.000Z", "max_issues_repo_path": "Chapter 3/5.jl", "max_issues_repo_name": "PacktPublishing/Julia-for-data-science", "max_issues_repo_head_hexsha": "dbdb53aa9294324ef982f1189acbcb78fbd2cb80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 3/5.jl", "max_forks_repo_name": "PacktPublishing/Julia-for-data-science", "max_forks_repo_head_hexsha": "dbdb53aa9294324ef982f1189acbcb78fbd2cb80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-10-13T15:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T14:59:57.000Z", "avg_line_length": 14.0, "max_line_length": 50, "alphanum_fraction": 0.7551020408, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7799383346725823}}
{"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 \u03be between X and Y.\n\nUnlike most coefficients of correlation, \u03be 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> \u03be = 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> \u03be = xicor(x, y, true, MersenneTwister(0))\n-0.01830183018301823\njulia> \u03be = 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] \u2264 Y[i]\n    L = zeros(Int, n)  # L[i] is the number of j such that Y[j] \u2265 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": "# Jonas August 1/2022\n\n#=\nThis problem was asked by Google.\n\nGiven an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer.\n\nFor example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19.\n\nDo this in O(N) time and O(1) space.\n=#\n\n#=\nAssume that the array is correctly formed (one single among triples; no doubles, quadruples, etc.; only integers).\n\nThere are only at most (n-1)/3 + 1 unique numbers.\n\nn = 3*m+1 is odd if m even and vice versa.\n\n=#\n\n#=\nIf y is the single entry, then the sum of the remaining entries is divisible by three.  Let x\\y denote set x with y removed.\n\ny is unique in in x => (sum of z s.t. z in x\\y) mod 3 = 0\n\nThis is necessary condition for identifying y, but is it sufficient?  No!  Consider x=[13,19,13,13].  Try y=13.  Then sum of x\\y is 19+13+13 = 45 which is divisible by 3.  Argh!\n\nBut maybe there's some function of the elements that can be used instead?\n\nIf a,b are integers, then cube root of aab is integer iff b = a?\n\nRelevance Fermat's last theorem?\nx^k + y^k = z^k has no positive integer solutions x,y,z for integer k>2.\nTry k = 3 and cube entries?\n\n=#\n\n\"Find that integer in input array x that has no match, while all other elements come in three, in no particular order.  Takes O(n) time, O(1) space, where n = length of the array.\"\nfunction single_among_triples_fast(x::Vector{Int})::Int\n    # TODO: allow zeros and negatives\n    if any(x .== 0) @error(\"No zeroes allowed\") end\n    if any(x .< 0) @error(\"No negatives allowed\") end\n    p = 1\n    for y in x\n        p *= y\n    end\n    for y in x\n        # TODO: CHECK that this always works\n        c = (p/y)^(1/3)\n        # TODO: what tolerance ensures correct results?\n        if abs(c-round(c)) < sqrt(eps(c))    # is c approximately an integer?\n            return y\n        end\n    end\n    @error(\"This line should never be reached for well-formed input.\")\nend\n\n\n\"Find that integer in input array x that has no match, while all other elements come in three, in no particular order.  Takes O(n^2) time, O(1) space, where n = length of the array.\"\nfunction single_among_triples_brute_force(x::Vector{Int})::Int\n    for i in 1:length(x)\n       matched = false\n       for j in i+1:length(x)\n           if x[j] == x[i]\n\t       matched = true\n\t       break\n\t   end\n       end\n       if !matched\n           return x[i]\n       end\n    end\n    @error(\"This line should never be reached for well-formed input.\")\nend\n\n#=\nOther False starts:\n\nNot O(1) space:\n\n- Convert to linked list.  Pick first element and scan for match and delete matches if found, then start again.  Must end up with unmatched number at beginning.\n\nx[i[1]] is unique in x[:]\nx[i[2]] == x[i[3]] == x[i[4]]\nx[i[5]] == x[i[6]] == x[i[7]]\n...\n\nx[i[1]] + sum(j = 2:3:n) 3*x[i[j]]\n\nNot O(n) time:\n\n- Sort.  Triples will cluster, so linearly scan for the single.\n\n=#\n\n# TODO: Construct random inputs\n\nusing Test\n\nfor single_among_triples in [single_among_triples_brute_force, single_among_triples_fast]\n  # @test @test single_among_triples([]) == ?  not defined? exception?\n  @test single_among_triples([19]) == 19\n  @test single_among_triples([13, 19, 13, 13]) == 19\n  @test single_among_triples([6, 1, 3, 3, 3, 6, 6]) == 1\nend\n", "meta": {"hexsha": "e29c471187d0ade1eebfea58ea9f28419d57809f", "size": 3300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Single among triples - Problem 40.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": "Single among triples - Problem 40.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": "Single among triples - Problem 40.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": 30.8411214953, "max_line_length": 182, "alphanum_fraction": 0.6581818182, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.7798966495916374}}
{"text": "using Multicombinations\nusing Base.Test\n\n# multichoose\n\n@test multichoose(3,2) == 6\n@test multichoose(3,0) == 1\n@test multichoose(0,3) == 0\n@test multichoose(0,0) == 1\n@test multichoose(-1,-1) == 0\n\n# multicombinations\n\n@test collect(multicombinations(\"abc\",3)) == [\"aaa\",\"aab\",\"aac\",\"abb\",\"abc\",\"acc\",\"bbb\",\"bbc\",\"bcc\",\"ccc\"]\n@test collect(multicombinations(\"\u00e5\u00e4\u00f6\",3)) == [\"\u00e5\u00e5\u00e5\",\"\u00e5\u00e5\u00e4\",\"\u00e5\u00e5\u00f6\",\"\u00e5\u00e4\u00e4\",\"\u00e5\u00e4\u00f6\",\"\u00e5\u00f6\u00f6\",\"\u00e4\u00e4\u00e4\",\"\u00e4\u00e4\u00f6\",\"\u00e4\u00f6\u00f6\",\"\u00f6\u00f6\u00f6\"]\n@test collect(multicombinations(\"abc\",0)) == collect(combinations(\"abc\",0))\n@test collect(multicombinations(\"\",1)) == collect(combinations(\"\",1))\n@test collect(multicombinations(\"\",0)) == collect(combinations(\"\",0))\n@test collect(multicombinations(\"\",-1)) == collect(combinations(\"\",-1))\n\n# integersums\n\n@test collect(integersums(3,3)) == {[3,0,0],[2,1,0],[2,0,1],[1,2,0],[1,1,1],[1,0,2],[0,3,0],[0,2,1],[0,1,2],[0,0,3]}\n@test collect(integersums(3,0)) == {[0,0,0]}\n@test collect(integersums(0,3)) == {}\n@test collect(integersums(0,0)) == {[]}\n@test collect(integersums(-1,-1)) == {}\n\n# is2mc\n\n@test map(is2mc,integersums(3,3)) == collect(multicombinations(1:3,3))\n@test map(is2mc,integersums(3,0)) == collect(multicombinations(1:3,0))\n@test map(is2mc,integersums(0,3)) == collect(multicombinations([],3))\n@test map(is2mc,integersums(0,0)) == collect(multicombinations([],0))\n\n# length\n\n@test length(collect(multicombinations(\"abc\",3))) == length(multicombinations(\"abc\",3))\n@test length(collect(multicombinations(\"\u00e5\u00e4\u00f6\",3))) == length(multicombinations(\"\u00e5\u00e4\u00f6\",3))\n@test length(collect(integersums(3,3))) == length(integersums(3,3))\n", "meta": {"hexsha": "f02804256fdd23126f10bd3c22435065d173164b", "size": 1565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jarnoharno/Multicombinations.jl", "max_stars_repo_head_hexsha": "4c7ac6b5d237a04fa5477c0394bad677db96c77f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-26T03:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:06:17.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "jlep/Multicombinations.jl", "max_issues_repo_head_hexsha": "4c7ac6b5d237a04fa5477c0394bad677db96c77f", "max_issues_repo_licenses": ["MIT"], "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": "jlep/Multicombinations.jl", "max_forks_repo_head_hexsha": "4c7ac6b5d237a04fa5477c0394bad677db96c77f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:15:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:15:10.000Z", "avg_line_length": 38.1707317073, "max_line_length": 116, "alphanum_fraction": 0.6626198083, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7798966317354848}}
{"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} \u03b2_{t} + A z_{t} + e_{t} .\nTransition Equation:    \n    \u03b2_{t} = \u03bc + F \u03b2_{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- \u03bc         = 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, \u03bc, 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_\u03b2 = 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 \u03b2_pred and P_pred \n    \u03b2_pred_laglag = inv(I - F) * \u03bc\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        \u03b2_pred_lag = \u03bc + F * \u03b2_pred_laglag\n        P_pred_lag = F * P_pred_laglag * transpose(F) + Q\n        y_pred_lag = H * \u03b2_pred_lag\n        \u03b7_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        \u03b2_pred = \u03b2_pred_lag + K * \u03b7_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_\u03b2[t, :] = \u03b2_pred\n\n        # Lag the predictions \n        \u03b2_pred_laglag = \u03b2_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_\u03b2, 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} \u03b2_{t} + A z_{t} + e_{t}.\nTransition Equation:    \n    \u03b2_{t} = \u03bc + F \u03b2_{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- \u03bc         = 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, \u03bc, 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_\u03b2 = 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_\u03b2, Pttlag, Ptt = kalmanFilter(data_y, ssmodel)\n\n    # Initialize \u03b2_{t+1|T} (\u03b2_{T|T})\n    \u03b2tflagT = data_filtered_\u03b2[end]\n    data_smoothed_\u03b2[end] = \u03b2tflagT\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 \u03b2_{t|t}\n        \u03b2tt = data_filtered_\u03b2[end-i]\n\n        # Compute \u03b2_{t|T} using \u03b2_{t+1|T}, \u03b2_{t|t}, P_{t|t}, and P_{t+1|t}\n        \u03b2tT = \u03b2tt +\n              Ptt[end-i] * transpose(F) * inv(Pttlag[end-i+1]) *\n              (\u03b2tflagT - F * \u03b2tt - \u03bc)\n\n        # Store \u03b2_{t+1|T} in smoothed data \n        data_smoothed_\u03b2[end-i] = \u03b2tT\n\n        # Set \u03b2_{t|T} as new \u03b2_{t+1|T} for next iteration \n        \u03b2tflagT = \u03b2tT\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 * \u03b2tT\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_\u03b2, 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} \u03b2_{t} + A z_{t} + e_{t}.\nTransition Equation:    \n    \u03b2_{t} = \u03bc + F \u03b2_{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- \u03bc         = 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, \u03bc, R, Q, Z = ssmodel\n\n    # Run Kalman filter \n    data_filtered_y, data_filtered_\u03b2, Pttlag, Ptt = kalmanFilter(data_y, ssmodel)\n\n    # Create placeholders for factor distr. \n    # mean vector and covariance matrix for all t \n    \u03b2_t_mean = Any[]\n    \u03b2_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    \u03b2_realized = similar(data_filtered_\u03b2)\n\n    # Initialize \u03b2_realized \n    push!(\u03b2_t_mean, data_filtered_\u03b2[T, :])\n    push!(\u03b2_t_var, Ptt[T])\n    \u03b2_realized[T, :] = sim_MvNormal_alt(\u03b2_t_mean[1], \u03b2_t_var[1])\n\n    # Generate `\u03b2_t_mean` and `\u03b2_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            # \u03b2_{t|t,\u03b2*_{t+1}}\n            \u03b2_t_mean_temp = data_filtered_\u03b2[T-j, :]\n            +Ptt[T-j] * transpose(F_star) * inv(F_star * Ptt[T-j] * transpose(F_star) + Q_star) * (\u03b2_realized[T+1-j, :][1:num_use_rows] - \u03bc[1:num_use_rows] - F_star * data_filtered_\u03b2[T-j, :])\n            push!(\u03b2_t_mean, \u03b2_t_mean_temp)\n\n            # P_{t|t,\u03b2*_{t+1}}\n            \u03b2_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!(\u03b2_t_var, \u03b2_t_var_temp)\n\n            # Draw new \u03b2_t \n            \u03b2_realized[T-j, :] = sim_MvNormal_alt(\u03b2_t_mean[1+j], \u03b2_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            # \u03b2_{t|t,\u03b2_{t+1}}\n            \u03b2_t_mean_temp = data_filtered_\u03b2[T-j, :]\n            +Ptt[T-j] * transpose(F) * inv(F * Ptt[T-j] * transpose(F) + Q) * (\u03b2_realized[T+1-j, :] - \u03bc - F * data_filtered_\u03b2[T-j, :])\n            push!(\u03b2_t_mean, \u03b2_t_mean_temp)\n\n            # P_{t|t,\u03b2_{t+1}}\n            \u03b2_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!(\u03b2_t_var, \u03b2_t_var_temp)\n\n            # Draw new \u03b2_t \n            \u03b2_realized[T-j, :] = sim_MvNormal_alt(\u03b2_t_mean[1+j], \u03b2_t_var[1+j])\n        end\n    end\n\n    # Return sampled factor series \n    # fot t = 1,...,T \n    return \u03b2_realized\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    linearRegressionSampler(Y,X)\n\nDescription: \nEstimate \u03b2 and \u03c3^2 in Y = X\u03b2 + e, e ~ N(0,\u03c3^2 I_T).\nGenerate samples of \u03b2 and \u03c3^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 \u03c32 \n    \u03c32 = 1.0\n\n    ##################################\n    ##################################\n    # Generate new \u03b2\n\n    ## Prior parameters in N(\u03b20,\u03a30)\n    \u03b20 = zeros(size(X)[2])\n    \u03a30 = Matrix(I, size(\u03b20)[1], size(\u03b20)[1]) .* 1000.0\n\n    ## Posterior parameters in N(\u03b21,\u03a31) \n    \u03b21 = inv(inv(\u03a30) + inv(\u03c32) * transpose(X) * X) * (inv(\u03a30) * \u03b20 + inv(\u03c32) * transpose(X) * Y)\n    \u03b21 = vec(\u03b21)\n    \u03a31 = inv(inv(\u03a30) + inv(\u03c32) * transpose(X) * X)\n    \u03a31 = Hermitian(\u03a31)\n\n    ## Generate new \u03b2\n    \u03b2 = sim_MvNormal(\u03b21, \u03a31)\n\n    ##################################\n    ##################################\n    # Update \u03c32\n\n    ## Prior parameters in IG(\u03bd0/2, \u03b40/2) \n    \u03bd0 = 0.002\n    \u03b40 = 0.002\n\n    ## Posterior parameters in IG(\u03bd1/2, \u03b41/2)\n    \u03bd1 = \u03bd0 + T\n    \u03b41 = \u03b40 + norm(Y - X * \u03b2)^2\n\n    ## Generate new \u03c32\n    \u03c32 = rand(InverseGamma(\u03bd1 / 2, \u03b41 / 2))\n\n    ##################################\n    ##################################\n    # Return parameters \n    return \u03b2, \u03c32\nend;\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n######################\n@doc \"\"\"\n    \n    linearRegressionSamplerRestrictedVariance(Y, X, \u03c32)\n\nDescription: \nEstimate \u03b2 and \u03c3^2 in Y = X\u03b2 + e, e ~ N(0,\u03c3^2 I_T),\nwhere \u03c3^2 is restricted to some chosen value. \nGenerate samples of \u03b2 and \u03c3^2. \n\nInputs: \n- Y     = Dependent data matrix\n- X     = Independent data matrix \n- \u03c32    = Restricted error variance \n\"\"\"\nfunction linearRegressionSamplerRestrictedVariance(Y, X, \u03c32)\n\n    # Save number of obs \n    T = size(X)[1]\n\n    ##################################\n    ##################################\n    # Generate new \u03b2\n\n    ## Prior parameters in N(\u03b20,\u03a30)\n    \u03b20 = zeros(size(X)[2])\n    \u03a30 = Matrix(I, size(\u03b20)[1], size(\u03b20)[1]) .* 1000.0\n\n    ## Posterior parameters in N(\u03b21,\u03a31) \n    \u03b21 = inv(inv(\u03a30) + inv(\u03c32) * transpose(X) * X) * (inv(\u03a30) * \u03b20 + inv(\u03c32) * transpose(X) * Y)\n    \u03b21 = vec(\u03b21)\n    \u03a31 = inv(inv(\u03a30) + inv(\u03c32) * transpose(X) * X)\n    \u03a31 = Hermitian(\u03a31)\n\n    ## Generate new \u03b2\n    \u03b2 = sim_MvNormal(\u03b21, \u03a31)\n\n    ##################################\n    ##################################\n    # Return parameters \n    return \u03b2\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 \u03b2, \u03c3^2, and \u03d5 in Y = X\u03b2 + e, e = E\u03d5 + \u03bd, \u03bd_t ~ i.i.d.N(0,\u03c3^2).  \nGenerate samples of \u03b2, \u03c3^2, and \u03d5.  \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, \u03d5old, \u03c32old, error_lag_num)\n\n    # Save number of obs \n    T = size(X)[1]\n\n    # Initialize \u03c32 \n    \u03d5 = \u03d5old\n    \u03c32 = \u03c32old\n\n    ##################################\n    ##################################\n    # Generate \u03b2\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^\u22c6 \n    X_star = similar(X[(1+length(\u03d5)):end, :])\n    for i = 1:size(X)[2] # iterate over variables in X\n        x_temp = X[:, i]\n        for p = 1:length(\u03d5) # iterate over lag params in \u03d5\n            x_temp[(1+length(\u03d5)):end, :] = x_temp[(1+length(\u03d5)):end, :] - \u03d5[p] .* lag(x_temp, p)[(1+length(\u03d5)):end, :]\n        end\n        x_temp = x_temp[(1+length(\u03d5)):end, :]\n        X_star[:, i] = x_temp\n    end\n\n    ## Generate Y^\u22c6\n    Y_star = similar(Y[(1+length(\u03d5)):end, :])\n    y_temp = Y\n    for p = 1:length(\u03d5)\n        y_temp = Y\n        y_temp = y_temp[(1+length(\u03d5)):end, :] - \u03d5[p] .* lag(y_temp, p)[(1+length(\u03d5)):end, :]\n    end\n    Y_star = y_temp\n\n    ## Posterior parameters in N(b1,A1) \n    b1 = inv(inv(A0) + inv(\u03c32) * transpose(X_star) * X_star) * (inv(A0) * b0 + inv(\u03c32) * transpose(X_star) * Y_star)\n    b1 = vec(b1)\n    A1 = inv(inv(A0) + inv(\u03c32) * transpose(X_star) * X_star)\n    A1 = Hermitian(A1)\n\n    ## Draw new \u03b2\n    \u03b2 = sim_MvNormal(b1, A1)\n\n    ##################################\n    ##################################\n    # Generate \u03d5\n\n    ## Prior parameters in N(c0,B0)\n    c0 = zeros(size(\u03d5)[1])\n    B0 = Matrix(I, size(c0)[1], size(c0)[1]) .* 1000.0\n\n    ## Generate e^\u22c6 \n    e_star = Y - X * \u03b2\n\n    ## Generate E^\u22c6\n    E_star = zeros(T, length(\u03d5))\n    E_star = E_star[(1+length(\u03d5)):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(\u03d5)):end]\n    end\n    e_star = e_star[(1+length(\u03d5)):end]\n\n    ## Posterior parameters in N(c1,B1)\n    c1 = inv(inv(B0) + inv(\u03c32) * transpose(E_star) * E_star) * (inv(B0) * c0 + inv(\u03c32) * transpose(E_star) * e_star)\n    c1 = vec(c1)\n    B1 = inv(inv(B0) + inv(\u03c32) * transpose(E_star) * E_star)\n    B1 = Hermitian(B1)\n\n    ## Generate new \u03d5\n    ###=\n    ind = 0\n    accept = 0\n    \u03d5 = similar(\u03d5old)\n    while accept == 0\n\n        ind += 1\n\n        ## Draw \u03c8\n        \u03d5 = sim_MvNormal(c1, B1)\n\n        ## Check for stationarity \n        coef = [-reverse(vec(\u03d5), 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            \u03d5 = \u03d5old\n            coef = [-reverse(vec(\u03d5), 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    #\u03d5 = sim_MvNormal(c1, B1)\n\n\n    ##################################\n    ##################################\n    # Generate \u03c32\n\n    ## Prior parameters in IG(\u03bd0/2, \u03b40/2) \n    \u03bd0 = 0.002\n    \u03b40 = 0.002\n\n    ## Posterior parameters in IG(\u03bd1/2, \u03b41/2)\n    \u03bd1 = \u03bd0 + T\n    \u03b41 = \u03b40 .+ norm(Y_star - X_star * \u03b2)^2\n    \u03b41 = \u03b41[1, 1]\n\n    ## Generate new \u03c32\n    \u03c32 = rand(InverseGamma(\u03bd1 / 2, \u03b41 / 2))\n\n    ##################################\n    ##################################\n    # Return parameters \n    return \u03b2, \u03c32, \u03d5\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, \u03b5 = box_counting_dimension(s, 9, 0.0)\n\nloglog_regression(N,\u03b5)\n\nlog(3)/log(2)\n\nplot(-log.(\u03b5), log.(N), xlabel=\"-ln \u03b5\", 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# \u2554\u2550\u2561 37b018c4-34b0-11eb-234d-4fbeaa683873\nusing LinearAlgebra, SparseArrays, Plots, DifferentialEquations\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8f5d25dc-34ae-11eb-2aa7-39e601f648a1\nmd\"#### Code: implementing physical constants\"\n\n# \u2554\u2550\u2561 8f493cca-34ae-11eb-3e60-31ab68674568\n# Length of rod\nL = 0.5\n\n# \u2554\u2550\u2561 8f149f6a-34ae-11eb-01f2-5983e256a7de\n# Thermal conductivity\n\u03bb = 45.0 \n\n# \u2554\u2550\u2561 8efa0286-34ae-11eb-1952-e790d141e19b\n# Specific heat capacity\nc = 480.0\n\n# \u2554\u2550\u2561 8ecb6bba-34ae-11eb-2c16-819675412725\n# Mass density\n\u03c1 = 7800.0\n\n# \u2554\u2550\u2561 e6433430-34af-11eb-318d-2199461e5ec9\n# Thermal diffusivity\n\u03b1 = \u03bb/(c*\u03c1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 65049b1a-3549-11eb-33ee-9dfae609164d\n# Number of grid elements\nN = 101\n\n# \u2554\u2550\u2561 a36fd440-3549-11eb-0e93-0d36244400ef\n# Finite discretization\n\u0394x = L/(N-1)   \n\n# \u2554\u2550\u2561 c18a976a-3549-11eb-2991-799f558e4493\n# 1-dimensional grid\nxspan = 0 : \u0394x : L\n\n# \u2554\u2550\u2561 d7d5be46-3549-11eb-3a12-afab5ab4bce5\n# Diffusion matrix\nM = spdiagm(-1 => ones(N-1), 0 => -2*ones(N), 1 => ones(N-1));\n\n# \u2554\u2550\u2561 045066e2-354a-11eb-164b-09fc7095de47\nMatrix(M)[1:5,1:5]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3768b7e0-34b0-11eb-0772-f5f4c95cf8f5\n# First row\nM[1,1] = M[1,2] = 0;\n\n# \u2554\u2550\u2561 37529500-34b0-11eb-1ee4-b5837bea23c9\n# Last row\nM[end,end] = M[end,end-1] = 0;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 371c6d52-34b0-11eb-12ab-a51e10fe33c5\n# Heat Equation as ODE\nfunction heat_eq(d\u03b8, \u03b8, p, t)\n    return d\u03b8 .= (1/\u0394x^2) * \u03b1 * M * \u03b8\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 78b7fa20-354c-11eb-3754-d5d515d0a2d5\n#Initial conditions: \u03b8(0) = m * (L * x - x^2)\nfunction initial_data(x, params)\n    # \u03b1 = params[1] # unused here \n    L = params[2]\n    m = params[3]\n\n    return m*( L * x - x^2)\nend\n\n# \u2554\u2550\u2561 77906a42-354c-11eb-397e-9dca847ab964\n# Initial heat distribution\n\u03b8\u2080 = zeros(N);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a91c8b80-354d-11eb-03ec-8f4386a69708\nm = amp\n\n# \u2554\u2550\u2561 86f0f21c-354d-11eb-2a32-299183f9118b\n# Parameters\nparam = [\u03b1, L, amp]\n\n# \u2554\u2550\u2561 666a8878-354d-11eb-22dc-e94a72ede22d\nlet\n\n\tfor i = 1 : length(xspan)\n\t\t\u03b8\u2080[i] = initial_data(xspan[i], param)\n\tend\n\t\n\tplot(xspan, \u03b8\u2080, xlabel=\"Position x\", ylabel=\"Temperature\", legend=false)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 25789968-3552-11eb-1e25-35c0d1b1c461\n# Upper limit of sampling time\nul = 0.5 * \u0394x^2 / \u03b1\n\n# \u2554\u2550\u2561 56daee6e-3554-11eb-37cd-49ad4ac56805\n# Sampling time\n\u0394t = 0.8\n\n# \u2554\u2550\u2561 56bb225a-3554-11eb-0062-6d03b8ea772f\n# time discretization\ntspan = (0.0, 1000.0)\n\n# \u2554\u2550\u2561 569a20f0-3554-11eb-0479-f1e583620682\nmd\"### Code: Solving the ODE\"\n\n# \u2554\u2550\u2561 56790ed8-3554-11eb-3c51-b9b31a4c340e\n# Solving the ODE\nlet\n\tprob = ODEProblem( heat_eq, \u03b8\u2080, tspan ) # ODE Problem\n\t\n\tsol = solve(prob,Euler(),dt=\u0394t,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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500baed3ace-34ad-11eb-0cf6-19357238b1de\n# \u255f\u25008f5d25dc-34ae-11eb-2aa7-39e601f648a1\n# \u2560\u25508f493cca-34ae-11eb-3e60-31ab68674568\n# \u2560\u25508f149f6a-34ae-11eb-01f2-5983e256a7de\n# \u2560\u25508efa0286-34ae-11eb-1952-e790d141e19b\n# \u2560\u25508ecb6bba-34ae-11eb-2c16-819675412725\n# \u2560\u2550e6433430-34af-11eb-318d-2199461e5ec9\n# \u255f\u250037c91fae-34b0-11eb-0f82-639173602ac0\n# \u2560\u255037b018c4-34b0-11eb-234d-4fbeaa683873\n# \u2560\u255065049b1a-3549-11eb-33ee-9dfae609164d\n# \u2560\u2550a36fd440-3549-11eb-0e93-0d36244400ef\n# \u2560\u2550c18a976a-3549-11eb-2991-799f558e4493\n# \u2560\u2550d7d5be46-3549-11eb-3a12-afab5ab4bce5\n# \u2560\u2550045066e2-354a-11eb-164b-09fc7095de47\n# \u255f\u250037822ec8-34b0-11eb-175d-7745382c2955\n# \u2560\u25503768b7e0-34b0-11eb-0772-f5f4c95cf8f5\n# \u2560\u255037529500-34b0-11eb-1ee4-b5837bea23c9\n# \u255f\u2500373652f0-34b0-11eb-2fea-4f14b3ee9140\n# \u2560\u2550371c6d52-34b0-11eb-12ab-a51e10fe33c5\n# \u255f\u250037013e12-34b0-11eb-3d23-9d43ca3f06a3\n# \u2560\u255078b7fa20-354c-11eb-3754-d5d515d0a2d5\n# \u2560\u255077906a42-354c-11eb-397e-9dca847ab964\n# \u2560\u255093696cf4-354d-11eb-0af3-9b27a8186fbd\n# \u2560\u2550a91c8b80-354d-11eb-03ec-8f4386a69708\n# \u2560\u255086f0f21c-354d-11eb-2a32-299183f9118b\n# \u2560\u2550666a8878-354d-11eb-22dc-e94a72ede22d\n# \u255f\u2500cfc0e592-354d-11eb-2b06-458d198c38e5\n# \u2560\u255025789968-3552-11eb-1e25-35c0d1b1c461\n# \u2560\u255056daee6e-3554-11eb-37cd-49ad4ac56805\n# \u2560\u255056bb225a-3554-11eb-0062-6d03b8ea772f\n# \u255f\u2500569a20f0-3554-11eb-0479-f1e583620682\n# \u2560\u255056790ed8-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* `\u03b4`: Deviation from the null\n* `\u03c3s`: Per-group standard deviations\n\"\"\"\nfunction hypotheses(::Type{OneSampleTTest}, n::Real, \u03b4::Real, \u03c3::Real)\n    df = n - 1\n    ncp = sqrt(n) * \u03b4 / \u03c3\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* `\u03b4`: Deviation from the null\n* `\u03c3s`: Per-group standard deviations\n\"\"\"\nfunction hypotheses(::Type{EqualVarianceTTest}, n::Real, \u03b4::Real, \u03c3::Real)\n    df = 2 * n - 2\n    ncp = sqrt(n / 2) * \u03b4 / \u03c3\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* `\u03b4`: Deviation from the null\n* `\u03c3s`: Per-group standard deviations\n\"\"\"\nfunction hypotheses(::Type{EqualVarianceTTest}, ns::Tuple, \u03b4::Real, \u03c3::Real)\n    n1, n2 = ns[1], ns[2]\n    df = n1 + n2 - 2\n    ncp = (1 / sqrt(1 / n1 + 1 / n2)) * \u03b4 / \u03c3\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 \u03b4.\n# \"\"\" ->\nthresholds(alt::NoncentralT) = -alt.\u03bb, alt.\u03bb\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\u00e1lez [^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\u00e1lez, \u00c1. (2010). Measurement of areas on a sphere using Fibonacci\nand latitude\u2013longitude lattices. Mathematical Geosciences, 42(1), 49.\n\"\"\"\nfunction fibonacci_points(n)\n    \u03d5 = (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 / \u03c0\n        lon = floatmod(i, \u03d5) * 360 / \u03d5\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": "@test collect(partitions(4)) ==  Any[[4], [3,1], [2,2], [2,1,1], [1,1,1,1]]\n@test collect(partitions(8,3)) == Any[[6,1,1], [5,2,1], [4,3,1], [4,2,2], [3,3,2]]\n@test collect(partitions(8, 1)) == Any[[8]]\n@test collect(partitions(8, 9)) == []\n@test collect(partitions([1,2,3])) == Any[Any[[1,2,3]], Any[[1,2],[3]], Any[[1,3],[2]], Any[[1],[2,3]], Any[[1],[2],[3]]]\n@test collect(partitions([1,2,3,4],3)) == Any[Any[[1,2],[3],[4]], Any[[1,3],[2],[4]], Any[[1],[2,3],[4]],\n                                              Any[[1,4],[2],[3]], Any[[1],[2,4],[3]], Any[[1],[2],[3,4]]]\n@test collect(partitions([1,2,3,4],1)) == Any[Any[[1, 2, 3, 4]]]\n@test collect(partitions([1,2,3,4],5)) == []\n\n@inferred first(partitions(4))\n@inferred first(partitions(8,3))\n@inferred first(partitions([1,2,3]))\n@inferred first(partitions([1,2,3,4],3))\n\n@test isa(collect(partitions(4)), Vector{Vector{Int}})\n@test isa(collect(partitions(8,3)), Vector{Vector{Int}})\n@test isa(collect(partitions([1,2,3])), Vector{Vector{Vector{Int}}})\n@test isa(collect(partitions([1,2,3,4], 3)), Vector{Vector{Vector{Int}}})\n\n@test length(partitions(0)) == 1\n@test length(partitions(-1)) == 0\n@test length(collect(partitions(30))) == length(partitions(30))\n@test length(collect(partitions(90,4))) == length(partitions(90,4))\n@test length(collect(partitions('a':'h'))) == length(partitions('a':'h'))\n@test length(collect(partitions('a':'h',5))) == length(partitions('a':'h',5))\n\n# integer_partitions\n@test integer_partitions(0) == []\n@test integer_partitions(5) == Any[[1, 1, 1, 1, 1], [2, 1, 1, 1], [2, 2, 1], [3, 1, 1], [3, 2], [4, 1], [5]]\n@test_throws DomainError integer_partitions(-1)\n\n@test_throws ArgumentError prevprod([2,3,5],Int128(typemax(Int))+1)\n@test prevprod([2,3,5],30) == 30\n@test prevprod([2,3,5],33) == 32\n\n# noncrossing partitions\nlet nc4 = ncpartitions(4)\n    @test nc4 == Any[Any[[1],[2],[3],[4]], Any[[1],[2],[3,4]], Any[[1],[2,3],[4]], Any[[1],[2,4],[3]], Any[[1],[2,3,4]],\n                     Any[[1,2],[3],[4]], Any[[1,2],[3,4]],\n                     Any[[1,3],[2],[4]], Any[[1,4],[2],[3]], Any[[1,4],[2,3]],\n                     Any[[1,2,3],[4]], Any[[1,3,4],[2]], Any[[1,2,4],[3]],\n                     Any[[1,2,3,4]]]\n    @test length(nc4) == catalannum(4)\nend\n", "meta": {"hexsha": "7c068c3b6471c8959d77533c5dee76ca1bf13c6e", "size": 2250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/partitions.jl", "max_stars_repo_name": "Sedictious/Combinatorics.jl", "max_stars_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 165, "max_stars_repo_stars_event_min_datetime": "2016-09-13T17:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:29:52.000Z", "max_issues_repo_path": "test/partitions.jl", "max_issues_repo_name": "Sedictious/Combinatorics.jl", "max_issues_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86, "max_issues_repo_issues_event_min_datetime": "2016-08-25T18:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T12:58:42.000Z", "max_forks_repo_path": "test/partitions.jl", "max_forks_repo_name": "Sedictious/Combinatorics.jl", "max_forks_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2016-10-29T00:18:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T10:21:39.000Z", "avg_line_length": 48.9130434783, "max_line_length": 121, "alphanum_fraction": 0.5462222222, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7798765673000045}}
{"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\u2081, r\u2082, \u03c3 = p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]\n    \n    \u03b8 = a - b/(c + x^2 + y^2)\n    \u03bc = r\u2081*sin(t) - r\u2082\n    d = Uniform(0.1, 0.4)\n    \n    dx = 1 + \u03bc*(x*cos(\u03b8) - c_yx*y*sin(\u03b8)) - min(\u03c3*rand(d)/(1-x), rand(d))\n    dy = \u03bc*(y*cos(\u03b8) + c_xy*x*sin(\u03b8)) -  min(\u03c3*rand(d)/(1-y), rand(d))\n    \n    SVector{2}(dx, dy)\nend\n\n\"\"\"\n    ikeda(; u\u2080 = rand(2), c_xy = 1.0, c_yx = 1.0, a = 0.8, b = 12, c = 0.9,\n        r\u2081 = rand(Uniform(0.01, 0.3)), r\u2082 = rand(Uniform(0.01, 0.3)), \u03c3 = 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\u2080, c_xy, c_yx, a, b, c, r\u2081, r\u2082, \u03c3)\n    p = [c_xy, c_yx, a, b, c, r\u2081, r\u2082, \u03c3]\n    DiscreteDynamicalSystem(eom_ikeda, u\u2080, p)\nend\n\nfunction ikeda(; u\u2080 = rand(2), c_xy = 1.0, c_yx = 1.0, a = 0.8, b = 12, c = 0.9,\n        r\u2081 = rand(Uniform(0.01, 0.3)), r\u2082 = rand(Uniform(0.01, 0.3)), \u03c3 = 0.05)\n    ikeda(u\u2080, c_xy, c_yx, a, b, c, r\u2081, r\u2082, \u03c3)\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": "using ExamplePackage_rosa\nusing Test, Polynomials, Random\n\n@testset \"ExamplePackage_rosa.jl\" begin\n    testfn(x)= (x-1)^3\n    testfn_prime(x)=3*(x-1)^2\n    testfn1(x)= exp(x)-1\n    testfn_prime1(x)=exp(x)\n    testfn2(x)= atan(x)\n    testfn_prime2(x)= 1/((x)^2+1)\n    \n    Random.seed!(1234)\n\n    #test for functions with derivative\n\n    root1, conv, iter  = ExamplePackage_rosa.newtonroot(testfn,testfn_prime,x_0=0.0)\n    root2, conv, iter  = ExamplePackage_rosa.newtonroot(testfn1,testfn_prime1,x_0=1.0)\n    root3, conv, iter  = ExamplePackage_rosa.newtonroot(testfn1,testfn_prime1,x_0=-0.3)\n\n    @test abs(root1-1.0)<1e-6\n    @test abs(root2 - 0.0)<1e-6\n    @test abs(root3 - 0.0)<1e-6\n\n    #do the same for functions without derivative\n\n    root1, conv, iter  = ExamplePackage_rosa.newtonroot(testfn,x_0=0.0)\n    root2, conv, iter  = ExamplePackage_rosa.newtonroot(testfn1,x_0=1.0)\n    root3, conv, iter  = ExamplePackage_rosa.newtonroot(testfn1,x_0=-.4)\n\n    @test abs(root1-1.0)<1e-6\n    @test abs(root2 - 0.0)<1e-6\n    @test abs(root3 - 0.0)<1e-6\n\n\n    #check maxiter works\n    root1, conv, iter  = ExamplePackage_rosa.newtonroot(testfn,testfn_prime,x_0=0.5,  maxiter = 3)\n    # if the function converged, return number of iteration, else return nothing \n    @test iter == nothing ||iter <= 3\n    #check for tolerance, increasing it to 1e-8\n    root1, conv, iter  = ExamplePackage_rosa.newtonroot(testfn,testfn_prime,x_0=0.5,  tol = 1e-8)\n    @test abs(root1-1.0)<1e-7\n    \n    #check lack iof convergence\n    \n    test_nc(x) = x^2+1\n\n    rootnc, conv, iter  = ExamplePackage_rosa.newtonroot(test_nc,x_0=1.0)\n    @test rootnc==nothing\n\n    #check bigfloot\n    x0 = BigFloat(0.53)\n    root1, conv, iter  = ExamplePackage_rosa.newtonroot(testfn,x_0=x0)\n    \n    @test abs(root1-1.0)<1e-6\n\n    #check for the polynomials roots\n    \n    p_1 = Polynomial([2, -5, 2])\n    p_2 = Polynomial(rand(4))\n    p_3 = convert(Polynomial,ChebyshevT(rand(4)))\n\n    root1, conv, iter  = ExamplePackage_rosa.newtonroot(p_1,x_0=1.0)\n    root2, conv, iter  = ExamplePackage_rosa.newtonroot(p_2,x_0=1.0)\n    root3, conv, iter  = ExamplePackage_rosa.newtonroot(p_3,x_0=1.0)\n\n    @test minimum(abs.(roots(p_1).-root1))<=1e-6\n    @test minimum(abs.(roots(p_2).-root2))<=1e-6\n    @test minimum(abs.(roots(p_3).-root3))<=1e-6\n\n\nend\n", "meta": {"hexsha": "2e2b22aa6a2c119e2588eb71c489246d951093b9", "size": 2310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "janrosa1/ExamplePackage_rosa.jl", "max_stars_repo_head_hexsha": "cd6ff463538b7c8f362aa320c313ae50c5cef147", "max_stars_repo_licenses": ["MIT"], "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": "janrosa1/ExamplePackage_rosa.jl", "max_issues_repo_head_hexsha": "cd6ff463538b7c8f362aa320c313ae50c5cef147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-14T00:43:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T00:43:56.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "janrosa1/ExamplePackage_rosa.jl", "max_forks_repo_head_hexsha": "cd6ff463538b7c8f362aa320c313ae50c5cef147", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 98, "alphanum_fraction": 0.670995671, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7798765631949991}}
{"text": "using FastGaussQuadrature\nusing Test, LinearAlgebra, Random, SpecialFunctions\n\n\ninclude(\"test_gausschebyshev.jl\")\ninclude(\"test_gausslegendre.jl\")\ninclude(\"test_gaussjacobi.jl\")\ninclude(\"test_gaussradau.jl\")\ninclude(\"test_gausslobatto.jl\")\ninclude(\"test_besselroots.jl\")\ninclude(\"test_gausslaguerre.jl\")\ninclude(\"test_gausshermite.jl\")\n", "meta": {"hexsha": "7ac84f768c85290c79b6e1080bb29c9d2bc395a8", "size": 336, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 25.8461538462, "max_line_length": 51, "alphanum_fraction": 0.8214285714, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7798765578506883}}
{"text": "module Interpolation\n\nexport polyint\n\n\"\"\"    polyint(xs, ys[, n])\n\nReturns a function that performs polynomial interpolation across the `xs` and\n`ys`.\n\n`n`, if given, is the order of the interpolating polynomial; if the length of\nthe `xs` and `ys` is greater than `n+1`, then multiple interpolants are\nreturned.\n\"\"\"\nfunction polyint(xs, ys)\n    n = length(xs)\n    polyint(xs, ys, n-1)\nend\n\nfunction polyint(xs::Array{T, 1}, ys::Array{T, 1}, n) where T\n    triangle = Array{T,1}[ys]\n    for i in 2:n+1\n        push!(triangle, zeros(T, length(triangle[i-1])-1))\n    end\n\n    full =  n == length(xs)-1\n\n    function interpolate(x)\n        for i in 2:n+1\n            k = length(triangle[i])\n            for j in 1:k\n                triangle[i][j] = (x-xs[j+i-1])*triangle[i-1][j]/(xs[j]-xs[j+i-1]) + (x-xs[j])*triangle[i-1][j+1]/(xs[j+i-1]-xs[j])\n            end\n        end\n\n        if full\n            triangle[end][1]\n        else\n            Tuple(triangle[end])\n        end\n    end\nend\n\nend # module\n", "meta": {"hexsha": "78e03cb73d5b7f9b32000e5c46e31c8c1d8bec12", "size": 1001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Interpolation.jl", "max_stars_repo_name": "Farr-PHY-604/Interpolation.jl", "max_stars_repo_head_hexsha": "1c3b82812a0ead2d4f1c1db7635e1c7689cbc22c", "max_stars_repo_licenses": ["MIT"], "max_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.jl", "max_issues_repo_name": "Farr-PHY-604/Interpolation.jl", "max_issues_repo_head_hexsha": "1c3b82812a0ead2d4f1c1db7635e1c7689cbc22c", "max_issues_repo_licenses": ["MIT"], "max_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.jl", "max_forks_repo_name": "Farr-PHY-604/Interpolation.jl", "max_forks_repo_head_hexsha": "1c3b82812a0ead2d4f1c1db7635e1c7689cbc22c", "max_forks_repo_licenses": ["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": 130, "alphanum_fraction": 0.5654345654, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7798765572310358}}
{"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": "include(\"Utils.jl\")\n\n\"\"\"\nFile: MMAFunctions.jl\nAuthors: Reese Pathak, Stephen Boyd\n\nThis file defines a set of scalar-valued functions that take one or two vectors\nas input and output a scalar as output. We support average, standard deviation,\nroot mean square, angle, distance, and correlation coefficient.\n\"\"\"\n\nmodule Functions\n  using Utils\nexport avg, std, rms, angle, corrcoef, dist\n\n\n# FUNCTION DEFINITIONS.\n\n# Average\n@mma_function avg(x) = mean(x)\n\n# RMS value\n@mma_function rms(x) = norm(x)/sqrt(length(x))\n\n# Distance\n@mma_function dist(x, y) = norm(x - y)\n\n# Standard deviation\n@mma_function std(x) = norm(demean(x))/sqrt(length(x))\n\n# Angle\n@mma_function angle(x, y) = acos(dot(x,y)/(norm(x)*norm(y)))\n\n# Correlation coefficient\n@mma_function corrcoef(x, y) = dot(demean(x), demean(y))/norm(demean(x))*norm(demean(y))\n\nend\n", "meta": {"hexsha": "9cad7fac0c387dc3b675a0c4c2ca4ab3724dfc3b", "size": 835, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Functions.jl", "max_stars_repo_name": "reesepathak/mma-functions", "max_stars_repo_head_hexsha": "724e65608faf9da5038606555f4ae964c8ecd997", "max_stars_repo_licenses": ["MIT"], "max_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": "reesepathak/mma-functions", "max_issues_repo_head_hexsha": "724e65608faf9da5038606555f4ae964c8ecd997", "max_issues_repo_licenses": ["MIT"], "max_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": "reesepathak/mma-functions", "max_forks_repo_head_hexsha": "724e65608faf9da5038606555f4ae964c8ecd997", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T11:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T11:04:54.000Z", "avg_line_length": 21.9736842105, "max_line_length": 88, "alphanum_fraction": 0.7209580838, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7798660729991401}}
{"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    \u2207::T2\n    inner::T3\nend\n\n# Default costructor.\nBregman(F, \u2207) =  Bregman(F, \u2207, 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.\u2207(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, \u2207, x, y; inner = LinearAlgebra.dot) = Bregman(F, \u2207, 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": "#=\nGiven an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.\n\nFor example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].\n\nFollow-up: what if you can't use division?\n=#\n\nusing Test\ninclude(\"Solutions/problem2_product_except_i.jl\")\n@test product_excepti([1, 2, 3, 4, 5]) == [120, 60, 40, 30, 24]\n@test product_excepti([3, 2, 1]) == [2, 3, 6]\n", "meta": {"hexsha": "bd12d2b6fe3fecd81218450f7f7229d8d99a2685", "size": 565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tests/problem2_product_except_i_test.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": "Tests/problem2_product_except_i_test.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": "Tests/problem2_product_except_i_test.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": 43.4615384615, "max_line_length": 174, "alphanum_fraction": 0.6849557522, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8887587839164801, "lm_q1q2_score": 0.7798652025573004}}
{"text": "###Target functions\nfunction sincos!(r::Matrix,paras::Vector,t::AbstractVector)\n    p1 = 2pi*paras[1]\n    p2 = 2pi*paras[2]\n    @simd for i=1:length(t)\n        @inbounds r[i,1] = sin(p1*t[i])\n    end\n    @simd for i=1:length(t)\n        @inbounds r[i,2] = cos(p2*t[i])\n    end\n    r\nend\n\nsincos(paras::Vector,t::AbstractVector) = sincos!(zeros(eltype(t),length(t),2),paras,t)\n\n@inline function _commonsincoscomponents(t::AbstractVector,measurementparas::Vector,variance::Vector,paraminit...)\n    modelparameters = parameters([:a,:b],paraminit...)\n    noisemodel = noise(:gaussian,variance)\n    measurementdata = data(:array,t,applynoise!(noisemodel,sincos(measurementparas,t)))\n    modelparameters,measurementdata,noisemodel\nend\n\n###Create a target function model\nfunction sincosmodel(t::AbstractVector,measurementparas::Vector,variance::Vector,paraminit...)\n    model(:target,_commonsincoscomponents(t,measurementparas,variance,paraminit...)...,sincos,t;name=\"Sine-Cosine Model\")\nend\n\n###Create a target function model\nfunction sincosmodel!(t::AbstractVector,measurementparas::Vector,variance::Vector,paraminit...)\n    model(:target!,_commonsincoscomponents(t,measurementparas,variance,paraminit...)...,sincos!,t;name=\"Sine-Cosine In-Place Model\")\nend\n", "meta": {"hexsha": "c74a68b4545631adba45c17f4421180fbb035e0e", "size": 1252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "target/sincos/models/model.jl", "max_stars_repo_name": "QuantifyingUncertainty/GMH-Examples.jl", "max_stars_repo_head_hexsha": "5a037daefacfd9f873c7293d064c4dbaa7b58a93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-08T19:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-08T19:20:21.000Z", "max_issues_repo_path": "target/sincos/models/model.jl", "max_issues_repo_name": "QuantifyingUncertainty/GMH-Examples.jl", "max_issues_repo_head_hexsha": "5a037daefacfd9f873c7293d064c4dbaa7b58a93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "target/sincos/models/model.jl", "max_forks_repo_name": "QuantifyingUncertainty/GMH-Examples.jl", "max_forks_repo_head_hexsha": "5a037daefacfd9f873c7293d064c4dbaa7b58a93", "max_forks_repo_licenses": ["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.125, "max_line_length": 132, "alphanum_fraction": 0.7284345048, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7798571363837983}}
{"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\u03bd, n\u03bd)` where `n\u03bd` 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] \u2260 size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] \u2260 length(a) || size(cij)[1] \u2260 length(b)\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector do not match\"))\n    elseif a \u2248 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\u2113, a, b[, \u2113id=3])\n\nThis function returns weights (a `n\u03bd`-by-`n\u2113` matrix) of the constrained ILC (CILC) method.\n\nHere, `n\u03bd` is the number of frequency channels and `n\u2113` 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\u2113::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(n\u2113, n\u03bd, n\u03bd)`, `(n\u03bd, n\u2113, n\u03bd)` or `(n\u03bd, n\u03bd, n\u2113)` (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- `\u2113id::Integer=3`: location of the index for the `n\u2113` domain. `\u2113id=1` if `cij\u2113[n\u2113,n\u03bd,n\u03bd]`, `\u2113id=2` if `cij\u2113[n\u03bd,n\u2113,n\u03bd]`, and `\u2113id=3` (the default value) if `cij\u2113[n\u03bd,n\u03bd,n\u2113]`.\n\"\"\"\nfunction cilc_weights(\n    cij\u2113::Array{T,3},\n    a::Array{T,1},\n    b::Array{T,1},\n    \u2113id::Integer = 3,\n) where {T<:AbstractFloat}\n    if \u2113id > 3 || \u2113id < 1\n        throw(DomainError(\u2113id, \"\u2113id must be 1, 2, or 3\"))\n    end\n    if (\u2113id == 3 && size(cij\u2113)[1] \u2260 size(cij\u2113)[2]) ||\n       (\u2113id == 2 && size(cij\u2113)[1] \u2260 size(cij\u2113)[3]) ||\n       (\u2113id == 1 && size(cij\u2113)[2] \u2260 size(cij\u2113)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    n\u2113 = size(cij\u2113)[\u2113id]\n    n\u03bd = ifelse(\u2113id == 3, size(cij\u2113)[1], size(cij\u2113)[3])\n    if length(a) \u2260 n\u03bd || length(b) \u2260 n\u03bd\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector do not match\"))\n    elseif a \u2248 b\n        throw(ErrorException(\"vectors of the frequency response are too similar\"))\n    else\n    end\n    w\u2113 = zeros(n\u03bd, n\u2113) # ILC weights\n    for i\u2113 = 1:n\u2113\n        if \u2113id == 3\n            M = Symmetric(cij\u2113[:, :, i\u2113])\n        elseif \u2113id == 2\n            M = Symmetric(cij\u2113[:, i\u2113, :])\n        else\n            M = Symmetric(cij\u2113[i\u2113, :, :])\n        end\n        x = M \\ a # R^-1 a\n        y = M \\ b # R^-1 b\n        w\u2113[:, i\u2113] = (b'y * x - a'y * y) / (a'x * b'y - (a'y)^2)\n    end\n    return w\u2113\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": "mutable struct Tikhonov{T} <: AbstractRegularization{T}\n    \u03b1::T\nend\nTikhonov() =  Tikhonov\n\nget_regularization_matrix(regop::Tikhonov{T},N,ds) where {T} =   Matrix(I(N))\n\nmutable struct SecondDerivative{T} <: AbstractRegularization{T}\n    \u03b1::T\nend\nSecondDerivative()=SecondDerivative\n\nfunction get_regularization_matrix(regop::SecondDerivative{T},N,ds) where {T}\n    \u03b1=regop.\u03b1\n    L=zeros( N+2,N)\n    for j in 3:N\n        L[j,j]= 1/(ds[j]*(ds[j]+ds[j-1]))#\n        L[j,j-1]= -2*1/(ds[j-1]*(ds[j]))#\n        L[j,j-2]= 1/(ds[j-1]*(ds[j]+ds[j-1]))#\n    end\n\n    # if regop.lower_bc\n         L[1,1]=1/ds[1]\n         L[2,1]=-2*1/(ds[1]*(ds[2]))\n         L[2,2]=1/ds[2]*(ds[1]+ds[2])\n    # end\n    # if regop.upper_bc\n         L[N+1,N-1]=1/ds[N-1]*(ds[N]+ds[N-1])\n         L[N+1,N]=-2*1/((ds[N]*ds[N-1]))\n         L[N+2,N]=1/ds[N]\n    # end\n    return L\n    #L[:,end] .=0  #Do not regularize on the y offset   \nend", "meta": {"hexsha": "5e3606ece092a578c15c727ada0b9f07fe078bc7", "size": 909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regularizations.jl", "max_stars_repo_name": "MatFi/Fredholm.jl", "max_stars_repo_head_hexsha": "1791c0c8ac27db553a79984c9bcbd0f8de1345f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-21T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T09:47:33.000Z", "max_issues_repo_path": "src/regularizations.jl", "max_issues_repo_name": "MatFi/Fredholm.jl", "max_issues_repo_head_hexsha": "1791c0c8ac27db553a79984c9bcbd0f8de1345f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-26T20:04:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-29T20:08:52.000Z", "max_forks_repo_path": "src/regularizations.jl", "max_forks_repo_name": "MatFi/Fredholm.jl", "max_forks_repo_head_hexsha": "1791c0c8ac27db553a79984c9bcbd0f8de1345f3", "max_forks_repo_licenses": ["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.7352941176, "max_line_length": 77, "alphanum_fraction": 0.5423542354, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7798571243039276}}
{"text": "function nlp_cvx_106_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - cos and sin expressions\n    # - convex constraint, only in given domains\n    # Variants\n    #   010 - intersection point\n    #   011 - intersection point\n\n    model = Model(optimizer)\n\n    @variable(model, -3 <= x <= 3)\n    @variable(model, -1 <= y <= 1)\n\n    @objective(model, Min, -x - y)\n    @NLconstraint(model, sin(-x - 1.0) + x / 2 + 0.5 <= y)\n    @NLconstraint(model, cos(x - 0.5) + x / 4 - 0.5 >= y)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -1.8572155128552428, tol = objective_tol)\n    return check_solution(\n        [x, y],\n        [1.369771397576555, 0.4874441152786876],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "129cf741ac787c4fa4d2116a765dcc9366b5391f", "size": 915, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/106_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/106_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/106_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 26.1428571429, "max_line_length": 76, "alphanum_fraction": 0.6284153005, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7798351633142594}}
{"text": "# Matern 1/2 isotropic covariance Function\n\n\"\"\"\n    Mat12Iso <: MaternISO\n\nIsotropic Matern 1/2 kernel (covariance)\n```math\nk(x,x') = \u03c3^2 \\\\exp(-|x-y|/\u2113)\n```\nwith length scale ``\u2113`` and signal standard deviation ``\u03c3``.\n\"\"\"\nmutable struct Mat12Iso{T} <: MaternIso where {T<:Real}\n    \"Length scale\"\n    \u2113::T\n    \"Signal variance\"\n    \u03c32::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nMatern 1/2 isotropic covariance Function\n\n    Mat12Iso(ll::T, l\u03c3::T)\n\n# Arguments\n  - `ll::Real`: length scale (given on log scale)\n  - `l\u03c3::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat12Iso(ll::T, l\u03c3::T) where T = Mat12Iso{T}(exp(ll), exp(2 * l\u03c3), [])\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.\u2113, mat.\u03c32 = exp(hyp[1]), exp(2 * hyp[2])\nend\n\nget_params(mat::Mat12Iso{T}) where T = T[log(mat.\u2113), log(mat.\u03c32) / 2]\nget_param_names(mat::Mat12Iso) = [:ll, :l\u03c3]\nnum_params(mat::Mat12Iso) = 2\n\ncov(mat::Mat12Iso, r::Number) = mat.\u03c32 * exp(-r / mat.\u2113)\n\n@inline dk_dll(mat::Mat12Iso, r::Real) = r / mat.\u2113 * 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": "using YaoBase\n\nexport ShiftGate, shift\n\n\"\"\"\n    ShiftGate <: PrimitiveBlock\n\nPhase shift gate.\n\n# Definition\n\n```math\n\\\\begin{pmatrix}\n1 & 0\n0 & e^(im \u03b8)\n\\\\end{pmatrix}\n```\n\"\"\"\nmutable struct ShiftGate{T <: Real} <: PrimitiveBlock{1}\n    theta::T\nend\n\n\"\"\"\n    shift(\u03b8)\n\nCreate a [`ShiftGate`](@ref) with phase `\u03b8`.\n\n# Example\n\n```jldoctest\njulia> shift(0.1)\nshift(0.1)\n```\n\"\"\"\nshift(\u03b8::AbstractFloat) = ShiftGate(\u03b8)\nshift(\u03b8::Real) = shift(Float64(\u03b8))\nmat(::Type{T}, gate::ShiftGate) where {T <: Complex} = Diagonal(T[1.0, exp(im * gate.theta)])\n\ncache_key(gate::ShiftGate) = gate.theta\n\n# parametric interface\nniparams(::Type{<:ShiftGate}) = 1\ngetiparams(x::ShiftGate) = x.theta\nsetiparams!(r::ShiftGate, param::Real) = (r.theta = param; r)\n\n\nBase.adjoint(blk::ShiftGate) = ShiftGate(-blk.theta)\nBase.copy(block::ShiftGate{T}) where T = ShiftGate{T}(block.theta)\nBase.:(==)(lhs::ShiftGate, rhs::ShiftGate) = lhs.theta == rhs.theta\nYaoBase.isunitary(r::ShiftGate) = true\n", "meta": {"hexsha": "bbc44c6c76bdfcb1fe5fd8d55c66c44761a4cea5", "size": 970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/primitive/shift_gate.jl", "max_stars_repo_name": "wsmoses/YaoBlocks.jl", "max_stars_repo_head_hexsha": "a28de84ca2e89c3df3fca9fd3340e882f35aca0e", "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/primitive/shift_gate.jl", "max_issues_repo_name": "wsmoses/YaoBlocks.jl", "max_issues_repo_head_hexsha": "a28de84ca2e89c3df3fca9fd3340e882f35aca0e", "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/primitive/shift_gate.jl", "max_forks_repo_name": "wsmoses/YaoBlocks.jl", "max_forks_repo_head_hexsha": "a28de84ca2e89c3df3fca9fd3340e882f35aca0e", "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.0196078431, "max_line_length": 93, "alphanum_fraction": 0.6659793814, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7798341987393466}}
{"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 \u21a6 0 if ||x|| = r, +\u221e 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.\u03bc[1]\nconfidence_array[1] = 2*sqrt(initial_guess.\u03a3.diag[1])\nfor i in x_data\n    current_state = filtered_state.state[i]\n    state_array[i+1] = current_state.\u03bc[1]\n    confidence_array[i+1] = 2*sqrt(current_state.\u03a3.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.\u03bc[1]\n    confidence_array[i] = 2*sqrt(current_state.\u03a3.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 \u00d7 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 \u03a3 V^*``, with ``\u03a3 = \\\\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(\u03b8::Real)\n\nUnnormalized version of `sinc` function, i.e. $\\operatorname{usinc}(\u03b8) = \\frac{\\sin(\u03b8)}{\u03b8}$.\nThis is equivalent to `sinc(\u03b8/\u03c0)`.\n\"\"\"\n@inline usinc(\u03b8::Real) = \u03b8 == 0 ? one(\u03b8) : isinf(\u03b8) ? zero(\u03b8) : sin(\u03b8) / \u03b8\n\n@doc raw\"\"\"\n    usinc_from_cos(x::Real)\n\nUnnormalized version of `sinc` function, i.e. $\\operatorname{usinc}(\u03b8) = \\frac{\\sin(\u03b8)}{\u03b8}$,\ncomputed from $x = cos(\u03b8)$.\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(\u2264(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(\u2264(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) \u2264 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\ud835\udd3d}, \ud835\udd3d::AbstractNumbers) -> Y::AbstractMatrix{<:Real}\n\nGiven a matrix $X \u2208 \ud835\udd3d^{n \u00d7 n}$, compute $Y \u2208 \u211d^{m \u00d7 m}$, where $m = n \\operatorname{dim}_\ud835\udd3d$,\nand $\\operatorname{dim}_\ud835\udd3d$ is the [`real_dimension`](@ref) of the number field $\ud835\udd3d$, using\nthe map $\u03d5 \\colon X \u21a6 Y$, that preserves the matrix product, so that for all\n$C,D \u2208 \ud835\udd3d^{n \u00d7 n}$,\n````math\n\u03d5(C) \u03d5(D) = \u03d5(CD).\n````\nSee [`realify!`](@ref) for an in-place version, and [`unrealify!`](@ref) to compute the\ninverse of $\u03d5$.\n\"\"\"\nfunction realify(X, \ud835\udd3d)\n    n = LinearAlgebra.checksquare(X)\n    n\u211d = real_dimension(\ud835\udd3d) * n\n    Y = allocate(X, real(eltype(X)), n\u211d, n\u211d)\n    return realify!(Y, X, \ud835\udd3d, n)\nend\nrealify(X, ::typeof(\u211d)) = X\n\n\"\"\"\n    realify!(Y::AbstractMatrix{<:Real}, X::AbstractMatrix{T\ud835\udd3d}, \ud835\udd3d::AbstractNumbers)\n\nIn-place version of [`realify`](@ref).\n\"\"\"\nrealify!(Y, X, \ud835\udd3d)\n\n@doc raw\"\"\"\n    realify!(Y::AbstractMatrix{<:Real}, X::AbstractMatrix{<:Complex}, ::typeof(\u2102))\n\nGiven a complex matrix $X = A + iB \u2208 \u2102^{n \u00d7 n}$, compute its realified matrix\n$Y \u2208 \u211d^{2n \u00d7 2n}$, written\nwhere\n````math\nY = \\begin{pmatrix}A & -B \\\\ B & A \\end{pmatrix}.\n````\n\"\"\"\nfunction realify!(Y, X, ::typeof(\u2102), 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\ud835\udd3d}, Y::AbstractMatrix{<:Real}, \ud835\udd3d::AbstractNumbers[, n])\n\nGiven a real matrix $Y \u2208 \u211d^{m \u00d7 m}$, where $m = n \\operatorname{dim}_\ud835\udd3d$, and\n$\\operatorname{dim}_\ud835\udd3d$ is the [`real_dimension`](@ref) of the number field $\ud835\udd3d$, compute\nin-place its equivalent matrix $X \u2208 \ud835\udd3d^{n \u00d7 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, \ud835\udd3d)\n\nfunction unrealify!(X, Y, ::typeof(\u2102), 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(\u211d), 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# \u2554\u2550\u2561 7c860884-5afd-4b4a-b358-4f2bce8bd395\nusing Pkg; Pkg.activate(\"../..\")\n\n# \u2554\u2550\u2561 38c4e220-d708-11ec-3968-fbbd41c26155\nusing PlutoUI, Plots, DifferentialEquations, NonLinearDynamicsCourse\n\n# \u2554\u2550\u2561 2ac364c2-cbdd-49b4-9f26-9fe89382be5e\nTableOfContents(title=\"\ud83d\udcda Table of Contents\", indent=true, depth=4, aside=true)\n\n# \u2554\u2550\u2561 6b6a5e19-5298-4969-b1c9-699aa1cb2996\nhtml\"\"\"\n<style>\ninput[type*=\"range\"] {\n\twidth: 50%;\n}\n</style>\n\"\"\"\n\n# \u2554\u2550\u2561 62cba86d-4406-4d16-8715-b29bee7d3178\nmd\"\"\"\n# Logistic Equation\n\n$\\dot{x}=Rx\\left(1-\\frac{x}{K}\\right)$\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4dc32b5a-5794-4d2d-844e-cdb80bec2e7b\nlogistic(x,p,t)=p[1]*x*(1.0-x/p[2])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 16a156b5-92ab-4e1c-ab70-c3b348186c57\nflux1D(logistic,pars2[3],100.0,pars2;xlims=[-0.1,2.0],title=\"Logistic\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 29474ca0-839b-45de-a7bf-7d91c5ea59aa\nlogharvest1(x,p,t)=p[1]*x*(1.0-x/p[2])-p[3]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b13d261e-1c1b-41b0-ae86-e20cd2304727\nmd\"\"\"\n## Critical Slowing Down\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c803ed90-958c-4d0e-84d5-3e8cc9c8fbfe\nmd\"\"\"\n# Consumer Equation\n\n$\\dot{x} = Rx\\left(1-\\frac{x}{K}\\right) - Px$ \n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5018d342-0a51-4275-8c0f-1b5d253c2ec0\nflux1D(consumer,pars_consumer[4],300.0,pars_consumer,xlims=[0.0,2.0],title=\"Consumer Equation\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25007c860884-5afd-4b4a-b358-4f2bce8bd395\n# \u2560\u255038c4e220-d708-11ec-3968-fbbd41c26155\n# \u255f\u25002ac364c2-cbdd-49b4-9f26-9fe89382be5e\n# \u255f\u25006b6a5e19-5298-4969-b1c9-699aa1cb2996\n# \u255f\u250062cba86d-4406-4d16-8715-b29bee7d3178\n# \u255f\u25006d64cc27-1059-4dd7-8f17-1c6fd9a2eca0\n# \u2560\u25504dc32b5a-5794-4d2d-844e-cdb80bec2e7b\n# \u255f\u250016a156b5-92ab-4e1c-ab70-c3b348186c57\n# \u255f\u250077766c99-4142-4acb-a855-ab133e67aa66\n# \u255f\u2500ce4da9bf-316b-45d2-8504-f2a63cdda247\n# \u2560\u255029474ca0-839b-45de-a7bf-7d91c5ea59aa\n# \u255f\u2500794936ae-d9ae-4319-994f-4282c99c4238\n# \u255f\u25008fc407f4-a242-4cdc-b7e0-062c8f5782d1\n# \u255f\u2500b13d261e-1c1b-41b0-ae86-e20cd2304727\n# \u255f\u2500f1f04dd4-0447-4e48-9bab-f34058a6a0f1\n# \u255f\u2500c3757398-060c-412c-997b-58331b2dee04\n# \u255f\u2500c803ed90-958c-4d0e-84d5-3e8cc9c8fbfe\n# \u2560\u2550b4ea8364-a582-443c-bdb1-46e75a5c4d4e\n# \u255f\u25005018d342-0a51-4275-8c0f-1b5d253c2ec0\n# \u255f\u25005afa3aff-af15-429b-a0fb-9a0dfcad740d\n# \u255f\u250084a596c1-3a0a-4edd-a7ea-f3fcd8839c2a\n# \u255f\u250091b2718a-a921-4bae-99c0-91ec9c7e6479\n# \u2560\u25505a0b156e-b0b2-43b8-b15e-bcdb65c154bf\n# \u255f\u2500a3270d8b-f167-4fb9-bcc5-c62c91b39649\n# \u255f\u25006528501f-3bb2-48a7-b24e-d32400033538\n# \u255f\u25000d0d6d2f-56b2-4e01-b9a4-6e469eac90ad\n# \u255f\u250076cfd5c8-6298-4ae2-9d2d-9e60deb12f49\n# \u255f\u25000bf40552-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) \u2248 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\u03c0)%(2\u03c0)]\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\u03c0)\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\u03c0)\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, \u03b81::Real, \u03b82::Real) =\nArc(c0, r*(cos(\u03b81)+sin(\u03b81)*im), r*(cos(\u03b82)+sin(\u03b82)*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, [\u03b80, \u03b81; 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- `\u03b80::Real`: Initial angle.\n- `\u03b81::Real`: Final angle.\n- `numpts::Integer`: Number of points to create.\n\"\"\"\ncirclepoints(c::AbstractCircle, \u03b80::Real=0, \u03b81::Real=2\u03c0; numpts::Integer=100) =\n[ (centerx(c) + radius(c)*cos(\u03b8), centery(c) + radius(c)*sin(\u03b8)) for \u03b8 \u2208 \u03b80:((\u03b81 - \u03b80)/numpts):\u03b81 ]\n\ncirclepoints(x::Real, y::Real, r::Real, \u03b80::Real=0, \u03b81::Real=2\u03c0; numpts::Integer=100) =\n[ (x + r*cos(\u03b8), y + r*sin(\u03b8)) for \u03b8 \u2208 \u03b80:((\u03b81 - \u03b80)/numpts):\u03b81 ]\n\n\"\"\"\n    circlepoints(c, [\u03b80, \u03b81; numpts]) -> Array{Complex{Float64}}\n\nCreate an array of complex number in a given circle.\n\n#### Arguments\n- `c::Circle`: A circle.\n- `\u03b80::Real`: Initial angle.\n- `\u03b81::Real`: Final angle.\n- `numpts::Integer`: Number of points to create.\n\"\"\"\ncirclecomplexes(c::AbstractCircle, \u03b80::Real=0, \u03b81::Real=2\u03c0; numpts::Integer=100) =\n[ centerC(c) + radius(c)*exp(\u03b8*im) for \u03b8 \u2208 \u03b80:((\u03b81 - \u03b80)/numpts):\u03b81 ]\n\ncirclecomplexes(z::Number, r::Real, \u03b80::Real=0, \u03b81::Real=2\u03c0; numpts::Integer=100) =\n[ z + r*cos(\u03b8) + r*sin(\u03b8)*im for \u03b8 \u2208 \u03b80:((\u03b81 - \u03b80)/numpts):\u03b81 ]\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": "export Ricker\n\"\"\"\n    Ricker(epp::Union{ElasticPropagatorParams, AcousticPropagatorParams}, \n    a::Union{PyObject, <:Real}, \n    shift::Union{PyObject, <:Real}, \n    amp::Union{PyObject, <:Real}=1.0)\n\nReturns a Ricker wavelet (a tensor). \n- `epp`: a `ElasticPropagatorParams` or an `AcousticPropagatorParams`\n- `a`: Width parameter\n- `shift`: Center of the Ricker wavelet\n- `amp`: Amplitude of the Ricker wavelet\n\n```math\nf(x) = \\\\mathrm{amp}A (1 - x^2/a^2) exp(-x^2/2 a^2)\n```\nwhere \n```math\nA = 2/sqrt(3a)pi^1/4\n```\n\"\"\"\nfunction Ricker(epp, \n        a, \n        shift, \n        amp=1.0)\n    NT, T = epp.NSTEP, epp.NSTEP*epp.DELTAT\n    A = @. 2 / (sqrt(3 * a) * (pi^0.25))\n    wsq = @. a^2\n    vec =  collect(1:NT) .-shift\n    xsq = @. vec^2\n    mod = @. (1 - xsq / wsq)\n    gauss = @. exp(-xsq / (2 * wsq))\n    total = @. amp * A * mod * gauss\n    return total\nend\n\nstruct SafeIndex{T}\n    arg::T\nend\n\nfunction SafeIndex(args::Tuple)\n    SafeIndex(CartesianIndex(args))\nend\nSafeIndex(args::Int...) = SafeIndex(args)\n\nfunction Base.getindex(x::AbstractArray, si::SafeIndex)\n    getindex(x, si.arg)\nend\n\nfunction Base.setindex!(x::AbstractArray, val, si::SafeIndex)\n    setindex!(x, val, si.arg)\nend\n\n", "meta": {"hexsha": "3fd501bc2e91fd789b4f5a47a334e935d4767473", "size": 1202, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "JuliaReverse/ReversibleSeismic.jl", "max_stars_repo_head_hexsha": "1cc2d722f48054ba7cb9629a6d7a728fbfd5af0b", "max_stars_repo_licenses": ["MIT"], "max_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": "JuliaReverse/ReversibleSeismic.jl", "max_issues_repo_head_hexsha": "1cc2d722f48054ba7cb9629a6d7a728fbfd5af0b", "max_issues_repo_licenses": ["MIT"], "max_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": "JuliaReverse/ReversibleSeismic.jl", "max_forks_repo_head_hexsha": "1cc2d722f48054ba7cb9629a6d7a728fbfd5af0b", "max_forks_repo_licenses": ["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.2592592593, "max_line_length": 74, "alphanum_fraction": 0.6114808652, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7797862461201116}}
{"text": "\nA = rand(4,3)   # simulate a matrix with elements selected at random from (0,1)\n\n\nB = rand(3, 4)\n\n\nA'   # \"lazy\" transpose\n\n\nA*B\n\n\nusing LinearAlgebra, RCall, StatsModels, Tables\n\n\nFormaldehyde = rcopy(R\"Formaldehyde\")\n\n\nR\"\"\"\nlibrary(ggplot2)\nqplot(x=carb, y=optden, data=Formaldehyde, geom=\"point\")\n\"\"\"\n\n\nX = hcat(ones(size(Formaldehyde, 1)), Formaldehyde.carb)\n\n\ny = Formaldehyde.optden\n\n\n\u03b2 = X\\y     # least squares estimate\n\n\nr = y - X*\u03b2   #residual\n\n\nX'r   # not exactly zero but very small entries\n\n\nusing GLM\n\n\nm1 = fit(LinearModel, @formula(optden ~ 1 + carb), Formaldehyde)\n\n\nf1 = @formula(optden ~ 1 + carb)\ny, X = modelcols(apply_schema(f1, schema(Formaldehyde)), Formaldehyde)\n\n\nX\n\n\nX\n\n\nxpx = X'X\n\n\nch = cholesky(xpx)\n\n\nch.U'ch.U\n\n\nch.U'ch.U \u2248 xpx\n\n\nv = ldiv!(ch.U', X'y)\n\n\n\u03b2c = ldiv!(ch.U, copy(v))     # solution from the Cholesky factorization\n\n\n\u03b2c \u2248 \u03b2\n\n\nldiv!(ch, X'y)\n\n\nXy = hcat(X, y)              # augmented model matrix\n\n\ncha = cholesky(Xy'Xy)        # augmented Cholesky factor\n\n\nRXX = UpperTriangular(view(cha.U, 1:2, 1:2))\n\n\nRXX \u2248 ch.U\n\n\nrXy = cha.U[1:2, end]     # creates a copy (\"view\" doesn't copy)\n\n\nrXy \u2248 v\n\n\n\u03b2ac = ldiv!(RXX, copy(rXy))     # least squares solution from the augmented Cholesky\n\n\n\u03b2ac \u2248 \u03b2\n\n\nabs2(cha.U[end,end]) \u2248 sum(abs2, y - X*\u03b2)   # check on residual sum of squares\n\n\nFormrows = Tables.rowtable(Formaldehyde)\n\n\nchr = cholesky(zeros(3, 3) + I)  # initialize\n\n\nfill!(chr.factors, 0);   # zero out the contents\nchr\n\n\nfill!(chr.factors, 0)\nfor r in Formrows\n    lowrankupdate!(chr, [1.0, r.carb, r.optden])\nend\nchr\n\n\nqrX = qr(X)\n\n\nqrX.R'qrX.R\n\n\nqrX.R'qrX.R \u2248 xpx\n\n", "meta": {"hexsha": "54590548495ee9bb612ef305c5bbab024f7775e0", "size": 1610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/linearalgebra/leastsquares.jl", "max_stars_repo_name": "dmbates/MixedModelsTutorials.jl", "max_stars_repo_head_hexsha": "7e8c91755504fd1221f5d4f8b401a63ded1560a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-19T16:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T09:52:33.000Z", "max_issues_repo_path": "script/linearalgebra/leastsquares.jl", "max_issues_repo_name": "RePsychLing/MixedModelsTutorials.jl", "max_issues_repo_head_hexsha": "7e8c91755504fd1221f5d4f8b401a63ded1560a4", "max_issues_repo_licenses": ["MIT"], "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/linearalgebra/leastsquares.jl", "max_forks_repo_name": "RePsychLing/MixedModelsTutorials.jl", "max_forks_repo_head_hexsha": "7e8c91755504fd1221f5d4f8b401a63ded1560a4", "max_forks_repo_licenses": ["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.1052631579, "max_line_length": 84, "alphanum_fraction": 0.6341614907, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7797862441568879}}
{"text": "module mbaruniax1\nusing FinEtools\nusing FinEtoolsDeforLinear\nusing FinEtools.FENodeSetModule\nusing FinEtools.MeshExportModule\nusing FinEtoolsDeforLinear.MatDeforLinearElasticModule: tangentmoduli!, update!, thermalstrain!\nusing Test\nimport LinearAlgebra: norm, cholesky, cross\nfunction test()\n    E = 30e6*phun(\"psi\") # Young's modulus\n    alpha = 5.5e-6*phun(\"in\")/phun(\"in\")/phun(\"F\")\n    for nu in [0.0 0.3 0.45]\n\n        MR = DeforModelRed1DStress\n        material = MatDeforElastIso(MR,  0.0, E, nu, alpha)\n        D = fill(0.0, 1, 1)\n        t::FFlt, dt::FFlt, loc::FFltMat, label::FInt = 0.0, 0.0, [0.0 0.0 0.0], 0\n        tangentmoduli!(material,  D,  t, dt, loc, label)\n        @test D[1, 1] \u2248 E\n    end\n    \n    true\nend\nend\nusing .mbaruniax1\nmbaruniax1.test()\n\nmodule mbaruniax2\nusing FinEtools\nusing FinEtoolsDeforLinear\nusing FinEtools.FENodeSetModule\nusing FinEtools.MeshExportModule\nusing FinEtoolsDeforLinear.MatDeforLinearElasticModule: tangentmoduli!, update!, thermalstrain!\nusing Test\nimport LinearAlgebra: norm, cholesky, cross\nfunction test()\n    E = 30e6*phun(\"psi\") # Young's modulus\n    alpha = 5.5e-6*phun(\"in\")/phun(\"in\")/phun(\"F\")\n    for nu in [0.0 0.3 0.45]\n\n        MR = DeforModelRed1DStrain\n        material = MatDeforElastIso(MR,  0.0, E, nu, alpha)\n        D = fill(0.0, 1, 1)\n        t::FFlt, dt::FFlt, loc::FFltMat, label::FInt = 0.0, 0.0, [0.0 0.0 0.0], 0\n        tangentmoduli!(material,  D,  t, dt, loc, label)\n        lambda = E * nu / (1 + nu) / (1 - 2*(nu));\n        mu = E / 2. / (1+nu);\n        @test D[1, 1] \u2248 lambda + 2*mu\n    end\n    \n    true\nend\nend\nusing .mbaruniax2\nmbaruniax2.test()\n", "meta": {"hexsha": "a70ce406e016130273ed98444c761c6ae36088d9", "size": 1636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_linear_defor_10.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": "test/test_linear_defor_10.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": "test/test_linear_defor_10.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": 29.2142857143, "max_line_length": 95, "alphanum_fraction": 0.6448655257, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7797862341314905}}
{"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  \u03b1 = [35//384;0;500//1113;125//192;-2187//6784;11//84;0]\n  \u03b1EEst = [5179//57600;0;7571//16695;393//640;-92097//339200;187//2100;1//40]\n  A = map(T,A)\n  \u03b1 = map(T,\u03b1)\n  \u03b1EEst = map(T,\u03b1EEst)\n  c = map(T,c)\n  return(ExplicitRKTableau(A,c,\u03b1,5,\u03b1EEst=\u03b1EEst,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": "include(\"utils.jl\")\n\n@testset \"SkewSymmetricMatrices\" begin\n    M = SkewSymmetricMatrices(3, \u211d)\n    A = [1 2 3; 4 5 6; 7 8 9]\n    A_skewsym = [0 -2 -3; 2 0 1; 3 -1 0]\n    A_skewsym2 = [0 -2 -3; 2 0 1; 3 -1 0]\n    B_skewsym = [0 -2 -3; 2 0 -1; 3 1 0]\n    M_complex = SkewSymmetricMatrices(3, \u2102)\n    A_skewsym_complex = [1.0im -2.0 -3.0; 2.0 0.0 1.0; 3.0 -1.0 0.0]\n    B_skewsym_complex = [2.0im -2.0 - 2.0im -3.0; 2.0 - 2.0im 0.0 -1.0; 3.0 1.0 0.0]\n    @test repr(M_complex) == \"SkewSymmetricMatrices(3, \u2102)\"\n    C = [0 -1 im; 1 0 -im; im -im 0]\n    D = [1 0; 0 1]\n    X = zeros(3, 3)\n    @testset \"Real Skew-Symmetric Matrices Basics\" begin\n        @test repr(M) == \"SkewSymmetricMatrices(3, \u211d)\"\n        @test representation_size(M) == (3, 3)\n        @test base_manifold(M) === M\n        @test typeof(get_embedding(M)) === Euclidean{Tuple{3,3},\u211d}\n        @test check_manifold_point(M, B_skewsym) === nothing\n        @test_throws DomainError is_manifold_point(M, A, true)\n        @test_throws DomainError is_manifold_point(M, C, true)\n        @test_throws DomainError is_manifold_point(M, D, true)\n        @test check_tangent_vector(M, B_skewsym, B_skewsym) === nothing\n        @test_throws DomainError is_tangent_vector(M, B_skewsym, A, true)\n        @test_throws DomainError is_tangent_vector(M, A, B_skewsym, true)\n        @test_throws DomainError is_tangent_vector(M, B_skewsym, D, true)\n        @test_throws DomainError is_tangent_vector(\n            M,\n            B_skewsym,\n            1 * im * zero_tangent_vector(M, B_skewsym),\n            true,\n        )\n        @test manifold_dimension(M) == 3\n        @test manifold_dimension(M_complex) == 9\n        @test A_skewsym2 == project!(M, A_skewsym, A_skewsym)\n        @test A_skewsym2 == project(M, A_skewsym, A_skewsym)\n        A_sym3 = similar(A_skewsym)\n        embed!(M, A_sym3, A_skewsym)\n        A_sym4 = embed(M, A_skewsym)\n        @test A_sym3 == A_skewsym\n        @test A_sym4 == A_skewsym\n    end\n    types = [Matrix{Float64}, ]\n    TEST_FLOAT32 && push!(types, Matrix{Float32})\n    TEST_STATIC_SIZED && push!(types, MMatrix{3, 3, Float64})\n    bases = (DefaultOrthonormalBasis(), ProjectedOrthonormalBasis(:svd))\n    for T in types\n        pts = [convert(T, A_skewsym), convert(T, B_skewsym), convert(T, X)]\n        @testset \"Type $T\" begin\n            test_manifold(\n                M,\n                pts,\n                test_injectivity_radius = false,\n                test_reverse_diff = isa(T, Vector),\n                test_project_tangent = true,\n                test_musical_isomorphisms = true,\n                test_vector_transport = true,\n                basis_types_vecs = (\n                    DiagonalizingOrthonormalBasis(log(M, pts[1], pts[2])),\n                    bases...,\n                ),\n                basis_types_to_from = bases,\n            )\n        end\n    end\n    complex_types = [ Matrix{ComplexF64}, ]\n    TEST_FLOAT32 && push!(complex_types, Matrix{ComplexF32})\n    TEST_STATIC_SIZED && push!(compley_types, MMatrix{3, 3, ComplexF64})\n    for T in complex_types\n        pts_complex =\n            [convert(T, A_skewsym_complex), convert(T, B_skewsym_complex), convert(T, X)]\n        @testset \"Type $T\" begin\n            test_manifold(\n                M_complex,\n                pts_complex,\n                test_injectivity_radius = false,\n                test_reverse_diff = isa(T, Vector),\n                test_project_tangent = true,\n                test_musical_isomorphisms = true,\n                test_vector_transport = true,\n                basis_types_vecs = (DefaultOrthonormalBasis(),),\n                basis_types_to_from = (DefaultOrthonormalBasis(),),\n            )\n            @test isapprox(\n                -pts_complex[1],\n                exp(M, pts_complex[1], log(M, pts_complex[1], -pts_complex[1])),\n            )\n        end # testset type $T\n    end # for\nend # test SymmetricMatrices\n", "meta": {"hexsha": "1a32811e6cf20134208d96f048757454c024ca35", "size": 3908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/skewsymmetric.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": "test/skewsymmetric.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": "test/skewsymmetric.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": 42.0215053763, "max_line_length": 89, "alphanum_fraction": 0.5759979529, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7797771462968766}}
{"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, \u03b1, 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, \u03b1, end_point, h, ::Riesz_Symmetric)\n    N=Int(floor(end_point/h))\n\n    mat = RieszMatrix(\u03b1, N+1, h)\n    return mat*f.(collect(0:h:end_point))\nend\nfunction RieszMatrix(\u03b1, N, h)\n    caputo = B(N+1, \u03b1)\n    caputo = caputo[2:(N+1), 1:N]\n    result = 1/2*(caputo+caputo')\n    result = h^(-\u03b1)*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 \u2208 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 \u2208 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(\ud835\udc65::Number,\ud835\udc66::Number,\ud835\udc4e::Number,\ud835\udc4f::Number)\n    \ud835\udc66^2 == \ud835\udc65^3 + \ud835\udc4e*\ud835\udc65 + \ud835\udc4f\nend\n\nPOINTTYPES = Union{Integer,PrimeField}\n\n\"\"\"\nRepresents a point with coordinates (\ud835\udc65,\ud835\udc66) on an elliptic curve where \ud835\udc66\u00b2 = \ud835\udc65\u00b3 + \ud835\udc4e\ud835\udc65 + \ud835\udc4f\nOptional parameter \ud835\udc5d represents finite field \ud835\udc39\u209a and will convert all other parameter to PrimeField\nPoint(\u221e,\u221e,\ud835\udc4e,\ud835\udc4f) represents point at infinity\nReturns an error if elliptic curve equation isn't satisfied\n\"\"\"\nstruct Point{T<:Number,S<:Number} <: AbstractPoint\n    \ud835\udc65::T\n    \ud835\udc66::T\n    \ud835\udc4e::S\n    \ud835\udc4f::S\n    Point{T,S}(\ud835\udc65,\ud835\udc66,\ud835\udc4e,\ud835\udc4f) where {T<:Number,S<:Number} = new(\ud835\udc65,\ud835\udc66,\ud835\udc4e,\ud835\udc4f)\nend\n\nPoint(\ud835\udc65::Infinity,\ud835\udc66::Infinity,\ud835\udc4e::T,\ud835\udc4f::T) where {T<:POINTTYPES} = Point{Infinity,T}(\ud835\udc65,\ud835\udc66,\ud835\udc4e,\ud835\udc4f)\nPoint(\ud835\udc65::T,\ud835\udc66::T,\ud835\udc4e::T,\ud835\udc4f::T) where {T<:POINTTYPES} = !iselliptic(\ud835\udc65,\ud835\udc66,\ud835\udc4e,\ud835\udc4f) ? throw(DomainError(\"Point is not on curve\")) : Point{T,T}(\ud835\udc65,\ud835\udc66,\ud835\udc4e,\ud835\udc4f)\nPoint(\ud835\udc65::Infinity,\ud835\udc66::Infinity,\ud835\udc4e::T,\ud835\udc4f::T,\ud835\udc5d::T) where {T<:Integer} = Point(\ud835\udc65,\ud835\udc66,FieldElement(\ud835\udc4e,\ud835\udc5d),FieldElement(\ud835\udc4f,\ud835\udc5d))\nPoint(\ud835\udc65::T,\ud835\udc66::T,\ud835\udc4e::T,\ud835\udc4f::T,\ud835\udc5d::T) where {T<:Integer} = Point(FieldElement(\ud835\udc65,\ud835\udc5d),FieldElement(\ud835\udc66,\ud835\udc5d),FieldElement(\ud835\udc4e,\ud835\udc5d),FieldElement(\ud835\udc4f,\ud835\udc5d))\n\n\"Formats AbstractPoint as (\ud835\udc65, \ud835\udc66) on \ud835\udc66\u00b2 = \ud835\udc65\u00b3 + \ud835\udc4e\ud835\udc65 + \ud835\udc4f (: \ud835\udc39\u209a)\"\nfunction show(io::IO, z::AbstractPoint)\n    if typeof(z.\ud835\udc65) <: PrimeField\n        x, y = z.\ud835\udc65.\ud835\udc5b, z.\ud835\udc66.\ud835\udc5b\n    else\n        x, y = z.\ud835\udc65, z.\ud835\udc66\n    end\n\n    if typeof(z.\ud835\udc4e) <: PrimeField\n        a, b = z.\ud835\udc4e.\ud835\udc5b, z.\ud835\udc4f.\ud835\udc5b\n        field = string(\" : \ud835\udc39\", z.\ud835\udc4e.\ud835\udc5d)\n    else\n        a, b = z.\ud835\udc4e, z.\ud835\udc4f\n        field = \"\"\n    end\n    print(io, \"(\", x, \", \", y, \") on \ud835\udc66\u00b2 = \ud835\udc65\u00b3 + \", a, \"\ud835\udc65 + \", 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 +(\ud835\udc43::AbstractPoint,\ud835\udc44::AbstractPoint)\n    T = typeof(\ud835\udc43)\n    S = typeof(\ud835\udc43.\ud835\udc4e)\n    if \ud835\udc43.\ud835\udc4e != \ud835\udc44.\ud835\udc4e || \ud835\udc43.\ud835\udc4f != \ud835\udc44.\ud835\udc4f\n        throw(DomainError(\"Points are not on the same curve\"))\n\n    # Case 0\n    elseif \ud835\udc43.\ud835\udc65 == \u221e\n        return \ud835\udc44\n    elseif \ud835\udc44.\ud835\udc65 == \u221e\n        return \ud835\udc43\n    elseif \ud835\udc43.\ud835\udc65 == \ud835\udc44.\ud835\udc65 && \ud835\udc43.\ud835\udc66 != \ud835\udc44.\ud835\udc66\n        # something more elegant should exist to return correct point type\n        if T <: Point\n            return Point{Infinity,S}(\u221e, \u221e, \ud835\udc43.\ud835\udc4e, \ud835\udc43.\ud835\udc4f)\n        elseif T <: S256Point\n            return S256Point{Infinity}(\u221e, \u221e, \ud835\udc43.\ud835\udc4e, \ud835\udc43.\ud835\udc4f)\n        end\n\n    # Case 1\n    elseif \ud835\udc43.\ud835\udc65 != \ud835\udc44.\ud835\udc65\n        \u03bb = (\ud835\udc44.\ud835\udc66 - \ud835\udc43.\ud835\udc66) \u00f7 (\ud835\udc44.\ud835\udc65 - \ud835\udc43.\ud835\udc65)\n        \ud835\udc65 = \u03bb^2 - \ud835\udc43.\ud835\udc65 - \ud835\udc44.\ud835\udc65\n    # Case 2\n    else\n        \u03bb = (3 * \ud835\udc43.\ud835\udc65^2 + \ud835\udc43.\ud835\udc4e) \u00f7 (2 * \ud835\udc43.\ud835\udc66)\n        \ud835\udc65 = \u03bb^2 - 2 * \ud835\udc43.\ud835\udc65\n    end\n    \ud835\udc66 = \u03bb * (\ud835\udc43.\ud835\udc65 - \ud835\udc65) - \ud835\udc43.\ud835\udc66\n    return T(S(\ud835\udc65), S(\ud835\udc66), \ud835\udc43.\ud835\udc4e, \ud835\udc43.\ud835\udc4f)\nend\n\n\"Scalar multiplication of a Point\"\nfunction *(\u03bb::Integer,\ud835\udc43::Point)\n    \ud835\udc45 = Point(\u221e, \u221e, \ud835\udc43.\ud835\udc4e, \ud835\udc43.\ud835\udc4f)\n    while \u03bb > 0\n        \ud835\udc45 += \ud835\udc43\n        \u03bb -= 1\n    end\n    return \ud835\udc45\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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -\u03b2*c*I/N*S\n        du[2] = \u03b2*c*I/N*S - \u03b3*I\n        du[3] = \u03b3*I\n    end\n    nothing\nend;\n\n\n\u03b4t = 0.1\ntmax = 80.0\ntspan = (0.0,tmax)\nt = 0.0:\u03b4t:tmax;\n\n\nu0 = [990.0,10.0,0.0]; # S,I.R\n\n\np = [0.05,10.0,0.25]; # \u03b2,c,\u03b3\n\n\nlockdown_times = [10.0, 20.0]\ncondition(u,t,integrator) = t \u2208 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": "include(\"diagnostics.jl\")\nusing DataFrames, Plots\n\nexport calc_auc\nexport roc_curve\n\n\"calc the AUC of a function given xs and ys\"\nfunction calc_auc(x::Array, y::Array)\n    df = rename!(hcat(x, y) |> DataFrame, Symbol.([\"x\", \"y\"]))\n    df = sort(df, [:x, :y])\n    auc = 0\n    for i in 2:nrow(df)\n        # rectangular component\n        x = df[i, :x][1] - df[i-1, :x][1]\n        y = df[i-1, :y][1]\n        auc += x*y\n        # triangular component\n        height = df[i, :y][1] - y\n        auc += 0.5*x * height\n    end\n    return auc\nend\n\n\"generates data necssary for ROC curve, array of true positive and false positive rates + AUC\"\nfunction roc_data(actual::Array{Int64}, pred::Array{Float64}, step = 0.01)\n    x = 0:step:1\n    tps = [true_positives(actual, predict_from_threshold(pred, threshold), rate=true) for threshold in x]\n    fps = [false_positives(actual, predict_from_threshold(pred, threshold), rate=true) for threshold in x]\n    auc = calc_auc(fps, tps)\n    return tps, fps, auc\nend\n\n\"\"\"\n_given array of predictions (0 \u2264 x \u2264 1] and array of actuals, return ROC AUC plot_\n\n#### parameters:\n    actual : Array{Int}\n        actual labels, \u2208 [0,1]\n    pred : Array{Float64}\n        an array of prediction values 0 \u2264 x \u2264 1\n\n#### returns: Plots.Plot{Plots.GRBackend}\n    plot of ROC AUC\n\"\"\"\nfunction roc_curve(actual::Array{Int}, pred::Array{Float64})\n    # diagonal line\n    p1 = plot(\n        [0, 1],\n        [0, 1],\n        label = \"\",\n        line = :dash,\n        color = :black,\n        ylim = (0, 1),\n        xlim = (0, 1),\n    )\n    y, x, auc = roc_data(actual, pred)\n    plot!(x, y, label = \"AUC=$(round(auc, digits=4))\", color = :blue)\n\n    plot!(legend = :bottomright)\n    plot!(\n        ylabel = \"True Positive Rate\",\n        xlabel = \"False Positive Rate\",\n        title = \"ROC and AUC\",\n    )\n    return p1\nend\n", "meta": {"hexsha": "21be9078f92071a82c2fac468434a074a838e675", "size": 1832, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evaluation/roc_auc.jl", "max_stars_repo_name": "dhopp1/BinaryClassificationTools", "max_stars_repo_head_hexsha": "b6411c440688b677b5eec54cca0b9cfbcf594d35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-12T11:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-12T11:32:18.000Z", "max_issues_repo_path": "src/evaluation/roc_auc.jl", "max_issues_repo_name": "dhopp1/BinaryClassificationTools.jl", "max_issues_repo_head_hexsha": "b6411c440688b677b5eec54cca0b9cfbcf594d35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/evaluation/roc_auc.jl", "max_forks_repo_name": "dhopp1/BinaryClassificationTools.jl", "max_forks_repo_head_hexsha": "b6411c440688b677b5eec54cca0b9cfbcf594d35", "max_forks_repo_licenses": ["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.3432835821, "max_line_length": 106, "alphanum_fraction": 0.5840611354, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7797152528844438}}
{"text": "## --- Weighted means\n\n    # Plain vanilla weighted mean\n    @test awmean([0,1,2,3],[1,1,1,1]) == (1.5, 0.5, 5/3)\n    @test awmean(1:10,ones(10)) == (5.5, 0.31622776601683794, 9.166666666666666)\n\n    # Weighted mean with geochronogists' MSWD-correction to uncertainty\n    @test gwmean([0,1,2,3],[1,1,1,1]) == (1.5, 0.6454972243679028, 5/3)\n    @test gwmean(1:10,ones(10)) == (5.5, 0.9574271077563381, 9.166666666666666)\n\n    # Mean Square of Weighted Deviates (aka reduced chi-squared)\n    @test MSWD(0:10, ones(11)) == 11\n    @test MSWD([0,1,2],[1,1,1]) == 1.0\n\n## --- York fit\n\n    x = [0.9304, 2.2969, 2.8047, 3.7933, 5.3853, 6.1995, 6.7479, 8.1856, 8.7423, 10.2588]\n    y = [0.8742, 2.1626, 3.042, 3.829, 5.0116, 5.5614, 6.7675, 7.8856, 9.6414, 10.4955]\n    fobj = yorkfit(x, ones(10)/4, y, ones(10)/4)\n    @test fobj.intercept \u2248  -0.23498964673701916\n    @test fobj.intercept_sigma \u2248 0.02250863813481163\n    @test fobj.slope \u2248 1.041124018512526\n    @test fobj.slope_sigma \u2248 0.0035683808205783673\n    @test fobj.mswd \u2248 1.1419901440278089\n\n    @test display(fobj) != NaN\n\n## ---\n", "meta": {"hexsha": "f299b7154b3066530e3c12666ba5c34634c020b1", "size": 1082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testGeochronology.jl", "max_stars_repo_name": "brenhinkeller/StatGeochemBase", "max_stars_repo_head_hexsha": "ead6e2c124191b43de7a3aecd49479bdd6512599", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-30T22:39:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T22:39:11.000Z", "max_issues_repo_path": "test/testGeochronology.jl", "max_issues_repo_name": "brenhinkeller/StatGeochemBase", "max_issues_repo_head_hexsha": "ead6e2c124191b43de7a3aecd49479bdd6512599", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-02T23:41:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T06:56:33.000Z", "max_forks_repo_path": "test/testGeochronology.jl", "max_forks_repo_name": "brenhinkeller/StatGeochemBase", "max_forks_repo_head_hexsha": "ead6e2c124191b43de7a3aecd49479bdd6512599", "max_forks_repo_licenses": ["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.3103448276, "max_line_length": 89, "alphanum_fraction": 0.6247689464, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7797152442574493}}
{"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    \u03c3 ~ Exponential(1)\n    for i in eachindex(D)\n        \u03bc = lin(a, A[i], bA)\n        D[i] ~ Normal(\u03bc, \u03c3)\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    \u03c3 ~ Exponential(1)\n    for i in eachindex(D)\n        \u03bc = lin(a, M[i], bM)\n        D[i] ~ Normal(\u03bc, \u03c3)\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    \u03c3 ~ Exponential(1)\n    for i in eachindex(D)\n        \u03bc = a + M[i] * bM + A[i] * bA\n        D[i] ~ Normal(\u03bc, \u03c3)\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, :\u03c3],:]) |> display\nParticles(chn5_2t[:,[:a, :bM, :\u03c3],:]) |> display\nParticles(chn5_3t[:,[:a, :bA, :bM, :\u03c3],:]) |> 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": "#\n# Me Learning Machine Learning\n# Chapter 1: Julia and Knet\n#\n# In summary, I am (loosely) following the Knet tutorial\n# (https://github.com/denizyuret/Knet.jl/blob/master/README.md#Tutorial-1)\n# and adding lots of comments, including some of these noob-style \"this line\n# does x, y and z\" comments (because I am a Julia noob :-) ).\n#\n# Leandro Motta Barros\n#\n\nusing Knet\n\n# ------------------------------------------------------------------------------\n# Reading and pre-processing data\n# ------------------------------------------------------------------------------\n\n# This is based on the classic \"Boston Housing\" dataset, which I downloaded from\n# https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data\n# (see the file `housing.names` on the same server and directory for more info).\n# This database contains 506 lines by 14 columns.\n\n# Read the data into an array. By default, `readdlm` assumes that fields are\n# separated by blanks -- quite handy, 'cause that's exactly what we have here.\nrawdata = readdlm(\"housing.data\") # [506 x 14]\n\n# Take only the input (independent variables), which is everything but the 14th\n# column. We also transpose the matrix, which at first seemed weird for me. It\n# turns out that Julia stores arrays in column-major order, so having the data\n# transposed will make it more efficient to iterate over the training examples.\nx = rawdata[:,1:13]' # [13 x 506]\n\n# Normalization of input variables. The operation itself is pretty standard,\n# though the implementation might deserve a comment or two. Here (as in the\n# previous line, indeed), there is a lot of Matlab/Octave taste. \"Dot-operator\"\n# to execute element-wise operations. Second parameter to `mean` and `std` (`2`)\n# meaning that the mean and standard deviation are to be made along the second\n# dimension of the array. In other words, along all elements in a single column.\n# Which, in still other words, is the same as saying that we are computing the\n# mean and standard deviation among all values of each feature (recall that `x`\n# was transposed in the previous line).\nx = (x .- mean(x,2)) ./ std(x,2) # [13 x 506]\n\n# Now take the expected output, which is on the 14th (and last) column in our\n# data. Again, transpose.\ny = rawdata[:,14:14]'\n\n# ------------------------------------------------------------------------------\n# Linear regression\n# ------------------------------------------------------------------------------\n\n# Initialize the weights. `randn` generates Gaussian-distributed random numbers\n# with mean equals to zero and standard deviation of 1.0.\n\n# TODO: Why this explicit array of `Any`? Why that additional zero?\n\nw = Any[ 0.1 * randn(1,13), 0 ]\n\n\n\nfunction train(w, data; lr = .1)\n    for (x,y) in data\n        dw = lossgradient(w, x, y)\n        for i in 1:length(w)\n            w[i] -= lr * dw[i]\n        end\n    end\n    return w\nend\n\n\nshow(w)\n\n#print(x)\n", "meta": {"hexsha": "77550514a916fcda151840f64f3921f3cd463ea1", "size": 2903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "knet_basics.jl", "max_stars_repo_name": "lmbarros/MLML-0001-Julia_Knet_Basics", "max_stars_repo_head_hexsha": "22bc842427d65a01b134e3a9040e88171d0fbaaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knet_basics.jl", "max_issues_repo_name": "lmbarros/MLML-0001-Julia_Knet_Basics", "max_issues_repo_head_hexsha": "22bc842427d65a01b134e3a9040e88171d0fbaaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knet_basics.jl", "max_forks_repo_name": "lmbarros/MLML-0001-Julia_Knet_Basics", "max_forks_repo_head_hexsha": "22bc842427d65a01b134e3a9040e88171d0fbaaf", "max_forks_repo_licenses": ["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.1973684211, "max_line_length": 80, "alphanum_fraction": 0.6369273166, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8499711737573763, "lm_q1q2_score": 0.7796808163372575}}
{"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)) \u00f7 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_\u03b1(b::ChebyshevU{T}) where {T} = one(T)/2\njacobi_\u03b2(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": "include(\"spline_kernel.jl\")\n\n# Removing t = 0, such that \u03a3 is invertible\nt = Vector(0.1:0.1:1)\nn = length(t);\n\n# Creating a test matrix \u03a3 = tril(UV') + triu(VU',1) that is PSD\np = 2;\nU, V = spline_kernel(t, p);\n\u03a3    = spline_kernel_matrix(U, V) + I;\nchol = cholesky(\u03a3)\n\n# Creating a symmetric exended generator representable semiseperable matrix\nK  = DiaSymSemiseparable(U,V,ones(n))\n# Calculating its Cholesky factorization\nL = DiaSymSemiseparableChol(K)\n# Creating a test vector\nx = randn(n);\n\n# Testing multiplication\n@test isapprox(L*x, chol.L*x, atol=1e-6)\n@test isapprox(L'*x, chol.U*x, atol=1e-6)\n\n# Testing inverses (Using Cholesky factorizations)\n@test isapprox(L'\\(L\\x), chol.U\\(chol.L\\x), atol=1e-6)\n@test isapprox(inv(L), chol.U\\(chol.L\\Diagonal(ones(K.n))), atol=1e-6)\n@test isapprox(inv(L,x), chol.U\\(chol.L\\x), atol=1e-6)\n@test isapprox(K*(K\\x), x)\n@test isapprox(K'*(K'\\x), x)\n\n# Testing logdet\n@test isapprox(logdet(L), logdet(chol.L), atol=1e-10)\n@test isapprox(logdet(L'), logdet(chol.U), atol=1e-10)\n\n# Testing traces\n@test isapprox(tr(L), tr(chol.L)) # Trace of L\n@test isapprox(trinv(L), tr(chol\\Diagonal(ones(K.n)))) # Trace of (K+D)^(-1)\nD = SymSemiseparable(U,V);\n@test isapprox(tr(L,D), tr(chol\\spline_kernel_matrix(U, V))) # Trace of (K+D)^(-1)K\n\n# Testing using the SymSemiseparableChol struct as a lower triangular matrix\nC = DiaSymSemiseparableChol(U,V,ones(K.n));\n@test isapprox(C*x, (tril(U*V',-1) + I)*x)\n", "meta": {"hexsha": "7fe0704da2913f346b68c1887b871a425f003a3d", "size": 1438, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_diasymsepchol.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SymSemiseparableMatrices.jl-c927be06-f564-11e9-2e25-11633cdb9fcb", "max_stars_repo_head_hexsha": "b5d7d3a338151204fe2d78f1780420b302b6c66f", "max_stars_repo_licenses": ["MIT"], "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_diasymsepchol.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SymSemiseparableMatrices.jl-c927be06-f564-11e9-2e25-11633cdb9fcb", "max_issues_repo_head_hexsha": "b5d7d3a338151204fe2d78f1780420b302b6c66f", "max_issues_repo_licenses": ["MIT"], "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_diasymsepchol.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SymSemiseparableMatrices.jl-c927be06-f564-11e9-2e25-11633cdb9fcb", "max_forks_repo_head_hexsha": "b5d7d3a338151204fe2d78f1780420b302b6c66f", "max_forks_repo_licenses": ["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.6818181818, "max_line_length": 83, "alphanum_fraction": 0.6870653686, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7796163986618145}}
{"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|| \u2a7d 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 \u21a6 0 if ||x|| \u2a7d r, +\u221e 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 \u00d7 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\u27e9`` 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\u030c = chebyshevtransform(f, Val(1))\nf\u0303 = x -> [cos(k*acos(x)) for k=0:n-1]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# First kind polynomials $\\to$ first kind points\nichebyshevtransform(f\u030c, Val(1)) \u2248 exp.(p_1)\n\n# Second kind points $\\to$ first kind polynomials\np_2 = chebyshevpoints(Float64, n, Val(2))\nf = exp.(p_2)\nf\u030c = chebyshevtransform(f, Val(2))\nf\u0303 = x -> [cos(k*acos(x)) for k=0:n-1]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# First kind polynomials $\\to$ second kind points\nichebyshevtransform(f\u030c, Val(2)) \u2248 exp.(p_2)\n\n# First kind points $\\to$ second kind polynomials\np_1 = chebyshevpoints(Float64, n, Val(1))\nf = exp.(p_1)\nf\u030c = chebyshevutransform(f, Val(1))\nf\u0303 = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-1]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# Second kind polynomials $\\to$ first kind points\nichebyshevutransform(f\u030c, Val(1)) \u2248 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\u030c = chebyshevutransform(f, Val(2))\nf\u0303 = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-3]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# Second kind polynomials $\\to$ second kind points\nichebyshevutransform(f\u030c, Val(2)) \u2248 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": "module TestCWrapper\n\nusing Ipopt\nusing Test\n\nfunction test_hs071()\n  # hs071\n  # min x1 * x4 * (x1 + x2 + x3) + x3\n  # st  x1 * x2 * x3 * x4 >= 25\n  #     x1^2 + x2^2 + x3^2 + x4^2 = 40\n  #     1 <= x1, x2, x3, x4 <= 5\n  # Start at (1,5,5,1)\n  # End at (1.000..., 4.743..., 3.821..., 1.379...)\n\n  function eval_f(x::Vector{Float64})\n    return x[1] * x[4] * (x[1] + x[2] + x[3]) + x[3]\n  end\n\n  function eval_g(x::Vector{Float64}, g::Vector{Float64})\n    # Bad: g    = zeros(2)  # Allocates new array\n    # OK:  g[:] = zeros(2)  # Modifies 'in place'\n    g[1] = x[1]   * x[2]   * x[3]   * x[4]\n    g[2] = x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2\n  end\n\n  function eval_grad_f(x::Vector{Float64}, grad_f::Vector{Float64})\n    # Bad: grad_f    = zeros(4)  # Allocates new array\n    # OK:  grad_f[:] = zeros(4)  # Modifies 'in place'\n    grad_f[1] = x[1] * x[4] + x[4] * (x[1] + x[2] + x[3])\n    grad_f[2] = x[1] * x[4]\n    grad_f[3] = x[1] * x[4] + 1\n    grad_f[4] = x[1] * (x[1] + x[2] + x[3])\n  end\n\n  function eval_jac_g(x::Vector{Float64}, mode, rows::Vector{Int32}, cols::Vector{Int32}, values::Vector{Float64})\n    if mode == :Structure\n      # Constraint (row) 1\n      rows[1] = 1; cols[1] = 1\n      rows[2] = 1; cols[2] = 2\n      rows[3] = 1; cols[3] = 3\n      rows[4] = 1; cols[4] = 4\n      # Constraint (row) 2\n      rows[5] = 2; cols[5] = 1\n      rows[6] = 2; cols[6] = 2\n      rows[7] = 2; cols[7] = 3\n      rows[8] = 2; cols[8] = 4\n    else\n      # Constraint (row) 1\n      values[1] = x[2]*x[3]*x[4]  # 1,1\n      values[2] = x[1]*x[3]*x[4]  # 1,2\n      values[3] = x[1]*x[2]*x[4]  # 1,3\n      values[4] = x[1]*x[2]*x[3]  # 1,4\n      # Constraint (row) 2\n      values[5] = 2*x[1]  # 2,1\n      values[6] = 2*x[2]  # 2,2\n      values[7] = 2*x[3]  # 2,3\n      values[8] = 2*x[4]  # 2,4\n    end\n  end\n\n  function eval_h(x::Vector{Float64}, mode, rows::Vector{Int32}, cols::Vector{Int32}, obj_factor::Float64, lambda::Vector{Float64}, values::Vector{Float64})\n    if mode == :Structure\n      # Symmetric matrix, fill the lower left triangle only\n      idx = 1\n      for row = 1:4\n        for col = 1:row\n          rows[idx] = row\n          cols[idx] = col\n          idx += 1\n        end\n      end\n    else\n      # Again, only lower left triangle\n      # Objective\n      values[1] = obj_factor * (2*x[4])  # 1,1\n      values[2] = obj_factor * (  x[4])  # 2,1\n      values[3] = 0                      # 2,2\n      values[4] = obj_factor * (  x[4])  # 3,1\n      values[5] = 0                      # 3,2\n      values[6] = 0                      # 3,3\n      values[7] = obj_factor * (2*x[1] + x[2] + x[3])  # 4,1\n      values[8] = obj_factor * (  x[1])  # 4,2\n      values[9] = obj_factor * (  x[1])  # 4,3\n      values[10] = 0                     # 4,4\n\n      # First constraint\n      values[2] += lambda[1] * (x[3] * x[4])  # 2,1\n      values[4] += lambda[1] * (x[2] * x[4])  # 3,1\n      values[5] += lambda[1] * (x[1] * x[4])  # 3,2\n      values[7] += lambda[1] * (x[2] * x[3])  # 4,1\n      values[8] += lambda[1] * (x[1] * x[3])  # 4,2\n      values[9] += lambda[1] * (x[1] * x[2])  # 4,3\n\n      # Second constraint\n      values[1]  += lambda[2] * 2  # 1,1\n      values[3]  += lambda[2] * 2  # 2,2\n      values[6]  += lambda[2] * 2  # 3,3\n      values[10] += lambda[2] * 2  # 4,4\n    end\n  end\n\n  n = 4\n  x_L = [1.0, 1.0, 1.0, 1.0]\n  x_U = [5.0, 5.0, 5.0, 5.0]\n\n  m = 2\n  g_L = [25.0, 40.0]\n  g_U = [2.0e19, 40.0]\n\n  prob = createProblem(n, x_L, x_U, m, g_L, g_U, 8, 10,\n  eval_f, eval_g, eval_grad_f, eval_jac_g, eval_h)\n\n  prob.x = [1.0, 5.0, 5.0, 1.0]\n  solvestat = solveProblem(prob)\n\n  @test Ipopt.ApplicationReturnStatus[solvestat] == :Solve_Succeeded\n  @test prob.x[1] \u2248 1.0000000000000000 atol=1e-5\n  @test prob.x[2] \u2248 4.7429996418092970 atol=1e-5\n  @test prob.x[3] \u2248 3.8211499817883077 atol=1e-5\n  @test prob.x[4] \u2248 1.3794082897556983 atol=1e-5\n  @test prob.obj_val \u2248 17.014017145179164 atol=1e-5\n\n  # This tests callbacks.\n  function intermediate(alg_mod::Int, iter_count::Int,\n    obj_value::Float64, inf_pr::Float64, inf_du::Float64, mu::Float64,\n    d_norm::Float64, regularization_size::Float64, alpha_du::Float64, alpha_pr::Float64,\n    ls_trials::Int)\n    return iter_count < 1  # Interrupts after one iteration.\n  end\n\n  setIntermediateCallback(prob, intermediate)\n\n  solvestat = solveProblem(prob)\n\n  @test Ipopt.ApplicationReturnStatus[solvestat] == :User_Requested_Stop\n\n  # Test setting some options\n  # String option\n  println(\"\\nString option\")\n  addOption(prob, \"hessian_approximation\", \"exact\")\n  @test_throws ErrorException addOption(prob, \"hessian_approximation\", \"badoption\")\n  println(\"\\nInt option\")\n  # Int option\n  addOption(prob, \"file_print_level\", 3) == nothing\n  @test_throws ErrorException addOption(prob, \"file_print_level\", -1)\n  # Double option\n  println(\"\\nFloat option\")\n  addOption(prob, \"derivative_test_tol\", 0.5)\n  @test_throws ErrorException addOption(prob, \"derivative_test_tol\", -1.0)\n\n  # Test opening an output file\n  openOutputFile(prob, \"blah.txt\", 5)\n  Ipopt.freeProblem(prob) # Needed before the `rm` on Windows.\n  # unlink the output file\n  rm(\"blah.txt\")\nend\n\nfunction test_binary()\n  # Test that the ipopt binary works\n  @test Ipopt.amplexefun(\"-v\") == 0\nend\n\nend  # TestCWrapper\n\nruntests(TestCWrapper)\n", "meta": {"hexsha": "133869f6c8939a52e6760b25c3cc672c611cb7a2", "size": 5258, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/C_wrapper.jl", "max_stars_repo_name": "loicvh/Ipopt.jl", "max_stars_repo_head_hexsha": "708c47db37a9c12d894b45549b4070ccc25592d0", "max_stars_repo_licenses": ["MIT"], "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/C_wrapper.jl", "max_issues_repo_name": "loicvh/Ipopt.jl", "max_issues_repo_head_hexsha": "708c47db37a9c12d894b45549b4070ccc25592d0", "max_issues_repo_licenses": ["MIT"], "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/C_wrapper.jl", "max_forks_repo_name": "loicvh/Ipopt.jl", "max_forks_repo_head_hexsha": "708c47db37a9c12d894b45549b4070ccc25592d0", "max_forks_repo_licenses": ["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.6746987952, "max_line_length": 156, "alphanum_fraction": 0.552681628, "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.7795117433513171}}
{"text": "# ---\n# title: 121. Best Time to Buy and Sell Stock\n# id: problem121\n# author: zhwang\n# date: 2022-01-17\n# difficulty: Easy\n# categories: Array, Dynamic Programming\n# link: <https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/>\n# hidden: true\n# ---\n# \n# Say you have an array for which the _i_ th element is the price of a given\n# stock on day _i_.\n# \n# If you were only permitted to complete at most one transaction (i.e., buy one\n# and sell one share of the stock), design an algorithm to find the maximum\n# profit.\n# \n# Note that you cannot sell a stock before you buy one.\n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: [7,1,5,3,6,4]\n#     Output: 5\n#     Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n#                  Not 7-1 = 6, as selling price needs to be larger than buying price.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: [7,6,4,3,1]\n#     Output: 0\n#     Explanation: In this case, no transaction is done, i.e. max profit = 0.\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction max_profit_121(prices::Vector{Int})::Int\n    min_cost, profit = prices[1], 0\n    for price in @view prices[2:end]\n        profit = max(profit, price - min_cost)\n        min_cost = min(min_cost, price)\n    end\n    return profit\nend\n\n## @lc code=end\n", "meta": {"hexsha": "dff0cfdd877c043a4ace354643cdeaabedefa774", "size": 1326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/121.best-time-to-buy-and-sell-stock.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/121.best-time-to-buy-and-sell-stock.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/121.best-time-to-buy-and-sell-stock.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": 24.5555555556, "max_line_length": 92, "alphanum_fraction": 0.6206636501, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8740772450055544, "lm_q1q2_score": 0.7795117416619088}}
{"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    \u03b1, \u03b2 = capm(asset_returns, benchmark_returns; risk_free=risk_free)\n    mean(asset_returns .- risk_free) / \u03b2 * 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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    infection = \u03b2*c*I/N*S\n    recovery = \u03b3*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\u03b4t = 1.0\ntspan = (0.0,tmax)\nobstimes = 1.0:\u03b4t:tmax;\nu0 = [990.0,10.0,0.0,0.0]; # S,I.R,C\np = [0.05,10.0,0.25]; # \u03b2,c,\u03b3\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p)\nsol_ode = solve(prob_ode,saveat=\u03b4t)\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,\u03b2) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000-I,I,0.0,0.0],p=[\u03b2,10.0,0.25])\n    sol = solve(prob,Tsit5(),saveat=\u03b4t)\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 \u03f5\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 \u03f5\n  Prior(priors), #Prior for each of the parameters\n  maxiterations=convert(Int,1e7),\n  nparticles=n_particles,\n  \u03b1 = 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, \u03bb, 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- `\u03bb::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, \u03bb::Real, lx::Real, ly::Real)\n    (n, m) = size(Uin)\n    ua = (-n/2:n/2-1)/lx*\u03bb\n    va = (-m/2:m/2-1)/ly*\u03bb\n    ifft(fft(Uin).*ifftshift([1.0-u^2-v^2>=0.0 ? exp(2im*pi*d/\u03bb*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*\u03c0*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) \u2264 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 \u2264 r*buffer) || (x \u2265 (lx - r*buffer))\n        return true\n\n    elseif (y \u2264 r*buffer) || (y \u2265 (ly - r*buffer))\n        return true\n    \n    elseif (z \u2264 r*buffer) || (z \u2265 (lz - r*buffer))\n        return true\n    end\n\n    return false\nend\n\nfunction generate_inclusions(lx, ly, lz, \u03d5, 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 \u2264 \u03d5\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 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# %%\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    \u03b1 ~ Normal(100, 10)\n    w ~ filldist(Normal(0, 2), size(B, 2))\n    \u03c3 ~ Exponential(1)\n    \u03bc = \u03b1 .+ B * w\n    doy ~ MvNormal(\u03bc, \u03c3)\nend\n\nm = spline(d2.doy)\n\n# %%\n# Sample from the prior. Looks pretty reasonable.\nprior = sample(m, Prior(), 100) |> DataFrame\nw_str = [\"w[$i]\" for i in 1:length(basis)]\n\nscatter(d2.year, d2.doy, alpha = 0.3)\nfor r in eachrow(prior)\n    p = r.\u03b1 .+ B * Array(r[w_str])\n    plot!(d2.year, p, color = :black, alpha = 0.2)\nend\nplot!(legend = false)\n\n# %%\n\"\"\"\nIt looks like the prior on the weights \"controls\" the possible amplitude of the wiggle (as\nopposed to the number of knots which controls its frequency).\n\"\"\"\n", "meta": {"hexsha": "491d78efa9226cd275355d909a6f5c18bf7f78f8", "size": 1206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch04/4H6.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/4H6.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/4H6.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.3333333333, "max_line_length": 90, "alphanum_fraction": 0.6691542289, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7794472434128717}}
{"text": "sqrt(sum(A.^2.) / length(A))\n", "meta": {"hexsha": "77af378a5b757cf667d6d439455d38eea7f23da1", "size": 29, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/averages-root-mean-square-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/averages-root-mean-square-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/averages-root-mean-square-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": 14.5, "max_line_length": 28, "alphanum_fraction": 0.5517241379, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7793733489755799}}
{"text": "using SymPy\nimport PyCall\nusing Test\n\n## Test of importing an external module using `pyimport_conda` and `import_from`.\n## from issue #262\n\nstats = PyCall.pyimport_conda(\"sympy.stats\", \"sympy\")\n\n# this brings in all functions into the session using introspection, specialized on a\n# symbolic first argument\nimport_from(stats)\n\n\n@testset \"Test stats module\" begin\n\n    @vars mu z x\n    @vars sigma positive=true\n    X = stats.Normal(\"x\", mu, sigma)\n\n    # some operations:\n    @test variance(X) == sigma^2\n    @test E(X) == mu\n    P(Gt(X,3)) ## or P(X \u226b 3)\n\n    Z = stats.Normal(\"Z\", 0, 1)  # needs `stats.` as \"Z\" is not symbolic,\n    # could also do this:\n    @vars Z\n    Z = Normal(Z, 0, 1)\n    @test E(Z) == 0\n    @test variance(Z) == 1\n\n    simplify(P(Gt(Z, 1)))\n\n    @test 0.68 <= 1 - 2*N(P(Gt(Z, 1))) <= 0.69\n\n\n    @vars Y\n    @vars a b c\n    Y = DiscreteUniform(Y, (a,b,c))\n    density(Y).dict\n    @test density(Y).dict[a] == 1//3\n\n    # And density\n    density(X)  #NormalDistribution(mu, sigma)\n    density(X).pdf(z)  # need the `pdf` call here\n\nend\n", "meta": {"hexsha": "9baccb1bde570b42c81f9c6cd58ac1f9d85e1477", "size": 1059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-external-module.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_stars_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 179, "max_stars_repo_stars_event_min_datetime": "2016-09-09T07:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:14:33.000Z", "max_issues_repo_path": "test/test-external-module.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_issues_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 256, "max_issues_repo_issues_event_min_datetime": "2016-09-08T13:37:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:26:16.000Z", "max_forks_repo_path": "test/test-external-module.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_forks_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2016-11-07T20:26:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T03:16:24.000Z", "avg_line_length": 21.612244898, "max_line_length": 85, "alphanum_fraction": 0.6071765817, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7793704052749909}}
{"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] \u22bb 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# title: 166. Fraction to Recurring Decimal\n# id: problem166\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Hash Table, Math\n# link: <https://leetcode.com/problems/fraction-to-recurring-decimal/description/>\n# hidden: true\n# ---\n# \n# Given two integers representing the `numerator` and `denominator` of a\n# fraction, return _the fraction in string format_.\n# \n# If the fractional part is repeating, enclose the repeating part in\n# parentheses.\n# \n# If multiple answers are possible, return **any of them**.\n# \n# It is **guaranteed** that the length of the answer string is less than `104`\n# for all the given inputs.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: numerator = 1, denominator = 2\n#     Output: \"0.5\"\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: numerator = 2, denominator = 1\n#     Output: \"2\"\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: numerator = 2, denominator = 3\n#     Output: \"0.(6)\"\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: numerator = 4, denominator = 333\n#     Output: \"0.(012)\"\n#     \n# \n# **Example 5:**\n# \n#     \n#     \n#     Input: numerator = 1, denominator = 5\n#     Output: \"0.2\"\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `-231 <= numerator, denominator <= 231 - 1`\n#   * `denominator != 0`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "c3626f6c0d840050900d36f58210c868788660ee", "size": 1386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/166.fraction-to-recurring-decimal.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/166.fraction-to-recurring-decimal.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/166.fraction-to-recurring-decimal.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.7692307692, "max_line_length": 82, "alphanum_fraction": 0.5663780664, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8723473846343394, "lm_q1q2_score": 0.7792761215629584}}
{"text": "# ------------------------------------------------------------------- #\n# CES Producer\n# ------------------------------------------------------------------- #\nimmutable CESProducer <: AbstractProducer\n    \u03b7::Float64\n    \u03bd::Float64\nend\n\n# call(p::CESProducer, k, l) = (p.\u03b7*k.^p.\u03bd + (1-p.\u03b7)*l.^(p.\u03bd)).^(1./p.\u03bd)\nBase.produce(p::CESProducer, k, l) = (p.\u03b7*k.^p.\u03bd + (1-p.\u03b7)*l.^(p.\u03bd)).^(1./p.\u03bd)\nf_k(p::CESProducer, k, l) = p.\u03b7 * (produce(p, k, l) ./ k).^(1.-p.\u03bd)\n\n# ------------------------------------------------------------------- #\n# Cobb-Douglas Producer\n# ------------------------------------------------------------------- #\nimmutable CobbDouglassProducer <: AbstractProducer\n    \u03b1_k::Float64\n    \u03b1_l::Float64\nend\n\nis_crs(i::CobbDouglassProducer) = i.\u03b1_k == 1. - i.\u03b1_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": "function nlp_cvx_206_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - linear objective\n    # - intersection convex quadratic constraints\n    # - power cones\n    # Variants\n    #   010 - intersection set\n\n    model = Model(optimizer)\n\n    # NOTE, starting any of these at 0.0 will segfault libcoinmumps\n    @variable(model, x >= 0, start = 0.1)\n    @variable(model, y >= 0, start = 0.1)\n    @variable(model, z >= 0, start = 0.1)\n\n    @objective(model, Max, 2 * x + y + z)\n    @NLconstraint(model, z <= x^(0.3) * y^(0.7))\n    @NLconstraint(model, x <= z^(0.7) * y^(0.3))\n    @NLconstraint(model, x^2 + y^2 <= z + 1)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, 4.0, tol = objective_tol)\n    return check_solution([x, y, z], [1, 1, 1], tol = primal_tol)\nend\n", "meta": {"hexsha": "1a91c3f51e860e21643ee9b8320a33efa7f756b8", "size": 977, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/206_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/206_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/206_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 28.7352941176, "max_line_length": 76, "alphanum_fraction": 0.6335721597, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7792356327083991}}
{"text": "# This function implements Kalman Filter on a state-space model of the form:\n# \u03b1_{t} = T * \u03b1_{t-1} + \u03b7_{t}\n# y_{t} = Z * \u03b1_{t} + \u03f5_{t}\n# E[\u03b7_{t}\u03b7'_{t}] = Q, E[\u03f5_{t}\u03f5'_{t}] = H\n\nfunction KalmanFilter(T::Matrix, Z::Matrix, Q::Matrix, H::Matrix, n::Integer, \u03b10, y)\n    \n    # Initialize state variables\n    \u03b1hat = repeat([zeros(size(\u03b10))], n);\n    \u03b1hat[1] = T*\u03b10;\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 * \u03b1hat[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        \u03b1hat[i + 1] = T * \u03b1hat[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 * \u03b1hat[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 \u03b1hat, 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\u1d40x'/\u2113\u00b2\n# Arguments:\n* `ll::Float64`: Log of the length scale \u2113\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*\u03c0*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,\u03a9,g,\u03b2)=(1/\u03b2) * log( sinh(\u03b2*\u03a9/2)/(\u03b2*\u03a9/2) ) - (\u03a9^2/2) * a2 + Va2(x0,a2,g)[1]\n# Large \u03b2 limit; by taking sinh(x)=e^x-e^-x , and then dropping e^-x\n#Wtilde(x0,a2,\u03a9,g,\u03b2)=(1/\u03b2) * (\u03b2*\u03a9/2 - log(\u03b2*\u03a9/2)) - (\u03a9^2/2) * a2 + Va2(x0,a2,g)[1]\n\n# Branch depending on \u03b2; for accuracy + lack of infinities\n\"\"\"\n    Wtilde(x0,a2,\u03a9,V,\u03b2)\n\n(5) in Feynman and Kleinert. Switches depending on D=\u03b2*\u03a9/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\u03b2.  \n\"\"\"\nfunction Wtilde(x0,a2,\u03a9,V,\u03b2)\n    D=\u03b2*\u03a9/2\n    if D>7.5\n        F=(1/\u03b2) * (D - log(2*D)) # Large limit;  by taking sinh(x)=e^x-e^-x , and then dropping e^-x\n    else\n        F=(1/\u03b2)*( log(sinh(D)/D) ) # explicit evaluation, naively as written in (5)\n    end\n    V0=Va2(x0,a2,V)[1]\n    mid=(\u03a9^2/2) * a2\n    return F-mid+V0\nend\n\n\"\"\"\n   verboseWtilde(x0,a2,\u03a9,g,\u03b2)\n\nExpanded version of Wtilde, reporting the decomposition - this was used to explain what was going wrong\n\"\"\"\nfunction verboseWtilde(x0,a2,\u03a9,g,\u03b2)\n    D=\u03b2*\u03a9/2\n    println(\"D=\u03b2*\u03a9/2 = $D\")\n    F= (1/\u03b2)*( log(sinh(D)) - log(D) )\n    #F= (1/\u03b2)*( (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/\u03b2) * (D - log(2*D))\n    V=Va2(x0,a2,g)[1]\n    mid=(\u03a9^2/2) * a2\n    println(\"Wtilde(x0=$x0,a2=$a2,\u03a9=$\u03a9,g=$g,\u03b2=$\u03b2) \\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,\u03b2)\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,\u03b2)\n    #println(\"W(x0=$x0,g=$g,\u03b2=$\u03b2)\")\n    \n    a2(\u03a9)=1/(\u03b2*\u03a9^2)*( (\u03b2*\u03a9)/2 * coth(\u03b2*\u03a9/2)-1 ) #(7)\n    myf(x)=Wtilde(x0,a2(x[1]),x[1],g,\u03b2)\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    \u03a9=Optim.minimizer(res)[1]\n    mya2=a2(\u03a9)[1]\n    #println(\"Optimised for W(x0=$x0,g=$g,\u03b2=$\u03b2). \\n\\t\u03a9=$\u03a9, 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 \u2113_0 and \u2113_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## \u2113_1 trend filtering, see \"\u2113_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\u03bb = 2.0\nproblem = minimize(sumsquares(x - g) + \u03bb * 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## \u2113_0 trend filtering\n\u03b6 = 0.02\nI_l0, Y_l0, f_l0 = fit_pwl_regularized(g, \u03b6)\n\n\n\nplot(g, label=\"SP500\", size=(1000,550));\nplot!(x_l1, lw=2.5, label=\"l1 reg. lambda = $\u03bb\");\nplot!(I_l0, Y_l0, lw=2.5, label=\"l0 reg. zeta = $\u03b6\")\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": "@testset \"Minimum Volume Ellipsoid\" begin\n    X = [\n        -1 -1 1 2\n        1 -1 -1 2\n    ]\n\n    @testset \"Centered\" begin\n        \u03f5 = minimum_volume_ellipsoid(X, 1e-10; centered=true)\n\n        @test \u03f5.x == [0, 0]\n        @test \u03f5.H \u2248 [5/8 -3/8; -3/8 5/8] atol = 1e-10\n    end\n\n    @testset \"Not Centered\" begin\n        \u03f5 = minimum_volume_ellipsoid(X, 1e-10)\n\n        @test \u03f5.x \u2248 [0.5, 0.5] atol = 1e-10\n        @test \u03f5.H \u2248 [2/3 -2/9; -2/9 2/3] atol = 1e-10\n    end\nend\n", "meta": {"hexsha": "d49b722580e98720b49b577fe390e8ae002a9504", "size": 471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/minimumvolumeellipsoid.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": "test/minimumvolumeellipsoid.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": "test/minimumvolumeellipsoid.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.4285714286, "max_line_length": 61, "alphanum_fraction": 0.5031847134, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7791639829835344}}
{"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,\u03a3,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) \u2218 R \u2218 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\u0142 Kami\u0144ski, 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\u00b2(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\u00b2(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 `\u221a(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 \u00b1 \u221a(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\u0303 | real(x\u0303) = 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 DynamicalSystems, Base.Test\n\nprintln(\"\\nTesting discrete system lyapunov exponents...\")\n\n\n@testset \"Towel Map\" begin\n  @testset \"lyapunovs\" begin\n    ds = Systems.towel()\n    \u03bb1 = lyapunovs(ds, 1e5)\n    @test 0.42 < \u03bb1[1] < 0.44\n    @test 0.36 < \u03bb1[2] < 0.38\n    @test -3.4 < \u03bb1[3] < -3.2\n  end\n\n  @testset \"lyapunovs ForwardDiff\" begin\n    ds = Systems.towel()\n    ds = DiscreteDS(ds.state, ds.eom)\n    \u03bb1 = lyapunovs(ds, 1e5)\n    @test 0.42 < \u03bb1[1] < 0.44\n    @test 0.36 < \u03bb1[2] < 0.38\n    @test -3.4 < \u03bb1[3] < -3.1\n  end\n\n  @testset \"lyapunov\" begin\n    ds1 = Systems.towel()\n    ds2 = DiscreteDS(ds1.state, ds1.eom)\n    \u03bb1 = lyapunov(ds1, 100000)\n    \u03bb2 = lyapunov(ds2, 100000)\n    @test 0.42 < \u03bb1[1] < 0.44\n    @test 0.42 < \u03bb2[1] < 0.44\n    @test isapprox(\u03bb1, \u03bb2; rtol = 1e-3)\n  end\nend\n\n@testset \"Logistic Map\" begin\n  lg1 = Systems.logistic(0.1, r=4)\n  lg2 = DiscreteDS1D(lg1.state, lg1.eom)\n  lg3 = Systems.logistic(big(0.1), r=4)\n  @test typeof(lg3.state) == BigFloat\n  \u03bb1 = lyapunov(lg1, 10000000; Ttr = 100)\n  \u03bb2 = lyapunovs(lg2, 10000000; Ttr = 100)\n  \u03bb3 = lyapunovs(lg3, 100000; Ttr = 100)\n  @test typeof(\u03bb3) == BigFloat\n  @test isapprox(\u03bb1, log(2); rtol = 1e-3)\n  @test isapprox(\u03bb2, log(2); rtol = 1e-3)\n  @test isapprox(\u03bb3, log(2); rtol = 1e-3)\nend\n\n@testset \"Henon Map\" begin\n  @testset \"lyapunovs\" begin\n    ds = Systems.henon()\n    \u03bb1 = lyapunovs(ds, 1e6)\n    @test 0.418 < \u03bb1[1] < 0.422\n    @test -1.63 < \u03bb1[2] < -1.61\n  end\n\n  @testset \"lyapunovs ForwardDiff\" begin\n    ds = Systems.henon()\n    ds = DiscreteDS(ds.state, ds.eom)\n    \u03bb1 = lyapunovs(ds, 1e6)\n    @test 0.418 < \u03bb1[1] < 0.422\n    @test -1.63 < \u03bb1[2] < -1.61\n  end\n\n  @testset \"lyapunov\" begin\n    ds1 = Systems.henon()\n    ds2 = DiscreteDS(ds1.state, ds1.eom)\n    \u03bb1 = lyapunov(ds1, 1000000)\n    \u03bb2 = lyapunov(ds2, 1000000)\n    @test 0.418 < \u03bb1[1] < 0.422\n    @test 0.418 < \u03bb2[1] < 0.422\n    @test isapprox(\u03bb1, \u03bb2; rtol = 1e-3)\n  end\nend\n", "meta": {"hexsha": "e9c7af280bf1cddde7c198dc2d3fb0b14be1baf6", "size": 1927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/discrete_lyapunov.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/discrete_lyapunov.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/discrete_lyapunov.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": 25.6933333333, "max_line_length": 58, "alphanum_fraction": 0.5973015049, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7791408672486336}}
{"text": "module TestGegenbauer\n\nexport constant_ode, linear_ode, trig_ode \n\ninclude(\"../src/CustomTypes.jl\")\ninclude(\"../src/Chebyshev.jl\")\ninclude(\"../src/Gegenbauer.jl\")\nusing LinearAlgebra, SparseArrays\nusing SpecialFunctions: airyai\nusing Jacobi: jacobi \nusing .CustomTypes\nimport .Chebyshev as CH \nimport .Gegenbauer as GE \n\nimport Test: @test\n\nconst tolerance = 1e-8 ## tolerance we compare to\n\n##============================================================\n\n\"\"\"\nEvaluate ODE u' = 0, with u(xmin) = c0.\n\"\"\"\nfunction constant_sol_ode(\n      nx::myI,\n      xmin::myF,\n      xmax::myF,\n      c0::myF\n   ) \n   D1 = GE.compute_D(nx,tomyI(1))\n   D1 = [transpose([(-1)^i for i=0:(nx-1)]);D1]\n\n   f0 = [c0; [0.0 for i=1:nx]]\n\n   numerical_sol = D1\\f0\n   analytic_sol  = [c0; [0.0 for i=1:(nx-1)]]\n\n   println(\"Test: Gegenbauer constant solution ODE\")\n   @test norm(numerical_sol .- analytic_sol,1) < tolerance\n   return nothing \nend\n\n\"\"\"\nEvaluate ODE u'' = 0, with u(xmin) = c0, u'(xmax) = c1.\n\"\"\"\nfunction linear_sol_ode(\n      nx::myI,\n      xmin::myF,\n      xmax::myF,\n      c0::myF,\n      c1::myF\n   ) \n   D2 = GE.compute_D(nx,tomyI(2))\n   D2 = [transpose([1      for i=0:(nx-1)]);D2]\n   D2 = [transpose([(-1)^i for i=0:(nx-1)]);D2]\n\n   f0 = [c0; c1; [0.0 for i=1:nx]]\n\n   numerical_sol = D2\\f0\n   \n   ## coordinate change\n   numerical_sol[1] -= numerical_sol[2]*(xmax+xmin)/(xmax-xmin)\n   numerical_sol[2] *= 2.0/(xmax-xmin)\n   \n   analytic_sol  = [\n                    (c0*xmax - c1*xmin)/(xmax-xmin); \n                    (c1-c0)/(xmax-xmin); \n                    [0.0 for i=1:(nx-2)]\n                   ]\n\n   println(\"Test: Gegenbauer linear solution ODE\")\n   @test norm(numerical_sol .- analytic_sol,1) < tolerance\n   return nothing \nend\n\n\"\"\"\nEvaluate ODE u'' - x*u = 0, with u(xmin) = Airy(xmin), u(xmax) = Airy(xmax).\n\"\"\"\nfunction airy_sol_ode(\n      nx::myI,\n      xmin::myF,\n      xmax::myF,\n      om2::myF\n   ) \n   D2  = GE.compute_D(nx,tomyI(2),xmin,xmax)\n   X1  = GE.compute_MXp(nx,tomyI(2),tomyI(1),xmin,xmax)\n   S0  = GE.compute_S(nx,tomyI(0))\n   S1  = GE.compute_S(nx,tomyI(1))\n   \n   Op  = D2 - X1*S1*S0 \n   Op  = [transpose([1      for i=0:(nx-1)]);Op]\n   Op  = [transpose([(-1)^i for i=0:(nx-1)]);Op]\n\n   f0 = [airyai(xmin); airyai(xmax); [0.0 for i=1:nx]]\n\n   numerical_sol = Op\\f0 \n   \n   pts = CH.cheb_pts(xmin,xmax,nx)\n   analytic_sol = CH.to_cheb(airyai.(pts))\n\n   println(\"Test: Gegenbauer Airy function solution ODE\")\n   @test norm(numerical_sol .- analytic_sol,1) < tolerance\n   return nothing \nend\n\n\"\"\"\nEvaluate ODE Jacobi equation\n\"\"\"\nfunction jacobi_sol_ode(\n      nx::myI,\n      n::myI,\n      a::myF,\n      b::myF\n   ) \n   xmin = tomyF(-1)\n   xmax = tomyF(+1)\n\n   f(x) = jacobi(x, n, a, b)\n\n   Id  = sparse(I,nx,nx)\n   D1  = GE.compute_D(nx,tomyI(1),xmin,xmax)\n   D2  = GE.compute_D(nx,tomyI(2),xmin,xmax)\n   X1  = GE.compute_MXp(nx,tomyI(2),tomyI(1),xmin,xmax)\n   X2  = GE.compute_MXp(nx,tomyI(2),tomyI(2),xmin,xmax)\n   S0  = GE.compute_S(nx,tomyI(0))\n   S1  = GE.compute_S(nx,tomyI(1))\n\n   println(Id)\n   println(X2)\n   println(D2)\n   println((Id .- X2)*D2 .+ ((b-a)*Id .- (a+b+2.0)*X1)*S1*D1 .+ n*(n+a+b+1)*S1*S0)\n\n   Op  = (Id .- X2)*D2 .+ ((b-a)*Id .- (a+b+2.0)*X1)*S1*D1 #+ n*(n+a+b+1)*S1*S0\n\n   println(Op)\n   println(eigen(Matrix(Op)).values)\n   \n   f0 = [0.0 for i=1:nx]\n\n   numerical_sol = Op\\f0\n\n   pts = CH.cheb_pts(xmin,xmax,nx)\n   analytic_sol  = f.(pts) \n   analytic_sol  = CH.to_cheb(analytic_sol) \n\n   println(f0)\n   println(Op)\n   println(numerical_sol)\n   println(analytic_sol)\n\n   println(\"Test: Gegenbauer Jacobi function solution ODE\")\n   @test norm(numerical_sol .- analytic_sol,1) < tolerance\n   return nothing \nend\n\nend\n", "meta": {"hexsha": "61894a949e46af329a052daecc83d32440f82a20", "size": 3668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TestGegenbauer.jl", "max_stars_repo_name": "JLRipley314/TeukolskyQNMFunctions.jl", "max_stars_repo_head_hexsha": "5468ce0c71348a31eb71368791fb198b17d05a35", "max_stars_repo_licenses": ["MIT"], "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/TestGegenbauer.jl", "max_issues_repo_name": "JLRipley314/TeukolskyQNMFunctions.jl", "max_issues_repo_head_hexsha": "5468ce0c71348a31eb71368791fb198b17d05a35", "max_issues_repo_licenses": ["MIT"], "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/TestGegenbauer.jl", "max_forks_repo_name": "JLRipley314/TeukolskyQNMFunctions.jl", "max_forks_repo_head_hexsha": "5468ce0c71348a31eb71368791fb198b17d05a35", "max_forks_repo_licenses": ["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.3630573248, "max_line_length": 82, "alphanum_fraction": 0.5779716467, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7791306622738028}}
{"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 \u03c0 \u00d7 f(0,0).\n# We analyze the function on an N\u00d7M tensor product grid defined by:\n#\n#   r\u2099 = cos[(n+1/2)\u03c0/2N], for 0 \u2264 n < N, and\n#\n#   \u03b8\u2098 = 2\u03c0 m/M, for 0 \u2264 m < M;\n#\n# we convert the function samples to Chebyshev\u00d7Fourier coefficients using\n# `plan_disk_analysis`; and finally, we transform the Chebyshev\u00d7Fourier\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\u03b8 = (0:M-1)*2/M # mod \u03c0.\n\n# On the mapped tensor product grid, our function samples are:\nF = [f(r*cospi(\u03b8), r*sinpi(\u03b8)) for r in r, \u03b8 in \u03b8]\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 \u03c0/2 by harmonicity. The coefficient of Z_0^0\n# multiplied by \u221a\u03c0 is:\nU[1, 1]*sqrt(\u03c0)\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\u03b1, randomindex\n\n\"\"\"\n\tresample\u03b1(\u03b1::Float64, N::Int, K::Int)\n\nResample \u03b1 given the approach by Escobar and West. (page 585)\n\"\"\"\nfunction resample\u03b1(\u03b1::Float64, N::Int, K::Int; k = 1.0, \u0398 = 1.0, maxiter = 1)\n\n    w = zeros(2)\n    w[2] = N\n\n    f0 = k + K\n    f1 = \u0398 + K - 1\n\n    new\u03b1 = \u03b1\n\n    for i in 1:maxiter\n\n        \u03b7 = rand(Beta(new\u03b1 + 1, N))\n        f3 = \u0398 - log(\u03b7)\n\n        w[1] = f1 / f3\n\n        z = randomindex(w)\n\n        if z == 1\n            new\u03b1 = rand(Gamma(f0, 1/f3))\n        else\n            new\u03b1 = rand(Gamma(f1, 1/f3))\n        end\n    end\n\n    return new\u03b1\nend\n\nfunction resample\u03b1(\u03b1::Float64, N::Array{Int}, K::Array{Int}; k = 1.0, \u0398 = 1.0, maxiter = 1)\n    # implementation according to escobar - west page\n    totalK = sum(K)\n    num = length(N)\n\n    \u03b7 = zeros(num)\n\n\t\tnew\u03b1 = \u03b1\n    for i in 1:maxiter\n\n        for j in 1:num\n            \u03b7[j] = rand(Beta(new\u03b1 + 1, N[j]))\n        end\n\n        z = rand(num) .* (new\u03b1 + N) .< N\n\n        g_a = k + totalK - sum(z)\n        g_b = \u0398 - sum(log(\u03b7))\n\n        new\u03b1 = rand(Gamma(g_a, 1/g_b))\n    end\n\n    new\u03b1\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": "using PolyChaos, GaussQuadrature, Test, LinearAlgebra\n\n@testset \"Test Fejer rule\" begin\n    for m = 1:20\n        n, w = fejer(m)\n        @test length(n) == length(w) == m\n    end\n    for m = 1:20\n        n, w = golubwelsch(rm_hermite(m+1)...)\n        @test length(n) == length(w) == m\n    end\nend\n\n@testset \"N+1 quadrature rules\" begin\n    @testset \"Test Fejer2 rule\" begin\n        for m = 2:20\n            n, w = fejer2(m)\n            @test length(n) == length(w) == m + 1\n        end\n    end\n    @testset \"Test Clenshaw Curtis rule\" begin\n        for m = 2:20\n            n, w = clenshaw_curtis(m)\n            @test length(n) == length(w) == m + 1\n        end\n    end\n    @testset \"Test Radau rule\" begin\n        for m = 1:20\n            n, w = radau(rm_hermite(m+2)...,4.)\n            @test length(n) == length(w) == m + 1\n        end\n    end\nend\n\n@testset \"N+2 quadrature rule (lobatto)\" begin\n    for m = 1:20\n        n, w = lobatto(rm_legendre(m+3)...,-1.,1.)\n        @test length(n) == length(w) == m + 2\n    end\nend", "meta": {"hexsha": "3fe4031fc6b2a4da7b819dd81a5182b089c791c0", "size": 1023, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/comparison_gaussquadrature.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": "test/comparison_gaussquadrature.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": "test/comparison_gaussquadrature.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": 25.575, "max_line_length": 53, "alphanum_fraction": 0.5083088954, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.779049393716823}}
{"text": "@testset \"Sinc interpolation based on FFT\" begin\n\n    function test_interpolation_sum_fft(N_low, N)\n\t    x_min = 0.0\n\t    x_max = 16\u03c0\n\t    \n\t    xs_low = range(x_min, x_max, length=N_low+1)[1:N_low]\n\t    xs_high = range(x_min, x_max, length=N)[1:end-1]\n\t    f(x) = sin(0.5*x) + cos(x) + cos(2 * x) + sin(0.25*x)\n\t    arr_low = f.(xs_low)\n\t    arr_high = f.(xs_high)\n\n\t    xs_interp = range(x_min, x_max, length=N+1)[1:N]\n\t    arr_interp = resample(arr_low, N)\n\n\t    xs_interp_s = range(x_min, x_max, length=N+1)[1:N]\n\t    arr_interp_s = FFTResampling.sinc_interpolate_sum(arr_low, N)\n\n        @test \u2248(arr_interp[2*N \u00f710: N*8\u00f710], arr_high[2* N \u00f710: N*8\u00f710], rtol=0.05)\n        @test \u2248(arr_high[2*N \u00f710: N*8\u00f710], arr_interp_s[2*N \u00f710: N*8\u00f710], rtol=0.05)\n    end\n\n    test_interpolation_sum_fft(128, 1000)\n    test_interpolation_sum_fft(129, 1000)\n    test_interpolation_sum_fft(120, 1531)\n    test_interpolation_sum_fft(121, 1211)\nend\n\n\n@testset \"Downsampling based on frequency cutting\" begin\n    function test_resample(N_low, N)\n\t    x_min = 0.0\n\t    x_max = 16\u03c0\n\t    \n\t    xs_low = range(x_min, x_max, length=N_low+1)[1:N_low]\n\t    f(x) = sin(0.5*x) + cos(x) + cos(2 * x) + sin(0.25*x)\n\t    arr_low = f.(xs_low)\n\n\t    xs_interp = range(x_min, x_max, length=N+1)[1:N]\n\t    arr_interp = resample(arr_low, N)\n\n\t    xs_interp_s = range(x_min, x_max, length=N+1)[1:N]\n\t    arr_interp_s = FFTResampling.sinc_interpolate_sum(arr_low, N)\n\n        arr_ds = FFTResampling.resample(arr_interp, N_low)\n        @test \u2248(arr_ds, arr_low)\n        @test eltype(arr_low) === eltype(arr_ds)\n        @test eltype(arr_interp) === eltype(arr_ds)\n    end\n\n    test_resample(128, 1000)\n    test_resample(128, 1232)\n    test_resample(128, 255)\n    test_resample(253, 254)\n    test_resample(253, 1001)\n    test_resample(99, 100101)\n\n    \n\n\nend\n\n\n@testset \"Check if resample and interpolate return real result real input\" begin\n    function test_real(s, s_n, s_n2)\n        x = randn(s)\n        y = resample(x, s_n, take_real=false)\n        y2 = resample(x, s_n2, take_real=false)\n        @test all(imag.(y) .< 5e-15)\n        @test all(imag.(y2) .< 5e-14)\n    end\n    \n    test_real((12, 13, 14, 15), (12, 12, 12, 12), (20, 21, 22, 23))\n    test_real((12, 13, 14, 15), (12, 13, 13, 13), (20, 22, 22, 23))\n    test_real((12, 13, 14, 15), (12, 12, 13, 14), (21, 23, 21, 23))\n\n    test_real((7,7), (6,6), (8, 8))\n    test_real(100, 99, 101)\n    test_real(101, 89, 101)\n    test_real(100, 98, 120)\n    test_real(101, 90, 120)\n\n\nend\n\n\n@testset \"FFT sinc resample and upsample together in 2D\" begin\n\n\n    function test_2D(in_s, out_s)\n        x = range(-10.0, 10.0, length=in_s[1] + 1)[1:end-1]\n        y = range(-10.0, 10.0, length=in_s[2] + 1)[1:end-1]'\n\t    arr = abs.(x) .+ abs.(y) .+ sinc.(sqrt.(x .^2 .+ y .^2))\n\t    arr_interp = resample(arr[1:end, 1:end], out_s);\n\t    arr_ds = resample(arr_interp, in_s)\n        @test arr_ds \u2248 arr\n    end\n\n    test_2D((128, 128), (150, 150))\n    test_2D((128, 128), (151, 151))\n    test_2D((129, 129), (150, 150))\n    test_2D((129, 129), (151, 151))\n    \n    test_2D((150, 128), (151, 150))\n    test_2D((128, 128), (151, 153))\n    test_2D((129, 128), (150, 153))\n    test_2D((129, 128), (129, 153))\n\n\n    x = range(-10.0, 10.0, length=129)[1:end-1]\n    x2 = range(-10.0, 10.0, length=130)[1:end-1]\n    x_exact = range(-10.0, 10.0, length=2049)[1:end-1]\n    y = x'\n    y2 = x2'\n    y_exact = x_exact'\n    arr = abs.(x) .+ abs.(y) .+sinc.(sqrt.(x .^2 .+ y .^2))\n    arr2 = abs.(x) .+ abs.(y) .+sinc.(sqrt.(x .^2 .+ y .^2))\n    arr_exact = abs.(x_exact) .+ abs.(y_exact) .+ sinc.(sqrt.(x_exact .^2 .+ y_exact .^2))\n    arr_interp = resample(arr[1:end, 1:end], (131, 131));\n    arr_interp2 = resample(arr[1:end, 1:end], (512, 512));\n    arr_interp3 = resample(arr[1:end, 1:end], (1024, 1024));\n    arr_ds = resample(arr_interp, (128, 128))\n    arr_ds2 = resample(arr_interp, (128, 128))\n    arr_ds23 = resample(arr_interp2, (512, 512))\n    arr_ds3 = resample(arr_interp, (128, 128))\n\n    @test \u2248(arr_ds3, arr)\n    @test \u2248(arr_ds2, arr)\n    @test \u2248(arr_ds, arr)\n    @test \u2248(arr_ds23, arr_interp2)\n\nend\n\n\n\n\n@testset \"FFT sinc resample and upsample together in 2D for a complex signal\" begin\n\n    function test_2D(in_s, out_s)\n    \tx = range(-10.0, 10.0, length=in_s[1] + 1)[1:end-1]\n    \ty = range(-10.0, 10.0, length=in_s[2] + 1)[1:end-1]'\n    \tf(x, y) = 1im * (abs(x) + abs(y) + sinc(sqrt(x ^2 + y ^2)))\n    \tf2(x, y) =  abs(x) + abs(y) + sinc(sqrt((x - 5) ^2 + (y - 5)^2))\n    \n    \tarr = f.(x, y) .+ f2.(x, y)\n    \tarr_interp = resample(arr[1:end, 1:end], out_s);\n    \tarr_ds = resample(arr_interp, in_s)\n        \n        @test eltype(arr) === eltype(arr_ds)\n        @test eltype(arr_interp) === eltype(arr_ds)\n        @test imag(arr) \u2248 imag(arr_ds)\n        @test real(arr) \u2248 real(arr_ds)\n    end\n\n    test_2D((128, 128), (150, 150))\n    test_2D((128, 128), (151, 151))\n    test_2D((129, 129), (150, 150))\n    test_2D((129, 129), (151, 151))\n    \n    test_2D((150, 128), (151, 150))\n    test_2D((128, 128), (151, 153))\n    test_2D((129, 128), (150, 153))\n    test_2D((129, 128), (129, 153))\nend\n\n\n\n@testset \"FFT sinc resample and upsample together in 2D for a purely imaginary signal\" begin\n    function test_2D(in_s, out_s)\n    \tx = range(-10.0, 10.0, length=in_s[1] + 1)[1:end-1]\n    \ty = range(-10.0, 10.0, length=in_s[2] + 1)[1:end-1]'\n    \tf(x, y) = 1im * (abs(x) + abs(y) + sinc(sqrt(x ^2 + y ^2)))\n    \n    \tarr = f.(x, y)\n    \tarr_interp = resample(arr[1:end, 1:end], out_s);\n    \tarr_ds = resample(arr_interp, in_s)\n        \n        @test imag(arr) \u2248 imag(arr_ds)\n        @test all(real(arr_ds) .< 1e-14)\n        @test all(real(arr_interp) .< 1e-14)\n    end \n\n    test_2D((128, 128), (150, 150))\n    test_2D((128, 128), (151, 151))\n    test_2D((129, 129), (150, 150))\n    test_2D((129, 129), (151, 151))\n    \n    test_2D((150, 128), (151, 150))\n    test_2D((128, 128), (151, 153))\n    test_2D((129, 128), (150, 153))\n    test_2D((129, 128), (129, 153))\n\n\nend\n\n\n\n\n\nreturn \n", "meta": {"hexsha": "71459cd9383615cc09ceb48664b6b76297e0759f", "size": 5991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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.8059701493, "max_line_length": 92, "alphanum_fraction": 0.5740277082, "num_tokens": 2354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7790493912634247}}
{"text": "using Yields\nusing Test\n\n@testset \"Yields.jl\" begin\n\n    @testset \"rate types\" begin\n        rs = Rate.([0.1, 0.02], Yields.Continuous())\n        @test rs[1] == Rate(0.1, Yields.Continuous())\n        @test rate(rs[1]) == 0.1\n    end\n\n    @testset \"constructor\" begin\n        @test Yields.Continuous(0.05) == Rate(0.05, Yields.Continuous())\n        @test Yields.Periodic(0.02, 2) == Rate(0.02, Yields.Periodic(2))\n        @test Rate(0.02, 2) == Rate(0.02, Yields.Periodic(2))\n        @test Rate(0.02, Inf) == Rate(0.02, Yields.Continuous())\n    end\n\n    @testset \"rate conversions\" begin\n        m = Rate(0.1, Yields.Periodic(2))\n        @test rate(convert(Yields.Continuous(), m)) \u2248 rate(Rate(0.09758, Yields.Continuous())) atol = 1e-5\n        c = Rate(0.09758, Yields.Continuous())\n        @test convert(Yields.Continuous(), c) == c\n        @test rate(convert(Yields.Periodic(2), c)) \u2248 rate(Rate(0.1, Yields.Periodic(2))) atol = 1e-5\n        @test rate(convert(Yields.Periodic(4), m)) \u2248 rate(Rate(0.09878030638383972, Yields.Periodic(4))) atol = 1e-5\n\n    end\n\n    @testset \"rate equality\" begin\n        a = Yields.Periodic(0.02, 2)\n        b = Yields.Periodic(0.03, 2)\n        c = Yields.Continuous(0.02)\n\n        @test a == a\n        @test a != b\n        @test ~(a \u2248 b)\n        @test (a \u2248 a)\n        @test ~(a \u2248 c)\n\n    end\n\n    @testset \"constant curve and rate -> Constant\" begin\n        yield = Yields.Constant(0.05)\n        rate = Yields.Rate(0.05, Yields.Periodic(1))\n\n        @test Yields.zero(yield, 1) == Rate(0.05, Yields.Periodic(1))\n        @test Yields.zero(Yields.Constant(0.05, Yields.Periodic(2)), 10) == Rate(0.05, Yields.Periodic(2))\n        @test Yields.zero(yield, 5, Yields.Periodic(2)) == convert(Yields.Periodic(2), Rate(0.05, Yields.Periodic(1)))\n\n        @testset \"constant discount time: $time\" for time in [0, 0.5, 1, 10]\n            @test discount(yield, time) \u2248 1 / (1.05)^time\n            @test discount(rate, time) \u2248 1 / (1.05)^time\n            @test discount(rate, 0, time) \u2248 1 / (1.05)^time\n        end\n        @testset \"constant discount scalar time: $time\" for time in [0, 0.5, 1, 10]\n            @test discount(0.05, time) \u2248 1 / (1.05)^time\n        end\n\n        @testset \"constant accumulation scalar time: $time\" for time in [0, 0.5, 1, 10]\n            @test accumulation(0.05, time) \u2248 1 * (1.05)^time\n        end\n\n        @testset \"broadcasting\" begin\n            @test all(discount.(yield, [1, 2, 3]) .== 1 ./ 1.05 .^ (1:3))\n            @test all(accumulation.(yield, [1, 2, 3]) .== 1.05 .^ (1:3))\n        end\n\n        @testset \"constant accumulation time: $time\" for time in [0, 0.5, 1, 10]\n            @test accumulation(yield, time) \u2248 1 * 1.05^time\n            @test accumulation(rate, time) \u2248 1 * 1.05^time\n            @test accumulation(rate, 0, time) \u2248 1 * 1.05^time\n        end\n\n        @testset \"CompoundingFrequency\" begin\n            @testset \"Continuous\" begin\n                cnst = Yields.Constant(Yields.Continuous(0.05))\n                @test accumulation(cnst, 1) == exp(0.05)\n                @test accumulation(cnst, 2) == exp(0.05 * 2)\n                @test discount(cnst, 2) == 1 / exp(0.05 * 2)\n            end\n\n            @testset \"Periodic\" begin\n                p = Yields.Constant(Rate(0.05, Yields.Periodic(2)))\n                @test accumulation(p, 1) == (1 + 0.05 / 2)^(1 * 2)\n                @test accumulation(p, 2) == (1 + 0.05 / 2)^(2 * 2)\n                @test discount(p, 2) == 1 / (1 + 0.05 / 2)^(2 * 2)\n\n            end\n        end\n\n\n        yield_2x = yield + yield\n        yield_add = yield + 0.05\n        add_yield = 0.05 + yield\n        @testset \"constant discount added\" for time in [0, 0.5, 1, 10]\n            @test discount(yield_2x, time) \u2248 1 / (1.1)^time\n            @test discount(yield_add, time) \u2248 1 / (1.1)^time\n            @test discount(add_yield, time) \u2248 1 / (1.1)^time\n        end\n\n        yield_1bps = yield - Yields.Constant(0.04)\n        yield_minus = yield - 0.01\n        minus_yield = 0.05 - Yields.Constant(0.01)\n        @testset \"constant discount subtraction\" for time in [0, 0.5, 1, 10]\n            @test discount(yield_1bps, time) \u2248 1 / (1.01)^time\n            @test discount(yield_minus, time) \u2248 1 / (1.04)^time\n            @test discount(minus_yield, time) \u2248 1 / (1.04)^time\n        end\n    end\n\n    @testset \"short curve\" begin\n        z = Yields.Zero([0.0, 0.05], [1, 2])\n        @test rate(zero(z, 1)) \u2248 0.00\n        @test discount(z, 1) \u2248 1.00\n        @test rate(zero(z, 2)) \u2248 0.05\n\n        # test no times constructor\n        z = Yields.Zero([0.0, 0.05])\n        @test rate(zero(z, 1)) \u2248 0.00\n        @test discount(z, 1) \u2248 1.00\n        @test rate(zero(z, 2)) \u2248 0.05\n    end\n\n    @testset \"Step curve\" begin\n        y = Yields.Step([0.02, 0.05], [1, 2])\n\n        @test rate(y, 0.5) == 0.02\n\n        @test discount(y, 0.0) \u2248 1\n        @test discount(y, 0.5) \u2248 1 / (1.02)^(0.5)\n        @test discount(y, 1) \u2248 1 / (1.02)^(1)\n        @test rate(y, 1) \u2248 0.02\n\n        @test discount(y, 2) \u2248 1 / (1.02) / 1.05\n        @test rate(y, 2) \u2248 0.05\n        @test rate(y, 2.5) \u2248 0.05\n\n        @test discount(y, 2) \u2248 1 / (1.02) / 1.05\n\n        @test discount(y, 1.5) \u2248 1 / (1.02) / 1.05^(0.5)\n\n        @testset \"broadcasting\" begin\n            @test all(discount.(y, [1, 2]) .== [1 / 1.02, 1 / 1.02 / 1.05])\n            @test all(accumulation.(y, [1, 2]) .== [1.02, 1.02 * 1.05])\n        end\n\n        y = Yields.Step([0.02, 0.07])\n        @test rate(y, 0.5) \u2248 0.02\n        @test rate(y, 1) \u2248 0.02\n        @test rate(y, 1.5) \u2248 0.07\n\n    end\n\n    @testset \"Salomon Understanding the Yield Curve Pt 1 Figure 9\" begin\n        maturity = collect(1:10)\n\n        par = [6.0, 8.0, 9.5, 10.5, 11.0, 11.25, 11.38, 11.44, 11.48, 11.5] ./ 100\n        spot = [6.0, 8.08, 9.72, 10.86, 11.44, 11.71, 11.83, 11.88, 11.89, 11.89] ./ 100\n\n        # the forwards for 7+ have been adjusted from the table - perhaps rounding issues are exacerbated \n        # in the text? forwards for <= 6 matched so reasonably confident that the algo is correct\n        # fwd = [6.,10.2,13.07,14.36,13.77,13.1,12.55,12.2,11.97,11.93] ./ 100 # from text\n        fwd = [6.0, 10.2, 13.07, 14.36, 13.77, 13.1, 12.61, 12.14, 12.05, 11.84] ./ 100  # modified\n\n        y = Yields.Par(Rate.(par, Yields.Periodic(1)), maturity)\n\n        @testset \"UTYC Figure 9 par -> spot : $mat\" for mat in maturity\n            @test rate(zero(y, mat)) \u2248 spot[mat] atol = 0.0001\n            @test forward(y, mat - 1) \u2248 Yields.Periodic(fwd[mat], 1) atol = 0.0001\n        end\n\n    end\n\n    @testset \"simple rate and forward\" begin\n        # Risk Managment and Financial Institutions, 5th ed. Appendix B\n\n        maturity = [0.5, 1.0, 1.5, 2.0]\n        zero = [5.0, 5.8, 6.4, 6.8] ./ 100\n        curve = Yields.Zero(zero, maturity)\n\n        @test discount(curve, 0) \u2248 1\n        @test discount(curve, 1) \u2248 1 / (1 + zero[2])\n        @test discount(curve, 2) \u2248 1 / (1 + zero[4])^2\n\n        @test forward(curve, 0.5, 1.0) \u2248 Yields.Periodic(6.6 / 100, 1) atol = 0.001\n        @test forward(curve, 1.0, 1.5) \u2248 Yields.Periodic(7.6 / 100, 1) atol = 0.001\n        @test forward(curve, 1.5, 2.0) \u2248 Yields.Periodic(8.0 / 100, 1) atol = 0.001\n\n        y = Yields.Zero(zero)\n\n        @test discount(y, 1) \u2248 1 / 1.05\n        @test discount(y, 2) \u2248 1 / 1.058^2\n\n        @testset \"broadcasting\" begin\n            @test all(discount.(y, [1, 2]) .\u2248 [1 / 1.05, 1 / 1.058^2])\n            @test all(accumulation.(y, [1, 2]) .\u2248 [1.05, 1.058^2])\n        end\n\n    end\n\n    @testset \"Forward Rates\" begin\n        # Risk Managment and Financial Institutions, 5th ed. Appendix B\n\n        forwards = [0.05, 0.04, 0.03, 0.08]\n        curve = Yields.Forward(forwards, [1, 2, 3, 4])\n\n\n        @testset \"discounts: $t\" for (t, r) in enumerate(forwards)\n            @test discount(curve, t) \u2248 reduce((v, r) -> v / (1 + r), forwards[1:t]; init = 1.0)\n        end\n\n        # test constructor without times\n        curve = Yields.Forward(forwards)\n\n        @testset \"discounts: $t\" for (t, r) in enumerate(forwards)\n            @test discount(curve, t) \u2248 reduce((v, r) -> v / (1 + r), forwards[1:t]; init = 1.0)\n        end\n\n        @test accumulation(curve, 0, 1) \u2248 1.05\n        @test accumulation(curve, 1, 2) \u2248 1.04\n        @test accumulation(curve, 0, 2) \u2248 1.04 * 1.05\n\n        @testset \"broadcasting\" begin\n            @test all(accumulation.(curve, [1, 2]) .\u2248 [1.05, 1.04 * 1.05])\n            @test all(discount.(curve, [1, 2]) .\u2248 1 ./ [1.05, 1.04 * 1.05])\n        end\n\n        # addition / subtraction\n        @test discount(curve + 0.1, 1) \u2248 1 / 1.15\n        @test discount(curve - 0.03, 1) \u2248 1 / 1.02\n\n\n\n        @testset \"with specified timepoints\" begin\n            i = [0.0, 0.05]\n            times = [0.5, 1.5]\n            y = Yields.Forward(i, times)\n            @test discount(y, 0.5) \u2248 1 / 1.0^0.5\n            @test discount(y, 1.5) \u2248 1 / 1.0^0.5 / 1.05^1\n\n        end\n\n    end\n\n    @testset \"forwardcurve\" begin\n        maturity = [0.5, 1.0, 1.5, 2.0]\n        zero = [5.0, 5.8, 6.4, 6.8] ./ 100\n        curve = Yields.Zero(zero, maturity)\n\n        fwd = Yields.ForwardStarting(curve, 1.0)\n        @test discount(fwd, 0) \u2248 1\n        @test discount(fwd, 0.5) \u2248 discount(curve, 1, 1.5)\n        @test discount(fwd, 1) \u2248 discount(curve, 1, 2)\n        @test accumulation(fwd, 1) \u2248 accumulation(curve, 1, 2)\n    end\n\n    @testset \"base + spread\" begin\n        riskfree_maturities = [0.5, 1.0, 1.5, 2.0]\n        riskfree = [5.0, 5.8, 6.4, 6.8] ./ 100 # spot rates\n\n        spread_maturities = [0.5, 1.0, 1.5, 3.0] # different maturities\n        spread = [1.0, 1.8, 1.4, 1.8] ./ 100 # spot spreads\n\n        rf_curve = Yields.Zero(riskfree, riskfree_maturities)\n        spread_curve = Yields.Zero(spread, spread_maturities)\n\n        yield = rf_curve + spread_curve\n\n        @test discount(yield, 1.0) \u2248 1 / (1 + riskfree[2] + spread[2])^1\n        @test discount(yield, 1.5) \u2248 1 / (1 + riskfree[3] + spread[3])^1.5\n    end\n\n    @testset \"actual cmt treasury\" begin\n        # Fabozzi 5-5,5-6\n        cmt = [5.25, 5.5, 5.75, 6.0, 6.25, 6.5, 6.75, 6.8, 7.0, 7.1, 7.15, 7.2, 7.3, 7.35, 7.4, 7.5, 7.6, 7.6, 7.7, 7.8] ./ 100\n        mats = collect(0.5:0.5:10.0)\n        curve = Yields.CMT(cmt, mats)\n        targets = [5.25, 5.5, 5.76, 6.02, 6.28, 6.55, 6.82, 6.87, 7.09, 7.2, 7.26, 7.31, 7.43, 7.48, 7.54, 7.67, 7.8, 7.79, 7.93, 8.07] ./ 100\n        target_periodicity = fill(2, length(mats))\n        target_periodicity[2] = 1 # 1 year is a no-coupon, BEY yield, the rest are semiannual BEY\n        @testset \"Fabozzi bootstrapped rates\" for (r, mat, target, tp) in zip(cmt, mats, targets, target_periodicity)\n            @test rate(zero(curve, mat, Yields.Periodic(tp))) \u2248 target atol = 0.0001\n        end\n\n        # Hull, problem 4.34\n        adj = ((1 + 0.051813 / 2)^2 - 1) * 100\n        cmt = [4.0816, adj, 5.4986, 5.8620] ./ 100\n        mats = [0.5, 1.0, 1.5, 2.0]\n        curve = Yields.CMT(cmt, mats)\n        targets = [4.0405, 5.1293, 5.4429, 5.8085] ./ 100\n        @testset \"Hull bootstrapped rates\" for (r, mat, target) in zip(cmt, mats, targets)\n            @test rate(zero(curve, mat, Yields.Continuous())) \u2248 target atol = 0.001\n        end\n\n        # test that showing the curve doesn't error\n        @test isnothing(show(devnull, curve))\n\n        #     # https://www.federalreserve.gov/pubs/feds/2006/200628/200628abs.html\n        #     # 2020-04-02 data\n        #     cmt = [0.0945,0.2053,0.4431,0.7139,0.9724,1.2002,1.3925,1.5512,1.6805,1.7853,1.8704,1.9399,1.9972,2.045,2.0855,2.1203,2.1509,2.1783,2.2031,2.2261,2.2477,2.2683,2.2881,2.3074,2.3262,2.3447,2.3629,2.3809,2.3987,2.4164] ./ 100\n        #     mats = collect(1:30)\n        #     curve = Yields.USCMT(cmt,mats)\n        #     target = [0.0945,0.2053,0.444,0.7172,0.9802,1.2142,1.4137,1.5797,1.7161,1.8275,1.9183,1.9928,2.0543,2.1056,2.1492,2.1868,2.2198,2.2495,2.2767,2.302,2.3261,2.3494,2.372,2.3944,2.4167,2.439,2.4614,2.4839,2.5067,2.5297] ./ 100\n\n        #     @testset \"FRB data\" for (t,mat,target) in zip(1:length(mats),mats,target)\n        #         @show mat\n        #         if mat >= 1\n        #             @test rate(zero(curve,mat, Yields.Continuous())) \u2248 target[mat] atol=0.001\n        #         end\n        #     end\n    end\n\n    @testset \"OIS\" begin\n        ois = [1.8, 2.0, 2.2, 2.5, 3.0, 4.0] ./ 100\n        mats = [1 / 12, 1 / 4, 1 / 2, 1, 2, 5]\n        curve = Yields.OIS(ois, mats)\n        targets = [0.017987, 0.019950, 0.021880, 0.024693, 0.029994, 0.040401]\n        @testset \"bootstrapped rates\" for (r, mat, target) in zip(ois, mats, targets)\n            @test rate(zero(curve, mat, Yields.Continuous())) \u2248 target atol = 0.001\n        end\n    end\n\n    @testset \"InstrumentQuotes\" begin\n\n        maturities = [1.3, 2.7]\n        prices = [1.1, 0.8]\n        zcq = Yields.ZeroCouponQuote.(prices, maturities)\n        @test isa(first(zcq), Yields.ZeroCouponQuote)\n\n        @test_throws DimensionMismatch Yields.ZeroCouponQuote.([1.3, 2.4, 0.9], maturities)\n\n        rates = [0.4, -0.7]\n        swq = Yields.SwapQuote.(rates, maturities, 3)\n        @test first(swq).frequency == 3\n\n        @test_throws DimensionMismatch Yields.SwapQuote.([1.3, 2.4, 0.9], maturities, 3)\n        @test_throws DomainError Yields.SwapQuote.(rates, maturities, 0)\n        @test_throws DomainError Yields.SwapQuote.(rates, maturities, -2)\n\n        rates = [0.4, -0.7]\n        bbq = Yields.BulletBondQuote.(rates, prices, maturities, 3)\n        @test first(bbq).frequency == 3\n        @test first(bbq).yield == first(rates)\n\n\n        @test_throws DimensionMismatch Yields.BulletBondQuote.([1.3, 2.4, 0.9], prices, maturities, 3)\n        @test_throws DimensionMismatch Yields.BulletBondQuote.(rates, prices, [4.3, 5.6, 4.4, 4.4], 3)\n        @test first(Yields.BulletBondQuote.(rates, [5.7], maturities, 3)).price == 5.7\n        @test_throws DomainError Yields.BulletBondQuote.(rates, prices, maturities, 0)\n        @test_throws DomainError Yields.BulletBondQuote.(rates, prices, maturities, -4)\n\n    end\n\n    @testset \"SmithWilson\" begin\n\n        ufr = 0.03\n        \u03b1 = 0.1\n        u = [5.0, 7.0]\n        qb = [2.3, -1.2]\n\n        # Basic behaviour\n        sw = Yields.SmithWilson(u, qb; ufr = ufr, \u03b1 = \u03b1)\n        @test sw.ufr == ufr\n        @test sw.\u03b1 == \u03b1\n        @test sw.u == u\n        @test sw.qb == qb\n        @test_throws DomainError Yields.SmithWilson(u, [2.4, -3.4, 8.9], ufr = ufr, \u03b1 = \u03b1)\n\n        # Empty u and Qb should result in a flat yield curve\n        # Use this to test methods expected from <:AbstractYieldCurve\n        # Only discount and zero are explicitly implemented, so the others should follow automatically\n        sw_flat = Yields.SmithWilson(Float64[], Float64[], ufr = ufr, \u03b1 = \u03b1)\n        @test discount(sw_flat, 10.0) == exp(-ufr * 10.0)\n        @test accumulation(sw_flat, 10.0) \u2248 exp(ufr * 10.0)\n        @test rate(convert(Yields.Continuous(), zero(sw_flat, 8.0))) \u2248 ufr\n        @test discount.(sw_flat, [5.0, 10.0]) \u2248 exp.(-ufr .* [5.0, 10.0])\n        @test rate(convert(Yields.Continuous(), forward(sw_flat, 5.0, 8.0))) \u2248 ufr\n\n        # A trivial Qb vector (=0) should result in a flat yield curve\n        ufr_curve = Yields.SmithWilson(u, [0.0, 0.0], ufr = ufr, \u03b1 = \u03b1)\n        @test discount(ufr_curve, 10.0) == exp(-ufr * 10.0)\n\n        # A single payment at time 4, zero interest\n        curve_with_zero_yield = Yields.SmithWilson([4.0], reshape([1.0], 1, 1), [1.0], ufr = ufr, \u03b1 = \u03b1)\n        @test discount(curve_with_zero_yield, 4.0) == 1.0\n\n        # In the long end it's still just UFR\n        @test rate(convert(Yields.Continuous(), forward(curve_with_zero_yield, 1000.0, 2000.0))) \u2248 ufr\n\n        # Three maturities have known discount factors\n        times = [1.0, 2.5, 5.6]\n        prices = [0.9, 0.7, 0.5]\n        cfs = [1 0 0\n            0 1 0\n            0 0 1]\n\n        curve_three = Yields.SmithWilson(times, cfs, prices, ufr = ufr, \u03b1 = \u03b1)\n        @test transpose(cfs) * discount.(curve_three, times) \u2248 prices\n\n        # Two cash flows with payments at three times\n        prices = [1.0, 0.9]\n        cfs = [0.1 0.1\n            1.0 0.1\n            0.0 1.0]\n        curve_nondiag = Yields.SmithWilson(times, cfs, prices, ufr = ufr, \u03b1 = \u03b1)\n        @test transpose(cfs) * discount.(curve_nondiag, times) \u2248 prices\n\n        # Round-trip zero coupon quotes\n        zcq_times = [1.2, 4.5, 5.6]\n        zcq_prices = [1.0, 0.9, 1.2]\n        zcq = Yields.ZeroCouponQuote.(zcq_prices, zcq_times)\n        sw_zcq = Yields.SmithWilson(zcq, ufr = ufr, \u03b1 = \u03b1)\n        @testset \"ZeroCouponQuotes round-trip\" for idx = 1:length(zcq_times)\n            @test discount(sw_zcq, zcq_times[idx]) \u2248 zcq_prices[idx]\n        end\n\n        # uneven frequencies\n        swq_maturities = [1.2, 2.5, 3.6]\n        swq_interests = [-0.02, 0.3, 0.04]\n        frequency = [2, 1, 2]\n        swq = Yields.SwapQuote.(swq_interests, swq_maturities, frequency)\n        swq_times = 0.5:0.5:3.5   # Maturities are rounded down to multiples of 1/frequency, [1.0, 2.5, 3.5]\n        swq_payments = [\n            -0.01 0.3 0.02\n            0.99 0 0.02\n            0 0.3 0.02\n            0 0 0.02\n            0 1.3 0.02\n            0 0 0.02\n            0 0 1.02\n        ]\n\n        # Round-trip swap quotes\n        swq_maturities = [1.2, 2.5, 3.6]\n        swq_interests = [-0.02, 0.3, 0.04]\n        frequency = 2\n        swq = Yields.SwapQuote.(swq_interests, swq_maturities, frequency)\n        swq_times = 0.5:0.5:3.5   # Maturities are rounded down to multiples of 1/frequency, [1.0, 2.5, 3.5]\n        swq_payments = [-0.01 0.15 0.02\n            0.99 0.15 0.02\n            0.0 0.15 0.02\n            0.0 0.15 0.02\n            0.0 1.15 0.02\n            0.0 0.0 0.02\n            0.0 0.0 1.02]\n        sw_swq = Yields.SmithWilson(swq, ufr = ufr, \u03b1 = \u03b1)\n        @testset \"SwapQuotes round-trip\" for swapIdx = 1:length(swq_interests)\n            @test sum(discount.(sw_swq, swq_times) .* swq_payments[:, swapIdx]) \u2248 1.0\n        end\n\n        # Round-trip bullet bond quotes (reuse data from swap quotes)\n        bbq_prices = [1.3, 0.1, 4.5]\n        bbq = Yields.BulletBondQuote.(swq_interests, bbq_prices, swq_maturities, frequency)\n        sw_bbq = Yields.SmithWilson(bbq, ufr = ufr, \u03b1 = \u03b1)\n        @testset \"BulletBondQuotes round-trip\" for bondIdx = 1:length(swq_interests)\n            @test sum(discount.(sw_bbq, swq_times) .* swq_payments[:, bondIdx]) \u2248 bbq_prices[bondIdx]\n        end\n\n        @testset \"SW ForwardStarting\" begin\n            fwd_time = 1.0\n            fwd = Yields.ForwardStarting(sw_swq, fwd_time)\n\n            @test discount(fwd, 3.7) \u2248 discount(sw_swq, fwd_time, fwd_time + 3.7)\n        end\n\n        # EIOPA risk free rate (no VA), 31 August 2021.\n        # https://www.eiopa.europa.eu/sites/default/files/risk_free_interest_rate/eiopa_rfr_20210831.zip\n        eiopa_output_qb = [-0.59556534586390800\n            -0.07442224713453920\n            -0.34193181987682400\n            1.54054875814153000\n            -2.15552046042343000\n            0.73559290752221900\n            1.89365225129089000\n            -2.75927773116240000\n            2.24893737130629000\n            -1.51625404117395000\n            0.19284859623817400\n            1.13410725406271000\n            0.00153268224642171\n            0.00147942301778158\n            -1.85022125156483000\n            0.00336230229850928\n            0.00324546553910162\n            0.00313268874430658\n            0.00302383083427276\n            1.36047951448615000]\n        eiopa_output_u = 1:20\n        eiopa_ufr = log(1.036)\n        eiopa_\u03b1 = 0.133394\n        sw_eiopa_expected = Yields.SmithWilson(eiopa_output_u, eiopa_output_qb; ufr = eiopa_ufr, \u03b1 = eiopa_\u03b1)\n\n        eiopa_eurswap_maturities = [1:12; 15; 20]\n        eiopa_eurswap_rates = [-0.00615, -0.00575, -0.00535, -0.00485, -0.00425, -0.00375, -0.003145,\n            -0.00245, -0.00185, -0.00125, -0.000711, -0.00019, 0.00111, 0.00215]   # Reverse engineered from output curve. This is the full precision of market quotes.\n        eiopa_eurswap_quotes = Yields.SwapQuote.(eiopa_eurswap_rates, eiopa_eurswap_maturities, 1)\n        sw_eiopa_actual = Yields.SmithWilson(eiopa_eurswap_quotes, ufr = eiopa_ufr, \u03b1 = eiopa_\u03b1)\n\n        @testset \"Match EIOPA calculation\" begin\n            @test sw_eiopa_expected.u \u2248 sw_eiopa_actual.u\n            @test sw_eiopa_expected.qb \u2248 sw_eiopa_actual.qb\n        end\n    end\n\nend\n", "meta": {"hexsha": "d6a27ecf23f45753245f1fab847f08b03c8da036", "size": 20315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaActuary/Yields.jl", "max_stars_repo_head_hexsha": "18c7d521b531a4eac18bb05091cecc2150440572", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-06T12:03:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T13:42:24.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "JuliaActuary/Yields.jl", "max_issues_repo_head_hexsha": "18c7d521b531a4eac18bb05091cecc2150440572", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2020-10-02T09:51:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:36:38.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "JuliaActuary/Yields.jl", "max_forks_repo_head_hexsha": "18c7d521b531a4eac18bb05091cecc2150440572", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-28T22:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T19:46:45.000Z", "avg_line_length": 40.1482213439, "max_line_length": 237, "alphanum_fraction": 0.5549101649, "num_tokens": 7815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7790493895556002}}
{"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": "using Replay\n\ninstructions = raw\"\"\"\nusing OhMyREPL\n\nusing LinearAlgebra\nusing Printf\nusing Statistics\n\nusing DataFrames\nusing RDatasets\nusing StatsPlots\n\n# use UnicodePlots.jl as backend\nunicodeplots();\n\niris = dataset(\"datasets\", \"iris\");\n@show names(iris);\nN = size(iris, 1)\n@show names(iris);\n# Execute PCA\nX = Matrix(select(iris, Not(:Species)))\nX .= X .- mean(X, dims=1)\n\u03a3 = (X' * X)/N # will be the covariance matrix for iris dataset\ne = eigen(\u03a3, sortby = -);\n# display  eigen values in descending order\ne.values\n# eigen vectors\ne.vectors\n\n@printf \"1st contribution ratio = %.2f percent\\n\" 100e.values[1]/sum(e.values)\n@printf \"2nd contribution ratio = %.2f percent\\n\" 100e.values[2]/sum(e.values)\n\n# Visualize the reduced data via PCA\ntopk = 2;\nreduced_data = DataFrame(X * e.vectors[:, 1:topk], [:X, :Y]);\n@df reduced_data scatter(:X, :Y, group=iris.Species)\n\"\"\"\n\nreplay(instructions, use_ghostwriter=true, julia_project=@__DIR__)\n", "meta": {"hexsha": "0a3861c25b34617696e3e12332e2924faf32e1f3", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/iris/app.jl", "max_stars_repo_name": "AtelierArith/Replay.jl", "max_stars_repo_head_hexsha": "fc1652434fa5270c4199784704120a7a9e2923ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-11-17T08:32:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:31:51.000Z", "max_issues_repo_path": "examples/iris/app.jl", "max_issues_repo_name": "AtelierArith/Replay.jl", "max_issues_repo_head_hexsha": "fc1652434fa5270c4199784704120a7a9e2923ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-11-16T17:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T06:33:39.000Z", "max_forks_repo_path": "examples/iris/app.jl", "max_forks_repo_name": "AtelierArith/Replay.jl", "max_forks_repo_head_hexsha": "fc1652434fa5270c4199784704120a7a9e2923ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-17T08:34:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T13:21:32.000Z", "avg_line_length": 22.9024390244, "max_line_length": 78, "alphanum_fraction": 0.7156549521, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7790493862170674}}
{"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\ud835\udca9(\u03bc, \u03c3) = 1 / (\u03c3 * \u221a(2\u03c0)) * exp.(-0.5 * ((x .- \u03bc) / \u03c3) .^ 2)\n\nx = LinRange(-5, 5, 500);\ny = hcat(\ud835\udca9(0, \u221a0.2), \ud835\udca9(0, \u221a1), \ud835\udca9(0, \u221a5), \ud835\udca9(-2, \u221a0.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": "using ValidatedNumerics, ValidatedNumerics.RootFinding\nusing Test\n\n@testset \"Bisection tests\" begin\n    @testset \"Single variable\" begin\n        f(x) = sin(x) + cos(x/2) + x/5\n\n        roots = bisection(f, -\u221e..\u221e, tolerance=1e-3)\n        roots2 = [root.interval for root in roots]\n\n        @test roots2 ==  [  Interval(-0.8408203124999999, -0.8398437499999999),\n                            Interval(3.6425781249999996, 3.6435546874999996),\n                            Interval(6.062499999999999, 6.063476562499999)\n                         ]\n\n    end\n\n    @testset \"Two variables\" begin\n        @intervalbox g(x, y) = (x^2 + y^2 - 1, y - x)\n\n        X = (-\u221e..\u221e) \u00d7 (-\u221e..\u221e)\n        roots = bisection(g, X, tolerance=1e-3)\n        roots2 = [root.interval for root in roots]\n        \n        @test roots2 == [IntervalBox(Interval(-0.7080078124999999, -0.7070312499999999), Interval(-0.7080078124999999, -0.7070312499999999)),\n IntervalBox(Interval(-0.7080078124999999, -0.7070312499999999), Interval(-0.7070312499999999, -0.7060546874999999)),\n IntervalBox(Interval(-0.7070312499999999, -0.7060546874999999), Interval(-0.7080078124999999, -0.7070312499999999)),\n IntervalBox(Interval(0.7060546874999999, 0.7070312499999999), Interval(0.7070312499999999, 0.7080078124999999)),\n IntervalBox(Interval(0.7070312499999999, 0.7080078124999999), Interval(0.7060546874999999, 0.7070312499999999)),\n IntervalBox(Interval(0.7070312499999999, 0.7080078124999999), Interval(0.7070312499999999, 0.7080078124999999))]\n\n    end\n\nend\n", "meta": {"hexsha": "a59a4b4a44d3661927fc000ed7d975dfcb0da6b5", "size": 1513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bisection.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": "test/bisection.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": "test/bisection.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": 43.2285714286, "max_line_length": 141, "alphanum_fraction": 0.6688697951, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180243, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7789562434028476}}
{"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\u00e1nchez 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 \u0394b 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 \u0394b, 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: \u03b8 ~ N(0, \u03c30^2) with \u03c30 = 10.0\n    # Likelihood:  x ~ N(\u03b8, \u03c3^2) with \u03c3 = 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    \u03b20 = zeros(2)\n    \u03c30 = 10.0\n    \u03ba0 = inv(\u03c30^2)\n    pri = MvNormalCanon(\u03b20, \u03ba0)\n\n    # likelihood model\n    \u03c3 = 1.0\n    g = IsoGaussModel(\u03c3)\n\n    # H0: single component\n    pp0 = posterior(pri, suffstats(g, X))\n    \u0394b0 = logpar(pp0) - logpar(pri)\n\n    # H1: two components:\n    pp1 = posterior(pri, suffstats(g, X1))\n    pp2 = posterior(pri, suffstats(g, X2))\n    \u0394b1 = (logpar(pp1) - logpar(pri)) + (logpar(pp2) - logpar(pri))\n\n    return (\u0394b0, \u0394b1)\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    \u0394b0, \u0394b1 = simulate(r, n)\n    @printf(\"With r = %5.1f:  H0.\u0394b = %8.2f,  H1.\u0394b = %8.2f\\n\", r, \u0394b0, \u0394b1)\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!(\u03bc,\u03a3;kw...)\n    for i=1:3\n        plot!([tuple((i*sqrt(\u03a3)*[cos(t),sin(t)]+\u03bc)...) for t in range(0,stop=2\u03c0,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\u2081,X\u2082,\u03bc\u2080,\u03a3\u2080,\u03bc\u2081,\u03a3\u2081,\u03a0)\n    scatter(X\u2081,X\u2082;fillalpha=0.5,markerstrokewidth=0.5,\n        marker_z=\u03a0,mc=ColorGradient([:lightblue,:orange]),\n        colorbar=:false)\n    ellipse!(\u03bc\u2080,\u03a3\u2080,fillcolor=:lightblue)\n    ellipse!(\u03bc\u2081,\u03a3\u2081,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\u03b1 = 0.4\n\ud835\udca9\u2080 = MvNormal([1,1],[2.0 1.0; 1.0 2.0])\n\ud835\udca9\u2081 = MvNormal([3.0,7.0],[1.5 0; 0 0.5])\nX\u2081 = zeros(n)\nX\u2082 = zeros(n)\nZ = zeros(Bool,n)\nfor i=1:n\n    Z[i] = rand(Bernoulli(\u03b1))\n    X\u2081[i],X\u2082[i] = Z[i] ? rand(\ud835\udca9\u2081) : rand(\ud835\udca9\u2080)\nend\n\n\u03b1 = 0.6\n\u03bc\u2080 = [3.0,3.0]\n\u03bc\u2081 = [1.0,6.0]\n\u03a3\u2080 = 1.0*Matrix(I, 2, 2)\n\u03a3\u2081 = 1.0*Matrix(I, 2, 2)\nmixtureplot(X\u2081,X\u2082,\u03bc\u2080,\u03a3\u2080,\u03bc\u2081,\u03a3\u2081)\n\n\u03a0 = [\u03b1*pdf(MvNormal(\u03bc\u2081,\u03a3\u2081),[x\u2081,x\u2082]) /\n       ((1-\u03b1)*pdf(MvNormal(\u03bc\u2080,\u03a3\u2080),[x\u2081,x\u2082]) +\n        \u03b1*pdf(MvNormal(\u03bc\u2081,\u03a3\u2081),[x\u2081,x\u2082])) for (x\u2081,x\u2082) in zip(X\u2081,X\u2082)];\n\n\u03b1 = sum(\u03a0)/n\n\u03bc\u2080 = [(1 .- \u03a0) \u22c5 X\u2081, (1 .- \u03a0) \u22c5 X\u2082] / sum(1 .- \u03a0)\n\u03bc\u2081 = [\u03a0 \u22c5 X\u2081, \u03a0 \u22c5 X\u2082] / sum(\u03a0)\n\u03a3\u2080 = Matrix(Hermitian(sum((1-\u03c0)*([x\u2081,x\u2082] - \u03bc\u2080) * ([x\u2081,x\u2082] - \u03bc\u2080)' for (x\u2081,x\u2082,\u03c0) in zip(X\u2081,X\u2082,\u03a0))/sum(1 .- \u03a0)))\n\u03a3\u2081 = Matrix(Hermitian(sum(\u03c0*([x\u2081,x\u2082] - \u03bc\u2081) * ([x\u2081,x\u2082] - \u03bc\u2081)' for (x\u2081,x\u2082,\u03c0) in zip(X\u2081,X\u2082,\u03a0))/sum(\u03a0)))\n\u03a0 = [\u03b1*pdf(MvNormal(\u03bc\u2081,\u03a3\u2081),[x\u2081,x\u2082]) /\n       ((1-\u03b1)*pdf(MvNormal(\u03bc\u2080,\u03a3\u2080),[x\u2081,x\u2082]) +\n        \u03b1*pdf(MvNormal(\u03bc\u2081,\u03a3\u2081),[x\u2081,x\u2082])) for (x\u2081,x\u2082) in zip(X\u2081,X\u2082)];\n\nmixtureplot(X\u2081,X\u2082,\u03bc\u2080,\u03a3\u2080,\u03bc\u2081,\u03a3\u2081,\u03a0)\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\u2033 + cx\u2032 + kx + \u03bcx\u00b3 = F\u2080cos(\u03c9t)\n```\n\"\"\"\nBase.@kwdef mutable struct Duffing\n    m::Float64 = 1.0\n    c::Float64 = 0.01\n    k::Float64 = 2.0\n    \u03bc::Float64 = 1\n    F\u2080::Float64 = 0.05\n    \u03c9::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\u2032 = u[2]\n    f = p.F\u2080 * cos(p.\u03c9 * t)\n    # Use a static vector (SVector) for speed; it's not necessary for any other reason\n    return SVector(x\u2032, (f - p.c * x\u2032 - p.k * x - p.\u03bc * 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 \u03bcs (0.00% GC)\n#   median time:      75.700 \u03bcs (0.00% GC)\n#   mean time:        90.955 \u03bcs (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": "# 1D diffusion problem\n\n# Packages and inclusions\nusing ModelingToolkit,DiffEqOperators,LinearAlgebra,Test,OrdinaryDiffEq, DomainSets\nusing ModelingToolkit: Differential\n\n# Tests\n@testset \"Test 00: Dt(u(t,x)) ~ Dxx(u(t,x))\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * cos.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)\n    Dxx = Differential(x)^2\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ cos(x),\n           u(t,0) ~ exp(-t),\n           u(t,Float64(\u03c0)) ~ -exp(-t)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,Float64(\u03c0))]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = range(0.0,Float64(\u03c0),length=30)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n    discretization_edge = MOLFiniteDifference([x=>dx],t;grid_align=edge_align)\n    # Explicitly specify order of centered difference\n    discretization_centered = MOLFiniteDifference([x=>dx],t;centered_order=order)\n    # Higher order centered difference\n    discretization_centered_order4 = MOLFiniteDifference([x=>dx],t;centered_order=4)\n\n    for disc in [discretization, discretization_edge, discretization_centered, discretization_centered_order4]\n        # Convert the PDE problem into an ODE problem\n        prob = discretize(pdesys,disc)\n\n        # Solve ODE problem\n        sol = solve(prob,Tsit5(),saveat=0.1)\n\n        if disc.grid_align == center_align\n            x = dx[2:end-1]\n        else\n            x = (dx[1:end-1]+dx[2:end])/2\n        end\n        t = sol.t\n\n        # Test against exact solution\n        for i in 1:length(sol)\n            exact = u_exact(x, t[i])\n            u_approx = sol.u[i]\n            @test all(isapprox.(u_approx, exact, atol=0.01))\n        end\n    end\nend\n\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    Dt = Differential(t)\n    Dxx = Differential(x)^2\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 \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)],[D=>10.0])\n\n    # Method of lines discretization\n    dx = 0.1\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    # Test\n    n = size(sol,1)\n    t_f = size(sol,3)\n    @test sol[end] \u2248 zeros(n) atol = 0.001;\nend\n\n# @test_set \"Test 02: Dt(u(t,x)) ~ Dx(D(t,x))*Dx(u(t,x))+D(t,x)*Dxx(u(t,x))\" begin\n@test_broken begin\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..) D(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    D = (t,x) -> 0.999 + 0.001 * t * x\n    DxD = expand_derivatives(Dx(D(t,x)))\n\n    # 1D PDE and boundary conditions\n\n    eq  = [ Dt(u(t,x)) ~ DxD*Dx(u(t,x))+D(t,x)*Dxx(u(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\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = 0.1\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    # Test\n    n = size(sol,1)\n    t_f = size(sol,3)\n    @test_broken sol[:,1,t_f] \u2248 zeros(n) atol=0.01;\nend\n\n@testset \"Test 03: Dt(u(t,x)) ~ Dxx(u(t,x)), homogeneous Neumann BCs\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * cos.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ cos(x),\n           Dx(u(t,0)) ~ 0,\n           Dx(u(t,Float64(pi))) ~ 0]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,Float64(pi))]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = range(0.0,Float64(\u03c0),length=300)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n    discretization_edge = MOLFiniteDifference([x=>dx],t;grid_align=center_align)\n\n    # Convert the PDE problem into an ODE problem\n    for disc in [discretization, discretization_edge]\n        prob = discretize(pdesys,disc)\n\n        # Solve ODE problem\n        sol = solve(prob,Tsit5(),saveat=0.1)\n\n        if disc.grid_align == center_align\n            x_sol = dx[2:end-1]\n        else\n            x_sol = (dx[1:end-1]+dx[2:end])/2\n        end\n        t_sol = sol.t\n\n        # Test against exact solution\n        for i in 1:length(sol)\n            exact = u_exact(x_sol, t_sol[i])\n            u_approx = sol.u[i]\n            @test all(isapprox.(u_approx, exact, atol=0.01))\n            @test sum(u_approx) \u2248 0 atol=1e-10\n        end\n    end\nend\n\n@testset \"Test 03a: Dt(u(t,x)) ~ Dxx(u(t,x)), Neumann BCs\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * sin.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ sin(x),\n           Dx(u(t,0)) ~ exp(-t),\n           Dx(u(t,Float64(pi))) ~ -exp(-t)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,Float64(pi))]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = range(0.0,Float64(\u03c0),length=30)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n    discretization_edge = MOLFiniteDifference([x=>dx],t;grid_align=edge_align)\n\n    # Convert the PDE problem into an ODE problem\n    for disc \u2208 [discretization, discretization_edge]\n        prob = discretize(pdesys,disc)\n\n        # Solve ODE problem\n        sol = solve(prob,Tsit5(),saveat=0.1)\n\n        if disc.grid_align == center_align\n            x = dx[2:end-1]\n        else\n            x = (dx[1:end-1]+dx[2:end])/2\n        end\n        t = sol.t\n\n        # Test against exact solution\n        # exact integral based on Neumann BCs\n        integral_u_exact = t -> sum(sol.u[1] * dx[2]) + 2 * (exp(-t) - 1)\n        for i in 1:length(sol)\n            exact = u_exact(x, t[i])\n            u_approx = sol.u[i]\n            @test all(isapprox.(u_approx, exact, atol=0.01))\n            # test mass conservation\n            integral_u_approx = sum(u_approx * dx[2])\n            @test integral_u_exact(t[i]) \u2248 integral_u_approx atol=1e-13\n        end\n    end\nend\n\n@testset \"Test 04: Dt(u(t,x)) ~ Dxx(u(t,x)), Neumann + Dirichlet BCs\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * sin.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ sin(x),\n           u(t,0) ~ 0.0,\n           Dx(u(t,Float64(pi))) ~ -exp(-t)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,Float64(pi))]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = range(0.0,Float64(\u03c0),length=30)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n    x = dx[2:end-1]\n    t = sol.t\n\n    # Test against exact solution\n    for i in 1:length(sol)\n        exact = u_exact(x, t[i])\n        u_approx = sol.u[i]\n        @test all(isapprox.(u_approx, exact, atol=0.01))\n    end\nend\n\n@testset \"Test 05: Dt(u(t,x)) ~ Dxx(u(t,x)), Robin BCs\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * sin.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ sin(x),\n           u(t,-1.0) + 3Dx(u(t,-1.0)) ~ exp(-t) * (sin(-1.0) + 3cos(-1.0)),\n           4u(t,1.0) + Dx(u(t,1.0)) ~ exp(-t) * (4sin(1.0) + cos(1.0))]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(-1.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = 0.01\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n    discretization_edge = MOLFiniteDifference([x=>dx],t;grid_align=edge_align)\n\n    for disc \u2208 [discretization, discretization_edge]\n        # Convert the PDE problem into an ODE problem\n        prob = discretize(pdesys,disc)\n\n        # Solve ODE problem\n        sol = solve(prob,Tsit5(),saveat=0.1)\n        x = (-1:dx:1)\n        if disc.grid_align == center_align\n            x = x[2:end-1]\n        else\n            x = (x[1:end-1].+x[2:end])/2\n        end\n        t = sol.t\n\n        # Test against exact solution\n        for i in 1:length(sol)\n            exact = u_exact(x, t[i])\n            u_approx = sol.u[i]\n            @test all(isapprox.(u_approx, exact, atol=0.1))\n        end\n    end\nend\n\n\n@testset \"Test 06: Dt(u(t,x)) ~ Dxx(u(t,x)), time-dependent Robin BCs\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * sin.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ sin(x),\n          t^2 * u(t,-1.0) + 3Dx(u(t,-1.0)) ~ exp(-t) * (t^2 * sin(-1.0) + 3cos(-1.0)),\n          4u(t,1.0) + t * Dx(u(t,1.0)) ~ exp(-t) * (4sin(1.0) + t * cos(1.0))]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(-1.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = 0.01\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Rodas4(),reltol=1e-6,saveat=0.1)\n\n    x = (-1:dx:1)\n    t = sol.t\n\n    # Test against exact solution\n    for i in 1:length(sol)\n       exact = u_exact(x, t[i])\n       # Due to structural simplification\n       # [u2 -> u(n-1), u(1), u(n)]\n       # Will be fixed by sol[u]\n       u_approx = [sol.u[i][end-1];sol.u[i][1:end-2];sol.u[i][end]]\n       @test all(isapprox.(u_approx, exact, atol=0.01))\n    end\nend\n\n@testset \"Test 07: Dt(u(t,r)) ~ 1/r^2 * Dr(r^2 * Dr(u(t,r))) (Spherical Laplacian)\" begin\n    # Method of Manufactured Solutions\n    # general solution of the spherical Laplacian equation\n    # satisfies Dr(u(t,0)) = 0\n    u_exact = (r,t) -> exp.(-t) * sin.(r) ./ r\n\n    # Parameters, variables, and derivatives\n    @parameters t r\n    @variables u(..)\n    Dt = Differential(t)\n    Dr = Differential(r)\n\n    # 1D PDE and boundary conditions\n\n    eq  = Dt(u(t,r)) ~ 1/r^2 * Dr(r^2 * Dr(u(t,r)))\n    bcs = [u(0,r) ~ sin(r)/r,\n           Dr(u(t,0)) ~ 0,\n           u(t,1) ~ exp(-t) * sin(1)]\n        #    Dr(u(t,1)) ~ -exp(-t) * sin(1)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               r \u2208 Interval(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,r],[u(t,r)])\n\n    # Method of lines discretization\n    dr = 0.1\n    order = 2\n    discretization = MOLFiniteDifference([r=>dr],t)\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    r = (0:dr:1)[2:end-1]\n    t = sol.t\n\n    # Test against exact solution\n    for i in 1:length(sol)\n        exact = u_exact(r, t[i])\n        u_approx = sol.u[i]\n        @test all(isapprox.(u_approx, exact, atol=0.01))\n    end\nend\n\n@testset \"Test 08: Dt(u(t,r)) ~ 4/r^2 * Dr(r^2 * Dr(u(t,r))) (Spherical Laplacian)\" begin\n    # Method of Manufactured Solutions\n    # general solution of the spherical Laplacian equation\n    # satisfies Dr(u(t,0)) = 0\n    u_exact = (r,t) -> exp.(-4t) * sin.(r) ./ r\n\n    # Parameters, variables, and derivatives\n    @parameters t r\n    @variables u(..)\n    Dt = Differential(t)\n    Dr = Differential(r)\n\n    # 1D PDE and boundary conditions\n\n    eq  = Dt(u(t,r)) ~ 4/r^2 * Dr(r^2 * Dr(u(t,r)))\n    bcs = [u(0,r) ~ sin(r)/r,\n           Dr(u(t,0)) ~ 0,\n           u(t,1) ~ exp(-4t) * sin(1)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               r \u2208 Interval(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,r],[u(t,r)])\n\n    # Method of lines discretization\n    dr = 0.1\n    order = 2\n    discretization = MOLFiniteDifference([r=>dr],t)\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    r = (0:dr:1)[2:end-1]\n    t = sol.t\n\n    # Test against exact solution\n    for i in 1:length(sol)\n        exact = u_exact(r, t[i])\n        u_approx = sol.u[i]\n        @test all(isapprox.(u_approx, exact, atol=0.01))\n    end\nend\n\n@testset \"Test 10: linear diffusion, two variables, mixed BCs\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * cos.(x)\n    v_exact = (x,t) -> exp.(-t) * sin.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..) v(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Dx^2\n\n    # 1D PDE and boundary conditions\n    eqs = [Dt(u(t,x)) ~ Dxx(u(t,x)),\n           Dt(v(t,x)) ~ Dxx(v(t,x))]\n    bcs = [u(0,x) ~ cos(x),\n           v(0,x) ~ sin(x),\n           u(t,0) ~ exp(-t),\n           Dx(u(t,1)) ~ -exp(-t) * sin(1),\n           Dx(v(t,0)) ~ exp(-t),\n           v(t,1) ~ exp(-t) * sin(1)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eqs,bcs,domains,[t,x],[u(t,x),v(t,x)])\n\n    # Method of lines discretization\n    l = 100\n    dx = range(0.0,1.0,length=l)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    x_sol = dx[2:end-1]\n    t_sol = sol.t\n\n    # Test against exact solution\n    for i in 1:length(sol)\n        @test all(isapprox.(u_exact(x_sol, t_sol[i]), sol.u[i][1:l-2], atol=0.01))\n        @test all(isapprox.(v_exact(x_sol, t_sol[i]), sol.u[i][l-1:end], atol=0.01))\n    end\nend\n\n@testset \"Test 11: linear diffusion, two variables, mixed BCs, with parameters\" begin\n    @parameters t x\n    @parameters Dn, Dp\n    @variables u(..) v(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Differential(x)^2\n\n    eqs  = [Dt(u(t,x)) ~ Dn * Dxx(u(t,x)) + u(t,x)*v(t,x), \n            Dt(v(t,x)) ~ Dp * Dxx(v(t,x)) - u(t,x)*v(t,x)]\n    bcs = [u(0,x) ~ sin(pi*x/2),\n        v(0,x) ~ sin(pi*x/2),\n        u(t,0) ~ 0.0, Dx(u(t,1)) ~ 0.0,\n        v(t,0) ~ 0.0, Dx(v(t,1)) ~ 0.0]\n\n    domains = [t \u2208 Interval(0.0,1.0),\n            x \u2208 Interval(0.0,1.0)]\n\n    pdesys = PDESystem(eqs,bcs,domains,[t,x],[u(t,x),v(t,x)],[Dn=>0.5, Dp=>2])\n    discretization = MOLFiniteDifference([x=>0.1],t)\n    prob = discretize(pdesys,discretization)\n    @test prob.p == [0.5,2]\n    # Make sure it can be solved\n    sol = solve(prob,Tsit5())\nend\n\n@testset \"Test 12: linear diffusion, two variables, mixed BCs, different independent variables\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * cos.(x)\n    v_exact = (y,t) -> exp.(-t) * sin.(y)\n\n    # Parameters, variables, and derivatives\n    @parameters t x y\n    @variables u(..) v(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Dx^2\n    Dy = Differential(y)\n    Dyy = Dy^2\n\n    # 1D PDE and boundary conditions\n    eqs = [Dt(u(t,x)) ~ Dxx(u(t,x)),\n           Dt(v(t,y)) ~ Dyy(v(t,y))]\n    bcs = [u(0,x) ~ cos(x),\n           v(0,y) ~ sin(y),\n           u(t,0) ~ exp(-t),\n           Dx(u(t,1)) ~ -exp(-t) * sin(1),\n           Dy(v(t,0)) ~ exp(-t),\n           v(t,2) ~ exp(-t) * sin(2)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,1.0),\n               y \u2208 Interval(0.0,2.0)]\n\n    # PDE system\n    pdesys = PDESystem(eqs,bcs,domains,[t,x,y],[u(t,x),v(t,y)])\n\n    # Method of lines discretization\n    l = 100\n    dx = range(0.0,1.0,length=l)\n    dy = range(0.0,2.0,length=l)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx,y=>dy],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    x_sol = dx[2:end-1]\n    y_sol = dy[2:end-1]\n    t_sol = sol.t\n\n    # Test against exact solution\n    for i in 1:length(sol)\n        @test all(isapprox.(u_exact(x_sol, t_sol[i]), sol.u[i][1:l-2], atol=0.01))\n        @test all(isapprox.(v_exact(y_sol, t_sol[i]), sol.u[i][l-1:end], atol=0.01))\n    end\nend\n\n@testset \"Test 13: one linear diffusion with mixed BCs, one ODE\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * sin.(x)\n    v_exact = (t) -> exp.(-t)\n\n    @parameters t x\n    @variables u(..) v(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Dx^2\n\n    # 1D PDE and boundary conditions\n    eqs = [Dt(u(t,x)) ~ Dxx(u(t,x)),\n           Dt(v(t)) ~ -v(t)]\n    bcs = [u(0,x) ~ sin(x),\n           v(0) ~ 1,\n           u(t,0) ~ 0,\n           Dx(u(t,1)) ~ exp(-t) * cos(1)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,1.0)]\n\n    # PDE system\n    pdesys = PDESystem(eqs,bcs,domains,[t,x],[u(t,x),v(t)])\n\n    # Method of lines discretization\n    l = 100\n    dx = range(0.0,1.0,length=l)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Tsit5(),saveat=0.1)\n\n    x_sol = dx[2:end-1]\n    t_sol = sol.t\n\n    # Test against exact solution\n    for i in 1:length(sol)\n        @test all(isapprox.(u_exact(x_sol, t_sol[i]), sol.u[i][1:length(x_sol)], atol=0.01))\n        @test v_exact(t_sol[i]) \u2248 sol.u[i][end] atol=0.01\n    end\nend\n\n@testset \"Test error 01: Test Invalid Centered Order\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * cos.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..)\n    Dt = Differential(t)\n    Dxx = Differential(x)^2\n\n    # 1D PDE and boundary conditions\n    eq  = Dt(u(t,x)) ~ Dxx(u(t,x))\n    bcs = [u(0,x) ~ cos(x),\n           u(t,0) ~ exp(-t),\n           u(t,Float64(\u03c0)) ~ -exp(-t)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,Float64(\u03c0))]\n\n    # PDE system\n    pdesys = PDESystem(eq,bcs,domains,[t,x],[u(t,x)])\n\n    # Method of lines discretization\n    dx = range(0.0,Float64(\u03c0),length=30)\n\n    # Explicitly specify and invalid order of centered difference\n    for order in 1:6\n        discretization = MOLFiniteDifference([x=>dx],t;centered_order=order)\n        if order % 2 != 0\n            @test_throws ArgumentError discretize(pdesys,discretization)\n        else\n            discretize(pdesys,discretization)\n        end\n    end\nend\n", "meta": {"hexsha": "dba7aae9f138cb77fede036338924addf8ad73f3", "size": 20292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MOL/MOL_1D_Linear_Diffusion.jl", "max_stars_repo_name": "mjsheikh/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "687d41d2650b660550024462061057758617dd48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-09T13:38:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-27T23:29:13.000Z", "max_issues_repo_path": "test/MOL/MOL_1D_Linear_Diffusion.jl", "max_issues_repo_name": "mjsheikh/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "687d41d2650b660550024462061057758617dd48", "max_issues_repo_licenses": ["MIT"], "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/MOL_1D_Linear_Diffusion.jl", "max_forks_repo_name": "mjsheikh/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "687d41d2650b660550024462061057758617dd48", "max_forks_repo_licenses": ["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.3407821229, "max_line_length": 110, "alphanum_fraction": 0.5590380445, "num_tokens": 6802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7789350682387541}}
{"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": "using Random, Statistics, LinearAlgebra, Test, FillArrays, Printf, TotalLeastSquares, StatsBase\nusing RandomizedLinAlg\nRandom.seed!(0)\n\n\n@testset \"TotalLeastSquares\" begin\n\n    @testset \"TLS\" begin\n        @info \"Testing TLS\"\n        x   = randn(3)\n        A   = randn(50,3)\n        \u03c3a  = 1\n        \u03c3y  = 0.01\n        An  = A + \u03c3a*randn(size(A))\n        y   = A*x\n        yn  = y + \u03c3y*randn(size(y))\n        Qaa = \u03c3a^2*Eye(prod(size(A)))\n        Qay = 0Eye(prod(size(A)),length(y))\n        Qyy = \u03c3y^2*Eye(prod(size(y)))\n\n        x\u0302 = An\\yn\n        @printf \"Least squares error: %25.3e %10.3e %10.3e, Norm: %10.3e\\n\" (x-x\u0302)... norm(x-x\u0302)\n        @test norm(x-x\u0302) < 1\n\n        x\u0302 = wls(An,yn,Qyy)\n        @printf \"Weigthed Least squares error: %16.3e %10.3e %10.3e, Norm: %10.3e\\n\" (x-x\u0302)... norm(x-x\u0302)\n        @test norm(x-x\u0302) < 1\n\n        x\u0302 = tls(An,yn)\n        @printf \"Total Least squares error: %19.3e %10.3e %10.3e, Norm: %10.3e\\n\" (x-x\u0302)... norm(x-x\u0302)\n        @test norm(x-x\u0302) < 1\n\n        x\u0302 = wtls(An,yn,Qaa,Qay,Qyy,iters=10)\n        @printf \"Weighted Total Least squares error: %10.3e %10.3e %10.3e, Norm: %10.3e\\n\" (x-x\u0302)... norm(x-x\u0302)\n        println(\"----------------------------\")\n        @test norm(x-x\u0302) < 1\n\n        @test tls(An,yn) \u2248 tls!([An yn], size(An,2))\n\n        rowC = rowcovariance([[\u03c3a^2*Eye(3) zeros(3); zeros(1,3) \u03c3y^2] for _ in 1:50])\n        @test rowC[1] \u2248 Qaa\n        @test rowC[2] \u2248 Qay\n        @test rowC[3] \u2248 Qyy\n\n    end\n\n\n    @testset \"Robust PCA\" begin\n        @info \"Testing Robust PCA\"\n        D = [0.462911    0.365901  0.00204357    0.692873    0.935861;\n        0.0446199    0.108606   0.0664309   0.0736707    0.264429;\n        0.320581    0.287788    0.073133    0.188872    0.526404;\n        0.356266    0.197536 0.000718338    0.513795    0.370094;\n        0.677814    0.011651    0.818047   0.0457694    0.471477]\n\n        A = [0.462911   0.365901  0.00204356   0.345428   0.623104;\n        0.0446199  0.108606  0.0429271    0.0736707  0.183814;\n        0.320581   0.203777  0.073133     0.188872   0.472217;\n        0.30725    0.197536  0.000717701  0.201626   0.370094;\n        0.234245   0.011651  0.103622     0.0457694  0.279032]\n\n        E = [0.0        0.0        0.0        0.347445  0.312757 ;\n        0.0        0.0        0.0235038  0.0       0.0806151;\n        0.0        0.0840109  0.0        0.0       0.0541868;\n        0.0490157  0.0        6.5061e-7  0.312169  0.0      ;\n        0.443569   0.0        0.714425   0.0       0.192445]\n\n        A\u0302, E\u0302,_,_ = rpca(D, nonnegE=true, nonnegA=true, verbose=false)\n\n        @test A\u0302 \u2248 A atol=1.0e-6\n        @test E\u0302 \u2248 E atol=1.0e-6\n        @test norm(D - (A\u0302 + E\u0302))/norm(D) < sqrt(eps())\n\n\n        A\u0302, E\u0302,_,_ = rpca(D, nonnegE=false, nonnegA=false, verbose=false)\n        @test norm(D - (A\u0302 + E\u0302))/norm(D) < sqrt(eps())\n\n\n        @testset \"Missing values\" begin\n            @info \"Testing Missing values\"\n\n            res = map(1:20) do _\n                N = 500\n                y = sin.(0.1 .* (1:N)) .+ 0.1*randn(N)\n                miss = rand(N) .< 0.1\n                yn = y .+ miss .* 1e2\n                yf = lowrankfilter(yn,40)\n                mean(abs2,y-yf)/mean(abs2,y)\n            end\n            @test mean(res) < 0.025\n\n        end\n\n        @testset \"Complex\" begin\n            @info \"Testing Complex\"\n            u = randn(ComplexF64, 100)\n            v = randn(ComplexF64, 20)\n            E = randn(ComplexF64,100,20) .* 10 .* (rand.() .< 0.01)\n            A = u*v'\n            D = A .+ E\n            Ah, Eh, s, sv = rpca(D)\n            @test sum(abs2, Eh-E)/sum(abs2, E) < 1e-5\n            @test sum(abs2, Ah-A)/sum(abs2, A) < 1e-5\n\n\n        end\n\n    end\n\n@testset \"rtls\" begin\n    @info \"Testing rtls\"\n    passes = map(1:1000) do _\n        x   = randn(3)\n        A   = randn(50,3)\n        \u03c3   = 5\n        An  = A + \u03c3*randn(size(A)) .* (rand(size(A)...) .< 0.1)\n        y   = A*x\n        yn  = y + \u03c3*randn(size(y)) .* (rand(size(y)...) .< 0.1)\n\n        AA  = [An yn]\n        Ah,Eh,_,_ = rpca(AA, verbose=false)\n\n        sum(abs2, Ah - [A y])/sum(abs2,[A y]) < sum(abs2, AA - [A y])/sum(abs2,[A y])\n    end\n    @show mean(passes)\n    @test mean(passes) > 0.9\n\n    passes = map(1:1000) do _\n        x   = randn(3)\n        A   = randn(50,3)\n        \u03c3   = 50\n        An  = A + \u03c3*randn(size(A)) .* (rand(size(A)...) .< 0.1)\n        y   = A*x\n        yn  = y + \u03c3*randn(size(y)) .* (rand(size(y)...) .< 0.1)\n\n        x\u0302t = tls(An,yn)\n        x\u0302r = rtls(An,yn)\n\n        norm(x-x\u0302r) < norm(x-x\u0302t)\n    end\n    @show mean(passes)\n    @test mean(passes) > 0.9\n\n    # @testset \"Elastic Net rtls\" begin\n    #     @info \"Testing Elastic Net rtls\"\n    #     passes = map(1:500) do _\n    #         x     = randn(10)\n    #         A     = randn(100,3) * randn(3,10)\n    #         \u03c3s    = 50\n    #         \u03c3d    = 0.5\n    #         S     = \u03c3s*randn(size(A)) .* (rand(size(A)...) .< 0.1)\n    #         D     = \u03c3d*randn(size(A))\n    #         N     = S + D\n    #         An    = A + N\n    #\n    #         Ah,Eh,_,_ = rpca(An, verbose=false)\n    #\n    #         \u03bb = 1/sqrt(100)\n    #         \u03bc = 0.001\u03bb\n    #         Ah2,Eh2,_,_ = rpca(An, verbose=false, proxE = ElasticNet(\u03bb, \u03bc))\n    #\n    #         sum(abs2, Ah - A)/sum(abs2,A) < sum(abs2, An - A)/sum(abs2,A),\n    #         sum(abs2, Eh2 - N)/sum(abs2,N) < sum(abs2, Eh - N)/sum(abs2,N)\n    #     end\n    #     @show mean(getindex.(passes, 1))\n    #     @test mean(getindex.(passes, 1)) > 0.9\n    #     @show mean(getindex.(passes, 2))\n    #     @test mean(getindex.(passes, 2)) > 0.9\n    #\n    #\n    # end\n\nend\n\n\n# @testset \"rtls ga\" begin\n#     @info \"Testing rtls ga\"\n#\n#     passes = map(1:1000) do _\n#         x   = randn(5)\n#         A   = randn(500,5)\n#         \u03c3   = 50\n#         An  = A + \u03c3*randn(size(A)) .* (rand(size(A)...) .< 0.01)\n#         y   = A*x\n#         yn  = y + \u03c3*randn(size(y)) .* (rand(size(y)...) .< 0.01)\n#\n#         x\u0302t = tls(An,yn)\n#         x\u0302r = rtls_ga(An,yn, \u03bc=entrywise_median)\n#\n#         norm(x-x\u0302r) < norm(x-x\u0302t)\n#     end\n#     @show mean(passes)\n#     @test mean(passes) > 0.7\n#\n# end\n\n@testset \"soft hankel\" begin\n    @info \"Testing soft hankel\"\n\n    @test hankel(1:20,2) == [1:19 2:20]\n    @test hankel(1:20,3,2) == [1:2:17 2:2:18 3:2:19]\n\n    A = hankel(1:8,4)\n    @test ishankel(A)\n    An = A + 0.1randn(size(A))\n    @test !ishankel(An)\n    Anc = copy(An)\n    TotalLeastSquares.soft_hankel!(An, 0.1)\n    @test sum(abs2,An-A) < sum(abs2,Anc-A)\n\n    An = -A + 0.1randn(size(A))\n    Anc = copy(An)\n    TotalLeastSquares.soft_hankel!(An, 0.1)\n    @test sum(abs2,An+A) < sum(abs2,Anc+A)\n\n    passes = map(1:100) do _\n        y = randn(20)\n        yn = y .+ 0.1 .* randn.()\n        A = hankel(y,3)\n        An = hankel(yn,3)\n        Anc = copy(An)\n        A1,E1,_,_ = rpca(An, verbose=false, nukeA=false)\n        A2,E2,_,_ = rpca(An, verbose=false, nukeA=false, hankel=true)\n        sum(abs2,A2-A) < sum(abs2,A1-A)\n    end\n    @show mean(passes)\n    @test mean(passes) > 0.7\n\n    @info \"Small random Hankel\"\n    passes = map(1:500) do _\n        y = randn(100)\n        A = hankel(y,5)\n        @test ishankel(A)\n        A1,E1,_,_ = rpca(A, verbose=false, nukeA=false)\n        A2,E2,_,_ = rpca(A, verbose=false, nukeA=false, hankel=true)\n        @test ishankel(A2)\n        @test ishankel(E2)\n        mean(abs2,A2-A) < mean(abs2,A1-A)\n    end\n    @show mean(passes)\n    @test mean(passes) > 0.8\n\n    @info \"Big random Hankel\"\n    passes = map(1:10) do _\n        y = randn(1000)\n        A = hankel(y,50)\n        @test ishankel(A)\n        A1,E1,_,_ = rpca(A, verbose=false, nukeA=false)\n        A2,E2,_,_ = rpca(A, verbose=false, nukeA=false, hankel=true)\n        @test ishankel(A2)\n        @test ishankel(E2)\n        mean(abs2,A2-A) < mean(abs2,A1-A)\n    end\n    @show mean(passes)\n    @test mean(passes) >= 0.8\n\n\nend\n\n\n@testset \"lowrankfilter\" begin\n    @info \"Testing lowrankfilter\"\n    qn(x) = x ./ quantile(abs.(x), 0.9)\n    T = 1000\n    t = 1:T\n    y = sin.(0.1 .* t) |> qn\n\n    H = hankel(y, 2)\n    @test ishankel(H)\n    @test unhankel(H) == y\n\n    H = hankel(y,2,2)\n    yh = unhankel(H,2,T)\n    @test yh == y\n\n    H = hankel(y,5,2)\n    yh = unhankel(H,2,T)\n    @test yh[1:end-1] \u2248 y[1:end-1]\n\n    y2 = randn(T)\n    H = hankel([y y2],5,2)\n    yh = unhankel(H,2,T,2)\n    @test yh[1:end-1,:] \u2248 [y y2][1:end-1,:]\n\n    n = 20randn(T) .* (rand(T) .< 0.01) + 0.1randn(T)\n    yf = lowrankfilter(y+n) |> qn\n    @test mean(abs2, y-yf)/mean(abs2, n) < 0.001\n    @show mean(abs2, y-yf)/mean(abs2, n)\n\n    # Randomized lin alg\n    yf = lowrankfilter(y+n, opnorm=x->rnorm(x,10)) |> qn\n    @test mean(abs2, y-yf)/mean(abs2, n) < 0.001\n    @show mean(abs2, y-yf)/mean(abs2, n)\n\n    yf = lowrankfilter(y+n, svd=rsvd_fnkz) |> qn\n    @test mean(abs2, y-yf)/mean(abs2, n) < 0.05\n    @show mean(abs2, y-yf)/mean(abs2, n)\n\n    yf = lowrankfilter(y+n, opnorm=x->rnorm(x,10), svd=rsvd_fnkz) |> qn\n    @test mean(abs2, y-yf)/mean(abs2, n) < 0.05\n    @show mean(abs2, y-yf)/mean(abs2, n)\n\n    yf = lowrankfilter(y+n, opnorm=x->rnorm(x,10), svd=rsvd_fnkz, maxrank=5) |> qn\n    @test mean(abs2, y-yf)/mean(abs2, n) < 0.05\n    @show mean(abs2, y-yf)/mean(abs2, n)\n\n\n    # Only SSA\n    n = randn(T)\n    yf = lowrankfilter(y+n, sv=2) |> qn\n    @test mean(abs2, y-yf)/mean(abs2, n) < 0.05\n    @show mean(abs2, y-yf)/mean(abs2, n)\n\n\n    @testset \"Multi channel\" begin\n        @info \"Testing Multi channel\"\n\n        T = 1000\n        t = 1:T\n        y1 = sin.(0.1 .* t)\n        y2 = sin.(0.3 .* t)\n        y = [y1 y2+0.5y1]\n        yn = y .+ 0.1 .* randn.() .+ (rand.() .< 0.01) .* 5 .* randn.()\n        yf = lowrankfilter(yn, 20)\n        @show mean(abs2,y-yf)/mean(abs2,y-yn)\n        @test mean(abs2,y-yf)/mean(abs2,y-yn) < 0.05\n\n        # There shoud be benefit to joint filtering since the two signals are correlated\n        yf1 = lowrankfilter(yn[:,1], 20)\n        @test mean(abs2,y1-yf1)/mean(abs2,y1-yf[:,1]) > 1.02\n\n        # Same freq, different phase\n        y1 = sin.(0.1 .* t)\n        y2 = sin.(0.1 .* t .+ 0.01)\n        y = [y1 y2]\n        yn = y .+ 0.1 .* randn.() .+ (rand.() .< 0.01) .* 5 .* randn.()\n        yf = lowrankfilter(yn, 20)\n        @show mean(abs2,y-yf)/mean(abs2,y-yn)\n        @test mean(abs2,y-yf)/mean(abs2,y-yn) < 0.02\n\n        yf1 = lowrankfilter(yn[:,1], 20)\n        @show mean(abs2,y1-yf1)/mean(abs2,y1-yf[:,1])\n        @test mean(abs2,y1-yf1)/mean(abs2,y1-yf[:,1]) > 1.2\n\n\n    end\n\nend\n\n@testset \"rpca_ga\" begin\n    @info \"Testing rpca_ga\"\n\n    Random.seed!(1)\n    for r = 1:10, \u03f5 = exp10.(LinRange(-8, 0, 20))\n        s = svd(randn(10,40))\n        u,v = s.U[:,1:r], s.V[:,1:r]\n        A = u*Diagonal(10*(1:r))*v' .+ \u03f5 .* randn.()\n        Q = rpca_ga(A, r, verbose=false)\n        @test rank([Q u], atol=\u03f5) == r # Q and u should span the same space, but they may not share any other properties\n        @test norm(Q'Q - I) < sqrt(eps())\n    end\n\n    # Below is the reverse dimensions of above\n    for r = 1:10, \u03f5 = exp10.(LinRange(-8, 0, 20))\n        s = svd(randn(40,10))\n        u,v = s.U[:,1:r], s.V[:,1:r]\n        A = u*Diagonal(10*(1:r))*v' .+ \u03f5 .* randn.()\n        Q = rpca_ga(A, r, verbose=false)\n        @test rank([Q u], atol=\u03f5) == r # Q and u should span the same space, but they may not share any other properties\n        @test norm(Q'Q - I) < sqrt(eps())\n    end\n\n    @testset \"entrywise trimmed mean\" begin\n        @info \"Testing entrywise trimmed mean\"\n\n        U = randn(10,10)\n        s = zeros(10)\n        w = ones(10)\n        m1 = TotalLeastSquares.\u03bc!(s,w,U)\n        @test m1 \u2248 mean(U, dims=2)\n\n        m2 = TotalLeastSquares.entrywise_trimmed_mean(s,w,U,0)\n        @test m2 \u2248 mean(U, dims=2)\n\n        w = randn(10)\n        m1 = TotalLeastSquares.\u03bc!(s,w,U)\n        @test m1 \u2248 sum(U .* w', dims=2)./ sum(w)\n\n        m2 = TotalLeastSquares.entrywise_trimmed_mean(s,w,U,0)\n        @test m2 \u2248 sum(U .* w', dims=2)./ sum(w)\n\n        w = ones(10)\n        m2 = TotalLeastSquares.entrywise_trimmed_mean(s,w,U,0.1)\n        for i in eachindex(m2)\n            @test m2[i] \u2248 mean(StatsBase.trim(U[i,:], prop=0.1))\n        end\n\n        r = 3; \u03f5 = 1e-8\n        Random.seed!(1)\n        passes = map(Iterators.product(1:4, exp10.(LinRange(-8, -1, 3)))) do (r,\u03f5)\n            # @show r, \u03f5\n            s = svd(randn(10,1000))\n            u,v = s.U[:,1:r], s.V[:,1:r]\n            # A = u*Diagonal(10*(1:r))*v' .+ \u03f5 .* randn.()\n            A = u*Diagonal(s.S[1:r])*v' .+ \u03f5 .* randn.()\n            A .+= 1000*randn.() .* (rand.() .< 0.01)\n\n            Qtm = rpca_ga(A, r, verbose=false, \u03bc = TotalLeastSquares.entrywise_trimmed_mean, iters=120)\n            Qm = rpca_ga(A, r, verbose=false, iters=120)\n            sum(svdvals([Qtm u])[r+1:2r]) < sum(svdvals([Qm u])[r+1:2r])\n            # @test norm(Q'Q - I) < r*sqrt(eps()) # This test should pass but doesn't\n        end\n        @show mean(passes)\n        @test mean(passes) > 0.8\n\n        passes = map(Iterators.product(1:4, exp10.(LinRange(-8, -1, 3)))) do (r,\u03f5)\n            # @show r, \u03f5\n            s = svd(randn(10,1000))\n            u,v = s.U[:,1:r], s.V[:,1:r]\n            # A = u*Diagonal(10*(1:r))*v' .+ \u03f5 .* randn.()\n            A = u*Diagonal(s.S[1:r])*v' .+ \u03f5 .* randn.()\n            A .+= 1000*randn.() .* (rand.() .< 0.01)\n\n            Qmed = rpca_ga(A, r, verbose=false, \u03bc = TotalLeastSquares.entrywise_median, iters=120)\n            Qm = rpca_ga(A, r, verbose=false, iters=120)\n            sum(svdvals([Qmed u])[r+1:2r]) < sum(svdvals([Qm u])[r+1:2r])\n            # @test norm(Q'Q - I) < r*sqrt(eps())  # This test should pass but doesn't\n        end\n        @show mean(passes)\n        @test mean(passes) > 0.9\n    end\nend\n\n@testset \"irls\" begin\n    @info \"Testing irls\"\n\n    N = 10000\n    n = 20\n    A = randn(N, n)\n    x = randn(n)\n    y = A*x\n    e = 100*(rand(N) .< 0.01) + 0.1randn(N)\n    @time xh = irls(A,y+e, verbose=true,iters=100)\n    @test norm(x-xh)/norm(x) < 0.01\n    xhls = A\\(y+e)\n    @test norm(x-xh) < norm(x-xhls)\nend\n\n@testset \"sls\" begin\n    @info \"Testing sls\"\n\n    for i = 1:100\n        x = TotalLeastSquares.proj_simplex!(randn(i))\n        @test sum(x) \u2248 1\n        @test all(x .>= 0)\n    end\n\n\n    s1(x) = x ./= sum(x)\n    ##\n    n = 10\n    N = 2\n    results = map(1:100) do _\n        a = [(rand(n)) for _ in 1:N]\n        A = reduce(hcat,a)\n        x = s1(rand(N))\n        y = A*x\n        yn = y .+ 0.01.*randn.()\n        xh1 = TotalLeastSquares.proj_simplex!(A\\yn)\n\n        xh2 = sls(A,yn,verbose=false)\n        @test sum(xh2) \u2248 1\n\n        norm(x-xh2) < norm(x-xh1) || norm(yn-A*xh2) < norm(yn-A*xh1)\n    end\n    @test mean(results) >= 0.98\nend\n\n@testset \"flts\" begin\n    @info \"Testing flts\"\n    # Example from paper \n    x = 10randn(1000)\n    a, b = 1, 2\n    y = a*x .+ b \n    y[801:end] = 5randn(200) \n    x[801:end] = 5randn(200) .+ 50 \n    xb = [x ones(1000)]\n    # default\n    res = flts(xb,y, verbose = true)\n    @test a \u2248 res[1]\n    @test b \u2248 res[2]\n    # define % of outliers\n    res1 = flts(xb,y, N = 10, outliers = 0.20, verbose = true)\n    @test a \u2248 res1[1]\n    @test b \u2248 res1[2]\n    # define length of set H and check the subset\n    (H, res2, Q) = flts(xb,y, N = 10, h = 800, return_set = true, verbose = true)\n    @test a \u2248 res2[1]\n    @test b \u2248 res2[2]\n    @test all(H .< 801)\n    @test Q + 1 \u2248 1\nend\nend\n", "meta": {"hexsha": "c786b6f4877d2b03d3d6b18178d5ef8d254bc8f8", "size": 15197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "baggepinnen/TotalLeastSquares.jl", "max_stars_repo_head_hexsha": "297b9a8277c01358f54889944f3dcc711c0fe535", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-04-11T19:03:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T00:56:52.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "baggepinnen/TotalLeastSquares.jl", "max_issues_repo_head_hexsha": "297b9a8277c01358f54889944f3dcc711c0fe535", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-04-17T09:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T13:25:27.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "baggepinnen/TotalLeastSquares.jl", "max_forks_repo_head_hexsha": "297b9a8277c01358f54889944f3dcc711c0fe535", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:58:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T15:55:16.000Z", "avg_line_length": 30.1527777778, "max_line_length": 120, "alphanum_fraction": 0.490294137, "num_tokens": 6067, "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(\ud835\udebd, \ud835\udecc, Q; \u03b1 = 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- `\ud835\udebd::Matrix{Float64}`: matrix of (weighted) graph Laplacian eigenvectors.\n- `\ud835\udecc::Vector{Float64}`: vector of eigenvalues.\n- `Q::Matrix{Float64}`: unweighted incidence matrix of the graph.\n- `\u03b1::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(\ud835\udf19\u1d62\u208b\u2081, \ud835\udf19\u2c7c\u208b\u2081).\n\n\"\"\"\nfunction natural_eigdist(\ud835\udebd, \ud835\udecc, Q; \u03b1 = 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(\ud835\udebd)\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, \u03b1 = \u03b1)\n    elseif distance == :HAD\n        D = eigHAD_Distance(\ud835\udebd, \ud835\udecc)\n    elseif distance == :DAG\n        D = eigDAG_Distance(\ud835\udebd, Q, N; edge_weight = edge_weight)\n    elseif distance == :TSD\n        tL = Q * Q'\n        t\ud835\udecc, t\ud835\udebd = eigen(Matrix(tL))\n        D = eigTSD_Distance(P, t\ud835\udebd, t\ud835\udecc, 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": "@testset \"lanczos\" begin\n\t@testset \"givens\" begin\n\t\tsymOrth = KrylovMethods.symOrtho\n\n\t\tv     = ([0;randn()],[randn();0],randn(2))\n\t\tfor k=1:3\n\t\t\tprintln(\"Givens rotation for v=[$(v[k][1]),$(v[k][2])]\")\n\t\t\tc,s,r = symOrth(v[k][1],v[k][2])\n\t\t\t@test abs(c.^2 + s.^2 - 1) < 1e-14\n\t\t\tQ = [c s; -s c]\n\t\t\tw = [norm(v[k]);0]\n\t\t\t@test norm(Q*v[k]-w) < 1e-13\n\t\tend\n\tend\n\t@testset \"bidiag\" begin\n\t\tprintln(\"=== Testing Lanczos Bidiagonalization ===\")\n\t\tA = sprandn(10,10,.4) + I\n\t\tp = randn(10)\n\t\tk = 9\n\n\t\tU,B,V = lanczosBidiag(A,p,k)\n\n\t\t@test norm(Matrix(U'*A*V-B))/norm(Matrix(A)) < 1e-15\n\tend\n\n\n\t@testset \"tridiag\" begin\n\t\t# test stopping for low-rank matrix\n\t\tA = randn(100,10)\n\t\tH = A*A'\n\t\tT,V = lanczosTridiag(H,ones(100),100,doReorth=true)\n\t\t@test size(T,1)==11\n\t\t@test size(V,2)==11\n\n\t\t# A   = matrixdepot(\"rosser\",4)\n\t\t# Aff  = x -> A*x\n\t\t# T1,V1 = lanczosTridiag(A,ones(size(A,1)),size(A,1),tol=1e-10,doReorth=true)\n\t\t# T2,V2 = lanczosTridiag(Aff,ones(size(A,1)),size(A,1),tol=1e-10,doReorth=false)\n\t\t# sT1  = svd(Matrix(T1)).S\n\t\t# sT2  = svd(Matrix(T2)).S\n\t\t# sA   = svd(Matrix(A)).S\n\t\t#\n\t\t# @test abs(sT1[1]-sA[1])/sA[1] < 1e-4\n\t\t# @test abs(sT2[1]-sA[1])/sA[1] < 1e-4\n\t\t# B = V1'*V1\n\t\t# @test norm(B - Diagonal(diag(B))) < 1e-10\n\t\t# @test norm(diag(B)- ones(size(B,1))) < 1e-10\n\tend\nend\n", "meta": {"hexsha": "e342e38d6a2e91450a0bbc100c06bff453d83280", "size": 1290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testLANCZOS.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": "test/testLANCZOS.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": "test/testLANCZOS.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": 25.8, "max_line_length": 82, "alphanum_fraction": 0.5658914729, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7789350607316494}}
{"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\u00b2 = sum(X .^ 2; dims=1)\n    y\u00b2 = sum(Y .^ 2; dims=1)\n    transpose(x\u00b2) .+ y\u00b2 - 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\u00b2 = sum(X .^ 2; dims=1)\n    transpose(x\u00b2) .+ x\u00b2 - 2XiXj\nend\n\n\"\"\"\n    gaussian_gramian(xs, ys, \u03c3=1)\n\nGramian matrix for samples `xs` and `ys` using a Gaussian kernel\nkernel with bandwidth `\u03c3`.\n\"\"\"\ngaussian_gramian(xs; kwargs...) = gaussian_gramian(xs, xs; kwargs...)\ngaussian_gramian(xs, ys; \u03c3=1) =\n  [exp(-euclidsq(x, y) / 2\u03c3^2) for x in xs, y in ys]\n\nfunction gaussian_gramian(X::T, Y::T; \u03c3=1) where {T<:AbstractMatrix}\n    gaussian_gramian(euclidsq(X, Y), \u03c3)\nend\n\ngaussian_gramian(esq, \u03c3::AbstractFloat) = exp.(-esq ./ 2\u03c3^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 \u03c3\u00b2_estimator(l::Int, n::Int, \u03f5::Vector{Fl}) where Fl\n    return ((1/n)*sum(\u03f5[t]^2 for t in 1:n)) + ((2/n)*sum((1-(s/(l + 1))) * (sum(\u03f5[t]*\u03f5[t - s] for t in s + 1:n)) for s in 1:l))\nend\n\nfunction p_value_weighted_average(\u03b7::Fl, p1::Fl, cv1::Fl, \n                                  p2::Fl, cv2::Fl) where Fl\n    return ((p1*(cv1 - cv2)) - ((cv1 - \u03b7)*(p1 - p2)))/(cv1 - cv2)\nend\n\nfunction p_value_from_\u03b7(\u03b7::Fl, crit_vals::Vector{Fl}) where Fl\n    if \u03b7 >= crit_vals[1]\n        p_value = 0.01\n    elseif \u03b7 < crit_vals[1] && \u03b7 >= crit_vals[2]\n        p_value = p_value_weighted_average(\u03b7, 0.01, crit_vals[1], 0.025, crit_vals[2])\n    elseif \u03b7 < crit_vals[2] && \u03b7 >= crit_vals[3]\n        p_value = p_value_weighted_average(\u03b7, 0.025, crit_vals[2], 0.05, crit_vals[3])\n    elseif \u03b7 < crit_vals[3] && \u03b7 <= crit_vals[4]\n        p_value = p_value_weighted_average(\u03b7, 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_\u03b7_level(y::Vector{Fl}, lags::Bool) where Fl\n    n = length(y)\n    \u03f5 = y .- (mean(y))\n    l = calc_lag_kpss(lags, n)\n    \u03b7 = (1/n^2)*sum(sum((((sum(\u03f5[i] for i in 1:t))^2)/\u03c3\u00b2_estimator(l, n, \u03f5)) for t in 1:n))\n    return \u03b7\nend\n\nfunction kpss_test(y::Vector{Fl}; lags::Bool = true) where Fl\n    \u03b7 = calc_\u03b7_level(y, lags)\n    crit_vals = [0.739, 0.574, 0.463, 0.347]\n    p_value = p_value_from_\u03b7(\u03b7, 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": "using Test\n\nfunction naive!(C, A, B)\n    row, col = size(C)\n    colA = size(A)[2]\n    for i in 1:row\n        for j in 1:col\n            for k in 1:colA\n                C[i, j] = C[i, j] + A[i, k] * B[k, j]\n            end\n        end\n    end\nend\n\n\nfunction unroll_k!(C, A, B)\n    row, col = size(C)\n    colA = size(A)[2]\n    for i in 1:row\n        for j in 1:col\n            for k in 1:2:colA\n                C[i, j] = C[i, j] + A[i, k] * B[k, j] + A[i, k+1] * B[k+1, j]\n            end\n        end\n    end\nend\n\n\nfunction unroll_j!(C, A, B)\n    row, col = size(C)\n    colA = size(A)[2]\n    for i in 1:row\n        for j in 1:2:col\n            for k in 1:colA\n                C[i,   j] = C[i, j] + A[i, k] * B[k, j]\n                C[i, j+1] = C[i, j+1] + A[i, k] * B[k, j+1]\n            end\n        end\n    end\nend\n\n\nfunction unroll_i!(C, A, B)\n    row, col = size(C)\n    colA = size(A)[2]\n    for i in 1:2:row\n        for j in 1:col\n            for k in 1:colA\n                C[i,   j] = C[i,   j] + A[i,   k] * B[k, j]\n                C[i+1, j] = C[i+1, j] + A[i+1, k] * B[k, j]\n            end\n        end\n    end\nend\n\n\nfunction unroll_ij!(C, A, B)\n    row, col = size(C)\n    colA = size(A)[2]\n    for i in 1:2:row\n        for j in 1:2:col\n            for k in 1:colA\n                C[i ,  j] = C[i,   j] + A[i, k] * B[k, j]\n                C[i+1, j] = C[i+1, j] + A[i+1, k] * B[k ,j]\n                C[i, j+1] = C[i, j+1] + A[i, k] * B[k, j+1]\n                C[i+1, j+1] = C[i+1, j+1] + A[i+1, k] * B[k, j+1]\n            end\n        end\n    end\nend\n\n\nfunction main(N)\n    A = reshape(convert.(Float64, collect(1:N^2)), N, N)\n    B = reshape(convert.(Float64, collect(1:N^2)), N, N)\n    C = zeros(N, N)\n    @time refC = A * B\n    C = zeros(N, N)\n    @time naive!(C, A, B)\n    C = zeros(N ,N)\n    @time unroll_k!(C, A, B)\n    @test C \u2248 refC\n    C = zeros(N, N)\n    @time unroll_i!(C, A, B)\n    @test C \u2248 refC\n    C = zeros(N, N)\n    @time unroll_j!(C, A, B)\n    @test C \u2248 refC\n    C = zeros(N, N)\n    @time unroll_ij!(C, A, B)\n    @test C \u2248 refC\nend\n", "meta": {"hexsha": "52fcac6e7a91ca2e16e318a31564ffc83a7eca29", "size": 2054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "matrixProd/loopunrolling.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": "matrixProd/loopunrolling.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": "matrixProd/loopunrolling.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": 22.0860215054, "max_line_length": 77, "alphanum_fraction": 0.4011684518, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7789350500027385}}
{"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  \u03b1, \u03b2, \u03b3, \u03b4  = p\n  du[1] = (\u03b1 - \u03b2*y)x # dx =\n  du[2] = (\u03b4*x - \u03b3)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    \u03c3 ~ InverseGamma(2, 3) # ~ is the tilde character\n    \u03b1 ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    \u03b2 ~ truncated(Normal(1.2,0.5),0,2)\n    \u03b3 ~ truncated(Normal(3.0,0.5),1,4)\n    \u03b4 ~ truncated(Normal(1.0,0.5),0,2)\n\n    p = [\u03b1,\u03b2,\u03b3,\u03b4]\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], \u03c3)\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    \u03c3 ~ InverseGamma(2, 3) # ~ is the tilde character\n    \u03b1 ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    \u03b2 ~ truncated(Normal(1.2,0.5),0,2)\n    \u03b3 ~ truncated(Normal(3.0,0.5),1,4)\n    \u03b4 ~ truncated(Normal(1.0,0.5),0,2)\n\n    p = [\u03b1,\u03b2,\u03b3,\u03b4]\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], \u03c3) # 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 - :\u03b1, :\u03b2, :\u03b3, :\u03b4\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   \u03b1, \u03b2, \u03b3, \u03b4 = p\n   du[1] = \u03b1 * h(p, t-1; idxs=1) - \u03b2 * x * y\n   du[2] = -\u03b3 * y + \u03b4 * 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    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ Truncated(Normal(1.5,0.5),0.5,2.5)\n    \u03b2 ~ Truncated(Normal(1.2,0.5),0,2)\n    \u03b3 ~ Truncated(Normal(3.0,0.5),1,4)\n    \u03b4 ~ Truncated(Normal(1.0,0.5),0,2)\n\n    p = [\u03b1,\u03b2,\u03b3,\u03b4]\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], \u03c3)\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 - :\u03b1, :\u03b2, :\u03b3, :\u03b4\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    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    \u03b2 ~ truncated(Normal(1.2,0.5),0,2)\n    \u03b3 ~ truncated(Normal(3.0,0.5),1,4)\n    \u03b4 ~ truncated(Normal(1.0,0.5),0,2)\n    p = [\u03b1,\u03b2,\u03b3,\u03b4]\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], \u03c3)\n    end\nend;\nmodel = fitlv(odedata, prob1)\nchain = sample(model, NUTS(.65),1000)\n\n\n@model function fitlv(data, prob)\n    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ truncated(Normal(1.5,0.5),0.5,2.5)\n    \u03b2 ~ truncated(Normal(1.2,0.5),0,2)\n    \u03b3 ~ truncated(Normal(3.0,0.5),1,4)\n    \u03b4 ~ truncated(Normal(1.0,0.5),0,2)\n    p = [\u03b1,\u03b2,\u03b3,\u03b4]\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], \u03c3)\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  \u03b1,\u03b2,\u03b3,\u03b4 = p\n  du[1] = dx = \u03b1*x - \u03b2*x*y\n  du[2] = dy = \u03b4*x*y - \u03b3*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    \u03c3 ~ InverseGamma(2,3)\n    \u03b1 ~ truncated(Normal(1.3,0.5),0.5,2.5)\n    \u03b2 ~ truncated(Normal(1.2,0.25),0.5,2)\n    \u03b3 ~ truncated(Normal(3.2,0.25),2.2,4.0)\n    \u03b4 ~ truncated(Normal(1.2,0.25),0.5,2.0)\n    \u03d51 ~ truncated(Normal(0.12,0.3),0.05,0.25)\n    \u03d52 ~ truncated(Normal(0.12,0.3),0.05,0.25)\n    p = [\u03b1,\u03b2,\u03b3,\u03b4,\u03d51,\u03d52]\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],\u03c3)\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": "module problem119\n\ndescription = \"\"\"\nDigit power sum\n\nThe number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284.\nWe shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.\nYou are given that a2 = 512 and a10 = 614656.\n\nFind a30.\n\"\"\"\n\n# sum the digits of an integer by repeated div/mod by 10\nfunction digitsum(n :: Integer)\n  total = 0\n  while n > 0\n    total += n % 10\n    n = div(n, 10)\n  end\n  return total\nend\n\n# Find all numbers with are powers of their digit sums, up to a maximum number of digits\n# Insight: the digit sum for any number < 10^N can be at most N*9\n#          so just consider powers of i from 2 to 9N, checking digitsums\nfunction digitPowerSums(maxDigits = 15)\n  results = BigInt[]\n  xMax = BigInt(10)^maxDigits\n  for i = 2 : 9 * maxDigits\n    x = BigInt(i)\n    while x < xMax\n      if x > 10 && digitsum(x) == i\n        push!(results, x)\n      end\n      x *= i\n    end\n  end\n  sort!(results)\n  return results\nend\n\n\nusing Base.Test\n\n@test digitsum(1234) == (1+2+3+4)\na = digitPowerSums()\n@test a[2] == 512\n@test a[10] == 614656\n\nend", "meta": {"hexsha": "40c35328333ea32a0b442f59ae9c83c190708b46", "size": 1253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem119.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/problem119.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/problem119.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.06, "max_line_length": 189, "alphanum_fraction": 0.6640063847, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7788466069146235}}
{"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 \u2216 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 \u2286 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 \u2229 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, \u03b1=0.49609375)\n\nSplit the interval `X` at position \u03b1; \u03b1=0.5 corresponds to the midpoint.\nReturns a tuple of the new intervals.\n\"\"\"\nfunction bisect(X::Interval, \u03b1=where_bisect)\n    @assert 0 \u2264 \u03b1 \u2264 1\n\n    m = mid(X, \u03b1)\n\n    return (unsafe_interval(X.lo, m), unsafe_interval(m, X.hi))\nend\n\n\"\"\"\n    mid(a::Interval, \u03b1=0.5)\n\nFind an intermediate point at a relative position `\u03b1`` in the interval `a`.\nThe default is the true midpoint at `\u03b1 = 0.5`.\n\nAssumes 0 \u2264 \u03b1 \u2264 1.\n\nWarning: if the parameter `\u03b1 = 0.5` is explicitly set, the behavior differs\nfrom the default case if the provided `Interval` is not finite, since when\n`\u03b1` 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}, \u03b1) 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    \u03b2 = T(\u03b1)\n\n    midpoint = \u03b2 * (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 - \u03b2) * lo + \u03b2 * hi\nend\n\nmid(::EmptyInterval{T}, \u03b1) 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": "using SMC\nusing PyPlot\nusing Base.Test\n\n@testset \"logsumexp tests\" begin\n\n    # on vector\n    vec = [1., 2.2, 3.1]\n    actual = logsumexp(vec)\n    expected = log(sum(exp.(vec)))\n    @test isapprox(actual, expected)\n\n    # on 2D array\n    arr = [[1. 2. 3.]; [3.3 4.1 5.2]]\n    # sum over rows\n    actual = logsumexp(arr, 1)\n    expected = [3.3955454645979626 4.215519523179755 5.305083319768697] \n    @test isapprox(actual, expected)\n\n    # sum over columns\n    actual = logsumexp(arr, 2)\n    expected = [3.40760596444438 5.593689178496464]'\n    @test isapprox(actual, expected)\nend\n\n@testset \"hmm tests\" begin\n    \n    initial_state_prior = [0.4, 0.6]\n    transition_model = [0.7 0.3; \n                        0.1 0.9]\n    observation_model = [0.6 0.3 0.1; \n                         0.1 0.4 0.5]\n    hmm = HiddenMarkovModel(initial_state_prior, \n                            transition_model, \n                            observation_model)\n    observations = [1, 3, 2]\n\n    @testset \"forward probabilities\" begin\n        # p(x_t | y_{1:t-1}) for each t = 1,..,T\n        actual = SMC.hmm_forward_pass(hmm, observations)\n        # number of time steps x number of states\n        @test size(actual) == (3, 2) \n\n        # check against manually computed values\n        expected = begin\n\n            # p(x_2 = 1, y_1 = 1, y_2 = 3) = p(x_1 = 1, x_2 = 1, y_1 = 1, y_2 = 3) + p(x_1 = 2, x_2 = 1, y_1 = 1, y_2 = 3)\n            shared_x2_eq_1 = ((0.4 * 0.7 * 0.6 * 0.1) + (0.6 * 0.1 * 0.1 * 0.1))\n\n            # p(x_2 = 2, y_1 = 1, y_2 = 3) = p(x_1 = 1, x_2 = 2, y_1 = 1, y_2 = 3) + p(x_1 = 2, x_2 = 2, y_1 = 1, y_2 = 3)\n            shared_x2_eq_2 = ((0.4 * 0.3 * 0.6 * 0.5) + (0.6 * 0.9 * 0.1 * 0.5)) # \n\n            f11 = 0.4 # p(x_1 = 1)\n            f12 = 0.6 # p(x_1 = 2)\n\n            # p(x_2 = 1, y_1 = 1) = p(x_1 = 1, x_2 = 1, y_1 = 1) + p(x_1 = 2, x_2 = 1, y_1 = 1) \n            f21 = (0.4 * 0.7 * 0.6) + (0.6 * 0.1 * 0.1) \n\n            # p(x_2 = 2, y_1 = 1) = p(x_1 = 1, x_2 = 2, y_1 = 1) + p(x_1 = 2, x_2 = 2, y_1 = 1) \n            f22 = (0.4 * 0.3 * 0.6) + (0.6 * 0.9 * 0.1)\n\n            # p(x_3 = 1, y_1 = 1, y_2 = 3) = p(x_2 = 1, x_3 = 1, y_1 = 1, y_2 = 3) + p(x_2 = 2, x_3 = 1, y_1 = 1, y_2 = 3)\n            f31 = shared_x2_eq_1 * 0.7 + shared_x2_eq_2 * 0.1 \n\n            # p(x_3 = 2, y_1 = 1, y_2 = 3) = p(x_2 = 1, x_3 = 2, y_1 = 1, y_2 = 3) + p(x_2 = 2, x_3 = 2, y_1 = 1, y_2 = 3)\n            f32 = shared_x2_eq_1 * 0.3 + shared_x2_eq_2 * 0.9 \n\n            [f11 f12; f21 f22; f31 f32]\n        end\n        @test isapprox(actual, expected)\n\n        # check log space agrees\n        @test isapprox(exp.(SMC.hmm_log_forward_pass(hmm, observations)), expected)\n    end\n\n    @testset \"marginal likelihoods\" begin\n        actual = SMC.hmm_marginal_likelihood(hmm, observations)\n\n        expected = (\n              (0.4 * 0.7 * 0.7 * 0.6 * 0.1 * 0.3) + # x = (1, 1, 1)\n              (0.4 * 0.7 * 0.3 * 0.6 * 0.1 * 0.4) + # x = (1, 1, 2)\n              (0.4 * 0.3 * 0.1 * 0.6 * 0.5 * 0.3) + # x = (1, 2, 1)\n              (0.4 * 0.3 * 0.9 * 0.6 * 0.5 * 0.4) + # x = (1, 2, 2)\n              (0.6 * 0.1 * 0.7 * 0.1 * 0.1 * 0.3) + # x = (2, 1, 1)\n              (0.6 * 0.1 * 0.3 * 0.1 * 0.1 * 0.4) + # x = (2, 1, 2)\n              (0.6 * 0.9 * 0.1 * 0.1 * 0.5 * 0.3) + # x = (2, 2, 1)\n              (0.6 * 0.9 * 0.9 * 0.1 * 0.5 * 0.4)) # x = (2, 2, 2)\n        \n        @test isapprox(actual, expected)\n\n        # check that log space agrees\n        @test isapprox(actual, exp(hmm_log_marginal_likelihood(hmm, observations)))\n    end\n\n    @testset \"posterior sampling\" begin\n        particle = hmm_posterior_sample(hmm, observations)\n        \n        # smoke test: check the type and dimensions and other basic properties\n        @test typeof(particle) == Array{Int,1}\n        @test length(particle) == 3\n        @test all(particle .>= 1)\n        @test all(particle .<= 2)\n\n        # TODO: test the distribution? Maybe next year :)\n\n    end\n\n    @testset \"sanity checks\" begin\n\n        # sanity check on extreme observation\n        srand(1)\n        hmm = HiddenMarkovModel([0.5, 0.5],                     # prior\n                                [0.5 0.5; 0.5 0.5],             # transition\n                                [0.9999 0.0001; 0.0001 0.9999]) # observation\n        obs = [1]\n        num_samples = 100\n        num_1 = 0\n        for i = 1:num_samples\n            particle = hmm_posterior_sample(hmm, obs)\n            num_1 += (particle[1] == 1)\n        end\n        @test num_1 >= 95\n\n        # sanity check on extreme prior and transition\n        srand(1)\n        hmm = HiddenMarkovModel([0.0001, 0.9999],                     # prior\n                                [0.9999 0.0001; 0.0001 0.9999],             # transition\n                                [0.5 0.5; 0.5 0.5]) # observation\n        obs = [1, 2]\n        num_samples = 100\n        num_1 = 0\n        for i = 1:num_samples\n            particle = hmm_posterior_sample(hmm, obs)\n            num_1 += (particle[2] == 1)\n        end\n        @test num_1 <= 5\n\n        # a symmetric extreme distribution\n        hmm = HiddenMarkovModel([0.5, 0.5],         # prior\n                                [0.9999 0.0001; 0.0001 0.9999],  # transition\n                                [0.9999 0.0001; 0.0001 0.9999]) # observation\n\n        # switch happens at step 9 -> 10\n        obs_a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2]\n        obs_b = [2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1]\n\n        # test for symmetry\n        @test isapprox(hmm_log_marginal_likelihood(hmm, obs_a),\n                       hmm_log_marginal_likelihood(hmm, obs_b))\n\n        # check samples\n        srand(1)\n        num_samples = 100\n\n        num_start_1 = 0\n        num_end_2 = 0\n        for i = 1:num_samples\n            particle = hmm_posterior_sample(hmm, obs_a)\n            num_start_1 += all(particle[1:9] .== 1)\n            num_end_2 += all(particle[10:end] .== 2)\n        end\n        @test num_start_1 >= 95\n        @test num_end_2 >= 95\n\n        srand(1)\n        num_start_2 = 0\n        num_end_1 = 0\n        for i = 1:num_samples\n            particle = hmm_posterior_sample(hmm, obs_b)\n            num_start_2 += all(particle[1:9] .== 2)\n            num_end_1 += all(particle[10:end] .== 1)\n        end\n        @test num_start_2 >= 95\n        @test num_end_1 >= 95\n    end\n\nend\n\n@testset \"smc tests\" begin\n\n    hmm = HiddenMarkovModel(\n            [0.4, 0.6], # prior\n            [0.7 0.3; \n             0.1 0.9], # transition\n            [0.6 0.3 0.1; \n             0.1 0.4 0.5]) # observation\n    observations = [1, 3, 2]\n\n    # SMC with prior proposal\n    srand(1)\n    num_particles = 10000\n    scheme = HMMPriorSMCScheme(hmm, observations, num_particles)\n    output, log_ml_estimate = smc(scheme)\n    @test length(output) == 3\n    expected = hmm_log_marginal_likelihood(hmm, observations)\n    @test isapprox(log_ml_estimate, expected, atol=0.1, rtol=0)\n\n    # conditional SMC (take output from above as input)\n    log_ml_estimate = conditional_smc(scheme, output)\n    @test isapprox(log_ml_estimate, expected, atol=0.1, rtol=0)\n\n    # SMC with conditional proposal\n    srand(1)\n    num_particles = 10000\n    scheme = HMMConditionalSMCScheme(hmm, observations, num_particles)\n    output, log_ml_estimate = smc(scheme)\n    @test length(output) == 3\n    expected = hmm_log_marginal_likelihood(hmm, observations)\n    @test isapprox(log_ml_estimate, expected, atol=0.02, rtol=0)\n\n    # conditional SMC (take output from above as input)\n    log_ml_estimate = conditional_smc(scheme, output)\n    @test isapprox(log_ml_estimate, expected, atol=0.1, rtol=0)\nend\n\n@testset \"smc sandwiching the evidence with exact sampling\" begin\n\n    hmm = HiddenMarkovModel(\n            [0.4, 0.6], # prior\n            [0.7 0.3; \n             0.1 0.9], # transition\n            [0.6 0.3 0.1; \n             0.1 0.4 0.5]) # observation\n    observations = [1, 3, 2]\n\n    # true marginal likelihood\n    expected = hmm_log_marginal_likelihood(hmm, observations)\n\n    function test_bounds(smc_scheme_constructor, all_num_particles::Array{Int,1},\n                         num_reps::Int)\n        lower_bound_raw_data = Array{Float64, 2}(length(all_num_particles), num_reps)\n        upper_bound_raw_data = Array{Float64, 2}(length(all_num_particles), num_reps)\n        for (i, num_particles) in enumerate(all_num_particles)\n            scheme = HMMConditionalSMCScheme(hmm, observations, num_particles)\n            for j = 1:num_reps\n                output, lml_estimate = smc(scheme)\n                lower_bound_raw_data[i, j] = lml_estimate \n            end\n            for j = 1:num_reps\n                output = hmm_posterior_sample(hmm, observations)\n                lml_estimate = conditional_smc(scheme, output)\n                upper_bound_raw_data[i, j] = lml_estimate \n            end\n        end\n    \n        lower_bound_means = mean(lower_bound_raw_data, 2)\n        lower_bound_stds = std(lower_bound_raw_data, 2)\n        upper_bound_means = mean(upper_bound_raw_data, 2)\n        upper_bound_stds = std(upper_bound_raw_data, 2)\n\n        # they should be upper and lower bounds in all cases\n        for i=1:length(all_num_particles)\n            @test lower_bound_means[i] <= expected\n            @test upper_bound_means[i] >= expected\n        end\n\n        # the estimates should get tighter and less noisy with more particles\n        for i=1:length(all_num_particles)-1\n            @test lower_bound_means[i] <= lower_bound_means[i+1]\n            @test upper_bound_means[i] >= upper_bound_means[i+1]\n            @test lower_bound_stds[i] >= lower_bound_stds[i+1]\n            @test upper_bound_stds[i] >= upper_bound_stds[i+1]\n        end\n\n        # the final estimates should both be tight\n        @test isapprox(lower_bound_means[end], expected, atol=0.01, rtol=0)\n        @test isapprox(upper_bound_means[end], expected, atol=0.01, rtol=0)\n\n    end\n\n    # SMC with prior proposal\n    srand(1)\n    test_bounds(HMMConditionalSMCScheme, [1, 3, 10, 30, 100], 1000)\n\n    # SMC with conditional proposal\n    srand(1)\n    test_bounds(HMMPriorSMCScheme, [1, 3, 10, 30, 100], 1000)\n\nend\n\n@testset \"rendering hmm\" begin\n    hmm = HiddenMarkovModel(\n        [0.4, 0.6], # prior\n        [0.7 0.3; \n         0.1 0.9], # transition\n        [0.6 0.3 0.1; \n         0.1 0.4 0.5]) # observation\n\n    hmm_fname = \"$(tempname()).png\"\n    latent_states_fname = \"$(tempname()).png\"\n    observations_fname = \"$(tempname()).png\"\n\n    # just check that rendering works in the current environment without crashign\n    plt[:figure]()\n    render_hmm!(hmm)\n    plt[:savefig](hmm_fname)\n    \n    plt[:figure]()\n    render_hmm_states!(hmm, [1, 1, 1, 2, 2, 1, 2, 1, 2, 2, 2], true, [1, 10], [1, 2])\n    plt[:savefig](latent_states_fname)\n        \n    plt[:figure]()\n    render_hmm_observations!(hmm, [1, 1, 1, 3, 3, 1, 2, 1, 2, 2, 2])\n    plt[:savefig](observations_fname)\n\n    Base.Filesystem.rm(hmm_fname)\n    Base.Filesystem.rm(latent_states_fname)\n    Base.Filesystem.rm(observations_fname)\nend\n", "meta": {"hexsha": "d3020d55f7def2a8ac3418e7f51df3f66840ff78", "size": 11001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 35.4870967742, "max_line_length": 122, "alphanum_fraction": 0.540769021, "num_tokens": 3889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7788416335126895}}
{"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 \u2261 even -> normal pattern\n\t# section \u2261 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": "# Univariate Normal setup, following Richardson & Green (1997).\r\n# This version uses the general version of the sampler.\r\nmodule NormalNonoptimized\r\n\r\nmodule NormalModel\r\nexport Theta, Data, log_likelihood, log_prior, prior_sample!, new_theta, Theta_clear!, Theta_adjoin!, Theta_remove!,\r\n       Hyperparameters, construct_hyperparameters, update_hyperparameters!, update_parameter!\r\n\r\ninclude(\"Random.jl\")\r\nusing .Random\r\n\r\nconst Data = Float64\r\n\r\ntype Normal_params\r\n    mu::Float64\r\n    sigma::Float64\r\n    n::Int64        # number of data points assigned to this cluster\r\n    sum_x::Float64  # sum of the data points x assigned to this cluster\r\n    sum_xx::Float64 # sum of x^2 for the data points assigned to this cluster\r\n    Normal_params(mu,sigma) = (p=new(); p.mu=mu; p.sigma=sigma; p.n=0; p.sum_x=0.0; p.sum_xx=0.0; p)\r\nend\r\n\r\nNormal_logpdf(x,mu,sigma) = (r=(x-mu)/sigma;  -0.5*r*r - 0.5*log(2.0*pi) - log(sigma))\r\nNormal_clear!(p) = (p.sum_x = 0.; p.sum_xx = 0.; p.n = 0)\r\nNormal_adjoin!(p,x) = (p.sum_x += x; p.sum_xx += x*x; p.n += 1)\r\nNormal_remove!(p,x) = (p.sum_x -= x; p.sum_xx -= x*x; p.n -= 1)\r\n\r\ntype Hyperparameters\r\n    m::Float64  # prior mean of mu\r\n    s::Float64  # prior stddev of mu\r\n    a::Float64  # prior shape of sigma\r\n    b::Float64  # prior rate of sigma (starting value)\r\n    g::Float64  # (hyper)prior shape of b\r\n    h::Float64  # (hyper)prior rate of b\r\nend\r\n\r\nGamma_logpdf(x,a,b) = (a-1)*log(x) - b*x + a*log(b) - lgamma(a)\r\n# log density of SqrtInvGamma (distn of sigma when 1/sigma^2 ~ Gamma(a,b))\r\nSqrtInvGamma_logpdf(x,a,b) = Gamma_logpdf(1/x^2,a,b) + log(2/x^3)\r\n\r\nconst Theta = Normal_params\r\nlog_likelihood(x,p) = Normal_logpdf(x,p.mu,p.sigma)\r\n# prior: Normal(mu|H.m,H.s) * SqrtInvGamma(sigma|H.a,H.b)\r\nlog_prior(p,m,s,a,b) = Normal_logpdf(p.mu,m,s) + SqrtInvGamma_logpdf(p.sigma,a,b)\r\nlog_prior(p,H) = log_prior(p,H.m,H.s,H.a,H.b)\r\nprior_sample!(p,H) = (p.mu = randn()*H.s + H.m; p.sigma = 1/sqrt(Random.gamma(H.a,H.b)))\r\nnew_theta(H) = Normal_params(0.0,1.0)\r\nTheta_clear!,Theta_adjoin!,Theta_remove! = Normal_clear!,Normal_adjoin!,Normal_remove!\r\n\r\n\r\nfunction construct_hyperparameters(options)\r\n    x = options.x\r\n    # Use values in Green & Richardson (1997) to enable comparison.\r\n    m = (minimum(x) + maximum(x))/2\r\n    R = maximum(x) - minimum(x)\r\n    s = R\r\n    a = 2.0\r\n    b = 1.0  # b will be updated in Gibbs sampling\r\n    g = 0.2\r\n    h = 10/R^2\r\n    return Hyperparameters(m,s,a,b,g,h)\r\nend\r\n\r\n\r\nfunction update_parameter!(theta_a,theta_b,H,active,density)\r\n    n,sum_x,sum_xx = theta_b.n,theta_b.sum_x,theta_b.sum_xx\r\n    # update mean\r\n    ell = 1/H.s^2\r\n    lambda = 1/(theta_a.sigma^2)\r\n    L = lambda*n + ell\r\n    M = (lambda*sum_x + ell*H.m) / L\r\n    if active; theta_b.mu = randn()/sqrt(L) + M; end\r\n    \r\n    # update standard deviation\r\n    alpha = H.a + 0.5*n\r\n    beta = H.b + 0.5*(sum_xx - 2*theta_b.mu*sum_x + n*theta_b.mu^2)\r\n    if active; theta_b.sigma = 1/sqrt(Random.gamma(alpha,beta)); end\r\n\r\n    return (density? log_prior(theta_b,M,1/sqrt(L),alpha,beta) : NaN)\r\nend\r\n\r\nfunction update_hyperparameters!(H,theta,list,t,x,z)\r\n    sum_lambdas = 0.0\r\n    for k = 1:t; sum_lambdas += 1/theta[list[k]].sigma^2; end\r\n    alpha = H.g + H.a*t\r\n    beta = H.h + sum_lambdas\r\n    H.b = Random.gamma(alpha,beta)\r\nend\r\n\r\nend # module NormalModel\r\nusing .NormalModel\r\n\r\n# Include generic code\r\ninclude(\"generic.jl\")\r\n\r\n# Include core sampler code\r\ninclude(\"coreNonconjugate.jl\")\r\n\r\nend # module NormalNonoptimized\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "8b7a568ab1aa61cc93557e32258135793962e41b", "size": 3497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NormalNonoptimized.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/NormalNonoptimized.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/NormalNonoptimized.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": 32.9905660377, "max_line_length": 117, "alphanum_fraction": 0.6488418645, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.8479677506936879, "lm_q1q2_score": 0.7788416303670642}}
{"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\u0303` 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\u0303` should differ from the actual minimum `x` at most\n`abs_tol + rel_tol * abs(x\u0303)`.\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": "# test_problems.jl : definition of some test problems\n\ng(x, y) = Float64[1 + sin(\u03c0 * x\u1d62) * sin(\u03c0 * y\u1d62) for x\u1d62 in x, y\u1d62 in y]\ng(x, y, z) = Float64[1 + sin(\u03c0 * x\u1d62) * sin(\u03c0 * y\u1d62) * sin(\u03c0 * z\u1d62) for x\u1d62 in x, y\u1d62 in y, z\u1d62 in z]\n\nf(n, m) = g(range(1/n, stop = 1 - 1/n, length = n - 1), range(1/m, stop = 1 - 1/m, length = m - 1))\nf(n, m, l) = g(range(1/n, stop = 1 - 1/n, length = n - 1),range(1/m, stop = 1 - 1/m, length = m - 1), range(1/l, stop = 1 - 1/l, length = l - 1))\n\np\u2081\u2082(n) = laplace2d(n, n)\np\u2081\u2083(n) = laplace3d(n, n, n)\n\np\u2082\u2082(n) = elliptic2d(f(n, n))\np\u2082\u2083(n) = elliptic3d(f(n, n, n))\n\np\u2083\u2082(n) = anisotropic2d(1e-4, n, n)\np\u2083\u2083(n) = anisotropic3d(1e-4,1, n, n, n)\n\np\u2084\u2082(n) = anisotropic2d(1e-4, 10 * \u03c0/180, n, n)\n", "meta": {"hexsha": "c557bb34cce37774909dffe740bf2ae5b01d4792", "size": 708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_problems.jl", "max_stars_repo_name": "PieterjanRobbe/NotSoSimpleMultigrid.jl", "max_stars_repo_head_hexsha": "877de2f5be2c96bc9c7796bf321434858ba9659d", "max_stars_repo_licenses": ["MIT"], "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_problems.jl", "max_issues_repo_name": "PieterjanRobbe/NotSoSimpleMultigrid.jl", "max_issues_repo_head_hexsha": "877de2f5be2c96bc9c7796bf321434858ba9659d", "max_issues_repo_licenses": ["MIT"], "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_problems.jl", "max_forks_repo_name": "PieterjanRobbe/NotSoSimpleMultigrid.jl", "max_forks_repo_head_hexsha": "877de2f5be2c96bc9c7796bf321434858ba9659d", "max_forks_repo_licenses": ["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.2631578947, "max_line_length": 145, "alphanum_fraction": 0.5451977401, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615413, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.77880029607474}}
{"text": "using Spectra\nusing Test\n\n#### Dummy x\nx = collect(0.1:0.1:100.)\n\n#### gaussienne test\np = [10.,50.,5.]\ny = p[1] .* exp.(-log(2) .* ((x.-p[2])./p[3]).^2)\n\ny_calc, y_peaks = gaussiennes([p[1]],[p[2]],[p[3]],x)\n\n@test isapprox(y,y_calc)\n\n#### lorentzienne test\np = [10.,50.,5.]\ny = p[1] ./ (1.0 .+ ((x.-p[2])./p[3]).^2)\n\ny_calc, y_peaks = lorentziennes([p[1]],[p[2]],[p[3]],x)\n\n@test isapprox(y,y_calc)\n\n#### pearson7 test\na = [10.,50.,5., 5.]\ny = a[1] ./ (1.0 .+ ((x.-a[2])./a[3]).^2 .* (2.0.^(1.0./a[4]) .- 1.0))\n\ny_calc, y_peaks = pearson7([a[1]],[p[2]],[p[3]],[a[4]],x)\n\n@test isapprox(y,y_calc)\n\n#### pseudovoigt test\np = [10.,50.,5.,0.5]\n\ny_lor = p[4] .* (p[1] ./ (1 .+ ((x.-p[2])./p[3]).^2))\ny_gauss = (1.0 .-p[4]) .* (p[1] .* exp.(-log(2) .* ((x.-p[2])./p[3]).^2))\ny = y_gauss + y_lor\n\ny_calc, y_peaks = pseudovoigts([p[1]],[p[2]],[p[3]],[p[4]],x)\n@test isapprox(y,y_calc)\n\n#### normal distribution test\np = [1.,50.,5.]\ny = p[1]./(p[3].*sqrt(2.0 .*pi)) .* exp.(-0.5.*((x.-p[2])./p[3]).^2)\n\ny_calc, y_peaks = normal_dist([p[1]],[p[2]],[p[3]],x)\n@test isapprox(y,y_calc)\n", "meta": {"hexsha": "b90497e53d6103fdbe3b158a1e63683c42708e19", "size": 1075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/peaks.jl", "max_stars_repo_name": "asinghvi17/Spectra.jl", "max_stars_repo_head_hexsha": "aa369ae314ee3b94b1fb11d1513243ef035d0da2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2016-03-26T01:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T02:39:37.000Z", "max_issues_repo_path": "test/peaks.jl", "max_issues_repo_name": "asinghvi17/Spectra.jl", "max_issues_repo_head_hexsha": "aa369ae314ee3b94b1fb11d1513243ef035d0da2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2016-07-25T01:42:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T15:55:48.000Z", "max_forks_repo_path": "test/peaks.jl", "max_forks_repo_name": "asinghvi17/Spectra.jl", "max_forks_repo_head_hexsha": "aa369ae314ee3b94b1fb11d1513243ef035d0da2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-06-09T20:51:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T19:19:15.000Z", "avg_line_length": 22.8723404255, "max_line_length": 73, "alphanum_fraction": 0.4948837209, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760639, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.778800295905818}}
{"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    \u0394x::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, \u0394x::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)\u00f72)+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) \u2248 step(grid_evaluate)\n        @argcheck last(grid_compute) < last(grid_evaluate)\n\n        new{T, Grid, RFFT, BRFFT}(jac, \u0394x, 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\u00f72+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(\u03c0) / (xmax - xmin) / N # / N because of brfft instead of BRFFT\n    \u0394x = (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, \u0394x, 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\u00f72+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}, \u03b1, \u03b2) 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, \u03b1, \u03b2)\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 \u0394x = D\n\n    @inbounds res = sum(func, u)\n\n    \u0394x * res\nend\n\nfunction mass_matrix(D::FourierDerivativeOperator)\n    @unpack \u0394x = D\n\n    \u0394x * I\nend\n\n\n\n\"\"\"\n    fourier_derivative_matrix(N, xmin::Real=0.0, xmax::Real=2\u03c0)\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\u03c0)\n    T = promote_type(typeof(xmin), typeof(xmax))\n    jac_2 = T(\u03c0) / (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(\u03c0)/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.\u0394x == D2.\u0394x 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.\u03bb * 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.\u0394x == poly2.D1.\u0394x 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.\u0394x == poly2.D1.\u0394x 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.\u03bb, 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.\u0394x == poly2.D1.\u0394x 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.\u03bb, 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.\u03bb - 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.\u0394x == den.D1.\u0394x 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.\u0394x == rat2.D1.\u0394x 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.\u0394x == rat2.D1.\u0394x 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.\u0394x == rat2.D1.\u0394x 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.\u0394x == rat2.D1.\u0394x 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)\u00f72)+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# \u2554\u2550\u2561 67477abe-0b56-49a6-818d-3fccc669c6ce\nbegin\n\t# using Pkg; Pkg.add(\"Primes\")\n\tusing Primes\nend\n\n# \u2554\u2550\u2561 727bf063-5fef-4126-a615-8a483aab9c99\nbegin\n\t# using Pkg; Pkg.add(\"Plots\") \n\tusing Plots\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u00f7 p^m)\n\tend\n\tsum\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3c9f9459-9828-47ec-bdfc-8bd8a0187553\nfor n in 0:25\n\tprintln(\"n=$n\\tD(n)=$(arithmetic_derivative(n))\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9ebc2997-8db4-4aeb-a2e1-4614302d4f56\nplot_derivatives(80)\n\n# \u2554\u2550\u2561 f9b2636f-231c-44f4-95a3-013ba47df516\nplot_derivatives(80, connect_dots = true)\n\n# \u2554\u2550\u2561 652bf146-8059-4c52-8f9a-63c3b5a22487\nplot_derivatives(100, connect_dots = true)\n\n# \u2554\u2550\u2561 9cbc71f0-d902-4276-8a3d-b025355dddef\nplot_derivatives(200, connect_dots = true)\n\n# \u2554\u2550\u2561 9c06d571-24e9-4678-9c0f-a7ac01f7d8f6\nplot_derivatives(500, connect_dots = true)\n\n# \u2554\u2550\u2561 0374c7ce-c485-4712-a95b-55e2f3c30a67\nplot_derivatives(3000, connect_dots = true)\n\n# \u2554\u2550\u2561 c3248ade-6106-47df-8e6f-38847aee52ce\nmd\"\nWe can plot this function and overlay it with the scatter plot for $N=100$:\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250080fc74b2-e038-11eb-39c8-fbd84caf7338\n# \u2560\u255067477abe-0b56-49a6-818d-3fccc669c6ce\n# \u255f\u25008b83eccb-c629-45ff-b8cb-4b4879664ace\n# \u2560\u2550c0d8d582-364c-4b06-8b08-cf902a359897\n# \u255f\u2500fa3e00d3-7f8e-4158-98ee-4e22285952d7\n# \u2560\u25503c9f9459-9828-47ec-bdfc-8bd8a0187553\n# \u255f\u250049eea834-b3bf-426b-993b-d2ea01da742d\n# \u2560\u2550727bf063-5fef-4126-a615-8a483aab9c99\n# \u2560\u25501f2295eb-188f-4498-9d8c-1c0f303b2396\n# \u2560\u25509ebc2997-8db4-4aeb-a2e1-4614302d4f56\n# \u255f\u25005fbd5946-9e1e-444b-9ab6-03bfed725620\n# \u2560\u2550f9b2636f-231c-44f4-95a3-013ba47df516\n# \u255f\u25005166fe7d-50fc-4e0e-b839-c0db8bf73b01\n# \u255f\u2500652bf146-8059-4c52-8f9a-63c3b5a22487\n# \u255f\u25009cbc71f0-d902-4276-8a3d-b025355dddef\n# \u255f\u25009c06d571-24e9-4678-9c0f-a7ac01f7d8f6\n# \u255f\u25000374c7ce-c485-4712-a95b-55e2f3c30a67\n# \u255f\u2500a3a14843-7b62-4f6f-8e81-ed772e4a27f3\n# \u2560\u25508af8ac5e-616d-407b-8001-6fa7529c5729\n# \u255f\u2500c3248ade-6106-47df-8e6f-38847aee52ce\n# \u2560\u25502ae73301-1458-4d49-80f4-249706d2eb09\n# \u255f\u25007f491dc8-d921-4637-acc9-09ccc3d2b9d6\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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# \u2264 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 \u2265 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 \u2264 N \u2264 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    \u03c1 = U * eigs * (U')\n    return Hermitian((\u03c1 + \u03c1') / 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 \u227a 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 \u227a q && return p, q\n        p \u227b 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 \u227a q)` and `!(q \u227a 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 \u227a q && continue\n        p \u227b 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, \u03b5 = 1/2, frame=false, frame_color=:blue)\n\tx = [center[1] + \u03b5 * spanning_vector_a[1] + \u03b5 * spanning_vector_b[1],\n\t     center[1] - \u03b5 * spanning_vector_a[1] + \u03b5 * spanning_vector_b[1],\n\t     center[1] + \u03b5 * spanning_vector_a[1] - \u03b5 * spanning_vector_b[1],\n\t     center[1] - \u03b5 * spanning_vector_a[1] - \u03b5 * spanning_vector_b[1]]\n\t\n\ty = [center[2] + \u03b5 * spanning_vector_a[2] + \u03b5 * spanning_vector_b[2],\n\t     center[2] - \u03b5 * spanning_vector_a[2] + \u03b5 * spanning_vector_b[2],\n\t     center[2] + \u03b5 * spanning_vector_a[2] - \u03b5 * spanning_vector_b[2],\n\t     center[2] - \u03b5 * spanning_vector_a[2] - \u03b5 * spanning_vector_b[2]]\n\n\tz = [center[3] + \u03b5 * spanning_vector_a[3] + \u03b5 * spanning_vector_b[3],\n\t     center[3] - \u03b5 * spanning_vector_a[3] + \u03b5 * spanning_vector_b[3],\n\t     center[3] + \u03b5 * spanning_vector_a[3] - \u03b5 * spanning_vector_b[3],\n\t     center[3] - \u03b5 * spanning_vector_a[3] - \u03b5 * 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,\u03bb` of the SOH model computed for the `model` `\"Fokker-Planck\"` (default)\nor `\"BGK\"` with the concentration parameters `\u03ba`.\nThese coefficients are given by\n\nc\u2081 = \u222b\\\\_[0,\u03c0] cos(\u03b8)exp(\u03bacos(\u03b8))d\u03b8 / \u222b\\\\_[0,\u03c0] exp(\u03bacos(\u03b8))d\u03b8\n\nc\u2082 = \u222b\\\\_[0,\u03c0] cos(\u03b8)sin(\u03b8)g(\u03b8)exp(\u03bacos(\u03b8))d\u03b8 / \u222b\\\\_[0,\u03c0] sin(\u03b8)g(\u03b8)exp(\u03bacos(\u03b8))d\u03b8\n\n\u03bb = 1/\u03ba\n\nwhere\n\ng(\u03b8) = \u03b8/\u03ba - \u03c0/\u03ba * \u222b\\\\_[0,\u03b8] exp(-\u03bacos(\u03c8))d\u03c8 / \u222b\\\\_[0,\u03c0] exp(-\u03bacos(\u03c8))d\u03c8 in the Fokker-Planck case\n\nand\n\ng(\u03b8) = 1 in the BGK case.\n\"\"\"\nfunction coefficients_Vicsek(\u03ba;model=\"Fokker-Planck\")\n    \u03bb = 1/\u03ba\n    I1 = quadgk(\u03b8->cos(\u03b8)*exp(\u03ba*cos(\u03b8)),0,pi,rtol=1e-5)[1]\n    Z1 = quadgk(\u03b8->exp(\u03ba*cos(\u03b8)),0,pi,rtol=1e-5)[1]\n    c1 = I1/Z1\n    if model==\"BGK\"\n        I2 = quadgk(\u03b8->cos(\u03b8)*sin(\u03b8)^2*exp(\u03ba*cos(\u03b8)),0,pi,rtol=1e-5)[1]\n        Z2 = quadgk(\u03b8->sin(\u03b8)^2*exp(\u03ba*cos(\u03b8)),0,pi,rtol=1e-5)[1]\n        c2 = I2/Z2\n        return c1,c2,\u03bb\n    elseif model==\"Fokker-Planck\"\n        Zinv = quadgk(\u03b8->exp(-\u03ba*cos(\u03b8)),0,pi,rtol=1e-5)[1]\n        I21 = quadgk(\u03b8->\u03b8*cos(\u03b8)*sin(\u03b8)*exp(\u03ba*cos(\u03b8)),0,pi,rtol=1e-5)[1]/\u03ba\n        I22 = pi/(\u03ba*Zinv) * hcubature(x->cos(x[1])*sin(x[1])*exp(\u03ba*cos(x[1]))*exp(-\u03ba*cos(x[2]))*(x[2]<x[1]),(0,0),(pi,pi),rtol=1e-3)[1]\n        I2 = I21 - I22\n        Z21 = quadgk(\u03b8->\u03b8*sin(\u03b8)*exp(\u03ba*cos(\u03b8)),0,pi,rtol=1e-5)[1]/\u03ba\n        Z22 = pi/(\u03ba*Zinv) * hcubature(x->sin(x[1])*exp(\u03ba*cos(x[1]))*exp(-\u03ba*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,\u03bb\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 \u03b1 \u03b2 \ud835\udc0d\nexport Hahn\n\n\"\"\"\n    Hahn{\u03b1,\u03b2,\ud835\udc0d}\n\nReferences: [Koekoek and Swarttouw \u00a71.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{\u03b1,\u03b2,\ud835\udc0d}})  where {\u03b1,\u03b2,\ud835\udc0d} = NamedTuple{(:a,:b,:c,:d,:e)}((1, -(\u03b2+\ud835\udc0d+1), 0,  \u03b1+\u03b2+2, -\ud835\udc0d*(\u03b1+1)))\n\nbasis_symbol(::Type{<:Hahn{\u03b1,\u03b2,\ud835\udc0d}}) where {\u03b1,\u03b2,\ud835\udc0d} = \"Q\u207d\u1d45\u1d5d\u207e\"\nPolynomials.domain(::Type{<:Hahn{\u03b1, \u03b2, \ud835\udc0d}}) where {\u03b1, \u03b2,  \ud835\udc0d} = Polynomials.Interval(0, \ud835\udc0d)\nweight_function(::Type{<:Hahn{\u03b1,\u03b2,\ud835\udc0d}}) where {\u03b1,\u03b2,\ud835\udc0d} = x -> generalized_binomial(\u03b1+x,x) * generalized_binomial(\ud835\udc0d+\u03b2-x,\ud835\udc0d-x)\n\n# use   recurrence relation  1.5.3 of Koekoek and Swarttouw\n# -xQ\u1d62 = AQ\u1d62\u208a\u2081 -  (A+C)Q\u1d62 + CQ\u1d62\u208b\u2081\n#  or Q\u1d62\u208a\u2081 = (1/A \u22c5 x - (1 + C/A)) Q\u1d62 + C/A \u22c5 Q\u1d62\u208b\u2081\n# Using k\u1d62 = A\u207b\u00b9\u1d62\u208b\u2081 \u22c5 A\u207b\u00b9\u1d62\u208b\u2082 \u22ef A\u207b\u00b9\u2080; so k\u1d62\u208a\u2081/k\u1d62 = A\u207b\u00b9\u1d62, k\u1d62\u208a\u2081/k\u1d62\u208b\u1d62 = A\u207b\u00b9\u1d62A\u207b\u00b9\u1d62\u208b\u2081\n#\n# function A\u1d62\u207b\u00b9(n,\u03b1,\u03b2,\ud835\udc0d)\n#     num = (2n+\u03b1+\u03b2 + 1) * (2n+\u03b1+\u03b2+2)\n#     den = (n+\u03b1 + \u03b2 + 1)*(n + \u03b1 + 1) *(\ud835\udc0d-n)\n#     num/den\n# end\n\n# define kn, k1k_1 through defaults\nfunction k1k0(P::Type{<:Hahn{\u03b1,\u03b2, \ud835\udc0d}}, n::Int) where {\u03b1,\u03b2,\ud835\udc0d}\n\n    num  = (2*n + \u03b1 + \u03b2 + 1)*(2*n + \u03b1 + \u03b2 + 2)\n    den = (-n + \ud835\udc0d)*(n + \u03b1 + 1)*(n + \u03b1 + \u03b2 + 1)\n\n    -(one(eltype(P))*num)/den\n    \nend\n\n# end\n\nfunction classical_hypergeometric(::Type{<:Hahn{\u03b1,\u03b2,\ud835\udc0d}}, n::Int, x)  where {\u03b1,\u03b2,\ud835\udc0d}\n    pFq((-n, -x, n+1+\u03b1+\u03b2),  (\u03b1+1, -\ud835\udc0d),  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 TravelingSalesmanExact, GLPK\nusing TravelingSalesmanHeuristics\nusing TravelingSalesmanExact: ATT, euclidean_distance\nusing TravelingSalesmanBenchmarks\nusing Plots\nusing Printf, Random\ngr(fmt=:svg)\n\n\nfunction get_plt_coords(cities)\n    n = length(cities)\n    inc(a) = a == n ? one(a) : a + 1\n    return [cities[inc(j)][1] for j = 0:n], [cities[inc(j)][2] for j = 0:n]\nend\nTravelingSalesmanExact.plot_cities(cities; kwargs...) = plot(get_plt_coords(cities)...; kwargs...)\nplot_cities!(cities; kwargs...) = plot!(get_plt_coords(cities)...; kwargs...)\n\nfunction plot_tours(cities, pairs; kwargs...)\n    plts = []\n    colors = sequential_palette(0, length(pairs)+1)[2:end]\n    for (index, (tour, label)) in enumerate(pairs)\n        plt = plot_cities(cities[tour], label = label, linewidth = 2,\n                            color = colors[index])\n        plot_cities!(cities; title=\"Comparison of tours\", st=:scatter, label=\"City locations\", markersize = 5, kwargs...)\n        push!(plts, plt)\n    end\n    return plts\nend\n\n\nRandom.seed!(155);\nN = 50\ncities = [100*rand(2) for _ = 1:N]\ncost = [ euclidean_distance(cities[i], cities[j]) for i=1:N, j=1:N ]\n\n\nt_exact, c_exact = get_optimal_tour(cost, with_optimizer(GLPK.Optimizer))\n\nc(q) = solve_tsp(cost; quality_factor = q)[2]\n\nqs = range(10, stop = 100, step = 10)\n\nplot(qs, c, xlabel=\"quality\", ylabel=\"Cost\", label=\"solve_tsp 1\", title=\"random cities\")\nfor j = 2:5\n    plot!(qs, c, label=\"solve_tsp $j\")\nend\nhline!([c_exact], label=\"Exact cost\")\n\n\nt_heuristic_100, c_heuristic_100 = solve_tsp(cost; quality_factor = 100)\nt_heuristic_40, c_heuristic_40 = solve_tsp(cost; quality_factor = 40)\n\nplts = plot_tours(cities, [\n    (t_heuristic_40, @sprintf(\"Heuristic; quality 40, cost=%.2f\",   c_heuristic_40)),\n    (t_heuristic_100, @sprintf(\"Heuristic; quality 100, cost=%.2f\", c_heuristic_100)),\n    (t_exact, @sprintf(\"Optimal tour; cost=%.2f\", c_exact))\n    ])\nfor plt in plts\n    display(plt)\nend\n\n\nfunction compare_cities(N)\n    cities = [100*rand(2) for _ = 1:N]\n    cost = [ euclidean_distance(cities[i], cities[j]) for i=1:N, j=1:N ]\n    t_exact, c_exact = get_optimal_tour(cost, with_optimizer(GLPK.Optimizer))\n\n    c(q) = solve_tsp(cost; quality_factor = q)[2]\n\n    qs = range(10, stop = 100, step = 10)\n\n    line_plt = plot(qs, c, xlabel=\"quality\", ylabel=\"Cost\", label=\"solve_tsp 1\", title=\"random cities\")\n    for j = 2:5\n        plot!(qs, c, label=\"solve_tsp $j\")\n    end\n    hline!([c_exact], label=\"Exact cost\")\n\n    t_heuristic_100, c_heuristic_100 = solve_tsp(cost; quality_factor = 100)\n    t_heuristic_40, c_heuristic_40 = solve_tsp(cost; quality_factor = 40)\n    city_plts = plot_tours(cities, [\n    (t_heuristic_40, @sprintf(\"Heuristic; quality 40, cost=%.2f\",   c_heuristic_40)),\n    (t_heuristic_100, @sprintf(\"Heuristic; quality 100, cost=%.2f\", c_heuristic_100)),\n    (t_exact, @sprintf(\"Optimal tour; cost=%.2f\", c_exact))\n    ])\n    return line_plt, city_plts...\nend\n\nfor j = 1:5\n    plts = compare_cities(50)\n    for plt in plts\n        display(plt)\n    end\nend\n\n\nfile = @isdefined(WEAVE_ARGS) ? WEAVE_ARGS[:file] : nothing\nTravelingSalesmanBenchmarks.bench_footer(file)\n\n", "meta": {"hexsha": "4af38cff1386391974a40ba38455cc10e22d187b", "size": 3150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/random_50_cities_cost_vs_quality.jl", "max_stars_repo_name": "ericphanson/TravelingSalesmanBenchmarks", "max_stars_repo_head_hexsha": "d5d9a328a16b200dd3efabef3b00ade96a2b2a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-15T15:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T01:56:35.000Z", "max_issues_repo_path": "script/random_50_cities_cost_vs_quality.jl", "max_issues_repo_name": "ericphanson/TravelingSalesmanBenchmarks.jl", "max_issues_repo_head_hexsha": "d5d9a328a16b200dd3efabef3b00ade96a2b2a36", "max_issues_repo_licenses": ["MIT"], "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/random_50_cities_cost_vs_quality.jl", "max_forks_repo_name": "ericphanson/TravelingSalesmanBenchmarks.jl", "max_forks_repo_head_hexsha": "d5d9a328a16b200dd3efabef3b00ade96a2b2a36", "max_forks_repo_licenses": ["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.5, "max_line_length": 121, "alphanum_fraction": 0.6720634921, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7786667683634333}}
{"text": "\nusing Tables\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\nfunction sir_ode!(du,u,p,t)\n    (S,I,R) = u\n    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -\u03b2*c*I/N*S\n        du[2] = \u03b2*c*I/N*S - \u03b3*I\n        du[3] = \u03b3*I\n    end\n    nothing\nend;\n\n\nt0 = 0.0\n\u03b4t = 0.1\ntmax = 40.0\nu0 = [990.0,10.0,0.0] # S,I,R\np = [0.05,10.0,0.25]; # \u03b2,c,\u03b3\n\n\nfunction euler(f, u0, p, \u03b4t, 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 + \u03b4t # Update time\n        u .= u .+ du.*\u03b4t # 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, \u03b4t, 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, \u03b4t, 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, \u2207fun!, 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\u2081, ..., a\u2099)``\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 * `\u2207fun!` 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\u2207fun!(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\u2096\u207f\u207a\u00b9 = a\u2096\u207f + \u03b4\u2096``\n\nConvergence is achieved when\n\n``|\u03b4\u1d4f / a\u2096\u2070| < \u03b5``\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 \u2207fun!(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, \u2207fun!, [0.5, 0.5, 0.5], 1e-8, 30)\n```\n\"\"\"\nfunction gauss_newton_fit(x::AbstractVector{T}, y::AbstractVector{T}, fun, \u2207fun!, 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    \u03b4ref = 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            \u2207fun!(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        \u03b4 = A\\b\n        a .+= \u03b4\n\n        # Verify convergence:\n        maxerr = maximum(abs, \u03b4./\u03b4ref)\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, \u2207fun!, 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\u2081,..., x\u2098, a\u2081, ..., a\u2099) = 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 * `\u2207fun!` 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\u2207fun!(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\u2096\u207f\u207a\u00b9 = a\u2096\u207f + \u03b4\u2096``\n\nConvergence is achieved when\n\n``|\u03b4\u1d4f / a\u2096\u2070| < \u03b5``\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 \u2207fun!(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, \u2207fun!, [0.5, 0.5, 0.5], 1e-8, 30)\n```\n\n\"\"\"\nfunction gauss_newton_generic_fit(x::AbstractMatrix{T}, fun, \u2207fun!, 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    \u03b4ref = 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            \u2207fun!(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        \u03b4 = A\\b\n        a .+= \u03b4\n\n        # Verify convergence:\n        maxerr = maximum(abs, \u03b4./\u03b4ref)\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, \u2207fun!, 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\u2081, ..., a\u2099)``\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 * `\u2207fun!` 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\u2207fun!(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\u2096\u207f\u207a\u00b9 = a\u2096\u207f + \u03b4\u2096``\n\nConvergence is achieved when\n\n``|\u03b4\u1d4f / a\u2096\u2070| < \u03b5``\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, \u2207fun!, [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    \u03b4 = a .* (one(T)/20)\n    f1 = zeros(T, P)\n    a .+= \u03b4\n    A = zeros(T, N, N)\n    b = zeros(T, N)\n\n    \u03b4ref = 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] -= \u03b4[k]\n                df[k] = (f1[i] - fun(xi, a)) / \u03b4[k]\n                a[k] += \u03b4[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        \u03b4 = A\\b\n        a .+= \u03b4\n        # Verify convergence:\n        maxerr = maximum(abs, \u03b4./\u03b4ref)\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": "using Test, Polyhedra\n\n@testset \"./src/LocalPolytope/facets.jl\" begin\n\nusing BellScenario\n\n@testset \"facets()\" begin\n    @testset \"3-simplex normalized\" begin\n        vertices = [[1,0],[0,1],[0,0]]\n        facet_dict = LocalPolytope.facets(vertices)\n\n        @test facet_dict[\"equalities\"] == Vector{Vector{Int64}}[]\n        @test facet_dict[\"facets\"] == [[-1,0,0],[0,-1,0],[1,1,1]]\n        @test length(keys(facet_dict)) == 2\n    end\n\n    @testset \"3-simplex generalized\" begin\n        vertices = [[1,0,0],[0,1,0],[0,0,1]]\n        facet_dict = LocalPolytope.facets(vertices)\n\n        @test facet_dict[\"equalities\"] == [[1,1,1,1]]\n        @test facet_dict[\"facets\"] == [[0,-1,0,0],[0,0,-1,0],[0,1,1,1]]\n        @test length(keys(facet_dict)) == 2\n    end\n\n    @testset \"CH inequalities\" begin\n        scenario = BipartiteNonSignaling(2,2,2,2)\n        vertices = LocalPolytope.vertices(scenario)\n        facet_dict = LocalPolytope.facets(vertices)\n\n        @test facet_dict[\"equalities\"] == Vector{Vector{Int64}}[]\n        @test facet_dict[\"facets\"] == [\n            [0, 0, 0, 0, -1, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 0, 0, 0, 0, -1, 0],\n            [-1, 0, 0, 0, 0, 1, 0, 0, 0], [-1, 0, 0, 0, 1, 0, 0, 0, 0],\n            [0, -1, 0, 0, 0, 0, 0, 1, 0], [0, -1, 0, 0, 0, 0, 1, 0, 0],\n            [0, 0, -1, 0, 0, 0, 1, 0, 0], [0, 0, -1, 0, 1, 0, 0, 0, 0],\n            [0, 0, 0, -1, 0, 0, 0, 1, 0], [0, 0, 0, -1, 0, 1, 0, 0, 0],\n            [-1, 0, -1, 0, 1, 1, 1, -1, 0], [-1, 0, 0, -1, 1, 1, -1, 1, 0],\n            [0, -1, -1, 0, 1, -1, 1, 1, 0], [0, -1, 0, -1, -1, 1, 1, 1, 0],\n            [0, 1, 0, 1, 0, 0, 0, -1, 1], [0, 1, 1, 0, 0, 0, -1, 0, 1],\n            [1, 0, 0, 1, 0, -1, 0, 0, 1], [1, 0, 1, 0, -1, 0, 0, 0, 1],\n            [0, 1, 0, 1, 1, -1, -1, -1, 1], [0, 1, 1, 0, -1, 1, -1, -1, 1],\n            [1, 0, 0, 1, -1, -1, 1, -1, 1], [1, 0, 1, 0, -1, -1, -1, 1, 1]\n        ]\n        @test length(keys(facet_dict)) == 2\n    end\nend\n\n@testset \"facets(::Polyhedron)\" begin\n    scenario = LocalSignaling(3,3,2)\n    local_poly = LocalPolytope.vrep(scenario)\n\n    @test !hrepiscomputed(local_poly)\n\n    facets = LocalPolytope.facets(local_poly)\n    @test length(facets) == 15\n\n    @test hrepiscomputed(local_poly)\n\n    match_vertices = LocalPolytope.vertices(scenario)\n    match_facets = LocalPolytope.facets(match_vertices)[\"facets\"]\n\n    @test facets == match_facets\nend\n\nend\n", "meta": {"hexsha": "c0472e7c1c31e74e0c851d8861be99ef3e18b73f", "size": 2440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit/LocalPolytope/facets.jl", "max_stars_repo_name": "ChitambarLab/BellScenario.jl", "max_stars_repo_head_hexsha": "74932c1d6efa5960ce8ded00599d73f914fa2281", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-01T00:02:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T18:38:27.000Z", "max_issues_repo_path": "test/unit/LocalPolytope/facets.jl", "max_issues_repo_name": "ChitambarLab/BellScenario.jl", "max_issues_repo_head_hexsha": "74932c1d6efa5960ce8ded00599d73f914fa2281", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-08-01T12:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T00:49:45.000Z", "max_forks_repo_path": "test/unit/LocalPolytope/facets.jl", "max_forks_repo_name": "ChitambarLab/BellScenario.jl", "max_forks_repo_head_hexsha": "74932c1d6efa5960ce8ded00599d73f914fa2281", "max_forks_repo_licenses": ["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.8823529412, "max_line_length": 75, "alphanum_fraction": 0.4922131148, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828604, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7786555761849732}}
{"text": "@testset \"Information Measures\" begin\n\n    s = res\"ARNDCQEGHILKMFPSTWYV-\"\n    r = reverse(s)\n    g = res\"GGGGGGGGGGGGGGGGGGGGG\"\n    Pg = probabilities(g)\n    Pgg = probabilities(g,g)\n    Pggg = probabilities(g,g,g)\n    Ps = probabilities(s)\n    Pss = probabilities(s,s)\n    Psr = probabilities(s,r)\n    Psss = probabilities(s,s,s)\n    count_random = count(Residue[], Residue[], pseudocounts=AdditiveSmoothing(1.0))\n    prob_random = probabilities(Residue[], Residue[], pseudocounts=AdditiveSmoothing(1.0))\n\n    @testset \"Entropy\" begin\n\n        @testset \"H(X)\" begin\n\n            @test entropy(Pg) \u2248 0.0\n            @test entropy(Ps) \u2248 log(20.0)\n            @test entropy(Ps, 2) \u2248 log(2, 20.0)\n        end\n\n        @testset \"Joint Entropy: H(X,Y)\" begin\n\n            @test entropy(Pgg) \u2248 0.0\n            @test entropy(Pss) \u2248 log(20.0)\n            @test entropy(Psr) \u2248 log(19.0)\n            @test entropy(Pss, 2) \u2248 log(2, 20.0)\n            @test entropy(count_random) \u2248 log(400.0)\n            @test entropy(prob_random) \u2248 log(400.0)\n        end\n\n        @testset \"Joint Entropy: H(X,Y,Z)\" begin\n\n            @test entropy(Pggg) \u2248 0.0\n            @test entropy(Psss) \u2248 log(20)\n        end\n\n        @testset \"Using counts\" begin\n\n            @test entropy(count(g,g)) \u2248 entropy(Pgg)\n            @test entropy(count(s,s)) \u2248 entropy(Pss)\n            @test entropy(count(s,r)) \u2248 entropy(Psr)\n        end\n    end\n\n    @testset \"Kullback-Leibler\" begin\n\n        @test kullback_leibler(Ps, [1.0/20.0 for i in 1:20]) \u2248 0.0\n        @test kullback_leibler(Ps, Ps) \u2248 0.0\n        @test kullback_leibler(Ps, BLOSUM62_Pi) \u2248 kullback_leibler(Ps)\n        @test kullback_leibler(Ps, BLOSUM62_Pi) \u2248 mapreduce(i->0.05*log(0.05/BLOSUM62_Pi[i]),+,1:20)\n        @test kullback_leibler(Psr, Psr) \u2248 0.0\n    end\n\n    @testset \"Mutual Information\" begin\n\n        @test mutual_information(Pgg) \u2248 0.0\n\n        P = gettablearray(prob_random)\n        Q = getmarginalsarray(prob_random)[:,1] * getmarginalsarray(prob_random)[:,2]' # 0.002500000000000001\n        @test mutual_information(prob_random) \u2248 sum(P .* log.(P./Q)) # So, it's != 0.0\n        @test mutual_information(count_random) \u2248 0.0 # It's more accurate\n\n        Pgs = probabilities(g,s)\n        P = gettablearray(Pgs)\n        Q = getmarginalsarray(Pgs)[:,1] * getmarginalsarray(Pgs)[:,2]' # 0.05000000000000002\n        @test mutual_information(Pgs) \u2248 mapreduce(x -> isnan(x) ? 0.0 : x, +, P.*log.(P./Q))\n        @test mutual_information(count(g,s)) \u2248 0.0 # It's more accurate\n\n        # MI(X,Y)=H(X)+H(Y)-H(X,Y)\n\n        @test mutual_information(Psr) \u2248 (marginal_entropy(Psr,1) +\n                                         marginal_entropy(Psr,2) - entropy(Psr))\n\n        @test mutual_information(Pss) \u2248 (marginal_entropy(Pss,1) +\n                                         marginal_entropy(Pss,2) - entropy(Pss))\n\n        @test mutual_information(Psr,2) \u2248 (marginal_entropy(Psr,1,2) +\n                                           marginal_entropy(Psr,2,2) - entropy(Psr,2))\n\n        @test mutual_information(Pss,20) \u2248 (marginal_entropy(Pss,1,20) +\n                                            marginal_entropy(Pss,2,20) - entropy(Pss,20))\n\n        @test isapprox(mutual_information(prob_random), 0.0, atol=1e-15)\n        @test mutual_information(count_random) \u2248 0.0\n        @test isapprox(mutual_information(count_random), marginal_entropy(count_random,1) +\n                       marginal_entropy(count_random,2) - entropy(count_random), atol=1e-13)\n\n        @testset \"Using counts\" begin\n\n            @test mutual_information(count_random) \u2248 0.0\n            @test mutual_information(count(g,g)) \u2248 mutual_information(Pgg)\n            @test mutual_information(count(s,s)) \u2248 mutual_information(Pss)\n            @test mutual_information(count(s,r)) \u2248 mutual_information(Psr)\n        end\n\n        @testset \"MI(X,Y,Z)\" begin\n\n            @test mutual_information(Pggg) \u2248 0.0\n            @test mutual_information(probabilities(g,s,r)) \u2248 0.0\n            @test mutual_information(probabilities(s,s,r)) \u2248 mutual_information(count(s,s,r))\n\n            # MI(X,Y,Z) = H(X) + H(Y) + H(Z) - H(X,Y) - H(X,Z) - H(Y,Z) + H(X,Y,Z)\n            @test mutual_information(Psss) \u2248 mutual_information(count(s,s,s))\n            @test mutual_information(Psss) \u2248 (marginal_entropy(Psss, 1) +\n                                              marginal_entropy(Psss, 2) +\n                                              marginal_entropy(Psss, 3) -\n                                              entropy(Pss) - entropy(Pss) -\n                                              entropy(Pss) + entropy(Psss))\n\n            # MI(X,Y,Z) <= min{ H(X,Y), H(X,Z), H(Y,Z) }\n            @test mutual_information(Psss) \u2248 mutual_information(Pss)\n        end\n\n        @testset \"Pairwise Gap Percentage\" begin\n\n            @test gap_union_percentage(count(res\"AA--\", res\"--AA\", alphabet=GappedAlphabet())) \u2248 100.0\n            @test gap_intersection_percentage(count(res\"AA--\", res\"--AA\", alphabet=GappedAlphabet())) \u2248 0.0\n\n            @test gap_union_percentage(count(res\"AA--\", res\"--AA\", alphabet=GappedAlphabet(), weights=Weights([.25, .25, .25, .25]))) \u2248 100.0\n            @test gap_intersection_percentage(count(res\"AA--\", res\"--AA\", alphabet=GappedAlphabet(), weights=Weights([.25, .25, .25, .25]))) \u2248 0.0\n\n            @test gap_union_percentage(count(res\"AAA-\", res\"AA--\", alphabet=GappedAlphabet())) \u2248 50.0\n            @test gap_intersection_percentage(count(res\"AAA-\", res\"AA--\", alphabet=GappedAlphabet())) \u2248 25.0\n\n            @test gap_union_percentage(count(res\"AAA-\", res\"AA--\", alphabet=GappedAlphabet(), weights=Weights([.2, .2, .2, .4]))) \u2248 60.0\n            @test gap_intersection_percentage(count(res\"AAA-\", res\"AA--\", alphabet=GappedAlphabet(), weights=Weights([.2, .2, .2, .4]))) \u2248 40.0\n        end\n    end\nend\n", "meta": {"hexsha": "ed1811f6a0979aaa7f2dfe008f3aaceceee749ff", "size": 5798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Information/InformationMeasures.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MIToS.jl-51bafb47-8a16-5ded-8b04-24ef4eede0b5", "max_stars_repo_head_hexsha": "6237d5a885e43f49b74e0a9e56120012711b2d46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2015-08-13T02:11:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T12:22:31.000Z", "max_issues_repo_path": "test/Information/InformationMeasures.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MIToS.jl-51bafb47-8a16-5ded-8b04-24ef4eede0b5", "max_issues_repo_head_hexsha": "6237d5a885e43f49b74e0a9e56120012711b2d46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2015-06-19T22:44:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T15:40:25.000Z", "max_forks_repo_path": "test/Information/InformationMeasures.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MIToS.jl-51bafb47-8a16-5ded-8b04-24ef4eede0b5", "max_forks_repo_head_hexsha": "6237d5a885e43f49b74e0a9e56120012711b2d46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2015-08-11T02:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T00:13:20.000Z", "avg_line_length": 43.2686567164, "max_line_length": 146, "alphanum_fraction": 0.5714039324, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7786544756646578}}
{"text": "module problem117\n\ndescription = \"\"\"\nRed, green, and blue tiles\nUsing a combination of black square tiles and oblong tiles chosen from: \n red tiles measuring two units, \n green tiles measuring three units, \n and blue tiles measuring four units, \n it is possible to tile a row measuring five units in length in exactly fifteen different ways.\n\nHow many ways can a row measuring fifty units in length be tiled?\"\"\"\n\n# Fill function, based on problems 114, 115, 116\nfunction F(n :: Integer, memo = zeros(Int, n))\n  # Base case: no space remaining in the row\n  if n < 2 return 0 end\n\n  # Recursive case, count 1 for each placement of block at positions 1:n-m+1, and all ways of\n  # filling the remaining space at the end of the row after each placement, memoizing results.\n  if memo[n] == 0\n    total = 0\n    for m=2:4, blockpos = 1:(n-m+1)\n      total += 1 + F(n - blockpos - m + 1, memo)\n    end\n    memo[n] = total\n  end\n  return memo[n]\nend\n\nfunction mixed_fill_count(n :: Integer)\n  return 1 + F(n) # +1 for empty row being a valid solution\nend\n\n\nusing Base.Test\n\n@test mixed_fill_count(5) == 15\n\nend", "meta": {"hexsha": "044558ba6c40d44c902f95dafb01bfbd8d7352e0", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem117.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/problem117.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/problem117.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": 28.2051282051, "max_line_length": 95, "alphanum_fraction": 0.7018181818, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7786544741422509}}
{"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": "# In this exercise we will try to predict the quality class of wines given some chemical characteristics\n\n# In detail, the attributes of this dataset are:\n#   1) Alcohol\n#   2) Malic acid\n#   3) Ash\n#   4) Alcalinity of ash  \n#   5) Magnesium\n#   6) Total phenols\n#   7) Flavanoids\n#   8) Nonflavanoid phenols\n#   9) Proanthocyanins\n#   10) Color intensity\n#   11) Hue\n#   12) OD280/OD315 of diluted wines\n#   13) Proline \n\n# Further information concerning this dataset can be found online on the [UCI Machine Learning Repository dedicated page](https://archive.ics.uci.edu/ml/datasets/wine) or in particular on [this file](https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.names)\n\n# Our prediction concerns the quality class of the wine (1, 2 or 3) that is given as first column of the data.\n\n# 1) Start by setting the working directory to the directory of this file and activate it. If you have the provided `Manifest.toml` file in the directory, just run `Pkg.instantiate()`, otherwise manually add the packages Pipe, HTTP, Plots and BetaML.\n# Also, seed the random seed with the integer `123`.\n\n\n# 2) Load the packages/modules DelimitedFiles, Pipe, HTTP, Plots, BetaML\n\n\n# 3) Load from internet or from local file the input data as a Matrix.\n# You can use `readdlm`` using the comma as field separator.\ndataURL=\"https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data\"\n\n\n# 4) Now create the X matrix of features using the second to final columns of the data you loaded above and the Y vector by taking the 1st column. Transform the Y vector to a vector of integers using the `Int()` function (broadcasted). Make shure you have a 178\u00d713 matrix and a 178 elements vector\n\n\n# 5) Partition the data in (xtrain,xval) and (ytrain,yval) keeping 80% of the data for training and reserving 35% for testing. Keep the default option to shuffle the data, as the input data isn't.\n\n\n# 6) As the output is multinomial we need to encode ytrain. We use the `oneHotEncoder()` function to make `ytrain_oh`\n\n\n# 7) Define a Neural Network model with the following characteristics:\n#   - 3 dense layers with respectively 13, 20 and 3 nodes and activation function relu\n#   - a `VectorFunctionLayer` with 3 nodes and `softmax` as activation function\n#   - `crossEntropy` as the neural network cost function\n\n\n# 8) Train your model using `ytrain` and a scaled version of `xtrain`` (where all columns have zero mean and 1 standard deviaiton) for 100 epochs and use a batch size of 6 records.\n# Save the output of your training function to `trainingLogs`\n\n\n# 9) Predict the training labels y\u0302train and the validation labels y\u0302val. Recall you did the training on the scaled features!\n\n\n# 10) Compute the train and test accuracies using the function `accuracy`\n\n\n# 11) Compute and print a ConfutionMatrix of the validation data true vs. predicted\n\n\n# 12) Run the following commands to plots the average loss per epoch \nplot(trainingLogs.\u03f5_epochs)\n\n\n# 13) (Optional) Run the same workflow without scaling the data or using `squaredCost` as cost function. How this affect the quality of your predictions ? \n", "meta": {"hexsha": "afa221a53a7141ac08e3fb7dff0364dd67c17164", "size": 3117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessonsMaterial/04_NN/wineClass/WineClass.jl", "max_stars_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_stars_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-26T15:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T13:05:52.000Z", "max_issues_repo_path": "lessonsMaterial/04_NN/wineClass/WineClass.jl", "max_issues_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_issues_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "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": "lessonsMaterial/04_NN/wineClass/WineClass.jl", "max_forks_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_forks_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-26T08:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T08:06:40.000Z", "avg_line_length": 46.5223880597, "max_line_length": 297, "alphanum_fraction": 0.7526467757, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7786544679290149}}
{"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    \u03bc ~ 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(\u03bc[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, \u03b1, K)\n    N = length(y)\n    crm = DirichletProcess(\u03b1)\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    \u03bc ~ filldist(Normal(), L)\n\n    # Observations\n    for n = 1:N\n        y[n] ~ Normal(\u03bc[z[n]], 1.0)\n    end\nend\n\nimm_stick_tarray_example(y = data_neal, \u03b1 = \u03b1_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 \u0393 = gamma\n\n# Coefficients in the Jacobi polynomial recurrence relations.\na(\u03b1, \u03b2, n) = 2/(2n+\u03b1+\u03b2) * \u221a(n * (n+\u03b1+\u03b2) * (n+\u03b1) * (n+\u03b2) / (2n+\u03b1+\u03b2-1) / (2n+\u03b1+\u03b2+1))\nb(\u03b1, \u03b2, n) = -(\u03b1^2 - \u03b2^2) / (2n+\u03b1+\u03b2) / (2n+\u03b1+\u03b2+2)\n\n\" Evaluates the Jacobi polynomial P\u2099\u1d45\u1d5d(x). \"\nfunction jacobi(x, \u03b1, \u03b2, n::Int)\n    P\u1d45\u1d5d = n <= 1 ? OffsetArray(zeros(2), 0:1) : OffsetArray(zeros(n+1), 0:n)\n    P\u1d45\u1d5d[0] = \u221a(2.0^-(\u03b1+\u03b2+1) * \u0393(\u03b1+\u03b2+2) / \u0393(\u03b1+1) / \u0393(\u03b2+1))\n    P\u1d45\u1d5d[1] = P\u1d45\u1d5d[0]/2 * \u221a((\u03b1+\u03b2+3) / (\u03b1+1) / (\u03b2+1)) * ((\u03b1+\u03b2+2)*x + \u03b1 - \u03b2)\n    for n\u2032 in 1:n-1\n        P\u1d45\u1d5d[n\u2032+1] = ((x - b(\u03b1,\u03b2,n\u2032)) * P\u1d45\u1d5d[n\u2032] - a(\u03b1,\u03b2,n\u2032) * P\u1d45\u1d5d[n\u2032-1]) / a(\u03b1, \u03b2, n\u2032+1)\n    end\n    return P\u1d45\u1d5d[n]\nend\n\n\" Evaluates the derivative of the Jacobi polynomial P\u2099\u1d45\u1d5d(x). \"\n\u2202jacobi(x, \u03b1, \u03b2, n::Int) = n == 0 ? 0 : \u221a(n * (n+\u03b1+\u03b2+1)) * jacobi(x, \u03b1+1, \u03b2+1, n-1)\n\n\" Guassian quadrature points and weights for the Jacobi polynomial P\u2099\u1d45\u1d5d. \"\nfunction jacobi_gauss_quadrature(\u03b1, \u03b2, N)\n    N == 0 && return [(\u03b1-\u03b2) / (\u03b1+\u03b2+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(\u03b1, \u03b2, n)\n        ev[n] = a(\u03b1, \u03b2, 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    (\u03b1 + \u03b2) \u2248 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^(\u03b1+\u03b2+1) / (\u03b1+\u03b2+1)\n    @. w *= factorial(\u03b1) * factorial(\u03b2) / factorial(\u03b1+\u03b2)\n\n    return x, w\nend\n\n\" Guass-Labatto quadrature points for the Jacobi Polynomial P\u2099\u1d45\u1d5d. \"\nfunction jacobi_gauss_lobatto(\u03b1, \u03b2, 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(\u03b1+1, \u03b2+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.\u03c3 * O.\u03c3 / 2) * O.t) / (O.\u03c3 * \u221aO.t)\n    d2 = d1 - O.\u03c3 * \u221aO.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 * \u03c0) * 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9088c5d0-f07c-404f-8e08-2c8585f86a2f\nimport Random\n\n# \u2554\u2550\u2561 fc9d6f80-70c1-4518-b9db-29c6e3e2d280\nimport Statistics\n\n# \u2554\u2550\u2561 6a0019bf-ab70-4095-ac52-7606e401d9a5\nimport LinearAlgebra\n\n# \u2554\u2550\u2561 b8447232-6b1d-4b3a-8d11-a9a2da1cf31b\nJuTools = ingredients(\"../tools.jl\").JuTools\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8c3fa961-d88d-4e28-98e9-18b8804c568e\nX_data, Y_data = JuTools.data_generate_linear_2d()\n\n# \u2554\u2550\u2561 6341ae48-9cda-4019-bfe6-443caf8788aa\nY_data .= Y_data .* 2.0 .- 1.0 # convert from {0,1} to {-1,1}\n\n# \u2554\u2550\u2561 500703d2-e315-44c7-8d6c-c36f40b815df\nX_train, X_test, Y_train, Y_test = JuTools.split_data(X_data, Y_data)\n\n# \u2554\u2550\u2561 7531e45c-95fd-4664-8c37-3364aae7020b\n@show size(X_train)\n\n# \u2554\u2550\u2561 747fabf5-fd7b-40cc-b5da-b15f6925cff0\n@show size(X_test)\n\n# \u2554\u2550\u2561 9504574b-2281-4f8a-83d5-3eea38acec53\n@show size(Y_train)\n\n# \u2554\u2550\u2561 c496efb2-5a50-4131-bd65-e9025a3273a4\n@show size(Y_test)\n\n# \u2554\u2550\u2561 46e9b187-d445-4efe-b4f2-ad824e5ec832\nweight_test = WeightsLinearSVM(1.0, Random.randn(size(X_data)[2]), Random.randn())\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 50e8d679-d4fc-4ed8-9868-b59cc4151d2c\ncost(X_data, Y_data, weight_test)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fb710b22-79b0-477c-b2a6-f85fe8b4271a\nJuTools.compute_accuracy(predict(X_test, weights), Y_test)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1b11d952-a35f-4778-8a7f-779eb72f0436\nJuTools.compute_accuracy(predict(X_test, X_train, Y_train, weights_svm), Y_test)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25006a41e9d0-c58c-11eb-078e-c36bf22a38d2\n# \u255f\u25009cfc2328-0e4f-4a86-944c-31c0c133fe9a\n# \u255f\u250030975066-eb17-4682-bda1-fd77f9d44734\n# \u2560\u25509088c5d0-f07c-404f-8e08-2c8585f86a2f\n# \u2560\u2550fc9d6f80-70c1-4518-b9db-29c6e3e2d280\n# \u2560\u25506a0019bf-ab70-4095-ac52-7606e401d9a5\n# \u2560\u2550b8447232-6b1d-4b3a-8d11-a9a2da1cf31b\n# \u255f\u2500e4380307-4abe-4a20-9127-e608d1a5fa6e\n# \u2560\u25506841f5fe-45ad-4f71-84d5-368d196a40ab\n# \u2560\u2550a093820c-20a0-4af1-98b3-ea92ad37bc77\n# \u2560\u25508c3fa961-d88d-4e28-98e9-18b8804c568e\n# \u2560\u25506341ae48-9cda-4019-bfe6-443caf8788aa\n# \u2560\u2550500703d2-e315-44c7-8d6c-c36f40b815df\n# \u2560\u25507531e45c-95fd-4664-8c37-3364aae7020b\n# \u2560\u2550747fabf5-fd7b-40cc-b5da-b15f6925cff0\n# \u2560\u25509504574b-2281-4f8a-83d5-3eea38acec53\n# \u2560\u2550c496efb2-5a50-4131-bd65-e9025a3273a4\n# \u2560\u255046e9b187-d445-4efe-b4f2-ad824e5ec832\n# \u2560\u255050e8d679-d4fc-4ed8-9868-b59cc4151d2c\n# \u2560\u25508adbc614-9440-42d3-9672-f3b816e114a4\n# \u2560\u2550633040d0-651b-427f-a5a8-83124bbea43b\n# \u2560\u2550ea07e163-d2a0-4447-9239-64d1aee8b3a0\n# \u2560\u2550aafac217-757c-442a-88b1-17e8895f703a\n# \u2560\u2550ec256a57-ea44-4f73-af5b-f5e09ba2fec1\n# \u2560\u2550fb710b22-79b0-477c-b2a6-f85fe8b4271a\n# \u255f\u250077bd6c88-335f-46a9-a46b-3d3596d54bf9\n# \u2560\u2550111304b2-bfbb-4875-838a-93c153d452be\n# \u2560\u25503f6728b3-fb75-4783-ab6e-96ae6301f7cb\n# \u2560\u2550e3b0cd51-75bc-41aa-96eb-251b376a183d\n# \u2560\u25504a0ee69a-6151-423b-9227-65fa4e9f2b5e\n# \u2560\u255085939fbf-de18-46d8-9708-dec8a85f49dd\n# \u2560\u255099d0a23e-e06b-4c13-89a7-62aeebf7c559\n# \u2560\u2550ece26477-6e53-4536-a6a8-61947cb2815e\n# \u2560\u255059c861e3-8c4d-450d-b727-c59cdf17a84f\n# \u2560\u2550882b95f5-6261-42d4-91b2-16a7ce9c1aa4\n# \u2560\u2550dde248cd-6fac-4c59-877d-58e5b8f06685\n# \u2560\u255047846484-1824-41b3-b26d-e4e3953fd079\n# \u2560\u2550fdd56685-18d1-47b5-9b9c-27090422f250\n# \u2560\u25501b11d952-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 \u00abname\u00bb end\n# abstract type \u00abname\u00bb <: \u00absupertype\u00bb 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 \u00abname\u00bb \u00abbits\u00bb end\n# primitive type \u00abname\u00bb <: \u00absupertype\u00bb \u00abbits\u00bb 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 \u2013 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    \u0398::T\nend\n\nPolar(r::Real,\u0398::Real) = Polar(promote(r,\u0398)...)\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  (\u03b2,c,\u03b3) = p\n  N = S+I+R\n  infection = \u03b2*c*I/N*S\n  recovery = \u03b3*I\n  [infection,recovery]\nend;\n\n\nsir_transitions = float.([[-1  1  0];\n                          [ 0 -1  1]])\n\n\n\u03b4t = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:\u03b4t: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]; # \u03b2,c,\u03b3\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() \u306f\uff0c\u5206\u5272\u8868\u306e\u30de\u30b9\u76ee\u306e\u3046\u3061\u306b 0 \u304c\u3042\u308b\u3088\u3046\u306a\u5834\u5408\u3067\u3082\uff0c\u6b63\u78ba\u306b lambda=0.0 \u306b\u3057\u305f\u5834\u5408\u306e\uff0c\u6b63\u3057\u3044\u7b54\u3048\u3092\u8fd4\u3059\u3002\n\n\"\"\"\n\nusing Distributions\nfunction trueG2_test(x; correct=false)\n    # \u30bb\u30eb\u306b 0 \u304c\u3042\u3063\u3066\u3082\u6b63\u3057\u3044\u7b54\u3048\u3092\u51fa\u3059\n    # correct=true \u3067\uff0c\u9023\u7d9a\u6027\u306e\u88dc\u6b63\u3082\u884c\u3046\u3053\u3068\u304c\u3067\u304d\u308b\n    ln(n) = sum(n .== 0 ? 0 : n .* log(n) for n in vcat(n...))\n    nrows, ncols = size(x)\n    n = sum(x) # \u5168\u30b5\u30f3\u30d7\u30eb\u30b5\u30a4\u30ba\n    n1 = sum(x, dims=2) # \u884c\u548c\n    n2 = sum(x, dims=1) # \u5217\u548c\n    G2 = 2*(ln(x) - ln(n1) - ln(n2) + ln(n)) # G \u7d71\u8a08\u91cf\n    correct && (G2 /= 1 + (n * sum(1 ./ n1) - 1) * (n * sum(1 ./ n2) - 1) / (6n * nrows * ncols)) # \u9023\u7d9a\u6027\u306e\u88dc\u6b63\n    df = (nrows - 1) * (ncols - 1) # G \u306e\u81ea\u7531\u5ea6\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\u4f7f\u7528\u6cd5\n\njulia> z = [4 5 2 0\n            0 7 6 1\n            1 0 3 1]\n3\u00d74 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\u307e\u305f\uff0c\u30d4\u30a2\u30bd\u30f3\u306e \u03c72\n\u691c\u5b9a\u3067\u306f 2\u00d72 \u5206\u5272\u8868\u306e\u5834\u5408\u306b\u3057\u304b\u9023\u7d9a\u6027\u306e\u88dc\u6b63\u306f\u884c\u3048\u306a\u3044\u304c\uff0cG2 \u691c\u5b9a\u306f\u5206\u5272\u8868\u306e\u5927\u304d\u3055\u306b\u95a2\u308f\u3089\u305a\uff0c\u9023\u7d9a\u6027\u306e\u88dc\u6b63\u3092\u884c\u3046\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u4e0a\u306b\u793a\u3057\u305f\u95a2\u6570 trueG2_test() \u3067 correct=true \u3092\u6307\u5b9a\u3059\u308c\u3070\u3088\u3044\u3002\n\njulia> trueG2_test(z, correct=true) # \u9023\u7d9a\u6027\u306e\u88dc\u6b63\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": "function predict_svm(\u03b8,x)\n\treturn dot(\u03b8,x) > 0 ? 1 : -1\nend\n\nfunction predict_logreg(theta,x)\n\tprediction =  1 / ( 1 + exp(dot(-theta,x)))\n\tif prediction  < 0.5\n\t\treturn -1\n\telse\n\t\treturn 1\n\tend\nend\n\nfunction evaluate(X,y,theta,mode,verbose=false)\n\tpositiveHits = 0\n\tfor i in 1:size(X,1)\n\t\tif mode == \"logreg\"\n\t\t\tlabel = predict_logreg(theta,X[i:i,:])\n\t\telseif mode == \"svm\"\n\t\t\tlabel = predict_svm(theta,X[i:i,:])\n\t\telse\n\t\t\terror(\"Prediction mode not aviable\")\n\t\tend\n\t\tif label == y[i]\n\t\t\tpositiveHits += 1\n\t\tend\n\t\tif label == 1\n\t\t\tlabel = \"+1\"\n\t\tend\n\t\tlabelString = \"-1.0\"\n\t\tif y[i] == 1.0\n\t\t\tlabelString = \"+1.0\"\n\t\tend\n\t\tif verbose\n\t\t\t@printf(\"Prediction : %s | Label : %s | Accuracy %f \\n\",label,labelString,positiveHits / i)\n\t\tend\n\tend\n\treturn positiveHits / size(X,1)\nend\n", "meta": {"hexsha": "7d2a27971ad22831b0cbe282bb11df31eb9900a0", "size": 777, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evaluate/Evaluate.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/evaluate/Evaluate.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/evaluate/Evaluate.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": 19.425, "max_line_length": 94, "alphanum_fraction": 0.6254826255, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7785178313108525}}
{"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": "module TestModels\n\n    using LinearAlgebra\n\n    export p_fun, \n        model,\n        set_locations,\n        set_indices \n\n    export HyperCube,\n        Polytope,\n        HyperSphere,\n        OddShape\n\n    \"\"\"\n        model(parms, args...; kwargs...) \n    \n    Model function for test models. It is an identity function. \n\n    # Arguments\n\n    - `parms`: a proposed location \n\n    \"\"\"\n    model(parms, args...; kwargs...) = parms\n\n    \"\"\"\n        HyperCube\n\n    A hypercube oject divided into partitions. \n\n    # Field \n\n    - `p_bounds`: a vector of boundaries of partitions\n    \"\"\"\n    struct HyperCube\n        p_bounds::Vector{Float64}\n    end\n\n    \"\"\"\n        p_fun(location, hypercube::HyperCube, args...; kwargs...)\n\n    Returns the qualitative pattern associated with a hypercube. \n\n    # Arguments\n\n    - 'location`: location of chain in the hypercube\n    - `p_bounds`: boundaries of partitions for each dimension \n\n    \"\"\"\n    function p_fun(location, hypercube::HyperCube, args...; kwargs...)\n        p_bounds = hypercube.p_bounds\n        nb = length(p_bounds)\n        nd = length(location)\n        vals = fill(-100, nd)\n        for j in 1:nd\n            for i in 1:(nb-1) \n                if (location[j] \u2265 p_bounds[i]) && (location[j] \u2264 p_bounds[i+1])\n                    vals[j] = i \n                    continue\n                end\n            end\n        end\n        return vals\n    end\n\n    \"\"\"\n        Polytope\n    \n    A polytope object containing centroid locations for each partition \n\n    # Fields\n\n    - `location`: location of centroid for each partition\n    \"\"\"\n    struct Polytope\n        location::Vector{Float64}\n    end\n\n\n    \"\"\"\n        p_fun(location, points::Vector{Polytope}, args...; kwargs...)\n\n    Returns the qualitative pattern associated with a polytope. \n\n    # Arguments\n\n    - 'location`: location of chain in the hypercube\n    - `points`: a vector of polytopes containing locations\n\n    \"\"\"\n    function p_fun(location, points::Vector{Polytope}, args...; kwargs...)\n        distances = map(p -> norm(location .- p.location), points)\n        _,idx = findmin(distances)\n        return idx\n    end\n\n    \"\"\"\n        HyperSphere\n\n    A hypersphere object with arbitrary dimensionality. \n\n    # Fields \n\n    - `location`: a vector representing the centroid of the hypersphere\n    - `radius`: the radius of the hypersphere\n    \"\"\"\n    mutable struct HyperSphere\n        location::Vector{Float64}\n        radius::Float64\n    end\n    \n    function HyperSphere(;location, radius)\n        return HyperSphere(location, radius)\n    end\n    \n    function in_contact(v1::HyperSphere, v2::HyperSphere)\n        dist = norm(v1.location - v2.location)\n        return dist \u2264 max(v1.radius, v2.radius)\n    end\n    \n    function in_contact(v1::HyperSphere, proposal::Vector{<:Number})\n        dist = norm(v1.location - proposal)\n        return dist \u2264 v1.radius\n    end\n    \n    not_valid(v, vs)  = any(x -> in_contact(v, x), vs) || out_of_bounds(v)\n    \n    out_of_bounds(v) = any((v.location .- v.radius) .< 0) || any((v.location .+ v.radius) .> 1)\n\n    \"\"\"\n        set_locations(r_dist, n_dims, n_obj)\n    \n    Sets the location of hypspheres within a unit hypercube\n    \n    # Arguments\n\n    - `r_dist`: a function that samples a value for the radius \n    - `n_dims`: the number of dimensions of the hypersphere \n    - `n_obj`: the number of hyperspheres\n\n    \"\"\"\n    function set_locations(r_dist, n_dims, n_obj)\n        hs = [HyperSphere(;location = rand(n_dims), radius = r_dist())]\n        for i in 1:(n_obj-1)\n            h = HyperSphere(;location = rand(n_dims), radius = r_dist())\n            while not_valid(h, hs)\n                h.location = rand(n_dims)\n            end\n            push!(hs, h)\n        end\n        return hs\n    end\n\n    \"\"\"\n        p_fun(location, hyperspheres::Vector{HyperSphere}, args...; kwargs...)\n\n    Returns the qualitative data pattern for hypspheres embedded in a hypercube. -100 is\n    returned if the proposed location is not in a hypsphere. Otherwise, an index of the hypersphere \n    in which the proposed location is contained. \n\n    # Arguments\n\n    - `location`: a proposed location in a unit hypercube\n    - `hyperspheres`: a vector of `HyperSphere` objects\n    \"\"\"\n    function p_fun(location, hyperspheres::Vector{HyperSphere}, args...; kwargs...)\n        for (i,h) in enumerate(hyperspheres)\n            in_contact(h, location) ? (return i) : nothing\n        end\n        # invalid area (not in a hypersphere)\n        return -100 \n    end\n\n\"\"\"\n        OddShape\n\n    An odd shape the is found by (1) initializing a shape at random partition and adding it to set of indices, (2)\n    selecting random indices from the set, (3) adding an ajecent index to the set of indices, and repeating 2-3.\n\n    # Fields \n\n    - `indices`: a vector of vectors that represent the location of the odd shape\n    - `p_bounds`: the partition boundaries for each dimension\n    \"\"\"\n    mutable struct OddShape{T1,T2}\n        indices::T1\n        p_bounds::T2\n        shape_ids::Vector{Int}\n        n_shapes::Int\n    end\n\n    function OddShape(indices, p_bounds, n_cells::Vector{Int})\n        shape_ids = vcat(fill.(1:length(n_cells), n_cells)...)\n        n_shapes = length(n_cells)\n        return OddShape(indices, p_bounds, shape_ids, n_shapes)\n    end\n    \n    \"\"\"\n        set_locations(r_dist, n_dims, n_obj)\n    \n    Sets the location of `OddShape` within a unit hypercube\n    \n    # Arguments\n\n    - `n_dims`: the number of dimensions of the hypersphere\n    - `n_part`: number of partitions along a dimension \n    - `n_cells`: the number of cells per shape\n    \"\"\"\n    function set_indices(n_dims, n_part, n_cells)\n        n_shapes = length(n_cells)\n        indices = Vector{Vector{Int}}()\n        for s in 1:n_shapes\n            index = rand(1:n_part, n_dims)\n            push!(indices, index)\n            for i in 1:(n_cells[s]-1)\n                while not_valid(indices, index, n_part)\n                    index = propose(indices)\n                end\n                push!(indices, index)\n            end\n        end\n        return indices\n    end\n\n    function not_valid(xs, x, n_part)\n        return (x \u2208 xs) || any(x .< 1) || any(x .> n_part)\n    end\n\n    function propose(indices)\n        index = deepcopy(rand(indices))\n        i = rand(1:length(index))\n        index[i] += rand() \u2264 .5 ? 1 : -1\n        return index\n    end\n\n    \"\"\"\n        p_fun(location, shape::OddShape, args...; kwargs...)\n\n    Returns 1 if location is in OddShape and 0 otherwise.\n\n    # Arguments\n\n    - `location`: a proposed location in a unit hypercube\n    - `Oddshape`: an odd contiguous shape\n    \"\"\"\n    function p_fun(location, shape::OddShape, args...; kwargs...)\n        bounds = shape.p_bounds\n        indices = shape.indices\n        shape_ids = shape.shape_ids\n        n_dims = length(location)\n        n_b = length(bounds)\n        index = fill(0, n_dims)\n\n        for j in 1:n_dims\n            for i in 1:(n_b-1) \n                if (location[j] \u2265 bounds[i]) && (location[j] \u2264 bounds[i+1])\n                    index[j] = i \n                    continue\n                end\n            end\n        end\n        return get_id(index, indices, shape_ids)\n    end\n\n    function get_id(index, indices, shape_ids)\n        for i in 1:length(indices)\n            if indices[i] == index \n                return shape_ids[i]\n            end\n        end\n        return 0\n    end\n\nend", "meta": {"hexsha": "00a9f93e22a1f9e1d54f48590aa366628e057758", "size": 7415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestModels.jl", "max_stars_repo_name": "itsdfish/ParameterSpacePartitions", "max_stars_repo_head_hexsha": "fac247a26549fde108419ed2dd52d165ea97f1e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2022-01-10T00:26:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T01:33:46.000Z", "max_issues_repo_path": "src/TestModels.jl", "max_issues_repo_name": "itsdfish/ParameterSpacePartitions.jl", "max_issues_repo_head_hexsha": "fac247a26549fde108419ed2dd52d165ea97f1e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2022-01-09T18:29:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T19:22:05.000Z", "max_forks_repo_path": "src/TestModels.jl", "max_forks_repo_name": "itsdfish/ParameterSpacePartitions", "max_forks_repo_head_hexsha": "fac247a26549fde108419ed2dd52d165ea97f1e8", "max_forks_repo_licenses": ["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.9636363636, "max_line_length": 114, "alphanum_fraction": 0.5831422792, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.778476602168739}}
{"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\u25bd(x, y) = [fdx(x, y), fdy(x, y)]\nL(x, y, \u03bb) = [x, y] .- (\u03bb .* \u25bd(x, y))\n\nfunction simpleGradientDescent(f, \u25bd, x0, y0, \u025b) # down gradient with exponentital slow step\n  callCnt, gradCallCnt, xs, ys = 1, 0, [x0], [y0]\n\n  \u03bb = 0.05\n  fprev = f(x0, y0)\n  while true\n    xk, yk = xs[end], ys[end]\n    xnew, ynew = L(xk, yk, \u03bb)\n    gradCallCnt += 1\n    if xnew < 0 || 1 < xnew || ynew < 0 || 1 < ynew\n      \u03bb *= 0.75\n      continue\n    end\n    fnew = f(xnew, ynew)\n    callCnt += 1\n    if fnew > fprev\n      \u03bb *= 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]]) < \u025b\n      break\n    end\n  end\n  xs, ys, callCnt, gradCallCnt\nend\n\nfunction fastGradienDescent(f, \u25bd, x0, y0, \u025b) # 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 = \u25bd(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    \u03bb, cnt, _, _, _ = fibSearch(arg -> f(x_left - arg * g[1], y_left - arg * g[2]), a[1], a[2], \u025b)\n    callCnt += cnt\n    xnew, ynew = x_left - \u03bb * g[1], y_left - \u03bb * g[2]\n    push!(xl, xnew)\n    push!(yl, ynew)\n    if norm([xl[end] - xl[end - 1], yl[end] - yl[end - 1]]) < \u025b\n      break\n    end\n  end\n  xl, yl, callCnt, gradCallCnt\nend\n\n\u025b = 0.0001\nx0, y0 = 0.2, 0.8\nsgx, sgy, cnt1, gcnt1 = simpleGradientDescent(f, \u25bd, x0, y0, \u025b)\nfgx, fgy, cnt2, gcnt2 = fastGradienDescent(f, \u25bd, x0, y0, \u025b)\n\n@printf(\"\u041e\u0431\u044b\u0447\u043d\u044b\u0439 \u0433\u0440\u0430\u0434\u0438\u0435\u043d\u0442\u043d\u044b\u0439 \u0441\u043f\u0443\u0441\u043a: %d \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438, %d \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0439 \u0433\u0440\u0430\u0434\u0438\u0435\u043d\u0442\u0430\\n\", cnt1, gcnt1)\n@printf(\"\u041d\u0430\u0438\u0441\u043a\u043e\u0440\u0435\u0439\u0448\u0438\u0439 \u0441\u043f\u0443\u0441\u043a: %d \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438, %d \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0439 \u0433\u0440\u0430\u0434\u0438\u0435\u043d\u0442\u0430\\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(\"\u041b\u0438\u043d\u0438\u0438 \u0443\u0440\u043e\u0432\u043d\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 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\u03b3 = 2 # parameter from CRRA utility\nr = 0.03 # the interest rate\n\u03c1 = 0.05 # the discount rate\n\nz1=.1\nz2 =.2\nz= [z1 z2]\n\n\u03bb1 = 0.02\n\u03bb2 = 0.03\n\n\u03bb = [\u03bb1 \u03bb2]\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-\u03b3)/(1-\u03b3)/\u03c1\nv0[:,2] = (z[2] .+ r.*a).^(1-\u03b3)/(1-\u03b3)/\u03c1\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).^(-\u03b3)\n\n    # Find consumption and savings with the forward difference\n    cf = dVf.^(-1/\u03b3)\n    sf = zz +r.*aa -cf\n\n    # Find consumption and savings with the backward difference\n    cb= dVb.^(-1/\u03b3)\n    sb = zz +r.*aa -cb\n\n    # Find consumption and savings at steady state\n    c0 = zz + r.*aa\n    dV0 = c0.^(-\u03b3)\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/\u03b3)\n    global V_switch = [V[:,2] V[:,1]]\n\n    V_change = c.^(1-\u03b3)/(1-\u03b3) + dV_Upwind.*(zz + r.*aa -c) + ones(H,1)*\u03bb.*(V_switch-V)-\u03c1.*V\n\n    \u0394 = .9*da/(findmax(z2 .+r.*a)[1])\n    global v = v  + \u0394*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-\u03b3)/(1-\u03b3) + dV_Upwind.*(zz +r.*aa -c) + ones(H,1)*\u03bb.*(V_switch-V)-\u03c1.*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)^(-\u03b3)\nu2 = c[1,2]^(-\u03b3)\nu11 = -\u03b3*(z1+r*amin)^(-\u03b3-1)\n\u03bd = sqrt(-2*((\u03c1-r)*u1 + \u03bb1*(u1-u2))/u11)\ns_approx = -\u03bd*(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    \u03b3::TF                 # coefficient of risk aversion\n    \u03b2::TF                 # Discount factor in (0, 1)\n    \u03b1::TF                 # Correlation coefficient in the shock process\n    \u03c3::TF                 # Volatility of shock process\n    \u03d5::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(;\u03b3::AbstractFloat=2.0,\n                \u03b2::AbstractFloat=0.95,\n                \u03b1::AbstractFloat=0.9,\n                \u03c3::AbstractFloat=0.1,\n                grid_size::Integer=100)\n\n    \u03d5 = LogNormal(0.0, \u03c3)\n    shocks = rand(\u03d5, 500)\n\n    # == build a grid with mass around stationary distribution == #\n    ssd = \u03c3 / sqrt(1 - \u03b1^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) = \u03b2 * int u'(G(y,z)) G(y,z) \u03d5(dz) == #\n    h = similar(grid)\n    for (i, y) in enumerate(grid)\n        h[i] = \u03b2 * mean((y^\u03b1 .* shocks).^(1 - \u03b3))\n    end\n\n    return LucasTree(\u03b3,\n                     \u03b2,\n                     \u03b1,\n                     \u03c3,\n                     \u03d5,\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, \u03b1, \u03b2, h = lt.grid, lt.\u03b1, lt.\u03b2, lt.h\n    z = lt.shocks\n\n    Af = LinInterp(grid, f)\n\n    Tf = [h[i] + \u03b2 * mean(Af.(grid[i]^\u03b1.*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, \u03b3 = lt.grid, lt.\u03b3\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 ^ \u03b3\n    price = f .* grid.^\u03b3\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 \u2229 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    \u03b8 = acos((r^2 + d^2 - s^2) / (2 * r * d))\n    u = (w - z) / abs(w - z)\n    uu = u * exp(\u03b8 * im)\n    a = z + uu * r\n    uu = u * exp(-\u03b8 * 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        \u03b4 = sqrt(r^2 - y^2)\n        a = G(x + \u03b4)\n        b = G(x - \u03b4)\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 \u2229 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    # \u03b4 = y / slope\n    # z = G(x - \u03b4)\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": "function hessian(f::Function, x::Array{T, 1}) where T <: AbstractFloat\n\n  m = length(x)\n\n\te = eps(T)^(1/4)*maximum(abs,[x;one(T)])\n\tdh = Matrix{Float64}(I, m, m)*e\n  hess = Array{T}(undef,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]))[1,1]/(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]))[1,1]/(4*e^2)\n        hess[j,i] = hess[i,j]\n      end\n    end\n\n    return hess\n\nend\n", "meta": {"hexsha": "c6fe32bc866586a15c3ba34a6389cc9f52764c8e", "size": 540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hessian.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/hessian.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/hessian.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": 23.4782608696, "max_line_length": 115, "alphanum_fraction": 0.4740740741, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7784378685691035}}
{"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(\u03ba::PeriodicKernel) = Sinus(\u03ba.r)\n\nkappa(::PeriodicKernel, d::Real) = exp(-0.5d)\n\nfunction Base.show(io::IO, \u03ba::PeriodicKernel)\n    return print(io, \"Periodic Kernel, length(r) = $(length(\u03ba.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 \u03c3, \u03c1, \u03b2 = p\n    @unpack x, y, z = u\n    \n    D.x = \u03c3*(y - x)\n    D.y = x*(\u03c1 - z) - y - f\n    D.z = x*y - \u03b2*z\n    return nothing\nend\n\nlorenz_p = (\u03c3=10.0, \u03c1=28.0, \u03b2=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 \u03b1, \u03b2, \u03b3, \u03b4 = p\n    @unpack x, y = u\n    \n    D.x =  \u03b1*x - \u03b2*x*y + f\n    D.y = -\u03b3*y + \u03b4*x*y\n    return nothing\nend\n\nlotka_p = (\u03b1=2/3, \u03b2=4/3, \u03b3=1.0, \u03b4=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": "@testset \"ModelKit - Symbolic\" begin\n    @testset \"SymEngine\" begin\n        @test Expression(MathConstants.catalan) isa Expression\n        @test Expression(MathConstants.e) isa Expression\n        @test Expression(MathConstants.pi) isa Expression\n        @test Expression(MathConstants.\u03b3) isa Expression\n        @test Expression(Float16(2.1)) isa Expression\n        @test Expression(Float32(2.1)) isa Expression\n        @test Expression(big(2.1)) isa Expression\n        @test Expression(Int32(2)) isa Expression\n        @test Expression(Int16(2)) isa Expression\n        @test Expression(Int128(2)) isa Expression\n        @test Expression(2 // 3) isa Expression\n        @test convert(BigFloat, Expression(big(2.1))) == big(2.1)\n        @test ModelKit.is_number(Expression(2))\n        @test ModelKit.to_number(Expression(big(2.1))) isa BigFloat\n        @test ModelKit.to_number(Expression(2 // 3)) isa Rational{Int32}\n        @test ModelKit.to_number(Expression(2) // Expression(3)) isa Rational{Int32}\n        @test ModelKit.to_number(Expression(big(2)^129)) isa BigInt\n\n        @test BigFloat(Expression(big(2.1))) == big(2.1)\n        @test Float64(Expression(2)) == 2.0\n        @test Rational{Int32}(Expression(2 // 3)) == 2 // 3\n        @test UInt(Expression(2)) == UInt(2)\n\n        @test complex(Expression(1), Expression(2)) == Expression(1) + im * 2\n        @test complex(Expression(1), 2) == Expression(1) + im * 2\n        @test complex(1, Expression(2)) == Expression(1) + im * 2\n        @test +Expression(2) == 2\n        @test Expression(HC.DoubleDouble.DoubleF64(2)) == big(2.0)\n    end\n\n    @testset \"Variables\" begin\n        @var a b x[1:2] y[1:2, 1:3]\n\n        @test a isa Variable\n        @test b isa Variable\n        @test x isa Vector{Variable}\n        @test length(x) == 2\n        @test y isa Matrix{Variable}\n        @test size(y) == (2, 3)\n        @test join(x, \" \") == \"x\u2081 x\u2082\"\n\n        @test reshape(sort(vec(y)), 2, 3) == y\n        @var x[9:11]\n        @test sort(x) == x\n\n        @var c, d\n        @test c isa Variable\n        @test d isa Variable\n        @test variables(c) == [c]\n        @test c === c\n        @test c !== copy(c)\n\n        let\n            c2 = @unique_var c\n            @test c != c2\n        end\n\n        f = a + b\n        @test variables(f) == [a, b]\n        @test nvariables(f) == 2\n        g = x[1]\n        @test variables([f, g]) == [a, b, x[1]]\n        @test nvariables([f, g]) == 3\n    end\n\n    @testset \"Subs\" begin\n        @var x y w z u\n        f = x^2 * (x + y * w)\n\n        @test subs(f, x => z) == z^2 * (z + w * y)\n        @test subs([f], x => z) == [z^2 * (z + w * y)]\n        @test subs(f, [x, y] => [z^2, z + 2]) == z^4 * (w * (2 + z) + z^2)\n        @test subs(f, [x, y] => [z^2, z + 2], w => u) == z^4 * (u * (2 + z) + z^2)\n        @test subs(f, x => z^2, y => 3, w => u) == z^4 * (3 * u + z^2)\n        @test subs(f, Dict(x => z^2, y => 3, w => u)) == z^4 * (3 * u + z^2)\n    end\n\n    @testset \"Evaluation\" begin\n        @var x y w\n        f = x^2 * (x + y * w)\n        @test evaluate([f, f], [x, y, w] => [2, 3, -5]) == [-52, -52]\n        @test [f, 2f]([x, y, w] => [2, 3, -5]) == [-52, -104]\n    end\n\n    @testset \"Linear Algebra\" begin\n        @var x[1:2, 1:2]\n        @test det(x[1:1, 1:1]) == x[1, 1]\n        @test det(x) == -x[2, 1] * x[1, 2] + x[2, 2] * x[1, 1]\n        @test det(x') == -x[2, 1] * x[1, 2] + x[2, 2] * x[1, 1]\n        @test det(transpose(x)) == -x[2, 1] * x[1, 2] + x[2, 2] * x[1, 1]\n    end\n\n    @testset \"Differentiation\" begin\n        @var x y\n\n        f = x^2 + y^2\n        g = x^3 + y^3\n\n        @test differentiate(f, x) == 2x\n        @test differentiate(f, [x, y]) == [2x, 2y]\n\n        @test differentiate([f, g], x) == [2x, 3 * x^2]\n        @test differentiate([f, g], [x, y]) == [2x 2y; 3*x^2 3*y^2]\n    end\n\n    @testset \"Expand\" begin\n        @var x y\n        @test expand((x + y)^2) == 2 * x * y + x^2 + y^2\n    end\n\n    @testset \"to_dict\" begin\n        @var x y a\n        @test ModelKit.to_dict(x^2 + y * x * a + y * x, [x, y]) ==\n              Dict([2, 0] => Expression(1), [1, 1] => a + 1)\n        @test ModelKit.degree(x * y^5 + y^2, [x, y]) == 6\n    end\n\n    @testset \"Modeling\" begin\n        @testset \"Bottleneck\" begin\n            @var x y z\n            f = [\n                (0.3 * x^2 + 0.5z + 0.3x + 1.2 * y^2 - 1.1)^2 +\n                (0.7 * (y - 0.5x)^2 + y + 1.2 * z^2 - 1)^2 - 0.3,\n            ]\n\n            I = let x = [x, y, z]\n                n, m = length(x), length(f)\n                @unique_var y[1:n] v[1:m] w[1:m]\n                J = differentiate(f, x)\n                f\u2032 = f(x => y)\n                J\u2032 = J(x => y)\n                Nx = (x - y) - J' * v\n                Ny = (x - y) - J\u2032' * w\n                System([f; f\u2032; Nx; Ny], [x; y; v; w])\n            end\n            @test I isa System\n            @test size(I) == (8, 8)\n        end\n\n        @testset \"Steiner\" begin\n            @var x[1:2] a[1:5] c[1:6] y[1:2, 1:5]\n\n            #tangential conics\n            f = sum([a; 1] .* monomials([x; 1], 2; affine = false))\n            \u2207 = differentiate(f, x)\n            #5 conics\n            g = sum(c .* monomials([x; 1], 2; affine = false))\n            \u2207_2 = differentiate(g, x)\n            #the general system\n            #f_a_0 is tangent to g_b\u2080 at x\u2080\n            function Incidence(f, a\u2080, g, b\u2080, x\u2080)\n                f\u1d62 = f(x => x\u2080, a => a\u2080)\n                \u2207\u1d62 = \u2207(x => x\u2080, a => a\u2080)\n                C\u1d62 = g(x => x\u2080, c => b\u2080)\n                \u2207_C\u1d62 = \u2207_2(x => x\u2080, c => b\u2080)\n\n                [f\u1d62; C\u1d62; det([\u2207\u1d62 \u2207_C\u1d62])]\n            end\n            @var v[1:6, 1:5]\n            I = vcat(map(i -> Incidence(f, a, g, v[:, i], y[:, i]), 1:5)...)\n            F = System(I, [a; vec(y)], vec(v))\n            @test size(F) == (15, 15)\n        end\n\n        @testset \"Reach plane curve\" begin\n            @var x y\n            f = (x^3 - x * y^2 + y + 1)^2 * (x^2 + y^2 - 1) + y^2 - 5\n            \u2207 = differentiate(f, [x; y]) # the gradient\n            H = differentiate(\u2207, [x; y]) # the Hessian\n\n            g = \u2207 \u22c5 \u2207\n            v = [-\u2207[2]; \u2207[1]]\n            h = v' * H * v\n            dg = differentiate(g, [x; y])\n            dh = differentiate(h, [x; y])\n\n            \u2207\u03c3 = g .* dh - ((3 / 2) * h) .* dg\n\n            F = System([v \u22c5 \u2207\u03c3; f], [x, y])\n            @test size(F) == (2, 2)\n        end\n    end\n\n    @testset \"Horner\" begin\n        # use fano scheme as test\n        n = 4\n        s = 1\n        @var x[1:n]\n        \u03bd = monomials(x, 5; affine = false)\n        N = length(\u03bd)\n        q\u2080 = randn(ComplexF64, N - 1)\n        @var q[1:N-1]\n        F = sum(q[i] * \u03bd[i] for i = 1:N-1) + 1\n\n        @var a[1:n-1] b[1:n-1] t\n        L = [a; 1] .* t + [b; 0]\n\n        G = subs(F, x => L)\n\n        FcapL = collect(values(ModelKit.to_dict(expand(G), [t])))\n\n        @test all(FcapL) do f\n            g = horner(f)\n            expand(g) == f\n        end\n        @test all(FcapL) do f\n            g = horner(f, [a; b])\n            expand(g) == f\n        end\n    end\n\n    @testset \"Rand / dense poly\" begin\n        @var x y\n        f, c = dense_poly([x, y], 3)\n        @test length(c) == 10\n        g = rand_poly(Float64, [x, y], 3)\n        @test subs(f, c => coefficients(g, [x, y])) == g\n        _, coeffs = exponents_coefficients(g, [x, y]; expanded = true)\n        @test subs(f, c => coeffs) == g\n\n        @var x[1:3]\n        f, c = dense_poly(x, 3, coeff_name = :c)\n        g = x[1]^3 + x[2]^3 + x[3]^3 - 1\n        gc = coeffs_as_dense_poly(g, x, 3)\n        @test subs(f, c => gc) == g\n    end\n\n    @testset \"System\" begin\n        @var x y a b\n        f = [(x + y)^3 + x^2 + x + 5y + 3a, 2 * x^2 + b]\n        F = System(f, [x, y], [b, a])\n        @test nvariables(F) == 2\n        @test nparameters(F) == 2\n        @test variables(F) == [x, y]\n        @test parameters(F) == [b, a]\n        show_F = \"\"\"\n        System of length 2\n         2 variables: x, y\n         2 parameters: b, a\n\n         3*a + x + 5*y + x^2 + (x + y)^3\n         b + 2*x^2\"\"\"\n        @test sprint(show, F) == show_F\n        @test degrees(F) == [3, 2]\n\n        T = CompiledSystem(F; optimizations = false)\n        F2 = System(T)\n        @test F == F2\n        @test sprint(show, T) == \"Compiled: $show_F\"\n        @test size(T) == size(F) == (2, 2)\n\n        T2 = CompiledSystem(F; optimizations = true)\n        F3 = System(T2)\n        @test expand.(F.expressions) == expand.(F3.expressions)\n\n        F4 = System(f, parameters = [b, a])\n        @test variables(F4) == [x, y]\n\n        @var x y a b\n        f = Any[(x+y)^3+x^2+x+5y+3a, 2*x^2+b]\n        F = System(f, [x, y], [b, a])\n        @test F isa System\n    end\n\n    @testset \"System variables groups + homogeneous\" begin\n        @var x y z\n        f = System([\n            (x^2 + y^2 + x * y - 3 * z^2) * (x + 3z),\n            (x^2 + y^2 + x * y - 3 * z^2) * (y - x + 2z),\n            2x + 5y - 3z,\n        ])\n        @test is_homogeneous(f)\n        multi_degrees(f) == [1 1; 2 0]\n\n        @var x y z v w\n        g = System([x * y - 2v * w, x^2 - 4 * v^2], variable_groups = [[x, v], [y, w]])\n        @test is_homogeneous(g)\n        multi_degrees(g) == [1 1; 2 0]\n    end\n\n    @testset \"Homotopy\" begin\n        @var x y z t\n\n        h = [x^2 + y + z + 2t, 4 * x^2 * z^2 * y + 4z - 6x * y * z^2]\n        H = Homotopy(h, [x, y, z], t)\n\n        @test nvariables(H) == 3\n        @test nparameters(H) == 0\n        @test variables(H) == [x, y, z]\n        @test parameters(H) == []\n        show_H = \"\"\"\n        Homotopy in t of length 2\n         3 variables: x, y, z\n\n         2*t + y + z + x^2\n         4*z - 6*x*y*z^2 + 4*x^2*y*z^2\"\"\"\n\n        @test sprint(show, H) == show_H\n\n        H_any = Homotopy(convert(Vector{Any}, h), [x, y, z], t)\n        @test H_any isa Homotopy\n\n        T = CompiledHomotopy(H)\n        H2 = ModelKit.interpret(T)\n        @test H == H2\n        @test sprint(show, T) == \"Compiled: $show_H\"\n        @test size(T) == size(H) == (2, 3)\n    end\n\n    @testset \"Optimizations for rational system\" begin\n        @var y[1:6] q[1:8]\n        y\u2081, y\u2082, y\u2083, y\u2084, y\u2085, y\u2086 = y\n        q\u2081, q\u2082, q\u2083, q\u2084, q\u2085, q\u2086, q\u2087, q\u2088 = q\n\n        f =\n            q\u2081 / y\u2081 - q\u2082 / (-y\u2081 + y\u2082) +\n            q\u2085 * y\u2084 / (y\u2081 * y\u2084 - y\u2083 * y\u2082) +\n            q\u2088 * y\u2086 / (y\u2081 * y\u2086 - y\u2082 * y\u2085)\n        F = ModelKit.System([f], y, q)\n        I = ModelKit.interpreter(ModelKit.optimize(F))\n        u = Expression[0]\n        ModelKit.execute!(u, I, y, q, ModelKit.InterpreterCache(Expression, I))\n\n        @test expand(u[1] - f) == 0\n    end\nend\n", "meta": {"hexsha": "dc10941d771394e7c29570208ce9042285444eaa", "size": 10440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/model_kit/symbolic_test.jl", "max_stars_repo_name": "aliddell/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "a420f50f825ab85f6cf635cc73bae15048765c31", "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": "test/model_kit/symbolic_test.jl", "max_issues_repo_name": "aliddell/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "a420f50f825ab85f6cf635cc73bae15048765c31", "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": "test/model_kit/symbolic_test.jl", "max_forks_repo_name": "aliddell/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "a420f50f825ab85f6cf635cc73bae15048765c31", "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": 31.7325227964, "max_line_length": 87, "alphanum_fraction": 0.4370689655, "num_tokens": 3846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7783941219249322}}
{"text": "function dbscan(arr::Array{Float64,2} , \u03f5::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 <= \u03f5, 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": "using Distributions, Random, Statistics, Test\r\nimport ThorinDistributions\r\nimport DynamicPolynomials, Statistics, StatsBase\r\n\r\n####################################\r\n# Previous versions of the code, used now for testing purposes only. \r\n####################################\r\nfunction Bell_partial_matrix(N,K,x)\r\n    M = zeros(eltype(x .+ 1.0),(N+1,K+1))\r\n    for n in 0:N\r\n        for k in 0:n\r\n            if n == 0 && k == 0\r\n                M[n+1,k+1] = 1\r\n            elseif n == 0 || k == 0\r\n                M[n+1,k+1] = 0\r\n            else\r\n                M[n+1,k+1] = sum([binomial(n-1,i-1)*x[i]*M[n-i+1,k] for i in 1:n-k+1])\r\n            end\r\n        end\r\n    end\r\n    return M\r\nend\r\nfunction cumulants_from_moments(\u03bc, mu0 = 1)\r\n    # we ned to construct kappa that are the derivatives of the log times mu \r\n    n = length(\u03bc)\r\n    M = Bell_partial_matrix(n-1,n-1,\u03bc)\r\n    log_der_fact = [log(mu0),[factorial(big(i-1)) * (-1)^(i-1) * mu0^(-i) for i in 1:(n-1)]...]\r\n    return M''log_der_fact\r\nend\r\n# According to wikipedia, we could also obtain them by recursion.\r\n# see end of paragraph https://en.wikipedia.org/wiki/Cumulant#Cumulants_and_moments\r\nfunction cum_from_mom_rec!(\u03ba,\u03bc,mu0=nothing)\r\n    if isnothing(mu0)\r\n        mu0 = \u03bc[1]\r\n        \u03bc = \u03bc[2:end]\r\n    end\r\n    # much faster algorithm ! \r\n    \u03ba[1] = log(mu0)\r\n    \u03ba[2] = \u03bc[1] ./ mu0\r\n    for n in 2:(length(\u03bc)-1)\r\n        \u03ba[n+1] = (\u03bc[n] - sum(binomial(big(n-1),big(m-1))*\u03ba[m+1]*\u03bc[n-m] for m in 1:(n-1))) / mu0\r\n    end\r\n    return \u03ba\r\nend\r\nfunction cum_from_mom_rec(\u03bc;mu0)\r\n    if isnothing(mu0)\r\n        mu0 = \u03bc[1]\r\n        \u03bc = \u03bc[2:end]\r\n    end\r\n    \u03ba = Array{Any}(undef, length(\u03bc)) # needs to be Array{Any} so that the test with polynomials passes...\r\n    cum_from_mom_rec!(\u03ba,\u03bc,mu0)\r\n    return \u03ba\r\nend\r\nfunction old_thorin_moments(D,t_star,m)\r\n    n = length(D)\r\n    mu = sum(D .^(0:(m+1))' .* exp.(t_star .* D),dims=1)/n\r\n    return [log(mu[1]),(cum_from_mom_rec(mu[2:end],mu0=mu[1])[2:end] ./ factorial.(big.(0:(m-1))))...]\r\nend\r\nfunction old_resemps_thorin_moments(M,D,t_star,m)\r\n    n = length(D)\r\n    T = eltype(D)\r\n    mu_mat = D .^(0:(m+1))' .* exp.(t_star .* D)\r\n    kappa = zeros(T,(M,m+1))\r\n    facts = [T(1),factorial.(T.(0:(m-1)))...]\r\n    for i in 1:M\r\n        @views kappa[i,:] = cum_from_mom_rec!(kappa[i,:], StatsBase.mean(mu_mat[StatsBase.sample(1:n,n,replace=true),:],dims=1)) ./ facts\r\n    end\r\n    return kappa\r\nend\r\nfunction cum_from_mom_rec_simplified(\u03bc;mu0)\r\n    # for test only\r\n    if isnothing(mu0)\r\n        mu0 = \u03bc[1]\r\n        \u03bc = \u03bc[2:end]\r\n    end\r\n    \u03b7 = Array{Any}(undef, length(\u03bc)+1)\r\n    \u03c4 = Array{Any}(undef, length(\u03bc)+1)\r\n    \u03b7 .= [mu0,(\u03bc ./ factorial.(big.(1:length(\u03bc))))...]\r\n    \u03b7[2:end] ./= mu0\r\n    \u03c4[1] = log.(mu0)\r\n    \u03c4[2] = \u03b7[2]\r\n    for k in 3:length(\u03b7)\r\n        \u03c4[k] = (k-1)*\u03b7[k]\r\n        for j in 1:(k-2)\r\n            \u03c4[k] -= \u03c4[j+1] * \u03b7[k-j]\r\n        end\r\n    end\r\n    \u03ba = \u03c4 .* [1,factorial.(big.(0:(length(\u03c4)-2)))...]\r\n    return \u03ba[1:end-1]\r\nend \r\n\r\n@testset \"ThorinMoments.jl tests\" begin\r\n\r\n    DynamicPolynomials.@polyvar \u03bc[1:10];\r\n    \u03ba1 = cumulants_from_moments(\u03bc,1);\r\n    \u03ba2 = cum_from_mom_rec(\u03bc,mu0=1);\r\n    \u03ba3 = cum_from_mom_rec_simplified(\u03bc,mu0=1);\r\n    \u03ba4 = cumulants_from_moments(\u03bc,0.5);\r\n    \u03ba5 = cum_from_mom_rec(\u03bc,mu0=0.5);\r\n    \u03ba6 = cum_from_mom_rec_simplified(\u03bc,mu0=0.5);\r\n\r\n    n = 100\r\n    D = BigFloat.(rand(LogNormal(),n));\r\n\r\n    @testset \"thorin_moment_function is alright\" begin\r\n        \u03c4 = ThorinDistributions.thorin_moments(D,-1,9)\r\n        \u03b7s = zeros(eltype(D),(n,11))\r\n        ThorinDistributions.\u03b7s_from_data!(\u03b7s,D,-1)\r\n        \u03b7_mom = Statistics.mean(\u03b7s,dims=1) .* factorial.(big.(0:10))'\r\n        \u03c41 = cum_from_mom_rec(\u03b7_mom,mu0=nothing) ./ factorial.([big(0),big.(0:8)...])\r\n        \u03c42 = cum_from_mom_rec_simplified(\u03b7_mom,mu0=nothing) ./ factorial.([big(0),big.(0:8)...])\r\n        \u03c43 = cumulants_from_moments(\u03b7_mom[2:end],\u03b7_mom[1]) ./ factorial.([big(0),big.(0:8)...])\r\n        \r\n        @test \u03c4 \u2248 \u03c41\r\n        @test \u03c4 \u2248 \u03c42\r\n        @test \u03c4 \u2248 \u03c43\r\n    end\r\n\r\n    @testset \"firsts cumulants corretness, mu0=1\" begin\r\n        @test \u03ba1[1] == 0\r\n        @test \u03ba1[2] == \u03bc[1]\r\n        @test \u03ba1[3] == \u03bc[2] - \u03bc[1]^2\r\n        @test \u03ba1[4] == 2.0\u03bc[1]^3 - 3.0\u03bc[1]\u03bc[2] + \u03bc[3]\r\n        @test \u03ba1[5] ==  -6.0\u03bc[1]^4 + 12.0\u03bc[1]^2*\u03bc[2] - 4.0\u03bc[1]\u03bc[3] - 3.0\u03bc[2]^2 + \u03bc[4]\r\n        @test \u03ba1[6] ==   24.0\u03bc[1]^5 - 60.0\u03bc[1]^3*\u03bc[2] + 20.0\u03bc[1]^2*\u03bc[3] + 30.0\u03bc[1]*\u03bc[2]^2 - 5.0\u03bc[1]*\u03bc[4] - 10.0\u03bc[2]*\u03bc[3] + \u03bc[5]\r\n    end\r\n\r\n    @testset \"cumulants recursivity\" begin\r\n        @test \u03ba1 == \u03ba2\r\n        @test \u03ba4 == \u03ba5\r\n    end\r\n\r\n    @testset \"\u03b7/\u03c4 simplification\" begin\r\n        @test all(\u03ba3 .\u2248 \u03ba1)\r\n        @test all(\u03ba3 .\u2248 \u03ba2)\r\n        @test all(\u03ba6 .\u2248 \u03ba4)\r\n        @test all(\u03ba6 .\u2248 \u03ba5)\r\n    end\r\n\r\n    @testset \"Bell partial matrix\" begin\r\n        M1 = [1   0      0       0       0       0       0      0     0   0  0\r\n        0   1      0       0       0       0       0      0     0   0  0\r\n        0   2      1       0       0       0       0      0     0   0  0\r\n        0   3      6       1       0       0       0      0     0   0  0\r\n        0   4     24      12       1       0       0      0     0   0  0\r\n        0   5     80      90      20       1       0      0     0   0  0\r\n        0   6    240     540     240      30       1      0     0   0  0\r\n        0   7    672    2835    2240     525      42      1     0   0  0\r\n        0   8   1792   13608   17920    7000    1008     56     1   0  0\r\n        0   9   4608   61236  129024   78750   18144   1764    72   1  0\r\n        0  10  11520  262440  860160  787500  272160  41160  2880  90  1]\r\n        @test Int.(Bell_partial_matrix(10,10,1:30)) == M1\r\n    end\r\n\r\n    @testset \"Resemp is OK\" begin\r\n        M = 10\r\n        Random.seed!(123)\r\n        x1 = old_resemps_thorin_moments(M,D,-1,10)\r\n        Random.seed!(123)\r\n        x2 = ThorinDistributions.resemps_thorin_moments(M,D,-1,10)\r\n        @test x1 \u2248 x2\r\n        Random.seed!(123)\r\n        x3 = ThorinDistributions.resemps_thorin_moments(M,[D 2D]',-1,10)\r\n        @test x1 \u2248 x3[:,1,:]\r\n\r\n    end\r\nend\r\n", "meta": {"hexsha": "a98af75a8c71b68deaa34e5ea97167bdb9773431", "size": 6039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ThorinMoments.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": "test/ThorinMoments.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": "test/ThorinMoments.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": 35.9464285714, "max_line_length": 138, "alphanum_fraction": 0.4966053982, "num_tokens": 2357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7783941145580289}}
{"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 = \u03bb 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 = \u03bb 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": "@testset \"Composition\" begin\n    @testset \"total degree\" begin\n        @polyvar a b c x y z u v\n        e = [u + 1, v - 2]\n        f = [a * b - 2, a * c - 1]\n        g = [x + y, y + 3, x + 2]\n        res = solve(e \u2218 f \u2218 g)\n        @test nnonsingular(res) == 2\n        @test nnonsingular(solve(e \u2218 f \u2218 g, system_scaling = nothing)) == 2\n        @test nnonsingular(solve(e \u2218 f \u2218 g, system_scaling = :equations_and_variables)) == 2\n\n        res = solve(e \u2218 f \u2218 g, system = SPSystem)\n        @test nnonsingular(res) == 2\n    end\n\n    @testset \"polyhedral\" begin\n        @polyvar x y u v\n        result = solve(\n            [2y + 3 * y^2 - x * y^3, x + 4 * x^2 - 2 * x^3 * y] \u2218 [u, v];\n            seed = 32241, start_system = :polyhedral,\n        )\n        @test nsolutions(result) == 6\n    end\n\n    @testset \"parameter homotopy\" begin\n        @polyvar p q a b c x y z u v\n\n        f = [a * b - 2, a * c - 1]\n        g = [x + y, y + 3, x + 2]\n        res = solve(f \u2218 g; system = FPSystem, threading = false)\n        @test nnonsingular(res) == 2\n        # parameters at the end\n        f2 = [a * b - q, a * c - p]\n        g = [x + y, y + 3, x + 2]\n        r = solve(\n            f2 \u2218 g,\n            solutions(res);\n            parameters = [p, q], p\u2081 = [1, 2], p\u2080 = [2, 3], threading = false,\n        )\n        @test nnonsingular(r) == 2\n\n        # parameters at the beginning\n        f = [a * b - 2, a * c - 1]\n        g2 = [x + y, y + u, x + v]\n        r = solve(\n            f \u2218 g2,\n            solutions(res);\n            parameters = [u, v], p\u2081 = [3, 2], p\u2080 = [-2, 3], threading = false,\n        )\n        @test nnonsingular(r) == 2\n\n        # parameter in the middle\n        e = [u + 1, v - 2]\n        res2 = solve(e \u2218 f \u2218 g; system = SPSystem)\n        f2 = [a * b - q, a * c - p]\n        r = solve(\n            e \u2218 f2 \u2218 g,\n            solutions(res2);\n            parameters = [p, q], p\u2081 = [1, 2], p\u2080 = [2, 3], threading = false,\n        )\n        @test nnonsingular(r) == 2\n    end\nend\n", "meta": {"hexsha": "a63efe60c3e56b2c262d40aab1ff6f7e3c61b2e5", "size": 1989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "v1/test/composition_test.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/test/composition_test.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/test/composition_test.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": 31.078125, "max_line_length": 92, "alphanum_fraction": 0.4323780794, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7783941125738942}}
{"text": "# using Distributions, Bijectors\n\n# Define a deterministic distribution\nstruct Determin{T<:Real} <: ContinuousUnivariateDistribution\n  val::T\nend\n\nDistributions.rand(rng::AbstractRNG, d::Determin) = d.val\nDistributions.logpdf(d::Determin, x::T) where T<:Real = zero(x)\n\nBijectors.bijector(d::Determin) = Identity{0}() # <= `0` indicates 0-dimensional, i.e. univariate \n\n\n\n# # useful functions\nfunction compute_stats(chain::Chains, name::Symbol)\n    # x = Array(x)\n    # x = DataFrame(x)\n    x = Array(group(chain, name))\n    mean_x = mean(x, dims=1)\n    xlb = mean_x - mapslices(x -> quantile(x, 0.025), x, dims=1)\n    xub = mean_x - mapslices(x -> quantile(x, 0.975), x, dims=1)\n    return (\u03bc = mean_x, lb = xlb, ub = xub)\nend\n\nfunction compute_stats(x::Array)\n    mean_x = mean(x, dims=1)\n    xlb = mean_x - mapslices(x -> quantile(x, 0.025), x, dims=1)\n    xub = mean_x - mapslices(x -> quantile(x, 0.975), x, dims=1)\n    return (\u03bc = mean_x, lb = xlb, ub = xub)\nend\n\nfunction get_omega(chain::Chains)   \n    w1 = Array(group(chain, :\u03c91))\n    w2 = Array(group(chain, :\u03c92))\n    w = w1 .+ w2\n    return (w = w, w1 = w1, w2 = w2)\nend\n\n\nfunction summarize_omega(chain::Chains)\n    w1_array = Array(group(chain, :\u03c91))\n    w2_array = Array(group(chain, :\u03c92))\n    w_array = Array(group(chain, :\u03c9))\n\n    w = compute_stats(w_array)\n    w1 = compute_stats(w1_array)\n    w2 = compute_stats(w2_array)\n    return (w = w, w1 = w1, w2 = w2)\nend\n\ninvlogit(x) = 1/(1 + exp(-x))\n\nfunction beta_params_mode(mode, k)\n    #= http://doingbayesiandataanalysis.blogspot.com/2012/06/beta-distribution-parameterized-by-mode.html\n    mode = (\u03b1 - 1)/(\u03b1 + \u03b2 - 2)\n    k = a + b # sample size\n    =#\n    @assert 0 < mode < 1\n    @assert k > 2\n\n    \u03b1 = mode * (k-2) + 1\n    \u03b2 = (1-mode) * (k-2) + 1\n    return \u03b1, \u03b2\nend\n\nfunction beta_params(\u03bc, \u03c3)\n    @assert 0 < \u03bc < 1\n    @assert \u03c3 > 0\n\n    \u03b1 = ((1-\u03bc)/\u03c3^2 - (1/\u03bc)) * \u03bc^2\n    \u03b2 = \u03b1 * (1 / \u03bc - 1)\n    return \u03b1, \u03b2\nend\n\n", "meta": {"hexsha": "8d6318fc84983f001ed001b7d5c283db4f4c0cfb", "size": 1937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/turingutils.jl", "max_stars_repo_name": "awellis/MentalSimulation.jl", "max_stars_repo_head_hexsha": "13c186cd4b7975ae8f4e91951779c2ad1a89e802", "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/turingutils.jl", "max_issues_repo_name": "awellis/MentalSimulation.jl", "max_issues_repo_head_hexsha": "13c186cd4b7975ae8f4e91951779c2ad1a89e802", "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/turingutils.jl", "max_forks_repo_name": "awellis/MentalSimulation.jl", "max_forks_repo_head_hexsha": "13c186cd4b7975ae8f4e91951779c2ad1a89e802", "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.4868421053, "max_line_length": 105, "alphanum_fraction": 0.6081569437, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.7783633762483633}}
{"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    \u03c4 = 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.\u03c4\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    \u03c41 = Measurement(estimator,  9.5, uncertainties = (stat=unc[1],) ),\n    \u03c42 = Measurement(estimator, 11.9, uncertainties = (stat=unc[2],) ),\n    \u03c43 = Measurement(estimator, 11.1, uncertainties = (stat=unc[3],) ),\n    \u03c44 = 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 \u03c4:\nplot(samples, :\u03c4, mean=true)\n#md # ![blue plots](plots/plot_blue.png)\n\n#~print numerical results of combination:\nprintln(\"Mode: $(mode(samples).\u03c4)\")\nprintln(\"Mean: $(mean(samples).\u03c4) \u00b1 $(std(samples).\u03c4)\")\n#md ```\n#md Mode: 11.15985\n#md Mean: 11.15471 \u00b1 0.80180\n#md ```\n\n#!jl # ### Comparison with BLUE method\n#jl # comparison with BLUE method:\nblue = BLUE(model)\nprintln(\"BLUE: $(blue.value) \u00b1 $(blue.unc)\") \nprintln(\"BLUE weights: $(blue.weights)\") \n#md ```\n#md BLUE: 11.15983 \u00b1 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\u1d64 = ReferenceFE(lagrangian,VectorValue{2,Float64},order)\nV = TestFESpace(model,reffe\u1d64,conformity=:H1,labels=labels,dirichlet_tags=[\"diri0\",\"diri1\"])\n\n# The interpolation space for the pressure is built as follows\n\nreffe\u209a = ReferenceFE(lagrangian,Float64,order-1;space=:P)\nQ = TestFESpace(model,reffe\u209a,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\u03a9\u2095 = Triangulation(model)\nd\u03a9 = Measure(\u03a9\u2095,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,\u2207u) = Re*(\u2207u')\u22c5u\ndconv(du,\u2207du,u,\u2207u) = conv(u,\u2207du)+conv(du,\u2207u)\n\n# The bilinear form reads\na((u,p),(v,q)) = \u222b( \u2207(v)\u2299\u2207(u) - (\u2207\u22c5v)*p + q*(\u2207\u22c5u) )d\u03a9\n\n# The nonlinear term and its Jacobian are given by\nc(u,v) = \u222b( v\u2299(conv\u2218(u,\u2207(u))) )d\u03a9\ndc(u,du,v) = \u222b( v\u2299(dconv\u2218(du,\u2207(du),u,\u2207(u))) )d\u03a9\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(\u03a9\u2095,\"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 \u2208 1:length(coins)\n        for j \u2208 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": "using ODE, Test, LinearAlgebra\n\ntols = [5e-2, 1e-2, 1e-2]\n\nsolvers = [\n           ## Non-stiff\n           # fixed step\n           ODE.ode1,\n           ODE.ode2_midpoint,\n           ODE.ode2_heun,\n           ODE.ode4,\n           ODE.ode4ms,\n           ODE.ode5ms,\n           # adaptive\n#           ODE.ode21, # this fails on Travis with 0.4?! TODO revert once fixed.\n           ODE.ode23,\n           ODE.ode45_dp,\n           ODE.ode45_fe,\n           ODE.ode78,\n\n           ## Stiff\n           # fixed-step\n           ODE.ode4s_s,\n           ODE.ode4s_kr,\n           # adaptive\n           ODE.ode23s]\n\ndtypes = [Float32, Float64, BigFloat]\nfor solver in solvers\n    println(\"using $solver\")\n    for (tol,T) in zip(tols, dtypes)\n        if solver==ODE.ode45_fe && T==Float32\n            # For some reason ode45_fe hangs with Float32!\n            continue\n        end\n\n        # dy\n        # -- = 6 ==> y = 6t\n        # dt\n        t,y=solver((t,y)->T(6), T(0), T[0:.1:1;])\n        @test maximum(abs.(y-6t)) < tol\n        @test eltype(t)==T\n\n        # dy\n        # -- = 2t ==> y = t.^2\n        # dt\n        t,y=solver((t,y)->T(2)*t, T(0), T[0:.001:1;])\n        @test maximum(abs.(y-t.^2)) < tol\n        @test eltype(t)==T\n\n        # dy\n        # -- = y ==> y = y0*e.^t\n        # dt\n        t,y=solver((t,y)->y, T(1), T[0:.001:1;])\n        @test maximum(abs.(y-\u212f.^t)) < tol\n        @test eltype(t)==T\n\n        t,y=solver((t,y)->y, T(1), T[1:-.001:0;])\n        @test maximum(abs.(y .- \u212f .^ (t.-1))) < tol\n        @test eltype(t)==T\n\n        # dv       dw\n        # -- = -w, -- = v ==> v = v0*cos(t) - w0*sin(t), w = w0*cos(t) + v0*sin(t)\n        # dt       dt\n        #\n        # y = [v, w]\n        t,y=solver((t,y)->[-y[2]; y[1]], T[1, 2], T[0:.001:2*pi;])\n        ys = hcat(y...)'   # convert Vector{Vector{T}} to Matrix{T}\n        @test maximum(abs.(ys-[cos.(t)-2*sin.(t) 2*cos.(t)+sin.(t)])) < tol\n        @test eltype(t)==T\n    end\nend\n\n# Test negative starting times ODE.ode23s\n@test length(ODE.ode23s((t,y)->[-y[2]; y[1]], [1., 2.], [-5., 0])[1]) > 1\n\n\n# rober testcase from http://www.unige.ch/~hairer/testset/testset.html\nlet\n    println(\"ROBER test case\")\n    function f(t, y)\n        ydot = similar(y)\n        ydot[1] = -0.04*y[1] + 1.0e4*y[2]*y[3]\n        ydot[3] = 3.0e7*y[2]*y[2]\n        ydot[2] = -ydot[1] - ydot[3]\n        ydot\n    end\n    t = [0., 1e11]\n    t,y = ode23s(f, [1.0, 0.0, 0.0], t; abstol=1e-8, reltol=1e-8,\n                                        maxstep=1e11/10, minstep=1e11/1e18)\n\n    refsol = [0.2083340149701255e-07,\n              0.8333360770334713e-13,\n              0.9999999791665050] # reference solution at tspan[2]\n    @test LinearAlgebra.norm(refsol-y[end], Inf) < 2e-10\nend\ninclude(\"interface-tests.jl\")\ninclude(\"common.jl\")\nprintln(\"All looks OK\")\n", "meta": {"hexsha": "3e5837f0d7ea3dba6130627763acce97c55be860", "size": 2786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "stjordanis/ODE.jl", "max_stars_repo_head_hexsha": "79d43ae51a08e7650e72ed9dddd3547aa06d8301", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2016-09-08T12:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T18:46:19.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "stjordanis/ODE.jl", "max_issues_repo_head_hexsha": "79d43ae51a08e7650e72ed9dddd3547aa06d8301", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 68, "max_issues_repo_issues_event_min_datetime": "2015-01-29T13:56:11.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-25T09:10:07.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "stjordanis/ODE.jl", "max_forks_repo_head_hexsha": "79d43ae51a08e7650e72ed9dddd3547aa06d8301", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2015-01-03T12:57:18.000Z", "max_forks_repo_forks_event_max_datetime": "2016-07-12T02:15:44.000Z", "avg_line_length": 27.86, "max_line_length": 82, "alphanum_fraction": 0.4630294329, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.8577681122619885, "lm_q1q2_score": 0.778263489198928}}
{"text": "using Plots\r\nusing Statistics\r\n\r\nfunction main()\r\n\r\n    x = range(1, 5, length=100)\r\n    l = size(x)\r\n    noise = rand(-2:0.5:2, l)\r\n\r\n    y1 = exp.(x) .+ noise\r\n    y2 = exp.(x)\r\n    yerr = std(noise)\r\n\r\n    # normal_plot(x, y1, y2, yerr)\r\n    # log_plots(x, y1, y2)\r\n    # subplots(x, y1, y2, yerr)\r\n\r\nend\r\n\r\nfunction normal_plot(x, y1, y2, yerr)\r\n\r\n    scatter(x, y1, yerr=yerr, markersize=2, markershape=:o, alpha=0.5, label=\"data\")\r\n    plot!(x, y2, color=\"red\", legend=:topleft, label=\"f(x)\", dpi=200)\r\n    \r\n    annotate!(3, 50, Plots.text(\"Hello world!\", 5, :red))\r\n\r\n    xaxis!(\"x\")\r\n    yaxis!(\"y\")\r\n    title!(\"simple plot\")\r\n\r\nend\r\n\r\n\r\nfunction log_plots(x, y1, y2)\r\n\r\n    scatter(x, y1, markersize=1, markershape=:o, label=\"data\")\r\n    plot!(x, y2, xaxis=\"x\", yaxis=(\"y\", :log), legend=:topleft, label=\"f(x)\", dpi=200)\r\n\r\n    title!(\"log plot\")\r\n\r\nend\r\n\r\nfunction subplots(x, y1, y2, yerr)\r\n\r\n    p1 = scatter(x, y1,yerr=yerr, markershape=:o, markersize=1, alpha=0.5, label=\"data\")\r\n    p1 = plot!(x, y2, yaxis=\"y\", legend=:topleft, label=\"f(x)\", title=\"\u03b1 data\")\r\n\r\n    p2 = scatter(x, y1, label=\"label\")\r\n    p2 = plot!(x, y2, xaxis=\"x\", yaxis=(\"y\", :log), legend=:topleft, label=\"f(x)\")\r\n\r\n    plot(p1, p2, layout=(2,1), dpi=200)\r\n\r\nend\r\n\r\nmain()", "meta": {"hexsha": "8b543a6eb4f5909e908061deb7ee7fa9b571d6ac", "size": 1261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-learning-src/advance/03-more_plotting.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/03-more_plotting.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/03-more_plotting.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": 22.9272727273, "max_line_length": 89, "alphanum_fraction": 0.5535289453, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7782634841020728}}
{"text": "\n\n\n\"\"\"\n\n- `\u207ap\u1d62` : Particle i at next step\n- `p\u1d62`  : Particle i\n- `p\u2c7c`  : Particle j\n- `\u03f5`   : Softening parameter\n\"\"\"\nfunction evaluate_Euler!(\u207aa\u1d62, p\u1d62, p\u2c7c, \u03f5)\n    r = p\u2c7c.r .- p\u1d62.r\n    r\u207b\u00b3 = (norm(r)^2 + \u03f5^2)^(-3/2)\n    \n    @. \u207aa\u1d62 += G * p\u2c7c.m * r\u207b\u00b3 * r\nend\n\n\nfunction evaluate_Euler!(ps, \u03f5)\n    for p\u1d62 in ps\n        p\u1d62.a .= 0.\n        for p\u2c7c in ps\n            p\u1d62 != p\u2c7c && evaluate_Euler!(p\u1d62.a, p\u1d62, p\u2c7c, \u03f5)\n        end\n    end\nend\n\n\nfunction update!(p::AbstractParticle, \u0394t)\n    @. p.v += p.a * \u0394t\n    @. p.r += p.v * \u0394t\nend\n\n\nfunction update!(ps, \u0394t)\n    for p in ps\n        update!(p, \u0394t)\n    end\nend\n\n\nfunction run_Euler(ps, params_sim)\n    @unpack \u03f5, \u0394t, t_end = params_sim\n    \n    times = (0:\u0394t:t_end)\n    ts, rs, vs, as = prep_snapshot(ps, params_sim)\n    \n    for (i, t) in enumerate(times)\n        evaluate_Euler!(ps, \u03f5)\n        save_snapshot!(ts, rs, vs, as, i, t, ps, params_sim)\n        update!(ps, \u0394t)\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)\u03c0r^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) * \u03c0 * 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 \u00f7 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(\u03c4)]=W*\u03b4(t-\u03c4)` where \u03b4 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\u221e 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\u221e norm of the LTI system `sys`.\nThe H\u221e norm is the same as the L\u221e 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\u221e norms.\nIt represents the desired relative accuracy for the computed L\u221e norm\n(this is not an absolute certificate however).\n\nsys is first converted to a state space model if needed.\n\nThe L\u221e norm computation implements the 'two-step algorithm' in:\nN.A. Bruinsma and M. Steinbuch, 'A fast algorithm to compute the H\u221e-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\u221e-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\u221e 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\u221e norm is the same as the L\u221e 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\u221e norm (this is not an absolute certificate however).\n\nsys is first converted to a state space model if needed.\n\nThe L\u221e norm computation implements the 'two-step algorithm' in:\nN.A. Bruinsma and M. Steinbuch, 'A fast algorithm to compute the H\u221e-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\u221e-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\u221e 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\u00f4le 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\u00e4ra 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,\u03a3,V = svd(Q1*P*Q1')\n    \u03a3 .= sqrt.(\u03a3)\n    \u03a31 = diagm(0 => sqrt.(\u03a3))\n    T = \u03a31\\(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(\u03a3)\n    end\n\n    sysr = ST(T*sys.A/T, T*sys.B, sys.C/T, sys.D, sys.Ts), diagm(0 => \u03a3)\nend\n\n\n\"\"\"\n`sysr, G = baltrunc(sys::StateSpace, atol = \u221a\u03f5, 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 \u03c3max` 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\u00e4ra 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\u0303 = x` on `sys` such that\n```\nA\u0303 = T\u207b\u00b9AT\nB\u0303 = T\u207b\u00b9 B\nC\u0303 = CT\nD\u0303 = 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, \u00c5str\u00f6m\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": "function nlp_cvx_102_013(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n\n    @objective(model, Min, x^2 + y^2)\n    @NLconstraint(model, x^2 + y^2 <= 1.0)\n    @constraint(model, x + y >= 1.2)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, 0.72, tol = objective_tol)\n    return check_solution([x, y], [0.6, 0.6], tol = primal_tol)\nend\n", "meta": {"hexsha": "041db33e7916288b59fac2769a14ab463267c027", "size": 603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/102_013.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/102_013.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/102_013.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 25.125, "max_line_length": 76, "alphanum_fraction": 0.671641791, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7782215919086671}}
{"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": "using ForwardDiff\n\n#thresh = 1e-12\n\n@testset \"Derivative checks\" begin\n\n    ###################################\n    # Test Jacobians\n    ###################################\n\n    @testset \"Jacobian checks\" begin\n\n        # Quaternion to rotation matrix\n        @testset \"Jacobian (QuatRotation -> RotMatrix)\" begin\n            for i = 1:10    # do some repeats\n                q = rand(QuatRotation)  # a random quaternion\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(RotMatrix, q)\n                FD_jac = ForwardDiff.jacobian(x -> SVector{9}(QuatRotation(x[1], x[2], x[3], x[4])),\n                                              Rotations.params(q))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n\n        # MRP to UnitQuternion\n        @testset \"Jacobian (MRP -> QuatRotation)\" begin\n            for i = 1:10    # do some repeats\n                p = rand(MRP)  # a random MRP\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(QuatRotation, p)\n                FD_jac = ForwardDiff.jacobian(x -> (q = QuatRotation(MRP(x[1],x[2],x[3]));\n                                                    Rotations.params(q)),\n                                              SVector(p.x, p.y, p.z))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n\n        @testset \"Jacobian (MRP -> QuatRotation) [Corner Cases]\" begin\n            for p = [MRP(1.0, 0.0, 0.0), MRP(0.0, 1.0, 0.0), MRP(0.0, 0.0, 1.0)]\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(QuatRotation, p)\n                FD_jac = ForwardDiff.jacobian(x -> (q = QuatRotation(MRP(x[1],x[2],x[3]));\n                                                    Rotations.params(q)),\n                                              SVector(p.x, p.y, p.z))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n\n        # MRP to QuatRotation\n        @testset \"Jacobian (QuatRotation -> MRP)\" begin\n            for i = 1:10    # do some repeats\n                q = rand(QuatRotation)  # a random QuatRotation\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(MRP, q)\n                FD_jac = ForwardDiff.jacobian(x -> (p = MRP(QuatRotation(x[1], x[2], x[3], x[4]));\n                                                    SVector(p.x, p.y, p.z)),\n                                              Rotations.params(q))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n\n        # MRP to rotation matrix\n        @testset \"Jacobian (MRP -> RotMatrix)\" begin\n            for i = 1:10    # do some repeats\n                p = rand(MRP)  # a random MRP\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(RotMatrix, p)\n                FD_jac = ForwardDiff.jacobian(x -> SVector{9}(MRP(x[1], x[2], x[3])),\n                                              SVector(p.x, p.y, p.z))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n\n\n        ##############################\n        # Jacobians for rotating stuff\n        ##############################\n#=\n        # Quaternion multiplication\n        @testset \"Jacobian (Quaternion muliplication w.r.t. the right quaternion)\" begin\n\n            for i = 1:10    # do some repeats\n\n                ql = quatrand()    # a random quaternion (should work for non-unit quaternions)\n                qr = quatrand()    # a random quaternion (should work for non-unit quaternions)\n\n                # transformation function\n                J(X) = vec(ql * Quaternion(X...))\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(ql, qr)\n                FD_jac = ForwardDiff.jacobian(J, vec(qr))\n\n                # compare\n                @test all(abs(Matrix(R_jac) - FD_jac) .< thresh)\n\n            end\n        end\n\n\n        @testset \"Jacobian (Quaternion muliplication w.r.t. the left quaternion)\" begin\n\n            for i = 1:10    # do some repeats\n\n                ql = quatrand()    # a random quaternion (should work for non-unit quaternions)\n                qr = quatrand()    # a random quaternion (should work for non-unit quaternions)\n\n                # transformation function\n                J(X) = vec(Quaternion(X...) * qr)\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(ql, qr, Val{false})\n                FD_jac = ForwardDiff.jacobian(J, vec(ql))\n\n                # compare\n                @test all(abs(Matrix(R_jac) - FD_jac) .< thresh)\n\n            end\n        end =#\n\n\n        # rotate a point by a RotMatrix\n        @testset \"Jacobian (RotMatrix rotation)\" begin\n            for i = 1:10    # do some repeats\n                r = rand(RotMatrix{3,Float64})    # a random quaternion\n                v = randn(SVector{3,Float64})\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(r, v)\n                FD_jac = ForwardDiff.jacobian(x -> RotMatrix(x)*v,\n                                              SVector(r))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n\n        # rotate a point by a quaternion\n        @testset \"Jacobian (QuatRotation rotation)\" begin\n            for i = 1:10    # do some repeats\n                q = rand(QuatRotation)    # a random quaternion\n                v = randn(SVector{3,Float64})\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(q, v)\n                FD_jac = ForwardDiff.jacobian(x -> QuatRotation(x[1], x[2], x[3], x[4])*v,\n                                              Rotations.params(q))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n\n        # rotate a point by a MRP\n        @testset \"Jacobian (MRP rotation)\" begin\n            for i = 1:10    # do some repeats\n                p = rand(MRP)    # a random quaternion\n                v = randn(SVector{3,Float64})\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(p, v)\n                FD_jac = ForwardDiff.jacobian(x -> MRP(x[1], x[2], x[3])*v,\n                                              SVector(p.x, p.y, p.z))\n\n                # compare\n                @test FD_jac \u2248 R_jac\n            end\n        end\n#=\n        # rotate a point by an MRP\n        @testset \"Jacobian (MRP rotation)\" begin\n\n            for i = 1:10    # do some repeats\n\n                spq = SpQuat(nquatrand())    # a random quaternion\n                X = randn(Vec{3,Float64})\n\n                # transformation function\n                J(spq) = Vector(rotate(SpQuat(spq...), X))\n\n                # test jacobian to a Rotation matrix\n                R_jac = Rotations.jacobian(spq, X)\n                FD_jac = ForwardDiff.jacobian(J, vec(spq))\n\n                # compare\n                @test all(abs(Matrix(R_jac) - FD_jac) .< thresh)\n\n            end\n        end\n=#\n\n    end\n\n\n    ###################################\n    # Test Hessians\n    ###################################\n    #=\n    @testset \"Hessian checks\" begin\n\n        # SpQuat to Quaternion\n        @testset \"Hessian (SpQuat -> Quaternion)\" begin\n\n            for i = 1:10    # do some repeats\n\n                q = nquatrand()                           # a random quaternion\n                spq = Rotations.quat_to_spquat_naive(q)   # I want to test the full domain of SpQuats, not just the one with ||.|| < 1\n\n                # test jacobian to a Rotation matrix\n                R_hess = Rotations.hessian(Quaternion, spq)\n                for d = 1:4\n                    H(X) = vec(Quaternion(SpQuat(X...)))[d]   # transformation function\n                    FD_hess = ForwardDiff.hessian(H, vec(spq))\n\n                    # compare\n                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)\n                end\n            end\n        end\n\n\n        # Quaternion to SpQuat\n        @testset \"Hessian (Quaternion -> SpQuat)\" begin\n\n            for i = 1:10    # do some repeats\n\n                q = nquatrand()                           # a random quaternion\n\n                # test jacobian to a Rotation matrix\n                R_hess = Rotations.hessian(SpQuat, q)\n                for d = 1:3\n                    H(X) = vec(SpQuat(Quaternion(X...)))[d]   # transformation function\n                    FD_hess = ForwardDiff.hessian(H, vec(q))\n\n                    # compare\n                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)\n                end\n            end\n        end\n\n        @testset \"Hessian (Quaternion rotation)\" begin\n\n            for i = 1:10   # do some repeats\n\n                q = nquatrand()    # a random quaternion\n                X = randn(Vec{3,Float64})\n\n                # transformation function\n                R_hess = Rotations.hessian(q, X)\n\n                for d = 1:3\n                    H(q) = Vector(rotate(Quaternion(q...), X))[d]\n\n                    # test\n                    FD_hess = ForwardDiff.hessian(H, vec(q))\n\n                    # compare\n                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)\n                end\n            end\n        end\n\n        @testset \"Hessian (SpQuat rotation)\" begin\n\n            for i = 1:10    # do some repeats\n\n                q = nquatrand()    # a random quaternion\n                spq = SpQuat(q)\n                X = randn(Vec{3,Float64})\n\n                # transformation function\n                R_hess = Rotations.hessian(spq, X)\n\n                for d = 1:3\n                    H(spq) = Vector(rotate(SpQuat(spq...), X))[d]\n\n                    # test\n                    FD_hess = ForwardDiff.hessian(H, vec(spq))\n\n                    # compare\n                    @test all(abs(Matrix(R_hess[d]) - FD_hess) .< thresh)\n                end\n            end\n        end\n    end =#\nend\n", "meta": {"hexsha": "047750970f57faa6eb20fa853717beae31b94e48", "size": 10080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/derivative_tests.jl", "max_stars_repo_name": "nhz2/Rotations.jl", "max_stars_repo_head_hexsha": "827c6447998fdfa393bd027a0bab8bde2aef29f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-03-11T14:31:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T17:42:06.000Z", "max_issues_repo_path": "test/derivative_tests.jl", "max_issues_repo_name": "nhz2/Rotations.jl", "max_issues_repo_head_hexsha": "827c6447998fdfa393bd027a0bab8bde2aef29f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2020-03-11T06:31:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T03:55:25.000Z", "max_forks_repo_path": "test/derivative_tests.jl", "max_forks_repo_name": "nhz2/Rotations.jl", "max_forks_repo_head_hexsha": "827c6447998fdfa393bd027a0bab8bde2aef29f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-03-22T00:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T09:11:24.000Z", "avg_line_length": 33.488372093, "max_line_length": 134, "alphanum_fraction": 0.4507936508, "num_tokens": 2464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.778221585548823}}
{"text": "# tests for library routines\n\nimport SPTK: agexp, gexp, glog, mseq, theq!, theq, toeplitz!, toeplitz\n\nfunction test_agexp()\n    println(\"-- test_agexp\")\n    @test_approx_eq agexp(1, 1, 1) 5.0\n    @test_approx_eq agexp(1, 2, 3) 18.0\n    @test_approx_eq agexp(2, 3, 5) 12.206555615733702\nend\n\nfunction test_gexp()\n    println(\"-- test_gexp\")\n    @test_approx_eq gexp(1, 1) 2.0\n    @test_approx_eq gexp(2, 4) 3.0\nend\n\nfunction test_glog()\n    println(\"-- test_glog\")\n    @test_approx_eq glog(1, 2) 1.0\n    @test_approx_eq glog(2, 3) 4.0\nend\n\nfunction test_mseq()\n    println(\"-- test_mseq\")\n    for i = 1:1000 @test !isnan(mseq()) end\nend\n\nfunction fill_toeplitz!{T}(A::AbstractMatrix{T}, t::AbstractVector{T})\n    n = length(t)\n    for j=1:n, i=1:n\n        A[i,j] = i-j+1 >= 1 ? t[i-j+1] : t[j-i+1]\n    end\n    A\nend\n\nfunction fill_hankel!{T}(A::AbstractMatrix{T}, h::AbstractVector{T})\n    n = length(h)>>1 + 1\n    for j=1:n, i=1:n\n        A[i,j] = h[i+j-1]\n    end\n    A\nend\n\n# (T + H)a = b\nfunction test_theq()\n    println(\"-- test_theq\")\n    srand(98765)\n\n    n = 2\n    # toeplitz elements\n    t = [1.0, -1.0]\n    T = zeros(2,2)\n    fill_toeplitz!(T, t)\n\n    # hankel elements\n    h = zeros(2n-1)\n    h[1] = 1.0\n    h[3] = 1.0\n    H = zeros(2,2)\n    fill_hankel!(H, h)\n\n    b = ones(n)\n    a = zeros(n)\n\n    # solve (T + H)a = b\n    theq!(a, t, h, b)\n    @test_approx_eq a ones(n)\n    @test_approx_eq a theq(t, h, b)\n    @test_approx_eq a (T + H) \\ b\n\n    # fail to solve toeplitz plus hankel matrix system\n    for m in [3, 5, 10]\n        a = ones(m)\n        t = ones(a)\n        h = ones(2length(a)-1)\n        b = ones(a)\n        @test_throws ErrorException theq!(a, t, h, b)\n    end\n\n    a = ones(5)\n    t = ones(a)\n    h = ones(2length(a)-1)\n    b = ones(a)\n\n    @test_throws ArgumentError theq!(a, t, h, b, min_det=-1.0)\n    @test_throws DimensionMismatch theq!(a, t, h, ones(length(b)-1))\n    @test_throws DimensionMismatch theq!(a, t, ones(length(h)-1), b)\n    @test_throws DimensionMismatch theq!(a, t, ones(length(h)-1), b)\n    @test_throws DimensionMismatch theq!(a, ones(length(t)-1), h, b)\n    @test_throws DimensionMismatch theq!(ones(length(a)-1), t, h, b)\nend\n\n# Ta = b\nfunction test_toeplitz()\n    println(\"-- test_toeplitz\")\n    srand(98765)\n\n    n = 2\n    # toeplitz elements\n    t = [2.0, -1.0]\n    T = zeros(2,2)\n    fill_toeplitz!(T, t)\n    b = [1.0, 1.0]\n    b = ones(n)\n    a = zeros(n)\n\n    # solve Ta = b\n    toeplitz!(a, t, b)\n    @test_approx_eq a ones(n)\n    @test_approx_eq a toeplitz(t, b)\n    @test_approx_eq a T \\ b\n\n    # fail to solve toeplitz set of linear equations\n    for m in [3, 5, 10]\n        a = ones(m)\n        t = ones(a)\n        b = ones(a)\n        @test_throws ErrorException toeplitz!(a, t, b)\n    end\n\n    a = ones(5)\n    t = ones(a)\n    b = ones(a)\n    @test_throws ArgumentError toeplitz!(a, t, b, eps=-1.0)\n    @test_throws DimensionMismatch toeplitz!(a, t, ones(length(b)-1))\n    @test_throws DimensionMismatch toeplitz!(a, ones(length(t)-1), b)\n    @test_throws DimensionMismatch toeplitz!(ones(length(a)-1), t, b)\nend\n\nprintln(\"test library routines\")\ntest_agexp()\ntest_gexp()\ntest_glog()\ntest_mseq()\ntest_theq()\ntest_toeplitz()\n", "meta": {"hexsha": "ec0b5d59c1181ca55fdbf78499b7a7c18e236644", "size": 3183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/lib.jl", "max_stars_repo_name": "JuliaPackageMirrors/SPTK.jl", "max_stars_repo_head_hexsha": "2fb5f51caf336edbd8ffd4e72fcc02d3f323ad06", "max_stars_repo_licenses": ["MIT"], "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/lib.jl", "max_issues_repo_name": "JuliaPackageMirrors/SPTK.jl", "max_issues_repo_head_hexsha": "2fb5f51caf336edbd8ffd4e72fcc02d3f323ad06", "max_issues_repo_licenses": ["MIT"], "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/lib.jl", "max_forks_repo_name": "JuliaPackageMirrors/SPTK.jl", "max_forks_repo_head_hexsha": "2fb5f51caf336edbd8ffd4e72fcc02d3f323ad06", "max_forks_repo_licenses": ["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.0652173913, "max_line_length": 70, "alphanum_fraction": 0.5859252278, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7782215849139136}}
{"text": "export calc_k, calc_\u03bb, calc_\u03ba\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(\u03bb, n=1)\n\nCalculate the value of the (angular) wave number with vacuum wavelength `\u03bb` in\nmedium with refractive index `n`.\nIt holds: \\$ k = \\\\kappa \\\\cdot 2 \\\\pi \\$\n\"\"\"\nfunction calc_k(\u03bb, n=1)\n    return 2 * oftype(\u03bb, \u03c0) * n / \u03bb\nend\n\n\"\"\"\n    calc_\u03ba(\u03bb, n=1)\n\nCalculate the value of the (non angular) wave number with vacuum wavelength `\u03bb` in\nmedium with refractive index `n`.\nIt holds: \\$ \\\\kappa = \\\\frac{k}{2 \\\\pi} \\$\n\"\"\"\nfunction calc_\u03ba(\u03bb, n=1)\n    return calc_k(\u03bb, n) / 2 / oftype(\u03bb, \u03c0)\nend\n\n\n\"\"\"\n    calc_\u03bb(k, n=1)\n\nCalculate the vacuum wavelength `\u03bb` from the angular wave number `k` in \nmedium with refractive index `n`.\nIt holds: \\$ \\\\lambda = \\\\frac{n \\\\cdot 2 \\\\pi}{k} \\$\n\"\"\" \nfunction calc_\u03bb(k, n=1)\n    return 2 * oftype(k, \u03c0) * n / k\nend\n\n\n\"\"\"\n    fresnel_number(a, L, \u03bb=\u03bb0)\n\nCalculate the Fresnel number where `a` is the characteristic size,\n`L` the distance from screen to aperture and `\u03bb` the wavelength.\n\"\"\"\nfunction fresnel_number(a, L, \u03bb=\u03bb0)\n    return a^2 / L / \u03bb\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": "using Test\nusing Random\nusing UnitTestDesign\n\n\n### total_combinations\ntc_trials = [\n    [[2, 2, 2], 2, 12],\n    [[2, 3, 2], 2, 16],\n    [[2, 3, 2, 2], 2, 6+4+4+6+6+4],\n    [[2, 3, 2, 2], 3, 12+12+8+12]\n]\nfor trial in tc_trials\n    res = UnitTestDesign.total_combinations(trial[1], trial[2])\n    @test res == trial[3]\nend\n\n\n### combination_number\n\nfor cn_a in 1:6\n    for cn_b in 1:cn_a\n        @test UnitTestDesign.combination_number(cn_a, cn_b) == factorial(cn_a) \u00f7 (factorial(cn_a - cn_b) * factorial(cn_b))\n    end\nend\n\n\n### next_multiplicative\narity0 = [3, 7, 9, 4]\nvv0 = copy(arity0)\nUnitTestDesign.next_multiplicative!(vv0, arity0)\n@test vv0 == [1, 1, 1, 1]\nvv = [1,1,1]\nnmarity = [2,3,2]\nfor i in 1:prod(nmarity)\n    UnitTestDesign.next_multiplicative!(vv, nmarity)\nend\n@test vv == [1, 1, 1]\n\n\n### all_combinations\nrng = MersenneTwister(9237425)\nfor ac_trial_idx in 1:5\n    n_way = [2, 3, 4][rand(rng, 1:3)]\n    param_cnt = rand(rng, (n_way + 1):(n_way + 3))\n    arity = rand(rng, 2:4, param_cnt)\n    coverage = UnitTestDesign.all_combinations(arity, n_way)\n    # It has the right column dimnsion.\n    @test size(coverage, 1) == length(arity)\n    # Every combination is nonzero.\n    @test sum(sum(coverage, dims = 1) == 0) == 0\n    # The total number of combinations agrees with expectations.\n    @test UnitTestDesign.total_combinations(arity, n_way) == size(coverage, 2)\n    # Generate some random combinations and check that they are in there.\n    for comb_idx in 1:100\n        comb = [rand(rng, 1:arity[cj]) for cj in 1:param_cnt]\n        comb[randperm(rng, param_cnt)[1:(param_cnt - n_way)]] .= 0\n        @test sum(comb .!= 0) == n_way\n        found = false\n        for sidx in 1:size(coverage, 2)\n            if coverage[:, sidx] == comb\n                found = true\n            end\n        end\n        @test found\n    end\nend\n\n\n### one_parameter_combinations(arity, n_way)\n\nminimal = UnitTestDesign.one_parameter_combinations([2, 3], 1)\n@test minimal == [0 1; 0 2; 0 3]'\n\npaired = UnitTestDesign.one_parameter_combinations([2, 3], 2)\n@test paired == [1 1; 2 1; 1 2; 2 2; 1 3; 2 3]'\n\nsingled = UnitTestDesign.one_parameter_combinations([2, 2, 3], 2)\n@test singled == [\n    1 0 1; 2 0 1; 0 1 1; 0 2 1;\n    1 0 2; 2 0 2; 0 1 2; 0 2 2;\n    1 0 3; 2 0 3; 0 1 3; 0 2 3\n    ]'\n\nagain = UnitTestDesign.one_parameter_combinations([2, 2, 3], 3)\n@test again == [\n    1 1 1; 1 2 1; 2 1 1; 2 2 1;\n    1 1 2; 1 2 2; 2 1 2; 2 2 2;\n    1 1 3; 1 2 3; 2 1 3; 2 2 3\n    ]'\n", "meta": {"hexsha": "7e6327ccc717e0affc6deaad7935501df426a18b", "size": 2467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 27.1098901099, "max_line_length": 123, "alphanum_fraction": 0.609647345, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.778219085228001}}
{"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\u2013Pasta\u2013Ulam 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": "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\"))\ndropmissing!(d, [:temp, :doy])\n\n# scatter(d.temp, d.doy, alpha = 0.3)\n\n# %%\n# First, a pure linear model.\nflin(temp, \u03b1, \u03b2) = \u03b1 .+ \u03b2 .* temp\n\n@model function cherry_linear(temp, doy)\n    # \u03b2: With a higher temperature I expect the doy to be earlier. Maybe 1 month per 10\u00b0C?\n    \u03b1 ~ Normal(100, 10)\n    \u03b2 ~ Normal(-3, 2)\n    \u03c3 ~ Exponential(1)\n    \u03bc = flin(temp, \u03b1, \u03b2)\n    doy ~ MvNormal(\u03bc, \u03c3)\nend\n\nm = cherry_linear(d.temp, d.doy)\n\n# %%\n# Sample from the prior. Looks pretty reasonable.\nprior = sample(m, Prior(), 100) |> DataFrame\n\nscatter(d.year,  d.doy, alpha = 0.3)\nfor r in eachrow(prior)\n    p = flin(d.temp, r.\u03b1, r.\u03b2)\n    plot!(d.year, p, alpha = 0.2)\nend\nplot!(legend = false, ylims = (0, 200))\n\n# %%\n# Fit and show the fit.\nq = quap(m)\npost = DataFrame(rand(q.distr, 1000)', [\"\u03b1\", \"\u03b2\", \"\u03c3\"])\n\nmu = flin(d.temp, post.\u03b1', post.\u03b2')\nmu_m, mu_lower, mu_upper = meanlowerupper(mu)\nsim = rand.(Normal.(mu, post.\u03c3'))\nsim_m, sim_lower, sim_upper = meanlowerupper(sim)\n\nscatter(d.year, d.doy, alpha = 0.3, legend = false)\nplot!(d.year, mu_m, ribbon = (mu_m .- mu_lower, mu_upper .- mu_m))\nplot!(d.year, sim_lower, fillrange = sim_upper, alpha = 0.3, linealpha = 0.0, c = 2)\n\n# %%\n# Second, a linear model enhanced with extra wiggle.\nusing BSplines: BSplineBasis, basismatrix\n\nnum_knots = 15\nknot_list = quantile(d.year, range(0, 1, length = num_knots))\n\nbasis = BSplineBasis(4, knot_list)\nB = basismatrix(basis, d.year)\n\n# %%\n# Fit the model.\n@model function spline(temp, doy, B = B)\n    \u03b1 ~ Normal(100, 10)\n    \u03b2 ~ Normal(-3, 2)\n    w ~ filldist(Normal(0, 10), size(B, 2))\n    \u03c3 ~ Exponential(1)\n    \u03bc = flin(temp, \u03b1, \u03b2) .+ B * w\n    doy ~ MvNormal(\u03bc, \u03c3)\nend\n\nsample(spline(d.temp, d.doy), NUTS(), 1000)\n\nqspl = quap(spline(d.temp, d.doy))\n\nw_str = [\"w[$i]\" for i in 1:length(basis)]\npost = DataFrame(rand(qspl.distr, 1000)', [\"\u03b1\"; \"\u03b2\"; w_str; \"\u03c3\"])\n\nsmu = fspl(d.temp, post.\u03b1', post.\u03b2', Array(post[!, w_str])', B)\nsmu_m, smu_lower, smu_upper = meanlowerupper(smu)\n\n# %%\n# Display both solutions together.\nscatter(d.year, d.doy, alpha = 0.3, label = \"data\")\nplot!(d.year, smu_m, ribbon = (smu_m .- smu_lower, smu_upper .- smu_m), label = \"linear\")\nplot!(d.year, mu_m, ribbon = (mu_m .- mu_lower, mu_upper .- mu_m), label = \"linear+spline\")\n", "meta": {"hexsha": "0b52696fec2d666d1efb54880ff2e4ec5d89d148", "size": 2544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch04/4H5.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/4H5.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/4H5.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.5, "max_line_length": 91, "alphanum_fraction": 0.641509434, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7782190788815806}}
{"text": "\nusing ModelingToolkit\nusing DiffEqJump\nusing Random\nusing DataFrames\nusing Tables\nusing StatsPlots\nusing BenchmarkTools\n\n\n@parameters \u03b2 c \u03b3\n@variables t S(t) I(t) R(t)\nN = S+I+R\nrate\u2081   = \u03b2*c*S*I/N\naffect\u2081 = [S ~ S - 1, I ~ I + 1]\nrate\u2082   = \u03b3*I\naffect\u2082 = [I ~ I - 1, R ~ R + 1]\nj\u2081      = ConstantRateJump(rate\u2081,affect\u2081)\nj\u2082      = ConstantRateJump(rate\u2082,affect\u2082)\n@named sir_js = JumpSystem([j\u2081,j\u2082], t, [S,I,R], [\u03b2,c,\u03b3])\n\n\ntmax = 40.0\ntspan = (0.0,tmax)\n\u03b4t = 1.0;\n\n\nu0 = [S => 990, I => 10, R => 0];\n\n\np = [\u03b2 => 0.05, c => 10.0, \u03b3 => 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:\u03b4t: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": "using LinearAlgebra, IntervalSets, UnPack\nimport ClimaCore: Domains, Topologies, Meshes, Spaces, Geometry\n\nusing Test\n\n@testset \"Surface area of a sphere\" begin\n    FT = Float64\n    radius = FT(3)\n    ne = 4\n    Nq = 4\n    domain = Domains.SphereDomain(radius)\n    mesh = Meshes.EquiangularCubedSphere(domain, ne)\n    grid_topology = Topologies.Topology2D(mesh)\n    quad = Spaces.Quadratures.GLL{Nq}()\n    space = Spaces.SpectralElementSpace2D(grid_topology, quad)\n\n    @test sum(ones(space)) \u2248 4pi * radius^2 rtol = 1e-3\nend\n\n@testset \"Volume of a spherical shell\" begin\n    FT = Float64\n    radius = FT(128)\n    zlim = (0, 1)\n    helem = 4\n    zelem = 10\n    Nq = 4\n\n    vertdomain = Domains.IntervalDomain(\n        Geometry.ZPoint{FT}(zlim[1]),\n        Geometry.ZPoint{FT}(zlim[2]);\n        boundary_tags = (:bottom, :top),\n    )\n    vertmesh = Meshes.IntervalMesh(vertdomain, nelems = zelem)\n    vert_center_space = Spaces.CenterFiniteDifferenceSpace(vertmesh)\n\n    horzdomain = Domains.SphereDomain(radius)\n    horzmesh = Meshes.EquiangularCubedSphere(horzdomain, helem)\n    horztopology = Topologies.Topology2D(horzmesh)\n    quad = Spaces.Quadratures.GLL{Nq}()\n    horzspace = Spaces.SpectralElementSpace2D(horztopology, quad)\n\n    hv_center_space =\n        Spaces.ExtrudedFiniteDifferenceSpace(horzspace, vert_center_space)\n\n    # \"shallow atmosphere\" spherical shell: volume = surface area * height\n    @test sum(ones(hv_center_space)) \u2248 4pi * radius^2 * (zlim[2] - zlim[1]) rtol =\n        1e-3\nend\n", "meta": {"hexsha": "2497d54e5156ade652374c5c024df677ef2758c1", "size": 1507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sphere_metric_terms.jl", "max_stars_repo_name": "CliMA/ClimaCore.jl", "max_stars_repo_head_hexsha": "e28309249a4c0dea0e8bb897b4dc9ebc376fa94e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-07-19T20:14:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T00:18:43.000Z", "max_issues_repo_path": "test/sphere_metric_terms.jl", "max_issues_repo_name": "CliMA/ClimaCore.jl", "max_issues_repo_head_hexsha": "e28309249a4c0dea0e8bb897b4dc9ebc376fa94e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 543, "max_issues_repo_issues_event_min_datetime": "2021-07-06T18:21:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:39:02.000Z", "max_forks_repo_path": "test/sphere_metric_terms.jl", "max_forks_repo_name": "CliMA/ClimateMachineCore.jl", "max_forks_repo_head_hexsha": "73dff5e125aa641b1560f3ca5163db472c1ed07a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-27T16:54:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T16:54:21.000Z", "avg_line_length": 30.7551020408, "max_line_length": 82, "alphanum_fraction": 0.6907763769, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7781867719003157}}
{"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": "using JuMP, GLPK, Test\n\nfunction optimal_price_probabilties(\n    price, demand, capacity; verbose = true)\n    revenue = price .* demand\n    model = Model(with_optimizer(GLPK.Optimizer))\n    @variable(model, x[1:length(price)], lower_bound=0)\n    # Objective: maximize profit\n    @objective(model, Max, revenue' * x)\n    # Constraint: can carry all\n    @constraint(model, sum(x) <= 1)\n    #=\n    for i in 1:length(prices)\n        @constraint(model, x[i] <= demand[i])\n    end\n    =#\n    # Solve problem using MIP solver\n    JuMP.optimize!(model)\n    if verbose\n        println(\"Objective is: \", JuMP.objective_value(model))\n        println(\"Solution is:\")\n        for i in 1:length(price)\n            print(\"x[$i] = \", JuMP.value(x[i]))\n            println(\", revenue = \", price[i] * JuMP.value(x[i]))\n        end\n    end\n    @test JuMP.termination_status(model) == MOI.OPTIMAL\n    @test JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n    JuMP.value.(x)\nend\n\nprice = [1.99, 2.49, 2.99, 3.49, 3.99, 4.49]\ndemand = 50 .- 7 * price\ncapacity = 60\n\nprob = optimal_price_probabilties(price, demand, capacity)\nprob |> display\nprintln()\n\ndemand2 = [33.74, 31.29, 25.81, 34.68, 31.84, 15.64]\nprob2 = optimal_price_probabilties(price, demand2, capacity)\nprob2 |> display\n", "meta": {"hexsha": "8821ae4663506fad8a484a2dbde69ce4729d7c49", "size": 1261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/jump.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": "test/jump.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": "test/jump.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": 29.3255813953, "max_line_length": 64, "alphanum_fraction": 0.6328310864, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7781867664700436}}
{"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\u03b1_hat_multinomial = optimize(td, startvals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\n\u03b1_hat_multinomial_ad = \u03b1_hat_multinomial.minimizer\r\n\r\n# Find Hessian #\r\nH  = Optim.hessian!(td, \u03b1_hat_multinomial_ad) # Finding the Hessian Matrix\r\n\u03b1_hat_multinomial_ad_se = sqrt.(diag(inv(H))) # Standard Errors of alpha_hat\r\n\r\nprintln([\u03b1_hat_multinomial_ad \u03b1_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_{\u03d5}` for any demand not attended \u03d5.\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_\u03d5::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, \u03d5 >= 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) + \u03d5 == d)\n\n    ## Objectives\n    @objective(model, Min, dot(c_g, g) + c_\u03d5 * \u03d5)\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, \u03f5::Float64 = 1.0)\n    ## Initialization of parameters and references to simplify the notation\n    vect_ref = [model[:g]; model[:\u03d5]]\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}, \u03f5)\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, \u03f5::Float64 = 1.0)\n    ## Initialization of parameters and references to simplify the notation\n    vect_ref = [model[:g]; model[:\u03d5]]\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] = \u03f5\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_\u03d5 = 10.0\n;\n\n# Generate models for each demand `d`\nmodels = generate_model.(d; g_sup = g_sup, c_g = c_g, c_\u03d5 = c_\u03d5);\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": "using LinearAlgebra, DiffEqOperators, Random, Test\n\n# Generate random parameters\nal = rand(5)\nbl = rand(5)\ncl = rand(5)\ndx = rand(5)\nar = rand(5)\nbr = rand(5)\ncr = rand(5)\n\n\n# Construct 5 arbitrary RobinBC operators\nfor i in 1:5\n    Q = RobinBC((al[i], bl[i], cl[i]), (ar[i], br[i], cr[i]), dx[i])\n\n    Q_L, Q_b = Array(Q,5i)\n\n    #Check that Q_L is is correctly computed\n    @test Q_L[2:5i+1,1:5i] \u2248 Array(I, 5i, 5i)\n    @test Q_L[1,:] \u2248 [1 / (1-al[i]*dx[i]/bl[i]); zeros(5i-1)]\n    @test Q_L[5i+2,:] \u2248 [zeros(5i-1); 1 / (1+ar[i]*dx[i]/br[i])]\n\n    #Check that Q_b is computed correctly\n    @test Q_b \u2248 [cl[i]/(al[i]-bl[i]/dx[i]); zeros(5i); cr[i]/(ar[i]+br[i]/dx[i])]\n\n    # Construct the extended operator and check that it correctly extends u to a (5i+2)\n    # vector, along with encoding boundary condition information.\n    u = rand(5i)\n\n    Qextended = Q*u\n    CorrectQextended = [(cl[i]-(bl[i]/dx[i])*u[1])/(al[i]-bl[i]/dx[i]); u; (cr[i]+ (br[i]/dx[i])*u[5i])/(ar[i]+br[i]/dx[i])]\n    @test length(Qextended) \u2248 5i+2\n\n    # Check concretization\n    @test Array(Qextended) \u2248 CorrectQextended\n\n    # Check that Q_L and Q_b correctly compute BoundaryPaddedVector\n    @test Q_L*u + Q_b \u2248 CorrectQextended\n\n    @test [Qextended[1]; Qextended.u; Qextended[5i+2]] \u2248 CorrectQextended\n\nend\n\n# Construct 5 arbitrary RobinBC operators w/non-uniform grid\nal = rand(5)\nbl = rand(5)\ncl = rand(5)\ndx = rand(5)\nar = rand(5)\nbr = rand(5)\ncr = rand(5)\nfor j in 1:2\n    for i in 1:5\n        if j == 1\n            Q = RobinBC((al[i], bl[i], cl[i]), (ar[i], br[i], cr[i]),\n                        dx[i] .* ones(5 * i))\n        else\n            Q = RobinBC([al[i], bl[i], cl[i]], [ar[i], br[i], cr[i]],\n                        dx[i] .* ones(5 * i))\n        end\n        Q_L, Q_b = Array(Q,5i)\n\n        #Check that Q_L is is correctly computed\n        @test Q_L[2:5i+1,1:5i] \u2248 Array(I, 5i, 5i)\n        @test Q_L[1,:] \u2248 [1 / (1-al[i]*dx[i]/bl[i]); zeros(5i-1)]\n        @test Q_L[5i+2,:] \u2248 [zeros(5i-1); 1 / (1+ar[i]*dx[i]/br[i])]\n\n        #Check that Q_b is computed correctly\n        @test Q_b \u2248 [cl[i]/(al[i]-bl[i]/dx[i]); zeros(5i); cr[i]/(ar[i]+br[i]/dx[i])]\n\n        # Construct the extended operator and check that it correctly extends u to a (5i+2)\n        # vector, along with encoding boundary condition information.\n        u = rand(5i)\n\n        Qextended = Q*u\n        CorrectQextended = [(cl[i]-(bl[i]/dx[i])*u[1])/(al[i]-bl[i]/dx[i]); u; (cr[i]+ (br[i]/dx[i])*u[5i])/(ar[i]+br[i]/dx[i])]\n        @test length(Qextended) \u2248 5i+2\n\n        # Check concretization\n        @test Array(Qextended) \u2248 CorrectQextended\n\n        # Check that Q_L and Q_b correctly compute BoundaryPaddedVector\n        @test Q_L*u + Q_b \u2248 CorrectQextended\n\n        @test [Qextended[1]; Qextended.u; Qextended[5i+2]] \u2248 CorrectQextended\n\n    end\nend\n\n#3rd order RobinBC, calculated with left stencil [-11/6 3 -3/2 1/3], right stencil [-1/3 3/2 -3 11/6] and [\u03b1,\u03b2,\u03b3] = [1 6 10]\nu0 = -4/10\nuend = 125/12\nu = Vector(1.0:10.0)\nQ = RobinBC((1.0, 6.0, 10.0), (1.0, 6.0, 10.0), 1.0, 3)\nurobinextended = Q*u\n@test urobinextended.l \u2248 u0\n@test urobinextended.r \u2248 uend\n# General BC should be equivalent\nG = GeneralBC([-10.0, 1.0, 6.0], [-10.0, 1.0, 6.0], 1.0, 3)\nugeneralextended = G*u\n@test ugeneralextended.l \u2248 u0\n@test ugeneralextended.r \u2248 uend\n\n\n#TODO: Implement tests for BC's that are contingent on the sign of the coefficient on the operator near the boundary\n", "meta": {"hexsha": "d7c8b3882d1397387735d91135e061d506f789fc", "size": 3418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/robin.jl", "max_stars_repo_name": "simenhu/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a7faab6cfbe60a04d53690141cd8b71350c38351", "max_stars_repo_licenses": ["MIT"], "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/robin.jl", "max_issues_repo_name": "simenhu/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a7faab6cfbe60a04d53690141cd8b71350c38351", "max_issues_repo_licenses": ["MIT"], "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/robin.jl", "max_forks_repo_name": "simenhu/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a7faab6cfbe60a04d53690141cd8b71350c38351", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-12T14:42:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T14:42:04.000Z", "avg_line_length": 31.9439252336, "max_line_length": 128, "alphanum_fraction": 0.5816266823, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.7781859164041893}}
{"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 `\u03bc` and ``F_\\nu^{-1}`` is the\n# quantile function of `\u03bd`.\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 `\u03bc` and `\u03bd`,\n# respectively.\n# \n# We start by defining the distributions.\n\n\u03bc = Normal(0, 1)\n\nN = 10\n\u03bd = 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, \u03bc, \u03bd);\n\n# `T` is the Monge Map. Let's visualize it.\np1 = plot(\u03bc; label='\u03bc')\np1 = plot!(\u03bd; marker=:circle, label='\u03bd')\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, \u03bc, \u03bd)\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(\u03bc, \u03bd; 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\u03bc = DiscreteNonParametric(1.5rand(M), fill(1 / M, M))\n\nN = 10\n\u03bd = DiscreteNonParametric(1.5rand(N) .+ 2, fill(1 / N, N))\n\n\u03b3 = ot_plan(sqeuclidean, \u03bc, \u03bd);\n\n# This time \u03b3 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(\u03bc; marker=:circle, label='\u03bc')\np = plot!(\u03bd; marker=:circle, label='\u03bd', ylims=(0, 0.2))\nfor i in 1:M, j in 1:N\n    if \u03b3[i, j] > 0\n        transport = curve(\u03bc.support[i], \u03bd.support[j], 1 / M, 1 / N)\n        x = range(\u03bc.support[i], \u03bd.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, \u03bc, \u03bd)\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 \u2208 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\u00b2 = 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\u00b2, 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 OrdinaryDiffEq, Test, DiffEqDevTools\nusing LinearAlgebra, Random\n\n\n# Linear exponential solvers\nA = DiffEqArrayOperator([2.0 -1.0; -1.0 2.0])\nu0 = ones(2)\nprob = ODEProblem(A,u0,(0.0,1.0))\nsol1 = solve(prob, LinearExponential(krylov=:off))(1.0)\nsol2 = solve(prob, LinearExponential(krylov=:simple))(1.0)\nsol3 = solve(prob, LinearExponential(krylov=:adaptive))(1.0)\nsol_analytic = exp(1.0 * Matrix(A)) * u0\n\n@test isapprox(sol1, sol_analytic, rtol=1e-10)\n@test isapprox(sol2, sol_analytic, rtol=1e-10)\n@test isapprox(sol3, sol_analytic, rtol=1e-10)\n\n# u' = A(t)u solvers\n\nfunction update_func(A,u,p,t)\n    A[1,1] = cos(t)\n    A[2,1] = sin(t)\n    A[1,2] = cos(t)*sin(t)\n    A[2,2] = sin(t)^2\nend\nA = DiffEqArrayOperator(ones(2,2),update_func=update_func)\nprob = ODEProblem(A, ones(2), (0.0, 5.))\ndts = 1 ./2 .^(10:-1:1)\nsol  = solve(prob,OrdinaryDiffEq.MagnusMidpoint(),dt=1/4)\n\ndts = 1 ./2 .^(10:-1:1)\ntest_setup = Dict(:alg=>Vern9(),:reltol=>1e-14,:abstol=>1e-14)\nsim = analyticless_test_convergence(dts,prob,MagnusMidpoint(),test_setup)\n@test sim.\ud835\udcaaest[:l2] \u2248 2 atol=0.2\nsim = analyticless_test_convergence(dts,prob,MagnusMidpoint(krylov=true),test_setup)\n@test sim.\ud835\udcaaest[:l2] \u2248 2 atol=0.2\n\nA = DiffEqArrayOperator(ones(2,2),update_func=update_func)\nprob = ODEProblem(A, ones(2), (0.0, 5.))\ndts = 1 ./2 .^(10:-1:1)\nsol  = solve(prob,OrdinaryDiffEq.MagnusLeapfrog(),dt=1/4)\n\ndts = 1 ./2 .^(10:-1:1)\ntest_setup = Dict(:alg=>Vern9(),:reltol=>1e-14,:abstol=>1e-14)\nsim = analyticless_test_convergence(dts,prob,MagnusLeapfrog(),test_setup)\n@test sim.\ud835\udcaaest[:l2] \u2248 2 atol=0.2\nsim = analyticless_test_convergence(dts,prob,MagnusLeapfrog(krylov=true),test_setup)\n@test sim.\ud835\udcaaest[:l2] \u2248 2 atol=0.2\n\nfunction update_func(A,u,p,t)\n    A[1,1] = cos(t)*u[1]\n    A[2,1] = sin(t)*u[2]\n    A[1,2] = -cos(t)*sin(t)\n    A[2,2] = -(sin(t)^2) *u[1] * u[2]\nend\nA = DiffEqArrayOperator(ones(2,2),update_func=update_func)\nprob = ODEProblem(A, ones(2), (0.5, 5.))\ndts = 1 ./2 .^(10:-1:1)\nsol  = solve(prob,OrdinaryDiffEq.LieEuler(),dt=1/4)\n\ndts = 1 ./2 .^(10:-1:1)\ntest_setup = Dict(:alg=>Vern9(),:reltol=>1e-14,:abstol=>1e-14)\nsim = analyticless_test_convergence(dts,prob,LieEuler(),test_setup)\n@test sim.\ud835\udcaaest[:l2] \u2248 1 atol=0.2\nsim = analyticless_test_convergence(dts,prob,LieEuler(krylov=true),test_setup)\n@test sim.\ud835\udcaaest[:l2] \u2248 1 atol=0.2\n", "meta": {"hexsha": "8fe3d6176658b7c3b29408a7aca4e1647b3864c2", "size": 2319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/algconvergence/linear_method_tests.jl", "max_stars_repo_name": "d-netto/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "294783f26bd1a228f738ba9ea9e08c68ec2848fd", "max_stars_repo_licenses": ["MIT"], "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/algconvergence/linear_method_tests.jl", "max_issues_repo_name": "d-netto/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "294783f26bd1a228f738ba9ea9e08c68ec2848fd", "max_issues_repo_licenses": ["MIT"], "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/algconvergence/linear_method_tests.jl", "max_forks_repo_name": "d-netto/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "294783f26bd1a228f738ba9ea9e08c68ec2848fd", "max_forks_repo_licenses": ["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.6119402985, "max_line_length": 84, "alphanum_fraction": 0.680465718, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7780679660057541}}
{"text": "using LinearAlgebra\nusing LinearManifoldCluster\nusing Distributions\nusing Distances\nusing LMCLUS\nusing Test\nusing Random\n\n@testset \"Random direction\" begin\n    n = 1000\n    N = 10\n    pinf, psup = extrema(LinearManifoldCluster.on_ball(N, n))\n    @test pinf > -1.0\n    @test psup <  1.0\n    pinf, psup = extrema(LinearManifoldCluster.in_ball(N, n))\n    @test pinf > -1.0\n    @test psup <  1.0\n    for d in colwise(Euclidean(), LinearManifoldCluster.on_ball(N,n), zeros(N))\n        @test d \u2248 1.\n    end\nend\n\n@testset \"Translation vectors\" begin\n    n = 1000\n    N = 10\n    \u03bc_bounds = 0.25 => 0.75\n    \u03bc = LinearManifoldCluster.translations(N, n, \u03bc_bounds)\n    # distance from center of unit hypercube to\n    # any translation vector should be within bounds\n    for d in colwise(Euclidean(), \u03bc, ones(N)/2.)\n        @test \u03bc_bounds[1]/2. <= d <= \u03bc_bounds[2]/2.\n    end\nend\n\n@testset \"Basis formation\" begin\n    N = 10\n    M = 3\n    B, B\u2032 = LinearManifoldCluster.lm_basis(N, M)\n    @test size(B) == (N,M)\n    @test size(B\u2032) == (N,N-M)\n    P = B*B'\n    @test P*P \u2248 P\n    @test P' \u2248 P\n    P\u2032 = B\u2032*(B\u2032)'\n    @test P\u2032*P\u2032 \u2248 P\u2032\n    @test (P\u2032)' \u2248 P\u2032\nend\n\n@testset \"Manifold cluster generator\" begin\n    n = 1000\n    N = 3\n    M = 2\n    \u03bc_bounds = 0.25 => 0.75\n    t = LinearManifoldCluster.translations(N, 1, \u03bc_bounds)[:]\n    D = Matrix{Float64}(I, N, N)\n    B = D[:,1:2]\n    B\u2032 = D[:, 3:3]\n    \u03a6 = 0.5\n    E = 0.05\n\n    Random.seed!(230898573857)\n    mfld_s = LinearManifoldCluster.generate_cluster(n, t, B, B\u2032, \u03a6, E)\n\n    Random.seed!(230898573857)\n    \u03a6 = fill(0.5, M)\n    E = fill(0.05, N-M)\n    mfld = LinearManifoldCluster.generate_cluster(n, t, B, B\u2032, \u03a6, E)\n    # one scalar bounds and array bounds return values\n    @test mfld_s == mfld\n\n    # manifold size & space dimension\n    @test size(mfld) == (N,n)\n    # if \u03a6 is scalar, then manifold forms a hypercube\n    # with side equal to \u03a6 (\u00b1 E)?\n    mbound_max = norm(fill(\u03a6[1]+E[1],M),2)\n    for d in colwise(Euclidean(), mfld.-t, zeros(N))\n        @test 0.0 <= d <= mbound_max\n    end\n    # if E is scalar, then a distance from any point to\n    # the manifold should be within ||[\u025b, ...,\u025b]||\n    mdist_max = norm(E,2)\n    for d in LMCLUS.distance_to_manifold(mfld, t, B)\n        @test 0.0 <= d <= mdist_max\n    end\n\n    # manifold dimension generator\n    @test LinearManifoldCluster.mdims(10,13,7) == [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7]\nend\n\n@testset \"Multi-manifold cluster generator\" begin\n    n = 1000\n    N = 3\n    M = [1,2,2]\n    \u03c4 = 0.25 => 0.75\n    \u03a6 = Vector{Float64}[   # bounds on manifold points (per manifold wrt dims)\n        [.6],\n        [.2,  .73],\n        [.4, .65]\n    ]\n    E = Vector{Float64}[   # bound of a point extent (per manifold wrt dims)\n        [.05,  .03],\n        [.01],\n        [.04]\n    ]\n    lmcs, Bs, \u03bcs = generate(n,N,M,\u03c4,\u03a6,E)\n    @test length(lmcs) == length(M) # number of manifold\n    @test size(lmcs[1]) == (N,n)      # number of manifold points\n    for i in length(\u03a6)\n        @test size(Bs[i]) == (N,length(\u03a6[i]))  # bases dimensions\n    end\n    @test size(\u03bcs) == (N,length(M))\n\n    # multi-manifold generator (scalar)\n    n = 1000\n    N = 3\n    m = 12\n    \u03c4 = 0.25 => 0.75\n    \u03ba = 1.5\n    lmcs, Bs, \u03bcs = generate(n,N,m,\u03c4,\u03ba)\n    @test length(lmcs) == m\nend\n", "meta": {"hexsha": "d85d9bc49215993304fecd8b11a9d24f33adbdaa", "size": 3247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "wildart/LinearManifoldCluster.jl", "max_stars_repo_head_hexsha": "dea743c5883d588822feac10204de46676f2f0f5", "max_stars_repo_licenses": ["MIT"], "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": "wildart/LinearManifoldCluster.jl", "max_issues_repo_head_hexsha": "dea743c5883d588822feac10204de46676f2f0f5", "max_issues_repo_licenses": ["MIT"], "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": "wildart/LinearManifoldCluster.jl", "max_forks_repo_head_hexsha": "dea743c5883d588822feac10204de46676f2f0f5", "max_forks_repo_licenses": ["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.6147540984, "max_line_length": 89, "alphanum_fraction": 0.5728364644, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7780109513040242}}
{"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\u03d5 = \u03c0/100,\n  \u03d5min = \u03c0/4,\n   Two\u03a9 = 1, \n      g = 10,\n      a = 1,\n    Lj = \u03c0/2000, \n    Uj = 1.0,\n    N\u03d5 = 100,\n    dk = 1e-2,\n    k\u2098 = 3\n    ); \n    \nparams.Fr = (params.Two\u03a9 * params.Lj)^2/(params.g * params.H);\nparams.Ro =  params.Uj/(params.Two\u03a9 * 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\u2098) / params.Lj;\nNk = length(ks);\n\n# Grid and basic state\nD\u03d5, D\u03d52, \u03d5 = geometry(params);\n      U,  E = profile(  \u03d5, params);\n\nplot_basic_state(\u03d5, U, E, \"basic_state.png\")\n\n# initialize fields to store\nNmodes = 2\n     \u03c3 = zeros(Nmodes, Nk);\n     \u03c9 = zeros(Nmodes, Nk);   \n\u03c3modes = zeros(ComplexF64, 3*params.N\u03d5+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\u03d5, D\u03d52, \u03d5, params);\n    local \u03c3[:,cnt], \u03c9[:,cnt], \u03c3modes[:,:,cnt] = compute_spectrum(A, k, params, Nmodes);\nend\n\nplot_growth_rates(ks, \u03c3, Nmodes, \"growth_rates_spherical_Bickley_jet.png\")\n\n#print(\"\u03c3 = \", \u03c3[1,:],\"\\n\")\n\nmode_number = 1;\n      \u03c3_max = maximum(\u03c3[mode_number,:]);\n    k_index = sortperm(\u03c3[mode_number,:],rev=true)[1];\n          k = ks[k_index]; # pick wavenumber\n\nplot_1D_streamfunction(k_index, k, \u03d5, \u03c3modes, mode_number, \"modes_1D_streamfunction.png\")\nplot_2D_streamfunction(k_index, k, \u03d5, \u03c3modes, mode_number, \"modes_2D_streamfunction.png\")\nplot_2D_vorticity(D\u03d5,  k_index, k, \u03d5, \u03c3modes, 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(\u03b8)^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\u00b2 replaced by x\u00b2+y\u00b2+z\u00b2\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": "using Statistics\n\n#mean\nx = [20:100];\nmean(x)\n\n#median\nmedian(skipmissing([10, 32, missing, 41, 75, 96]))\n\nquantile(x, [0.1, 0.5, 0.9])\n\n#standard deviation\nfunction sd(x):\n  expectation = mean(x)\n  x = map(i -> (i - expectation)^2, x)\n  std_dev = sqrt(sum(x)/(length(x) - 1))\n  return std_dev\n", "meta": {"hexsha": "6952501174fb37932693935054e9fa7d19fb94e7", "size": 294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lib_stat.jl", "max_stars_repo_name": "ilkayn01/18.600-probability-RandomVariables", "max_stars_repo_head_hexsha": "640961a15c30713b08776f7412b5fb0b4ed4c8a6", "max_stars_repo_licenses": ["MIT"], "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_stat.jl", "max_issues_repo_name": "ilkayn01/18.600-probability-RandomVariables", "max_issues_repo_head_hexsha": "640961a15c30713b08776f7412b5fb0b4ed4c8a6", "max_issues_repo_licenses": ["MIT"], "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_stat.jl", "max_forks_repo_name": "ilkayn01/18.600-probability-RandomVariables", "max_forks_repo_head_hexsha": "640961a15c30713b08776f7412b5fb0b4ed4c8a6", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 50, "alphanum_fraction": 0.6258503401, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7780109414866562}}
{"text": "function compute_seat_id(spec)\n  front::UInt8 = 0\n  back::UInt8 = 127\n  left::UInt8 = 0\n  right::UInt8 = 7\n  for c in spec\n    if c == 'F'\n      back = div(back - front, 2) + front\n    elseif c == 'B'\n      front = div(back - front, 2) + front\n    elseif c == 'L'\n      right = div(right - left, 2) + left \n    elseif c == 'R'\n      left = div(right - left, 2) + left\n    end\n  end\n\n  back * 8 + right\nend\n\nfunction find_seat(data)\n  seats = sort(map(compute_seat_id, data))\n  max_id = maximum(seats)\n  seat_id = -1\n  for (idx, seat) in enumerate(seats)\n    if seats[idx + 1] == seat + 2\n      seat_id = seat + 1\n      break\n    end\n  end\n\n  max_id, seat_id\nend\n\nfunction solve(data)\n  println(@time find_seat(data))\nend\n\ndata = readlines(\"input.txt\")\nsolve(data)\n", "meta": {"hexsha": "dc499cb343782cad2d564015c390a8661d2a0c98", "size": 764, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/day5/solution.jl", "max_stars_repo_name": "wbthomason/advent", "max_stars_repo_head_hexsha": "87fd3d107df999ebe335dac1fe833efa2a701d53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-12-09T22:11:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-02T03:34:34.000Z", "max_issues_repo_path": "2020/day5/solution.jl", "max_issues_repo_name": "wbthomason/advent", "max_issues_repo_head_hexsha": "87fd3d107df999ebe335dac1fe833efa2a701d53", "max_issues_repo_licenses": ["MIT"], "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/day5/solution.jl", "max_forks_repo_name": "wbthomason/advent", "max_forks_repo_head_hexsha": "87fd3d107df999ebe335dac1fe833efa2a701d53", "max_forks_repo_licenses": ["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.6341463415, "max_line_length": 42, "alphanum_fraction": 0.5876963351, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7780109379333614}}
{"text": "\"\"\"\n    poisson_rng(p, n, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Poisson(`\u03bb`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Poisson distribution is given by:\n\n``f(x, \u03bb) = \\\\frac{\u03bb^x}{x!} e^\u03bb \\\\quad x = 0,1,2,\u2026``\n\n# Examples\n\n```julia-repl\njulia> poisson_rng(3)\n1\u00d71 Matrix{Int64}:\n 7\n\njulia> poisson_rng(10, 5)\n5\u00d71 Matrix{Int64}:\n 13\n 11\n 10\n  8\n 15\n\njulia> poisson_rng(10, (5,5))\n5\u00d75\u00d71 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(\u03bb::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    n = ceil(Int, \u03bb*5)  # ensure n is integer\n    U = expon_rng(\u03bb, (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    \u03b1::Float64\n    \u03b2::Float64\n\n    function Beta(a::Real, b::Real)\n        (a > zero(a) && b > zero(b)) || error(\"\u03b1 and \u03b2 must be positive\")\n        new(float64(a), float64(b))\n    end\n\n    Beta(\u03b1::Real) = Beta(\u03b1, \u03b1)\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.\u03b1, d.\u03b2)\n\n\n#### Statistics\n\nmean(d::Beta) = ((\u03b1, \u03b2) = params(d); \u03b1 / (\u03b1 + \u03b2)) \n\nfunction mode(d::Beta)\n    (\u03b1, \u03b2) = params(d)\n    (\u03b1 > 1.0 && \u03b2 > 1.0) || error(\"mode is defined only when \u03b1 > 1 and \u03b2 > 1.\")\n    return (\u03b1 - 1.0) / (\u03b1 + \u03b2 - 2.0)\nend\n\nmodes(d::Beta) = [mode(d)]\n\nfunction var(d::Beta)\n    (\u03b1, \u03b2) = params(d)\n    s = \u03b1 + \u03b2\n    return (\u03b1 * \u03b2) / (abs2(s) * (s + 1.0))\nend\n\nmeanlogx(d::Beta) = ((\u03b1, \u03b2) = params(d); digamma(\u03b1) - digamma(\u03b1 + \u03b2))\n\nvarlogx(d::Beta) = ((\u03b1, \u03b2) = params(d); trigamma(\u03b1) - trigamma(\u03b1 + \u03b2))\n\nfunction skewness(d::Beta)\n    (\u03b1, \u03b2) = params(d)\n    if \u03b1 == \u03b2\n        return 0.0\n    else\n        s = \u03b1 + \u03b2\n        (2.0 * (\u03b2 - \u03b1) * sqrt(s + 1.0)) / ((s + 2.0) * sqrt(\u03b1 * \u03b2))\n    end\nend\n\nfunction kurtosis(d::Beta)\n    \u03b1, \u03b2 = params(d)\n    s = \u03b1 + \u03b2\n    p = \u03b1 * \u03b2\n    6.0 * (abs2(\u03b1 - \u03b2) * (s + 1.0) - p * (s + 2.0)) / (p * (s + 2.0) * (s + 3.0))\nend\n\nfunction entropy(d::Beta)\n    \u03b1, \u03b2 = params(d)\n    s = \u03b1 + \u03b2\n    lbeta(\u03b1, \u03b2) - (\u03b1 - 1.0) * digamma(\u03b1) - (\u03b2 - 1.0) * digamma(\u03b2) + \n        (s - 2.0) * digamma(s)\nend\n\n\n#### Evaluation\n\ngradlogpdf(d::Beta, x::Float64) = \n    ((\u03b1, \u03b2) = params(d); 0.0 <= x <= 1.0 ? (\u03b1 - 1.0) / x - (\u03b2 - 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    \u03b1 = x_bar * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    \u03b2 = (1.0 - x_bar) * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    Beta(\u03b1, \u03b2)\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\u00b0 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\u00b0 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        \u03b8, \u03d5 = Healpix.pix2ang(beam_map, idx)\n\n        # We could have used `Healpix.ang2vec`, but we need the value\n        # of sin\u03b8 in order to calculate d\u03a9 = sin\u03b8\u22c5d\u03b8\u22c5d\u03d5\n        sin\u03b8, cos\u03b8 = sincos(\u03b8)\n        sin\u03d5, cos\u03d5 = sincos(\u03d5)\n        \n        x = sin\u03b8 * cos\u03d5\n        y = sin\u03b8 * sin\u03d5\n        z = cos\u03b8\n        \n        result += x^l * y^m * z^n * sin\u03b8 * 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 \u21a6 0 if ||x|| = r, +\u221e 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, \u03b3=1.0)\n\nReturns the Moreau envelope (also known as Moreau-Yosida regularization) of function `f` with parameter `\u03b3` (positive), that is\n```math\nf^\u03b3(x) = \\\\min_z \\\\left\\\\{ f(z) + \\\\tfrac{1}{2\u03b3}\\\\|z-x\\\\|^2 \\\\right\\\\}.\n```\nIf ``f`` is convex, then ``f^\u03b3`` 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{\u03bb$(i),f$(i)}(A$(i)x))+ 1/2 \u2016x - prox{\u03bb$(i),f$(i)}(A$(i)x)\u2016\u00b2\"\n\nfun_par( f::MoreauEnvelope,i::Int64)  = \"\u03bb$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 \u03f0\nconst \u03f0 = -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\u2080\u2081::Vector{F},\n    r\u2080\u2082::Vector{F},\n    r\u2080\u2083::Vector{F},\n    v\u2080\u2081::Vector{F},\n    v\u2080\u2082::Vector{F},\n    v\u2080\u2083::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\u2080\u2081)\n    # Prepare the output vectors\n    r\u2081 = copy(r\u2080\u2081)\n    r\u2082 = copy(r\u2080\u2082)\n    r\u2083 = copy(r\u2080\u2083)\n    v\u2081 = copy(v\u2080\u2081)\n    v\u2082 = copy(v\u2080\u2082)\n    v\u2083 = copy(v\u2080\u2083)\n    # Compute the solutions (in-place)\n    for _ in 1:n\n        \u03c1\u2081\u2082 = norm(r\u2081 - r\u2082)^3\n        \u03c1\u2081\u2083 = norm(r\u2081 - r\u2083)^3\n        \u03c1\u2082\u2083 = norm(r\u2082 - r\u2083)^3\n        for k in 1:N\n            a\u2081\u2082 = \u03f0 * (r\u2081[k] - r\u2082[k]) / \u03c1\u2081\u2082\n            a\u2081\u2083 = \u03f0 * (r\u2081[k] - r\u2083[k]) / \u03c1\u2081\u2083\n            a\u2082\u2083 = \u03f0 * (r\u2082[k] - r\u2083[k]) / \u03c1\u2082\u2083\n            a\u2082\u2081 = -a\u2081\u2082\n            a\u2083\u2081 = -a\u2081\u2083\n            a\u2083\u2082 = -a\u2082\u2083\n            r\u2081[k] += h * v\u2081[k]\n            r\u2082[k] += h * v\u2082[k]\n            r\u2083[k] += h * v\u2083[k]\n            v\u2081[k] += h * (a\u2081\u2082 + a\u2081\u2083)\n            v\u2082[k] += h * (a\u2082\u2081 + a\u2082\u2083)\n            v\u2083[k] += h * (a\u2083\u2081 + a\u2083\u2082)\n        end\n    end\n    return r\u2081, r\u2082, r\u2083, v\u2081, v\u2082, v\u2083\nend\n\n# Integrate the three-body problem using the\n# two-step Adams\u2013Bashforth's method, return the\n# values of position and velocity on the last step\nfunction ab2(\n    r\u2080\u2081::Vector{F},\n    r\u2080\u2082::Vector{F},\n    r\u2080\u2083::Vector{F},\n    v\u2080\u2081::Vector{F},\n    v\u2080\u2082::Vector{F},\n    v\u2080\u2083::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\u2080\u2081)\n    # Prepare the output vectors\n    r\u2081 = copy(r\u2080\u2081)\n    r\u2082 = copy(r\u2080\u2082)\n    r\u2083 = copy(r\u2080\u2083)\n    v\u2081 = copy(v\u2080\u2081)\n    v\u2082 = copy(v\u2080\u2082)\n    v\u2083 = copy(v\u2080\u2083)\n    # Prepare buffers for previous values\n    r\u2081_\u2096\u208b\u2081 = copy(r\u2080\u2081)\n    r\u2082_\u2096\u208b\u2081 = copy(r\u2080\u2082)\n    r\u2083_\u2096\u208b\u2081 = copy(r\u2080\u2083)\n    v\u2081_\u2096\u208b\u2081 = copy(v\u2080\u2081)\n    v\u2082_\u2096\u208b\u2081 = copy(v\u2080\u2082)\n    v\u2083_\u2096\u208b\u2081 = copy(v\u2080\u2083)\n    # Compute the second value of the solution\n    # by using the one-step Euler's method\n    r\u2081, r\u2082, r\u2083, v\u2081, v\u2082, v\u2083 = euler(r\u2080\u2081, r\u2080\u2082, r\u2080\u2083, v\u2080\u2081, v\u2080\u2082, v\u2080\u2083, h, UInt(1))\n    # Define a couple of independent coefficients\n    k\u2081 = 3 / 2 * h\n    k\u2082 = -1 / 2 * h\n    # Compute the rest in two steps\n    for _ in 2:n\n        \u03c1\u2081\u2082_\u2096 = norm(r\u2081 - r\u2082)^3\n        \u03c1\u2081\u2083_\u2096 = norm(r\u2081 - r\u2083)^3\n        \u03c1\u2082\u2083_\u2096 = norm(r\u2082 - r\u2083)^3\n        \u03c1\u2081\u2082_\u2096\u208b\u2081 = norm(r\u2081_\u2096\u208b\u2081 - r\u2082_\u2096\u208b\u2081)^3\n        \u03c1\u2081\u2083_\u2096\u208b\u2081 = norm(r\u2081_\u2096\u208b\u2081 - r\u2083_\u2096\u208b\u2081)^3\n        \u03c1\u2082\u2083_\u2096\u208b\u2081 = norm(r\u2082_\u2096\u208b\u2081 - r\u2083_\u2096\u208b\u2081)^3\n        for k in 1:N\n            a\u2081\u2082_\u2096 = k\u2081 * \u03f0 * (r\u2081[k] - r\u2082[k]) / \u03c1\u2081\u2082_\u2096\n            a\u2081\u2083_\u2096 = k\u2081 * \u03f0 * (r\u2081[k] - r\u2083[k]) / \u03c1\u2081\u2083_\u2096\n            a\u2082\u2083_\u2096 = k\u2081 * \u03f0 * (r\u2082[k] - r\u2083[k]) / \u03c1\u2082\u2083_\u2096\n            a\u2081\u2082_\u2096\u208b\u2081 = k\u2082 * \u03f0 * (r\u2081_\u2096\u208b\u2081[k] - r\u2082_\u2096\u208b\u2081[k]) / \u03c1\u2081\u2082_\u2096\u208b\u2081\n            a\u2081\u2083_\u2096\u208b\u2081 = k\u2082 * \u03f0 * (r\u2081_\u2096\u208b\u2081[k] - r\u2083_\u2096\u208b\u2081[k]) / \u03c1\u2081\u2083_\u2096\u208b\u2081\n            a\u2082\u2083_\u2096\u208b\u2081 = k\u2082 * \u03f0 * (r\u2082_\u2096\u208b\u2081[k] - r\u2083_\u2096\u208b\u2081[k]) / \u03c1\u2082\u2083_\u2096\u208b\u2081\n\n            a\u2082\u2081_\u2096 = -a\u2081\u2082_\u2096\n            a\u2083\u2081_\u2096 = -a\u2081\u2083_\u2096\n            a\u2083\u2082_\u2096 = -a\u2082\u2083_\u2096\n            a\u2082\u2081_\u2096\u208b\u2081 = -a\u2081\u2082_\u2096\u208b\u2081\n            a\u2083\u2081_\u2096\u208b\u2081 = -a\u2081\u2083_\u2096\u208b\u2081\n            a\u2083\u2082_\u2096\u208b\u2081 = -a\u2082\u2083_\u2096\u208b\u2081\n\n            r\u2081_\u2096\u208b\u2081[k] = r\u2081[k]\n            r\u2082_\u2096\u208b\u2081[k] = r\u2082[k]\n            r\u2083_\u2096\u208b\u2081[k] = r\u2083[k]\n\n            r\u2081[k] += k\u2081 * v\u2081[k] + k\u2082 * v\u2081_\u2096\u208b\u2081[k]\n            r\u2082[k] += k\u2081 * v\u2082[k] + k\u2082 * v\u2082_\u2096\u208b\u2081[k]\n            r\u2083[k] += k\u2081 * v\u2083[k] + k\u2082 * v\u2083_\u2096\u208b\u2081[k]\n\n            v\u2081_\u2096\u208b\u2081[k] = v\u2081[k]\n            v\u2082_\u2096\u208b\u2081[k] = v\u2082[k]\n            v\u2083_\u2096\u208b\u2081[k] = v\u2083[k]\n\n            v\u2081[k] += a\u2081\u2082_\u2096 + a\u2081\u2083_\u2096 + a\u2081\u2082_\u2096\u208b\u2081 + a\u2081\u2083_\u2096\u208b\u2081\n            v\u2082[k] += a\u2082\u2081_\u2096 + a\u2082\u2083_\u2096 + a\u2082\u2081_\u2096\u208b\u2081 + a\u2082\u2083_\u2096\u208b\u2081\n            v\u2083[k] += a\u2083\u2081_\u2096 + a\u2083\u2082_\u2096 + a\u2083\u2081_\u2096\u208b\u2081 + a\u2083\u2082_\u2096\u208b\u2081\n        end\n    end\n    return r\u2081, r\u2082, r\u2083, v\u2081, v\u2082, v\u2083\nend\n\n# Integrate the three-body problem using the\n# three-step Adams\u2013Bashforth's method, return the\n# values of position and velocity on the last step\nfunction ab3(\n    r\u2080\u2081::Vector{F},\n    r\u2080\u2082::Vector{F},\n    r\u2080\u2083::Vector{F},\n    v\u2080\u2081::Vector{F},\n    v\u2080\u2082::Vector{F},\n    v\u2080\u2083::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\u2080\u2081)\n    # Prepare the output vectors\n    r\u2081 = copy(r\u2080\u2081)\n    r\u2082 = copy(r\u2080\u2082)\n    r\u2083 = copy(r\u2080\u2083)\n    v\u2081 = copy(v\u2080\u2081)\n    v\u2082 = copy(v\u2080\u2082)\n    v\u2083 = copy(v\u2080\u2083)\n    # Prepare buffers for previous values\n    r\u2081_\u2096\u208b\u2081 = copy(r\u2080\u2081)\n    r\u2082_\u2096\u208b\u2081 = copy(r\u2080\u2082)\n    r\u2083_\u2096\u208b\u2081 = copy(r\u2080\u2083)\n    v\u2081_\u2096\u208b\u2081 = copy(v\u2080\u2081)\n    v\u2082_\u2096\u208b\u2081 = copy(v\u2080\u2082)\n    v\u2083_\u2096\u208b\u2081 = copy(v\u2080\u2083)\n    r\u2081_\u2096\u208b\u2082 = copy(r\u2080\u2081)\n    r\u2082_\u2096\u208b\u2082 = copy(r\u2080\u2082)\n    r\u2083_\u2096\u208b\u2082 = copy(r\u2080\u2083)\n    v\u2081_\u2096\u208b\u2082 = copy(v\u2080\u2081)\n    v\u2082_\u2096\u208b\u2082 = copy(v\u2080\u2082)\n    v\u2083_\u2096\u208b\u2082 = copy(v\u2080\u2083)\n    # Compute the second value of the solution\n    # by using the one-step Euler's method\n    r\u2081, r\u2082, r\u2083, v\u2081, v\u2082, v\u2083 = euler(r\u2080\u2081, r\u2080\u2082, r\u2080\u2083, v\u2080\u2081, v\u2080\u2082, v\u2080\u2083, h, UInt(1))\n    # Compute the third value of the solution\n    # by using the two-step Adams\u2013Bashforth's method\n    r\u2081_\u2096\u208b\u2081, r\u2082_\u2096\u208b\u2081, r\u2083_\u2096\u208b\u2081, v\u2081_\u2096\u208b\u2081, v\u2082_\u2096\u208b\u2081, v\u2083_\u2096\u208b\u2081 = r\u2081, r\u2082, r\u2083, v\u2081, v\u2082, v\u2083\n    r\u2081, r\u2082, r\u2083, v\u2081, v\u2082, v\u2083 = ab2(r\u2080\u2081, r\u2080\u2082, r\u2080\u2083, v\u2080\u2081, v\u2080\u2082, v\u2080\u2083, h, UInt(2))\n    # Define a couple of independent coefficients\n    k\u2081 = 23 / 12 * h\n    k\u2082 = -4 / 3 * h\n    k\u2083 = 5 / 12 * h\n    # Compute the rest in two steps\n    for _ in 3:n\n        \u03c1\u2081\u2082_\u2096 = norm(r\u2081 - r\u2082)^3\n        \u03c1\u2081\u2083_\u2096 = norm(r\u2081 - r\u2083)^3\n        \u03c1\u2082\u2083_\u2096 = norm(r\u2082 - r\u2083)^3\n        \u03c1\u2081\u2082_\u2096\u208b\u2081 = norm(r\u2081_\u2096\u208b\u2081 - r\u2082_\u2096\u208b\u2081)^3\n        \u03c1\u2081\u2083_\u2096\u208b\u2081 = norm(r\u2081_\u2096\u208b\u2081 - r\u2083_\u2096\u208b\u2081)^3\n        \u03c1\u2082\u2083_\u2096\u208b\u2081 = norm(r\u2082_\u2096\u208b\u2081 - r\u2083_\u2096\u208b\u2081)^3\n        \u03c1\u2081\u2082_\u2096\u208b\u2082 = norm(r\u2081_\u2096\u208b\u2082 - r\u2082_\u2096\u208b\u2082)^3\n        \u03c1\u2081\u2083_\u2096\u208b\u2082 = norm(r\u2081_\u2096\u208b\u2082 - r\u2083_\u2096\u208b\u2082)^3\n        \u03c1\u2082\u2083_\u2096\u208b\u2082 = norm(r\u2082_\u2096\u208b\u2082 - r\u2083_\u2096\u208b\u2082)^3\n        for k in 1:N\n            a\u2081\u2082_\u2096 = k\u2081 * \u03f0 * (r\u2081[k] - r\u2082[k]) / \u03c1\u2081\u2082_\u2096\n            a\u2081\u2083_\u2096 = k\u2081 * \u03f0 * (r\u2081[k] - r\u2083[k]) / \u03c1\u2081\u2083_\u2096\n            a\u2082\u2083_\u2096 = k\u2081 * \u03f0 * (r\u2082[k] - r\u2083[k]) / \u03c1\u2082\u2083_\u2096\n            a\u2081\u2082_\u2096\u208b\u2081 = k\u2082 * \u03f0 * (r\u2081_\u2096\u208b\u2081[k] - r\u2082_\u2096\u208b\u2081[k]) / \u03c1\u2081\u2082_\u2096\u208b\u2081\n            a\u2081\u2083_\u2096\u208b\u2081 = k\u2082 * \u03f0 * (r\u2081_\u2096\u208b\u2081[k] - r\u2083_\u2096\u208b\u2081[k]) / \u03c1\u2081\u2083_\u2096\u208b\u2081\n            a\u2082\u2083_\u2096\u208b\u2081 = k\u2082 * \u03f0 * (r\u2082_\u2096\u208b\u2081[k] - r\u2083_\u2096\u208b\u2081[k]) / \u03c1\u2082\u2083_\u2096\u208b\u2081\n            a\u2081\u2082_\u2096\u208b\u2082 = k\u2083 * \u03f0 * (r\u2081_\u2096\u208b\u2082[k] - r\u2082_\u2096\u208b\u2082[k]) / \u03c1\u2081\u2082_\u2096\u208b\u2082\n            a\u2081\u2083_\u2096\u208b\u2082 = k\u2083 * \u03f0 * (r\u2081_\u2096\u208b\u2082[k] - r\u2083_\u2096\u208b\u2082[k]) / \u03c1\u2081\u2083_\u2096\u208b\u2082\n            a\u2082\u2083_\u2096\u208b\u2082 = k\u2083 * \u03f0 * (r\u2082_\u2096\u208b\u2082[k] - r\u2083_\u2096\u208b\u2082[k]) / \u03c1\u2082\u2083_\u2096\u208b\u2082\n\n            a\u2082\u2081_\u2096 = -a\u2081\u2082_\u2096\n            a\u2083\u2081_\u2096 = -a\u2081\u2083_\u2096\n            a\u2083\u2082_\u2096 = -a\u2082\u2083_\u2096\n            a\u2082\u2081_\u2096\u208b\u2081 = -a\u2081\u2082_\u2096\u208b\u2081\n            a\u2083\u2081_\u2096\u208b\u2081 = -a\u2081\u2083_\u2096\u208b\u2081\n            a\u2083\u2082_\u2096\u208b\u2081 = -a\u2082\u2083_\u2096\u208b\u2081\n            a\u2082\u2081_\u2096\u208b\u2082 = -a\u2081\u2082_\u2096\u208b\u2082\n            a\u2083\u2081_\u2096\u208b\u2082 = -a\u2081\u2083_\u2096\u208b\u2082\n            a\u2083\u2082_\u2096\u208b\u2082 = -a\u2082\u2083_\u2096\u208b\u2082\n\n            r\u2081_\u2096\u208b\u2082[k] = r\u2081_\u2096\u208b\u2081[k]\n            r\u2082_\u2096\u208b\u2082[k] = r\u2082_\u2096\u208b\u2081[k]\n            r\u2083_\u2096\u208b\u2082[k] = r\u2083_\u2096\u208b\u2081[k]\n            r\u2081_\u2096\u208b\u2081[k] = r\u2081[k]\n            r\u2082_\u2096\u208b\u2081[k] = r\u2082[k]\n            r\u2083_\u2096\u208b\u2081[k] = r\u2083[k]\n\n            r\u2081[k] += k\u2081 * v\u2081[k] + k\u2082 * v\u2081_\u2096\u208b\u2081[k] + k\u2083 * v\u2081_\u2096\u208b\u2082[k]\n            r\u2082[k] += k\u2081 * v\u2082[k] + k\u2082 * v\u2082_\u2096\u208b\u2081[k] + k\u2083 * v\u2082_\u2096\u208b\u2082[k]\n            r\u2083[k] += k\u2081 * v\u2083[k] + k\u2082 * v\u2083_\u2096\u208b\u2081[k] + k\u2083 * v\u2083_\u2096\u208b\u2082[k]\n\n            v\u2081_\u2096\u208b\u2082[k] = v\u2081_\u2096\u208b\u2081[k]\n            v\u2082_\u2096\u208b\u2082[k] = v\u2082_\u2096\u208b\u2081[k]\n            v\u2083_\u2096\u208b\u2082[k] = v\u2083_\u2096\u208b\u2081[k]\n            v\u2081_\u2096\u208b\u2081[k] = v\u2081[k]\n            v\u2082_\u2096\u208b\u2081[k] = v\u2082[k]\n            v\u2083_\u2096\u208b\u2081[k] = v\u2083[k]\n\n            v\u2081[k] += a\u2081\u2082_\u2096 + a\u2081\u2083_\u2096 + a\u2081\u2082_\u2096\u208b\u2081 + a\u2081\u2083_\u2096\u208b\u2081 + a\u2081\u2082_\u2096\u208b\u2082 + a\u2081\u2083_\u2096\u208b\u2082\n            v\u2082[k] += a\u2082\u2081_\u2096 + a\u2082\u2083_\u2096 + a\u2082\u2081_\u2096\u208b\u2081 + a\u2082\u2083_\u2096\u208b\u2081 + a\u2082\u2081_\u2096\u208b\u2082 + a\u2082\u2083_\u2096\u208b\u2082\n            v\u2083[k] += a\u2083\u2081_\u2096 + a\u2083\u2082_\u2096 + a\u2083\u2081_\u2096\u208b\u2081 + a\u2083\u2082_\u2096\u208b\u2081 + a\u2083\u2081_\u2096\u208b\u2082 + a\u2083\u2082_\u2096\u208b\u2082\n        end\n    end\n    return r\u2081, r\u2082, r\u2083, v\u2081, v\u2082, v\u2083\nend\n\nprintln(\" \"^4, \"> Integrating the 3-body problem...\")\n\n# Define the initial values of the position and velocity\nr\u2080\u2081 = [0.97, -0.2431]\nr\u2080\u2082 = [-0.97, 0.2431]\nr\u2080\u2083 = [0.0, 0.0]\nv\u2080\u2081 = [0.4662, 0.4324]\nv\u2080\u2082 = [0.4662, 0.4324]\nv\u2080\u2083 = [-0.9324, -0.8647]\n\n# Calculate total energy\nE\u2080 = 1 / 2 * (norm(v\u2080\u2081)^2 + norm(v\u2080\u2082)^2 + norm(v\u2080\u2083)^2) - \u03f0^2 *\n    (1 / norm(r\u2080\u2081 - r\u2080\u2082) + 1 / norm(r\u2080\u2083 - r\u2080\u2082) + 1 / norm(r\u2080\u2083 - r\u2080\u2081))\n\n# Print the initial values\nprintln(\n    '\\n',\n    \" \"^6, \"r\u2080\u2081: \", r\u2080\u2081[1], \" \", r\u2080\u2081[2], '\\n',\n    \" \"^6, \"r\u2080\u2082: \", r\u2080\u2082[1], \" \", r\u2080\u2082[2], '\\n',\n    \" \"^6, \"r\u2080\u2083: \", r\u2080\u2083[1], \" \", r\u2080\u2083[2], '\\n',\n    \" \"^6, \"v\u2080\u2081: \", v\u2080\u2081[1], \" \", v\u2080\u2081[2], '\\n',\n    \" \"^6, \"v\u2080\u2082: \", v\u2080\u2082[1], \" \", v\u2080\u2082[2], '\\n',\n    \" \"^6, \"v\u2080\u2083: \", v\u2080\u2083[1], \" \", v\u2080\u2083[2], '\\n',\n    \" \"^6, \"E\u2080: \", E\u2080,\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\u2081 = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    r\u2082 = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    r\u2083 = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    v\u2081 = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    v\u2082 = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n    v\u2083 = [ Vector{Vector{F}}() for _ in 1:length(io) ]\n\n    E = [ Vector{F}() for _ in 1:length(io) ]\n    \u0394E = [ 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\u1d62\u2081, r\u1d62\u2082, r\u1d62\u2083, v\u1d62\u2081, v\u1d62\u2082, v\u1d62\u2083 = methods[j](r\u2080\u2081, r\u2080\u2082, r\u2080\u2083, v\u2080\u2081, v\u2080\u2082, v\u2080\u2083, h[i], n[i])\n\n            push!(r\u2081[j], r\u1d62\u2081)\n            push!(r\u2082[j], r\u1d62\u2082)\n            push!(r\u2083[j], r\u1d62\u2083)\n            push!(v\u2081[j], v\u1d62\u2081)\n            push!(v\u2082[j], v\u1d62\u2082)\n            push!(v\u2083[j], v\u1d62\u2083)\n\n            E\u1d62 = 1 / 2 * (norm(v\u1d62\u2081)^2 + norm(v\u1d62\u2082)^2 + norm(v\u1d62\u2083)^2) - \u03f0^2 *\n                (1 / norm(r\u1d62\u2081 - r\u1d62\u2082) + 1 / norm(r\u1d62\u2083 - r\u1d62\u2082) + 1 / norm(r\u1d62\u2083 - r\u1d62\u2081))\n            \u0394E\u1d62 = abs(E\u2080 - E\u1d62)\n\n            push!(E[j], E\u1d62)\n            push!(\u0394E[j], \u0394E\u1d62)\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\u2081[j][i][1], r\u2081[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\u2082[j][i][1], r\u2082[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\u2083[j][i][1], r\u2083[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\u2081[j][i][1], v\u2081[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\u2082[j][i][1], v\u2082[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\u2083[j][i][1], v\u2083[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], \u0394E[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\u03b2 = y\nX = [1. 3.; -2. 7.; 0. 1.]\ny = [2., 1., 0.]\n\u03b2 = 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": "function nlp_cvx_104_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - redundant nonlinear constraint (feasible set is inside the circle constraint)\n    # Variants\n    #   010 - redundant constraint\n\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n\n    @objective(model, Min, -x)\n    @NLconstraint(model, x^2 <= y)\n    @NLconstraint(model, -x^2 + 1 >= y)\n    @NLconstraint(model, x^2 + (y - 0.5)^2 <= 1.0)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -1 / sqrt(2), tol = objective_tol)\n    return check_solution([x, y], [1 / sqrt(2), 1 / 2], tol = primal_tol)\nend\n", "meta": {"hexsha": "6a05a4b7c954e8e8ea00e734a05ac0d6544ab402", "size": 815, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/104_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/104_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/104_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 27.1666666667, "max_line_length": 85, "alphanum_fraction": 0.6601226994, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731137267749, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7779045783465336}}
{"text": "# Estimates the Klein consumption equation by GMM\nusing Econometrics, DelimitedFiles, Statistics\nfunction KleinMoments(\u03b8, y, x, z)\n\te = y - x*\u03b8\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\u03b8start = x\\y # ols start values\nnames = [\"Constant\", \"Profits\", \"Profits-1\", \"Wages\"]\nmoments = \u03b8 -> KleinMoments(\u03b8, y, x, exogs)\n# estimation results using CUE\ngmmtitle = \"Klein model 1 GMM example CUE\"\ngmmresults(moments, \u03b8start, \"\",  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": "using Sigma\n\nPI = 3.1415926535897\n# arc of a circle\nX = uniform(-2,2)\nY = uniform(-2,2)\nZ = uniform(-2,2)\ncond1 = X*X + Y*Y == 0.1\n# cond2 = in(asin(X/Y), (-1/2PI,1/2PI))\ncond2 = asin(X/Y) > 1/2PI\nxy = RandArray(Any[X,Y])\nsamples = rand(xy, cond1 & cond2, 100)\n\n# x = [sample[1] for sample in samples]\n# y = [sample[2] for sample in samples]\n#\n# plot(x=x,y=y,Geom.point)\n\n# Ellipsoid\n## =========\na = 2\nb = 1\nc = 0.5\nellip_cond = ((X*X)/(a*a) + (Y*Y)/(b*b) + (Z*Z)/(c*c)) ==  1.0\nxyz = RandArray(Any[X,Y,Z])\nsamples_ellipsoid = rand(xyz, ellip_cond, 100)\n\n## Fractal\n## =======\nZsqr = Z*Z\nYsqr = Y*Y\nXsqr = X*X\n\nxcond = (((3Zsqr - Xsqr - Ysqr)*X*(Xsqr-3Ysqr))/(Xsqr+Ysqr)) == X\nycond = (((3Zsqr - Xsqr - Ysqr) * Y * (3*Xsqr - Ysqr))/(Xsqr+Ysqr)) == Y\nzcond = (Z*(Zsqr-3*Xsqr - 3*Ysqr)) == Z\nsamples_fractal = rand(xyz, xcond & ycond & zcond, 10)\n", "meta": {"hexsha": "519b314f787e984fb6e7e9cf776f95ae0d9ce56c", "size": 846, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/geometry.jl", "max_stars_repo_name": "JuliaPackageMirrors/Sigma.jl", "max_stars_repo_head_hexsha": "f222b3a0c0dc76db24eb7add19cca75351bb9dcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-04-01T03:10:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T10:48:43.000Z", "max_issues_repo_path": "examples/geometry.jl", "max_issues_repo_name": "JuliaPackageMirrors/Sigma.jl", "max_issues_repo_head_hexsha": "f222b3a0c0dc76db24eb7add19cca75351bb9dcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2015-01-13T22:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:30:23.000Z", "max_forks_repo_path": "examples/geometry.jl", "max_forks_repo_name": "JuliaPackageMirrors/Sigma.jl", "max_forks_repo_head_hexsha": "f222b3a0c0dc76db24eb7add19cca75351bb9dcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-06-22T20:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:27:15.000Z", "avg_line_length": 22.2631578947, "max_line_length": 72, "alphanum_fraction": 0.5673758865, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762052772658, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7778668989176106}}
{"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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -\u03b2*c*I/N*S\n        du[2] = \u03b2*c*I/N*S - \u03b3*I\n        du[3] = \u03b3*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]; # \u03b2,c,\u03b3\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    \u03b1::Float64\n    \u03b2::Float64\n    \u03b3::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, \u03b1::Number, \u03b2::Number, \u03b3::Number, l0::Number, b0::Number, s0::Array{Float64, 1}) = \n\t\tm == length(s0) ? new(m, Float64(\u03b1), Float64(\u03b2), Float64(\u03b3), 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\u03b1 = model.\u03b1\n\t\u03b2 = model.\u03b2\n\t\u03b3 = model.\u03b3\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_) * \u03b1 + (l_t_ + b_t_) * (1 - \u03b1) \n\t\t\tb_t = \u03b2 * (l_t - l_t_) + (1 - \u03b2) * 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] = \u03b3 * (time_series[i + 1] - l_t_ - b_t_) + (1 - \u03b3) * 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\u03b1 = model.\u03b1\n\t\u03b2 = model.\u03b2\n\t\u03b3 = model.\u03b3\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_) * \u03b1 + (l_t_ + b_t_) * (1 - \u03b1) \n\t\t\tb_t = \u03b2 * (l_t - l_t_) + (1 - \u03b2) * 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] = \u03b3 * (time_serie[i + 1] - l_t_ - b_t_) + (1 - \u03b3) * s[i%m + 1]\t\n\tend\n\t\n\tl_t = (time_serie[end] - s_) * \u03b1 + (l_t + b_t) * (1 - \u03b1)\n\tb_t = \u03b2 * (l_t - l_t_) + (1 - \u03b2) * 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\u2013432.\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\u2013126.\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\u2013228.\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\u03a0(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\u03a0(k, r, l, m) = prod([r-q+1 for q in 0:k if q \u2209 (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\u03a0(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+\u00bd) 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+\u00bd) 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\u00d7k static array containing ENO coefficients to reconstruct a value at the\npoint x(i+\u00bd) 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    \u03b3 = C \\ b\n    \u03b3 = rationalize.(\u03b3, tol=\u221aeps(Float64)) |> reverse\n    return SVector{k,FT}(\u03b3)\nend\n\noptimal_weno_weights(k) = optimal_weno_weights(Rational, k)\n\n#####\n##### Jiang & Shu (1996) WENO smoothness indicators \u03b2\n##### See equation (2.61) of Shu (1998).\n#####\n\nx(j) = j  # Assume uniform grid for now.\n\n\"\"\"\n    \u2113(\u03be, k, r, j)\n\nReturn a symbolic expression for the `j`th Lagrange basis polynomial \u2113(\u03be) for an\nENO reconstruction scheme of order k and left shift `r` with field values `\u03d5`.\n\"\"\"\n\u2113(\u03be, k, r, j) = prod((\u03be - x(m-r)) / (x(j-r) - x(m-r)) for m in 0:k-1 if m != j)\n\n\"\"\"\n    L(\u03be, k, r, \u03d5)\n\nReturn a symbolic expression for the interpolating Lagrange polynomial p(\u03be) for an\nENO reconstruction scheme of order k and left shift `r` with field values `\u03d5`.\n\"\"\"\np(\u03be, k, r, \u03d5) = sum(\u2113(\u03be, k, r, j) * \u03d5[j+1] for j in 0:k-1)\n\n\"\"\"\n    \u03b2(k, r, \u03d5)\n\nReturn a symbolic expression for the smoothness indicator \u03b2 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 `\u03d5` which should have length k.\n\"\"\"\nfunction \u03b2(k, r, \u03d5)\n    @vars \u03be\n    return sum(integrate(diff(p(\u03be, k, r, \u03d5), \u03be, l)^2, (\u03be, 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 ? \"\u208a\" : n < 0 ? \"\u208b\" : \"\"\n\nsubscript_index(n) = n == 0 ? \"\" : subscript_sign(n) * subscript(abs(n))\n\n\"\"\"\n    \u03b2_coefficients([FT=Rational], k)\n\nReturn a k\u00d7k\u00d7k 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`\u03d5[r-k+m+1] * \u03d5[r-k+n+1]` term where r-k+1 <= m, n <= r and `r` is the left shift of\nthe ENO interpolants.\n\"\"\"\nfunction \u03b2_coefficients(FT, k)\n    B = zeros(Float64, k, k, k)\n    \n    for r in 0:k-1\n        \u03d5 = [Sym(\"\u03d5\u1d62\" * subscript_index(n)) for n in r:-1:r-k+1]\n        \u03b2_symbolic = \u03b2(k, r, \u03d5) |> expand\n\n        for m in 1:k, n in 1:k\n            B[m, n, r+1] = \u03b2_symbolic.coeff(\u03d5[m] * \u03d5[n])\n        end\n    end\n    \n    B = rationalize.(B, tol=\u221aeps(Float64))\n    return SArray{Tuple{k,k,k},FT}(B)\nend\n\n\u03b2_coefficients(k) = \u03b2_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), \u2205 --> mRNA\n#       mRNA_degradation_rate, mRNA \u2192 \u2205\n#       protein_degradation_rate, protein \u2192 \u2205\n#       translation_rate, mRNA \u2192 mRNA + protein\n#    end repression_threshold hill_coefficient mRNA_degradation_rate protein_degradation_rate basal_transcription_rate translation_rate\n#\n#    # parameters [\u03b1,K,n,\u03b4,\u03b3,\u03b2,\u03bc]\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\u2080 = [40.,50000.]\n#    tspan = (0.0,100.0)\n#    # create the ODEProblem we want to solve\n#    prob = ODEProblem(hes5_network, u\u2080,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": "using LinearAlgebra, Distributions\nusing Test\nusing DistributionVectors\nusing StatsBase # coef\n\n@testset \"cormatrix_for_acf\" begin    \n    acf0 = [1,0.4,0.1]\n    nsum = 5\n    Sigma = cormatrix_for_acf(nsum, acf0);\n    @test diag(Sigma) == fill(1.0, nsum)\n    @test diag(Sigma,1) == diag(Sigma,-1) == fill(0.4, nsum - 1)\n    @test diag(Sigma,2) == diag(Sigma,-2) == fill(0.1, nsum - 2)\n    @test diag(Sigma,3) == diag(Sigma,-3) == fill(0.0, nsum - 3)\n    #dmn = MvNormal(ones(nsum), Symmetric(Sigma));\nend;\n\n@testset \"AutoCorrelationFunction\" begin  \n    acfvec = [1,0.4,0.1]\n    acf = @inferred AutoCorrelationFunction(acfvec)\n    @test @inferred coef(acf) == acfvec\n    @test @inferred coef(acf,1) == acfvec[2] # vector starts with lag 0\nend;\n\n\n", "meta": {"hexsha": "11be200401e568d1946924f7e51139423bfae347", "size": 746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/autocor.jl", "max_stars_repo_name": "bgctw/DistributionVectors.jl", "max_stars_repo_head_hexsha": "94b5226a77462ae5068874cce991e46d758e43ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-05T11:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T11:10:14.000Z", "max_issues_repo_path": "test/autocor.jl", "max_issues_repo_name": "bgctw/DistributionVectors.jl", "max_issues_repo_head_hexsha": "94b5226a77462ae5068874cce991e46d758e43ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-03-22T00:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T15:47:37.000Z", "max_forks_repo_path": "test/autocor.jl", "max_forks_repo_name": "bgctw/DistributionVectors.jl", "max_forks_repo_head_hexsha": "94b5226a77462ae5068874cce991e46d758e43ed", "max_forks_repo_licenses": ["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.84, "max_line_length": 71, "alphanum_fraction": 0.6434316354, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7778508567167599}}
{"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])) \u2200 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# \u2202f/\u2202Z[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] * \u2202f/\u2202Z[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# \u2202f/\u2202Z[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] * \u2202f/\u2202Z[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# \u2202f/\u2202Z[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] * \u2202f/\u2202Z[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; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2) = MaternCovariance_12(abs(x1-x2); \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\nfunction MaternCovariance_12(d; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\n    @assert(d >= 0)\n\n    \u03c3\u00b2 * exp(-d/\u03c1)\n\nend\n\n\nmatern32(x1, x2; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2) = MaternCovariance_32(abs(x1-x2); \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\nfunction MaternCovariance_32(d; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\n    @assert(d >= 0)\n\n    \u03c3\u00b2 * (1 + sqrt(3)*d/\u03c1) * exp(- sqrt(3)*d/\u03c1)\n\nend\n\n\nmatern52(x1, x2; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2) = MaternCovariance_52(abs(x1-x2); \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\nfunction MaternCovariance_52(d; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\n    @assert(d >= 0)\n\n    \u03c3\u00b2 * (1 + sqrt(5)*d/\u03c1 + 5*d^2/(3*\u03c1^2)) * exp(- sqrt(5)*d/\u03c1)\n\nend\n\n\nrbf(x1, x2; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2) = RBFCovariance(abs(x1-x2); \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\nfunction RBFCovariance(d; \u03c1=\u03c1, \u03c3\u00b2=\u03c3\u00b2)\n\n    @assert(d >= 0)\n\n    \u03c3\u00b2 * exp(-d^2 / (2\u03c1))\n\nend\n\n\nlinear(x1, x2; c=c, \u03c3\u00b2=\u03c3\u00b2) = \u03c3\u00b2 * (x1 - c) * (x2 - c)\n\nfunction calculatekernelmatrix(k, \u03c1, \u03c3\u00b2, x)\n\n    calculatekernelmatrix(k, \u03c1, \u03c3\u00b2, x, x)\n\nend\n\nfunction calculatekernelmatrix(k, \u03c1, \u03c3\u00b2, x1, x2)\n\n    [k(a, b; \u03c1 = \u03c1, \u03c3\u00b2 = \u03c3\u00b2) 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": "using ValidatedNumerics, ValidatedNumerics.RootFinding\nusing ForwardDiff\n\nusing FactCheck\n\nconst D = RootFinding.derivative\n\ninclude(\"wilkinson.jl\")\n\n\nfunction generate_wilkinson(n)#, T=BigFloat)   # SLOW\n\n    p = poly(collect(1:n))\n    p_prime = polyder(p)\n\n    coeffs = p.a #[convert(T, coeff) for coeff in p.a]\n    # coeffs_prime = [convert(T, coeff) for coeff in p_prime.a]\n\n    function f(x)\n        total = coeffs[1]\n        for i in 2:length(coeffs)\n            total += coeffs[i]*x^(i-1)\n        end\n        total\n    end\n\n    f\nend\n\n\nsetprecision(Interval, Float64)\nfloat_pi = @interval(pi)\n\nsetprecision(Interval, 10000)\nbig_pi = @interval(pi)\n# Using precision \"only\" 256 leads to overestimation of the true roots for `cos`\n# i.e the Newton method gives more accurate results!\n\nhalf_pi = big_pi / 2\nthree_halves_pi = 3*big_pi/2\n\n\n# Format:  (function, derivative, lower_bound, upper_bound, [true_roots])\nfunction_list = [\n                    (sin, cos,    -5,  5,    [ -big_pi, @interval(0), big_pi ] ) ,\n                    (cos, x->D(cos, x), -7.5, 7.5, [ -three_halves_pi, -half_pi, half_pi, three_halves_pi ] ),\n                    (W\u2083, x->D(W\u2083, x),   -10, 10,   [ @interval(1), @interval(2), @interval(3) ] ),\n                    (W\u2087, x->D(W\u2087, x),   -10, 10,   [ @interval(i) for i in 1:7 ] ),\n                    (x->exp(x)-2, y->D(x->exp(x),y),  -20, 20,  [log(@biginterval(2))] ),\n                    (x->asin(sin(x)) - 0.1, y->D(x->asin(sin(x)),y), 0, 1, [@biginterval(0.1)])\n                ]\n\n\nfacts(\"Testing root finding\") do\n\n    for rounding_type in (:wide, :narrow)\n        context(\"Interval rounding: $rounding_type\") do\n            setrounding(Interval, rounding_type)\n\n            for prec in ( (BigFloat,53), (BigFloat,256), (Float64,64) )\n                context(\"Precision: $prec\") do\n                    setprecision(Interval, prec)\n\n                    for method in (newton, krawczyk)\n                        context(\"Method $method\") do\n\n                            for func in function_list\n\n                                f, f_prime, a_lower, a_upper, true_roots = func\n                                a = @interval(a_lower, a_upper)\n\n                                context(\"Function $f; interval $a\") do\n\n                                    for autodiff in (false, true)\n\n                                        context(\"With autodiff=$autodiff\") do\n\n                                            if autodiff\n                                                roots = method(f, a)\n                                            else\n                                                roots = method(f, f_prime, a)\n                                            end\n\n                                            @fact length(roots) --> length(true_roots)\n\n                                            for i in 1:length(roots)\n                                                root = roots[i]\n\n                                                @fact isa(root, Root{prec[1]}) --> true\n                                                @fact is_unique(root) --> true\n                                                @fact true_roots[i] \u2286 root.interval --> true\n                                            end\n                                        end\n                                    end\n                                end\n                            end\n                        end\n                    end\n                end\n            end\n        end\n    end\nend\n\n\n\nf(x) = x^2 - 2\n\nroots = newton(f, @interval(10, 11))\n\nfacts() do\n    @fact length(roots) --> 0\nend\n\nsetprecision(Interval, Float64)\n\nfacts(\"find_roots tests\") do\n    f(x) = x^2 - 2\n\n\n    roots = find_roots_midpoint(f, -5, 5)\n    @fact length(roots) --> 3\n    @fact length(roots[1]) --> 2\n\n    roots = find_roots(f, -5, 5)\n    @fact length(roots) --> 2\n\n    setprecision(Interval, 256)\n\n    for method in (newton, krawczyk)\n        new_roots = method(f, roots)\n        @fact length(new_roots) == length(roots) --> true\n\n        for (root1, root2) in zip(new_roots, roots)\n            @fact root1 \u2286 root2 --> true\n        end\n    end\n\nend\n\nfacts(\"Multiple roots\") do\n    setprecision(Interval, Float64)\n    let\n        f(x) = (x-1) * (x^2 - 2)^3 * (x^3 - 2)^4\n\n        roots = newton(f, -5..5.1, maxlevel=1000)\n\n        @fact length(roots) --> 4\n        @fact roots[1].status --> :unknown\n        @fact roots[1].interval --> Interval(-1.4142135623730954, -1.414213562373095)\n        @fact roots[3].interval --> Interval(1.259921049894873, 1.2599210498948734)\n\n    end\nend\n\n\n\n# Example of a function with a double root at 0 from Burden & Faires, 9th ed, p.84\n# exp(x) - x - 1\n", "meta": {"hexsha": "e737ce7328525a5f7a6093b094d38bfa3a4b5687", "size": 4663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/root_finding_tests/findroots.jl", "max_stars_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_stars_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/root_finding_tests/findroots.jl", "max_issues_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_issues_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/root_finding_tests/findroots.jl", "max_forks_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_forks_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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.14375, "max_line_length": 110, "alphanum_fraction": 0.4666523697, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.833324587033253, "lm_q1q2_score": 0.777850851298035}}
{"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_\u03bc = 0.0\ntrue_\u03c4\u00b2 = 0.5\ntrue_\u03c3\u00b2 = 1.0\nn = 20\ntrue_\u03b8 = rand(Normal(true_\u03bc, sqrt(true_\u03c4\u00b2)), n)\n#y = rand.(Normal.(true_\u03b8, sqrt(true_\u03c3\u00b2)))\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    \u03c4\u00b2 ~ InverseGamma(1,1)\n    \u03b8 ~ filldist(Normal(0.0, sqrt(\u03c4\u00b2)), length(Y))\n    Y ~ arraydist(Normal.(\u03b8, 1.0))\nend\n\n@model H1(Y) = begin\n    \u03bc ~ Normal()\n    \u03c4\u00b2 ~ InverseGamma(1,1)\n    \u03b8 ~ filldist(Normal(\u03bc, sqrt(\u03c4\u00b2)), length(Y))\n    Y ~ arraydist(Normal.(\u03b8, 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.\u03b8[i], 1.0), y[i]) for i = 1:n]) + \n                sum([logpdf(Normal(0.0, sqrt(x.\u03c4\u00b2)), x.\u03b8[i]) for i = 1:n]) + \n                logpdf(InverseGamma(1,1), x.\u03c4\u00b2)\n\nlog_posterior_H1(x) = sum([logpdf(Normal(x.\u03b8[i], 1.0), y[i]) for i = 1:n]) + \n                sum([logpdf(Normal(x.\u03bc, sqrt(x.\u03c4\u00b2)), x.\u03b8[i]) for i = 1:n]) + \n                logpdf(InverseGamma(1,1), x.\u03c4\u00b2) + \n                logpdf(Normal(), x.\u03bc)\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\u22c5x - .5v\u22c5x\u00b2 - 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 43970fa0-8e1b-11eb-3052-1701966a4478\nbegin\n\tT = 300 \t#period of 300 daysplot\n\t\u0394t = 1/4 \t#time interval of 6 hours (1/4 of a day)\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d59335ac-913b-11eb-228f-273be8d7a86a\nmd\"\"\"\n---\n**Additional parameter and functions for simulations with two subgroups**\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 da008842-9142-11eb-388c-d7e1f662d9db\nmd\"\"\"\n---\n#### Plots\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2680b820-8e32-11eb-28de-6f039360524b\nbegin\n\tfunction euler(f::Function,change_par!::Function,t0,tn,\u0394t,x\u2080,par)\n\t\tT = t0:\u0394t:tn\n\t\tF = Matrix{eltype(x\u2080)}(undef,(length(T),length(x\u2080)))\n\t\tF[1,:] = x\u2080\n\t\tfor (n,t) \u2208 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) .* \u0394t,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,\u0394t,x\u2080,par) = euler(f,no_change!,t0,tn,\u0394t,x\u2080,par)\nend;\n\n# \u2554\u2550\u2561 58f42866-9146-11eb-29ea-87830bc8db66\nmd\"\"\"\n**Defines the infinitesimal change of system**\n\"\"\"\n\n# \u2554\u2550\u2561 3ab68bec-8e2f-11eb-203e-f9530bc39073\nbegin\n\tfunction SIR_step(t,x,\u03b2,\u03b4,\u03b3,\u03c1,N)\n\t\tS, I, R, D = x[1], x[2], x[3], x[4]\n\t\tnI = rand(Poisson(\u03b2*I*S/N))\n\t\tnIL = rand(Poisson(\u03b4*R))\n\t\tnR = rand(Poisson(\u03b3*I))\n\t\tnD = rand(Poisson(\u03c1*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# \u2554\u2550\u2561 a7ac774a-913b-11eb-267b-8f9841c44cb4\nbegin\n\tfunction SIR_step_2D(t,H,n,par\u2081::Dict,par\u2082::Dict,par_mix::Dict)\n\t\tx\u2081,x\u2082 = view(H,n,1:4), view(H,n,5:8)\t\n\t\tx = vcat(SIR_step(t,x\u2081,par\u2081),SIR_step(t,x\u2082,par\u2082))\n\t\treturn x + SIR_interaction(t,x\u2081,x\u2082,\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\u2081[\"total population\"]+par\u2082[\"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\u2081,x\u2082,\u03b2\u2083,\u03b2\u2084,N)\n\t\tS\u2081, I\u2081, S\u2082, I\u2082 = x\u2081[1], x\u2081[2], x\u2082[1], x\u2082[2]\n\t\tnI\u2081 = rand(Poisson(\u03b2\u2084*S\u2081*I\u2082/N))\n\t\tnI\u2082 = rand(Poisson(\u03b2\u2083*S\u2082*I\u2081/N))\n\t\treturn [\n\t\t\t-nI\u2081, nI\u2081, 0, 0,\n\t\t\t-nI\u2082, nI\u2082, 0, 0\n\t\t]\n\tend\nend;\n\n# \u2554\u2550\u2561 c6bbb678-9080-11eb-2047-a3dcd34e8c77\nbegin\n\tN\u2081,N\u2082 = parameter[\"total population\"], parameter_subpopulation[\"total population\"]\n\tI\u2081,I\u2082 = parameter[\"initial number of infected\"], parameter_subpopulation[\"initial number of infected\"]\n\t\n\tx\u2080 = [\n\t\tN\u2081-I\u2081,\n\t\tI\u2081,\n\t\t0.0,\n\t\t0.0,\n\t\tN\u2082-I\u2082,\n\t\tI\u2082,\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,\u0394t,\n\t\tx\u2080,\n\t\t(parameter,parameter_subpopulation,mixing_parameter)\n\t\t)\nend;\n\n# \u2554\u2550\u2561 3d9185a6-908c-11eb-301c-358ed4a3eb37\nlet\n\tp1 = plot(framestlye=:zerolines,title=\"Main Population\")\n\n\tplot!(p1, 0.0:\u0394t: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:\u0394t: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# \u2554\u2550\u2561 de101aba-9145-11eb-2457-7b1831145eeb\nmd\"\"\"\n\n**Supporting function for calculating the Incidence**\n\"\"\"\n\n# \u2554\u2550\u2561 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\u2080 = max(t-round(Int,ndays/\u0394t),1)\n\t\t#return Incidence\n\t\treturn (nI[t] - nI[t\u2080]) .* (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/\u0394t)\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\u2080 \u2208 1:length(nI)-ndays\n\t\t\tappend!(I,nI[t\u2080+ndays] - nI[t\u2080])\n\t\tend\n\t\t#scale and return\n\t\treturn I .* scale/pop_size\n\tend\nend;\n\n# \u2554\u2550\u2561 ceedca8e-9148-11eb-189c-a3a088520c2c\nmd\"\"\"\n---\nPackage Management\n\"\"\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u250010a9374c-8e1a-11eb-10b4-fb8272dd46d1\n# \u2560\u255043970fa0-8e1b-11eb-3052-1701966a4478\n# \u2560\u2550742d1fd0-907d-11eb-27d1-59ca2af59f97\n# \u255f\u2500d59335ac-913b-11eb-228f-273be8d7a86a\n# \u2560\u255056b9df4c-913b-11eb-180a-eb784c2b5181\n# \u255f\u2500f8e23e02-9142-11eb-1700-6974da1a09c0\n# \u2560\u2550c6bbb678-9080-11eb-2047-a3dcd34e8c77\n# \u255f\u2500da008842-9142-11eb-388c-d7e1f662d9db\n# \u255f\u25003d9185a6-908c-11eb-301c-358ed4a3eb37\n# \u255f\u250093b1fcc4-9145-11eb-3d5e-4b9bd577a545\n# \u2560\u25502680b820-8e32-11eb-28de-6f039360524b\n# \u255f\u250058f42866-9146-11eb-29ea-87830bc8db66\n# \u2560\u25503ab68bec-8e2f-11eb-203e-f9530bc39073\n# \u2560\u2550a7ac774a-913b-11eb-267b-8f9841c44cb4\n# \u255f\u2500de101aba-9145-11eb-2457-7b1831145eeb\n# \u2560\u255016a50518-906d-11eb-1e2b-3faa1765f30c\n# \u255f\u2500ceedca8e-9148-11eb-189c-a3a088520c2c\n# \u2560\u25509f18ccd0-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": "e_x, _ = noisy_sin(50; noise = 0.)\ne_X = expand_poly(e_x, degree = 5)\ndf = DataFrame(A=rand(10), B=collect(1:10), C=[string(x) for x in 1:10])\ndf_na = deepcopy(df)\ndf_na[!, :A] = allowmissing(df_na[!, :A])\ndf_na[1, :A] = missing\n\n@testset \"Test expand_poly\" begin\n    @test size(e_X) == (5, 50)\nend\n\n@testset \"Test center! and rescale!\" begin\n    # Center Vectors\n    xa = copy(e_x)\n    @test center!(xa) \u2248 mean(e_x)\n    @test abs(mean(xa)) <= 10e-10\n\n    xa = copy(e_x)\n    mu = mean(xa)\n    center!(xa, mu, obsdim=1)\n    @test abs(mean(xa)) <= 10e-10\n\n    xa = copy(e_x)\n    mu = vec(fill!(similar(xa),1))\n    center!(xa, mu, obsdim=1)\n    @test sum(e_x .- mean(xa)) \u2248 length(mu)\n\n    # Center Matrix w/o mu\n    Xa = copy(e_X)\n    center!(Xa)\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n\n    Xa = copy(e_X)\n    center!(Xa, obsdim=1)\n    @test abs(sum(mean(Xa, dims=1))) <= 10e-10\n\n    Xa = copy(e_X)\n    center!(Xa, ObsDim.First())\n    @test abs(sum(mean(Xa, dims=1))) <= 10e-10\n\n    Xa = copy(e_X)\n    center!(Xa, obsdim=2)\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n\n    Xa = copy(e_X)\n    center!(Xa, ObsDim.Last())\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n\n\n    # Center Matrix with mu as input\n    Xa = copy(e_X)\n    mu = vec(mean(Xa, dims=1))\n    center!(Xa, mu, obsdim=1)\n    @test abs(sum(mean(Xa, dims=1))) <= 10e-10\n\n    Xa = copy(e_X)\n    mu = vec(mean(Xa, dims=2))\n    center!(Xa, mu, obsdim=2)\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n\n    Xa = copy(e_X)\n    mu = vec(mean(Xa, dims=2))\n    center!(Xa, mu, ObsDim.Last())\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n\n    # Center DataFrame\n    D = copy(df)\n    mu_check = [mean(D[!, colname]) for colname in names(D)[1:2]]\n    mu = center!(D)\n    @test length(mu) == 2\n    @test abs(sum(mu .- mu_check)) <= 10e-10\n\n    D = copy(df)\n    mu_check = [mean(D[!, colname]) for colname in names(D)[1:2]]\n    mu = center!(D, [:A, :B])\n    @test abs(sum(mu .- mu_check)) <= 10e-10\n\n    D = copy(df)\n    mu_check = [mean(D[!, colname]) for colname in names(D)[1:2]]\n    mu = center!(D, [:A, :B], mu_check)\n    @test abs(sum([mean(D[!, colname]) for colname in names(D)[1:2]])) <= 10e-10\n\n    # skip columns that contain missing values\n    D = copy(df_na)\n    mu = center!(D, [:A, :B])\n    @test ismissing(D[1, :A])\n    @test all(D[2:end, :A] .== df_na[2:end, :A])\n    @test abs(mean(D[!, :B])) < 10e-10\n\n    D = copy(df_na)\n    mu_check = [mean(D[!, colname]) for colname in names(D)[1:2]]\n    mu = center!(D, [:A, :B], mu_check)\n    @test ismissing(D[1, :A])\n    @test all(D[2:end, :A] .== df_na[2:end, :A])\n    @test abs(mean(D[!, :B])) < 10e-10\n\n    # Rescale Vector\n    xa = copy(e_x)\n    mu, sigma = rescale!(xa)\n    @test mu \u2248 mean(e_x)\n    @test sigma \u2248 std(e_x)\n    @test abs(mean(xa)) <= 10e-10\n    @test std(xa) \u2248 1\n\n    xa = copy(e_x)\n    mu, sigma = rescale!(xa, mu, sigma)\n    @test abs(mean(xa)) <= 10e-10\n    @test std(xa) \u2248 1\n\n    xa = copy(e_x)\n    mu, sigma = rescale!(xa, mu, sigma, obsdim=1)\n    @test abs(mean(xa)) <= 10e-10\n    @test std(xa) \u2248 1\n\n    xa = copy(e_x)\n    mu = copy(e_x) .- 1\n    sigma = fill!(similar(e_x),1)\n    mu, sigma = rescale!(xa, mu, sigma, obsdim=1)\n    @test mean(xa) \u2248 1\n\n    Xa = copy(e_X)\n    rescale!(Xa)\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n    @test std(Xa, dims=2) \u2248 [1, 1, 1, 1, 1]\n\n    Xa = copy(e_X)\n    rescale!(Xa, obsdim=2)\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n    @test std(Xa, dims=2) \u2248 [1, 1, 1, 1, 1]\n\n    Xa = copy(e_X)\n    rescale!(Xa, obsdim=1)\n    @test abs(sum(mean(Xa, dims=1))) <= 10e-10\n\n    Xa = copy(e_X)\n    mu = vec(mean(Xa, dims=1))\n    sigma = vec(std(Xa, dims=1))\n    rescale!(Xa, mu, sigma, obsdim=1)\n    @test abs(sum(mean(Xa, dims=1))) <= 10e-10\n\n    Xa = copy(e_X)\n    mu = vec(mean(Xa, dims=2))\n    sigma = vec(std(Xa, dims=2))\n    rescale!(Xa, mu, sigma, obsdim=2)\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n\n    D = copy(df)\n    mu, sigma = rescale!(D)\n    @test abs(sum([mean(D[!, colname]) for colname in names(D)[1:2]])) <= 10e-10\n    @test mean([std(D[!, colname]) for colname in names(D)[1:2]]) - 1 <= 10e-10\n\n    D = copy(df)\n    mu, sigma = rescale!(D, [:A, :B])\n    @test abs(sum([mean(D[!, colname]) for colname in names(D)[1:2]])) <= 10e-10\n    @test mean([std(D[!, colname]) for colname in names(D)[1:2]]) - 1 <= 10e-10\n\n    D = copy(df)\n    mu_check = [mean(D[!, colname]) for colname in names(D)[1:2]]\n    sigma_check = [std(D[!, colname]) for colname in names(D)[1:2]]\n    mu, sigma = rescale!(D, [:A, :B], mu_check, sigma_check)\n    @test abs(sum([mean(D[!, colname]) for colname in names(D)[1:2]])) <= 10e-10\n    @test mean([std(D[!, colname]) for colname in names(D)[1:2]]) - 1 <= 10e-10\n\n    # skip columns that contain missing values\n    D = copy(df_na)\n    mu, sigma = rescale!(D, [:A, :B])\n    @test ismissing(D[1, :A])\n    @test all(D[2:end, :A] .== df_na[2:end, :A])\n    @test abs(mean(D[!, :B])) < 10e-10\n    @test abs(std(D[!, :B])) - 1 < 10e-10\n\n    D = copy(df_na)\n    mu_check = [mean(D[!, colname]) for colname in names(D)[1:2]]\n    if VERSION >= v\"0.7.0-DEV.2035\"\n        sigma_check = [std(D[!, colname]) for colname in names(D)[1:2]]\n        mu, sigma = rescale!(D, [:A, :B], mu_check, sigma_check)\n    end\n    #= @test ismissing(D[1, :A]) =#\n    #= @test all(D[2:end, :A] .== df_na[2:end, :A]) =#\n    #= @test abs(mean(D[:B])) < 10e-10 =#\n    #= @test (abs(std(D[:B])) - 1) < 10e-10 =#\nend\n\ne_x = collect(-5:.1:5)\ne_X = [e_x e_x.^2 e_x.^3]'\n\n@testset \"Test FeatureNormalizer model\" begin\n    cs = fit(FeatureNormalizer, e_X)\n    @test vec(mean(e_X, dims=2)) \u2248 cs.offset\n    @test vec(std(e_X, dims=2)) \u2248 cs.scale\n\n    Xa = predict(cs, e_X)\n    @test Xa != e_X\n    @test abs(sum(mean(Xa, dims=2))) <= 10e-10\n    @test std(Xa, dims=2) \u2248 [1, 1, 1]\nend\n", "meta": {"hexsha": "f1001393d5354325251634a560daff873701cc8e", "size": 5769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tst_feature_scaling.jl", "max_stars_repo_name": "ppalmes/MLDataUtils.jl", "max_stars_repo_head_hexsha": "d2bfa0eefd44ede1976d4931f792a8f5e314a686", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2016-03-14T19:43:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:24:41.000Z", "max_issues_repo_path": "test/tst_feature_scaling.jl", "max_issues_repo_name": "ppalmes/MLDataUtils.jl", "max_issues_repo_head_hexsha": "d2bfa0eefd44ede1976d4931f792a8f5e314a686", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2016-02-12T22:06:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T08:46:23.000Z", "max_forks_repo_path": "test/tst_feature_scaling.jl", "max_forks_repo_name": "ppalmes/MLDataUtils.jl", "max_forks_repo_head_hexsha": "d2bfa0eefd44ede1976d4931f792a8f5e314a686", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2016-03-14T19:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T21:39:17.000Z", "avg_line_length": 29.2842639594, "max_line_length": 80, "alphanum_fraction": 0.5434217369, "num_tokens": 2290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7778486997265021}}
{"text": "using NamedArrays\n\ntaskNr = 3\n\n####### Code used by several tasks #######\nfunction trafoCSV(filename)\n    # transforms a given CSV file with 3 columns into a matrix and the into\n    # a named array.\n    # The first two columns of the CSV file need to be categorical\n    # The third column needs to be numerical\n\n    open(filename) do myFile\n        lines = readlines(myFile)\n\n        # Header information\n        header = split(lines[1],\",\");\n        rowName, colName = header[1:2];\n\n        colNr = length(header)\n        rowNr = length(lines) - 1\n\n        # Empty data matrix\n        data = Array{String}(undef, rowNr, colNr)\n\n        # Split and put each line into the data matrix:\n        for (idx, line) in enumerate(lines[2:end])\n            data[idx, 1:colNr] = split(line,\",\");\n        end\n\n        # Get the categorical values:\n        hairCols = unique(data[:,1]);\n        eyeCols = unique(data[:,2]);\n        # Alternatively:\n    #        hairCols = Set(data[:,1]);\n    #        eyeCols = Set(data[:,2]);\n\n        # Make a named array:\n        namedData = NamedArray(zeros(length(eyeCols),length(hairCols)),\n                            (eyeCols,hairCols), (colName, rowName))\n\n        # Populate it with absolute numbers:\n        for i in 1:length(data[:,1])\n            namedData[data[i,2],data[i,1]] = parse(Float64,data[i,3]);\n        end\n\n        # Tranfsorm to relative proportions:\n        namedData = namedData ./ sum(namedData);\n\n        return namedData\n    end\nend\n###################################\n\nif taskNr == 1\n    thisFile = \"HairEyeColor.csv\";\n    println(trafoCSV(thisFile))\n\nelseif taskNr == 2\n    thisFile = \"HairEyeColor.csv\";\n    M = trafoCSV(thisFile);\n\n    # a)\n    println(\"\\nMarginal of the hair colors:\")\n    println(sum(M, dims=1))\n    # b)\n    println(\"\\nMarginal of the eye colors:\")\n    println(sum(M, dims=2))\n    # c )\n    println(\"\\nTotal sum:\")\n    println(sum(M, dims=:))\n\nelseif taskNr == 3\n    thisFile = \"HairEyeColor.csv\";\n    M = trafoCSV(thisFile);\n\n    # a)\n    print(\"\\nP(Blue eyes, Blond hair) = \")\n    println(M[\"Blue\",\"Blond\"])\n\n    # b)\n    print(\"\\nP(Brown eyes) = \")\n    println(sum(M[\"Brown\",:]))\n\n    # c)\n    # Conditional prob -> reallocate on the summed \"universe\"\n    print(\"\\nP(Brown eyes | Red hair) = \")\n    println(M[\"Brown\",\"Red\"] / sum(M[\"Brown\",:]))\n\n    # Allow several categories to survive by using a vector as input\n    # d) Make intersection of subspaces\n    print(\"\\nP((Red OR Blond) AND (Brown OR Blue) = \")\n    overlap = sum(M[[\"Brown\",\"Blue\"],[\"Red\",\"Blond\"]]);\n    println(overlap)\n\n    # e) Sum the two subspaces (remove the intersection to avoid double counting)\n    print(\"\\nP((Red OR Blond) OR (Brown OR Blue) = \")\n    combine = sum(M[[\"Brown\",\"Blue\"],:]) + sum(M[:,[\"Red\",\"Blond\"]]) - overlap;\n    println(combine)\n\n    # f) Show that P(x,y) != P(x)P(y)\n    println(\"\\nP(Blue eyes, Blond hair) != P(Blue eyes) P(Blond hair)\")\n    print(M[\"Blue\",\"Blond\"])\n    print(\" != \")\n    println(sum(M[\"Blue\",:]) * sum(M[:,\"Blond\"]))\n\n\nend\n", "meta": {"hexsha": "d3d9231e6b30f6f8244bafbee88309ae2819cec8", "size": 3019, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A2/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": "A2/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": "A2/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": 27.9537037037, "max_line_length": 81, "alphanum_fraction": 0.567406426, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7778430855991928}}
{"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": "\nusing jInv.Mesh\nusing Test\n\n# setup 2D problem for Nodal DivSigGrad\nnc = [5, 7]\nx0 = rand(2)\ndomain = [x0[1], 4, x0[2], 2]\nM = getRegularMesh(domain,nc)\nprint(\"\\ttesting forward operators for $(typeof(M))...\")\nLap = getNodalLaplacianMatrix(M)\nLsig = getNodalDivSigGradMatrix(M,ones(prod(M.nc)); saveMat = false, avN2C = avN2C_Nearest);\n@test norm(Lsig- Lap,Inf) <1e-12\t\nprint(\"passed!\\n\")\n\n\n# setup 3D problem for Nodal DivSigGrad\nnc = [5, 7, 8]\nx0 = rand(3)\ndomain = [x0[1], 4, x0[2], 2, x0[3], 6]\nh   = (domain[2:2:end]-domain[1:2:end])./nc\nh1  = h[1]*ones(nc[1])\nh2  = h[2]*ones(nc[2])\nh3  = h[3]*ones(nc[3])\n\nMt = getTensorMesh3D(h1,h2,h3,x0)\nMr = getRegularMesh(domain,nc)\nMt2 = getTensorMesh3D(h1+rand(nc[1]),h2+rand(nc[2]),h3+rand(nc[3]),x0)\n\nMeshes = (Mt,Mr,Mt2)\n\nfor k=1:length(Meshes)\n\tMk = Meshes[k]\n\tprint(\"\\ttesting forward operators for $(typeof(M))...\")\n\tLap_k = getNodalLaplacianMatrix(M)\n\tLsig_k = getNodalDivSigGradMatrix(M,ones(prod(M.nc)); saveMat = false, avN2C = avN2C_Nearest);\n\t@test norm(Lsig_k- Lap_k,Inf) <1e-12\t\n\tprint(\"passed!\\n\")\nend\n\n\n# setup 2D problem for Face Elasticity\n\nprint(\"\\ttesting 2D elasticity operators for $(typeof(M))...\")\nnc = [5, 7]\nx0 = rand(2)\ndomain = [x0[1], 4, x0[2], 2]\nM = getRegularMesh(domain,nc)\nmu = ones(prod(M.n));\nlambda = ones(prod(M.n));\nL = GetLinearElasticityOperator(M, mu,lambda);\nL2 = GetLinearElasticityOperatorFullStrain(M, mu,lambda);\nprintln(\"Diff between two elasticity ops (not sure if needs to be zero):\",norm(L-L2,1));\n# @test norm(L- L2,Inf) <1e-8\t\nprint(\"passed!\\n\")\n\n\n# setup 3D problem for Face Elasticity\nprint(\"\\ttesting 3D elasticity operators for $(typeof(M))...\")\nn = [5,7,8];\ndomain = [0.0,1.0,0.0,2.0,0.0,1.0];\nM = getRegularMesh(domain,n);\nmu = ones(prod(M.n));\nlambda = ones(prod(M.n));\nL = GetLinearElasticityOperator(M, mu,lambda)\nL2 = GetLinearElasticityOperatorFullStrain(M, mu,lambda)\n\nprintln(\"Diff between two elasticity ops (not sure if needs to be zero): \",norm(L-L2,1));\n# @test norm(L- L2,Inf) <1e-8\t\nprint(\"passed!\\n\")", "meta": {"hexsha": "723952fbe93b7e203019c9b5cac96162e527711e", "size": 2021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Mesh/testForward.jl", "max_stars_repo_name": "JuliaInv/jInv", "max_stars_repo_head_hexsha": "1e436c93e730f0356f6aec2c84c64fb61a82463c", "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": "test/Mesh/testForward.jl", "max_issues_repo_name": "JuliaInv/jInv", "max_issues_repo_head_hexsha": "1e436c93e730f0356f6aec2c84c64fb61a82463c", "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": "test/Mesh/testForward.jl", "max_forks_repo_name": "JuliaInv/jInv", "max_forks_repo_head_hexsha": "1e436c93e730f0356f6aec2c84c64fb61a82463c", "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": 28.8714285714, "max_line_length": 95, "alphanum_fraction": 0.6739238001, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7778430726444792}}
{"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": "for N in [Float64, Rational{Int}, Float32]\n    # =======\n    #  Ball1\n    # =======\n\n    # approximation of a centered unit Ball1\n    b = Ball1(N[0, 0, 0], N(1))\n    @test norm(b) \u2248 N(1)  # in the infinity norm (default)\n    @test radius(b) \u2248 N(1)  # in the infinity norm (default)\n    @test diameter(b) \u2248 N(2)  # in the infinity norm (default)\n\n    # approximations of a non-centered unit Ball1\n    b = Ball1(N[1, 2, 0], N(1))\n    @test norm(b) \u2248 N(3)  # in the infinity norm (default)\n    @test radius(b) \u2248 N(1)  # in the infinity norm (default)\n    @test diameter(b) \u2248 N(2)  # in the infinity norm (default)\n\n\n    # ================\n    #  Hyperrectangle\n    # ================\n\n    # metrics in the infinity norm (default)\n    h = Hyperrectangle(N[-1, 2], N[0.2, 0.5])\n    @test norm(h, Inf) \u2248 N(2.5)\n    @test radius(h, Inf) \u2248 N(0.5)\n    @test diameter(h, Inf) \u2248 N(1)\n\n    # metrics in the 2-norm\n    @test norm(h, 2) \u2248 N(sqrt(2.5^2 + 1.2^2))\n    @test radius(h, 2) \u2248 N(sqrt(0.5^2 + 0.2^2))\n    @test diameter(h, 2) \u2248 N(2*sqrt(0.5^2 + 0.2^2))\n\n    # =========\n    #  BallInf\n    # =========\n\n    # metrics in the infinity norm (default)\n    b = BallInf(N[-1, -2, -4], N(0.2))\n    @test norm(b, Inf) \u2248 N(4.2)\n    @test radius(b, Inf) \u2248 N(0.2)\n    @test diameter(b, Inf) \u2248 N(0.4)\n\n    # metrics in the 2-norm\n    @test norm(b, 2) \u2248 N(sqrt(1.2^2 + 2.2^2 + 4.2^2))\n    @test radius(b, 2) \u2248 N(sqrt(0.2^2 * 3))\n    @test diameter(b, 2) \u2248 N(2*sqrt(0.2^2 * 3))\n\n    # ====================================\n    #  failing case (not implemented yet)\n    # ====================================\n\n    s = MinkowskiSum(b, b)\n    @test_throws ErrorException norm(s, 2)\n    @test_throws ErrorException radius(s, 2)\n    @test_throws ErrorException diameter(s, 2)\nend\n", "meta": {"hexsha": "edd54fd9f1ed032505095d3c753a2e8c8cc98318", "size": 1754, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit_radiusdiameter.jl", "max_stars_repo_name": "UnofficialJuliaMirror/LazySets.jl-b4f0291d-fe17-52bc-9479-3d1a343d9043", "max_stars_repo_head_hexsha": "375c103128089b12d3c08f7011d24fdbffc65c47", "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": "test/unit_radiusdiameter.jl", "max_issues_repo_name": "UnofficialJuliaMirror/LazySets.jl-b4f0291d-fe17-52bc-9479-3d1a343d9043", "max_issues_repo_head_hexsha": "375c103128089b12d3c08f7011d24fdbffc65c47", "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": "test/unit_radiusdiameter.jl", "max_forks_repo_name": "UnofficialJuliaMirror/LazySets.jl-b4f0291d-fe17-52bc-9479-3d1a343d9043", "max_forks_repo_head_hexsha": "375c103128089b12d3c08f7011d24fdbffc65c47", "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": 30.2413793103, "max_line_length": 62, "alphanum_fraction": 0.5085518814, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7777619820888629}}
{"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    \u03b1::Real\n    \u025b::Real\n    \u03bb::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.\u03bb\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), \u03b1 = $(R.\u03b1), \u025b = $(R.\u025b))\")\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, \u03b1=1.0, \u025b=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* `\u03b1`: a normalization parameter\n* `\u025b`: 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, \u03b1::Real=0.0, \u025b::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, \u025b))\n    # L = pairwise((x,y)-> exp(-norm(x-y,2)^2/\u03b5), Xtr)\n\n    # Calculate Laplacian & normalize it\n    if \u03b1 > 0\n        D = transpose(sum(L, dims=1))\n        L ./= (D * transpose(D)) .^ convert(T, \u03b1)\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\u207b\u1d45 = inv(D^\u03b1)\n    # L\u1d45 = D\u207b\u1d45*L*D\u207b\u1d45\n    # D\u1d45 = Diagonal(vec(sum(L\u1d45, dims=1)))\n    # M = inv(D\u1d45)*L\u1d45\n\n    # Eigendecomposition & reduction\n    F = eigen(M, permute=false, scale=false)\n    \u03bb = real.(F.values)\n    idx = sortperm(\u03bb, rev=true)[2:maxoutdim+1]\n    \u03bb = \u03bb[idx]\n    V = real.(F.vectors[:,idx])\n    Y = (\u03bb.^t) .* V'\n\n    return DiffMap{T}(t, \u03b1, \u025b, \u03bb, 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, \u03d5, \u03b1, \u03c4, 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] = \u03d5(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, \u03b1, h)*f(t[j], y[j], v(\u03d5, j, \u03c4, h, y, yp))\n        end\n        yp[n+1] = yp[n+1]/gamma(\u03b1)+\u03d5(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, \u03b1, h)*f(t[j], y[j], v(\u03d5, j, \u03c4, h, y, yp))\n        end\n\n        y[n+1] = y[n+1]/gamma(\u03b1)+h^\u03b1*f(t[n+1], yp[n+1], v(\u03d5, n+1, \u03c4, h, y, yp))/gamma(\u03b1+2)+\u03d5(0)\n    end\n\n    delayedterm = copy(t)\n    @fastmath @inbounds @simd for n = 1:maxn-1\n        delayedterm[n] = v(\u03d5, n, \u03c4, h, y, yp)\n    end\n    return delayedterm, y\nend\n\nfunction a(j, n, \u03b1, h)\n    if j == n+1\n        result = 1\n    elseif j == 0\n        result = n^(\u03b1+1)-(n-\u03b1)*(n+1)^\u03b1\n    else\n        result = (n-j+2)^(\u03b1+1) + (n-j)^(\u03b1+1) - 2*(n-j+1)^(\u03b1+1)\n    end\n    return result*h^\u03b1 / (\u03b1 * (\u03b1 + 1))\nend\n\nfunction b(j, n, \u03b1, h)\n    return h^\u03b1/\u03b1*((n-j+1)^\u03b1 - (n-j)^\u03b1)\nend\n\nfunction v(\u03d5, n, \u03c4, h, y, yp)\n    if \u03c4 >= n*h\n        return \u03d5((n-1)*h-\u03c4)\n    else\n        m = floor(Int, \u03c4/h)\n        \u03b4 = m-\u03c4/h\n\n        if m>1\n            return \u03b4*y[n-m+2] + (1-\u03b4)*y[n-m+1]\n        elseif m == 1\n            return \u03b4*yp[n+1] + (1-\u03b4)*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 ``\u0395^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 ``\u0395^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\u2081::Plane3, h\u2082::Plane3)\n\nTest for equality: two planes are equal, iff they have a non empty intersection\nand the same orientation.\n\"\"\"\n==(h\u2081::Plane3, h\u2082::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    \u03c8 = -cumsimp(u)+repeat(cx',ly,1)\n    \u03c8 = (\u03c8+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 (`\u03b1`), number of\niterations (`n`), and convergence threshold (`\u03f5`). If convergence is not\nreached within `n` iterations, an error will be returned.\n\"\"\"\nfunction pagerank(g::DiGraph, \u03b1=0.85, n=100, \u03f5 = 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 = \u03b1 * (M * x + sum(x[is_dangling]) * dangling_weights) + (1 - \u03b1) * p\n        err = sum(abs(x - xlast))\n        if (err < N * \u03f5)\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# \u2554\u2550\u2561 2cf61e2a-ff3f-11ea-2d5b-77a2b52fd6e7\nusing CSV, DataFrames\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bea5f54e-ff37-11ea-2c37-8707c75a9b5c\nn = 15\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c9897d6a-ff47-11ea-1212-9d5eb14cd0d7\nS, b = [4 2; 1 0.3; -0.5 4], [100, 300, 210]  # soil effects\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ea977544-ff37-11ea-310b-79307ef120d3\nmd\"Below are the concentrations of nitrogen ($u$) and water status ($v$) for every field.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 17088b36-ff38-11ea-3519-85055dd00929\ncx, cy, cz = 250, 175, 325\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 223cec90-ff38-11ea-040f-47c9ee1c9036\nwx, wy, wz = 0.7, 0.85, 0.6\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 57dc25e6-ff38-11ea-342c-f19e90a2c732\nx1, y1, z1 = 10, 6, 8  # amount of seed per plot\n\n# \u2554\u2550\u2561 6137fea8-ff38-11ea-34b7-631de98c3ad4\n(Ax1, Ay1, Az1) = S * [u[1], v[1]] .+ b\n\n# \u2554\u2550\u2561 7e33d806-ff38-11ea-2297-512188693a6a\nX1 = (Ax1 * x1^2) / (120 + x1^2 + 2y1 - 0.8x1 * z1 + z1^2)\n\n# \u2554\u2550\u2561 84e7171e-ff38-11ea-07fd-5fb12ff4f039\nY1 = (Ay1 * y1^2) / (30 + 4x1 + y1^2 + 7z1)\n\n# \u2554\u2550\u2561 85d3cd6e-ff38-11ea-2d7d-539601eec8aa\nZ1 = (Az1 * z1^2) / (80 + 0.4x1 + 0.2x1*z1 +0.6y1 + z1^2)\n\n# \u2554\u2550\u2561 8a574622-ff38-11ea-15dc-1b4bb63497df\nrevenue_plot1 = wx * X1 + wy * Y1 + wz * Z1  # in EUR\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 64049c58-ff37-11ea-1ae8-f907d5e33509\nstudent_name = missing  # fill in your name(s)\n\n# \u2554\u2550\u2561 2568b67a-ff37-11ea-37fd-87a3d569fc31\nmd\"\"\"\n# Project: Sowing plan\n\n**STMO**\n\n2020-2021\n\nProject by: $student_name\n\"\"\"\n\n# \u2554\u2550\u2561 ddab3252-07bc-11eb-390a-750512ee8c90\nif ismissing(student_name)\n\tmd\"fill in your name(s) below\"\nend\n\n# \u2554\u2550\u2561 562bc43a-ff43-11ea-0451-d9e7005c56a1\nmd\"\"\"\n### 1. Formal description of the problem\n\nCOMPLETE\n\"\"\"\n\n# \u2554\u2550\u2561 5232b83c-ff43-11ea-36e4-7d08693203dc\nmd\"\"\"\n### 2. Concavity\n\nCOMPLETE\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9d2eabae-ff43-11ea-3103-0f22b5c59e6b\n\n\n# \u2554\u2550\u2561 9cd521d8-ff43-11ea-174e-71556bcdebac\n\n\n# \u2554\u2550\u2561 67882c04-ff3f-11ea-19b5-890bd3bd15a9\nsolution = fill(1.0, 15, 3)  # valid, but can be improved...\n\n# \u2554\u2550\u2561 0a220a2a-ff45-11ea-2b35-c70cdb18c0a8\nmd\"Check if the solution is valid.\"\n\n# \u2554\u2550\u2561 1411424e-ff45-11ea-2b3e-c75c7d39917a\nmd\"Save the solution.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 79df7272-ff44-11ea-01bb-716d0bf52464\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 79897d9a-ff44-11ea-269c-bba522b74d66\n\n\n# \u2554\u2550\u2561 796e75c2-ff44-11ea-2a85-0b3fbdc675b5\n\n\n# \u2554\u2550\u2561 0ba3f5f6-ff46-11ea-0449-29b505430cf9\n\n\n# \u2554\u2550\u2561 7ade6b7e-ff44-11ea-130a-bdd36b48b8af\nmd\"## Functions\"\n\n# \u2554\u2550\u2561 b96c0828-ff3b-11ea-3ee3-b979608fe705\n\"\"\"Check if a solution is valid.\"\"\"\nfunction isvalidsolution(solution::Matrix)\n\treturn size(solution) == (15, 3) && all(solution .\u2265 0.0) && all(sum(solution, dims=1) .\u2264 [cx cy cz])\nend\n\n# \u2554\u2550\u2561 6f98672e-ff3f-11ea-0198-5fbef05027da\nisvalidsolution(solution)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 928fd032-ff3f-11ea-13a0-07140325ab9f\n!ismissing(student_name) && save_solution(\"solution_$(student_name).csv\", solution);\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25002568b67a-ff37-11ea-37fd-87a3d569fc31\n# \u255f\u2500ddab3252-07bc-11eb-390a-750512ee8c90\n# \u255f\u250078701408-ff37-11ea-04a8-07805ef3cc1c\n# \u2560\u2550bea5f54e-ff37-11ea-2c37-8707c75a9b5c\n# \u255f\u25009b5ec9c8-ff37-11ea-1816-0365aa76c976\n# \u255f\u2500d327e0c2-ff37-11ea-3006-53be838b7dc8\n# \u2560\u2550c9897d6a-ff47-11ea-1212-9d5eb14cd0d7\n# \u255f\u2500e4a29d80-ff37-11ea-0d0b-59545bce9bd2\n# \u255f\u2500ea977544-ff37-11ea-310b-79307ef120d3\n# \u2560\u2550eba6a9dc-ff37-11ea-233d-1b9aca686ea4\n# \u2560\u25500e9a6d52-ff38-11ea-2472-810a521cb8f8\n# \u255f\u2500100a63f4-ff38-11ea-1fbf-05c136011e28\n# \u2560\u255017088b36-ff38-11ea-3519-85055dd00929\n# \u255f\u250025b72854-ff38-11ea-0817-0f44e6420882\n# \u2560\u2550223cec90-ff38-11ea-040f-47c9ee1c9036\n# \u255f\u25003282d3c6-ff38-11ea-0458-af74eb6b42dc\n# \u255f\u2500625ffadc-ff48-11ea-1849-39df2c3ddb85\n# \u2560\u255057dc25e6-ff38-11ea-342c-f19e90a2c732\n# \u2560\u25506137fea8-ff38-11ea-34b7-631de98c3ad4\n# \u2560\u25507e33d806-ff38-11ea-2297-512188693a6a\n# \u2560\u255084e7171e-ff38-11ea-07fd-5fb12ff4f039\n# \u2560\u255085d3cd6e-ff38-11ea-2d7d-539601eec8aa\n# \u2560\u25508a574622-ff38-11ea-15dc-1b4bb63497df\n# \u255f\u250092a481f4-ff39-11ea-1cc0-855d93b3967b\n# \u255f\u2500ea2c0d3e-ff43-11ea-14f4-932602b2fecd\n# \u2560\u255064049c58-ff37-11ea-1ae8-f907d5e33509\n# \u2560\u2550562bc43a-ff43-11ea-0451-d9e7005c56a1\n# \u2560\u25505232b83c-ff43-11ea-36e4-7d08693203dc\n# \u255f\u25008cb9cf68-ff43-11ea-399d-df193400c077\n# \u2560\u25509d2eabae-ff43-11ea-3103-0f22b5c59e6b\n# \u2560\u25509cd521d8-ff43-11ea-174e-71556bcdebac\n# \u2560\u255067882c04-ff3f-11ea-19b5-890bd3bd15a9\n# \u255f\u25000a220a2a-ff45-11ea-2b35-c70cdb18c0a8\n# \u2560\u25506f98672e-ff3f-11ea-0198-5fbef05027da\n# \u255f\u25001411424e-ff45-11ea-2b3e-c75c7d39917a\n# \u2560\u2550928fd032-ff3f-11ea-13a0-07140325ab9f\n# \u255f\u250007575a02-ff45-11ea-2794-63681f41a7bf\n# \u2560\u255079df7272-ff44-11ea-01bb-716d0bf52464\n# \u255f\u250079a661b0-ff44-11ea-10ef-fbc61315162b\n# \u2560\u255079897d9a-ff44-11ea-269c-bba522b74d66\n# \u2560\u2550796e75c2-ff44-11ea-2a85-0b3fbdc675b5\n# \u2560\u25500ba3f5f6-ff46-11ea-0449-29b505430cf9\n# \u255f\u25007ade6b7e-ff44-11ea-130a-bdd36b48b8af\n# \u2560\u25502cf61e2a-ff3f-11ea-2d5b-77a2b52fd6e7\n# \u2560\u2550b96c0828-ff3b-11ea-3ee3-b979608fe705\n# \u2560\u2550a9ca6492-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": "xvals = 0.01:0.01:8.0\nyvals = map(xvals) do x\n    comp1 = pdf(LogNormal(), x)\n    comp2 = pdf(Uniform(2.0, 3.0), x)\n    0.5 * comp1 + 0.5 * comp2\nend\n\np = Plots.plot()\nPlots.plot!(p, xvals, yvals, labels = \"Real distribution\")\n\nkde = KernelDensity.kde(xs, bandwidth = 0.1)\nPlots.plot!(p, kde.x, kde.density, labels = \"KDE\")\n\nPlots.plot!(p, xvals, yvals, labels = \"Real distribution\")\nPlots.xlims!(p, 0.0, 8.0)\nPlots.savefig(joinpath(base_img, \"compare_kde.pdf\"))\n", "meta": {"hexsha": "bfc38720b8e6571dc77aafe1bc086dab5aed3eea", "size": 463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/compare_kde.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/compare_kde.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/compare_kde.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": 27.2352941176, "max_line_length": 58, "alphanum_fraction": 0.6479481641, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.777653751124509}}
{"text": "function miuntesTillNext(a_now::Int, busId::Int)\n    #println(a_now, \", \" , busId)\n    timeSinceLast = a_now % busId\n    #println(\"timeSinceLast=\", timeSinceLast)\n    a_lastDep = (a_now \u00f7 busId) * busId\n    #println(\"a_lastDep=\", a_lastDep)\n    a_nextDep = a_lastDep + busId\n    #println(\"a_nextDep=\", a_nextDep)\n    tillNext = a_nextDep - a_now\n    #println(\"tillNext=\", tillNext)\n    return tillNext\nend\n\nfunction findEarliest(inputfile)\n    lines = readlines(inputfile)\n    now::Int = parse(Int,lines[1])\n    idsStirng = lines[2]\n    ids:: Vector{Int} = []\n    for idSubString in split(idsStirng, ',') \n        idString = String(idSubString)\n        if idString != \"x\"\n            push!(ids, parse(Int, idString))\n        end\n    end\n    candidates = Dict()\n    for id in ids\n        candidates[id] = miuntesTillNext(now, id)\n    end\n    min = findmin(candidates)\n    println(min, \" \" , min[1]*min[2])\nend\n\nfindEarliest(\"data.txt\")\n", "meta": {"hexsha": "7a3f2dbcab1dacd9544a305af855f1daf039a371", "size": 935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "13/thirteen_a.jl", "max_stars_repo_name": "antoncic/aoc2020", "max_stars_repo_head_hexsha": "3b12f9423258bc122cdb44ce166b6edcf602a2f2", "max_stars_repo_licenses": ["MIT"], "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/thirteen_a.jl", "max_issues_repo_name": "antoncic/aoc2020", "max_issues_repo_head_hexsha": "3b12f9423258bc122cdb44ce166b6edcf602a2f2", "max_issues_repo_licenses": ["MIT"], "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/thirteen_a.jl", "max_forks_repo_name": "antoncic/aoc2020", "max_forks_repo_head_hexsha": "3b12f9423258bc122cdb44ce166b6edcf602a2f2", "max_forks_repo_licenses": ["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": 49, "alphanum_fraction": 0.6245989305, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7776537473612076}}
{"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 \u00d7 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": "# Script to generate Figure 15.\nusing Plots, SparseArrays, JLD2, LinearAlgebra, Wavelets, MultiscaleGraphSignalTransforms\ninclude(\"auxilaries.jl\")\ninclude(\"../../../src/unbalanced_haar_image.jl\")\n\n# Set up the resolution and display size\ngr(dpi=200, size=(800,600))\n\n# Load the Barbara image data\nJLD2.@load \"barbara.jld2\"\n\n# smaller face region of size 100x100\nrow_zoom = 71:170\ncol_zoom = 341:440\ndisplay(heatmap(barbara[row_zoom, col_zoom],ratio=1, yaxis =:flip, \n    showaxis = false, ticks = false, color = :grays, clims = (0,1)))\n\n# Extract that portion of the image\nmatrix = deepcopy(barbara[row_zoom, col_zoom])\n\n#\n# Perform the image partition using the penalized total variation and then\n# compute the expansion coefficients\n#\np = 3.0\nmaxlev = 9 # need this to reach the single node leaves\nGPcols = PartitionTreeMatrix_unbalanced_haar_binarytree(matrix, maxlev, p)\nmaxlev = 8 # need this to reach the single node leaves\nGProws = PartitionTreeMatrix_unbalanced_haar_binarytree(copy(matrix'), maxlev, p)\n# copy() is necessary to switch the Adjoint type to a regular Matrix{Float64}.\ndmatrix = ghwt_analysis_2d(matrix, GProws, GPcols)\n\n#\n# Compute the graph Haar coefficients from the previous PTV partition tree\n#\nBS_haar_rows = bs_haar(GProws)\nBS_haar_cols = bs_haar(GPcols)\ndvec_haar, loc_haar = BS2loc(dmatrix, GProws, GPcols, BS_haar_rows, BS_haar_cols)\n\n#\n# Compute the eGHWT best basis\n#\ndvec_eghwt, loc_eghwt = eghwt_bestbasis_2d(matrix, GProws, GPcols)\n\n#\n# Classical Haar transform via Wavelets.jl with direct input\n#\ndvec_classichaar = dwt(matrix, wavelet(WT.haar))\n\n#\n# Classical Haar transform via Wavelets.jl via putting in the dyadic image\n#\nmatrix2 = zeros(128,128)\nmatrix2[15:114,15:114] = deepcopy(matrix)\ndvec_classichaar2 = dwt(matrix2, wavelet(WT.haar))\n\n#\n# Classical Haar transform via Wavelets.jl via putting in the dyadic image\n#\nmatrix3 = zeros(128,128)\nmatrix3[1:100,1:100] = deepcopy(matrix)\nmatrix3[101:end,1:100] = deepcopy(matrix[end:-1:end-27,1:100])\nmatrix3[:,101:end] = matrix3[:,100:-1:73]\ndvec_classichaar3 = dwt(matrix3, wavelet(WT.haar))\n\n# Figure 15 (Approximation error plot up to the top 5000 coefficients)\nDVEC = [ dvec_classichaar[:], dvec_classichaar2[:], dvec_classichaar3[:], \n    dvec_haar[:], dvec_eghwt[:] ]\nT = [ \"Classic Haar (direct)\", \"Classic Haar (zero pad)\", \n    \"Classic Haar (even refl)\", \"Graph Haar (PTV cost)\", \"eGHWT (PTV cost)\" ]\nL = [ (:dashdot, :orange), (:dashdot, :red), (:dashdot, :green),\n      (:solid, :blue), (:solid, :black) ]\napprox_error3(DVEC, T, L, 5000)\nsavefig(\"barbara_face100_nondyadic_haar_error.pdf\")\nsavefig(\"barbara_face100_nondyadic_haar_error.png\")\n", "meta": {"hexsha": "4265b28ffab407f3496b814c8233f47ddad203f5", "size": 2644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/paperscripts/eGHWT2021/fig15.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/fig15.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/fig15.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": 34.7894736842, "max_line_length": 89, "alphanum_fraction": 0.7443267776, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320945, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7776537426060997}}
{"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    \u03c71 = sequences .* (dim + 1)\n    \u03c72 = repeat(transpose(collect(1:dim)), n_seq, 1)\n    \u03c7::Array{Int, 2} = \u03c71 .+ \u03c72\n    \u03c7 = sort(\u03c7, dims=2)\n\n    # Define multiplicity matrix M\n    M = zeros(Float64, size(\u03c7, 1), size(\u03c7, 2) + 1)\n    M[:, 1] = \u03c7[:, 1]\n    M[:, 2:(end - 1)] = \u03c7[:, 2:end] - \u03c7[:, 1:(end - 1)]\n    M[:, end] = (dim+1)*split_factor * ones(size(\u03c7, 1)) - \u03c7[:, 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": "# This file is part of the ValidatedNumerics.jl package; MIT licensed\n\nusing ValidatedNumerics\nusing FactCheck\n\nsetprecision(Interval, 128)\nsetprecision(Interval, Float64)\n\nfacts(\"Hyperb tests\") do\n    @fact sinh(emptyinterval()) --> emptyinterval()\n    @fact sinh(Interval(0.5)) --> Interval(0.5210953054937473, 0.5210953054937474)\n    @fact sinh(Interval(0.5, 1.67)) --> Interval(0.5210953054937473, 2.5619603657712102)\n    @fact sinh(Interval(-4.5, 0.1)) --> Interval(-45.00301115199179, 0.10016675001984404)\n    @fact sinh(@biginterval(0.5)) \u2286 sinh(@interval(0.5)) --> true\n\n\n    @fact sinh(@biginterval(0.5, 1.67)) \u2286 sinh(@interval(0.5, 1.67)) --> true\n    @fact sinh(@biginterval(1.67, 3.2)) \u2286 sinh(@interval(1.67, 3.2)) --> true\n    @fact sinh(@biginterval(2.1, 5.6)) \u2286 sinh(@interval(2.1, 5.6)) --> true\n    @fact sinh(@biginterval(0.5, 8.5)) \u2286 sinh(@interval(0.5, 8.5)) --> true\n    @fact sinh(@biginterval(-4.5, 0.1)) \u2286 sinh(@interval(-4.5, 0.1)) --> true\n    @fact sinh(@biginterval(1.3, 6.3)) \u2286 sinh(@interval(1.3, 6.3)) --> true\n\n    @fact cosh(emptyinterval()) --> emptyinterval()\n    @fact cosh(Interval(0.5)) --> Interval(1.1276259652063807, 1.127625965206381)\n    @fact cosh(Interval(0.5, 1.67)) --> Interval(1.1276259652063807, 2.750207431409957)\n    @fact cosh(Interval(-4.5, 0.1)) --> Interval(1.0, 45.01412014853003)\n    @fact cosh(@biginterval(0.5)) \u2286 cosh(@interval(0.5)) --> true\n    @fact cosh(@biginterval(0.5, 1.67)) \u2286 cosh(@interval(0.5, 1.67)) --> true\n    @fact cosh(@biginterval(1.67, 3.2)) \u2286 cosh(@interval(1.67, 3.2)) --> true\n    @fact cosh(@biginterval(2.1, 5.6)) \u2286 cosh(@interval(2.1, 5.6)) --> true\n    @fact cosh(@biginterval(0.5, 8.5)) \u2286 cosh(@interval(0.5, 8.5)) --> true\n    @fact cosh(@biginterval(-4.5, 0.1)) \u2286 cosh(@interval(-4.5, 0.1)) --> true\n    @fact cosh(@biginterval(1.3, 6.3)) \u2286 cosh(@interval(1.3, 6.3)) --> true\n\n    @fact tanh(emptyinterval()) --> emptyinterval()\n    @fact tanh(Interval(0.5)) --> Interval(0.46211715726000974, 0.4621171572600098)\n    @fact tanh(Interval(0.5, 1.67)) --> Interval(0.46211715726000974, 0.9315516846152083)\n    @fact tanh(Interval(-4.5, 0.1)) --> Interval(-0.9997532108480276, 0.09966799462495583)\n\n    @fact tanh(@biginterval(0.5)) \u2286 tanh(@interval(0.5)) --> true\n    @fact tanh(@biginterval(0.5, 1.67)) \u2286 tanh(@interval(0.5, 1.67)) --> true\n    @fact tanh(@biginterval(1.67, 3.2)) \u2286 tanh(@interval(1.67, 3.2)) --> true\n    @fact tanh(@biginterval(2.1, 5.6)) \u2286 tanh(@interval(2.1, 5.6)) --> true\n    @fact tanh(@biginterval(0.5, 8.5)) \u2286 tanh(@interval(0.5, 8.5)) --> true\n    @fact tanh(@biginterval(-4.5, 0.1)) \u2286 tanh(@interval(-4.5, 0.1)) --> true\n    @fact tanh(@biginterval(1.3, 6.3)) \u2286 tanh(@interval(1.3, 6.3)) --> true\n\n    @fact asinh(@biginterval(1)) \u2286 asinh(@interval(1)) --> true\n    @fact asinh(@biginterval(0.9, 2)) \u2286 asinh(@interval(0.9, 2)) --> true\n    @fact asinh(@biginterval(3, 4)) \u2286 asinh(@interval(3, 4)) --> true\n\n    @fact acosh(@biginterval(1)) \u2286 acosh(@interval(1)) --> true\n    @fact acosh(@biginterval(-2, -0.9)) \u2286 acosh(@interval(-2, -0.9)) --> true\n    @fact acosh(@biginterval(3, 4)) \u2286 acosh(@interval(3, 4)) --> true\n\n    for a in ( Interval(17, 19), Interval(0.5, 1.2) )\n        @fact tanh(a) \u2286 sinh(a)/cosh(a) --> true\n    end\n\nend\n", "meta": {"hexsha": "79f45fe165b2a851052263073fedc9cefef851cf", "size": 3252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interval_tests/hyperbolic.jl", "max_stars_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_stars_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/interval_tests/hyperbolic.jl", "max_issues_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_issues_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/interval_tests/hyperbolic.jl", "max_forks_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_forks_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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": 52.4516129032, "max_line_length": 90, "alphanum_fraction": 0.6180811808, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7776474058681967}}
{"text": "\"\"\"\nCalculates the average of the elements in a vector ``x``.\n\"\"\"\nfunction sample_mean(x::Vector)\n    n = length(x)\n    x\u0305 = 1 / n * sum(x)\n    return x\u0305\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\u00b2 = 1 / (n - 1) * (sum(x.^2) - 1 / n * sum(x)^2)\n    return s\u00b2 \nend\n\n\n\"\"\"\nCalculates the covariance of vector ``x``.\n\"\"\"\nfunction sample_covariance(x::Vector)\n    n = length(x)\n    c\u1d6a\u1d6a = sum_of_squares(x) / (n - 1)\n    return c\u1d6a\u1d6a \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\u1d6a\u1d67 = 1 / (n -1) * (sum(x .* y) - 1 / n * sum(x) * sum(y))\n    return c\u1d6a\u1d67\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\u1d6a = \u221a(sample_variance(x))\n    s\u1d67 = \u221a(sample_variance(y))\n    c\u1d6a\u1d67 = two_sample_covariance(x, y)\n    r\u1d6a\u1d67 = c\u1d6a\u1d67 / (s\u1d6a * s\u1d67)\n    return r\u1d6a\u1d67\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\u1d6a = length(x)\n    n\u1d67 = length(y)\n    s\u00b2\u1d6a = sample_variance(x)\n    s\u00b2\u1d67 = sample_variance(y)\n    s\u00b2\u1d6a\u1d67 = ((n\u1d6a - 1) * s\u00b2\u1d6a + (n\u1d67 - 1) * s\u00b2\u1d67) / (n\u1d6a + n\u1d67 - 2)\n    return s\u00b2\u1d6a\u1d67    \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\u1d6a\u1d67 = (sum(x .* y) - 1 / n * sum(x) * sum(y))\n    return S\u1d6a\u1d67 \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- `\u03b1`: utility curvature for gains\n- `\u03b2`: utility curvature for losses\n- `\u03b3g`: probability weighting parameter for gains \n- `\u03b3l`: probability weighting parameter for losses\n- `\u03bb`: loss aversion parameter\n\nConstructor\n````julia\nProspectTheory(;\u03b1=.80, \u03b2=\u03b1, \u03b3g=.70, \u03b3l=\u03b3g, \u03bb=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    \u03b1::T1\n    \u03b2::T2\n    \u03b3g::T3\n    \u03b3l::T4\n    \u03bb::T5\nend\n\nfunction ProspectTheory(;\u03b1=.80, \u03b2=\u03b1, \u03b3g=.70, \u03b3l=\u03b3g, \u03bb=2.25)\n    return ProspectTheory(\u03b1, \u03b2, \u03b3g, \u03b3l, \u03bb)\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 \u03b1,\u03b2,\u03bb = model\n    vl,vg = split_values(gamble)\n    utilg = vg.^\u03b1\n    utill = @. -\u03bb*abs(vl)^\u03b2 \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 \u03b3g,\u03b3l = model\n    \u03c9 = [_compute_weights(pl, \u03b3l); _compute_weights(pg, \u03b3g)]\n    return \u03c9\nend\n\n\"\"\"\n*_compute_weights*\n\n`_compute_weights` computes decision weights based on cummulative outcomes\n\n- `p`: a probability vector\n- `\u03b3`: parameter that controls weighting of low and high probabilities\n\nFunction Signature\n````julia\n_compute_weights(p, \u03b3)\n````\n\"\"\"\nfunction _compute_weights(p, \u03b3)\n    n = length(p)\n    f(i) = weight(sum(p[i:n]), \u03b3) - weight(sum(p[(i+1):n]), \u03b3)\n    \u03c9 = [f(i) for i in 1:n-1]\n    isempty(p) ? nothing : push!(\u03c9, weight(p[n], \u03b3))\n    return \u03c9\nend\n\nweight(p, \u03b3) = (p^\u03b3)/(p^\u03b3 + (1-p)^\u03b3)^(1/\u03b3)\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\u00d7N with spectral radius \u03c1.\n\n```julia\nrandom_complex_matrix(N, \u03c1)\n```\n\"\"\"\nfunction random_complex_matrix(N, \u03c1)\n    \u03c3 = 1/\u221aN\n    d = Normal(0.0, \u03c3)\n    H = \u03c1 * (rand(d, (N, N)) + rand(d, (N, N)) * 1im) / \u221a2\nend\n\n\n\"\"\"Construct a random real-valued matrix of size N\u00d7N with spectral radius \u03c1.\n\n```julia\nrandom_real_matrix(N, \u03c1)\n```\n\"\"\"\nfunction random_real_matrix(N, \u03c1)\n    \u03c3 = 1/\u221aN\n    d = Normal(0.0, \u03c3)\n    H = \u03c1 * rand(d, (N, N))\nend\n\n\n\"\"\"Construct a random Hermitian matrix of size N\u00d7N with spectral radius \u03c1.\n\n```julia\nrandom_hermitian_matrix(N, \u03c1)\n```\n\"\"\"\nfunction random_hermitian_matrix(N, \u03c1)\n    \u03c3 = 1/\u221aN\n    d = Normal(0.0, \u03c3)\n    X = rand(d, (N, N))\n    H = \u03c1 * (X + X') / (2*\u221a2)\nend\n\n\n\"\"\"Construct a random sparse complex matrix.\n\n```julia\nrandom_complex_sparse_matrix(N, \u03c1, sparsity)\n```\n\nreturns a matrix of size N\u00d7N with spectral radius \u03c1 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, \u03c1, sparsity)\n    \u03c3 = 1/\u221a(sparsity * N)\n    d = Normal(0.0, \u03c3)\n    Hre = sprand(N, N, sparsity, (dims...) -> rand(d, dims...))\n    Him = sprand(N, N, sparsity, (dims...) -> rand(d, dims...))\n    H = \u03c1 * (Hre + Him * 1im) / \u221a2\nend\n\n\n\"\"\"Construct a random sparse real-valued matrix.\n\n```julia\nrandom_real_sparse_matrix(N, \u03c1, sparsity)\n```\n\nreturns a matrix of size N\u00d7N with spectral radius \u03c1 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, \u03c1, sparsity)\n    \u03c3 = 1/\u221a(sparsity * N)\n    d = Normal(0.0, \u03c3)\n    H = \u03c1 * 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, \u03c1, sparsity)\n```\n\nreturns a matrix of size N\u00d7N with spectral radius \u03c1 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, \u03c1, sparsity)\n    \u03c3 = 1/\u221a(sparsity * N)\n    d = Normal(0.0, \u03c3)\n    H = sprand(N, N, sparsity, (dims...) -> rand(d, dims...))\n    return 0.5\u03c1 * (H + H') / \u221a2\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    \u03a8 = rand(N) .* exp.((2\u03c0 * im) .* rand(N))\n    \u03a8 ./= norm(\u03a8)\n    return \u03a8\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): \u2211(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": "using Pkg\nusing NumericalMethodsforEngineers\nusing Test\n\na = [10. 5. 6.; 5. 20. 4.; 6. 4. 30.]\nx0 = [1., 1., 1.]\n\ntol = 1.0e-5\nlimit = 100\n\n(iters, eigval, eigvec) = nmex(a, x0; tol=tol, limit=limit, show=8)\n\nprintln(\"\\nNo of iters:                   $iters\")\nprintln(\"Largest eigen value:           $eigval\")\nprintln(\"Corresponding eigen vector:    $eigvec\")\nprintln()\n\njeigval, jeigvec = eigen(a);\n\nprintln(\"\\nEigen values:                   $jeigval\")\nprintln(\"Corresponding eigen vectors:\")\njeigvec |> display\n\n@test round(maximum(jeigval), digits=3) == round(eigval, digits=3)", "meta": {"hexsha": "2f6fe8090d8044acf57c60686c663766e92b7abc", "size": 581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch01/f-01-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": "examples/ch01/f-01-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": "examples/ch01/f-01-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.2083333333, "max_line_length": 67, "alphanum_fraction": 0.6265060241, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7776473927514066}}
{"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, \u03bd, blkdims)\r\n\r\nReduce the regular matrix pencil `A - \u03bbE` to an equivalent form `At - \u03bbEt = Q'*(A - \u03bbE)*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-\u03bbEi |   *     |\r\n        At - \u03bbEt = |--------|---------|, \r\n                   |    O   | Af-\u03bbEf  |\r\n \r\nwhere the `ni x ni` subpencil `Ai-\u03bbEi` contains the infinite elementary divisors and \r\nthe `nf x nf` subpencil `Af-\u03bbEf` contains the finite eigenvalues of the pencil `A-\u03bbE`.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[i]-\u03bd[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `\u03bd[nb+1] = 0`).\r\n\r\nThe subpencil `Af-\u03bbEf` 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-\u03bbEf |   *    |\r\n        At - \u03bbEt = |--------|--------|, \r\n                   |   O    | Ai-\u03bbEi |\r\n \r\nwhere the `nf x nf` subpencil `Af-\u03bbEf`, with `Ef` nonsingular and upper triangular, \r\ncontains the finite eigenvalues of the pencil `A-\u03bbE` and the `ni x ni` subpencil `Ai-\u03bbEi` \r\ncontains the infinite elementary divisors.\r\n\r\nThe subpencil `Af-\u03bbEf` is with `Af` in an upper Hessenberg form and `Ef` nonsingular and upper triangular.  \r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular  and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[nb-j+1]-\u03bd[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `\u03bd[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    \u03bd, 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, \u03bd, 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, \u03bd, blkdims)\r\n\r\nReduce the regular matrix pencil `A - \u03bbE` to an equivalent form `At - \u03bbEt = Q'*(A - \u03bbE)*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-\u03bbEi |   *     |\r\n        At - \u03bbEt = |--------|---------|, \r\n                   |    O   | Af-\u03bbEf  |\r\n \r\nwhere the `ni x ni` subpencil `Ai-\u03bbEi` contains the infinite elementary divisors and \r\nthe `nf x nf` subpencil `Af-\u03bbEf` contains the finite eigenvalues of the pencil `A-\u03bbE`.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[i]-\u03bd[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `\u03bd[nb+1] = 0`).\r\n\r\nThe subpencil `Af-\u03bbEf` 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-\u03bbEf |   *    |\r\n        At - \u03bbEt = |--------|--------|, \r\n                   |   O    | Ai-\u03bbEi |\r\n \r\nwhere the `nf x nf` subpencil `Af-\u03bbEf`, with `Ef` nonsingular and upper triangular, \r\ncontains the finite eigenvalues of the pencil `A-\u03bbE` and the `ni x ni` subpencil `Ai-\u03bbEi` \r\ncontains the infinite elementary divisors.\r\n\r\nThe subpencil `Af-\u03bbEf` 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-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular \r\nand `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[nb-j+1]-\u03bd[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `\u03bd[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    \u03bd, 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, \u03bd, 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, \u03bd, blkdims)\r\n\r\nReduce the regular matrix pencil `A - \u03bbE` to an equivalent block upper triangular form `At - \u03bbEt = Q'*(A - \u03bbE)*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 - \u03bbEt` 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-\u03bbEi   *      *    |\r\n        At - \u03bbEt = |    O   A1-\u03bbE1   *    |\r\n                   |    0     0    A2-\u03bbE2 |\r\n \r\nwhere the `ni x ni` subpencil `Ai-\u03bbEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-\u03bbE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-\u03bbE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-\u03bbE1` has unstable finite eigenvalues and `A2-\u03bbE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-\u03bbE1` has stable finite eigenvalues and `A2-\u03bbE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[i]-\u03bd[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `\u03bd[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-\u03bbE1   *      *    |\r\n        At - \u03bbEt = |    O   A2-\u03bbE2   *    |\r\n                   |    0     0    Ai-\u03bbEi |\r\n \r\nwhere the `ni x ni` subpencil `Ai-\u03bbEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-\u03bbE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-\u03bbE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-\u03bbE1` has unstable finite eigenvalues and `A2-\u03bbE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-\u03bbE1` has stable finite eigenvalues and `A2-\u03bbE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular \r\nand `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[nb-j+1]-\u03bd[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `\u03bd[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    \u03bd, 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        _, _, \u03b1, \u03b2, _, _ = 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.(\u03b1[i2]) .< smarg*abs.(\u03b2[i2]) : real.(\u03b1[i2] ./ \u03b2[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, \u03bd, (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, \u03bd, blkdims)\r\n\r\nReduce the regular matrix pencil `A - \u03bbE` to an equivalent block upper triangular form `At - \u03bbEt = Q'*(A - \u03bbE)*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 - \u03bbEt` 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 - \u03bbEt = |  0  A1-\u03bbE1   *       *     |\r\n                   |  0    0    A2-\u03bbE2    *     |\r\n                   |  0    0      0    Ai2-\u03bbEi2 |\r\n \r\nwhere the `ni1 x ni1` matrix `Ai1` and the  `ni2 x ni2` subpencil `Ai2-\u03bbEi2` contain the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-\u03bbE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-\u03bbE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-\u03bbE1` has unstable finite eigenvalues and `A2-\u03bbE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-\u03bbE1` has stable finite eigenvalues and `A2-\u03bbE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai2-\u03bbEi2` is in a staircase form, with `Ai2` nonsingular and upper triangular and `Ei2` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai2-\u03bbEi2` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[nb-j+2]-\u03bd[nb-j+1]` for `j = 1, 2, ..., nb+1` is the number of infinite elementary \r\ndivisors of degree `j` (with `\u03bd[0] := 0` and `\u03bd[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-\u03bbEi1   *      *     *  |\r\n                   |    0     A1-\u03bbE1   *     *  |\r\n        At - \u03bbEt = |    0       0    A2-\u03bbE2  *  |\r\n                   |    0       0      0    Ai2 |\r\n \r\nwhere the `ni1 x ni1` subpencil `Ai1-\u03bbEi1` and the `ni2 x ni2` upper triangular and nonsingular matrix `Ai2` contain\r\nthe infinite elementary divisors of `A-\u03bbE`, \r\nthe `n1 x n1` subpencil `A1-\u03bbE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-\u03bbE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-\u03bbE1` has unstable finite eigenvalues and `A2-\u03bbE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-\u03bbE1` has stable finite eigenvalues and `A2-\u03bbE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai1-\u03bbEi1` is in a staircase form, with `Ai1` nonsingular and upper triangular \r\nand `Ei1` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai1-\u03bbEi1` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[i]-\u03bd[i+1]` for `i = 0, 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `\u03bd[nb+1] = 0` and `\u03bd[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    \u03bd, 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        _, _, \u03b1, \u03b2, _, _ = 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.(\u03b1[i2]) .< smarg*abs.(\u03b2[i2]) : real.(\u03b1[i2] ./ \u03b2[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, \u03bd, 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, \u03bd, blkdims, sep)\r\n\r\nReduce the regular matrix pencil `A - \u03bbE` to an equivalent form `At - \u03bbEt = Q*(A - \u03bbE)*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-\u03bbEi |   0     |\r\n        At - \u03bbEt = |--------|---------|, \r\n                   |    O   | Af-\u03bbEf  |\r\n \r\nwhere the `ni x ni` subpencil `Ai-\u03bbEi` contains the infinite elementary \r\ndivisors and the `nf x nf` subpencil `Af-\u03bbEf`, with `Ef` nonsingular and upper triangular, contains the finite eigenvalues of the pencil `A-\u03bbE`.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[i]-\u03bd[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `\u03bd[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-\u03bbEf |   0    |\r\n        At - \u03bbEt = |--------|--------|, \r\n                   |   O    | Ai-\u03bbEi |\r\n \r\nwhere the `nf x nf` subpencil `Af-\u03bbEf`, with `Ef` nonsingular and upper triangular, \r\ncontains the finite eigenvalues of the pencil `A-\u03bbE` and the `ni x ni` subpencil `Ai-\u03bbEi` \r\ncontains the infinite elementary divisors.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular  and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[nb-j+1]-\u03bd[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `\u03bd[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-\u03bbEi` and `Af-\u03bbEf` is returned in `sep`, where  `0 < sep \u2264 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, \u03bd, 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, \u03bd, 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, \u03bd, 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, \u03bd, blkdims, sep)\r\n\r\nReduce the regular matrix pencil `A - \u03bbE` to an equivalent block diagonal triangular form `At - \u03bbEt = Q*(A - \u03bbE)*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 - \u03bbEt` 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-\u03bbEi   *      0    |\r\n        At - \u03bbEt = |    O   A1-\u03bbE1   0    |\r\n                   |    0     0    A2-\u03bbE2 |\r\n \r\nwhere the `ni x ni` subpencil `Ai-\u03bbEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-\u03bbE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-\u03bbE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-\u03bbE1` has unstable finite eigenvalues and `A2-\u03bbE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-\u03bbE1` has stable finite eigenvalues and `A2-\u03bbE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular and `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vector `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form  `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[i]-\u03bd[i+1]` for `i = 1, 2, ..., nb` is the number of infinite elementary divisors of degree `i` \r\n(with `\u03bd[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-\u03bbE1   0      0    |\r\n        At - \u03bbEt = |    O   A2-\u03bbE2   *    |\r\n                   |    0     0    Ai-\u03bbEi |\r\n \r\nwhere the `ni x ni` subpencil `Ai-\u03bbEi` contains the infinite elementary divisors, \r\nthe `n1 x n1` subpencil `A1-\u03bbE1` is with the pair `(A1,E1)` in a generalized Schur form, and the \r\n`n2 x n2` subpencil `A2-\u03bbE2` is with the pair `(A2,E2)` in a generalized Schur form. \r\nThe pencil `A1-\u03bbE1` has unstable finite eigenvalues and `A2-\u03bbE2` has stable finite eigenvalues if `stable_unstable = false`,\r\nwhile `A1-\u03bbE1` has stable finite eigenvalues and `A2-\u03bbE2` has unstable finite eigenvalues if `stable_unstable = true`.\r\n\r\nThe subpencil `Ai-\u03bbEi` is in a staircase form, with `Ai` nonsingular and upper triangular \r\nand `Ei` nilpotent and upper triangular. \r\nThe `nb`-dimensional vectors `\u03bd` contains the dimensions of the diagonal blocks\r\nof the staircase form `Ai-\u03bbEi` such that `i`-th block has dimensions `\u03bd[i] x \u03bd[i]`. \r\nThe difference `\u03bd[nb-j+1]-\u03bd[nb-j]` for `j = 1, 2, ..., nb` is the number of infinite elementary \r\ndivisors of degree `j` (with `\u03bd[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 \u2264 sep \u2264 1`. A value `sep \u2248 0` indicates that `A1-\u03bbE1` and `A2-\u03bbE2` 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, \u03bd, 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, \u03bd, 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, \u03bd, 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 - \u03bbI` to an equivalent block diagonal triangular form `At - \u03bbI = Q*(A - \u03bbI)*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 \u2264 sep \u2264 1`. A value `sep \u2248 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}, \u03b1::T, \u03b2::T) where {T<:BlasFloat} = \r\n                           BLAS.gemm!('N', 'N', \u03b1, A, B, \u03b2, 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": "module TestUtil\nusing Test\nusing LinearAlgebra\nusing CompressedSensing: cumbabel, coherence, babel, sparse_data,\n                precondition!, normalize!, preconditioner, dropindex!\n\n@testset \"dictionary analysis\" begin\n    n, m, k = 64, 128, 16\n    A, x, b = sparse_data(n = n, m = m, k = k, rescaled = true)\n    \u03bc = coherence(A)\n    @test \u03bc isa Real\n    @test 0 < \u03bc\n    @test babel(A, 1) \u2248 \u03bc\n    \u03bc\u2081 = cumbabel(A, k)\n    @test \u03bc\u2081 \u2248 babel.((A,), 1:k)\n    tol = 1e-12 # tolerance for violation of inequality\n    for (i, \u03bc_i) in enumerate(\u03bc\u2081)\n        @test \u03bc_i \u2264 i*\u03bc + tol\n    end\nend\n\n@testset \"preconditioning\" begin\n    n, m, k = 64, 128, 6\n    A, x, b = sparse_data(n = n, m = m, k = k, rescaled = false)\n    @. A = abs(A) # preconditioning important for coherence dictionaries\n    normalize!(A)\n    @. x = abs(x)\n    b = A*x\n\n    # svd-based preconditioner, generally yields good babel function improvements\n    PA = copy(A)\n    PA = normalize!(preconditioner(A)(PA)) # renormalize after preconditioning\n    \u03bc = cumbabel(A, k)\n    P\u03bc = cumbabel(PA, k)\n    for i in 1:k  # test that preconditioner decreases babel function\n        @test P\u03bc[i] < \u03bc[i]\n    end\n    # mean preconditioner, babel improvement of MA good but not as large as PA\n    \u03b5 = 1e-6\n    MA = copy(A)\n    normalize!(preconditioner(\u03b5)(MA))\n    M\u03bc = cumbabel(MA, k)\n    for i in 1:k  # test that preconditioner decreases babel function\n        @test M\u03bc[i] < \u03bc[i]\n    end\nend\nusing SparseArrays\n@testset \"SparseArrays extensions\" begin\n    n = 16\n    x = spzeros(n)\n    k = 3\n    @. x[1:k] = 1:k\n    @test nnz(x) == k\n    dropindex!(x, 1)\n    @test x.nzind == [2, 3]\n    @test x.nzval == [2, 3]\n    @test nnz(x) == k-1\n    # TODO: argmin, findmin\nend\n\nend\n\n# display(\u03bc)\n# display(M\u03bc)\n# display(P\u03bc)\n\n# PPA = copy(PA)\n# repeated application does change babel function, but not meaningfully\n# for _ in 1:6\n#     PPA = normalize!(preconditioner(PPA)(copy(PPA)))\n#     PP\u03bc = cumbabel(PPA, k)\n#     display(PP\u03bc)\n# end\n", "meta": {"hexsha": "c6ee805ee4448c23dc804af2a94c4cc6bfcfc1eb", "size": 1978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/util.jl", "max_stars_repo_name": "SebastianAment/CompressedSensing.jl", "max_stars_repo_head_hexsha": "ea296503966c4c50ba943bed1f9bb8168683bb2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-12-13T11:51:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T12:41:15.000Z", "max_issues_repo_path": "test/util.jl", "max_issues_repo_name": "SebastianAment/CompressedSensing.jl", "max_issues_repo_head_hexsha": "ea296503966c4c50ba943bed1f9bb8168683bb2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-11T23:57:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:54:22.000Z", "max_forks_repo_path": "test/util.jl", "max_forks_repo_name": "SebastianAment/CompressedSensing.jl", "max_forks_repo_head_hexsha": "ea296503966c4c50ba943bed1f9bb8168683bb2b", "max_forks_repo_licenses": ["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": 81, "alphanum_fraction": 0.6102123357, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7776394420641146}}
{"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)^\u03b1 (1+x)^\u03b2.\n```\n\"\"\"\nstruct Jacobi{T} <: OPS{T}\n    n       ::  Int\n    \u03b1       ::  T\n    \u03b2       ::  T\n\n    Jacobi{T}(n, \u03b1 = 0, \u03b2 = 0) where {T} = new{T}(n, \u03b1, \u03b2)\nend\n\nJacobi(n::Int; \u03b1 = 0, \u03b2 = 0) = Jacobi(n, \u03b1, \u03b2)\nJacobi(n::Int, \u03b1, \u03b2) = Jacobi(n, promote(\u03b1, \u03b2)...)\nJacobi(n::Int, \u03b1::T, \u03b2::T) where {T <: AbstractFloat} = Jacobi{T}(n, \u03b1, \u03b2)\nJacobi(n::Int, \u03b1::S, \u03b2::S) where {S} = Jacobi(n, float(\u03b1), float(\u03b2))\n\nsimilar(b::Jacobi, ::Type{T}, n::Int) where {T} = Jacobi{T}(n, b.\u03b1, b.\u03b2)\n\nsupport(b::Jacobi{T}) where {T} = ChebyshevInterval{T}()\n\nfirst_moment(b::Jacobi{T}) where {T} = (b.\u03b1+b.\u03b2+1\u22480) ?\n    T(2).^(b.\u03b1+b.\u03b2+1)*gamma(b.\u03b1+1)*gamma(b.\u03b2+1) :\n    T(2).^(b.\u03b1+b.\u03b2+1)*gamma(b.\u03b1+1)*gamma(b.\u03b2+1)/(b.\u03b1+b.\u03b2+1)/gamma(b.\u03b1+b.\u03b2+1)\n    # 2^(b.\u03b1+b.\u03b2) / (b.\u03b1+b.\u03b2+1) * gamma(b.\u03b1+1) * gamma(b.\u03b2+1) / gamma(b.\u03b1+b.\u03b2+1)\n\njacobi_\u03b1(b::Jacobi) = b.\u03b1\njacobi_\u03b2(b::Jacobi) = b.\u03b2\n\nmeasure(b::Jacobi) = JacobiWeight(b.\u03b1, b.\u03b2)\n\niscompatible(d1::Jacobi, d2::Jacobi) = d1.\u03b1 == d2.\u03b1 && d1.\u03b2 == d2.\u03b2\n\nisorthogonal(dict::Jacobi, measure::JacobiWeight) =\n\tdict.\u03b1 == measure.\u03b1 && dict.\u03b2 == measure.\u03b2\n\ngauss_rule(dict::Jacobi) = GaussJacobi(length(dict), dict.\u03b1, dict.\u03b2)\n\ninterpolation_grid(dict::Jacobi) = JacobiNodes(length(dict), dict.\u03b1, dict.\u03b2)\niscompatible(dict::Jacobi, grid::JacobiNodes) =  length(dict) == length(grid) && dict.\u03b1 \u2248 grid.\u03b1 && dict.\u03b2 \u2248 grid.\u03b2\nisorthogonal(dict::Jacobi, measure::GaussJacobi) = jacobi_\u03b1(dict) \u2248 jacobi_\u03b1(measure) && jacobi_\u03b2(dict) \u2248 jacobi_\u03b2(measure) && opsorthogonal(dict, measure)\n\nissymmetric(dict::Jacobi) = jacobi_\u03b1(dict)\u2248jacobi_\u03b2(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.\u03b1 + b.\u03b2+1 == 0)\n        one(T)/2*(b.\u03b1+b.\u03b2)+1\n    else\n        T(2*n + b.\u03b1 + b.\u03b2 + 1) * (2*n + b.\u03b1 + b.\u03b2 + 2) / T(2 * (n+1) * (n + b.\u03b1 + b.\u03b2 + 1))\n    end\nend\n\nfunction rec_Bn(b::Jacobi{T}, n::Int) where {T}\n    if (n == 0) && ((b.\u03b1 + b.\u03b2 + 1 == 0) || (b.\u03b1+b.\u03b2 == 0))\n        one(T)/2*(b.\u03b1-b.\u03b2)\n    else\n        T(b.\u03b1^2 - b.\u03b2^2) * (2*n + b.\u03b1 + b.\u03b2 + 1) / T(2 * (n+1) * (n + b.\u03b1 + b.\u03b2 + 1) * (2*n + b.\u03b1 + b.\u03b2))\n    end\nend\n\nrec_Cn(b::Jacobi{T}, n::Int) where {T} =\n    T(n + b.\u03b1) * (n + b.\u03b2) * (2*n + b.\u03b1 + b.\u03b2 + 2) / T((n+1) * (n + b.\u03b1 + b.\u03b2 + 1) * (2*n + b.\u03b1 + b.\u03b2))\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.\u03b1\n\t\t\tb = d1.\u03b2\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_\u03b1(b) == 0 && jacobi_\u03b2(b) == 0\n\t\tprint(io, \"Jacobi($(length(b)))\")\n\telse\n\t\tprint(io, \"Jacobi($(length(b)); \u03b1 = $(jacobi_\u03b1(b)), \u03b2 = $(jacobi_\u03b2(b)))\")\n\tend\nend\n\nfunction show(io::IO, b::Jacobi{T}) where T\n\tif jacobi_\u03b1(b) == 0 && jacobi_\u03b2(b) == 0\n\t\tprint(io, \"Jacobi{$(T)}($(length(b)))\")\n\telse\n\t\tprint(io, \"Jacobi{$(T)}($(length(b)); \u03b1 = $(jacobi_\u03b1(b)), \u03b2 = $(jacobi_\u03b2(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_\u03b1(b::UltrasphericalBasis) = b.\u03b1\njacobi_\u03b2(b::UltrasphericalBasis) = b.\u03b1\n\nweightfun(b::UltrasphericalBasis, x) = (1-x)^(b.\u03b1) * (1+x)^(b.\u03b1)\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            \u00b5 = mean(tmp)\n            \u03c3 = std(tmp)\n\n            # compute the z-score -\n            z_score_col = (tmp .- \u03bc)./\u03c3\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        \u00b5 = mean(dataVector)\n        \u03c3 = 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 - \u00b5)/\u03c3\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    \u03c3, \u03c1, \u03b2 = p\n    x_t = \u03c3*(u[2]-u[1])\n    y_t = u[1]*(\u03c1-u[3]) - u[2]\n    z_t = u[1]*u[2] - \u03b2*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, \u03b8, \u03d5) = r*cos(\u03b8)*sin(\u03d5), r*sin(\u03b8)*sin(\u03d5), r*cos(\u03d5)\n\nf(x) = 2x^2+5x-10\n\u2207f(x) = 4x+5\n\u2207\u00b2f(x) = 4\n\n# Set notation are defined operators\n10 \u2208 [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^{\u22a4} Q x + p^{\u22a4} 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^{\u22a4} 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^{\u22a4} 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^{\u22a4} Q x + p^{\u22a4} 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^{\u22a4} 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^{\u22a4} 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^{\u22a4} Q x + p^{\u22a4} 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^{\u22a4} 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^{\u22a4} 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": "using ClassicalOrthogonalPolynomials, ContinuumArrays, FillArrays, Test\nimport ClassicalOrthogonalPolynomials: jacobimatrix, oneto, OrthonormalWeighted\nimport DomainSets: \u211d\n\n@testset \"Hermite\" begin    \n    @testset \"Basics\" begin\n        H = Hermite()\n        w = HermiteWeight()\n        @test axes(H) == (Inclusion(\u211d), oneto(\u221e))\n        x = axes(H,1)\n        @test H[0.1,1:4] \u2248 hermiteh.(0:3,0.1) \u2248 [1,2*0.1,4*0.1^2-2,8*0.1^3-12*0.1]\n        @test w[0.1] \u2248 exp(-0.1^2)\n\n        X = jacobimatrix(H)\n        @test 0.1 * H[0.1,1:10]' \u2248 H[0.1,1:11]'*X[1:11,1:10]\n\n        @test (H'*(w .* H))[1,1] \u2248 sqrt(\u03c0)\n        @test (H'*(w .* H))[2,2] \u2248 2sqrt(\u03c0)\n        @test (H'*(w .* H))[3,3] \u2248 8sqrt(\u03c0)\n\n        D = Derivative(x)\n        @test (D*H)[0.1,1:4] \u2248 [0,2,8*0.1,24*0.1^2-12]\n    end\n\n    @testset \"OrthonormalWeighted\" begin\n        H = Hermite()\n        Q = OrthonormalWeighted(H)\n        @testset \"evaluation\" begin\n            x = 0.1\n            @test Q[x,1] \u2248 exp(-x^2/2)/\u03c0^(1/4)\n            @test Q[x,2] \u2248 2x*exp(-x^2/2)/(sqrt(2)\u03c0^(1/4))\n            # Trap test of L^2 orthonormality\n            x = range(-20,20; length=1_000)\n            @test Q[x,1:5]'Q[x,1:5] * step(x) \u2248 I\n        end\n        \n        @testset \"Differentiation\" begin\n            x = axes(Q,1)\n            D = Derivative(x)\n            D\u00b9 = Q \\ (D * Q)\n            @test D\u00b9[1:10,1:10] \u2248 -D\u00b9[1:10,1:10]'\n            D\u00b2 = Q \\ (D^2 * Q)\n            X = Q \\ (x .* Q)\n            @test (D\u00b2 - X^2)[1:10,1:10] \u2248 -Diagonal(1:2:19)\n        end\n    end\nend", "meta": {"hexsha": "b79f251a49e6d956d6d063ef620a41e13e524fe5", "size": 1524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_hermite.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": "test/test_hermite.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": "test/test_hermite.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": 32.4255319149, "max_line_length": 82, "alphanum_fraction": 0.4737532808, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.77762959580403}}
{"text": "sigmoid(x) = 1 ./ (1 .+ e.^(-x))\n\nfunction \u2207sigmoid(x)\n    f = sigmoid(x)\n    return f .* (1 - f)\nend\n", "meta": {"hexsha": "d515aad43e583b11895e6790b997ebe098a72a41", "size": 102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activation.jl", "max_stars_repo_name": "IshitaTakeshi/NeuralNetwork", "max_stars_repo_head_hexsha": "d3dce08befa2f7fff355797285d5fbe065b9af2d", "max_stars_repo_licenses": ["MIT"], "max_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": "IshitaTakeshi/NeuralNetwork", "max_issues_repo_head_hexsha": "d3dce08befa2f7fff355797285d5fbe065b9af2d", "max_issues_repo_licenses": ["MIT"], "max_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": "IshitaTakeshi/NeuralNetwork", "max_forks_repo_head_hexsha": "d3dce08befa2f7fff355797285d5fbe065b9af2d", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 32, "alphanum_fraction": 0.4803921569, "num_tokens": 39, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.777627524424961}}
{"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 \u2208 N: length of array, i.e., x \u2208 R\u207f\nd \u2208 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\u03bc is a (T x p) matrix of measurement means\n\u03a3 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    \u03bc::Matrix{AbstractFloat}\n    \u03a3::Array{AbstractFloat, 3}\nend\n\nmutable struct Filtered <: Output\n    x::Matrix{AbstractFloat}\n    P::Array{AbstractFloat, 3}\n    \u03bc::Matrix{AbstractFloat}\n    \u03a3::Array{AbstractFloat, 3}\nend\n\nmutable struct Smoothed <: Output\n    x::Matrix{AbstractFloat}\n    P::Array{AbstractFloat, 3}\n    \u03bc::Matrix{AbstractFloat}\n    \u03a3::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\u2013Borwein\u2013Plouffe formula (BBP formula) is a formula for \u03c0\n\n\n#=\nComputing Bailey\u2013Borwein\u2013Plouffe 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": "using Test\nusing AutoDiff.Backward\n\n@testset \"f(x,y,z) = x + 2*y/z\" begin\n    f(x, y, z) = x + 2.0*y/z\n    g = gradient(f)\n\n    @test all(isapprox.(g(1.0, 2.0, 3.0), [1.0, 2.0/3.0, -4.0/9.0]))\nend\n\n@testset \"one-arg functions\" begin\n    f(x) = 2.0*x + 3.0\n    g = gradient(f)\n\n    @test isapprox(g(1.0), 2.0)\nend\n\n@testset \"vector-mode functions\" begin\n    f(xs) = sqrt(xs[1]*xs[1] + xs[2]*xs[2] + xs[3]*xs[3])\n    g = gradient(f)\n    xs = randn(3)\n    @test all(isapprox.(g(xs), [xs[1]/f(xs), xs[2]/f(xs), xs[3]/f(xs)]))\nend\n\n@testset \"array-mode functions\" begin\n    f(xs) = sqrt(sum(xs.*xs))\n    g = gradient(f)\n    xs = randn(3, 5, 7)\n    r = f(xs)\n    @test all(isapprox.(g(xs), xs./r))\n    @test size(g(xs))==(3,5,7)\nend\n\n@testset \"reuse variable\" begin\n    f(x, y, z) = x - 3.0*x/(y*z) + z*y\n    g = gradient(f)\n\n    x = randn()\n    y = randn()\n    z = randn()\n\n    @test all(isapprox.(g(x, y, z), [1.0 - 3.0/(y*z), 3.0*x/(y*y*z) + z, 3.0*x/(y*z*z) + y]))\nend\n\n@testset \"unary minus\" begin\n    f(x,y,z) = -x + (-y)*z\n    g = gradient(f)\n    x,y,z = randn(3)\n    @test all(isapprox.(g(x,y,z), [-1.0, -z, -y]))\nend\n\n@testset \"exp\" begin\n    f(x,y,z) = x*exp(y*z)\n    g = gradient(f)\n    x,y,z = randn(3)\n    ff = f(x,y,z)\n    @test all(isapprox.(g(x,y,z), [ff/x, z*ff, y*ff]))\nend\n\n@testset \"sqrt\" begin\n    f(x,y,z) = sqrt(x*x + y*y + z*z)\n    f_and_g = value_and_gradient(f)\n    x,y,z = randn(3)\n\n    ff, gg = f_and_g(x,y,z)\n\n    @test all(isapprox.(gg, [x/ff, y/ff, z/ff]))\nend\n\n@testset \"trig\" begin\n    @testset \"sin\" begin\n        f(x,y,z) = x*sin(y*z)\n        g = gradient(f)\n        x,y,z = randn(3)\n        @test all(isapprox.(g(x,y,z), [sin(y*z), x*z*cos(y*z), x*y*cos(y*z)]))\n    end\n\n    @testset \"cos\" begin\n        f(x,y,z) = x*cos(y*z)\n        g = gradient(f)\n        x,y,z = randn(3)\n        @test all(isapprox.(g(x,y,z), [cos(y*z), -z*x*sin(y*z), -x*y*sin(y*z)]))\n    end\n\n    @testset \"tan\" begin\n        f(x,y,z) = x*tan(y*z)\n        ff(x,y,z) = x*sin(y*z)/cos(y*z)\n        g = gradient(f)\n        gg = gradient(ff)\n        x,y,z = randn(3)\n        @test all(isapprox.(g(x,y,z), gg(x,y,z)))\n    end\n\n    @testset \"sec\" begin\n        f(x,y,z) = x*sec(y*z)\n        ff(x,y,z) = x/cos(y*z)\n        g = gradient(f)\n        gg = gradient(ff)\n        x,y,z = randn(3)\n        @test all(isapprox.(g(x,y,z), gg(x,y,z)))\n    end\n\n    @testset \"csc\" begin\n        f(x,y,z) = x*csc(y*z)\n        ff(x,y,z) = x/sin(y*z)\n        g = gradient(f)\n        gg = gradient(ff)\n        x,y,z = randn(3)\n        @test all(isapprox.(g(x,y,z), gg(x,y,z)))\n    end\n\n    @testset \"cot\" begin\n        f(x,y,z) = x*cot(y*z)\n        ff(x,y,z) = x/tan(y*z)\n        g = gradient(f)\n        gg = gradient(ff)\n        x,y,z = randn(3)\n        @test all(isapprox.(g(x,y,z), gg(x,y,z)))\n    end\n\n    @testset \"atan\" begin\n        f(x,y,z) = atan(fff(x,y,z))\n        ff(x,y,z) = tan(f(x,y,z))\n        fff(x,y,z) = sqrt(x*x+y*y+z*z)\n        g = gradient(f)\n        gg = gradient(ff)\n        ggg = gradient(fff)\n        x,y,z = randn(3)\n        @test all(isapprox.(ggg(x,y,z), gg(x,y,z)))\n    end\n\n    @testset \"atan2\" begin\n        f(theta) = atan(sin(theta),cos(theta))\n        g = gradient(f)\n        theta = 2*pi*randn()\n        @test isapprox(g(theta), 1.0)\n    end\nend\n\n@testset \"sum like functions\" begin\n    @testset \"sum\" begin\n        f(x, y, z) = sum([x,y,z])\n        g = gradient(f)\n        x,y,z = randn(3)\n        @test all(isapprox.(g(x,y,z), ones(3)))\n    end\nend\n\n@testset \"log\" begin\n    f(x,y,z) = log(x*y*z)\n    g = gradient(f)\n    x,y,z = abs.(randn(3))\n    @test all(isapprox.(g(x,y,z), [1.0/x, 1.0/y, 1.0/z]))\nend\n\n@testset \"log1p\" begin\n    f(x,y,z) = log1p(x*y*z)\n    g = gradient(f)\n    x,y,z = 1e-3.*randn(3)\n    @test all(isapprox.(g(x,y,z), [y*z/(1+x*y*z), x*z/(1+x*y*z), x*y/(1+x*y*z)]))\nend\n\n@testset \"logsumexp\" begin\n    f(x,y,z) = logsumexp(x, logsumexp(y, z))\n    f_exact(x,y,z) = log(exp(x) + exp(y) + exp(z))\n    g = gradient(f)\n    g_exact = gradient(f_exact)\n    gg = gradient(logsumexp) # Array version\n\n    x,y,z = randn(3)\n\n    @test all(isapprox.(g(x,y,z), g_exact(x,y,z)))\n    @test all(isapprox.(gg([x,y,z]), g_exact(x,y,z)))\nend\n\n@testset \"intermediate reuse\" begin\n    function f(x,y,z)\n        q = x*y + cos(z*x)\n        x*sin(q) + z*q*q\n    end\n    g = gradient(f)\n    x,y,z = randn(3)\n\n    @test all(isapprox.(g(x,y,z),\n                        [(2.0*z*(x*y + cos(x*z)) + x*cos(x*y + cos(x*z)))*(y-z*sin(z*x)) + sin(x*y + cos(x*z)),\n                         x*(2.0*z*(x*y + cos(x*z)) + x*cos(x*y + cos(x*z))),\n                         (x*y + cos(x*z))^2 - x*(2.0*z*(x*y + cos(x*z)) + x*(cos(x*y + cos(x*z))))*sin(x*z)]))\nend\n", "meta": {"hexsha": "35b04dbd376fe0892bd9c856f601613e1191ef8d", "size": 4659, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/BackwardTest.jl", "max_stars_repo_name": "farr/AutoDiff.jl", "max_stars_repo_head_hexsha": "adb53b6a3055d91c2ae62cd81afa6e7c2063bd1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-23T20:25:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-23T20:25:43.000Z", "max_issues_repo_path": "test/BackwardTest.jl", "max_issues_repo_name": "farr/AutoDiff.jl", "max_issues_repo_head_hexsha": "adb53b6a3055d91c2ae62cd81afa6e7c2063bd1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-27T00:51:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-09T22:20:12.000Z", "max_forks_repo_path": "test/BackwardTest.jl", "max_forks_repo_name": "farr/AutoDiff.jl", "max_forks_repo_head_hexsha": "adb53b6a3055d91c2ae62cd81afa6e7c2063bd1c", "max_forks_repo_licenses": ["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.6507936508, "max_line_length": 111, "alphanum_fraction": 0.4764971024, "num_tokens": 1785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.7775098667522082}}
{"text": "# ---\n# title: 494. Target Sum\n# id: problem494\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Dynamic Programming, Depth-first Search\n# link: <https://leetcode.com/problems/target-sum/description/>\n# hidden: true\n# ---\n# \n# You are given a list of non-negative integers, a1, a2, ..., an, and a target,\n# S. Now you have 2 symbols `+` and `-`. For each integer, you should choose one\n# from `+` and `-` as its new symbol.\n# \n# Find out how many ways to assign symbols to make sum of integers equal to\n# target S.\n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: nums is [1, 1, 1, 1, 1], S is 3. \n#     Output: 5\n#     Explanation: \n#     \n#     -1+1+1+1+1 = 3\n#     +1-1+1+1+1 = 3\n#     +1+1-1+1+1 = 3\n#     +1+1+1-1+1 = 3\n#     +1+1+1+1-1 = 3\n#     \n#     There are 5 ways to assign symbols to make the sum of nums be target 3.\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * The length of the given array is positive and will not exceed 20.\n#   * The sum of elements in the given array will not exceed 1000.\n#   * Your output answer is guaranteed to be fitted in a 32-bit integer.\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "e591090888f64c863b7baab39da7542a105f3b28", "size": 1185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/494.target-sum.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/494.target-sum.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/494.target-sum.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.7, "max_line_length": 80, "alphanum_fraction": 0.5983122363, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8633915976709976, "lm_q1q2_score": 0.7775098461768813}}
{"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 (\u52fe\u914d\u6cd5)\n#\n# \u52fe\u914d\u6cd5\u306e\u7df4\u7fd2\u3068\u3057\u3066\u4e0b\u8a18\u306e\u7c21\u5358\u306a\u8a2d\u5b9a\u306e\u3082\u3068\u3067\u52fe\u914d\u6cd5\u3092\u9010\u6b21\u9069\u7528\u3059\u308b\u3053\u3068\u3067\u76ee\u7684\u95a2\u6570\u306e\u6975\u5024\u554f\u984c\u3092\u89e3\u304f\u969b\u306e\u70b9\u306e\u52d5\u304d\u3092\u53ef\u8996\u5316\u3059\u308b.\n#\n# $A$ \u3092 2x2 \u306e\u5b9f\u5bfe\u79f0\u884c\u5217\u3068\u3057, $f=f(x,y)$ \u3092\u6b21\u3067\u5b9a\u3081\u308b\u4e8c\u5909\u6570\u95a2\u6570\u3068\u3059\u308b.\n#\n# $$\n# f(x,y) =  \\begin{bmatrix}x & y\\end{bmatrix} A \\begin{bmatrix} x \\\\ y \\end{bmatrix}\n# $$\n#\n# \u3053\u306e\u3068\u304d $f$ \u306e\u52fe\u914d\u30d9\u30af\u30c8\u30eb\u306f $\\nabla f$ \u306f \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# \u3068\u66f8\u3051\u308b. \u521d\u671f\u4f4d\u7f6e\u3092 $v_0\\in\\mathbb{R}^2$, \u5b66\u7fd2\u7387\u3092 $\\eta$ \u3068\u3059\u308c\u3070 $i$ \u756a\u76ee\u306e\u30b9\u30c6\u30c3\u30d7\u3067\u5f97\u3089\u308c\u308b\u70b9\u306f\u6b21\u306e\u3088\u3046\u306b\u306a\u308b.\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\u2207f(v) = A * v\n\u03b7 = 0.05 # learning rate\n# -\n\n# ## \u7b49\u9ad8\u7dda\u306e\u63cf\u753b\n\nx = range(-10,stop=10,length=50)\ny = range(-10,stop=10,length=50)\np = contour(x, y, f)\n\n# ## \u52fe\u914d\u6cd5\u3092\u8a66\u3059\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 .-= \u03b7 .* \u2207f(v)\n    scatter!(\n        p, [v[1]], [v[2]], \n        label=:none, color=:blue, msize=3,\n    )\nend\n\nplot(p)\n# -\n\n# ## \u30e9\u30f3\u30c0\u30e0\u306b\u70b9\u3092\u914d\u7f6e\u3057\u305d\u308c\u3092\u521d\u671f\u5024\u3068\u3059\u308b\u52fe\u914d\u6cd5\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 =\u3000RGB(rand(3)...)\n    for _ in 1:30 # num steps\n        v .-= \u03b7 .* \u2207f(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 Revise\nusing NLS_Fit\nusing DelimitedFiles\nusing LinearAlgebra\n\nrootDir = joinpath(dirname(pathof(NLS_Fit)), \"..\")\ndataDir = joinpath(rootDir,\"data\")\ndataFile = joinpath(dataDir,\"simple_gaussian.txt\")\n\n# Getting started example ****************\n#\n\n# Data ================\n#\nXY=readdlm(dataFile);\nX=XY[:,1];\nY=XY[:,2];\n\n# Fitting ================\n#\nmodel = Gaussian_Peak() \n\n\u03b8_init = Float64[1,10,5]\n\nnls = NLS_ForwardDiff_From_Model2Fit(model,X,Y);\nconf = NLS_Solver.LevenbergMarquardt_Conf()\nresult = NLS_Solver.solve(nls,\u03b8_init,conf)\n\n# Fit result ================\n#\n@assert NLS_Solver.converged(result)\n\n\u03b8_true = Float64[2,25,3] # cheating...\n\u03b8_solver = NLS_Solver.solution(result)\n\nprintln(\"Found $\u03b8_solver, error is $(norm(\u03b8_solver-\u03b8_true,Inf))\")\nprintln(\"(caveat: error is mainly due to noisy data, not due to solver accuracy)\")\n\n# Check solver accuracy by using a noise free input ****************\n#\n\n# Generate noise free input ================\n#\nn = 50\nmodel = Gaussian_Peak()\n\u03b8 = Float64[2,n/2,3]\n\nX=Float64[1:n;];\nY=eval_y(model,X,\u03b8);\n\n# Solve and print new noise free results ================\n#\nnls = NLS_ForwardDiff_From_Model2Fit(model,X,Y);\nresult = NLS_Solver.solve(nls,\u03b8_init,conf)\n\u03b8_solver = NLS_Solver.solution(result)\n\nprintln(\"Found $\u03b8_solver, error is $(norm(\u03b8_solver-\u03b8_true,Inf))\")\n", "meta": {"hexsha": "45e81e70a54fb0323893c7df57fd3d187d26f8e9", "size": 1310, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sandbox/simple_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": "sandbox/simple_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": "sandbox/simple_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": 22.5862068966, "max_line_length": 82, "alphanum_fraction": 0.6702290076, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7774067549850308}}
{"text": "using NaNStatistics\nusing Test, StatsBase, Statistics, LinearAlgebra\n\n@testset \"ArrayStats\" begin include(\"testArrayStats.jl\") end\n@testset \"Covariance and Correlation\" begin include(\"testCovCor.jl\") end\n@testset \"Sorting\" begin include(\"testSorting.jl\") end\n\n@testset \"Histograms\" begin include(\"testHistograms.jl\") end\n@testset \"Binning\" begin include(\"testBinning.jl\") end\n", "meta": {"hexsha": "54ed4ebf799630e44e455b42e45d4cf7e1a1403f", "size": 376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 37.6, "max_line_length": 72, "alphanum_fraction": 0.789893617, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7774067539452622}}
{"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": "# Removing t = 0, such that \u03a3 is invertible\nt = Vector(0.1:0.1:10)\np = 2\n\n# Creating generators U,V that result in a positive-definite matrix \u03a3\nUt, Vt = spline_kernel(t', p)\nK = SymSemiseparableMatrix(Ut,Vt)\n\u03a3    = Matrix(K)\nchol = cholesky(\u03a3)\n\n# Creating a symmetric extended generator representable semiseperable matrix\n# Calculating its Cholesky factorization\nL = cholesky(K)\n# Creating a test vector\nxt = ones(size(K,1),10)\n\n# Testing size\n@test size(L,1) == length(t)\n@test size(L,2) == length(t)\n\n\n# Testing inverses (Using Cholesky factorizations)\n@test chol.L\\xt  \u2248 L\\xt\n@test chol.U\\xt  \u2248 L'\\xt\n@test chol.L*xt  \u2248 L*xt\n@test chol.L'*xt \u2248 L'*xt\n\n# Testing logdet and det\n@test logdet(L) \u2248 logdet(chol.L)\n@test det(L) \u2248 det(chol.L)\n\n# Testing show\n@test L.L \u2248 tril(Ut'*L.Wt)\n@test L.U \u2248 triu(L.Wt'*Ut)\n@test Matrix(L) \u2248 tril(Ut'*L.Wt)\n@test L[3,1] \u2248 chol.L[3,1]\n@test L[2,2] \u2248 chol.L[2,2]\n@test L[1,3] \u2248 chol.L[1,3]\n", "meta": {"hexsha": "ebbc230c9c5d814ab86a89002caca862ed7e61a2", "size": 923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_symsepchol.jl", "max_stars_repo_name": "mipals/SymSemiseparableMatrices.jl", "max_stars_repo_head_hexsha": "788560fd69ccd0abc00c0b821120f866afb8fb46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-31T10:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T10:54:48.000Z", "max_issues_repo_path": "test/test_symsepchol.jl", "max_issues_repo_name": "mipals/SymSemiseparableMatrices.jl", "max_issues_repo_head_hexsha": "788560fd69ccd0abc00c0b821120f866afb8fb46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-10-31T09:46:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T18:04:52.000Z", "max_forks_repo_path": "test/test_symsepchol.jl", "max_forks_repo_name": "mipals/SymSemiseparableMatrices.jl", "max_forks_repo_head_hexsha": "788560fd69ccd0abc00c0b821120f866afb8fb46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:52:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:52:16.000Z", "avg_line_length": 23.6666666667, "max_line_length": 76, "alphanum_fraction": 0.6684723727, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7774067504912527}}
{"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": "\r\n\r\n\r\n\r\ninclude(\"../../common/numder/src/numder_module.jl\")\r\n\r\nmodule nonlineq\r\nusing LinearAlgebra\r\nusing ..numder\r\n\r\ninclude(\"../../opti/src/line_search.jl\")\r\n\r\n\r\nstruct ToleranceOptions\r\n    max_iter::Int\r\n    step_size_tol::Float64\r\nend\r\n\r\nfunction ToleranceOptions(;max_iter = 100, step_size_tol = 1e-15)\r\n    ToleranceOptions(max_iter, step_size_tol)\r\nend\r\n\r\n\r\nfunction broyden(\r\n    fcn,\r\n    x0::Vector{T};\r\n    tol_options::ToleranceOptions = ToleranceOptions(),\r\n    B0 = nothing,\r\n    damping = 1.0) where {T}\r\n\r\n    n_dim = length(x0)\r\n\r\n    if isnothing(B0)\r\n        B = Matrix( one(T) * I, n_dim, n_dim )\r\n        B = numder.jacobian_fw(fcn, x0)\r\n    else\r\n        B = B0\r\n    end\r\n    \r\n    x = x0\r\n    f = fcn(x)\r\n\r\n    x_sol = x\r\n\r\n    # merit_fcn(x) = norm( fcn(x) )\r\n    iter = 0\r\n    for outer iter = 1:tol_options.max_iter\r\n        \r\n        p = -(B \\ f)\r\n        # line search? -> damping\r\n        s = damping * p\r\n\r\n        if norm(s) <= tol_options.step_size_tol\r\n            x_sol = x\r\n            break\r\n        end\r\n\r\n        x = x + s\r\n        f1 = fcn(x)\r\n        y = f1 - f\r\n        f = f1\r\n        B = B + (y - B * s) * (s ./ dot(s, s))'\r\n\r\n    end\r\n    if iter == tol_options.max_iter\r\n        x_sol = x\r\n    end\r\n    return (x_sol, iter)\r\n\r\nend\r\n\r\n\r\n\r\n\r\n\r\nend # nonlineq\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "54a4cf99cd2ac141164f3a5189363ddab58a4f61", "size": 1313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/nonlineq/src/nonlineq_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/nonlineq/src/nonlineq_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/nonlineq/src/nonlineq_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": 16.2098765432, "max_line_length": 66, "alphanum_fraction": 0.5072353389, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.8198933337131077, "lm_q1q2_score": 0.7773855860283092}}
{"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) \u00f7 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        \u0394 = stop-start\n        dist = distance(\u0394)\n        \u03b4 = intdiv(\u0394, dist)\n        for l in 0:dist\n            pos = start+\u03b4*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} \u21a6 \\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,\u03b8)` 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 `\u03b7`:\nS = number_of_boundary_sampling_nodes(N; \u03b7=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\u03a6ppw = approximation_set(N; k=k);\n# The matrix and its (SVD) factorization\nAppw = samples_from_nodes(\u03a6ppw, X);\niAppw = RegularizedSVDPseudoInverse(Appw; \u03f5=1e-14);\n# The coefficients of the approximation are computed:\n\u03beppw = solve_via_regularizedSVD(iAppw, b);\nu\u0303ppw = (r,\u03b8) -> sum([\u03bei * \u03d5i(r,\u03b8) for (\u03bei, \u03d5i) in zip(\u03beppw, \u03a6ppw)]);\n# Absolute error function\neppw = (r,\u03b8) -> u\u0303ppw(r,\u03b8) - u(r,\u03b8); eppw(1,\u03c0/2)\n# Let's compute the relative residual:\nresppw = norm(Appw * \u03beppw - b) / norm(b)\n# We did not obtained any accuracy whatsoever!\n# The reason is that the coefficients are too large:\nnrmppw = norm(\u03beppw) / norm(U)\n\n\n# ## Approximation with **evanescent** plane waves\n\n# We construct the approximation set of EPW:\n\u03a6epw = 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(\u03a6epw, X);\niAepw = RegularizedSVDPseudoInverse(Aepw; \u03f5=1e-14);\n# The coefficients of the approximation are computed:\n\u03beepw = solve_via_regularizedSVD(iAepw, b);\nu\u0303epw = (r,\u03b8) -> sum([\u03bei * \u03d5i(r,\u03b8) for (\u03bei, \u03d5i) in zip(\u03beepw, \u03a6epw)]);\n# Absolute error function\neepw = (r,\u03b8) -> u\u0303epw(r,\u03b8) - u(r,\u03b8); eepw(1,\u03c0/2)\n# Let's compute the relative residual:\nresepw = norm(Aepw * \u03beepw - b) / norm(b)\n# We get almost 8 digits of accuracy!\n# The size of the coefficients remains quite high:\nnrmepw = norm(\u03beepw) / 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_, \u03beepw, u\u0303epw, 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": "using FFTW\nusing DelimitedFiles\n\n# using the convolutional theorem\nfunction convolve_fft(signal1::Array{T}, signal2::Array{T}) where {T <: Number}\n    return ifft(fft(signal1).*fft(signal2))\nend\n\nfunction main()\n\n    # Random distribution in x\n    x = rand(100)\n\n    # Gaussian signals\n    y = [exp(-((i-50)/100)^2/.01) for i = 1:100]\n\n    # Normalization is not strictly necessary, but good practice\n    normalize!(x)\n    normalize!(y)\n\n    # cyclic convolution via the convolutional theorem\n    fft_output = convolve_fft(x, y)\n\n    # outputting convolutions to different files for plotting in external code\n    writedlm(\"fft.dat\", fft_output)\n\nend\n", "meta": {"hexsha": "31a504eaf44281e69ce12810a3b188fc72f04288", "size": 650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/convolutions/code/julia/convolutional_theorem.jl", "max_stars_repo_name": "Ridham177/algorithm-archive", "max_stars_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-06-30T08:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T17:24:30.000Z", "max_issues_repo_path": "contents/convolutions/code/julia/convolutional_theorem.jl", "max_issues_repo_name": "Ridham177/algorithm-archive", "max_issues_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-05T19:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-05T22:31:07.000Z", "max_forks_repo_path": "contents/convolutions/code/julia/convolutional_theorem.jl", "max_forks_repo_name": "Ridham177/algorithm-archive", "max_forks_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-28T12:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T20:38:46.000Z", "avg_line_length": 23.2142857143, "max_line_length": 79, "alphanum_fraction": 0.6938461538, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7773825633668513}}
{"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 \u2265 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\u25b2\n        \u2502     /\n        \u2502    /\n  u_min \u2502   /\n\u2500\u2500\u2500\u2500\u2500|\u2500\u2500\u253c\u2500\u2500|\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba u\n    /   \u2502   u_max\n   /    \u2502\n  /     \u2502\n```\n\"\"\"\nfunction DeadZone(; name, u_max, u_min=-u_max)\n    if !ModelingToolkit.isvariable(u_max)\n        u_max \u2265 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 \u2265 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": "# m5.4.AMs.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_AM = \"\ndata {\n    int N;\n    vector[N] A;\n    vector[N] M;\n}\nparameters {\n    real a;\n    real bAM;\n    real<lower=0> sigma;\n}\nmodel {\n    vector[N] mu = a + bAM * M;\n    a ~ normal( 0 , 0.2 );\n    bAM ~ normal( 0 , 0.5 );\n    sigma ~ exponential( 1 );\n    A ~ normal( mu , sigma );\n}\n\";\n\n# Define the SampleModel\n#tmpdir=ProjDir*\"/tmp\"\nm5_4_AMs = SampleModel(\"m5.4.AM\", stan5_4_AM);\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_AMs = stan_sample(m5_4_AMs, data=m5_4_data);\n\nif success(rc5_4_AMs)\n\n    part5_4_AMs = read_samples(m5_4_AMs, :particles)\n    part5_4_AMs |> display\n\nend\n\n# End of m5.3.AMs.jl", "meta": {"hexsha": "02f5fa06a78397f91fd3ba7e980f4ac4cf2da6dd", "size": 1068, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/05/m5.4.AMs.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.AMs.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.AMs.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.1818181818, "max_line_length": 58, "alphanum_fraction": 0.5983146067, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7773825592607527}}
{"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\u2013Stokes\n=====\n***\n\nFor a moment, recall the Navier\u2013Stokes 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? \u2014If 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    \u03bcstate, \u03a3state = Array{Vector{Float64}}(undef, N), Array{Matrix{Float64}}(undef, N)\n\n    # Start recursion with prior mean and prior covariance\n\n    m\u02e2\u2096\u208a\u2081, P\u02e2\u2096\u208a\u2081 = m[end], P[end]\n\n    \u03bcstate[N], \u03a3state[N] = m\u02e2\u2096\u208a\u2081, P\u02e2\u2096\u208a\u2081\n\n    for k in N-1:-1:1\n\n        m\u207b\u2096\u208a\u2081 = A * m[k]\n\n        P\u207b\u2096\u208a\u2081 = A * P[k] * A' + Q\n\n        G\u2096 = (P[k] * A') / P\u207b\u2096\u208a\u2081\n\n        m\u02e2\u2096 = m[k] + G\u2096 * (m\u02e2\u2096\u208a\u2081 - m\u207b\u2096\u208a\u2081)\n\n        P\u02e2\u2096 = P[k] + G\u2096 * (P\u02e2\u2096\u208a\u2081 - P\u207b\u2096\u208a\u2081) * (G\u2096)'\n\n        # store mean and covariance of Gaussian distribution N(x\u2096|m\u02e2\u2096, P\u02e2\u2096)\n        P\u02e2\u2096 = (P\u02e2\u2096 + (P\u02e2\u2096)') / 2\n\n        \u03bcstate[k], \u03a3state[k] = m\u02e2\u2096, P\u02e2\u2096\n\n        # previous state\n\n        m\u02e2\u2096\u208a\u2081, P\u02e2\u2096\u208a\u2081 = m\u02e2\u2096, P\u02e2\u2096\n\n    end\n\n    return \u03bcstate, \u03a3state\n\nend\n\n\n\nfunction testsmoothing(seed=1)\n\n    yclean, y, x, A, H, Q, R, m\u2080, P\u2080 = simulatedata(seed=seed)\n\n    \u03bcfilter, \u03a3filter = filteringrecursion(y; A = A, H = H, Q = Q, R = R, m\u2080 = m\u2080, P\u2080 = P\u2080)\n\n    \u03bcsmooth, \u03a3smooth = smoothingrecursion(y; A = A, H = H, Q = Q, R = R, m = \u03bcfilter, P = \u03a3filter)\n\n\n    figure()\n    subplot(211)\n    plot([y\u1d62[1]        for y\u1d62 in yclean], label = \"simulated 1\")\n    plot([(H*x\u1d62)[1]    for x\u1d62 in x], label = \"simulated 1\")\n    legend()\n\n    subplot(212)\n    plot([x\u1d62[1]    for x\u1d62 in x], label = \"simulated 1\")\n    plot([x\u1d62[1]    for x\u1d62 in \u03bcfilter], label = \"filtered 1\")\n    plot([x\u1d62[1]    for x\u1d62 in \u03bcsmooth], \"--\", 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*\u03bcfilter[i]).^2)/ length(y)\n\n        accsmooth += sum((yclean[i] - H*\u03bcsmooth[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] - \u03bcfilter[i]).^2)\n\n        accsmoothx += sum((x[i] - \u03bcsmooth[i]).^2)\n\n    end\n\n    @show accx, accfilterx, accsmoothx\n\n\n    x, \u03bcfilter, \u03bcsmooth\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": "module MINLP\n\nusing JuMP, BARON, Test\n\nm = Model(BARON.Optimizer)\nub = [2, 2, 1]\n@variable(m, 0 \u2264 x[i=1:3] \u2264 ub[i])\n@variable(m, y[1:3], Bin)\n\n@NLconstraints(m, begin\n    0.8log(x[2]+1) + 0.96log(x[1]-x[2]+1) - 0.8x[3]         \u2265  0\n       log(x[2]+1) + 1.20log(x[1]-x[2]+1)  -   x[3] - 2y[3] \u2265 -2\n       x[2] \u2264  x[1]\n       x[2] \u2264 2y[1]\n       x[1] - x[2] \u2264 2y[2]\n       y[1] + y[2] \u2264 1\nend)\n\n@NLobjective(m, Min, 5y[1] + 6y[2] + 8y[3] + 10x[1] - 7x[3] - 18log(x[2]+1) -\n                        19.2log(x[1]-x[2]+1) + 10)\n\noptimize!(m)\n\n@test isapprox(value(x[1]), 1.300975890892825, rtol=1e-6)\n@test isapprox(value(x[2]), 0.0, rtol=1e-6)\n@test isapprox(value(x[3]), 1.0, rtol=1e-6)\n@test isapprox(value(y[1]), 0.0, rtol=1e-6)\n@test isapprox(value(y[2]), 1.0, rtol=1e-6)\n@test isapprox(value(y[3]), 0.0, rtol=1e-6)\n@test isapprox(objective_value(m), 6.00975890893, rtol=1e-6)\n\nend # module\n", "meta": {"hexsha": "26bc5799c20445853c6d84931cece7f19deec2eb", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/minlp.jl", "max_stars_repo_name": "ericphanson/BARON.jl", "max_stars_repo_head_hexsha": "1188123f830b83017f3757f5f0ffde5ce59a81fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-10-28T10:10:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T20:43:37.000Z", "max_issues_repo_path": "test/minlp.jl", "max_issues_repo_name": "ericphanson/BARON.jl", "max_issues_repo_head_hexsha": "1188123f830b83017f3757f5f0ffde5ce59a81fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2015-01-20T20:14:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T19:50:14.000Z", "max_forks_repo_path": "test/minlp.jl", "max_forks_repo_name": "jump-dev/BARON.jl", "max_forks_repo_head_hexsha": "d052dc01551198d27ab201221e8ace0b452f2096", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-08-25T10:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:07:42.000Z", "avg_line_length": 26.9696969697, "max_line_length": 77, "alphanum_fraction": 0.5337078652, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7773743133278069}}
{"text": "using Test\n\n\"\nFunction shootingmethod() for 2nd order BVP ODEs.\n\nArguments to shootingmethod(f, bvs, initg, steps, tol, limit):\n\nf::Function           : Function to be estimated (see below).\\n\nbvs::Vector{Float64}  : Vector of boundary values [xa, ya, xb, yb].\\n\ninitg::Matrix{Float64}: Vector of nitial gradients [a0, a1].\\n\nsteps::Int64          : Number of calculations steps.\\n\ntol::Float64          : Tolerance for convergence.\\n\nlimit::Int64          : Max number of iterations.\n\nExample of how to define the function f(x, y) for y'' = 3x^3+4y:\n\nDecompose in two first order equations:\n\ndy[1] = y[2]\\n\ndy[2] = 3x^3 + 4y[1]\n\n```\nfunction f(x::Float64, y::Vector{Float64})\n  [y[2], 3x^3 +4y[1]]\nend\n```\n\"\nfunction shootingmethod(f::Function, bvs::Vector{Float64}, initg::Vector{Float64}, \n  steps::Int64, tol::Float64=0.00001, limit::Int64=25)\n  #println(\"\\n--- Shooting method for Second Order ODEs ---\\n\")\n  @test size(bvs, 1) == 4\n  @test size(initg, 1) == 2\n  nsteps = steps + 1\n  y0 = zeros(Float64, nsteps, 2)\n  ystar = zeros(Float64, nsteps)\n  y = zeros(Float64, 2)\n  (xa, ya, xb, yb) = bvs[:, 1]\n  a0 = initg[:, 1]\n  h = (xb - xa)/steps\n  res = zeros(Float64, nsteps, 2)\n  for j in 1:2\n    x = xa\n    y[1] = ya\n    y[2] = a0[j]\n    for i in 1:nsteps\n      y0[i, j] = y[1]\n      k0 = h * f(x, y)\n      k1 = h * f(x+h/2, y+k0/2)\n      k2 = h * f(x+h/2, y+k1/2)\n      k3 = h * f(x+h, y+k2)\n      y += (k0+2k1+2k2+k3)/6\n      x = x + h\n    end\n  end\n  if (y0[nsteps,1]-yb)*(y0[nsteps,2]-yb) > 0.0\n    println(\"Try new gradients ... ?\")\n    converged = abs((ystar[nsteps]-yb)/yb) < tol\n    return((0, nsteps, converged, res))\n  end\n  iter = 0\n  while iter <= limit\n    iter += 1\n    if iter > limit\n      println(\"Max number of iterations exceeded ...\")\n      println(\"Iterations performed: $iter\")\n      for i in 1:nsteps\n        res[i,:] = [xa+(i-1)*h ystar[i]]\n      end\n      println(\"Try new gradients ... ?\")\n      converged = abs((ystar[nsteps]-yb)/yb) < tol\n      return((iter, nsteps, converged, res))\n    end\n    astar = a0[1] + (yb-y0[nsteps, 1])*(a0[2]-a0[1])/(y0[nsteps,2])\n    x = xa\n    y[1] = ya\n    y[2] = astar\n    for i in 1:nsteps\n      ystar[i] = y[1]\n      k0 = h * f(x, y)\n      k1 = h * f(x+h/2, y+k0/2)\n      k2 = h * f(x+h/2, y+k1/2)\n      k3 = h * f(x+h, y+k2)\n      y += (k0+2k1+2k2+k3)/6\n      x = x + h\n    end\n    if abs((ystar[nsteps]-yb)/yb) < tol\n      #println(\"Iterations to convergence: $iter\")\n      for i in 1:nsteps\n        res[i,:] = [xa+(i-1)*h ystar[i]]\n      end\n      break\n    end\n    if (ystar[nsteps]-yb)*(y0[nsteps, 1]-yb) > 0.0\n      y0[:, 1] = ystar\n      a0[1] = astar\n    else\n      y0[:, 2] = ystar\n      a0[2] = astar\n    end\n  end\n  converged = abs((ystar[nsteps]-yb)/yb) < tol\n  (iter, nsteps, converged, res)\nend\n", "meta": {"hexsha": "b8285c2e3714c073223b44d52fbcc817f52a5640", "size": 2778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ch07/bvp.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/ch07/bvp.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/ch07/bvp.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": 26.7115384615, "max_line_length": 83, "alphanum_fraction": 0.5467962563, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7773525472790189}}
{"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(\"\u03b2[\" * string(country) * \"]\"), Symbol(\"\u03b3[\" * 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) \u2265 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 \u2264 (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 \u2264 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 \u2264 (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(\u2248), instead of exact equal (==), should be considered\n    sum(probs) \u2248 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 \u03b1 and \u03b2 is given accordingly. (default to\n  false)\n\n* `\u03b1::AbstractVector` : Place-dependent probility coefficient(defaults to nothing)\n\n* `\u03b2::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 `\u03b1` and `\u03b2` where p(x) = \u03b1 x + \u03b2.\n\"\"\"\nfunction randalg(ifs, initset; numiter=100, numtransient=10, parallel=false, placedependent=false, \u03b1=nothing, \u03b2=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, \u03b1, \u03b2, allocated)\n            set = randalg_parallel_pd(ws, transient, numiter, probs, \u03b1, \u03b2, 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, \u03b1, \u03b2, 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, \u03f5 = 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    \u03c3, index = findmax(contfactor.(ws))\n    if num_iter === nothing\n        # Compute num_iter with respect to \u03f5\n        x1 = ws[index](xinit)\n        _k = (log(\u03f5) - log(norm(x1 - xinit))) / log(\u03c3) + 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#     \u03c3 = zeros(lenght(ws))\n#     for i, transformation in ws\n#         \u03c3[i] = norm(transformation.A, inf)\n#     end\n#     # TODO : Returns nothing\n#     \u03c3\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, \u03b1, \u03b2, 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 = \u03b1 * xi + \u03b2\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, \u03b1, \u03b2)\n    loadprocs()\n    vcat(pmap(process_chunk_pd, [(ws, set, floor(Int, numiter / nworkers()), probs, \u03b1, \u03b2) 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, \u03b1, \u03b2 = 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 = \u03b1 * xi + \u03b2\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 \u2264 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 \u2264 x \u2264 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] = \u039b(r)(x[i]), where\n\t\t\t\u039b(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\"\u039b(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(\u039b(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(\u039b(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: \u039b(r)(x) == x.\n\t\t\n\t\tWhat was the limit point of the motion \u039b(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 \u039b(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 \u039b(1.5)?\n\t\t\"\"\",\n\t\t\"You can work it out for yourself by solving the equation \u039b(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 \u039b(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 \u039b(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\u039b(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 \u039b(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 \u039b(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\u039b(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 \u039b(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 \u039b(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 \u039b(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(\u039b(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 \u039b(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 \u039b(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 \u039b(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 \u039b(3.7) for the different starting conditions x0 \u2208 [0.5,0.50001,4.99999]\n\n\t\t\tlines(nestlist(\u039b(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\u00e9 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 \u03b3 = 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\u2207f(x) = ForwardDiff.gradient(f, x)\n\u2207\u00b2f(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 = \u2207f(x)\n        println(\"x:  $x\")\n        println(\"grad norm: $(norm(grad))\")\n        norm(grad) < 1.0e-3 && break\n\n        hess = \u2207\u00b2f(x)\n        # \u0394 = hess \\ grad\n        \u0394 = grad\n\n        \u03b1 = 1.0\n        iter = 1\n        while norm(\u2207f(x - \u03b1 * \u0394)) > norm(grad) && iter < 100\n            \u03b1 *= 0.5\n            iter += 1\n        end\n\n        x .-= \u03b1 * \u0394\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(\u03b8)^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\u00fcrzen ergibt sich ein Grad von l-deg fuer r\n\t\tpush!(tout,(x^2+y^2+z^2)^div(degR,2)*t) # r\u00b2 wird durch x\u00b2+y\u00b2+z\u00b2 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 \u2211\u1d62 2\u2071\u207b\u00b9y\u1d62.\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(\u03bc, X) = (mean(X) - \u03bc)/\u221a(var(X) / length(X))\npvalue(\u03bc, X) = 2ccdf(TDist(length(X) - 1), abs(tstat(\u03bc, X)))\n\nfunction ci(X, \u03b1)\n    X\u0304 = mean(X)\n    c = quantile(TDist(length(X) - 1), 1 - \u03b1/2)\n    d = \u221a(var(X) / length(X))\n    X\u0304 - c*d, X\u0304 + c*d\nend\n\nisininterval(x, int) = first(int) \u2264 x \u2264 last(int)\nisinci(\u03bc, X, \u03b1) = isininterval(\u03bc, ci(X, \u03b1))\n\nprob_trueisinci(dist, n, \u03b1; L=10^6) = mean(isinci(mean(dist), rand(dist, n), \u03b1) 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\u03bc, \u03c3\u00b2 = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - \u03bc)/\u221a(\u03c3\u00b2/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\u03bc, \u03c3\u00b2 = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - \u03bc)/\u221a(\u03c3\u00b2/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\u03bc, \u03c3\u00b2 = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - \u03bc)/\u221a(\u03c3\u00b2/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\u03bc, \u03c3\u00b2 = mean(model), var(model)\nPP = []\nfor n in (5, 10, 20, 100)\n    Z = [(mean(rand(model, n)) - \u03bc)/\u221a(\u03c3\u00b2/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    \u03bcs = mean.(xs)\n    vs = var.(xs)\n    return combined_mean_and_var(ns, \u03bcs, vs)\nend\n\nexport combined_mean_and_var\n\n\n\n\n\"\"\"\n    combined_mean_and_var(ns, \u03bcs, vs) -> meanc, varc\nGiven N samples characterized by their lengths `ns`,\ntheir means `\u03bcs`, 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                               \u03bcs::AbstractVector{<:Number},\n                               vs::AbstractVector{<:Number})\n    nsum = sum(ns)\n    meanc = dot(ns, \u03bcs) / nsum\n    varc = sum((ns .- 1) .* vs + ns .* abs2.(\u03bcs .- meanc)) / (nsum - 1)\n    return meanc, varc\nend\n\n\nfunction combined_mean_and_var(ns::AbstractVector{<:Integer},\n                               \u03bcs::AbstractVector{<:AbstractArray{<:Number}},\n                               vs::AbstractVector{<:AbstractArray{<:Number}})\n    meanc = zero(\u03bcs[1])\n    varc = zero(vs[1])\n\n    nsum = sum(ns)\n    N = length(\u03bcs) # number of samples\n    for i in eachindex(meanc)\n\n        for k in 1:N\n            meanc[i] += ns[k] * \u03bcs[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(\u03bcs[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    \u03bc1, \u03bc2 = mean(x1), mean(x2)\n    v1, v2 = var(x1), var(x2)\n    return combined_mean_and_var(n1, \u03bc1, v1, n2, \u03bc2, v2)\nend\n\n\n\"\"\"\n    combined_mean_and_var(n1, \u03bc1, v1, n2, \u03bc2, v2) -> meanc, varc\nGiven two samples characterized by their lengths `n1`, `n2`, \ntheir means `\u03bc1`, `\u03bc2`, 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, \u03bc1::Number, v1::Number,\n                               n2::Integer, \u03bc2::Number, v2::Number)\n    meanc = (n1 * \u03bc1 + n2 * \u03bc2) / (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(\u03bc1 - meanc) + n2*abs2(\u03bc2 - 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    \u03bc1, \u03bc2, \u03bc3 = 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, \u03bc1, v1, n2, \u03bc2, v2)\n    n12 = n1 + n2\n    return combined_mean_and_var(n12, meanc12, varc12, n3, \u03bc3, 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    \u03bcs = [r.mean for r in ors]\n    vs = [r.error^2 for r in ors]\n\n    meanc, varc = combined_mean_and_var(ns, \u03bcs, 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": "function fib(x, y)\n  return y, x+y\nend\na, b, s = 1, 1, 0\nwhile a+b < 4000_000\n  global a, b, s\n  a, b = fib(a, b)\n  if iseven(b)\n    s += b\n  end\nend\nprintln(s)\n", "meta": {"hexsha": "c2c95cb26e648a0bfaa228548b2883c363f66c5e", "size": 161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ans2.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": "ans2.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": "ans2.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": 12.3846153846, "max_line_length": 20, "alphanum_fraction": 0.5403726708, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7770860003224486}}
{"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\u00e9rateurs  classiques : +-*/\\\n\n1 + 3\n3 / 7\n3 \\ 7 # \u2248 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\u00e9triques usuelles : sin, cos, tan, cot, sec, csc, sinh, cosh, tanh, coth, sech, csch, asin, acos, atan...\n\n\nsin(\u03c0+\u221a2) # 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\u00e9e en 32/64 bits en fonction de l'architecture machine\ntypeof(3 + 5) \n3. * 4. # nombre en virgule flottante stock\u00e9e en 32/64 bits en fonction de l'architecture machine\ntypeof(3. * 4.)\ntypeof(3. * 4)\ntypeof(Float64)\n\u03c0 # tapez \"\\pi<tab>\"\ntypeof(\u03c0)\nFloat64(\u03c0)\nFloat32(\u03c0)\ntypeof(1 + 2im)\n[1,2,3]\ntypeof([1,2,3])\n1:5 # it\u00e9rateur\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\u00e8res et cha\u00eenes de caract\u00e8res\n\n'A'\ntypeof('A')\n\"hello\" \n\ntypeof(\"hello\")\n\n\"racine carr\u00e9e de 2 : $(sqrt(2))\"\n\n\" \u221a3 : $(\u221a3)\" \n\n\"Hello\" * \" John Doe\"\n\n# Bol\u00e9ens et op\u00e9rateurs 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\u00e9thodes, modules, types, macros)\n# =============================================================================\n#= \n- noms des variables  en minuscule, la s\u00e9paration des mots dans une variable se fait \u00e0 l'aide d'un underscore ('_') (\"snake case\")\n- noms de type et de modules commencent par une lettre majuscule, les majuscules s\u00e9parant les diff\u00e9rents 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'\u00e9crit avec ! \u00e0 la fin. =#\n\n\n# =============================================================================\n# VARIABLES (\u00e9tiquettes associ\u00e9es aux valeurs)\n# =============================================================================\n\n# Les variables contenant des nombres scalaires\n\n\u03b1 = 6 # variable latex-unicode  names \u2014 tapez \"\\alpha<tab>\"\ntypeof(\u03b1)\n\u03b2 = 2\u03b1 + 1.5\ntypeof(\u03b2)\n\u03b3 = \u03b1 + \u03b2 * im\ntypeof(\u03b3)\n\u03b4 = Float64(10)\n\u03b4 = MyComplex(1, 2)\n\u03b4._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\u00e8s \u00e0 l'\u00e9l\u00e9ment d'index n\u00b02 (indice de d\u00e9part = 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\u00e9e de x\nv2 = Float64[1, 2, 3, 4]\nv + v2\nv' * v2\nsin.(v) # op\u00e9rateur . de broadcast ( sin de chaque terme)\nv .* v2 # op\u00e9rateur . de broadcast (ici multiplication terme \u00e0 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\u00e9nation horizontale par bloc (hcat)\nAAAA = [AA;AA] # concat\u00e9nation 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 \u2260 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\u00e8bre lin\u00e9aire\n# D\u00e9terminant, 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\u00e9solution du syst\u00e8me lin\u00e9aire Ax=b\nxx = inv(A) * b # r\u00e9solution du syst\u00e8me lin\u00e9aire Ax=b\nx - xx\n\n\n# =============================================================================\n# Fonctions, M\u00e9thodes, Compilation, Sp\u00e9cialisation, Multiple Dispatch\n# =============================================================================\n\n# Version longue\n\nfunction fun_name(arg1, arg2)\n    tmp = arg1 + arg2\n    return tmp * arg1          # <- le mot-cl\u00e9 return est optionnel, la derni\u00e8re valeur calcul\u00e9e est retourn\u00e9e\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\u00e9rentes impl\u00e9mentations (m\u00e9thodes) 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(\u03c0)\nf(1)\nf(im, 2)\nf(\u03c0, [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'\u00e9l\u00e9ment 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\u00e9cution de la fonction  my_sum avec argument de type vecteur (sp\u00e9cialisation)\n@time my_sum(V) # Ex\u00e9cution 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\u00e9cution de la fonction  my_sum avec argument de type UnitRange (sp\u00e9cialisation)\n@time my_sum(UR)\n@time my_sum(UR)\n\n@code_native debuginfo = :none my_sum(UR) # code natif diff\u00e9rent du pr\u00e9c\u00e9dent  avec m\u00eame impl\u00e9mnetation => sp\u00e9cialisation\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\u03c0/100:2\u03c0\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\u00e9es \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\u00e8le 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, \u03b8 = symbols(\"E S L \u03b8\",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(\u03b8) sin(\u03b8) 0 0; -sin(\u03b8) cos(\u03b8) 0 0; 0 0 cos(\u03b8) sin(\u03b8); 0 0 -sin(\u03b8) cos(\u03b8)]\nKe=Re'*ke*Re\n\n# using Pkg; Pkg.add(\"Symbolics\");Pkg.add(\"SymbolicUtils\")\nusing Symbolics\n\n@variables E\u2091 S\u2091 L\u2091 \u03b8\u2091\nk\u2091 = E\u2091 * S\u2091 / L\u2091 * [1 0 -1 0;0 0 0 0;-1 0 1 0;0 0 0 0 ]\nR\u2091 = [cos(\u03b8\u2091) sin(\u03b8\u2091) 0 0; -sin(\u03b8\u2091) cos(\u03b8\u2091) 0 0; 0 0 cos(\u03b8\u2091) sin(\u03b8\u2091); 0 0 -sin(\u03b8\u2091) cos(\u03b8\u2091)]\nK\u2091 = R\u2091' * k\u2091 * R\u2091", "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    \u0394x::DT\n    xgrid::Vector{DT}\n    \u03c1::Vector{DT}\n    \u03d5::Vector{DT}\n\n    function PoissonSolver{DT}(nx::Int) where {DT}\n        \u0394x = 1/nx\n        xgrid = collect(0:\u0394x:1)\n        new(nx, \u0394x, 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.\u03c1 .= h.weights ./ length(x)\n    \u03c1\u0302 = rfft(p.\u03c1)\n    k\u00b2 = [(i-1)^2 for i in eachindex(\u03c1\u0302)]\n    \u03d5\u0302 = - \u03c1\u0302 ./ k\u00b2\n    \u03d5\u0302[1] = 0\n    p.\u03d5 .= irfft(\u03d5\u0302, length(p.\u03c1))\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.\u0394x) + 1\n    i2 = mod( ceil(Int, y / p.\u0394x), p.nx) + 1\n    i1 == i2 && (i1 = i1-1)\n    i1 == 0 && (i1 = lastindex(p.\u03d5))\n    return - (p.\u03d5[i2] - p.\u03d5[i1]) / p.\u0394x\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": "using SpecialPolynomials;\nconst SP = SpecialPolynomials;\nusing Polynomials\nimport LinearAlgebra: eigvals, det, dot, norm\nimport SpecialFunctions: gamma\nusing Test\n\n@testset \"Orthogonal\" begin\n    include(\"Orthogonal.jl\")\nend\n@testset \"Orthogonal compare with tables\" begin\n    include(\"Orthogonal-compare.jl\")\nend\n#@testset \"ChebyshevT\" begin include(\"ChebyshevT.jl\") end\n#@testset \"ChebyshevU\" begin include(\"ChebyshevU.jl\") end\n#@testset \"Laguerre{\u03b1}\" begin include(\"GeneralizedLaguerre.jl\") end\n#@testset \"Gegenbauer{\u03b1}\" begin include(\"Gegenbauer.jl\") end\n\n@testset \"Lagrange\" begin\n    include(\"Lagrange.jl\")\nend\n@testset \"Newton\" begin\n    include(\"Newton.jl\")\nend\n\n@testset \"Bernstein\" begin\n    include(\"Bernstein.jl\")\nend\n", "meta": {"hexsha": "f3056c18144b93857e881a209a6bea445c3ede11", "size": 730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jishnub/SpecialPolynomials.jl", "max_stars_repo_head_hexsha": "8401241bbcd82d65d48d495a3aa59ab8daea1f97", "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": "test/runtests.jl", "max_issues_repo_name": "jishnub/SpecialPolynomials.jl", "max_issues_repo_head_hexsha": "8401241bbcd82d65d48d495a3aa59ab8daea1f97", "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": "test/runtests.jl", "max_forks_repo_name": "jishnub/SpecialPolynomials.jl", "max_forks_repo_head_hexsha": "8401241bbcd82d65d48d495a3aa59ab8daea1f97", "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": 25.1724137931, "max_line_length": 67, "alphanum_fraction": 0.7547945205, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7770609137819556}}
{"text": "##---begin-Plot-functions---------------------------------------------------------------------------\n\"\"\"\n    chromatogram(t, tR, \u03c4R)\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 `\u03c4R`.    \n\"\"\"\nfunction chromatogram(t::Array{Float64,1}, tR::Array{Float64,1}, \u03c4R::Array{Float64,1})\n\tg(t,tR,\u03c4R) = 1/sqrt(2*\u03c0*\u03c4R^2)*exp(-(t-tR)^2/(2*\u03c4R^2))\n\tchromatograms = Array{Array{Float64,1}}(undef, length(tR))\n\tfor j=1:length(tR)\n\t\tchromatograms[j] = g.(t, tR[j], \u03c4R[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\u2080 = tlims[1]\n\ttMax = tlims[2]\n\tt = t\u2080: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.\u03c4R) .+ offset\n\tchrom_tR = sgn.*chromatogram(peaklist.tR, peaklist.tR, peaklist.\u03c4R) .+ 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\u2080=0.0, annotation=true, number=true, mirror=false, offset=0.0)\n\tt\u2080 = tlims[1]\n\ttMax = tlims[2]\n\tt = t\u2080: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.\u03c4R) .+ offset\n\tchrom_tR = sgn.*chromatogram(peaklist.tR, peaklist.tR, peaklist.\u03c4R) .+ 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 \u00b0C\", 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 \u00b0C\", 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 \u00b0C\")\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  \"\u03c4\", \"\u03c3\" and \"u\".\n* `yy`: Selected quantity shown on the y-axis. Possible values: \"z\", \"t\", \"T\",\n  \"\u03c4\", \"\u03c3\" 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 \u00b0C\"\n\t\telseif xx==\"\u03c4\"\n\t\t\txvalues[i] = sqrt.(df_sol.\u03c4\u00b2[i])\n\t\t\txlabel = \"peak width \u03c4 in s\"\n\t\telseif xx==\"\u03c3\"\n\t\t\txvalues[i] = velocity(df_sol, i, par).*sqrt.(df_sol.\u03c4\u00b2[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 \u00b0C\"\n\t\telseif yy==\"\u03c4\"\n\t\t\tyvalues[i] = sqrt.(df_sol.\u03c4\u00b2[i])\n\t\t\tylabel = \"peak width in s\"\n\t\telseif yy==\"\u03c3\"\n\t\t\tyvalues[i] = velocity(df_sol, i, par).*sqrt.(df_sol.\u03c4\u00b2[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\u0394Cp = par.sub[i].\u0394Cp\n\tTchar = par.sub[i].Tchar\n\t\u03b8char = par.sub[i].\u03b8char\n\t\u03c6\u2080 = par.sub[i].\u03c6\u2080\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, \u0394Cp, Tchar, \u03b8char, \u03c6\u2080; 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\u1d62)^2 for x\u1d62 \u2208 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 \u2a75 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 \u03b1, x, f(), g()\n(\u03b1, x, f, g)\n\njulia> \u2202 = Differential(x)\nDifferential(x)\n\njulia> eqn = \u2202(f(x)) ~ \u03b1 * x\nd\n\u2500\u2500(f(x)) = x\u22c5\u03b1\ndx\n```\n\n```julia\njulia> dsolve(eqn)\n             2\n            x \u22c5\u03b1\nf(x) = C\u2081 + \u2500\u2500\u2500\u2500\n             2\n```\n\n```jldoctest dsolve\njulia> dsolve(eqn(\u03b1=>2); ics=Dict(f(0)=>1)) |> print # fill in parameter, initial condition\nEq(f(x), x^2 + 1)\n\njulia> eqn = \u2202(\u2202(f(x))) ~ -f(x); print(eqn)\nEq(Derivative(f(x), (x, 2)), -f(x))\n\njulia> dsolve(eqn)\nf(x) = C\u2081\u22c5sin(x) + C\u2082\u22c5cos(x)\n\njulia> dsolve(eqn; ics = Dict(f(0)=>1, \u2202(f)(0) => -1))\nf(x) = -sin(x) + cos(x)\n\njulia> eqn = \u2202(\u2202(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> \u2202 = Differential(t)\nDifferential(t)\n\njulia> eqns = [\u2202(x(t)) ~ y(t), \u2202(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 = [\u2202(\u2202(x(t))) ~ 0, \u2202(\u2202(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\u2081 + C\u2082\u22c5t\n Eq(y(t), C3 + C4*t - g*t^2/2)\n\njulia> @syms t x() y()\n(t, x, y)\n\njulia> eq = (\u2202(x)(t) ~ x(t)*y(t)*sin(t), \u2202(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\u2080, u\u2080)`, to specify initial conditions is deprecated. Use a dictionary: `ics=Dict(u(x\u2080) => u\u2080)`.\", :_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\u03b11 = 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 + \u03b11[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 + \u03b11[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 \u2202x!(dudx::AbstractMatrix,u::AbstractMatrix)\n    m,n = size(dudx)\n    @boundscheck (m+1,n) == size(u) || throw(BoundsError())\n\n    @inbounds for j \u2208 1:n\n        for i \u2208 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 \u2202y!(dudy::AbstractMatrix,u::AbstractMatrix)\n    m,n = size(dudy)\n    @boundscheck (m,n+1) == size(u) || throw(BoundsError())\n\n    @inbounds for j \u2208 1:n\n        for i \u2208 1:m\n            dudy[i,j] = u[i,j+1] - u[i,j]\n        end\n    end\nend\n\n\"\"\" \u2207\u00b2 is the 2nd order centred Laplace-operator \u2202/\u2202x^2 + \u2202/\u2202y^2.\nThe 1/\u0394\u00b2-factor is omitted and moved into the viscosity coefficient.\"\"\"\nfunction \u2207\u00b2!(du::AbstractMatrix,u::AbstractMatrix)\n    m, n = size(du)\n    @boundscheck (m+2,n+2) == size(u) || throw(BoundsError())\n\n    @inbounds for i \u2208 1:n\n        for j \u2208 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": "module PoissonTests\n\nusing Gridap\nusing Gridap.Algebra\nusing Gridap.FESpaces\nusing GridapDistributed\nusing PartitionedArrays\nusing Test\n\nfunction main(parts)\n\n  output = mkpath(joinpath(@__DIR__,\"output\"))\n\n  domain = (0,4,0,4)\n  cells = (4,4)\n  model = CartesianDiscreteModel(parts,domain,cells)\n\n  labels = get_face_labeling(model)\n  add_tag_from_tags!(labels,\"dirichlet\",[1,2,3,5,7])\n  add_tag_from_tags!(labels,\"neumann\",[4,6,8])\n\n  \u03a9 = Triangulation(model)\n  \u0393n = Boundary(model,tags=\"neumann\")\n  n_\u0393n = get_normal_vector(\u0393n)\n\n  k = 2\n  u((x,y)) = (x+y)^k\n  f(x) = -\u0394(u,x)\n  g = n_\u0393n\u22c5\u2207(u)\n\n  reffe = ReferenceFE(lagrangian,Float64,k)\n  V = TestFESpace(model,reffe,dirichlet_tags=\"dirichlet\")\n  U = TrialFESpace(u,V)\n\n  d\u03a9 = Measure(\u03a9,2*k)\n  d\u0393n = Measure(\u0393n,2*k)\n\n  a(u,v) = \u222b( \u2207(v)\u22c5\u2207(u) )d\u03a9\n  l(v) = \u222b( v*f )d\u03a9 + \u222b( v*g )d\u0393n\n  op = AffineFEOperator(a,l,U,V)\n\n  uh = solve(op)\n  eh = u - uh\n  @test sqrt(sum( \u222b(abs2(eh))d\u03a9 )) < 1.0e-9\n\n  # Now with DG\n  h = 2\n  \u03b3 = 10\n\n  V_dg = FESpace(model,reffe,conformity=:L2)\n\n  \u039b = Skeleton(model)\n  \u0393d = Boundary(model,tags=\"dirichlet\")\n\n  d\u039b = Measure(\u039b,2*k)\n  d\u0393d = Measure(\u0393d,2*k)\n\n  n_\u0393d = get_normal_vector(\u0393d)\n  n_\u039b = get_normal_vector(\u039b)\n\n  a_dg(u,v) =\n    \u222b( \u2207(v)\u22c5\u2207(u) )*d\u03a9 +\n    \u222b( (\u03b3/h)*v*u  - v*(n_\u0393d\u22c5\u2207(u)) - (n_\u0393d\u22c5\u2207(v))*u )*d\u0393d +\n    \u222b( (\u03b3/h)*jump(v*n_\u039b)\u22c5jump(u*n_\u039b) -\n       jump(v*n_\u039b)\u22c5mean(\u2207(u)) -\n       mean(\u2207(v))\u22c5jump(u*n_\u039b) )*d\u039b\n  \n  l_dg(v) =\n    \u222b( v*f )*d\u03a9 +\n    \u222b( v*g )d\u0393n +\n    \u222b( (\u03b3/h)*v*u - (n_\u0393d\u22c5\u2207(v))*u )*d\u0393d\n\n  op = AffineFEOperator(a_dg,l_dg,V_dg,V_dg)\n  uh = solve(op)\n  eh = u - uh\n  @test sqrt(sum( \u222b(abs2(eh))d\u03a9 )) < 1.0e-9\n\nend\n\nend # module\n", "meta": {"hexsha": "ea26c8f50ffbb828c66548b506c5039e28d61c1e", "size": 1624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/PoissonTests.jl", "max_stars_repo_name": "gridap/GridapDistributed.jl", "max_stars_repo_head_hexsha": "7bc90bfb6a92d3f609ba1b208329610a27b03209", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2020-04-25T17:20:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T19:54:45.000Z", "max_issues_repo_path": "test/PoissonTests.jl", "max_issues_repo_name": "gridap/GridapDistributed.jl", "max_issues_repo_head_hexsha": "7bc90bfb6a92d3f609ba1b208329610a27b03209", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2020-04-28T11:08:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:13:29.000Z", "max_forks_repo_path": "test/PoissonTests.jl", "max_forks_repo_name": "gridap/GridapDistributed.jl", "max_forks_repo_head_hexsha": "7bc90bfb6a92d3f609ba1b208329610a27b03209", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-12T14:17:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T07:37:31.000Z", "avg_line_length": 20.049382716, "max_line_length": 57, "alphanum_fraction": 0.5880541872, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7770374549420945}}
{"text": "\"\"\"\n    GaussianLikelihood(\u03c3\u00b2)\n\nGaussian likelihood with `\u03c3\u00b2` 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, \u03c3\u00b2)\n```\nOn calling, this would return a normal distribution with mean `f` and variance \u03c3\u00b2.\n\"\"\"\nstruct GaussianLikelihood{T<:Real}\n    \u03c3\u00b2::Vector{T}\nend\n\nGaussianLikelihood() = GaussianLikelihood(1e-6)\n\nGaussianLikelihood(\u03c3\u00b2::Real) = GaussianLikelihood([\u03c3\u00b2])\n\n@functor GaussianLikelihood\n\n(l::GaussianLikelihood)(f::Real) = Normal(f, sqrt(first(l.\u03c3\u00b2)))\n\n(l::GaussianLikelihood)(fs::AbstractVector{<:Real}) = MvNormal(fs, first(l.\u03c3\u00b2) * 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 \u2018se3mat\u2019 (an element of Lie Algebra se3)\r\n# from given twist vector (= 6x1 vector) \u2018xi\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 \u2018xi\u2019 from given twist matrix \u2018se3mat\u2019\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 \u2018R\u2019 by\r\n# evaluating matrix exponential of 3x3 skew symmetric matrix \u2018so3mat\u2019\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 \u2018g\u2019 by\r\n# evaluating matrix exponential of 4x4 twist matrix \u2018se3mat\u2019\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 \u2018so3mat\u2019\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 \u2018se3mat\u2019\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(\u03bb::Real=1.0)\n\nReturns the function `\u03bb\u2211\u03c3_i(X)`, where `\u03c3_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 \u03bb 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 \u21a6 \u03bb\u2211\u03c3_i(X)\"\nfun_params(f::NuclearNorm) = \"\u03bb = $(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_\u03b3, fS_\u03b3 =  prox(ftemp,S,f.lambda*gamma)\n  Y = U * diagm(S_\u03b3) * V'\n  return Y, f.lambda * sum(S_\u03b3)\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    (\u03b2,c,\u03b3,\u03b4t) = 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*\u03b4t))\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() < \u03b2\n                    du[i] = Infected\n                    break\n                end\n                ncontacts -= 1\n            end\n        # If infected\n        else u[i]==Infected\n            if rand() < \u03b3\n                du[i] = Recovered\n            end\n        end\n    end\n    nothing\nend;\n\n\n\u03b4t = 0.1\ntf = 40.0\ntspan = (0.0,tf);\n\n\n\u03b2 = 0.05\nc = 10.0\n\u03b3 = rate_to_proportion(0.25,\u03b4t)\np = [\u03b2,c,\u03b3,\u03b4t];\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:\u03b4t:tf);\n\n\nprob_abm = DiscreteProblem(sir_abm!,u0,tspan,p);\n\n\nsol_abm = solve(prob_abm,\n    solver = FunctionMap(),\n    dt = \u03b4t,\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=\u03b4t,\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": "using CalculusWithJulia\nusing Test\n\n## test package\n@testset \"test packages\" begin\n\n    ## Roots\n    @test fzero(sin, 3, 4)  \u2248 pi\n    @test fzero(sin, 3.0)  \u2248 pi\n\n    ## ForwardDiff\n    f(x) = sin(x)\n    @test f'(2)  \u2248 cos(2)\n    @test f''(2)  \u2248 -sin(2)\n\n    ## QuadGK\n    @test quadgk(sin, 0, pi)[1]  \u2248 2\n    @test abs(quadgk(x -> x^2, 0, 1)[2]) <= 1e-14\n\n    ## HQuadrature\n    @test hquadrature(x -> 2, (0.0, 0.0), (2pi, 1pi))[1]  \u2248 2 * (2pi) * (1pi)\n\n    ## SymPy\n    @test limit(x -> sin(x)/x, 0) == 1\n    @test integrate(sin,  0, pi) == 2\n\n\n\nend\n\n\n\n@testset \"multidimensional\" begin\n\n    x = [[1,2,3], [4,5,6]]\n    @test unzip(x)[1] == [1, 4]\n    @test unzip(x)[2] == [2, 5]\n    @test unzip(x)[3] == [3, 6]\n\n    xs = [1,2,3]\n    ys = [1,2]\n    M = ((x,y) -> (x,y)).(xs, ys')\n    @test unzip(M, recursive=true)  == ([[1,2,3], [1,2,3]], [[1,1,1], [2,2,2]])\n\n\n    @vars x y z real=true\n\n    f(x,y,z) = x*y*z\n    f(v) = f(v...)\n    @test gradient(f(x,y,z), [x,y,z]) == [y*z, x*z, x*y]\n    @test \u2207(f)([1,2,3]) \u2248  [2*3, 1*3, 1*2]\n\n    F(x,y,z) = [x,y,z]\n    F(v) = F(v...)\n    @test divergence(F(x,y,z), [x,y,z]) == 3\n    @test  (\u2207\u22c5F)([1,0,0]) \u2248 3\n\n\n    F(x,y,z) = [-y, x, 0]\n    F(v) = F(v...)\n    @test curl(F(x,y,z), [x,y,z]) == [0,0,2]\n    @test all((\u2207 \u00d7 F)([1,2,3]) .\u2248 [0.0, 0.0, 2.0])\n\nend\n\n\n@testset \"derivatives\" begin\n\n    f(x) = x^2\n    @test secant(f, 0, 1)(1/2) \u2248 1/2\n    @test tangent(f, 1/2)(1) \u2248 f(1/2) + 2*(1/2)*(1-1/2)\n\n    @test f'(1) \u2248 2\n    @test f''(1)  \u2248 2\n    @test iszero(f'''(1))\n\n    r(t) = [t, t^2, t^3]\n    @test all(r'(1) .\u2248 [1.0, 2*1, 3*1^2])\nend\n\n@testset \"integration\" begin\n\n    @test quadgk(sin, 0, pi)[1]  \u2248 2\n    @test hcubature(xy -> sin(xy[1])*sin(xy[2]), (0,0), (pi,pi))[1] \u2248 4\n    @test riemann(sin, 0, pi, 10_000)  \u2248 2\n    @test fubini((x,y) -> 1, (x->-sqrt(1-x^2), x->sqrt(1-x^2)), (-1,1)) \u2248 pi\n\n\nend\n\n@testset \"plot-utils\" begin\n\n    if isinteractive()\n\n        pyplot()\n        f(x) = 1/x\n\n        plotif(f, f, -1, 1)\n        plotif(f, f', -1, 1)\n        trimplot(f, -1, 1)\n        signchart(f, -1, 1)\n\n        rr(theta) = cos(theta)\n        plot_polar(rr, 0, 2pi)\n\n        rr(t) = [sin(t), cos(t)]\n        plot_parametric_curve(rr, 0, 2pi)\n        arrow!(rr(2pi), rr'(2pi))\n\n        rr(t) = [sin(t), cos(t), t]\n        plot_parametric_curve(rr, 0, 2pi)\n        arrow!(rr(2pi), rr'(2pi))\n\n        F(u, v) = [u*cos(v), u*sin(v)]\n        us = range(0, 1, length=20)\n        vs = range(0, 2pi, length=20)\n        plot(legend=false)\n        plot!(unzip(F.(us, vs'))...) # constant angle, draws rays\n        plot!(unzip(F.(us', vs))...) # constant radii, draws circles\n\n        pyplot() # surface doesn't work with gr()\n        Phi(u,v) = [u*cos(v), u*sin(v), u]\n        plot_parametric_surface(Phi, xlims=(0, 1), ylims=(0,2pi))\n\n        V(x,y) = [x, x-y]\n        vectorfieldplot(V, xlims=(-2,2))#, nx=8, ny=8) # ylim=(-5,5) plotly not happy, gr is\n\n        V(x,y,z) = [-y, x, 0]\n        vectorfieldplot3d(V, nx=4, ny=4, nz=3)\n\n        a,b = 1, 3\n        F(x,y,z) =  (x^2+((1+b)*y)^2+z^2-1)^3-x^2*z^3-a*y^2*z^3\n        CalculusWithJulia.plot_implicit_surface(F, xlims=(-2,2),ylims=(-1,1),zlims=(-1,2))\n    end\n\nend\n", "meta": {"hexsha": "67a1ae48b9d5043152cda6d2168047ad159b25fb", "size": 3154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 23.0218978102, "max_line_length": 92, "alphanum_fraction": 0.4616360178, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.777036280478889}}
{"text": "@testset \"material\" begin\n\n@testset \"tensorize\" begin\n    @test MaxwellBase.tensorize(3) === SMatrix{3,3,ComplexF64,9}(3,0,0, 0,3,0, 0,0,3)\n    @test MaxwellBase.tensorize([2,4,6]) === SMatrix{3,3,ComplexF64,9}(2,0,0, 0,4,0, 0,0,6)\n    @test MaxwellBase.tensorize([1 4 7; 2 5 8; 3 6 9]) === SMatrix{3,3,ComplexF64,9}(1,2,3,4,5,6,7,8,9)\nend\n\n@testset \"Material\" begin\n    m_nn = Material(\"(num,num)\", \u03b5 = 2, \u03bc = 3)\n    m_vv = Material(\"(vec,vec)\", \u03b5 = [2.1,2.2,2.3], \u03bc = [3.1,3.2,3.3])\n    m_mm = Material(\"(mat,mat)\", \u03b5 = [2 2 2; 2 2 2; 2 2 2], \u03bc = [3 3 3; 3 3 3; 3 3 3])\n\n    @test matparam(m_nn,EE) == diagm(0=>[2,2,2]) && matparam(m_nn,HH) == diagm(0=>[3,3,3]) && string(m_nn) == \"(num,num)\"\n    @test matparam(m_vv,EE) == diagm(0=>[2.1,2.2,2.3]) && matparam(m_vv,HH) == diagm(0=>[3.1,3.2,3.3]) && string(m_vv) == \"(vec,vec)\"\n    @test matparam(m_mm,EE) == fill(2, (3,3)) && matparam(m_mm,HH) == fill(3, (3,3)) && string(m_mm) == \"(mat,mat)\"\nend\n\n@testset \"\u03c4_trans\" begin\n    # Check if \u03c4_trans for a 2\u00d72 matrix is \u03c4_trans for the 3\u00d73 version of the matrix.  The\n    # 3\u00d73 version needs to have the original 2\u00d72 matrix as the top-left 2\u00d72 block, and the\n    # third row and column has the (3,3) entry as the only nonzero entry.\n    \u03b52 = @SMatrix rand(ComplexF64, 2, 2)\n    \u03b53temp = zeros(ComplexF64, 3, 3)\n    \u03b53temp[1:2,1:2] .= \u03b52\n    \u03b53temp[3,3] = rand(ComplexF64)\n    \u03b53 = MaxwellBase.S\u00b2ComplexF3(\u03b53temp)\n\n    \u03c42 = MaxwellBase.\u03c4_trans(\u03b52)\n    \u03c43 = MaxwellBase.\u03c4_trans(\u03b53)\n    @test \u03c43[1:2,1:2] == \u03c42\nend\n\nend  # @testset \"material\"\n", "meta": {"hexsha": "5d7eaf2a47368f4a73ad30e824b7bb278ba2544d", "size": 1538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/material.jl", "max_stars_repo_name": "wsshin/MaxwellBase.jl", "max_stars_repo_head_hexsha": "2397f0d83d989c4e5cc1082f51ae7de84040cd43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-11T10:47:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T18:37:03.000Z", "max_issues_repo_path": "test/material.jl", "max_issues_repo_name": "wsshin/MaxwellBase.jl", "max_issues_repo_head_hexsha": "2397f0d83d989c4e5cc1082f51ae7de84040cd43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-11T00:41:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T02:56:22.000Z", "max_forks_repo_path": "test/material.jl", "max_forks_repo_name": "wsshin/MaxwellBase.jl", "max_forks_repo_head_hexsha": "2397f0d83d989c4e5cc1082f51ae7de84040cd43", "max_forks_repo_licenses": ["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.9428571429, "max_line_length": 133, "alphanum_fraction": 0.5968790637, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7770362785489974}}
{"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    \u03c4::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, \u03c4, q, n, reps) =\n        new(Exponential(a), Exponential(p), \u03c4, 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.\u03c4)\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, \u0394) =\n    push!(s.state.state_chunks,\n          (length(s.state.job_queue), !isnothing(s.state.job), \u0394))\n\nfunction run(a, p, \u03c4, q, n, reps)\n    sc = SharedComputer(a, p, \u03c4, 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 `\u03bc` is equal to the birth rate `\u03bb` and the time `t`\nis equal to `1 / \u03bb`. 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, \u03bb)\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  \u03bb::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  \u03b8 = \u03bb * t\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + (i + j) * log(\u03b8 / (1 + \u03b8)) +\n  log_hypergeometric(a, b, logexpm1(-2 * log(\u03b8)))\nend\n\n\"\"\"\n    logtp_equal_rates_alternating(i, j, t, \u03bb)\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  \u03bb::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  \u03b8 = \u03bb * t\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + (i + j) * log(\u03b8 / (1 + \u03b8)) +\n  log_meixner_ortho_poly(a, b, 2 * log(\u03b8))\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 `\u03bc` is equal to the birth rate `\u03bb`, time `t` is\nequal to `1 / \u03bb`, 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, \u03bb)\n\nEvaluate the logarithm of the probability of extinction for a simple birth and\ndeath process when the death rate `\u03bc` is equal to the birth rate `\u03bb`.\n\"\"\"\n@inline function logtp_equal_rates_extinction(\n  i::I,\n  t::F,\n  \u03bb::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  i * log((\u03bb * t) / (1 + \u03bb * t))\nend\n\n\"\"\"\n    logtp_pure_birth(i, j, t, \u03bb)\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  \u03bb::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  lgamma(j) + (j - i) * logexpm1(\u03bb * t) -\n  (lgamma(i) + lgamma(j - i + 1) + j * \u03bb * t)\nend\n\n\"\"\"\n    logtp_pure_death(i, j, t, \u03bc)\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  \u03bc::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  lgamma(i + 1) + (i - j) * logexpm1(\u03bc * t) -\n  (lgamma(j + 1) + lgamma(i - j + 1) + i * \u03bc * t)\nend\n\n\"\"\"\n    logtp_equal_time(i, j, \u03bb, \u03bc)\n\nEvaluate the logarithm of a transition probability of a simple birth and death\nprocess when the time `t` is equal to `log(\u03bb / \u03bc) / (\u03bb - \u03bc)`. 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  \u03bb::F,\n  \u03bc::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  lgamma(i + j) + i * log(\u03bc) + j * log(\u03bb) -\n  (lgamma(i) + lgamma(j + 1) + (i + j) * log(\u03bb + \u03bc))\nend\n\n\"\"\"\n    logtp_sum(i, j, t, \u03bb, \u03bc)\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  \u03bb::F,\n  \u03bc::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  \u03b8 = (\u03bb - \u03bc) * t\n  \u03c9 = log(\u03bb / \u03bc)\n\n  x = if \u03bb < \u03bc\n    logexpm1(\u03b8 - \u03c9) + log1mexp(\u03b8 + \u03c9) - 2 * log1mexp(\u03b8)\n  else\n    logexpm1(\u03b8 + \u03c9) + log1mexp(\u03b8 - \u03c9) - 2 * logexpm1(\u03b8)\n  end\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + j * \u03c9 +\n  (i + j) * log(expm1(\u03b8) / expm1(\u03b8 + \u03c9)) +\n  log_hypergeometric(a, b, x)\nend\n\n\"\"\"\n    logtp_sum_alternating(i, j, t, \u03bb, \u03bc)\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  \u03bb::F,\n  \u03bc::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  a::F, b::F = (j <= i) ? (i, j) : (j, i)\n\n  \u03b8 = (\u03bb - \u03bc) * t\n  \u03c9 = log(\u03bb / \u03bc)\n\n  x = log(2 * \u03bb * \u03bc) +\n      logexpm1(log1pexp(2 * \u03b8) - (\u03b8 + log(F(2)))) -\n      log((\u03bb - \u03bc)^2)\n\n  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + j * \u03c9 +\n  (i + j) * log(expm1(\u03b8) / expm1(\u03b8 + \u03c9)) +\n  log_meixner_ortho_poly(a, b, x)\nend\n\n\"\"\"\n    logtp_equal_time_extinction(i, t, \u03bb, \u03bc)\n\nEvaluate the logarithm of the probability of extinction for a simple birth and\ndeath process when `t = log(\u03bb / \u03bc) / (\u03bb - \u03bc)`.\n\"\"\"\n@inline function logtp_equal_time_extinction(\n  i::I,\n  \u03bb::F,\n  \u03bc::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  i * log(\u03bc / (\u03bb + \u03bc))\nend\n\n\"\"\"\n    logtp_extinction(i, t, \u03bb, \u03bc)\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  \u03bb::F,\n  \u03bc::F\n)::F where {\n  I <: Integer,\n  F <: AbstractFloat\n}\n  i * log(expm1((\u03bb - \u03bc) * t) / expm1(log(\u03bb / \u03bc) + (\u03bb - \u03bc) * t))\nend\n\n\"\"\"\n    trans_prob(i, j, t, \u03bb, \u03bc; 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 `\u03bb` and the death rate is equal to `\u03bc`.\n\nThe minimum amount of units `i` allowed at time 0 is 1 but `j` is allowed to be\n0. Time `t`, birth rate `\u03bb`, and death rate `\u03bc` cannot be negative.\n\nLet ``\u03b1 = (\u03bc e^{(\u03bb - \u03bc) t} - \u03bc) / (\u03bb e^{(\u03bb - \u03bc) t} - \u03bc)`` and\n``\u03b2 = (\u03bb e^{(\u03bb - \u03bc) t} - \u03bb) / (\u03bb e^{(\u03bb - \u03bc) t} - \u03bc)``. 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\u03b1^{i - h} \u03b2^{j - h} (1 - \u03b1 - \u03b2)^{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  \u03b7::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 \u03b7[1] < 0\n    msg = \"Birth rate '\u03b7[1]' must be greater than or equal to zero.\"\n    throw(DomainError(\u03b7[1], msg))\n  end\n\n  if \u03b7[2] < 0\n    msg = \"Death rate '\u03b7[2]' must be greater than or equal to zero.\"\n    throw(DomainError(\u03b7[2], msg))\n  end\n\n  # promote values to the appropriate float\n  F = float(R)\n  t, \u03bb, \u03bc = F(t), F(\u03b7[1]), F(\u03b7[2])\n  \u03f5 = floatmin(F)\n\n  log_trans_prob::F = if (t < \u03f5) || ((\u03bb < \u03f5) && (\u03bc < \u03f5))\n    if i == j\n      0\n    else\n      -Inf\n    end\n  elseif \u03bb \u2248 \u03bc\n    \u03be = 1 / \u03bb\n\n    if j > 0\n      if t \u2248 \u03be\n        logtp_equal_rates_equal_time(i, j)\n      elseif t < \u03be\n        logtp_equal_rates(i, j, t, \u03bb)\n      else\n        logtp_equal_rates_alternating(i, j, t, \u03bb)\n      end\n    else\n      if t \u2248 \u03be\n        logtp_equal_rates_equal_time_extinction(i)\n      else\n        logtp_equal_rates_extinction(i, t, \u03bb)\n      end\n    end\n  elseif \u03bc < \u03f5\n    if j >= i\n      logtp_pure_birth(i, j, t, \u03bb)\n    else\n      -Inf\n    end\n  elseif \u03bb < \u03f5\n    if j <= i\n      logtp_pure_death(i, j, t, \u03bc)\n    else\n      -Inf\n    end\n  else\n    \u03be = log(\u03bb / \u03bc) / (\u03bb - \u03bc)\n\n    if j > 0\n      if t \u2248 \u03be\n        logtp_equal_time(i, j, \u03bb, \u03bc)\n      elseif t < \u03be\n        logtp_sum(i, j, t, \u03bb, \u03bc)\n      else\n        logtp_sum_alternating(i, j, t, \u03bb, \u03bc)\n      end\n    else\n      if t \u2248 \u03be\n        logtp_equal_time_extinction(i, \u03bb, \u03bc)\n      else\n        logtp_extinction(i, t, \u03bb, \u03bc)\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 = \u00b14 (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, \u03b1=0, \u03b2=0)\nInitialize Gauss-Legendre-Lobatto (GLL) quadrature nodes and weights (x,w)\nto be able to exactly integrate (\u03b1,\u03b2) Jacobi polynomial of given degree\n\"\"\"\nfunction gauss_lobatto_quad(degree, \u03b1=0, \u03b2=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 (\u03b1!=0) && (\u03b2!=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, \u03b1+1, \u03b2+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, \u03b1, \u03b2)\nInitialize Gaussian quadrature nodes and weights (x,w) to be able to exactly\nintegrate Jacobi Polynomial (\u03b1,\u03b2) of given degree\n\"\"\"\nfunction gauss_quad(degree, \u03b1=0, \u03b2=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 = [-(\u03b1-\u03b2)/(\u03b1+\u03b2+2)]\n        w = [2]\n        return x, w\n    end\n\n    J = zeros(p+1, p+1)\n    h\u2081 = @. 2*(0:p)+\u03b1+\u03b2\n    J = diagm(0 => (@. -1/2*(\u03b1^2-\u03b2^2)/(h\u2081+2)/h\u2081), 1 => (@. 2/(h\u2081[1:p]+2)*sqrt((1:p)*((1:p)+\u03b1+\u03b2)*((1:p)+\u03b1)*((1:p)+\u03b2)/(h\u2081[1:p]+1)/(h\u2081[1:p]+3))))\n    if \u03b1+\u03b2<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^(\u03b1+\u03b2+1)/(\u03b1+\u03b2+1)*gamma(\u03b1+1)*gamma(\u03b2+1)/gamma(\u03b1+\u03b2+1)\n    return x[:], w[:]\nend\n\n\"\"\"\n    grad_jacobiP(p, r, \u03b1, \u03b2)\nEvaluate the derivative of Jacobi Polynomial (\u03b1, \u03b2) of order p at nodes r\n\"\"\"\nfunction grad_jacobiP(p, r, \u03b1, \u03b2)\n    dP = zeros(length(r))\n    if p != 0\n        dP = sqrt(p*(p+\u03b1+\u03b2+1))*jacobiP(p-1,r,\u03b1+1,\u03b2+1)\n    end\n    return dP\nend\n\n\"\"\"\n    jacobiP(p, x, \u03b1, \u03b2)\nEvaluate Jacobi Polynomial (\u03b1, \u03b2) of order p at points x\n\"\"\"\nfunction jacobiP(p, x, \u03b1, \u03b2)\n    xp = x\n    if size(xp, 2) == 1\n        xp = transpose(xp)\n    end\n\n    PL = zeros(p+1,length(xp))\n    \u03b3\u2080 = 2^(\u03b1+\u03b2+1)/(\u03b1+\u03b2+1)*gamma(\u03b1+1)*gamma(\u03b2+1)/gamma(\u03b1+\u03b2+1)\n    PL[1,:] .= 1.0/sqrt(\u03b3\u2080)\n    if p == 0\n        P = transpose(PL)\n        return P\n    end\n    \u03b3\u2081 = (\u03b1+1)*(\u03b2+1)/(\u03b1+\u03b2+3)*\u03b3\u2080\n    PL[2,:] = ((\u03b1+\u03b2+2).*xp/2 .+ (\u03b1-\u03b2)/2)/sqrt(\u03b3\u2081)\n    if p == 1\n        P = PL[p+1,:]\n        return P\n    end\n\n    aold = 2/(2+\u03b1+\u03b2)*sqrt((\u03b1+1)*(\u03b2+1)/(\u03b1+\u03b2+3))\n\n    for i = 1:p-1\n        h\u2081 = 2i+\u03b1+\u03b2\n        anew = 2/(h\u2081+2)*sqrt((i+1)*(i+1+\u03b1+\u03b2)*(i+1+\u03b1)*(i+1+\u03b2)/(h\u2081+1)/(h\u2081+3))\n        bnew = -(\u03b1^2-\u03b2^2)/h\u2081/(h\u2081+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)*\u03c0/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 \u2208 \u211c^(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 \u2208 \u211c^(size of x_to \u00d7 size of x_from \u00d7 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 \u2208 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\u2081 \u2265 0)\n@variable(m, x\u2082 \u2265 0)\n@variable(m, x\u2083 \u2265 0)\n\n@objective(m, Max, 2x\u2081  + 4x\u2082 + 3x\u2083)\n@constraint(m, 3x\u2081  + 4x\u2082 + 2x\u2083 \u2264 60)\n@constraint(m, 2x\u2081  + x\u2082 + 2x\u2083 \u2264 40)\n@constraint(m, x\u2081  + 3x\u2082 + 2x\u2083 \u2264 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\u2081 = \", value(x\u2081))\nprintln(\"x\u2082 = \", value(x\u2082))\nprintln(\"x\u2083 = \", value(x\u2083))\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(\u03b1,\u03b2) density\n\u03b1 = 10\n\u03b2 = 5\n\nx_values = 0:0.001:1\n\n# Get prior and posterior values\nprior = [pdf(Beta(\u03b1,\u03b2),x) for x in x_values]\nposterior = [pdf(Beta(\u03b1+p,\u03b2+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(\u03b1+p,\u03b2+q),0.65) - cdf(Beta(\u03b1+p,\u03b2+q),0.55)\nconfidence_interval = [quantile(Beta(\u03b1+p,\u03b2+q),0.025), quantile(Beta(\u03b1+p,\u03b2+q),0.975)]\nbayes_mean = mean(Beta(\u03b1+p,\u03b2+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 DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing Distributions\nusing Plots\n\n# %% 4.6\nw = 6\nn = 9\np_grid = range(0, 1, length = 100)\nposterior = @. pdf(Binomial(n, p_grid), w) * pdf(Uniform(0, 1), p_grid)\nposterior ./= sum(posterior)\n\nplot(p_grid, posterior)\n", "meta": {"hexsha": "ad43085b27a5e63fc75447b30e45349c4b218b81", "size": 262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/snippet_04_06.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_04_06.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_04_06.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": 16.375, "max_line_length": 71, "alphanum_fraction": 0.6717557252, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7769839462840007}}
{"text": "# Counting Inversions\n#\n# This implementation assumes all the values in the collection are distinct.\n\nfunction count_inversions_naive(a::AbstractVector)::Int\n    cnt = 0\n    n = length(a)\n    for i in 1:(n - 1)\n        cnt += sum(a[i] .> @view a[(i + 1):n])\n    end\n    cnt\nend\n\n\"Merge sorts `a` and returns its number of inversions.\"\nfunction count_inversions_mergesort!(a::AbstractVector)::Int\n    aux = zeros(eltype(a), length(a))\n    ms_inv_r!(a, aux)\nend\n\nfunction ms_inv_r!(a::AbstractVector, aux::AbstractVector)::Int\n    n = length(a)\n    if n <= 1\n        return 0\n    end\n\n    m = div(n, 2)\n    cnt = @views ms_inv_r!(a[1:m], aux[1:m]) +\n                 ms_inv_r!(a[(m + 1):n], aux[(m + 1):n])\n\n    i = 1\n    j = m + 1\n    for k in 1:n\n        if i > m\n            aux[k] = a[j]\n            j += 1\n        elseif j > n\n            aux[k] = a[i]\n            i += 1\n        elseif a[i] < a[j]\n            aux[k] = a[i]\n            i += 1\n        else\n            aux[k] = a[j]\n            j += 1\n            cnt += m - i + 1\n        end\n    end\n    a .= aux\n\n    cnt\nend\n\n# Plargarized from https://stackoverflow.com/a/23201616\nfunction count_inversions_fenwick(a::AbstractVector)::Int\n    n = length(a)\n    cnt = 0\n    count_tree = zeros(Int, n)\n    ranks = Dict(v => i for (i, v) in enumerate(sort(a)))\n    for x in Iterators.reverse(a)\n        r = ranks[x]\n        i = r - 1\n        while i > 0\n            cnt += count_tree[i]\n            i -= i & (-i)\n        end\n\n        i = r\n        while i <= n\n            count_tree[i] += 1\n            i += i & (-i)\n        end\n    end\n    cnt\nend\n\n\n#===== Unit Tests =====#\n\nusing Test\nusing Random: seed!, shuffle!\n\n@testset \"Count inversions\" begin\n    n = 1000\n    seed!()\n    a = collect(1:n)\n    shuffle!(a)\n\n    n_inversions_naive = count_inversions_naive(a)\n    n_inversions_fenwick = count_inversions_fenwick(a)\n    n_inversions_mergesort = count_inversions_mergesort!(a)\n    @test n_inversions_naive == n_inversions_mergesort == n_inversions_fenwick\n    @test issorted(a)\nend\n", "meta": {"hexsha": "d63763b1eeb888323df080cc5451c4976b8367a0", "size": 2041, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CountInversions/CountInversions.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": "CountInversions/CountInversions.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": "CountInversions/CountInversions.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": 21.7127659574, "max_line_length": 78, "alphanum_fraction": 0.530622244, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7769814201297762}}
{"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\u2013Kutta\nmethod (a.k.a. RK4, or Classic Runge\u2013Kutta). 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\u00b2x/dt\u00b2 = a(t, x(t)) using the Euler\u2013Cromer method\n(a.k.a. the semi-implicit euler method, or the Newton\u2013St\u00f8rmer\u2013Verlet).\n\n# Arguments\n- `initx`, `initv`: initial x (displacement) and dx/dt (velocity v)\n- `acceleration`: the function d\u00b2x/dt\u00b2 = 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\u00b2x/dt\u00b2 = 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\u00b2x/dt\u00b2 = 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\u00b2x/dt\u00b2 = a(t, x(t)) using Verlet integration\n(a.k.a. the St\u00f6rmer\u2013Verlet method).\n\n# Arguments\n- `initx`, `initv`: initial x (displacement) and dx/dt (velocity v)\n- `acceleration`: the function d\u00b2x/dt\u00b2 = 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\u00b2x/dt\u00b2 = 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\u00b2x/dt\u00b2 = 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 -\u03b3\n    elseif t==2\n        # return \u03b3^2 - \u03b3 + pi^2/6, Crandall seems to be wrong on this\n        return \u03b3^2 + pi^2/6  # from Mathematica\n    elseif t==3\n        # return -2*\u03b3^3 + 9*\u03b3^2 - (\u03c0^2+6)*\u03b3 + 3*\u03c0^2/2 - 4*SpecialFunctions.zeta(3), Crandall seems to be wrong on this\n        return -\u03b3^3  - \u03c0^2*\u03b3/2 + PG21 # from Mathematica\n    elseif t==4\n        return \u03b3^4 + \u03b3^2*\u03c0^2 + 3*\u03c0^4/20 - 4*\u03b3*PG21 # from Mathematica\n    elseif t==5\n        return -\u03b3^5 - (20/12)*\u03b3^3*\u03c0^2 - (9/12)*\u03b3*\u03c0^4 + (10*\u03b3^2 + (20/12)*\u03c0^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": "#############################################################################\n#############################################################################\n#\n# This file contains units tests for polynomial operations\n#                                                                               \n#############################################################################\n#############################################################################\n\n\n\"\"\"\nTest product of polynomials.\n\"\"\"\nfunction prod_test_poly(;N::Int = 10, N_prods::Int = 20, seed::Int = 0)\n    Random.seed!(seed)\n    for _ in 1:N\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        prod = p1*p2\n        @assert leading(prod) == leading(p1)*leading(p2)\n    end\n\n    for _ in 1:N\n        p_base = Polynomial(Term(1,0))\n        for _ in 1:N_prods\n            p = rand(Polynomial)\n            prod = p_base*p\n            @assert leading(prod) == leading(p_base)*leading(p)\n            p_base = prod\n        end\n    end\n    println(\"prod_test_poly - PASSED\")\nend\n\n\"\"\"\nTest product of polynomials modulo P.\n\"\"\"\nfunction prod_test_poly_mod_p(;N::Int = 10, N_prods::Int = 20, seed::Int = 0)\n    Random.seed!(seed)\n    sample_primes_array = [3,5,7,11,13,17,19]\n    for _ in 1:N\n        rand_prime = rand(sample_primes_array)\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        p1mod = PolynomialModP(p1, rand_prime)\n        p2mod = PolynomialModP(p2, rand_prime)\n        prod = p1mod*p2mod\n        @assert mod(leading(prod), rand_prime) == leading(mod(p1mod.terms*p2mod.terms, rand_prime))\n    end\n\n    for _ in 1:N\n        rand_prime = rand(sample_primes_array)\n        p_base = PolynomialModP(Polynomial(Term(1,0)), rand_prime)\n        for _ in 1:N_prods\n            p = PolynomialModP(rand(Polynomial), rand_prime)\n            prod = p_base*p\n            prod = PolynomialModP(prod, rand_prime)\n            @assert leading(prod.terms) == leading(mod(p_base.terms*p.terms, rand_prime))\n            p_base = prod\n        end\n    end\n    println(\"prod_test_poly_mod_p - PASSED\")\nend\n\n\"\"\"\nTest power of polynomial/integer mod P\n\"\"\"\nfunction power_test_poly(;N::Int = 10, seed::Int = 0)\n    sample_primes_array = [3,5,7,11,13,17,19]\n    Random.seed!(seed)\n    x = x_poly()\n    print(\"Proceeding with power tests ~ [\")\n    for i in 1:N\n        exponent = rand(10:20)\n        rand_prime = rand(sample_primes_array)\n        p1 = rand(Polynomial)\n        out = 1\n        for i in 1:exponent\n            out = mod(out*p1, rand_prime)\n        end\n        if ^(p1, exponent, rand_prime) - out != 0\n            println(\"--- TEST FAILED ---\")\n            break\n        end \n        print(\"-\")\n    end\n    print(\"]\\n\")\n    println(\"power_test_poly - COMPLETED\\n\")\nend\n\n\"\"\"\nTest power of polynomial mod P\n\"\"\"\nfunction power_test_poly_modp(;N::Int = 10, seed::Int = 0)\n    sample_primes_array = [3,5,7,11,13,17,19]\n    Random.seed!(seed)\n    x = x_poly()\n    print(\"Proceeding with power tests using PolynomialModP data type ~ [\")\n    for i in 1:N\n        exponent = rand(10:20)\n        rand_prime = rand(sample_primes_array)\n        p1 = rand(Polynomial)\n        p1mod = PolynomialModP(p1, rand_prime)\n        out = 1\n        for i in 1:exponent\n            out = mod(out*p1mod.terms, p1mod.prime)\n        end\n        if ^(p1mod, exponent) - out != 0\n            println(\"--- TEST FAILED ---\")\n            break\n        end \n        print(\"-\")\n    end\n    print(\"]\\n\")\n    println(\"power_test_poly_modp - COMPLETED\\n\")\nend\n\n\"\"\"\nBenchmark multiplication \n\"\"\"\nfunction prod_benchmark(;N::Int = 50, seed::Int = 0)\n    println(\"Begin prod_benchmark: Demonstrating performance of polynomial multiplication algorithm\")\n    Random.seed!(seed)\n    p1 = 0\n    p2 = 0\n    x = x_poly()\n    for i in 1:N\n        p1 += rand(1:N)*x^(i)\n        p2 += rand(1:N)*x^(i)\n        if i%10 == 0\n            print(\"Time taken to multiply two polynomials with $i terms:\")\n            @time prod = p1*p2\n            @assert leading(prod) == leading(p1)*leading(p2)\n        end\n    end\n    println(\"prod_benchmark COMPLETED\\n\")\nend\n\nfunction prod_modP_benchmark(;N::Int = 50, seed::Int = 0)\n    println(\"Begin prod_modP_benchmark: Demonstrating performance of polynomial multiplication algorithm in modulo P\")\n    Random.seed!(seed)\n    sample_primes_array = [3,5,7,11,13,17,19]\n    p1 = 0\n    p2 = 0\n    x = x_poly()\n    for i in 1:N\n        rand_prime = rand(sample_primes_array)\n        p1 += rand(1:N)*x^(i)\n        p2 += rand(1:N)*x^(i)\n        p1mod = PolynomialModP(p1, rand_prime)\n        p2mod = PolynomialModP(p2, rand_prime)\n        if i%10 == 0\n            print(\"Time taken to multiply two polynomials with $i terms:\")\n            @time prod = p1mod*p2mod\n            @assert leading(prod) == leading(mod((mod(p1mod.terms, rand_prime) * mod(p2mod.terms, rand_prime)), rand_prime))\n        end\n    end\n    println(\"prod_modP_benchmark COMPLETED\\n\")\nend\n\nfunction crt_benchmark(;N::Int = 50, seed::Int = 0)\n    println(\"Begin crt_benchmark: Demonstrating performance of polynomial multiplication using the Chinese Remainder Theorem\")\n    Random.seed!(seed)\n    sample_primes_array = [3,5,7,11,13,17,19]\n    p1 = 0\n    p2 = 0\n    x = x_poly()\n    for i in 1:N\n        x = x_poly()\n        rand_prime = rand(sample_primes_array)\n        p1 += rand(1:N)*x^(i)\n        p2 += rand(1:N)*x^(i)\n        if i%10 == 0\n            print(\"Time taken to multiply two polynomials with $i terms:\")\n            @time prod = mult_poly_with_crt(p1, p2)\n            @assert prod == p1 * p2 \"Error: CRT does not net p1*p2\"\n        end\n    end\n    println(\"crt_benchmark COMPLETED\\n\")\nend\n\n\n\"\"\"\nTest derivative of polynomials (as well as product).\n\"\"\"\nfunction prod_derivative_test_poly(;N::Int = 10^3,  seed::Int = 0)\n    Random.seed!(seed)\n    for _ in 1:N\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        p1d = derivative(p1)\n        p2d = derivative(p2)\n        @assert (p1d*p2) + (p1*p2d) == derivative(p1*p2)\n    end\n    println(\"prod_derivative_test_poly - PASSED\")\nend\n\n\"\"\"\nTest derivative of polynomials modulo P (as well as product).\n\"\"\"\nfunction prod_derivative_test_poly_mod_p(;N::Int = 10^3,  seed::Int = 0)\n    Random.seed!(seed)\n    sample_primes_array = [3,5,7,11,13,17,19]\n    for _ in 1:N\n        rand_prime = rand(sample_primes_array)\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        p1mod = PolynomialModP(p1, rand_prime)\n        p2mod = PolynomialModP(p2, rand_prime)\n        p1d = derivative(p1)\n        p2d = derivative(p2)\n        p1mod_d = PolynomialModP(p1d, rand_prime)\n        p2mod_d = PolynomialModP(p2d, rand_prime)\n        @assert mod((p1d*p2) + (p1*p2d), rand_prime) == mod(derivative(p1mod.terms*p2mod.terms), rand_prime)\n    end\n    println(\"prod_derivative_test_poly_mod_p - PASSED\")\nend\n\n\n\n\"\"\"\nTest division of polynomials modulo p.\n\"\"\"\n## REMOVE\nfunction division_test_poly(;prime::Int = 101, N::Int = 10^4, seed::Int = 0)\n    Random.seed!(seed)\n    for _ in 1:N\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        p_prod = p1*p2\n        q, r = Polynomial(), Polynomial()\n        try\n            q, r = divide(p_prod, p2)(prime)\n            if (q, r) == (nothing,nothing)\n                println(\"Unlucky prime: $p1 is reduced to $(p1 % prime) modulo $prime\")\n                continue\n            end\n        catch e\n            if typeof(e) == DivideError\n                @assert mod(p2, prime) == 0\n            else\n                throw(e)\n            end\n        end\n        @assert iszero( mod(q*p2+r - p_prod, prime) )\n    end\n    println(\"division_test_poly - PASSED\")\nend\n\n\"\"\"\nTest the extended euclid algorithm for polynomials modulo p.\n\"\"\"\nfunction ext_euclid_test_poly(;prime::Int=101, N::Int = 10^3, seed::Int = 0)\n    Random.seed!(seed)\n    for _ in 1:N\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        g, s, t = extended_euclid_alg(p1, p2, prime)\n        @assert mod(s*p1 + t*p2 - g, prime) == 0\n    end\n    println(\"ext_euclid_test_poly - PASSED\")\nend\n\n\"\"\"\nTest division of polynomials modulo p using PolynomialModP data type.\n\"\"\"\nfunction division_test_poly_mod_p(;prime::Int = 101, N::Int = 10^3, seed::Int = 0)\n    Random.seed!(seed)\n    for _ in 1:N\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        p1mod = PolynomialModP(p1, prime)\n        p2mod = PolynomialModP(p2, prime)\n        p_prod = PolynomialModP(p1mod.terms*p2mod.terms, prime)\n        q, r = Polynomial(), Polynomial()\n        try\n            q, r = divide(p_prod, p2mod)\n            if (q, r) == (nothing,nothing)\n                println(\"Unlucky prime: $p1 is reduced to $(p1 % prime) modulo $prime\")\n                continue\n            end\n        catch e\n            if typeof(e) == DivideError\n                @assert mod(p2mod.terms, prime) == 0\n            else\n                throw(e)\n            end\n        end\n        @assert iszero(mod(q*p2mod.terms+r - p_prod.terms, prime))\n    end\n    println(\"division_test_poly_mod_p - PASSED\")\nend\n\n\"\"\"\nTest the extended euclid algorithm for polynomials modulo p.\n\"\"\"\nfunction ext_euclid_test_poly_mod_p(;prime::Int=101, N::Int = 10^3, seed::Int = 0)\n    Random.seed!(seed)\n    for _ in 1:N\n        p1 = rand(Polynomial)\n        p2 = rand(Polynomial)\n        p1mod = PolynomialModP(p1, prime)\n        p2mod = PolynomialModP(p2, prime)\n        g, s, t = extended_euclid_alg(p1mod, p2mod)\n        @assert mod(s*p1mod.terms + t*p2mod.terms - g, prime) == 0\n    end\n    println(\"ext_euclid_test_poly_mod_p - PASSED\")\nend\n", "meta": {"hexsha": "362f76f3244428497e3ccc630b8081baa52aba81", "size": 9530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/polynomials_test.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": "test/polynomials_test.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": "test/polynomials_test.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": 30.9415584416, "max_line_length": 126, "alphanum_fraction": 0.5644281217, "num_tokens": 2700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7769811972455778}}
{"text": "# collatz conjenture\n\n\n#Jl Plots\n\nfunction collatz_next(n)\n    if n % 2 == 0\n        return n \u00f7 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, +\u221e 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 \u21a6 0 if all(x = 0), +\u221e 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": "@testset \"Gauss\u2013Chebyshev\" begin\n\n    n = 10\n\n    @testset \"x.^2\" begin\n        x, w = gausschebyshev(n,1)\n        @test dot(x.^2,w) \u2248 pi/2\n        x, w = gausschebyshev(n,2)\n        @test dot(x.^2,w) \u2248 pi/8\n        x, w = gausschebyshev(n,3)\n        @test dot(x.^2,w) \u2248 pi/2\n        x, w = gausschebyshev(n,4)\n        @test dot(x.^2,w) \u2248 pi/2\n    end\n\n    @testset \"x^3\" begin\n        x, w = gausschebyshev(n,1)\n        @test abs(dot(x.^3,w))<1e-15\n        x, w = gausschebyshev(n,2)\n        @test abs(dot(x.^3,w))<1e-15\n        x, w = gausschebyshev(n,3)\n        @test dot(x.^3,w) \u2248 3*pi/8\n        x, w = gausschebyshev(n,4)\n        @test dot(x.^3,w) \u2248 -3*pi/8\n    end\nend", "meta": {"hexsha": "3d291c7d1fc11efda91dc11d2dbf761839a76592", "size": 674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gausschebyshev.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": "test/test_gausschebyshev.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": "test/test_gausschebyshev.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": 25.9230769231, "max_line_length": 36, "alphanum_fraction": 0.4807121662, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7769643783072103}}
{"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\u0303 = zeros(N, M+2);\n        for k in 1:M+1\n           c\u0303[:,k+1] = sum(cc[:,1:k].*cc[:,k:-1:1], dims = 2);\n        end\n        E = c\u0303[:,1:M+1] - (x .- x0).*c\u0303[:,2:M+2];\n        D = c\u0303[:,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": "using MLJ\nimport RDatasets: dataset\nimport DataFrames: DataFrame, select, Not, describe\nusing Random\n\ndata = dataset(\"datasets\", \"USArrests\")\nnames(data)\n\ndescribe(data, :mean, :std)\n\nX = select(data, Not(:State))\nX = coerce(X, :UrbanPop=>Continuous, :Assault=>Continuous);\n\nPCA = @load PCA pkg=MultivariateStats\n\npca_mdl = PCA(pratio=1)\npca = machine(pca_mdl, X)\nfit!(pca)\nPCA\nW = MLJ.transform(pca, X);\n\nschema(W).names\n\nr = report(pca)\ncumsum(r.principalvars ./ r.tvar)\n\ndata = dataset(\"ISLR\", \"OJ\")\n\nfeature_names = [\n    :PriceCH, :PriceMM, :DiscCH, :DiscMM, :SalePriceMM, :SalePriceCH,\n    :PriceDiff, :PctDiscMM, :PctDiscCH\n]\n\nX = select(data, feature_names);\n\nRandom.seed!(1515)\n\nSPCA = Pipeline(\n    Standardizer(),\n    PCA(pratio=1-1e-4)\n)\n\nspca = machine(SPCA, X)\nfit!(spca)\nW = MLJ.transform(spca, X)\nnames(W)\n\nrpca = collect(values(report(spca).report_given_machine))[2]\ncs = cumsum(rpca.principalvars ./ rpca.tvar)\n\nusing PyPlot\n\nfigure(figsize=(8,6))\n\nPyPlot.bar(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\nRandom.seed!(1515)\n\nKMeans = @load KMeans pkg=Clustering\nSPCA2 = Pipeline(\n    Standardizer(),\n    PCA(),\n    KMeans(k=3)\n)\n\nspca2 = machine(SPCA2, X)\nfit!(spca2)\n\nassignments = collect(values(report(spca2).report_given_machine))[3].assignments\nmask1 = assignments .== 1\nmask2 = assignments .== 2\nmask3 = assignments .== 3;\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\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "49099644afbecdd7fdecafa33fc5801b45c26fea", "size": 1854, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__site/__generated/ISL-lab-10/tutorial-raw.jl", "max_stars_repo_name": "JuliaAI/DataScienceTutorials.jl", "max_stars_repo_head_hexsha": "76b1d3d1a5045c62b104a8358e4c37049f15ccb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-08-09T11:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:20:43.000Z", "max_issues_repo_path": "__site/__generated/ISL-lab-10/tutorial-raw.jl", "max_issues_repo_name": "alan-turing-institute/MLJTutorials", "max_issues_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-10-22T00:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T14:38:09.000Z", "max_forks_repo_path": "__site/__generated/ISL-lab-10/tutorial-raw.jl", "max_forks_repo_name": "alan-turing-institute/MLJTutorials", "max_forks_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-11-20T16:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T11:55:15.000Z", "avg_line_length": 20.3736263736, "max_line_length": 87, "alphanum_fraction": 0.6855447681, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7769470228781133}}
{"text": "module BracketingTests\n\nimport ..Algopt # ensure we are using the correct Algopt\n\nusing Test\nusing Algopt.Bracketing:\nsearch, find_bracket, search_bracket,\nBracket,\nGoldenSection\n\nusing Algopt.TestFunctions: Rosenbrock\n\n\nquad2 = x->(x - 2)^2\n\nros = Rosenbrock(a = 1, b = 5)\n\n@testset \"Algopt.Bracketing.search(::GoldenSection)\" begin\n    @test 2 \u2248 search(GoldenSection(), quad2)\n    @test 2 \u2248 search(GoldenSection(), quad2, -1e6)\n    @test !(2 \u2248 search(GoldenSection(max_iter = 2), quad2))\n    \n    @test abs(0 - search(GoldenSection(), x->x'x)) <= eps()\n\n    # Line search of \u03b1 on 2D Rosenbrock function\n    ros_line = \u03b1->ros.f([10, 10] + \u03b1 * [-1, -1])\n    @test 9 \u2248 search(GoldenSection(), ros_line, 0)\nend\n\n@testset \"Algopt.Bracketing.find_bracket\" begin\n    bracket = find_bracket(quad2, 0)\n    @test bracket.left < 2\n    @test bracket.right > 2\n    \n    bracket = find_bracket(quad2, 10)\n    @test bracket.left < 2\n    @test bracket.right > 2\n    \n    bracket = find_bracket(quad2, -1e6)\n    @test bracket.left < 2\n    @test bracket.right > 2\nend\n\n@testset \"Algopt.Bracketing.search_bracket\" begin\n    bracket = search_bracket(GoldenSection(), quad2, Bracket(0, 10))\n    @test bracket.left \u2248 2\n    @test bracket.right \u2248 2\n\n    bracket = search_bracket(GoldenSection(), quad2, Bracket(-1e6, 1e6))\n    @test bracket.left \u2248 2\n    @test bracket.right \u2248 2\n\n    bracket = search_bracket(GoldenSection(max_iter = 2), quad2, Bracket(-1e6, 1e6))\n    @test !(bracket.left \u2248 2)\n    @test !(bracket.right \u2248 2)\nend\n\nend # module\n", "meta": {"hexsha": "4c64e72fd81faa9815f3f39680875c2f4b31b9c6", "size": 1521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bracketing.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": "test/bracketing.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": "test/bracketing.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": 25.7796610169, "max_line_length": 84, "alphanum_fraction": 0.6653517423, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7769470228781133}}
{"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 \u2113\u1d56 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 \u2113\u1d56 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 \u2113\u1d56-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\u1d63, I = (p...,)\n    x, y, z = (u...,)\n\n\t\u03d5 = -a*x^3 + b*x^2\n\t\u03c8 = c - d*x^2\n    dx = y + \u03d5 - z + I\n\tdy = \u03c8 - y\n\tdz = r*(s*(x - x\u1d63) - z)\n    return SVector{3}(dx, dy, dz)\nend\n\n\"\"\"\n\thindmarsh_rose(u\u2080, 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\u1d63, I]`.\n\"\"\"\nfunction hindmarsh_rose(u\u2080, p)\n    ContinuousDynamicalSystem(eom_hindmarsh_rose, u\u2080, p)\nend\nhindmarsh_rose(;u\u2080 = rand(3), a = 1, b = 3, c = 1, d = 5, r = 1e-3, s = 4, x\u1d63 = - 8/5, I = -8) =\n    hindmarsh_rose(u\u2080, [a, b, c, d, r, s, x\u1d63, 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, \u03bb)\n\t\nCompute soft thresholding operator with scaling parameter `\u03bb` at `x`, proximal\noperator of ``\u2113\u2081``-norm.\n\n#### Arguments\n  - `x::Real`\t: input\n  - `\u03bb::Real`\t: scaling parameter\n\n#### Returns\n  - `y::Real`\t: soft thresholded value\n\"\"\"\nfunction soft_thresh(x::Real, \u03bb::Real)\n\t# Soft thresholding\n\ty= sign(x)*max(abs(x) - \u03bb, zero(\u03bb))\n\n\treturn y\nend\n\n\"\"\"\n\tblock_soft_thresh(x, \u03bb)\n\t\nCompute block soft thresholding operator with scaling parameter `\u03bb` at `x`,\nproximal operator of the ``\u2113\u2082``-norm.\n\n#### Arguments\n  - `x::AbstractVector`\t: input (n x 1)\n  - `\u03bb::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, \u03bb::Real)\n    y= similar(x)\n\tblock_soft_thresh!(y, x, \u03bb)\n\n\treturn y\nend\n\n\"\"\"\n\tblock_soft_thresh!(y, x, \u03bb)\n\t\nCompute block soft thresholding operator with scaling parameter `\u03bb` at `x`,\nproximal operator of the ``\u2113\u2082``-norm, storing the results in `y`. See also\n`block_soft_thresh`.\n\"\"\"\nfunction block_soft_thresh!(y::AbstractVector, x::AbstractVector, \u03bb::Real)\n\tT= eltype(x)\n\t# Scaling\n\t\u03c4= max(one(\u03bb) - \u03bb*inv(norm(x) + eps(T)), zero(\u03bb))\n\n\t# Block soft thresholding\n\t@. y= \u03c4*x\n\n\treturn nothing\nend\n\n\"\"\"\n\tblock_soft_thresh!(x, \u03bb)\n\t\nCompute block soft thresholding operator with scaling parameter `\u03bb` at `x`,\nproximal operator of the ``\u2113\u2082``-norm, overwriting `x`. See also\n`block_soft_thresh`.\n\"\"\"\nfunction block_soft_thresh!(x::AbstractVector, \u03bb::Real)\n\tT= eltype(x)\n\t# Scaling\n\t\u03c4= max(one(\u03bb) - \u03bb*inv(norm(x) + eps(T)), zero(\u03bb))\n\n\t# Block soft thresholding\n\t@. x= \u03c4*x\n\n\treturn nothing\nend\n\n\"\"\"\n\tshrinkage(x, \u03bb)\n\t\nCompute shrinkage operator with scaling parameter `\u03bb` at `x`, proximal operator\nof the squared \u2113\u2082-norm (ridge).\n\n#### Arguments\n  - `x::Real`\t: input\n  - `\u03bb::Real`\t: scaling parameter\n\n#### Returns\n  - `y::Real`\t: shrunken value\n\"\"\"\nfunction shrinkage(x::Real, \u03bb::Real)\n\t# Scaling\n\t\u03c4= one(\u03bb)*inv(one(\u03bb) + \u03bb)\n\n\t# Shrinkage\n\ty= \u03c4*x\n\n\treturn y\nend\n\n\"\"\"\n    shrinkage!(x, \u03bb, fac, b)\n\nCompute the generalized shrinkage operator with scaling parameter `\u03bb` at `x`,\nproximal operator of a quadratic function with quadratic parameters `A` and\nlinear parameters `b` using a factorization `fac` of ``I + \u03bbA``, overwriting\n`x`. See also `shrinkage`.\n\"\"\"\nfunction shrinkage!(x::AbstractVector, \u03bb::Real, fac::Factorization, b::AbstractVector)\n    # x - \u03bbb\n    x.-= \u03bb .* b \n    # (I + \u03bbA)\u207b\u00b9(x - \u03bbb)\n    ldiv!(fac, x)\n\n    return nothing\nend\n\n\"\"\"\n    shrinkage(x, \u03bb, fac, b)\n\nCompute the generalized shrinkage operator with scaling parameter `\u03bb` at `x`,\nproximal operator of a quadratic function with quadratic parameters `A` and\nlinear parameters `b` using a factorization `fac` of ``I + \u03bbA``.\n\n#### Arguments\n  - `x::AbstractVector` : input\n  - `\u03bb::Real`           : scaling parameter\n  - `fac::Factorization`: factorization of ``I + \u03bbA`` \n  - `b::AbstractVector` : linear coefficients\n\n#### Returns\n  - `y::AbstractVector` : shrunken values\n\"\"\"\nfunction shrinkage(x::AbstractVector, \u03bb::Real, fac::Factorization, b::AbstractVector)\n    y= similar(x)\n    shrinkage!(y, \u03bb, fac, b)\n\n    return y\nend\n\n\"\"\"\n    shrinkage!(x, \u03bb, A, b)\n\nCompute the generalized shrinkage operator with scaling parameter `\u03bb` 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, \u03bb::Real, A::AbstractMatrix, b::AbstractVector)\n    # scaling I + \u03bbA\n    S= \u03bb .* 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, \u03bb, C, b)\n\n    return nothing\nend\n\n\"\"\"\n    shrinkage(x, \u03bb, A, b)\n\nCompute the generalized shrinkage operator with scaling parameter `\u03bb` at `x`,\nproximal operator of a quadratic function with quadratic parameters `A` and\nlinear parameters `b`.\n\n#### Arguments\n  - `x::AbstractVector` : input\n  - `\u03bb::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, \u03bb::Real, A::AbstractMatrix, b::AbstractVector)\n    y= similar(x)\n    shrinkage!(y, \u03bb, A, b)\n\n    return y\nend\n\nfunction smooth!(x::AbstractVector, \u03bb::Real, f::Function, \u2207f!::Function, x0::AbstractVector)\n    # adjust objective function and gradient\n    # f(y) + (1/2\u03bb)\u2016y - x\u2016\u2082\u00b2 \n    g(y::AbstractVector)= f(y) + inv(\u03bb + \u03bb) * ( sum(abs2, y) + sum(abs2, x) - 2 * dot(y, x) )\n    # \u2207f(y) + (1/\u03bb)(y - x)\n    \u2207g!(\u2207g::AbstractVector, y::AbstractVector)= begin\n                                                    # gradient    \n                                                    \u2207f!(\u2207g, y)\n                                                    # quadratic term\n                                                    \u2207g.+= inv(\u03bb) .* (y .- x)\n                                                end\n    \n    # solve using L-BFGS\n    res= optimize(g, \u2207g!, 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\u2013Hopf factorization.  If the symbol of\n# the Toeplitz operator is G(z), we find a Wiener\u2013Hopf factorization\n#\n# \tG(z) = \u03c6_+(z)*\u03c6_-(z)\n#\n# where \u03c6_\u00b1 are analytic in the interior/exterior of the unit\n# circle.  Then we have the UL decomposition\n#\n#   T[G]=T[\u03c6_+]*T[\u03c6_-]\n#\n# The Wiener\u2013Hopf factorization is found by rephrasing as a\n# Riemann\u2013Hilbert problem:\n#\n#   \u03c6_+(z)=\u03c6_-(z)^(-1)*G(z)\n#\n# and writing\n#\n#   \u03c6_-(z)^(-1) = 1 + C_-V(z) and \u03c6_+(z)=1+C_+V(z)=1+V+C_-V(z)\n#\n# where C_\u00b1 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\u03a6mi = 1+C*V\n\u03a6p = V+\u03a6mi\n\nL  = ToeplitzOperator(1/\u03a6mi)\nU  = ToeplitzOperator(\u03a6p)\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\u03a6mi = I+C*V\n\u03a6p = V+\u03a6mi\n\nL  = ToeplitzOperator(inv(\u03a6mi))\nU  = ToeplitzOperator(\u03a6p)\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; \u03b2 = 0.2; \u03b1 = 0.5\r\n    \u03bc = p[2]*(1.0 - u[3]/x3m)*u[2]/(p[3] + u[2])\r\n    du[1] = (\u03bc - D)*u[1]\r\n    du[2] = D*(x2f - u[2]) - \u03bc*u[1]/Y\r\n    du[3] = D*u[3] + (\u03b1*\u03bc + \u03b2)*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    \u03b1, \u03b2, \u03b3, a, b, c, \u03c3x, \u03c3y, \u03c3z = (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    \u03b7x = \u03c3x == 0 ? 0 : rand(Normal(0, \u03c3x))\n    \u03b7y = \u03c3y == 0 ? 0 : rand(Normal(0, \u03c3y))\n    \u03b7z = \u03c3z == 0 ? 0 : rand(Normal(0, \u03c3z))\n\n    dx = \u03b1*(y - fx) + \u03b7x\n    dy = x - y + z + \u03b7y\n    dz = -\u03b2*y - \u03b3*z + \u03b7z\n    return SVector{3}(dx, dy, dz)\nend\n\n\"\"\"\n    chua_nscroll_sinefunc(u\u2080, \u03b1, \u03b2, \u03b3, 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\u2080, \u03b1, \u03b2, \u03b3, a, b, c::Int, \u03c3x, \u03c3y, \u03c3z)\n    p = [\u03b1, \u03b2, \u03b3, a, b, c, \u03c3x, \u03c3y, \u03c3z]\n    ContinuousDynamicalSystem(eom_chuacircuit_nscroll_sine, u\u2080, p)\nend\nchuacircuit_nscroll_sine(;u\u2080 = [0.0, 0.0, 0.28695],\n        \u03b1 = 10.814, \u03b2 = 14, \u03b3 = 0, a = 1.3, b = 0.11, c = 2,\n        \u03c3x = 0.0, \u03c3y = 0.0, \u03c3z = 0.0) =\n    chuacircuit_nscroll_sine(u\u2080, \u03b1, \u03b2, \u03b3, a, b, c, \u03c3x, \u03c3y, \u03c3z)\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 Test\nusing FlightMechanics\n\n\n\u03c8, \u03b8, \u03d5 = 0.5, 0.05, 0.2  # rad\np, q, r = 1.0, 0.2, 0.1  # rad/s\n\n# Test regression\near = body_angular_velocity_to_euler_angles_rates(p, q, r, \u03b8, \u03d5)\npqr = euler_angles_rates_to_body_angular_velocity(ear..., \u03b8, \u03d5)\n@test isapprox(pqr, [p, q, r])\n\n# Test against trimmer function\n\u03c8_dot = 0.2\npqr1 = euler_angles_rates_to_body_angular_velocity(\u03c8_dot, 0.0, 0.0, \u03b8, \u03d5)\npqr2 = turn_rate_angular_velocity(\u03c8_dot, \u03b8, \u03d5)\n@test isapprox(pqr1, pqr2)\n\n# Test body_angular_velocity_to_quaternion_rates\nquat = euler2quaternion(\u03c8, \u03b8, \u03d5)\nqdot = body_angular_velocity_to_quaternion_rates(p, q, r, quat...)\n\n\u03a9_inv = inv(\n    [0 -p -q -r;\n     p  0  r -q;\n     q -r  0  p;\n     r  q -p  0]\n)\n@test isapprox(\u03a9_inv * qdot * 2, quat)\n\n# Test uvw_to_tas\u03b1\u03b2\nexp_tas = 100  # m/s\nexp_\u03b1 = 0.01  # rad\nexp_\u03b2 = 0.005  # rad\nu, v, w = wind2body(tas, 0, 0, exp_\u03b1, exp_\u03b2)\ntas, \u03b1, \u03b2 = uvw_to_tas\u03b1\u03b2(u, v, w)\n@test isapprox(tas, exp_tas)\n@test isapprox(\u03b1, exp_\u03b1)\n@test isapprox(\u03b2, exp_\u03b2, atol=1e-7)\n\n\n# Test tas_\u03b1_\u03b2_dot_from_uvw_dot\nu = 50.0\nv = 1.0\nw = 5.0\nu_dot = 5.0\nv_dot = 0.5\nw_dot = 2.0\ntas_dot, \u03b1_dot, \u03b2_dot = tas_\u03b1_\u03b2_dot_from_uvw_dot(u, v, w, u_dot, v_dot, w_dot)\n\n# Test alpha_dot against formula and tas_dot\ntas = \u221a(u*u + v*v + w*w)\n@test isapprox(\u03b1_dot, (w_dot * u - w * u_dot) / (u*u + w*w))\n@test isapprox(tas_dot, (u * u_dot + v * v_dot + w * w_dot) / tas)\n# Test \u03b2_dot against Stevens implementation (function uses Morelli)\n@test isapprox(\u03b2_dot, (v_dot * tas - v * tas_dot) / (tas * sqrt(u*u + w*w)))\n\n# tas_\u03b1_\u03b2_dot_from_uvw_dot <--> uvw_dot_from_tas_\u03b1_\u03b2\ntas, \u03b1, \u03b2 = uvw_to_tas\u03b1\u03b2(u, v, w)\nu_dot_, v_dot_, w_dot_ = uvw_dot_from_tas_\u03b1_\u03b2(tas, \u03b1, \u03b2, tas_dot, \u03b1_dot, \u03b2_dot)\n@test isapprox([u_dot, v_dot, w_dot], [u_dot_, v_dot_, w_dot_], atol=1e-4)\n", "meta": {"hexsha": "f8883875a4f70627227f4838c1ba75b380b6be51", "size": 1758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/flight_mechanics.jl", "max_stars_repo_name": "AlexS12/FlightMechanics.jl", "max_stars_repo_head_hexsha": "12bc740341aee3fd61f5a43f1253b598725989fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-07-08T11:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T14:34:34.000Z", "max_issues_repo_path": "test/flight_mechanics.jl", "max_issues_repo_name": "AlexS12/FlightMechanics.jl", "max_issues_repo_head_hexsha": "12bc740341aee3fd61f5a43f1253b598725989fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2018-07-10T21:23:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-16T03:39:48.000Z", "max_forks_repo_path": "test/flight_mechanics.jl", "max_forks_repo_name": "AlexS12/FlightMechanics.jl", "max_forks_repo_head_hexsha": "12bc740341aee3fd61f5a43f1253b598725989fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:49:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T14:34:26.000Z", "avg_line_length": 28.3548387097, "max_line_length": 79, "alphanum_fraction": 0.672923777, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7768903980252982}}
{"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": "using Statistics, MultivariateStats, RDatasets, LinearAlgebra, Plots; pyplot()\n\ndata = dataset(\"datasets\", \"iris\")\ndata = data[:,[:SepalLength,:SepalWidth,:PetalLength,:PetalWidth]]\nx = convert(Array{Float64,2},data)'\n\nmodel = fit(PCA, x, maxoutdim=4, pratio = 0.999)\nM = projection(model)\n\nfunction manualProjection(x)\n    covMat = cov(x')\n    ev = eigvals(covMat)\n    eigOrder = sortperm(eigvals(covMat),rev=true)\n    eigvecs(covMat)[:,eigOrder]\nend\n\nprintln(\"Manual vs. package: \",maximum(abs.(M-manualProjection(x))))\n\npcVar = principalvars(model) ./ tvar(model)\ncumVar = cumsum(pcVar)\npcDat = M[:,1:2]'*x\n\np1 = plot(pcVar, c=:blue, label=\"Variance due to PC\")\n\tplot!(1:length(cumVar), cumVar, label=\"Cumulative Variance\", c=:red, \n        xlabel=\"Principle component\",ylabel=\"Variance Proportion\",ylims=(0,1))\np2 = scatter(pcDat[1,:],pcDat[2,:], c=:blue, xlabel=\"PC 1\", ylabel=\"PC 2\",\n            msw=0, legend=:none)\nplot(p1, p2, size=(800,400))", "meta": {"hexsha": "696f8c7f34da6a25a70b68b0d1bd9d18e4df31b1", "size": 951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "9_chapter/pca.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": "9_chapter/pca.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": "9_chapter/pca.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.9642857143, "max_line_length": 78, "alphanum_fraction": 0.6792849632, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7768884001660483}}
{"text": "function vblast{T}(H::Array{T,2},mu=Inf)\n# (W,P,B) = vblast(H)\n#  Returns a VBLAST matrix decomposition of H such that \n#  H = pinv(W)*B*P' or B = W*H*P.  Here P is a permutation matrix, B is\n#  lower triangular with ones on the diagonal, and W has orthogonal rows.\n# (W,P,B) = vblast(H,mu)\n#  If an SNR argument mu is passed in, a regularized (\"MMSE\")\n#  decomposition is done, with the result that W will no longer have\n#  orthogonal rows and B is no longer lower triangular.\n#\n# Example: For decoding with N receivers\n#  N=4;H = rand(N,N); include(\"vblast.jl\");(W,P,B) = vblast(H)\n# Example: For MMSE decoding with N receivers mu=rho/N \n#  (W,P,B) = vblast(H,rho/size(H,1)); \n\n(K,N) = size(H);\n\nW = zeros(T,K,K);\nP = zeros(Int,N,N);\nHp = H;\nk = zeros(Int,K,1);\nindexH = [1:N;];\nfor i=1:N\n    G = inv(Hp'*Hp + eye(N-i+1)/mu)*Hp'; # Do pseudoinverse\n    gn = diag(G*G');\n    (mx,mi) = findmin(abs(gn))\n    k[i] = indexH[mi];\n    W[i,:] = G[mi,:];\n    P[k[i],i]=1;\n    indexH = setdiff(indexH,k[i]);\n    Hp = H[:,indexH];\nend\nB = W*H*P  # Calculating B may not be required in some real-world scenarios\nreturn (W,P,B)\nend\n", "meta": {"hexsha": "25933632ea258f84a2ea95c4d954a50878643fef", "size": 1121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vblast.jl", "max_stars_repo_name": "JuliaPackageMirrors/LLLplus.jl", "max_stars_repo_head_hexsha": "149bbace637238708a63eeb048f7860f44c71049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vblast.jl", "max_issues_repo_name": "JuliaPackageMirrors/LLLplus.jl", "max_issues_repo_head_hexsha": "149bbace637238708a63eeb048f7860f44c71049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vblast.jl", "max_forks_repo_name": "JuliaPackageMirrors/LLLplus.jl", "max_forks_repo_head_hexsha": "149bbace637238708a63eeb048f7860f44c71049", "max_forks_repo_licenses": ["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.1388888889, "max_line_length": 75, "alphanum_fraction": 0.6173059768, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377308419051, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7768746096241556}}
{"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 \u201ctwo parabolas\u201d problem in two dimensions reads as\n# ```math\n#     \\min_{\ud835\udc31 \u2208 X } \n#     \\begin{bmatrix} f\u2081(\\mathbf{x}) \\\\ f\u2082(\\mathbf{x}) \\end{bmatrix} = \n#     \\min_{\\mathbf{x} \u2208 X}\n#     \\begin{bmatrix}\n#     (x\u2081 - 1)\u00b2 + (x\u2082 - 1)\u00b2 \\\\\n#     (x\u2081 + 1)\u00b2 + (x\u2082 + 1)\u00b2\n#     \\end{bmatrix}.\n# ```\n# It is unconstrained if the feasible set is ``X = \u211d^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} \u2208 \u211d^2 : x\u2081 = x\u2082, \\, -1 \\le x\u2081, x\u2082 \\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\u2081 = x -> sum( (x .- 1).^2 )\nf\u2082 = x -> sum( (x .+ 1).^2 )\n\u2207f\u2081 = x -> 2 .* ( x .- 1 )\n\u2207f\u2082 = x -> 2 .* ( x .+ 1 )\n\nmop = MixedMOP(2);  # problem with 2 variables\nadd_objective!(mop, f\u2081, \u2207f\u2081 )\nadd_objective!(mop, f\u2082, \u2207f\u2082 )\n\n#~ starting point\nx\u2080 = [ -\u03c0 ;  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\u2080; algo_config = ac );\nx\n\n# Hopefully, `x` is critical, i.e., `x[1] \u2248 x[2]`.\n@test x[1] \u2248 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 \u2259 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\u2081 = [ f\u2081([x;y]) for x \u2208 X, y \u2208 X ]\nZ\u2082 = [ f\u2082([x;y]) for x \u2208 X, y \u2208 X ]\nlevels = [ i.^2 for i = LinRange(.1, 6, 6) ]\ncontour!(X,Y,Z\u2081; colormap = :greens, levels = levels, linewidth = .5 )\ncontour!(X,Y,Z\u2082; 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\u2081, rbf_cfg )\nadd_objective!(mop_rbf, f\u2082, rbf_cfg )\n\n#~ only perform 10 iterations\nac = AlgoConfig( max_iter = 10 )\nx, fx, _, db = optimize( mop_rbf, x\u2080; 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\u2081, rbf_cfg ); #hide\nadd_objective!(mop_rbf, f\u2082, rbf_cfg ); #hide\n\n#~ an array of well spread points in [-4,4]\u00b2 #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 \u211d\u00b2.\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\u2080 = nothing # initial database can be `nothing`\nfor x\u2080 \u2208 X\n    global db\u2080, start_fin_points\n    x_fin, fx_fin, _, db\u2080 = optimize( mop_rbf, x\u2080; algo_config = ac, populated_db = db\u2080 )\n    #~ add points to dict\n    start_fin_points[x\u2080] = 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') = \u03c3\u00b2(1 + (x - x')\u1d40(x - x')/(2\u03b1\u2113\u00b2))^{-\u03b1}\n```\nwith length scale ``\u2113``, signal standard deviation ``\u03c3``, and shape parameter ``\u03b1``.\n\"\"\"\nmutable struct RQIso <: Isotropic{SqEuclidean}\n    \"Squared length scale\"\n    \u21132::Float64\n    \"Signal variance\"\n    \u03c32::Float64\n    \"Shape parameter\"\n    \u03b1::Float64\n    \"Priors for kernel parameters\"\n    priors::Array\n\n    \"\"\"\n        RQIso(ll:Float64, l\u03c3::Float64, l\u03b1::Float64)\n\n    Create `RQIso` with length scale `exp(ll)`, signal standard deviation `exp(l\u03c3)`, and\n    shape parameter `exp(l\u03b1)`.\n    \"\"\"\n    RQIso(ll::Float64, l\u03c3::Float64, l\u03b1::Float64) =\n        new(exp(2 * ll), exp(2 * l\u03c3), exp(l\u03b1), [])\nend\n\nfunction set_params!(rq::RQIso, hyp::VecF64)\n    length(hyp) == 3 || throw(ArgumentError(\"Rational Quadratic function has three parameters\"))\n    rq.\u21132, rq.\u03c32, rq.\u03b1 = exp(2 * hyp[1]), exp(2 * hyp[2]), exp(hyp[3])\nend\n\nget_params(rq::RQIso) = Float64[log(rq.\u21132) / 2, log(rq.\u03c32) / 2, log(rq.\u03b1)]\nget_param_names(rq::RQIso) = [:ll, :l\u03c3, :l\u03b1]\nnum_params(rq::RQIso) = 3\n\nStatistics.cov(rq::RQIso, r::Float64) = rq.\u03c32 * (1 + r / (2 * rq.\u03b1 * rq.\u21132))^(-rq.\u03b1)\n\n@inline dk_dll(rq::RQIso, r::Float64) =\n    (s = r / rq.\u21132; rq.\u03c32 * s * (1 + s / (2 * rq.\u03b1))^(-rq.\u03b1 - 1)) # dK_d(log \u2113)dK_d\u2113\n@inline function dk_dl\u03b1(rq::RQIso, r::Float64)\n    s = r / rq.\u21132\n    part = 1 + s / (2 * rq.\u03b1)\n    rq.\u03c32 * part^(-rq.\u03b1) * (s / (2 * part) - rq.\u03b1 * log(part))  # dK_d(log \u03b1)\nend\n@inline function dk_d\u03b8p(rq::RQIso, r::Float64, p::Int)\n    if p==1\n        return dk_dll(rq, r)\n    elseif p==2\n        return dk_dl\u03c3(rq, r)\n    elseif p==3\n        return dk_dl\u03b1(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 ``\u03b7 > 2`` nodes.\n# There are ``\u03b7`` 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, \u2026, U_\u03b7, I_1, I_2, \u2026, I_\u03b7]^T,\n# ```\n# and the state dimension is ``2\u03b7``.\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(;\u03b7=3, R=1.00, Rd=10.0, L=1e-10, C=1e-13 * 4.00)\n    A\u2081\u2081 = zeros(\u03b7, \u03b7)\n    A\u2081\u2082 = Bidiagonal(fill(-1/C, \u03b7), fill(1/C, \u03b7-1), :U)\n    A\u2082\u2081 = Bidiagonal(fill(1/L, \u03b7), fill(-1/L, \u03b7-1), :L)\n    A\u2082\u2082 = Diagonal(vcat(-Rd/L, fill(-R/L, \u03b7-1)))\n    A  = [A\u2081\u2081 A\u2081\u2082; A\u2082\u2081 A\u2082\u2082]\n    B = sparse([\u03b7+1], [1], 1/L, 2\u03b7, 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(\u03b7=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 ``\u03b1 > 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, \u03b1=1.0)\n    s.A .*= \u03b1\n    s.B .*= \u03b1\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 [\u2126] | driver resistance in [\u2126] | Inductance in [H] | Capacitance in [F] |\n# |------------------|--------------------------|------------------|-------------------|\n# |R = 1.00| Rdriver = 10.0| L = 1e\u221210 | C = 4e\u221213|\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 \u25a1(0.001),\n# ```\n# where ``\u25a1(\u03f5)`` is the infinity-norm ball of center zero and radius ``\u03f5``.\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\u03b7 = 20 # order\nn = 2\u03b7 # state-space dimension\nA, B = tline(\u03b7=\u03b7);\n\nUin_ss = Interval(-0.2, 0.2)\n\u25a1(\u03f5) = BallInf(zeros(n), \u03f5)\nX0 = -inv(Matrix(A)) * B * Uin_ss \u2295 \u25a1(0.001);\n\nUin = Interval(0.99, 1.01)\ns = @system(x'= A*x + B*u, x \u2208 Universe(n), u \u2208 Uin)\n\u03b1 = 1e-9 # scaling factor\nscale!(s, \u03b1);\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 `\u03b4=1e-3` and the box algorithm.\n\nsol = solve(P, T=0.7, alg=BOX(\u03b4=1e-3));\n\n# To get the variable ``U_{out}`` we have to project onto the ``\u03b7``-th coordinate\n# and invert the sign of the flowpipe.\n\nUout_vs_t = @. (-1.0) * project(sol, \u03b7);\n\n#-\n\nplot(Uout_vs_t, vars=(0, \u03b7), 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(\u03b4=1e-3, dim=statedim(P), vars=[\u03b7]))`,\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": "using Plots\n\nexport true_positives\nexport true_negatives\nexport false_positives\nexport false_negatives\nexport precision_classification\nexport recall\nexport accuracy\nexport f1_score\nexport confusion_matrix\nexport predict_from_threshold\nexport best_f1_search\n\n\"true positives. If rate: sensitivity (true positives / actual positives)\"\ntrue_positives(actual::Array{Int64,1}, pred::Array{Int64,1}; rate = false) =\n    sum(actual .== pred .== 1) / (rate ? sum(actual .== 1) : 1)\n\n\"true negatives. If rate: specificity (true negatives / actual negatives)\"\ntrue_negatives(actual::Array{Int64,1}, pred::Array{Int64,1}; rate = false) =\n    sum(actual .== pred .== 0) / (rate ? sum(actual .== 1) : 1)\n\n\"false positives. If rate: fall-out (false positives / actual negatives)\"\nfalse_positives(actual::Array{Int64,1}, pred::Array{Int64,1}; rate = false) =\n    sum((actual .== 0) .& (pred .== 1)) / (rate ? sum(actual .== 0) : 1)\n\n\"true negatives. If rate: (false negatives / actual positives)\"\nfalse_negatives(actual::Array{Int64,1}, pred::Array{Int64,1}; rate = false) =\n    sum((actual .== 1) .& (pred .== 0)) / (rate ? sum(actual .== 1) : 1)\n\n\"precision (false positives / (true positives + false positives))\"\nfunction precision_classification(actual::Array{Int64,1}, pred::Array{Int64,1})\n    tp = true_positives(actual, pred)\n    fp = false_positives(actual, pred)\n    return tp / (tp + fp)\nend\n\n\"recall (true positives / (true positives + false negatives))\"\nfunction recall(actual::Array{Int64,1}, pred::Array{Int64,1})\n    tp = true_negatives(actual, pred)\n    fn = false_negatives(actual, pred)\n    return tp / (tp + fn)\nend\n\n\"proportion of classifications made correctly\"\naccuracy(actual::Array{Int64,1}, pred::Array{Int64,1}) = sum(actual .== pred) / length(actual)\n\n\"F1 score, harmonic mean of precision and recall, 2 * ((precision * recall) / (precision + recall))\"\nfunction f1_score(actual::Array{Int64,1}, pred::Array{Int64,1})\n    prec = precision_classification(actual, pred)\n    rec = recall(actual, pred)\n    return 2 * ((prec * rec) / (prec + rec))\nend\n\n\"\"\"\n_given array of 1s and 0s, actuals and predictions, returns confusion matrix_\n\n#### parameters:\n    actual : Array{Int}\n        actual labels, \u2208 [0,1]\n    pred : Array{Float64}\n        an array of prediction values 0 <= x <= 1\n    ratio : Boolean\n        if true, return matrix as ratios, sum = 1, else return absolute numbers\n\n#### returns: Array{Float64,2}\n    confusion matrix of form:\n    [tp fp]\n    [fn tn]\n    X axis = actual\n    y axis = predicted\n\"\"\"\nfunction confusion_matrix(\n    actual::Array{Int64,1},\n    pred::Array{Int64,1};\n    ratio = false,\n)\n    [\n     true_positives(actual, pred) false_positives(actual, pred)\n     false_negatives(actual, pred) true_negatives(actual, pred)\n    ] ./ (ratio ? (length(actual) |> x -> round.(x, digits = 3)) : 1)\nend\n\n\"given an array of predicted probabilities, return 1 or 0 depending on threshold\"\npredict_from_threshold(pred::Array{Float64}, threshold::Float64) = [perc > threshold ? 1 : 0 for perc in pred]\n\n\"\"\"\n_given array of true labels and % predictions, return best threshold and F1 score, plot of F1 score a>_\n\n#### parameters:\n    actual : Array{Int}\n        actual labels, \u2208 [0,1]\n    pred : Array{Float64}\n        an array of prediction values 0 <= x <= 1\n\n#### returns: Tuple{Float64, Float64, Plots.Plot{Plots.GRBackend}}\n    tuple of best threshold, best F1 score, plot of F1 scores\n\"\"\"\nfunction best_f1_search(actual::Array{Int}, pred::Array{Float64})\n    x = 0:0.01:1\n    accuracies = [sum(predict_from_threshold(pred, threshold) .== actual) / length(actual) for threshold in x]\n    f1s = [f1_score(actual, predict_from_threshold(pred, threshold)) for threshold in x]\n\n    p1 = plot(\n        x,\n        accuracies,\n        label = \"Accuracy\",\n        xlabel = \"threshold\",\n        ylabel = \"F1 Score\",\n        title = \"F1 Score\",\n        legend = :outerbottomright,\n        ylim = (0, 1),\n    )\n    plot!(x, f1s, label = \"F1\")\n\n    best_f1, best_threshold_index = findmax([isnan(f1) ? 0 : f1 for f1 in f1s])\n    return x[best_threshold_index], best_f1, p1\nend\n", "meta": {"hexsha": "316abc6711aaf229f0d321f8d7fce27ec0897f43", "size": 4096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evaluation/diagnostics.jl", "max_stars_repo_name": "dhopp1/BinaryClassificationTools", "max_stars_repo_head_hexsha": "b6411c440688b677b5eec54cca0b9cfbcf594d35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-12T11:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-12T11:32:18.000Z", "max_issues_repo_path": "src/evaluation/diagnostics.jl", "max_issues_repo_name": "dhopp1/BinaryClassificationTools.jl", "max_issues_repo_head_hexsha": "b6411c440688b677b5eec54cca0b9cfbcf594d35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/evaluation/diagnostics.jl", "max_forks_repo_name": "dhopp1/BinaryClassificationTools.jl", "max_forks_repo_head_hexsha": "b6411c440688b677b5eec54cca0b9cfbcf594d35", "max_forks_repo_licenses": ["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.4201680672, "max_line_length": 110, "alphanum_fraction": 0.6691894531, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7768314117617403}}
{"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') = \u03c3\u00b2(1+\u221a5*d/\u2113 + 5d\u00b2/3\u2113\u00b2)exp(-\u221a5*d/\u2113), where d = |x-x'|\n# Arguments:\n* `ll::Float64`: Log of the length scale \u2113\n* `l\u03c3::Float64`: Log of the signal standard deviation \u03c3\n\"\"\" ->\ntype Mat52Iso <: Isotropic\n    \u2113::Float64      # Length scale \n    \u03c32::Float64     # Signal std\n    Mat52Iso(ll::Float64, l\u03c3::Float64) = new(exp(ll), exp(2*l\u03c3))\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.\u2113, mat.\u03c32 = exp(hyp[1]), exp(2.0*hyp[2])\nend\nget_params(mat::Mat52Iso) = Float64[log(mat.\u2113), log(mat.\u03c32)/2.0]\nget_param_names(mat::Mat52Iso) = [:ll, :l\u03c3]\nnum_params(mat::Mat52Iso) = 2\n\nmetric(mat::Mat52Iso) = Euclidean()\ncov(mat::Mat52Iso, r::Float64) = mat.\u03c32*(1+sqrt(5)*r/mat.\u2113+5*r^2/(3*mat.\u2113^2))*exp(-sqrt(5)*r/mat.\u2113)\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.\u2113)\n\n    g1 = mat.\u03c32*(5*r^2/mat.\u2113^2)*((1+sqrt(5)*r/mat.\u2113)/3)*exp_r   #dK_d(log \u2113)\n    g2 = 2.0*mat.\u03c32*(1+sqrt(5)*r/mat.\u2113+5*r^2/(3*mat.\u2113^2))*exp_r #dK_d(log \u03c3)\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.\u2113)\n\n    for i in 1:nobsv, j in 1:i\n        @inbounds stack[i,j,1] = mat.\u03c32*(5*R[i,j]^2/mat.\u2113^2)*((1+sqrt(5)*R[i,j]/mat.\u2113)/3)*exp_R[i,j]      # dK_d\u2113\n        @inbounds stack[j,i,1] = stack[i,j,1] \n        @inbounds stack[i,j,2] = 2.0*mat.\u03c32*(1+sqrt(5)*R[i,j]/mat.\u2113+5*R[i,j]^2/(3*mat.\u2113^2))*exp_R[i,j]   # dK_d\u03c3\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 \u00d7 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\u03bb_stability(expI_inteq_jac)\n\nexpI_00_jac = jac([0.0,0.0], cr_expI_model, CRPar())\n\n\u03bb_stability(expI_00_jac)\n\neigvals(expI_00_jac)\n\nexpI_k_jac = jac([3.0,0.0], cr_expI_model, CRPar())\n\n\u03bb_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\u03bb_stability(logI_inteq_jac)\n\nlogI_00_jac = jac([0.0,0.0], cr_logI_model, CRPar())\n\n\u03bb_stability(logI_00_jac)\n\neigvals(logI_00_jac)\n\nlogI_k_jac = jac([3.0,0.0], cr_logI_model, CRPar())\n\n\u03bb_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\u03bb_stability(logII_inteq_jac)\n\nlogII_00_jac = jac([0.0,0.0], cr_logII_model, CRPar())\n\n\u03bb_stability(logII_00_jac)\n\neigvals(logII_00_jac)\n\nlogII_k_jac = jac([3.0,0.0], cr_logII_model, CRPar())\n\n\u03bb_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\u03bb_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\u03bb_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": "\nimport BS\nusing Test\n\n@testset \"BS Price\" begin\n    @testset \"no dividends\" begin\n\n        let\n            s = 42\n            k = 40\n            r = 0.1\n            sigma = 0.2\n            t = 0.5\n\n            @test BS.call(s, k, t, r, sigma) \u2248 4.759422392871542\n            @test BS.put(s, k, t, r, sigma) \u2248 0.8085993729000975\n            @test BS.price(BS.EuropeanCall(), s, k, t, r, sigma) \u2248 4.759422392871542\n            @test BS.price(BS.EuropeanPut(), s, k, t, r, sigma) \u2248 0.8085993729000975\n        end\n\n        let\n            s = 40.0\n            k = 40.0\n            r = 0.1\n            t = 0.5\n            sigma = 0.3\n\n            @test BS.call(s, k, t, r, sigma) \u2248 4.3625999408029585\n            @test BS.put(s, k, t, r, sigma) \u2248 2.4117769208315245\n            @test BS.price(BS.EuropeanCall(), s, k, t, r, sigma) \u2248 4.3625999408029585\n            @test BS.price(BS.EuropeanPut(), s, k, t, r, sigma) \u2248 2.4117769208315245\n        end\n    end\n\n    @testset \"dividends q\" begin\n\n        let\n            s = 930\n            k = 900\n            r = 0.08\n            sigma = 0.2\n            t = 2/12\n            q = 0.03\n\n            @test BS.call(s, k, t, r, q, sigma) \u2248 51.83295679649086\n            @test BS.put(s, k, t, r, q, sigma) \u2248 14.550996773772397\n            @test BS.price(BS.EuropeanCall(), s, k, t, r, q, sigma) \u2248 51.83295679649086\n            @test BS.price(BS.EuropeanPut(), s, k, t, r, q, sigma) \u2248 14.550996773772397\n        end\n\n        let\n            s = 1.8\n            k = 1.8\n            r = 0.1\n            rf = 0.03\n            t = 0.5\n            sigma = 0.2\n\n            @test BS.call(s, k, t, r, rf, sigma) \u2248 0.13172208280604858\n            @test BS.put(s, k, t, r, rf, sigma) \u2248 0.07073355562182104\n            @test BS.price(BS.EuropeanCall(), s, k, t, r, rf, sigma) \u2248 0.13172208280604858\n            @test BS.price(BS.EuropeanPut(), s, k, t, r, rf, sigma) \u2248 0.07073355562182104\n        end\n    end\nend\n\n@testset \"impvol\" begin\n    @testset \"no dividends\" begin\n        s = 40\n        k = 40\n        r = 0.1\n        t = 1\n\n        @test BS.impvol(BS.EuropeanCall(), 4.12, s, k, t, r) \u2248 0.099644799474057\n        @test BS.impvol(BS.EuropeanPut(), 4.12, s, k, t, r) \u2248 0.3860639608047352\n\n        @test BS.impvol(BS.EuropeanCall(), 17, s, k, t, r) \u2248 1.0332662114853954\n        @test BS.impvol(BS.EuropeanPut(), 13.15, s, k, t, r) \u2248 1.0299775738714554\n    end\n\n    @testset \"dividends q\" begin\n        s = 1.8\n        k = 1.8\n        r = 0.1\n        rf = 0.03\n        t = 0.5\n        sigma = 0.2\n\n        call_price = 0.13172208280604858\n        put_price = 0.07073355562182104\n\n        @test BS.impvol(BS.EuropeanCall(), call_price, s, k, t, r, rf) \u2248 sigma\n        @test BS.impvol(BS.EuropeanPut(), put_price, s, k, t, r, rf) \u2248 sigma\n    end\nend\n\n@testset \"Greeks\" begin\n\n    s = 49\n    k = 50\n    r = 0.05\n    t = 0.3846\n    sigma = 0.2\n\n    @testset \"Delta\" begin\n        @test BS.delta(BS.EuropeanCall(), s, k, t, r, sigma) \u2248 0.5216016339715761\n        @test BS.delta(BS.EuropeanPut(), s, k, t, r, sigma) \u2248 -0.4783983660284239\n    end\n\n    @testset \"Theta\" begin\n        @test BS.theta(BS.EuropeanCall(), s, k, t, r, sigma) \u2248 -4.305389964546104\n        @test BS.theta(BS.EuropeanPut(), s, k, t, r, sigma) \u2248 -1.853005672196868\n    end\n\n    @testset \"Gamma\" begin\n        @test BS.gamma(BS.EuropeanCall(), s, k, t, r, sigma) \u2248 0.06554537725247868\n        @test BS.gamma(BS.EuropeanPut(), s, k, t, r, sigma) \u2248 0.06554537725247868\n    end\n\n    @testset \"Vega\" begin\n        @test BS.vega(BS.EuropeanCall(), s, k, t, r, sigma) \u2248 12.105242754243843\n        @test BS.vega(BS.EuropeanPut(), s, k, t, r, sigma) \u2248 12.105242754243843\n    end\n\n    @testset \"Rho\" begin\n        @test BS.rho(BS.EuropeanCall(), s, k, t, r, sigma) \u2248 8.906574098800945\n        @test BS.rho(BS.EuropeanPut(), s, k, t, r, sigma) \u2248 -9.95716587794938\n    end\nend\n\n@testset \"Examples\" begin\n    include(\"examples.jl\")\nend\n\n", "meta": {"hexsha": "160b44306eee8e90798c556fd837e83192a6afab", "size": 3920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "felipenoris/BS.jl", "max_stars_repo_head_hexsha": "92c126546687c00702554676663912e9ac6efd9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-23T00:24:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-23T00:24:00.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "felipenoris/BS.jl", "max_issues_repo_head_hexsha": "92c126546687c00702554676663912e9ac6efd9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-19T10:22:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T15:36:19.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "felipenoris/BS.jl", "max_forks_repo_head_hexsha": "92c126546687c00702554676663912e9ac6efd9e", "max_forks_repo_licenses": ["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.037037037, "max_line_length": 90, "alphanum_fraction": 0.518622449, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7767780119717866}}
{"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\u2080) = p\u2080 + 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\u2080; abstol=1e-8, maxiter=50)\n    x\u2099 = Float64(x\u2080)\n    f\u2099\u208a\u2081 = x - f / Symbolics.derivative(f, x)\n\n    for i = 1:maxiter\n        x\u2099\u208a\u2081 = substitute(f\u2099\u208a\u2081, Dict(x => x\u2099))\n        if abs(x\u2099\u208a\u2081 - x\u2099) < abstol\n            return x\u2099\u208a\u2081\n        else\n            x\u2099 = x\u2099\u208a\u2081\n        end\n    end\n    return x\u2099\u208a\u2081\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\u02cdt = string(s)\n        name_without\u02cdt = replace(name_with\u02cdt, r\"\\(.*\\)\" => \"\")\n\n        if haskey(d, name_with\u02cdt)\n            u0[s] = d[name_with\u02cdt]\n        elseif haskey(d, name_without\u02cdt)\n            u0[s] = d[name_without\u02cdt]\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 \u03f5 z a[1:n]\n    x = def_taylor(\u03f5, a, 1)\n    eq = x^5 + \u03f5*x - 1\n    eqs = collect_powers(eq, \u03f5, 1:n)\n    vals = solve_coef(eqs, a)\n\n    x\u2032 = substitute(x, vals)\n    X = \ud835\udf00 -> substitute(x\u2032, Dict(\u03f5 => \ud835\udf00))\n\n    x\u209a = X(1.0)\n    x\u2099 = solve_newton(z^5 + z - 1, z, 1.0)\n\n    return x\u209a, x\u2099\nend\n\n\"\"\"\n    E - e * sin(E) = M\n\"\"\"\nfunction test_kepler(n=4)\n    @variables \u03f5 z M a[1:n]\n    x = def_taylor(\u03f5, a, M)\n    eq = x - \u03f5 * expand_sin(x, n) - M\n    eqs = collect_powers(eq, \u03f5, 1:n)\n    vals = solve_coef(eqs, a)\n\n    x\u2032 = substitute(x, vals)\n    X = (\ud835\udf00, \ud835\udc40) -> substitute(x\u2032, Dict(\u03f5 => \ud835\udf00, M => \ud835\udc40))\n\n    \ud835\udc52 = 0.01671    # The Earth eccentricity\n    M\u2080 = \u03c0/2\n\n    x\u209a = X(\ud835\udc52, M\u2080)\n    x\u2099 = solve_newton(z - \ud835\udc52*sin(z) - M\u2080, z, M\u2080)\n\n    return x\u209a, x\u2099\nend\n\nfunction test_rocket(n=3)\n    sys, y = calc_rocket_sys(n)\n    u0 = calc_u0(sys, Dict(\"y\u2081\u02cdt\" => 1.0))\n    prob = ODEProblem(sys, u0, (0, 3.0))\n    sol = solve(prob; dtmax=0.01)\n    X = \ud835\udf00 -> sum([\ud835\udf00^(i-1) * sol[y[i]] for i in eachindex(y)])\n    plot(sol.t, hcat([X(\u03f5) for \u03f5 = 0.0:0.1:0.5]...))\nend\n\nfunction calc_rocket_sys(n)\n    @variables \u03f5 t y[1:n](t) \u2202\u2202y[1:n]\n    x = def_taylor(\u03f5, y[2:end], y[1])\n    \u2202\u2202x = def_taylor(\u03f5, \u2202\u2202y[2:end], \u2202\u2202y[1])\n    eq = \u2202\u2202x * (1 + \u03f5*x)^2 + 1\n    eqs = collect_powers(eq, \u03f5, 0:n)\n    vals = solve_coef(eqs, \u2202\u2202y)\n\n    D = Differential(t)\n    subs = Dict(\u2202\u2202y[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\u2081\u02cdt\" => 1.0))\n    prob = ODEProblem(sys, u0, (0, 50.0))\n    sol = solve(prob; dtmax=0.01)\n\n    X = \ud835\udf00 -> sum([\ud835\udf00^(i-1) * sol[y[i]] for i in eachindex(y)])\n    T = sol.t\n    Y = \ud835\udf00 -> exp.(-\ud835\udf00*T) .* sin.(sqrt(1 - \ud835\udf00^2)*T) / sqrt(1 - \ud835\udf00^2)    # exact solution\n\n    plot(sol.t, [Y(0.1), X(0.1)])\nend\n\nfunction calc_oscillator_sys(n)\n    @variables \u03f5 t y[1:n](t) \u2202y[1:n] \u2202\u2202y[1:n]\n    x = def_taylor(\u03f5, y[2:end], y[1])\n    \u2202x = def_taylor(\u03f5, \u2202y[2:end], \u2202y[1])\n    \u2202\u2202x = def_taylor(\u03f5, \u2202\u2202y[2:end], \u2202\u2202y[1])\n\n    eq = \u2202\u2202x + 2*\u03f5*\u2202x + x\n    eqs = collect_powers(eq, \u03f5, 0:n)\n    vals = solve_coef(eqs, \u2202\u2202y)\n\n    D = Differential(t)\n    subs1 = Dict(\u2202y[i] => D(y[i]) for i in eachindex(y))\n    subs2 = Dict(\u2202\u2202y[i] => D(D(y[i])) for i in eachindex(y))\n    subs = subs1 \u222a 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# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    Center()\n\nApplies the center transform to all columns of the table.\nThe center transform of the column `x`, with mean `\u03bc`,\nis defined by `x .- \u03bc`.\n\"\"\"\nstruct Center <: Colwise end\n\nassertions(::Type{Center}) = [assert_continuous]\n\nisrevertible(::Type{Center}) = true\n\ncolcache(::Center, x) = mean(x)\n\ncolapply(::Center, x, \u03bc)  = @. x - \u03bc\n\ncolrevert(::Center, y, \u03bc) = @. y + \u03bc\n", "meta": {"hexsha": "63dde83aa9962fb34f4a0f463933ba22501e3170", "size": 590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/center.jl", "max_stars_repo_name": "ceferisbarov/TableTransforms.jl", "max_stars_repo_head_hexsha": "988265e6c7460e1d08c8f79fccd8301a840ba5c7", "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/center.jl", "max_issues_repo_name": "ceferisbarov/TableTransforms.jl", "max_issues_repo_head_hexsha": "988265e6c7460e1d08c8f79fccd8301a840ba5c7", "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/center.jl", "max_forks_repo_name": "ceferisbarov/TableTransforms.jl", "max_forks_repo_head_hexsha": "988265e6c7460e1d08c8f79fccd8301a840ba5c7", "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": 25.652173913, "max_line_length": 68, "alphanum_fraction": 0.506779661, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7767780086087376}}
{"text": "# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# Desription\n# ==============================================================================\n#\n#   Tests related to the function `create_rotation_matrix`.\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# File: ./src/dcm.jl\n# ==================\n\n# Functions: create_rotation_matrix\n# ---------------------------------\n\n@testset \"Function create_rotation_matrix (Float64)\" begin\n    # Sample an angle to use in all rotations.\n    ang = _rand_ang()\n\n    # Rotations\n    # =========\n\n    # X Axis\n    # ------\n\n    # Create a DCM that rotates about X axis.\n    dcm = create_rotation_matrix(ang, :X)\n    @test eltype(dcm) === Float64\n\n    # Create a vector that does not have X component.\n    v = SVector(0, randn(), randn())\n\n    # Rotate the reference using the DCM.\n    v_r = dcm * v\n    @test eltype(v_r) === Float64\n\n    # Get the sine of the angle between the representations.\n    sin_ang = ((v_r \u00d7 v) / norm(v)^2)[1]\n\n    # Test the angle between the two representations.\n    @test abs(sin(ang) - sin_ang) \u2248 0 atol = 1e-12\n\n    # Y Axis\n    # ------\n\n    # Create a DCM that rotates about Y axis.\n    dcm = create_rotation_matrix(ang, :Y)\n    @test eltype(dcm) === Float64\n\n    # Create a vector that does not have Y component.\n    v = SVector(randn(), 0, randn())\n\n    # Rotate the reference using the DCM.\n    v_r = dcm * v\n    @test eltype(v_r) === Float64\n\n    # Get the sine of the angle between the representations.\n    sin_ang = ((v_r \u00d7 v) / norm(v)^2)[2]\n\n    # Test the angle between the two representations.\n    @test abs(sin(ang) - sin_ang) \u2248 0 atol = 1e-12\n\n    # Z Axis\n    # ------\n\n    # Create a DCM that rotates about Z axis.\n    dcm = create_rotation_matrix(ang, :Z)\n    @test eltype(dcm) === Float64\n\n    # Create a vector that does not have Z component.\n    v = SVector(randn(), randn(), 0)\n\n    # Rotate the reference using the DCM.\n    v_r = dcm * v\n    @test eltype(v_r) === Float64\n\n    # Get the sine of the angle between the representations.\n    sin_ang = ((v_r \u00d7 v) / norm(v)^2)[3]\n\n    # Test the angle between the two representations.\n    @test abs(sin(ang) - sin_ang) \u2248 0 atol = 1e-12\nend\n\n@testset \"Function create_rotation_matrix (Float32)\" begin\n    # Sample an angle to use in all rotations.\n    ang = _rand_ang(Float32)\n\n    # Rotations\n    # =========\n\n    # X Axis\n    # ------\n\n    # Create a DCM that rotates about X axis.\n    dcm = create_rotation_matrix(ang, :X)\n    @test eltype(dcm) === Float32\n\n    # Create a vector that does not have X component.\n    v = SVector{3, Float32}(0, randn(), randn())\n\n    # Rotate the reference using the DCM.\n    v_r = dcm * v\n    @test eltype(v_r) === Float32\n\n    # Get the sine of the angle between the representations.\n    sin_ang = ((v_r \u00d7 v) / norm(v)^2)[1]\n\n    # Test the angle between the two representations.\n    @test abs(sin(ang) - sin_ang) \u2248 0 atol = 1e-6\n\n    # Y Axis\n    # ------\n\n    # Create a DCM that rotates about Y axis.\n    dcm = create_rotation_matrix(ang, :Y)\n    @test eltype(dcm) === Float32\n\n    # Create a vector that does not have Y component.\n    v = SVector{3, Float32}(randn(), 0, randn())\n\n    # Rotate the reference using the DCM.\n    v_r = dcm * v\n    @test eltype(v_r) === Float32\n\n    # Get the sine of the angle between the representations.\n    sin_ang = ((v_r \u00d7 v) / norm(v)^2)[2]\n\n    # Test the angle between the two representations.\n    @test abs(sin(ang) - sin_ang) \u2248 0 atol = 1e-6\n\n    # Z Axis\n    # ------\n\n    # Create a DCM that rotates about Z axis.\n    dcm = create_rotation_matrix(ang, :Z)\n    @test eltype(dcm) === Float32\n\n    # Create a vector that does not have Z component.\n    v = SVector{3, Float32}(randn(), randn(), 0)\n\n    # Rotate the reference using the DCM.\n    v_r = dcm * v\n    @test eltype(v_r) === Float32\n\n    # Get the sine of the angle between the representations.\n    sin_ang = ((v_r \u00d7 v) / norm(v)^2)[3]\n\n    # Test the angle between the two representations.\n    @test abs(sin(ang) - sin_ang) \u2248 0 atol = 1e-6\nend\n\n@testset \"Function create_rotation_matrix (Errors)\" begin\n    @test_throws ArgumentError create_rotation_matrix(0, :A)\nend\n", "meta": {"hexsha": "43c963b815570498449e1bc82ab68022e9049bf0", "size": 4208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dcm/create_rotation_matrix.jl", "max_stars_repo_name": "ChrisRackauckas/ReferenceFrameRotations.jl", "max_stars_repo_head_hexsha": "eded8889b66537e0907398ac53299587f8839d69", "max_stars_repo_licenses": ["MIT"], "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/dcm/create_rotation_matrix.jl", "max_issues_repo_name": "ChrisRackauckas/ReferenceFrameRotations.jl", "max_issues_repo_head_hexsha": "eded8889b66537e0907398ac53299587f8839d69", "max_issues_repo_licenses": ["MIT"], "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/dcm/create_rotation_matrix.jl", "max_forks_repo_name": "ChrisRackauckas/ReferenceFrameRotations.jl", "max_forks_repo_head_hexsha": "eded8889b66537e0907398ac53299587f8839d69", "max_forks_repo_licenses": ["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.1483870968, "max_line_length": 80, "alphanum_fraction": 0.5743821293, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7767780080147159}}
{"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(\u03c3::Real, \u03b8::Real, l = 4 * ceil(Int,\u03c3) + 1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = \u03c3 == 0 ? [1f0] : [exp(-x*cos(\u03b8) / (2f0 * \u03c3)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_pv(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = \u03c3 == 0 ? [1f0] : [exp(-x*sin(\u03b8)/(2f0*\u03c3)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_mh(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = \u03c3 == 0 ? [1f0] : [exp(x*cos(\u03b8)/(2f0*\u03c3)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_mv(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = \u03c3 == 0 ? [1f0] : [exp(x*sin(\u03b8)/(2f0*\u03c3)) for x=-w:w]\n    centered(g/sum(g))\nend\n\nfunction kern_d_p(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n    kern_d_pv(\u03c3, \u03b8, l) .* transpose(kern_d_ph(\u03c3, \u03b8, l))\nend\n\nfunction kern_d_m(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n    kern_d_mv(\u03c3, \u03b8, l) .* transpose(kern_d_mh(\u03c3, \u03b8, l))\nend\n\nfunction kern_d(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n    kern_d_p(\u03c3, \u03b8, l).-kern_d_m(\u03c3, \u03b8, l)\nend\n\n\n# function kern_d(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n#     relu.(kern_d(\u03c3, \u03b8, l)) .- relu.(-1 .*(kern_d(\u03c3, \u03b8, l)))\n# end\n\nfunction kern_b(\u03c3::Real, \u03b8::Real, l = 4*ceil(Int,\u03c3)+1)\n    relu.(kern_d(\u03c3, \u03b8, l)) .+ relu.(-1f0 .*(kern_d(\u03c3, \u03b8, l)))\nend\n\n\n\n\nfunction gaussian_rot(\u03c3_x::Real, \u03c3_y::Real, \u03b8::Real, l = 4*ceil(Int, max(\u03c3_a,\u03c3_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 \u03c3_x or/and \u03c3_y == 0\n    for x \u2208 -w:w, y \u2208 -w:w\n        g[x,y] = exp(-1f0/2f0*((((x*cos(\u03b8)-y*sin(\u03b8))/\u03c3_x)^2f0)+(((x*sin(\u03b8)+y*cos(\u03b8))/\u03c3_y)^2f0)))\n    end\n    centered(g/sum(g))\nend\n\n\n\n# Rotating function\nfunction fun_R(x,y,\u03b8)\n    x*cos(\u03b8)-y*sin(\u03b8), x*sin(\u03b8)+y*cos(\u03b8)\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": "using SeisProcessing\nusing Test\n\nnt=250;\ndt=0.004;\nnx=30;\ndx=5;\n\nparam = Dict(:nt=>nt, :dt=>dt,:nx1=>nx,:dx1=>dx,\n              :p1=>[0.0003, -0.0005, 0.000], :p2=>[0,0,0],:p3=>[0,0,0],:p4=>[0,0,0],\n              :tau=>[0.3, 0.4,0.5], :amp=>[ -1.0, 0.7,1],:f0=>20);\n\n\nd=SeisLinearEvents(;param...);\n\nh = collect(0:nx-1)*dx;\n\n\n# 2- Define linear moveouts p\npmin = -2*dt/dx;\npmax = 2*dt/dx;\nnp = 60\ndp = (pmax-pmin)/(np-1)\np = collect(pmin:dp:pmax);\n\n# 3- Transform to Radon domain\n\nm = SeisRadonFreqInv(d, order=\"linear\", dt=dt, h=h, p=p, flow=2, fhigh=80,\n                     mu=0.00001 )\n\n# 4- Transform back to data domain\nd2 = SeisRadonFreqFor(m, nt, order=\"linear\", dt=dt, h=h, p=p, flow=2, fhigh=80)\n\n# 5- Calculate and print modeling error (%)\ne2 = 100*(sum((d-d2).^2))/sum(d.^2);\nprintln(\"Relative error = \", e2, \" %\")\n@test e2 < 0.1\n", "meta": {"hexsha": "e8524ae7e1d2b54ab36ce9b2d92908a65baa1ce5", "size": 842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_radon.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": "test/test_radon.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": "test/test_radon.jl", "max_forks_repo_name": "fercarozzi/SeisProcessing.jl", "max_forks_repo_head_hexsha": "cf91516e0c45b4aba60bbb331eee1a0cb7acc896", "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": 22.1578947368, "max_line_length": 84, "alphanum_fraction": 0.5605700713, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7767514199318805}}
{"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 `\u03b1` of degree `p` at `x` using\nthe three term recursion.\n\"\"\"\nfunction gegenbauer(x, p::Integer, \u03b1)\n    T = typeof( 2\u03b1*x )\n    p\u2080 = one(T)\n    p\u2081 = 2\u03b1*x\n\n    if p <= 0\n        return p\u2080\n    elseif p == 1\n        return p\u2081\n    end\n\n    for n in 2:p\n        p\u2080, p\u2081 = p\u2081, ( 2x*(n+\u03b1-1)*p\u2081 - (2\u03b1+n-2)*p\u2080 ) / n\n    end\n\n    p\u2081\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: \u2202_t T = \u03b1 * \u2207\u00b2(T) + S, S = [\u03b2*sin(\u03b3*z), \u03b2]\n# Boundary conditions: \u2207T(z=a) = \u2207T_bottom, T(z=b) = T_top\nimport Plots\nusing LinearAlgebra\n\n# Note that we can stably take huge timesteps even when \u03b1 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\u0302_min, n\u0302_max = -1, 1            # Outward facing unit vectors\n\u03b1 = 100;                        # thermal diffusivity, larger means more stiff\n\u03b2, \u03b3 = 10000, \u03c0;                # source term coefficients\n\u0394t = 1000;                      # timestep\nN_t = 10;                       # number of timesteps\nFT = Float64;                   # float type\n\u0394z = FT(b-a)/FT(n)\n\u0394z\u00b2 = \u0394z^2;\n\u2207\u00b2_op = [1/\u0394z\u00b2, -2/\u0394z\u00b2, 1/\u0394z\u00b2]; # row or Laplacian operator\nT_init = 1;                     # Initial temperature, shouldn't matter for steady solution\n\u2207T_bottom = 10;                  # Temperature gradient at the top\nT_top = 1;                      # Temperature at the bottom\nuse_sin_forcing = true\nS(z) = use_sin_forcing ? \u03b2*sin(\u03b3*z) : \u03b2 # source term, (sin for easy integration)\nzf = range(a, b, length=n+1);\nzc = map(i-> zf[i]+\u0394z/2, 1:n);\n\n# Analytic steady state solution:\n# \u2202\u2202T\u2202\u2202z = -S(z)/\u03b1 = -\u03b2*sin(\u03b3*z)/\u03b1\n# \u2202T\u2202z = \u03b2*cos(\u03b3*z)/(\u03b3*\u03b1)+c1\n# T(z) = \u03b2*sin(\u03b3*z)/(\u03b3^2*\u03b1)+c1*z+c2 # generic solution\n# Apply bc: \u2202T\u2202z(a) = \u03b2*cos(\u03b3*a)/(\u03b3*\u03b1)+c1 = \u2207T_bottom => c1 = \u2207T_bottom-\u03b2*cos(\u03b3*a)/(\u03b3*\u03b1)\n# Apply bc: T(b) =    \u03b2*sin(\u03b3*b)/(\u03b3^2*\u03b1)+c1*b+c2 = T_top =>\n#         c2 = T_top-(\u03b2*sin(\u03b3*b)/(\u03b3^2*\u03b1)+c1*b)\nfunction T_analytic_sin(z)\n    c1 = \u2207T_bottom-\u03b2*cos(\u03b3*a)/(\u03b3*\u03b1)\n    c2 = T_top-(\u03b2*sin(\u03b3*b)/(\u03b3^2*\u03b1)+c1*b)\n    return \u03b2*sin(\u03b3*z)/(\u03b3^2*\u03b1)+c1*z+c2\nend\n\n# Analytic steady state solution:\n# \u2202\u2202T\u2202\u2202z = -S(z)/\u03b1 = -\u03b2/\u03b1\n# \u2202T\u2202z = -z*\u03b2/\u03b1+c1\n# T(z) = -\u03b2*z^2/(2*\u03b1)+c1*z+c2 # generic solution\n# Apply bc: \u2202T\u2202z(a) = -a*\u03b2/\u03b1+c1 = \u2207T_bottom => c1 = \u2207T_bottom+a*\u03b2/\u03b1\n# Apply bc: T(b) =    -\u03b2*b^2/(2*\u03b1)+c1*b+c2 = T_top =>\n#         c2 = T_top-(-\u03b2*b^2/(2*\u03b1)+c1*b)\nfunction T_analytic_uniform(z)\n    c1 = \u2207T_bottom+a*\u03b2/\u03b1\n    c2 = T_top-(-\u03b2*b^2/(2*\u03b1)+c1*b)\n    return -\u03b2*z^2/(2*\u03b1)+c1*z+c2\nend\n\nT_analytic(z) =\n    use_sin_forcing ? T_analytic_sin(z) : T_analytic_uniform(z)\n\n#####\n##### T \u2208 cell centers, \u2207T \u2208 cell faces\n#####\nprintln(\"Solve for T \u2208 cell centers\")\nT = zeros(FT, n);\n\n# Equations: derivation to matrix form\n# \u2202_t T = \u03b1 * \u2207\u00b2(T) + S\n# (T^{n+1}-T^n) = \u0394t (\u03b1 * \u2207\u00b2(T^{n+1}) + S)\n# (T^{n+1} - \u0394t \u03b1 * \u2207\u00b2(T^{n+1})) = T^n + \u0394t*S\n# (I - \u0394t \u03b1 * \u2207\u00b2) T^{n+1} = T^n + \u0394t*S\n\n# Derive Dirichlet boundary stencil & source:\n# \u2202_t T = \u03b1 * (T[i-1]+T[g]-2*T[i])/\u0394z\u00b2 + S\n# \u2202_t T = \u03b1 * (T[i-1]+(2 T[b] - T[i])-2*T[i])/\u0394z\u00b2 + S\n# \u2202_t T = \u03b1 * (T[i-1]-3*T[i])/\u0394z\u00b2 + S + \u03b1 * (2 T[b])/\u0394z\u00b2\n\n# Derive Neumann boundary stencil & source:\n# \u2207T_bottom*n\u0302 = (T[g] - T[i])/\u0394z,     n\u0302 = [-1,1] \u2208 [zmin,zmax]\n# \u2207T_bottom*n\u0302 = -(T[i] - T[g])/\u0394z,    n\u0302 = [-1,1] \u2208 [zmin,zmax]\n# \u2202_t T = \u03b1 * ((T[ii] - T[i])/\u0394z - (T[i] - T[g])/\u0394z)/\u0394z + S\n# \u2202_t T = \u03b1 * ((T[ii] - T[i])/\u0394z + \u2207T_bottom*n\u0302)/\u0394z + S\n# \u2202_t T = \u03b1 * (T[ii] - T[i])/\u0394z\u00b2 + S + \u03b1*\u2207T_bottom*n\u0302/\u0394z\n\n# Note that size(A) = (n,n) due to 1 Dirichlet and 1 Neumann.\n\u2207\u00b2 = Tridiagonal(\n    ones(FT, n-1) .* \u2207\u00b2_op[1],\n    ones(FT, n)   .* \u2207\u00b2_op[2],\n    ones(FT, n-1) .* \u2207\u00b2_op[3]\n);\n# Modify boundary stencil to account for BC\n\u2207\u00b2.d[1] = -1/\u0394z\u00b2\n\u2207\u00b2.d[end] = -3/\u0394z\u00b2\n\nA = LinearAlgebra.I - \u0394t.* \u03b1 .* \u2207\u00b2\n\n# Compute boundary sources: \u03b1 * (2 T[b])/\u0394z\u00b2, \u03b1 * \u2207T_bottom*n\u0302/\u0394z\nAT_b = zeros(FT, n);\nAT_b[1] = \u03b1*\u2207T_bottom*n\u0302_min/\u0394z;\nAT_b[end] = \u03b1*2*T_top/\u0394z\u00b2;\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 .+ \u0394t .* (S.(zc) .+ AT_b)\n    T_new = A \\ b_rhs\n    \u0394T_norm = sum(T .- T_new)/length(T)\n    @show \u0394T_norm # watch \u0394T 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# \u2207T_bottom*n\u0302 = (T[g] - T[i])/\u0394z, T[g] = 2*T[b] - T[i]\n# \u2207T_bottom*n\u0302 = ((2*T[b] - T[i]) - T[i])/\u0394z\n# \u0394z*\u2207T_bottom*n\u0302 = 2*T[b] - 2*T[i]\n# (\u0394z*\u2207T_bottom*n\u0302 + 2*T[i])/2 = T[b]\nTf[1] = (\u0394z*\u2207T_bottom*n\u0302_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 \u2208 cell centers\")\n\np3 = Plots.plot(zf, abs.(Tf .- T_analytic.(zf)), label=\"error\", markershape=:circle, markersize=6)\np3 = Plots.plot!(p3, title=\"T \u2208 cell centers\")\n\n#####\n##### T \u2208 cell faces, \u2207T \u2208 cell centers\n#####\n\nprintln(\"Solve for T \u2208 cell faces\")\nT = zeros(FT, n+1);\n\n# Equations: derivation to matrix form\n# \u2202_t T = \u03b1 * \u2207\u00b2(T) + S\n# (T^{n+1}-T^n) = \u0394t (\u03b1 * \u2207\u00b2(T^{n+1}) + S)\n# (T^{n+1} - \u0394t \u03b1 * \u2207\u00b2(T^{n+1})) = T^n + \u0394t*S\n# (I - \u0394t \u03b1 * \u2207\u00b2) T^{n+1} = T^n + \u0394t*S\n\n# Derive Dirichlet boundary stencil & source:\n# \u2202_t T = \u03b1 * (T[i-1]+T[b]-2*T[i])/\u0394z\u00b2 + S\n# \u2202_t T = \u03b1 * (T[i-1]-2*T[i])/\u0394z\u00b2 + S + \u03b1 * T[b] / \u0394z\u00b2\n\n# Derive Neumann boundary stencil & source:\n# \u2207T_bottom*n\u0302= (T[g] - T[i])/(2\u0394z),     n\u0302 = [-1,1] \u2208 [zmin,zmax]\n# T[i] + 2*\u0394z*\u2207T_bottom*n\u0302 = T[g]\n# \u2202_t T = \u03b1 * (((T[i] + 2*\u0394z*\u2207T_bottom*n\u0302) - T[b])/\u0394z - (T[b] - T[i])/\u0394z)/\u0394z + S\n# \u2202_t T = \u03b1 * (((T[i]) - T[b])/\u0394z - (T[b] - T[i])/\u0394z)/\u0394z + S + \u03b1/\u0394z\u00b2*2*\u0394z*\u2207T_bottom*n\u0302\n# \u2202_t T = \u03b1 * (2*T[i] - 2*T[b])/\u0394z\u00b2 + S + 2\u03b1/\u0394z*\u2207T_bottom*n\u0302\n\n# Note that size(A) = (n,n) due to 1 Dirichlet and 1 Neumann.\n\u2207\u00b2 = Tridiagonal(\n    ones(FT, n) .* \u2207\u00b2_op[1],\n    ones(FT, n+1)   .* \u2207\u00b2_op[2],\n    ones(FT, n) .* \u2207\u00b2_op[3]\n);\n\n# Modify boundary stencil to account for BCs\n\u2207\u00b2.d[1] = -2/\u0394z\u00b2\n\u2207\u00b2.du[1] = +2/\u0394z\u00b2\n\n# Modify boundary stencil to account for BCs\n\u2207\u00b2.du[n] = 0  # modified stencil\n\u2207\u00b2.d[n+1] = 0 # to ensure `\u2202_t T = 0` at `z=zmax`\n\u2207\u00b2.dl[n] = 0  # to ensure `\u2202_t T = 0` at `z=zmax`\n\nA = LinearAlgebra.I - \u0394t.* \u03b1 .* \u2207\u00b2\n\n# Compute boundary source: \u03b1 * T[b] / \u0394z\u00b2\nAT_b = zeros(FT, n+1);\nAT_b[1] = \u03b1*2/\u0394z*\u2207T_bottom*n\u0302_min;\nAT_b[end-1] = \u03b1*T_top/\u0394z\u00b2;\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 .+ \u0394t .* (S.(zf) .+ AT_b)\n    T_new = A \\ b_rhs\n    \u0394T_norm = sum(T .- T_new)/length(T)\n    @show \u0394T_norm # watch \u0394T 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 \u2208 cell faces\")\n\np4 = Plots.plot(zf, abs.(T .- T_analytic.(zf)), label=\"error\", markershape=:circle, markersize=6)\np4 = Plots.plot!(p4, title=\"T \u2208 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# \u0394u + k^2u = 0,\n# u|\u0393 = 0,\n# u^i = e^{im k x\u22c5d},\n# u = u^i + u^s.\n# The normal derivative \u2202u/\u2202n of the entire wave is calculated on the sound-soft boundaries.\n# The scattered wave is calculated by convolving [\u2202u/\u2202n] 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\u03c9 = 2\u03c0\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)+\u03b3)/2/\u03c0 + im/4 : im/4*hankelh1(0,k*abs(y-x)) - g1(x,y).*logabs(y-x)/\u03c0\n\n\n# A variety of domains.\n\n#dom = Circle(0.0,1/\u03c0)\u222aSegment(-1.0im,1.0)\n#dom = \u222a(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 = \u222a(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 = \u222a(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 = \u222a(Circle.([0.,-1.0im],[0.5,0.25]))\u222a(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\u2297sp,0)\nui\u0393,\u2a0d = Fun(t->ui(real(t),imag(t)),sp),DefiniteLineIntegral(dom)\n\n@time G = GreensFun(g1,cwsp;method=:Cholesky) + GreensFun(g2,sp\u2297sp;method=:Cholesky)\n\n@time \u2202u\u2202n = \u2a0d[G]\\ui\u0393\nprintln(\"The length of \u2202u\u2202n is: \",ncoefficients(\u2202u\u2202n))\nus = (x,y) -> -logkernel(g1,\u2202u\u2202n,complex(x,y))-linesum(g2,\u2202u\u2202n,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": "module BezierRefFEsTests\n\nusing Gridap\n\nusing Gridap.ReferenceFEs\nusing Gridap.Polynomials\nusing Gridap.Fields\nusing Gridap.Arrays\nusing FillArrays\n\nusing Test\n\nusing Gridap.ReferenceFEs: _berstein_matrix\nusing Gridap.ReferenceFEs: berstein_basis\nusing Gridap.ReferenceFEs: rationalize_bernstein_basis\n\n## Test Bernstein basis\n\np_filter(e,o) = sum(e) \u2264 o\n\n# 1D\np = 2\nprebasis_seg = MonomialBasis{1}(Float64,p,p_filter)\nC = _berstein_matrix(prebasis_seg,SEGMENT)\nC12 =\n[\n 1  -2   1\n 0   2  -2\n 0   0   1\n]\n\n@test transpose(C) == C12\n\n\u03d5 = berstein_basis(prebasis_seg,SEGMENT)\nX = [ Point(0.0,0.0), Point(0.5,0.5), Point(1.0,0.0) ]\n\u03c8 = linear_combination(X,\u03d5)\n\u03be = [Point(0.0),Point(0.5),Point(1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == [ Point(0.0,0.0), Point(0.5,0.25), Point(1.0,0.0) ]\n\np = 3\nprebasis_seg = MonomialBasis{1}(Float64,p,p_filter)\nC = _berstein_matrix(prebasis_seg,SEGMENT)\nC13 =\n[\n 1  -3   3  -1\n 0   3  -6   3\n 0   0   3  -3\n 0   0   0   1\n]\n\n@test transpose(C) == C13\n\n\u03d5 = berstein_basis(prebasis_seg,SEGMENT)\nX = [ Point(0.0,0.0), Point(0.25,0.5), Point(0.75,0.5), Point(1.0,0.0) ]\n\u03c8 = linear_combination(X,\u03d5)\n\u03be = [Point(0.0),Point(0.5),Point(1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == [ Point(0.0,0.0), Point(0.5,0.375), Point(1.0,0.0) ]\n\n# 2D\n\np = 2\nprebasis_tri = MonomialBasis{2}(Float64,p,p_filter)\nC = _berstein_matrix(prebasis_tri,TRI)\nC22 =\n[\n 1  -2   1  -2   2   1\n 0   2  -2   0  -2   0\n 0   0   1   0   0   0\n 0   0   0   2  -2  -2\n 0   0   0   0   2   0\n 0   0   0   0   0   1\n]\n\n@test transpose(C) == C22\n\n\u03d5 = berstein_basis(prebasis_tri,TRI)\nX = [ Point(0.0,0.0), Point(0.5,0.0), Point(1.0,0.0), Point(0.0,0.5), Point(0.5,0.5), Point(0.0,1.0) ]\n\u03c8 = linear_combination(X,\u03d5)\n\u03be = [Point(0.0,0.0),Point(0.0,0.5),Point(0.3,0.3),Point(1.0,0.0),Point(0.0,1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be\n\np = 3\nprebasis_tri = MonomialBasis{2}(Float64,p,p_filter)\nC = _berstein_matrix(prebasis_tri,TRI)\nC23 =\n[\n 1  -3   3  -1  -3   6  -3   3  -3  -1\n 0   3  -6   3   0  -6   6   0   3   0\n 0   0   3  -3   0   0  -3   0   0   0\n 0   0   0   1   0   0   0   0   0   0\n 0   0   0   0   3  -6   3  -6   6   3\n 0   0   0   0   0   6  -6   0  -6   0\n 0   0   0   0   0   0   3   0   0   0\n 0   0   0   0   0   0   0   3  -3  -3\n 0   0   0   0   0   0   0   0   3   0\n 0   0   0   0   0   0   0   0   0   1\n]\n\n@test transpose(C) == C23\n\n\nX = [\n  Point(0.0,0.0), Point(0.25,0.0), Point(0.75,0.0), Point(1.0,0.0),\n  Point(0.0,0.25), Point(0.25,0.25), Point(0.75,0.25),\n  Point(0.0,0.75), Point(0.25,0.75),\n  Point(0.0,1.0) ]\n\u03d5 = berstein_basis(prebasis_tri,TRI)\n\u03c8 = linear_combination(X,\u03d5)\n\u03be = [Point(0.0,0.0),Point(0.0,0.5),Point(0.5,0.5),Point(1.0,0.0),Point(0.0,1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be\n\n## BezierRefFE\n\ntri = BezierRefFE(Float64,TRI,(3,3))\nnodes = get_node_coordinates(tri) * 5\n\u03d5 = get_shapefuns(tri)\n\u03c8 = linear_combination(nodes,\u03d5)\n\u03be = [Point(0.0,0.0),Point(0.0,0.5),Point(0.5,0.5),Point(1.0,0.0),Point(0.0,1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be.*5\n\nf = ConstantField(1)\nq = Quadrature(TRI,3*2)\np = get_coordinates(q)\nw = get_weights(q)\nJ = \u2207(\u03c8)\n\n@test integrate(f,p,w,J) \u2248 (5*5)/2\n\ntri = BezierRefFE(Float64,TRI,(3,3))\nnodes = get_node_coordinates(tri)\nnodes[10] = Point(0.1,0.1)\n\u03d5 = get_shapefuns(tri)\n\u03c8 = linear_combination(nodes,\u03d5)\n\u03be = [Point(0.0,0.0),Point(0.0,0.5),Point(0.5,0.5),Point(1.0,0.0),Point(0.0,1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be\n\nf = ConstantField(1)\nq = Quadrature(TRI,3*2)\np = get_coordinates(q)\nw = get_weights(q)\nJ = \u2207(\u03c8)\n\n@test integrate(f,p,w,J) \u2248 1/2\n\ntri = BezierRefFE(Float64,TRI,(3,3))\nnodes = get_node_coordinates(tri)\nnodes[4] = Point(1/3,-0.1)\nnodes[5] = Point(2/3,-0.1)\n\u03d5 = get_shapefuns(tri)\n\u03c8 = linear_combination(nodes,\u03d5)\nf = ConstantField(1)\nq = Quadrature(TRI,3*2)\np = get_coordinates(q)\nw = get_weights(q)\nJ = \u2207(\u03c8)\n\n@test integrate(f,p,w,J) > 1/2\n\ntet = BezierRefFE(Float64,TET,(3,3,3))\nnodes = get_node_coordinates(tet) .* 5\n\u03d5 = get_shapefuns(tet)\n\u03c8 = linear_combination(nodes,\u03d5)\n\u03be = [Point(0.0,0.0,0.0),Point(0.0,0.0,0.5),Point(0.5,0.5,0.5),Point(1.0,0.0,0.0),Point(0.0,1.0,0.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be .* 5\n\nf = ConstantField(1)\nq = Quadrature(TET,3*2)\np = get_coordinates(q)\nw = get_weights(q)\nJ = \u2207(\u03c8)\n\n@test integrate(f,p,w,J) \u2248 (5*5*5)/6\n\nquad = BezierRefFE(Float64,QUAD,(3,3))\nnodes = get_node_coordinates(quad) .* 5\n\u03d5 = get_shapefuns(quad)\n\u03c8 = linear_combination(nodes,\u03d5)\n\u03be = [Point(0.0,0.0),Point(0.0,0.5),Point(1.0,0.5),Point(1.0,0.0),Point(0.0,1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be .* 5\n\nf = ConstantField(1)\nq = Quadrature(QUAD,3*2)\np = get_coordinates(q)\nw = get_weights(q)\nJ = \u2207(\u03c8)\n\n@test integrate(f,p,w,J) \u2248 (5*5)\n\nhex = BezierRefFE(Float64,HEX,(3,3,3))\nnodes = get_node_coordinates(hex) .* 5\n\u03d5 = get_shapefuns(hex)\n\u03c8 = linear_combination(nodes,\u03d5)\n\u03be = [Point(0.0,0.0,0.0),Point(0.0,0.0,0.5),Point(0.5,1.0,0.5),Point(1.0,0.0,0.0),Point(0.0,1.0,0.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be .* 5\n\nf = ConstantField(1)\nq = Quadrature(HEX,3*2)\np = get_coordinates(q)\nw = get_weights(q)\nJ = \u2207(\u03c8)\n\n@test integrate(f,p,w,J) \u2248 (5*5*5)\n\ntri = ReferenceFE(TRI,bezier,Float64,(3,3))\n_tri = BezierRefFE(Float64,TRI,(3,3))\n\n@test tri == _tri\n\n\ntri = BezierRefFE(Float64,TRI,(3,3))\n\u03d5 = get_shapefuns(tri)\nw = ones(length(\u03d5))\n\u03d5r = rationalize_bernstein_basis(\u03d5,w)\nnodes = get_node_coordinates(tri)\n\u03c8 = linear_combination(nodes,\u03d5r)\n\u03be = [Point(0.0,0.0),Point(0.0,0.5),Point(0.5,0.5),Point(1.0,0.0),Point(0.0,1.0)]\n\u03a8 = Fill(\u03c8,length(\u03be))\nXi = lazy_map( evaluate, \u03a8, \u03be )\n\n@test Xi == \u03be\n\n\nreffe = BezierRefFE(Float64,SEGMENT,(3,))\ntest_lagrangian_reference_fe(reffe)\n\nreffe = BezierRefFE(Float64,TRI,(3,3))\ntest_lagrangian_reference_fe(reffe)\n\nreffe = BezierRefFE(Float64,TET,(3,3,3))\ntest_lagrangian_reference_fe(reffe)\n\nend # module\n", "meta": {"hexsha": "483cdfad81b03fdaa4ebd70ece30c77817643326", "size": 6012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ReferenceFEsTests/BezierRefFEsTests.jl", "max_stars_repo_name": "aerappa/Gridap.jl", "max_stars_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-03-18T06:52:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T11:01:18.000Z", "max_issues_repo_path": "test/ReferenceFEsTests/BezierRefFEsTests.jl", "max_issues_repo_name": "aerappa/Gridap.jl", "max_issues_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2019-03-17T12:26:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-13T14:53:34.000Z", "max_forks_repo_path": "test/ReferenceFEsTests/BezierRefFEsTests.jl", "max_forks_repo_name": "aerappa/Gridap.jl", "max_forks_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-17T12:23:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-17T12:23:55.000Z", "avg_line_length": 23.1230769231, "max_line_length": 102, "alphanum_fraction": 0.619594145, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7766160348348843}}
{"text": "# FeynmanTheory.jl\n\n\"\"\"\nfrohlichalpha(\u03b5_Inf,\u03b5_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(\u03b5_optic,\u03b5_static,freq,m_eff)\n    \u03c9=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\u03c0\u03f5_0).\n    \u03b1= 0.5/(4*\u03c0*\u03b5_0) *              # Units: m/F\n       (1/\u03b5_optic - 1/\u03b5_static) *   # Units: none\n       (q^2/(hbar*\u03c9)) *             # Units: F\n       sqrt(2*me*m_eff*\u03c9/\u0127)         # Units: 1/m\n    return (\u03b1)\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(\u03c4,v,w)=(w^2 * \u03c4 + (v^2-w^2)/v*(1-exp(-v*\u03c4)))^-0.5 * exp(-\u03c4)\n# (31) in Feynman I\nAF(v,w,\u03b1)=\u03c0^(-0.5) * \u03b1*v * quadgk(\u03c4->fF(\u03c4,v,w),0,Inf)[1]\n# (33) in Feynman I\nF(v,w,\u03b1)=(3/(4*v))*(v-w)^2-AF(v,w,\u03b1)\n\n# Let's wrap the Feynman athermal variation approximation in a simple function\n\"\"\"\n    feynmanvw(\u03b1; v=7.0, w=6.0)\n\n    Calculate v and w variational polaron parameters,\n    for the supplied \u03b1 Frohlich coupling.\n    This version uses the original athermal action (Feynman 1955).\n\tReturns v,w.\n\"\"\"\nfunction feynmanvw(\u03b1; 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],\u03b1) # 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,\u03b2)=3/\u03b2*( log(v/w) - 1/2*log(2*\u03c0*\u03b2) - log(sinh(v*\u03b2/2)/sinh(w*\u03b2/2)))\n# 62d\nY(x,v,\u03b2)=1/(1-exp(-v*\u03b2))*(1+exp(-v*\u03b2)-exp(-v*x)-exp(v*(x-\u03b2)))\n# 62c integrand\nf(x,v,w,\u03b2)=(exp(\u03b2-x)+exp(x))/(w^2*x*(1-x/\u03b2)+Y(x,v,\u03b2)*(v^2-w^2)/v)^(1/2)\n# 62c\nB(v,w,\u03b2,\u03b1) = \u03b1*v/(sqrt(\u03c0)*(exp(\u03b2)-1)) * quadgk(x->f(x,v,w,\u03b2),0,\u03b2/2)[1]\n# 62e\nC(v,w,\u03b2)=3/4*(v^2-w^2)/v * (coth(v*\u03b2/2)-2/(v*\u03b2))\n# 62a\nF(v,w,\u03b2,\u03b1)=-(A(v,w,\u03b2)+B(v,w,\u03b2,\u03b1)+C(v,w,\u03b2))\n\n# Can now evaluate, e.g.\n# F(v,w,\u03b2,\u03b1)=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(\u03b1, \u03b2red; v=7.1, w=6.5, verbose::Bool=false)\n\n    Calculate v and w variational polaron parameters,\n    for the supplied \u03b1 Frohlich coupling and \u03b2red reduced thermodynamic temperature.\n    This uses the Osaka finite temperature action.\n    Returns v,w.\n\"\"\"\nfunction feynmanvw(\u03b1, \u03b2red; 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],\u03b2red,\u03b1) # 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": "function neville_error(n::Int, F::Function)\n    #random polynomial coefficents\n    rng = MersenneTwister(n)\n    a = rand(rng, n)\n    #the polynomial\n    p(x) = sum(a[i]*x^(i-1) for i=1:n)\n    #samples\n    x = LinRange(-1, 1, n)\n    y = p.(x)\n    #closure\n    f(\u03be) = F(\u03be, x, y)\n    #maximum error in [-1,1]\n    \u03be = -1:0.001:1\n    maximum( @. abs(p(\u03be) - f(\u03be)) )\nend\n\n#simple checks on polynomial interpolation accuracy\n@test neville_error(3, quadratic) < 1e-3\n@test neville_error(4, cubic) < 1e-3\n@test neville_error(5, neville) < 1e-3\n@test neville_error(6, neville) < 1e-3", "meta": {"hexsha": "690bb93bd3cfd48904cbd431cfed1d7cceda0348", "size": 572, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_nevilles.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": "test/test_nevilles.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": "test/test_nevilles.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": 27.2380952381, "max_line_length": 51, "alphanum_fraction": 0.6118881119, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7766000115556669}}
{"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 = \u03b8 -> portfolio_moments(\u03b8, 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": "using QuantileRegression\nusing DataFrames\ncd(Pkg.dir(\"QuantileRegression\")*\"/examples\")\ndf = readtable(\"engel.csv\")\n\n\nout_ip = qreg(foodexp~income, df, IP()) # or just qreg(foodexp~income, df)\nout_irls = qreg(foodexp~income, df, IRLS())\n\nprintln(\"...... Interior point ......\")\nprintln(out_ip)\nprintln(\".......... IRLS ............\")\nprintln(out_irls)\n", "meta": {"hexsha": "af27b98202e10aa2ab2c7d03528e6e9b83563137", "size": 352, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/qreg_and_ip_ex.jl", "max_stars_repo_name": "tbeason/QuantileRegression.jl", "max_stars_repo_head_hexsha": "96b20e99e958ddda6890a6d0506cf8a3005bc136", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-23T00:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T00:32:13.000Z", "max_issues_repo_path": "examples/qreg_and_ip_ex.jl", "max_issues_repo_name": "tbeason/QuantileRegression.jl", "max_issues_repo_head_hexsha": "96b20e99e958ddda6890a6d0506cf8a3005bc136", "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_and_ip_ex.jl", "max_forks_repo_name": "tbeason/QuantileRegression.jl", "max_forks_repo_head_hexsha": "96b20e99e958ddda6890a6d0506cf8a3005bc136", "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.1428571429, "max_line_length": 74, "alphanum_fraction": 0.6619318182, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.776569378896968}}
{"text": "# https://www.hackerrank.com/challenges/s10-basic-statistics/problem\n\nusing Statistics\nusing Printf\n\ndata = readlines()\nn_data = parse(Float64, data[1])\nvalues = [parse(Float64, x) for x in split(data[2])]\n\nfunction mode(x)\n    a_keys = sort(unique(x))\n    a_counts = zeros(length(a_keys))\n\n    for val in x\n        ma = a_keys.==val\n        a_counts[ma] .+= 1\n    end\n\n    max_counts = maximum(a_counts)\n    if max_counts == 1.0\n        return a_keys[1]\n    else\n        ma = a_counts.==max_counts\n        return minimum(a_keys[ma])\n    end\nend\n\nmean_val = mean(values)\nmedian_val = median(values)\nmode_val = mode(values)\n\n@printf(\"%.1f\\n\", mean_val)\n@printf(\"%.1f\\n\", median_val)\n@printf(\"%.1f\\n\", mode_val)\n", "meta": {"hexsha": "15264b4798d1df5766ae1987eb795f8bbe423ab6", "size": 710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Practice/Tutorials/10 Days of Statistics/Day 00 Mean, Median, and Mode.jl", "max_stars_repo_name": "mtaufanr/hackerrank-code-julia", "max_stars_repo_head_hexsha": "512d17bf8469f09eecd27e772d7a66364beb5337", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Practice/Tutorials/10 Days of Statistics/Day 00 Mean, Median, and Mode.jl", "max_issues_repo_name": "mtaufanr/hackerrank-code-julia", "max_issues_repo_head_hexsha": "512d17bf8469f09eecd27e772d7a66364beb5337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Practice/Tutorials/10 Days of Statistics/Day 00 Mean, Median, and Mode.jl", "max_forks_repo_name": "mtaufanr/hackerrank-code-julia", "max_forks_repo_head_hexsha": "512d17bf8469f09eecd27e772d7a66364beb5337", "max_forks_repo_licenses": ["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": 68, "alphanum_fraction": 0.6422535211, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615413, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.776569375718392}}
{"text": "\"\"\"\nCreated on Wed Sep 23 2020\n\n@author: Yoann Pradat\n\nMultiplicative update algorithms for \u03b1 divergence.\n\"\"\"\n\n\"\"\"\n    _update_nmf_mu_\u03b1!(V, WH, W, H, \u03b1, \u03f5)\n    \n\"\"\"\nfunction _update_nmf_mu_\u03b1!(V::Matrix{T}, WH::Matrix{T}, W::Matrix{T}, H::Matrix{T}, \u03b1::Real, \u03f5::Real) where T <: Real\n    if \u03b1 == 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 .+ \u03f5)))) \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 .+ \u03f5)) * transpose(H)))\n        WH .= W * H\n\n    else\n        #### general \u03b1 divergence updates for \u03b1 != 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 .+ \u03f5) ./ (WH .+ \u03f5)) .^ \u03b1 * transpose(H)) .^ (1/\u03b1)\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 .+ \u03f5)./(WH .+ \u03f5)) .^ \u03b1)) .^ (1/\u03b1)\n        # WH .= W * H\n\n        #### eqs (44)\n        \n        # update W\n        W .= W .* ((((V .+ \u03f5) ./ (WH .+ \u03f5)) .^ \u03b1 * transpose(H)) ./ (ones(size(V)) * transpose(H)) .+ \u03f5) .^ (1/\u03b1) \n        WH .= W * H\n\n        # update H\n        H .= H .* (((transpose(W) * ((V .+ \u03f5) ./ (WH .+ \u03f5)) .^ \u03b1)) ./ (transpose(W) * ones(size(V))) .+ \u03f5) .^ (1/\u03b1)\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)/\u03c0^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(\u03bc, \u03bcj, \u03d5j) = 1/(1+exp(-gg2(\u03d5j)*(\u03bc - \u03bcj)))\n    gg2(\u03d5) = 1/sqrt(1 + 3*(\u03d5^2)/\u03c0^2)\n    compute_v(\u03bc, \u03bcjs, \u03d5js) = 1/sum(gg2.(\u03d5js).^2 .* Eg2.(\u03bc, \u03bcjs, \u03d5js) .* (1 .- Eg2.(\u03bc, \u03bcjs, \u03d5js)))\n    compute_\u0394(\u03bc, \u03bcjs, \u03d5js, sjs, v) = v * sum(gg2.(\u03d5js) .* (sjs .- Eg2.(\u03bc, \u03bcjs, \u03d5js)))\n    \u03d5increase(\u03d5, \u03c3) = sqrt(\u03d5^2 + \u03c3^2)\n\n    \"\"\"\n        glicko2(\u03bc::Real, \u03d5::Real, \u03c3::Real, \u03bcjs::Vector{Real}, \u03d5js::Vector{Real}, sjs::Vector{Real}; \u03c4=0.05, \u03f5=10^-6)\n    \n    # Arguments:\n    * `\u03bc`: Rating of player\n    * `\u03d5`: Rating deviation of player\n    * `\u03c3`: Rating volatility\n    * `\u03bcjs`: Ratings of oppenents within rating period\n    * `\u03bcjs`: Rating deviations within rating period\n    * `sjs`: Game outcomes from the perspective of the \"player\": 1 - won, 0.5 - draw, 0 - lost.\n    * `\u03c4=0.5`: smaller values constrain the change in volatility over time, reasonable range between 0.3 and 1.2\n    * `\u03f5=10^-6`: Convergence bound\n\n    Returns tuple `(\u03bc, \u03d5, \u03c3)`: 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(\u03bc::Real, \u03d5::Real, \u03c3::Real, \u03bcjs::Vector{R}, \u03d5js::Vector{R}, sjs::Vector{S}; \u03c4=0.5, \u03f5=10^-6) where {R <: Real, S <: Real}\n        v = compute_v(\u03bc, \u03bcjs, \u03d5js)\n        \u0394 = compute_\u0394(\u03bc, \u03bcjs, \u03d5js, sjs, v) \n        a = log(\u03c3^2)\n        f(x) = exp(x)*(\u0394^2 - \u03d5^2  - v - exp(x)) / (2 * (\u03d5^2 + v + exp(x))^2) - (x - a)/\u03c4^2\n        A = a\n        if \u0394^2 > \u03d5^2 + v \n            B = log(\u0394^2 - \u03d5^2  - v)\n        else\n            k = 1\n            while (f(a - k*\u03c4) < 0)\n                k += 1\n            end\n            B = a - k*\u03c4\n        end\n        fA = f(A)\n        fB = f(B)\n        while abs(B - A) > \u03f5\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        \u03c3new = exp(A/2)\n        \u03d5increased = sqrt(\u03d5^2 + \u03c3new^2)\n        \u03d5new = 1/sqrt(1/\u03d5increased^2 + 1/v)\n        \u03bcnew = \u03bc + \u03d5new^2 * sum(gg2.(\u03d5js) .* (sjs .- Eg2.(\u03bc, \u03bcjs, \u03d5js)))\n        \u03bcnew, \u03d5new, \u03c3new\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 (\u03bc and \u03d5).\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 \u2208 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 \u2265 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": "# Tests for entropy function\n\narr = rand(1000)\nsqrt_1000 = sqrt(1000)\n\n# Test with 1 values array\n@test get_entropy(arr) \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with 1 array passed.\")\n\n# Test with 2 values arrays\n@test get_entropy(arr, arr) \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with 2 arrays passed.\")\n\n# Test with 3 values arrays\n@test get_entropy(arr, arr, arr) \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with 3 arrays passed.\")\n\n# Test with uniform_width\n@test get_entropy(arr, mode = \"uniform_width\") \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with uniform width passed.\")\n\n# Test with uniform_count\n@test get_entropy(arr, mode = \"uniform_count\") \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with uniform count passed.\")\n\n# Test with bayesian_blocks\n# @test get_entropy(arr, mode = \"bayesian_blocks\") \u2248 log2(10) atol = 0.05\n# println(\"Entropy with Bayesian blocks passed.\")\n\n# Test with number_of_bins\n@test get_entropy(arr, number_of_bins = 5) \u2248 log2(5) atol = 0.05\nprintln(\"Entropy with number of bins passed.\")\n\n# Test with get_number_of_bins\n@test get_entropy(arr, get_number_of_bins = function(values) return 2 end) \u2248 log2(2) atol = 0.05\nprintln(\"Entropy with get number of bins passed.\")\n\n# Test with maximum_likelihood\n@test get_entropy(arr, estimator = \"maximum_likelihood\") \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with maximum likelihood passed.\")\n\n# Test with shrinkage\n@test get_entropy(arr, estimator = \"shrinkage\") \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with shrinkage passed.\")\n\n# Test with shrinkage and lambda\n@test get_entropy(arr, estimator = \"shrinkage\", lambda = 0) \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with shrinkage and lambda passed.\")\n\n# Test with dirichlet\n@test get_entropy(arr, estimator = \"dirichlet\") \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with Dirichlet passed.\")\n\n# Test with dirichlet and prior\n@test get_entropy(arr, estimator = \"dirichlet\", prior = 1) \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with Dirichlet and prior passed.\")\n\n# Test with miller_madow\n@test get_entropy(arr, estimator = \"miller_madow\") \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with Miller-Madow passed.\")\n\n# Test with base e\n@test get_entropy(arr, base = e) \u2248 log(sqrt_1000) atol = 0.05\nprintln(\"Entropy with change of base passed.\")\n\n# Test with discretized\n@test get_entropy(discretize_values(arr), discretized = true) \u2248 log2(sqrt_1000) atol = 0.05\nprintln(\"Entropy with discretized input passed.\")\n", "meta": {"hexsha": "a28c4c71351b71c5d4e02761581cd1ad2ce35e3b", "size": 2480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testEntropy.jl", "max_stars_repo_name": "alavendelm/InformationMeasures.jl", "max_stars_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_stars_repo_licenses": ["MIT"], "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/testEntropy.jl", "max_issues_repo_name": "alavendelm/InformationMeasures.jl", "max_issues_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_issues_repo_licenses": ["MIT"], "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/testEntropy.jl", "max_forks_repo_name": "alavendelm/InformationMeasures.jl", "max_forks_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_forks_repo_licenses": ["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.9420289855, "max_line_length": 96, "alphanum_fraction": 0.7419354839, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7765321569164926}}
{"text": "doc\"\"\"\n    Beta(\u03b1,\u03b2)\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    \u03b1::T\n    \u03b2::T\n\n    function Beta(\u03b1::T, \u03b2::T)\n        @check_args(Beta, \u03b1 > zero(\u03b1) && \u03b2 > zero(\u03b2))\n        new(\u03b1, \u03b2)\n    end\nend\n\nBeta{T<:Real}(\u03b1::T, \u03b2::T) = Beta{T}(\u03b1, \u03b2)\nBeta(\u03b1::Real, \u03b2::Real) = Beta(promote(\u03b1, \u03b2)...)\nBeta(\u03b1::Integer, \u03b2::Integer) = Beta(Float64(\u03b1), Float64(\u03b2))\nBeta(\u03b1::Real) = Beta(\u03b1, \u03b1)\nBeta() = Beta(1, 1)\n\n@distr_support Beta 0.0 1.0\n\n#### Conversions\nfunction convert{T<:Real}(::Type{Beta{T}}, \u03b1::Real, \u03b2::Real)\n    Beta(T(\u03b1), T(\u03b2))\nend\nfunction convert{T <: Real, S <: Real}(::Type{Beta{T}}, d::Beta{S})\n    Beta(T(d.\u03b1), T(d.\u03b2))\nend\n\n#### Parameters\n\nparams(d::Beta) = (d.\u03b1, d.\u03b2)\n@inline partype{T<:Real}(d::Beta{T}) = T\n\n\n#### Statistics\n\nmean(d::Beta) = ((\u03b1, \u03b2) = params(d); \u03b1 / (\u03b1 + \u03b2))\n\nfunction mode(d::Beta)\n    (\u03b1, \u03b2) = params(d)\n    (\u03b1 > 1 && \u03b2 > 1) || error(\"mode is defined only when \u03b1 > 1 and \u03b2 > 1.\")\n    return (\u03b1 - 1) / (\u03b1 + \u03b2 - 2)\nend\n\nmodes(d::Beta) = [mode(d)]\n\nfunction var(d::Beta)\n    (\u03b1, \u03b2) = params(d)\n    s = \u03b1 + \u03b2\n    return (\u03b1 * \u03b2) / (abs2(s) * (s + 1))\nend\n\nmeanlogx(d::Beta) = ((\u03b1, \u03b2) = params(d); digamma(\u03b1) - digamma(\u03b1 + \u03b2))\n\nvarlogx(d::Beta) = ((\u03b1, \u03b2) = params(d); trigamma(\u03b1) - trigamma(\u03b1 + \u03b2))\nstdlogx(d::Beta) = sqrt(varlogx(d))\n\nfunction skewness(d::Beta)\n    (\u03b1, \u03b2) = params(d)\n    if \u03b1 == \u03b2\n        return zero(\u03b1)\n    else\n        s = \u03b1 + \u03b2\n        (2(\u03b2 - \u03b1) * sqrt(s + 1)) / ((s + 2) * sqrt(\u03b1 * \u03b2))\n    end\nend\n\nfunction kurtosis(d::Beta)\n    \u03b1, \u03b2 = params(d)\n    s = \u03b1 + \u03b2\n    p = \u03b1 * \u03b2\n    6(abs2(\u03b1 - \u03b2) * (s + 1) - p * (s + 2)) / (p * (s + 2) * (s + 3))\nend\n\nfunction entropy(d::Beta)\n    \u03b1, \u03b2 = params(d)\n    s = \u03b1 + \u03b2\n    lbeta(\u03b1, \u03b2) - (\u03b1 - 1) * digamma(\u03b1) - (\u03b2 - 1) * digamma(\u03b2) +\n        (s - 2) * digamma(s)\nend\n\n\n#### Evaluation\n\n@_delegate_statsfuns Beta beta \u03b1 \u03b2\n\ngradlogpdf{T<:Real}(d::Beta{T}, x::Real) =\n    ((\u03b1, \u03b2) = params(d); 0 <= x <= 1 ? (\u03b1 - 1) / x - (\u03b2 - 1) / (1 - x) : zero(T))\n\n\n#### Sampling\n\nrand(d::Beta) = StatsFuns.RFunctions.betarand(d.\u03b1, d.\u03b2)\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    \u03b1 = x_bar * (((x_bar * (1 - x_bar)) / v_bar) - 1)\n    \u03b2 = (1 - x_bar) * (((x_bar * (1 - x_bar)) / v_bar) - 1)\n    Beta(\u03b1, \u03b2)\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": "# # Arrays and Loops\n#\n# We'll cover:\n# 1. Array literals\n# 2. Concatenation\n# 3. For loops\n# 4. Comprehensions\n# 5. Element types\n# 6. Dequeues\n# 7. The `bang!` convention\n# 8. Variable names vs. copies\n#\n# # Arrays\n#\n# Julia has highly efficient multidimensional arrays, both constructed and indexed with square brackets.\n#\n# Syntax: <br>\n# ```julia\n# [item1, item2, ...]\n# ```\n\nsquares = [1, 4, 9, 15, 25, 36, 49, 64]\n\n#-\n\nsquares[1]\n\n#-\n\nsquares[1:3]\n\n#-\n\nsquares[end]\n\n#-\n\nsquares[4] = 16\n\n#-\n\nsquares\n\n#-\n\ntypeof(squares)\n\n# ## Concatenation\n#\n# If, instead of commas, you just use spaces, then the values are concatenated horizontally.\n\ncubes = [1, 8, 27, 64, 125, 216, 343, 512]\n\n#-\n\npowers = [1:8 squares cubes]\n\n#-\n\npowers[4, 2]\n\n#-\n\npowers[:, 3]\n\n#-\n\npowers[7, :]\n\n#-\n\ntypeof(powers)\n\n# Semicolon separators perform vertical concatenation:\n\n[squares; cubes]\n\n# Whereas commas would simply create an array of arrays:\n\nnested_powers = [[1,2,3,4,5,6,7,8], squares, cubes]\n\n#-\n\nnested_powers[2]\n\n# Horizontal and vertical concatenation can be used together to as a simple syntax for matrix literals:\n\n[1 3 5; 2 4 6]\n\n# # Loops\n\n#-\n\n# Of course, we could construct this programmatically with a for-loop. The syntax for a `for` loop is\n#\n# ```julia\n# for *var* in *loop iterable*\n#     *loop body*\n# end\n# ```\n#\n\n\nA = fill(0, (8, 3)) # Allocate an 8x3 matrix to store the values into\nfor pow in 1:3\n    for value in 1:8\n        A[value, pow] = value ^ pow\n    end\nend\nA\n\n#-\n\nA == powers\n\n# ## Array Comprehensions\n\nsquares = [value^2 for value in 1:8]\n\n#-\n\ncubes = [value^3 for value in 1:8]\n\n#-\n\npowers = [value^pow for value in 1:8, pow in 1:3]\n\n# # The element type\n#\n# Note that every time an array prints out, it is displaying its element type and dimensionality, for example `Array{Int64, 2}`. This describes what it can store \u2014\u00a0and thus what it can return upon indexing.\n\ntypeof(powers)\n\n#-\n\ntypeof(powers[1, 1])\n\n# Further, the array will try to convert any new values assigned into it to its element type:\n\npowers[1, 1] = 1.6\n\n#-\n\npowers[1, 1] = -5.0 # This can be losslessly converted to an integer\n\n#-\n\npowers\n\n# Arrays that have an exact and concrete element type are generally significantly faster, so Julia will try to find an amenable element type for you in its literal construction syntax:\n\nfortytwosarray = [42, 42.0, 4.20e1, 4.20f1, 84//2, 0x2a]\n\n#-\n\nfor x in fortytwosarray\n    show(x)\n    println(\"\\tisa $(typeof(x))\")\nend\n\n# The `Any` array can be helpful for disabling these behaviors and allowing all kinds of different objects:\n\nanyfortytwos = Any[42, 42.0, 4.20e1, 4.20f1, 84//2, 0x2a]\n\n#-\n\nanyfortytwos[1] = \"FORTY TWO\"\nanyfortytwos\n\n# # Vectors as dequeues\n\n#-\n\n# One-dimensional arrays can be appended to and have items removed from them:\n\nfib = [1, 1, 2, 3, 5, 8, 13]\n\n#-\n\npush!(fib, 21)\n\n#-\n\npush!(fib, sum(fib[end-1:end]))\n\n#-\n\npop!(fib)\n\n#-\n\npushfirst!(fib, 0)\n\n#-\n\npopfirst!(fib)\n\n# ## Aside: why so shouty!?\n#\n# Why are there exclamations in all the above function calls? `push!(fib, ...)`, `pop!(fib)`, etc.?\n\npush!\n\n# This is entirely a convention. It's a signal to the caller that one of the argument is going to be _mutated_. It's perhaps easiest to demonstrate with an example:\n\nA = rand(0:10, 10)\n\n#-\n\nsort(A)\n\n#-\n\nA\n\n#-\n\nsort!(A)\n\n#-\n\nA # That changed A!\n\n# ## Aside: names vs. copies\n#\n# Remember that variables are just names we give our objects. So watch what happens if we give the same object two different names:\n\nfibonacci = [1, 1, 2, 3, 5, 8, 13]\n\n#-\n\nsome_numbers = fibonacci\nsome_numbers[1] = 404\nsome_numbers\n\n#-\n\nfibonacci\n\n#-\n\nfibonacci[1] = 1\nsome_numbers = copy(fibonacci)\nsome_numbers[2] = 404\nfibonacci\n", "meta": {"hexsha": "d20a30831347005e7e356a57484e58ba9cfc2e75", "size": 3667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Introduction to Julia/02. Arrays and Loops.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/02. Arrays and Loops.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/02. Arrays and Loops.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": 14.906504065, "max_line_length": 206, "alphanum_fraction": 0.6648486501, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.9032942112597332, "lm_q1q2_score": 0.7765293024562958}}
{"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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8f2743fe-7c39-11eb-27d6-d527b21f46b8\nbegin\n\tfunction euler(f,t\u2080,t\u2091,\u0394t,x\u2080,P)\n\t\tT = t\u2080:\u0394t:t\u2091\n\t\tF = Vector{typeof(x\u2080)}(undef,length(T))\n\n\t\tF[1] = x\u2080\n\t\t\n\t\tfor (n,t\u2099) \u2208 enumerate(@view T[2:end])\n\t\t\tF[n+1] = F[n] .+ f(t\u2099,F[n],P) .* \u0394t\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 \u2208 F] for i \u2208 1:length(F[1])]\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 62311b66-7c3b-11eb-335c-c53b566fcb9f\nbegin\t\n\tfunction OneLocus(t,X,P)\n\t\tX\u2080\u2080, X\u2080\u2081, X\u2081\u2081 = (x for x \u2208 X)\n\t\tb, d, K, \u03bc = (p for p \u2208 P)\n\t\t\n\t\t\u03a3 = sum(X)\n\t\tM = \u03a3 - X\u2081\u2081\n\t\tD = d+((b-d)/K(t))*\u03a3\n\t\t\n\t\treturn [\n\t\t\t\t(b * (1-\u03bc)*(X\u2080\u2080+0.5*X\u2080\u2081)^2/M - D*X\u2080\u2080),\n\t\t\t\t(b * ((1-\u03bc)*(X\u2080\u2080+0.5*X\u2080\u2081)*X\u2080\u2081/M + \u03bc*(X\u2080\u2080+0.5*X\u2080\u2081)^2/M) - D*X\u2080\u2081),\n\t\t\t\t(b * ((1-\u03bc)*0.25*(X\u2080\u2081)^2/M + \u03bc*(X\u2080\u2080+0.5*X\u2080\u2081)*X\u2080\u2081/M + \u03bc^2*(X\u2080\u2080+0.5*X\u2080\u2081)^2/M) - D*X\u2081\u2081)\n\t\t\t\t]\n\t\tend\nend\n\n# \u2554\u2550\u2561 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 \u03bc NumberField(0.0:0.0001:0.2, default=0.001))\n\"\"\"\n\n# \u2554\u2550\u2561 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,\u03bc])\n\trF = reshape_result(F)\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25008491344a-7c39-11eb-327e-df48b337d147\n# \u255f\u25000904e59a-7c3b-11eb-307d-6fd2049ea8bc\n# \u2560\u25508f2743fe-7c39-11eb-27d6-d527b21f46b8\n# \u255f\u2500925558e8-7cc7-11eb-37a8-c98fb8a33355\n# \u2560\u255062311b66-7c3b-11eb-335c-c53b566fcb9f\n# \u255f\u2500348cb7ba-7c40-11eb-1a80-4768b0c6b4d4\n# \u255f\u2500d728c114-7c40-11eb-1fcb-a1ecbb31ae54\n# \u255f\u2500619eab70-7c41-11eb-1fc0-fb3ec4e64220\n# \u2560\u2550a19430e8-7c3d-11eb-0790-4b883ac9cd39\n# \u255f\u250020a4f4dc-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# title: 1590. Make Sum Divisible by P\n# id: problem1590\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Array, Hash Table, Math, Binary Search\n# link: <https://leetcode.com/problems/make-sum-divisible-by-p/description/>\n# hidden: true\n# ---\n# \n# Given an array of positive integers `nums`, remove the **smallest** subarray\n# (possibly **empty** ) such that the **sum** of the remaining elements is\n# divisible by `p`. It is **not** allowed to remove the whole array.\n# \n# Return _the length of the smallest subarray that you need to remove, or_`-1`\n# _if it 's impossible_.\n# \n# A **subarray** is defined as a contiguous block of elements in the array.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: nums = [3,1,4,2], p = 6\n#     Output: 1\n#     Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: nums = [6,3,5,2], p = 9\n#     Output: 2\n#     Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: nums = [1,2,3], p = 3\n#     Output: 0\n#     Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: nums = [1,2,3], p = 7\n#     Output: -1\n#     Explanation: There is no way to remove a subarray in order to get a sum divisible by 7.\n#     \n# \n# **Example 5:**\n# \n#     \n#     \n#     Input: nums = [1000000000,1000000000,1000000000], p = 3\n#     Output: 0\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= nums.length <= 105`\n#   * `1 <= nums[i] <= 109`\n#   * `1 <= p <= 109`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "89cf40821defb014c2a6795b7a5628e30fe63e74", "size": 1945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1590.make-sum-divisible-by-p.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/1590.make-sum-divisible-by-p.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/1590.make-sum-divisible-by-p.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.012345679, "max_line_length": 187, "alphanum_fraction": 0.5881748072, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.9032942014971871, "lm_q1q2_score": 0.7765292875683607}}
{"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 \u2264 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": "using CircGeometry, Test\n\np1 = Point(0.0,0.0); q1 = Point(0.0,1.0)\np2 = Point(-0.5,0.5); q2 = Point(0.5,0.5)\n@testset \"do_intersect tests\" begin \n    @test CircGeometry.do_intersect(p1,q1,p2,q2) == true\n    @test CircGeometry.do_intersect(p1,p2,q1,q2) == false\nend\n\nz = Point(0.5+Float64(pi),1.5+Float64(pi))\n@testset \"get_orientation tests\" begin\n    @test CircGeometry.get_orientation(p2,q1,z) == 0\n    @test CircGeometry.get_orientation(p2,z,q1) == 0\n    @test CircGeometry.get_orientation(z,p2,q1) == 0\n    @test CircGeometry.get_orientation(p1,q1,Point(1.0,0.0)) == 1\n    @test CircGeometry.get_orientation(p1,q1,Point(-1.0,0.0)) == 2\nend\n\na = Point(13.2,12.3)\nb = Point(1.0+5*eps(),1.0)\nc = Point(-1.0,0.0)\ncirclewall = CircGeometry.CircleWall(Point(0.0,0.0),1.0)\nlwall1 = CircGeometry.LineWall(Point(-1.0,1.0),Point(1.0,1.0))\nlwall2 = CircGeometry.LineWall(Point(-1.0,-1.0),Point(-1.0,1.0))\n@testset \"is_point_in_wall tests\" begin\n    @test CircGeometry.is_point_in_wall(q1,circlewall) == true\n    @test CircGeometry.is_point_in_wall(p2,circlewall) == false\n    @test CircGeometry.is_point_in_wall(a,circlewall) == false\n\n    @test CircGeometry.is_point_in_wall(q1,lwall1) == true\n    @test CircGeometry.is_point_in_wall(p1,lwall1) == false\n    @test CircGeometry.is_point_in_wall(b,lwall1) == false\n\n    @test CircGeometry.is_point_in_wall(c,lwall2) == true\n    @test CircGeometry.is_point_in_wall(p1,lwall2) == false\nend\n\n# test for on_segment where point is colinear with other two points\npolygon = [Point(0.0,0.0),Point(2.0,0.0),Point(2.0,1.0)]\npoint = Point(1.0,0.0)\n@test CircGeometry.is_inside_polygon(polygon, point; extreme = Point(100_000.0, point.y)) == true\n\n# check on_segment\n@testset \"on_segment tests\" begin \n    @test CircGeometry.on_segment(Point(0.0,0.0),Point(1.0,0.0),Point(2.0,0.0)) == true\n    @test CircGeometry.on_segment(Point(0.0,0.0),Point(1.0,0.1),Point(2.0,0.0)) == false\n    @test CircGeometry.on_segment(Point(0.0,0.0),Point(3.0,0.0),Point(2.0,0.0)) == false\nend\n", "meta": {"hexsha": "da69b5851cb862cc5271f7affdaf781aa453b3e9", "size": 2002, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/position_checking_test.jl", "max_stars_repo_name": "pseastham/CircGeometry", "max_stars_repo_head_hexsha": "c75150b9bd189eecf9a2398a59fd22d5f3eae422", "max_stars_repo_licenses": ["MIT"], "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/position_checking_test.jl", "max_issues_repo_name": "pseastham/CircGeometry", "max_issues_repo_head_hexsha": "c75150b9bd189eecf9a2398a59fd22d5f3eae422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-05-18T17:28:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-29T02:05:36.000Z", "max_forks_repo_path": "test/position_checking_test.jl", "max_forks_repo_name": "pseastham/CircGeometry.jl", "max_forks_repo_head_hexsha": "c75150b9bd189eecf9a2398a59fd22d5f3eae422", "max_forks_repo_licenses": ["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.8571428571, "max_line_length": 97, "alphanum_fraction": 0.7027972028, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7765242062629796}}
{"text": "\nusing Test\nusing Plots\nusing BenchmarkTools\nusing LinearAlgebra\nusing Random\nusing Roots\n\npush!(LOAD_PATH, abspath(@__DIR__,\"..\",\"src\"))\n\nusing SmoothedSpectralAbscissa ; const SSA = SmoothedSpectralAbscissa\n\n##\n\n\n\"\"\"\n    lyap_simple!(A::AbstractMatrix)\nreturns the naive implementation of the Lyapunov objective function and its\nderivative. Can be used for testing, plotting, etc\n\"\"\"\nfunction lyap_simple!(A::AbstractMatrix)\n    function  myf(s::Float64)::Float64\n        P = lyap(A - UniformScaling(s),one(A))\n        tr(P)\n    end\n    function d_myf(s::Float64)::Float64\n        sc,Id = UniformScaling(s), one(A)\n        P =  lyap(A - sc,Id)\n        Q = lyap(A' - sc,Id)\n        -2.0tr(P*Q)\n    end\n    myf,d_myf\nend\n\n\n\"\"\"\n    ssa_test(A::Matrix{Float64})\n\nThis is the easiest implementation\nfor testing and benchmarking.\n\"\"\"\nfunction ssa_test(A::Matrix{Float64} ; ssa_eps=nothing)\n    myf,d_myf = lyap_simple!(A)\n    ssa_eps = something(ssa_eps,SSA.default_eps_ssa(A))\n    myg(s)= 1.0 / myf(s) - ssa_eps\n    d_myg(s) = - d_myf(s) / myf(s)^2\n    sa = SSA.spectral_abscissa(A)\n    ssa_start = sa + 0.5*ssa_eps\n    find_zero( (myg,d_myg),ssa_start, Roots.Newton())\nend\n\nfunction ssa_simple(A::AbstractMatrix, with_gradient::Bool,PQ,\n        ssa_eps::Union{Nothing,Float64}=nothing)\n    _ssa_eps = something(ssa_eps, SSA.default_eps_ssa(A))\n    SSA.PQ_init!(A,PQ)\n    _sa = SSA.spectral_abscissa(PQ)\n    _start = _sa + 0.5*ssa_eps\n    g(s)=SSA._g(s,PQ,_ssa_eps,_sa)\n    x = range(_start, 10 ; length=200)\n    y = g.(x)\n    (x,y)\nend\n\n##", "meta": {"hexsha": "91c7fb58bf538b9fe2551cfb129eae2139643234", "size": 1537, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsplots.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": "test/testsplots.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": "test/testsplots.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": 24.015625, "max_line_length": 75, "alphanum_fraction": 0.6616785947, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7765242007820529}}
{"text": "function drawline!(img::Matrix{T}, x0::Int, y0::Int, x1::Int, y1::Int, col::T) where T\n    \u03b4x = abs(x1 - x0)\n    \u03b4y = abs(y1 - y0)\n    \u03b4e = abs(\u03b4y / \u03b4x)\n    er = 0.0\n\n    y = y0\n    for x in x0:x1\n        img[x, y] = col\n        er += \u03b4e\n        if er > 0.5\n            y  += 1\n            er -= 1.0\n        end\n    end\n\n    return img\nend\n\nusing Images\n\nimg = fill(Gray(255.0), 5, 5);\nprintln(\"\\nImage:\")\ndisplay(img); println()\ndrawline!(img, 1, 1, 5, 5, Gray(0.0));\nprintln(\"\\nModified image:\")\ndisplay(img); println()\n", "meta": {"hexsha": "eb12afe64a6f5e2092787c6eac5871bbd2a10b8f", "size": 522, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/bitmap-bresenhams-line-algorithm.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/bitmap-bresenhams-line-algorithm.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/bitmap-bresenhams-line-algorithm.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": 18.6428571429, "max_line_length": 86, "alphanum_fraction": 0.4961685824, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9759464506036182, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7765196915573056}}
{"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 (\u2297_{i \u2208 xy_indices} X_i) + (\u2297_{i \u2208 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 \u2208 xy_indices ? X : I(2) for i \u2208 1:d)...\n        ) + kron((i \u2208 xy_indices ? Y : I(2) for i \u2208 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    \u03b2::Vector{Float64}\n    r::Integer # this is the r in r-Nearby-values\n    d::Integer # d (= \u03ba) = number of colors\n\n    function RNearbyValuesMixerGate(\u03b2::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([\u03b2], 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.\u03b2[] * H_rNV)\n\n    return U_rNV\nend\n\n# Adjoint of r-NV = r-NV gate with negated \u03b2 parameter\nQaintessent.adjoint(g::RNearbyValuesMixerGate) = RNearbyValuesMixerGate(-g.\u03b2[], 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    \u03b2::Vector{Float64}\n    d::Integer # d (= \u03ba) = number of colors\n    is_adjoint::Bool # if yes, the order in the product is reversed\n\n    function ParityRingMixerGate(\u03b2::Float64, d::Integer; is_adjoint::Bool = false)\n        d > 0 || throw(ArgumentError(\"Parameter d must be a positive integer.\"))\n        new([\u03b2], 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 \u2260 n, the paper actually means a \u2260 d.\n    # assumption: by X_a for a = d+1, the paper means X_1.\n    U_odd = prod([exp(-im * g.\u03b2[] * XY_sum([a, a+1], g.d)) for a \u2208 1:2:(g.d - 1)], init=I)\n    U_even = prod([exp(-im * g.\u03b2[] * XY_sum([a, a < g.d ? (a+1) : 1], g.d)) for a \u2208 2:2:g.d], init=I)\n\n    # Implements Eq. (9)\n    U_last =  isodd(g.d) ? exp(-im * g.\u03b2[] * 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 \u03b2 parameter, reversed order in the product\nQaintessent.adjoint(g::ParityRingMixerGate) = ParityRingMixerGate(-g.\u03b2[], 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    \u03b2::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(\u03b2::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 \u2208 partition\n            part_indices = union(reduce(vcat, collect.(partition_part)))\n            part_indices \u2286 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([\u03b2], 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 \u2208 g.partition\n        # we can represent each part by one Hamiltonian, because the individual XY gates commute\n        # and therefore exp(-i\u03b2 \u2211H_{a,b}) = \u220fexp(-i\u03b2 H_{a,b})\n        H_part = sum(XY_sum([a, b], g.d) for (a, b) \u2208 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 \u03b2\n# than is stored in the gate struct (useful for backward pass)\nfunction partition_mixer_gate_matrix(g::PartitionMixerGate, \u03b2::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 * \u03b2 * hamiltonians)\n    return prod(reverse(Us))\nend\n\nQaintessent.matrix(g::PartitionMixerGate) = partition_mixer_gate_matrix(g, g.\u03b2[])\n\n# Adjoint of partition ring mixer -> negated \u03b2 parameter, reversed order in the product\nQaintessent.adjoint(g::PartitionMixerGate) = PartitionMixerGate(-g.\u03b2[], 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\u22121)^n + (p_n+1)^n is divided by p_n^2.\n\nFor example, when n = 3, p3 = 5, and 43 + 63 = 280 \u2261 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": "module test_stdlib_linearalgebra_det\n\nusing Test\nusing LinearAlgebra\n\nA = [4 3;\n     6 3]\n\n@test det(A) == 4*3 - 3*6 == -6\n@test det(exp(A)) \u2248 exp(tr(A)) == 1096.6331584284585\n@test sum(diag(A)) == tr(A) \u2248 log(det(exp(A)))\n@test tr(I - inv(A)) < tr(A - I)\n\nA = [  4  12 -16;\n      12  37 -43;\n     -16 -43  98]\n@test det(A) \u2248 36\n@test det(2A) \u2248 288\n\nend # module test_stdlib_linearalgebra_det\n\n\nmodule test_stdlib_linearalgebra_eigen\n\nusing Test\nusing LinearAlgebra\n\nA = [  4  12 -16;\n      12  37 -43;\n     -16 -43  98]\n\nE1 = eigen(A)\nE2 = eigen(2A)\n@test E1.values \u2248 [0.018804980460810916, 15.5039632294076, 123.47723179013143]\n@test E2.values \u2248 [0.03760996092162183 , 31.0079264588152, 246.95446358026285]\n@test 2 * E1.values == E2.values\n@test E1.vectors == E2.vectors\n\nend # module test_stdlib_linearalgebra_eigen\n\n\nmodule test_stdlib_linearalgebra_diagonal\n\nusing Test\nusing LinearAlgebra\n\nA = [  4  12 -16;\n      12  37 -43;\n     -16 -43  98]\n@test Diagonal(A) ==\n      Diagonal(diag(A)) ==\n      diagm(0=>diag(A)) ==\n                           [  4   0   0;\n                              0  37   0;\n                              0   0  98]\n@test I * A == A\n@test I + A == Diagonal([1, 1, 1]) + A\n\nend # module test_stdlib_linearalgebra_diagonal\n\n\nmodule test_stdlib_linearalgebra_rank\n\nusing Test\nusing LinearAlgebra\n\n@test rank(-5) == rank(5) == 1\n@test rank(0) == 0\n@test rank([ 0 0 0; 0 2 2; 0 3 3]) == 1\n@test rank([ 0 0 0; 0 0 2; 0 3 3]) == 2\n\nend # module test_stdlib_linearalgebra_rank\n\n\nmodule test_stdlib_linearalgebra_cholesky\n\nusing LinearAlgebra\nusing Test\n\n# https://en.wikipedia.org/wiki/Cholesky_decomposition#Example\n\nA = [  4  12 -16;\n      12  37 -43;\n     -16 -43  98]\n\n@test UpperTriangular(A) ==\n      triu(A) ==\n                            [  4  12 -16;\n                               0  37 -43;\n                               0   0  98]\n\n@test LowerTriangular(A) ==\n      tril(A) ==\n                            [  4   0   0;\n                              12  37   0;\n                             -16 -43  98]\n@test issymmetric(A)\n@test A' == adjoint(A) == transpose(A) == A\n\nC = cholesky(A)\n@test C.L * C.U == A\n\nend # module test_stdlib_linearalgebra_cholesky\n\n\nmodule test_stdlib_linearalgebra_dot\n\nusing Test\nusing LinearAlgebra\n\n@test dot([1, 3, -5], [4, -2, -1]) == 3\n# 1 * 4 + 3 * -2 + -5 * -1\n\n@test [1 2; 3 4] * [5 6; 7 8] == [19 22; 43 50]\n# 1 * 5 + 2 * 7    1 * 6 + 2 * 8\n# 3 * 5 + 4 * 7    3 * 6 + 4 * 8\n\nend # module test_stdlib_linearalgebra_dot\n\n\nmodule test_stdlib_linearalgebra_cross\n\nusing Test\nusing LinearAlgebra\n\n@test cross([2, 3, 4], [5, 6, 7]) == [-3, 6, -3]\n# 3 * 7 - 4 * 6\n# 4 * 5 - 2 * 7\n# 2 * 6 - 3 * 5\n\nend # module test_stdlib_linearalgebra_cross\n\n\nmodule test_stdlib_linearalgebra_norm\n\nusing Test\nusing LinearAlgebra\n\n@test (norm \u2218 normalize)(rand(10)) \u2248 1\n\nend # module test_stdlib_linearalgebra_norm\n", "meta": {"hexsha": "9d9dc21e91010cb40a1d90c8e6044c7de64fe7d9", "size": 2864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/stdlib/linearalgebra.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": "test/stdlib/linearalgebra.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": "test/stdlib/linearalgebra.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": 20.1690140845, "max_line_length": 78, "alphanum_fraction": 0.5712290503, "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693631290971, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7764254321174228}}
{"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_\u03b5\", \"sigma2_\u03be\", \"sigma2_\u03b6\", \"sigma2_\u03c9\"]\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_\u03b5\" => one(Fl),\n        \"sigma2_\u03be\" => one(Fl),\n        \"sigma2_\u03b6\" => one(Fl),\n        \"sigma2_\u03c9\" => 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_\u03b5\")\n    constrain_variance!(model, \"sigma2_\u03be\")\n    constrain_variance!(model, \"sigma2_\u03b6\")\n    constrain_variance!(model, \"sigma2_\u03c9\")\n    return model\nend\n\nfunction unconstrain_hyperparameters!(model::BasicStructural)\n    unconstrain_variance!(model, \"sigma2_\u03b5\")\n    unconstrain_variance!(model, \"sigma2_\u03be\")\n    unconstrain_variance!(model, \"sigma2_\u03b6\")\n    unconstrain_variance!(model, \"sigma2_\u03c9\")\n    return model\nend\n\nfunction fill_model_system!(model::BasicStructural)\n    model.system.H = get_constrained_value(model, \"sigma2_\u03b5\")\n    model.system.Q[1] = get_constrained_value(model, \"sigma2_\u03be\")\n    model.system.Q[5] = get_constrained_value(model, \"sigma2_\u03b6\")\n    model.system.Q[end] = get_constrained_value(model, \"sigma2_\u03c9\")\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": "@testset \"utility.jl\" begin\n    p1 = rad2deg(Point(0.5, 1.0))\n    p2 = rad2deg(Point(1.0, 0.5))\n    p3 = rad2deg(Point(0.6, 1.0))  # above p1\n\n    rs = RouteSection(p1,p2)\n\n    @test (p1-p2).\u03d5 \u2248 -28.6478897565 atol = 0.001\n\n    @test Navigation.normalize(-270.0, -180.0, 180.0) \u2248 90.0 atol = 0.1\n    @test Navigation.normalize(181.0, -180.0, 180.0) \u2248 -179.0 atol = 0.1\n    @test deg2rad(p1).\u03d5 \u2248 0.5 atol = 0.0001\n    @test deg2rad(p2).\u03bb \u2248 0.5 atol = 0.0001\n\n    p3 = Point(80.0, 190.0)\n    @test Navigation.normalize(p3).\u03d5 \u2248 rad2deg(1.3962634016) atol = 0.0001\n    @test Navigation.normalize(p3).\u03bb \u2248 rad2deg(-2.96705972839) atol = 0.0001\n    @test Navigation.normalize(p3).\u03bb \u2248 -170.000 atol = 0.01\n\nend\n", "meta": {"hexsha": "5ad45fa7975d9c3ab38296c344ee6196479c618a", "size": 703, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/utility.jl", "max_stars_repo_name": "rjdverbeek-tud/Navigation.jl", "max_stars_repo_head_hexsha": "7f27ab75cf8f0f34140e1ce838e33a488643b7aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-05T21:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T21:29:10.000Z", "max_issues_repo_path": "test/utility.jl", "max_issues_repo_name": "rjdverbeek-tud/Navigation.jl", "max_issues_repo_head_hexsha": "7f27ab75cf8f0f34140e1ce838e33a488643b7aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2019-11-01T17:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-06T16:34:18.000Z", "max_forks_repo_path": "test/utility.jl", "max_forks_repo_name": "rjdverbeek-tud/Navigation.jl", "max_forks_repo_head_hexsha": "7f27ab75cf8f0f34140e1ce838e33a488643b7aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-05T13:43:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T13:43:03.000Z", "avg_line_length": 33.4761904762, "max_line_length": 76, "alphanum_fraction": 0.613086771, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7764254278962271}}
{"text": "@testset \"life expectancy\" begin\n    \n    @testset \"parametric\" begin\n\n        # ALMC 2.5\n        m = MortalityTables.Gompertz(a=0.0003,b=log(1.07))\n\n        @test life_expectancy(m,0) \u2248 71.938 atol=0.001\n        @test life_expectancy(m,50) \u2248 26.691 atol=0.001\n    end\n\n    @testset \"vector\" begin\n        # if no distribution of deaths given, assume curtate otherwise complete\n        t = MortalityTables.table(\"1980 CSO Basic Table \u2013 Male, ANB\")\n\n        # calculate sum of tpx in Excel\n        @test life_expectancy(t.ultimate,55) \u2248 22.16469212 atol=1e-6\n        @test life_expectancy(t.ultimate,100) \u2248 0.0 atol=1e-6\n\n        @test_throws ArgumentError life_expectancy(t,100)\n\n        # relation of curtate to complete, ALMC 2.6.1\n        @test life_expectancy(t.ultimate,55,MortalityTables.Uniform()) \u2248 22.16469212 + 0.5 atol=1e-3\n    end\n\nend", "meta": {"hexsha": "10675c5e17c1fcec0653d0514838550160f07104", "size": 847, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/life_expectancy.jl", "max_stars_repo_name": "MatthewCaseres/MortalityTables.jl", "max_stars_repo_head_hexsha": "0b86f174115fd3a2126addc974e5735f3e3bcf22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-02-09T08:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T18:06:01.000Z", "max_issues_repo_path": "test/life_expectancy.jl", "max_issues_repo_name": "MatthewCaseres/MortalityTables.jl", "max_issues_repo_head_hexsha": "0b86f174115fd3a2126addc974e5735f3e3bcf22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2019-12-18T01:38:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:33:15.000Z", "max_forks_repo_path": "test/life_expectancy.jl", "max_forks_repo_name": "MatthewCaseres/MortalityTables.jl", "max_forks_repo_head_hexsha": "0b86f174115fd3a2126addc974e5735f3e3bcf22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-31T01:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T06:44:59.000Z", "avg_line_length": 32.5769230769, "max_line_length": 100, "alphanum_fraction": 0.6493506494, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7763677023798635}}
{"text": "Q, R = qr([12 -51 4; 6 167 -68; -4 24 -41])\n", "meta": {"hexsha": "dbf961d4ac17c65ed0dd11cbc7ac4172fbb77bc9", "size": 44, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/qr-decomposition.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/qr-decomposition.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/qr-decomposition.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.0, "max_line_length": 43, "alphanum_fraction": 0.4545454545, "num_tokens": 26, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122696813392, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7763676843556598}}
{"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(\u03c3)\n\nStores the bandwidth parameter `\u03c3` 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_\u03c3_sq::F\n    \n    SqExp(\u03c3::F = 1.0) where F <: Real = new{F}(-F(0.5)/(\u03c3^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_\u03c3_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\u2013Bera 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\u03bb], 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 #[\u03bb]\n    vv = vv .* 1e3 #[\u03bb]\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\u03bb], 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 \u03c1 da corda\n\n## densidade pela geometria\n\nm1 = 0.00552 \u00b1 0.00001 # kg\nl = 22.97 \u00b1 0.01 # m\n\n\u03c11 = m1.val/l.val \u00b1 (m1.val*l.err + m1.err*l.val)/l.val^2\nprintstyled(\"Densidade linear calculada pela geometria \\n\"; color=:red);\nprintln(\"\u03c1 \u00b1 \u0394\u03c1 = (\",\u03c11, \") kg/m\");\n\n\n## densidade pela tra\u00e7\u00e3o\nm2 = 0.06067 \u00b1 0.00001 #kg\nv = [48.9, 49.5, 49.8, 49.7, 49.3]\nvm = Statistics.mean(v);\nv = round(vm,digits=3) \u00b1 round(standartDeviation(v),digits=2);\nprintstyled(\"Velocidade m\u00e9dia e erro calculado pelo desvio padr\u00e3o\\n\"; color=:red);\nprintln(\"v_medio \u00b1 \u0394v = (\",v, \") m/s\")\n\n\n# tra\u00e7\u00e3o\ng = 9.81\nt = m2.val*g \u00b1 m2.err*g# Newtons\nprintstyled(\"Tra\u00e7\u00e3o:\\n\"; color=:red);\nprintln(\"T \u00b1 \u0394T = (\", t, \") N\");\n\n# densidade linear calculada a partir da tra\u00e7\u00e3o\n\u03c12 = t.val/v.val^2 \u00b1 (2*t.val*v.val*v.err + t.err*v.val^2)/(v.val^4)\nprintstyled(\"Densidade linear \\n \"; color =:red);\nprintln(\"\u03c12 \u00b1 \u0394\u03c12= (\", \u03c12 , \") kg/m\");\n\n\n\n# equival\u00eancia\n\nv1 = abs(\u03c12.val - \u03c11.val);\nv2 = 2*(\u03c11.err + \u03c12.err);\n\nprintstyled(\"Checando equival\u00eancia\", color=:red);\nprintln(\"| x1 - x2 | < 2*(\u03c31 + \u03c32)\");\nprintln(\"| \",round(\u03c11.val,digits=10) , \" - \", round(\u03c12.val,digits=10) , \" | < 2*(\", round(\u03c11.err,digits=10), \" + \", round(\u03c12.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 \u00b1 0.0001);\nf = []\nn = 5\n\n\n## frequ\u00eancia constante\nprintstyled(\"Experimento 3\\n\", color =:green);\n\nf = (2000\u00b10.1);\nL = [0.087,0.088,0.086,0.087];\n\u0394L = 0.1;\n\n\u03bb(L) = 2*L;\n\n\u03bbs = Statistics.mean([\u03bb(L[1]),\u03bb(L[2]),\u03bb(L[3]),\u03bb(L[4])]) \u00b1 standartDeviation(L);\n\n\nprintstyled(\"Frequ\u00eancia constante \\n \", color =:red);\n\nprintln(\"Comprimento de onda m\u00e9dio: \u03bb \u00b1 \u0394\u03bb = \", \u03bbs);\n\nv =  \u03bbs*f;\nprintln(\"Velocidade m\u00e9dia: v \u00b1 \u0394v = \",v);\n\n\n\n\n\n## g\u00e1s desconhecido\nprintstyled(\"Experimento 4 - G\u00e1s desconhecido 1\u00b0 harm\u00f4nico \\n \", color =:red);\nf = (2000\u00b10.1);\nn = 1\nl = (0.23 \u00b10.0001);\n\nv = 2*l*f;\nprintln(\"Velocidade m\u00e9dia: v \u00b1 \u0394v = \",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": "using Plots\n\ninclude(\"QuadraturePoints.jl\")\ninclude(\"element_matrices.jl\")\n\n#Some Constants\nDFloat = Float64\nmachine_zero=eps(DFloat)\n\n#ipoints=1: Lobatto\n#ipoints=2: Legendre\n#ipoints=3: Chebyshev\n#ipoints=4: Equi-spaced\n\n#{{{ Main\nfunction main()\n\n    #Fix Interpolation and Integration Order\n    N=1\n    Q=N+1\n    Np=N+1\n    Nq=Q+1\n    ipoints=1\n    qpoints=1\n\n    #Allocate Arrays\n    M=zeros(DFloat,Np,Np)\n    D=zeros(DFloat,Np,Np)\n\n    #Select Interpolation Points\n    if ipoints == 1\n        (\u03be,\u03c9) = QuadraturePoints.lobatto_gauss(Np,DFloat) #Lobatto\n    elseif ipoints == 2\n        (\u03be,\u03c9) = QuadraturePoints.legendre_gauss(Np,DFloat) #Legendre\n    elseif ipoints == 3\n        (\u03be,\u03c9) = QuadraturePoints.chebyshev_gauss(Np,DFloat) #Chebyshev\n    elseif ipoints == 4\n        (\u03be,\u03c9) = QuadraturePoints.equispaced_points(Np,DFloat) #Equi-spaced\n    end\n\n    #Select Quadrature Points\n    if qpoints == 1\n        (\u03beq,\u03c9q) = QuadraturePoints.lobatto_gauss(Nq,DFloat) #Lobatto\n    elseif qpoints == 2\n        (\u03beq,\u03c9q) = QuadraturePoints.legendre_gauss(Nq,DFloat) #Legendre\n    end\n\n    #Construct Lagrange Polynomials\n    (\u03c8,d\u03c8) = QuadraturePoints.lagrange_basis(Np,Nq,\u03be,\u03beq)\n\n    (M,D) = element_matrices(\u03c8,d\u03c8,Np,Nq,\u03c9q,DFloat)\n\n    #Check correctness\n    for j=1:Np, i=1:Np\n        @show(i,j,M[i,j])\n    end\n    row_sum=zeros(DFloat,Np)\n    for i=1:Np\n        row_sum[i]=sum(D[i,:])\n    end\n    @show(row_sum)\n    @show(sum(M))\n\n    #Plot Interpolation\n    println(\"Done\") #output\n\nend\n#}}} Main\n\n#----------------------------------#\n# Run the main function\n#----------------------------------#\nmain()\n", "meta": {"hexsha": "611a06f3221ebe4b13b9da53f48228a377e80ea4", "size": 1597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_02_1D_Wave/For_Instructors/julia/Global_Matrices_approach/Project2_Mass_and_Differentiation.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/Global_Matrices_approach/Project2_Mass_and_Differentiation.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/Global_Matrices_approach/Project2_Mass_and_Differentiation.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": 21.5810810811, "max_line_length": 74, "alphanum_fraction": 0.6186599875, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7763028969131461}}
{"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(; \u03b1) = new{typeof(\u03b1)}(\u03b1)\nend\n\n# Dirichlet(\u03b1::Real...) = Dirichlet(\u03b1)\n# Dirichlet(\u03b1::Integer...) = Dirichlet(Float64.(\u03b1))\n# Dirichlet(n::Integer, \u03b1::Real)= Dirichlet(ntuple(_->\u03b1, n))\n\n\nfunction randDirichlet(\u03b1::Tuple{Vararg{T}}) where T<:Real\n    p = Tuple(randGamma(\u03b1i, one(T)) for \u03b1i in \u03b1)\n    p ./ sum(p)\nend\nrandDirichlet(\u03b1::Tuple{Vararg{Integer}}) = randDirichlet(Float64.(\u03b1))\nrandDirichlet(n::Integer, \u03b1::Real) = randDirichlet(Tuple(\u03b1 for _ in 1:n))\nrandDirichlet(n::Integer, \u03b1::Integer) = randDirichlet(n, Float64(\u03b1))\n\n@cufunc function logpdfDirichlet(x::NTuple{N,Real}, \u03b1::NTuple{N,Real}) where N\n    # a, b = sum(u -> SVector(u,lgamma(u)), \u03b1)\n    # s = sum(((u,v) -> (u-one(u))log(v)).(\u03b1, x))\n    # s - b + lgamma(a)\n    T = promote_type(typeof.(x)..., typeof.(\u03b1)...)\n    a = b = s = zero(T)\n    for (xi, \u03b1i) in zip(x, \u03b1)\n        a += T(\u03b1i)\n        b += lgamma(T(\u03b1i))\n        s += (T(\u03b1i) - 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": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mos\u00e8 Giordano.\n\n\"\"\"\n    sec2rad(sec) -> radians\n\n### Purpose ###\n\nConvert from seconds to radians.\n\n### Argument ###\n\n* `sec`: number of seconds.\n\n### Output ###\n\nThe number of radians corresponding to `sec`.\n\n### Example ###\n\n```jldoctest\njulia> using AstroLib\n\njulia> sec2rad(3600 * 30)\n0.5235987755982988\n```\n\n### Notes ###\n\nUse `rad2sec` to convert radians to seconds.\n\"\"\"\nsec2rad(sec::Real) = deg2rad(sec / 3600)\n", "meta": {"hexsha": "9508a7496849dfa7258222553a0c2b71a736e688", "size": 501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sec2rad.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/sec2rad.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/sec2rad.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": 15.1818181818, "max_line_length": 61, "alphanum_fraction": 0.6506986028, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7762938535559392}}
{"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\u2013335, 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": "using OrdinaryDiffEq, Test, DiffEqDevTools, DiffEqOperators\nusing LinearAlgebra, Random\n\nRandom.seed!(0); u0 = rand(2)\nA = DiffEqArrayOperator([2.0 -1.0; -1.0 2.0])\n\n# B = DiffEqArrayOperator(ones(2,2))\n# L = AffineDiffEqOperator{Float64}((A,B),(),rand(2))\n# function (p::typeof(L))(::Type{Val{:analytic}},u0,p,t)\n#     exp((p.As[1].A+p.As[2].A)*t)*u0\n# end\n\n# # Midpoint splitting\n\n# prob = ODEProblem(L,u0,(0.0,1.0))\n# sol = solve(prob,MidpointSplitting(),dt=1/10)\n# # using Plots; pyplot; plot(sol)\n\n\n# ## Midpoint splitting convergence\n# ##\n# ## We use the inhomogeneous Lorentz equation for an electron in a\n# ## time-dependent field. To write this on matrix form and simplify\n# ## comparison with the analytic solution, we introduce two dummy\n# ## variables:\n# ## 1) As the third component, a one is stored to allow the\n# ##    inhomogeneous part to be expressed on matrix form.\n# ## 2) As the fourth component, the initial time t_i is stored,\n# ##    for use by the analytical formula.\n# ## This wastes a lot of space, but simplifies the error analysis.\n# ##\n# ## We can then write the Lorentz equation as q\u0307 = [A + f(t)B]q.\n\n# f = t -> -sin(2pi*t)\n# F = t -> cos(2pi*t)/2pi # Primitive function of f(t)\n\n# A = DiffEqArrayOperator([0 1 0 0\n#                          0 0 0 0\n#                          0 0 0 0\n#                          0 0 0 0])\n\n# B = DiffEqArrayOperator([0 0 0 0\n#                          0 0 1 0\n#                          0 0 0 0\n#                          0 0 0 0], f)\n\n# H = AffineDiffEqOperator{Float64}((A,B),(),rand(4))\n# function (p::typeof(H))(::Type{Val{:analytic}},u0,p,t)\n#     x0,v0 = u0[1:2]\n#     ti = u0[end]\n#     x = x0 + (t-ti)*v0 - (f.(t)-f(ti))/(2pi)^2 - (t-ti)*F(ti)\n#     v = v0 + (F.(t)-F(ti))\n#     [x, v, 1, ti]\n# end\n\n# x0,v0,ti = rand(3)\n# prob = ODEProblem(H, [x0, v0, 1, ti], (ti, 5.))\n# dts = 1./2.^(10:-1:1)\n# sim  = test_convergence(dts,prob,MidpointSplitting())\n# @test sim.\ud835\udcaaest[:l2] \u2248 2 atol=0.2\n\n# Linear exponential solvers\nprob = ODEProblem(A,u0,(0.0,1.0))\nsol1 = solve(prob, LinearExponential(krylov=:off))(1.0)\nsol2 = solve(prob, LinearExponential(krylov=:simple))(1.0)\nsol3 = solve(prob, LinearExponential(krylov=:adaptive))(1.0)\nsol_analytic = exp(1.0 * Matrix(A)) * u0\n\n@test isapprox(sol1, sol_analytic, rtol=1e-10)\n@test isapprox(sol2, sol_analytic, rtol=1e-10)\n@test isapprox(sol3, sol_analytic, rtol=1e-10)\n", "meta": {"hexsha": "a23be8176a654358d9f74afae853d7a253bc332f", "size": 2382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/algconvergence/linear_method_tests.jl", "max_stars_repo_name": "jlumpe/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "2749f37186f0dce04fbe9351571a11364426f51f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-10T17:32:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-10T17:32:02.000Z", "max_issues_repo_path": "test/algconvergence/linear_method_tests.jl", "max_issues_repo_name": "jlumpe/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "2749f37186f0dce04fbe9351571a11364426f51f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-16T19:27:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T19:27:47.000Z", "max_forks_repo_path": "test/algconvergence/linear_method_tests.jl", "max_forks_repo_name": "jlumpe/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "2749f37186f0dce04fbe9351571a11364426f51f", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 68, "alphanum_fraction": 0.6003358522, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7762938433208653}}
{"text": "\"\"\"\n    capm(asset_returns, benchmark_returns; risk_free=0.0)\n\nCalculates the CAPM \u03b1 and \u03b2 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 = \u03b1 + \u03b2(r_b - r_f) + \u03f5\n\nThe \u03b1 coefficient in this model is also known as Jensen's alpha. \u03b2 is the slope coefficient, and \u03f5 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 (\u03b1, \u03b2) with the estimated \u03b1 and \u03b2 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    \u03bc1 = mean(asset_returns_ex)\n    \u03bc2 = mean(benchmark_returns_ex)\n    \u03b2 = sum((asset_returns_ex .- \u03bc1).*(benchmark_returns_ex .- \u03bc2)) / sum((benchmark_returns_ex .- \u03bc2).^2)\n    \u03b1 = \u03bc1 - \u03b2*\u03bc2\n    (\u03b1, \u03b2)\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": "using LinearAlgebra, DiffEqOperators, Random, Test, BandedMatrices, SparseArrays\n\nfunction fourth_deriv_approx_stencil(N)\n    A = zeros(N,N+2)\n    A[1,1:8] = [3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3]\n    A[2,1:8] = [2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6]\n    A[N-1,N-5:end] = reverse([2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6], dims=2)\n    A[N,N-5:end] = reverse([3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3], dims=2)\n    for i in 3:N-2\n        A[i,i-2:i+4] = [-1/6 2.0 -13/2 28/3 -13/2 2.0 -1/6]\n    end\n    return A\nend\n\nfunction second_derivative_stencil(N)\n  A = zeros(N,N+2)\n  for i in 1:N, j in 1:N+2\n      (j-i==0 || j-i==2) && (A[i,j]=1)\n      j-i==1 && (A[i,j]=-2)\n  end\n  A\nend\n\n@testset \"Differentiation on 2D array\" begin\n    M = zeros(22,22)\n    M_temp = zeros(20,22)\n    indices = Iterators.drop(CartesianIndices((22,22)), 0)\n    for idx in indices\n        M[idx] = sin(idx[1]*0.1)\n    end\n    L = CenteredDifference(4,4,0.1,20)\n\n    #test mul!\n    mul!(M_temp, L, M)\n\n    correct_row = 10000.0*fourth_deriv_approx_stencil(20)*M[:,1]\n\n    for i in 1:22\n        @test M_temp[:,i] \u2248 correct_row\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp == L*M\n\n    # Differentiation along second dimension\n    L = CenteredDifference{2}(4,4,0.1,20)\n    M_temp_2 = zeros(22,20)\n    indices = Iterators.drop(CartesianIndices((22,22)), 0)\n    for idx in indices\n        M[idx] = sin(idx[2]*0.1)\n    end\n\n    #test mul!\n    mul!(M_temp_2, L, M)\n    for i in 1:22\n        @test M_temp_2[i,:] \u2248 correct_row\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp_2 == L*M\nend\n\n@testset \"Differenting on 3D array with L2\" begin\n    M = zeros(22,22,22)\n    M_temp = zeros(20,22,22)\n    indices = Iterators.drop(CartesianIndices((22,22,22)), 0)\n    for idx in indices\n        M[idx] = sin(idx[1]*0.1)\n    end\n    L = CenteredDifference(2,2,0.1,20)\n\n    #test mul!\n    mul!(M_temp, L, M)\n\n    correct_row = 100.0*second_derivative_stencil(20)*M[:,1,1]\n\n    for i in 1:22\n        for j in 1:22\n            @test M_temp[:,i,j] \u2248 correct_row\n        end\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp == L*M\n\n    # Differentiation along second dimension\n    L = CenteredDifference{2}(2,2,0.1,20)\n    M_temp_2 = zeros(22,20,22)\n    indices = Iterators.drop(CartesianIndices((22,22,22)), 0)\n    for idx in indices\n        M[idx] = sin(idx[2]*0.1)\n    end\n\n    #test mul!\n    mul!(M_temp_2, L, M)\n    for i in 1:22\n        for j in 1:22\n            @test M_temp_2[i,:,j] \u2248 correct_row\n        end\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp_2 == L*M\n\n    # Differentiation along third dimension\n    L = CenteredDifference{3}(2,2,0.1,20)\n    M_temp_3 = zeros(22,22,20)\n    indices = Iterators.drop(CartesianIndices((22,22,22)), 0)\n    for idx in indices\n        M[idx] = sin(idx[3]*0.1)\n    end\n\n    #test mul!\n    mul!(M_temp_3, L, M)\n    for i in 1:22\n        for j in 1:22\n            @test M_temp_3[i,j,:] \u2248 correct_row\n        end\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp_3 == L*M\nend\n\n@testset \"Differentiation on 3D array with L4\" begin\n    M = zeros(22,22,22)\n    M_temp = zeros(20,22,22)\n    indices = Iterators.drop(CartesianIndices((22,22,22)), 0)\n    for idx in indices\n        M[idx] = sin(idx[1]*0.1)\n    end\n    L = CenteredDifference(4,4,0.1,20)\n\n    #test mul!\n    mul!(M_temp, L, M)\n\n    correct_row = 10000.0*fourth_deriv_approx_stencil(20)*M[:,1,1]\n\n    for i in 1:22\n        for j in 1:22\n            @test M_temp[:,i,j] \u2248 correct_row\n        end\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp == L*M\n\n    # Differentiation along second dimension\n    L = CenteredDifference{2}(4,4,0.1,20)\n    M_temp_2 = zeros(22,20,22)\n    for idx in indices\n        M[idx] = sin(idx[2]*0.1)\n    end\n\n    #test mul!\n    mul!(M_temp_2, L, M)\n    for i in 1:22\n        for j in 1:22\n            @test M_temp_2[i,:,j] \u2248 correct_row\n        end\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp_2 == L*M\n\n    # Differentiation along third dimension\n    L = CenteredDifference{3}(4,4,0.1,20)\n    M_temp_3 = zeros(22,22,20)\n    for idx in indices\n        M[idx] = sin(idx[3]*0.1)\n    end\n\n    #test mul!\n    mul!(M_temp_3, L, M)\n    for i in 1:22\n        for j in 1:22\n            @test M_temp_3[i,j,:] \u2248 correct_row\n        end\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp_3 == L*M\nend\n\n@testset \"Differentiating an arbitrary higher dimension\" begin\n    N = 6\n    L = CenteredDifference{N}(4,4,0.1,30)\n    M = zeros(5,5,5,5,5,32,5);\n    M_temp = zeros(5,5,5,5,5,30,5);\n    indices = Iterators.drop(CartesianIndices((5,5,5,5,5,32,5)), 0);\n    for idx in indices\n        M[idx] = cos(idx[N]*0.1)\n    end\n\n    correct_row = (10.0^4)*fourth_deriv_approx_stencil(30)*M[1,1,1,1,1,:,1]\n\n    #test mul!\n    mul!(M_temp, L, M)\n    indices = Iterators.drop(CartesianIndices((5,5,5,5,5,30,5)), 0);\n    for idx in indices\n        @test M_temp[idx] \u2248 correct_row[idx[N]]\n    end\n\n    # Test that * agrees will mul!\n    @test M_temp == L*M\nend\n\n@testset \"Differentiating with non-symmetric interior stencil\" begin\n\n    # The following tests check that multiplication of an operator with a\n    # non-symmetric interior stencil is consistent with what we expect\n\n    N = 1\n    L = CenteredDifference{N}(3,4,0.1,30)\n    M = zeros(32,32)\n    for i in 1:32\n        for j in 1:32\n            M[i,j] = cos(0.1i)\n        end\n    end\n\n    M_temp = zeros(30,32)\n    mul!(M_temp, L, M)\n\n    @test M_temp \u2248 Array(L)*M\n\n    N = 2\n    L = CenteredDifference{N}(3,4,0.1,30)\n    M = zeros(32,32)\n    for i in 1:32\n        for j in 1:32\n            M[i,j] = cos(0.1j)\n        end\n    end\n\n    M_temp = zeros(32,30)\n    mul!(M_temp, L, M)\n\n    @test M_temp \u2248 transpose(Array(L)*transpose(M))\n\n    # Three dimensions\n\n    N = 1\n    L = CenteredDifference{N}(3,4,0.1,30)\n    M = zeros(32,32,32)\n    for i in 1:32\n        for j in 1:32\n            for k in 1:32\n                M[i,j,k] = cos(0.1i)\n            end\n        end\n    end\n\n    M_temp = zeros(30,32,32)\n    mul!(M_temp, L, M)\n    for i in 1:32\n        @test M_temp[:,:,i] \u2248 Array(L)*M[:,:,i]\n    end\n\n    correct_row = L*M[:,1,1]\n\n    N = 2\n    L = CenteredDifference{N}(3,4,0.1,30)\n    M = zeros(32,32,32)\n    for i in 1:32\n        for j in 1:32\n            for k in 1:32\n                M[i,j,k] = cos(0.1j)\n            end\n        end\n    end\n\n    M_temp = zeros(32,30,32)\n    mul!(M_temp, L, M)\n\n    for i in 1:32\n        for j in 1:32\n            @test M_temp[i,:,j] \u2248 correct_row\n        end\n    end\n\n    N = 3\n    L = CenteredDifference{N}(3,4,0.1,30)\n    M = zeros(32,32,32)\n    for i in 1:32\n        for j in 1:32\n            for k in 1:32\n                M[i,j,k] = cos(0.1k)\n            end\n        end\n    end\n\n    M_temp = zeros(32,32,30)\n    mul!(M_temp, L, M)\n\n    for i in 1:32\n        for j in 1:32\n            @test M_temp[i,j,:] \u2248 correct_row\n        end\n    end\nend\n\n@testset \"Differentiating with coefficients\" begin\n\n    # Three dimensions\n    N = 1\n    \u00b5 = 5.5\n    L = CenteredDifference{N}(3,4,0.1,30)\n\n    \u00b5L = \u00b5*L\n    M = zeros(32,32,32)\n    for i in 1:32\n        for j in 1:32\n            for k in 1:32\n                M[i,j,k] = cos(0.1i)\n            end\n        end\n    end\n\n    correct_slice = 5.5*(L*M[:,1,1])\n    M_temp = zeros(30,32,32)\n    mul!(M_temp, \u00b5L, M)\n\n    for i in 1:32\n        for j in 1:32\n            @test M_temp[:,i,j] \u2248 correct_slice\n        end\n    end\n\n    N = 2\n    \u00b5L = \u00b5*CenteredDifference{N}(3,4,0.1,30)\n    M = zeros(32,32,32)\n    for i in 1:32\n        for j in 1:32\n            for k in 1:32\n                M[i,j,k] = cos(0.1j)\n            end\n        end\n    end\n\n    M_temp = zeros(32,30,32)\n    mul!(M_temp, \u00b5L, M)\n\n    for i in 1:32\n        for j in 1:32\n            @test M_temp[i,:,j] \u2248 correct_slice\n        end\n    end\n\n    N = 3\n    \u00b5L = \u00b5*CenteredDifference{N}(3,4,0.1,30)\n    M = zeros(32,32,32)\n    for i in 1:32\n        for j in 1:32\n            for k in 1:32\n                M[i,j,k] = cos(0.1k)\n            end\n        end\n    end\n\n    M_temp = zeros(32,32,30)\n    mul!(M_temp, \u00b5L, M)\n\n    for i in 1:32\n        for j in 1:32\n            @test M_temp[i,j,:] \u2248 correct_slice\n        end\n    end\nend\n", "meta": {"hexsha": "5ab6f6fca5240af3ea4020e7e10e2cfd8b5a0ff4", "size": 8189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DerivativeOperators/differentiation_dimension.jl", "max_stars_repo_name": "briochemc/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/differentiation_dimension.jl", "max_issues_repo_name": "briochemc/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/differentiation_dimension.jl", "max_forks_repo_name": "briochemc/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": 22.1324324324, "max_line_length": 80, "alphanum_fraction": 0.5331542313, "num_tokens": 3097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176860436174, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7762919478272545}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 d9cff120-aba1-11eb-0f83-db8e49ac6bab\nmd\"# Chapter 03 from NNFS book\"\n\n# \u2554\u2550\u2561 4a34dd2f-cbf5-4ac0-8f97-fd4050354547\nmd\"### 2 Layers of Neurons (4 inputs, 3 hidden layers)\"\n\n# \u2554\u2550\u2561 ab14105e-a405-4d87-80d7-940ce87ef19a\nmd\"\"\"\n**One observation:**\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7ec38404-9380-411d-8b0d-f073ba5c6cbc\nmd\"\"\"\n**Multiple observations:**\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6aabd18d-d0a1-4f7e-9019-92d7671e7265\nmd\"### Creating the LayerDense Struct\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 da9d7fdb-8b5a-466c-9370-654c133e10a3\nD = LayerDense(2, 3)\n\n# \u2554\u2550\u2561 173fe819-779e-4d8e-a2b3-e00fb9363cb2\nimp01 = [3.5, 4.3]\n\n# \u2554\u2550\u2561 c14fce98-4470-4153-ba62-75521c3e5ed8\nimp02 = [[3.5, 4.3] [2.4, -2.8]]\n\n# \u2554\u2550\u2561 f8915121-453b-49bc-83ed-07ea13541160\nD(imp01)\n\n# \u2554\u2550\u2561 ffe4c9ac-bbbf-49e0-b882-b6a8ed096622\nD(imp02)\n\n# \u2554\u2550\u2561 ae0e3918-c07e-40a5-880d-15cec3afce71\nD(randn(2))\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500d9cff120-aba1-11eb-0f83-db8e49ac6bab\n# \u255f\u25004a34dd2f-cbf5-4ac0-8f97-fd4050354547\n# \u255f\u2500ab14105e-a405-4d87-80d7-940ce87ef19a\n# \u2560\u2550fed9705c-b748-4cf9-827a-f10fd8073967\n# \u255f\u25007ec38404-9380-411d-8b0d-f073ba5c6cbc\n# \u2560\u2550773a22f6-99c3-4bf5-936b-0b22759038ed\n# \u255f\u25006aabd18d-d0a1-4f7e-9019-92d7671e7265\n# \u2560\u255050edc678-40c3-483c-8556-666f01553802\n# \u2560\u2550da9d7fdb-8b5a-466c-9370-654c133e10a3\n# \u2560\u2550173fe819-779e-4d8e-a2b3-e00fb9363cb2\n# \u2560\u2550c14fce98-4470-4153-ba62-75521c3e5ed8\n# \u2560\u2550f8915121-453b-49bc-83ed-07ea13541160\n# \u2560\u2550ffe4c9ac-bbbf-49e0-b882-b6a8ed096622\n# \u2560\u2550ae0e3918-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": "\"\"\"\n\n    euclideanDistances(dataMatrix)\n\nCalculate Euclidean distances between pairs. \n\n# Arguments\n- `dataMatrix::Array{Float64, 1}`: Data matrix with dimensions n x p, where n is the number of observations and p is the number of variables.\n\n# Notes\n    This is the helper function for the dataimage() function defined in Marchette & Solka (2003).\n    \n# References\nMarchette, David J., and Jeffrey L. Solka. \"Using data images for outlier detection.\" \nComputational Statistics & Data Analysis 43.4 (2003): 541-552.\n\"\"\"\nfunction euclideanDistances(dataMatrix::Array{Float64,2})::Array{Float64,2}\n    n, p = size(dataMatrix)\n    d = zeros(Float64, n, n)\n    for i in 1:n\n        for j in i:n\n            if i != j \n                @inbounds d[i, j] = sqrt(sum((dataMatrix[i,:] .- dataMatrix[j,:]).^2.0))\n                @inbounds d[j, i] = d[i, j]\n            end\n        end\n    end\n    return d\nend\n\n\n\"\"\"\n\n    mahalanobisBetweenPairs(dataMatrix)\n\nCalculate Mahalanobis distances between pairs. \n\n# Arguments\n- `dataMatrix::Array{Float64, 1}`: Data matrix with dimensions n x p, where n is the number of observations and p is the number of variables.\n\n# Notes\n    Differently from Mahalabonis distances, this function calculates Mahalanobis distances between \n    pairs, rather than the distances to center of the data. This is the helper function for the \n    dataimage() function defined in Marchette & Solka (2003).\n    \n# References\nMarchette, David J., and Jeffrey L. Solka. \"Using data images for outlier detection.\" \nComputational Statistics & Data Analysis 43.4 (2003): 541-552.\n\"\"\"\nfunction mahalanobisBetweenPairs(dataMatrix::Array{Float64,2})::Array{Float64,2}\n    n, p = size(dataMatrix)\n    d = zeros(Float64, n, n)\n    covmat = cov(dataMatrix)\n    if det(covmat) == 0.0\n        @warn \"Covariance matrix is singular, mahalanobis distances can not be calculated.\"\n    end\n    covinv = inv(covmat)\n    for i in 1:n\n        for j in i:n\n            if i != j \n                @inbounds d[i, j] = sqrt((dataMatrix[i,:] .- dataMatrix[j,:]) * covinv * (dataMatrix[i,:] .- dataMatrix[j,:])')\n                @inbounds d[j, i] = d[i, j]\n            end\n        end\n    end\n    return d\nend\n\n\n\n\"\"\"\n\n    dataimage(dataMatrix; distance = :mahalanobis)\n\nGenerate the Marchette & Solka (2003) data image for a given data matrix. \n\n# Arguments\n- `dataMatrix::Array{Float64, 1}`: Data matrix with dimensions n x p, where n is the number of observations and p is the number of variables.\n- `distance::Symbol`: Optional argument for the distance function.\n\n# Notes\n    distance is :mahalanobis by default, for the Mahalanobis distances. \n    use \n\n        dataimage(mat, distance = :euclidean)\n    \n    to use Euclidean distances.\n    \n# Examples\n```julia-repl\njulia> x1 = hbk[:,\"x1\"];\njulia> x2 = hbk[:,\"x2\"];\njulia> x3 = hbk[:,\"x3\"];\njulia> mat = hcat(x1, x2, x3);\njulia> dataimage(mat)\n```\n\n# References\nMarchette, David J., and Jeffrey L. Solka. \"Using data images for outlier detection.\" \nComputational Statistics & Data Analysis 43.4 (2003): 541-552.\n\"\"\"\nfunction dataimage(dataMatrix::Array{Float64,2}; distance=:mahalanobis)\n    d = nothing\n    if distance == :mahalanobis\n        d = mahalanobisSquaredBetweenPairs(dataMatrix)\n    elseif distance == :euclidean\n        d = euclideanDistances(dataMatrix)\n    else\n        @error \"Distance function unknown: \" distance \n        @error \"Using mahalanobis instead\"\n        d = mahalanobisSquaredBetweenPairs(dataMatrix)\n    end\n    colours = 1.0 .- d / maximum(d)\n    n, _ = size(d)\n    colormatrix = Array{RGB{Float64}}(undef, n, n)\n    for i in 1:n\n        for j in 1:n\n            @inbounds colormatrix[i, j] = RGB(colours[i, j])\n        end\n    end\n    plot(colormatrix)\nend\n", "meta": {"hexsha": "485706782787acce60faaffa9a04647606dd4d8b", "size": 3731, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dataimage.jl", "max_stars_repo_name": "akadal/LinRegOutliers", "max_stars_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:13:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:13:31.000Z", "max_issues_repo_path": "src/dataimage.jl", "max_issues_repo_name": "akadal/LinRegOutliers", "max_issues_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-09-21T09:30:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T18:52:18.000Z", "max_forks_repo_path": "src/dataimage.jl", "max_forks_repo_name": "akadal/LinRegOutliers", "max_forks_repo_head_hexsha": "86bcb5ffb61ddc40b162b30c782d9f6799de64ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-09-22T20:04:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T22:24:04.000Z", "avg_line_length": 30.3333333333, "max_line_length": 141, "alphanum_fraction": 0.6537121415, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.776282109780745}}
{"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- `\u03b1::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    \u03b1::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.\u03b1 * 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": "using Jags, StatsPlots, Random, Distributions\n\ncd(@__DIR__)\nProjDir = pwd()\nRandom.seed!(3431)\n\ny = rand(Normal(0,1),50)\n\nModel = \"\nmodel {\n      for (i in 1:length(y)) {\n            y[i] ~ dnorm(mu[i],sigma);\n      }\n      for(i in 1:length(y)){\n            mu[i]  ~ dnorm(0, 1/sqrt(10));\n        }\n\n      sigma  ~ dt(0,1,1) T(0, );\n  }\n\"\n\nmonitors = Dict(\n  \"mu\" => true,\n  \"sigma\" => true,\n  )\n\ninits = [\n  Dict(\"mu\"=>.0,\"sigma\"=>1.0)\n]\n\n\njagsmodel = Jagsmodel(\n  name=\"Gaussian\",\n  model=Model ,\n  monitor=monitors,\n  ncommands=1, nchains=4\n  ,\n  #deviance=true, dic=true, popt=true,\n  pdir=ProjDir\n  )\n\nprintln(\"\\nJagsmodel that will be used:\")\njagsmodel |> display\n\ndata = Dict{String, Any}(\n  \"y\" => y,\n)\n\ninits = [\n  Dict(\"mu\" => 0.0,\"sigma\" => 1.0,\n  \".RNG.name\" => \"base::Mersenne-Twister\")\n]\n\nprintln(\"Input observed data dictionary:\")\ndata |> display\nprintln(\"\\nInput initial values dictionary:\")\ninits |> display\nprintln()\n#######################################################################################\n#                                 Estimate Parameters\n#######################################################################################\nsim = jags(jagsmodel, data, inits, ProjDir)\nsim = sim[5001:end,:,:]\n", "meta": {"hexsha": "673a62cba8a532b641caac5f26f185ef6d874eca", "size": 1234, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_chris2.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Jags.jl-7de783dc-89a7-511c-b223-597fcba0cc71", "max_stars_repo_head_hexsha": "6f07bf05efe6775705d4ac9cbafce3334cea6325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:40:06.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T22:09:49.000Z", "max_issues_repo_path": "test/test_chris2.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Jags.jl-7de783dc-89a7-511c-b223-597fcba0cc71", "max_issues_repo_head_hexsha": "6f07bf05efe6775705d4ac9cbafce3334cea6325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-01-16T23:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-23T17:02:03.000Z", "max_forks_repo_path": "test/test_chris2.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Jags.jl-7de783dc-89a7-511c-b223-597fcba0cc71", "max_forks_repo_head_hexsha": "6f07bf05efe6775705d4ac9cbafce3334cea6325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:34:15.000Z", "avg_line_length": 19.28125, "max_line_length": 87, "alphanum_fraction": 0.4854132901, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7762106214238479}}
{"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\u03bb = 100         # Frequencey of changes\n\n# Mu parameter sampled from a N(0,10) distribution for each changepoint\n\u03bc = Normal(0,5) \n\u03c3 = 1.0 # Sigma parameter fixed\n\n# Construct sample with changepoints where\n# at each changepoint a new value is sample for \u03bc\nsample, cps = @changepoint_sampler n \u03bb Normal(\u03bc, \u03c3)\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 \u03c3\npelt_cps, pelt_cost = @PELT sample Normal(:?, \u03c3)\n\n# Find changepoints via Binary Segmentation\nbs_cps, bs_cost = @BS sample Normal(:?, \u03c3)\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\ufb01cation; 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)) \u00f7 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: \u2202_t T = \u03b1 * \u2207\u00b2(T) + \u03b2*sin(\u03b3*z)\n# Boundary conditions: \u2207T(z=a) = \u2207T_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\u0302_min, n\u0302_max = -1, 1            # Outward facing unit vectors\n\u03b1 = 100;                        # thermal diffusivity, larger means more stiff\n\u03b2, \u03b3 = 10000, \u03c0;                # source term coefficients\n\u0394t = 1000;                      # timestep\nN_t = 10;                       # number of timesteps\nFT = Float64;                   # float type\n\u0394z = FT(b-a)/FT(n)\n\u0394z\u00b2 = \u0394z^2;\n\u2207\u00b2_op = [1/\u0394z\u00b2, -2/\u0394z\u00b2, 1/\u0394z\u00b2]; # row or Laplacian operator\n\u2207T_bottom = 10;                 # Temperature gradient at the top\nT_top = 1;                      # Temperature at the bottom\nS(z) = \u03b2*sin(\u03b3*z)               # source term, (sin for easy integration)\nzf = range(a, b, length=n+1);\nzc = map(i-> zf[i]+\u0394z/2, 1:n);\n\nfunction T_analytic(z) # Analytic steady state solution\n    c1 = \u2207T_bottom-\u03b2*cos(\u03b3*a)/(\u03b3*\u03b1)\n    c2 = T_top-(\u03b2*sin(\u03b3*b)/(\u03b3^2*\u03b1)+c1*b)\n    return \u03b2*sin(\u03b3*z)/(\u03b3^2*\u03b1)+c1*z+c2\nend\n\nT = zeros(FT, n+1);\n\n# Equations: derivation to matrix form\n# \u2202_t T = \u03b1 * \u2207\u00b2(T) + S\n# (T^{n+1}-T^n) = \u0394t (\u03b1 * \u2207\u00b2(T^{n+1}) + S)\n# (T^{n+1} - \u0394t \u03b1 * \u2207\u00b2(T^{n+1})) = T^n + \u0394t*S\n# (I - \u0394t \u03b1 * \u2207\u00b2) T^{n+1} = T^n + \u0394t*S\n\n# Derive Dirichlet boundary stencil & source:\n# \u2202_t T = \u03b1 * (T[i-1]+T[b]-2*T[i])/\u0394z\u00b2 + S\n# \u2202_t T = \u03b1 * (T[i-1]-2*T[i])/\u0394z\u00b2 + S + \u03b1 * T[b] / \u0394z\u00b2\n\n# Derive Neumann boundary stencil & source:\n# \u2207T_bottom*n\u0302= (T[g] - T[i])/(2\u0394z),     n\u0302 = [-1,1] \u2208 [zmin,zmax]\n# T[i] + 2*\u0394z*\u2207T_bottom*n\u0302 = T[g]\n# \u2202_t T = \u03b1 * (((T[i] + 2*\u0394z*\u2207T_bottom*n\u0302) - T[b])/\u0394z - (T[b] - T[i])/\u0394z)/\u0394z + S\n# \u2202_t T = \u03b1 * (((T[i]) - T[b])/\u0394z - (T[b] - T[i])/\u0394z)/\u0394z + S + \u03b1/\u0394z\u00b2*2*\u0394z*\u2207T_bottom*n\u0302\n# \u2202_t T = \u03b1 * (2*T[i] - 2*T[b])/\u0394z\u00b2 + S + 2\u03b1/\u0394z*\u2207T_bottom*n\u0302\n\u2207\u00b2 = Tridiagonal(\n    ones(FT, n) .* \u2207\u00b2_op[1],\n    ones(FT, n+1)   .* \u2207\u00b2_op[2],\n    ones(FT, n) .* \u2207\u00b2_op[3]\n);\n\n# Modify boundary stencil to account for BCs\n\u2207\u00b2.d[1] = -2/\u0394z\u00b2\n\u2207\u00b2.du[1] = +2/\u0394z\u00b2\n\n# Modify boundary stencil to account for BCs\n\u2207\u00b2.du[n] = 0  # modified stencil\n\u2207\u00b2.d[n+1] = 0 # to ensure `\u2202_t T = 0` at `z=zmax`\n\u2207\u00b2.dl[n] = 0  # to ensure `\u2202_t T = 0` at `z=zmax`\n\n# Compute boundary source: \u03b1 * T[b] / \u0394z\u00b2\nAT_b = zeros(FT, n+1);\nAT_b[1] = \u03b1*2/\u0394z*\u2207T_bottom*n\u0302_min;\nAT_b[end-1] = \u03b1*T_top/\u0394z\u00b2;\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 = \u03b1 .* \u2207\u00b2\n\nparams = (;n)\n\ntspan = (FT(0), N_t*FT(\u0394t))\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 = \u0394t,\n    saveat = range(FT(0), N_t*FT(\u0394t), 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 \u2208 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 \u2208 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": "using Printf\n\nfunction multifact(n::Integer, k::Integer)\n    n > 0 && k > 0 || throw(DomainError())\n    k > 1 || factorial(n)\n    return prod(n:-k:2)\nend\n\nconst khi = 5\nconst nhi = 10\nprintln(\"Showing multifactorial for n in [1, $nhi] and k in [1, $khi].\")\nfor k = 1:khi\n    a = multifact.(1:nhi, k)\n    lab = \"n\" * \"!\" ^ k\n    @printf(\"  %-6s \u2192  %s\\n\", lab, a)\nend\n", "meta": {"hexsha": "9272d99778791f3b4ad650bd66159f9c92ab690a", "size": 366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/multifactorial.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/multifactorial.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/multifactorial.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.5294117647, "max_line_length": 72, "alphanum_fraction": 0.5573770492, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7762106198383784}}
{"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 \u00f7 3)\n\t\tfor b in (a+1):(x \u00f7 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": "@testset \"Curve struct\" begin\n@testset \"Uniformly distributed values\" begin\n    n = 20\n    data = rand(Uniform(0,10), n)\n    curve = CalculatedABC.ABCcurve(data)\n    @test curve.effort == 0:0.05:1.0\n    expected_yield = [0,\n                      0.10223370412290836,\n                      0.19630374973228518,\n                      0.2798337861487627,\n                      0.35309289814499817,\n                      0.4251124119444249,\n                      0.49223359866263033,\n                      0.5559340313195282,\n                      0.6192318028485928,\n                      0.6706485917196718,\n                      0.7210686469145637,\n                      0.7696104643520768,\n                      0.812596101423477,\n                      0.8466456273448749,\n                      0.8777009051387628,\n                      0.9076823618805581,\n                      0.9368834040175215,\n                      0.9647084964342312,\n                      0.9824989229044542,\n                      0.994333140487581,\n                      1.0000000000000002]\n    @test isapprox(curve.yield, expected_yield)\nend\n\n@testset \"Exponentially distributed values\" begin\n    n = 20\n    data = rand(Exponential(1), n)\n    curve = CalculatedABC.ABCcurve(data)\n    @test curve.effort == 0:0.05:1.0\n    expected_yield = [0.0,\n                      0.1559704817922999,\n                      0.259107787045309,\n                      0.36017085915674457,\n                      0.4567531613173713,\n                      0.530483819367366,\n                      0.5905820392527759,\n                      0.6503414525690904,\n                      0.6912925133668514,\n                      0.7318440937106174,\n                      0.7704643555492486,\n                      0.8031964684921609,\n                      0.8353247928350085,\n                      0.8670259991394021,\n                      0.8976554662905372,\n                      0.9212877248856802,\n                      0.9431001183934831,\n                      0.964704167187443,\n                      0.9810003669812493,\n                      0.9911110632975999,\n                      1.0]\n    @test isapprox(curve.yield, expected_yield)\nend\n\n@testset \"SwissInhabitants data\" begin\n    data = readdlm(\"swissinhabitants\")[:,1]\n    curve = CalculatedABC.ABCcurve(data)\n    @test curve.effort == 0:0.0003453038674033149:1.0\n    expected_yield = readdlm(\"expected_yield\")[:,1]\n    @test isapprox(curve.yield, expected_yield)\nend\nend\n", "meta": {"hexsha": "8da4849079d71e41471006958b71760b11ce90bc", "size": 2482, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_curve.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CalculatedABC.jl-6c2f61f8-fafd-4db0-a534-9240d45f7a9c", "max_stars_repo_head_hexsha": "9cba934113266ac49df11f00f9cb4e1ac060db1e", "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/test_curve.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CalculatedABC.jl-6c2f61f8-fafd-4db0-a534-9240d45f7a9c", "max_issues_repo_head_hexsha": "9cba934113266ac49df11f00f9cb4e1ac060db1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-04T09:26:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T09:26:03.000Z", "max_forks_repo_path": "test/test_curve.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CalculatedABC.jl-6c2f61f8-fafd-4db0-a534-9240d45f7a9c", "max_forks_repo_head_hexsha": "9cba934113266ac49df11f00f9cb4e1ac060db1e", "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.5, "max_line_length": 53, "alphanum_fraction": 0.4959709911, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7762106138388717}}
{"text": "using PlaneGeometry\nusing PlaneGeometry.Theorems.Napoleon\nusing SymPy\nusing Test\n\n@testset \"PlaneGeometry.jl\" begin\n    A = Point(0,0) \n    B = Point(1, 3) \n    C = Point(4,2)\n    tri = Triangle(A, B, C)\n\n    @test vertices(tri) == [A, B, C]\n    @test edges(tri) == [Edge(A, B), Edge(B, C), Edge(C, A)]\n\n    c = Circle(A, 2)\n    @test PlaneGeometry.center(c) == A\n\n    @test squaredist(A, B) == 10\n    @test distance(A, B) == SymPy.sqrt(Sym(10))\n\n    @test midpoint(Point(0, 0), Point(2,4)) == Point(1, 2)\n    @test midpoint(A, B) == Point(1//2, 3//2)\n\n    @test median(A, B, C) == Edge(Point(1//2, 3//2), C)\n\n    @test concurrent(edges(tri)) == nothing\n\n    @test concurrent(Edge(A, B), Edge(A, C)) == A\n\n    elist = map(i->median(circshift([A, B, C], i)...), 0:2)\n    @test concurrent(elist) == Point(5//3, 5//3)\n\n    @test equipoints(A, B) == \n    [\n    Point(1//2 - 3*sympy.sqrt(3)//2, sympy.sqrt(3)//2 + 3//2),\n    Point(1//2 + 3*sympy.sqrt(3)//2, 3//2 - sympy.sqrt(3)//2)\n    ]\n\n    outer_tri = outer_equitriangles(tri)\n\n    @test outer_tri == \n    [\n    Triangle(A, B, Point(1//2 - 3*sympy.sqrt(3)//2, sympy.sqrt(3)//2 + 3//2)),\n    Triangle(C, A, Point(sympy.sqrt(3) + 2, 1 - 2*sympy.sqrt(3))),\n    Triangle(B, C, Point(sympy.sqrt(3)//2 + 5//2, 5//2 + 3*sympy.sqrt(3)//2))\n    ]\n\n    @test_throws ArgumentError circumcircle([A, B])\n\n    outer_circles = circumcircle.(vertices.(outer_tri))\n\n    @test outer_circles ==\n    [\n    Circle(Point(1//2 - sympy.sqrt(3)//2, sympy.sqrt(3)//6 + 3//2), sympy.sqrt(30)//3), \n    Circle(Point(sympy.sqrt(3)//3 + 2, 1 - 2*sympy.sqrt(3)//3), 2*sympy.sqrt(15)//3), \n    Circle(Point(sympy.sqrt(3)//6 + 5//2, sympy.sqrt(3)//2 + 5//2), sympy.sqrt(30)//3)\n    ]\n\n    @test isequilateral(tri) == false\n\n    np =  napoleon_tri(tri)\n\n    @test isequilateral(np)\n\n    @vars a1 a2 b1 b2 c1 c2\n    tri1 = Triangle(a1, a2, b1, b2, c1, c2)\n\n    # This needs to fail.\n    @test !isequilateral(tri1)\n\n    @test np == Triangle(\n        Point(1//2 - sympy.sqrt(3)//2, sympy.sqrt(3)//6 + 3//2),\n        Point(sympy.sqrt(3)//3 + 2, 1 - 2*sympy.sqrt(3)//3), \n        Point(sympy.sqrt(3)//6 + 5//2, sympy.sqrt(3)//2 + 5//2))\n\n    @test ceva(tri, O) == (\n        [Point(0, 0), Point(1, 3), Point(4, 2), Point(5//2, 5//2), Point(4//9, 2//9), Point(1//9, 1//3)], \n        [Edge(Point(1, 3), Point(5//2, 5//2)), \n            Edge(Point(5//2, 5//2), Point(4, 2)), \n            Edge(Point(4, 2), Point(4//9, 2//9)), \n            Edge(Point(4//9, 2//9), Point(0, 0)), \n            Edge(Point(0, 0), Point(1//9, 1//3)), \n            Edge(Point(1//9, 1//3), Point(1, 3))])\n\n    @test napoleon_proof()\n\n    @test centroid_proof()\n\n    @test ceva_proof()\nend\n", "meta": {"hexsha": "1b48a55271106d2d33dab828e15687c461336d95", "size": 2670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 29.3406593407, "max_line_length": 106, "alphanum_fraction": 0.5344569288, "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7762106124693858}}
{"text": "# ---\n# title: 264. Ugly Number II\n# id: problem264\n# author: Tian Jun\n# date: 2020-10-31\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\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "c0bd72d78eb7859ca07e3be478ab64e85e8e2bea", "size": 742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/264.ugly-number-ii.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/264.ugly-number-ii.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/unresolved/264.ugly-number-ii.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": 20.6111111111, "max_line_length": 94, "alphanum_fraction": 0.6091644205, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.776131128026883}}
{"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\u03c0 * 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\u03c0 * xi) - cos(2\u03c0 * xf)) / (2\u03c0) + (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": "using CompScienceMeshes\nusing Test\n\np1 = point(1,0,0)\np2 = point(0,1,0)\np3 = point(0,0,1)\np4 = point(0,0,0)\n\ntet = simplex(p1,p2,p3,p4)\nc = neighborhood(tet, point(1,1,1)/4)\n\n@test cartesian(c) \u2248 point(0.25, 0.25, 0.25)\n@test parametric(c) \u2248 point(0.25, 0.25, 0.25)\n\n@test length(c) == 3\n@test c[1] \u2248 0.25\n@test c[2] \u2248 0.25\n@test c[3] \u2248 0.25\n\n@test jacobian(1.234) \u2248 1\n\n@test tangents(c,1) \u2248 point(1,0,0)\n@test tangents(c,2) \u2248 point(0,1,0)\n@test tangents(c,3) \u2248 point(0,0,1)\n\ntri = simplex(p1,p2,p4)\nc_tri = neighborhood(tri, point(1,1)/3)\n\n@test normal(c_tri) \u2248 point(0,0,1)\n", "meta": {"hexsha": "d9e2abe3057f16e32f1180e6540769e6f444510a", "size": 576, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_nbd.jl", "max_stars_repo_name": "UnofficialJuliaMirror/CompScienceMeshes.jl-3e66a162-7b8c-5da0-b8f8-124ecd2c3ae1", "max_stars_repo_head_hexsha": "4630538a4fadeb831d04ef34959c752b7fd553e7", "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": "test/test_nbd.jl", "max_issues_repo_name": "UnofficialJuliaMirror/CompScienceMeshes.jl-3e66a162-7b8c-5da0-b8f8-124ecd2c3ae1", "max_issues_repo_head_hexsha": "4630538a4fadeb831d04ef34959c752b7fd553e7", "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": "test/test_nbd.jl", "max_forks_repo_name": "UnofficialJuliaMirror/CompScienceMeshes.jl-3e66a162-7b8c-5da0-b8f8-124ecd2c3ae1", "max_forks_repo_head_hexsha": "4630538a4fadeb831d04ef34959c752b7fd553e7", "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": 19.2, "max_line_length": 45, "alphanum_fraction": 0.625, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7761229729572945}}
{"text": "_tri(t, period) = (2 / \u03c0) * abs(asin(sin(\u03c0 * (t - 1) / period)))\n_sin(t, period) = abs(sin(\u03c0 * (t - 1) / period))\n_cycle(\u03bb0, \u03bb1, g) = abs(\u03bb0 - \u03bb1) * g + min(\u03bb0, \u03bb1)\n\n\"\"\"\n    Triangle{T, S<:Integer}(range0, range1, period)\n    Triangle(;\u03bb0, \u03bb1, period)\n\nA [triangle wave](https://en.wikipedia.org/wiki/Triangle_wave) schedule\nwith `period`.\nThe output conforms to\n```text\nabs(\u03bb0 - \u03bb1) * (2 / \u03c0) * abs(asin(sin(\u03c0 * (t - 1) / period))) + min(\u03bb0, \u03bb1)\n```\n\n# Arguments\n- `range0`/`\u03bb0`: the first range endpoint\n- `range1`/`\u03bb1`: 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(;\u03bb0, \u03bb1, period) = Triangle(\u03bb0, \u03bb1, 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(;\u03bb0, \u03bb1, 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(\u03bb0 - \u03bb1) * Triangle(t) / (2^floor((t - 1) / period)) + min(\u03bb0, \u03bb1)\n```\nwhere `Triangle(t)` is `(2 / \u03c0) * abs(asin(sin(\u03c0 * (t - 1) / schedule.period)))` (see [`Triangle`](#)).\n\n# Arguments\n- `range0`/`\u03bb0`: the first range endpoint\n- `range1`/`\u03bb1`: 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(;\u03bb0, \u03bb1, period) = TriangleDecay2(\u03bb0, \u03bb1, 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(\u03bb0, \u03bb1, period, \u03b3)\n    TriangleExp(;\u03bb0, \u03bb1, period, \u03b3)\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(\u03bb0 - \u03bb1) * Triangle(t) * \u03b3^(t - 1) + min(\u03bb0, \u03bb1)\n```\nwhere `Triangle(t)` is `(2 / \u03c0) * abs(asin(sin(\u03c0 * (t - 1) / schedule.period)))` (see [`Triangle`](#)).\n\n# Arguments\n- `range0`/`\u03bb0`: the first range endpoint\n- `range1`/`\u03bb1`: the second range endpoint\n- `period::Integer`: the period\n- `decay`/`\u03b3`: the decay rate\n\"\"\"\nstruct TriangleExp{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\n    decay::T\nend\nTriangleExp(;\u03bb0, \u03bb1, period, \u03b3) = TriangleExp(\u03bb0, \u03bb1, period, \u03b3)\n\nstartvalue(schedule::TriangleExp) = schedule.tri.\u03bb0\nendvalue(schedule::TriangleExp) = schedule.tri.\u03bb1\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(;\u03bb0, \u03bb1, period)\n\nA sine wave schedule with `period`.\nThe output conforms to\n```text\nabs(\u03bb0 - \u03bb1) * abs(sin(\u03c0 * (t - 1) / period)) + min(\u03bb0, \u03bb1)\n```\n\n# Arguments\n- `range0`/`\u03bb0`: the first range endpoint\n- `range1`/`\u03bb1`: 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(;\u03bb0, \u03bb1, period) = Sin(\u03bb0, \u03bb1, 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(;\u03bb0, \u03bb1, period)\n\nA sine wave schedule with `period` and half the amplitude each cycle.\nThe output conforms to\n```text\nabs(\u03bb0 - \u03bb1) * Sin(t) / (2^floor((t - 1) / period)) + min(\u03bb0, \u03bb1)\n```\nwhere `Sin(t)` is `abs(sin(\u03c0 * (t - 1) / period))` (see [`Sin`](#)).\n\n# Arguments\n- `range0`/`\u03bb0`: the first range endpoint\n- `range1`/`\u03bb1`: 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(;\u03bb0, \u03bb1, period) = SinDecay2(\u03bb0, \u03bb1, 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(;\u03bb0, \u03bb1, period, \u03b3)\n\nA sine wave schedule with `period` and an exponentially decaying amplitude.\nThe output conforms to\n```text\nabs(\u03bb0 - \u03bb1) * Sin(t) * \u03b3^(t - 1) + min(\u03bb0, \u03bb1)\n```\nwhere `Sin(t)` is `abs(sin(\u03c0 * (t - 1) / period))` (see [`Sin`](#)).\n\n# Arguments\n- `range0`/`\u03bb0`: the first range endpoint\n- `range1`/`\u03bb1`: the second range endpoint\n- `period::Integer`: the period\n- `decay`/`\u03b3`: the decay rate\n\"\"\"\nstruct SinExp{T, S<:Integer}\n    range0::T\n    range1::T\n    period::S\n    decay::T\nend\nSinExp(;\u03bb0, \u03bb1, period, \u03b3) = SinExp(\u03bb0, \u03bb1, period, \u03b3)\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(;\u03bb0, \u03bb1, 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(\u03bb0 - \u03bb1) * (1 + cos(\u03c0 * mod(t - 1, period) / period)) / 2 + min(\u03bb0, \u03bb1)\n```\nThis schedule is also referred to as \"cosine annealing with warm restarts\"\nin machine learning literature.\n\n# Arguments\n- `range0`/`\u03bb0`: the first range endpoint\n- `range1`/`\u03bb1`: 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(;\u03bb0, \u03bb1, period) = Cos(\u03bb0, \u03bb1, period)\n\n(schedule::Cos)(t) = _cycle(schedule.range0, schedule.range1,\n                            (1 + cos(\u03c0 * 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, \u03bc::Real, \u03c3::Real)\n\nNormal distribution density function\n\"\"\"\ndnorm(x::Real, \u03bc::Real, \u03c3::Real) = exp(-0.5 * ((x - \u03bc)/\u03c3)^2)/(\u03c3*sqrt2\u03c0)\n\n\"\"\"\n    dgumbel(x::Real, \u03bc::Real, \u03c3::Real)\n\nGumbel density, parameterized by mean (\u03bc) and SD (\u03c3) of x.\n\"\"\"\nfunction dgumbel(x::Real, \u03bc::Real, \u03c3::Real)\n    \u03b2 = (\u221a6 * \u03c3) / \u03c0\n    \u03b1 = \u03bc - (\u03b2*\u03b3)\n    z = (x - \u03b1) / \u03b2\n    exp(-(z + exp(-z)))\nend\n\n\"\"\"\n    dgamma(x::Real, \u03bc::Real, \u03c3::Real)\n\nGamma density, parameterized by mean (\u03bc) and sigma(\u03c3) of x.\n\"\"\"\nfunction dgamma(x::Real, \u03bc::Real, \u03c3::Real)\n    \u03b1 = \u03bc^2 / \u03c3^2\n    \u03b2 = \u03bc / \u03c3^2\n    (x^(\u03b1 - 1) * exp(-\u03b2 * x))  * (\u03b2^\u03b1 / \u0393(\u03b1))\nend\n\n\"\"\"\n    dlognorm(x::Real, \u03bc::Real, \u03c3::Real)\n\nLognormal density, parameterized by mean (\u03bc) and SD (\u03c3) of x, NOT of log(x).\n\"\"\"\nfunction dlognorm(x::Real, \u03bc::Real, \u03c3::Real)\n    l\u03bc = log(\u03bc^2 / sqrt(1 + \u03c3^2 / \u03bc^2))\n    l\u03c3 = \u221a(log(1 + \u03c3^2 / \u03bc^2))\n    dnorm(log(x), l\u03bc, l\u03c3) / 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 FractionalTransforms\nusing Test\n\n@testset \"Test FRFT\" begin\n    @test isapprox(real(frft([1,2,3], 0.5)), [0.100464613588213, 3.07460010423315, 1.31566432887283], atol=1e-5)\n    @test isapprox(imag(frft([1,2,3], 0.5)), [-0.259409480977277, 0.199349381540632, -0.93645356561191], atol=1e-5)\nend\n\n@testset \"Test FRFT auxillary functions\" begin\n    @testset \"Test Sinc Interpolation\" begin\n        @test isapprox(real(sinc_interp([1, 2, 3], 3)), [1.0, 1.1577906803857638, 1.4472383504822042, 2.0, 2.6877283651812367, 3.1425747039042147, 3.0]; atol=1e-5)\n        @test isapprox(imag(sinc_interp([1, 2, 3], 3)), [-4.0696311822644287e-17, -2.4671622769447922e-17, -2.522336560207922e-16, -3.331855648569948e-17, 0.0, 1.9624582529744518e-17, 3.331855648569948e-17]; atol=1e-5)\n    end\n\n    @testset \"Test Frequency Shear\" begin\n        @test isapprox(real(freq_shear([1, 2, 3], 3)), [0.0707372016677029, 2.0, 0.2122116050031087]; atol=1e-5)\n        @test isapprox(imag(freq_shear([1, 2, 3], 3)), [0.9974949866040544, 0.0, 2.9924849598121632]; atol=1e-5)\n    end\nend", "meta": {"hexsha": "27715761b2ad3b0e7a951dca0166aa75fdcc153d", "size": 1063, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/frft.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": "test/frft.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": "test/frft.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": 55.9473684211, "max_line_length": 218, "alphanum_fraction": 0.6952022578, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7761082967542274}}
{"text": "using DiffEqFlux, Flux, OrdinaryDiffEq, Test, Optim, DiffEqSensitivity\r\n\r\nx = Float32[0.8; 0.8]\r\ntspan = (0.0f0,10.0f0)\r\n\r\nann = Chain(Dense(2,10,tanh), Dense(10,1))\r\np = Float32[-2.0,1.1]\r\np2,re = Flux.destructure(ann)\r\n_p = [p;p2]\r\n\u03b8 = [x;_p]\r\n\r\nfunction dudt2_(u,p,t)\r\n    x, y = u\r\n    [(re(p[3:end])(u)[1]),p[1]*y + p[2]*x]\r\nend\r\n\r\nprob = ODEProblem(dudt2_,x,tspan,_p)\r\nsolve(prob,Tsit5())\r\n\r\nfunction predict_rd(\u03b8)\r\n  Array(solve(prob,Tsit5(),u0=\u03b8[1:2],p=\u03b8[3:end],abstol=1e-7,reltol=1e-5,sensealg=TrackerAdjoint()))\r\nend\r\nloss_rd(p) = sum(abs2,x-1 for x in predict_rd(p))\r\nl = loss_rd(\u03b8)\r\n\r\ncb = function (\u03b8,l)\r\n  println(l)\r\n  #display(plot(solve(remake(prob,u0=Flux.data(_x),p=Flux.data(p)),Tsit5(),saveat=0.1),ylim=(0,6)))\r\n  false\r\nend\r\n\r\n# Display the ODE with the current parameter values.\r\ncb(\u03b8,l)\r\n\r\nloss1 = loss_rd(\u03b8)\r\nres = DiffEqFlux.sciml_train(loss_rd, \u03b8, BFGS(initial_stepnorm = 0.01), cb = cb)\r\nloss2 = res.minimum\r\n@test 10loss2 < loss1\r\n\r\n## Partial Neural Adjoint\r\n\r\nu0 = Float32[0.8; 0.8]\r\ntspan = (0.0f0,25.0f0)\r\n\r\nann = Chain(Dense(2,10,tanh), Dense(10,1))\r\n\r\np1,re = Flux.destructure(ann)\r\np2 = Float32[-2.0,1.1]\r\np3 = [p1;p2]\r\n\u03b8 = [u0;p3]\r\n\r\nfunction dudt_(du,u,p,t)\r\n    x, y = u\r\n    du[1] = re(p[1:41])(u)[1]\r\n    du[2] = p[end-1]*y + p[end]*x\r\nend\r\nprob = ODEProblem(dudt_,u0,tspan,p3)\r\nsolve(prob,Tsit5(),abstol=1e-8,reltol=1e-6)\r\n\r\nfunction predict_adjoint(\u03b8)\r\n  Array(solve(prob,Tsit5(),u0=\u03b8[1:2],p=\u03b8[3:end],saveat=0.0:1:25.0))\r\nend\r\nloss_adjoint(\u03b8) = sum(abs2,x-1 for x in predict_adjoint(\u03b8))\r\nl = loss_adjoint(\u03b8)\r\n\r\ncb = function (\u03b8,l)\r\n  println(l)\r\n  #display(plot(solve(remake(prob,p=Flux.data(p3),u0=Flux.data(u0)),Tsit5(),saveat=0.1),ylim=(0,6)))\r\n  false\r\nend\r\n\r\n# Display the ODE with the current parameter values.\r\ncb(\u03b8,l)\r\n\r\nloss1 = loss_adjoint(\u03b8)\r\nres1 = DiffEqFlux.sciml_train(loss_adjoint, \u03b8, ADAM(0.01), cb = cb, maxiters = 100)\r\nres = DiffEqFlux.sciml_train(loss_adjoint, res1.minimizer, BFGS(initial_stepnorm = 0.01), cb = cb)\r\nloss2 = res.minimum\r\n@test 10loss2 < loss1\r\n", "meta": {"hexsha": "27c4083ef72c312d6438f691badfee94cbabef13", "size": 2026, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/partial_neural.jl", "max_stars_repo_name": "jonniedie/DiffEqFlux.jl", "max_stars_repo_head_hexsha": "0b2b4db87c1658e2008c770ffd0bd39427837fc2", "max_stars_repo_licenses": ["MIT"], "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/partial_neural.jl", "max_issues_repo_name": "jonniedie/DiffEqFlux.jl", "max_issues_repo_head_hexsha": "0b2b4db87c1658e2008c770ffd0bd39427837fc2", "max_issues_repo_licenses": ["MIT"], "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/partial_neural.jl", "max_forks_repo_name": "jonniedie/DiffEqFlux.jl", "max_forks_repo_head_hexsha": "0b2b4db87c1658e2008c770ffd0bd39427837fc2", "max_forks_repo_licenses": ["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.325, "max_line_length": 101, "alphanum_fraction": 0.6411648569, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7760974598828316}}
{"text": "using DEMC\nusing Random\nusing LinearAlgebra\nusing Distributions\nRandom.seed!(31953150)\n\n# generate data\nnobs = 100\nnpar = 3\n\u03a3 = ones(npar, npar)\nfor i = 1:npar\n    for iprime = 1:i\n        if i != iprime\n            \u03a3[i, iprime] = 0.25\n            \u03a3[iprime, i] = 0.25\n        end\n    end\nend\n\nDataDistribution = MvNormal(zeros(npar), \u03a3)\nX = zeros(nobs, npar+1)\nX[:,1] .= 1.\nfor iobs = 1:nobs\n    X[iobs, 2:end] .= rand(DataDistribution)\nend\n\n\u03b2 = rand(npar+1)\ny = X*\u03b2 + 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(\u03b2)\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\u03b3 = 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, \u03b3; 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 - \u03b2)\n# covariance of estimates\nb, \u03a3b = 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\u03a3ols = 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 \u03b1 = 0.33\nconst \u03b2 = 0.96\nconst \u03b4 = 0.05\n\n\"\"\"\nCompute wage rate given an interest rate, r\n\"\"\"\nfunction r_to_w(r::Real)\n    return A * (1 - \u03b1) * (A * \u03b1 / (r + \u03b4)) ^ (\u03b1 / (1 - \u03b1))\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 * \u03b1 * (N / K) ^ (1 - \u03b1) - \u03b4\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.\u03b2)\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(\u03b2=\u03b2, 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": "@testset \"polynomial\" begin\n    rng = MersenneTwister(123456)\n    x = rand(rng)*2\n    v1 = rand(rng, 3)\n    v2 = rand(rng, 3)\n    c = randn(rng)\n    @testset \"LinearKernel\" begin\n        k = LinearKernel()\n        @test kappa(k,x) \u2248 x\n        @test k(v1,v2) \u2248 dot(v1,v2)\n        @test kappa(LinearKernel(),x) == kappa(k,x)\n        @test metric(LinearKernel()) == KernelFunctions.DotProduct()\n        @test metric(LinearKernel(c=2.0)) == KernelFunctions.DotProduct()\n        @test repr(k) == \"Linear Kernel (c = 0.0)\"\n\n        # Standardised tests.\n        TestUtils.test_interface(k, Float64)\n        test_ADs(x->LinearKernel(c=x[1]), [c])\n        test_params(LinearKernel(; c=c), ([c],))\n    end\n    @testset \"PolynomialKernel\" begin\n        k = PolynomialKernel()\n        @test kappa(k,x) \u2248 x^2\n        @test k(v1,v2) \u2248 dot(v1,v2)^2\n        @test kappa(PolynomialKernel(),x) == kappa(k,x)\n        @test repr(k) == \"Polynomial Kernel (c = 0.0, d = 2.0)\"\n\n        # Coherence tests.\n        @test kappa(PolynomialKernel(d=1.0,c=c),x) \u2248 kappa(LinearKernel(c=c),x)\n        @test metric(PolynomialKernel()) == KernelFunctions.DotProduct()\n        @test metric(PolynomialKernel(d=3.0)) == KernelFunctions.DotProduct()\n        @test metric(PolynomialKernel(d=3.0,c=2.0)) == KernelFunctions.DotProduct()\n\n        # Standardised tests.\n        TestUtils.test_interface(k, Float64)\n        # test_ADs(x->PolynomialKernel(d=x[1], c=x[2]),[2.0,  c])\n        @test_broken \"All, because of the power\"\n        test_params(PolynomialKernel(; d=x, c=c), ([x], [c]))\n    end\nend\n", "meta": {"hexsha": "a9e6d8e5d7f75397136c75e80ac2d19db9b725b0", "size": 1563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/polynomial.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": "test/basekernels/polynomial.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": "test/basekernels/polynomial.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": 38.1219512195, "max_line_length": 83, "alphanum_fraction": 0.587971849, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741298, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7760974417770619}}
{"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                                   \u03b1=1., \u03ba=0., \u03b2=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": "using Test; using PyPlot; using Revise; using BenchmarkTools; using AbstractFFTs; using FFTW;\n\n#= test function without discontinuity in derivative at t=0 =#\nfunction funk1(x)\n  return (1/2)*x^2 + (1/3)*x^3 - (1/4)*x^4 \nend\n\nfunction funk1dot(x)\n  return x + x^2 - x^3\nend\n\nfunction funk2(x)\n  return x + (1/2)*x^2 - (1/3)*x^3\nend\n\nfunction funk2dot(x)\n  return 1 + x - x^2\nend\n\neven(x) = x%2==0\n\nfunction spectralmultiplier(x, L)\n  N = length(x)\n  out = similar(x, Complex{Float64})\n  for k in 0:(N-1)\n    if k<(N/2)\n      out[k+1] = x[k+1]*2*\u03c0*im*k/L\n    \n    elseif k>(N/2)\n      out[k+1] = x[k+1]*2*\u03c0*im*(k-N)/L\n\n    end\n  end\n  if even(N); out[N\u00f72]=0.0; end\n  \n  return out\nend\n\nfunction specdifftest(f, fdot)\n\tyff = fft(f)\n\tyffdot = spectralmultiplier(yff, t[end])\n\tydot_approx = real.(ifft(yffdot))\n\tplot(t, fdot)\n\tplot(t, ydot_approx, \"--\", alpha=0.2)\n  return\nend\n\ndt = 0.01\nt = Vector{Float64}(0.0:dt:8*pi)\n#y = -cos.(t)\n#ydot = sin.(t)\n\nspecdifftest(funk1.(t), funk1dot.(t))\n", "meta": {"hexsha": "c97923c5349fae81b40d2f9d66a6ce517517727a", "size": 986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "20191011_diffSpectral.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": "20191011_diffSpectral.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": "20191011_diffSpectral.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": 18.2592592593, "max_line_length": 93, "alphanum_fraction": 0.6115618661, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7760818391534108}}
{"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\u00e9nyi 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\u00e9nyi 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) \u2192 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, \u03b4 = 0.9, \u03b5 = 1e-3) \u2192 (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 `\u03b4`.\n\nIf iteration occurs for more than `max_steps` without convergence better than `\u03b5`,\nthen iteration stops and `success` will be `false`.\n\"\"\"\nfunction corrector(zpred, zprev, f, J; \u03b4 = 0.9, max_steps = 200, \u03b5 = 1e-6)\n    \u0394z = 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, \u0394z) ? length(\u0394z) : argmax(\u0394z .^ 2)\n    c = 0\n    z\u2c7c = zpred\n    z\u2c7c\u208a\u2081 = newton_step!(z\u2c7c, zpred, i, f, J, \u03b4)\n    while norm(z\u2c7c\u208a\u2081 - z\u2c7c) > \u03b5\n        z\u2c7c = z\u2c7c\u208a\u2081\n        z\u2c7c\u208a\u2081 = newton_step!(z\u2c7c, zpred, i, f, J, \u03b4)\n        c += 1\n        if c > max_steps \n            @warn(\"Newton did not converge.\")\n            return (z\u2c7c\u208a\u2081, false)\n        end\n    end\n    return z\u2c7c\u208a\u2081, true\nend\n\nfunction newton_step!(z\u2c7c, zpred, i, f, J, \u03b4)\n    Jfinal = mixed_jacobian(z\u2c7c, i, f, J)\n    x\u2c7c = z\u2c7c[1:end-1]; p\u2c7c = z\u2c7c[end]\n    g = f(x\u2c7c, p\u2c7c)\n    gz = vcat(g, z\u2c7c[i] - zpred[i])\n    z\u2c7c\u208a\u2081 = z\u2c7c - \u03b4*(inv(Jfinal))*gz\n    return z\u2c7c\u208a\u2081\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 \u2264 zpred[end] \u2264 pmax) || return false\n    z\u02e3, success = corrector(zpred, zs[end], f, J)\n    push!(zs, z\u02e3)\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        \u03bc = maximum(real(v) for v \u2208 eigenvalues)\n        isstable = \u03bc < 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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.05\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.05\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u255067a42f40-3a99-11eb-2199-cb72cdee58fa\n# \u2560\u255067a46e56-3a99-11eb-1254-3d0d490364f5\n# \u255f\u2500475ff888-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": "using Test\nusing Example2018\n\n# Polynomials form a ring\n# 1. addition is associative\n# 2. additive identity\n# 3. additive inverse\n# 4. addition commutes\n\n@testset \"Polynomials form a ring\" begin\n\n\tz = Polynomial([0])\n\n\tfor n in 1:100\n\n\t\tdeg = rand(0:100)\n\t\tp = Polynomial(rand(-1000000:1000000, deg+1))\n\n\t\t@test p + z == p\n\t\t@test z + p == p\n\t\t@test p + (-p) == z\n\n\tend\n\nend\n\n# Scaler Multiplication\n# 1. A scaler multiplied by a polynomial gives a polynomial\n# 2. A polynomial multiplied by zero gives zero\n\n@testset \"Scaler Multiplication\" begin\n\n\tz = Polynomial([0])\n\t\n\tfor n in 1:100\n\n\n\t\tdeg = rand(0:100)\n\t\tsclr = rand()\n\t\tp = Polynomial(rand(-1000000:1000000, deg+1))\n\t\t\n\t\t@test poly(sclr*p) == true\n\t\t@test 0*p == z\n\n\tend\n\nend\n\n# Derivative Test\n# 1. The derivative of a polynomial must be a polynomial\n# 2. If the polynomial has degree n, the derivative must have degree (n-1)\n\n@testset \"Derivative Test\" begin\n\n\tfor n in 1:100\n\n\n\t\tdeg = rand(0:100)\n\t\tp = Polynomial(rand(-1000000:1000000, deg+1))\n\t\tdp = deriv(p)\n\t\t\n\t\t@test poly(dp) == true\n\t\t@test length(dp.coeffs) == deg\n\n\tend\n\nend\n", "meta": {"hexsha": "d6f3c27cb9fcd21be17787fe24fff311f0406f50", "size": 1094, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "CourtA96/Example2018-1", "max_stars_repo_head_hexsha": "2ca15463859e614004f58eda1bb77b5a02b21944", "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/runtests.jl", "max_issues_repo_name": "CourtA96/Example2018-1", "max_issues_repo_head_hexsha": "2ca15463859e614004f58eda1bb77b5a02b21944", "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/runtests.jl", "max_forks_repo_name": "CourtA96/Example2018-1", "max_forks_repo_head_hexsha": "2ca15463859e614004f58eda1bb77b5a02b21944", "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.0882352941, "max_line_length": 74, "alphanum_fraction": 0.6617915905, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7760332775780716}}
{"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# \u2554\u2550\u2561 e77948a6-1ecc-11eb-3285-7f06dcdb7cf5\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e7799b9e-1ecc-11eb-311f-035de72c3603\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing StatsBase, Combinatorics, Plots\nend\n\n# \u2554\u2550\u2561 6c38d2ce-1ecc-11eb-281d-0d13a832adea\nmd\"## Listing 2.3\"\n\n# \u2554\u2550\u2561 fe1ee6a6-1ecc-11eb-1930-0301940bc5f7\n\tN = 10^3\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e7965b58-1ecc-11eb-2308-093c9f5a167e\nmd\"## End of listing 2.3\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25006c38d2ce-1ecc-11eb-281d-0d13a832adea\n# \u2560\u2550e77948a6-1ecc-11eb-3285-7f06dcdb7cf5\n# \u2560\u2550e7799b9e-1ecc-11eb-311f-035de72c3603\n# \u2560\u2550fe1ee6a6-1ecc-11eb-1930-0301940bc5f7\n# \u2560\u2550e77a2a28-1ecc-11eb-0acb-5167936362f5\n# \u2560\u2550e7885e54-1ecc-11eb-03d1-2580aad82a3d\n# \u2560\u2550e788edce-1ecc-11eb-3682-b1bfc98646a0\n# \u255f\u2500e7965b58-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# \u2554\u2550\u2561 7ef4b0b3-9d0a-4356-bd16-14487f14e0ab\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(aside=true)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u010dica Miro\u0161evi\u0107.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3b5ed1fa-75b0-43fb-a918-4c2e8f52d039\n# What is the optimal bipartition?\ngplot(G, nodelabel=1:n, edgelabel=wn)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b7f127d8-e8cd-4771-8091-c88f9ffe6b08\nW=WeightMatrix(sn,tn,wn)\n\n# \u2554\u2550\u2561 3f5447bb-95cd-4520-b0b9-e85f33b323bd\nMatrix(W)\n\n# \u2554\u2550\u2561 ecb2a46e-f9dc-4e57-812f-0a2788afb202\nbegin\n\tL=Laplacian(W)\n\tMatrix(L)\nend\n\n# \u2554\u2550\u2561 86e5f00f-13ee-4867-b0cd-187f2c782a46\nL\u2099=NormalizedLaplacian(L)\n\n# \u2554\u2550\u2561 cf26dbe9-3c4f-4c95-88ef-f197f360d759\nMatrix(L\u2099)\n\n# \u2554\u2550\u2561 8fcd2440-4013-4b37-a747-2c0c7f6d4aeb\nissymmetric(L\u2099)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1437aadc-1c26-4eff-bb22-9cf9c15e1f5f\nI\u1d67=IncidenceMatrix(G,wn)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a9ba64a6-bd17-4b86-acb4-e7c7d8f87dc1\nmd\"\"\"\n### Examples\n\"\"\"\n\n# \u2554\u2550\u2561 6a6f5db5-7dd4-4a26-ac1a-ef3ca3a5d6be\n# Fact 1\nnorm(L-I\u1d67*I\u1d67')\n\n# \u2554\u2550\u2561 e11bc23d-03e2-4780-9488-93f0adfc2fcb\n# Facts 2 and 7\nissymmetric(L), eigs(L)[1], 2*maximum(diag(L))\n\n# \u2554\u2550\u2561 7192f7d0-28b9-11eb-28dd-8db0019504ca\neigen(Matrix(L))\n\n# \u2554\u2550\u2561 e5890dca-368f-437e-bc45-6a395714dae2\n# Fact 3\nL*ones(n)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 da7f85ed-73b0-44b9-a97f-4a8ed5e9a1d1\nbegin\n\t# Fact 6\n\t\u03b1,\u03b2=rand(),rand()\n\t(\u03b1*x+\u03b2*ones(n))'*L*(\u03b1*x+\u03b2*ones(n)), \u03b1^2*x'*L*x\nend\n\n# \u2554\u2550\u2561 fed7f592-be03-4baf-8ace-ff9ee78fee71\n# Fact 8\neigvals(Matrix(L\u2099))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c188b7cf-03e7-40b3-bf90-773978c7b410\n# Voila!\neigs(L,nev=2,which=:SM, v0=ones(n))\n\n# \u2554\u2550\u2561 f60b51b6-79c3-4a3f-8bfb-8f198cdb92a8\n# For the normalized cut\neigs(L\u2099,nev=2,which=:SM, v0=ones(n))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03d5=2*\u03c0*rand(sum(sizes))\n\tfor i=1:csizes[1]\n\t\tX[:,i]=center+radii[1]*[cos(\u03d5[i]);sin(\u03d5[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(\u03d5[i]);sin(\u03d5[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# \u2554\u2550\u2561 fa4ae713-a0b2-46ce-b5f7-558b26d82019\n# Weight matrix\nW\u2081=1 ./pairwise(SqEuclidean(),X)\n\n# \u2554\u2550\u2561 760e8ca2-596f-435f-befb-140b3d204f7f\nbegin\n\t# Laplacian matrix\n\tm=csizes[end]\n\tfor i=1:m\n\t    W\u2081[i,i]=0\n\tend\n\tL\u2081=Diagonal(vec(sum(W\u2081,dims=2)))-W\u2081\n\t# Check Fact 3\n\tnorm(L\u2081*ones(m))\nend\n\n# \u2554\u2550\u2561 75956488-76ab-4262-a32f-0c53e1b3dc17\n# Notice \u03bb\u2081=0\nE=eigs(L\u2081,nev=2,which=:SM, v0=ones(m))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 46de28bc-73ed-495c-a2e0-f565c1ce5651\nplotKpartresult(C,X)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bb9d4d98-3aff-439e-b8a3-8347cf345839\nbegin\n\t\u03c3=0.7 # 0.1\n\tW\u2082=exp.(-pairwise(SqEuclidean(),X)/\u03c3^2)-I\n\tL\u2082=Diagonal(vec(sum(W\u2082,dims=2)))-W\u2082\n\tE\u2082=eigs(L\u2082,nev=2,which=:SM, v0=ones(m))\n\tC\u2082=ones(Int64,m)\n\tC\u2082[findall(E\u2082[2][:,2].>0)].=2\n\tplotKpartresult(C\u2082,X)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f3eb8ad4-55a8-4e76-a581-07f9a7cc75f7\n\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25007ef4b0b3-9d0a-4356-bd16-14487f14e0ab\n# \u255f\u2500cb61f761-b2ee-4818-9149-f85d95b76a1e\n# \u255f\u25005926c79a-6038-4dbc-b49a-5b05d02250a0\n# \u255f\u2500a66a6e80-1f80-11eb-15f8-71ffaa5050e7\n# \u255f\u2500d4cf12ce-12fb-4562-bbea-e9b85cba94c2\n# \u2560\u25500cd92d78-1da6-435b-ad8e-60af29502e1d\n# \u2560\u255087cca1d3-b944-4d74-bf4c-1562f34cf91a\n# \u2560\u25503d7b4a01-9a7d-4111-a45d-1d31f1ef6278\n# \u2560\u25503b5ed1fa-75b0-43fb-a918-4c2e8f52d039\n# \u2560\u25508f7d1f6c-ee4c-407f-80d9-d2abc2af949e\n# \u2560\u2550b7f127d8-e8cd-4771-8091-c88f9ffe6b08\n# \u2560\u25503f5447bb-95cd-4520-b0b9-e85f33b323bd\n# \u2560\u2550ecb2a46e-f9dc-4e57-812f-0a2788afb202\n# \u2560\u255086e5f00f-13ee-4867-b0cd-187f2c782a46\n# \u2560\u2550cf26dbe9-3c4f-4c95-88ef-f197f360d759\n# \u2560\u25508fcd2440-4013-4b37-a747-2c0c7f6d4aeb\n# \u2560\u25500c8d3572-3436-446f-952a-b19d0370ab38\n# \u2560\u25501437aadc-1c26-4eff-bb22-9cf9c15e1f5f\n# \u255f\u25006529324b-49f7-4f01-b5cd-33668979b56b\n# \u255f\u2500a9ba64a6-bd17-4b86-acb4-e7c7d8f87dc1\n# \u2560\u25506a6f5db5-7dd4-4a26-ac1a-ef3ca3a5d6be\n# \u2560\u2550e11bc23d-03e2-4780-9488-93f0adfc2fcb\n# \u2560\u25507192f7d0-28b9-11eb-28dd-8db0019504ca\n# \u2560\u2550e5890dca-368f-437e-bc45-6a395714dae2\n# \u2560\u255061a978a7-b2d2-43e7-b3f7-95bf4c4f54b9\n# \u2560\u2550da7f85ed-73b0-44b9-a97f-4a8ed5e9a1d1\n# \u2560\u2550fed7f592-be03-4baf-8ace-ff9ee78fee71\n# \u255f\u25009f31928e-c933-43bb-9a5c-bf55f29737cd\n# \u255f\u25001e6d4c72-f25d-4bf5-99d6-ae0446be25dd\n# \u255f\u250002035eed-6d49-4253-a755-68a999e7e90e\n# \u2560\u2550c188b7cf-03e7-40b3-bf90-773978c7b410\n# \u2560\u2550f60b51b6-79c3-4a3f-8bfb-8f198cdb92a8\n# \u255f\u2500bfac7a55-0d82-4549-b999-7db3272eaa20\n# \u2560\u255080ed91ad-6f9a-4f12-a1ee-bc8dc6b58168\n# \u2560\u25502d8689c9-1b9e-4360-865c-23c2c8c5dcb9\n# \u2560\u2550fa4ae713-a0b2-46ce-b5f7-558b26d82019\n# \u2560\u2550760e8ca2-596f-435f-befb-140b3d204f7f\n# \u2560\u255075956488-76ab-4262-a32f-0c53e1b3dc17\n# \u2560\u2550a55260dd-f05d-4a65-9fdf-cb3fd4638857\n# \u2560\u2550ba164ff3-5ef4-4480-8af2-9dd9a99b1e8d\n# \u2560\u255046de28bc-73ed-495c-a2e0-f565c1ce5651\n# \u255f\u2500e004e4bf-ca04-4b41-947b-9f1ecd058abb\n# \u2560\u2550bb9d4d98-3aff-439e-b8a3-8347cf345839\n# \u255f\u2500012fa54a-5171-4980-a0ba-474a22c25981\n# \u2560\u2550f3eb8ad4-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 NURBS\nusing Base.Test\n\n@testset \"RB-Spline curve generator\" begin\n   \n\t@testset \"rbasis\" begin\n\t\tx = knot(5, 4)\n\t\th = [1, 1, 0.25, 1, 1]\n\t\t@test typeof(rbasis(5, 4, 0.5, x, h)) == Array{Float64,1}\n\t\t@test isapprox(rbasis(5, 4, 0.5, x, h), [0.153846, 0.730769, 0.0769231, 0.0384615, 0.0], atol = 1e-5)\n\tend\n    \n\t@testset \"rbspline\" begin\n\t\tb = [0 1 5/2 4 5; 1 2 0 2 0; 0 0 0 0 0]\n\t\th = [1, 1, 0.25, 1, 1]\n\t\t@test typeof(rbspline(5, 3, 10, b, h)[1]) == Array{Float64,2}\n\t\t@test typeof(rbspline(5, 3, 10, b, h)[2]) == Array{Array{Int64,1},1}\n\t\t@test isapprox(rbspline(5, 3, 10, b, h)[1], [0.0 0.557971 0.966667 1.3 1.95455 3.04545 3.7 4.03333 4.44203 5.0; 1.0 1.50725 1.73333 1.6 1.21212 1.21212 1.6 1.6 1.04348 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0], atol = 1e-5)\n\tend\n    \n\t@testset \"rbsplinu\" begin\n\t\tb = [0 1 5/2 4 5; 1 2 0 2 0; 0 0 0 0 0]\n\t\th = [1, 1, 0.25, 1, 1]\n\t\t@test typeof(rbsplinu(5, 3, 10, b, h)[1]) == Array{Float64,2}\n\t\t@test typeof(rbsplinu(5, 3, 10, b, h)[2]) == Array{Array{Int64,1},1}\n\t\t@test isapprox(rbsplinu(5, 3, 10, b, h)[1], [0.5 0.789855 1.03333 1.3 1.95455 3.04545 3.7 3.96667 4.21014 4.75; 1.5 1.73913 1.8 1.6 1.21212 1.21212 1.6 1.73333 1.50725 0.5; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0], atol = 1e-4)\n\tend\n    \nend\n", "meta": {"hexsha": "b2d979a2c28ae257f9cedeeb624b418154aa45a7", "size": 1259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rbspline.jl", "max_stars_repo_name": "eOnofri04/IN480", "max_stars_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-06T17:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:30:18.000Z", "max_issues_repo_path": "test/rbspline.jl", "max_issues_repo_name": "TheChoice04/IN480", "max_issues_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-11-22T18:10:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-07T16:32:36.000Z", "max_forks_repo_path": "test/rbspline.jl", "max_forks_repo_name": "TheChoice04/IN480", "max_forks_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-06T17:54:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T17:54:09.000Z", "avg_line_length": 41.9666666667, "max_line_length": 229, "alphanum_fraction": 0.5798252581, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7760016839803129}}
{"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 \u00c5^-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\"\u03bcm\"\n(1.0:0.020202020202020204:3.0) \u03bcm\n\njulia> bb = blackbody(wave, 2000u\"K\")\nUnitfulSpectrum (100,)\n  \u03bb (\u03bcm) f (W \u03bcm^-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 \u03bcm\n\njulia> 2898u\"\u03bcm*K\" / bb.T # See if it matches up with Wien's law\n1.449 \u03bcm\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": "@testset \"Kolmogorov-Smirnov test\" begin\n    x = [\n        392,585,410,414,384,423,456,549,455,406,470,402,416,431,435,413,468,435,\n        432,438,425,392,410,498,475,431,460,440,420,422,409,417,370,500,501,478,\n        454,444,447,393,446,454,500,433,444,427,412,433,460,434\n    ]\n    res_kstest = ks_test(x, Normal(mean(x), std(x)))\n    @test res_kstest.statistic \u2248 0.119089045870544\n    @test res_kstest.n_obs == 50\n    @test res_kstest.pval \u2248 0.477419559223632\nend\n", "meta": {"hexsha": "88013f26e04b1b8d1edca1a4b7b538836a58632f", "size": 470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_ks.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": "test/test_ks.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": "test/test_ks.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": 39.1666666667, "max_line_length": 80, "alphanum_fraction": 0.6680851064, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7760016787360462}}
{"text": "## PART 2\n\n# Define the error functions\n\nfunction \u03c3f1(v\u0304\u0302,\u03c3\u0302)\n    ddvs = zeros(5);\n    ddvs[1] = 1 / v\u0304\u0302[2]^2;\n    ddvs[2] = v\u0304\u0302[1]^2 / v\u0304\u0302[2]^4;\n    return sqrt( dot( ddvs, \u03c3\u0302.^2) );\nend\n\nfunction \u03c3f2(v\u0304\u0302,\u03c3\u0302)\n    ddvs = zeros(5);\n    ddvs[3] = exp(v\u0304\u0302[3] - v\u0304\u0302[4])^2;\n    ddvs[4] = exp(v\u0304\u0302[3] - v\u0304\u0302[4])^2;\n    return sqrt( dot( ddvs, \u03c3\u0302.^2) );\nend\n\nfunction \u03c3f3(v\u0304\u0302,\u03c3\u0302)\n    lv5s = log(v\u0304\u0302[5])^2;\n    ddvs = zeros(5);\n    ddvs[1] = lv5s / v\u0304\u0302[2]^2;\n    ddvs[2] = lv5s * v\u0304\u0302[1]^2 / v\u0304\u0302[2]^4;\n    ddvs[3] = lv5s / v\u0304\u0302[4]^2;\n    ddvs[4] = lv5s * v\u0304\u0302[3]^2 / v\u0304\u0302[4]^4;\n    ddvs[5] = ( ( v\u0304\u0302[1]/v\u0304\u0302[2] + v\u0304\u0302[3]/v\u0304\u0302[4] ) / v\u0304\u0302[5] )^2;\n    return sqrt( dot( ddvs, \u03c3\u0302.^2) );\nend\n\nprintln(\"Calculating \u03c3\u0302f1, \u03c3\u0302f2, \u03c3\u0302f3 for sample sizes N1, N2\");\n\u03c3\u0302f1N1 = \u03c3f1(v\u0304\u0302,\u03c3\u03021); \n\u03c3\u0302f2N1 = \u03c3f2(v\u0304\u0302,\u03c3\u03021);\n\u03c3\u0302f3N1 = \u03c3f3(v\u0304\u0302,\u03c3\u03021);\n\n\u03c3\u0302f1N2 = \u03c3f1(v\u0304\u0302,\u03c3\u03022); \n\u03c3\u0302f2N2 = \u03c3f2(v\u0304\u0302,\u03c3\u03022);\n\u03c3\u0302f3N2 = \u03c3f3(v\u0304\u0302,\u03c3\u03022);\n\nprintln(\"\\n\\tNaive standard deviations for sample size 1,000\");\nprintln(\"\\t\u03c3\u0302f1N1 = $\u03c3\u0302f1N1\"); \nprintln(\"\\t\u03c3\u0302f2N1 = $\u03c3\u0302f2N1\");\nprintln(\"\\t\u03c3\u0302f3N1 = $\u03c3\u0302f3N1\");\n\nprintln(\"\\n\\tNaive standard deviations for sample size 10,000\");\nprintln(\"\\t\u03c3\u0302f1N2 = $\u03c3\u0302f1N2\"); \nprintln(\"\\t\u03c3\u0302f2N2 = $\u03c3\u0302f2N2\");\nprintln(\"\\t\u03c3\u0302f3N2 = $\u03c3\u0302f3N2\");\n\nprintln(\"\\n\\tTrue standard deviations for sample size 1,000\");\nprintln(\"\\t\u03c3\u0302truef1N1 = $\u03c3\u0302truef1N1\"); \nprintln(\"\\t\u03c3\u0302truef2N1 = $\u03c3\u0302truef2N1\");\nprintln(\"\\t\u03c3\u0302truef3N1 = $\u03c3\u0302truef3N1\");\n\nprintln(\"\\n\\tTrue standard deviations for sample size 10,000\");\nprintln(\"\\t\u03c3\u0302truef1N2 = $\u03c3\u0302truef1N2\"); \nprintln(\"\\t\u03c3\u0302truef2N2 = $\u03c3\u0302truef2N2\");\nprintln(\"\\t\u03c3\u0302truef3N2 = $\u03c3\u0302truef3N2\");\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\u2080, nu\u2080, \u03b11, \u03b13, \u03b211, \u03b213, \u03b233)\n\nCompute 6\u00d76 stiffness matrix (in Voight notation) for a cracked material characterised by normalised crack density parameters \u03b11, \u03b13, \u03b211, \u03b213 and \u03b233, with solid matrix moduli E\u2080 and nu\u2080. Crack density parameters are normalised by h = 3E\u2080(2-nu\u2080)/(32(1-nu\u2080\u00b2)). From Sayers and Kachanov 1995.\n\"\"\"\nfunction cracks2moduli(E\u2080, nu\u2080, \u03b11, \u03b13, \u03b211, \u03b213, \u03b233)\n    S011 = 1/E\u2080\n    S012 = -nu\u2080/E\u2080\n    h = cracknormfactor(E\u2080, nu\u2080)\n\n    D = (S011 + \u03b13/h + \u03b233/h)*(S011 + S012 + \u03b11/h + 4\u03b211/h/3) -\n        2*(S012 + \u03b213/h)^2\n\n    c11 = (1/2)*((S011+\u03b13/h+\u03b233/h)/D + 1/(S011-S012+\u03b11/h+2\u03b211/h/3))\n    c33 = (S011 + S012 + \u03b11/h + 4\u03b211/h/3)/D\n    c44 = 1/(2S011 - 2S012 + \u03b11/h + \u03b13/h + 4\u03b213/h)\n    c13 = -(S012 + \u03b213/h)/D\n    c66 = 1/(S011-S012+\u03b11/h+2\u03b211/h/3)/2\n\n    return stiffmatrixTI(c11, c13, c33, c44, c66)\nend\n\n\"\"\"\n\tcracknormfactor(E\u2080, \u03bd\u2080)\n\nCompute normalisation factor h=3E\u2080*(2-nu\u2080)/(32(1-nu\u2080\u00b2)).\n\"\"\"\nfunction cracknormfactor(E\u2080, \u03bd\u2080)\n    return 3E\u2080*(2-\u03bd\u2080)/(32(1-\u03bd\u2080^2))\nend\n\n\"\"\"\n\tfindcracks(p::Vector{VMeasure},\n                    sv::Vector{VMeasure},\n                    sh::Vector{VMeasure},\n                    \u03c1::Real,\n                    E\u2080::Real,\n                    nu\u2080::Real,\n                    \u03b1\u2081\u2080::Tuple{Real,Real},\n                    \u03b1\u2083\u2080::Tuple{Real,Real},\n                    \u03b2\u2081\u2081\u2080::Tuple{Real,Real},\n                    \u03b2\u2081\u2083\u2080::Tuple{Real,Real},\n                    \u03b2\u2083\u2083\u2080::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 ()\u2080 are tuples with value and standard deviation (a priori gaussian).\n\nReturn \u03b1\u2081\u2081, \u03b1\u2083\u2083, \u03b2\u2081\u2081\u2081\u2081, \u03b2\u2081\u2081\u2083\u2083, \u03b2\u2083\u2083\u2083\u2083, \u03b8p, \u03b8sv, \u03b8sh, CMpost.\n\"\"\"\nfunction findcracks(p::Vector{VMeasure},\n                    sv::Vector{VMeasure},\n                    sh::Vector{VMeasure},\n                    \u03c1::Real,\n                    E\u2080::Real,\n                    nu\u2080::Real,\n                    \u03b1\u2081\u2080::Tuple{Real,Real},\n                    \u03b1\u2083\u2080::Tuple{Real,Real},\n                    \u03b2\u2081\u2081\u2080::Tuple{Real,Real},\n                    \u03b2\u2081\u2083\u2080::Tuple{Real,Real},\n                    \u03b2\u2083\u2083\u2080::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\u2080 = [\u03b1\u2081\u2080[1],\u03b1\u2083\u2080[1],\u03b2\u2081\u2081\u2080[1],\u03b2\u2081\u2083\u2080[1],\u03b2\u2083\u2083\u2080[1]]\n    \u03c3m = [\u03b1\u2081\u2080[2],\u03b1\u2083\u2080[2],\u03b2\u2081\u2081\u2080[2],\u03b2\u2081\u2083\u2080[2],\u03b2\u2083\u2083\u2080[2]]\n\n    C\u2080 = cracks2moduli(E\u2080, nu\u2080, m\u2080...)\n    \u03f5\u2080, \u03b4\u2080, \u03b3\u2080 = moduli2thomsen(C\u2080)\n    vp,vs = velocities0(C\u2080,\u03c1) # here density does not matter\n    \n    for x in p\n        push!(m\u2080, phaseangleP(x.angle, vp/vs, \u03f5\u2080, \u03b4\u2080))\n        push!(\u03c3m, 100)\n    end\n    for x in sv\n        push!(m\u2080, phaseangleSV(x.angle, vp/vs, \u03f5\u2080, \u03b4\u2080))\n        push!(\u03c3m, 100)\n    end\n    for x in sh\n        push!(m\u2080, phaseangleSH(x.angle, \u03b3\u2080))\n        push!(\u03c3m, 100)\n    end\n    \n    CM = Diagonal(\u03c3m.^2)\n    CMi = inv(CM)\n\n    m, CMpost = quasinewton(dobs, _gf, m\u2080, CMi, CDi, (E\u2080, nu\u2080, \u03c1,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\u2080,nu\u2080,\u03c1,np,nsv,nsh)\n    C\u2080 = cracks2moduli(E\u2080, nu\u2080, m[1:5]...)\n    \u03f5, \u03b4, \u03b3 = moduli2thomsen(C\u2080)\n    vp0,vs0 = velocities0(C\u2080,\u03c1)\n    mt = vcat([vp0,vs0,\u03f5,\u03b4,\u03b3], 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": "function vector_identities(c)\n    A = ContravariantVector(2*randn(3),c,unit_basis=true)\n    B = ContravariantVector(2*randn(3),c,unit_basis=true)\n    C = CovariantVector(2*randn(3),c,unit_basis=true)\n    D = CovariantVector(2*randn(3),c,unit_basis=true)\n\n    \u03f5 = eps(abs(float(one(eltype(A)))))\n\n    A_BxC = dot(A,cross(B,C))\n    @test isapprox(A_BxC, dot(cross(A,B),C), atol=500\u03f5)\n    @test isapprox(A_BxC, dot(B,cross(C,A)), atol=500\u03f5)\n    @test isapprox(A_BxC, dot(cross(B,C),A), atol=500\u03f5)\n    @test isapprox(A_BxC, dot(C,cross(A,B)), atol=500\u03f5)\n    @test isapprox(A_BxC, dot(cross(C,A),B), atol=500\u03f5)\n\n    AxBxC = cross(A,cross(B,C))\n    @test isapprox(AxBxC, cross(cross(C,B),A), atol=500\u03f5)\n    @test isapprox(AxBxC, dot(A,C)*B - dot(A,B)*C, atol=500\u03f5)\n\n    @test isapprox(cross(A,cross(B,C)) + cross(B,cross(C,A)) + cross(C,cross(A,B)), zeros(eltype(A),length(A)), atol=2000\u03f5)\n\n    AxB_CxD = dot(cross(A,B),cross(C,D))\n    @test isapprox(AxB_CxD, dot(A,C)*dot(B,D) - dot(A,D)*dot(B,C), atol=2000\u03f5)\n\n    AxBxCxD = cross(cross(A,B),cross(C,D))\n    @test isapprox(AxBxCxD, (dot(cross(A,B),D)*C - dot(cross(A,B),C)*D), atol=2000\u03f5)\nend\n\n@testset \"Algebraic Operations\" begin\n    println(\"Testing Algebraic Identities...\")\n    @testset \"Algebraic Identities\" begin\n        @testset \"Cartesian\" begin\n            c = CartesianCoordinate([2.0,-1.0,1.5])\n            vector_identities(c);\n        end\n        @testset \"Cylindrical\" begin\n            c = CylindricalCoordinate([2.0,pi/4,-1.0])\n            vector_identities(c);\n        end\n        @testset \"Spherical\" begin\n            c = SphericalCoordinate([2.0,pi/4,pi/3])\n            vector_identities(c);\n        end\n    end\nend\n", "meta": {"hexsha": "492a69b247c5661b0e2c44b6e171039008d0b087", "size": 1683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/algebraic.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": "test/algebraic.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": "test/algebraic.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": 36.5869565217, "max_line_length": 123, "alphanum_fraction": 0.6185383244, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7759898284020365}}
{"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. \u201cBI-LEVEL IMAGE THRESHOLDING - A Fast Method\u201d, 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\u2080\u2081 = 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\u2080\u2081[i] = img[i] < t ? 0 : 1\r\n  end\r\n  img\u2080\u2081\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": "using Printf\n\nfunction distcheck(f::Function, rep::Int=10000, \u0394::Int=3)\n    smpl = f(rep)\n    counts = Dict(k => count(smpl .== k) for k in unique(smpl))\n    expected = rep / length(counts)\n    lbound = expected * (1 - 0.01\u0394)\n    ubound = expected * (1 + 0.01\u0394)\n    noobs = count(x -> !(lbound \u2264 x \u2264 ubound), values(counts))\n    if noobs > 0 warn(@sprintf \"%2.4f%% values out of bounds\" noobs / rep) end\n    return counts\nend\n\n# Dice5 check\ndistcheck(x -> rand(1:5, x))\n# Dice7 check\ndistcheck(dice7)\n", "meta": {"hexsha": "5e3e5fb15fb3bbbc3af058767ec852a606e92cff", "size": 501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/verify-distribution-uniformity-naive.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/verify-distribution-uniformity-naive.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/verify-distribution-uniformity-naive.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.8333333333, "max_line_length": 78, "alphanum_fraction": 0.620758483, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.775985236649062}}
{"text": "function boxcox(z, \u03bb)\n    reduce(&, z .> 0) || throw(DomainError(\"boxcox requires strictly positive data\"))\n\tif \u03bb == 0\n\t\treturn log.(z) \n\telse\n\t\treturn (z.^\u03bb .- 1) ./ \u03bb\n\tend\nend\n\nfunction inv_boxcox(z, \u03bb)\n    if \u03bb == 0\n        return exp.(z)\n    else \n        return (\u03bb .* z .+ 1).^(1/\u03bb)\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 \u00f7 s, s)\n    m = mean(rz, dims=1)\n    sd = std(rz, mean=m, dims=1)\n    function cv(\u03bb)\n        w = sd ./ (m.^(1 - \u03bb))\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(-\u03c0,\u03c0)\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([-\u03c0,\u03c0])\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/\u03c0\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": "using Pythia\nusing Test\nusing CSV\nusing DataFrames\n\n# Using Examples from Forecasting: Principles and Practice (2nd ed.) by Rob J Hyndman and George Athanasopoulos\n# Ground Truth Taken from statsmodels\n\n### Exponential Smoothing Tests ###\n\n## Simple Exponential Smoothing ##\n\n# Import Data\noildata = CSV.read(\"fpp2_datasets/oil.csv\", DataFrame)\ny = oildata[!, 3] \ny = y[32:49]\n\n# Initialize Model and Make Prediction\nmdl = SES(y, h = 5)\nfitted_mdl = fit(mdl, v = 0)\nyhat = predict(fitted_mdl)\nyactual = [542.6803683882322, 542.6803683882322, 542.6803683882322, 542.6803683882322, 542.6803683882322]\n\n@test yhat \u2248 yactual rtol=0.05\n# Compare yhat with ground truth\n\n## Holt's Linear Trend Method ##\n\n# Import Data\nausair = CSV.read(\"fpp2_datasets/ausair.csv\", DataFrame)\ny = ausair[!, 3]\ny = y[21:47]\n\n# Initialize Model and Make Prediction\nmdl = Holt(y, h = 5)\nfitted_mdl = fit(mdl, v = 0)\nyhat = predict(fitted_mdl)\nyactual = [74.59331490568717, 76.69123025401483, 78.7891456023425, 80.88706095067016, 82.98497629899784]\n@test yhat \u2248 yactual rtol=0.05\n\n## Holt's Linear Method - Damped ##\nmdl = Holt(y, h = 5, damped = true)\nfitted_mdl = fit(mdl, v = 0)\nyhat = predict(fitted_mdl)\nyactual = [74.4245006855701, 76.3634111773908, 78.2926270423973, 80.21219675409546, 82.12216854362171]\n@test yhat \u2248 yactual rtol=0.05\n\n## HoltWinter's Method ##\n\n# Import Data\naustourists = CSV.read(\"fpp2_datasets/austourists.csv\", DataFrame)\ny = austourists[!, 3]\ny = y[25:68]\n\n# Initialize Model and Make Prediction\nmdl = HoltWinters(y, h = 5, m = 4, init_season = [9.70, -9.31, -1.69, 1.31])\nfitted_mdl = fit(mdl, v = 0)\nyhat = predict(fitted_mdl)\n# @test yhat \u2248 yactual rtol=0.05", "meta": {"hexsha": "4d9ffa24cea60eb061f72dc80e395a4b1cf539bc", "size": 1665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ETS_test.jl", "max_stars_repo_name": "ababii/Pythia", "max_stars_repo_head_hexsha": "7f358694f8f586c44ea465d22d40a43c2060b0d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-02-18T17:43:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:31:40.000Z", "max_issues_repo_path": "test/ETS_test.jl", "max_issues_repo_name": "ababii/Pythia", "max_issues_repo_head_hexsha": "7f358694f8f586c44ea465d22d40a43c2060b0d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-01-05T06:58:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-13T22:05:24.000Z", "max_forks_repo_path": "test/ETS_test.jl", "max_forks_repo_name": "ababii/Pythia", "max_forks_repo_head_hexsha": "7f358694f8f586c44ea465d22d40a43c2060b0d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-03-27T19:55:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-20T21:20:20.000Z", "avg_line_length": 28.2203389831, "max_line_length": 111, "alphanum_fraction": 0.7201201201, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7758905039405652}}
{"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": "using OrdinaryDiffEq, ModelingToolkit, Test, LinearAlgebra\n@parameters t\n@variables y[1:3](t)\n@parameters k[1:3]\nD = Differential(t)\n\neqs = [D(y[1]) ~ -k[1] * y[1] + k[3] * y[2] * y[3],\n    D(y[2]) ~ k[1] * y[1] - k[3] * y[2] * y[3] - k[2] * y[2]^2,\n    0 ~ y[1] + y[2] + y[3] - 1]\n\n@named sys = ODESystem(eqs, t, y, k)\n@test_throws ArgumentError ODESystem(eqs, y[1])\nM = calculate_massmatrix(sys)\n@test M == [1 0 0\n            0 1 0\n            0 0 0]\n\nf = ODEFunction(sys)\nprob_mm = ODEProblem(f, [1.0, 0.0, 0.0], (0.0, 1e5), (0.04, 3e7, 1e4))\nsol = solve(prob_mm, Rodas5(), reltol = 1e-8, abstol = 1e-8)\n\nfunction rober(du, u, p, t)\n    y\u2081, y\u2082, y\u2083 = u\n    k\u2081, k\u2082, k\u2083 = p\n    du[1] = -k\u2081 * y\u2081 + k\u2083 * y\u2082 * y\u2083\n    du[2] = k\u2081 * y\u2081 - k\u2083 * y\u2082 * y\u2083 - k\u2082 * y\u2082^2\n    du[3] = y\u2081 + y\u2082 + y\u2083 - 1\n    nothing\nend\nf = ODEFunction(rober, mass_matrix = M)\nprob_mm2 = ODEProblem(f, [1.0, 0.0, 0.0], (0.0, 1e5), (0.04, 3e7, 1e4))\nsol2 = solve(prob_mm2, Rodas5(), reltol = 1e-8, abstol = 1e-8, tstops = sol.t,\n             adaptive = false)\n\n# MTK expression are canonicalized, so the floating point numbers are slightly\n# different\n@test Array(sol) \u2248 Array(sol2)\n\n# Test mass matrix in the identity case\neqs = [D(y[1]) ~ y[1], D(y[2]) ~ y[2], D(y[3]) ~ y[3]]\n\n@named sys = ODESystem(eqs, t, y, k)\n\n@test calculate_massmatrix(sys) === I\n", "meta": {"hexsha": "f1894981a9d1c79dbdf361f225f858c70924c944", "size": 1320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mass_matrix.jl", "max_stars_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146, "max_stars_repo_stars_event_min_datetime": "2018-03-18T19:25:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-21T16:11:30.000Z", "max_issues_repo_path": "test/mass_matrix.jl", "max_issues_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 198, "max_issues_repo_issues_event_min_datetime": "2018-03-18T17:03:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T08:15:41.000Z", "max_forks_repo_path": "test/mass_matrix.jl", "max_forks_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-03-26T14:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T18:41:19.000Z", "avg_line_length": 29.3333333333, "max_line_length": 78, "alphanum_fraction": 0.5643939394, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.775880410175141}}
{"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": "@testset \"BasicEMD\" begin\n    @testset \"BasicEMD Test 1\" begin\n        n = 200\n        s = EMDSetting(n, 50, 10, 2)\n\n        t = collect(range(0,1, length=n))\n        x = zeros(n)\n\n        for i=1:n\n            x[i] = cos(22*pi*t[i]^2) + 6*t[i]^2\n        end\n\n        output = emd(x, s)\n\n        @test size(output, 2) == s.m\n\n        recovered = zeros(n)\n\n        for i=1:size(output, 2)\n            recovered += output[:, i]\n        end\n\n        @test recovered == x || isapprox(recovered, x)\n    end\n\n    @testset \"BasicEMD Test 2\" begin\n        N = 1024\n        s = EMDSetting(N, 50, 10, 10)\n\n        function input_signal(x::Float64)\n            omega = 2*pi/(N-1)\n            return sin(17*omega*x)+0.5*(1.0-exp(-0.002*x))*sin(51*omega*x+1)\n        end\n\n        input = zeros(N)\n\n        for i=1:N\n            input[i] = input_signal(float(i))\n        end\n\n\n        output = emd(input, s)\n\n        @test size(output, 2) == s.m\n\n        recovered = zeros(N)\n\n        for i=1:size(output, 2)\n            recovered += output[:, i]\n        end\n\n        @test recovered == input || isapprox(recovered, input)\n    end\nend\n\n", "meta": {"hexsha": "510d18b1936e03a0d86a35c33cbd85783329227e", "size": 1122, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basic_emd.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalModeDecomposition.jl-6a34a51b-2f4a-4636-bd3c-e47519ebd0d9", "max_stars_repo_head_hexsha": "706f65c0a2a28271e2d31979ce5c1478d40ec43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-21T14:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T14:21:37.000Z", "max_issues_repo_path": "test/basic_emd.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalModeDecomposition.jl-6a34a51b-2f4a-4636-bd3c-e47519ebd0d9", "max_issues_repo_head_hexsha": "706f65c0a2a28271e2d31979ce5c1478d40ec43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-08-28T04:56:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-05T09:14:18.000Z", "max_forks_repo_path": "test/basic_emd.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalModeDecomposition.jl-6a34a51b-2f4a-4636-bd3c-e47519ebd0d9", "max_forks_repo_head_hexsha": "706f65c0a2a28271e2d31979ce5c1478d40ec43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:06.000Z", "avg_line_length": 20.0357142857, "max_line_length": 76, "alphanum_fraction": 0.4768270945, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.853912747375134, "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\u00b2_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\u0302, 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\u0302, y; weight = ones(eltype(y),length(y)))  = -sum(y .* log.(y\u0302 .+ 1e-15) .* weight)\ndCrossEntropy(y\u0302, y; weight = ones(eltype(y),length(y))) = - y .* weight ./ (y\u0302 .+ 1e-15)\n\n\n\"\"\" accuracy(y\u0302,y;ignoreLabels=false) - Categorical accuracy between two vectors (T vs T). \"\"\"\nfunction accuracy(y\u0302::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\u0302 .== y)/length(y\u0302)\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\u0302OrigIdx = [findfirst(x -> x == y\u0302[i] , classes) for i in 1:N]\n        for perm in pSet\n            py = perm[yOrigIdx] # permuted specific version\n            acc = sum(y\u0302OrigIdx .== py)/N\n            if acc > bestAcc\n                bestAcc = acc\n            end\n        end\n        return bestAcc\n    end\nend\n\n\"\"\" error(y\u0302,y;ignoreLabels=false) - Categorical error (T vs T)\"\"\"\nerror(y\u0302::AbstractArray{T,1},y::AbstractArray{T,1}; ignoreLabels=false) where {T} = (1 - accuracy(y\u0302,y;ignoreLabels=ignoreLabels) )\n\n\n\"\"\"\n    accuracy(y\u0302,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\u0302::Array{T,1},y_pos::Int64;tol=1,rng=Random.GLOBAL_RNG) where {T <: Number}\n    #if  length(Set(y\u0302) == 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\u0302;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\u0302)[end:-1:1]\n    if y\u0302[y_pos] in y\u0302[sIdx[1:min(tol,length(sIdx))]]\n        return 1\n    else\n        return 0\n    end\nend\n\n\"\"\"\n    accuracy(y\u0302,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\u0302`: 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\u0302::Dict{T,Float64},y::T;tol=1,rng=Random.GLOBAL_RNG) where {T}\n    if !(y in keys(y\u0302)) return 0 end\n    tol > 1 || return (mode(y\u0302;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\u0302)))[end:-1:1]            # sort by decreasing values of the dictionary values\n    sKeys = collect(keys(y\u0302))[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\u0302,y;tol,ignoreLabels)\n\nCategorical accuracy with probabilistic predictions of a dataset (PMF vs Int).\n\n# Parameters:\n- `y\u0302`: 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\u0302::Array{T,2},y::Array{Int64,1};tol=1,ignoreLabels=false,rng=Random.GLOBAL_RNG) where {T <: Number}\n    (N,D) = size(y\u0302)\n    pSet = ignoreLabels ? collect(permutations(1:D)) : [collect(1:D)]\n    bestAcc = -Inf\n    for perm in pSet\n        py\u0302 = hcat([y\u0302[:,c] for c in perm]...)\n        acc = sum([accuracy(py\u0302[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\u0302,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\u0302`: 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\u0302::Array{Dict{T,Float64},1},y::Array{T,1};tol=1,rng=Random.GLOBAL_RNG) where {T}\n    N = size(y\u0302,1)\n    acc = sum([accuracy(y\u0302[i],y[i];tol=tol,rng=rng) for i in 1:N])/N\n    return acc\nend\n\n\n\"\"\" error(y\u0302,y) - Categorical error with probabilistic prediction of a single datapoint (PMF vs Int). \"\"\"\nerror(y\u0302::Array{T,1},y::Int64;tol=1) where {T <: Number} = 1 - accuracy(y\u0302,y;tol=tol)\n\"\"\" error(y\u0302,y) - Categorical error with probabilistic predictions of a dataset (PMF vs Int). \"\"\"\nerror(y\u0302::Array{T,2},y::Array{Int64,1};tol=1) where {T <: Number} = 1 - accuracy(y\u0302,y;tol=tol)\n\"\"\" error(y\u0302,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\u0302::Array{Dict{T,Float64},1},y::Array{T,1};tol=1) where {T} = 1 - accuracy(y\u0302,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\u0302,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\u0302,y;classes,labels,rng)\n\nBuild a \"confusion matrix\" between predicted (columns) vs actual (rows) categorical values\n\n# Parameters:\n- `y\u0302`: 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\u0302` 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\u0302,y::AbstractArray{T};classes=unique(y),labels=string.(classes),rng=Random.GLOBAL_RNG) where {T}\n    nCl              = length(labels)\n    y\u0302                = typeof(y\u0302) <: AbstractVector{T} ? y\u0302 : mode(y\u0302,rng=rng) # get the mode if needed\n    N                = length(y)\n    length(y\u0302) == N || @error \"y\u0302 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\u0302),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\u0302[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\u0302,y)\n\nCompute the squared costs between a vector of prediction and one of observations as (1/2)*norm(y - y\u0302)^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\u0302,y)   = (1/2)*norm(y - y\u0302)^2\ndSquaredCost(y\u0302,y)  = ( y\u0302 - y)\n\"\"\"\n    mse(y\u0302,y)\n\nCompute the mean squared error (MSE) (aka mean squared deviation - MSD) between two vectors y\u0302 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\u0302,y) = (sum((y-y\u0302).^(2))/length(y))\n\n\"\"\"\n  meanRelError(y\u0302,y;normDim=true,normRec=true,p=1)\n\nCompute the mean relative error (l-1 based by default) between y\u0302 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\u0302 = [2,45,2]`, the _mean relative error_ `meanRelError(y\u0302,y)` is `0.452`, while the _relative mean error_ `meanRelError(y\u0302,y, normRec=false)` is \"only\" `0.0625`.\n\n\"\"\"\nfunction meanRelError(y\u0302,y;normDim=true,normRec=true,p=1)\n    y\u0302 = makeMatrix(y\u0302)\n    y = makeMatrix(y)\n    (n,d) = size(y)\n    #\u03f5 = abs.(y\u0302-y) .^ p\n    if (!normDim && !normRec) # relative mean error\n        avg\u03f5Rel = (sum(abs.(y\u0302-y).^p)^(1/p) / (n*d)) / (sum( abs.(y) .^p)^(1/p) / (n*d)) # (avg error) / (avg y)\n        # avg\u03f5Rel = (norm((y\u0302-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\u03f5Rel_byRec = (sum(abs.(y\u0302-y) .^ (1/p),dims=2).^(1/p) ./ d) ./   (sum(abs.(y) .^ (1/p) ,dims=2) ./d)\n        avg\u03f5Rel = mean(avg\u03f5Rel_byRec)\n    elseif (normDim && !normRec) # normalised by dimensions (i.e.  all dimensions play the same weigth)\n        avg\u03f5Rel_byDim = (sum(abs.(y\u0302-y) .^ (1/p),dims=1).^(1/p) ./ n) ./   (sum(abs.(y) .^ (1/p) ,dims=1) ./n)\n        avg\u03f5Rel = mean(avg\u03f5Rel_byDim)\n    else # mean relative error\n        avg\u03f5Rel = sum(abs.((y\u0302-y)./ y).^p)^(1/p)/(n*d) # avg(error/y)\n        # avg\u03f5Rel = (norm((y\u0302-y)./ y,p)/(n*d))\n    end\n    return avg\u03f5Rel\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 \u03c3 in IterTools.subsets(face, Val(D + 1))\n            @assert issorted(\u03c3; rev=true)\n            \u03c3_idx = index(\u03c3)\n            if !haskey(dicts[D + 1], \u03c3_idx)\n                _, \u03c3_r2 = circumcenter_radius2(points[SVector(\u03c3)])\n                if isfinite(\u03c3_r2)\n                    dicts[D + 1][\u03c3_idx] = \u03c3_r2\n                else\n                    continue\n                end\n            end\n            # Propagate birth time to facets.\n            \u03c3_r2 = dicts[D + 1][\u03c3_idx]\n            for i in 1:(D + 1)\n                \u03c4 = TupleTools.deleteat(\u03c3, i)\n                \u03c4_idx = index(\u03c4)\n                if haskey(dicts[D], \u03c4_idx)\n                    dicts[D][\u03c4_idx] = min(\u03c3_r2, dicts[D][\u03c4_idx])\n                elseif length(\u03c4) > 1\n                    \u03c4_c, \u03c4_r2 = circumcenter_radius2(points[SVector(\u03c4)])\n                    if sum(abs2, \u03c4_c - points[\u03c3[i]]) < \u03c4_r2\n                        dicts[D][\u03c4_idx] = \u03c3_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        \u03c3 = Tuple(_vertices(idx, Val(D + 1)))\n        \u03c3_idx = index(\u03c3)\n        if D > 1\n            for i in 1:(D + 1)\n                \u03c4 = TupleTools.deleteat(\u03c3, i)\n                \u03c4_idx = index(\u03c4)\n                dicts[D][\u03c4_idx] = min(dicts[D][\u03c4_idx], birth)\n            end\n        end\n        corrected_birth = 2 * \u221adicts[D + 1][\u03c3_idx]\n        dicts[D + 1][\u03c3_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 - \u03c0)^2) for t in range(0, 2\u03c0, 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    (\u03b2,\u03b3) = p\n    dS = -\u03b2*S*I\n    dI = \u03b2*S*I - \u03b3*I\n    dC = \u03b2*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\u03b4t = 1;\n\n\nsir_prob = ODEProblem(sir_ode, u0, tspan, p)\nsir_sol = solve(sir_prob, solver, saveat = \u03b4t);\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:\u03b4t:train_time))\ncdata = diff(tsdata[3,:])\nnoisy_data = rand.(Poisson.(N .* cdata));\n\n\nplot(1:\u03b4t:train_time, N .* cdata,\n     xlabel = \"Time\",\n     ylabel = \"New cases per day\",\n     label = \"True value\")\nscatter!(1:\u03b4t: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    \u03b2,\u03b3 = p\n    \u03bb = foi([I],p_)[1]\n    dS = -\u03bb*S\n    dI = \u03bb*S - \u03b3*I\n    dC = \u03bb*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(\u03b8, prob)\n    Array(solve(prob,\n                solver;\n                u0 = u0,\n                p = \u03b8,\n                saveat = \u03b4t,\n                sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP())))\nend;\n\n\nfunction loss(\u03b8, prob)\n    pred = predict(\u03b8, 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((\u03b8)->loss(\u03b8,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 = \u03b4t)\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\u03bb = [foi1([I],res_ude1.minimizer)[1] for I in Igrid]\nscatter(Igrid,\u03bb,xlabel=\"Proportion of population infected, I\",ylab=\"Force of infection, \u03bb\",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((\u03b8)->loss(\u03b8,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 = \u03b4t)\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\u03bb = [foi2([I],res_ude2.minimizer)[1] for I in Igrid]\nscatter(Igrid, \u03bb, xlabel=\"Proportion of population infected, i\", ylab=\"Force of infection, \u03bb\", 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, \u03c3!\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\u03c3(x, w, b) = 1 / (1 + exp(-w * x + b))\r\n#+\r\n\r\n#' What we want is that when we give \u03c3 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 \u03c3 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 -> \u03c3(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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -\u03b2*c*I/N*S\n        du[2] = \u03b2*c*I/N*S - \u03b3*I\n        du[3] = \u03b3*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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    ifrac = \u03b2*I/N*S\n    rfrac = \u03b3*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\u03b4t = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:\u03b4t:tmax;\n\n\nu0 = [990.0,10.0,0.0]; # S,I,R\n\n\np = [0.05,10.0,0.25]; # \u03b2,c,\u03b3\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\u2032` 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\u2032::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 \u2209 f\u2032(X)\n            while true\n                m = mid(X)\n                N = m - (f(Interval(m)) / f\u2032(X))\n                X = X \u2229 N\n\n                if isempty(X)\n                    break\n\n                elseif 0 \u2208 f(Interval(prevfloat(m), nextfloat(m)))\n                    push!(R, Root(X, :unique))\n                    break\n                end\n            end\n\n        else\n            # 0 \u2208 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 \u2208 f(Interval(mid(X)))\n                # 0 \u2208 f\u2071(x)\n                # Step 7\n\n                if 0 \u2209 f(Interval(X.lo))\n                    expansion_pt = X.lo\n\n                elseif 0 \u2209 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 \u2209 f(Interval(x1)) || 0 \u2209 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 \u2209 f\u2071(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\u2032(X)\n\n            if 0 < b.hi && 0 > b.lo && 0 \u2209 a\n                if a.hi < 0\n                    push!(L, X \u2229 (expansion_pt - Interval(-Inf, a.hi / b.hi)))\n                    push!(L, X \u2229 (expansion_pt - Interval(a.hi / b.lo, Inf)))\n\n                elseif a.lo > 0\n                    push!(L, X \u2229 (expansion_pt - Interval(-Inf, a.lo / b.lo)))\n                    push!(L, X \u2229 (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\u2032(X))\n                X = X \u2229 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    \u03b4 = 1.0e-7\n    # -sum(t .* log.(y .+ \u03b4))\n    return -(t \u22c5 log.(y .+ \u03b4))\nend\n\nfunction crossentropyerror(y::Matrix, t::Matrix)\n    batch_size = size(y, 2)\n    \u03b4 = 1.0e-7\n    # -sum(t .* log.(y .+ \u03b4)) ./ batch_size\n    return -vecdot(t, log.(y .+ \u03b4)) ./ 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": "@testset \"area.jl\" begin\n\n    angular_distance_x = 34.49\n    angular_distance_y = 28.11\n    angular_distance_z = 29.0\n\n    @test area(angular_distance_z, angular_distance_y, angular_distance_x) \u2248 0.1239 atol = 0.01\n\n    p1a = Point(0.0, 0.0)\n    p2a = Point(0.0, 90.0)\n    p3a = Point(89.99, 0.0)\n\n    @test area(p1a, p2a, p3a) \u2248 1.5708 atol = 0.001\n    @test area(p1a, Point(0.0, 179.99), p3a) \u2248 3.1416 atol = 0.001\n\n    pi = Point(32.0, 47.0)\n    poly = Polygon(pi, [p1a, p2a, p3a])\n\n    @test area(poly) \u2248 1.5708 atol = 0.001\n    @test area(Polygon(pi, [p1a, Point(0.0, 179.99), p3a])) \u2248 3.1416 atol = 0.001\n    @test area(Polygon(pi, [p1a, p2a, p3a, Point(0.0, 270.001), Point(-89.99, 0.0)])) \u2248 4.7124 atol = 0.001\n    @test area(Polygon(pi, [p2a, p3a, Point(0.0, 270.001), Point(-89.99, 0.0)])) \u2248 2*\u03c0 atol = 0.001\n    \n    #concave polygon\n    p1 = Point(64.0, 27.0)\n    p2 = Point(47.0, 0.0)\n    p3 = Point(42.0, 25.0)\n    p4 = intermediate_point(p2,p3,0.33)\n    p5 = Point(52.0, 16.0)\n    p6 = intermediate_point(p2,p3,0.67)\n    p7 = Point(55.0, -7.0)\n    p8 = intermediate_point(p2,p1,0.33)\n    p9 = Point(62.0, 4.0)\n    p10 = intermediate_point(p2,p1,0.67)\n    p11 = Point(56.0, 21.0)\n\n    ## triangle areas\n    at1 = area(p1,p2,p3)\n    at2 = area(p4,p5,p6)\n    at3 = area(p2,p7,p8)\n    at4 = area(p8,p9,p10)\n\n    ## area polygon\n    expected_area_polygon = at1-at2+at3+at4\n\n    polygon_complex_clockwise = Polygon(p11, [p1,p3,p6,p5,p4,p2,p7,p8,p9,p10])\n    polygon_complex_counterclockwise = Polygon(p11, [p10,p9,p8,p7,p2,p4,p5,p6,p3,p1])\n\n    @test area(polygon_complex_clockwise) \u2248 expected_area_polygon atol = 0.001\n    @test area(polygon_complex_counterclockwise) \u2248 expected_area_polygon atol = 0.001\nend", "meta": {"hexsha": "0929b8d3b21f0ee6d4fab4e2b7d172cfd083398b", "size": 1718, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 33.6862745098, "max_line_length": 107, "alphanum_fraction": 0.621653085, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7758105340302065}}
{"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 \u03c7(k) = \u03c7(|i-j|) = \u27e8x\u1d62x\u2c7c\u27e9 - \u27e8x\u1d62\u27e9\u27e8x\u2c7c\u27e9\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        # \u0305x\u1d62\u208a\u2081 = \u0305x\u1d62 + (x\u1d62\u208a\u2081 - \u0305x\u1d62) / (N+1)\n        # \u0305y\u1d62\u208a\u2081 = \u0305y\u1d62 + (y\u1d62\u208a\u2081 - \u0305y\u1d62) / (N+1)\n        # \u03c7\u1d62\u208a\u2081 = \u03c7\u1d62 + [(x\u1d62\u208a\u2081 - \u0305x\u1d62)(y\u1d62\u208a\u2081 - \u0305y\u1d62\u208a\u2081) - \u03c7\u1d62] / (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 `\u03c4 = \u2211\u2096 (1 - k/N) \u03c7\u2096/\u03c7\u2080` from a sample using the \ncorrelation function `\u03c7\u2096 = \u27e8x\u1d62 x\u1d62\u208a\u2096\u27e9 - \u27e8x\u1d62\u27e9\u27e8x\u1d62\u208a\u2096\u27e9` where x are values in the sample.\n\nNote that by default this function truncated the sum over k if \n`v / \u03c4 < 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": "using Pkg\nPkg.activate(pwd())\n\n# # Unconstrained Optimization\n# ## Visualization of gradients\n# \n# ### Exercise: Contour plot\n# Write a function `g(x)` which computes the derivative of `f` at a point  `x`.\n# Plot the contours of `f` on the domain. \n#  \n# **Hint:** Use the optional argument `color = :jet` for better visualization.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Computation of gradients\n# \n# ### Exercise: Finite difference approximation\n# Write a function `finite_difference` which computes the approximation of $f'(x)$ by\n# finite differences. The inputs are a function $f:\\mathbb R\\to\\mathbb R$ and a point\n# $x \\in \\mathbb{R}$. It should have an optional input $h \\in \\mathbb{R}$, for which\n# you need to choose a reasonable value.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ### Exercise: Finite difference approximation\n# Fix a point $x = (-2,-1)$. For a proper discretization of $h \\in [10^{-15}, 10^{-1}]$\n# compute the finite difference approximation of the partial derivative of $f$ with \n# respect to the second variable.\n# \n# Plot the dependence of this approximation on $h$. Add the true derivative computed\n# from $g$.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n\nx = 1;\nh = 1e-13;\n(x+h)^2 - x^2\n2*x*h + h^2\n\n# ### Exercise: Direction of gradients\n# Plot the contours of $f$ and its gradient at $(-2,-1)$.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Numerical Methods\n# ### Gradient Descent\n# \n# ### Exercise: Gradient descent\n# Implement function `optim`, which takes as inputs function $f$, its gradient,\n# starting point $x^0$ and fixed stepsize $\\alpha$ and runs the gradient descent.\n# Its output should be the first 100 iterations.\n# \n# This example is rather artificial because usually only the last iteration is returned\n# and some stopping criterion is employed instead of the fixed number of iterations.\n# We want to get all iterations to make visualizations.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\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: Gradient descent\n# Use the implementation of the gradient descent to minimize the function\n# $$\n# f(x) = \\sin(x_1 + x_2) + \\cos(x_1)^2\n# $$\n# from the starting point $x^0 = (0,-1)$. Use the constant stepsize $\\alpha = 0.1$. \n# Store all iterations into matrix $xs$.\n# \n# Use the `create_anim` function to plot the iteration into a gif file.\n# \n# Use one line of code to evaluate the function values for all iterations $xs$ and plot \n# these function values.\n# \n# **Hint:** to evaluate all $xs$ in one line, use iterate either via `eachcol(xs)` or\n# `eachrow(xs)`.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# $\\alpha = 0.01$\n\nx_gd = optim([], g, [0; -1], 0.01)\ncreate_anim(f, x_gd, xlims, ylims, joinpath(pwd(), \"lecture_08\", \"anim2.gif\"))\n\n# $\\alpha = 1$\n\nx_gd = optim([], g, [0; -1], 1)\ncreate_anim(f, x_gd, xlims, ylims, joinpath(pwd(), \"lecture_08\", \"anim3.gif\"))\n\n# ### Adaptive Stepsize\n\nabstract type Step end\n\nstruct GD <: Step\n    \u03b1::Float64\nend\n\noptim_step(s::GD, f, g, x) = -s.\u03b1*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, joinpath(pwd(), \"lecture_08\", \"anim4.gif\"))\n\n# ### Exercise: Armijo condition\n# Implement the `Armijo` subclass of the `Step` class. It should have two parameters \n# `c` from the definition and `\u03b1_max` which will be the initial value of $\\alpha$.\n# The value $\\alpha$ should be divided by two until the Armijo condition is satisfied.\n# \n# Then run the optimization with the Armijo stepsize selection and plot the animation.\n# \n# ---\n# ### Solution:\n", "meta": {"hexsha": "db33510a19e122cbce9ed7e8c33d18a1684fe49e", "size": 4702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_08/01-unconstrained.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/01-unconstrained.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/01-unconstrained.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": 24.7473684211, "max_line_length": 88, "alphanum_fraction": 0.6354742663, "num_tokens": 1400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.7757836063537965}}
{"text": "# ### Hisogram plot 2d\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\nx = randn(50000);\ny = x * 1.2 + randn(50000);\n\nplot(\n    x,\n    y,\n    seriestype = :histogram2d,\n    c = :vik,\n    nbins = 200,\n    show_empty_bins = :true\n)\n\n## equivalent\n## histogram2d(\n##     x,\n##     y,\n##     c = :vik,\n##     nbins = 200,\n##     show_empty_bins = :true\n## )\n", "meta": {"hexsha": "2e5107c1ee529e4cc50e98a2840683d08c42df7d", "size": 353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/histogram_2d.jl", "max_stars_repo_name": "goropikari/JuliaPlotsGallery.jl", "max_stars_repo_head_hexsha": "367fca5dbca42a90d1f28e3b5aae1652e3ce4f3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-22T08:40:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-22T08:40:34.000Z", "max_issues_repo_path": "site_generator/histogram_2d.jl", "max_issues_repo_name": "goropikari/JuliaPlotsGallery.jl", "max_issues_repo_head_hexsha": "367fca5dbca42a90d1f28e3b5aae1652e3ce4f3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "site_generator/histogram_2d.jl", "max_forks_repo_name": "goropikari/JuliaPlotsGallery.jl", "max_forks_repo_head_hexsha": "367fca5dbca42a90d1f28e3b5aae1652e3ce4f3b", "max_forks_repo_licenses": ["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.12, "max_line_length": 44, "alphanum_fraction": 0.5184135977, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8774767986961403, "lm_q1q2_score": 0.7757239535064975}}
{"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": "# This file includes the plugin for standard deviation of data\n\nusing Statistics \n\n\"\"\"\n    $TYPEDEF\n\nConstructs a `Std` plugin. The [`process(plg::Std, x)`](@ref) function takes the standard deviation of the input data `x`\nalong dimension `dims`.\n\n# Fields \n    \n    $TYPEDFIELDS\n\"\"\"\nstruct Std <: AbstractPlugin\n    \"Dimension\"\n    dims::Int\nend\nStd(;dims::Int=1) = Std(dims)\n\nshow(io::IO, plg::Std) = print(io, \"Mean(dims:$(plg.dims))\")\n\n\"\"\"\n    $SIGNATURES\n\nReturns the standard deviation of `x` along the dimension `plg.dims`.\n\n# Example \n```julia \njulia> x = collect(reshape(1:16, 4,4))\n4\u00d74 Array{Int64,2}:\n 1  5   9  13\n 2  6  10  14\n 3  7  11  15\n 4  8  12  16\n\njulia> plg = Plugins.Std(dims=1)\nMean(dims:1)\n\njulia> process(plg, x)\n1\u00d74 Array{Float64,2}:\n 1.29099  1.29099  1.29099  1.29099\n```\n\"\"\"\nprocess(plg::Std, x) = std(x, dims=plg.dims)\n", "meta": {"hexsha": "a1ae60de71b4088cf29f2076f254e701cd27b60c", "size": 850, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plugins/essentials/std.jl", "max_stars_repo_name": "zekeriyasari/Jusdl.jl", "max_stars_repo_head_hexsha": "57309ba672dfa5234c315e7bc8e09b6d43866133", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2020-02-16T17:13:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-21T04:43:59.000Z", "max_issues_repo_path": "src/plugins/essentials/std.jl", "max_issues_repo_name": "zekeriyasari/Causal.jl", "max_issues_repo_head_hexsha": "14de4c00488ae55463e75a3859dbc23df39bf07a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2020-08-24T07:48:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T07:07:21.000Z", "max_forks_repo_path": "src/plugins/essentials/std.jl", "max_forks_repo_name": "zekeriyasari/Causal.jl", "max_forks_repo_head_hexsha": "14de4c00488ae55463e75a3859dbc23df39bf07a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-09-01T18:08:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:33:06.000Z", "avg_line_length": 18.4782608696, "max_line_length": 121, "alphanum_fraction": 0.6411764706, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7756702650095217}}
{"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": "using Catalan\nusing Base.Test\n\n# catalan\n@test catalan(5) == 42\n@test catalan(30) == BigInt(\"3814986502092304\")\n\n# derangement\n@test derangement(4) == 9\n@test derangement(24) == BigInt(\"228250211305338670494289\")\n\n# doublefactorial\n@test doublefactorial(70) == BigInt(\"355044260642859198243475901411974413130137600000000\")\n\n# fibonacci\n@test fibonacci(5) == 5\n@test fibonacci(101) == BigInt(\"573147844013817084101\")\n\n# hyperfactorial\n@test hyperfactorial(8) == BigInt(\"55696437941726556979200000\")\n\n# lassalle\n@test lassalle(14) == BigInt(\"270316008395632253340\")\n\n# legendresymbol\n@test legendresymbol(1001,9907) == jacobisymbol(1001,9907)\n\n# lucas\n@test lucas(10) == 123\n@test lucas(100) == BigInt(\"792070839848372253127\")\n\n# multifactorial\n@test multifactorial(40,2) == doublefactorial(40)\n\n# multinomial\n@test multinomial(1,4,4,2) == 34650\n\n# primorial\n@test primorial(17) == 510510\n\n# stirlings1\n@test sum([abs(stirlings1(8, i)) for i = 0:8]) == factorial(8)\n\n# bell\n@test bell(7) == 877\n@test bell(42) == BigInt(\"35742549198872617291353508656626642567\")\n@test_throws bell(-1)\n\n# integer_partitions\n@test integer_partitions(5) == {[1, 1, 1, 1, 1], [2, 1, 1, 1], [2, 2, 1], [3, 1, 1], [3, 2], [4, 1], [5]}\n@test_throws integer_partitions(-1)\n\ninclude(\"youngdiagrams.jl\")\n", "meta": {"hexsha": "4324b0a9b9eb86e1ec48ed53f6d0b0f0cc0b261e", "size": 1275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Catalan_test.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Catalan.jl-a10504cf-72a7-53fd-8489-d9cc60862a4b", "max_stars_repo_head_hexsha": "02f6d749326a8d8f47316ed2fe4717b4294d891c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-30T02:14:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T18:24:22.000Z", "max_issues_repo_path": "test/Catalan_test.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Catalan.jl-a10504cf-72a7-53fd-8489-d9cc60862a4b", "max_issues_repo_head_hexsha": "02f6d749326a8d8f47316ed2fe4717b4294d891c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-03-13T21:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:33:15.000Z", "max_forks_repo_path": "test/Catalan_test.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Catalan.jl-a10504cf-72a7-53fd-8489-d9cc60862a4b", "max_forks_repo_head_hexsha": "02f6d749326a8d8f47316ed2fe4717b4294d891c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:12:24.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:26:49.000Z", "avg_line_length": 23.6111111111, "max_line_length": 105, "alphanum_fraction": 0.7152941176, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7756702647629343}}
{"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": "module exdiff\nusing SDE\nusing Diffusion\n\tprintln(\"euler\")\n\tprintln(quvar(euler(0, 1, (t,x)-> -5x, (t,x) -> 1, diff(linspace(0., 1.,1000)))))\n\n\tdt = diff(linspace(0., 0.5, 100))\n\tdw = dW1(dt)\n\n\tprintln(\"Brownian motion with drift\")\n\tprintln(\" sint(4 .. dt) + ito (8 .. dw)\")\n\tprintln((ito(4 .. dt) + ito(8 .. dw))[1:10])\n\n\tprintln(bracket(brown1(0, 2, 100))[1:10])\n\n\t#%discretization error of quadratic variation ?\n\ttic()\n\tprintln(\"Quadratic variation of B(0<t<2) = 2 \\u2248 \", mean([quvar(brown1(0, 2, 5)) for i in 1:100000]))\n\ttoc()\n\n\ttic()\n\tdt2 = diff(linspace(0., 2,5))\n\tprintln(\"Quadratic variation of B(0<t<2) = 2 \\u2248 \", mean([quvar(ito(dW1(dt2))) for i in 1:100000]))\n\ttoc()\n\n\tprintln(\"W_aug\")\n\tadw = aug(dw,dt,10)\n\tprintln(adw[1:10])\n\tprintln(\"W(t) - W_aug(t):\", sum(dw) - sum(adw))\n\tprintln(\"quvar(W, W_aug):\", quvar(ito(1 .. dw)), \" \", quvar(ito(1 .. adw)))\n\n\tdx = dW1(5,3)\n\tprintln(ito(dx .. dx)[end])\nend\n \n", "meta": {"hexsha": "d1069f22a7e42a1b59daa5a965785184ca935dae", "size": 921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/exdiff.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": "examples/exdiff.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": "examples/exdiff.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": 25.5833333333, "max_line_length": 105, "alphanum_fraction": 0.6004343105, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7756453296493361}}
{"text": "using SuiteSparseGraphBLAS\nfunction pagerank(\n    A,\n    d = reduce(Monoids.PLUS_MONOID, A; dims=2),\n    \u03b1 = 0.85,\n    maxiters = 100,\n    \u03f5 = 1.0e-4\n)\n    n = size(A, 1)\n    r = GBVector{Float32}(n)\n    t = GBVector{Float32}(n)\n    d[:, accum=BinaryOps.DIV] = \u03b1\n    r[:] = 1.0 / n\n    teleport = (1 - \u03b1) / n\n    rdiff = 1.0\n    i = 0\n    for outer i \u2208 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 <= \u03f5\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 \u2208 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 \u2208 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,\u03b1,\u03b2)\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] += \u03b1(t)/h^2\n        b[m] += \u03b2(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": "#the followng are all the activatoin functions avalible\nfunction sigmoid(x)  \n    return 1 ./ (1 + exp(-x))\n end\n \n function hardlim(x)\n     if x <0 \n         return 0\n     else\n         return 1\n     end    \n end\n \n function linear(x)\n     return x\n end\n \n function LeakyReLU(x::Float64,alpha=0.3)\n \n     if x<0\n         return alpha*x\n     else\n         return x\n     end\n end\n \n function relu(x)\n     return maximum!(0,x)\n end\n \n function elu(x,alpha)\n     if z >= 0\n         z = x\n     else\n         alpha*(exp(z) -1)\n     end\n     return z \n end\n \n ", "meta": {"hexsha": "a333ca1818968c9b77889fd27ab400f2429a1414", "size": 554, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ELM/src/activation_fucntions.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/activation_fucntions.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/activation_fucntions.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": 13.85, "max_line_length": 55, "alphanum_fraction": 0.5288808664, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7756101169779481}}
{"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, \u03b3 = 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 + \u03b3*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": "using AssigmentProblem\nusing Test\n\n#test matrix\nm = [10  2 10 10 10 10;\n\t  1 10 10 10 10 10;\n\t 10 10  3 10 10 10;\n\t 10 10 10 10  5 10;\n\t 10 10 10  4 10 10;\n\t 10 10 10 10 10  6];\n\n#small matrix\nsm = rand(Int,2,2);\n\n#optimal combination\noc = [1,2,3,4,5,6];\n\n@testset \"AssigmentProblem.jl\" begin\n    println(\"Test Matrix\");\n    display(m);\n    println();\n    print(\"Possible combinations: \")\n    println(factorial(6));\n    println(\"Optimal Combination\");\n    println(oc);\n    println();\n    println(\"Brute Force Solution (test all the posible combinations)\");\t#Brute force\n    solve_with_brute_force(sm);\t\t#Precompiling\n    @time bfs = solve_with_brute_force(m)[1]; \t#Solve\n    @test bfs == oc \t#Test with optimal\n   \tprintln(bfs);   #Print\n    println();\t\n    println(\"Linear Programming Solution\");\t\t#Lineal programming\n    solve_with_lineal_programming(sm); \t\t#precompiling\n    @time lps = solve_with_lineal_programming(m)[1];\t#solve\n    @test lps == oc\t\t#Test with optimal\n    println(lps);\n    println();\n\n\nend\n\n", "meta": {"hexsha": "60f4d3c40ed6329f15c5f9b5af1b8ea909fc6ec6", "size": 1014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 23.5813953488, "max_line_length": 85, "alphanum_fraction": 0.6518737673, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782468, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7755522488016695}}
{"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        \u03a3 = Symmetric(X * X')\n        \n        println(\"Dimension of \u03a3 : \", size(\u03a3))\n        println(\"Any missing data? \", any(isnan.(\u03a3))) \n\n        if any(isnan.(\u03a3))\n            throw(ErrorException(\"Data contains NaN!\"))\n        end        \n\n        @time F = eigen(\u03a3)\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 = 5 # rand(2:10)\n\nA = matrixdepot(\"wilkinson\", n)\n\n@test A == matrixdepot(\"wilkinson\", Float64, n)\n\n@test issymmetric(Matrix(A))\n\n@test diag(Matrix(A),1) \u2248 ones(Float64, n - 1)\n\n# symmetric along antidiagonal\n@test issymmetric(Matrix(A)[n:-1:1,:])\n\n\u03b8 = matrixdepot(\"wilkinson\", 1)\n\nprintln(\"'wilkinson' passed test...\")\n\n\n", "meta": {"hexsha": "d666140732dac830af6054ec7285056cc9b137c1", "size": 324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_wilkinson.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_wilkinson.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_wilkinson.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-02-19T22:47:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:02:00.000Z", "avg_line_length": 17.0526315789, "max_line_length": 47, "alphanum_fraction": 0.6604938272, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361700013355, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.77554444932996}}
{"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": "# ---\n# title: 313. Super Ugly Number\n# id: problem313\n# author: Tian Jun\n# date: 2020-10-31\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` \u2264 100, 0 < `n` \u2264 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\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "97b15e32ecbe1a247c5c53598263f64961345514", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/313.super-ugly-number.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/313.super-ugly-number.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/unresolved/313.super-ugly-number.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": 26.1538461538, "max_line_length": 83, "alphanum_fraction": 0.6156862745, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.7754582766267941}}
{"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# \u2227 = & for and\n# \u2228 = | for or\n# \u22bb = for xor\n# \u25b7 = >> for shift right\n# \u25c1 = << for shift left\n# \u2308x\u2309 = ceil(x)\n# \u230ax\u230b = 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) \u22bb 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\u230a(i-1)/2\u230b) = 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) \u22bb hi_d(i, n)\n\"\"\"\nhi_f(i, n) = hi_e(one(i)<<n - one(i) - i) \u22bb (one(i)<<(n-1))\n# hi_f(i, n) = hi_e(i) \u22bb hi_d(i, n)\n#hi_f(i, n) = hi_e(i) \u22bb (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 \u22bb 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) \u22bb 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 \u22bb (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 \u22bb= one(e) << (n - 1)\n        else\n            e \u22bb= 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 \u22bb= (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 \u22bb= (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 \u22bb 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 \u22bb 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\u22c5m\u207b\u00b2\u22c5day\u207b\u00b9 immigration rate of bream\nconst ip = 2e-5; # g\u22c5m\u207b\u00b2\u22c5day\u207b\u00b9 immigration rate of pike\nconst r = 7.5e-3; # day\u207b\u00b9 maximum growth rate of bream\nconst H\u2081 = 0.5; # half saturation constant\nconst H\u2082 = 10; # % half saturation constant\nconst H\u2083 = 20; # g\u22c5m\u207b\u00b2 half saturation constant\nconst H\u2084 = 15; # g\u22c5m\u207b\u00b2 half saturation constant\nconst cb = 7.5e-5; # m\u207b\u00b2\u22c5g\u207b\u00b9\u22c5day\u207b\u00b9 intraspecific competition constant for bream\nconst cp = 2.75e-4; # m\u207b\u00b2\u22c5g\u207b\u00b9\u22c5day\u207b\u00b9 intraspecific competition constant for pike\nconst prmax = 5e-2; # day\u207b\u00b9 maximum predation rate of pike\nconst ce = 0.1; # pike food conversion efficiency to growth\nconst mp = 2.25e-3; # day\u207b\u00b9 mortality rate of pike\nconst K = 100; # % maximum vetetation coverage\n\nfunction scheffer!(du,u,p,t)\n    B, P = u # g\u22c5m\u207b\u00b2 bream/pike density\n    ib, r, nutr, H\u2081, H\u2082, H\u2083, H\u2084, cb, prmax, ip, ce, mp, cp, K = p\n\n    V = K*(H\u2083^2/(H\u2083^2 + B^2)); # % of lake covered vetetation\n    FR = B^2/(B^2 + H\u2084^2); # fuctional response of pike\n\n    du[1] = dB = ib + r*(nutr/(nutr + H\u2081))*B - cb*B^2 - prmax*FR*P\n    du[2] = dP = ip + ce*prmax*FR*P*(V/(V + H\u2082)) - 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\u2081, H\u2082, H\u2083, H\u2084, 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\u2084^2); # fuctional response of pike\n\n    ib + r*(nutr/(nutr + H\u2081))*B - cb*B^2 - prmax*FR*P\nend\n\nfunction dP(B, P)\n    V = K*(H\u2083^2/(H\u2083^2 + B^2)); # % of lake covered vetetation\n    FR = B^2/(B^2 + H\u2084^2); # fuctional response of pike\n\n    ip + ce*prmax*FR*P*(V/(V + H\u2082)) - 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(\u03bb, D)\n\nConvert Laplace eigenvalue to length scale.\n\"\"\"\neig2length(\u03bb, D) = \u03bb > 0 ? \u03c0 * \u221a(D / \u03bb) : Inf\n\n\"\"\"\n    length2eig(length, D)\n\nConvert length scale to Laplace eigenvalue.\n\"\"\"\nlength2eig(length, D) = D * (\u03c0 / 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    \u03a3_c = Array{Float64}(undef,M,M)\n    BLAS.blascopy!(length(\u03a3_c), XTX, stride(XTX,1), \u03a3_c, stride(\u03a3_c,1))\n    BLAS.scal!(1.0/var_e, \u03a3_c)\n    for i in 1:M; \u03a3_c[i,i] += 1.0/var_c[i]; end\n    C = cholesky!(Symmetric(\u03a3_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    \u03a3_c = Array{Float64}(undef,M,M)\n    BLAS.blascopy!(length(\u03a3_c), XTX, stride(XTX,1), \u03a3_c, stride(\u03a3_c,1))\n    BLAS.scal!(1.0/var_e, \u03a3_c)\n    for i in 1:M; \u03a3_c[i,i] += 1.0/var_c[i]; end\n    C = cholesky!(Symmetric(\u03a3_c))\n    \u03a3_c = C \\ I(M)\n    \u03bc_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*\u03c0)\n    lml -= 0.5/var_e*y'*(y-X*\u03bc_c)\n    grad[1:M] .= 0.5*(\u03bc_c.^2 .+ diag(\u03a3_c) .- var_c)./var_c.^2\n    grad[M+1] = 0.5/var_e^2*(sum((y-X*\u03bc_c).^2) + dot(XTX,\u03a3_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    \u03a3_y = X*Diagonal(var_c)*X'\n    for i=1:N; \u03a3_y[i,i] += var_e; end\n    C = cholesky!(Symmetric(\u03a3_y))\n    inv\u03a3y_y = C \\ y\n    lml = -0.5*y'*inv\u03a3y_y - 0.5*logdet(C) - 0.5*N*log(2*\u03c0)\n    grad[1:M] .= 0.5*(X'*inv\u03a3y_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\u03a3y_y,inv\u03a3y_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) \u2265 degree(g) \n        h = Polynomial( (leading(f) \u00f7 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\u00f7(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": "###\n  Name     : c7_20_JuMP01.jl\n  Book     : Hands-on Data Science with Anaconda )\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan and James Yan\n  Date     : 3/15/2018\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n###\n\n\nusing JuMP\nusing ECOS\nm= Model(solver =ECOSSolver())\n@variable(m, 0 <= x <= 2 )\n@variable(m, 0 <= y <= 30 )\n@setObjective(m, Max, 5x + 3*y )\n@addConstraint(m, 1x + 5y <= 3.0 )\nprint(m)\nstatus = solve(m)\nprintln(\"Objective value: \", getObjectiveValue(m))\nprintln(\"x = \", getValue(x))\nprintln(\"y = \", getValue(y))\n\n\n#https://jump.readthedocs.io/en/release-0.2/jump.html", "meta": {"hexsha": "7a8b8c1db9857c5543c2f84e60fa15b22e3ddeda", "size": 618, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter07/c7_20_JuMP01.jl", "max_stars_repo_name": "andrewjcoxon/Hands-On-Data-Science-with-Anaconda", "max_stars_repo_head_hexsha": "82504a059ecd284b3599fa9af2b3eb6bbd6e28f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-06-25T16:21:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T09:28:29.000Z", "max_issues_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter07/c7_20_JuMP01.jl", "max_issues_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_issues_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter07/c7_20_JuMP01.jl", "max_forks_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_forks_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-06-15T02:55:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T15:24:42.000Z", "avg_line_length": 23.7692307692, "max_line_length": 53, "alphanum_fraction": 0.6310679612, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7754561581118539}}
{"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 \u201crisk\u201d 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 \u201crisk\u201d in our investment.\r\n#' Markowitz, in his Nobel prize winning work, showed that a rational investor\u2019s 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\u00e9jols, G., Pe\u00f1a, J., & T\u00fct\u00fcnc\u00fc, 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(\ud835\udc9e(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 \u2218 Composition, X, dims=2)\n\nfunction revertmatrix(::ILR, Y)\n  D = size(Y, 2)\n  f = components \u2218 ilrinv \u2218 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\u2032, x\u2080; maxiter = 100, tol = 1e-8)\nFind `f`s root via Newton's method.\n\"\"\"\nfunction newton(f, f\u2032, x\u2080; maxiter = 100, tol = 1e-8)\n    x\u2099\u208a\u2081 = x\u2080\n    x\u2099 = NaN\n    iter = 0\n    while true\n        f\u2093\u208a\u2081 = f(x\u2099\u208a\u2081)\n        f\u2093 = f(x\u2099)\n        if abs(f\u2093\u208a\u2081 - f\u2093) < tol\n            return x\u2099\u208a\u2081\n        end\n        if iter > maxiter\n            error(\"Did not converge!\")\n        end\n\n        f\u2032\u2099\u208a\u2081 = f\u2032(x\u2099\u208a\u2081)\n        if f\u2032\u2099\u208a\u2081 == 0.0\n            error(\"Derivative is zero!\")\n        end\n        x\u2099\u208a\u2081, x\u2099 = x\u2099\u208a\u2081 - f\u2093\u208a\u2081/f\u2032\u2099\u208a\u2081, x\u2099\u208a\u2081\n        iter += 1\n    end\nend\n\nnewton(f, x\u2080; maxiter = 100, tol = 1e-8) =\n    newton(f, x -> ForwardDiff.derivative(f, x), x\u2080; 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 \u03b2 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\u2013116, 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 \u2229 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 \u2229 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 \u2229 Interval(0.0,two_pi.hi)\n        x_new = x \u2229 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 \u2229 Interval(-half_pi.hi, half_pi.hi)\n        x_new = x \u2229 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": "# 1D diffusion problem\n\n# Packages and inclusions\nusing ModelingToolkit, MethodOfLines, LinearAlgebra, Test\nusing ModelingToolkit: Differential\nusing NonlinearSolve\nusing DomainSets\n\n\n# Handrolled discrete laplace problem\n@testset \"Hand rolled 1D Laplace\" begin\n    @variables a b c d\n    eqs = [0 ~ a - 1,\n        0 ~ a + c - 2 * b,\n        0 ~ b + d - 2 * c,\n        0 ~ d - 1]\n    @named ns = NonlinearSystem(eqs, [a, b, c, d], [])\n    f = eval(generate_function(ns, [a, b, c, d])[2])\n    prob = NonlinearProblem(ns, zeros(4), [])\n    sol = NonlinearSolve.solve(prob, NewtonRaphson())\n\n    @test sol.u \u2248 ones(4)\nend\n\n# Laplace's Equation, same as above but with MOL discretization\n@testset \"1D Laplace - constant solution\" begin\n    @parameters x\n    @variables u(..)\n    Dxx = Differential(x)^2\n\n    eq = Dxx(u(x)) ~ 0\n    dx = 1 / 3\n\n    bcs = [u(0) ~ 1,\n        u(1) ~ 1]\n\n    # Space and time domains\n    domains = [x \u2208 Interval(0.0, 1.0)]\n\n    @named pdesys = PDESystem([eq], bcs, domains, [x], [u(x)])\n    discretization = MOLFiniteDifference([x => dx], nothing, approx_order=2)\n    prob = discretize(pdesys, discretization)\n    grid = get_discrete(pdesys, discretization)\n    sol = NonlinearSolve.solve(prob, NewtonRaphson())\n    sol\u2032 = map(d -> sol[d], grid[u(x)])\n    @test sol\u2032 \u2248 ones(4)\nend\n\n# Laplace's Equation, linear solution\n@testset \"1D Laplace - linear solution\" begin\n    @parameters x\n    @variables u(..)\n    Dxx = Differential(x)^2\n\n    eq = Dxx(u(x)) ~ 0\n    dx = 0.1\n\n    bcs = [u(0) ~ 1,\n        u(1) ~ 2]\n\n    # Space and time domains\n    domains = [x \u2208 Interval(0.0, 1.0)]\n\n    @named pdesys = PDESystem([eq], bcs, domains, [x], [u(x)])\n    discretization = MOLFiniteDifference([x => dx], nothing, approx_order=2)\n    grid = get_discrete(pdesys, discretization)\n\n    prob = discretize(pdesys, discretization)\n    sol = NonlinearSolve.solve(prob, NewtonRaphson())\n    sol\u2032 = map(d -> sol[d], grid[u(x)])\n\n\n    @test sol\u2032 \u2248 1.0:0.1:2.0\nend\n\n# 2D heat\n@testset \"2D heat equation\" begin\n    @parameters x y\n    @variables u(..)\n    Dxx = Differential(x)^2\n    Dyy = Differential(y)^2\n\n    eq = Dxx(u(x, y)) + Dyy(u(x, y)) ~ 0\n    dx = 0.1\n    dy = 0.1\n\n    bcs = [u(0, y) ~ x * y,\n        u(1, y) ~ x * y,\n        u(x, 0) ~ x * y,\n        u(x, 1) ~ x * y]\n\n\n    # Space and time domains\n    domains = [x \u2208 Interval(0.0, 1.0),\n        y \u2208 Interval(0.0, 1.0)]\n\n    @named pdesys = PDESystem([eq], bcs, domains, [x, y], [u(x, y)])\n\n    # Note that we pass in `nothing` for the time variable `t` here since we\n    # are creating a stationary problem without a dependence on time, only space.\n    discretization = MOLFiniteDifference([x => dx, y => dy], nothing, approx_order=2)\n\n    prob = discretize(pdesys, discretization)\n    grid = get_discrete(pdesys, discretization)\n    sol = NonlinearSolve.solve(prob, NewtonRaphson())\n    xs, ys = [infimum(d.domain):dx:supremum(d.domain) for d in domains]\n    u_sol = map(d -> sol[d], grid[u(x, y)])\n\n    # test boundary\n    @test all(abs.(u_sol[:, 1]) .< eps(Float32))\n    @test all(abs.(u_sol[1, :]) .< eps(Float32))\n    @test u_sol[2:end-1, end] \u2248 (0.0:dy:1.0)[2:end-1]\n    @test u_sol[end, 2:end-1] \u2248 (0.0:dx:1.0)[2:end-1]\n\n    # test interior with finite differences\n    interior = CartesianIndices((axes(xs)[1], axes(ys)[1]))[2:end-1, 2:end-1]\n    fd = map(interior) do I\n        abs(u_sol[(I-CartesianIndex(1, 0))] + u_sol[(I+CartesianIndex(1, 0))] - 2 * u_sol[I]) < 0.01\n    end#\n    @test all(fd)\nend\n", "meta": {"hexsha": "77fdbff01520f861bc1ba16a0e9bd6d7c4d49447", "size": 3475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pde_systems/MOL_NonlinearProblem.jl", "max_stars_repo_name": "SciML/MethodOfLines.jl", "max_stars_repo_head_hexsha": "60018ac8d4e52d27ea810d05687765fff5f983d4", "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/MOL_NonlinearProblem.jl", "max_issues_repo_name": "SciML/MethodOfLines.jl", "max_issues_repo_head_hexsha": "60018ac8d4e52d27ea810d05687765fff5f983d4", "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/MOL_NonlinearProblem.jl", "max_forks_repo_name": "SciML/MethodOfLines.jl", "max_forks_repo_head_hexsha": "60018ac8d4e52d27ea810d05687765fff5f983d4", "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": 28.4836065574, "max_line_length": 100, "alphanum_fraction": 0.5951079137, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7753737498649894}}
{"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 \u03b1.\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": "## 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##\nusing MatrixNetworks\nf,lam = fiedler_vector(A)\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=400,\n  markersize=2, linecolor=1, linealpha=0.2, linewidth=0.5,\n  markeralpha=0.3,\n  #colorbar=true,\n  marker_z=f,\n  axis_buffer=0.02, background=nothing)\n##\nsavefig(\"mnist-train-4-fiedler.png\")\n\n##\ncut = spectral_cut(A)\nx = zeros(n)\nx[cut.set] .= 1\ngraphplot(ei, ej, x =xy[:,1], y=xy[:,2],\n  markercolor=:black, markerstrokecolor=:white,\n  size=(1200,1200),dpi=400,\n  markersize=2, linecolor=1, linealpha=0.2, linewidth=0.5,\n  markeralpha=0.3,\n  #colorbar=true,\n  marker_z=x,\n  axis_buffer=0.02, background=nothing)\nfor i=1:100\n  annotate!(xy[i,1],xy[i,2],\"$(train_y[i])\",color=:white)\nend\n##\nsavefig(\"mnist-train-4-spectral-cut.png\")\n\n## Make a figure for the label 1\n# find the first 10 nodes labeled 1\nusing MLDatasets\ntrain_x, train_y = MNIST.traindata()\nnlabels = 10\nS = findall(train_y .== 1)[1:nlabels]\n## Show the labeled nodes.\nscatter(xy[:,1],xy[:,2])\nscatter!(xy[S,1], xy[S,2], markersize=25)\n##\n# Form the incidence matrix for the least squares problem\nfunction incidence_matrix(A)\n  ei,ej = findnz(triu(A,1))\n  n = size(A,1)\n  m = length(ei)\n  return sparse(1:m,ei,1,m,n) - sparse(1:m,ej,1,m,n)\nend\nB = incidence_matrix(A)\nIS = sparse(0.1*I, n,n)\nIS[S,S] .*= 1/maximum(IS)\nlabels = zeros(n)\nlabels[S] .= 1.0\n## solve the least squares problems\n#x = [B; IS] \\ [zeros(size(B,1)); 1]\nAtA = [B; IS]'* [B; IS]\nAtb = [B; IS]'* [zeros(size(B,1)); labels]\n##\nx = AtA\\Atb\n##\nscatter(xy[:,1],xy[:,2], marker_z = log10.(x), markerstrokewidth=0)\n\n## Show the labeled nodes.\nscatter(xy[:,1],xy[:,2],background=nothing,framestyle=:none,markersize=2,\n  size=(1200,1200),markerstrokewidth=0, alpha=0.5,dpi=300)\nscatter!(xy[S,1], xy[S,2], markersize=12)\nfor i in S\n  annotate!(xy[i,1],xy[i,2], \"$(train_y[i])\")\nend\nplot!(legend=false)\nsavefig(\"mnist-train-4-labels.png\")\n##\nscatter(xy[:,1],xy[:,2],background=nothing,framestyle=:none,markersize=2,\n  size=(1200,1200),markerstrokewidth=0, marker_z = log10.(x),\n  colorbar=false, alpha=0.5,dpi=300,label=\"\")\nsavefig(\"mnist-train-4-soln.png\")\n", "meta": {"hexsha": "c5b5e4903869678afa44dfd40f1d428314501863", "size": 2406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5-unit-4-demos/mnist-graph-intro-figures.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/mnist-graph-intro-figures.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/mnist-graph-intro-figures.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": 27.0337078652, "max_line_length": 73, "alphanum_fraction": 0.6741479634, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7753450261531742}}
{"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\u03f5 = eps(typeof(float(t)))\n\t\u03f53 = 0.5*\u03f5^(1/3)\n\tif t < \u03f53\n\t\t\u03c4 = (-1.5*z(t) + 2*z(t+\u03f53) - 0.5*z(t+2\u03f53)) / \u03f53\n\telseif t > 1-\u03f53\n\t\t\u03c4 = (1.5*z(t) - 2*z(t-\u03f53) + 0.5*z(t-2\u03f53)) / \u03f53\n\telse\n\t\t\u03c4 = (z(t+\u03f53) - z(t-\u03f53)) / (2\u03f53)\n\tend\n\treturn \u03c4\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,\u03c4l,\u03c4r,maxdz,d=depth)\t\t\n\t\tdzkap = dist(\u03c4r,\u03c4l)  # approximately, the stepsize over radius of curvature\n\t\ttm = (tl+tr)/2\n\t\tzm = point(tm)\n\t\t\u03c4m = utangent(tm) \n\t\tif d > 0 && (dzkap > curvemax || dist(zr,zl) > maxdz )\n\t\t\tzl = refine(tl,tm,zl,zm,\u03c4l,\u03c4m,maxdz,d-1)\n\t\t\tzr = refine(tm,tr,zm,zr,\u03c4m,\u03c4r,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\u03c4 = 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],\u03c4[j],\u03c4[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# \u2554\u2550\u2561 de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, StatsBase, DataFrames\n\tRandom.seed!(1)\nend\n\n# \u2554\u2550\u2561 ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.7\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6285dea2-1ee5-11eb-2b6a-f9906c0d3351\nmd\"## End of listing 2.7\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# \u2560\u2550de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# \u2560\u2550e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# \u2560\u2550c4bef1a4-1ee9-11eb-0b58-8be033f6fbad\n# \u2560\u255023c4c304-1eea-11eb-2a57-d9b2e99a3253\n# \u255f\u25006285dea2-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|\u00b2.\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\u03bb = c/transmit_frequency_hz;\n\t\u03931 = -1;\n\t\u03932 = -0.6;\n\n\tF\u00b2( \u0393 ) = RadioPropagation.two_ray_propagation.( target_range_m, transmit_height_m, receive_height_m, transmit_frequency_hz, \u0393 );\n\n\tF\u00b21 = F\u00b2( \u03931 );\n\tF\u00b22 = F\u00b2( \u03932 );\n\n\tf\u2074_db( F\u00b2 ) = 10*log10.( abs2.( F\u00b2 ));\n\n\tfreespace_loss_db = 10 .*log10.(\u03bb^2 ./( (4*\u03c0)^3 .*target_range_m .^4 ));\n\tbias = freespace_loss_db[1]\n\n\n\tplot1 = plot( \ttarget_range_m, f\u2074_db.(F\u00b21)+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|\u2074+L, \u0393=-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\u2074_db.(F\u00b22)+freespace_loss_db .-bias,\n\t \t\tlabel = \"|F|\u2074+L, \u0393=-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- '\u0393'                           The reflection coefficient of the medium of the plane earth.\n\t\"\"\"\n\tfunction two_ray_propagation( distance, transmit_height, receive_height, frequency_hz, \u0393 )\n\t\t\u03bb = c/frequency_hz;\n\t\t\u0394\u03d5=  4*\u03c0*transmit_height*receive_height/(\u03bb*distance);\n\t\tF = 1+abs(\u0393)*exp(i*\u0394\u03d5);\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\u03b1 = a*r^b;\n\t\treturn \u03b1;\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\u03b1_lin( pol ) = rain_attenuation_db_per_km( pol, frequency_ghz, fall_rate_mm_hour );\n\t\t\u03b1v = \u03b1_lin('v');\n\t\t\u03b1h = \u03b1_lin('h');\n\t\t\n\t\t\u03b1 = 1/sqrt(2) * sqrt(\u03b1v^2+\u03b1h^2);\n\n\t\treturn \u03b1;\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\u00b3.\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\u03b1= M*( -1.347 + 0.66*f+(11.152/f) - 0.022*T )\n\t\treturn \u03b1;\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\u00b3' \tThe water vapur density in g/m\u00b3.\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\u00b3=7.5, dry_air_pressure_h_pa=1013.25 )\n\t\tf = frequency_ghz;\n\t\tT = T_kelvin;\n\t\t\u03c1 = water_vapour_density_g_m\u00b3;\n\t\tp = dry_air_pressure_h_pa;\t# Dry air pressure [hPa].\n\t\te = \u03c1*T/216.7;\t\t\t\t# Water vapour partial pressure [hPa].\n\t\t\u03b8 = 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*\u03b8^3*exp( a2*(1-\u03b8));\n\t\tS_w\t\t= @. b1*10^(-1)*e*\u03b8^3.5*exp(b2*(1-\u03b8));\n\t\t\n\t\t\u0394f_o_\t= @. a3*10^(-4) *(p*\u03b8^(0.8-a4) + 1.1*e*\u03b8);\n\t\t\u0394f_o\t= @. sqrt( \u0394f_o_^2 + 2.25*10^(-6) );\n\n\t\t\u0394f_w_\t= @. b3*10^(-4) *(p*\u03b8^b4 + b5*e*\u03b8^b6);\n\t\t\u0394f_w\t= @. 0.535*\u0394f_w_ + sqrt( 0.217*\u0394f_w_^2 + (2.1316*10^-12*f0b^2)/ \u03b8 );\n\n\t\t\u03b4_o\t\t= @. (a5+a6*\u03b8)*10^(-4) *(p+e)*\u03b8^(0.8);\n\t\t\u03b4_w\t\t= 0;\n\n\t\tF_o\t\t= @. f/f0a *( (\u0394f_o-\u03b4_o*(f0a-f))/((f0a-f)^2 + \u0394f_o^2 ) + (\u0394f_o-\u03b4_o*(f0a+f))/((f0a+f)^2 + \u0394f_o^2) );\n\t\tF_w\t\t= @. f/f0b *( (\u0394f_w-\u03b4_w*(f0b-f))/((f0b-f)^2 + \u0394f_w^2 ) + (\u0394f_w-\u03b4_w*(f0b+f))/((f0b+f)^2 + \u0394f_w^2) );\n\t\t\n\t\td\t\t= 5.6*10^(-4) * (p+e)*\u03b8^0.8;\n\t\t\n\t\tN_D_prime = f*p*\u03b8^2 * ( (6.14*10^(-5) / ( d*(1+(f/d)^2) )) +  (1.4*10^(-12) *p*\u03b8^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\u03b3 = 0.1820*f*(N_d_prime_oxygen+N_d_prime_water_vapour);\n\t\treturn \u03b3;\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# \u2554\u2550\u2561 7224ff21-b911-417d-b42c-b2aac200d930\nbegin\n\tusing PlutoUI\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250066ee80df-26f5-4d6b-8d2b-deba85ef5a2e\n# \u255f\u2500025f1c63-7f8e-4b8c-b470-b35f86f19901\n# \u255f\u25001da07d3d-3dd5-48e8-a679-fbeef8128091\n# \u255f\u250051c6ff9c-dc99-422d-83d4-fece9bb0068d\n# \u255f\u25006d1b3eb5-6f2b-48c6-b8dd-73fbf6c38130\n# \u255f\u25009917ccf9-1503-4dd9-9bd7-c9a28e9ef7a6\n# \u255f\u250095d7109f-314d-4851-ac59-4bf059626d24\n# \u255f\u2500646ceac0-b72c-4b87-a3a1-0888d9bd4a83\n# \u255f\u2500a3ed9688-4459-4270-856d-bfb9bcd9a562\n# \u255f\u25009ec579ae-059a-46e3-b73c-089271a4b83f\n# \u255f\u25004ed2f1f8-1249-4679-b93b-a54684163729\n# \u255f\u25005aef28d5-8ffd-45f9-a547-6bb41e359bc0\n# \u255f\u2500392c63d4-75aa-4df1-b0fc-40702c8745b8\n# \u2560\u255047c88a48-5392-4b2f-abe6-8593657587bf\n# \u255f\u25007224ff21-b911-417d-b42c-b2aac200d930\n# \u255f\u2500c51953b1-d267-4206-879d-63a139d12afa\n# \u255f\u2500b481618c-13b7-4fd3-bf21-e736b6902fb9\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "using SchattenNorms\nusing Test\nusing LinearAlgebra\n\nimport Random\nimport LinearAlgebra\n\nRandom.seed!(31415926)\n\n@testset \"snorm sanity checks\" begin\n    @test isapprox(snorm([1 0; 0 -1]),sqrt(2.0))\n    @test isapprox(snorm([1 0; 0 -1],1.0),2.0)\n    @test isapprox(snorm([1 0; 0 -1],Inf),1.0)\nend\n\n@testset \"snorm\" begin\n    for i=1:100\n        for d=2:4\n            R = randn(d,d)\n            U = LinearAlgebra.svd(randn(d,d)).U\n            V = LinearAlgebra.svd(randn(d,d)).U\n            p = sort(abs.(randn(3)) .+ 1.0)\n            @test isapprox(snorm(R),snorm(R,2.0))\n            @test isapprox(snorm(U*R*V,1),snorm(R,1))\n            @test isapprox(snorm(U*R*V),snorm(R,2.0))\n            @test isapprox(snorm(U*R*V,Inf),snorm(R,Inf))\n            @test isapprox(snorm(U*R*V,p[1]),snorm(R,p[1]))\n            @test snorm(R,1) >= snorm(R,2) >= snorm(R,Inf)\n            @test snorm(R,p[1]) >= snorm(R,p[2]) >= snorm(R,p[3])\n            @test snorm(R,1.0) == snorm(R,1) == trnorm(R) == nucnorm(R)\n        end\n    end\nend\n\n# E\n# U,V\n# @test isapprox(cbnorm(E),dnorm(E'))\n# @test isapprox(cbnorm(E),cbnorm(U*E*V))\n# @test isapprox(dnorm(E),dnorm(U*E*V))\n\ninclude(\"test-dnorm.jl\")\n", "meta": {"hexsha": "c42074d4b5f811a7cc8c10e4daf441639f3b8933", "size": 1175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SchattenNorms.jl-03bc5d91-8e1a-555a-857b-eaff090ecb7c", "max_stars_repo_head_hexsha": "189bc807cea38c7c35ac2d7cd3c637f8aaf9f2a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-03-09T21:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:58:48.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SchattenNorms.jl-03bc5d91-8e1a-555a-857b-eaff090ecb7c", "max_issues_repo_head_hexsha": "189bc807cea38c7c35ac2d7cd3c637f8aaf9f2a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-11-20T21:33:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T16:54:30.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SchattenNorms.jl-03bc5d91-8e1a-555a-857b-eaff090ecb7c", "max_forks_repo_head_hexsha": "189bc807cea38c7c35ac2d7cd3c637f8aaf9f2a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-03-15T06:46:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:58:50.000Z", "avg_line_length": 27.9761904762, "max_line_length": 71, "alphanum_fraction": 0.5540425532, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7751978265198409}}
{"text": "function f2(x)\n  x[1]^2 + (2.0 - x[2])^2\nend\nfunction g2(x, storage)\n  storage[1] = 2.0 * x[1]\n  storage[2] = -2.0 * (2.0 - x[2])\nend\nd2 = DifferentiableFunction(f2, g2)\ninitial_x = [100.0, 100.0]\n\nresults = Optim.bfgs(d2, initial_x)\n@assert length(results.trace.states) == 0\n@assert results.converged\n@assert norm(results.minimum - [0.0, 2.0]) < 0.01\n", "meta": {"hexsha": "a7c11862daad602f6e6411d34e0ad5e3309bb18a", "size": 352, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bfgs.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/bfgs.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/bfgs.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": 23.4666666667, "max_line_length": 49, "alphanum_fraction": 0.6392045455, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7751978257773489}}
{"text": "# Test of Min-Cut and maximum adjacency visit\n\nusing LightGraphs\nusing Base.Test\n\ng = Graph(8)\n\n# Original example by Stoer\n\nwedges = [\n    (1, 2, 2.),\n    (1, 5, 3.),\n    (2, 3, 3.),\n    (2, 5, 2.),\n    (2, 6, 2.),\n    (3, 4, 4.),\n    (3, 7, 2.),\n    (4, 7, 2.),\n    (4, 8, 2.),\n    (5, 6, 3.),\n    (6, 7, 1.),\n    (7, 8, 3.) ]\n\n\nm = length(wedges)\neweights = spzeros(nv(g),nv(g))\n\nfor (s, d, w) in wedges\n    add_edge!(g, s, d)\n    eweights[s, d] = w\n    eweights[d, s] = w\nend\n\n@test nv(g) == 8\n@test ne(g) == m\n\nparity, bestcut = mincut(g, eweights)\n\n@test length(parity) == 8\n@test parity == [2, 2, 1, 1, 2, 2, 1, 1]\n@test bestcut == 4.0\n\nparity, bestcut = mincut(g)\n\n@test length(parity) == 8\n@test parity == [2, 1, 1, 1, 1, 1, 1, 1]\n@test bestcut == 2.0\n\nv = maximum_adjacency_visit(g)\n\n@test v == Vector{Int64}([1, 2, 5, 6, 3, 7, 4, 8])\n", "meta": {"hexsha": "f79d9dde4db253aa7c6231d0500124fde0793762", "size": 845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/traversals/maxadjvisit.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": "test/traversals/maxadjvisit.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": "test/traversals/maxadjvisit.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": 16.25, "max_line_length": 50, "alphanum_fraction": 0.5076923077, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.775197824067204}}
{"text": "@testset \"azimuth.jl\" begin\n    p1 = rad2deg(Point(0.5, 1.0))\n    p2 = rad2deg(Point(1.0, 0.5))\n    p3 = rad2deg(Point(0.6, 1.0))  # above p1\n\n    rs = Arc(p1,p2)\n    @test azimuth(p1, p2) \u2248 rad2deg(5.81412807071) atol = 0.001\n    @test azimuth(rs) \u2248 rad2deg(5.81412807071) atol = 0.001\n    @test azimuth(p3, p1) \u2248 180.0 atol = 0.001\n\n    @test final_azimuth(p1, p2) \u2248 rad2deg(5.45864813531) atol = 0.001\n    @test final_azimuth(rs) \u2248 rad2deg(5.45864813531) atol = 0.001\n\n    angular_distance_x = 34.49\n    angular_distance_y = 28.11\n    angular_distance_z = 29.0\n    \n    @test spherical_angle(angular_distance_z, angular_distance_y, angular_distance_x) \u2248 76.6 atol = 0.1\n    @test spherical_angle(angular_distance_x, angular_distance_z, angular_distance_y) \u2248 54.1 atol = 0.1\n    @test spherical_angle(angular_distance_y, angular_distance_x, angular_distance_z) \u2248 56.4 atol = 0.1\n\n    @test spherical_excess(angular_distance_z, angular_distance_y, angular_distance_x) \u2248 7.1 atol = 0.1\n\n    angular_distance_x2 = 35.0\n    angular_distance_y2 = 35.0\n    angular_distance_z2 = 0.1\n\n    @test spherical_angle(angular_distance_z2, angular_distance_y2, angular_distance_x2) \u2248 89.9 atol = 0.1\n    @test spherical_angle(angular_distance_x2, angular_distance_z2, angular_distance_y2) \u2248 89.9 atol = 0.1\n    @test spherical_angle(angular_distance_y2, angular_distance_x2, angular_distance_z2) \u2248 0.174 atol = 0.001\n\nend\n", "meta": {"hexsha": "c2111746a3af756799ecde8f93dab1bef2d9c033", "size": 1409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/angles.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": "test/angles.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": "test/angles.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": 42.696969697, "max_line_length": 109, "alphanum_fraction": 0.7189496097, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7751869516549256}}
{"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\u0302, y)\n\nReturn the mean squared error `sum((y\u0302 .- y).^2) / length(y)`. \n\"\"\"\nmse(y\u0302, y) = sum((y\u0302 .- y).^2) * 1 // length(y)\n\n\nfunction _crossentropy(y\u0302::AbstractVecOrMat, y::AbstractVecOrMat, weight::Nothing)\n  return -sum(y .* log.(y\u0302)) * 1 // size(y, 2)\nend\n\nfunction _crossentropy(y\u0302::AbstractVecOrMat, y::AbstractVecOrMat, weight::Number)\n  return -sum(y .* log.(y\u0302)) .* weight * 1 // size(y, 2)\nend\n\nfunction _crossentropy(y\u0302::AbstractVecOrMat, y::AbstractVecOrMat, weight::AbstractVector)\n  return -sum(y .* log.(y\u0302) .* weight) * 1 // size(y, 2)\nend\n\n\"\"\"\n    crossentropy(y\u0302, y; weight=1)\n\nReturn the crossentropy computed as `-sum(y .* log.(y\u0302) .* weight) / size(y, 2)`. \n\nSee also [`logitcrossentropy`](@ref), [`binarycrossentropy`](@ref).\n\"\"\"\ncrossentropy(y\u0302::AbstractVecOrMat, y::AbstractVecOrMat; weight=nothing) = _crossentropy(y\u0302, y, weight)\n\n\"\"\"\n    logitcrossentropy(y\u0302, y; weight=1)\n\nReturn the crossentropy computed after a [softmax](@ref) operation: \n\n  -sum(y .* logsoftmax(y\u0302) .* weight) / size(y, 2)\n\nSee also [`crossentropy`](@ref), [`binarycrossentropy`](@ref).\n\"\"\"\nfunction logitcrossentropy(y\u0302::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\n  return -sum(y .* logsoftmax(y\u0302) .* weight) * 1 // size(y, 2)\nend\n\n\"\"\"\n    binarycrossentropy(y\u0302, y; \u03f5=eps(y\u0302))\n\nReturn `-y*log(y\u0302 + \u03f5) - (1-y)*log(1-y\u0302 + \u03f5)`. The \u03f5 term provides numerical stability.\n\nTypically, the prediction `y\u0302` is given by the output of a [`sigmoid`](@ref) activation.\n\"\"\"\nbinarycrossentropy(y\u0302, y; \u03f5=eps(y\u0302)) = -y*log(y\u0302 + \u03f5) - (1 - y)*log(1 - y\u0302 + \u03f5)\n\n# Re-definition to fix interaction with CuArrays.\nCuArrays.@cufunc binarycrossentropy(y\u0302, y; \u03f5=eps(y\u0302)) = -y*log(y\u0302 + \u03f5) - (1 - y)*log(1 - y\u0302 + \u03f5)\n\n\"\"\"\n    logitbinarycrossentropy(\u0177, y)\n\n`logitbinarycrossentropy(\u0177, y)` is mathematically equivalent to `binarycrossentropy(\u03c3(\u0177), y)`\nbut it is more numerically stable.\n\nSee also [`binarycrossentropy`](@ref), [`sigmoid`](@ref), [`logsigmoid`](@ref).  \n\"\"\"\nlogitbinarycrossentropy(\u0177, y) = (1 - y)*\u0177 - log\u03c3(y\u0302)\n\n# Re-definition to fix interaction with CuArrays.\nCuArrays.@cufunc logitbinarycrossentropy(\u0177, y) = (1 - y)*\u0177 - log\u03c3(y\u0302)\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\u00d73 Array{Int64,2}:\n  1  4  7\n  2  5  8\n  3  6  9\n\njulia> normalise(a)\n3\u00d73 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\u00d73 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  \u03bc\u2032 = mean(x, dims = dims)\n  \u03c3\u2032 = std(x, dims = dims, mean = \u03bc\u2032, corrected=false)\n  return (x .- \u03bc\u2032) ./ \u03c3\u2032\nend\n\n\"\"\"\n    kldivergence(y\u0302, 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\u0302, y)\n  entropy = sum(y .* log.(y)) *1 //size(y,2)\n  cross_entropy = crossentropy(y\u0302, y)\n  return entropy + cross_entropy\nend\n\n\"\"\"\n    poisson(y\u0302, 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\u0302, y) = sum(y\u0302 .- y .* log.(y\u0302)) *1 // size(y,2)\n\n\"\"\"\n    hinge(y\u0302, y)\n\nMeasures the loss given the prediction `y\u0302` and true labels `y` (containing 1 or -1). \n[Hinge Loss](https://en.wikipedia.org/wiki/Hinge_loss).\n\"\"\"\nhinge(y\u0302, y) = sum(max.(0, 1 .-  y\u0302 .* 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 \u2265 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\u2013Sylvester) 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 \u2265 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\u2013Sylvester) 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 \u2265 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 \u2264 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 \u2265 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 \u2265 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 \u2264 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 \u2265 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 \u2265 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    _, \u03c4 = LinearAlgebra.LAPACK.geqrf!(A)\r\n    T <: Complex ? tran = 'C' : tran = 'T'\r\n    LinearAlgebra.LAPACK.ormqr!('L',tran,A,\u03c4,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, \u03b4)\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 \u03b4 is computed as \u03b4 = 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 \u03b4, 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\u00e9bay, 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\u2013217.\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, \u03b4 = gcdvwupd(a1, b1, d, v, w, maxnit = maxnit)\r\n    else\r\n       \u03b4 = norm( [a1; b1] - [ conv(v,d); conv(w,d) ])\r\n    end\r\n\r\n    switch ? (return d, w, v, \u03b4) : (return d, v, w, \u03b4)\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, \u03b4)\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 \u03b4 = 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\u00e9bay, 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\u2013217.\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    \u0394f = f-fh;\r\n    \u03b4 = norm(\u0394f)\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        # \u0394z = Jh\\\u0394f;   # this does not exploit the zero structure\r\n        \u0394z = qrsolve!(copy(Jh),copy(\u0394f));  # this is probably the fastest\r\n        # \u0394z = qr(Jh)\\\u0394f;  # this is usually slower, but faster for full matrices\r\n        v1 = v0 + \u0394z[j1];\r\n        w1 = w0 + \u0394z[j2];\r\n        d1 = d0 + \u0394z[j3];\r\n        fh1 = [conv(v1,d1); conv(w1,d1); fill(dot(h,d1),1)];\r\n        \u0394f1 = f-fh1;\r\n        \u03b41 = norm(\u0394f1)\r\n        if \u03b41 < \u03b4\r\n           d0 = copy(d1); v0 = copy(v1); w0 = copy(w1); \u03b4 = copy(\u03b41); \u0394f = copy(\u0394f1);\r\n        else\r\n           break\r\n        end\r\n    end\r\n    return d0, v0, w0, \u03b4 \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\u00d74 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\u00d72 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": "using Ipopt\n\n# hs071\n# min x1 * x4 * (x1 + x2 + x3) + x3\n# st  x1 * x2 * x3 * x4 >= 25\n#     x1^2 + x2^2 + x3^2 + x4^2 = 40\n#     1 <= x1, x2, x3, x4 <= 5\n# Start at (1,5,5,1)\n# End at (1.000..., 4.743..., 3.821..., 1.379...)\n\nfunction eval_f(x::Vector{Float64}) \n  return x[1] * x[4] * (x[1] + x[2] + x[3]) + x[3]\nend\n\nfunction eval_g(x::Vector{Float64}, g::Vector{Float64})\n  # Bad: g    = zeros(2)  # Allocates new array\n  # OK:  g[:] = zeros(2)  # Modifies 'in place'\n  g[1] = x[1]   * x[2]   * x[3]   * x[4]\n  g[2] = x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2\nend\n\nfunction eval_grad_f(x::Vector{Float64}, grad_f::Vector{Float64})\n  # Bad: grad_f    = zeros(4)  # Allocates new array\n  # OK:  grad_f[:] = zeros(4)  # Modifies 'in place'\n  grad_f[1] = x[1] * x[4] + x[4] * (x[1] + x[2] + x[3])\n  grad_f[2] = x[1] * x[4]\n  grad_f[3] = x[1] * x[4] + 1\n  grad_f[4] = x[1] * (x[1] + x[2] + x[3])\nend\n\nfunction eval_jac_g(x::Vector{Float64}, mode, rows::Vector{Int32}, cols::Vector{Int32}, values::Vector{Float64})\n  if mode == :Structure\n    # Constraint (row) 1\n    rows[1] = 1; cols[1] = 1\n    rows[2] = 1; cols[2] = 2\n    rows[3] = 1; cols[3] = 3\n    rows[4] = 1; cols[4] = 4\n    # Constraint (row) 2\n    rows[5] = 2; cols[5] = 1\n    rows[6] = 2; cols[6] = 2\n    rows[7] = 2; cols[7] = 3\n    rows[8] = 2; cols[8] = 4\n  else\n    # Constraint (row) 1\n    values[1] = x[2]*x[3]*x[4]  # 1,1\n    values[2] = x[1]*x[3]*x[4]  # 1,2\n    values[3] = x[1]*x[2]*x[4]  # 1,3\n    values[4] = x[1]*x[2]*x[3]  # 1,4\n    # Constraint (row) 2\n    values[5] = 2*x[1]  # 2,1\n    values[6] = 2*x[2]  # 2,2\n    values[7] = 2*x[3]  # 2,3\n    values[8] = 2*x[4]  # 2,4\n  end\nend\n\nfunction eval_h(x::Vector{Float64}, mode, rows::Vector{Int32}, cols::Vector{Int32}, obj_factor::Float64, lambda::Vector{Float64}, values::Vector{Float64})\n  if mode == :Structure\n    # Symmetric matrix, fill the lower left triangle only\n    idx = 1\n    for row = 1:4\n      for col = 1:row\n        rows[idx] = row\n        cols[idx] = col\n        idx += 1\n      end\n    end\n  else\n    # Again, only lower left triangle\n    # Objective\n    values[1] = obj_factor * (2*x[4])  # 1,1\n    values[2] = obj_factor * (  x[4])  # 2,1\n    values[3] = 0                      # 2,2\n    values[4] = obj_factor * (  x[4])  # 3,1\n    values[5] = 0                      # 3,2\n    values[6] = 0                      # 3,3\n    values[7] = obj_factor * (2*x[1] + x[2] + x[3])  # 4,1\n    values[8] = obj_factor * (  x[1])  # 4,2\n    values[9] = obj_factor * (  x[1])  # 4,3\n    values[10] = 0                     # 4,4\n\n    # First constraint\n    values[2] += lambda[1] * (x[3] * x[4])  # 2,1\n    values[4] += lambda[1] * (x[2] * x[4])  # 3,1\n    values[5] += lambda[1] * (x[1] * x[4])  # 3,2\n    values[7] += lambda[1] * (x[2] * x[3])  # 4,1\n    values[8] += lambda[1] * (x[1] * x[3])  # 4,2\n    values[9] += lambda[1] * (x[1] * x[2])  # 4,3\n\n    # Second constraint\n    values[1]  += lambda[2] * 2  # 1,1\n    values[3]  += lambda[2] * 2  # 2,2\n    values[6]  += lambda[2] * 2  # 3,3\n    values[10] += lambda[2] * 2  # 4,4\n  end\nend\n\nfunction intermediate(alg_mod::Int, iter_count::Int, \n  obj_value::Float64, inf_pr::Float64, inf_du::Float64, mu::Float64,\n  d_norm::Float64, regularization_size::Float64, alpha_du::Float64, alpha_pr::Float64, \n  ls_trials::Int)\n  println(\"Iteration $iter_count, objective value is $obj_value.\")\n  return true\nend\n\nn = 4\nx_L = [1.0, 1.0, 1.0, 1.0]\nx_U = [5.0, 5.0, 5.0, 5.0]\n\nm = 2\ng_L = [25.0, 40.0]\ng_U = [2.0e19, 40.0]\n\nprob = createProblem(n, x_L, x_U, m, g_L, g_U, 8, 10,\n                     eval_f, eval_g, eval_grad_f, eval_jac_g, eval_h)\n\nprob.x = [1.0, 5.0, 5.0, 1.0]\nstat = solveProblem(prob)\n\n@test Ipopt.ApplicationReturnStatus[stat] == :Solve_Succeeded\n@test_approx_eq_eps prob.x[1] 1.0000000000000000 1e-5\n@test_approx_eq_eps prob.x[2] 4.7429996418092970 1e-5\n@test_approx_eq_eps prob.x[3] 3.8211499817883077 1e-5\n@test_approx_eq_eps prob.x[4] 1.3794082897556983 1e-5\n@test_approx_eq_eps prob.obj_val 17.014017145179164 1e-5\n", "meta": {"hexsha": "7542e234e2df5035278c57f4366650702c9b03c4", "size": 4004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/hs071_test.jl", "max_stars_repo_name": "JuliaPackageMirrors/Ipopt.jl", "max_stars_repo_head_hexsha": "41b1e7010a2ed92e1f21cec7df6195b581d5707a", "max_stars_repo_licenses": ["MIT"], "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/hs071_test.jl", "max_issues_repo_name": "JuliaPackageMirrors/Ipopt.jl", "max_issues_repo_head_hexsha": "41b1e7010a2ed92e1f21cec7df6195b581d5707a", "max_issues_repo_licenses": ["MIT"], "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/hs071_test.jl", "max_forks_repo_name": "JuliaPackageMirrors/Ipopt.jl", "max_forks_repo_head_hexsha": "41b1e7010a2ed92e1f21cec7df6195b581d5707a", "max_forks_repo_licenses": ["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.7777777778, "max_line_length": 154, "alphanum_fraction": 0.534965035, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7751443594056346}}
{"text": "\"\"\"\nsolve the 1D linear advection equation\n```math\n\u2202q/\u2202t=\u2212u\u2202q/\u2202x\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 \u2190 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": "export randomM\n\n\"\"\"\nfunction randomM(m,n;p=2,N=1)\n\nGenerate samples for M from uniform distribution with non-repeated columns.\n\nInput:\n    m - number of blocks\n    n - number of columns\n    p - number of categories in each block (default=2)\n    N - number of samples (default=1)\n\nOutput:\n    M - BitArray of size (m*(p-1),n,N), or (m*(p-1),n) if N==1\n\"\"\"\nfunction randomM(m::Int64,n::Int64;p::Int64=2,N::Int64=1)\n    if log(n) > m*log(p)\n        error(\"unique columns in M not possible if n > p^m\")\n    end\n\n    # store all feasible blocks of M in a matrix B of size ((p-1)*p^n, n)\n    B = getB(n,p)\n\n    M = falses(m*(p-1),n,N)\n    for idx = 1:N\n        # rejection sampling: check uniqueness of columns\n        firstFlag = true # (this should be a do-while loop)\n        while firstFlag || size(unique(M[:,:,idx],2),2) < n\n            firstFlag = false\n            # randomly choose m blocks from B\n            blockIdB = rand(1:p^n, m)\n            for blockIdM = 1:m\n                subsB = (blockIdB[blockIdM]-1)*(p-1)+1:blockIdB[blockIdM]*(p-1)\n                subsM = (blockIdM-1)*(p-1)+1:blockIdM*(p-1)\n                M[subsM,:,idx] = B[subsB,:]\n            end\n        end\n    end\n\n    # output\n    if N==1\n        M = squeeze(M,3)\n    end\n    return M\nend\n", "meta": {"hexsha": "a1e39d7761f38d72a52a070060bd1ab111e8cac6", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/randomM.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/randomM.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/randomM.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": 26.9361702128, "max_line_length": 79, "alphanum_fraction": 0.5545023697, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7751073361289762}}
{"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} = \u2202_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 ? \u221aeps(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} = \u2202_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# \u2554\u2550\u2561 9daa72fd-1145-4733-a21e-bd209367380a\nusing Pkg; Pkg.develop(path=\"..\"); Pkg.activate(\"..\")\n\n# \u2554\u2550\u2561 947fbdc9-3c48-44f3-b4d3-183f70e2194e\nusing LinearAlgebra\n\n# \u2554\u2550\u2561 a465636e-bc12-4e8f-9db2-1a20ea771504\nbegin\n\t\ud835\udc31 = rand(100, 3)\n\t\ud835\udc31 = hcat(ones(size(\ud835\udc31, 1)), \ud835\udc31)\n\ty = \ud835\udc31 * [1, 2, 3, 4] + 1e-3randn(size(\ud835\udc31, 1))\nend;\n\n# \u2554\u2550\u2561 833c56c2-d2ab-4f94-968b-b5771c9fa945\nfunction irls(\ud835\udc31, y; p=2, n_iter=100)\n\tw = ones(size(\ud835\udc31, 1))\n\t\ud835\udc30 = diagm(w)\n\t\u03b2 = inv(\ud835\udc31' * \ud835\udc30 * \ud835\udc31) * \ud835\udc31' * \ud835\udc30 * y\n\t\n\tif p == 2\n\t\treturn \u03b2\n\tend\n\t\n\tfor _ in 1:n_iter\n\t\tw = abs.(y - \ud835\udc31 * \u03b2).^(p-2)\n\t\t\ud835\udc30 = diagm(w)\n\t\t\u03b2 = inv(\ud835\udc31' * \ud835\udc30 * \ud835\udc31) * \ud835\udc31' * \ud835\udc30 * y\n\tend\n\t\n\treturn \u03b2\nend\n\n# \u2554\u2550\u2561 2c663777-b6e3-42b2-a279-d7b42dd27d70\nirls(\ud835\udc31, y, p=4, n_iter=10)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25009daa72fd-1145-4733-a21e-bd209367380a\n# \u2560\u2550947fbdc9-3c48-44f3-b4d3-183f70e2194e\n# \u2560\u2550a465636e-bc12-4e8f-9db2-1a20ea771504\n# \u2560\u2550833c56c2-d2ab-4f94-968b-b5771c9fa945\n# \u2560\u25502c663777-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\u03b5 = 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 \u039b\u2081(U, x, y, h_x, i, j) + \u039b\u2082(U, x, y, h_y, i, j)\nend\n\n\"Compute the value of the differential operator \u039b\u2081\"\nfunction \u039b\u2081(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 \u039b\u2082\"\nfunction \u039b\u2082(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 \u03be, 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\u2081 = minimum(args -> p(args...), pairs)\n    c\u2082 = maximum(args -> p(args...), pairs)\n    d\u2081 = minimum(args -> q(args...), pairs)\n    d\u2082 = maximum(args -> q(args...), pairs)\n    k\u2081 = 4 / h_x^2\n    k\u2082 = 4 / h_y^2\n    arg\u2081 = (\u03c0 * h_x) / (2 * l_x)\n    arg\u2082 = (\u03c0 * h_y) / (2 * l_y)\n    \u03b4 = c\u2081 * k\u2081 * sin(arg\u2081)^2 +\n        d\u2081 * k\u2082 * sin(arg\u2082)^2\n    \u0394 = c\u2082 * k\u2081 * cos(arg\u2081)^2 +\n        d\u2082 * k\u2082 * cos(arg\u2082)^2\n    return \u03b4 / \u0394\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\u2096\u208b\u2081, \u03be, \u03b5, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    U\u2096 = copy(U\u2096\u208b\u2081)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / \u03b5) / (2\u03be))\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\u2081 = p(x[i] - h_x / 2, y[j]) / h_x^2\n            k\u2082 = p(x[i] + h_x / 2, y[j]) / h_x^2\n            k\u2083 = q(x[i], y[j] - h_y / 2) / h_y^2\n            k\u2084 = q(x[i], y[j] + h_y / 2) / h_y^2\n            U\u2096[i, j] = (k\u2081 * U\u2096\u208b\u2081[i-1, j] +\n                        k\u2082 * U\u2096\u208b\u2081[i+1, j] +\n                        k\u2083 * U\u2096\u208b\u2081[i, j-1] +\n                        k\u2084 * U\u2096\u208b\u2081[i, j+1] +\n                        f(x[i], y[j])) /\n                       (k\u2081 + k\u2082 + k\u2083 + k\u2084)\n        end\n        # Reassign the current iteration as the previous one\n        U\u2096\u208b\u2081 = U\u2096\n    end\n    return U\u2096, m\nend\n\n\"Iterate using the Seidel's method\"\nfunction seidel(U\u2096\u208b\u2081, \u03be, \u03b5, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    U\u2096 = copy(U\u2096\u208b\u2081)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / \u03b5) / (4\u03be))\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\u2081 = p(x[i] - h_x / 2, y[j]) / h_x^2\n            k\u2082 = p(x[i] + h_x / 2, y[j]) / h_x^2\n            k\u2083 = q(x[i], y[j] - h_y / 2) / h_y^2\n            k\u2084 = q(x[i], y[j] + h_y / 2) / h_y^2\n            U\u2096[i, j] = (k\u2081 * U\u2096[i-1, j] +\n                        k\u2082 * U\u2096\u208b\u2081[i+1, j] +\n                        k\u2083 * U\u2096[i, j-1] +\n                        k\u2084 * U\u2096\u208b\u2081[i, j+1] +\n                        f(x[i], y[j])) /\n                       (k\u2081 + k\u2082 + k\u2083 + k\u2084)\n        end\n        # Reassign the current iteration as the previous one\n        U\u2096\u208b\u2081 = U\u2096\n    end\n    return U\u2096, m\nend\n\n\"Iterate using the upper relaxation method\"\nfunction upper_relaxation(U\u2096\u208b\u2081, \u03be, \u03b5, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    U\u2096 = copy(U\u2096\u208b\u2081)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / \u03b5) / sqrt(\u03be))\n    # Define \u03c9 in (0,2), which affects the speed of convergence\n    \u03c9 = 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\u2081 = p(x[i] + h_x / 2, y[j]) / h_x^2\n            k\u2082 = p(x[i] - h_x / 2, y[j]) / h_x^2\n            k\u2083 = q(x[i], y[j] + h_y / 2) / h_y^2\n            k\u2084 = q(x[i], y[j] - h_y / 2) / h_y^2\n            U\u2096[i, j] = U\u2096\u208b\u2081[i, j] +\n                       \u03c9 * (k\u2081 * (U\u2096\u208b\u2081[i+1, j] - U\u2096\u208b\u2081[i, j]) -\n                            k\u2082 * (U\u2096\u208b\u2081[i, j] - U\u2096[i-1, j]) +\n                            k\u2083 * (U\u2096\u208b\u2081[i, j+1] - U\u2096\u208b\u2081[i, j]) -\n                            k\u2084 * (U\u2096\u208b\u2081[i, j] - U\u2096[i, j-1]) +\n                            f(x[i], y[j])) /\n                       (k\u2081 + k\u2082 + k\u2083 + k\u2084)\n        end\n        # Reassign the current iteration as the previous one\n        U\u2096\u208b\u2081 = U\u2096\n    end\n    return U\u2096, m\nend\n\n\"Iterate, using the alternately triangular iterative method\"\nfunction triangular(U\u2096\u208b\u2081, \u03b5, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix\n    U\u2096 = copy(U\u2096\u208b\u2081)\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\u2081 = minimum(args -> p(args...), pairs)\n    c\u2082 = maximum(args -> p(args...), pairs)\n    d\u2081 = minimum(args -> q(args...), pairs)\n    d\u2082 = maximum(args -> q(args...), pairs)\n    k\u2081 = 4 / h_x^2\n    k\u2082 = 4 / h_y^2\n    \u03b4 = c\u2081 * k\u2081 * sin((\u03c0 * h_x) / (2 * l_x))^2 +\n        d\u2081 * k\u2082 * sin((\u03c0 * h_y) / (2 * l_y))^2\n    \u0394 = c\u2082 * k\u2081 + d\u2082 * k\u2082\n    \u03c9 = 2 / sqrt(\u03b4 * \u0394)\n    \u03b7 = \u03b4 / \u0394\n    \u03b3\u2081 = \u03b4 / (2 + 2 * sqrt(\u03b7))\n    \u03b3\u2082 = \u03b4 / (4 * sqrt(\u03b7))\n    \u03be = \u03b3\u2081 / \u03b3\u2082\n    \u03ba\u2081 = \u03c9 / h_x^2\n    \u03ba\u2082 = \u03c9 / h_y^2\n    \u03c4 = 2 / (\u03b3\u2081 + \u03b3\u2082)\n    # Compute the optimal number of iterations\n    m = ceil(Int, log(1 / \u03b5) / log((1 + \u03be) / (1 - \u03be)))\n    # Iterate enough times to achieve desired precision\n    for _ in 1:m\n        # Prepare intermediate matrices\n        U\u0303 = zeros(size(U\u2096\u208b\u2081)...)\n        U\u0305 = zeros(size(U\u2096\u208b\u2081)...)\n        # Compute values at the inner nodes of the first intermediate matrix\n        for i = 2:N, j = 2:M\n            k\u2081 = \u03ba\u2081 * p(x[i] - h_x / 2, y[j])\n            k\u2082 = \u03ba\u2082 * q(x[i], y[j] - h_y / 2)\n            U\u0303[i, j] = (k\u2081 * U\u0303[i-1, j] + k\u2082 * U\u0303[i, j-1] +\n                        L(U\u2096\u208b\u2081, x, y, h_x, h_y, i, j) + f(x[i], y[j])) /\n                       (1 + k\u2081 + k\u2082)\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\u2081 = \u03ba\u2081 * p(x[i] + h_x / 2, y[j])\n            k\u2082 = \u03ba\u2082 * q(x[i], y[j] + h_y / 2)\n            U\u0305[i, j] = (k\u2081 * U\u0305[i+1, j] + k\u2082 * U\u0305[i, j+1] + U\u0303[i, j]) /\n                       (1 + k\u2081 + k\u2082)\n        end\n        # Add up the matrices\n        U\u2096[2:N, 2:M] .= U\u2096\u208b\u2081[2:N, 2:M] .+ \u03c4 .* U\u0305[2:N, 2:M]\n        # Reassign the current iteration as the previous one\n        U\u2096\u208b\u2081 = U\u2096\n    end\n    return U\u2096, m\nend\n\n\"Iterate using the variable directions method\"\nfunction variable_directions(U\u2096\u208b\u2081, \u03b5, N, M, h_x, h_y, x, y)::Tuple{Matrix{Float64},Int}\n    # Prepare a new matrix and an intermediate matrix\n    U\u2096 = copy(U\u2096\u208b\u2081)\n    U\u0305 = copy(U\u2096\u208b\u2081)\n    # Compute the optimal number of iterations\n    m = ceil(Int, N / (2 * \u03c0) * log(1 / \u03b5))\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\u2081 = minimum(args -> p(args...), pairs)\n    c\u2082 = maximum(args -> p(args...), pairs)\n    d\u2081 = minimum(args -> q(args...), pairs)\n    d\u2082 = maximum(args -> q(args...), pairs)\n    k\u2081 = 4 / h_x^2\n    k\u2082 = 4 / h_y^2\n    arg\u2081 = (\u03c0 * h_x) / (2 * l_x)\n    arg\u2082 = (\u03c0 * h_y) / (2 * l_y)\n    \u03b4\u2081 = c\u2081 * k\u2081 * sin(arg\u2081)^2\n    \u03b4\u2082 = d\u2081 * k\u2082 * sin(arg\u2082)^2\n    \u0394\u2081 = c\u2082 * k\u2081 * cos(arg\u2081)^2\n    \u0394\u2082 = d\u2082 * k\u2081 * cos(arg\u2082)^2\n    \u03b4 = min(\u03b4\u2081, \u03b4\u2082)\n    \u0394 = max(\u0394\u2081, \u0394\u2082)\n    \u03c4 = 2 / sqrt(\u03b4 * \u0394)\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\u0303 = Tridiagonal(\n                # A's\n                [repeat([\u03c4 / (2 * h_x^2)], N - 1); 0],\n                # B's\n                [1; repeat([-\u03c4 / h_x^2 + 1], N - 1); 1],\n                # C's\n                [0; repeat([\u03c4 / (2 * h_x^2)], N - 1)],\n            )\n            # Compute the linear system's right-hand side vector\n            g = [\n                U\u2096\u208b\u2081[1, j]\n                [-U\u2096\u208b\u2081[i, j] -\n                 \u03c4 / 2 * (\u039b\u2082(U\u2096\u208b\u2081, x, y, h_y, i, j) +\n                          f(x[i], y[j]))\n                 for i in 2:N\n                ]\n                U\u2096\u208b\u2081[N+1, j]]\n            # Compute the solution of the linear system\n            U\u0305[:, j] .= U\u0303 \\ 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\u0303 = Tridiagonal(\n                # A's\n                [repeat([\u03c4 / (2 * h_y^2)], N - 1); 0],\n                # B's\n                [1; repeat([-\u03c4 / h_y^2 + 1], N - 1); 1],\n                # C's\n                [0; repeat([\u03c4 / (2 * h_y^2)], N - 1)],\n            )\n            # Compute the linear system's right-hand side vector\n            g = [\n                U\u2096\u208b\u2081[i, 1]\n                [-U\u0305[i, j] -\n                 \u03c4 / 2 * (\u039b\u2081(U\u0305, x, y, h_x, i, j) +\n                          f(x[i], y[j]))\n                 for j in 2:M\n                ]\n                U\u2096\u208b\u2081[i, M+1]]\n            # Compute the solution of the linear system\n            U\u2096[i, :] .= U\u0303 \\ g\n        end\n        # Reassign the current iteration as the previous one\n        U\u2096\u208b\u2081 = U\u2096\n    end\n    return U\u2096, 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    \u0394u = 0\n    for i = 1:N1, j = 1:M1\n        _\u0394u = abs(u(x[i], y[j]) - U[i, j])\n        if _\u0394u > \u0394u\n            \u0394u = _\u0394u\n        end\n    end\n    return \u0394u\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 \u03be\n    \u03be = 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, \u03be, \u03b5, 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, \"  \u0394u = \", max_difference(U, x, y)\n    )\n    # Iterate, using the Seidel's method\n    U, m = seidel(U, \u03be, \u03b5, 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, \"  \u0394u = \", max_difference(U, x, y)\n    )\n    # Iterate, using the upper relaxation method\n    U, m = upper_relaxation(U, \u03be, \u03b5, 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, \"  \u0394u = \", max_difference(U, x, y)\n    )\n    # Iterate, using the alternately triangular iterative method\n    U, m = triangular(U, \u03b5, 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, \"  \u0394u = \", max_difference(U, x, y)\n    )\n    # Iterate, using the variable directions method\n    U, m = variable_directions(U, \u03b5, 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, \"  \u0394u = \", 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, \u03b8 = state\n    \u03c9_left, \u03c9_right = control\n\n    \u03b8\u207a = \u03b8 + \u0394\u03b8(\u03c9_left, \u03c9_right, elapsed_time)\n    x\u207a = x + \u0394x(\u03c9_left, \u03c9_right, \u03b8, \u03b8\u207a, elapsed_time)\n    y\u207a = y + \u0394y(\u03c9_left, \u03c9_right, \u03b8, \u03b8\u207a, elapsed_time)\n\n    return [x\u207a y\u207a \u03b8\u207a]\nend\n\n# Change in the x position after the elapsed time.\nfunction \u0394x(\u03c9_left, \u03c9_right, \u03b8_init, \u03b8_new, elapsed_time)\n    if \u03c9_left != \u03c9_right\n        L/2.0 * (\u03c9_left + \u03c9_right)/(\u03c9_right - \u03c9_left) * (sin(\u03b8_new) - sin(\u03b8_init))\n    else\n        r/2.0 * (\u03c9_left + \u03c9_right) * cos(\u03b8_init) * elapsed_time\n    end\nend\n\n# Change in the y position after the elapsed time.\nfunction \u0394y(\u03c9_left, \u03c9_right, \u03b8_init, \u03b8_new, elapsed_time)\n    if \u03c9_left != \u03c9_right\n        L/2.0 * (\u03c9_left + \u03c9_right)/(\u03c9_right - \u03c9_left) * (cos(\u03b8_init) - cos(\u03b8_new))\n    else\n        r/2.0 * (\u03c9_left + \u03c9_right) * sin(\u03b8_init) * elapsed_time\n    end\nend\n\n# Change in the orientation after the elapsed time.\n\u0394\u03b8(\u03c9_left, \u03c9_right, elapsed_time) = r/L * (\u03c9_right - \u03c9_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, \u03b8_world) = [x_world y_world \u03b8_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\u2220(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 \u03c0_2 = \u03c0 / 2\n\nfunction fastacos(d)\n    if d <= -1.0\n        \u03c0\n    elseif d >= 1.0\n        0.0\n    elseif d == 0  # turn around for zero vectors, in particular for denominator=0\n        \u03c0_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\u00e5sa'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\u00b2 = x.^2\n    y\u00b2 = y.^2\n    \n    A = var(x) \n    B = cov(x, y) \n    C = var(y) \n    D = cov(x, y\u00b2) + cov(x, x\u00b2)\n    E = cov(y, x\u00b2) + cov(y, y\u00b2) \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)\u00b2+(y-b)\u00b2-r\u00b2\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)\u00b2+(y-b)\u00b2-r\u00b2\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 40d54e00-f40b-11ea-3ddf-a39ce834ea41\nusing Gadfly\n\n# \u2554\u2550\u2561 54dca870-f411-11ea-1f67-ad216b5b2e49\nset_default_plot_size(20cm, 15cm)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250040d54e00-f40b-11ea-3ddf-a39ce834ea41\n# \u2560\u25505a0472c2-f40b-11ea-231b-a52e7382c1bc\n# \u255f\u250054dca870-f411-11ea-1f67-ad216b5b2e49\n# \u255f\u2500dd853160-f40c-11ea-318e-5751cdc6ffdf\n# \u2560\u2550bc85d0e0-f40d-11ea-2344-dd5ea4b66cde\n# \u2560\u25505e773960-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 CSV, DataFrames, StatsBase\nusing StanSample, StatsPlots\nusing StatisticalRethinkingPlots, StatisticalRethinking\n\ndf = CSV.read(sr_datadir(\"WaffleDivorce.csv\"), DataFrame);\ndf[!, :M] = zscore(df.Marriage)\ndf[!, :A] = zscore(df.MedianAgeMarriage)\ndf[!, :D] = zscore(df.Divorce)\ndata = (N=size(df, 1), D=df.D, A=df.A, M=df.M)\n\nstan5_1 = \"\ndata {\n    int < lower = 1 > N; // Sample size\n    vector[N] D; // Outcome\n    vector[N] A; // Predictor\n}\nparameters {\n    real a; // Intercept\n    real bA; // Slope (regression coefficients)\n    real < lower = 0 > sigma;    // Error SD\n}\ntransformed parameters {\n    vector[N] mu;               // mu is a vector\n    for (i in 1:N)\n        mu[i] = a + bA * A[i];\n}\nmodel {\n    a ~ normal(0, 0.2);         //Priors\n    bA ~ normal(0, 0.5);\n    sigma ~ exponential(1);\n    D ~ normal(mu , sigma);     // Likelihood\n}\ngenerated quantities {\n    vector[N] log_lik;\n    for (i in 1:N)\n        log_lik[i] = normal_lpdf(D[i] | mu[i], sigma);\n}\n\";\n\nstan5_2 = \"\ndata {\n    int N;\n    vector[N] D;\n    vector[N] M;\n}\nparameters {\n    real a;\n    real bM;\n    real<lower=0> sigma;\n}\ntransformed parameters {\n    vector[N] mu;\n    for (i in 1:N)\n        mu[i]= a + bM * M[i];\n\n}\nmodel {\n    a ~ normal( 0 , 0.2 );\n    bM ~ normal( 0 , 0.5 );\n    sigma ~ exponential( 1 );\n    D ~ normal( mu , sigma );\n}\ngenerated quantities {\n    vector[N] log_lik;\n    for (i in 1:N)\n        log_lik[i] = normal_lpdf(D[i] | mu[i], sigma);\n}\n\";\n\nstan5_3 = \"\ndata {\n  int N;\n  vector[N] D;\n  vector[N] M;\n  vector[N] A;\n}\nparameters {\n  real a;\n  real bA;\n  real bM;\n  real<lower=0> sigma;\n}\ntransformed parameters {\n    vector[N] mu;\n    for (i in 1:N)\n        mu[i] = a + bA * A[i] + bM * M[i];\n}\nmodel {\n  a ~ normal( 0 , 0.2 );\n  bA ~ normal( 0 , 0.5 );\n  bM ~ normal( 0 , 0.5 );\n  sigma ~ exponential( 1 );\n  D ~ normal( mu , sigma );\n}\ngenerated quantities{\n    vector[N] log_lik;\n    for (i in 1:N)\n        log_lik[i] = normal_lpdf(D[i] | mu[i], sigma);\n}\n\";\n\nfname = joinpath(@__DIR__, \"coeftab_plot.png\")\nisfile(fname) && rm(fname)\n\nm5_1s = SampleModel(\"m5.1s\", stan5_1)\nrc5_1s = stan_sample(m5_1s; data)\n\nm5_2s = SampleModel(\"m5.2s\", stan5_2)\nrc5_2s = stan_sample(m5_2s; data)\n\nm5_3s = SampleModel(\"m5.3s\", stan5_3)\nrc5_3s = stan_sample(m5_3s; data)\nmodels = [m5_1s, m5_2s, m5_3s]\n\nif success(rc5_1s) && success(rc5_2s) && success(rc5_3s)\n\n    m5_1s_df = read_samples(m5_1s, :dataframe)\n    m5_2s_df = read_samples(m5_2s, :dataframe)\n    m5_3s_df = read_samples(m5_3s, :dataframe)\n\n    if isinteractive()\n\n        coeftab_plot(m5_1s_df, m5_2s_df, m5_3s_df; pars=(:bA, :bM),\n            names=[\"m5.1\", \"m5.2\", \"m5.3\"])\n        savefig(joinpath(@__DIR__, \"coeftab_plot.png\"))\n\n    end\nend\n", "meta": {"hexsha": "a8f3fc78c9e47398823bcf7f330ce4d5ebc52c14", "size": 2712, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Coeftab_plot/test_coeftab_plot.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": "test/Coeftab_plot/test_coeftab_plot.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": "test/Coeftab_plot/test_coeftab_plot.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.023255814, "max_line_length": 67, "alphanum_fraction": 0.5825958702, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7750020874521814}}
{"text": "using FFTW, BenchmarkTools, FourierFlows, Random\nusing LinearAlgebra: mul!, ldiv!\nusing Random: seed!\n\nseed!(1234) # for reproducibility\n\nLx, Ly = 2\u03c0, 3\u03c0\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 \u2202f/\u2202x\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 \u2202f/\u2202x 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 \u2202f/\u2202x using fft\")\n  @btime dx_using_fft(f);\n  println(\" \")\n  println(\"computing \u2202f/\u2202x using rfft\")\n  @btime dx_using_rfft(f);\n  println(\" \")\n  println(\"computing \u2202f/\u2202x using fftplan\")\n  @btime dx_using_fftplan(f);\n  println(\" \")\n  println(\"computing \u2202f/\u2202x using rfftplan\")\n  @btime dx_using_rfftplan(f);\n  println(\" \")\n  println(\"computing \u2202f/\u2202x using fftplan & mul!\")\n  @btime dx_using_fftplan_mul(f);\n  println(\" \")\n  println(\"computing \u2202f/\u2202x 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, \u03d5, par, dx, dy, dt)\r\n    \u03d5n = Array{Float64}(undef, par.Nx, par.Ny) # Pre-allocate array of \u03d5\r\n    # Compute solutions on staggered grid using Lin-Tadmor\r\n    \u03d5s = lt_staggered(V, \u03d5, par, dx, dy, dt)\r\n    # Compute derivatives on staggered grid\r\n    dx\u03d5s = Array{Float64}(undef, par.Nx-1, par.Ny-1) # Pre-allocate x-derivatives at staggered grid points\r\n    dy\u03d5s = 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\u03d5s[i,j] = (\u03d5s[i+1,j]-\u03d5s[i,j])/dx # \u03d5'_{i+1/2,j+1/2}/\u0394x\r\n            elseif i == par.Nx-1\r\n                dx\u03d5s[i,j] = (\u03d5s[i,j]-\u03d5s[i-1,j])/dx # \u03d5'_{i+1/2,j+1/2}/\u0394x\r\n            else\r\n                dx\u03d5s[i,j] = minmod(par.\u03b8*(\u03d5s[i+1,j]-\u03d5s[i,j])/dx, (\u03d5s[i+1,j]-\u03d5s[i-1,j])/(2*dx), par.\u03b8*(\u03d5s[i,j]-\u03d5s[i-1,j])/dx) # \u03d5'_{i+1/2,j+1/2}/\u0394x\r\n            end\r\n            if j == 1\r\n                dy\u03d5s[i,j] = (\u03d5s[i,j+1]-\u03d5s[i,j])/dy # \u03d5`_{i+1/2,j+1/2}/\u0394y\r\n            elseif j == par.Ny-1\r\n                dy\u03d5s[i,j] = (\u03d5s[i,j]-\u03d5s[i,j-1])/dy # \u03d5`_{i+1/2,j+1/2}/\u0394y\r\n            else\r\n                dy\u03d5s[i,j] = minmod(par.\u03b8*(\u03d5s[i,j+1]-\u03d5s[i,j])/dy, (\u03d5s[i,j+1]-\u03d5s[i,j-1])/(2*dy), par.\u03b8*(\u03d5s[i,j]-\u03d5s[i,j-1])/dy) # \u03d5`_{i+1/2,j+1/2}/\u0394y\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                \u03d5n[i,j] = \u03d5[i,j]\r\n            else\r\n                \u03d5n[i,j] = (\u03d5s[i,j] + \u03d5s[i-1,j] + \u03d5s[i,j-1] + \u03d5s[i-1,j-1])/4 + \r\n                (dx*(dx\u03d5s[i-1,j-1]-dx\u03d5s[i,j-1]) + dx*(dx\u03d5s[i-1,j]-dx\u03d5s[i,j]) + dy*(dy\u03d5s[i-1,j-1]-dy\u03d5s[i-1,j]) + dy*(dy\u03d5s[i,j-1]-dy\u03d5s[i,j]))/16 # Compute non-staggered cell average\r\n            end\r\n        end\r\n    end\r\n    return \u03d5n\r\nend\r\n\r\n\"Staggered Lin-Tadmor scheme\"\r\nfunction lt_staggered(V, \u03d5, par, dx, dy, dt)\r\n    \u03d5_stag = Array{Float64}(undef, par.Nx-1, par.Ny-1) # Pre-allocate solution on staggered grid \u03d5_stag[i,j] = \u03d5[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] = \u03d5[i+1/2, j+1/2], one-based indexing\r\n    dx\u03d5 = Array{Float64}(undef, par.Nx, par.Ny) # Pre-allocate x-derivatives at non-staggered grid points\r\n    dy\u03d5 = Array{Float64}(undef, par.Nx, par.Ny) # Pre-allocate y-derivatives at non-staggered grid points\r\n    \u03d5_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\u03d5/dx\r\n            if i == 1 # Boundary condition\r\n                dx\u03d5[i,j] = (\u03d5[i+1,j] - \u03d5[i,j])/dx\r\n            elseif i == par.Nx # Boundary condition\r\n                dx\u03d5[i,j] = (\u03d5[i,j] - \u03d5[i-1,j])/dx\r\n            else # Apply min-mod at interior grid points\r\n                dx\u03d5[i,j] = minmod(par.\u03b8*(\u03d5[i+1,j]-\u03d5[i,j])/dx, (\u03d5[i+1,j]-\u03d5[i-1,j])/(2*dx), par.\u03b8*(\u03d5[i,j]-\u03d5[i-1,j])/dx)\r\n            end\r\n            # Compute d\u03d5/dy\r\n            if j == 1 # Boundary condition\r\n                dy\u03d5[i,j] = (\u03d5[i,j+1] - \u03d5[i,j])/dy\r\n            elseif j == par.Ny # Boundary condition\r\n                dy\u03d5[i,j] = (\u03d5[i,j] - \u03d5[i,j-1])/dy\r\n            else # Apply min-mod at interior grid points\r\n                dy\u03d5[i,j] = minmod(par.\u03b8*(\u03d5[i,j+1]-\u03d5[i,j])/dy, (\u03d5[i,j+1]-\u03d5[i,j-1])/(2*dy), par.\u03b8*(\u03d5[i,j]-\u03d5[i,j-1])/dy)\r\n            end\r\n            \u03d5_mid[i,j] = \u03d5[i,j] - dt/2*hamiltonian_ls(V[i,j], dx\u03d5[i,j], dy\u03d5[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            \u03d5_stag[i,j] = (\u03d5[i,j] + \u03d5[i+1,j] + \u03d5[i,j+1] + \u03d5[i+1,j+1])/4 + \r\n            (dx\u03d5[i,j]-dx\u03d5[i+1,j]+dx\u03d5[i,j+1]-dx\u03d5[i+1,j+1])*dx/16 + \r\n            (dy\u03d5[i,j]-dy\u03d5[i,j+1]+dy\u03d5[i+1,j]-dy\u03d5[i+1,j+1])*dy/16 - \r\n            dt/2*(hamiltonian_ls(V_stag[i,j], (\u03d5_mid[i+1,j]-\u03d5_mid[i,j])/dx, (\u03d5_mid[i+1,j+1]-\u03d5_mid[i+1,j])/dy) + \r\n            hamiltonian_ls(V_stag[i,j], (\u03d5_mid[i+1,j+1]-\u03d5_mid[i,j+1])/dx, (\u03d5_mid[i,j+1]-\u03d5_mid[i,j])/dy))\r\n        end\r\n    end\r\n    return \u03d5_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, \u03d5x, \u03d5y)\r\n    return v*sqrt(\u03d5x^2 + \u03d5y^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\u0307::Function, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080]\n    x = x\u2080\n    for t \u2208 tcoll[2:end]\n        x += h * x\u0307(t, x)\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction UnstableDES(; x\u0307::Function, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080, x\u2080 + h * x\u0307(t\u2080, x\u2080)]\n    for t \u2208 tcoll[3:end]\n        x\u2099\u208a\u2081 = 2 * h * x\u0307(t, xcoll[end]) + xcoll[end-1]\n        push!(xcoll, x\u2099\u208a\u2081)\n    end\n    return tcoll, xcoll\nend\n\nfunction EulerYaghoubDES(; x\u0307::Function, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080]\n    x = x\u2080\n    x\u0307val = x\u0307(t\u2080, x\u2080)\n    for t \u2208 tcoll[2:end]\n        x += h * x\u0307val\n        x\u0307val = x\u0307(t, x)\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction RK2DES(; x\u0307::Function, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080]\n    x = x\u2080\n    for t \u2208 tcoll[2:end]\n        K\u2081 = x\u0307(t, x) * h\n        K\u2082 = h * x\u0307(t + h / 2, x + (K\u2081 * h) / 2)\n        x += K\u2082\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction RK4DES(; x\u0307::Function, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080]\n    x = x\u2080\n    for t \u2208 tcoll[2:end]\n        K\u2081 = x\u0307(t, x)\n        K\u2082 = x\u0307(t + h / 2, x .+ h / 2 * K\u2081)\n        K\u2083 = x\u0307(t + h / 2, x .+ h / 2 * K\u2082)\n        K\u2084 = x\u0307(t + h, x .+ h * K\u2083)\n        x += (K\u2081 + 2 * K\u2082 + 2 * K\u2083 + K\u2084) * h / 6\n        push!(xcoll, x)\n    end\n    return tcoll, xcoll\nend\n\nfunction EulerCromerDES(; x\u0308::Function, x\u0307\u2080::Vector{T}, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080]\n    x\u0307coll = [x\u0307\u2080]\n    x = x\u2080\n    x\u0307 = x\u0307\u2080\n    for t \u2208 tcoll[2:end]\n        x\u0307 += h * x\u0308(t, x, x\u0307)\n        x += h * x\u0307\n        push!(xcoll, x)\n        push!(x\u0307coll, x\u0307)\n    end\n\n    return tcoll, xcoll, x\u0307coll\nend\n\nfunction EulerMidPiontDES(; x\u0308::Function, x\u0307\u2080::Vector{T}, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080]\n    x\u0307coll = [x\u0307\u2080 - (x\u0308(t\u2080, x\u2080, x\u0307\u2080) * h / 2)]\n    x = x\u2080\n    x\u0307 = x\u0307\u2080 - (x\u0308(t\u2080, x\u2080, x\u0307\u2080) * h / 2)\n\n    for t \u2208 tcoll[2:end]\n        x\u0307 += h * x\u0308(t, x, x\u0307)\n        x += h * x\u0307\n\n        push!(xcoll, x)\n        push!(x\u0307coll, x\u0307)\n    end\n\n    return tcoll, xcoll, x\u0307coll\nend\n\nfunction VerletDES(; x\u0308::Function, x\u0307\u2080::Vector{T}, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080, x\u2080 + x\u0307\u2080 * h + x\u0308(t\u2080, x\u2080, x\u0307\u2080) * (h^2) / 2]\n    x\u0307coll = [x\u0307\u2080, x\u0307\u2080 + x\u0308(t\u2080, x\u2080, x\u0307\u2080) * h]\n\n    for i \u2208 3:length(tcoll)\n        x\u1d62 = 2 * xcoll[i-1] - xcoll[i-2] + x\u0308(tcoll[i-1], xcoll[i-1], x\u0307coll[i-1]) * (h^2)\n        push!(xcoll, x\u1d62)\n        x\u0307\u1d62 = (xcoll[i] - xcoll[i-1]) / h\n        push!(x\u0307coll, x\u0307\u1d62)\n    end\n\n    return tcoll, xcoll, x\u0307coll\nend\n\nfunction VelVerDES(; x\u0308::Function, x\u0307\u2080::Vector{T}, x\u2080::Vector{T}, t\u2080::T, t\u2081::T, h::T) where {T<:AbstractFloat}\n    tcoll = collect(t\u2080:h:t\u2081)\n    xcoll = [x\u2080]\n    x\u0307coll = [x\u0307\u2080]\n    x = x\u2080\n    x\u0307 = x\u0307\u2080\n\n    for t \u2208 tcoll[2:end]\n        x\u0308\u2099 = x\u0308(t, x, x\u0307)\n        x += x\u0307 * h + x\u0308\u2099 * (h^2) / 2\n        x\u0308\u2099\u208a\u2081 = x\u0308(t + h, x, x\u0307)\n        x\u0307 += (x\u0308\u2099 + x\u0308\u2099\u208a\u2081) * h / 2\n        push!(xcoll, x)\n        push!(x\u0307coll, x\u0307)\n    end\n\n    return tcoll, xcoll, x\u0307coll\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": "using Test\n# using Revise\nusing CutCellDG\ninclude(\"../useful_routines.jl\")\n\nl,m = 1.,2.\nstiffness = CutCellDG.plane_strain_voigt_hooke_matrix(l,m)\nteststiffness = [5. 1. 0.\n                 1. 5. 0.\n                 0. 0. 2.]\n@test allapprox(teststiffness,stiffness)\n\nstiffness = CutCellDG.HookeStiffness(l,m,l,m)\n@test allapprox(teststiffness,stiffness[-1])\n@test allapprox(teststiffness,stiffness[+1])\n\nl1,m1 = 1.,2.\nl2,m2 = 3.,4.\nstiffness = CutCellDG.HookeStiffness(l1,m1,l2,m2)\nteststiffness2 = [11.  3.  0.\n                   3.  11. 0.\n                   0.   0. 4.]\nteststiffness1 = [5. 1. 0.\n                  1. 5. 0.\n                  0. 0. 2.]\n@test allapprox(teststiffness1,stiffness[1])\n@test allapprox(teststiffness2,stiffness[-1])\n\n@test allapprox((l1,m1),CutCellDG.lame_coefficients(stiffness,1))\n@test allapprox((l2,m2),CutCellDG.lame_coefficients(stiffness,-1))\n", "meta": {"hexsha": "d60adc32486ed73e3425d99edfcb5f39c1b0b067", "size": 881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/miscellaneous/test_hooke_stiffness.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": "test/miscellaneous/test_hooke_stiffness.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": "test/miscellaneous/test_hooke_stiffness.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": 28.4193548387, "max_line_length": 66, "alphanum_fraction": 0.6333711691, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7750020796515987}}
{"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 \u00f7 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 TuringModels, StatsFuns\n\nTuring.setadbackend(:reversediff)\n\n# outcome and predictor almost perfectly associated\n\nx = repeat([-1], 9); append!(x, repeat([1],11))\ny = repeat([0], 10); append!(y, repeat([1],10))\n\n@model m_good_stan(x,y) = begin\n    \u03b1 ~ Normal(0,10)\n    \u03b2 ~ Normal(0,10)\n\n    logits = \u03b1 .+ \u03b2 * x\n\n    y .~ BinomialLogit.(1, logits)\nend\n\nchns = sample(m_good_stan(x,y), Turing.NUTS(0.65), 1000)\n\n# Stan results\n\nm_10_x,_results = \"\n    mean   sd   5.5% 94.5% n_eff Rhat\n a -5.09 4.08 -12.62 -0.25   100 1.00\n b  7.86 4.09   2.96 15.75   104 1.01\n\";\n\n# Look at the proper draws (in corrected chn2)\n\ndescribe(chns)\n\n# End of 10/m10.xxt.jl\n", "meta": {"hexsha": "f37f70350240492c826b41c599ceb1f60e1a01b7", "size": 655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/10/m10.xxt.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.xxt.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.xxt.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": 19.2647058824, "max_line_length": 56, "alphanum_fraction": 0.6305343511, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7749910843129436}}
{"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": "using DynamicHMCModels\n\nRandom.seed!(1)\n\ncd(@__DIR__)\ninclude(\"simulateGaussian.jl\")\n\nstruct GaussianProb{TY <: AbstractVector}\n   \"Observations.\"\n   y::TY\nend\n\nfunction (problem::GaussianProb)(\u03b8)\n   @unpack y = problem   # extract the data\n   @unpack mu, sigma = \u03b8\n   loglikelihood(Normal(mu, 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.\n\ndata = simulateGaussian(;Nd=100)\np = GaussianProb(data.y);\np((mu = 0.0, sigma = 1.0))\n\n# Write a function to return properly dimensioned transformation.\n\nproblem_transformation(p::GaussianProb) =\n  as((mu  = as(Real, -25, 25), sigma = as\u211d\u208a), )\n \n# Use Flux for the gradient.\nP = TransformedLogDensity(problem_transformation(p), p)\n\n\u2207P = ADgradient(:ForwardDiff, P)\n\n#import Zygote\n#\u2207P = ADgradient(:Zygote, P)\n\n# Sample from the posterior.\nchain, NUTS_tuned = NUTS_init_tune_mcmc(\u2207P, 4000);\n\n# Undo the transformation to obtain the posterior from the chain.\nposterior = TransformVariables.transform.(Ref(problem_transformation(p)),\nget_position.(chain));\n\nchns = nptochain(posterior, NUTS_tuned)\n\ndescribe(chns)", "meta": {"hexsha": "0fb1cc03fd8dec5c2ed773e333c868af3a452c08", "size": 1135, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/Gaussian/gaussian.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": "benchmarks/Gaussian/gaussian.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": "benchmarks/Gaussian/gaussian.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": 23.6458333333, "max_line_length": 73, "alphanum_fraction": 0.7215859031, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7749910792804363}}
{"text": "\r\ninclude(\"../src/autodiff_module.jl\")\r\ninclude(\"../../__lib__/math/opti/src/opti_module.jl\")\r\n\r\nmodule optitest\r\nusing ..autodiff\r\nusing ..opti\r\n\r\n\r\nfunction quadratic(x)\r\n    y = zero(eltype(x))\r\n    for ii in eachindex(x)\r\n        y += x[ii]^2\r\n    end\r\n    return y\r\nend \r\n\r\nfunction quadratic(x, x0)\r\n    y = zero(eltype(x))\r\n    for ii in eachindex(x)\r\n        y += (x[ii] - x0[ii])^2\r\n    end\r\n    return y\r\nend \r\n\r\n\r\n\r\n# x1a = autodiff.DualNumber(3.0)\r\n# x2a = autodiff.DualNumber(4.0)\r\n\r\n# x_vec = [x1a, x2a]\r\n# g = autodiff.gradient(quadratic, x_vec)\r\n\r\n\r\nx0 = [3.0, 4.0]\r\n\r\nc = [5.0, 6.0]\r\nobj_fcn(x)              = quadratic(x, c)\r\ngrad_fcn(objfcn, x)     = autodiff.gradient(autodiff.ForwardMode(), objfcn, x)\r\ndir_diff_fcn(fcn, x, s) = autodiff.directional_derivative(fcn, x, s)\r\n\r\ntol_options      = opti.ToleranceOptions(\r\n    step_size_tol = 1e-15,\r\n    f_abs_tol = 1e-15,\r\n    f_rel_tol = 1e-15,\r\n    g_abs_tol = 1e-15,\r\n    max_iter = 100)\r\n\r\n\r\n# (x_sol, y_sol, iter, stopping_crit) = opti.quasi_newton(\r\n#     obj_fcn,\r\n#     x0;\r\n#     tol_options          = tol_options,\r\n#     gradient_fcn         = grad_fcn,\r\n#     directional_diff_fcn = dir_diff_fcn)\r\n\r\nstat = opti.cg_pr(\r\n    obj_fcn,\r\n    x0;\r\n    tol_options          = tol_options,\r\n    gradient_fcn         = grad_fcn,\r\n    directional_diff_fcn = dir_diff_fcn)\r\n\r\n\r\n\r\n\r\n# directional diff\r\n# lim[h -> 0] (fcn(x + h * s) - fcn(x)) / h\r\n\r\n\r\n# x0 = [3.0, 4.0]\r\n# obj_fcn(x) = quadratic(x)\r\n\r\n# # s = [-4.0, 3.0]\r\n# # s = -[-3.0, 4.0]\r\n# s = [0.0, 5.0]\r\n# s = [5.0, 0.0]\r\n\r\n# dg = autodiff.directional_derivative(obj_fcn, x0, s)\r\n\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "226a5587b3a912155bfa94f5bb8075b683033e19", "size": 1619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "autodiff/test/test_opti.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": "autodiff/test/test_opti.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": "autodiff/test/test_opti.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.2738095238, "max_line_length": 79, "alphanum_fraction": 0.5583693638, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7749760124489427}}
{"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        \u03ba = 0.5*log(det(P.ss.\u03a3_1)/det(P.ss.\u03a3_p))/log(2); #returns capacity in bits\n    elseif unit == \"nat\"\n        \u03ba = 0.5*log(det(P.ss.\u03a3_1)/det(P.ss.\u03a3_p));        #returns capacity in nats\n    else\n        println(\"Invalid input for unit! Capacity is reported in bits.\")\n        \u03ba = 0.5*log(det(P.ss.\u03a3_1)/det(P.ss.\u03a3_p))/log(2);\n    end\n    return(\u03ba)\nend\n\n\"\"\"\n    infinitesum(func; tol = 1e-6,maxit = 1000,start=0)\nReturns the infinite sum `\u03a3\u2093func(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": "using IntUtils\n\nfunction is_abundant(n::Integer)\n    d = proper_divisors(n)\n    s = sum(d)\n    if s > n\n        return true\n    else\n        return false\n    end\nend\n\nfunction is_sum_of_pairs_from(n::Integer, s::Set{Integer})\n    for elt in s\n        d = n - elt\n        if d > 0 && d in s\n            return true\n        end\n    end\n    return false\nend\n\nfunction main()\n    abundants = Set{Integer}()\n    for i in 12:28123\n        if is_abundant(i)\n            push!(abundants, i)\n        end\n    end\n    s = 0\n    for i in 1:28123\n        if !is_sum_of_pairs_from(i, abundants)\n            s += i\n        end\n    end\n    @printf(\"The sum of all numbers not the sum of two abundant numbers is %d\\n\", s)\nend\n\nmain()\n", "meta": {"hexsha": "3ebc846c70e0dbbeb452441a6e157f7d77f0d555", "size": 717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem_023.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_023.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_023.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": 17.925, "max_line_length": 84, "alphanum_fraction": 0.5481171548, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203815, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7749463828198917}}
{"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., \u03b1=.5, \u03b2=0.5, q=.1, \u03bb=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     \u03bb : 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, \u201cThe kernel recursive least-squares algorithm,\u201d IEEE Transactions on Signal Processing, vol. 52, no. 8, pp. 2275\u20132285, 2004.\n\n\n\u03bb = convert(T, \u03bb)\nnu = convert(T, nu)\n\n\u03bb2 = \u03bb.^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 = (\u03b1*y[1] ./ (\u03bb*\u03b2+K))'\npr = \u03bb*\u03b2 / (abs(\u03b1)^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]) + \u03bb2\n\n\tktt = kernelfunc(x[:,ii], x[:,ii]) + \u03bb2\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, \u03bb::Float64)\n    total = 0\n\n    for (u, v, r) in dataset\n        total += (r - model[u, v])^2\n        total += \u03bb * (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, \u03b3::Float64, \u03bb::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,:] += \u03b3 * (e .* Q .- \u03bb .* P)\n        model.Q[v,:] += \u03b3 * (e .* P .- \u03bb .* 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,\u03c0/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 \u03c0-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 \u03c0-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 \u03c0-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 \u03c0-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(\u03b1)\n\nis a quasi-vector representing `x^\u03b1 * exp(-x)` on `0..Inf`.\n\"\"\"\nstruct LaguerreWeight{T} <: Weight{T}\n    \u03b1::T\nend\n\nLaguerreWeight{T}() where T = LaguerreWeight{T}(zero(T))\nLaguerreWeight() = LaguerreWeight{Float64}()\naxes(::LaguerreWeight{T}) where T = (Inclusion(\u211d),)\nfunction getindex(w::LaguerreWeight, x::Number)\n    x \u2208 axes(w,1) || throw(BoundsError())\n    x^w.\u03b1 * exp(-x)\nend\n\nsum(L::LaguerreWeight{T}) where T = gamma(L.\u03b1 + 1)\n\nstruct Laguerre{T} <: OrthogonalPolynomial{T} \n    \u03b1::T\n    Laguerre{T}(\u03b1) where T = new{T}(convert(T, \u03b1))\nend\nLaguerre{T}() where T = Laguerre{T}(zero(T))\nLaguerre() = Laguerre{Float64}()\nLaguerre(\u03b1::T) where T = Laguerre{float(T)}(\u03b1)\northogonalityweight(L::Laguerre)= LaguerreWeight(L.\u03b1)\n\n==(L1::Laguerre, L2::Laguerre) = L1.\u03b1 == L2.\u03b1\naxes(::Laguerre{T}) where T = (Inclusion(HalfLine{T}()), oneto(\u221e))\n\n\"\"\"\n     laguerrel(n, \u03b1, z)\n\ncomputes the `n`-th generalized Laguerre polynomial, orthogonal with \nrespec to `x^\u03b1 * exp(-x)`, at `z`.\n\"\"\"\nlaguerrel(n::Integer, \u03b1, z::Number) = Base.unsafe_getindex(Laguerre{promote_type(typeof(\u03b1), typeof(z))}(\u03b1), 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+\u03b1+1)/(n+1)) L_n - (n+\u03b1)/(n+1) L_{n-1}\n# - (n+\u03b1) L_{n-1} + (2n+\u03b1+1)* L_n -(n+1) L_{n+1} = x  L_n\n# x*[L_0 L_1 L_2 \u2026] = [L_0 L_1 L_2 \u2026] * [(\u03b1+1)    -(\u03b1+1); -1  (\u03b1+3)     -(\u03b1+2);0  -2   (\u03b1+5) -(\u03b1+3); \u2026]   \nfunction jacobimatrix(L::Laguerre{T}) where T\n    \u03b1 = L.\u03b1\n    Tridiagonal(-(1:\u221e), (\u03b1+1):2:\u221e, -(\u03b1+1:\u221e))\nend\n\nrecurrencecoefficients(L::Laguerre{T}) where T = ((-one(T)) ./ (1:\u221e), ((L.\u03b1+1):2:\u221e) ./ (1:\u221e), (L.\u03b1:\u221e) ./ (1:\u221e))\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,\u221e), \u221e, -1,1)\n    Laguerre(L.\u03b1+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 \u03c9 t \u03bc\n\n@testset \"   Euler-Lagrange Solver\" begin\n    function \u0393(w)\n       t -> UpTuple([t, w(t), D(w)(t)])\n    end\n\n    function Lagrange_Equations(L)\n        w -> D(\u2202(3)(L)\u2218\u0393(w)) - \u2202(2)(L)\u2218\u0393(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*\u03c9^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 * \u03c9 ^ 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)+\u03bc/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) * \u03bc, m * (D(D(y)))(t) + ((x)(t) ^ 2 + (y)(t) ^ 2) ^ -1.5 * (y)(t) * \u03bc]\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 \u00f7 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 GARCH\nusing Pkg, Test, DelimitedFiles, Statistics\n\n\nfilename = Pkg.dir(\"GARCH\", \"test\", \"data\", \"price.csv\")\nprice = Array{Float64}(readdlm(filename, ',')[:,2])\n\nret = diff(log.(price))\nret = ret .- mean(ret)\nfit = garchFit(ret)\n\nparam = [2.469347e-06, 1.142268e-01, 8.691734e-01] #R fGarch garch(1,1) estimated params\n\n@test fit.params \u2248 param atol=1e-3\n@test predict(fit) \u2248 0.005617744 atol = 1e-4\n@test predict(fit, 2) \u2248 [0.005617744, 0.005788309] atol = 1e-4\n\n", "meta": {"hexsha": "447da8d1b03628e36931ea84abcdec439146c902", "size": 470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 26.1111111111, "max_line_length": 88, "alphanum_fraction": 0.6765957447, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067260443809, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7749187938103829}}
{"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 - `\u03b2::Real`: set in order to obtain comparable summands in norm\n\n# References\n> J\u00e1n Plesn\u00edk, Finding the orthogonal projection of a point onto \n> an affine subspace, Linear Algebra and its Applications, Volume 422, \n> Issues 2\u20133, 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                    \u03b2::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(\u03b2) && throw(ArgumentError(\"`\u03b2` 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 + \u03b2 * 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 \u03c3, \u03c1 and \u03b2 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        \u03c3, \u03c1, \u03b2=p\n\n        dxdt=\u03c3*(y-x)\n        dydt=\u03c1*x-x*z-y\n        dzdt=x*y-\u03b2*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": "@testset \"spectral operators\" begin\n    function P5(r::AbstractVector{T}) where {T}\n        return T(1) / T(8) * (T(15) * r - T(70) * r .^ 3 + T(63) * r .^ 5)\n    end\n    function P6(r::AbstractVector{T}) where {T}\n        return T(1) / T(16) * (-T(5) .+ T(105) * r .^ 2 - T(315) * r .^ 4 + T(231) * r .^ 6)\n    end\n    function DP6(r::AbstractVector{T}) where {T}\n        return T(1) / T(16) * (T(2 * 105) * r - T(4 * 315) * r .^ 3 + T(6 * 231) * r .^ 5)\n    end\n\n    IPN(::Type{T}, N) where {T} = T(2) / T(2 * N + 1)\n\n    for T in (Float32, Float64, BigFloat)\n        r, w = legendregausslobatto(T, 7)\n        x = LinRange{T}(-1, 1, 101)\n        D = spectralderivative(r)\n        P = spectralinterpolation(r, x)\n\n        @test sum(P5(r) .^ 2 .* w) \u2248 IPN(T, 5)\n        @test D * P6(r) \u2248 DP6(r)\n        @test P * P6(r) \u2248 P6(x)\n    end\n\n    for T in (Float32, Float64, BigFloat)\n        r, w = legendregauss(T, 7)\n        D = spectralderivative(r)\n\n        @test sum(P5(r) .^ 2 .* w) \u2248 IPN(T, 5)\n        @test sum(P6(r) .^ 2 .* w) \u2248 IPN(T, 6)\n        @test D * P6(r) \u2248 DP6(r)\n    end\nend\n", "meta": {"hexsha": "551f934e05787efffa3675a60612f14bfd7367e0", "size": 1087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/operators.jl", "max_stars_repo_name": "lcw/OneDimensionalNodes.jl", "max_stars_repo_head_hexsha": "401fe49f0be45fdf76b9ccf8e41b751b834f0df8", "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": "test/operators.jl", "max_issues_repo_name": "lcw/OneDimensionalNodes.jl", "max_issues_repo_head_hexsha": "401fe49f0be45fdf76b9ccf8e41b751b834f0df8", "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": "test/operators.jl", "max_forks_repo_name": "lcw/OneDimensionalNodes.jl", "max_forks_repo_head_hexsha": "401fe49f0be45fdf76b9ccf8e41b751b834f0df8", "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": 31.9705882353, "max_line_length": 92, "alphanum_fraction": 0.4719411224, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.774918776782329}}
{"text": "function nlp_mi_005_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - function /\n\n    model = Model(optimizer)\n\n    @variable(model, x >= 0, Int)\n    @variable(model, y >= 0)\n\n    @objective(model, Min, x + y)\n    @NLconstraint(model, y >= 1 / (x + 0.1) - 0.5)\n    @NLconstraint(model, x >= y^(-2) - 0.5)\n    @NLconstraint(model, 4 / (x + y + 0.1) >= 1)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, 1.8164965727459055, tol = objective_tol)\n    return check_solution([x, y], [1, 0.816496581496872], tol = primal_tol)\nend\n", "meta": {"hexsha": "77252be2aab9ab07d76c6951aca3da513775b6df", "size": 741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-mi/005_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-mi/005_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-mi/005_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 26.4642857143, "max_line_length": 76, "alphanum_fraction": 0.645074224, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7748861195635021}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8ed00c06-7348-49dc-a9f2-041465beb969\nband1=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,track_hist=true)\n\n# \u2554\u2550\u2561 472fee46-6e48-47a7-9235-ccb7c460f735\nbegin \nRandom.seed!(1001)\nMultiArmBandit.Train!(band1,999,\u03f5 = 0.1)\nend \n\n# \u2554\u2550\u2561 1243d0ab-f95c-482d-b81e-3b3eb60907eb\nband1_df = MultiArmBandit.GetHistoryDF(band1)\n\n# \u2554\u2550\u2561 794d15a3-a4b4-4ffa-9afb-bb19d79e79e5\nplot(band1_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# \u2554\u2550\u2561 5e8e7408-aa48-4a2d-a427-40e8adf81d3c\nband1_summary = summary(band1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 65945e4f-17e9-40ba-870f-88da0c5d13d0\nbegin\nband2=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,track_hist=true)\nRandom.seed!(1102)\nMultiArmBandit.Train!(band2,999,\u03f5 = 0.03)\nband2_df = MultiArmBandit.GetHistoryDF(band2)\nband2_summary = summary(band2)\nend \n\n# \u2554\u2550\u2561 3566a579-84dc-4cb6-91ab-833d0d5e9782\nplot(band2_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 77d6e956-219e-40e9-978d-f7e0906a8d6c\nbegin\nband3=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q\u2080=5,track_hist=true)\nRandom.seed!(901)\nMultiArmBandit.Train!(band3,99,\u03f5 = 0.1)\nband3_df = MultiArmBandit.GetHistoryDF(band3)\nband3_summary = summary(band3)\nend \n\n# \u2554\u2550\u2561 043f9d99-e8b5-4b33-82ac-3870a2238f85\nplot(band3_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9f3d4773-ac0a-4dd2-992d-b549f58f4021\nbegin\nband4=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q\u2080=5,track_hist=true)\nRandom.seed!(555)\nMultiArmBandit.Train!(band4,2999,\u03f5 = 0.1,\u03b7=0.01)\nband4_df = MultiArmBandit.GetHistoryDF(band4)\nband4_summary = summary(band4)\nend \n\n# \u2554\u2550\u2561 3789a09f-73fb-4ca8-b267-bbe2d7b32848\nplot(band4_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2342907c-75e0-4126-b2df-6ce5a5901bf1\nbegin\nband5=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q\u2080=5,track_hist=true)\nRandom.seed!(1556)\nMultiArmBandit.Train!(band5,2999,\u03f5 = 0.1,\u03b7=1)\nband5_df = MultiArmBandit.GetHistoryDF(band5)\nband5_summary = summary(band5)\nend \n\n# \u2554\u2550\u2561 7c511272-01f8-4270-bdf7-f4f66e78df07\nplot(band5_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8bbfae0c-6648-4f42-a40c-ada03d17bb3a\nbegin\nband6=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q\u2080=0,track_hist=true)\nRandom.seed!(121)\nMultiArmBandit.Train!(band6,2999,\u03f5 = 0.1,\u03b7=0.01)\nband6_df = MultiArmBandit.GetHistoryDF(band6)\nband6_summary = summary(band6)\nend \n\n# \u2554\u2550\u2561 613e3215-4402-4ba2-8402-2ab5bf1f1247\nplot(band6_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bf545060-f55c-4a91-99f8-c41543c25ebb\nbegin\nband7=MultiArmBandit.CreateBandit(simdata,:Arm,:Y,Q\u2080=0,track_hist=true)\nRandom.seed!(13)\nMultiArmBandit.Train!(band7,2999,\u03f5 = 0.1,\u03b7=1)\nband7_df = MultiArmBandit.GetHistoryDF(band7)\nband7_summary = summary(band7)\nend \n\n# \u2554\u2550\u2561 5af03195-5199-48b9-8792-f02da75dc320\nplot(band7_df,x=:steps,y=:Q,color=:Group,Geom.line)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500b65dd189-456b-40ac-88fc-d05b5e29b396\n# \u2560\u2550db4a6b48-99a7-11eb-097b-676aed417c48\n# \u255f\u250038528382-a1ec-4117-88d4-fbcc019c7302\n# \u2560\u255060e50c4e-8120-4306-9c6c-9282fff8eb47\n# \u255f\u250065107f38-7916-43a4-b36f-1ef012c43b51\n# \u2560\u25508ed00c06-7348-49dc-a9f2-041465beb969\n# \u2560\u2550472fee46-6e48-47a7-9235-ccb7c460f735\n# \u2560\u25501243d0ab-f95c-482d-b81e-3b3eb60907eb\n# \u2560\u2550794d15a3-a4b4-4ffa-9afb-bb19d79e79e5\n# \u2560\u25505e8e7408-aa48-4a2d-a427-40e8adf81d3c\n# \u255f\u250032f83952-c660-4fde-8bd5-ae1a97e7bacd\n# \u2560\u255065945e4f-17e9-40ba-870f-88da0c5d13d0\n# \u2560\u25503566a579-84dc-4cb6-91ab-833d0d5e9782\n# \u255f\u2500a15c8f8f-f077-4758-a668-01c8b562ca95\n# \u2560\u255077d6e956-219e-40e9-978d-f7e0906a8d6c\n# \u2560\u2550043f9d99-e8b5-4b33-82ac-3870a2238f85\n# \u255f\u250050196d6d-8a52-4043-aa9f-e3f43a9ed2a1\n# \u2560\u25509f3d4773-ac0a-4dd2-992d-b549f58f4021\n# \u2560\u25503789a09f-73fb-4ca8-b267-bbe2d7b32848\n# \u255f\u25007825e432-9f3b-4099-bf37-0b1b3ccf38c1\n# \u2560\u25502342907c-75e0-4126-b2df-6ce5a5901bf1\n# \u2560\u25507c511272-01f8-4270-bdf7-f4f66e78df07\n# \u255f\u2500c1deba65-a93f-4992-958e-38a987346691\n# \u2560\u25508bbfae0c-6648-4f42-a40c-ada03d17bb3a\n# \u2560\u2550613e3215-4402-4ba2-8402-2ab5bf1f1247\n# \u255f\u2500e7772e4c-b798-4bdd-85c1-6ee291fce282\n# \u2560\u2550bf545060-f55c-4a91-99f8-c41543c25ebb\n# \u2560\u25505af03195-5199-48b9-8792-f02da75dc320\n# \u255f\u2500a94f1ce9-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 Threshold(input, threshold, value)\n    output = map(x -> x > threshold ? x : value, input)\n    return output\nend\n\nfunction Threshold!(input, threshold, value)\n    input = map(x -> x > threshold ? x : value, input)\n    return input\nend\n\nfunction ReLU(input)\n    return max(0, input)\nend\n\nfunction ReLU!(input)\n    input = max(0, input)\n    return input\nend\n\nfunction Hardtanh(input, min_value, max_value)\n    return map(x -> x > max_value ? 1 : x < min_value ? -1 : x, input)\nend\n\nfunction Hardtanh(input, min_value, max_value)\n    input = map(x -> x > max_value ? 1 : x < min_value ? -1 : x, input)\n    return input\nend\n\nfunction ReLU6(input)\n    return min(max(0, x), 6)\nend\n\nfunction ReLU6!(input)\n    input = min(max(0, x), 6)\n    return input\nend\n\nSigmoid(x) = 1 ./ (1 + exp(-x))\n\nTanh(x) = (exp(x) - exp(-x)) ./ (exp(x) + exp(-x))\n\nELU(x) = max(0, x) + min(0, alpha * (exp(x) - 1))\n\nfunction hardshrink(input, lambda)\n    return map(x -> x > lambda || x < lambda ? x : 0, input)\nend\n\nfunction hardshrink!(input, lambda)\n    input = map(x -> x > lambda || x < lambda ? x : 0, input)\nend\n\nLeakyReLU(x, negative_slope) = max(0, x) + negative_slope(0, x)\n\nLogSigmoid(x) = log(Sigmoid(x))\n\nSoftplus(x, beta) = 1 ./ beta * log(1 + exp(beta * x))\n\nfunction Softshrink(input, lambda)\n    output = map(input) do x\n        if x > lambda\n            return x - lambda\n        elseif x < -lambda\n            return x + lambda\n        else\n            return 0\n        end\n    end\n    return output\nend\n\nfunction Softshrink!(input, lambda)\n    input = map(input) do x\n        if x > lambda\n            return x - lambda\n        elseif x < - lambda\n            return x + lambda\n        else \n            return 0\n        end\n    end\n    return input\nend\n\nPReLU(x, a) = max(0, x) + a * min(0, x)\n\nSoftsign(x) = x ./ (1 + abs(x))\n\nTanhshrink(x) = x - Tanh(x)\n\nfunction Softmin(input)\n    shift(x) = max(input) - x\n    return map(x -> exp(-x - shift(x)) ./ sum(exp(map(y -> y - shift(x), input))), input)\nend\n\nfunction Softmin!(input)\n    shift(x) = max(input) - x\n    input = map(x -> exp(-x - shift(x)) ./ sum(map(y -> exp(y - shift(x)), input)), input)   \nend\n\nfunction Softmax(input)\n    return map(x -> exp(x - max(x)) ./ sum(map(y -> exp(y - max(x)), input)), input)\nend\n\nfunction Softmax!(input)\n    input = map(x -> exp(x - max(x)) ./ sum(map(y -> exp(y - max(x)), input)), input) \nend\n\nLogSoftmax(x) = log(Softmax(x))\n", "meta": {"hexsha": "f81fa2fd13672a2fad4e564075afaa76a906acd9", "size": 2425, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nn/activation.jl", "max_stars_repo_name": "Faldict/Torch.jl", "max_stars_repo_head_hexsha": "5f7b90647ef1dd1a9b5a8c87df8e1d50853bc1e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-27T04:08:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-27T04:08:46.000Z", "max_issues_repo_path": "src/nn/activation.jl", "max_issues_repo_name": "Faldict/Torch.jl", "max_issues_repo_head_hexsha": "5f7b90647ef1dd1a9b5a8c87df8e1d50853bc1e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nn/activation.jl", "max_forks_repo_name": "Faldict/Torch.jl", "max_forks_repo_head_hexsha": "5f7b90647ef1dd1a9b5a8c87df8e1d50853bc1e2", "max_forks_repo_licenses": ["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.247706422, "max_line_length": 93, "alphanum_fraction": 0.5756701031, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.774816957699858}}
{"text": "\"\"\"Computes the value of the function ackerman(n,m)\"\"\"\nfunction ack(m :: Int64, n :: Int64) :: Int64\n    if m == 0\n        return n + 1\n    elseif n == 0\n        return ack(m - 1, 1)\n    else\n        return ack(m - 1, ack(m, n - 1))\n    end\nend\n", "meta": {"hexsha": "e957d0b79e5bf486400ea44c98caf7116e12dbbb", "size": 245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "acker.jl", "max_stars_repo_name": "Sup3Legacy/pjulia-packages", "max_stars_repo_head_hexsha": "e11e9d9823dd0654c752b25693e947c5ea3bcae2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-24T09:20:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T10:31:55.000Z", "max_issues_repo_path": "acker.jl", "max_issues_repo_name": "Sup3Legacy/pjulia-packages", "max_issues_repo_head_hexsha": "e11e9d9823dd0654c752b25693e947c5ea3bcae2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "acker.jl", "max_forks_repo_name": "Sup3Legacy/pjulia-packages", "max_forks_repo_head_hexsha": "e11e9d9823dd0654c752b25693e947c5ea3bcae2", "max_forks_repo_licenses": ["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": 54, "alphanum_fraction": 0.5142857143, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7748059085196544}}
{"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\u2080, \u03c3)\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\u2080`: absolute zero (\u00b0C)\n- `\u03c3` (``W\\\\ m^{-2}\\\\ K^{-4}``) [Stefan-Boltzmann constant](https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law)\n\n# Note\n\n`K\u2080` and `\u03c3` are taken from [`Constants`](@ref) if not provided.\n\n\"\"\"\nfunction black_body(T, K\u2080, \u03c3)\n  T\u2096 = T - K\u2080\n  \u03c3 * (T\u2096^4.0)\nend\n\nfunction black_body(T)\n    constants = Constants()\n    black_body(T, constants.K\u2080, constants.\u03c3)\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- `\u03b5` object [emissivity](https://en.wikipedia.org/wiki/Emissivity) (not to confuse with \u03b5 the\nratio of molecular weights from [`Constants`](@ref)). A typical value for a leaf is 0.955.\n- `K\u2080`: absolute zero (\u00b0C)\n- `\u03c3` (``W\\\\ m^{-2}\\\\ K^{-4}``) [Stefan-Boltzmann constant](https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law)\n\n# Note\n\n`K\u2080` and `\u03c3` are taken from [`Constants`](@ref) if not provided.\n\n# Examples\n\n```julia\n# Thermal infrared radiation of water at 25 \u00b0C:\ngrey_body(25.0, 0.96)\n```\n\"\"\"\nfunction grey_body(T, \u03b5, K\u2080, \u03c3)\n  \u03b5 * black_body(T, K\u2080, \u03c3)\nend\n\nfunction grey_body(T, \u03b5)\n    constants = Constants()\n    grey_body(T, \u03b5, constants.K\u2080, constants.\u03c3)\nend\n\n\n\"\"\"\n    net_longwave_radiation(T\u2081,T\u2082,\u03b5\u2081,\u03b5\u2082,F\u2081,K\u2080,\u03c3)\n    net_longwave_radiation(T\u2081,T\u2082,\u03b5\u2081,\u03b5\u2082,F\u2081)\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\u2081 and has an emissivity \u03b5\u2081, and the object with\nwich it exchanges energy is at temperature T\u2082 and has an emissivity \u03b5\u2082.\n\nIf the result is positive, then the object of interest gain energy.\n\n# Arguments\n\n- `T\u2081` (Celsius degree): temperature of the target object (object 1)\n- `T\u2082` (Celsius degree): temperature of the object with which there is potential exchange (object 2)\n- `\u03b5\u2081`: object 1 emissivity\n- `\u03b5\u2082`: object 2 emissivity\n- `F\u2081`: view factor (0-1), *i.e.* visible fraction of object 2 from object 1 (see note)\n- `K\u2080`: absolute zero (\u00b0C)\n- `\u03c3` (``W\\\\ m^{-2}\\\\ K^{-4}``) [Stefan-Boltzmann constant](https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law)\n\n# Note\n\n`F\u2081`, 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\u2081 = 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\u2081F\u2081\u2082 = A\u2082F\u2082\u2081.\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\u2081` for a leaf is twice its common used leaf area, because `A\u2081` 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\u2097 = 25.0 ; T\u2090 = 20.0\n\u03b5\u2081 = 0.955 ; \u03b5\u2082 = 1.0\nR\u2097\u2097 = net_longwave_radiation(T\u2097,T\u2090,\u03b5\u2081,\u03b5\u2082,1.0)\nR\u2097\u2097\n\n# R\u2097\u2097 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\u00b2:\nleaf_area = 2e-4 # in m\u00b2\nR\u2097\u2097 * 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\u2081,T\u2082,\u03b5\u2081,\u03b5\u2082,F\u2081,K\u2080,\u03c3)\n    (black_body(T\u2082,K\u2080,\u03c3) - black_body(T\u2081,K\u2080,\u03c3)) / (1.0 / \u03b5\u2081 + 1.0 / \u03b5\u2082 - 1.0) * F\u2081\nend\n\nfunction net_longwave_radiation(T\u2081,T\u2082,\u03b5\u2081,\u03b5\u2082,F\u2081)\n    constants = Constants()\n    net_longwave_radiation(T\u2081,T\u2082,\u03b5\u2081,\u03b5\u2082,F\u2081,constants.K\u2080,constants.\u03c3)\nend\n\n\"\"\"\n    atmosphere_emissivity(T\u2090,e\u2090)\n\nEmissivity of the atmoshpere at a given temperature and vapor pressure.\n\n# Arguments\n\n- `T\u2090` (\u00b0C): air temperature\n- `e\u2090` (kPa): air vapor pressure\n- `K\u2080` (\u00b0C): absolute zero\n\n# Examples\n\n```julia\nT\u2090 = 20.0\nVPD = 1.5\natmosphere_emissivity(T\u2090, vapor_pressure(T\u2090,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\u00a0\u00bb. Plant,\nCell & Environment 18 (10): 1183\u20111200.\n\"\"\"\nfunction atmosphere_emissivity(T\u2090,e\u2090,K\u2080)\n    0.642 * (e\u2090 * 100 / (T\u2090 - K\u2080))^(1 / 7)\nend\n\nfunction atmosphere_emissivity(T\u2090,e\u2090)\n    atmosphere_emissivity(T\u2090,e\u2090,Constants().K\u2080)\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\u03c3 = 1\n\u03c4 = sqrt(10)\n\u03bc = 5\nn = 5\n\n\n\nX = [9.37;10.18;9.16;11.60;10.33]\n\u03bcn = mean(X)*n/\u03c3^2/(n/\u03c3^2 + 1/\u03c4^2) + \u03bc*(1/\u03c4^2)/(n/\u03c3^2 + 1/\u03c4^2)\n\u03c4n2 = 1/(n/\u03c3^2+1/\u03c4^2)\n\n# Hyperparameters\n# proposal step size\n\u03b4 = 3/100\nburnin = 2000\nN = 10000\n\u03b80 = 0.0\n\nfunction logf(\u03b8)\n    -sum((X.-\u03b8).^2)/2\u03c3^2 - (\u03b8-\u03bc)^2/2\u03c4^2\nend\n\nfunction proposal(x)\n    x + (rand()-0.5)*2 * \u03b4\nend\n\n\nsim = zeros(N)\nsim[1] = \u03b80\n@showprogress for i = 1:N-1\n    x = sim[i]\n    x_star = proposal(x)\n    \u0394 =  logf(x_star) - logf(x)\n    if log(rand())<\u0394\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))*\u03bcn, \"--\")\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(\u03bcn, sqrt(\u03c4n2)), 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 \ud835\udd4b, where \ud835\udd4b is a Metzler matrix (i.e. off-diagonal components are nonnegative)\n\nDenote a = -minimum(Diagonal(V)), which implies \ud835\udd4b + a * I has all positive entries. Applying Perron Frobenus, there a unique largest eigenvalue for aI + \ud835\udd4b, 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 \ud835\udd4b, which happens to be real.\nDenote \u03b7(\ud835\udd4b) the eigenvalue with largest real part of a matrix and \u03c1(\ud835\udd4b) the eigenvalue with largest modulus. We have\n\n    \u03b7(\ud835\udd4b) = \u03c1(\ud835\udd4b + a * I) - a\n\nMoreover, the associated eigenvector is real and strictly positive.\n\n\nNote that, when \ud835\udd4b is generator, its rows sum to zero. This means that eigenvalue with largest real part is \n    \u03b7(\ud835\udd4b) = 0\nIn other words, all eigenvalues of \ud835\udd4b have real part <= 0. This means that \ud835\udd4b is a singular M matrix.\n(another proof is to say that, for any s, sI - \ud835\udd4b is a non-singular M-Matrix for any s> 0, since there exists x = e such that (sI - \ud835\udd4b) * x > 0). \n\n\"\"\"\nfunction principal_eigenvalue(\ud835\udd4b; r0 = ones(size(\ud835\udd4b, 1)))\n    \u03b7, r = 0.0, r0\n    a = - minimum(diag(\ud835\udd4b))\n    try\n        vals, vecs = Arpack.eigs(\ud835\udd4b + a * I; v0 = collect(r0), nev = 1, which = :LM)\n        \u03b7 = vals[1]\n        r = vecs[:, 1]\n    catch\n        vals, vecs = KrylovKit.eigsolve(\ud835\udd4b + a * I, collect(r0), 1, :LM; maxiter = size(\ud835\udd4b, 1))\n        \u03b7 = vals[1]\n        r = vecs[1]\n    end\n    abs(imag(\u03b7)) <= eps() || @warn \"Principal Eigenvalue has an imaginary part\"\n    maximum(abs.(imag.(r))) <= eps() || @warn \"Principal Eigenvector has an imaginary part\"\n    real(\u03b7) - 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": "x = [1, 3, -5]\ny = [4, -2, -1]\nz = dot(x, y)\nz = x'*y\n", "meta": {"hexsha": "315d6e321c2b4526466f0aee9032ed1317f0b04a", "size": 54, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/dot-product.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/dot-product.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/dot-product.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": 10.8, "max_line_length": 15, "alphanum_fraction": 0.3148148148, "num_tokens": 35, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.955981348882942, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7748027225399378}}
{"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 \u2264 N && as[crt] - as[last] < d\n            crt += 1\n        end\n\n        if crt \u2265 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\u0332, d\u0304 = 0, maximum(as)\n    while d\u0304 - d\u0332 > 1\n        d = (d\u0304 + d\u0332) \u00f7 2\n        if check(d, M, as)\n            d\u0332 = d\n        else\n            d\u0304 = d\n        end\n    end\n\n    if check(d\u0304, M, as)\n        println(d\u0304)\n    else\n        println(d\u0332)\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": "## 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##\nusing Random\nfunction simple_spectral_eigenvector(A,nsteps=500)\n  @assert issymmetric(A) # expensive, but useful...\n  Random.seed!(1)\n  n = size(A,1)\n  d = vec(sum(A,dims=1))\n  nd2 = d'*d\n  x = randn(n)\n  # project x orthogonal to d\n  x .-= ((d'*x)/(d'*d)).*d\n  x ./= x'*(d.*x) # normalize\n  for i=1:nsteps\n    x = (A*x)./d          # matrix-vector\n    x .-= ((d'*x)/nd2).*d\n    x ./= sqrt(x'*(d.*x)) # normalize\n    # make sure the first component is positive\n    x .*= sign(x[1])\n  end\n\n  return x\nend\nf = simple_spectral_eigenvector(A)\n##\nusing MatrixNetworks\nf2 = fiedler_vector(A)[1]\n# make sure the first component is positive\nf2 .*= sign(f2[1])\n##\nnorm(f-f2)\n## why different? convergence is slow :(\nf = simple_spectral_eigenvector(A,2500)\nnorm(f-f2)\n## why different? convergence is slow :(\nf = simple_spectral_eigenvector(A,4000)\nnorm(f-f2)\n##\nusing Plots\nx = f\np = sortperm(x) # this gets things to draw in the right z-order\nscatter(xy[p,1],xy[p,2], marker_z=x[p],colorbar=false,alpha=0.5,\n  color=:magma,\n  size=(1200,1200),\n  markerstrokecolor=:white,markerstrokewidth=0.0,label=\"\",framestyle=:none,\n  background=nothing,dpi=220)\nsavefig(\"spectral-mnist-500.png\")\n##\nusing Plots\nx = f2\np = sortperm(x) # this gets things to draw in the right z-order\nscatter(xy[p,1],xy[p,2], marker_z=x[p],colorbar=false,alpha=0.5,\n  color=:magma,\n  size=(1200,1200),\n  markerstrokecolor=:white,markerstrokewidth=0.0,label=\"\",framestyle=:none,\n  background=nothing,dpi=220)\nsavefig(\"spectral-mnist-converged.png\")  \n## Let's watch spectra converge\nusing Plots\nusing GraphRecipes\nRandom.seed!(1)\nfunction spectral_convergence_animation(A,xy,nsteps_per_frame,nframes)\n  @assert issymmetric(A) # expensive, but useful...\n  Random.seed!(1)\n  n = size(A,1)\n  d = vec(sum(A,dims=1))\n  sumd = sum(d)\n  x = randn(n)\n  # project x orthogonal to d\n  x .-= (d'*x)/sum(d)\n  x ./= x'*(d.*x) # normalize\n\n  anim = @animate for i=1:nframes\n\n    f = zeros(n)\n    for j=1:nsteps_per_frame\n      x = (A*x)./d          # matrix-vector\n      x .-= (d'*x)/sum(d)   # project out\n      x ./= sqrt(x'*(d.*x)) # normalize\n      # make sure the first component is positive\n      #x .*= sign(x[1])\n      f .+= x./nsteps_per_frame\n    end\n\n    p = sortperm(f) # this gets things to draw in the right z-order\n    scatter(xy[p,1],xy[p,2], marker_z=f[p],colorbar=false,alpha=0.5,\n      color=:magma,\n      size=(1200,1200),dpi=100,\n      markerstrokecolor=nothing,markerstrokewidth=0,label=\"\",framestyle=:none,background=:black)\n  end\n  return anim\nend\nanim = spectral_convergence_animation(A,xy,10,500)\ngif(anim,\"spectral-convergence-mnist.gif\",fps=30)\n##\nanim = spectral_convergence_animation(A,xy,1,500)\ngif(anim,\"spectral-convergence-mnist-1-500.gif\",fps=30)\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", "meta": {"hexsha": "87b34053663c15957943b49b28ff2007892d9002", "size": 3523, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5-unit-4-demos/spectral-clustering-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/spectral-clustering-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/spectral-clustering-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": 27.9603174603, "max_line_length": 96, "alphanum_fraction": 0.6727221118, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7747967628501791}}
{"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    \u03b3 = 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 \u03b3\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    \u03b3 = 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 \u03b3\nend\n\n\n\"\"\"\n$(SIGNATURES)\n\nCalculate speed of sound\n\"\"\"\nsound_speed(\u03bb::Real, \u03b3::Real) = (0.5 * \u03b3 / \u03bb)^0.5\n\n\"\"\"\n$(SIGNATURES)\n\"\"\"\nsound_speed(prim::AV, \u03b3) = sound_speed(prim[end], \u03b3)\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\nCalculate sound speed in mixture\n\"\"\"\nfunction sound_speed(prim::AM, \u03b3)\n    c = similar(prim, axes(prim, 2))\n    for j in eachindex(c)\n        c[j] = sound_speed(prim[end, j], \u03b3)\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": "using GeneralizedSampling\nimport IntervalWavelets: unit\nusing Base.Test\n\nprintln(\"Testing least squares solver...\")\n\n#=\nTest the least squares solvers:\n- Solution with Freq2Wave and the collected version should be identical.\n- When sampling from a scaling function used in the Freq2Wave type, the solution should be a unit vector.\n=#\n\n\n# ------------------------------------------------------------\n# Reconstruct unit vector\n\nJ = 3\nM = 2^(J+1)\nN = 2^J\nxi = grid(M, 0.5)\nwavename = \"db2\"\nvm = van_moment(wavename)\n\nT = Freq2Wave(xi, wavename, J)\n\nfor k = 1:N\n\tif k <= vm\n\t\tF = FourScalingFunc(xi, wavename, 'L', J)\n\t\tf = F[:,k]\n\telseif k > N-vm\n\t\tF = FourScalingFunc(xi, wavename, 'R', J)\n\t\tf = F[:,k-N+vm]\n\telse\n\t\ttrans = k - div(N,2) - 1\n\t\tf = FourDaubScaling(xi, vm, J, trans)\n\tend\n\ty = T \\ f\n\n\tu = unit(Complex{Float64}, length(y), k)\n\t#@show k, norm( y - u )\n\t@test_approx_eq_eps y u 1e-4\nend\n\n\n# ------------------------------------------------------------\n\nbegin\n\tJ = 10\n\tM = 2^(J+2)\n\tN = 2^J\n\n\t# Uniform samples\n\txi = grid(M, 0.5)\n\tTU = Freq2Wave(xi, \"Haar\", J)\n\tAU = collect(TU)\n\n\tb = rand(M)\n\tx0 = rand(N)\n\n\tx1 = AU \\ b\n\tx2 = TU \\ b\n\n\t#@show norm(x1 - x2, Inf)\n\t@test_approx_eq_eps x1 x2 1e-5\n\n\n\t# Non-uniform samples: Requires high M/N ratio \n\tK = N/2\n\txi = 2*K*rand(M) - K\n\tsort!(xi)\n\tTNU = Freq2Wave(xi, \"Haar\", J, K)\n\tANU = collect(TNU)\n\tb = rand(M) + rand(M)*im\n\n\tbb = b .* get(TNU.weights)\n\tz1 = ANU \\ bb\n\tz2 = TNU \\ b\n\n\t#@show norm(z1 - z2, Inf)\n\t@test_approx_eq_eps z1 z2 1e-4\nend\n\n# 2D\nbegin\n\tJ = 5\n\tM = 2^(J+1)\n\tN = 2^J\n\n\t# Uniform samples\n\txi = grid((M,M), 0.5)\n\tTU = Freq2Wave(xi, \"Haar\", J)\n\tAU = collect(TU)\n\tb = rand(size(TU,1))\n\n\tx1 = AU \\ b\n\tx2 = TU \\ b\n\n\t#@show norm(x1 - vec(x2), Inf)\n\t@test_approx_eq_eps x1 x2 1e-5\n\n\t# Non-uniform samples: Requires high M/N ratio \n\tK = N/2\n\txi = 2*K*rand(M^2,2) - K\n\tTNU = Freq2Wave(xi, \"Haar\", J, K)\n\tANU = collect(TNU)\n\tb = rand(M^2) + rand(M^2)*im\n\n\tbb = b .* get(TNU.weights)\n\tz1 = ANU \\ bb\n\tz2 = TNU \\ b\n\n\t#@show norm(z1 - z2, Inf)\n\t@test_approx_eq_eps z1 z2 1e-4\nend\n\n", "meta": {"hexsha": "1e98ee251a6cf4afda1dba7bb654b34b1f400d8e", "size": 2038, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/CGNR.jl", "max_stars_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": "test/CGNR.jl", "max_issues_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": "test/CGNR.jl", "max_forks_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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.5689655172, "max_line_length": 105, "alphanum_fraction": 0.5701668302, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7747967597178762}}
{"text": "using ParetoFront\nusing Test\n\n\n# Suppose we are in two dimensions and want min, min to dominate.\n# We know then, that the point that has a minimum value of y will dominate\n# all points to the right of it, ie  at x > x(at ymin) will be dominated\n# and so for all x on the Pareto front we must have x < x(at ymin)\n# and also the point with the minimum value of x will dominate all \n# points that are above it, ie that y > y(at xmin) will be dominated\n# and so for all y on the Pareto front we must have y < y(at xmin)\nfunction test_min_blob(n)\n    v = randn(n, 2)\n    ((xmin, ymin), (ix, iy)) = findmin(v, dims=1)\n    ymax = v[ix[1], 2]\n    xmax = v[iy[1], 1]\n    pareto = get_pareto(v, min_idxs=[1,2], max_idxs=[])\n    front = Matrix(reduce(hcat, collect(pareto))')\n    pxmax, pymax = maximum(front, dims=1)\n    return pxmax <= xmax && pymax <= ymax\nend\n\n# the test for max, max as optimal\nfunction test_max_blob(n)\n    v = randn(n, 2)\n    ((xmax, ymax), (ix, iy)) = findmax(v, dims=1)\n    ymin = v[ix[1], 2]\n    xmin = v[iy[1], 1]\n    pareto = get_pareto(v, min_idxs=[], max_idxs=[1,2])\n    front = Matrix(reduce(hcat, collect(pareto))')\n    pxmin, pymin = minimum(front, dims=1)\n    return pxmin >= xmin && pymin >= ymin\nend\n\n\n@testset \"ParetoFront.jl\" begin\n    for i in 10 .^ (1:6)\n        @test test_min_blob(i)\n        @test test_max_blob(i)\n    end\nend\n\n", "meta": {"hexsha": "100eb3dc211b995630136031c2ea08ef09795ee1", "size": 1360, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "macd/ParetoFront.jl", "max_stars_repo_head_hexsha": "99d42620dbd1aba5401a682db35ba9b9a08f4c39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-05T04:00:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T16:28:02.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "macd/ParetoFront.jl", "max_issues_repo_head_hexsha": "99d42620dbd1aba5401a682db35ba9b9a08f4c39", "max_issues_repo_licenses": ["MIT"], "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": "macd/ParetoFront.jl", "max_forks_repo_head_hexsha": "99d42620dbd1aba5401a682db35ba9b9a08f4c39", "max_forks_repo_licenses": ["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.6279069767, "max_line_length": 74, "alphanum_fraction": 0.6389705882, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7747967580406404}}
{"text": "# Test that the minimum image distance is correctly calculated\n\n@testset \"Minimum image distance\" begin\n@testset \"fcc\" begin\n    @test MkCell.score_image_distance(fcc1*cellfcc)   \u2248 0.7071067811865476\n    @test MkCell.score_image_distance(fcc4*cellfcc)   \u2248 1.000\n    @test MkCell.score_image_distance(fcc7*cellfcc)   \u2248 1.224744871391589\n    @test MkCell.score_image_distance(fcc13*cellfcc)  \u2248 1.5811388300841898\n    @test MkCell.score_image_distance(fcc23*cellfcc)  \u2248 1.7320508075688772\n    @test MkCell.score_image_distance(fcc26*cellfcc)  \u2248 1.8708286933869707\n    @test MkCell.score_image_distance(fcc32*cellfcc)  \u2248 2.000\n    @test MkCell.score_image_distance(fcc38*cellfcc)  \u2248 2.1213203435596424\n    @test MkCell.score_image_distance(fcc50*cellfcc)  \u2248 2.345207879911715\n    @test MkCell.score_image_distance(fcc70*cellfcc)  \u2248 2.5495097567963922\n    @test MkCell.score_image_distance(fcc92*cellfcc)  \u2248 2.7386127875258306\n    @test MkCell.score_image_distance(fcc96*cellfcc)  \u2248 2.8284271247461903\n    @test MkCell.score_image_distance(fcc100*cellfcc) \u2248 2.9154759474226504\n    @test MkCell.score_image_distance(fcc108*cellfcc) \u2248 3.000\nend;\n@testset \"cubic\" begin\n    @test MkCell.score_image_distance(cubic1*cellcubic)   \u2248 1.000\n    @test MkCell.score_image_distance(cubic3*cellcubic)   \u2248 1.4142135623730951\n    @test MkCell.score_image_distance(cubic7*cellcubic)   \u2248 1.7320508075688772\n    @test MkCell.score_image_distance(cubic8*cellcubic)   \u2248 2.000\n    @test MkCell.score_image_distance(cubic13*cellcubic)  \u2248 2.23606797749979\n    @test MkCell.score_image_distance(cubic14*cellcubic)  \u2248 2.449489742783178\n    @test MkCell.score_image_distance(cubic24*cellcubic)  \u2248 2.8284271247461903\n    @test MkCell.score_image_distance(cubic27*cellcubic)  \u2248 3.000\n    @test MkCell.score_image_distance(cubic33*cellcubic)  \u2248 3.1622776601683795\n    @test MkCell.score_image_distance(cubic38*cellcubic)  \u2248 3.3166247903554\n    @test MkCell.score_image_distance(cubic52*cellcubic)  \u2248 3.605551275463989\n    @test MkCell.score_image_distance(cubic56*cellcubic)  \u2248 3.7416573867739413\n    @test MkCell.score_image_distance(cubic64*cellcubic)  \u2248 4.000\n    @test MkCell.score_image_distance(cubic73*cellcubic)  \u2248 4.123105625617661\n    @test MkCell.score_image_distance(cubic76*cellcubic)  \u2248 4.242640687119285\n    @test MkCell.score_image_distance(cubic93*cellcubic)  \u2248 4.358898943540674\n    @test MkCell.score_image_distance(cubic100*cellcubic) \u2248 4.47213595499958\nend;\n@testset \"bcc\" begin\n    @test MkCell.score_image_distance(bcc1*cellbcc)   \u2248 0.8660254037844386\n    @test MkCell.score_image_distance(bcc2*cellbcc)   \u2248 1.000\n    @test MkCell.score_image_distance(bcc6*cellbcc)   \u2248 1.4142135623730951\n    @test MkCell.score_image_distance(bcc9*cellbcc)   \u2248 1.6583123951777\n    @test MkCell.score_image_distance(bcc16*cellbcc)  \u2248 2.000\n    @test MkCell.score_image_distance(bcc21*cellbcc)  \u2248 2.179449471770337\n    @test MkCell.score_image_distance(bcc25*cellbcc)  \u2248 2.23606797749979\n    @test MkCell.score_image_distance(bcc28*cellbcc)  \u2248 2.449489742783178\n    @test MkCell.score_image_distance(bcc35*cellbcc)  \u2248 2.598076211353316\n    @test MkCell.score_image_distance(bcc48*cellbcc)  \u2248 2.8284271247461903\n    @test MkCell.score_image_distance(bcc53*cellbcc)  \u2248 2.958039891549808\n    @test MkCell.score_image_distance(bcc54*cellbcc)  \u2248 3.000\n    @test MkCell.score_image_distance(bcc65*cellbcc)  \u2248 3.278719262151\n    @test MkCell.score_image_distance(bcc84*cellbcc)  \u2248 3.3166247903554\n    @test MkCell.score_image_distance(bcc91*cellbcc)  \u2248 3.570714214271425\n    @test MkCell.score_image_distance(bcc103*cellbcc) \u2248 3.605551275463989\n    @test MkCell.score_image_distance(bcc107*cellbcc) \u2248 3.7416573867739413\n    @test MkCell.score_image_distance(bcc112*cellbcc) \u2248 3.840572873934304\n    @test MkCell.score_image_distance(bcc128*cellbcc) \u2248 4.000\nend;\n@testset \"hcp\" begin\n    @test MkCell.score_image_distance(hcp1*cellhcp)   \u2248 0.5612\n    @test MkCell.score_image_distance(hcp3*cellhcp)   \u2248 0.9164357624332797\n    @test MkCell.score_image_distance(hcp6*cellhcp)   \u2248 0.972026913207654\n    @test MkCell.score_image_distance(hcp8*cellhcp)   \u2248 1.1224\n    @test MkCell.score_image_distance(hcp11*cellhcp)  \u2248 1.3359232113660824\n    @test MkCell.score_image_distance(hcp14*cellhcp)  \u2248 1.4490121692610682\n    @test MkCell.score_image_distance(hcp16*cellhcp)  \u2248 1.4847956357694483\n    @test MkCell.score_image_distance(hcp21*cellhcp)  \u2248 1.7448417081978143\n    @test MkCell.score_image_distance(hcp27*cellhcp)  \u2248 1.9168629232855088\n    @test MkCell.score_image_distance(hcp37*cellhcp)  \u2248 2.023435375790391\n    @test MkCell.score_image_distance(hcp39*cellhcp)  \u2248 2.0746696957989883\n    @test MkCell.score_image_distance(hcp42*cellhcp)  \u2248 2.149232371491428\n    @test MkCell.score_image_distance(hcp53*cellhcp)  \u2248 2.221293593081893\n    @test MkCell.score_image_distance(hcp62*cellhcp)  \u2248 2.358820914496619\n    @test MkCell.score_image_distance(hcp65*cellhcp)  \u2248 2.4246611199643273\n    @test MkCell.score_image_distance(hcp69*cellhcp)  \u2248 2.4462140871150257\n    @test MkCell.score_image_distance(hcp76*cellhcp)  \u2248 2.6122438375210435\n    @test MkCell.score_image_distance(hcp80*cellhcp)  \u2248 2.6718464227321648\n    @test MkCell.score_image_distance(hcp88*cellhcp)  \u2248 2.7301481180819964\n    @test MkCell.score_image_distance(hcp90*cellhcp)  \u2248 2.749307287299839\n    @test MkCell.score_image_distance(hcp100*cellhcp) \u2248 2.806\nend;\nend;", "meta": {"hexsha": "cd2129e4397af5701a5017f05ca3eed2e8f7ec32", "size": 5388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/paper/dmin.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": "test/paper/dmin.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": "test/paper/dmin.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": 64.9156626506, "max_line_length": 78, "alphanum_fraction": 0.7780252413, "num_tokens": 1960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7747948578233306}}
{"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\u00e9zier 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\u00e9zier 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\u00e9zier 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 \u2212 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 01506de2-918a-11eb-2a4d-c554a6e54631\nTableOfContents(title=\"\ud83d\udcda Table of Contents\", aside=true)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 83912943-a847-420a-bfdb-450027b631e8\nmd\"\"\"\n# Fahrenheit and Celsius Data Set\n\"\"\"\n\n# \u2554\u2550\u2561 280d112f-d34a-4cc4-9e3a-4ebbfcd5eb51\nn = 10\n\n\n# \u2554\u2550\u2561 b5031c96-db57-4baf-b271-6bb12e29de9b\nx = sort((rand( -10:100, n)))\n\n# \u2554\u2550\u2561 c2f77e8f-a8c0-4144-a8b4-b25dd98ed234\ny = 5/9 .* x  .- 17.7777777 #  same as y =  5/9 .* (x .- 32)\n\n# \u2554\u2550\u2561 ad161b98-f4a1-42ac-ad4f-8b71fabcfde9\nbegin\t\n\tplot(x,y, m=:c, mc=:red,legend=false)\n\txlabel!(\"\u00b0F\")\n\tannotate!(-4,16,text(\"\u00b0C\",11))\n\t# plot!( x, (x.-30)./2) Dave's cool approximation\nend\n\n# \u2554\u2550\u2561 8e422886-74ef-4c0f-be1e-fda238c8db44\n[x y]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 41e05b1e-8b5e-45e3-91bb-01355ade9f3d\nmd\"\"\"\n### Data Frame by Columns with labels\n\"\"\"\n\n# \u2554\u2550\u2561 9d2e3861-ca36-406e-952d-831ca3947e44\ndata = DataFrame(\u00b0F=x,\u00b0C=y) # Label = data\n\n# \u2554\u2550\u2561 e73854ed-3581-41c4-ada5-e48242033759\nmd\"\"\"\n### Data Frame with a matrix\n\"\"\"\n\n# \u2554\u2550\u2561 9873d944-b611-46f9-82a7-0cf714a3078c\nbegin\n\tdata2 = DataFrame([x  y]) # convert Matrix to DataFrame\n    rename!(data2,[\"\u00b0F\",\"\u00b0C\"]) # add column labels\nend\n\n# \u2554\u2550\u2561 2be44753-afee-4125-b6bc-8866d2293dc2\nMatrix(data2) # Convert back to a matrix (lose label information)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a755e58a-b16c-4d3b-a85f-81ccf374793f\nmd\"\"\"\n# Reading/Writing CSV (comma separated values) Files\n\"\"\"\n\n# \u2554\u2550\u2561 f1e10fb7-adac-4083-8977-616a505fd591\nmd\"\"\"\n  ## Writing Data to a CSV  file \nreadable by spreadsheet software.\n\"\"\"\n\n# \u2554\u2550\u2561 2e42986c-2de3-49e6-9c29-a7313c0b1da8\nCSV.write(\"testCSVwrite.csv\", data)\n\n# \u2554\u2550\u2561 22758dd6-9d04-4616-ba99-1430f2dedf9a\nmd\"\"\"\n ## Reading Data from a CSV file to a DataFrame\n\"\"\"\n\n# \u2554\u2550\u2561 aff6a616-6d8b-4584-a6f2-195decef7774\ndata_again = CSV.read(\"testCSVwrite.csv\", DataFrame ) \n\n# \u2554\u2550\u2561 338da13a-3c26-4366-a669-ac3e24f31577\ndata_again[:,\"\u00b0F\" ] #or data_again[:,1]\n\n# \u2554\u2550\u2561 5a742546-1e4d-4aee-bed1-cb10c543e439\ndata_again[:,1]\n\n# \u2554\u2550\u2561 6a9c8c9a-fac7-42f7-976d-3168132cae48\nmd\"\"\"\n# Noisy Data\n## Add some random noise to the celsius readings\n\"\"\"\n\n# \u2554\u2550\u2561 3c038b68-8676-4877-9720-38da7c4e0e0e\nbegin\n\tnoisy_data = copy(data)  # Noisy DataFrame\n\tnoisy_data[:, \"\u00b0C\" ] .+= noise * randn(n)\n\tyy = noisy_data[:, \"\u00b0C\" ]\n\tnoisy_data\nend\n\n# \u2554\u2550\u2561 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!(\"\u00b0F\")\n\tannotate!(-15,16,text(\"\u00b0C\",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# \u2554\u2550\u2561 83c28c76-2eab-49f9-9999-05df85054520\nmd\"\"\"\n# The noise slider (so I can find it easily)\n\"\"\"\n\n# \u2554\u2550\u2561 ba671804-dc6d-415c-89de-9cf6294907b3\nmd\"\"\"\nnoise = $(@bind noise Slider(0:.5:1000, show_value = true ))\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0489e5d8-51ca-4955-83e1-95ea353d9cf2\nols = lm(@formula(\u00b0C ~ \u00b0F), noisy_data)\n\n# \u2554\u2550\u2561 9a65aee4-ab8e-4ab7-be6f-cc2a2e9d5127\nnoisy_data\n\n# \u2554\u2550\u2561 c3539f42-6ca7-47fb-9707-4d11c9e76643\nmd\"\"\"\nThis lecture is about explaining the meaning and significance to every part of this table.\n\"\"\"\n\n# \u2554\u2550\u2561 469d809f-424f-4595-ad43-a5b2cc055304\nmd\"\"\"\n# Regression a few ways \n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9eb7caaa-438d-4bcb-9c54-4a0fa72c61de\nb, m = [ one.(x) x]\\ yy  # The mysterious linear algebra solution using \"least squares\"\n\n# \u2554\u2550\u2561 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\u1d49 = sum( x0 .* y0 ) / sum(  x0.^2 ) # slope estimate\n\tb\u1d49 = mean(y) - m\u1d49 * mean(x) # intercept estimate\n\t\n\ts2\u1d49 = sum(  (m\u1d49.*x .+ b\u1d49 .- y).^2 ) /(n-2) # noise estimate\n\tb\u1d49,m\u1d49,s2\u1d49\nend\n\n# \u2554\u2550\u2561 71590890-38b6-440e-b61b-ece6c49ac602\nlinear_regression(x,yy)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f64815e2-44b8-4585-9269-9a62655c984c\nmd\"\"\"\n# Demystifying the word \"Model\"\n\n    Step I:  The Model is y = m*x + b + \u03c3*randn() . \n    This means that out there in the real world are b, m, and \u03c3.  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\u1d49,  m\u1d49, and \u03c3\u1d49.  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 \u03c3 which are unknown.  The predictor variable x which is considered fixed and known.  The response variable y which is considered noisy.\n\"\"\"\n\n# \u2554\u2550\u2561 feb3c45e-88f4-4ffc-a4a0-e89489187c8d\nmd\"\"\"\n## Understanding the relationship `\u00b0C ~ 1 + \u00b0F`\n\"\"\"\n\n# \u2554\u2550\u2561 99069dd7-e088-4626-aa29-e48d6f9a474e\nols\n\n# \u2554\u2550\u2561 051a9e38-9a84-4ead-96fa-24c86c2b9f2d\nmd\"\"\"\n`\u00b0C ~ 1 + \u00b0F` means the celsius (y) is (Coef1)*1 + (Coef2)*(\u00b0F),\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# \u2554\u2550\u2561 2f33ee51-0725-46c2-9f1b-a61cd68abab1\nmd\"\"\"\n# Simulating the real world: running many noisy models\n\"\"\"\n\n# \u2554\u2550\u2561 e4acd97b-22f7-4812-9898-1a485887a5f2\nfunction simulate(\u03c3,howmany)\n\t[linear_regression(x,y .+ \u03c3 * randn(length(x)))   for i=1:howmany]\n\t#[linear_regression(x,y .+ (\u03c3 * sqrt(12)) * (-.5 .+ rand(length(x))))   for i=1:howmany]\n\t# [linear_regression(x,y .+ (\u03c3 ) * ( rand([-1,1],length(x))))   for i=1:howmany]\n\t\nend\n\n# \u2554\u2550\u2561 4e413b40-81c4-4160-9d01-046c2d179a06\nhowmany = 100_000\n\n# \u2554\u2550\u2561 7b94db0d-f46b-4621-9413-1dc787ae9a39\nmd\"\"\"\n## Julia: underscore as a digits separator\n\"\"\"\n\n# \u2554\u2550\u2561 51a28b67-ad64-4cf2-a0e6-a78fb101eb15\ns = simulate(\u03c3, howmany)\n\n# \u2554\u2550\u2561 d451af49-3139-4329-a885-a210b1760f74\ns[1] # first simulation,  intercept, slope, estimation of noise \u03c3\n\n# \u2554\u2550\u2561 c7455f7a-9c72-42f5-8238-1799cad96f6c\nmd\"\"\"\n## Simulated intercepts ($howmany simulations)\n\"\"\"\n\n# \u2554\u2550\u2561 d2971801-2cdb-4b9f-8ec8-c74cbb2a0b31\nmd\"\"\"\n\u03c3 = $(@bind \u03c3 Slider(0:.1:3, show_value=true, default=1))\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1429be09-a31f-415f-9c3d-f32b085ef68d\nmd\"\"\"\nExperimental mean of the intercept\n\"\"\"\n\n# \u2554\u2550\u2561 da321202-0dc5-44ad-aac0-f3ea0d229243\nmean(first.(s)), -17.777777\n\n# \u2554\u2550\u2561 2aceb366-a067-4271-9362-c320f4735ed1\nmd\"\"\"\nExperimental std of the intercept\n\"\"\"\n\n# \u2554\u2550\u2561 58f548fd-f6d0-479d-8469-bc886783f9a7\nstd( first.(s))\n\n# \u2554\u2550\u2561 07be9435-bc07-4a18-aad8-3ff19f5bcce4\nmd\"\"\"\nStatisticians know an exact formula for the theoretical std of the intercept\n\"\"\"\n\n# \u2554\u2550\u2561 1a6ad08d-c3bb-47e7-bdee-156bbff3aeda\n    sb = \u03c3 * norm(x)  / norm(x.-mean(x)) / sqrt(n)\n        \n\n# \u2554\u2550\u2561 c55e4894-db71-4729-a1a1-5f68b45e3bf5\nmd\"\"\"\n## Simulated slopes ($howmany simulations)\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5c7a7361-f0e7-473a-9e38-226828aa00ca\nmd\"\"\"\nSample mean of the slope\n\"\"\"\n\n# \u2554\u2550\u2561 acf0e90e-8f1f-451f-9f0f-70a0bcc7efca\nmean(getindex.(s,2)), .555555\n\n# \u2554\u2550\u2561 c9f65e15-f222-4a88-98c2-9e1d8b5ec3eb\nmd\"\"\"\nSample std of the slope.\n\"\"\"\n\n# \u2554\u2550\u2561 2589a369-8b21-406d-906d-71b18e4c7895\nstd( getindex.(s,2))\n\n# \u2554\u2550\u2561 ed6a0e6a-2d0c-4f77-9b08-1a5b5d56dd34\nmd\"\"\"\nStatisticians know a formula for the theoretical std of the slope.\n\"\"\"\n\n# \u2554\u2550\u2561 61d1c1f7-e070-413b-8a92-76f44d237206\n \u03c3  / norm(x.-mean(x))\n\n# \u2554\u2550\u2561 94d80ad6-0403-4322-aa9f-647c291c19d7\nmd\"\"\"\n## Simulated \u03c3 ($howmany simulations)\n\"\"\"\n\n# \u2554\u2550\u2561 ce89b805-39a2-49e6-8781-c557aa73ed27\nbegin\t\n\thistogram( last.(s) ./ (\u03c3^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# \u2554\u2550\u2561 75f9b5e9-775d-4767-9da6-222f977da686\nmean( last.(s)  )\n\n# \u2554\u2550\u2561 797c9f2f-0b85-4435-b1c0-edc8cf67f738\n\u03c3^2\n\n# \u2554\u2550\u2561 6e0b2452-9f8b-4730-8072-a663704893c5\nstd(last.(s))\n\n# \u2554\u2550\u2561 bf537a3a-b7c6-4c64-8b44-85511c3d492e\n (\u03c3^2/ sqrt((n-2)/2))\n\n# \u2554\u2550\u2561 1340818c-3391-420b-aa94-acaea8a47d7d\nmd\"\"\"\n# The Linear Model Table\n\"\"\"\n\n# \u2554\u2550\u2561 829607ff-25e0-4585-9c5c-d132ecb86cc8\nols # = lm(@formula(\u00b0C ~ \u00b0F), noisy_data)\n\n# \u2554\u2550\u2561 3fc0a4a8-6719-4920-99c7-bd576225214e\n-24.3784  / 19.0397\n\n# \u2554\u2550\u2561 24a7ad28-936c-47dc-bc53-d1ddbf39d05d\n0.686156 / 0.330459\n\n# \u2554\u2550\u2561 9233dc6a-7578-4d72-b0c2-c3bb110a9fbe\nmd\"\"\"\n## The Coef column is just the regression formula for the best line\n\"\"\"\n\n# \u2554\u2550\u2561 07e02bb6-380d-40dd-86ad-19d713cd1657\nm\u1d49, b\u1d49, \u03c3\u00b2\u1d49 =  linear_regression(x, yy)\n\n# \u2554\u2550\u2561 b14593ba-cb8c-4f28-8fb0-2d2df479357b\nmd\"\"\"\n## The Std. error column\n\"\"\"\n\n# \u2554\u2550\u2561 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) = \u03c3 * norm(x)  / norm(x.-mean(x)) / sqrt(n)`\n\n` std(slope) =  \u03c3  / norm(x.-mean(x))`\n\"\"\"\n\n# \u2554\u2550\u2561 08f43fff-fbd8-468f-8b3b-efd1829f4fc0\nmd\"\"\"\nLet's replace \u03c3 with our estimate \u221a\u03c3\u00b2\u1d49\n\"\"\"\n\n# \u2554\u2550\u2561 43ec6124-c3e5-4f34-b0d9-1a0b069aa3e0\nsqrt(\u03c3\u00b2\u1d49) * norm(x) / norm(x.-mean(x)) / sqrt(n)\n\n# \u2554\u2550\u2561 3fe71215-bbf2-40e9-bcfc-0bc9b3ac94c8\nsqrt(\u03c3\u00b2\u1d49) / norm(x.-mean(x))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8851dca3-e1a6-46b2-9745-f175ef0b0fae\nmd\"\"\"\n## The t column\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 13858c0a-3e7a-4742-a821-97dd9a45109d\nmd\"\"\"\n### The t-distribution\n\"\"\"\n\n# \u2554\u2550\u2561 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 \u03c7 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 \u03c3 is unknown and is merely being estimated.\n\"\"\"\n\n# \u2554\u2550\u2561 305e4dfc-af7d-4667-8da8-a7ba5fd20fa6\nrand_t(k) = sqrt(k)* randn() / norm( randn(k))\n\n# \u2554\u2550\u2561 a648ba4f-fec4-4fa7-b328-1b52070224eb\nmd\"\"\"\nk = $(@bind k Slider(3:100, show_value=true))\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3d0ea801-d66b-4e4e-90da-3a7dce28140d\nmd\"\"\"\n# Degrees of Freedom\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fb495ba4-52e6-4e0d-bd9c-981700edfebc\nmd\"\"\"\nHow many degrees of freedom are in a \"demeaned\" vector of normals?\n\"\"\"\n\n# \u2554\u2550\u2561 cdc4b25d-d05f-40c8-9c79-265876f01523\n   \nmean([ (v = randn(17);v.-=mean(v);sum(v.^2)) for i=1:1_000_000])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25004ea0ccfa-9622-11eb-1cf0-e9ae2f927dd2\n# \u2560\u2550d155ea12-9628-11eb-347f-7754a33fd403\n# \u2560\u255001506de2-918a-11eb-2a4d-c554a6e54631\n# \u255f\u2500877deb2c-702b-457b-a54b-f27c277928d4\n# \u255f\u250036ce167f-382c-4b9a-be34-83250b10c4e5\n# \u255f\u250083912943-a847-420a-bfdb-450027b631e8\n# \u2560\u2550280d112f-d34a-4cc4-9e3a-4ebbfcd5eb51\n# \u2560\u2550b5031c96-db57-4baf-b271-6bb12e29de9b\n# \u2560\u2550c2f77e8f-a8c0-4144-a8b4-b25dd98ed234\n# \u255f\u2500ad161b98-f4a1-42ac-ad4f-8b71fabcfde9\n# \u2560\u25508e422886-74ef-4c0f-be1e-fda238c8db44\n# \u255f\u2500ca21122a-2522-482a-b7ef-bd73e96cb5a9\n# \u255f\u250041e05b1e-8b5e-45e3-91bb-01355ade9f3d\n# \u2560\u25509d2e3861-ca36-406e-952d-831ca3947e44\n# \u255f\u2500e73854ed-3581-41c4-ada5-e48242033759\n# \u2560\u25509873d944-b611-46f9-82a7-0cf714a3078c\n# \u2560\u25502be44753-afee-4125-b6bc-8866d2293dc2\n# \u255f\u25006e07e8fb-fe51-4b37-bfb2-d1466e768754\n# \u255f\u2500a755e58a-b16c-4d3b-a85f-81ccf374793f\n# \u255f\u2500f1e10fb7-adac-4083-8977-616a505fd591\n# \u2560\u25502e42986c-2de3-49e6-9c29-a7313c0b1da8\n# \u255f\u250022758dd6-9d04-4616-ba99-1430f2dedf9a\n# \u2560\u2550aff6a616-6d8b-4584-a6f2-195decef7774\n# \u2560\u2550338da13a-3c26-4366-a669-ac3e24f31577\n# \u2560\u25505a742546-1e4d-4aee-bed1-cb10c543e439\n# \u255f\u25006a9c8c9a-fac7-42f7-976d-3168132cae48\n# \u255f\u25003c038b68-8676-4877-9720-38da7c4e0e0e\n# \u255f\u25005a877e40-a101-4f7d-b2a1-ef4cfe5d8807\n# \u255f\u250083c28c76-2eab-49f9-9999-05df85054520\n# \u255f\u2500ba671804-dc6d-415c-89de-9cf6294907b3\n# \u255f\u2500e8683a71-5822-4491-9ccd-20e0fc3bf531\n# \u2560\u25500489e5d8-51ca-4955-83e1-95ea353d9cf2\n# \u2560\u25509a65aee4-ab8e-4ab7-be6f-cc2a2e9d5127\n# \u255f\u2500c3539f42-6ca7-47fb-9707-4d11c9e76643\n# \u255f\u2500469d809f-424f-4595-ad43-a5b2cc055304\n# \u255f\u25006128b8fd-9b85-4896-a0bf-934a0733fafb\n# \u2560\u25509eb7caaa-438d-4bcb-9c54-4a0fa72c61de\n# \u2560\u25500e8fce45-f1c0-41d4-996a-d6093182afee\n# \u2560\u255071590890-38b6-440e-b61b-ece6c49ac602\n# \u255f\u2500f7cc7146-9ee6-4d87-b024-2a91863f4b24\n# \u255f\u2500f64815e2-44b8-4585-9269-9a62655c984c\n# \u255f\u2500feb3c45e-88f4-4ffc-a4a0-e89489187c8d\n# \u2560\u255099069dd7-e088-4626-aa29-e48d6f9a474e\n# \u255f\u2500051a9e38-9a84-4ead-96fa-24c86c2b9f2d\n# \u255f\u25002f33ee51-0725-46c2-9f1b-a61cd68abab1\n# \u2560\u2550e4acd97b-22f7-4812-9898-1a485887a5f2\n# \u2560\u25504e413b40-81c4-4160-9d01-046c2d179a06\n# \u255f\u25007b94db0d-f46b-4621-9413-1dc787ae9a39\n# \u2560\u255051a28b67-ad64-4cf2-a0e6-a78fb101eb15\n# \u2560\u2550d451af49-3139-4329-a885-a210b1760f74\n# \u255f\u2500c7455f7a-9c72-42f5-8238-1799cad96f6c\n# \u255f\u2500d2971801-2cdb-4b9f-8ec8-c74cbb2a0b31\n# \u2560\u2550e1e8c140-bc4e-400d-beb2-0986e071c3a3\n# \u255f\u25001429be09-a31f-415f-9c3d-f32b085ef68d\n# \u2560\u2550da321202-0dc5-44ad-aac0-f3ea0d229243\n# \u255f\u25002aceb366-a067-4271-9362-c320f4735ed1\n# \u2560\u255058f548fd-f6d0-479d-8469-bc886783f9a7\n# \u255f\u250007be9435-bc07-4a18-aad8-3ff19f5bcce4\n# \u2560\u25501a6ad08d-c3bb-47e7-bdee-156bbff3aeda\n# \u255f\u2500c55e4894-db71-4729-a1a1-5f68b45e3bf5\n# \u2560\u2550f50d66eb-0357-4017-ac9b-99e63cd52dc0\n# \u255f\u25005c7a7361-f0e7-473a-9e38-226828aa00ca\n# \u2560\u2550acf0e90e-8f1f-451f-9f0f-70a0bcc7efca\n# \u255f\u2500c9f65e15-f222-4a88-98c2-9e1d8b5ec3eb\n# \u2560\u25502589a369-8b21-406d-906d-71b18e4c7895\n# \u255f\u2500ed6a0e6a-2d0c-4f77-9b08-1a5b5d56dd34\n# \u2560\u255061d1c1f7-e070-413b-8a92-76f44d237206\n# \u255f\u250094d80ad6-0403-4322-aa9f-647c291c19d7\n# \u2560\u2550ce89b805-39a2-49e6-8781-c557aa73ed27\n# \u2560\u255075f9b5e9-775d-4767-9da6-222f977da686\n# \u2560\u2550797c9f2f-0b85-4435-b1c0-edc8cf67f738\n# \u2560\u25506e0b2452-9f8b-4730-8072-a663704893c5\n# \u2560\u2550bf537a3a-b7c6-4c64-8b44-85511c3d492e\n# \u255f\u25001340818c-3391-420b-aa94-acaea8a47d7d\n# \u2560\u2550829607ff-25e0-4585-9c5c-d132ecb86cc8\n# \u2560\u25503fc0a4a8-6719-4920-99c7-bd576225214e\n# \u2560\u255024a7ad28-936c-47dc-bc53-d1ddbf39d05d\n# \u255f\u25009233dc6a-7578-4d72-b0c2-c3bb110a9fbe\n# \u2560\u255007e02bb6-380d-40dd-86ad-19d713cd1657\n# \u255f\u2500b14593ba-cb8c-4f28-8fb0-2d2df479357b\n# \u255f\u2500ac204681-b9df-471b-a22e-9d8f68679151\n# \u255f\u250008f43fff-fbd8-468f-8b3b-efd1829f4fc0\n# \u2560\u255043ec6124-c3e5-4f34-b0d9-1a0b069aa3e0\n# \u2560\u25503fe71215-bbf2-40e9-bcfc-0bc9b3ac94c8\n# \u255f\u2500a2b27841-256e-4898-aeca-04c4f44138fb\n# \u255f\u25008851dca3-e1a6-46b2-9745-f175ef0b0fae\n# \u255f\u2500ccfcb4d9-5a88-48fb-9568-1147a74f6eec\n# \u255f\u250013858c0a-3e7a-4742-a821-97dd9a45109d\n# \u255f\u2500b2c3c1e5-e569-4c6f-bad9-055a25d73dce\n# \u2560\u2550305e4dfc-af7d-4667-8da8-a7ba5fd20fa6\n# \u255f\u2500a648ba4f-fec4-4fa7-b328-1b52070224eb\n# \u2560\u2550d652df7d-7364-4da4-b51e-9fc88b978cda\n# \u255f\u25002e530106-57a8-46a9-8f99-49a871d43255\n# \u255f\u2500a990b133-ce50-4edf-81e1-1e78aeff8cd6\n# \u255f\u25003d0ea801-d66b-4e4e-90da-3a7dce28140d\n# \u255f\u25006fb223bb-f193-414d-9144-df180d09bea1\n# \u255f\u2500fb495ba4-52e6-4e0d-bd9c-981700edfebc\n# \u2560\u2550cdc4b25d-d05f-40c8-9c79-265876f01523\n# \u255f\u2500967c5e3e-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# ``\u222b \u222b 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\u0394 = 1/2^10\nx = range(-1, stop=1, step=\u0394)\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 * \u0394^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)) * \u0394^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) \u2248 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) \u2248 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) \u2248 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) \u2248 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) * \u0394^2\nend\n@assert area!(xl,yl) \u2248 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) \u2248 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 * \u0394^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) \u2248 area0\nt = @benchmark area_ci(xl,yl) # 5.2 ms (3 allocations: 48 bytes)\nbtime(t)\n\n#\n@assert area_ci(xa,ya) \u2248 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 * \u0394^2\nend\n@assert area_for2(xa, ya) \u2248 area0\nt = @benchmark area_for2($xa, $ya) # 5.9 ms (3 allocations: 48 bytes)\nbtime(t)\n\n#\n@assert area_for2(xl, yl) \u2248 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')) * \u0394^2\n@assert areab(x,y) \u2248 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)) * \u0394^2\n@assert areaz(xa, ya) \u2248 area0\nt = @benchmark areaz($xa, $ya) # 3.9 ms (3 allocations: 48 bytes)\nbtime(t)\n\n#\n@assert areaz(xl, yl) \u2248 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)) * \u0394^2\n@assert areap(x,y) \u2248 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\u0394c = 1/2^8 # coarse grid\nxc = range(-1, stop=1, step=\u0394c)\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,\u0394) = 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    )) * \u0394^3\nvol_br([0.],[0.],[0.],\u0394c) # warm-up\n@timeo vol0 = vol_br(xc,yc,zc,\u0394c) # 2.7 sec, 3.0 GiB, roughly (4/3)\u03c0\n\nfunction vol_ci(xx, yy, zz, \u0394)\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 * \u0394^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.], \u0394c) # warm-up\n@timeo vol_ci(xlc, ylc, zlc, \u0394c) # 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, \u0394c) # 0.2 seconds (1.1 MiB)\n\n# Using `zip` is more concise (but slower):\nvol_zip(xx, yy, zz, \u0394) = sum(sphere, zip(xx,yy,zz)) * \u0394^3\n\n#\nvol_zip([0.], [0.], [0.], \u0394c) # warm-up\n@timeo vol_zip(xlc, ylc, zlc, \u0394c) # 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, \u0394c) \u2248 vol0\n@timeo vol_zip(xac, yac, zac, \u0394c) # 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, \u0394) # 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 (\u03c0^2/2, sum(sphere, zip(ndgrid(xc,xc,xc,xc)...)) * \u0394c^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 \u2265 0)\n@variable(m, potatoes \u2265 0)\n\n@objective(m, Min, 8 * steak + 4 * potatoes)\n\n\n\n\n@constraint(m, 5 * steak + 15 * potatoes \u2265 CARBS)\n@constraint(m, 20 * steak + 5 * potatoes \u2265 PROTEIN)\n@constraint(m, 15 * steak + 2 * potatoes \u2264 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# \u2554\u2550\u2561 0810c98f-2526-4ab4-9cd5-a662434e332d\nbegin\n\tusing Statistics\n\tusing StatsBase\n\tusing Plots\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e42b8dfb-1a75-448c-acc1-3255c87a0edf\npickups = rand(0:500, 100)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fbbc6413-0afb-4531-8113-bb85afd2710d\nresponses = sample(pickups, 30)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f9153c34-d26b-4e54-847e-c3bae8cdb4df\nsims = [mean(sample(pickups, 30; replace=false)) for x in 1:100000]\n\n# \u2554\u2550\u2561 d273d1b8-e66c-4461-ab55-b2a4fe578d0c\nhistogram(sims, fillcolor=:black, plot_title=\"Histogram of Sample Means\", legend = false)\n\n# \u2554\u2550\u2561 14b9e9b0-d67b-4376-80a5-cb0b76602174\nconvergence = [mean(sims[1:i]) for i in 1:100000]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dd9e01ed-64c6-43cf-bde2-add77d470770\nbootmeans = [mean(sample(responses, 30; replace=true)) for x in 1:100000]\n\n# \u2554\u2550\u2561 38c6b0b4-08a9-49ed-8268-1cdfd3861d2a\nbootmean = mean(bootmeans)\n\n# \u2554\u2550\u2561 fddd7c16-90b7-45dc-bcd0-8fbae1b64bb4\ntruemean = mean(pickups)\n\n# \u2554\u2550\u2561 cb88575d-719b-44d6-aebe-e071e5a90069\nbootmeanstd = sqrt(var(bootmeans))\n\n# \u2554\u2550\u2561 57c0deb6-feb6-4e79-bc1d-a57a6e678eda\ntruestderror = std(pickups) / (30^(.5))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000810c98f-2526-4ab4-9cd5-a662434e332d\n# \u255f\u2500a4283cac-c253-11ec-1d76-495287bbab72\n# \u255f\u2500c33fde47-ac17-4194-973b-cdb277907b60\n# \u255f\u2500e42b8dfb-1a75-448c-acc1-3255c87a0edf\n# \u255f\u25000e14ff27-5d05-4367-947e-d97e96ddfa8e\n# \u2560\u2550fbbc6413-0afb-4531-8113-bb85afd2710d\n# \u255f\u25000ed657f2-8f2b-4e8f-a375-9c8986448340\n# \u255f\u2500c30c49a1-2821-4ada-ab10-5cac70a99e87\n# \u255f\u2500520524ab-53ef-4edb-bc58-f6a86620a126\n# \u255f\u2500fda6b303-a082-4f44-8341-49446b100609\n# \u255f\u25004453da4c-12fc-427d-9f9c-89476bf65541\n# \u255f\u2500f9153c34-d26b-4e54-847e-c3bae8cdb4df\n# \u255f\u2500d273d1b8-e66c-4461-ab55-b2a4fe578d0c\n# \u255f\u250014b9e9b0-d67b-4376-80a5-cb0b76602174\n# \u255f\u2500ceb8a078-4c55-40e7-a1bf-41bc357eaf86\n# \u255f\u25003c1f21fb-be76-446d-b27f-54119ee4835a\n# \u255f\u25001e05bcbc-cf0a-47ba-a1be-cb2e9bafff78\n# \u255f\u250056116619-fd06-4af1-9e6c-d78b8f166542\n# \u255f\u250006fef3c2-21cf-41d4-b645-6d3dbb75450c\n# \u255f\u2500a2a3d276-f33e-40e3-bf66-bfeeb0c99f95\n# \u255f\u250058ac0581-bde8-4940-9020-a738f695a2fd\n# \u2560\u2550dd9e01ed-64c6-43cf-bde2-add77d470770\n# \u2560\u255038c6b0b4-08a9-49ed-8268-1cdfd3861d2a\n# \u2560\u2550fddd7c16-90b7-45dc-bcd0-8fbae1b64bb4\n# \u2560\u2550cb88575d-719b-44d6-aebe-e071e5a90069\n# \u2560\u255057c0deb6-feb6-4e79-bc1d-a57a6e678eda\n# \u255f\u25005b9bc0f6-c43d-4ea5-9ce6-2aa41d0ec74a\n# \u255f\u2500d9166184-8705-49c4-a7e9-0bba61adcaae\n# \u255f\u2500e41995a5-1591-4404-b585-3c4e9aac49bf\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "@testset \"Data\" begin\n\n@test artificialInSARImage(2) == S1Point.(zeros(2,2))\n@test artificialInSARImage(2,RnPoint) == RnPoint.(2*\u03c0*ones(2,2))\n@test artificialInSARImage(2,SnPoint) == repeat([SnPoint([1.,0.])],2,2)\n\n@test artificialS1SlopeSignal(20,0.) == repeat([S1Point(-\u03c0/2)],20)\n\n@test ismissing( artificialS1Signal(-1.) )\n@test ismissing( artificialS1Signal(2.) )\n@test artificialS1Signal(2) == S1Point.([-3*\u03c0/4,-3*\u03c0/4])\n\n# for the remainder check data types only\n@test length( artificialS1Signal(20) ) == 20\n\n@test size( artificialS2WhirlImage(64) ) == (64,64)\n@test length(getValue(artificialS2WhirlImage(64)[1,1])) == 3\n@test eltype( getValue(artificialS2WhirlImage(64)) ) == SnPoint{Float64}\n\n@test size( artificialS2RotationsImage(64) ) == (64,64)\n@test length(getValue(artificialS2RotationsImage(64)[1,1])) == 3\n@test eltype( getValue(artificialS2RotationsImage(64)) ) == SnPoint{Float64}\n\n@test size( artificialS2WhirlPatch(8) ) == (8,8)\n@test length(getValue(artificialS2WhirlPatch(8)[1,1])) == 3\n@test eltype( getValue(artificialS2WhirlPatch(8)) ) == SnPoint{Float64}\n\n@test size( artificialSPDImage(8) ) == (8,8)\n@test size(getValue(artificialSPDImage(8)[1,1])) == (3,3)\n@test eltype( getValue(artificialSPDImage(8)) ) == SPDPoint{Float64}\n\n@test size( artificialSPDImage2(8) ) == (8,8)\n@test size(getValue(artificialSPDImage2(8)[1,1])) == (3,3)\n@test eltype( getValue(artificialSPDImage2(8)) ) == SPDPoint{Float64}\n\n@test length( artificialS2Lemniscate(SnPoint([0.,0.,1.]),20) ) == 20\n@test length( getValue( artificialS2Lemniscate(SnPoint([0.,0.,1.]),20)[1])) == 3\n@test eltype( artificialS2Lemniscate(SnPoint([0.,0.,1.]),20)) == SnPoint{Float64}\n\nend", "meta": {"hexsha": "e0e07dc3bd5ab676308dbb80791811444292fead", "size": 1667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/helpers/testData.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": "test/helpers/testData.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": "test/helpers/testData.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": 41.675, "max_line_length": 81, "alphanum_fraction": 0.7108578284, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7746274143107302}}
{"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 = rand(1:10)\nm = n + rand(0:5)\nA = rand(m, n)\n\nr = polarfact(A, alg = :svd);\n\n\n# Test unitary matrix U\n\nU = r.U\nH = r.H\n\n@test_approx_eq_eps U'*U eye(n) 1e-7\n\n# Test Hermitian positive semifefinite matrix H\n\n@test issym(H)\n \nfor i in eigvals(H)\n    @test i >= 0.\nend\n\n@test_approx_eq A U*H\n\nprintln(\"SVD method passed test...\")\n", "meta": {"hexsha": "eac7dec6762a3d377c9b4fe381e032389c94a276", "size": 330, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_svd.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_stars_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_stars_repo_licenses": ["MIT"], "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_svd.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_issues_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_issues_repo_licenses": ["MIT"], "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_svd.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_forks_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_forks_repo_licenses": ["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.6923076923, "max_line_length": 47, "alphanum_fraction": 0.6272727273, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7745564134578902}}
{"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 HomotopyContinuation\nusing Base.Test\nimport DynamicPolynomials\nconst PolyImpl = DynamicPolynomials\n\ninclude(\"base_utilities_test.jl\")\n\ninclude(\"straight_line_test.jl\")\ninclude(\"gamma_trick_test.jl\")\ninclude(\"fixedhomotopy_test.jl\")\ninclude(\"spherical_test.jl\")\ninclude(\"affine_test.jl\")\ninclude(\"test_systems_test.jl\")\ninclude(\"cauchyendgame_test.jl\")\n", "meta": {"hexsha": "88306129ffbf2e9b036111e5acb262653f068dcc", "size": 358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 23.8666666667, "max_line_length": 35, "alphanum_fraction": 0.8268156425, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7745255576971941}}
{"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> = \u222b_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) = \u2211_{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{\u03c6}``,\nwhere ``M_{ij} = \\left< b_i, b_j \\right>`` and ``\u03c6_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{\u03c6}`` 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{\u03c6}``.\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\u00d7n` squared distances matrix `D` into `n\u00d7n` 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 \u03c3: %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\u00d7ndims` 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": "module TestMonoidalDirectedWiringDiagrams\nusing Test\n\nusing Catlab.Theories, Catlab.WiringDiagrams\n\n# Categorical interface\n#######################\n\n# Category\n#---------\n\n# Generators\nA, B = Ports([:A]), Ports([:B])\nf = singleton_diagram(Box(:f,A,B))\ng = singleton_diagram(Box(:g,B,A))\n@test nboxes(f) == 1\n@test boxes(f) == [ Box(:f,A,B) ]\n@test nwires(f) == 2\n\n# Composition\n@test nboxes(compose(f,g)) == 2\n@test boxes(compose(f,g)) == [ Box(:f,A,B), Box(:g,B,A) ]\n@test nwires(compose(f,g)) == 3\n\n# Domains and codomains\n@test dom(f) == Ports([:A])\n@test codom(f) == Ports([:B])\n@test dom(compose(f,g)) == Ports([:A])\n@test codom(compose(f,g)) == Ports([:A])\n\n# Associativity\n@test compose(compose(f,g),f) == compose(f,compose(g,f))\n\n# Identity\n@test compose(id(dom(f)), f) == f\n@test compose(f, id(codom(f))) == f\n\n# Symmetric monoidal category\n#----------------------------\n\n# Domains and codomains\n@test dom(otimes(f,g)) == otimes(dom(f),dom(g))\n@test codom(otimes(f,g)) == otimes(codom(f),codom(g))\n\n# Associativity and unit\nX, Y = Ports([:A,:B]), Ports([:C,:D])\nI = munit(Ports)\n@test otimes(X,I) == X\n@test otimes(I,X) == X\n@test otimes(otimes(X,Y),X) == otimes(X,otimes(Y,X))\n@test otimes(otimes(f,g),f) == otimes(f,otimes(g,f))\n\n# Braiding\n@test compose(braid(X,Y),braid(Y,X)) == id(otimes(X,Y))\n\n# Permutations\nW = otimes(X,Y)\n@test permute(W, [1,2,3,4]) == id(W)\n@test permute(W, [1,2,3,4], inverse=true) == id(W)\n@test permute(W, [3,4,1,2]) == braid(X,Y)\n@test permute(W, [3,4,1,2], inverse=true) == braid(Y,X)\n@test_throws AssertionError permute(W, [1,2])\n\n# Diagonals\n#----------\n\n# Basic composition\nd = WiringDiagram(dom(f), otimes(codom(f),codom(f)))\nfv1 = add_box!(d, first(boxes(f)))\nfv2 = add_box!(d, first(boxes(f)))\nadd_wires!(d, [\n  (input_id(d),1) => (fv1,1),\n  (input_id(d),1) => (fv2,1),\n  (fv1,1) => (output_id(d),1),\n  (fv2,1) => (output_id(d),2),\n])\n@test compose(mcopy(dom(f)), otimes(f,f)) == d\n\n# Domains and codomains\n@test dom(mcopy(Ports([:A]))) == Ports([:A])\n@test codom(mcopy(Ports([:A]))) == Ports([:A,:A])\n@test dom(mcopy(Ports([:A,:B]),3)) == Ports([:A,:B])\n@test codom(mcopy(Ports([:A,:B]),3)) == Ports([:A,:B,:A,:B,:A,:B])\n\n# Associativity\nA = Ports([:A])\n@test compose(mcopy(A), otimes(id(A),mcopy(A))) == mcopy(A,3)\n@test compose(mcopy(A), otimes(mcopy(A),id(A))) == mcopy(A,3)\n\n# Commutativity\n@test compose(mcopy(A), braid(A,A)) == mcopy(A)\n\n# Unitality\n@test compose(mcopy(A), otimes(id(A),delete(A))) == id(A)\n\n# Cartesian categories\nA = Ports{CartesianCategory}([:A])\n@test mcopy(A) == mcopy(Ports([:A]))\n@test delete(A) == delete(Ports([:A]))\n@test_throws MethodError mmerge(A)\n@test_throws MethodError create(A)\n\n# Codiagonals\n#------------\n\n# Domains and codomains\n@test dom(mmerge(Ports([:A]))) == Ports([:A,:A])\n@test codom(mmerge(Ports([:A]))) == Ports([:A])\n@test dom(mmerge(Ports([:A,:B]),3)) == Ports([:A,:B,:A,:B,:A,:B])\n@test codom(mmerge(Ports([:A,:B]),3)) == Ports([:A,:B])\n\n# Associativity\nA = Ports([:A])\n@test compose(otimes(id(A),mmerge(A)), mmerge(A)) == mmerge(A,3)\n@test compose(otimes(mmerge(A),id(A)), mmerge(A)) == mmerge(A,3)\n\n# Commutativity\n@test compose(braid(A,A), mmerge(A)) == mmerge(A)\n\n# Unitality\n@test compose(otimes(id(A),create(A)), mmerge(A)) == id(A)\n\n# Cocartesian categories\nA = Ports{CocartesianCategory}([:A])\n@test mmerge(A) == mmerge(Ports([:A]))\n@test create(A) == create(Ports([:A]))\n@test_throws MethodError mcopy(A)\n@test_throws MethodError delete(A)\n\n# Bidiagonals\n#------------\n\n# Monoidal categories with bidiagonals, and non-naturality of explicit\n# representation.\nA = Ports{MonoidalCategoryWithBidiagonals}([:A])\n@test boxes(mcopy(A)) == [ Junction(:A,1,2) ]\n@test boxes(mcopy(otimes(A,A))) == repeat([ Junction(:A,1,2) ], 2)\n@test compose(create(A), mcopy(A)) != create(otimes(A,A))\n@test compose(mmerge(A), delete(A)) != delete(otimes(A,A))\n\n# Biproduct categories, and naturality of implicit representation.\nA = Ports{BiproductCategory}([:A])\n@test compose(create(A), mcopy(A)) == create(otimes(A,A))\n@test compose(mmerge(A), delete(A)) == delete(otimes(A,A))\n\n# Dagger category\n#----------------\n\nf = singleton_diagram(DaggerSymmetricMonoidalCategory, Box(:f,[:A],[:B]))\ng = singleton_diagram(DaggerSymmetricMonoidalCategory, Box(:g,[:B],[:A]))\n\n@test boxes(dagger(f)) == [ BoxOp{:dagger}(Box(:f,[:A],[:B])) ]\n\n# Domain and codomain\n@test dom(dagger(f)) == codom(f)\n@test codom(dagger(f)) == dom(f)\n\n# Functoriality\n@test is_permuted_equal(dagger(compose(f,g)), compose(dagger(g),dagger(f)), [2,1])\n@test dagger(otimes(f,g)) == otimes(dagger(f),dagger(g))\n\n# Involutivity\n@test dagger(dagger(f)) == f\n@test dagger(dagger(compose(f,g))) == compose(f,g)\n@test dagger(dagger(otimes(f,g))) == otimes(f,g)\n\n# Compact closed category\n#------------------------\n\n### Duals\n\nA, B = [ Ports{CompactClosedCategory}([sym]) for sym in [:A, :B] ]\nI = munit(typeof(A))\n\n@test boxes(dunit(A)) == [ Junction(:A, [], [PortOp{:dual}(:A), :A]) ]\n@test boxes(dcounit(A)) == [ Junction(:A, [:A, PortOp{:dual}(:A)], []) ]\n\n# Domains and codomains\n@test dom(dunit(A)) == I\n@test codom(dunit(A)) == otimes(dual(A),A)\n@test dom(dcounit(A)) == otimes(A,dual(A))\n@test codom(dcounit(A)) == I\n\n# Coherence relations\n@test is_permuted_equal(dunit(otimes(A,B)),\n  compose(dunit(B), otimes(id(dual(B)), dunit(A), id(B))), [2,1])\n@test is_permuted_equal(dcounit(otimes(A,B)),\n  compose(otimes(id(A), dcounit(B), id(dual(A))), dcounit(A)), [2,1])\n\n### Adjoint mates\n\nf = singleton_diagram(CompactClosedCategory, Box(:f,[:A],[:B]))\ng = singleton_diagram(CompactClosedCategory, Box(:g,[:B],[:A]))\n\n@test boxes(mate(f)) == [ BoxOp{:mate}(Box(:f,[:A],[:B])) ]\n\n# Domain and codomain\n@test dom(mate(f)) == dual(codom(f))\n@test codom(mate(f)) == dual(dom(f))\n\n# Functoriality\n@test is_permuted_equal(mate(compose(f,g)), compose(mate(g),mate(f)), [2,1])\n@test is_permuted_equal(mate(otimes(f,g)), otimes(mate(g),mate(f)), [2,1])\n\n# Involutivity\n@test mate(mate(f)) == f\n@test mate(mate(compose(f,g))) == compose(f,g)\n@test mate(mate(otimes(f,g))) == otimes(f,g)\n\n# Traced monoidal category\n#-------------------------\n\nconst TracedMon = TracedMonoidalCategory\nA, B, X, Y = [ Ports{TracedMon}([sym]) for sym in [:A,:B,:X,:Y] ]\nI = munit(typeof(A))\nf = singleton_diagram(TracedMon, Box(:f, [:X,:A], [:X,:B]))\n\n# Domain and codomain\n@test dom(trace(X, A, B, f)) == A\n@test codom(trace(X, A, B, f)) == B\n\n# Naturality\ng = singleton_diagram(TracedMon, Box(:g, [:A], [:A]))\nh = singleton_diagram(TracedMon, Box(:h, [:B], [:B]))\n@test trace(X, compose(id(X)\u2297g, f, id(X)\u2297h)) == compose(g, trace(X,f), h)\n\n# Stength, aka superposing\ng = singleton_diagram(TracedMon, Box(:g, [:C], [:C]))\n@test trace(X, otimes(f,g)) == otimes(trace(X,f), g)\n\n# Symmetry sliding\nf = singleton_diagram(TracedMon, Box(:f, [:X,:Y,:A], [:Y,:X,:B]))\n@test trace(X\u2297Y, compose(f, braid(Y,X)\u2297id(B))) ==\n  trace(Y\u2297X, compose(braid(Y,X)\u2297id(A), f))\n\n# Vanishing\nf = singleton_diagram(TracedMon, Box(:f, [:X,:Y,:A], [:X,:Y,:B]))\n@test trace(X\u2297Y, f) == trace(Y, trace(X, f))\nf = singleton_diagram(TracedMon, Box(:f, [:A], [:B]))\n@test trace(I, f) == f\n\n# Yanking\n@test trace(X, braid(X,X)) == id(X)\n\n# Bicategory of relations\n#------------------------\n\nA, B = [ Ports{BicategoryRelations}([sym]) for sym in [:A, :B] ]\nR = singleton_diagram(BicategoryRelations, Box(:R,[:A],[:B]))\nS = singleton_diagram(BicategoryRelations, Box(:S,[:A],[:B]))\n\n# Domains and codomains\n@test dom(meet(R,S)) == A\n@test codom(meet(R,S)) == B\n@test dom(top(A,B)) == A\n@test codom(top(A,B)) == B\n\n# Units and counits\n@test dunit(A) == merge_junctions(compose(create(A), mcopy(A)))\n@test dcounit(A) == merge_junctions(compose(mmerge(A), delete(A)))\n\n# Abelian bicategory of relations\n#--------------------------------\n\nA, B = [ Ports{AbelianBicategoryRelations}([sym]) for sym in [:A, :B] ]\nR = singleton_diagram(AbelianBicategoryRelations, Box(:R,[:A],[:B]))\nS = singleton_diagram(AbelianBicategoryRelations, Box(:S,[:A],[:B]))\n\n# Domains and codomains.\n@test dom(plus(A)) == dom(mmerge(A)) && codom(plus(A)) == codom(mmerge(A))\n@test dom(coplus(A)) == dom(mcopy(A)) && codom(coplus(A)) == codom(mcopy(A))\n@test dom(zero(A)) == dom(create(A)) && codom(zero(A)) == codom(create(A))\n@test dom(cozero(A)) == dom(delete(A)) && codom(cozero(A)) == codom(delete(A))\n\n@test dom(join(R,S)) == A\n@test codom(join(R,S)) == B\n@test dom(bottom(A,B)) == A\n@test codom(bottom(A,B)) == B\n\n# Distinctness of \"multiplicative\" and \"additive\" (co)diagonals.\n@test plus(A) != mmerge(A)\n@test coplus(A) != mcopy(A)\n@test zero(A) != create(A)\n@test cozero(A) != delete(A)\n\n# Junctions\n###########\n\n# Add and remove junctions\n#-------------------------\n\nA, B, C = [ Ports([sym]) for sym in [:A, :B, :C] ]\nf = singleton_diagram(Box(:f, [:A], [:B]))\ng = singleton_diagram(Box(:g, [:B], [:C]))\n\n# Copies.\nd = compose(f, mcopy(B))\njunctioned = compose(f, junction_diagram(B,1,2))\n@test add_junctions(d) == junctioned\n@test rem_junctions(junctioned) == d\n\nd = compose(mcopy(A), otimes(f,f))\njunctioned = compose(junction_diagram(A,1,2), otimes(f,f))\n@test is_permuted_equal(add_junctions(d), junctioned, [3,1,2])\n@test rem_junctions(junctioned) == d\n\n# Merges.\nd = compose(mmerge(A), f)\njunctioned = compose(junction_diagram(A,2,1), f)\n@test is_permuted_equal(add_junctions(d), junctioned, [2,1])\n@test rem_junctions(junctioned) == d\n\nd = compose(otimes(f,f), mmerge(B))\njunctioned = compose(otimes(f,f), junction_diagram(B,2,1))\n@test add_junctions(d) == junctioned\n@test rem_junctions(junctioned) == d\n\n# Deletions.\nd = compose(f, delete(B))\njunctioned = compose(f, junction_diagram(B,1,0))\n@test add_junctions(d) == junctioned\n@test rem_junctions(junctioned) == d\n\n# Creations.\nd = compose(create(A), f)\njunctioned = compose(junction_diagram(A,0,1), f)\n@test is_permuted_equal(add_junctions(d), junctioned, [2,1])\n@test rem_junctions(junctioned) == d\n\n# Copies, merges, deletions, and creations, all at once.\nd = compose(create(A), f, mcopy(B), mmerge(B), g, delete(C))\njunctioned = compose(junction_diagram(A,0,1), f, junction_diagram(B,1,2),\n                     junction_diagram(B,2,1), g, junction_diagram(C,1,0))\nactual = add_junctions(d)\n# XXX: An isomorphism test would be more convenient.\nperm = [ findfirst([b] .== boxes(actual)) for b in boxes(junctioned) ]\n@test is_permuted_equal(actual, junctioned, perm)\n@test rem_junctions(junctioned) == d\n\n# Simplify junctions\n#-------------------\n\nA = Ports([:A])\nj = junction_diagram\n\n# Comonoid laws.\n@test merge_junctions(j(A,1,2)\u22c5(j(A,1,2)\u2297id(A))) ==\n  j(A,1,3)\u22c5permute(A\u2297A\u2297A,[3,1,2]) # FIXME: Shouldn't need permutation.\n@test merge_junctions(j(A,1,2)\u22c5(id(A)\u2297j(A,1,2))) == j(A,1,3)\n@test merge_junctions(j(A,1,2)\u22c5(j(A,1,0)\u2297id(A))) == j(A,1,1)\n@test merge_junctions(j(A,1,2)\u22c5(id(A)\u2297j(A,1,0))) == j(A,1,1)\n\n# Caps and cups.\n@test merge_junctions(j(A,0,1)\u22c5j(A,1,2)) == j(A,0,2)\n@test merge_junctions(j(A,2,1)\u22c5j(A,1,0)) == j(A,2,0)\n\n# Zigzag laws.\n@test merge_junctions((id(A)\u2297j(A,0,2))\u22c5(j(A,2,0)\u2297id(A))) == j(A,1,1)\n@test merge_junctions((j(A,0,2)\u2297id(A))\u22c5(id(A)\u2297j(A,2,0))) == j(A,1,1)\n\nend\n", "meta": {"hexsha": "58e5e6754681ef9c2d77219aec88446fc38ce2f5", "size": 11023, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/wiring_diagrams/MonoidalDirected.jl", "max_stars_repo_name": "cbw124/Catlab.jl", "max_stars_repo_head_hexsha": "7f3e76c44941c2812a994c8fbe6aeb2a2eccaf57", "max_stars_repo_licenses": ["MIT"], "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/wiring_diagrams/MonoidalDirected.jl", "max_issues_repo_name": "cbw124/Catlab.jl", "max_issues_repo_head_hexsha": "7f3e76c44941c2812a994c8fbe6aeb2a2eccaf57", "max_issues_repo_licenses": ["MIT"], "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/wiring_diagrams/MonoidalDirected.jl", "max_forks_repo_name": "cbw124/Catlab.jl", "max_forks_repo_head_hexsha": "7f3e76c44941c2812a994c8fbe6aeb2a2eccaf57", "max_forks_repo_licenses": ["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.4502762431, "max_line_length": 82, "alphanum_fraction": 0.6268710877, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7745255480789149}}
{"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\u2081(op::TransferKind,n::Int) = expand(GridTransferOperator(op,Restriction()),n) # 1d restriction operator\nR(op::TransferKind,n::Int) = R\u2081(op,n)\nR(op::TransferKind,n::Int...) = kron(R\u2081.(op,n)...)\nrestrict(u::Vector{T},op::TransferKind,n::Int...) where {T<:AbstractFloat} = R(op,n...)*u\n\n# interpolation\nP\u2081(op::TransferKind,n::Int) = expand(GridTransferOperator(op,Interpolation()),2n) # 1d interpolation operator\nP(op::TransferKind,n::Int) = P\u2081(op,n)\nP(op::TransferKind,n::Int...) = kron(P\u2081.(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": "\"\"\"\n    get_proportion(for_prop_arr::AbstractVector{Float64})::AbstractVector{Float64}\nCompute the proportional values for each element in the 1-Dim array.\nreturns a AbstractVector{Float64}\n# Example\n```\njulia> get_proportion([1.0,2.0,3.0,4.0,5.0,34.0000034,2423,5656.98988])\n=[0.00012301651427098885, 0.0002460330285419777, 0.00036904954281296654, 0.0004920660570839554, 0.0006150825713549442, 0.004182561903469769, 0.298069014078606, 0.6959031763038594]\n```\n\"\"\"\nfunction get_proportion(for_prop_arr::AbstractVector{Float64})::AbstractVector{Float64}\n    return for_prop_arr ./ sum(for_prop_arr)\nend\n\n\"\"\"\n    get_proportion_round(for_prop_arr::AbstractVector{Float64};round_digits::Int64)::AbstractVector{Float64}\nCompute the proportional values for each element in the array and round to a specified decimal digits.\nIf the sum of all the elements is not 1 , then the adjustment is done in the 1st largest element\nreturns a AbstractVector{Float64}\n# Example\n```\njulia> get_proportion_round([1.33,1.33,1.23,1.1111],round_digits = 2)\n=[0.26, 0.27, 0.25, 0.22]\n```\n\"\"\"\nfunction get_proportion_round(for_prop_arr::AbstractVector{Float64};round_digits::Int64 = 2)::AbstractVector{Float64}\n    temparr=  round.(for_prop_arr ./ sum(for_prop_arr), digits=round_digits, base = 10)\n    diff = 1 - sum(temparr) #delta naming\n    if diff != 0.0\n        max = argmax(temparr)\n        temparr[max] =  round(temparr[max] + diff, digits=round_digits, base = 10)\n    end\n    return temparr\nend\n\n\"\"\"\n    get_proportion_round_add1251(for_prop_arr::AbstractVector{Float64};round_digits::Int64)::AbstractVector{Float64}\nCompute the proportional values for each element in the array and round to a specified decimal digits.\nIf the sum of all the elements is not 1 , then add 1251 to the array and try looking for proportional correctness\nafter 2 itterations , the adjustment is done in the 1st largest element\nreturns a AbstractVector{Float64}\n# Example\n```\njulia> get_proportion_round_add1251([1.33,1.33,1.23,1.1111],round_digits = 2)\n=[0.26, 0.27, 0.25, 0.22]\n```\n\"\"\"\nfunction get_proportion_round_add1251(for_prop_arr::AbstractVector{Float64};round_digits::Int64 = 2)::AbstractVector{Float64}\n    temparr=  round.(for_prop_arr ./ sum(for_prop_arr), digits=round_digits, base = 10)\n    diff = 1 - sum(temparr)\n    if diff != 0.0\n        check = 1\n        while check < 2\n            sqarr= (for_prop_arr) .+1251\n            temparr=  round.(sqarr ./ sum(sqarr), digits=round_digits, base = 10)\n            diff = 1 - sum(temparr)\n            if diff != 0.00\n                check = check + 1\n                if check == 2\n                    max = argmax(temparr)\n                    temparr[max] = round(temparr[max]+diff,digits=round_digits, base = 10)\n                end\n            else\n                break\n            end\n        end\n    end\n    return temparr\nend\n", "meta": {"hexsha": "ea82ea755e4da98c7f59e14031bf7c9dafa20853", "size": 2854, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/onedproportion.jl", "max_stars_repo_name": "hillelawaskar/Proportions", "max_stars_repo_head_hexsha": "9cc5e388e9680bf6274879848e33e6ac24109cce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-13T17:54:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T02:32:36.000Z", "max_issues_repo_path": "src/onedproportion.jl", "max_issues_repo_name": "hillelawaskar/Proportions", "max_issues_repo_head_hexsha": "9cc5e388e9680bf6274879848e33e6ac24109cce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-11T18:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T17:56:37.000Z", "max_forks_repo_path": "src/onedproportion.jl", "max_forks_repo_name": "hillelawaskar/Proportions.jl", "max_forks_repo_head_hexsha": "9cc5e388e9680bf6274879848e33e6ac24109cce", "max_forks_repo_licenses": ["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.7714285714, "max_line_length": 179, "alphanum_fraction": 0.6948142957, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7744764890354199}}
{"text": "# problem 1a\nN = 10\nA = zeros(N,N)\nfor i in 1:N, j in 1:N\n    abs(i-j)<=1 ? A[i,j]+=1 : nothing\n    i==j ? A[i,j]-=3 : nothing\nend\nA\n\n# problem 1b\nsum(sum(1/j for j in 1:i) for i in 1:25)\n\n#### Prepare Data\n\nX = rand(1000, 3)               # feature matrix\na0 = rand(3)                    # ground truths\ny = X * a0 + 0.1 * randn(1000);  # generate response\n\nX2 = hcat(ones(1000),X)\nlreg = X2\\y\n\n#\u00a0problem 3\nusing DataFrames\ndata = DataFrame(X)\ndata[:y] = y\nlm1 = fit(LinearModel, @formula(y ~ x1 + x2 + x3), data)\n@test coef(lm1) \u2248 lreg atol=1e-16\n\n\n# problem 4\nr = 2.9:.00005:4; numAttract = 150\nsteady = ones(length(r),1)*.25\nfor i=1:400 ## Get to steady state\n  steady .= r.*steady.*(1-steady)\nend\nx = zeros(length(steady),numAttract)\nx[:,1] = steady\n@inbounds for i=2:numAttract ## Grab values at the attractor\n  x[:,i] = r.*x[:,i-1].*(1-x[:,i-1])\nend\nusing Plots\nplot(collect(r),x,seriestype=:scatter,markersize=.002,legend=false)\n\n\nmacro ~(y,ex)\n  new_ex = Meta.quot(ex)\n  quote\n    inner_ex = $(esc(new_ex))\n    data_name = Symbol(string(inner_ex.args[end])[1])\n    eval_ex = Expr(:(=),:data,data_name)\n    eval(Main,eval_ex)\n    new_X = Matrix{Float64}(size(data,1),length(inner_ex.args)-1)\n    cur_spot = 0\n    for i in 2:length(inner_ex.args)\n      if inner_ex.args[i] == 1\n        new_X[:,i-1] = ones(size(data,1))\n      else\n        col = parse(Int,string(string(inner_ex.args[i])[2]))\n        new_X[:,i-1] = data[:,col]\n      end\n    end\n    $(esc(y)),new_X\n  end\nend\n\ny = rand(10)\nX = rand(10,4)\ny~1+X1+X2+X4\n\nfunction solve_least_squares(y,X)\n  X\\y\nend\nsolve_least_squares(tup::Tuple) = solve_least_squares(tup...)\nsolve_least_squares(y~1+X1+X2+X4)\n\nfunction myquantile(d::UnivariateDistribution, q::Number)\n    \u03b8 = mean(d)\n    tol = Inf\n    while tol > 1e-5\n        \u03b8old = \u03b8\n        \u03b8 = \u03b8 - (cdf(d, \u03b8) - q) / pdf(d, \u03b8)\n        tol = abs(\u03b8old - \u03b8)\n    end\n    \u03b8\nend\n\nfor dist in [Gamma(5, 1), Normal(0, 1), Beta(2, 4)]\n    @show myquantile(dist, .75)\n    @show quantile(dist, .75)\n    println()\nend\n\nusing LightGraphs, Distributions\nfunction mkTree(maxdepth::Int = 10, p::Float64 = 0.8, g::SimpleGraph = Graph(1), currhead::Int = 1)\n    if (maxdepth <= 1) g\n    else\n       b = Binomial(2, p)\n       nEdges = max(1, rand(b))\n        for leaves in 1:nEdges\n            add_vertex!(g)\n            newnode = nv(g)\n            add_edge!(g, currhead, newnode)\n            mkTree(maxdepth-1, p, g, newnode)\n        end\n    end\n    g\nend\n\nusing Roots\nf(x) = 10 - x + e*sin(x)\nfzero(f,BigFloat(2.0))\n\nf! = function (x,dx)\n  dx[1] = x[1]   + x[2]   + x[3]^2 -12\n  dx[2] = x[1]^2 - x[2]   + x[3]   - 2\n  dx[3] = 2x[1]  - x[2]^2 + x[3]   - 1\nend\nusing NLsolve\nres = nlsolve(f!,[1.0;1.0;1.0])\nres.zero\nres = nlsolve(f!,[1.0;1.0;1.0],autodiff=true)\nres.zero\n", "meta": {"hexsha": "07a16cc735a1b1c413a508cb192f300a49ba115b", "size": 2761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ProblemAnswers.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/ProblemAnswers.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/ProblemAnswers.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": 22.4471544715, "max_line_length": 99, "alphanum_fraction": 0.575878305, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7744764825665268}}
{"text": "println(\"\\nTesting cost terms\\n\")\n\n# Simple Terms\n\nx = Variable(randn(10))\nX = Variable(randn(3,4))\nA = randn(4,10)\nb = randn(4)\n\ncf = norm(x, 0)\n@test cf.lambda == 1\n@test cf.f(~x) == norm(~x,0)\n\ncf = 3*norm(x, 0)\n@test cf.lambda == 3\n@test cf.f(~x) == norm(~x,0)\n\ncf = norm(x, 0) <= 3\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBallL0(3))(~x)\n\ncf = norm(x, 1)\n@test cf.lambda == 1\n@test cf.f(~x) == (NormL1())(~x)\n\ncf = norm(x, 1) <= 1.5\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBallL1(1.5))(~x)\n\ncf = 10*norm(x, 1) <= 1.5\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBallL1(1.5/10))(~x)\n\ncf = norm(x)\n@test cf.lambda == 1\n@test cf.f(~x) == norm(~x)\n\ncf = pi*norm(x,2)\n@test cf.lambda - pi == 0\n@test cf.f(~x) == norm(~x)\n\ncf = 3*norm(X,2,1)\n@test cf.lambda - 3 == 0\n@test cf.f(~X) == sum(  sqrt.(sum((~X).^2, dims=1 )) ) \n\ncf = 4*norm(X,2,1,2)\n@test cf.lambda - 4 == 0\n@test cf.f(~X) == sum(  sqrt.(sum((~X).^2, dims=2 )) ) \n\n@test_throws ErrorException 4*norm(X,1,2)\n\ncf = norm(x, 2) <= 2.3\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBallL2(2.3))(~x)\n\ncf = norm(x, 2) == 2.3\n@test cf.lambda == 1\n@test cf.f(~x) == (IndSphereL2(2.3))(~x)\n\ncf = norm(x, Inf)\n@test cf.lambda == 1\n@test cf.f(~x) == norm(~x,Inf)\n\ncf = norm(x, Inf) <= 5.0\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBallLinf(5.0))(~x)\n\ncf = x <= 3.0\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBox(-Inf, 3.0))(~x)\n\ncf = 3.0 <= x\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBox(3.0, Inf))(~x)\n\ncf = x >= 1.0\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBox(1.0, Inf))(~x)\n\ncf = 1.0 >= x\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBox(-Inf,1.0))(~x)\n\ncf = x in [-5.0, 5.0]\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBox(-5.0, 5.0))(~x)\n\ncf = norm(x, 2)^2\n@test cf.lambda == 1\n@test cf.f(~x) == norm(~x)^2\n\ncf = 0.5*norm(x, 2)^2\n@test cf.lambda == 0.5\n@test cf.f(~x) == norm(~x)^2\n\ncf = 7*(0.5*norm(x, 2))^2\n@test cf.lambda == 7*0.25\n@test cf.f(~x) == norm(~x)^2\n\ncf = 2*rank(X) <= 6\n@test cf.lambda == 1\n@test cf.f(~X) == (IndBallRank(3))(~X)\n\ncf = rank(X)\n@test_throws MethodError cf.f(~X)\n\ncf = norm(X,*)\nU, S, V = svd(~X)\n@test cf.lambda == 1\n@test cf.f(~X) == sum(S)\n\ncf = rank(X)\n@test_throws MethodError cf.f(~X)\n\ny = randn(size(~x))\ncf = hingeloss(x,y)\n@test cf.lambda == 1\n@test cf.f(~x) == (HingeLoss(y))(~x)\n\ny = randn(size(~x))\ncf = sqrhingeloss(x,y)\n@test cf.lambda == 1\n@test cf.f(~x) == (SqrHingeLoss(y))(~x)\n\ny = randn(size(~x))\ncf = logisticloss(x,y)\n@test cf.lambda == 1\n@test cf.f(~x) == (LogisticLoss(y))(~x)\n\nxp = Variable(rand(10)) \nbp = rand(Float64, size(~xp))\ncf = crossentropy(xp,bp)\n@test cf.lambda == 1\n@test cf.f(~xp) == (CrossEntropy(bp))(~xp)\n\ncf = logbarrier(x)\n@test cf.lambda == 1\n@test cf.f(~x) == (LogBarrier(1.0))(~x)\n\ncf = maximum(x)\n@test cf.lambda == 1\n@test cf.f(~x) == (Maximum(1.0))(~x)\n\ncf = sumpositive(x)\n@test cf.lambda == 1\n@test cf.f(~x) == (SumPositive())(~x)\n\na = 1.\ncf = huberloss(x,a)\n@test cf.lambda == 1\n@test cf.f(~x) == (HuberLoss(a))(~x)\n\na = randn(size(x))\ncf = dot(a,x)\n@test cf.lambda == 1\n@test cf.f(~x) == (Linear(a))(~x)\n\n#IndBinary\nlu = (-1.0,randn(length(~x)))\ncf = x == lu\n@test cf.lambda == 1\n@test cf.f(~x) == (IndBinary(lu...))(~x)\n\n# IndAffine (not working in julia < 1.1)\nif VERSION.major >= 1 && VERSION.minor >= 1\n  cf = A*x-b == 0\n  @test cf.lambda == 1\n  @test cf.f(~x) == (IndAffine(A,b))(~x)\n\n  cf = (A*x == b)\n  @test cf.lambda == 1\n  @test cf.f(~x) == (IndAffine(A,-b))(~x)\nend\n\ncf = 2*norm(x,1)\nccf = conj(cf)\n@test ccf.A == cf.A\n@test ccf.f == Conjugate(Postcompose(NormL1(),2))\n@test_throws ErrorException conj(norm(randn(2,10)*x,1))\n\ncf = 2*norm(x,1)\nccf = smooth(cf,2.0)\n@test ccf.A == cf.A\n@test ccf.f(~x) == MoreauEnvelope(Postcompose(NormL1(),2),2.0)(~x)\n\n# Summing terms\n\nx = Variable(10)\ncf = ls(x) + 10*norm(x, 1)\n@test cf[1].lambda == 1\n@test cf[1].f(~x) == 0.5*norm(~x)^2\n@test cf[2].lambda == 10\n@test cf[2].f(~x) == norm(~x,1)\n\nx = Variable(10)\ncf = () #empty cost function \ncf += 10*norm(x, 1)\n@test length(cf) == 1\n@test cf[1].lambda == 10\n@test cf[1].f(~x) == 10*norm(~x,1)\n\nx = Variable(10)\ncf = () #empty cost function \ncf += ls(x) + 10*norm(x, 1)\n@test cf[1].lambda == 1\n@test cf[1].f(~x) == 0.5*norm(~x)^2\n@test cf[2].lambda == 10\n@test cf[2].f(~x) == norm(~x,1)\n\n# More complex situations\n\nx = Variable(10)\nA = randn(5, 10)\ny = Variable(7)\nB = randn(5, 7)\nb = randn(5)\n\ncf = ls(A*x - b) + norm(x, 1)\n@test cf[1].lambda == 1\n@test cf[1].f(~x) == 0.5*norm(~x)^2\n@test norm(affine(cf[1])*(~x) - (A*(~x)-b)) < 1e-12\n@test cf[2].lambda == 1\n@test cf[2].f(~x) == norm(~x,1)\n\ncf = ls(A*x - B*y + b) + norm(y, 1) + 5*norm(y, 2)\n@test cf[1].lambda == 1\n@test cf[1].f(~x) == 0.5*norm(~x)^2\n@test cf[2].lambda == 1\n@test cf[2].f(~x) == norm(~x,1)\n@test cf[3].lambda == 5\n@test cf[3].f(~x) == norm(~x,2)\n\ncf = 10*(ls(A*x - B*y + b) + norm(y, 1) + 5*norm(y, 2))\n@test cf[1].lambda == 10\n@test cf[1].f(~x) == 0.5*norm(~x)^2\n@test cf[2].lambda == 10\n@test cf[2].f(~x) == norm(~x,1)\n@test cf[3].lambda == 50\n@test cf[3].f(~x) == norm(~x,2)\n\ncf = 0.5*norm(A*x - B*y + b, 2)^2 + norm(x, 1) + norm(y, 2)\n@test cf[1].lambda == 0.5\n@test cf[1].f(~x) == norm(~x)^2\n@test cf[2].lambda == 1\n@test cf[2].f(~x) == norm(~x,1)\n@test cf[3].lambda == 1\n@test cf[3].f(~x) == norm(~x,2)\n\n# Properties\nA = randn(5, 10)\nu = Variable(5)\nw = Variable(5)\nz = Variable(5)\n\ncf = norm(A*x + z)\n@test StructuredOptimization.is_smooth(cf) == false\n@test StructuredOptimization.is_smooth(cf^2) == true\n\ncf = norm(w + z)^2\n@test StructuredOptimization.is_smooth(cf) == true\n@test StructuredOptimization.is_AcA_diagonal(cf) == false\n\ncf = norm(x, 1) + norm(y, 2)\n@test StructuredOptimization.is_smooth.(cf) == (false,false)\n@test StructuredOptimization.is_AcA_diagonal.(cf) == (true,true)\n", "meta": {"hexsha": "69881941d701b5fdefaecb8aae020b4aa2037b22", "size": 5705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_terms.jl", "max_stars_repo_name": "lostella/StructuredOptimization.jl", "max_stars_repo_head_hexsha": "26200902c6223d17f0cc33e89761a9b069e58673", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2018-03-08T13:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T20:29:36.000Z", "max_issues_repo_path": "test/test_terms.jl", "max_issues_repo_name": "lostella/StructuredOptimization.jl", "max_issues_repo_head_hexsha": "26200902c6223d17f0cc33e89761a9b069e58673", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-03-16T01:06:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T21:39:30.000Z", "max_forks_repo_path": "test/test_terms.jl", "max_forks_repo_name": "lostella/StructuredOptimization.jl", "max_forks_repo_head_hexsha": "26200902c6223d17f0cc33e89761a9b069e58673", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-11T14:10:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T09:08:24.000Z", "avg_line_length": 21.4473684211, "max_line_length": 66, "alphanum_fraction": 0.5581069238, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7744764780095721}}
{"text": "\"Implements Zeckendorf's theorem and outputs a Zeckendorf sequence {c\u1d6a | c \u2208 {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": "\n# Normal distribution\n\nimport StatsFuns\nexport Normal\n\nimport Base: eltype\n\n\n@measure Normal(\u03bc,\u03c3) \u2243 (1/sqrt2\u03c0) * Lebesgue(X)\n\n\nfunction logdensity(d::Normal{P} , x::X) where {P <: NamedTuple{(:\u03bc, :\u03c3)}, X}    \n    return - log(d.par.\u03c3)  - (x - d.par.\u03bc)^2 / (2 * d.par.\u03c3^2)\nend\n\n# Standard normal\n\nfunction logdensity(d::Normal{EmptyNamedTuple} , x::X) where {X}  \n    return - x^2 / 2 \nend\n\n# Normal() = Normal{EmptyNamedTuple,Real}(NamedTuple())\n \nsampletype(::Normal{NamedTuple{(),Tuple{}}}) = Real\n\nBase.rand(\u03bc::Normal{EmptyNamedTuple}) = randn()\n\n\u226a(::Normal, ::Lebesgue{X}) where X <: Real = true\nrepresentative(::Normal) = Lebesgue(Real)\n", "meta": {"hexsha": "3bde63494403ab61cad938c4716ac9f3a5e526e0", "size": 643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/probability/normal.jl", "max_stars_repo_name": "AzamatB/MeasureTheory.jl", "max_stars_repo_head_hexsha": "604990a123e7443b9be4f5e6c8d79371aa5b1d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/probability/normal.jl", "max_issues_repo_name": "AzamatB/MeasureTheory.jl", "max_issues_repo_head_hexsha": "604990a123e7443b9be4f5e6c8d79371aa5b1d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/probability/normal.jl", "max_forks_repo_name": "AzamatB/MeasureTheory.jl", "max_forks_repo_head_hexsha": "604990a123e7443b9be4f5e6c8d79371aa5b1d1e", "max_forks_repo_licenses": ["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.7419354839, "max_line_length": 81, "alphanum_fraction": 0.6469673406, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7742659959159267}}
{"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(\u03c3\u00b2)\n\nGaussian likelihood with `\u03c3\u00b2` 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, \u03c3\u00b2)\n```\nOn calling, this would return a normal distribution with mean `f` and variance \u03c3\u00b2.\n\"\"\"\nstruct GaussianLikelihood{T<:Real}\n    \u03c3\u00b2::T\nend\n\nGaussianLikelihood() = GaussianLikelihood(1e-6)\n\n@functor GaussianLikelihood\n\n(l::GaussianLikelihood)(f::Real) = Normal(f, sqrt(l.\u03c3\u00b2))\n\n(l::GaussianLikelihood)(fs::AbstractVector{<:Real}) = MvNormal(fs, sqrt(l.\u03c3\u00b2))\n\n\"\"\"\n    HeteroscedasticGaussianLikelihood(\u03c3\u00b2)\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\u00e8 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\u03c1, \u03b8 = 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) \u2264 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 \u00f7 squares_poly)(prime) \n    # @show \"after square free:\", ff\n\n    # make f monic\n    old_coeff = leading(ff).coeff\n    ff = (ff \u00f7 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 \u00f7 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 \u00f7 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) \u00f7 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 \u00f7 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) \u00f7 2\n    g = gcd(pow_mod(w,n_power,prime) - one(Polynomial), f, prime)\n    g\u0304 = (f \u00f7 g)(prime) # g\\bar + [TAB]\n    return vcat(dd_split(g, d, prime), dd_split(g\u0304, 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\u2020\nJOURNAL OF COMPUTATIONAL PHYSICS 124, 93\u2013114 (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, \u03be, \u03b7)\n        X, Y = tan(\u03c0 * \u03be / 4), tan(\u03c0 * \u03b7 / 4)\n        \u03b61 = sR / sqrt(X^2 + Y^2 + 1)\n        \u03b62, \u03b63 = X * \u03b61, Y * \u03b61\n        \u03b61, \u03b62, \u03b63\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               |       \u2193 |\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+\u0394, xs+2\u0394, ..., xe]\n    xci = view(xc, 2:ne)                   # [xs+\u0394, xs+2\u0394, ..., xe-\u0394]\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 \u0394 = (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 \u2264 panelno \u2264 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, \u03b3 = nothing)\n\nSynthesize H\u2082-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 `\u03b3 = nothing`, use the formulas for H\u2082 in Ch 14.5. If \u03b3 is a large value, the H\u221e formulas are used. As \u03b3 \u2192 \u221e, these two are equivalent. The h\u221e formulas do a coordinate transfromation that handles slightly more general systems so if you run into an error, it might be worth trying setting \u03b3 to something large, e.g., 1000.\n\"\"\"\nfunction h2synthesize(P::ExtendedStateSpace, \u03b3 = nothing)\n\n    if \u03b3 === nothing\n        X2, Y2, F2, L2 = _solvematrixequations2(P)\n        A\u03022 = P.A + P.B2*F2 + L2*P.C2\n        K = ss(A\u03022, -L2, F2, 0)\n        return K, lft(ss(P), K)\n    end\n    \n    P\u0304, Ltrans12, Rtrans12, Ltrans21, Rtrans21 = _transformp2pbar(P)\n    X2, Y2, F2, L2 = _solvematrixequations(P\u0304, \u03b3)\n\n    _checkfeasibility(\n        X2,\n        Y2,\n        \u03b3,\n        1e-3,\n        10;\n        verbose = false,\n    ) || throw(DomainError(\"Not feasible for \u03b3 = $\u03b3\"))\n\n\n    K = _synthesizecontroller(\n        P\u0304,\n        X2,\n        Y2,\n        F2,\n        L2,\n        \u03b3,\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# \u2554\u2550\u2561 f29303e2-1d66-11eb-3313-f335871e9674\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 f2935b8a-1d66-11eb-02e8-3dacec840928\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing LinearAlgebra, StatsBase, DataFrames\nend\n\n# \u2554\u2550\u2561 7877839e-1d66-11eb-0a3c-5953d222ccbc\nmd\"## Listing 1.8\"\n\n# \u2554\u2550\u2561 f293d704-1d66-11eb-36d8-4bb2f8dff940\nmd\"##### Transition probability matrix.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f2a0c444-1d66-11eb-0f37-99e69755fe8f\nmd\"##### First way.\"\n\n# \u2554\u2550\u2561 f2a67846-1d66-11eb-022c-6f0a51c33a42\npiProb1 = (P^100)[1,:]\n\n# \u2554\u2550\u2561 f2b43238-1d66-11eb-3713-c5c8f2d4af76\nmd\"##### Second way.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f2c17bc8-1d66-11eb-0569-9b84c6b33cca\nmd\"##### Third way.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f2d180ba-1d66-11eb-216b-e3e640811323\nmd\"##### Fourth way.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f2dbd9d2-1d66-11eb-12b9-af2d7f1f73da\nDataFrame(:piProb1 => piProb1, :piProb2 => piProb2, :piProb3 => piProb3, :piProb4 => piProb4)\n\n# \u2554\u2550\u2561 f2e37750-1d66-11eb-3f4e-e7b249fb2052\nmd\"## End of listing 1.8\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25007877839e-1d66-11eb-0a3c-5953d222ccbc\n# \u2560\u2550f29303e2-1d66-11eb-3313-f335871e9674\n# \u2560\u2550f2935b8a-1d66-11eb-02e8-3dacec840928\n# \u255f\u2500f293d704-1d66-11eb-36d8-4bb2f8dff940\n# \u2560\u2550f2a01cf8-1d66-11eb-3573-d91ed64fb7bc\n# \u255f\u2500f2a0c444-1d66-11eb-0f37-99e69755fe8f\n# \u2560\u2550f2a67846-1d66-11eb-022c-6f0a51c33a42\n# \u255f\u2500f2b43238-1d66-11eb-3713-c5c8f2d4af76\n# \u2560\u2550f2b4d63e-1d66-11eb-3d9f-65ba9b1ac506\n# \u255f\u2500f2c17bc8-1d66-11eb-0569-9b84c6b33cca\n# \u2560\u2550f2c2e8fa-1d66-11eb-3421-3d76cd8c9a73\n# \u255f\u2500f2d180ba-1d66-11eb-216b-e3e640811323\n# \u2560\u2550f2da9662-1d66-11eb-1f95-3da69865d370\n# \u2560\u2550f2dbd9d2-1d66-11eb-12b9-af2d7f1f73da\n# \u255f\u2500f2e37750-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": "#!/usr/bin/env julia\n#\n# Jerzy Wroczy\u0144ski (nr. indeksu 250075)\n# Obliczenia Naukowe, Laboratorium\n# Lista 5.\n#\n\ninclude(\"utilities.jl\")\nusing .utilities\n\ninclude(\"blocksys.jl\")\nusing .blocksys\n\ninclude(\"generate-a-test.jl\")\nusing .testdata\n\nglobal l = 4\n\nglobal n = parse(Int, ARGS[1])\n\nlet A, b\nend\n\n# whether to run with classic built-in algorithm\nclassic = \"classic\" in ARGS\n\n# whether to run using a custom sparse matrix solution\ncustom = \"custom\" in ARGS\n\n# whether to run improved algorithm with pivoting\npivot = \"pivot\" in ARGS\n\n# whether to run using the LU decomposition\nlu = \"lu\" in ARGS\n\nprintln(stderr, \"loading data...\")\nif n == 16\n    # read the already pregenerated testfiles\n    A = utilities.Amatrix(\"test-data/n16/A.txt\", custom)\n    b = utilities.bmatrix(\"test-data/n16/b.txt\")\nelse\n    pathA, pathb = testdata.generateTestData(n, l)\n    A = utilities.Amatrix(pathA, custom)\n    b = utilities.bmatrix(pathb)\nend\n\nlet x\u0303\nend\n\nprintln(stderr, \"finding solution...\")\n@time if classic\n    println(stderr, \"classic algorithm\")\n    x\u0303 = A\\b\nelse\n    println(stderr, \"improved algorithm\")\n    let pivot\n    end\n\n    # by default don\u2019t perform pivoting\n    pivot_ = [i for i in 1:n]\n\n    if pivot\n        # calculate the pivot row permutation vector\n        pivot_ = blocksys.partialPivot(A, n, l, true)\n    end\n\n    if lu\n        LU, _ = blocksys.decomposeIntoLU(A, b, n, l, pivot_)\n        x\u0303 = blocksys.solveFromLU(LU, b, n, l, pivot_)\n    else\n        # calculate the `x` vector\n        x\u0303 = blocksys.gaussianElimination(A, b, n, l, pivot_)\n    end\nend\n\n# print relative error\nprintln(\"relative error = \", utilities.relativeError(x\u0303))\n", "meta": {"hexsha": "52f543acdabf01202734e3c4f14a66e2812f40d1", "size": 1650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5th-semester/on/lab/lista-5/code/run-a-test.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-5/code/run-a-test.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-5/code/run-a-test.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": 21.1538461538, "max_line_length": 61, "alphanum_fraction": 0.6721212121, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8652240704135291, "lm_q1q2_score": 0.7741933815968928}}
{"text": "using ApproxFun, Base.Test\n\n\n## PDEs\n\nd=Interval()^2\n\nx=Fun(identity,d[1]);y=Fun(identity,d[2])\n\n#dirichlet(d) is u[-1,:],u[1,:],u[:,-1],u[:,1]\nA=[dirichlet(d);lap(d)]\nf=[real(exp(-1+1.0im*y));\n                        real(exp(1+1im*y));\n                        real(exp(x-1im));\n                        real(exp(x+1im))]\nS=schurfact(A,100)\n@time S=schurfact(A,100)\nu=S\\f\nu=S\\f\n@time u=S\\f;\nprintln(\"Laplace: should be ~0.014, 0.01\")\n\n\n\nd=Interval()^2\nS=schurfact([neumann(d);lap(d)+100I],100)\n@time S=schurfact([neumann(d);lap(d)+100I],100)\nu=S\\ones(4)\nu=S\\ones(4)\n@time u=S\\ones(4)\nprintln(\"Neumann Helmholtz: should be ~0.016, 0.016\")\n\n\n\n\ndx=Interval(0.,1.);dt=Interval(0.0,0.54)\nd=dx*dt\n\nV=Fun(x->x^2,dx)\n\nDt=Derivative(d,[0,1]);Dx=Derivative(d,[1,0])\n\n\u03f5=0.1\n\nu0=Fun(x->exp(-25*(x-.5)^2)*exp(-1.0im/(5*\u03f5)*log(2cosh(5*(x-.5)))),dx)\nL=1im*\u03f5*Dt+.5*\u03f5^2*Dx^2-V\u22971\n\nPO=discretize([timedirichlet(d);L],50)\n@time PO=discretize([timedirichlet(d);L],50)\nu=PO\\u0\n@time    u=PO\\u0\n\nprintln(\"Schrodinger: should be ~0.013,0.015\")\n", "meta": {"hexsha": "89cdadc44ce268dad85f2288df098672deccdc4b", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SpeedPDETest.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": "test/SpeedPDETest.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": "test/SpeedPDETest.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": 18.8888888889, "max_line_length": 70, "alphanum_fraction": 0.5803921569, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7741902181633332}}
{"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 `\u00b5`/`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 `\u00b5`/`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": "using Test, TSVD, LinearAlgebra, SparseArrays\n\n@testset \"test tsvd with m = $m, n = $n, and p = $p\" for\n    (m, n, p) in ((10, 6, 0.8),\n                  (6, 10, 0.8),\n                  (10, 10, 0.8),\n                  (100, 60, 0.1),\n                  (60, 100, 0.1),\n                  (100, 100, 0.1))\n\n    mnp = round(Integer, m*n*p)\n\n    for A in (randn(m, n),\n              complex.(randn(m, n), randn(m, n)),\n              sprandn(m, n, p),\n              sparse(rand(1:m, mnp), rand(1:n, mnp), complex.(randn(mnp), randn(mnp)), m, n))\n\n        Uf, sf, Vf = svd(Array(A))\n\n        for k = 1:5\n            U, s, V = TSVD.tsvd(A, k)\n            @test norm(s - sf[1:k]) < sqrt(eps(real(eltype(A))))*mnp\n            @test norm(abs.(U'Uf[:,1:k]) - I) < sqrt(eps(real(eltype(A))))*mnp\n            @test norm(abs.(V'Vf[:,1:k]) - I) < sqrt(eps(real(eltype(A))))*mnp\n\n            s, V = TSVD.tsvd2(A, k)\n            # tmp = TSVD._teig(TSVD.AtA(A, randn(n)), k, debug = true)\n            # @test norm(sqrt(reverse(tmp[1]))[1:k] - sf[1:k]) < sqrt(eps(real(eltype(A))))*mnp\n            @test norm(s - sf[1:k]) < sqrt(eps(real(eltype(A))))*mnp\n            @test norm(abs.(V'Vf[:,1:k]) - I) < sqrt(eps(real(eltype(A))))*mnp\n        end\n    end\nend\n\n@testset \"Issue 9\" begin\n    data = rand(1:100, 50, 50)\n    @test @inferred(TSVD.tsvd(data, 2))[2] \u2248 svdvals(data)[1:2]\nend\n\n@testset \"Issue 25. Degenerate basis\" begin\n  @test tsvd([1 0 ; 0 1], 1, initvec=[1.0; 0.0])[2] \u2248 [1.0]\nend\n", "meta": {"hexsha": "5820e6ccef8ba71b763016692666f60d945a69fe", "size": 1473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaLinearAlgebra/TSVD.jl", "max_stars_repo_head_hexsha": "dc8a11a95756d58af5a87ee88ee3a61c96b7ff8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:26:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T09:43:43.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "JuliaLinearAlgebra/TSVD.jl", "max_issues_repo_head_hexsha": "dc8a11a95756d58af5a87ee88ee3a61c96b7ff8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-03-17T16:59:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T20:18:48.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "andreasnoack/TSVD.jl", "max_forks_repo_head_hexsha": "dc8a11a95756d58af5a87ee88ee3a61c96b7ff8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-06-15T13:43:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-17T05:04:33.000Z", "avg_line_length": 34.2558139535, "max_line_length": 95, "alphanum_fraction": 0.466395112, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7741902046060789}}
{"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": "using Triangulation_diagrams\nusing PyPlot\n\nN = [ 0  1  2  4  4  5  3  3  2  1  5  6  6  2  6  4\n      2  1  0  0  2  1  1  3  2  3  3  0  4  4  2  4 ]\n\nT = [  1  3  3  5  5\n       3  5 12 12 13\n      14 14  5 13 14\n       9  8  6 15 16\n      10  9  7 11  8\n       2  7  4  6 11 ]\n\nE = [ 14 10  1  2  3  4 12 15 13 16\n      10  1  2  3  4 12 15 13 16 14 ]\n\nQN = 6\n\ntri = Triangulation(N, T, E, QN)\n\nfigure(1)\ndraw_triangles(tri)\nenumerate_vertices(tri)\nenumerate_triangles(tri)\nenumerate_bdry_edges(tri, 0.2)\nmark_first_local_vertex(tri, 0.3)\naxis(\"off\")\nsavefig(\"quad_triangulation.pdf\")\n", "meta": {"hexsha": "1bcaa6ff85596cbe563aff04840829050ee6d202", "size": 588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap6/quadratic_elts.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/quadratic_elts.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/quadratic_elts.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": 20.275862069, "max_line_length": 54, "alphanum_fraction": 0.5544217687, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7741902024105648}}
{"text": "# # Chebyshev center\n# Boyd & Vandenberghe, \"Convex Optimization\"\n# Jo\u00eblle 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) \u2248 0.0020781361856598\n    main(unknown_storage=:dense) \u2248 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 ``\u0395^2``, i.e. a straight line\nsegment ``[p, q]`` connecting two points ``p, q \u2208 \u211d^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": "using LinearAlgebra\n\nimport Base: iszero\n\npcTol(::Type{T}) where {T <: Integer}       = zero(T)\npcTol(::Type{T}) where {T <: Rational}      = zero(T)\npcTol(::Type{T}) where {T <: Float32}       = T(1f-3)\npcTol(::Type{T}) where {T <: Float64}       = T(1e-6) \n\niszero(n::T, tol::T=pcTol(T)) where {T <: Number} = -tol <= n <= tol\n\nconst notvoid = Base.notnothing\nconst _nv = notvoid\n\n\"\"\"\n```\n    parallelogram_area(m::Matrix) -> Number\n```\nArea of the parallelogram. The matrix is a 2x3 matrix.\n\"\"\"\nfunction parallelogram_area(p1::Tuple{T, T},\n                            p2::Tuple{T, T},\n                            p3::Tuple{T, T}) where T <: Number\n    v1 = (p2[1]-p3[1], p2[2]-p3[2])\n    v2 = (p3[1]-p1[1], p3[2]-p1[2])\n    v3 = (p1[1]-p2[1], p1[2]-p2[2])\n    v = max(dot(v1, v1), dot(v2, v2), dot(v3, v3))\n    \n    d = v3[1]*v1[2] - v1[1]*v3[2]\n\n    v*pcTol(T)*pcTol(T) >= d*d && return zero(T)\n    return d\nend\n\n", "meta": {"hexsha": "050b38e5bb339c8fe38de08d297a18073c254b05", "size": 917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Rectangle.jl-9a9db56c-8f71-5460-add5-cb450131785e", "max_stars_repo_head_hexsha": "6a3427b4b883a6fa7903826d9e0c592e2e56e2ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-01-26T19:34:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T14:47:11.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Rectangle.jl-9a9db56c-8f71-5460-add5-cb450131785e", "max_issues_repo_head_hexsha": "6a3427b4b883a6fa7903826d9e0c592e2e56e2ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-01-25T08:17:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T20:31:38.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Rectangle.jl-9a9db56c-8f71-5460-add5-cb450131785e", "max_forks_repo_head_hexsha": "6a3427b4b883a6fa7903826d9e0c592e2e56e2ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:49:56.000Z", "avg_line_length": 26.2, "max_line_length": 68, "alphanum_fraction": 0.5212649945, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7741785952803767}}
{"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\u03bc, \u03a3 =  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(\u03bc[j]*x[j] for j=1:n) >= r_min/T);\n\n@objective(port, Min , sum(x[i]*\u03a3[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 = \u03bc*alloc*T\n# Looking at risk as the st. deviation of the returns.\nrisk = sqrt(alloc'*\u03a3*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, \u0393)\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) + \u0393*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\u0393_range = linspace(0,1,10)\n\n# storing the results of each run\nfeas = []\ntotal_value = []\n\u0393_used = []\n\n# for each Gamma, solve te model and store the results\nfor \u0393 in \u0393_range\n    println(\u0393)\n    x = solve_robust_model(N, value, weight_average, P, \u0393)\n    push!(\u0393_used, \u0393)\n    push!(feas, feasibility_estimate(x,5000))\n    push!(total_value, value'x)\nend\n\n# potting the results from simulation\np1 = plot(\u0393_used, feas, xlabel = L\"\\Gamma\", ylabel = \"feas. prob.\", legend=false)\np2 = plot(\u0393_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, \u03b4)\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        + \u03b4*(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 \u03b4=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\u0394 = lat2 - lat1\n  lon\u0394 = lon2 - lon1\n\n  a = sin(.5lat\u0394)^2 + cos(lat1)*cos(lat2)*sin(.5lon\u0394)^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 = \u03c0/2 - lat1\n  b = \u03c0/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  \u0192 = (a - b) / a\n  b = (1 - \u0192)*a\n\n  u1 = atan((1-\u0192)*tan(lat1))\n  u2 = atan((1-\u0192)*tan(lat2))\n  L = lon2 - lon1\n  sin\u03c3 = 0.\n  cos\u03c3 = 0.\n  cos2\u03b1 = 0.\n  cos2\u03c3m = 0.\n  \u03c3 = 0.\n\n  \u03bb = copy(L)\n  \u03bb2 = \u03bb\n  \u03b4 = 1. + tol\n  n = 0\n\n  while \u03b4 > tol && n < maxiter\n    n += 1\n    sin\u03c3 = sqrt( (cos(u2)*sin(\u03bb))^2 + (cos(u1)*sin(u2)-sin(u1)*cos(u2)*cos(\u03bb))^2 )\n    cos\u03c3 = sin(u1)*sin(u2) + cos(u1)*cos(u2)*cos(\u03bb)\n    \u03c3 = atan(sin\u03c3/cos\u03c3)\n    sin\u03b1 = (cos(u1)*cos(u2)*sin(\u03bb))/sin\u03c3\n    cos2\u03b1 = 1 - sin\u03b1^2\n    cos2\u03c3m = cos\u03c3 - (2*sin(u1)*sin(u2))/cos2\u03b1\n    C = \u0192/16 * cos2\u03b1*(4 + \u0192*(4-3cos2\u03b1))\n\n    x1 = cos2\u03c3m + C*cos\u03c3*(-1+2cos2\u03c3m^2)\n    x2 = \u03c3 + C*sin\u03c3*x1\n    \u03bb = L + (1-C)*\u0192*sin\u03b1*x2\n    \u03b4 = abs(\u03bb-\u03bb2)\n    \u03bb2 = copy(\u03bb)\n  end\n\n  if n == maxiter && \u03b4 > tol && verbose\n    println(\"Warning: vincenty formula did not converge to desired tolerance.\")\n  end\n\n  \u03bc2 = cos2\u03b1 * (a^2 - b^2)/(b^2)\n  A = 1 + \u03bc2/16384*(4096 + \u03bc2*(-768+\u03bc2*(320-175\u03bc2)))\n  B = (\u03bc2/1024)*(256 + \u03bc2*(-128+\u03bc2*(74-47\u03bc2)))\n\n  x3 = cos2\u03c3m + .25B*(cos\u03c3*(-1+2cos2\u03c3m^2))\n  x4 = (1/6)*B*cos2\u03c3m*(-3+4sin\u03c3^2)*(-3+4cos2\u03c3m^2)\n  \u0394\u03c3 = B*sin\u03c3*(x3-x4)\n\n  return b*A*(\u03c3 - \u0394\u03c3)\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\u03c0t), sin(2\u03c0t)]` from `[0,1)` to the unit circle in `\u211d^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    \u03b8 = atan(x[2],x[1])\n    if \u03b8 < 0\n        # atan2 returns an angle in (-\u03c0,\u03c0], convert to [0,2\u03c0) using periodicity.\n        \u03b8 += twopi\n    end\n    # And divide by 2\u03c0 to scale to [0,1)\n    \u03b8 / 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": "# plot gaussian probabilistic distribution\n# using cumulative distribution function\n\nmodule GaussProbDistCdf\n    using Plots, Distributions\n    pyplot()\n\n    function main(is_test=false)\n        norm_dist = Normal(209.7, 4.84) # mu, std_dev\n\n        zs = Array(193:229)\n        ys = [cdf(norm_dist, z) for z in zs]\n        plot(zs, ys, color=:red, label=\"CDF\")\n\n        if is_test == false\n            save_path = joinpath(split(@__FILE__, \"src\")[1], \"src/prob_stats/prob_model/gauss_prob_dist_cdf/gauss_prob_dist_cdf.png\")\n            savefig(save_path)\n        end\n    end\nend", "meta": {"hexsha": "709c0495a0550c6acef8dadeeb433f64d3926ba1", "size": 578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/prob_stats/prob_model/gauss_prob_dist_cdf/gauss_prob_dist_cdf.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/prob_model/gauss_prob_dist_cdf/gauss_prob_dist_cdf.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/prob_model/gauss_prob_dist_cdf/gauss_prob_dist_cdf.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.9, "max_line_length": 133, "alphanum_fraction": 0.6487889273, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7741785767859426}}
{"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": "module Functions\nexport sigmoid, relu, softmax, cross_entropy_error\n\n# TODO:\u95a2\u6570\u306e\u5185\u90e8\u306bdot\u3092\u4ed8\u3051\u308b\u306e\u3067\u306f\u306a\u304f\uff0c\u95a2\u6570\u306e\u547c\u3073\u51fa\u3057\u5143\u306bdot\u3092\u4ed8\u3051\u308b\u3088\u3046\u306b\u5909\u66f4\nfunction sigmoid(x)\n    return 1 ./ (1 .+ exp.(-x))\nend\n\nfunction relu(x)\n    return max(0, x) # NOT maximum()\nend\n\n\nfunction softmax(x)\n    y = []\n    for row_i = 1:size(x, 1)\n        c = maximum(x[row_i, :])\n        exp_a = exp.(x[row_i, :] .- c) # \u30aa\u30fc\u30d0\u30d5\u30ed\u30fc\u5bfe\u7b56\n        push!(y, exp_a ./ sum(exp_a))\n    end\n    return hcat(y...)' # cf. https://docs.julialang.org/en/v1/manual/faq/?highlight=splat#What-does-the-...-operator-do?\nend\n\nfunction cross_entropy_error(y, t)\n    return -sum(t .* log.(y .+ 1e-7)) # 0\u9664\u7b97\u3092\u56de\u907f\u3059\u308b\u305f\u3081\u306b\u5fae\u5c0f\u306a\u5024\u3092\u52a0\u7b97\nend\nend", "meta": {"hexsha": "fedf492ab0d3ddb574f58cc437d00d5fe85f61d6", "size": 650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "common/functions.jl", "max_stars_repo_name": "skypenguins/Deep-Learning-from-Scratch-2", "max_stars_repo_head_hexsha": "9e284f5b4f552946bdf0340b8e010ed6dd0984ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common/functions.jl", "max_issues_repo_name": "skypenguins/Deep-Learning-from-Scratch-2", "max_issues_repo_head_hexsha": "9e284f5b4f552946bdf0340b8e010ed6dd0984ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/functions.jl", "max_forks_repo_name": "skypenguins/Deep-Learning-from-Scratch-2", "max_forks_repo_head_hexsha": "9e284f5b4f552946bdf0340b8e010ed6dd0984ab", "max_forks_repo_licenses": ["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.0740740741, "max_line_length": 120, "alphanum_fraction": 0.6369230769, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7741690857655873}}
{"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\u2080=[3,0.1,0.1,0.5]\nr\u2080=6\nv\u2080=0\n\n#function to compute lagrangian\nfunction lagrangian!(du,u,p,t)\n    \u03b8,\u03c9,\u03d5,\u03c8=u\n    v=v\u2080\n    r=r\u2080+v*t\n    du[1]=d\u03b8=\u03c9\n    du[2]=d\u03c9=sin(\u03b8)*cos(\u03b8)*\u03c8^2-((2*v*\u03c9)/r)+((g*sin(\u03b8))/r)\n    du[3]=d\u03d5=\u03c8\n    du[4]=d\u03c8=-((2*v*\u03c8)/r)-(2*cot(\u03b8)*\u03c9*\u03c8)\nend\n\n#time interval\ntspan=(0.0,20.0)\n\n#defining the problem and solving\nprob=ODEProblem(lagrangian!,u\u2080,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(\u03b81,\u03c91,\u03d51,\u03c81)=[U1[x,:] for x in 1:size(U1,1)]\nt=sol1.t\n\nU2=sol2[1:end,:]\n(\u03b82,\u03c92,\u03d52,\u03c82)=[U2[x,:] for x in 1:size(U2,1)]\nt=sol2.t\n\nU3=sol3[1:end,:]\n(\u03b83,\u03c93,\u03d53,\u03c83)=[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=\"\u03b8 (rad)\")\np2=plot!(p1,sol2,vars=(0,1),label=\"rtol=1e-3,atol=1e-6\",\n    color=\"blue\", xaxis=\"t (s)\", yaxis=\"\u03b8 (rad)\")\np3=plot!(p2,sol3,vars=(0,1),label=\"rtol=1e-5,atol=1e-8\",\n    color=\"red\", xaxis=\"t (s)\", yaxis=\"\u03b8 (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=\"\u03d5 (rad)\")\np5=plot!(p4,sol2,vars=(0,3),label=\"rtol=1e-3,atol=1e-6\",\n    color=\"blue\", xaxis=\"t (s)\", yaxis=\"\u03d5 (rad)\")\np6=plot!(p5,sol3,vars=(0,3),label=\"rtol=1e-5,atol=1e-8\",\n    color=\"red\", xaxis=\"t (s)\", yaxis=\"\u03d5 (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\u00f3pez, D. and Mu\u00f1oz-Pacheco, J. M. and F\u00e9lix-Beltr\u00e1n, O. G. and Volos, C.},  \nbooktitle={2019 8th International Conference on Modern Circuits and Systems Technologies (MOCAST)},   \ntitle={Efficient Computation of the Gr\u00fcnwald-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, \u03b1, 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+\u03b1)/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^\u03b1 - 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\u2013Warshall_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\u03b2 = [10., -1.]\n\u03f5 = randn(n)\ny = x*\u03b2 + \u03f5\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\u1d62 = \u03b2 -> (y-x*\u03b2).^2.  \t# i\u1d57\u02b0 obs contrib to sum of squares\nobj = \u03b2 -> mean(obj\u1d62(\u03b2))\t# average objective\ntol = 1e-08\n\u03b2hat = 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 \u2110, the covariance of the score \n\tcontributions, and \ud835\udca5, the Hessian matrix.\n=#\n\n# the calculations to get \u2110 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\u1d62, \u03b2hat) # get the score contributions\n# from theory, we know that sc = -2x.*\u03f5cat. Let's use this verify\n# that the automatic differentiation worked.\nsc - (-2x.*(y - x*\u03b2hat))\n\n##\n\n# Next, we use the score contributions to estimate \u2110 \n\u2110hat = zeros(2,2)\nfor i = 1:n\n\t\u2110hat .+= sc[i,:]*sc[i,:]'\nend\n\u2110hat ./= 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\ud835\udca5hat = ForwardDiff.hessian(obj, \u03b2hat)\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\u221e = inv(\ud835\udca5hat)*\u2110hat*inv(\ud835\udca5hat) # this is the estimate of the limiting var of \u221an(\u03b2-\u03b2\u2070) \nse = sqrt.(diag(v\u221e/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\u00b2 + 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-\u03b1)% confidence intervals,\n# and verify that the pseudo-true values lie inside them approximately 100x(1-\u03b1)% 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\u03b1 = 0.05\t\t\t# try out 90, 95 and 99% CIs\ncrit = quantile(Normal(),1-\u03b1/2)\n\u03b2\u2070 = [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\u03b2hat, v\u03b2hat, junk = ols(y, X, silent=true)\n\tse = sqrt.(diag(v\u03b2hat))\n\tinci[i,:] = (\u03b2\u2070 .>= \u03b2hat .- crit*se) .& (\u03b2\u2070 .<= \u03b2hat .+ crit*se)\nend\nci = Int64(100*(1-\u03b1))\nprintln(\"Coverage of $ci% CIs\")\nmean(inci, dims=1) # these should be approximately 1-\u03b1, 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 \u03b2c = 0.5*log(sqrt(2.0)+1.0)\n\nfunction ising_free_energy(\u03b2::Real,J::Real=1.0)\n  k = \u03b2*J\n  c = cosh(2.0*k)\n  s = sinh(2.0*k)\n  xmin = 0.0\n  xmax = \u03c0\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/\u03c0)/(2.0*\u03b2)\nend\n\nfunction ising_magnetization(\u03b2::Real)\n \u03b2>\u03b2c && return (1.0-sinh(2.0*\u03b2)^(-4))^(1/8)\n return 0.0\nend\n\nfunction ising_mpo(sh::Tuple{Index,Index},sv::Tuple{Index,Index},\n                   \u03b2::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(\u03b2*J) exp(-\u03b2*J); exp(-\u03b2*J) exp(\u03b2*J)]\n    D,U = eigen(Symmetric(Q))\n    \u221aQ = U*Diagonal(sqrt.(D))*U'\n    Xh1 = ITensor(vec(\u221aQ),sh[1],sh[1]')\n    Xh2 = ITensor(vec(\u221aQ),sh[2],sh[2]')\n    Xv1 = ITensor(vec(\u221aQ),sv[1],sv[1]')\n    Xv2 = ITensor(vec(\u221aQ),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(-\u03b2*(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": "using FractalTools\nusing Plots \nusing Cubature \n\n# Definitions \nti, ts, tf = 0, 0.1, 1.\nt = ti : ts : tf \nf(t) = sin(2\u03c0 * t) \ng(t) = cos(2\u03c0 * t)\n# f(t) = t * (1 - t)\n\n# Construct interpolation \ninterp = interpolate(t, f.(t), d=0.01)\n\n# Construct hidden interpolation \nhiddeninterp = hiddenfif(t, f.(t), g.(t)) \n\n# Quadratute integration\nhquad(tk) = hquadrature(f, ti, tk, abstol=1e-9)[1]\n\n# Fractal integration \nhfrac(tk) = integrate(ti:ts:tk, f.(ti:ts:tk), d=0.01)\n\n# Fractal hidden integration \nhhiddenfrac(tk) = integrate(ti:ts:tk, f.(ti:ts:tk), g.(ti:ts:tk))\n\n# Plots \ntd = 0 : 0.01 * ts : tf \nplot(td, f.(td), label=\"f\")\nplot!(td, hquad.(td), label=\"intfquad\")\nplot!(td, hfrac.(td), label=\"intffrac\")\nplot!(td, hhiddenfrac.(td), label=\"intfhiddenfrac\")\nplot!(td, getindex.(hiddeninterp.(td), 1), label=\"fhiddenfrac\")\nscatter!(t, f.(t), marker=(:circle, 2), label=\"data\")\n", "meta": {"hexsha": "cbd5f9fada0e495e98b028de3c7949e748ad13f7", "size": 876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/stash/integration/onedim.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/integration/onedim.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/integration/onedim.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.0285714286, "max_line_length": 65, "alphanum_fraction": 0.6358447489, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7741243119317467}}
{"text": "using NDTensors,\n      Test\nusing LinearAlgebra\n\n@testset \"random_orthog\" begin\n  n,m = 10,4\n  O1 = random_orthog(n,m)\n  @test norm(transpose(O1)*O1 - Diagonal(fill(1.,m))) < 1E-14\n\n  n,m = 4,10\n  O2 = random_orthog(n,m)\n  @test norm(O2*transpose(O2) - Diagonal(fill(1.,n))) < 1E-14\nend\n\n@testset \"random_unitary\" begin\n  n,m = 10,4\n  U1 = random_unitary(n,m)\n  @test eltype(U1) <: ComplexF64\n  @test norm(U1'*U1 - Diagonal(fill(1.,m))) < 1E-14\n\n  n,m = 4,10\n  U2 = random_unitary(n,m)\n  @test norm(U2*U2' - Diagonal(fill(1.,n))) < 1E-14\nend\n\nnothing\n", "meta": {"hexsha": "2a4e86fbe1a0640b1a4cb3a4bdc2071624cebe07", "size": 551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/linearalgebra.jl", "max_stars_repo_name": "emstoudenmire/NDTensors.jl", "max_stars_repo_head_hexsha": "ed998458da4fba5be106416187f546cb85bb89c3", "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/linearalgebra.jl", "max_issues_repo_name": "emstoudenmire/NDTensors.jl", "max_issues_repo_head_hexsha": "ed998458da4fba5be106416187f546cb85bb89c3", "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/linearalgebra.jl", "max_forks_repo_name": "emstoudenmire/NDTensors.jl", "max_forks_repo_head_hexsha": "ed998458da4fba5be106416187f546cb85bb89c3", "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.4074074074, "max_line_length": 61, "alphanum_fraction": 0.6352087114, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.774124308274724}}
{"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# \u2211S(i) for 2 \u2264 i \u2264 10^2 == 2012\n# \u2211S(i) for 2 \u2264 i \u2264 10^6 == 64938007616\n# \u2211S(i) for 2 \u2264 i \u2264 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(\"\u2211S(i) for 2 \u2264 i \u2264 $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#\n# The Stopping structure eases the implementation of algorithms and the\n# stopping criterion.\n#\n# The following examples illustrate solver for linear algebra:\n#  Ax = b with A an m x n matrix.\n#\n# This tutorial illustrates the different step in preparing the resolution of a\n# new problem.\n# - we create a LinearAlgebraPRoblem (that stores A, b)\n# - we use the GennericState storing x and the current_time\n# - we create a LinearAlgebraStopping\n# - the optimality function linear_system_check!\n#\n# A more sophisticated version can be found in LAStopping.\n#\n###############################################################################\nusing LinearAlgebra, Stopping, Test\n\nm, n = 400, 200 #size of A: m x n\nA    = 100 * rand(m, n)\nxref = 100 * rand(n)\nb    = A * xref\n\n#Our initial guess\nx0 = zeros(n)\n\nmutable struct LinearAlgebraProblem\n    A :: Any #matrix type\n    b :: Vector\nend\n\nla_pb = LinearAlgebraProblem(A, b)\nla_state = GenericState(xref)\n\n@test norm(la_pb.A * xref - la_pb.b) <= 1e-6\n\nmutable struct LinearAlgebraStopping <: AbstractStopping\n\n        # problem\n        pb :: LinearAlgebraProblem\n\n        # Common parameters\n        meta :: AbstractStoppingMeta\n\n        # current state of the problem\n        current_state :: AbstractState\n\n        # Stopping of the main problem, or nothing\n        main_stp :: Union{AbstractStopping, Nothing}\n\n        function LinearAlgebraStopping(pb               :: LinearAlgebraProblem,\n                                       current_state    :: AbstractState; kwargs...)\n         return new(pb, linear_system_check!, StoppingMeta(;optimality_check = linear_system_check, kwargs...), la_state, nothing)\n        end\nend\n\nfunction linear_system_check(pb    :: LinearAlgebraProblem,\n                             state :: AbstractState; kwargs...)\n return norm(pb.A * state.x - pb.b)\nend\n\n@test linear_system_check(la_pb, la_state) == 0.0\nupdate!(la_state, x = x0)\n@test linear_system_check(la_pb, la_state) != 0.0\n\nla_stop = LinearAlgebraStopping(la_pb, la_state,\n                                max_iter = 150000, rtol = 1e-6, optimality_check = linear_system_check)\n\n\"\"\"\nRandomized block Kaczmarz\n\"\"\"\nfunction RandomizedBlockKaczmarz(stp :: AbstractStopping; kwargs...)\n\n    #A,b = stp.current_state.Jx, stp.current_state.cx\n    A,b = stp.pb.A, stp.pb.b\n    x0  = stp.current_state.x\n\n    m,n = size(A)\n    xk  = x0\n\n    OK = start!(stp)\n\n    while !OK\n\n     i  = Int(floor(rand() * m)+1) #rand a number between 1 and m\n     Ai = A[i,:]\n     xk  = Ai == 0 ? x0 : x0 - (dot(Ai,x0)-b[i])/dot(Ai,Ai) * Ai\n\n     OK = update_and_stop!(stp, x = xk)\n     x0  = xk\n\n    end\n\n return stp\nend\n\nRandomizedBlockKaczmarz(la_stop)\n@test status(la_stop) == :Optimal\n", "meta": {"hexsha": "e57b8203129b607fed5488b64e57ff476857fb14", "size": 2786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/examples/linear-algebra.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": "test/examples/linear-algebra.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": "test/examples/linear-algebra.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": 27.5841584158, "max_line_length": 130, "alphanum_fraction": 0.6170136396, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7741072255860162}}
{"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": "# This problem finds a least cost shipping schedule that meets\n# requirements at markets and supplies at factories.\n#\n# Dantzig, G B, Chapter 3.3. In Linear Programming and Extensions.\n# Princeton University Press, Princeton, New Jersey, 1963.\n\nusing GAMS\nusing JuMP\nusing Test\n\nfunction example_transport(; verbose = true)\n   model = Model(GAMS.Optimizer)\n   set_optimizer_attribute(model, MOI.Silent(), !verbose)\n\n   a = [350, 600]\n   b = [325, 300, 275]\n   d = [2.5 1.7 1.8; 2.5 1.8 1.4]\n\n   @variable(model, x[1:2,1:3] >= 0)\n\n   @objective(model, Min, 0.09 * sum(d[i,j] * x[i,j] for i = 1:2, j = 1:3))\n\n   @constraint(model, [i = 1:2], sum(x[i,j] for j = 1:3) <= a[i])\n   @constraint(model, [j = 1:3], sum(x[i,j] for i = 1:2) >= b[j])\n\n   if verbose\n      print(model)\n   end\n\n   JuMP.optimize!(model)\n\n   obj_opt = JuMP.objective_value(model)\n   x_opt = JuMP.value.(x)\n\n   if verbose\n      println(\"Objective value: \", obj_opt)\n      println(\"x = \", x_opt)\n   end\n\n   @test obj_opt \u2248 153.6750\n   @test x_opt[1,1] \u2248 50.0\n   @test x_opt[1,2] \u2248 300.0\n   @test x_opt[1,3] \u2248 0.0\n   @test x_opt[2,1] \u2248 275.0\n   @test x_opt[2,2] \u2248 0.0\n   @test x_opt[2,3] \u2248 275.0\nend\n\nexample_transport(verbose = false)\n", "meta": {"hexsha": "f016e196396c31ce245e4f5a8b5a991543c792c5", "size": 1201, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/transport.jl", "max_stars_repo_name": "GAMS-dev/gams.jl", "max_stars_repo_head_hexsha": "311026239f63b4d67aa73036a7dc977ce372e4da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-05-14T13:19:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T18:33:03.000Z", "max_issues_repo_path": "examples/transport.jl", "max_issues_repo_name": "GAMS-dev/gams.jl", "max_issues_repo_head_hexsha": "311026239f63b4d67aa73036a7dc977ce372e4da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-06-20T10:33:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T08:15:11.000Z", "max_forks_repo_path": "examples/transport.jl", "max_forks_repo_name": "GAMS-dev/gams.jl", "max_forks_repo_head_hexsha": "311026239f63b4d67aa73036a7dc977ce372e4da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-12T01:15:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T20:57:18.000Z", "avg_line_length": 24.02, "max_line_length": 75, "alphanum_fraction": 0.6194837635, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7741072182761175}}
{"text": "using EmpiricalRisks\nusing Base.Test\nusing DualNumbers\n\n### Auxiliary functions\n\nfunction verify_multiloss(loss::MultivariateLoss, f, u::Vector{Float64}, y)\n    # verify inferred types\n    YT = typeof(y)\n    for VT in [Float64]\n        @test Base.return_types(value, Tuple{typeof(loss), Vector{VT}, YT}) == [VT]\n        @test Base.return_types(grad, Tuple{typeof(loss), Vector{VT}, YT}) == [Vector{VT}]\n        @test Base.return_types(value_and_grad, Tuple{typeof(loss), Vector{VT}, YT}) == [Tuple{VT, Vector{VT}}]\n    end\n\n    # verify computation correctness\n\n    # prepare ground-truth\n    d = length(u)\n    v_r = f(u, y)\n    g_r = zeros(d)\n    for i = 1:d\n        _ep = zeros(d)\n        _ep[i] = 1.0\n        _in = dual(u, _ep)\n        _out = f(_in, y)\n        @assert isa(_out, Dual{Float64})\n        @assert isapprox(v_r, real(_out))\n        g_r[i] = epsilon(_out)\n    end\n\n    # verify\n    @test_approx_eq v_r value(loss, u, y)\n    @test_approx_eq g_r grad(loss, u, y)\n\n    (v, g) = value_and_grad(loss, u, y)\n    @test_approx_eq v_r v\n    @test_approx_eq g_r g\nend\n\n\n### Test cases\n\nk = 3\nn = 8\n\n# Sum squared loss\n\n_sumsqrf(u, y) = sum(abs2(u - y)) / 2\n\nu = randn(k, n)\ny = randn(k, n)\nfor i = 1:n\n    verify_multiloss(SumSqrLoss(), _sumsqrf, copy(u[:,i]), y[:,i])\nend\n\n\n# Multilogistic loss\n\n_mlogisticf(u, y::Int) = log(sum(exp(u))) - u[y]\n\nu = randn(k, n)\nfor i = 1:n, y = 1:k\n    verify_multiloss(MultiLogisticLoss(), _mlogisticf, copy(u[:,i]), y)\nend\n", "meta": {"hexsha": "8fb1f274c51777ca91b03f482aa071d1be3bcee7", "size": 1464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/multiloss.jl", "max_stars_repo_name": "JuliaPackageMirrors/EmpiricalRisks.jl", "max_stars_repo_head_hexsha": "28361a117a4c97a89991a7d99968ba2c7850df03", "max_stars_repo_licenses": ["MIT"], "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/multiloss.jl", "max_issues_repo_name": "JuliaPackageMirrors/EmpiricalRisks.jl", "max_issues_repo_head_hexsha": "28361a117a4c97a89991a7d99968ba2c7850df03", "max_issues_repo_licenses": ["MIT"], "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/multiloss.jl", "max_forks_repo_name": "JuliaPackageMirrors/EmpiricalRisks.jl", "max_forks_repo_head_hexsha": "28361a117a4c97a89991a7d99968ba2c7850df03", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 111, "alphanum_fraction": 0.6031420765, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7741072146747472}}
{"text": "using RDatasets\nusing Random\nusing Statistics\nusing LinearAlgebra\nusing Plots\n\niris = dataset(\"datasets\", \"iris\")\n\nX = Matrix(iris[:, 1:4])\ny = iris.Species\n\n# Exercise\n\n\n\n# Exercise\n\n\n\n# Exercise\n\n\n\n# Preparing data\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\nRandom.seed!(666)\n\niris = dataset(\"datasets\", \"iris\")\n\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# Testing dims in prepare_data\n\nRandom.seed!(666)\naux1 = prepare_data(X, y; dims=1)\nRandom.seed!(666)\naux2 = prepare_data(X', y; dims=2)\n\nnorm(aux1[1] - aux2[1]')\n\n# SimpleNet\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\n\n\n# Initialize SimpleNet\n\nRandom.seed!(666)\n\nm = SimpleNet(size(X_train,1), 5, size(y_train,1))\n\n# Exercise\n\n\n\n# Evaluate SimpleNet\n\nm(X_train[:,1:2]) \n\n# Gradient computation\n\nfunction grad(m::SimpleNet, x::AbstractVector, y; \u03f5=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 .+ \u03f5))\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 .+ \u03f5)\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# Few comments about the gradient\n\ng_all = [grad(m, X_train[:,k], y_train[:,k]) for k in 1:size(X_train,2)]\n\ntypeof(g_all)\n\nmean_tuple(d::AbstractArray{<:Tuple}) = Tuple([mean([d[k][i] for k in 1:length(d)]) for i in 1:length(d[1])])\n\ng_mean = mean_tuple(g_all)\n\ntypeof(g_mean)\n\n# Exercise\n\n\n\n# Exercise\n\n\n\n", "meta": {"hexsha": "37212a9d07f8ade7fe581b934b374fb91a346f93", "size": 2131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/lecture_09/script.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_09/script.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_09/script.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": 15.9029850746, "max_line_length": 109, "alphanum_fraction": 0.6156733928, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.774099570041364}}
{"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    \u222b_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    \u03b2/2 \u222b_0^1 (1 - cosh(\u03a9\u03b2(1-x)/2)) cosh(x\u03b2/2) / (a^2 - \u03b2^2 x^2/4 - bcosh(v\u03b2x/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    \u222b_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 \u03b2s.\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(\u03a9, \u03b2, \u03b1, v, w)\n\n    err = eps(\u03a9)\n\n    # Initialise constants.\n    R = (v^2 - w^2) / (w^2 * v)\n    a = sqrt(\u03b2^2 / 4 + R * \u03b2 * coth(\u03b2 * v / 2))\n    b = R * \u03b2 / sinh(\u03b2 * v / 2)\n\n    coefficient = 2 * \u03b1 * \u03b2^(3 // 2) * v^3 / (3 * sqrt(\u03c0) * sinh(\u03b2 / 2) * w^3)\n\n    integrand(x) = (1 - cosh(\u03a9 * \u03b2 * (1 - x) / 2)) * cosh(x * \u03b2 / 2) / (a^2 - \u03b2^2 * x^2 / 4 - b * cosh(v * \u03b2 * x / 2))^(3 // 2)\n\n    integral = quadgk(x -> integrand(x), BigFloat(\"0.0\"), BigFloat(\"1.0\"), atol = err)\n\n    return coefficient * \u03b2 * integral[1] / 2\nend\n\n\"\"\"\nCheck output and timing of the above function.\n\"\"\"\n\nsetprecision(BigFloat, 128)\n\u03a9_range = [BigFloat(\"12.01\")]\n\u03b2 = BigFloat(\"4.0\")\n\u03b1 = BigFloat(\"7.0\")\nv = BigFloat(\"5.8\")\nw = BigFloat(\"1.6\")\n# For \u03a9_range = [BigFloat(\"12.01\")], \u03b2 = BigFloat(\"4.0\"), \u03b1 = 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.(\u03a9_range, \u03b2, \u03b1, 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": "# Seed random generator to avoid random effects in testing\nsrand(1)\n\nX = [1 1; 2 2;  1 -1]\n\n# binomial\ny = [-1; -1; 1]\n@test_approx_eq_eps optimize(BinomialLogReg(X, y), optimizer=:l_bfgs).theta [-0.07276615319846116,-0.1680076736259885] 5e-5\n@test_approx_eq_eps optimize(BinomialLogReg(X, y, \u03bb=1.0), optimizer=:l_bfgs).theta [-0.16588135026949055,-0.840712964600344] 5e-5\n@test_approx_eq_eps optimize(BinomialLogReg(X, y, \u03bb= 10.0), optimizer=:l_bfgs).theta [-0.0745584919313508,-2.20259301054857] 5e-5\n\n# TODO: should be moved to test/sgd.jl\n@test_approx_eq_eps optimize(BinomialLogReg(X, y), optimizer=:sgd).theta [-0.07276615319846116,-0.1680076736259885] 5e-2\n@test_approx_eq_eps optimize(BinomialLogReg(X, y, \u03bb=1.0), optimizer=:sgd).theta [-0.16588135026949055,-0.840712964600344] 5e-2\n@test_approx_eq_eps optimize(BinomialLogReg(X, y, \u03bb=10.0), optimizer=:sgd).theta [-0.0745584919313508,-2.20259301054857] 5e-2\nmodel = optimize(BinomialLogReg(X, y, \u03bb=10.0), optimizer=:sgd)\n@test predict(model, X) == y\nshow(IOBuffer(), BinomialLogReg(X, y))\n\n@test_throws DimensionMismatch BinomialLogReg(X', y)\n@test_throws ArgumentError BinomialLogReg(X, [3; 3; 2])\n@test_throws ArgumentError optimize(BinomialLogReg(X, y, \u03bb=0.0))\n\n# multinomial\ny = [1; 1; 2]\nmethod = MultinomialLogReg(X, y, \u03bb=10.0)\nmodel = optimize(method, optimizer=:l_bfgs)\n@test predict(model, X) == y\n", "meta": {"hexsha": "f5e46be5d8fee39eb3a1de61cca85b0be6253256", "size": 1366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/logistic_regression.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/RegERMs.jl-d41b3cee-bfd5-59f4-ae46-2d539e075afd", "max_stars_repo_head_hexsha": "1b5a065cc16d978360df7884af21a53d66f105fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-01-13T03:04:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T01:38:19.000Z", "max_issues_repo_path": "test/logistic_regression.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/RegERMs.jl-d41b3cee-bfd5-59f4-ae46-2d539e075afd", "max_issues_repo_head_hexsha": "1b5a065cc16d978360df7884af21a53d66f105fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-01-05T09:56:32.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-23T15:29:01.000Z", "max_forks_repo_path": "test/logistic_regression.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/RegERMs.jl-d41b3cee-bfd5-59f4-ae46-2d539e075afd", "max_forks_repo_head_hexsha": "1b5a065cc16d978360df7884af21a53d66f105fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-06-17T17:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T01:38:35.000Z", "avg_line_length": 47.1034482759, "max_line_length": 129, "alphanum_fraction": 0.7481698389, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.7740995683336421}}
{"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 \ud835\udf4e:\nphik(x, k) = [xi^k for xi in x]  # \u03d5\u2096(\ud835\udc99) = ..., for vector \ud835\udc99, all inputs\nphi1tok(x, k) = [phik(x, i) for i in 0:k-1]  # \u03a6(\ud835\udc99) = \ud835\udc99 \u22c5 \ud835\udf4b = \ud835\udc99 \u22c5 (\u03d5\u2081(), \u03d5\u2082(), ..., \u03d5\u2096())\ntransformed_x_kk(x, k) = hcat(phi1tok(x, k)...)  # \u03a6(\ud835\udc99) as a matrix\nw_k(x, y, k) = transformed_x_kk(x, k) \\ y  # \ud835\udf4e = \u03a6\\\ud835\udc9a\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))  # \u0302\ud835\udc66 = \u03a6(\ud835\udc65) \u22c5 \ud835\udf4e\n\nplot(S, line=:scatter, lab=\"data set\", legend=:bottomright)\nW = zeros(4, 4)\nfor i = 1:4\n    \ud835\udc98\u03a6(x_test) = w_phi_k(x_test, x, y, i)\n    display(plot!(\ud835\udc98\u03a6, 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 = \ud835\udeba\u1d62(\ud835\udc66\u1d62 - \u0302\ud835\udc66\u1d62)\u00b2 = \ud835\udeba\u1d62(\ud835\udc66\u1d62 - \u03a6(\ud835\udc65\u1d62) \u22c5 \ud835\udf4e)\u00b2\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": "function parse_encoded_string(input_string, lower_bound=0, upper_bound=127, upper_string=\"F\", lower_string=\"B\")\n\n    for direction in input_string\n        letter = string(direction)\n        if letter == upper_string\n            upper_bound = upper_bound - Int32(div(upper_bound - lower_bound, 2, RoundUp))\n        elseif letter == lower_string\n            lower_bound = lower_bound + Int32(div(upper_bound - lower_bound, 2, RoundUp))\n        else\n            throw(\"Invalid string type $letter\")\n        end\n        # println(\"letter: $letter\")\n        # println((lower_bound, upper_bound))\n    end\n    @assert lower_bound == upper_bound\n    lower_bound\nend\n\nfunction parse_rows(input_string)\n    return parse_encoded_string(input_string, 0, 127, \"F\", \"B\")\nend\n\nfunction parse_columns(input_string)\n    return parse_encoded_string(input_string, 0, 7, \"L\", \"R\")\nend\n\nfunction get_seat_id(input_string)\n    row_string = input_string[1:7]\n    col_string = input_string[8:end]\n\n    row_num = parse_rows(row_string)\n    col_num = parse_columns(col_string)\n\n    seat_id = row_num * 8 + col_num\n    seat_id\nend\n\n# turns out we didn't need this\nfunction id_to_row_column(seat_id)\n    column = seat_id % 8\n    row = (seat_id - column) / 8\n    row, column\nend\n\n\nfunction main()\n    input_file = \"day5_input.txt\"\n\n    highest_boarding_pass = open(input_file) do file\n        file_string = read(file, String)\n        all_seats = split(file_string, \"\\n\")\n        all_seats_ids = Vector{Int32}()\n\n        for seat_entry in all_seats\n            seat_id = get_seat_id(strip(seat_entry))\n            push!(all_seats_ids, seat_id)\n        end\n        \n        set_of_all_seats = Set(all_seats_ids) # easier to test if things are in a set\n        for i in minimum(all_seats_ids):maximum(all_seats_ids)\n            if !in(i, set_of_all_seats) && in(i-1, set_of_all_seats) && in(i+1, set_of_all_seats)\n                println(\"My seat ID is $i\")\n            end\n        end\n\n        # Debugging\n        # sort!(all_seats_ids)\n        # println(\"all_seats_ids: $all_seats_ids\")\n        maximum(all_seats_ids)\n    end\n    println(\"Highest Seat ID: $highest_boarding_pass\")\nend\n\n#if abspath(PROGRAM_FILE) == @__FILE__\n    main()\n#end", "meta": {"hexsha": "95331310396c91d48c49d5268c42972755a768ad", "size": 2210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Day5/day5_solution.jl", "max_stars_repo_name": "FedericoV/JuliaAdventOfCode2020", "max_stars_repo_head_hexsha": "30426fdee9f32fa15f4dd219462efff3de2d0fc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day5/day5_solution.jl", "max_issues_repo_name": "FedericoV/JuliaAdventOfCode2020", "max_issues_repo_head_hexsha": "30426fdee9f32fa15f4dd219462efff3de2d0fc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day5/day5_solution.jl", "max_forks_repo_name": "FedericoV/JuliaAdventOfCode2020", "max_forks_repo_head_hexsha": "30426fdee9f32fa15f4dd219462efff3de2d0fc9", "max_forks_repo_licenses": ["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.0789473684, "max_line_length": 111, "alphanum_fraction": 0.6524886878, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7740995601954932}}
{"text": "n = 10 # rand(1:10)\n@test matrixdepot(\"binomial\", n) == matrixdepot(\"binomial\", Float64, n)\n\nA = matrixdepot(\"binomial\", n)\n\n@test A*A \u2248 2^(n-1)*Matrix(1.0I, n, n)\nprintln(\"'binomial' passed test...\")\n", "meta": {"hexsha": "213785c8ab462961d98c62f78610d86c5ee43fb5", "size": 201, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_binomial.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_binomial.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_binomial.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-02-19T22:47:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:02:00.000Z", "avg_line_length": 25.125, "max_line_length": 71, "alphanum_fraction": 0.631840796, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7740995538709475}}
{"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\u00e9zout coefficient x\"\n    x::T\n\n    \"B\u00e9zout 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 \u00f7 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    # \u221a2 \u00d7 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 \u00f7 2)\n            q = random_prime(key_size \u00f7 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) \u2265 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 \u00d7 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0967dc46-0f4d-11eb-13b2-2b2042595b6e\nmd\"#### 2) Numerical implementation\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e700c752-0e2d-11eb-2c61-3959bdba269a\nbegin\n\tnx = 10\n\tLx = 1.\n\t\u0394x = Lx/nx\n\t\u0394t = 0.001\n\tU = 1.\n\t\n\tx = \u0394x/2.:\u0394x:Lx\nend;\n\n# \u2554\u2550\u2561 5b1b6802-0e2e-11eb-1fa6-1ddd5478cc54\nbegin\n\t# Initial conditions\n\tT = sin.(2\u03c0*x);\n\tt = [0.]\nend;\n\n# \u2554\u2550\u2561 4463cf8c-0ef8-11eb-2c6e-45d982d5687a\nfunction advect(T)\n\treturn U*(circshift(T, (1)) .- circshift(T, (-1)))/(2\u0394x)\nend\n\n# \u2554\u2550\u2561 67cb0ed2-0efa-11eb-2645-495dba94ea64\nfunction timestep!(t, T)\n\tT .+= \u0394t*(advect(T))\n\tt .+= \u0394t\nend\n\n# \u2554\u2550\u2561 ba1ea938-0f44-11eb-0fac-cd1afe507d57\ntimestepButton = @bind go Button(\"Timestep\")\n\n# \u2554\u2550\u2561 18a3f9dc-0e6d-11eb-0b31-0b5296c2e83b\nbegin\n\t\u23e9 = nothing\n\tgo\n\tnT = 50\n\tfor i = 1:nT\n\t\ttimestep!(t, T)\n\tend\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 37bed6e8-12da-11eb-1c36-c7f92fe732e4\n\u03ba = 0.05\n\n# \u2554\u2550\u2561 3e1d44b6-12da-11eb-16ac-2524d0e0d900\nfunction diffuse(T)\n\treturn \u03ba*(circshift(T, (1)) .- 2*T .+ circshift(T, (-1)))/(\u0394x^2)\nend\n\n# \u2554\u2550\u2561 43d1272a-2113-11eb-1d03-c948d11a8423\n# function timestep!(t, T)\n# \tT .+= \u0394t*(diffuse(T))\n# \tt .+= \u0394t\n# end\n\n# \u2554\u2550\u2561 74a36fd4-2113-11eb-2d3e-3be5e4318dea\ntimestepButton\n\n# \u2554\u2550\u2561 d2c101c8-0f4e-11eb-0c4f-0972be924ce1\nmd\"#### 3) Advection-Diffusion\"\n\n# \u2554\u2550\u2561 7c490fd2-2113-11eb-3239-f72cc77c0b53\n# function timestep!(t, T)\n# \tT .+= \u0394t*(advect(T) .+ diffuse(T))\n# \tt .+= \u0394t\n# end\n\n# \u2554\u2550\u2561 894b97f4-2113-11eb-3b86-2986a6cd4fd1\ntimestepButton\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70ae3138-0f44-11eb-1a8d-d3b5a39c1b42\nmd\"\"\"#### Pluto Book-keeping\"\"\"\n\n# \u2554\u2550\u2561 845e102a-0f44-11eb-3935-2d9a0efecedc\nas_svg(x) = PlutoUI.Show(MIME\"image/svg+xml\"(), repr(MIME\"image/svg+xml\"(), x))\n\n# \u2554\u2550\u2561 00cc530a-0e35-11eb-133b-ef8e30ea7b12\nbegin\n\t\u23e9\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# \u2554\u2550\u2561 4c5b62fa-2113-11eb-14ff-2bd776efe96c\nas_svg(p)\n\n# \u2554\u2550\u2561 869c4be8-2113-11eb-0703-f905fe93142f\nas_svg(p)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500beed7b48-0e2b-11eb-2805-edf0be651fc3\n# \u255f\u2500e74322be-12d6-11eb-3f27-f17821669699\n# \u255f\u2500c9a1719a-12d6-11eb-1c8c-13e1f75bc852\n# \u255f\u2500c3f99436-0f49-11eb-33b6-e78c150d4ff5\n# \u255f\u25000967dc46-0f4d-11eb-13b2-2b2042595b6e\n# \u255f\u250019273c8a-0f4d-11eb-3caf-678f073c6b1a\n# \u2560\u2550e700c752-0e2d-11eb-2c61-3959bdba269a\n# \u2560\u25505b1b6802-0e2e-11eb-1fa6-1ddd5478cc54\n# \u2560\u25504463cf8c-0ef8-11eb-2c6e-45d982d5687a\n# \u2560\u255067cb0ed2-0efa-11eb-2645-495dba94ea64\n# \u2560\u2550ba1ea938-0f44-11eb-0fac-cd1afe507d57\n# \u2560\u255000cc530a-0e35-11eb-133b-ef8e30ea7b12\n# \u2560\u255018a3f9dc-0e6d-11eb-0b31-0b5296c2e83b\n# \u2560\u2550f2c7638a-0e34-11eb-2210-9f9b0c3519fe\n# \u255f\u2500b19bfb58-0f4e-11eb-218f-8d930b7afff6\n# \u2560\u255037bed6e8-12da-11eb-1c36-c7f92fe732e4\n# \u2560\u25503e1d44b6-12da-11eb-16ac-2524d0e0d900\n# \u2560\u255043d1272a-2113-11eb-1d03-c948d11a8423\n# \u2560\u255074a36fd4-2113-11eb-2d3e-3be5e4318dea\n# \u2560\u25504c5b62fa-2113-11eb-14ff-2bd776efe96c\n# \u255f\u2500d2c101c8-0f4e-11eb-0c4f-0972be924ce1\n# \u2560\u25507c490fd2-2113-11eb-3239-f72cc77c0b53\n# \u2560\u2550894b97f4-2113-11eb-3b86-2986a6cd4fd1\n# \u2560\u2550869c4be8-2113-11eb-0703-f905fe93142f\n# \u255f\u2500b00f7bec-12da-11eb-3e20-7769cc2bd0ec\n# \u255f\u250070ae3138-0f44-11eb-1a8d-d3b5a39c1b42\n# \u2560\u2550232c24de-0e30-11eb-1544-53cb0b45ec9b\n# \u2560\u2550845e102a-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 \u00f7 2; n2 = n \u00f7 2; p2 = p \u00f7 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), \" \u2260 $m \u00d7 $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 HypothesisTests, Test\nusing HypothesisTests: default_tail\n\n@testset \"T-test\" begin\n\n@testset \"One sample\" begin\n\t@test pvalue(OneSampleTTest(-5:5)) == 1\n\n\ttst = OneSampleTTest(-5:10)\n\t@test abs(pvalue(tst) - 0.0530) <= 1e-4\n\t@test abs(pvalue(tst; tail=:left) - 0.9735) <= 1e-4\n\t@test abs(pvalue(tst; tail=:right) - 0.0265) <= 1e-4\n\t@test default_tail(tst) == :both\n\tshow(IOBuffer(), tst)\n\n\ttst = OneSampleTTest(mean(-5:10), std(-5:10), 16)\n\t@test abs(pvalue(tst) - 0.0530) <= 1e-4\n\n\t@test all(abs.([confint(tst)...;] - [-0.0369, 5.0369]) .<= 1e-4)\n\t@test all(abs.([confint(tst, level=0.9)...;] - [0.4135, 4.5865]) .<= 1e-4)\n\tc = confint(tst; tail=:left)\n\t@test c[1] == -Inf\n\t@test abs(c[2] - 4.5865) .<= 1e-4\n\tc = confint(tst; tail=:right)\n\t@test abs(c[1] - 0.4135) .<= 1e-4\n\t@test c[2] == Inf\n\tshow(IOBuffer(), tst)\n\n\ttst = OneSampleTTest(-10:5)\n\t@test abs(pvalue(tst) - 0.0530) <= 1e-4\n\t@test abs(pvalue(tst; tail=:left) - 0.0265) <= 1e-4\n\t@test abs(pvalue(tst; tail=:right) - 0.9735) <= 1e-4\n\t@test all(abs.([confint(tst)...] - [-5.0369, 0.0369]) .<= 1e-4)\n\t@test abs.(confint(tst; tail=:left)[2] - (-0.4135)) .<= 1e-4\n\t@test abs.(confint(tst; tail=:right)[1] - (-4.5865)) .<= 1e-4\n\tshow(IOBuffer(), tst)\nend\n\n@testset \"Paired\" begin\n\t@test abs(pvalue(OneSampleTTest([1, 1, 2, 1, 0], [0, 1, 1, 1, 0])) - 0.1778) <= 1e-4\nend\n\n@testset \"Two sample\" begin\n\t# From http://en.wikipedia.org/w/index.php?title=Student%27s_t-test&oldid=526762741\n\n\ta1 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99]\n\ta2 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98]\n\n\ttst = EqualVarianceTTest(a1, a2)\n\t@test tst.df == 10\n\t@test abs(tst.t - 1.959) <= 1e-3\n\t@test abs(pvalue(tst) - 0.078) <= 1e-3\n\t@test all(abs.([confint(tst)...] - [-0.0131, 0.2031]) .<= 1e-4)\n\t@test default_tail(tst) == :both\n\tshow(IOBuffer(), tst)\n\n\ttst = UnequalVarianceTTest(a1, a2)\n\t@test abs(tst.df - 7.03) <= 0.01\n\t@test abs(tst.t - 1.959) <= 1e-3\n\t@test abs(pvalue(tst) - 0.091) <= 1e-3\n\t@test all(abs.([confint(tst)...] - [-0.0196, 0.2096]) .<= 1e-4)\n\t@test default_tail(tst) == :both\n\tshow(IOBuffer(), tst)\nend\nend\n", "meta": {"hexsha": "1f0ccb4bde7bc34f4ad7d27717cfe4be212466d0", "size": 2072, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/t.jl", "max_stars_repo_name": "harryscholes/HypothesisTests.jl", "max_stars_repo_head_hexsha": "d1ec83dadf340f042b6e4ee3eac9bf8a25b4473e", "max_stars_repo_licenses": ["MIT"], "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/t.jl", "max_issues_repo_name": "harryscholes/HypothesisTests.jl", "max_issues_repo_head_hexsha": "d1ec83dadf340f042b6e4ee3eac9bf8a25b4473e", "max_issues_repo_licenses": ["MIT"], "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/t.jl", "max_forks_repo_name": "harryscholes/HypothesisTests.jl", "max_forks_repo_head_hexsha": "d1ec83dadf340f042b6e4ee3eac9bf8a25b4473e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-12T00:57:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T00:57:32.000Z", "avg_line_length": 31.3939393939, "max_line_length": 85, "alphanum_fraction": 0.6023166023, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7740796316233548}}
{"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, \u03ba=1.0)\n#\n#  Solves a linear elliptic PDE on the unit square\n#     - \u2207\u22c5(\u03ba\u2207u) = 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/\u03c0^2\n    return C*sin.(\u03c0*x[:,1])*sin.(2*\u03c0*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.(\u03c0*x[:,1]).*sin.(2*\u03c0*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  \u03ba_g   = \u03ba*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,\u03d5,\u03d5_x,\u03d5_y = twodShape( xLocal, r, s, w )\n    fg   = f(xg)         # forcing function evaluated at quadrature points\n\n    ALoc = twodBilinear( \u03ba_g, \u03d5_x, \u03d5_x, wg ) + twodBilinear( \u03ba_g, \u03d5_y, \u03d5_y, wg )\n    bLoc = twodLinForm(   fg,      \u03d5  , 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": "@testset \"GeometricBM\" begin\n\nusing DiffEqNoiseProcess, DiffEqBase, DiffEqMonteCarlo, Test, Statistics\n\n\u03bc = 1.0\n\u03c3 = 2.0\n\nW = GeometricBrownianMotionProcess(\u03bc,\u03c3,0.0,1.0,1.0)\ndt = 0.1\ncalculate_step!(W,dt)\nfor i in 1:10\n  accept_step!(W,dt)\nend\n\nW = GeometricBrownianMotionProcess(\u03bc,\u03c3,0.0,1.0,1.0)\nprob = NoiseProblem(W,(0.0,1.0))\nsol = solve(prob;dt=0.1)\n\nW = GeometricBrownianMotionProcess(\u03bc,\u03c3,0//1,1.0,1.0)\nprob_rational = NoiseProblem(W,(0,1))\ndt = 1//10\nsol = solve(prob_rational;dt=dt)\n\ndt = dt/100\nfor t in dt:dt:1-dt\n  sol(t)\nend\n\nt = 1.0\nu0 = 1.0\nexpected_mean = u0*exp(\u03bc*t)\nexpected_variance = u0^2*exp(2\u03bc*t)*(exp(\u03c3^2*t)-1)\nmonte_prob = MonteCarloProblem(prob;output_func = (sol,i)-> (sol[end],false))\nsol = solve(monte_prob;dt=0.1,num_monte=40000)\n@test abs(mean(sol) - expected_mean) < 0.4\n#abs(var(sol) - expected_variance) < 0.4 # Converges slowly\n\nW = GeometricBrownianMotionProcess!(\u03bc,\u03c3,0.0,ones(2),ones(2))\nprob = NoiseProblem(W,(0.0,1.0))\nsol = solve(prob;dt=0.1)\n\nend\n", "meta": {"hexsha": "ead8b834faca6e9a294c1a3dd6172fb092474bb0", "size": 985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/geometric_bm.jl", "max_stars_repo_name": "david-pl/DiffEqNoiseProcess.jl", "max_stars_repo_head_hexsha": "40915c62a4502bf51302c2e879648964b84b3b9d", "max_stars_repo_licenses": ["MIT"], "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/geometric_bm.jl", "max_issues_repo_name": "david-pl/DiffEqNoiseProcess.jl", "max_issues_repo_head_hexsha": "40915c62a4502bf51302c2e879648964b84b3b9d", "max_issues_repo_licenses": ["MIT"], "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/geometric_bm.jl", "max_forks_repo_name": "david-pl/DiffEqNoiseProcess.jl", "max_forks_repo_head_hexsha": "40915c62a4502bf51302c2e879648964b84b3b9d", "max_forks_repo_licenses": ["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.9069767442, "max_line_length": 77, "alphanum_fraction": 0.6984771574, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7740378608608626}}
{"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,\u03b8,\u03bb)\n        return log(1+exp(-y_i*dot(\u03b8,x_i)))\n    end\nend\n\nfunction f_logreg(X,y,\u03b8,\u03bb)\n    return function(\u03b8)\n        data = X\n        labels = y\n        \u03bb = \u03bb\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(\u03b8,x_i) ) )\n        end\n        funcVal += \u03bb/2*(norm(\u03b8,2)^2)\n        return funcVal\n    end\nend\n\nfunction g_logreg(X,y,\u03b8,\u03bb)\n    return function(\u03b8)\n        data = X\n        labels = y\n        \u03bb = \u03bb\n        # n-dim-column-vector\n        array = zeros(size(data,2))\n        # add l2 norm\n        array += \u03bb * \u03b8\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(\u03b8,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,\u03b8,\u03bb)\n              exponential = exp(-y_i*dot(\u03b8,x_i))\n              return (-y_i * x_i * exponential) / ( 1 + exponential ) + \u03bb * \u03b8\n        end\nend\n\n#=\nhinge-loss - Loss-function and gradient\n=#\nfunction f_svm(X,y,\u03b8,\u03bb)\n    return function(\u03b8)\n        X = X\n        y = y\n        \u03bb = \u03bb\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(\u03b8,x_i)))\n        end\n        fval = fval / size(X,1)\n        fval += \u03bb/2 * norm(\u03b8,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,\u03b8,\u03bb)\n      val = 1 - (y_i * dot(\u03b8,x_i))\n      if val < 0\n          return \u03bb * \u03b8;\n      else\n          return -y_i * x_i + \u03bb * \u03b8;\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 \u2229 exp(x)\n    x = x \u2229 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 \u2229 (0..\u221e)\n    x_new = x \u2229 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 \u2229 (0..\u221e)\n    x_new = x \u2229 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 \u2229 (0..\u221e)\n    x_new = x \u2229 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 \u2229 (-1.0..\u221e)\n    x_new = x \u2229 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 \u2229 exp(y)\n    y = y \u2229 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 \u2229 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 \u2229 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 \u2229 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 \u2229 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 \u2286 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 \u2208 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) \u00d7 (0.01 .. 0.01) \u00d7 (0.01 .. 0.01)\nprob = @ivp(x'= prod_dest_I!(x), dim:3, x(0) \u2208 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) \u00d7 (0.01 .. 0.01) \u00d7 (0.01 .. 0.01) \u00d7 (0.296 .. 0.304)\nprob = @ivp(x'= prod_dest_IP!(x), dim:4, x(0) \u2208 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) \u00d7 (0.01 .. 0.01) \u00d7 (0.01 .. 0.01) \u00d7 (0.296 .. 0.304)\nprob = @ivp(x'= prod_dest_IP!(x), dim:4, x(0) \u2208 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": "######### CmdStan program example  ###########\n\nusing CmdStan\n\nProjDir = @__DIR__\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 = Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1])\n\n  # Preserve these variables outside cd/do block.\n  global stanmodel, rc, samples, cnames, df\n    \n  stanmodel = Stanmodel(name=\"bernoulli\", model=bernoullimodel,\n    printsummary=false);\n\n  rc, samples, cnames = stan(stanmodel, observeddata, ProjDir, CmdStanDir=CMDSTAN_HOME);\n  \n  if rc == 0\n    # Fetch cmdstan summary as a DataFrame\n    df = read_summary(stanmodel)\n\n    df |> display\n    println()\n\n    df[df.parameters .== :theta, [:mean, :ess, :r_hat]] |> display\n  end\n\nend # cd block\n", "meta": {"hexsha": "05ccb72622ab8a21f31d6627f95fff57b1c1997f", "size": 874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Bernoulli/bernoulli.jl", "max_stars_repo_name": "mkshirazi/CmdStan.jl", "max_stars_repo_head_hexsha": "61c90f0dc160b23e691b0563a8f77c51d4f5677d", "max_stars_repo_licenses": ["MIT"], "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.jl", "max_issues_repo_name": "mkshirazi/CmdStan.jl", "max_issues_repo_head_hexsha": "61c90f0dc160b23e691b0563a8f77c51d4f5677d", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "mkshirazi/CmdStan.jl", "max_forks_repo_head_hexsha": "61c90f0dc160b23e691b0563a8f77c51d4f5677d", "max_forks_repo_licenses": ["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": 88, "alphanum_fraction": 0.6029748284, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7740378524540719}}
{"text": "using MultivariateStats\nusing Base.Test\nimport StatsBase\n\nsrand(34568)\n\n## PCA with zero mean\n\nX = randn(5, 10)\nY = randn(3, 10)\n\nW = qr(randn(5, 5))[1][:, 1:3]\n\u03c3\u00b2 = 0.1\nM = PPCA(Float64[], W, \u03c3\u00b2)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test mean(M) == zeros(5)\n@test loadings(M) == W\n@test var(M) == \u03c3\u00b2\n\nT = inv(W'*W .+ \u03c3\u00b2*eye(3))*W'\n@test transform(M, X[:,1]) \u2248 T * X[:,1]\n@test transform(M, X) \u2248 T * X\n\nR = W*inv(W'W)*(W'W .+ \u03c3\u00b2*eye(3))\n@test reconstruct(M, Y[:,1]) \u2248 R * Y[:,1]\n@test reconstruct(M, Y) \u2248 R * Y\n\n\n## PCA with non-zero mean\n\nmv = rand(5)\nM = PPCA(mv, W, \u03c3\u00b2)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test mean(M) == mv\n@test loadings(M) == W\n@test var(M) == \u03c3\u00b2\n\n@test transform(M, X[:,1]) \u2248 T * (X[:,1] .- mv)\n@test transform(M, X) \u2248 T * (X .- mv)\n\n@test reconstruct(M, Y[:,1]) \u2248 R * Y[:,1] .+ mv\n@test reconstruct(M, Y) \u2248 R * Y .+ mv\n\n\n## prepare training data\n\nd = 5\nn = 1000\n\nR = qr(randn(d, d))[1]\n@test R'R \u2248 eye(5)\nscale!(R, sqrt.([0.5, 0.3, 0.1, 0.05, 0.05]))\n\nX = R'randn(5, n) .+ randn(5)\nmv = vec(mean(X, 2))\nZ = X .- mv\n\nM0 = fit(PCA, X; mean=mv, maxoutdim = 4)\n\n## ppcaml (default)\n\nM = fit(PPCA, X)\nP = projection(M)\nW = loadings(M)\n\n@test indim(M) == 5\n@test outdim(M) == 4\n@test mean(M) == mv\n@test P'P \u2248 eye(4)\n@test reconstruct(M, transform(M, X)) \u2248 reconstruct(M0, transform(M0, X))\n\nM = fit(PPCA, X; mean=mv)\n@test loadings(M) \u2248 W\n\nM = fit(PPCA, Z; mean=0)\n@test loadings(M) \u2248 W\n\nM = fit(PPCA, X; maxoutdim=3)\nP = projection(M)\nW = loadings(M)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test P'P \u2248 eye(3)\n\n# ppcaem\n\nM = fit(PPCA, X; method=:em)\nP = projection(M)\nW = loadings(M)\n\n@test indim(M) == 5\n@test outdim(M) == 4\n@test mean(M) == mv\n@test P'P \u2248 eye(4)\n@test all(isapprox.(reconstruct(M, transform(M, X)), reconstruct(M0, transform(M0, X)), atol=1e-3))\n\nM = fit(PPCA, X; method=:em, mean=mv)\n@test loadings(M) \u2248 W\n\nM = fit(PPCA, Z; method=:em, mean=0)\n@test loadings(M) \u2248 W\n\nM = fit(PPCA, X; method=:em, maxoutdim=3)\nP = projection(M)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test P'P \u2248 eye(3)\n\n@test_throws StatsBase.ConvergenceException fit(PPCA, X; method=:em, tot=1)\n\n# bayespca\nM0 = fit(PCA, X; mean=mv, maxoutdim = 3)\n\nM = fit(PPCA, X; method=:bayes)\nP = projection(M)\nW = loadings(M)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test mean(M) == mv\n@test P'P \u2248 eye(3)\n@test reconstruct(M, transform(M, X)) \u2248 reconstruct(M0, transform(M0, X))\n\nM = fit(PPCA, X; method=:bayes, mean=mv)\n@test loadings(M) \u2248 W\n\nM = fit(PPCA, Z; method=:bayes, mean=0)\n@test loadings(M) \u2248 W\n\nM = fit(PPCA, X; method=:em, maxoutdim=2)\nP = projection(M)\n\n@test indim(M) == 5\n@test outdim(M) == 2\n@test P'P \u2248 eye(2)\n\n@test_throws StatsBase.ConvergenceException fit(PPCA, X; method=:bayes, tot=1)\n\n# test that fit works with Float32 values\nX2 = convert(Array{Float32,2}, X)\n# Float32 input, default pratio\nM = fit(PPCA, X2; maxoutdim=3)\n", "meta": {"hexsha": "4eec2064b769cf7bbb57f97b4e6e258dce1a574c", "size": 2865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ppca.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": "test/ppca.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": "test/ppca.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": 19.2281879195, "max_line_length": 99, "alphanum_fraction": 0.5979057592, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7740378524540719}}
{"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# \u2211 [\u03bb^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\u2093(a) = v\u2097\n    problem.A[1,1] = -2\n    problem.A[1,2] = 2\n\n    # Construct rows corresponding to interior mesh points\n    for i \u2208 2:problem.n\u2093 + 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\u2093(b) = v\u1d63\n    problem.A[end, end] = -2\n    problem.A[end, end - 1] = 2\n\n    @. problem.A *= 1/(problem.\u0394x)^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\u2080\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 \u2208 2:problem.n\u2093\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\u2099\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.\u0394x)^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": "using Giac\nusing Test\n\nusing SpecialFunctions\n\n#For elementary functions we check whether the Giac/Function of a \n#numerical value computes (approximately) the same result as the\n#corresponding Julia function\n\nfor (ex, res) in [\n    (sqrt(giac(0.9)), sqrt(0.9)),\n    (exp(giac(0.9)), exp(0.9)),\n    (log(giac(0.9)), log(0.9)),\n    (log(3,giac(0.9)), log(3,0.9)),\n    (log10(giac(0.9)), log10(0.9)), # log10 not available in Giac\n    (sin(giac(0.9)), sin(0.9)),\n    (cos(giac(0.9)), cos(0.9)),\n    (tan(giac(0.9)), tan(0.9)),\n    (cot(giac(0.9)), cot(0.9)),\n    (sec(giac(0.9)), sec(0.9)),\n    (csc(giac(0.9)), csc(0.9)),\n    (sinh(giac(0.9)), sinh(0.9)),\n    (cosh(giac(0.9)), cosh(0.9)),\n    (tanh(giac(0.9)), tanh(0.9)),\n    (asin(giac(0.9)), asin(0.9)),\n    (acos(giac(0.9)), acos(0.9)),\n    (atan(giac(0.9)), atan(0.9)),\n    (acot(giac(0.9)), acot(0.9)),\n    (asec(giac(1.9)), asec(1.9)), # |arg|>=1\n    (acsc(giac(1.9)), acsc(1.9)), # |arg|>=1\n    (asinh(giac(0.9)), asinh(0.9)),\n    (acosh(giac(1.9)), acosh(1.9)), #arg>=1\n    (atanh(giac(0.9)), atanh(0.9)),\n    (expm1(giac(0.9)), expm1(0.9)),\n    (log1p(giac(0.9)), log1p(0.9)),\n\n    (erf(giac(0.9)), erf(0.9)),\n    (erfc(giac(0.9)), erfc(0.9)),\n    (gamma(giac(0.9)), gamma(0.9)),\n    (beta(giac(0.9),giac(1.9)), beta(0.9,1.9)),\n    (zeta(giac(0.9)), zeta(0.9)),\n    (factorial(giac(13)), factorial(13)),\n    (binomial(giac(13),giac(7)), binomial(13,7)),\n    (airyai(giac(0.9)), airyai(0.9)), # Giac/Airy_Ai does not work as expected\n    (airybi(giac(0.9)), airybi(0.9)), # Giac/Airy_Bi does not work as expected\n    (besselj(2,giac(0.9)), besselj(2,0.9)),\n    (bessely(2,giac(0.9)), bessely(2,0.9)),\n    (digamma(giac(0.9)), digamma(0.9)),\n    (polygamma(2,giac(0.9)), polygamma(2,0.9)),\n    (sinint(giac(0.9)), sinint(0.9)),\n    (cosint(giac(0.9)), cosint(0.9)),\n    (Ei(giac(0.9)), 1.6228117136968674413),\n]\n    @test convert(Float64,ex) \u2248 res\nend    \n\n@test convert(Float64, sign(giac(-12.3))) == -1.0\n@test convert(Float64, sign(giac(0.0))) == 0.0 \n@test convert(Float64, sign(giac(1.3))) == 1.0\n@test convert(Float64, round(giac(-1.7))) == -2.0\n@test convert(Float64, round(giac(1.4999))) == 1.0\n@test convert(Float64, ceil(giac(1.1))) == 2.0\n@test convert(Float64, ceil(giac(-1.1))) == -1.0\n@test convert(Float64, floor(giac(1.1))) == 1.0\n@test convert(Float64, floor(giac(-1.1))) == -2.0\n@test convert(Float64, trunc(giac(1.1))) == 1.0\n@test convert(Float64, trunc(giac(-1.1))) == -1.0\n\n\n\n#Note: We don't check whether the underlying Giac C++ library computes\n#correct results. We only test if the Julia functions in Giac.jl/src/library.jl\n#are correctly implemented. We assume that this is the case, if the Julia\n#function computes the same (or at least an equivalent) result as the\n#corresponding Giac function called via the Giac parser.\n\n@giac x y z n\n\nex1 = simplify(4*atan(giac(1//5))-atan(giac(1//239)))\nex2 = giac(\"simplify(4*atan(1/5)-atan(1/239))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = collect(x+2*x+1-4)\nex2 = giac(\"collect(x+2*x+1-4)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = expand((x+y)*(z+1))\nex2 = giac(\"expand((x+y)*(z+1))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = factor(x^4-4)\nex2 = giac(\"factor(x^4-4)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = partfrac((x^2-2*x+3)/(x^2-3*x+2))\nex2 = giac(\"partfrac((x^2-2*x+3)/(x^2-3*x+2))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = numerator((x^3-1)/(x^2-1))\nex2 = giac(\"numer((x^3-1)/(x^2-1))\")\n#Note: Giac/numer -> Julia/numerator\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = denominator((x^3-1)/(x^2-1))\nex2 = giac(\"denom((x^3-1)/(x^2-1))\")\n#Note: Giac/denom -> Julia/denominator\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = left(x^2-1 \u2a66 2*x+3)\nex2 = giac(\"left(x^2-1 = 2*x+3)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = right(x^2-1 \u2a66 2*x+3)\nex2 = giac(\"right(x^2-1 = 2*x+3)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = diff(x^3-x,x)\nex2 = giac(\"diff(x^3-x,x)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = diff(exp(x*y),x,x,x,y,y)\nex2 = giac(\"diff(exp(x*y),x,x,x,y,y)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = integrate(1/(4+z^2),z)\nex2 = giac(\"integrate(1/(4+z^2),z)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = integrate(1/(1-x^4),x,2,3)\nex2 = giac(\"integrate(1/(1-x^4),x,2,3)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = limit(sin(x)/(x^2-3*x),x=>0)\nex2 = giac(\"limit(sin(x)/(x^2-3*x),x=0)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = limit((2*x-1)/exp(1/(x-1)),x=>plus_inf)\nex2 = giac(\"limit((2*x-1)/exp(1/(x-1)),x=+infinity)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = limit(sign(x),x=>0,1)\nex2 = giac(\"limit(sign(x),x=0,1)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = series((x^4+x+2)/(x^2+1),x=>0, 5)\nex2 = giac(\"series((x^4+x+2)/(x^2+1),x=0, 5)\")\n@test evaluate(ex1) == evaluate(ex2)\n\n#ex1 = series(1/(1+x+y),[x,y],[0,0],5)\n#ex2 = giac(\"series(1/(1+x+y),[x,y],[0,0],5)\")\n#@test evaluate(ex1) == evaluate(ex2)\n\nex1 = sum(1/n^2,n,1,17)\nex2 = giac(\"sum(1/n^2,n,1,17)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = sum(1/n^2,n,1,17,2)\nex2 = giac(\"sum(1/n^2,n,1,17,2)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = sum(1/n^2,n,1,infinity)\nex2 = giac(\"sum(1/n^2,n,1,infinity)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = sum(cos(n*x),n)\nex2 = giac(\"sum(cos(n*x),n)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = curl([2*x*y,x*z,y*z],[x,y,z])\nex2 = giac(\"curl([2*x*y,x*z,y*z],[x,y,z])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = divergence([x^2+y,x+z+y,z^3+x^2],[x,y,z])\nex2 = giac(\"divergence([x^2+y,x+z+y,z^3+x^2],[x,y,z])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = grad(2*x^2*y-x*z^3,[x,y,z])\nex2 = giac(\"grad(2*x^2*y-x*z^3,[x,y,z])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = hessian(2*x^2*y-x*z,[x,y,z])\nex2 = giac(\"hessian(2*x^2*y-x*z,[x,y,z])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = taylor(sin(x)/x,x)\nex2 = giac(\"taylor(sin(x)/x,x)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = taylor(sin(x)/x,x=>0, 7)\nex2 = giac(\"taylor(sin(x)/x,x=0, 7)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = solve(x^2-3\u2a661)\nex2 = giac(\"solve(x^2-3=1)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = solve([y-z\u2a660,z-x\u2a660,x-y\u2a660,x-1+y+z\u2a660],[x,y,z])\nex2 = giac(\"solve([y-z=0,z-x=0,x-y=0,x-1+y+z=0],[x,y,z])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = zeros(x^2-4,x)\nex2 = giac(\"zeros(x^2-4,x)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = zeros([x^2-1,x^2-y^2],[x,y])\nex2 = giac(\"zeros([x^2-1,x^2-y^2],[x,y])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = cSolve(x^4-1\u2a660, x)\nex2 = giac(\"cSolve(x^4-1=0, x)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = cSolve([x^4-y^4,x+y\u2a660,x^2\u2a662*x],[x,y])\nex2 = giac(\"cSolve([x^4-y^4,x+y=0,x^2=2*x],[x,y])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = cZeros(x^4-1, x)\nex2 = giac(\"cZeros(x^4-1, x)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = cZeros([x^2-1,x^2-y^2],[x,y])\nex2 = giac(\"cZeros([x^2-1,x^2-y^2],[x,y])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = fSolve(cos(x)\u2a66x,x=>0)\nex2 = giac(\"fsolve(cos(x)=x,x=0)\")\n#Note: renamed fsolve->fSolve, because that is the name the HP Prime uses\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = deSolve(diff(y(x),x,x)+y(x)\u2a660, y)\nex2 = giac(\"deSolve(diff(y(x),x,x)+y(x)=0, y)\")\n@test evaluate(ex1) == evaluate(ex2)\n\n#ex1 = deSolve(y''(x)+y(x)\u2a660, y)\n#ex2 = giac(\"deSolve(y''+y=0, y)\")\n##Note: standalone y,y',y'' in this context not yet defined\n#@test evaluate(ex1) == evaluate(ex2)\n\nex1 = linsolve([x+y+z\u2a661,x-y\u2a662,2*x-z\u2a663],[x,y,z])\nex2 = giac(\"linsolve([x+y+z=1,x-y=2,2*x-z=3],[x,y,z])\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = logcollect(log(x)+2*log(y))\nex2 = giac(\"lncollect(log(x)+2*log(y))\")\n#Note: renamed lncollect->logcollect because Giac/ln is Julia/log\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = powexpand(2^(x+y))\nex2 = giac(\"powexpand(2^(x+y))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = texpand(sin(2*x)+exp(x+y))\nex2 = giac(\"texpand(sin(2*x)+exp(x+y))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = exp2pow(exp(3*log(x)))\nex2 = giac(\"exp2pow(exp(3*log(x)))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = pow2exp(x^y)\nex2 = giac(\"pow2exp(x^y)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = exp2trig(exp(im*x))\nex2 = giac(\"exp2trig(exp(i*x))\")\n#Note: Julia/im corresponds to Giac/i\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = expexpand(exp(3*x+2*y))\nex2 = giac(\"expexpand(exp(3*x+2*y))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = asin2acos(acos(x)+asin(x))\nex2 = giac(\"asin2acos(acos(x)+asin(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = asin2atan(2*asin(x))\nex2 = giac(\"asin2atan(2*asin(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = sin2costan(sin(x))\nex2 = giac(\"sin2costan(sin(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = acos2asin(acos(x)+asin(x))\nex2 = giac(\"acos2asin(acos(x)+asin(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = acos2atan(2*acos(x))\nex2 = giac(\"acos2atan(2*acos(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = cos2sintan(cos(x))\nex2 = giac(\"cos2sintan(cos(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = atan2asin(atan(2*x))\nex2 = giac(\"atan2asin(atan(2*x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = atan2acos(atan(2*x))\nex2 = giac(\"atan2acos(atan(2*x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = tan2sincos(tan(x))\nex2 = giac(\"tan2sincos(tan(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = halftan(sin(x))\nex2 = giac(\"halftan(sin(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = trigsin(cos(x)^4+sin(x)^2)\nex2 = giac(\"trigsin(cos(x)^4+sin(x)^2)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = trigcos(cos(x)^4+sin(x)^2)\nex2 = giac(\"trigcos(cos(x)^4+sin(x)^2)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = trigtan(cos(x)^4+sin(x)^2)\nex2 = giac(\"trigtan(cos(x)^4+sin(x)^2)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = atrig2log(atan(x))\nex2 = giac(\"atrig2ln(atan(x))\")\n#Note: renamed atrig2ln->atrig2log because Giac/ln is Julia/log\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = tlin(sin(x)^3)\nex2 = giac(\"tlin(sin(x)^3)\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = tcollect(sin(x)+cos(x))\nex2 = giac(\"tcollect(sin(x)+cos(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = trigexpand(sin(3*x))\nex2 = giac(\"trigexpand(sin(3*x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\nex1 = trig2exp(sin(x))\nex2 = giac(\"trig2exp(sin(x))\")\n@test evaluate(ex1) == evaluate(ex2)\n\n# to be continued ...\n", "meta": {"hexsha": "64e456b91fbf7417490bda25637446099943304d", "size": 10168, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_library.jl", "max_stars_repo_name": "chakravala/Giac.jl", "max_stars_repo_head_hexsha": "6aa9652195b61d5b23621a65d4e6f50d85663fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-03T16:54:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T20:27:00.000Z", "max_issues_repo_path": "test/test_library.jl", "max_issues_repo_name": "chakravala/Giac.jl", "max_issues_repo_head_hexsha": "6aa9652195b61d5b23621a65d4e6f50d85663fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-11T09:34:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-11T09:34:52.000Z", "max_forks_repo_path": "test/test_library.jl", "max_forks_repo_name": "chakravala/Giac.jl", "max_forks_repo_head_hexsha": "6aa9652195b61d5b23621a65d4e6f50d85663fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-06T01:42:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-10T18:36:21.000Z", "avg_line_length": 29.3025936599, "max_line_length": 79, "alphanum_fraction": 0.6099527931, "num_tokens": 4208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7739535471299352}}
{"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    \u03a3(\u03c4) = J\u00b2 * G(\u03c4) * G(\u03c4) * G(\u03b2-\u03c4),\n    \n where Green's function of the SYK model is given by the Dyson equation,\n\n    G(i\u03c9\u2099) = -1/(i\u03c9\u2099 -\u03bc + \u03a3(i\u03c9\u2099))\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 \u03bc=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(\u03c4, \u03b2) = \u03c0^(1 / 4) / sqrt(2\u03b2) * 1 / sqrt(sin(\u03c0 * \u03c4 / \u03b2))\n\nfunction syk_sigma_dlr(d, G_x, J = 1.0; sumrule = nothing, verbose = false)\n\n    tau_k = d.\u03c4 # DLR imaginary time nodes\n    tau_k_rev = d.\u03b2 .- 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 \u2248 0.0 \"Only the case \u03bc=0 enjoys the particle-hole symmetry.\"\n        return 1im * imag.(-1 ./ (d.\u03c9n * 1im .- mu .+ sigma_q))\n    elseif d.symmetry == :none\n        return -1 ./ (d.\u03c9n * 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\", \"\u03c4\", \"DLR imag\", \"DLR real\", \"asymtotically exact\")\n    for i in 1:d.size\n        if d.\u03c4[i] <= d.\u03b2 / 2\n            @printf(\"%15.8f%40.15f%40.15f%40.15f\\n\", d.\u03c4[i], imag(G_x[i]), real(G_x[i]), conformal_tau(d.\u03c4[i], d.\u03b2))\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, \u03b2 = 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    \u03b2 = 10000.0\n    # printstyled(\"=====     Symmetrized DLR solver for SYK model     =======\\n\", color = :yellow)\n    mix = 0.01\n    dsym = DLRGrid(Euv = Euv, \u03b2 = \u03b2, 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, \u03b2 = \u03b2, 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\", \"\u03c4\", \"sym DLR (interpolated)\", \"unsym DLR\", \"difference\")\n    # G_x_interp = tau2tau(dsym_correct, G_x_correct, dnone.\u03c4)\n    # for i in 1:dnone.size\n    #     if dnone.\u03c4[i] <= dnone.\u03b2 / 2\n    #         @printf(\"%15.8f%40.15f%40.15f%40.15f\\n\", dnone.\u03c4[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.\u03c4)\n    G_x_interp_none = tau2tau(dsym_correct, G_x_correct, dnone.\u03c4)\n    G_x_interp_none_sumrule = tau2tau(dsym_correct, G_x_correct, dnone.\u03c4)\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": "include(\"preamble.jl\")\n\n# ----------------------------\n# Plotting a 3D polyhedron\n# ----------------------------\n\n# Note: in this figure we use non-latex fonts for the ticks labels because\n# the Makie plot ignores L\"x_3\"\n\nusing LazySets, Symbolics\nimport Polyhedra, CDDLib, Plots\nusing Colors\n\n# projected polyhedron from symbolic constraints\nvars = @variables x1, x2, x3  # create symbols\nP = HPolyhedron([2*x1>=0, 3*x2+1.7*x3>=0], vars)\nQ = project(P, [2, 3])  # 2D projection (x2 and x3)\n\n\nfig = p(xlim=(-4, 4), ylim=(-4, 4), ratio=1, xlab=\"x\u2082\", ylab=\"x\u2083\",\n           legendfontsize=20,\n           tickfont=font(20), # , \"Times\"),\n           guidefontsize=20,\n           xguidefont=font(20), # , \"Times\"),\n           yguidefont=font(20), # , \"Times\"),\n           xtick = ([-4, 0, 4], [\"-4\", \"0\", \"4\"]),\n           ytick = ([-4, 0, 4], [\"-4\", \"0\", \"4\"]),\n           bottom_margin=0mm, left_margin=0mm, right_margin=0mm, top_margin=2mm, size=(500, 380))\n\nplot!(fig, Q, color=:deepskyblue)  # plot the 2D projection\n\nsavefig(\"polyhedron2D.pdf\")\n\n\n# plot the 3D set directly\nusing GLMakie\n\n# intersection with a bounding box\nB = BallInf(zeros(3), 5.0)\nR = intersection(P, B)\n\n# obtain the mesh\nbackend = LazySets.default_polyhedra_backend(R);\nP_poly_mesh = LazySets._plot3d_helper(R, backend);\n\nfig3d = Figure()\nax = Axis3(fig3d[1, 1], xlabel=\"x\u2081\", xlabelsize=40, xticklabelsize=40,\n                    ylabel=\"x\u2082\", ylabelsize=40, yticklabelsize=40,\n                    zlabel=\"x\u2083\", zlabelsize=40, zticklabelsize=40,\n                    aspect=:data,\n                    height=400)\n\nmesh!(P_poly_mesh, alpha=1.0, color=:deepskyblue, colormap=:viridis, colorrange=Makie.Automatic(), interpolate=false,\n                   linewidth=1, overdraw=false, shading=true, transparency=true, visible=true)\n\nwireframe!(P_poly_mesh, color = :red, linewidth=1.5, linestyle=:dash, axis=(type=Axis3,))\n\nMakie.save(\"polyhedron3D.png\", fig3d)\n\n# f = Figure()\n# fig = plot3d(R)  # plot in three dimensions\n# current_figure()\n# display(fig) # display in a pop-up window\n", "meta": {"hexsha": "7414e10ac367e18f8a5ac8f43d4e53b2af4e3f0d", "size": 2051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "paper/img/plot_polyhedron.jl", "max_stars_repo_name": "JuliaReach/LazySets-JuliaCon21", "max_stars_repo_head_hexsha": "033612bd98ef8692195e4860e7eaa7bfbd05e6c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-28T20:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T16:51:11.000Z", "max_issues_repo_path": "paper/img/plot_polyhedron.jl", "max_issues_repo_name": "JuliaReach/LazySets-JuliaCon21", "max_issues_repo_head_hexsha": "033612bd98ef8692195e4860e7eaa7bfbd05e6c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-03T13:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T21:15:45.000Z", "max_forks_repo_path": "paper/img/plot_polyhedron.jl", "max_forks_repo_name": "JuliaReach/LazySets-JuliaCon21", "max_forks_repo_head_hexsha": "033612bd98ef8692195e4860e7eaa7bfbd05e6c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-27T15:57:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T15:57:41.000Z", "avg_line_length": 32.046875, "max_line_length": 117, "alphanum_fraction": 0.614334471, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7739535366557845}}
{"text": "# indicator of a simplex\n\n\"\"\"\n  IndSimplex(a::Union{Real, Integer}=1.0)\n\nReturns the function `g = ind{x : x \u2a7e 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\u2013585, 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 \u21a6 0 if x \u2a7e 0 and sum(x) = a, +\u221e 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": "#=\n  Test of Bernoulli\n\n  See\n     ~/blog/bernoulli_test.blog\n     ~/webppl/bernoulli_test.wppl\n=#\n\n# using Memoization\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 bernoulli_test(y)\n    prob ~ Beta(4,4)\n    n = length(y)\n    for i in 1:n\n        y[i] ~ Bernoulli(prob)\n    end\n\nend\n\n# Generated by R:\n# > rbinom(120,1,0.3)\n# I.e. prob should be around 0.3\n#=\ny = [0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,1,1,0,1,0,\n    1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,1,1,0,1,0,1,0,0,1,1,0,0,0,1,0,1,0,0,0,\n    0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,1,1,0,0,1,0,0,1,0,1,1,\n    0,1,0,1,0,0,0,0,0,1,0,0]\n=#\n# Generate data\ny = rand(Bernoulli(0.3),1_000)\nprintln(\"length(y):$(length(y))\")\n# println(\"y:$y\")\nmodel = bernoulli_test(y)\nnum_chns = 4\n\n# chns = sample(model, Prior(), MCMCThreads(), 1000, num_chns)\n\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, MH(), MCMCThreads(), 10_000, num_chns)\n\n# chns = sample(model, PG(20), MCMCThreads(), 10_000, num_chns)\n# chns = sample(model, PG(20), 1_000)\n# chns = sample(model, IS(), MCMCThreads(), 10_000, num_chns) # Nope: does not handle the observation\n# chns = sample(model, IS(), 10_000)\n\n# chns = sample(model, SMC(), 10_000)\n\n\n# chns = sample(model, NUTS(1000,0.65), MCMCThreads(), 40_000, num_chns)\n# chns = sample(model, Gibbs(MH(:zlabels),NUTS(1000,0.65,:m,:b,:sigma)), MCMCThreads(), 40_000, num_chns)\n\ndisplay(chns)\n", "meta": {"hexsha": "c504dcdd47aec466d9baff01f72ae4ee5de234ef", "size": 1567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bernoulli_test.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/bernoulli_test.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/bernoulli_test.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.5593220339, "max_line_length": 105, "alphanum_fraction": 0.6375239311, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7739505947430715}}
{"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    \u0394x = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h\u2080 = h(x[1])\n\n    all(\u2248(h(x[1])), h.(x)) || error(\"Filter width must be constant\")\n    if \u0394x .\u2248 2h\u2080\n        # Three point stencil\n        inds = [-1, 0, 1]\n        stencil = [1 // 24, 11 // 12, 1 // 24]\n    elseif \u0394x .\u2248 h\u2080\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) \u2208 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    \u0394x = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h\u2080 = h(x[1])\n\n    all(\u2248(h(x[1])), h.(x)) || error(\"Filter width must be constant\")\n    \u0394x \u2248 2h\u2080 || 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) \u2208 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": "# tests based on AMLCR 2nd ed,\n@testset \"AMLCR Math\" begin\n\n    # \u00a75.7 payment frequency and certain (Tables 5.1 and 5.2)\n    function f(age)\n        life = SingleLife(mort = AMLCR_std, issue_age = age)\n        int = Yields.Constant(0.05)\n        lc = [\n            AnnuityImmediate(life,int)\n            AnnuityImmediate(life,int,frequency=4)\n            AnnuityDue(life,int)\n            AnnuityDue(life,int,frequency=4)\n            AnnuityImmediate(life,int,n=10)\n            AnnuityImmediate(life,int,n=10,frequency=4)\n            AnnuityDue(life,int,n=10,frequency=4)\n        ]\n        \n        return present_value.(lc)\n    end\n\n    # atol only to two decimals b/c AMLCR uses rounded rates?\n    @test all(isapprox.(f(20), [18.966, 19.338, 19.966, 19.588, 7.711, 7.855, 7.952],atol=.01))\n    @test all(isapprox.(f(80), [ 7.548,  7.917,  8.548,  8.167, 6.128, 6.373, 6.539],atol=.01))\n\n    life = SingleLife(mort = AMLCR_std, issue_age = 20)\n    int = Yields.Constant(0.05)\n\n    # property tests\n\n    @test present_value(AnnuityDue(life,int)) > present_value(AnnuityDue(life,int,start_time=5))\n\n    @test present_value(AnnuityDue(life,int,n=5,certain=5,start_time=5)) == sum([1 for t in 5:9] .* [1/1.05 ^t for t in 5:9])\n    \n    # relation on pg 124\n    @test issorted(present_value.([\n        AnnuityImmediate(life,int)\n        AnnuityImmediate(life,int,frequency=4) \n        AnnuityDue(life,int,frequency=4)\n        AnnuityDue(life,int) \n    ]))\n\nend#", "meta": {"hexsha": "31366b6a5d214c9868f9de7879cd3c875d355c12", "size": 1457, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/AMLCR.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": "test/AMLCR.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": "test/AMLCR.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": 34.6904761905, "max_line_length": 125, "alphanum_fraction": 0.6135895676, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7739132710066376}}
{"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\u0307, y\u0307, z\u0307]`.\n\nThe order of the parameters follows: `[\u03bc]`.\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 \u03bc \n    @variables x(t) y(t) z(t) x\u0307(t) y\u0307(t) z\u0307(t)\n    \u03b4 = Differential(t)\n    r = @SVector [x,y,z]\n    v = @SVector [x\u0307,y\u0307,z\u0307]\n\n    eqs = vcat(\n        \u03b4.(r) .~ v,\n        \u03b4.(v) .~ -\u03bc .* (r ./ norm(r)^3)\n    )\n\n    if stm \n        @variables \u03a6[1:6,1:6](t)\n        \u03a6 = Symbolics.scalarize(\u03a6)\n        A = Symbolics.jacobian(map(el -> el.rhs, eqs), vcat(r,v))\n    \n        LHS = map(\u03b4, \u03a6)\n        RHS = map(simplify, A * \u03a6)\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,\u03a6...) : vcat(r,v), [\u03bc]; \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\u0307, y\u0307, z\u0307]`.\n\nThe order of the parameters follows: `[\u03bc]`.\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": "using SpecialPolynomials; const SP=SpecialPolynomials\nusing Polynomials\nimport LinearAlgebra: eigvals, det, dot, norm\nimport SpecialFunctions: gamma\nusing Test\n\n@testset \"Orthogonal\" begin include(\"Orthogonal.jl\") end\n@testset \"Orthogonal compare with tables\" begin include(\"Orthogonal-compare.jl\") end\n#@testset \"ChebyshevT\" begin include(\"ChebyshevT.jl\") end\n#@testset \"ChebyshevU\" begin include(\"ChebyshevU.jl\") end\n#@testset \"Laguerre{\u03b1}\" begin include(\"GeneralizedLaguerre.jl\") end\n#@testset \"Gegenbauer{\u03b1}\" begin include(\"Gegenbauer.jl\") end\n\n@testset \"Lagrange\" begin include(\"Lagrange.jl\") end\n@testset \"Newton\" begin include(\"Newton.jl\") end\n\n@testset \"Bernstein\" begin include(\"Bernstein.jl\") end\n", "meta": {"hexsha": "17a9b0cfbb9371d02a25b72791c7fdad792c010e", "size": 707, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "t-bltg/SpecialPolynomials.jl", "max_stars_repo_head_hexsha": "d003acce77af1490333dcfd6697228ca1614e1ae", "max_stars_repo_licenses": ["MIT"], "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": "t-bltg/SpecialPolynomials.jl", "max_issues_repo_head_hexsha": "d003acce77af1490333dcfd6697228ca1614e1ae", "max_issues_repo_licenses": ["MIT"], "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": "t-bltg/SpecialPolynomials.jl", "max_forks_repo_head_hexsha": "d003acce77af1490333dcfd6697228ca1614e1ae", "max_forks_repo_licenses": ["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.2777777778, "max_line_length": 84, "alphanum_fraction": 0.7793493635, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7739115229072752}}
{"text": "\"\"\"\n    count_total_bits(n::Int64)\n\nCalculates the total number of bits from 1 to `n` for a given integer `n` by combing a \nwhile-loop for building the binary subsets with a range for-loop for counting the bits.\n\n\n# Arguments\n- `n::Int64`: Integer value which has to be evaluated.\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> ClassicAlgorithmsCollections.count_total_bits(17)\n35\n```\n\"\"\"\nfunction count_total_bits(n::Int64)\n\n    i = 0\n    result = 0\n\n    while n > (1 << i)\n\n        k =0\n        change = 1 << i\n\n        for _ in 1:n+1\n            result += k\n\n            if change == 1\n                # Flipping the bit\n                if k == 0\n                    k = 1\n                else\n                    k = 0\n                end\n                change = 1 << i \n  \n            else \n                change -= 1\n            end\n        end\n        i += 1\n\n    end\n    return result\nend\n", "meta": {"hexsha": "c3b112ac9255b5862c43ebd81fad1e3377ce7bd6", "size": 929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BitManipulation/CountTotalBits.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/CountTotalBits.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/CountTotalBits.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": 18.58, "max_line_length": 87, "alphanum_fraction": 0.5069967707, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303732328411, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7739115206150895}}
{"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 Distributions\ndists = [\n    DiscreteUniform(10,20),\n    Binomial(10,0.5),\n    Geometric(0.5),\n    NegativeBinomial(10,0.5),\n    Hypergeometric(30, 40, 10),\n    Poisson(5.5)]\n\nprintln(\"Distribution \\t\\t\\t\\t\\t\\t Parameters \\t Support\")\nreshape([dists ;  params.(dists) ;\n\t\t((d)->(minimum(d),maximum(d))).(dists) ],\n\t\tlength(dists),3)\n", "meta": {"hexsha": "b9505376277de3fdce08b74f3230dd40bf382547", "size": 338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/discreteDists.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/discreteDists.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/discreteDists.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.1428571429, "max_line_length": 58, "alphanum_fraction": 0.6331360947, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7739115183229033}}
{"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\u2080 = g.k[2] # Fundamental wavenumber\n\n    # Analytic function\n    \u03c6 = \u03c0/3\n    f\u2081 = @. cos(m*k\u2080*g.x + \u03c6)\n\n    # Transform of f\u2081 three ways\n     f\u2081h = fft(f\u2081)\n    f\u2081hr = rfft(f\u2081)\n    f\u2081hr_mul = zeros(Complex{eltype(g.x)}, g.nkr)\n    mul!(f\u2081hr_mul, g.rfftplan, f\u2081)\n\n    # Analytical values of the fft and rfft\n     f\u2081h_analytical = zeros(Complex{Float64}, size(f\u2081h))\n    f\u2081hr_analytical = zeros(Complex{Float64}, size(f\u2081hr))\n\n    for i in 1:g.nk\n      if abs(real(g.k[i])) == m*k\u2080\n        f\u2081h_analytical[i] = -exp(sign(real(g.k[i]))*im*\u03c6)*g.nx/2\n      end\n    end\n\n    for i in 1:g.nkr\n      if abs(real(g.k[i])) == m*k\u2080\n        f\u2081hr_analytical[i] = -exp(sign(real(g.kr[i]))*im*\u03c6)*g.nx/2\n      end\n    end\n\n    f\u2081, f\u2081h, f\u2081hr, f\u2081hr_mul, f\u2081h_analytical, f\u2081hr_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\u2080 = g.k[2]\n    l\u2080 = g.l[2]\n\n    # Analytic functions\n    f\u2081 = @. cos(m*k\u2080*g.x) * cos(n*l\u2080*g.y)\n    f\u2082 = @. sin(m*k\u2080*g.x + n*l\u2080*g.y)\n\n     f\u2081h = fft(f\u2081)\n     f\u2082h = fft(f\u2082)\n    f\u2081hr = rfft(f\u2081)\n    f\u2082hr = rfft(f\u2082)\n\n    f\u2081hr_mul = zeros(Complex{eltype(g.x)}, (g.nkr, g.nl))\n    f\u2082hr_mul = zeros(Complex{eltype(g.x)}, (g.nkr, g.nl))\n    mul!(f\u2081hr_mul, g.rfftplan, f\u2081)\n    mul!(f\u2082hr_mul, g.rfftplan, f\u2082)\n\n    # Theoretical results\n     f\u2081h_analytical = zeros(Complex{eltype(g.x)}, size(f\u2081h))\n     f\u2082h_analytical = zeros(Complex{eltype(g.x)}, size(f\u2082h))\n    f\u2081hr_analytical = zeros(Complex{eltype(g.x)}, size(f\u2081hr))\n    f\u2082hr_analytical = zeros(Complex{eltype(g.x)}, size(f\u2082hr))\n\n    for j in 1:g.nl, i in 1:g.nk\n      if ( abs(real(g.k[i])) == m*k\u2080 && abs(real(g.l[j])) == n*l\u2080 )\n        f\u2081h_analytical[i, j] = - g.nx*g.ny/4\n      end\n      if ( real(g.k[i]) == m*k\u2080 && real(g.l[j]) == n*l\u2080 )\n        f\u2082h_analytical[i, j] = -g.nx*g.ny/2\n      elseif ( real(g.k[i]) == -m*k\u2080 && real(g.l[j]) == -n*l\u2080 )\n        f\u2082h_analytical[i, j] = g.nx*g.ny/2\n      end\n    end\n    f\u2082h_analytical = -im*f\u2082h_analytical;\n\n    for j in 1:g.nl, i in 1:g.nkr\n      if ( abs(g.kr[i])==m*k\u2080 && abs(g.l[j])==n*l\u2080 )\n        f\u2081hr_analytical[i, j] = - g.nx*g.ny/4\n      end\n      if ( real(g.kr[i]) == m*k\u2080 && real(g.l[j]) == n*l\u2080 )\n        f\u2082hr_analytical[i, j] = -g.nx*g.ny/2\n      elseif ( real(g.kr[i]) == -m*k\u2080 && real(g.l[j]) == -n*l\u2080 )\n        f\u2082hr_analytical[i, j] = g.nx*g.ny/2\n      end\n    end\n    f\u2082hr_analytical = -im*f\u2082hr_analytical;\n\n    f\u2081, f\u2082, f\u2081h, f\u2082h, f\u2081hr, f\u2082hr, f\u2081hr_mul, f\u2082hr_mul, f\u2081h_analytical, f\u2081hr_analytical, f\u2082h_analytical, f\u2082hr_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\u00d74 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\u00d74 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\u00d75 Matrix{Number}:\n  1   1  im  1   1\n  1  im   1  1   \u03c0\n im   1   1  \u03c0   \u03c0\n  1   1   \u03c0  \u03c0   \u03c0\n  1   \u03c0   \u03c0  \u03c0  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# \u2554\u2550\u2561 93b38489-898a-4695-a167-5f5a782ef0e8\nusing DifferentialEquations\n\n# \u2554\u2550\u2561 8a49cf89-d1c8-4847-8b9b-70b23c2b609c\nusing Plots\n\n# \u2554\u2550\u2561 3e86dfc7-8567-4b0d-a75a-13422acfa20a\nusing HypertextLiteral\n\n# \u2554\u2550\u2561 71bcf780-2eb2-487f-b90e-1a2b3f740e19\nusing PlutoUI\n\n# \u2554\u2550\u2561 1de38637-f5d2-4679-a6f6-2a9672a9e5ea\nusing ParameterizedFunctions\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2080`. For our model, the only parameter is the rate constant `k`, therefore we build the parameter collection `p` as\"\n\n# \u2554\u2550\u2561 5c41d702-aab7-44a8-9347-a26ed27703ed\nk=1;\n\n# \u2554\u2550\u2561 0995aee5-f4f9-4d75-9651-5513bd243a36\np=(k);\n\n# \u2554\u2550\u2561 9913179f-1a94-4d20-87ff-bd2c2bec7530\nu\u2080=[0.02,0.01,0];\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 379f8c7e-3f7c-43f4-8387-f75728b3c4a3\ntspan = (0.0,100.0);\n\n# \u2554\u2550\u2561 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\u2080`, the time span `tspan` and the parameters  `p`:\"\n\n# \u2554\u2550\u2561 93854457-e209-42ea-b533-5a018ad2024b\nprob1 = ODEProblem(simpleODE1!,u\u2080,tspan,p)\n\n# \u2554\u2550\u2561 292bcc76-e7e6-4628-a839-5e83f8caba68\nsol1 = solve(prob1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cd970122-8288-40d8-ac15-564ca8cb26f3\nsol1.t[3],sol1.u[3]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 981c2e93-9495-4482-9c5c-970c6c8e03d2\nsol1[:,3]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b0f2ef4b-29c2-44d9-9382-dd5421260296\nsol1(60.4)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ce923957-2f70-4023-bab4-8a73a6fd3800\nsol1_ = solve(prob1,dense=false)\n\n# \u2554\u2550\u2561 65cd089f-7563-4696-a5fa-81074ef8bb33\nplot(sol1_,label=[\"a\",\"b\",\"c\"],seriestype=:scatter)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 75c7c433-c228-4417-be7b-f1f50b2c4921\nbegin\n\tprob2 = ODEProblem(simpleODE2!,u\u2080,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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2080,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# \u2554\u2550\u2561 353b1a99-0c87-4286-9b22-3c5f72145e52\nmd\"or, using the DSL notation avaliable in Julia\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 50e9d7ee-68b1-497c-bd91-0be168e0b964\nbegin\n\tprob = ODEProblem(simpleODE2_rev!,u\u2080,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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 63e0ac0e-c6a1-40f4-8af9-a0a5eaabf344\nbegin\n\tBB=sol4[2,:]\n\tc_eq=BB*u\u2080[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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 26c8db68-c21d-4f94-a93c-a82eb7753d3e\nbegin\n\tk1_=2.3e0;  # units 1/(Ms)\n\tk2_=2.5e0;  # units 1/(M M s)\n\ta\u2080=0.02; # units (M)\n\tb\u2080=0.01; # units (M)\n\tc\u2080=0; # units (M)\n\td\u2080=0; # units (M)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d12f7049-25b8-4cca-b2f4-788a2314c973\nbegin\n\tprob5 = ODEProblem(simpleODE3!,[a\u2080,b\u2080,c\u2080,d\u2080],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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a1dc49b8-52b4-474f-9463-9231ac879b90\nbegin\n\tcte=a\u2080+b\u2080+c\u2080+d\u2080/2\n\tprob7 = ODEProblem(simpleODE4!,[a\u2080,b\u2080,d\u2080],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# \u2554\u2550\u2561 0e0f7785-e323-4aed-8dd4-e7fa91eddd4a\nplot!(sol7.t,a\u2080.+b\u2080.+c\u2080.+(d\u2080./2).-(sol7[1,:].+sol7[2,:].+(sol7[3,:]./2)),label=\"c(t)\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25006458ccf4-03b2-4d7f-8206-dcdeef1bc020\n# \u2560\u255093b38489-898a-4695-a167-5f5a782ef0e8\n# \u2560\u25508a49cf89-d1c8-4847-8b9b-70b23c2b609c\n# \u2560\u25503e86dfc7-8567-4b0d-a75a-13422acfa20a\n# \u2560\u255071bcf780-2eb2-487f-b90e-1a2b3f740e19\n# \u255f\u250023c6e540-3049-419b-bf82-4141977f9a0f\n# \u2560\u2550ed4267e2-8c95-4d78-955f-b89cdb125f18\n# \u255f\u2500423bf107-0d98-48f6-b780-932fd216b803\n# \u2560\u25505c41d702-aab7-44a8-9347-a26ed27703ed\n# \u2560\u25500995aee5-f4f9-4d75-9651-5513bd243a36\n# \u2560\u25509913179f-1a94-4d20-87ff-bd2c2bec7530\n# \u255f\u25003ac8e1d7-429f-4ae3-8b33-beafaf9bf043\n# \u2560\u2550379f8c7e-3f7c-43f4-8387-f75728b3c4a3\n# \u255f\u2500f25d32de-fd9f-408d-b3b8-0b4707467186\n# \u2560\u255093854457-e209-42ea-b533-5a018ad2024b\n# \u2560\u2550292bcc76-e7e6-4628-a839-5e83f8caba68\n# \u255f\u2500edebc440-cf82-4ba4-a97e-90da9220690b\n# \u2560\u2550cd970122-8288-40d8-ac15-564ca8cb26f3\n# \u255f\u2500e4f3b341-4136-4f77-884b-e9c403e45d09\n# \u2560\u2550981c2e93-9495-4482-9c5c-970c6c8e03d2\n# \u2560\u25506837c59d-1d1b-4ff6-8016-dd81703226c9\n# \u255f\u2500f67a4f14-3051-4e43-9fbf-a332d1b59dd7\n# \u2560\u2550b0f2ef4b-29c2-44d9-9382-dd5421260296\n# \u255f\u2500995b908f-ccf8-48ba-a45c-024f8d6527f4\n# \u2560\u2550ce923957-2f70-4023-bab4-8a73a6fd3800\n# \u2560\u255065cd089f-7563-4696-a5fa-81074ef8bb33\n# \u255f\u2500b4696fcc-8c09-4563-88e2-0aca1d734eba\n# \u2560\u25501de38637-f5d2-4679-a6f6-2a9672a9e5ea\n# \u2560\u2550d8158943-8ba2-4176-b3d7-e99197c82e1b\n# \u2560\u255075c7c433-c228-4417-be7b-f1f50b2c4921\n# \u255f\u25008a5644dc-69cf-44dc-b5f7-eadc8c3aa0a7\n# \u2560\u2550d275e770-76f0-4a9f-8628-1abfc4eeedf5\n# \u255f\u2500416c8f55-154a-4953-8162-b0c2e6069f48\n# \u2560\u2550a7993c27-7f27-40e6-8d63-ff74b31e6935\n# \u2560\u255005e01d78-de55-4655-b792-5ce62abea53a\n# \u255f\u2500353b1a99-0c87-4286-9b22-3c5f72145e52\n# \u2560\u2550dd5601e5-fc2a-4927-9292-f6bf2f51d2a0\n# \u2560\u255050e9d7ee-68b1-497c-bd91-0be168e0b964\n# \u255f\u25004481524c-8117-4835-b46e-ebe9d6878f40\n# \u2560\u255063e0ac0e-c6a1-40f4-8af9-a0a5eaabf344\n# \u255f\u25000b3661cc-ca0e-485d-bcdb-4fbc339c0195\n# \u255f\u250052196376-6060-4fd6-8fcc-d1505075bae8\n# \u255f\u250062516169-0e2e-4907-a87d-65af79e0926f\n# \u2560\u255026c8db68-c21d-4f94-a93c-a82eb7753d3e\n# \u255f\u2500143ef067-a8ec-4cc5-b2b5-43746529d4c6\n# \u2560\u2550a627aa52-e44a-4f83-99af-40e316643b3c\n# \u2560\u2550d12f7049-25b8-4cca-b2f4-788a2314c973\n# \u255f\u250075f33bbd-2340-4c92-aef3-77a33dd6ae3e\n# \u2560\u2550d268c6a7-45db-42a1-9a63-77800663ad6e\n# \u2560\u2550a1dc49b8-52b4-474f-9463-9231ac879b90\n# \u2560\u25500e0f7785-e323-4aed-8dd4-e7fa91eddd4a\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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(\u221e)]\nu = T*c\n\n@test u[0.0] \u2248 airyai(0.0)\nplot(u)\n\n\n##\n# Lee & Greengard\n# \u03b5*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\u03b5 = 1/100\nA = [T[[begin,end],:]; C \\ ((\u03b5*D^2 - x .* D + I) * T)]\nc = A \\ [1; 2; zeros(\u221e)]\nu = T*c\nplot(u)\n\nC \\ (\u03b5*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 \u00d7 9 \u00d7 8 \u00d7 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": "\r\nmodule cg\r\n\r\nusing BenchmarkTools\r\nusing LinearAlgebra\r\n\r\nfunction conjgrad(A, b, x_init; max_iter = Int(ceil(length(b)*5)), residual_tol = 1e-20 )\r\n\r\n    n_dim = length(b)\r\n    \r\n    x0  = copy(x_init)\r\n    r0  = A * x0 - b\r\n    p0  = -r0\r\n    rtr = dot(r0, r0)\r\n    iter = 0\r\n    \r\n    Ap = similar(x0)\r\n    for outer iter = 1:max_iter\r\n        if rtr <= residual_tol\r\n            break\r\n        end\r\n        # Ap      = A * p0\r\n        mul!(Ap, A, p0)\r\n        alpha   = rtr / dot(p0, Ap)\r\n        @inbounds @simd for ii = 1:n_dim\r\n            x0[ii] += alpha * p0[ii]\r\n            r0[ii] += alpha * Ap[ii]\r\n        end\r\n        # x1      = x0 + alpha * p0\r\n        # r1      = r0 + alpha * Ap\r\n        rtr1    = dot(r0, r0)\r\n        beta    = rtr1 / rtr\r\n        # p1      = - r1 + beta * p0\r\n\r\n        @inbounds  @simd  for ii = 1:n_dim\r\n            p0[ii] = p0[ii] * beta - r0[ii]\r\n        end\r\n\r\n        # p0  = p1\r\n        rtr = rtr1\r\n        # x0  = x1\r\n        # r0  = r1\r\n    end\r\n    return (x0, iter)\r\nend\r\n\r\n\r\nfunction test()\r\n    \r\n    # n_dim = 3000\r\n    # 0.193567 seconds (6 allocations: 68.711 MiB, 28.44% gc time)\r\n    # 35.281426 seconds (10 allocations: 117.578 KiB)\r\n\r\n    n_dim = 5\r\n    A = rand(n_dim, n_dim)\r\n    A = A' * A\r\n    b = rand(n_dim)\r\n\r\n    x0 = rand(n_dim)\r\n\r\n    # b = @benchmark x_theo = $A \\ $b\r\n    # b = @benchmark (x_cg, iter) = conjgrad($A, $b, $x0)\r\n\r\n    b1 = @benchmark $A \\ $b\r\n    b2 = @benchmark conjgrad($A, $b, $x0)\r\n\r\n    return (b1, b2)\r\n\r\n    # println(\"dx: $(x_theo - x_cg)\")\r\n    # println(\"norm dx: $(norm(x_theo - x_cg))\")\r\n\r\nend\r\n\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "9ee77bf8560c727e514c943c92637834c167649b", "size": 1604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/opti/src/ch.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/ch.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/ch.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.8311688312, "max_line_length": 90, "alphanum_fraction": 0.4488778055, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7737570291877379}}
{"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 \u2208(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\u22c3(aset, bset, x) = (\u2208(aset, x) || \u2208(bset, x))\n\n\u22c2(aset, bset, x) = (\u2208(aset, x) && \u2208(bset, x))\n\n-(aset, bset, x) = (\u2208(aset, x) && !\u2208(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] \u222a [0, 2): $(\u22c3(s1, s2, i))\")\n        println(\"    [0, 2) \u2229 (1, 2]: $(\u22c2(s2, s3, i))\")\n        println(\"    [0, 3) \u2212 (0, 1): $(-(s4, s5, i))\")\n        println(\"    [0, 3) \u2212 [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": "##\nusing Plots\nusing LinearAlgebra\nusing CSV\nusing MultivariateStats\nusing DataFrames\ntheme(:dark)\n##\ndf = CSV.read(\"wdbc.data\",header=false)\n## Filter to a matrix of only diagonstic information.\nX = Float64.(Matrix(df[:,3:end]))'\nX = df[:,3:end] |> Matrix |> (X -> Float64.(X)')\n\n\n##\nusing Statistics\nusing LinearAlgebra\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(X, true)\nscatter(V[:,1], V[:,2], alpha=0.5, color=Int.(CategoricalVector(df[:,2]).refs),\n    label=\"\", colorbar=false, size=(400,400), xticks=[], yticks=[])\n##\nsavefig(\"pca-breast-fig.pdf\")\n##\nscatter(S, label=\"\",size=(250,250))\n##\nsavefig(\"pca-breast-fig-singvals.pdf\")\n\n## For fun, try TSNE too...\nusing TSne\nusing Random\nRandom.seed!(0)\nrescale(A; dims=1) = (A .- mean(A, dims=dims)) ./ max.(std(A, dims=dims), eps())\nXr = rescale(X'; dims=1)\nY = tsne(Xr, 2, 50, 1000, 20.0)\nscatter(Y[:,1], Y[:,2],color=Int.(CategoricalVector(df[:,2]).refs), label=\"\")\n", "meta": {"hexsha": "f88dfef65306bc6b3e0aa155655742dde0b182cc", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2-unit-1-demos/pca-breast.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-breast.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-breast.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": 25.4130434783, "max_line_length": 80, "alphanum_fraction": 0.6458511548, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7737385022903672}}
{"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\u0394InitCost = B_InitCost - A_InitCost\n\u0394AnnualCost(x) = B_AnnualSavings + B_AnnualSavingsGradient * singlePaymentPresentWorthArithmetic(x, N) - A_AnnualSavings\n\u0394IRR(x) = \u0394InitCost + \u0394AnnualCost(x)\n\u0394IRR_ans = find_zero(\u0394IRR, 0.05)\n\nprintln(\"\u0394IRR > 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": "using PyCall\n@pyimport matplotlib.pyplot as plt\n\nsrand(0)\ninclude(\"generate_data.jl\")\n\nM = 100\nN = 100\n\n# A \"blurring\" matrix\nmy_matrix = zeros((M, N))\n# Note: Julia uses column-major order\nfor(j in 1:N)\n\tfor(i in 1:M)\n\t\tmy_matrix[i, j] = exp(-abs(i - j)/5.0)\n\tend\nend\n\n# A true signal that we want to recover\nx = zeros(N)\nx[Int(N/2):Int(N/2+5)] = 1.0\n\n# A dataset\ny = generate_data(x, my_matrix)\n\n# Do regularised inversion\ninclude(\"reginv.jl\")\nx_fit = reginv(y, my_matrix, 1.0)\n\n# Plot the data and the inferred signal using matplotlib\nplt.plot(x, \"ro-\", label=\"True signal\")\nplt.plot(y, \"bo-\", label=\"Blurred, noisy data\")\nplt.plot(x_fit, \"go-\", label=\"MAP\")\nplt.legend(loc=\"upper right\")\nplt.show()\n\n\n", "meta": {"hexsha": "a5715dc83a3597c6ec431b99858f06d46d4512d2", "size": 705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "main.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": "main.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": "main.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": 18.5526315789, "max_line_length": 56, "alphanum_fraction": 0.6737588652, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844408, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7737215944941987}}
{"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": "include(\"derivative.jl\")\n\nfunction quadratic(f)\n    # Compute the first derivative of f\n\tf1 = derivative(f)\n    \n    # Get the y intercept (explictly passing a floating point number)\n\tc = f(0.0)\n\n\t# Get the y intercept of the first derivative\n\tb = f1(0.0)\n\n\ta = f(1.0) - b - c\n    \n    # Our old friend the quadratic formula\n    # Notice how Julia lets you return multiple values\n    # Multiple values should be separated by a comma and\n    # are returned as a tuple\n    # return (-b + sqrt(b^2 -4a*c)) / 2a, (-b - sqrt(b^2 -4a*c)) / 2a\n\treturn (-b + sqrt(b^2 -4a*c + 0im)) / 2a, (-b - sqrt(b^2 -4a*c + 0im)) / 2a\nend\n\n\n\n", "meta": {"hexsha": "2bcaaf7c034b6996d8cef3f9e45dcf7eb860ff50", "size": 621, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 1/Chapter03/Old/quadratic/quadratic.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/quadratic.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/quadratic.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": 24.84, "max_line_length": 76, "alphanum_fraction": 0.616747182, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8056321913146128, "lm_q1q2_score": 0.7736978646805468}}
{"text": "module hw1_4\n\nusing LinearAlgebra, PlotlyJS, ORCA\n\nexport total_manuever, plot_maneuver\n\nfunction oe_to_r\u03b8h(oe::Vector,\u03bc::Real) :: Vector\n\n  a,e,i,\u03a9,\u03c9,\u03bd = oe\n  return [a*(1-e^2)/(1+e*cos(\u03bd)),\n  0,\n  0,\n  (\u03bc/sqrt(\u03bc*a*(1-e^2)))*e*sin(\u03bd),\n  (\u03bc/sqrt(\u03bc*a*(1-e^2)))*(1+e*cos(\u03bd)),\n  0]\n\nend\n\nfunction r\u03b8h_to_xyz(r\u03b8h_vec::Vector,oe::Vector)\n\n  a,e,i,\u03a9,\u03c9,\u03bd = oe\n  \u03b8 = \u03c9+\u03bd\n  c\u03a9,s\u03a9,ci,si,c\u03b8,s\u03b8 = cos(\u03a9),sin(\u03a9),cos(i),sin(i),cos(\u03b8),sin(\u03b8)\n  DCM = [c\u03a9*c\u03b8-s\u03a9*ci*s\u03b8 -c\u03a9*s\u03b8-s\u03a9*ci*c\u03b8 s\u03a9*si;\n  s\u03a9*c\u03b8+c\u03a9*ci*s\u03b8 -s\u03a9*s\u03b8+c\u03a9*ci*c\u03b8 -c\u03a9*si;\n  si*s\u03b8 si*c\u03b8 ci]\n  DCM = kron(Matrix(I,2,2),DCM)\n  return DCM*r\u03b8h_vec\n\nend\n\nfunction oe_to_xyz(oe::Vector,\u03bc::Real)\n\n  return r\u03b8h_to_xyz(oe_to_r\u03b8h(oe,\u03bc),oe)\n\nend\n\nfunction xyz_to_oe(cart_vec::Vector,\u03bc::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  \u03be = dot(v_xyz,v_xyz)/2 - \u03bc/r #km^2 s^-2\n  a = -\u03bc/(2\u03be) #km\n  e = sqrt(1 + (2h^2*\u03be)/\u03bc^2)\n  e_xyz = cross(v_xyz,h_xyz)/\u03bc - r_xyz/r\n  i = acos(h_xyz[3]/h) #rad\n  n_xyz = cross([0,0,1],h_xyz)\n  \u03a9 = acos(dot(n_xyz,[1,0,0])/norm(n_xyz))\n  \u03c9 = acos((dot(n_xyz,e_xyz)/(norm(n_xyz)*e)))\n  \u03bd = acos((dot(r_xyz,e_xyz))/(r*norm(e_xyz)))\n  \u03a9 = dot(n_xyz,[0,1,0]) > 0. ? \u03a9 : -\u03a9\n  \u03c9 = dot(e_xyz,[0,0,1]) > 0. ? \u03c9 : -\u03c9\n  \u03bd = dot(r_xyz,v_xyz) > 0. ? \u03bd : -\u03bd\n  return [a,e,i,\u03a9,\u03c9,\u03bd]\n\nend\n\nfunction total_manuever(r1::Float64, \n                        r2::Float64,\n                        i1::Float64, \n                        i2::Float64, \n                        i3::Float64, \n                        i4::Float64, \n                        \u03bc::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.], \u03bc)[4:6]\n    v1_post = oe_to_xyz([a2, e2, i2, 0., 0., 0.], \u03bc)[4:6]\n    v2_pre = oe_to_xyz([a2, e2, i2, 0., 0., \u03c0], \u03bc)[4:6]\n    v2_post = oe_to_xyz([a2, e2, i3, 0., 0., \u03c0], \u03bc)[4:6]\n    v3_pre = oe_to_xyz([a2, e2, i3, 0., 0., 0.], \u03bc)[4:6]\n    v3_post = oe_to_xyz([a1, e1, i4, 0., 0., 0.], \u03bc)[4:6]\n    \u0394v1 = norm(v1_post-v1_pre)\n    \u0394v2 = norm(v2_post-v2_pre)\n    \u0394v3 = norm(v3_post-v3_pre)\n    return \u0394v1 + \u0394v2 + \u0394v3\n  end\nend\n\nfunction plot_maneuver(r1::Float64, r2::Float64, \u0394_i::Float64,  \u03bc::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], \u0394_i-node3_inc[j], \u0394_i, \u03bc) \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=\"\u0394V\", contours=attr(size=0.2),\n                 colorbar=attr(title=attr(text=\"\u0394V (km/s)\")))\n  if lim < \u0394_i\n    layout = Layout(\n      ;title=\"Total \u0394V vs. \u0394i\u2081 and \u0394i\u2083 for a 90\u00b0 Bi-Elliptic Transfer (zoomed)\",\n      width=920,\n      height=920,\n      xaxis=attr(title=attr(text=\"\u0394i\u2081 (radians)\")),\n      yaxis=attr(title=attr(text=\"\u0394i\u2083 (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 \u0394V vs. \u0394i\u2081 and \u0394i\u2083 for a 90\u00b0 Bi-Elliptic Transfer\",\n      width=920,\n      height=920,\n      xaxis=attr(title=attr(text=\"\u0394i\u2081 (radians)\")),\n      yaxis=attr(title=attr(text=\"\u0394i\u2083 (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/\u03c0*angles[1], \"\u00b0, \", 180/\u03c0*angles[2], \"\u00b0\")\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, \u0394y, 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- \u0394y: 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, \u0394y, 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 \u0394y==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 = -\u0394y^2\n    D = - (s2-s1)^2/4\n    return B*x + branch * sqrt(-D*x.^2-C) + yoff\nend\n\n\"\"\"\n    hyperbola01(x, \u0394y, xoff=0.0, yoff=0.0)\n\nA hyperbola with asymptotes y=0 for x<0 and y=x for x>0, and\nabcissa \u0394y.  Its origin can be moved with xoff and yoff.\n\"\"\"\nfunction hyperbola01(x, \u0394y, xoff=0.0, yoff=0.0)\n    x = x-xoff\n    B = 1/2\n    C = -\u0394y^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 \u2208 Interval(0.0,1.0),\n           x \u2208 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) \u2248 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\u2013585, 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 \u21a6 0 if x \u2a7e 0 and sum(x) = a, +\u221e 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 \u2248 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'\u03c3XA + C = X\n\nwhere `\u03c3` is the forward shift operator `\u03c3X(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 \u2248 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 = \u03c3X\n\nwhere `\u03c3` is the forward shift operator `\u03c3X(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 \u2248 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\u00d7n\u00d7pa` and `n\u00d7n\u00d7pc` 3-dimensional \narrays `A` and `C`, respectively, and `X` results as a `n\u00d7n\u00d7p` 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'\u03c3XA - 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'\u03c3XA + C = X, if adj = true,\n\nor \n\n      A*X*A' + C =  \u03c3X, if adj = false, \n\nwhere `\u03c3` is the forward shift operator `\u03c3X(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": "#=\nGiven a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it.\n\nFor example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars.\n=#\n\nusing Test\ninclude(\"Solutions/problem47_find_maximum_profit.jl\")\n\n@test maximumprofit([9, 11, 8, 5, 7, 10]) == 5\n", "meta": {"hexsha": "550e2ab8b59bd9ab11bfdeb1800972f5ed0b81e3", "size": 495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tests/problem47_find_maximum_profit_test.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": "Tests/problem47_find_maximum_profit_test.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": "Tests/problem47_find_maximum_profit_test.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": 45.0, "max_line_length": 241, "alphanum_fraction": 0.7515151515, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8539127529517044, "lm_q1q2_score": 0.773636257334806}}
{"text": "\nmodule BS\n\nusing ..Distributions\nimport ..Roots\n\n#\n# types\n#\n\nstruct D\u2081Parts{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\u2081Parts(s, k, t, \u03c3) = D\u2081Parts(log(s/k) + (\u03c3^2/2)*t, \u03c3*sqrt(t))\n\n@inline d\u2081(parts::D\u2081Parts) = parts.numerator / parts.denominator\n@inline d\u2082(parts::D\u2081Parts) = d\u2081(parts) - parts.denominator\n\n@inline d\u2081(s, k, t, \u03c3) = d\u2081(D\u2081Parts(s, k, t, \u03c3))\n@inline d\u2082(s, k, t, \u03c3) = d\u2082(D\u2081Parts(s, k, t, \u03c3))\n\n@inline function bscall(s, k, t, \u03c3)\n    parts = D\u2081Parts(s, k, t, \u03c3)\n    return s*N(d\u2081(parts)) - k*N(d\u2082(parts))\nend\n\n@inline function bsput(s, k, t, \u03c3)\n    parts = D\u2081Parts(s, k, t, \u03c3)\n    return k*N(-d\u2082(parts)) - s*N(-d\u2081(parts))\nend\n\n@inline price(::EuropeanCall, s, k, t, \u03c3) = bscall(s, k, t, \u03c3)\n@inline price(::EuropeanPut, s, k, t, \u03c3) = bsput(s, k, t, \u03c3)\n\nfunction impvol(opt::BSOption, observed_price, s, k, t, interval::Tuple=infer_impvol_interval(opt, observed_price, s, k, t))\n    f(\u03c3) = observed_price - price(opt, s, k, t, \u03c3)\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, \u03c3) = N(d\u2081(s, k, t, \u03c3))\n@inline delta(::EuropeanPut, s, k, t, \u03c3) = N(d\u2081(s, k, t, \u03c3)) - 1\n\n@inline function theta(::EuropeanCall, s, k, t, r, \u03c3)\n    parts = D\u2081Parts(s, k, t, \u03c3)\n    return -(s * pdf(Normal(), d\u2081(parts)) * \u03c3) / ( 2*sqrt(t) ) - r*k*N(d\u2082(parts))\nend\n\n@inline function theta(::EuropeanPut, s, k, t, r, \u03c3)\n    parts = D\u2081Parts(s, k, t, \u03c3)\n    return -(s * pdf(Normal(), d\u2081(parts)) * \u03c3) / ( 2*sqrt(t) ) + r*k*N(-d\u2082(parts))\nend\n\n@inline function gamma(s, k, t, \u03c3)\n    parts = D\u2081Parts(s, k, t, \u03c3)\n    return pdf(Normal(), d\u2081(parts)) / (s * parts.denominator)\nend\n@inline gamma(::BSOption, s, k, t, \u03c3) = gamma(s, k, t, \u03c3)\n\n\n@inline vega(s, k, t, \u03c3) = s*sqrt(t)*pdf(Normal(), d\u2081(s, k, t, \u03c3))\n@inline vega(::BSOption, s, k, t, \u03c3) = vega(s, k, t, \u03c3)\n\n@inline rho(::EuropeanCall, s, k, t, \u03c3) = k*t*N(d\u2082(s, k, t, \u03c3))\n@inline rho(::EuropeanPut, s, k, t, \u03c3) = -k*t*N(-d\u2082(s, k, t, \u03c3))\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": "#Test start to finish\n\nusing SimpleNeuralNet\nusing LinearAlgebra #for norm()\nusing Printf\n\n#Build the neural net\nnNeurons = [4; 5; 2]; #number of neurons by layer\nnn = neuralNet(nNeurons);\n\n#Define some important functions\nSimpleNeuralNet.nnAct(z) = sigmoid.(z); #activation function (assume the same everywhere)\nSimpleNeuralNet.nnDAct(z) = dsigmoid.(z); #derivative of activation function (assume the same everywhere)\nSimpleNeuralNet.nnCost(datay,y) = 0.5*norm(y-datay,2)^2;\nSimpleNeuralNet.nnDCost(datay,y) = y - datay;\n\n#Initialize the weights and biases to random values\nnn.w = rand(length(nn.w));\nnn.b = rand(length(nn.b));\n\n#Define the training parameters\nlr=1.0;      #learning rate\nepochs=1000; #epochs\n\n#Define the dataset\nnData = 10;\ndatax = rand(nn.nNeurons[1],nData);   #draw input dataset at random\ndatay = rand(nn.nNeurons[end],nData); #draw output dataset at random\n\n#Compute the initial costs\nc0 = nnComputeCosts(nn,datax,datay;print=false);\n\n#Train\nnnTrain(nn,datax,datay,epochs,lr;verbose=true);\n\n#Compute the final costs\ncf = nnComputeCosts(nn,datax,datay;print=false);\n\n#Print a comparison of initial/final costs\nfor d=1:length(cf)\n    @printf(\"dataset %3d: initial cost=%10.8f final cost=%10.8f\\n\",d,c0[d],cf[d]);\nend\n", "meta": {"hexsha": "720501cd2cd467ad9a86639ea2d0060444b93be3", "size": 1239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/simple.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": "examples/simple.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": "examples/simple.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": 28.8139534884, "max_line_length": 105, "alphanum_fraction": 0.7425343019, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537142, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7735881780543098}}
{"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\u03b3(h1,h3) = return (h1) / (h1 - h3);\n\n\u0394h = 0.1;\n\nh1 = [18.1 \u00b1 \u0394h, 16.0 \u00b1 \u0394h, 17.6 \u00b1 \u0394h];\nh3 = [5.7, 4,5.1];\n\n\u0263s = [\u03b3(h1[1],h3[1]), \u03b3(h1[2],h3[2]), \u03b3(h1[3],h3[3])];\ndeviation(\u0263s);\n\nA(d) = return \u03c0 * (d^2 / 4);\n# \u0394A = 0.00001;\n\nP0 = 691 * 133.322 \u00b1 0.01; # \u0394P = 0.01;\ng = 9.81;\n\nd = 0.016 \u00b1 0.001; # \u0394d = 0.001;\nm = 0.0167 \u00b1 0.0001; # \u0394m = 0.0001;\nV = 0.0104  \u00b1 0.0001; # \u0394V = 0.0001;\nP = (m * g)/A(d) + P0;\nT = 1.2  \u00b1 0.01; # \u0394T = 0.01;\n\n\ud835\udec4 = 4 * \u03c0^2 * ((m * V)/(P * A(d)^2 * T^2));\n#x, \u0394x = m * V, \u0394m * V + \u0394V * m;\n#y, \u0394y = P*A(d)^2 * T^2, 2*T*\u0394T*(P*A(d)^2)  +  (\u0394P * A(d)^2 + 2 * A(d) * \u0394A * P);\n#\u0394\ud835\udec4 = 4 * \u03c0^2 * (\u0394x * y + \u0394y * x) / (y^2);\n\n\n@printf(\"\ud835\udec4 = %.6f \u00b1 %.6f\", \ud835\udec4.val, \ud835\udec4.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(\u03d5) = laplacianunwrap!(copy(\u03d5))\nfunction laplacianunwrap!(\u03d5::AbstractArray)\n    FFTW.set_num_threads(Threads.nthreads())\n    \u03d5 .+= 2\u03c0 .* k(\u03d5)\nend\n\n# Schofield and Zhu 2003, https://doi.org/10.1364/OL.28.001194\nk(\u03d5w) = 1 / 2\u03c0 .* \u2207\u207b\u00b2(\u2207\u00b2_nw(\u03d5w) - \u2207\u00b2(\u03d5w))  # (1)\n\n\u2207\u00b2(x) = -(2\u03c0)^ndims(x) / length(x) .* idct(pqterm(size(x)) .* dct(x))  # (2)\n\n\u2207\u207b\u00b2(x) = -length(x) / (2\u03c0)^ndims(x) .* idct(dct(x) ./ pqterm(size(x)))  # (3)\n\n\u2207\u00b2_nw(\u03d5w) = cos.(\u03d5w) .* \u2207\u00b2(sin.(\u03d5w)) .- sin.(\u03d5w) .* \u2207\u00b2(cos.(\u03d5w))  # (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(\u03d5::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": "using ChebyshevQuantum\nusing Test\n\ntol_val = 1e-11\n\n\n@testset \"test C interp\" begin\n\n    function f(x)\n        return exp(-0.2*sin(3*x))\n    end\n\n    c = ChebyshevQuantum.Chebyshev.make_Cheb(f , a=2, b = 3)\n\n    @test isapprox(c(2.3), f(2.3), atol=tol_val)\n\n    function f2(x)\n        if x < 0.1\n            return exp(-0.2*sin(3*x))\n        else\n            return 1+x^2\n        end\n    end\n\n    c = ChebyshevQuantum.Chebyshev.make_Cheb(f2 , a=-1, b = 1)\n\n    x=0.0\n    @test isapprox(c(x), f2(x), atol=tol_val)\n    x=0.2\n    @test isapprox(c(x), f2(x), atol=tol_val)\n    \n\n\nend\n\n", "meta": {"hexsha": "727da0ffff5dffaaea84b0a283f4d5a5ee090d51", "size": 581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_C_interp.jl", "max_stars_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_stars_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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": "test/test_C_interp.jl", "max_issues_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_issues_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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": "test/test_C_interp.jl", "max_forks_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_forks_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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.1388888889, "max_line_length": 62, "alphanum_fraction": 0.5490533563, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7735071025325774}}
{"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 \u2208 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": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing Random\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\nfunction infection_rate(u,p,t)\n    (S,I,R) = u\n    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    \u03b2*c*I/N*S\nend\nfunction infection!(integrator)\n  integrator.u[1] -= 1\n  integrator.u[2] += 1\nend\ninfection_jump = ConstantRateJump(infection_rate,infection!);\n\n\nfunction recovery_rate(u,p,t)\n    (S,I,R) = u\n    (\u03b2,c,\u03b3) = p\n    \u03b3*I\nend\nfunction recovery!(integrator)\n  integrator.u[2] -= 1\n  integrator.u[3] += 1\nend\nrecovery_jump = ConstantRateJump(recovery_rate,recovery!);\n\n\ntmax = 40.0\ntspan = (0.0,tmax);\n\n\n\u03b4t = 0.1\nt = 0:\u03b4t:tmax;\n\n\nu0 = [990,10,0]; # S,I,R\n\n\np = [0.05,10.0,0.25]; # \u03b2,c,\u03b3\n\n\nRandom.seed!(1234);\n\n\nprob = DiscreteProblem(u0,tspan,p)\n\n\nprob_jump = JumpProblem(prob,Direct(),infection_jump,recovery_jump)\n\n\nsol_jump = solve(prob_jump,SSAStepper());\n\n\nout_jump = sol_jump(t);\n\n\ndf_jump = DataFrame(out_jump')\ndf_jump[!,:t] = out_jump.t;\n\n\n@df df_jump plot(:t,\n    [:x1 :x2 :x3],\n    label=[\"S\" \"I\" \"R\"],\n    xlabel=\"Time\",\n    ylabel=\"Number\")\n\n\n@benchmark solve(prob_jump,FunctionMap())\n\n\ninclude(joinpath(@__DIR__,\"tutorials\",\"appendix.jl\"))\nappendix()\n\n", "meta": {"hexsha": "3ac4794a6ca1b02364aa98f5f67e03a3ad97f2e5", "size": 1171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/jump_process/jump_process.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/jump_process/jump_process.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/jump_process/jump_process.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": 14.4567901235, "max_line_length": 67, "alphanum_fraction": 0.6609735269, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.773447534246107}}
{"text": "# All square roots are periodic when written as continued fractions and can be\n# written in the form:\n#\n# \u221aN = a0 + 1 / (a1 + 1 / (a2 + 1 / (a3 + ...)))\n#\n# For example, let us consider \u221a23:\n# \u221a23 = 4 + \u221a23 \u2212 4 = 4 + 1 / (1 / (\u221a23 \u2212 4)) = 4 + 1 / (1 + (\u221a23 \u2212 3) / 7)\n#\n# If we continue we would get the following expansion:\n# \u221a23 = 4 + 1 / (1 + 1 / (3 + 1 / (1 + 1 / (8 + ...))))\n#\n# The process can be summarised as follows:\n#\n# a0 = 4, 1 / (23\u221a - 4) = (\u221a23 + 4) / 7 = 1 + (\u221a23 - 3) / 7\n# a1 = 1, 7 / (23\u221a - 3) = 7 * (23\u221a+3)14 = 3 + (\u221a23 - 3) / 2\n# a2 = 3, 2 / (23\u221a - 3) = 2 * (23\u221a+3)14 = 1 + (\u221a23 - 4) / 7\n# a3 = 1, 7 / (23\u221a - 4) = 7 * (23\u221a+4)7 = 8 + \u221a23 - 4\n# a4 = 8, 1 / (23\u221a - 4) = (\u221a23 + 4) / 7 = 1 + (\u221a23 - 3) / 7\n# a5 = 1, 7 / (23\u221a - 3) = 7 * (\u221a23 + 3) / 14 = 3 + (\u221a23 - 3) / 2\n# a6 = 3, 2 / (23\u221a - 3) = 2 * (\u221a23 + 3) / 14 = 1 + (\u221a23 - 4) / 7\n# a7 = 1, 7 / (23\u221a - 4) = 7 * (\u221a23 + 4) / 7 = 8 + \u221a23 - 4\n# \n# It can be seen that the sequence is repeating. For conciseness, we use the\n# notation \u221a23 = [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# \u221a2 = [1;(2)], period=1\n# \u221a3 = [1;(1,2)], period=2\n# \u221a5 = [2;(4)], period=1\n# \u221a6 = [2;(2,4)], period=2\n# \u221a7 = [2;(1,1,1,4)], period=4\n# \u221a8 = [2;(1,4)], period=2\n# \u221a10 = [3;(6)], period=1\n# \u221a11 = [3;(3,6)], period=2\n# \u221a12 = [3;(2,6)], period=2\n# \u221a13 = [3;(1,1,1,1,6)], period=5\n#\n# Exactly four continued fractions, for N \u2264 13, have an odd period.\n#\n# How many continued fractions for N \u2264 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                            \u03b1_t=3e-5, Niter=1000,\n                            verbose=false )\n  #\n  Npoints = LF.Nx * LF.Ny * LF.Nz\n  \u0394V = 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  \u03b2 = 0\n  \u03b1 = 0\n  for iter = 1:Niter\n    g = calc_grad( LF, Vpot, v )\n    #\n    if iter != 1\n      \u03b2 = trace( g' * g)/trace( g_old'*g_old )\n      #\u03b2 = trace( (g-g_old)'*g ) / trace( g_old'*g_old )\n      #\u03b2 = trace( (g-g_old)'*g )/ trace( (g-g_old)'*d )\n    end\n    d = -g + \u03b2*d_old\n    #\n    # compute gradient at trial step\n    #\n    v2 = orthonormalize(LF, v + \u03b1_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      \u03b1 = abs( \u03b1_t * trace( g'*d )/denum )\n    else\n      \u03b1 = 0.0\n    end\n    v = v + \u03b1*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, \u03c4)\n\nReturns the value of the Legendre polynomial of degree `n` at `\u03c4`.\n(Recursive function used in `../test`).\n\"\"\"\nfunction P(n::Integer, \u03c4::T) where T <: AbstractFloat\n    if n == 0\n        return one(T)\n    elseif n == 1\n        return \u03c4\n    else\n        return ( (2n-1) * \u03c4 * P(n-1, \u03c4) - (n-1) * P(n-2, \u03c4) ) / n\n    end\nend\n\n\"\"\"\n    legendre_polys!(P, \u03c4)\n\nIf `\u03c4` is a scalar, then `P` is a vector with `P[n+1]` equal to the value \nof the Legendre polynomial of degree `n` at `\u03c4`.\n\nIf `\u03c4` 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 `\u03c4[j]`.\n\"\"\"\nfunction legendre_polys!(P::AbstractVector{T}, \u03c4::T) where T <: AbstractFloat\n    I = length(P)\n    if I \u2265 1\n        P[1] = one(T)\n    end\n    if I \u2265 2\n        P[2] = \u03c4\n    end\n    for j = 1:I, i = 1:I-2\n        P[i+2] = ((2i+1) * \u03c4 * P[i+1] - i * P[i] ) / (i+1)\n    end\nend\n\nfunction legendre_polys!(P::AbstractMatrix{T}, \u03c4::AbstractVector{T}\n                        ) where T <: AbstractFloat\n    I = size(P, 1)\n    J = size(P, 2)\n    @argcheck length(\u03c4) == J\n    if I \u2265 1\n        for j = 1:J\n            P[1,j] = one(T)\n        end\n    end\n    if I \u2265 2\n        for j = 1:J\n            P[2,j] = \u03c4[j]\n        end\n    end\n    for j = 1:J, i = 1:I-2\n        P[i+2,j] = ((2i+1) * \u03c4[j] * P[i+1,j] - i * P[i,j] ) / (i+1)\n    end\nend\n\n\"\"\"\n    dP(n, \u03c4)\n\nReturns the value of the derivative of the Legendre polynomial of degree `n` \nat `\u03c4`.  (Recursive function used in `../test`).\n\"\"\"\nfunction dP(n::Integer, \u03c4::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) * \u03c4 * dP(n-1, \u03c4) - n * dP(n-2, \u03c4) ) / ( n - 1 )\n    end\nend\n\nfunction deriv_legendre_polys!(dP::AbstractVector{T}, \u03c4::T\n                              ) where T <: AbstractFloat\n    I = length(dP)\n    if I \u2265 1\n        dP[1] = zero(T)\n    end\n    if I \u2265 2\n        dP[2] = one(T)\n    end\n    for i = 1:I-2\n        dP[i+2] = ( (2i+1) * \u03c4 * dP[i+1] - (i+1) * dP[i] ) / i\n    end\nend\n\nfunction deriv_legendre_polys!(dP::AbstractMatrix{T}, \u03c4::AbstractVector{T}\n                               ) where T <: AbstractFloat\n    I = size(dP, 1)\n    J = size(dP, 2)\n    @argcheck length(\u03c4) == J\n    if I \u2265 1\n        for j = 1:J\n            dP[1,j] = zero(T)\n        end\n    end\n    if I \u2265 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) * \u03c4[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    \u03c4 = range(-one(T), stop=one(T), length=ppI) \n    pcwise_t, pcwise_U = evaluate_pcwise_poly!(U, t, \u03c4, store) \n    return pcwise_t, pcwise_U\nend\n\nfunction evaluate_pcwise_poly!(U::Vector{Vector{T}}, t::OffsetVector{T},\n                               \u03c4::AbstractVector{T}, store::Store{T}\n                              ) where T <: AbstractFloat \n    N = length(U)\n    ppI = length(\u03c4)\n    @argcheck ppI \u2264 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, \u03c4, 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                               \u03c4::AbstractVector{T}, store::Store{T}\n                              ) where { T <: AbstractFloat }\n    N = length(U)\n    pts_per_interval = length(\u03c4)\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    \u03a8 = view(store.\u03a8, 1:rmax, 1:pts_per_interval)\n    legendre_polys!(\u03a8, \u03c4)\n    for n = 1:N\n        rn = length(U[n])\n        for m = 1:pts_per_interval\n            pcwise_t[m,n] = ( (1-\u03c4[m])*t[n-1] + (1+\u03c4[m])*t[n] ) / 2\n            s = zero(T)\n            for j = 1:rn\n                s += U[n][j] * \u03a8[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    \u03c4, w\u03c4 = rule(store.legendre[M])\n    \u03a8 = view(store.\u03a8, 1:r, 1:M)\n    legendre_polys!(\u03a8, \u03c4)\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-\u03c4[m])*t[n-1] + (1+\u03c4[m])*t[n] ) / 2\n                s += w\u03c4[m] * u(tnm) * \u03a8[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    \u03c4, w\u03c4 = GaussQuadrature.legendre(T, r, right)\n    return OffsetArray([ -one(0); \u03c4 ], 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 \u2264 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 \u2264 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, \u03c4::AbstractVector{T}) where T <: AbstractFloat\n    N = length(t) - 1\n    pts_per_interval = length(\u03c4)\n    pcwise_t = Matrix{T}(undef, pts_per_interval, N)\n    pcwise_approx_err = similar(pcwise_t)\n    \u03a8 = Matrix{T}(undef, r+1, pts_per_interval)\n    legendre_polys!(\u03a8, \u03c4)\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-\u03c4[m])*t[n-1] + (1+\u03c4[m])*t[n] ) / 2\n            pcwise_approx_err[m,n] = (sign/2) * JU[n-1] * ( \u03a8[r+1,m] - \u03a8[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    \u03c4 = range(-1.0, 1.0, length=pts_per_interval)\n    return dG_error_estimator(JU, t, r, \u03c4)\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": "using MultivariateStats\nusing LinearAlgebra, StatsBase, SparseArrays\nusing Test\nimport Statistics: mean, cov\nimport Random\n\n@testset \"Whitening\" begin\n\n    Random.seed!(34568)\n\n    ## data\n\n    d = 3\n    n = 5\n\n    X = rand(d, n)\n    mval = vec(mean(X, dims=2))\n    C = cov(X, dims=2)\n    C0 = copy(C)\n\n    emax = maximum(eigvals(C))\n    rc = 0.01\n    Cr = C + (emax * rc) * Matrix(I, d, d)\n\n    ## cov_whitening\n\n    cf = cholesky(Hermitian(C, :U))\n    W = cov_whitening(cf)\n    @test istriu(W)\n    @test W'C * W \u2248 Matrix(I, d, d)\n\n    cf = cholesky(Hermitian(C, :L))\n    W = cov_whitening(cf)\n    @test istriu(W)\n    @test W'C * W \u2248 Matrix(I, d, d)\n\n    W = cov_whitening(C)\n    @test C == C0\n    @test istriu(W)\n    @test W'C * W \u2248 Matrix(I, d, d)\n\n    W = cov_whitening(C, 0.0)\n    @test C == C0\n    @test istriu(W)\n    @test W'C * W \u2248 Matrix(I, d, d)\n\n    W = cov_whitening(C, rc)\n    @test istriu(W)\n    @test W'Cr * W \u2248 Matrix(I, d, d)\n\n\n    # Whitening from data\n\n    f = fit(Whitening, X)\n    W = f.W\n    @test isa(f, Whitening{Float64})\n    @test mean(f) === f.mean\n    @test length(f) == d\n    @test size(f) == (d,d)\n    @test istriu(W)\n    @test W'C * W \u2248 Matrix(I, d, d)\n    @test transform(f, X) \u2248 W' * (X .- f.mean)\n\n    f = fit(Whitening, X; regcoef=rc)\n    W = f.W\n    @test W'Cr * W \u2248 Matrix(I, d, d)\n\n    f = fit(Whitening, X; mean=mval)\n    W = f.W\n    @test W'C * W \u2248 Matrix(I, d, d)\n\n    f = fit(Whitening, X; mean=0)\n    Cx = (X * X') / (n - 1)\n    W = f.W\n    @test W'Cx * W \u2248 Matrix(I, d, d)\n\n    # invsqrtm\n\n    R = invsqrtm(C)\n    @test C == C0\n    @test R \u2248 inv(sqrt(C))\n\n    # mixing types\n    X = rand(Float64, 5, 10)\n    XX = convert.(Float32, X)\n\n    M = fit(Whitening, X)\n    MM = fit(Whitening, XX)\n\n    # mixing types should not error\n    transform(M, XX)\n    transform(MM, X)\n\n    # type consistency\n    @test eltype(mean(M)) == Float64\n    @test eltype(mean(MM)) == Float32\n\n    # sparse arrays\n    SX = sprand(Float32, d, n, 0.75)\n    SM = fit(Whitening, SX; mean=sprand(Float32, 3, 0.75))\n    Y = transform(SM, SX)\n    @test eltype(Y) == Float32\n\n    # different dimensions\n    @test_throws DomainError fit(Whitening, X'; dims=3)\n    M1 = fit(Whitening, X'; dims=1)\n    M2 = fit(Whitening, X; dims=2)\n    @test M1.W == M2.W\n    @test_throws DimensionMismatch transform(M1, rand(6,4))\n    @test_throws DimensionMismatch transform(M2, rand(4,6))\n    Y1 = transform(M1,X')\n    Y2 = transform(M2,X)\n    @test Y1' == Y2\n    @test_throws DimensionMismatch transform(M1, rand(7))\n    V1 = transform(M1,X[:,1])\n    V2 = transform(M2,X[:,1])\n    @test V1 == V2\nend\n", "meta": {"hexsha": "fb6209c045c71e88ae5c6815babc0e68737e96f9", "size": 2595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 21.8067226891, "max_line_length": 59, "alphanum_fraction": 0.5518304432, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7734443920159578}}
{"text": "using HigherOrderKernels\nusing GaussQuadrature\nusing Test\n\nimport HigherOrderKernels: density_kernel, density_bandwidth_constant, roughness, firstnzmoment\n\nfor s = 0:20, \u03bd = 2:2:20\n    N = s + div(\u03bd, 2)\n    x, w = legendre(N)\n    @test density_kernel.(PolynomialKernel{s,\u03bd}, x)'*w \u2248 1\nend\n\nfor \u03bd = 2:2:20\n    N = div(\u03bd, 2)\n    k = x -> density_kernel(GaussianKernel{\u03bd}, x)\n    x, w = hermite(N)\n    @test sum(w[i]*k(sqrt(2)*x[i])*exp(x[i]^2) for i=1:N)*sqrt(2) \u2248 1\nend\n\n# table 1\n@test roughness(     UniformKernel{2}) \u2248 1/2\n@test roughness(EpanechnikovKernel{2}) \u2248 3/5\n@test roughness(    BiweightKernel{2}) \u2248 5/7\n@test roughness(   TriweightKernel{2}) \u2248 350/429\n@test roughness(    GaussianKernel{2}) \u2248 1/(2sqrt(pi))\n@test firstnzmoment(     UniformKernel{2}) \u2248 1/3\n@test firstnzmoment(EpanechnikovKernel{2}) \u2248 1/5\n@test firstnzmoment(    BiweightKernel{2}) \u2248 1/7\n@test firstnzmoment(   TriweightKernel{2}) \u2248 1/9\n@test firstnzmoment(    GaussianKernel{2}) \u2248 1\n\n# table 2\n@test roughness(EpanechnikovKernel{4}) \u2248 5/4\n@test roughness(    BiweightKernel{4}) \u2248 805/572\n@test roughness(   TriweightKernel{4}) \u2248 3780/2431\n@test roughness(    GaussianKernel{4}) \u2248 27/(32sqrt(pi))\n@test firstnzmoment(EpanechnikovKernel{4}) \u2248 -1/21\n@test firstnzmoment(    BiweightKernel{4}) \u2248 -1/33\n@test firstnzmoment(   TriweightKernel{4}) \u2248 -3/143\n@test firstnzmoment(    GaussianKernel{4}) \u2248 -3\n\n# table 3\n@test roughness(EpanechnikovKernel{6}) \u2248 1575/832\n@test roughness(    BiweightKernel{6}) \u2248 29295/14144\n@test roughness(   TriweightKernel{6}) \u2248 301455/134368\n@test roughness(    GaussianKernel{6}) \u2248 2265/(2048sqrt(pi))\n@test firstnzmoment(EpanechnikovKernel{6}) \u2248 5/429\n@test firstnzmoment(    BiweightKernel{6}) \u2248 1/143\n@test firstnzmoment(   TriweightKernel{6}) \u2248 1/221\n@test firstnzmoment(    GaussianKernel{6}) \u2248 15\n\n# table 4\n@test round(density_bandwidth_constant(PolynomialKernel{1,2}), digits=2) == 2.34\n@test round(density_bandwidth_constant(PolynomialKernel{1,4}), digits=2) == 3.03\n@test round(density_bandwidth_constant(PolynomialKernel{1,6}), digits=2) == 3.53\n@test round(density_bandwidth_constant(PolynomialKernel{2,2}), digits=2) == 2.78\n@test round(density_bandwidth_constant(PolynomialKernel{2,4}), digits=2) == 3.39\n@test round(density_bandwidth_constant(PolynomialKernel{2,6}), digits=2) == 3.84\n@test round(density_bandwidth_constant(PolynomialKernel{3,2}), digits=2) == 3.15\n@test round(density_bandwidth_constant(PolynomialKernel{3,4}), digits=2) == 3.72\n@test round(density_bandwidth_constant(PolynomialKernel{3,6}), digits=2) == 4.13\n@test round(density_bandwidth_constant(GaussianKernel{2}), digits=2) == 1.06\n@test round(density_bandwidth_constant(GaussianKernel{4}), digits=2) == 1.08\n@test round(density_bandwidth_constant(GaussianKernel{6}), digits=2) == 1.08\n", "meta": {"hexsha": "56273c2d597fbf81dfd15456d82bc98a1c9e6f4e", "size": 2779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Godisemo/HigherOrderKernels.jl", "max_stars_repo_head_hexsha": "5c7c61cebf0ec731285e2fc317c5c6dec81968a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:31:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T08:55:56.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "Godisemo/HigherOrderKernels.jl", "max_issues_repo_head_hexsha": "5c7c61cebf0ec731285e2fc317c5c6dec81968a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-04T16:33:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-12T18:11:44.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "Godisemo/HigherOrderKernels.jl", "max_forks_repo_head_hexsha": "5c7c61cebf0ec731285e2fc317c5c6dec81968a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:32:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:05:49.000Z", "avg_line_length": 42.7538461538, "max_line_length": 95, "alphanum_fraction": 0.7218423893, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7734443907100946}}
{"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    \u03b8 = inner_angle(a, b, t)\n    return im * ((a + b) * exp(\u03b8 * im) + offset * exp(t * im))\nend\n\n@inline stop_t(a::Int, b::Int) = 2 * \u03c0 * (lcm(a, b) \u00f7 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": "# Gaussian mixture model\nstruct GMM{T<:AbstractVector{<:Real}, M<:Normal, S<:InverseGamma, W<:Dirichlet} <: MCMC.Model\n  y::T\n  K::Int\n  mu::M\n  sigmasq::S\n  eta::W\nend\nfunction GMM(y::AbstractVector{<:Real}, K::Int; mu=Normal(0, 1),\n             sigmasq=InverseGamma(3, 2), eta=Dirichlet(K, 1/K))\n  return GMM(y, K, mu, sigmasq, eta)\nend\nfunction MCMC.make_init_state(m::GMM)\n  nobs = length(m.y)\n  eta = rand(m.eta)\n  return (mu=rand(m.mu, m.K), sigmasq=rand(m.sigmasq, m.K),\n          eta=eta, lambda=rand(Categorical(eta), nobs))\nend\nfunction MCMC.update(m::GMM, s::T) where T\n  s = setproperty!!(s, :mu, update_mu(m, s))\n  s = setproperty!!(s, :sigmasq, update_sigmasq(m, s))\n  s = setproperty!!(s, :eta, update_eta(m, s))\n  s = setproperty!!(s, :lambda, update_lambda(m, s))\n\n  return s\nend\nfunction update_mu(m::GMM, s::T) where T\n  m_mu, s_mu = params(m.mu)\n\n  vkernels = zero.(s.mu)\n  mkernels = zero.(s.mu)\n\n  for n in eachindex(m.y)\n    k = s.lambda[n]\n    vkernels[k] += 1\n    mkernels[k] += m.y[n]\n  end\n\n  vnew = 1 ./ (s_mu^-2 .+ vkernels ./ s.sigmasq)\n  mnew = vnew .* (m_mu/(s_mu^2) .+ mkernels ./ s.sigmasq)\n\n  return randn(m.K) .* sqrt.(vnew) + mnew\nend\nfunction update_sigmasq(m::GMM, s::T) where T\n  a, b = params(m.sigmasq)\n  akernel = zero.(s.sigmasq)\n  bkernel = zero.(s.sigmasq)\n\n  for n in eachindex(m.y)\n    k = s.lambda[n]\n    akernel[k] += 1\n    bkernel[k] += (m.y[n] - s.mu[k]) ^ 2\n  end\n\n  anew = a .+ akernel / 2\n  bnew = b .+ bkernel / 2\n  s.sigmasq .= rand.(InverseGamma.(anew, bnew))\n\n  return s.sigmasq\nend\nfunction update_eta(m::GMM, s::T) where T\n  anew = copy(collect(m.eta.alpha))\n  for lam in s.lambda\n    anew[lam] += 1\n  end\n  return rand(Dirichlet(anew))\nend\nfunction update_lambda(m::GMM, s::T) where T\n  logeta = s.eta\n  lambda = [let\n              logmix = normlogpdf.(s.mu, sqrt.(s.sigmasq), yn) + logeta\n              wsample_logprob(logmix)\n            end for yn in m.y]\n  return lambda\nend\n@testset \"GMM\" begin\n  true_model = MixtureModel([Normal(3, .6), Normal(-2, 1)], [.3, .7])\n\n  Random.seed!(0)\n\n  nobs = 1000\n  y = rand(true_model, nobs)\n  model = GMM(y, 2)\n  nsamps = 1000\n  chain, _ = mcmc(model, nsamps, nburn=1000)\n\n  mu = hcat(map(c -> c.mu, chain)...)\n  sigma = hcat(map(c -> sqrt.(c.sigmasq), chain)...)\n  eta = hcat(map(c -> c.eta, chain)...)\n  lambda = hcat(map(c -> c.lambda, chain)...)\n\n  @test size(mu) == (model.K, nsamps)\n  @test size(sigma) == (model.K, nsamps)\n  @test size(eta) == (model.K, nsamps)\n  @test size(lambda) == (nobs, nsamps)\n\n  function match_components(postmean::AbstractVector{<:Real}, truth::AbstractVector{<:Real}, atol)\n    cond1 = abs2(postmean[1] - truth[1]) < atol\n    cond2 = abs2(postmean[2] - truth[2]) < atol\n    cond3 = abs2(postmean[1] - truth[2]) < atol\n    cond4 = abs2(postmean[2] - truth[1]) < atol\n    return (cond1 && cond2) || (cond3 && cond4)\n  end\n  function match_components(postmean, sym::Symbol, atol)\n    truth = [getfield(true_model.components[1], sym),\n             getfield(true_model.components[2], sym)]\n    return match_components(postmean, truth, atol)\n  end\n  mean_mu = vec(mean(mu, dims=2))\n  mean_sigma = vec(mean(sigma, dims=2))\n  mean_eta = vec(mean(eta, dims=2))\n  # println(mean_mu)\n  # println(mean_sigma)\n  # println(mean_eta)\n  @test match_components(mean_mu, :\u03bc, 1e-1)\n  @test match_components(mean_sigma, :\u03c3, 1e-2)\n  @test match_components(mean_eta, true_model.prior.p, 1e-2)\nend\n", "meta": {"hexsha": "43e059a773c05459afa3297a977151ee7fa57c91", "size": 3413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/gmm.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": "test/models/gmm.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": "test/models/gmm.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": 28.6806722689, "max_line_length": 98, "alphanum_fraction": 0.6220334017, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7734443829429767}}
{"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(\u03c6) = -4sin(\u03c6 - \u03c0/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 \ud83d\udd25\ud83d\udd25\ud83d\udd25\ud83d\udd25\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, \u03c0/2, 3\u03c0/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 \u2218 +)(3, 6) # equivalent to sqrt(3 + 6)\n(sqrt \u2218 abs \u2218 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": "\"\"\"\n\n```\ncenterofcoordinates(coor::AbstractVector{T}) where T\n```\n\nComputes the center of coordinates of a vector.\n\n\"\"\"\nfunction centerofcoordinates(coor::AbstractVector{T}) where T\n  cm = zeros(T)\n  n = length(coor)\n  for i in 1:n\n    cm = cm + coor[i]\n  end\n  cm = cm / n\n  return cm\nend\n\n", "meta": {"hexsha": "ae922fd0624a67ff9a46d084cad77b51bc9dacc1", "size": 291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centerofcoordinates.jl", "max_stars_repo_name": "m3g/ComplexMixtures.jl", "max_stars_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-14T02:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T15:56:19.000Z", "max_issues_repo_path": "src/centerofcoordinates.jl", "max_issues_repo_name": "m3g/ComplexMixtures.jl", "max_issues_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-03-18T19:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T13:56:17.000Z", "max_forks_repo_path": "src/centerofcoordinates.jl", "max_forks_repo_name": "m3g/ComplexMixtures.jl", "max_forks_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_forks_repo_licenses": ["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.55, "max_line_length": 61, "alphanum_fraction": 0.6529209622, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7733947335433273}}
{"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) \u2248  testval &&\n        main(unknown_storage=:dense,max_lureuse=0) \u2248 testval &&\n        main(unknown_storage=:sparse,max_lureuse=10) \u2248 testval &&\n        main(unknown_storage=:dense,max_lureuse=10) \u2248 testval &&\n        main(unknown_storage=:sparse,max_lureuse=0, factorization=ILU0Preconditioner()) \u2248 testval &&\n        main(unknown_storage=:dense,max_lureuse=0, factorization=ILU0Preconditioner()) \u2248 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": "using CSV, DataFrames, StatsPlots, StanSample\nusing Distributions, Statistics, Random\n\nProjDir = @__DIR__\n\n# Simulate the data\n\nRandom.seed!(123)\n\nN = 15\nobspairs = ((30.0, 53), (35.0, 45), (40.0, 28), (45.0, 26), (50.0, 25))\n\nppu = []; quantity = []\nfor i in 1:N in \n\tobs = rand(obspairs, 1)\n\tappend!(ppu, [rand(Normal(obs[1][1], 1.0))])\n\tappend!(quantity, [rand(Normal(obs[1][2], 1.0))])\nend\n\ndf = DataFrame()\ndf[!, :ppu] = ppu\ndf[!, :quantity] = quantity\ndf[!, :ppu_l] = log.(ppu)\ndf[!, :quantity_l] = log.(quantity)\n\nCSV.write(joinpath(ProjDir, \"data\", \"data.csv\"), df)\n\nopt_01 = \"\ndata {\n\tint<lower=0> N;\n\tvector[N] q; // Outcome\n\tvector[N] p; // Predictor\n}\nparameters {\n\treal a;\n\treal b;\n\treal<lower=0> sigma;\n}\nmodel {\n\tvector[N] mu;            \t\t// mu is a vector\n\ta ~ cauchy(0.0, 5.0);\t\t\t// intercept positive\n\tb ~ cauchy(0.0, 5.0);\t\t\t// demand drops as price increases\n\tsigma ~ uniform(0, 15);\n\tmu = a + b * (p - mean(p));\n\tq ~ normal(mu, sigma);\n}\n\";\n\nmean_q_l = mean(df[:, :quantity_l])\nmean_p_l = mean(df[:, :ppu_l])\ndata = Dict(\n  :N => size(df, 1),\n  :q => df[:, :quantity_l], # .- mean_q_l,\n  :p => df[:, :ppu_l]\t\t# .- mean_p_l\n)\n\np1 = scatter(df[:, :ppu], df[:, :quantity],\n\txlabel=\"ppu\", ylabel=\"quantity sold\", leg=false)\np2 = scatter(data[:p], data[:q],\n\txlabel=\"log(ppu)\", ylabel=\"log(quantity sold)\", leg=false)\nplot(p1, p2, layout=(2, 1))\nsavefig(joinpath(ProjDir, \"plots\", \"data.png\"))\n\nsm = SampleModel(\"opt_01\", opt_01)\n\nrc = stan_sample(sm, data=data)\n\nif success(rc)\n\tchns = read_samples(sm; output_format=:mcmcchains)\n\tshow(chns)\n\tplot(chns)\n\tsavefig(joinpath(ProjDir, \"plots\", \"chains.png\"))\n\n\tdfs = read_samples(sm; output_format=:dataframe)\n\t\n\tdfsa = DataFrame(chns)\n\t#density(dfsa[:, Symbol(\"mu_pred.1\")], label=\"mu_pred.1\")\n\t#for i in 2:3:N\n\t#\tdensity!(dfsa[:, Symbol(\"mu_pred.$i\")], label=\"mu_pred.$i\")\n\t#end\n\t#savefig(joinpath(ProjDir, \"plots\", \"density.png\"))\n\n\n\tp = 3.4:0.01:4.0\n\tps = collect(p)\n\tp1 = scatter(data[:p], data[:q],\n\t\t#xlims=(3.4, 4.0), ylims=(3.0, 4.0),\n\t\txlabel=\"ppu_l\", ylabel=\"quantity_l sold\", leg=false)\n\ta_mean = mean(dfs[:, :a])\n\tb_mean = mean(dfs[:, :b])\n\tmu_q = a_mean .+ b_mean .* (p .- mean(p))\n\tplot!(p1, p, mu_q)\n\tsavefig(joinpath(ProjDir, \"plots\", \"regression.png\"))\n\n\tprice_points_l = data[:p]\n\tplot(xlabel=\"Price\", ylabel=\"Quantity\", leg=false)\n\tselected_rows = rand(1:size(dfs, 1), 75)\n\tfor row in eachrow(dfs[selected_rows,:])\n\t\tqs = exp.(row[:a] .+ row[:b] .* (ps .- mean(ps)))\n\t\tplot!(exp.(p), qs, color=:gray)\n\tend\n\tqqs = exp.(a_mean .+ b_mean .* (price_points_l .- mean(ps)))\n\tscatter!(exp.(price_points_l), qqs)\n\tsavefig(joinpath(ProjDir, \"plots\", \"sampling.png\"))\n\n\tscatter(dfs[:, :a], dfs[:, :b],\n\t\t#xlims = (-0.1, 1.0), ylims= (-10.0, 10.0), \n\t\txlabel=\"a\", ylabel=\"b\", leg=false)\n\tsavefig(joinpath(ProjDir, \"plots\", \"correlations.png\"))\nend\n", "meta": {"hexsha": "9bc923533c11cf713d57f96a5f98955685899a1c", "size": 2821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "approaches/optimal_pricing_02/optimal_02.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/optimal_pricing_02/optimal_02.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/optimal_pricing_02/optimal_02.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": 25.4144144144, "max_line_length": 71, "alphanum_fraction": 0.6129032258, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7733439123222191}}
{"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\u2080, a, b)\nReturns trigonometric polynomial.\nUse with 2a,-2b and divide by 2m+1 to use with rfft coefficients.\n\"\"\"\nfunction interpolateTrigonometric(a\u2080, a, b)\n\treturn mbUtil.vectorize() do x\n\t\ta\u2080 + 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\u2080, a, b, x) = interpolateTrigonometric(a\u2080, 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\u1d62 = k | f\u1d62) = \u03b8\u1d4f\\\\exp(-\u03b8)/k!\n```\nfor ``k \u2208 N\u2080``, where ``\u03b8 = \\\\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": "let xmin = (-1.0, -1.0, -1.0)\n    xmax = ( 1.0,  1.0,  1.0)\n\n    for n = 0:2:10\n        @test nintegrate((x,y,z)->x^n, xmin, xmax)[1] \u2248 8/(n+1)\n        @test nintegrate((x,y,z)->y^n, xmin, xmax)[1] \u2248 8/(n+1)\n        @test nintegrate((x,y,z)->z^n, xmin, xmax)[1] \u2248 8/(n+1)\n    end\n\n    @test nintegrate((x,y,z)->x^2*y^2, xmin, xmax)[1] \u2248 8/9\n    @test nintegrate((x,y,z)->z^2*y^2, xmin, xmax)[1] \u2248 8/9\n    @test nintegrate((x,y,z)->x^2*z^2, xmin, xmax)[1] \u2248 8/9\n\n    @test nintegrate((x,y,z)->x^2*y^2*z^2, xmin, xmax)[1] \u2248 8/27\n\n    \u025b = eps()\n\n    for n = 1:2:11\n        @test nintegrate((x,y,z)->x^n, xmin, xmax)[1] < \u025b\n    end\n\n    @test nintegrate((x,y,z)->x^2*z^3, xmin, xmax)[1] < \u025b\n    @test nintegrate((x,y,z)->x^3*z^2, xmin, xmax)[1] < \u025b\n\n    @test nintegrate((x,y,z)->x^2*y*z, xmin, xmax)[1] < \u025b\n    @test nintegrate((x,y,z)->x*y^2*z, xmin, xmax)[1] < \u025b\n    @test nintegrate((x,y,z)->x*y*z^2, xmin, xmax)[1] < \u025b\n\nend\n\nlet xmin = (0.0, 0.0, 0.0)\n    xmax = (1.0, 1.0, 1.0)\n\n    for n = 0:11\n        @test nintegrate((x,y,z)->x^n, xmin, xmax)[1] \u2248 1/(n+1)\n        @test nintegrate((x,y,z)->y^n, xmin, xmax)[1] \u2248 1/(n+1)\n        @test nintegrate((x,y,z)->z^n, xmin, xmax)[1] \u2248 1/(n+1)\n    end\n\n    @test nintegrate((x,y,z)->x^2*y^2, xmin, xmax)[1] \u2248 1/9\n    @test nintegrate((x,y,z)->z^2*y^2, xmin, xmax)[1] \u2248 1/9\n    @test nintegrate((x,y,z)->x^2*z^2, xmin, xmax)[1] \u2248 1/9\n\n    @test nintegrate((x,y,z)->x^2*z^3, xmin, xmax)[1] \u2248 1/12\n    @test nintegrate((x,y,z)->x^3*z^2, xmin, xmax)[1] \u2248 1/12\n    @test nintegrate((x,y,z)->x^2*y*z, xmin, xmax)[1] \u2248 1/12\n    @test nintegrate((x,y,z)->x*y^2*z, xmin, xmax)[1] \u2248 1/12\n    @test nintegrate((x,y,z)->x*y*z^2, xmin, xmax)[1] \u2248 1/12\n\n    @test nintegrate((x,y,z)->x^3*y*z, xmin, xmax)[1] \u2248 1/16\n    @test nintegrate((x,y,z)->x*y^3*z, xmin, xmax)[1] \u2248 1/16\n    @test nintegrate((x,y,z)->x*y*z^3, xmin, xmax)[1] \u2248 1/16\n\n    @test nintegrate((x,y,z)->x^2*y^2*z^2, xmin, xmax)[1] \u2248 1/27\n\nend\n\nlet f = (x, y, z) -> x * sin(2y) * cos(3z)\n\n    xmin = (0.0, 0.0, 0.0)\n    xmax = (1.0, 1.0, 1.0)\n\n    (I, E, n, R) = nintegrate(f, xmin, xmax)\n    @test I == nintegrate(f, R)\n    @test length(R) == 1\n\n    W = weightedpoints(R)\n    @test I \u2248 nintegrate(f, W)\n\n    W = weightedpoints(NIntegration.idem, R)\n    @test I \u2248 nintegrate(f, W)\n\n    p = [0.5, 0.5, 0.5]\n    io = IOBuffer()\n    show(io, R)\n    @test String(take!(io)) == \"1 subregion\"\n    show(io, R[1])\n    @test String(take!(io)) == string(\"(\", p, \", \", p, \")\")\n\nend\n", "meta": {"hexsha": "1774513da827b5065f4e312a69cbd25a496ce50c", "size": 2467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/integration.jl", "max_stars_repo_name": "pabloferz/NIntegration.jl", "max_stars_repo_head_hexsha": "cf4cb5244dd8f0c4d23dd9844d454419a6d99959", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-03-27T09:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T14:32:56.000Z", "max_issues_repo_path": "test/integration.jl", "max_issues_repo_name": "pabloferz/NIntegration.jl", "max_issues_repo_head_hexsha": "cf4cb5244dd8f0c4d23dd9844d454419a6d99959", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-27T01:57:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-14T20:17:33.000Z", "max_forks_repo_path": "test/integration.jl", "max_forks_repo_name": "pabloferz/NIntegration.jl", "max_forks_repo_head_hexsha": "cf4cb5244dd8f0c4d23dd9844d454419a6d99959", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-28T14:04:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T05:25:39.000Z", "avg_line_length": 30.4567901235, "max_line_length": 64, "alphanum_fraction": 0.5030401297, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7732629851461388}}
{"text": "using VoronoiCells\nimport VoronoiCells: LEFT, RIGHT, LOWER, UPPER\nusing VoronoiDelaunay\nusing Base.Test\n\n# Area of square\nS = [Point2D(LEFT,LOWER) ; Point2D(RIGHT,LOWER) ; Point2D(RIGHT,UPPER) ; Point2D(LEFT,UPPER)]\n@test_approx_eq polyarea(S) 1.0\n\n# Area of triangle\nT1 = [Point2D(LEFT,LOWER) ; Point2D(RIGHT,LOWER) ; 0.5*(Point2D(RIGHT,UPPER) + Point2D(LEFT,UPPER))]\n@test_approx_eq polyarea(T1) 0.5\n\nT2 = [Point2D(LEFT,LOWER) ; Point2D(LEFT+0.5,LOWER) ;\nPoint2D(LEFT,LOWER+0.5)]\n@test_approx_eq polyarea(T2) 0.5^3\n", "meta": {"hexsha": "438358df247296b299e2234f533e77a29d5dbccd", "size": 517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Polyarea.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": "test/Polyarea.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": "test/Polyarea.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": 30.4117647059, "max_line_length": 100, "alphanum_fraction": 0.7388781431, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7732629835011053}}
{"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 \u2248 y`. Here, we use the approach proposed by\nIsmail and Roe (2009).\nSet \u03be = y / x. Then, we have\n\n    (y - x) / log(y / x) = (x + y) / log(\u03be) * (\u03be - 1) / (\u03be + 1)\n\nSet f = (\u03be - 1) / (\u03be + 1) = (y - x) / (x + y). Then, we use the expansion\n\n    log(\u03be) = 2 * f * (1 + f^2 / 3 + f^4 / 5 + f^6 / 7) + O(\u03be^9)\n\nInserting the first few terms of this expansion yields\n\n    (y - x) / log(\u03be) \u2248 (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 \u03b5 = 1.0e-4, we use the following algorithm.\n\n    if f^2 < \u03b5\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] \u22c5 \u22c5 \u22c5 \u22c5 ...;\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\u1d40 * P * x = w\u1d40 * \u03d5(x)\nwhere \u03d5(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    ## \u03d5(x) = (I_m \u2297 x) x;\n    ## Px = (I_m \u2297 x\u1d40) w\n    ## where P \u2208 \u211d^{m\u00d7n}, w \u2208 \u211d^{nm\u00d71}, I_m: m\u00d7m identity matrix, \u2297: Kronecker product\n    # n = length(x)\n    # kron(Matrix(I, n, n), x) * x\n    ## for dimension reduction\n    n = length(x)\n    \u03d5 = zeros(Int(n*(n+1)/2))\n    idx = 1\n    for i in 1:n\n        for j in i:n\n            \u03d5[idx] = x[j] * x[i]\n            idx += 1\n        end\n    end\n    \u03d5\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\u0303 = (xy) -> f(xy[1], xy[2])\nF = f\u0303.(p)\nF\u030c = transform(S, F)  # 105 Chebyshev^2 coefficients ordered by polynomial degree\nf\u030c = Fun(S, F\u030c)\nf\u030c(0.1,0.2) \u2248 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\u030c = 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\u030c(0.1,0.2,0.3) \u2248 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\u03c7(\u03a9::Float64, \u03b1::Float64, v::Float64, w::Float64)\n\n    Calculate the memory function \u03c7(\u03a9) of the polaron at finite temperatures (equation (35a) in FHIP 1962) for a given frequency \u03a9. v and w are the variational polaron parameters that minimise the free energy, for the supplied \u03b1 Frohlich coupling.\n\"\"\"\nfunction \u03c7(\u03a9, \u03b2, \u03b1, 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(\u03b2 * v / 2) + x^2 / \u03b2 - 1im * (R * sin(v * x) + x))\n\n    # FHIP1962, page 1009, eqn (36).\n    S(x) = 2 * \u03b1 / (3 * \u221a\u03c0) * (exp(1im * x) + 2 * cos(x) / (exp(\u03b2) - 1)) / (D(x))^(3 / 2)\n\n    # FHIP1962, page 1009, eqn (35a).\n    integrand(x) = (1 - exp(-1im * \u03a9 * x)) * imag(S(x))\n    QuadGK.quadgk(x -> integrand(x), 0.0, Inf)[1]\nend\n\n\"\"\"\n\u03c7(\u03a9::Float64, \u03b1::Float64, v::Float64, w::Float64)\n\n    Calculate the memory function \u03c7(\u03a9) of the polaron at zero-temperatures (equation (35a) in FHIP 1962) for a given frequency \u03a9. v and w are the variational polaron parameters that minimise the free energy, for the supplied \u03b1 Frohlich coupling.\n\"\"\"\nfunction \u03c7(\u03a9, \u03b1, 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 \u03b2 \u2192 \u221e.\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 \u03b2 \u2192 \u221e.\n    S(x) = 2 * \u03b1 / (3 * \u221a\u03c0) * exp(1im * x) / (D(x))^(3 / 2)\n\n    # FHIP1962, page 1009, eqn (35a). Set upper limit < \u221e but very large so cos argument finite.\n    integrand(x) = (1 - exp(-1im * \u03a9 * x)) * imag(S(x))\n    QuadGK.quadgk(x -> integrand(x), 0.0, 1e200)[1]\nend\n\n\"\"\"\n\u03c7_dc(\u03b2::Float64, \u03b1::Float64, v::Float64, w::Float64)\n\n    Calculate the memory function lim(\u03a9 \u2192 0){\u03c7(\u03a9) / \u03a9} 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 \u03b1 Frohlich coupling.\n\"\"\"\nfunction \u03c7_dc(\u03b2, \u03b1, 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(\u03b2 * v / 2) + x^2 / \u03b2 - 1im * (R * sin(v * x) + x))\n\n    # FHIP1962, page 1009, eqn (36).\n    S(x) = 2 * \u03b1 / (3 * \u221a\u03c0) * (exp(1im * x) + 2 * cos(x) / (exp(\u03b2) - 1)) / (D(x))^(3 / 2)\n\n    # Set frequency small enough to mimic \u03a9 = 0 without generating numerical instabilities in integral.\n    \u03a9 = 1e-200\n\n    # FHIP1962, page 1009, eqn (35a). Readily divided by \u03a9 to get sinc function in integrand rather than sine which would give 0 all the time.\n    integrand(x) = (1 - exp(-1im * \u03a9 * x)) * imag(S(x)) / \u03a9\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": "using FastTransforms, Test\n\n@testset \"Padua transform and its inverse\" begin\n    n=200\n    N=div((n+1)*(n+2),2)\n    v=rand(N)  #Length of v is the no. of Padua points\n    Pl=plan_paduatransform!(v)\n    IPl=plan_ipaduatransform!(v)\n    @test Pl*(IPl*copy(v)) \u2248 v\n    @test IPl*(Pl*copy(v)) \u2248 v\n    @test Pl*copy(v) \u2248 paduatransform(v)\n    @test IPl*copy(v) \u2248 ipaduatransform(v)\n\n    # check that the return vector is NOT reused\n    Pl=plan_paduatransform!(v)\n    x=Pl*v\n    y=Pl*rand(N)\n    @test x \u2260 y\n\n    IPl=plan_ipaduatransform!(v)\n    x=IPl*v\n    y=IPl*rand(N)\n    @test x \u2260 y\n\n    # Accuracy of 2d function interpolation at a point\n\n    \"\"\"\n    Interpolates a 2d function at a given point using 2d Chebyshev series.\n    \"\"\"\n    function paduaeval(f::Function,x::AbstractFloat,y::AbstractFloat,m::Integer,lex)\n        T=promote_type(typeof(x),typeof(y))\n        M=div((m+1)*(m+2),2)\n        pvals=Vector{T}(undef,M)\n        p=paduapoints(T,m)\n        map!(f,pvals,p[:,1],p[:,2])\n        coeffs=paduatransform(pvals,lex)\n        plan=plan_ipaduatransform!(pvals,lex)\n        cfs_mat=FastTransforms.trianglecfsmat(plan,coeffs)\n        f_x=sum([cfs_mat[k,j]*cos((j-1)*acos(x))*cos((k-1)*acos(y)) for k=1:m+1, j=1:m+1])\n        return f_x\n    end\n    f_xy = (x,y) ->x^2*y+x^3\n    g_xy = (x,y) ->cos(exp(2*x+y))*sin(y)\n    x=0.1;y=0.2\n    m=130\n    l=80\n    f_m=paduaeval(f_xy,x,y,m,Val{true})\n    g_l=paduaeval(g_xy,x,y,l,Val{true})\n    @test f_xy(x,y) \u2248 f_m\n    @test g_xy(x,y) \u2248 g_l\n\n    f_m=paduaeval(f_xy,x,y,m,Val{false})\n    g_l=paduaeval(g_xy,x,y,l,Val{false})\n    @test f_xy(x,y) \u2248 f_m\n    @test g_xy(x,y) \u2248 g_l\nend\n", "meta": {"hexsha": "cc46d462307a7e84c529bc87145b52f2a2bd9835", "size": 1625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/paduatests.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": "test/paduatests.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": "test/paduatests.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.5087719298, "max_line_length": 90, "alphanum_fraction": 0.5975384615, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7732620036855061}}
{"text": "@testset \"Certification\" begin\n    @testset \"Simple 1: Input = Vector{Expression}\" begin\n        @var x y\n        # define the polynomials\n        f\u2081 = (x^4 + y^4 - 1) * (x^2 + y^2 - 2) + x^5 * y\n        f\u2082 = x^2 + 2x * y^2 - 2 * y^2 - 1 / 2\n        F = [f\u2081, f\u2082]\n        result = solve(F)\n\n        # Input: System(F)\n        cert = certify(System(F), result)\n        @test nnonsingular(result) == 18\n        @test ncertified(cert) == 18\n        @test ndistinct_certified(cert) == 18\n        @test nreal_certified(cert) == 4\n        @test ncomplex_certified(cert) == 14\n        @test ndistinct_real_certified(cert) == 4\n        @test ndistinct_complex_certified(cert) == 14\n        save(\"tmp_cert.txt\", cert)\n        @test !isempty(read(\"tmp_cert.txt\", String))\n\n        # Input: F\n        cert = certify(F, result)\n        @test nnonsingular(result) == 18\n        @test ncertified(cert) == 18\n        @test ndistinct_certified(cert) == 18\n        @test nreal_certified(cert) == 4\n        @test ndistinct_real_certified(cert) == 4\n\n        # Control Display\n        cert = certify(F, result, show_progress = false)\n\n        # Double solutions\n        S = solutions(result)\n        cert = certify(F, [S; S])\n        @test ncertified(cert) == 36\n        @test ndistinct_certified(cert) == 18\n        @test nreal_certified(cert) == 8\n        @test ndistinct_real_certified(cert) == 4\n    end\n\n    @testset \"Simple 2: Input = Vector{MP.Polynomial}\" begin\n        @polyvar x y\n        # define the polynomials\n        f\u2081 = (x^4 + y^4 - 1) * (x^2 + y^2 - 2) + x^5 * y\n        f\u2082 = x^2 + 2x * y^2 - 2 * y^2 - 1 / 2\n        F = [f\u2081, f\u2082]\n        result = solve(F)\n\n        # Input: System(F)\n        cert = certify(System(F), result)\n        @test nnonsingular(result) == 18\n        @test ncertified(cert) == 18\n        @test ndistinct_certified(cert) == 18\n        @test nreal_certified(cert) == 4\n        @test ndistinct_real_certified(cert) == 4\n\n        # Input: F\n        cert = certify(F, result)\n        @test nnonsingular(result) == 18\n        @test ncertified(cert) == 18\n        @test ndistinct_certified(cert) == 18\n        @test nreal_certified(cert) == 4\n        @test ndistinct_real_certified(cert) == 4\n\n        # Control Display\n        cert = certify(F, result, show_progress = false)\n\n        # Double solutions\n        S = solutions(result)\n        cert = certify(System(F), [S; S])\n        @test ncertified(cert) == 36\n        @test ndistinct_certified(cert) == 18\n        @test nreal_certified(cert) == 8\n        @test ndistinct_real_certified(cert) == 4\n    end\n\n    @testset \"Parameters: Input = Vector{Expression}\" begin\n        @var x y\n        f = (x^4 + y^4 - 1) * (x^2 + y^2 - 2) + x^5 * y\n        # define new variables u\u2081, u\u2082 and \u03bb\u2081\n        @var \u03bb[1:1] u[1:2]\n        # define the jacobian of F\n        J = differentiate([f], [x, y])\n        # J' defines the transpose of J\n        F = [[x, y] - u - J' * \u03bb; f]\n        u\u2080 = [-0.32, -0.1]\n        res = solve(F, parameters = u, target_parameters = u\u2080)\n\n        # Input: System(F)\n        C = System(F, parameters = u)\n        cert = certify(C, res; target_parameters = u\u2080)\n        @test ncertified(cert) == 36\n        @test ndistinct_certified(cert) == 36\n        @test nreal_certified(cert) == 8\n        @test ndistinct_real_certified(cert) == 8\n\n        # Input: F\n        cert = certify(F, res, u\u2080; parameters = u)\n        @test ncertified(cert) == 36\n        @test ndistinct_certified(cert) == 36\n        @test nreal_certified(cert) == 8\n        @test ndistinct_real_certified(cert) == 8\n\n        # Invalid solutions\n        cert = certify(C, [100 .* randn(ComplexF64, 3) for i = 1:10], u\u2080)\n        @test ncertified(cert) < 10\n    end\n\n    @testset \"Parameters: Input = Vector{MP.Polynomial}\" begin\n        @polyvar x y\n        f = (x^4 + y^4 - 1) * (x^2 + y^2 - 2) + x^5 * y\n        # define new variables u\u2081, u\u2082 and \u03bb\u2081\n        @polyvar \u03bb[1:1] u[1:2]\n        # define the jacobian of F\n        J = differentiate([f], [x, y])\n        # J' defines the transpose of J\n        F = [[x, y] - u - J' * \u03bb; f]\n        u\u2080 = [-0.32, -0.1]\n        res = solve(F, parameters = u, target_parameters = u\u2080)\n\n        # Input: System(F)\n        C = System(F, parameters = u)\n        cert = certify(C, res; target_parameters = u\u2080)\n        @test ncertified(cert) == 36\n        @test ndistinct_certified(cert) == 36\n        @test nreal_certified(cert) == 8\n        @test ndistinct_real_certified(cert) == 8\n\n        # Input: F\n        cert = certify(F, res; parameters = u, target_parameters = u\u2080)\n        @test ncertified(cert) == 36\n        @test ndistinct_certified(cert) == 36\n        @test nreal_certified(cert) == 8\n        @test ndistinct_real_certified(cert) == 8\n    end\n\n    @testset \"positive\" begin\n        @var x y\n        f = System([x^2 + y^2 - 1, x - y])\n        res = solve(f; compile = false, start_system = :total_degree)\n        cert = certify(f, res, compile = false)\n        @test count(is_positive, certificates(cert)) == 1\n        @test count(s -> is_positive(s, 1), certificates(cert)) == 1\n        @test count(is_real, certificates(cert)) == 2\n    end\n\n    @testset \"3264\" begin\n        F = steiner()\n        real_conics = [\n            10124547 // 662488724,\n            8554609 // 755781377,\n            5860508 // 2798943247,\n            -251402893 // 1016797750,\n            -25443962 // 277938473,\n            1 // 1,\n            520811 // 1788018449,\n            2183697 // 542440933,\n            9030222 // 652429049,\n            -12680955 // 370629407,\n            -24872323 // 105706890,\n            1 // 1,\n            6537193 // 241535591,\n            -7424602 // 363844915,\n            6264373 // 1630169777,\n            13097677 // 39806827,\n            -29825861 // 240478169,\n            1 // 1,\n            13173269 // 2284890206,\n            4510030 // 483147459,\n            2224435 // 588965799,\n            33318719 // 219393000,\n            92891037 // 755709662,\n            1 // 1,\n            8275097 // 452566634,\n            -19174153 // 408565940,\n            5184916 // 172253855,\n            -23713234 // 87670601,\n            28246737 // 81404569,\n            1 // 1,\n        ]\n        real_sols = read_solutions(joinpath(@__DIR__, \"data/3264_real_sols.txt\"))\n        cert = certify(F, real_sols, real_conics; compile = true)\n        @test ndistinct_real_certified(cert) == 3264\n        cert = certify(F, real_sols, real_conics; compile = false)\n        @test ndistinct_real_certified(cert) == 3264\n        @test_throws ArgumentError certify(F, real_sols; compile = false)\n        @test_throws ArgumentError certify(F, real_sols; compile = true)\n    end\n\n    @testset \"certify uses complex inversion\" begin\n        @var x y\n        F = System([y / x + x^2 - 3], parameters = [y])\n        monres = monodromy_solve(F)\n        cert = certify(F, monres)\n        @test ndistinct_certified(cert) >= 1\n    end\nend\n", "meta": {"hexsha": "ae6c0ccaebd665e95b340253fcc55a51a71f40e3", "size": 6917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/certification_test.jl", "max_stars_repo_name": "LauraBMo/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "19662a0c4f3eea4f28179987ffebe86e833865f2", "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": "test/certification_test.jl", "max_issues_repo_name": "LauraBMo/HomotopyContinuation.jl", "max_issues_repo_head_hexsha": "19662a0c4f3eea4f28179987ffebe86e833865f2", "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": "test/certification_test.jl", "max_forks_repo_name": "LauraBMo/HomotopyContinuation.jl", "max_forks_repo_head_hexsha": "19662a0c4f3eea4f28179987ffebe86e833865f2", "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": 34.7587939698, "max_line_length": 81, "alphanum_fraction": 0.5385282637, "num_tokens": 2171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7732620011820188}}
{"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(\u03b8; n_pts=1000000)\n    xmin, xmax = cos(\u03b8), 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(\u03b8)\nend\n\nfunction circle_len2(\u03b8; n_pts=1000000)\n    xmin, xmax = cos(\u03b8), 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(\u03b8)\nend\n\nfunction circle_len3(\u03b8; n_pts=1000000)\n    ts = \u03b8 * 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(\u03b8)\nend\n\ncircle_len3(2\u03c0)", "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    \u03b8::Float64  # angle\n    function RegularPolygon((x, y), n::Int; R=1.0, \u03b8=0.0)\n        @assert n \u2265 3 \"polygons need a minimum of three corners\"\n        return new{n}(x, y, R, \u03b8)\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    \u03b8 = shape.\u03b8\n    R = shape.R\n    n = ncorners(shape)\n    return [(x+R*cos(t+\u03b8), y+R*sin(t+\u03b8)) for t in range(0, step=2\u03c0/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\u03c0, 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\u03b8 = 2\u03c0 / n  # angle of a triangle\n    h = R * cos(d\u03b8/2)\n    b = R * sin(d\u03b8/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 * \u03c0\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\u03b8) = shape\n\nfunction rotate!(shape::RegularPolygon, d\u03b8)\n    shape.\u03b8 += d\u03b8\n    shape\nend\n\n\nfunction rotate!(shape::Triangle, d\u03b8)\n    xc, yc = center(shape)\n    # center triangle\n    move!(shape, (-xc, -yc))\n    (x1, y1), (x2, y2), (x3, y3) = corners(shape)\n    cosd\u03b8 = cos(d\u03b8)\n    sind\u03b8 = sin(d\u03b8)\n    shape.x1 = x1 * cos(d\u03b8) - y1 * sin(d\u03b8)\n    shape.x2 = x2 * cos(d\u03b8) - y2 * sin(d\u03b8)\n    shape.x3 = x3 * cos(d\u03b8) - y3 * sin(d\u03b8)\n    shape.y1 = y1 * cos(d\u03b8) + x1 * sin(d\u03b8)\n    shape.y2 = y2 * cos(d\u03b8) + x2 * sin(d\u03b8)\n    shape.y3 = y3 * cos(d\u03b8) + x3 * sin(d\u03b8)\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 \u2264 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 \u2264 x \u2264 xc + 0.5l) && (yc - 0.5w \u2264 y \u2264 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 \u22c5 (p .- a)) == sign(n \u22c5 (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 \u2264 t \u2264 1.0 &&  0.0 \u2264 s \u2264 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 \u2264 xmin2 \u2264 xmax1 || xmin1 \u2264 xmax2 \u2264 xmax1 || xmin2 \u2264 xmin1 \u2264 xmax2) &&\n            (ymin1 \u2264 ymin2 \u2264 ymax1 || ymin1 \u2264 ymax2 \u2264 ymax1 ||ymin2 \u2264 ymin1 \u2264 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) \u2208 shape2 ||\n            center(shape2) \u2208 shape1 ||\n            any(c->c \u2208 shape2, corners(shape1)) ||\n            any(c->c \u2208 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 \u2208 shape2 || q1 \u2208 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\u03c0 * 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 COSMO, JuMP, LinearAlgebra\nusing Statistics\nusing JuMP\nimport Plots as Plots\nimport ProgressMeter as Pm\nMOI = JuMP.MathOptInterface\n\ninclude(\"utils.jl\")\n\n\nfunction MakeLassoOptimizationProblem(A::Matrix, y::Matrix, \u03bb::Float64)\n    \"\"\"\n        Phrase the quadratic programming problem for Lasso regularization \n        problem. \n        \n    \"\"\"\n    m, n = size(A)\n    @assert size(y, 1) == m && size(y, 2) == 1 \"the label and\"* \n    \" the data matrix doesn't have the maching dimension X:\" * \n    string(m, \"\u00d7\",  n) * string(\";y: \", size(y))\n    @assert \u03bb \u2264 1 && \u03bb \u2265 0 \"Regularization \u03bb should be between (0, 1)\"\n\n\n    Pb = Pm.ProgressUnknown(\"Building Optimization Model: \", spinner=true)\n\n    model = Model(with_optimizer(COSMO.Optimizer); bridge_constraints = false)\n\n    set_optimizer_attribute(model, MOI.Silent(), true)\n    set_optimizer_attribute(model, \"max_iter\", 5000*10)\n\n    @variable(model, x[1:n]); Pm.next!(Pb)\n    setvalue.(x, A\\y); Pm.next!(Pb)\n    @variable(model, \u03b7[1:n]); Pm.next!(Pb)\n    @constraint(model, -\u03b7 .<= x); Pm.next!(Pb)\n    @constraint(model, x .<= \u03b7); Pm.next!(Pb)\n    @objective(model, Min, \u03bb*sum(\u03b7) + sum((A*x - y).^2)); Pm.finish!(Pb)\n\n    return model\n\nend\n\n\nfunction MakeQuantileOptimizationProblem(A::Matrix, y::Matrix, \u03bb::Float64)\n    \"\"\"\n        Phrase the Quantile regression problem into a Quadratic Programming \n        problem\n\n    \"\"\"\nend\n\n\nmutable struct LassoSCOP\n    ## It's just a collection of data. \n\n    A::Matrix # Feature matrix\n    y::Matrix # label vector \n    \u03bc::Matrix # feature mean\n    u::Number # label mean\n    Z::Matrix # Starndardized Matrix\n    l::Matrix # Zero mean label \n    \n    OptModel::Model  # The JuMP model for getting it right. \n    \u03bb::Float64       # the regularization parameter. \n\n    LassoPath::Union{Matrix, Nothing} # going along a fixed row is the fixing \n    # the feature while varying the lambda quantity. \n    \u03bbs::Union{Vector, Nothing} # the lambda values. \n\n    function LassoSCOP(A::Matrix, y::Union{Matrix, Vector}, \u03bb::Float64=0.0)\n        A = copy(A)\n        m, _ = size(A)\n        @assert size(y, 1) == m \"\"*\n        \"The rows of X should match of the columns of y, but the size of\"*\n        string(\"X, Y is: \", size(A), \" \", size(y))\n        \n        y = copy(y)\n        if ndims(y) == 1\n            y = reshape(y, (length(y), 1))\n        end\n        \u03bc = mean(A, dims=1)::Matrix\n        u = mean(y)\n        Z = A .- \u03bc\n        l = y .- u\n        OptModel = MakeLassoOptimizationProblem(Z, l, \u03bb)\n\n        return new(A, y, \u03bc, u, Z, l, OptModel, \u03bb)\n    end\nend\n\n\nfunction LassoPath(this::LassoSCOP, tol::Float64=1e-8)\n    \"\"\"\n        Analyze the Lasso Problem by drawing a lasso path. It will start with \n        a parameter that will make all predictors zero and then solve it \n        iterative by chopping the regularization \u03bb by half each iteration. \n\n        **this**: \n            An instance of the LassoSCOP\n        **tol**: \n            If the infinity norm of vector of the change in the weights is \n            less than this quantity, then it stops and return all the results. \n\n    \"\"\"\n\n    u = this.u\n    A = this.Z\n    y = this.l\n    Results = Vector{Vector}()\n    \n    function \u03bbMax(A, y)\n        ToMax = A'*(y .- u)\n        ToMax *= 2\n        return maximum(abs.(ToMax))\n    end\n\n\n    \u03bb = \u03bbMax(A, y)\n    \u03bbs = Vector{Float64}()\n    Change\u03bb(this, \u03bb)\n    x = SolveForx(this)\n    dx = Inf\n    push!(Results, x)\n    push!(\u03bbs, \u03bb)\n    MaxItr = 100\n    pb = Pm.ProgressThresh(tol, \"inf norm of \u03b4x: \")\n    while dx >= tol && MaxItr >= 0\n        push!(\u03bbs, \u03bb)\n        \u03bb /= 2\n        MaxItr -= 1\n        setvalue.(this.OptModel[:x], x) # warm start! \n        Change\u03bb(this, \u03bb)\n        x = SolveForx(this)\n        push!(Results, x)\n        dx = norm(Results[end - 1] - Results[end], Inf)\n        Pm.update!(pb, dx)\n    end\n\n\n    ResultsMatrix = zeros(length(x), length(Results))\n    for II \u2208 1:length(Results)\n        ResultsMatrix[:, II] = Results[II]\n    end\n\n    # Store it. \n    this.LassoPath = ResultsMatrix\n    this.\u03bbs = \u03bbs\n    return ResultsMatrix, \u03bbs\nend\n\n\nfunction VisualizeLassoPath(\n                            this::LassoSCOP, \n                            fname::Union{String, Nothing}=nothing,\n                            title::Union{String, Nothing}=nothing\n                            )\n    \"\"\"\n        Make a plots for the lasso path and save it in the pwd. \n        \n    \"\"\"\n    @assert isdefined(this, :LassoPath) \"Lasso Path not defined for the object\"*\n    \"yet\". \n    error(\"Haven't implemented it yet.\")\n    \u03bbs = this.\u03bbs\n    Paths = this.LassoPath\n    Logged\u03bb = log2.(\u03bbs)\n    p1 = Plots.heatmap(\n        Paths[end:-1:begin, :], \n        title=title===nothing ? \"Lasso Path\" : title\n        )\n    p2 = plot(Logged\u03bb, Paths', label=nothing)\n    Plots.xlabel!(p2, \"log_2(\u03bb)\")\n    p = Plots.plot(p1, p2, layout=(2, 1))\n    Plots.plot!(size=(600, 800))\n    Plots.plot!(dpi=400)\n    Plots.savefig(p, fname===nothing ? \"plot.png\" : fname)\n    return\nend\n\n\nfunction CaptureImportantWeights(\n                                this::LassoSCOP, \n                                top_k::Union{Float64, Int64} = 0.5, \n                                threshold::Float64=1e-10\n                                )\n    \"\"\"\n        Caputre the indices for the most important predictors from the \n        regression. Returns the indices of the important weights. \n        \n        ---\n        **this::LassoSCOP**: \n            An instance of the type LassoSCOP\n\n        ---\n        **top_k::Union{Float64, Int64} = 0.5**\n            When it's in between 0, 1, it's specifying the portion of weights\n            that are non-zero, when it's not in in this range and it's positive,\n            then it's specifying the number of top weights, measured by the \n            absolute value of the weights. \n\n        ---\n        **threshold::Float64=1e-10**\n            Weigthts less than threshold is viewed as unimportant and it's \n            discarded as zero. \n        \n    \"\"\"\n    # TODO: test this \n    @assert isdefined(this, :LassoPath) \"Lasso Path not defined for this\"*\n    \"Object yet. \"\n    @assert top_k >= 0 \"this parameters, should be a positive number\"\n    top_k = min(top_k, size(this.LassoPath, 1))\n    @assert threshold >= 0 \"This parameters shouold be a positive number\"\n\n    Paths = this.LassoPath\n    top_k::Int64 = top_k <= 1 ? ceil(size(Paths, 1)*0.5) : round(top_k)\n    for JJ in size(Paths, 2)\n        Col = view(Paths, :, JJ)\n        NonNegative = sum(abs.(Col) .>= threshold)\n        # rank them by abs and returns the indices for top k weights\n        if NonNegative >= top_k \n            Indices = sortperm(abs.(Col), rev=true)\n            return Indices[begin:top_k]\n        end\n    end\n    return Vector{Int64}()\nend\n\n\nfunction Change\u03bb(this::LassoSCOP, \u03bb)\n    \"\"\"\n        Change the Lasso regularizer of the current model \n    \"\"\"\n    model = this.OptModel\n    x = model[:x]  # objects can be indexed with symbols! \n    \u03b7 = model[:\u03b7]\n    y = this.l\n    A = this.Z\n    @objective(model, Min, \u03bb*sum(\u03b7) + sum((A*x - y).^2))\n    \nend\n\n\nfunction SolveForx(this::LassoSCOP)::Vector{Float64}\n    \"\"\"\n        Solve for the weights of the current model, \n        given the current configuration of the model.\n    \"\"\"\n    optimize!(this.OptModel)\n    TernimationStatus = termination_status(this.OptModel)\n    # @assert TernimationStatus == MOI.OPTIMAL \"Terminated with non-optimal value when solving for x. \"*\n    # string(\"The status is: \", TernimationStatus)*\"\\n this is the results \\n $(OptResults)\"\n    \n    if !(TernimationStatus == MOI.OPTIMAL)\n        Warn(\"\\nWarning: convergence status for solver: $(TernimationStatus)\")\n        Warn(\"Current Value \u03bb: $(this.\u03bb)\")\n        PrintTitle(\"Here is the summary for the solution: \")\n        display(solution_summary(this.OptModel))\n    end\n    return value.(this.OptModel[:x])\nend\n\n\nfunction Get\u03b1\u03b2(this::LassoSCOP, lambda::Float64)\n    \"\"\"\n        Get the weights and biases, for the original model \n        (The model trained is normalized), \n        for a particular regularization value. \n    \"\"\"\n    error(\"Not yet implemented. \")\n    \nend\n\n\n# TODO: Override Base.show for this LASSOPath TYPE.\n\n\n# TODO: Iterate, Use Base.Iterate, override it. \nfunction Base.iterate(this::LassoSCOP)\n    \"\"\"\n        Iterate through the parameters for the Lasso program: \n            * \u03bb\n            * solutions\n    \"\"\"\n    u = this.u\n    A = this.Z\n    y = this.l\n    \n    function \u03bbMax(A, y)\n        ToMax = A'*(y .- u)\n        ToMax *= 2\n        return maximum(abs.(ToMax))\n    end\n    \u03bb = \u03bbMax(A, y)\n    x = SolveForx(this)\n    return \u03bb, x\n\n\nend\n\nfunction Base.Iterate(this::LassoSCOP, state::Int64)\n    \nend\n\n\n", "meta": {"hexsha": "1132c4208edaeedc867af586e055b427d436f488", "size": 8668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "prototype/lasso.jl", "max_stars_repo_name": "iluvjava/LassoPath.jl", "max_stars_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/lasso.jl", "max_issues_repo_name": "iluvjava/LassoPath.jl", "max_issues_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/lasso.jl", "max_forks_repo_name": "iluvjava/LassoPath.jl", "max_forks_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_forks_repo_licenses": ["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.5131578947, "max_line_length": 104, "alphanum_fraction": 0.5808721735, "num_tokens": 2406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7732320606822333}}
{"text": "module OperationsTests\n\nusing Test\nusing TensorValues\n\na = VectorValue(1,2,3)\nb = VectorValue(2,1,6)\n\n# Comparison\n\n@test a==a\n@test a \u2248 a\n@test a!=b\n@test [a,a] == [a,a]\n@test [a,a] \u2248 [a,a]\n\n# Addition / subtraction\n\nc = +a\nr = VectorValue(1,2,3)\n@test c == r\n\nc = -a\nr = VectorValue(-1,-2,-3)\n@test c == r\n\nc = a + b\nr = VectorValue(3,3,9)\n@test c == r\n\nc = a - b\nr = VectorValue(-1,1,-3)\n@test c == r\n\n# Matrix Division\n\nt = one(TensorValue{3,Int,9})\n\nc = t\\a\n\n@test c == a\n\n# Operations by a scalar\n\na = VectorValue(1,2,3)\nr = VectorValue(2,4,6)\n\nc = 2 * a\n@test isa(c,VectorValue{3,Int})\n@test c == r\n\nc = a * 2\n@test isa(c,VectorValue{3,Int})\n@test c == r\n\nr = VectorValue(3,4,5)\n\nc = 2 + a\n@test isa(c,VectorValue{3,Int})\n@test c == r\n\nc = a + 2\n@test isa(c,VectorValue{3,Int})\n@test c == r\n\nr = VectorValue(1/2,1.0,3/2)\n\nc = a / 2\n@test isa(c,VectorValue{3,Float64})\n@test c == r\n\n# Dot product (simple contraction)\n\na = VectorValue(1,2,3)\nb = VectorValue(2,1,6)\n\nt = TensorValue(1,2,3,4,5,6,7,8,9)\ns = TensorValue(9,8,3,4,5,6,7,2,1)\n\nc = a * b\n@test isa(c,Int)\n@test c == 2+2+18\n\nc = t * a\n@test isa(c,VectorValue{3,Int})\nr = VectorValue(30,36,42)\n@test c == r\n\nc = s * t\n@test isa(c,TensorValue{3,Int})\nr = TensorValue(38,24,18,98,69,48,158,114,78)\n@test c == r\n\n# Inner product (full contraction)\n\nc = inner(2,3)\n@test c == 6\n\nc = inner(a,b)\n@test isa(c,Int)\n@test c == 2+2+18\n\nc = inner(t,s)\n@test isa(c,Int)\n@test c == 185\n\n# Reductions\n\na = VectorValue(1,2,3)\n\nc = sum(a)\n@test isa(c,Int)\n@test c == 1+2+3\n\nc = maximum(a)\n@test isa(c,Int)\n@test c == 3\n\nc = minimum(a)\n@test isa(c,Int)\n@test c == 1\n\n# Outer product (aka dyadic product)\n\na = VectorValue(1,2,3)\ne = VectorValue(2,5)\n\nc = outer(2,3)\n@test c == 6\n\nr = VectorValue(2,4,6)\nc = outer(2,a)\n@test isa(c,VectorValue{3,Int})\n@test c == r\n\nc = outer(a,2)\n@test isa(c,VectorValue{3,Int})\n@test c == r\n\nc = outer(a,e)\n@test isa(c,MultiValue{Tuple{3,2},Int})\nr = MultiValue{Tuple{3,2},Int}(2,4,6,5,10,15)\n@test c == r\n\n# Linear Algebra\n\nt = TensorValue(10,2,30,4,5,6,70,8,9)\n\nc = det(t)\n@test c \u2248 -8802.0\n\nc = inv(t)\n@test isa(c,TensorValue{3})\n\n# Measure\n\na = VectorValue(1,2,3)\nc = meas(a)\n@test c \u2248 3.7416573867739413\n\nt = TensorValue(10,2,30,4,5,6,70,8,9)\nc = meas(t)\n@test c \u2248 8802.0\n \n# Broadcasted operations\n\na = VectorValue(1,2,3)\nb = VectorValue(2,1,6)\n\nA = Array{VectorValue{3,Int},2}(undef,(4,5))\nA .= a\n@test A == fill(a,(4,5))\n\nC = .- A\n\nr = VectorValue(-1,-2,-3)\nR = fill(r,(4,5))\n@test C == R\n\nB = fill(b,(4,1))\n\nC = A .+ B\n\nr = VectorValue(3,3,9)\nR = fill(r,(4,5))\n@test C == R\n\nC = A .- B\n\nr = VectorValue(-1,1,-3)\nR = fill(r,(4,5))\n@test C == R\n\n# conj\n\nv = VectorValue(1,0)\n@test v == v'\n@test conj(v) == v'\n\nt = TensorValue(1,2,3,4)\n@test trace(t) == 5\n@test tr(t) == 5\n\nt = TensorValue(1,2,3,4,5,6,7,8,9)\n@test trace(t) == 15\n@test tr(t) == 15\n\n@test symmetic_part(t) == TensorValue(1.0, 3.0, 5.0, 3.0, 5.0, 7.0, 5.0, 7.0, 9.0)\n\na = TensorValue(1,2,3,4)\nb = a'\n@test adjoint(a) == b\n@test b == TensorValue(1,3,2,4)\n@test a*b == TensorValue(10,14,14,20)\n\nu = VectorValue(1.0,2.0)\nv = VectorValue(2.0,3.0)\n@test dot(u,v) \u2248 inner(u,v)\n@test norm(u) \u2248 sqrt(inner(u,u))\n\nend # module OperationsTests\n", "meta": {"hexsha": "30135faa0b96b1948b72cffcd4359cf520230bdf", "size": 3183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/OperationsTests.jl", "max_stars_repo_name": "JuliaTagBot/TensorValues.jl", "max_stars_repo_head_hexsha": "0dc91d9d5846cf9f19ccc755c985188b6ed0c222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-10T17:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T05:05:59.000Z", "max_issues_repo_path": "test/OperationsTests.jl", "max_issues_repo_name": "JuliaTagBot/TensorValues.jl", "max_issues_repo_head_hexsha": "0dc91d9d5846cf9f19ccc755c985188b6ed0c222", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-05-16T16:10:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:21:08.000Z", "max_forks_repo_path": "test/OperationsTests.jl", "max_forks_repo_name": "JuliaTagBot/TensorValues.jl", "max_forks_repo_head_hexsha": "0dc91d9d5846cf9f19ccc755c985188b6ed0c222", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:14:14.000Z", "avg_line_length": 14.3378378378, "max_line_length": 82, "alphanum_fraction": 0.589695256, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7732183789431459}}
{"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# \u03bb ~ Gamma(\u03b1\u2080, \u03b8\u2080)\n# m ~ Normal(0, \u221a(1 / \u03bb))\n# X\u1d62 ~ Normal(m, \u221a(1 / \u03bb)) (iid)\n    \n\nfunction gdemo_forward(N, \u03b1\u2080, \u03b8\u2080)\n    \u03bb = rand(Gamma(\u03b1\u2080, \u03b8\u2080))\n    \u03c3 = \u221a(1 / \u03bb)\n    m = rand(Normal(0, \u03c3))\n    x = rand(Normal(m, \u03c3), N)\n    return (m=m, \u03bb=\u03bb), x\nend\n\nfunction gdemo_logjoint(\u03b1\u2080, \u03b8\u2080, x, m, \u03bb)\n    \u03c3 = \u221a(1 / \u03bb)\n    return logpdf(Gamma(\u03b1\u2080, \u03b8\u2080), \u03bb) +\n        logpdf(Normal(0, \u03c3), m) +\n        sum(logpdf.(Normal(m, \u03c3), 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\u0304 = mean(x) # sample mean\n    s\u00b2 = var(x; mean=x\u0304, corrected=false) # sample variance\n    return N, x\u0304, s\u00b2\nend\n\nfunction gdemo_cond_m(\u03b1\u2080, \u03b8\u2080, x, \u03bb)\n    N, x\u0304, s\u00b2 = gdemo_statistics(x)\n    m\u2099 = N * x\u0304 / (N + 1)\n    \u03bb\u2099 = \u03bb * (N + 1)\n    \u03c3\u2099 = \u221a(1 / \u03bb\u2099)\n    return Normal(m\u2099, \u03c3\u2099)\n    # return Normal(7/6, 0.00001)\nend\n\nfunction gdemo_cond_\u03bb(\u03b1\u2080, \u03b8\u2080, x, m)\n    N, x\u0304, s\u00b2 = gdemo_statistics(x)\n    \u03b1\u2099 = \u03b1\u2080 + (N - 1) / 2 + 1\n    \u03b2\u2099 = (s\u00b2 * N / 2 + m^2 / 2 + inv(\u03b8\u2080))\n    return Gamma(\u03b1\u2099, inv(\u03b2\u2099))\nend\n\n\nfunction gdemo(x; \u03b1\u2080=2.0, \u03b8\u2080=inv(3.0))\n    cond_m((\u03bb,)) = gdemo_cond_m(\u03b1\u2080, \u03b8\u2080, x, \u03bb)\n    cond_\u03bb((m,)) = gdemo_cond_\u03bb(\u03b1\u2080, \u03b8\u2080, x, m)\n    conditionals = (m=cond_m, \u03bb=cond_\u03bb)\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# \u03bc ~ arraydist(Normal.(fill(m, K), fill(\u03bb, K)))\n# z ~ arraydist(Categorical.(fill(\u03c0, N)))\n# x ~ arraydist(Normal.(\u03bc[z], \u03c3))\n\nfunction mixture_cond_z(\u03c0, K, m, \u03bb, \u03c3, x, \u03bc)\n    function mixtureweight(x)\n        p = \u03c0 .* pdf.(Normal.(\u03bc, \u03c3), Ref(x))\n        return p ./ sum(p)\n    end\n    return Product(Categorical.(mixtureweight.(x)))\nend\n\nfunction mixture_cond_\u03bc(\u03c0, K, m, \u03bb, \u03c3, 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    \u03bb_hat = [(n[k] != 0) ? inv(n[k] / \u03c3^2 + 1/\u03bb^2) : \u03bb for k = 1:K]\n    \u03bc_hat = [(n[k] != 0) ? x_bar[k] * (n[k] / \u03c3^2) * \u03bb_hat[k] : m for k = 1:K]\n\n    return Product(Normal.(\u03bc_hat, \u03bb_hat))\nend\n\n\nfunction mixture(\u03c0, K, m, \u03bb, \u03c3, x)\n    cond_z((\u03bc,)) = mixture_cond_z(\u03c0, K, m, \u03bb, \u03c3, x, \u03bc)\n    cond_\u03bc((z,)) = mixture_cond_\u03bc(\u03c0, K, m, \u03bb, \u03c3, x, z)\n    return (z=cond_z, \u03bc=cond_\u03bc)\nend\n\n\n\n########### 1D ISING MODEL #########################\nfunction ising_conditional(\u03b2, 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\u2081 = exp(-\u03b2 * (x_prev + x_next))\n        p\u2082 = exp(-\u03b2 * (abs(x_prev - 1) + abs(x_next - 1)))\n        return Bernoulli(p\u2081 / (p\u2081 + p\u2082))\n    end\nend\n\nfunction isingdemo(\u03b2, 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(\u03b2, i, M) for i = 1:M]\n    conditionals = merge(NamedTuple(), conditional_dists)\nend\n\nfunction ising_conditional(\u03b2, 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\u2081 = exp(-\u03b2 * (x_prev + x_next + x_up + x_down))\n        p\u2082 = exp(-\u03b2 * (abs(x_prev - 1) + abs(x_next - 1) + abs(x_up - 1) + abs(x_down - 1)))\n        return Bernoulli(p\u2081 / (p\u2081 + p\u2082))\n    end\nend\n\nfunction isingdemo(\u03b2, 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(\u03b2, i, j, M, N) for i = 1:M, j = 1:N]\n    conditionals = merge(NamedTuple(), conditional_dists)\nend\n\nfunction visualize_ising(\u03b8::AbstractVector{<:Real})\n    join(v == 1 ? '\\u2588' : ' ' for v in values(\u03b8))\nend\n\nfunction visualize_ising(\u03b8::AbstractMatrix{<:Real})\n    join((join(v == 1 ? '\\u2588' : ' ' for v in row) for row in eachrow(\u03b8)), '\\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    \u03bc = p[1]\n\n    dx[1] = \u03bc * (x[1] - 1/3 * x[1]^3 - x[2] ) \n    dx[2] = 1/\u03bc * x[1]\nend\n\ntspan = (0.0, 100.0) # time span\nx0    = [0.5, 0.5]   # initial values\np     = [1.0]        # parameter: \u03bc\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 \u03bc\"))\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( \"\u03bc = \", 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\u03bc0 = 4pi*1e-7 #F/m\n\u03f50 = 8.854e-12 #H/m\n\n\n#Input data\n#-------------------------------------------------------------------------------\nfmax = 10e9\nfstep = 50e6\nf = collect(0:fstep:fmax)\n\u2113 = 50e-3 #Meters\nZL = Float64[1e6, 377, 60.0]\n_colors = [blue, red, green]\n\n\n#==Equations\n===============================================================================#\n\u0393(Z; Zref::Real=50.0) = (Z - Zref) ./ (Z + Zref)\n#ZC: Characteristic impedance\n#ZL: Load impendance (termination)\nfunction Zline(\u2113::Real, f::Vector, ZL::Number; ZC::Number=50.0, \u03b1::Real=0, \u03bc::Real=\u03bc0, \u03f5::Real=\u03f50)\n\tj = im\n\t\u03b2 = f*(2pi*sqrt(\u03bc*\u03f5))\n\t\u03b3 = \u03b1+j*\u03b2\n\ttanh_\u03b3\u2113 = tanh(\u03b3*\u2113)\n\treturn ZC*(ZL+ZC*tanh_\u03b3\u2113)./(ZC+ZL*tanh_\u03b3\u2113)\nend\nfunction \u0393line(\u2113::Real, f::Vector, ZL::Number; ZC::Number=50.0, Zref::Number=50.0, \u03b1::Real=0, \u03bc::Real=\u03bc0, \u03f5::Real=\u03f50)\n\treturn \u0393(Zline(\u2113, f, ZL; ZC=ZC, \u03b1=\u03b1, \u03bc=\u03bc, \u03f5=\u03f5), Zref=Zref)\nend\n\n#Calculations\n#-------------------------------------------------------------------------------\n\u0393load = []\nfor ZLi in ZL\n\t_\u0393 = \u0393line(\u2113, f, ZLi, ZC=40)\n\tpush!(\u0393load, _\u0393)\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 (\u0393)\"\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(\u0393)\"\n\ta.ylabel = \"Imaginary(\u0393)\"\n\na = plot_smith.annotation\n\ta.title = \"Z-Smith Chart\"\n\ta.xlabel = \"Real(\u0393)\"\n\ta.ylabel = \"Imaginary(\u0393)\"\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(\u0393load)\n\t\twfrm = add(plot, f, \u0393load[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 `\u03c9x`, `\u03c9y` and ``\u03c9z` have near unit ratios by default.\n\n# References\nKrakovsk\u00e1, 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    \u03c9x, \u03c9y, \u03c9z, k, l, m, c = (p...,)\n    x\u2081, x\u2082, x\u2083, y\u2081, y\u2082, y\u2083, z\u2081, z\u2082, z\u2083 = (u...,)\n\n    dx\u2081 = -\u03c9x*x\u2082 - x\u2083 + c*(z\u2081 - x\u2081)\n\tdx\u2082 = \u03c9x*x\u2081 + k*x\u2082\n\tdx\u2083 = l + x\u2083*(x\u2081 - m)\n\n\tdy\u2081 = -\u03c9y*y\u2082 - y\u2083 + c*(z\u2081 - y\u2081)\n\tdy\u2082 = \u03c9y*y\u2081 + k*y\u2082\n\tdy\u2083 = l + y\u2083*(y\u2081 - m)\n\n\tdz\u2081 = -\u03c9z*z\u2082 - z\u2083\n\tdz\u2082 = \u03c9z*z\u2081 + k*z\u2082\n\tdz\u2083 = l + z\u2083*(z\u2081 - m)\n\n    SVector{9}(dx\u2081, dx\u2082, dx\u2083, dy\u2081, dy\u2082, dy\u2083, dz\u2081, dz\u2082, dz\u2083)\nend\n\nfunction mediated_link(u\u2080, \u03c9x, \u03c9y, \u03c9z, k, l, m, c)\n    p = [\u03c9x, \u03c9y, \u03c9z, k, l, m, c]\n    ContinuousDynamicalSystem(eom_mediated_link, u\u2080, p)\nend\n\n\"\"\"\n    mediated_link(;u\u2080 = rand(9), \u03c9x = 1, \u03c9y = 1.015, \u03c9z = 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\u00e1, 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\u2080 = rand(9), \u03c9x = 1, \u03c9y = 1.015, \u03c9z = 0.985,\n            k = 0.15, l = 0.2, m = 10.0, c = 0.06) =\n    mediated_link(u\u2080, \u03c9x, \u03c9y, \u03c9z, 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(\u03b1, \u03b2), x)\nhttps://en.wikipedia.org/wiki/Inverse-gamma_distribution\n\"\"\"\nfunction log_inverse_gamma(x::Real, \u03b1::Real=1., \u03b2::Real=1.; d::Integer=0)\n    @assert 0 <= d <= 2\n    if d == 0\n        x > 0 ? val = -(\u03b2 / x) - (1 + \u03b1) * log(x) + \u03b1 * log(\u03b2) - loggamma(\u03b1) : val = -Inf\n    elseif d == 1\n        x > 0 ? val = (\u03b2 / x - (1 + \u03b1)) / x : val = 0\n    else\n        x > 0 ? val = (-2 * \u03b2 / x + (1 + \u03b1)) / (x * x) : val = 0\n    end\n    return val\nend\n\n\nfunction gamma_mode_std_2_alpha_theta(m::Real, s::Real)\n    \u03b8 = (sqrt(m ^ 2 + 4 * s ^ 2) - m) / 2\n    \u03b1 = m / \u03b8 + 1\n    return [\u03b1, \u03b8]\nend\n\n\"\"\"\nLog of the Gamma PDF. Equivalent to using Distributions; logpdf(Gamma(\u03b1, \u03b2), 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    \u03b1 = parameters[1]\n    \u03b8 = parameters[2]\n    if d == 0\n        x > 0 ? val = -(x / \u03b8) + (\u03b1 - 1) * log(x) - \u03b1 * log(\u03b8) - loggamma(\u03b1) : val = -Inf\n    elseif d == 1\n        x > 0 ? val = (\u03b1 - 1) / x - 1 / \u03b8 : val = 0\n    else\n        x > 0 ? val = -(\u03b1 - 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(\u03bc, \u03c3), 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    \u03bc = parameters[1]\n    \u03c3 = parameters[2]\n    assert_positive(\u03c3)\n    @assert min < max\n    normalization = 1 - gauss_cdf(min - \u03bc) - gauss_cdf(\u03bc - max)\n    if d == 0\n        (min < x < max) ? val = -((x - \u03bc)^2/(2 * \u03c3 * \u03c3)) - log(sqrt(2 * \u03c0) * \u03c3) - log(normalization) : val = -Inf\n    elseif d == 1\n        (min < x < max) ? val = -(x - \u03bc)/(\u03c3 * \u03c3) : val = 0\n    else\n        (min < x < max) ? val = -1 / (\u03c3 * \u03c3) : 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, \u03c3::Real; d::Integer=0)\n    @assert 0 <= d <= 2\n    if d == 0\n        0 <= x <= 1 ? val = -(x * x / (2 * \u03c3 * \u03c3)) + log(x / \u03c3 / \u03c3) -  log(1 - exp(-1 / (2 * \u03c3 * \u03c3))) : val = -Inf\n    elseif d == 1\n        0 <= x <= 1 ? val = 1 / x - x / \u03c3 / \u03c3 : val = 0\n    elseif d == 2\n        0 <= x <= 1 ? val = -1 / x / x - 1 / \u03c3 / \u03c3 : 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_\u03b8 < atan(x[1], x[2]) < max_\u03b8\n    if all(d .== 0)\n        min_r < sqrt(dot(x, x)) < max_r ? val = -log(2 * \u03c0 * (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 / \u03c0 * (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 / \u03c0 * (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 / \u03c0 * (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 \u03c3 = 1/5\n\"\"\"\nfunction log_rot_Rayleigh(x::Vector{<:Real}; d::Vector{<:Integer}=[0,0], \u03c3=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    \u03c3_sq = \u03c3 ^ 2\n    log_norm = -2 * log(\u03c3) - 0.454215\n    if d == [0,0]\n        0 <= r < 1 ? val = -r_sq / (2 * \u03c3_sq) + log(r) + log_norm : val = -Inf\n    elseif d == [0,1]\n        0 <= r < 1 ? val = -x[2] * (r_sq - \u03c3_sq) / (r_sq * \u03c3_sq) : val = 0\n    elseif d == [0,2]\n        0 <= r < 1 ? val = -(x[1] ^ 4 + x[1] ^ 2 * (2 * x[2] ^ 2 - \u03c3_sq) + x[2] ^ 2 * (x[2] ^ 2 + \u03c3_sq)) / (r_sq ^ 2 * \u03c3_sq) : val = 0\n    elseif d == [1,0]\n        0 <= r < 1 ? val = -x[1] * (r_sq - \u03c3_sq) / (r_sq * \u03c3_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 - \u03c3_sq) + x[1] ^ 2 * (x[1] ^ 2 + \u03c3_sq)) / (r_sq ^ 2 * \u03c3_sq) : val = 0\n    end\n    return val\nend\n\n\n\"\"\"\nLog of the bivariate normal PDF\nNOTE THAT THAT WHEN USING lows!=[-\u221e,...], THIS IS NOT PROPERLY NORMALIZED\n\"\"\"\nfunction log_bvnormal(x::Vector{T}, \u03a3::Cholesky{T,Matrix{T}}; \u03bc::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(\u03bc) == 2\n    y = x - \u03bc\n\n    if sum(d) == 0\n        all(x .>= lows) ? val = -nlogL(\u03a3, y) : val = -Inf\n    elseif sum(d) == 1\n        y1 = Float64.(d)\n        all(x .>= lows) ? val = -dnlogLd\u03b8(y1, \u03a3 \\ y) : val = 0\n    elseif d == [0,2]\n        y1 = y2 = [0, 1.]\n        all(x .>= lows) ? val = -d2nlogLd\u03b8(y2, [0,0.], \u03a3 \\ y, \u03a3 \\ y1) : val = 0\n    elseif d == [1,1]\n        y1 = [1, 0.]\n        y2 = [0, 1.]\n        all(x .>= lows) ? val = -d2nlogLd\u03b8(y2, [0,0.], \u03a3 \\ y, \u03a3 \\ y1) : val = 0\n    elseif d == [2,0]\n        y1 = y2 = [1, 0.]\n        all(x .>= lows) ? val = -d2nlogLd\u03b8(y2, [0,0.], \u03a3 \\ y, \u03a3 \\ y1) : val = 0\n    end\n    return val\nend\nfunction bvnormal_covariance(\u03c311::Real, \u03c322::Real, \u03c1::Real)\n    assert_positive(\u03c311, \u03c322)\n    @assert 0 <= \u03c1 <= 1\n    v12 = \u03c311*\u03c322*\u03c1\n    return ridge_chol([\u03c311^2 v12;v12 \u03c322^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(\u03f5::Real,\u03b4::Real)\nCompute the proportionality constant \u03ba(\u03f5,\u03b4) for the Gaussian mechanism.\n\"\"\"\nfunction gaussianMechConstant(\u03f5::Real, \u03b4::Real)\n    K = sqrt(2) * SpecialFunctions.erfinv(1-2\u03b4)\n    return (K+sqrt(K^2+2\u03f5))/(2\u03f5)\nend\n\n\"\"\"    (k\u2081, k\u2082) = gaussianMechConstant2(\u03f5::Real,\u03b4::Real)\nCompute the proportionality constant \u03ba(\u03f5,\u03b4) for the Gaussian mechanism,\nboth with the formula using the inverse Q-function (k\u2081), and according to the\napproximation of Theorem A.1 in Dwork and Roth's book (k\u2082, higher value).\n\"\"\"\nfunction gaussianMechConstant2(\u03f5::Real, \u03b4::Real)\n    K = sqrt(2) * SpecialFunctions.erfinv(1-2\u03b4)\n    return ((K+sqrt(K^2+2\u03f5))/(2\u03f5), sqrt(2log(1.25/\u03b4))/\u03f5)\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 (\u03f5,\u03b4)-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, \u03f5::Real, \u03b4::Real=0.0)\n    if \u03b4 == 0.0\n        d = Distributions.Laplace(0, 1/(\u03f5*length(x)))\n    else\n        d = Distributions.Normal(0, gaussianMechConstant(\u03f5,\u03b4)/length(x))\n    end\n    return Distributions.mean(x) + Distributions.rand(d)\nend\n\n\"\"\"    laplaceMech(x,f,l1sens::Real,\u03f5::Real)\nComputes a randomized version to f(x) according to the\nLaplace mechanism, for \u03f5-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, \u03f5::Real)\n    t = f(x)\n    d = Distributions.Laplace(0, l1sens/\u03f5)\n    return (t .+ Distributions.rand(d, length(t)))\nend\n\n\"\"\"    gaussianMech(x,f,l2sens::Real,\u03f5::Real,\u03b4::Real)\nComputes a randomized version to f(x) according to the\nGaussian mechanism, for (\u03f5,\u03b4)-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, \u03f5::Real, \u03b4::Real)\n    t = f(x)\n    d = Distributions.Normal(0, gaussianMechConstant(\u03f5, \u03b4) * l2sens)\n    return (t .+ Distributions.rand(d, length(t)))\nend\n\n\"\"\"    truncatedLaplaceMech(x,f,l1sens::Real,\u03f5::Real,\u03b4::Real)\nComputes a randomized version to f(x) according to the\ntruncated Laplace mechanism, for (\u03f5,\u03b4)-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, \u03f5::Real, \u03b4::Real)\n    t = f(x)\n    k = length(t)\n    \u03bb = l1sens/\u03f5\n    a = \u03bb * log( 1 + exp(\u03f5) * (k*(1-exp(-\u03f5/k)))/(2*\u03b4) )\n    # alternative, more conservative but indpt of k\n    # a = \u03bb * log(1 + \u03f5 * exp(\u03f5) / (2*\u03b4))\n    d1 = Distributions.Laplace(0, \u03bb)\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": "function test_softlabel_softmax_loss_layer(backend::Backend, tensor_dim, T, eps)\n  println(\"-- Testing SoftlabelSoftmaxLossLayer on $(typeof(backend)){$T}...\")\n\n  dims = abs(rand(Int,tensor_dim)) % 6 + 6\n  dims = tuple(dims...)\n  op_dim = max(abs(rand(Int)) % tensor_dim, 1)\n  println(\"    > $dims (operate on dimension $op_dim)\")\n\n  input = rand(T, dims) + 0.01\n  input_blob = make_blob(backend, input)\n  diff_blob = make_blob(backend, T, size(input))\n\n  labels = abs(rand(T, dims)) + 0.01\n  labels = labels ./ sum(labels, op_dim)\n  label_blob = make_blob(backend, labels)\n\n  inputs = Blob[input_blob, label_blob]\n\n  loss_weight = abs(rand(T))\n  layer = SoftlabelSoftmaxLossLayer(bottoms=[:pred, :labels], dim=op_dim, weight=loss_weight)\n  state = setup(backend, layer, inputs, Blob[diff_blob])\n\n  println(\"    > Forward\")\n  forward(backend, state, inputs)\n\n  expected_loss = 0\n  expected_grad = zeros(T, size(input))\n\n  dim_pre, dim_prob, dim_post = split_dims(input, op_dim)\n  canonical_input = reshape(input, dim_pre, dim_prob, dim_post)\n  canonical_label = reshape(labels, dim_pre, dim_prob, dim_post)\n  canonical_grad = reshape(expected_grad, dim_pre, dim_prob, dim_post)\n\n  for i = 1:dim_pre\n    for j = 1:dim_post\n      pred = exp(canonical_input[i,:,j])\n      pred /= sum(pred)\n\n      expected_loss += sum(-log(pred) .* canonical_label[i,:,j])\n      canonical_grad[i,:,j] = repmat(vec(pred), 1, dim_prob) * vec(canonical_label[i,:,j])\n      canonical_grad[i,:,j] -= canonical_label[i,:,j]\n    end\n  end\n  scale = dims[op_dim] / prod(dims)\n  expected_loss *= scale * loss_weight\n  expected_grad *= scale * loss_weight\n  expected_grad = reshape(expected_grad, size(input))\n\n  @test -eps < state.loss - expected_loss < eps\n\n  println(\"    > Backward\")\n  backward(backend, state, inputs, Blob[diff_blob])\n  grad = to_array(diff_blob)\n\n  @test all(-eps .< grad - expected_grad .< eps)\n\n  shutdown(backend, state)\nend\n\nfunction test_softlabel_softmax_loss_layer(backend::Backend, T, eps)\n  for i in [2,4,5]\n    test_softlabel_softmax_loss_layer(backend, i, T, eps)\n  end\nend\nfunction test_softlabel_softmax_loss_layer(backend::Backend)\n  test_softlabel_softmax_loss_layer(backend, Float64, 1e-5)\n  test_softlabel_softmax_loss_layer(backend, Float32, 1e-3)\nend\nif test_cpu\n  test_softlabel_softmax_loss_layer(backend_cpu)\nend\nif test_gpu\n  test_softlabel_softmax_loss_layer(backend_gpu)\nend\n", "meta": {"hexsha": "69fd400664c8054654b28090024584ffe3fe3a7a", "size": 2393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/layers/softlabel-softmax-loss.jl", "max_stars_repo_name": "jeff-regier/Latte.jl", "max_stars_repo_head_hexsha": "bf69d21594dad3f8e568c1e5056eac2d906bd327", "max_stars_repo_licenses": ["MIT"], "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/layers/softlabel-softmax-loss.jl", "max_issues_repo_name": "jeff-regier/Latte.jl", "max_issues_repo_head_hexsha": "bf69d21594dad3f8e568c1e5056eac2d906bd327", "max_issues_repo_licenses": ["MIT"], "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/layers/softlabel-softmax-loss.jl", "max_forks_repo_name": "jeff-regier/Latte.jl", "max_forks_repo_head_hexsha": "bf69d21594dad3f8e568c1e5056eac2d906bd327", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-09T06:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T06:41:05.000Z", "avg_line_length": 31.9066666667, "max_line_length": 93, "alphanum_fraction": 0.7137484329, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7732002407179267}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.0\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d44f3f70-705b-43a2-85c0-a441e08fbbe6\nload(\"Pydata_Jeddah_22_new-06.png\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2877f488-1ab3-46da-8a49-7db65c3d8a45\nmd\"\"\"\n## Objective\nThe goal of this exercise is to cluster \ud835\udc5b cities into \ud835\udc58 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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  \ud835\udc43  for a group is simply the total population of the 20 cities divided by 3:\n\"\"\"\n\n# \u2554\u2550\u2561 0a9212cd-4c79-4752-930b-45dce6a1f3e8\nbegin\n\tn = size(cities,1)\n\tk = 3\n\tP = sum(cities.population) / k\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3e708ffa-05d9-4cf7-ba4c-11ca5a3e43e7\ndm = Distances.pairwise(Haversine(6372.8), Matrix(cities[:, [3,4]])', dims=2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6bc42cc7-e3d4-4470-bece-6af950280372\ndm2 = LowerTriangular(dm)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d5fc7ca7-33cd-4f8a-aecf-8897bcd40e15\nbegin\n\t\u03b1 = -2_500_000\n\t\u03b2 = 2_500_000\n\tfor i in 1:k\n\t    @constraint(model, (x' * cities.population)[i] - P <= \u03b2)\n\t    @constraint(model, (x' * cities.population)[i] - P >= \u03b1)\n\tend\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 17088a0b-a568-431c-8d01-13f957e2a4c0\nbegin\n\t@objective(model, Min, dot(z,dm));\n\t\n\toptimize!(model)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a2fad4bc-66fa-4466-ae29-b495590f035f\nload(\"output.png\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500d44f3f70-705b-43a2-85c0-a441e08fbbe6\n# \u255f\u2500a12d1135-ce89-414c-866e-14b4415e1990\n# \u255f\u2500d35c109a-e5b6-4c01-a9c2-333b883783f2\n# \u2560\u25502d6d0588-f4e4-4cad-8353-9c0ba020fec6\n# \u255f\u25002877f488-1ab3-46da-8a49-7db65c3d8a45\n# \u2560\u2550cf6d3f77-781d-4cd0-ad45-9c5c58380354\n# \u255f\u250011c8323a-9cd5-4580-93d9-ebcd085b4551\n# \u2560\u25500a9212cd-4c79-4752-930b-45dce6a1f3e8\n# \u255f\u25007f7439d3-3d3b-4098-8be5-ca9aa59373ce\n# \u2560\u25503e708ffa-05d9-4cf7-ba4c-11ca5a3e43e7\n# \u255f\u250054082ac4-c31d-4d27-9cc3-5248018c6838\n# \u2560\u25506bc42cc7-e3d4-4470-bece-6af950280372\n# \u255f\u2500a5f3abe7-a843-4ea5-8e77-dfd075b243a5\n# \u2560\u2550ee41a6b3-fb13-4269-ab22-ad2a85bf26e5\n# \u255f\u2500dd262e8b-4697-4aa7-9bc7-a32ac25c96dc\n# \u2560\u2550d5fc7ca7-33cd-4f8a-aecf-8897bcd40e15\n# \u255f\u25004ab84877-f5d8-4c1b-b0d2-346f0048bb20\n# \u2560\u25501054b6a4-1c28-46b6-88a4-6f7cae84edee\n# \u255f\u250007f58656-4826-4ce5-8c97-bf5570f0fc60\n# \u2560\u255017088a0b-a568-431c-8d01-13f957e2a4c0\n# \u255f\u25004ded521e-c41f-4927-854b-86f8912269db\n# \u2560\u2550dab4e559-9dc6-4a72-8d38-9a0487b6251a\n# \u255f\u2500aa340dc7-8833-4e40-b63e-c602096e40e3\n# \u255f\u2500a2fad4bc-66fa-4466-ae29-b495590f035f\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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\u03c6_i = \u27e8 b_i, f \u27e9\n= \u222b_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    \u03c6 = V(undef, N)\n    galerkin_projection!(f, \u03c6, B, deriv)\nend\n\n\"\"\"\n    galerkin_projection!(\n        f, \u03c6::AbstractVector, B::AbstractBSplineBasis, [deriv = Derivative(0)],\n    )\n\nCompute Galerkin projection ``\u03c6_i = \u27e8 b_i, f \u27e9``.\n\nSee [`galerkin_projection`](@ref) for details.\n\"\"\"\nfunction galerkin_projection!(\n        f, \u03c6::AbstractVector, B::AbstractBSplineBasis, deriv = Derivative(0),\n    )\n    N = length(B)\n    if length(\u03c6) != N\n        throw(DimensionMismatch(\"incorrect length of output vector \u03c6\"))\n    end\n    Base.require_one_based_indexing(\u03c6)\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!(\u03c6, 0)\n\n    nlast = last(eachindex(ts))\n\n    # We loop over all knot segments \u03a9[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 \u03c6[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 \u2208 [tn, tn1]\n        xs = metric .* quadx\n        # @assert all(x -> tn \u2264 x \u2264 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) \u2264 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            \u03c6[i] += metric.\u03b1 * ((bs .* fs) \u22c5 quadw)\n        end\n    end\n\n    \u03c6\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": "using Test\nusing Statistics\nusing DelimitedFiles\nusing Dates\n\n\n@testset \"nse\" begin\n        for i in 1: 1000\n                Observed_Discharge = rand(5:0.5:80, 1000)\n                Modelled_Discharge = rand(5:0.5:80, 1000)\n                Mean_Observed_Discharge = ones(1000) * mean(Observed_Discharge)\n                Nominator = sum((Modelled_Discharge - Observed_Discharge).^2)\n                Denominator = sum((Observed_Discharge - Mean_Observed_Discharge).^2)\n                NSE = 1 - Nominator / Denominator\n                @test NSE == nse(Observed_Discharge, Modelled_Discharge)\n                # observed is the same as modelled\n                Modelled_Discharge = Observed_Discharge\n                @test nse(Observed_Discharge, Modelled_Discharge) == 1\n        end\nend\n\n\n@testset \"nselog\" begin\n        for i in 1: 1000\n                Observed_Discharge = rand(5:0.5:80, 1000)\n                Modelled_Discharge = rand(5:0.5:80, 1000)\n                Mean_Observed_Discharge = ones(1000) * mean(Observed_Discharge)\n                Nominator = sum((log.(Modelled_Discharge) - log.(Observed_Discharge)).^2)\n                Denominator = sum((log.(Observed_Discharge) - log.(Mean_Observed_Discharge)).^2)\n                NSE = 1 - Nominator / Denominator\n                @test NSE == lognse(Observed_Discharge, Modelled_Discharge)\n                # observed is the same as modelled\n                Modelled_Discharge = Observed_Discharge\n                @test lognse(Observed_Discharge, Modelled_Discharge) == 1\n        end\nend\n\n\n@testset \"VE\" begin\n        for i in 1: 10000\n                Observed_Discharge = rand(5:0.5:80, 1000)\n                Modelled_Discharge = rand(5:0.5:80, 1000)\n                Nominator = sum(abs.(Modelled_Discharge - Observed_Discharge))\n                Denominator = sum(Observed_Discharge)\n                VE = 1 - Nominator / Denominator\n                @test VE == volumetricefficiency(Observed_Discharge, Modelled_Discharge)\n                # observed is the same as modelled\n                Modelled_Discharge = Observed_Discharge\n                @test volumetricefficiency(Observed_Discharge, Modelled_Discharge) == 1\n        end\nend\n\n@testset \"FDC\" begin\n        for i in 1:1000\n                Discharge = rand(5:0.5:80, 1000)\n                SortedQ = sort(Discharge, rev = true)\n                Rank = collect(1 : length(Discharge))\n                @test minimum(Discharge) == SortedQ[end]\n                @test maximum(Discharge) == SortedQ[1]\n                Exceedance = Rank / (length(Discharge) + 1)\n                SortedQ_Function, Exceedance_Function = flowdurationcurve(Discharge)\n                @test Exceedance == Exceedance_Function\n                @test SortedQ == SortedQ_Function\n        end\nend\n\n@testset \"autocorrelation\" begin\n        for i in 1:1000\n                Discharge = rand(5:0.5:80, 1000)\n                Timelag = 1\n                Discharge_1 = Discharge[1 + Timelag: end]\n                Discharge_0 = Discharge[1: end - Timelag]\n                Mean_Discharge = ones(length(Discharge_0)) * mean(Discharge_0)\n                Nominator = sum((Discharge_0 - Mean_Discharge) .* (Discharge_1 - Mean_Discharge))\n                Denominator = sum((Discharge_0 - Mean_Discharge).^2)\n                Correlation = Nominator / Denominator\n                @test round(Correlation, digits=12) == round(autocorrelation(Discharge, Timelag), digits=12)\n                #@test round(Correlation, digits=12) == round(autocorrelation2(Discharge, Timelag), digits = 12)\n                # if timelag is zero correlation should be one\n                Timelag = 0\n                @test 1 == autocorrelation(Discharge, Timelag)\n                #@test 1 == autocorrelation2(Discharge, Timelag)\n        end\nend\n\n@testset \"autocorrelationcurve\" begin\n        for i in 1: 1000\n                Discharge = rand(5:0.5:80, 1000)\n                Timelag = 30\n                Discharge_0 = Discharge[1 : end - Timelag]\n                Discharge_0_Shift = Discharge[1 + Timelag : end]\n                Mean_Discharge = ones(length(Discharge_0)) * mean(Discharge_0)\n                AC = zeros(Timelag + 1)\n                AC_cor = zeros(Timelag + 1)\n                count = 0\n                count_large = 0\n                for i in 0 : Timelag\n                        Discharge_1 = Discharge[1 + i : end - Timelag + i]\n                        Discharge_1_shift = Discharge[1 + Timelag - i : end - i]\n                        Nominator = sum((Discharge_0 - Mean_Discharge) .* (Discharge_1 - Mean_Discharge))\n                        Denominator = sum((Discharge_0 - Mean_Discharge).^2)\n                        AC[i + 1] = Nominator / Denominator\n                        @test AC[1] >= AC[i + 1]\n                        if i > 0 && AC[i + 1] <= AC[i]\n                                count += 1\n                        elseif i > 0 && AC[i + 1] > AC[i]\n                                count_large += 1\n                        end\n                        # for other function\n                        AC_cor[i + 1] = cor(Discharge_0_Shift, Discharge_1_shift)\n                end\n                Lags = collect(0:Timelag)\n                #@test count >= count_large\n                AC_Function, Lags_Function = autocorrelationcurve(Discharge, Timelag)\n                @test AC == AC_Function\n                @test Lags == Lags_Function\n                #test other function\n                # AC_Function, Lags_Function = autocorrelationcurve(Discharge, Timelag)\n                # @test AC_cor == AC_Function\n                # @test Lags == Lags_Function\n        end\nend\n\n\n@testset \"runoff\" begin\n        for i in 1 :100\n                Area = rand(50.:5.:500.)[1]\n                Timespan = 1096\n                Precipitation = rand(5:0.5:80, Timespan)\n                Discharge = rand(5:0.5:80, Timespan)\n                Timeseries = readdlm(\"Defreggental/tas_model_timeseries.txt\")[1 : Timespan]\n                Timeseries_DateFormat = Date.(Timeseries, dateformat\"y,m,d\")\n                Runoff_1 = sum(Discharge[1:31]) / Area * (1000 * 3600 * 24) / sum(Precipitation[1:31])\n                Runoff_2 = sum(Discharge[32:59]) / Area * (1000 * 3600 * 24) / sum(Precipitation[32:59])\n                Runoff_Function, Month = monthlyrunoff(Area, Precipitation, Discharge,Timeseries_DateFormat)\n                @test round(Runoff_Function[1], digits= 6) == round(Runoff_1, digits = 6)\n                @test round(Runoff_Function[2], digits= 6) == round(Runoff_2, digits = 6)\n\n                Runoff_mean_yearly = averagemonthlyrunoff(Area, Precipitation, Discharge,Timeseries_DateFormat)\n                Runoff_51 = sum(Discharge[366: 366+30]) / Area * (1000 * 3600 * 24) / sum(Precipitation[366 : 30 + 366])\n                Runoff_52 = sum(Discharge[731: 731+30]) / Area * (1000 * 3600 * 24) / sum(Precipitation[731: 30 + 731])\n                meanRunoff = mean([Runoff_1 Runoff_51 Runoff_52])\n                @test round(meanRunoff, digits=5) == round(Runoff_mean_yearly[1], digits=5)\n\n                # if Precipitation is equal to Discharge than Runoff = 1\n                Timespan = 31\n                Precipitation = rand(5:0.5:80, Timespan)\n                Discharge = rand(5:0.5:80, Timespan)\n                Timeseries = readdlm(\"Defreggental/tas_model_timeseries.txt\")[1 : Timespan]\n                Timeseries_DateFormat = Date.(Timeseries, dateformat\"y,m,d\")\n                Discharge = Precipitation * Area / (1000 * 3600 * 24)\n                Runoff_Function, Month = monthlyrunoff(Area, Precipitation, Discharge,Timeseries_DateFormat)\n                @test Runoff_Function[1] == 1.0\n\n                # calculate yearly mean runoff\n        end\n\nend\n", "meta": {"hexsha": "f16878e5335769d6ec943f5b4aff994e467c6559", "size": 7708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Test/Test_Objectives.jl", "max_stars_repo_name": "sarah-hanus/hbv-mountain", "max_stars_repo_head_hexsha": "bba8b06b311dec3fcdca77179eef2751dd548255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-08T12:26:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T20:52:55.000Z", "max_issues_repo_path": "Test/Test_Objectives.jl", "max_issues_repo_name": "sarah-hanus/hbv-mountain", "max_issues_repo_head_hexsha": "bba8b06b311dec3fcdca77179eef2751dd548255", "max_issues_repo_licenses": ["MIT"], "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_Objectives.jl", "max_forks_repo_name": "sarah-hanus/hbv-mountain", "max_forks_repo_head_hexsha": "bba8b06b311dec3fcdca77179eef2751dd548255", "max_forks_repo_licenses": ["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.4779874214, "max_line_length": 120, "alphanum_fraction": 0.5551375195, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.77315603470102}}
{"text": "using Test\nusing OrdinaryDiffEq\nusing SparseArrays\nusing LinearAlgebra\n\n#https://github.com/JuliaDiffEq/SparseDiffTools.jl/blob/master/test/test_integration.jl\nfunction f(dx,x,p,t)\n    for i in 2:length(x)-1\n      dx[i] = x[i-1] - 2x[i] + x[i+1]\n    end\n    dx[1] = -2x[1] + x[2]\n    dx[end] = x[end-1] - 2x[end]\n    nothing\n  end\n\nfunction second_derivative_stencil(N)\n  A = zeros(N,N)\n  for i in 1:N, j in 1:N\n    (j-i==-1 || j-i==1) && (A[i,j]=1)\n    j-i==0 && (A[i,j]=-2)\n  end\n  A\nend\n\nfunction generate_sparsity_pattern(N::Integer)\n  dl = repeat([1.0],N-1)\n  du = repeat([1.0],N-1)\n  d = repeat([-2.0],N)\n  return Tridiagonal(dl,d,du)\nend\n\njac_sp = sparse(generate_sparsity_pattern(10))\n#jac = second_derivative_stencil(10)\ncolors = repeat(1:3,10)[1:10]\nu0=[1.,2.,3,4,5,5,4,3,2,1]\ntspan=(0.,10.)\nodefun_sp= ODEFunction(f,colorvec=colors,jac_prototype=jac_sp)\nprob_sp = ODEProblem(odefun_sp,u0,tspan)\nprob_std = ODEProblem(f,u0,tspan)\n\nsol_sp=solve(prob_sp,Rodas5(autodiff=false),abstol=1e-10,reltol=1e-10)\n@test sol_sp.retcode==:Success#test sparse finitediff\nsol=solve(prob_std,Rodas5(autodiff=false),abstol=1e-10,reltol=1e-10)\n@test sol_sp.u[end]\u2248sol.u[end] atol=1e-10\n@test length(sol_sp.t)==length(sol.t)\n\nsol_sp=solve(prob_sp,Rodas5(autodiff=false))\nsol=solve(prob_std,Rodas5(autodiff=false))\n@test sol_sp.u[end]\u2248sol.u[end]\n@test length(sol_sp.t)==length(sol.t)\n\nsol_sp=solve(prob_sp,Rodas5())\nsol=solve(prob_std,Rodas5())\n@test sol_sp.u[end]\u2248sol.u[end]\n@test length(sol_sp.t)==length(sol.t)", "meta": {"hexsha": "9deac6f7aed3a08a899395e1c327b2accd77dd8a", "size": 1502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interface/sparsediff_tests.jl", "max_stars_repo_name": "jlumpe/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "2749f37186f0dce04fbe9351571a11364426f51f", "max_stars_repo_licenses": ["MIT"], "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/interface/sparsediff_tests.jl", "max_issues_repo_name": "jlumpe/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "2749f37186f0dce04fbe9351571a11364426f51f", "max_issues_repo_licenses": ["MIT"], "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/sparsediff_tests.jl", "max_forks_repo_name": "jlumpe/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "2749f37186f0dce04fbe9351571a11364426f51f", "max_forks_repo_licenses": ["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.3090909091, "max_line_length": 87, "alphanum_fraction": 0.6924101198, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7731560309594844}}
{"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\u00b2(x\u20d7, y\u20d7) = sum((x\u20d7 - y\u20d7).^2)\nd\u2032(x\u20d7\u1d62, x\u20d7\u2c7c, n\u1d62, n\u2c7c) = ((n\u1d62 * n\u2c7c) / (n\u1d62 + n\u2c7c)) * sum((x\u20d7\u1d62 - x\u20d7\u2c7c).^2)\n\nT = 2 # C\n\nfor t = 1:T\n    D = [i<j ? d\u2032(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\u00b2(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": "@testset \"linear complementarity problem\" begin\n    M = [0  0 -1 -1 ;\n         0  0  1 -2 ;\n         1 -1  2 -2 ;\n         1  2 -2  4 ]\n\n    q = [2; 2; -2; -6]\n\n    myfunc(x) = M*x + q\n\n    n = 4\n    lb = zeros(n)\n    ub = 100*ones(n)\n\n    status, z, f = solveLCP(myfunc, M, lb, ub)\n    @show status\n    @show z\n    @show f\n    @test isapprox(z, [2.8, 0.0, 0.8, 1.2])\n    @test status == :Solved\n\n    status, z, f = solveLCP(myfunc, lb, ub)\n    @show status\n    @show z\n    @show f\n    @test isapprox(z, [2.8, 0.0, 0.8, 1.2])\n    @test status == :Solved\n\n\n    println(\"-------------------------------------------------------\")\n\n\n    M = [0  0 -1 -1 ;\n         0  0  1 -2 ;\n         1 -1  2 -2 ;\n         1  2 -2  4 ]\n\n    q = [2; 2; -2; -6]\n\n    myfunc(x) = M*x + q\n\n    n = 4\n    lb = zeros(n)\n    ub = 100*ones(n)\n\n    options(convergence_tolerance=1e-2, output=:no, time_limit=3600)\n\n    status, z, f = solveLCP(myfunc, M, lb, ub)\n    @show status\n    @show z\n    @show f\n    @test isapprox(z, [2.8, 0.0, 0.8, 1.2])\n    @test status == :Solved\n\n    status, z, f = solveLCP(myfunc, lb, ub)\n    @show status\n    @show z\n    @show f\n    @test isapprox(z, [2.8, 0.0, 0.8, 1.2])\n    @test status == :Solved\n\n\n\n    println(\"-------------------------------------------------------\")\n\n\n    function elemfunc(x)\n        val = similar(x)\n        val[1] = -x[3]-x[4] + q[1]\n        val[2] = x[3] -2x[4] + q[2]\n        val[3] = x[1]-x[2]+2x[3]-2x[4] + q[3]\n        val[4] = x[1]+2x[2]-2x[3]+4x[4] + q[4]\n        return val\n    end\n\n    n = 4\n    lb = zeros(n)\n    ub = 100*ones(n)\n\n    var_name = [\"x1\", \"x2\", \"x3\", \"x4\"]\n    con_name = [\"F1\", \"F2\", \"F3\", \"F4\"]\n\n    options(convergence_tolerance=1e-2, output=:yes, time_limit=3600)\n\n    status, z, f = solveLCP(elemfunc, M, lb, ub)\n    status, z, f = solveLCP(elemfunc, M, lb, ub, var_name)\n    status, z, f = solveLCP(elemfunc, M, lb, ub, var_name, con_name)\n    status, z, f = solveLCP(elemfunc, lb, ub)\n    status, z, f = solveLCP(elemfunc, lb, ub, var_name)\n    status, z, f = solveLCP(elemfunc, lb, ub, var_name, con_name)\n\n    @show status\n    @show z\n    @show f\n\n\n    @test isapprox(z, [2.8, 0.0, 0.8, 1.2])\n    @test status == :Solved\nend\n", "meta": {"hexsha": "c47e1da70d62eb62e260299eb320f4b48b970c36", "size": 2190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/lcp.jl", "max_stars_repo_name": "chrished/PATH2.jl", "max_stars_repo_head_hexsha": "06a79ebe4b78a9498c9f81916d49381eff78dbb3", "max_stars_repo_licenses": ["MIT"], "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/lcp.jl", "max_issues_repo_name": "chrished/PATH2.jl", "max_issues_repo_head_hexsha": "06a79ebe4b78a9498c9f81916d49381eff78dbb3", "max_issues_repo_licenses": ["MIT"], "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/lcp.jl", "max_forks_repo_name": "chrished/PATH2.jl", "max_forks_repo_head_hexsha": "06a79ebe4b78a9498c9f81916d49381eff78dbb3", "max_forks_repo_licenses": ["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.9, "max_line_length": 70, "alphanum_fraction": 0.4675799087, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7731004147819172}}
{"text": "using Derivatives, InplaceRealFFT\nusing LESFilter: rfftfreq, fftfreq\nusing Base.Test\n\n#=\nTest function: f = sin(3x)*cos(3y)*sin(4z)\n=#\nfor (lx,ly,lz) in ((1.,1.,1.),(2.,2.,2.),(3.,3.,3.))\n\n# lx = 1.0\n# ly = 1.0\n# lz = 1.0\n\nnx = 32\nny = 32\nnz = 32\n\nx = reshape(linspace(0,lx*2\u03c0*(1-1/nx),nx),(nx,1,1))\ny = reshape(linspace(0,ly*2\u03c0*(1-1/ny),ny),(1,ny,1))\nz = reshape(linspace(0,lz*2\u03c0*(1-1/nz),nz),(1,1,nz))\n\nfield = @. sin(3*x) * cos(3*y) * sin(4*z) \n\ncorrect(f::typeof(Derivatives.dx)) = @. 3*cos(3*x) * cos(3*y) * sin(4*z) \ncorrect(f::typeof(Derivatives.dy)) = @. sin(3*x) * -3*sin(3*y) * sin(4*z)\ncorrect(f::typeof(Derivatives.dz)) = @. sin(3*x) * cos(3*y) * 4*cos(4*z)\n\ncorrect2(f::typeof(Derivatives.dx)) = @. -9*sin(3*x) * cos(3*y) * sin(4*z) \ncorrect2(f::typeof(Derivatives.dy)) = @. sin(3*x) * -9*cos(3*y) * sin(4*z)\ncorrect2(f::typeof(Derivatives.dz)) = @. sin(3*x) * cos(3*y) * -16*sin(4*z)\n\ncorrect3(f::typeof(Derivatives.dx)) = @. -27*cos(3*x) * cos(3*y) * sin(4*z) \ncorrect3(f::typeof(Derivatives.dy)) = @. sin(3*x) * 27*sin(3*y) * sin(4*z)\ncorrect3(f::typeof(Derivatives.dz)) = @. sin(3*x) * cos(3*y) * -64*cos(4*z)\n\n\nfor (c,n) in zip((correct,correct2,correct3),(1,2,3))\n  for (f,l) in zip((Derivatives.dx,Derivatives.dy,Derivatives.dz),(lx,ly,lz))\n    @test f(field,l,n) \u2248 c(f)\n  end\nend\n\nfield2 = PaddedArray(field)\n\nfor (c,n) in zip((correct,correct2,correct3),(1,2,3))\n  for (f,l) in zip((Derivatives.dx,Derivatives.dy,Derivatives.dz),(lx,ly,lz))\n    @test real(f(field,l,n)) \u2248 c(f)\n  end\nend\n\nrfft!(field2)\n\n@inferred Derivatives.loopdx!(complex(field2),rfftfreq(nx,lx))\n@inferred Derivatives.loopdy!(complex(field2),fftfreq(ny,ly))\n@inferred Derivatives.loopdz!(complex(field2),fftfreq(nz,lz))\n\nend", "meta": {"hexsha": "932ca4c1d2d3afdcc20d9a84ab0173d3de1ecbdf", "size": 1716, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "favba/Derivatives.jl", "max_stars_repo_head_hexsha": "de6ce83c7c8331f5645753cd8a1051c5d4660eb6", "max_stars_repo_licenses": ["MIT"], "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": "favba/Derivatives.jl", "max_issues_repo_head_hexsha": "de6ce83c7c8331f5645753cd8a1051c5d4660eb6", "max_issues_repo_licenses": ["MIT"], "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": "favba/Derivatives.jl", "max_forks_repo_head_hexsha": "de6ce83c7c8331f5645753cd8a1051c5d4660eb6", "max_forks_repo_licenses": ["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.1052631579, "max_line_length": 77, "alphanum_fraction": 0.6194638695, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7731004109162167}}
{"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 ``\u03f5`` 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    \u03c1,I,\u03c3,\u03c4 = estimate_img_properties(img)\r\n    \u03bb=smoothness\r\n    return retrieve_surface(DiscreteShape(), img, \u03c1, I, iterations, smoothness=\u03bb)\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    \u03c1 = 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(\u03c1, 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": "@testset \"Numerical integral\" begin\n    gl1 = BasicBSpline.GaussLegendre(1)\n    gl2 = BasicBSpline.GaussLegendre(2)\n    gl3 = BasicBSpline.GaussLegendre(3)\n    gl4 = BasicBSpline.GaussLegendre(4)\n\n    I = 2..8\n    coef = rand(10)\n\n    f(n,x) = sum(coef[i]*x^(i-1) for i in 1:n)\n    F(n,x) = sum(coef[i]*x^(i)/i for i in 1:n)\n\n    @test F(1,maximum(I)) - F(1,minimum(I)) \u2248 BasicBSpline.integrate(x->f(1,x), I, gl1)\n    @test F(2,maximum(I)) - F(2,minimum(I)) \u2248 BasicBSpline.integrate(x->f(2,x), I, gl1)\n    @test F(3,maximum(I)) - F(3,minimum(I)) \u2248 BasicBSpline.integrate(x->f(3,x), I, gl2)\n    @test F(4,maximum(I)) - F(4,minimum(I)) \u2248 BasicBSpline.integrate(x->f(4,x), I, gl2)\n    @test F(5,maximum(I)) - F(5,minimum(I)) \u2248 BasicBSpline.integrate(x->f(5,x), I, gl3)\n    @test F(6,maximum(I)) - F(6,minimum(I)) \u2248 BasicBSpline.integrate(x->f(6,x), I, gl3)\n    @test F(7,maximum(I)) - F(7,minimum(I)) \u2248 BasicBSpline.integrate(x->f(7,x), I, gl4)\n    @test F(8,maximum(I)) - F(8,minimum(I)) \u2248 BasicBSpline.integrate(x->f(8,x), I, gl4)\nend\n", "meta": {"hexsha": "a087929f96b7373e1105cba59253c107e5e85fdb", "size": 1034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 47.0, "max_line_length": 87, "alphanum_fraction": 0.6083172147, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7730247390156666}}
{"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 = [\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]),\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 0, 1, 0, 0, 0, 0, 1]),\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 1, 0]),\n  Dict(\"N\" => 10, \"y\" => [0, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n]\n\n# Keep tmpdir identical across multiple runs to prevent re-compilation\nstanmodel = SampleModel(\n  \"bernoulli\", bernoulli_model;\n  method =  StanSample.Sample(adapt=StanSample.Adapt(delta=0.85)))\n\nrc = stan_sample(stanmodel, data=bernoulli_data)\n\nif success(rc)\n\n  # Fetch the same output in the `sdf` ChainDataFrame\n  sdf = read_summary(stanmodel)\n\n  @test sdf[sdf.parameters .== :theta, :mean][1] \u2248 0.33 rtol=0.05\n  \nend", "meta": {"hexsha": "67e20002dfb78053314e89ff74012616e53f275f", "size": 921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_basic_runs/test_bernoulli_array_dict_1.jl", "max_stars_repo_name": "Vaibhavdixit02/StanSample.jl", "max_stars_repo_head_hexsha": "2b2820fe3471bae53e5d7f46ac0956680ed1f61d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-01-25T10:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T16:03:11.000Z", "max_issues_repo_path": "test/test_basic_runs/test_bernoulli_array_dict_1.jl", "max_issues_repo_name": "Vaibhavdixit02/StanSample.jl", "max_issues_repo_head_hexsha": "2b2820fe3471bae53e5d7f46ac0956680ed1f61d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2019-07-22T20:04:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T17:47:20.000Z", "max_forks_repo_path": "test/test_basic_runs/test_bernoulli_array_dict_1.jl", "max_forks_repo_name": "Vaibhavdixit02/StanSample.jl", "max_forks_repo_head_hexsha": "2b2820fe3471bae53e5d7f46ac0956680ed1f61d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:32:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T06:15:00.000Z", "avg_line_length": 23.025, "max_line_length": 70, "alphanum_fraction": 0.5830618893, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341962906709, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7730247227532877}}
{"text": "using LinearAlgebra\n\nconst n = 8\na, b = legendre_coefs(Float64, n)\n\nTn = SymTridiagonal(copy(a), b[2:n])\nF = eigen(Tn)\n\nv = zeros(n)\nspecial_eigenproblem!(a, b, v, 30)\n\nidx = sortperm(a)\n@test a[idx] \u2248 F.values\n@test abs.(v[idx]) \u2248 abs.(F.vectors[1,:])\n", "meta": {"hexsha": "da401c951efc5de98628ffe7c8b2a511770398a1", "size": 253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_eigen.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/test_eigen.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/test_eigen.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": 16.8666666667, "max_line_length": 41, "alphanum_fraction": 0.6442687747, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7730144028704201}}
{"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) \u2a7d 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 \u21a6 0 if rank(x) \u2a7d r, +\u221e 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 \u03c3x, \u03c3y, \u03c3z, \ud835\udfd9, up, down, \u2297, speye, identity_op, single_spin_op, correlator, op_list, symmetrize_state, symmetrize_op, nspins\n\n\nconst \u03c3x = sparse([0 1; 1 0])\nconst \u03c3y = sparse([0 -im; im 0])\nconst \u03c3z = sparse([1 0; 0 -1])\nconst \ud835\udfd9 = spdiagm([1, 1])\n\nconst up = [1,0]\nconst down = [0,1]\n\nconst \u2297 = 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) \u2297 op \u2297 identity_op(N-k)\ncorrelator(op, i::Integer, j::Integer, N::Integer) = i > j ? correlator(op, j, i, N) : identity_op(i-1) \u2297 op \u2297 identity_op(j-i-1) \u2297 op \u2297 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\u2013420. 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, \u03bc, M2) = st\n        n += 1\n        \u03b4 = input - \u03bc\n        \u03bc += \u03b4/n\n        \u03b42 = input - \u03bc\n        M2 += \u03b4*\u03b42\n        iinput = (\u03bc, M2 / (n-1))\n        iresult = next(inner(rf), iresult, iinput)\n        return (n, \u03bc, 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": "module ReactiveMPModelsLGSSMTest\n\nusing Test, InteractiveUtils\nusing Rocket, ReactiveMP, GraphPPL, Distributions\nusing BenchmarkTools, Random, Plots, Dates, LinearAlgebra, StableRNGs\n\n## Model definition\n## -------------------------------------------- ##\n@model function univariate_lgssm_model(n, x0, c_, P_)\n\n    x_prior ~ NormalMeanVariance(mean(x0), cov(x0)) \n\n    x = randomvar(n)\n    c = constvar(c_)\n    P = constvar(P_)\n    y = datavar(Float64, n)\n    \n    x_prev = x_prior\n    \n    for i in 1:n\n        x[i] ~ x_prev + c\n        y[i] ~ NormalMeanVariance(x[i], P)\n        x_prev = x[i]\n    end\n\n    return x, y\nend\n## -------------------------------------------- ##\n@model function multivariate_lgssm_model(n, x0, A, B, Q, P)\n    \n    # We create constvar references for better efficiency\n    cA = constvar(A)\n    cB = constvar(B)\n    cQ = constvar(Q)\n    cP = constvar(P)\n    \n    # `x` is a sequence of hidden states\n    x = randomvar(n)\n    # `y` is a sequence of \"clamped\" observations\n    y = datavar(Vector{Float64}, n)\n    \n    x_prior ~ MvNormalMeanCovariance(mean(x0), cov(x0))\n    x_prev = x_prior\n    \n    for i in 1:n\n        x[i] ~ MvNormalMeanCovariance(cA * x_prev, cQ)\n        y[i] ~ MvNormalMeanCovariance(cB * x[i], cP)\n        x_prev = x[i]\n    end\n    \n    return x, y\nend\n## -------------------------------------------- ##\n## Inference definition\n## -------------------------------------------- ##\nfunction univariate_lgssm_inference(data, x0, c, P)\n    n = length(data)\n\n    model, (x, y) = univariate_lgssm_model(n, x0, c, P);\n    \n    x_buffer = buffer(Marginal, n)\n    fe       = keep(Float64)\n\n    x_sub = subscribe!(getmarginals(x), x_buffer)\n    f_sub = subscribe!(score(Float64, BetheFreeEnergy(), model), fe)\n    \n    update!(y, data)\n    \n    unsubscribe!((x_sub, f_sub))\n    \n    return x_buffer, fe\nend\n## -------------------------------------------- ##\nfunction multivariate_lgssm_inference(data, x0, A, B, Q, P)\n    n = length(data)\n\n    model, (x, y) = multivariate_lgssm_model(n, x0, A, B, Q, P, options = (limit_stack_depth = 100, ));\n\n    xbuffer = buffer(Marginal, n)\n    fe      = keep(Float64)\n\n    x_sub = subscribe!(getmarginals(x), xbuffer)\n    f_sub  = subscribe!(score(Float64, BetheFreeEnergy(), model), fe)\n\n    update!(y, data)\n\n    unsubscribe!((x_sub, f_sub))\n    \n    return xbuffer, fe\nend\n## -------------------------------------------- ##\n\n@testset \"Linear Gaussian State Space Model\" begin\n\n    @testset \"Univariate\" begin \n        ## -------------------------------------------- ##\n        ## Data creation\n        ## -------------------------------------------- ##\n        rng = StableRNG(123)\n        P   = 100.0\n        n   = 500\n        hidden   = collect(1:n)\n        data     = hidden + rand(rng, Normal(0.0, sqrt(P)), n);\n        x0_prior = NormalMeanVariance(0.0, 10000.0)\n        ## -------------------------------------------- ##\n        ## Inference execution\n        x_estimated, fe = univariate_lgssm_inference(data, x0_prior, 1.0, P);\n        ## -------------------------------------------- ##\n        ## Test inference results\n        @test length(x_estimated) === n\n        @test all((mean.(x_estimated) .- 3 .* std.(x_estimated)) .< hidden .< (mean.(x_estimated) .+ 3 .* std.(x_estimated)))\n        @test all(var.(x_estimated) .> 0.0)\n        @test length(fe) === 1\n        @test abs(last(fe) - 1854.297647) < 0.01\n        ## -------------------------------------------- ##\n        ## Form debug output\n        base_output = joinpath(pwd(), \"_output\", \"models\")\n        mkpath(base_output)\n        timestamp        = Dates.format(now(), \"dd-mm-yyyy-HH-MM\") \n        plot_output      = joinpath(base_output, \"lgssm_univariate_plot_$(timestamp)_v$(VERSION).png\")\n        benchmark_output = joinpath(base_output, \"lgssm_univariate_benchmark_$(timestamp)_v$(VERSION).txt\")\n        ## -------------------------------------------- ##\n        ## Create output plots\n        subrange = 200:215\n        m = mean.(x_estimated)[subrange]\n        s = std.(x_estimated)[subrange]\n        p = plot()\n        p = plot!(subrange, m, ribbon = s, label = \"Estimated signal\")\n        p = plot!(subrange, hidden[subrange], label = \"Hidden signal\")\n        p = scatter!(subrange, data[subrange], label = \"Observations\")\n        savefig(p, plot_output)\n        ## -------------------------------------------- ##\n        ## Create output benchmarks\n        benchmark = @benchmark univariate_lgssm_inference($data, $x0_prior, 1.0, $P) seconds=15\n        open(benchmark_output, \"w\") do io\n            show(io, MIME(\"text/plain\"), benchmark)\n            versioninfo(io)\n        end\n        ## -------------------------------------------- ##\n    end\n\n    @testset \"Multivariate\" begin \n        ## -------------------------------------------- ##\n        ## Data creation\n        ## -------------------------------------------- ##\n        function generate_data(rng, A, B, Q, P)\n            x_prev = [ 10.0, -10.0 ]\n        \n            x = Vector{Vector{Float64}}(undef, n)\n            y = Vector{Vector{Float64}}(undef, n)\n        \n            for i in 1:n\n                x[i] = rand(rng, MvNormal(A * x_prev, Q))\n                y[i] = rand(rng, MvNormal(B * x[i], P))\n                x_prev = x[i]\n            end\n            \n            return x, y\n        end\n        ## -------------------------------------------- ##\n        # Seed for reproducibility\n        rng = StableRNG(1234)\n        # We will model 2-dimensional observations with rotation matrix `A`\n        # To avoid clutter we also assume that matrices `A`, `B`, `P` and `Q`\n        # are known and fixed for all time-steps\n        \u03b8 = \u03c0 / 35\n        A = [ cos(\u03b8) -sin(\u03b8); sin(\u03b8) cos(\u03b8) ]\n        B = diageye(2)\n        Q = diageye(2)\n        P = 25.0 .* diageye(2)\n        n = 1_000 # Number of observations\n        x, y = generate_data(rng, A, B, Q, P)\n        x0 = MvNormalMeanCovariance(zeros(2), 100.0 * diageye(2));\n        ## -------------------------------------------- ##\n        ## Inference execution\n        xmarginals, fe = multivariate_lgssm_inference(y, x0, A, B, Q, P);\n        ## Test inference results\n        @test length(xmarginals) === n\n        # We use 3.0var instead of 3.0std here for easier dot broadcasting with mean\n        @test all((mean.(xmarginals) .- 3.0 .* var.(xmarginals)) .< x .< (mean.(xmarginals) .+ 3.0 .* var.(xmarginals))) \n        @test all(isposdef.(cov.(xmarginals)))\n        @test length(fe) === 1\n        @test abs(last(fe) - 6275.9015944677) < 0.01\n        ## -------------------------------------------- ##\n        ## Form debug output\n        base_output = joinpath(pwd(), \"_output\", \"models\")\n        mkpath(base_output)\n        timestamp        = Dates.format(now(), \"dd-mm-yyyy-HH-MM\") \n        plot_output      = joinpath(base_output, \"lgssm_multivariate_plot_$(timestamp)_v$(VERSION).png\")\n        benchmark_output = joinpath(base_output, \"lgssm_multivariate_benchmark_$(timestamp)_v$(VERSION).txt\")\n        ## -------------------------------------------- ##\n        ## Create output plots\n        slicedim(dim) = (a) -> map(e -> e[dim], a)\n\n        subrange = 100:500\n        px = plot()\n\n        px = plot!(px, x[subrange] |> slicedim(1), label = \"Hidden Signal (dim-1)\", color = :orange)\n        px = plot!(px, x[subrange] |> slicedim(2), label = \"Hidden Signal (dim-2)\", color = :green)\n\n        px = plot!(px, mean.(xmarginals)[subrange] |> slicedim(1), ribbon = var.(xmarginals)[subrange] |> slicedim(1) .|> sqrt, fillalpha = 0.5, label = \"Estimated Signal (dim-1)\", color = :teal)\n        px = plot!(px, mean.(xmarginals)[subrange] |> slicedim(2), ribbon = var.(xmarginals)[subrange] |> slicedim(2) .|> sqrt, fillalpha = 0.5, label = \"Estimated Signal (dim-1)\", color = :violet)\n\n        savefig(px, plot_output)\n        ## -------------------------------------------- ##\n        ## Create output benchmarks\n        benchmark = @benchmark multivariate_lgssm_inference($y, $x0, $A, $B, $Q, $P) seconds=15\n        open(benchmark_output, \"w\") do io\n            show(io, MIME(\"text/plain\"), benchmark)\n            versioninfo(io)\n        end\n        ## -------------------------------------------- ##\n    end\n\nend\n\nend", "meta": {"hexsha": "fedf870a33596ae0b849910933b8bd2e79d5c2f5", "size": 8201, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/models/test_lgssm.jl", "max_stars_repo_name": "HoangMHNguyen/ReactiveMP.jl", "max_stars_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415", "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": "test/models/test_lgssm.jl", "max_issues_repo_name": "HoangMHNguyen/ReactiveMP.jl", "max_issues_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415", "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": "test/models/test_lgssm.jl", "max_forks_repo_name": "HoangMHNguyen/ReactiveMP.jl", "max_forks_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415", "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": 37.7926267281, "max_line_length": 197, "alphanum_fraction": 0.4964028777, "num_tokens": 2219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7729871969292732}}
{"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} + \u0394t \\mathbf{K} \\mathbf{u}_{n+1} = \u0394t \\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} = \u0394t \\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\u0394t = 1\nT = 200\nch = ConstraintHandler(dh);\n\n# Here, we define the boundary condition related to $\\partial \\Omega_1$.\n\u2202\u03a9\u2081 = union(getfaceset.((grid, ), [\"left\", \"right\"])...)\ndbc = Dirichlet(:u, \u2202\u03a9\u2081, (x, t) -> 0)\nadd!(ch, dbc);\n# While the next code block corresponds to the linearly increasing temperature description on $\\partial \\Omega_2$.\n\u2202\u03a9\u2082 = union(getfaceset.((grid, ), [\"top\", \"bottom\"])...)\ndbc = Dirichlet(:u, \u2202\u03a9\u2082, (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\u03a9 = getdetJdV(cellvalues, q_point)\n\n            for i in 1:n_basefuncs\n                v  = shape_value(cellvalues, q_point, i)\n                \u2207v = shape_gradient(cellvalues, q_point, i)\n                fe[i] += v * d\u03a9\n                for j in 1:n_basefuncs\n                    \u2207u = shape_gradient(cellvalues, q_point, j)\n                    Ke[i, j] += (\u2207v \u22c5 \u2207u) * d\u03a9\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\u03a9 = 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 \u22c5 u) * d\u03a9\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 = (\u0394t .* 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\u2099,  to $\\mathbf{0}$.\nu\u2099 = 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:\u0394t: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 = \u0394t .* f .+ M * u\u2099\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\u2099 .= 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": "using jInv.Mesh;\r\nusing FactoredEikonalFastMarching;\r\n\r\ninclude(\"../examples/getAnalyticalMediums.jl\");\r\n\r\n\r\nfunction runSensitivityTest()\r\ntic()\r\nprintln(\"########### 2D TEST SETTING ##############################\");\r\nn = [100,100]\r\nOmega = [0.0,4.0,0.0,8.0];\r\nMsh = getRegularMesh(Omega,n-1);\r\n\r\n(kappaSquared,src,T_exact) = getAnalyticalConstGradInv2D(Msh.n+1,Msh.h);\r\nT0 = getAnalytic2DeikonalSolution(n,Msh.h,src)[1];\r\nprintln(\"First order test\");\r\ndoSensTest(kappaSquared,src,T_exact,Msh,T0,false);\r\nprintln(\"Second order test\");\r\ndoSensTest(kappaSquared,src,T_exact,Msh,T0,true);\r\n##########################################################\r\nprintln(\"########### 3D TEST SETTING ##############################\");\r\nn = [64,64,32]\r\nOmega = [0.0,1.0,0.0,1.0,0.0,0.5];\r\nMsh = getRegularMesh(Omega,n-1);\r\n(kappaSquared,src,T_exact) = getAnalyticalConstGradInv3D(Msh.n+1,Msh.h);\r\nT0 = getAnalytic3DeikonalSolution(n,Msh.h,src)[1];\r\nprintln(\"First order test\");\r\ndoSensTest(kappaSquared,src,T_exact,Msh,T0,false);\r\nprintln(\"Second order test\");\r\ndoSensTest(kappaSquared,src,T_exact,Msh,T0,true);\r\n\r\n##########################################################\r\ntoc()\r\nreturn;\r\nend\r\n\r\n\r\nfunction doSensTest(kappaSquared,src,T_exact,Msh,T0,HO)\r\nn = Msh.n+1;\r\npMem = getEikonalTempMemory(n);\r\npEik = getEikonalParam(Msh,kappaSquared,src,HO);\r\nsolveFastMarchingUpwindGrad(pEik,pMem);\r\nT = T0[:].*pEik.T1[:];\r\nprintln(\"Maximum error norm: \",maximum(abs((T_exact[:] - T))));\r\nprintln(\"Sensitivity Check:\");\r\ndelta_kappa = 0.05*randn(size(kappaSquared))*mean(kappaSquared[:]);\r\nTlin = zeros(prod(n));\r\nfor k = 1:10\r\n\tdelta_kappa *= 0.5;\r\n\tnew_kappa = kappaSquared + delta_kappa;\r\n\tpEikNew = getEikonalParam(Msh,new_kappa,src,HO);\r\n\tsolveFastMarchingUpwindGrad(pEikNew,pMem);\r\n\tgetSensMatVecEik(delta_kappa[:],Tlin,pEik);\r\n\tTlin += T;\r\n\tprint(\"||dm||: \");\r\n\tprint(norm(delta_kappa[:]))\r\n\tprint(\". ||T(m + dm) - T(m)|| \");\r\n\tTnew = T0[:].*pEikNew.T1[:];\r\n\terr0 = (T - Tnew);\r\n\tprint(norm(err0));\r\n\tprint(\". ||T(m + dm) - (T(m) + J*dm)||: \");\r\n\terr = Tnew - Tlin;\r\n\tprintln(norm(err));\r\n\t\r\nend\r\nv = rand(prod(n));\r\nJv = zeros(prod(n));\r\ngetSensMatVecEik(v,Jv,pEik);\r\nZ = rand(size(Jv));\r\nJtZ = rand(prod(n));\r\ngetSensTMatVecEik(Z,JtZ,pEik);\r\nif abs(dot(JtZ[:],v) - dot(Jv[:],Z[:])) > 1e-8\r\n\tprintln(\"Checking that (J^T)^T = J for eikonal solver falied: \",abs(dot(JtZ[:],v) - dot(Jv[:],Z[:])) );\r\nend\r\nreturn;\r\nend\r\n", "meta": {"hexsha": "e1d29eaf74ae197e29667b2e7c045d30068f43cb", "size": 2402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sensitivityTest.jl", "max_stars_repo_name": "adbX/j.jcp.2016.08.012-1", "max_stars_repo_head_hexsha": "99628230897503d55338e4aac43499b5d82924a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-06T00:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T00:58:11.000Z", "max_issues_repo_path": "test/sensitivityTest.jl", "max_issues_repo_name": "adbX/j.jcp.2016.08.012-1", "max_issues_repo_head_hexsha": "99628230897503d55338e4aac43499b5d82924a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-06T00:18:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-22T21:28:11.000Z", "max_forks_repo_path": "test/sensitivityTest.jl", "max_forks_repo_name": "adbX/j.jcp.2016.08.012-1", "max_forks_repo_head_hexsha": "99628230897503d55338e4aac43499b5d82924a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-23T19:03:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T03:02:09.000Z", "avg_line_length": 31.1948051948, "max_line_length": 105, "alphanum_fraction": 0.6094920899, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7729871926588112}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 b425dc3c-89aa-11eb-29f0-271d5d515fb2\nusing IterTools: product\n\n# \u2554\u2550\u2561 e80d9c13-4601-46b8-a6fe-6fc4cfddd31d\nusing Yao\n\n# \u2554\u2550\u2561 2f7f49f4-89b3-11eb-3bc3-ebc27d833a26\nusing LinearAlgebra: I\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b3d03fd8-89a6-11eb-31c3-d77d45414e64\nbegin \n\timport PlutoUI\n\tPlutoUI.LocalResource(\"../figures/two_magnets.svg\", :width => 200, :alt => \"Two magnets\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca4a2698-7d5f-4480-9e6e-6bc4dd3f8a3a\ncalculate_energy(J, \u03c3) = -sum(J_ij*\u03c3[i]*\u03c3[i+1] for (i,J_ij) in enumerate(J))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b84763a1-996a-4d50-ab7d-8126d758ce4b\nbegin\n\tJ = [1.0, -1.0]\n\t\u03c3 = [+1, -1, +1]\nend\n\n# \u2554\u2550\u2561 d6241dd0-0540-40c9-8d7d-8554c182a1c0\nmd\"\"\"\nThe energy of this is\n\"\"\"\n\n# \u2554\u2550\u2561 7972486c-eb23-461d-8998-ccb5474049f5\ncalculate_energy(J, \u03c3)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bc02c9c9-3fc1-486e-b837-e6e3113f4069\nlet\n\tt = r =[]\n\tfor \u03c3 in collect(product([+1,-1], [+1, -1], [+1, -1]))\n\t    t = [t;calculate_energy(J, \u03c3)]\n\t\tr = [r; [i for i in \u03c3]]\n\tend\n\t(t,r) = hcat(t), reshape(r, 8,3)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 41dd7fe8-89ac-11eb-3b00-a5df2682ae75\nPlutoUI.LocalResource(\"../figures/energy_landscape.svg\", :width => 300, :alt => \"Energy Landscape\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 54f1adc8-ef80-4801-86f5-835b1d499336\nimport dimod\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4405ace5-a383-4810-81b4-cae1fcb2222c\nJ = {(0, 1): 1.0, (1, 2): -1.0}\nh = {0:0, 1:0, 2:0}\n\n# \u2554\u2550\u2561 5efc75f4-3de1-4b0e-b9f4-87e74cda9103\nmd\"\"\"\nWe instantiate an Ising model:\n\"\"\"\n\n# \u2554\u2550\u2561 0ce517fd-1989-400a-bfe7-77ce043a7ac2\nmodel = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ee4c6fd4-7082-4a74-bcd5-9a101e6fb1e3\nsampler = dimod.SimulatedAnnealingSampler()\nresponse = sampler.sample(model, num_reads=10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cedb40a8-91b8-40e3-a37d-2e2da894dddc\n[solution.energy for solution in response.data()].count(-2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f0398f32-79da-4c74-b3f3-40f47d4a18f5\nmd\"\"\"\n# The transverse-field Ising model\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5cc78f38-5061-4212-b9dc-a2d740caf65f\nlet\n\tq = zero_state(1)\n\tstate(q |> put(1, 1=>Z))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cb9c2854-2050-4767-9f2c-9499062f5539\ncalculate_energy_expectation(state, hamiltonian) = Float64(real(conj(state'\u1d40) * hamiltonian * state))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03c8 = kron([1, 0], [1, 0])\n\tcalculate_energy_expectation(\u03c8, H)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25001a3b87dd-b03e-44c9-8cac-906da4327396\n# \u255f\u2500b3d03fd8-89a6-11eb-31c3-d77d45414e64\n# \u255f\u250031807b64-89a7-11eb-1957-9fd9c5e60f41\n# \u2560\u2550ca4a2698-7d5f-4480-9e6e-6bc4dd3f8a3a\n# \u255f\u25000aff9cab-8f0d-42ee-ab52-cc96b0a05895\n# \u2560\u2550b84763a1-996a-4d50-ab7d-8126d758ce4b\n# \u255f\u2500d6241dd0-0540-40c9-8d7d-8554c182a1c0\n# \u2560\u25507972486c-eb23-461d-8998-ccb5474049f5\n# \u255f\u2500f2133911-8380-47a1-823f-49f5425f5f15\n# \u2560\u2550b425dc3c-89aa-11eb-29f0-271d5d515fb2\n# \u2560\u2550bc02c9c9-3fc1-486e-b837-e6e3113f4069\n# \u255f\u25006b89bdf8-7c27-4a87-8375-3e80aa4a2bdd\n# \u255f\u250041dd7fe8-89ac-11eb-3b00-a5df2682ae75\n# \u255f\u25006e79b61e-89ac-11eb-238e-d5a2f77d0008\n# \u2560\u255054f1adc8-ef80-4801-86f5-835b1d499336\n# \u255f\u25003adf3d6f-1d41-464c-a3d1-8558478600f3\n# \u2560\u25504405ace5-a383-4810-81b4-cae1fcb2222c\n# \u255f\u25005efc75f4-3de1-4b0e-b9f4-87e74cda9103\n# \u2560\u25500ce517fd-1989-400a-bfe7-77ce043a7ac2\n# \u255f\u2500536f1777-09e3-48de-82a5-0058dc921b95\n# \u2560\u2550ee4c6fd4-7082-4a74-bcd5-9a101e6fb1e3\n# \u255f\u2500b9f62b85-8648-4c96-b571-69fe67ab4ccd\n# \u2560\u2550cedb40a8-91b8-40e3-a37d-2e2da894dddc\n# \u255f\u2500c0a1d5c7-7e97-4eb9-b423-543132776439\n# \u255f\u2500f0398f32-79da-4c74-b3f3-40f47d4a18f5\n# \u255f\u250055ff9df7-574b-4963-992b-7905e2c24331\n# \u2560\u2550e80d9c13-4601-46b8-a6fe-6fc4cfddd31d\n# \u255f\u250051f0a505-6608-435d-b28c-7ab2d2398e0a\n# \u2560\u25505cc78f38-5061-4212-b9dc-a2d740caf65f\n# \u255f\u2500529cba9b-cc11-4e20-b9a5-2eb432236ff2\n# \u2560\u2550d311efdc-8ea4-4579-950b-114d17d1b6ea\n# \u255f\u2500a5c79e07-f541-4910-9bea-7553b7d4374c\n# \u2560\u2550cb9c2854-2050-4767-9f2c-9499062f5539\n# \u255f\u250039a8fa28-4750-496b-8f80-feb34f0fa876\n# \u2560\u25502f7f49f4-89b3-11eb-3bc3-ebc27d833a26\n# \u2560\u25507b1acb49-4ea6-4b7e-9982-4c64a8cdd54f\n# \u255f\u2500132f9367-fabe-477e-a3f2-63d65b1cc1ae\n# \u2560\u2550de97610f-33a2-4cae-a5b5-b3a0f56fa3dc\n# \u2560\u2550bc5307be-89b3-11eb-0083-11121b2d595e\n# \u255f\u2500c1920c45-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": "function magic_square(n, ::Val{:JuMP})\n    N = n^2\n    model = JuMP.Model(CBLS.Optimizer)\n    magic_constant = n * (N + 1) / 2\n\n    @variable(model, 1 \u2264 X[1:n, 1:n] \u2264 N, Int)\n    @constraint(model, vec(X) in AllDifferent())\n\n    for i in 1:n\n        @constraint(model, X[i,:] in SumEqualParam(magic_constant))\n        @constraint(model, X[:,i] in SumEqualParam(magic_constant))\n    end\n    @constraint(model, [X[i,i] for i in 1:n] in SumEqualParam(magic_constant))\n    @constraint(model, [X[i,n + 1 - i] for i in 1:n] in SumEqualParam(magic_constant))\n\n    return model, X\nend\n\n\"\"\"\n    magic_square(n; modeler = :JuMP)\n\nCreate a model for the magic square problem of order `n`. The `modeler` argument accepts :JuMP (default), which refer to the solver the JuMP model.\n\"\"\"\nmagic_square(n; modeler = :JuMP) = magic_square(n, Val(modeler))\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9125ddc5b5c3501f1e57ef89d012ec0c85014188", "size": 845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/magic_square.jl", "max_stars_repo_name": "JuliaConstraints/ConstraintModels.jl", "max_stars_repo_head_hexsha": "90ec2346e256c4044d5dfb2c55546eb288e80290", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-29T05:43:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T10:01:08.000Z", "max_issues_repo_path": "src/magic_square.jl", "max_issues_repo_name": "JuliaConstraints/ConstraintModels.jl", "max_issues_repo_head_hexsha": "90ec2346e256c4044d5dfb2c55546eb288e80290", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-03-21T02:36:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T00:57:03.000Z", "max_forks_repo_path": "src/magic_square.jl", "max_forks_repo_name": "JuliaConstraints/ConstraintModels.jl", "max_forks_repo_head_hexsha": "90ec2346e256c4044d5dfb2c55546eb288e80290", "max_forks_repo_licenses": ["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.6060606061, "max_line_length": 147, "alphanum_fraction": 0.6461538462, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.772966379579636}}
{"text": "using Test\nusing WikstromTerelius: PrimeGenerator, validate, order, Enc, Dec, modulus, value, gen_shuffle\n\n\nq = 11\np = 2*q + 1\n\n@test validate(PrimeGenerator(3, p)) == true\n@test validate(PrimeGenerator(11, p)) == false\n\nn = let \n    n = 0\n    for i in 1:p\n        validate(PrimeGenerator(i, p)) && (n+=1)\n    end\n    n\nend\n@test n == q - 1\n\n\n\ng = PrimeGenerator(3, p)\n\n#q = 17\n#g = PrimeGenerator(3, q)\n\n@test g*g^2 == g^3\n@test (g^2)^2 == g^4\n@test g^(order(g) + 1) == g\n\nh = g^7\n\n@test h*h^2 == h^3\n@test (h^2)^2 == h^4\n@test h^(order(h) + 1) == h\n\n\n@test inv(g)*g^2 == g\n@test (g^7)^6 == g^(7*6) # This is only true for a cyclic group\n@test g*g*g == g^3 # Checking multiplication\n@test g^2/g == g\n\n\n\n### Let's test ElGammal encryption\n\n\nsk = 5\npk = g^sk\nr = 3\nm = g^5\nr2 = 4\n\nenc = Enc(pk, g)\ndec = Dec(sk)\n\n@test dec(enc(m, r)) == m\n@test enc(enc(m, r), r2) == enc(m, r + r2)\n\n### Shuffle generation\n\nsk = 5\npk = g^sk\n\nenc = Enc(pk, g)\n\n\nm_vec = [g, g^2, g^3]\ne_vec = enc.(m_vec, 1) # It is not necessary to randomize encryption for user. It however does make sense to do so for intermidiatery who collects messages from users to not reveal internals. \n\n### The shuffling\nr_vec = Int[1, 2, 3]\n\ne_enc = enc.(e_vec, r_vec)\n\u03c8 = sortperm(e_enc)\nsort!(e_enc)\n\n@test sort(dec.(e_enc)) == sort(m_vec)\n\n\nm_vec = [g, g^2, g^3]\ne_vec = enc.(m_vec, 1)\n\n\n\n", "meta": {"hexsha": "458ccc34ec191cd8d4a354881567589e707be63c", "size": 1349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/generators.jl", "max_stars_repo_name": "akels/WikstromTerelius.jl", "max_stars_repo_head_hexsha": "1f658f33ec46999ddf77fbed568897ef23b98e88", "max_stars_repo_licenses": ["MIT"], "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/generators.jl", "max_issues_repo_name": "akels/WikstromTerelius.jl", "max_issues_repo_head_hexsha": "1f658f33ec46999ddf77fbed568897ef23b98e88", "max_issues_repo_licenses": ["MIT"], "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/generators.jl", "max_forks_repo_name": "akels/WikstromTerelius.jl", "max_forks_repo_head_hexsha": "1f658f33ec46999ddf77fbed568897ef23b98e88", "max_forks_repo_licenses": ["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.6860465116, "max_line_length": 192, "alphanum_fraction": 0.5967383247, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7729663762571437}}
{"text": "@testset \"Derivatives\" begin\n\n    @testset \"Euro Options\" begin\n        # tested against https://option-price.com/index.php\n        params = (S = 1.0, K = 1.0, \u03c4 = 1, r = 0.05, \u03c3 = 0.25, q = 0.0)\n\n        @test eurocall(; params...) \u2248 0.12336 atol = 1e-5\n        @test europut(; params...) \u2248 0.07459 atol = 1e-5\n\n        params = (S = 1.0, K = 1.0, \u03c4 = 1, r = 0.05, \u03c3 = 0.25, q = 0.03)\n        @test eurocall(; params...) \u2248 0.105493 atol = 1e-5\n        @test europut(; params...) \u2248 0.086277 atol = 1e-5\n\n        params = (S = 1.0, K = 0.5, \u03c4 = 1, r = 0.05, \u03c3 = 0.25, q = 0.03)\n        @test eurocall(; params...) \u2248 0.49494 atol = 1e-5\n        @test europut(; params...) \u2248 0.00011 atol = 1e-5\n\n        params = (S = 1.0, K = 0.5, \u03c4 = 1, r = 0.05, \u03c3 = 0.25, q = 0.03)\n        @test eurocall(; params...) \u2248 0.49494 atol = 1e-5\n        @test europut(; params...) \u2248 0.00011 atol = 1e-5\n\n    end\nend\n\n", "meta": {"hexsha": "672734bb77dc510e72b5f6fa6dd897c767391a93", "size": 895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 35.8, "max_line_length": 72, "alphanum_fraction": 0.4927374302, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7729467421288034}}
{"text": "#= \nHackerrank problem: Standard deviation\nhttps://www.hackerrank.com/challenges/s10-standard-deviation/problem\n\nNote: I think it is a variance not a std dev. =#\n\nusing Printf\n\nn = parse(Int, readline(stdin))\narray = parse.(Int, split(readline(stdin)))\n\navg = sum(array) / n\nsum_residues_sq = sum((array .- avg) .^ 2)\nstdev = sqrt(sum_residues_sq / n)\n\n@printf(\"%.1f\", stdev)\n", "meta": {"hexsha": "f22b4ec4cb4749403cb8b8c9d75d5f1fe9ca3066", "size": 376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hackerrank_standard_dev.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_standard_dev.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_standard_dev.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": 22.1176470588, "max_line_length": 68, "alphanum_fraction": 0.7074468085, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7729467390168453}}
{"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\u0302, y; agg=mean)\n\nReturn the loss corresponding to mean absolute error: \n\n    agg(abs.(y\u0302 .- y))\n\"\"\"\nmae(y\u0302, y; agg=mean) = agg(abs.(y\u0302 .- y))\n\n\"\"\"\n    mse(y\u0302, y; agg=mean)\n\nReturn the loss corresponding to mean square error: \n    \n    agg((y\u0302 .- y).^2)\n\"\"\"\nmse(y\u0302, y; agg=mean) = agg((y\u0302 .- y).^2)\n\n\"\"\"\n    msle(y\u0302, y; agg=mean, \u03f5=eps(y\u0302))\n\nThe loss corresponding to mean squared logarithmic errors, calculated as\n\n    agg((log.(y\u0302 .+ \u03f5) .- log.(y .+ \u03f5)).^2)\n\nThe `\u03f5` term provides numerical stability.\nPenalizes an under-estimation more than an over-estimatation.\n\"\"\"\nmsle(y\u0302, y; agg=mean, \u03f5=epseltype(y\u0302)) = agg((log.((y\u0302 .+ \u03f5) ./ (y .+ \u03f5))).^2)\n\n\"\"\"\n    huber_loss(y\u0302, y; \u03b4=1, agg=mean)\n\nReturn the mean of the [Huber loss](https://en.wikipedia.org/wiki/Huber_loss)\ngiven the prediction `y\u0302` and true values `y`.\n\n                 | 0.5 * |y\u0302 - y|,            for |y\u0302 - y| <= \u03b4\n    Huber loss = |\n                 |  \u03b4 * (|y\u0302 - y| - 0.5 * \u03b4), otherwise\n\"\"\"\nfunction huber_loss(y\u0302, y; agg=mean, \u03b4=ofeltype(y\u0302, 1))\n   abs_error = abs.(y\u0302 .- y)\n   #TODO: remove dropgrad when Zygote can handle this function with CuArrays\n   temp = Zygote.dropgrad(abs_error .<  \u03b4)\n   x = ofeltype(y\u0302, 0.5)\n   agg(((abs_error.^2) .* temp) .* x .+ \u03b4*(abs_error .- x*\u03b4) .* (1 .- temp))\nend\n\n\"\"\"\n    crossentropy(y\u0302, y; dims=1, \u03f5=eps(y\u0302), agg=mean)\n\nReturn the cross entropy between the given probability distributions;\ncalculated as\n\n    agg(-sum(y .* log.(y\u0302 .+ \u03f5); 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\u0302` 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\u0302, y; dims=1, agg=mean, \u03f5=epseltype(y\u0302))\n    agg(.-sum(xlogy.(y, y\u0302 .+ \u03f5); dims=dims))\nend\n\n\"\"\"\n    logitcrossentropy(y\u0302, y; dims=1, \u03f5=eps(y\u0302), agg=mean)\n\nReturn the crossentropy computed after a [`Flux.logsoftmax`](@ref) operation;\ncalculated as \n\n    agg(.-sum(y .* logsoftmax(y\u0302; dims=dims); dims=dims))\n\n`logitcrossentropy(y\u0302, y)` is mathematically equivalent to\n[`Flux.crossentropy(softmax(y\u0302), 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\u0302, y; dims=1, agg=mean)\n    agg(.-sum(y .* logsoftmax(y\u0302; dims=dims); dims=dims))\nend\n\n\"\"\"\n    bce_loss(y\u0302, y; agg=mean, \u03f5=eps(y\u0302))\n\nReturn the binary cross-entropy loss, computer as \n\n    agg(@.(-y*log(y\u0302 + \u03f5) - (1-y)*log(1-y\u0302 + \u03f5)))\n    \nThe `\u03f5` term provides numerical stability.\n\nTypically, the prediction `y\u0302` 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\u0302, y; agg=mean, \u03f5=epseltype(y\u0302))\n    agg(@.(-xlogy(y, y\u0302+\u03f5) - xlogy(1-y, 1-y\u0302+\u03f5)))\nend\n# Re-definition to fix interaction with CuArrays.\n# CUDA.@cufunc bce_loss(y\u0302, y; \u03f5=eps(y\u0302)) = -y*log(y\u0302 + \u03f5) - (1 - y)*log(1 - y\u0302 + \u03f5)\n\n\"\"\"\n    logitbce_loss(\u0177, y; agg=mean)\n\nMathematically equivalent to\n[`Flux.bce_loss(\u03c3(\u0177), 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\u0302, y; agg=mean)\n    agg(@.((1-y)*y\u0302 - log\u03c3(y\u0302)))\nend\n# Re-definition to fix interaction with CuArrays.\n# CUDA.@cufunc logitbce_loss(\u0177, y) = (1 - y)*\u0177 - log\u03c3(y\u0302)\n\n\n\"\"\"\n    kldivergence(y\u0302, 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\u0302, y; dims=1, agg=mean, \u03f5=epseltype(y\u0302))\n  entropy = agg(sum(xlogx.(y), dims=dims))\n  cross_entropy = crossentropy(y\u0302, y; dims=dims, agg=agg, \u03f5=\u03f5)\n  return entropy + cross_entropy\nend\n\n\"\"\"\n    poisson_loss(y\u0302, y)\n\n# Return how much the predicted distribution `y\u0302` diverges from the expected Poisson\n# distribution `y`; calculated as `sum(y\u0302 .- y .* log.(y\u0302)) / 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\u0302, y; agg=mean) = agg(y\u0302 .- xlogy.(y, y\u0302))\n\n\"\"\"\n    hinge_loss(y\u0302, y; agg=mean)\n\nReturn the [hinge_loss loss](https://en.wikipedia.org/wiki/Hinge_loss) given the\nprediction `y\u0302` and true labels `y` (containing 1 or -1); calculated as\n`sum(max.(0, 1 .- y\u0302 .* y)) / size(y, 2)`.\n\nSee also: [`squared_hinge_loss`](@ref)\n\"\"\"\nhinge_loss(y\u0302, y; agg=mean) = agg(max.(0, 1 .-  y\u0302 .* y))\n\n\"\"\"\n    squared_hinge_loss(y\u0302, y)\n\nReturn the squared hinge_loss loss given the prediction `y\u0302` and true labels `y`\n(containing 1 or -1); calculated as `sum((max.(0, 1 .- y\u0302 .* y)).^2) / size(y, 2)`.\n\nSee also: [`hinge_loss`](@ref)\n\"\"\"\nsquared_hinge_loss(y\u0302, y; agg=mean) = agg((max.(0, 1 .- y\u0302 .* y)).^2)\n\n\"\"\"\n    dice_coeff_loss(y\u0302, 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\u0302 .* y| + smooth) / (sum(y\u0302.^2) + sum(y.^2) + smooth)\n\"\"\"\ndice_coeff_loss(y\u0302, y; smooth=ofeltype(y\u0302, 1.0)) = 1 - (2*sum(y .* y\u0302) + smooth) / (sum(y.^2) + sum(y\u0302.^2) + smooth) #TODO agg\n\n\"\"\"\n    tversky_loss(y\u0302, y; \u03b2=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 \u03b2 weigh recall more than precision (by placing more emphasis on false negatives)\nCalculated as:\n    1 - sum(|y .* y\u0302| + 1) / (sum(y .* y\u0302 + \u03b2*(1 .- y) .* y\u0302 + (1 - \u03b2)*y .* (1 .- y\u0302)) + 1)\n\"\"\"\nfunction tversky_loss(y\u0302, y; \u03b2=ofeltype(y\u0302, 0.7))\n    #TODO add agg\n    num = sum(y .* y\u0302) + 1\n    den = sum(y .* y\u0302 + \u03b2*(1 .- y) .* y\u0302 + (1 - \u03b2)*y .* (1 .- y\u0302)) + 1\n    1 - num / den\nend\n             \n\"\"\"\n    xlogx(x)\n\nReturn `x * log(x)` for `x \u2265 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, \u0394 -> (nothing, Zygote.unbroadcast(x, xlogy.(\u0394, y)), Zygote.unbroadcast(y, \u0394 .* 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, \u03f5=1e-5)\n\nNormalise `x` to mean 0 and standard deviation 1 across the dimensions given by `dims`.\n`\u03f5` is a small additive factor added to the denominator for numerical stability.\n\"\"\"\nfunction normalise(x::AbstractArray; dims, \u03f5=ofeltype(x, 1e-5))\n  \u03bc = mean(x, dims=dims)\n    #   \u03c3 = std(x, dims=dims, mean=\u03bc, corrected=false) # use this when #478 gets merged\n  \u03c3 = std(x, dims=dims, corrected=false)\n  return (x .- \u03bc) ./ (\u03c3 .+ \u03f5)\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": "pd1 = ProbabilityDistribution([\"head\",\"tails\"], [0.5,0.5])\n\n@test states(pd1) == ([\"head\",\"tails\"])\n@test_approx_eq 0.5 pd1[\"head\"]\n\nupd1 = ProbabilityDistribution([\"test\", \"b\u00f8h\", \"bjarke\", \"thomas\"])\n@test Set(states(upd1)) == Set([\"bjarke\", \"b\u00f8h\", \"test\", \"thomas\"])\n\nupd2 = ProbabilityDistribution([\"test\", \"b\u00f8h\", \"bjarke\", \"thomas\"])\n\n@test upd1 == upd2\n\nupd3 = ProbabilityDistribution([\"test\", \"b\u00f8h\", \"bjarke\", \"esben\"])\n\n@test upd1 != upd3\n\npd2 = ProbabilityDistribution([\"tails\",\"head\"], [0.5,0.5])\n\n@test pd1 == pd2\n\npd3 = ProbabilityDistribution([\"tails\",\"head\"], [0.6,0.4])\n\n@test pd1 == pd2 == pd3\n\n@test_approx_eq 0.6 pd3[\"tails\"]\n\n@test_throws pd3 = ProbabilityDistribution([\"tails\",\"head\"], [0.7,0.4])\n\npd4 = ProbabilityDistribution([\"one\", \"two\", \"three\", \"four\", \"five\", \"six\"], [0.2, 0.1, 0.2, 0.2, 0.1, 0.2])\n\n@test_approx_eq 0.2 pd4[\"one\"]\n\n@test_throws pd4 = ProbabilityDistribution([\"one\", \"two\", \"three\", \"four\", \"five\", \"six\"], [0.2, 0.2, 0.2, 0.2, 0.2, 0.2])\n\npd4 = ProbabilityDistribution([\"rain\",\"sun\"], [0.6,0.4])\n\nj_pd1_pd4=pd1*pd4\n\n@test length(states(j_pd1_pd4)) == 4\n@test_throws p2*p3\n@test_approx_eq j_pd1_pd4[Set{ASCIIString}({\"head\",\"rain\"})] 0.3\n\n# P(X|Y) * P(Y)\n\npd5 = ProbabilityDistribution([\"x1\",\"x2\"],[0.5 0.5; 0.7 0.3],[\"y1\",\"y2\"])\npd6 = ProbabilityDistribution([\"y1\",\"y2\"],[0.5,0.5])\n\npd_q=pd5*pd6\n@test_approx_eq 0.15 pd_q[Set{ASCIIString}({\"y2\",\"x2\"})]\n@test sum(probabilities(pd_q)) == 1\n\npd7 = ProbabilityDistribution([\"x1\", \"x2\", \"x3\"],[0.34 0.33 0.33; 0.6 0.2 0.2], [\"y1\", \"y2\"])\npd8 = ProbabilityDistribution([\"y1\",\"y2\"],[0.7,0.3])\n\npd_q1=pd7*pd8\n@test sum(probabilities(pd_q1)) == 1\n@test_approx_eq 0.238 pd_q1[Set{ASCIIString}({\"y1\",\"x1\"})]\n@test_approx_eq pd_q1[Set{ASCIIString}({\"y2\",\"x2\"})] pd_q1[Set{ASCIIString}({\"y2\",\"x3\"})]\n@test_approx_eq 0.06 pd_q1[Set{ASCIIString}({\"y2\",\"x2\"})]\n@test_approx_eq 0.231 pd_q1[Set{ASCIIString}({\"y1\",\"x2\"})]\n\npd9 = ProbabilityDistribution([\"x1\", \"x2\", \"x3\"],[0.34 0.33 0.33; 0.6 0.2 0.2], [\"y1\", \"y2\"])\npd10 = ProbabilityDistribution([\"y2\",\"y1\"],[0.3,0.7])\n\npd_q2=pd9*pd10\n@test sum(probabilities(pd_q2)) == 1\n@test_approx_eq 0.238 pd_q2[Set{ASCIIString}({\"y1\",\"x1\"})]\n@test_approx_eq pd_q2[Set{ASCIIString}({\"y2\",\"x2\"})] pd_q2[Set{ASCIIString}({\"y2\",\"x3\"})]\n@test_approx_eq 0.06 pd_q2[Set{ASCIIString}({\"y2\",\"x2\"})]\n@test_approx_eq 0.231 pd_q2[Set{ASCIIString}({\"y1\",\"x2\"})]\n\npd11 = ProbabilityDistribution([\"x1\", \"x2\"],[0.5 0.5; 0.6 0.4; 0.23 0.77], [\"y1\", \"y2\", \"y3\"])\npd12 = ProbabilityDistribution([\"y1\",\"y3\", \"y2\"],[0.2,0.5,0.3])\n\npd_q3=pd11*pd12\n@test sum(probabilities(pd_q3)) == 1\n@test_approx_eq 0.385 pd_q3[Set{ASCIIString}({\"y3\",\"x2\"})]\n@test_approx_eq 0.1 pd_q3[Set{ASCIIString}({\"y1\",\"x1\"})]\n@test_approx_eq 0.18 pd_q3[Set{ASCIIString}({\"y2\",\"x1\"})]\n@test_approx_eq 0.115 pd_q3[Set{ASCIIString}({\"y3\",\"x1\"})]\n@test typeof(probabilities(pd_q3)) == Array{Float64,1}\n\n@test_approx_eq probabilities(pd_q3/pd12) probabilities(pd11)\n", "meta": {"hexsha": "c24741d3ad8d9db1d11b9bb866a3cf8b011c6786", "size": 2933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/probability_distribution.jl", "max_stars_repo_name": "tpanum/BayesianNetworks.jl", "max_stars_repo_head_hexsha": "9f6b81140f2fabfb8a055fad890203a3df0c147f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-28T17:12:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-28T17:12:51.000Z", "max_issues_repo_path": "test/probability_distribution.jl", "max_issues_repo_name": "tpanum/BayesianNetworks.jl", "max_issues_repo_head_hexsha": "9f6b81140f2fabfb8a055fad890203a3df0c147f", "max_issues_repo_licenses": ["MIT"], "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/probability_distribution.jl", "max_forks_repo_name": "tpanum/BayesianNetworks.jl", "max_forks_repo_head_hexsha": "9f6b81140f2fabfb8a055fad890203a3df0c147f", "max_forks_repo_licenses": ["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.9166666667, "max_line_length": 122, "alphanum_fraction": 0.6481418343, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8459424411924674, "lm_q1q2_score": 0.772917748676857}}
{"text": "using FinancialToolbox\nif !(VERSION.major == 0 && VERSION.minor <= 6)\n    using Test, Dates\nelse\n    using Base.Test\nend\nfunction yearFractionTester(StartDate, EndDate, MatlabResults, TestToll = 1e-14)\n    for i = 0:FinancialToolbox.currMaxImplemented\n        @test(abs(MatlabResults[i+1] - yearfrac(StartDate, EndDate, i)) < TestToll)\n    end\n    return\nend\n\nStartDate = Date(1992, 12, 14);\nEndDate = Date(1996, 2, 28);\n@test(-yearfrac(StartDate, StartDate, 0) == 0)\n@test(-yearfrac(StartDate, EndDate, 0) == yearfrac(EndDate, StartDate, 0))\nMatlabResults = [3.20821917808219; 3.20555555555556; 3.25277777777778; 3.20821917808219; 3.20555555555556; 3.20555555555556; 3.20555555555556; 3.20821917808219; 3.20821917808219; 3.25277777777778; 3.20821917808219; 3.20555555555556; 3.20765027322409];\nyearFractionTester(StartDate, EndDate, MatlabResults);\n\nEndDate2 = Date(1996, 2, 29);\nMatlabResults2 = [3.21095890410959; 3.20833333333333; 3.25555555555556; 3.21095890410959; 3.20833333333333; 3.20833333333333; 3.20833333333333; 3.21095890410959; 3.21095890410959; 3.25555555555556; 3.21095890410959; 3.20833333333333; 3.21038251366122];\nyearFractionTester(StartDate, EndDate2, MatlabResults2);\n\nEndDate3 = Date(2026, 2, 28);\nMatlabResults3 = [33.2301369863014; 33.2055555555556; 33.6916666666667; 33.2301369863014; 33.2055555555556; 33.2055555555556; 33.2055555555556; 33.2082191780822; 33.2301369863014; 33.6916666666667; 33.2301369863014; 33.2055555555556; 33.2080844374580];\nTestToll = 1e-13;\nyearFractionTester(StartDate, EndDate3, MatlabResults3, TestToll);\n\nStartDate2 = Date(1992, 2, 29);\nEndDate4 = Date(1996, 2, 29);\nMatlabResults4 = [3.99180327868852; 4; 4.05833333333333; 4.00273972602740; 3.99722222222222; 4; 4; 4; 3.99180327868852; 4.05833333333333; 4.00273972602740; 4; 4]\nyearFractionTester(StartDate2, EndDate4, MatlabResults4);\n\nStartDate3 = Date(1992, 3, 30);\nEndDate5 = Date(1996, 12, 31);\nMatlabResults5 = [4.75890410958904; 4.75000000000000; 4.82500000000000; 4.75890410958904; 4.75000000000000; 4.75000000000000; 4.75000000000000; 4.75616438356164; 4.75890410958904; 4.82500000000000; 4.75890410958904; 4.75000000000000; 4.75409836065569]\nyearFractionTester(StartDate3, EndDate5, MatlabResults5);\n\nStartDate4 = Date(1992, 3, 31);\nEndDate6 = Date(1996, 12, 30);\nMatlabResults6 = [4.75342465753425; 4.75000000000000; 4.81944444444445; 4.75342465753425; 4.75000000000000; 4.75000000000000; 4.75000000000000; 4.75068493150685; 4.75342465753425; 4.81944444444445; 4.75342465753425; 4.75000000000000; 4.74863387978144]\nyearFractionTester(StartDate4, EndDate6, MatlabResults6);\n\n@test_throws(ErrorException, yearfrac(StartDate, EndDate3, FinancialToolbox.currMaxImplemented + 1));\n@test_throws(ErrorException, yearfrac(StartDate, EndDate3, -1));\n\n@test(daysact(Date(1992, 12, 14), Date(1992, 12, 13)) == -1)\n\n##Excel test\n@test(fromExcelNumberToDate(33952) == Date(1992, 12, 14))\n\nprintln(\"Test Dates Passed\")\n", "meta": {"hexsha": "6040242737541ee873dbf620ccf29fed36baea59", "size": 2923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testDates.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": "test/testDates.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": "test/testDates.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": 54.1296296296, "max_line_length": 252, "alphanum_fraction": 0.7765993842, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.772917747758922}}
{"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\u03a6 = 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\u03a6[i,j] = ChebyT(x[i],j-1)\n\t\t\t# \u03a6[i,j] = abmap(\u03a6[i,j], lb, ub)\n\t\tend\n\tend\n\treturn \u03a6\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\u03d5 = 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(\u03d5)\n\n\t# Build Function grid\n\t\u03a6 = chebpol(S, n)\n\n\t# Estimate parameters of approximation\n\tc = \u03a6\\Y\n\n\t# Evaluate approximation\n\tYhat = \u03a6*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\u03a6_new = chebpol(unitmap(n_new,lb,ub), n)\n\n\t# Evaluate using fitted coefficients\n\tYhat_new = \u03a6_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} #\u00a0evaluation 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#\u00a0function 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": "using IntervalArithmetic\nusing Test\n\n\nconst Interval = IntervalArithmetic.Interval\n\n# Interval tests:\n\nsetformat(:full)\n\ninclude(\"interval_tests/intervals.jl\")\ninclude(\"decoration_tests/decoration_tests.jl\")\n\ninclude(\"rand.jl\")\n\n# Display tests:\ninclude(\"display_tests/display.jl\")\n\ninclude(\"multidim_tests/multidim.jl\")\n\n# ITF1788 tests\n\ninclude(\"test_ITF1788/run_ITF1788.jl\")\n", "meta": {"hexsha": "79a3f3a5f3f925415a0bb9b0cb15851a8a52870c", "size": 378, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "mlliarm/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "07d74b712b5a5fcd4b87197e8ecd20d4ddd6917f", "max_stars_repo_licenses": ["MIT"], "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": "mlliarm/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "07d74b712b5a5fcd4b87197e8ecd20d4ddd6917f", "max_issues_repo_licenses": ["MIT"], "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": "mlliarm/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "07d74b712b5a5fcd4b87197e8ecd20d4ddd6917f", "max_forks_repo_licenses": ["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.75, "max_line_length": 47, "alphanum_fraction": 0.791005291, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7729177451281806}}
{"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 \u2248 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 \u2248 dp2 \u2248 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": "# this file tests the rk4 function\n# this uses rk4 to integrate the function t^4 + t^3 + t^2 +t + 1\n# thus the function supplied to rk4 is d/dt of that function\n# and q_vec_rk[1] is initially function(t=0) = 1\nfunction true_f(t)\n#   return t + 1\n  return t^4 + t^3 + t^2 + t + 1\nend\n\nfunction test_f(q_vec, res_vec, opts, t)\n#   return res_vec[1] = 1\n  res_vec[1] = 4*t^3 + 3*t^2 + 2*t + 1\nend\n\npre_func = (a...) -> 3\nfunction post_func(q_vec, res_vec, opts; calc_norm=true) \n  return norm(res_vec)\nend\n\n\"\"\"\n  Use rk4 to solve an 4th order polynoial ODE, for which it is exact\n\"\"\"\nfunction test_rk4()\n    @testset \"----- testing rk4 -----\" begin\n    opts_rk = Dict{Any, Any}(\"physics\" => \"Euler\", \"run_type\" => 1, \"smb_name\" => \"\", \"output_freq\" => 1, \"write_vis\" => false, \"use_itermax\" => false, \"numBC\" => 0)\n    read_input(opts_rk)\n\n    q_vec_rk = [1.0]\n    res_vec_rk = [0.0]\n    ctx = (q_vec_rk, res_vec_rk)\n\n    delta_t = 0.1\n    t_max = 1.0\n\n    t = rk4(test_f, delta_t, t_max, q_vec_rk, res_vec_rk, pre_func, post_func, ctx, opts_rk, real_time=true)\n\n    f_approx = q_vec_rk[1]\n    f_exact = true_f(t)\n    err = abs(f_approx - f_exact)\n\n    @test isapprox( t, t_max) atol=1e-14\n    @test  err  < 1e-14# machine precision\n  end  # end facts block\n\n  @testset \"----- testing lserk54 -----\" begin\n    opts_rk = Dict{Any, Any}(\"physics\" => \"Euler\", \"run_type\" => 30, \"smb_name\" => \"\", \"output_freq\" => 1, \"write_vis\" => false, \"use_itermax\" => false, \"numBC\" => 0)\n    read_input(opts_rk)\n\n    q_vec_rk = [1.0]\n    res_vec_rk = [0.0]\n    ctx = (q_vec_rk, res_vec_rk)\n\n    delta_t = 0.1\n    t_max = 1.0\n\n    t = lserk54(test_f, delta_t, t_max, q_vec_rk, res_vec_rk, pre_func, post_func, ctx, opts_rk, real_time=true)\n\n    f_approx = q_vec_rk[1]\n    f_exact = true_f(t)\n    err = abs(f_approx - f_exact)\n\n    @test  err  < 1e-14# machine precision\n\n  end\n\n  return nothing\nend\n\n#test_rk4()\nadd_func1!(EulerTests, test_rk4, [TAG_NLSOLVERS, TAG_SHORTTEST])\n", "meta": {"hexsha": "4d7345d9f0f407c97da38e19231175cd5faab68b", "size": 1958, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/euler/test_rk4.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": "test/euler/test_rk4.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": "test/euler/test_rk4.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": 27.5774647887, "max_line_length": 166, "alphanum_fraction": 0.6292134831, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.772878986327157}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 8ffa93f8-7e46-11eb-24dd-d3a098d446db\nrun(`pwd`)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0d70902e-7e44-11eb-353e-a9a2b3249ede\nbegin\n  A = .8\n  f = 1000    # i.e. 1000 cycles/sec\n  \u03d5 = pi/2\n  fs = 44100  # i.e. 44100 samples/sec\n  t = range(-.002, .002, step=1/fs)\n  x = A .* cos.(2\u03c0*f.*t .+ \u03d5)\n  size(x)\nend\n\n# \u2554\u2550\u2561 4a3f2772-7e44-11eb-22ed-a1fe51593505\nt, size(t)\n\n# \u2554\u2550\u2561 e439ba0e-7e44-11eb-3650-b974bc440e07\nsize(@. A * cos(2\u03c0*f*t + \u03d5))\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u25508ffa93f8-7e46-11eb-24dd-d3a098d446db\n# \u2560\u2550771d9d7c-7e45-11eb-333b-89c14c371bb1\n# \u255f\u25003890caac-7e40-11eb-1abf-cb2d856fde8b\n# \u2560\u25500d70902e-7e44-11eb-353e-a9a2b3249ede\n# \u2560\u25504a3f2772-7e44-11eb-22ed-a1fe51593505\n# \u2560\u2550e439ba0e-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}; \u0394t::Float64 = 1.0) -> DataFrame\n\n# Computes \u03bc 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# \u0394t \t\t    Time step size. Default is 1.0 in the units you want the \u03bc to be calculated in\n# ------------------------------------------------------------------------------------------------------------------------------ #\nfunction compute_log_return_array(data_table::DataFrame, map::Pair{Symbol,Symbol}; \u0394t = (1.0 / 365.0))\n\n    # initialize -\n    (number_of_rows, _) = size(data_table)\n    return_table = DataFrame(timestamp = Date[], P1 = Float64[], P2 = Float64[], \u03bc = 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        \u03bc = (1 / \u0394t) * log(today_close_price / yesterday_close_price)\n\n        # push! -\n        push!(return_table, (tmp_date, yesterday_close_price, today_close_price, \u03bc))\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}; \u0394t = (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 \u2208 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; \u0394t = \u0394t)\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    \u0394_array = Array{Float64,1}()\n\n    for step_index \u2208 2:number_of_steps\n\n        # compute -\n        P\u2081 = data[step_index-1]\n        P\u2082 = data[step_index]\n        \u0394 = multiplier*(P\u2082 - P\u2081)/(P\u2081)\n\n        # grab -\n        push!(\u0394_array,\u0394)\n    end\n\n    # return -\n    return \u0394_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    \u0394_array = Array{Float64,2}(undef, number_of_steps - 1, number_of_cols)\n\n    for col_index \u2208 1:number_of_cols\n        for step_index \u2208 2:number_of_steps\n\n            # compute -\n            P\u2081 = data[step_index-1,col_index]\n            P\u2082 = data[step_index, col_index]\n            \u0394 = multiplier*(P\u2082 - P\u2081)/(P\u2081)\n    \n            # grab -\n            \u0394_array[step_index - 1, col_index] = \u0394\n        end\n    end\n\n    # return -\n    return \u0394_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[], \u03bc = 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        \u03bc = ((today_close_price/yesterday_close_price) - 1.0)*multiplier;\n\n        # push! -\n        push!(return_table, (tmp_date, yesterday_close_price, today_close_price, \u03bc))\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 \u2208 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; \u0394t::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    \u03bc = model.\u03bc\n    \u03c3 = model.\u03c3\n\n    # calculate the random term -\n    d = Normal{Float64}(0.0, 1.0)\n\n    # calculate the drift term -\n    drift_term = \u03bc*\u0394t\n\n    # main: sample paths -\n    for sample_path_index \u2208 1:N\n\n        # generate new sequence of steps for this sample path -\n        random_terms = \u03c3*sqrt(\u0394t)*rand(d,number_of_steps)\n        \n        # solve the model -\n        for time_step_index \u2208 2:number_of_steps\n            \n            # grab the current price P\u2081 -\n            P\u2081 = state_array[time_step_index-1,sample_path_index]\n            \n            # compute the price difference -\n            \u0394P = P\u2081*(drift_term+random_terms[time_step_index])\n\n            # capture -\n            state_array[time_step_index,sample_path_index] = (P\u2081 + \u0394P)\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(\u03bc,\u03a3,target_return::Float64; \n    w_lower::Float64 = 0.0, w_upper::Float64 = 1.0)\n\n    # initialize -\n    number_of_assets = length(\u03bc)\n    w = Variable(number_of_assets)\n    risk = quadform(w,\u03a3)\n    ret  = dot(w,\u03bc)\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(\u03bc,\u03a3)\n\n    # how many assets do we have?\n    \ud835\udcab = length(\u03bc)\n\n    # initialize -\n\tterm_array = Array{Float64,1}(undef, \ud835\udcab)\n\tfor term_index \u2208 1:\ud835\udcab\n\t\tterm_array[term_index] = max(0.0, \u03bc[term_index]/\u03a3[term_index,term_index])\n\tend\n\n    # compute the u-variable -\n\t\ud835\udcb5 = sum(term_array)\n\n    # if we have no good options (all the returns are negative, then all allocations would be zero)\n    if (\ud835\udcb5 == 0)\n        u_variable_array = zeros(\ud835\udcab)\n    else\n        u_variable_array = (1/\ud835\udcb5)*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    \u03bc_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) \u2208 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[!,:\u03bc])\n\t\tpush!(\u03bc_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,:\u03bc]\n\t\tend\n    end\n\n    # compute the covariance -\n    \u03a3 = cov(R_array)\n\n    # return -\n    return (\u03bc_bar,\u03a3)\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(\u03ba\u2080,\u03c4\u2080,\u03d5\u2080,\u03ba\u2081,\u03c4\u2081,\u03d5\u2081,\u03bd)\nThe *Bulk-And-Tails (BATs) distribution* has cumulative distribution function\n```math\nF(x) = T_\u03bd(H(x))\n```\nwhere T_\u03bd is the student-t cdf with \u03bd degrees of freedom and H is a monotone increasing function.\n\u03d5\u2080 and \u03d5\u2081 are location parameters for the lower and upper tails.\n\u03c4\u2080 and \u03c4\u2081 are scale parameters for the lower and upper tails.\n\u03ba\u2080 and \u03ba\u2081 are shape parameters for the lower and upper tails.\nNegative \u03ba indicates a bounded tail. Positive \u03ba indicates a heavy tail.\nThe case \u03ba=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(\u03ba\u2080,\u03c4\u2080,\u03d5\u2080,\u03ba\u2081,\u03c4\u2081,\u03d5\u2081,\u03bd)     # 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\u03ba\u2080::T\n\u03c4\u2080::T\n\u03d5\u2080::T\n\u03ba\u2081::T\n\u03c4\u2081::T\n\u03d5\u2081::T\n\u03bd::T\nend\n\nDistributions.params(d::BulkAndTailsDist) = (d.\u03ba\u2080,d.\u03c4\u2080,d.\u03d5\u2080,d.\u03ba\u2081,d.\u03c4\u2081,d.\u03d5\u2081,d.\u03bd)\nDistributions.minimum(d::BulkAndTailsDist) = (d.\u03ba\u2080 \u2265 0.0 ? -Inf : d.\u03d5\u2080 - d.\u03c4\u2080*i\u03a8(-1.0/d.\u03ba\u2080))\nDistributions.maximum(d::BulkAndTailsDist) = (d.\u03ba\u2081 \u2265 0.0 ? Inf : d.\u03d5\u2081 + d.\u03c4\u2081*i\u03a8(-1.0/d.\u03ba\u2081))\n\nBulkAndTailsDist(\u03ba\u2080::Real,\u03c4\u2080::Real,\u03d5\u2080::Real,\u03ba\u2081::Real,\u03c4\u2081::Real,\u03d5\u2081::Real,\u03bd::Real) = BulkAndTailsDist(promote(\u03ba\u2080,\u03c4\u2080,\u03d5\u2080,\u03ba\u2081,\u03c4\u2081,\u03d5\u2081,\u03bd)...)\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\u03bd\u2080 = 1f-4\n\u03bd\u208b = 0.1f0\n\u03bd\u2082 = 1f0\n\nRi\u1d9c = 0.25\n\u0394Ri\u208a = 0.1\n\u0394Ri\u208b = 0.1\n\nRis = -1:0.001:2\nmpp(Ri, \u03bd\u2080, \u03bd\u208b, Ri\u1d9c, \u0394Ri) = \u03bd\u2080 + \u03bd\u208b * tanh_step((Ri - Ri\u1d9c) / \u0394Ri)\nmpp_ca(Ri, \u03bd\u2080, \u03bd\u208b, \u03bd\u2082, Ri\u1d9c, \u0394Ri\u208a) = \u03bd\u2080 + \u03bd\u208b * tanh_step((Ri - Ri\u1d9c) / \u0394Ri\u208a) + \u03bd\u2082 * tanh_step((Ri + Ri\u1d9c) / \u0394Ri\u208b)\n\nmpp_str = \"Modified Pac-Phil\"\nmpp_ca_str = \"New Modified Pac-Phil\"\n\nplot(Ris, mpp.(Ris, \u03bd\u2080, \u03bd\u208b, Ri\u1d9c, \u0394Ri\u208a), label=mpp_str)\nplot!(Ris, mpp_ca.(Ris, \u03bd\u2080, \u03bd\u208b, \u03bd\u2082, Ri\u1d9c, \u0394Ri\u208a), 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, \u03bd\u2080, \u03bd\u208b, Ri\u1d9c, \u0394Ri), color=color_palette[1], label=L\"\\nu_0\")\n# lines!(ax, Ris, mpp_ca.(Ris, \u03bd\u2080, \u03bd\u208b, \u03bd\u2082, Ri\u1d9c, \u0394Ri), 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": "\n\n\nfunction counting_sort_letters(A::Array, position::Int)\n\tc = zeros(Int, 26)\n\tfor i in A\n\t\tc[Int(i[position]) - 96] += 1\n\tend\n\tfor i in 2:26\n\t\tc[i] += c[i - 1]\n\tend\n\tret = Array{String, 1}(undef, length(A))\n\tfor i in length(A) : -1 : 1\n\t\tret[c[Int(A[i][position]) - 96]] = A[i]\n\t\tc[Int(A[i][position]) - 96] -= 1\n\tend\n\treturn ret\nend\n\n\nfunction 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_left_(A, v)\n\treturn bisect_left_(A, 1, length(A) + 1, v)\nend\n\n\nfunction counting_sort_length(A::Array)\n\tmax_len = 0\n\tfor i in A\n\t\tif max_len < length(i)\n\t\t\tmax_len = length(i)\n\t\tend\n\tend\n\tc = zeros(Int, max_len + 1)\n\n\tfor i in A\n\t\tc[length(i) + 1] += 1\n\tend\n\n\tfor i in 2 : max_len + 1\n\t\tc[i] += c[i - 1]\n\tend\n\n\tret = Array{String, 1}(undef, length(A))\n\n\tfor i in length(A) : -1 : 1\n\t\tret[c[length(A[i]) + 1]] = A[i]\n\t\tc[length(A[i]) + 1] -= 1\n\tend\n\treturn ret\nend\n\n\nfunction copy_into!(to, from, p, r)\n\tfor i in p : r\n\t\tto[i] = from[i - p + 1]\n\tend\nend\n\n\nfunction flexradix(A::Array, max_len)\n\tA = counting_sort_length(A)\n\n\tnum_empty = 0\n\n\tfor i in A\n\t\tif length(i) == 0\n\t\t\tnum_empty += 1\n\t\tend\n\t\tif max_len < length(i)\n\t\t\tmax_len = length(i)\n\t\tend\n\tend\n\n\tif max_len == 0\n\t\treturn A\n\tend\n\n\tc = zeros(Int, max_len + 1)\n\n\tfor i in A\n\t\tc[length(i) + 1] += 1\n\tend\n\n\tfor i in max_len : -1 : 1\n\t\tc[i] += c[i + 1]\n\tend\n\n\tr = length(A)\n\n\tfor cur_len in (max_len + 1) : -1 : 2\n\t\tp = r - c[cur_len] + 1\n\n\t\tif r - p > 0\n\t\t\tcopy_into!(A, counting_sort_letters(A[p : r], cur_len - 1), p, r)\n\t\tend\n\tend\n\n\tcopy_into!(A, counting_sort_letters(A[(num_empty + 1) : r], 1), num_empty + 1, r)\n\n\treturn A\nend\n\n", "meta": {"hexsha": "ae1b65e534713874c630f72d043a630d0673471c", "size": 1753, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving4/Ov4.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/Oving4/Ov4.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/Oving4/Ov4.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": 14.9829059829, "max_line_length": 82, "alphanum_fraction": 0.5687393041, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7727946303558917}}
{"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\u03b1 = 0.5\nimp_pp = inv(process_noise)\nimp_mp = inv(measurement_noise)\nnominal_dynamics(u) = Normal(u, sqrt(\u03b1))\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        \u03a3_pinv = zeros(length(A.S))\r\n        index = A.S .> tol\r\n        \u03a3_pinv[index] = 1. ./ A.S[index]\r\n        \u03a3_pinv[findall(.!isfinite.(\u03a3_pinv))] .= 0.\r\n        VVt = A.V * A.Vt\r\n        pinv_A_b = A.V * Diagonal(\u03a3_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": "using AnalyticalEOR \n\nswr = 0.2\nsor = 0.2\n\nkrw0 = 0.5\nkro0 = 1.0\nnw = 3.0\nno = 1.0\n\nkr = RelPerms(swr, sor, krw0, kro0, nw, no)\n\n\u03bcw = 1.0\n\u03bco = 3.0\n\nsi = 0.20\nsj = 0.80\n\n\nwf = solve_waterflooding(si, sj, kr, \u03bcw, \u03bco)\n\nwf.S\u0303\n\nplot_fw(wf)\n\nplot_sw_profile(wf, 0.1, 0.2, 0.3, 0.5)\n\n\nanimate_sw_profile(wf)\n\n\n\n\n\n\n", "meta": {"hexsha": "96958b440f1b43a3a8d99750f3e7d0cf849c3f43", "size": 307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Ex1 - Waterflooding.jl", "max_stars_repo_name": "rlarao/AnalyticalEOR.jl", "max_stars_repo_head_hexsha": "219b2c6ef9a14209c90a9b39d7fa8e0b5581127a", "max_stars_repo_licenses": ["MIT"], "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/Ex1 - Waterflooding.jl", "max_issues_repo_name": "rlarao/AnalyticalEOR.jl", "max_issues_repo_head_hexsha": "219b2c6ef9a14209c90a9b39d7fa8e0b5581127a", "max_issues_repo_licenses": ["MIT"], "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 - Waterflooding.jl", "max_forks_repo_name": "rlarao/AnalyticalEOR.jl", "max_forks_repo_head_hexsha": "219b2c6ef9a14209c90a9b39d7fa8e0b5581127a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 8.5277777778, "max_line_length": 44, "alphanum_fraction": 0.5928338762, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593031, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7727549850615366}}
{"text": "@testset \"Single Criterion Decision Making Functions\" begin\n    @testset \"Single Criterion Decision Making tools\" begin\n        @testset \"Laplace\" begin\n\n            tol = 0.00001\n\n            mat = [\n                3000 2750 2500 2250\n                1500 4750 8000 7750\n                2000 5250 8500 11750\n            ]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = laplace(dm)\n\n            @test isa(result, LaplaceResult)\n\n            @test isapprox(result.expected_values, [2625.0, 5500, 6875], atol = tol)\n\n            @test result.bestIndex == 3\n        end\n\n\n        @testset \"Maximin\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = maximin(dm)\n\n            @test isa(result, MaximinResult)\n\n            @test isapprox(result.rowmins, [18, 18, 24, 20], atol = tol)\n\n            @test result.bestIndex == 3\n        end\n\n\n        @testset \"Maximax\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = maximax(dm)\n\n            @test isa(result, MaximaxResult)\n\n            @test isapprox(result.rowmaxs, [26, 34, 34, 30], atol = tol)\n\n            @test result.bestIndex in [2, 3]\n        end\n\n\n        @testset \"Minimax\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = minimax(dm)\n\n            @test isa(result, MinimaxResult)\n\n            @test isapprox(result.rowmaxs, [26, 34, 34, 30], atol = tol)\n\n            @test result.bestIndex == 1\n        end\n\n\n        @testset \"Minimin\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = minimin(dm)\n\n            @test isa(result, MiniminResult)\n\n            @test isapprox(result.rowmins, [18, 18, 24, 20], atol = tol)\n\n            @test result.bestIndex in [1, 2]\n        end\n\n\n\n        @testset \"Savage\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = savage(dm)\n\n            @test isa(result, SavageResult)\n\n            @test result.bestIndex == 4\n\n        end\n\n\n        @testset \"Hurwicz\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = hurwicz(dm)\n\n            @test isa(result, HurwiczResult)\n\n            @test result.bestIndex == 3\n\n        end\n\n\n\n        @testset \"Maximum likelihood for single criterion\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            weights = [0.2, 0.5, 0.2, 0.1]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = mle(dm, weights)\n\n            @test isa(result, MLEResult)\n\n            @test result.bestIndex == 2\n\n            @test isapprox(result.scores, [24, 29.2, 27, 27], atol = tol)\n        end\n\n\n\n        @testset \"Expected Regret\" begin\n\n            tol = 0.00001\n\n            mat = [\n                26 26 18 22\n                22 34 30 18\n                28 24 34 26\n                22 30 28 20\n            ]\n\n            weights = [0.2, 0.5, 0.2, 0.1]\n\n            dm = makeDecisionMatrix(mat)\n\n            result = expectedregret(dm, weights)\n\n            @test isa(result, ExpectedRegretResult)\n\n            @test result.bestIndex == 2\n\n            @test isapprox(result.scores, [8, 2.8, 5, 5], atol = tol)\n        end\n    end\nend\n", "meta": {"hexsha": "f3c115046b908b07ebcf81f61f7c6ccd6a40d993", "size": 4275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testscdm.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": "test/testscdm.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": "test/testscdm.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": 19.976635514, "max_line_length": 84, "alphanum_fraction": 0.4318128655, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7727549716452513}}
{"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\u00e8 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(\u03b8) = @. \u03b8*mat1 + (1-\u03b8)*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 \u03f5 for the SSA\nssa_eps_vals = [0.005,0.001,0.0005];\n\n# ### Compute and plot the SA\nsas = map(\u03b8->SSA.spectral_abscissa(mat(\u03b8)),thetas)\nplt=plot(thetas,sas ; color=:black, linewidth=3,lab=\"SA\",\n  xlabel=\"\u03b8\",ylabel=\"SA value\",leg=:top)\n\n# ### Compute and plot the SSA\nmycols=cgrad([colorant\"DarkGreen\",colorant\"orange\"])\nfor \u03f5 in ssa_eps_vals\n  ssas = map(\u03b8->SSA.ssa(mat(\u03b8),\u03f5),thetas)\n  plot!(plt,thetas,ssas ; linewidth=2.5 ,\n    lab=\"SSA $\u03f5\",palette=mycols)\nend\nplot!(plt,xlabel=\"\u03b8\",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 \u03f5 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": "@testset \"GeometricBM\" begin\n\nusing DiffEqNoiseProcess, DiffEqBase, Test, Statistics\n\n\u03bc = 1.0\n\u03c3 = 2.0\n\nW = GeometricBrownianMotionProcess(\u03bc,\u03c3,0.0,1.0,1.0)\ndt = 0.1\ncalculate_step!(W,dt,nothing,nothing)\nfor i in 1:10\n  accept_step!(W,dt,nothing,nothing)\nend\n\nW = GeometricBrownianMotionProcess(\u03bc,\u03c3,0.0,1.0,1.0)\nprob = NoiseProblem(W,(0.0,1.0))\nsol = solve(prob;dt=0.1)\n\nW = GeometricBrownianMotionProcess(\u03bc,\u03c3,0//1,1.0,1.0)\nprob_rational = NoiseProblem(W,(0,1))\ndt = 1//10\nsol = solve(prob_rational;dt=dt)\n\ndt = dt/100\nfor t in dt:dt:1-dt\n  sol(t)\nend\n\nt = 1.0\nu0 = 1.0\nexpected_mean = u0*exp(\u03bc*t)\nexpected_variance = u0^2*exp(2\u03bc*t)*(exp(\u03c3^2*t)-1)\nensemble_prob = EnsembleProblem(prob;output_func = (sol,i)-> (sol[end],false))\nsol = solve(ensemble_prob;dt=0.1,trajectories=40000)\n@test abs(mean(sol) - expected_mean) < 0.4\n#abs(var(sol) - expected_variance) < 0.4 # Converges slowly\n\nW = GeometricBrownianMotionProcess!(\u03bc,\u03c3,0.0,ones(2),ones(2))\nprob = NoiseProblem(W,(0.0,1.0))\nsol = solve(prob;dt=0.1)\n\nend\n", "meta": {"hexsha": "01486be24d59d62a3b49eaa35d35e083b04686d8", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/geometric_bm.jl", "max_stars_repo_name": "sfalmo/DiffEqNoiseProcess.jl", "max_stars_repo_head_hexsha": "b7c69ab44995be507fe830f76177d264defce252", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-04-14T12:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:47:33.000Z", "max_issues_repo_path": "test/geometric_bm.jl", "max_issues_repo_name": "frankschae/DiffEqNoiseProcess.jl", "max_issues_repo_head_hexsha": "108f01f545ef397e042a3a31f654e8fa1b073cf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2020-04-05T13:15:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T09:24:42.000Z", "max_forks_repo_path": "test/geometric_bm.jl", "max_forks_repo_name": "frankschae/DiffEqNoiseProcess.jl", "max_forks_repo_head_hexsha": "108f01f545ef397e042a3a31f654e8fa1b073cf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-05-02T14:51:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:39.000Z", "avg_line_length": 23.3953488372, "max_line_length": 78, "alphanum_fraction": 0.7027833002, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104868, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7726946214351242}}
{"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, \u03bd, \u03bc, \u03c3)\n    return (gamma((\u03bd+1)/2) / (gamma(\u03bd/2) * sqrt(pi*\u03bd*\u03c3^2)) * (1 + (x-\u03bc)^2/(\u03bd*\u03c3^2))^(-(\u03bd+1)/2))\nend\n\n\"\"\"\nt-distribution probability density function usinf Distributions.LocationScale\n\"\"\"\nfunction tdist_from_LocationScale(\u03bd, \u03bc, \u03c3)\n    return LocationScale(\u03bc, \u03c3, TDist(\u03bd))\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 (\u03bc|\u03c3^2 ~ Normal, \u03c3^2 ~ InverseGamma)\n\n    Inputs\n    ------\n    data: data (0 or 1)\n    \u03b10: shape parameter of prior (Gamma dist)\n    \u03b20: 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    \u03b1_star: shape parameter of posterior (Gamma dist)\n    \u03b2: inversed scale parameter (1/\u03b8) of posterior (Gamma dist)\n\n\"\"\"\nfunction gaussian_stats(data, \u03bc0, n0, \u03bd0, \u03bb0, 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    \u03bc_star = (n * mean_data + n0 * \u03bc0) / n_star\n    \u03bd_star = n + \u03bd0\n    \u03bb_star = ssd_data + (n * n0 / n_star) * (\u03bc0 - mean_data)^2 + \u03bb0\n    \u03c4_star = sqrt(\u03bb_star / (\u03bd_star * n_star))\n\n    posterior_\u03c3_sq = InverseGamma(\u03bd_star/2, \u03bb_star/2)\n    marginal_posterior_\u03bc = LocationScale(\u03bc_star, \u03c4_star, TDist(\u03bd_star))\n\n    sd_\u03bc = std(marginal_posterior_\u03bc)\n    ci_\u03bc_upper = quantile(marginal_posterior_\u03bc, prob - (1-prob)/2)\n    ci_\u03bc_lower = quantile(marginal_posterior_\u03bc, (1-prob)/2)\n    ci_\u03bc = [ci_\u03bc_lower, ci_\u03bc_upper]\n    mean_\u03c3_sq = mean(posterior_\u03c3_sq)\n    mode_\u03c3_sq = mode(posterior_\u03c3_sq)\n    median_\u03c3_sq = median(posterior_\u03c3_sq)\n    sd_\u03c3_sq = std(posterior_\u03c3_sq)\n    ci_\u03c3_sq_upper = quantile(posterior_\u03c3_sq, prob - (1-prob)/2)\n    ci_\u03c3_sq_lower = quantile(posterior_\u03c3_sq, (1-prob)/2)\n    ci_\u03c3_sq = [ci_\u03c3_sq_lower, ci_\u03c3_sq_upper]\n\n    stats_\u03bc = reshape([\u03bc_star, \u03bc_star, \u03bc_star, sd_\u03bc, ci_\u03bc], 1, 5)\n    stats_\u03c3_sq = reshape([mean_\u03c3_sq, median_\u03c3_sq, mode_\u03c3_sq, sd_\u03c3_sq, ci_\u03c3_sq], 1, 5)\n\n    stats_string = [\"Mean\", \"Median\", \"Mode\", \"SD\", \"CI\"]\n    results = DataFrame([stats_\u03bc; stats_\u03c3_sq], stats_string)\n    return results, marginal_posterior_\u03bc, posterior_\u03c3_sq\nend\n\n# Generate moc data\n\u03bc = 1.0\n\u03c3 = 2.0\nn = 50\nRandom.seed!(99)\ndata = rand(Normal(\u03bc, \u03c3), n)\n# histogram(data, bins=20)\n\n# Set prior\n\u03bc0 = 0.0\nn0 = 0.2\n\u03bd0 = 5.0\n\u03bb0 = 7.0\n\u03c40 = sqrt(\u03bb0 / (\u03bd0 * n0))\n\nprior_\u03c3_sq = InverseGamma(\u03bd0/2, \u03bb0/2)\nmarginal_prior_\u03bc = LocationScale(\u03bc0, \u03c40, TDist(\u03bd0))\n\n# Calculate posterior statistics\nprob = 0.95\nresults, marginal_posterior_\u03bc, posterior_\u03c3_sq = gaussian_stats(data, \u03bc0, n0, \u03bd0, \u03bb0, prob)\nprint(results)\n\n# Visualize Posterior\nl = @layout [grid(1, 2)]\n\np1 = plot(\n    marginal_prior_\u03bc, xlims=(-6, 6), ylims=(0, 1.55), xlabel=\"\u03bc\", ylabel=\"Probability Density\", \n    label=@sprintf(\"prior: T(\u03bd=%.1f, \u03bc=%.1f, \u03c3^2=%.1f)\", params(params(marginal_prior_\u03bc)[3])[1], params(marginal_prior_\u03bc)[1], params(marginal_prior_\u03bc)[2]), linestyle=:dash)\nplot!(marginal_posterior_\u03bc, label=@sprintf(\"posterior: T(\u03bd=%.1f, \u03bc=%.1f, \u03c3^2=%.1f)\", params(params(marginal_posterior_\u03bc)[3])[1], params(marginal_posterior_\u03bc)[1], params(marginal_posterior_\u03bc)[2]), linestyle=:solid)\n\np2 = plot(\n    prior_\u03c3_sq, xlims=(0, 10), ylims=(0, 0.65), xlabel=\"\u03c3^2\", ylabel=\"Probability Density\", \n    label=@sprintf(\"prior: InverseGamma(\u03b1=%.1f, \u03b8=%.1f)\", params(prior_\u03c3_sq)[1], params(prior_\u03c3_sq)[2]), linestyle=:dash)\nplot!(posterior_\u03c3_sq, label=@sprintf(\"posterior: InverseGamma(\u03b1=%.1f, \u03b8=%.1f)\", params(posterior_\u03c3_sq)[1], params(posterior_\u03c3_sq)[2]), linestyle=:solid)\n\nplot(p1, p2, laypout=l)\n# \u03bc\u306e\u63a8\u5b9a\u30d8\u30bf\u30af\u30bd\u3058\u3083\u306d?", "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\u2080, f, g, P, R, Q;\r\n        \u03b1=1e-3, \u03ba=1.0, \u03b2=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\u2080: 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\u03b1:  Distance between the sample point and mean point: 1 \u2264 \u03b1 \u2264 1e-3 (default)\r\n\u03ba:  Scaling factor (default 1.0)\r\n\u03b2:  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\u2080::Vector,\r\n    f::Function,\r\n    g::Function,\r\n    P::AbstractMatrix,\r\n\tR::AbstractMatrix,\r\n\tQ::AbstractMatrix;\r\n\t\u03b1::Real=1e-3,\r\n\t\u03ba::Real=3-length(x),\r\n\t\u03b2::Real=2.0,\r\n\tsqrt_filter::SquareRootFilter=CholeskyModSqrt(),\r\n\t)\r\n\r\n\tm = length(x\u2080)\r\n\r\n\t## Predict process\r\n\t# Sigma points and weights\r\n\t_X = _sigma_points(x\u2080, P, sqrt_filter, \u03b1, \u03ba, \u03b2, m)\r\n\tw_m, w_c = _mean_covariance_weights(m; \u03b1=\u03b1, \u03b2=\u03b2, \u03ba=\u03ba)\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\u0302 = _estimation(X_, w_m)\r\n\t# Predicted process covariance matrix, a priori\r\n\tP_ = _covariance_matrix_ukf(P, X_, x\u0302, 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, \u03b1, \u03ba, \u03b2, size(X_, 1))\r\n\tw_m_, w_c_ = _mean_covariance_weights(2*m; \u03b1=\u03b1, \u03b2=\u03b2, \u03ba=\u03ba)\r\n\t# Measurement estimation\r\n\tY_ = _propagate_sigma_nlf(g, _Y)\r\n\ty\u0302 = _estimation(Y_, w_m_)\r\n\t# Covariance matrix\r\n\tPyy = _covariance_matrix_ukf(P, Y_, y\u0302, w_c_, R)\r\n\t# Cross-covariance matrix\r\n\tPxy = _covariance_matrix_ukf(P, _Y, x\u0302, Y_, y\u0302, 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\u0302), x\u0302)\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\u0302),\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, \u03b1::Real, \u03b2::Real, \u03ba::Real, m::Int64,\r\n\t)\r\n\t\u03bb = \u03b1^2 * (m + \u03ba) - m\r\n\tPi = _square_root_filter(filter, sqrt(m + \u03bb) .* 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, \u03b1::Real, \u03b2::Real, \u03ba::Real, m::Int64,\r\n\t)\r\n\t\u03bb = \u03b1^2 * (m + \u03ba) - m\r\n\tPi = _square_root_filter(filter, sqrt(m + \u03bb).*P)\r\n\treturn hcat(X, X[:,1] .+ Pi, X[:,1] .- Pi)\r\nend\r\n\r\nfunction _mean_covariance_weights(m::Int64; \u03b1::Real=1e-3, \u03b2::Real=2.0, \u03ba::Real=1.0)\r\n\t\u03bb = \u03b1^2 * (m + \u03ba) - m\r\n\tw_m = ones(2*m + 1) .* 0.5 / (m + \u03bb) # mean weights\r\n\tw_c = copy(w_m) # covariance weights\r\n\tw_m[1] = \u03bb / (m + \u03bb)\r\n\tw_c[1] += one(\u03b2) + \u03b2 - \u03b1^2\r\n\treturn w_m, w_c\r\nend\r\n\r\n_propagate_sigma_nlf(f::Function, \u03c7::Array) = (x -> f(x))(\u03c7)\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\u030c = chebyshevtransform(f; kind=1)\n\nf\u0303 = x -> [cos(k*acos(x)) for k=0:n-1]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# first kind polynomials -> first kind points\nichebyshevtransform(f\u030c; kind=1) \u2248 exp.(p_1)\n\n# second kind points -> first kind polynomials\np_2 = chebyshevpoints(Float64, n; kind=2)\nf = exp.(p_2)\nf\u030c = chebyshevtransform(f; kind=2)\n\nf\u0303 = x -> [cos(k*acos(x)) for k=0:n-1]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# first kind polynomials -> second kind points\nichebyshevtransform(f\u030c; kind=2) \u2248 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\u030c = chebyshevutransform(f; kind=1)\nf\u0303 = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-1]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# second kind polynomials -> first kind points\nichebyshevutransform(f\u030c; kind=1) \u2248 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\u030c = chebyshevutransform(f; kind=2)\nf\u0303 = x -> [sin((k+1)*acos(x))/sin(acos(x)) for k=0:n-3]' * f\u030c\nf\u0303(0.1) \u2248 exp(0.1)\n\n# second kind polynomials -> second kind points\nichebyshevutransform(f\u030c; kind=2) \u2248 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^(\u2297p) = A \u2297 A \u2297 ... \u2297 A\n# where \u2297 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: \u03c1v(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\u03c3= 2.0 #\n\u03c1 = 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\u03b5 = 10e-6\n\n\u0394 = 1000\n\ndVf, dVb= [zeros(H,1) for i =1:2]\n\n#initial guess for V\nv0 = (w.+r.*a).^(1-\u03c3)/(1-\u03c3)/\u03c1\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).^(-\u03c3) # the boundary condition\n\n\tI_concave = dVb .> dVf\n\n    # consumption and savings with forward difference\n    cf = dVf.^(-1/\u03c3)\n    ssf = w.+r.*a-cf\n\n    # consumption and savings with backward difference\n\tcb = dVb.^(-1/\u03c3)\n\tssb = w.+r.*a-cb\n\n    # consumption and savings at steady state\n    c0=w.+r.*a\n    dV0 =c0.^(-\u03c3)\n\n    #look at the sign of the drift\n        #to choose forward or backward difference\n    If = ssf .> 0 # positive drift \u21d2 forward difference\n    Ib = ssb .< 0  # negative drift \u21d2 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/\u03c3)\n     u = c.^(1-\u03c3)/(1-\u03c3)\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 = (\u03c1 + 1/\u0394)*sparse(I, H, H) - A\n\n     b = u + V/\u0394\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] .< \u03b5\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-\u03c3)/(1-\u03c3) + dVb.*(w .+ r.*a -c) - \u03c1.*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        \u0394\u03bb = deg2rad(y[1] - x[1])\n\n        # latitudes\n        \u03c6\u2081 = deg2rad(x[2])\n        \u03c6\u2082 = deg2rad(y[2])\n    end\n\n    \u0394\u03c6 = \u03c6\u2082 - \u03c6\u2081\n\n    # haversine formula\n    a = sin(\u0394\u03c6/2)^2 + cos(\u03c6\u2081)*cos(\u03c6\u2082)*sin(\u0394\u03bb/2)^2\n\n    # distance on the sphere\n    2 * dist.radius * asin( min(\u221aa, 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": "# by Lazaro Alonso\n# port from the original code used in:\n# L Alonso, et. al. https://doi.org/10.1093/comnet/cnx053\n\n# using CairoMakie # HIDE\nusing LinearAlgebra, Random, GLMakie\nGLMakie.activate!() # hide\nfunction RRGAdjacencyM3D(;radius = 0.17, nodes = 500, rseed = 123)\n    Random.seed!(rseed)\n    xy = rand(nodes, 3)\n    x = xy[:,1]\n    y = xy[:,2] \n    z = xy[:,3]\n\n    matrixAdjDiag = Diagonal(\u221a2 * randn(nodes))\n    matrixAdj = zeros(nodes, nodes)\n    for point in 1:nodes-1\n        xseps = (x[point + 1:end] .- x[point]).^2\n        yseps = (y[point + 1:end] .- y[point]).^2\n        zseps = (z[point + 1:end] .- z[point]).^2\n        \n        distance = sqrt.(xseps.+ yseps .+ zseps)\n        dindx = findall(distance .<= radius) .+ point\n        if length(dindx) > 0\n            rnd = randn(length(dindx))\n            matrixAdj[point, dindx] = rnd\n            matrixAdj[dindx, point] = rnd\n        end\n    end\n    return (matrixAdj .+ matrixAdjDiag, x, y, z)\nend\nadjacencyM3D, x, y, z = RRGAdjacencyM3D()\n\nfunction getGraphEdges3D(adjMatrix3D, x, y, z)\n    xyzos = []\n    weights = [] \n    for i in 1:length(x), j in i+1:length(x)\n        if adjMatrix3D[i,j] != 0.0\n            push!(xyzos, [x[i], y[i], z[i]])\n            push!(xyzos, [x[j], y[j], z[j]])\n            push!(weights, adjMatrix3D[i,j])\n            push!(weights, adjMatrix3D[i,j])\n        end\n    end\n    return (Point3f0.(xyzos), Float32.(weights))\nend\n\nfunction plotGraph3D(adjacencyM3D, x, y, z)\n    cmap = (:Spectral_11, 0.75)\n    adjmin = minimum(adjacencyM3D)\n    adjmax = maximum(adjacencyM3D)\n    diagValues = diag(adjacencyM3D)\n    segm, weights = getGraphEdges3D(adjacencyM3D, x, y, z)\n    \n    fig, ax, pltobj = linesegments(segm, color = weights, colormap = cmap, \n        linewidth = abs.(weights), colorrange = (adjmin, adjmax), \n        figure = (;resolution = (1000,800)), \n        axis = (; type = Axis3, aspect =(1,1,1), perspectiveness = 0.5))\n    meshscatter!(ax, x, y, z, color = diagValues, markersize = abs.(diagValues)./90,\n        colorrange = (adjmin, adjmax), colormap = cmap)\n    #limits!(ax, -0.02,1.02,-0.02,1.02)\n    Colorbar(fig[1,2], pltobj, label = \"weights\", height = Relative(0.5))\n    fig\nend\n#plotGraph(adjacencyM, x, y)\nrrgraph3D = with_theme(theme_black()) do\n    plotGraph3D(adjacencyM3D, x, y, z)\nend\nsave(joinpath(@__DIR__, \"output\", \"RRGraph3D.png\"), rrgraph3D, px_per_unit = 2.0) # HIDE\nusing Pkg # HIDE\nPkg.status([\"GLMakie\", \"LinearAlgebra\", \"Random\"]) # HIDE", "meta": {"hexsha": "4cf758a8f483980a7f0f87a97f27a0f6ab908f76", "size": 2478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_assets/scripts/RRGraph3D.jl", "max_stars_repo_name": "MisterBiggs/BeautifulMakie", "max_stars_repo_head_hexsha": "5e43819d1f2af8b80bf45895bc117cd55197d972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 249, "max_stars_repo_stars_event_min_datetime": "2021-06-07T13:10:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:55:41.000Z", "max_issues_repo_path": "_assets/scripts/RRGraph3D.jl", "max_issues_repo_name": "MisterBiggs/BeautifulMakie", "max_issues_repo_head_hexsha": "5e43819d1f2af8b80bf45895bc117cd55197d972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-06-09T06:03:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T16:17:43.000Z", "max_forks_repo_path": "_assets/scripts/RRGraph3D.jl", "max_forks_repo_name": "MisterBiggs/BeautifulMakie", "max_forks_repo_head_hexsha": "5e43819d1f2af8b80bf45895bc117cd55197d972", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2021-06-09T05:21:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T09:16:08.000Z", "avg_line_length": 34.9014084507, "max_line_length": 88, "alphanum_fraction": 0.5960451977, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7726510199737358}}
{"text": "@testset \"FBM\" begin\n    rng = MersenneTwister(42)\n    h = 0.3\n    k = FBMKernel(h = h)\n    v1 = rand(rng, 3); v2 = rand(rng, 3)\n    @test k(v1,v2) \u2248 (sqeuclidean(v1, zero(v1))^h + sqeuclidean(v2, zero(v2))^h - sqeuclidean(v1-v2, zero(v1-v2))^h)/2 atol=1e-5\n\n    # kernelmatrix tests\n    m1 = rand(rng, 3, 3)\n    m2 = rand(rng, 3, 3)\n    Kref = kernelmatrix(k, m1, m1)\n    @test kernelmatrix(k, m1) \u2248 Kref atol=1e-5\n    K = zeros(3, 3)\n    kernelmatrix!(K, k, m1, m1)\n    @test K \u2248 Kref atol=1e-5\n    fill!(K, 0)\n    kernelmatrix!(K, k, m1)\n    @test K \u2248 Kref atol=1e-5\n\n    x1 = rand(rng)\n    x2 = rand(rng)\n    @test kernelmatrix(k, x1*ones(1,1), x2*ones(1,1))[1] \u2248 k(x1, x2) atol=1e-5\n\n    @test repr(k) == \"Fractional Brownian Motion Kernel (h = $(h))\"\n    test_ADs(FBMKernel, ADs = [:ReverseDiff])\n    @test_broken \"Tests failing for kernelmatrix(k, x) for ForwardDiff and Zygote\"\nend\n", "meta": {"hexsha": "77ed3b537a316a945421560585a837ff9281874c", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/fbm.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": "test/basekernels/fbm.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": "test/basekernels/fbm.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": 31.7857142857, "max_line_length": 128, "alphanum_fraction": 0.5876404494, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7726510176336501}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e44af6da-9045-11eb-15ab-ad339f35ca21\nusing ImageFiltering,FileIO,ImageShow,TestImages,Images\n\n# \u2554\u2550\u2561 002e63da-9046-11eb-20b5-4f1bf8ff7260\nimg = load(\"../hello-world.png\");\n\n# \u2554\u2550\u2561 03a23ec6-9046-11eb-035c-ffb12919833f\nimgg = imfilter(img, Kernel.gaussian(3));\n\n# \u2554\u2550\u2561 09e7aea6-9046-11eb-3d06-c3980898c7bb\nimgl = imfilter(img, Kernel.Laplacian());\n\n# \u2554\u2550\u2561 3ffbb60e-9048-11eb-1b5e-57ef5a52c22d\n# imgs = imfilter(img, Kernel.sobel())\n\n# \u2554\u2550\u2561 54499d7c-9048-11eb-0b1b-13f6373e402c\nimg_coins = load(\"../1.jpg\")\n\n# \u2554\u2550\u2561 9d38abe4-905d-11eb-1ba2-958ed4d9e9af\nimg_gray = Gray.(img_coins)\n\n# \u2554\u2550\u2561 da50f694-905d-11eb-29dd-d160c78bc260\nkernel = [1 0 -1; 2 0 -2;1 0 -1];\n\n# \u2554\u2550\u2561 e082aeb8-905d-11eb-047c-5bb3725816ab\nsobel_x = imfilter(img_gray, kernel);\n\n# \u2554\u2550\u2561 e42883f6-905d-11eb-07bf-a9f6acecf1a1\ngrad = imfilter(sobel_x, kernel')\n\n# \u2554\u2550\u2561 acceb0e8-905e-11eb-027a-a1c08f28641c\n\n\n# \u2554\u2550\u2561 02069d1a-905e-11eb-3471-9f3545ac23f4\ngrad .^ 4\n\n# \u2554\u2550\u2561 10460d34-905e-11eb-15ab-57d2dd4b66ef\nbegin\n\tkernel_1 = [1 2 1]';\nkernel_2 = [1 0 -1];\ngrad_sep = imfilter(img_gray, (kernel_1, kernel_2, kernel_2', kernel_1'))\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550e44af6da-9045-11eb-15ab-ad339f35ca21\n# \u2560\u2550002e63da-9046-11eb-20b5-4f1bf8ff7260\n# \u2560\u255003a23ec6-9046-11eb-035c-ffb12919833f\n# \u2560\u255009e7aea6-9046-11eb-3d06-c3980898c7bb\n# \u2560\u25503ffbb60e-9048-11eb-1b5e-57ef5a52c22d\n# \u2560\u255054499d7c-9048-11eb-0b1b-13f6373e402c\n# \u2560\u25509d38abe4-905d-11eb-1ba2-958ed4d9e9af\n# \u2560\u2550da50f694-905d-11eb-29dd-d160c78bc260\n# \u2560\u2550e082aeb8-905d-11eb-047c-5bb3725816ab\n# \u2560\u2550e42883f6-905d-11eb-07bf-a9f6acecf1a1\n# \u2560\u2550acceb0e8-905e-11eb-027a-a1c08f28641c\n# \u2560\u255002069d1a-905e-11eb-3471-9f3545ac23f4\n# \u2560\u255010460d34-905e-11eb-15ab-57d2dd4b66ef\n", "meta": {"hexsha": "554af3e01caba680dbbc776bc5a7c1db249c96ea", "size": 1716, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "image_filter.jl", "max_stars_repo_name": "ashwani-rathee/Demos", "max_stars_repo_head_hexsha": "b4980035c9cdf0384bfe1f743c0442d68861238b", "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": "image_filter.jl", "max_issues_repo_name": "ashwani-rathee/Demos", "max_issues_repo_head_hexsha": "b4980035c9cdf0384bfe1f743c0442d68861238b", "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": "image_filter.jl", "max_forks_repo_name": "ashwani-rathee/Demos", "max_forks_repo_head_hexsha": "b4980035c9cdf0384bfe1f743c0442d68861238b", "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.8125, "max_line_length": 73, "alphanum_fraction": 0.729020979, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797051879432, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7726510155884034}}
{"text": "\"\"\"\n        greedy_star1_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 `\u03c7(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\"\"\"\nfunction color_graph(g::LightGraphs.AbstractGraph, ::GreedyStar1Color)\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\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                        for y in inneighbors(g, x)\n                           if colorvec[y] != 0\n                                if y != w && colorvec[y] == colorvec[w]\n                                    forbidden_colors[colorvec[x]] = vertex_i\n                                    break\n                                end\n                            end\n                        end\n                    end\n                end\n            end\n        end\n\n        colorvec[vertex_i] = find_min_color(forbidden_colors, vertex_i)\n    end\n\n    colorvec\nend\n\nfunction find_min_color(forbidden_colors::AbstractVector, vertex_i::Integer)\n    c = 1\n    while (forbidden_colors[c] == vertex_i)\n        c+=1\n    end\n    c\nend\n", "meta": {"hexsha": "693e4386fc3d8c0c54458149b57773ef19e46c6b", "size": 2106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coloring/greedy_star1_coloring.jl", "max_stars_repo_name": "michel2323/SparseDiffTools.jl", "max_stars_repo_head_hexsha": "0e32898593170640238bd6f85ead67a749dda18d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93, "max_stars_repo_stars_event_min_datetime": "2020-01-08T19:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:12:26.000Z", "max_issues_repo_path": "src/coloring/greedy_star1_coloring.jl", "max_issues_repo_name": "michel2323/SparseDiffTools.jl", "max_issues_repo_head_hexsha": "0e32898593170640238bd6f85ead67a749dda18d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2020-01-07T16:14:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T23:05:53.000Z", "max_forks_repo_path": "src/coloring/greedy_star1_coloring.jl", "max_forks_repo_name": "michel2323/SparseDiffTools.jl", "max_forks_repo_head_hexsha": "0e32898593170640238bd6f85ead67a749dda18d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2020-02-06T06:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T08:25:54.000Z", "avg_line_length": 30.9705882353, "max_line_length": 153, "alphanum_fraction": 0.5769230769, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7726510147225129}}
{"text": "n = 10 # rand(1:10)\n# no null vector for 1-by-1 chebspec.\nif n == 1\n    n = 2\nend\nA = matrixdepot(\"chebspec\", n)\n# A has null vector ones(n)\n@test A*ones(n) \u2248 zeros(n) atol = 1e-6\nB = matrixdepot(\"chebspec\", n, 1)\n# B's eigenvalues have negative real parts.\nv = real(eigvals(B))\nfor i = 1:n\n    @test v[i] < 0\nend\nprintln(\"'chebspec' passed test...\")\n", "meta": {"hexsha": "f8d27cc43d11c11c1d7f59b89f854f2d3a35a83d", "size": 351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_chebspec.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_chebspec.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_chebspec.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 21.9375, "max_line_length": 43, "alphanum_fraction": 0.6239316239, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7726510147225129}}
{"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, \u03be)\n    prev = [3, 1, 2]\n    succ = [2, 3, 1]\n    m = length(\u03be)\n    start = zeros(2, m)\n    finish = zeros(2, m)\n    for k = 1:m\n        \u03b7 = -0.3\n        start[:,k] = ( a[:,prev[j]] + \u03be[k] * ( a[:,j] - a[:,prev[j]] ) \n                      + \u03b7 * ( a[:,succ[j]] - a[:,prev[j]] ) )\n        \u03b7 = 1.1 - \u03be[k] \n        finish[:,k] = ( a[:,prev[j]] + \u03be[k] * ( a[:,j] - a[:,prev[j]] ) \n                      + \u03b7 * ( 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    \u03be = [0, 1/3, 2/3, 1]\n    start, finish = level_sets(a, j, \u03be)\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        \u03bb = dot(c - a[:,succ[j]], bhat)\n        foot = c - \u03bb * 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": "using SymPy\nusing Base.Test\n\n\n## matrices\n(x,) = @syms x\nA = [x 1; 1 x]\na = convert(SymMatrix, A) ## for [:meth] calls\nb = [x, 2]\n\n\n## These fail for older installations of SymPy, such as are present in the travis test environment\n\ndet(A)\ndet(a)\n\n## we use inverse for A[:inv]()\ninv(A) # aliased to use inverse\ninverse(A)\na[:inv]() |> u -> convert(Array{Sym}, u)\na[:inv](\"LU\")                   # pass argument to function\nadjoint(A)\ndual(A)\ncholesky(A)\n## other functions, could wrap\nb = subs(a, x, 2)\nQRdecomposition(b)\n\n@assert is_square(a) == true\n@assert is_symmetric(a) == true\n\n\neigvals(A)\n\n\n\na = [1 0 0; 0 1 0; 0 0 x]\nevecs = eigvecs(a)\n@assert float(evecs) == eye(3)\n\neh = convert(SymMatrix, a)\neh[9]\nconvert(SymMatrix, reshape([x, 1:23...], (2,3,4)))\n\n", "meta": {"hexsha": "e4a37d7b1fa156c8bb1c01271611d94f595b610b", "size": 762, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-matrix.jl", "max_stars_repo_name": "JuliaPackageMirrors/SymPy.jl", "max_stars_repo_head_hexsha": "a99bac82866a35bf9d61bd2c7802998c4efb3418", "max_stars_repo_licenses": ["MIT"], "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-matrix.jl", "max_issues_repo_name": "JuliaPackageMirrors/SymPy.jl", "max_issues_repo_head_hexsha": "a99bac82866a35bf9d61bd2c7802998c4efb3418", "max_issues_repo_licenses": ["MIT"], "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-matrix.jl", "max_forks_repo_name": "JuliaPackageMirrors/SymPy.jl", "max_forks_repo_head_hexsha": "a99bac82866a35bf9d61bd2c7802998c4efb3418", "max_forks_repo_licenses": ["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.9333333333, "max_line_length": 98, "alphanum_fraction": 0.624671916, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7726093217109445}}
{"text": "function inner_product(x::AbstractExpr, y::AbstractExpr)\n    if x.size == y.size && x.size[1] == x.size[2]\n        return real(tr(x'*y))\n    else\n        error(\"Arguments must be square matrix of same dimension\")\n    end\nend\n\ninner_product(x::Value, y::AbstractExpr) = inner_product(Constant(x),y)\ninner_product(x::AbstractExpr, y::Value) = inner_product(x,Constant(y))\n", "meta": {"hexsha": "ab402896ba3c08e8db42a0607d587ed0b0c33695", "size": 370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoms/affine/inner_product.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/affine/inner_product.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/affine/inner_product.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.6363636364, "max_line_length": 71, "alphanum_fraction": 0.6810810811, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7726093216807666}}
{"text": "m = 21          # The number of 'space' nodes\nn = 401         # The number of 'time' nodes\n\u03c4 = 10/(n-1)    # Time step size\nh = 1/(m-1)     # Space step size\n\n\u03bb = 0.3\n\u03b1 = 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\u03b1 = 0.3+0.1*(1-cos(1))         # Integral of g(x) = 0.3 +0.1sin(x) = 0.3+0.1(1-cos1)\n\u03bc = 1./(1-x).^2; \u03bc[1] = 0; \u03bc[m] = 0;\n\u03b2 = zeros(m,m)\n\u03b3 = (1-\u03bb*\u03c4+h*\u03c4/2)\n\noptv = 0.85 + 0.05cos(2\u03c0*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 - \u03c4*\u03bc[i] + \u03c4/h\n    A[i,i+1] = 1 - \u03c4*\u03bc[i] - \u03c4/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(\u03c0t) 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+\u221a30)/36,(18-\u221a30)/36]\npoint1 = \u221a(3-2(\u221a6)/(\u221a5))/\u221a7\npoint2 = \u221a(3+2(\u221a6)/(\u221a5))/\u221a7\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(\u03c0*t)\n\n## Calculate \u03b2\n\u03b2 = zeros(n,n)\n\u03b2[1,1] = \u03b1\nfor j=2:n\n    for k = 1:j-1\n       a = (A^(j-1-k))'*\u03bc\n       \u03b2[j,k] = dot(\u03bc,g)[1]\n    end\n       \u03b2[j,j] = \u03b1\nend\n\nB = zeros(n,n)\nB[1,1] = \u03b1\nfor j=2:n\n    for k=1:j\n        B[j,:] += \u03b3^(j-k)*\u03b2[k,:]\n    end\nend\nB = \u03c4*B\nd = zeros(n,1)\nfor i=1:n\n  d[i] = \u03b3^(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,:] = \u03bb*estv\nw[1,1] = 0\nfor i=2:n\n    w[:,i] = A*w[:,i]-\u03c4*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\u03c0 * k) / (size-1))\ncosine_series2( size, k, a0, a1, a2) = \n    cosine_series1(size, k, a0, a1) + a2 * cos((2 * 2\u03c0 * k) / (size-1))\ncosine_series3(size, k, a0, a1, a2, a3) = \n    cosine_series2(size, k, a0, a1, a2) - a3 * cos((3 * 2\u03c0 * 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\u03c0 * 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": "@testset \"link\" begin\n    x = rand()\n    xs = rand(3)\n\n    # Generic link\n    f = sin\n    l = Link(f)\n    @test l(x) == f(x)\n\n    # Log\n    l = LogLink()\n    @test l(x) == log(x)\n    @test inv(l) == ExpLink()\n    @test inv(inv(l)) == l\n\n    # Exp\n    l = ExpLink()\n    @test l(x) == exp(x)\n    @test inv(l) == LogLink()\n    @test inv(inv(l)) == l\n\n    # Sqrt\n    l = SqrtLink()\n    @test l(x) == sqrt(x)\n    @test inv(l) == SquareLink()\n    @test inv(inv(l)) == l\n\n    # Square\n    l = SquareLink()\n    @test l(x) == x^2\n    @test inv(l) == SqrtLink()\n    @test inv(inv(l)) == l\n\n    # Logit\n    l = LogitLink()\n    @test l(x) == logit(x)\n    @test inv(l) isa LogisticLink\n    @test inv(inv(l)) == l\n\n    # Logistic\n    l = LogisticLink()\n    @test l(x) == logistic(x)\n    @test inv(l) isa LogitLink\n    @test inv(inv(l)) == l\n\n    # Probit\n    l = ProbitLink()\n    @test l(x) == norminvcdf(x)\n    @test inv(l) == NormalCDFLink()\n    @test inv(inv(l)) == l\n\n    # NormalCDF\n    l = NormalCDFLink()\n    @test l(x) == normcdf(x)\n    @test inv(l) == ProbitLink()\n    @test inv(inv(l)) == l\n\n    # SoftMax\n    l = SoftMaxLink()\n    @test l(xs) == softmax(xs)\nend\n", "meta": {"hexsha": "d4e4aa2a420929b73782f1de57217ef2f9172dd2", "size": 1159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/links.jl", "max_stars_repo_name": "JuliaGaussianProcesses/GPLikelihoods.jl", "max_stars_repo_head_hexsha": "d42a9a2d5169e19f2b2290100d2510de291cf71d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-09-17T07:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:22:53.000Z", "max_issues_repo_path": "test/links.jl", "max_issues_repo_name": "JuliaGaussianProcesses/GPLikelihoods.jl", "max_issues_repo_head_hexsha": "d42a9a2d5169e19f2b2290100d2510de291cf71d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-09-04T16:02:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:25:36.000Z", "max_forks_repo_path": "test/links.jl", "max_forks_repo_name": "JuliaGaussianProcesses/GPLikelihoods.jl", "max_forks_repo_head_hexsha": "d42a9a2d5169e19f2b2290100d2510de291cf71d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-21T01:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T23:19:03.000Z", "avg_line_length": 18.6935483871, "max_line_length": 35, "alphanum_fraction": 0.4849007765, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030095, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7726035635955216}}
{"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": "module new_logistic_regression\n\nusing Distributions\n\nstruct data\n    y::Vector\n    x::Array{Float64}\n    m::Vector\nend\n\n## Logistic regression nobs\nfunction nobs(data::data)\n    nx = size(data.x)[1]\n    ny = length(data.y)\n    nm = length(data.m)\n    if (nx != ny) \n        error(\"number of rows in of x is not equal to the length of y\")\n    elseif (nx != nm)\n        error(\"number of rows in of x is not equal to the length of m\")\n    elseif (ny != nm)\n        error(\"length of y is not equal to the length of m\")\n    end\n    return nx\nend\n\nfunction observation(data::data, i::Int64)\n    vcat(data.y[i], data.m[i], data.x[i,:])\nend\n\nfunction loglik(theta::AbstractArray,\n                obs::AbstractArray)\n    y = obs[1]\n    m = obs[2]\n    x = obs[3:end]\n    eta = sum(x .* theta)\n    mu = exp.(eta) ./ (1 .+ exp.(eta))\n    return y .* log.(mu) + (m - y) .* log.(1 .- mu)\nend\n\nfunction logistic_ef(theta::AbstractArray,\n                     obs::AbstractArray)\n    y = obs[1]\n    m = obs[2]\n    x = obs[3:end]\n    eta = sum(x .* theta)\n    mu = exp.(eta) ./ (1 .+ exp.(eta))\n    return x * (y - m * mu)\nend\n\nfunction simulate(theta::Vector,\n                  x::Matrix{Float64},\n                  m::Vector{Int64})\n    n = size(x)[2]\n    y = rand.(Binomial.(m, cdf.(Logistic(), x * theta)))\n    data(y, x, m);\nend\n\n\nend", "meta": {"hexsha": "9f7d2a6f62aadb342ce7663b4740bf7485ffa505", "size": 1321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/new_logistic_regression.jl", "max_stars_repo_name": "jacobusmmsmit/MEstimation.jl", "max_stars_repo_head_hexsha": "966b4b0cd0599c3af629e65ff9785e7f87316782", "max_stars_repo_licenses": ["MIT"], "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/new_logistic_regression.jl", "max_issues_repo_name": "jacobusmmsmit/MEstimation.jl", "max_issues_repo_head_hexsha": "966b4b0cd0599c3af629e65ff9785e7f87316782", "max_issues_repo_licenses": ["MIT"], "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/new_logistic_regression.jl", "max_forks_repo_name": "jacobusmmsmit/MEstimation.jl", "max_forks_repo_head_hexsha": "966b4b0cd0599c3af629e65ff9785e7f87316782", "max_forks_repo_licenses": ["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.3898305085, "max_line_length": 71, "alphanum_fraction": 0.550340651, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7726035505294808}}
{"text": "\n# ## Data\n\nimport CSV\nimport Random\nimport TuringModels\n\nusing DataFrames\n\nRandom.seed!(1)\n\ndata_path = joinpath(TuringModels.project_root, \"data\", \"UCBadmit.csv\")\ndf = CSV.read(data_path, DataFrame; delim=';')\n\n# ## Model\n\nusing StatsFuns: logistic\nusing Turing\n\n@model function m11_5(admit, applications)\n  \u03b8 ~ truncated(Exponential(1), 0, Inf)\n  \u03b1 ~ Normal(0, 2)\n\n  ## alpha and beta for the BetaBinomial must be provided.\n  ## The two parameterizations are related by\n  ## alpha = prob * theta, and beta = (1-prob) * theta.\n  ## See https://github.com/rmcelreath/rethinking/blob/master/man/dbetabinom.Rd\n\n  prob = logistic(\u03b1)\n  alpha = prob * \u03b8\n  beta = (1 - prob) * \u03b8\n  admit .~ BetaBinomial.(applications, alpha, beta)\nend\n\nmodel = m11_5(df.admit, df.applications);\n\n# ## Output\n\nchns = sample(model, NUTS(), 1000)\n\n# \\defaultoutput{}\n\n# ## Original output\n\n\"\"\"\n        mean   sd  5.5% 94.5% n_eff Rhat\ntheta   2.74 0.96  1.43  4.37  3583    1\na       -0.37 0.31 -0.87  0.12  3210    1\n\"\"\";\n", "meta": {"hexsha": "6d882c449ed414af9a1b64b2cb3a05c1a54e9856", "size": 998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/beta-binomial.jl", "max_stars_repo_name": "mojojojoe/TuringModels.jl", "max_stars_repo_head_hexsha": "6c10dc5d432452f0d6dd76d2be623c6bf04b8597", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 145, "max_stars_repo_stars_event_min_datetime": "2019-03-05T12:24:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:37:26.000Z", "max_issues_repo_path": "scripts/beta-binomial.jl", "max_issues_repo_name": "mojojojoe/TuringModels.jl", "max_issues_repo_head_hexsha": "6c10dc5d432452f0d6dd76d2be623c6bf04b8597", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-10-01T20:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T13:36:40.000Z", "max_forks_repo_path": "scripts/beta-binomial.jl", "max_forks_repo_name": "mojojojoe/TuringModels.jl", "max_forks_repo_head_hexsha": "6c10dc5d432452f0d6dd76d2be623c6bf04b8597", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2019-06-29T17:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T18:32:53.000Z", "avg_line_length": 19.96, "max_line_length": 79, "alphanum_fraction": 0.6593186373, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992905050948, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7725644112181363}}
{"text": "\nusing JuMP\nusing ECOS\nusing LinearAlgebra\nusing Random\n\nRandom.seed!(1234);\n\n@testset \"Test SecondOrderCone formulations\" begin\n    u0 = rand(10)\n    p = rand(10)\n    q = rand();\n\n    optimal_value_soc = 0.7413476010760025\n    @testset \"Primal formulation\" begin\n        model = 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)\n        optimize!(model)\n        @test JuMP.termination_status(model) == MOI.OPTIMAL\n        @test objective_value(model) \u2248 optimal_value_soc atol=1e-6\n    end\n    @testset \"Dual formulation\" begin\n        e1 = [1, zeros(10)...]\n        dual_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())\n        optimize!(dual_model)\n        @test JuMP.termination_status(dual_model) == MOI.OPTIMAL\n        @test objective_value(dual_model) \u2248 optimal_value_soc atol=1e-6\n    end\nend\n\n@testset \"Test RotatedSecondOrderCone formulation\" begin\n    u0 = rand(10)\n    p = rand(10)\n    q = rand();\n    model = 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)\n    optimize!(model)\n    @test JuMP.termination_status(model) == MOI.OPTIMAL\n    @test objective_value(model) \u2248 0.5495962595148015 atol=1e-6\nend\n\n@testset \"Test ExponentialCone formulations\" begin\n    n = 15;\n    m = 10;\n    A = randn(m, n);\n    b = rand(m, 1);\n\n    model = 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], [t[i], x[i], 1.0] in MOI.ExponentialCone())\n\n    optimize!(model);\n    @test objective_value(model) \u2248 2.708050207925179\n    @test JuMP.termination_status(model) == MOI.OPTIMAL\nend\n\n", "meta": {"hexsha": "4c8b05657ae64e48538d8df145dbbdc1715ff03a", "size": 2518, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optimization_concepts/conic_programming.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": "test/optimization_concepts/conic_programming.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/optimization_concepts/conic_programming.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": 33.5733333333, "max_line_length": 92, "alphanum_fraction": 0.6350277998, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7725580174218105}}
{"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": "using GeneralTridiagonal\nusing LinearAlgebra: Tridiagonal\n\nconst T = Rational{Int64}\n\n\u03b2 = T[-1, 3, 0, 5]\n\u03b1 = T[0, 8, 2, 1, 8]\n\u03b3 = T[1, 4, 0, -3]\n\u03b4 = Array{T}(undef, 3)\np = Array{Bool}(undef, 4)\n\nA = Tridiagonal(\u03b2, \u03b1, \u03b3)\nx = T[-2, 5, 8, 0, -3]\nb = A*x\n\nfactorize!(\u03b2, \u03b1, \u03b3, \u03b4, p)\nprintln(\"Row swaps: \", p)\n\nsolve!(b, \u03b2, \u03b1, \u03b3, \u03b4, p)\nprintln(\"   Exact solution: x = \", x)\nprintln(\"Computed solution: x = \", b)\n", "meta": {"hexsha": "9b68ad2f86c9a02b0076df504307a97f7dd1fc6e", "size": 406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/appendixA/test1.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/appendixA/test1.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/appendixA/test1.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": 18.4545454545, "max_line_length": 37, "alphanum_fraction": 0.5714285714, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.772497933915022}}
{"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    \u03bc0 = 0.0\n    \u03c30 = 1.0\n\n    # Draw weights.\n    \u03c01 ~ Beta(1, 1)\n    \u03c02 = 1 - \u03c01\n\n    # Draw locations of the components.\n    \u03bc1 ~ Normal(\u03bc0, \u03c30)\n    \u03bc2 ~ Normal(\u03bc0, \u03c30)\n\n    # Draw latent assignment.\n    z ~ Categorical([\u03c01, \u03c02])\n\n    # Draw observation from selected component.\n    if z == 1\n        x ~ Normal(\u03bc1, 1.0)\n    else\n        x ~ Normal(\u03bc2, 1.0)\n    end\nend\n\n\nusing Turing.RandomMeasures\n\n\n# Concentration parameter.\n\u03b1 = 10.0\n\n# Random measure, e.g. Dirichlet process.\nrpm = DirichletProcess(\u03b1)\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    \u03b1 = 1.0\n    \u03bc0 = 0.0\n    \u03c30 = 1.0\n\n    # Define random measure, e.g. Dirichlet process.\n    rpm = DirichletProcess(\u03b1)\n\n    # Define the base distribution, i.e. expected value of the Dirichlet process.\n    H = Normal(\u03bc0, \u03c30)\n\n    # Latent assignment.\n    z = tzeros(Int, length(x))\n\n    # Locations of the infinitely many clusters.\n    \u03bc = 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!(\u03bc, 0.0)\n\n            # Draw location of new cluster.\n            \u03bc[z[i]] ~ H\n        end\n\n        # Draw observation.\n        x[i] ~ Normal(\u03bc[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    \u03b2 = p[1]\n    #Recover per-capita rate\n    \u03b3 = p[2]\n    \n    #Susceptible Individuals\n    S = u[1]\n    #Infected by Infected Individuals\n    I = u[2]\n   \n    du[1] = -\u03b2 * S * I\n    du[2] = \u03b2 * S * I - \u03b3 * I\n    du[3] = \u03b3 * 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') = \u03c3\u00b2(x\u1d40x' + c)\u1d48\n```\nwith signal standard deviation ``\u03c3``, additive constant ``c``, and degree ``d``.\n\"\"\"\nmutable struct Poly <: Kernel\n    \"Constant\"\n    c::Float64\n    \"Signal variance\"\n    \u03c32::Float64\n    \"Degree of polynomial\"\n    deg::Int\n    \"Priors for kernel parameters\"\n    priors::Array\n\n    \"\"\"\n        Poly(lc::Float64, l\u03c3::Float64, deg::Int)\n\n    Create `Poly` with signal standard deviation `exp(l\u03c3)`, additive constant `exp(lc)`,\n    and degree `deg`.\n    \"\"\"\n    Poly(lc::Float64, l\u03c3::Float64, deg::Int) = new(exp(lc), exp(2 * l\u03c3), 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.\u03c32*(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.\u03c32) / 2]\nget_param_names(poly::Poly) = [:lc, :l\u03c3]\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.\u03c32 = exp(2 * hyp[2])\nend\n\n@inline dk_dlc(poly::Poly, xTy::Float64) = poly.c*poly.deg*poly.\u03c32*(poly.c+xTy).^(poly.deg-1)\n@inline dk_dl\u03c3(poly::Poly, xTy::Float64) = 2 * _cov(poly,xTy)\n@inline function dKij_d\u03b8p(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\u03c3(poly, dotij(X,i,j,dim))\n    end\nend\n@inline function dKij_d\u03b8p(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\u03c3(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": "using SymPy.Physics\nusing SymPy: Sym, sqrt, symbols, doit, PI\nusing SymPy.SpecialFuncs: Ynm\nusing PyCall: PyError\nusing Test\n\n\n@testset \"Physics\" begin\n    @test clebsch_gordan(Sym(3)/2, Sym(1)/2, 2, Sym(3)/2, Sym(1)/2, 2) == 1\n    @test clebsch_gordan(Sym(3)/2, Sym(1)/2, 1, Sym(3)/2, -Sym(1)/2, 1) == sqrt(Sym(3))/2\n    @test clebsch_gordan(Sym(3)/2, Sym(1)/2, 1, -Sym(1)/2, Sym(1)/2, 0) == -sqrt(Sym(2))/2\n\n    \u03b8, \u03d5 = symbols(\"theta, phi\")\n    @test doit(dot_rot_grad_Ynm(3, 2, 2, 0, \u03b8, \u03d5)) == 3*sqrt(Sym(55))*Ynm(5, 2, \u03b8, \u03d5)/(11*sqrt(PI))\n\n    @test gaunt(1,0,1,1,0,-1) == -1/(2*sqrt(PI))\n    #@test N(gaunt(1000,1000,1200,9,3,-12)) \u2248 0.00689500421922113448 # takes forever to compute\n\n    @test_throws PyError gaunt(1.2,0,1.2,0,0,0)\n    @test_throws PyError gaunt(1,0,1,1.1,0,-1.1)\n\n    @test racah(3,3,3,3,3,3) == -1//14\n\n\n    @test wigner_3j(2, 6, 4, 0, 0, 0) == sqrt(Sym(715))/143\n    @test wigner_3j(2, 6, 4, 0, 0, 1) == 0\n\n    @test wigner_6j(3,3,3,3,3,3) == -1//14\n    @test wigner_6j(5,5,5,5,5,5) == 1//52\n\n\n    # Optics\n    @test RayTransferMatrix(1,2,3,4) == Sym[1 2; 3 4]\n    @test FlatMirror() == Sym[1 0; 0 1]\n\n    # Spin\n    @test doit(WignerD(Sym(3), Sym(2), Sym(1), PI, PI/2, -PI)) == -sqrt(Sym(10))/8\n    @test doit(WignerD(Sym(1), Sym(1), Sym(0), 0, \u03b8, 0)) == -sin(\u03b8)/sqrt(Sym(2))\nend\n", "meta": {"hexsha": "ca86d7bb2b453ce64f3bc6c41194d8fe64d954a1", "size": 1307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-physics.jl", "max_stars_repo_name": "baggepinnen/SymPy.jl", "max_stars_repo_head_hexsha": "605551ebd78921ea6bc72b80e9894d023895bc94", "max_stars_repo_licenses": ["MIT"], "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-physics.jl", "max_issues_repo_name": "baggepinnen/SymPy.jl", "max_issues_repo_head_hexsha": "605551ebd78921ea6bc72b80e9894d023895bc94", "max_issues_repo_licenses": ["MIT"], "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-physics.jl", "max_forks_repo_name": "baggepinnen/SymPy.jl", "max_forks_repo_head_hexsha": "605551ebd78921ea6bc72b80e9894d023895bc94", "max_forks_repo_licenses": ["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.675, "max_line_length": 99, "alphanum_fraction": 0.5723029839, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7724971892189677}}
{"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, \u03b5max, metric = Chebyshev(),\u03b5min = 0) \u2192 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 `\u03b5min` 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\u2013106.\n[^Theiler1988]: Theiler, [Lacunarity in a best estimator of fractal dimension. Physics Letters A, 133(4\u20135)](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, \u03b5max, metric = Chebyshev(); \u03b5min=0)\n    n, \u03b7, 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 \u03b5min < d < \u03b5max\n                n += 1\n                \u03b7 += log(d/\u03b5max)\n            end\n        end\n    end\n    # bias-corrected version (log-likelihood function shifted on x-axis)\n    \u03b1 = -(n-1)/\u03b7\n    # biased version (maximum of original log-likelihood function)\n    \u03b1_b = -n/\u03b7\n    # value of maximum of original log-likelihood function\n    mxl = n*log(\u03b1_b) + \u03b1_b * \u03b7\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) + \u03b7 * x - mxl +2 , 0,2*\u03b1)\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 \u03b1-\u03b1_b\n    \u03b195u = \u03b1 - \u03b1_b + mn\n    \u03b195l = \u03b1 - \u03b1_b + mx\n\n    return \u03b1, \u03b195u, \u03b195l\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 ``\u03b8(\\bm{x})`` in Fourier space, where $\\bm{x} = (x, y, z)$.\n# It is assumed that the field is periodic with period $L = 2\u03c0$ along all\n# dimensions.\n#\n# ## General procedure\n#\n# The discrete Fourier expansion of ``\u03b8`` writes\n# ```math\n# \u03b8(\\bm{x}) = \u2211_{\\bm{k} \u2208 \\Z^3} \\hat{\u03b8}(\\bm{k}) \\, e^{i \\bm{k} \u22c5 \\bm{x}},\n# ```\n# where $\\bm{k} = (k_x, k_y, k_z)$ are the Fourier wave numbers and $\\hat{\u03b8}$ is\n# the discrete Fourier transform of $\u03b8$.\n# Then, the spatial derivatives of $\u03b8$ are given by\n# ```math\n# \\frac{\u2202 \u03b8(\\bm{x})}{\u2202 x_i} =\n# \u2211_{\\bm{k} \u2208 \\Z^3} i k_i \\hat{\u03b8}(\\bm{k}) \\, e^{i \\bm{k} \u22c5 \\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{\u2207} \u03b8 = (\u2202_x \u03b8, \u2202_y \u03b8, \u2202_z \u03b8)$, one has to:\n# 1. transform $\u03b8$ to Fourier space to obtain $\\hat{\u03b8}$,\n# 2. multiply $\\hat{\u03b8}$ by $i \\bm{k}$,\n# 3. transform the result back to physical space to obtain $\\bm{\u2207} \u03b8$.\n\n# ## Preparation\n\n# In this section, we initialise a random real-valued scalar field $\u03b8$ 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 \u00d7 Ny \u00d7 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\u03b8 = allocate_input(plan)\nrandn!(\u03b8)\n\n## Perform distributed FFT\n\u03b8_hat = plan * \u03b8\nnothing  # hide\n\n# Finally, we initialise the output that will hold \u2207\u03b8 in Fourier space.\n# Noting that \u2207\u03b8 is a vector field, we choose to store it as a tuple of\n# 3 PencilArrays.\n\n\u2207\u03b8_hat = allocate_output(plan, Val(3))\n\n## This is equivalent:\n## \u2207\u03b8_hat = ntuple(d -> similar(\u03b8_hat), Val(3))\n\nsummary(\u2207\u03b8_hat)\n\n# ## Fourier wave numbers\n\n# In general, the Fourier wave numbers are of the form\n# ``k_i = 0, \u00b1\\frac{2\u03c0}{L_i}, \u00b1\\frac{4\u03c0}{L_i}, \u00b1\\frac{6\u03c0}{L_i}, \u2026``,\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\u03c0}{L_x}, \\frac{4\u03c0}{L_x}, \u2026``.\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\u03c0, 2\u03c0, 2\u03c0)  # Lx, Ly, Lz\nsample_rate = 2\u03c0 .* dims ./ box_size\n\n## In our case (Lx = 2\u03c0 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\u03c0 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\u03b8_glob = global_view(\u03b8_hat)\n\u2207\u03b8_glob = global_view.(\u2207\u03b8_hat)\nsummary(\u03b8_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(\u03b8_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 \u2207\u03b8_glob also modifies the original PencilArray \u2207\u03b8_hat.\n    \u2207\u03b8_glob[1][I] = im * kx * \u03b8_glob[I]\n    \u2207\u03b8_glob[2][I] = im * ky * \u03b8_glob[I]\n    \u2207\u03b8_glob[3][I] = im * kz * \u03b8_glob[I]\nend\n\n# The above loop can be written in a slightly more efficient manner by precomputing\n# `im * \u03b8_glob[I]`:\n\n@inbounds for I in CartesianIndices(\u03b8_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 * \u03b8_glob[I]\n\n    \u2207\u03b8_glob[1][I] = kx * u\n    \u2207\u03b8_glob[2][I] = ky * u\n    \u2207\u03b8_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{\u2207} \u03b8$ in physical\n# space:\n\n\u2207\u03b8 = plan \\ \u2207\u03b8_hat;\n\n# Note that the transform is automatically broadcast over the three fields\n# of the `\u2207\u03b8_hat` vector, and the result `\u2207\u03b8` 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(\u03b8_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(\u03b8_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 * \u03b8_glob[i, j, k]\n\n    \u2207\u03b8_glob[1][i, j, k] = kx * u\n    \u2207\u03b8_glob[2][i, j, k] = ky * u\n    \u2207\u03b8_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(\u03b8_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\u20d7  # hide\n    k\u20d7 = grid_fourier[I]\n    u = im * \u03b8_hat[I]\n    \u2207\u03b8_hat[1][I] = k\u20d7[1] * u\n    \u2207\u03b8_hat[2][I] = k\u20d7[2] * u\n    \u2207\u03b8_hat[3][I] = k\u20d7[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@. \u2207\u03b8_hat[1] = im * grid_fourier[1] * \u03b8_hat\n@. \u2207\u03b8_hat[2] = im * grid_fourier[2] * \u03b8_hat\n@. \u2207\u03b8_hat[3] = im * grid_fourier[3] * \u03b8_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 \u00d7 32 \u00d7 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 \u03bcs\n#         gradient_global_view! (lazy)...           92.060 \u03bcs  [Method 1]\n#         gradient_global_view_explicit!...         88.958 \u03bcs\n#         gradient_global_view_explicit! (lazy)...  81.055 \u03bcs  [Method 2]\n#         gradient_local!...                        92.305 \u03bcs\n#         gradient_grid!...                         92.770 \u03bcs\n#         gradient_grid! (lazy)...                  101.388 \u03bcs  [Method 3]\n#         gradient_grid_broadcast!...               88.606 \u03bcs\n#         gradient_grid_broadcast! (lazy)...        151.020 \u03bcs  [Method 4]\n#         gradient_local_parent!...                 92.248 \u03bcs\n#         gradient_local_linear!...                 91.212 \u03bcs\n#         gradient_local_linear_explicit!...        90.992 \u03bcs\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": "# ## \u30ed\u30b8\u30b9\u30c6\u30a3\u30c3\u30af\u56de\u5e30\n# ### \u4f8b29\n# \u30b7\u30b0\u30e2\u30a4\u30c9\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u3066\u304a\u304d\u307e\u3059\u3002\n# ```julia\n# sigmoid(x::Matrix, \u03b2::Vector) = 1 / (1 + exp(-x*\u03b2))\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=\"\u30ed\u30b8\u30b9\u30c6\u30a3\u30c3\u30af\u66f2\u7dda\")\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# ## \u30cb\u30e5\u30fc\u30c8\u30f3\u30fb\u30e9\u30d5\u30bd\u30f3\u6cd5\n# ### \u4f8b31\n# $x^2-1=0$\u30924\u3092\u521d\u671f\u5024\u3068\u3057\u3066\u6570\u5024\u8a08\u7b97\u3067\u89e3\u304f\u554f\u984c\u300210\u56de\u3067\u3069\u306e\u7a0b\u5ea6\u8fd1\u3065\u304f\u304b\u3002\n# \u305b\u3063\u304b\u304f\u306a\u306e\u3067\u3001 \u5fae\u5206\u3092\u3042\u3089\u308f\u306b\u66f8\u304d\u4e0b\u3059\u306e\u3067\u306f\u306a\u304f\u3066\u3001\u81ea\u52d5\u5fae\u5206\u30d1\u30c3\u30b1\u30fc\u30b8\u3092\u4f7f\u3063\u3066\u307f\u308b\u3053\u3068\u306b\u3057\u307e\u3059\u3002\n# \u898b\u305f\u76ee\u304c$x \\leftarrow x - \\dfrac{f(x)}{f'(x)}$\u3068\u3044\u3046\u516c\u5f0f\u306e\u307e\u3093\u307e\u3067\u3059\u306d\u3002\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# ### \u4f8b31\n# 2\u5909\u6570\u95a2\u6570\u304c2\u3064\u3042\u308b\u5834\u5408\u3002 Zygote.jl\u306bjacobian\u304c\u306a\u304b\u3063\u305f\u306e\u3067\u3001ForwardDiff.jl\u3092\u4f7f\u3063\u3066\u307f\u307e\u3059\u3002\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# ### \u4f8b33\n# \u6700\u5c24\u63a8\u5b9a\u306b\u3088\u308a\u30ed\u30b8\u30b9\u30c6\u30a3\u30c3\u30af\u56de\u5e30\u3092\u884c\u3046\u554f\u984c\u3002\n# $\\nabla l(\\beta_0, \\beta) = 0$\u3092\u6c42\u3081\u308b\u554f\u984c\u3092\u89e3\u3044\u3066\u307f\u308b\u3002\nusing Joe, Random, LinearAlgebra\nusing Plots\nN=1000; p=2; Random.seed!(1)\nX = insert_ones(randn(N,p))\n\u03b2 = randn(p+1)\nprob = @. 1/(1 + exp($*(X,\u03b2)))\nthreshold=0.5\ny = ifelse.(rand(N) .> prob,1,-1) # \u3053\u3053\u307e\u3067\u30c7\u30fc\u30bf\u751f\u6210\n@show y \u03b2;\n# \u305b\u3063\u304b\u304f\u306a\u306e\u3067\u30c7\u30fc\u30bf\u3092\u53ef\u8996\u5316\u3057\u3066\u307f\u307e\u3059\u3002\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-> -\u03b2[1]/\u03b2[3] - \u03b2[2]/\u03b2[3]*x, label=\"\u03b2\")\nsavefig(p33,joinpath(@OUTPUT,\"fig2-2.svg\")) # hide\n# \\fig{fig2-2}\n\u03b3 = randn(2+1) #\u521d\u671f\u5024\n\u03b32 = copy(\u03b3) #\u5225\u89e3\u7528\u306b\u30b3\u30d4\u30fc\n@show \u03b3\nW(v::Vector) = @.(v/(1+ v)^2) |> diagm\nt = true\nfor i in 1:10\n    global \u03b3\n    s=X*\u03b3\n    v = @. exp(-y*s)\n    u = @. y*v/(1+v)\n    \u03b3 += ((X'*W(v)*X) \\ X') * u\n    #\u03b4'*\u03b4 < 0.001 && (t = false)\n    @show \u03b3\nend \nplot!(x-> -\u03b3[1]/\u03b3[3] - \u03b3[2]/\u03b3[3]*x, label=\"\u03b3\")\n# \u4eca\u5ea6\u306f\u6a2a\u7740\u3092\u3057\u3066\u3001\u30d8\u30b7\u30a2\u30f3\u3092\u4f7f\u3063\u3066\u8a08\u7b97\u3057\u3066\u307f\u307e\u3059\u3002\nusing Zygote, LinearAlgebra\nl(\u03b3,X=X,y=y) = sum(@. log( 1 /(1+exp(*($*(X,\u03b3),-y))))) #\u5bfe\u6570\u5c24\u5ea6\u95a2\u6570\n\nfor i in 1:10\n    global \u03b32\n    \u03b4 =  Zygote.hessian(l,\u03b32) \\ l'(\u03b32)\n    \u03b32 -= \u03b4\n    @show \u03b32\nend\n\nplot!(p33,x-> -\u03b32[1]/\u03b32[3] - \u03b32[2]/\u03b32[3]*x, label=\"\u03b32\")\nsavefig(p33,joinpath(@OUTPUT,\"fig2-2-2.svg\")) # hide\n# \\fig{fig2-2-2}\n# \\lineskip\n# \u3060\u3044\u305f\u3044\u540c\u3058\u3088\u3046\u306a\u5883\u754c\u7dda\u304c\u5f97\u3089\u308c\u308b\u3053\u3068\u304c\u5206\u304b\u308a\u307e\u3057\u305f\u3002\n# ### \u4f8b34\n# \u30c7\u30fc\u30bf\u306e\u534a\u5206\u3092\u4f7f\u3063\u3066\u30ed\u30b8\u30b9\u30c6\u30a3\u30c3\u30af\u56de\u5e30\u3067\u5b66\u7fd2\u3057\u3001\u6b8b\u308a\u306e\u30c7\u30fc\u30bf\u3067\u691c\u8a3c\u3059\u308b\u7df4\u7fd2\u3002\n# \u307e\u305a\u30c7\u30fc\u30bf\u3092\u751f\u6210\u3057\u307e\u3059\u3002 \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# \u8a13\u7df4\u30c7\u30fc\u30bf\u3068\u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u3092\u5206\u3051\u3066\u53ef\u8996\u5316\u3057\u307e\u3059\u3002\nindex = sample(1:2n,2n,replace=false); #\u30e9\u30f3\u30c0\u30e0\u306a\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u4f5c\u308a\ntrain = index[begin:n];# \u5b66\u7fd2\u7528\u3068\u30c6\u30b9\u30c8\u7528\u306b\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u5206\u3051\u308b\u3002\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    # **\u8a13\u7df4\u30c7\u30fc\u30bf\u3068\u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u3092\u5206\u3051\u308b\u65b9\u6cd5**\n    # \n    # \u539f\u8457\u306epython\u30b3\u30fc\u30c9\u3067\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u3063\u3066\u3044\u307e\u3059\u3002\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\u3092\u4f7f\u3063\u305f\u66f8\u304d\u65b9\u306f\u4fbf\u5229\u3067\u3059\u304c\u3001julia\u3067\u306f\u91cd\u8907\u3092\u8a31\u3055\u305a\u306b\u30e9\u30f3\u30c0\u30e0\u306b\u4e26\u3079\u305f\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u4e8c\u3064\u306b\u5206\u3051\u308b\n    # \u65b9\u6cd5\u3092\u4f7f\u3044\u307e\u3057\u305f\u3002\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    # \u3067\u3082\u3088\u304f\u8003\u3048\u308b\u3068setdiff\u3092\u4f7f\u3048\u3070\u5341\u5206\u3067\u3057\u305f\u3002\n    # ```julia\n    # train = sample(1:2n,n,replace=false); test = setdiff(1:2n,train)\n    # ```\n# }\n# \u30eb\u30fc\u30d7\u306f\u539f\u8457\u306e\u65b9\u6cd5\u306b\u5f93\u3044\u307e\u3057\u305f\u3002\n\u03b2 = [0,0] #\u521d\u671f\u5024\n\u03b3 = randn(2)\nwhile sum(\u03b2-\u03b3)^2 > 0.001\n    global \u03b2, \u03b3\n    local W\n    \u03b2 = \u03b3\n    s = X_train*\u03b2\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    \u03b3 = (X_train'*W*X_train)\\(X_train'*W*z)\n    @show \u03b3;\nend\n# \u6b21\u306b\u3053\u306e\u03b3\u3092\u4f7f\u3063\u3066\u3001\u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u3092\u4e88\u6e2c\u3057\u3066\u307f\u307e\u3059\u3002 \u6b63\u8aa4\u3092\u30ab\u30a6\u30f3\u30c8\u3059\u308b\u95a2\u6570\u3092\u6b21\u306e\u3088\u3046\u306b\u5b9a\u7fa9\u3057\u307e\u3059\u3002\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*\u03b3 .|> 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\u6b63\u7b54\u7387 = sum(diag(table)) / sum(table)\n# ## 2.3 \u7dda\u5f62\u5224\u5225\u3068\u4e8c\u6b21\u5224\u5225\n# ### \u4f8b35\n# \u307e\u305a\u306f\u4e0e\u3048\u3089\u308c\u305f\u5e73\u5747\u3068\u5206\u6563\u5171\u5206\u6563\u884c\u5217\u304b\u3089\u4e8c\u6b21\u5143\u6b63\u898f\u5206\u5e03\u306e\u30c7\u30fc\u30bf\u30922\u7a2e\u985e\u751f\u6210\u3057\u307e\u3059\u3002\nusing Distributions, Random,Plots, LinearAlgebra, Parameters\n\u03bc\u2081=[2,2];  \u03a3\u2081 = [2 0; 0 2]\n\u03bc\u2082=[-3,-3]; \u03a3\u2082 = [1 -0.8; -0.8 1]\n\nN = 100;Random.seed!(123)\ndata1 = rand(MvNormal(\u03bc\u2081,\u03a3\u2081),100) |> transpose\ndata2 = rand(MvNormal(\u03bc\u2082,\u03a3\u2082),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# \u3053\u3053\u307e\u3067\u30c7\u30fc\u30bf\u306e\u751f\u6210\u3002\n# \u751f\u6210\u3057\u305f\u30c7\u30fc\u30bf\u304b\u3089\u5e73\u5747\u3068\u5206\u6563\u5171\u5206\u6563\u884c\u5217\u3092\u8a08\u7b97\u3059\u308b\u3002\n\u03bc\u0302\u2081 = mean(data1,dims=1)'; \u03a3\u0302\u2081 = cov(data1,dims=1);\n\u03bc\u0302\u2082 = mean(data2,dims=1)' ; \u03a3\u0302\u2082 = cov(data2,dims=1);\n# \\warning{mean\u95a2\u6570\u3067\u884c\u5217\u306e\u5217\u65b9\u5411\u306e\u5e73\u5747\u3092\u3068\u308b\u6642\u3001\u5f97\u3089\u308c\u308b\u30c7\u30fc\u30bf\u306f\u4e8c\u6b21\u5143\u306e\u6a2a\u30d9\u30af\u30c8\u30eb\u306b\u306a\u3063\u3066\u3044\u308b\u3002\n# \u7e26\u30d9\u30af\u30c8\u30eb\u3068\u3057\u3066\u6271\u3044\u305f\u3044\u306e\u3067\u3001\u8ee2\u7f6e(\u6b63\u78ba\u306b\u306f\u8907\u7d20\u5171\u5f79\uff09\u3092\u3057\u3066\u3044\u308b\u3002}\n# \u305d\u308c\u305e\u308c\u306e\u5206\u5e03\u306e\u60c5\u5831\u3092\u8907\u5408\u578b\u306b\u307e\u3068\u3081\u3066\u304a\u304d\u307e\u3059\u3002\n# ```julia\n# @with_kw struct QDA \n#     \u03bc::Array # \u5e73\u5747\n#     \u03a3::Matrix # \u5206\u6563\u5171\u5206\u6563\u884c\u5217\n#     inv\u03a3::Array = inv(\u03a3) # \u5206\u6563\u5171\u5206\u6563\u884c\u5217\u306e\u9006\u884c\u5217\n#     det\u03a3 = det(\u03a3) # \u5206\u6563\u5171\u5206\u6563\u884c\u5217\u306e\u884c\u5217\u5f0f\n# end\n# ```\n# \\note{\u3057\u308c\u3063\u3068\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u521d\u671f\u5316\u3057\u305f\u8907\u5408\u578b\u3092\u4f7f\u3063\u3066\u3044\u307e\u3059\u304c\u3001\u3053\u3053\u3067\u306fParameters.jl\u3068\u3044\n# \u3046\u30b5\u30fc\u30c9\u30d1\u30fc\u30c6\u30a3\u30e9\u30a4\u30d6\u30e9\u30ea\u3092\u4f7f\u3063\u3066\u3044\u307e\u3059\u3002}\n# \u307e\u305f\u3001\u591a\u5909\u91cf\u6b63\u898f\u5206\u5e03\u306e\u5bfe\u6570\u5c24\u5ea6\u3092\u53d6\u5f97\u3059\u308b\u95a2\u6570\u3092\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u5b9a\u7fa9\u3057\u307e\u3059\u3002\n# \u3053\u3053\u3067\u306f\u3001julia\u306efunction-like object\u306e\u6a5f\u80fd\u3092\u5229\u7528\u3057\u3066\u3044\u307e\u3059\u3002\n# \u307e\u305f\u3001\u53ef\u5909\u9577\u5f15\u6570(x...)\u3092\u5229\u7528\u3057\u3066\u3001\u30c7\u30fc\u30bf\u304c3\u6b21\u5143\u4ee5\u4e0a\u306e\u5834\u5408\u306b\u3082\u62e1\u5f35\u3057\u3066\u3044\u307e\u3059\u3002\n# \u30ad\u30fc\u30ef\u30fc\u30c9\u4ed8\u304d\u5f15\u6570\u306b\u4e8b\u524d\u78ba\u7387\u3092\u52a0\u3048\u3066\u3044\u307e\u3059\u3002\n# \\note{function-like object\u306e\u6a5f\u80fd\u3092\u4f7f\u3046\u3068\u3001\u8907\u5408\u578b\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u95a2\u6570\u306e\u3088\u3046\u306b\n# \u4f7f\u3046\u3053\u3068\u304c\u3067\u304d\u3001\u518d\u5229\u7528\u3057\u3084\u3059\u304f\u306a\u308a\u307e\u3059\u3002}\n# ```julia\n# function (qda::QDA)(x...,prior=1.0)\n#     data = collect(x)\n#     @unpack \u03bc,inv\u03a3,det\u03a3 = qda\n#     a = -0.5*(data-\u03bc)' * inv\u03a3 * (data-\u03bc) \n#     a[1] - log(det\u03a3) - log(prior)\n# end\n# ```\nusing Joe: QDA\nparam1=QDA(\u03bc= \u03bc\u0302\u2081,\u03a3 = \u03a3\u0302\u2081);param2=QDA(\u03bc = \u03bc\u0302\u2082,\u03a3 = \u03a3\u0302\u2082)\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# \u7dda\u5f62\u5224\u5225\u3092\u884c\u3046\u5834\u5408\u306f\u3001\u5206\u6563\u5171\u5206\u6563\u884c\u5217\u304c\u7b49\u3057\u3044\u3053\u3068\u3092\u4eee\u5b9a\u3057\u307e\u3059\u3002\n# data1\u3068data2\u3092\u3001\u305d\u308c\u305e\u308c\u4e2d\u5fc3\u5316\u5f8c\u306b\u7d71\u5408\u3057\u305f\u30c7\u30fc\u30bf\u30bb\u30c3\u30c8\u306b\u3064\u3044\u3066\u3001\n# \u65b0\u305f\u306a\u5206\u6563\u5171\u5206\u6563\u884c\u5217\u3092\u6c42\u3081\u308b\u3053\u3068\u306b\u3057\u307e\u3059\u3002 \n\u03a3_L =  vcat(data1 .- \u03bc\u0302\u2081' , data2 .- \u03bc\u0302\u2082') |> cov\nparam1_L=QDA(\u03bc= \u03bc\u0302\u2081,\u03a3 =\u03a3_L );param2_L=QDA(\u03bc = \u03bc\u0302\u2082,\u03a3 = \u03a3_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# ### \u4f8b36 (Fisher\u306e\u3042\u3084\u3081)\n# \u307e\u305aRDatasets\u304b\u3089iris\u306e\u30c7\u30fc\u30bf\u30bb\u30c3\u30c8\u3092\u8aad\u307f\u8fbc\u307f\u307e\u3059\u3002\nusing ScikitLearn, StatsBase, Random\nusing Joe:QDA\n@sk_import datasets: load_iris\niris = load_iris()\nx = iris[\"data\"]\ny = iris[\"target\"]\n# \u8a13\u7df4\u30c7\u30fc\u30bf\u3068\u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u3092\u5206\u3051\u307e\u3059\u3002\nRandom.seed!(123)\nn = length(y)\nindex = sample(1:n,n,replace=false); #\u30e9\u30f3\u30c0\u30e0\u306a\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u4f5c\u308a\ntrain = index[begin:Int(n/2)];# \u5b66\u7fd2\u7528\u3068\u30c6\u30b9\u30c8\u7528\u306b\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u5206\u3051\u308b\u3002\ntest = index[Int(n/2)+1:end];\nX_train= x[train,:]; X_test = x[test,:];\ny_train = y[train]; y_test = y[test];\n# \u305d\u308c\u305e\u308c\u306e\u3042\u3084\u3081\u306e\u8a13\u7df4\u30c7\u30fc\u30bf\u306e\u5e73\u5747\u3068\u5206\u6563\u5171\u5206\u6563\u884c\u5217\u3092\u6c42\u3081\u3066\u4fdd\u5b58\u3059\u308b\u3002\nParams = QDA[]\nfor i in 1:3\n    \u03bc,\u03a3 =  mean_and_cov(X_train[y_train .==i,:])\n    push!(Params, QDA(\u03bc=\u03bc', \u03a3=\u03a3)) #\u03bc\u306f\u884c\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u3053\u3068\u306b\u6ce8\u610f\nend\n\n# \u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u3067\u691c\u8a3c\u3059\u308b\u3002\u5bfe\u6570\u5c24\u5ea6\u3092\u6700\u5927\u5316\u3059\u308b\u30e9\u30d9\u30eb\u3092\u9078\u629e\u3057\u307e\u3059\u3002\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# ### \u554f29 \u4e8b\u524d\u78ba\u7387\u304c\u5206\u304b\u3063\u3066\u3044\u308b\u5834\u5408\n# \u3042\u3084\u3081\u306e\u4e8b\u524d\u78ba\u7387\u304c[0.5,0.25,0.25]\u3060\u3063\u305f\u3068\u304d\u306f\u3001\u5bfe\u6570\u3092\u3068\u3063\u3066\u8db3\u305b\u3070\u826f\u3044\u3067\u3057\u3087\u3046\u3002\n# \u30ad\u30fc\u30ef\u30fc\u30c9\u4ed8\u304d\u5f15\u6570\u3067\u4e8b\u524d\u78ba\u7387\u3092\u6307\u5b9a\u3067\u304d\u308b\u3088\u3046\u306b\u3057\u305f\u306e\u3067\u3001\n# \u5c11\u3057\u66f8\u304d\u63db\u3048\u308b\u3060\u3051\u3067\u5bfe\u5fdc\u53ef\u80fd\u3067\u3059\u3002\u4eca\u56de\u306e\u5834\u5408\u3001\u4e88\u6e2c\u7d50\u679c\u306b\u5bfe\u3057\u3066\u5f71\u97ff\u306f\u5c11\u306a\u3044\u3088\u3046\u3067\u3059\u3002\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\u8fd1\u508d\u6cd5\n# \u307e\u305a\u3001K\u8fd1\u508d\u6cd5\u306b\u3088\u308b\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u307e\u3059\u3002\u539f\u8457\u306e\u8a18\u6cd5\u3092\u307b\u307c\u8e0f\u8972\u3057\u3066\u3044\u307e\u3059\u3002\n# \u30bf\u30a4\u30d6\u30ec\u30fc\u30ad\u30f3\u30b0\u304c\u5c11\u3057\u91cd\u8907\u3057\u305f\u66f8\u304d\u65b9\u306b\u306a\u3063\u3066\u3044\u308b\u306e\u304c\u6b8b\u5ff5\u3002\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 #\u30bf\u30a4\u30d6\u30ec\u30fc\u30ad\u30f3\u30b0\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# \u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\u304c\u8907\u6570\u306e\u5834\u5408\u306f\u591a\u91cd\u30c7\u30a3\u30b9\u30d1\u30c3\u30c1\u3067\u5bfe\u5fdc\u3057\u307e\u3059\u3002 \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# ### \u4f8b37 Fisher\u306e\u3042\u3084\u3081 returns\n# \u4f8b36\u3068\u540c\u3058\u30c7\u30fc\u30bf\u3092\u4f7f\u3063\u3066K\u8fd1\u508d\u6cd5\u3067\u3084\u3063\u3066\u307f\u307e\u3059\u3002\nusing Joe:knn,table_count\ny_pred_knn = knn(X_train,y_train,X_test,3)\ntable_count(y_test,y_pred_knn)\n# \u3053\u306e\u4e71\u6570\u306e\u7a2e\u306e\u5834\u5408\u3060\u3068\u3001\u4e8c\u6b21\u5224\u5225\u3068\u305d\u308c\u307b\u3069\u7cbe\u5ea6\u306f\u5909\u308f\u308a\u307e\u305b\u3093\u3002\n# ## ROC\u66f2\u7dda\n# ### \u4f8b38 \n# x, y \u3068\u3044\u3046\u8868\u8a18\u306fpositive, negative\u306b\n# \u6dfb\u3048\u5b57\u3092\u967d\u6027\u3092p(positive), \u9670\u6027\u3092n(negative)\u306b\u5909\u3048\u3066\u3044\u307e\u3059\u3002\n# \u307e\u305f\u3001var\u306f\u03c3\u306b\u5909\u66f4\u3057\u3066\u3044\u307e\u3059\u3002\nusing Distributions, Plots\n\u03bc\u209a = 1; \u03bc\u2099 = -1 \n\u03c3\u209a=1; \u03c3\u2099 =1\nN\u209a = 1000; N\u2099 = 10000\npositive = rand(Normal(\u03bc\u209a,\u03c3\u209a),N\u209a)\nnegative = rand(Normal(\u03bc\u2099,\u03c3\u2099),N\u2099)\n\u03b8 = exp.(-10:0.1:100);\nU = Vector{Float64}(undef,length(\u03b8))\nV = Vector{Float64}(undef,length(\u03b8))\nfor i in 1:length(\u03b8)\n    global U,V # hide\n    U[i] = sum(@. pdf(Normal(\u03bc\u209a,\u03c3\u209a),negative) / pdf(Normal(\u03bc\u2099,\u03c3\u2099),negative) > \u03b8[i]) / N\u2099\n    V[i] = sum(@. pdf(Normal(\u03bc\u209a,\u03c3\u209a),positive) / pdf(Normal(\u03bc\u2099,\u03c3\u2099),positive) > \u03b8[i]) / N\u209a\nend\n\nAUC = 0\nfor i in 1:length(\u03b8)-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": "using Test, Astro\n\nprint(\"12.a Sidereal time (mean)\")\n# Meeus page 88\n# Find mean and apparent sidereal  time at Greenwich on 1987 April 10 at 0 UT:\n# Mean sidereal time should be 13h10m46.3668s\n# Nutation in right ascension should be -0.2317 degrees\n# Apparent sidereal time is 13h10m46.1351s\njd = cal_to_jd(1987, 4, 10) + hms_to_fday(0,0,0)\ntheta0 = mean_sidereal_time_greenwich(jd)\n# theta0 is mean sidereal time in radians (2pi radians = 24 hrs)\n\ntheta0_st = fday_to_hms(theta0 / (pi * 2)) # is a tuple!\ntheta_fday = hms_to_fday(theta0_st...)     # so splat required... :)\n# mean sidereal time\n@test isapprox(theta0 / (pi * 2), theta_fday, atol=0.1)\n@test(theta0_st[1] == 13)\n@test(theta0_st[2] == 10)\n@test isapprox(theta0_st[3], 46.3668, atol=0.1)\nprintln(\" passed\")\n\nprint(\"12.a Sidereal time (apparent)\")\njd = cal_to_jd(1987, 4, 10) + hms_to_fday(0,0,0)\ntheta0 = apparent_sidereal_time_greenwich(jd)\n# apparent sidereal time\nast_hms = fday_to_hms(theta0/(2 * pi))\n@test(ast_hms[1] == 13)\n@test(ast_hms[2] == 10)\n@test isapprox(ast_hms[3], 46.1351, atol=0.1)\nprintln(\" passed\")\n\nprint(\"12.b Sidereal time (mean)\")\n# find the mean sidereal time at Greenwich on 1987 April 10 at 19h21m00s\n# jd = cal_to_jd(1987, 4, 10) + hms_to_fday(19,21,0)\nmsd_midnight = mean_sidereal_time_greenwich(cal_to_jd(1987, 4, 10))\nprintln(msd_midnight)\n\n@test isapprox(theta0 / (pi * 2), 128.7378734 / 360, atol=0.2)\nprintln(\" passed\")\n\nprintln(\" Mean and apparent sidereal time\")\nmst_g = fday_to_hms(mean_sidereal_time_greenwich(cal_to_jd(1987, 4, 10)) / (2 * pi))\n@test(mst_g[1] == 13)\n@test(mst_g[2] == 10)\n@test isapprox(mst_g[3] , 46.3668, atol=0.01)\n\nast_g = fday_to_hms(apparent_sidereal_time_greenwich(cal_to_jd(1987, 4, 10)) / (2 * pi))\n@test(ast_g[1] == 13)\n@test(ast_g[2] == 10)\n@test ast_g[3] \u2248  46.1351 atol= 0.3#  good enough?\n\n# mean sidereal time and gmt/ut should be the same around September 21/22\nmst = fday_to_hms(mod2pi(mean_sidereal_time_greenwich(cal_to_jd(2014,9,21)))/(2 * pi))\n@test(mst[1] == 23)\n@test(mst[2] == 59)\nprintln(\" passed\")\n\n# Meeus Example 12.a\n# mean_sidereal_time_greenwich(Dates.datetime2julian(DateTime(1987, 4, 10, 0, 0, 0))) |> radianstime_to_fday |> fday_to_hms\n# (13,10,46.366821793410054)\n\n#=\n\nfunction gmst(dt::DateTime)\n    jd = Dates.datetime2julian(dt)\n    theta0 = mean_sidereal_time_greenwich(jd) # theta0 is mean sidereal time in radians (2pi radians = 24 hrs)\n    theta0_st = fday_to_hms(theta0 / (pi * 2)) # is a tuple!\nend\n\n# from https://www.cv.nrao.edu/~rfisher/Ephemerides/times.html\n\nfunction gmst1(dt::DateTime)\n    jd  = Dates.datetime2julian(dt)\n    d =   jd - 2451545.0\n    T =  d/36525\n    gmst = 24110.54841 + 8640184.812866T + 0.093104(T^2) - 0.0000062(T^3)\n    # difference from UT1\n    gmst += (Dates.hour(dt) * 60 * 60) + (Dates.minute(dt) * 60) + Dates.second(dt)\n    return fday_to_hms((gmst % 86400) / 86400)\nend\n\n=#\n", "meta": {"hexsha": "17416db18027f9f2f8e9c7f55f0b32c053494ee4", "size": 2876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sidereal-tests.jl", "max_stars_repo_name": "cormullion/Astro.jl", "max_stars_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-05T19:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T21:37:33.000Z", "max_issues_repo_path": "test/sidereal-tests.jl", "max_issues_repo_name": "cormullion/Astro.jl", "max_issues_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-02-03T15:20:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-07T19:52:09.000Z", "max_forks_repo_path": "test/sidereal-tests.jl", "max_forks_repo_name": "cormullion/Astro.jl", "max_forks_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-10T17:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:09:32.000Z", "avg_line_length": 34.6506024096, "max_line_length": 123, "alphanum_fraction": 0.6995827538, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7724755077208317}}
{"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": "module TestStats\n\nusing Test: @test, @test, @testset\nusing Ensemble\nusing Ensemble.Stats: logsumexp\n\nfunction testlogsumexp_random()\n    for i in 1:100\n        x = randn()\n        y = randn()\n\n        @test isapprox(logsumexp(x,y), log(exp(x)+exp(y)))\n    end\nend\n\nfunction testlogsumexp_inf()\n    @test logsumexp(-Inf, 0.0)==0.0\n    @test logsumexp(0.0, -Inf)==0.0\n    @test logsumexp(-Inf,-Inf)==-Inf\nend\n\nfunction testall()\n    testlogsumexp_random()\n    testlogsumexp_inf()\nend\n\nend\n", "meta": {"hexsha": "50b187e3ecbfd9240d828bc573824825d228358f", "size": 487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TestStats.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Ensemble.jl-5eb8da3a-fee4-5650-9757-078c5de4c78d", "max_stars_repo_head_hexsha": "3d77ebe3175a96671717a3812399c577b3a068b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-06-25T11:32:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T23:44:43.000Z", "max_issues_repo_path": "test/TestStats.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Ensemble.jl-5eb8da3a-fee4-5650-9757-078c5de4c78d", "max_issues_repo_head_hexsha": "3d77ebe3175a96671717a3812399c577b3a068b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-04T15:59:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T19:54:39.000Z", "max_forks_repo_path": "test/TestStats.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Ensemble.jl-5eb8da3a-fee4-5650-9757-078c5de4c78d", "max_forks_repo_head_hexsha": "3d77ebe3175a96671717a3812399c577b3a068b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-05-02T20:31:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T19:05:25.000Z", "avg_line_length": 17.3928571429, "max_line_length": 58, "alphanum_fraction": 0.6509240246, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7724755031898541}}
{"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 \u3067\u306f\u30a6\u30a7\u30eb\u30c1\u306e\u65b9\u6cd5\u306b\u3088\u308b\u4e00\u5143\u5143\u914d\u7f6e\u5206\u6563\u5206\u6790\u304c\u30c7\u30d5\u30a9\u30eb\u30c8\u306a\u306e\u3067\u3042\u308b\u304c\uff0cJulia \u306b\u306f\u306a\u3044\u306e\u3067\u4ee5\u4e0b\u306e\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u3066\u304a\u304f\u3002\n\n\u95a2\u6570\u5b9a\u7fa9\nUnequalVarianceOneWayANOVATestOneWayANOVATest(groups::AbstractVector{<:Real}...)\n\nOneWayANOVATest(groups::AbstractVector{<:Real}...) \u306e\u5834\u5408\u3068\u540c\u3058\u304f\uff0c\u5f15\u6570\u3068\u3057\u3066\u5404\u6a19\u672c\u306e\u89b3\u6e2c\u30c7\u30fc\u30bf\u30d9\u30af\u30c8\u30eb\u3092\u5217\u6319\u3059\u308b\u3002\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\u4f7f\u7528\u4f8b\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# Check type of max-plus and type promotions\n# ==============================================================================\n\na = MP(1.0)\n@test typeof(a) == MP{Float64}\n\nb = MP(1)\n@test typeof(b) == MP{Int64}\n\nc = MP{Float64}(1)\n@test typeof(c) == MP{Float64}\n\nA = [1 2; 3 4]\n@test typeof(A) == Array{Int64,2}\n@test typeof(MP(A)) == ArrMP{Int64,2}\n\nB = [MP(1) MP(2); MP(3) MP(4)]\n@test typeof(B) == ArrMP{Int64,2}\n\nC = [MP(1) 2; 3 4]\n@test typeof(C) == ArrMP{Int64,2}\n@test typeof(array(C)) == Array{Int64,2}\n\nD = [MP(1.0) 2; 3 4]\n@test typeof(D) == ArrMP{Float64,2}\n@test typeof(array(D)) == Array{Float64,2}\n\nE = [MP(1) 2.0; 3 4]\n@test typeof(E) == ArrMP{Int64,2}\n@test typeof(array(E)) == Array{Int64,2}\n\nF = [2 MP(1.0); 3 4]\n@test typeof(F) == ArrMP{Float64,2}\n@test typeof(array(F)) == Array{Float64,2}\n\n@test typeof(array(MP(A))) == typeof(A)\n@test typeof(MP(array(B))) == typeof(B)\n\n# ==============================================================================\n# Max-plus constructor\n# ==============================================================================\n\nc = MP(1.0)\n@test typeof(MP(c)) == MP{Float64}\nd = MP(c)\n@test typeof(d) == MP{Float64}\n\n# ==============================================================================\n# Max-plus comparaisons\n# ==============================================================================\n\n# Max-plus scalars\nb = MP(3.0)\n@test (b == b) == true\n@test (b != b) == (b \u2260 b) == false\n@test (b >= b) == (b \u2265 b) == true\n@test (b <= b) == (b \u2264 b) == true\n@test (b > b) == false\n@test (b < b) == false\n\n# Max-plus vs. real comparaison\n@test (b == 3.0) == true\n@test (b == 4.0) == false\n@test (b != 4.0) == true\n@test (b < 4.0) == true\n@test (b <= 4.0) == true\n@test (b > 4.0) == false\n@test (b >= 4.0) == false\n@test (4.0 > b) == true\n@test (4.0 >= b) == true\n\n# Matrix comparaison\nB = [MP(1) MP(2); MP(3) MP(4)]\n@test (B == B) == true\n@test (B != B) == (B \u2260 B) == false\n@test (B .>= B) == (B .\u2265 B) == [true true; true true]\n@test (B .<= B) == (B .\u2264 B) == [true true; true true]\n@test (B .> B) == [false false; false false]\n@test (B .< B) == [false false; false false]\n\n# ==============================================================================\n# Max-Plus zero\n# ==============================================================================\n\n@test zero(MP{Float64}) == MP(-Inf) == -Inf\n@test mp0 == zero(MP{Float64})\n@test zero(MP{Int64}) == -9223372036854775808\n@test zero(MP{Bool}) == false\n@test zero(MP(42.0)) == mp0\n@test iszero(mp0) == true\n@test isone(mp1) == true\n@test iszero(mp1) == false\n@test isone(mp0) == false\n\n# ==============================================================================\n# Max-Plus one\n# ==============================================================================\n\n@test one(MP{Float64}) == MP(0.0) == 0.0\n@test mp1 == one(MP{Float64})\n@test one(MP{Int64}) == 0\n@test one(MP{Bool}) == false\n@test one(MP(42.0)) == mp1\n\n# ==============================================================================\n# Max-plus operations and neutral elements and commutativity\n# ==============================================================================\n\nb = MP(3.0)\n@test b + mp0 == mp0 + b == MP(max(3.0, -Inf)) == MP(max(-Inf, 3.0)) == b == MP(3.0)\n@test b * mp1 == mp1 * b == MP(3.0 + 0.0) == MP(0.0 + 3.0) == b == MP(3.0)\n\n@test b * b == MP(3.0 + 3.0) == MP(6.0)\n@test b + b == MP(max(3.0, 3.0)) == MP(3.0)\n\na = MP(5.0)\nb = MP(3.0)\n@test a + b == MP(max(5.0, 3.0)) == b + a == MP(max(3.0, 5.0)) == MP(5.0)\n@test a * b == MP(5.0 + 3.0) == b * a == MP(3.0 + 5.0) == MP(8.0)\n\n# ==============================================================================\n# Max-plus distributivity of operations\n# ==============================================================================\n\nc = MP(1.0)\n@test (a + b) + c == a + (b + c) == a + b + c == MP(max(1.0, 3.0, 5.0)) == MP(5.0)\n@test (a * b) * c == a * (b * c) == a * b * c == MP(1.0 + 3.0 + 5.0) == MP(9.0)\n\n# ==============================================================================\n# Max-plus distributivity\n# ==============================================================================\n\n@test (a + b) * c == MP(max(5.0, 3.0) + 1.0) == MP(6.0)\n@test (a * c) + (b * c) == MP(max(5.0 + 1.0, 3.0 + 1.0)) == MP(6.0)\n\n# ==============================================================================\n# mp0, mp1 and mptop operations\n# ==============================================================================\n\n@test mp0 + mp0 == mp0\n@test mp0 + mp1 == 0\n@test mp0 + mptop == mptop\n@test mp1 + mp0 == 0\n@test mp1 + mp1 == 0\n@test mp1 + mptop == mptop\n\n@test mp0 * mp0 == mp0\n@test mp0 * mp1 == mp0\n#FIXME @test mp0 * mptop == mp0\n@test mp1 * mp0 == mp0\n@test mp1 * mp1 == 0\n@test mp1 * mptop == mptop\n\n#FIXME @test mp0 - mp0 == mp0\n@test mp0 - mp1 == mp0\n#FIXME @test mp1 - mp0 == 0\n@test mp1 - mp1 == 0\n\n@test mptop - mp0 == mptop\n@test mptop - mp1 == mptop\n@test mp0 - mptop == mp0\n@test mp1 - mptop == mp0\n\n# ==============================================================================\n# Max-plus element by element operations\n# ==============================================================================\n\nA=MP([1.0 2.0; 3.0 4.0])\n@test 2.0 .+ A == A .+ 2.0 == [MP(2.0) + MP(1.0) MP(2.0) + MP(2.0); MP(2.0) + MP(3.0) MP(2.0) + MP(4.0)] == MP([2.0 2.0; 3.0 4.0])\n@test 2.0 .* A == A .* 2.0 == [MP(2.0) * MP(1.0) MP(2.0) * MP(2.0); MP(2.0) * MP(3.0) MP(2.0) * MP(4.0)] == MP([3.0 4.0; 5.0 6.0])\n\n# ==============================================================================\n# Max-plus other operations\n# ==============================================================================\n\n@test MP(2)^4   == MP(2 * 4) == MP(8)\n@test MP(0)^0   == MP(0 * 0) == MP(0)\n@test MP(2)^0   == MP(2 * 0) == MP(0)\n@test MP(2)^-3  == MP(2)^(-3) == MP(2 * -3) == MP(-6)\n@test MP(2)^0.5 == MP(2 * 0.5) == MP(1.0)\n\n@test b / b == MP(3.0 - 3.0) == MP(0.0)\n@test b - b == MP(3.0 - 3.0) == MP(0.0)\n\n@test MP(3.0) / MP(5.0) == MP(3.0 - 5.0) == MP(-2.0)\n@test MP(3.0) - MP(5.0) == MP(3.0 - 5.0) == MP(-2.0)\n\n@test abs2(MP(3.0)) == MP(6.0)\n\n# ==============================================================================\n# Max-plus min\n# ==============================================================================\n\nb=MP(3.0)\n@test min(b, mp0) == mp0\n@test min(b, mp1) == mp1\n@test min(MP(1), MP(2)) == MP(1)\n@test min(MP([10 1; 10 1]), MP([4 5; 6 5])) == MP([4 1; 6 1])\n@test min(mpsparse([10 1; 10 1]), mpsparse([4 5; 6 5])) == mpsparse([4 1; 6 1])\n\n# ==============================================================================\n# Julia found bugs. Check if they are really fixed.\n\nA = mpzeros(Float64, 2,2)\n\n# Do not insert zero() element\nA[1,1] = mp0\n@test A.nzval == []\n@test isempty(nonzeros(A))\n\n# Insert fake zero element\nA[1,1] = MP(0.0)\n@test A[1,1] == MP(0.0)\n@test A.nzval == MP([0.0])\n@test !isempty(nonzeros(A))\n\n# Allow replacing a non-zero() element by a zero() element\nA[1,1] = mp0\n@test A[1,1] == MP(-Inf)\n@test A.nzval == MP([-Inf])\n@test !isempty(nonzeros(A))\n\n# ==============================================================================\n# Max-plus length() and isempty()\n# ==============================================================================\n# Note: ScicosLab will return isempty == false and length = 2\n# Note: NSP, like Julia will return isempty == false and length = 4\n\nA = mpzeros(Float64, 2,2)\n@test length(A) == 4\n@test !isempty(A)\n\nA[1,1] = MP(0.0)\n@test length(A) == 4\n@test !isempty(A)\n\n# ==============================================================================\n# Max-plus between objects of different types\n# ==============================================================================\n\nb = MP(3.0)\n@test b + 3.0 == 3.0 + b == b == MP(max(3.0, 3.0)) == MP(3.0)\n@test b + 3   == 3   + b == b == MP(max(3.0, 3.0)) == MP(3.0)\n@test b * 3.0 == 3.0 * b == MP(3.0 + 3.0) == MP(6.0)\n@test b * 3   == 3   * b == MP(3.0 + 3.0) == MP(6.0)\n\n# ==============================================================================\n# Max-plus dense matrix creation\n# ==============================================================================\n\nb = MP(3.0); C = [b 4.0; 5.0 6.0]; D = MP([3.0 4.0; 5.0 6.0])\n@test C == D\n@test typeof(C) == ArrMP{Float64,2}\n\n# Max-Plus matrix of max-plus ones\nO = mpones(Float64, 2)\n@test typeof(O) == Array{MP{Float64},1}\n@test O == [mp1; mp1]\n\nO = mpones(Float64, 2,5)\n@test typeof(O) == ArrMP{Float64,2}\n@test O == [mp1 mp1 mp1 mp1 mp1; mp1 mp1 mp1 mp1 mp1]\n\n# Identity matrix\nId = mpeye(Float64, 2)\n@test Id == mpeye(Float64, 2)\n@test typeof(Id) == ArrMP{Float64,2}\n@test Id == [mp1 mp0; mp0 mp1]\n\nId = mpeye(Float64, 2,5)\n@test typeof(Id) == ArrMP{Float64,2}\n@test Id == [mp1 mp0 mp0 mp0 mp0; mp0 mp1 mp0 mp0 mp0]\n\n# ==============================================================================\n# Max-plus / non max-plus conversion\n# ==============================================================================\n\nA=MP([1.0 2.0; 3.0 4.0])\nn = 2.0\n@test plustimes(MP(n)) == n\n@test plustimes(mpzeros(Float64,2,2)) == ones(Float64, 2,2) .* mp0\n@test array(MP(A)) == plustimes(MP(A)) == A\n@test MP(array(B)) == MP(plustimes(B)) == B\n\n# ==============================================================================\n# Convert values usable for min-plus\n# ==============================================================================\n@test minplus(MP(1.0)) == MP(1.0)\n@test minplus(mp0) == mptop\n@test minplus(mptop) == mp0\n@test minplus(MP([Inf 0.0; 7 -Inf])) == MP([-Inf 0.0; 7 Inf])\n#FIXME @test minplus(mpsparse([Inf 0.0; 7 -Inf], preserve=true)) == mpsparse([-Inf 0.0; 7 Inf], preserve=true)\nA = MP([0 3 Inf 1; 1 2 2 -Inf; -Inf Inf 1 0])\n@test minplus(A) == MP([0 3 -Inf 1; 1 2 2 Inf; Inf -Inf 1 0])\n@test minplus(minplus(A)) == A\n\n# ==============================================================================\n# Max-plus sparse matrix creation and conversion\n# ==============================================================================\n\n# Construct a sparse max-plus vector\nV = MP(sparse([1.0, 0.0, 1.0]))\n@test typeof(V) == SpvMP{Float64,Int64}\n@test V.nzval == MP([1.0; 1.0])\n\n# Construct a sparse max-plus vector of zeros\nV = mpzeros(Float64, 2)\n@test typeof(V) == SpvMP{Float64,Int64}\n@test V.nzval == MP([])\n\n# Construct a sparse max-plus matrix\nA = MP(sparse([1, 2, 3], [1, 2, 3], [-Inf, 2, 0]))\n@test typeof(A) == SpaMP{Float64,Int64}\n@test A.nzval == [MP(-Inf), MP(2.0), MP(0.0)]\n\n# Construct a sparse max-plus matrix\nA = MP(sparse([1, 2, 3], [1, 2, 3], [-Inf, 2, 0]), preserve=false)\n@test typeof(A) == SpaMP{Float64,Int64}\n@test A.nzval == [MP(2.0)]\n\n# Basic dense non max-plus matrix to max-plus sparse array\nA = mpsparse([1.0 2.0; 3.0 4.0])\n@test typeof(A) == SpaMP{Float64,Int64}\n@test (A.m == 2) && (A.n == 2)\n@test nonzeros(A) == MP([1.0; 3.0; 2.0; 4.0])\n\nA = mpsparse(MP([1.0 2.0; 3.0 4.0]))\n@test typeof(A) == SpaMP{Float64,Int64}\n@test (A.m == 2) && (A.n == 2)\n@test nonzeros(A) == MP([1.0; 3.0; 2.0; 4.0])\n\n# 0.0 are not eliminated in the max-plus sparse array\nB = mpsparse([1.0 2.0; 0.0 4.0])\n@test typeof(B) == SpaMP{Float64,Int64}\n@test (B.m == 2) && (B.n == 2)\n@test nonzeros(B) == MP([1.0; 0.0; 2.0; 4.0])\n\nB = mpsparse(MP([1.0 2.0; 0.0 4.0]))\n@test typeof(B) == SpaMP{Float64,Int64}\n@test (B.m == 2) && (B.n == 2)\n@test nonzeros(B) == MP([1.0; 0.0; 2.0; 4.0])\n\n# -Inf are eliminated in the max-plus sparse array\nC = mpsparse([1.0 2.0; -Inf 4.0])\n@test typeof(C) == SpaMP{Float64,Int64}\n@test (C.m == 2) && (C.n == 2)\n@test nonzeros(C) == MP([1.0; 2.0; 4.0])\n\nC = mpsparse(MP([1.0 2.0; -Inf 4.0]))\n@test typeof(C) == SpaMP{Float64,Int64}\n@test (C.m == 2) && (C.n == 2)\n@test nonzeros(C) == MP([1.0; 2.0; 4.0])\n\n# Max-Plus matrix of zeros is already a max-plus sparse array\nD = mpzeros(Float64, 3,4)\n@test typeof(D) == SpaMP{Float64,Int64}\n@test (D.m == 3) && (D.n == 4)\n@test nonzeros(D) == []\n\n# Convert max-plus array to max-plus sparse array\nE = mpsparse(mpones(Float64, 3,4))\n@test typeof(E) == SpaMP{Float64,Int64}\n@test (E.m == 3) && (E.n == 4)\n@test nonzeros(E) == MP(zeros(Float64, 12))\n\n# Convert non max-plus array to max-plus sparse array\nF = mpsparse(ones(Float64, 3,4))\n@test typeof(F) == SpaMP{Float64,Int64}\n@test (F.m == 3) && (F.n == 4)\n@test nonzeros(F) == ones(12) .+ MP(1.0)\n\n#\nG = mpsparse(MP([1.0 2.0 3.0; 1.0 2.0 3.0; 0.0 2.0 0.0]))\n@test typeof(G) == SpaMP{Float64,Int64}\n@test (G.m == 3) && (G.n == 3)\n@test nonzeros(G) == MP([1.0; 1.0; 0.0; 2.0; 2.0; 2.0; 3.0; 3.0; 0.0])\n\n# max-plus sparse array to max-plus dense array\nZ = dense(mpzeros(Float64, 2,2))\n@test typeof(Z) == ArrMP{Float64,2}\n@test Z == [mp0 mp0; mp0 mp0]\n\n# max-plus sparse array to max-plus dense array\nZ = full(mpzeros(Float64, 2,2))\n@test typeof(Z) == ArrMP{Float64,2}\n@test Z == [mp0 mp0; mp0 mp0]\n\n# max-plus sparse array to non max-plus dense array\nZ = array(mpzeros(Float64, 2,2))\n@test typeof(Z) == SparseMatrixCSC{Float64,Int64}\n@test Z == [-Inf -Inf; -Inf -Inf]\n\n# ==============================================================================\n# Bug with Julia with SparseMatrixCSC and operator== which confused zero() and 0.0\n\nA = MP(sparse([1, 2], [1, 2], [0.0, 0.0]))\nB = mpzeros(Float64, 2,2)\n@test A.nzval == MP([0.0, 0.0])\n@test (A == B) == false\n\nAA = sparse([1, 2], [1, 2], [mp0, mp0])\nBB = mpzeros(Float64, 2,2)\n@test AA.nzval == MP([-Inf, -Inf])\n@test (AA == BB) == true\n\n# ==============================================================================\n# Max-plus operations with matrices\n# ==============================================================================\n\nA = MP([4 3; 7 -Inf])\n@test A^0 == mpeye(Float64, 2,2)\n@test A * A == A^2 == MP([10.0 7.0; 11.0 10.0])\n@test A * A * A == A^3 == MP([14.0 13.0; 17.0 14.0])\n# TODO A^-1\n\nC = [MP(3.0) 4.0; 5.0 6.0]\nD = MP([1.0 2; 3 4])\n@test C + D == D + C == MP([3.0 4.0; 5.0 6.0]) == C\n\n# Trace\n# TODO shall we forbid trace of non squared matrices ?\n@test mptrace([]) == mp0\n@test mptrace(mpeye(Float64, 2,2)) == tr(mpeye(Float64, 2,2)) == 0.0\n@test mptrace(mpeye(Float64, 2,5)) == 0.0\n@test mptrace(mpzeros(Float64, 2,2)) == mptrace(full(mpzeros(Float64, 2,2))) == tr(mpzeros(Float64, 2,2)) == mp0\n@test mptrace(mpzeros(Float64, 2,5)) == mptrace(full(mpzeros(Float64, 2,5))) == mp0\n@test mptrace([1.0 2.0; 3.0 4.0]) == tr(MP([1.0 2.0; 3.0 4.0])) == MP(1.0) + MP(4.0) == MP(4.0)\n@test mptrace(sparse([1.0 2.0; 3.0 4.0])) == mptrace(mpsparse([1.0 2.0; 3.0 4.0])) == MP(4.0)\n\n# ==============================================================================\n# Max-plus norm\n# ==============================================================================\n\n@test mpnorm(MP([1 20 2;30 400 4;4 50 10])) == MP(400 - 1) == MP(399)\n@test mpnorm(mpsparse([1 20 2;30 400 4;4 50 10])) == MP(400 - 1) == MP(399)\n@test mpnorm([mp0 1; 10 mp0]) == MP(10.0) - mp0 == mptop\n\n# ==============================================================================\n# Max-plus star\n# ==============================================================================\n@test mpstar(MP(1.0)) == mpstar(1.0) == mptop\n@test mpstar(MP(-1.0)) == mpstar(-1.0) == mp1\n@test mpstar(MP([1.0 2; 3 4])) == mpstar([1.0 2; 3 4]) == [mptop mptop; mptop mptop]\nA=MP([-3.0 -2; -1 0]); B = mpstar(A)\n@test B == mpeye(Float64, 2,2) + A\n@test B == B + A^2\n@test B == B + A^3\n\n@test mpstar(mpeye(Float64, 2,2)) == mpeye(Float64, 2,2)\n\n#TODO sparse\n#sA = mpsparse(A); sB = mpstar(sA)\n#@test B == mpeye(Float64, 2,2) + A\n#@test B == B + A^2\n#@test B == B + A^3\n\n# ==============================================================================\n# TODO @test C / C == MP([0.0 -2.0; 2.0 0.0])\n# ==============================================================================\n\n\n# ==============================================================================\n# Max-plus display\n# ==============================================================================\nusing Suppressor\n\nmp_change_display(0)\nresult = @capture_out show(stdout, mp0)\n@test result == \"-Inf\"\nresult = @capture_out show(stdout, mp1)\n@test result == \"0.0\"\nresult = @capture_out show(stdout, MP(4.0))\n@test result == \"4.0\"\nresult = @capture_out show(stdout, mpzero(Int64))\n@test result == \"-9223372036854775808\"\n\nmp_change_display(1)\nresult = @capture_out show(stdout, mp0)\n@test result == \".\"\nresult = @capture_out show(stdout, mp1)\n@test result == \"0\"\nresult = @capture_out show(stdout, MP(4.0))\n@test result == \"4\"\nresult = @capture_out show(stdout, mpzero(Int64))\n@test result == \".\"\n\nmp_change_display(2)\nresult = @capture_out show(stdout, mp0)\n@test result == \".\"\nresult = @capture_out show(stdout, mp1)\n@test result == \"e\"\nresult = @capture_out show(stdout, MP(4.0))\n@test result == \"4\"\nresult = @capture_out show(stdout, mpzero(Int64))\n@test result == \".\"\n\nmp_change_display(3)\nresult = @capture_out show(stdout, mp0)\n@test result == \"\u03b5\"\nresult = @capture_out show(stdout, mp1)\n@test result == \"0\"\nresult = @capture_out show(stdout, MP(4))\n@test result == \"4\"\nresult = @capture_out show(stdout, mpzero(Int64))\n@test result == \"\u03b5\"\n\nmp_change_display(4)\nresult = @capture_out show(stdout, mp0)\n@test result == \"\u03b5\"\nresult = @capture_out show(stdout, mp1)\n@test result == \"e\"\nresult = @capture_out show(stdout, MP(4.0))\n@test result == \"4\"\nresult = @capture_out show(stdout, mpzero(Int64))\n@test result == \"\u03b5\"\n\nA = MP([4.5 0.0; 7.0 -Inf])\nresult = @capture_out show(stdout, A)\n@test result == \"MP{Float64}[4.5 e; 7 \u03b5]\"\nresult = @capture_out LaTeX(stdout, A)\n@test result == \"\\\\left[\\n\\\\begin{array}{*{20}c}\\n4.5 & e \\\\\\\\\\n7 & \\\\varepsilon \\\\\\\\\\n\\\\end{array}\\n\\\\right]\\n\"\nmp_change_display(0)\nresult = @capture_out LaTeX(stdout, A)\n@test result == \"\\\\left[\\n\\\\begin{array}{*{20}c}\\n4.5 & 0 \\\\\\\\\\n7 & -\\\\infty \\\\\\\\\\n\\\\end{array}\\n\\\\right]\\n\"\n", "meta": {"hexsha": "8d512fb66414f2c95959e0121fa0fbbcae50910f", "size": 17729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_maxplus.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MaxPlus.jl-41177cfe-c387-11e9-2806-edd030e4594e", "max_stars_repo_head_hexsha": "bce044436a7985269229500c53363081e7263d87", "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": "test/test_maxplus.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MaxPlus.jl-41177cfe-c387-11e9-2806-edd030e4594e", "max_issues_repo_head_hexsha": "bce044436a7985269229500c53363081e7263d87", "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": "test/test_maxplus.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MaxPlus.jl-41177cfe-c387-11e9-2806-edd030e4594e", "max_forks_repo_head_hexsha": "bce044436a7985269229500c53363081e7263d87", "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.7053231939, "max_line_length": 130, "alphanum_fraction": 0.4508996559, "num_tokens": 6083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7724457245301476}}
{"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\u22121] 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\u2217(X[i\u22121])2+X[i\u22121] \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\u00b2(n) = 2^8*n^7*(n-1)^(2n-5)/((n+1)^(2n+5))\n\nbalmer_s\u00b2(n) = 2^17*n^7*(n^2-1)*(n-2)^(2n-6)/((n+2)^(2n+6))\n\nfunction balmer_p\u00b2(n,\u2113)\n    if \u2113 == 0\n        2^15*n^9*(n-2)^(2n-6)/(3*(n+2)^(2n+6))\n    elseif \u2113 == 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\u00b2(o, n, \u2113)\n    # Eq. (BS63.5)\n    n == o.n && return (3/2*n*\u221a(n^2-max(\u2113,o.\u2113)^2))^2\n    n = float(n)\n    if o == o\"1s\"\n        lyman\u00b2(n)\n    elseif o == o\"2s\"\n        balmer_s\u00b2(n)\n    elseif o == o\"2p\"\n        balmer_p\u00b2(n, \u2113)\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,\u2113\u2032)) in enumerate([(o\"1s\",1), (o\"2s\",1), (o\"2p\",0), (o\"2p\",2)])\n            for n\u2032 = 1+\u2113\u2032:8\n                @test radial_dipole_moment(o, Orbital(n\u2032, \u2113\u2032))^2 \u2248\n                    lyman_balmer\u00b2(o, n\u2032, \u2113\u2032)\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) \u2248 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": "# Solve Project Euler problem 96 (sudoku) to test ExactCovers.\n#\n# The idea here is to reduce sudoku to the exact cover problem and then use\n# ExactCovers to solve that. Because we need to solve multiple sudokus, we\n# costruct a general sudoku matrix and then, for each sudoku,\n# 1. cover the parts of the matrix that correspond to givens,\n# 2. find an exact cover for the partially covered matrix, and finally\n# 3. uncover in reverse order.\n# This is more efficient (and also easier to write down) than creating a\n# specialized matrix for each sudoku.\n#\n# Each row (subset) in the sudoku matrix corresponds to placing a number into a\n# square. The columns (elements) correspond to the individual constraints that\n# each placement fulfills. These are:\n# * The corresponding square is filled.\n# * The corresponding row has the placed number.\n# * The corresponding column has the placed number.\n# * The corresponding box (3x3-subgrid) has the placed number.\n#\n# Because the sudoku rules dictate that each of these constraints must be\n# satisfied exactly once, an exact cover for that matrix is a solution to\n# sudoku. Preselecting (covering) rows (subsets) now makes sure that we are\n# actually solving the given sudoku instance, instead of an empty grid.\n\n\"Creates the `CoverSet` that represents an empty sudoku grid.\"\nfunction make_sudoku_matrix()\n  box_for(row, column) = (div(row - 1, 3) + 1, div(column - 1, 3) + 1)\n\n  constraints_for(row, column, number) = Set(Any[\n    (:square_is_filled, row, column),\n    (:row_has, row, number),\n    (:column_has, column, number),\n    (:box_has, box_for(row, column), number)\n  ])\n\n  CoverMatrix(Dict([\n    (row, column, number) => constraints_for(row, column, number) for\n      row in 1:9,\n      column in 1:9,\n      number in 1:9\n  ]))\nend\n\n\"\"\"\nPreselects the given placements from `sudoku` in `matrix`.\n\"\"\"\nfunction cover_givens!(sudoku, matrix)\n  for row in 1:9, column in 1:9\n    if sudoku[row, column] > 0\n      cover_subset!(matrix, (row, column, sudoku[row, column]))\n    end\n  end\nend\n\n\"\"\"\nReverses the preselection from `sudoku`, so that `matrix` is restored to a\npristine sudoku matrix.\n\"\"\"\nfunction uncover_givens!(sudoku, matrix)\n  for row in 9:-1:1, column in 9:-1:1\n    if sudoku[row, column] > 0\n      uncover_subset!(matrix, (row, column, sudoku[row, column]))\n    end\n  end\nend\n\n\"\"\"\nSolves `sudoku`, assuming `matrix` is a sudoku matrix representing an empty\ngrid. `matrix` will be restored to that state when the call returns.\n\"\"\"\nfunction solve(sudoku, matrix)\n  result = copy(sudoku)\n  cover_givens!(sudoku, matrix)\n  for entry in find_exact_cover(matrix)\n    row, column, number = entry\n    result[row, column] = number\n  end\n  uncover_givens!(sudoku, matrix)\n  \n  result\nend\n\n\"\"\"\nReads the source file containing the sudoku instances to solve.\n\"\"\"\nsudoku_producer() = @task let\n  file = open(joinpath(dirname(@__FILE__), \"data\", \"sudokus.txt\"))\n  while !eof(file)\n    readline(file)\n    sudoku = Array(Int8, 9, 9)\n    for row in 1:9\n        sudoku[row, :] = [c - Int8('0') for c in read(file, Int8, 9)]\n        readline(file)\n    end\n\n    produce(sudoku)\n  end\nend\n\n# Actually solve Project Euler problem 96. This means solving the sudokus,\n# extracting the first three boxes of each, interpreting them as 3-digit\n# numbers and adding them up.\nlet\n  result = 0\n\n  matrix = make_sudoku_matrix()\n  for sudoku in sudoku_producer()\n    sudoku = solve(sudoku, matrix)\n    result += 100sudoku[1, 1] + 10sudoku[1, 2] + sudoku[1, 3]\n  end\n\n  @test result == 24702\nend\n", "meta": {"hexsha": "8e517a3f8f352232c6b83299bebcbc4a743a1d56", "size": 3524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/euler96.jl", "max_stars_repo_name": "lmshk/ExactCovers.jl", "max_stars_repo_head_hexsha": "4be7fa23728618b229b37c07fac0a24445bf3a68", "max_stars_repo_licenses": ["MIT"], "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/euler96.jl", "max_issues_repo_name": "lmshk/ExactCovers.jl", "max_issues_repo_head_hexsha": "4be7fa23728618b229b37c07fac0a24445bf3a68", "max_issues_repo_licenses": ["MIT"], "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/euler96.jl", "max_forks_repo_name": "lmshk/ExactCovers.jl", "max_forks_repo_head_hexsha": "4be7fa23728618b229b37c07fac0a24445bf3a68", "max_forks_repo_licenses": ["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.9122807018, "max_line_length": 79, "alphanum_fraction": 0.703461975, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809829, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7723358066049435}}
{"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        \u03b1 = -0.5x[i+1]+x[i]^2\n        fx += cos(\u03b1)\n    end\n    return fx\nend\n\ng! = (g, x) -> begin\n    for i in 1:lastindex(x)-1\n        \u03b1 = -0.5x[i+1]+x[i]^2\n        g[i] -= 2.0sin(\u03b1)x[i]\n        g[i+1] += 0.5sin(\u03b1)\n    end\n    return g\nend\n \nfg! = (g, x) -> begin\n    fx = 0.0 \n    for i in 1:lastindex(x)-1\n        \u03b1 = -0.5x[i+1]+x[i]^2\n        fx += cos(\u03b1)\n        g[i] -= 2.0sin(\u03b1)*x[i]\n        g[i+1] += 0.5sin(\u03b1)\n    end\n    return fx, g\nend\n\ninit = (n::Int=10000) -> begin\n    n < 2 && @warn(\"COSINE: number of variables must be \u2265 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": "# # [How to port rules generated by SparseADRules to Zygote](@id lowrank_svd)\n#\n# In this demo we'll show how to insert SparseADRules's sparse gradient implementation to boost Zygote's gradient in lowrank svd.\nusing Zygote\nusing SparseArrays, LinearAlgebra\nusing SparseADRules:low_rank_svd\nimport FiniteDifferences\nusing BenchmarkTools\nusing ChainRulesCore, ChainRulesTestUtils\ninclude(joinpath(@__DIR__, \"..\", \"test\", \"testutils.jl\"))\n\nfunction svd_loss(A::AbstractSparseMatrix{T}, z::Vector{T}, r::Int) where T\n    U, S, Vt = low_rank_svd(A, r)\n    residual_mat = U * Diagonal(S) * Vt - U * Diagonal(z) * Vt\n    return tr(residual_mat'*residual_mat) # square of Frobenius norm\nend\n\n# generate test data\nr = 10\nA = sprand(100, r, 0.2) * Diagonal(rand(r)) * sprand(r, 50, 0.2)\nz = rand(r)\n\n@btime grad_A = Zygote.gradient(A -> svd_loss(A, z, r), $A) \ngrad_A = Zygote.gradient(A -> svd_loss(A, z, r), A)[1] \n\ngrad_fA = FiniteDifferences.grad(FiniteDifferences.central_fdm(5, 1), A -> svd_loss(A, z, r), A)[1]\n\nusing Test\n@testset \"test AD on lowrank svd\" begin\n    @test grad_A \u2248 grad_fA\nend\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0f0f6596606c6b2d4e9c378f571ba22d8d0307c8", "size": 1098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lowrank_svd.jl", "max_stars_repo_name": "jieli-matrix/SparseADRules.jl", "max_stars_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-10-01T14:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T11:56:47.000Z", "max_issues_repo_path": "examples/lowrank_svd.jl", "max_issues_repo_name": "jieli-matrix/SparseADRules.jl", "max_issues_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-03T07:23:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T07:23:55.000Z", "max_forks_repo_path": "examples/lowrank_svd.jl", "max_forks_repo_name": "jieli-matrix/SparseArraysAD.jl", "max_forks_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T00:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:59:17.000Z", "avg_line_length": 28.1538461538, "max_line_length": 129, "alphanum_fraction": 0.7131147541, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7722990084867323}}
{"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, \u03c3)\n    \u03b2 = 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-\u03c3) .- 1) ./ (1-\u03c3)\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 .+ \u03b2*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    \u03b8 = mean(d)\n    for i in 1:20\n        \u03b8 -= (cdf(d, \u03b8) - q) / pdf(d, \u03b8)  # \u03b8 = \u03b8 - (F(\u03b8) - q) / F'(\u03b8)\n    end\n    \u03b8\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 = \u03c0/2\neang = \u03c0\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    \u2207\u00b2f = state.\u2207\u00b2f\n    isposdef(\u2207\u00b2f) && return \u2207\u00b2f\n    return n.modify(\u2207\u00b2f)\nend\n\nfunction direction(n::Newton, state)\n    \u2207f = state.\u2207f\n    \u2207\u00b2f = approx_hessian(n::Newton, state)\n    return -inv(\u2207\u00b2f) * \u2207f\nend\n\n\"\"\"\n    MultipleIdentity{B, S}\n\nModify the Hessian by adding some multiples, \u03c4, of the identity matrix, as described in \nNocedal and Wright's Numerical Optimization.\n\n# Fields\n- `\u03b2::B`: constant to compute appropriate \u03c4\n- `scale::S`: scale factor to expand \u03c4\n\"\"\"\nstruct MultipleIdentity{B, S}\n    \u03b2::B\n    scale::S\n\n    function MultipleIdentity(\u03b2, \u03c1)\n        \u03b2 > 0 || error(\"\u03b2 must be positive\")\n        \u03c1 > 1 || error(\"\u03c1 must be larger than 1\")\n        new{typeof(\u03b2), typeof(\u03c1)}(\u03b2, \u03c1)\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)(\u2207\u00b2f::Matrix{T}) where T\n    \u03b2 = T(mi.\u03b2)\n    scale = T(mi.scale)\n    \u03c4 = -minimum(diag(\u2207\u00b2f)) + \u03b2\n    h = similar(\u2207\u00b2f)\n    while true\n        h .= \u2207\u00b2f + \u03c4*I\n        isposdef(h) && return h\n        \u03c4 = max(scale*\u03c4, \u03b2)\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": "# v0.6\n\nusing Distributions\n\nfunction eqdist(data::Vector{T}, \u03b1::Float64=0.05)::Bool where T <: Real\n    if ! (0 \u2264 \u03b1 \u2264 1); error(\"\u03b1 must be in [0, 1]\") end\n    exp = mean(data)\n    chisqval = sum((x - exp) ^ 2 for x in data) / exp\n    pval = ccdf(Chisq(2), chisqval)\n    return pval > \u03b1\nend\n\ndata1 = [199809, 200665, 199607, 200270, 199649]\ndata2 = [522573, 244456, 139979,  71531,  21461]\n\nfor data in (data1, data2)\n    println(\"Data:\\n$data\")\n    println(\"Hypothesis test: the original population is \", (eqdist(data) ? \"\" : \"not \"), \"uniform.\\n\")\nend\n", "meta": {"hexsha": "3add14625c59bd9f39290eab4d987f9c30ca1073", "size": 554, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/verify-distribution-uniformity-chi-squared-test.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/verify-distribution-uniformity-chi-squared-test.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/verify-distribution-uniformity-chi-squared-test.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.7, "max_line_length": 103, "alphanum_fraction": 0.6173285199, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7722288500214036}}
{"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 = \u222b (x' Q x + u' R u) from 0 to \u221e\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": "module Day5\nexport day5\n\nfunction parseLine(line)\n    for r in (\"F\"=>\"0\", \"B\"=>\"1\", \"L\"=>\"0\", \"R\"=>\"1\")\n        line = replace(line, r)\n    end\n    parse(Int, line; base = 2)\nend\n\nfunction readInput(inputfile=\"inputs/input05.txt\")\n    [parseLine(line) for line in eachline(inputfile)]\nend\n\nfunction day5(inputfile=\"inputs/input05.txt\")\n    values = readInput(inputfile)\n    (maximum(values), day5Part2(values))\nend\n\nfunction day5Part2(values)\n    sort!(values)\n    for (a,b) in zip(values, @view values[2:end])\n        if b-a == 2\n            return a+1\n        end\n    end\nend\n\nend #module", "meta": {"hexsha": "c5290af90653e5b4bf18b41968a7cb1f63371696", "size": 590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day05.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/day05.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/day05.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": 20.3448275862, "max_line_length": 53, "alphanum_fraction": 0.6169491525, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.772220144432}}
{"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 \u2018se3mat\u2019 (an element of Lie Algebra se3)\r\n# from given twist vector (= 6x1 vector) \u2018xi\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 \u2018xi\u2019 from given twist matrix \u2018se3mat\u2019\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 \u2018R\u2019 by\r\n# evaluating matrix exponential of 3x3 skew symmetric matrix \u2018so3mat\u2019\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 \u2018g\u2019 by\r\n# evaluating matrix exponential of 4x4 twist matrix \u2018se3mat\u2019\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(\u03bc, \u03c3, \u03c1)\n\nA shifted and scaled (affinely transformed) version of `\u03c1`.\n\nIf ``Z`` is a random variable with distribution `\u03c1`, then `AffineDistribution(\u03bc, \u03c3, \u03c1)` is\nthe distribution of the random variable\n```math\nX = \u03bc + \u03c3 Z\n```\n\nIf `\u03c1` 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-\u03bc}{\u03c3} \\\\right).\n```\n\nIf `\u03c1` 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}{|\u03c3|} f_Z\\\\left( \\\\frac{x-\u03bc}{\u03c3} \\\\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 = \u03bc + \u03c3 * \u03c1       # Create location-scale transformed distribution\nparams(d)           # Get the parameters, i.e. (\u03bc, \u03c3, \u03c1)\n```\n\"\"\"\nstruct AffineDistribution{T<:Real, S<:ValueSupport, D<:UnivariateDistribution{S}} <: UnivariateDistribution{S}\n    \u03bc::T\n    \u03c3::T\n    \u03c1::D\n    function AffineDistribution{T,S,D}(\u03bc::T, \u03c3::T, \u03c1::D; check_args=true) where {T<:Real, S<:ValueSupport, D<:UnivariateDistribution{S}}\n        check_args && @check_args(AffineDistribution, \u03c3 > zero(\u03c3))\n        new{T, S, D}(\u03bc, \u03c3, \u03c1)\n    end\nend\n\nfunction AffineDistribution(\u03bc::T, \u03c3::T, \u03c1::UnivariateDistribution; check_args::Bool=true) where {T<:Real}\n    _T = promote_type(eltype(\u03c1), T)\n    D = typeof(\u03c1)\n    S = value_support(D)\n    return AffineDistribution{_T,S,D}(_T(\u03bc), _T(\u03c3), \u03c1; check_args=check_args)\nend\n\nfunction AffineDistribution(\u03bc::Real, \u03c3::Real, \u03c1::UnivariateDistribution; check_args::Bool=true)\n    return AffineDistribution(promote(\u03bc, \u03c3)..., \u03c1; check_args=check_args)\nend\n\n# aliases\nconst LocationScale{T,S,D} = AffineDistribution{T,S,D}\nfunction LocationScale(\u03bc::Real, \u03c3::Real, \u03c1::UnivariateDistribution; check_args::Bool=true)\n    Base.depwarn(\"`LocationScale` is deprecated, use `AffineDistribution` instead\", :LocationScale)\n    if check_args && \u03c3 \u2264 0  # preparation for future PR where I remove \u03c3 > 0 check\n        throw(ArgumentError(\"\u03c3 must be strictly positive.\"))\n    end\n    return AffineDistribution(\u03bc, \u03c3, \u03c1; 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.\u03bc + d.\u03c3 * minimum(d.\u03c1)\nmaximum(d::AffineDistribution) = d.\u03bc + d.\u03c3 * maximum(d.\u03c1)\nsupport(d::AffineDistribution) = affinedistribution_support(d.\u03bc, d.\u03c3, support(d.\u03c1))\nfunction affinedistribution_support(\u03bc::Real, \u03c3::Real, support::RealInterval)\n    return RealInterval(\u03bc + \u03c3 * support.lb, \u03bc + \u03c3 * support.ub)\nend\naffinedistribution_support(\u03bc::Real, \u03c3::Real, support) = \u03bc .+ \u03c3 .* support\n\nAffineDistribution(\u03bc::Real, \u03c3::Real, d::AffineDistribution) = AffineDistribution(\u03bc + d.\u03bc * \u03c3, \u03c3 * d.\u03c3, d.\u03c1)\n\n#### Conversions\n\nconvert(::Type{AffineDistribution{T}}, \u03bc::Real, \u03c3::Real, \u03c1::D) where {T<:Real, D<:UnivariateDistribution} = AffineDistribution(T(\u03bc),T(\u03c3),\u03c1)\nconvert(::Type{AffineDistribution{T}}, d::AffineDistribution{S}) where {T<:Real, S<:Real} = AffineDistribution(T(d.\u03bc),T(d.\u03c3),d.\u03c1, check_args=false)\n\n#### Parameters\n\nlocation(d::AffineDistribution) = d.\u03bc\nscale(d::AffineDistribution) = d.\u03c3\nparams(d::AffineDistribution) = (d.\u03bc,d.\u03c3,d.\u03c1)\npartype(::AffineDistribution{T}) where {T} = T\n\n#### Statistics\n\nmean(d::AffineDistribution) = d.\u03bc + d.\u03c3 * mean(d.\u03c1)\nmedian(d::AffineDistribution) = d.\u03bc + d.\u03c3 * median(d.\u03c1)\nmode(d::AffineDistribution) = d.\u03bc + d.\u03c3 * mode(d.\u03c1)\nmodes(d::AffineDistribution) = d.\u03bc .+ d.\u03c3 .* modes(d.\u03c1)\n\nvar(d::AffineDistribution) = d.\u03c3^2 * var(d.\u03c1)\nstd(d::AffineDistribution) = d.\u03c3 * std(d.\u03c1)\nskewness(d::AffineDistribution) = skewness(d.\u03c1)\nkurtosis(d::AffineDistribution) = kurtosis(d.\u03c1)\n\nisplatykurtic(d::AffineDistribution) = isplatykurtic(d.\u03c1)\nisleptokurtic(d::AffineDistribution) = isleptokurtic(d.\u03c1)\nismesokurtic(d::AffineDistribution) = ismesokurtic(d.\u03c1)\n\nentropy(d::ContinuousAffineDistribution) = entropy(d.\u03c1) + log(d.\u03c3)\nentropy(d::DiscreteAffineDistribution) = entropy(d.\u03c1)\n\nmgf(d::AffineDistribution,t::Real) = exp(d.\u03bc*t) * mgf(d.\u03c1,d.\u03c3*t)\n\n#### Evaluation & Sampling\n\npdf(d::ContinuousAffineDistribution, x::Real) = pdf(d.\u03c1,(x-d.\u03bc)/d.\u03c3) / d.\u03c3\npdf(d::DiscreteAffineDistribution, x::Real) = pdf(d.\u03c1,(x-d.\u03bc)/d.\u03c3)\n\nlogpdf(d::ContinuousAffineDistribution,x::Real) = logpdf(d.\u03c1,(x-d.\u03bc)/d.\u03c3) - log(d.\u03c3)\nlogpdf(d::DiscreteAffineDistribution, x::Real) = logpdf(d.\u03c1,(x-d.\u03bc)/d.\u03c3)\n\nfor f in (:cdf, :ccdf, :logcdf, :logccdf)\n    @eval $f(d::AffineDistribution, x::Real) = $f(d.\u03c1, (x - d.\u03bc) / d.\u03c3)\nend\n\nquantile(d::AffineDistribution,q::Real) = d.\u03bc + d.\u03c3 * quantile(d.\u03c1,q)\n\nrand(rng::AbstractRNG, d::AffineDistribution) = d.\u03bc + d.\u03c3 * rand(rng, d.\u03c1)\ncf(d::AffineDistribution, t::Real) = cf(d.\u03c1,t*d.\u03c3) * exp(1im*t*d.\u03bc)\ngradlogpdf(d::ContinuousAffineDistribution, x::Real) = gradlogpdf(d.\u03c1,(x-d.\u03bc)/d.\u03c3) / d.\u03c3\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\u2080 :: Real)\n    success=0\n    x= X\u2080\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 -> \u212f^(-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\u1d63Data=[]\nfor n in ProgressBar(1:N)\n    xList, successful_steps=Metropolis(x -> \u212f^(-x^2/2), 10^5, stepsList[n] , 0.0)\n    push!(a\u1d63Data, successful_steps)\nend\nplot(stepsList,a\u1d63Data , 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\u1d63List=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\nC\u2c7cList=[]\nfor n in ProgressBar(1:9)\n    xList, successful_steps=Metropolis(x -> \u212f^(-x^2/2), 10^5, stepsList[n] , 0.0)\n    push!(C\u2c7cList, autocor(xList))\nend\nsave(\"../../chapter8/8.1/CjList.jld\",\"CjList\",C\u2c7cList)\nselectedNums=[1, 3, 6, 9 ]\n\nplot()\nfor i in selectedNums\n    plot!(1:length(C\u2c7cList[i]), C\u2c7cList[i], linewidth=3, label=L\"a_r\\ =\\ %$(a\u1d63List[i])\")\nend\nplot!(ylabe=\"C\u2c7c\", 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\u03beList=Float64[]\nx=[i for i in 1:10]\nfor i in C\u2c7cList\n    push!(logCl,log.(i[1:10]))\nend\nhcat(x, ones(10))\nfor y in logCl\n    \u03be\u207d\u207b\u00b9\u207e, Const= hcat(x, ones(10)) \\ y\n    \u03be= -1/\u03be\u207d\u207b\u00b9\u207e\n    push!(\u03beList, \u03be)\nend\nplot(a\u1d63List, \u03beList, title=\"Correlation Length\", xlabel=L\"a_r\", ylabel=L\"\\xi\", label=nothing)\nscatter!(a\u1d63List, \u03beList, dpi=600, label=nothing)\nsave(\"../../chapter8/8.1/xiList.jld\",\"\u03beList\",\u03beList)\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\u2081\")\nprintln(\"--------------------------\")\ndisplay_matrix(stdout, group_multiplication_table(group1))\nprintln()\n\nprintln(\"Multiplication Table of G\u2082\")\nprintln(\"--------------------------\")\ndisplay_matrix(stdout, group_multiplication_table(group2))\nprintln()\n\n\n# ## Group Isomorphism\n\nprintln(\"Group Isomorphism  \u03d5: G\u2081 \u2192 G\u2082\")\nprintln(\"-----------------------------\")\n\u03d5 = group_isomorphism(group1, group2)\nfor g in 1:group_order(group1)\n    println(\"  \u03d5($g) = $(\u03d5[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[\u03d5[g], \u03d5[h]] = \u03d5[ group_product(group1, g, h) ]\nend\n\nprintln(\"Multiplication Table of \u03d5(G\u2081)\")\nprintln(\"-----------------------------\")\ndisplay_matrix(stdout, mtab2)\nprintln()\nprintln(\"  \u03d5(g)\u22c5\u03d5(h) = \u03d5(g\u22c5h)\")\nprintln(\"  \u03d5(G\u2081) \u2261 G\u2082 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!(\u03a0old, \u03a0new, p, q)\n    Nold = size(\u03a0old, 1)\n    \u03a0new[1:Nold, 1:Nold] = p*\u03a0old\n    \u03a0new[1:Nold, 2:(Nold+1)] .+= (1-p)*\u03a0old\n    \u03a0new[2:(Nold+1), 1:Nold] .+= (1-q)*\u03a0old\n    \u03a0new[2:(Nold+1), 2:(Nold+1)] .+= q*\u03a0old\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, \u03c1, \u03c3)\n    # Discretizes\n    # y\u2032 = \u03c1 y +  \u03c3 \u03f5\n\n    \u03c9 = \u03c3/sqrt(1-\u03c1^2) # Long run std dev\n    # println(\"Long run variance: $\u03c9\")\n    q = (1+\u03c1)/2\n\n    points = range(-\u03c9*sqrt(npts - 1),\n                   \u03c9*sqrt(npts-1),\n                   length=npts)\n\n    # points = GenGrid(uniform(npts, bds))\n    \u03a0 = rouwenmat(npts, q, q)\n    return points, \u03a0\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": "using HypothesisTests, Distributions, Test, Random\nusing HypothesisTests: default_tail\nusing StableRNGs\n\n@testset \"Anderson-Darling\" begin\n@testset \"One sample test\" begin\n    n = 1000\n    rng = StableRNG(1984948)\n\n    d = Normal(1000, 100)\n    x = rand(rng, d, n)\n    t = OneSampleADTest(x, d)\n    @test t.A\u00b2 \u2248 1.2960 atol=0.1^4\n    @test pvalue(t) \u2248 0.2336 atol=0.1^4\n    @test default_tail(t) == :right\n\n    d = DoubleExponential()\n    x = rand(rng, d, n)\n    t = OneSampleADTest(x, Normal(mean(d), std(d)))\n    @test t.A\u00b2 \u2248 11.0704 atol=0.1^4\n    @test pvalue(t) \u2248 0.0 atol=0.1^4\n    t = OneSampleADTest(x, d)\n    @test t.A\u00b2 \u2248 0.8968 atol=0.1^4\n    @test pvalue(t) \u2248 0.4162 atol=0.1^4\n\n    d = Cauchy()\n    x = rand(rng, Cauchy(), n)\n    t = OneSampleADTest(x, Normal())\n    @test pvalue(t) \u2248 0.0 atol=0.1^4\n    t = OneSampleADTest(x, d)\n    @test pvalue(t) \u2248 0.9640 atol=0.1^4\n\n    d = LogNormal()\n    x = rand(rng, d, n)\n    t = OneSampleADTest(x, Normal(mean(d), std(d)))\n    @test pvalue(t) \u2248 0.0 atol=0.1^4\n    t = OneSampleADTest(x, d)\n    @test pvalue(t) \u2248 0.9123 atol=0.1^4\n\n    d = Uniform(-pi, 2pi)\n    x = rand(rng, d, n)\n    t = OneSampleADTest(x, d)\n    @test pvalue(t) \u2248 0.2337 atol=0.1^4\n\n    x = rand(rng, Uniform(0, 1.8), n)\n    t = OneSampleADTest(x, Uniform())\n    @test pvalue(t) \u2248 0.0 atol=0.1^4\n\n    x = rand(rng, Exponential(), n)\n    t = OneSampleADTest(x, Exponential())\n    @test pvalue(t) \u2248 0.8579 atol=0.1^4\nend\n\n@testset \"k-sample test\" begin\n    samples = Any[\n        [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0],\n        [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8],\n        [34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0],\n        [34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]\n    ]\n\n    t = KSampleADTest(samples...)\n    @test t.A\u00b2k \u2248 8.3926 atol=0.1^4\n    @test t.\u03c3 \u2248 1.2038 atol=0.1^4\n    @test pvalue(t) \u2248 0.0022 atol=0.1^4\n    @test default_tail(t) == :right\n\n    ts = KSampleADTest(samples..., nsim = 20000);\n    @test pvalue(ts) \u2248 0.00155 atol=0.1^3\n\n    t = KSampleADTest(samples..., modified = false)\n    @test t.A\u00b2k \u2248 8.3559 atol=0.1^4\n    @test t.\u03c3 \u2248 1.2038 atol=0.1^4\n    @test pvalue(t) \u2248 0.0023 atol=0.1^4\n\n    ts = KSampleADTest(samples..., modified = false, nsim = 20000);\n    @test pvalue(ts) \u2248 0.00150 atol=0.1^3\nend\n\n@testset \"more tests\" begin\n    rng =  StableRNG(31412455)\n    samples = Any[rand(rng, Normal(), 50), rand(rng, Normal(0.5), 30)]\n    t = KSampleADTest(samples...)\n    @test pvalue(t) < 0.05\n\n    samples = Any[rand(rng, Normal(), 50), rand(rng, Normal(), 30), rand(rng, Normal(), 20)]\n    t = KSampleADTest(samples...)\n    @test pvalue(t) > 0.05\n\n    @test pvalue(OneSampleADTest(vcat(rand(rng, Normal(),500), rand(rng, Beta(2,2),500)), Beta(2,2))) \u2248 0.0 atol=0.1^4\n\n    n = 1000\n    x = rand(rng, Exponential(), n)\n    @test pvalue(KSampleADTest(rand(rng, 1000), randn(rng, 1000))) \u2248 0.0 atol=eps()\n    @test pvalue(KSampleADTest(x,x,x,x,x,x)) \u2248 1.0\nend\n\nend\n", "meta": {"hexsha": "66ae09587a26b982c33415719ad63e71abad393b", "size": 2945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/anderson_darling.jl", "max_stars_repo_name": "BERENZ/HypothesisTests.jl", "max_stars_repo_head_hexsha": "21ba623a10035685a01b7c9416b2916468a9a989", "max_stars_repo_licenses": ["MIT"], "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/anderson_darling.jl", "max_issues_repo_name": "BERENZ/HypothesisTests.jl", "max_issues_repo_head_hexsha": "21ba623a10035685a01b7c9416b2916468a9a989", "max_issues_repo_licenses": ["MIT"], "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/anderson_darling.jl", "max_forks_repo_name": "BERENZ/HypothesisTests.jl", "max_forks_repo_head_hexsha": "21ba623a10035685a01b7c9416b2916468a9a989", "max_forks_repo_licenses": ["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.7474747475, "max_line_length": 118, "alphanum_fraction": 0.5803056027, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7722089010757545}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.17\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 42338250-4387-11eb-1d21-a3b1adbf202c\nbegin\n\tusing Pkg\n    Pkg.activate(pwd())\nend\n\n# \u2554\u2550\u2561 593f78f0-4387-11eb-3175-93d23999fd88\nbegin\n\tusing CSV\n\tusing Statistics\n\tusing DataFrames\nend\n\n# \u2554\u2550\u2561 9d6fccb0-4395-11eb-34d8-8de61157070c\nusing Colors\n\n# \u2554\u2550\u2561 1d3942f0-4387-11eb-05e8-85639ea3579a\nmd\"\"\"\n# Data Mining\n## Assignment 3 - Correlation Matrix\n### Aadam - CS1945\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4f544fa0-438c-11eb-1c71-f10ea0b7747c\ndf = transform(\"data/iris.data\")[:, 2:end-1]\n\n# \u2554\u2550\u2561 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\u2019s correlation coefficient between each of the row in data matrix. Pearson\u2019s 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0eb51410-438d-11eb-0a4b-a59b660f63dd\ncor_matrix = cor(Matrix(df))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0ee10610-438d-11eb-193c-3d806714919a\ncor_mean = mean(cor_matrix, dims=1)\n\n# \u2554\u2550\u2561 0ef59f80-438d-11eb-15f0-6986acb67f16\ncor_median = median(cor_matrix, dims=1)\n\n# \u2554\u2550\u2561 0b236830-4395-11eb-129b-65553ddfc548\ncor_mean_matrix = zeros(size(cor_matrix));\n\n# \u2554\u2550\u2561 16ab1130-4395-11eb-3d46-ad660d6c74c6\ncor_median_matrix = zeros(size(cor_matrix));\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c0379bb0-4395-11eb-269b-19b8db40b0d5\nmd\"\"\"\n# Visualize\nConvert the discretized matrix into bitmap.\n\"\"\"\n\n# \u2554\u2550\u2561 1257b542-4398-11eb-3aec-d9c38c46ccf3\nmd\"\"\"\n### Median Discretized Correlation Matrix\n\"\"\"\n\n# \u2554\u2550\u2561 9d8884d2-4395-11eb-294b-5d0b022f06e5\nGray.(cor_median_matrix)\n\n# \u2554\u2550\u2561 23e78ec2-4398-11eb-35d0-0b6de4d620de\nmd\"\"\"\n### Mean Discretized Correlation Matrix\n\"\"\"\n\n# \u2554\u2550\u2561 f627fab0-4397-11eb-00e1-0f3bc6802852\nGray.(cor_mean_matrix)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25001d3942f0-4387-11eb-05e8-85639ea3579a\n# \u255f\u250042338250-4387-11eb-1d21-a3b1adbf202c\n# \u2560\u2550593f78f0-4387-11eb-3175-93d23999fd88\n# \u255f\u2500b3196bd0-43a3-11eb-3831-65d049f3abef\n# \u2560\u2550bd551d90-4387-11eb-1e63-a5993648b680\n# \u2560\u25504f544fa0-438c-11eb-1c71-f10ea0b7747c\n# \u255f\u2500afbd4320-4390-11eb-1e7a-df636c495cba\n# \u2560\u2550eaa97310-438f-11eb-2ad5-d141a81d9791\n# \u2560\u2550578bf662-43a4-11eb-3d40-0b491ad520b2\n# \u2560\u25500eb51410-438d-11eb-0a4b-a59b660f63dd\n# \u255f\u25000ecb0d10-438d-11eb-2b61-a783a5176442\n# \u2560\u25500ee10610-438d-11eb-193c-3d806714919a\n# \u2560\u25500ef59f80-438d-11eb-15f0-6986acb67f16\n# \u2560\u25500b236830-4395-11eb-129b-65553ddfc548\n# \u2560\u255016ab1130-4395-11eb-3d46-ad660d6c74c6\n# \u2560\u25500f0d1f20-438d-11eb-27ef-b9a25e3b9436\n# \u255f\u2500c0379bb0-4395-11eb-269b-19b8db40b0d5\n# \u2560\u25509d6fccb0-4395-11eb-34d8-8de61157070c\n# \u255f\u25001257b542-4398-11eb-3aec-d9c38c46ccf3\n# \u2560\u25509d8884d2-4395-11eb-294b-5d0b022f06e5\n# \u255f\u250023e78ec2-4398-11eb-35d0-0b6de4d620de\n# \u2560\u2550f627fab0-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": "# ---\n# title: 67. Add Binary\n# id: problem67\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math, String\n# link: <https://leetcode.com/problems/add-binary/description/>\n# hidden: true\n# ---\n# \n# Given two binary strings `a` and `b`, return _their sum as a binary string_.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: a = \"11\", b = \"1\"\n#     Output: \"100\"\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: a = \"1010\", b = \"1011\"\n#     Output: \"10101\"\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= a.length, b.length <= 104`\n#   * `a` and `b` consist only of `'0'` or `'1'` characters.\n#   * Each string does not contain leading zeros except for the zero itself.\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "48bf61b870efde91ddde7bed02dafb47e376471d", "size": 787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/67.add-binary.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/67.add-binary.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/67.add-binary.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.1086956522, "max_line_length": 78, "alphanum_fraction": 0.5451080051, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7721774491525465}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.1\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f0f80b1a-d090-11eb-2b0d-d11fd8196311\n#using Omega, Distributions, UnicodePlots\n\n# \u2554\u2550\u2561 4936c45a-a5bf-49cb-bfdc-c05883d5982b\nfaulty_pin = @~ DiscreteUniform(1, 10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d3af8df6-5375-4a52-9432-41ef6227af0c\nerror_prob = Variable(\u03c9 -> 0.01) # constant random variable\n\n# \u2554\u2550\u2561 b0769639-7b6a-4d95-bc8d-bdedd5d27c4f\nerror_occurred = @~ Bernoulli(error_prob)\n\n# \u2554\u2550\u2561 8e2fb0c5-ca50-4bcb-85bf-d78c06ea5653\nalternative_pin = @~ DiscreteUniform(1, 10)\n\n# \u2554\u2550\u2561 ad3ec928-dc20-4987-aaed-78e8c4141d3e\nfunction measure(\u03c9)\n\tif error_occurred(\u03c9)\n\t\talternative_pin(\u03c9)\n\telse\n\t\tfaulty_pin(\u03c9)\n\tend\nend\n\n# \u2554\u2550\u2561 87199546-b427-4908-9531-28d40995efa8\nmd\"As described above, a chip is bad if the faulty_pin is pin 1\"\n\n# \u2554\u2550\u2561 4b8285ca-0fa8-4c38-a2a9-870169a2c1d7\nbad_chip = faulty_pin ==\u209a 1\n\n# \u2554\u2550\u2561 021546fa-267d-4789-b6a5-b69d7eea01e6\nmd\"We'll define a function `prob` to estimate the probability that an event is true:\"\n\n# \u2554\u2550\u2561 0ed2799b-0e1b-434a-85be-99a3869a89c7\nprob(x; n = 1000) = mean(randsample(x, n))\n\n# \u2554\u2550\u2561 505f497c-2852-44f2-bf17-8bfb12886554\nmd\"The probability that it's a bad chip is:\"\n\n# \u2554\u2550\u2561 fc03484c-206d-4c3d-90f9-773e3b9b0a90\nprob(bad_chip)\n\n# \u2554\u2550\u2561 413d05ce-ed65-406e-be97-32a2bad22d92\nmd\"Now suppose we use our probe and observe a measurement of 1\"\n\n# \u2554\u2550\u2561 ff0aced3-466f-44e8-8d84-9521fca7c7c4\nevidence = measure ==\u209a 1;\n\n# \u2554\u2550\u2561 233e3ee2-e56c-4c4d-a53d-83c144c303d0\nmd\"Given the evidence, we can look at our conditional belief over which pin is faulty:\"\n\n# \u2554\u2550\u2561 5774b63a-d492-490e-862a-0c3645722885\nhistogram(randsample(cnd(faulty_pin, evidence), 1000))\n\n# \u2554\u2550\u2561 c6d93cdd-a2bd-4e5b-b835-1509cc582978\nmd\"And compute the conditional probability that it is indeed a bad chip (faulty pin == 1)\"\n\n# \u2554\u2550\u2561 32b3da83-0fb4-4a99-9742-46f9ad13eb8b\nconditional_bad_chip = cnd(bad_chip, evidence);\n\n# \u2554\u2550\u2561 5ddfb321-d696-4853-bb9a-f3b8593f074d\nmd\"Given the evidence, the conditional probability the chip is bad is high, at:\"\n\n# \u2554\u2550\u2561 ff904fa3-898b-4c35-a1c4-8a08ca5f82df\nprob_bad = prob(conditional_bad_chip)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dbe58fac-bc39-4ee1-8930-6bb4e8453317\ncan_certify(p) = p < 0.3\n\n# \u2554\u2550\u2561 03ac41b7-10fd-4466-976d-f2815fe655a2\nmd\"Clearly, we cannot certify this chip:\"\n\n# \u2554\u2550\u2561 6b9ac9fa-56c3-453f-aba7-69cd193d91c3\ncan_certify(prob_bad)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 aa15703f-6137-4d67-bb25-bec070d3d193\nerror_prob_noisy = 0.9\n\n# \u2554\u2550\u2561 da0608ac-94bd-4ba1-81be-1cde40bd4cae\nconditional_bad_chip_noisy_probe = intervene(conditional_bad_chip, error_prob => error_prob_noisy);\n\n# \u2554\u2550\u2561 828161b0-c32e-4ae8-9206-1f7ce95dfda4\nprob_bad_noisy = prob(conditional_bad_chip_noisy_probe)\n\n# \u2554\u2550\u2561 1e1a3659-0a82-46c1-9b6e-0f8de142f9be\nmd\"Job done?\"\n\n# \u2554\u2550\u2561 b6470b88-3ac0-4ccf-81df-c6f80e409a64\ncan_certify(prob_bad_noisy)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 672b6bfa-54ce-4b12-80f0-ee930a777cbc\nprobwow = pw(prob, rid(conditional_bad_chip_noisy_probe, (faulty_pin, alternative_pin)))\n\n# \u2554\u2550\u2561 36a6cb8a-f81e-4e05-9dd0-a475e88ab62c\n# histogram(randsample(probwow, 100))\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500daa9fd86-5a36-4aa2-842e-477cdb19b8d5\n# \u255f\u250062257a75-2949-4afc-8543-fe3fa4073be5\n# \u255f\u250053572568-9d02-465a-baba-1c624d79d4b5\n# \u2560\u2550f0f80b1a-d090-11eb-2b0d-d11fd8196311\n# \u2560\u2550ca32437b-65ce-401b-93fc-1f3b7011ae88\n# \u2560\u25504936c45a-a5bf-49cb-bfdc-c05883d5982b\n# \u255f\u250057c308fa-a2e7-49fb-b52d-41346ee7ea0d\n# \u2560\u2550d3af8df6-5375-4a52-9432-41ef6227af0c\n# \u2560\u2550b0769639-7b6a-4d95-bc8d-bdedd5d27c4f\n# \u2560\u25508e2fb0c5-ca50-4bcb-85bf-d78c06ea5653\n# \u2560\u2550ad3ec928-dc20-4987-aaed-78e8c4141d3e\n# \u255f\u250087199546-b427-4908-9531-28d40995efa8\n# \u2560\u25504b8285ca-0fa8-4c38-a2a9-870169a2c1d7\n# \u255f\u2500021546fa-267d-4789-b6a5-b69d7eea01e6\n# \u2560\u25500ed2799b-0e1b-434a-85be-99a3869a89c7\n# \u255f\u2500505f497c-2852-44f2-bf17-8bfb12886554\n# \u2560\u2550fc03484c-206d-4c3d-90f9-773e3b9b0a90\n# \u255f\u2500413d05ce-ed65-406e-be97-32a2bad22d92\n# \u2560\u2550ff0aced3-466f-44e8-8d84-9521fca7c7c4\n# \u255f\u2500233e3ee2-e56c-4c4d-a53d-83c144c303d0\n# \u2560\u25505774b63a-d492-490e-862a-0c3645722885\n# \u255f\u2500c6d93cdd-a2bd-4e5b-b835-1509cc582978\n# \u2560\u255032b3da83-0fb4-4a99-9742-46f9ad13eb8b\n# \u255f\u25005ddfb321-d696-4853-bb9a-f3b8593f074d\n# \u2560\u2550ff904fa3-898b-4c35-a1c4-8a08ca5f82df\n# \u255f\u2500ae28acc2-fb0f-4189-bdaa-574a3e090f75\n# \u2560\u2550dbe58fac-bc39-4ee1-8930-6bb4e8453317\n# \u255f\u250003ac41b7-10fd-4466-976d-f2815fe655a2\n# \u2560\u25506b9ac9fa-56c3-453f-aba7-69cd193d91c3\n# \u255f\u25009ef8cafd-49e5-439a-9723-479babd7e6d7\n# \u255f\u25008c128635-e46d-418e-8c51-d74fc55973e4\n# \u2560\u2550aa15703f-6137-4d67-bb25-bec070d3d193\n# \u2560\u2550da0608ac-94bd-4ba1-81be-1cde40bd4cae\n# \u2560\u2550828161b0-c32e-4ae8-9206-1f7ce95dfda4\n# \u255f\u25001e1a3659-0a82-46c1-9b6e-0f8de142f9be\n# \u2560\u2550b6470b88-3ac0-4ccf-81df-c6f80e409a64\n# \u255f\u2500abe64bc4-cdef-4cb5-80cc-2e99e792ecab\n# \u2560\u2550672b6bfa-54ce-4b12-80f0-ee930a777cbc\n# \u2560\u255036a6cb8a-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": "function counting_sort_letters(A, pos) # A:Array, p:position\n    n = length(A)\n    k = 26 # number of letters in alphabet\n    start_ascii = Int('a'[1]) # Ascii decimal of a\n    C = fill(0,k) # initialize counter array to 0\n    # Storing count for each letter\n    for i = 1:n\n        if (length(A[i]) < pos) return A end\n        counterIdx = Int(A[i][pos])-start_ascii+1 # -a_ascii+1 to start from 1\n        C[counterIdx] = C[counterIdx] + 1\n    end\n    # Changing C[j] so it contains actual position of all each element\n    for j = 2:(k)\n        C[j] = C[j] + C[j-1]\n    end\n    B = fill(\"z\",n) # initialize return array\n    for i = n:-1:1\n        counterIdx = Int(A[i][pos])-start_ascii+1\n        B[C[counterIdx]] = A[i] # Always adds next string to first element of B\n        C[counterIdx] = C[counterIdx] - 1 # Reduce the count of current element by 1\n    end\n    return B\nend\n\nfunction counting_sort_length(A)\n    n = length(A)\n    k = 0 # Max string length in array A\n    for i = 1:n # find the longest string\n        if (length(A[i]) > k) k = length(A[i]) end\n    end\n    C = fill(0,k) # initialize counter array to 0\n    for i = 1:n # counter\n        counterIdx = length(A[i])\n        C[counterIdx] = C[counterIdx] + 1\n    end\n    # Changing C[j] so it contains actual position of all each element\n    for j = 2:(k)\n        C[j] = C[j] + C[j-1]\n    end\n    B = fill(\"z\",n) # initialize return array\n    for i = n:-1:1\n        counterIdx = length(A[i])\n        B[C[counterIdx]] = A[i]  # Always adds next string to first element of B\n        C[counterIdx] = C[counterIdx] - 1 # Reduce the count of current element by 1\n    end\n    return B\nend\n\nfunction flexradix(A, max_length)\n    A = counting_sort_length(A)\n\n    # SPLIT UP ARRAY AND RETURN ONLY THE SIDE WHERE EVERY ELEMENT HAS\n    # STRING SIZE BIGGER THAN P??\n\n    for p = 1:max_length # p: position\n        A = counting_sort_letters(A, p)\n    end\n    return A\n\n    #=\n    n = length(A)\n    C = fill(0,max_length) # initialize counter array to 0\n    for i = 1:n # counter\n        counterIdx = length(A[i])\n        C[counterIdx] = C[counterIdx] + 1\n    end\n    # Now we have a sorted list by length, and the number of lengths. We can then\n    # iterate through the lengths and ommit the previous smaller arrays as\n    # the problem developes\n    for i = 1:max_length\n        A =\n        C = fill(0,n) # Counter for strings with different sizes\n        A = counting_sort_letters(A, i)\n        C[counterIdx] = C[counterIdx] - 1 # Reduce the count of current element by 1\n    end\n    =#\nend\n", "meta": {"hexsha": "9336f341ab9ee7bee4fb390fc731c3eae12904cb", "size": 2549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "assignment-04/assignment-04.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-04/assignment-04.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-04/assignment-04.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": 32.6794871795, "max_line_length": 84, "alphanum_fraction": 0.6041584935, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7721254252535158}}
{"text": "##\nusing IFGF\nusing LinearAlgebra\nusing StaticArrays\nusing Random\nusing Plots\nplotlyjs()\nRandom.seed!(1)\n\nincludet(joinpath(IFGF.PROJECT_ROOT,\"test\",\"testutils.jl\"))\n\nk    = 8\u03c0\n\u03bb    = 2\u03c0/k\nppw  = 10\ndx   = \u03bb/ppw\n\nXpts = Ypts = sphere_uniform_surface_mesh(dx)\nnpts = length(Xpts)\n\nK    = HelmholtzKernel(k)\nT    = ComplexF64\n\nI   = rand(1:npts,100)\nB   = randn(T,npts)\nexa = [sum(K( Xpts[i],Ypts[j])*B[j] for j in 1:npts) for i in I]\n\n# trees\nsplitter   = Trees.CardinalitySplitter(;nmax=200)\n\n# cone size function\nds_func = IFGF.cone_domain_size_func(k,(1.0,\u03c0/2,\u03c0/2))\n\n# loop over interpolation order\npvec = 2:8\ner   = []\nfor p in pvec\n    ptuple  = (p,p,p)\n    A       = IFGFOp(K,Xpts,Ypts;splitter,p=ptuple,ds_func,threads=true)\n    C       = zeros(T,npts)\n    mul!(C,A,B,1,0;threads=true)\n    ee = norm(C[I]-exa,2) / norm(exa,2)\n    push!(er,ee)\nend\n\nprint(\n    \"Uniform points on surfaces of sphere with parameters:\n        r   = 1\n        k   = $k\n        n   = $npts\n        ppw = $ppw\"\n)\n\n\nfig = plot(pvec,er,yscale=:log10,m=:circle,\n    ylabel=\"approximate \u2113\u2082 relative error\",\n    xlabel=\"p\",\n    label=\"sphere\")\n\ndir = @__DIR__\nsavefig(fig,joinpath(dir,\"sphere_p_convergence.png\"))\n", "meta": {"hexsha": "cd5c3b6ecdb9d30136ed552f1d7126c93e29139f", "size": 1191, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "convergence/helmholtz/vary_p.jl", "max_stars_repo_name": "WaveProp/IFGF", "max_stars_repo_head_hexsha": "4d80918792a4b3512eea85ddddabc575622a7ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "convergence/helmholtz/vary_p.jl", "max_issues_repo_name": "WaveProp/IFGF", "max_issues_repo_head_hexsha": "4d80918792a4b3512eea85ddddabc575622a7ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-02-03T20:28:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T08:14:51.000Z", "max_forks_repo_path": "convergence/helmholtz/vary_p.jl", "max_forks_repo_name": "WaveProp/IFGF", "max_forks_repo_head_hexsha": "4d80918792a4b3512eea85ddddabc575622a7ace", "max_forks_repo_licenses": ["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.5245901639, "max_line_length": 72, "alphanum_fraction": 0.6305625525, "num_tokens": 424, "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": "# module Angles\n\nexport\n    wrap_to_2pi,\n    wrap_to_pi,\n    angular_difference\n\nwrap_to_2pi(\u03b8) = mod(\u03b8,2\u03c0)\n\n\"\"\"\n    `wrap_to_pi(\u03b8\u2080)`\n\n    wraps the angle \u03b8\u2080 to a value in (-\u03c0,\u03c0]\n\"\"\"\nfunction wrap_to_pi(\u03b8\u2080)\n    # \u03b8 = \u03b8\u2080\n    \u03b8 = wrap_to_2pi(\u03b8\u2080)\n    # while \u03b8 > \u03c0\n    if \u03b8 > \u03c0\n        \u03b8 = \u03b8 - 2\u03c0\n    # end\n    # while \u03b8 <= -\u03c0\n    elseif \u03b8 <= -\u03c0\n        \u03b8 += 2\u03c0\n    end\n    return \u03b8\nend\n\nfunction angular_difference(\u03b81,\u03b82)\n    t1 = wrap_to_2pi(\u03b81)\n    t2 = wrap_to_2pi(\u03b82)\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\u03c9 = 1.0\nx_sor = [(i=i, sor=sor(A, a, \u03c9; maxiter=i)) for i in r]\nA * x_sor[11].sor |> display\nprintln()\n\nx_ssor = [(i=i, ssor=ssor(A, a, \u03c9; 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 \u00d7 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 (\u03ba::LinearMixingModelKernel)((x, px)::Tuple{Any,Int}, (y, py)::Tuple{Any,Int})\n    (px > size(\u03ba.H, 2) || py > size(\u03ba.H, 2) || px < 1 || py < 1) &&\n        error(\"`px` and `py` must be within the range of the number of outputs\")\n    return sum(\u03ba.H[i, px] * \u03ba.K[i](x, y) * \u03ba.H[i, py] for i in 1:length(\u03ba.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\u0305 = mean(X)\n    X\u0305j = mean.(R)\n    k = length(R)\n    top = sum(nj .*(X\u0305j .- X\u0305) .^2) /(k-1)\n    bottom = sum([sum((R[i] .- X\u0305j[i]) .^2) for i in 1:k])/(N-k)\n    return top/bottom\nend\nfunction f_slow(R,N,nj,X\u0305,k)\n    X\u0305j = mean.(R)\n    top = sum(nj .*(X\u0305j .- X\u0305) .^2) /(k-1)\n    bottom = sum([sum((R[i] .- X\u0305j[i]) .^2) for i in 1:k])/(N-k)\n    return top/bottom\nend\n\nfunction f(R,N,nj,X\u0305,k)\n    X\u0305j = mean.(R)\n    top = 0.0\n    bottom = 0.0\n    @inbounds for i in 1:k\n        top += nj[i] * (X\u0305j[i] - X\u0305)^2\n        for j in 1:nj[i]\n            bottom += (R[i][j] - X\u0305j[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\u0305 ::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\u0305[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\u0305_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\u0305_p[i,j] = mean(vcat(R[i]...,R[j]...))\n        end\n    end\n    return N_p,nj_p,X\u0305_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 \ud835\udc32 = \ud835\udc17\u03b2 + \u03f5, with \u03b2 = \ud835\udc17\u1d57\ud835\udc17\u207b\u00b9\ud835\udc17\u1d57\ud835\udc32\n\"\"\"\nmutable struct SecondOrderPolynomialSurrogate{X,Y,B,L,U} <: AbstractSurrogate\n    x::X\n    y::Y\n    \u03b2::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    \u03b2 = X\\Y\n    return SecondOrderPolynomialSurrogate(x, y, \u03b2, 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)\u00f72\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)\u00f72] = 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.\u03b2[1, :]\n    for j = 1:d\n        y += val[j]*my_second_ord.\u03b2[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.\u03b2[idx, :]\n    end\n    for j = 1:d\n        y += val[j]^2 * my_second_ord.\u03b2[j+1+d+d*(d-1)\u00f72, :]\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    \u03b2 = X\\Y\n    my_second.\u03b2 = \u03b2\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] \u2208 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(\u221e) and \u03bd:\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: \u03bd-->0.61 , Pc(\u221e)-->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, \u03b1=0.85, n::Integer=100, \u03f5=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 .- \u03b1) .* 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 = \u03b1 .* (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 * \u03f5)\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') = \u03c3\u00b2(1+\u221a5|x-x'|/\u2113 + 5|x-x'|\u00b2/(3\u2113\u00b2))\\\\exp(- \u221a5|x-x'|/\u2113)\n```\nwith length scale ``\u2113`` and signal standard deviation ``\u03c3``.\n\"\"\"\nmutable struct Mat52Iso{T<:Real} <: MaternIso\n    \"Length scale\"\n    \u2113::T\n    \"Signal variance\"\n    \u03c32::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nMatern 5/2 isotropic covariance function\n    \n    Mat52Iso(ll::Real, l\u03c3::Real)\n\n# Arguments\n  - `ll::Real`: length scale (given on log scale)\n  - `l\u03c3::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat52Iso(ll::T, l\u03c3::T) where T = Mat52Iso{T}(exp(ll), exp(2 * l\u03c3), [])\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.\u2113, mat.\u03c32 = exp(hyp[1]), exp(2 * hyp[2])\nend\nget_params(mat::Mat52Iso{T}) where T = T[log(mat.\u2113), log(mat.\u03c32) / 2]\nget_param_names(mat::Mat52Iso) = [:ll, :l\u03c3]\nnum_params(mat::Mat52Iso) = 2\n\ncov(mat::Mat52Iso, r::Number) =\n    (s = \u221a5 * r / mat.\u2113; mat.\u03c32 * (1 + s + s^2 / 3) * exp(-s))\n\n@inline dk_dll(mat::Mat52Iso, r::Real) =\n    (s = \u221a5 * r / mat.\u2113; mat.\u03c32 / 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": "# This file was generated, do not modify it.\n\nusing MLJ, RDatasets, Random\n\ndata = dataset(\"datasets\", \"USArrests\")\nnames(data)\n\ndescribe(data, :mean, :std)\n\nX = select(data, Not(:State))\nX = coerce(X, :UrbanPop=>Continuous);\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\nschema(W).names\n\nr = report(pca)\ncumsum(r.principalvars ./ r.tvar)\n\ndata = dataset(\"ISLR\", \"OJ\")\n\nX = select(data, [:PriceCH, :PriceMM, :DiscCH, :DiscMM, :SalePriceMM,\n                  :SalePriceCH, :PriceDiff, :PctDiscMM, :PctDiscCH]);\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\nr  = report(spca).reports[1]\ncs = cumsum(r.principalvars ./ r.tvar)\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(\"assets/literate/ISL-lab-10-g1.svg\") # hide\n\nRandom.seed!(1515)\n\n@load KMeans\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\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(\"assets/literate/ISL-lab-10-cluster.svg\") # hide\n\n", "meta": {"hexsha": "f7beba7c4e7d0546b06dd9c8c6c4bd24518375e5", "size": 1784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_assets/literate/ISL-lab-10_script.jl", "max_stars_repo_name": "giordano/DataScienceTutorials.jl", "max_stars_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-08-09T11:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:20:43.000Z", "max_issues_repo_path": "_assets/literate/ISL-lab-10_script.jl", "max_issues_repo_name": "giordano/DataScienceTutorials.jl", "max_issues_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-10-22T00:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T14:38:09.000Z", "max_forks_repo_path": "_assets/literate/ISL-lab-10_script.jl", "max_forks_repo_name": "giordano/DataScienceTutorials.jl", "max_forks_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-11-20T16:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T11:55:15.000Z", "avg_line_length": 20.9882352941, "max_line_length": 73, "alphanum_fraction": 0.6513452915, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7720804332829385}}
{"text": "## Canonical Form of Normal distribution\n\nimmutable NormalCanon <: ContinuousUnivariateDistribution\n    \u03b7::Float64       # \u03c3^(-2) * \u03bc\n    \u03bb::Float64    # \u03c3^(-2)\n    \u03bc::Float64       # \u03bc\n\n    function NormalCanon(\u03b7::Real, \u03bb::Real)\n        @check_args(NormalCanon, \u03bb > zero(\u03bb))\n    \tnew(\u03b7, \u03bb, \u03b7 / \u03bb)\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.\u03bc, 1.0 / sqrt(d.\u03bb))\nBase.convert(::Type{NormalCanon}, d::Normal) = (\u03bb = 1.0 / \u03c3^2; NormalCanon(\u03bb * d.\u03bc, \u03bb))\ncanonform(d::Normal) = convert(NormalCanon, d)\n\n\n#### Parameters\n\nparams(d::NormalCanon) = (d.\u03b7, d.\u03bb)\n\n\n#### Statistics\n\nmean(d::NormalCanon) = d.\u03bc\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.\u03bb\nstd(d::NormalCanon) = sqrt(var(d))\n\nentropy(d::NormalCanon) = 0.5 * (log2\u03c0 + 1.0 - log(d.\u03bb))\n\n\n#### Evaluation\n\npdf(d::NormalCanon, x::Float64) = (sqrt(d.\u03bb) / sqrt2\u03c0) * exp(-0.5 * d.\u03bb * abs2(x - d.\u03bc))\nlogpdf(d::NormalCanon, x::Float64) = 0.5 * (log(d.\u03bb) - log2\u03c0 - d.\u03bb * abs2(x - d.\u03bc))\n\nzval(d::NormalCanon, x::Float64) = (x - d.\u03bc) * sqrt(d.\u03bb)\nxval(d::NormalCanon, z::Float64) = d.\u03bc + z / sqrt(d.\u03bb)\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.\u03bc + randn() / sqrt(cf.\u03bb)\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": "using Test, DiscreteExteriorCalculus\nconst DEC = DiscreteExteriorCalculus\nusing LinearAlgebra: norm\nusing Statistics: mean\n\n@testset \"Point and Simplex\" begin\n    p = Point(1,2,3)\n    @test typeof(p) == Point{3}\n    s = Simplex(Point(1,2,3), Point(4,5,6), Point(1,4,7))\n    @test typeof(s) == Simplex{3, 3}\nend\n\n@testset \"Barycentric and barycentric_projection\" begin\n    m = Metric(3)\n    s = Simplex(Point(0,0,0), Point(2,0,0), Point(1,.5,0))\n    for p in [s.points; Point(3,5,7); Point(-12,25,-100); Point(24.3,-3.5,-2.2)]\n        b = Barycentric(m, s, p)\n        @test norm(Point(b).coords - [p.coords[1:end-1]; 0]) < 1e-14\n    end\nend\n\n@testset \"distance\" begin\n    m = Metric(3)\n    s = Simplex(Point(0,0,0), Point(2,0,0), Point(1.3,.7,0), Point(0,0,1))\n    ps = [s.points; Point(3,5,7); Point(-12,25,-100); Point(24.3,-3.5,-2.2)]\n    for p1 in ps\n        for p2 in ps\n            d1 = sqrt(abs(distance_square(m, Barycentric(m, s, p1), p2)))\n            d2 = norm(m, p1.coords - p2.coords)\n            d3 = norm(p1.coords - p2.coords) # using Euclidean metric\n            @test d2 \u2248 d3\n            @test abs(d1 - d2) < 1e-5\n        end\n    end\nend\n\n@testset \"circumsphere\" begin\n    function is_circumcenter(m::Metric{N}, s::Simplex{N, K}, p::Point{N}) where {N, K}\n        if K == 1\n            return s.points[1] == p\n        else\n            dists = [norm(m, p.coords - q.coords) for q in s.points]\n            return all([d \u2248 dists[1] for d in dists])\n        end\n    end\n    function circumradius_square(m::Metric{N}, s::Simplex{N}) where N\n        center, _ = circumsphere(m, s)\n        return mean([norm_square(m, center.coords - v.coords) for v in s.points])\n    end\n    m = Metric(3)\n    s = Simplex(Point(1,2,3), Point(-12,3,5), Point(8,3,4), Point(9,25,-2))\n    for k in 1:4\n        for sub_s in subsimplices(s, k)\n            center, radius_square = circumsphere(m, sub_s)\n            @test is_circumcenter(m, sub_s, center)\n            @test radius_square \u2248 circumradius_square(m, sub_s)\n        end\n    end\nend\n\n@testset \"barycentric_subspace\" begin\n    m = Metric(2)\n    s = Simplex(Point(0,0), Point(1,0), Point(0,1))\n    f = Simplex(s.points[1:2]...)\n    p = Point(.5, 3)\n    M, v = DEC.barycentric_subspace(m, s, f, p)\n    @test M * Barycentric(m, s, p).coords == v\n    @test M * [.5, .5, 0] == v\n    @test M * Barycentric(m, s, Point(.5, -2)).coords == v\nend\n\n@testset \"rotate_about_face\" begin\n    m = Metric(3)\n    s = Simplex(Point(-1,0,0), Point(0,0,0), Point(0,1,0))\n    r, \u03b8 = 3, \u03c0/6\n    p = Point(r * cos(\u03b8), 0, r * sin(\u03b8))\n    b = DEC.rotate_about_face(m, s, p, 1)\n    @test norm(Point(b).coords - [r, 0, 0]) < 1e-15\n\n    m = Metric(2)\n    s = Simplex(Point(0,0),Point(1,0))\n    p = Point(1,1)\n    b = DEC.rotate_about_face(m, s, p, 2)\n    @test Point(b).coords \u2248 [-sqrt(2), 0]\n    b = DEC.rotate_about_face(m, s, p, 1)\n    @test Point(b).coords \u2248 [2, 0]\nend\n\n@testset \"pairwise_delaunay\" begin\n    m = Metric(3)\n    s1 = Simplex(Point(-.1,.5,0), Point(0,0,0), Point(0,1,0))\n    center, _ = circumsphere(m, s1)\n    \u03b8 = \u03c0/6\n    for r in [.1, 1, 5, 10]\n        p = Point(r * cos(\u03b8), 0, r * sin(\u03b8))\n        proj_p = Point(r, 0, 0)\n        # using Euclidean metric\n        delaunay = norm(center.coords - proj_p.coords)^2 - norm(center.coords - s1.points[1].coords)^2\n        s2 = Simplex(s1.points[2:end]..., p)\n        @test pairwise_delaunay(m, s1, s2) \u2248 delaunay\n    end\nend\n\n# TODO test with other metrics\n", "meta": {"hexsha": "182abc44d07b9b670784b7a69d7cfc0866b9d423", "size": 3441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_simplices.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": "test/test_simplices.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": "test/test_simplices.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": 32.7714285714, "max_line_length": 102, "alphanum_fraction": 0.5669863412, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7720560022714459}}
{"text": "using Plots\n\nusing Algopt.TestFunctions: Rosenbrock\n\nusing Algopt.FirstOrder\n\nros = Rosenbrock()\n\nfunction solve_with_method(method)\n    x_0 = [rand(-2:.1:2), rand(-2:.1:2)]\n    res = FirstOrder.search(method, ros.f, ros.\u2207f, x_0, trace = true)\n    println(res[:, end])\n    println(size(res))\n\n    x = y = range(-2, 2, step = .1)\n    plot(contour(x, y, (x, y)->ros.f([x, y]); levels = range(0, 5, step = .1)))\n    plot!(res[1,:], res[2,:], linewidth = 3)\nend\n\nfunction max_grad_descent()\n    mgd = FirstOrder.MaximumGradientDescent()\n    solve_with_method(mgd)\nend\n\nfunction grad_descent(\u03b1)\n    grd = FirstOrder.GradientDescent(\u03b1 = \u03b1)\n    solve_with_method(grd)\nend\n\nfunction conjugate_grad_descent()\n    cgd = FirstOrder.ConjugateGradientDescent()\n    solve_with_method(cgd)\nend\n", "meta": {"hexsha": "6eaed7fc9066955aeb1ecb74e684fb3632910284", "size": 779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plot/first_order.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": "plot/first_order.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": "plot/first_order.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": 22.9117647059, "max_line_length": 79, "alphanum_fraction": 0.6700898588, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7720560017464806}}
{"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) \u2248 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\u0393(z) = gamma(z)\n\nfunction pade(\u03b1::T, \u03b2::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 / \u0393(\u03b2+k*\u03b1)\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*\u03b1-\u03b2) * \u0393(1+k*\u03b1-\u03b2) / \u03c0\n    end\n    A = zeros(T, 2r-1, 2r-1)\n    rhs = zeros(T, 2r-1)\n    if m \u2265 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\u03b1 = 1 / parse(T, \"2\")\n\u03b2 = 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(\u03b1, \u03b2, 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(\u03b1, \u03b2, 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]) \u2264 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, \u03bb, \u0394t)\n    \u039b = Diagonal(\u03bb)\n    R = assemble_transformation_matrix_inverse(\u03bb)\n    S = assemble_transformation_matrix(\u03bb)\n    A = S * \u039b * R * \u0394t\n    return exp(A) * c_0\nend\n\n\n\nfunction transformation_matrix_inverse_ij(i, j, \u03bb)\n    s_ij::eltype(\u03bb) = 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 *= \u03bb[l] / (\u03bb[l] - \u03bb[i])\n    end\n    return s_ij\nend\n\n\n\nfunction transformation_matrix_ij(i, j, \u03bb)\n    s_ij = \u03bb[j] / (\u03bb[i] - \u03bb[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 *= \u03bb[l] / (\u03bb[l] - \u03bb[j])\n    end\n    return s_ij\nend\n\n\n\nfunction assemble_transformation_matrix(\u03bb)\n    n = length(\u03bb)\n    S = zeros(eltype(\u03bb), length(\u03bb), length(\u03bb))\n    S = UnitLowerTriangular(S)\n    for i = 2:n\n        for j = 1:(i-1)\n            S[i, j] = transformation_matrix_ij(i, j, \u03bb)\n        end\n    end\n    return S\nend\n\n\n\nfunction assemble_transformation_matrix_inverse(\u03bb)\n    n = length(\u03bb)\n    R = zeros(eltype(\u03bb), length(\u03bb), length(\u03bb))\n    R = UnitLowerTriangular(R)\n    for i = 2:n\n        for j = 1:i\n            R[i, j] = transformation_matrix_inverse_ij(i, j, \u03bb)\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(\u03bb = [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] = \u03bb[1] / (\u03bb[2] - \u03bb[1])\n    s[3, 1] = \u03bb[1] / (\u03bb[3] - \u03bb[1]) * \u03bb[2] / (\u03bb[2] - \u03bb[1])\n    s[4, 1] = \u03bb[1] / (\u03bb[4] - \u03bb[1]) * \u03bb[2] / (\u03bb[2] - \u03bb[1]) * \u03bb[3] / (\u03bb[3] - \u03bb[1])\n    s[5, 1] =\n        \u03bb[1] / (\u03bb[5] - \u03bb[1]) * \u03bb[2] / (\u03bb[2] - \u03bb[1]) *\n        \u03bb[3] / (\u03bb[3] - \u03bb[1]) * \u03bb[4] / (\u03bb[4] - \u03bb[1])\n\n    s[2, 2] = 1\n    s[3, 2] = \u03bb[2] / (\u03bb[3] - \u03bb[2])\n    s[4, 2] = \u03bb[2] / (\u03bb[4] - \u03bb[2]) * \u03bb[3] / (\u03bb[3] - \u03bb[2])\n    s[5, 2] = \u03bb[2] / (\u03bb[5] - \u03bb[2]) * \u03bb[3] / (\u03bb[3] - \u03bb[2]) * \u03bb[4] / (\u03bb[4] - \u03bb[2])\n\n    s[3, 3] = 1\n    s[4, 3] = \u03bb[3] / (\u03bb[4] - \u03bb[3])\n    s[5, 3] = \u03bb[3] / (\u03bb[5] - \u03bb[3]) * \u03bb[4] / (\u03bb[4] - \u03bb[3])\n\n    s[4, 4] = 1\n    s[5, 4] = \u03bb[4] / (\u03bb[5] - \u03bb[4])\n\n    s[5, 5] = 1\n\n    return s\nend\n\n\n\nfunction transformation_matrix_inverse_5x5(\u03bb = [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] = \u03bb[1] / (\u03bb[1] - \u03bb[2])\n    s[3, 1] = \u03bb[1] / (\u03bb[1] - \u03bb[3]) * \u03bb[2] / (\u03bb[2] - \u03bb[3])\n    s[4, 1] = \u03bb[1] / (\u03bb[1] - \u03bb[4]) * \u03bb[2] / (\u03bb[2] - \u03bb[4]) * \u03bb[3] / (\u03bb[3] - \u03bb[4])\n    s[5, 1] =\n        \u03bb[1] / (\u03bb[1] - \u03bb[5]) * \u03bb[2] / (\u03bb[2] - \u03bb[5]) * \u03bb[3] / (\u03bb[3] - \u03bb[5]) *\n        \u03bb[4] / (\u03bb[4] - \u03bb[5])\n\n    s[2, 2] = 1\n    s[3, 2] = \u03bb[2] / (\u03bb[2] - \u03bb[3])\n    s[4, 2] = \u03bb[2] / (\u03bb[2] - \u03bb[4]) * \u03bb[3] / (\u03bb[3] - \u03bb[4])\n    s[5, 2] = \u03bb[2] / (\u03bb[2] - \u03bb[5]) * \u03bb[3] / (\u03bb[3] - \u03bb[5]) * \u03bb[4] / (\u03bb[4] - \u03bb[5])\n\n    s[3, 3] = 1\n    s[4, 3] = \u03bb[3] / (\u03bb[3] - \u03bb[4])\n    s[5, 3] = \u03bb[3] / (\u03bb[3] - \u03bb[5]) * \u03bb[4] / (\u03bb[4] - \u03bb[5])\n\n    s[4, 4] = 1\n    s[5, 4] = \u03bb[4] / (\u03bb[4] - \u03bb[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\u2260j) <= 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\u2260j) == 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\u2260j) == 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\u2260j) <= 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\u2260i) == y[i,v,r]) # (3)\n                @constraint(model, sum(x[j,i,v,r] for j in 1:n+1 if j\u2260i) == y[i,v,r]) # (3)\n                @constraint(model, sum(x[j,i,v,r] for j in 1:n+1 if j\u2260i) == sum(x[i,j,v,r] for j in 1:n+1 if j\u2260i)) # (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\u2260j) <= 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, \u03b2, \u03b3)\n\n    tspan = (0.0, 160.0)\n    u0 = [N-1.0, 1.0, 0.0]\n    p = [\u03b2, \u03b3]\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.:(\u2248)(a::Point{T}, b::Point{T}) where T\n    a.x \u2248 b.x && a.y \u2248 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": "module TestDiagrammaticPrograms\nusing Test\n\nusing Catlab.CategoricalAlgebra, Catlab.Programs.DiagrammaticPrograms\nusing Catlab.Programs.DiagrammaticPrograms: NamedGraph, MaybeNamedGraph\nusing Catlab.Graphs.BasicGraphs: TheoryGraph\n\n# Graphs\n########\n\npara_parsed = @graph begin\n  s\n  t\n  s \u2192 t\n  s \u2192 t\nend\npara = @acset MaybeNamedGraph{Symbol} begin\n  V = 2\n  E = 2\n  src = [1,1]\n  tgt = [2,2]\n  vname = [:s, :t]\n  ename = [nothing, nothing]\nend\n@test para_parsed == para\n\npara_parsed = @graph NamedGraph{Symbol} begin\n  x, y\n  (f, g): x \u2192 y\nend\npara = @acset NamedGraph{Symbol} begin\n  V = 2\n  E = 2\n  src = [1,1]\n  tgt = [2,2]\n  vname = [:x, :y]\n  ename = [:f, :g]\nend\n@test para_parsed == para\n\ntri_parsed = @graph NamedGraph{Symbol} begin\n  v0, v1, v2\n  fst: v0 \u2192 v1\n  snd: v1 \u2192 v2\n  comp: v0 \u2192 v2\nend\ntri = @acset NamedGraph{Symbol} begin\n  V = 3\n  E = 3\n  src = [1,2,1]\n  tgt = [2,3,3]\n  vname = [:v0, :v1, :v2]\n  ename = [:fst, :snd, :comp]\nend\n@test tri_parsed == tri\n\n# Categories\n############\n\n\u0394\u00b9_parsed = @category begin\n  V, E\n  (\u03b4\u2080, \u03b4\u2081): V \u2192 E\n  \u03c3\u2080: E \u2192 V\n\n  \u03c3\u2080 \u2218 \u03b4\u2080 == id(V)\n  \u03c3\u2080 \u2218 \u03b4\u2081 == id(V)\nend\n\u0394\u00b9_graph = @acset NamedGraph{Symbol} begin\n  V = 2\n  E = 3\n  src = [1,1,2]\n  tgt = [2,2,1]\n  vname = [:V, :E]\n  ename = [:\u03b4\u2080, :\u03b4\u2081, :\u03c3\u2080]\nend\n\u0394\u00b9 = FinCat(\u0394\u00b9_graph, [ [1,3] => empty(Path, \u0394\u00b9_graph, 1),\n                        [2,3] => empty(Path, \u0394\u00b9_graph, 1) ])\n@test \u0394\u00b9_parsed == \u0394\u00b9\n\n# Diagrams\n##########\n\nC = FinCat(TheoryGraph)\nF_parsed = @diagram C begin\n  v::V\n  (e1, e2)::E\n  t::tgt : e1 \u2192 v\n  s::src : e2 \u2192 v\nend\nJ = FinCat(@acset NamedGraph{Symbol} begin\n  V = 3\n  E = 2\n  src = [2,3]\n  tgt = [1,1]\n  vname = [:v, :e1, :e2]\n  ename = [:t, :s]\nend)\n@test dom(F_parsed) == J\nF = FinFunctor([:V,:E,:E], [:tgt, :src], J, C)\n@test F_parsed == F\n\nF_parsed = @diagram C begin\n  v => V\n  (e1, e2) => E\n  t: e1 \u2192 v => tgt\n  s: e2 \u2192 v => src\nend\n@test F_parsed == F\n\nend\n", "meta": {"hexsha": "31e765543290b500884bed9c0154c5b96d4ad700", "size": 1880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/programs/DiagrammaticPrograms.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": "test/programs/DiagrammaticPrograms.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": "test/programs/DiagrammaticPrograms.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": 16.9369369369, "max_line_length": 71, "alphanum_fraction": 0.5718085106, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273499, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7719620760437422}}
{"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(\"\u03c0\uff08\u8a08\u7b97\u5024\uff09 = \", DIGIT, ramanujan(n))\n    MyPrintf.myprintf(\"\u03c0\uff08\u53b3\u5bc6\u5024\uff09 = \", DIGIT, BigFloat(\u03c0))\n    @printf(\"n = %d, \u8a08\u7b97%d\u6841\u3067\u3001%d\u6841\u6c42\u307e\u308a\u307e\u3057\u305f\\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(\u03b1, \u03b2, 0.0, 10.0)\n```\nwould make a ScaledBeta type d which is bounded by 0.0 and 10.0. Note\n- (\u03b1,\u03b2) are usual parameters;\n- lb = lower bound;\n- ub = upper bound.\n\"\"\"\nstruct ScaledBeta<:ContinuousUnivariateDistribution\n    \u03b1::Float64\n    \u03b2::Float64\n    lb::Float64\n    ub::Float64\nend\n\nDistributions.rand(d::ScaledBeta) = d.lb + (d.ub-d.lb) * rand(Beta(d.\u03b1, d.\u03b2))\nDistributions.mean(d::ScaledBeta) = d.lb + (d.ub-d.lb) * ( d.\u03b1 / (d.\u03b1 + d.\u03b2) )\nDistributions.pdf(d::ScaledBeta, x::Real) = (d.lb \u2264 x \u2264 d.ub) ? pdf(Beta(d.\u03b1, d.\u03b2), (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 \u2264 x \u2264 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\u22651.0) + d.lb*(q\u22640.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 \u2264 ub) \"Lower bound must be \u2264 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": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    PlanePartition(normal; tol=1e-6)\n\nA method for partitioning spatial data into a family of hyperplanes defined\nby a `normal` direction. Two points `x` and `y` belong to the same\nhyperplane when `(x - y) \u22c5 normal < tol`.\n\"\"\"\nstruct PlanePartition{T,N} <: SPredicatePartitionMethod\n  normal::SVector{N,T}\n  tol::Float64\n\n  function PlanePartition{T,N}(normal, tol) where {N,T}\n    new(normalize(normal), tol)\n  end\nend\n\nPlanePartition(normal::SVector{N,T}; tol=1e-6) where {T,N} =\n  PlanePartition{T,N}(normal, tol)\n\nPlanePartition(normal::NTuple{N,T},; tol=1e-6) where {T,N} =\n  PlanePartition(SVector(normal), tol=tol)\n\n(p::PlanePartition)(x, y) = abs((x - y) \u22c5 p.normal) < p.tol\n", "meta": {"hexsha": "1e3430c175ac612e6a278593800162e91bf5891b", "size": 893, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/partitioning/plane.jl", "max_stars_repo_name": "mauro3/GeoStatsBase.jl", "max_stars_repo_head_hexsha": "98bd6c4c2f6ab4cbb228677329b95a6a3df3d95d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/partitioning/plane.jl", "max_issues_repo_name": "mauro3/GeoStatsBase.jl", "max_issues_repo_head_hexsha": "98bd6c4c2f6ab4cbb228677329b95a6a3df3d95d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/partitioning/plane.jl", "max_forks_repo_name": "mauro3/GeoStatsBase.jl", "max_forks_repo_head_hexsha": "98bd6c4c2f6ab4cbb228677329b95a6a3df3d95d", "max_forks_repo_licenses": ["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.8928571429, "max_line_length": 75, "alphanum_fraction": 0.5901455767, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.771955198133998}}
{"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": "using FinancePlus\nusing Test\n\n@testset \"FinancePlus.jl\" begin\n    # Write your tests here.\n    @test FinancePlus.simple_interest(100.00 , 0.1 ,2) == 20.0\n    @test FinancePlus.compound_interest(100.00 , 0.1 ,2) == 21.000000000000014\n    @test FinancePlus.future_value(100.00 , 0.1 ,2) == 121.00000000000001\n    @test FinancePlus.present_value(121.00000000000001 , 0.1 ,2) == 100.00\n    @test FinancePlus.future_value(100.00 , 0.1 ,2, 1) == 121.00000000000001\n    @test FinancePlus.future_value(100.00 , 0.1 ,2, 2) == 121.55062500000003\n    @test FinancePlus.present_value(121.00000000000001 , 0.1 ,2, 2) == 99.54699944981772\n    @test FinancePlus.present_value(121.00000000000001 , 0.1 ,2, 1) == 100.00\n    @test FinancePlus.present_annuity(50000.00 , 0.06 ,25) == 639167.8079134206\n    @test FinancePlus.present_annuity_due(50000.00 , 0.06 ,25) == 677517.8763882258\n    @test FinancePlus.present_value_interest_factor(0.05 ,5) == 0.7835261664684589\n    @test FinancePlus.future_value_interest_factor(0.05 ,5) == 1.2762815625000004\n    \n\nend\n", "meta": {"hexsha": "76ffaac4aedf26d9d5fd23868abd0b1ab33b1b66", "size": 1042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "hillelawaskar/FinancePlus.jl", "max_stars_repo_head_hexsha": "9f4ef075b4a627d416282da3baf454cd4d3a13c5", "max_stars_repo_licenses": ["MIT"], "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": "hillelawaskar/FinancePlus.jl", "max_issues_repo_head_hexsha": "9f4ef075b4a627d416282da3baf454cd4d3a13c5", "max_issues_repo_licenses": ["MIT"], "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": "hillelawaskar/FinancePlus.jl", "max_forks_repo_head_hexsha": "9f4ef075b4a627d416282da3baf454cd4d3a13c5", "max_forks_repo_licenses": ["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.619047619, "max_line_length": 88, "alphanum_fraction": 0.7178502879, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7719551868813561}}
{"text": "abstract type PrimeField <: Number end\n\ninfield(x::Number,y::Number) = x >= 0 && x < y\n\n\"Represents FieldElement type in which \ud835\udc5b \u2208 \ud835\udc39\ud835\udc5d and \ud835\udc5d \u2208 \u2119\"\nstruct FieldElement <: PrimeField\n    \ud835\udc5b::Integer\n    \ud835\udc5d::Integer\n    FieldElement(\ud835\udc5b,\ud835\udc5d) = !infield(\ud835\udc5b,\ud835\udc5d) ? throw(DomainError(\"\ud835\udc5b is not in field range\")) : new(\ud835\udc5b,\ud835\udc5d)\nend\n\n\"Formats PrimeField as \ud835\udc5b : \ud835\udc39\u209a\"\nfunction show(io::IO, z::PrimeField)\n    print(io, z.\ud835\udc5b, \" : \ud835\udc39\", z.\ud835\udc5d)\nend\n\n\"Returns true if both \ud835\udc5b and \ud835\udc5d are the same\"\n==(\ud835\udc4b\u2081::PrimeField,\ud835\udc4b\u2082::PrimeField) = \ud835\udc4b\u2081.\ud835\udc5d == \ud835\udc4b\u2082.\ud835\udc5d && \ud835\udc4b\u2081.\ud835\udc5b == \ud835\udc4b\u2082.\ud835\udc5b\n==(::PrimeField,::Integer) = false\n\n\n\"Adds two numbers of the same field\"\nfunction +(\ud835\udc4b\u2081::PrimeField,\ud835\udc4b\u2082::PrimeField)\n    if \ud835\udc4b\u2081.\ud835\udc5d != \ud835\udc4b\u2082.\ud835\udc5d\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        \ud835\udc5b = mod(\ud835\udc4b\u2081.\ud835\udc5b + \ud835\udc4b\u2082.\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d)\n        return typeof(\ud835\udc4b\u2081)(\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d)\n    end\nend\n\n\"Substracts two numbers of the same field\"\nfunction -(\ud835\udc4b\u2081::PrimeField,\ud835\udc4b\u2082::PrimeField)\n    if \ud835\udc4b\u2081.\ud835\udc5d != \ud835\udc4b\u2082.\ud835\udc5d\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        \ud835\udc5b = mod(\ud835\udc4b\u2081.\ud835\udc5b - \ud835\udc4b\u2082.\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d)\n        return typeof(\ud835\udc4b\u2081)(\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d)\n    end\nend\n\n\"Multiplies two numbers of the same field\"\nfunction *(\ud835\udc4b\u2081::PrimeField,\ud835\udc4b\u2082::PrimeField)\n    if \ud835\udc4b\u2081.\ud835\udc5d != \ud835\udc4b\u2082.\ud835\udc5d\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        \ud835\udc5b = mod(\ud835\udc4b\u2081.\ud835\udc5b * \ud835\udc4b\u2082.\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d)\n        return typeof(\ud835\udc4b\u2081)(\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d)\n    end\nend\n\n\"Multiplies a PrimeField by an Integer\"\nfunction *(\ud835\udc50::Integer,\ud835\udc4b::PrimeField)\n    \ud835\udc5b = mod(\ud835\udc50 * \ud835\udc4b.\ud835\udc5b, \ud835\udc4b.\ud835\udc5d)\n    return typeof(\ud835\udc4b)(\ud835\udc5b, \ud835\udc4b.\ud835\udc5d)\nend\n\n\"Returns \ud835\udc4b\u1d4f using Fermat's Little Theorem\"\nfunction ^(\ud835\udc4b::PrimeField,\ud835\udc58::Int)\n    \ud835\udc5b = powermod(\ud835\udc4b.\ud835\udc5b, mod(\ud835\udc58, (\ud835\udc4b.\ud835\udc5d - 1)), \ud835\udc4b.\ud835\udc5d)\n    return typeof(\ud835\udc4b)(\ud835\udc5b, \ud835\udc4b.\ud835\udc5d)\nend\n\n\"Returns 1/\ud835\udc4b as a special case of exponentiation where \ud835\udc58 = -1\"\nfunction inv(\ud835\udc4b::PrimeField)\n    \ud835\udc5b = powermod(\ud835\udc4b.\ud835\udc5b, mod(-1, (\ud835\udc4b.\ud835\udc5d - 1)), \ud835\udc4b.\ud835\udc5d)\n    return typeof(\ud835\udc4b)(\ud835\udc5b, \ud835\udc4b.\ud835\udc5d)\nend\n\nfunction div(\ud835\udc4b\u2081::PrimeField,\ud835\udc4b\u2082::PrimeField)\n    return \ud835\udc4b\u2081 / \ud835\udc4b\u2082\nend\n\n\"Returns \ud835\udc4b\u2081/\ud835\udc4b\u2082 using Fermat's Little Theorem\"\nfunction /(\ud835\udc4b\u2081::PrimeField,\ud835\udc4b\u2082::PrimeField)\n    if \ud835\udc4b\u2081.\ud835\udc5d != \ud835\udc4b\u2082.\ud835\udc5d\n        throw(DomainError(\"Cannot operate on two numbers in different Fields\"))\n    else\n        \ud835\udc5b = mod(\ud835\udc4b\u2081.\ud835\udc5b * powermod(\ud835\udc4b\u2082.\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d - 2, \ud835\udc4b\u2081.\ud835\udc5d), \ud835\udc4b\u2081.\ud835\udc5d)\n        return typeof(\ud835\udc4b\u2081)(\ud835\udc5b, \ud835\udc4b\u2081.\ud835\udc5d)\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": "using FEMfunctions\n\nusing LinearAlgebra\nusing SparseArrays\n\ninclude(\"twodElliptic.jl\")\n\nx,eConn,u = twodElliptic(129)\n\n\nfunction uExact(x)\n  C = 0.2/\u03c0^2\n  return C*sin(\u03c0*x[1])*sin(2*\u03c0*x[2])\nend\n\nnNodes = size(x,1)\nuEx = zeros(Float64,nNodes)\nfor i=1:nNodes\n  uEx[i] = uExact(x[i,:])\nend\n\nM = twodMassMatrix(x,eConn)\n\ndiff = u-uEx \n@test sqrt( dot(diff,(M*diff)) ) < 1e-8\n\n\n", "meta": {"hexsha": "44eed16d3eab4050cbe2a2e5274a2e15e8bbbb39", "size": 373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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/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/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": 13.3214285714, "max_line_length": 39, "alphanum_fraction": 0.6675603217, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7719349046737372}}
{"text": "using IntervalArithmetic\nusing Test\n\nusing LinearAlgebra\n\n@testset \"Complex interval operations\" begin\n    a = @interval 1im\n    b = @interval 4im + 3\n    c = (@interval -1 4) + (@interval 0 2)*im\n\n    @test typeof(a) == Complex{IntervalArithmetic.Interval{Float64}}\n    @test a ==  Interval(0) + Interval(1)*im\n    @test a * a == Interval(-1)\n    @test a + a == Interval(2)*im\n    @test a - a == 0\n    @test a / a == 1\n\n    @test 3+2im \u2208 c\n    @test a \u222a b == (@interval 0 3) + (@interval 1 4)*im\n    @test c \u2229 (a \u222a b) == (@interval 0 3) + (@interval 1 2)*im\n    @test a \u2229 b == \u2205 + \u2205*im\n    @test isdisjoint(a,b) == true\nend\n\n@testset \"Complex functions\" begin\n    Z = (3 \u00b1 1e-7) + (4 \u00b1 1e-7)*im\n    @test sin(Z) == complex(sin(real(Z)) * cosh(imag(Z)), sinh(imag(Z)) * cos(real(Z)))\n    @test exp(-im * Interval(\u03c0)) == Interval(-1.0, -0.9999999999999999) - Interval(1.224646799147353e-16, 1.2246467991473532e-16)*im\n\n    sZ = sqrt(Z)\n    @test sZ == Interval(1.99999996999999951619,2.00000003000000070585) + Interval(0.99999996999999984926,1.00000003000000048381)*im\n    @test sqrt(-Z) == imag(sZ) - real(sZ)*im\n\n    @test sqrt((@interval -1 0) + (@interval 0)*im) .== (@interval 0 1)*im\n    @test sqrt((@interval -1 1) + (@interval 0)*im) .== (@interval 0 1) + (@interval 0 1)*im\n    @test sqrt((@interval -9//32 Inf)*im + (@interval 0)) .== (@interval 0 Inf) + (@interval -3//8 Inf)*im\nend\n\n\n@testset \"Complex powers\" begin\n    x = (3..3) + 4im\n    @test x^2 == -7 + 24im\n    @test sqrt(x) \u2286 x^0.5\n    @test x^-2 == inv(x)^2\n\n    a = -3.1\n    @test x \u2286 (x^a)^(1/a)\nend\n\n@testset \"abs2 and abs\" begin\n    x = (0..3) + (0..4)*im\n    @test abs2(x) == 0..25\n    @test abs(x) == norm(x) == 0..5\n\n    y = (-1..1) + (-2..2)*im\n    @test abs(y).lo == 0.0\n    @test abs2(y).lo == 0.0\nend\n", "meta": {"hexsha": "ad0b744ee0cb663e538e6cf3b0b2711f339faa7d", "size": 1782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interval_tests/complex.jl", "max_stars_repo_name": "bocc/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "aa781cc5b2d23138d1141519dd652c5e522d5a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-20T04:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T04:02:34.000Z", "max_issues_repo_path": "test/interval_tests/complex.jl", "max_issues_repo_name": "bocc/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "aa781cc5b2d23138d1141519dd652c5e522d5a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-28T23:57:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T23:57:24.000Z", "max_forks_repo_path": "test/interval_tests/complex.jl", "max_forks_repo_name": "bocc/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "aa781cc5b2d23138d1141519dd652c5e522d5a6e", "max_forks_repo_licenses": ["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.2033898305, "max_line_length": 132, "alphanum_fraction": 0.5611672278, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7719313484655655}}
{"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 \u2248 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": "using SparseGrids\nusing Base.Test\n\n# Moments of exp(-x^2)\nfunction gaussmoment(m::Int)\n\t@assert m >= 0\n\n\tif isodd(m)\n\t\treturn 0.0\n\telseif iseven(m)\n\t\tm2 = div(m,2)\n\t\treturn prod( 1:2:m-1 ) * sqrt(pi) / 2^m2\n\tend\nend\n\n# Moments of exp(-|x|^2)\nfunction gaussmoment( P::Vector{Int} )\n\tI = 1.0\n\tfor d = 1:length(P)\n\t\tI *= gaussmoment(P[d])\n\tend\n\n\treturn I \nend\n\n# Like gaussmoment, but with quadrature rule\nfunction gaussquad( P::Vector, nodes::Matrix, weights::Vector )\n\t# Evaluate integrand\n\tF = broadcast( ^, nodes, P )\n\tI = vec(prod(F,1))\n\n\t# Evaluate quadrature sum\n\tQ = dot( I, weights )\n\n\treturn Q\nend\n\n\n# ------------------------------------------------------------\n# Test quadrature for various dimensions and orders\n# Note: It is not interesting to test uneven moments for Gauss-Hermite\n\n# Dimension and order\nD = 3\norder = 4\n\n# Moments to test\nvecs = Vector{Vector{Int}}(D)\nfor d in 1:D\n\tvecs[d] = [0:order;]\nend\nP = combvec( vecs )\n\nM = size(P, 2)\n\nfor generator = [FastGaussQuadrature.gausshermite, kpn]\n\t# Quadrature points and weights\n\tN, W = sparsegrid( D, order, generator )\n\n\t# Maximum degree for which the generator gives correct results\n\tgenerator == FastGaussQuadrature.gausshermite ?  max_degree = 2*order-1 : max_degree = D*order\n\n\tfor m = 1:M\n\t\t# Test if all moments are even\n\t\tcurP = P[:,m]\n\n\t\tif all(map(iseven, curP))\n\t\t\tI = gaussmoment(curP) \n\t\t\tQ = gaussquad(curP, N, W)\n\n\t\t\t# Expected test result depends on the total degree\n\t\t\tif sum(curP) <= max_degree\n\t\t\t\t@test_approx_eq I Q\n\t\t\telse\n\t\t\t\t@test abs(I - Q) > 1e-3\n\t\t\tend\n\t\tend\n\tend\nend\n\n", "meta": {"hexsha": "26785d49d10c1d9344f29ac01109729a95b6e555", "size": 1564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/quadtest.jl", "max_stars_repo_name": "JuliaPackageMirrors/SparseGrids.jl", "max_stars_repo_head_hexsha": "070de99be0a654f5ce3877d548de11bcf87e4619", "max_stars_repo_licenses": ["MIT"], "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/quadtest.jl", "max_issues_repo_name": "JuliaPackageMirrors/SparseGrids.jl", "max_issues_repo_head_hexsha": "070de99be0a654f5ce3877d548de11bcf87e4619", "max_issues_repo_licenses": ["MIT"], "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/quadtest.jl", "max_forks_repo_name": "JuliaPackageMirrors/SparseGrids.jl", "max_forks_repo_head_hexsha": "070de99be0a654f5ce3877d548de11bcf87e4619", "max_forks_repo_licenses": ["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.3086419753, "max_line_length": 95, "alphanum_fraction": 0.6425831202, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365572, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7719313315942237}}
{"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# \u2554\u2550\u2561 d2e14b19-98d7-4fba-8bd9-bbbb47e002f6\nbegin\n\tbigbreak = HTML(\"<br>\"^4);\n\tusing PlutoUI\n\tusing Test\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fd2ee11d-1734-457b-b587-4128b474b772\n@bind N PlutoUI.Slider(1:20, show_value = true)\n\n# \u2554\u2550\u2561 7b619e85-abb8-4115-a9df-b5fedd04a8e4\nmd\"N = $N\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5732d2dc-c411-4c56-9720-ce6d979fc60f\nx = 10\n\n# \u2554\u2550\u2561 d993ffa0-c613-4b4b-baeb-a223ce408217\ny = 30\n\n# \u2554\u2550\u2561 782a5034-9184-4a55-b877-bd0bb4e4aebb\nmd\"Using the if and else keywords, we might write:\n\"\n\n# \u2554\u2550\u2561 14d69119-9a68-428b-a857-56298b42aee5\nif x > y\n    x\nelse\n    y\nend\n\n# \u2554\u2550\u2561 46533172-0fe1-406b-a52d-23305282d43b\nmd\"and as a ternary operator, the conditional looks like this:\"\n\n# \u2554\u2550\u2561 b13c9cc4-3c4e-4416-896f-d5cbdc2d51c0\n(x > y) ? x : y\n\n# \u2554\u2550\u2561 8b81523f-79dc-46ba-8e4e-5dbc19d5d434\ntrue ? 5 : 2 * 6\n\n# \u2554\u2550\u2561 7925dfa8-63b1-4fc2-beae-922fa93aa081\n( false  ?  1  : 2 )\n\n# \u2554\u2550\u2561 fdfb1f2e-6105-43dd-92cf-4b78e1db8e73\nbigbreak\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 75efd803-be55-4d0f-b8c8-6b63dd90d68c\nmd\"\"\"M = $(@bind M PlutoUI.Slider(-100:100, show_value = true)) \"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 602b3c77-e46e-4592-a787-4aeed77eb059\nbigbreak\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 283c45af-47a3-4446-b873-205d8aa568e7\nmd\"\"\"\n**Alice:** _Is the number $M even?_\n \n**Bob:**   _I don't know._\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500d2e14b19-98d7-4fba-8bd9-bbbb47e002f6\n# \u255f\u2500ce3c8fde-802a-11ec-1b1a-31be58ae3474\n# \u255f\u2500fd2ee11d-1734-457b-b587-4128b474b772\n# \u255f\u25007b619e85-abb8-4115-a9df-b5fedd04a8e4\n# \u2560\u2550da9796ce-4572-4d2d-bb96-5949f52d46d0\n# \u255f\u2500aca5d158-2902-4b7a-bf50-6f7a722f5ea7\n# \u255f\u25008a3c8101-0c2a-438f-ba58-b80e9b14bc10\n# \u2560\u25505732d2dc-c411-4c56-9720-ce6d979fc60f\n# \u2560\u2550d993ffa0-c613-4b4b-baeb-a223ce408217\n# \u255f\u2500782a5034-9184-4a55-b877-bd0bb4e4aebb\n# \u2560\u255014d69119-9a68-428b-a857-56298b42aee5\n# \u255f\u250046533172-0fe1-406b-a52d-23305282d43b\n# \u2560\u2550b13c9cc4-3c4e-4416-896f-d5cbdc2d51c0\n# \u2560\u25508b81523f-79dc-46ba-8e4e-5dbc19d5d434\n# \u2560\u25507925dfa8-63b1-4fc2-beae-922fa93aa081\n# \u255f\u2500fdfb1f2e-6105-43dd-92cf-4b78e1db8e73\n# \u255f\u250061aa9056-ebfe-4c06-a752-d081ece68167\n# \u255f\u250075efd803-be55-4d0f-b8c8-6b63dd90d68c\n# \u2560\u25508f1298ab-309f-4d4d-8165-4ee522f3b1c8\n# \u255f\u2500602b3c77-e46e-4592-a787-4aeed77eb059\n# \u255f\u2500c7c1ec65-49ed-4ae9-b9a9-0d82a346af81\n# \u2560\u2550283c45af-47a3-4446-b873-205d8aa568e7\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "using Printf\n# ARRAYS ARE INDEXED FROM ONE NOT ZERO IN JULIA!!!!\n\n## I wrote this for displaying arrays, but we don't actually need it. println() works just fine!\n#\n#function display_array(some_array)\n#    for x in some_array\n#        print(x, \" \")\n#    end\n#    println()\n#end\n\nfunction array_examples()\n    println(\"--------------------------------------\")\n    println(\"Array examples\")\n    \n    println()\n    \n    println(\"We can create one-dimensional arrays of zeros\")\n    one_dimensional_array = zeros(Int32, 5)\n    println(one_dimensional_array)\n\n    println(\"We can create two-dimensional arrays of zeros\")\n    two_dimensional_array = zeros(Int32, 5, 2)\n    println(two_dimensional_array)\n\n    println(\"We can create arrays where we specify the type, the size, and the initial value (in this case undefined)\")\n    undefined_array = Array{Int32}(undef, 5)\n    println(undefined_array)\n\n    println(\"We can create a int array and set initial values\")\n    int_array = Int32[1,2,3,4]\n    println(int_array)\n    \n    println(\"We can get individual values. REMEMBER JULIA INDEXED FROM ONE NOT ZERO!\")\n    println(int_array[2]) # The second element really is the second element (not the third as would be the case with zero-indexing)\n\n    println(\"We can create a float array and set initial values\")\n    float_array = Float64[1,2,3,4]\n    println(float_array)\n    \n    println(\"We can create an array where each element is off a different type\")\n    array_of_different_types = [99, 3.1415, \"foo\", true, 'x']\n    println(array_of_different_types)\n\n    println(\"We can create an array from a range (2 to 10, stepping at intervals of 2\")\n    even_number_array = collect(2:2:10)\n    println(even_number_array)\n    \n    println(\"We can create an array using comprehension\")\n    square_numbers = [n^2 for n in 1:5]\n    println(square_numbers)\n\n    println(\"We can also create multi-dimensional arrays using comprehension\")\n    another_multi_dim_array = [n * m for n in 1:5, m in 1:5]\n    println(another_multi_dim_array)\n\n    println(\"We can get a specific (one-indexed) element from the array\")\n    println(array_of_different_types[1])\n    \n    println(\"We can get the last element from the array\")\n    println(array_of_different_types[end])\n    \n    println(\"We can get a range, in this case items 2-4\")\n    println(array_of_different_types[2:4])\n    \n    println(\"We can check if an item, e.g. 3.1415 exists in the array\")\n    println(3.1415 in array_of_different_types)\n    \n    println(\"We can find a specific item in the array, e.g. 'x'\")\n    println(findfirst(isequal('x'), array_of_different_types))\n    \n    int_array = [1,2,3,4,5,6,7,8,10]\n    println(\"We can find all the even numbers in an array using a generic function and findall\")    \n    f(a) = mod(a, 2) == 0 ? true : false\n    println(findall(f, int_array))\n    \n    println(\"We can get the number of items that pass the test\")\n    println(count(f, int_array))\n \n    println(\"We can get the row and column size of our 5x2 array we created earlier\")\n    println(size(two_dimensional_array))\n \n    println(\"We can get the length of an array\")\n    println(length(int_array))\n    \n    println(\"We can get the sum of all the values in the array\")\n    println(sum(int_array))\n    \n    println(\"We can insert items at index 2 (second number after colon seems to specify range in target array to overwrite. increase this number to see old items in array go missing!)\")\n    splice!(int_array, 2:1, [100,200,300,400,500])\n    println(int_array)\n    \n    println(\"We can remove items at index 2 to 6\")\n    splice!(int_array, 2:6)\n    println(int_array)\n    \n    println(\"We get the maximum value in the array\")\n    println(maximum(int_array))\n    \n    println(\"We get the minimum value in the array\")\n    println(minimum(int_array))\n\n    println(\"We can perform calculations on an array without looping\")\n    println(int_array * 2)\n \n    println(\"We can store functions in an array\")\n    function_array = [sin, cos, tan]\n    println(function_array)\n    \n    for n in function_array\n        println(n(45))\n    end    \n \n    two_dimensional_int_array = [1 2 3 4; 5 6 7 8; 9 10 11 12]\n    for row = 1:3, col = 1:4\n        @printf(\"row %d, col %d = %d\\n\", row, col, two_dimensional_int_array[row,col])\n    end\n    println()\n    \n    println(\"We can print just the items from column 2\")\n    println(two_dimensional_int_array[:, 2])\n\n    println(\"We can push items to the end of an array\")    \n    push!(int_array, 999)\n    println(int_array)    \nend\n\n", "meta": {"hexsha": "5e89a0678a818ac014c6fc9232a7fd53f04ff37b", "size": 4500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arrays.jl", "max_stars_repo_name": "James-P-D/JuliaDump", "max_stars_repo_head_hexsha": "6be0a591aa6372709c1b990b9657a3fa9113591a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/arrays.jl", "max_issues_repo_name": "James-P-D/JuliaDump", "max_issues_repo_head_hexsha": "6be0a591aa6372709c1b990b9657a3fa9113591a", "max_issues_repo_licenses": ["MIT"], "max_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": "James-P-D/JuliaDump", "max_forks_repo_head_hexsha": "6be0a591aa6372709c1b990b9657a3fa9113591a", "max_forks_repo_licenses": ["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.8837209302, "max_line_length": 185, "alphanum_fraction": 0.6744444444, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.867035752930664, "lm_q1q2_score": 0.7719169297230809}}
{"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 .*= \u221a(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)/\u221a(2\u03c0), -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": "#HW2 Problem 2\n#Minhao Yan my497, Wentong Chen wc422\n#1. Generate array of random numbers named x\nx = rand(Float64, (20000,20000))\n\n#2. Column by Column\nexp_column = zeros((20000,20000))\nfunction exp_cols(x)\n    for i in 1:20000\n        exp_column[:,i] = exp.(x[:,i])\n    end\n    return exp_column\nend\n\n#3. Row by Row\nexp_row = zeros((20000,20000))\nfunction exp_rows(x)\n    for i in 1:20000\n        exp_row[i,:] = exp.(x[i,:])\n    end\n    return exp_row\nend\n\n#4.Calculate time\n@time exp_cols(x)\n#23.460586 seconds (523.19 k allocations: 5.984 GiB, 4.02% gc time)\n@time exp_rows(x)\n#320.930191 seconds (273.41 k allocations: 5.970 GiB, 0.56% gc time)\n\n#5. The columnn by column one is much faster.\n\n#6. Exponentiate the full array\n@time exp_full = exp.(x)\n#55.045882 seconds (314.79 k allocations: 2.996 GiB, 0.01% gc time)\n#Overall, the column by column method is the fastest, then the overall one,\n#the slowest is the row by row method.\n", "meta": {"hexsha": "d51ada38f15193e564e6664bba224bfa4ef5046b", "size": 938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problem2.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": "Problem2.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": "Problem2.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": 25.3513513514, "max_line_length": 75, "alphanum_fraction": 0.6876332623, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.7719169191686941}}
{"text": "using SparseArrays, DiffEqOperators, LinearAlgebra, Random,\n      Test, BandedMatrices, FillArrays\n\nfunction second_derivative_stencil(N)\n  A = zeros(N,N+2)\n  A[1,1:5] = [0.916667,   -1.66667,    0.5,   0.333333,  -0.0833333]\n  A[2,1:5] = [-0.0833333,   1.33333,   -2.5,   1.33333,   -0.0833333]\n  A[3,1:5] = [-0.0833333,   0.333333,   0.5,  -1.66667,    0.916667]\n  A[4,1:5] = [0.916667,   -4.66667,    9.5,  -8.66667,    2.91667]\n  for i in 5:N-4, j in 5:N-2\n      (j-i==0 || j-i==2) && (A[i,j]=1)\n      j-i==1 && (A[i,j]=-2)\n  end\n  A[end,end-4:end] = reverse(A[1,1:5])\n  A[end-1,end-4:end] = reverse(A[2,1:5])\n  A[end-2,end-4:end] = reverse(A[3,1:5])\n  A[end-3,end-4:end] = reverse(A[4,1:5])\n\n  return A\nend\n\n# Analytic solutions to higher order operators.\n# Do not modify unless you are completely certain of the changes.\nfunction fourth_deriv_approx_stencil(N)\n    A = zeros(N,N+2)\n    A[1,1:8] = [3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3]\n    A[2,1:8] = [2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6]\n    A[N-1,N-5:end] = reverse([2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6], dims=2)\n    A[N,N-5:end] = reverse([3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3], dims=2)\n    for i in 3:N-2\n        A[i,i-2:i+4] = [-1/6 2.0 -13/2 28/3 -13/2 2.0 -1/6]\n    end\n    return A\nend\n\nfunction second_deriv_fourth_approx_stencil(N)\n    A = zeros(N,N+2)\n    A[1,1:6] = [5/6 -1.25 -1/3 7/6 -0.5 5/60]\n    A[N,N-3:end] = reverse([5/6 -1.25 -1/3 7/6 -0.5 5/60], dims=2)\n    for i in 2:N-1\n        A[i,i-1:i+3] = [-1/12 4/3 -5/2 4/3 -1/12]\n    end\n    return A\nend\n\nfunction convert_by_multiplication(::Type{Array}, A::AbstractDerivativeOperator{T}, N::Int=A.dimension) where T\n    @assert N >= A.stencil_length # stencil must be able to fit in the matrix\n    mat = zeros(T, (N, N+2))\n    v = zeros(T, N+2)\n    for i=1:N+2\n        v[i] = one(T)\n        #=\n            calculating the effect on a unit vector to get the matrix of transformation\n            to get the vector in the new vector space.\n        =#\n        mul!(view(mat,:,i), A, v)\n        v[i] = zero(T)\n    end\n    return mat\nend\n\n# Tests the corrrectness of stencils, along with concretization.\n# Do not modify the following test-set unless you are completely certain of your changes.\n@testset \"Correctness of Stencils\" begin\n    N = 20\n    L1 = UpwindDifference(1,2, 1.0, N, t->1.0)\n    correct = [-3/2, 2.0, -1/2]\n    @test L1.stencil_coefs \u2248 correct\n\n    L1 = UpwindDifference(1,3, 1.0, N, t->1.0)\n    correct = [-2/6, -3/6, 6/6, -1/6]\n    @test L1.stencil_coefs \u2248 correct\nend\n\n@testset \"Taking derivatives\" begin\n    N = 20\n    x = 0:1/(N-1):1\n    y = 2x.^2 .- 3x .+2\n    y_ = y[2:end-1]\n    dx = x[2] - x[1]\n    # y = x.^2\n\n    # Dirichlet BC with fixed end points\n    Q = RobinBC((1.0, 0.0, y[1]), (1.0, 0.0, y[end]), 1.0)\n    U = UpwindDifference(1,2, dx, N-2, t->1.0)\n    A = CenteredDifference(1,2, dx, N-2)\n    D1 = CenteredDifference(1,2, dx, N-4) # For testing whether the array is constant\n\n    res1 = U*Q*y_\n    res2 = A*Q*y_\n\n    @test res1[3:end-2] \u2248 res2[1:end-4] # shifted due to upwind operators\n    # It is shifted by a constant value so its first derivative has to be 0\n    @test D1*(res1[3:end-2] - res2[3:end-2]) \u2248 zeros(12) atol=10.0^(-6)\n\n    # @test res3[3:end-2] \u2248 res4[1:end-4] # shifted due to upwind operators\n    # It is shifted by a constant value so its first derivative has to be 0\n    # @test D1*(res4[3:end-2] - res4[3:end-2]) \u2248 zeros(12) atol=10.0^(-6)\n\n\n    y = 3x.^3 .- 4x.^2 .+ 2x .+ 1\n    y_ = y[2:end-1]\n    Q = RobinBC((1.0, 0.0, y[1]), (1.0, 0.0, y[end]), 1.0)\n    U = UpwindDifference(2,2, 1.0, N-2, t->1.0)\n    A = CenteredDifference(2,2, 1.0, N-2)\n    res1 = U*Q*y_\n    res2 = A*Q*y_\n\n    @test res1 \u2248 res2 # shifted due to upwind operators\nend\n\n@testset \"Full and Sparse functions:\" begin\n    N = 10\n    d_order = 2\n    approx_order = 2\n    correct = second_derivative_stencil(N)\n    A = UpwindDifference(d_order,approx_order,1.0,N,t->1.0)\n\n    @test convert_by_multiplication(Array,A,N) \u2248 correct atol=10.0^(-4)\n    @test Array(A) \u2248 second_derivative_stencil(N) atol=10.0^(-4)\n    @test sparse(A) \u2248 second_derivative_stencil(N) atol=10.0^(-4)\n    @test BandedMatrix(A) \u2248 second_derivative_stencil(N) atol=10.0^(-4)\n    @test_broken opnorm(A, Inf) \u2248 opnorm(correct, Inf) atol=10.0^(-4)\n\n    # testing higher derivative and approximation concretization\n    N = 20\n    d_order = 4\n    approx_order = 4\n    A = UpwindDifference(d_order,approx_order,1.0,N,t->1.0)\n    correct = convert_by_multiplication(Array,A,N)\n\n    @test Array(A) \u2248 correct\n    @test sparse(A) \u2248 correct\n    @test BandedMatrix(A) \u2248 correct\n\n    N = 100\n    d_order = 8\n    approx_order = 8\n    A = UpwindDifference(d_order,approx_order,1.0,N,t->1.0)\n    correct = convert_by_multiplication(Array,A,N)\n\n    @test Array(A) \u2248 correct\n    @test sparse(A) \u2248 correct\n    @test BandedMatrix(A) \u2248 correct\n\n    # testing correctness of multiplication\n    N = 1000\n    d_order = 4\n    approx_order = 10\n    y = collect(1:1.0:N+2).^4 - 2*collect(1:1.0:N+2).^3 + collect(1:1.0:N+2).^2;\n    y = convert(Array{BigFloat, 1}, y)\n\n    A = UpwindDifference(d_order,approx_order,one(BigFloat),N,t->1.0)\n    correct = convert_by_multiplication(Array,A,N)\n    @test Array(A) \u2248 correct\n    @test sparse(correct) \u2248 correct\n    @test BandedMatrix(A) \u2248 correct\n    @test A*y \u2248 Array(A)*y\nend\n\n@testset \"Indexing tests\" begin\n    N = 1000\n    d_order = 4\n    approx_order = 10\n\n    A = UpwindDifference(d_order,approx_order,1.0,N,t->1.0)\n    @test A[1,1] == Array(A)[1,1]\n    @test A[10,20] == 0.0\n\n    correct = Array(A)\n    for i in 1:N\n        @test A[i,i] \u2248 correct[i,i] atol=10^-9\n    end\n\n    # Indexing Tests\n    N = 1000\n    d_order = 2\n    approx_order = 2\n\n    A = UpwindDifference(d_order,approx_order,1.0,N,t->1.0)\n    M = Array(A,N)\n    @test A[1,1] == M[1,1]\n    @test A[1:4,1] == M[1:4,1]\n    @test A[5,2:10] == M[5,2:10]\n    @test A[60:100,500:600] == M[60:100,500:600]\n\n    d_order = 4\n    approx_order = 10\n\n    A = UpwindDifference(d_order,approx_order,1.0,N,t->1.0)\n    M = Array(A,N)\n    @test A[1,1] == M[1,1]\n    @test A[1:4,1] == M[1:4,1]\n    @test A[5,2:10] == M[5,2:10]\n    @test A[524,:] == M[524,:]\n    @test A[60:100,500:600] == M[60:100,500:600]\nend\n\n@testset begin \"Operations on matrices\"\n    N = 51\n    M = 101\n    d_order = 2\n    approx_order = 2\n\n    xarr = range(0,stop=1,length=N)\n    yarr = range(0,stop=1,length=M)\n    dx = xarr[2]-xarr[1]\n    dy = yarr[2]-yarr[1]\n    F = [x^2+y for x = xarr, y = yarr]\n\n    A = UpwindDifference(d_order,approx_order,dx,length(xarr)-2,t->1.0)\n    B = UpwindDifference(d_order,approx_order,dy,length(yarr),t->1.0)\n\n    @test A*F \u2248 2*ones(N-2,M)\n    F*B\n    # A*F*B\n\n    G = [x^2+y^2 for x = xarr, y = yarr]\n\n    @test A*G \u2248 2*ones(N-2,M) atol=1e-2\n    G*B\n    # A*G*B\nend\n", "meta": {"hexsha": "7f01d1e233eaea6c3cc7ea9c6de9110f04b9d2e3", "size": 6773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/upwind_operators_interface.jl", "max_stars_repo_name": "jw3126/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "e53af6db6b6fbbb77f5894a2cb53df12c7369978", "max_stars_repo_licenses": ["MIT"], "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/upwind_operators_interface.jl", "max_issues_repo_name": "jw3126/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "e53af6db6b6fbbb77f5894a2cb53df12c7369978", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:11:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T14:11:05.000Z", "max_forks_repo_path": "test/upwind_operators_interface.jl", "max_forks_repo_name": "jw3126/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "e53af6db6b6fbbb77f5894a2cb53df12c7369978", "max_forks_repo_licenses": ["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.2366071429, "max_line_length": 111, "alphanum_fraction": 0.5849697328, "num_tokens": 2803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7719116903254464}}
{"text": "using RowEchelon\nusing Test\n\nAs = Vector{Matrix{Int}}()\nRs = Vector{Matrix{Int}}()\nPs = Vector{Vector{Int}}()\n# Issue #518 of Julia Base\npush!(As, [ 1  2  0   3;\n            2  4  0   7])\npush!(Rs, [ 1  2  0   0;\n            0  0  0   1])\npush!(Ps, [ 1; 4])\n# Example from Wikipedia\npush!(As, [ 1  3  -1;\n            0  1   7])\npush!(Rs, [ 1  0 -22;\n            0  1   7])\npush!(Ps, [ 1; 2])\n# Example from Wikibooks\npush!(As, [ 0  3 -6   6  4  -5;\n            3 -7  8  -5  8   9;\n            3 -9 12  -9  6  15])\npush!(Rs, [ 1  0 -2   3  0 -24;\n            0  1 -2   2  0  -7;\n            0  0  0   0  1   4])\npush!(Ps, [ 1; 2; 5])\n# Example from Rosetta Code\npush!(As, [ 1  2 -1  -4;\n            2  3 -1 -11;\n           -2  0 -3  22])\npush!(Rs, [ 1  0  0  -8;\n            0  1  0   1;\n            0  0  1  -2])\npush!(Ps, [ 1; 2; 3])\n# Magic Square\npush!(As, [16  2  3  13;\n            5 11 10   8;\n            9  7  6  12;\n            4 14 15   1])\npush!(Rs, [ 1  0  0   1;\n            0  1  0   3;\n            0  0  1  -3;\n            0  0  0   0])\npush!(Ps, [ 1; 2; 3])\n\n@testset \"Matrices of integers (treated as Float64)\" begin\n    for (A,R) in zip(As,Rs)\n        C = rref(A)\n        @test C isa Matrix{Float64}\n        @test C \u2248 R\n    end\nend\n\n@testset \"Matrices of rationals\" begin\n    for (A,R) in zip(As,Rs)\n        B = Matrix{Rational{Int}}(A)\n        C = rref(B)\n        @test C isa Matrix{Rational{Int}}\n        @test C == R\n    end\nend\n\n@testset \"Matrix of Complex numbers\" begin\n    A = [1+ im 1-im  4;\n         3+2im 2-im  2]\n    R = [1     0    -2- im;\n         0     1     1+4im]\n    for conv in [false, true]\n        if conv\n            A = Matrix{ComplexF64}(A)\n        end\n        C = rref(A)\n        @test C isa Matrix{ComplexF64}\n        @test C \u2248 R\n    end\nend\n\n@testset \"Matrices of integers (treated as Float64) with Pivots\" begin\n    for (A,X) in zip(As, zip(Rs,Ps))\n        R=X[1]\n        P=X[2]\n        C = rref_with_pivots(A)\n        @test C[1] isa Matrix{Float64}\n        @test C[1] \u2248 R\n        @test C[2] == P\n    end\nend\n\n@testset \"Matrices of rationals with Pivots\" begin\n    for (A,X) in zip(As, zip(Rs,Ps))\n        R=X[1]\n        P=X[2]\n        B = Matrix{Rational{Int}}(A)\n        C = rref_with_pivots(B)\n        @test C[1] isa Matrix{Rational{Int}}\n        @test C[1] == R\n        @test C[2] == P\n    end\nend\n\n@testset \"Matrix of Complex numbers with Pivots\" begin\n    A = [1+ im 1-im  4;\n         3+2im 2-im  2]\n    R = [1     0    -2- im;\n         0     1     1+4im]\n    for conv in [false, true]\n        if conv\n            A = Matrix{ComplexF64}(A)\n        end\n        C = rref_with_pivots(A)\n        @test C[1] isa Matrix{ComplexF64}\n        @test C[1] \u2248 R\n        @test C[2] == [1; 2]\n    end\nend\n", "meta": {"hexsha": "6f321b6f84f8344cffdee94c5af0c6aa68967c03", "size": 2741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "stevengj/RowEchelon.jl", "max_stars_repo_head_hexsha": "3ce894af5b5db7a279bda3ed1b1c9665397abca3", "max_stars_repo_licenses": ["MIT"], "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": "stevengj/RowEchelon.jl", "max_issues_repo_head_hexsha": "3ce894af5b5db7a279bda3ed1b1c9665397abca3", "max_issues_repo_licenses": ["MIT"], "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": "stevengj/RowEchelon.jl", "max_forks_repo_head_hexsha": "3ce894af5b5db7a279bda3ed1b1c9665397abca3", "max_forks_repo_licenses": ["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.6293103448, "max_line_length": 70, "alphanum_fraction": 0.4483765049, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7719116816268223}}
{"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": "using RobustAndOptimalControl, ControlSystems\n\n# example 19.1\nA = [\n    -1 0 4\n    0 2 0\n    0 0 -3\n]\nB1 = [\n    0 0\n    1 0\n    0 0\n]\nC1 = B1'\nB2 = [\n    1\n    1\n    1\n]\nC2 = B2'\nD11 = 0I(2)\nD12 = [\n    0\n    1\n]\nD21 = D12'\nD22 = 0I(1)\n\nP = ExtendedStateSpace(A, B1, B2, C1, C2, D11, D12, D21, D22)\nfor \u03b3 \u2208 (nothing, 1000)\n    K, Cl = h2synthesize(P, \u03b3) # the example uses h2syn\n    @test norm(Cl) \u2248 8.9582 rtol = 1e-3\n\n    K_ML = let\n        A = [-1.0 -4.236148004700622 4.0; -4.23607198996497 -6.472215758593602 -4.23607198996497; 0.0 -4.236148004700622 -3.0]\n        B = [0.0; 4.23607198996497; 0.0]\n        C = [0.0 -4.236148004700622 0.0]\n        D = [0.0]\n        sys = ss(A,B,C,D)\n    end\n    @test K \u2248 K_ML rtol=1e-3\n\n\n\n    Cl_ML = let\n        A = [-1.0 0.0 4.0 0.0 -4.236148004700622 0.0; 0.0 2.0 0.0 0.0 -4.236148004700622 0.0; 0.0 0.0 -3.0 0.0 -4.236148004700622 0.0; 0.0 0.0 0.0 -1.0 -4.236148004700622 4.0; 4.23607198996497 4.23607198996497 4.23607198996497 -4.23607198996497 -6.472215758593602 -4.23607198996497; 0.0 0.0 0.0 0.0 -4.236148004700622 -3.0]\n        B = [0.0 0.0; 1.0 0.0; 0.0 0.0; 0.0 0.0; 0.0 4.23607198996497; 0.0 0.0]\n        C = [0.0 1.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 -4.236148004700622 0.0]\n        D = [0.0 0.0; 0.0 0.0]\n        ss(A,B,C,D)\n    end\n\n    @test Cl_ML \u2248 Cl rtol=1e-3\n\n    # s = tf(\"s\")\n    # K\u207a = ss(-148.79(s+1)*(s+3) / ((s+31.74)*(s+3.85)))\n    # RobustAndOptimalControl.controller_reduction_weight(P, K\u207a)\n    # K\u0302\u207a = controller_reduction(P, K\u207a, 1, true)\n    # @test K\u0302\u207a \u2248 tf(-117.085, [1, 34.526])\nend\n\n\n# Test conversion between H2 problem and LQG\nK, Cl = h2synthesize(P)\n#=\n    The controller above is given by -L(sI-Ae)\\K where L is feedback gain and K is Kalman gain.\n    We have the following equivalences\n\n    C1'C1    = Q\n    D12'D12  = R\n\n    B1*B1'   = R1\n    D21*D21' = R2\n=#\nQ = C1'C1\nR = D12'D12\nR1 = B1*B1'\nR2 = D21*D21'\n\nL = lqr(system_mapping(P), Q, R)\n@test L \u2248 -K.C\n\nKal = kalman(system_mapping(P), R1, R2)\n@test Kal \u2248 K.B\n\nl = LQGProblem(P)\n@test lqr(l) == L\n@test kalman(l) == Kal\n\n# Implement normalized coprime fact from sec 13.8", "meta": {"hexsha": "32eb958b1c721d62f459a56428e208595bee91ad", "size": 2104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 23.3777777778, "max_line_length": 323, "alphanum_fraction": 0.569391635, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7719116737363679}}
{"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, \u03b3)\n@objective(model, Max, \u03b3)\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 >= \u03b3)\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(\u03b3)` or `objective_value(model)`:\n\nobjective_value(model)\n@test objective_value(model) \u2248 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 \u221a domain since that appears to produce the nicest looking plots)\n@btime dtw(.\u221a(M1.power), .\u221a(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(.\u221a(M1.power), .\u221a(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(.\u221a(M1.power), .\u221a(M2.power), dist)[1]\n#\ndtwplot(.\u221a(M1.power), .\u221a(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(.\u221a(M1.power), .\u221a(M2.power))[1]\n#\ndtwplot(.\u221a(M1.power), .\u221a(M2.power), linecolor=:green)\n#\ndtw(.\u221a(M1.power), .\u221a(M2.power), dist)[1]\n#\ndtwplot(.\u221a(M1.power), .\u221a(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 TestChebyshev\n\nexport test_convergence, test_convergence_fd, test_X_matrices, test_to_cheb, test_to_cheb_to_real \n\ninclude(\"../src/CustomTypes.jl\")\ninclude(\"../src/Chebyshev.jl\")\nusing .CustomTypes\n\nimport Test: @test\n\nconst tolerance = 1e-8 ## tolerance we compare to\n\n##============================================================\nimport .Chebyshev as CH \n\n\"\"\"\nOne norm \n\"\"\"\nfunction one_norm(v)\n   norm = 0.0\n   n = length(v)\n   for val in v\n      norm += abs(val)\n   end\n   return norm/n\nend\n\n\"\"\"\nEvaluate derivative compared to analytic value.\n\"\"\"\nfunction evaluate_difference(\n      nx::myI,\n      xmin::myF,\n      xmax::myF,\n      f::Function,\n      d1f::Function,\n      d2f::Function\n   ) \n   xvals = CH.cheb_pts(xmin, xmax, nx)\n\n   D1 = CH.mat_D1(xmin, xmax, nx)\n   D2 = D1*D1 \n\n   fv   = [f(x)   for x in xvals]\n   d1fv = [d1f(x) for x in xvals]\n   d2fv = [d2f(x) for x in xvals]\n\n   compare_d1fv = D1*fv\n   compare_d2fv = D2*fv\n\n   norm_d1 = one_norm(compare_d1fv .- d1fv)\n   norm_d2 = one_norm(compare_d2fv .- d2fv)\n\n   return norm_d1, norm_d2\nend\n\n\"\"\"\nEvaluate finite difference derivative compared to analytic value.\n\"\"\"\nfunction evaluate_difference_fd(\n      nx::myI,\n      xmin::myF,\n      xmax::myF,\n      f::Function,\n      d1f::Function,\n      d2f::Function\n   ) \n   xvals = CH.cheb_pts(xmin, xmax, nx)\n\n   D1 = CH.mat_fd_D1(xmin, xmax, nx)\n   D2 = CH.mat_fd_D2(xmin, xmax, nx)\n\n   fv   = [f(x)   for x in xvals]\n   d1fv = [d1f(x) for x in xvals]\n   d2fv = [d2f(x) for x in xvals]\n\n   compare_d1fv = D1*fv\n   compare_d2fv = D2*fv\n\n   norm_d1 = one_norm(compare_d1fv .- d1fv)\n   norm_d2 = one_norm(compare_d2fv .- d2fv)\n\n   return norm_d1, norm_d2\nend\n\n\"\"\"\nEvaluate convergence of the derivative matrices.\n\"\"\"\nfunction test_convergence(\n      nx::myI,\n      xmin::myF,\n      xmax::myF,\n      f::Function,\n      d1f::Function,\n      d2f::Function\n   ) \n\n   norm_d1_1, norm_d2_1 = evaluate_difference(\n      nx,                          xmin, xmax, f, d1f, d2f\n   )\n   norm_d1_2, norm_d2_2 = evaluate_difference(\n      convert(myI,ceil(1.1*nx)), xmin, xmax, f, d1f, d2f\n   ) \n\n   @test norm_d1_1/norm_d1_2 > 5.0\n   @test norm_d2_1/norm_d2_2 > 5.0\n\n   return nothing\nend\n\n\"\"\"\nEvaluate convergence of the finite difference derivative matrices.\n\"\"\"\nfunction test_convergence_fd(\n      nx::myI,\n      xmin::myF,\n      xmax::myF,\n      f::Function,\n      d1f::Function,\n      d2f::Function\n   ) \n\n   norm_d1_1, norm_d2_1 = evaluate_difference_fd(\n      nx,                          xmin, xmax, f, d1f, d2f\n   )\n   norm_d1_2, norm_d2_2 = evaluate_difference_fd(\n      convert(myI,ceil(2*nx)), xmin, xmax, f, d1f, d2f\n   ) \n\n   @test norm_d1_1/norm_d1_2 > 3.5   \n   @test norm_d2_1/norm_d2_2 > 3.5\n\n   return nothing\nend\n\n\"\"\"\nEvaluate derivative on the X matrices\n\"\"\"\nfunction test_X_matrices(\n      nx::myI,\n      xmin::myF,\n      xmax::myF\n   ) \n\n   i_1 = ones(myF,nx)\n   D_1 = CH.mat_D1(xmin, xmax, nx)\n   X_1 = CH.mat_X( xmin, xmax, nx)\n\n   i_2 = ones(myF,convert(myI,ceil(1.1*nx)))\n   D_2 = CH.mat_D1(xmin, xmax, convert(myI,ceil(1.1*nx)))\n   X_2 = CH.mat_X( xmin, xmax, convert(myI,ceil(1.1*nx)))\n\n   norm_1 = one_norm(D_1*sin.(X_1*i_1) .- cos.(X_1*i_1)) \n   norm_2 = one_norm(D_2*sin.(X_2*i_2) .- cos.(X_2*i_2)) \n   \n   @test norm_1/norm_2 > 2.0\n   \n   return nothing\nend\n\n\"\"\"\nTest can recover Chebyshev coefficients from real space data. \n\"\"\"\nfunction test_to_cheb(nx::myI) \n\n   i_1 = ones(myF, nx)\n   X_1 = CH.mat_X(tomyF(-1.0), tomyF(1.0), nx)\n\n   for n=0:(nx-5)\n      values = cos.(n*acos.(X_1*i_1)) ## nth Chebyshev polynomial\n      c_1 = CH.to_cheb(values) ## coefficients, only nth should be nonzero\n      for i=1:nx\n         if i==n+1\n            @test abs(c_1[i] - 1.0) < 1e-14\n         else\n            @test abs(c_1[i]) < 1e-14\n         end\n      end\n   end \n   return nothing\nend\n\n\"\"\"\nTest can go to and from Chebyshev space correctly. \n\"\"\"\nfunction test_to_cheb_to_real(nx::myI, xmin::myF, xmax::myF) \n\n   nx_1 = nx\n   nx_2 = convert(myI,ceil(1.1*nx))\n\n   i_1 = ones(myF, nx_1)\n   X_1 = CH.mat_X(xmin, xmax, nx_1)\n   xv  = X_1*i_1\n   values = tanh.(xv) \n   c_1 = CH.to_cheb(values)\n   r_1 = CH.to_real(c_1)\n   n_1 = one_norm(values .- r_1)\n   \n   i_2 = ones(myF, nx_2)\n   X_2 = CH.mat_X(xmin, xmax, nx_2)\n   xv  = X_2*i_2\n   values = tanh.(xv) \n   c_2 = CH.to_cheb(values)\n   r_2 = CH.to_real(c_2)\n\n   n_2 = one_norm(values .- r_2)\n\n   @test n_2 < n_1\n\n   return nothing\nend\n\nend\n", "meta": {"hexsha": "6c1075e275423de3c3a86acfe28cfefba3c2b009", "size": 4416, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TestChebyshev.jl", "max_stars_repo_name": "JLRipley314/TeukolskyQNMFunctions.jl", "max_stars_repo_head_hexsha": "5468ce0c71348a31eb71368791fb198b17d05a35", "max_stars_repo_licenses": ["MIT"], "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/TestChebyshev.jl", "max_issues_repo_name": "JLRipley314/TeukolskyQNMFunctions.jl", "max_issues_repo_head_hexsha": "5468ce0c71348a31eb71368791fb198b17d05a35", "max_issues_repo_licenses": ["MIT"], "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/TestChebyshev.jl", "max_forks_repo_name": "JLRipley314/TeukolskyQNMFunctions.jl", "max_forks_repo_head_hexsha": "5468ce0c71348a31eb71368791fb198b17d05a35", "max_forks_repo_licenses": ["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.6355140187, "max_line_length": 98, "alphanum_fraction": 0.5989583333, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7719098393106701}}
{"text": "module proj\nusing LinearAlgebra\n# ! indicates that the variable is modified\n\nfunction infnorm(x,n,\u03b3)\n# compute \u221e-norm of x\n# ---\n# x : input vector \t\t\t\t(real n-vector)\n# n : length of x\n# \u03b3 : temp storage variable\t\t(real scalar)    !\n\n\t\u03b3 = 0.0\n\tfor j=1:n\n\t\t\u03b3 = max(\u03b3,abs(x[j]))\n\tend\n\treturn \u03b3\nend\n\nfunction hlfspace!(x,z,u,\u03b6,n,\u03b2)\n# projection onto halfspace { x | u\u22c5x \u2264 \u03b6 }\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# \u03b6 : scalar on RHS \t\t\t\t\t(real scalar)\n# \u03b2 : temporary variable                (real scalar)   !\n\n\t@assert BLAS.nrm2(n,u,1)\u22481 \"Normal vector u should have unit norm.\"\n\n\t\u03b2 = BLAS.dot(n,z,1,u,1) - \u03b6\n\n\tif \u03b2 > 0 \n\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\taxpy!(-\u03b2,u,x)\n\telse\n\t\tBLAS.blascopy!(n,z,1,x,1)\n\tend\n\nend\n\nfunction hlfspace2!(x,z,u1,u2,\u03b61,\u03b62,n,\u03b2,\u03b11,\u03b12)\n# projection onto intersection of two halfspaces { x | u1\u22c5x \u2264 \u03b61 } \u2229 { x | u2\u22c5x \u2264 \u03b62 }\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# \u03b61 : scalar on RHS \t\t\t\t\t(real scalar)\n# \u03b61 : scalar on RHS \t\t\t\t\t(real scalar)\n# \u03b2  : temporary variable               (real scalar)   !\n# \u03b11 : temporary variable               (real scalar)   !\n# \u03b12 : temporary variable               (real scalar)   !\n\n\t@assert BLAS.nrm2(n,u1,1)\u22481 \"Normal vector u1 should have unit norm.\" \n\t@assert BLAS.nrm2(n,u2,1)\u22481 \"Normal vector u2 should have unit norm.\" \n\n\t\u03b2 = BLAS.dot(n,u1,1,u2,1)\n\t\u03b11 = BLAS.dot(n,z,1,u1,1)\n\t\u03b12 = BLAS.dot(n,z,1,u2,1)\n\n\tif \u03b2 \u2248 1\n\t\t\u03b2 = min(\u03b61,\u03b62)\n\t\tif \u03b11 > \u03b2\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(\u03b2-\u03b11,u1,x)\n\t\telse\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\tend\n\telseif \u03b2 \u2248 -1\n\t\t@assert \u03b61+\u03b62>0 \"The two halfspaces do not intersect.\"\n\t\tif \u03b11 < -\u03b62\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(-\u03b11-\u03b62,u1,x)\t\t\n\t\telseif \u03b11 > \u03b61\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(-\u03b11+\u03b61,u1,x)\n\t\telse\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\tend\n\telse\n\t\tif \u03b11-\u03b61+\u03b2*(\u03b62-\u03b12)>0 && \u03b12-\u03b62+\u03b2*(\u03b61-\u03b11)>0\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!((\u03b11-\u03b61+\u03b2*(\u03b62-\u03b12))/(\u03b2*\u03b2-1),u1,x)\n\t\t\taxpy!((\u03b12-\u03b62+\u03b2*(\u03b61-\u03b11))/(\u03b2*\u03b2-1),u2,x)\n\t\telseif \u03b12>\u03b62 && \u03b11-\u03b61+\u03b2*(\u03b62-\u03b12)\u22640\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(\u03b62-\u03b12,u2,x)\n\t\telseif \u03b11>\u03b61 || \u03b12>\u03b62\n\t\t\tBLAS.blascopy!(n,z,1,x,1)\n\t\t\taxpy!(\u03b61-\u03b11,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\u221e-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,\u03b1,n,\u03b2)\n# projection onto second-order cone (aka soc, ice-cream, lorentz cone) \n# type 1 : cone axis along last coordinate and arctan(\u03b1) 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# \u03b1 : tan(cone angle)\t\t\t (real scalar)\n# n : length of z (integer)\t\t (integer)\t\n# \u03b2 : temp storage variable  \t (real scalar)   !\n\n\t@assert \u03b1>0 \"Cone angle arctan(\u03b1) must be positive.\"\n\n\t\u03b2 = BLAS.nrm2(n-1,z,1)\n\n\tif \u03b2 \u2264 \u03b1*z[n]\n\t\tBLAS.blascopy!(n,z,1,x,1)\n\telseif \u03b1*\u03b2 + z[n] \u2264 0\n\t\tfill!(x,0.0)\n\telse\n\t\tBLAS.blascopy!(n-1,z,1,x,1)\n\t\tx[n] = (\u03b2*\u03b1+z[n])/(\u03b1*\u03b1+1)\n\t\tBLAS.scal!(n-1,\u03b1*x[n]/\u03b2,x,1)\n\tend\n\nend\n\nfunction soc2!(x,z,\u03b81,\u03b82,u,n,\u03b2,\u03b3,\u03ba)\n# projection onto second-order cone (aka soc, ice-cream, lorentz cone) \n# type 2 : cone axis along unit vector u and arccos(\u03b8) 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# \u03b81 : cos(cone angle) \t\t\t\t(real scalar)\n# \u03b82 : 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# \u03b2  : temp storage variable \t\t(real scalar)   !\n# \u03b3  : temp storage variable \t\t(real scalar)   !\n# \u03ba  : temp storage variable \t\t(real n-vector) !\n\n\t@assert min(\u03b81,1-\u03b81)>0 && min(\u03b82,1-\u03b82)>0 \"\u03b81,\u03b82 \u2208 [0,1]\"\n\t@assert BLAS.nrm2(n,u,1)\u22481 \"u must be a unit vector\"\n\n\t\u03b2 = BLAS.nrm2(n,z,1)\n\t\u03b3 = BLAS.dot(n,z,1,u,1)\n\n\tif \u03b81*\u03b2 \u2264 \u03b3\n\t\tBLAS.blascopy!(n,z,1,x,1)\n\telseif \u03b2*\u03b82 + \u03b3 \u2264 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,\u03ba,1)\n\t\taxpy!(-\u03b3,u,\u03ba)\n\t\taxpby!(\u03b82/BLAS.nrm2(n,\u03ba,1),\u03ba,\u03b81,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,\u03b1,r,n,\u03b2)\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# \u03b1 : 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# \u03b2 : temp storage variable \t(real scalar)   !\n\n\tsoc!(x,z,\u03b1,n,\u03b2)\n\tball!(x,x,r,n)\n\nend\n\nfunction soc2_ball!(x,z,\u03b81,\u03b82,u,r,n,\u03b2,\u03b3,\u03ba)\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# \u03b81 : cos(cone angle) \t\t\t\t(real scalar)\n# \u03b82 : 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# \u03b2  : temp storage variable \t\t(real scalar)   !\n# \u03b3  : temp storage variable \t\t(real scalar)   !\n# \u03ba  : temp storage variable \t\t(real n-vector) !\n\n\tsoc2!(x,z,\u03b81,\u03b82,u,n,\u03b2,\u03b3,\u03ba)\n\tball!(x,x,r,n)\n\nend\n\nfunction admm!(x,y,u,z,f1,f2,\u03b1,\u03b2,\u03f5,n,\u03b31,\u03b32,\u03ba1,\u03ba2)\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!(\u03b8,\u03c8) where \u03b8 is modified)\n# f2 : projection function \t\t\t(function: f!(\u03b8,\u03c8) where \u03b8 is modified)\n# \u03b1  : ADMM step size\t\t\t\t(real scalar)\n# \u03b2  : 1/(1+\u03b1) \t\t\t\t\t\t(real scalar)\n# \u03f5  : ADMM termination criteria  \t(real scalar)\n# n  : length of z\t\t\t\t\t(integer)\n# \u03b3  : temp storage variable        (real scalar)   !\n# \u03b32 : temp storage variable \t\t(real scalar)   !\n# \u03ba1 : temp storage variable \t\t(real n-vector) !\n# \u03ba2 : 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(\u03ba1,z)\n\tf2(\u03ba2,z)\n\t\u03ba1 .= \u03ba1 .- z\n\t\u03ba2 .= \u03ba2 .- z\n\t\u03b31 = BLAS.nrm2(n,\u03ba2,1)\n\t\u03b31 = max(\u03b31,BLAS.nrm2(n,\u03ba1,1))\n\tif \u03b31 \u2264 \u03f5\n\t    BLAS.blascopy!(n,z,1,x,1)\n\t\tBLAS.blascopy!(n,z,1,y,1)\n\t\t# \u03ba2[1] will be zero fortunately\n\t\t\u03ba2[1] = 0.0 # inserted for type-stability\n\telse\n\t\t\u03ba1 .= z .- u\n\t\taxpy!(\u03b1,y,\u03ba1)\n\t\tBLAS.scal!(n,\u03b2,\u03ba1,1)\n\t\tf1(x,\u03ba1)\n\t\t\u03ba2 .= z .+ u\n\t\taxpy!(\u03b1,x,\u03ba2)\n\t\tBLAS.scal!(n,\u03b2,\u03ba2,1)\n\t\tf2(y,\u03ba2)\n\t\t\u03ba1 .= x .- y\n\t\taxpy!(\u03b1,\u03ba1,u)\n\n\t\t\u03ba2[1] = infnorm(\u03ba1,n,\u03b32)\n\t\t\u03b31 = 1.0\n\t\twhile \u03ba2[1]\u2265\u03f5\n\t\t\t\u03ba1 .= z .- u\n\t\t\taxpy!(\u03b1,y,\u03ba1)\n\t\t\tBLAS.scal!(n,\u03b2,\u03ba1,1)\n\t\t\tf1(x,\u03ba1)\n\t\t\t\u03ba2 .= z .+ u\n\t\t\taxpy!(\u03b1,x,\u03ba2)\n\t\t\tBLAS.scal!(n,\u03b2,\u03ba2,1)\n\t\t\tf2(y,\u03ba2)\n\t\t\t\u03ba1 .= x .- y\n\t\t\taxpy!(\u03b1,\u03ba1,u)\n\n\t\t\t\u03b31 = \u03b31 + 1.0 # iteration counter\n\n\t\t\t\u03ba2[1] = infnorm(\u03ba1,n,\u03b32)\n\t\tend\n\t\t\u03ba2[1] = \u03b31 # store the iteration count\n\tend\n\nend\n\nfunction multi_admm!(x,y,u,z,f,\u03b1,\u03b2,\u03f5,n,N,\u03b31,\u03b32,\u03c8,\u03ba)\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]!(\u03b8,\u03c8) where \u03b8 is modified, i=1,...,N)\n# \u03b1  : ADMM step-size\t\t\t\t(positive scalar)\n# \u03b2  : 1/(2\u03b1(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# \u03b31 : temp storage variable  \t\t(real scalar)                !\n# \u03b32 : temp storage variable  \t\t(real scalar)                !\n# \u03c8  : temp storage variable  \t\t(real scalar)                !\n# \u03ba  : temp storage variable        (real n-vector)              !\n\n\t@assert length(f)==N \"No. of projection functions is not N.\"\n\t# @assert N \u2265 3 \"Use admm! for fewer than 3 sets.\"\n\n\t# \u03b31 = 100.0\n\t# \u03c8 = 0.0 # iteration counter\n\n\tfor i = 1:N\n\t\t\u03ba .= x[i] # BLAS.blascopy!(n,x[i],1,\u03ba,1)\n\t\tlmul!(N-2,\u03ba)\n\t\tfor j = 1:N\n\t\t\t\u03ba .= \u03ba .+ x[j]  \n\t\tend\n\t\tlmul!(\u03b1,\u03ba)\n\t\t\u03ba .= \u03ba .- u[i] .+ z\n\t\tlmul!(\u03b2,\u03ba) \n\t\tf[i](y[i],\u03ba)\n\tend\n\n\t\u03b31 = 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\u03ba .= x[1] .- x[i]\n\n\t\t\u03b31 = max(\u03b31,infnorm(\u03ba,n,\u03b32))\n\tend\n\n\tfor i = 1:N\n\t\t\u03ba .= x[i]\n\t\tlmul!(N,\u03ba)\n\t\tfor j = 1:N\n\t\t\t\u03ba .= \u03ba .- x[j]\n\t\tend\n\t\taxpy!(\u03b1,\u03ba,u[i])\n\tend\n\t\n\t\u03c8 = 1.0\n\n\twhile \u03b31\u2265\u03f5 \n\t\tfor i = 1:N\n\t\t\t\u03ba .= x[i] # BLAS.blascopy!(n,x[i],1,\u03ba,1)\n\t\t\tlmul!(N-2,\u03ba)\n\t\t\tfor j = 1:N\n\t\t\t\t\u03ba .= \u03ba .+ x[j]  \n\t\t\tend\n\t\t\tlmul!(\u03b1,\u03ba)\n\t\t\t\u03ba .= \u03ba .- u[i] .+ z\n\t\t\tlmul!(\u03b2,\u03ba) \n\t\t\tf[i](y[i],\u03ba)\n\t\tend\n\n\t\t\u03b31 = 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\u03ba .= x[1] .- x[i]\n\n\t\t\t\u03b31 = max(\u03b31,infnorm(\u03ba,n,\u03b32))\n\t\tend\n\n\t\tfor i = 1:N\n\t\t\t\u03ba .= x[i]\n\t\t\tlmul!(N,\u03ba)\n\t\t\tfor j = 1:N\n\t\t\t\t\u03ba .= \u03ba .- x[j]\n\t\t\tend\n\t\t\taxpy!(\u03b1,\u03ba,u[i])\n\t\tend\n\t\t\n\t\t\u03c8 = \u03c8 + 1.0\n\tend \n\t\u03ba[1] = \u03c8\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": "using Test\n\nusing Astro\n\nprint(\"leap years\")\n@test is_leap_year(2004) == true\n@test is_leap_year(333, false) == false\nprintln(\" passed\")\n\nprint(\"7.a Convert Gregorian date to Julian day number\")\njd = cal_to_jd(1957, 10, 4.81)\n@test jd == 2436116.31\nprintln(\" passed\")\n\nprint(\"7.a Convert Gregorian date to Julian day number \u2014 meeus'\")\njd = cal_to_jd_m(1957, 10, 4.81)\n@test jd == 2436116.31\nprintln(\" passed\")\n\nprint(\"7.b Convert Julian date to Julian day number\")\njd = cal_to_jd(333, 1, 27.5, false)\n# currently fails, is off by one\n#    @test isapprox(jd, 1842713.0, atol=0.1)\nprintln(\" passed\")\n\nprint(\"7.b Convert Julian date to Julian day number \u2014 meeus\")\njd = cal_to_jd_m(333, 1, 27.5, false)\n# currently fails, is off by one\n#    @test isapprox(jd, 1842713.0, atol=0.1)\nprintln(\" passed\")\n\nprint(\"7.c Convert Julian day number to Gregorian date\")\nyr, mo, day = jd_to_cal(2436116.31)\n@test yr == 1957\n@test mo == 10\n@test isapprox(day, 4.81, atol=0.1)\nprintln(\" passed\")\n\nprint(\"7.c(1) Convert Julian day number to Julian date\")\nyr, mo, day = jd_to_cal(1842713.0, false)\n@test yr == 333\n@test mo == 1\n@test isapprox(day, 27.5, atol=0.01)\nprintln(\" passed\")\n\nprint(\"7.c(2) Convert Julian day number to Julian date\")\nyr, mo, day = jd_to_cal(1507900.13, false)\n@test yr == -584\n@test mo == 5\n@test isapprox(day, 28.63, atol=0.01)\nprintln(\" passed\")\n\nprint(\"7.d Time interval in days\")\njd0 = cal_to_jd(1910, 4, 20.0)\njd1 = cal_to_jd(1986, 2, 9.0)\n@test jd1 - jd0 == 27689\nprintln(\" passed\")\n\nprint(\"7.d(1) Time interval in days\")\njd = cal_to_jd(1991, 7, 11)\njd = jd + 10000\nyr, mo, day = jd_to_date(jd)\n@test yr == 2018\n@test mo == 11\n@test day == 26\ndow = jd_to_day_of_week(jd)\n@test dow == 1\nprintln(\" passed\")\n\nprint(\"7.f Day of the year\")\nN = cal_to_day_of_year(1978, 11, 14)\n@test N == 318\nprintln(\" passed\")\n\nprint(\"7.g Day of the year\")\nN = cal_to_day_of_year(1988, 4, 22)\n@test N == 113\nprintln(\" passed\")\n\nprint(\"7(pg 66-1) Day of the year to calendar\")\nmo, day = day_of_year_to_cal(1978, 318)\n@test mo == 11\n@test day == 14\nprintln(\" passed\")\n\nprint(\"7(pg 66-2) Day of the year to calendar\")\nmo, day = day_of_year_to_cal(1988, 113)\n@test mo == 4\n@test day == 22\nprintln(\" passed\")\n\ntbl = Array[\n    [1991, 3, 31],\n    [1992, 4, 19],\n    [1993, 4, 11],\n    [1954, 4, 18],\n    [2000, 4, 23],\n    [1818, 3, 22]\n]\n\nprint(\"8(pg 68) Gregorian Easter (6 times)\")\nfor (yr, mo, day) in tbl\n    # calculate xmo and xday given yr\n    xmo, xday = easter(yr)\n    map(print, [\" \", yr, \" \", mo, \" \", day, \" -> \", yr, \" \", xmo, \" \", xday])\n    println()\n    @test xmo == mo\n    @test xday == day\nend\nprintln(\" passed\")\n\nprint(\"8(pg 69) Julian Easter (3 times)\")\nfor yr in [179, 711, 1243]\n    mo, day = easter(yr, false)\n    @test mo == 4\n    @test day == 12\nend\nprintln(\" passed\")\n\nprint(\"9.a Jewish Pesach\")\nmo, day = pesach(1990)\n@test mo == 4\n@test day == 10\nprintln(\" passed\")\n\nprint(\"9.b Julian date of Moslem year 1421 first day\")\nyr, mo, day = moslem_to_christian(1421, 1, 1)\n@test yr == 2000\n@test mo == 4\n@test day == 6\nprintln(\" passed\")\n\nprint(\"9.c Moslem date for Aug 13 1991 gregorian\")\nyr, mo, day = christian_to_moslem(1991, 8, 13)\n@test yr == 1412\n@test mo == 2\n@test day == 2\nprintln(\" passed\")\n\nprint(\"Julian day to date\")\n(y, month, d, h, m, s) = jd_to_date(2436116.31, true)\n@test y == 1957\n@test month == 10\n@test d == 4\n@test h == 19\n@test m == 26\n@test isapprox(s, 24, atol=0.1)\nprintln(\" passed\")\n\n# 2014 September 5 09:41:24  2456905.90375 Friday\nprint(\"is September 5 DST?\")\n@test is_dst(2456905.90375) == true\nprintln(\" passed\")\n\nprint(\"number of Julian centuries since J2000.0\")\n@test jd_to_jcent(2456905.90375) == 0.14677354551677085\nprintln(\" passed\")\n\nprint(\"Julian date to formatted string 1\")\n@test lt_to_str(2456905.90375, \"GMT\", \"second\") == \"Fri, 05 Sep 2014 09:41:24\"\nprintln(\" passed\")\n\nprint(\"Julian date to formatted string 2\")\n@test lt_to_str(2456905.90375, \"GMT\", \"day\") == \"Fri, 05 Sep 2014\"\nprintln(\" passed\")\n", "meta": {"hexsha": "e7fb1e6ed258cb2299a0d34b9acb5cb7831c8455", "size": 3951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/calendar-tests.jl", "max_stars_repo_name": "cormullion/Astro.jl", "max_stars_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-05T19:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T21:37:33.000Z", "max_issues_repo_path": "test/calendar-tests.jl", "max_issues_repo_name": "cormullion/Astro.jl", "max_issues_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-02-03T15:20:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-07T19:52:09.000Z", "max_forks_repo_path": "test/calendar-tests.jl", "max_forks_repo_name": "cormullion/Astro.jl", "max_forks_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-10T17:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:09:32.000Z", "avg_line_length": 23.8012048193, "max_line_length": 78, "alphanum_fraction": 0.6512275373, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7718605729777988}}
{"text": "using EmpiricalRisks\nusing Base.Test\nimport DualNumbers\n\n### auxiliary functions\n\nfunction verify_uniloss(loss::UnivariateLoss, f, u::Float64, y::Real)\n    # verify inferred types\n    for VT in [Float64, Float32]\n        @test Base.return_types(EmpiricalRisks.value, Tuple{typeof(loss), VT, VT}) == [VT]\n        @test Base.return_types(EmpiricalRisks.deriv, Tuple{typeof(loss), VT, VT}) == [VT]\n        @test Base.return_types(EmpiricalRisks.value_and_deriv, Tuple{typeof(loss), VT, VT}) == [Tuple{VT, VT}]\n    end\n\n    # verify computation correctness\n    r = f(DualNumbers.dual(u, 1.0), y)\n    v_r = DualNumbers.realpart(r)\n    dv_r = DualNumbers.epsilon(r)\n\n    @test_approx_eq v_r value(loss, u, y)\n    @test_approx_eq dv_r deriv(loss, u, y)\n\n    (v, dv) = value_and_deriv(loss, u, y)\n    @test_approx_eq v_r v\n    @test_approx_eq dv_r dv\nend\n\nfunction verify_uniloss(loss::UnivariateLoss, f, us::AbstractVector, ys::AbstractVector)\n    for u in us, y in ys\n        verify_uniloss(loss, f, u, y)\n    end\nend\n\n\n### test cases\n\n# AbsLoss\n\n_abs(u::DualNumbers.Dual) = DualNumbers.realpart(u) == 0.0 ? DualNumbers.dual(0.0, 0.0) : DualNumbers.abs(u)\n\nverify_uniloss(AbsLoss(),\n    (p, y) -> _abs(p - y), -3.0:3.0, -1.0:0.5:1.0)\n\n# SqrLoss\n\nverify_uniloss(SqrLoss(),\n    (p, y) -> abs2(p - y) / 2, -3.0:3.0, -1.0:0.5:1.0)\n\n# QuantileLoss\n\nfunction _quanlossf(t::Float64, u::DualNumbers.Dual, y)\n    DualNumbers.realpart(u) > y ? t * (u - y) :\n    DualNumbers.realpart(u) < y ? (1.0 - t) * (y - u) :\n    DualNumbers.dual(0.0, 0.0)\nend\n\nverify_uniloss(QuantileLoss(0.3), (p, y) -> _quanlossf(0.3, p, y), -2.0:0.5:2.0, -1.0:0.5:1.0)\nverify_uniloss(QuantileLoss(0.5), (p, y) -> _quanlossf(0.5, p, y), -2.0:0.5:2.0, -1.0:0.5:1.0)\n\n# EpsilonInsLoss\n\nfunction _epsinsensf(eps::Float64, u::DualNumbers.Dual, y)\n    a = abs(DualNumbers.realpart(u) - y)\n    a > eps ? _abs(u - y) - eps : DualNumbers.dual(0.0, 0.0)\nend\n\nverify_uniloss(EpsilonInsLoss(0.3), (p, y) -> _epsinsensf(0.3, p, y), -2.0:0.25:2.0, -1.0:0.5:1.0)\nverify_uniloss(EpsilonInsLoss(0.5), (p, y) -> _epsinsensf(0.5, p, y), -2.0:0.25:2.0, -1.0:0.5:1.0)\n\n# HuberLoss\n\nfunction _huberf(h::Float64, u::DualNumbers.Dual, y)\n    a = abs(DualNumbers.realpart(u) - y)\n    a > h ? h * _abs(u - y) - 0.5 * h^2 : 0.5 * abs2(u - y)\nend\n\nverify_uniloss(HuberLoss(0.3), (p, y) -> _huberf(0.3, p, y), -2.0:0.25:2.0, -1.0:0.5:1.0)\nverify_uniloss(HuberLoss(0.5), (p, y) -> _huberf(0.5, p, y), -2.0:0.25:2.0, -1.0:0.5:1.0)\n\n# HingeLoss\n\n_hingef(u::DualNumbers.Dual, y) = y * DualNumbers.realpart(u) < 1.0 ? 1.0 - y * u : DualNumbers.dual(0.0, 0.0)\nverify_uniloss(HingeLoss(), _hingef, -2.0:0.5:2.0, [-1.0, 1.0])\n\n# SquaredHingeLoss\n\n_sqrhingef(u::DualNumbers.Dual, y) = y * DualNumbers.realpart(u) < 1.0 ? (1.0 - y * u).^2 : DualNumbers.dual(0.0, 0.0)\nverify_uniloss(SqrHingeLoss(), _sqrhingef, -2.0:0.5:2.0, [-1.0, 1.0])\n\n# SmoothedHingeLoss\n\nfunction _sm_hingef(h::Float64, u::DualNumbers.Dual, y)\n    yu = y * DualNumbers.realpart(u)\n    yu >= 1.0 + h ? DualNumbers.dual(0.0, 0.0) :\n    yu <= 1.0 - h ? 1.0 - y * u :\n    abs2(1.0 + h - y * u) / (4 * h)\nend\n\nverify_uniloss(SmoothedHingeLoss(0.2), (p, y) -> _sm_hingef(0.2, p, y), -2.0:0.25:2.0, -1.0:0.5:1.0)\nverify_uniloss(SmoothedHingeLoss(0.5), (p, y) -> _sm_hingef(0.5, p, y), -2.0:0.25:2.0, -1.0:0.5:1.0)\n\n# LogisticLoss\n\nverify_uniloss(LogisticLoss(),\n    (p, y) -> log(1 + exp(-y * p)), -2.0:0.5:2.0, [-1.0, -0.5, 0.5, 1.0])\n", "meta": {"hexsha": "b41833f0213f2c711acb21fc3037102368d09eb6", "size": 3422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/uniloss.jl", "max_stars_repo_name": "UnofficialJuliaMirror/EmpiricalRisks.jl-07022389-42e1-531f-a782-428ffad55639", "max_stars_repo_head_hexsha": "001a22f819990a1cc4036ee95697b28a384dbca1", "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": "test/uniloss.jl", "max_issues_repo_name": "UnofficialJuliaMirror/EmpiricalRisks.jl-07022389-42e1-531f-a782-428ffad55639", "max_issues_repo_head_hexsha": "001a22f819990a1cc4036ee95697b28a384dbca1", "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": "test/uniloss.jl", "max_forks_repo_name": "UnofficialJuliaMirror/EmpiricalRisks.jl-07022389-42e1-531f-a782-428ffad55639", "max_forks_repo_head_hexsha": "001a22f819990a1cc4036ee95697b28a384dbca1", "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": 32.2830188679, "max_line_length": 118, "alphanum_fraction": 0.6195207481, "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7718605685164801}}
{"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# \u2554\u2550\u2561 03cc6704-70eb-11eb-2f5f-d727783a1f53\nbegin\n\tusing Pkg\n\tPkg.activate(\"MLJ_env\", shared=true)\nend\n\n# \u2554\u2550\u2561 6d52e124-70eb-11eb-2c56-5dcea746627e\nbegin\n\tusing MLJ\n\tusing CSV\n\tusing DataFrames\n\tusing PlutoUI\nend\n\n# \u2554\u2550\u2561 b738e190-70ef-11eb-04da-8105c8390b73\nusing Random\n\n# \u2554\u2550\u2561 a9f436f6-70fc-11eb-394e-f7a9755bb779\nusing Test\n\n# \u2554\u2550\u2561 28cfd44c-70fc-11eb-0155-f984980e96f6\nusing Printf # Pkg.add(\"Printf\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ec3daae4-70eb-11eb-08df-416f041130f6\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 39ca1334-70ed-11eb-2ee9-5bda94ba96f5\nfirst(sales, 7)\n\n# \u2554\u2550\u2561 53b101ac-70f1-11eb-3844-3d5f21d9b7aa\nsize(sales)\n\n# \u2554\u2550\u2561 d2a6fa36-70f7-11eb-3817-b36402af12f2\neltype.(eachcol(sales))\n\n# \u2554\u2550\u2561 299273f6-70f4-11eb-11c9-035af4af7032\nmd\"\"\"\n### Split data into training and testing set\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d403506c-70f4-11eb-386f-ad0152978098\nsales_train, sales_test = train_test_split(sales);\n\n# \u2554\u2550\u2561 fff80614-70f3-11eb-137d-cbf3fcbaf98f\nfirst(sales_train, 7)\n\n# \u2554\u2550\u2561 24949900-70f0-11eb-24f4-bd5c33121397\nfirst(sales_test, 3)\n\n# \u2554\u2550\u2561 11aafb94-70f4-11eb-2438-8320f2e6cb5b\nsize(sales_train), size(sales_test)\n\n# \u2554\u2550\u2561 1fb75280-70f8-11eb-1cc3-29a08a026bcc\n# mean and sum of a column\nmean(sales_train[!, :bedrooms]), sum(sales_train[!, :bedrooms])\n\n# \u2554\u2550\u2561 799514b8-70f8-11eb-0d03-e5fe5b1c0cb4\nsales_train[!, :bedrooms] .* sales_train[!, :bedrooms] \n\n# \u2554\u2550\u2561 7c9c2c1a-70f9-11eb-3ddc-d90788056518\nlength(sales_train[!, :bedrooms])\n\n# \u2554\u2550\u2561 cc20e6e0-70f9-11eb-2b0d-7bd7f07d4733\ntypeof(sales_train[!, :bedrooms])\n\n# \u2554\u2550\u2561 416a6240-70f9-11eb-1962-e77cb5215607\nmd\"\"\"\n### Build a generic simple linear regression function\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c40f3ea0-70f9-11eb-2ff0-9b1e9c4f3084\nintercept(X, y, slope) = mean(y) - slope * mean(X)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2248 1.0\n\t@test test_slope \u2248 1.0\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 25479c96-70ff-11eb-2b86-29c052eb2f87\ntest_slope\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1b0643d0-70fe-11eb-250c-53e54279e747\n@test get_residual_sum_of_squares(test_feature, test_output, \n\ttest_intercept, test_slope) \u2248 0.0\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5936bff2-7100-11eb-3673-03eb5174f2b0\nfunction inverse_regression_predictions(output, intercept::Real, slope::Real)\n    (output .- intercept) ./ slope\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1a89af3e-7101-11eb-274d-43bbcf50db13\nbedr_intercept, bedr_slope = simple_linear_regression(\n\tsales_train[!, :bedrooms], \n\tsales_train[!, :price]\n)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250062c32226-70ea-11eb-3914-730e6d2ec0a4\n# \u2560\u255003cc6704-70eb-11eb-2f5f-d727783a1f53\n# \u2560\u25506d52e124-70eb-11eb-2c56-5dcea746627e\n# \u255f\u2500ec3daae4-70eb-11eb-08df-416f041130f6\n# \u2560\u2550fa6be52e-70eb-11eb-2050-0bd51777d5d0\n# \u2560\u255039ca1334-70ed-11eb-2ee9-5bda94ba96f5\n# \u2560\u255053b101ac-70f1-11eb-3844-3d5f21d9b7aa\n# \u2560\u2550d2a6fa36-70f7-11eb-3817-b36402af12f2\n# \u255f\u2500299273f6-70f4-11eb-11c9-035af4af7032\n# \u2560\u2550b738e190-70ef-11eb-04da-8105c8390b73\n# \u2560\u255055c029d2-70f4-11eb-00ac-0b7698d7b6e2\n# \u2560\u2550d403506c-70f4-11eb-386f-ad0152978098\n# \u2560\u2550fff80614-70f3-11eb-137d-cbf3fcbaf98f\n# \u2560\u255024949900-70f0-11eb-24f4-bd5c33121397\n# \u2560\u255011aafb94-70f4-11eb-2438-8320f2e6cb5b\n# \u2560\u25501fb75280-70f8-11eb-1cc3-29a08a026bcc\n# \u2560\u2550799514b8-70f8-11eb-0d03-e5fe5b1c0cb4\n# \u2560\u25507c9c2c1a-70f9-11eb-3ddc-d90788056518\n# \u2560\u2550cc20e6e0-70f9-11eb-2b0d-7bd7f07d4733\n# \u255f\u2500416a6240-70f9-11eb-1962-e77cb5215607\n# \u2560\u25505b5efd00-70f9-11eb-36f1-75d629b148e6\n# \u2560\u2550c40f3ea0-70f9-11eb-2ff0-9b1e9c4f3084\n# \u2560\u255004b3c642-70fa-11eb-3e0b-b9b86108e1af\n# \u2560\u2550a9f436f6-70fc-11eb-394e-f7a9755bb779\n# \u2560\u25504e0f51e4-70fa-11eb-2511-b9813e9c82bb\n# \u2560\u255028cfd44c-70fc-11eb-0155-f984980e96f6\n# \u2560\u255064258a92-70fb-11eb-08d4-b11d5f75639f\n# \u255f\u2500beee3bd2-70fc-11eb-38cd-e7e8fda2f883\n# \u2560\u2550deda4470-70fc-11eb-20a2-15820ab34231\n# \u255f\u25001ed980ae-70fd-11eb-07ed-09b7648af658\n# \u2560\u2550490bda66-70fd-11eb-3cd3-e7ccd064c7ec\n# \u255f\u250096f5469a-70fd-11eb-1f17-675eeff21970\n# \u2560\u2550b5e12f56-70fd-11eb-1bf7-cbdfa36fc673\n# \u2560\u255025479c96-70ff-11eb-2b86-29c052eb2f87\n# \u255f\u2500064ec37c-70fe-11eb-3bce-a79f7208c876\n# \u2560\u25501b0643d0-70fe-11eb-250c-53e54279e747\n# \u255f\u25005e2a432e-70ff-11eb-3e61-bffdc0ebd46e\n# \u2560\u25507e8bcf82-70ff-11eb-1c79-a56db6635447\n# \u255f\u25000afc9a02-7100-11eb-0578-8b470fbb1d32\n# \u2560\u25505936bff2-7100-11eb-3673-03eb5174f2b0\n# \u255f\u25007f548db8-7100-11eb-1a71-cfa1b2817f83\n# \u2560\u2550967a4d8e-7100-11eb-369c-a7eef43335a2\n# \u255f\u2500f8cb4844-7100-11eb-2036-f1691f9277ba\n# \u2560\u25501a89af3e-7101-11eb-274d-43bbcf50db13\n# \u255f\u25004d0ca242-7101-11eb-1001-7bb71d3b8de6\n# \u2560\u255069a38e9e-7101-11eb-2e57-83829ceb7ab9\n# \u2560\u2550d043648a-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 ConvDiffMIPDECO\nusing Test\nusing jInv.Mesh\n\nprintln(\"=== 2D test === \")\n\ndomain = [0. 3. 0 1. ]\nn      = 2*[7 9 ]\nM      = getRegularMesh(domain,n)\nbc = (:dir,:neu,:neu,:neu)\ngd = X->sin.(X[:,2]*pi)\npFor = getConvDiffFEMParam(M,bc=bc,gd=gd)\n\nA,B,b = getConvDiffFEMConstraintsAMPL(M,gd=gd)\n\nmc = rand(M.nc); \ndobs = getData(mc,pFor)\nutrue = pFor.Fields;\nutest = A\\(B*mc+b); # -->    A *u = B*m + b\n@test norm(utrue-utest)/norm(utrue) < 1e-10\n\n\nprintln(\"=== 3D test === \")\n\ndomain = [0. 3. 0 1. 0 2.]\nn      = 2*[7 9 12]\nM      = getRegularMesh(domain,n)\nbc = (:dir,:neu,:neu,:neu,:neu,:neu)\ngd = X->sin.(X[:,2]*pi)\npFor = getConvDiffFEMParam(M,bc=bc,gd=gd)\n\nA,B,b = getConvDiffFEMConstraintsAMPL(M,gd=gd)\n\nmc = rand(M.nc); \ndobs = getData(mc,pFor)\nutrue = pFor.Fields;\nutest = A\\(B*mc+b);\n@test norm(utrue-utest)/norm(utrue) < 1e-10\n", "meta": {"hexsha": "b3cd7947ba4559370097096c4dcac8b0db476fd1", "size": 838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testGetConvDiffFEMConstraintsAMPL.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": "test/testGetConvDiffFEMConstraintsAMPL.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": "test/testGetConvDiffFEMConstraintsAMPL.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": 21.4871794872, "max_line_length": 46, "alphanum_fraction": 0.6026252983, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7717249603121639}}
{"text": "using Flux, Random, LinearAlgebra, CSV\nusing Flux.Optimise: update!\nRandom.seed!(0)\n\ndata = CSV.read(\"../data/L1L2data.csv\")\nxVals, yVals = Array{Float64}(data.X), Array{Float64}(data.Y)\n\neta = 0.05\nepsilon = 10^-7\n\nb = rand(2)\n\npredict(x) = b[1] .+ b[2]*x\nloss(x,y) = sum((y .- predict(x)).^2)\nopt = ADAM(eta)\n\niter, gradNorm = 0, 1.0\nwhile gradNorm >= epsilon\n    gs = gradient(()->loss(xVals,yVals),params(b))\n    update!(opt,b,gs[b])\n    gradNorm = norm(gs[b])\n    global iter += 1\nend\n\nprintln(\"Number of iterations: \", iter)\nprintln(\"Coefficients:\", b)", "meta": {"hexsha": "e5faa1e4e3845d93f5f77c93c9e2d63b3f101e2b", "size": 558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "9_chapter/fluxADAMsimpleRegression.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": "9_chapter/fluxADAMsimpleRegression.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": "9_chapter/fluxADAMsimpleRegression.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": 21.4615384615, "max_line_length": 61, "alphanum_fraction": 0.6379928315, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7717249497347731}}
{"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": "using Test\nusing Plots\n\nimport Pkg\nPkg.add(\"ToeplitzMatrices\")\nPkg.add(\"SparseArrays\")\n\nimport SparseArrays.spdiagm\nimport LinearAlgebra.I\nimport ToeplitzMatrices.Toeplitz\n\n# 22\nn = 1000\ne = ones(n)\n\nK = spdiagm(-1 => -e[1:999], 0 => e * 2, 1 => -e[1:999])\n\n@test K[1,1] == 2.0\n@test K[2,1] == -1.0\n@test K[1,2] == -1.0\n@test K[500,456] == 0.0\n@test K[75,22] == 0.0\n@test K[1000,999] == -1.0\n@test K[1000,1000] == 2.0\n@test K[999,1000] == -1.0\n\nu = K \\ e\nplot(u)\n\n# 23\nA = rand(Float64, 4, 3)\n\nK\u2082 = spdiagm(-1 => A[:,1], 0 => A[:,2], 1 => A[:,3])\n\n# last 2 items is left out -> last(A[:,1]) and last(A[:,3])\nK\u2093 = convert(Array{Float64}, K\u2082)\n\n@test K\u2093[5,4] == last(A[:,1]) && K\u2093[4,5] == last(A[:,3])\n\n# 24\n@test spdiagm(0 => ones(100)) == I(100)\n\n# 26\nv = [2, -1, zeros(2)..., -1]\nToeplitz(v, v)\n\n# 27\nA\u2080 = [\n  -1 1 0 0\n  0 -1 1 0\n  0 0 -1 1\n]\n\nK = A\u2080 * A\u2080'\n\nA\u2081 = A\u2080[:,2:4]\n\nT = A\u2081 * A\u2081'\n\nA\u2082 = A\u2080[:,2:3]\n\nB = A\u2082 * A\u2082'\n", "meta": {"hexsha": "d2344b16532967838510ed292f5adebe5426832f", "size": 917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.AppliedLInearAlgebra/1.FourSpecialMatrices/ProblemSet/22-end.jl", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "1.AppliedLInearAlgebra/1.FourSpecialMatrices/ProblemSet/22-end.jl", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_issues_repo_licenses": ["MIT"], "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.AppliedLInearAlgebra/1.FourSpecialMatrices/ProblemSet/22-end.jl", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 14.5555555556, "max_line_length": 59, "alphanum_fraction": 0.5299890949, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.771716098536091}}
{"text": "\"\"\"\nx = admm(A, B; ...)\n\nSolves non-negative least-squares problem by the Alternating Direction Method\nof Multipliers (ADMM).\n\nOptional arguments:\n    \u03c1: penalty parameter (set heuristically by default)\n    \u03b5: 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          \u03c1=max(0.1,vecnorm(A)^2/size(A,2)),\n\t          \u03b5=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\u03c1 = A'*A + eye(k)*\u03c1\n\n\t# Cache cholesky factorization\n\tL = cholfact(AtA\u03c1)\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+\u03c1*(Z-U))\n\t\n\t# Solve\n\twhile vecnorm(X-Z) > \u03b5\n\t\tZ = max(0,X+U)\n\t\tU = U+X-Z\n\t\tX = L \\ (AtB+\u03c1*(Z-U))\n\tend\n\n\t# Z \u2248 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 \ud835\udc39\u209a where `P = 2\u00b2\u2075\u2076 - 2\u00b3\u00b2 - 977`\"\nstruct FieldElement <: Number\n     \ud835\udc5b::BigInt\n     FieldElement(\ud835\udc5b) = !infield(\ud835\udc5b) ? throw(NotInField()) : new(\ud835\udc5b)\nend\n\nFieldElement(x::FieldElement) = x\nFieldElement(x::Union{Int128, Int64, Int32, Int16, Int8, Unsigned}) = FieldElement(big(x))\n\ud835\udc39 = FieldElement\n\n\"Formats FieldElement showing \ud835\udc5b in hexadecimal format\"\nfunction show(io::IO, z::FieldElement)\n    print(io, string(z.\ud835\udc5b, base = 16),\"\\n(in scep256k1 field)\")\nend\n\n==(\ud835\udc4b\u2081::FieldElement, \ud835\udc4b\u2082::FieldElement) = \ud835\udc4b\u2081.\ud835\udc5b == \ud835\udc4b\u2082.\ud835\udc5b\n==(::FieldElement, ::Integer) = false\n+(\ud835\udc4b\u2081::FieldElement, \ud835\udc4b\u2082::FieldElement) = \ud835\udc39(mod(\ud835\udc4b\u2081.\ud835\udc5b + \ud835\udc4b\u2082.\ud835\udc5b, P))\n-(\ud835\udc4b\u2081::FieldElement, \ud835\udc4b\u2082::FieldElement) = \ud835\udc39(mod(\ud835\udc4b\u2081.\ud835\udc5b - \ud835\udc4b\u2082.\ud835\udc5b, P))\n*(\ud835\udc4b\u2081::FieldElement, \ud835\udc4b\u2082::FieldElement) = \ud835\udc39(mod(\ud835\udc4b\u2081.\ud835\udc5b * \ud835\udc4b\u2082.\ud835\udc5b, P))\n*(\ud835\udc50::Integer, \ud835\udc4b::FieldElement) = \ud835\udc39(mod(\ud835\udc50 * \ud835\udc4b.\ud835\udc5b, P))\n*(\ud835\udc4b::FieldElement, \ud835\udc50::Integer) = *(\ud835\udc50, \ud835\udc4b)\n^(\ud835\udc4b::FieldElement, \ud835\udc58::Int) = \ud835\udc39(powermod(\ud835\udc4b.\ud835\udc5b, mod(\ud835\udc58, (P - 1)), P))\n/(\ud835\udc4b\u2081::FieldElement, \ud835\udc4b\u2082::FieldElement) = \ud835\udc39(mod(\ud835\udc4b\u2081.\ud835\udc5b * powermod(\ud835\udc4b\u2082.\ud835\udc5b, P - 2, P), P))\ndiv(\ud835\udc4b\u2081::FieldElement, \ud835\udc4b\u2082::FieldElement) = \ud835\udc4b\u2081 / \ud835\udc4b\u2082\ninv(\ud835\udc4b::FieldElement) = \ud835\udc39(powermod(\ud835\udc4b.\ud835\udc5b, mod(-1, (P - 1)), P))\nsqrt(\ud835\udc4b::FieldElement) = \ud835\udc4b^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": "\nprintln(\"testing ransac\")\n\n# Just a simple line fitting test for the moment\n# Adapted from fitlinedemo()\noutliers = 0.2\nsigma = 0.02\noutsigma = 30*sigma  # outlying points have a distribution that is\n                     # 30 times as spread as the inlying points\nnpts = 100           # Number of 3D data points\t\nvpts = round(Int, (1-outliers)*npts)  # No of valid points\nopts = npts - vpts                    # No of outlying points\n\n# Define a line:\n#    Y = m*X\n#    Z = 0\nm = 6    \n# Generate npts points in the line\nX = rand(1,npts)\nY = m*X\nZ = zeros(size(Y))\n\nXYZ =  [X\n    \tY\n    \tZ]\n\n# Add uniform noise of +/-sigma\nXYZ = XYZ + (2*rand(size(XYZ))-1)*sigma\n\n# Generate opts random outliers\nn = size(XYZ,2)\nind = randperm(n)[1:opts]  # get a random set of point indices of length opts \n\n\n# Perform RANSAC fitting of the line\nt = 0.02  # inlier tolerance\n(V, P, inliers) = ransacfitline(XYZ, t)\n\n# get slope of line and test values with a generous tolerance given\n# the stochasic nature of things\nslope = (V[2,2]-V[2,1])/(V[1,2]-V[1,1])\n@test abs(slope-m) < 0.2\n@test maximum(V[3,:]) < 0.1  # Check Z is close to 0\n", "meta": {"hexsha": "ce31b39b17cf791ae6a8118af40954745f3bb9f6", "size": 1121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_ransac.jl", "max_stars_repo_name": "JuliaPackageMirrors/ImageProjectiveGeometry.jl", "max_stars_repo_head_hexsha": "5d31c1bc3d45178121b846f85d0b28fe0c517174", "max_stars_repo_licenses": ["MIT"], "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_ransac.jl", "max_issues_repo_name": "JuliaPackageMirrors/ImageProjectiveGeometry.jl", "max_issues_repo_head_hexsha": "5d31c1bc3d45178121b846f85d0b28fe0c517174", "max_issues_repo_licenses": ["MIT"], "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_ransac.jl", "max_forks_repo_name": "JuliaPackageMirrors/ImageProjectiveGeometry.jl", "max_forks_repo_head_hexsha": "5d31c1bc3d45178121b846f85d0b28fe0c517174", "max_forks_repo_licenses": ["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.4772727273, "max_line_length": 78, "alphanum_fraction": 0.632471008, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7716963556102567}}
{"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 \u2264 t \u2264 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\u0394f = fs / (l - 1)\n\u0394t = ts\nEt = sum(abs.(x).^2) * \u0394t\nEf = sum(psd) * \u0394f / (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\u2212r)!\n,where r \u2264 n, n! = n\u00d7(n\u22121)\u00d7...\u00d73\u00d72\u00d71, 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 \u2264 n \u2264 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 \u2260 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\u207d\u1d4f\u207a\u00b9\u207e = D\u207b\u00b9(b - Rx\u207d\u1d4f\u207e),\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    \u03c9\n    maxiter\n    function JacobiSolver(A, tol, \u03c9=2./3, maxiter = 10)\n        D = Diagonal(diag(A))\n        new(A, inv(D), A-D, tol, \u03c9, maxiter)\n    end\nend\n\n# This implementation assumes that x is reasonably \"close\" to b; this\n# is the case if A = I + \u039e, with |\u039e| << 1.\nfunction solve!(b::StridedVecOrMat, J::JacobiSolver)\n    xp = ones(b)\n    x = xp\n    for k = 1:J.maxiter\n        x = J.\u03c9*(J.Dinv*(b - J.R*xp)) + (1-J.\u03c9)*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    \u2297(A, B)\n\nCompute the kronecker product, ``A\\\\otimes B``.\n\n# Examples\n```julia-repl\njulia> [1 0; 0 1]\u2297[1 0; 0 -1]\n4\u00d74 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\u2297(A, B) = kron(A, B)\n\n\n\"\"\"\n    \u2297(A, B, C...)\n\nCompute the kronecker product, ``A\\\\otimes B\\\\otimes C \\\\cdots``.\n\"\"\"\nfunction \u2297(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": "using Test\n\nfunction factorial(x)\n    if x == 1\n        return 1\n    end\n    return x * factorial(x-1)\nend\n\n@test factorial(5) == 120\n", "meta": {"hexsha": "96675b033b8829c8c3ecd849651cb4bc50664ed4", "size": 134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "03_recursion/julia/03_factorial.jl", "max_stars_repo_name": "filchyboy/grokking_algorithms_work", "max_stars_repo_head_hexsha": "16dace97610e2cb0938704e2b8cfd6e92d6b024d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-03-11T00:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:19:23.000Z", "max_issues_repo_path": "book04grokkingAlgo/03_recursion/julia/03_factorial.jl", "max_issues_repo_name": "mcuallen/CodeLrn2019", "max_issues_repo_head_hexsha": "adc727d92904c5c5d445a2621813dfa99474206d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 160, "max_issues_repo_issues_event_min_datetime": "2021-04-26T19:04:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T20:18:37.000Z", "max_forks_repo_path": "book04grokkingAlgo/03_recursion/julia/03_factorial.jl", "max_forks_repo_name": "mcuallen/CodeLrn2019", "max_forks_repo_head_hexsha": "adc727d92904c5c5d445a2621813dfa99474206d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-04-26T19:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:36:29.000Z", "avg_line_length": 12.1818181818, "max_line_length": 29, "alphanum_fraction": 0.5895522388, "num_tokens": 42, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7716782618120768}}
{"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, \u03bb=1.0)\n\nGiven `ind_S` the indicator function of a convex set ``S``, and an optional positive parameter `\u03bb`, returns the (weighted) squared Euclidean distance from ``S``, that is function\n```math\ng(x) = \\\\tfrac{\u03bb}{2}\\\\mathrm{dist}_S^2(x) = \\\\min \\\\left\\\\{ \\\\tfrac{\u03bb}{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 \u03bb 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 \u21a6 (\u03bb/2) inf { ||x-y||^2 : y \u2208 S} \"\nfun_params(f::SqrDistL2) = string(\"\u03bb = $(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) \u00f7 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": "using NestedSamplers.Bounds: randball, volume_prefactor\n\n@testset \"Rand Sphere\" begin\n    for _ in 1:100, k in 1:10\n        x = randball(rng, Float64, k)\n        @test sum(t->t^2, x) < 1\n    end\nend\n\n@testset \"Volume Prefactor\" begin\n    @test volume_prefactor(1) \u2248 2\n    @test volume_prefactor(2) \u2248 \u03c0\n    @test volume_prefactor(3) \u2248 4 / 3 * \u03c0\n    @test volume_prefactor(4) \u2248 1 / 2 * \u03c0^2\n    @test volume_prefactor(5) \u2248 8 / 15 * \u03c0^2\n    @test volume_prefactor(6) \u2248 1 / 6 * \u03c0^3\n    @test volume_prefactor(7) \u2248 16 / 105 * \u03c0^3\n    @test volume_prefactor(9) \u2248 32 / 945 * \u03c0^4\nend\n", "meta": {"hexsha": "7976e778af0787cffe8af2eceeb852e1b35b5f15", "size": 575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bounds/helpers.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": "test/bounds/helpers.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": "test/bounds/helpers.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": 28.75, "max_line_length": 55, "alphanum_fraction": 0.6173913043, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7716782524565436}}
{"text": "using MLJ\nusing  PrettyPrinting\nimport DataFrames: DataFrame\nimport Statistics\n\nX, y = @load_reduced_ames\nX = DataFrame(X)\n@show size(X)\nfirst(X, 3) |> pretty\n\n@show y[1:3]\nscitype(y)\n\ncreg = ConstantRegressor()\n\ncmach = machine(creg, X, y)\n\ntrain, test = partition(collect(eachindex(y)), 0.70, shuffle=true); # 70:30 split\nfit!(cmach, rows=train)\ny\u0302 = predict(cmach, rows=test)\ny\u0302[1:3] |> pprint\n\ny\u0302 = predict_mean(cmach, rows=test)\ny\u0302[1:3]\n\nrmsl(y\u0302, y[test])\n\nRidgeRegressor = @load RidgeRegressor pkg=\"MultivariateStats\"\nKNNRegressor = @load KNNRegressor\n\nXs = source(X)\nys = source(y)\n\nhot = machine(OneHotEncoder(), Xs)\n\nW = transform(hot, Xs)\nz = log(ys);\n\nknn   = machine(KNNRegressor(K=5), W, z)\nridge = machine(RidgeRegressor(lambda=2.5), W, z)\n\nz\u0302\u2081 = predict(ridge, W)\nz\u0302\u2082 = predict(knn, W)\n\nz\u0302 = 0.3z\u0302\u2081 + 0.7z\u0302\u2082;\n\ny\u0302 = exp(z\u0302);\n\nfit!(y\u0302, rows=train)\nypreds = y\u0302(rows=test)\nrmsl(y[test], ypreds)\n\nmutable struct KNNRidgeBlend <: DeterministicComposite\n    knn_model::KNNRegressor\n    ridge_model::RidgeRegressor\n    knn_weight::Float64\nend\n\nfunction MLJ.fit(model::KNNRidgeBlend, verbosity::Int, X, y)\n    Xs = source(X)\n    ys = source(y)\n    hot = machine(OneHotEncoder(), Xs)\n    W = transform(hot, Xs)\n    z = log(ys)\n    ridge_model = model.ridge_model\n    knn_model = model.knn_model\n    ridge = machine(ridge_model, W, z)\n    knn = machine(knn_model, W, z)\n\n    z\u0302 = model.knn_weight * predict(knn, W) + (1.0 - model.knn_weight) * predict(ridge, W)\n    y\u0302 = exp(z\u0302)\n\n    mach = machine(Deterministic(), Xs, ys; predict=y\u0302)\n    return!(mach, model, verbosity)\nend\n\nkrb = KNNRidgeBlend(KNNRegressor(K=5), RidgeRegressor(lambda=2.5), 0.3)\nmach = machine(krb, X, y)\nfit!(mach, rows=train)\n\npreds = predict(mach, rows=test)\nrmsl(y[test], preds)\n\n@show krb.knn_weight\n@show krb.knn_model.K\n@show krb.ridge_model.lambda\n\nparams(krb) |> pprint\n\nk_range = range(krb, :(knn_model.K), lower=2, upper=100, scale=:log10)\nl_range = range(krb, :(ridge_model.lambda), lower=1e-4, upper=10, scale=:log10)\nw_range = range(krb, :(knn_weight), lower=0.1, upper=0.9)\n\nranges = [k_range, l_range, w_range]\n\ntuning = Grid(resolution=3)\nresampling = CV(nfolds=6)\n\ntm = TunedModel(model=krb, tuning=tuning, resampling=resampling,\n                ranges=ranges, measure=rmsl)\n\nmtm = machine(tm, X, y)\nfit!(mtm, rows=train);\n\nkrb_best = fitted_params(mtm).best_model\n@show krb_best.knn_model.K\n@show krb_best.ridge_model.lambda\n@show krb_best.knn_weight\n\npreds = predict(mtm, rows=test)\nrmsl(y[test], preds)\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "e2e77faa51f7a237aa953ddd9df9f134ed03ec67", "size": 2588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__site/__generated/EX-AMES/tutorial-raw.jl", "max_stars_repo_name": "JuliaAI/DataScienceTutorials.jl", "max_stars_repo_head_hexsha": "76b1d3d1a5045c62b104a8358e4c37049f15ccb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-08-09T11:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:20:43.000Z", "max_issues_repo_path": "__site/__generated/EX-AMES/tutorial-raw.jl", "max_issues_repo_name": "alan-turing-institute/MLJTutorials", "max_issues_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-10-22T00:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T14:38:09.000Z", "max_forks_repo_path": "__site/__generated/EX-AMES/tutorial-raw.jl", "max_forks_repo_name": "alan-turing-institute/MLJTutorials", "max_forks_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-11-20T16:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T11:55:15.000Z", "avg_line_length": 22.5043478261, "max_line_length": 90, "alphanum_fraction": 0.6881761978, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7716782523106351}}
{"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": "using SymPy\nusing Test\n\n@testset \"ODes\" begin\n    ## ODEs\n    x, a = Sym(\"x, a\")\n    F = SymFunction(\"F\")\n    ex = diff(F(x), x) - a*F(x)\n    ex1 = dsolve(ex)\n    ex2 = rhs(ex1) |> subs(Sym(:C1), 1) |> subs(a, 2)\n    @test ex2 == exp(2x)\n\n    t, = @syms t\n    X, Y = SymFunction(\"X, Y\")\n    eq = [Eq(diff(X(t),t), 12*t*X(t) + 8*Y(t)), Eq(diff(Y(t),t), 21*X(t) + 7*t*Y(t))]\n    dsolve(eq)\n\n\n    ## version 0.4+ allow use of u'(x) in lieu of diff(u(x), x) and `ivpsolve`\n    u = SymFunction(\"u\")\n    a, x, y, y0, y1 = symbols(\"a, x, y, y0, y1\")\n\n    @test dsolve(u'(x) - a*u(x), x, (u, 0, 1)) == Eq(u(x), exp(a*x))\n    @test dsolve(u'(x) - a*u(x), x, (u, 0, y1)) == Eq(u(x), y1*exp(a*x))\n    dsolve(u'(x) - a*u(x), x, (u, y0, y1)) # == Eq(u(x), y1 * exp(a*(x - y0)))\n    dsolve(x*u'(x) + x*u(x) + 1, x, (u, 1, 1))\n    dsolve((u'(x))^2 - a*u(x), x, (u, 0, 1))\n    dsolve(u''(x) - a * u(x), x, (u, 0, 1), (u', 0, 0))\n\n    F, G, K = SymFunction(\"F, G, K\")\n    eqn = F(x)*u'(y)*y + G(x)*u(y) + K(x)\n    dsolve(eqn, y, (u, 1, 0))\n\n    ## dsolve eqn has two answers, but we want to eliminate one\n    # based on initial condition\n    dsolve(u'(x) - (u(x)-1)*u(x)*(u(x)+1), x, (u, 0, 1//2))\nend\n", "meta": {"hexsha": "aaa4879ac767ecbd14c8f09a3a30c5d70914cc94", "size": 1185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-ode.jl", "max_stars_repo_name": "baggepinnen/SymPy.jl", "max_stars_repo_head_hexsha": "605551ebd78921ea6bc72b80e9894d023895bc94", "max_stars_repo_licenses": ["MIT"], "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-ode.jl", "max_issues_repo_name": "baggepinnen/SymPy.jl", "max_issues_repo_head_hexsha": "605551ebd78921ea6bc72b80e9894d023895bc94", "max_issues_repo_licenses": ["MIT"], "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-ode.jl", "max_forks_repo_name": "baggepinnen/SymPy.jl", "max_forks_repo_head_hexsha": "605551ebd78921ea6bc72b80e9894d023895bc94", "max_forks_repo_licenses": ["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": 85, "alphanum_fraction": 0.4565400844, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7716405289743675}}
{"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": "# ## \u591a\u9805\u5f0f\u56de\u5e30\n# ### \u4f8b52\n# sin\u95a2\u6570\u306b\u4e71\u6570\u3092\u8db3\u3057\u305f\u89b3\u6e2c\u30c7\u30fc\u30bf\u3092\u591a\u9805\u5f0f\u3067\u56de\u5e30\u3057\u307e\u3059\u3002\n# \\lineskip\n# \u30c7\u30fc\u30bf\u306e\u751f\u6210\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\u30015\u30017\u6b21\u306e\u591a\u9805\u5f0f\u3067\u56de\u5e30\u3057\u307e\u3059\u3002\n# \u591a\u9805\u5f0f\u56de\u5e30\u7528\u306b\u30c7\u30fc\u30bf\u30bb\u30c3\u30c8\u3092\u4f5c\u308b\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u305f\u306e\u3067\u3001\u3053\u308c\u3092\u4f7f\u3063\u3066\u307f\u307e\u3059\u3002\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    \u03b2\u0302 = multiple_regression(X,y)\n    y\u0302 = insert_ones(polynomial(x_seq,p))*\u03b2\u0302\n    plot!(p52, x_seq,y\u0302,label=\"p = $p\")\nend\nsavefig(p52,joinpath(@OUTPUT,\"fig6-1.svg\")) # hide\n# \\fig{fig6-1}\n# ### \u4f8b53\n# \u77e9\u5f62\u6ce2\u306b\u96d1\u97f3\u3092\u30ce\u30a4\u30ba\u3092\u306e\u305b\u305f\u30c7\u30fc\u30bf\u3092\u4f5c\u3063\u3066\u3001\u30d5\u30a3\u30c3\u30c6\u30a3\u30f3\u30b0\u3057\u307e\u3059\u3002\n# \u307e\u305a\u306f\u30c7\u30fc\u30bf\u3092\u751f\u6210\u3057\u307e\u3059\u3002\nusing Plots, Random\nRandom.seed!(123)\nn = 100; x = randn(n) * \u03c0\ny = abs.(round.(x) .%2) * 2  .- 1+ randn(n)*0.2 \np53 = scatter(x,y,label= false);\n# \u57fa\u5e95\u95a2\u6570\u304c\u3001$f_1(x) = 1$\u3001 $f_2(x) = \\cos(x) $\u3001 $f_3(x) = \\cos(2x)$\u3001\n# $f_4(x) = \\cos(3x)$\u306e\u5834\u5408\u3068\u3001$f_1(x) = 1$\u3001 $f_2(x) = \\sin(x) $\u3001 $f_3(x) = \\sin(2x)$\u3001\n# $f_4(x) = \\sin(4x)$\u306e\u5834\u5408\u3068\u3067\u305d\u308c\u305e\u308c\u56de\u5e30\u5206\u6790\u3057\u307e\u3059\u3002\n# \u6e96\u5099\u3068\u3057\u3066\u5148\u307b\u3069\u306epolynomial\u95a2\u6570\u3092\u3079\u304d\u4e57\u4ee5\u5916\u306b\u3082\u5bfe\u5fdc\u3067\u304d\u308b\u3088\u3046\u306b\u591a\u91cd\u30c7\u30a3\u30b9\u30d1\u30c3\u30c1\u3067\u62e1\u5f35\u3057\u307e\u3059\u3002\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)$\u306e\u533a\u9593\u3067\u30d5\u30a3\u30c3\u30c6\u30a3\u30f3\u30b0\u3057\u307e\u3059\u3002\nx_seq = -8:0.2:8\n# cos\u306e\u5834\u5408\nX_cos = polynomial(x,3,cos)\n\u03b2\u0302_cos = multiple_regression(X_cos,y)\ny\u0302_cos = insert_ones(polynomial(x_seq,3,cos))*\u03b2\u0302_cos;\n# sin\u306e\u5834\u5408\nX_sin = polynomial(x,3,sin)\n\u03b2\u0302_sin = multiple_regression(X_sin,y)\ny\u0302_sin = insert_ones(polynomial(x_seq,3,sin))*\u03b2\u0302_sin;\n# \u53ef\u8996\u5316\u3057\u307e\u3059\u3002\nplot!(p53,x_seq,y\u0302_cos,label=\"cos\")\nplot!(p53,x_seq,y\u0302_sin,label=\"sin\")\nsavefig(p53,joinpath(@OUTPUT,\"fig6-2.svg\")) # hide\n# \\fig{fig6-2}\n# \\lineskip\n# cos\u3092\u57fa\u5e95\u306b\u3068\u3063\u305f\u307b\u3046\u304c\u3001\u4e0a\u624b\u304f\u30d5\u30a3\u30c3\u30c6\u30a3\u30f3\u30b0\u3067\u304d\u308b\u3053\u3068\u304c\u78ba\u8a8d\u3067\u304d\u307e\u3057\u305f\u3002\n# ## \u30b9\u30d7\u30e9\u30a4\u30f3\u56de\u5e30\n# \u30b9\u30d7\u30e9\u30a4\u30f3\u56de\u5e30\u306b\u3064\u3044\u3066\u306f\u3001\u307e\u305a\u30b9\u30d7\u30e9\u30a4\u30f3\u306b\u95a2\u3059\u308b\u8907\u5408\u578b\u3092\u4f5c\u3063\u3066\u3001\n# function-like object\u3092\u5b9f\u88c5\u3057\u307e\u3057\u305f\u3002\n# spline_matrix\u95a2\u6570\u306f\u3001\u3042\u3068\u3067\u5909\u66f4\u3067\u304d\u308b\u3088\u3046\u306b\u30ad\u30fc\u30ef\u30fc\u30c9\u5f15\u6570\u306b\u3057\u307e\u3057\u305f\u3002\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#     \u03b2 = (X'X)\\X'y\n#     ypred = X_pred*\u03b2\n# end\n# (s::Spline)(x::Vector, y::Vector, x_pred::AbstractRange;kwargs...) = s(x,y,collect(x_pred);kwargs...)\n# ```\n# ### \u4f8b54\n# sin\u30ab\u30fc\u30d6\u306b\u4e71\u6570\u3092\u52a0\u3048\u305f\u30c7\u30fc\u30bf\u306b\u30b9\u30d7\u30e9\u30a4\u30f3\u56de\u5e30\u3067\u30d5\u30a3\u30c3\u30c6\u30a3\u30f3\u30b0\u3057\u307e\u3059\u3002\n# \u5206\u5272\u70b9\u6570\u304c7\u4ee5\u4e0a\u3067\u30c7\u30fc\u30bf\u306b\u8ffd\u968f\u3057\u3066\u3044\u308b\u3053\u3068\u304c\u308f\u304b\u308a\u307e\u3059\u3002\nusing Plots, Random\nusing Joe: Spline\nusing Joe\nRandom.seed!(123)\nn = 100; x = randn(n)*2\u03c0; 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\u03c0, xmax=2\u03c0, 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# ### \u4f8b56 \u81ea\u7136\u306a\u30b9\u30d7\u30e9\u30a4\u30f3\u66f2\u7dda\n# \u30b9\u30d7\u30e9\u30a4\u30f3\u66f2\u7dda\u306e\u4e21\u7aef\u304c\u76f4\u7dda\u306b\u306a\u3063\u3066\u3044\u308b\u3082\u306e\u3067\u3059\u3002\n# \u539f\u8457\u3067\u306f\u3001\u95a2\u6570d\u3068\u304b\u95a2\u6570h\u3092\u5b9a\u7fa9\u3057\u3066\u4f7f\u3063\u3066\u3044\u307e\u3057\u305f\u3002\n# \u305d\u3093\u306a\u3053\u3068\u306f\u3057\u305f\u304f\u306a\u3044\u3051\u3069\u3001\u3044\u3044\u540d\u524d\u3082\u306a\u3044\u306e\u3067\u3001\u95a2\u6570\u5185\u3067\u5b9a\u7fa9\u3057\u3066\u4f7f\u3046\u3053\u3068\u306b\u3057\u307e\u3057\u305f\u3002\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# \u4f8b54\u3068\u540c\u3058\u30c7\u30fc\u30bf\u306b\u3001\u305f\u3060\u306e\u30b9\u30d7\u30e9\u30a4\u30f3\u3068\u81ea\u7136\u306a\u30b9\u30d7\u30e9\u30a4\u30f3\u306e\u56de\u5e30\u3092\u9069\u7528\u3057\u3001\n# \u7d50\u679c\u3092\u53ef\u8996\u5316\u3057\u307e\u3059\u3002\u307e\u305a\u30c7\u30fc\u30bf\u306e\u751f\u6210\u3068\u30b9\u30d7\u30e9\u30a4\u30f3\u578b\u3092\u5b9a\u7fa9\u3057\u307e\u3059\u3002\nusing Plots, Random\nusing Joe: Spline\nusing Joe\nRandom.seed!(123)\nn = 100; x = randn(n)*2\u03c0; y = sin.(x) + 0.2randn(n)\nspline6 = Spline(xmin=-5, xmax=5, K=6);\nspline11 = Spline(xmin=-5, xmax=5, K=11);\n# \u6b21\u306b\u56de\u5e30\u3092\u884c\u3044\u307e\u3059\u3002\u81ea\u7136\u306a\u30b9\u30d7\u30e9\u30a4\u30f3\u3067\u56de\u5e30\u3092\u884c\u3046\u5834\u5408\u306b\u306f\u3001\u30ad\u30fc\u30ef\u30fc\u30c9\u5f15\u6570\u3092\u6307\u5b9a\u3057\u307e\u3059\u3002\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# \u53ef\u8996\u5316\u3057\u307e\u3059\u3002\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# ## \u5e73\u6ed1\u5316\u30b9\u30d7\u30e9\u30a4\u30f3\n# \u5e73\u6ed1\u5316\u30b9\u30d7\u30e9\u30a4\u30f3\u306f\u533a\u5207\u308a\u70b9\u3092\u6307\u5b9a\u3059\u308b\u3068\u304d\u306b\u30c7\u30fc\u30bf\u70b9\u81ea\u8eab\u3092\u4f7f\u3063\u3066\u3044\u305f\u306e\u3067\u3001\n# \u4ee5\u4e0b\u306e\u3088\u3046\u306b\u66f8\u304d\u76f4\u3057\u307e\u3057\u305f\u3002(function-like object\u306b\u3059\u308b\u307e\u3067\u3082\u306a\u304b\u3063\u305f\u3002)\n# ```julia\n# struct SmoothingSpline\n#     x::Vector\n# end\n# function (s::SmoothingSpline)(y::Vector,x_pred::Union{Vector,AbstractRange};\u03bb=0)\n#     x = s.x\n#     X = smoothing_spline_matrix(x,x)\n#     G = green_silverman(x)\n#     \u03b3 = (X'X + \u03bb*G)\\X'y\n#     X_pred = smoothing_spline_matrix(x_pred,x)\n#     ypred = X_pred*\u03b3\n# end\n# ```\n# \u305f\u3060\u3057\u3001smoothing_spline_matrix\u3068green_silverman\u95a2\u6570\u306f\u4ee5\u4e0b\u306e\u901a\u308a\u3067\u3059\u3002\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# ### \u4f8b57\n# $x\\in(-5,5)$\u306e\u4e00\u69d8\u5206\u5e03\u304b\u3089\u30b5\u30f3\u30d7\u30eb\u3092\u751f\u6210\u3057\u307e\u3059\u3002\n# \u539f\u8457\u3067\u306f\u3001\u30b5\u30f3\u30d7\u30eb\u751f\u6210\u30b3\u30fc\u30c9\u304c\u9593\u9055\u3063\u3066\u3044\u308b\u3088\u3046\u306a\u306e\u3067\u3001ipynb\u306e\u8a18\u8ff0\u3092\u53c2\u7167\u3057\u307e\u3057\u305f\u3002\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\u03bb_set = [40,400,1000]\nfor \u03bb in \u03bb_set\n    global u_seq, p57 # hide\n    v_seq = sspline(y,u_seq,\u03bb=\u03bb)\n    plot!(p57,u_seq,v_seq,label=\"\u03bb = $\u03bb\")\nend\np57\nplot!(p57,u_seq,sspline(y,u_seq,\u03bb=1),label=\"\u03bb = 1\")\nsavefig(p57,joinpath(@OUTPUT, \"fig6-8.svg\")) # hide\n# \\fig{fig6-8}\n# \\lineskip\n# $\\lambda$\u304c\u5927\u304d\u304f\u306a\u308b\u3068\u3001\u76f4\u7dda\u306b\u8fd1\u304f\u306a\u3063\u3066\u3044\u304f\u3088\u3046\u3067\u3059\u3002\n# ### \u4f8b58 \u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u306b\u3088\u308b\u5e73\u6ed1\u5316\u30b9\u30d7\u30e9\u30a4\u30f3\u306e\u6b63\u5247\u5316\u4e57\u6570\u306e\u6700\u9069\u5316\n# 3\u7ae0\u3067\u4f7f\u3063\u305f\u7dda\u5f62\u56de\u5e30\u306e\u5834\u5408\u306e\u9ad8\u901f\u306a\u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u306e\u516c\u5f0f\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# \u3092\u5229\u7528\u3057\u3066\u3001$\\lambda$\u306e\u6700\u9069\u5316\u3092\u884c\u3044\u307e\u3059\u3002\n# \u4ee5\u4e0b\u306ecv_ss_fast\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u3066\u5229\u7528\u3057\u307e\u3059\u3002\n# ```julia\n# function cv_ss_fast(X::AbstractArray,y::Vector,G::AbstractArray,K::Int;\u03bb=0)\n#     n = length(y); m = round(Int,n/K)\n#     H = X*((X'X + \u03bb*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\u7ae0\u306e\u4f7f\u3063\u305fcv_fast\u95a2\u6570\u3068\u307b\u307c\u540c\u69d8\u3067\u3059\u304c\u3001\u5b9a\u6570\u9805\u306e\u5217\u3092\u4ed8\u3051\u306a\u3044\u3053\u3068\u3068\u3001\n# \u6b63\u5247\u5316\u4e57\u6570\u304c\u5f15\u6570\u306b\u306a\u3063\u3066\u3044\u308b\u3053\u3068\u3001\u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u8aa4\u5dee\u3060\u3051\u3067\u306a\u304f\u3001\n# H\u306e\u30c8\u30ec\u30fc\u30b9\u3082\u8fd4\u3057\u3066\u3044\u308b\u3053\u3068\u306a\u3069\u304c\u7570\u306a\u308a\u307e\u3059\u3002\n# \u307e\u305a\u306f\u30c7\u30fc\u30bf\u3092\u751f\u6210\u3057\u307e\u3059\u3002\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\u3068G\u3092\u8a08\u7b97\u3057\u307e\u3059\u3002\nX = Joe.smoothing_spline_matrix(x,x);\nG = Joe.green_silverman(x);\n# \u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u8aa4\u5dee\u3068H\u306e\u30c8\u30ec\u30fc\u30b9(\u6709\u52b9\u81ea\u7531\u5ea6)\u3092\u6c42\u3081\u307e\u3059\u3002\nresult = hcat([collect(Joe.cv_ss_fast(X,y,G,n,\u03bb=\u03bb)) for \u03bb in 1:50]...)\nusing Plots\np58 = plot(result[2,:], result[1,:],label= false, \n            xlabel=\"\u6709\u52b9\u81ea\u7531\u5ea6\", ylabel=\"CV\u306b\u3088\u308b\u4e88\u6e2c\u8aa4\u5dee\",\n            title = \"\u6709\u52b9\u81ea\u7531\u5ea6\u3068CV\u306b\u3088\u308b\u4e88\u6e2c\u8aa4\u5dee\")\nsavefig(p58,joinpath(@OUTPUT,\"fig6-9.svg\")) \n# \\fig{fig6-9}\n# \\lineskip\n# (\u6ce8)\u3061\u306a\u307f\u306b\u751f\u6210\u3059\u308b\u30c7\u30fc\u30bf\u306b\u3088\u3063\u3066\u3001\u30b0\u30e9\u30d5\u306e\u5f62\u306f\u304b\u306a\u308a\u5909\u308f\u308a\u307e\u3059\u3002\n# ## \u5c40\u6240\u56de\u5e30\n# ### \u4f8b60 nadaraya-watson\u63a8\u5b9a\u91cf\n# nadaraya-watson\u63a8\u5b9a\u91cf\u306e\u8a08\u7b97\u306e\u5b9f\u88c5\u3067\u3059\u3002\n# \u30ab\u30fc\u30cd\u30eb\u306f\u95a2\u6570\u306e\u5f15\u6570\u306b\u3057\u3066\u3001\u5225\u306e\u3082\u306e\u306b\u5909\u66f4\u3067\u304d\u308b\u3088\u3046\u306b\u3057\u307e\u3057\u305f\u3002(\u3053\u3053\u3067\u306f\u4ed6\u306e\u30ab\u30fc\u30cd\u30eb\u306f\u51fa\u3066\u304d\u307e\u305b\u3093\u304c\u3002)\n# ```julia\n# epanechnikov(x,y,\u03bb) = norm(x-y)/\u03bb |> 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;\u03bb=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,\u03bb)*y_observed[i]\n#         T += kk(x_observed[i],x_pred,\u03bb)\n#     end\n#     result = T == 0 ? 0 : S/T\n#     return result\n# end\n# \u30d9\u30af\u30c8\u30eb\u5316\u306b\u3082\u5bfe\u5fdc\u3057\u3066\u3044\u307e\u3059\u3002\n# function nadaraya_watson_estimator(x_observed::Vector,y_observed::Vector,kk::Function,x_pred::Union{Vector,AbstractRange};\u03bb=1.0) \n#     y_pred = [nadaraya_watson_estimator(x_observed,y_observed,kk,xp; \u03bb) for xp in x_pred]\n# end\n# ```\n# \\note{epanechnikoc\u95a2\u6570\u306b\u7d76\u5bfe\u5024\u306e\u51e6\u7406\u306f\u5fc5\u8981\u306b\u306a\u308a\u307e\u3059\u304c\u3001abs\u95a2\u6570\u3092\u4f7f\u3046\u3088\u308a\u3082LinearAlgebra.jl\u306enorm\u3092\u4f7f\u3063\u305f\u65b9\u304c\u3001\u591a\u6b21\u5143\u5316\u306b\u5bfe\u5fdc\u3067\u304d\u3066\u826f\u3044\u3068\u601d\u3044\u307e\u3059\u3002}\n# \u30c8\u30a4\u30c7\u30fc\u30bf\u3068\u3057\u3066sin\u95a2\u6570\u306b\u30ce\u30a4\u30ba\u3092\u306e\u305b\u305f\u30c7\u30fc\u30bf\u3092\u4f5c\u6210\u3057\u307e\u3059\u3002\nusing Random\nRandom.seed!(123)\nn=250;x = 2randn(n); y = sin.(2\u03c0*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$\u306e\u5834\u5408\u306b\u30d7\u30ed\u30c3\u30c8\u3057\u3066\u307f\u307e\u3059\u3002\nplot!(p58,xx,nadaraya_watson_estimator(x,y,epanechnikov,xx;\u03bb=0.05),\n         label=\"\u03bb = 0.05\");\nplot!(p58,xx,nadaraya_watson_estimator(x,y,epanechnikov,xx;\u03bb=0.25),\n         label=\"\u03bb = 0.25\");\n# \u30af\u30ed\u30b9\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u3067$\\lambda$\u3092\u6700\u9069\u5316\u3057\u3066\u30d7\u30ed\u30c3\u30c8\u3057\u3066\u307f\u307e\u3059\u3002\n\u03bb_seq = 0.05:0.01:1\nSS_min = Inf\n\u03bb_best = \u03bb_seq[1]\nfor \u03bb in \u03bb_seq\n    global SS_min, \u03bb_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];\u03bb=\u03bb)\n        SS += dot(y[test]-y_pred,y[test]-y_pred)\n    end\n    if SS < SS_min\n        SS_min = SS\n        \u03bb_best = \u03bb\n    end\nend\n\nplot!(p58,xx,nadaraya_watson_estimator(x,y,epanechnikov,xx;\u03bb=\u03bb_best), label=\"\u03bb = \u03bb_best\")\nsavefig(p58,joinpath(@OUTPUT,\"fig6-10.svg\")) # hide\n# \\fig{fig6-10}\n# \\lineskip\n# $\\lambda_{best}$\u306f\u3053\u306e\u7a0b\u5ea6\u306e\u5024\u306b\u306a\u308b\u3088\u3046\u3067\u3059\u3002\n@show \u03bb_best;\n# ### \u4f8b61 \u5c40\u6240\u7dda\u5f62\u56de\u5e30\n# \u30ab\u30fc\u30cd\u30eb\u95a2\u6570$k$\u3092\u6210\u5206\u306b\u6301\u3063\u305f\u5bfe\u89d2\u884c\u5217$\\bm{W}$\u3092\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# \u3068\u3057\u305f\u6642\u3001\n# $$ L \\coloneqq (\\bm{y} - \\bm{X\u03b2}(x))^\\mathsf{T}\\bm{W}(\\bm{y} - \\bm{X\u03b2}(x)) $$\n# \u3092\u6700\u5c0f\u5316\u3059\u308b$\\bm{\\beta}(x)$\u3092\u6c42\u3081\u307e\u3059\u3002\n# $$ \\dfrac{\\partial L}{\\partial \\bm{\\beta}} = \n# -2\\bm{X}^\\mathsf{T}\\bm{W}(\\bm{y} - \\bm{X\u03b2}(x))=0$$\u3068\u304a\u304f\u3068\u3001\n# $$ \\bm{\\beta}(x) = (\\bm{X}^\\mathsf{T}\\bm{WX})^{-1}\\bm{X}^\\mathsf{T}\\bm{Wy}$$\n# \u3067\u4fc2\u6570\u3092\u6c42\u3081\u308b\u3053\u3068\u304c\u3067\u304d\u307e\u3059\u3002\u3053\u306e\u51e6\u7406\u3092\u95a2\u6570\u3067\u5b9f\u88c5\u3059\u308b\u308f\u3051\u3067\u3059\u304c\u3001\u539f\u8457\u306elocal\u3068\u3044\u3046\u95a2\u6570\u540d\u306f\u826f\u304f\u306a\u3044\u306e\u3067\u3001\n# local_regression\u3068\u3044\u3046\u540d\u524d\u3067\u5b9f\u88c5\u3057\u307e\u3057\u305f\u3002\u4f8b\u3067\u306f1\u6b21\u5143\u306b\u9650\u5b9a\u3057\u3066\u3044\u307e\u3057\u305f\u304c\u3001\n# \u591a\u6b21\u5143\u30c7\u30fc\u30bf\u306b\u3082\u5bfe\u5fdc\u3055\u305b\u3066\u3044\u307e\u3059\u3002\n# ```julia\n# function local_regression(x::Matrix{T}, \n#                           y::Vector{T},\n#                           kernel::Function;\n#                           x_pred=x, \u03bb=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,:],\u03bb) for i in 1:N] |> diagm\n#         \u03b2\u0302 = (X'*W*X)\\X'*W*y\n#         y_pred[j] = dot(insert_ones(x_pred[j,:]),\u03b2\u0302)\n#     end\n#     return y_pred\n# end\n# function local_regression(x::Vector{T}, y::Vector{T},kernel::Function;x_pred=x,\u03bb=1) where {T<:Number}\n#     return local_regression(x[:,:],y,kernel;x_pred=x_pred[:,:],\u03bb=\u03bb)\n# end\n# ```\n# \u30c8\u30a4\u30c7\u30fc\u30bf\u3068\u3057\u3066sin\u95a2\u6570\u306b\u30ce\u30a4\u30ba\u3092\u306e\u305b\u305f\u30c7\u30fc\u30bf\u3092\u4f5c\u6210\u3057\u307e\u3059\u3002\nusing Random,Joe\nRandom.seed!(123)\nn=30; x = 2\u03c0*rand(n) .- \u03c0; y = sin.(x) .+ randn()\np61 = scatter(x,y,label=false)\nm = 200;U = -\u03c0:\u03c0/m:\u03c0;\n# \u6b63\u5247\u5316\u30d1\u30e9\u30e1\u30fc\u30bf$\\lambda=1$\u306e\u6761\u4ef6\u3067\u56de\u5e30\u5206\u6790\u3092\u884c\u3063\u3066\u30d7\u30ed\u30c3\u30c8\u3057\u307e\u3059\u3002\nV = Joe.local_regression(x,y,Joe.epanechnikov;x_pred=U)\nplot!(p61,U,V,label=false,title = \"\u5c40\u6240\u7dda\u5f62\u56de\u5e30(p=1, N=30)\")\nsavefig(p61,joinpath(@OUTPUT,\"fig6-11.svg\")) # hide\n# \\fig{fig6-11}\n# \\lineskip\n# \u4e88\u6e2c\u3057\u305f\u3044\u5834\u6240\u306e\u6570\u3060\u3051\u56de\u5e30\u5206\u6790\u306e\u8a08\u7b97\u3092\u884c\u308f\u306a\u3044\u3068\u3044\u3051\u306a\u3044\u306e\u3067\u3001\u5143\u30c7\u30fc\u30bf\u306e\u6570\u304c\u591a\u3044\u6642\u306f\n# \u8a08\u7b97\u304c\u5927\u5909\u305d\u3046\u3067\u3059\u3002\n# ## \u4e00\u822c\u5316\u52a0\u6cd5\u30e2\u30c7\u30eb\n# ### \u4f8b62\n# \u57fa\u5e95\u95a2\u6570\u306e\u6570\u304c\u6709\u9650\u500b\u306a\u3089\u7dda\u5f62\u56de\u5e30\u306e\u624b\u6cd5\u3067\u4fc2\u6570\u3092\u6c42\u3081\u3089\u308c\u308b\u3051\u3069\u3001\n# \u6570\u304c\u591a\u3059\u304e\u308b\u3068\u9006\u884c\u5217\u3092\u89e3\u304f\u306e\u304c\u5927\u5909\u3067\u3069\u3046\u3057\u307e\u3057\u3087\u3046\u3068\u3044\uff13\u3046\u8a71\u3002\n# \u30d0\u30c3\u30af\u30d5\u30a3\u30c3\u30c6\u30a3\u30f3\u30b0\u306f\u4f8b63\u3067\u5b9f\u88c5\u3057\u307e\u3059\u3002\n# ### \u4f8b63\n# \u4ee5\u4e0b\u306e\u3088\u3046\u306apolyfit\u95a2\u6570\u3092\u5b9f\u88c5\u3057\u307e\u3057\u305f\u3002\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#     \u03b2\u0302 = multiple_regression(X,y)\n#     y_pred = insert_ones(X_pred) * \u03b2\u0302\n# end\n# ```\n# [\u4f8b\uff16\uff11](#\u4f8b61)\u306e\u30c7\u30fc\u30bf\u306b\u4e00\u822c\u52a0\u6cd5\u30e2\u30c7\u30eb\u3092\u9069\u7528\u3057\u307e\u3059\u3002\n# \u5148\u306b\u591a\u9805\u5f0f\u3067\u30d5\u30a3\u30c3\u30c6\u30a3\u30f3\u30b0\u3057\u3066\u6b8b\u308a\u3092\u5c40\u6240\u7dda\u5f62\u56de\u5e30\u3067\u6c42\u3081\u3066\u3044\u304d\u307e\u3059\u3002\nusing Random,Joe\nRandom.seed!(123)\nn=30; x = 2\u03c0*rand(n) .- \u03c0; sort!(x); y = sin.(x) .+ randn()\ny\u2081 = zeros(n); y\u2082 = zeros(n)\nfor k in 1:10\n    global x,y,y\u2081,y\u2082 # hide\n    y\u2081 = Joe.polyfit(x,y-y\u2082)\n    y\u2082 = Joe.local_regression(x,y-y\u2081,Joe.epanechnikov)\nend\nusing Plots\np62_1 = plot(x,y\u2081,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"\u591a\u9805\u5f0f\u56de\u5e30(3\u6b21)\")\np62_2 = plot(x,y\u2082,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"\u5c40\u6240\u7dda\u5f62\u56de\u5e30\")\np62\u3000= plot(p62_1,p62_2,layout=(1,2))\nsavefig(p62,joinpath(@OUTPUT,\"fig6-12.svg\")) # hide\n# \\fig{fig6-12}\n# \\lineskip\n# \u5927\u4f53\uff13\u6b21\u591a\u9805\u5f0f\u3067\u56de\u5e30\u3055\u308c\u3066\u3044\u3066\u3001\u6b8b\u308a\u304c\u5c40\u6240\u7dda\u5f62\u56de\u5e30\u3055\u308c\u3066\u3044\u308b\u3053\u3068\u304c\u5206\u304b\u308a\u307e\u3059\u3002\n# \u5148\u306b3\u6b21\u591a\u9805\u5f0f\u3067\u56de\u5e30\u3057\u305f\u305f\u3081\u3067\u3057\u3087\u3046\u304b\u3002 \u78ba\u8a8d\u3057\u3066\u307f\u308b\u3053\u3068\u306b\u3057\u307e\u3059\u3002\nusing Random,Joe\nRandom.seed!(123)\nn=30; x = 2\u03c0*rand(n) .- \u03c0; sort!(x); y = sin.(x) .+ randn()\ny\u2081 = zeros(n); y\u2082 = zeros(n)\nusing Plots \nfor k in 1:10\n    global x,y,y\u2081,y\u2082 # hide\n    y\u2082 = Joe.local_regression(x,y-y\u2081,Joe.epanechnikov)\n    y\u2081 = Joe.polyfit(x,y-y\u2082)\nend\np62_3 = plot(x,y\u2081,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"\u591a\u9805\u5f0f\u56de\u5e30(3\u6b21)\")\np62_4 = plot(x,y\u2082,label=false,xlabel=\"x\",ylabel=\"f(x)\",title=\"\u5c40\u6240\u7dda\u5f62\u56de\u5e30\")\np62_5\u3000= 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# \u591a\u9805\u5f0f\u56de\u5e30\u306e\u5f71\u97ff\u304c\u6e1b\u3063\u3066\u3001\u5c40\u6240\u7dda\u5f62\u56de\u5e30\u306e\u6210\u5206\u304c\u5927\u304d\u304f\u306a\u308b\u3053\u3068\u304c\u78ba\u8a8d\u3067\u304d\u307e\u3057\u305f\u3002", "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": "using Symbolics\nusing Test\nusing IfElse\n\n# Derivatives\n@variables t \u03c3 \u03c1 \u03b2\n@variables x y z\n@variables uu(t) uu\u02cdt(t)\nD = Differential(t)\nD2 = Differential(t)^2\nDx = Differential(x)\n\n@test Symbol(D(D(uu))) === Symbol(\"uu\u02cdtt(t)\")\n@test Symbol(D(uu\u02cdt)) === Symbol(D(D(uu)))\n\ntest_equal(a, b) = @test isequal(simplify(a), simplify(b))\n\n#@test @macroexpand(@derivatives D'~t D2''~t) == @macroexpand(@derivatives (D'~t), (D2''~t))\n\n@test isequal(expand_derivatives(D(t)), 1)\n@test isequal(expand_derivatives(D(D(t))), 0)\n\ndsin = D(sin(t))\n@test isequal(expand_derivatives(dsin), cos(t))\n\ndcsch = D(csch(t))\n@test isequal(expand_derivatives(dcsch), simplify(-coth(t) * csch(t)))\n\n@test isequal(expand_derivatives(D(-7)), 0)\n@test isequal(expand_derivatives(D(sin(2t))), simplify(cos(2t) * 2))\n@test isequal(expand_derivatives(D2(sin(t))), simplify(-sin(t)))\n@test isequal(expand_derivatives(D2(sin(2t))), simplify(-sin(2t) * 4))\n@test isequal(expand_derivatives(D2(t)), 0)\n@test isequal(expand_derivatives(D2(5)), 0)\n\n# Chain rule\ndsinsin = D(sin(sin(t)))\ntest_equal(expand_derivatives(dsinsin), cos(sin(t))*cos(t))\n\nd1 = D(sin(t)*t)\nd2 = D(sin(t)*cos(t))\n@test isequal(expand_derivatives(d1), simplify(t*cos(t)+sin(t)))\n@test isequal(expand_derivatives(d2), simplify(cos(t)*cos(t)+(-sin(t))*sin(t)))\n\neqs = [\u03c3*(y-x),\n       x*(\u03c1-z)-y,\n       x*y - \u03b2*z]\njac = Symbolics.jacobian(eqs, [x, y, z])\ntest_equal(jac[1,1], -1\u03c3)\ntest_equal(jac[1,2], \u03c3)\ntest_equal(jac[1,3], 0)\ntest_equal(jac[2,1],  \u03c1 - z)\ntest_equal(jac[2,2], -1)\ntest_equal(jac[2,3], -1x)\ntest_equal(jac[3,1], y)\ntest_equal(jac[3,2], x)\ntest_equal(jac[3,3], -1\u03b2)\n\n# issue #545\nz = t + t^2\n#test_equal(expand_derivatives(D(z)), 1 + t * 2)\n\nz = t-2t\n#test_equal(expand_derivatives(D(z)), -1)\n\n# Variable dependence checking in differentiation\n@variables a(t) b(a)\n@test !isequal(D(b), 0)\n@test isequal(expand_derivatives(D(t)), 1)\n@test isequal(expand_derivatives(Dx(x)), 1)\n\n@variables x(t) y(t) z(t)\n\n@test isequal(expand_derivatives(D(x * y)), simplify(y*D(x) + x*D(y)))\n@test isequal(expand_derivatives(D(x * y)), simplify(D(x)*y + x*D(y)))\n\n@test isequal(expand_derivatives(D(2t)), 2)\n@test isequal(expand_derivatives(D(2x)), 2D(x))\n@test isequal(expand_derivatives(D(x^2)), simplify(2 * x * D(x)))\n\n# n-ary * and +\n# isequal(Symbolics.derivative(Term(*, [x, y, z*\u03c1]), 1), y*(z*\u03c1))\n# isequal(Symbolics.derivative(Term(+, [x*y, y, z]), 1), 1)\n\n@test iszero(expand_derivatives(D(42)))\n@test all(iszero, Symbolics.gradient(42, [t, x, y, z]))\n@test all(iszero, Symbolics.hessian(42, [t, x, y, z]))\n@test isequal(Symbolics.jacobian([t, x, 42], [t, x]),\n              Num[1  0\n                  Differential(t)(x)           1\n                  0  0])\n\n# issue 252\n@variables beta, alpha, delta\n@variables x1, x2, x3\n\n# expression\ntmp = beta * (alpha * exp(x1) * x2 ^ (alpha - 1) + 1 - delta) / x3\n# derivative w.r.t. x1 and x2\nt1 = Symbolics.gradient(tmp, [x1, x2])\n@test_nowarn Symbolics.gradient(t1[1], [beta])\n\n@variables t k\n@variables x(t)\nD = Differential(k)\n@test Symbolics.tosymbol(D(x).val) === Symbol(\"x\u02cdk(t)\")\n\nusing Symbolics\n@variables t x(t)\n\u2202\u209c = Differential(t)\n\u2202\u2093 = Differential(x)\nL = .5 * \u2202\u209c(x)^2 - .5 * x^2\n@test isequal(expand_derivatives(\u2202\u2093(L)), -1 * x)\ntest_equal(expand_derivatives(Differential(x)(L) - \u2202\u209c(Differential(\u2202\u209c(x))(L))), -1 * (\u2202\u209c(\u2202\u209c(x)) + x))\n@test isequal(expand_derivatives(Differential(x)(L) - \u2202\u209c(Differential(\u2202\u209c(x))(L))), (-1 * x) - \u2202\u209c(\u2202\u209c(x)))\n\n@variables x2(t)\n@test isequal(expand_derivatives(Differential(x)(2 * x + x2 * x)), 2 + x2)\n\n@variables x y\n@variables u(..)\nDy = Differential(y)\nDx = Differential(x)\ndxyu = Dx(Dy(u(x,y)))\n@test isequal(expand_derivatives(dxyu), dxyu)\ndxxu = Dx(Dx(u(x,y)))\n@test isequal(expand_derivatives(dxxu), dxxu)\n\nusing Symbolics, LinearAlgebra, SparseArrays\nusing Test\n\ncanonequal(a, b) = isequal(simplify(a), simplify(b))\n\n# Calculus\n@variables t \u03c3 \u03c1 \u03b2\n@variables x y z\n@test isequal(\n    (Differential(z) * Differential(y) * Differential(x))(t),\n    Differential(z)(Differential(y)(Differential(x)(t)))\n)\n\n@test canonequal(\n                 Symbolics.derivative(sin(cos(x)), x),\n                 -sin(x) * cos(cos(x))\n                )\n\nSymbolics.@register no_der(x)\n@test canonequal(\n                 Symbolics.derivative([sin(cos(x)), hypot(x, no_der(x))], x),\n                 [\n                  -sin(x) * cos(cos(x)),\n                  x/hypot(x, no_der(x)) + no_der(x)*Differential(x)(no_der(x))/hypot(x, no_der(x))\n                 ]\n                )\n\nSymbolics.@register intfun(x)::Int\n@test Symbolics.symtype(intfun(x)) === Int\n\neqs = [\u03c3*(y-x),\n       x*(\u03c1-z)-y,\n       x*y - \u03b2*z]\n\n\u2202 = Symbolics.jacobian(eqs,[x,y,z])\nfor i in 1:3\n    \u2207 = Symbolics.gradient(eqs[i],[x,y,z])\n    @test canonequal(\u2202[i,:],\u2207)\nend\n\n@test all(canonequal.(Symbolics.gradient(eqs[1],[x,y,z]),[\u03c3 * -1,\u03c3,0]))\n@test all(canonequal.(Symbolics.hessian(eqs[1],[x,y,z]),0))\n\ndu = [x^2, y^3, x^4, sin(y), x+y, x+z^2, z+x, x+y^2+sin(z)]\nreference_jac = sparse(Symbolics.jacobian(du, [x,y,z]))\n\n@test findnz(Symbolics.jacobian_sparsity(du, [x,y,z]))[[1,2]] == findnz(reference_jac)[[1,2]]\n\nlet\n    @variables t x(t) y(t) z(t)\n    @test Symbolics.exprs_occur_in([x,y,z], x^2*y) == [true, true, false]\nend\n\n@test isequal(Symbolics.sparsejacobian(du, [x,y,z]), reference_jac)\n\nusing Symbolics\n\nrosenbrock(X) = sum(1:length(X)-1) do i\n    100 * (X[i+1] - X[i]^2)^2 + (1 - X[i])^2\nend\n\n@variables a,b\nX = [a,b]\n\nspoly(x) = simplify(x, expand=true)\nrr = rosenbrock(X)\n\nreference_hes = Symbolics.hessian(rr, X)\n@test findnz(sparse(reference_hes))[1:2] == findnz(Symbolics.hessian_sparsity(rr, X))[1:2]\n\nsp_hess = Symbolics.sparsehessian(rr, X)\n@test findnz(sparse(reference_hes))[1:2] == findnz(sp_hess)[1:2]\n@test isequal(map(spoly, findnz(sparse(reference_hes))[3]), map(spoly, findnz(sp_hess)[3]))\n\n#96\n@variables t x[1:4](t) \u1e8b[1:4](t)\nexpression = sin(x[1] + x[2] + x[3] + x[4]) |> Differential(t) |> expand_derivatives\nexpression2 = substitute(expression, Dict(Differential(t).(x) .=> \u1e8b))\n@test isequal(expression2, (\u1e8b[1] + \u1e8b[2] + \u1e8b[3] + \u1e8b[4])*cos(x[1] + x[2] + x[3] + x[4]))\n\n@test isequal(\n    Symbolics.derivative(IfElse.ifelse(signbit(b), b^2, sqrt(b)), b),\n    IfElse.ifelse(signbit(b), 2b, (1//2)*(sqrt(b)^-1))\n)\n", "meta": {"hexsha": "0ac78753af113a0c5caa6df4f852ef314f23e178", "size": 6217, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/diff.jl", "max_stars_repo_name": "charleskawczynski/Symbolics.jl", "max_stars_repo_head_hexsha": "78a3c97ee27a630df1741ed32ee33996b390eff8", "max_stars_repo_licenses": ["MIT"], "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/diff.jl", "max_issues_repo_name": "charleskawczynski/Symbolics.jl", "max_issues_repo_head_hexsha": "78a3c97ee27a630df1741ed32ee33996b390eff8", "max_issues_repo_licenses": ["MIT"], "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/diff.jl", "max_forks_repo_name": "charleskawczynski/Symbolics.jl", "max_forks_repo_head_hexsha": "78a3c97ee27a630df1741ed32ee33996b390eff8", "max_forks_repo_licenses": ["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.1877934272, "max_line_length": 104, "alphanum_fraction": 0.6297249477, "num_tokens": 2206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.771571812528983}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Plots, LaTeXStrings\nend;\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.12\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.12\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u2550874034ba-3b2b-11eb-2b77-c1d2d28a1116\n# \u2560\u255087407402-3b2b-11eb-36de-2b731fe48190\n# \u255f\u2500475ff888-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": "module postwidderTests\n\nusing Test\nusing InverseLaplace: gaverstehfest, stehfest_coeffs\n\n# Compare against results reported in Algorithm 368: Numerical inversion of Laplace transforms [D5].\n\n#### F(s) = 1/sqrt(s), f(t) = 1/sqrt(\u03c0*t)\n\n# test for single time point\n\n## test in double precision Float64\nt = 1.0\n@test isapprox(gaverstehfest(s -> 1/sqrt(s), t, v = convert(Vector{Float64}, stehfest_coeffs(18))), 1/sqrt(pi*t), rtol = 1e-5)\nt = 5.0\n@test isapprox(gaverstehfest(s -> 1/sqrt(s), t, v = convert(Vector{Float64}, stehfest_coeffs(18))), 1/sqrt(pi*t), rtol = 1e-5)\n\n# test in the default BigFloat\nt = 1.0\n@test isapprox(gaverstehfest(s -> 1/sqrt(s), t, v = stehfest_coeffs(36)), 1/sqrt(pi*t), rtol = 1e-16)\nt = 5.0\n@test isapprox(gaverstehfest(s -> 1/sqrt(s), t, v = stehfest_coeffs(36)), 1/sqrt(pi*t), rtol = 1e-16)\n\n# test across t array in BigFloat\nt = 1.0:10.0\n@test isapprox(gaverstehfest(s -> 1/sqrt(s), t, v = stehfest_coeffs(36)), 1 ./ sqrt.(pi.*t), rtol = 1e-12)\n\n\n#### F(s) = 1/s^4, f(t) = t^3 / 6\n\n# test for single time point\n## tests in double precision\nt = 1.0\n@test isapprox(gaverstehfest(s -> 1/s^4, t, v = convert(Vector{Float64}, stehfest_coeffs(18))), t^3/6, rtol = 1e-4)\nt = 5.0\n@test isapprox(gaverstehfest(s -> 1/s^4, t, v = convert(Vector{Float64}, stehfest_coeffs(18))), t^3/6, rtol = 1e-4)\n\n# test in BigFloat\nt = 1.0\n@test isapprox(gaverstehfest(s -> 1/s^4, t, v = stehfest_coeffs(36)), t^3/6, rtol = 1e-14)\nt = 5.0\n@test isapprox(gaverstehfest(s -> 1/s^4, t, v = stehfest_coeffs(36)), t^3/6, rtol = 1e-14)\n\n# test across t array\nt = 1.0:10.0\n@test isapprox(gaverstehfest(s -> 1/s^4, t, v = stehfest_coeffs(36)), t.^3 ./6, rtol = 1e-12)\n\n#### F(s) = 1/(s+1), f(t) = exp(-t)\n## for larger t you need a higher amount of coeffs depending on accuracy\n\n# test for single time point\n## double precision\nt = 1.0\n@test isapprox(gaverstehfest(s -> 1/(s+1), t, v = convert(Vector{Float64}, stehfest_coeffs(18))), exp(-t), rtol = 1e-4)\nt = 5.0\n@test isapprox(gaverstehfest(s -> 1/(s+1), t, v = convert(Vector{Float64}, stehfest_coeffs(18))), exp(-t), rtol = 1e-3)\n\n# BigFloat\nt = 1.0\n@test isapprox(gaverstehfest(s -> 1/(s+1), t, v = stehfest_coeffs(36)), exp(-t), rtol = 1e-12)\nt = 5.0\n@test isapprox(gaverstehfest(s -> 1/(s+1), t, v = stehfest_coeffs(36)), exp(-t), rtol = 1e-8)\n\n# test across t array\nt = 1.0:10.0\n@test isapprox(gaverstehfest(s -> 1/(s+1), t, v = stehfest_coeffs(36)), exp.(-t), rtol = 1e-8)\n\nend # module\n", "meta": {"hexsha": "610f57c7942185ed06b420b9fc032cf9c36e4461", "size": 2446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gaverstehfest_tests.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": "test/gaverstehfest_tests.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": "test/gaverstehfest_tests.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.4492753623, "max_line_length": 126, "alphanum_fraction": 0.6516762061, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7715717986747819}}
{"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 \u00b1 0.05 -4.0 \u00b1 0.05;\n                    4.0 \u00b1 0.05 -1.0 \u00b1 0.05])\n\n# IVP(LCS(A), X0) TODO: remove\ninterval2D_linear = @ivp x' = Ax, x(0) \u2208 X0\n\n# affine ODE: x' = Ax + Bu\nB = IntervalMatrix(hcat([1.0 \u00b1 0.0; 1.0 \u00b1 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) \u2208 X0, u \u2208 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": "using JuMP, NLopt, Test\n\nm = Model(solver=NLoptSolver(algorithm=:LD_MMA))\n\na1 = 2\nb1 = 0\na2 = -1\nb2 = 1\n\n@variable(m, x1)\n@variable(m, x2 >= 0)\n\n@NLobjective(m, Min, sqrt(x2))\n@NLconstraint(m, x2 >= (a1*x1+b1)^3)\n@NLconstraint(m, x2 >= (a2*x1+b2)^3)\n\nsetvalue(x1, 1.234)\nsetvalue(x2, 5.678)\n\nstatus = solve(m)\n\nprintln(\"got \", getobjectivevalue(m), \" at \", [getvalue(x1),getvalue(x2)])\n\n@test_approx_eq_eps getvalue(x1) 1/3 1e-5\n@test_approx_eq_eps getvalue(x2) 8/27 1e-5\n@test_approx_eq_eps getobjectivevalue(m) sqrt(8/27) 1e-5\n@test status == :Optimal\n\n\n\n", "meta": {"hexsha": "a2cb418dc2453854b7185bfaab64d0fb295a64ec", "size": 557, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tutorial_jump.jl", "max_stars_repo_name": "JeffBezanson/NLopt.jl", "max_stars_repo_head_hexsha": "6824bbc259bc74faa0d97a838b447900e13002d3", "max_stars_repo_licenses": ["MIT"], "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/tutorial_jump.jl", "max_issues_repo_name": "JeffBezanson/NLopt.jl", "max_issues_repo_head_hexsha": "6824bbc259bc74faa0d97a838b447900e13002d3", "max_issues_repo_licenses": ["MIT"], "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/tutorial_jump.jl", "max_forks_repo_name": "JeffBezanson/NLopt.jl", "max_forks_repo_head_hexsha": "6824bbc259bc74faa0d97a838b447900e13002d3", "max_forks_repo_licenses": ["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.9677419355, "max_line_length": 74, "alphanum_fraction": 0.6750448833, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7714650741646435}}
{"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": "# Julia program to reverse a number\n\n# Function to reverse a number.\nfunction reverse(num)\n    rev = 0\n    while(num > 0)\n        # Extract the last digit of num and add it to rev\n        rev = rev * 10 + num %10\n        num = num \u00f7 10\n    end\n    return rev\nend\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\nrev = reverse(num)\nprintln(\"The reverse of the given number is $rev.\")\n\n\n\"\"\"\nTime Complexity: O(log(n)), where 'n' is the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the number: 1234\nThe reverse of the given number is 4321.\n\nSAMPLE 2\nEnter the number: 785487\nThe reverse of the given number is 784587.\n\"\"\"\n", "meta": {"hexsha": "a55890d2e0b1bfed2aaafe47b91fef43e5929b40", "size": 670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/reverse_number.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/math/reverse_number.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/math/reverse_number.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.1428571429, "max_line_length": 57, "alphanum_fraction": 0.6671641791, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.7714309008821562}}
{"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# \u2554\u2550\u2561 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 = \"\u521d\u8bc6 Julia\")\nend\n\n# \u2554\u2550\u2561 3baed4bd-1c0c-4d44-b7ab-f7c0627fda1b\nbegin\n\tPkg.add(\"AbstractTrees\") # command + /: \u5207\u6362\u4e3a\u6ce8\u91ca\u5f62\u5f0f\n\tusing AbstractTrees\n\tAbstractTrees.children(x::Type) = subtypes(x)\n\twith_terminal(() -> print_tree(Number))\nend\n\n# \u2554\u2550\u2561 2edcc72c-bfa4-4623-a34f-220c0df9c4d3\nbegin\n\tPkg.add(\"HTTP\")\n\tPkg.add(\"JSON\")\n\tusing HTTP, JSON\nend\n\n# \u2554\u2550\u2561 d507db6a-f869-4dc3-b7ef-fd3518fc1660\nPkg.add.([\"Plots\", \"LaTeXStrings\", \"Measures\"])\n\n# \u2554\u2550\u2561 2fdb3281-7229-4f18-b9d9-bc5e3086d903\nusing Statistics\n\n# \u2554\u2550\u2561 f924796f-52f3-4b4b-aa47-61a179874647\nusing Plots, LaTeXStrings, Measures\n\n# \u2554\u2550\u2561 ec3f7b5c-cee9-432f-b33c-a08e16c0171a\nStatisticsWithJulia.header(title = @__FILE__, author=\"\")\n\n# \u2554\u2550\u2561 9d98fa7a-3654-40a0-8a96-75c3fca007ae\nmd\"\"\"\n## \u672c\u7ae0\u8bb2\u4e49\n\n- [\u8bb2\u4e49\u4e0b\u8f7d](http://likan.oss-cn-beijing.aliyuncs.com/StatisticsWithJulia/01-%E5%88%9D%E8%AF%86Julia.pdf)\n\n\"\"\"\n\n# \u2554\u2550\u2561 42da8f74-1b44-11ec-32f2-276bdcef1c69\nmd\"\"\"\n## 1.1. \u4f60\u597d\u4e16\u754c\n\"\"\"\n\n# \u2554\u2550\u2561 e71aacbb-efff-4b93-b5c4-cbdfa88981ad\nmd\"\"\"\n- `command/control + m`: \u628a\u5f53\u4e0b\u5355\u5143\u683c\u5207\u6362\u5230markdown\u683c\u5f0f\n\"\"\"\n\n# \u2554\u2550\u2561 0660d564-9a26-417d-9a2c-42ef181187c2\nwith_terminal() do\n    println(\"\u4f60\u597d\uff0c \u4e16\u754c!\")\nend\n\n# \u2554\u2550\u2561 77c5ddd3-ddfc-4a57-ab48-e9db765057d3\nwith_terminal(() -> println(\"\u4f60\u597d\uff0c \u4e16\u754c!\"))\n\n# \u2554\u2550\u2561 8eefb8aa-ae85-4231-abf5-9948cdc92ec1\nmd\"\"\"\n`do f() end` \u7b49\u4ef7\u4e8e `\uff08\uff09 -> f()`\n\"\"\"\n\n# \u2554\u2550\u2561 d22fc28f-c591-4db2-8275-54d93fda85e9\nf(x) = BigInt(x)^BigInt(x)\n\n# \u2554\u2550\u2561 4ece5fc8-18d5-408a-851b-31ce58015e72\nmap(x -> 3x, 1:10)\n\n# \u2554\u2550\u2561 c266f6e2-4e8e-4870-ac38-d4d0e8b9d042\nmap(1:10) do x\n\t3x\nend\n\n# \u2554\u2550\u2561 8f3277e9-7905-4beb-9ef1-c3e18b2f449a\nmap(x -> rand(), 1:10)\n\n# \u2554\u2550\u2561 f6e99ac9-2183-4ea2-991e-f3422b1d1f20\nmap(__ -> rand(), 1:10)\n\n# \u2554\u2550\u2561 cd0ce1b4-9bc9-4218-95e9-e576abeb1af1\n# map(() -> rand(), 1:10) # \u4e0d\u5408\u8bed\u6cd5\n\n# \u2554\u2550\u2561 37fec978-f817-4aa8-85fc-4912eaeb402e\nhelloArray = [\"\u4f60\u597d\", \"\ud83d\udc4b\", \"\u4e16\u754c\"]\n\n# \u2554\u2550\u2561 adc183db-ff23-43de-8cf6-a961d13c2f01\nwith_terminal() do\n\tfor i \u2208 eachindex(helloArray)\n\t\tprintln(helloArray[i])\n\tend\nend\n\n# \u2554\u2550\u2561 4f1ce95f-2f2f-4817-9d5f-348184a1b800\n[i^2 for i in 1:10 for __ in 1:10] # \u4e00\u7ef4\u6570\u7ec4\n\n# \u2554\u2550\u2561 dec64158-9161-4b37-b19f-432a5635719e\n[i^2 for i in 1:10, __ in 1:10]   # \u77e9\u9635\n\n# \u2554\u2550\u2561 5a401f10-09d2-4939-87fe-621f469a68ee\nSquare = [i^2 for i in 1:10]\n\n# \u2554\u2550\u2561 c2c7c916-1ba8-4e14-a25b-e15faf676f8a\nwith_terminal() do\n\tfor i \u2208 eachindex(Square)\n\t\t\tprintln(Square[i])\n\tend\nend\n\n# \u2554\u2550\u2561 93b0afb2-e9f3-434d-b21a-2ccad6a12d90\n[rand() for __ in 1:100]\n\n# \u2554\u2550\u2561 8bcc15c7-d66a-40cc-9f33-50c6de62fadc\nmd\"\"\"\n### \u8fd0\u884c\u901f\u5ea6\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0e8b6a32-ba23-4e37-b78c-8ffb3779a43e\n\"98%\u7684\u5e73\u5747\u503c\u4f4d\u4e8e $(quantile(data, 0.01)) \u548c $(quantile(data, 0.99)) \u4e4b\u95f4\u3002\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1b45a9bf-56c7-4b7b-bdd5-b4fcaa572ec0\n\"98%\u7684\u5e73\u5747\u503c\u4f4d\u4e8e $(quantile(data2, 0.01)) \u548c $(quantile(data2, 0.99)) \u4e4b\u95f4\u3002\"\n\n# \u2554\u2550\u2561 60b263eb-f786-40c4-b60b-2daabdacba7b\nmd\"\"\"\n### \u7c7b\u578b\u548c\u591a\u91cd\u6d3e\u53d1\n\"\"\"\n\n# \u2554\u2550\u2561 b0db7a9c-2498-46c5-bf3c-280d3083ba88\n# @edit 1 + 2\n\n# \u2554\u2550\u2561 412ee0c1-26ad-4b9f-9d6e-c552d8431e76\n# @edit 1.0 + 2\n\n# \u2554\u2550\u2561 aa5e313d-19d9-4300-a65e-f547f7e571d0\nmutable struct zhan\n\tdt::Int64\nend\n\n# \u2554\u2550\u2561 0ba25fa7-72cb-4d6e-bfaf-eddcf12b9f9c\nx = zhan(4)\n\n# \u2554\u2550\u2561 d5251a23-b71e-4faf-9f5a-f6ab1d2ffb7d\ny = zhan(8)\n\n# \u2554\u2550\u2561 b717d872-0d16-4556-a6c8-1ccc3c7b76c3\nBase.:+(x::zhan, y::zhan) = x.dt * 100 + y.dt * 200\n\n# \u2554\u2550\u2561 a0322171-cff9-48bb-9f73-792c8ea4798f\nfunction g(x)\n\tx + 1000\nend\n\n# \u2554\u2550\u2561 3711c338-748f-448e-a06d-d3c29094a14b\nmap(g, 1:10)\n\n# \u2554\u2550\u2561 f77b7762-29ee-4472-a4ee-a5c1a6dfb369\nsqrt.(Square) .+ 100\n\n# \u2554\u2550\u2561 e9d5ee6c-de1a-41ee-850e-a6f5471537ea\n@. sqrt(Square) + 100\n\n# \u2554\u2550\u2561 90fe2c2b-d62d-40b5-9a34-0eb1e9836250\n[10 + x for x in 1:100]\n\n# \u2554\u2550\u2561 72b3ed37-3f3f-4a7d-9036-dadb06c3e1e4\nx + y\n\n# \u2554\u2550\u2561 8c6e966d-9185-4a44-8cd9-e69528cee54b\n# methods(+)\n\n# \u2554\u2550\u2561 1e9be5f5-ab15-4a29-8fd6-d20fee084ad5\nabstract type LIKANZHAN <: Signed end #\u62bd\u8c61\u7c7b\u578b\n\n# \u2554\u2550\u2561 59b884e5-a55a-42f6-9ed4-404d55eae5e9\nmd\"\"\"\n## 1.2. \u51e0\u4e2a\u4f8b\u5b50\n\"\"\"\n\n# \u2554\u2550\u2561 3cbd7219-7fb0-4c6e-a2ad-724e97b67d94\nfunction bubbleSort!(a)\n\tn = length(a)\n\tfor i \u2208 1:n-1\n\t\tfor j \u2208 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# \u2554\u2550\u2561 93a86467-cf02-4d3c-b127-79247a588250\ndata3 = [65, 66, 55, 44, 20, 34, 78, 80]\n\n# \u2554\u2550\u2561 0423223e-90c5-4d86-8370-66ddee6ba496\nwith_terminal() do\n\t@time bubbleSort!(rand(10^5))\nend\n\n# \u2554\u2550\u2561 721c67fd-6d40-4171-89c4-21a1c0064880\nwith_terminal() do\n\t@time sort!(rand(10^5))\nend\n\n# \u2554\u2550\u2561 5a4dd40b-d917-4634-a4d4-255c63d68d3f\nmd\"\"\"\n- \u7f51\u7edc\u63a5\u53e3\u548c JSON\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fbbc0558-7916-4308-b8be-4428f47ca4e5\nshakespeare = String(data4)\n\n# \u2554\u2550\u2561 290d3b7f-ee12-476c-a4f2-189671c84398\n# shakespeareWords = split(shakespeare)\n\n# \u2554\u2550\u2561 cc728038-b20f-4b93-97a7-883d5734a0b2\n# jsonWords = HTTP.request(\"GET\", \"https://raw.githubusercontent.com/\"*\"h-Klok/StatsWithJuliaBook/master/data/jsonCode.json\")\n\n# \u2554\u2550\u2561 2eca9295-370d-41e9-95a4-b56ee2b0e1dc\n\"julia\" * \" is good\"\n\n# \u2554\u2550\u2561 b4c5a72d-5ce1-4e21-a04f-8344d1023648\nstring(\"Julia\", \" is Good\", \". Python\", \" is slow.\")\n\n# \u2554\u2550\u2561 4f11cc1a-a78e-4d6c-8bd2-857f85f48aa8\nls = 1:7\n\n# \u2554\u2550\u2561 50039da8-2c71-4a1d-8cc1-2d4bd8126988\ntypeof(ls)\n\n# \u2554\u2550\u2561 efb2b80c-af6c-4f6e-bcba-e57c7c39cab3\ncollect(ls)\n\n# \u2554\u2550\u2561 1ca893dd-2040-47df-8fa0-c3cb4dd0d7dc\nmd\"\"\"\n- \u6570\u636e\u5b58\u50a8\u7684\u5e38\u89c1\u683c\u5f0f\uff1a\u6570\u7ec4\n\"\"\"\n\n# \u2554\u2550\u2561 dbbcd955-e0c9-4a6c-81bf-fe5c5ad2f018\nmd\"\"\"\n- \u6570\u636e\u5b58\u50a8\u7684\u53e6\u5916\u683c\u5f0f\uff1a \u8bcd\u5178\n\"\"\"\n\n# \u2554\u2550\u2561 5565b0a4-792b-40f6-82a2-f8f642432129\ndct = Dict(\"x\" => collect(ls), \"y\" => collect(ls .+ 1) )\n\n# \u2554\u2550\u2561 6d4175a4-af6e-4a08-bcd2-0b1966ae9035\ngetindex(dct, \"x\")\n\n# \u2554\u2550\u2561 c4a58e43-2ea8-48fa-a99d-09f83b1b8ba8\nmd\"\"\"\n- \u6570\u636e\u5b58\u50a8\u7684\u53e6\u5916\u683c\u5f0f\uff1a \u5143\u7ec4\n\"\"\"\n\n# \u2554\u2550\u2561 e0e5ef4a-fc35-4d9b-9a34-a9439d87051d\nvec = [1, 2, 3]; typeof(vec)\n\n# \u2554\u2550\u2561 c9d041cb-6a29-449a-8909-b529e8c562a6\nyz = (1, 2, 4); typeof(yz)\n\n# \u2554\u2550\u2561 c77241fb-bd9e-4270-bd04-e8b5bcb2406b\nmd\"\"\"\n## 1.3. \u505a\u56fe\u521d\u6b65\n\"\"\"\n\n# \u2554\u2550\u2561 87296377-fe6d-4225-b114-a8c3b8bea1bc\nwith_terminal() do\n\tPkg.status()\nend\n\n# \u2554\u2550\u2561 aa61efe4-b3a2-4379-a748-f37cd7f9c6fb\nf(x, y) = x^2 + y^2\n\n# \u2554\u2550\u2561 9d9f4d96-7755-4fd1-851a-092929ad1ac7\nf(6)\n\n# \u2554\u2550\u2561 8b0db1dd-5d79-42e5-9763-ca4ef7259060\nmap(f, 1:10)\n\n# \u2554\u2550\u2561 182ab07b-a3e6-47f0-8de5-d59113027c43\nf0(x) = f(x, 0)\n\n# \u2554\u2550\u2561 6262451f-4dcf-4f84-8be6-2f8fbf2631bd\nf2(x) = f(x, 2)\n\n# \u2554\u2550\u2561 3d664567-d879-41f7-9e1a-cdfc08e4e7c9\nxVals, yVals = -5:0.1:5, -5:0.1:5\n\n# \u2554\u2550\u2561 5e03a17e-861e-4749-b18e-00e293d24f28\nplot([f0, f2], xVals) # command + /\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9461292e-3658-41e2-8349-45790fa7c9e0\nz = [f(x, y) for y in yVals, x in xVals];\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e54420c1-1ff3-4f38-b9b8-0e3a18127c9a\nM = z[1:10, 1:10];\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b7729c93-781a-46ec-b057-65c4e9e15a04\nplot(p1, p2, p3, layout = (1, 3), size = (1200, 400), xlabel = \"x\", margin = 5mm)\n\n# \u2554\u2550\u2561 543de112-675c-4368-957d-f37647ad85bd\n L\"\\frac{\\delta}{\\gamma\\times \\cdots}\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 68d89124-d6e9-4609-b12a-d3b508733680\n# surface() # \u7b49\u4ef7\u4e8e plot(.., seriestype = :surface,...,)\n\n# \u2554\u2550\u2561 6003cd52-89ea-4d93-ac00-43ca395357b8\nmd\"\"\"\n### 1.3.1 \u5e0c\u5c14\u987f\u5e8f\u5217\n\"\"\"\n\n# \u2554\u2550\u2561 92c42555-8550-4c1b-9b1a-502813c40237\nmd\"\"\"\n- \u6761\u4ef6\u53e5\n\"\"\"\n\n# \u2554\u2550\u2561 5c3f1925-ebfb-4bef-8425-635262927bf1\nfunction ff1(x)\n\tif x % 3 == 0\n\t\treturn \"$x \u9664\u4ee5 3 \u7684\u4f59\u6570\u662f 0\"\n\telseif x % 3 == 1\n\t\treturn \"$x \u9664\u4ee5 3 \u7684\u4f59\u6570\u662f 1\"\n\telse\n\t\treturn \"$x \u9664\u4ee5 3 \u7684\u4f59\u6570\u662f 2\"\n\tend\nend\n\n# \u2554\u2550\u2561 ec02b4a7-529b-4d37-ba4b-bf146a33ee0f\n[ff1(x) for x in 1:5]\n\n# \u2554\u2550\u2561 954f166b-e8db-4cf7-a0a2-75ab3b3acbe0\nfunction ff2(x)\n\tif x % 3 == 0\n\t\treturn \"x \u96643\u7684\u4f59\u6570\u662f 0\"\n\tend\nend\n\n# \u2554\u2550\u2561 e97dcedb-4b53-4ce8-a0e9-ed20b77d8b2d\n[ff2(x) for x in 1:5]\n\n# \u2554\u2550\u2561 f662c9f4-8004-43d6-ad1e-872ad3d24e48\nmd\"\"\"\n- \u7c7b\u578b\u7a33\u5b9a\u6027\uff1a \u9664\u53f7\u53ef\u80fd\u4f1a\u6539\u53d8\u6570\u636e\u7684\u7c7b\u578b\n\"\"\"\n\n# \u2554\u2550\u2561 c72335d5-39e3-4ab9-a398-e3960dcafe0c\nxd = Int(2)\n\n# \u2554\u2550\u2561 8ebae10c-3148-43fe-9b14-f07934c3b2ea\ntypeof(xd)\n\n# \u2554\u2550\u2561 e49a1426-bcf5-453a-8753-2bb8387e67eb\nyd = xd/2\n\n# \u2554\u2550\u2561 46bd26e6-c1bf-4fa3-890a-2d424865c2dc\ntypeof(yd)\n\n# \u2554\u2550\u2561 55e79482-e30e-4eea-b083-cac2a9667348\nmd\"\"\"\n- \u5e0c\u5c14\u987f\u5e8f\u5217\n\"\"\"\n\n# \u2554\u2550\u2561 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 # \u7b49\u4ef7\u4e8e n = n + 1, *=, /= \n\tend\n\treturn n\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4abd57c6-1a0c-4e7c-a195-d07ddc299b2c\nmd\"\"\"\n\u6ce8\u610f\uff1a `condition ? res1 : res2` \u7b49\u4ef7\u4e8e `if condition res1 else res2`\n\"\"\"\n\n# \u2554\u2550\u2561 aa2c895f-7219-4b98-bf50-c96d676ead09\nx2 = 13\n\n# \u2554\u2550\u2561 5fb204e1-d150-4a3c-ac19-6fa5b67b072b\nif x2 % 2 == 1 \"\u5947\u6570\" else \"\u5076\u6570\" end\n\n# \u2554\u2550\u2561 c0df29b8-368d-40d1-bad0-73493531903a\nlengths = [hailLength(x0) for x0 in 2:10^7];\n\n# \u2554\u2550\u2561 51046c66-6e14-420e-8a5e-5a58580841a6\n# histogram(lengths)\n\n# \u2554\u2550\u2561 3659f664-3fc3-48bd-94e3-f57ae84e7301\nplot(lengths, seriestype = :histogram,\n\tbins = 1000,\n\t# fill = (:green, true) # \u5143\u7ec4\n\tfill = true, color = :green,\n\tnormed = true, legend = false,\n\tlinealpha = 0.2\n)\n\n# \u2554\u2550\u2561 9392cdfb-ceef-40ac-a67b-8c7ca33de123\nmd\"\"\"\n### 1.3.2 \u52a8\u56fe\n\"\"\"\n\n# \u2554\u2550\u2561 20605ee6-f245-4e77-b014-a8e42a520e8d\nn = 10\n\n# \u2554\u2550\u2561 c69f8278-9627-458b-8204-91ae08efbf92\npoints = [exp(2 * pi * im * k / n) for k in 1:n];\n\n# \u2554\u2550\u2561 a5f4d797-db11-4d6a-8906-b4af6804a936\nplot(points, seriestype = :scatter, legend = false);\n\n# \u2554\u2550\u2561 46f62dad-820b-42d3-8cdd-ab02cacabc47\nxPts, yPts = real.(points), imag.(points);\n\n# \u2554\u2550\u2561 758082fe-038e-4090-b658-111db3ee1f13\nedges  = [(v, u) for v in 1:n for u in (v+1):n];\n\n# \u2554\u2550\u2561 931e4862-c109-4b17-9048-7826f3dd0c6f\nanimate = Animation();\n\n# \u2554\u2550\u2561 3017c6db-acee-422d-bb97-692495972631\nplot(xPts, yPts, seriestype = :scatter, legend = false) # \u7b49\u4ef7\u4e8e scatter(xPts, yPts)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 43b3b163-05a7-4c06-a948-bf5c001b7af0\ngif(animate)\n\n# \u2554\u2550\u2561 4c0169d7-b280-4326-aa79-9c979280077a\nmd\"\"\"\n## 1.4. \u968f\u673a\u6570\n\"\"\"\n\n# \u2554\u2550\u2561 694d2ceb-233f-49ea-9416-9e8a8f272d38\nmd\"\"\"\n## 1.6. \u5d4c\u5165\u5176\u4ed6\u8bed\u8a00\n\"\"\"\n\n# \u2554\u2550\u2561 72a095fa-c5cf-4eb1-909d-d8b49af0bdc9\nStatisticsWithJulia.list_notebooks(@__FILE__)\n\n# \u2554\u2550\u2561 8a20fa4c-338c-48c9-a12a-02e6d67153df\nStatisticsWithJulia.footer() ## FFFFF\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ec3f7b5c-cee9-432f-b33c-a08e16c0171a\n# \u255f\u25006dd76507-be07-4c3a-9747-99eca74d3519\n# \u255f\u25009d98fa7a-3654-40a0-8a96-75c3fca007ae\n# \u255f\u250042da8f74-1b44-11ec-32f2-276bdcef1c69\n# \u255f\u2500e71aacbb-efff-4b93-b5c4-cbdfa88981ad\n# \u2560\u25500660d564-9a26-417d-9a2c-42ef181187c2\n# \u2560\u255077c5ddd3-ddfc-4a57-ab48-e9db765057d3\n# \u255f\u25008eefb8aa-ae85-4231-abf5-9948cdc92ec1\n# \u2560\u2550d22fc28f-c591-4db2-8275-54d93fda85e9\n# \u2560\u25509d9f4d96-7755-4fd1-851a-092929ad1ac7\n# \u2560\u25504ece5fc8-18d5-408a-851b-31ce58015e72\n# \u2560\u25508b0db1dd-5d79-42e5-9763-ca4ef7259060\n# \u2560\u2550a0322171-cff9-48bb-9f73-792c8ea4798f\n# \u2560\u25503711c338-748f-448e-a06d-d3c29094a14b\n# \u2560\u2550c266f6e2-4e8e-4870-ac38-d4d0e8b9d042\n# \u2560\u25508f3277e9-7905-4beb-9ef1-c3e18b2f449a\n# \u2560\u2550f6e99ac9-2183-4ea2-991e-f3422b1d1f20\n# \u2560\u2550cd0ce1b4-9bc9-4218-95e9-e576abeb1af1\n# \u2560\u255037fec978-f817-4aa8-85fc-4912eaeb402e\n# \u2560\u2550adc183db-ff23-43de-8cf6-a961d13c2f01\n# \u2560\u25504f1ce95f-2f2f-4817-9d5f-348184a1b800\n# \u2560\u2550dec64158-9161-4b37-b19f-432a5635719e\n# \u2560\u25505a401f10-09d2-4939-87fe-621f469a68ee\n# \u2560\u2550c2c7c916-1ba8-4e14-a25b-e15faf676f8a\n# \u2560\u25502fdb3281-7229-4f18-b9d9-bc5e3086d903\n# \u2560\u2550f77b7762-29ee-4472-a4ee-a5c1a6dfb369\n# \u2560\u2550e9d5ee6c-de1a-41ee-850e-a6f5471537ea\n# \u2560\u255093b0afb2-e9f3-434d-b21a-2ccad6a12d90\n# \u2560\u255090fe2c2b-d62d-40b5-9a34-0eb1e9836250\n# \u255f\u25008bcc15c7-d66a-40cc-9f33-50c6de62fadc\n# \u2560\u2550428c124a-1052-45c8-a49b-b1047267d644\n# \u2560\u2550863624c7-f378-467a-bed2-94182bae73b7\n# \u2560\u25500e8b6a32-ba23-4e37-b78c-8ffb3779a43e\n# \u2560\u25509e35d6a1-df94-4a27-9e04-234548495780\n# \u2560\u25501b45a9bf-56c7-4b7b-bdd5-b4fcaa572ec0\n# \u255f\u250060b263eb-f786-40c4-b60b-2daabdacba7b\n# \u2560\u2550b0db7a9c-2498-46c5-bf3c-280d3083ba88\n# \u2560\u2550412ee0c1-26ad-4b9f-9d6e-c552d8431e76\n# \u2560\u2550aa5e313d-19d9-4300-a65e-f547f7e571d0\n# \u2560\u25500ba25fa7-72cb-4d6e-bfaf-eddcf12b9f9c\n# \u2560\u2550d5251a23-b71e-4faf-9f5a-f6ab1d2ffb7d\n# \u2560\u2550b717d872-0d16-4556-a6c8-1ccc3c7b76c3\n# \u2560\u255072b3ed37-3f3f-4a7d-9036-dadb06c3e1e4\n# \u2560\u25508c6e966d-9185-4a44-8cd9-e69528cee54b\n# \u2560\u25501e9be5f5-ab15-4a29-8fd6-d20fee084ad5\n# \u2560\u25503baed4bd-1c0c-4d44-b7ab-f7c0627fda1b\n# \u255f\u250059b884e5-a55a-42f6-9ed4-404d55eae5e9\n# \u2560\u25503cbd7219-7fb0-4c6e-a2ad-724e97b67d94\n# \u2560\u255093a86467-cf02-4d3c-b127-79247a588250\n# \u2560\u25500423223e-90c5-4d86-8370-66ddee6ba496\n# \u2560\u2550721c67fd-6d40-4171-89c4-21a1c0064880\n# \u2560\u25505a4dd40b-d917-4634-a4d4-255c63d68d3f\n# \u2560\u25502edcc72c-bfa4-4623-a34f-220c0df9c4d3\n# \u2560\u255020097ff6-c516-454c-978f-4c92e6c72d52\n# \u2560\u2550fbbc0558-7916-4308-b8be-4428f47ca4e5\n# \u2560\u2550290d3b7f-ee12-476c-a4f2-189671c84398\n# \u2560\u2550cc728038-b20f-4b93-97a7-883d5734a0b2\n# \u2560\u25502eca9295-370d-41e9-95a4-b56ee2b0e1dc\n# \u2560\u2550b4c5a72d-5ce1-4e21-a04f-8344d1023648\n# \u2560\u25504f11cc1a-a78e-4d6c-8bd2-857f85f48aa8\n# \u2560\u255050039da8-2c71-4a1d-8cc1-2d4bd8126988\n# \u2560\u2550efb2b80c-af6c-4f6e-bcba-e57c7c39cab3\n# \u255f\u25001ca893dd-2040-47df-8fa0-c3cb4dd0d7dc\n# \u255f\u2500dbbcd955-e0c9-4a6c-81bf-fe5c5ad2f018\n# \u2560\u25505565b0a4-792b-40f6-82a2-f8f642432129\n# \u2560\u25506d4175a4-af6e-4a08-bcd2-0b1966ae9035\n# \u255f\u2500c4a58e43-2ea8-48fa-a99d-09f83b1b8ba8\n# \u2560\u2550e0e5ef4a-fc35-4d9b-9a34-a9439d87051d\n# \u2560\u2550c9d041cb-6a29-449a-8909-b529e8c562a6\n# \u255f\u2500c77241fb-bd9e-4270-bd04-e8b5bcb2406b\n# \u2560\u2550d507db6a-f869-4dc3-b7ef-fd3518fc1660\n# \u2560\u2550f924796f-52f3-4b4b-aa47-61a179874647\n# \u2560\u255087296377-fe6d-4225-b114-a8c3b8bea1bc\n# \u2560\u2550aa61efe4-b3a2-4379-a748-f37cd7f9c6fb\n# \u2560\u2550182ab07b-a3e6-47f0-8de5-d59113027c43\n# \u2560\u25506262451f-4dcf-4f84-8be6-2f8fbf2631bd\n# \u2560\u25503d664567-d879-41f7-9e1a-cdfc08e4e7c9\n# \u2560\u25505e03a17e-861e-4749-b18e-00e293d24f28\n# \u2560\u25504d5c7119-f2bf-44ed-bc20-5597a795fbcd\n# \u2560\u2550af2e86c1-4c58-4577-9ae9-313f8ae78475\n# \u2560\u25509461292e-3658-41e2-8349-45790fa7c9e0\n# \u2560\u25507e03b8d1-1ddb-435f-b9ba-b72b0c44da18\n# \u2560\u2550e54420c1-1ff3-4f38-b9b8-0e3a18127c9a\n# \u2560\u2550458dfaeb-0370-4e61-90a2-f5b54a0fab42\n# \u2560\u2550b7729c93-781a-46ec-b057-65c4e9e15a04\n# \u2560\u2550543de112-675c-4368-957d-f37647ad85bd\n# \u2560\u255037f6486e-e03c-4ddb-bca6-d13157d69822\n# \u2560\u255068d89124-d6e9-4609-b12a-d3b508733680\n# \u255f\u25006003cd52-89ea-4d93-ac00-43ca395357b8\n# \u255f\u250092c42555-8550-4c1b-9b1a-502813c40237\n# \u2560\u25505c3f1925-ebfb-4bef-8425-635262927bf1\n# \u2560\u2550ec02b4a7-529b-4d37-ba4b-bf146a33ee0f\n# \u2560\u2550954f166b-e8db-4cf7-a0a2-75ab3b3acbe0\n# \u2560\u2550e97dcedb-4b53-4ce8-a0e9-ed20b77d8b2d\n# \u255f\u2500f662c9f4-8004-43d6-ad1e-872ad3d24e48\n# \u2560\u2550c72335d5-39e3-4ab9-a398-e3960dcafe0c\n# \u2560\u25508ebae10c-3148-43fe-9b14-f07934c3b2ea\n# \u2560\u2550e49a1426-bcf5-453a-8753-2bb8387e67eb\n# \u2560\u255046bd26e6-c1bf-4fa3-890a-2d424865c2dc\n# \u255f\u250055e79482-e30e-4eea-b083-cac2a9667348\n# \u2560\u25509537df9b-7fc8-4b32-bc7c-d8ee8730d73a\n# \u2560\u25506434a9f1-aa8a-491f-ac7e-c58b3a4b2638\n# \u2560\u25504abd57c6-1a0c-4e7c-a195-d07ddc299b2c\n# \u2560\u2550aa2c895f-7219-4b98-bf50-c96d676ead09\n# \u2560\u25505fb204e1-d150-4a3c-ac19-6fa5b67b072b\n# \u2560\u2550c0df29b8-368d-40d1-bad0-73493531903a\n# \u2560\u255051046c66-6e14-420e-8a5e-5a58580841a6\n# \u2560\u25503659f664-3fc3-48bd-94e3-f57ae84e7301\n# \u255f\u25009392cdfb-ceef-40ac-a67b-8c7ca33de123\n# \u2560\u255020605ee6-f245-4e77-b014-a8e42a520e8d\n# \u2560\u2550c69f8278-9627-458b-8204-91ae08efbf92\n# \u2560\u2550a5f4d797-db11-4d6a-8906-b4af6804a936\n# \u2560\u255046f62dad-820b-42d3-8cdd-ab02cacabc47\n# \u2560\u2550758082fe-038e-4090-b658-111db3ee1f13\n# \u2560\u2550931e4862-c109-4b17-9048-7826f3dd0c6f\n# \u2560\u25503017c6db-acee-422d-bb97-692495972631\n# \u2560\u2550404716dd-7a05-4f3b-b336-cab7fc679ed1\n# \u2560\u255043b3b163-05a7-4c06-a948-bf5c001b7af0\n# \u255f\u25004c0169d7-b280-4326-aa79-9c979280077a\n# \u255f\u2500694d2ceb-233f-49ea-9416-9e8a8f272d38\n# \u255f\u250072a095fa-c5cf-4eb1-909d-d8b49af0bdc9\n# \u255f\u25008a20fa4c-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\u0304 = [2;-1;1]\n\u03bb = [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(\"\u03bb = \", 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(\"\u03bb = \", 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": "using MultipleViewGeometry, Test, Random\nusing MultipleViewGeometry.ModuleCostFunction\nusing MultipleViewGeometry.ModuleTypes\nusing MultipleViewGeometry.ModuleConstraints\nusing MultipleViewGeometry.ModuleConstruct\nusing LinearAlgebra\nusing StaticArrays\nusing GeometryTypes\n\n# Fix random seed.\nRandom.seed!(1234)\n# Construct two camera matrices and parametrise two planar surfaces.\nf = 50\nimage_width = 640 / 10\nimage_height = 480 / 10\n\ud835\udc0a\u2081 = @SMatrix [f 0 0 ;\n               0 f 0 ;\n               0 0 1 ]\n\ud835\udc11\u2081 = SMatrix{3,3,Float64,9}(rotxyz(0, 25*(pi/180), 0))\n\ud835\udc2d\u2081 = [-30.0, 0.0, -5.0]\n\n\ud835\udc0a\u2082 = @SMatrix [f 0 0 ;\n               0 f 0 ;\n               0 0 1 ]\n\n\ud835\udc11\u2082 = SMatrix{3,3,Float64,9}(rotxyz(0, -25*(pi/180), 0))\n\ud835\udc2d\u2082 = [30.0, 0.0, 5.0]\n\n# Normals and distance from origin\n\ud835\udc27\u2081 = [0.0, 0.0, 1.0]\nd\u2081 = 55.0\n\n# Normals and distance from origin\n\ud835\udc27\u2081 = [0.0, 0.0, 1.0]\nd\u2081 = 55.0\n\n\ud835\udc27\u2082 = [0.5, -0.2, 2.0]\nd\u2082 = 145.0\n\n\ud835\udcb3\u2081 = generate_planar_points(\ud835\udc27\u2081,d\u2081, 20, 50)\n\ud835\udcb3\u2082 = generate_planar_points(\ud835\udc27\u2082,d\u2082, 20, 50)\n\n\nworld_basis = (Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0), Vec(0.0, 0.0, 1.0))\ncamera_basis = (Point(0.0, 0.0, 0.0), Vec(-1.0, 0.0, 0.0), Vec(0.0, -1.0, 0.0), Vec(0.0, 0.0, 1.0))\npicture_basis = (Point(0.0, 0.0), Vec(-1.0, 0.0), Vec(0.0, -1.0))\n\ncamera\u2081 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\ncamera\u2082 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\nrelocate!(camera\u2081, \ud835\udc11\u2081, \ud835\udc2d\u2081)\nrelocate!(camera\u2082, \ud835\udc11\u2082, \ud835\udc2d\u2082)\n\n\ud835\udc11\u2081\u2032, \ud835\udc2d\u2081\u2032 = ascertain_pose(camera\u2081, world_basis... )\n\ud835\udc0a\u2081\u2032 = obtain_intrinsics(camera\u2081, CartesianSystem())\n\ud835\udc11\u2082\u2032, \ud835\udc2d\u2082\u2032 = ascertain_pose(camera\u2082, world_basis... )\n\ud835\udc0a\u2082\u2032 = obtain_intrinsics(camera\u2082, CartesianSystem())\n\n\ud835\udc0f\u2081 = construct(ProjectionMatrix(),\ud835\udc0a\u2081\u2032,\ud835\udc11\u2081\u2032,\ud835\udc2d\u2081\u2032)\n\ud835\udc0f\u2082 = construct(ProjectionMatrix(),\ud835\udc0a\u2082\u2032,\ud835\udc11\u2082\u2032,\ud835\udc2d\u2082\u2032)\n\n# Set of corresponding points.\n\u2133\u2081 = project(camera\u2081,\ud835\udc0f\u2081,\ud835\udcb3\u2081)\n\u2133\u2081\u02b9= project(camera\u2082,\ud835\udc0f\u2082,\ud835\udcb3\u2081)\n\u2133\u2082 = project(camera\u2081,\ud835\udc0f\u2081,\ud835\udcb3\u2082)\n\u2133\u2082\u02b9= project(camera\u2082,\ud835\udc0f\u2082,\ud835\udcb3\u2082)\n\n# 3D points corresponding to the first and second planar surface\n\ud835\udcb4\u2081 = triangulate(DirectLinearTransform(),\ud835\udc0f\u2081,\ud835\udc0f\u2082,(\u2133\u2081,\u2133\u2081\u02b9))\n\ud835\udcb4\u2082 = triangulate(DirectLinearTransform(),\ud835\udc0f\u2081,\ud835\udc0f\u2082,(\u2133\u2082,\u2133\u2082\u02b9))\n\n# Triangulating with the same projection matrices that were used to construct\n# (\u2133,\u2133\u02b9) should yield 3D points that lie on a plane.\nN = length(\ud835\udcb4\u2081)\nfor n = 1:N\n    X = \ud835\udcb4\u2081[n]\n    @test isapprox(dot(\ud835\udc27\u2081,X) - d\u2081, 0.0; atol = 1e-11)\nend\n\nN = length(\ud835\udcb4\u2082)\nfor n = 1:N\n    X = \ud835\udcb4\u2082[n]\n    @test isapprox(dot(\ud835\udc27\u2082,X) - d\u2082, 0.0; atol = 1e-11)\nend\n\n# Triangulating with the same projection matrices that were used to construct\n# (\u2133,\u2133\u02b9) should yield the same 3D points as the original \ud835\udcb3.\nN = length(\ud835\udcb4\u2081)\nfor n = 1:N\n    @test  isapprox(sum(abs.(\ud835\udcb3\u2081[n]-\ud835\udcb4\u2081[n])/3), 0.0; atol = 1e-12)\nend\n\nN = length(\ud835\udcb4\u2082)\nfor n = 1:N\n    @test  isapprox(sum(abs.(\ud835\udcb3\u2082[n]-\ud835\udcb4\u2082[n])/3), 0.0; atol = 1e-12)\nend\n", "meta": {"hexsha": "554de64eaea5c1021fd907f91445882e959aae54", "size": 2742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/planar_triangulate_tests.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": "test/planar_triangulate_tests.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": "test/planar_triangulate_tests.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": 28.5625, "max_line_length": 99, "alphanum_fraction": 0.6652078775, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7713472527755104}}
{"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 LinearAlgebra: dot, norm, diagm\n# using SymPy: symbols\n\n@testset \"Test length in a hexagonal lattice\" begin\n    g = MetricTensor(1, 1, 2, 90, 90, 120)  # Primitive hexagonal\n    @test g \u2248 MetricTensor([1, 0, 0], [-1 // 2, sqrt(3) / 2, 0], [0, 0, 2])\n    @test g \u2248 MetricTensor(Lattice([\n        1.0 -1/2 0.0\n        0.0 sqrt(3)/2 0.0\n        0.0 0.0 2.0\n    ]))\n    a = [1, 2, 1]\n    @test dot(a, g, a) \u2248 7\n    @test norm([1, 2, 1], g)^2 \u2248 7\nend\n\n@testset \"Test distance between atoms in a hexagonal lattice\" begin\n    g = MetricTensor(1, 1, 2, 90, 90, 120)  # Primitive hexagonal\n    a = [1, 1, 1]\n    b = [1 // 3, 1 // 3, 1 // 2]\n    @test distance(a, g, b)^2 == 13 / 9\nend\n\n@testset \"Test direction cosine in a tetragonal lattice\" begin\n    g = MetricTensor(2, 2, 3, 90, 90, 90)  # Primitive tetragonal\n    @test g == MetricTensor(Lattice(diagm([2, 2, 3])))\n    @test g == MetricTensor([2, 0, 0], [0, 2, 0], [0, 0, 3])\n    a = [1, 2, 1]\n    b = [0, 0, 1]\n    @test directioncosine(a, g, b)^2 \u2248 9 / 29\nend\n\n# @testset \"Symbolic calculation\" begin\n#     a, c = symbols(\"a, c\", positive = true)\n#     @test MetricTensor(a, a, c, 90, 90, 120) ==\n#           MetricTensor([a^2 -0.5*a^2 0; -0.5*a^2 a^2 0; 0 0 c^2])  # Primitive hexagonal\n# end\n\n# From https://ssd.phys.strath.ac.uk/wp-content/uploads/Crystallographic_maths.pdf\n@testset \"Find angle \u03b8 between [100] and [111] directions in GaN\" begin\n    a, c = 3.19u\"angstrom\", 5.19u\"angstrom\"\n    g = MetricTensor(a, a, c, 90, 90, 120)\n    @test directioncosine([1, 0, 0], g, [1, 1, 1]) == a / 2 / sqrt(a^2 + c^2)\nend\n", "meta": {"hexsha": "22246674f6377f6b838778f0ae149fb4808a5775", "size": 1573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/metric.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": "test/metric.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": "test/metric.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": 34.9555555556, "max_line_length": 90, "alphanum_fraction": 0.5683407502, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7713438326103798}}
{"text": "using Plots, Distributions, LaTeXStrings\n\n# Evaluates target distribution \u03c0(q)\nfunction \u03c0_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 \u03c0(p|q)\nfunction \u03c0_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(\u03c0_pq(p,q))\nend\n\n# Evaluates Potential energy V(q)\nfunction V(q)\n    return -log(\u03c0_q(q))\nend\n\n# Evaluates dV/dq at q\nfunction dV_dq(q)\n    return 1/\u03c0_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    \u03f5 = 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        \u03c8 = p_trajectory[j-1] - \u03f5/2 * dV_dq(q_trajectory[j-1])\n        q_trajectory[j] = q_trajectory[j-1] + \u03f5*\u03c8\n        p_trajectory[j] = \u03c8 - \u03f5/2*dV_dq(q_trajectory[j])\n    end\n\n    return q_trajectory, p_trajectory\nend\n\nfunction hmc_alg(q\u2080, p\u2080)\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\u2080\n    p_samples[1] = p\u2080\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        \u03b1 = min(1, exp(H(p,q) - H(-p_L,q_L)))\n\n        if rand() < \u03b1\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 = [\u03c0_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\u00df-Legendre nodes with $s$ stages and $\\bar{c}$ are Gau\u00df-Lobatto nodes with $\\sigma$ stages.\n\"\"\"\nfunction get_lobatto_glrk_coefficients(s, \u03c3=s+1, T=Float64)\n    if \u03c3 == 1\n        @error \"Lobatto III coefficients for one stage are not defined.\"\n    end\n\n    c = get_gauss_nodes(s)\n    b\u0304 = get_lobatto_weights(\u03c3)\n    c\u0304 = get_lobatto_nodes(\u03c3)\n    M = [ c[j]^(k-1) for k in 1:s, j in 1:s ]\n    \n    row(i) = begin\n        r = [ c\u0304[i]^k / k for k in 1:s ]\n        M \\ r\n    end\n    \n    a\u0304 = vcat([row(i)' for i in 1:\u03c3]...)\n\n    CoefficientsIRK{T}(:LobattoIIIGLRK, s^2, s, \u03c3, a\u0304, b\u0304, c\u0304)\nend\n\n\nfunction get_lobatto_\u03c9_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    \u03c9 = inv(L) * Q\n    \n    return \u03c9\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; \u03b1=10.0, \u03c1=28.0, \u03b2=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} = \u03b1 * (y - x)\\$\n\\$\\\\frac{dy}{dt} = x * (\u03c1 - z) - y\\$\n\\$\\\\frac{dz}{dt} = x * y - \u03b2 * 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- `\u03b1::Float64`: Constant associated with Lorenz system of differential equations.\n- `\u03c1::Float64`: Constant associated with Lorenz system of differential equations.\n- `\u03b2::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    \u03b1::Float64=10.0,\n    \u03c1::Float64=28.0,\n    \u03b2::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] + (\u03b1 * (y[i] - x[i]) * dt)\n        y[i + 1] = y[i] + ((x[i] * (\u03c1 - z[i]) - y[i]) * dt)\n        z[i + 1] = z[i] + ((x[i] * y[i] - \u03b2 * 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": "@safetestset \"Binomial Model\" begin\n    using DifferentialEvolutionMCMC, Test, Random, Turing, Parameters, Distributions\n    Random.seed!(29542)\n    N = 10\n    k = rand(Binomial(N, .5))\n    data = (N = N,k = k)\n    \n    prior_loglike(\u03b8) = logpdf(Beta(1, 1), \u03b8)\n\n    sample_prior() = rand(Beta(1, 1))\n\n    bounds = ((0,1),)\n    names = (:\u03b8,)\n\n    function loglike(data, \u03b8)\n        return logpdf(Binomial(data.N, \u03b8), data.k)\n    end\n\n    model = DEModel(; \n        sample_prior, \n        prior_loglike, \n        loglike, \n        data,\n        names\n    )\n\n    de = DE(;sample_prior, bounds, burnin=1500, Np=3)\n\n    n_iter = 3000\n    chains = sample(model, de, n_iter)\n    \u03bc\u03b8 = describe(chains)[1][:,:mean][1]\n    \u03c3\u03b8 = describe(chains)[1][:,:std][1]\n    rhat = describe(chains)[1][:,:rhat][1]\n    solution = Beta(k + 1, N - k + 1)\n    @test \u03bc\u03b8 \u2248 mean(solution) rtol = .02\n    @test \u03c3\u03b8 \u2248 std(solution) rtol = .02\n    @test rhat \u2248 1.0 atol = .01\nend", "meta": {"hexsha": "6d434599483edbed9b17c57e9fdd2fb4d736cedb", "size": 945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/binomial_tests.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/binomial_tests.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/binomial_tests.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": 24.8684210526, "max_line_length": 84, "alphanum_fraction": 0.5597883598, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7713369131260206}}
{"text": "\n###############################################\n# Solve laplace equation\n\n# by: Jose Miguel Mu\u00f1oz\n# please contact me if this doesn't works\n###############################################\n\nusing Plots, Statistics, BenchmarkTools\n###############################################\n#       BOUNDARY\n###############################################\nN = 100\na , b = 0,2\n\nRx = a:(b-a)/(N-1):b\nRy = Rx\n\nboundary_X_Up = map(rx -> 0,Rx)\n\nboundary_X_Down = map(rx -> 0, Rx)\n\nboundary_Y_R = map(rx -> 10,Rx)\n\nboundary_Y_L = map(rx -> 0,Rx)\n\n\nV = zeros(N, N)\n\nV[1,:] = boundary_X_Up\nV[:,1] = boundary_Y_R\nV[N,:] = boundary_X_Down\nV[:,N] = boundary_Y_L\n\n###############################################\n#       SOLVER\n###############################################\nfunction solver!(V,n_inter,N=N, tol=1)\n    for rep = 1:n_inter\n        \n        for row = 2:N-1\n            for column = 2:N-1\n                V[row, column] = mean([V[row-1, column],V[row+1, column],V[row, column-1],V[row, column+1]])\n                #if (row+10)^2+(column+10)^2<1000\n                #    V[row, column]=1\n                #end\n    end end\n end\n    return V\nend\n\n###############################################\n#       Ask for the boundaries\n###############################################\n@benchmark solver!(V,1000)\nV = solver!(V,100000)\n\nplot(Ry, Ry, V, linetype=:contourf,title = \"Solucion por Gauss_Seidel\")\n\n#gr()\n#anim = @animate for n = 1:100:1000\n#    heatmap(vss[:,:,n])\n#end\n#gif(anim)\nusing Statistics\nplot(Ry, Ry, (V-Space*1.01), linetype=:contourf,title = \"Solucion por Jacobi\")\nmean(V-Space)\nmean(V.^2-Space.^2)\nstd(V.^2-Space.^2)\n\n\n#######################################################\n#       Convergence Analysis\n#######################################################\nlistconvGauss=[]\nfor n_reps=500:100:5000\n    V = rand(N, N)\n\n    V[1,:] = boundary_X_Up\n    V[:,1] = boundary_Y_R\n    V[N,:] = boundary_X_Down\n    V[:,N] = boundary_Y_L\n\n    V = solver!(V,n_reps)\n    append!(listconvGauss,abs(mean(V-Space)))\nend\nlistconvGauss\n\n\nalistconvSOR=map(x->abs(x),listconvSOR)\nalistconvJacobi=map(x->abs(x),listconvJacobi)\nalistconvGauss=map(x->abs(x),listconvGauss)\nplot()\nplot!(Vector(500:100:5000),alistconvGauss,label=\"Metodo Gauss_Seidel\")\nplot!(ps,alistconvSOR[begin+6:end],label=\"Metodo SOR\")\nplot!(ps,alistconvJacobi.+randn(),label=\"Metodo Jacobi\")\nxlabel!(\"Numero de iteraciones\")\nylabel!(\"\u0394\u03c6\")\nps\nalistconvSOR[begin:end-6]\n\nalistconvJacobi\nps", "meta": {"hexsha": "5a9f4abe77bf0485a887e73d851703d690ace56b", "size": 2432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2D/2Gauss_Seidel.jl", "max_stars_repo_name": "munozariasjm/Laplace-and-Julia", "max_stars_repo_head_hexsha": "c8e4c536e7735cbd5958545525237413061b716e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2D/2Gauss_Seidel.jl", "max_issues_repo_name": "munozariasjm/Laplace-and-Julia", "max_issues_repo_head_hexsha": "c8e4c536e7735cbd5958545525237413061b716e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2D/2Gauss_Seidel.jl", "max_forks_repo_name": "munozariasjm/Laplace-and-Julia", "max_forks_repo_head_hexsha": "c8e4c536e7735cbd5958545525237413061b716e", "max_forks_repo_licenses": ["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.6116504854, "max_line_length": 108, "alphanum_fraction": 0.5020559211, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7713344349675855}}
{"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": "### Testing quadrature related function\nusing Jacobi\nusing Polynomials\n@static if VERSION > v\"0.7-\"\n    using Test\nelse\n    using Base.Test\nend\n\nNmax = 200\na = rand(1:6, Nmax)  # Coefficient for a ninth degree polynomial\n\nN = 10\nQ = 5\np = Poly(a[1:N])\np_int = polyint(p)\nX = polyval(p_int, 1.0) - polyval(p_int, -1.0)\nq = Quadrature(GJ, Q, 0.0, 0.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n# I'm not getting the precision I need for BigFloats. Should investigate further\n#X = polyval(p1_int, BigFloat(1.0)) - polyval(p1_int, BigInt(-1.0))\n#q2 = Quadrature(GJ, 5, BigFloat(0), BigFloat(0), BigFloat)\n#y = polyval(p1, qzeros(q2))\n#Xg= sum(qweights(q2) .* y)\n#@test abs(Xg-X) 0.0 200*eps(Xg)\n\n\n# Weights a=1, b=2\np2 = p * Poly([1, -1]) * Poly([1, 1])^2\np2_int = polyint(p2)\nX = polyval(p2_int, 1.0) - polyval(p2_int, -1.0)\nq = Quadrature(GJ, Q, 1.0, 2.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n# Test Gauss-Radau:\n# GRJM\nN = 9\nQ = 5\np = Poly(a[1:N])\np_int = polyint(p)\nX = polyval(p_int, 1.0) - polyval(p_int, -1.0)\nq = Quadrature(GRJM, Q, 0.0, 0.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n# GRJP\nq = Quadrature(GRJP, Q, 0.0, 0.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n\n# Weights a=1, b=2 GRJM\np2 = p * Poly([1, -1]) * Poly([1, 1])^2\np2_int = polyint(p2)\nX = polyval(p2_int, 1.0) - polyval(p2_int, -1.0)\nq = Quadrature(GRJM, Q, 1.0, 2.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n\n# Weights a=1, b=2 GRJP\np2 = p * Poly([1, -1]) * Poly([1, 1])^2\np2_int = polyint(p2)\nX = polyval(p2_int, 1.0) - polyval(p2_int, -1.0)\nq = Quadrature(GRJP, Q, 1.0, 2.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n\n\n\n\n# Test Gauss-Lobatto\nN = 8\nQ = 5\np = Poly(a[1:N])\np_int = polyint(p)\nX = polyval(p_int, 1.0) - polyval(p_int, -1.0)\nq = Quadrature(GLJ, Q, 0.0, 0.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n# Weights a=1, b=2 GLJ\np2 = p * Poly([1, -1]) * Poly([1, 1])^2\np2_int = polyint(p2)\nX = polyval(p2_int, 1.0) - polyval(p2_int, -1.0)\nq = Quadrature(GRJM, Q, 1.0, 2.0, Float64)\ny = polyval(p, qzeros(q))\nXg = sum(qweights(q) .* y)\n@test Xg \u2248 X\n\n\n# Testing derivatives:\n# GJ\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GJ, Q, 0, 0)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n# GRJM\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GRJM, Q, 0, 0)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n\n# GRJP\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GRJP, Q, 0, 0)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n# GLJ\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GLJ, Q, 0, 0)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n\n# Testing with weights a and b\na1 = 0.5\nb1 = 0.9\n\n# GJ\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GJ, Q, a1, b1)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n# GRJM\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GRJM, Q, a1, b1)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n# GRJP\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GRJP, Q, a1, b1)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n# GLJ\nQ = 10\nN = 10\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GLJ, Q, a1, b1)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\nQ = 200\nN = 200\np = Poly(a[1:N])\ndp = polyder(p)\nq = Quadrature(GLJ, Q, a1, b1)\nz = qzeros(q)\ny = polyval(p, z)\ndy = polyval(dp, z)\ndyg = qdiff(q) * y\n@test dy \u2248 dyg\n\n\n# Test interpolation:\n# GJ\n\nN = 10\nQ = 10\np = Poly(a[1:N])\nx = -1.0:0.02:1.0\nue = polyval(p, x)\nq = Quadrature(GLJ, Q, 1.0, 0.5)\nz = qzeros(q)\nu = polyval(p, z)\nI = interp_mat(x, z)\nui = I * u\n@test ui \u2248 ue\n", "meta": {"hexsha": "138e60033db09cca0627a98609d05f0f4d849eff", "size": 4097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testgauss.jl", "max_stars_repo_name": "KristofferC/Jacobi.jl", "max_stars_repo_head_hexsha": "b185af2196a6f611a75bd40728ffe1a4a2c86af3", "max_stars_repo_licenses": ["MIT"], "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/testgauss.jl", "max_issues_repo_name": "KristofferC/Jacobi.jl", "max_issues_repo_head_hexsha": "b185af2196a6f611a75bd40728ffe1a4a2c86af3", "max_issues_repo_licenses": ["MIT"], "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/testgauss.jl", "max_forks_repo_name": "KristofferC/Jacobi.jl", "max_forks_repo_head_hexsha": "b185af2196a6f611a75bd40728ffe1a4a2c86af3", "max_forks_repo_licenses": ["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.1422594142, "max_line_length": 80, "alphanum_fraction": 0.5850622407, "num_tokens": 1900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7713153621099609}}
{"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 \u03b8 (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\u00f72)\n        k_choose_k_over_2 = binomial(big(k), k\u00f72)\n        \n        for j = 0:(k\u00f72 - 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\u00f72 term\n        value *= sgn / \u03c0 / k_choose_k_over_2\n\n    else\n        norm_ = 0\n        for j = 0:(k-1)\u00f72\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 / \u03c0\ntheta_dist_2d = ThetaDistribution(2)\nfor x = range(0, \u03c0; length=10)\n    computed_cdf = cdf(theta_dist_2d, x)\n    expected_cdf = x / \u03c0\n    @assert (computed_cdf \u2248 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, \u03c0; length=10)\n    computed_cdf = cdf(theta_dist_3d, x)\n    expected_cdf = 0.5 * (1 - cos(x))\n    @assert (computed_cdf \u2248 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": "function testDCT1d(N=32)\n  Random.seed!(1235)\n  x = zeros(ComplexF64, N^2)\n  for i=1:5\n    x .+= rand()*cos.(rand(1:N^2)*collect(1:N^2)) .+ 1im*rand()*cos.(rand(1:N^2)*collect(1:N^2))\n  end\n  D1 = DCTOp(ComplexF64,(N^2,),2)\n  D2 = sqrt(2/N^2)*[cos(pi/(N^2)*j*(k+0.5)) for j=0:N^2-1,k=0:N^2-1]\n  D2[1,:] .*= 1/sqrt(2)\n  D3 = DCTOp(ComplexF64,(N^2,),4)\n  D4 = sqrt(2/N^2)*[cos(pi/(N^2)*(j+0.5)*(k+0.5)) for j=0:N^2-1,k=0:N^2-1]\n\n  y1 = D1*x\n  y2 = D2*x\n\n  @test norm(y1 - y2) / norm(y1) \u2248 0 atol=0.01\n\n  y3 = D3*x\n  y4 = D4*x\n  @test norm(y3 - y4) / norm(y1) \u2248 0 atol=0.01\n\n  x1 = adjoint(D1)*y1\n  @test norm(x1 - x) / norm(x) \u2248 0 atol=0.01\n\n  x2 = adjoint(D3)*y3\n  @test norm(x2 - x) / norm(x) \u2248 0 atol=0.01\nend\n\nfunction testFFT1d(N=32,shift=true)\n  Random.seed!(1234)\n  x = zeros(N^2)\n  for i=1:5\n    x .+= rand()*cos.(rand(1:N^2)*collect(1:N^2))\n  end\n  D1 = FFTOp(ComplexF64,(N^2,),shift)\n  D2 =  1.0/N*[exp(-2*pi*im*j*k/N^2) for j=0:N^2-1,k=0:N^2-1]\n\n  y1 = D1*x\n  if shift\n    y2 = fftshift(D2*fftshift(x))\n  else\n    y2 = D2*x\n  end\n  @test norm(y1 - y2) / norm(y1) \u2248 0 atol=0.01\n\n  x1 = adjoint(D1) * y1\n  if shift\n    x2 = ifftshift(adjoint(D2)*ifftshift(y2))\n  else\n    x2 = adjoint(D2)*y2\n  end\n  @test norm(x1 - x2) / norm(x1) \u2248 0 atol=0.01\nend\n\nfunction testFFT2d(N=32,shift=true)\n  Random.seed!(1234)\n  x = zeros(N^2)\n  for i=1:5\n    x .+= rand()*cos.(rand(1:N^2)*collect(1:N^2))\n  end\n  D1 = FFTOp(ComplexF64,(N,N),shift)\n\n  idx = CartesianIndices((N,N))[collect(1:N^2)]\n  D2 =  1.0/N*[ exp(-2*pi*im*((idx[j][1]-1)*(idx[k][1]-1)+(idx[j][2]-1)*(idx[k][2]-1))/N) for j=1:N^2, k=1:N^2 ]\n\n  y1 = D1*x\n  if shift\n    y2 = D2*vec(fftshift(reshape(x,N,N)))\n    y2 = vec(fftshift(reshape(y2,N,N)))\n  else\n    y2 = D2*x\n  end\n  @test norm(y1 - y2) / norm(y1) \u2248 0 atol=0.01\n\n  x1 = adjoint(D1) * y1\n  if shift\n    x2 = adjoint(D2)*vec(ifftshift(reshape(y2,N,N)))\n    x2 = vec(ifftshift(reshape(x2,N,N)))\n  else\n    x2 = adjoint(D2)*y2\n  end\n  @test norm(x1 - x2) / norm(x1) \u2248 0 atol=0.01\nend\n\nfunction testWeighting(N=512)\n  Random.seed!(1234)\n  x1 = rand(N)\n  weights = rand(N)\n  W = WeightingOp(weights)\n  y1 = W*x1\n  y = weights .* x1\n\n  @test norm(y1 - y) / norm(y) \u2248 0 atol=0.01\n\n  x2 = rand(2*N)\n  W2 = WeightingOp(weights,2)\n  y2 = W2*x2\n  y = repeat(weights,2) .* x2\n\n  @test norm(y2 - y) / norm(y) \u2248 0 atol=0.01\nend\n\nfunction testGradOp1d(N=512)\n  x = rand(N)\n  G = GradientOp(eltype(x),size(x))\n  G0 = Bidiagonal(ones(N),-ones(N-1), :U)[1:N-1,:]\n\n  y = G*x\n  y0 = G0*x\n  @test norm(y - y0) / norm(y0) \u2248 0 atol=0.001\n\n  xr = transpose(G)*y\n  xr0 = transpose(G0)*y0\n\n  @test norm(y - y0) / norm(y0) \u2248 0 atol=0.001\nend\n\nfunction testGradOp2d(N=64)\n  x = repeat(1:N,1,N)\n  G = GradientOp(eltype(x),size(x))\n  G_1d = Bidiagonal(ones(N),-ones(N-1), :U)[1:N-1,:]\n\n  y = G*vec(x)\n  y0 = vcat( vec(G_1d*x), vec(x*transpose(G_1d)) )\n  @test norm(y - y0) / norm(y0) \u2248 0 atol=0.001\n\n  xr = transpose(G)*y\n  y0_x = reshape(y0[1:N*(N-1)],N-1,N)\n  y0_y = reshape(y0[N*(N-1)+1:end],N,N-1)\n  xr0 = transpose(G_1d)*y0_x + y0_y*G_1d\n  xr0 = vec(xr0)\n\n  @test norm(xr - xr0) / norm(xr0) \u2248 0 atol=0.001\nend\n\nfunction testSampling(N=64)\n  x = rand(ComplexF64,N,N)\n  idx = shuffle(collect(1:N^2)[1:N*div(N,2)])\n  SOp = SamplingOp(idx,(N,N))\n  y = SOp*vec(x)\n  x2 = adjoint(SOp)*y\n  # references\n  y_ref = vec(x[idx])\n  x2_ref = zeros(ComplexF64,N^2)\n  x2_ref[idx] .= y_ref\n  # perform tests\n  @test norm(y - y_ref) / norm(y_ref) \u2248 0 atol=0.000001\n  @test norm(x2 - x2_ref) / norm(x2_ref) \u2248 0 atol=0.000001\nend\n\nfunction testWavelet(M=64,N=60)\n  x = rand(M,N)\n  WOp = WaveletOp(Float64,(M,N))\n  x_wavelet = WOp*vec(x)\n  x_reco = reshape( adjoint(WOp)*x_wavelet, M, N)\n\n  @test norm(x_reco - x) / norm(x) \u2248 0 atol=0.001\nend\n\n@testset \"Linear Operators\" begin\n  @info \"test DCT-II and DCT-IV\"\n  for N in [2,8,16,32]\n    testDCT1d(N)\n  end\n  @info \"test FFT\"\n  for N in [8,16,32]\n    testFFT1d(N,false)\n    testFFT1d(N,true)\n    testFFT2d(N,false)\n    testFFT2d(N,true)\n  end\n  @info \"test Weighting\"\n  testWeighting(512)\n  @info \"test gradientOp\"\n  testGradOp1d(512)\n  testGradOp2d(64) \n  @info \"test sampling\"\n  testSampling(64)\n  @info \"test WaveletOp\"\n  testWavelet(64,64)\n  testWavelet(64,60)\nend\n", "meta": {"hexsha": "bfef887f7cab3aef9cb01d03db62bff224a5ef03", "size": 4189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testOperators.jl", "max_stars_repo_name": "alexjaffray/SparsityOperators.jl", "max_stars_repo_head_hexsha": "a17da68354affb57a400de49d77c0976ec278077", "max_stars_repo_licenses": ["MIT"], "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/testOperators.jl", "max_issues_repo_name": "alexjaffray/SparsityOperators.jl", "max_issues_repo_head_hexsha": "a17da68354affb57a400de49d77c0976ec278077", "max_issues_repo_licenses": ["MIT"], "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/testOperators.jl", "max_forks_repo_name": "alexjaffray/SparsityOperators.jl", "max_forks_repo_head_hexsha": "a17da68354affb57a400de49d77c0976ec278077", "max_forks_repo_licenses": ["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.8907103825, "max_line_length": 112, "alphanum_fraction": 0.5848651229, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7712929614342297}}
{"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 .\u2265 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2080\",\"p\u2081\"], w=\"labels\")\nend\n\n# \u2554\u2550\u2561 e42579e4-5e98-4cca-a425-a3b356dd03ba\nbegin\n\tusing LinearAlgebra\n\tp = [0.8, 0.2]\n\tnorm(p, 1)\nend\n\n# \u2554\u2550\u2561 6de3cf91-1739-49ac-aac5-0dcd72871461\nbegin\n\tusing Yao\n\tq = zero_state(1)\nend\n\n# \u2554\u2550\u2561 0ef307d4-84d3-11eb-10e7-07cc58485fba\ninclude(\"./essentials.jl\"); import .essentials\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c3898a67-d4b2-46a0-b5cc-69420762cd62\nmd\"\"\"\nWe naturally expect that the empirically observed frequencies also sum to one:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0d931337-ad9b-45d1-85fa-2b89f052099d\nbegin\n\t\u03a0\u2080 = [1 0;0 0]\n\tnorm(\u03a0\u2080 * p)\nend\n\n# \u2554\u2550\u2561 29c91dc7-cfda-42d4-bd0f-f479c611339e\nmd\"\"\"\nWe can repeat the process to get the probability of tails:\n\"\"\"\n\n# \u2554\u2550\u2561 c1ec3e28-93fc-42d5-8ef7-454cdb7f7c33\nbegin\n\t\u03a0\u2081 = [0 0; 0 1]\n\tnorm(\u03a0\u2081 * p)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 15416de9-5fe1-4cb7-a5bb-b4227fd9ad4a\nlet\n\t\u03f5 = 10^-10\n\tp_0 = range(\u03f5, 1-\u03f5;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\u2080'\", xrange = (0,1), yrange = (0,1)))\n\tplot!([0.5, 0.5], [0,1], ls = :dash)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9e2a3016-ac1a-447c-a223-3c4b80c62025\nmeasure(q)\n\n# \u2554\u2550\u2561 3e692d90-58ce-4562-a3fa-4d73e24b7b62\nmd\"\"\"\nLet us execute it a hundred times and study the result\n\"\"\"\n\n# \u2554\u2550\u2561 ee624636-c6fa-434a-bd6a-7048e755dffa\nresult = measure(q, nshots=100)\n\n# \u2554\u2550\u2561 0ebecb30-7db3-11eb-0dab-6ba6b1b2522a\nbegin\n\tusing StatsBase\n\t[fit(Histogram, Int.(result), 0:2).weights string.(0:1)]\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ba3d9b32-88dd-11eb-3b2a-0f96968e5bcb\nessentials.plot_blochsph(state(zero_state(1)))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a9bfa0e3-b128-43b1-af54-579d2bdcb3b7\nessentials.plot_hist(measure(zero_state(1) |> Ry(\u03c0/2), nshots=1024))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 770ae76e-6521-4613-b781-3627847ffae9\nessentials.plot_blochsph(state(zero_state(1) |> Ry(\u03c0/2)))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a2eaec0e-63a1-4771-899e-240289173b90\nessentials.plot_blochsph(state(zero_state(1) |> chain(1, put(1=>X), put(1=>Ry(\u03c0/2)))))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0c6bdade-da51-4442-90d4-f3c36aa06e4c\nbegin\n\tessentials.plot_hist(measure(zero_state(1) |> chain(1, put(1=>X), put(1=>Ry(\u03c0/2))), nshots=1024))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 21a24eb3-6104-4f6a-bae5-d11e504aad62\nessentials.plot_hist(measure(zero_state(1) |> chain(1, put(1=>Ry(\u03c0/2)), put(1=>Ry(\u03c0/2))), nshots=1024))\n\n# \u2554\u2550\u2561 5846d249-d73f-46d7-a1b9-09efc42ef331\nmd\"\"\"\nMany quantum algorithms exploit interference, for instance, the seminal [Deutsch-Josza algorithm](https://en.wikipedia.org/wiki/Deutsch\u2013Jozsa_algorithm), which is among the simplest to understand its significance.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f98f70cf-aaf2-4710-9ef7-33c401b10c06\nlet\n\tq0 = [1, 0]\n\tq1 = [1, 0]\n\tkron(q0, q1)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5a2944be-209c-4fbe-b1b1-19a5f9df4316\nmd\"\"\"\nNotice that 01 or 10 never appear in the measurement statistics.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25004f69ca95-0111-40d3-b74b-34e999f4f185\n# \u2560\u2550feadb782-9905-4e05-a0c9-e1b1b54fb3b0\n# \u255f\u2500c3898a67-d4b2-46a0-b5cc-69420762cd62\n# \u2560\u255002a05ce8-35ad-4192-a9d6-e7d3cc29e6ba\n# \u255f\u2500a776d9b8-9adb-4985-9830-165acb8d805b\n# \u2560\u2550c54da392-7d0b-11eb-278e-b3a7ec910fc7\n# \u255f\u25008c7034ce-8286-4d06-9fe1-17581695219c\n# \u2560\u2550e42579e4-5e98-4cca-a425-a3b356dd03ba\n# \u255f\u250013533ef2-3be4-4aea-981d-0bc77ec5db57\n# \u2560\u25500d931337-ad9b-45d1-85fa-2b89f052099d\n# \u255f\u250029c91dc7-cfda-42d4-bd0f-f479c611339e\n# \u2560\u2550c1ec3e28-93fc-42d5-8ef7-454cdb7f7c33\n# \u255f\u2500de543889-d698-4926-a2a2-9aea48578fd8\n# \u255f\u2500caa23a10-d43e-4a8c-b987-af69b55ed16e\n# \u2560\u2550cac5a2c0-6913-4997-b29d-154250be44dd\n# \u255f\u25001dee601c-2f9f-46d8-be37-99d31e589ebe\n# \u2560\u255015416de9-5fe1-4cb7-a5bb-b4227fd9ad4a\n# \u255f\u2500d803bf96-6cd4-4874-a3f7-ed7c0bf16267\n# \u255f\u25004cf8cd38-ac26-48f5-8507-9ac56fb90867\n# \u2560\u25506de3cf91-1739-49ac-aac5-0dcd72871461\n# \u255f\u25001b623852-7074-4211-bbcd-a65ac55c3070\n# \u2560\u25509e2a3016-ac1a-447c-a223-3c4b80c62025\n# \u255f\u25003e692d90-58ce-4562-a3fa-4d73e24b7b62\n# \u2560\u2550ee624636-c6fa-434a-bd6a-7048e755dffa\n# \u2560\u25500ebecb30-7db3-11eb-0dab-6ba6b1b2522a\n# \u255f\u2500d6fc78fa-ba2e-45bf-af00-45fee2fd017e\n# \u2560\u25500ef307d4-84d3-11eb-10e7-07cc58485fba\n# \u2560\u2550ba3d9b32-88dd-11eb-3b2a-0f96968e5bcb\n# \u255f\u250063946ad1-d28d-4759-8898-085f189e57db\n# \u2560\u2550a9bfa0e3-b128-43b1-af54-579d2bdcb3b7\n# \u255f\u25000ee44bd4-e41f-4977-b71c-9bc04bba0385\n# \u2560\u2550770ae76e-6521-4613-b781-3627847ffae9\n# \u255f\u250085bea7c1-71ba-4b6b-9341-affd291c0a7c\n# \u2560\u2550a2eaec0e-63a1-4771-899e-240289173b90\n# \u255f\u2500d054d2e6-da5d-4070-8b93-c81f07af756d\n# \u2560\u25500c6bdade-da51-4442-90d4-f3c36aa06e4c\n# \u255f\u2500ca2b7743-b2b3-4335-8c4c-2647492072ed\n# \u2560\u255021a24eb3-6104-4f6a-bae5-d11e504aad62\n# \u255f\u25005846d249-d73f-46d7-a1b9-09efc42ef331\n# \u255f\u25002994d86d-c2ba-417b-aa0e-b0c7d0956008\n# \u2560\u2550f98f70cf-aaf2-4710-9ef7-33c401b10c06\n# \u255f\u25002f1a3452-a122-41f2-8ab7-df4e1cc01b02\n# \u2560\u2550a7cdf304-48d2-4485-b473-dd2248bb7ce6\n# \u255f\u25005a2944be-209c-4fbe-b1b1-19a5f9df4316\n# \u255f\u2500ec3512fa-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": "# Test geometry.jl\n\nprintln(\"testing geometry\")\n\nusing Test\n\ntol = 1e-8\n\n# ray2raydist\np1 = [0,0,0]\np2 = [0,0,1]\nv1 = [1,0,0]\nv2 = [0,1,0]\nd = ray2raydist(p1,v1,p2,v2) # basic test\n@test abs(d-1) < tol\n\nd = ray2raydist(p1,v1,p2,v1) # Test parallel rays\n@test abs(d-1) < tol\n\nd = ray2raydist(p1,v1,p1,v2) # Test intersecting rays\n@test abs(d) < tol\nd = ray2raydist(p1,v1,p1,v1) # Test identical rays\n@test abs(d) < tol\n\n# circleintersectionpts\nc1 = [-1,0]\nr1 = 2\nc2 = [1,0]\nr2 = 2\n(i1, i2) = circleintersectionpts(c1, r1, c2, r2, \"lr\")\n@test abs(i1[1] < eps())\n@test abs(i1[2] - sqrt(3)) < eps()\n@test abs(i2[1] < eps())\n@test abs(i2[2] + sqrt(3)) < eps()\n\n# Check left and right solutions\nileft = circleintersectionpts(c1, r1, c2, r2, \"l\")\n@test all(abs.(ileft - i1) .< eps())\niright = circleintersectionpts(c1, r1, c2, r2, \"r\")\n@test all(abs.(iright - i2) .< eps())\n\n# no intersection\n(i1, i2) = circleintersectionpts(c1, r1, c2 .+ 10, r2, \"lr\")\n@test isempty(i1)\n@test isempty(i2)\n\n# circles just touching\nr1 = 1\nr2 = 1\nil = circleintersectionpts(c1, r1, c2, r2, \"l\")\n@test all(abs.(il) .< eps())\n\n# circle of zero radius\nc2 = [0,0]\nr2 = 0\nil = circleintersectionpts(c1, r1, c2, r2, \"l\")\n@test all(abs.(il) .< eps())\n\n\n\n# rectintersect\nr1 = [0, 0, 2, 4]\nr2 = [0, 0, 1, 1]\n@test rectintersect(r1, r2) # r2 inside r1\nr2 = [2, 4, 1, 1]\n@test rectintersect(r1, r2) # r2 touching r1\nr2 = [10, 20, 1, 1]\n@test !rectintersect(r1, r2) # r2 outside r1\n@test rectintersect(r1, r1)  # r2 same as r1\n\n# pointinconvexpoly\npoly = [0  1  2  2  0\n        0  0  0  1  1]\n\n@test pointinconvexpoly([2,1], poly) == 0      # on boundary\n@test pointinconvexpoly([0.5,0.5], poly) == 1  # inside\n@test pointinconvexpoly([10,10], poly) == -1   # outside\n\n# isconvexpoly\n@test isconvexpoly(poly)  # convex\npoly2 = [0    1  2  3  2  0\n         0  -10  0  0  1  1]\n@test !isconvexpoly(poly2)  # non-convex\n\n\n# convexpolyintersect\npoly1 = [0  2  3  0 \n         0  0  1  1]\n\npoly2 = [0  2  1\n         0  0  1]\n@test convexpolyintersect(poly1, poly2)         # intersect\n@test !convexpolyintersect(poly1, poly2 .+ 10)  # not intersect\n\npoly3 = [-2  0  -1\n          0  0   1]\n@test convexpolyintersect(poly2, poly3)      # touching\n@test convexpolyintersect(poly1, poly1)      # identical\n\n", "meta": {"hexsha": "d43123fe61fec2a8de05fdf7a1cb631fc1422ebf", "size": 2260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_geometry.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_stars_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_stars_repo_licenses": ["MIT"], "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_geometry.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_issues_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_issues_repo_licenses": ["MIT"], "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_geometry.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ImageProjectiveGeometry.jl-b9d14576-938f-5430-9d4c-b7d7de1409d6", "max_forks_repo_head_hexsha": "ec7f6103e003e648201d0fff38219e3d91e2c6f3", "max_forks_repo_licenses": ["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.6, "max_line_length": 63, "alphanum_fraction": 0.6110619469, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7712929484070429}}
{"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 \u2a7d 0, +\u221e 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 \u21a6 0 if all(0 \u2a7e x), +\u221e 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    (\u03b2,c,\u03c4) = p\r\n    N = S+I+R\r\n    infection = \u03b2*c*I/N*S\r\n    (Sd,Id,Rd) = h(p, t-\u03c4) # Time delayed variables\r\n    Nd = Sd+Id+Rd\r\n    recovery = \u03b2*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    (\u03b2,c,\u03c4) = p\r\n    N = S+I+R\r\n    infection = \u03b2*c*I/N*S\r\n    (Sd,Id,Rd) = h(p, t-\u03c4) # Time delayed variables\r\n    Nd = Sd+Id+Rd\r\n    recovery = \u03b2*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\u03b4t = 0.1\r\ntmax = 40.0\r\ntspan = (0.0,tmax)\r\nt = 0.0:\u03b4t: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]; # \u03b2,c,\u03c4\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": "\"\"\"\nAbstract type for the Baseline, each subtype should define the method\ngenBaseline(p::Baseline,,Nlon,Nlat,Ntime )\n\"\"\"\nabstract Baseline\nexport Baseline\n\n\"This function generates the Baseline 3D Array of size Nlon, Nlat, Ntime.\"\ngenBaseline(m::Baseline,Nlon,Nlat,Ntime)=error(\"Method genBaseline not implemented for $(typeof(m))\")\nexport genBaseline\n\n\"\"\"\nMost trivial baseline case, constant mean `m` without seasonal cycle\n\"\"\"\ntype ConstantBaseline <: Baseline\n    m::Float64\nend\nexport ConstantBaseline\ngenBaseline(c::ConstantBaseline,Ntime,Nlat,Nlon)=fill(c.m,Ntime,Nlat,Nlon)\n\n\"\"\"\nvery simple periodic BaseLine returning a sine oscillation in the time domain,\nwhere `nOsc` is the number of oscillations and `amp` is the amplitude\n\"\"\"\ntype SineBaseline <: Baseline\n\tnOsc::Float64 # Number of oscillations\n\tamp::Float64\nend\nexport SineBaseline\ngenBaseline(m::SineBaseline,Ntime,Nlat,Nlon)=[m.amp*sin(k*m.nOsc/Ntime*2*pi) for k=1:Ntime,j=1:Nlat,i=1:Nlon]\n\n\"\"\"\nA trend baseline where the mean is 0 and there is a trend in Lon, Lat and Time dimension. The range of the trend will be\n`[-tlon,tlon], [-tlat,tlat], [-ttime,ttime]`\n\"\"\"\ntype TrendBaseline <: Baseline\n\ttlon::Float64\n\ttlat::Float64\n\tttime::Float64\nend\nexport TrendBaseline\ngenBaseline(m::TrendBaseline,Ntime,Nlat,Nlon)=[(i-1)/(Nlon-1)*2*m.tlon-m.tlon + (j-1)/(Nlat-1)*2*m.tlat-m.tlat + (k-1)/(Ntime-1)*2*m.ttime-m.ttime for k=1:Ntime,j=1:Nlat,i=1:Nlon]\n", "meta": {"hexsha": "b6e9a51e441c66b45bde58dd11848ae15d2f78b6", "size": 1415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/baseline.jl", "max_stars_repo_name": "CAB-LAB/DataFarm", "max_stars_repo_head_hexsha": "6beaa30c8500a362be2e335a60342f5482a6a91d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-27T07:49:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T07:49:16.000Z", "max_issues_repo_path": "src/baseline.jl", "max_issues_repo_name": "esa-esdl/DataFarm", "max_issues_repo_head_hexsha": "6beaa30c8500a362be2e335a60342f5482a6a91d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/baseline.jl", "max_forks_repo_name": "esa-esdl/DataFarm", "max_forks_repo_head_hexsha": "6beaa30c8500a362be2e335a60342f5482a6a91d", "max_forks_repo_licenses": ["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.9069767442, "max_line_length": 179, "alphanum_fraction": 0.7455830389, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7712790539543746}}
{"text": "using TensorMatrices_lemon\nusing Base.Test\n\n# creating a tenmat\n#= \n\t\t\"\"\"    \n\t\t\tmatrix = rand(6,8)\n\t\t\trowindex = [3,1]\n\t\t\tcolindex = [2,4]\n\t\t\ttensorsize = (2,4,3,2)\n\t\t\ttenmat = Tenmat(matrix, rowindex, colindex, tensorsize)\n\t\t\"\"\"\n\t\t\"\"\" [test]\n\t\t\ttensorSize(tenmat)  == (2,4,3,2)\n\t\n\"\"\"\n\n# initialization \n\"\"\"\n\tA = rand(4,7,2,9,6)\n\trowindex = [5,2]\n\tcolindex = [3,4,1]\n\ttenmat = Tenmat(A,rowindex,colindex)\n\n\tA = rand(4,7,6);\n\ttenmat = Tenmat(A,[3,1],[2])\n\tsize(tenmat) == (24,7) || println(\"wrong\")\n\tsize(tenmat,2) == 7 || println(\"wrong\")\n\tgetindex(tenmat, 2, 6) == getindex(tenmat.matrix, 2, 6) || println(\"wrong\")\n\tsetindex!(tenmat, 100.0 , 2, 6)\n\tgetindex(tenmat, 2, 6) == 100.0 || println(\"wrong\")\n\tsimilar(tenmat, Int)\n\tsimilar(tenmat, Int, (5,2,7))\n\tsimilar(tenmat, Int, [1,3],[2])\n\tsimilar(tenmat, Int, [4,2,5], [1,3], (2,4,3,1,6))\n\tsimilar(tenmat)\n\tsimilar(tenmat, (5,2,7))\n\tsimilar(tenmat, [1,3],[2])\n\tsimilar(tenmat, [4,2,5], [1,3], (2,4,3,1,6))\n\t\n\t\n\"\"\"\n=#\n", "meta": {"hexsha": "2ae6cf3ad629782f9bf0b28c870c128cb691ba72", "size": 968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "yoyoyoju/TensorMatrices_lemon.jl", "max_stars_repo_head_hexsha": "6baf74cef22c07b34f3ea4f0cfdecdd35ecea194", "max_stars_repo_licenses": ["MIT"], "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": "yoyoyoju/TensorMatrices_lemon.jl", "max_issues_repo_head_hexsha": "6baf74cef22c07b34f3ea4f0cfdecdd35ecea194", "max_issues_repo_licenses": ["MIT"], "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": "yoyoyoju/TensorMatrices_lemon.jl", "max_forks_repo_head_hexsha": "6baf74cef22c07b34f3ea4f0cfdecdd35ecea194", "max_forks_repo_licenses": ["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": 76, "alphanum_fraction": 0.5826446281, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7712790483648332}}
{"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 \u21a6 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 `\u03c1`.\n\"\"\"\nneumann_entropy(\u03c1::AbstractMatrix) = -sum(xlogx.(real(eigvals(Matrix(\u03c1)))))\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(\u03b8list) = -sum(xlogx.(sum(\u03b8list .* eigvs)))\n\n\"\"\"\nCompute `-log(Z)`, with `Z` the partition function.\n\"\"\"\nthermal_logZ(\u03b2H::AbstractMatrix) = -log(tr(exp(-Matrix(\u03b2H))))\n\n\"\"\"\nUse representation of density matrix in terms of Pauli matrices; cos(\u03b8) is Bloch vector coefficient of Pauli-Z for each qubit\n\"\"\"\nlatent_density(\u03b8list) = DensityMatrix(kron([[1, 0, 0, cos(\u03b8)] for \u03b8 in \u03b8list]...), length(\u03b8list))\n\n\"\"\"\nTrace distance to target density matrix `\u03c3`.\n\"\"\"\ntrdistance(\u03b8list, \u03c3, cgc) = 0.5 * opnorm(real.(matrix(apply(latent_density(\u03b8list), cgc))) - \u03c3, 1)\n\n\n\"\"\"\nCalculate fidelity as defined in arxiv:1910.02071\n\"\"\"\nfunction fidelity(\u03b8list, \u03c3therm, cgc)\n    \u03c1sqrt = sqrt(real.(matrix(apply(latent_density(\u03b8list), cgc))))\n    return real(tr(sqrt(\u03c1sqrt * \u03c3therm * \u03c1sqrt))^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, \u0394) in zip(xs, grads), i in 1:length(x)\n        \u03b4 = sqrt(eps())\n        tmp = x[i]\n        x[i] = tmp - \u03b4/2\n        y1 = f(xs...)\n        x[i] = tmp + \u03b4/2\n        y2 = f(xs...)\n        x[i] = tmp\n        \u0394[i] = (y2-y1)/\u03b4\n        if eltype(x) <: Complex\n            # derivative with respect to imaginary part\n            x[i] = tmp - im*\u03b4/2\n            y1 = f(xs...)\n            x[i] = tmp + im*\u03b4/2\n            y2 = f(xs...)\n            x[i] = tmp\n            \u0394[i] += im*(y2-y1)/\u03b4\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 = \u0394x * \u27e8y\u27e9\n    # where \u0394x is the width of the base of trapezoid\n    # and \u27e8y\u27e9 is mean height\n    \n    \u0394x = abs(x2-x1) \n    mean_y = abs( get_line_point(x2,a,b) + get_line_point(x1,a,b)) / 2\n    return \u0394x * 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 - \u0394E. \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, \u0394E. \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\u03a3V'\n\n\"\"\"\nstruct LowRankMatrix{T} <: AbstractMatrix{T}\n    U::Matrix{T}\n    \u03a3::Matrix{T}\n    V::Matrix{T}\nend\n\nsize(L::LowRankMatrix) = size(L.U, 1), size(L.V, 1)\nrank(L::LowRankMatrix) = size(L.\u03a3,1)\nnorm(L::LowRankMatrix) = first(L.\u03a3)\ncond(L::LowRankMatrix) = ifelse(rank(L) < minimum(size(L)), Inf, first(L.\u03a3)/last(L.\u03a3))\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, \u03a3, V, r = L.U, L.\u03a3, L.V, rank(L)\n    # for k = r:-1:1\n    #     ret += U[i,k]*\u03a3[k,k]*V[j,k]\n    # end\n    U[i,:]'*\u03a3*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": "# basic one\nY = [\n     0  3;\n     1  0;\n     1 -3;\n    -2  3;\n     0  0;\n]\n\nD, X = ksvd(Y, 8, max_iter_mp = 600, sparsity_allowance = 1.0)\n@test norm(Y-D*X) < 1e-4\n\n# sparsity_allowance must be > 0\n@test_throws ArgumentError ksvd(Y, 20, sparsity_allowance = -0.1)\n@test_throws ArgumentError ksvd(Y, 20, sparsity_allowance = 1.1)\n\n# should work normally\nksvd(Y, 20, max_iter = 1)\nksvd(Y, 20, sparsity_allowance = 0.0)\nksvd(Y, 20, sparsity_allowance = 1.0)\n\n# But should work well when size(Y, 1) == n_atoms\nY = [\n    -1 1 2;\n     1 0 1\n]\nD, X = ksvd(Y, 2, max_iter_mp = 4000)\n@test norm(Y-D*X) < 0.001  # relax the constraint since the dictionary is small\n\n# Return only if X is sparse enough\nY = [\n\t0  2  3 -1  1;\n\t1 -3  1  3  0\n]\n\n# More than 20% of elements in X must be zeros\nsparsity_allowance = 0.2\nD, X = ksvd(Y, 5, max_iter = Int(1e10), sparsity_allowance = sparsity_allowance)\n@test sum(iszero, X) / length(X) > sparsity_allowance\n", "meta": {"hexsha": "df38195f7d6b4b6f19bbd6fa649ccf78a85e9a74", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 23.475, "max_line_length": 80, "alphanum_fraction": 0.6411075612, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7712376455247472}}
{"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 \u03c0.\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 < \u03c0\n        return sin(x)/2\n    else\n        return 0\n    end\nend\nfunction Distributions.logpdf(d::Sine, x::Real)\n    if 0 < x < \u03c0\n        return log(sin(x)/2)\n    else\n        return -Inf\n    end\nend\nDistributions.minimum(d::Sine) = 0\nDistributions.maximum(d::Sine) = \u03c0\nDistributions.insupport(d::Sine, x::Real) = 0 < x < \u03c0\nDistributions.mean(d::Sine) = \u03c0/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 InstantiateFromURL\n# optionally add arguments to force installation: instantiate = true, precompile = true\ngithub_project(\"QuantEcon/quantecon-notebooks-julia\", version = \"0.8.0\")\n\n# Exercise 1\n\n# Part 1: compute inner product using zip()\n\nA = [1 2 3]\nB = [4 5 6]\n@show sum(a * b for (a,b) \u2208 zip(A,B))\n\n# part 2: count even numbers between 0,99 using comprehension\n@show even = sum(iseven, 1:99)\n\n# part 3: count number of pairs where both elements are even using comprehension\nA = [2 4 9 12]\nB = [5 2 8 10]\n@show sum( iseven(a)&&iseven(b) for (a,b) \u2208 zip(A,B))\n\n# or\npairs = ((2, 5), (4, 2), (9, 8), (12, 10))\n@show sum(xy -> all(iseven, xy), pairs);\n\n\n\n# Exercise 2\n\nfunction p(x,coef)\n    values = zeros(0)\n    for (i, \u03b1) in enumerate(coef)\n        val = \u03b1 * x^(i-1)\n        push!(values,val)\n    end\n    return sum(values)\nend\n\ncoef = [12 0.5 3]\nx = 2\n\n@show sol = p(x,coef)\n\n# or\n\np(x,coef) = sum( \u03b1 * x^(i-1) for (i,\u03b1) in enumerate(coef))\n\n@show sol2 = p(x,coef);\n\n\n# Exercise 3\n\nuppercase(\"foo\")\n\nfunction countuppercase(string)\n    count = 0\n    for letter in string\n        if letter == uppercase(letter) && isletter(letter)\n            count += 1\n        end\n    end\n    return count\nend\n\n@show sol = countuppercase(\"Romulus and Remus founded Rome\")\n\n\n# or\n\ncountuppercase(string) = sum( letter == uppercase(letter) && isletter(letter) for letter in string)\n\n@show sol2 = countuppercase(\"Romulus and Remus founded Rome\");\n\n\n# Exercise 4\n\nsameset(seq_a,seq_b) = all( a \u2208 seq_b for a in seq_a )\n\nA = [\"apple\" , 4, 2]\nB = [2, \"apple\", 4]\n\nsameset(A,B)\n\n\n# Exercise 5 piecewise linear interpolation\n\nfunction linapprox(f,a,b,n,x)\n\n    interval_length = b-a # total length of interval\n\n    no_subintervals = n-1 # number of subintervals = gridpoints - 1\n\n    subinterval_length = interval_length/no_subintervals\n\n    step = subinterval_length\n\n    # find grid point larger than x\n    point = a\n    while point < x\n        point+= step\n    end\n\n    # x must lie between the gridpoints (point - step) and point\n    u, v = point - step, point\n\n    # computer interpolation polynomial\n    return f(u) + (x-u) * (f(v)-f(u)) / (v-u)\nend\n\nf(x) = exp(x) + x^2\nf_approx(x) = linapprox(f, -1, 1, 3, x)\n\nusing Plots\n\nx_grid = range(-5.0, 5.0, length = 400)\ny_vals = f.(x_grid)\ny = f_approx.(x_grid)\nplot(x_grid, y_vals, label = \"true\")\nplot!(x_grid, y, label = \"approximation\")\n\n# Exercise 6\n\nopen(\"us_cities.txt\", \"w\") do f\n  write(f,\n\"new york: 8244910\nlos angeles: 3819702\nchicago: 2707120\nhouston: 2145146\nphiladelphia: 1536471\nphoenix: 1469471\nsan antonio: 1359758\nsan diego: 1326179\ndallas: 1223229\")\nend\n\npop = open(\"us_cities.txt\", \"r\")\n\ntotal_pop =0\nfor line in eachline(pop)\n    city, population = split(line, \":\")\n    total_pop += parse(Int, population)\nend\n\nclose(pop)\nprintln(\"total population = $total_pop\")\n", "meta": {"hexsha": "2f3b7cdc52f7b686cbe71c74ac3d832ef9baf785", "size": 2822, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GettingStarted_JuliaEssentials.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": "GettingStarted_JuliaEssentials.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": "GettingStarted_JuliaEssentials.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": 19.4620689655, "max_line_length": 99, "alphanum_fraction": 0.6470588235, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8991213684847575, "lm_q1q2_score": 0.7712376324012792}}
{"text": "\"\"\"\n    partition(array::Array{Int64,1}, low::Int64, high::Int64)\n\nThe partion algorithm is shuffeling the array for a given interval of low and high\nboundaries.\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array of integers\n- `low::Int64`: Lowest index of the unsorted array or subarray\n- `high::Int64`: Highes index of the unsorted array or subarray\n\n\"\"\"\nfunction partition(array::Array{Int64,1}, low::Int64, high::Int64)\n    # index of smaller element\n    i = low - 1\n    # pivot\n    pivot = array[high]\n\n    for j in low:high\n\n        # If current element is smaller than the pivot\n        if array[j] < pivot\n\n            # increment index of smaller element\n            i = i + 1\n            # Swap if the element found is greater than the next element\n            array[i], array[j] = array[j], array[i]\n        end\n    end\n    array[i+1], array[high] = array[high], array[i+1]\n    return (i + 1)\nend\n\n\"\"\"\n    quick_sorting(array::Array{Int64,1}, low = nothing, high = nothing)\n\nThe quick sort algorithm (QSA) works by selecting a pivot element from the array and\npartitioning the other elements into two subarrays, according to whether they are less than\nor greater than the pivot-window. Then the sorting of subarrays is recursively organized.\nThis procedure repeatedly happens until each subarray is organized; consequently, the\nsubarrays' merging is an organized array. For more information see:\n[https://en.wikipedia.org/wiki/Quicksort#Parallelization](https://en.wikipedia.org/wiki/Quicksort#Parallelization)\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array of integers\n- `low::Int64`: Lowest index of the unsorted array or subarray\n- `high::Int64`: Highes index of the unsorted array or subarray\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr = [64, 34, 25, 12, 22, 11, 90]\njulia> ClassicAlgorithmsCollections.quick_sorting(arr)\n[11, 12, 22, 25, 34, 64, 90]\n```\n\"\"\"\nfunction quick_sorting(array::Array{Int64,1}, low = nothing, high = nothing)\n    # If nothing, then the intial run, so low and high are set to array size\n    if isnothing(low) && isnothing(high)\n        low = 1\n        high = length(array)\n    end\n    if low < high\n\n        # p_i is partitioning index, array[p_i] is now at right place\n        p_i = partition(array, low, high)\n\n        # Separately sort elements before partition and after partition\n        array = quick_sorting(array, low, p_i - 1)\n        array = quick_sorting(array, p_i + 1, high)\n    else\n        return array\n    end\nend\n", "meta": {"hexsha": "507b67b74d616e6c66c81505f7e600f1a01f51e0", "size": 2523, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SortingAndSearching/QuickSorting.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/QuickSorting.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/QuickSorting.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": 32.3461538462, "max_line_length": 114, "alphanum_fraction": 0.6845025763, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.7712376322392932}}
{"text": "include(\"../src/eis_series.jl\")\n\nfunction test_eis_series_length()\n\tprint(\"eis_series.length...\")\n  \n  @test length(eisenstein_series_poly(4, 5)) == 5\n  @test length(eisenstein_series_poly(6, 500)) == 500\n  @test length(eisenstein_series_poly(12, 1)) == 1\n\tprintln(\"PASS\")\nend\n\nfunction test_eis_series_normalisation()\n\tprint(\"eis_series.normalisation...\")\n  \n  e4 = eisenstein_series_qexp(4, 5, QQ, \"q\", \"linear\")\n  @test coeff(e4, 1) == 1\n  @test coeff(e4, 0) == 1//240\n  e6 = eisenstein_series_qexp(6, 5, QQ, \"q\", \"constant\")\n  @test coeff(e6, 0) == 1\n  @test coeff(e6, 1) == -504\n  e12 = eisenstein_series_qexp(12, 5, ZZ, \"q\", \"integral\")\n  @test coeff(e12, 0) == 691\n  @test coeff(e12, 1) == 65520\n\tprintln(\"PASS\")\nend\n\nfunction test_eis_series_coefficients()\n\tprint(\"eis_series.coefficients...\")\n  \n  e4 = eisenstein_series_qexp(4, 11, QQ, \"q\", \"constant\")\n  S = parent(e4)\n  q = gen(S)\n  @test e4 - (1+240*q+2160*q^2+6720*q^3+17520*q^4+30240*q^5+60480*q^6+82560*q^7+140400*q^8+181680*q^9+272160*q^10+O(q^11)) == 0\n  e6 = eisenstein_series_qexp(6, 11, ZZ, \"q\", \"integral\")\n  S = parent(e6)\n  q = gen(S)\n  @test e6 - (1-504*q-16632*q^2-122976*q^3-532728*q^4-1575504*q^5-4058208*q^6-8471232*q^7-17047800*q^8-29883672*q^9-51991632*q^10+O(q^11)) == 0\n  e12 = eisenstein_series_qexp(12, 11, QQ, \"q\", \"linear\")\n  S = parent(e12)\n  q = gen(S)\n  @test e12 - (691//65520+q+2049*q^2+177148*q^3+4196353*q^4+48828126*q^5+362976252*q^6+1977326744*q^7+8594130945*q^8+31381236757*q^9+100048830174*q^10+O(q^11)) == 0\n\tprintln(\"PASS\")\nend\n\nfunction test_eis_series()\n\ttest_eis_series_length()\n  test_eis_series_normalisation()\n  test_eis_series_coefficients()\n\n\tprintln(\"\")\nend\n", "meta": {"hexsha": "66223e69158a39686c95688546af486e4afaaea2", "size": 1667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/eisenstein-test.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": "test/eisenstein-test.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": "test/eisenstein-test.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": 32.0576923077, "max_line_length": 164, "alphanum_fraction": 0.6712657469, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7712045814684882}}
{"text": "using Test\n\ninput = joinpath(@__DIR__, \"input\")\npasses = readlines(input)\n\n# our boarding pass is a thinly disguised 10 bit integer\nconst factors = [512, 256, 128, 64, 32, 16, 8, 4, 2, 1]\nconst translator = Dict('F' => 0, 'L' => 0, 'B' => 1, 'R' => 1) \n\nfunction seat(pass)\n    bin = map(c -> translator[c], collect(pass))\n    return sum(bin .* factors)\nend\n\nfunction findseat(seatids)\n    allpossible = collect(minimum(seatids):maximum(seatids))\n    return only(filter(i -> !(i in seatids), allpossible))\nend\n\nseatids = map(p -> seat(p), passes)\n\np1 = maximum(seatids)\np2 = findseat(seatids)\n\n@assert(p1 == 994)\n@assert(p2 == 741)\n\n@test seat(\"BFFFBBFRRR\") == 567\n@test seat(\"FFFBBBFRRR\") == 119\n@test seat(\"BBFFBBFRLL\") == 820\n\nprintln(\"-----------------------------------------------------------------------\")\nprintln(\"binary boarding -- part one :: $p1\")\nprintln(\"binary boarding -- part two :: $p2\")\nprintln(\"-----------------------------------------------------------------------\")\n", "meta": {"hexsha": "256cfd5ea85072a349ee01b0a089d79a45242f7b", "size": 988, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bin/five/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/five/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/five/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": 27.4444444444, "max_line_length": 82, "alphanum_fraction": 0.5546558704, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8418256492357359, "lm_q1q2_score": 0.7712045779434539}}
{"text": "using DelimitedFiles\n\n\nadditiveFactorial(n::Int) :: Int = sum(1:n)\n\ndistance(pos1::Int, pos2::Int) :: Int = abs(pos1-pos2)\n\n# Cost of a distance for problem 1\ncost(t::Int,positions::Vector{Int}) :: Int = sum(map(p -> distance(t,p), positions))\n\n# Cost of a distance for problem 2\nfunction cost2(t::Int,positions::Vector{Int}) :: Int \n  distances = map(p -> distance(t,p), positions)\n  return sum( map( d -> additiveFactorial(d) , distances))\nend\n\n# Calculates least-cost alignment for problem 1.\nfunction minimalAlignment(positions::Vector{Int}) :: Tuple{Int,Int}\n  targets = Vector(0:maximum(positions))\n  costs = map(t -> cost(t,positions), targets)\n  i_best = argmin(costs)\n  return (i_best, costs[i_best])\nend\n\n# Calculates least-cost alignment for problem 2\nfunction minimalAlignment2(positions::Vector{Int}) :: Tuple{Int,Int}\n  targets = Vector(0:maximum(positions))\n  costs = map(t -> cost2(t,positions), targets)\n  i_best = argmin(costs)\n  return (i_best, costs[i_best])\nend\n\n# Read input\nfunction readInput() :: Vector{Int}\n  data = readdlm(\"./inputs/day7.txt\", ',', Int)\n  return reshape(data,length(data))\nend\n\nprintln(\"Problem 1: \")\npositions = readInput()\nres = minimalAlignment(positions)\ndisplay(res)\n\n\nprintln(\"Problem 2: \")\npositions = readInput()\nres = minimalAlignment2(positions)\ndisplay(res)", "meta": {"hexsha": "060141572d4accfa1bd31ad24f09047943883c1a", "size": 1312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day07.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/day07.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/day07.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": 27.3333333333, "max_line_length": 84, "alphanum_fraction": 0.7096036585, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7712045722695183}}
{"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    \u03ba(x,y) = (a\u22c5x\u1d40y + c)\u1d48   \u03b1 > 0, c \u2267 0, d \u2208 \u2124\u207a\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 \u2267 0\")\n        @check_args(PolynomialKernel, d, d >= one(d) && d == trunc(d), \"d \u2208 \u2124\u208a\")\n        return new{T}(a, c, d)\n    end\nend\n\nfunction PolynomialKernel(\n        a::T\u2081=1.0,\n        c::T\u2082=T\u2081(1),\n        d::T\u2083=convert(promote_float(T\u2081,T\u2082), 3)\n    ) where {T\u2081<:Real,T\u2082<:Real,T\u2083<:Real}\n    T = promote_float(T\u2081,T\u2082,T\u2083)\n    return PolynomialKernel{T}(a, c, d)\nend\n\n@inline basefunction(::PolynomialKernel) = ScalarProduct()\n\n@inline function kappa(\u03ba::PolynomialKernel{T}, x\u1d40y::T) where {T}\n    return (\u03ba.a*x\u1d40y + \u03ba.c)^(\u03ba.d)\nend\n\nfunction convert(::Type{K}, \u03ba::PolynomialKernel) where {K>:PolynomialKernel{T}} where T\n    return PolynomialKernel{T}(\u03ba.a, \u03ba.c, \u03ba.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    \u03b8::Float64\nend\n\nGeneralizedMinmodLimiter(;\u03b8=1.0) = GeneralizedMinmodLimiter(\u03b8)\n(limiter::GeneralizedMinmodLimiter)(a,b) =minmod(limiter.\u03b8*a,0.5*(a+b),limiter.\u03b8*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    \u03b2::Float64\nend\nOsherLimiter(;\u03b2=1.0) = OsherLimiter(\u03b2)\n(limiter::OsherLimiter)(a,b) = max(zero(a),min(a,limiter.\u03b2*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, \u03b8, 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  `\u03b8` 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  \u2207u = similar(u)\n  Threads.@threads for j in cell_indices(mesh)\n      inner_slopes_loop!(\u2207u,j,u,mesh,slopeLimiter,nonscalar)\n  end\n  \u2207u\nend\n\nfunction compute_slopes(u::AbstractArray, mesh::AbstractFVMesh, slopeLimiter::AbstractSlopeLimiter, nonscalar::Bool, ::Type{Val{false}})\n  \u2207u = similar(u)\n  for j in cell_indices(mesh)\n      inner_slopes_loop!(\u2207u,j,u,mesh,slopeLimiter,nonscalar)\n  end\n  \u2207u\nend\n\nfunction inner_slopes_loop!(\u2207u,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      \u2207u[i,j] = slopeLimiter(u[i,j]-ul[i], ur[i]-u[i,j])\n    end\n  else\n    \u2207u[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[-\u03c0:\u03c0], or [-180\u00b0:180\u00b0].\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\ncdist(a, b) = mod(b - a + pi, 2\u03c0) - 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) -> \u03c3\n\nReturn the standard deviation, `\u03c3`, 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) -> \u03c3\u00b2\n\nReturn the circular variance, `\u03c3\u00b2`, 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, \u00b5, \u03ba, degrees=false) -> p\n\nReturn the Von Mises probability density function at `a`, for a von Mises\ndistribution with circular mean `\u00b5` and concentration `\u03ba`.\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, \u03bc, \u03ba, degrees=false) -> cdf\n\nReturn the von Mises cumulative distribution function at\n`a` for a distribution with mean `\u03bc` and concentration `\u03ba`.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\nfunction von_mises_cdf(a, \u03bc, \u03ba, degrees=false)\n    degrees && (\u03bc = deg2rad(\u03bc))\n    d = Distributions.VonMises(\u03bc, \u03ba)\n    Distributions.cdf(d, degrees ? deg2rad(a) : a)\nend\n\n\"\"\"\n    fit_vonMises(\u03b8, degrees=false; axial=false) -> \u03bc, \u03ba\n\nReturn the maximum-likelihood values of the mean `\u03bc` and concentration\n`\u03ba` for the von Mises distribution which fits the set of angles `\u03b8`.\n\nIf `axial` is `true`, then the data are assumed to have a \u03c0 (or 180\u00b0)\nambiguity.\n\nAngles are in radians, unless `degrees` == true.\n\"\"\"\nfunction fit_vonMises(\u03b8, degrees=false; axial=false)\n    degrees && (\u03b8 = deg2rad.(\u03b8))\n    axial && (\u03b8 = 2\u03b8)\n    \u03bc = cmean(\u03b8)\n    \u03ba = estimate_kappa_vonMises(\u03b8, \u03bc)\n    degrees ? (rad2deg(\u03bc), \u03ba) : (\u03bc, \u03ba)\nend\n\n\"\"\"\n    estimate_kappa_vonMises(\u03b8, \u03bc) -> \u03ba\n\nReturn the maximum likelihood estimation of the concentration\nparameter `\u03ba` for the best-fitting von Mises distribution, given\na set of angles `\u03b8` in radians.\n\nUses the polynomial approximation given by Best and Fisher (1981).\n**N.B.** This may not be reliable when R\u0304 is small (e.g., < 0.7).\n\"\"\"\nfunction estimate_kappa_vonMises(\u03b8, \u03bc)\n    R\u0304 = mean(cos.(\u03b8 .- \u03bc))\n    if 0 <= R\u0304 < 0.53\n        2R\u0304 + R\u0304^3 + 5R\u0304^5/6\n    elseif 0.53 <= R\u0304 < 0.85\n        -0.4 + 1.39R\u0304 + 0.43/(1 - R\u0304)\n    elseif R\u0304 >= 0.85\n        1/(R\u0304^3 - 4R\u0304^2 + 3R\u0304)\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": "using CmdStan, DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions,\n      RecursiveArrayTools, Distributions, Test\n\nprintln(\"One parameter case\")\nf1 = @ode_def 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,p)\nsol = solve(prob1,Tsit5())\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)\npriors = [Truncated(Normal(1.5,0.1),0,2)]\n\nbayesian_result = stan_inference(prob1,t,data,priors;num_samples=300,\n                                 num_warmup=500,likelihood=Normal)\n\n@test mean(get(bayesian_result.chains,:theta1).theta1') \u2248 1.5 atol=3e-1\n\n\nprintln(\"Four parameter case\")\nf1 = @ode_def begin\n  dx = a*x - b*x*y\n  dy = -c*y + d*x*y\nend a b c d\nu0 = [1.0,1.0]\ntspan = (0.0,10.0)\np = [1.5,1.0,3.0,1.0]\nprob1 = ODEProblem(f1,u0,tspan,p)\nsol = solve(prob1,Tsit5())\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)\npriors = [Truncated(Normal(1.5,0.01),0,2),Truncated(Normal(1.0,0.01),0,1.5),\n          Truncated(Normal(3.0,0.01),0,4),Truncated(Normal(1.0,0.01),0,2)]\n\nbayesian_result = stan_inference(prob1,t,data,priors;num_samples=100,num_warmup=500,vars =(DiffEqBayes.StanODEData(),InverseGamma(4,1)))\n@test mean(get(bayesian_result.chains,:theta1).theta1') \u2248 1.5 atol=1e-1\n@test mean(get(bayesian_result.chains,:theta2).theta2') \u2248 1.0 atol=1e-1\n@test mean(get(bayesian_result.chains,:theta3).theta3') \u2248 3.0 atol=1e-1\n@test mean(get(bayesian_result.chains,:theta4).theta4') \u2248 1.0 atol=1e-1\n", "meta": {"hexsha": "9c2f2237a8bfd253eb74f2942a89f5177c77148d", "size": 1663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/stan.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DiffEqBayes.jl-ebbdde9d-f333-5424-9be2-dbf1e9acfb5e", "max_stars_repo_head_hexsha": "6af350eda391508becd2a59bc01474f59af81259", "max_stars_repo_licenses": ["MIT"], "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/stan.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DiffEqBayes.jl-ebbdde9d-f333-5424-9be2-dbf1e9acfb5e", "max_issues_repo_head_hexsha": "6af350eda391508becd2a59bc01474f59af81259", "max_issues_repo_licenses": ["MIT"], "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/stan.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DiffEqBayes.jl-ebbdde9d-f333-5424-9be2-dbf1e9acfb5e", "max_forks_repo_head_hexsha": "6af350eda391508becd2a59bc01474f59af81259", "max_forks_repo_licenses": ["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.152173913, "max_line_length": 136, "alphanum_fraction": 0.6806975346, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7711840184372464}}
{"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\u0398 = [ \u03c0/3; 5*\u03c0/6 ]\n\n# Spatial frequencies\n\u039e = [0.2; 0.3; 0.4; 0.5]\n# Convert them to wavelengths\n\u039b = 1.0 ./ \u039e\n\n# Gaussian bandwidth for Gabor filters\nbw = 1.0\n\u03c3 = 1.0/\u03c0 * sqrt(log(2)/2) * (2^bw+1)/(2^bw-1)\n\n# Spatial aspect ratio: \u03c3x = \u03c3; \u03c3y = \u03c3/\u03b3\n\u03b3 = 1.0\n\n# Step 2: Apply Gabor filters; the same size as the input image.\nm, n = size(textures)\n\nK = length(\u0398) *length(\u039b) # 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 \u03b8 in \u0398\n    for \u03bb in \u039b\n        kernel = Kernel.gabor(m, n, \u03bb*\u03c3, \u03b8, \u03bb, \u03b3, 0.0)\n        kernel[1] ./= 2*\u03c0*\u03c3*\u03c3/\u03b3\n        kernel[2] ./= 2*\u03c0*\u03c3*\u03c3/\u03b3\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*\u03bb))\n        global k += 1\n    end\nend \n\n# Display those Gabor features\nplot(K, layout=(length(\u0398),length(\u039b)), 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(\u0398),length(\u039b)), 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(\u0398),length(\u039b)), 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\u03c3 = 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, \u03c3)    \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    \u03bc::Float64 \n    \u03c3::Float64\n    r::Float64\n    \u03c1::Float64  \n    \u03b3::Float64 \n    \u03c8::Float64\n    wmax::Float64\nend\n\nfunction WangWangYangModel(;\u03bc = 0.01, \u03c3 = 0.1, r = 0.05, \u03c1 = 0.06, \u03b3 = 2, \u03c8 = 0.5, wmax = 5000.0)\n    WangWangYangModel(\u03bc, \u03c3, r, \u03c1, \u03b3, \u03c8, 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    \u03bc = m.\u03bc ;  \u03c3 = m.\u03c3 ;  r = m.r ;  \u03c1 = m.\u03c1 ;  \u03b3 = m.\u03b3 ;  \u03c8 = m.\u03c8 ; wmax = m.wmax\n    w = state.w\n    p, pw, pww = y.p, y.pw, y.pww\n    c = (r + \u03c8 * (\u03c1 - r)) * p * pw^(-\u03c8)\n    \u03bcw = (r - \u03bc + \u03c3^2) * w + 1 - c\n    # One only needs a ghost node if \u03bcw <= 0 (since w^2p_ww = 0). In this case, we obtain a formula for pw so that c <= 1\n    if w \u2248 0.0 && \u03bcw <= 0.0\n       pw = ((r + \u03c8 * (\u03c1 - r)) * p)^(1 / \u03c8)\n       c = 1.0\n       \u03bcw = 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 + \u03c8 * (\u03c1 - r)) * pw^(1 - \u03c8) - \u03c8 * \u03c1) / (\u03c8 - 1) + \u03bc - \u03b3 * \u03c3^2 / 2) * p + ((r - \u03bc + \u03b3 * \u03c3^2) * w + 1) * pw + \u03c3^2 * w^2 / 2  * (pww - \u03b3 * pw^2 / p)\n    \u03bcw = (r - \u03bc + \u03c3^2) * w + 1 - c\n    return (pt,), (\u03bcw,), (w = w, p = p, pw = pw, pww = pww, \u03bcw = \u03bcw, 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": "\"\"\"\n    assigndist_binomial(n, p; trunc_lower = -Inf, trunc_upper = Inf)\n\nAssign parameters to a binomial distribution with `n` trials and probability `p`\nof success in individual trials, optionally truncating the distribution.\n\"\"\"\nfunction assigndist_binomial(n, p; trunc_lower = -Inf, trunc_upper = Inf)\n    truncated(Binomial(n, p), trunc_lower, trunc_upper)\nend\n\nexport assigndist_binomial\n", "meta": {"hexsha": "16bdb8a330d4d0ca1aee0f1545a4c8b9263fcc33", "size": 394, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/uncertain_values/distributions/assigndist_binomial.jl", "max_stars_repo_name": "JeffreySarnoff/UncertainData.jl", "max_stars_repo_head_hexsha": "939759ad0d2e3b42c203e0ee844409e70afafd4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-01-04T10:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T01:11:13.000Z", "max_issues_repo_path": "src/uncertain_values/distributions/assigndist_binomial.jl", "max_issues_repo_name": "JeffreySarnoff/UncertainData.jl", "max_issues_repo_head_hexsha": "939759ad0d2e3b42c203e0ee844409e70afafd4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 78, "max_issues_repo_issues_event_min_datetime": "2018-12-17T20:12:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T20:46:04.000Z", "max_forks_repo_path": "src/uncertain_values/distributions/assigndist_binomial.jl", "max_forks_repo_name": "JeffreySarnoff/UncertainData.jl", "max_forks_repo_head_hexsha": "939759ad0d2e3b42c203e0ee844409e70afafd4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-01-22T23:05:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T12:21:02.000Z", "avg_line_length": 32.8333333333, "max_line_length": 80, "alphanum_fraction": 0.7664974619, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7711575858647961}}
{"text": "function numdivisors(n)\n\td = 0\n\tlimit = n;\n    \n    i = 1\n\twhile i < limit\n\t\tif n % i == 0\n\t\t\tlimit = div(n,i) # converge to sqrt(n)\n\t\t\tif limit != i\n\t\t\t\td += 1\n\t\t\tend\n\t\t\td += 1\n\t\tend\n\t\ti += 1\n\tend\n\treturn d\nend\n\nfunction main()\n\tN = 5\n\n\tn = 0\n\ti = 0\n\twhile true\n\t\ti += 1\n\t\tn += i\n\t\td = numdivisors(n)\n\t\tprintln(\"$d $n\")\n\t\tif d > N\n\t\t\tprintln(n)\n\t\t\treturn\n\t\tend\n\tend\nend\n\nmain()\n", "meta": {"hexsha": "17a4e51669129e5b0638b7f8b22fa46c30795915", "size": 379, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem12.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": "problem12.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": "problem12.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": 10.2432432432, "max_line_length": 41, "alphanum_fraction": 0.4960422164, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.771157585333548}}
{"text": "using FractionalTimeDG\nusing PyPlot\n\n\u03b1 = 3/4\nN = 1000\nr = 4\nM = 2r\nversion = 1\n\nstore = Store(\u03b1, r, M)\nH = coef_H_uniform!(r, N, M, store, version)\n\n\u2113 = collect(1:N-1)\n\nfunction max_antidiags(H)\n    r = size(H[0], 1)\n    N = length(H)\n    \u03b3 = zeros(N-1, 2r-1)\n    for m = 2:2r\n        for \u2113bar = 1:N-1\n            if m \u2264 r\n                antidiag = [ H[\u2113bar][i,m-i] for i = 1:m-1 ]\n            else\n                antidiag = [ H[\u2113bar][i,m-i] for i = m-r:r ]\n            end\n#            println(antidiag)\n            largest = maximum(abs.(antidiag))\n            if largest \u2265 eps(Float64)\n                \u03b3[\u2113bar, m-1] = largest\n            else\n                \u03b3[\u2113bar, m-1] = NaN\n            end\n        end\n    end\n    return \u03b3\nend\n\n\u03b3 = max_antidiags(H)\n\nfigure(2)\nfmt = [\":\", \"--\", \"-.\", \"-\", \":\", \"--\", \"-.\"]\nfor m = 2:2r\n    loglog(\u2113, \u03b3[:,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 + \u221aT(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, \u03f5, n)\n    c1 = (c2 & 1) + 1  # c1 is the other column (row, actually)\n    for i=1:n\n        \u03f5[c1,i] = \u03f5[c1,i+1] + 1 / (\u03f5[c2,i+1] - \u03f5[c2,i])\n    end\n    return c1\nend\n\n\nfunction accel_wynn_eps!(\u03f5)\n    N = size(\u03f5, 2)\n    c = 2\n    for j=1:N-1\n        c = next_j!(c, \u03f5, N - j)\n    end\n    return \u03f5[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    \u0394N = 1 - (length(ak) & 1)  # 1 for even length, 0 for odd\n    N = length(ak) - \u0394N\n    \u03f5 = Array{eltype(ak)}(undef, 2, N)\n    for n=1:N\n        \u03f5[1,n] = zero(eltype(ak))\n        \u03f5[2,n] = sum(ak[1:n+\u0394N])\n    end\n    return accel_wynn_eps!(\u03f5)\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": "using Symbolics, Test, DiffRules, SpecialFunctions\n\n@sym x y z m \u03bd\n\n@testset \"             Derivatives\" begin\n    f(x) = x^3\n    g(x) = x^2\n    @test D(f+g)(x) |> simplify == 3 * x ^ 2 + 2x\n    @test (D^2)(f+g)(x) == 3 * (2x) + 2\n    @test (D^3)(f+g)(x) == 6\n    @test D(x^2 + y^2 + z^2, x) == 2x\n    @test D(D(2x*y, x), y) == 2\n    # test diff rules\n    @test D(x -> atan(x,y))(x) ==  y/(x^2 + y^2)\n    @test D(y -> atan(x,y))(y) == -x/(x^2 + y^2)\n    @test D(x -> hypot(x,y))(x) == x/hypot(x,y)\n    @test D(y -> hypot(x,y))(y) == y/hypot(x,y)\n\n    @test D(x -> besselj(\u03bd,x))(x) == (besselj(\u03bd - 1, x) - besselj(\u03bd + 1, x))/2\n    @test D(x -> besseli(\u03bd,x))(x) == (besseli(\u03bd - 1, x) + besseli(\u03bd + 1, x))/2\n    @test D(x -> bessely(\u03bd,x))(x) == (bessely(\u03bd - 1, x) - bessely(\u03bd + 1, x))/2\n    @test D(x -> besselk(\u03bd,x))(x) == (besselk(\u03bd - 1, x) + besselk(\u03bd + 1, x))/2\n\n    @test D(x -> hankelh1(\u03bd,x))(x) == (hankelh1(\u03bd - 1, x) - hankelh1(\u03bd + 1, x))/2\n    @test D(x -> hankelh2(\u03bd,x))(x) == (hankelh2(\u03bd - 1, x) - hankelh2(\u03bd + 1, x))/2\n\n    @test D(x -> polygamma(m,x))(x) == polygamma(m + 1, x)\n\n    @test D(x -> beta(x,y))(x) == beta(x,y)*(digamma(x)-digamma(x+y))\n    @test D(y -> beta(x,y))(y) == beta(x,y)*(digamma(y)-digamma(x+y))\n\n    @test D(x -> lbeta(x,y))(x) == digamma(x)-digamma(x+y)\n    @test D(y -> lbeta(x,y))(y) == digamma(y)-digamma(x+y)\n\n    for (M, f, arity) in DiffRules.diffrules()\n        if arity == 1 && (M == :Base || M == :SpecialFunctions) && f \u2209 [:inv, :+, :-, :abs, ] # [:bessely0, :besselj0, :bessely1, :besselj1]\n            deriv = DiffRules.diffrule(M, f, :x)\n            @eval begin\n                @test D($M.$f)(x) == $deriv\n            end\n        end\n    end\nend\n", "meta": {"hexsha": "09e6654e773eead0db6e447ba2c27ef883e84988", "size": 1693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/derivatives.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/derivatives.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/derivatives.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": 38.4772727273, "max_line_length": 140, "alphanum_fraction": 0.4695806261, "num_tokens": 762, "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    \u03d1\u2081(t, q) = + log(q[2]) / q[1]\n    \u03d1\u2082(t, q) = zero(eltype(q))\n\n    d\u03d1\u2081dx\u2081(t, q) = - log(q[2]) / q[1]^2\n    d\u03d1\u2081dx\u2082(t, q) = + 1 / (q[1] * q[2])\n\n    d\u03d1\u2082dx\u2081(t, q) = zero(eltype(q))\n    d\u03d1\u2082dx\u2082(t, q) = zero(eltype(q))\n\n\n    # \u03d1\u2081(t, q) = zero(eltype(q))\n    # \u03d1\u2082(t, q) = - log(q[1]) / q[2]\n\n    # d\u03d1\u2081dx\u2081(t, q) = zero(eltype(q))\n    # d\u03d1\u2081dx\u2082(t, q) = zero(eltype(q))\n\n    # d\u03d1\u2082dx\u2081(t, q) = - 1 / (q[2] * q[1])\n    # d\u03d1\u2082dx\u2082(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(\u03b8::Int64, samples::Int64, dim::Int64)\n\tres = zeros(dim, samples)\n\tU_dist = Uniform(0,1)\n\t\u03b3_dist = Gamma(1/\u03b8,1)\n\tfor i = 1:samples\n\t\tV = rand(U_dist, dim)\n\t\t\u03b3 = rand(\u03b3_dist, 1)\n\t\t\u03a8(t) = (t+1)^(-1/\u03b8)\n\t\tU_\u03b3 = \u03a8.(-log.(V)./\u03b3)\n        for j = 1:dim\n            res[j,i] = U_\u03b3[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 Images, TestImages, Colors, ZernikePolynomials, FFTW\nusing NumberTheoreticTransforms\n\nimage_float = channelview(testimage(\"cameraman\"))\nimage_int = map(x -> x.:i, image_float) .|> Int64\n\nblur_float = evaluateZernike(LinRange(-41,41,512), [12, 4, 0], [1.0, -1.0, 2.0], index=:OSA)\nblur_float ./= (sum(blur_float))\nblur_float = blur_float\nblur_int = blur_float .|> Normed{UInt8, 8} .|> x -> x.:i .|> Int64\n\nblur_int = fftshift(blur_int)\n\n@assert sum(blur_int) == 256 # to not change brightness\n\nblurred_image_float = ifft(fft(image_float) .* fft(fftshift(blur_float))) |> real\n\nt = 4\n(g, q) = (314, 2^2^t+1)\nX = fnt(image_int, g, q)\n@assert ifnt(X, g, q) == image_int\nH = fnt(blur_int, g, q)\n@assert ifnt(H, g, q) == blur_int\nY = mod.((X .* H), q)\ny = ifnt(Y, g, q)\nblurred_image_int = y / 2^16\n\nusing Statistics\n@show maximum(abs.(blurred_image_float .- blurred_image_int))\n@show mean(abs.(blurred_image_float .- blurred_image_int))\n@show var(abs.(blurred_image_float .- blurred_image_int))\n\nsave(\"doc/src/fnt/original.jpg\", Images.clamp01nan.(image_float))\nsave(\"doc/src/fnt/blurred_fft.jpg\", Images.clamp01nan.(Gray.(Normed{UInt8, 8}.(blurred_image_float))))\nsave(\"doc/src/fnt/blurred_fnt.jpg\", Images.clamp01nan.(Gray.(Normed{UInt8, 8}.(blurred_image_int))))\n", "meta": {"hexsha": "82cf84acaef8d7c7fb2a932313e3c3e5c3c3261a", "size": 1267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "doc/src/fnt/cameraman.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": "doc/src/fnt/cameraman.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": "doc/src/fnt/cameraman.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": 35.1944444444, "max_line_length": 102, "alphanum_fraction": 0.7087608524, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.771047924286507}}
{"text": "using FdeSolver\nusing Plots\nusing SpecialFunctions\n\n## inputs\ntSpan = [0, 1]     # [intial time, final time]\ny0 = 0             # intial value\n\u03b2 = 0.5            # order of the derivative\nh=2^-5\n\n# Equation\npar = \u03b2\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, \u03b2, par, h = h, StopIt = \"Convergence\", tol = 10e-8, itmax = 30)\n\nt1, Yapp1 = FDEsolver(F, tSpan, y0, \u03b2, 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 + \u03b2 / 2) + 9 / 4 * t.^\u03b2),\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\u00e6rs\u00f8k\n## Bin\u00e6rs\u00f8k er en enkel, men viktig algoritme med mange bruksomr\u00e5der. Les om den i appendiks C (\u00abBin\u00e6rs\u00f8k\u00bb) i pensumheftet.\n## Under vises julia-koden for funksjonen bisect_left som er en variant av bin\u00e6rs\u00f8k. 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\u00e5 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\u00e5 denne indeksen i sortert rekkef\u00f8lge.\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, \u03bc=1.0)\n\nReturns the function\n```math\nf(x) = \u03bc\u22c5\u2211_i \\\\max\\\\{0, 1 - y_i \u22c5 x_i\\\\}^2,\n```\nwhere `y` is an array and `\u03bc` 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 \u21a6 \u03bc * sum( max(0,1-b*x_i)^2, i=1,...,n )\"\nfun_params(f::SqrHingeLoss) = \"b = $(typeof(f.y)), \u03bc = $(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": "using GeneralizedSampling\nusing Base.Test\n\nprintln(\"Testing NFFT...\")\n\n#=\nTest if the (N)FFT part of a Freq2Wave type behaves like a DFT matrix by\nremoving the parts related to wavelets.\n\nFor integer samples [0:N-1] the DFT matrix is Hermitian.\n\nThe special version of NFFT with uniform sampling locations should agree \nwith the general version.\n=#\n\n\n# ------------------------------------------------------------\n# 1D\n\nbegin\n\tN = 16.0\n\tsamples = collect( 0:N-1 )\n\n\tJ = Int(log2(N))\n\tT = Freq2Wave(samples, \"haar\", J)\n\tfor idx in eachindex(T.internal)\n\t\tT.internal[idx] = 1.0 + 0.0*im\n\tend\n\n\tF = collect(T)\n\tB = F'*F / N\n\n\t@test_approx_eq B eye(B)\nend\n\n\n# ------------------------------------------------------------\n# 2D\n\nbegin\n\tM = 4\n\tsamples = grid(M)\n\n\tJ = Int(log2(M))\n\tT = Freq2Wave(samples, \"haar\", J)\n\tfor idx in eachindex(T.internal)\n\t\tT.internal[idx] = 1.0 + 0.0*im\n\tend\n\n\tF = collect(T)\n\tN = size(T,2)\n\tB = F'*F / N\n\n\t@test_approx_eq B eye(B)\nend\n\n\n# ------------------------------------------------------------\n# Uniform NFFT\n\nJ = rand(2:5)\nM = 2*rand( 2^(J-1):2^J )\nepsilon = 1/rand(2:5)\nxi = GeneralizedSampling.grid(M, epsilon)\n\nusing NFFT\n\nN1 = 2*rand( 2:2^(J-1) )\nchi = xi * 2.0^-J\nP1 = NFFTPlan( frac(chi), N1 )\n\nf = rand(N1) + rand(N1)*im\ny1 = nfft(P1, f)\n\nP2 = GeneralizedSampling.FFTPlan( xi, J, N1 )\ny2 = similar(y1)\nGeneralizedSampling.myfft!(y2, P2, f)\n\n@test_approx_eq_eps y1 y2 1e-5\n\n", "meta": {"hexsha": "49a0fe474ad2bd8ac045a3517ff58df84e24cca7", "size": 1410, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/NFFT.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": "test/NFFT.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": "test/NFFT.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.4074074074, "max_line_length": 73, "alphanum_fraction": 0.565248227, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7710471380472067}}
{"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, \" \u2192 \" * 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    \u03c3::Float64 = 10.0\n    \u03b2::Float64 = 8 / 3\n    \u03c1::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.\u03c3 * (x[2] - x[1])\n    dx[2] = x[1] * (node.\u03c1 - x[3]) - x[2]\n    dx[3] = x[1] * x[2] - node.\u03b2 * 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) \u2264 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    \u03b1::Float64 = 9.0\n    \u03b2::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.\u03b1 * (x[2] - x[1] - ds.diode(x[1]))\n    dx[2] = x[1] - x[2] + x[3]\n    dx[3] = -ds.\u03b2 * 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') = \u03c3\u00b2\n```\nwith signal standard deviation ``\u03c3``.\n\"\"\"\nmutable struct Const{T} <: Kernel where {T<:Real}\n    \"Signal variance\"\n    \u03c32::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nConstant kernel function\n    \n    Const(l\u03c3::T)\n\n# Arguments\n  - `l\u03c3::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nConst(l\u03c3::T) where T = Const{T}(exp(2 * l\u03c3), [])\n\nfunction set_params!(cons::Const, hyp::AbstractVector)\n    length(hyp) == 1 || throw(ArgumentError(\"Constant kernel has one parameter, received $(length(hyp)).\"))\n    cons.\u03c32 = exp(2.0*hyp[1])\nend\n\nget_params(cons::Const{T}) where T = T[log(cons.\u03c32)/2.0]\nget_param_names(cons::Const) = [:l\u03c3]\nnum_params(cons::Const) = 1\n\ncov(cons::Const) = cons.\u03c32\nfunction cov(cons::Const, x::AbstractVector, y::AbstractVector)\n    return cov(cons)\nend\n\n@inline dk_dl\u03c3(cons::Const) = 2.0*cov(cons)\n@inline function dKij_d\u03b8p(cons::Const, X1, X2, i::Int, j::Int, p::Int, dim::Int)\n    if p == 1\n        return dk_dl\u03c3(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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7cc2-eacd-11eb-29e2-810a573295cf\nusing LinearAlgebra\n\n# \u2554\u2550\u2561 034f7c90-eacd-11eb-1b40-8722209689fa\nusing DataFrames # load the DataFrames package\n\n# \u2554\u2550\u2561 034f7d1a-eacd-11eb-1d48-591daf597cd6\nusing Random\n\n# \u2554\u2550\u2561 034f7d3a-eacd-11eb-1144-65f9acfcf24c\nbegin\n\tusing Plots\n\tplotly()\nend\n\n# \u2554\u2550\u2561 034f7d58-eacd-11eb-3189-bff16ec27739\nusing Distributions\n\n# \u2554\u2550\u2561 034f7d76-eacd-11eb-24cc-fd8d53d736c2\nusing Statistics\n\n# \u2554\u2550\u2561 d6e5fe02-21a5-486c-a237-878be1d95439\nbegin\n    using MLCourse\n    MLCourse.list_notebooks(@__FILE__)\nend\n\n# \u2554\u2550\u2561 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 \u00f7 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b8630ee9-d2c0-4cd0-b3f7-77f66e997a80\n\n\n# \u2554\u2550\u2561 034f7b46-eacd-11eb-1aa2-f380d08206cc\n1 + 2\n\n# \u2554\u2550\u2561 034f7b64-eacd-11eb-1618-6de6def66405\n2 * 3\n\n# \u2554\u2550\u2561 034f7b6e-eacd-11eb-1733-650ad4da2730\n3 ^ 2\n\n# \u2554\u2550\u2561 034f7b78-eacd-11eb-003a-5b5801c19d80\n3 == 9 / 3 # test for equality\n\n# \u2554\u2550\u2561 034f7b6e-eacd-11eb-184a-d504fab31681\n4 / 3 # compute the fraction as a floating point number\n\n# \u2554\u2550\u2561 fb3677a9-1610-49dd-96e4-3bd7badc58db\n4 // 3 # leave the fraction as a fraction\n\n# \u2554\u2550\u2561 884f568b-079c-47d6-a597-34b67925f195\n4//3 * 3//2 * 1//7 # simplify fractions\n\n# \u2554\u2550\u2561 034f7b84-eacd-11eb-2836-11cebedb05b9\n5 \u00f7 2 # Write this symbol with \\div [TAB]. Try it in a new cell!\n\n# \u2554\u2550\u2561 52efdece-3c21-43d4-a826-3b96e3a23e60\nmd\"# Variables and Simple Functions\n\nSee also [here](https://docs.julialang.org/en/v1/manual/variables/).\"\n\n# \u2554\u2550\u2561 034f7ba0-eacd-11eb-3fc1-9dca0e072755\nx = 2\n\n# \u2554\u2550\u2561 034f7ba0-eacd-11eb-23ae-cd327563ec60\ny = 4.5\n\n# \u2554\u2550\u2561 034f7ba0-eacd-11eb-3347-49deb13761d9\nz = x * y\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7baa-eacd-11eb-33f2-5f619e4a7832\nsin(x)\n\n# \u2554\u2550\u2561 034f7bb2-eacd-11eb-006b-7b935e35af66\nexp(x)\n\n# \u2554\u2550\u2561 034f7bb2-eacd-11eb-214b-cbfc83965c26\nlog(x)\n\n# \u2554\u2550\u2561 ec1dd4c4-d61d-4fdb-b576-3fe3b059eb3a\ntypeof(2)\n\n# \u2554\u2550\u2561 1a3387ee-b59d-49d7-9cca-2a8bd04eaaad\ntypeof(2.0)\n\n# \u2554\u2550\u2561 034f7b96-eacd-11eb-0c81-ad33210de120\ntypeof(4//3)\n\n# \u2554\u2550\u2561 034f7b96-eacd-11eb-2ee1-cd8e6813a726\ntypeof(2f0)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7bbe-eacd-11eb-2e95-a93ad2d5e867\nmyfunc(x, y) = 2 * x + 3 - y # creates a new function called `myfunc`\n\n# \u2554\u2550\u2561 034f7bbe-eacd-11eb-2c36-d3949367ce5a\nmyfunc(x, y)\n\n# \u2554\u2550\u2561 e0ec7ba3-4858-4572-994d-953caa98080b\nanonfunc = x -> x^2 # creates an anonymous function called `anonfunc`\n\n# \u2554\u2550\u2561 04da39a1-e3bc-4086-b555-6cea2cf1689d\nanonfunc(4)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7bc8-eacd-11eb-31f9-c119d1dfb8a5\nlongfunc(x, y)\n\n# \u2554\u2550\u2561 ce3c7687-c7a9-4b5d-9a55-51514ed90fd9\nmd\"We will sometimes use the pipe operator to chain functions.\"\n\n# \u2554\u2550\u2561 034f7bd2-eacd-11eb-28f3-b707012e1db0\nx |> sin |> exp |> log10\n\n# \u2554\u2550\u2561 034f7bd2-eacd-11eb-1789-7380a89d5339\nlog10(exp(sin(x)))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7cd6-eacd-11eb-0f8c-11179c3ab48f\ns1 = \"Hi! \"\n\n# \u2554\u2550\u2561 034f7ce0-eacd-11eb-3c49-e39b8d3e917f\ns2 = \"Welcome to Machine Learning\"\n\n# \u2554\u2550\u2561 034f7ce0-eacd-11eb-18a1-bd2d1849b9bc\ns1 * s2\n\n# \u2554\u2550\u2561 034f7cec-eacd-11eb-3262-bdc0f2e13a3a\ns1 ^ 3 * s2\n\n# \u2554\u2550\u2561 034f7cec-eacd-11eb-27da-9bb861643df2\nsplit(s2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 91b0de0c-221c-468e-9077-5233aedeb4ca\nanswer = 42\n\n# \u2554\u2550\u2561 0c7ae3ec-a40f-4e3e-85d8-3f79f091e3b4\n\"The answer is $answer.\" # we interpolate with the dollar sign\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0efb1f1a-8051-4843-aa68-1f4ad8618f92\nmd\"# Vectors, Matrices and Arrays\n\nSee also [here](https://docs.julialang.org/en/v1/manual/arrays/).\"\n\n# \u2554\u2550\u2561 034f7bdc-eacd-11eb-1999-9b62efdb4128\nv = [1, 2, 3] # this is a vector\n\n# \u2554\u2550\u2561 034f7cba-eacd-11eb-2f1a-836ccc185dd9\npush!(v, 12)\n\n# \u2554\u2550\u2561 034f7cba-eacd-11eb-3901-2bc3d0ff0e39\npop!(v)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7bfa-eacd-11eb-1839-371285e2c6ed\nw = [1 2 3] # this is a matrix with 1 row and 3 columns\n\n# \u2554\u2550\u2561 034f7be4-eacd-11eb-1616-2df92f244e73\nv[1] # access to the first element of the vector\n\n# \u2554\u2550\u2561 034f7bf0-eacd-11eb-0b3f-69f172657051\nv[2] = 4 # assign value 4 to the second element of the vector\n\n# \u2554\u2550\u2561 034f7bf0-eacd-11eb-012e-997132cd41c6\nv # here we check that the second element is indeed 4 now\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7c04-eacd-11eb-3448-832bd75c3356\nm[3, 2] # accessing the element in the 3 row, second column\n\n# \u2554\u2550\u2561 9c34e4ef-4eba-459f-a7ff-b20708155e65\nm' # transpose the matrix\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7c0e-eacd-11eb-114f-9dbad3e74dd6\nsin.(v)\n\n# \u2554\u2550\u2561 034f7c0e-eacd-11eb-1b73-27539a68f26d\nexp.(m)\n\n# \u2554\u2550\u2561 034f7c16-eacd-11eb-0d0b-518b28558fda\nv .+ 3\n\n# \u2554\u2550\u2561 034f7c16-eacd-11eb-2cb0-8b1198bfcb78\nmyfunc.(v, v)\n\n# \u2554\u2550\u2561 034f7ccc-eacd-11eb-1613-cbdf2386b60b\nm * v  # matrix vector multiplication\n\n# \u2554\u2550\u2561 034f7ccc-eacd-11eb-2ab4-599e0ed86304\nv' * v # inner product\n\n# \u2554\u2550\u2561 034f7cd6-eacd-11eb-37bb-f1930f2f2772\neigvals(m) # compute the Eigen values\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 07fd5baf-ae0b-4e74-97a6-5a6e14644122\n[[1, 2, 3]; [77, 88, 99]] # the semicolon concatenates the two vectors\n\n# \u2554\u2550\u2561 11422ca4-c096-4167-aa53-de312615348e\nmd\"The same can be achieved with\"\n\n# \u2554\u2550\u2561 0ace8c81-e481-4323-9b20-116de412330a\nvcat([1, 2, 3], [77, 88, 99])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e33c0eea-4f5c-4fc8-800d-fa16335eedd0\n[i^2 for i in [3, 4, 9, 7]]\n\n# \u2554\u2550\u2561 315e5a3b-dc28-4c3b-8fc2-3442cb7590be\n[i^2 for i in [3, 4, 9, 7] if isodd(i)]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b91eda3c-95cb-4372-9c6b-03fa6a6b02b2\nmd\"# Ranges\n\nSee also [here](https://docs.julialang.org/en/v1/base/math/#Base.::).\"\n\n# \u2554\u2550\u2561 034f7c16-eacd-11eb-3877-6ba06a933698\ncollect(1:10) # 1:10 is a range; the function `collect` turns it into a vector\n\n# \u2554\u2550\u2561 034f7c22-eacd-11eb-3ab7-b30813d11e94\nr1 = 1:.1:10 # a range from 1 to 10 with step-size 0.1\n\n# \u2554\u2550\u2561 034f7c2c-eacd-11eb-1aae-97b030af71e9\nr3 = 10:-.1:1 # a range from 10 to 1 with step-size -0.1\n\n# \u2554\u2550\u2561 034f7c2c-eacd-11eb-1f56-052874c5c6ab\ncollect(r3)\n\n# \u2554\u2550\u2561 034f7c36-eacd-11eb-0188-cd307154555c\nexp.(r1) # apply exp to the range\n\n# \u2554\u2550\u2561 034f7c40-eacd-11eb-26d9-956b65235a10\nv[2:3] # you can use ranges to access multiple elements of a vector or matrix\n\n# \u2554\u2550\u2561 4237f5df-208d-44c4-90d7-db0efbe7b710\nv[[1, 3]] # a vector of indices can also be used\n\n# \u2554\u2550\u2561 034f7c40-eacd-11eb-1beb-bb9e9bb325db\nv[2:end]\n\n# \u2554\u2550\u2561 034f7c4a-eacd-11eb-0de4-537297318c85\nv[begin:2]\n\n# \u2554\u2550\u2561 034f7c4a-eacd-11eb-03ed-bfc7b532501b\nm[:, 2] # the colon : alone is a short-hand for begin:end\n\n# \u2554\u2550\u2561 034f7c54-eacd-11eb-2918-ef8f2befddc1\nm[1:2, 2:3]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7c5e-eacd-11eb-24c6-d7e7213a7a5e\nis_larger_than_10(4)\n\n# \u2554\u2550\u2561 034f7c5e-eacd-11eb-1ff7-55f09fb796fe\nis_larger_than_10(78)\n\n# \u2554\u2550\u2561 d9ad1d6d-a3b5-4a83-bda9-05ee43ded9d6\nmd\"# Tuples\n\nSee also [here](https://docs.julialang.org/en/v1/manual/functions/#Tuples).\"\n\n# \u2554\u2550\u2561 034f7c68-eacd-11eb-1e11-d77379c677c8\nt = (2, 3, 4., \"bla\")\n\n# \u2554\u2550\u2561 034f7c68-eacd-11eb-12e6-51022c54f6ed\ntypeof(t)\n\n# \u2554\u2550\u2561 034f7c72-eacd-11eb-28a5-d7d6f3b9f75a\nt[1]\n\n# \u2554\u2550\u2561 034f7c72-eacd-11eb-1cc2-91eaa2de5e25\nt[4]\n\n# \u2554\u2550\u2561 034f7c7c-eacd-11eb-1aaa-297c951dd8cd\nnt = (year = 1789,\n\t  event = \"French Revolution\",\n\t  slogan = \"libert\u00e9, \u00e9galit\u00e9, fraternit\u00e9\")\n\n# \u2554\u2550\u2561 034f7c88-eacd-11eb-28f2-c1c7e05279c6\ntypeof(nt)\n\n# \u2554\u2550\u2561 034f7c88-eacd-11eb-14fe-b3d49ff91622\nnt.year\n\n# \u2554\u2550\u2561 034f7c90-eacd-11eb-0d1c-5dbd7b62d55c\nnt.slogan\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7c9a-eacd-11eb-2e85-29c5bffbc39a\ndf = DataFrame(year = [1789, 1863],\n               event = [\"French Revolution\", \"Foundation of Red Cross\"],\n               slogan = [\"libert\u00e9, \u00e9galit\u00e9, fraternit\u00e9\", missing])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7c9a-eacd-11eb-3aee-0bab7ab5d502\ndf.year\n\n# \u2554\u2550\u2561 034f7ca4-eacd-11eb-2f3b-c1dd9be6ad84\ndf[:, 1] # we can also access columns like for matrices\n\n# \u2554\u2550\u2561 034f7ca4-eacd-11eb-054e-1f930c99d304\ndropmissing(df) # removes all rows with missing entries.\n\n# \u2554\u2550\u2561 034f7cae-eacd-11eb-38c0-57df4ba09992\ndf[1, :] # show the first row\n\n# \u2554\u2550\u2561 034f7cc2-eacd-11eb-0f0f-ff16d1ac454b\ndf[df.year .== 1789, [:year, :slogan]] # select all rows where year == 1789 and columns year and slogan\n\n# \u2554\u2550\u2561 034f7cf4-eacd-11eb-302f-55b164df3b90\nmd\"# Random Numbers\n\nSee also [here](https://docs.julialang.org/en/v1/stdlib/Random/).\n\"\n\n# \u2554\u2550\u2561 034f7cf4-eacd-11eb-302f-55b164df3b9f\nrand() # a sample from the uniform distribution over the interval [0, 1).\n\n# \u2554\u2550\u2561 034f7cf4-eacd-11eb-003c-133f34cca508\nrand() # different number than in the cell above.\n\n# \u2554\u2550\u2561 034f7cfe-eacd-11eb-2514-4b6fdbc42e8f\nrand(10)\n\n# \u2554\u2550\u2561 034f7d08-eacd-11eb-2694-51c1baa997e6\nrand(3, 3)\n\n# \u2554\u2550\u2561 034f7d12-eacd-11eb-1673-c94969427bbf\nrandn() # a sample from the normal distribution with mean 0 and variance 1\n\n# \u2554\u2550\u2561 034f7d12-eacd-11eb-261c-a5de2f06f420\nrand((:bla, \"bli\", 3, 1.2))\n\n# \u2554\u2550\u2561 034f7d1a-eacd-11eb-1e34-21d5eef62940\nRandom.seed!(123) # sets the seed of the random number generator to 123\n\n# \u2554\u2550\u2561 034f7d26-eacd-11eb-066c-538e5b614536\nrand()\n\n# \u2554\u2550\u2561 034f7d30-eacd-11eb-081f-970c4daee184\nRandom.seed!(123) # resets the seed\n\n# \u2554\u2550\u2561 034f7d30-eacd-11eb-0b09-7b3b9ac47570\nrand() # same result as when `rand()` was called last time.\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7d3a-eacd-11eb-3fbe-6dc4ab1efd56\nplot(1:4, rand(4))\n\n# \u2554\u2550\u2561 034f7d3a-eacd-11eb-1ef3-4f89b8e5aee9\nscatter(rand(100), rand(100))\n\n# \u2554\u2550\u2561 034f7d44-eacd-11eb-0ab2-2f0d2caed9d6\nwith_terminal(plotattr) # get some help on plotting attributes\n\n# \u2554\u2550\u2561 034f7d4c-eacd-11eb-3960-d10d1c16075d\nwith_terminal(plotattr, :Series)\n\n# \u2554\u2550\u2561 034f7d4c-eacd-11eb-3841-97ca37e34c9f\nwith_terminal(plotattr, :Series, \"label\")\n\n# \u2554\u2550\u2561 034f7d58-eacd-11eb-123f-9b563a7ae27e\nscatter(rand(100), rand(100), label = \"my data\", xlabel = \"X1\", ylabel = \"X2\")\n\n# \u2554\u2550\u2561 4ca1cd98-a24b-491f-b9ac-28a7daf96d50\nmd\"To compose figures with multiple elements, you can use the `!` version of the plotting functions\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e7ed9e83-7f17-4d9a-a49b-e87bc0747035\nbegin\n\ta_global_variable = 17\n\tanother_global_variable = \"Hi\"\nend;\n\n# \u2554\u2550\u2561 0d66592a-d098-4ab5-9323-503db8fc73f6\na_global_variable * 3\n\n# \u2554\u2550\u2561 a9a3f29e-4931-4464-9bc5-af6598815f24\n\"$another_global_variable there!\"\n\n# \u2554\u2550\u2561 6e65247f-b285-49e5-a16e-31b4541225bf\nlet\n\ta_local_variable = 17\n\tanother_local_variable = \"Hi\"\nend;\n\n# \u2554\u2550\u2561 fcd77620-f18a-499b-87c4-fffaa876e59f\na_local_variable * 3\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 034f7d62-eacd-11eb-3840-51c0622eb8a9\nd1 = Normal(3, 2.5)\n\n# \u2554\u2550\u2561 034f7d6c-eacd-11eb-0eb6-277bf88c13d3\nrand(d1) # draw a sample from this normal distribution\n\n# \u2554\u2550\u2561 034f7d6c-eacd-11eb-2792-d773a2c77cb6\nrand(d1, 10) # draw 10 samples from this distriution\n\n# \u2554\u2550\u2561 034f7d6c-eacd-11eb-0dc0-3bd2b5a24d38\nmean(rand(d1, 10^5))\n\n# \u2554\u2550\u2561 034f7d76-eacd-11eb-141d-0f90eef73f08\nstd(rand(d1, 10^5)) # standard deviation\n\n# \u2554\u2550\u2561 034f7d7e-eacd-11eb-0945-2dda6be01349\nd2 = Bernoulli(.7)\n\n# \u2554\u2550\u2561 034f7d7e-eacd-11eb-2a1b-933e1231c220\nrand(d2, 10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03c0. Hint: type `\\pi + [Tab]` to enter the symbol \u03c0. 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# \u2554\u2550\u2561 0314376e-ff8c-4ad0-8a4b-f94f04f31f2c\nMLCourse.footer()\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500f3508747-da29-47c9-a98e-22ea15caaf2f\n# \u255f\u2500d92c0729-c7ab-42cc-b713-30f00e237833\n# \u2560\u2550b8630ee9-d2c0-4cd0-b3f7-77f66e997a80\n# \u2560\u2550034f7b46-eacd-11eb-1aa2-f380d08206cc\n# \u2560\u2550034f7b64-eacd-11eb-1618-6de6def66405\n# \u2560\u2550034f7b6e-eacd-11eb-1733-650ad4da2730\n# \u2560\u2550034f7b78-eacd-11eb-003a-5b5801c19d80\n# \u2560\u2550034f7b6e-eacd-11eb-184a-d504fab31681\n# \u2560\u2550fb3677a9-1610-49dd-96e4-3bd7badc58db\n# \u2560\u2550884f568b-079c-47d6-a597-34b67925f195\n# \u2560\u2550034f7b84-eacd-11eb-2836-11cebedb05b9\n# \u255f\u250052efdece-3c21-43d4-a826-3b96e3a23e60\n# \u2560\u2550034f7ba0-eacd-11eb-3fc1-9dca0e072755\n# \u2560\u2550034f7ba0-eacd-11eb-23ae-cd327563ec60\n# \u2560\u2550034f7ba0-eacd-11eb-3347-49deb13761d9\n# \u255f\u2500121b3dbb-f86c-44b8-8b0f-f6b4d0b9992f\n# \u2560\u2550034f7baa-eacd-11eb-33f2-5f619e4a7832\n# \u2560\u2550034f7bb2-eacd-11eb-006b-7b935e35af66\n# \u2560\u2550034f7bb2-eacd-11eb-214b-cbfc83965c26\n# \u2560\u2550ec1dd4c4-d61d-4fdb-b576-3fe3b059eb3a\n# \u2560\u25501a3387ee-b59d-49d7-9cca-2a8bd04eaaad\n# \u2560\u2550034f7b96-eacd-11eb-0c81-ad33210de120\n# \u2560\u2550034f7b96-eacd-11eb-2ee1-cd8e6813a726\n# \u255f\u25000f4e3f45-71dd-41b2-a0b3-c55a04ace61f\n# \u2560\u2550034f7bbe-eacd-11eb-2e95-a93ad2d5e867\n# \u2560\u2550034f7bbe-eacd-11eb-2c36-d3949367ce5a\n# \u2560\u2550e0ec7ba3-4858-4572-994d-953caa98080b\n# \u2560\u255004da39a1-e3bc-4086-b555-6cea2cf1689d\n# \u2560\u2550034f7bc8-eacd-11eb-0396-5b743b505b2a\n# \u2560\u2550034f7bc8-eacd-11eb-31f9-c119d1dfb8a5\n# \u255f\u2500ce3c7687-c7a9-4b5d-9a55-51514ed90fd9\n# \u2560\u2550034f7bd2-eacd-11eb-28f3-b707012e1db0\n# \u2560\u2550034f7bd2-eacd-11eb-1789-7380a89d5339\n# \u255f\u2500034f7cd6-eacd-11eb-0f8c-11179c3ab480\n# \u2560\u2550034f7cd6-eacd-11eb-0f8c-11179c3ab48f\n# \u2560\u2550034f7ce0-eacd-11eb-3c49-e39b8d3e917f\n# \u2560\u2550034f7ce0-eacd-11eb-18a1-bd2d1849b9bc\n# \u2560\u2550034f7cec-eacd-11eb-3262-bdc0f2e13a3a\n# \u2560\u2550034f7cec-eacd-11eb-27da-9bb861643df2\n# \u255f\u2500832ce046-ab34-4623-9d02-793dc5748208\n# \u2560\u255091b0de0c-221c-468e-9077-5233aedeb4ca\n# \u2560\u25500c7ae3ec-a40f-4e3e-85d8-3f79f091e3b4\n# \u255f\u2500732ae082-b90f-4108-9872-36077fb2c54c\n# \u2560\u25506bfb60b4-964e-46ec-adc2-ec9e9a0f8158\n# \u255f\u25000efb1f1a-8051-4843-aa68-1f4ad8618f92\n# \u2560\u2550034f7bdc-eacd-11eb-1999-9b62efdb4128\n# \u2560\u2550034f7cba-eacd-11eb-2f1a-836ccc185dd9\n# \u2560\u2550034f7cba-eacd-11eb-3901-2bc3d0ff0e39\n# \u255f\u250050d83a01-f4c5-45c1-9c81-ed71d8313642\n# \u2560\u2550034f7bfa-eacd-11eb-1839-371285e2c6ed\n# \u2560\u2550034f7be4-eacd-11eb-1616-2df92f244e73\n# \u2560\u2550034f7bf0-eacd-11eb-0b3f-69f172657051\n# \u2560\u2550034f7bf0-eacd-11eb-012e-997132cd41c6\n# \u2560\u2550034f7bfa-eacd-11eb-2bf8-c795453a8959\n# \u2560\u2550034f7c04-eacd-11eb-3448-832bd75c3356\n# \u2560\u25509c34e4ef-4eba-459f-a7ff-b20708155e65\n# \u255f\u2500e576bf44-9cc1-4053-b40f-b82c8c39c89d\n# \u2560\u2550034f7c0e-eacd-11eb-114f-9dbad3e74dd6\n# \u2560\u2550034f7c0e-eacd-11eb-1b73-27539a68f26d\n# \u2560\u2550034f7c16-eacd-11eb-0d0b-518b28558fda\n# \u2560\u2550034f7c16-eacd-11eb-2cb0-8b1198bfcb78\n# \u2560\u2550034f7ccc-eacd-11eb-1613-cbdf2386b60b\n# \u2560\u2550034f7ccc-eacd-11eb-2ab4-599e0ed86304\n# \u2560\u2550034f7cc2-eacd-11eb-29e2-810a573295cf\n# \u2560\u2550034f7cd6-eacd-11eb-37bb-f1930f2f2772\n# \u255f\u2500c997a07f-bc89-4c29-9945-62046b6889d2\n# \u2560\u255007fd5baf-ae0b-4e74-97a6-5a6e14644122\n# \u255f\u250011422ca4-c096-4167-aa53-de312615348e\n# \u2560\u25500ace8c81-e481-4323-9b20-116de412330a\n# \u2560\u25505d09ccbf-5a51-41f7-a7ef-84cf2cc5fa1f\n# \u255f\u25009fd6e8c1-7b84-4d76-abef-9e3da4a56dc7\n# \u2560\u2550e33c0eea-4f5c-4fc8-800d-fa16335eedd0\n# \u2560\u2550315e5a3b-dc28-4c3b-8fc2-3442cb7590be\n# \u2560\u255045deab46-9a8c-4d22-9460-980a3900396f\n# \u255f\u2500b91eda3c-95cb-4372-9c6b-03fa6a6b02b2\n# \u2560\u2550034f7c16-eacd-11eb-3877-6ba06a933698\n# \u2560\u2550034f7c22-eacd-11eb-3ab7-b30813d11e94\n# \u2560\u2550034f7c2c-eacd-11eb-1aae-97b030af71e9\n# \u2560\u2550034f7c2c-eacd-11eb-1f56-052874c5c6ab\n# \u2560\u2550034f7c36-eacd-11eb-0188-cd307154555c\n# \u2560\u2550034f7c40-eacd-11eb-26d9-956b65235a10\n# \u2560\u25504237f5df-208d-44c4-90d7-db0efbe7b710\n# \u2560\u2550034f7c40-eacd-11eb-1beb-bb9e9bb325db\n# \u2560\u2550034f7c4a-eacd-11eb-0de4-537297318c85\n# \u2560\u2550034f7c4a-eacd-11eb-03ed-bfc7b532501b\n# \u2560\u2550034f7c54-eacd-11eb-2918-ef8f2befddc1\n# \u2560\u2550034f7c54-eacd-11eb-2fe9-5330d3cd3cd5\n# \u2560\u2550034f7c5e-eacd-11eb-24c6-d7e7213a7a5e\n# \u2560\u2550034f7c5e-eacd-11eb-1ff7-55f09fb796fe\n# \u255f\u2500d9ad1d6d-a3b5-4a83-bda9-05ee43ded9d6\n# \u2560\u2550034f7c68-eacd-11eb-1e11-d77379c677c8\n# \u2560\u2550034f7c68-eacd-11eb-12e6-51022c54f6ed\n# \u2560\u2550034f7c72-eacd-11eb-28a5-d7d6f3b9f75a\n# \u2560\u2550034f7c72-eacd-11eb-1cc2-91eaa2de5e25\n# \u2560\u2550034f7c7c-eacd-11eb-1aaa-297c951dd8cd\n# \u2560\u2550034f7c88-eacd-11eb-28f2-c1c7e05279c6\n# \u2560\u2550034f7c88-eacd-11eb-14fe-b3d49ff91622\n# \u2560\u2550034f7c90-eacd-11eb-0d1c-5dbd7b62d55c\n# \u255f\u2500df8588cb-400b-4423-9766-e6cac2c9717a\n# \u2560\u2550034f7c90-eacd-11eb-1b40-8722209689fa\n# \u2560\u2550034f7c9a-eacd-11eb-2e85-29c5bffbc39a\n# \u2560\u2550034f7cae-eacd-11eb-39dc-ab39e97cc716\n# \u2560\u2550034f7c9a-eacd-11eb-3aee-0bab7ab5d502\n# \u2560\u2550034f7ca4-eacd-11eb-2f3b-c1dd9be6ad84\n# \u2560\u2550034f7ca4-eacd-11eb-054e-1f930c99d304\n# \u2560\u2550034f7cae-eacd-11eb-38c0-57df4ba09992\n# \u2560\u2550034f7cc2-eacd-11eb-0f0f-ff16d1ac454b\n# \u255f\u2500034f7cf4-eacd-11eb-302f-55b164df3b90\n# \u2560\u2550034f7cf4-eacd-11eb-302f-55b164df3b9f\n# \u2560\u2550034f7cf4-eacd-11eb-003c-133f34cca508\n# \u2560\u2550034f7cfe-eacd-11eb-2514-4b6fdbc42e8f\n# \u2560\u2550034f7d08-eacd-11eb-2694-51c1baa997e6\n# \u2560\u2550034f7d12-eacd-11eb-1673-c94969427bbf\n# \u2560\u2550034f7d12-eacd-11eb-261c-a5de2f06f420\n# \u2560\u2550034f7d1a-eacd-11eb-1d48-591daf597cd6\n# \u2560\u2550034f7d1a-eacd-11eb-1e34-21d5eef62940\n# \u2560\u2550034f7d26-eacd-11eb-066c-538e5b614536\n# \u2560\u2550034f7d30-eacd-11eb-081f-970c4daee184\n# \u2560\u2550034f7d30-eacd-11eb-0b09-7b3b9ac47570\n# \u255f\u2500034f7d3a-eacd-11eb-3fbe-6dc4ab1efd50\n# \u2560\u2550034f7d3a-eacd-11eb-1144-65f9acfcf24c\n# \u2560\u2550034f7d3a-eacd-11eb-3fbe-6dc4ab1efd56\n# \u2560\u2550034f7d3a-eacd-11eb-1ef3-4f89b8e5aee9\n# \u2560\u2550034f7d44-eacd-11eb-0ab2-2f0d2caed9d6\n# \u2560\u2550034f7d4c-eacd-11eb-3960-d10d1c16075d\n# \u2560\u2550034f7d4c-eacd-11eb-3841-97ca37e34c9f\n# \u2560\u2550034f7d58-eacd-11eb-123f-9b563a7ae27e\n# \u255f\u25004ca1cd98-a24b-491f-b9ac-28a7daf96d50\n# \u2560\u255065e73d27-3709-4894-87ab-432343d314c6\n# \u255f\u25009f69c2ab-2940-40ce-b164-07bfa6cc1697\n# \u2560\u2550e7ed9e83-7f17-4d9a-a49b-e87bc0747035\n# \u2560\u25500d66592a-d098-4ab5-9323-503db8fc73f6\n# \u2560\u2550a9a3f29e-4931-4464-9bc5-af6598815f24\n# \u2560\u25506e65247f-b285-49e5-a16e-31b4541225bf\n# \u2560\u2550fcd77620-f18a-499b-87c4-fffaa876e59f\n# \u255f\u2500034f7d62-eacd-11eb-3840-51c0622eb8a0\n# \u2560\u2550034f7d58-eacd-11eb-3189-bff16ec27739\n# \u2560\u2550034f7d62-eacd-11eb-3840-51c0622eb8a9\n# \u2560\u2550034f7d6c-eacd-11eb-0eb6-277bf88c13d3\n# \u2560\u2550034f7d6c-eacd-11eb-2792-d773a2c77cb6\n# \u2560\u2550034f7d6c-eacd-11eb-0dc0-3bd2b5a24d38\n# \u2560\u2550034f7d76-eacd-11eb-24cc-fd8d53d736c2\n# \u2560\u2550034f7d76-eacd-11eb-141d-0f90eef73f08\n# \u2560\u2550034f7d7e-eacd-11eb-0945-2dda6be01349\n# \u2560\u2550034f7d7e-eacd-11eb-2a1b-933e1231c220\n# \u255f\u2500034f7d8a-eacd-11eb-1dc0-d99d481ab6fa\n# \u255f\u25004a03cfae-9876-4cf0-a498-d750853191cb\n# \u255f\u2500d6e5fe02-21a5-486c-a237-878be1d95439\n# \u255f\u2500065a1e67-6b63-43df-9d6d-303af08d8434\n# \u255f\u25000314376e-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": "@testset \"Test Jacobian matrix\" begin\n    @test isapprox(jacobian(sin, [1, 2, 3], 0.0000001), [0.540302 0.0 0.0; 0.0 -0.416147 0.0; 0.0 0.0 -0.989992]; atol=1e-5)\nend", "meta": {"hexsha": "b69eb4d0f2ac8fac846c32024d7ba1a0f7295f5a", "size": 166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/jacobiantest.jl", "max_stars_repo_name": "ErikQQY/ComplexDiff.jl", "max_stars_repo_head_hexsha": "0e7117c03f255ac845c28610a31c00864822ed6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-12T14:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T16:11:35.000Z", "max_issues_repo_path": "test/jacobiantest.jl", "max_issues_repo_name": "ErikQQY/ComplexDiff.jl", "max_issues_repo_head_hexsha": "0e7117c03f255ac845c28610a31c00864822ed6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-30T10:01:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T10:01:35.000Z", "max_forks_repo_path": "test/jacobiantest.jl", "max_forks_repo_name": "ErikQQY/ComplexDiff.jl", "max_forks_repo_head_hexsha": "0e7117c03f255ac845c28610a31c00864822ed6e", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 124, "alphanum_fraction": 0.6445783133, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9658995713428385, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7709682595147355}}
{"text": "using Base.Test\nusing StateEstimation\n\n\nprintln(\"1. Testing State constructors and methods...\")\ninclude(\"state_tests.jl\")\n\nprintln(\"2. Testing System constructors and methods...\")\ninclude(\"system_tests.jl\")\n\nprintln(\"3. Testing Observer constructors and methods...\")\ninclude(\"observer_tests.jl\")\n\nprintln(\"4. Testing UnscentedTransform constructors and methods...\")\ninclude(\"unscented_transform_tests.jl\")\n\nprintln(\"5. Testing KalmanFilter constructors and methods...\")\ninclude(\"kalman_filter_tests.jl\")\n\nprintln(\"6. Testing ExtendedKalmanFilter constructors and methods...\")\ninclude(\"extended_kalman_filter_tests.jl\")\n\nprintln(\"7. Testing MultiTargetFilter constructors and methods...\")\ninclude(\"multi_target_filter_tests.jl\")\n\nprintln(\"8. Testing LeastSquaresEstimator constructors and methods...\")\ninclude(\"least_squares_tests.jl\")\n\nprintln(\"9. Testing EstimatorHistory constructors and methods...\")\ninclude(\"archive_tests.jl\")\n", "meta": {"hexsha": "104d400d6d3f6524800724fd982d851fd97aadcb", "size": 931, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "bradsease/StateEstimation.jl", "max_stars_repo_head_hexsha": "415b97b1601eaaddd35762bbb9a5de9587270ea5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-11T17:39:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-04T00:02:32.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "bradsease/StateEstimation.jl", "max_issues_repo_head_hexsha": "415b97b1601eaaddd35762bbb9a5de9587270ea5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-02-12T14:15:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-13T23:46:14.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "bradsease/StateEstimation.jl", "max_forks_repo_head_hexsha": "415b97b1601eaaddd35762bbb9a5de9587270ea5", "max_forks_repo_licenses": ["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.0322580645, "max_line_length": 71, "alphanum_fraction": 0.7905477981, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7708953167982098}}
{"text": "\"\"\"\n    ECON 602 Problem Set 1 Question 4\n\"\"\"\n\nusing Roots, Plots\n\nfunction adequilibrium(\u03c0, \u03b3, \u03c9A, \u03c9B, 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 \u03c0, \u03b3, \u03c9A, \u03c9B;\n\n    f(p, \u03c0, \u03b3, \u03c9A, \u03c9B) = \u03c0*(\u03c9A[1] + p*\u03c9B[1]) + 1/(1 + p*(p*\u03c0/(1-\u03c0))^(-1/\u03b3))*(\u03c9A[2] + p*\u03c9B[2]) - \u03c9A[1] - \u03c9A[2]\n    cA(p, \u03c0, \u03b3, \u03c9A, \u03c9B) = [\u03c0*(\u03c9A[1] + p*\u03c9B[1]), 1/(1 + p*(p*\u03c0/(1 - \u03c0))^(-1/\u03b3))*(\u03c9A[2] + p*\u03c9B[2])]\n    cB(p, \u03c0, \u03b3, \u03c9A, \u03c9B) = [(1 - \u03c0)/p * (\u03c9A[1] + p*\u03c9B[1]), 1/(p + (p*\u03c0/(1 - \u03c0))^(1/\u03b3))*(\u03c9A[2] + p*\u03c9B[2])]\n\n    # It never hurts to plot and see what you're working with\n    plot(p -> f(p, \u03c0, \u03b3, \u03c9A, \u03c9B), 0, 4)\n    plot!(x -> 0, 0, 4)\n    \n    @show p_star = fzero(p -> f(p, \u03c0, \u03b3, \u03c9A, \u03c9B), p_0);\n    #=\n     The first argument, p -> f(p, \u03c0, \u03b3, \u03c9A, \u03c9B), 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, \u03c0, \u03b3, \u03c9A, \u03c9B);\n    @show cB = cB(p_star, \u03c0, \u03b3, \u03c9A, \u03c9B);\n    return (p_star = p_star, cA = cA, cB = cB)  \nend\n\nfunction adequilibrium_alt(\u03c0, \u03b3, \u03c9A, \u03c9B, 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 \u03c0, \u03b3, \u03c9A, \u03c9B;\n\n    f(p, \u03c0, \u03b3, \u03c9A, \u03c9B) = \u03c0*(\u03c9A[1] + p*\u03c9B[1]) + 1/(1 + p*(p*\u03c0/(1-\u03c0))^(-1/\u03b3))*(\u03c9A[2] + p*\u03c9B[2]) - \u03c9A[1] - \u03c9A[2]\n    cA(p, \u03c0, \u03b3, \u03c9A, \u03c9B) = [\u03c0*(\u03c9A[1] + p*\u03c9B[1]), 1/(1 + p*(p*\u03c0/(1 - \u03c0))^(-1/\u03b3))*(\u03c9A[2] + p*\u03c9B[2])]\n    cB(p, \u03c0, \u03b3, \u03c9A, \u03c9B) = [(1 - \u03c0)/p * (\u03c9A[1] + p*\u03c9B[1]), 1/(p + (p*\u03c0/(1 - \u03c0))^(1/\u03b3))*(\u03c9A[2] + p*\u03c9B[2])]\n\n    # It never hurts to plot and see what you're working with\n    plot(p -> f(p, \u03c0, \u03b3, \u03c9A, \u03c9B), p_min, p_max)\n    plot!(x -> 0, p_min, p_max)\n    \n    # Alternative to anonymous function\n    f(p) = f(p, \u03c0, \u03b3, \u03c9A, \u03c9B)\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, \u03c0, \u03b3, \u03c9A, \u03c9B);\n    @show cB = cB(p_star, \u03c0, \u03b3, \u03c9A, \u03c9B);\n    return (p_star = p_star, cA = cA, cB = cB);\nend\n\n# q4e\n\u03c9A = [2, 5];\n\u03c9B = [5, 2];\n\u03b3 = 2;\n\u03c0 = 0.5;\nq4e = adequilibrium(\u03c0, \u03b3, \u03c9A, \u03c9B, 1.1);\nq4e_alt = adequilibrium_alt(\u03c0, \u03b3, \u03c9A, \u03c9B, 0.01, 10.);\n\n# q4f\n\u03c9A = [2, 5];\n\u03c9B = [5, 2];\n\u03b3 = 2;\n# \u03c0 = 0.25\n\u03c0 = 0.25;\nq4f_\u03c0025 = adequilibrium(\u03c0, \u03b3, \u03c9A, \u03c9B, 1.1);\n# \u03c0 = 0.75\n\u03c0 = 0.75;\nq4f_\u03c0075 = adequilibrium(\u03c0, \u03b3, \u03c9A, \u03c9B, 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\u2013517. 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# \u2554\u2550\u2561 3ea4f8be-d0a7-455d-b58e-3e81ea61f9c1\nusing Plots,Images, Combinatorics, PlutoUI, Colors, ImageIO, LinearAlgebra\n\n# \u2554\u2550\u2561 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; \u03bb=1.0, \u03f5=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) \u2248 sum(b) \"a and b don't have equal sums\"\n\t\tu, v = copy(a), copy(b)\n\t\tM = exp.(-\u03bb * (C .- mean(C)))\n\t\t# normalize this matrix\n\t\twhile maximum(abs.(a .- Diagonal(u) * (M * v))) > \u03f5\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ed3f476c-2205-43a7-a4cf-5941a0d0afd0\nstaff = [\"Bernard\", \"Jan\", \"Willem\", \"Hilde\", \"Steffie\", \"Marlies\", \"Tim\", \"Wouter\"]\n\n# \u2554\u2550\u2561 0e579d2e-9b78-4a56-a30d-883cec0ad5d6\ndesserts = [\"merveilleux\", \"eclair\", \"chocolate mousse\", \"bavarois\", \"carrot cake\"]\n\n# \u2554\u2550\u2561 ce639d43-7481-43f4-8724-1da9c18d716a\na = [3.0, 3, 3, 4, 2, 2, 2, 1]\n\n# \u2554\u2550\u2561 c32441ee-c62d-4ee7-8e1b-ff7de1072d43\nb = [4.0, 2, 6, 4, 4]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 01e3b967-e441-4041-8bd8-5cfc0e0ebaa4\nCdessert = -preferences;  # cost\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1468ec48-bedb-4977-8b88-794d89e5ae8f\nC_cells = missing\n\n# \u2554\u2550\u2561 88569ef5-bc60-4a77-aa72-fc9bdf66b3a4\n# add the lines to the cells\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8214f18f-5d45-455f-b2ce-01085377cdf1\nfunction sinkhorn(C::Matrix, a::Vector, b::Vector; \u03bb=1.0, \u03f5=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) \u2248 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))) > \u03f5\n        # scale u\n        # scale v\n      end\n    return Diagonal(u) * M * Diagonal(v)\n  end\n\n# \u2554\u2550\u2561 425ce568-f3a2-4e73-a6f9-e0373f71436e\n# solve the dessert problem for \u03bb=0.1\n\n# \u2554\u2550\u2561 f320803a-0439-4881-9570-3b4f6621d044\n# solve the dessert problem for \u03bb=10\n\n# \u2554\u2550\u2561 0295836f-0672-4903-a3f1-9004a187481b\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c365eb3f-a7a7-485c-b696-02dd7fccbde3\nimage1 = load(\"image1.jpg\")\n\n# \u2554\u2550\u2561 648ead24-cd9b-4fe5-97b4-f7a458c9f374\nimage2 = load(\"image2.jpg\")\n\n# \u2554\u2550\u2561 d160a399-7908-48af-9384-c245344e3bdd\nmd\"These images might be large, so let's subsample them!\"\n\n# \u2554\u2550\u2561 8c92dbde-e6a3-42aa-a6a6-b2e615fc9f29\nsubsample(image, every=8) = image[1:every:size(image,1), 1:every:size(image,2)]\n\n# \u2554\u2550\u2561 3fb7114f-c765-4153-be6c-66af2d629338\nimage1ss = subsample(image1)\n\n# \u2554\u2550\u2561 80e00b5d-3206-4d26-81ed-1228122a60ac\nimage2ss = subsample(image2)\n\n# \u2554\u2550\u2561 02b3e106-64e9-4fb4-b4b5-9e1bbe7b8a6d\nmd\"Take a look at the distribution of colors!\"\n\n# \u2554\u2550\u2561 1161be1d-9fcf-45e4-9127-c8560adcca5a\ncolors1 = vec(image1ss)\n\n# \u2554\u2550\u2561 cc587c5b-bdf1-426a-8733-f4a2ce33637e\ncolors2 = vec(image2ss)\n\n# \u2554\u2550\u2561 ad3eebaa-4fa2-438a-a088-16334dba3a89\nn_colors1 = length(colors1)\n\n# \u2554\u2550\u2561 11deb453-bd6e-43b1-b1e1-61606644eef8\nn_colors2 = length(colors2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dfe40afd-5153-4315-8511-cba00806d7e5\nmd\"Use this to compute the pairwise distances between all the colors!\"\n\n# \u2554\u2550\u2561 7733a347-47bc-4a98-ac54-7139a945de0c\nCcol = [colordiff(c1, c2) for c1 in colors1, c2 in colors2]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 84470c18-41f7-4ed8-b6a8-25eefbc97e41\na_col = ones(n_colors1) / n_colors1\n\n# \u2554\u2550\u2561 6be95f94-e71f-4447-bc7a-cf1bfcda49a4\nb_col = ones(n_colors2) / n_colors2\n\n# \u2554\u2550\u2561 49fd9af6-f5a5-4f82-a39d-39f741430df6\nPcolors = Solution.sinkhorn(Ccol,\n\t\t\ta_col,\n\t\t\tb_col, \u03bb=10, \u03f5=1e-5)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e07b9f46-3cbe-490e-8e42-60470db2d4b4\nimage1_transf = reshape(mapdistr(colors2, Pcolors), size(image1ss))\n\n# \u2554\u2550\u2561 64dcfee5-941c-417f-9698-18f57e4887f6\nimage2_transf = reshape(mapdistr(colors1, Pcolors'), size(image2ss))\n\n# \u2554\u2550\u2561 be1024ce-78fb-4436-9771-d1d952bfa69b\nmd\"## References\n\n- Gabriel Peyr\u00e9 and Marco Cuturi, *Computational Optimal Transport*, ArXiv:1803.00567, 2018.\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 49b390b5-2192-43d9-ac71-337e2d19799b\nmyr, myg, myb = parse(Colorant, myred), parse(Colorant, mygreen), parse(Colorant, myblue)\n\n# \u2554\u2550\u2561 49193509-14ea-4f0f-8fc1-14e7a924d2d7\ncolordiff(myr, myg)  # difference between red and green\n\n# \u2554\u2550\u2561 627d6a6f-1c20-4242-8fc8-0a6a2ed91549\ncolordiff(myb, myg)  # difference between blue and green\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ef606085-c423-4287-b4db-62ce3ddd0ed7\nplot(\n  colorscatter(colors1, title=\"figure 1\"),\n  colorscatter(colors2, title=\"figure 2\"))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25006f9362d0-1bb6-11ec-2b8b-491ef1f091e5\n# \u2560\u25503ea4f8be-d0a7-455d-b58e-3e81ea61f9c1\n# \u255f\u2500ccb9bf05-1830-4c56-bf28-312c5d324484\n# \u255f\u250065a73b72-967d-4a62-af17-f71b286f3303\n# \u2560\u2550ed3f476c-2205-43a7-a4cf-5941a0d0afd0\n# \u2560\u25500e579d2e-9b78-4a56-a30d-883cec0ad5d6\n# \u2560\u2550ce639d43-7481-43f4-8724-1da9c18d716a\n# \u2560\u2550c32441ee-c62d-4ee7-8e1b-ff7de1072d43\n# \u255f\u25000b50b550-8c2b-43d7-849b-73ee8f60ff52\n# \u255f\u2500245acb05-d58b-4ca6-9cf4-e59ff50e86c9\n# \u2560\u2550114c8c91-34f3-4256-ab0f-c1fbd64e4827\n# \u2560\u255001e3b967-e441-4041-8bd8-5cfc0e0ebaa4\n# \u255f\u25007dbf484a-f3fb-4510-b500-57f4b13c0f59\n# \u255f\u2500b3440682-8443-4052-bbf2-8f593c4e54c3\n# \u255f\u2500984effce-9a76-4bbb-9105-06887dfa629e\n# \u255f\u25009567f11f-486a-4960-8b69-42d2e5ee413f\n# \u255f\u25001104b6a8-e781-4f58-ba2d-798ebbc11422\n# \u255f\u2500b85b69fb-bfdb-41bd-a6a1-1aebe3077e08\n# \u2560\u2550cc62b7b1-fe34-4a19-846d-ca6c7fb69ff9\n# \u2560\u25501468ec48-bedb-4977-8b88-794d89e5ae8f\n# \u2560\u255088569ef5-bc60-4a77-aa72-fc9bdf66b3a4\n# \u255f\u2500da2cc178-64c7-4b30-909a-24fb402a489b\n# \u255f\u2500bdd25212-576e-4b81-8178-1212ac759cbc\n# \u255f\u2500c9cdf082-e986-4a21-8348-cc9faeeeb25a\n# \u255f\u2500efe892d3-23a3-4545-8c05-7ca9c90a9c81\n# \u2560\u25508214f18f-5d45-455f-b2ce-01085377cdf1\n# \u2560\u2550425ce568-f3a2-4e73-a6f9-e0373f71436e\n# \u2560\u2550f320803a-0439-4881-9570-3b4f6621d044\n# \u2560\u25500295836f-0672-4903-a3f1-9004a187481b\n# \u255f\u25008d015b52-96a2-4e7a-9827-76a14fe6b58b\n# \u255f\u2500531be0de-e969-42db-a2fa-f9d125797296\n# \u2560\u2550653a441a-bf0f-4606-a49d-da360d8922dc\n# \u2560\u2550f5d8bd7d-c335-4a10-9cdf-c8f4e953a4ce\n# \u2560\u2550c365eb3f-a7a7-485c-b696-02dd7fccbde3\n# \u2560\u2550648ead24-cd9b-4fe5-97b4-f7a458c9f374\n# \u255f\u2500d160a399-7908-48af-9384-c245344e3bdd\n# \u2560\u25508c92dbde-e6a3-42aa-a6a6-b2e615fc9f29\n# \u2560\u25503fb7114f-c765-4153-be6c-66af2d629338\n# \u2560\u255080e00b5d-3206-4d26-81ed-1228122a60ac\n# \u2560\u255002b3e106-64e9-4fb4-b4b5-9e1bbe7b8a6d\n# \u2560\u25501161be1d-9fcf-45e4-9127-c8560adcca5a\n# \u2560\u2550cc587c5b-bdf1-426a-8733-f4a2ce33637e\n# \u2560\u2550ad3eebaa-4fa2-438a-a088-16334dba3a89\n# \u2560\u255011deb453-bd6e-43b1-b1e1-61606644eef8\n# \u2560\u2550ef606085-c423-4287-b4db-62ce3ddd0ed7\n# \u255f\u2500e52d67d0-b161-403a-85c6-1bb59354f2ee\n# \u2560\u255049b390b5-2192-43d9-ac71-337e2d19799b\n# \u2560\u255049193509-14ea-4f0f-8fc1-14e7a924d2d7\n# \u2560\u2550627d6a6f-1c20-4242-8fc8-0a6a2ed91549\n# \u255f\u2500dfe40afd-5153-4315-8511-cba00806d7e5\n# \u2560\u25507733a347-47bc-4a98-ac54-7139a945de0c\n# \u255f\u25000d719be9-aa39-4d12-9530-d50feb179753\n# \u2560\u255084470c18-41f7-4ed8-b6a8-25eefbc97e41\n# \u2560\u25506be95f94-e71f-4447-bc7a-cf1bfcda49a4\n# \u2560\u255049fd9af6-f5a5-4f82-a39d-39f741430df6\n# \u255f\u250096792a45-2a1f-48de-a514-e5dfd97aabf7\n# \u2560\u2550fa81b789-a1ec-42cc-b73f-2fb1e6d343c3\n# \u2560\u2550e07b9f46-3cbe-490e-8e42-60470db2d4b4\n# \u2560\u255064dcfee5-941c-417f-9698-18f57e4887f6\n# \u255f\u2500be1024ce-78fb-4436-9771-d1d952bfa69b\n# \u255f\u250015da4690-13fd-4b05-ac12-b5ccc2898bd0\n# \u255f\u2500086947e8-1baf-43c6-9c64-f10187b0a9c4\n# \u255f\u2500ba9e51ae-f9d5-4ffe-af79-7bff04ae41b1\n# \u255f\u250031627338-8e0b-4568-a85b-3d7414c87769\n# \u255f\u25003070288a-8060-4da0-8007-41b69c606521\n# \u2560\u25508de53f65-0d4a-4af0-a890-609ddcc92b36\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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  \u03bb = 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*\u03bb*mapreduce(x->x^2,+,ydiffs) # add the regularizer\n  if !isnothing(G)\n    @. G += \u03bb*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  \u03bb = 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*\u03bb*mapreduce(x->x^2,+,ydiffs)\n  if !isnothing(G)\n    @. G += \u03bb*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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.27\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.27\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u255028860946-21c1-11eb-228d-09798b3886ad\n# \u255f\u250070182cd8-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 \u27e8\u00c2\u27e9 for the displaced oscillator\n\nThe parameters to be given are: \u03c9, \u03bb, g, \u03b3, \u03b1, and a list of sampled times t, plus r and \u03b8 for the squeezed states\n\n\"\n\nexport ann_a, num_a, quad_a, quads_a, nums_a\n\n\"`quad_a(\u03b1, \u03bb, \u03c9, \u03b3, t)` evaluate the position quadrature operator average for the coherent state. \u03b1 \u2208 Complex\"\nquad_a(\u03b1, \u03bb, \u03c9, \u03b3, t) = (\u03b1 + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(1im * \u03c9/\u03b3))) + (conj(\u03b1) + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(-1im * \u03c9/\u03b3))) - 2 * (\u03bb/\u03c9)\n\n\"`num_a(\u03b1, \u03bb, \u03c9, \u03b3, t)` evaluate the number operator average for the coherent state. \u03b1 \u2208 Complex\"\nnum_a(\u03b1, \u03bb, \u03c9, \u03b3, t) = abs2(\u03b1) + (\u03bb/\u03c9) * (\u03b1 + conj(\u03b1)) + 2 * (\u03bb/\u03c9)^2 - (\u03bb/\u03c9) * ((\u03b1 + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(1im * \u03c9/\u03b3))) + (conj(\u03b1) + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(-1im * \u03c9/\u03b3))))\n\n# Squeezed coefficients\n\u03bc(r) = cosh(r)\n\u03bd(r, \u03b8) = exp(1im * \u03b8) * sinh(r)\n\n\"`quads_a(\u03b1, r, \u03b8, \u03bb, \u03c9, \u03b3, t)` evaluate the position quadrature operator average for the squeezed state. \u03b1 \u2208 Complex\"\nquads_a(\u03b1, r, \u03b8, \u03bb, \u03c9, \u03b3, t) = (\u03bc(r) * conj(\u03b1) + conj(\u03bd(r, \u03b8)) * \u03b1 + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(1im * \u03c9/\u03b3))) + (\u03bc(r) * \u03b1 + \u03bd(r, \u03b8) * conj(\u03b1) + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(-1im * \u03c9/\u03b3))) - 2 * (\u03bb/\u03c9)\n\n# Number operator squeezed coefficients\nncf1(r, \u03b8, \u03b1) = (\u03bc(r)^2 + abs2(\u03bd(r, \u03b8))) * abs2(\u03b1)\nncf2(r, \u03b8, \u03b1) = \u03bc(r) * (\u03bd(r, \u03b8) * conj(\u03b1)^2 + conj(\u03bd(r, \u03b8)) * \u03b1^2)\nncf3(r, \u03b8, \u03b1) = (\u03bc(r) - conj(\u03bd(r, \u03b8))) * \u03b1 + (\u03bc(r) - \u03bd(r, \u03b8)) * conj(\u03b1)\nncf4(r, \u03b8, \u03b1) = \u03bc(r) * conj(\u03b1) - conj(\u03bd(r, \u03b8)) * \u03b1\nncf5(r, \u03b8, \u03b1) = \u03bc(r) * \u03b1 - \u03bd(r, \u03b8) * conj(\u03b1)\n\n\"`nums_a(\u03b1, r, \u03b8, \u03bb, \u03c9, \u03b3, t)` evaluate the number operator average for the squeezed state. \u03b1 \u2208 Complex\"\nnums_a(\u03b1, r, \u03b8, \u03bb, \u03c9, \u03b3, t) = (ncf1(r, \u03b8, \u03b1) - ncf2(r, \u03b8, \u03b1) + (\u03bb/\u03c9) * ncf3(r, \u03b8, \u03b1) + 2 * (\u03bb/\u03c9)^2 + abs2(\u03bd(r, \u03b8))) - (\u03bb/\u03c9) * ((ncf4(r, \u03b8, \u03b1) + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(1im * \u03c9/\u03b3))) + (ncf5(r, \u03b8, \u03b1) + (\u03bb/\u03c9)) * exp(-\u03b3 * t * (1 - exp(-1im * \u03c9/\u03b3))))\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    \ud835\udc27 = nrow(data)\n    if \ud835\udc27 > 1\n      # independent variable vector\n      x\u1d62 = data[!, x]\n      # dependent variable vector\n      y\u1d62 = data[!, y]\n      # mean of dependent vector\n      y\u2098 = (1/\ud835\udc27)*sum(y\u1d62)\n      # https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n      m = median([(y\u1d62[i+1]-y\u1d62[i])/(x\u1d62[i+1]-x\u1d62[i]) for i \u2208 1:\ud835\udc27-1])\n      \ud835\udc4f = median([(y\u1d62[i]-m*x\u1d62[i]) for i \u2208 1:\ud835\udc27])\n      # https://en.wikipedia.org/wiki/Coefficient_of_determination\n      # predicted vector\n      f\u1d62 = [(m*x+\ud835\udc4f) for x \u2208 x\u1d62]\n      # residual vector\n      \ud835\uddbe\u1d62 = [(y\u1d62[i]-f\u1d62[i]) for i \u2208 1:\ud835\udc27]\n      SStot = sum([abs2(y\u1d62[i]-y\u2098) for i \u2208 1:\ud835\udc27])\n      SSres = sum([abs2(\ud835\uddbe\u1d62[i]) for i \u2208 1:\ud835\udc27])\n      \ud835\udc11\u00b2 = 1 - (SSres/SStot)\n      return Dict(\"\ud835\udc11\u00b2\" => \ud835\udc11\u00b2, \"m\" => m, \"\ud835\udc4f\" => \ud835\udc4f)\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 MultivariateStats\nusing Base.Test\n\nimport MultivariateStats: qnormalize!\n\nsrand(34568)\n\ndx = 5\ndy = 6\np = 3\n\n# CCA with zero means\n\nX = rand(dx, 100)\nY = rand(dy, 100)\n\nPx = qr(randn(dx, dx))[1][:, 1:p]\nPy = qr(randn(dy, dy))[1][:, 1:p]\n\nM = CCA(Float64[], Float64[], Px, Py, [0.8, 0.6, 0.4])\n\n@test xindim(M) == dx\n@test yindim(M) == dy\n@test xmean(M) == zeros(dx)\n@test ymean(M) == zeros(dy)\n@test xprojection(M) == Px\n@test yprojection(M) == Py\n@test correlations(M) == [0.8, 0.6, 0.4]\n\n@test_approx_eq xtransform(M, X) Px'X\n@test_approx_eq ytransform(M, Y) Py'Y\n\n## CCA with nonzero means\n\nux = randn(dx)\nuy = randn(dy)\n\nM = CCA(ux, uy, Px, Py, [0.8, 0.6, 0.4])\n\n@test xindim(M) == dx\n@test yindim(M) == dy\n@test xmean(M) == ux\n@test ymean(M) == uy\n@test xprojection(M) == Px\n@test yprojection(M) == Py\n@test correlations(M) == [0.8, 0.6, 0.4]\n\n@test_approx_eq xtransform(M, X) Px' * (X .- ux)\n@test_approx_eq ytransform(M, Y) Py' * (Y .- uy)\n\n\n## prepare data\n\nn = 1000\ndg = 10\nG = randn(dg, n)\n\nX = randn(dx, dg) * G + 0.2 * randn(dx, n)\nY = randn(dy, dg) * G + 0.2 * randn(dy, n)\nxm = vec(mean(X, 2))\nym = vec(mean(Y, 2))\nZx = X .- xm\nZy = Y .- ym\n\nCxx = cov(X; vardim=2)\nCyy = cov(Y; vardim=2)\nCxy = cov(X, Y; vardim=2)\nCyx = Cxy'\n\n## ccacov\n\n# X ~ Y\nM = fit(CCA, X, Y; method=:cov, outdim=p)\nPx = xprojection(M)\nPy = yprojection(M)\nrho = correlations(M)\n@test xindim(M) == dx\n@test yindim(M) == dy\n@test outdim(M) == p\n@test xmean(M) == xm\n@test ymean(M) == ym\n@test issorted(rho; rev=true)\n\n@test_approx_eq Px' * Cxx * Px eye(p)\n@test_approx_eq Py' * Cyy * Py eye(p)\n@test_approx_eq Cxy * (Cyy \\ Cyx) * Px scale(Cxx * Px, rho.^2)\n@test_approx_eq Cyx * (Cxx \\ Cxy) * Py scale(Cyy * Py, rho.^2)\n@test_approx_eq Px qnormalize!(Cxx \\ (Cxy * Py), Cxx)\n@test_approx_eq Py qnormalize!(Cyy \\ (Cyx * Px), Cyy)\n\n# Y ~ X\nM = fit(CCA, Y, X; method=:cov, outdim=p)\nPy = xprojection(M)\nPx = yprojection(M)\nrho = correlations(M)\n@test xindim(M) == dy\n@test yindim(M) == dx\n@test outdim(M) == p\n@test xmean(M) == ym\n@test ymean(M) == xm\n@test issorted(rho; rev=true)\n\n@test_approx_eq Px' * Cxx * Px eye(p)\n@test_approx_eq Py' * Cyy * Py eye(p)\n@test_approx_eq Cxy * (Cyy \\ Cyx) * Px scale(Cxx * Px, rho.^2)\n@test_approx_eq Cyx * (Cxx \\ Cxy) * Py scale(Cyy * Py, rho.^2)\n@test_approx_eq Px qnormalize!(Cxx \\ (Cxy * Py), Cxx)\n@test_approx_eq Py qnormalize!(Cyy \\ (Cyx * Px), Cyy)\n\n\n## ccasvd\n\n# n > d\nM = fit(CCA, X, Y; method=:svd, outdim=p)\nPx = xprojection(M)\nPy = yprojection(M)\nrho = correlations(M)\n@test xindim(M) == dx\n@test yindim(M) == dy\n@test outdim(M) == p\n@test xmean(M) == xm\n@test ymean(M) == ym\n@test issorted(rho; rev=true)\n\n@test_approx_eq Px' * Cxx * Px eye(p)\n@test_approx_eq Py' * Cyy * Py eye(p)\n@test_approx_eq Cxy * (Cyy \\ Cyx) * Px scale(Cxx * Px, rho.^2)\n@test_approx_eq Cyx * (Cxx \\ Cxy) * Py scale(Cyy * Py, rho.^2)\n@test_approx_eq Px qnormalize!(Cxx \\ (Cxy * Py), Cxx)\n@test_approx_eq Py qnormalize!(Cyy \\ (Cyx * Px), Cyy)\n\n", "meta": {"hexsha": "ebe6bc73646f1c8c7bd2629a673648481a63a7db", "size": 2952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cca.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": "test/cca.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": "test/cca.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": 22.3636363636, "max_line_length": 62, "alphanum_fraction": 0.6165311653, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7708701525104892}}
{"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    \u03bc = vecPar[1]./(1-vecPar[2])\n    #Y_T = zeros(T)\n    epsilon_T = sigma.* randn(T)\n    Y_T = epsilon_T\n    lagged_val = \u03bc\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": "function OPF(optimizer,set_generators,set_nodes,set_demands,generators,demands,capacity,varcost,load_node,utility_node,links,F_max_dict,B_dict,MapG,MapD)\n\nm=Model(optimizer)\n\n@variable(m, f[link in links] )\n@variable(m, \u03b8[set_nodes])\n@variable(m, p_G[g in set_generators]>= 0)\n@variable(m, p_D[d in set_demands]>= 0)\n#@variable(m, f[link in links] <= F_max_dict[link])\n\n@objective(m, Max, sum(sum(demands[d,utility_node]*p_D[d]  for d in set_demands) -\n                       sum(generators[g,varcost]*p_G[g]  for g in set_generators)))\n\n@constraint(m, constraint1[g in set_generators], p_G[g] <= generators[g,capacity])\n\n@constraint(m, constraint2[d in set_demands],  p_D[d] <= demands[d,load_node])\n\n@constraint(m, constraint3[j in links], f[j] == B_dict[j]*(\u03b8[j[1]]-\u03b8[j[2]]))\n\n@constraint(m, constraint4[j in links], f[j] <= F_max_dict[j])\n\n@constraint(m, constraint5, \u03b8[3] == 0 )\n\n#Analyze shadow prices in Jump/ it is different if supply is on the right hand-side\n@constraint(m, constraint6[n in set_nodes], +sum(p_G[g] for g in set_generators if n == MapG[g][2])\n                                          -sum(p_D[d] for d in set_demands if n == MapD[d][2])\n                                          -sum(f[j] for j in links if n == j[:][1])== 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\np_G_value=zeros(length(set_generators))\nfor g in set_generators\n  p_G_value[g]=JuMP.value.(p_G[g])\nend\nprintln(\"Production level of generator g:\",p_G_value)\n\np_D_value=zeros(length(set_demands))\nfor d in set_demands\n  p_D_value[d]=JuMP.value.(p_D[d])\nend\nprintln(\"Consumption level of demand d:\",p_D_value)\n\nDual_constraint6=zeros(length(set_nodes))\n\nfor n in set_nodes\n   Dual_constraint6[n]= JuMP.dual(constraint6[n])\nend\nprintln(\"Electricity Price:\", Dual_constraint6)\n\nfor j in links\nprintln(\"Power Flow line $j:\", JuMP.value.(f[j]))\nend\n\nf_value=zeros(n_link)\nglobal i=1\nfor j in links\nglobal f_value[i]= JuMP.value.(f[j])\nglobal i=1+i\nend\n\nreturn (syscost_det,p_G_value,p_D_value,Dual_constraint6,f_value)\nend\n\n#cd(\"C:\\\\Users\\\\braya\\\\.julia\\\\dev\\\\DTU_BrayamValqui_SP2021\\\\src\")\n#include(\"OPF.jl\")\n", "meta": {"hexsha": "7e483856d1638f0c116aeafb55f6bf812205f6ec", "size": 2221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OPF.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.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.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": 30.4246575342, "max_line_length": 153, "alphanum_fraction": 0.6951823503, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7708701463032941}}
{"text": "using  Test\nusing SimplePosets, SimplePosetAlgorithms\n\nP = BooleanLattice(5)\nC = max_chain(P)\n@test length(C) == 6\n@test height(P) == 6\n\nA = max_antichain(P)\n@test length(A) == 10\n@test width(P) == 10\n\nR = realizer(P,5)\nQ = realize_poset(R)\n@test P==Q\n\nP = StandardExample(4)\n@test dimension(P) == 4\n", "meta": {"hexsha": "7d5ed53345f37b909c452c536fab50bdc4d2dc6a", "size": 300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimplePosetAlgorithms.jl-0c1320c5-0940-5dc6-8c7d-d9650cdddf58", "max_stars_repo_head_hexsha": "6e74b1b273f717ba6b4a1051273c7dab3c3db7d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-08-13T08:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T20:43:16.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimplePosetAlgorithms.jl-0c1320c5-0940-5dc6-8c7d-d9650cdddf58", "max_issues_repo_head_hexsha": "6e74b1b273f717ba6b4a1051273c7dab3c3db7d2", "max_issues_repo_licenses": ["MIT"], "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": "UnofficialJuliaMirrorSnapshots/SimplePosetAlgorithms.jl-0c1320c5-0940-5dc6-8c7d-d9650cdddf58", "max_forks_repo_head_hexsha": "6e74b1b273f717ba6b4a1051273c7dab3c3db7d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:18.000Z", "avg_line_length": 15.7894736842, "max_line_length": 41, "alphanum_fraction": 0.6733333333, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.770870142760958}}
{"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 \u03be(k)\n    return x ->  [\u221a2*sin(\u03c0*k*x[1]), 0.]\nend\n\nfunction \u03bex(k)\n    return x -> \u221a2\u03c0*k*cos(\u03c0*k*x[1]) \nend\n\nfunction D\u03be(k)\n    return x -> [[\u221a2\u03c0*k*cos(\u03c0*k*x[1]) 0.]; [0. 0.]]\nend\n\n\n\n\"\"\"\nTYPE 2 Basis Function: Sines*Cosines\n\"\"\"\nfunction \u03b7(k, l)\n    return x -> [2*sin(\u03c0*k*x[1])*cos(2\u03c0*l*x[2]), 0.]\nend\n\nfunction \u03b7x(k, l)\n    return x -> 2\u03c0*k*cos(\u03c0*k*x[1])*cos(2\u03c0*l*x[2])\nend\n\nfunction D\u03b7(k, l)\n    return x -> [[2\u03c0*k*cos(\u03c0*k*x[1])*cos(2\u03c0*l*x[2]) -4\u03c0*l*sin(\u03c0*k*x[1])*sin(2\u03c0*l*x[2])]; [0. 0.]]\nend\n\n\"\"\"\nTYPE 3 Basis Function: Sines*Sines\n\"\"\"\nfunction \u03c6(k, l)\n    return x -> [2*sin(\u03c0*k*x[1])*sin(2\u03c0*l*x[2]), 0.]\nend\n\nfunction \u03c6x(k, l)\n    return x -> 2\u03c0*k*cos(\u03c0*k*x[1])*sin(2\u03c0*l*x[2])\nend\n\nfunction D\u03c6(k, l)\n    return x -> [[2\u03c0*k*cos(\u03c0*k*x[1])*sin(2\u03c0*l*x[2]) 4\u03c0*l*sin(\u03c0*k*x[1])*cos(2\u03c0*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 _\u03be(l)\n    return x ->  [0., \u221a2*sin(\u03c0*l*x[2])]\nend\n\nfunction _\u03bey(l)\n    return x -> \u221a2\u03c0*l*cos(\u03c0*l*x[2]) \nend\n\nfunction _D\u03be(l)\n    return x -> [[0. 0.]; [0. \u221a2\u03c0*l*cos(\u03c0*l*x[2])]]\nend\n\n\n\"\"\"\nTYPE 2 Basis Function: Sines*Cosines\n\"\"\"\nfunction _\u03b7(l, k)\n    return x -> [0., 2*sin(\u03c0*l*x[2])*cos(2\u03c0*k*x[1])]\nend\n\nfunction _\u03b7y(l, k)\n    return x -> 2\u03c0*l*cos(\u03c0*l*x[2])*cos(2\u03c0*k*x[1])\nend\n\nfunction _D\u03b7(l, k)\n    return x -> [[0. 0.]; [-4\u03c0*k*sin(\u03c0*l*x[2])*sin(2\u03c0*k*x[1]) 2\u03c0*l*cos(\u03c0*l*x[2])*cos(2\u03c0*k*x[1])]]\nend\n\n\n\"\"\"\nTYPE 2 Basis Function: Sines*Sines\n\"\"\"\nfunction _\u03c6(l, k)\n    return x -> [0., 2*sin(\u03c0*l*x[2])*sin(2\u03c0*k*x[1])]\nend\n\nfunction _\u03c6y(l, k)\n    return x -> 2\u03c0*l*cos(\u03c0*l*x[2])*sin(2\u03c0*k*x[1])\nend\n\nfunction _D\u03c6(l, k)\n    return x -> [[0. 0.]; [4\u03c0*k*sin(\u03c0*l*x[2])*cos(2\u03c0*k*x[1]) 2\u03c0*l*cos(\u03c0*l*x[2])*sin(2\u03c0*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] = \u03be(k)\n        B[N + i] = _\u03be(k)\n        \n        # Jacobian Matrices\n        DB[i] = D\u03be(k)\n        DB[N + i] = _D\u03be(k)\n\n        # Divergence \n        divB[i] = \u03bex(k)\n        divB[N + i] = _\u03bey(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) \u00f7 K) + 1\n        l = j - K * ((j-1) \u00f7 K)\n        \n        # Basis Functions\n        B[i] = \u03b7(k, l)\n        B[N + i] = _\u03b7(k, l)\n        \n        # Jacobian Matrices\n        DB[i] = D\u03b7(k, l)\n        DB[N + i] = _D\u03b7(k, l)\n\n        # Divergence \n        divB[i] = \u03b7x(k, l)\n        divB[N + i] = _\u03b7y(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) \u00f7 K) + 1\n        l = j - K * ((j-1) \u00f7 K)\n        \n\n        # Basis Functions\n        B[i] = \u03c6(k, l)\n        B[N + i] = _\u03c6(k, l)\n        \n        # Jacobian Matrices\n        DB[i] = D\u03c6(k, l)\n        DB[N + i] = _D\u03c6(k, l)\n\n        # Divergence \n        divB[i] = \u03c6x(k, l)\n        divB[N + i] = _\u03c6y(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*\u03c0/180\n\n# adapted from Distances.jl\n@inline function haversine(\u03bb\u2081, \u03c6\u2081, \u03bb\u2082, \u03c6\u2082)\n    \u0394\u03bb = \u03bb\u2082 - \u03bb\u2081  # longitudes\n    \u0394\u03c6 = \u03c6\u2082 - \u03c6\u2081  # latitudes\n\n    # haversine formula\n    a = sin(\u0394\u03c6/2)^2 + cos(\u03c6\u2081)*cos(\u03c6\u2082)*sin(\u0394\u03bb/2)^2\n    \n    # # distance on the sphere\n    2 * 6_371_000 * asin( min(\u221aa, 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 \u2208 axes(dist, 1), j \u2208 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 \u2208 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\u00b2 + 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\u00b2 + 41 + 41 is clearly divisible by 41.\n\nThe incredible formula  n\u00b2 \u2212 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, \u221279 and 1601, is \u2212126479.\n\nConsidering quadratics of the form:\n\nn\u00b2 + an + b, where |a| < 1000 and |b| < 1000\n\nwhere |n| is the modulus/absolute value of n\ne.g. |11| = 11 and |\u22124| = 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\u00b3 + b*x\u00b2 + 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\u00b2 + 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 - \u221a(D)) / 2a, (-b + \u221a(D)) / 2a]\n    elseif D < zero(typeof(D))\n        return [(-b - \u221a(-D)*im) / 2a, (-b + \u221a(-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 \u2208 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": "using LinearAlgebra, SimpleDifferentialOperators, DiffEqOperators, Test, Parameters\n\n#parameters\nparams = @with_kw (\n    \u03bc = -0.1, # constant negative drift\n    \u03c3 = 0.1,\n    \u03c1 = 0.05,\n    M = 3, # size of grid (interior points)\n    x\u0304 = range(0.0, 1.0, length = (M+2)),\n    x = interiornodes(x\u0304), # i.e., x\u0304[2:end-1]\n    S = 3.0\n)\np = params();\n\n#----------------------------------\n#Testing For Negative Drifts\n#----------------------------------\n# payoff function\n\u03c0(x) = x^2\n# SimpleDifferentialOperators setup\nfunction SDO_negative_drift(\u03c0, params)\n    bc = (Reflecting(), Reflecting())\n    L\u2093 = params.\u03bc*L\u2081\u208bbc(params.x\u0304, bc) + params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304, bc)\n    L_bc = I * params.\u03c1 - L\u2093\n    v = L_bc \\ \u03c0.(params.x);\n    return (v = v, L_bc = L_bc, L\u2093 = L\u2093, L\u2081\u208bbc = L\u2081\u208bbc(params.x\u0304, bc), L\u2082bc = L\u2082bc(params.x\u0304, bc))\nend\n# DiffEqOperators Setup\nfunction DEO_negative_drift(\u03c0, params)\n    dx = params.x[2] - params.x[1]\n    # discretize L = \u03c1 - \u03bc D_x - \u03c3^2 / 2 D_xx\n    # subject to reflecting barriers at 0 and 1\n    L1 = UpwindDifference(1,1,dx,params.M,1.)\n    L2 = CenteredDifference(2,2,dx,params.M)\n    Q = Neumann0BC(dx, 1)\n    L\u2081\u208bbc = -1. .* Array(UpwindDifference(1,1,dx,params.M,-1.) * Q)[1]\n    # Here Array(A::GhostDerivativeOperator) will return a tuple of the linear part\n    # and the affine part of the operator A, hence we index Array(\u00b5*L1*Q).\n    # The operators in this example are purely linear, so we don't worry about Array(\u00b5*L1*Q)[2]\n    L\u2093 = Array(params.\u03bc*L1*Q)[1] + Array(params.\u03c3^2/2*L2*Q)[1] # when scalar coefficient is properly implemented\n    # L\u2093 = Array(L1*Q)[1] + Array(params.\u03c3^2/2*L2*Q)[1] # when scalar coefficient is properly implemented\n    L_bc = I * params.\u03c1 - L\u2093\n\n    # solve the value function\n    v = L_bc \\ \u03c0.(params.x);\n    return (v = v, L_bc = L_bc, L\u2093 = L\u2093, L\u2081\u208bbc = L\u2081\u208bbc, L\u2082bc = Array(L2*Q)[1] )\nend\n@testset \"Constant Negative Drifts\" begin\n    @test DEO_negative_drift(\u03c0, p).v \u2248 SDO_negative_drift(\u03c0, p).v\n    @test DEO_negative_drift(\u03c0, p).L_bc \u2248 SDO_negative_drift(\u03c0, p).L_bc\n    @test DEO_negative_drift(\u03c0, p).L\u2093 \u2248 SDO_negative_drift(\u03c0, p).L\u2093\n    @test DEO_negative_drift(\u03c0, p).L\u2081\u208bbc \u2248 SDO_negative_drift(\u03c0, p).L\u2081\u208bbc\n    @test DEO_negative_drift(\u03c0, p).L\u2082bc \u2248 SDO_negative_drift(\u03c0, p).L\u2082bc\nend\np = params(\u03bc = 0.1);\n#----------------------------------\n#Testing For Positive Drifts\n#----------------------------------\n# SimpleDifferentialOperators setup\nfunction SDO_positive_drift(\u03c0, params)\n    bc = (Reflecting(), Reflecting())\n    L\u2093 = params.\u03bc*L\u2081\u208abc(params.x\u0304, bc) + params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304, bc)\n    L_bc = I * params.\u03c1 - L\u2093\n    v = L_bc \\ \u03c0.(params.x);\n    return (v = v, L_bc = L_bc, L\u2093 = L\u2093, L\u2081\u208abc = L\u2081\u208abc(params.x\u0304, bc), L\u2082bc = L\u2082bc(params.x\u0304, bc))\nend\n# DiffEqOperators Setup\nfunction DEO_positive_drift(\u03c0, params)\n    dx = params.x[2] - params.x[1]\n    # discretize L = \u03c1 - \u03bc D_x - \u03c3^2 / 2 D_xx\n    # subject to reflecting barriers at 0 and 1\n    L1 = UpwindDifference(1,1,dx,params.M,1.0)\n    L2 = CenteredDifference(2,2,dx,params.M)\n    Q = Neumann0BC(dx, 1)\n    # Here Array(A::GhostDerivativeOperator) will return a tuple of the linear part\n    # and the affine part of the operator A, hence we index Array(\u00b5*L1*Q).\n    # The operators in this example are purely linear, so we don't worry about Array(\u00b5*L1*Q)[2]\n    L\u2093 = Array(params.\u00b5*L1*Q)[1] + Array(params.\u03c3^2/2*L2*Q)[1]\n    L_bc = I * params.\u03c1 - L\u2093\n\n    # solve the value function\n    v = L_bc \\ \u03c0.(params.x);\n    return (v = v, L_bc = L_bc, L\u2093 = L\u2093, L\u2081\u208abc = Array(L1*Q)[1], L\u2082bc = Array(L2*Q)[1] )\nend\n\n@testset \"Constant Positive Drifts\" begin\n    @test DEO_positive_drift(\u03c0, p).v \u2248 SDO_positive_drift(\u03c0, p).v\n    @test DEO_positive_drift(\u03c0, p).L_bc \u2248 SDO_positive_drift(\u03c0, p).L_bc\n    @test DEO_positive_drift(\u03c0, p).L\u2093 \u2248 SDO_positive_drift(\u03c0, p).L\u2093\n    @test DEO_positive_drift(\u03c0, p).L\u2081\u208abc \u2248 SDO_positive_drift(\u03c0, p).L\u2081\u208abc\n    @test DEO_positive_drift(\u03c0, p).L\u2082bc \u2248 SDO_positive_drift(\u03c0, p).L\u2082bc\nend\n\n\n#----------------------------------\n#Testing For State Dependent Drifts\n#----------------------------------\n\u03bc(x) = -x\n# SimpleDifferentialOperators setup\nfunction SDO_state_dependent_drift(\u03c0, \u03bc, params)\n    bc = (Reflecting(), Reflecting())\n    L\u2081 = Diagonal(min.(\u03bc.(params.x), 0.0)) * L\u2081\u208bbc(params.x\u0304, bc) + Diagonal(max.(\u03bc.(params.x), 0.0)) * L\u2081\u208abc(params.x\u0304, bc)\n    L\u2093 = L\u2081 - params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304, bc)\n    L_bc = I * params.\u03c1 - L\u2093\n    v = L_bc \\ \u03c0.(params.x)\n    return (v = v, L_bc = L_bc,  L\u2093 = L\u2093, L\u2081 = L\u2081, L\u2082bc = L\u2082bc(params.x\u0304, bc))\nend\n# DiffEqOperators Setup\nfunction DEO_state_dependent_drift(\u03c0, \u03bc, params)\n    dx = params.x[2] - params.x[1]\n    # discretize L = \u03c1 - \u03bc D_x - \u03c3^2 / 2 D_xx\n    # subject to reflecting barriers at 0 and 1\n    drift = \u03bc.(params.x)\n    L1 = UpwindDifference(1,1,dx,params.M,drift)\n    L2 = CenteredDifference(2,2,dx,params.M)\n    Q = Neumann0BC(dx, 1)\n    # Here Array(A::GhostDerivativeOperator) will return a tuple of the linear part\n    # and the affine part of the operator A, hence we index Array(\u00b5*L1*Q).\n    # The operators in this example are purely linear, so we don't worry about Array(\u00b5*L1*Q)[2]\n    L\u2081 = Array(L1*Q)[1]\n    L\u2093 = L\u2081 - Array(params.\u03c3^2/2*L2*Q)[1]\n    L_bc = I * params.\u03c1 - L\u2093\n\n    # solve the value function\n    v = L_bc \\ \u03c0.(params.x);\n    return (v = v, L_bc = L_bc, L\u2093 = L\u2093, L\u2081 = L\u2081, L\u2082bc = Array(L2*Q)[1] )\nend\n\n@testset \"State Dependent Drifts\" begin\n    @test DEO_state_dependent_drift(\u03c0, \u03bc, p).v \u2248 SDO_state_dependent_drift(\u03c0, \u03bc, p).v\n    @test DEO_state_dependent_drift(\u03c0, \u03bc, p).L_bc \u2248 SDO_state_dependent_drift(\u03c0, \u03bc, p).L_bc\n    @test DEO_state_dependent_drift(\u03c0, \u03bc, p).L\u2093 \u2248 SDO_state_dependent_drift(\u03c0, \u03bc, p).L\u2093\n    @test DEO_state_dependent_drift(\u03c0, \u03bc, p).L\u2081 \u2248 SDO_state_dependent_drift(\u03c0, \u03bc, p).L\u2081\n    @test DEO_state_dependent_drift(\u03c0, \u03bc, p).L\u2082bc \u2248 SDO_state_dependent_drift(\u03c0, \u03bc, p).L\u2082bc\nend\n\n\n\n#----------------------------------\n#Testing For Absorbing BC\n#----------------------------------\n\n\n# payoff function\n\u03c0(x) = x^2\n# SimpleDifferentialOperators setup\nfunction SDO_absorbing_bc(\u03c0, params)\n    bc = (NonhomogeneousAbsorbing(params.S), Reflecting())\n    L\u2093bc = params.\u03bc*L\u2081\u208bbc(params.x\u0304, bc) + params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304 , bc)\n    L_bc = I * params.\u03c1 - L\u2093bc\n\n    # construct the RHS with affine boundary\n    \u03c0_star = \u03c0.(params.x) + L\u2080affine(params.x\u0304, \u03c0.(params.x), bc)\n\n    # solve the value function\n    v = L_bc \\ \u03c0_star\n\n    return (v = v, L_bc = L_bc, L\u2093bc = L\u2093bc, L\u2081\u208bbc = L\u2081\u208bbc(params.x\u0304, bc), L\u2082bc = L\u2082bc(params.x\u0304, bc),\n        \u03c0_star = \u03c0_star, \u03c0 = \u03c0.(params.x))\nend\n\n\n# DiffEqOperators Setup\nfunction DEO_absorbing_bc(\u03c0, params)\n    dx = params.x[2] - params.x[1]\n\n    L1 = UpwindDifference(1,1,dx,params.M,params.\u03bc)\n    L2 = CenteredDifference(2,2,dx,params.M)\n    # RobinBC(l::NTuple{3,T}, r::NTuple{3,T}, dx::T, order = 1)\n    # The variables in l are [\u03b1l, \u03b2l, \u03b3l], and correspond to a BC of the form \u03b1l*u(0) + \u03b2l*u'(0) = \u03b3l\n    # imposed on the lower index boundary. The variables in r are [\u03b1r, \u03b2r, \u03b3r],\n    # and correspond to an analagous boundary on the higher index end.\n    l = (1.0, 0.0, p.S)\n    r = (0.0, 1.0, 0.0)\n    Q = RobinBC(l, r, dx, 1)\n\n    L\u2093bc = Array(L1*Q)[1] + Array(params.\u03c3^2/2*L2*Q)[1]\n    L_bc = I * params.\u03c1 - L\u2093bc\n\n    # solve the value function\n    v = L_bc \\ \u03c0.(params.x)\n    return (v = v, L_bc = L_bc, L\u2093bc = L\u2093bc, L\u2081\u208bbc = Array(L1*Q)[1] ./ params.\u03bc, L\u2082bc = Array(L2*Q)[1],\n        \u03c0_star = \u03c0.(params.x), \u03c0 = \u03c0.(params.x))\nend\n\np = params(x\u0304 = range(0.0, 1.0, length = (p.M+2)))\n\n@testset \"Absorbing BC\" begin\n    @test DEO_absorbing_bc(\u03c0, p).v \u2248 SDO_absorbing_bc(\u03c0, p).v\n    @test DEO_absorbing_bc(\u03c0, p).L_bc \u2248 SDO_absorbing_bc(\u03c0, p).L_bc\n    @test DEO_absorbing_bc(\u03c0, p).L\u2093bc \u2248 SDO_absorbing_bc(\u03c0, p).L\u2093bc\n    @test DEO_absorbing_bc(\u03c0, p).L\u2081\u208bbc \u2248 SDO_absorbing_bc(\u03c0, p).L\u2081\u208bbc\n    @test DEO_absorbing_bc(\u03c0, p).L\u2082bc \u2248 SDO_absorbing_bc(\u03c0, p).L\u2082bc\n    @test DEO_absorbing_bc(\u03c0, p).\u03c0_star \u2248 SDO_absorbing_bc(\u03c0, p).\u03c0_star\n    @test DEO_absorbing_bc(\u03c0, p).\u03c0 \u2248 SDO_absorbing_bc(\u03c0, p).\u03c0\nend\n\n\n\n#----------------------------------\n#Testing For Solving KFE\n#----------------------------------\n\n\nfunction SDO_Solve_KFE(params)\n    # \u03be values for mixed boundary conditions\n    \u03be_lb = \u03be_ub = -2 * params.\u03bc / params.\u03c3^2\n    # define the corresponding mixed boundary conditions\n    # note that the direction on the lower bound is backward (default is forward)\n    # as the drift \u03bc is negative.\n    bc = (Mixed(\u03be = \u03be_lb, direction = :backward), Mixed(\u03be = \u03be_ub))\n\n    # use SimpleDifferentialOperators.jl to construct the operator on the interior\n    L_KFE_with_drift = Array(-params.\u03bc*L\u2081\u208abc(params.x\u0304, bc) + params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304, bc))\n    L_KFE_without = params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304, bc)\n    return (L_KFE_with_drift = L_KFE_with_drift, L_KFE_without = L_KFE_without)\nend\n\nfunction SDO_Solve_KFE_forward(params)\n    # \u03be values for mixed boundary conditions\n    \u03be_lb = \u03be_ub = -2 * params.\u03bc / params.\u03c3^2\n    # define the corresponding mixed boundary conditions\n    # but with forward finite difference derivatives at boundaries\n    bc = (Mixed(\u03be = \u03be_lb, direction = :forward), Mixed(\u03be = \u03be_ub))\n\n    # use SimpleDifferentialOperators.jl to construct the operator on the interior\n    L_KFE_with_drift = Array(-params.\u03bc*L\u2081\u208abc(params.x\u0304, bc) + params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304, bc))\n    L_KFE_without = params.\u03c3^2 / 2 * L\u2082bc(params.x\u0304, bc)\n    return (L_KFE_with_drift = L_KFE_with_drift, L_KFE_without = L_KFE_without)\nend\n\n\nfunction DEO_Solve_KFE(params)\n    dx = params.x[2] - params.x[1]\n\n    L1 = UpwindDifference(1,1,dx,params.M,-params.\u03bc)\n    # L2l = UpwindDifference(2,2,dx,params.M,\n    #                          vcat(-1.,zeros(params.M-1)))\n    # L2r = UpwindDifference(2,2,dx,params.M,\n    #                          vcat(zeros(params.M-1),1.))\n    L2 = CenteredDifference(2,2,dx,params.M)\n\n    \u03be_lb = \u03be_ub = -2 * params.\u03bc / params.\u03c3^2\n\n    l = (\u03be_lb, 1., 0.)\n    r = (\u03be_ub, 1., 0.)\n    Q = RobinBC(l, r, dx, 1)\n\n    # use SimpleDifferentialOperators.jl to construct the operator on the interior\n    # Only difference is handling of L2, we may need to upwind for boundary\n    L_KFE_with_drift = Array(L1*Q)[1] + Array(params.\u03c3^2/2 *L2*Q)[1]\n    L_KFE_without = (params.\u03c3^2 / 2) .* Array(L2 * Q)[1]\n    # L_KFE_without = (params.\u03c3^2 / 2) .* ([0., 1., 0.] .* Array(L2 * Q)[1] +\n    #     -(Array(L2l * Q)) + Array(L2r * Q))\n\n    return (L_KFE_with_drift = L_KFE_with_drift, L_KFE_without = L_KFE_without)\nend\n\n\np = params(x\u0304 = range(0.0, 1.0, length = (p.M+2)))\n@testset \"Solving KFE\" begin\n    @test_broken DEO_Solve_KFE(p).L_KFE_with_drift \u2248 SDO_Solve_KFE(p).L_KFE_with_drift # concretization of Robin conditions appears broken\n    @test_broken DEO_Solve_KFE(p).L_KFE_without \u2248 SDO_Solve_KFE(p).L_KFE_without # Hard to check what's wrong since KFE uses forward/backward at boundaries rather than central differences when w/mixed bcs\n    @test DEO_Solve_KFE(p).L_KFE_with_drift \u2248 SDO_Solve_KFE_forward(p).L_KFE_with_drift\n    @test DEO_Solve_KFE(p).L_KFE_without \u2248 SDO_Solve_KFE_forward(p).L_KFE_without\nend\n\nnothing\n", "meta": {"hexsha": "76af883c3efd572c635d4e80ece1c7f020d27484", "size": 11006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/BasicSDOExamples.jl", "max_stars_repo_name": "scheidan/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "bb78889283f64882aef77f89c83a145d533976ee", "max_stars_repo_licenses": ["MIT"], "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/BasicSDOExamples.jl", "max_issues_repo_name": "scheidan/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "bb78889283f64882aef77f89c83a145d533976ee", "max_issues_repo_licenses": ["MIT"], "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/BasicSDOExamples.jl", "max_forks_repo_name": "scheidan/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "bb78889283f64882aef77f89c83a145d533976ee", "max_forks_repo_licenses": ["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.9144981413, "max_line_length": 204, "alphanum_fraction": 0.6337452299, "num_tokens": 4094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7708055806327423}}
{"text": "# an example on mixed integer programming\n#\n#   maximize x + 2 y + 5 z\n#\n#   s.t.  x + y + z <= 10\n#         x + 2 y + z <= 15\n#\n#         x is continuous: 0 <= x <= 5\n#         y is integer: 0 <= y <= 10\n#         z is binary\n#\n# z = 1, y= 7, x = 0\nusing Xpress, Compat.Test\nusing Compat.SparseArrays\n\n@testset \"MIP 4\" begin\n\n    model = Xpress.Model( \"mip_01\", :maximize)\n\n    add_cvar!(model, 1., 0., 5.)  # x\n    add_ivar!(model, 2., 0, 10)   # y\n    add_bvar!(model, 5.)          # z\n\n    add_constr!(model, ones(3), '<', 10.)\n    add_constr!(model, [1., 2., 1.], '<', 15.)\n\n    @test Xpress.get_obj(model) == [1, 2, 5]\n    @test Xpress.get_constrmatrix(model) == sparse([1. 1. 1.; 1. 2. 1.])\n    @test Xpress.get_rhs(model) == [10, 15]\n    @test Xpress.get_lb(model) == [0, 0, 0]\n    @test Xpress.get_ub(model) == [5, 10, 1]\n    @test Xpress.get_sense(model) == [:<=,:<=]\n\n    optimize(model)\n\n    ans = get_optiminfo(model)\n    @test ans.status_mip == :mip_optimal\n\n    @test isapprox(get_solution(model), [0, 7, 1]; atol = 1e-3)\n\n    @test isapprox(get_objval(model), 19; atol = 1e-3)\nend", "meta": {"hexsha": "8a95accf684ed59233b917b0c843db5d8c088ae0", "size": 1096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mip_01.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Xpress.jl-9e70acf3-d6c9-5be6-b5bd-4e2c73e3e054", "max_stars_repo_head_hexsha": "162f714998af86e8fd76d96b5008ebd7fb79d6d5", "max_stars_repo_licenses": ["MIT"], "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/mip_01.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Xpress.jl-9e70acf3-d6c9-5be6-b5bd-4e2c73e3e054", "max_issues_repo_head_hexsha": "162f714998af86e8fd76d96b5008ebd7fb79d6d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-29T04:14:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T05:04:47.000Z", "max_forks_repo_path": "test/mip_01.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Xpress.jl-9e70acf3-d6c9-5be6-b5bd-4e2c73e3e054", "max_forks_repo_head_hexsha": "162f714998af86e8fd76d96b5008ebd7fb79d6d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:29:00.000Z", "avg_line_length": 26.0952380952, "max_line_length": 72, "alphanum_fraction": 0.5419708029, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7708055800909976}}
{"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}, \u03f5::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, \u2207f, \u03be = Voronoi.Optimization.init(points, WIDTH, HEIGHT)\n   evaluations = 1\n   push!(results, (f, \u03be, evaluations, times))\n\n   while \u03be > \u03f5\n      time = @elapsed V, f, \u03be = Voronoi.Optimization.lloydIteration(points, V)\n\n      evaluations += 1\n      times += time\n\n      push!(results, (f, \u03be, evaluations, times))\n   end\n\n   return results\nend\n\nfunction benchmarkGradient(Z::Array{Tuple{Real, Real}, 1}, \u03f5::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, \u2207f, \u03be = Voronoi.Optimization.init(points, WIDTH, HEIGHT)\n   evaluations = 1\n   push!(results, (f, \u03be, evaluations, times))\n   \u03bc = 0.5\n   \u03b1 = 0.01\n   \u03bb\u2080 = 0.01\n\n   while \u03be > \u03f5\n      d = \u2207f\n\n      time = @elapsed V, f, \u2207f, \u03be, evals = Voronoi.Optimization.lineSearch(points, d, \u03b1, \u03bb\u2080, \u03bc, \u03f5, V, f, \u2207f, \u03be)\n\n      evaluations += evals\n      times += time\n\n      push!(results, (f, \u03be, evaluations, times))\n   end\n\n   return results\nend\n\nfunction benchmark(n, \u03f5)\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, \u03f5)\n   gradient_results = benchmarkGradient(points, \u03f5)\n\n   lloyd_f = Array{Number}([])\n   lloyd_\u03be = Array{Number}([])\n   lloyd_evals = Array{Number}([])\n   lloyd_time = Array{Number}([])\n   gradient_f = Array{Number}([])\n   gradient_\u03be = Array{Number}([])\n   gradient_evals = Array{Number}([])\n   gradient_time = Array{Number}([])\n\n   i = 1\n   t\u2080 = lloyd_results[1][4]\n   for (f\u1d62, \u03be\u1d62, evals\u1d62, time\u1d62) in lloyd_results\n      push!(lloyd_f, f\u1d62)\n      push!(lloyd_\u03be, \u03be\u1d62)\n      push!(lloyd_evals, evals\u1d62)\n      push!(lloyd_time, time\u1d62 - t\u2080)\n      i += 1\n   end\n\n   i = 1\n   t\u2080 = gradient_results[1][4]\n   for (f\u1d62, \u03be\u1d62, evals\u1d62, time\u1d62) in gradient_results\n      push!(gradient_f, f\u1d62)\n      push!(gradient_\u03be, \u03be\u1d62)\n      push!(gradient_evals, evals\u1d62)\n      push!(gradient_time, time\u1d62 - t\u2080)\n      i += 1\n   end\n\n   #@printf(\"f = %.10g\\t\\t|\u2207f| = %.10g\\t\\ttime: %s seconds\\n\", f, \u03be, time)\n   #@printf(\"f = %.10g\\t\\t|\u2207f| = %.10g\\t\\ttime: %s seconds\\n\", f, \u03be, 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\u00e9todo do Gradiente\", \":\")\n   Draw.legend(\"Tempo (s)\", \"Valor da Fun\u00e7\u00e3o 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_\u03be, \"xkcd:azure\", \"Algoritmo de Lloyd\", \"-\")\n   Draw.plot(gradient_time, gradient_\u03be, \"xkcd:tomato\", \"M\u00e9todo 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\u03f5 = 10^-2\nbenchmark(3, \u03f5)\nbenchmark(30, \u03f5)\nbenchmark(100, \u03f5)\nbenchmark(300, \u03f5)\nbenchmark(1000, \u03f5)\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) -> [\u03b8, \u03d5]\n    c2s(xyz::AbstractVector) -> [\u03b8, \u03d5]\n    c2s(xyz::AbstractMatrix) -> [\u03b8s; \u03d5s]\n\nConvert Cartesian vector `[x, y, z]` (or `xyz`) to spherical unit vector `[\u03b8,\n\u03d5]`.  For AbstractMatrix `xyz`, each column is converted and the results are\nreassmebled into a Matrix using `hcat`.\n\"\"\"\nfunction c2s(x,y,z)\n    \u03b8=atan(y,x)\n    \u03d5=atan(z, hypot(x,y))\n    [\u03b8, \u03d5]\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(\u03b8, \u03d5) -> [x, y, z)\n    s2c(\u03b8\u03d5::AbstractVector) -> [x, y, z]\n    s2c(\u03b8\u03d5::AbstractMaxtrix) -> [xs; ys; zs]\n\nConvert spherical unit vector `[\u03b8, \u03d5]` (or `\u03b8\u03d5`) to Cartesian unit vector `[x,\ny, z]`.  For AbstractMatrix `\u03b8\u03d5`, each column is converted and the results are\nreassmebled into a Matrix using `hcat`.\n\"\"\"\nfunction s2c(\u03b8,\u03d5)\n    z, r = sincos(\u03d5)\n    y, x = sincos(\u03b8) .* r\n    [x, y, z]\nend\n\nfunction s2c(\u03b8\u03d5::AbstractVector{<:Real})\n    s2c(\u03b8\u03d5[1], \u03b8\u03d5[2])\nend\n\nfunction s2c(\u03b8\u03d5::AbstractMatrix{<:Real})\n    @views reduce(hcat, s2c.(\u03b8\u03d5[1,:], \u03b8\u03d5[2,:]))\nend\n\n\"\"\"\n    beamrings(\u03b8, \u03d5; nrings=4, d\u03d5=deg2rad(10/3600)) -> Matrix\n\nCompute the centers of beams that are arranged in concentric rings around the\nspherical coordinates `(\u03b8, \u03d5)`, both in radians with `\u03b8` being the longitudinal\ncoordinate and `\u03d5` 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\u03d5` 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 `(\u03b8, \u03d5)` 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 `\u03b8_beam` coordinates and the second row\ncontains the `\u03d5_beam` coordinates.\n\"\"\"\nfunction beamrings(\u03b8, \u03d5; nrings=4, d\u03d5=deg2rad(10/3600))\n    nbeams = 6 * sum(1:nrings) + 1\n    \u03b8s = Vector{Float64}(undef, nbeams)\n    \u03d5s = Vector{Float64}(undef, nbeams)\n    \u03b8s[1] = 0.0\n    \u03d5s[1] = \u03c0/2\n    b=2\n    for r in 1:nrings\n        n\u03b8 = 6r\n        d\u03b8 = 2\u03c0/n\u03b8\n        \u03d5r = \u03c0/2 - r * d\u03d5\n        for i in 0:n\u03b8-1\n            \u03b8s[b] = i*d\u03b8\n            \u03d5s[b] = \u03d5r\n            b += 1\n        end\n    end\n    reduce(hcat, c2s.(Ref(RotZY(\u03b8, \u03c0/2-\u03d5)) .* s2c.(\u03b8s, \u03d5s)))\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)) \u2192 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 \u03a8(j) - \\\\log N\n```\nwhere `` \\\\Psi(j) = \\\\frac{\\\\text{d} \\\\log \u0393(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": "@test factorial(7) == 5040\n@test factorial(7,3) == 7*6*5*4\n@test binomial(5,3) == 10\np = shuffle([1:1000])\n@test isperm(p)\n@test all(invperm(invperm(p)) .== p)\npush!(p, 1)\n@test !isperm(p)\na = randcycle(10)\n@test ipermute!(permute!([1:10], a),a) == [1:10]\n@test collect(combinations(\"abc\",2)) == [\"ab\",\"ac\",\"bc\"]\n@test collect(permutations(\"abc\")) == [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]\n@test collect(filter(x->(iseven(x[1])),permutations([1,2,3]))) == {[2,1,3],[2,3,1]}\n@test collect(filter(x->(iseven(x[3])),permutations([1,2,3]))) == {[1,3,2],[3,1,2]}\n@test collect(filter(x->(iseven(x[1])),combinations([1,2,3],2))) == {[2,3]}\n@test collect(partitions(4)) ==  {[4], [3,1], [2,2], [2,1,1], [1,1,1,1]}\n@test collect(partitions(8,3)) == {[6,1,1], [5,2,1], [4,3,1], [4,2,2], [3,3,2]}\n@test collect(partitions([1,2,3])) == {{[1,2,3]}, {[1,2],[3]}, {[1,3],[2]}, {[1],[2,3]}, {[1],[2],[3]}}\n@test collect(partitions([1,2,3,4],3)) == {{[1,2],[3],[4]}, {[1,3],[2],[4]}, {[1],[2,3],[4]}, {[1,4],[2],[3]}, {[1],[2,4],[3]},{[1],[2],[3,4]}}\n\n@test length(collect(partitions(30))) == length(partitions(30))\n@test length(collect(partitions(90,4))) == length(partitions(90,4))\n@test length(collect(partitions('a':'h'))) == length(partitions('a':'h'))\n@test length(collect(partitions('a':'h',5))) == length(partitions('a':'h',5))\n\nfor n = 0:7, k = 1:factorial(n)\n    p = nthperm!([1:n], k)\n    @test isperm(p)\n    @test nthperm(p) == k\nend\n\n#Issue 6154\n@test binomial(int32(34), int32(15)) == binomial(BigInt(34), BigInt(15)) == 1855967520\n@test binomial(int64(67), int64(29)) == binomial(BigInt(67), BigInt(29)) == 7886597962249166160\n@test binomial(int128(131), int128(62)) == binomial(BigInt(131), BigInt(62)) == 157311720980559117816198361912717812000 \n\n", "meta": {"hexsha": "49b9fac475d6f6b17ca30bea0ff4d920e7114eb6", "size": 1747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/combinatorics.jl", "max_stars_repo_name": "alyst/julia", "max_stars_repo_head_hexsha": "c46ae3bd0e881887126b0e800f7480d3c44ea1a8", "max_stars_repo_licenses": ["MIT"], "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/combinatorics.jl", "max_issues_repo_name": "alyst/julia", "max_issues_repo_head_hexsha": "c46ae3bd0e881887126b0e800f7480d3c44ea1a8", "max_issues_repo_licenses": ["MIT"], "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/combinatorics.jl", "max_forks_repo_name": "alyst/julia", "max_forks_repo_head_hexsha": "c46ae3bd0e881887126b0e800f7480d3c44ea1a8", "max_forks_repo_licenses": ["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.2162162162, "max_line_length": 143, "alphanum_fraction": 0.5787063537, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7707715543472228}}
{"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    (\u03b2,\u03b3) = p\n    @inbounds begin\n        du[1] = -\u03b2*S*I\n        du[2] = \u03b2*S*I - \u03b3*I\n        du[3] = \u03b3*I\n    end\n    nothing\nend;\n\n\ntmax = 10000.0\ntspan = (0.0,tmax)\n\u03b4t = 1.0;\n\n\nn_train = 50 # Number of training samples\nn_test = 1000; # Number of test samples\n\n\n# Parameters are \u03b2, \u03b3\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\u03b8 = 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.(\u03b8);\n\n\ntraining_df = DataFrame(\u03b8)\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\u03b8_test = sample(n_test,lb,ub,sampler)\nlfs_test = logit_final_size.(\u03b8_test);\n\n\ntest_df = DataFrame(\u03b8_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\u03b2_grid = collect(lb[1]:0.00001:ub[1])\n\u03b8_eval = [(\u03b2\u1d62,0.25) for \u03b2\u1d62 in \u03b2_grid]\neval_df = DataFrame(\u03b8_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(\u03b2_grid,\n     fs_eval,\n     xlabel = \"Infectivity parameter, \u03b2\",\n     ylabel = \"Final size\",\n     label = \"Model\")\nplot!(\u03b2_grid,\n      invlogit.(logit_final_size.(\u03b8_eval)),\n      ribbon = (fs_eval .- fs_eval_lc, fs_eval_uc - fs_eval),\n      label = \"Surrogate\",\n      legend = :right)\n\n\n\u03b3_grid = collect(lb[2]:0.001:ub[2])\n\u03b8_eval = [(0.001,\u03b3\u1d62) for \u03b3\u1d62 in \u03b3_grid]\neval_df = DataFrame(\u03b8_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(\u03b3_grid,\n     fs_eval,\n     xlabel = \"Recovery rate, \u03b3\",\n     ylabel = \"Final size\",\n     label = \"Model\")\nplot!(\u03b3_grid,\n      invlogit.(logit_final_size.(\u03b8_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 \u03b2\")\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 \u03b3\")\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": "using Test, DayCounts, Dates\nusing XLSX\nusing Tables\n\nxf = XLSX.readxlsx(\"yearfrac.xlsx\")\n\nfunction range_to_table(rng)\n    Tables.table(rng[2:end,:]; header = Symbol.(rng[1,:]))\nend\n\n@testset \"Excel basis 0\" begin\n    table = range_to_table(xf[\"basis0\"][:])\n    dc = DayCounts.Thirty360Excel()\n    for r in Tables.rows(table)\n        @test yearfrac(Date(r.startdate), Date(r.enddate), dc) == r.yearfrac\n    end\nend\n\n@testset \"Excel basis 1\" begin\n    table = range_to_table(xf[\"basis1\"][:])\n    dc = DayCounts.ActualActualExcel()\n    for r in Tables.rows(table)\n        @test yearfrac(Date(r.startdate), Date(r.enddate), dc) == r.yearfrac\n    end\nend\n\n@testset \"Excel basis 2\" begin\n    table = range_to_table(xf[\"basis2\"][:])\n    dc = DayCounts.Actual360()\n    for r in Tables.rows(table)\n        @test yearfrac(Date(r.startdate), Date(r.enddate), dc) == r.yearfrac\n    end\nend\n\n@testset \"Excel basis 3\" begin\n    table = range_to_table(xf[\"basis3\"][:])\n    dc = DayCounts.Actual365Fixed()\n    for r in Tables.rows(table)\n        @test yearfrac(Date(r.startdate), Date(r.enddate), dc) == r.yearfrac\n    end\nend\n\n@testset \"Excel basis 4\" begin\n    table = range_to_table(xf[\"basis4\"][:])\n    dc = DayCounts.ThirtyE360()\n    for r in Tables.rows(table)\n        @test yearfrac(Date(r.startdate), Date(r.enddate), dc) == r.yearfrac\n    end\nend", "meta": {"hexsha": "fa0a282c03f973e7fef3a6f5ea3a6e154e93d09d", "size": 1341, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/excel.jl", "max_stars_repo_name": "JuliaFinance/DayCounts.jl", "max_stars_repo_head_hexsha": "2f20d22b18190942f90125650e6de8cf2aa9ad60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-01-12T13:17:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T10:08:39.000Z", "max_issues_repo_path": "test/excel.jl", "max_issues_repo_name": "JuliaFinance/DayCounts.jl", "max_issues_repo_head_hexsha": "2f20d22b18190942f90125650e6de8cf2aa9ad60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2019-01-19T12:11:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-25T04:48:57.000Z", "max_forks_repo_path": "test/excel.jl", "max_forks_repo_name": "JuliaFinance/DayCounts.jl", "max_forks_repo_head_hexsha": "2f20d22b18190942f90125650e6de8cf2aa9ad60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-01-18T05:33:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:24:58.000Z", "avg_line_length": 27.3673469388, "max_line_length": 76, "alphanum_fraction": 0.6562266965, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7707715510101788}}
{"text": "\"\"\"\n    GaussLik <: Likelihood\n\nGaussian, a.k.a. Normal, likelihood\n```math\np(y | f, \u03c3) = 1 / \u221a(2\u03c0\u03c3\u00b2) \\\\exp(-(x - f)\u00b2/(2\u03c3\u00b2)),\n```\nwhere standard deviation ``\u03c3`` is a non-fixed hyperparameter and ``f`` is the latent\nGaussian process.\n\"\"\"\nmutable struct GaussLik <: Likelihood\n    \"Standard deviation\"\n    \u03c3::Float64\n    \"Priors for likelihood parameters\"\n    priors::Array\n\n    \"\"\"\n        GaussLik(l\u03c3::Float64)\n\n    Create `GaussLik` with standard deviation `exp(l\u03c3)`.\n    \"\"\"\n    GaussLik(l\u03c3::Float64) = new(exp(l\u03c3), [])\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.\u03c3)) .- 0.5 * ((y - f) / gauss.\u03c3).^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.\u03c3^2 for (fi,yi) in zip(f,y)]\nend\n\n# derivative of log pdf wrt to parameters\nfunction dlog_dens_d\u03b8(gauss::GaussLik, f::VecF64, y::VecF64)\n    return gauss.\u03c3*[-1/gauss.\u03c3 + 1/gauss.\u03c3^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.\u03c3^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.\u03c3 = exp(hyp[])\nend\n\nget_params(gauss::GaussLik) = Float64[log(gauss.\u03c3)]\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.\u03c3^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    \u03b8::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.\u03b8)\nBase.:+(line::Line, V::VecE2) = Line(line.C + V, line.\u03b8)\n\nget_polar_angle(line::Line) = line.\u03b8\nrot(line::Line, \u0394\u03b8::Float64) = Line(line.C, line.\u03b8+\u0394\u03b8)\nBase.rot180(line::Line) = rot(line, 1\u03c0)\nBase.rotl90(line::Line) = rot(line,  \u03c0/2)\nBase.rotr90(line::Line) = rot(line, -\u03c0/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.\u03b8)\n    pb = P - line.C\n\n    denom = abs2(ab)\n    if denom \u2248 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, \u03b5::Float64=1e-10)\n    ab = polar(1.0, line.\u03b8)\n    signed_dist = ab.x*(p.y-line.C.y) - ab.y*(p.x-line.C.x)\n    if abs(signed_dist) < \u03b5\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, \u03b1, p)\n\nComputing the \u03b1 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, \u03b1, 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*\u03b1*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": "\"\"\"\nperfect_square(number)\n\nCheck if a number is a perfect square or not.\n\n# Example\n```jula\nperfect_square(9)   # returns True\nperfect_square(16)  # returns True\nperfect_square(1)   # returns True\nperfect_square(0)   # returns True\nperfect_square(10)  # returns False\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction perfect_square(number)\n    return sqrt(number) * sqrt(number) == number\nend\nperfect_square(9)", "meta": {"hexsha": "83c375b6bbf72bb93d40c938e85426ab46879507", "size": 449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/perfect_square.jl", "max_stars_repo_name": "ashwani-rathee/Julia", "max_stars_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-22T18:32:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-22T18:32:05.000Z", "max_issues_repo_path": "src/math/perfect_square.jl", "max_issues_repo_name": "ashwani-rathee/Julia", "max_issues_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_issues_repo_licenses": ["MIT"], "max_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/perfect_square.jl", "max_forks_repo_name": "ashwani-rathee/Julia", "max_forks_repo_head_hexsha": "f02c1b07bb491a27e02599888a545db86305a97a", "max_forks_repo_licenses": ["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.45, "max_line_length": 68, "alphanum_fraction": 0.7349665924, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7707195720425466}}
{"text": "using GeneralizedSampling\nusing Base.Test\n\n#=\nVarious small functions are defined to interact with a Freq2Wave type.\n=#\n\n\n# ------------------------------------------------------------\n# Creating matrices\n\nJ = 3\nM = 2^(J+1)\nN = 2^J\n\n# Uniform samples, No Boundary\nUsamples = grid(M, 0.5)\nTUNB = Freq2Wave(Usamples, \"haar\", J)\n\n# Uniform samples, with Boundary\nwavename = \"db3\"\nTUB = Freq2Wave(Usamples, wavename, J)\n\n# Non-Uniform samples, No Boundary\nK = N/2\nNUsamples = N*rand(M) - K\nTNUNB = Freq2Wave(NUsamples, \"haar\", J, K)\n\n# Non-Uniform samples, with Boundary\nTNUB = Freq2Wave(NUsamples, wavename, J, K)\n\n\n# ------------------------------------------------------------\n# Testing\n\n@test isuniform(TUNB)\n@test isuniform(TUB)\n@test !isuniform(TNUNB)\n@test !isuniform(TNUB)\n\n@test !hasboundary(TUNB)\n@test hasboundary(TUB)\n@test !hasboundary(TNUNB)\n@test hasboundary(TNUB)\n\n@test dim(TUNB) == dim(TUB) == dim(TNUNB) == dim(TNUB) == 1\n\n@test wscale(TUNB) == wscale(TUB) == wscale(TNUNB) == wscale(TNUB) == J\n\n@test wsize(TUNB) == wsize(TUB) == wsize(TNUNB) == wsize(TNUB) == (N,)\n\n@test size(TUNB) == size(TUB) == size(TNUNB) == size(TNUB) == (M,N)\n\n@test van_moment(TUNB) == van_moment(TNUNB) == 1\n@test van_moment(TUB) == van_moment(TNUB) == van_moment(wavename)\n\n", "meta": {"hexsha": "5071bf71b04a30145ec28c6048d30ae9acde1679", "size": 1268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Freq2Wave.jl", "max_stars_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": "test/Freq2Wave.jl", "max_issues_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": "test/Freq2Wave.jl", "max_forks_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": 22.2456140351, "max_line_length": 71, "alphanum_fraction": 0.6143533123, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8519528076067261, "lm_q1q2_score": 0.7707195676623388}}
{"text": "using ArrayFire\nusing BenchmarkTools\n\nfunction pi_gpu(n)\n    return 4 *\n           sum(rand(AFArray{Float64}, n)^2 .+ rand(AFArray{Float64}, n)^2 .<= 1) ./\n           n\nend\n\n@btime pi_gpu(10_000_000)\n\nfunction pi_serial(n)\n    inside = 0\n    for i = 1:n\n        x, y = rand(), rand()\n        inside += (x^2 + y^2 <= 1)\n    end\n    return 4 * inside / n\nend\n\n@btime pi_serial(10_000_000)\n\n#%% Mandelbrot fractal\nusing Plots\ngr()\n\nmaxIterations = 500\ngridSize = 2048\nxlim = [-0.748766713922161, -0.748766707771757]\nylim = [0.123640844894862, 0.123640851045266]\n\nx = range(xlim[1], xlim[2], length = gridSize)\ny = range(ylim[1], ylim[2], length = gridSize)\n\nxGrid = [i for i in x, j in y]\nyGrid = [j for i in x, j in y]\n\nz0 = xGrid + im * yGrid\n\nfunction mandelbrotGPU(z0, maxIterations)\n    z = z0\n    count = ones(AFArray{Float32}, size(z))\n\n    for n = 1:maxIterations\n        z = z .* z .+ z0\n        count = count + (abs(z) <= 2)\n    end\n    return sync(log(count))\nend\n\ncount = Array(mandelbrotGPU(AFArray(z0), maxIterations))\nheatmap(\n    count,\n    color = :inferno,\n    grid = false,\n    colorbar = :none,\n    framestyle = :none,\n    size = (2048, 2048),\n)\nsavefig(\"mandelbrot.png\")\n", "meta": {"hexsha": "367b749805fc33b8354f88658c92eaf330cbda11", "size": 1189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lesson-arrayfire/lesson-arrayfire.jl", "max_stars_repo_name": "JeffreySarnoff/techytok-examples", "max_stars_repo_head_hexsha": "5c34c9fc0660da1a69f9e3959465ed80659c30cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-10-28T11:21:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T09:06:49.000Z", "max_issues_repo_path": "lesson-arrayfire/lesson-arrayfire.jl", "max_issues_repo_name": "JeffreySarnoff/techytok-examples", "max_issues_repo_head_hexsha": "5c34c9fc0660da1a69f9e3959465ed80659c30cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lesson-arrayfire/lesson-arrayfire.jl", "max_forks_repo_name": "JeffreySarnoff/techytok-examples", "max_forks_repo_head_hexsha": "5c34c9fc0660da1a69f9e3959465ed80659c30cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-01-20T23:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T20:51:24.000Z", "avg_line_length": 19.4918032787, "max_line_length": 83, "alphanum_fraction": 0.6072329689, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7707195632821309}}
{"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\u00d73 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) \u2248 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(\u03bc::AbstractFloat,\u03c1::AbstractFloat,\u03c3::AbstractFloat,n::Int64,\u03bb::AbstractFloat)\n    #output is xgrid, xprob\n    # x_t+1 = \u03bc + \u03c1 x_t + \u03c3 e_{t+1}, e_t+1 \u223c N(0,1)\n    xhi = \u03bc/(1-\u03c1) + \u03bb*sqrt(\u03c3^2/(1-\u03c1)^2)\n    xlo = \u03bc/(1-\u03c1) - \u03bb*sqrt(\u03c3^2/(1-\u03c1)^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(\u03bc+\u03c1*xgrid[i],\u03c3)\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 \u03c1 = 0.\n# i.e. i.i.d noise with mean \u03bc, std. \u03c3, 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(\u03bc::AbstractFloat, \u03c3::AbstractFloat, n::Int64, \u03bb::AbstractFloat)\n    xgrid, xprob, xscale = tauchen86(\u03bc, 0., \u03c3, n, \u03bb)\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": "include(\"../src/HMat2d.jl\");\n\nfunction laplacian2d(nx,ny)\n    M = speye(nx*ny);\n    for x=1:nx\n        for y=1:ny\n            s = x+(y-1)*nx;\n            M[s,s] = 4;\n            if x > 1\n                M[s,s-1] = -1;\n            end\n            if x < nx\n                M[s,s+1] = -1;\n            end\n            if y > 1\n                M[s,s-nx] = -1;\n            end\n            if y < ny\n                M[s,s+nx] = -1;\n            end\n        end\n    end\n    return M;\nend\n\nEPS = 1e-6;\nMaxRank = 2;\nminn = 8;\n\nfor n = [16 32 64]\n    A = full(laplacian2d(n,n));\n    Z2C = Z2Cmapper([n,n],minn,reshape(1:n^2,n,n));\n    A = full(A[Z2C,Z2C]);\n    AH = HMat2dd2h(A, [n,n], [n,n], WEAK, [0,0], [0,0], 1, EPS, MaxRank, minn);\n    BH = hcopy(AH);\n    v = rand(n^2,5);\n    tic();\n    uhmat = hmatvec(AH,v);\n    toc();\n    tic();\n    CH = hmul(AH,BH);\n    toc();\n    CD = hh2d(CH);\n    @printf(\"N^2 = %4d^2, hmul error: %.3e\\n\",n,norm(CD-A*A)/norm(A*A));\nend\n", "meta": {"hexsha": "08cb1c44aa72f45f96aba147031059f54e007632", "size": 956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HMat.jl/test/test.jl", "max_stars_repo_name": "YingzhouLi/HMat", "max_stars_repo_head_hexsha": "518f497e8140505ea7c69896ac27675ccbe9f3c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-09-15T16:03:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T07:06:11.000Z", "max_issues_repo_path": "HMat.jl/test/test.jl", "max_issues_repo_name": "YingzhouLi/HMat", "max_issues_repo_head_hexsha": "518f497e8140505ea7c69896ac27675ccbe9f3c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-02-09T18:36:28.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-09T18:36:28.000Z", "max_forks_repo_path": "HMat.jl/test/test.jl", "max_forks_repo_name": "YingzhouLi/HMat.jl", "max_forks_repo_head_hexsha": "518f497e8140505ea7c69896ac27675ccbe9f3c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-10-12T06:56:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T22:31:42.000Z", "avg_line_length": 20.7826086957, "max_line_length": 79, "alphanum_fraction": 0.3912133891, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597459, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7706286932349603}}
{"text": "using NumericalMethodsforEngineers\nusing Test\n\n# write your own tests here\n\ncode_tests = [\n  # Ch01 tests\n  \"ch01_nmex.jl\",\n  \n  # Ch02 tests\n  \"ch02_lufac.jl\",\n  \"ch02_ldlt.jl\",\n  #\"ch02_SymmetricBandedMatrix.jl\",\n  #\"ch02_SkylineMatrix.jl\",\n  \"ch02_gaussian.jl\",\n  \"ch02_penalized.jl\",\n  \"ch02_jacobi.jl\",\n  \"ch02_bicgstab.jl\",                               # Initial version of bicgstab\n  \n  # Ch03 tests\n  # Ch04 tests\n  \n  \"ch04_symata.jl\",\n  \n  # Ch05 tests\n  \n  # Ch06 tests\n  \"ch06_p6.2.jl\",\n  \n  # Ch07 tests\n  \"ch07_ivp_ex7.3.jl\",                           # Four direct methods\n  \"ch07_bvp_ex7.4a.jl\",                        # Shooting method example 7.4a\n  \"ch07_bvp_ex7.4b.jl\",                        # Shooting method example 7.4b\n  \n  # Symata Weighted Residual Method tests\n  \"wrm_with_using_symata.jl\",\n  \"wrm_with_using_nmfe.jl\",\n  \"../examples/ch07/WRM/Ex.7.13.jl\",         # 1 point LagrangePolynomial\n  \"../examples/ch07/WRM/Ex.7.14.jl\",     # 2 point LagrangePolynomial\n  \"../examples/ch07/WRM/Ex.7.15.jl\",     # 1 point collocation  \n  \"../examples/ch07/WRM/Ex.7.15b.jl\",    # 2 point collocation  \n  \"../examples/ch07/WRM/Ex.7.16.jl\",     # 1 point subdomain\n  \"../examples/ch07/WRM/Ex.7.16b.jl\",    # 2 point subdomain\n  \"../examples/ch07/WRM/Ex.7.17.jl\",     # 1 point least-squares\n  \"../examples/ch07/WRM/Ex.7.17b.jl\",    # 2 point least-squares\n  \"../examples/ch07/WRM/Ex.7.18.jl\",     # 1 point galerkin\n  \"../examples/ch07/WRM/Ex.7.18b.jl\",   # 2 point galerkin\n\n  # Ch08 tests\n  \"ch08_ex01.jl\",\n  \n  # Extra tests\n  \"vianello_symata.jl\"                           # Vianello procedure\n  \n]\n\nprintln(\"Running tests:\")\n\n@testset \"NumericalMethodsforEngineers.jl\" begin\n  for my_test in code_tests\n      println(\"\\n  * $(my_test) *\")\n      include(\"$(my_test)\")\n  end\n  println()\nend", "meta": {"hexsha": "be833f3449d38a69740483631d89267f4f2a7d7a", "size": 1811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 27.8615384615, "max_line_length": 81, "alphanum_fraction": 0.6085035892, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8887588052782737, "lm_q1q2_score": 0.7705856721224295}}
{"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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    @inbounds begin\n        du[1] = -\u03b2*c*I/N*S\n        du[2] = \u03b2*c*I/N*S - \u03b3*I\n        du[3] = \u03b3*I\n    end\n    nothing\nend;\n\n\n\u03b4t = 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\u2080=Particles(n_samples,Uniform(1.0,50.0))\nu0 = [N-I\u2080,I\u2080,0.0]\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p);\n\n\nsol_ode = solve(prob_ode, Tsit5(), dt=\u03b4t);\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\u2080)),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": "@test factorial(7,3) == 7*6*5*4\n@test_throws DomainError factorial(3,7)\n@test_throws DomainError factorial(-3,-7)\n@test_throws DomainError factorial(-7,-3)\n#JuliaLang/julia#9943\n@test factorial(big(100), (80)) == 1303995018204712451095685346159820800000\n#JuliaLang/julia#9950\n@test_throws OverflowError factorial(1000,80)\n\n# derangement\n@test derangement(4) == subfactorial(4) == 9\n@test derangement(24) == parse(BigInt,\"228250211305338670494289\")\n\n# partialderangement\n@test partialderangement(7, 3) == 315\n@test_throws DomainError partialderangement(8, 9)\n@test_throws DomainError partialderangement(-8, 0)\n\n# doublefactorial\n@test doublefactorial(70) == parse(BigInt,\"355044260642859198243475901411974413130137600000000\")\n@test_throws DomainError doublefactorial(-1)\n\n# hyperfactorial\n@test hyperfactorial(8) == parse(BigInt,\"55696437941726556979200000\")\n@test hyperfactorial(0) == parse(BigInt,\"1\")\n@test hyperfactorial(1) == parse(BigInt,\"1\")\n@test hyperfactorial(2) == parse(BigInt,\"4\")\n\n# multifactorial\n@test multifactorial(40,2) == doublefactorial(40)\n@test_throws DomainError multifactorial(-1,1)\n\n# multinomial\n@test multinomial(1,4,4,2) == 34650\n\n# primorial\n@test primorial(17) == 510510\n@test_throws DomainError primorial(-1)\n", "meta": {"hexsha": "f77d2ca414030257c34ee40997b704610343f508", "size": 1240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/factorials.jl", "max_stars_repo_name": "gdalle/Combinatorics.jl", "max_stars_repo_head_hexsha": "ebc4d6777a933dce71442b38c51ec49f0be96529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-15T01:01:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T01:01:50.000Z", "max_issues_repo_path": "test/factorials.jl", "max_issues_repo_name": "gdalle/Combinatorics.jl", "max_issues_repo_head_hexsha": "ebc4d6777a933dce71442b38c51ec49f0be96529", "max_issues_repo_licenses": ["MIT"], "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/factorials.jl", "max_forks_repo_name": "gdalle/Combinatorics.jl", "max_forks_repo_head_hexsha": "ebc4d6777a933dce71442b38c51ec49f0be96529", "max_forks_repo_licenses": ["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.7948717949, "max_line_length": 96, "alphanum_fraction": 0.7758064516, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399244, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7705694315178065}}
{"text": "@testset \"Matrix\" begin\n    @testset \"Matrix: Determinant\" begin\n        M1 = [1 0; 2 2]\n        M2 = rand(3, 3)\n        M3 = rand(4, 4)\n\n        @test determinant(M1) == det(M1)\n        @test round(determinant(M2), digits = 4) == round(det(M2), digits = 4)\n        @test round(determinant(M3), digits = 4) == round(det(M3), digits = 4)\n    end\n\n    @testset \"Matrix: LU Decompose\" begin\n        mat = [\n            2 -1 -2\n            -4 6 3\n            -4 -2 8\n        ]\n\n        L = [\n            1 0 0\n            -2 1 0\n            -2 -1 1\n        ]\n        U = [\n            2 -1 -2\n            0 4 -1\n            0 0 3\n        ]\n\n        @test lu_decompose(mat) == (L, U)\n    end\n\n    @testset \"Matrix: rotation matrix\" begin\n        theta = pi / 6\n        a = [1; 0]\n        b = [0; 1]\n        @test rotation_matrix(theta) * a == [cos(theta); sin(theta)]\n        @test rotation_matrix(theta) * b == [-sin(theta); cos(theta)]\n    end\n\n    @testset \"Matrix: Gauss-Jordan Elimination\" begin\n        M1 = [1 2 3; 4 5 6]\n        M2 = [1 2 3; 4 8 12]\n        M3 = [1 2; 4 8]\n        M4 = [\n            1 4 8 1 4\n            4 5 6 8 11\n            1 3 2 4 8\n            4 5 67 23 0\n        ]\n        M5 = Float64[\n            1 4 8 1 4\n            4 5 6 8 11\n            1 3 2 4 8\n            4 5 67 23 0\n        ]\n        M6 = [\n            1 4 8\n            4 0 6\n            1 3 2\n        ]\n\n        R3 = [\n            1.0 0.0 0.0 0.0 -1.10637\n            0.0 1.0 0.0 0.0 1.89743\n            0.0 0.0 1.0 0.0 -0.444913\n            0.0 0.0 0.0 1.0 1.07598\n        ]\n\n        @test gauss_jordan(M1) == Float64[1 0 -1; 0 1 2]\n        @test_throws AssertionError gauss_jordan(M2)\n        @test_throws AssertionError gauss_jordan(M3)\n        @test isapprox(gauss_jordan(M4), R3, atol = 1e-5)\n        @test isapprox(gauss_jordan(M5), R3, atol = 1e-5)\n        @test isapprox(\n            gauss_jordan(M6),\n            Float64[1 0 0; 0 1 0; -0 -0 1],\n            atol = 1e-5,\n        )\n    end\nend\n", "meta": {"hexsha": "2c5797dbf7b29002e3a91337e1f9d259264f575d", "size": 1993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/matrix.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": "test/matrix.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": "test/matrix.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": 24.3048780488, "max_line_length": 78, "alphanum_fraction": 0.414450577, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7705694291947274}}
{"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 \u03a3_j \u03d5(X, \u03c9_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) .\u2265 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) \u2264  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) \u2264 1.0) ? 1.09375 * (1.0-x*x)^3  : 0.0 )\nuniform(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) \u2264 1.0) ? 0.5 : 0.0 )\ncosinus(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) \u2264 1.0) ?   0.7853981633974483    * cos( 1.5707963267948966 * x ) : 0.0 )\nquartic(x::Tp) where {Tp<:AbstractFloat} = Tp( (abs(x) \u2264 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": "module TestGaussNewton\n\nusing Test\nusing OptimizationAlgorithms\nusing OptimizationAlgorithms: GaussNewton, LevenbergMarquart, DecreasingStep, LevenbergMarquartSettings\nusing OptimizationAlgorithms: update!, optimize!\n\nfunction test_problem(n)\n    x = sort!(randn(n))\n    g(a, b) = x -> sin(2\u03c0*a*x) + b*x^2\n    a, b = randn(2)\n    y = g(a, b).(x)\n    return [a,b], x, y, g, function residual!(r, ab)\n        @. r = y - g(ab...).(x)\n    end\nend\n\n@testset \"GaussNewton\" begin\n    n = 64\n    ab0, x, y, g, r = test_problem(n)\n    G = GaussNewton(r, ab0, y)\n    \u03c3 = .1\n    ab = ab0 + \u03c3*randn(2)\n    for i in 1:16\n        update!(G, ab)\n    end\n    tol = 1e-8\n    @test isapprox(ab, ab0, atol = tol)\n\n    D = DecreasingStep(G, ab)\n    ab = ab0 + \u03c3*randn(2)\n    for i in 1:16\n        update!(D, ab)\n    end\n    tol = 1e-8\n    @test isapprox(ab, ab0, atol = tol)\nend\n\n@testset \"LevenbergMarquart\" begin\n    n = 64\n    ab0, x, y, g, r = test_problem(n)\n    LM = LevenbergMarquart(r, ab0, y)\n    \u03c3 = .1\n    ab = ab0 + \u03c3*randn(2)\n    tol = 1e-8\n    # tesing out intitialization with very large lambda, min_decrease, and min_iter\n    res = copy(y)\n    stn = LevenbergMarquartSettings(max_iter = 16, min_decrease = 1e-10, min_resnorm = 1e-10, min_res = 0)\n    optimize!(LM, ab, res, Val(false), stn, 1e-6, Val(true))\n    @test isapprox(ab, ab0, atol = tol)\nend\n\n@testset \"Geodesic LevenbergMarquart\" begin\n    n = 64\n    ab0, x, y, g, r = test_problem(n)\n    LM = LevenbergMarquart(r, ab0, y)\n    \u03c3 = .1\n    ab = ab0 + \u03c3*randn(2)\n    tol = 1e-8\n    # tesing out intitialization with very large lambda, min_decrease, and min_iter\n    res = copy(y)\n    stn = LevenbergMarquartSettings(max_iter = 16, min_decrease = 1e-10, min_resnorm = 1e-10, min_res = 0)\n    optimize!(LM, ab, res, Val(true), stn, 1e-6, 0.01, 0.75, Val(true))\n    @test isapprox(ab, ab0, atol = tol)\nend\n\nend\n", "meta": {"hexsha": "e3bfff80e7516b09f1c7607d8080b814d550abe9", "size": 1862, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gaussnewton.jl", "max_stars_repo_name": "MingChiangChang/OptimizationAlgorithms.jl", "max_stars_repo_head_hexsha": "90380fd8526d1eba6037036fbc472e40134e7770", "max_stars_repo_licenses": ["MIT"], "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/gaussnewton.jl", "max_issues_repo_name": "MingChiangChang/OptimizationAlgorithms.jl", "max_issues_repo_head_hexsha": "90380fd8526d1eba6037036fbc472e40134e7770", "max_issues_repo_licenses": ["MIT"], "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/gaussnewton.jl", "max_forks_repo_name": "MingChiangChang/OptimizationAlgorithms.jl", "max_forks_repo_head_hexsha": "90380fd8526d1eba6037036fbc472e40134e7770", "max_forks_repo_licenses": ["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.3823529412, "max_line_length": 106, "alphanum_fraction": 0.6127819549, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7705645242574495}}
{"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\u00b0,0) and `z` is\nthrough lat = 90\u00b0.\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\u00b0\")\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 \u03c0 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\u00b0).  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 \u00d7 p\n    # Check for point and pole being the same\n    norm(gp) \u2248 0. && error(\"Point and pole to plane the same\")\n    gp = normalize(gp)\n    pp = gp \u00d7 g\n    acos(p\u22c5pp) > \u03c0/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 : \u03c0/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 \u2248 p2 && error(\"Two points overlap (are: $p1 and $p2)\")\n    delta(lon1, lat1, lon2, lat2, degrees) \u2248 (degrees ? 180 : \u03c0) &&\n        error(\"Points are antipodal (are: $p1 and $p2)\")\n    gp = p1 \u00d7 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 : \u03c0/2), (degrees ? 360 : 2\u03c0))\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\u00b0\u201390\u00b0 (-\u03c0\u2013\u03c0).  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": "using Distributions, DiffResults, ForwardDiff, DiffResults, AdvancedHMC\n\n# Evaluates target distribution \u03c0(q)\nfunction \u03c0_q(q)\n    q\u2081 = q[1]\n    q\u2082 = q[2]\n    in_bound = (-\u03c0/2 < q\u2081 < \u03c0/2) & (-\u03c0/2 < q\u2082 < \u03c0/2)\n    return in_bound*(2/\u03c0 * exp(-2*(q\u2081^2 + q\u2082^2)) + (sin(q\u2081*q\u2082)*sin(q\u2081)*cos(q\u2082))^2)\nend\n\n# Initial sample\nq\u2080 = [0.0, 0.0]\n\n# State space size\n\u03a9_size = length(q\u2080)\n\n# Number of samples desired\nnum_samples = 25000\n\n# Number of \u03f5 updates\nnum_adapts = 2000\n\n# Evaluates log of target distribution\nfunction \u2113\u03c0(q)\n    return log(\u03c0_q(q))\nend\n\n# Evaluates gradient of log of target distribution\n# This implementation of NUTS requires the gradient function to be defined this\n# way\nfunction \u2202\u2113\u03c0_\u2202q(q)\n    result = DiffResults.GradientResult(q)\n    ForwardDiff.gradient!(result, \u2113\u03c0, q)\n    return (DiffResults.value(result), DiffResults.gradient(result))\nend\n\n# Use Euclidean matrix. 2 here is dimension of sample space\nmetric = DiagEuclideanMetric(\u03a9_size)\n\n# Define Hamiltonian function\nhamiltonian = Hamiltonian(metric, \u2113\u03c0, \u2202\u2113\u03c0_\u2202q)\n\n# Initial step size\n\u03f5\u2080 = find_good_eps(hamiltonian, q\u2080)\n\n# Define leapfrog symplectic integrator\nlf_integrator = Leapfrog(\u03f5\u2080)\n\n# Define NUTS sampler\nsampler = NUTS{MultinomialTS,GeneralisedNoUTurn}(lf_integrator)\n\n# Define \u03f5 adapter. Used to find apatively determine optimal step size \u03f5\nadaptor = StanHMCAdaptor(num_adapts, Preconditioner(metric), NesterovDualAveraging(0.8, lf_integrator))\n\n# Get samples. stats stores information for each sample (e.g., acceptance rate)\nsamples, stats = sample(hamiltonian, sampler, q\u2080, num_samples, adaptor, num_adapts; progress=true)\n\n\nsamples_mat = zeros(num_samples, 2)\nfor i=1:num_samples\n    samples_mat[i,1] = samples[i][1]\n    samples_mat[i,2] = samples[i][2]\nend\n\nusing PyCall, Plots, Pandas\n@pyimport seaborn as sns\nusing PyPlot\npygui(true)\ndata = Pandas.DataFrame(Dict(:q\u2081=>samples_mat[:,1], :q\u2082=>samples_mat[:,2]))\nrc(\"axes\",facecolor = \"#f7ece2\")\nrc(\"figure\",facecolor = \"#f7ece2\")\nrc(\"savefig\",facecolor = \"#f7ece2\")\nsns.jointplot(x = \"q\u2081\", y = \"q\u2082\", data = data, s = 1, alpha = 0.18)\n", "meta": {"hexsha": "0326f753535415a0e4d2b87a9046021f074930fd", "size": 2064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/nuts_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/nuts_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/nuts_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": 27.8918918919, "max_line_length": 103, "alphanum_fraction": 0.7233527132, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7705645219733387}}
{"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": "using Test\n\nusing StableRNGs\nusing Distributions\nusing BetaML\n\n#TESTRNG = FIXEDRNG # This could change...\nTESTRNG = StableRNG(123)\n\nprintln(\"*** Testing the Stats module...\")\n\n# ==================================\n# NEW TEST\n\nprintln(\"Testing welchSatterthwaite ...\")\n\nd = welchSatterthwaite(2,2,20,20)\n@test d == 38\n\n\nobs                     = rand(copy(TESTRNG),Gamma(2,2),50000)\ncandidates              = 0:0.01:maximum(obs)\nmedianWithAbs           = mEstimationBruteForce(obs,candidates)\n@test medianWithAbs     \u2248 3.35\nmedianWithHuberLoss     = mEstimationBruteForce(obs,candidates,x->huberLoss(x,0.0000000001))\n@test medianWithAbs     \u2248 3.35\nmeanWithHuberLoss       = mEstimationBruteForce(obs,candidates,x->huberLoss(x,1000))\n@test meanWithHuberLoss \u2248 3.98\n\n# ----------------------------------------\n\nlB = 100; uB = 200\nobs = rand(copy(TESTRNG),Uniform(lB,uB),10000)\nq0  = findQuantile(obs,0.2)\nq0_2 = sort(obs)[Int(round(length(obs)*0.2))]\n@test isapprox(q0,q0_2,atol=0.01)\n\n# ----------------------------------------\nout = goodnessOfFitDiscrete([205,26,25,19],[0.72,0.07,0.12,0.09],\u03b1=0.05)\n@test out.testValue \u2248 5.889610389610388\n@test out.p_value \u2248  0.1171061913085063\n\n# ----------------------------------------\ndata    = [\"a\",\"y\",\"y\",\"b\",\"b\",\"a\",\"b\"]\nsupport = [\"a\",\"b\",\"y\"]\n@test computeDensity(data,support) == [2,3,2]\n\n# ----------------------------------------\nsupport = [0,1,2,3]\ndata    = [339,455,180,26]\n\u03b8hat    = sum(data .* support)/(sum(data)*3)\nout     = goodnessOfFitDiscrete(data,support,Binomial(3,\u03b8hat),compressedData=true,\u03b1=0.05,d=1)\n@test out.testValue  \u2248  0.8828551921498722\n@test out.p_value  \u2248  0.643117653187048\n\n\n#----------------------------------------\n\nf\u2080   = Uniform(0,1)\ndata = [0.8,0.7,0.4,0.7,0.2]\nout  = ksTest(data,f\u2080;\u03b1=0.05)\n@test out.testValue  \u2248  0.6708203932499368\n@test out.p_value    \u2248  0.009598291426747618\n\n# --------------------------------------\n\n#f\u2080 = Exponential(10)\n#f\u2080 = Normal(0,1)\n#f\u2080 = Uniform(0,10)\nf\u2080 = Normal(0,1)\nrepetitions = 1000\nouts = fill(false,repetitions)\nfor rep in 1:repetitions\n    local data = rand(f\u2080 ,31)\n    local out  = ksTest(data,f\u2080;\u03b1=0.05)\n    outs[rep] = out.rejectedH\u2080\nend\n@test isapprox(sum(outs)/repetitions,0.05,atol=0.05)\n\n#=\n# -------------------------\nfunction computeKSTableValue(f\u2080,N,\u03b1,repetitions=1000)\n    Ts = Array{Float64,1}(undef,repetitions)\n    for rep in 1:repetitions\n        data       = sort(rand(f\u2080,N))\n        N          = length(data)\n        cdfhat     = collect(0:N) ./ N\n        maxDist    = 0.0\n        for (n,x) in enumerate(data)\n            dist = max(abs(cdfhat[n]-cdf(f\u2080,x)), abs(cdfhat[n+1]-cdf(f\u2080,x)))\n            if dist > maxDist\n                maxDist = dist\n            end\n        end\n        T          = sqrt(N) * maxDist\n        Ts[rep]    = T\n    end\n    Ts = sort(Ts)\n    return Ts[Int(ceil((1-\u03b1)*repetitions))]/sqrt(N)\nend\n(N,\u03b1,f\u2080) = 7,0.05,Normal(20,20)\ncomputeKSTableValue(f\u2080,N,\u03b1,1000000) * sqrt(N)\nquantile(Kolmogorov(),1-\u03b1)\nDistributions.quantile_bisect(KSDist(N),1-\u03b1) *sqrt(N)\n=#\n", "meta": {"hexsha": "d66e393ffb9e29cf1fad4ca2e7ce55bead787334", "size": 3015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Stats_tests.jl", "max_stars_repo_name": "sylvaticus/bmlt.jl", "max_stars_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2020-06-08T20:21:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T05:57:47.000Z", "max_issues_repo_path": "test/Stats_tests.jl", "max_issues_repo_name": "sylvaticus/bmlt.jl", "max_issues_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-06-08T14:38:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T15:57:51.000Z", "max_forks_repo_path": "test/Stats_tests.jl", "max_forks_repo_name": "sylvaticus/bmlt.jl", "max_forks_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-06-17T17:00:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T05:57:39.000Z", "avg_line_length": 28.4433962264, "max_line_length": 93, "alphanum_fraction": 0.5691542289, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7705645172902319}}
{"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(\u03b8\u2081, \u03b8\u2082)\n   \tr = sqrt(\u03b8\u2081^2.0 + \u03b8\u2082^2.0) + 1e-10\n\tz = sin(r) / (2*r)\n\tz = z + \u03b8\u2081/40.0 - 2*(\u03b8\u2081/40.0)^2.0 + \u03b8\u2082/40.0 - 2*(\u03b8\u2082/40.0)^2.0 \n\tz = -z/10.0 # switch to minimization\nend\n\nfunction FoggyMountainObj(\u03b8)\n\t\u03b8\u2081 = \u03b8[1]\n\t\u03b8\u2082 = \u03b8[2]\n    FoggyMountainObj(\u03b8\u2081, \u03b8\u2082)\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 `\u03bc` and `\u03c3` for `Distributions.Lognormal(\u03bc, \u03c3)`.\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 `\u03c3`:\n\nlogit_priors = Dict(\"Narrow (\u03c3 = 0.1)\"                 => ScaledLogitNormal(\u03c3 = 0.1),\n                    \"Default (\u03c3 = 1)\"                  => ScaledLogitNormal(\u03c3 = 1),\n                    \"Weird (\u03c3 = 4 with bounds=(0, 1))\" => ScaledLogitNormal(\u03c3 = 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 `\u03c3 > 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_\u03b1,\n    jacobi_\u03b2,\n    laguerre_\u03b1\n\n\n####################\n# Lebesgue measures\n####################\n\n\n\"Supertype of Lebesgue measures\"\nabstract type LebesgueMeasure{T} <: Weight{T} end\n\nunsafe_weightfun(\u03bc::LebesgueMeasure, x) = one(codomaintype(\u03bc))\n\nislebesguemeasure(m::Measure) = false\nislebesguemeasure(m::LebesgueMeasure) = true\n\n==(\u03bc1::LebesgueMeasure, \u03bc2::LebesgueMeasure) = support(\u03bc1) == support(\u03bc2)\n\n\n\"The Lebesgue measure on the space `FullSpace{T}`.\"\nstruct Lebesgue{T} <: LebesgueMeasure{T}\nend\n\nLebesgue() = Lebesgue{Float64}()\nsimilar(\u03bc::Lebesgue, ::Type{T}) where {T} = Lebesgue{T}()\n\nBase.show(io::IO, \u03bc::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(\u03bc::LebesgueUnit, ::Type{T}) where {T <: Real} = Lebesgue{T}()\nsupport(\u03bc::LebesgueUnit{T}) where {T} = UnitInterval{T}()\n\nisnormalized(\u03bc::LebesgueUnit) = true\n\nBase.show(io::IO, \u03bc::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(\u03bc::LebesgueDomain, ::Type{T}) where {T} = LebesgueDomain{T}(\u03bc.domain)\nsupport(m::LebesgueDomain) = m.domain\n\nBase.show(io::IO, mime::MIME\"text/plain\", \u03bc::LebesgueDomain) = composite_show(io, mime, \u03bc)\nDisplay.displaystencil(\u03bc::LebesgueDomain) = [\"dx(\", support(\u03bc), \")\"]\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(\u03bc::DiracWeight, ::Type{T}) where {T} = DiracWeight{T}(\u03bc.point)\n\npoint(\u03bc::DiracWeight) = \u03bc.point\nsupport(\u03bc::DiracWeight) = Point(\u03bc.point)\nisnormalized(\u03bc::DiracWeight) = true\nunsafe_weightfun(\u03bc::DiracWeight, x) = convert(codomaintype(\u03bc), Inf)\n\nBase.show(io::IO, \u03bc::DiracWeight) = iszero(point(\u03bc)) ? print(io, \"\u03b4(x)dx\") : print(io, \"\u03b4(x-$(repr(point(\u03bc))))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(\u03bc::LegendreWeight, ::Type{T}) where {T <: Real} = LegendreWeight{T}()\nsupport(\u03bc::LegendreWeight{T}) where {T} = ChebyshevInterval{T}()\n\nBase.show(io::IO, \u03bc::LegendreWeight) = print(io, \"dx(-1..1)  (Legendre)\")\nDisplay.object_parentheses(\u03bc::LegendreWeight) = true\n\n\n\"Supertype of Jacobi weights.\"\nabstract type AbstractJacobiWeight{T} <: Weight{T} end\n\n==(\u03bc1::AbstractJacobiWeight, \u03bc2::AbstractJacobiWeight) =\n    jacobi_\u03b1(\u03bc1) == jacobi_\u03b1(\u03bc2) && jacobi_\u03b2(\u03bc1) == jacobi_\u03b2(\u03bc2)\n\n\"The Jacobi weight on the interval `[-1,1]`.\"\nstruct JacobiWeight{T} <: AbstractJacobiWeight{T}\n    \u03b1   ::  T\n    \u03b2   ::  T\n\n    JacobiWeight{T}(\u03b1 = zero(T), \u03b2 = zero(T)) where {T} = new(\u03b1, \u03b2)\nend\nJacobiWeight() = JacobiWeight{Float64}()\nJacobiWeight(\u03b1, \u03b2) = JacobiWeight(promote(\u03b1, \u03b2)...)\nJacobiWeight(\u03b1::T, \u03b2::T) where {T<:AbstractFloat} = JacobiWeight{T}(\u03b1, \u03b2)\nJacobiWeight(\u03b1::N, \u03b2::N) where {N<:Number} = JacobiWeight(float(\u03b1), float(\u03b2))\n\njacobi_weightfun(x, \u03b1, \u03b2) = (1+x)^\u03b1 * (1-x)^\u03b2\n\nsimilar(\u03bc::JacobiWeight, ::Type{T}) where {T <: Real} = JacobiWeight{T}(\u03bc.\u03b1, \u03bc.\u03b2)\nsupport(\u03bc::JacobiWeight{T}) where {T} = ChebyshevInterval{T}()\nunsafe_weightfun(\u03bc::JacobiWeight, x) = jacobi_weightfun(x, \u03bc.\u03b1, \u03bc.\u03b2)\n\njacobi_\u03b1(\u03bc::JacobiWeight) = \u03bc.\u03b1\njacobi_\u03b2(\u03bc::JacobiWeight) = \u03bc.\u03b2\n\nBase.show(io::IO, \u03bc::JacobiWeight) = print(io, \"(1+x)^$(jacobi_\u03b1(\u03bc))(1-x)^$(jacobi_\u03b2(\u03bc)) dx  (Jacobi)\")\nDisplay.object_parentheses(\u03bc::JacobiWeight) = true\n\n\n\"\"\"\nThe `Chebyshev` or `ChebyshevT` weight is the measure on `[-1,1]` with the\nChebyshev weight function `w(x) = 1/\u221a(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_\u03b1(\u03bc::ChebyshevTWeight{T}) where {T} = -one(T)/2\njacobi_\u03b2(\u03bc::ChebyshevTWeight{T}) where {T} = -one(T)/2\n\nsimilar(\u03bc::ChebyshevTWeight, ::Type{T}) where {T <: Real} = ChebyshevTWeight{T}()\nsupport(\u03bc::ChebyshevTWeight{T}) where {T} = ChebyshevInterval{T}()\nunsafe_weightfun(\u03bc::ChebyshevTWeight, x) = chebyshev_weight_firstkind(x)\n\nweightfunction(\u03bc::ChebyshevTWeight) = chebyshev_weight_firstkind\n\nBase.show(io::IO, \u03bc::ChebyshevTWeight) = print(io, \"1/\u221a(1+x)^2 dx  (ChebyshevT)\")\nDisplay.object_parentheses(\u03bc::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) = \u221a(1-x^2).`\n\"\"\"\nstruct ChebyshevUWeight{T} <: AbstractJacobiWeight{T}\nend\nChebyshevUWeight() = ChebyshevUWeight{Float64}()\n\nchebyshev_weight_secondkind(x) = sqrt(1-x^2)\n\njacobi_\u03b1(\u03bc::ChebyshevUWeight{T}) where {T} = one(T)/2\njacobi_\u03b2(\u03bc::ChebyshevUWeight{T}) where {T} = one(T)/2\n\nsimilar(\u03bc::ChebyshevUWeight, ::Type{T}) where {T <: Real} = ChebyshevUWeight{T}()\nsupport(\u03bc::ChebyshevUWeight{T}) where {T} = ChebyshevInterval{T}()\nunsafe_weightfun(\u03bc::ChebyshevUWeight, x) = chebyshev_weight_secondkind(x)\n\nweightfunction(\u03bc::ChebyshevUWeight) = chebyshev_weight_secondkind\n\nBase.show(io::IO, \u03bc::ChebyshevUWeight) = print(io, \"\u221a(1+x)^2 dx  (ChebyshevU)\")\nDisplay.object_parentheses(\u03bc::ChebyshevUWeight) = true\n\n\nconvert(::Type{JacobiWeight}, \u03bc::LegendreWeight{T}) where {T} =\n    JacobiWeight{T}(0, 0)\nconvert(::Type{JacobiWeight}, \u03bc::ChebyshevTWeight{T}) where {T} =\n    JacobiWeight{T}(-one(T)/2, -one(T)/2)\nconvert(::Type{JacobiWeight}, \u03bc::ChebyshevUWeight{T}) where {T} =\n    JacobiWeight{T}(one(T)/2, one(T)/2)\n\nfunction convert(::Type{ChebyshevTWeight}, \u03bc::JacobiWeight{T}) where {T}\n    (jacobi_\u03b1(\u03bc) \u2248 -one(T)/2 && jacobi_\u03b2(\u03bc) \u2248 -one(T)/2) || throw(InexactError(:convert, ChebyshevTWeight, \u03bc))\n    ChebyshevTWeight{T}()\nend\n\nfunction convert(::Type{ChebyshevUWeight}, \u03bc::JacobiWeight{T}) where {T}\n    (jacobi_\u03b1(\u03bc) \u2248 one(T)/2 && jacobi_\u03b2(\u03bc) \u2248 one(T)/2) || throw(InexactError(:convert, ChebyshevUWeight, \u03bc))\n    ChebyshevUWeight{T}()\nend\n\nfunction convert(::Type{LegendreWeight}, \u03bc::JacobiWeight{T}) where {T}\n    (\u03bc.\u03b1 \u2248 0 && \u03bc.\u03b2 \u2248 0) || throw(InexactError(:convert, LegendreWeight, \u03bc))\n    LegendreWeight{T}()\nend\n\njacobi_\u03b1(\u03bc::LegendreWeight{T}) where {T} = zero(T)\njacobi_\u03b2(\u03bc::LegendreWeight{T}) where {T} = zero(T)\n\n==(\u03bc1::AbstractJacobiWeight, \u03bc2::LegendreWeight) =\n    jacobi_\u03b1(\u03bc1) == jacobi_\u03b1(\u03bc2) && jacobi_\u03b2(\u03bc1) == jacobi_\u03b2(\u03bc2)\n==(\u03bc1::LegendreWeight, \u03bc2::AbstractJacobiWeight) =\n    jacobi_\u03b1(\u03bc1) == jacobi_\u03b1(\u03bc2) && jacobi_\u03b2(\u03bc1) == jacobi_\u03b2(\u03bc2)\n\n\n\"The generalised Laguerre measure on the halfline `[0,\u221e)`.\"\nstruct LaguerreWeight{T} <: Weight{T}\n    \u03b1   ::  T\n\n    LaguerreWeight{T}(\u03b1 = zero(T)) where {T} = new(\u03b1)\nend\nLaguerreWeight() = LaguerreWeight{Float64}()\nLaguerreWeight(\u03b1::T) where {T<:AbstractFloat} = LaguerreWeight{T}(\u03b1)\nLaguerreWeight(\u03b1) = LaguerreWeight(float(\u03b1))\n\nlaguerre_weightfun(x, \u03b1) = exp(-x) * x^\u03b1\n\nsimilar(\u03bc::LaguerreWeight, ::Type{T}) where {T <: Real} = LaguerreWeight{T}(\u03bc.\u03b1)\nsupport(\u03bc::LaguerreWeight{T}) where {T} = HalfLine{T}()\nisnormalized(m::LaguerreWeight) = m.\u03b1 == 0\n\nunsafe_weightfun(\u03bc::LaguerreWeight, x) = laguerre_weightfun(x, \u03bc.\u03b1)\n\nlaguerre_\u03b1(\u03bc::LaguerreWeight) = \u03bc.\u03b1\n\nBase.show(io::IO, \u03bc::LaguerreWeight) =\n    laguerre_\u03b1(\u03bc) == 0 ? print(io, \"exp(-x)dx  (Laguerre)\") : print(io, \"x^$(laguerre_\u03b1(\u03bc))exp(-x)dx  (Laguerre)\")\nDisplay.object_parentheses(\u03bc::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(\u03bc::HermiteWeight, ::Type{T}) where {T <: Real} = HermiteWeight{T}()\nunsafe_weightfun(\u03bc::HermiteWeight, x) = hermite_weightfun(x)\n\nweightfunction(\u03bc::HermiteWeight) = hermite_weightfun\n\nBase.show(io::IO, \u03bc::HermiteWeight) = print(io, \"exp(-x^2)dx  (Hermite)\")\nDisplay.object_parentheses(\u03bc::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(\u03bc::GaussianWeight, ::Type{T}) where {T} = GaussianWeight{T}()\nisnormalized(\u03bc::GaussianWeight) = true\nunsafe_weightfun(\u03bc::GaussianWeight, x) = gaussian_weightfun(x, prectype(\u03bc))\n\nBase.show(io::IO, \u03bc::GaussianWeight{T}) where {T<:StaticTypes} =\n    print(io, \"1/(2\u03c0)^($(euclideandimension(T)/2)) exp(-|x|^2)dx  (Gauss)\")\nBase.show(io::IO, \u03bc::GaussianWeight) = print(io, \"C(d) exp(-|x|^2)dx  (Gauss)\")\nDisplay.object_parentheses(\u03bc::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\u03c0; -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\u03bbs = exp10.(-10:0.1:-1)\nopt = STLSQ(\u03bbs)\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 \u00d7 3^2 \u00d7 7, so rad(504) = 2 \u00d7 3 \u00d7 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 \u2211c = 12523.\n\nFind \u2211c for c < 120000.\n\n--------------------------------------------------------------------------------\n\nAnalyse\n-------\n\n1) a < b; a + b = c < bound\n    a)  \u21d2 2a < a + b = c < bound - 1 \u21d2 1 \u2264 a < bound \u00f7 2\n    b)  \u21d2 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 \u21d2 gcd(a, c) = gcd(b, c) = 1\n\n3) gcd(a, b) == 1 \u21d4 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          \u2265 2 if n > 1\n\n6) So the conditions can be simplifed to\n        gcd(a, b) = 1\n        1 \u2264 a < bound \u00f7 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 \u2264 b \u2264 bound-2\n    c = 1+b\n    rad(b) rad(c) < c \u21d2 rad(b) < (1+b) \u00f7 2\n                      \u21d2 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 \u2264 b,\n    2a+1 \u2264 a + b = c < bound => a < (bound-1)\u00f72\n                             => a \u2264 (bound-1)\u00f72 -1\n    rad(a) \u2265 2, rad(b) \u2265 2, rad(c) \u2265 2\n    rad(a) rad(b) rad(a+b) < a+b \u21d2 rad(a) < c \u00f7 4\n                                 \u21d2 rad(b) < c \u00f7 (2 rad(a))\n\n    Therefore the constraints are:\n        2   \u2264 a \u2264 (bound-1)\u00f72 -1\n        a+1 \u2264 b \u2264 bound - 1 - a\n        gcd(a,b) = 1\n        c = a + b\n        rad(a) < c \u00f7 4                  < (bound-1) \u00f7 4\n        rad(b) < c \u00f7 (2 rad(a))         < (bound-1) \u00f7 4\n        rad(c) < c \u00f7 (rad(a) rad(b))    < (bound-1) \u00f7 4\n\n\nConclusion\n==========\n\nThe principle behind the algorithm is to precompute rad(n) for 2 \u2264 n \u2264 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) \u00f7 2 -1\n        rad_a = rad[a]\n        if (rad_a \u2265 (bound-1) \u00f7 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] \u2265 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) + \u03b1*(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| \u2265 |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\u2013242, 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\u2013242, 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\u20131988, 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": "\nx0 = 10\ny0 = 10\nr = 1\nx = r.*[-1.1,0,0,1] .+ x0\ny = r.*[0.0,1,-1,0] .+ y0\nresult = Circle([x0,y0],r,[x y],:kasa)\ncoefs = coef(result)\n@test x0 \u2248 coefs[1]\n@test y0 \u2248 coefs[2]\n@test r \u2248 coefs[3]\n@test dof(result) == 1\n@test all(coef(result) .== [result.position...,result.radius])\n@test length(coefnames(result)) == length(coef(result))\n@test residuals(result) \u2248 [0.1,0,0,0]\n@test rss(result) \u2248 0.1^2\n\n\nx = r.*[-1,0,0,1] .+ x0\nresult = fit(Circle,x,y)\ncoefs = coef(result)\n@test x0 \u2248 coefs[1]\n@test y0 \u2248 coefs[2]\n@test r \u2248 coefs[3]\n@test algorithm(result) == :kasa\n\nresult = fit(Circle,x,y,alg=:pratt)\ncoefs = coef(result)\n@test x0 \u2248 coefs[1]\n@test y0 \u2248 coefs[2]\n@test r \u2248 coefs[3]\n@test algorithm(result) == :pratt\n\nresult = fit(Circle,x,y,alg=:taubin)\ncoefs = coef(result)\n@test x0 \u2248 coefs[1]\n@test y0 \u2248 coefs[2]\n@test r \u2248 coefs[3]\n@test algorithm(result) == :taubin", "meta": {"hexsha": "63fb9783f20d4214e86fbe614a75240e8057a026", "size": 867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Circle.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": "test/Circle.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": "test/Circle.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": 22.2307692308, "max_line_length": 62, "alphanum_fraction": 0.6193771626, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7704492220186602}}
{"text": "using Choices\nusing Test\nusing Base.Iterators: take, countfrom\n\n# test iterating over the first few emirp numbers\n# https://en.wikipedia.org/wiki/Emirp\n\n# first some common definitions:\ndivides(x::Integer, y::Integer) = isinteger(x / y)\nisprime(x::Integer) = !any(y -> divides(x, y), 2:trunc(Integer, \u221ax))\nreverse_digits(x::Int) = parse(Int, reverse(string(x)))\n\n# the conventional way to do it with a Generator:\nfunction isemirp(x::Int)\n  isprime(x) || return false\n  rev_x = reverse_digits(x)\n  return (x != rev_x && isprime(rev_x))\nend\ngenerated_emirps = [take((x for x \u2208 countfrom() if isemirp(x)), 10)...]\n\n# a way to do it with Choices:\nemirps_chooser =\n  choose(countfrom()) |> x ->\n  (isprime(x) ? reverse_digits(x) : fail()) |> rev_x ->\n  ((x != rev_x && isprime(rev_x)) ? x : fail())\nchosen_emirps = [take(emirps_chooser, 10)...]\ncut()\n\nexpected_emirps = [13, 17, 31, 37, 71, 73, 79, 97, 107, 113]\n@test generated_emirps == expected_emirps\n@test chosen_emirps == expected_emirps\n", "meta": {"hexsha": "8b72c23709d83813c191dc019c565e9ead621637", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/emirp.jl", "max_stars_repo_name": "wdebeaum/Choices.jl", "max_stars_repo_head_hexsha": "972289765d757ee97020831947e7a0c844fda928", "max_stars_repo_licenses": ["MIT"], "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/emirp.jl", "max_issues_repo_name": "wdebeaum/Choices.jl", "max_issues_repo_head_hexsha": "972289765d757ee97020831947e7a0c844fda928", "max_issues_repo_licenses": ["MIT"], "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/emirp.jl", "max_forks_repo_name": "wdebeaum/Choices.jl", "max_forks_repo_head_hexsha": "972289765d757ee97020831947e7a0c844fda928", "max_forks_repo_licenses": ["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": 71, "alphanum_fraction": 0.6845298281, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7704492191221493}}
{"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    \u03b1, \u03b2, \u03b3, \u03b4 = p\n    # Current state.\n    x, y = u\n\n    # Evaluate differential equations.\n    du[1] = (\u03b1 - \u03b2 * y) * x # prey\n    du[2] = (\u03b4 * x - \u03b3) * 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    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    \u03b2 ~ truncated(Normal(1.2, 0.5), 0, 2)\n    \u03b3 ~ truncated(Normal(3.0, 0.5), 1, 4)\n    \u03b4 ~ truncated(Normal(1.0, 0.5), 0, 2)\n\n    # Simulate Lotka-Volterra model. \n    p = [\u03b1, \u03b2, \u03b3, \u03b4]\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], \u03c3^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[[:\u03b1, :\u03b2, :\u03b3, :\u03b4]], 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    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    \u03b2 ~ truncated(Normal(1.2, 0.5), 0, 2)\n    \u03b3 ~ truncated(Normal(3.0, 0.5), 1, 4)\n    \u03b4 ~ 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 = [\u03b1, \u03b2, \u03b3, \u03b4]\n    predicted = solve(prob, Tsit5(); p=p, saveat=0.1, save_idxs=2)\n\n    # Observations of the predators.\n    data ~ MvNormal(predicted.u, \u03c3^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[[:\u03b1, :\u03b2, :\u03b3, :\u03b4]], 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    \u03b1, \u03b2, \u03b3, \u03b4 = p\n\n    # Current state.\n    x, y = u\n    # Evaluate differential equations\n    du[1] = \u03b1 * h(p, t - 1; idxs=1) - \u03b2 * x * y\n    du[2] = -\u03b3 * y + \u03b4 * 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    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ Truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    \u03b2 ~ Truncated(Normal(1.2, 0.5), 0, 2)\n    \u03b3 ~ Truncated(Normal(3.0, 0.5), 1, 4)\n    \u03b4 ~ Truncated(Normal(1.0, 0.5), 0, 2)\n\n    # Simulate Lotka-Volterra model.\n    p = [\u03b1, \u03b2, \u03b3, \u03b4]\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], \u03c3^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[[:\u03b1, :\u03b2, :\u03b3, :\u03b4]], 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    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ truncated(Normal(1.5, 0.5), 0.5, 2.5)\n    \u03b2 ~ truncated(Normal(1.2, 0.5), 0, 2)\n    \u03b3 ~ truncated(Normal(3.0, 0.5), 1, 4)\n    \u03b4 ~ truncated(Normal(1.0, 0.5), 0, 2)\n\n    # Simulate Lotka-Volterra model and use a specific algorithm for computing sensitivities.\n    p = [\u03b1, \u03b2, \u03b3, \u03b4]\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], \u03c3^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    \u03b1, \u03b2, \u03b3, \u03b4 = p\n    du[1] = dx = \u03b1 * x - \u03b2 * x * y\n    return du[2] = dy = \u03b4 * x * y - \u03b3 * 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    \u03c3 ~ InverseGamma(2, 3)\n    \u03b1 ~ truncated(Normal(1.3, 0.5), 0.5, 2.5)\n    \u03b2 ~ truncated(Normal(1.2, 0.25), 0.5, 2)\n    \u03b3 ~ truncated(Normal(3.2, 0.25), 2.2, 4.0)\n    \u03b4 ~ truncated(Normal(1.2, 0.25), 0.5, 2.0)\n    \u03d51 ~ truncated(Normal(0.12, 0.3), 0.05, 0.25)\n    \u03d52 ~ truncated(Normal(0.12, 0.3), 0.05, 0.25)\n\n    # Simulate stochastic Lotka-Volterra model.\n    p = [\u03b1, \u03b2, \u03b3, \u03b4, \u03d51, \u03d52]\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], \u03c3^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": "\"\"\"\n````        \nsimple!(u,A,b;\n                 abstol::Real = zero(real(eltype(b))),\n                 reltol::Real = sqrt(eps(real(eltype(b)))),\n                 log=false,\n                 maxiter=100,\n                 P=nothing\n                 ) -> solution, [history]\n````\n\nSimple iteration scheme ``u_{i+1}= u_i - P^{-1} (A u_i -b)`` with similar API as the methods in IterativeSolvers.jl.\n\n\"\"\"\nfunction simple!(u,A,b;\n                 abstol::Real = zero(real(eltype(b))),\n                 reltol::Real = sqrt(eps(real(eltype(b)))),\n                 log=false,\n                 maxiter=100,\n                 Pl=nothing\n                 )\n    res=A*u-b # initial residual\n    upd=similar(res)\n    r0=norm(res) # residual norm\n    history=[r0]  # intialize history recording\n    for i=1:maxiter\n        ldiv!(upd,Pl,res)\n\tu.-=upd # solve preconditioning system and update solution\n\tmul!(res,A,u)    # calculate residual\n        res.-=b\n\tr=norm(res)       # residual norm\n\tpush!(history,r)  # record in history \n\tif (r/r0)<reltol || r<abstol    # check for tolerance\n            break\n\tend\n    end\n    if log \n\treturn u,Dict( :resnorm =>history )\n    else\n        return u\n    end\nend\n\nsimple(A,b;kwargs...)=simple!(zeros(eltype(b),length(b)),A,b;kwargs...)\n", "meta": {"hexsha": "19cc8caec73c4dddc5da7c34d610a4d068ec9471", "size": 1263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple_iteration.jl", "max_stars_repo_name": "mattlie82/ExtendableSparse.jl", "max_stars_repo_head_hexsha": "0a8bff831e7af3596ee44e99839adfc415b3c62f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-07-08T22:42:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T12:46:40.000Z", "max_issues_repo_path": "src/simple_iteration.jl", "max_issues_repo_name": "mattlie82/ExtendableSparse.jl", "max_issues_repo_head_hexsha": "0a8bff831e7af3596ee44e99839adfc415b3c62f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-04-08T14:30:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T16:03:08.000Z", "max_forks_repo_path": "src/simple_iteration.jl", "max_forks_repo_name": "mattlie82/ExtendableSparse.jl", "max_forks_repo_head_hexsha": "0a8bff831e7af3596ee44e99839adfc415b3c62f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:09:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:14:24.000Z", "avg_line_length": 28.0666666667, "max_line_length": 116, "alphanum_fraction": 0.5201900238, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7704492164707627}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 c4e34a90-77b8-11eb-108e-93d91efc7480\nmd\"# Solving Tic Tac Toe With MiniMax Trees!\"\n\n# \u2554\u2550\u2561 a6e0b518-4f39-45d0-b2a3-a95cb1de7114\nmd\"First we need to build out our minimax tree for the game\"\n\n# \u2554\u2550\u2561 72fc2712-61b8-43a6-b68e-b3c5c87ed0a1\nstruct GameState\n\tturn::Int8\n\ttiles::Array{Int8, 2}\nend\n\n# \u2554\u2550\u2561 e6e3a756-6526-483d-af9e-9e53cf6d9f52\nBase.:(==)(x::GameState, y::GameState) = x.turn == y.turn && all(x.tiles .== y.tiles)\n\n# \u2554\u2550\u2561 b3d7a96e-f3fc-4dbd-94a9-552b21426396\nBase.hash(x::GameState) = hash(x.tiles)\n\n# \u2554\u2550\u2561 82323b7f-1e92-46b0-8cff-5d85152d7d5c\nmd\"0's are empty, 1's are player 1 (x), and 2's are player 2 (o)\n\nOur objective is to optimize the policy of player 1\"\n\n# \u2554\u2550\u2561 a51583a3-0faa-4bac-a60b-e763644f674d\nEMPTY = 0x00\n\n# \u2554\u2550\u2561 eb2f779f-c651-4444-a34d-42681de9f3c6\nPLAYER_1 = Int8(1)\n\n# \u2554\u2550\u2561 f0e3fa72-9acf-4325-9173-622f93497b68\nPLAYER_2 = Int8(-1)\n\n# \u2554\u2550\u2561 2a78b1ad-63cb-4cfa-98f4-a11ab05a9022\nnext_player(p) = p == PLAYER_1 ? PLAYER_2 : PLAYER_1\n\n# \u2554\u2550\u2561 d1efdbe8-1a18-4a1c-84fc-f80dc3b9272d\ninitial_tiles = fill(EMPTY, 3, 3)\n\n# \u2554\u2550\u2561 e0e9cbb2-01a8-4523-a6a9-ec7cfdb351d5\ninitial_state = GameState(PLAYER_1, initial_tiles)\n\n# \u2554\u2550\u2561 e9dd6424-1031-44fb-970c-15aa3a4a1385\nstruct MinimaxNode\n\tstate::GameState\n\tchildren::Vector{MinimaxNode}\n\twinner::Int8\n\tleaf::Bool\nend\n\n# \u2554\u2550\u2561 5feafefc-740c-4450-838d-9e2ac47ceb32\nfunction get_winner(state::GameState)\n\t# Really ugly check for game winners\n\t# Rows\n\trows = [all(state.tiles[i, :] .== state.tiles[i, 1]) ? state.tiles[i, 1] : 0 for i \u2208 1:size(state.tiles)[1]]\n\tcols = [all(state.tiles[:, j] .== state.tiles[1, j]) ? state.tiles[1, j] : 0 for j \u2208 1:size(state.tiles)[2]]\n\tdiag1 = state.tiles[1, 1] == state.tiles[2, 2] && state.tiles[1, 1] == state.tiles[3, 3] ? state.tiles[1, 1] : 0\n\tdiag2 = state.tiles[3, 1] == state.tiles[2, 2] && state.tiles[3, 1] == state.tiles[1, 3] ? state.tiles[3, 1] : 0\n\t\n\tmax_rows = max(rows..., cols..., diag1, diag2)\n\tmin_rows = min(rows..., cols..., diag1, diag2)\n\t\n\treturn max_rows > 0 ? max_rows : min_rows\nend\n\n# \u2554\u2550\u2561 7b143cf1-920d-4626-a927-bf33885ae7a9\nget_winner(GameState(PLAYER_1, Int8[\n\t1 -1 1;\n\t-1 -1 1;\n\t-1 -1 0;\n]))\n\n# \u2554\u2550\u2561 31ff651f-b275-46d2-97e9-206c9926dfb8\nfunction possible_moves(state::GameState)\n\tmoves = []\n\tfor i \u2208 1:length(state.tiles)\n\t\tif state.tiles[i] == EMPTY\n\t\t\tnew_tiles = copy(state.tiles)\n\t\t\tnew_tiles[i] = state.turn\n\t\t\tpush!(moves, GameState(next_player(state.turn), new_tiles))\n\t\tend\n\tend\n\t\n\tmoves\nend\n\n# \u2554\u2550\u2561 258017ed-4bf0-4fdd-8239-2fc381e94d0c\nfunction build_minimax(state::GameState)\n\twinner = get_winner(state)\n\tnodes = []\n\tfor pm \u2208 possible_moves(state)\n\t\tpush!(nodes, build_minimax(pm))\n\tend\n\t\n\tif length(nodes) > 0 && winner == EMPTY\n\t\treturn MinimaxNode(state, nodes, (state.turn == PLAYER_1 ? max : min)((x->x.winner).(nodes)...), true)\n\telse\n\t\treturn MinimaxNode(state, [], winner, true)\n\tend\nend\n\n# \u2554\u2550\u2561 45d2cddd-adfe-470a-89bc-56fb5d5982dc\nbegin\n\ttree = build_minimax(initial_state)\n\tnothing\nend\n\n# \u2554\u2550\u2561 d607a5e3-78f5-4308-999f-bf49858004a7\n(x->x.winner).(tree.children[1].children[4].children[4].children[2].children)\n\n# \u2554\u2550\u2561 c9254d06-75b9-47dc-8d29-495c80c9215d\ntree.children[1].children[2].state\n\n# \u2554\u2550\u2561 15fd5bd7-d2c4-4337-a2ad-0fc43ad2b4e0\nmd\"## Flattening our Tree\nTic Tac Toe has the nice property that if a game reaches a particular state, regardless of how that state was obtained, the minimax tree from that state will be the same. Therefore we can build up a dictionary of game states for keys, and the corresponding value is yet another game state representing the best move.\"\n\n# \u2554\u2550\u2561 248c158c-41bc-478f-be12-b7e4ab43544d\nfunction flatten_minimax!(flat_tree, tree)\n\tflat_tree[tree.state] = tree.children[argmin((x->x.winner).(tree.children))].state\n\tfor node \u2208 tree.children\n\t\tif get_winner(node.state) == EMPTY && length(node.children) > 0\n\t\t\tflatten_minimax!(flat_tree, node)\n\t\tend\n\tend\nend\n\n# \u2554\u2550\u2561 72c6bdcd-6d6b-4bf4-a759-1c4256384352\nbegin\n\tflat_tree = Dict()\n\tflatten_minimax!(flat_tree, tree)\nend\n\n# \u2554\u2550\u2561 c0634c74-9228-4d05-8146-3492aaf3a8ef\nflat_tree[initial_state]\n\n# \u2554\u2550\u2561 decac4e3-d5d3-4a51-a5bb-fdb658dec971\nmd\"Fantastic! As can be seen above, the minimax tree has determined that the best move for player 1 is the center square!\"\n\n# \u2554\u2550\u2561 2bb59351-cb34-45a7-bd58-72409adf48fa\nhtml\"<div style='height: 300px'></div>\"\n\n# \u2554\u2550\u2561 4aa39de7-db17-42d7-924f-abb486c03eed\nmd\"## Building the backend\"\n\n# \u2554\u2550\u2561 d5ba2170-d687-4ef8-a7fc-e8fef48b3a2c\nmd\"Set **tiles** and **player** from the frontend\"\n\n# \u2554\u2550\u2561 b385f71f-c608-4be7-a0b6-30a39397451e\nplayer = PLAYER_2\n\n# \u2554\u2550\u2561 c1480936-bc64-481d-a754-31d5a35a2d6d\nmd\"Note that tiles will be a vector of vectors, not an array\"\n\n# \u2554\u2550\u2561 c1cd29c9-b3dc-497b-b200-e6ad08356b39\ntiles = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]\n\n# \u2554\u2550\u2561 7d6a905a-2445-4569-8fe1-8e703b635218\nmd\"And request **next_state**\"\n\n# \u2554\u2550\u2561 4b879529-0359-462e-b032-3bb95a11ac36\nnext_state = flat_tree[GameState(player, hcat(tiles...))].tiles\n\n# \u2554\u2550\u2561 3e54ccec-d960-4cc2-a34a-7fce0964addb\nmd\"Viola! Our \\\"backend\\\" is complete!\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500c4e34a90-77b8-11eb-108e-93d91efc7480\n# \u255f\u2500a6e0b518-4f39-45d0-b2a3-a95cb1de7114\n# \u2560\u255072fc2712-61b8-43a6-b68e-b3c5c87ed0a1\n# \u2560\u2550e6e3a756-6526-483d-af9e-9e53cf6d9f52\n# \u2560\u2550b3d7a96e-f3fc-4dbd-94a9-552b21426396\n# \u255f\u250082323b7f-1e92-46b0-8cff-5d85152d7d5c\n# \u2560\u2550a51583a3-0faa-4bac-a60b-e763644f674d\n# \u2560\u2550eb2f779f-c651-4444-a34d-42681de9f3c6\n# \u2560\u2550f0e3fa72-9acf-4325-9173-622f93497b68\n# \u2560\u25502a78b1ad-63cb-4cfa-98f4-a11ab05a9022\n# \u2560\u2550d1efdbe8-1a18-4a1c-84fc-f80dc3b9272d\n# \u2560\u2550e0e9cbb2-01a8-4523-a6a9-ec7cfdb351d5\n# \u2560\u2550e9dd6424-1031-44fb-970c-15aa3a4a1385\n# \u2560\u25505feafefc-740c-4450-838d-9e2ac47ceb32\n# \u2560\u25507b143cf1-920d-4626-a927-bf33885ae7a9\n# \u2560\u255031ff651f-b275-46d2-97e9-206c9926dfb8\n# \u2560\u2550258017ed-4bf0-4fdd-8239-2fc381e94d0c\n# \u2560\u255045d2cddd-adfe-470a-89bc-56fb5d5982dc\n# \u2560\u2550d607a5e3-78f5-4308-999f-bf49858004a7\n# \u2560\u2550c9254d06-75b9-47dc-8d29-495c80c9215d\n# \u255f\u250015fd5bd7-d2c4-4337-a2ad-0fc43ad2b4e0\n# \u2560\u2550248c158c-41bc-478f-be12-b7e4ab43544d\n# \u2560\u255072c6bdcd-6d6b-4bf4-a759-1c4256384352\n# \u2560\u2550c0634c74-9228-4d05-8146-3492aaf3a8ef\n# \u255f\u2500decac4e3-d5d3-4a51-a5bb-fdb658dec971\n# \u255f\u25002bb59351-cb34-45a7-bd58-72409adf48fa\n# \u255f\u25004aa39de7-db17-42d7-924f-abb486c03eed\n# \u255f\u2500d5ba2170-d687-4ef8-a7fc-e8fef48b3a2c\n# \u2560\u2550b385f71f-c608-4be7-a0b6-30a39397451e\n# \u255f\u2500c1480936-bc64-481d-a754-31d5a35a2d6d\n# \u2560\u2550c1cd29c9-b3dc-497b-b200-e6ad08356b39\n# \u255f\u25007d6a905a-2445-4569-8fe1-8e703b635218\n# \u2560\u25504b879529-0359-462e-b032-3bb95a11ac36\n# \u255f\u25003e54ccec-d960-4cc2-a34a-7fce0964addb\n", "meta": {"hexsha": "c2477b730a1a2c2002174cde99f9eb0e55e43856", "size": 6429, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Unbeatable Tic Tac Toe.jl", "max_stars_repo_name": "ctrekker/pluto-static-test", "max_stars_repo_head_hexsha": "1ad2ee3218399dd60ffcfd5991dcadcdd79020b7", "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": "Unbeatable Tic Tac Toe.jl", "max_issues_repo_name": "ctrekker/pluto-static-test", "max_issues_repo_head_hexsha": "1ad2ee3218399dd60ffcfd5991dcadcdd79020b7", "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": "Unbeatable Tic Tac Toe.jl", "max_forks_repo_name": "ctrekker/pluto-static-test", "max_forks_repo_head_hexsha": "1ad2ee3218399dd60ffcfd5991dcadcdd79020b7", "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": 31.0579710145, "max_line_length": 317, "alphanum_fraction": 0.7220407528, "num_tokens": 3071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7704492162256382}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.19\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.19\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u25500cbc946e-2164-11eb-1b0c-7d4c7a607b1e\n# \u2560\u25500cbcbdf2-2164-11eb-193d-2baa8a6bce0b\n# \u255f\u250070182cd8-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": "module TestOperators\nusing Test\nusing Operators\nusing LinearAlgebra\n\n@testset \"basic operators\" begin\n    # evaluation functional\n    f = x->sin(sum(x))\n    x = randn()\n    \u03b4 = Operators.Evaluation(x)\n    @test \u03b4(f) \u2248 f(x)\n\n    # 2d evaluation functional test\n    x = randn(2)\n    \u03b4 = Operators.Evaluation(x)\n    @test \u03b4(f) \u2248 f(x)\n    @test Operators.islinear(\u03b4)\n\n    # sum\n    \u03b4 = Operators.Evaluation.(x)\n    \u03b4 = Operators.Sum(\u03b4...)\n    @test \u03b4(f) \u2248 sum(f.(x))\n\n    # scaling\n    \u03b4 = 2\u03b4\n    @test Operators.isfunctional(\u03b4)\n    @test Operators.islinear(\u03b4)\n    @test \u03b4(f) \u2248 2sum(f.(x))\n\n    # dot\n\n    # shift\n    x = randn()\n    y = randn()\n    S = Operators.Shift(x)\n    \u03b4 = Operators.Evaluation(y)\n    @test \u03b4(S(f)) \u2248 f(y-x)\n\n# composition\n# println(Operators.Composition(\u03b4, S)(f))\n\nend\n\n@testset \"scalar differential operators\" begin\n    f(x) = sin(sum(x))\n    # del\n    \u2207 = Operators.del\n    # derivative\n    x = randn()\n    \u03b4 = Operators.\u03b4(x)\n    @test \u03b4(\u2207(f)) \u2248 cos(x)\n    # gradient\n    x = randn(2)\n    \u03b4 = Operators.Evaluation(x)\n    @test  \u03b4(\u2207(f)) \u2248 cos(sum(x)) * ones(2)\n\n    # laplacian\n    # \u0394 = Operators.Laplacian()\n    \u0394 = Operators.\u0394\n    x = randn()\n    \u03b4 = Operators.Evaluation(x)\n    @test \u03b4(\u0394(f)) \u2248 -sin(x)\n\n    x = randn(2)\n    \u03b4 = Operators.Evaluation(x)\n    @test  \u03b4(\u0394(f)) \u2248 sum(-sin(sum(x)) * ones(2))\n    # ODE operator\nend\n\n@testset \"vector differential operators\" begin\n\n    g(x) = [sin(sum(x)), cos(sum(x))]\n    Operators.outputvalue(::typeof(g)) = Operators.VectorValued()\n\n    # vector del, scalar input\n    \u2207 = Operators.\u2207\n    @test \u2207(g)(0.) \u2248 [1, 0]\n\n    # vector del, vector input\n    x = randn(2)\n    @test \u2207(g)(x) \u2248 [[cos(sum(x)) cos(sum(x))]; [-sin(sum(x)) -sin(sum(x))]]\n\n    # vector laplacian, scalar input\n    \u0394 = Operators.\u0394\n    println(\u0394(g)(1.))\n\n    # vector laplacian, vector input\n    # println(\u0394(g)(randn(2)))\n\n    # curl\n    f(x, y, z) = [y, -x, zero(z)]\n    f(x::AbstractVector) = f(x...)\n    x = randn(3)\n    @test (\u2207 \u00d7 f)(x) \u2248 [0, 0, -2]\n\n    f(x, y, z) = [zero(x), -x^2, zero(z)]\n    f(x::AbstractVector) = f(x...)\n    x = randn(3)\n    @test (\u2207 \u00d7 f)(x) \u2248 [0, 0, -2x[1]]\nend\n\nend # TestOperators\n", "meta": {"hexsha": "68e261ea83ae679f591ca22db216484936cd09fd", "size": 2147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/operators.jl", "max_stars_repo_name": "MingChiangChang/OptimizationAlgorithms.jl", "max_stars_repo_head_hexsha": "90380fd8526d1eba6037036fbc472e40134e7770", "max_stars_repo_licenses": ["MIT"], "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/operators.jl", "max_issues_repo_name": "MingChiangChang/OptimizationAlgorithms.jl", "max_issues_repo_head_hexsha": "90380fd8526d1eba6037036fbc472e40134e7770", "max_issues_repo_licenses": ["MIT"], "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/operators.jl", "max_forks_repo_name": "MingChiangChang/OptimizationAlgorithms.jl", "max_forks_repo_head_hexsha": "90380fd8526d1eba6037036fbc472e40134e7770", "max_forks_repo_licenses": ["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.8446601942, "max_line_length": 76, "alphanum_fraction": 0.5444806707, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7704492083701058}}
{"text": "using Base: Int64\nusing BioCCP\n@testset \"BioCCP\" begin\n    \n    n = 20\n\n    # Equal probabilities\n    p_uniform = ones(n)/n\n\n    # Probabilities following Zipf's law\n    \u03c1 = 10\n\t\u03b1 = exp(log(\u03c1)/(n-1))\n\tp_zipf = collect(\u03b1.^-(1:n))\n    p_zipf = p_zipf ./ sum(p_zipf)\n\n    @testset \"Expectation\" begin\n        @test expectation_minsamplesize(n; p = p_uniform) isa Int64\n        @test expectation_minsamplesize(n; p = p_uniform) == Int(ceil(n*sum(1 ./ (1:n))))\n        @test expectation_minsamplesize(n; p = p_uniform) < expectation_minsamplesize(n; p = p_zipf)\n        @test expectation_minsamplesize(n; p = p_uniform, m = 1) < expectation_minsamplesize(n; p = p_uniform, m = 2)\n        @test Int(ceil(expectation_minsamplesize(n; p = p_uniform, m = 1, r = 1)/3)) == expectation_minsamplesize(n; p = p_uniform, m = 1, r = 3)\n    end\n\n    @testset \"Standard deviation\" begin\n        @test std_minsamplesize(n; p = p_uniform) isa Int64\n        @test std_minsamplesize(n; p = p_uniform) < std_minsamplesize(n; p = p_zipf)\n        @test std_minsamplesize(n; p = p_uniform, m = 1) < std_minsamplesize(n; p = p_uniform, m = 2)\n    end \n\n    t = 500\n\n    @testset \"Success probability\" begin\n        @test success_probability(n, t; p = p_uniform) isa Float64\n        @test success_probability(n, t; p = p_uniform) > success_probability(n, t; p = p_zipf)\n        @test success_probability(n, t; p = p_uniform, m = 1) > success_probability(n, t; p = p_uniform, m = 2)\n        @test all(success_probability(n, t; p = p_uniform) .< success_probability.(n, [t+10, t+100, t+1000]; p = p_uniform))\n        @test all(success_probability.(n, [1, 5, 10, 100, 500]) .<= 1)\n        @test all(success_probability.(n, [1, 5, 10, 100, 500]) .>= 0)\n\n    end\n\n    @testset \"Expected fraction collected\" begin\n        @test expectation_fraction_collected(n, t; p = p_uniform) isa Float64\n        @test expectation_fraction_collected(n, t; p = p_uniform) > expectation_fraction_collected(n, t; p = p_zipf)\n        @test all(expectation_fraction_collected(n, t; p = p_uniform) .< expectation_fraction_collected.(n, [t+10, t+100, t+1000]; p = p_uniform))\n        @test all(expectation_fraction_collected.(n, [1, 10, 100, 1000, 10000]) .<= 1)\n        @test all(expectation_fraction_collected.(n, [1, 10, 100, 1000, 10000]) .>= 0)\n\n    end\n\n    k = 2\n    p\u1d62 = 0.005\n    r = 3\n\n    @testset \"Probability occurence\" begin\n        @test prob_occurrence_module(p\u1d62, t, r, k) isa Float64\n        @test all(prob_occurrence_module.(p\u1d62, [0, 10, 100, 1000, 10000], r, k) .>= 0)\n        @test all(prob_occurrence_module.(p\u1d62, [0, 10, 100, 1000, 10000], r, k) .<= 1)\n    end\nend\n", "meta": {"hexsha": "50fc8deac5027de8a5109503a96194ee02e8f7a3", "size": 2632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/BioCCP.jl", "max_stars_repo_name": "kirstvh/BioCCP.jl", "max_stars_repo_head_hexsha": "f4c9208f618f15e63cc6aaf5748b5b16dfeeb6e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-12T05:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T14:09:59.000Z", "max_issues_repo_path": "test/BioCCP.jl", "max_issues_repo_name": "kirstvh/BioCCP", "max_issues_repo_head_hexsha": "f4c9208f618f15e63cc6aaf5748b5b16dfeeb6e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-25T14:33:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T13:36:52.000Z", "max_forks_repo_path": "test/BioCCP.jl", "max_forks_repo_name": "kirstvh/BioCCP", "max_forks_repo_head_hexsha": "f4c9208f618f15e63cc6aaf5748b5b16dfeeb6e6", "max_forks_repo_licenses": ["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.1475409836, "max_line_length": 146, "alphanum_fraction": 0.6360182371, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.7703903972075341}}
{"text": "using DelayEmbeddings\nusing Test\nusing DynamicalSystemsBase\n\nprintln(\"\\nTesting traditional optimal embedding dimension...\")\ntest_value = (val, vmin, vmax) -> @test vmin <= val <= vmax\n\n@testset \"Embedding dimension estimation\" begin\ndiffeq = (atol = 1e-9, rtol = 1e-9, maxiters = typemax(Int))\ns_sin = sin.(0:0.1:1000)\nro = Systems.roessler(ones(3));\ndata = trajectory(ro,1000;\u0394t=0.1,diffeq)\ns_roessler = data[:,1]\nlo = Systems.lorenz96(4, [0.1, 0.2, 0.5, 0.1]; F = 16.0);\ndata = trajectory(lo,5000.0;\u0394t=0.05, Ttr = 100.0, diffeq)\ns_lorenz = data[:,1]\n\n@testset \"Caos method\" begin\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_roessler, \"afnn\")\n    @test 3 \u2264 size(\ud835\udc9f, 2) \u2264 5\n\n    E2s = DelayEmbeddings.stochastic_indicator(s_roessler, \u03c4, 1:6)\n    @test minimum(E2s) < 0.3\n\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_roessler, \"afnn\"; metric = Chebyshev())\n    @test 3 \u2264 size(\ud835\udc9f, 2) \u2264 5\n\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_lorenz, \"afnn\")\n    @test 4 \u2264 size(\ud835\udc9f, 2) \u2264 8\n\n    #Test against random signal\n    E2s = DelayEmbeddings.stochastic_indicator(rand(10000), 1, 1:5)\n    @test minimum(E2s) > 0.9\nend\n\n@testset \"fnn method\" begin\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_sin, \"fnn\")\n    @test 1 \u2264 size(\ud835\udc9f, 2) \u2264 3\n\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_roessler, \"fnn\")\n    @test 3 \u2264 size(\ud835\udc9f, 2) \u2264 5\n\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_lorenz, \"fnn\")\n    @test 4 \u2264 size(\ud835\udc9f, 2) \u2264 8\nend\n\n@testset \"ifnn method\" begin\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_sin, \"ifnn\")\n    @test 1 \u2264 size(\ud835\udc9f, 2) \u2264 4\n\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_roessler, \"ifnn\")\n    @test 3 \u2264 size(\ud835\udc9f, 2) \u2264 5\n\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_roessler, \"ifnn\"; metric = Chebyshev())\n    @test 3 \u2264 size(\ud835\udc9f, 2) \u2264 5\n\n    \ud835\udc9f, \u03c4, x = optimal_traditional_de(s_lorenz, \"ifnn\")\n    @test 4 \u2264 size(\ud835\udc9f, 2) \u2264 8\nend\n\nend\n", "meta": {"hexsha": "42e1c3d9aab9de956728665c892fc251ad07d58c", "size": 1778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/traditional/embedding_dimension_test.jl", "max_stars_repo_name": "kahaaga/DelayEmbeddings.jl", "max_stars_repo_head_hexsha": "786c9cbdb98495629b68f7adaf380a9824826bea", "max_stars_repo_licenses": ["MIT"], "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/traditional/embedding_dimension_test.jl", "max_issues_repo_name": "kahaaga/DelayEmbeddings.jl", "max_issues_repo_head_hexsha": "786c9cbdb98495629b68f7adaf380a9824826bea", "max_issues_repo_licenses": ["MIT"], "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/traditional/embedding_dimension_test.jl", "max_forks_repo_name": "kahaaga/DelayEmbeddings.jl", "max_forks_repo_head_hexsha": "786c9cbdb98495629b68f7adaf380a9824826bea", "max_forks_repo_licenses": ["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.6774193548, "max_line_length": 78, "alphanum_fraction": 0.6394825647, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7703903865533608}}
{"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)(\u03b8)\n    @unpack y = problem   # extract the data\n    @unpack mu, sigma = \u03b8\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\u211d\u208a), )\n\n  # Use Flux for the gradient.\n\n  P = TransformedLogDensity(trans, p)\n  \u2207P = ADgradient(autodiff, P)\n\n  # Sample from the posterior.\n  results = mcmc_with_warmup(Random.GLOBAL_RNG, \u2207P, 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(; \u03bc=0, \u03c3=1, Nd, kwargs...) = (y=rand(Normal(\u03bc, \u03c3), 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 ; \u03b7::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 ; \u03b7::Real = 1.1)\n    if \u03b7<0; throw(ErrorException(\"requires positive eta (RRA)\")); end\n    \u03b7 == 1 ? (return u_log(x)::Real)  :  (return (x^(1-\u03b7)/(1-\u03b7))::Real)\nend # u_crra\n\n\n# ----------------\n\"\"\"\n    u_cara(x::Real ; \u03b1::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 ; \u03b1::Real = 1.0)\n    if \u03b1<0; throw(ErrorException(\"requires positive alpha (ARA)\")); end\n    return (-exp(-\u03b1 * x))::Real\nend # u_cara\n\n\n# ----------------\n\"\"\"\n    u_ces2(x1::Real, x2::Real ; \u03c1::Real = 1.0, \u03b2::Real = 1.0, \u03b1::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 ; \u03c1::Real = 1.0, \u03b2::Real = 1.0, \u03b1::Real = 0.5 )\n    if \u03c1 == 0\n        return ( ( x1^\u03b1 * x2^(1-\u03b1) )^\u03b2 )::Real\n    elseif \u03c1 == -Inf\n        return ( \u03b2 * min(x1,x2) )::Real\n    end # if\n    return ( ( \u03b1*x1^\u03c1 + (1-\u03b1)*x2^\u03c1 )^(\u03b2/\u03c1) )::Real\nend # u_ces2\n\n\n# ----------------\n\"\"\"\n    u_cesk(X::Vector ; W::Vector = ones(length(X)) , \u03b2::Real = 1.0, \u03c1::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)) , \u03b2::Real = 1.0, \u03c1::Real = 1.0 )\n    if \u03c1 == 0\n        return ( ( u_cdk(X, W=W) )^\u03b2 )::Real\n    elseif \u03c1 == -Inf\n        return ( \u03b2 * 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 ^ \u03c1\n    end # for\n    return ( U^(\u03b2/\u03c1) )::Real\nend # u_cesk\n\n\n# ----------------\n\"\"\"\n    u_cd1(x::Real ; \u03b8::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 ; \u03b8::Real = 1.0)\n    return (x^\u03b8)::Real\nend # u_cd1\n\n\n\n# ----------------\n\"\"\"\n    u_cd2(x::Real ; \u03b8::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 ; \u03b8::Real = 0.5)\n    return (x1^\u03b8 * x2^(1-\u03b8))::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 ; \u03b2::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 ; \u03b2::Real = 1.0 )\n    return ( log(x1) + \u03b2 * 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 Printf\n\nvandercorput(num::Integer, base::Integer) = sum(d * Float64(base) ^ -ex for (ex, d) in enumerate(digits(num, base)))\n\nfor base in 2:9\n    @printf(\"%10s %i:\", \"Base\", base)\n    for num in 0:9 @printf(\"%7.3f\", vandercorput(num, base)) end\n    println(\" [...]\")\nend\n", "meta": {"hexsha": "9aac8c714f4dace9888de17b655e4f01c81ce9a6", "size": 277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/van-der-corput-sequence.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/van-der-corput-sequence.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/van-der-corput-sequence.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.7, "max_line_length": 116, "alphanum_fraction": 0.6173285199, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7703732216202553}}
{"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": "\nA = [[+4.  +5.  -2.]\n     [+7.  -1.  +2.]\n     [+3.  +1.  +4.]]\nb = [-14., +42., +28.]\nx = [+4., -4., +5.]\n\nlu = LUSolverLAPACK(A, b)\n\nfactorize!(lu)\nsolve!(lu)\n\n@test lu.b == x\n", "meta": {"hexsha": "4918dd4544cf07c8b701ccf9ff590cfef13a33e9", "size": 179, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/solvers/linear_solvers_tests.jl", "max_stars_repo_name": "ChrisRackauckas/GeomDAE.jl", "max_stars_repo_head_hexsha": "dbaf5d909dc1686d211312f4143ad7355ffbc325", "max_stars_repo_licenses": ["MIT"], "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/solvers/linear_solvers_tests.jl", "max_issues_repo_name": "ChrisRackauckas/GeomDAE.jl", "max_issues_repo_head_hexsha": "dbaf5d909dc1686d211312f4143ad7355ffbc325", "max_issues_repo_licenses": ["MIT"], "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/solvers/linear_solvers_tests.jl", "max_forks_repo_name": "ChrisRackauckas/GeomDAE.jl", "max_forks_repo_head_hexsha": "dbaf5d909dc1686d211312f4143ad7355ffbc325", "max_forks_repo_licenses": ["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.7857142857, "max_line_length": 25, "alphanum_fraction": 0.3631284916, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7703109506430721}}
{"text": "doc\"\"\"\n    TDist(\u03bd)\n\nThe *Students T distribution* with `\u03bd` 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    \u03bd::Float64\n\n    TDist(\u03bd::Real) = (@check_args(TDist, \u03bd > zero(\u03bd)); new(\u03bd))\nend\n\n@distr_support TDist -Inf Inf\n\n\n#### Parameters\n\ndof(d::TDist) = d.\u03bd\nparams(d::TDist) = (d.\u03bd,)\n\n\n#### Statistics\n\nmean(d::TDist) = d.\u03bd > 1.0 ? 0.0 : NaN\nmedian(d::TDist) = 0.0\nmode(d::TDist) = 0.0\n\nfunction var(d::TDist)\n    \u03bd = d.\u03bd\n    \u03bd > 2.0 ? \u03bd / (\u03bd - 2.0) :\n    \u03bd > 1.0 ? Inf : NaN\nend\n\nskewness(d::TDist) = d.\u03bd > 3.0 ? 0.0 : NaN\n\nfunction kurtosis(d::TDist)\n    \u03bd = d.\u03bd\n    \u03bd > 4.0 ? 6.0 / (\u03bd - 4.0) :\n    \u03bd > 2.0 ? Inf : NaN\nend\n\nfunction entropy(d::TDist)\n    h = 0.5 * d.\u03bd\n    h1 = h + 0.5\n    h1 * (digamma(h1) - digamma(h)) + 0.5 * log(d.\u03bd) + lbeta(h, 0.5)\nend\n\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns TDist tdist \u03bd\n\nrand(d::TDist) = StatsFuns.Rmath.tdistrand(d.\u03bd)\n\nfunction cf(d::TDist, t::Real)\n    t == 0 && return complex(1.0)\n    h = d.\u03bd * 0.5\n    q = d.\u03bd * 0.25\n    t2 = t*t\n    complex(2*(q*t2)^q*besselk(h,sqrt(d.\u03bd)*abs(t))/gamma(h))\nend\n\ngradlogpdf(d::TDist, x::Float64) = -((d.\u03bd + 1.0) * x) / (x^2 + d.\u03bd)\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\u00e9non_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\u00e9non_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\u00e9non-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\u00e9non_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": "#=\nYou are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up.\n\nCompute how many units of water remain trapped on the map in O(N) time and O(1) space.\n\nFor example, given the input [2, 1, 2], we can hold 1 unit of water in the middle.\n\nGiven the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water.\n=#\n\nfunction watertrapped(elevation_map::Array{Int64, 1})\n    sum_water = 0\n    for map_unit in 2:length(elevation_map)-1\n        max_left = maximum(elevation_map[1:map_unit-1])\n        max_right = maximum(elevation_map[map_unit+1:end])\n        water_trapped = maximum([minimum([max_left, max_right]) - elevation_map[map_unit], 0])\n        sum_water = sum_water + water_trapped\n    end\n    return sum_water\nend\n", "meta": {"hexsha": "44212a4ff907277fc00928154db5b8963f929707", "size": 1027, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem30_watertrapped_in_elevation_map.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/problem30_watertrapped_in_elevation_map.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/problem30_watertrapped_in_elevation_map.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": 48.9047619048, "max_line_length": 232, "alphanum_fraction": 0.7224926972, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7703109469344177}}
{"text": "\"\"\"\n    Compression(c, d, i; \u03c3 = 1.0, \u03bc = 0.0)\n\nMaps ``\u211d \u2192 (-1, 1)``.\n\n# Arguments\n- `c`: the \"compression\", i.e., the map ``\u211d \u2192 (-1, 1)``,\n- `d`: the \"decompression\", i.e., the map ``(-1, 1) \u2192 \u211d``,\n- `i`: the jacobian of the map, i.e., ``\u2202d(\u03c4) /\u2202\u03c4``,\n- `\u03c3`, `\u03bc`: 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\u03c3::Float64\n\t\u03bc::Float64\n\tfunction Compression(c, d, i; \u03c3 = 1.0, \u03bc = 0.0)\n\t\t\u03c3 \u2264 0.0 && error(\"\u03c3 needs to be positive\")\n\t\tnew(c, d, i, \u03c3, \u03bc)\n\tend\nend\n\n\"\"\"\n    Algebraic(; \u03c3 = 1.0, \u03bc = 0.0)\n\nMaps ``\u211d \u2192 (-1, 1)`` by ``t \u21a6 \\\\frac{t}{1 + |t|}``.\nEquivalent symbol is `:algebraic`.\n\"\"\"\nAlgebraic(; \u03c3 = 1.0, \u03bc = 0.0) = Compression(\n\tt ->   t / (1.0 + abs(t)),\n\t\u03c4 ->   \u03c4 / (1.0 - abs(\u03c4)),\n\t\u03c4 -> 1.0 / (1.0 - abs(\u03c4))^2, # == (1.0 + abs( \u03c4 / (1.0 - abs(\u03c4)) ) )^2\n\t\u03c3 = \u03c3, \u03bc = \u03bc\n)\n\n\"\"\"\n    Exponential(; \u03c3 = 1.0, \u03bc = 0.0)\n\nMaps ``\u211d \u2192 (-1, 1)`` by ``t \u21a6 \\\\mathrm{tanh}(t)``.\nEquivalent symbol is `:exponential`.\n\"\"\"\nExponential(; \u03c3 = 1.0, \u03bc = 0.0) = Compression(\n\tt -> tanh(t),\n\t\u03c4 -> atanh(\u03c4),\n\t\u03c4 -> 1.0 / (1.0 - \u03c4^2), # == cosh(atanh(\u03c4))^2\n\t\u03c3 = \u03c3, \u03bc = \u03bc\n)\n\n\"\"\"\n    Trigonometric(; \u03c3 = 1.0, \u03bc = 0.0)\n\nMaps ``\u211d \u2192 (-1, 1)`` by ``t \u21a6 \\\\frac{2}{\u03c0} \\\\mathrm{tan}^{-1}(t)``.\nEquivalent symbol is `:trigonometric`.\n\"\"\"\nTrigonometric(; \u03c3 = 1.0, \u03bc = 0.0) = Compression(\n\tt -> 2.0 * atan(t) / \u03c0,\n\t\u03c4 -> tan(\u03c0*\u03c4/2.0),\n\t\u03c4 -> \u03c0 * (1.0 + tan(\u03c0*\u03c4/2.0)^2) / 2.0,\n\t\u03c3 = \u03c3, \u03bc = \u03bc\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# \u2554\u2550\u2561 7c62a2c4-9159-11eb-1b54-452017ea90d9\nusing LinearAlgebra, SparseArrays\n\n# \u2554\u2550\u2561 7ad16586-9162-11eb-1d94-5188eb8d4c5d\nusing DifferentialEquations, Plots\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 aff71d6e-9158-11eb-0559-cb7334f4a624\nL = 0.1 # Length of rod\n\n# \u2554\u2550\u2561 3771dab8-9159-11eb-3a69-cd9b94a10399\nTf = 60.0 # Final simulation time\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 86a40dc8-9158-11eb-16a3-1f776d6bde4e\nbegin\n\t\u03bb = 45.0;    # Thermal conductivity\n\t\u03c1 = 7800.0;  # Mass density\n\tcap = 480.0; # Specific heat capacitivity\nend\n\n# \u2554\u2550\u2561 9e8ee0a2-9158-11eb-0210-4513221b7823\n\u03b1 = \u03bb/(cap * \u03c1)   # Diffusivity\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7c9e9a4a-9159-11eb-3dda-59d2aa15f32a\nbegin\n\th = 10.0; # Heat transfer coefficient\n\t\u03f5 = 0.6;  # Emissivity\n\tsb = 5.67*10^(-8) # Stefan-Boltzmann constant\n\tk = \u03f5 * sb; \t  # Radiation coefficient\nend\n\n# \u2554\u2550\u2561 c5da798e-9160-11eb-1d16-75ce792ef2fe\n\u03b8amb = 298.0 # Ambient temperature in Kelvin\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3487893a-915c-11eb-3a04-1fdd31009413\nN = 101 # Number of grid elements\n\n# \u2554\u2550\u2561 39663578-915c-11eb-108c-2718b706729e\n\u0394x = L/(N-1) # Finite discretization   \n\n# \u2554\u2550\u2561 3468092a-915c-11eb-1719-d1b9b04b68e0\n# Diffusion matrix\nM = spdiagm(-1 => ones(N-1), 0 => -2*ones(N), 1 => ones(N-1));\n\n# \u2554\u2550\u2561 344c1bb6-915c-11eb-2be7-35f340f4caa8\nMatrix(M)[1:5,1:5]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3414b70c-915c-11eb-2606-4d1ad425d3ab\n# First row\nM[1,2] = 2;\n\n# \u2554\u2550\u2561 33cd51a0-915c-11eb-3c62-efc367e08126\n# Last row\nM[end,end-1] = 2;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 328a1ed0-9160-11eb-0892-7d0a9d05a54d\n# Heat Equation as ODE\nfunction heat_eq!(d\u03b8, \u03b8, p, t)\n\t\n\tN = size(\u03b8)\n\t\u03a6out = zeros(N);\n\t\n\t\u03a6out[1] = -h * (\u03b8[1] - \u03b8amb) - k*(\u03b8[1]^4 - \u03b8amb^4)\n\n\t\u03a6out[end] = -h * (\u03b8[end] - \u03b8amb) - k*(\u03b8[end]^4 - \u03b8amb^4)\n\n    d\u03b8 .= (1/\u0394x^2) * \u03b1 * M * \u03b8 + (2/\u0394x) * \u03b1 * \u03a6out\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 91a272be-9162-11eb-1046-8dd9e33653e5\n\u03b8\u2080 = 10^3 * ones(N)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f85a2d4a-9161-11eb-0e0f-851c0750832a\n\u0394t_ul = (0.5*\u0394x^2)/\u03b1 # upper limit of sampling time\n\n# \u2554\u2550\u2561 5aa78f74-9162-11eb-1bd4-c96f2b90e586\n\u0394t = 10^(-2) # Sampling time\n\n# \u2554\u2550\u2561 66ba8b22-9162-11eb-13b0-b14dfcead641\nmd\"## Simulation\"\n\n# \u2554\u2550\u2561 861018de-9162-11eb-2a01-2354acd868e2\ntspan = (0.0, Tf)\n\n# \u2554\u2550\u2561 e0e033e8-9162-11eb-3fe6-05565991ce77\n# 1-dimensional grid\nxspan = 0 : \u0394x : L\n\n# \u2554\u2550\u2561 01b373f0-9163-11eb-3f35-3f645825720f\nprob = ODEProblem( heat_eq!, \u03b8\u2080, tspan ) # ODE Problem\n\n# \u2554\u2550\u2561 0103888c-9163-11eb-16ae-371cd6d04c45\nsol = solve(prob,Euler(),dt=\u0394t,progress=true, save_everystep=false, save_start=true) # Solving the ODE\n\n# \u2554\u2550\u2561 08dcb90e-9163-11eb-2ff0-7129add62934\nplot(xspan, sol.u[2], xlabel = \"Position x\", ylabel=\"Temperature\", legend=false)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u250044df6004-9158-11eb-1a63-651d7dca957b\n# \u2560\u2550aff71d6e-9158-11eb-0559-cb7334f4a624\n# \u2560\u25503771dab8-9159-11eb-3a69-cd9b94a10399\n# \u255f\u250044dbf81c-9159-11eb-2920-27ee60a7db9a\n# \u2560\u255086a40dc8-9158-11eb-16a3-1f776d6bde4e\n# \u2560\u25509e8ee0a2-9158-11eb-0210-4513221b7823\n# \u255f\u2500a4f1e1e2-9158-11eb-0754-a70399a341ba\n# \u2560\u25507c9e9a4a-9159-11eb-3dda-59d2aa15f32a\n# \u2560\u2550c5da798e-9160-11eb-1d16-75ce792ef2fe\n# \u255f\u25007c80218c-9159-11eb-301a-95a428fb76d9\n# \u2560\u25507c62a2c4-9159-11eb-1b54-452017ea90d9\n# \u2560\u25503487893a-915c-11eb-3a04-1fdd31009413\n# \u2560\u255039663578-915c-11eb-108c-2718b706729e\n# \u2560\u25503468092a-915c-11eb-1719-d1b9b04b68e0\n# \u2560\u2550344c1bb6-915c-11eb-2be7-35f340f4caa8\n# \u255f\u2500342fe676-915c-11eb-3f22-1d20d5b502ed\n# \u2560\u25503414b70c-915c-11eb-2606-4d1ad425d3ab\n# \u2560\u255033cd51a0-915c-11eb-3c62-efc367e08126\n# \u255f\u250033af0164-915c-11eb-30f0-313d926c2dae\n# \u2560\u2550328a1ed0-9160-11eb-0892-7d0a9d05a54d\n# \u255f\u250066d5aee4-9161-11eb-1ef1-2193d9c2f6a2\n# \u2560\u255091a272be-9162-11eb-1046-8dd9e33653e5\n# \u255f\u25001571f3f2-9162-11eb-0b63-ff4e25a07572\n# \u2560\u2550f85a2d4a-9161-11eb-0e0f-851c0750832a\n# \u2560\u25505aa78f74-9162-11eb-1bd4-c96f2b90e586\n# \u2560\u255066ba8b22-9162-11eb-13b0-b14dfcead641\n# \u2560\u25507ad16586-9162-11eb-1d94-5188eb8d4c5d\n# \u2560\u2550861018de-9162-11eb-2a01-2354acd868e2\n# \u2560\u2550e0e033e8-9162-11eb-3fe6-05565991ce77\n# \u2560\u255001b373f0-9163-11eb-3f35-3f645825720f\n# \u2560\u25500103888c-9163-11eb-16ae-371cd6d04c45\n# \u2560\u255008dcb90e-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\u03b2 = 5.0;\nx\u2080 = [-1.0];\nM = 1.0;\nseed = 100;\n\u0394t = 2e-1;\nn_iters = 10^4; # number of samples\nn\u0394t = 10^1; # number of Verlet steps per HMC iteration\nn_save_iters=10;\n\nV = x->DoubleWell(x);\ncfg = ForwardDiff.GradientConfig(V, x\u2080);\ngradV! = (gradV, x)-> ForwardDiff.gradient!(gradV, V, x, cfg);\n\n# second moment and energy obsrevables\nf\u2081 = x-> x[1]^2;\nf\u2082 = x-> V(x[1]);\nobservables = (f\u2081, f\u2082);\n\nsampler = HMC(V, gradV!, \u03b2, M, \u0394t, n\u0394t);\n\nRandom.seed!(100);\nXvals,_ = sample_trajectory(x\u2080, sampler, options=MDOptions(n_iters=n_iters,n_save_iters=n_save_iters));\nf\u2081_estimate = mean(f\u2081.(Xvals));\nf\u2082_estimate = mean(f\u2082.(Xvals));\n@printf(\"f\u2081 estimate with %d samples: %g\\n\",length(Xvals), f\u2081_estimate);\n@printf(\"f\u2082 estimate with %d samples: %g\\n\", length(Xvals), f\u2082_estimate);\nRandom.seed!(100);\nobservable_samples = sample_observables(x\u2080, sampler, observables, options=MDOptions(n_iters=n_iters,n_save_iters=n_save_iters));\n@printf(\"f\u2081 estimate with %d samples: %g\\n\",length(observable_samples), mean(observable_samples[1,:]));\n@printf(\"f\u2082 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\u2013158, 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": " @printf(\"\\nTesting linear operators\\n\")\n\n######## Conv ############\nn,m = 5, 6\nh = randn(m)\nop = Conv(Float64,(n,),h)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n+m-1), verb)\ny2 = conv(x1,h)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nop = Conv(x1,h)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\n########## DCT ############\nn = 4\nop = DCT(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = dct(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nop = DCT((n,))\nop = DCT(n,n)\nop = DCT(Complex{Float64}, n,n)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == true\n@test is_AAc_diagonal(op)     == true\n@test is_orthogonal(op)       == true\n@test is_invertible(op)       == true\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\nm = 10\nop = DCT(n,m)\nx1 = randn(n,m)\n\n@test norm(op'*(op*x1) - x1) <= 1e-12\n@test diag_AAc(op) == 1.\n@test diag_AcA(op) == 1.\n\n######### IDCT ############\nn = 4\nop = IDCT(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = idct(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nop = IDCT((n,))\nop = IDCT(n,n)\nop = IDCT(Complex{Float64}, n,n)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == true\n@test is_AAc_diagonal(op)     == true\n@test is_orthogonal(op)       == true\n@test is_invertible(op)       == true\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\nm = 10\nop = IDCT(n,m)\nx1 = randn(n,m)\n\n@test norm(op'*(op*x1) - x1) <= 1e-12\n@test diag_AAc(op) == 1.\n@test diag_AcA(op) == 1.\n\n######## DFT ############\n# seems like there is an object called DFT in Base julia 0.7 (however in 1.0 was rm)\nn,m = 4,7\n\nop = AbstractOperators.DFT(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = fft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Complex{Float64},(n,))\nx1 = randn(n)+im*randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = fft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = fft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Complex{Float64},(n,))\nx1 = randn(n)+im*randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = fft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Float64,(n,),1)\nx1 = randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = fft(x1,1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Complex{Float64},(n,),1)\nx1 = randn(n)+im*randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = fft(x1,1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Float64,(n,m))\nx1 = randn(n,m)\ny1 = test_op(op, x1, fft(randn(n,m)), verb)\ny2 = fft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Complex{Float64},(n,m))\nx1 = randn(n,m)+im*randn(n,m)\ny1 = test_op(op, x1, fft(randn(n,m)), verb)\ny2 = fft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Float64,(m,n),1)\nx1 = randn(m,n)\ny1 = test_op(op, x1, fft(randn(m,n)), verb)\ny2 = fft(x1,1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.DFT(Complex{Float64},(n,m),2)\nx1 = randn(n,m)+im*randn(n,m)\ny1 = test_op(op, x1, fft(randn(n,m)), verb)\ny2 = fft(x1,2)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nop = AbstractOperators.DFT((n,))\nop = AbstractOperators.DFT(n,n)\nop = AbstractOperators.DFT(Complex{Float64}, n,n)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == true\n@test is_AAc_diagonal(op)     == true\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == true\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\nm = 10\nop = AbstractOperators.DFT(n,m)\nx1 = randn(n,m)\ny1 = op*x1\n@test norm(op'*(op*x1) - diag_AcA(op)*x1) <= 1e-12\n@test norm(op*(op'*y1) - diag_AAc(op)*y1) <= 1e-12\n\n######### IDFT ############\nn,m = 5,6\n\nop = IDFT(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = ifft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = IDFT(Complex{Float64},(n,))\nx1 = randn(n)+im*randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = ifft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = IDFT(Float64,(n,),1)\nx1 = randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = ifft(x1,1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = IDFT(Complex{Float64},(n,),1)\nx1 = randn(n)+im*randn(n)\ny1 = test_op(op, x1, fft(randn(n)), verb)\ny2 = ifft(x1,1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = AbstractOperators.IDFT(Float64,(n,m))\nx1 = randn(n,m)\ny1 = test_op(op, x1, fft(randn(n,m)), verb)\ny2 = ifft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = IDFT(Complex{Float64},(n,m))\nx1 = randn(n,m)+im*randn(n,m)\ny1 = test_op(op, x1, fft(randn(n,m)), verb)\ny2 = ifft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = IDFT(Float64,(m,n),1)\nx1 = randn(m,n)\ny1 = test_op(op, x1, fft(randn(m,n)), verb)\ny2 = ifft(x1,1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = IDFT(Complex{Float64},(m,n),2)\nx1 = randn(m,n)+im*randn(m,n)\ny1 = test_op(op, x1, fft(randn(m,n)), verb)\ny2 = ifft(x1,2)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 4,19,5\nop = IDFT(Complex{Float64},(n,m,l),2)\nx1 = fft(randn(n,m,l),2)\ny1 = test_op(op, x1, ifft(x1,2), verb)\ny2 = ifft(x1,2)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 4,18,5\nop = IDFT(Complex{Float64},(n,m,l),(1,2))\nx1 = fft(randn(n,m,l),(1,2))\ny1 = test_op(op, x1, ifft(x1,(1,2)), verb)\ny2 = ifft(x1,(1,2))\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nop = IDFT(Complex{Float64},(n,m,l),(3,2))\nx1 = fft(randn(n,m,l),(3,2))\ny1 = test_op(op, x1, ifft(x1,(3,2)), verb)\ny2 = ifft(x1,(3,2))\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nop = IDFT((n,))\nop = IDFT(n,n)\nop = IDFT(Complex{Float64}, n,n)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == true\n@test is_AAc_diagonal(op)     == true\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == true\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\nm = 10\nop = IDFT(n,m)\nx1 = randn(n,m)\ny1 = op*x1\n@test norm(op'*(op*x1) - diag_AcA(op)*x1) <= 1e-12\n@test norm(op*(op'*y1) - diag_AAc(op)*y1) <= 1e-12\n\n####### RDFT ############\nn = 4\nop = RDFT(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, rfft(x1), verb)\ny2 = rfft(x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 4,8,5\nop = RDFT(Float64,(n,m,l),2)\nx1 = randn(n,m,l)\ny1 = test_op(op, x1, rfft(x1,2), verb)\ny2 = rfft(x1,2)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nop = RDFT((n,))\nop = RDFT(n,n)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == true\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == false\n\n####### IRDFT ############\nn = 12\nop = IRDFT(Complex{Float64},(div(n,2)+1,),n)\nx1 = rfft(randn(n))\ny1 = test_op(op, x1,irfft(randn(div(n,2)+1),n), verb)\ny2 = irfft(x1,n)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn = 11\nop = IRDFT(Complex{Float64},(div(n,2)+1,),n)\nx1 = rfft(randn(n))\ny1 = test_op(op, x1,irfft(randn(div(n,2)+1),n), verb)\ny2 = irfft(x1,n)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 4,19,5\nop = IRDFT(Complex{Float64},(n,div(m,2)+1,l),m,2)\nx1 = rfft(randn(n,m,l),2)\ny1 = test_op(op, x1, irfft(x1,m,2), verb)\ny2 = irfft(x1,m,2)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 4,18,5\nop = IRDFT(Complex{Float64},(n,div(m,2)+1,l),m,2)\nx1 = rfft(randn(n,m,l),2)\ny1 = test_op(op, x1, irfft(x1,m,2), verb)\ny2 = irfft(x1,m,2)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 5,18,5\nop = IRDFT(Complex{Float64},(div(n,2)+1,m,l),n,1)\nx1 = rfft(randn(n,m,l),1)\ny1 = test_op(op, x1, irfft(x1,n,1), verb)\ny2 = irfft(x1,n,1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n## other constructors\nop = IRDFT((10,),19)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == true\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == false\n\n########## DiagOp ############\nn = 4\nd = randn(n)\nop = DiagOp(Float64,(n,),d)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = d.*x1\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn = 4\nd = randn(n)+im*randn(n)\nop = DiagOp(Float64,(n,),d)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n).+im*randn(n), verb)\ny2 = d.*x1\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn = 4\nd = pi\nop = DiagOp(Float64,(n,),d)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = d.*x1\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn = 4\nd = im\nop = DiagOp(Float64,(n,),d)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n)+im*randn(n), verb)\ny2 = d.*x1\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nd = randn(4)\nop = DiagOp(d)\n\nd = randn(4).+im\nop = DiagOp(d)\n\nn = 4\nd = pi\nop = DiagOp((n,), d)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == true\n@test is_AcA_diagonal(op)     == true\n@test is_AAc_diagonal(op)     == true\n@test is_orthogonal(op)       == false\n@test is_invertible(DiagOp(ones(10)))       == true\n@test is_invertible(DiagOp([ones(5);0]))    == false\n@test is_full_row_rank(op)    == true\n@test is_full_row_rank(DiagOp([ones(5);0]))    == false\n@test is_full_column_rank(op) == true\n@test is_full_column_rank(DiagOp([ones(5);0]))    == false\n\n@test diag(op) == d\n@test norm(op'*(op*x1) .- diag_AcA(op).*x1) <= 1e-12\n@test norm(op*(op'*x1) .- diag_AAc(op).*x1) <= 1e-12\n\nn = 4\nd = pi\nop = DiagOp((n,), d)\nx1 = randn(n)\n\n@test diag(op) == d\n@test norm(op'*(op*x1) .- diag_AcA(op).*x1) <= 1e-12\n@test norm(op*(op'*x1) .- diag_AAc(op).*x1) <= 1e-12\n\n########## Eye ############\nn = 4\nop = Eye(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n), verb)\n\n@test all(norm.(y1 .- x1) .<= 1e-12)\n\n# other constructors\nop = Eye(Float64, (n,))\nop = Eye((n,))\nop = Eye(n)\nop = Eye(x1)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == true\n@test is_diagonal(op)         == true\n@test is_AcA_diagonal(op)     == true\n@test is_AAc_diagonal(op)     == true\n@test is_orthogonal(op)       == true\n@test is_invertible(op)       == true\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\n@test diag(op) == 1\n@test diag_AcA(op) == 1\n@test diag_AAc(op) == 1\n\n######## Filt ############\nn,m = 15,2\nb,a = [1.;0.;1.;0.;0.], [1.;1.;1.]\nop = Filt(Float64,(n,),b,a)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = filt(b, a, x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nh = randn(10)\nop = Filt(Float64,(n,m),h)\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(n,m), verb)\ny2 = filt(h, [1.], x1)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# other constructors\nFilt(n,  b, a)\nFilt((n,m),  b, a)\nFilt(n,  h)\nFilt((n,),  h)\nFilt(x1, b, a)\nFilt(x1, b)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\n###### FiniteDiff ############\nn= 10\nop = FiniteDiff(Float64,(n,))\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n-1), verb)\ny1 = op*collect(range(0,stop=1,length=n))\n@test all(norm.(y1 .- 1/9) .<= 1e-12)\n\nI1, J1, V1 = SparseArrays.spdiagm_internal(0 => ones(n-1))\nI2, J2, V2 = SparseArrays.spdiagm_internal(1 => ones(n-1))\nB = -sparse(I1,J1,V1,n-1,n)+sparse(I2,J2,V2,n-1,n)\n\n@test norm(B*x1-op*x1) <= 1e-8\n\nn,m= 10,5\nop = FiniteDiff(Float64,(n,m))\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(n-1,m), verb)\ny1 = op*repeat(collect(range(0,stop=1,length=n)),1,m)\n@test all(norm.(y1 .- 1/9) .<= 1e-12)\n\nn,m= 10,5\nop = FiniteDiff(Float64,(n,m),2)\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(n,m-1), verb)\ny1 = op*repeat(collect(range(0,stop=1,length=n)),1,m)\n@test all(norm.(y1) .<= 1e-12)\n\nn,m,l= 10,5,7\nop = FiniteDiff(Float64,(n,m,l))\nx1 = randn(n,m,l)\ny1 = test_op(op, x1, randn(n-1,m,l), verb)\ny1 = op*reshape(repeat(collect(range(0,stop=1,length=n)),1,m*l),n,m,l)\n@test all(norm.(y1 .- 1/9) .<= 1e-12)\n\nn,m,l= 10,5,7\nop = FiniteDiff(Float64,(n,m,l),2)\nx1 = randn(n,m,l)\ny1 = test_op(op, x1, randn(n,m-1,l), verb)\ny1 = op*reshape(repeat(collect(range(0,stop=1,length=n)),1,m*l),n,m,l)\n@test all(norm.(y1) .<= 1e-12)\n\nn,m,l= 10,5,7\nop = FiniteDiff(Float64,(n,m,l),3)\nx1 = randn(n,m,l)\ny1 = test_op(op, x1, randn(n,m,l-1), verb)\ny1 = op*reshape(repeat(collect(range(0,stop=1,length=n)),1,m*l),n,m,l)\n@test all(norm.(y1) .<= 1e-12)\n\nn,m,l,i = 5,6,2,3\nop = FiniteDiff(Float64,(n,m,l,i),1)\nx1 = randn(n,m,l,i)\ny1 = test_op(op, x1, randn(n-1,m,l,i), verb)\ny1 = op*reshape(repeat(collect(range(0,stop=1,length=n)),1,m*l*i),n,m,l,i)\n@test all(norm.(y1 .- 1/(n-1)) .<= 1e-12)\n\nn,m,l,i = 5,6,2,3\nop = FiniteDiff(Float64,(n,m,l,i),4)\nx1 = randn(n,m,l,i)\ny1 = test_op(op, x1, randn(n,m,l,i-1), verb)\ny1 = op*reshape(repeat(collect(range(0,stop=1,length=n)),1,m*l*i),n,m,l,i)\n@test norm(y1) <= 1e-12\n\n@test_throws ErrorException FiniteDiff(Float64,(n,m,l), 4)\n\n## other constructors\nFiniteDiff((n,m))\nFiniteDiff(x1)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == false\n\n########## GetIndex ############\nn,m = 5,4\nk = 3\nop = GetIndex(Float64,(n,),(1:k,))\nx1 = randn(n)\ny1 = test_op(op, x1, randn(k), verb)\n\n@test all(norm.(y1 .- x1[1:k]) .<= 1e-12)\n\nn,m = 5,4\nk = 3\nop = GetIndex(Float64,(n,m),(1:k,:))\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(k,m), verb)\n\n@test all(norm.(y1 .- x1[1:k,:]) .<= 1e-12)\n\nn,m = 5,4\nop = GetIndex(Float64,(n,m),(:,2))\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(n), verb)\n\n@test all(norm.(y1 .- x1[:,2]) .<= 1e-12)\n\nn,m,l = 5,4,3\nop = GetIndex(Float64,(n,m,l),(1:3,2,:))\nx1 = randn(n,m,l)\ny1 = test_op(op, x1, randn(3,3), verb)\n\n@test all(norm.(y1 .- x1[1:3,2,:]) .<= 1e-12)\n\n# other constructors\nGetIndex((n,m), (1:k,:))\nGetIndex(x1, (1:k,:))\n\n@test_throws ErrorException GetIndex(Float64,(n,m),(1:k,:,:))\nop = GetIndex(Float64,(n,m),(1:n,1:m))\n@test typeof(op) <: Eye\n\nop = GetIndex(Float64,(n,),(1:k,))\n\n##properties\n@test is_sliced(op)           == true\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == true\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == false\n\n@test diag_AAc(op) == 1\n\n####### MatrixOp ############\n\n# real matrix, real input\nn,m = 5,4\nA = randn(n,m)\nop = MatrixOp(Float64,(m,),A)\nx1 = randn(m)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = A*x1\n\n# real matrix, complex input\nn,m = 5,4\nA = randn(n,m)\nop = MatrixOp(Complex{Float64},(m,),A)\nx1 = randn(m)+im.*randn(m)\ny1 = test_op(op, x1, randn(n)+im*randn(n), verb)\ny2 = A*x1\n\n# complex matrix, complex input\nn,m = 5,4\nA = randn(n,m)+im*randn(n,m)\nop = MatrixOp(Complex{Float64},(m,),A)\nx1 = randn(m)+im.*randn(m)\ny1 = test_op(op, x1, randn(n)+im*randn(n), verb)\ny2 = A*x1\n\n# complex matrix, real input\nn,m = 5,4\nA = randn(n,m)+im*randn(n,m)\nop = MatrixOp(Float64,(m,),A)\nx1 = randn(m)\ny1 = test_op(op, x1, randn(n)+im*randn(n), verb)\ny2 = A*x1\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n# complex matrix, real matrix input\nc = 3\nop = MatrixOp(Float64,(m,c),A)\n@test_throws ErrorException MatrixOp(Float64,(m,c,3),A)\n@test_throws MethodError MatrixOp(Float64,(m,c),randn(n,m,2))\nx1 = randn(m,c)\ny1 = test_op(op, x1, randn(n,c).+randn(n,c), verb)\ny2 = A*x1\n\n# other constructors\nop = MatrixOp(A)\nop = MatrixOp(Float64, A)\nop = MatrixOp(A, c)\nop = MatrixOp(Float64, A, c)\n\nop = convert(LinearOperator,A)\nop = convert(LinearOperator,A,c)\nop = convert(LinearOperator, Complex{Float64}, size(x1), A)\n\n##properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(MatrixOp(randn(Random.seed!(0),3,4)))    == true\n@test is_full_column_rank(MatrixOp(randn(Random.seed!(0),3,4))) == false\n\n\n##### LMatrixOp ############\n\nn,m = 5,6\nb = randn(m)\nop = LMatrixOp(Float64,(n,m),b)\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = x1*b\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m = 5,6\nb = randn(m)+im*randn(m)\nop = LMatrixOp(Complex{Float64},(n,m),b)\nx1 = randn(n,m)+im*randn(n,m)\ny1 = test_op(op, x1, randn(n)+im*randn(n), verb)\ny2 = x1*b\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 5,6,7\nb = randn(m,l)\nop = LMatrixOp(Float64,(n,m),b)\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(n,l), verb)\ny2 = x1*b\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nn,m,l = 5,6,7\nb = randn(m,l)+im*randn(m,l)\nop = LMatrixOp(Complex{Float64},(n,m),b)\nx1 = randn(n,m)+im*randn(n,m)\ny1 = test_op(op, x1, randn(n,l)+im*randn(n,l), verb)\ny2 = x1*b\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n## other constructors\nop = LMatrixOp(b,n)\n\n##properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == false\n@test is_full_column_rank(op) == false\n\n######### MyLinOp ############\n\nn,m = 5,4;\nA = randn(n,m);\nop = MyLinOp(Float64, (m,),(n,), (y,x) -> mul!(y,A,x), (y,x) -> mul!(y,A',x))\nx1 = randn(m)\ny1 = test_op(op, x1, randn(n), verb)\ny2 = A*x1\n\n# other constructors\nop = MyLinOp(Float64, (m,), Float64, (n,), (y,x) -> mul!(y,A,x), (y,x) -> mul!(y,A',x))\n\n\n######### MIMOFilt ############\nm,n = 10,2\nb = [[1.;0.;1.;0.;0.],[1.;0.;1.;0.;0.]]\na = [[1.;1.;1.],[2.;2.;2.]]\nop = MIMOFilt(Float64, (m,n), b, a)\n\nx1 = randn(m,n)\ny1 = test_op(op, x1, randn(m,1), verb)\ny2 = filt(b[1],a[1],x1[:,1])+filt(b[2],a[2],x1[:,2])\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nm,n = 10,3; #time samples, number of inputs\nb = [[1.;0.;1.],[1.;0.;1.],[1.;0.;1.],[1.;0.;1.],[1.;0.;1.],[1.;0.;1.], ];\na = [[1.;1.;1.],[2.;2.;2.],[      3.],[      4.],[      5.],[      6.], ];\nop = MIMOFilt(Float64, (m,n), b, a)\n\nx1 = randn(m,n)\ny1 = test_op(op, x1, randn(m,2), verb)\ny2 = [filt(b[1],a[1],x1[:,1])+filt(b[2],a[2],x1[:,2])+filt(b[3],a[3],x1[:,3]) filt(b[4],a[4],x1[:,1])+filt(b[5],a[5],x1[:,2])+filt(b[6],a[6],x1[:,3])]\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\nm,n = 10,3\nb = [randn(10),randn(5),randn(10),randn(2),randn(10),randn(10)]\na = [[1.],[1.],[1.],[1.],[1.],[1.]]\nop = MIMOFilt(Float64, (m,n), b, a)\n\nx1 = randn(m,n)\ny1 = test_op(op, x1, randn(m,2), verb)\ny2 = [filt(b[1],a[1],x1[:,1])+filt(b[2],a[2],x1[:,2])+filt(b[3],a[3],x1[:,3]) filt(b[4],a[4],x1[:,1])+filt(b[5],a[5],x1[:,2])+filt(b[6],a[6],x1[:,3])]\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n\n## other constructors\nMIMOFilt((10,3),  b, a)\nMIMOFilt((10,3),  b)\nMIMOFilt(x1,  b, a)\nMIMOFilt(x1,  b)\n\n#errors\n@test_throws ErrorException MIMOFilt(Float64, (10,3,2) ,b,a)\na2 = [[1.0f0],[1.0f0],[1.0f0],[1.0f0],[1.0f0],[1.0f0]]\nb2 = convert.(Array{Float32,1},b)\n@test_throws ErrorException MIMOFilt(Float64, (m,n),b2,a2)\n@test_throws ErrorException MIMOFilt(Float64, (m,n),b,a[1:end-1])\npush!(a2,[1.0f0])\npush!(b2,randn(Float32,10))\n@test_throws ErrorException MIMOFilt(Float32, (m,n),b2,a2)\na[1][1] = 0.\n@test_throws ErrorException MIMOFilt(Float64, (m,n) ,b,a)\n\nb = [randn(10),randn(5),randn(10),randn(2),randn(10),randn(10)]\na = [[1.],[1.],[1.],[1.],[1.],[1.]]\nop = MIMOFilt(Float64, (m,n), b, a)\n\n##properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\n######## Variation ############\n\nn,m = 10,5\nop = Variation(Float64,(n,m))\nx1 = randn(n,m)\ny1 = test_op(op, x1, randn(m*n,2), verb)\n\ny1 = op*repeat(collect(range(0,stop=1,length=n)),1,m)\n@test all(norm.(y1[:,1] .- 1/(n-1) ) .<= 1e-12)\n@test all(norm.(y1[:,2] ) .<= 1e-12)\n\nDx = spdiagm(0 => ones(n), -1 => -ones(n-1))\nDx[1,1],Dx[1,2] = -1,1\nDy = spdiagm(0 => ones(m), -1 => -ones(m-1))\nDy[1,1],Dy[1,2] = -1,1\n\nDxx = kron(sparse(I,m,m),Dx)\nDyy = kron(Dy,sparse(I,n,n))\nTV = [Dxx;Dyy]\n\nx1 = randn(n,m)\n@test norm(op*x1-reshape(TV*(x1[:]),n*m,2))<1e-12\n\nn,m,l = 10,5,3\nop = Variation(Float64,(n,m,l))\nx1 = randn(n,m,l)\ny1 = test_op(op, x1, randn(m*n*l,3), verb)\n\ny1 = op*reshape(repeat(collect(range(0,stop=1,length=n)),1,m*l),n,m,l)\n@test all(norm.(y1[:,1] .- 1/(n-1) ) .<= 1e-12)\n@test all(norm.(y1[:,2] ) .<= 1e-12)\n@test all(norm.(y1[:,3] ) .<= 1e-12)\n\n### other constructors\nVariation(Float64, n,m)\nVariation((n,m))\nVariation(n,m)\nVariation(x1)\n\n##errors\n@test_throws ErrorException Variation(Float64,(n,))\n\n###properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == false\n@test is_full_column_rank(op) == false\n\n######## Xcorr ############\nn,m = 5, 6\nh = randn(m)\nop = Xcorr(Float64,(n,),h)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n+m), verb)\ny2 = xcorr(x1, h; padmode=:longest)\n\n@test all(norm.(y1 .- y2) .<= 1e-12)\n# other constructors\nop = Xcorr(x1,h)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == true\n@test is_full_column_rank(op) == true\n\n######## ZeroPad ############\nn = (3,)\nz = (5,)\nop = ZeroPad(Float64,n,z)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n.+z), verb)\n@test all(norm.(y1 .- [x1;zeros(5)] ) .<= 1e-12)\n\nn = (3,2)\nz = (5,3)\nop = ZeroPad(Float64,n,z)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n.+z), verb)\ny2 = zeros(n.+z)\ny2[1:n[1],1:n[2]] = x1\n@test all(norm.(y1 .- y2 ) .<= 1e-12)\n\nn = (3,2,2)\nz = (5,3,1)\nop = ZeroPad(Float64,n,z)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(n.+z), verb)\ny2 = zeros(n.+z)\ny2[1:n[1],1:n[2],1:n[3]] = x1\n@test all(norm.(y1 .- y2 ) .<= 1e-12)\n\n# other constructors\nZeroPad(n, z...)\nZeroPad(Float64, n, z...)\nZeroPad(n, z...)\nZeroPad(x1, z)\nZeroPad(x1, z...)\n\n#errors\n@test_throws ErrorException ZeroPad(Float64,n,(1,2))\n@test_throws ErrorException ZeroPad(Float64,n,(1,-2,3))\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == false\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == true\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == false\n@test is_full_column_rank(op) == true\n\ndiag_AcA(op) == 1\n\n########## Zeros ############\nn = (3,4)\nD = Float64\nm = (5,2)\nC = Complex{Float64}\nop = Zeros(D,n,C,m)\nx1 = randn(n)\ny1 = test_op(op, x1, randn(m)+im*randn(m), verb)\n\n#properties\n@test is_linear(op)           == true\n@test is_null(op)             == true\n@test is_eye(op)              == false\n@test is_diagonal(op)         == false\n@test is_AcA_diagonal(op)     == false\n@test is_AAc_diagonal(op)     == false\n@test is_orthogonal(op)       == false\n@test is_invertible(op)       == false\n@test is_full_row_rank(op)    == false\n@test is_full_column_rank(op) == false\n", "meta": {"hexsha": "2a7a2bf88bafa519feba36a4286550ed7b11e41e", "size": 25564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_linear_operators.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": "test/test_linear_operators.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": "test/test_linear_operators.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.0381978452, "max_line_length": 150, "alphanum_fraction": 0.5792129557, "num_tokens": 10089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7703103141143869}}
{"text": "using HypothesisTests, Base.Test\nusing HypothesisTests: default_tail\n\n# www.uni-siegen.de/phil/sozialwissenschaften/soziologie/mitarbeiter/ludwig-mayerhofer/statistik/statistik_downloads/statistik_ii_7.pdf\nu5 = [620, 5350, 7220]\nu250 = [3580, 4180, 5690]\nu2500 = [3600, 3820, 3840, 3850, 4160, 5300, 6900, 7120, 9370]\nmore = [3920, 4520, 4760, 8560, 10350]\nt = HypothesisTests.KruskalWallisTest(u5, u250, u2500, more)\n\n@test t.n_i == [length(u5), length(u250), length(u2500), length(more)]\n@test t.df == 3\n@test t.R_i == [31, 25, 88, 66]\n@test t.H \u2248 1.5803174603174597\n@test t.tie_adjustment == 1\n@test pvalue(t) \u2248 0.6638608922384397\n@test default_tail(t) == :right\nshow(IOBuffer(), t)\n\n# http://www.brightstat.com/index.php?option=com_content&task=view&id=41&Itemid=1&limit=1&limitstart=2\ncity1 = [68, 93, 123, 83, 108, 122]\ncity2 = [119, 116, 101, 103, 113, 84]\ncity3 = [70, 68, 54, 73, 81, 68]\ncity4 = [61, 54, 59, 67, 59, 70]\nt = HypothesisTests.KruskalWallisTest(city1, city2, city3, city4)\n\n@test t.n_i == [length(city1), length(city2), length(city3), length(city4)]\n@test t.df == 3\n@test t.R_i == [104, 113, 53, 30]\n@test t.H \u2248 16.028783253379856\n@test t.tie_adjustment \u2248 0.9969565217391304\n@test pvalue(t) \u2248 0.0011186794961869423\nshow(IOBuffer(), t)\n\n# example with non-integer rank sum\nt1 = [1.2,1.9,2.1]\nt2 = [3.4,1.9,5.6]\nt3 = [1.3,4.4,9.9]\nt = KruskalWallisTest(t1, t2, t3)\n@test t.n_i == [length(t1), length(t2), length(t3)]\n@test t.df == 2\n@test t.R_i ==  [9.5, 17.5, 18.0]\n@test t.H \u2248 2.039215686274513\n@test t.tie_adjustment \u2248 0.9916666666666667\n@test pvalue(t) \u2248 0.3607363776845705\nshow(IOBuffer(), t)\n", "meta": {"hexsha": "b23ecfbeae4fc00d73c323c8306bfc2cee344a5c", "size": 1619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/kruskal_wallis.jl", "max_stars_repo_name": "kalmarek/HypothesisTests.jl", "max_stars_repo_head_hexsha": "b28a4587fe441d1da0479c0791e5f9fd2120cb6b", "max_stars_repo_licenses": ["MIT"], "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/kruskal_wallis.jl", "max_issues_repo_name": "kalmarek/HypothesisTests.jl", "max_issues_repo_head_hexsha": "b28a4587fe441d1da0479c0791e5f9fd2120cb6b", "max_issues_repo_licenses": ["MIT"], "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/kruskal_wallis.jl", "max_forks_repo_name": "kalmarek/HypothesisTests.jl", "max_forks_repo_head_hexsha": "b28a4587fe441d1da0479c0791e5f9fd2120cb6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T22:55:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T22:55:40.000Z", "avg_line_length": 34.4468085106, "max_line_length": 135, "alphanum_fraction": 0.693020383, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7703040183676757}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 5bb6cf00-9b75-4e74-bc75-6a059bc1b32d\n# U\u010dita se paket SymPy\nusing SymPy\n\n# \u2554\u2550\u2561 efc1cf20-8276-11eb-39ba-bd62a4342e68\nmd\"\n# Integrali racionalnih funkcija\n\"\n\n# \u2554\u2550\u2561 d52c1d09-9bee-4359-8e2c-a969a2f32ea3\n# Ova naredba daje popis svih djelova paketa, uglavnom su to funkcije.\n# varinfo(SymPy)\n\n# \u2554\u2550\u2561 8153dabd-5be6-4308-b7c5-1f4ed54722ab\nbegin\n\t# Izra\u010dunajmo nekoliko integrala.\n\tx=Sym(\"x\")\n\tintegrate(x^2*sin(x))\nend\n\n# \u2554\u2550\u2561 10b872ad-f070-404c-9ec8-19f0bc2032c5\nintegrate(exp(-x^2))\n\n# \u2554\u2550\u2561 056c397f-7303-464e-9ec6-8cf893bbc98c\n# Primjer rekurzivne formule. Ovo traje malo du\u017ee\nintegrate(1/(1+x^2)^13)\n\n# \u2554\u2550\u2561 b29b5f68-8978-4b4b-9b29-4840a4097978\n# Kra\u0107a rekurzivna formula\nintegrate(1/(1+x^2)^3)\n\n# \u2554\u2550\u2561 232dcad5-1984-4421-9c1a-001406096217\nmethods(diff)\n\n# \u2554\u2550\u2561 a2819cd4-d0b3-476a-ab8c-40838db72d54\n# Derivacija\ndiff(x^2*exp(sin(1/x)))\n\n# \u2554\u2550\u2561 74af42dd-9768-4e91-aa3b-b26c69d6fb68\n# Racionalna funkcija trigonometrijskih funkcija (univerzalna trigonometrijska supstitucija)\nintegrate(1/((2+cos(x))*sin(x)))\n\n# \u2554\u2550\u2561 de024987-9c44-4199-9085-b259980e94a5\nmd\"\"\"\n#### Zadatak 1.5.e)\n\"\"\"\n\n# \u2554\u2550\u2561 62c5d76c-9eef-40a9-b8c9-446720733f80\nintegrate(1/(4*sin(x)+3*cos(x)+5))\n\n# \u2554\u2550\u2561 379bc6e9-7a38-4f3e-8e4a-2ff80917880b\nintegrate(1/(sin(x)*(2+cos(x)-2*sin(x))))\n\n# \u2554\u2550\u2561 28dd8649-ed7c-47e5-b7ab-69e99dc0ce86\n# Ovo traje beskona\u010dno?\n# integrate(cos(x)^3/(sin(x)^2+sin(x)))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bf1829c9-b2fb-4e3b-b92d-38a93513678b\n# Ovo traje jako dugo i ne uspije izra\u010dunati nego vrati polazni integral\n# integrate( (2*tan(x)+3)/(sin(x)^2+2*cos(x)^2))\n\n# \u2554\u2550\u2561 3732f5f7-ed44-4254-8b16-d9d860d2c04f\nmd\"\"\"\nUz supstituciju $t=\\tan(x)$ integral postaje jednostavan:\n\"\"\"\n\n# \u2554\u2550\u2561 232927bc-ac81-4225-801f-9da5e5842d6d\nbegin\n\tt=Sym(\"t\")\n\tI\u2081=integrate( (2*t+3)/(t^2+2))\nend\n\n# \u2554\u2550\u2561 13e53f50-8c7d-403c-85c5-848bf2ccbe94\nbegin\n\t# Vratimo supstituciju natrag\n\tI\u2082=convert(Function,I\u2081)\n\tI\u2082(tan(x))\nend\n\n# \u2554\u2550\u2561 d9ada9db-2651-4895-876b-704e4ed05bcb\nmd\"\"\"\n#### Zadatak 1.6\n\"\"\"\n\n# \u2554\u2550\u2561 f2eb749b-51d6-4875-8e14-1e0f688cdfc7\n# Ovo traje beskona\u010dno!\n# I\u2084=integrate((1+sinh(x))/((2+cosh(x))*(3+sinh(x))),x)\n# Program treba na\u0161u pomo\u0107!!!\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 78acc71b-b314-4799-b633-4ab5b7958496\nI\u2084=(1+sinh(x))/((2+cosh(x))*(3+sinh(x)))\n\n# \u2554\u2550\u2561 463c1ac7-e503-4507-8aca-d671acf04d36\n# supstitucija za sinh(x)\nI\u2085=subs(I\u2084,sinh(x),(2*t)/(1-t^2))\n\n# \u2554\u2550\u2561 1b47139d-6c06-4227-91d2-1556d2f3a9d2\n# Supstitucija za cosh(x)\nI\u2086=subs(I\u2085,cosh(x),(1+t^2)/(1-t^2))\n\n# \u2554\u2550\u2561 646c21be-c589-43b6-b648-3d0dea8353db\n# Pomno\u017eimo s dx\nI\u2087=I\u2086*2/(1-t^2)\n\n# \u2554\u2550\u2561 34320cf9-d978-46ca-ace2-ea638cc602d7\n# Integriramo racionalnu funkciju\nI\u2088=integrate(I\u2087,t)\n\n# \u2554\u2550\u2561 6e0e6146-fefa-4967-938e-1755a0a04607\n# Vratimo supstituciju natrag\nI\u2089=subs(I\u2088,t,tanh(x/2))\n\n# \u2554\u2550\u2561 a817a9d1-f9d2-4fb9-ad16-2477a0a6dea6\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500efc1cf20-8276-11eb-39ba-bd62a4342e68\n# \u2560\u25505bb6cf00-9b75-4e74-bc75-6a059bc1b32d\n# \u2560\u2550d52c1d09-9bee-4359-8e2c-a969a2f32ea3\n# \u2560\u25508153dabd-5be6-4308-b7c5-1f4ed54722ab\n# \u2560\u255010b872ad-f070-404c-9ec8-19f0bc2032c5\n# \u2560\u2550056c397f-7303-464e-9ec6-8cf893bbc98c\n# \u2560\u2550b29b5f68-8978-4b4b-9b29-4840a4097978\n# \u2560\u2550232dcad5-1984-4421-9c1a-001406096217\n# \u2560\u2550a2819cd4-d0b3-476a-ab8c-40838db72d54\n# \u2560\u255074af42dd-9768-4e91-aa3b-b26c69d6fb68\n# \u255f\u2500de024987-9c44-4199-9085-b259980e94a5\n# \u2560\u255062c5d76c-9eef-40a9-b8c9-446720733f80\n# \u2560\u2550379bc6e9-7a38-4f3e-8e4a-2ff80917880b\n# \u2560\u255028dd8649-ed7c-47e5-b7ab-69e99dc0ce86\n# \u2560\u255012904f05-67c3-4d8a-aefd-e9645e6ef0eb\n# \u2560\u2550bf1829c9-b2fb-4e3b-b92d-38a93513678b\n# \u255f\u25003732f5f7-ed44-4254-8b16-d9d860d2c04f\n# \u2560\u2550232927bc-ac81-4225-801f-9da5e5842d6d\n# \u2560\u255013e53f50-8c7d-403c-85c5-848bf2ccbe94\n# \u255f\u2500d9ada9db-2651-4895-876b-704e4ed05bcb\n# \u2560\u2550f2eb749b-51d6-4875-8e14-1e0f688cdfc7\n# \u255f\u2500244208a5-b153-424b-8305-5b6002fd8186\n# \u2560\u255078acc71b-b314-4799-b633-4ab5b7958496\n# \u2560\u2550463c1ac7-e503-4507-8aca-d671acf04d36\n# \u2560\u25501b47139d-6c06-4227-91d2-1556d2f3a9d2\n# \u2560\u2550646c21be-c589-43b6-b648-3d0dea8353db\n# \u2560\u255034320cf9-d978-46ca-ace2-ea638cc602d7\n# \u2560\u25506e0e6146-fefa-4967-938e-1755a0a04607\n# \u2560\u2550a817a9d1-f9d2-4fb9-ad16-2477a0a6dea6\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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\u2081`\nand `r\u2082` are set to the chaotic regime by default\n\n# References\n1. Diego, D., Agas\u00f8ster 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\u2081, r\u2082, \u03c3 = (p...,)\n    \u03be = rand() # random number from flat distribution on [0, 1]\n    x, y = x[1], x[2]\n    f_xy = (y +  (c*(x + \u03c3*\u03be)/2) ) / (1 + (c/2)*(1+\u03c3))\n\n    dx[1] = r\u2081 * x * (1 - x)\n    dx[2] = r\u2082 * (f_xy) * (1 - f_xy)\n    return\nend\n\nfunction logistic2(u\u2080, c, r\u2081, r\u2082, \u03c3)\n    p = [c, r\u2081, r\u2082, \u03c3]\n    DiscreteDynamicalSystem(eom_logistic2, u\u2080, p)\nend\n\n\"\"\"\n    logistic2(;u\u2080 = rand(2), c = 0.1, \u03c3 = 0.05,\n        r\u2081 = 3.78, r\u2082 = 3.66) -> DiscreteDynamicalSystem\n\nInitialise a system consisting of two coupled logistic maps where X\nunidirectionally influences Y. By default, the parameters `r\u2081` and `r\u2082` are set\nto values yielding chaotic behaviour.\n\nThe parameter `c` controls how strong the dynamical forcing is. If `\u03c3 > 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 `\u03c3 = 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\u00f8ster 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\u2080 = rand(2), c = 0.1, r\u2081 = 3.78, r\u2082 = 3.66, \u03c3 = 0.05) =\n    logistic2(u\u2080, c, r\u2081, r\u2082, \u03c3)\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": "using QuasiGeostrophy, LinearAlgebra, Test, FFTW, BenchmarkTools, Plots\n\n# boiler plate definitions\n\u03a9xy = S\u00b9(0,2\u03c0) \u00d7 S\u00b9(0,2\u03c0)\nNx = 2^6; Ny = 2^6;\nfourier_grid = FourierGrid((Nx, Ny), \u03a9xy)\nx, y = fourier_grid.grid\nkx, ky = fourier_grid.wavenumbers\nu = @. 1 * sin(x) * sin(y) + 0im\nv = @. 1 * cos(x) * cos(y) + 0im\nu\u0302 = copy(u)\nv\u0302 = copy(v)\n\n\nFFTW.set_num_threads(Threads.nthreads())\nP = plan_fft(u) # typeof(iP) <: AbstractFFTs.ScaledPlan\niP = plan_ifft(u)\n\nuv = P * (u .* v)\nnorm(uv - convolve(P * u, P * v, P, iP)) / norm(uv)\n\n## Define Parameter\nconst Re  = 100.0 \nconst \u0394t = 1.0 / Re\nconst G  = 4.0\n\n## Define forcing\nforcing = @. G * sin(5 * x) * sin(5 * y) + 0im\nf\u0302 = copy(forcing)\nmul!(f\u0302, P, forcing)\n\n## Define Operators\n\u2202x = FourierOperator(im .* kx)\n\u2202y = FourierOperator(im .* ky)\n\u0394 = \u2202x^2 + \u2202y^2\n\u0394\u207b\u00b9 = inv(\u0394)\n\n\nfunction get_pressure(u_rhs, v_rhs, \u2202x, \u2202y, G)\n    return G(\u2202x(u_rhs) + \u2202y(v_rhs))\nend\n\nfunction closure_rhs(\u2202x, \u2202y, \u0394\u207b\u00b9, P, iP, forcing)\n    function rhs(state)\n        u = state[1]\n        v = state[2]\n        uu = convolve(u, u, P, iP)\n        uv = convolve(u, v, P, iP)\n        vv = convolve(v, v, P, iP)\n        u_rhs = - \u2202x(uu) - \u2202y(uv) +  forcing\n        v_rhs = - \u2202x(uv) - \u2202y(vv)\n        p = get_pressure(u_rhs, v_rhs, \u2202x, \u2202y, \u0394\u207b\u00b9)\n        u_rhs -= \u2202x(p)\n        v_rhs -= \u2202y(p)\n        return [u_rhs, v_rhs]\n    end\nend\n\nrhs = closure_rhs(\u2202x, \u2202y, \u0394\u207b\u00b9, P, iP, forcing)\n\nfunction closure_lhs(\u0394, Re, \u0394t)\n    function lhs()\n        u_lhs = 1 + -(\u0394t / Re) * \u0394\n        return [u_lhs, u_lhs]\n    end\nend\n\nlhs = closure_lhs(\u0394, Re, \u0394t)\noperators = lhs()\nlhs_operator = [inv(operator) for operator in operators]\n\nfunction imex_step!(state, lhs_operator, rhs, \u0394t)\n    rhs_state = rhs(state)\n    current_state = copy(state)\n    for i in eachindex(state)\n        tmp = lhs_operator[i](current_state[i] .+ \u0394t .* rhs_state[i])\n        @. state[i] =  tmp\n    end\nend\n\n##\ncontourf(x[:], y[:], real.(forcing)', linewidth = 0, color = :thermometer)\n##\nu = @. 1 * sin(x) * sin(y) + 0im\nv = @. 1 * cos(x) * cos(y) + 0im\nu\u0302 = copy(u)\nv\u0302 = copy(v)\nmul!(u\u0302, P, u)\nmul!(v\u0302, P, v)\n# u\u0302, v\u0302 = copy(good_start)\nstate = [u\u0302, v\u0302]\n## Checking Incompressibility\nrhs_tmp = rhs(state)\nmaximum(abs.(\u2202x(rhs_tmp[1]) + \u2202y(rhs_tmp[2])))\n##\nfor i in 1:20000\n    imex_step!(state, lhs_operator, rhs, \u0394t)\n    if (i%1000) == 0\n        println(i)\n        \u03c9\u0302 = \u2202x(v\u0302) - \u2202y(u\u0302)\n        mul!(u, iP, \u03c9\u0302)\n        local p1 = contourf(x[:],y[:], real.(u)', linewidth = 0, color = :thermometer)\n        display(p1)\n        println(\"checking conergence to steady state\")\n        println(norm(rhs(state) + (1/Re) * \u0394.(state)) / (norm(rhs(state))))\n        sleep(0.01)\n    end \nend\n# good_start = copy(state)\n## check steady state\n# include(pwd() * \"/sandbox/two_d_navier_stokes.jl\")", "meta": {"hexsha": "5fbea952e13f292e73c3590848a4f5609e1f6ced", "size": 2758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sandbox/two_d_navier_stokes.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": "sandbox/two_d_navier_stokes.jl", "max_issues_repo_name": "sandreza/QuasiGeostrophy", "max_issues_repo_head_hexsha": "05b6e622e981afebf880e4890d24e2b813087e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-13T17:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-13T17:29:21.000Z", "max_forks_repo_path": "sandbox/two_d_navier_stokes.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.8468468468, "max_line_length": 86, "alphanum_fraction": 0.5678027556, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7702505284475335}}
{"text": "module ProblemTest\nusing LinearAlgebra\nP1 = (sol = [[1,0], [0, 1]], vsol = -1,  A = [1 1], b = [1], c = [-1, -1], isoptimal = true, isbounded = true, isfeasible = true)\nP2 = (sol = [[1,0], [0, 1]], vsol = -1, A = [1 1; 1 1], b = [1, 1], c = [-1, -1], isoptimal = true, isbounded = true, isfeasible = true)\nfunction kmstar(n::Int, ::Type{T} = Int) where T\n    xstar = zeros(T, 2*n)\n    xstar[n] = 100^(n - 1)\n    rest = [100^(k - 1) for k in 1:n]\n    rest[end] = 0\n    xstar[n+1:end] = rest\n    return xstar\nend\nfunction km(n::Int, ::Type{T} = Int) where T\n    c = [10^(n - i) for i in 1:n]\n    b = [100^(i - 1) for i in 1:n]\n    A = zeros(T, n, n)\n    for i in 1:n\n        A[i, 1:i] = 2*[10^(i - j) for j in 1:i]\n    end\n    A[:, :] -= I\n    A = [A I]\n    c = [c; zeros(T, n)]\n    return A, b, -c, -100^(n - 1), kmstar(n)\nend\nPKM = [\n    ((A, b, c, vstar, xstar) = km(i);\n        (sol = [xstar],\n        vsol = vstar,\n            A = A,\n            b = b,\n            c = c, \n            isoptimal = true, \n            isbounded = true, \n            isfeasible = true\n        )\n    )\n    for i in 1:10\n]\n#Problem List\nPL = [P1, P2, PKM...]\nend", "meta": {"hexsha": "4abb27d3045a6091c04f2f83db3c5724701b389d", "size": 1143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test/problems.jl", "max_stars_repo_name": "fbastin/Jasmin", "max_stars_repo_head_hexsha": "cdb0b693664eabf0d53766e7e65da92ec0d8a50a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-21T00:45:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T00:45:51.000Z", "max_issues_repo_path": "src/test/problems.jl", "max_issues_repo_name": "fbastin/Jasmin", "max_issues_repo_head_hexsha": "cdb0b693664eabf0d53766e7e65da92ec0d8a50a", "max_issues_repo_licenses": ["MIT"], "max_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/problems.jl", "max_forks_repo_name": "fbastin/Jasmin", "max_forks_repo_head_hexsha": "cdb0b693664eabf0d53766e7e65da92ec0d8a50a", "max_forks_repo_licenses": ["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.8780487805, "max_line_length": 136, "alphanum_fraction": 0.4505686789, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8354835452961427, "lm_q1q2_score": 0.7702505230706214}}
{"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": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 b37139ed-ca54-4a70-a4aa-190fc4ff223a\nusing PlutoUI\n\n# \u2554\u2550\u2561 48988162-68d1-11eb-22dc-2bbc0e41043b\nusing Test\n\n# \u2554\u2550\u2561 cb0ae3b2-42b8-485b-9c04-c1190e5eed94\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# \u2554\u2550\u2561 b6e6f16a-68ce-11eb-320d-6b292123f85a\nmd\"\"\"\n### Functions in julia\n\"\"\"\n\n# \u2554\u2550\u2561 d8456146-68ce-11eb-2872-3d66933b3385\nbegin\n\tDT = Float64\n\n\tfunction \u03b4(a::DT, b::DT, c::DT)::DT\n    \tb * b - 4 * a * c\n\tend\nend\n\n# \u2554\u2550\u2561 fbec986e-68ce-11eb-1598-619db8bca4cc\nfunction root(a::DT, b::DT, c::DT)::NamedTuple{(:x1, :x2),Tuple{DT, DT}}\n    \u0394 = \u03b4(a, b, c) \n    \u0394 < 0 && throw(ArgumentError(\"No solution in \u211c\"))\n    \n\tx\u2081 = (-b + \u221a \u0394) / 2a\n   \tx\u2082 = (-b - \u221a \u0394) / 2a\n    (x1 = x\u2081, x2 = x\u2082) # named tuple\nend\n\n# \u2554\u2550\u2561 3750513e-68cf-11eb-0e76-7169551337af\nwith_terminal() do\n\tprintln(typeof(\u03b4(1., 1., 1.)))\nend\n\n# \u2554\u2550\u2561 50a85e6a-68cf-11eb-0e5e-2f2cbbfcce73\nwith_terminal() do\n\tr = root(2., -3., 1.)\n\tprintln(\"r: $(r) / typeof(r): $(typeof(r))\")\nend\n\n# \u2554\u2550\u2561 80512f66-68cf-11eb-3f58-498f113425d4\nwith_terminal() do\n\tr = root(1., -2., 1.)\n\tprintln(\"r: $(r) / typeof(r): $(typeof(r))\")\nend\n\n# \u2554\u2550\u2561 94a3ce9c-68cf-11eb-1a26-e57d02e78f19\nwith_terminal() do\n\ttry\n    \tprintln(root(1., -1., 1.))\n\tcatch ex\n    \tprintln(\"Intercepted: \", string(ex))\n\tend\nend\n\n# \u2554\u2550\u2561 a5f7141a-68cf-11eb-3dd1-9b04e8b62317\nmd\"\"\"\n#### Function composition\n\"\"\"\n\n# \u2554\u2550\u2561 b2f4f754-68cf-11eb-3d27-dd9df6feb65f\nfunction f(x::Real)::Real  ## Real is an abstract type\n    2. * x\nend\n\n# \u2554\u2550\u2561 c06c4d8a-68cf-11eb-133e-ed1e6ae4c889\nfunction g(x::Real)::Real\n    x - 5.\nend\n\n# \u2554\u2550\u2561 cadfceca-68cf-11eb-1b1b-7fcc66d4c632\n(g \u2218 f)(4.)  # type: \\circ<tab>: g(f(4.)) = 2 * 4. - 5, = 3\n\n# \u2554\u2550\u2561 d97425bc-68cf-11eb-20c0-2dcaf9ede5f4\n(f \u2218 g)(7.) \n\n# \u2554\u2550\u2561 e0553894-68cf-11eb-0e1f-5be65d986ed8\nary = [x for x in 0:5:100]\n\n# \u2554\u2550\u2561 e4d32200-68cf-11eb-2ff7-0b227d2de510\nnary = map(x -> 3x + 2, ary) |> \n    x -> filter(isodd, x)\n\n# \u2554\u2550\u2561 f250750e-68cf-11eb-3e4e-b5fcbcdf2320\nmap(x -> 3x + 2, ary) |> \n    x -> filter(isodd, x) |>\n    x -> reduce(+, x, init=0)\n\n# \u2554\u2550\u2561 fcf27c16-68cf-11eb-3ae6-9b5a3d98c6ab\nreduce(+, [x for x in 1:10], init=0)\n\n# \u2554\u2550\u2561 07a84580-68d0-11eb-0dcc-2dfc25b93d8b\nreduce(+, 1:10, init=11)\n\n# \u2554\u2550\u2561 0b7b3b18-68d0-11eb-0e84-57cbc7e344d1\nmd\"\"\"\n#### Function and Closure\n\"\"\"\n\n# \u2554\u2550\u2561 1c25a7be-68d0-11eb-29f3-4dd237a2ef2e\nadder = function(\u03b1::Number=2)\n    x -> x + \u03b1\nend\n\n# \u2554\u2550\u2561 44e600ba-68d0-11eb-122f-e9973916ffc8\nadd2 = adder()   # \u2261 ad2(x) = x + 2\n\n# \u2554\u2550\u2561 53b8de8a-68d0-11eb-34e0-c1bbb3824ede\nadd2(2)\n\n# \u2554\u2550\u2561 7174059e-68d0-11eb-01fe-e712691890a4\nbegin\n\tadd3 = adder(3)\n\tadd3(10)\nend\n\n# \u2554\u2550\u2561 840923b0-68d0-11eb-039f-05cd7abb2c04\nmap(add2, 1:10)\n\n# \u2554\u2550\u2561 8c579696-68d0-11eb-1321-ad2e8290b3bd\ncounter = function(; init=0)\n    cnt = init\n\t\n    inc() = cnt += 1\n\tdec() = cnt -= 1\n\treset() = cnt = 0\n    \n\t## Declare public:\n    ()->(inc, dec, reset)\nend\n\n# \u2554\u2550\u2561 2542f116-68d1-11eb-0eb2-0fa4398666ee\nbegin \n\txc = counter()\n\t\n\t@test xc.inc() == 1\n\t@test xc.inc() == 2  \n\t@test xc.inc() == 3\n\t\n\t@test xc.dec() == 2\n\t\n\t@test xc.reset() == 0\nend\n\n# \u2554\u2550\u2561 6d948d44-68d1-11eb-283f-95c7209184f3\nbegin \n\tyc = counter(init=100)\n\t\n\t@test yc.inc() == 101\n\t@test yc.inc() == 102  \n\t@test yc.inc() == 103\n\t\n\t@test yc.dec() == 102\n\t\n\t@test yc.reset() == 0\nend\n\n# \u2554\u2550\u2561 8d553214-68d1-11eb-29d7-d791c9dff9f4\ncounter_ng = function(;init=0)\n    cnt = init\n\n\t# closure\n    \u03bb = function(action=:inc)\n        if action == :inc\n            cnt += 1\n        elseif action == :dec\n            cnt -= 1\n        elseif action == :reset\n            cnt = 0\n        else\n            throw(ArgumentError(\"action $(action) not yet supported...\"))\n        end\n    end\n\t\n    \u03bb\nend\n\n# \u2554\u2550\u2561 b2a41b98-68d1-11eb-21b3-9b48c657591d\nbegin \n\tix = counter_ng()\n\t\n\t@test ix(:inc) == 1\n\t@test ix(:inc) == 2  \n\t@test ix(:inc) == 3\n\t\n\t@test ix(:dec) == 2\n\t@test ix(:dec) == 1\n\t\n\t@test ix(:reset) == 0\nend\n\n# \u2554\u2550\u2561 eadfe19a-68d1-11eb-05c0-43915ae2d1b1\nbegin \n\tjy = counter_ng(init=100)\n\t\n\t@test jy(:inc) == 101\n\t@test jy(:inc) == 102  \n\t@test jy(:inc) == 103\n\t\n\t@test jy(:dec) == 102\n\t@test_throws ArgumentError jy(:rec)\n\t\n\t@test jy(:reset) == 0\nend\n\n# \u2554\u2550\u2561 3dc862b0-a58a-4731-a3c8-4eb44ded1443\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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550b37139ed-ca54-4a70-a4aa-190fc4ff223a\n# \u2560\u2550cb0ae3b2-42b8-485b-9c04-c1190e5eed94\n# \u255f\u2500b6e6f16a-68ce-11eb-320d-6b292123f85a\n# \u2560\u2550d8456146-68ce-11eb-2872-3d66933b3385\n# \u2560\u2550fbec986e-68ce-11eb-1598-619db8bca4cc\n# \u2560\u255048988162-68d1-11eb-22dc-2bbc0e41043b\n# \u2560\u25503750513e-68cf-11eb-0e76-7169551337af\n# \u2560\u255050a85e6a-68cf-11eb-0e5e-2f2cbbfcce73\n# \u2560\u255080512f66-68cf-11eb-3f58-498f113425d4\n# \u2560\u255094a3ce9c-68cf-11eb-1a26-e57d02e78f19\n# \u255f\u2500a5f7141a-68cf-11eb-3dd1-9b04e8b62317\n# \u2560\u2550b2f4f754-68cf-11eb-3d27-dd9df6feb65f\n# \u2560\u2550c06c4d8a-68cf-11eb-133e-ed1e6ae4c889\n# \u2560\u2550cadfceca-68cf-11eb-1b1b-7fcc66d4c632\n# \u2560\u2550d97425bc-68cf-11eb-20c0-2dcaf9ede5f4\n# \u2560\u2550e0553894-68cf-11eb-0e1f-5be65d986ed8\n# \u2560\u2550e4d32200-68cf-11eb-2ff7-0b227d2de510\n# \u2560\u2550f250750e-68cf-11eb-3e4e-b5fcbcdf2320\n# \u2560\u2550fcf27c16-68cf-11eb-3ae6-9b5a3d98c6ab\n# \u2560\u255007a84580-68d0-11eb-0dcc-2dfc25b93d8b\n# \u255f\u25000b7b3b18-68d0-11eb-0e84-57cbc7e344d1\n# \u2560\u25501c25a7be-68d0-11eb-29f3-4dd237a2ef2e\n# \u2560\u255044e600ba-68d0-11eb-122f-e9973916ffc8\n# \u2560\u255053b8de8a-68d0-11eb-34e0-c1bbb3824ede\n# \u2560\u25507174059e-68d0-11eb-01fe-e712691890a4\n# \u2560\u2550840923b0-68d0-11eb-039f-05cd7abb2c04\n# \u2560\u25508c579696-68d0-11eb-1321-ad2e8290b3bd\n# \u2560\u25502542f116-68d1-11eb-0eb2-0fa4398666ee\n# \u2560\u25506d948d44-68d1-11eb-283f-95c7209184f3\n# \u2560\u25508d553214-68d1-11eb-29d7-d791c9dff9f4\n# \u2560\u2550b2a41b98-68d1-11eb-21b3-9b48c657591d\n# \u2560\u2550eadfe19a-68d1-11eb-05c0-43915ae2d1b1\n# \u255f\u25003dc862b0-a58a-4731-a3c8-4eb44ded1443\n", "meta": {"hexsha": "39dc941842b2fdc5804fa3c9c27f5313d601cb74", "size": 5697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia_Investigation/julia_explore_p07_functions.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_p07_functions.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_p07_functions.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": 21.4981132075, "max_line_length": 73, "alphanum_fraction": 0.6389327716, "num_tokens": 3017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7702505191021952}}
{"text": "##\n#\n# PiBBP tests\n#\n\nusing PiBBP\nusing Base.Test\n\n#\n# Particular digits\n#\n\n@test digpi(0)       == 2\n@test digpi(1000000) == 6\n\n#\n# It actually computes fractional part of $\\pi$.\n#\n\n@test pi - (3 + sum(digpi(n) / 16^(n+1) for n in 0:14)) \u2248 0\n@test pi - (3 + sum(digpi(n) / big(16)^(n+1) for n in 0:64)) \u2248 0\n", "meta": {"hexsha": "ac66cba14263d246ed2afb7a72cbcb68d18d0aab", "size": 308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "kalvotom/PiBBP.jl", "max_stars_repo_head_hexsha": "d8950b372586d9a5d01538bfd653bd6415ce64f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-05-19T00:16:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T17:52:06.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "kalvotom/PiBBP.jl", "max_issues_repo_head_hexsha": "d8950b372586d9a5d01538bfd653bd6415ce64f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-05-18T20:31:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-27T20:07:33.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "kalvotom/PiBBP.jl", "max_forks_repo_head_hexsha": "d8950b372586d9a5d01538bfd653bd6415ce64f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-05-18T20:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-12T18:56:36.000Z", "avg_line_length": 14.0, "max_line_length": 64, "alphanum_fraction": 0.5714285714, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7702505136293284}}
{"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": "using CGMethod1D, FastGaussQuadrature\nusing Test\n\n\ninclude(\"test_interpolation.jl\")\ninclude(\"test_quadrature.jl\")\n", "meta": {"hexsha": "743ee8e4d83d3438c224190b7439eec1e43d62b5", "size": 114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "cfgarciar/CGMethod1D.jl", "max_stars_repo_head_hexsha": "cb1d604ccfc128f2f90d7ac91554328eeba4630a", "max_stars_repo_licenses": ["MIT"], "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": "cfgarciar/CGMethod1D.jl", "max_issues_repo_head_hexsha": "cb1d604ccfc128f2f90d7ac91554328eeba4630a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-18T01:26:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T01:57:56.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "cfgarciar/CGMethod1D.jl", "max_forks_repo_head_hexsha": "cb1d604ccfc128f2f90d7ac91554328eeba4630a", "max_forks_repo_licenses": ["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.2857142857, "max_line_length": 37, "alphanum_fraction": 0.8245614035, "num_tokens": 33, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7702505117410697}}
{"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": "using Test\n\n@testset \"Neumann0 Boundary\" begin\n    N = 100\n    d_order = 2\n    approx_order = 2\n    x = collect(1:1.0:N).^2\n    A = DerivativeOperator{Float64}(2,2,1.0,N,:Neumann0,:Neumann0)\n    boundary_points = A.boundary_point_count\n    res = A*x\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 2.0*ones(N - sum(boundary_points)) atol=10.0^approx_order\n    FD = DerivativeOperator{Float64}(1,2,1.0,N,:Neumann0,:Neumann0)\n    first_deriv = FD*res\n    @test first_deriv[1] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n    @test first_deriv[end] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n\n    N = 1000\n    d_order = 4\n    approx_order = 10\n    y = collect(1:1.0:N).^4 - 2*collect(1:1.0:N).^3 + collect(1:1.0:N).^2;\n    A = DerivativeOperator{Float64}(d_order,approx_order,1.0,N,:Neumann0,:Neumann0)\n    boundary_points = A.boundary_point_count\n    res = A*y\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 24.0*ones(N - sum(boundary_points)) atol=10.0^-1; # Float64 is less stable\n    FD = DerivativeOperator{Float64}(1,2,1.0,N,:Neumann0,:Neumann0)\n    first_deriv = FD*res\n    @test first_deriv[1] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n    @test first_deriv[end] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n\n    A = DerivativeOperator{BigFloat}(d_order,approx_order,one(BigFloat),N,:Neumann0,:Neumann0)\n    y = convert(Array{BigFloat, 1}, y)\n    res = A*y\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 24.0*ones(N - sum(boundary_points)) atol=10.0^-approx_order;\n    FD = DerivativeOperator{BigFloat}(1,2,one(BigFloat),N,:Neumann0,:Neumann0)\n    first_deriv = FD*res\n    @test first_deriv[1] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n    @test first_deriv[end] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\nend\n\n@testset \"General Neumann Boundary Condition\" begin\n    N = 100\n    h_inv = 1/(N-1)\n    d_order = 2\n    approx_order = 2\n    x = 0:h_inv:\u03c0\n    A = DerivativeOperator{Float64}(2,2,h_inv,N,:Neumann,:Neumann;BC=(1,-1))\n    boundary_points = A.boundary_point_count\n    res = A*sin.(x)\n    @test res \u2248 cos.(x) atol=10.0^approx_order\n    FD = DerivativeOperator{Float64}(1,2,h_inv,N,:None,:None)\n    first_deriv_res = FD*res\n    @test first_deriv_res[1] \u2248 -1.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n    @test first_deriv_res[end] \u2248 +1.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n\n\n    N = 1000\n    h_inv = 1/(N-1)\n    d_order = 2\n    approx_order = 2\n    x = 0:h_inv:1\n    A = DerivativeOperator{Float64}(d_order,approx_order,h_inv,N,:Neumann,:Neumann;BC=(1,-1))\n    boundary_points = A.boundary_point_count\n    res = A*(x.*(1.0.-x))\n    @test res \u2248 -2*ones(size(x)) atol=10.0^-approx_order\n\n    # A = DerivativeOperator{BigFloat}(d_order,approx_order,N,:Neumann0,:Neumann0)\n    # y = convert(Array{BigFloat, 1}, y)\n    # res = A*y\n    # @test res[boundary_points + 1: N - boundary_points] \u2248 24.0*ones(N - 2*boundary_points) atol=10.0^-approx_order;\n    # FD = DerivativeOperator{BigFloat}(1,2,N,:Neumann0,:Neumann0)\n    # first_deriv = FD*res\n    # @test first_deriv[1] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n    # @test first_deriv[end] \u2248 0.0 atol=10.0^-1 ## Derivative at edges in Neumann 0 is 0\n\nend\n", "meta": {"hexsha": "3d15a86b920204ee3a2cec842f60791e235da4d9", "size": 3313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/neumann.jl", "max_stars_repo_name": "npbarnes/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a74ffa8b353c9c4857374e8016b4599eea5ce0c0", "max_stars_repo_licenses": ["MIT"], "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/neumann.jl", "max_issues_repo_name": "npbarnes/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a74ffa8b353c9c4857374e8016b4599eea5ce0c0", "max_issues_repo_licenses": ["MIT"], "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/neumann.jl", "max_forks_repo_name": "npbarnes/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a74ffa8b353c9c4857374e8016b4599eea5ce0c0", "max_forks_repo_licenses": ["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.5921052632, "max_line_length": 138, "alphanum_fraction": 0.6598249321, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741298, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7702505102366287}}
{"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\u0394t = 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)*\u0394t)\n    y_pos_true[i] = y_pos(initial_location[2], initial_velocity[2], (i-1)*\u0394t, gravAcc)\n    Vx_true[i] = initial_velocity[1]\n    Vy_true[i] = velocityY(initial_velocity[2], (i-1)*\u0394t, 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, \u0394t, 0.0, 0.0] [0.0, 1.0, 0.0, 0.0] [0.0, 0.0, 1.0, \u0394t] [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 * \u0394t^2)/2, -(gravAcc * \u0394t)]\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.\u03bc[1]\n    y_filt[i] = current_state.\u03bc[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    (\u03b1, \u03b2) = capm(asset_returns, benchmark_returns; risk_free)\n    \u03b1\nend\n\n\n\n\"\"\"\n    modified_jensen(asset_returns, benchmark_returns; risk_free=0.0)\n\nDivides Jensen\u2019s 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    (\u03b1, \u03b2) = capm(asset_returns, benchmark_returns; risk_free)\n    \u03b1 / \u03b2\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": "using LinearAlgebra: size\nusing Test\nusing SemiLagrangian\n\n# include(\"mpoly/runtests.jl\")\ninclude(\"test_interpolation.jl\")\ninclude(\"test_lagrange.jl\")\ninclude(\"test_hermite.jl\")\ninclude(\"test_splinelu.jl\")\ninclude(\"test_bspline.jl\")\ninclude(\"testfftbig.jl\")\ninclude(\"test_util.jl\")\ninclude(\"test_mesh.jl\")\ninclude(\"test_advection.jl\")\n# include(\"test_poisson1d.jl\")\ninclude(\"test_poisson.jl\")\ninclude(\"test_poisson2d.jl\")\n# include(\"test_rotation1d.jl\")\ninclude(\"test_rotation.jl\")\n# include(\"test_translation1d.jl\")\ninclude(\"test_translation.jl\")\ninclude(\"test_swirling.jl\")\ninclude(\"test_quasigeostrophic.jl\")\n", "meta": {"hexsha": "78b49a3e1df8923f0b152f035b192974e15ec2b7", "size": 612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 25.5, "max_line_length": 35, "alphanum_fraction": 0.7843137255, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.770187084839417}}
{"text": "using Test, ApproxInference\n\nconst VecI  = AbstractVector # Input  Vector\nconst VecIO = AbstractVector # In/Out Vector\nconst MatI  = AbstractMatrix # Input  Matrix\nconst MatIO = AbstractMatrix # In/Out Matrix\n\nprint_head(s::String) = println(\"\\033[1m\\033[32mTesting Task\\033[0m \\033[1m\\033[33m$s\\033[0m\")\nprint_body(s::String) = println(\"             $s\")\n\n##############################\n#   NIST Dataset: BoxBOD     #\n##############################\n@objective struct BoxBOD\n    x::Vector{Float64}; y::Vector{Float64}\n\n    BoxBOD() = new([1., 2., 3., 5., 7., 10.], [109., 149., 149., 191., 213., 224.])\nend\n\nfunction ApproxInference.get_residual!(r::VecIO, \u03b8::VecI, f::BoxBOD)\n    x, y = f.x, f.y\n    @inbounds \u03b81 = \u03b8[1]\n    @inbounds \u03b82 = \u03b8[2]\n    @simd for i in eachindex(x)\n        @inbounds r[i] = y[i] - \u03b81 * (1.0 - exp(-\u03b82 * x[i]))\n    end\n    return nothing\nend\n\nfunction ApproxInference.get_jacobian!(J::MatIO, \u03b8::VecI, f::BoxBOD)\n    x = f.x\n    @inbounds \u03b81 = \u03b8[1]\n    @inbounds \u03b82 = \u03b8[2]\n    @inbounds for i in eachindex(x)\n        tmp = exp(-\u03b82 * x[i])\n        J[i,1] = 1.0 - tmp\n        J[i,2] = \u03b81 * x[i] * tmp\n    end\n    return nothing\nend\n\ninclude(\"./test-BoxBOD-LM.jl\")\ninclude(\"./test-BoxBOD-VI.jl\")\n\n##############################\n#   NIST Dataset: Eckerle4   #\n##############################\n@objective struct Eckerle4\n    x::Vector{Float64}; y::Vector{Float64}\n\n    Eckerle4() = new(\n        # x vector\n        [400.0, 405.0, 410.0, 415.0, 420.0, 425.0, 430.0,\n         435.0, 436.5, 438.0, 439.5, 441.0, 442.5, 444.0,\n         445.5, 447.0, 448.5, 450.0, 451.5, 453.0, 454.5,\n         456.0, 457.5, 459.0, 460.5, 462.0, 463.5, 465.0,\n         470.0, 475.0, 480.0, 485.0, 490.0, 495.0, 500.0],\n        # y vector\n        [1.575000e-04, 1.699000e-04, 2.350000e-04, 3.102000e-04, 4.917000e-04,\n         8.710000e-04, 1.741800e-03, 4.640000e-03, 6.589500e-03, 9.730200e-03,\n         1.490020e-02, 2.373100e-02, 4.016830e-02, 7.125590e-02, 1.264458e-01,\n         2.073413e-01, 2.902366e-01, 3.445623e-01, 3.698049e-01, 3.668534e-01,\n         3.106727e-01, 2.078154e-01, 1.164354e-01, 6.167640e-02, 3.372000e-02,\n         1.940230e-02, 1.178310e-02, 7.435700e-03, 2.273200e-03, 8.800000e-04,\n         4.579000e-04, 2.345000e-04, 1.586000e-04, 1.143000e-04, 7.100000e-05]\n    )\nend\n\nfunction ApproxInference.get_residual!(r::VecIO, \u03b8::VecI, f::Eckerle4)\n    x, y = f.x, f.y\n    @inbounds \u03b81 = \u03b8[1]\n    @inbounds \u03b82 = \u03b8[2]\n    @inbounds \u03b83 = \u03b8[3]\n    @simd for i in eachindex(x)\n        @inbounds r[i] = y[i] - \u03b81 * exp(-0.5 * abs2((x[i] - \u03b83) / \u03b82)) / \u03b82\n    end\n    return nothing\nend\n\nfunction ApproxInference.get_jacobian!(J::MatIO, \u03b8::VecI, f::Eckerle4)\n    x = f.x\n    @inbounds \u03b81 = \u03b8[1]\n    @inbounds \u03b82 = \u03b8[2]\n    @inbounds \u03b83 = \u03b8[3]\n\n    \u03b82\u00b2 = abs2(\u03b82)\n    \u03b82\u00b3 = \u03b82 * \u03b82 * \u03b82\n\n    @inbounds for i in eachindex(x)\n        tmp1 = abs2(x[i] - \u03b83) / \u03b82\u00b2\n        tmp2 = exp(-0.5 * tmp1)\n        J[i,1] = tmp2 / \u03b82\n        J[i,2] = \u03b81 * tmp2 * (tmp1 - 1.0) / \u03b82\u00b2\n        J[i,3] = \u03b81 * (x[i] - \u03b83) * tmp2 / \u03b82\u00b3\n    end\n    return nothing\nend\n\ninclude(\"./test-Eckerle4-LM.jl\")\ninclude(\"./test-Eckerle4-VI.jl\")\n", "meta": {"hexsha": "77a1c81ba18a8d6509452c5c974a45685dc2f404", "size": 3127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "brianyjtai1994/Inference.jl", "max_stars_repo_head_hexsha": "4635fcd17eb44caaeff16dd05e3e58cc9acb5311", "max_stars_repo_licenses": ["MIT"], "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": "brianyjtai1994/Inference.jl", "max_issues_repo_head_hexsha": "4635fcd17eb44caaeff16dd05e3e58cc9acb5311", "max_issues_repo_licenses": ["MIT"], "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": "brianyjtai1994/Inference.jl", "max_forks_repo_head_hexsha": "4635fcd17eb44caaeff16dd05e3e58cc9acb5311", "max_forks_repo_licenses": ["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.9603960396, "max_line_length": 94, "alphanum_fraction": 0.5510073553, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7701615751675646}}
{"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, \u03c4)` function\n# ------------------------------------------------------------------------------------------\n\nusing DynamicalSystems\n\ns = rand(100000)\nD = 3 # reconstruction dimension\n\u03c4 = 4 # reconstruction delay\nR = Reconstruction(s, D, \u03c4)\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 \u03c4 in [5, 30, 100]\n        R = Reconstruction(xyz[i], 2, \u03c4)\n        ax = subplot(3,3,k)\n        plot(R[:, 1], R[:, 2], color = \"C$(k-1)\", lw = 0.8)\n        title(\"var = $i, \u03c4 = $\u03c4\")\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 \u2208 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 `\u03c4` 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 `\u03b5` 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 < \u03b5 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\u03b5 = 0.000001\nwhere_u_at = FixedSizeNeighborhood(\u03b5)\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) \u2265 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 \u200b\u200borganized 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 \u2208 IntervalDomain(t_min,t_max),\n           x \u2208 IntervalDomain(x_min,x_max),\n           y \u2208 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 \u2208 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": "# This implements src/snes/examples/tutorials/ex2.c from PETSc using the PETSc.jl package, using SNES\n#\n# This is the same as SNES_ex2b.j, except that we show how automatic differentiation can be used to\n# compute the jacobian. \n#\n# Newton method to solve u'' + u^{2} = f, sequentially.\n\nusing PETSc, MPI, LinearAlgebra, SparseArrays, Plots, ForwardDiff\n\nif ~MPI.Initialized()\n    MPI.Init()\nend\n\nPETSc.initialize()\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 the residual f, given solution vector x\n```\nfunction FormResidual!(f,x)\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\nend\n\n```\n    Wrapper which makes it easier to compute the jacobian using automatic differntiation\n```\nfunction  ForwardDiff_res(x)\n\n    f   = zero(x)               # vector of zeros, of same type as e\n    FormResidual!(f,x);\n\n    return f;\nend\n\n```\n    Computes the jacobian, given solution vector x\n```\nfunction FormJacobian!(x, args...)\n\n    J        =  args[1];        # preconditioner = args[2], in case we want it to be different from J\n\n    # Use AD to compute jacobian; by transferring x into sparse, the output will be sparse\n    J_julia  =  ForwardDiff.jacobian(ForwardDiff_res,sparse(x));\n\n    J       .=  J_julia;   # copy to petsc format\nend\n\n\n# ==========================================\n# Main code \n\n\n# Compute initial solution\nn   =   101;\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 PETSc (initialize matrix with correct nonzero pattern)\n\n# Setup SNES\nx_s = PETSc.VecSeq(x);                  # solution vector\nres = PETSc.VecSeq(zeros(size(x)));     # residual vector\n\nS = PETSc.SNES{Float64}(MPI.COMM_SELF; \n        snes_rtol=1e-12, \n        snes_monitor=true, \n        snes_converged_reason=true);\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@show norm(res.array)\n\nplot(LinRange(0,1,n),x_sol,xlabel=\"width\",ylabel=\"solution\")\n\n#PETSc.finalize()\n", "meta": {"hexsha": "47a462aa3f5b932d5f109ed4ea61987727e2e9d1", "size": 2889, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/SNES_ex2b.jl", "max_stars_repo_name": "jkozdon/PETSc.jl", "max_stars_repo_head_hexsha": "6f68f083431afb52cd3d369ad1b35bcbedd0598a", "max_stars_repo_licenses": ["MIT"], "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/SNES_ex2b.jl", "max_issues_repo_name": "jkozdon/PETSc.jl", "max_issues_repo_head_hexsha": "6f68f083431afb52cd3d369ad1b35bcbedd0598a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-07T16:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T16:18:15.000Z", "max_forks_repo_path": "examples/SNES_ex2b.jl", "max_forks_repo_name": "jkozdon/PETSc.jl", "max_forks_repo_head_hexsha": "6f68f083431afb52cd3d369ad1b35bcbedd0598a", "max_forks_repo_licenses": ["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.2547169811, "max_line_length": 124, "alphanum_fraction": 0.612322603, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7701101098857402}}
{"text": "# ---\n# title: 746. Min Cost Climbing Stairs\n# id: problem746\n# author: zhwang\n# date: 2022-01-19\n# difficulty: Easy\n# categories: Array, Dynamic Programming\n# link: <https://leetcode.com/problems/min-cost-climbing-stairs/description/>\n# hidden: true\n# ---\n# \n# On a staircase, the `i`-th step has some non-negative cost `cost[i]` assigned\n# (0 indexed).\n# \n# Once you pay the cost, you can either climb one or two steps. You need to find\n# minimum cost to reach the top of the floor, and you can either start from the\n# step with index 0, or the step with index 1.\n# \n# **Example 1:**  \n# \n#     \n#     \n#     Input: cost = [10, 15, 20]\n#     Output: 15\n#     Explanation: Cheapest is start on cost[1], pay that cost and go to the top.\n#     \n# \n# **Example 2:**  \n# \n#     \n#     \n#     Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]\n#     Output: 6\n#     Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].\n#     \n# \n# **Note:**  \n# \n#   1. `cost` will have a length in the range `[2, 1000]`.\n#   2. Every `cost[i]` will be an integer in the range `[0, 999]`.\n# \n# \n## @lc code=start\nusing LeetCode\n\n## Dynamic Programming\nfunction min_cost_climbing_stairs(cost::Vector{Int})::Int\n    first, second = cost[1], cost[2]\n    for c in @view cost[3:end]\n        first, second = second, min(first, second) + c\n    end\n    return min(first, second)\nend\n\n## @lc code=end\n", "meta": {"hexsha": "62128eb96c1a9bc1ed0dd00f5969e4a3df2b06b9", "size": 1400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/746.min-cost-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/746.min-cost-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/746.min-cost-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": 25.0, "max_line_length": 87, "alphanum_fraction": 0.6178571429, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7701101081447139}}
{"text": "# Arvind Prasadan\n# 2019 January\n# DMF Package\n# Creates an Autocorrelation Matrix at a given lag\n\n\"\"\"\n\tautocorr_mat(X, lags = 1)\n\nCreates an Autocorrelation Matrix at a set of given lags.\n\n# Arguments\n- `X`: Data matrix: p dimensions/sensors x n samples\n- `lags`: list of lags (Integral)\n\n# Outputs\n- `R`: Data cube of autocorrelation matrices: # lags x p x p\n- `lags`: Lags used\n\"\"\"\nfunction autocorr_mat(X, lags = 1)\n    \n    p, n = size(X)\n    \n    # Subtract Mean\n    mu = mean(X; dims = 2)\n    X = X .- mu\n    \n    # Get Standard Deviations\n    sigma = std(X; dims = 2)\n    \n    # Sanity check lags\n    lags = abs.(Int.(round.(lags)))\n    if 1 == length(lags)\n        lags = [lags]\n    else\n        lags = [min(x, n - 1) for x in lags]\n        lags = sort(unique(lags))\n    end\n    \n    R_unshaped = autocor(X', lags)\n    R = zeros(length(lags), p, p)\n    for l = 1:1:length(lags)\n        R[l, :, :] = hcat([circshift(R_unshaped[l, :], t)[:] for t in 0:1:(p - 1)]...)\n    end\n    \n    return R, lags\nend\n\n", "meta": {"hexsha": "e1d2e8375373461aa17e1e5abf4ad8ccdff4fbca", "size": 1011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/autocorr_mat.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/autocorr_mat.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/autocorr_mat.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": 21.0625, "max_line_length": 86, "alphanum_fraction": 0.5707220574, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8333245932423309, "lm_q1q2_score": 0.7701101044909983}}
{"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\u03b4\u0302 = \u2202[log N(r)]/\u2202[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, \u03b4\u0302 = linear_regression(logr, logNr)\n    (corrdim=\u03b4\u0302, logr=logr, logNr=logNr, intercept=c)\nend\n\n\"\"\"\n    correlation_dimension(x1, x2, ..., xN; kwargs...) -> \u03b4\u0302\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": "using NumericalMethodsforEngineers\nusing Test\n\nb = [16. -24. 18.; 3. -2. 0.; -9. 18. -17.]\nx0 = [1., 1., 1.]\n\ntol = 1.0e-5\nlimit = 100\n\n(iters, eigval, eigvec) = nmex(b, x0; tol=tol, limit=100)\n\n#eb = eig(b)\nebvals, ebvecs = (eigen(b)...,)\n\n\n@test round.(eigvec[:,1], digits=5) == round.(ebvecs[:,1], digits=5)\n", "meta": {"hexsha": "4d1bf5f54e66c9f196f6de25ba493cc2809b22fb", "size": 311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch01_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": "test/ch01_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": "test/ch01_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": 18.2941176471, "max_line_length": 68, "alphanum_fraction": 0.5819935691, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7700950955969763}}
{"text": "using Test, FinancialMonteCarlo;\n@show \"Black Scholes Model\"\nS0 = 100.0;\nK = 100.0;\nr = 0.02;\nT = 1.0;\nd = 0.01;\nd_ = FinancialMonteCarlo.Curve([0.009999, 0.01], T);\nD = 90.0;\n\nNsim = 10000;\nNstep = 30;\nsigma = 0.2;\nmc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SobolMode());\ntoll = 0.8\n\nspotData1 = ZeroRate(r);\n\nFwdData = Forward(T)\nEUData = EuropeanOption(T, K)\nEUBin = BinaryEuropeanOption(T, K)\nAMData = AmericanOption(T, K)\nAmBin = BinaryEuropeanOption(T, K)\nBarrierData = BarrierOptionDownOut(T, K, D)\nAsianFloatingStrikeData = AsianFloatingStrikeOption(T)\nAsianFixedStrikeData = AsianFixedStrikeOption(T, K)\nModel = BlackScholesProcess(sigma, Underlying(S0, d));\n\ndisplay(Model)\n\n@show FwdPrice = pricer(Model, spotData1, mc, FwdData);\n@show EuPrice = pricer(Model, spotData1, mc, EUData);\n@show EuBinPrice = pricer(Model, spotData1, mc, EUBin);\n@show AmPrice = pricer(Model, spotData1, mc, AMData);\n@show AmBinPrice = pricer(Model, spotData1, mc, AmBin);\n@show BarrierPrice = pricer(Model, spotData1, mc, BarrierData);\n@show AsianPrice1 = pricer(Model, spotData1, mc, AsianFloatingStrikeData);\n\n@test abs(FwdPrice - 99.1078451563562) < toll\n@test abs(EuPrice - 8.43005524824866) < toll\n@test abs(AmPrice - 8.450489415187354) < toll\n@test abs(BarrierPrice - 7.5008664470880735) < toll\n@test abs(AsianPrice1 - 4.774451704549382) < toll\n", "meta": {"hexsha": "91b80a447bdf430f7d7b8fe30b0577700f5e6783", "size": 1359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_black_sobol.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": "test/test_black_sobol.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": "test/test_black_sobol.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": 30.8863636364, "max_line_length": 75, "alphanum_fraction": 0.7387785136, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.947381042195331, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7700950910342951}}
{"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# \u2554\u2550\u2561 1e037376-8252-41fb-ae95-93bc9011b7fa\n# we need to install a special package in order to use the gamma function\nusing SpecialFunctions\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b58cf6d8-291c-49f4-a61a-51f1a7454651\nn = 10000;\n\n# \u2554\u2550\u2561 2f4a8b5e-f7c9-4abc-b04d-3286207a97b3\ndim = 20;\n\n# \u2554\u2550\u2561 4da795ef-b8d3-4c94-bb89-7eeaca9602fb\nmd\"Exact volume is:\"\n\n# \u2554\u2550\u2561 8d8e10d0-2597-4198-92b1-9ab2ebe4b3c8\nexV = exactVol(dim)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c8381d29-3b9f-4399-9a60-c0b6b620e99c\nsphereVolMCImpExp(20, n, 2)\n\n# \u2554\u2550\u2561 0e1580e1-cdae-498e-ab14-261f8a96a802\nmd\" We do the calculation $m$ times and check mean/variance:\"\n\n# \u2554\u2550\u2561 770e2019-420d-415b-b498-96493ac676bf\nm = 1000;\n\n# \u2554\u2550\u2561 dc6e6729-7ce5-45a8-8ecc-b320d283340a\ndata = [sphereVolMCImpExp(20, n, 2) for i in 1:m];\n\n# \u2554\u2550\u2561 fb6c8ff3-d200-4e48-b9ad-aa34d188e675\nmean = sum(data)/m\n\n# \u2554\u2550\u2561 48b51297-b3fb-4bce-8d41-7af6120b553c\nerror = mean - exV\n\n# \u2554\u2550\u2561 bb18d766-cdad-45b7-aebb-c59763896bd4\nvariance = sum(broadcast(x -> (x-mean)^2, data))/m\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u25501e037376-8252-41fb-ae95-93bc9011b7fa\n# \u2560\u255076d6c2d4-e370-4e83-9d04-ca6fc546bdd9\n# \u2560\u2550b58cf6d8-291c-49f4-a61a-51f1a7454651\n# \u2560\u25502f4a8b5e-f7c9-4abc-b04d-3286207a97b3\n# \u255f\u25004da795ef-b8d3-4c94-bb89-7eeaca9602fb\n# \u2560\u25508d8e10d0-2597-4198-92b1-9ab2ebe4b3c8\n# \u2560\u25506a8c6c37-2a48-47c7-8d40-ca276c8a09d2\n# \u2560\u25508de1cad7-ac2c-42ec-9581-1d7ff06d576d\n# \u2560\u2550c8381d29-3b9f-4399-9a60-c0b6b620e99c\n# \u255f\u25000e1580e1-cdae-498e-ab14-261f8a96a802\n# \u2560\u2550770e2019-420d-415b-b498-96493ac676bf\n# \u2560\u2550dc6e6729-7ce5-45a8-8ecc-b320d283340a\n# \u2560\u2550fb6c8ff3-d200-4e48-b9ad-aa34d188e675\n# \u2560\u255048b51297-b3fb-4bce-8d41-7af6120b553c\n# \u2560\u2550bb18d766-cdad-45b7-aebb-c59763896bd4\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "using StatsBase\nusing Test\n\n### Trimming outliers\n\n@test collect(trim([8,2,3,4,5,6,7,1], prop=0.1)) == [8,2,3,4,5,6,7,1]\n@test collect(trim([8,2,3,4,5,6,7,1], prop=0.2)) == [2,3,4,5,6,7]\n@test collect(trim([1,2,3,4,5,6,7,8,9], prop=0.4)) == [4,5,6]\n@test collect(trim([8,7,6,5,4,3,2,1], count=1)) == [7,6,5,4,3,2]\n@test collect(trim([1,2,3,4,5,6,7,8,9], count=3)) == [4,5,6]\n\n\n@test_throws ArgumentError trim([])\n@test_throws ArgumentError trim([1,2,3,4,5], prop=0.5)\n\n@test collect(trim!([8,2,3,4,5,6,7,1], prop=0.1)) == [8,2,3,4,5,6,7,1]\n@test collect(trim!([8,2,3,4,5,6,7,1], prop=0.2)) == [2,3,4,5,6,7]\n@test collect(trim!([1,2,3,4,5,6,7,8,9], prop=0.4)) == [4,5,6]\n@test collect(trim!([8,7,6,5,4,3,2,1], count=1)) == [7,6,5,4,3,2]\n@test collect(trim!([1,2,3,4,5,6,7,8,9], count=3)) == [4,5,6]\n\n@test_throws ArgumentError trim!([])\n@test_throws ArgumentError trim!([1,2,3,4,5], prop=0.5)\n\n@test collect(winsor([8,2,3,4,5,6,7,1], prop=0.1)) == [8,2,3,4,5,6,7,1]\n@test collect(winsor([8,2,3,4,5,6,7,1], prop=0.2)) == [7,2,3,4,5,6,7,2]\n@test collect(winsor([1,2,3,4,5,6,7,8,9], prop=0.4)) == [4,4,4,4,5,6,6,6,6]\n@test collect(winsor([1,2,3,4,5,6,7,8], count=1)) == [2,2,3,4,5,6,7,7]\n@test collect(winsor([8,7,6,5,4,3,2,1], count=1)) == [7,7,6,5,4,3,2,2]\n@test collect(winsor([1,2,3,4,5,6,7,8,9], count=3)) == [4,4,4,4,5,6,6,6,6]\n\n@test_throws ArgumentError winsor([])\n@test_throws ArgumentError winsor([1,2,3,4,5], prop=0.5)\n\n@test collect(winsor!([8,2,3,4,5,6,7,1], prop=0.1)) == [8,2,3,4,5,6,7,1]\n@test collect(winsor!([8,2,3,4,5,6,7,1], prop=0.2)) == [7,2,3,4,5,6,7,2]\n@test collect(winsor!([1,2,3,4,5,6,7,8,9], prop=0.4)) == [4,4,4,4,5,6,6,6,6]\n@test collect(winsor!([8,7,6,5,4,3,2,1], count=1)) == [7,7,6,5,4,3,2,2]\n@test collect(winsor!([1,2,3,4,5,6,7,8,9], count=3)) == [4,4,4,4,5,6,6,6,6]\n\n@test_throws ArgumentError winsor!([])\n@test_throws ArgumentError winsor!([1,2,3,4,5], prop=0.5)\n\n### Variance\n\n@test trimvar([1,1,1,1,1]) \u2248 0.0\n@test trimvar([2,3,4,5,6,7,8,9], prop=0.25) \u2248 1.0\n\n@test_throws ArgumentError trimvar([])\n@test_throws ArgumentError trimvar([1,2,3,4,5], prop=0.5)\n\n### Other\n\n@test mean(trim([-Inf,1,2,3,4], count=1)) == 2\n@test mean(winsor([-Inf,1,2,3,4], count=1)) == 2\n", "meta": {"hexsha": "9d35c9b7297f119fa6d642d18ecffef7a0369757", "size": 2200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/robust.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": "test/robust.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": "test/robust.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": 39.2857142857, "max_line_length": 76, "alphanum_fraction": 0.5836363636, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7700652344866579}}
{"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)*\u03c0\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`, `\u03c9(A)`.\n\nUses `eigvals()`. `\u03c9(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]):  \u03bb = $(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": "@testset \"moments\" begin\n\n# Build histogram from an image correctly and compare the threshold to the answer\n# from another implementation.\nimg = testimage(\"cameraman\")\nimgg = gray.(img)\nimgg_uint8 = reinterpret.(imgg)\nedges, counts = build_histogram(imgg_uint8, 0:1:255)\nt1 = find_threshold(Moments(),counts[1:end], 0:1:255)\n@test t1 == 111\n\n# Build a histogram from an array and compare the threshold to that in another\n# implementation.\narr = [10  8 10  9 20 21 32 30 40 41 41 40;\n       12 10 11 10 19 20 30 28 38 40 40 39;\n       10  9 10  8 20 21 30 29 42 40 40 39;\n       11 10  9 11 19 21 31 30 40 42 38 40]\nedges, counts = build_histogram(arr, 0:255)\nt2 = find_threshold(Moments(), counts[1:end], edges)\n@test t2 == 27\n\nend\n", "meta": {"hexsha": "0409eb9965cba3a0dac5231edcf164d450459fec", "size": 732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/moments.jl", "max_stars_repo_name": "AbbeyMac/HistogramThresholding", "max_stars_repo_head_hexsha": "8195a1319049283ba052725f35ea2450d8af4514", "max_stars_repo_licenses": ["MIT"], "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/moments.jl", "max_issues_repo_name": "AbbeyMac/HistogramThresholding", "max_issues_repo_head_hexsha": "8195a1319049283ba052725f35ea2450d8af4514", "max_issues_repo_licenses": ["MIT"], "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/moments.jl", "max_forks_repo_name": "AbbeyMac/HistogramThresholding", "max_forks_repo_head_hexsha": "8195a1319049283ba052725f35ea2450d8af4514", "max_forks_repo_licenses": ["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.8260869565, "max_line_length": 81, "alphanum_fraction": 0.6953551913, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.77005103668378}}
{"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": "# using Pkg; Pkg.add(\"https://github.com/QuantEcon/Games.jl\")\r\n\r\n#module beautifulmind \r\n\r\nusing Games\r\n\r\n#-----------------------------------------------------------------\r\n\r\n# defines the simultaneous game\r\nfunction init()\r\n\r\nif uppercase(\"n\") == uppercase(query(\"\\n*****Simultaneous games ****\\n\\nDefine own game?(y/n)\\n\\n\\tchoice: \"))\r\n    mat = Array{Float64}(undef, 2, 2, 2)\r\n    mat[1, 1, :] = [3, 2]  \r\n    mat[1, 2, :] = [2, 2]\r\n    mat[2, 1, :] = [2, 3]\r\n    mat[2, 2, :] = [5, 0]\r\n\r\n    sim = NormalFormGame(mat)\r\n    determineStrategy(sim)\r\n    output(sim)\r\nelse\r\n\r\n\r\n\r\nprintln(\"Defining own game\\n\")\r\n    if 1 == parse(Int,query(\"choose input method\\n\\t1.by matrix\\n\\t2.by vector\\n\\n\\tchoice: \"))\r\n\r\n        matrix = Array{Int}(undef, 2, 2, 2)\r\n        for o in 1:2\r\n            for i in 1:2\r\n             \r\n             str = query(\"Input values for row $o column $i e.g(2 5): \")\r\n            matrix[o, i, :] =  [parse(Int,split(str,\" \")[1]), parse(Int,split(str,\" \")[2])]\r\n    \r\n            end\r\n        end\r\n        game = NormalFormGame(matrix)\r\n        determineStrategy(game)\r\n        output(game)\r\n    else\r\n\r\n         p1 = [1 2 ; 3 4]\r\n          str = replace(query(\"Input player1 strategies e.g(2 5;3 7): \"),\";\" => \"\")\r\n          str = replace(str,\" \" => \"\")\r\n\r\n          for (i,x) in enumerate(str)\r\n             p1[i]=parse(Int,x)\r\n          end \r\n\r\n        p1 = Player(p1)\r\n\r\n         \r\n          p2 = [1 2 ; 3 4]\r\n          str = replace(query(\"Input player2 strategies e.g(2 5;3 7): \"),\";\" => \"\")\r\n          str = replace(str,\" \" => \"\")\r\n\r\n          for (i,x) in enumerate(str)\r\n             p2[i]=parse(Int,x)\r\n         end \r\n\r\n        p2 = Player(p2)\r\n\r\n        game = NormalFormGame(p1,p2)\r\n        determineStrategy(game)\r\n        output(game)\r\n    end\r\n\r\n  end\r\nend\r\n\r\n#-----------------------------------------------------------------\r\n\r\nfunction determineStrategy(game)\r\n\r\n\r\n    a = query(\"\\n\\nwhat is player1's first strategy e.g(a): \")\r\n    b = query(\"\\nwhat is player1's second strategy e.g(b): \")\r\n\r\n    c = query(\"\\nwhat is player2's first strategy e.g(c): \")\r\n    d = query(\"\\nwhat is player2's second strategy e.g(d): \")\r\n\r\n\r\n    act11 = game.players[1].payoff_array[1] + game.players[1].payoff_array[3]\r\n\r\n    act12 = game.players[1].payoff_array[2] +game.players[1].payoff_array[4]  \r\n\r\n    act21 = game.players[2].payoff_array[1] + game.players[2].payoff_array[2]\r\n    act22 = game.players[2].payoff_array[3] + game.players[2].payoff_array[4]\r\n\r\nprintln(\"\\n\")\r\n\r\n    if act11 > act12\r\n        println(\"player1  dominant strategy: $a\\n         dominated stratergy: $b\")\r\n    end\r\n\r\n    if act12 > act11\r\n        println(\"player1  dominant strategy: $b\\n         dominated stratergy: $a\")\r\n    elseif act11 == act12\r\n        println(\"player1's strategies are equal\")\r\n    end\r\n\r\n\r\n     if(act21>act22)\r\n        println(\"player2  dominant strategy: $c\\n         dominated stratergy: $d\")\r\n    elseif(act22>act21)\r\n        println(\"player2  dominant strategy: $d\\n         dominated stratergy: $c\")\r\n    else\r\n        println(\"player2's strategies are equal\")\r\n    end\r\n\r\n   # best_responses(game.players[1], game.players[1])\r\n   \r\n\r\n\r\n   \r\n    return\r\nend\r\n\r\n#-----------------------------------------------------------------\r\n\r\nfunction output(game::NormalFormGame)\r\n    equilibria = pure_nash(game)\r\n    equilibriaNo = length(equilibria)\r\n\r\n    if equilibriaNo == 0\r\n        str = \"no pure Nash equilibrium found\"\r\n    elseif equilibriaNo == 1\r\n        str = \"There is 1 equilibrium at:\\n$(equilibria[1])\"\r\n    else\r\n        str = \"There is $equilibriaNo  equilibria:\\n\"\r\n        for (i, E) in enumerate(equilibria)\r\n            i < equilibriaNo ? str *= \"$E, \" : str *= \"$E\"\r\n        end\r\n    end\r\n    println(join([\"\\n\",str]))\r\n    \r\nend\r\n\r\n#-----------------------------------------------------------------\r\n\r\nfunction query(str::String)\r\n\r\n    print(str);\r\n   return input = readline();\r\n\r\nend\r\n\r\n#-----------------------------------------------------------------\r\n\r\ninit() #driver statement\r\n#end #module\r\n", "meta": {"hexsha": "021322c494b9621f412a2112a0d3a45464072c36", "size": 4054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "prob2.jl", "max_stars_repo_name": "Qronus/AIG.3", "max_stars_repo_head_hexsha": "99298ee86860a69ad2bbf1df9d501443b9d60867", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prob2.jl", "max_issues_repo_name": "Qronus/AIG.3", "max_issues_repo_head_hexsha": "99298ee86860a69ad2bbf1df9d501443b9d60867", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prob2.jl", "max_forks_repo_name": "Qronus/AIG.3", "max_forks_repo_head_hexsha": "99298ee86860a69ad2bbf1df9d501443b9d60867", "max_forks_repo_licenses": ["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.4967320261, "max_line_length": 111, "alphanum_fraction": 0.494326591, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7700510351108918}}
{"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) \u00f7 2 \n        pad_c = (filter_c - 1) \u00f7 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 \u03c3 in both dimensions\nfunction gaussian_kernel(\u03c3::Real; l::Int = 4*ceil(Int,\u03c3)+1)\n    isodd(l) || throw(ArgumentError(\"length must be odd\"))\n    w = l>>1\n    g = \u03c3 == 0 ? [exp(0/(2*oftype(\u03c3, 1)^2))] : [exp(-x^2/(2*\u03c3^2)) for x=-w:w]\n    k = g/sum(g)\n    return (k * k')\nend\n\n# gaussian kernel with different \u03c3s in both dimensions\nfunction gaussian_kernel(\n    \u03c3s::Tuple{Real, Real}; \n    l::Tuple{Int, Int} = (4*ceil(Int,\u03c3s[1])+1, 4*ceil(Int,\u03c3s[2])+1)\n)\n    all(isodd.(l)) || throw(ArgumentError(\"length must be odd\"))\n    w1 = l[1]>>1\n    g1 = \u03c3s[1] == 0 ? [exp(0/(2*oftype(\u03c3s[1], 1)^2))] : [exp(-x^2/(2*\u03c3s[1]^2)) for x=-w1:w1]\n    k1 = g1/sum(g1)\n\n    w2 = l[2]>>1\n    g2 = \u03c3s[2] == 0 ? [exp(0/(2*oftype(\u03c3s[2], 1)^2))] : [exp(-x^2/(2*\u03c3s[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": "### A Pluto.jl notebook ###\n# v0.19.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# \u2554\u2550\u2561 2d3d462e-d6bf-4ebd-ab34-db38f4261a11\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 18b5c138-9324-4c5a-86ca-be1e825ed11e\nbegin\n\tusing PlutoUI\n\tusing Random\n\tusing Distributions\n\tusing StatsPlots\n\tusing StatsBase\n\tusing LaTeXStrings\n\tusing CSV\n\tusing DataFrames\n\tusing PrettyTables\n\tusing StatisticalRethinking\n\tusing StatisticalRethinkingPlots\n\tusing LinearAlgebra\n\tusing Logging\n\tusing AxisKeys\n\tusing NamedDims\n\tusing NamedArrays\n\tusing DataStructures\n\tusing Random\n\tusing Turing\n\tusing ParetoSmooth\nend\n\n# \u2554\u2550\u2561 58b9da10-8cbd-42e4-bddf-ec4995ac756c\nmd\" ## Turing guide\"\n\n# \u2554\u2550\u2561 d3c6c774-a158-485c-acd1-e366c24df4bc\nmd\" ##### Widen notebook.\"\n\n# \u2554\u2550\u2561 0f75e85c-4506-483f-b0f8-a31ee698bf04\nhtml\"\"\"\n<style>\n\tmain {\n\t\tmargin: 0 auto;\n\t\tmax-width: 2000px;\n    \tpadding-left: max(160px, 10%);\n    \tpadding-right: max(160px, 10%);\n\t}\n</style>\n\"\"\"\n\n# \u2554\u2550\u2561 cb180e21-3778-40f1-93d8-af442d1be559\nmd\" ##### Commonly used packages in SR2TuringPluto\"\n\n# \u2554\u2550\u2561 a2d950f8-d780-4abe-af37-b189bd4a5e88\nmd\"##### Setting default attributes for logging and plots.\"\n\n# \u2554\u2550\u2561 bbb4a889-77e2-449b-9258-883e7434e641\nbegin\n\tLogging.disable_logging(Logging.Warn);\nend;\n\n# \u2554\u2550\u2561 496b257c-ea62-40b2-b1c9-e92fdda1d688\nbegin\n\thowell = CSV.read(sr_datadir(\"Howell1.csv\"), DataFrame)\n\thowell1 = howell[howell.age .>= 18, :]\n\tPRECIS(howell1)\nend\n\n# \u2554\u2550\u2561 96760a8e-8561-4576-a7c7-70596fa20d33\nmd\" ### Statistical Rethinking (SR2) models.\"\n\n# \u2554\u2550\u2561 b83bc4d0-8c65-40a8-9187-70ef2a0ff38d\nmd\"In the book and associated R package `rethinking`, statistical models are defined as illustrated below:\n\n```\nflist <- alist(\n  height ~ dnorm( mu , sigma ) ,\n  mu <- a + b*weight ,\n  a ~ dnorm( 156 , 100 ) ,\n  b ~ dnorm( 0 , 10 ) ,\n  sigma ~ dunif( 0 , 50 )\n)\n```\"\n\n# \u2554\u2550\u2561 b583eb23-4045-420c-80d5-4f339ebb6ad4\nmd\" ##### An equivalent Turing model:\"\n\n# \u2554\u2550\u2561 d5d66e16-487e-4214-b702-728dc3db32cc\n@model function ppl4_1(weights, heights)\n    a ~ Normal(178, 20)\n    b ~ LogNormal(0, 1)\n    \u03c3 ~ Uniform(0, 50)\n    \u03bc = a .+ b .* weights\n    for i in eachindex(heights)\n        heights[i] ~ Normal(\u03bc[i], \u03c3)\n    end\nend\n\n# \u2554\u2550\u2561 b14217e8-1f70-44cc-8d3c-528ab55e27ef\nmd\"\n!!! note\n\nThe sequence of the statements matter in Turing models!\"\n\n# \u2554\u2550\u2561 b3adef33-c111-4d20-b277-a5346eae9f23\nbegin\n\tm4_1t = ppl4_1(howell1.weight, howell1.height)\n\tpost4_1t = sample(m4_1t, NUTS(), MCMCThreads(), 1000, 4)\n\tpost4_1t_df = DataFrame(post4_1t)\n\tPRECIS(post4_1t_df)\nend\n\n# \u2554\u2550\u2561 6869d583-1590-4210-b696-b63fd7857e09\nplot(post4_1t)\n\n# \u2554\u2550\u2561 1f4e22a4-5fba-4331-9bf9-dd886ce45e74\nbegin\n\tx = 30.0:0.1:64.0\n\tpreds = mean(post4_1t[:a]) .+ mean(post4_1t[:b]) .* x\n\tplot(x, preds, color=:darkblue, label=\"Regression line\")\n\tscatter!(howell1.weight, howell1.height, marker=:cross, markersize=3,\n\t\tcolor=:darkred, label=\"Observations\")\nend\n\n# \u2554\u2550\u2561 cbe1028d-829d-4ed4-840d-d74f151f55bb\nCHNS(post4_1t[[:a, :b, :\u03c3, :lp, :log_density]])\n\n# \u2554\u2550\u2561 75ee3adf-2988-4f42-a0b5-21abe5829120\nmd\" ### Priors of Turing models.\"\n\n# \u2554\u2550\u2561 63db6c9f-ba40-41a2-975d-798d9f2cbeab\nlet\n\tpriors4_1t = sample(m4_1t, Prior(), 1000)\n\tPRECIS(DataFrame(priors4_1t))\nend\n\n# \u2554\u2550\u2561 534edcc4-2dac-4ddb-a6a9-55ee38a3e7ae\nmd\" ### Quadratic approximation.\"\n\n# \u2554\u2550\u2561 7c8e8a61-b1c1-4f9a-addc-61a987c2c5d2\nmap_estimate = optimize(m4_1t, MAP())\n\n# \u2554\u2550\u2561 a9d5118d-8fc7-4353-bb20-6b87ae0e9247\nbegin\n\t\u00e2, b\u0302, \u03c3\u0302 = map_estimate.values\n\t(\u00e2 = \u00e2, b\u0302 = b\u0302, \u03c3\u0302 = \u03c3\u0302)\nend\n\n# \u2554\u2550\u2561 f41d6486-7589-4b67-9eaf-92956622226a\nlet\n\tx = 30:0.1:65\n\tplot(x, \u00e2 .+ b\u0302 .* x)\n\tscatter!(howell1.weight, howell1.height, leg=false)\nend\n\n# \u2554\u2550\u2561 9f92d0a7-45ce-4148-b6a5-7ede9dc09234\nmd\" ### Prediction.\"\n\n# \u2554\u2550\u2561 1cc80dac-1120-4520-b73f-0e31dc1d8721\nbegin\n\tx_test = [31, 40, 50, 60, 63]\n\tm_test = ppl4_1(x_test, fill(missing, length(x_test)))\n\tpred4_1t = predict(m_test, post4_1t)\n\tPRECIS(DataFrame(pred4_1t))\nend\n\n# \u2554\u2550\u2561 159e07b6-dcd7-4ca7-9d3e-f5059b1b8803\nmd\"##### Get the mean predicted values.\"\n\n# \u2554\u2550\u2561 85121bc0-447a-4b79-ac6c-ce91871ca7d8\nbegin\n\tpred_summary_df = DataFrame()\n\tpred_summary_df.parameters = names(pred4_1t)\n\tpred_summary_df.mean = mean(pred4_1t)[:, 2]\n\tpred_summary_df.std = vec(std(Array(group(pred4_1t, :heights)); dims = 1))\n\tpred_summary_df.lower = hpd(pred4_1t; alpha=0.11)[:, 2]\n\tpred_summary_df.upper = hpd(pred4_1t; alpha=0.11)[:, 3]\n\tpred_summary_df\nend\n\n# \u2554\u2550\u2561 84b6ab83-7e65-477f-b87f-298d8b5eacea\nlet\n\tscatter(howell1.weight, howell1.height, lab=\"Observations\",leg=:bottomright)\n\tscatter!(x_test, pred_summary_df.mean,\n    \tmarkersize=5, color=:red, lab=\"Predictions at x_test\")\n\tx = range(minimum(howell1.weight), stop=maximum(howell1.weight), length=200)\n\tg(x) = mean(post4_1t[:a]) + mean(post4_1t[:b]) * x\n\tplot!(x, g.(x), lab=\"Regression line\", leg=:bottomright)\nend\n\n# \u2554\u2550\u2561 2d373995-f303-48b7-8cc3-1daf35d5ed36\nmd\" ### StatisticalRethinking link() function.\"\n\n# \u2554\u2550\u2561 91a627e0-a46c-40f8-a5c2-2f3b25187074\n@bind N Slider(1:1000, default=500)\n\n# \u2554\u2550\u2561 a492bfeb-452c-4138-b5a2-6d2c4cdd114b\nlet\n\txseq = 31:63\n\t\u03bc = StatisticalRethinking.link(post4_1t_df, [:a, :b], xseq)\n\t\u03bc = hcat(\u03bc...)\n\n\tp = plot(; xlim=xseq, ylim=xseq, \n\t\txlab=\"weight\", ylab=\"height\", \n\t\ttitle=\"Regression lines ($N) from draws\",\n\t\tleg=false\n\t)\n\tfor y \u2208 first(eachrow(\u03bc), N)\n\t\tplot!(p, xseq, y; c=:lightgrey, alpha=0.3)\n\tend\n\tp\nend\n\n# \u2554\u2550\u2561 ccf333ff-af94-439a-b41c-5be04c076007\nmd\"\"\"\n!!! note\n\nClick on \"Live docs\" and place cursor on link to see more help. \n\nClick little down arrow to the right to remove live docs again.\n\"\"\"\n\n# \u2554\u2550\u2561 65eaad30-7f58-4eb1-b458-07688dfeac81\nmd\" ### Model comparison\"\n\n# \u2554\u2550\u2561 3283d295-c60e-44bd-9547-8285cdbce9a9\nRandom.seed!(129111)\n\n# \u2554\u2550\u2561 de4e3b12-174b-4740-acab-db6d2a55eb0a\nbegin\n\tdf = CSV.read(sr_datadir(\"WaffleDivorce.csv\"), DataFrame)\n\tdf.D = zscore(df.Divorce)\n\tdf.M = zscore(df.Marriage)\n\tdf.A = zscore(df.MedianAgeMarriage)\n\tdata = (D=df.D, A=df.A)\nend;\n\n# \u2554\u2550\u2561 28bf03e4-2899-4f34-a8aa-892937ede3f9\nfunction lin(a, b, c, x...)\n\tresult = @. a + b * c\n\tfor i in 1:2:length(x)\n\t\t@. result += x[i] * x[i + 1]\n\tend\n\treturn result\nend\n\n# \u2554\u2550\u2561 30707462-75f5-4da9-9677-d7208f20a4fb\n@model function ppl5_1(A, D)\n\ta ~ Normal(0, 0.2)\n\tbA ~ Normal(0, 0.5)\n\t\u03c3 ~ Exponential(1)\n\tfor i in eachindex(D)\n\t\t\u03bc = lin(a, A[i], bA)\n\t\tD[i] ~ Normal(\u03bc, \u03c3)\n\tend\nend\n\n# \u2554\u2550\u2561 18b3a4a5-2506-4ced-8917-3da988c94eba\nbegin\n\tm5_1t = ppl5_1(df.A, df.D)\n\tchn5_1t = sample(m5_1t, NUTS(1000, 0.9), MCMCThreads(), 1000, 12)\n\tPRECIS(DataFrame(chn5_1t))\nend\n\n# \u2554\u2550\u2561 91b50108-414d-4520-8e57-5eaa58061b1a\n@model function ppl5_2(M, D)\n\ta ~ Normal(0, 0.2)\n\tbM ~ Normal(0, 0.5)\n\t\u03c3 ~ Exponential(1)\n\tfor i in eachindex(D)\n\t\t\u03bc = lin(a, M[i], bM)\n\t\tD[i] ~ Normal(\u03bc, \u03c3)\n\tend\nend\n\n# \u2554\u2550\u2561 f11d0597-8962-4cd7-8637-aef99abce80a\nbegin\n\tm5_2t = ppl5_2(df.M, df.D)\n\tchn5_2t = sample(m5_2t, NUTS(1000, 0.9), MCMCThreads(), 1000, 12)\n\tPRECIS(DataFrame(chn5_2t))\nend\n\n# \u2554\u2550\u2561 a0834a65-1f5e-497a-89ab-36adf38d1118\n@model function ppl5_3(A, M, D)\n\ta ~ Normal(0, 0.2)\n\tbA ~ Normal(0, 0.5)\n\tbM ~ Normal(0, 0.5)\n\t\u03c3 ~ Exponential(1)\n\tfor i in eachindex(D)\n\t\t\u03bc = a + M[i] * bM + A[i] * bA\n\t\tD[i] ~ Normal(\u03bc, \u03c3)\n\tend\nend\n\n# \u2554\u2550\u2561 ba0b9017-12c9-446d-a8dd-647d8735d2b0\nbegin\n\tm5_3t = ppl5_3(df.A, df.M, df.D)\n\tchn5_3t = sample(m5_3t, NUTS(1000, 0.9), MCMCThreads(), 1000, 12)\n\tPRECIS(DataFrame(chn5_3t))\nend\n\n# \u2554\u2550\u2561 e0febcf9-6e87-4ecc-8ef9-e27ab79af2fc\nfunction model_elpd(psis::T; digits=2) where {T <: PsisLoo}\n\tNamedArray(\n\t\tround.(Array(psis.estimates); digits=digits), \n\t\t(OrderedDict(:cv_elpd=>1, :naive_lpd=>2, :p_eff=>3), \n\t\tOrderedDict(:total=>1, :se_total=>2, :mean=>3, :se_mean=>4)),\n               (\"Statistic\", \"Value\")\n\t)\nend\n\n# \u2554\u2550\u2561 c82d6f3b-6a27-4cff-9043-c301aa09d53e\nbegin\n\t#pw_lls5_1t = pointwise_log_likelihoods(m5_1t, chn5_1t)\n\tpsis5_1t = psis_loo(m5_1t, chn5_1t)\n\tmodel_elpd(psis5_1t; digits=1)\nend\n\n# \u2554\u2550\u2561 74977e3a-b168-4bcd-a260-7191c60130ac\nbegin\n\t#pw_lls5_2t = pointwise_log_likelihoods(m5_2t, chn5_2t)\n\tpsis5_2t = psis_loo(m5_2t, chn5_2t)\n\tmodel_elpd(psis5_2t; digits=1)\nend\n\n# \u2554\u2550\u2561 7d6161c6-4805-4ee9-8d9a-d8f95faf47d7\nbegin\n\t#pw_lls5_3t = pointwise_log_likelihoods(m5_3t, chn5_3t)\n\tpsis5_3t = psis_loo(m5_3t, chn5_3t)\n\tmodel_elpd(psis5_3t; digits=1)\nend\n\n# \u2554\u2550\u2561 d8eb2079-2915-46e5-ac55-6849143aa194\nmd\"\"\"\n\n```\ndf_waic = compare([m5_1s, m5_2s, m5_3s], :waic)\n3\u00d78 DataFrame\n Row \u2502 models  WAIC     lppd     SE       dWAIC    dSE      pWAIC    weight  \n     \u2502 String  Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502 m5.1s     125.6   118.49    12.56      0.0     0.0      3.57     0.73\n   2 \u2502 m5.3s     127.6   118.13    12.63      2.0     0.74     4.72     0.27\n   3 \u2502 m5.2s     139.2   133.4      9.8      13.6     9.15     2.88     0.0\n\ncompare([m5_1s, m5_2s, m5_3s], :psis)\n3\u00d78 DataFrame\n Row \u2502 models  PSIS     lppd     SE       dPSIS    dSE      pPSIS    weight  \n     \u2502 String  Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502 m5.1s     125.1   118.49    12.35      0.0     0.0      3.57     0.71\n   2 \u2502 m5.3s     126.9   118.13    12.42      1.8     0.72     4.72     0.29\n   3 \u2502 m5.2s     138.7   133.4      9.7      13.6     8.87     2.88     0.0\n```\n\"\"\"\n\n# \u2554\u2550\u2561 5e18ac09-76e1-44a1-93a9-408d6971a5f6\nfunction compare_models(nt; digits=2)\n\tcomps = loo_compare(nt)\n\testimates = comps.estimates\n\tmodels = Pair{Symbol, Int}[]\n\tfor (indx, name) in enumerate(estimates.model)\n\t\tappend!(models, [name => indx])\n\tend\n\t\n\tNamedArray(\n\t\tround.(Array(estimates); digits=2), \n\t\t(OrderedDict(models...), \n\t\tOrderedDict(:cv_elpd=>1, :cv_avg=>2, :weight=>3)),\n               (\"Statistic\", \"Comparison\")\n\t)\nend\n\n# \u2554\u2550\u2561 cc0b2fad-d508-4135-8203-72e3d130fea1\nmc = compare_models((m5_1t=psis5_1t, m5_2t=psis5_2t, m5_3t=psis5_3t))\n\n# \u2554\u2550\u2561 3d2862bc-c217-4e8d-bf88-24e7e3b3eaa7\nmc[:m5_3t, :weight]\n\n# \u2554\u2550\u2561 222a9455-f017-47ff-bd52-42179f4a0320\nmd\" ### Graphs and DAGs.\"\n\n# \u2554\u2550\u2561 faeea7c5-d921-4dbe-9f72-d3e0ae17748f\nmd\" ### Working with ... .\"\n\n# \u2554\u2550\u2561 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nAxisKeys = \"94b1ba4f-4ee9-5380-92f1-94cde586c3c5\"\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nDataStructures = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nDrWatson = \"634d3b9d-ee7a-5ddf-bec9-22491ea816e1\"\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nLogging = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\nNamedArrays = \"86f7a689-2022-50b4-a561-43c23ac3c673\"\nNamedDims = \"356022a1-0364-5f58-8944-0da4b18d706f\"\nParetoSmooth = \"a68b5a21-f429-434e-8bfa-46b447300aac\"\nPkg = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPrettyTables = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatisticalRethinking = \"2d09df54-9d0f-5258-8220-54c2a3d4fbee\"\nStatisticalRethinkingPlots = \"e1a513d0-d9d9-49ff-a6dd-9d2e9db473da\"\nStatsBase = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nTuring = \"fce5fe82-541a-59a6-adf8-730c64b5f9a0\"\n\n[compat]\nAxisKeys = \"~0.1.25\"\nCSV = \"~0.10.4\"\nDataFrames = \"~1.3.3\"\nDataStructures = \"~0.18.11\"\nDistributions = \"~0.25.53\"\nDrWatson = \"~2.9.1\"\nLaTeXStrings = \"~1.3.0\"\nNamedArrays = \"~0.9.6\"\nNamedDims = \"~0.2.47\"\nParetoSmooth = \"~0.7.1\"\nPlutoUI = \"~0.7.38\"\nPrettyTables = \"~1.3.1\"\nStatisticalRethinking = \"~4.5.0\"\nStatisticalRethinkingPlots = \"~1.0.1\"\nStatsBase = \"~0.33.16\"\nStatsPlots = \"~0.14.33\"\nTuring = \"~0.21.1\"\n\n[extras]\nCPUSummary = \"2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9\"\n\"\"\"\n\n# \u2554\u2550\u2561 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.9.0-DEV\"\nmanifest_format = \"2.0\"\nproject_hash = \"a1d8f581b38228f11a3cd149dbd606d40d7b4284\"\n\n[[deps.ANSIColoredPrinters]]\ngit-tree-sha1 = \"574baf8110975760d391c710b6341da1afa48d8c\"\nuuid = \"a4c015fc-c6ff-483c-b24f-f7ea428134e9\"\nversion = \"0.0.1\"\n\n[[deps.AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[deps.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[[deps.AbstractPPL]]\ndeps = [\"AbstractMCMC\", \"DensityInterface\", \"Setfield\", \"SparseArrays\"]\ngit-tree-sha1 = \"6320752437e9fbf49639a410017d862ad64415a5\"\nuuid = \"7a57a42e-76ec-4ea3-a279-07e840d6d9cf\"\nversion = \"0.5.2\"\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.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[[deps.AdvancedMH]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Random\", \"Requires\"]\ngit-tree-sha1 = \"5d9e09a242d4cf222080398468244389c3428ed1\"\nuuid = \"5b7e9947-ddc0-4b3f-9b55-0d8042f74170\"\nversion = \"0.6.7\"\n\n[[deps.AdvancedPS]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Libtask\", \"Random\", \"StatsFuns\"]\ngit-tree-sha1 = \"78620daebe1b87dfe17cac4bc08cec73b057eb0a\"\nuuid = \"576499cb-2369-40b2-a588-c64705576edc\"\nversion = \"0.3.7\"\n\n[[deps.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[[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\"\nversion = \"1.1.1\"\n\n[[deps.Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\", \"Logging\"]\ngit-tree-sha1 = \"288d58589d4249a63095f3f41ece91bf34c32c19\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.5.0\"\n\n[[deps.Arpack_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"4c31b0101997beb213a9e6c39116b052e73ca38c\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.8.0+0\"\n\n[[deps.ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"c933ce606f6535a7c7b98e1d86d5d1014f730596\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"5.0.7\"\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.AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"cf6875678085aed97f52bfc493baaebeb6d40bcb\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.5\"\n\n[[deps.AxisKeys]]\ndeps = [\"AbstractFFTs\", \"ChainRulesCore\", \"CovarianceEstimation\", \"IntervalSets\", \"InvertedIndices\", \"LazyStack\", \"LinearAlgebra\", \"NamedDims\", \"OffsetArrays\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"d6ff375e8229819ef8e443b25009091e0e88eb24\"\nuuid = \"94b1ba4f-4ee9-5380-92f1-94cde586c3c5\"\nversion = \"0.1.25\"\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.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[[deps.BitTwiddlingConvenienceFunctions]]\ndeps = [\"Static\"]\ngit-tree-sha1 = \"28bbdbf0354959db89358d1d79d421ff31ef0b5e\"\nuuid = \"62783981-4cbd-42fc-bca8-16325de8dc4b\"\nversion = \"0.1.3\"\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.CPUSummary]]\ndeps = [\"CpuId\", \"IfElse\", \"Static\"]\ngit-tree-sha1 = \"913b28a04929053e4310d0a4915f1efe195c0ce6\"\nuuid = \"2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9\"\nversion = \"0.1.19\"\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.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.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[[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.CodecZlib]]\ndeps = [\"TranscodingStreams\", \"Zlib_jll\"]\ngit-tree-sha1 = \"ded953804d019afa9a3f98981d99b33e3db7b6da\"\nuuid = \"944b1d66-785c-5afd-91f1-9de20f533193\"\nversion = \"0.7.0\"\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.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 = \"b153278a25dd42c65abbf4e62344f9d22e59191b\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.43.0\"\n\n[[deps.CompatHelperLocal]]\ndeps = [\"DocStringExtensions\", \"Pkg\", \"UUIDs\"]\ngit-tree-sha1 = \"908a50c2805d2571379fe1595585148c8352f63e\"\nuuid = \"5224ae11-6099-4aaa-941d-3aab004bd678\"\nversion = \"0.1.20\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\nversion = \"0.5.2+0\"\n\n[[deps.CompositionsBase]]\ngit-tree-sha1 = \"455419f7e328a1a2493cabc6428d79e951349769\"\nuuid = \"a33af91c-f02d-484b-be07-31d278c5ca2b\"\nversion = \"0.1.1\"\n\n[[deps.ConsoleProgressMonitor]]\ndeps = [\"Logging\", \"ProgressMeter\"]\ngit-tree-sha1 = \"3ab7b2136722890b9af903859afcf457fa3059e8\"\nuuid = \"88cd18e8-d9cc-4ea6-8889-5259c0d15c8b\"\nversion = \"0.1.2\"\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.CovarianceEstimation]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"a3e070133acab996660d31dcf479ea42849e368f\"\nuuid = \"587fd27a-f159-11e8-2dae-1979310e6154\"\nversion = \"0.2.7\"\n\n[[deps.CpuId]]\ndeps = [\"Markdown\"]\ngit-tree-sha1 = \"32d125af0fb8ec3f8935896122c5e345709909e5\"\nuuid = \"adafc99b-e345-5852-983c-f28acb93d879\"\nversion = \"0.3.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.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.DefineSingletons]]\ngit-tree-sha1 = \"0fba8b706d0178b4dc7fd44a96a92382c9065c2c\"\nuuid = \"244e2a9f-e319-4986-a169-4d1fe445cd52\"\nversion = \"0.1.2\"\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.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.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.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[[deps.DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[deps.Documenter]]\ndeps = [\"ANSIColoredPrinters\", \"Base64\", \"Dates\", \"DocStringExtensions\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"LibGit2\", \"Logging\", \"Markdown\", \"REPL\", \"Test\", \"Unicode\"]\ngit-tree-sha1 = \"7d9a46421aef53cbd6b8ecc40c3dcbacbceaf40e\"\nuuid = \"e30172f5-a6a5-5a46-863b-614d45cd2de4\"\nversion = \"0.27.15\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"FileWatching\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\nversion = \"1.6.0\"\n\n[[deps.DrWatson]]\ndeps = [\"Dates\", \"FileIO\", \"JLD2\", \"LibGit2\", \"MacroTools\", \"Pkg\", \"Random\", \"Requires\", \"Scratch\", \"UnPack\"]\ngit-tree-sha1 = \"67e9001646db6e45006643bf37716ecd831d37d2\"\nuuid = \"634d3b9d-ee7a-5ddf-bec9-22491ea816e1\"\nversion = \"2.9.1\"\n\n[[deps.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[[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 = \"d064b0340db45d48893e7604ec95e7a2dc9da904\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.5.0\"\n\n[[deps.EllipticalSliceSampling]]\ndeps = [\"AbstractMCMC\", \"ArrayInterface\", \"Distributions\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"bed775e32c6f38a19c1dbe0298480798e6be455f\"\nuuid = \"cad2338a-1db2-11e9-3401-43bc07c9ede2\"\nversion = \"0.5.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.FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"80ced645013a5dbdc52cf70329399c35ce007fae\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.13.0\"\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.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.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.Functors]]\ngit-tree-sha1 = \"223fffa49ca0ff9ce4f875be001ffe173b2b7de4\"\nuuid = \"d9f16b24-f501-4c13-a1f2-28368ffc5196\"\nversion = \"0.2.8\"\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 = \"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.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 = \"303d70c961317c4c20fafaf5dbe0e6d610c38542\"\nuuid = \"e33a78d0-f292-5ffc-b300-72abe9b543c8\"\nversion = \"2.7.1+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.IRTools]]\ndeps = [\"InteractiveUtils\", \"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7f43342f8d5fd30ead0ba1b49ab1a3af3b787d24\"\nuuid = \"7869d1d1-7146-5819-86e3-90919afe41df\"\nversion = \"0.4.5\"\n\n[[deps.IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\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.InlineStrings]]\ndeps = [\"Parsers\"]\ngit-tree-sha1 = \"61feba885fac3a407465726d0c330b3055df897f\"\nuuid = \"842dd82b-1e85-43dc-bf29-5d0ee9dffc48\"\nversion = \"1.1.2\"\n\n[[deps.InplaceOps]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"50b41d59e7164ab6fda65e71049fee9d890731ff\"\nuuid = \"505f98c9-085e-5b2c-8e89-488be7bf1f34\"\nversion = \"0.3.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.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.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.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.JLD2]]\ndeps = [\"FileIO\", \"MacroTools\", \"Mmap\", \"OrderedCollections\", \"Pkg\", \"Printf\", \"Reexport\", \"TranscodingStreams\", \"UUIDs\"]\ngit-tree-sha1 = \"81b9477b49402b47fbe7f7ae0b252077f53e4a08\"\nuuid = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nversion = \"0.4.22\"\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.LRUCache]]\ngit-tree-sha1 = \"d64a0aff6691612ab9fb0117b0995270871c5dfc\"\nuuid = \"8ac3fa9e-de4c-5943-b1dc-09c6b5f20637\"\nversion = \"1.3.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 = \"6f14549f7760d84b2db7a9b10b88cd3cc3025730\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.14\"\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.LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[deps.LazyStack]]\ndeps = [\"LinearAlgebra\", \"NamedDims\", \"OffsetArrays\", \"Test\", \"ZygoteRules\"]\ngit-tree-sha1 = \"a8bf67afad3f1ee59d367267adb7c44ccac7fdee\"\nuuid = \"1fad7336-0346-5a1a-a56f-a06ba010965b\"\nversion = \"0.0.7\"\n\n[[deps.LeftChildRightSiblingTrees]]\ndeps = [\"AbstractTrees\"]\ngit-tree-sha1 = \"b864cb409e8e445688bc478ef87c0afe4f6d1f8d\"\nuuid = \"1d6d02ad-be62-4b6b-8a6d-2f90e265016e\"\nversion = \"0.1.3\"\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.Libtask]]\ndeps = [\"IRTools\", \"LRUCache\", \"LinearAlgebra\", \"MacroTools\", \"Statistics\"]\ngit-tree-sha1 = \"ed1b54f6df6fb7af8b315cfdc288ab5572dbd3ba\"\nuuid = \"6f1fad26-d15e-5dc8-ae53-837a1d7b8c9f\"\nversion = \"0.7.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\", \"OpenBLAS_jll\", \"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.LoggingExtras]]\ndeps = [\"Dates\", \"Logging\"]\ngit-tree-sha1 = \"dfeda1c1130990428720de0024d4516b1902ce98\"\nuuid = \"e6f89c97-d47a-5376-807f-9c37f3926c36\"\nversion = \"0.4.7\"\n\n[[deps.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[[deps.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[[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.MLJModelInterface]]\ndeps = [\"Random\", \"ScientificTypesBase\", \"StatisticalTraits\"]\ngit-tree-sha1 = \"74d7fb54c306af241c5f9d4816b735cb4051e125\"\nuuid = \"e80e1ace-859a-464e-9ed9-23947d8ae3ea\"\nversion = \"1.4.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.ManualMemory]]\ngit-tree-sha1 = \"bcaef4fc7a0cfe2cba636d84cda54b5e4e4ca3cd\"\nuuid = \"d125e4d3-2237-4719-b19c-fa641b8a4667\"\nversion = \"0.1.8\"\n\n[[deps.MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\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.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.MonteCarloMeasurements]]\ndeps = [\"Distributed\", \"Distributions\", \"LinearAlgebra\", \"MacroTools\", \"Random\", \"RecipesBase\", \"Requires\", \"SLEEFPirates\", \"StaticArrays\", \"Statistics\", \"StatsBase\", \"Test\"]\ngit-tree-sha1 = \"03619e255664666b352a5e5f6b45e8b00d439870\"\nuuid = \"0987c9cc-fe09-11e8-30f0-b96dd679fdca\"\nversion = \"1.0.8\"\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.NLSolversBase]]\ndeps = [\"DiffResults\", \"Distributed\", \"FiniteDiff\", \"ForwardDiff\"]\ngit-tree-sha1 = \"50310f934e55e5ca3912fb941dec199b49ca9b68\"\nuuid = \"d41bc354-129a-5804-8e4c-c37616107c6c\"\nversion = \"7.8.2\"\n\n[[deps.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[[deps.NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[deps.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[[deps.NamedDims]]\ndeps = [\"AbstractFFTs\", \"ChainRulesCore\", \"CovarianceEstimation\", \"LinearAlgebra\", \"Pkg\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"0856b62716585eb90cc1dada226ac9eab5f69aa5\"\nuuid = \"356022a1-0364-5f58-8944-0da4b18d706f\"\nversion = \"0.2.47\"\n\n[[deps.NamedTupleTools]]\ngit-tree-sha1 = \"63831dcea5e11db1c0925efe5ef5fc01d528c522\"\nuuid = \"d9ec5142-1e00-5aa0-9d6a-321866360f50\"\nversion = \"0.13.7\"\n\n[[deps.NaturalSort]]\ngit-tree-sha1 = \"eda490d06b9f7c00752ee81cfa451efe55521e21\"\nuuid = \"c020b1a1-e9b0-503a-9c33-f039bfc54a85\"\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.20+0\"\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.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.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.Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[deps.ParetoSmooth]]\ndeps = [\"AxisKeys\", \"InteractiveUtils\", \"LinearAlgebra\", \"LogExpFunctions\", \"MCMCDiagnosticTools\", \"NamedDims\", \"PrettyTables\", \"Printf\", \"Random\", \"Requires\", \"Statistics\", \"StatsBase\", \"Tullio\"]\ngit-tree-sha1 = \"832b20efeb8bc495cada4b412383cb4454c2897c\"\nuuid = \"a68b5a21-f429-434e-8bfa-46b447300aac\"\nversion = \"0.7.1\"\n\n[[deps.ParetoSmoothedImportanceSampling]]\ndeps = [\"CSV\", \"DataFrames\", \"Distributions\", \"JSON\", \"Printf\", \"Random\", \"StanSample\", \"Statistics\", \"StatsFuns\", \"StatsPlots\", \"Test\"]\ngit-tree-sha1 = \"031e5d690f4208b8605a6584af23b306d6cc1b1a\"\nuuid = \"98f080ec-61e2-11eb-1c7b-31ea1097256f\"\nversion = \"1.3.1\"\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\", \"FileWatching\", \"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\", \"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 = \"88ee01b02fba3c771ac4dce0dfc4ecf0cb6fb772\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.27.5\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"670e559e5c8e191ded66fa9ea89c97f10376bb4c\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.38\"\n\n[[deps.PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"28ef6c7ce353f0b35d0df0d5930e0d072c1f5b9b\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.1\"\n\n[[deps.PositiveFactorizations]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"17275485f373e6673f7e7f97051f703ed5b15b20\"\nuuid = \"85a6dd25-e78a-55b7-8502-1745935b8125\"\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.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.ProgressLogging]]\ndeps = [\"Logging\", \"SHA\", \"UUIDs\"]\ngit-tree-sha1 = \"80d919dee55b9c50e8d9e2da5eeafff3fe58b539\"\nuuid = \"33c8b6b6-d38a-422a-b730-caa89a2f386c\"\nversion = \"0.1.4\"\n\n[[deps.ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"d7a7aef8f8f2d537104f170139553b14dfe39fe9\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.2\"\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.RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[deps.Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"dc84268fe0e3335a62e315a3a7cf2afa7178a734\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.3\"\n\n[[deps.RealDot]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9\"\nuuid = \"c1ae055f-0cd5-4b69-90a6-9a35b1a98df9\"\nversion = \"0.1.0\"\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.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[[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.Roots]]\ndeps = [\"CommonSolve\", \"Printf\", \"Setfield\"]\ngit-tree-sha1 = \"838b60ee62bebc794864c880a47e331e00c47505\"\nuuid = \"f2b01f46-fcfa-551c-844a-d8ac1e96c665\"\nversion = \"1.4.1\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\nversion = \"0.7.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 = \"ac399b5b163b9140f9c310dfe9e9aaa225617ff6\"\nuuid = \"476501e8-09a2-5ece-8869-fb82de89a1fa\"\nversion = \"0.6.32\"\n\n[[deps.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[[deps.ScientificTypesBase]]\ngit-tree-sha1 = \"a8e18eb383b5ecf1b5e6fc237eb39255044fd92b\"\nuuid = \"30f210dd-8aff-4c5f-94ba-8e64358c1161\"\nversion = \"3.0.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.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.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.SplittablesBase]]\ndeps = [\"Setfield\", \"Test\"]\ngit-tree-sha1 = \"39c9f91521de844bad65049efd4f9223e7ed43f9\"\nuuid = \"171d559e-b47b-412a-8079-5efa626c420e\"\nversion = \"0.1.14\"\n\n[[deps.StanBase]]\ndeps = [\"CSV\", \"DataFrames\", \"DelimitedFiles\", \"Distributed\", \"DocStringExtensions\", \"Documenter\", \"JSON\", \"Parameters\", \"Random\", \"StanDump\", \"Unicode\"]\ngit-tree-sha1 = \"fe0c4b9057c1e23e1f8e27666e63f71eedf7b023\"\nuuid = \"d0ee94f6-a23d-54aa-bbe9-7f572d6da7f5\"\nversion = \"4.4.0\"\n\n[[deps.StanDump]]\ndeps = [\"ArgCheck\", \"DocStringExtensions\"]\ngit-tree-sha1 = \"bfaebe19ada44a52a6c797d48473f1bb22fd0853\"\nuuid = \"9713c8f3-0168-54b5-986e-22c526958f39\"\nversion = \"0.2.0\"\n\n[[deps.StanSample]]\ndeps = [\"CSV\", \"CompatHelperLocal\", \"DataFrames\", \"DelimitedFiles\", \"Distributed\", \"DocStringExtensions\", \"JSON\", \"MonteCarloMeasurements\", \"NamedTupleTools\", \"OrderedCollections\", \"Parameters\", \"Random\", \"Reexport\", \"Requires\", \"StanBase\", \"StanDump\", \"TableOperations\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"7301a753d5e78694b0a9bd4fe7df6c366ef500ec\"\nuuid = \"c1514b29-d3a0-5178-b312-660c88baa699\"\nversion = \"6.4.0\"\n\n[[deps.Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"87e9954dfa33fd145694e42337bdd3d5b07021a6\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.6.0\"\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.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 = \"b0bb5b9b958ae5174915271fed6a8f52cca5e549\"\nuuid = \"2d09df54-9d0f-5258-8220-54c2a3d4fbee\"\nversion = \"4.5.0\"\n\n[[deps.StatisticalRethinkingPlots]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"KernelDensity\", \"LaTeXStrings\", \"Parameters\", \"Plots\", \"Reexport\", \"Requires\", \"StatisticalRethinking\", \"StatsPlots\"]\ngit-tree-sha1 = \"4df7bd9b96a675715534ca051c1c3074db0de88c\"\nuuid = \"e1a513d0-d9d9-49ff-a6dd-9d2e9db473da\"\nversion = \"1.0.1\"\n\n[[deps.StatisticalTraits]]\ndeps = [\"ScientificTypesBase\"]\ngit-tree-sha1 = \"271a7fea12d319f23d55b785c51f6876aadb9ac0\"\nuuid = \"64bff920-2084-43da-a3e6-9bb72801c0c9\"\nversion = \"3.0.0\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"8d7530a38dbd2c397be7ddd01a424e4f411dcc41\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.2\"\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.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.StructuralCausalModels]]\ndeps = [\"CSV\", \"Combinatorics\", \"DataFrames\", \"DataStructures\", \"Distributions\", \"DocStringExtensions\", \"LinearAlgebra\", \"NamedArrays\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"5ec7266296539dab3af599106886f74b57f9b1cf\"\nuuid = \"a41e6734-49ce-4065-8b83-aff084c01dfd\"\nversion = \"1.3.1\"\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.TerminalLoggers]]\ndeps = [\"LeftChildRightSiblingTrees\", \"Logging\", \"Markdown\", \"Printf\", \"ProgressLogging\", \"UUIDs\"]\ngit-tree-sha1 = \"62846a48a6cd70e63aa29944b8c4ef704360d72f\"\nuuid = \"5d786b92-1e48-4d6f-9151-6b4477ca9bed\"\nversion = \"0.1.5\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.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[[deps.TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\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.Tullio]]\ndeps = [\"ChainRulesCore\", \"DiffRules\", \"LinearAlgebra\", \"Requires\"]\ngit-tree-sha1 = \"859e2e9a7222553a0c052e423557cedb49376da9\"\nuuid = \"bc48ee85-29a4-5162-ae0b-a64e1601d4bc\"\nversion = \"0.3.4\"\n\n[[deps.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[[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.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 = \"9d1b533f597d87ce9b4abd36a2ce4664f08e08ed\"\nuuid = \"3d5dd08c-fd9d-11e8-17fa-ed2836048c2f\"\nversion = \"0.21.29\"\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.WeakRefStrings]]\ndeps = [\"DataAPI\", \"InlineStrings\", \"Parsers\"]\ngit-tree-sha1 = \"b1be2855ed9ed8eac54e5caff2afcdb442d52c23\"\nuuid = \"ea10d353-3f73-51f8-a26c-33c1cb351aa5\"\nversion = \"1.4.2\"\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+3\"\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\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\nversion = \"5.1.0+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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250058b9da10-8cbd-42e4-bddf-ec4995ac756c\n# \u255f\u2500d3c6c774-a158-485c-acd1-e366c24df4bc\n# \u2560\u25500f75e85c-4506-483f-b0f8-a31ee698bf04\n# \u255f\u2500cb180e21-3778-40f1-93d8-af442d1be559\n# \u2560\u25502d3d462e-d6bf-4ebd-ab34-db38f4261a11\n# \u2560\u255018b5c138-9324-4c5a-86ca-be1e825ed11e\n# \u255f\u2500a2d950f8-d780-4abe-af37-b189bd4a5e88\n# \u2560\u2550bbb4a889-77e2-449b-9258-883e7434e641\n# \u2560\u2550496b257c-ea62-40b2-b1c9-e92fdda1d688\n# \u255f\u250096760a8e-8561-4576-a7c7-70596fa20d33\n# \u255f\u2500b83bc4d0-8c65-40a8-9187-70ef2a0ff38d\n# \u255f\u2500b583eb23-4045-420c-80d5-4f339ebb6ad4\n# \u2560\u2550d5d66e16-487e-4214-b702-728dc3db32cc\n# \u255f\u2500b14217e8-1f70-44cc-8d3c-528ab55e27ef\n# \u2560\u2550b3adef33-c111-4d20-b277-a5346eae9f23\n# \u2560\u25506869d583-1590-4210-b696-b63fd7857e09\n# \u2560\u25501f4e22a4-5fba-4331-9bf9-dd886ce45e74\n# \u2560\u2550cbe1028d-829d-4ed4-840d-d74f151f55bb\n# \u255f\u250075ee3adf-2988-4f42-a0b5-21abe5829120\n# \u2560\u255063db6c9f-ba40-41a2-975d-798d9f2cbeab\n# \u255f\u2500534edcc4-2dac-4ddb-a6a9-55ee38a3e7ae\n# \u2560\u25507c8e8a61-b1c1-4f9a-addc-61a987c2c5d2\n# \u2560\u2550a9d5118d-8fc7-4353-bb20-6b87ae0e9247\n# \u2560\u2550f41d6486-7589-4b67-9eaf-92956622226a\n# \u255f\u25009f92d0a7-45ce-4148-b6a5-7ede9dc09234\n# \u2560\u25501cc80dac-1120-4520-b73f-0e31dc1d8721\n# \u255f\u2500159e07b6-dcd7-4ca7-9d3e-f5059b1b8803\n# \u2560\u255085121bc0-447a-4b79-ac6c-ce91871ca7d8\n# \u2560\u255084b6ab83-7e65-477f-b87f-298d8b5eacea\n# \u255f\u25002d373995-f303-48b7-8cc3-1daf35d5ed36\n# \u2560\u255091a627e0-a46c-40f8-a5c2-2f3b25187074\n# \u2560\u2550a492bfeb-452c-4138-b5a2-6d2c4cdd114b\n# \u255f\u2500ccf333ff-af94-439a-b41c-5be04c076007\n# \u255f\u250065eaad30-7f58-4eb1-b458-07688dfeac81\n# \u2560\u25503283d295-c60e-44bd-9547-8285cdbce9a9\n# \u2560\u2550de4e3b12-174b-4740-acab-db6d2a55eb0a\n# \u2560\u255028bf03e4-2899-4f34-a8aa-892937ede3f9\n# \u2560\u255030707462-75f5-4da9-9677-d7208f20a4fb\n# \u2560\u255018b3a4a5-2506-4ced-8917-3da988c94eba\n# \u2560\u255091b50108-414d-4520-8e57-5eaa58061b1a\n# \u2560\u2550f11d0597-8962-4cd7-8637-aef99abce80a\n# \u2560\u2550a0834a65-1f5e-497a-89ab-36adf38d1118\n# \u2560\u2550ba0b9017-12c9-446d-a8dd-647d8735d2b0\n# \u2560\u2550e0febcf9-6e87-4ecc-8ef9-e27ab79af2fc\n# \u2560\u2550c82d6f3b-6a27-4cff-9043-c301aa09d53e\n# \u2560\u255074977e3a-b168-4bcd-a260-7191c60130ac\n# \u2560\u25507d6161c6-4805-4ee9-8d9a-d8f95faf47d7\n# \u255f\u2500d8eb2079-2915-46e5-ac55-6849143aa194\n# \u2560\u25505e18ac09-76e1-44a1-93a9-408d6971a5f6\n# \u2560\u2550cc0b2fad-d508-4135-8203-72e3d130fea1\n# \u2560\u25503d2862bc-c217-4e8d-bf88-24e7e3b3eaa7\n# \u255f\u2500222a9455-f017-47ff-bd52-42179f4a0320\n# \u255f\u2500faeea7c5-d921-4dbe-9f72-d3e0ae17748f\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "88d804700ec6feabd30c6cc13d518d3ef0808715", "size": 80259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/TuringGuide.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/SR2TuringPluto.jl", "max_stars_repo_head_hexsha": "bac316572c5a1a59f7b444ab5cf5601c71437fce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-12-27T21:58:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T11:10:10.000Z", "max_issues_repo_path": "notebooks/TuringGuide.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/SR2TuringPluto.jl", "max_issues_repo_head_hexsha": "bac316572c5a1a59f7b444ab5cf5601c71437fce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-10T07:30:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T00:31:54.000Z", "max_forks_repo_path": "notebooks/TuringGuide.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/SR2TuringPluto.jl", "max_forks_repo_head_hexsha": "bac316572c5a1a59f7b444ab5cf5601c71437fce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-12T01:34:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T21:15:31.000Z", "avg_line_length": 34.8195227766, "max_line_length": 467, "alphanum_fraction": 0.73286485, "num_tokens": 36141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7700143928334249}}
{"text": "#Constant mean function\n\n\"\"\"\n    MeanConst <: Mean\n\nConstant mean function\n```math\nm(x) = \u03b2\n```\nwith constant ``\u03b2``.\n\"\"\"\nmutable struct MeanConst <: Mean\n    \"Constant\"\n    \u03b2::Float64\n    \"Priors for mean parameters\"\n    priors::Array\n\n    \"\"\"\n        MeanConst(\u03b2::Float64)\n\n    Create `MeanConst` with constant `\u03b2`.\n    \"\"\"\n    MeanConst(\u03b2::Float64) = new(\u03b2, [])\nend\n\nmean(mConst::MeanConst, x::AbstractVector) = mConst.\u03b2\nmean(mConst::MeanConst, X::AbstractMatrix) = fill(mConst.\u03b2, size(X,2))\n\nget_params(mConst::MeanConst) = Float64[mConst.\u03b2]\nget_param_names(::MeanConst) = [:\u03b2]\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.\u03b2 = 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,\"\ud83c\udf49\")\n[\"H(\ud83c\udf491)\" \"H(\ud83c\udf491|\ud83c\udf492)\" \"H(\ud83c\udf492)\" \"H(\ud83c\udf492|\ud83c\udf491)\"]\n\njulia> ConditionalEntropyList(2)\n[\"H(X1)\" \"H(X1|X2)\" \"H(X2)\" \"H(X2|X1)\"]\n\njulia> ConditionalEntropyList(3,\"dice\ud83d\udca0\")\n[\"H(dice\ud83d\udca01)\"\n\"H(dice\ud83d\udca01|dice\ud83d\udca02)\"\n\"H(dice\ud83d\udca01|dice\ud83d\udca02,dice\ud83d\udca03)\"\n\"H(dice\ud83d\udca01|dice\ud83d\udca03)\"\n\"H(dice\ud83d\udca02)\"\n\"H(dice\ud83d\udca02|dice\ud83d\udca01)\"\n\"H(dice\ud83d\udca02|dice\ud83d\udca01,dice\ud83d\udca03)\"\n\"H(dice\ud83d\udca02|dice\ud83d\udca03)\"\n\"H(dice\ud83d\udca03)\"\n\"H(dice\ud83d\udca03|dice\ud83d\udca01)\"\n\"H(dice\ud83d\udca03|dice\ud83d\udca01,dice\ud83d\udca02)\"\n\"H(dice\ud83d\udca03|dice\ud83d\udca02)\"]\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    \u03b2 = m/n\n    \u03c9 = (8*\u03b2) / (\u03b2+1+sqrt(\u03b2^2+14\u03b2+1))\n    c = sqrt(2*(\u03b2+1)+\u03c9)\n\n    if known_noise\n        return c\n    else\n        median = median_marcenko_pastur(\u03b2)\n        return c / sqrt(median)\n    end\nend\n\nfunction marcenko_pastur_density(t, lower, upper, beta)\n    sqrt((upper-t).*(t-lower))./(2\u03c0*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 \u2248 zero(eltype(gamma))\n        i, \u03f5 = quadgk(x->(x^gamma)*marcenko_pastur(x), x, upper)\n        return i\n    else\n        i, \u03f5 = 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    \u03c4 = optimal_svht(m,n)\n    inds = S .>= \u03c4*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    \u03c4 = optimal_svht(m,n)\n    inds = S .>= \u03c4*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": "# function cutrod_naive(p::Array{Int, 1}, n::Int)::Int\n# \tif n == 0\n# \t\treturn 0\n# \tend\n\n# \tq = typemin(Int)    # q = -\u221e\n# \tfor i \u2208 1:n\n# \t\tq = max(q, p[i] + cutrod(p, n - i))\n# \tend\n\n# \treturn q\n# end\n\n\n# function cutrod_memoized(p::Array{Int, 1}, n::Int)::Int\n# \tr = fill(typemin(Int), length(p))\n\n# \tfunction cutrod_memoized_aux(p::Array{Int, 1}, n::Int, r::Array{Int, 1})::Int\n# \t\tif n == 0\n# \t\t\treturn 0\n# \t\tend\n\n# \t\tif r[n] \u2265 0\n# \t\t\treturn r[n]\n# \t\tend\n\n# \t\tq = typemin(Int)    # q = -\u221e\n# \t\tfor i \u2208 1:n\n# \t\t\tq = max(q, p[i] + cutrod_memoized_aux(p, n - i, r))\n# \t\tend\n\n# \t\treturn q\n# \tend\n\n# \treturn cutrod_memoized_aux(p, n, r)\n# end\n\n\n# prices = [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]\n# for j \u2208 1:10\n# \tprintln(\"Best reveneu for length $j is $(cutrod_memoized(prices, j)) \\$.\")\n# end", "meta": {"hexsha": "c6e965343b1ecc5643cb6e0ea0eb3ef4e1d58f58", "size": 789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algorithms/CutRod.jl", "max_stars_repo_name": "SudipSinha/edu", "max_stars_repo_head_hexsha": "43331bcc7dd76f5bd5c200c7f5292a1d50b22101", "max_stars_repo_licenses": ["MIT"], "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/CutRod.jl", "max_issues_repo_name": "SudipSinha/edu", "max_issues_repo_head_hexsha": "43331bcc7dd76f5bd5c200c7f5292a1d50b22101", "max_issues_repo_licenses": ["MIT"], "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/CutRod.jl", "max_forks_repo_name": "SudipSinha/edu", "max_forks_repo_head_hexsha": "43331bcc7dd76f5bd5c200c7f5292a1d50b22101", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-15T21:30:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T21:30:43.000Z", "avg_line_length": 18.7857142857, "max_line_length": 80, "alphanum_fraction": 0.5323193916, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.7699821754913976}}
{"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    \u03bb = oftype(float(x), selu_\u03bb)\n    \u03b1 = oftype(float(x), selu_\u03b1)\n    return ((x > 0) ? x : (exp(x)-1)\u03b1)*\u03bb\nend\n\nfunction selu(x, back::Bool)\n    \u03bb = oftype(float(x), selu_\u03bb)\n    \u03b1 = oftype(float(x), selu_\u03b1)\n    if x < 0\n        return \u03bb*alpha*exp(x)\n    else\n        return \u03bb\n    end\nend\n\nconst selu_\u03bb = 1.0507009873554804934193349852946\nconst selu_\u03b1 = 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": "using Test\n\nfunction binary_search(arr,item)\n    low = 0\n    high = length(arr)\n\n    while low <= high\n        mid = (low + high) \u00f7 2\n        guess = 0\n        try\n            guess = arr[mid]\n        catch\n            return nothing\n        end\n        if guess == item\n            return mid\n        elseif guess > item\n            high = mid - 1\n        else\n            low = mid + 1\n        end\n    end\nend\n\narr = [1,3,5,7,9]\n@test binary_search(arr,3) == 2\n@test binary_search(arr,-1) == nothing\n", "meta": {"hexsha": "89e85be8a77df21a3015bc65b4d3d5343a9e3039", "size": 502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "01_introduction_to_algorithms/julia/01_binary_search.jl", "max_stars_repo_name": "filchyboy/grokking_algorithms_work", "max_stars_repo_head_hexsha": "16dace97610e2cb0938704e2b8cfd6e92d6b024d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-03-11T00:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T00:19:23.000Z", "max_issues_repo_path": "book04grokkingAlgo/01_introduction_to_algorithms/julia/01_binary_search.jl", "max_issues_repo_name": "mcuallen/CodeLrn2019", "max_issues_repo_head_hexsha": "adc727d92904c5c5d445a2621813dfa99474206d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 160, "max_issues_repo_issues_event_min_datetime": "2021-04-26T19:04:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T20:18:37.000Z", "max_forks_repo_path": "book04grokkingAlgo/01_introduction_to_algorithms/julia/01_binary_search.jl", "max_forks_repo_name": "mcuallen/CodeLrn2019", "max_forks_repo_head_hexsha": "adc727d92904c5c5d445a2621813dfa99474206d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-04-26T19:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:36:29.000Z", "avg_line_length": 17.9285714286, "max_line_length": 38, "alphanum_fraction": 0.4760956175, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.7699452927584473}}
{"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(\u03bd::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(\u03bd::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(\u03bd, 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(\u03bd - 1, x) - bessel_j(\u03bd + 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(\u03bd - 2, x) + bessel_j(\u03bd + 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(\u03bd - 3, x) - bessel_j(\u03bd + 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                        \u03bd2 = \u03bd^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 - \u03bd2 + 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(\u03bd::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(\u03bd::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(\u03bd, 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(\u03bd - 1, x) - bessel_y(\u03bd + 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(\u03bd - 2, x) + bessel_y(\u03bd + 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(\u03bd - 3, x) - bessel_y(\u03bd + 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                        \u03bd2 = \u03bd^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 - \u03bd2 + 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(\u03bd::arb_series, \u03bc::arb, z::arb[, n = length(\u03bd)])\n\n> Compute the Taylor series of the Legendre function with respect to\n  the parameter \u03bd.\n\"\"\"\nfunction legendre_p(\u03bd::arb_series, \u03bc::arb, z::arb, n = length(\u03bd))\n    CC = ComplexField(z.parent.prec)\n    PP = AcbPolyRing(CC, :x)\n    \u03bd\u03bd = PP(\u03bd.poly)\n    \u03bc\u03bc = PP(\u03bc)\n    zz = PP(z)\n\n    a = -\u03bd\u03bd\n    b = \u03bd\u03bd + 1\n    c = 1 - \u03bc\u03bc\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(\u03bd.poly.parent([real(coeff(res, i)) for i = 0:degree(res)]), n)\n    ((1 + z) / (1 - z))^(\u03bc / 2) * realres\nend\n\n\"\"\"\n    legendre_p(\u03bd::arb, \u03bc::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(\u03bd::arb, \u03bc::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(\u03bd, \u03bc, 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 = ((\u03bd + 1) * x * a0 - (\u03bd - \u03bc + 1) * legendre_p_safe(\u03bd + 1, \u03bc, 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                \u03bd2 = \u03bd^2\n                \u03bc2 = \u03bc^2\n\n                a2 = (2x * a1 - (\u03bd2 + \u03bd - \u03bc2 / (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\u03bc2 - (\u03bd2 + \u03bd) * (onemx2)) * x * a0 +\n                            ((\u03bd2 + \u03bd + 2) * x2 + \u03bc2 - \u03bd2 - \u03bd + 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                        \u03bd2p\u03bd = \u03bd2 + \u03bd\n                        \u03bc2m\u03bd2p\u03bd = \u03bc2 - \u03bd2p\u03bd\n                        fourx = 4x\n                        for i = 4:n-1\n                            k = i - 4\n                            ai =\n                                (\n                                    (k + 1 + \u03bd) * (\u03bd - k) * res[k] -\n                                    (0.5 * (2k^2 + (5k + 3) - \u03bd2p\u03bd)) * fourx * res[k+1] +\n                                    (\n                                        ((-6k^2 - 24k - 24) + \u03bd2p\u03bd) * x2 +\n                                        (2k^2 + 8k + 8) +\n                                        \u03bc2m\u03bd2p\u03bd\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(\u03bd::arb, \u03bc::arb, z::arb_series, n = length(z))\n    legendre_p(\u03bd, \u03bc, 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! \ud83d\ude20\")\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! \ud83d\ude20\")\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": "#\n# Functions that compute the center of mass:\n#\n\n# Without masses (just assume all are identical)\n\nfunction center_of_mass( x :: Matrix{Float64} )\n  xcm = zeros(3)\n  n = length(x[:,1])\n  for i in 1:n\n    xcm[1] = xcm[1] + x[i,1]\n    xcm[2] = xcm[2] + x[i,2]\n    xcm[3] = xcm[3] + x[i,3]\n  end\n  xcm[1] = xcm[1] / n\n  xcm[2] = xcm[2] / n\n  xcm[3] = xcm[3] / n\n  return xcm\nend\n\n# Given the masses\n\nfunction center_of_mass( x :: Matrix{Float64}, masses :: Vector{Float64} )\n  xcm = zeros(3)\n  n = length(x[:,1])\n  mtot = 0.\n  for i in 1:n\n    mtot = mtot + masses[i]\n    xcm[1] = xcm[1] + x[i,1]\n    xcm[2] = xcm[2] + x[i,2]\n    xcm[3] = xcm[3] + x[i,3]\n  end\n  xcm[1] = xcm[1] / mtot\n  xcm[2] = xcm[2] / mtot\n  xcm[3] = xcm[3] / mtot\n  return xcm\nend\n\n", "meta": {"hexsha": "6b3e9b53e71aa70e670595cd3348d77e819b1849", "size": 752, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/center_of_mass.jl", "max_stars_repo_name": "mcubeg/JPleXL", "max_stars_repo_head_hexsha": "38fb23f7e66eef505ba1d85c78145c84f9995e4e", "max_stars_repo_licenses": ["MIT"], "max_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_of_mass.jl", "max_issues_repo_name": "mcubeg/JPleXL", "max_issues_repo_head_hexsha": "38fb23f7e66eef505ba1d85c78145c84f9995e4e", "max_issues_repo_licenses": ["MIT"], "max_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_of_mass.jl", "max_forks_repo_name": "mcubeg/JPleXL", "max_forks_repo_head_hexsha": "38fb23f7e66eef505ba1d85c78145c84f9995e4e", "max_forks_repo_licenses": ["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.2820512821, "max_line_length": 74, "alphanum_fraction": 0.5438829787, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7699001900671647}}
{"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": "using Test\nusing MultivariateBases\n\n@testset \"Orthogonal\" begin\n    orthogonal_test(LaguerreBasis, x -> [\n        1,\n        1 - x,\n        (x^2 - 4x + 2) / 2,\n        (-x^3 + 9x^2 - 18x + 6) / 6,\n        (x^4 - 16x^3 + 72x^2 - 96x + 24) / 24\n    ], false)\nend\n\n@testset \"API degree = $degree\" for degree in 0:3\n    api_test(LaguerreBasis, degree)\nend\n", "meta": {"hexsha": "2c8bf5e2da4a83cc56a5e8ca03a3fa617ef15e80", "size": 352, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/laguerre.jl", "max_stars_repo_name": "JuliaAlgebra/PolynomialBases", "max_stars_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-24T07:15:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:13:46.000Z", "max_issues_repo_path": "test/laguerre.jl", "max_issues_repo_name": "JuliaAlgebra/PolynomialBases", "max_issues_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-01-30T12:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T22:17:19.000Z", "max_forks_repo_path": "test/laguerre.jl", "max_forks_repo_name": "JuliaAlgebra/PolynomialBases", "max_forks_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-01-15T15:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T15:10:30.000Z", "avg_line_length": 20.7058823529, "max_line_length": 49, "alphanum_fraction": 0.5426136364, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7698909114505599}}
{"text": "using Test\nusing MieSeries\n\n@testset \"Test 1\" begin\n    x = 0.3\n    l_max = 3\n    m = 0\n    p, dp = MieSeries.associated_legendre(x; l_max, m)\n    @test p[1] \u2248 0.3\n    @test p[2] \u2248 -0.365\n    @test p[3] \u2248 -0.3825\n    @test dp[1] \u2248 1\n    @test dp[2] \u2248 0.9\n    @test dp[3] \u2248 -0.825\nend\n\n@testset \"Test 2\" begin\n    x = -0.3\n    l_max = 3\n    m = 0\n    p, dp = MieSeries.associated_legendre(x; l_max, m)\n    @test p[1] \u2248 -0.3\n    @test p[2] \u2248 -0.365\n    @test p[3] \u2248 0.3825\n    @test dp[1] \u2248 1\n    @test dp[2] \u2248 -0.9\n    @test dp[3] \u2248 -0.825\nend\n\n@testset \"Test 3\" begin\n    x = 0.3\n    l_max = 3\n    m = 1\n    p, dp = MieSeries.associated_legendre(x; l_max, m)\n    @test p[1] \u2248 -0.953939201416945649152621586023226540254623425250545753908\n    @test p[2] \u2248 -0.858545281275251084237359427420903886229161082725491178517\n    @test p[3] \u2248 0.7869998411689801605509128084691618957100643258317002469742\n    @test dp[1] \u2248 0.3144854510165755\n    @test dp[2] \u2248 -2.578780698335919\n    @test dp[3] \u2248 -4.55217690346493\nend\n\n@testset \"Test 4\" begin\n    x = -0.3\n    l_max = 3\n    m = 1\n    p, dp = MieSeries.associated_legendre(x; l_max, m)\n    @test p[1] \u2248 -0.953939201416945649152621586023226540254623425250545753908\n    @test p[2] \u2248 0.858545281275251084237359427420903886229161082725491178517\n    @test p[3] \u2248 0.7869998411689801605509128084691618957100643258317002469742\n    @test dp[1] \u2248 -0.3144854510165755\n    @test dp[2] \u2248 -2.578780698335919\n    @test dp[3] \u2248 4.55217690346493\nend\n\n@testset \"Test 5\" begin\n    x = 0.8\n    l_max = 50\n    m = 1\n    p, dp = MieSeries.associated_legendre(x; l_max, m)\n    @test p[48] \u2248 5.96348895739654\n    @test p[49] \u2248 2.40302362973485973633385371736914932219523828838\n    @test p[50] \u2248 -2.201121967241330605081500626464831230994512944496\n    @test dp[48] \u2248 328.9545358407495 \n    @test dp[49] \u2248 566.5997821783876 \n    @test dp[50] \u2248 584.9974550170323 \nend", "meta": {"hexsha": "950e7d5c6d80159de740fa7e83c7f4759e6a18cf", "size": 1878, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/legendre.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": "test/legendre.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": "test/legendre.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": 28.0298507463, "max_line_length": 77, "alphanum_fraction": 0.6453674121, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7698909114505599}}
{"text": "using Test\nusing LinearAlgebra\nusing FlightMechanics\n\n\n@testset \"quaternion <-> euler\" begin\n    quat = (0.8660254037844387, 0.0, 0.5, 0.0)\n    euler_exp = [0.0, 1.04719755, 0.0]\n\n    euler = quaternion2euler(quat...)\n    @test isapprox(euler, euler_exp)\n\n    quat_exp = [quat...]\n    quat = euler2quaternion(euler_exp...)\n    @test isapprox(quat, quat_exp)\n\n    quat = [0.5, 0.5, 0.0, 0.0]\n    euler_exp = [0.0, 0.0, pi/2.0]\n\n    euler = quaternion2euler(quat...)\n    @test isapprox(euler, euler_exp)\n\n    quat_exp = [quat...]\n    quat = euler2quaternion(euler_exp...)\n    @test isapprox(quat, quat_exp / norm(quat_exp))\n\n    psi, theta, phi = pi/4.0, pi/6.0, pi/12.0\n    quat = euler2quaternion(psi, theta, phi)\n    euler = quaternion2euler(quat...)\n    @test isapprox([psi, theta, phi], euler)\n\n    quat = [0.5, 0.1, 0.2, 0.7]\n    quat = quat / norm(quat)\n    euler = quaternion2euler(quat...)\n    quat3 = euler2quaternion(euler...)\n    @test isapprox(quat, quat3)\nend\n\n\n@testset \"body <-> horizon\" begin\n    ones_ = [1.0, 1.0, 1.0]\n\n    # body2hor Euler\n    # no rotation\n    @test ones_ \u2248 body2hor(ones_..., 0., 0., 0.)\n\n    angles1 = [0., 45*pi/180., 0.]\n    angles2 = [0., 0., 45*pi/180]\n    angles3 = [45*pi/180, 0., 0.]\n    exp_b2h_1 = [2*0.70710678118654757, 1, 0]\n    exp_b2h_2 = [1, 0, 2*0.70710678118654757]\n    exp_b2h_3 = [0, 2*0.70710678118654757, 1]\n\n    @test exp_b2h_1 \u2248 body2hor(ones_..., angles1...)\n    @test exp_b2h_2 \u2248 body2hor(ones_..., angles2...)\n    @test exp_b2h_3 \u2248 body2hor(ones_..., angles3...)\n\n    # hor2body Euler\n    @test ones_ \u2248 hor2body(ones_..., 0., 0., 0.)\n    @test ones_ \u2248 hor2body(exp_b2h_1..., angles1...)\n    @test ones_ \u2248 hor2body(exp_b2h_2..., angles2...)\n    @test ones_ \u2248 hor2body(exp_b2h_3..., angles3...)\n\n    # body2hor quaternion\n    @test ones_ \u2248 body2hor(ones_..., 0., 0., 0.)\n\n    quat1 = euler2quaternion(angles1...)\n    quat2 = euler2quaternion(angles2...)\n    quat3 = euler2quaternion(angles3...)\n\n    @test exp_b2h_1 \u2248 body2hor(ones_..., quat1...)\n    @test exp_b2h_2 \u2248 body2hor(ones_..., quat2...)\n    @test exp_b2h_3 \u2248 body2hor(ones_..., quat3...)\n\n    # hor2body quaternionr\n    @test ones_ \u2248 hor2body(ones_..., 0., 0., 0.)\n    @test ones_ \u2248 hor2body(exp_b2h_1...,  quat1...)\n    @test ones_ \u2248 hor2body(exp_b2h_2...,  quat2...)\n    @test ones_ \u2248 hor2body(exp_b2h_3...,  quat3...)\n\n    # rotation matrix body to hor (euler)\n    r_hb1 = rot_matrix_body2hor(angles1...)\n    @test exp_b2h_1 \u2248 r_hb1 * ones_\n    r_hb2 = rot_matrix_body2hor(angles2...)\n    @test exp_b2h_2 \u2248 r_hb2 * ones_\n    r_hb3 = rot_matrix_body2hor(angles3...)\n    @test exp_b2h_3 \u2248 r_hb3 * ones_\n\n    # rotation matrix body <-> hor (quaternion)\n    r_hb1q = rot_matrix_body2hor(quat1...)\n    @test exp_b2h_1 \u2248 r_hb1q * ones_\n    r_hb2q = rot_matrix_body2hor(quat2...)\n    @test exp_b2h_2 \u2248 r_hb2q * ones_\n    r_hb3q = rot_matrix_body2hor(quat3...)\n    @test exp_b2h_3 \u2248 r_hb3q * ones_\n\n    # r_hb equivalent with euler and quaternion\n    @test isapprox(r_hb1, r_hb1q)\n    @test isapprox(r_hb2, r_hb2q)\n    @test isapprox(r_hb3, r_hb3q)\n\n    # rotation matrix hor to body (euler)\n    r_bh1 = rot_matrix_hor2body(angles1...)\n    @test ones_ \u2248 r_bh1 * exp_b2h_1\n    r_bh2 = rot_matrix_hor2body(angles2...)\n    @test ones_ \u2248 r_bh2 * exp_b2h_2\n    r_bh3 = rot_matrix_hor2body(angles3...)\n    @test ones_ \u2248 r_bh3 * exp_b2h_3\n\n    # rotation matrix hor2body (quaternion)\n    r_bh1q = rot_matrix_hor2body(quat1...)\n    @test ones_ \u2248 r_bh1q * exp_b2h_1\n    r_bh2q = rot_matrix_hor2body(quat2...)\n    @test ones_ \u2248 r_bh2q * exp_b2h_2\n    r_bh3q = rot_matrix_hor2body(quat3...)\n    @test ones_ \u2248 r_bh3q * exp_b2h_3\n\n    # r_bh equivalent with euler and quaternion\n    @test isapprox(r_bh1, r_bh1q)\n    @test isapprox(r_bh2, r_bh2q)\n    @test isapprox(r_bh3, r_bh3q)\n\n    # Test that quaternion and euler produce the same transformation\n    psi, theta, phi = pi/4.0, pi/6.0, pi/12.0\n    quat = euler2quaternion(psi, theta, phi)\n    xh, yh, zh = 100.0, 10.0, -1.0\n\n    xyz_b_e = hor2body(xh, yh, zh, psi, theta, phi)\n    xyz_b_q = hor2body(xh, yh, zh, quat...)\n\n    @test isapprox(xyz_b_e, xyz_b_q)\n\n    xyz_h_e = body2hor(xyz_b_e..., psi, theta, phi)\n    xyz_h_q = body2hor(xyz_b_e..., quat...)\n\n    @test isapprox(xyz_h_e, xyz_h_q)\nend\n\n\n@testset \"wind <-> hor/body\" begin\n    ones_ = [1.0, 1.0, 1.0]\n    angles1 = [0., 45*pi/180., 0.]\n    angles2 = [0., 0., 45*pi/180]\n    angles3 = [45*pi/180, 0., 0.]\n    exp_b2h_1 = [2*0.70710678118654757, 1, 0]\n    exp_b2h_2 = [1, 0, 2*0.70710678118654757]\n    exp_b2h_3 = [0, 2*0.70710678118654757, 1]\n    #wind2hor\n    @test ones_ \u2248 wind2hor(ones_..., 0., 0., 0.)\n    @test exp_b2h_1 \u2248 wind2hor(ones_..., angles1...)\n    @test exp_b2h_2 \u2248 wind2hor(ones_..., angles2...)\n    @test exp_b2h_3 \u2248 wind2hor(ones_..., angles3...)\n    #hor2wind\n    @test ones_ \u2248 hor2wind(ones_..., 0., 0., 0.)\n    @test ones_ \u2248 hor2wind(exp_b2h_1..., angles1...)\n    @test ones_ \u2248 hor2wind(exp_b2h_2..., angles2...)\n    @test ones_ \u2248 hor2wind(exp_b2h_3..., angles3...)\n    #wind2body\n    @test ones_ \u2248 wind2body(ones_..., 0., 0.)\n    @test [0, 1, 2*0.70710678118654757] \u2248 wind2body(ones_..., 45*pi/180., 0.)\n    @test exp_b2h_3 \u2248 wind2body(ones_..., 0., 45*pi/180.)\n    #body2wind\n    @test ones_ \u2248 body2wind(ones_..., 0., 0.)\n    @test ones_ \u2248 body2wind(0, 1, 2*0.70710678118654757, 45*pi/180., 0.)\n    @test ones_ \u2248 body2wind(exp_b2h_3..., 0., 45*pi/180.)\nend\n\n\n@testset \"hor <-> ECEF\" begin\n    xecef, yecef, zecef = 1.0, 10.0, 100.0\n    lat, lon = 0.0, 0.0\n    exp_xyz_hor = [100.0, 10.0 ,-1.0]\n\n    xyz_hor =  ecef2hor(xecef, yecef, zecef, lat, lon)\n    @test isapprox(xyz_hor, exp_xyz_hor)\n\n    r_hecef = rot_matrix_ecef2hor(lat, lon)\n    @test isapprox(exp_xyz_hor, r_hecef * [xecef, yecef, zecef])\n\n    exp_xyz_ecef = [xecef, yecef, zecef]\n    xyz_ecef = hor2ecef(exp_xyz_hor..., lat, lon)\n    @test isapprox(xyz_ecef, exp_xyz_ecef)\n\n    r_ecefh = rot_matrix_hor2ecef(lat, lon)\n    @test isapprox(exp_xyz_ecef, r_ecefh * exp_xyz_hor)\n\n    lat, lon = pi/2.0, 0.0\n    exp_xyz_hor = [-1.0, 10.0 ,-100.0]\n\n    xyz_hor =  ecef2hor(xecef, yecef, zecef, lat, lon)\n    @test isapprox(xyz_hor, exp_xyz_hor)\n\n    r_hecef = rot_matrix_ecef2hor(lat, lon)\n    @test isapprox(exp_xyz_hor, r_hecef * [xecef, yecef, zecef])\n\n    exp_xyz_ecef = [xecef, yecef, zecef]\n    xyz_ecef = hor2ecef(exp_xyz_hor..., lat, lon)\n    @test isapprox(xyz_ecef, exp_xyz_ecef)\n\n    r_ecefh = rot_matrix_hor2ecef(lat, lon)\n    @test isapprox(exp_xyz_ecef, r_ecefh * exp_xyz_hor)\n\n    lat, lon = 0.0, pi/2.0\n    exp_xyz_hor = [100.0, -1.0 ,-10.0]\n\n    xyz_hor =  ecef2hor(xecef, yecef, zecef, lat, lon)\n    @test isapprox(xyz_hor, exp_xyz_hor)\n\n    r_hecef = rot_matrix_ecef2hor(lat, lon)\n    @test isapprox(exp_xyz_hor, r_hecef * [xecef, yecef, zecef])\n\n    exp_xyz_ecef = [xecef, yecef, zecef]\n    xyz_ecef = hor2ecef(exp_xyz_hor..., lat, lon)\n    @test isapprox(xyz_ecef, exp_xyz_ecef)\n\n    r_ecefh = rot_matrix_hor2ecef(lat, lon)\n    @test isapprox(exp_xyz_ecef, r_ecefh * exp_xyz_hor)\n\n    lat, lon = pi/2.0, pi/2.0\n    exp_xyz_hor = [-10.0, -1.0 ,-100.0]\n\n    xyz_hor =  ecef2hor(xecef, yecef, zecef, lat, lon)\n    @test isapprox(xyz_hor, exp_xyz_hor)\n\n    r_hecef = rot_matrix_ecef2hor(lat, lon)\n    @test isapprox(exp_xyz_hor, r_hecef * [xecef, yecef, zecef])\n\n    exp_xyz_ecef = [xecef, yecef, zecef]\n    xyz_ecef = hor2ecef(exp_xyz_hor..., lat, lon)\n    @test isapprox(xyz_ecef, exp_xyz_ecef)\n\n    r_ecefh = rot_matrix_hor2ecef(lat, lon)\n    @test isapprox(exp_xyz_ecef, r_ecefh * exp_xyz_hor)\nend\n\n@testset \"body <-> ECEF\" begin\n    # uses ecef2hor and hor2body so not intensive testing necessary\n    xecef, yecef, zecef = 1.0, 10.0, 100.0\n    psi, theta, phi = pi/4.0, pi/6.0, pi/12.0\n    quat = euler2quaternion(psi, theta, phi)\n    lat, lon = pi/3, pi/6\n    xh, yh, zh = ecef2hor(xecef, yecef, zecef, lat, lon)\n    exp_xyz_b = hor2body(xh, yh, zh, psi, theta, phi)\n\n    xyz_body = ecef2body(xecef, yecef, zecef, lat, lon , psi, theta, phi)\n    @test isapprox(xyz_body, exp_xyz_b)\n\n    r_becef = rot_matrix_ecef2body(lat, lon , psi, theta, phi)\n    @test isapprox(r_becef * [xecef, yecef, zecef], exp_xyz_b)\n\n    xyz_body = ecef2body(xecef, yecef, zecef, lat, lon , quat...)\n    @test isapprox(xyz_body, exp_xyz_b)\n\n    r_becef_q = rot_matrix_ecef2body(lat, lon , quat...)\n    @test isapprox(r_becef_q * [xecef, yecef, zecef], exp_xyz_b)\n\n    exp_xyz_ecef = [xecef, yecef, zecef]\n\n    xyz_ecef = body2ecef(exp_xyz_b..., lat, lon, psi, theta, phi)\n    @test isapprox(xyz_ecef, exp_xyz_ecef)\n\n    r_ecefb = rot_matrix_body2ecef(lat, lon , psi, theta, phi)\n    @test isapprox(r_ecefb * exp_xyz_b, exp_xyz_ecef)\n\n    xyz_ecef = body2ecef(exp_xyz_b..., lat, lon, quat...)\n    @test isapprox(xyz_ecef, exp_xyz_ecef)\n\n    r_ecefb_q = rot_matrix_body2ecef(lat, lon , quat...)\n    @test isapprox(r_ecefb_q * exp_xyz_b, exp_xyz_ecef)\nend\n\n\n@testset \"llh <-> ECEF\" begin\n    # llh ECEF (using data from\n    # - [1] Bowring, B. R. (1976). Transformation from spatial to geographical\n    # coordinates. Survey review, 23(181), 323-327.)\n    using FlightMechanics: Ellipsoid\n\n    # From [1] Example 1 (page 325)\n    x = 4114496.258  # m\n    y = 0.0          # m\n    z = 4870157.031  # m\n    # Ellipsoid does not match any known standard\n    a_bowring1976 = 6378249.145  # m\n    b_bowring1976 = 6356514.870  # m\n    finv_bowring1976 = a_bowring1976 / (a_bowring1976 - b_bowring1976)\n    Bowring1976 = Ellipsoid(a_bowring1976, finv_bowring1976)\n\n    exp_llh = [deg2rad(50.0), 0, 10000.0]\n    llh = ecef2llh(x, y, z; ellipsoid=Bowring1976)\n    @test isapprox(llh, exp_llh)\n\n    exp_xyz = [4114496.258, 0.0, 4870157.031]  # m\n    xyz = llh2ecef(deg2rad(50.0), 0, 10000.0; ellipsoid=Bowring1976)\n    @test isapprox(xyz, exp_xyz)\n\n\n    # http://www.sysense.com/products/ecef_lla_converter/index.html\n    x, y, z = (4114496.258, 0.0, 4870157.031)  # m\n    exp_llh = [deg2rad(49.996908), 0.000000, 9907.31]\n    llh = ecef2llh(x, y, z)\n    # Longitude should be exact, latitude max error: 0.0018\" according to [1]\n    # Altitude 0.17 m\n    # The implemented function must be better, but I don't know which one is using\n    # this web page. The ellipsoid is assumed to be WGS84\n    @test isapprox(llh[:2], exp_llh[:2], atol=deg2rad(0.0018/3600.0))\n    @test isapprox(llh[3], exp_llh[3], atol=0.17)\n\n    exp_xyz = [4114291.97, 0.00, 4870449.48]  # m\n    xyz = llh2ecef(deg2rad(50.0), 0, 10000.0)\n    @test isapprox(xyz, exp_xyz)\n\n    # non-zero longitude\n    x, y, z = (3814496.258, 1514496.258, 4870157.031)  # m\n    exp_llh = [deg2rad(50.068095), deg2rad(21.654910), 3263.97]\n    llh = ecef2llh(x, y, z)\n    # Longitude should be exact, latitude max error: 0.0018\" according to [1]\n    # Altitude 0.17 m\n    # The implemented function must be better, but I don't know which one is using\n    # this web page. The ellipsoid is assumed to be WGS84\n    @test isapprox(llh[:2], exp_llh[:2], atol=deg2rad(0.0018/3600.0))\n    @test isapprox(llh[3], exp_llh[3], atol=0.17)\n\n    exp_xyz = [3814496.258, 1514496.258, 4870157.031]  # m\n    xyz = llh2ecef(deg2rad(50.068095), deg2rad(21.654910), 3263.97)\n    @test isapprox(xyz, exp_xyz)\nend\n", "meta": {"hexsha": "1c4a2acc09099b0d3d5344a50b3ebddf5f6dc5c8", "size": 11129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/coordinates.jl", "max_stars_repo_name": "UnofficialJuliaMirror/FlightMechanics.jl-d8b13f87-1844-53e1-ad89-0742af8604bf", "max_stars_repo_head_hexsha": "75d91b0fff375000868f054857d1c6451eeb558a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-07-08T11:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T14:34:34.000Z", "max_issues_repo_path": "test/coordinates.jl", "max_issues_repo_name": "UnofficialJuliaMirror/FlightMechanics.jl-d8b13f87-1844-53e1-ad89-0742af8604bf", "max_issues_repo_head_hexsha": "75d91b0fff375000868f054857d1c6451eeb558a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2018-07-10T21:23:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-16T03:39:48.000Z", "max_forks_repo_path": "test/coordinates.jl", "max_forks_repo_name": "UnofficialJuliaMirror/FlightMechanics.jl-d8b13f87-1844-53e1-ad89-0742af8604bf", "max_forks_repo_head_hexsha": "75d91b0fff375000868f054857d1c6451eeb558a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:49:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T14:34:26.000Z", "avg_line_length": 33.9298780488, "max_line_length": 82, "alphanum_fraction": 0.642375775, "num_tokens": 4374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303732328411, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7698909092671423}}
{"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 \u2264 t \u2264 T\n\t return (a0 + a1 * cos((2\u03c0*t)/T) + a2 * cos((2\u03c0*2*t)/T) +  a3 * cos((2\u03c0*3*t)/T)) * cos(2\u03c0*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 \u2264 t \u2264 T\n\t return -( a1 * sin((2\u03c0*t)/T) + a2 * sin((2\u03c0*2*t)/T) +  a3 * sin((2\u03c0*3*t)/T)) * cos(2\u03c0*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\u03b4t = 1/(s.fc+ s.half_bandwidth)/nsamples\n\tt_samples = range(0,20T,step = \u03b4t)\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 MatrixPolynomials\nusing Test\n\nx = variable(\"x\")\n\n@testset \"Polynomials definition\" begin\n\n    p1 = x^2+x+1\n    @test p1 == Pol([1, 1, 1])\n\n    p2 = x^2+2x+3\n    @test p2 == Pol([3, 2, 1])\n\n    @test rev(p1) == p1\n    @test rev(p2) == Pol([1, 2, 3])\n\n    @test deg(p1) == 2\n    @test deg(Pol([3])) == 0\n\n    p2 = x+x+x^2+x^2\n    @test p2 == 2x^2+2x\n    @test lc(p2) == 2\n    @test lm(p2) == 2x^2\n\n    @test (x+1)^2 == x^2+2x+1\nend\n\n@testset \"Polynomial opereations\" begin\n    p1 = x^2+x+1\n\n    @test p1 + 0 == p1\n    @test 0 + p1 == p1\n    @test iszero(p1-p1)\n    @test length(p1-p1) == 1\n    @test deg(p1-p1) == 0\n\n    p2 = Pol(1.0)\n    @test p1+p2 == 1.0x^2+1.0x+2.0\n\n    @test (x+1)^2 == x^2+2x+1\n    @test (x+1)*(x+2) == x^2+3x+2\n    @test p1*1 == p1\n    @test 2*p1 == 2x^2+2x+2\n\n    p1 = x^2+2x+1\n    p2 = x+1\n    q, r = divrem(p1, p2)\n    @test iszero(r)\n    @test q == x+1\n\nend\n", "meta": {"hexsha": "6998328cbc075af5e72ed6a6f83f7f696ab7b10a", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testPolynomials.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": "test/testPolynomials.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": "test/testPolynomials.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": 17.1153846154, "max_line_length": 39, "alphanum_fraction": 0.4786516854, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317886, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7698909085284052}}
{"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) \u00f7 nrows +\n            (c[2] - 1) \u00f7 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": "#!/usr/bin/julia\n\n# Julia Lang\n\n# Written by Katrina Siegfried\n# 2018-09-15\n# CSCI3412_Algorithms\n\n# BubbleSort algorithm written from notes from DataStructures\nfunction bubbleSort(list)\n\tnumberOfSwaps = 0\n\tnumberOfComparisons = 0\n\tlen = length(list)\n\tfor i = 1:len-1\n\t\tfor j = 2:len\n\t\t\tnumberOfComparisons += 1\n\t\t\tif list[j-1] > list[j]\n\t\t\t\ttmp = list[j-1]\n\t\t\t\tlist[j-1] = list[j]\n\t\t\t\tlist[j] = tmp\n\t\t\t\tnumberOfSwaps += 1\n\t\t\tend\n\t\tend\n\tend\n\tprintln(\"Number of swaps: \", numberOfSwaps)\n\tprintln(\"Number of comparisons: \", numberOfComparisons)\nend\n\n\n# UNCOMMENT CODE BELOW TO PRINT UNSORTED LIST\t\nfor i = 1:length(listToSort)\n\t# println(listToSort[i])\nend\n\n# CALL BUBBLE SORT AND BENCHMARK IT\nprintln(\"Bubble Sort\")\n@time bubbleSort(listToSort)\nwritedlm(\"sortResults.txt\", listToSort)\n\n# UNCOMMENT CODE BELOW TO PRINT SORTED LIST\t\nfor i = 1:length(listToSort)\n\tprintln(listToSort[i])\nend\n\n", "meta": {"hexsha": "eb2ebf16ae5c8b956743b7db9b048a06ac699759", "size": 888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BubbleSort.jl", "max_stars_repo_name": "siegfrkn/JuliaDemoScripts", "max_stars_repo_head_hexsha": "1482cb06dd6d01d55e02b1f0074d0e13ab125be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BubbleSort.jl", "max_issues_repo_name": "siegfrkn/JuliaDemoScripts", "max_issues_repo_head_hexsha": "1482cb06dd6d01d55e02b1f0074d0e13ab125be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BubbleSort.jl", "max_forks_repo_name": "siegfrkn/JuliaDemoScripts", "max_forks_repo_head_hexsha": "1482cb06dd6d01d55e02b1f0074d0e13ab125be4", "max_forks_repo_licenses": ["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.7333333333, "max_line_length": 61, "alphanum_fraction": 0.7128378378, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8740772236840656, "lm_q1q2_score": 0.7698846700180122}}
{"text": "using PlotlyJS, FileIO, JLD2, SeisIO\n\n# This script makes two time_shifted or stretched traces for validation of SeisXcorrelation\n\n#----------------------------------#\ndt     = 0.01; # sampling time of waveform\n# control time shift\ntarrival_1 = 30 #wave arrival time at station 1\ntarrival_2 = 30.05 #wave arrival time at station 2\n# control relative frequency\nf1 = 0.1 # source sine frequency Hz\nf2 = f1*1.01\n\nnpts = 6000; # length of time series\n\nfoname = \"./sinStretchTest.jld2\"\n#----------------------------------#\n#Period of sine\nT1 = 1/f1\nT2 = 1/f2\n\nnpts_sine1 = round(Int64, T1/dt)\nnpts_sine2 = round(Int64, T2/dt)\n\n# make waveform time series\ns1   = sin.(LinRange(0, 2*pi, npts_sine1));\ns2   = sin.(LinRange(0, 2*pi, npts_sine2));\n\nu1 = zeros(Float64, npts)\nu2 = zeros(Float64, npts)\n\ntp1 = round(Int64, tarrival_1/dt)\ntp2 = round(Int64, tarrival_2/dt)\n\nu1[tp1:tp1+npts_sine1-1] = s1\nu2[tp2:tp2+npts_sine2-1] = s2\n\ntvec  = collect(( 0:npts - 1 ) .* dt);\n\n\u0394tlag_true = tarrival_2 - tarrival_1 # true arrival time, which should be equal to the time at maximam coherency of cross-correlation function\n\n# package generated signal in SeisChannel and save\nt=[1 0; npts 0]\nCh1 = SeisChannel(name=\"BP.u1u1.fst\", id=\"BP.u1u1.fst\", x=u1, fs=1/dt, t=t)\nCh1.misc[\"dlerror\"] = 0\nCh2 = SeisChannel(name=\"BP.u2u2.snd\", id=\"BP.u2u2.snd\", x=u2, fs=1/dt, t=t)\nCh2.misc[\"dlerror\"] = 0\njldopen(foname, \"a+\") do file\n    file[\"info/DLtimestamplist\"] = [\"time1\"]\n    file[\"info/stationlist\"] = [\"BP.u1u1.fst\", \"BP.u2u2.snd\"]\n    file[\"info/DL_time_unit\"] = npts*dt\n    file[\"info/f1\"] = f1\n    file[\"info/f2\"] = f2\n    file[\"info/\u0394tlag_true\"] = \u0394tlag_true\n    file[\"time1/BP.u1u1.fst\"] = Ch1\n    file[\"time1/BP.u2u2.snd\"] = Ch2\nend\n\n#plot curve\nfunction lineplot1()\n    tr1 = scatter(;x=tvec, y=u1, mode=\"lines+markers\", name=\"u1\")\n    tr2 = scatter(;x=tvec, y=u2, mode=\"lines+markers\", name=\"u2\")\n    layout = Layout(\n        xaxis=attr(title=\"u1\"),\n        yaxis=attr(title=\"u2\"),\n        title=\"True time shift = $\u0394tlag_true [s]\"\n    )\n    p = plot([tr1, tr2], layout)\n    display(p)\n    readline()\nend\n", "meta": {"hexsha": "d51c834a8f0aa0b611300ff13fda24b8a93435b8", "size": 2091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "EXAMPLE/codevalidation/Xcorrelation/makeSinewaveform.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/Xcorrelation/makeSinewaveform.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/Xcorrelation/makeSinewaveform.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.0416666667, "max_line_length": 142, "alphanum_fraction": 0.6408417025, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257062, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7698724053633724}}
{"text": "using Test, FinancialMonteCarlo;\n@show \"NormalInverseGaussianProcess\"\nS0 = 100.0;\nK = 100.0;\nr = 0.02;\nT = 1.0;\nd = 0.01;\nD = 90.0;\n\nNsim = 10000;\nNstep = 30;\nsigma = 0.2;\ntheta1 = 0.01;\nk1 = 0.03;\nmc = MonteCarloConfiguration(Nsim, Nstep);\nmc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());\ntoll = 0.8;\n\nrfCurve = ZeroRate(r);\n\nFwdData = Forward(T)\nEUData = EuropeanOption(T, K)\nAMData = AmericanOption(T, K)\nBarrierData = BarrierOptionDownOut(T, K, D)\nAsianData = AsianFloatingStrikeOption(T)\nModel = NormalInverseGaussianProcess(sigma, theta1, k1, Underlying(S0, d));\n\n@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);\n@show EuPrice = pricer(Model, rfCurve, mc, EUData);\n@show AmPrice = pricer(Model, rfCurve, mc, AMData);\n@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);\n@show AsianPrice = pricer(Model, rfCurve, mc, AsianData);\n\n@test abs(FwdPrice - 97.95852227697686) < toll\n@test abs(EuPrice - 7.738298817933206) < toll\n@test abs(BarrierPrice - 6.886023820038332) < toll\n@test abs(AsianPrice - 4.414948846776423) < toll\n\n@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);\n@show EuPrice = pricer(Model, rfCurve, mc1, EUData);\n@show AmPrice = pricer(Model, rfCurve, mc1, AMData);\n@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);\n@show AsianPrice = pricer(Model, rfCurve, mc1, AsianData);\ntollanti = 0.8;\n@test abs(FwdPrice - 97.95852227697686) < tollanti\n@test abs(EuPrice - 7.738298817933206) < tollanti\n@test abs(BarrierPrice - 6.886023820038332) < tollanti\n@test abs(AsianPrice - 4.414948846776423) < tollanti\n\n@show \"Test NIG Parameters\"\n\n@test_throws(ErrorException, NormalInverseGaussianProcess(-sigma, theta1, k1, Underlying(S0, d)))\n@test_throws(ErrorException, NormalInverseGaussianProcess(sigma, theta1, -k1, Underlying(S0, d)))\n@test_throws(ErrorException, NormalInverseGaussianProcess(sigma, 10000.0, k1, Underlying(S0, d)))\n", "meta": {"hexsha": "1ab7d399557cbaee3cf9aab7922bc8c7176bb9dc", "size": 1906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_nig.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": "test/test_nig.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": "test/test_nig.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": 34.6545454545, "max_line_length": 97, "alphanum_fraction": 0.7434417629, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509316, "lm_q2_score": 0.8175744761936438, "lm_q1q2_score": 0.7698724047787847}}
{"text": "ACTV_FUNCS = [\"relu\", \"sigmoid\", \"\u03c3\", \"tanh\"]\n\nfunction \u03c3(X)\n    return 1 ./(1 .+ exp.(.-X))\nend\n\nfunction relu(X)\n    return max.(0,X)\nend\n\nfunction d\u03c3(z)\n    return \u03c3(z).*(1 .-\u03c3(z))\nend\n\nfunction drelu(z)\n    return z.*(z.>0)\nend\n", "meta": {"hexsha": "2db98358f7d90a21746ce3f8261f785a7f51bb51", "size": 232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/neuralactivations.jl", "max_stars_repo_name": "mirandagil/NeuralNet.jl", "max_stars_repo_head_hexsha": "789b888663577f835c0f9efb4963302f0b2df482", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-13T00:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T00:14:50.000Z", "max_issues_repo_path": "src/neuralactivations.jl", "max_issues_repo_name": "mirandagil/NeuralNet.jl", "max_issues_repo_head_hexsha": "789b888663577f835c0f9efb4963302f0b2df482", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/neuralactivations.jl", "max_forks_repo_name": "mirandagil/NeuralNet.jl", "max_forks_repo_head_hexsha": "789b888663577f835c0f9efb4963302f0b2df482", "max_forks_repo_licenses": ["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.8888888889, "max_line_length": 45, "alphanum_fraction": 0.5560344828, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7698724038551759}}
{"text": "\ufeff#=\nGeometry in 2d euclidean space\n=#\n\n\"\"\"\ndeltaangle(a::Real, b::Real)\n\nReturn the minimum \u03b4 such that\n    a + \u03b4 = mod(b, 2\u03c0)\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 \u2248 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.\u03b8), cos(reference.\u03b8)\n    \u0394x = point.x - reference.x\n    \u0394y = point.y - reference.y\n    VecE2(c*\u0394x + s*\u0394y, c*\u0394y - s*\u0394x)\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.\u03b8), cos(reference.\u03b8)\n    \u0394x = point.x - reference.x\n    \u0394y = point.y - reference.y\n    VecSE2(c*\u0394x + s*\u0394y, c*\u0394y - s*\u0394x, point.\u03b8 - reference.\u03b8)\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.\u03b8), sin(reference.\u03b8)\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.\u03b8), sin(reference.\u03b8)\n    VecSE2(c*point.x -s*point.y + reference.x, s*point.x +c*point.y + reference.y, reference.\u03b8 + point.\u03b8)\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(\u03d5) = Complex{Int}(round(Int,cos(deg2rad(\u03d5))), round(Int,sin(deg2rad(\u03d5))))\nmoves = Dict(\n    'N' => \u03b1 -> c -> begin (p,d) = c; (p + Complex{Int}(0,\u03b1), d) end,\n    'S' => \u03b1 -> c -> begin (p,d) = c; (p + Complex{Int}(0,-\u03b1), d) end,\n    'E' => \u03b1 -> c -> begin (p,d) = c; (p + Complex{Int}(\u03b1,0), d) end,\n    'W' => \u03b1 -> c -> begin (p,d) = c; (p + Complex{Int}(-\u03b1,0), d) end,\n    'L' => \u03d5 -> c -> begin (p,d) = c; (p, d * rot(\u03d5)) end,\n    'R' => \u03d5 -> c -> begin (p,d) = c; (p, d * rot(-\u03d5)) 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' => \u03b1 -> c -> begin (p,d) = c; (p, d + Complex{Int}(0,\u03b1)) end,\n    'S' => \u03b1 -> c -> begin (p,d) = c; (p, d + Complex{Int}(0,-\u03b1)) end,\n    'E' => \u03b1 -> c -> begin (p,d) = c; (p, d + Complex{Int}(\u03b1,0)) end,\n    'W' => \u03b1 -> c -> begin (p,d) = c; (p, d + Complex{Int}(-\u03b1,0)) end,\n    'L' => \u03d5 -> c -> begin (p,d) = c; (p, d * rot(\u03d5)) end,\n    'R' => \u03d5 -> c -> begin (p,d) = c; (p, d * rot(-\u03d5)) 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": "@testset \"Algebra\" begin\n    @testset \"LorentzVector\" begin\n        zero = Vec4(0., 0., 0., 0.)\n        u1 = Vec4(1., 2., 3., 4.)\n        u2 = Vec4(-1., 3., 3., 7.)\n        @test -zero == zero\n        @test +u1 == u1\n        @test +u2 == u2\n        @test -(-u1) == u1\n        @test -(-u2) == u2\n        @test zero + u1 == u1\n        @test u1 - u1 == zero\n        @test u1 + u1 \u2248 2 * u1\n        @test u1 + u1 + u1 \u2248 3 * u1\n        @test u1 + u2 \u2248 Vec4(0., 5., 6., 11.)\n        @test u1 - u2 \u2248 Vec4(2., -1., 0., -3.)\n        @test 3.5 * u1 \u2248 u1 * 3.5\n        @test -1.2 * u2 \u2248 u2 * (-1.2)\n        @test u1 / 2 \u2248 Vec4(0.5, 1., 1.5, 2.)\n        @test (u1 / 11.) * 11. \u2248 u1\n\n        @test zero \u22c5 u1 == u1 \u22c5 zero == 0.\n        @test zero \u22c5 u2 == u2 \u22c5 zero == 0.\n        @test u1 \u22c5 u1 \u2248 -28.\n        @test u2 \u22c5 u2 \u2248 -66.\n        @test u1 \u22c5 u2 \u2248 -44.\n\n        @test Vec4(1, 0, 0, 1/3) - Vec4(1, 0, 0, 1/5) - Vec4(1, 0, 0, 2/15) \u2248 Vec4(-1., 0, 0, 0)\n        @test Vec4(1/3, 0, 0, 1) - Vec4(1/5, 0, 0, 1) - Vec4(2/15, 0, 0, 1) \u2248 Vec4(0, 0, 0, -1.)\n    end;\n\n    @testset \"SpatialVector\" begin\n        zero = Vec3(0., 0., 0.)\n        u1 = Vec3(1., 2., 4.)\n        u2 = Vec3(-1., 3., 7.)\n        @test -zero == zero\n        @test +u1 == u1\n        @test +u2 == u2\n        @test -(-u1) == u1\n        @test -(-u2) == u2\n        @test zero + u1 == u1\n        @test u1 - u1 == zero\n        @test u1 + u1 \u2248 2 * u1\n        @test u1 + u1 + u1 \u2248 3 * u1\n        @test u1 + u2 \u2248 Vec3(0., 5., 11.)\n        @test u1 - u2 \u2248 Vec3(2., -1., -3.)\n        @test 3.5 * u1 \u2248 u1 * 3.5\n        @test -1.2 * u2 \u2248 u2 * (-1.2)\n        @test u1 / 2 \u2248 Vec3(0.5, 1., 2.)\n        @test (u1 / 11.) * 11. \u2248 u1\n\n        @test zero \u22c5 u1 == u1 \u22c5 zero == 0.\n        @test zero \u22c5 u2 == u2 \u22c5 zero == 0.\n        @test u1 \u22c5 u1 \u2248 21.\n        @test u2 \u22c5 u2 \u2248 59.\n        @test u1 \u22c5 u2 \u2248 33.\n\n        @test Vec3(0, 1, 0) \u00d7 Vec3(0, 0, 1) == Vec3(1, 0, 0)\n        @test Vec3(0, 0, 1) \u00d7 Vec3(1, 0, 0) == Vec3(0, 1, 0)\n        @test Vec3(1, 0, 0) \u00d7 Vec3(0, 1, 0) == Vec3(0, 0, 1)\n        @test u1 \u00d7 u1 == zero\n        @test u2 \u00d7 u2 == zero\n        @test (u1 \u00d7 u2) \u22c5 u1 == 0\n        @test (u1 \u00d7 u2) \u22c5 u2 == 0\n        @test u1 \u00d7 u2 == Vec3(2., -11., 5.)\n\n        @test norm(zero) == 0.\n        @test norm(u1) \u2248 4.58257569495584\n        @test norm(u2) \u2248 7.681145747868608\n        @test norm(Vec3(1, 1, 0)) \u2248 \u221a2\n        @test norm(Vec3(1, 1, 1)) \u2248 \u221a3\n        @test norm(Vec3(2, 1, 2)) \u2248 3\n\n        @test normalize(Vec3(1, 1, 0)) \u2248 Vec3(1/\u221a2, 1/\u221a2, 0)\n        @test normalize(Vec3(1, 1, 1)) \u2248 Vec3(1/\u221a3, 1/\u221a3, 1/\u221a3)\n        @test normalize(Vec3(2, 2, 1)) \u2248 Vec3(2/3, 2/3, 1/3)\n    end;\nend;\n", "meta": {"hexsha": "1f6b64a358002f2556eb4cc8b42b7d9ca6815cfd", "size": 2628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/algebra.jl", "max_stars_repo_name": "UnofficialJuliaMirror/LorentzVectors.jl-3f54b04b-17fc-5cd4-9758-90c048d965e3", "max_stars_repo_head_hexsha": "960441520041584c500d5666ee702f4546a321da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-08-25T15:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T10:38:24.000Z", "max_issues_repo_path": "test/algebra.jl", "max_issues_repo_name": "UnofficialJuliaMirror/LorentzVectors.jl-3f54b04b-17fc-5cd4-9758-90c048d965e3", "max_issues_repo_head_hexsha": "960441520041584c500d5666ee702f4546a321da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-07-02T22:17:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-21T22:46:49.000Z", "max_forks_repo_path": "test/algebra.jl", "max_forks_repo_name": "Element-126/LorentzVectors.jl", "max_forks_repo_head_hexsha": "5a6db4ddc562c381f7ad4f753cca8b934133811f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:11:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T22:26:56.000Z", "avg_line_length": 33.2658227848, "max_line_length": 96, "alphanum_fraction": 0.3945966514, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7698033547967159}}
{"text": "using RLinearAlgebra\nusing LinearAlgebra\nusing UnicodePlots\n\nn = 10\nd = 10\n\u03ba = 8.0\n\nA = RLinearAlgebra.generate_matrix(n, d, d, \u03ba)\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": "using PolyChaos, Test\n\nfunction betaMoments(\u03b1, \u03b2)\n\t# moments of beta distribution, analytic solution\n\t\u03b1 / (\u03b1 + \u03b2), sqrt(\u03b1*\u03b2 / ((\u03b1+\u03b2)^2 * (1 + \u03b1 + \u03b2)))\nend\n\ndegs, Nsamples = 1:5, 10000\n\n\u03b1, \u03b2 = rand():2:10, rand():0.3:7\n\n@testset \"Mean and variance of beta distribution\" begin\n\tfor a in \u03b1, b in \u03b2, deg in degs\n\t\top = Beta01OrthoPoly(deg, a, b)\n\t\tcoeffs = calculateAffinePCE(op)\n\t\tmu, sigma = mean(coeffs, op), std(coeffs, op)\n\t\tmu_ana, sigma_ana = betaMoments(a, b)\n\t\t@test isapprox(mu, mu_ana; atol=1e-5)\n\t\t@test isapprox(sigma, sigma_ana; atol=1e-5)\n\n\t\tcoeffs = calculateAffinePCE(op.\u03b1)\n\t\tmu, sigma = mean(coeffs, op), std(coeffs, op)\n\t\tmu_ana, sigma_ana = betaMoments(a, b)\n\t\t@test isapprox(mu, mu_ana; atol=1e-5)\n\t\t@test isapprox(sigma, sigma_ana; atol=1e-5)\n\n\t\tsamples = sampleMeasure(Nsamples, op)\n\t\t@test isapprox(mu, mean(samples); atol=1e-2)\n\t\t@test isapprox(sigma, std(samples); atol=1e-2)\n\n\t\tevals = evaluatePCE(coeffs, samples, op)\n\t\t@test isapprox(mu, mean(evals); atol=1e-2)\n\t\t@test isapprox(sigma, std(evals); atol=1e-2)\n\n\t\tevals = samplePCE(Nsamples, coeffs, op)\n\t\t@test isapprox(mu, mean(evals); atol=1e-2)\n\t\t@test isapprox(sigma, std(evals); atol=1e-2)\n\tend\nend\n\n# op = GaussOrthoPoly(deg)\n# mop = MultiOrthoPoly([ op for i in 1:4 ], deg)\n\n# calculateAffinePCE(op)\n# calculateAffinePCE(3, mop)", "meta": {"hexsha": "e922f7b0846bda7acafffacdf04ff60a54ed107c", "size": 1309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/polynomial_chaos.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PolyChaos.jl-8d666b04-775d-5f6e-b778-5ac7c70f65a3", "max_stars_repo_head_hexsha": "2e60a0f205c7f32c3987b5d9e1e9ca271fca3186", "max_stars_repo_licenses": ["MIT"], "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/polynomial_chaos.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PolyChaos.jl-8d666b04-775d-5f6e-b778-5ac7c70f65a3", "max_issues_repo_head_hexsha": "2e60a0f205c7f32c3987b5d9e1e9ca271fca3186", "max_issues_repo_licenses": ["MIT"], "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/polynomial_chaos.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PolyChaos.jl-8d666b04-775d-5f6e-b778-5ac7c70f65a3", "max_forks_repo_head_hexsha": "2e60a0f205c7f32c3987b5d9e1e9ca271fca3186", "max_forks_repo_licenses": ["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.0888888889, "max_line_length": 55, "alphanum_fraction": 0.6776165011, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7698033463321573}}
{"text": "#= \nProblem 102\nThree distinct points are plotted at random on a Cartesian plane, for which -1000 \u2264 x, y \u2264 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    \u03bc::Float64\n    \u03c3::Float64\n\n    Cosine(\u03bc::Real, \u03c3::Real) = (@check_args(Cosine, \u03c3 > zero(\u03c3)); new(\u03bc, \u03c3))\n    Cosine(\u03bc::Real) = new(\u03bc, 1.0)\n    Cosine() = new(0.0, 1.0)\nend\n\n@distr_support Cosine d.\u03bc - d.\u03c3 d.\u03bc + d.\u03c3\n\n\n#### Parameters\n\nlocation(d::Cosine) = d.\u03bc\nscale(d::Cosine) = d.\u03c3\n\nparams(d::Cosine) = (d.\u03bc, d.\u03c3)\n\n\n#### Statistics\n\nmean(d::Cosine) = d.\u03bc\n\nmedian(d::Cosine) = d.\u03bc\n\nmode(d::Cosine) = d.\u03bc\n\nvar(d::Cosine) = d.\u03c3^2 * 0.13069096604865779  # 0.130... = 1/3 - 2 / \u03c0^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.\u03bc) / d.\u03c3\n        return (1.0 + cospi(z)) / (2 * d.\u03c3)\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.\u03bc) / d.\u03c3\n    0.5 * (1.0 + z + sinpi(z) * inv\u03c0)\nend\n\nfunction ccdf(d::Cosine, x::Float64)\n    nz = (d.\u03bc - x) / d.\u03c3\n    0.5 * (1.0 + nz + sinpi(nz) * inv\u03c0)\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 \u03b8, a standard deviation of direction \u03c3, and a position (x,y).\n\"\"\"\nstruct Bearing\n    \u03b8\n    \u03c3\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\u2081 + cos(\u03b8\u2081)t\u2081 = x\u2082 + cos(\u03b8\u2082)t\u2082\n    y\u2081 + sin(\u03b8\u2081)t\u2081 = y\u2082 + sin(\u03b8\u2082)t\u2082\n\n    x\u2081 - x\u2082 = -cos(\u03b8\u2081)t\u2081 + cos(\u03b8\u2082)t\u2082\n    y\u2081 - y\u2082 = -sin(\u03b8\u2081)t\u2081 + sin(\u03b8\u2082)t\u2082\n\n    This can be represented in matrix form as:\n    b = Ax\u0304\n    \n    where:\n    x\u0304 = [t\u2081, t\u2082]\n    A = |-cos(\u03b8\u2081) cos(\u03b8\u2082)|\n        |-sin(\u03b8\u2081) sin(\u03b8\u2082)|\n        \n    b = [x\u2081 - x\u2082, y\u2081 - y\u2082]\n\n    Solved by:\n    x\u0304 = A\u207b\u00b9 \u22c5 b\n\n    This matrix is singular when \u03b8\u2081 and \u03b8\u2082 are parallel, i.e.  mod(\u03b8\u2081,\u03c0) == mod(\u03b8\u2082,\u03c0)\n    In this case, there is a heuristic that sets the \"intersection\" as the midpoint between the two points.\n\n    Furthermore, if t\u1d62<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.\u03b8-b2.\u03b8,\u03c0)\u22480 \n        point = ([b1.x;b1.y] + [b2.x;b2.y])/2\n        return point\n    end\n\n    A = [-cos(b1.\u03b8) cos(b2.\u03b8);\n         -sin(b1.\u03b8) sin(b2.\u03b8)]\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.\u03b8), sin(b1.\u03b8)]*t[1];\n    return point\nend\n\n\n\"\"\"\nboundingBox(b1::Bearing, b2::Bearing)    \n    Return the box [x\u2097 x\u1d64;y\u2097 y\u1d64] 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\u1d62 = findIntersect(b1, b2);\n    p\u2081 = [b1.x;b1.y];\n    p\u2082 = [b2.x;b2.y];\n    d\u2081 = p\u1d62 - p\u2081;\n    d\u2082 = p\u1d62 - p\u2082;\n    D\u2081 = norm(d\u2081);\n    D\u2082 = norm(d\u2082);\n    D = 1.5*max(D\u2081, D\u2082);\n    box = p\u1d62 .+ 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    \u03b8 = mod(b.\u03b8 + \u03c0,2\u03c0) - \u03c0\n    D = Normal(0, b.\u03c3);\n    \u0398 = atan.(y .- b.y, x' .- b.x) .- \u03b8;\n    \u0398 = mod.(\u0398 .+ \u03c0, 2\u03c0) .-\u03c0\n    P = pdf.(D, \u0398);\n    \u0394A = convert(Float64,x.step * y.step);\n    P = P./sum(P[:])/\u0394A;\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\u2081 = probabilityGrid(b1, x, y);\n    _,_,P\u2082 = probabilityGrid(b2, x, y);\n    P\u1d62 = P\u2081 .* P\u2082\n    \u0394A = convert(Float64,x.step * y.step);\n    P\u1d62 = P\u1d62 ./ sum(P\u1d62[:])\n    P\u1d62 = P\u1d62 ./ \u0394A;\n    return x, y, P\u1d62, P\u2081, P\u2082\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(\u03b1::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 `\u03b1`\n\"\"\"\nfunction plotConfidenceInterval(\u03b1::Number, x::AbstractArray, y::AbstractArray, P...)\n    handle = contour(;aspect_ratio=:equal);\n    \u0394A = convert(Float64,x.step*y.step);\n    zeros = [bisectionRoots((p) -> \u0394A*sum(P\u2c7c[P\u2c7c .> p]) - \u03b1, minimum(P\u2c7c),maximum(P\u2c7c)) for P\u2c7c 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\u2097::Number,x\u1d64::Number; max_iteration = 100, xtol = 1e-3)\n\n    Computes the root of function `f(x)` on the bounded range `[x\u2097 x\u1d64]` with the Bisection algorithm.\n\n    Exit condition is defined by x\u1d64-x\u2097 < xtol\n\"\"\"\nfunction bisectionRoots(f::Function,x\u2097::Number,x\u1d64::Number; max_iteration = 100, xtol = 1e-3)\n    f\u2097  = f(x\u2097);\n    f\u1d64 = f(x\u1d64);\n\n    if f\u2097 == 0\n        return x\u2097\n    elseif f\u1d64 == 0\n        return x\u1d64\n    end\n\n    if (f\u2097<0 && f\u1d64<0) || (f\u2097>0 && f\u1d64>0)\n        return NaN\n    end\n\n    x\u1d62 = (x\u2097 + x\u1d64)/2;\n    iter = 1;\n\n    while abs(x\u1d64-x\u2097) > xtol\n        iter > max_iteration ? break : iter+=1;\n        if sign(f(x\u1d62))==sign(f\u2097)\n            x\u2097 = x\u1d62\n            x\u1d62 = (x\u1d62 + x\u1d64)/2\n        else\n            x\u1d64 = x\u1d62\n            x\u1d62 = (x\u2097 + x\u1d62)/2\n        end\n    end\n    return x\u1d62\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    \u03b4, \u0394 = f.\u03b4, f.\u0394\n    (zero(t) \u2264 t < \u03b4) * t + (\u03b4 \u2264 t < \u0394 + \u03b4) * \u03b4 - (\u0394 \u2264 t < \u0394 + \u03b4) * (t - \u0394)\nend\n\nfunction integral(f::DoublePGSE, t = echotime(f))\n    \u03b4, \u0394, p = f.\u03b4, f.\u0394, f.tpause\n    tmid = p + \u0394 + \u03b4\n    if zero(t) \u2264 t < \u03b4\n        t\n    elseif \u03b4 \u2264 t < \u0394\n        \u03b4\n    elseif \u0394 \u2264 t < \u0394 + \u03b4\n        \u03b4 - (t - \u0394)\n    elseif tmid \u2264 t < tmid + \u03b4\n        t - tmid\n    elseif tmid + \u03b4 \u2264 t < tmid + \u0394\n        \u03b4\n    elseif tmid + \u0394 \u2264 t < tmid + \u0394 + \u03b4\n        \u03b4 - (t - \u0394 - tmid)\n    else\n        zero(t)\n    end\nend\n\nfunction integral(f::CosOGSE, t = echotime(f))\n    \u03b4, \u0394, n = f.\u03b4, f.\u0394, f.nperiod\n    ((t < \u03b4) * sin(2\u03c0 * n * t / \u03b4) - (\u0394 \u2264 t) * sin(2\u03c0 * n * (t - \u0394) / \u03b4)) * \u03b4 / (2\u03c0 * n)\nend\n\nfunction integral(f::SinOGSE, t = echotime(f))\n    \u03b4, \u0394, n = f.\u03b4, f.\u0394, f.nperiod\n    ((t < \u03b4) * (1 - cos(2\u03c0 * n * t / \u03b4)) - (\u0394 \u2264 t) * (1 - cos(2\u03c0 * n * (t - \u0394) / \u03b4))) * \u03b4 /\n    (2\u03c0 * 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(\u03bc, \u03c3) # likelihood\n  \u03bc ~ Normal(178,20) # prior\n  \u03c3 ~ 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(\u03bc, \u03c3) # likelihood\n  \u03bc ~ Normal(178, 0.1) # prior\n  \u03c3 ~ 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": "using Test\nusing Random\n\nusing StatsModelsTools\nusing StatsModels\n\n@testset \"Test Polynomial Formulas\" begin\n\n    data = (\n            x=float.(1:10),\n            y=float.(1:10).^3,\n           )\n\n    f = @formula(y ~ poly(x, 3))\n    sch = apply_schema(f, schema(data))\n    @inferred modelcols(sch.rhs, data)\n\n    @test poly(data.x, 3) == data.x.^3\n    @test modelcols(sch.rhs, data) == [data.x data.x.^2 data.x.^3]\n\nend\n\n@testset \"Eval RMS Formulas\" begin\n\n    @test_throws Exception rcs([1,2,3], 0)\n    @test_throws Exception rcs([1,2,3], 1)\n\n    data = (\n            x=(float.(1:10)),\n            y=float.(1:10),\n            z=collect(1:10),\n           )\n\n    xs = collect(0:10)\n    @test rms_generate_knots(float.(0:100), 3) == [10, 50, 90]\n    @test rms_generate_knots((0:100), 3) == [10, 50, 90]\n    @test rms_generate_knots(vcat(float.(0:10), [missing]), 3) == [1, 5, 9]\n    @test rms_generate_knots(xs, 3) == [1, 5, 9]\n    @test rms_generate_knots(reverse(xs) |> collect, 3) == [1, 5, 9]\n    @test rms_generate_knots(shuffle(xs) |> collect, 3) == [1, 5, 9]\n\n    @test rcs(xs, [1, 5, 9]) == [0.0  0.0;\n                                 1.0  0.0;\n                                 2.0  0.015625;\n                                 3.0  0.125;\n                                 4.0  0.421875;\n                                 5.0  1.0;\n                                 6.0  1.921875;\n                                 7.0  3.125;\n                                 8.0  4.515625;\n                                 9.0  6.0;\n                                 10.0 7.5]\n\n    xs_with_missing = [xs; missing]\n    @inferred rms_generate_knots(xs, 3)\n    @inferred rms_generate_knots(xs_with_missing, 3)\n    @inferred rcs(xs_with_missing, [1, 5, 9])\n    @test rms_generate_knots(xs_with_missing, 3) == [1, 5, 9]\n\n    knots = [1, 5, 9]\n    result = rcs(xs, knots);\n    result_with_missing = rcs(xs_with_missing, knots)\n    @test all(result_with_missing .=== [result; [missing missing]])\n\n    f = @formula(y ~ rcs(x, 3))\n    sch = apply_schema(f, schema(data))\n    @inferred modelcols(sch.rhs, data)\n    @test coefnames(sch)[2] == [\"rcs(x, 3)[1]\", \"rcs(x, 3)[2]\"]\n\nend\n\n", "meta": {"hexsha": "0df00ac04d30fcb05f18eae8b91cbaa82ccde620", "size": 2156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "HHammond/StatsModelsTools.jl", "max_stars_repo_head_hexsha": "4d5e5c9208dabd64205ea170ffabebd2a03eff78", "max_stars_repo_licenses": ["MIT"], "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": "HHammond/StatsModelsTools.jl", "max_issues_repo_head_hexsha": "4d5e5c9208dabd64205ea170ffabebd2a03eff78", "max_issues_repo_licenses": ["MIT"], "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": "HHammond/StatsModelsTools.jl", "max_forks_repo_head_hexsha": "4d5e5c9208dabd64205ea170ffabebd2a03eff78", "max_forks_repo_licenses": ["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.9444444444, "max_line_length": 75, "alphanum_fraction": 0.4897959184, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7697289504119197}}
{"text": "@testset \"curl\" begin\n\nN = (3,4,5)\nM = prod(N)\nr = reshape(collect(1:3M), M, 3)'[:]  # index mapping from block matrix to narrowly banded matrix\nZ = spzeros(M,M)\n\nF = rand(ComplexF64, N..., 3)\nG = similar(F)\ng = zeros(ComplexF64, 3M)\n\n@testset \"create_curl and apply_curl!\" begin\n    for ci = CartesianIndices((false:true,false:true,false:true))\n        # Construct Curl for a uniform grid and Bloch boundaries.\n        isfwd = Vector{Bool}([ci.I...])\n        \u2202x = (nw = 1; create_\u2202(nw, isfwd[nw], [N...]))\n        \u2202y = (nw = 2; create_\u2202(nw, isfwd[nw], [N...]))\n        \u2202z = (nw = 3; create_\u2202(nw, isfwd[nw], [N...]))\n        Curl_blk = [Z -\u2202z \u2202y;\n                    \u2202z Z -\u2202x;\n                    -\u2202y \u2202x Z]\n\n        Curl = create_curl(isfwd, [N...], order_cmpfirst=false)\n\n        # Test the overall coefficients.\n        @test size(Curl) == (3M,3M)\n        @test all(any(Curl.\u22600, dims=1))  # no zero columns\n        @test all(any(Curl.\u22600, dims=2))  # no zero rows\n        @test all(sum(Curl, dims=2) .== 0)  # all row sums are zero, because Curl * ones(M) = 0\n\n        @test Curl == Curl_blk\n\n        # Construct Curl for a nonuniform grid and general boundaries.\n        \u2206l\u207b\u00b9 = rand.(N)  # isfwd = true (false) uses \u2206l\u207b\u00b9 at dual (primal) locations\n        isbloch = [true, false, false]\n        e\u207b\u2071\u1d4f\u1d38 = rand(ComplexF64, 3)\n        \u2202x = (nw = 1; create_\u2202(nw, isfwd[nw], [N...], \u2206l\u207b\u00b9[nw], isbloch[nw], e\u207b\u2071\u1d4f\u1d38[nw]))\n        \u2202y = (nw = 2; create_\u2202(nw, isfwd[nw], [N...], \u2206l\u207b\u00b9[nw], isbloch[nw], e\u207b\u2071\u1d4f\u1d38[nw]))\n        \u2202z = (nw = 3; create_\u2202(nw, isfwd[nw], [N...], \u2206l\u207b\u00b9[nw], isbloch[nw], e\u207b\u2071\u1d4f\u1d38[nw]))\n        Curl_blk = [Z -\u2202z \u2202y;\n                    \u2202z Z -\u2202x;\n                    -\u2202y \u2202x Z]\n\n        Curl = create_curl(isfwd, \u2206l\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n\n        # Test Curl.\n        @test Curl == Curl_blk\n\n        # Test Cartesian-component-major ordering.\n        Curl_cmpfirst = create_curl(isfwd, \u2206l\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=true)\n        @test Curl_cmpfirst == Curl[r,r]\n\n        # Test apply_curl!.\n        f = F[:]\n        mul!(g, Curl, f)\n        apply_curl!(G, F, Val(:(=)), isfwd, \u2206l\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38)\n        @test G[:] \u2248 g\n\n        # print(\"matrix: \"); @btime mul!($g, $Curl, $f)\n        # print(\"matrix-free: \"); @btime apply_curl!($G, $F, Val(:(=)), $isfwd, $\u2206l\u207b\u00b9, $isbloch, $e\u207b\u2071\u1d4f\u1d38)\n\n        # Test 1\u00d71 curls for 1D, and 1\u00d72, 2\u00d71 curls for 2D.\n        nw_blk = [0 -3 2;\n                  3 0 -1;\n                  -2 1 0]\n\n        cmp_shps = ([1], [2], [3], [1,2], [2,3], [3,1])\n        for cmp_shp = cmp_shps\n            if length(cmp_shp) == 1\n                cmp_outs = setdiff(([1],[2],[3]), tuple(cmp_shp))\n            else  # length(cmp_shp) == 2\n                cmp_outs = (cmp_shp, setdiff([1,2,3], cmp_shp))\n            end\n\n            for cmp_out = cmp_outs\n                if length(cmp_shp) == 1\n                    cmp_in = [6 - only(cmp_shp) - only(cmp_out)]\n                else  # length(cmp_shp) == 2\n                    cmp_in = setdiff([1,2,3], cmp_out)\n                end\n\n                Ncmp = N[cmp_shp]\n                Mcmp = prod(Ncmp)\n                Zcmp = spzeros(Mcmp,Mcmp)\n\n                isfwdcmp = isfwd[cmp_shp]\n                \u2206l\u207b\u00b9cmp = \u2206l\u207b\u00b9[cmp_shp]\n                isblochcmp = isbloch[cmp_shp]\n                e\u207b\u2071\u1d4f\u1d38cmp = e\u207b\u2071\u1d4f\u1d38[cmp_shp]\n\n                Curl = create_curl(isfwdcmp, \u2206l\u207b\u00b9cmp, isblochcmp, e\u207b\u2071\u1d4f\u1d38cmp;\n                                   cmp_shp, cmp_out, cmp_in, order_cmpfirst=false)\n\n                \u2202_blks = [[(nw = nw_blk[nv,nu];\n                            if iszero(nw)\n                                \u2202_blk = Z\n                            else\n                                sn = sign(nw)\n                                nw = abs(nw)\n                                ind_nw = findfirst(cmp_shp.==nw)\n                                \u2202_blk = sn * create_\u2202(ind_nw, isfwd[nw], [Ncmp...], \u2206l\u207b\u00b9[nw], isbloch[nw], e\u207b\u2071\u1d4f\u1d38[nw])\n                            end;\n                            \u2202_blk) for nu = cmp_in] for nv = cmp_out]\n\n                Curl_blk = cat(((row_blks->cat(row_blks..., dims=2)).(\u2202_blks))..., dims=1)\n\n                @test Curl == Curl_blk\n\n                Fcmp = rand(ComplexF64, Ncmp..., length(cmp_in))\n                Gcmp = similar(Fcmp, Ncmp..., length(cmp_out))\n                gcmp = zeros(ComplexF64, length(Gcmp))\n\n                fcmp = Fcmp[:]\n                mul!(gcmp, Curl, fcmp)\n                apply_curl!(Gcmp, Fcmp, Val(:(=)), isfwdcmp, \u2206l\u207b\u00b9cmp, isblochcmp, e\u207b\u2071\u1d4f\u1d38cmp;\n                            cmp_shp, cmp_out, cmp_in)\n                @test Gcmp[:] \u2248 gcmp\n            end\n        end\n    end\nend  # @testset \"create_curl and apply_curl!\"\n\n@testset \"curl of curl\" begin\n    # Construct Cu and Cv for a uniform grid and Bloch boundaries.\n    \u2206ldual\u207b\u00b9 = ones.(N)  # inverse of \u2206l evaluated at dual locations\n    \u2206lprim\u207b\u00b9 = ones.(N)  # inverse of \u2206l evaluated at primal locations\n    isbloch = [true, false, false]\n    e\u207b\u2071\u1d4f\u1d38 = ones(3)\n\n    Cu = create_curl([true,true,true], \u2206ldual\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n    Cv = create_curl([false,false,false], \u2206lprim\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n\n    # Test symmetry of each block.\n    for i = 1:3\n        for j = mod1.(i .+ [1,2], 3)\n            -Cv[(i-1)*M+1:i*M,(j-1)*M+1:j*M]' == Cu[(i-1)*M+1:i*M,(j-1)*M+1:j*M]\n        end\n    end\n\n    # Construct Cv * Cu.\n    isbloch = fill(true, 3)\n    Cu = create_curl([true,true,true], \u2206ldual\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n    Cv = create_curl([false,false,false], \u2206lprim\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n    A = Cv * Cu\n\n    # Test curl of curl.\n    @test all(diag(A) .== 4)  # all diagonal entries are 4\n    @test all(sum(A.\u22600, dims=2) .== 13)  # 13 nonzero entries per row\n    @test A == A'  # Hermitian\n\n    B = A - 4I\n    @test all(abs.(B[B.\u22600]).==1)  # all nonzero off-diagonal entries are \u00b11\nend  # @testset \"curl of curl\"\n\n@testset \"curl of curl, mixed forward and backward\" begin\n    # Construct Cu and Cv for a uniform grid and Bloch boundaries.\n    \u2206ldual\u207b\u00b9 = ones.(N)\n    \u2206lprim\u207b\u00b9 = ones.(N)\n    isbloch = [true, false, false]\n    e\u207b\u2071\u1d4f\u1d38 = ones(3)\n\n    isfwd = [true,false,true]\n    Cu = create_curl(isfwd, \u2206ldual\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n    Cv = create_curl(.!isfwd, \u2206lprim\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n\n    # Test symmetry of each block.\n    for i = 1:3\n        for j = mod1.(i .+ [1,2], 3)\n            -Cv[(i-1)*M+1:i*M,(j-1)*M+1:j*M]' == Cu[(i-1)*M+1:i*M,(j-1)*M+1:j*M]\n        end\n    end\n\n    # Construct Cv * Cu.\n    isbloch = fill(true, 3)\n    Cu = create_curl(isfwd, \u2206ldual\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n    Cv = create_curl(.!isfwd, \u2206lprim\u207b\u00b9, isbloch, e\u207b\u2071\u1d4f\u1d38, order_cmpfirst=false)\n    A = Cv * Cu\n\n    # Test curl of curl.\n    @test all(diag(A) .== 4)  # all diagonal entries are 4\n    @test all(sum(A.\u22600, dims=2) .== 13)  # 13 nonzero entries per row\n    @test A == A'  # Hermitian\n\n    B = A - 4I\n    @test all(abs.(B[B.\u22600]).==1)  # all nonzero off-diagonal entries are \u00b11\nend  # @testset \"curl of curl, mixed forward and backward\"\n\nend  # @testset \"curl\"\n", "meta": {"hexsha": "a794e5177663fa88158727343303f0c88f7538a4", "size": 7069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/curl.jl", "max_stars_repo_name": "wsshin/StaggeredGridCalculus.jl", "max_stars_repo_head_hexsha": "c9530e1c3e7dc32d67642eb140e1bb58df8d3ca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-11-03T23:16:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:07:22.000Z", "max_issues_repo_path": "test/curl.jl", "max_issues_repo_name": "wsshin/StaggeredGridCalculus.jl", "max_issues_repo_head_hexsha": "c9530e1c3e7dc32d67642eb140e1bb58df8d3ca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-02T02:05:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T16:02:20.000Z", "max_forks_repo_path": "test/curl.jl", "max_forks_repo_name": "wsshin/StaggeredGridCalculus.jl", "max_forks_repo_head_hexsha": "c9530e1c3e7dc32d67642eb140e1bb58df8d3ca5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-01T20:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:07:27.000Z", "avg_line_length": 37.4021164021, "max_line_length": 117, "alphanum_fraction": 0.5068609421, "num_tokens": 2666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.769728947177573}}
{"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(\u03b1::Float64, rng::RNG) where RNG <: AbstractRNG\n  @assert \u03b1 > 0.0\n  if \u03b1 < 1.0\n    return rand(rng)^(1/\u03b1)*sampleGamma(1.0+\u03b1, rng)\n  end\n  d::Float64 = \u03b1 - 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(\u03b1::Float64, \u03b2::Float64,\n  rng::RNG = GLOBAL_RNG) where RNG <: AbstractRNG\n  return sampleGamma(\u03b1, rng) / \u03b2\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": "include(\"../functions/Functions.jl\")\ninclude(\"../evaluate/Evaluate.jl\")\ninclude(\"../opt/sgd.jl\")\ninclude(\"../data/data.jl\")\ninclude(\"../plot/Plotting.jl\")\n\nusing Plotting\n\nX, y = getOldData()\n\nx0 = zeros(size(X,2),1)\n\nlambda = 0.1\n\niter = 15000\nstep = 0.0001\n\n#f = f_logreg(X,y,x0,lambda)\n#g = sub_g_logreg()\n\nf = f_svm(X,y,x0,lambda)\ng = sub_g_svm()\n\n@time (theta,state,val_array,stop_array) = sgd(X,y,x0,f,g,1e-8,lambda,iter,step,size(X,1))\n\nplotArray(val_array, \"sgd1.svg\")\n\ngrad = g_logreg(X,y,theta,lambda)(theta)\ngrad_norm = norm(grad, Inf)\n@printf(\"Inf-Norm of gradient is %f.\\n\",grad_norm)\nprintln(evaluate(X,y,theta,\"svm\",false))\n", "meta": {"hexsha": "4dbc0a772bccedc2da3c0d9c56fc31bf58acd523", "size": 639, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test/sgd_test.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/test/sgd_test.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/test/sgd_test.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": 19.96875, "max_line_length": 90, "alphanum_fraction": 0.6791862285, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7696869991463687}}
{"text": "function nlp_cvx_203_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - linear objective\n    # - intersection convex quadratic constraints\n    # - sqrt cone\n    # Variants\n    #   010 - intersection set\n\n    model = Model(optimizer)\n\n    @variable(model, x, start = 0.1)\n    @variable(model, y, start = 0.1)\n    @variable(model, z)\n\n    @objective(model, Min, x + y)\n    @NLconstraint(model, sqrt(x^2 + y^2) <= z - 0.25)\n    @NLconstraint(model, x^2 + y^2 <= -z + 1)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -1 / sqrt(2), tol = objective_tol)\n    return check_solution(\n        [x, y, z],\n        [-sqrt(1 / 8), -sqrt(1 / 8), 3 / 4],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "03ebec6b8319e2a171fbd51c5abaa839437ea278", "size": 894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/203_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/203_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/203_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 24.8333333333, "max_line_length": 76, "alphanum_fraction": 0.6163310962, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7696869969727077}}
{"text": "function nlp_cvx_001_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - linear objective\n    # - quadratic objective\n    # - linear constraints forming a closed set\n    # Variants\n    #   010 - binding constraints\n    #   011 - non-binding constraints\n\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y)\n\n    @objective(model, Min, x)\n    @constraint(model, x + y <= 5)\n    @constraint(model, 2 * x - y <= 3)\n    @constraint(model, 3 * x + 9 * y >= -10)\n    @constraint(model, 10 * x - y >= -20)\n    @constraint(model, -x + 2 * y <= 8)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, -2.0430107680954848, tol = objective_tol)\n    return check_solution(\n        [x, y],\n        [-2.0430107680954848, -0.4301075068564087],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "d95494ca231e3fdfe93fb9f32660d464d2641eca", "size": 1001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/001_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/001_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/001_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 25.6666666667, "max_line_length": 76, "alphanum_fraction": 0.6303696304, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7696869967020008}}
{"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# \u2554\u2550\u2561 f66e452c-97db-11eb-23fc-bd95da10e2d6\nusing Plots, FFTW, TestImages, PlutoUI, Images, ImageShow\n\n# \u2554\u2550\u2561 adaa78fa-d805-45e6-ba5f-d91a5d4823d6\nusing ImageContrastAdjustment\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u03b4(i,j)\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 899a3541-9cef-48de-a03d-367223fe3100\nmd\"\"\"### All 64 Basis Functions\"\"\"\n\n# \u2554\u2550\u2561 99028838-babb-4d29-a400-c321c65e455d\nmd\"\"\"### Code cells are hidden down here\"\"\"\n\n# \u2554\u2550\u2561 85859f7b-26e2-415e-87f1-b61180449a61\nimages = [i for i in TestImages.remotefiles if ! contains(i, \"tif\") && ! contains(i, \"256\") && ! contains(i, \"color\")] ;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c4d7b864-275a-4e6f-9cc1-74138a1f07ae\nfunction kd2(i,j)\n\timg = zeros((8,8))\n\timg[i,j] = 1\n\timg\nend ;\n\n# \u2554\u2550\u2561 4369ef1b-4291-4b2f-8bc1-ac011080bb18\nbimg = kd2(i,j) ;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6c43a6ef-41af-4343-910b-04e72fdc87fd\nalg = Equalization(nbins = 256);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 12fb095f-02a6-48c6-856a-afbc71a6ad64\nfimg = filter_img(kimg, kp) ;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250009fc6764-2050-4276-8a14-3596368d0c32\n# \u255f\u250048412713-7266-43dc-a49e-bab349318cce\n# \u255f\u25000d142947-1e3c-4adc-b6ca-09c502f89f0e\n# \u255f\u2500e50c3024-140d-4312-ad8e-66b94482964b\n# \u255f\u2500f90425a3-8e6f-440a-8522-5ccd5cca2797\n# \u255f\u2500740ecf61-15d7-4b30-8ef8-e9ed339912af\n# \u255f\u2500899a3541-9cef-48de-a03d-367223fe3100\n# \u255f\u25002b98ae25-097e-4dd5-aa4b-01a3b06c2fc8\n# \u255f\u250099028838-babb-4d29-a400-c321c65e455d\n# \u255f\u250085859f7b-26e2-415e-87f1-b61180449a61\n# \u255f\u250012fb095f-02a6-48c6-856a-afbc71a6ad64\n# \u255f\u2500f66e452c-97db-11eb-23fc-bd95da10e2d6\n# \u255f\u25004369ef1b-4291-4b2f-8bc1-ac011080bb18\n# \u255f\u2500c4d7b864-275a-4e6f-9cc1-74138a1f07ae\n# \u255f\u2500adaa78fa-d805-45e6-ba5f-d91a5d4823d6\n# \u255f\u25006c43a6ef-41af-4343-910b-04e72fdc87fd\n# \u255f\u2500628877b2-6e8d-47a1-8dce-752b9d75ab56\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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 (\u2211wx + b)\n    of the neurons to \u211d. 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": "module VerticesTests\n\nusing Contour, Test\nusing Base.MathConstants: \u03c0, \u03c6\nusing LinearAlgebra: Diagonal\nusing OffsetArrays\nusing StaticArrays\n\n# Setup test axes that will be shared among the tests\n\n# Shift the axes so that they do not line up with\n# integer values\n\u0394 = 0.01\nX = collect(0:\u0394:4) .+ \u03c0\nY = collect(0:\u0394:3) .+ \u03c6\n\n# TEST CASE 1\n#\n# f(x,y) = x^2 + y^2\n#\nZ = [(x^2 + y^2)::Float64 for x in X, y in Y]\nh = rand() * (maximum(Z) - minimum(Z)) + minimum(Z)\n\ncontourlevels = Contour.contour(X, Y, Z, h)\nfor line in contourlevels.lines\n    # Contour vertices lie on a circle around the origin\n    for v in line.vertices\n        @test isapprox(v[1]^2 + v[2]^2, h, atol=0.1\u0394)\n    end\n\n    # coordinates() returns the correct values\n    xs, ys = coordinates(line)\n    xs .== [v[1] for v in line.vertices]\n    ys .== [v[2] for v in line.vertices]\nend\n\n# TEST CASE 1.5\n#\n# Same as test case 1, but with a shifted center\n#\nh = 1\nx0, y0 = (.5, -1.5)\nZ = Float64[(x - x0)^2 + (y - y0)^2 for x in X, y in Y]\n\ncontourlevels = Contour.contour(X, Y, Z, h)\nfor line in contourlevels.lines\n    for v in line.vertices\n        @test isapprox((v[1] - x0)^2 + (v[2] - y0)^2, h, atol=0.01\u0394)\n    end\nend\n\n# TEST CASE 2\n#\n# Check that ambigious cells (5, 10) are handled correctly\n# Case 5: z_center > h\nX = [1.0, 2.0]\nY = [2.0, 1.0]\n\nZ = float([1 0;\n           0 1])\nh = 0.1\n\nlines = Contour.contour(X, Y, Z, h).lines\n@test length(lines) == 2\n\nfor line in lines\n    @test length(line.vertices) == 2\n    d = line.vertices[2] - line.vertices[1]\n    @test d[2] / d[1] \u2248 -1.0\nend\n\n# Case 5: z_center < h\nZ = float([1 0;\n           0 1])\nh = 0.9\n\nlines = Contour.contour(X, Y, Z, h).lines\n\n@test length(lines) == 2\n\nfor line in lines\n    @test length(line.vertices) == 2\n    d = line.vertices[2] - line.vertices[1]\n    @test d[2] / d[1] \u2248 1.0\nend\n\n# Case 10: z_center > h\nZ = float([0 1;\n           1 0])\nh = 0.1\n\nlines = Contour.contour(X, Y, Z, h).lines\n@test length(lines) == 2\n\nfor line in lines\n    @test length(line.vertices) == 2\n    d = line.vertices[2] - line.vertices[1]\n    @test d[2] / d[1] \u2248 1.0\nend\n\n# Case 10: z_center < h\n\nZ = float([0 1;\n           1 0])\nh = 0.9\n\nlines = Contour.contour(X, Y, Z, h).lines\n@test length(lines) == 2\n\nfor line in lines\n    @test length(line.vertices) == 2\n    d = line.vertices[2] - line.vertices[1]\n    @test d[2] / d[1] \u2248 -1.0\nend\n\n# Test curvilinear coordinates\n\u03b8 = range(0.0, stop=2\u03c0,length=100)\nR = range(1.0, stop=2.0, length=100)\n\u03b6 = ComplexF64[r*exp(im*\u03d5) for \u03d5 in \u03b8, r in R]\nx, y, z = real.(\u03b6), imag.(\u03b6), abs.(\u03b6)\n\nh = 1 + rand()\nxs, ys = coordinates(contour(x, y, z, h).lines[1])\n@test all(xs.^2 + ys.^2 .\u2248 h^2)\n\n\n# Test offset arrays\noffset_x, offset_y = -10, 27\nz = cumsum(cumsum(randn(20,20); dims=1); dims=2)\nzoff = OffsetArray(z, offset_x, offset_y)\n\nx, y = axes(z)\nxoff, yoff = axes(zoff)\ncurves = Contour.contour(x,y,z,0.5)\ncurves_off = Contour.contour(xoff, yoff, zoff, 0.5)\n\n# sort offset and non-offset curves to the same order\noffset = SVector(offset_x, offset_y)\nlns = sort(Contour.lines(curves); by=c->sum(sum.(c.vertices.+[offset])))\nlns_off = sort(Contour.lines(curves_off); by=c->sum(sum.(c.vertices)))\n\n# verify that each line matches a possibly circularly shifted or reversed\n# line from the offset array\nopencurve(a) = first(a) == last(a) ? a[1:end-1] : a\nfor (c1, c2) in zip(lns, lns_off)\n    o1 = opencurve(c1.vertices) .+ [offset]\n    o2 = opencurve(c2.vertices)\n    m = length(o1)\n    @test m == length(o2)\n    cshifts = [circshift(o2,i) for i=1:m]\n    @test any(o1 \u2248 c || o1 \u2248 reverse(c) for c in cshifts)\nend\n\n\n\n# Test Known Bugs\n\n# Issue #12\nx = float(collect(1:3));\ny = copy(x);\nz = Diagonal(ones(3));\ncontours(x, y, z)\n\n# Test handling of saddle points\n#\n# f(x,y) = x^2 - y^2\n#\n\u0394 = 0.01\nX = collect(-3:\u0394:3)\nY = collect(-3:\u0394:3)\n\nZ = [(x^2 - y^2)::Float64 for x in X, y in Y]\nh = rand() * (maximum(Z) - minimum(Z)) + minimum(Z)\n\ncontourlevels = Contour.contour(X, Y, Z, h)\nfor line in contourlevels.lines\n    # Contour vertices lie on a circle around the origin\n    for v in line.vertices\n        @test isapprox(v[1]^2 - v[2]^2, h, atol=0.1\u0394)\n    end\n\n    # coordinates() returns the correct values\n    xs, ys = coordinates(line)\n    xs .== [v[1] for v in line.vertices]\n    ys .== [v[2] for v in line.vertices]\nend\n\n\n# Test range API\n#\n# f(x,y) = x^2 - y^2\n#\n\u0394 = 0.01\nX = -3:\u0394:3\nY = -3:\u0394:3\n\nZ = [(x^2 - y^2)::Float64 for x in X, y in Y]\nh = rand() * (maximum(Z) - minimum(Z)) + minimum(Z)\n\ncontourlevels = Contour.contour(X, Y, Z, h)\nfor line in contourlevels.lines\n    # Contour vertices lie on a circle around the origin\n    for v in line.vertices\n        @test isapprox(v[1]^2 - v[2]^2, h, atol=0.1\u0394)\n    end\n\n    # coordinates() returns the correct values\n    xs, ys = coordinates(line)\n    xs .== [v[1] for v in line.vertices]\n    ys .== [v[2] for v in line.vertices]\nend\n\n# Test that closed contours are identified correctly\n# when ambiguous cells are involved\n\nZ = float([1 1 1 1 1 1\n           1 0 0 1 1 1\n           1 0 0 1 1 1\n           1 1 1 0 0 1\n           1 1 1 0 0 1\n           1 1 1 1 1 1])\n\nX = Y = collect(0:0.2:1)\nh = 0.75\ncontourlevels = Contour.contour(X, Y, Z, h)\n\n# There should be only one closed contour\n@test length(contourlevels.lines) == 1\n\n# Test contour location on a realistic dataset\ninclude(\"testdata.jl\")\ncts = Contour.contours(x, y, z)\n@test length(cts.contours) == 10\ncts_ct = (8, 8, 8, 8, 126, 7, 5, 5, 5, 4)\n\n# Length need to be sorted as hashing might change see #62\nlines_ct = sort!.([[138, 220, 469, 138, 469, 208, 143, 143],\n            [220, 475, 140, 210, 146, 475, 140, 146],\n            [222, 481, 140, 214, 481, 145, 140, 145],\n            [228, 485, 214, 142, 485, 142, 146, 146],\n            [9, 7, 515, 501, 9, 9, 9, 7, 7, 9, 7, 15, 7, 18, 39, 9, 7, 7, 9, 9, 7, 7, 7, 7, 9, 7, 18, 9, 7, 7, 9, 9, 35, 9, 9, 9, 7, 7, 9, 35, 9, 7, 9, 7, 9, 9, 7, 7, 7, 9, 7, 7, 7, 7, 9, 7, 9, 7, 9, 7, 7, 9, 9, 9, 7, 9, 7, 7, 9, 7, 7, 9, 7, 9, 7, 7, 7, 7, 7, 9, 7, 7, 7, 9, 7, 7, 7, 7, 9, 7, 7, 7, 7, 7, 7, 7, 9, 7, 9, 9, 7, 7, 7, 7, 7, 7, 9, 7, 7, 7, 7, 7, 7, 7, 9, 7, 9, 7, 7, 7, 7, 9, 7, 7, 7, 7],\n            [5, 17, 14, 34, 34, 14, 5],\n            [29, 12, 29, 15, 12],\n            [26, 10, 13, 26, 10],\n            [11, 11, 23, 11, 21],\n            [18, 19, 7, 7]])\nfor i in eachindex(cts_ct)\n    @test length(cts.contours[i].lines) == cts_ct[i]\n    @test all(lines_ct[i] .== sort!([length(c.vertices) for c in cts.contours[i].lines]))\nend\n\n\n# support non-float z\nusing StatsBase\n\nN = 10000\nx = randn(N)\ny = randn(N)\nH = fit(Histogram, (x, y), closed = :left)\ncontours(midpoints.(H.edges)..., H.weights)\n\nend\n", "meta": {"hexsha": "b771069df36851c79047ce352297f99a6a4a973a", "size": 6605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/verify_vertices.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": "test/verify_vertices.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": "test/verify_vertices.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": 25.1140684411, "max_line_length": 401, "alphanum_fraction": 0.5839515519, "num_tokens": 2743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7696201854312464}}
{"text": "function e003(N)\n    return largest_factor(N)\nend\n\nfunction largest_factor(N::Integer)\n    if N < 2\n        return 1\n    else\n        f::Integer = 2\n        while f <= sqrt(N)\n            while N % f == 0\n                N \u00f7= f\n                if N == 1\n                    return f\n                end\n            end\n            f += 1\n        end\n        return N\n    end\nend\n \nfunction solution003()\n    N = 600851475143\n    answer = e003(N)\n    println(\"The answer to problem 003 is $answer\")\nend\n\n", "meta": {"hexsha": "bf3cb6e6ba24f850cf5765810efc72dcc1099535", "size": 503, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/003.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/003.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/003.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": 17.3448275862, "max_line_length": 51, "alphanum_fraction": 0.4552683897, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7695940913355217}}
{"text": "# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file\n# containing over five-thousand first names, begin by sorting it into\n# alphabetical order. Then working out the alphabetical value for each name,\n# multiply this value by its alphabetical position in the list to obtain a name\n# score.\n#\n# For example, when the list is sorted into alphabetical order, COLIN, which is\n# worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN\n# would obtain a score of 938 \u00d7 53 = 49714.\n#\n# What is the total of all the name scores in the file?\n\nusing ProjectEulerSolutions\n\n# Use sort then map and collect to order names then convert to char array then\n# difference from the char 'A'.\nfunction p022_solution(path::String=\"\")::Integer\n    all_names = Vector{String}()\n    if isfile(path)\n        open(path) do file\n            for row in eachline(file)\n                rownames = split(row, \",\")\n                append!(all_names, [n[2:end-1] for n in rownames]) # Remove quotes\n            end\n        end\n    end\n    sort!(all_names)\n\n    return sum(map(x->sum(collect(x[2]).-'A'.+1)*x[1], enumerate(all_names)))\nend\n\np022 = Problems.Problem(p022_solution)\n\ninput_path = \"../data/p022_names.txt\"\n\nProblems.benchmark(p022, input_path)", "meta": {"hexsha": "90eefe64b8539b27b9e1457c34d0be909dba31bb", "size": 1264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/022.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/022.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/022.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": 35.1111111111, "max_line_length": 82, "alphanum_fraction": 0.6787974684, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7695940893738182}}
{"text": "spectral_resolutions = (31,42,85,170,341)\n\n@testset \"FFT of geopotential\" begin\n\n    # Test for variable resolution\n    for trunc in spectral_resolutions\n    \n        P = Parameters(NF=Float64;trunc=trunc)\n        G = GeoSpectral(P)\n        B = Boundaries(P,G)\n\n        geopot_surf_spectral = B.geopot_surf\n        geopot_surf_grid = gridded(geopot_surf_spectral,G)\n\n        @test all(geopot_surf_grid .\u2248 fourier_inverse(fourier(geopot_surf_grid,G),G))\n    end\nend\n\n@testset \"Legendre transform of geopotential\" begin\n\n    # Test for variable resolution\n    for trunc in spectral_resolutions\n    \n        P = Parameters(NF=Float64;trunc=trunc)\n        G = GeoSpectral(P)\n        B = Boundaries(P,G)\n\n        geopot_surf_spectral = B.geopot_surf\n        geopot_surf_grid = gridded(geopot_surf_spectral,G)\n\n        # using the already spectrally truncated geopotential\n        # geopot_surf_grid2 = gridded(spectral(geopot_surf_grid,G),G)\n\n        @test geopot_surf_grid \u2248 gridded(spectral(geopot_surf_grid,G),G)\n\n\n    end\nend\n\n@testset \"Spectral transform of spectral noise\" begin\n    \n    # Test for variable resolution\n    for trunc in spectral_resolutions\n    \n        P = Parameters(NF=Float64;trunc=trunc)\n        G = GeoSpectral(P)\n\n        mx = G.spectral.mx\n        nx = G.spectral.nx\n\n        A = rand(mx,nx) + im*rand(mx,nx)\n        At = spectral(gridded(A,G),G)   # the first transform includes truncation\n\n        # the next should be exact to machine precision\n        At2 = spectral(gridded(At,G),G)\n        At3 = spectral(gridded(At2,G),G)\n        @test all(At .\u2248 At2)\n        @test all(At2 .\u2248 At3)\n    end\nend", "meta": {"hexsha": "4503389d2911689c0e24c9df320a4fa857abbb58", "size": 1624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/spectral_transform.jl", "max_stars_repo_name": "samhatfield/SpeedyWeather.jl", "max_stars_repo_head_hexsha": "b97ab983391bdfb6a41dd4f5a911ee7400a3d56a", "max_stars_repo_licenses": ["MIT"], "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/spectral_transform.jl", "max_issues_repo_name": "samhatfield/SpeedyWeather.jl", "max_issues_repo_head_hexsha": "b97ab983391bdfb6a41dd4f5a911ee7400a3d56a", "max_issues_repo_licenses": ["MIT"], "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/spectral_transform.jl", "max_forks_repo_name": "samhatfield/SpeedyWeather.jl", "max_forks_repo_head_hexsha": "b97ab983391bdfb6a41dd4f5a911ee7400a3d56a", "max_forks_repo_licenses": ["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.0666666667, "max_line_length": 85, "alphanum_fraction": 0.6514778325, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7695940860898315}}
{"text": "function square_of_sum(n)\n    # https://docs.julialang.org/en/v1/manual/control-flow/#man-conditional-evaluation\n    # https://docs.julialang.org/en/v1/base/collections/#Base.collect-Tuple{Any}\n    # https://www.simonwenkel.com/2019/02/03/project-euler-problem-0006.html\n    return n > 1 ? sum(1:n)^2 : n\nend\n\nfunction sum_of_squares(n)\n    # https://docs.julialang.org/en/v1/base/collections/#Base.mapreduce-Tuple{Any,%20Any,%20Any}\n    # https://github.com/programacaodinamica/exercism-julia/blob/main/difference-of-squares/difference-of-squares.jl\n    return n > 1 ? mapreduce(x -> x^2, +, 1:n) : n\nend\n\nfunction difference(n)\n    return square_of_sum(n) - sum_of_squares(n)\nend\n", "meta": {"hexsha": "05cc40684efa3a499bee96b8600f6966239f2df4", "size": 682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercism/difference-of-squares.jl", "max_stars_repo_name": "joaopalmeiro/learning-julia", "max_stars_repo_head_hexsha": "12fc7abb712ad94fe1dbf8f02af8a383bfb65750", "max_stars_repo_licenses": ["MIT"], "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/difference-of-squares.jl", "max_issues_repo_name": "joaopalmeiro/learning-julia", "max_issues_repo_head_hexsha": "12fc7abb712ad94fe1dbf8f02af8a383bfb65750", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-07T00:39:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T08:46:14.000Z", "max_forks_repo_path": "exercism/difference-of-squares.jl", "max_forks_repo_name": "joaopalmeiro/learning-julia", "max_forks_repo_head_hexsha": "12fc7abb712ad94fe1dbf8f02af8a383bfb65750", "max_forks_repo_licenses": ["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.1176470588, "max_line_length": 116, "alphanum_fraction": 0.7228739003, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7695940838084181}}
{"text": "using Test\nusing UnPack\nusing MOONS.Grids\nusing MOONS.Fields\nusing MOONS.FFTs\n\n@testset \"FFTs\" begin\n\n    # Solve \u2207\u00b2 u = f\n    # where f = -2*(3*\u03c0)^2*cos(3*\u03c0*x)*cos(3*\u03c0*y)\n    #       u = cos(3*\u03c0*x)*cos(3*\u03c0*y))\n\n    FT = Float64\n    n = 128\n    cx = Coordinates(FT(0),FT(1),n)\n    cy = Coordinates(FT(0),FT(1),n)\n    cz = Coordinates(FT(0),FT(1),2)\n    g = Grid((cx,cy,cz))\n\n    f_exact = CellCenter(g)\n    u_exact = CellCenter(g)\n    f = CellCenter(g)\n    u = CellCenter(g)\n    u_err = CellCenter(g)\n\n    @inbounds for local_grid in GridField(g,f_exact)\n        @unpack ijk,x,y = local_grid\n        u_exact[ijk] = cos(3*\u03c0*x)*cos(3*\u03c0*y)\n        f_exact[ijk] = -2*(3*\u03c0)^2*cos(3*\u03c0*x)*cos(3*\u03c0*y)\n    end\n\n    \u2207\u00b2!(f, u_exact, g)\n    extrap!(f, g)\n    solve!(u, f_exact, g, 3)\n\n    @test max(average(u, 3)...) \u2248 1.0003012584260522\n    @test max(abs.(diff(u; dims=3))...) \u2248 0\n\n    u_err .= abs.(u_exact - u);\n    assign!(u_err, 0, Ghost())\n    @test max(u_err...) \u2248 0.0004518490779501505\nend\n", "meta": {"hexsha": "bf2bee258972b3df6fe28939c822a20c89f32a32", "size": 986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FFTs/runtests.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": "test/FFTs/runtests.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": "test/FFTs/runtests.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.9302325581, "max_line_length": 55, "alphanum_fraction": 0.5588235294, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7695940818032698}}
{"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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    infection = \u03b2*c*I/N*S\n    recovery = \u03b3*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]; # \u03b2,c,\u03b3\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\u2080  ~ Uniform(0.0,1.0)\n  \u03b2 ~ Uniform(0.0,1.0)\n  I = i\u2080*1000.0\n  u0=[1000.0-I,I,0.0,0.0]\n  p=[\u03b2,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[!,:\u03b2],posterior[!,:i\u2080],\n                bins=80,\n                xlabel=\"\u03b2\",\n                ylab=\"i\u2080\",\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\u2080 = chain[:i\u2080][idx]\n    \u03b2 = chain[:\u03b2][idx]\n    I = i\u2080*1000.0\n    u0=[1000.0-I,I,0.0,0.0]\n    p=[\u03b2,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 `\u03b1` based on the chosen estimation method. The VaR value represents the maximum expected loss at a certain significance level `\u03b1`. For a more tail-risk focused measure, see `expected_shortfall`.\n\n# Arguments\n- `returns`:     Vector of asset returns.\n- `\u03b1`:           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\u00e9d\u00e9e-Manesme, Charles-Olivier and Barth\u00e9l\u00e9my, Fabrice and Maillard, Didier (2017). Computation of the Corrected Cornish\u2013Fisher Expansion using the Response Surface Methodology: Application to VaR and CVaR. THEMA Working Paper n\u00b02017-21, Universit\u00e9 de Cergy-Pontoise, France.\n\"\"\"\nfunction value_at_risk(returns, \u03b1, method::Symbol; multiplier=1.0)\n    if method == :historical\n        # empirical quantile for VaR estimation\n        return quantile(returns, \u03b1) * sqrt(multiplier)\n    elseif method == :gaussian\n        # parametric Gaussian distribution fit\n        \u03bc = mean(returns)\n        \u03c3 = std(returns; corrected=false)\n        return quantile(Normal(\u03bc, \u03c3), \u03b1)\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(), \u03b1)\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        \u03bc = mean(returns)\n        \u03c3 = std(returns; corrected=false)\n        return (\u03bc + z*\u03c3) * 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": "include(\"euler/euler.jl\")\nusing .Numbers: count_divisors\nusing BenchmarkTools\nBenchmarkTools.DEFAULT_PARAMETERS.samples = 100\n\nfunction compute(n::Int)::Int\n    i, triangle = 1, 1\n    while count_divisors(triangle) < n\n        i += 1\n        triangle += i\n    end\n    return triangle\nend\n\ncompute(5)\n\ncompute(500)\n\n@benchmark compute(500)", "meta": {"hexsha": "bf57c12b1bf6760f04af55462554bfc7aff73ccb", "size": 338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/0012/solution.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/0012/solution.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/0012/solution.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": 17.7894736842, "max_line_length": 47, "alphanum_fraction": 0.6952662722, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7695781651549571}}
{"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\u2019s 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\u2014less than seven\u2014and 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\u2019 estimator that works better with non-normal datasets.\n        g\u2081 = moment(data, 3)\n        \u03c3 = sqrt((6*(n-2))/((n+1)*(n+3)))\n        nbins = ceil(Int, 1 + log(2,n) + log(2, 1+abs(g\u2081)/\u03c3))\n    elseif alg == :scott\n        # Less robust estimator that that takes into account data variability and data size.\n        \u03c3 = std(data)\n        binwidth = 3.5\u03c3/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 \u2018sturges\u2019 and \u2018fd\u2019 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::\u211d\u00b3) = 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)\ud835\udf3a\")\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\u0302 = normalize(q)\n    Biquaternion(q\u0302.real, q\u0302.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), \u211d\u00b3(0, 0, 0))\n\n\n\"\"\"\n    Biquaternion(translation)\n\nConstruct a Biquaternion with the given \u211d\u00b3 `translation`.\n\"\"\"\nBiquaternion(translation::\u211d\u00b3) = Biquaternion(Quaternion(1, 0, 0, 0), translation)\n\n\nvec(q::Biquaternion) = [vec(q.real); vec(q.dual)]\n\n\n+(q\u2081::Biquaternion, q\u2082::Biquaternion) = Biquaternion(q\u2081.real + q\u2082.real, q\u2081.dual + q\u2082.dual)\n-(q\u2081::Biquaternion, q\u2082::Biquaternion) = Biquaternion(q\u2081.real - q\u2082.real, q\u2081.dual - q\u2082.dual)\n*(q\u2081::Biquaternion, q\u2082::Biquaternion) = Biquaternion(q\u2081.real * q\u2082.real,\n                                                     q\u2081.real * q\u2082.dual + q\u2081.dual * q\u2082.real)\n*(q::Biquaternion, \u03bb::Real) = Biquaternion(\u03bb * q.real, \u03bb * q.dual)\n*(\u03bb::Real, q::Biquaternion) = q * \u03bb\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) = \u211d\u00b3(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": "\n\"\"\"\n    half_saturation(max, half, x)\nHalf satration curve.\n\"\"\"\nhalf_saturation(max, half, x) = max/(oneunit(half/x) + half/x)\n", "meta": {"hexsha": "09b8ad56b2cf12f1fc472b5cd7b600f554b2a0d2", "size": 128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "JuliaTagBot/DynamicEnergyBudgets.jl", "max_stars_repo_head_hexsha": "a2f26aa50d20df6309d155182ef4f2007fddf81d", "max_stars_repo_licenses": ["MIT"], "max_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": "JuliaTagBot/DynamicEnergyBudgets.jl", "max_issues_repo_head_hexsha": "a2f26aa50d20df6309d155182ef4f2007fddf81d", "max_issues_repo_licenses": ["MIT"], "max_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": "JuliaTagBot/DynamicEnergyBudgets.jl", "max_forks_repo_head_hexsha": "a2f26aa50d20df6309d155182ef4f2007fddf81d", "max_forks_repo_licenses": ["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.2857142857, "max_line_length": 62, "alphanum_fraction": 0.65625, "num_tokens": 40, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7695781615470673}}
{"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": "using DiscreteMarkovChains\nusing Test\nusing LinearAlgebra\n\n@testset \"Converting To Discrete\" begin\n    # Empty test\n    T = [][:,:]\n    X = ContinuousMarkovChain(T)\n    @test DiscreteMarkovChain(X) == DiscreteMarkovChain(T)\n\n    state_space = [1, 2, 3]\n    T = [\n        0 1 0;\n        1 0 0;\n        0 0 1;\n    ] - I\n    X = ContinuousMarkovChain(state_space, T)\n\n    T1 = transition_matrix(DiscreteMarkovChain(X))\n    T2 = transition_matrix(DiscreteMarkovChain(state_space, exp(T)))\n    @test T1 == T2\nend\n\n@testset \"Converting To Continuous\" begin\n    # Empty test\n    T = [][:,:]\n    X = DiscreteMarkovChain(T)\n    @test ContinuousMarkovChain(X) == ContinuousMarkovChain(T)\n\n    state_space = [1, 2, 3]\n    T = [\n        0.2 0.8 0;\n        0 0.2 0.8;\n        0 0 1;\n    ]\n    X = DiscreteMarkovChain(state_space, T)\n\n    Q1 = transition_matrix(ContinuousMarkovChain(X))\n    Q2 = transition_matrix(ContinuousMarkovChain(state_space, log(T)))\n    @test Q1 == Q2\nend\n\n@testset \"Embedded Chains\" begin\n    # Empty test\n    T = [][:,:]\n    X = ContinuousMarkovChain(T)\n    @test embedded(X) == DiscreteMarkovChain(T)\n\n    X = DiscreteMarkovChain(T)\n    @test embedded(X) == X\n\n    T = [\n        -2 1 1;\n        1 -1 0;\n        2 3 -5;\n    ]\n    X = ContinuousMarkovChain(T)\n    desired_new_matrix = [\n        0 0.5 0.5;\n        1 0 0;\n        0.4 0.6 0;\n    ]\n    @test transition_matrix(embedded(X)) \u2248 desired_new_matrix\nend\n\n@testset \"Communication Classes\" begin\n    # Empty test\n    T = [][:,:]\n    X = ContinuousMarkovChain(T)\n    @test communication_classes(X) == ([], [])\n\n    state_space = [1, 2, 3]\n    T = [\n        0 1 0;\n        1 0 0;\n        0 0 1;\n    ] - I\n    X = ContinuousMarkovChain(state_space, T)\n    @test communication_classes(X) == ([[1, 2], [3]], [true, true])\n\n    T = [\n        0 5 5 0 0;\n        0 0 0 10 0;\n        5 0 5 0 0;\n        0 10 0 0 0;\n        0 3 0 3 4;\n    ]/10 - I\n    X = ContinuousMarkovChain(0:4, T)\n    classes, recurrence = communication_classes(X)\n    @test classes == [[1, 3], [0, 2], [4]]\n    @test recurrence == [true, false, false]\n\n    T = [\n        0 0 0 10 0 0;\n        5 0 5 0 0 0;\n        0 4 0 0 0 6;\n        10 0 0 0 0 0;\n        0 10 0 0 0 0;\n        0 0 0 5 5 0;\n    ]/10 - I\n    X = ContinuousMarkovChain(0:5, T)\n    classes, recurrence = communication_classes(X)\n    @test classes == [[0, 3], [1, 2, 5, 4]]\n    @test recurrence == [true, false]\n\n    T = [\n        2 0 0 3 0 0 3 2 0 0;\n        0 10 0 0 0 0 0 0 0 0;\n        0 2 2 0 0 0 0 0 3 3;\n        0 0 0 3 0 0 6 1 0 0;\n        0 0 0 0 5 5 0 0 0 0;\n        0 0 0 0 0 10 0 0 0 0;\n        4 0 0 5 0 0 1 0 0 0;\n        2 0 0 4 0 0 2 2 0 0;\n        3 0 1 0 0 0 0 0 4 2;\n        0 0 4 0 0 0 0 0 3 3;\n    ]/10 - I\n    X = ContinuousMarkovChain(0:9, T)\n    classes, recurrence = communication_classes(X)\n    @test classes == [[0, 3, 6, 7], [1], [2, 8, 9], [5], [4]]\n    @test recurrence == [true, true, false, true, false]\nend\n\n@testset \"Decompose and Canonical Form\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test decompose(X) == ([], T, T, T)\n\n    T = [\n        1 0 0;\n        1//3 1//3 1//3;\n        0 1//4 3//4;\n    ] - I\n    X = ContinuousMarkovChain([\"Sunny\", \"Cloudy\", \"Rainy\"], T)\n    @test decompose(X) == (\n        [\"Sunny\", \"Cloudy\", \"Rainy\"],\n        T[1:1, 1:1], T[2:3, 1:1], T[2:3, 2:3],\n    )\n    @test canonical_form(X) == ([\"Sunny\", \"Cloudy\", \"Rainy\"], T)\n\n    T = [\n        1//4 3//4 0;\n        1//3 1//3 1//3;\n        0 1//4 3//4;\n    ] - I\n    X = ContinuousMarkovChain([1, 2, 3], T)\n    @test decompose(X) == ([1, 2, 3], T, Array{Any}(undef, 0, 3), Array{Any}(undef, 0, 0))\n    @test canonical_form(X) == ([1, 2, 3], T)\n\n    T = [\n        1 0 0 0 0;\n        1//2 0 1//2 0 0;\n        0 1//2 0 1//2 0;\n        0 0 1//2 0 1//2;\n        0 0 0 0 1;\n    ] - I\n    X = ContinuousMarkovChain(0:4, T)\n    states, A, B, C = decompose(X)\n    @test states == [0, 4, 1, 2, 3]\n    @test A == [1 0; 0 1] - I\n    @test B == [1//2 0; 0 0; 0 1//2]\n    @test C == [0 1//2 0; 1//2 0 1//2; 0 1//2 0] - I\n    states, new_matrix = canonical_form(X)\n    @test states == [0, 4, 1, 2, 3]\n    desired_new_matrix = [\n        1 0 0 0 0;\n        0 1 0 0 0;\n        1//2 0 0 1//2 0;\n        0 0 1//2 0 1//2;\n        0 1//2 0 1//2 0;\n    ] - I\n    @test new_matrix == desired_new_matrix\nend\n\n@testset \"Regular, Ergodic, Absorbing\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test !is_ergodic(X)\n    @test !is_absorbing(X)\n\n    T = [\n        0 4 0 0 0;\n        1 0 3 0 0;\n        0 2 0 2 0;\n        0 0 3 0 1;\n        0 0 0 4 0;\n    ]/4.0 - I\n    X = ContinuousMarkovChain(1:5, T)\n    @test is_ergodic(X)\n    @test !is_absorbing(X)\n\n    T = [\n        0 1;\n        1 0;\n    ] - I\n    X = ContinuousMarkovChain(1:2, T)\n    @test is_ergodic(X)\n    @test !is_absorbing(X)\n\n    T = [\n        2 1 1;\n        2 0 2;\n        1 1 2;\n    ]/4 - I\n    X = ContinuousMarkovChain(1:3, T)\n    @test is_ergodic(X)\n    @test !is_absorbing(X)\n\n    T = [\n        1 1;\n        1 1;\n    ]/2 - I\n    X = ContinuousMarkovChain(1:2, T)\n    @test is_ergodic(X)\n    @test !is_absorbing(X)\nend\n\n@testset \"Reversible\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = DiscreteMarkovChain(T)\n    @test is_reversible(X)\n    X = ContinuousMarkovChain(T)\n    @test is_reversible(X)\n\n    T = [\n        .425 .000 .075 .500;\n        .000 .550 .250 .200;\n        .300 .250 .450 .000;\n        .500 .050 .000 .450;\n    ]\n    X = DiscreteMarkovChain(T)\n    @test is_reversible(X)\n    X = ContinuousMarkovChain(T-I)\n    @test is_reversible(X)\n\n    T = [\n        0.5 0.5 0.0;\n        0.0 0.2 0.8;\n        0.3 0.3 0.4;\n    ]\n    X = DiscreteMarkovChain(T)\n    @test !is_reversible(X)\n    X = ContinuousMarkovChain(T-I)\n    @test !is_reversible(X)\nend\n\n@testset \"Stationary distribution\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test stationary_distribution(X) == Any[]\n\n    T = [-2 2 0; 0 -4 4; 0 0 0]\n    X = ContinuousMarkovChain(T)\n    @test stationary_distribution(X) == [0, 0, 1]\n\n    T = [\n        -25 20 5;\n        300 -500 200;\n        20 400 -420;\n    ]//1000\n    X = ContinuousMarkovChain(T)\n    @test stationary_distribution(X) == [100//113, 8//113, 5//113]\nend\n\n@testset \"Fundamental Matrix\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test fundamental_matrix(X) == Array{Any}(undef, 0, 0)\n\n    # http://www.mat.ufrgs.br/~giacomo/Softwares/R/Dobrow%20-%20Stochastic%20with%20R/ch7.pdf\n    # Example 7.16\n    T = [\n        0 0 0;\n        1 -1 0;\n        1 1 -2;\n    ]\n    X = ContinuousMarkovChain(T)\n    desired_new_matrix = [\n        1 0;\n        1/2 1/2;\n    ]\n    @test fundamental_matrix(X) == desired_new_matrix\nend\n\n@testset \"Expected Time To Absorption\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test mean_time_to_absorption(X) == Any[]\n\n    T = [\n        0 0 0;\n        4 -4 0;\n        0 2 -2;\n    ]\n    X = ContinuousMarkovChain(T)\n    @test mean_time_to_absorption(X) == [0.25, 0.75]\nend\n\n@testset \"Exit Probability\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test exit_probabilities(X) == Array{Any}(undef, 0, 0)\n\n    T = [\n        0 0 0;\n        0 -1 1;\n        2 2 -4;\n    ]\n    X = ContinuousMarkovChain(T)\n    @test exit_probabilities(X) == [1; 1][:, :]\n\n    T = [\n        0 0 0;\n        0 0 0;\n        8 8 -16;\n    ]\n    X = ContinuousMarkovChain(T)\n    @test exit_probabilities(X) == [0.5 0.5]\nend\n\n@testset \"Mean Recurrence Time\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test mean_recurrence_time(X) == Any[]\n\n    T = [\n        -1 1 0;\n        0 -1 1;\n        1 0 -1;\n    ]\n    X = ContinuousMarkovChain(T)\n    @test mean_recurrence_time(X) == [3, 3, 3]\n\n    T = [\n        -1 1 0;\n        0 -1 1;\n        2 2 -4;\n    ]\n    X = ContinuousMarkovChain(T)\n    @test mean_recurrence_time(X) == [3.5, 1.75, 1.75]\nend\n\n@testset \"Mean First Passage Time\" begin\n    # Empty test\n    T = Array{Any}(undef, 0, 0)\n    X = ContinuousMarkovChain([], T)\n    @test mean_first_passage_time(X) == Array{Any}(undef, 0, 0)\n\n    T = [\n        -1 1 0;\n        0 -1 1;\n        1 0 -1;\n    ]\n    X = ContinuousMarkovChain(T)\n    @test mean_first_passage_time(X) == [\n        0.0 1.0 2.0;\n        2.0 0.0 1.0;\n        1.0 2.0 0.0;\n    ]\n\n    T = [\n        -1 1 0;\n        0 -1 1;\n        2 2 -4;\n    ]\n    X = ContinuousMarkovChain(T)\n    @test mean_first_passage_time(X) == [\n        0.0 1.0 2.0;\n        2.5 0.0 1.0;\n        1.5 0.75 0.0;\n    ]\nend\n", "meta": {"hexsha": "f1412d15c65076f0796c31cc4289a4c7c9f6b101", "size": 8706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/CMC.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": "test/CMC.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": "test/CMC.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": 22.8503937008, "max_line_length": 93, "alphanum_fraction": 0.5093039283, "num_tokens": 3500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7695640327581204}}
{"text": "# This file includes modulation pulses \n\nexport RectangularPulse, RaisedCosinePulse, bandwidth\n\nabstract type AbstractPulse end \n\n\"\"\"\n    $TYPEDEF\n\nRectangularPulse pulse shape of the form,\n```math \n    p(t) = \n    \\\\begin{cases}\n    A & 0 \\\\leq t \\\\leq T \\\\\n    0 & othersie \\\\\n    \\\\end{cases}\n```\nwhere ``A`` is the amplitude and ``T`` is the pulse duration.\n\n# Fields \n    $TYPEDFIELDS\n\"\"\"\nstruct RectangularPulse <: AbstractPulse\n    \"Amplitude\"\n    amplitude::Float64 \n    \"Period\"\n    duration::Float64 \nend \nRectangularPulse() = RectangularPulse(1., 1.)\n\n(pulse::RectangularPulse)(t) = 0 \u2264 t \u2264 pulse.duration ? pulse.amplitude : zero(Float64)\n\n\"\"\"\n    $TYPEDEF\n\nRaised coise pulse shapse of the form, \n```math \n    p(t) = \n    \\\\begin{cases} \n    \\\\drac{A}{2}(1 - cos(w t) & 0 \\\\leq t \\\\leq T \\\\\n    0 & othersie \\\\\n    \\\\end{cases}\n```\n\n# Fields \n    $TYPEDFIELDS\n\"\"\"\nstruct RaisedCosinePulse <: AbstractPulse\n    amplitude::Float64 \n    duration::Float64 \nend \nRaisedCosinePulse() = RaisedCosinePulse(1., 1.)\n\n(pulse::RaisedCosinePulse)(t) = 0 \u2264 t \u2264 pulse.duration ? pulse.amplitude/2 * (1 - cos(2\u03c0/pulse.duration * t)) : zero(Float64)\n\n\"\"\"\n    $SIGNATURES\n\nReturns the energy of the pulse `pulse`\n\n# Example \n```julia \n\n```\n\"\"\"\nenergy(pulse::RectangularPulse) = (pulse.amplitude)^2 * pulse.duration\nenergy(pulse::RaisedCosinePulse) = (pulse.amplitude)^2 * 3 / 8\n\n\"\"\"\n    $SIGNATURES\n\nReturns the effetive bandwidth of the `pulse` in units of Hz.\n\"\"\"\nbandwidth(pulse::Union{RectangularPulse, RaisedCosinePulse}) = 1 / pulse.duration\n", "meta": {"hexsha": "cc89310914b3bbc18b73d48a840e416bbd98eb40", "size": 1543, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pulses.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": "src/pulses.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": "src/pulses.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.5733333333, "max_line_length": 125, "alphanum_fraction": 0.6532728451, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7695640270076793}}
{"text": "function normal_model(t :: Trace, data :: Vector{Float64})\n    loc = sample(t, :loc, Normal(0.0, 10.0))\n    scale = sample(t, :scale, LogNormal())\n    plate(t, observe, :obs, Normal(loc, scale), data)\nend\n\nfunction cat_model(t, dim, data)\n    probs = sample(t, \"probs\", Dirichlet(ones(dim)))\n    plate(t, observe, \"data\", Categorical(probs), data)\nend\n\n@testset \"aic 1\" begin\n    data = [1, 2, 1, 3, 4, 3, 3, 3, 4, 2]\n    dim = 4\n    results = mh(cat_model; params = (dim, data), burn=1000, thin=100, num_iterations=21000)\n    @time cat_aic = aic(results)\n    @info \"Computed AIC of cat model: $cat_aic\"\n    @info \"Cat model has $(numparams(results.traces[1])) parameters\"\nend\n\n@testset \"hpds 1\" begin\n    data = randn(10) .* 2.0 .+ 4.0\n    results = mh(normal_model; params = (data,), burn=1000, thin=100, num_iterations=21000)\n    @time intervals = hpdi(results, 0.95, [:loc, :scale])\n    @info \"HPDI: $intervals\"\n    normal_aic = aic(results)\n    @info \"Computed AIC of normal model: $normal_aic\"\n    @info \"Normal model has $(numparams(results.traces[1])) parameters\"\nend", "meta": {"hexsha": "220f1cb346cf33b3bf8992a4d3415a5960375567", "size": 1075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/statistics.jl", "max_stars_repo_name": "daviddewhurst/CrimsonSkyline.jl", "max_stars_repo_head_hexsha": "89661f5ed3c0fa4a0753f9ec8f3a24542b574cb8", "max_stars_repo_licenses": ["MIT"], "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/statistics.jl", "max_issues_repo_name": "daviddewhurst/CrimsonSkyline.jl", "max_issues_repo_head_hexsha": "89661f5ed3c0fa4a0753f9ec8f3a24542b574cb8", "max_issues_repo_licenses": ["MIT"], "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/statistics.jl", "max_forks_repo_name": "daviddewhurst/CrimsonSkyline.jl", "max_forks_repo_head_hexsha": "89661f5ed3c0fa4a0753f9ec8f3a24542b574cb8", "max_forks_repo_licenses": ["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.0689655172, "max_line_length": 92, "alphanum_fraction": 0.6437209302, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7694575009744725}}
{"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    \u03b8   ::  T   # inclination or polar angle\n    \u03d5   ::  T   # azimuthal angle\nend\n\npoint(p::SphericalCoordinate) = SVector(sin(p.\u03b8)*cos(p.\u03d5), sin(p.\u03b8)*sin(p.\u03d5), cos(p.\u03b8))\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    \u03b1 ~ Normal(0, 10)\n    \u03b2p ~ Normal(0, 1)\n\n    \u03c3_society ~ truncated(Cauchy(0, 1), 0, Inf)\n\n    N_society = length(unique(society)) ## 10\n\n    \u03b1_society ~ filldist(Normal(0, \u03c3_society), N_society)\n\n    for i in 1:N\n        \u03bb = exp(\u03b1 + \u03b1_society[society[i]] + \u03b2p*log_pop[i])\n        total_tools[i] ~ Poisson(\u03bb)\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, \u03b7, D, D2, \u03d5, params)\n    \n    a = params.a\n    N = params.N\u03d5\n    g = params.g\n    \n    k2 = k^2\n    ik = 1im*k    \n\n    h = \u03b7 .+ params.H\n    axcos = a * cos.(\u03d5)\n    \n           D = D/a\n       IxCos = diagm(0=>axcos)\n       IoCos = diagm(0=>1 ./ axcos)\n    Two\u03a9xSin = diagm(0=>params.Two\u03a9*sin.(\u03d5));\n       UoCos = diagm(0=>u./axcos)\n       UxTan = diagm(0=>u./axcos.*sin.(\u03d5))\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\u03a9 .+ 0*\u03d5)\n    dU = diagm(0 => D*u)\n    \n    A = [                UoCos             (-Two\u03a9xSin - UxTan + dU)[:, 2:N]    g*IoCos;\n          -(Two\u03a9xSin + 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": "using JuMP, NLopt, Test\n\nmodel = Model(NLopt.Optimizer)\nset_optimizer_attribute(model, \"algorithm\", :LD_MMA)\n\na1 = 2\nb1 = 0\na2 = -1\nb2 = 1\n\n@variable(model, x1)\n@variable(model, x2 >= 0)\n\n@NLobjective(model, Min, sqrt(x2))\n@NLconstraint(model, x2 >= (a1*x1+b1)^3)\n@NLconstraint(model, x2 >= (a2*x1+b2)^3)\n\nset_start_value(x1, 1.234)\nset_start_value(x2, 5.678)\n\noptimize!(model)\n\nprintln(\"got \", objective_value(model), \" at \", [value(x1), value(x2)])\n\n@test_approx_eq_eps value(x1) 1/3 1e-5\n@test_approx_eq_eps value(x2) 8/27 1e-5\n@test_approx_eq_eps objective_value(m) sqrt(8/27) 1e-5\n@test termination_status(model) == MOI.OPTIMAL\n", "meta": {"hexsha": "4b574df639d4c076c6af735615dbb6b913a109b2", "size": 633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tutorial_jump.jl", "max_stars_repo_name": "serenity4/NLopt.jl", "max_stars_repo_head_hexsha": "ddc7d8769bf191841d3d8bb7f9b20d75573e7da0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 188, "max_stars_repo_stars_event_min_datetime": "2015-01-02T02:13:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T14:24:14.000Z", "max_issues_repo_path": "test/tutorial_jump.jl", "max_issues_repo_name": "serenity4/NLopt.jl", "max_issues_repo_head_hexsha": "ddc7d8769bf191841d3d8bb7f9b20d75573e7da0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 132, "max_issues_repo_issues_event_min_datetime": "2015-01-06T21:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T22:28:48.000Z", "max_forks_repo_path": "test/tutorial_jump.jl", "max_forks_repo_name": "serenity4/NLopt.jl", "max_forks_repo_head_hexsha": "ddc7d8769bf191841d3d8bb7f9b20d75573e7da0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 57, "max_forks_repo_forks_event_min_datetime": "2015-05-20T12:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:22:32.000Z", "avg_line_length": 21.8275862069, "max_line_length": 71, "alphanum_fraction": 0.7077409163, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7693700277737263}}
{"text": "123.4 + 234.5     # This is a comment, ignored by Julia\n\n7 / 3             # Integer division returns floating point\n\n7 \u00f7 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\u22c510\u2077 (not e\u2077)\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\u03c0; -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 \u2208 1:5\n    push!(polys, u.^i...)\n    for j \u2208 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\u03a8 = SINDy(sol[:,1:25], DX[:, 1:25], basis, opt, p = [1.0; 1.0], maxiter = 100, convergence_error = 1e-5)\nprintln(\u03a8)\nprint_equations(\u03a8)\n\n# Lasso as ADMM, typically needs more information, more tuning\nopt = ADMM(1e-2, 1.0)\n\u03a8 = SINDy(sol[:,1:50], DX[:, 1:50], basis, opt, p = [1.0; 1.0], maxiter = 5000, convergence_error = 1e-3)\nprintln(\u03a8)\nprint_equations(\u03a8)\n\n# Get the associated parameters out of the result\nparameters(\u03a8)\n\n# SR3, works good with lesser data and tuning\nopt = SR3(1e-2, 1.0)\n\u03a8 = SINDy(sol[:,1:end], DX[:, 1:end], basis, opt, p = [0.5; 0.5], maxiter = 5000, convergence_error = 1e-5)\nprintln(\u03a8)\nprint_equations(\u03a8, show_parameter = true)\n\n\n# Vary the sparsity threshold -> gives better results\n\u03bbs = 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\u03a8 = SINDy(sol[:,1:10], DX[:, 1:10], basis, \u03bbs, opt, p = [1.0; 1.0], maxiter = 15000)\nprintln(\u03a8)\nprint_equations(\u03a8)\n\n# Transform into ODE System\nsys = ODESystem(\u03a8)\ndudt = ODEFunction(sys)\nps = parameters(\u03a8)\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": "using Diagonalizations, LinearAlgebra, PosDefManifold, Test\n\n# Method (1) real\nn, t=10, 100\nX=genDataMatrix(n, t)\nC=(X*X')/t\nwC=whitening(Hermitian(C); simple=true)\n# or, shortly\nwC=whitening(\u210d(C); simple=true)\n\n# Method (1) complex\nXc=genDataMatrix(ComplexF64, n, t)\nCc=(Xc*Xc')/t\nwCc=whitening(Hermitian(Cc); simple=true)\n\n\n# Method (2) real\nwX=whitening(X; simple=true)\n@test wC.F'*C*wC.F\u2248I\n@test wX.F'*C*wX.F\u2248I\n@test wX\u2248wC\n\n# Method (2) complex\nwXc=whitening(Xc; simple=true)\n@test wCc.F'*Cc*wCc.F\u2248I\n@test wXc.F'*Cc*wXc.F\u2248I\n@test wXc\u2248wCc\n\n\n# Method (3) real\nk=10\nXset=[genDataMatrix(n, t) for i=1:k]\n\n# whitening on the average covariance matrix\nw=whitening(Xset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.5\nw=whitening(Xset; eVar=0.5)\n\n# ... averaging the covariance matrices using the logEuclidean metric\nw=whitening(Xset; metric=logEuclidean, eVar=0.5)\n\n# ... giving weights `w` to the covariance matrices\nw=whitening(Xset; metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# ... subtracting the mean\nw=whitening(Xset; meanX=nothing, metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# whitening on the average of the covariance matrices computed along dims 1\nw=whitening(Xset; dims=1)\n\n# explained variance\nw.eVar\n\n# name of the filter\nw.name\n\nusing Plots\n# plot regularized accumulated eigenvalues\nplot(w.arev)\n\n# plot the original covariance matrix and the whitened covariance matrix\n Cmax=maximum(abs.(C));\n h1 = heatmap(C, clim=(-Cmax, Cmax), yflip=true, c=:bluesreds, title=\"C\");\n D=wC.F'*C*wC.F;\n h2 = heatmap(D, clim=(0, 1), yflip=true, c=:amp, title=\"F'*C*F\");\n \ud83d\udcc8=plot(h1, h2, size=(700, 300))\n# savefig(\ud83d\udcc8, homedir()*\"\\\\Documents\\\\Code\\\\julia\\\\Diagonalizations\\\\docs\\\\src\\\\assets\\\\FigWhitening.png\")\n\n\n# Method (3) complex\nk=10\nXcset=[genDataMatrix(ComplexF64, n, t) for i=1:k]\n\n# whitening on the average covariance matrix\nwc=whitening(Xcset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.5\nwc=whitening(Xcset; eVar=0.5)\n\n# ... averaging the covariance matrices using the logEuclidean metric\nwc=whitening(Xcset; metric=logEuclidean, eVar=0.5)\n\n# ... giving weights `w` to the covariance matrices\nwc=whitening(Xset; metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# ... subtracting the mean\nwc=whitening(Xcset; meanX=nothing, metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# whitening on the average of the covariance matrices computed along dims 1\nwc=whitening(Xcset; dims=1)\n\n# explained variance\nwc.eVar\n\n# name of the filter\nwc.name\n", "meta": {"hexsha": "6f2fb9f2c0a9f3519e8c62715630f581767f1686", "size": 2516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Whitening.jl", "max_stars_repo_name": "ericphanson/Diagonalizations.jl", "max_stars_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/Whitening.jl", "max_issues_repo_name": "ericphanson/Diagonalizations.jl", "max_issues_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/Whitening.jl", "max_forks_repo_name": "ericphanson/Diagonalizations.jl", "max_forks_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": 25.6734693878, "max_line_length": 105, "alphanum_fraction": 0.7217806041, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7693373883379266}}
{"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    \u03bay::Float64 \n    ybar::Float64\n    \u03c3y::Float64\n\n    r::Float64\n\n    # utility parameters\n    \u03c1::Float64  \n    \u03b3::Float64\n\n    amin::Float64\n    amax::Float64 \nend\n\nfunction AchdouHanLasryLionsMollModel(;\u03bay = 0.1, ybar = 1.0, \u03c3y = 0.07, r = 0.03, \u03c1 = 0.05, \u03b3 = 2.0, amin = 0.0, amax = 500.0)\n    AchdouHanLasryLionsMollModel(\u03bay, ybar, \u03c3y, r, \u03c1, \u03b3, amin, amax)\nend\n\nfunction (m::AchdouHanLasryLionsMollModel)(state::NamedTuple, value::NamedTuple)\n    (; \u03bay, \u03c3y, ybar, r, \u03c1, \u03b3, amin, amax) = m    \n    (; y, a) = state\n    (; v, vy_up, vy_down, va_up, va_down, vyy, vya, vaa) = value\n    \u03bcy = \u03bay * (ybar - y)\n    vy = (\u03bcy >= 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 / \u03b3)\n    \u03bca = y + r * a - c\n    if (iter == 0) & (\u03bca <= 0)\n        iter += 1\n        va = va_down\n        @goto start\n    end\n    if (a \u2248 amin) && (\u03bca <= 0.0)\n        va = (y + r * amin)^(-\u03b3)\n        c = y + r * amin\n        \u03bca = 0.0\n    end\n    vt = - (c^(1 - \u03b3) / (1 - \u03b3) + \u03bca * va + \u03bcy * vy + 0.5 * vyy * \u03c3y^2 - \u03c1 * v)\n    return (; vt)\nend\n\nm = AchdouHanLasryLionsMollModel()\ndistribution = Gamma(2 * m.\u03bay * m.ybar / m.\u03c3y^2, m.\u03c3y^2 / (2 * m.\u03bay))\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.\u03b3)/(1-m.\u03b3) for y in stategrid[:y], a in stategrid[:a]]) \n\u03c4s = range(0, stop = 100, step = 1)\nresult  = pdesolve(m, stategrid, yend, \u03c4s)\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.\u03c1 - m.r)/m.\u03b3))^(1/(1 - 1/m.\u03b3))\n#pw = (result[:v] * (1-m.\u03b3)).^(1/(1-m.\u03b3)-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": "using Stats\nusing Base.Test\n\n@test_approx_eq autocor([1, 2, 3, 4, 5], 1) 0.4\n\n@test iqr([1, 2, 3, 4, 5]) == [2.0, 4.0]\n\nz = [true, true, false, false, true, false, true, true, true]\nvalues, lengths = rle(z)\n@test values == [true, false, true, false, true]\n@test lengths == [2, 2, 1, 1, 3]\n@test inverse_rle(values, lengths) == z\n\nz = [true, true, false, false, true, false, true, true, true, false]\nvalues, lengths = rle(z)\n@test values == [true, false, true, false, true, false]\n@test lengths == [2, 2, 1, 1, 3, 1]\n@test inverse_rle(values, lengths) == z\n\nX = [1 0; 2 1; 3 0; 4 1; 5 10]\ny = [5, 3, 4, 2, 5]\n@test_approx_eq cor_spearman(X, y)[1] cor_spearman(X[:,1],y)\n@test_approx_eq cor_spearman(X) cor_spearman(X, X)\n@test_approx_eq cor_spearman(X, y) [-0.102597835208515, -0.081110710565381]\n@test_approx_eq cor_kendall(X,y) [-0.105409255338946, -0.117851130197758]\n\nfnecdf = ecdf(randn(10000000))\n@test_approx_eq_eps fnecdf([-1.96, -1.644854, -1.281552, -0.6744898, 0, 0.6744898, 1.281552, 1.644854, 1.96]) [0.025, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.975] 1e-3\n@test_approx_eq_eps fnecdf(1.96) 0.975 1e-3\n@test_approx_eq fnecdf([-1.96, -1.644854, -1.281552, -0.6744898, 0, 0.6744898, 1.281552, 1.644854, 1.96]) map(fnecdf, [-1.96, -1.644854, -1.281552, -0.6744898, 0, 0.6744898, 1.281552, 1.644854, 1.96])\n", "meta": {"hexsha": "6f8f7a3f42245fd1c9e516dca75289df8b6fc075", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Stats/test/01.jl", "max_stars_repo_name": "keirtheashby/ExoplanetsSysSim.jl-1", "max_stars_repo_head_hexsha": "b039911a7bd6ab8df40766baed526d65c6d07652", "max_stars_repo_licenses": ["MIT"], "max_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/test/01.jl", "max_issues_repo_name": "keirtheashby/ExoplanetsSysSim.jl-1", "max_issues_repo_head_hexsha": "b039911a7bd6ab8df40766baed526d65c6d07652", "max_issues_repo_licenses": ["MIT"], "max_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/test/01.jl", "max_forks_repo_name": "keirtheashby/ExoplanetsSysSim.jl-1", "max_forks_repo_head_hexsha": "b039911a7bd6ab8df40766baed526d65c6d07652", "max_forks_repo_licenses": ["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.4516129032, "max_line_length": 200, "alphanum_fraction": 0.6542553191, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7693046245617794}}
{"text": "\n# InverseGamma distribution\n\nexport InverseGamma\n\n@parameterized InverseGamma(shape) \u2243 Lebesgue(\u211d\u208a)\n\nfunction logdensity(\u03bc::InverseGamma{(:shape,)}, x) \n    \u03b1 = \u03bc.shape\n    xinv = 1/x\n\n    return xlogy(\u03b1 + 1, xinv) - xinv - loggamma(\u03b1) \nend\n\nBase.rand(rng::AbstractRNG, T::Type, \u03bc::InverseGamma{(:shape,)}) = rand(rng, Dists.InverseGamma(\u03bc.shape))\n\n\u226a(::InverseGamma, ::Lebesgue{X}) where X <: Real = true\n\nTV.as(::InverseGamma) = as\u211d\u208a\n\n# @\u03bc\u03c3_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": "using RayTracer\nusing LinearAlgebra\nusing Test\n\n@testset \"creating_4_x_4_matrix\" begin\n    m = [1 2 3 4; 5.5 6.5 7.5 8.5; 9 10 11 12; 13.5 14.5 15.5 16.5]\n    @test m[1,1] \u2248 1\n    @test m[1,4] \u2248 4\n    @test m[2,1] \u2248 5.5\n    @test m[2,3] \u2248 7.5\n    @test m[3,3] \u2248 11\n    @test m[4,1] \u2248 13.5\n    @test m[4,3] \u2248 15.5\nend\n\n@testset \"equal_matrices\" begin\n    m = [1 2 3 4; 5.5 6.5 7.5 8.5; 9 10 11 12; 13.5 14.5 15.5 16.5]\n    n = [1 2 3 4; 5.5 6.5 7.5 8.5; 9 10 11 12; 13.5 14.5 15.5 16.5]\n    @test m \u2248 n\nend\n\n@testset \"different_matrices\" begin\n    m = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]\n    n = [2 3 4 5; 6 7 8 9; 10 11 12 13; 14 15 16 1]\n    @test m \u2260 n\nend\n\n@testset \"matrix_tuple_multiplication\" begin\n    a = [1 2 3 4; 2 4 4 2; 8 6 4 1; 0 0 0 1]\n    b = RayTracer.tuple(1, 2, 3, 1)\n    @test a*b \u2248 RayTracer.tuple(18,24,33,1)\nend\n\n@testset \"creating_submatix\" begin\n    a = [1 5 0; -3 2 7; 0 6 -3]\n    b = RayTracer.submatrix(a,1,3)\n    @test b \u2248 [-3 2; 0 6]\nend\n\n@testset \"computing minor\" begin\n    a = [3 5 0; 2 -1 -7; 6 -1 5]\n    b = RayTracer.submatrix(a,2,1)\n    @test det(b) \u2248 25\n    @test RayTracer.minor(a,2,1) \u2248 25\nend\n\n@testset \"computing_cofactor\" begin\n    a = [3 5 0; 2 -1 -7; 6 -1 5]\n    @test RayTracer.minor(a,1,1) \u2248 -12\n    @test RayTracer.cofactor(a,1,1) \u2248 -12\n    @test RayTracer.minor(a,2,1) \u2248 25\n    @test RayTracer.cofactor(a,2,1) \u2248 -25\nend\n\n@testset \"multiplying_by_translation_matrix\" begin\n    transform = RayTracer.translation(5,-3,2)\n    p = RayTracer.point(-3,4,5)\n    @test transform * p \u2248 RayTracer.point(2,1,7)\nend\n\n@testset \"multiplying_by_inverse_translation\" begin\n    transform = RayTracer.translation(5,-3,2)\n    inv_transform = inv(transform)\n    p = RayTracer.point(-3,4,5)\n    @test inv_transform * p \u2248 RayTracer.point(-8,7,3)\nend\n\n@testset \"translation_does_not_affect_vectors\" begin\n    transform = RayTracer.translation(5,-3,2)\n    v = RayTracer.vector(-3,4,5)\n    @test transform*v \u2248 v\nend\n\n@testset \"scaling_applied_to_point\" begin\n    transform = RayTracer.scaling(2,3,4)\n    p = RayTracer.point(-4,6,8)\n    @test transform*p \u2248 RayTracer.point(-8,18,32)\nend\n\n@testset \"scaling_applied_to_vector\" begin\n    transform = RayTracer.scaling(2,3,4)\n    v = RayTracer.vector(-4,6,8)\n    @test transform*v \u2248 RayTracer.vector(-8,18,32)\nend\n\n@testset \"multiplying_inverse_scaling\" begin\n    transform = RayTracer.scaling(2,3,4)\n    inv_transform = inv(transform)\n    v = RayTracer.vector(-4,6,8)\n    @test inv_transform*v \u2248 RayTracer.vector(-2,2,2)\nend\n\n@testset \"reflection_is_scaling_negative\" begin\n    transform = RayTracer.scaling(-1,1,1)\n    p = RayTracer.point(2,3,4)\n    @test transform*p \u2248 RayTracer.point(-2,3,4)\nend\n\n@testset \"rotation_around_x_axis\" begin\n    p = RayTracer.point(0,1,0)\n    eith_turn = RayTracer.rotation_x(\u03c0/4)\n    quarter_turn = RayTracer.rotation_x(\u03c0/2)\n    @test eith_turn*p \u2248 RayTracer.point(0,\u221a2/2,\u221a2/2)\n    @test \u2248(quarter_turn*p,RayTracer.point(0,0,1),1e-10)\nend\n\n@testset \"inverse_rotation_x_axis\" begin\n    p = RayTracer.point(0,1,0)\n    eith_turn = RayTracer.rotation_x(\u03c0/4)\n    inv_transform = inv(eith_turn)\n    @test inv_transform*p \u2248 RayTracer.point(0,\u221a2/2,-\u221a2/2)\nend\n\n@testset \"rotation_around_y_axis\" begin\n    p = RayTracer.point(0,0,1)\n    eith_turn = RayTracer.rotation_y(\u03c0/4)\n    quarter_turn = RayTracer.rotation_y(\u03c0/2)\n    @test eith_turn*p \u2248 RayTracer.point(\u221a2/2,0,\u221a2/2)\n    @test \u2248(quarter_turn*p,RayTracer.point(1,0,0),1e-10)\nend\n\n@testset \"rotation_around_z_axis\" begin\n    p = RayTracer.point(0,1,0)\n    eith_turn = RayTracer.rotation_z(\u03c0/4)\n    quarter_turn = RayTracer.rotation_z(\u03c0/2)\n    @test eith_turn*p \u2248 RayTracer.point(-\u221a2/2,\u221a2/2,0)\n    @test \u2248(quarter_turn*p,RayTracer.point(-1,0,0),1e-10)\nend\n\n@testset \"shearing_x_wrt_y\" begin\n    transform = RayTracer.shearing(1,0,0,0,0,0)\n    p = RayTracer.point(2,3,4)\n    @test transform*p \u2248 RayTracer.point(5,3,4)\nend\n\n@testset \"shearing_x_wrt_z\" begin\n    transform = RayTracer.shearing(0,1,0,0,0,0)\n    p = RayTracer.point(2,3,4)\n    @test transform*p \u2248 RayTracer.point(6,3,4)\nend\n\n@testset \"shearing_y_wrt_x\" begin\n    transform = RayTracer.shearing(0,0,1,0,0,0)\n    p = RayTracer.point(2,3,4)\n    @test transform*p \u2248 RayTracer.point(2,5,4)\nend\n\n@testset \"shearing_y_wrt_z\" begin\n    transform = RayTracer.shearing(0,0,0,1,0,0)\n    p = RayTracer.point(2,3,4)\n    @test transform*p \u2248 RayTracer.point(2,7,4)\nend\n\n@testset \"shearing_z_wrt_x\" begin\n    transform = RayTracer.shearing(0,0,0,0,1,0)\n    p = RayTracer.point(2,3,4)\n    @test transform*p \u2248 RayTracer.point(2,3,6)\nend\n\n@testset \"shearing_z_wrt_y\" begin\n    transform = RayTracer.shearing(0,0,0,0,0,1)\n    p = RayTracer.point(2,3,4)\n    @test transform*p \u2248 RayTracer.point(2,3,7)\nend\n\n@testset \"individual_transformations_sequential\" begin\n    p = RayTracer.point(1,0,1)\n    A = RayTracer.rotation_x(\u03c0/2)\n    B = RayTracer.scaling(5,5,5)\n    C = RayTracer.translation(10,5,7)\n    p2 = A*p\n    @test \u2248(p2,RayTracer.point(1,-1,0),1e-10)\n    p3 = B*p2\n    @test \u2248(p3,RayTracer.point(5,-5,0),1e-10)\n    p4 = C*p3\n    @test \u2248(p4,RayTracer.point(15,0,7),1e-10)\nend\n\n@testset \"chained_transformations\" begin\n    p = RayTracer.point(1,0,1)\n    A = RayTracer.rotation_x(\u03c0/2)\n    B = RayTracer.scaling(5,5,5)\n    C = RayTracer.translation(10,5,7)\n    D = C*B*A\n    @test \u2248(D*p,RayTracer.point(15,0,7),1e-10)\nend", "meta": {"hexsha": "a38b67f816ee6ca6427d1d2022762d7bf35bae50", "size": 5315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/transformations.jl", "max_stars_repo_name": "etenedrac/RayTracer.jl", "max_stars_repo_head_hexsha": "a0eb8508105a74becfb09289999371ac0bffd1bd", "max_stars_repo_licenses": ["MIT"], "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/transformations.jl", "max_issues_repo_name": "etenedrac/RayTracer.jl", "max_issues_repo_head_hexsha": "a0eb8508105a74becfb09289999371ac0bffd1bd", "max_issues_repo_licenses": ["MIT"], "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/transformations.jl", "max_forks_repo_name": "etenedrac/RayTracer.jl", "max_forks_repo_head_hexsha": "a0eb8508105a74becfb09289999371ac0bffd1bd", "max_forks_repo_licenses": ["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.5752688172, "max_line_length": 67, "alphanum_fraction": 0.6511759172, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7693046098236593}}
{"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\u22121)/2   1, 5, 12, 22, 35, ...\n# Hexagonal   P6,n=n(2n\u22121)     1, 6, 15, 28, 45, ...\n# Heptagonal  P7,n=n(5n\u22123)/2   1, 7, 18, 34, 55, ...\n# Octagonal   P8,n=n(3n\u22122)     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": "#using TensorToolbox, Test, LinearAlgebra\n\nprintln(\"\\n\\n****Testing ktensor.jl\")\n\nIsz=5;J=4;K=3;\na=rand(Isz);\nb=rand(J);\nc=rand(K);\nX=zeros(Isz,J,K);\nfor i=1:Isz,j=1:J,k=1:K\n    X[i,j,k]=a[i]*b[j]*c[k];\nend\nprintln(\"\\n**Test rank-1 tensor X of size: \", size(X))\nprintln(\"...Testing cp_als.\")\nZ=cp_als(X,1)\nerr=norm(full(Z)-X)\nprintln(\"norm(full(Xcp)-X) = \",err)\n@test err \u2248 0 atol=1e-10\n\n#Ax = rand(4,2)\n#Bx = rand(3,2)\n#Cx = rand(2,2)\n#Xlambda=[0.5,2]\n#X = ktensor(Xlambda,[Ax,Bx,Cx])\nX=randktensor([4,3,2],2)\nAy = rand(4,3)\nBy = rand(3,3)\nCy = rand(2,3)\nYlambda=[2,3,1]\nY=ktensor(Ylambda,[Ay,By,Cy])\n\nprintln(\"\\n**Test ktensors X and Y of size: \", size(X))\nprintln()\n\nprintln(\"...Testing function ndims.\")\nprintln(\"X is of order: \",ndims(X))\n\nprintln(\"...Testing function ttensor and full.\")\nT=ttensor(X)\n@test norm(full(T)-full(X)) \u2248 0 atol=1e-10\n\nprintln(\"...Testing scalar multiplication.\")\nerr=norm(full(3*X) - 3*full(X))\nprintln(\"norm(full(3*X) - 3*full(X)) = \",err)\n@test norm(full(3*X) - 3*full(X)) \u2248 0 atol=1e-10\n\nprintln(\"...Testing functions plus and minus.\")\nZ=X+Y\nerr=norm(full(Z)-(full(X)+full(Y)))\nprintln(\"norm(full(Z)-(full(X)+full(Y))) = \",err)\n@test err \u2248 0 atol=1e-10\nZ=X-Y\nerr=norm(full(Z)-(full(X)-full(Y)))\nprintln(\"norm(full(Z)-(full(X)-full(Y))) = \",err)\n@test err \u2248 0 atol=1e-10\n\n\nprintln(\"...Testing function innerprod.\")\nerr=norm(innerprod(X,Y)-innerprod(full(X),full(Y)))\nprintln(\"norm(innerprod(X,Y)-innerprod(full(X),full(Y))) = \",err)\n@test err  \u2248 0 atol=1e-10\nZ=rand(4,3,2)\n@test norm(innerprod(X,Z)-innerprod(full(X),Z)) \u2248 0 atol=1e-10\n\nprintln(\"...Testing function norm.\")\n@test abs(norm(X)-norm(full(X)))\u2248 0 atol=1e-10\n\n\nprintln(\"...Testing functions arrange and arrange!.\")\nZ=arrange(X)\nerr=norm(full(X)-full(Z))\nprintln(\"norm(full(X)-full(Z)) = \",err)\n@test err \u2248 0 atol=1e-10\nZ=arrange(X,2)\n@test norm(full(X)-full(Z)) \u2248 0 atol=1e-10\nZ=arrange(X,[2,1])\n@test norm(full(X)-full(Z)) \u2248 0 atol=1e-10\nXcopy=deepcopy(X)\narrange!(X)\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\narrange!(X,2)\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\narrange!(X,[2,1])\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\n\nprintln(\"...Testing functions normalize and normalize!.\")\nZ=normalize(X)\nerr=norm(full(X)-full(Z))\nprintln(\"norm(full(X)-full(Z)) = \",err)\n@test err \u2248 0 atol=1e-10\nZ=normalize(X,2)\n@test norm(full(X)-full(Z)) \u2248 0 atol=1e-10\nZ=normalize(X,3,normtype=1)\n@test norm(full(X)-full(Z)) \u2248 0 atol=1e-10\nZ=normalize(X,\"sort\")\n@test norm(full(X)-full(Z)) \u2248 0 atol=1e-10\nZ=normalize(X,factor=2)\n@test norm(full(X)-full(Z)) \u2248 0 atol=1e-10\nXcopy=deepcopy(X)\nnormalize!(X)\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\nnormalize!(X,2)\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\nnormalize!(X,3,normtype=1)\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\nnormalize!(X,\"sort\")\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\nnormalize!(X,factor=2)\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\n\nprintln(\"...Testing functions redistribute and redistribute!.\")\nmode=2\nZ=redistribute(X,mode)\nerr=norm(full(X)-full(Z))\nprintln(\"norm(full(X)-full(Z)) = \",err)\n@test err \u2248 0 atol=1e-10\nXcopy=deepcopy(X)\nredistribute!(X,mode)\n@test norm(full(X)-full(Xcopy)) \u2248 0 atol=1e-10\n\nprintln(\"...Testing functions fixsigns, fixsigns! and isequal.\")\nXcopy=deepcopy(X)\nX.fmat[1][:,1]=-X.fmat[1][:,1]\nX.fmat[2][:,1]=-X.fmat[2][:,1]\nZ=fixsigns(X)\nerr=norm(full(X)-full(Z))\nprintln(\"norm(full(X)-full(Z)) = \",err)\n@test err \u2248 0 atol=1e-10\nfixsigns!(X)\n@test norm(X-Xcopy) \u2248 0 atol=1e-7\n\nprintln(\"...Testing functions ttm and ttv.\")\nM=MatrixCell(undef,2)\nM[1]=rand(4,3)\nM[2]=rand(4,2)\nmode=[2,3]\nZ=ttm(X,M,mode)\nW=ttm(full(X),M,mode)\n@test norm(W-full(Z)) \u2248 0 atol=1e-10\nv=VectorCell(undef,2)\nv[1]=rand(3)\nv[2]=rand(2)\nmode=[2,3]\nZ=ttv(X,v,mode)\nW=ttv(full(X),v,mode)\n@test norm(W-full(Z)) \u2248 0 atol=1e-10\n\nprintln(\"\\n...Testing function tocell.\")\nM=tocell(X)\nprintln(\"Is the output MatrixCell: \",isa(M,MatrixCell))\n@test isa(M,MatrixCell)\n\nmode=2;\nprintln(\"\\n...Testing function tenmat by mode $mode.\")\nXn=tenmat(X,mode)\n@test tenmat(full(X),mode) == Xn\n\nprintln(\"\\n...Testing function mttkrp.\")\nX=randktensor([5,4,3],3)\nmode=1\nM1=rand(5,5);\nM2=rand(4,5);\nM3=rand(3,5);\nM=[M1,M2,M3]\nprintln(\"Multiplying mode-$mode matricized tensor X by Khatri-Rao product of matrices.\")\nZ=mttkrp(X,M,mode)\nerr = norm(Z-tenmat(X,mode)*khatrirao(M3,M2))\nprintln(\"Multiplication error: \",err)\n@test err \u2248 0 atol=1e-10\n", "meta": {"hexsha": "1894e397af33d46e880d9c291733b01392ba210d", "size": 4405, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ktensorTest.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/TensorToolbox.jl-9c690861-8ade-587a-897e-15364bc6f718", "max_stars_repo_head_hexsha": "969a1a9f20b236fbd90dd47d8d01679ee75afe56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2017-05-25T14:02:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:46:13.000Z", "max_issues_repo_path": "test/ktensorTest.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/TensorToolbox.jl-9c690861-8ade-587a-897e-15364bc6f718", "max_issues_repo_head_hexsha": "969a1a9f20b236fbd90dd47d8d01679ee75afe56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-08-04T00:20:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T20:05:19.000Z", "max_forks_repo_path": "test/ktensorTest.jl", "max_forks_repo_name": "bovine3dom/TensorToolbox.jl", "max_forks_repo_head_hexsha": "fe96333d5d6ce4a03150f10f2ef5f191954b8efb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-05-25T10:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-10T12:18:38.000Z", "avg_line_length": 25.9117647059, "max_line_length": 88, "alphanum_fraction": 0.6565266742, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7693046077979603}}
{"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\u03b2 = 0.8;\n\u03c0s1 = 1/2;\n\u03c0s2 = 1/2;\nYs1 = 1;\nYs2 = 1/2;\nM = 20; # Number of grids\n\n## Grid for v\nvmax = (\u03c0s1 * u(Ys1) + \u03c0s2 * u(Ys2)) / (1 - \u03b2);\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 - (\u03c0s1 * (cs1^(1/2) + \u03b2 * ws1)) - (\u03c0s2 * (cs2^(1/2) + \u03b2 * ws2));\n            cs2 = findZero(f, 1.0);\n\n            U_temp = (\u03c0s1 * (u(Ys1 - cs1) + \u03b2 * Pi[ws1Index])) + \n                     (\u03c0s2 * (u(Ys2 - cs2) + \u03b2 * 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\u03bb = range(0.0, stop = 0.999, length = 100);\nu1 = zeros(100);\nu2 = zeros(100);\nfor i in 1:100\n    A = (\u03bb[i] / (1 - \u03bb[i]))^2;\n    cs1 = Ys1 * (A / (1 + A));\n    cs2 = Ys2 * (A / (1 + A));\n    u1[i] = (\u03c0s1 * u(cs1) + \u03c0s2 * u(cs2)) / (1 - \u03b2);\n    u2[i] = (\u03c0s1 * u(Ys1 - cs1) + \u03c0s2 * u(Ys2 - cs2)) / (1 - \u03b2);\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 SimpleGraphs, DrawSimpleGraphs, Plots\n\nexport KnightTourDrawing\n\n\"\"\"\n`KnightTourDrawing(r,c)` illustrates a Knight's tour of an r-by-c\nchessboard returning `true` if the tour exists and `false` if not.\n\"\"\"\nfunction KnightTourDrawing(r::Int=6, c::Int=6)\n    G = Knight(r,c)\n    println(\"Searching for a Hamiltonian cycle in an $r-by-$c Knight's move graph\")\n    @time h = hamiltonian_cycle(G)\n    println(\"Finished\")\n\n    if length(h)==0\n        println(\"Sorry. This graph is not Hamiltonian\")\n        return false\n    end\n\n    T = vertex_type(G)\n    H = SimpleGraph{T}()\n    for v in G.V\n        add!(H,v)\n    end\n\n    for k=1:NV(H)-1\n        add!(H,h[k],h[k+1])\n    end\n\n    add!(H,h[1],h[end])\n\n    xy = getxy(H)\n\n    for v in H.V\n        xy[v] = collect(v)\n    end\n\n    embed(H,xy)\n\n    draw(H)\n\n    for a=0:c\n        plot!( [0.5, r+0.5], [a+0.5, a+0.5], color=\"black\",\n                linestyle=:dash)\n    end\n\n    for b=0:r\n        plot!( [b+0.5, b+0.5], [0.5, c+0.5], color=\"black\",\n            linestyle=:dash)\n    end\n\n    finish()\n\nend\n", "meta": {"hexsha": "53413b04d55c14dfc4d01eb54c6b35e5c4e83ef4", "size": 1052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/KnightTourDrawing.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DrawSimpleGraphs.jl-1d51b185-1a84-59cf-b84e-03b0e3da30b7", "max_stars_repo_head_hexsha": "3f90ae8dfd998b942f0e476c6d190aea79cf7681", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KnightTourDrawing.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DrawSimpleGraphs.jl-1d51b185-1a84-59cf-b84e-03b0e3da30b7", "max_issues_repo_head_hexsha": "3f90ae8dfd998b942f0e476c6d190aea79cf7681", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/KnightTourDrawing.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DrawSimpleGraphs.jl-1d51b185-1a84-59cf-b84e-03b0e3da30b7", "max_forks_repo_head_hexsha": "3f90ae8dfd998b942f0e476c6d190aea79cf7681", "max_forks_repo_licenses": ["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.1272727273, "max_line_length": 83, "alphanum_fraction": 0.5551330798, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7692883627377324}}
{"text": "using Plots\nusing BenchmarkTools\n\nfunction vfsolve(vnew, kgrid, tolerance, imax)\n    \u03b1 = 0.3\n    \u03b4 = 0.1\n    \u03b2 = 0.9\n\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = log.(c)\n    u[kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while maximum(abs.(v - vnew)) > tolerance && i <= imax\n        v = vnew;\n        \n        (vnew, cartesianindex) = findmax(u .+ \u03b2*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 \u2248 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, \u03f5 = 1e-3), xs) # [4, 8, 26, 10, ...]\n\n# Values of R \u2208 [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": "# ---\n# title: 1480. Running Sum of 1d Array\n# id: problem1480\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Array\n# link: <https://leetcode.com/problems/running-sum-of-1d-array/description/>\n# hidden: true\n# ---\n# \n# Given an array `nums`. We define a running sum of an array as `runningSum[i] =\n# sum(nums[0]\u2026nums[i])`.\n# \n# Return the running sum of `nums`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: nums = [1,2,3,4]\n#     Output: [1,3,6,10]\n#     Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].\n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: nums = [1,1,1,1,1]\n#     Output: [1,2,3,4,5]\n#     Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].\n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: nums = [3,1,2,10,1]\n#     Output: [3,4,6,16,17]\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= nums.length <= 1000`\n#   * `-10^6 <= nums[i] <= 10^6`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "62d50df4b42e835c567070393064c41da5cc0526", "size": 1033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1480.running-sum-of-1d-array.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_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/1480.running-sum-of-1d-array.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "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/unresolved/1480.running-sum-of-1d-array.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["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.4464285714, "max_line_length": 91, "alphanum_fraction": 0.5314617619, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.7692381020865058}}
{"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": "# Conjugates for normal distribution\n\nusing Base.Test\nusing Distributions\nusing ConjugatePriors\n\nimport ConjugatePriors: NormalGamma, NormalInverseGamma\nimport ConjugatePriors: posterior, posterior_rand, posterior_mode, posterior_randmodel, fit_map\n\nn = 100\nw = rand(100)\n\n# \u039dormal - \u039dormal (known sigma)\n\npri = Normal(1.0, 5.0)\n\nx = rand(Normal(2.0, 3.0), n)\np = posterior((pri, 3.0), Normal, x)\n@test isa(p, Normal)\n@test_approx_eq mean(p)  (mean(pri) / var(pri) + sum(x) / 9.0) / (1.0 / var(pri) + n / 9.0)\n@test_approx_eq var(p) inv(1.0 / var(pri) + n / 9.0)\n\nr = posterior_mode((pri, 3.0), Normal, x)\n@test_approx_eq r mode(p)\n\nf = fit_map((pri, 3.0), Normal, x)\n@test isa(f, Normal)\n@test f.\u03bc == r\n@test f.\u03c3 == 3.0\n\np = posterior((pri, 3.0), Normal, x, w)\n@test isa(p, Normal)\n@test_approx_eq mean(p)  (mean(pri) / var(pri) + dot(x, w) / 9.0) / (1.0 / var(pri) + sum(w) / 9.0)\n@test_approx_eq var(p) inv(1.0 / var(pri) + sum(w) / 9.0)\n\nr = posterior_mode((pri, 3.0), Normal, x, w)\n@test_approx_eq r mode(p)\n\nf = fit_map((pri, 3.0), Normal, x, w)\n@test isa(f, Normal)\n@test f.\u03bc == r\n@test f.\u03c3 == 3.0\n\n\n# \u0399nverseGamma - \u039dormal (known mu)\n\npri = InverseGamma(1.5, 0.5)\n\nx = rand(Normal(2.0, 3.0), n)\np = posterior((2.0, pri), Normal, x)\n@test isa(p, InverseGamma)\n@test_approx_eq shape(p) shape(pri) + n / 2\n@test_approx_eq scale(p) scale(pri) + sum(abs2(x .- 2.0)) / 2\n\nr = posterior_mode((2.0, pri), Normal, x)\n@test_approx_eq r mode(p)\n\nf = fit_map((2.0, pri), Normal, x)\n@test isa(f, Normal)\n@test f.\u03bc == 2.0\n@test_approx_eq abs2(f.\u03c3) r\n\np = posterior((2.0, pri), Normal, x, w)\n@test isa(p, InverseGamma)\n@test_approx_eq shape(p) shape(pri) + sum(w) / 2\n@test_approx_eq scale(p) scale(pri) + dot(w, abs2(x .- 2.0)) / 2\n\nr = posterior_mode((2.0, pri), Normal, x, w)\n@test_approx_eq r mode(p)\n\nf = fit_map((2.0, pri), Normal, x, w)\n@test isa(f, Normal)\n@test f.\u03bc == 2.0\n@test_approx_eq abs2(f.\u03c3) r\n\n\n# Gamma - \u039dormal (known mu)\n\npri = Gamma(1.5, 2.0)\n\nx = rand(Normal(2.0, 3.0), n)\np = posterior((2.0, pri), Normal, x)\n@test isa(p, Gamma)\n@test_approx_eq shape(p) shape(pri) + n / 2\n@test_approx_eq scale(p) scale(pri) + sum(abs2(x .- 2.0)) / 2\n\nr = posterior_mode((2.0, pri), Normal, x)\n@test_approx_eq r mode(p)\n\nf = fit_map((2.0, pri), Normal, x)\n@test isa(f, Normal)\n@test f.\u03bc == 2.0\n@test_approx_eq abs2(f.\u03c3) inv(r)\n\np = posterior((2.0, pri), Normal, x, w)\n@test isa(p, Gamma)\n@test_approx_eq shape(p) shape(pri) + sum(w) / 2\n@test_approx_eq scale(p) scale(pri) + dot(w, abs2(x .- 2.0)) / 2\n\nr = posterior_mode((2.0, pri), Normal, x, w)\n@test_approx_eq r mode(p)\n\nf = fit_map((2.0, pri), Normal, x, w)\n@test isa(f, Normal)\n@test f.\u03bc == 2.0\n@test_approx_eq abs2(f.\u03c3) inv(r)\n\n\n# NormalInverseGamma - Normal\n\nmu_true = 2.\nsig2_true = 3.\nx = rand(Normal(mu_true, sig2_true), n)\n\nmu0 = 2.\nv0 = 3.\nshape0 = 5.\nscale0 = 2.\npri = NormalInverseGamma(mu0, v0, shape0, scale0)\n\npost = posterior(pri, Normal, x)\n@test isa(post, NormalInverseGamma)\n\n@test_approx_eq post.mu (mu0/v0 + n*mean(x))/(1./v0 + n)\n@test_approx_eq post.v0 1./(1./v0 + n)\n@test_approx_eq post.shape shape0 + 0.5*n\n@test_approx_eq post.scale scale0 + 0.5*(n-1)*var(x) + n./v0./(n + 1./v0)*0.5*(mean(x)-mu0).^2\n\nps = posterior_randmodel(pri, Normal, x)\n\n@test isa(ps, Normal)\n@test insupport(ps,ps.\u03bc) && ps.\u03c3 > zero(ps.\u03c3)\n\n\n# NormalGamma - Normal\n\nmu_true = 2.\ntau2_true = 3.\nx = rand(Normal(mu_true, 1./tau2_true), n)\n\nmu0 = 2.\nnu0 = 3.\nshape0 = 5.\nrate0 = 2.\npri = NormalGamma(mu0, nu0, shape0, rate0)\n\npost = posterior(pri, Normal, x)\n@test isa(post, NormalGamma)\n\n@test_approx_eq post.mu (nu0*mu0 + n*mean(x))./(nu0 + n)\n@test_approx_eq post.nu nu0 + n\n@test_approx_eq post.shape shape0 + 0.5*n\n@test_approx_eq post.rate rate0 + 0.5*(n-1)*var(x) + n*nu0/(n + nu0)*0.5*(mean(x)-mu0).^2\n\nps = posterior_randmodel(pri, Normal, x)\n\n@test isa(ps, Normal)\n@test insupport(ps, ps.\u03bc) && ps.\u03c3 > zero(ps.\u03c3)\n", "meta": {"hexsha": "31bf90cafcfdda47be695bcfabd0bc14fbaeabeb", "size": 3870, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/conjugates_normal.jl", "max_stars_repo_name": "JuliaPackageMirrors/ConjugatePriors.jl", "max_stars_repo_head_hexsha": "8f2f2dd42e7738b0a3fd32f3597e3e0b6371a574", "max_stars_repo_licenses": ["MIT"], "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/conjugates_normal.jl", "max_issues_repo_name": "JuliaPackageMirrors/ConjugatePriors.jl", "max_issues_repo_head_hexsha": "8f2f2dd42e7738b0a3fd32f3597e3e0b6371a574", "max_issues_repo_licenses": ["MIT"], "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/conjugates_normal.jl", "max_forks_repo_name": "JuliaPackageMirrors/ConjugatePriors.jl", "max_forks_repo_head_hexsha": "8f2f2dd42e7738b0a3fd32f3597e3e0b6371a574", "max_forks_repo_licenses": ["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": 99, "alphanum_fraction": 0.6444444444, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7692208149096059}}
{"text": "import StatisticalNonlocality: ou_transition_matrix, uniform_phase\nimport StatisticalNonlocality: discrete_laplacian\n\n@testset \"Transition Matrix Column Sum Zero\" begin\n    for n in 1:10\n        M = ou_transition_matrix(n)\n        @test all(abs.(sum(M, dims = 1)) .\u2264 eps(n / 2))\n        if n > 1\n            M = uniform_phase(n)\n            @test all(abs.(sum(M, dims = 1)) .\u2264 eps(n / 2))\n            \u0394 = discrete_laplacian(n)\n            @test all(abs.(sum(\u0394, dims = 1)) .\u2264 eps(n^2 / 2))\n        end\n    end\nend\n\n@testset \"OU Transition Matrix Correctness Test for n in 1:2\" begin\n    n = 1\n    M = ou_transition_matrix(n)\n    Mh = [\n        -1/2 1/2\n        1/2 -1/2\n    ]\n    @test all(abs.(Mh - M) .\u2264 eps(n / 2))\n\n    n = 2\n    M = ou_transition_matrix(n)\n    Mh = [\n        -1 1/2 0\n        1 -1 1\n        0 1/2 -1\n    ]\n    @test all(abs.(Mh - M) .\u2264 eps(n / 2))\nend\n\n@testset \"Uniform Phase Transition Matrix Correctness Test for n = 4\" begin\n    n = 4\n    M = uniform_phase(n)\n    Mh = [-1 1 0 0; 0 -1 1 0; 0 0 -1 1; 1 0 0 -1]\n    @test all(abs.(Mh - M) .\u2264 eps(n / 2))\n\nend\n\n@testset \"Eigenvalue Test for n in 1:10\" begin\n    for n in 1:10\n        \u03bb_exact = collect((-n):0)\n        \u03bb_approx = eigvals(ou_transition_matrix(n))\n        @test all(abs.(\u03bb_exact - \u03bb_approx) .\u2264 eps(20.0 * n))\n    end\nend\n\n@testset \"Symmetry Test for Discrete Laplacian\" begin\n    for n in 4:10\n        \u0394 = discrete_laplacian(n)\n        @test norm(\u0394 - \u0394') \u2264 eps(norm(\u0394))\n    end\nend", "meta": {"hexsha": "c26744bef6f9f6ec21899bc5350c22cd92902df1", "size": 1466, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/transition_matrix_test.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": "test/transition_matrix_test.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": "test/transition_matrix_test.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": 25.7192982456, "max_line_length": 75, "alphanum_fraction": 0.5525238745, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7692208125053056}}
{"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": "using MCMC\nusing Base.Test\n\n# Define immutable class State\nimmutable State\n  mu::Float64\n  sig2::Float64\nend\n\n@testset \"Posterior Means\" begin\n  srand(1)\n  using Distributions\n\n  # Generate data\n  const n = 1000\n  const (mu,sig2) = (5,2)\n  const y = rand(Normal(mu,sqrt(sig2)),n)\n\n  # precomputes\n  const ybar = mean(y)\n  const (sig2_a, sig2_b) = (2.0, 1.0)\n  rig(shape::Float64,rate::Float64) = 1 / rand(Gamma(shape,1/rate))\n\n\n  # define an update function for State\n  function update(state::State)\n    const newMu = rand(Normal(ybar,sqrt(state.sig2/n)))\n    const newSig2 = rig(sig2_a+n/2, sig2_b + sum((y-newMu).^2)/2)\n    State(newMu,newSig2)\n  end\n\n  # run gibbs\n  @time out = gibbs(State(0,1),update,10000,1000);\n\n  ## post processing\n  const postMu = map(o -> o.mu, out)\n  const postSig2 = map(o -> o.sig2, out)\n  @test abs(mean(postMu)-mu) < .05\n  @test abs(mean(postSig2)-sig2) < .05\nend\n\n#= Personal tests:\n# to test: vulture test.jl julia --color=yes test.jl\n\ninclude(\"runtests.jl\")\nusing RCall\nR\"library(rcommon) # install_github('luairthur/rcommon')\"\nplotPosts = R\"plotPosts\"\nplotPosts([postMu postSig2])\n=#\n", "meta": {"hexsha": "9f2185a432f6ba3a3c995c5128b13c2626f63854", "size": 1121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "luiarthur/mcmcJulia", "max_stars_repo_head_hexsha": "08d0d024a71e134bb79d92d9ebdb13ff8d575ab3", "max_stars_repo_licenses": ["MIT"], "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": "luiarthur/mcmcJulia", "max_issues_repo_head_hexsha": "08d0d024a71e134bb79d92d9ebdb13ff8d575ab3", "max_issues_repo_licenses": ["MIT"], "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": "luiarthur/mcmcJulia", "max_forks_repo_head_hexsha": "08d0d024a71e134bb79d92d9ebdb13ff8d575ab3", "max_forks_repo_licenses": ["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.9803921569, "max_line_length": 67, "alphanum_fraction": 0.6743978591, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7692208077486201}}
{"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": "\nimport Statistics\nimport Parameters.@with_kw\n\n##### BinFixedWidth #####\n\n\"\"\"\n\"\"\"\n@with_kw mutable struct BinFixedWidth\n    n_bins::Integer = 10; @assert n_bins > 0\n    data_min::Union{Float64,Missing} = missing\n    data_span::Union{Float64,Missing} = missing\n    bin_width::Union{Float64,Missing} = missing\n    is_fit::Bool = false\nend\n\n\"\"\"\n\"\"\"\nfunction fit_transform!(bin::BinFixedWidth, data::AbstractArray{<:Real})\n    bin.data_min = minimum(data)\n    bin.data_span = maximum(data) - bin.data_min\n    bin.bin_width = bin.data_span / bin.n_bins\n    bin.is_fit = true\n    bin\nend\n\n\"\"\"\n\"\"\"\nfunction apply_transform(bin::BinFixedWidth, data::AbstractArray{<:Real})\n    if !bin.is_fit | bin.data_min === missing | \\\n        bin.data_span === missing | bin.bin_width === missing\n        error(\"`bin` hasn't been fit.\")\n    end\n    ceil.(Int,(data .- bin.data_min) ./ bin.bin_width)\nend\n\n\n##### BinQuantile #####\n\n\"\"\"\n\"\"\"\n@with_kw mutable struct BinQuantile\n    n_bins::Integer = 10; @assert n_bins > 0\n    quantiles::Union{Array{Float64},Missing} = missing\n    is_fit::Bool = false\nend\n\n\"\"\"\n\"\"\"\nfunction fit_transform!(bin::BinQuantile, data::AbstractArray{<:Real})\n    bin.quantiles = Statistics.quantile(\n        data,\n        0:( 1 / (n_bins-1) ):1\n    )\n    bin.is_fit = true\n    bin\nend\n\n\"\"\"\n\"\"\"\nfunction apply_transform(bin::BinQuantile, data::AbstractArray{<:Real})\n    if !bin.is_fit | bin.quantiles === missing\n        error(\"`bin` hasn't been fit.\")\n    end\n    [findlast(q -> n < q, bin.quantiles) for n = data]\nend\n\n\n", "meta": {"hexsha": "a1353ddad06b5c4efab74e5b27b7f0c53ecd90dd", "size": 1527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numeric/binning.jl", "max_stars_repo_name": "a-poor/FeatureEng.jl", "max_stars_repo_head_hexsha": "d8aa98b29dd707c66812582dc0dd68506b46f015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-05T14:39:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T18:50:49.000Z", "max_issues_repo_path": "src/numeric/binning.jl", "max_issues_repo_name": "a-poor/FeatureEng.jl", "max_issues_repo_head_hexsha": "d8aa98b29dd707c66812582dc0dd68506b46f015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-29T00:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-03T16:33:04.000Z", "max_forks_repo_path": "src/numeric/binning.jl", "max_forks_repo_name": "a-poor/FeatureEng.jl", "max_forks_repo_head_hexsha": "d8aa98b29dd707c66812582dc0dd68506b46f015", "max_forks_repo_licenses": ["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.1304347826, "max_line_length": 73, "alphanum_fraction": 0.6417812705, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7692180731721818}}
{"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\u03bc = 1e-4\n\n# Build Spectrum (exp decay)\n\u03bbs = max.(\u221an * exp.(-(0:n-1) ./ \u221an), \u03bc)\nplot(\u03bbs, lw=3, legend=false, title=\"Spectrum\")\n\n# Build Matrix\nV = Array(qr(randn(n,n)).Q)\nA = V*Diagonal(\u03bbs)*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, \u03bc)\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, \u03bc, \u03bd; kwargs...)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with source and target\nmarginals `\u03bc` and `\u03bd` 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, \u03bc, \u03bd; kwargs...)\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with source and target\nmarginals `\u03bc` and `\u03bd` 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(\u03bc, \u03bd, C, optimizer)\n\nCompute the optimal transport plan `\u03b3` for the Monge-Kantorovich problem with source\nhistogram `\u03bc`, target histogram `\u03bd`, and cost matrix `C` of size `(length(\u03bc), length(\u03bd))`\nwhich solves\n```math\n\\\\inf_{\u03b3 \u2208 \u03a0(\u03bc, \u03bd)} \\\\langle \u03b3, 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(\u03bc, \u03bd, C, model::MOI.ModelLike)\n    # check size of cost matrix\n    n\u03bc = length(\u03bc)\n    n\u03bd = length(\u03bd)\n    size(C) == (n\u03bc, n\u03bd) || error(\"cost matrix `C` must be of size `(length(\u03bc), length(\u03bd))`\")\n    nC = length(C)\n\n    # define variables\n    x = MOI.add_variables(model, nC)\n    xmat = reshape(x, n\u03bc, n\u03bd)\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, \u03bci) in zip(axes(xmat, 1), \u03bc) # eachrow(xmat) is not available on Julia 1.0\n        f = MOI.ScalarAffineFunction(\n            [MOI.ScalarAffineTerm(one(\u03bci), xi) for xi in view(xmat, i, :)], zero(\u03bci)\n        )\n        MOI.add_constraint(model, f, MOI.EqualTo(\u03bci))\n    end\n\n    # add constraints for target\n    for (i, \u03bdi) in zip(axes(xmat, 2), \u03bd) # eachcol(xmat) is not available on Julia 1.0\n        f = MOI.ScalarAffineFunction(\n            [MOI.ScalarAffineTerm(one(\u03bdi), xi) for xi in view(xmat, :, i)], zero(\u03bdi)\n        )\n        MOI.add_constraint(model, f, MOI.EqualTo(\u03bdi))\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    \u03b3 = reshape(p, n\u03bc, n\u03bd)\n\n    return \u03b3\nend\n\n\"\"\"\n    emd2(\u03bc, \u03bd, C, optimizer; plan=nothing)\n\nCompute the optimal transport cost (a scalar) for the Monge-Kantorovich problem with source\nhistogram `\u03bc`, target histogram `\u03bd`, and cost matrix `C` of size `(length(\u03bc), length(\u03bd))`\nwhich is given by\n```math\n\\\\inf_{\u03b3 \u2208 \u03a0(\u03bc, \u03bd)} \\\\langle \u03b3, 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(\u03bc, \u03bd, C, optimizer; plan=nothing)\n    \u03b3 = if plan === nothing\n        # compute optimal transport plan\n        emd(\u03bc, \u03bd, C, optimizer)\n    else\n        # check dimensions\n        size(C) == (length(\u03bc), length(\u03bd)) ||\n            error(\"cost matrix `C` must be of size `(length(\u03bc), length(\u03bd))`\")\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(\u03b3, C)\nend\n\n###################################\n# Semidiscrete and continuous 1D OT\n###################################\n\n\"\"\"\n    ot_plan(c, \u03bc::ContinuousUnivariateDistribution, \u03bd::UnivariateDistribution)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with univariate\ndistributions `\u03bc` and `\u03bd` 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 `\u03bc` and ``F_\\\\nu^{-1}`` is the\nquantile function of `\u03bd`.\n\nSee also: [`ot_cost`](@ref), [`emd`](@ref)\n\"\"\"\nfunction ot_plan(c, \u03bc::ContinuousUnivariateDistribution, \u03bd::UnivariateDistribution)\n    # Use T instead of \u03b3 to indicate that this is a Monge map.\n    T(x) = quantile(\u03bd, cdf(\u03bc, x))\n    return T\nend\n\n\"\"\"\n    ot_cost(\n        c, \u03bc::ContinuousUnivariateDistribution, \u03bd::UnivariateDistribution; plan=nothing\n    )\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with univariate\ndistributions `\u03bc` and `\u03bd` 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 `\u03bc` and `\u03bd`,\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, \u03bc::ContinuousUnivariateDistribution, \u03bd::UnivariateDistribution; plan=nothing\n)\n    cost, _ = if plan === nothing\n        quadgk(0, 1) do q\n            return c(quantile(\u03bc, q), quantile(\u03bd, q))\n        end\n    else\n        quadgk(0, 1) do q\n            x = quantile(\u03bc, 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 `\u03bc` and `\u03bd` are expected to be iterators of the histograms where the\n# corresponding support is sorted\nfunction Discrete1DOTIterator(\u03bc, \u03bd)\n    T = Base.promote_eltype(\u03bc, \u03bd)\n    return Discrete1DOTIterator{T,typeof(\u03bc),typeof(\u03bd)}(\u03bc, \u03bd)\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, \u03bcnext, \u03bdnext)=(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 \u03bcnext === nothing || \u03bdnext === nothing\n        return nothing\n    end\n\n    # unpack next values and states of the source and target histograms\n    \u03bciter, \u03bcstate = \u03bcnext\n    \u03bditer, \u03bdstate = \u03bdnext\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(\u03bciter, \u03bditer)\n    iter = (i, j, min_iter)\n\n    # compute next state of the iterator\n    diff = max_iter - min_iter\n    state = if \u03bciter < max_iter\n        # move forward in the source histogram\n        (i + 1, j, iterate(d.mu, \u03bcstate), (diff, \u03bdstate))\n    else\n        # move forward in the target histogram\n        (i, j + 1, (diff, \u03bcstate), iterate(d.nu, \u03bdstate))\n    end\n\n    return iter, state\nend\n\n\"\"\"\n    ot_plan(c, \u03bc::DiscreteNonParametric, \u03bd::DiscreteNonParametric)\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with univariate\ndiscrete distributions `\u03bc` and `\u03bd` 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(_, \u03bc::DiscreteNonParametric, \u03bd::DiscreteNonParametric)\n    # unpack the probabilities of the two distributions\n    \u03bcprobs = probs(\u03bc)\n    \u03bdprobs = probs(\u03bd)\n\n    # create the iterator\n    # note: support of `DiscreteNonParametric` is sorted\n    iter = Discrete1DOTIterator(\u03bcprobs, \u03bdprobs)\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(\u03bcprobs, \u03bdprobs)}(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    \u03b3 = sparse(I, J, W, length(\u03bcprobs), length(\u03bdprobs))\n\n    return \u03b3\nend\n\n\"\"\"\n    ot_cost(\n        c, \u03bc::DiscreteNonParametric, \u03bd::DiscreteNonParametric; plan=nothing\n    )\n\nCompute the optimal transport cost for the Monge-Kantorovich problem with discrete\nunivariate distributions `\u03bc` and `\u03bd` 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, \u03bc::DiscreteNonParametric, \u03bd::DiscreteNonParametric; plan=nothing)\n    return _ot_cost(c, \u03bc, \u03bd, plan)\nend\n\n# compute cost from scratch if no plan is provided\nfunction _ot_cost(c, \u03bc::DiscreteNonParametric, \u03bd::DiscreteNonParametric, ::Nothing)\n    # unpack the probabilities of the two distributions\n    \u03bcprobs = probs(\u03bc)\n    \u03bdprobs = probs(\u03bd)\n\n    # create the iterator\n    # note: support of `DiscreteNonParametric` is sorted\n    iter = Discrete1DOTIterator(\u03bcprobs, \u03bdprobs)\n\n    # compute the cost\n    \u03bcsupport = support(\u03bc)\n    \u03bdsupport = support(\u03bd)\n    cost = sum(w * c(\u03bcsupport[i], \u03bdsupport[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, \u03bc::DiscreteNonParametric, \u03bd::DiscreteNonParametric, plan::SparseMatrixCSC\n)\n    # extract non-zero flows\n    I, J, W = findnz(plan)\n\n    # compute the cost\n    \u03bcsupport = support(\u03bc)\n    \u03bdsupport = support(\u03bd)\n    cost = sum(w * c(\u03bcsupport[i], \u03bdsupport[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, \u03bc::DiscreteNonParametric, \u03bd::DiscreteNonParametric, plan)\n    return dot(plan, StatsBase.pairwise(c, support(\u03bc), support(\u03bd)))\nend\n\n################\n# OT Gaussians\n################\n\n\"\"\"\n    ot_cost(::SqEuclidean, \u03bc::MvNormal, \u03bd::MvNormal)\n\nCompute the squared 2-Wasserstein distance between normal distributions `\u03bc` and `\u03bd` 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, \u03bc::MvNormal, \u03bd::MvNormal)\n    return sqeuclidean(\u03bc.\u03bc, \u03bd.\u03bc) + sqbures(\u03bc.\u03a3, \u03bd.\u03a3)\nend\n\n\"\"\"\n    ot_cost(::SqEuclidean, \u03bc::Normal, \u03bd::Normal)\n\nCompute the squared 2-Wasserstein distance between univariate normal distributions `\u03bc` and\n`\u03bd` as source and target marginals.\n\nSee also: [`ot_plan`](@ref), [`emd2`](@ref)\n\"\"\"\nfunction ot_cost(::SqEuclidean, \u03bc::Normal, \u03bd::Normal)\n    return (\u03bc.\u03bc - \u03bd.\u03bc)^2 + (\u03bc.\u03c3 - \u03bd.\u03c3)^2\nend\n\n\"\"\"\n    ot_plan(::SqEuclidean, \u03bc::MvNormal, \u03bd::MvNormal)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with multivariate\nnormal distributions `\u03bc` and `\u03bd` 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, \u03bc::MvNormal, \u03bd::MvNormal)\n    \u03a3\u03bcsqrt = \u03bc.\u03a3^(-1 / 2)\n    A = \u03a3\u03bcsqrt * sqrt(_gaussian_ot_A(\u03bc.\u03a3, \u03bd.\u03a3)) * \u03a3\u03bcsqrt\n    m\u03bc = \u03bc.\u03bc\n    m\u03bd = \u03bd.\u03bc\n    T(x) = m\u03bd + A * (x - m\u03bc)\n    return T\nend\n\n\"\"\"\n    ot_plan(::SqEuclidean, \u03bc::Normal, \u03bd::Normal)\n\nCompute the optimal transport plan for the Monge-Kantorovich problem with\nnormal distributions `\u03bc` and `\u03bd` 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, \u03bc::Normal, \u03bd::Normal)\n    m\u03bc = \u03bc.\u03bc\n    m\u03bd = \u03bd.\u03bc\n    a = \u03bd.\u03c3 / \u03bc.\u03c3\n    T(x) = m\u03bd + a * (x - m\u03bc)\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. `\u03bb` 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    \u03bb::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, \u03bb::U = first(opt.\u03bb);\n    maxiter = maximum(size(A)), abstol::U = eps(eltype(T)),\n    progress = nothing, kwargs...) where {T,U}\n\n    smallinds = abs.(X) .<= \u03bb\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) .<= \u03bb\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, \u03bb)\n\n            ProgressMeter.next!(\n            progress;\n            showvalues = [\n                (:Threshold, \u03bb), (: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, \u03bb; 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 SweepOperator, Test\n\n# setup\nn, p = 1000, 10\nx = randn(n, p)\nxtx = x'x\n\n@testset \"Sweep One By One\" begin\n    A = deepcopy(xtx)\n    B = deepcopy(xtx)\n    for j in 1:p\n        sweep!(A, j)\n        sweep!(A, j, true)\n    end\n    @test A \u2248 B\n\n    A = deepcopy(xtx)\n    B = deepcopy(xtx)\n    for j in 1:p\n        sweep!(A, j, true)\n    end\n    for j in 1:p\n        sweep!(A, j, true)\n    end\n    @test A \u2248 B\nend\n\n@testset \"Sweep All\" begin\n    A = deepcopy(xtx)\n    B = deepcopy(xtx)\n    sweep!(A, 1:p)\n    sweep!(A, 1:p, true)\n    @test A \u2248 B\nend\n\n@testset \"Linear Regression\" begin\n    y = x * collect(1.:p) + randn(n)\n    xy = [x y]\n    xytxy = xy'xy\n    sweep!(xytxy, 1:p)\n    @test xytxy[1:p, end] \u2248 x\\y\nend\n", "meta": {"hexsha": "54b604f93bc33825ff673b471adedebd30343773", "size": 715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SweepOperator.jl-7522ee7d-7047-56d0-94d9-4bc626e7058d", "max_stars_repo_head_hexsha": "0ea4098506b80a0d74c9ac3f687e25ff1d5f898f", "max_stars_repo_licenses": ["MIT"], "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/SweepOperator.jl-7522ee7d-7047-56d0-94d9-4bc626e7058d", "max_issues_repo_head_hexsha": "0ea4098506b80a0d74c9ac3f687e25ff1d5f898f", "max_issues_repo_licenses": ["MIT"], "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/SweepOperator.jl-7522ee7d-7047-56d0-94d9-4bc626e7058d", "max_forks_repo_head_hexsha": "0ea4098506b80a0d74c9ac3f687e25ff1d5f898f", "max_forks_repo_licenses": ["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.6279069767, "max_line_length": 36, "alphanum_fraction": 0.5188811189, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7691912377583946}}
{"text": "module TestGrad\n    using Calculus2\n    using Base.Test\n\n    # multivariate test function\n    function f(x::Vector)\n        return sin(x[1]) + cos(x[2])\n    end\n    x = [0.0, 0.0]\n    gr = similar(x)\n\n    # Test in-place multivariate grad!\n    grad!(gr, f, x)\n    @test norm(gr - [cos(0.0), -sin(0.0)]) < 10e-8\n    fill!(gr, 0.0)\n\n    grad!(gr, f, x, method = :ad)\n    @test norm(gr - [cos(0.0), -sin(0.0)]) < 10e-8\n    fill!(gr, 0.0)\n\n    \u2207!(gr, f, x)\n    @test norm(gr - [cos(0.0), -sin(0.0)]) < 10e-8\n    fill!(gr, 0.0)\n\n    # Test pure multivariate grad\n    @test norm(grad(f, x) - [cos(0.0), sin(0.0)]) < 10e-8\n    @test norm(\u2207(f, x) - [cos(0.0), sin(0.0)]) < 10e-8\n\n    # Test in-place multivariate gradfunc!\n    \u2207f! = gradfunc!(f, x)\n    \u2207f!(gr, x)\n    @test norm(gr - [cos(0.0), sin(0.0)]) < 10e-8\n\n    # Test in-place multivariate gradfunc!\n    \u2207f! = gradfunc!(f, x, method = :ad)\n    \u2207f!(gr, x)\n    @test norm(gr - [cos(0.0), sin(0.0)]) < 10e-8\n\n    # Test pure multivariate gradfunc\n    \u2207f = gradfunc(f, x)\n    @test norm(\u2207f(x) - [cos(0.0), sin(0.0)]) < 10e-8\n\n    # Test pure univariate grad\n    @test isapprox(grad(sin, 0.0), cos(0.0))\n    @test isapprox(grad(sin, 0.0, method = :ad), cos(0.0))\n\n    # Test pure univariate gradfunc\n    @test isapprox(gradfunc(sin, 0.0)(0.0), cos(0.0))\n    @test isapprox(gradfunc(sin, 0.0, method = :ad)(0.0), cos(0.0))\n\n    # TODO: Test automatic differentation\n    # TODO: Test symbolic differentiation\n    # TODO: Test direction options\nend\n", "meta": {"hexsha": "ddeb3b725f46f0660d5716b0ea3c0d4c1f6c18c6", "size": 1491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/api/grad.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": "test/api/grad.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": "test/api/grad.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": 27.1090909091, "max_line_length": 67, "alphanum_fraction": 0.5513078471, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7691912365788935}}
{"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": "#Test library imports\nusing Test\n\n#Arithmetic library imports\nusing IntervalArithmetic\n\n#Preamble\nsetprecision(53)\nsetprecision(Interval, Float64)\nsetrounding(Interval, :tight)\n# Set full format, and show decorations\n@format full\n@testset \"rational_power_test\" begin\n        @test ^(\u2205, 1//3) == \u2205\n        @test ^(1 .. 8, 1//3) == Interval(1, 2)\n        @test ^(2 .. 8, 1//3) \u2287  Interval(2^(1//3), 2)\n        @test ^(1 .. 9, 1//3) \u2287  Interval(1, 9^(1//3))\n        @test ^(2 .. 9, 1//3) \u2287  Interval(2^(1//3), 9^(1//3))\n        @test ^(-1 .. 8, 1//3) == Interval(0, 2)\n        @test ^(-2 .. 8, 1//3) \u2287  Interval(0, 2)\n        @test ^(-1 .. 9, 1//3) \u2287  Interval(0, 9^(1//3))\n        @test ^(-2 .. 9, 1//3) \u2287  Interval(0, 9^(1//3))\n        @test ^(1 .. 8, -1//3) == Interval(0.5, 1)\n        @test ^(2 .. 8, -1//3) \u2287  Interval(0.5, 2^(-1//3))\n        @test ^(1 .. 9, -1//3) \u2287  Interval(9^(-1//3), 1)\n        @test ^(2 .. 9, -1//3) \u2287  Interval(9^(-1//3), 2^(-1//3))\n        @test ^(-1 .. 8, -1//3) == Interval(0.5, Inf)\n        @test ^(-2 .. 8, -1//3) \u2287  Interval(0.5, Inf)\n        @test ^(-1 .. 9, -1//3) \u2287  Interval(9^(-1//3), Inf)\n        @test ^(-2 .. 9, -1//3) \u2287  Interval(9^(-1//3), Inf)\n        @test ^(-2 .. 4 , 1//2) == Interval(0, 2)\n        @test ^(-2 .. 8 , 1//3) == Interval(0, 2)\n        @test ^(-8 .. -2 , 1//3) == \u2205\n        @test ^(-8 .. -2 , 1//2) == \u2205\n        @test ^(-8 .. -2 , -1//3) == \u2205\n        @test ^(-8 .. -2 , -1//2) == \u2205\n        @test ^(\u2205, 2//3) == \u2205\n        @test ^(1 .. 8, 2//3) == Interval(1, 4)\n        @test ^(2 .. 8, 2//3) \u2287  Interval(2^(2//3), 4)\n        @test ^(1 .. 9, 2//3) \u2287  Interval(1, 9^(2//3))\n        @test ^(2 .. 9, 2//3) \u2287  Interval(2^(2//3), 9^(2//3))\n        @test ^(-1 .. 8, 2//3) == Interval(0, 4)\n        @test ^(-2 .. 8, 2//3) \u2287  Interval(0, 4)\n        @test ^(-1 .. 9, 2//3) \u2287  Interval(0, 9^(2//3))\n        @test ^(-2 .. 9, 2//3) \u2287  Interval(0, 9^(2//3))\n        @test ^(1 .. 8, -2//3) == Interval(0.25, 1)\n        @test ^(2 .. 8, -2//3) \u2287  Interval(0.25, 2^(-2//3))\n        @test ^(1 .. 9, -2//3) \u2287  Interval(9^(-2//3), 1)\n        @test ^(2 .. 9, -2//3) \u2287  Interval(9^(-2//3), 2^(-2//3))\n        @test ^(-1 .. 8, -2//3) == Interval(0.25, Inf)\n        @test ^(-2 .. 8, -2//3) \u2287  Interval(0.25, Inf)\n        @test ^(-1 .. 9, -2//3) \u2287  Interval(9^(-2//3), Inf)\n        @test ^(-2 .. 9, -2//3) \u2287  Interval(9^(-2//3), Inf)\n        @test ^(-2 .. 4 , 3//2) == Interval(0, 8)\n        @test ^(-2 .. 8 , 2//3) == Interval(0, 4)\n        @test ^(-8 .. -2 , 2//3) == \u2205\n        @test ^(-8 .. -2 , 3//2) == \u2205\n        @test ^(-8 .. -2 , -2//3) == \u2205\n        @test ^(-8 .. -2 , -3//2) == \u2205\nend\n", "meta": {"hexsha": "c1863a7fe0ee6e831170167dff2ee2febd3c9f73", "size": 2623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interval_tests/power.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": "test/interval_tests/power.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": "test/interval_tests/power.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": 43.0, "max_line_length": 64, "alphanum_fraction": 0.3896301944, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7691694692539989}}
{"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    \u0394 = bx_ax * dy_cy - by_ay * dx_cx\n    if abs(\u0394) < 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) / \u0394\n        s = (ay_cy * bx_ax - ax_cx * by_ay) / \u0394\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(\u03c0 * (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 DrWatson\n@quickactivate \"StatReth\"\n\n# %%\n# Bayes: Pr(Earth|Land) = Pr(Land|Earth) * Pr(Earth) / Pr(Land)\n\np_land_earth = 1 - 0.7\np_land_mars = 1.0\np_earth = 0.5\np_land = p_land_earth * p_earth + p_land_mars * (1 - p_earth)\n\np_earth_land = p_land_earth * p_earth / p_land\n", "meta": {"hexsha": "f3f53f7442f02b10c517a4a9325aefafc8f63c05", "size": 277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch02/2M3.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/2M3.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/2M3.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": 21.3076923077, "max_line_length": 63, "alphanum_fraction": 0.6931407942, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7691694560338296}}
{"text": "using DelimitedFiles\n\ninput = readdlm(ARGS[1], ' ', Int, '\\n');\n\n# Part 1\nfuel_required(mass) = (mass \u00f7 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'\u2248omega(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,\u03c3=1)\n\tv = 1/2 .+ \u03c3*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 \u2248 V\n\"\"\"\nfunction williamson(V)\n\tn, \u03a9 = _will_init(V)\n\tiv12 = inv(sqrt(Symmetric(V)))\n\tJ = iv12*\u03a9*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, \u03a9*iS*\u03a9\nend\n\n\"\"\"\n\tD,S = williamsonNew(V)\n\n\tfind the Williamson decomposition such that \n\tS'*wdiag(D)*S \u2248 V\n\tnew algorithm.\n\"\"\"\nfunction williamsonNew(V)\n\tn, \u03a9 = _will_init(V)\n\t\u03bb = sort(real(eigvals(V*\u03a9*1im)))[n+1:2n]\n\tS = zeros(2n,2n)\n    for m=1:n\n\t    denom = \u03bb[m]*prod(\u03bb[k]^2-\u03bb[m]^2 for k=1:n if k!=m) \n        V\u03bb = complex.(V)-(1im*\u03bb[m])*\u03a9\n\t    minorden(k) = det(view(V\u03bb,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\u03bb, 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": "\nusing DelimitedFiles\nusing Random\nusing LinearAlgebra\n\nimport Base: getindex, copy;\n\nexport euclidean_distance, mean_square_error, root_mean_square_error,\n        mean_error, manhattan_distance, mean_boolean_error, hamming_distance, gaussian,\n        DataSet, set_problem, attribute_index, check_dataset_fields,\n        check_example, update_values, add_example, remove_examples, sanitize, summarize, copy,\n        classes_to_numbers, split_values_by_classes, find_means_and_deviations,\n        AbstractCountingProbabilityDistribution,\n        CountingProbabilityDistribution, add, smooth_for_observation, getindex, top, sample,\n        AbstractLearner, PluralityLearner, predict,\n        AbstractNaiveBayesModel, NaiveBayesLearner, NaiveBayesSimpleModel,\n        NaiveBayesDiscreteModel, NaiveBayesContinuousModel, NearestNeighborLearner,\n        truncated_svd,\n        AbstractDecisionTreeNode, DecisionLeafNode, DecisionForkNode, classify,\n        DecisionTreeLearner, plurality_value,\n        RandomForest, data_bagging, feature_bagging,\n        DecisionListLearner, decision_list_learning,\n        NeuralNetworkUnit, NeuralNetworkLearner, neural_network,\n        back_propagation_learning, random_weights,\n        PerceptronLearner, EnsembleLearner,\n        weighted_mode, AdaBoostLearner, adaboost!, weighted_replicate,\n        partition_dataset, cross_validation, cross_validation_wrapper,\n        RestaurantDataSet, SyntheticRestaurantDataSet,\n        MajorityDataSet, ParityDataSet, XorDataSet, ContinuousXorDataSet;\n\nfunction euclidean_distance(X::AbstractVector, Y::AbstractVector)\n    return sqrt(sum(((x - y)^2) for (x, y) in zip(X, Y)));\nend\n\nfunction mean_square_error(X::AbstractVector, Y::AbstractVector)\n    return mean(((x - y)^2) for (x, y) in zip(X, Y));\nend\n\nfunction root_mean_square_error(X::AbstractVector, Y::AbstractVector)\n    return sqrt(mean_square_error(X, Y));\nend\n\nfunction mean_error(X::AbstractVector, Y::AbstractVector)\n    return mean(abs(x - y) for (x, y) in zip(X, Y));\nend\n\nfunction manhattan_distance(X::AbstractVector, Y::AbstractVector)\n    return sum(abs(x - y) for (x, y) in zip(X, Y));\nend\n\nfunction mean_boolean_error(X::AbstractVector, Y::AbstractVector)\n    return mean((x != y) for (x, y) in zip(X, Y));\nend\n\nfunction hamming_distance(X::AbstractVector, Y::AbstractVector)\n    return sum((x != y) for (x, y) in zip(X, Y));\nend\n\n\"\"\"\n    gaussian(mean::Float64, standard_deviation::Float64, x::Number)\n\nReturn the probability density of the gaussian distribution for variable 'x' given\nthe mean 'mean' and standard deviation 'standard_deviation'.\n\"\"\"\nfunction gaussian(mean::Number, standard_deviation::Number, x::Number)\n    return ((Float64(1)/(sqrt(2 * pi) * Float64(standard_deviation))) *\n            (Base.MathConstants.e^(-0.5*((Float64(x) - Float64(mean))/Float64(standard_deviation))^2)));\nend\n\n#=\n\n    DataSet is a data set used by machine learning algorithms.\n\n=#\nmutable struct DataSet\n    name::String\n    source::String\n    examples::AbstractMatrix\n    attributes::AbstractVector\n    attributes_names::AbstractVector\n    values::AbstractVector\n    exclude::AbstractVector\n    distance::Function\n    inputs::AbstractVector\n    target::Int64\n\n    function DataSet(;name::String=\"\", source::String=\"\", attributes::Union{Nothing, AbstractVector}=nothing,\n                    attributes_names::Union{Nothing, String, AbstractVector}=nothing,\n                    examples::Union{Nothing, String, AbstractMatrix}=nothing,\n                    values::Union{Nothing, AbstractVector}=nothing,\n                    inputs::Union{Nothing, String, AbstractVector}=nothing, target::Union{Int64, String}=-1,\n                    exclude::AbstractVector=[], distance::Function=mean_boolean_error)\n        # Use a matrix instead of array of arrays\n        local examples_array::AbstractMatrix;\n        if (typeof(examples) <: String)\n            examples_array = readdlm(examples, ',');\n        elseif (typeof(examples) <: Nothing)\n            # 'name'.csv must be in current directory.\n            examples_array = readdlm(name*\".csv\", ',');\n        else\n            examples_array = examples;\n        end\n        examples_array = map((function(element)\n                                if (typeof(element) <: AbstractString)\n                                    return strip(element);\n                                else\n                                    return element;\n                                end\n                            end),\n                            examples_array);\n        local attributes_array::AbstractVector;\n        if (typeof(attributes) <: Nothing)\n            attributes_array = collect(1:getindex(size(examples_array), 2));\n        else\n            attributes_array = attributes;\n        end\n        local attributes_names_array::AbstractVector;\n        if (typeof(attributes_names) <: String)\n            attributes_names_array = map(String, split(attributes_names));\n        elseif (!(typeof(attributes_names) <: Nothing) && (length(attributes_names) != 0))\n            attributes_names_array = attributes_names;\n        else\n            attributes_names_array = attributes_array;\n        end\n        local values_is_set::Bool;\n        local new_values::AbstractVector;\n        if (typeof(values) <: Nothing)\n            values_is_set = false;\n            new_values = [];\n        else\n            values_is_set = true;\n            new_values = values;\n        end\n\n        # Construct new DataSet without 'inputs' and 'target' fields.\n        local ds::DataSet = new(name, source, examples_array, attributes_array, attributes_names_array,\n                                new_values, exclude, distance);\n\n        # Set 'inputs' and 'target' fields of newly constructed DataSet.\n        set_problem(ds, target, inputs, exclude);\n        check_dataset_fields(ds, values_is_set);\n\n        return ds;\n    end\n\n    function DataSet(name::String,\n                    source::String,\n                    examples::AbstractMatrix,\n                    attributes::AbstractVector,\n                    attributes_names::AbstractVector,\n                    values::AbstractVector,\n                    exclude::AbstractVector,\n                    distance::Function,\n                    inputs::AbstractVector,\n                    target::Int64)\n        return new(name, source, examples, attributes, attributes_names, values, exclude, distance, inputs, target);\n    end\nend\n\nfunction set_problem(ds::DataSet, target::Int64, inputs::Nothing, exclude::AbstractVector)\n    ds.target = attribute_index(ds, target);\n    local mapped_exclude::AbstractVector = map(attribute_index, (ds for i in exclude), exclude);\n    ds.inputs = collect(a for a in ds.attributes if ((a != ds.target) && (!(a in mapped_exclude))));\n    if (length(ds.values) == 0)\n        update_values(ds);\n    end\n    nothing;\nend\n\nfunction set_problem(ds::DataSet, target::Int64, inputs::AbstractVector, exclude::AbstractVector)\n    ds.target = attribute_index(ds, target);\n    ds.inputs = removeall(inputs, ds.target);\n    if (length(ds.values) == 0)\n        update_values(ds);\n    end\n    nothing;\nend\n\nfunction set_problem(ds::DataSet, target::String, inputs::Nothing, exclude::AbstractVector)\n    ds.target = attribute_index(ds, target);\n    local mapped_exclude::AbstractVector = map(attribute_index, (ds for i in exclude), exclude);\n    ds.inputs = collect(a for a in ds.attributes if ((a != ds.target) && (!(a in mapped_exclude))));\n    if (length(ds.values) == 0)\n        update_values(ds);\n    end\n    nothing;\nend\n\nfunction set_problem(ds::DataSet, target::String, inputs::AbstractVector, exclude::AbstractVector)\n    ds.target = attribute_index(ds, target);\n    ds.inputs = removeall(inputs, ds.target);\n    if (length(ds.values) == 0)\n        update_values(ds);\n    end\n    nothing;\nend\n\nfunction attribute_index(ds::DataSet, attribute::String)\n    return utils.index(ds.attributes_names, attribute);\nend\n\nfunction attribute_index(ds::DataSet, attribute::Int64)\n    # Julia counts from 1.\n    if (attribute < 0)\n        return length(ds.attributes) + attribute + 1;\n    elseif (attribute > 0)\n        return attribute;\n    else\n        error(\"attribute_index: \\\"\", attribute, \"\\\" is not a valid index for an array!\");\n    end\nend\n\nfunction check_dataset_fields(ds::DataSet, values_bool::Bool)\n    if (length(ds.attributes_names) != length(ds.attributes))\n        error(\"check_dataset_fields(): The lengths of 'attributes_names' and 'attributes' must match!\");\n    elseif (!(ds.target in ds.attributes))\n        error(\"check_dataset_fields(): The target attribute was not found in 'attributes'!\");\n    elseif (ds.target in ds.inputs)\n        error(\"check_dataset_fields(): The target attribute should not be in the inputs!\");\n    elseif (!issubset(Set(ds.inputs), Set(ds.attributes)))\n        error(\"check_dataset_fields(): The 'inputs' field must be a subset of 'attributes'!\");\n    end\n    if (values_bool)\n        map(check_example, (ds for i in ds.examples), ds.examples);\n    end\n    nothing;\nend\n\nfunction check_example(ds::DataSet, example::AbstractVector)\n    if (length(ds.values) != 0)\n        for attribute in ds.attributes\n            if (!(example[attribute] in ds.values[attribute]))\n                error(\"check_example(): Found bad value \", example[attribute], \" for attribute \", \n                        ds.attribute_names[attribute], \" in \", example, \"!\");\n            end\n        end\n    end\n    nothing;\nend\n\nfunction check_example(ds::DataSet, example::AbstractMatrix)\n    if (length(ds.values) != 0)\n        for attribute in ds.attributes\n            if (!(example[attribute, :] in ds.values[attribute]))\n                error(\"check_example(): Found bad value \", example[attribute, :], \" for attribute \", \n                        ds.attribute_names[attribute], \" in \", example, \"!\");\n            end\n        end\n    end\n    nothing;\nend\n\nfunction update_values(ds::DataSet)\n    ds.values = collect(collect(Set(ds.examples[:, i])) for i in 1:size(ds.examples)[2]);\n    nothing;\nend\n\nfunction add_example(ds::DataSet, example::AbstractVector)\n    check_example(ds, example);\n    vcat(ds.examples, transpose(example));\n    nothing;\nend\n\nfunction remove_examples(ds::DataSet)\n    local updated_examples::AbstractVector = [];\n    for i in size(ds.examples)[1]\n        if (!(\"\" in ds.examples[i, :]))\n            push!(update_examples, transpose(ds.examples[i, :]));\n        end\n    end\n    ds.examples = reduce(vcat, Array{Any, 2}(undef, 0, 0), updated_examples);\n    update_values(ds);\nend\n\nfunction remove_examples(ds::DataSet, value::String)\n    local updated_examples::AbstractVector = [];\n    for i in size(ds.examples)[1]\n        if (!(value in ds.examples[i, :]))\n            push!(update_examples, transpose(ds.examples[i, :]));\n        end\n    end\n    ds.examples = reduce(vcat, Array{Any, 2}(undef, 0, 0), updated_examples);\n    update_values(ds);\nend\n\n\"\"\"\n    sanitize(ds::DataSet, example::AbstractVector)\n\nReturn a copy of the given array 'example', such that non-input attributes are removed.\n\"\"\"\nfunction sanitize(ds::DataSet, example::AbstractVector)\n    local sanitized_example::AbstractVector = [];\n    for (i, example_item) in enumerate(example)\n        if (i in ds.inputs)\n            push!(sanitized_example, example_item);\n        end\n    end\n    return sanitized_example;\nend\n\n\"\"\"\n    classes_to_numbers(ds::DataSet, classes::Nothing)\n    classes_to_numbers(ds::DataSet, classes::AbstractVector)\n\nSet the classifications of each example in ds.examples as numbers based on the given 'classes'.\n\"\"\"\nfunction classes_to_numbers(ds::DataSet, classes::Nothing)\n    local new_classes::AbstractVector = sort(ds.values[ds.target]);\n    for i in 1:size(ds.examples)[1]\n        local index_val::Int64 = utils.index(new_classes, ds.examples[i, ds.target]);\n        if (index_val == -1)\n            error(\"classes_to_numbers(): Could not find \", ds.examples[i, ds.target], \" in \", new_classes, \"!\");\n        end\n        ds.examples[i, ds.target] = index_val;\n    end\n    nothing;\nend\n\nfunction classes_to_numbers(ds::DataSet, classes::AbstractVector)\n    local new_classes::AbstractVector;\n    if (length(classes) == 0)\n        new_classes = sort(ds.values[ds.target]);\n    else\n        new_classes = classes;\n    end\n    for i in 1:size(ds.examples)[1]\n        local index_val::Int64 = utils.index(new_classes, ds.examples[i, ds.target]);\n        if (index_val == -1)\n            error(\"classes_to_numbers(): Could not find \", ds.examples[i, ds.target], \" in \", new_classes, \"!\");\n        end\n        ds.examples[i, ds.target] = index_val;\n    end\n    nothing;\nend\n\nfunction split_values_by_classes(ds::DataSet)\n    local buckets::Dict = Dict();\n    local target_names::AbstractVector = ds.values[ds.target];\n\n    for example in (ds.examples[i, :] for i in 1:size(ds.examples)[1])\n        local item::AbstractVector = collect(attribute for attribute in example\n                                            if (!(attribute in target_names)));\n        push!(get!(buckets, example[ds.target], []), item);\n    end\n\n    return buckets;\nend\n\nfunction find_means_and_deviations(ds::DataSet)\n    local target_names::AbstractVector = ds.values[ds.target];\n    local feature_numbers::Int64 = length(ds.inputs);\n    local item_buckets::Dict = split_values_by_classes(ds);\n    local means::Dict = Dict();\n    local deviations::Dict = Dict();\n    local key_initial_value::AbstractVector = collect(0.0 for i in 1:feature_numbers);\n\n    for target_name in target_names\n        local features = collect(Array{Float64, 1}() for i in 1:feature_numbers);\n        for item in item_buckets[target_name]\n            for i in 1:feature_numbers\n                push!(features[i], item[i]);\n            end\n        end\n        for i in 1:feature_numbers\n            get!(means, target_name, copy(key_initial_value))[i] = mean(features[i]);\n            get!(deviations, target_name, copy(key_initial_value))[i] = std(features[i]);\n        end\n    end\n    return means, deviations;\nend\n\nfunction summarize(ds::DataSet)\n    return @sprintf(\"<DataSet(%s): %d examples, %d attributes>\", ds.name, length(ds.examples), length(ds.attributes));\nend\n\ncopy(ds::DataSet) = DataSet(identity(ds.name),\n                            identity(ds.source),\n                            copy(ds.examples),\n                            copy(ds.attributes),\n                            copy(ds.attributes_names),\n                            copy(ds.values),\n                            copy(ds.exclude),\n                            ds.distance,\n                            copy(ds.inputs),\n                            identity(ds.target));\n\nabstract type AbstractCountingProbabilityDistribution end;\n\n#=\n\n    CountingProbabilityDistribution is a probability distribution for counting\n\n    observations. Unlike the other implementations of AbstractProbabilityDistribution,\n\n    CountingProbabilityDistribution calculates the key's probability when\n\n    accessing the CountingProbabilityDistribution by the given key.\n\n=#\nmutable struct CountingProbabilityDistribution <: AbstractCountingProbabilityDistribution\n    dict::Dict\n    number_of_observations::Int64\n    default::Int64\n    sample_function::Union{Nothing, Function}\n\n    function CountingProbabilityDistribution(observations::AbstractVector; default::Int64=0)\n        local cpd::CountingProbabilityDistribution = new(Dict(), 0, default, nothing);\n        for observation in observations\n            add(cpd, observation);\n        end\n        return cpd;\n    end\n\n    function CountingProbabilityDistribution(; default::Int64=0)\n        local cpd::CountingProbabilityDistribution = new(Dict(), 0, default, nothing);\n        return cpd;\n    end\nend\n\n\"\"\"\n    add(cpd::T, observation) where {T <: AbstractCountingProbabilityDistribution}\n\nAdd observation 'observation' to the probability distribution 'cpd'.\n\"\"\"\nfunction add(cpd::T, observation) where {T <: AbstractCountingProbabilityDistribution}\n    smooth_for_observation(cpd, observation);\n    cpd.dict[observation] = cpd.dict[observation] + 1;\n    cpd.number_of_observations = cpd.number_of_observations + 1;\n    cpd.sample_function = nothing;\n    nothing;\nend\n\n\"\"\"\n    smooth_for_observation(cpd::T, observation) where {T <: AbstractCountingProbabilityDistribution}\n\nInitialize observation 'observation' in the distribution 'cpd' if the observation doesn't\nexist in the distribution yet.\n\"\"\"\nfunction smooth_for_observation(cpd::T, observation) where {T <: AbstractCountingProbabilityDistribution}\n    if (!(observation in keys(cpd.dict)))\n        cpd.dict[observation] = cpd.default;\n        cpd.number_of_observations = cpd.number_of_observations + cpd.default;\n        cpd.sample_function = nothing;\n    end\n    nothing;\nend\n\n\"\"\"\n    getindex(cpd::T, key) where {T <: AbstractCountingProbabilityDistribution}\n\nReturn the probability of the given 'key'.\n\"\"\"\nfunction getindex(cpd::T, key) where {T <: AbstractCountingProbabilityDistribution}\n    smooth_for_observation(cpd, key);\n    return (Float64(cpd.dict[key]) / Float64(cpd.number_of_observations));\nend\n\n\"\"\"\n    top(cpd::T, n::Int64) where {T <: AbstractCountingProbabilityDistribution}\n\nReturn an array of (observation_count, observation) tuples such that the array\ndoes not exceed length 'n'.\n\"\"\"\nfunction top(cpd::T, n::Int64) where {T <: AbstractCountingProbabilityDistribution}\n    local observations::AbstractVector = sort(collect(reverse((i...,)) for i in cpd.dict),\n                                                lt=(function(p1::Tuple{Number, Any}, p2::Tuple{Number, Any})\n                                                        return (p1[1] > p2[1]);\n                                                    end));\n    if (length(observations) <= n)\n        return observations;\n    else\n        return observations[1:n];\n    end\nend\n\n\"\"\"\n    sample(cpd::CountingProbabilityDistribution)\n\nReturn a random sample from the probability distribution 'cpd'.\n\"\"\"\nfunction sample(cpd::CountingProbabilityDistribution)\n    if (cpd.sample_function === nothing)\n        cpd.sample_function = weighted_sampler(collect(keys(cpd.dict)), collect(values(cpd.dict)));\n    end\n    return cpd.sample_function();\nend\n\nabstract type AbstractLearner end;\n\nstruct PluralityLearner{T} <: AbstractLearner\n    most_popular::T\n\n    function PluralityLearner{T}(mp::T) where T\n        return new(mp);\n    end\nend\n\nfunction PluralityLearner(ds::DataSet)\n    most_popular = mode(example[ds.target]\n                        for example in (ds.examples[i, :] for i in 1:size(ds.examples)[1]));\n    return PluralityLearner{typeof(most_popular)}(most_popular);\nend\n\nfunction predict(pl::PluralityLearner, example::AbstractVector)\n    return pl.most_popular;\nend\n\nabstract type AbstractNaiveBayesModel end;\n\n#=\n\n    NaiveBayesLearner is a learner that chooses to uses either a continuous model, discrete model,\n\n    or a conditional probability model (if 'simple' keyword is given as true).\n\n=#\nstruct NaiveBayesLearner <: AbstractLearner\n    model::AbstractNaiveBayesModel\n\n    function NaiveBayesLearner(ds::DataSet; continuous::Bool=true)\n        if (continuous)\n            return new(NaiveBayesContinuousModel(ds));\n        else\n            return new(NaiveBayesDiscreteModel(ds));\n        end\n    end\n\n    # The expected type of distribution 'd' is Dict.\n    function NaiveBayesLearner(d::Dict; simple::Bool=false)\n        if (simple)\n            return new(NaiveBayesSimpleModel(d));\n        else\n            error(\"NaiveBayesLearner(): The values of 'simple' should be true! \"*\n                    \"If the expected model is either continuous or discrete, try passing a DataSet rather than an Dict!\");\n        end\n    end\nend\n\nfunction predict(nbl::NaiveBayesLearner, example::AbstractVector)\n    return predict(nbl.model, example);\nend\n\nfunction predict(nbl::NaiveBayesLearner, example::String)\n    return predict(nbl.model, example);\nend\n\n#=\n\n    NaiveBayesSimpleModel is a simple naive bayes classifier that is initialized with\n\n    a dictionary of classifications to CountingProbabilityDistributions.\n\n    Each key-value pair of the dictionary is in the form:\n    \n        (classification, probability)=>CountingProbabilityDistribution\n\n=#\nstruct NaiveBayesSimpleModel <: AbstractNaiveBayesModel\n    target_distribution::Dict\n    attributes_distributions::Dict\n\n    function NaiveBayesSimpleModel(distribution::Dict)\n        return new(Dict(collect((classification, p)\n                                for (classification, p) in keys(distribution))),\n                    Dict(collect((classification, cpd)\n                                for ((classification, p), cpd) in distribution)));\n    end\nend\n\nfunction predict(nbsm::NaiveBayesSimpleModel, example::AbstractVector)\n    return argmax(collect(keys(nbsm.target_distribution)),\n                (function(target)\n                    local attribute_distribution::AbstractCountingProbabilityDistribution = nbsm.attributes_distributions[target];\n                    return (nbsm.target_distribution[target] * prod(attribute_distribution[attribute] for attribute in example));\n                end));\nend\n\nfunction predict(nbsm::NaiveBayesSimpleModel, example::String)\n    return argmax(collect(keys(nbsm.target_distribution)),\n                (function(target)\n                    local attribute_distribution::AbstractCountingProbabilityDistribution = nbsm.attributes_distributions[target];\n                    return (nbsm.target_distribution[target] * prod(attribute_distribution[attribute] for attribute in example));\n                end));\nend\n\n#=\n\n    NaiveBayesDiscreteModel contains the frequencies of the input attribute values depending\n\n    on their corresponding target value.\n\n=#\nmutable struct NaiveBayesDiscreteModel <: AbstractNaiveBayesModel\n    dataset::DataSet\n    target_values::AbstractVector\n    target_distribution::CountingProbabilityDistribution\n    attributes_distributions::Dict\n\n    function NaiveBayesDiscreteModel(ds::DataSet)\n        local nbdm::NaiveBayesDiscreteModel = new(ds,\n                                                ds.values[ds.target],\n                                                CountingProbabilityDistribution(ds.values[ds.target]));\n        nbdm.attributes_distributions = Dict(Pair((val, attribute), CountingProbabilityDistribution(ds.values[attribute]))\n                                            for val in nbdm.target_values\n                                            for attribute in ds.inputs);\n        for example in (ds.examples[i, :] for i in 1:size(ds.examples)[1])\n            target_value = example[ds.target];\n            add(nbdm.target_distribution, target_value);\n            for attribute in ds.inputs\n                add(nbdm.attributes_distributions[(target_value, attribute)], example[attribute]);\n            end\n        end\n        return nbdm;\n    end\nend\n\nfunction predict(nbdm::NaiveBayesDiscreteModel, example::AbstractVector)\n    return argmax(nbdm.target_values,\n                    (function(target_value)\n                        return (nbdm.target_distribution[target_value] *\n                                prod(nbdm.attributes_distributions[(target_value, attribute)][example[attribute]]\n                                    for attribute in nbdm.dataset.inputs));\n                    end));\nend\n\n#=\n\n    NaiveBayesContinuousModel contains the frequencies of the target values and the\n\n    mean and deviations for the input attribute values for each target value.\n\n=#\nmutable struct NaiveBayesContinuousModel <: AbstractNaiveBayesModel\n    dataset::DataSet\n    target_values::AbstractVector\n    target_distribution::CountingProbabilityDistribution\n    means::Dict\n    deviations::Dict\n\n    function NaiveBayesContinuousModel(ds::DataSet)\n        local nbcm::NaiveBayesContinuousModel = new(ds,\n                                                    ds.values[ds.target],\n                                                    CountingProbabilityDistribution(ds.values[ds.target]));\n        nbcm.means, nbcm.deviations = find_means_and_deviations(ds);\n        return nbcm;\n    end\nend\n\nfunction predict(nbcm::NaiveBayesContinuousModel, example::AbstractVector)\n    return argmax(nbcm.target_values,\n                    (function(target_value)\n                        local p::Float64 = nbcm.target_distribution[target_value];\n                        for attribute in nbcm.dataset.inputs\n                            p = p * gaussian(nbcm.means[target_value][attribute],\n                                            nbcm.deviations[target_value][attribute],\n                                            example[attribute]);\n                        end\n                        return p;\n                    end));\nend\n\n#=\n\n    NearestNeighborLearner uses the k-nearest neighbors lookup for predictions.\n\n=#\nstruct NearestNeighborLearner <: AbstractLearner\n    dataset::DataSet\n    k::Int64\n\n    function NearestNeighborLearner(ds::DataSet)\n        return new(ds, 1);\n    end\n\n    function NearestNeighborLearner(ds::DataSet, k::Int64)\n        return new(ds, k);\n    end\nend\n\nfunction nearest_neighbor_predict_isless(t1::Tuple, t2::Tuple)\n    return (t1[1] < t2[1]);\nend\n\nfunction predict(nnl::NearestNeighborLearner, example::AbstractVector)\n    local best_distances::AbstractVector = sort(collect((nnl.dataset.distance(dataset_example, example), dataset_example)\n                                                        for dataset_example in (nnl.dataset.examples[i, :] for i in 1:size(nnl.dataset.examples)[1])),\n                                                lt=nearest_neighbor_predict_isless);\n    if (length(best_distances) > nnl.k)\n        best_distances = best_distances[1:nnl.k];\n    end\n    return mode(dataset_example[nnl.dataset.target] for (distance, dataset_example) in best_distances);\nend\n\nfunction truncated_svd_gram_schmidt_orthogonalization(M::Array{T, 1}, eigenvectors_m, eigenvectors_n, m, n) where {T <: Number}\n    for ev_i_m in eigenvectors_m\n        proj_ev_i_m = (dot(M[1:n], ev_i_m) * ev_i_m)\n        M[1:n] = collect(m_i - proj_ev_i_m_i for (m_i, proj_ev_i_m_i) in zip(M[1:n], proj_ev_i_m))\n    end\n    for ev_i_n in eigenvectors_n\n        proj_ev_i_n = (dot(M[n + 1:end], ev_i_n) * ev_i_n)\n        M[n + 1:end] = collect(n_i - proj_ev_i_n_i for (n_i, proj_ev_i_n_i) in zip(M[n + 1:end], proj_ev_i_n))\n    end\n    return M\nend\n\nfunction truncated_svd_gram_schmidt_orthonormalization(M::Array{T, 1}, eigenvectors_m, eigenvectors_n, m, n) where {T <: Number}\n    M = truncated_svd_gram_schmidt_orthogonalization(M, eigenvectors_m, eigenvectors_n, m, n)\n    # normalize resulting vectors for orthonormalization\n    M = vcat(collect(m_i/norm(M[1:n]) for m_i in M[1:n]), collect(n_i/norm(M[n + 1:end]) for n_i in M[n + 1:end]))\n    return M\nend\n\n\"\"\"\n    truncated_svd(A::Array{T, 2}; num_of_eigenvalues=2, max_iterations=1000, epsilon::Float64=1e-10) where {T <: AbstractFloat}\n\nReturn the computed approximations of the left-singular vectors, right-singular vectors,\nand singular values for the given matrix 'A'.\n\nNote: This implementation of the truncated SVD uses the Gram-Schmidt process for orthogonalization, \nwhich is known for numerical instability. When computing for very small singular values, this\nfunction will return erroneous values in place of the expected singular values. \n\nFor example, 'truncated_svd([1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16], num_of_eigenvalues=4)' will\ngenerate approximations for the first 2 singular values (38.6227 and 2.07132) of the given matrix \nbut not the last 2 singular values (7.60977e-16 and 3.86064e-16) of the given matrix.\n\"\"\"\nfunction truncated_svd(A::Array{T, 2}; num_of_eigenvalues=2, max_iterations=1000, epsilon::Float64=1e-10) where {T <: AbstractFloat}\n    local m::Int = size(A, 1)\n    local n::Int = size(A, 2)\n\n    local Y::Array{T, 2} = zeros(T, (m + n), (m + n))\n    #     [0 A^T]\n    # Y = [A 0]\n    for i in 1:m\n        for j in 1:n\n            # copy A to Y\n            Y[n + i, j] = A[i, j]\n            # copy A^T to Y\n            Y[j, n + i] = A[i, j]\n        end\n    end\n\n    local eigenvectors_m::Array{Array{T, 1}} = Array{Array{T, 1}}([])\n    local eigenvectors_n::Array{Array{T, 1}} = Array{Array{T, 1}}([])\n    local eigenvalues::Array{T, 1} = Array{T, 1}([])\n\n    for ev_i in 1:num_of_eigenvalues\n        # vector of (m + n) numbers\n        X = rand(RandomDeviceInstance, T, (m + n))\n        X = truncated_svd_gram_schmidt_orthonormalization(X, eigenvectors_m, eigenvectors_n, m, n)\n        for i in 1:max_iterations\n            previous_X = X\n            X = Y*X\n            X = truncated_svd_gram_schmidt_orthonormalization(X, eigenvectors_m, eigenvectors_n, m, n)\n            # check for convergence\n            if (norm(collect(p_x_i - x_i for (p_x_i, x_i) in zip(previous_X, X))) <= epsilon)\n                break\n            end\n        end\n        projected_X = Y * X\n        new_eigenvalue = sum(projected_X)/sum(X)\n        ev_m = X[1:n]\n        ev_n = X[n + 1:end]\n        if (new_eigenvalue < 0)\n            new_eigenvalue = -new_eigenvalue\n            ev_m = -ev_m\n            ev_n = ev_n\n        end\n        push!(eigenvalues, new_eigenvalue)\n        push!(eigenvectors_m, ev_m)\n        push!(eigenvectors_n, ev_n)\n    end\n    return eigenvectors_m, eigenvectors_n, eigenvalues\nend\n\ntruncated_svd(A::Array{T, 2}; kwargs...) where {T <: Integer} = truncated_svd(map(Float64, A); kwargs...)\n\nabstract type AbstractDecisionTreeNode end;\n\nstruct DecisionLeafNode{T} <: AbstractDecisionTreeNode\n    result::T\n\n    function DecisionLeafNode{T}(result::T) where T\n        return new(result);\n    end\nend\n\nfunction classify(dl::DecisionLeafNode, example::AbstractVector)\n    return dl.result;\nend\n\nDecisionLeafNode(result) = DecisionLeafNode{typeof(result)}(result);\n\nstruct DecisionForkNode <: AbstractDecisionTreeNode\n    attribute::Int64\n    attribute_name::Union{Nothing, Int64, String}\n    default_child::Union{Nothing, DecisionLeafNode}\n    branches::Dict\n\n    function DecisionForkNode(attribute::Int64;\n                        attribute_name::Union{Int64, String, Nothing}=nothing,\n                        default_child::Union{DecisionLeafNode, Nothing}=nothing,\n                        branches::Union{Dict, Nothing}=nothing)\n        local new_attribute_name::Union{Nothing, Int64, String};\n        local new_branches::Dict;\n        if (typeof(attribute_name) <: Nothing)\n            new_attribute_name = attribute;\n        else\n            new_attribute_name = attribute_name;\n        end\n        if (typeof(branches) <: Nothing)\n            new_branches = Dict();\n        else\n            new_branches = branches;\n        end\n        return new(attribute, new_attribute_name, default_child, new_branches);\n    end\nend\n\nfunction classify(df::DecisionForkNode, example::AbstractVector)\n    attribute_value = example[df.attribute];\n    if (haskey(df.branches, attribute_value))\n        return classify(df.branches[attribute_value], example);\n    else\n        return classify(df.default_child, example);\n    end\nend\n\nfunction add(dfn::DecisionForkNode, key::Real, subtree)\n    dfn.branches[key] = subtree;\n    nothing;\nend\n\nfunction summarize(dfn::DecisionForkNode)\n    return @sprintf(\"DecisionForkNode(%s, %s, %s)\", repr(dfn.attribute), repr(dfn.attribute_name), repr(dfn.branches));\nend\n\n\"\"\"\n    information_content(values::AbstractVector)\n\nReturn the number of bits that represent the probability distribution of non-zero values in 'values'.\n\"\"\"\nfunction information_content(values::AbstractVector)\n    local probabilities::Array{Float64, 1} = normalize(removeall(values, 0), 1);\n    if (length(probabilities) == 0)\n        return Float64(0);\n    else\n        return sum((-p * log2(p)) for p in probabilities);\n    end\nend\n\nfunction information_gain_content(dataset::DataSet, examples::AbstractMatrix)\n    return information_content(collect(count((function(example)\n                                            return (example[dataset.target] == value);\n                                        end), (examples[i,:] for i in 1:size(examples)[1]))\n                                    for value in dataset.values[dataset.target]));\nend\n\n\"\"\"\n    matrix_vcat(args::Vararg)\n\nReturns an empty matrix when vcat() returns an empty vector, otherwise return vcat(args).\n\"\"\"\nfunction matrix_vcat(args::Vararg)\n    if (length(args) == 0)\n        return Array{Any, 2}(undef, 0, 0);\n    else\n        return vcat(args...,);\n    end\nend\n\n\"\"\"\n    filter_examples_by_attribute(dataset::DataSet, attribute::Int64, examples::AbstractMatrix)\n\nReturn a Base.Generator of (value_i, examples_i) tuples for each value of 'attribute'.\n\"\"\"\nfunction filter_examples_by_attribute(dataset::DataSet, attribute::Int64, examples::AbstractMatrix)\n    return ((value, matrix_vcat((reshape(ex_i, (1, length(ex_i)))\n                                                    for ex_i in (examples[i,:] for i in 1:size(examples)[1])\n                                                    if (ex_i[attribute] == value))...,))\n            for value in dataset.values[attribute]);\nend\n\n\"\"\"\n    information_gain(dataset::DataSet, attribute::Int64, examples::AbstractMatrix)\n\nReturn the expected reduction in entropy from testing the attribute 'attribute' given\nthe dataset 'dataset' and matrix 'examples'.\n\"\"\"\nfunction information_gain(dataset::DataSet, attribute::Int64, examples::AbstractMatrix)\n    local N::Float64 = Float64(size(examples)[1]);\n    local remainder::Float64 = Float64(sum(((size(examples_i)[1]/N)\n                                            * information_gain_content(dataset, examples_i)\n                                            for (value, examples_i) in filter_examples_by_attribute(dataset, attribute, examples))));\n    return (Float64(information_gain_content(dataset, examples)) - remainder);\nend\n\n\"\"\"\n    plurality_value(dataset::DataSet, examples::AbstractMatrix)\n\nReturn a DecisionLeafNode with the result field set to the most common output value\nin the given matrix 'examples' (using argmax_random_tie()). \n\"\"\"\nfunction plurality_value(dataset::DataSet, examples::AbstractMatrix)\n    return DecisionLeafNode(argmax_random_tie(dataset.values[dataset.target],\n                                            (function(value)\n                                                return count((function(example::AbstractVector)\n                                                                return (example[dataset.target] == value);\n                                                            end), (examples[i,:] for i in 1:size(examples)[1]));\n                                            end)));\nend\n\n\"\"\"\n    decision_tree_learning(dataset::DataSet, examples::AbstractMatrix, attributes::AbstractVector; parent_examples::AbstractMatrix=Array{Any, 2}(undef, 0, 0))\n\nReturn a decision tree as a DecisionLeafNode or a DecisionForkNode by applying the decision-tree\nlearning algorithm (Fig. 18.5) on the given dataset 'dataset', example matrix 'example', attributes\nvector 'attributes', and parent examples 'parent_examples'.\n\"\"\"\nfunction decision_tree_learning(dataset::DataSet, examples::AbstractMatrix, attributes::AbstractVector; parent_examples::AbstractMatrix=Array{Any, 2}(undef, 0, 0))\n    # examples is empty\n    if (size(examples)[1] == 0)\n        return plurality_value(dataset, parent_examples);\n    # examples have the same classification\n    elseif (all((example[dataset.target] == examples[1, dataset.target])\n                for example in (examples[i, :] for i in 1:size(examples)[1])))\n        return DecisionLeafNode(examples[1, dataset.target]);\n    # attributes is empty\n    elseif (length(attributes) == 0)\n        return plurality_value(dataset, parent_examples);\n    else\n        local A::Int64 = argmax_random_tie(attributes,\n                                            (function(attribute)\n                                                return information_gain(dataset, attribute, examples);\n                                            end));\n        local tree::DecisionForkNode = DecisionForkNode(A,\n                                                    attribute_name=dataset.attributes_names[A],\n                                                    default_child=plurality_value(dataset, examples));\n        for (v_k, exs) in filter_examples_by_attribute(dataset, A, examples)\n            local subtree::AbstractDecisionTreeNode = decision_tree_learning(dataset, exs, removeall(attributes, A), parent_examples=examples);\n            add(tree, v_k, subtree);\n        end\n        return tree;\n    end\nend\n\nstruct DecisionTreeLearner <: AbstractLearner\n    decision_tree::AbstractDecisionTreeNode\n\n    function DecisionTreeLearner(dataset::DataSet)\n        return new(decision_tree_learning(dataset, dataset.examples, dataset.inputs));\n    end\n\n    # The following constructor method for DecisionTreeLearner is to be used with\n    # cross_validation() for a decision tree constructed in a breadth-first fashion.\n    #\n    # The breadth-first decision_tree_learning() method is not implemented yet.\n    function DecisionTreeLearner(dataset::DataSet, node_count::Int64)\n        return new(decision_tree_learning(dataset, dataset.examples, dataset.inputs, node_count));\n    end\nend\n\nfunction predict(dtl::DecisionTreeLearner, example::AbstractVector)\n    return classify(dtl.decision_tree, example);\nend\n\nfunction data_bagging(dataset::DataSet)\n    local n::Int64 = size(dataset.examples)[1];\n    local sampled_examples::AbstractVector = weighted_sample_with_replacement(collect(dataset.examples[i, :]\n                                                                                    for i in 1:size(dataset.examples)[1]), ones(n), n);\n    return reduce(vcat, (reshape(sample_example, (1, length(sample_example)))\n                        for sample_example in sampled_examples));\nend\n\nfunction data_bagging(dataset::DataSet, m::Int64)\n    local n::Int64 = size(dataset.examples)[1];\n    local sampled_examples::AbstractVector = weighted_sample_with_replacement(collect(dataset.examples[i, :]\n                                                                                    for i in 1:size(dataset.examples)[1]), ones(n), m);\n    return reduce(vcat, (reshape(sample_example, (1, length(sample_example)))\n                        for sample_example in sampled_examples));\nend\n\nfunction feature_bagging(dataset::DataSet; p::Float64=0.7)\n    local inputs::AbstractVector = collect(i for i in dataset.inputs if (rand(RandomDeviceInstance) < p));\n    if (length(inputs) == 0)\n        return dataset.inputs;\n    else\n        return inputs;\n    end\nend\n\nstruct RandomForest <: AbstractLearner\n    predictors::Array{DecisionTreeLearner, 1}\n\n    function RandomForest(dataset::DataSet; n::Int64=5)\n        local predictors::Array{DecisionTreeLearner, 1} = collect(DecisionTreeLearner(DataSet(examples=data_bagging(dataset),\n                                                                                                    attributes=dataset.attributes,\n                                                                                                    attributes_names=dataset.attributes_names,\n                                                                                                    target=dataset.target,\n                                                                                                    inputs=feature_bagging(dataset)))\n                                                                        for i in 1:n);\n        return new(predictors);\n    end\nend\n\nfunction predict(rf::RandomForest, example::AbstractVector)\n    return mode(predict(predictor, example) for predictor in rf.predictors);\nend\n\nfunction find_test_outcomes_from_examples(ds::DataSet, examples::Set)\n    println(\"find_test_outcomes_from_examples() is not yet implemented!\");\n    nothing;\nend\n\n\"\"\"\n    decision_list_learning(ds::DataSet, examples::Set)\n\nReturn an array of (test::Function, outcome) tuples by using the decision list learning\nalgorithm (Fig. 18.11) on the given dataset 'ds' and a set of examples 'examples'.\n\"\"\"\nfunction decision_list_learning(ds::DataSet, examples::Set)\n    if (length(examples) == 0)\n        return [((function(examples::AbstractVector)\n                        return true;\n                    end), false)];\n    end\n    local t::Function;\n    local examples_t::Set;\n    t, output, examples_t = find_test_outcomes_from_examples(ds, examples);\n    if (typeof(t) <: Nothing)\n        error(\"decision_list_learning(): Could not find valid test 't'!\");\n    end\n    return append!([(t, output)], decision_list_learning(ds, setdiff(examples, examples_t)));\nend\n\nstruct DecisionListLearner <: AbstractLearner\n    decision_list::AbstractVector\n\n    function DecisionListLearner(dataset::DataSet)\n        return new(decision_list_learning(dataset, Set(dataset.examples[i, :]\n                                                        for i in 1:size(dataset.examples)[1])));\n    end\nend\n\nfunction predict(dll::DecisionListLearner, examples::AbstractVector)\n    for (test, outcome) in dll.decision_list\n        if (test(examples))\n            return outcome;\n        end\n    end\n    error(\"predict(): All tests in the generated decision list failed for \", examples, \"!\");\nend\n\n#=\n\n    NeuralNetworkUnit is an unit (node) in a multilayer neural network.\n\n=#\nmutable struct NeuralNetworkUnit\n    weights::AbstractVector\n    inputs::AbstractVector\n    value   # can be any DataType, but check for Nothing DataType later\n    activation::Function\n\n    function NeuralNetworkUnit()\n        return new([], [], nothing, sigmoid);\n    end\n\n    function NeuralNetworkUnit(weights::AbstractVector, inputs::AbstractVector)\n        return new(weights, inputs, nothing, sigmoid);\n    end\nend\n\n\"\"\"\n    neural_network(input_units::Int64, hidden_layers_sizes::Array{Int64, 1}, output_units::Int64)\n\nReturn an untrained neural network by using the given the number of input units 'input_units', the\nhidden layers' sizes (the hidden layers should not include the input and output layers) in\n'hidden_layers_sizes', and the number of output units 'output_units'.\n\"\"\"\nfunction neural_network(input_units::Int64, hidden_layers_sizes::Array{Int64, 1}, output_units::Int64)\n    local layers_sizes::AbstractVector = Array{Int64, 1}();\n    if (length(hidden_layers_sizes) == 0)\n        push!(layers_sizes, input_units);\n        push!(layers_sizes, output_units);\n    else\n        push!(layers_sizes, input_units);\n        append!(layers_sizes, hidden_layers_sizes);\n        push!(layers_sizes, output_units);\n    end\n    local network::AbstractVector = collect(collect(NeuralNetworkUnit()\n                                                    for node in 1:layer_size)\n                                            for layer_size in layers_sizes);\n    for i in 2:length(network)\n        for n in network[i]\n            for k in network[i - 1]\n                push!(n.inputs, k);\n                push!(n.weights, 0.0);\n            end\n        end\n    end\n    return network;\nend\n\nfunction back_propagation_initialize_examples(examples::AbstractMatrix, idx_i::AbstractVector, idx_t::Int64, o_units::Int64)\n    local inputs::Dict = Dict();\n    local targets::Dict = Dict();\n\n    for i in 1:size(examples)[1]\n        local example::AbstractVector = examples[i, :];\n        inputs[i] = collect(example[idx] for idx in idx_i);\n        if (o_units > 1)\n            local t::AbstractVector = collect(0.0 for j in 1:o_units);\n            t[example[idx_t]] = 1.0;\n            targets[i] = t;\n        else\n            targets[i] = [example[idx_t]];\n        end\n    end\n    return inputs, targets;\nend\n\n\"\"\"\n    random_weights(bound_1::Real, bound_2::Real, num_weights::Int64)\n\nReturn an array of 'num_weights' weights that are randomly generated with the\nbounds 'bound_1' and 'bound_2'.\n\"\"\"\nfunction random_weights(bound_1::Real, bound_2::Real, num_weights::Int64)\n    local minimum_value::Real = min(bound_1, bound_2);\n    return collect((minimum_value + (rand(RandomDeviceInstance) * abs(bound_1 - bound_2)))\n                    for i in 1:num_weights);\nend\n\n\"\"\"\n    back_propagation_learning!(dataset::DataSet, network::AbstractVector, learning_rate::Float64, epochs::Int64)\n\nReturn the trained neural network by applying the back-propagation algorithm (Fig. 18.24) on the\ngiven multilayer neural network 'network', dataset 'dataset', learning rate 'learning_rate', and\nthe number of epochs 'epochs'.\n\"\"\"\nfunction back_propagation_learning!(dataset::DataSet, network::AbstractVector, learning_rate::Float64, epochs::Int64)\n    for layer in network\n        for unit in layer\n            unit.weights = random_weights(-0.5, 0.5, length(unit.weights));\n        end\n    end\n    local output_units::AbstractVector = network[end];\n    local input_units::AbstractVector = network[1];\n    local num_output_units::Int64 = length(output_units);\n    local inputs::Dict;\n    local targets::Dict;\n    local layer::AbstractVector;\n\n    inputs, targets = back_propagation_initialize_examples(dataset.examples, dataset.inputs, dataset.target, num_output_units);\n\n    for epoch in 1:epochs\n        for x in 1:size(dataset.examples)[1]\n            local input_value::AbstractVector = inputs[x];\n            local target_value::AbstractVector = targets[x];\n\n            # Activate the input layer.\n            for (v, u) in zip(input_value, input_units)\n                u.value = v;\n            end\n\n            # Propagate the inputs forward.\n            for layer in network[2:end]\n                for unit in layer\n                    local in_j::Real = dot(collect(unit_input.value\n                                                    for unit_input in unit.inputs),\n                                                    unit.weights);\n                    unit.value = unit.activation(in_j);\n                end\n            end\n\n            # Initialize deltas array with empty vectors.\n            local delta::AbstractVector = collect([] for i in 1:length(network));\n\n            # Compute the errors of the mean squared error function.\n            local errors::AbstractVector = collect((target_value[i] - output_units[i].value)\n                                                for i in 1:num_output_units);\n            delta[end] = collect((sigmoid_derivative(output_units[i].value) * errors[i])\n                                for i in 1:num_output_units);\n\n            # Propagate the deltas backward from ouput layer to input layer.\n            local num_hidden_layers::Int64 = length(network) - 2;\n            for i in reverse(2:(num_hidden_layers + 1))\n                layer = network[i];\n                local num_hidden_units::Int64 = length(layer);\n                local next_layer::AbstractVector = network[i + 1];\n                w = collect(collect(unit.weights[j]\n                                    for unit in next_layer)\n                            for j in 1:num_hidden_units);\n\n                delta[i] = collect((sigmoid_derivative(layer[j].value) * dot(w[j], delta[i + 1]))\n                                    for j in 1:num_hidden_units);\n            end\n\n            # Update every weight in network by using the deltas.\n            for i in 2:length(network)\n                layer = network[i];\n                local previous_layer_values::AbstractVector = collect(unit.value for unit in network[i - 1]);\n                local num_units::Int64 = length(layer);\n                for j in 1:num_units\n                    layer[j].weights = (layer[j].weights + ((learning_rate * delta[i][j]) * previous_layer_values));\n                end\n            end\n        end\n    end\n    return network;\nend\n\n#=\n\n    NeuralNetworkLearner contains a multilayer feed-forward neural network that is\n\n    trained by the back-propagation algorithm with the dataset 'dataset', learning rate\n\n    'learning_rate', and number of epochs (our criterion for stopping training) 'epochs'.\n\n=#\nmutable struct NeuralNetworkLearner <: AbstractLearner\n    network::AbstractVector\n\n    function NeuralNetworkLearner(dataset::DataSet;\n                                hidden_layers_sizes::AbstractVector=[3],\n                                learning_rate::Float64=0.01,\n                                epochs::Int64=100)\n        local num_input_units::Int64 = length(dataset.inputs);\n        local num_output_units::Int64 = length(dataset.values[dataset.target]);\n        local nnl::NeuralNetworkLearner = new(neural_network(num_input_units, hidden_layers_sizes, num_output_units));\n        nnl.network = back_propagation_learning!(dataset, nnl.network, learning_rate, epochs);\n        return nnl;\n    end\nend\n\n\"\"\"\n    predict(nnl::NeuralNetworkLearner, example::AbstractVector)\n\nReturn a prediction for the given 'example' by using the logistic regression hypothesis on the\nvalues of 'example' and the weights of each respective unit in the neural network 'nnl.network'.\n\"\"\"\nfunction predict(nnl::NeuralNetworkLearner, example::AbstractVector)\n    local input_units::AbstractVector = nnl.network[1];\n\n    # Set the values of the input units to the values of example.\n    for (v, u) in zip(example, input_units)\n        u.value = v;\n    end\n\n    # Propagate the example values forward.\n    for layer in nnl.network[2:end]\n        for unit in layer\n            local in_j::Real = dot(collect(unit_input.value\n                                            for unit_input in unit.inputs),\n                                            unit.weights);\n            unit.value = unit.activation(in_j);\n        end\n    end\n\n    local prediction::Int64 = utils.index(nnl.network[end], argmax(nnl.network[end],\n                                                                    (function(unit::NeuralNetworkUnit)\n                                                                        return unit.value;\n                                                                    end)));\n    if (prediction < 0)\n        error(\"predict(): NeuralNetworkLearner returned invalid array index '\", prediction, \"'!\");\n    else\n        return prediction;\n    end\nend\n\n#=\n\n    PerceptronLearner contains a neural network where hidden layers are not used.\n\n    The neural network is trained by the back-propagation algorithm with the given\n\n    dataset 'dataset'.\n\n=#\nmutable struct PerceptronLearner <: AbstractLearner\n    network::AbstractVector\n\n    function PerceptronLearner(dataset::DataSet;\n                                learning_rate::Float64=0.01,\n                                epochs::Int64=100)\n        local num_input_units::Int64 = length(dataset.inputs);\n        local num_output_units::Int64 = length(dataset.values[dataset.target]);\n        local hidden_layers_sizes::AbstractVector = Array{Int64, 1}();\n        local pl::PerceptronLearner = new(neural_network(num_input_units, hidden_layers_sizes, num_output_units));\n        pl.network = back_propagation_learning!(dataset, pl.network, learning_rate, epochs);\n        return pl;\n    end\nend\n\n\"\"\"\n    predict(pl::PerceptronLearner, example::AbstractVector)\n\nReturn a prediction for the given 'example' by using the logistic regression hypothesis on the\nvalues of 'example' and the weights of each respective unit in the neural network 'pl.network'.\n\"\"\"\nfunction predict(pl::PerceptronLearner, example::AbstractVector)\n    local output_units::AbstractVector = pl.network[end];\n\n    # Propagate the example values forward.\n    for unit in output_units\n        unit.value = unit.activation(dot(example, unit.weights));\n    end\n\n    local prediction::Int64 = utils.index(pl.network[end], argmax(pl.network[end],\n                                                                (function(unit::NeuralNetworkUnit)\n                                                                    return unit.value;\n                                                                end)));\n    if (prediction < 0)\n        error(\"predict(): PerceptronLearner returned invalid array index '\", prediction, \"'!\");\n    else\n        return prediction;\n    end\nend\n\n#=\n\n    LinearRegressionLearner creates a linear model by applying multivariate\n\n    linear regression to the given dataset. The regressands are assumed to be\n\n    real numbers.\n\n=#\nstruct LinearRegressionLearner <: AbstractLearner\n    dataset::DataSet\n    weights::AbstractVector\n\n    function LinearRegressionLearner(dataset::DataSet;\n                                    learning_rate::Float64=0.01,\n                                    epochs::Int64=100)\n        # Initialize random weights\n        local lrl::LinearRegressionLearner = new(dataset, random_weights(-0.5, 0.5, length(dataset.inputs) + 1));\n\n        # Initialize an array of x_i (vectors) such that the first component of each vector is 1.0.\n        local X::AbstractVector = collect(vcat(1.0, dataset.values[i]) for i in dataset.inputs);\n\n        for i in 1:epochs\n            local error::AbstractVector = Array{Float64, 1}();\n            for example in (dataset.examples[i, :] for i in 1:size(dataset.examples)[1])\n                # The target attribute will be ignored in the evaluation of h_w(x).\n                local x::AbstractVector = vcat(1, sanitize(dataset, example));\n                local h_x::Float64 = dot(lrl.weights, x);\n                # The error component is the square of the difference between the regressand y and h_w(x).\n                local y::Float64 = examples[dataset.target];\n                push!(error, t - y);\n            end\n\n            # Use the least mean squares algorithm for stochastic gradient descent.\n            for i in 1:length(lrl.weights)\n                lrl.weights[i] = lrl.weights[i] + ((learning_rate * dot(error, X))/size(dataset.examples)[1]);\n            end\n        end\n\n        return lrl;\n    end\nend\n\nfunction predict(lrl::LinearRegressionLearner, example::AbstractVector)\n    return dot(lrl.weights, vcat(1.0, sanitize(lrl.dataset, example)));\nend\n\n#=\n\n    EnsembleLearner is a learner that uses an ensemble of hypotheses generated by the given\n\n    learner constructors to vote on the best classification when predicting.\n\n=#\nstruct EnsembleLearner <: AbstractLearner\n    predictors::AbstractVector\n\n    function EnsembleLearner(dataset::DataSet, learners::AbstractVector)\n        if (!(all(((typeof(learner) <: DataType) && (learner <: AbstractLearner))\n                    for learner in learners)))\n            error(\"EnsembleLearner(): All items in learners must be a subtype of AbstractLearner!\");\n        end\n        return new(collect(learner(dataset) for learner in learners));\n    end\nend\n\nfunction predict(el::EnsembleLearner, example::AbstractVector)\n    return mode(predict(predictor, example) for predictor in predictors);\nend\n\n\"\"\"\n    weighted_mode(values::String, weights::AbstractVector)\n    weighted_mode(values::AbstractVector, weights::AbstractVector)\n\nReturn the value from 'values' with the largest cumulative weight.\n\"\"\"\nfunction weighted_mode(values::String, weights::AbstractVector)\n    local values_array::AbstractVector = map(String, collect([c] for c in map(Char, Vector{UInt8}(values))));\n    local weight_values::Dict = Dict();\n    for (value, weight) in zip(values_array, weights)\n        if (haskey(weight_values, value))\n            weight_values[value] = weight_values[value] + weight;\n        else\n            weight_values[value] = weight;\n        end\n    end\n    return reduce((function(t1::Pair, t2::Pair)\n                        if (t1[2] < t2[2])\n                            return t2;\n                        else\n                            return t1;\n                        end\n                    end),\n                    weight_values)[1];\nend\n\nfunction weighted_mode(values::AbstractVector, weights::AbstractVector)\n    local weight_values::Dict = Dict();\n    for (value, weight) in zip(values, weights)\n        if (haskey(weight_values, value))\n            weight_values[value] = weight_values[value] + weight;\n        else\n            weight_values[value] = weight;\n        end\n    end\n    return reduce((function(t1::Pair, t2::Pair)\n                        if (t1[2] < t2[2])\n                            return t2;\n                        else\n                            return t1;\n                        end\n                    end),\n                    weight_values)[1];\nend\n\n\"\"\"\n    weighted_majority(predictors::AbstractVector, weights::AbstractVector)\n\nReturn a function that returns the highest weighted vote based on the\nweights and predict() methods for the given learners 'predictors'.\n\"\"\"\nfunction weighted_majority(predictors::AbstractVector, weights::AbstractVector)\n    return (function(examples::AbstractVector)\n                return weighted_mode(collect(predict(predictor, example)\n                                            for predictor in predictors),\n                                    weights);\n            end);\nend\n\n\"\"\"\n    weighted_replicate(seq::AbstractVector, weights::AbstractVector, n::Int64)\n    weighted_replicate(seq::AbstractMatrix, weights::AbstractVector, n::Int64)\n\nReturn an array of 'n' examples where each example is proportional to the corresponding\nweight in the given weights array 'weights'. These 'n' examples are sampled from the given\narray 'seq' by using weighted_sample_with_replacement().\n\"\"\"\nfunction weighted_replicate(seq::AbstractVector, weights::AbstractVector, n::Int64)\n    if (length(seq) != length(weights))\n        error(\"weighted_replicate(): The length of 'seq' and 'weights' must match!\");\n    end\n\n    local normalized_weights::Array{Float64, 1} = normalize(weights, 1);\n    local integer_multiples::Array{Int64, 1} = collect(Int64(floor(weight * n))\n                                                        for weight in normalized_weights);\n    local fractions::Array{Float64, 1} = collect(((weight * n) % 1) for weight in normalized_weights);\n\n    return append!(reduce(vcat, \n                            collect(fill(x, num_x)\n                                    for (x, num_x) in zip(seq, integer_multiples)),\n                            init=[]),\n                    weighted_sample_with_replacement(seq, fractions, (n - sum(integer_multiples))));\nend\n\nfunction weighted_replicate(seq::AbstractMatrix, weights::AbstractVector, n::Int64)\n    if (size(seq)[1] != length(weights))\n        error(\"weighted_replicate(): The length of 'seq' and 'weights' must match!\");\n    end\n\n    local normalized_weights::Array{Float64, 1} = normalize(weights, 1);\n    local integer_multiples::Array{Int64, 1} = collect(Int64(floor(weight * n))\n                                                        for weight in normalized_weights);\n    local fractions::Array{Float64, 1} = collect(((weight * n) % 1) for weight in normalized_weights);\n\n    local integer_weighted::AbstractMatrix = vcat(collect(vcat((reshape(x, 1, length(x))\n                                                                for i in 1:num_x)...,)\n                                                for (x, num_x) in zip((seq[i, :]\n                                                                        for i in 1:size(seq)[1]),\n                                                                        integer_multiples)\n                                                if (num_x > 0))...,);\n    if ((n - sum(integer_multiples)) > 0)\n        local fraction_weighted::AbstractMatrix = vcat(collect(reshape(sample, 1, length(sample))\n                                                                for sample in weighted_sample_with_replacement(\n                                                                    collect(seq[i, :] for i in 1:size(seq)[1]),\n                                                                    fractions,\n                                                                    (n - sum(integer_multiples))))...,);\n\n        return vcat(integer_weighted, fraction_weighted);\n    else\n        return integer_weighted;\n    end\nend\n\nfunction reweighted_dataset(dataset::DataSet, weights::AbstractVector, n::Int64)\n    local dataset_copy::DataSet = copy(dataset);\n    dataset_copy.examples = weighted_replicate(dataset_copy.examples, weights, n);\n    return dataset_copy;\nend\n\nfunction reweighted_dataset(dataset::DataSet, weights::AbstractVector)\n    local n::Int64 = size(dataset.examples)[1];\n    local dataset_copy::DataSet = copy(dataset);\n    dataset_copy.examples = weighted_replicate(dataset_copy.examples, weights, n);\n    return dataset_copy;\nend\n\n\n#=\n\n    AdaBoostLearner contains the weights and hypotheses generated by adaboost!().\n\n=#\nstruct AdaBoostLearner <: AbstractLearner\n    h::AbstractVector\n    z::AbstractVector\n    hypothesis::Function\n\n    function AdaBoostLearner(dataset::DataSet, L::DataType, K::Int64)\n        if (!(L <: AbstractLearner))\n            error(\"AdaBoostLearner(): The learner \", L, \" is not a subtype of AbstractLearner!\");\n        end\n        local abl::AdaBoostLearner = new(Array{Float64, 1}(), Array{Float64, 1}());\n        abl.hypothesis = adaboost!(abl, dataset, L, K);\n        return abl;\n    end\nend\n\nfunction predict(abl::AdaBoostLearner, example::AbstractVector)\n    return abl.hypothesis(example);\nend\n\n\"\"\"\n    adaboost!(abl::AdaBoostLearner, dataset::DataSet, L::DataType, K::Int64)\n\nReturn a weighted-majority hypothesis by using the AdaBoost algorithm (Fig. 18.34)\non the given dataset 'dataset', learning algorithm 'L', and number of hypotheses to\nuse in ensemble learning 'K'.\n\nThis function sets abl.h to the vector of 'K' hypotheses and abl.z to the vector\nof 'K' hypothesis weights.\n\"\"\"\nfunction adaboost!(abl::AdaBoostLearner, dataset::DataSet, L::DataType, K::Int64)\n    local w::AbstractVector = fill((1/size(dataset.examples)[1]), size(dataset.examples)[1]);\n    for k in 1:K\n        local h_k::AbstractLearner = L(reweighted_dataset(dataset, w));\n        push!(abl.h, h_k);\n        local error::Float64 = sum(weight\n                                    for (example, weight) in zip((dataset.examples[i, :]\n                                                                for i in 1:size(dataset.examples)[1]),\n                                                                w));\n        for (j, example) in enumerate(dataset.examples[i, :] for i in 1:size(dataset.examples)[1])\n            if (example[dataset.target] == predict(h_k, example))\n                w[j] = w[j] * error;\n            end\n        end\n        w = normalize(w, 1);\n        push!(abl.z, log((1.0 - error)/error));\n    end\n    return weighted_majority(abl.h, abl.k);\nend\n\n\"\"\"\n    grade_learner(learner::AbstractLearner, tests::AbstractVector)\n\nReturn a score for the given learner 'learner' and the tests 'tests' (an array of (example, output)).\n\"\"\"\nfunction grade_learner(learner::AbstractLearner, tests::AbstractVector)\n    return mean(Float64(predict(learner, X) == y) for (X, y) in tests);\nend\n\n\"\"\"\n    error_ratio(learner::AbstractLearner, dataset::DataSet, examples::Union{Nothing, AbstractMatrix}=nothing, verbose::Int64=0)\n\nReturn the proportion of examples that were not correctly predicted.\n\nIf 'verbose' is set to 0, this function will not print extra messages.\nIf 'verbose' is set to 1, this function will print messages when a prediction fails.\nIf 'verbose' is set to 2 or more, this function will print messages for each prediction made.\n\"\"\"\nfunction error_ratio(learner::AbstractLearner, dataset::DataSet, examples::Union{Nothing, AbstractMatrix}=nothing, verbose::Int64=0)\n    local new_examples::AbstractMatrix;\n    if (typeof(examples) <: Nothing)\n        new_examples = dataset.examples;\n    else\n        new_examples = examples;\n    end\n    if (size(new_examples)[1] == 0)\n        return 0.0;\n    end\n    local correct::Float64 = 0.0;\n    for example in (new_examples[i, :] for i in 1:size(new_examples)[1])\n        desired = example[dataset.target];\n        output = predict(learner, sanitize(dataset, example));\n        if (output == desired)\n            correct = correct + 1;\n            if (verbose >= 2)\n                println(\"   OK:  Got \", desired, \" for \", example, \"!\");\n            end\n        elseif (verbose > 0)\n            println(\"WRONG: Got \", output, \", expected \", desired, \" for \", example, \"!\");\n        end\n    end\n    return 1.0 - (correct / size(new_examples)[1]);\nend\n\n\"\"\"\n    partition_dataset(dataset::DataSet, start_index::Real, end_index::Real)\n\nPartition the examples of the given dataset 'dataset' into a set of examples for training\nand a separate set of examples for validation.\n\"\"\"\nfunction partition_dataset(dataset::DataSet, start_index::Real, end_index::Real)\n    local int_start::Int64 = Int64(floor(start_index));\n    local int_end::Int64 = Int64(floor(end_index));\n    local training_set::AbstractMatrix = vcat(dataset.examples[1:(int_start - 1), :],\n                                                dataset.examples[int_end:end, :]);\n    local validation_set::AbstractMatrix = dataset.examples[int_start:(int_end - 1), :];\n    return training_set, validation_set;\nend\n\nfunction cross_validation(learner::DataType, size::Int64, k::Int64, dataset::DataSet, trials::Int64)\n    local error_T::AbstractVector = [];\n    local error_V::AbstractVector = [];\n    for i in 1:trials\n        new_error_T, new_error_V = cross_validation(learner, size, k, dataset);\n        push!(error_T, new_error_T);\n        push!(error_V, new_error_V);\n    end\n    return mean(error_T), mean(error_V);\nend\n\nfunction cross_validation(learner::DataType, size::Int64, k::Int64, dataset::DataSet)\n    local fold_errT::Float64 = 0.0;\n    local fold_errV::Float64 = 0.0;\n    local num_examples::Int64 = size(dataset.examples)[1];\n    for fold in 1:k\n        local original_set::AbstractMatrix = dataset.examples;\n        local training_set::AbstractMatrix;\n        local validation_set::AbstractMatrix;\n        training_set, validation_set = partition_dataset(dataset,\n                                                        ((fold * n)/k),\n                                                        (((fold * n) + n)/k));\n        dataset.examples = training_set;\n\n        # Section 18.4.1 (Model selection: Complexity vs goodness of fit) suggests using\n        # 'size' as the number of nodes to use in a breadth-first decision tree created\n        # by a decision-tree learning algorithm.\n        #\n        # Currently, decision_tree_learning() traverses the decision tree depth-first.\n        local h::AbstractLearner = learner(dataset, size);\n        fold_errT = fold_errT + error_ratio(h, dataset, training_set);\n        fold_errV = fold_errV + error_ratio(h, dataset, validation_set);\n        dataset.examples = original_set;\n    end\n    return (fold_errT/k), (fold_errV/k);\nend\n\n\"\"\"\n    cross_validation_wrapper(learner::DataType, dataset::DataSet; trials::Int64=1, k::Int64=10)\n\nApply the cross-validation algorithm (Fig. 18.8) on the given learning algorithm 'learner',\nthe number of equal subsets to make from splitting the dataset 'k', the dataset 'dataset',\nand the number of trials to make for a specific size 'trials'.\n\nReturn a trained learner if the errors from the training sets converge, otherwise raise an error\nfor reaching the max Int64 value before integer overflow.\n\"\"\"\nfunction cross_validation_wrapper(learner::DataType, dataset::DataSet; trials::Int64=1, k::Int64=10)\n    local error_training::Array{Float64, 1} = Array{Float64}();\n    local error_validation::Array{Float64, 1} = Array{Float64}();\n    local size::Int64 = 1;\n    while (true)\n        local errT::Float64;\n        local errV::Float64;\n\n        errT, errV = cross_validation(learner, size, k, dataset, trials);\n\n        if (length(error_training) != 0)\n            if (abs(error_training[end] - errT) <= (0.000001 * max(abs(error_training[end]), abs(errT))))\n                local best_size::Int64 = -1;\n                local minimum_error::Float64 = Inf64;\n                for i in 1:size\n                    if (error_validation[i] < minimum_error)\n                        minimum_error = error_validation[i];\n                        best_size = i;\n                    end\n                end\n                return learner(dataset, best_size);\n            end\n        end\n\n        if (size == typemax(Int64))\n            error(\"cross_validation(): The 'size' variable will integer overflow!\");\n        end\n        size = size + 1;\n    end\nend\n\n\"\"\"\n    leave_one_out_cross_validation(learner::DataType, dataset::DataSet)\n\nApply the leave-one-out cross-validation algorithm (LOOCV) on the given learning algorithm 'learner'\nand the dataset 'dataset'. The number of equal subsets to make from splitting the dataset, 'k', is\nset to the number of examples in the dataset.\n\"\"\"\nfunction leave_one_out_cross_validation(learner::DataType, dataset::DataSet)\n    return cross_validation_wrapper(learner, dataset, k=size(dataset.examples)[1]);\nend\n\n\"\"\"\n    learning_curve(learner::DataType, dataset::DataSet; trials::Int64=10, sizes::AbstractVector=[])\n\nReturn an array of (size, score) tuples which represent the data points of our learning curve.\n\"\"\"\nfunction learning_curve(learner::DataType, dataset::DataSet; trials::Int64=10, sizes::AbstractVector=[])\n    if (length(sizes) == 0)\n        sizes = collect(2:2:(size(dataset.examples)[1] - 2));\n    end\n\n    local original_set::AbstractMatrix = dataset.examples;\n\n    # Randomly shuffle the examples between trials.\n    local learning_curve_score::Function = (function(size::Int64)\n                                                dataset.examples = reduce(vcat, shuffle!(RandomDeviceInstance,\n                                                                                        collect(dataset.examples[i, :]\n                                                                                                for i in 1:size(dataset.examples)[1])));\n                                                local training_set::AbstractMatrix = getindex(partition_dataset(dataset, 0, size), 1);\n                                                return (1.0 - error_ratio(learner(dataset), dataset, training_set));\n                                            end);\n\n\n    local data_points::AbstractVector = collect((size, mean(learning_curve_score(size) for i in 1:trials))\n                                                for size in sizes);\n    dataset.examples = original_set;\n    return data_points;\nend\n\n# The following variables are DataSets read from the aima-data repository.\norings_dataset = DataSet(name=\"orings\", examples=\"./aima-data/orings.csv\", target=\"Distressed\",\n                        attributes_names=\"Rings Distressed Temperature Pressure Flightnumber\");\n\nzoo_dataset = DataSet(name=\"zoo\", examples=\"./aima-data/zoo.csv\", target=\"type\", exclude=[\"name\"],\n                    attributes_names=[\"name\", \"hair\", \"feathers\", \"eggs\", \"milk\", \"airborne\",\n                                    \"aquatic\", \"predator\", \"toothed\", \"backbone\", \"breathes\",\n                                    \"venomous\", \"fins\", \"legs\", \"tail\", \"domestic\", \"catsize\", \"type\"]);\n\niris_dataset = DataSet(name=\"iris\", examples=\"./aima-data/iris.csv\");\n\n\"\"\"\n    RestaurantDataSet(;examples::Union{Nothing, String, AbstractMatrix}=nothing)\n\nReturn a new DataSet based on the restaurant waiting examples (Fig. 18.3).\n\"\"\"\nfunction RestaurantDataSet(;examples::Union{Nothing, String, AbstractMatrix}=nothing)\n    if (typeof(examples) <: Nothing)\n        return DataSet(name=\"restaurant\", target=\"Wait\", examples=\"./aima-data/restaurant.csv\",\n                        attributes_names=[\"Alternate\", \"Bar\", \"Fri/Sat\", \"Hungry\", \"Patrons\", \"Price\",\n                                        \"Raining\", \"Reservation\", \"Type\", \"WaitEstimate\", \"Wait\"]);\n    else\n\n        return DataSet(name=\"restaurant\", target=\"Wait\", examples=examples,\n                        attributes_names=[\"Alternate\", \"Bar\", \"Fri/Sat\", \"Hungry\", \"Patrons\", \"Price\",\n                                        \"Raining\", \"Reservation\", \"Type\", \"WaitEstimate\", \"Wait\"]);\n    end\nend\n\nrestaurant_dataset = RestaurantDataSet();\n\n# The decision tree for deciding whether to wait for a table (Fig. 18.2).\nwaiting_decision_tree = DecisionForkNode(attribute_index(restaurant_dataset, \"Patrons\"),\n                                    attribute_name=\"Patrons\",\n                                    branches=Dict([Pair(\"None\", DecisionLeafNode(\"No\")),\n                                                    Pair(\"Some\", DecisionLeafNode(\"Yes\")),\n                                                    Pair(\"Full\", DecisionForkNode(attribute_index(restaurant_dataset, \"WaitEstimate\"),\n                                                                            attribute_name=\"WaitEstimate\",\n                                                                            branches=Dict([Pair(\">60\", DecisionLeafNode(\"No\")),\n                                                                                            Pair(\"0-10\", DecisionLeafNode(\"Yes\")),\n                                                                                            Pair(\"30-60\", DecisionForkNode(attribute_index(restaurant_dataset, \"Alternate\"),\n                                                                                                                        attribute_name=\"Alternate\",\n                                                                                                                        branches=Dict([Pair(\"No\", DecisionForkNode(attribute_index(restaurant_dataset, \"Reservation\"),\n                                                                                                                                                                attribute_name=\"Reservation\",\n                                                                                                                                                                branches=Dict([Pair(\"Yes\", DecisionLeafNode(\"Yes\")),\n                                                                                                                                                                            Pair(\"No\", DecisionForkNode(attribute_index(restaurant_dataset, \"Bar\"),\n                                                                                                                                                                                                    attribute_name=\"Bar\",\n                                                                                                                                                                                                    branches=Dict([Pair(\"No\", DecisionLeafNode(\"No\")),\n                                                                                                                                                                                                                    Pair(\"Yes\", DecisionLeafNode(\"Yes\"))])))]))),\n                                                                                                                                        Pair(\"Yes\", DecisionForkNode(attribute_index(restaurant_dataset, \"Fri/Sat\"),\n                                                                                                                                                                    attribute_name=\"Fri/Sat\",\n                                                                                                                                                                    branches=Dict([Pair(\"No\", DecisionLeafNode(\"No\")),\n                                                                                                                                                                                    Pair(\"Yes\", DecisionLeafNode(\"Yes\"))])))]))),\n                                                                                            Pair(\"10-30\", DecisionForkNode(attribute_index(restaurant_dataset, \"Hungry\"),\n                                                                                                                        attribute_name=\"Hungry\",\n                                                                                                                        branches=Dict([Pair(\"No\", DecisionLeafNode(\"Yes\")),\n                                                                                                                                        Pair(\"Yes\", DecisionForkNode(attribute_index(restaurant_dataset, \"Alternate\"),\n                                                                                                                                                                attribute_name=\"Alternate\",\n                                                                                                                                                                branches=Dict([Pair(\"No\", DecisionLeafNode(\"Yes\")),\n                                                                                                                                                                                Pair(\"Yes\", DecisionForkNode(attribute_index(restaurant_dataset, \"Raining\"),\n                                                                                                                                                                                                        attribute_name=\"Raining\",\n                                                                                                                                                                                                        branches=Dict([Pair(\"No\", DecisionLeafNode(\"No\")),\n                                                                                                                                                                                                                        Pair(\"Yes\", DecisionLeafNode(\"Yes\"))])))])))])))])))]));\n\n\"\"\"\n    SyntheticRestaurantDataSet(n::Int64)\n    SyntheticRestaurantDataSet()\n\nReturn a new restaurant dataset with 'n' examples (generates 20 examples when not\ngiven a specific value).\n\"\"\"\nfunction SyntheticRestaurantDataSet(n::Int64)\n    local examples_array::AbstractVector = [];\n    for i in 1:n\n        local new_example::AbstractVector = Array{Any, 1}(map((function(col::AbstractVector)\n                                                                    return rand(RandomDeviceInstance, col);\n                                                                end),\n                                                                restaurant_dataset.values));\n        new_example[restaurant_dataset.target] = classify(waiting_decision_tree, new_example);\n        push!(examples_array, reshape(new_example, (1, length(new_example))));\n    end\n    return RestaurantDataSet(examples=Array{Any, 2}(matrix_vcat(examples_array...,)));\nend\n\nfunction SyntheticRestaurantDataSet()\n    local examples_array::AbstractVector = [];\n    for i in 1:20\n        local new_example::AbstractVector = Array{Any, 1}(map((function(col::AbstractVector)\n                                                                    return rand(RandomDeviceInstance, col);\n                                                                end),\n                                                                restaurant_dataset.values));\n        new_example[restaurant_dataset.target] = classify(waiting_decision_tree, new_example);\n        push!(examples_array, reshape(new_example, (1, length(new_example))));\n    end\n    return RestaurantDataSet(examples=Array{Any, 2}(matrix_vcat(examples_array...,)));\nend\n\n# The following artificial DataSets are generated randomly.\n\"\"\"\n    MajorityDataSet(k::Int64, n::Int64)\n\nReturn a DataSet of n k-bit examples for a majority problem. 'k' random bits are generated\nrandomly for each example. The target attribute is 1 if more than half the 'k' bits are 1,\notherwise the target attribute is 0.\n\"\"\"\nfunction MajorityDataSet(k::Int64, n::Int64)\n    local examples_array::AbstractVector = [];\n    for i in 1:n\n        local bit_domain::AbstractVector = [0, 1];\n        local bits::AbstractVector = collect(rand(RandomDeviceInstance, bit_domain) for i in 1:k);\n        push!(bits, Int64(sum(bits)>(k/2)));\n        push!(examples_array, reshape(bits, (1, length(bits))));\n    end\n    return DataSet(name=\"majority\", examples=Array{Any, 2}(matrix_vcat(examples_array...,)));\nend\n\n\"\"\"\n    ParityDataSet(k::Int64, n::Int64; name::String=\"parity\")\n\nReturn a DataSet of n k-bit examples for a parity problem. 'k' random bits are generated\nrandomly for each example. The target attribute is 1 if an odd amount of 'k' bits are 1,\notherwise the target attribute is 0.\n\"\"\"\nfunction ParityDataSet(k::Int64, n::Int64; name::String=\"parity\")\n    local examples_array::AbstractVector = [];\n    for i in 1:n\n        local bit_domain::AbstractVector = [0, 1];\n        local bits::AbstractVector = collect(rand(RandomDeviceInstance, bit_domain) for i in 1:k);\n        push!(bits, Int64(sum(bits) % 2));\n        push!(examples_array, reshape(bits, (1, length(bits))));\n    end\n    return DataSet(name=name, examples=Array{Any, 2}(matrix_vcat(examples_array...,)));\nend\n\n\"\"\"\n    XorDataSet(n::Int64)\n\nReturn a DataSet of n 2-bit examples where 2 random bits are generated randomly for each\nexample. The target attribute is 1 only if 1 of the randomly generated bits is 1, otherwise\nthe target attribute is 0.\n\"\"\"\nfunction XorDataSet(n::Int64)\n    return ParityDataSet(2, n, name=\"xor\");\nend\n\n\"\"\"\n    ContinuousXorDataSet(n::Int64)\n\nReturn a DataSet where each example consists of 2 random floats that are uniformly generated\nin [0, 2). The target attribute is the xor of the floor of floats casted as integers.\n\"\"\"\nfunction ContinuousXorDataSet(n::Int64)\n    local examples_array::AbstractVector = [];\n    for i in 1:n\n        local x::Float64;\n        local y::Float64;\n        x, y = (rand(RandomDeviceInstance) * 2, rand(RandomDeviceInstance) * 2);\n        local example::AbstractVector = Array{Any, 1}();\n        push!(example, x);\n        push!(example, y);\n        push!(example, (Int64(floor(x)) != Int64(floor(y))));\n        push!(examples_array, reshape(example, (1, length(example))));\n    end\n    return DataSet(name=\"continuous xor\", examples=Array{Any, 2}(matrix_vcat(examples_array...,)));\nend\n\n", "meta": {"hexsha": "5f9f9d18fa4380297d394ea325cee9db5144ad4d", "size": 81953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "learning.jl", "max_stars_repo_name": "mikhail-j/aima-julia", "max_stars_repo_head_hexsha": "07ea7acd534266fd2b10ee0d4aeb847a88225ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 131, "max_stars_repo_stars_event_min_datetime": "2016-07-23T14:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:49:47.000Z", "max_issues_repo_path": "learning.jl", "max_issues_repo_name": "mikhail-j/aima-julia", "max_issues_repo_head_hexsha": "07ea7acd534266fd2b10ee0d4aeb847a88225ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-03-30T19:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-08T16:35:26.000Z", "max_forks_repo_path": "learning.jl", "max_forks_repo_name": "mikhail-j/aima-julia", "max_forks_repo_head_hexsha": "07ea7acd534266fd2b10ee0d4aeb847a88225ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 65, "max_forks_repo_forks_event_min_datetime": "2016-09-24T17:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:49:50.000Z", "avg_line_length": 42.7953002611, "max_line_length": 272, "alphanum_fraction": 0.6012104499, "num_tokens": 17188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7691616283381074}}
{"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\u2c7c, t\u1d62) 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\u03b1_vals = linspace(0.05, 0.5, grid_size)  \nw_bar_vals = similar(\u03b1_vals)\n\nmcm = McCallModel()\n\nfor (i, \u03b1) in enumerate(\u03b1_vals)\n    mcm.\u03b1 = \u03b1\n    w_bar = compute_reservation_wage(mcm)\n    w_bar_vals[i] = w_bar\nend\n\nplot(\u03b1_vals, \n     w_bar_vals, \n     lw=2, \n     \u03b1=0.7, \n     xlabel=\"job separation rate\",\n     ylabel=\"reservation wage\",\n     label=L\"$\\bar w$ as a function of $\\\u03b1$\")\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*\u03c0\n\n    #Initialize\n    qe=zeros(DFloat,Npoin)\n    qe\u2093=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\u2093[I]=-c*cos(c*x)\n            fe[I]=-c^2*sin(c*x)\n        end\n    end #I\n    return (qe,qe\u2093,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(\u03bc, \u03bb)\n\nT\u1ea1o m\u00f4 h\u00ecnh M/M/1\n\"\"\"\nstruct MM1{T<:Any} <: AbstractMMCK\n\t\u03bb::Union{T, Real}\n\t\u03bc::Union{T, Real}\n\t\u03c1::Union{T, Real}\n\tfunction MM1(\u03bb, \u03bc)\n\t\tT = Union{typeof(\u03bc), typeof(\u03bb)}\n\t\tnew{T}(\u03bb, \u03bc, \u03bb/\u03bc)\n\tend\n\tfunction MM1(\u03bb::Real, \u03bc::Real)\n\t\tif \u03bb/\u03bc >= 1\n\t\t\t@error \"\u03c1 ph\u1ea3i < 1\"\n\t\tend\n\t\tT = Union{typeof(\u03bc), typeof(\u03bb)}\n\t\tnew{T}(\u03bb, \u03bc, \u03bb/\u03bc)\n\tend\nend\n\npn(m::MM1, n::Int) = (1 - m.\u03c1) * m.\u03c1^n\nL(m::MM1) = m.\u03c1 / (1 - m.\u03c1)\nLq(m::MM1) = m.\u03c1 ^ 2 / (1 - m.\u03c1)\nW(m::MM1) = L(m) / m.\u03bb\nWq(m::MM1) = Lq(m) / m.\u03bb\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; \u03bb = 1)\n    flag = (abs.(t) .< \u03bb)\n    y1 = t.^2 / 2 .* flag .+ (\u03bb * abs.(t) .- \u03bb^2 / 2) .* (1 .- flag)\n    y2 = \u03bb * abs.(t) .- \u03bb^2 / 2\n    return y1, y2\nend\ny1, y2 = huber(t, \u03bb = 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') = \u03c3\u00b2(x\u1d40x'+c)\u1d48\n# Arguments:\n* `lc::Float64`: Log of the constant c\n* `l\u03c3::Float64`: Log of the signal standard deviation \u03c3\n* `d::Int64`   : Degree of the Polynomial\n\"\"\" ->\ntype Poly <: Kernel\n    lc::Float64      # Log of constant\n    l\u03c3::Float64      # Log of signal std\n    deg::Int64       # degree of polynomial\n    Poly(lc::Float64, l\u03c3::Float64, deg::Int64) = new(lc, l\u03c3, deg)\nend\n\nfunction cov(poly::Poly, x::Vector{Float64}, y::Vector{Float64})\n    c = exp(poly.lc)\n    sigma2 = exp(2*poly.l\u03c3)\n\n    K = sigma2*(c+dot(x,y)).^poly.deg\n    return K\nend\n\nget_params(poly::Poly) = Float64[poly.lc, poly.l\u03c3]\nget_param_names(poly::Poly) = [:lc, :l\u03c3]\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\u03c3 = 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\u03c3)\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) = \u03b8\\\\exp(-\u03b8y),\n```\nwhere ``\u03b8 = \\\\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(\u03bd::Real, z::Real, DI_over_I::Bool)\n\nPrefactor for the kinetic Sunyaev-Zel'dovich effect.\n\"\"\"\nfunction kSzPrefac(\u03bd::Real, z::Real, DI_over_I::Bool)\n\n    kSzPrefac  = -1.0 * \u03c3_T / c_light\n\n    if DI_over_I\n        x   = h_planck * \u03bd / ( 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                    \u03bd::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 `\u03bd` and redshift `z`.\n\"\"\"\nfunction kinetic_SZ(n_cm3::Real, vel_y_cgs::Real, \n                    \u03bd::Real=1.e9, z::Real=0.0; \n                    DI_over_I::Bool=false)\n    return kSzPrefac(\u03bd, 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(\u03bd::Real, z::Real)\n\nComputes the prefactor for the thermal Sunyaev-Zel'dovich effect.\n\"\"\"\nfunction tSzPrefac(\u03bd::Real, z::Real, DI_over_I::Bool)\n\n    x   = h_planck * \u03bd / ( 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, \u03bd::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 `\u03bd`.\n\"\"\"\nfunction thermal_SZ(n_cm3::Real, T_K::Real, \n                    z::Real=0.0, \u03bd::Real=1.44e9; \n                    DI_over_I::Bool=false)\n\n    return tSzPrefac(\u03bd, 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\u03b1::Float64\n\t\u03b2::Float64\n\tl\u2080::Float64\n\tb\u2080::Float64\n\n\tHLT() = new(0, 0, 0, 0)\n\tHLT(\u03b1::Number, \u03b2::Number, l\u2080::Number, b\u2080::Number) = new(Float64(\u03b1), Float64(\u03b2),\n\t\tFloat64(l\u2080), Float64(b\u2080))\nend\n\n\nfunction loss(model::HLT, time_series)\n\t\u03b1, \u03b2, l\u2080, b\u2080 = model.\u03b1, model.\u03b2, model.l\u2080, model.b\u2080\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\u2080\n\t\t\tb_t = b\u2080\n\t\telse\n\t\t\tl_t = time_series[t - 1] * \u03b1 + (l_t + b_t) * (1 - \u03b1) #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.\u03b1, model.\u03b2, model.l\u2080, model.b\u2080]\n\n\tfunction loss_(parameters::Array{Float64, 1})\n\t\t\u03b1, \u03b2, l\u2080, b\u2080 = parameters\n\t\treturn loss(HLT(\u03b1, \u03b2, l\u2080, b\u2080), 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\u03b1, \u03b2, l\u2080, b\u2080 = model.\u03b1, model.\u03b2, model.l\u2080, model.b\u2080\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\u2080\n\t\t\tb_t = b\u2080\n\t\telse\n\t\t\tl_t = time_series[t - 1] * \u03b1 + (l_t + b_t) * (1 - \u03b1) #b_t \"is\" b(t-1)\n\t\t\tb_t = \u03b2 * (l_t - l_t_) + (1 - \u03b2) * b_t\n\t\tend\n\t\tl_t_ = l_t\n\tend\n    \n    #The parameter\u00b4s values to make the forecast are those estimated in the last step of the time series\n\tl_t = time_series[end] * \u03b1 + (l_t + b_t) * (1 - \u03b1)\n\tb_t = \u03b2 * (l_t - l_t_) + (1 - \u03b2) * 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": "let\n\t# Test Optim.cg for all differentiable functions in Optim.UnconstrainedProblems.examples\n\tfor (name, prob) in Optim.UnconstrainedProblems.examples\n\t\tif prob.isdifferentiable\n\t\t\tdf = DifferentiableFunction(prob.f, prob.g!)\n\t\t\tres = Optim.optimize(df, prob.initial_x, ConjugateGradient())\n\t\t\t\t@assert norm(Optim.minimizer(res) - prob.solutions) < 1e-2\n\t\tend\n\tend\n\n\tlet\n\tobjective(X, B) = sum((X.-B).^2)/2\n\n\tfunction objective_gradient!(X, G, B)\n\t    for i = 1:length(G)\n\t        G[i] = X[i]-B[i]\n\t    end\n\tend\n\n\tsrand(1)\n\tB = rand(2,2)\n\tdf = Optim.DifferentiableFunction(X -> objective(X, B), (X, G) -> objective_gradient!(X, G, B))\n\tresults = Optim.optimize(df, rand(2,2), ConjugateGradient())\n\t@assert Optim.converged(results)\n\t@assert Optim.minimum(results) < 1e-8\n\tend\nend\n", "meta": {"hexsha": "24026b0a193cac10e94b58bfbd7311a24c70e1c5", "size": 780, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cg.jl", "max_stars_repo_name": "jngod2011/Optim.jl", "max_stars_repo_head_hexsha": "addda9ae36044d691b83a12c421b57675b234eeb", "max_stars_repo_licenses": ["MIT"], "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/cg.jl", "max_issues_repo_name": "jngod2011/Optim.jl", "max_issues_repo_head_hexsha": "addda9ae36044d691b83a12c421b57675b234eeb", "max_issues_repo_licenses": ["MIT"], "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/cg.jl", "max_forks_repo_name": "jngod2011/Optim.jl", "max_forks_repo_head_hexsha": "addda9ae36044d691b83a12c421b57675b234eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-15T05:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-15T05:01:29.000Z", "avg_line_length": 27.8571428571, "max_line_length": 96, "alphanum_fraction": 0.6871794872, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7690317336633468}}
{"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": "n = rand(1:10)\nA = matrixdepot(\"randcorr\", n)\n@test issym(A) # symmetric\n\n# positive semidefinite \nfor eig in eigvals(A)\n    @test eig >= 0\nend\n\n# 1s on the diagonal\n@test_approx_eq diag(A) ones(Float64, n)\nprintln(\"'randcorr' passed test...\")\n", "meta": {"hexsha": "2ab1a33a96aff44c565d71266d1e48849168564a", "size": 244, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_randcorr.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": "test/test_randcorr.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": "test/test_randcorr.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": 18.7692307692, "max_line_length": 40, "alphanum_fraction": 0.6803278689, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7690317327373862}}
{"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)\u00b2 + 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": "logis(x) = 1 ./(1 .+ exp(-x))\n", "meta": {"hexsha": "40951f218d3d2017efc1922e397b81843dbfc655", "size": 30, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/activations.jl", "max_stars_repo_name": "fmyilmaz/DeepNets.jl", "max_stars_repo_head_hexsha": "d4f903183da60974da0fef250709208038dd3255", "max_stars_repo_licenses": ["MIT"], "max_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": "fmyilmaz/DeepNets.jl", "max_issues_repo_head_hexsha": "d4f903183da60974da0fef250709208038dd3255", "max_issues_repo_licenses": ["MIT"], "max_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": "fmyilmaz/DeepNets.jl", "max_forks_repo_head_hexsha": "d4f903183da60974da0fef250709208038dd3255", "max_forks_repo_licenses": ["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": 29, "alphanum_fraction": 0.4, "num_tokens": 16, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7689984542470034}}
{"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": "infile = \"./src/Day13/input.txt\"\nf = readlines(infile)\narrival = parse(Int, f[1])\nbuses = parse.(Int,filter(x -> x != \"x\", split(f[2], \",\")))\n\nfunction find_next_bus(arrival, buses)\n    minutes_since_departure = mod.(arrival, buses)\n    if any(minutes_since_departure .== 0)\n        idx = findfirst(==(0), minutes_since_departure)\n        return buses[idx], 0\n    end\n    time_to_next = buses .- minutes_since_departure\n    idx = findmin(time_to_next)\n    return buses[idx[2]], idx[1]\nend\nid, wait =  find_next_bus(arrival, buses)\nid*wait\n\nstarttimes = [(parse(Int,step), t - 1) for (t, step) in enumerate(split(f[2],\",\")) if step != \"x\"]\n\nfunction find_match(start_t, multiple, nextbus)\n    step, offset = nextbus\n    check = start_t\n    while mod(check + offset, step) != 0\n        check +=  multiple\n    end\n    multiple = lcm(multiple, step)\n    return check, multiple\nend\n\ntestlist1 = \"17,x,13,19\"\ntestlist2 = \"67,7,59,61\"\n\nfind_match(0,17,(13,2))\nfind_match(102, 221, (19,3))\n\nfunction find_schedule(starttimes)\n    multiple, check = starttimes[1]\n    for nextbus in starttimes[2:end]\n        check, multiple = find_match(check, multiple, nextbus)\n    end\n    return check\nend\n\na = find_schedule(starttimes)\n", "meta": {"hexsha": "620b0c68da8fd1de98bcab3a43307e821a3b551d", "size": 1214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Day13/Day13.jl", "max_stars_repo_name": "metanoid/AOC2020", "max_stars_repo_head_hexsha": "2ab778dc749f54cdab16c01e134d572c3c6074e9", "max_stars_repo_licenses": ["MIT"], "max_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/Day13.jl", "max_issues_repo_name": "metanoid/AOC2020", "max_issues_repo_head_hexsha": "2ab778dc749f54cdab16c01e134d572c3c6074e9", "max_issues_repo_licenses": ["MIT"], "max_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/Day13.jl", "max_forks_repo_name": "metanoid/AOC2020", "max_forks_repo_head_hexsha": "2ab778dc749f54cdab16c01e134d572c3c6074e9", "max_forks_repo_licenses": ["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.3913043478, "max_line_length": 98, "alphanum_fraction": 0.6606260297, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7689984499344473}}
{"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   \u03bb, U=eigen(A)\n   return (reverse(\u03bb), reverse(U, dims=2))\nend\n\nfunction eig(A, B)\n   \u03bb, U=eigen(A, B)\n   return (reverse(\u03bb), 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\u22c5n`` square matrix `C`, defined as\n(Congedo et al., 2008)[\ud83c\udf93](@ref).\n\n``\\\\frac{\\\\sum_{i\u2260j}|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 \u2260 size(C, 2) && throw(ArgumentError(\"\ud83d\udccc, 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\u22c5n`` 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`, \u03b2 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\u22481.0 ? println(\" \u2b50 \") : println(\" \u26d4 \")\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 \u2260 c && throw(ArgumentError(\"\ud83d\udccc, 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\u2208eachcol(P)) + sum(mos(abs.(p)) for p\u2208eachrow(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=\u25cb) where {T<:AbstractFloat}\n```\n\n(1)\nGenerate a ``t\u22c5n`` random data matrix as ``XA``,\nwhere ``X`` is a ``t\u22c5n`` matrix with entries randomly drawn\nfrom a Gaussian distribution and ``A`` a ``n\u22c5n`` symmetric\nmatrix, which, if not provided as argument `A`,\nwill be generated with entries randomly drawn from a uniform\ndistribution \u2208[-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 \u2208[-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=\u25cb)\n   if A===\u25cb 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=\u25cb) where {T<:AbstractFloat}\n  if A===\u25cb 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   \u03bb, U = eig(C)\n   \u03bb=_check\u03bb(\u03bb) # make sure no imaginary noise is present (for complex data)\n   simple ? (U, Matrix(U'), Diagonal(\u03bb), \u25cb, \u25cb, \u25cb) :\n   begin\n     eVar===\u25cb ? eVar=0.999 : \u25cb\n     eVar, D, U, p, arev=_ssd!(eVar, \u03bb, U, _minDim(C), eVarMeth)\n     (U, Matrix(U'), D, eVar, \u03bb, 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\u2071, D, eVar, \u03bb, arev=_getEVD(C, eVar, eVarMeth, simple)\n  if simple\n     if eltype(C)<:Real\n        ispos(diag(D); tol=eps(eltype(C)), rev=true, \ud83d\udd14=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\u2071, D, \u25cb, \u25cb, \u25cb)\n  else\n     (U*D^-0.5, D^0.5*U\u2071, D, eVar, \u03bb, 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)\u2260n && throw(ArgumentError(\ud83d\udccc*\", _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===\u25cb\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_)\u2260s && throw(ArgumentError(\ud83d\udccc*\", _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 \u2208 (1, 2) || throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   wX\u2260\u25cb && lenght(wX)\u2260size(X, dims) && throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: The size of `wX` does not fit input matrix `X` with `dims`=$dims\"))\n   eltype(X)<:Complex && covEst\u2260SCM && throw(ArgumentError(\ud83d\udccc*\", _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(\ud83d\udccc*\", _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 \u2208 (1, 2) || throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   size(X, dims)==size(Y, dims) || throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: The `dims` dimension of argument `X` and `Y` must be the same\"))\n   wXY\u2260\u25cb && lenght(wXY)\u2260size(X, dims) && throw(ArgumentError(\ud83d\udccc*\", _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\u2260SCM && throw(ArgumentError(\ud83d\udccc*\", _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(\ud835\udc17::VecMat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Into, w::Twf)\n   dims \u2208 (1, 2) || throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   x=collect(size(X, _flip12(dims)) for X \u2208 \ud835\udc17)\n   all(y->y==x[1], x) ||  throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: Given `dims`=$dims, all matrices in `\ud835\udc17` must have the same dimension $(_flip12(dims))\"))\n   w\u2260\u25cb && !(w isa Function) && lenght(w)\u2260length(\ud835\udc17) && throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: The size of `w` must be equal to the number of matrices in `\ud835\udc17`\"))\n   !isempty(findall(x->eltype(x)<:Complex, \ud835\udc17)) && covEst\u2260SCM && throw(ArgumentError(\ud83d\udccc*\", _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(\ud835\udc17::VecMat, \ud835\udc18::VecMat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Into, meanY::Into, w::Twf)\n   dims \u2208 (1, 2) || throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: Argument `dims` may be 1 or 2. dims=$dims\"))\n   length(\ud835\udc17)==length(\ud835\udc18) || throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: The number of matrices in `\ud835\udc17` and `\ud835\udc18` must be the same\"))\n   x=collect(size(X, dims)-size(Y, dims) for (X, Y) \u2208 (\ud835\udc17, \ud835\udc18))\n   norm(x)==0 || throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: The `dims` dimension of all pairs of matrices in `\ud835\udc17` and `\ud835\udc18` must be the same\"))\n   w\u2260\u25cb && !(w isa Function) && lenght(w)\u2260length(\ud835\udc17) && throw(ArgumentError(\ud83d\udccc*\", _check-data internal function: The size of `w` must be equal to the number of matrices in `\ud835\udc17` and `\ud835\udc18`\"))\n   (!isempty(findall(x->eltype(x)<:Complex, \ud835\udc17)) || !isempty(findall(y->eltype(y)<:Complex, \ud835\udc18))) && covEst\u2260SCM && throw(ArgumentError(\ud83d\udccc*\", _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(\ud835\udc7f::VecVecMat, dims::Int64, covEst::StatsBase.CovarianceEstimator, meanX::Into, \u25cb)===\u25cb && 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 = \u25cb) where R<:Real\n   #T = R isa Real ? Symmetric : Hermitian\n   X_=_deMean(X, dims, meanX)\n   return wX===\u25cb ? 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 = \u25cb) where R<:Complex\n   X_=_deMean(X, dims, meanX)\n   wX\u2260\u25cb ? ( 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(\ud835\udc17::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   \ud835\udc02=Vector{Hermitian}(undef, length(\ud835\udc17))\n   @threads for i=1:length(\ud835\udc17)\n               \ud835\udc02[i]=Hermitian(_cov(\ud835\udc17[i], covEst, dims, meanX, \u25cb))\n   end\n   return \ud835\udc02\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 = \u25cb) where R<:Union{Real, Complex}\n   (size(X, dims) \u2260 size(Y, dims)) && throw(ArgumentError(\ud83d\udccc*\", _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===\u25cb ? ( 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(\ud835\udc17::VecMat, \ud835\udc18::VecMat;\n              dims     :: Int64 = 1,\n              meanX    :: Into = 0,\n              meanY    :: Into = 0)\n   (length(\ud835\udc17)\u2260length(\ud835\udc18)) && throw(ArgumentError(\ud83d\udccc*\", _cov internal function: vectors \ud835\udc17 and \ud835\udc18 must hold the same number of data matrices\"))\n   \ud835\udc02=Vector{Matrix}(undef, length(\ud835\udc17))\n   @threads for i=1:length(\ud835\udc17)\n               \ud835\udc02[i]=_cov(\ud835\udc17[i], \ud835\udc18[i], dims, meanX, meanY, \u25cb)\n            end\n   return \ud835\udc02\nend\n\n\n# if     m=1 \ud835\udc17 is a vector of k data matrices.\n#           Return a kx1x1 array of their covariance matrices in the k dimension\n# elseif k=1 \ud835\udc17 is a vector of m data matrices.\n#           Return a 1xmxm array of all cross-covariances of \ud835\udc17[i] and \ud835\udc17[j], for i,j=1:m\n# elseif \ud835\udc17 is a k-vector of m data matrices.\n#           Return a kxmxm array of all cross-covariances of \ud835\udc17[l][i] and \ud835\udc17[l][j], for l=1:k, i,j=1:m\nfunction _crossCov(\ud835\udc17, m, k;\n                   covEst  :: StatsBase.CovarianceEstimator=SCM,\n                   dims    :: Int64 = 1,\n                   meanX   :: Into = 0,\n                   trace1  :: Bool = false,\n                   w       :: Union{Tw, Function}=\u25cb)\n    \ud835\udc9e=Array{Matrix}(undef, k, m, m)\n    if      m==1\n      @inbounds for \u03ba=1:k \ud835\udc9e[\u03ba, 1, 1] = _cov(\ud835\udc17[\u03ba], covEst, dims, meanX, \u25cb) end\n    elseif  k==1\n      @inbounds for i=1:m-1, j=i+1:m\n                        \ud835\udc9e[1, i, j] = _cov(\ud835\udc17[i], \ud835\udc17[j], dims, meanX, meanX, \u25cb)\n                        \ud835\udc9e[1, j, i] = \ud835\udc9e[1, i, j]'\n                end\n      @inbounds for i=1:m \ud835\udc9e[1, i, i] = _cov(\ud835\udc17[i], covEst, dims, meanX, \u25cb) end # This is needed for scaling in any case\n    else\n      @inbounds for \u03ba=1:k, i=1:m-1, j=i+1:m\n                        \ud835\udc9e[\u03ba, i, j] = _cov(\ud835\udc17[\u03ba][i], \ud835\udc17[\u03ba][j], dims, meanX, meanX, \u25cb)\n                        \ud835\udc9e[\u03ba, j, i]=\ud835\udc9e[\u03ba, i, j]'\n                end\n      @inbounds for \u03ba=1:k, i=1:m \ud835\udc9e[\u03ba, i, i] = _cov(\ud835\udc17[\u03ba][i], covEst, dims, meanX, \u25cb) end # This is needed for scaling in any case\n    end\n\n    # trace normalize\n    if trace1 || w \u2260 \u25cb _Normalize!(\ud835\udc9e, m, k, trace1, w) end\n\n    return \ud835\udc9e\nend\n\n\n# get index and value of the\n# first value in \ud835\udf06 greater than or equal to eVar (eVarMeth=searchsortedfirst) or\n# last value in \ud835\udf06 less than or equal to eVar (eVarMeth=searchsortedlast),\n# where \ud835\udf06 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 (\u03bb),\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 (\u03bb!),\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, \u03bb::Vec, r::Int64, eVarMeth::Function)\n   eltype(\u03bb)<:Complex && @warn \"\ud83d\udccc, internal function `_getssd!`: the `\u03bb` vector is complex, subspace dimension is based on its absolute values.\"\n   eVar===\u25cb ? eVar=0.999 : \u25cb\n   \u03bb_=abs.(\u03bb)\n   arev = accumulate(+, \u03bb_./sum(\u03bb_))\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, \u03bb::Vec, U::Mat, r::Int64, eVarMeth::Function)\n   eltype(\u03bb)<:Complex && @warn \"\ud83d\udccc, internal function `_ssd!`: the `\u03bb` vector is complex, subspace dimension is based on its absolute values.\"\n   p, arev = _getssd!(eVar, \u03bb, r, eVarMeth)\n   return p==r ? 1. : arev[p], Diagonal(\u03bb[1:p]), U[:, 1:p], p, arev\nend\n\n#see PMCA and CCA\nfunction _ssdxy!(eVar::TeVaro, \u03bb::Vec, U1::Mat, U2::Mat, r::Int64, eVarMeth::Function)\n   eltype(\u03bb)<:Complex && @warn \"\ud83d\udccc, internal function `_ssdxy!`: the `\u03bb` vector is complex, subspace dimension  is based on its absolute values.\"\n   p, arev = _getssd!(eVar, \u03bb, r, eVarMeth)\n   return p==r ? 1. : arev[p], Diagonal(\u03bb[1:p]), U1[:, 1:p], U2[:, 1:p], p, arev\nend\n\n# see CSP\nfunction _ssdcsp!(eVar::TeVaro, \u03bb::Vec, U::Mat, r::Int64, eVarMeth::Function, selMeth::Symbol)\n   eltype(\u03bb)<:Complex && @warn \"\ud83d\udccc, internal function `_ssdcsp!`: the `\u03bb` vector is complex, subspace dimension  is based on its absolute values.\"\n   \u03bb_=abs.(\u03bb)\n   ratio = \u03bb_./(1.0.-\u03bb_)\n   d = (log.(ratio)).^2\n   h = selMeth==:extremal ? sortperm(d; rev=true) : [i for i=1:length(\u03bb)]\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(\u03bb[h[1:p]]), U[:, h[1:p]], p, arev\nend\n\n# see CSTP\nfunction _ssdcstp!(eVar::TeVaro, \u03bb::Vec, U::Mat, V::Mat, r::Int64, eVarMeth::Function)\n   eltype(\u03bb)<:Complex && @warn \"\ud83d\udccc, internal function `_ssdcstp!`: the `\u03bb` vector is complex, subspace dimension is based on its absolute values.\"\n   \u03bb_=abs.(\u03bb)\n   arev = accumulate(+, \u03bb_./sum(\u03bb_))\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(\u03bb[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, \ud83d\udccc*\", _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(\ud835\udc17::VecMat)=argmax(sum(collect(size(X)) for X \u2208 \ud835\udc17))\n_set_dims(\ud835\udc17::VecMat, \ud835\udc18::VecMat)=\n    argmax(sum(collect(size(X)) for X \u2208 \ud835\udc17)+sum(collect(size(Y)) for Y \u2208 \ud835\udc18))\n_set_dims(\ud835\udc7f::VecVecMat)=argmax(sum(collect(size(\ud835\udc7f[i][j])) for i=1:length(\ud835\udc7f) for j=1:length(\ud835\udc7f[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(\ud835\udc02::\u210dVector) = minimum(size(C, 1) for C \u2208 \ud835\udc02)\n_minDim(C1::SorH, C2::SorH) = min(size(C1, 1), size(C2, 1))\n_minDim(\ud835\udc17::VecMat) = minimum(minimum(size(X)) for X \u2208 \ud835\udc17)\n_minDim(\ud835\udc17::VecMat, \ud835\udc18::VecMat) = min(_minDim(\ud835\udc17), _minDim(\ud835\udc18))\n_minDim(\ud835\udc7f::VecVecMat) = minimum((minimum(minimum(size(X)) for X \u2208 \ud835\udc7f[i]) for i=1:length(\ud835\udc7f)))\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    \u03b1 ~ Normal(0, 100)\n    \u03b2p ~ Normal(0, 1)\n    \u03b2c ~ Normal(0, 1)\n    \u03b2pc ~ Normal(0, 1)\n\n    for i \u2208 1:length(total_tools)\n        \u03bb = exp(\u03b1 + \u03b2p*log_pop_c[i] + \u03b2c*contact_high[i] +\n            \u03b2pc*contact_high[i]*log_pop_c[i])\n        total_tools[i] ~ Poisson(\u03bb)\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\u209c = Au\u2093\u2093 + f(u)\n\non (a, b), where A = \u0394 and f(u) = -u\u00b3 + u.\n\"\"\"\nstruct AllenCahnProblem1D{TLBC, TRBC, TA}\n    a::Real # Left endpoint\n    b::Real # Right endpoint\n    \u03f5::Real # Model parameter\n    n\u2093::Int # Total number of interior spatial mesh points\n    \u0394x::Real # Spatial mesh spacing\n    x::Vector # Spatial mesh points including boundary\n    n\u209c::Int # Number of timesteps\n    t_max::Real # Final time for integration\n    \u0394t::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\u00b3 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\u2093(a) = v\u2097  or  u\u2093(b) = v\u1d63\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\u2093(a) = u\u2093(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": "# TODO:\n# - midpoint rule\n# x scattered/interpolation\n# x GCV\n# x L-curve\n# - bounds on \u03bb\n# - initial guess for \u03bb? will require mods to RegularizationTools\n# - scaled \u03bb? will need to work out equivalency with \u03bb\u00b2 formulation, and resolve with\n#   derivative rather than difference matrix\n# - standard deviation\n# - relative weights? (not sure if worth implementing)\n# - arbitrary weighting\n\n\nconst LA = LinearAlgebra\n\n# might move this to RegularizationTools.jl? JJS 12/6/21\n\"\"\"\nOrder d derivative matrix for the provided t vector\n\"\"\"\nfunction _derivative_matrix(t::AbstractVector, d::Int)\n    N = length(t)\n    if d == 0\n        return Array{Float64}(LA.I, (N, N))\n    end\n    dt = t[d+1:end] - t[1:end-d]\n    V = LA.diagm(1 ./ dt)\n    # could use this symbol:  D\u1d48\u207b\u00b9 (D\\^d\\^-\\^1) (but a lot of typing...)\n    Ddm1 = diff(_derivative_matrix(t, d-1), dims=1)\n    D = d * V*Ddm1\n    return D\nend\n\n### Regularization data smoothing and interpolation\nstruct RegularizationSmooth{uType,tType,FT,T} <: AbstractInterpolation{FT,T}\n    u::uType\n    u\u0302::uType\n    t::tType\n    t\u0302::tType\n    d::Int              # derivative degree used to calculate the roughness\n    \u03bb::AbstractFloat    # regularization parameter\n    alg::Symbol  # how to determine \u03bb: `:fixed`, `:gcv_svd`, `:gcv_tr`, `L_curve`\n    Aitp::AbstractInterpolation{FT,T}\n    RegularizationSmooth{FT}(u,u\u0302,t,t\u0302,d,\u03bb,alg,Aitp) where FT =\n        new{typeof(u),typeof(t),FT,eltype(u)}(u,u\u0302,t,t\u0302,d,\u03bb,alg,Aitp)\nend\n\nfunction RegularizationSmooth(u, t, d=2; \u03bb=1.0, t\u0302=nothing, alg=:gcv_svd)\n    # TBD:  make use of `munge_data`\n    u, t = munge_data(u, t)\n    \u03bb = float(\u03bb) # in case an integer is given for \u03bb\n    N = length(t)\n    if isnothing(t\u0302)\n        t\u0302 = t\n        M = Array{eltype(t)}(LA.I, (N, N)) # identity mapping matrix\n    else\n        M = _mapping_matrix(t\u0302, t) \n    end\n\n    # RT.\u0393 function, used internally there, does not not account for spacing of x \n    #\u03a8 = RT.setupRegularizationProblem(M, d)\n    D = _derivative_matrix(t\u0302,d)\n    \u03a8 = RT.setupRegularizationProblem(M, D)\n    \n    if alg == :fixed\n        b\u0304 = RT.to_standard_form(\u03a8, u) # via b\u0304\n        u\u0304 = RT.solve(\u03a8, b\u0304, \u03bb)\n        u\u0302 = RT.to_general_form(\u03a8, u, u\u0304)\n    else\n        # note that the provided \u03bb is currently ignored\n        result = RT.solve(\u03a8, u, alg=alg)\n        u\u0302 = result.x\n        \u03bb = result.\u03bb\n    end\n    # I'm not sure about mathematical theory for performing a posteriori interpolation via\n    # Regularization smoothing -- applying Cubic-spline interpolation seems reasonable to\n    # me, so setting that up here to use after object-creation; could allow users the option\n    # of a posteriori interpolation or not, or even a choice for the interpolation,\n    # depending on what is needed. B-spline interpolation of order d+1 also seems to be a\n    # reasonable choice, but it is not allowing extrapolation and doesn't show much benefit\n    # over cubic-spline. JJS 12/3/21\n    Aitp = CubicSpline(u\u0302,t\u0302)\n    #Aitp = BSplineInterpolation(u\u0302,t\u0302,d+1,:ArcLen,:Average)\n    RegularizationSmooth{true}(u,u\u0302,t,t\u0302,d,\u03bb,alg,Aitp)\nend\n\n\"\"\"Linear interpolation mapping matrix, which maps `u\u0302` to `u`.\"\"\"\nfunction _mapping_matrix(t\u0302::AbstractVector,t::AbstractVector)\n    N = length(t)\n    N\u0302 = length(t\u0302)\n    # map the scattered points to the appropriate index of the smoothed points\n    idx = searchsortedlast.(Ref(t\u0302),t)\n    # allow for \"extrapolation\"; i.e. for t\u0302 extremum that are interior to t\n    idx[idx.==0] .+= 1\n    idx[idx.==N\u0302] .+= -1 \n    # create the linear interpolation matrix\n    m2 = @. (t - t\u0302[idx])/(t\u0302[idx+1] - t\u0302[idx])\n    M = zeros(eltype(t), (N,N\u0302))\n    for i in 1:N\n        M[i,idx[i]] = 1 - m2[i] \n        M[i,idx[i]+1] = m2[i]\n    end\n    return M\nend\n\n_interpolate(A::RegularizationSmooth{<:AbstractVector{<:Number}}, t::Number) =\n    _interpolate(A.Aitp, t)\n", "meta": {"hexsha": "9d195608a1157084fc195989a4437b1c6bb6d73e", "size": 3821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regularization_smooth.jl", "max_stars_repo_name": "PumasAI/DataInterpolations.jl", "max_stars_repo_head_hexsha": "c5acb4e56ed8c9e929d4ae56622d16d4fb831458", "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/regularization_smooth.jl", "max_issues_repo_name": "PumasAI/DataInterpolations.jl", "max_issues_repo_head_hexsha": "c5acb4e56ed8c9e929d4ae56622d16d4fb831458", "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/regularization_smooth.jl", "max_forks_repo_name": "PumasAI/DataInterpolations.jl", "max_forks_repo_head_hexsha": "c5acb4e56ed8c9e929d4ae56622d16d4fb831458", "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": 35.3796296296, "max_line_length": 92, "alphanum_fraction": 0.6425019628, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7689984454577751}}
{"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    \u03f5 = 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 < -\u03f5\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 .< -\u03f5, 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] .< -\u03f5) : 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\u00d73 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\u00d73 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\u00d73 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        \u03f5 = T <: AbstractFloat ? eps(norm(M,Inf)) : eps(typeof(x))\n        return abs(x) > \u03f5\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\u00d73 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\u00d73 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\u00d73 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\u00d73 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            \u03bb\n            mult\n            eigenmatrix\n        end\n        \n        function texstring(E::EigenSpace)\n            s = \"\\\\mathrm{eigenspace}\\\\left(\"\n            s *= \"\u03bb = \"\n            s *= SymPy.latex(E.\u03bb,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 *= \"\u03bb = \"\n            _io = IOBuffer()\n            show(_io,(MIME\"text/plain\").instance,E.\u03bb)\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        \u23a13 + 2\u22c5\u221a3 \u23a4\n        \u23a2         \u23a5\n        \u23a3-2\u22c5\u221a3 + 3\u23a6\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        \u03bb = 3 + 2 \\\\sqrt{3}, mult = 1, \n        \u23a1  1   \u221a3\u23a4\n        \u23a2- \u2500 + \u2500\u2500\u23a5\n        \u23a2  2   2 \u23a5\n        \u23a2        \u23a5\n        \u23a3   1    \u23a6\n        )\n\n        eigenspace(\n        \u03bb = - 2 \\\\sqrt{3} + 3, mult = 1, \n        \u23a1  \u221a3   1\u23a4\n        \u23a2- \u2500\u2500 - \u2500\u23a5\n        \u23a2  2    2\u23a5\n        \u23a2        \u23a5\n        \u23a3   1    \u23a6\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            \u03bb = SymPy.symbols(\"lambda\")\n            B = map(x->convert(SymPy.Sym,x),A)\n            return SymPy.getindex(B,:charpoly)()(\u03bb)\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, \u03a3, 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, \u03b1=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 \u2286 m \u00b1 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 `\u03a1` (big rho). Normalise it so that it\n    # sums to 1 and forms a true probability distribution over the simplices.\n    =#\n    \u03a1 = rand(Float64, 1, size(M, 1))\n    \u03a1 = \u03a1 ./ sum(\u03a1, 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 \u03a1\n    # until the distribution converges. Here, we use the latter approach,\n    # meaning that we iterate until \u03a1 doesn't change substantially between\n    # iterations.\n    =#\n    distribution = \u03a1 * M\n\n    distance = norm(distribution - \u03a1) / norm(\u03a1)\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        \u03a1 = distribution\n\n        # Apply the Markov matrix to the current state of the distribution\n        distribution = \u03a1 * 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 - \u03a1) / norm(\u03a1)\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    \u0394t  = 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 \u03b8 in 0.0:2\u03c0/100:2\u03c0\n    v = [cos(\u03b8),sin(\u03b8)]\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\", \u03b8))\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\u03b8s = 0.0:\u03c0/1000:\u03c0\nplot(collect(\u03b8s), map(x -> var(vec([cos(x),sin(x)]'*Y)), \u03b8s),\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\u03b8pca = atan(-U[2,1],-U[1,1])\n##\nplot(collect(\u03b8s), map(x -> var(vec([cos(x),sin(x)]'*Y)), \u03b8s),\nlabel=\"\", size=(500,250))\nxlabel!(\"Angle\")\nylabel!(\"Variance\")\nannotate!(\u03b8pca, var(vec([cos(\u03b8pca),sin(\u03b8pca)]'*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\u03c3(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->\u03c3(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 `\u03c3(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 $\u03c3(x_1,w, b)$ for our apple. So, we want the difference $0 - \u03c3(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 - \u03c3(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 - \u03c3(x_1, w, b))^2 + (1 - \u03c3(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 - \u03c3(apple_green_amount,w,b))^2 + (1 - \u03c3(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->\u03c3(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 \u03bb 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 \u21a6 (\u03bb/2) inf { ||x-y||^2 : y \u2208 S} \"\nfun_params(f::SqrDistL2) = string(\"\u03bb = $(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\u03b2c() = 0.5*log(sqrt(2.0)+1.0)\n\nfunction ising_free_energy(\u03b2::Real,J::Real=1.0)\n  k = \u03b2*J\n  c = cosh(2.0*k)\n  s = sinh(2.0*k)\n  xmin = 0.0\n  xmax = \u03c0\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/\u03c0)/(2.0*\u03b2)\nend\n\nfunction ising_magnetization(\u03b2::Real)\n \u03b2>\u03b2c && return (1.0-sinh(2.0*\u03b2)^(-4))^(1/8)\n return 0.0\nend\n\nfunction ising_mpo(sh::Tuple{Index,Index},sv::Tuple{Index,Index},\n                   \u03b2::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(\u03b2*J) exp(-\u03b2*J); exp(-\u03b2*J) exp(\u03b2*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,\u03b2)\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]),\u03b2)\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": "\nusing SimpleSolvers\nusing Test\n\n\nn = 2\nx = rand(n)\ng = 2x\nT = eltype(x)\n\n\nfunction F(x::Vector)\n    1 + sum(x.^2)\nend\n\nfunction \u2207F!(g::Vector, x::Vector)\n    g .= 0\n    for i in eachindex(x,g)\n        g[i] = 2x[i]\n    end\nend\n\n\n\u2207PAD = GradientParameters{T}(F, n; mode = :autodiff, diff_type = :forward)\n\u2207PFD = GradientParameters{T}(F, n; mode = :autodiff, diff_type = :finite)\n\u2207PUS = GradientParameters{T}(\u2207F!, n; mode = :user)\n\n@test typeof(\u2207PAD) <: GradientParametersAD\n@test typeof(\u2207PFD) <: GradientParametersFD\n@test typeof(\u2207PUS) <: GradientParametersUser\n\n\nfunction test_grad(g1, g2, atol)\n    for i in eachindex(g1,g2)\n        @test g1[i] \u2248 g2[i] atol=atol\n    end\nend\n\n\ngad = zero(g)\ngfd = zero(g)\ngus = zero(g)\n\ncompute_gradient!(gad, x, \u2207PAD)\ncompute_gradient!(gfd, x, \u2207PFD)\ncompute_gradient!(gus, x, \u2207PUS)\n\ntest_grad(gad, g, eps())\ntest_grad(gfd, g, 1E-7)\ntest_grad(gus, g, 0)\n\n\ngad1 = zero(g)\ngfd1 = zero(g)\ngus1 = zero(g)\n\ncompute_gradient!(gad1, x, F; mode = :autodiff, diff_type = :forward)\ncompute_gradient!(gfd1, x, F; mode = :autodiff, diff_type = :finite)\ncompute_gradient!(gus1, x, \u2207F!; mode = :user)\n\ntest_grad(gad, gad1, 0)\ntest_grad(gfd, gfd1, 0)\ntest_grad(gus, gus1, 0)\n\n\ngad2 = zero(g)\ngfd2 = zero(g)\n\ncompute_gradient_ad!(gad2, x, F)\ncompute_gradient_fd!(gfd2, x, F)\n\ntest_grad(gad, gad2, 0)\ntest_grad(gfd, gfd2, 0)\n", "meta": {"hexsha": "f1ed6219fb4511581416f95cbf17c059ba4782bb", "size": 1342, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gradient_tests.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": "test/gradient_tests.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": "test/gradient_tests.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": 18.1351351351, "max_line_length": 74, "alphanum_fraction": 0.652757079, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.8577681104440171, "lm_q1q2_score": 0.7687758515697142}}
{"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].\u03bc for i in 1:4]) / 4.0;\nsigma_avg = sum([fits[i].\u03c3 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    \u03bc = round(fits[i].\u03bc, digits=2)\n    \u03c3 = round(fits[i].\u03c3, 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].\u03bc, fits[i].\u03c3), x), lab=\"Fitted Normal($\u03bc, $\u03c3)\")\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": "# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/\n#  Niccol\u00f2 Antonello <nantonel@idiap.ch>\n\n# compose \n# using ex from Mohri et al. Speech recognition with FiniteStateTransducers \nL = String\nW = TropicalWeight{Float32}\nA = WFST([\"a\",\"b\",\"c\"]; W = W)\nadd_arc!(A, 1, 2, \"a\", \"b\", 0.1) \nadd_arc!(A, 2, 2, \"c\", \"a\", 0.3) \nadd_arc!(A, 2, 4, \"a\", \"a\", 0.4) \nadd_arc!(A, 1, 3, \"b\", \"a\", 0.2) \nadd_arc!(A, 3, 4, \"b\", \"b\", 0.2) \nfinal!(A, 4, 0.6)\ninitial!(A, 1)\n#println(A)\nsize_A = size(A)\nB = WFST(get_isym(A); W = W)\nadd_arc!(B, 1, 2, \"b\", \"c\", 0.3) \nadd_arc!(B, 2, 3, \"a\", \"b\", 0.4) \nadd_arc!(B, 3, 3, \"a\", \"b\", 0.6) \nfinal!(B, 3, 0.7)\ninitial!(B, 1)\nsize_B = size(B)\n#println(B)\n\nC = \u2218(A,B; filter=Trivial)\n#println(C)\n@test size(A) == size_A\n@test size(B) == size_B\n@test isinitial(C,1)\n@test isfinal(C,4)\n@test get_weight(C,4) \u2248 W(1.3)\n@test get_weight(C[1][1]) \u2248 W(0.4)\n@test get_weight(C[2][1]) \u2248 W(0.7)\n@test get_weight(C[2][2]) \u2248 W(0.8)\n@test get_weight(C[3][1]) \u2248 W(0.9)\n@test get_weight(C[3][2]) \u2248 W(1.0)\n@test size(C) == (4,5)\n\n# using ex from http://openfst.org/twiki/bin/view/FST/ComposeDoc \nL = String\nW = TropicalWeight{Float64}\nA = WFST([\"a\",\"c\"],[\"q\",\"r\",\"s\"]; W=W)\nadd_arc!(A, 1, 2, \"a\", \"q\", 1.0) \nadd_arc!(A, 2, 2, \"c\", \"s\", 1.0) \nadd_arc!(A, 1, 3, \"a\", \"r\", 2.5) \ninitial!(A,1)\nfinal!(A,2,0)\nfinal!(A,3,2.5)\n#print(A)\n\nW = TropicalWeight{Float64}\nB = WFST(get_osym(A),[\"f\",\"h\",\"g\",\"j\"]; W=W)\nadd_arc!(B, 1, 2, \"q\", \"f\", 1.0) \nadd_arc!(B, 1, 3, \"r\", \"h\", 3.0) \nadd_arc!(B, 2, 3, \"s\", \"g\", 2.5) \nadd_arc!(B, 3, 3, \"s\", \"j\", 1.5) \ninitial!(B,1)\nfinal!(B,3,2)\n#print(B)\n\nC = \u2218(A,B,filter=Trivial)\n#println(C)\n\n@test isinitial(C,1)\n@test isfinal(C,3)\n@test isfinal(C,4)\n@test get_weight(C,3) \u2248 W(4.5)\n@test get_weight(C,4) \u2248 W(2.0)\n@test get_weight(C[1][1]) \u2248 W(2.0)\n@test get_ilabel(C,1,1) == \"a\"\n@test get_olabel(C,1,1) == \"f\"\n@test get_nextstate(C[1][1]) == 2\n@test get_weight(C[1][2]) \u2248 W(5.5)\n@test get_ilabel(C,1,2) == \"a\"\n@test get_olabel(C,1,2) == \"h\"\n@test get_nextstate(C[1][2]) == 3\n@test get_weight(C[2][1]) \u2248 W(3.5)\n@test get_ilabel(C,2,1) == \"c\"\n@test get_olabel(C,2,1) == \"g\"\n@test get_nextstate(C[2][1]) == 4\n@test get_weight(C[4][1]) \u2248 W(2.5)\n@test get_ilabel(C,4,1) == \"c\"\n@test get_olabel(C,4,1) == \"j\"\n@test get_nextstate(C[4][1]) == 4\n@test size(C) == (4,4)\n\n# using ex fig.8 (with different weights) from Mohri et al. Speech recognition with FiniteStateTransducers \n# with epsilon symbols\nA = txt2fst(\"openfst/A.fst\", \"openfst/sym.txt\")\nB = txt2fst(\"openfst/B.fst\", \"openfst/sym.txt\")\n# TODO add tests\n# for the moment we test equivalence of fst with sorted weights\nC = \u2218(A,B;filter=Trivial)\nC_openfst = txt2fst(\"openfst/C_trivial.fst\", \"openfst/sym.txt\")\n@test size(C) == size(C_openfst) \nw = sort([get_weight(a).x for a in get_arcs(C)])\nw_openfst = sort([get(get_weight(a)) for a in get_arcs(C_openfst)])\n@test all(w .== w_openfst)\n@test all(sort([values(C.finals)...]) .== sort([values(C_openfst.finals)...] ))\n#println(C)\n#println(C_openfst)\n\nC = \u2218(A,B;filter=EpsMatch)\nC_openfst = txt2fst(\"openfst/C_match.fst\", \"openfst/sym.txt\")\n@test size(C) == size(C_openfst)\nw = sort([get_weight(a).x for a in get_arcs(C)])\nw_openfst = sort([get(get_weight(a)) for a in get_arcs(C_openfst)])\n@test all(w .== w_openfst)\n@test all(sort([values(C.finals)...]) .== sort([values(C_openfst.finals)...] ))\n#println(C)\n#println(C_openfst)\n\nC = \u2218(A,B;filter=EpsSeq)\nC_openfst = txt2fst(\"openfst/C_sequence.fst\", \"openfst/sym.txt\")\n@test size(C) == size(C_openfst) \nw = sort([get_weight(a).x for a in get_arcs(C)])\nw_openfst = sort([get(get_weight(a)) for a in get_arcs(C_openfst)])\n@test all(w .== w_openfst)\n@test all(sort([values(C.finals)...]) .== sort([values(C_openfst.finals)...] ))\n#println(C)\n#println(C_openfst)\n\n## \nL = txt2fst(\"openfst/L.fst\", \"openfst/chars.txt\", \"openfst/words.txt\")\n#println(L)\nT = txt2fst(\"openfst/T.fst\", \"openfst/words.txt\", \"openfst/words.txt\")\n#println(T)\nLT = \u2218(L,T;filter=EpsSeq)\n#println(LT)\n@test size(LT) ==(11,10)\n@test_throws ErrorException T\u2218L # since A.osym != A.isym\n", "meta": {"hexsha": "6ede8fba09d83c53fbe67569fa9f11809b14d416", "size": 4048, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/compose.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": "test/compose.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": "test/compose.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": 30.2089552239, "max_line_length": 107, "alphanum_fraction": 0.6205533597, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7687758330331503}}
{"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_\u03bc = 30\n# number of observations per variable \nn_d = 100\n# random \u03bc parameters\n\u03bcs = rand(Normal(0.0, 1.0), n_\u03bc)\n# data\ndata = rand(MvNormal(\u03bcs, 1.0 * I), n_d)\n\n# function for initial values\nfunction sample_prior()\n    \u03bc = rand(Normal(0, 1), n_\u03bc)\n    \u03c3 = rand(truncated(Cauchy(0, 1), 0, Inf))\n    return as_union([\u03bc,\u03c3])\nend\n\n# returns prior log likelihood\nfunction prior_loglike(\u03bc, \u03c3)\n    LL = 0.0\n    LL += sum(logpdf.(Normal(0, 1), \u03bc))\n    LL += logpdf(truncated(Cauchy(0, 1), 0, Inf), \u03c3)\n    return LL\nend\n\n# likelihood function \nfunction loglike(data, \u03bcs, \u03c3)\n    return sum(logpdf(MvNormal(\u03bcs, \u03c3^2 * I), data))\nend\n\n# upper and lower bounds of parameters\nbounds = ((-Inf,Inf),(0.0,Inf))\n# parameter names \nnames = (:\u03bc,:\u03c3)\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_\u03bc + 1) * 4,\n    Np = 3,\n    n_groups = 1,\n    \u03b8snooker = 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": "\u03bd(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    \u03bd(G, L, Es, p)\nend\n\nfunction reaction(du, u, p, t)\n    G, L, Es = u\n    dG  = du[1] = - \u03bd(G, L, Es, p)\n    dL  = du[2] = - \u03bd(G, L, Es, p)\n    dEs = du[3] =   \u03bd(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\u2080, t\u2091; nPoints=20)\n    p = (9.03f-2, 5.0f-2, 1.9f1)\n    tspan = (0.0, t\u2091)\n    \n    prob = ODEProblem(reaction!, u\u2080, tspan, p, saveat=0:t\u2091/nPoints:t\u2091)\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": "using DelimitedFiles\n\nfunction ReadData(fname::AbstractString)\n    return readdlm(fname)\nend\n\nfunction Part1(instructions::AbstractArray)\n    x, y = 0, 0\n    for i = 1:length(instructions[:,1])\n        if instructions[i,1] == \"forward\"\n            x += instructions[i,2]\n        elseif instructions[i,1] == \"up\"\n            y -= instructions[i,2]\n        elseif instructions[i,1] == \"down\"\n            y += instructions[i,2]\n        end\n    end\n\n    return x*y\nend\n\n\nfunction Part2(instructions::AbstractArray)\n    x, y, aim = 0, 0, 0\n    for i = 1:length(instructions[:,1])\n        if instructions[i,1] == \"forward\"\n            x += instructions[i,2]\n            y += instructions[i,2]*aim\n        elseif instructions[i,1] == \"up\"\n            aim -= instructions[i,2]\n        elseif instructions[i,1] == \"down\"\n            aim += instructions[i,2]\n        end\n    end\n\n    return x*y\nend\n\ninstructions = ReadData(\"../data/day2.txt\")\nprintln(Part1(instructions))\nprintln(Part2(instructions))\n", "meta": {"hexsha": "d5c8728d13d92ee52be606e4db3f8ee8a2cedf3b", "size": 992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day2.jl", "max_stars_repo_name": "andrew0796/AdventOfCode_2021", "max_stars_repo_head_hexsha": "9d2e6f19cb555f89dac141cc081da4ce58558a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day2.jl", "max_issues_repo_name": "andrew0796/AdventOfCode_2021", "max_issues_repo_head_hexsha": "9d2e6f19cb555f89dac141cc081da4ce58558a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day2.jl", "max_forks_repo_name": "andrew0796/AdventOfCode_2021", "max_forks_repo_head_hexsha": "9d2e6f19cb555f89dac141cc081da4ce58558a2d", "max_forks_repo_licenses": ["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.619047619, "max_line_length": 43, "alphanum_fraction": 0.5786290323, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7687274301666999}}
{"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   - \u03a3 - the correlation matrix must be symmetric, positively defined and with ones on diagonal\n\nConstructor\n\n    Gaussian_cop(\u03a3::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  \u03a3::Matrix{T}\n  n::Int\n  function(::Type{Gaussian_cop})(\u03a3::Matrix{T}) where T <: Real\n    \u03a3 \u2248 transpose(\u03a3) || throw(DomainError(\"\u03a3 matrix not symmetric\"))\n    isposdef(\u03a3) || throw(DomainError(\"\u03a3 matrix not positivelly defined\"))\n    prod(diag(\u03a3)) \u2248 1.0 || throw(DomainError(\"\u03a3 matrix do not have ones on diagonal\"))\n    new{T}(\u03a3,size(\u03a3,1))\n  end\nend\n\n\nfunction simulate_copula!(U, copula::Gaussian_cop{T}; rng = Random.GLOBAL_RNG) where T\n  \u03a3 = copula.\u03a3\n  z = transpose(rand(rng, MvNormal(\u03a3),size(U,1)))\n  for i in 1:size(\u03a3, 1)\n    d = Normal(0, sqrt.(\u03a3[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  - \u03a3::Matrix{Real} - the correlation matrix must be symmetric, positively defined and with ones on diagonal\n  - \u03bd::Int - the parameter n.o. degrees of freedom we require \u03bd > 0\n\nConstructor:\n\n    Student_cop(\u03a3::Matrix{Real}, \u03bd::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  \u03a3::Matrix{T}\n  \u03bd::Int\n  n::Int\n  function(::Type{Student_cop})(\u03a3::Matrix{T}, \u03bd::Int) where T <: Real\n    \u03a3 \u2248 transpose(\u03a3) || throw(DomainError(\"\u03a3 matrix not symmetric\"))\n    isposdef(\u03a3) || throw(DomainError(\"\u03a3 matrix not positivelly defined\"))\n    prod(diag(\u03a3)) \u2248 1.0 || throw(DomainError(\"\u03a3 matrix do not have ones on diagonal\"))\n    \u03bd > 0 || throw(DomainError(\"\u03bd lower or equal zero\"))\n    new{T}(\u03a3, \u03bd,size(\u03a3,1))\n  end\nend\n\n\nfunction simulate_copula!(U, copula::Student_cop{T}; rng = Random.GLOBAL_RNG) where T\n  \u03a3 = copula.\u03a3\n  \u03bd = copula.\u03bd\n  z = transpose(rand(rng, MvNormal(\u03a3),size(U,1)))\n  V = rand(rng, Chisq(\u03bd), size(z, 1))\n  V = T.(V)\n  for i in 1:size(\u03a3, 1)\n    x = z[:,i].*sqrt.(\u03bd./V)./sqrt(\u03a3[i,i])\n    z[:,i] = cdf.(TDist(\u03bd), 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  - \u03b1 - the parameter of the maximal copula\n  - \u03b2 - the parameter of the minimal copula\n\nConstructor\n\n    Frechet_cop(n::Int, \u03b1::Real)\n\nThe one parameter Frechet copula is a combination of maximal copula with  weight \u03b1\nand independent copula with  weight 1-\u03b1.\n\nConstructor\n\n    Frechet_cop(n::Int, \u03b1::Real, \u03b2::Real)\n\nThe two parameters Frechet copula C = \u03b1 C{max} + \u03b2 C{min} + (1- \u03b1 - \u03b2) C{\u27c2}, 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  \u03b1::T\n  \u03b2::T\n  function(::Type{Frechet_cop})(n::Int, \u03b1::T) where T <:\u00a0Real\n    0 <= \u03b1 <= 1 || throw(DomainError(\"generaton not supported for \u03b1 \u2209 [0,1]\"))\n    n > 1 || throw(DomainError(\"n must be greater than 1\"))\n    new{T}(n, \u03b1, 0.)\n  end\n  function(::Type{Frechet_cop})(n::Int, \u03b1::T, \u03b2::T) where T <:\u00a0Real\n    0 <= \u03b1 <= 1 || throw(DomainError(\"generaton not supported for \u03b1 \u2209 [0,1]\"))\n    0 <= \u03b2 <= 1 || throw(DomainError(\"generaton not supported for \u03b2 \u2209 [0,1]\"))\n    n == 2 || throw(AssertionError(\"two parameters Frechet copula supported only for n = 2\"))\n    0 <= \u03b1+\u03b2 <= 1 || throw(DomainError(\"\u03b1+\u03b2 must be in range [0,1]\"))\n    new{T}(n, \u03b1, \u03b2)\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\u00d73 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\u00d73 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  \u03b1 = copula.\u03b1\n  \u03b2 = copula.\u03b2\n  size(U, 2) == n || throw(AssertionError(\"n.o. margins in pre allocated output and copula not equal\"))\n  if (\u03b2 > 0) & (n == 2)\n    for j in 1:size(U,1)\n      u_el = rand(rng, T, n)\n      frechet_el2!(u_el, \u03b1, \u03b2, 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, \u03b1, rand(rng))\n      U[j,:] = u_el\n    end\n  end\nend\n\n\"\"\"\n  frechet(t::Int, n::Int, \u03b1::Real; rng::AbstractRNG)\n\nGiven n-variate random data u \u2208 R^{t, n}\nReturns t realization of n variate data generated from one parameter Frechet_cop(n, \u03b1).\n\n```jldoctest\njulia> Random.seed!(43);\n\njulia> u = rand(10, 2);\n\njulia> frechet(0.5, u)\n10\u00d72 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(\u03b1::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, \u03b1, v)\n    u[j,:] = el\n  end\n  u\nend\n\n\"\"\"\n  frechet_el!(u::Vector{Real}, \u03b1::Real, v::Real)\n\nGiven n-variate random vector changes it to such modeled by the two parameters Frechet_cop(n, \u03b1, \u03b2).\nv is the random number form [0,1].\n\"\"\"\nfunction frechet_el!(u, \u03b1, v)\n  if (\u03b1 >= 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}, \u03b1::Real, \u03b2::Real, v::Real)\n\nGiven bivariate random vector changes it to such modeled by the two parameters Frechet_cop(n, \u03b1, \u03b2).\nv is the random number form [0,1]\n\n\"\"\"\nfunction frechet_el2!(u, \u03b1, \u03b2, v)\n  if (\u03b1 >= v)\n    u[1] = u[2]\n  elseif (\u03b1 < v <= \u03b1+\u03b2)\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  - \u03bb::Vector{Real} - vector of non-negative parameters \u03bb\u209b, i.e.:\n      \u03bb = [\u03bb\u2081, \u03bb\u2082, ..., \u03bb\u2099, \u03bb\u2081\u2082, \u03bb\u2081\u2083, ..., \u03bb\u2081\u2099, \u03bb\u2082\u2083, ..., \u03bb\u2099\u208b\u2081\u2099, \u03bb\u2081\u2082\u2083, ..., \u03bb\u2081\u2082...\u2099]\n      and n = ceil(Int, log(2, length(\u03bb)-1)).\n\nConstructor\n\n    Marshall_Olkin_cop(\u03bb)\n\nlength(\u03bb) \u2267 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  \u03bb::Vector{T}\n  function(::Type{Marshall_Olkin_cop})(\u03bb::Vector{T}) where T <: Real\n    minimum(\u03bb) >= 0 || throw(AssertionError(\"all parameters must by >= 0 \"))\n    length(\u03bb) >= 3 || throw(AssertionError(\"not supported for length(\u03bb) < 3\"))\n    n = floor(Int, log(2, length(\u03bb)+1))\n    new{T}(n, \u03bb)\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\u00d72 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\u00d72 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  \u03bb = copula.\u03bb\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, \u03bb, s)\n  end\nend\n\n\"\"\"\n  mocopula(u::Matrix{Real}, n::Int, \u03bb::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 \u03bb of non-negative elements \u03bb\u209b, given [0,1]\u1d57\u02e3\u02e1 \u220b u, where\n  l = 2\u207f-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\u00d72 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, \u03bb)\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, \u03bb, s)\n  end\n  U\nend\n\n\"\"\"\n    mocopula_el(u::Vector{Real}, n::Int, \u03bb::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, \u03bb, 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])./(\u03bb[k]) for k in inds])\n    \u039b = sum(\u03bb[inds])\n    U[i] = exp.(-\u039b*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    \u2202legendre(p::T, x) where {T<:Integer}\n\nCalculate derivatives of Legendre polynomials of degree p at location x\n\"\"\"\n\u2202legendre(p::T, x) where {T<:Integer} = last(sf_legendre_Pl_deriv_array(p, x)[2])\n\nfunction \u2202legendre(p::I, x::T) where {I<:Integer,T<:AbstractArray{<:Real,1}}\n    \u0394 = similar(x)\n    for i in eachindex(\u0394)\n        \u0394[i] = \u2202legendre(p, x[i])\n    end\n\n    return \u0394\nend\n\n\n\"\"\"\n    \u2202radau(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 \u2202radau(p::TI, x::TU) where {TI<:Integer,TU<:Union{Real,AbstractArray{<:Real,1}}}\n    \u0394 = \u2202legendre(p, x)\n    \u0394_plus = \u2202legendre(p + 1, x)\n\n    dgl = @. (-1.0)^p * 0.5 * (\u0394 - \u0394_plus)\n    dgr = @. 0.5 * (\u0394 + \u0394_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": "\"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u0438 \u0434\u043b\u044f \u0447\u0438\u0441\u043b\u0435\u043d\u043d\u043e\u0433\u043e \u0434\u0438\u0444\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0441 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435\u043c \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0445 \u0440\u0430\u0437\u043d\u043e\u0441\u0442\u0435\u0439\"\"\"\nmodule NumDiff\n\"\"\"\n\u041d\u0430\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u0435 \u0447\u0430\u0441\u0442\u043d\u043e\u0439 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u043e\u0439 \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u043f\u043e\u0440\u044f\u0434\u043a\u0430\n\u043e\u0442 \u0432\u0435\u043a\u0442\u043e\u0440\u043e\u0437\u043d\u0430\u0447\u043d\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043c\u043d\u043e\u0433\u0438\u0445 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445\n\n``derivative(func, [t,] x, k; p, h, order) -> df``\n\n\u0414\u043b\u044f \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u044b\u0445 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u043c\u0435\u0442\u043e\u0434 \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0445 \u0440\u0430\u0437\u043d\u043e\u0441\u0442\u0435\u0439.\n\n# \u0410\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b\n\n* `func::Function`: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0432 \u0432\u0438\u0434\u0435 func(t, x) \u0438\u043b\u0438 func(x).\n* `t::Float64`: \u043e\u0431\u0446\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u044b\u0439 \u0441\u043a\u0430\u043b\u044f\u0440\u043d\u044b\u0439 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 (\u0432\u0440\u0435\u043c\u044f).\n* `x::Vector{Float64}`: \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u044b\u0439 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 `x`.\n* `k::Int`: \u043d\u043e\u043c\u0435\u0440 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439, \u043f\u043e \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0432\u0437\u044f\u0442\u044c \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u0443\u044e.\n* `h::Float64`: \u0448\u0430\u0433 \u043f\u0440\u0438\u0440\u0430\u0449\u0435\u043d\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c.\n* `order::Int`: \u043f\u043e\u0440\u044f\u0434\u043e\u043a \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 {2, 4, 6, 8}.\n\n# \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\n\n`df::Vector{Float64}`: \u0432\u0435\u043a\u0442\u043e\u0440 \u0447\u0430\u0441\u0442\u043d\u044b\u0445 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u044b\u0445.\n\"\"\"\nfunction derivative(func::Function, t::Float64, x::Vector{Float64}; k=1, h=0.1, order=4)\n  # \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0442\u0441\u044f \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0435 \u043a\u043e\u043d\u0435\u0447\u043d\u044b\u0435 \u0440\u0430\u0437\u043d\u043e\u0441\u0442\u0438 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u044b \u044d\u0442\u0438\u0445 \u0440\u0430\u0437\u043d\u043e\u0441\u0442\u0435\u0439 \u0437\u0430\u0434\u0430\u044e\u0442\u0441\u044f \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u043c\n  # \u0417\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043c\u0430\u0441\u0441\u0438\u0432 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u043e\u0432\n  a = [[-0.5, 0.0, 0.5], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 2\n       [1.0/12.0, -2.0/3.0, 0.0, 2.0/3.0, -1.0/12.0], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 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], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 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]] # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 8\n\n  # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u043f\u043e \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c\u043e\u043c\u0443 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044e,\n  # \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043b\u0438 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u043e\u0439 \u0438\u043b\u0438 \u0441\u043a\u0430\u043b\u044f\u0440\u043d\u043e\u0439\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# \u0427\u0430\u0441\u0442\u043d\u044b\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u044b\u0435 \u043e\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u0431\u0435\u0437 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430 t\nfunction derivative(func::Function, x::Vector{Float64}; k=1, h=0.1, order=4)\n  # \u0417\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043c\u0430\u0441\u0441\u0438\u0432 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u043e\u0432\n  a = [[-0.5, 0.0, 0.5], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 2\n       [1.0/12.0, -2.0/3.0, 0.0, 2.0/3.0, -1.0/12.0], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 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], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 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]] # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 8\n\n  # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u043f\u043e \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c\u043e\u043c\u0443 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044e,\n  # \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043b\u0438 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u043e\u0439 \u0438\u043b\u0438 \u0441\u043a\u0430\u043b\u044f\u0440\u043d\u043e\u0439\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# \u0427\u0430\u0441\u0442\u043d\u044b\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u044b\u0435 \u043e\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043e\u0434\u043d\u043e\u0433\u043e \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u0430 \u0431\u0435\u0437 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430 t\nfunction derivative(func::Function, x::Float64; h=0.1, order=4)\n  # \u0417\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043c\u0430\u0441\u0441\u0438\u0432 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u043e\u0432\n  a = [[-0.5, 0.0, 0.5], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 2\n       [1.0/12.0, -2.0/3.0, 0.0, 2.0/3.0, -1.0/12.0], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 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], # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 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]] # \u041f\u043e\u0440\u044f\u0434\u043a\u0430 8\n\n  # \u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u043f\u043e \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c\u043e\u043c\u0443 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044e,\n  # \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043b\u0438 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u043e\u0439 \u0438\u043b\u0438 \u0441\u043a\u0430\u043b\u044f\u0440\u043d\u043e\u0439\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\u041d\u0430\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u042f\u043a\u043e\u0431\u0438 \u043e\u0442 \u0432\u0435\u043a\u0442\u043e\u0440\u043e\u0437\u043d\u0430\u0447\u043d\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043c\u043d\u043e\u0433\u0438\u0445 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445\n\n``jacobian(func, t, x; h=0.1, order=4) -> J``\n\n# \u0410\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b\n\n* `func::Function`: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0432 \u0432\u0438\u0434\u0435 func(t, x, p).\n* `t::Float64`: \u0441\u043a\u0430\u043b\u044f\u0440\u043d\u044b\u0439 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 (\u0432\u0440\u0435\u043c\u044f).\n* `x::Vector{Float64}`: \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u044b\u0439 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 `x`.\n* `p::Tuple`: \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u0444\u0443\u043d\u043a\u0446\u0438\u0438 (\u0434\u0430\u0436\u0435 \u0435\u0441\u043b\u0438 \u0438\u0445 \u043d\u0435\u0442).\n* `h::Float64`: \u0448\u0430\u0433 \u043f\u0440\u0438\u0440\u0430\u0449\u0435\u043d\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c.\n* `order::Int`: \u043f\u043e\u0440\u044f\u0434\u043e\u043a \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 {2, 4, 6, 8}.\n\n# \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\n\n* `J::Matrix{Float64}(n, n)`: \u043c\u0430\u0442\u0440\u0438\u0446\u0430 \u042f\u043a\u043e\u0431\u0438.\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{\u221a{\u03b2(\u03f1) - x)(x - \u03b1(\u03f1))}}{2\u03c0x} 1_{[\u03b1(\u03f1),\u03b2(\u03f1)]}(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    \u03c1::T\n    MarcenkoPastur{T}(\u03c1::T) where {T<:Real} = new{T}(\u03c1)\nend\n\nfunction MarcenkoPastur(\u03c1::T, check_args=true) where {T <: Real}\n    check_args && @check_args(MarcenkoPastur, \u03c1 > zero(\u03c1))\n    return MarcenkoPastur{T}(\u03c1)\nend\n\nMarcenkoPastur(\u03c1::Integer) = MarcenkoPastur(float(\u03c1))\n\n@distr_support MarcenkoPastur (1-\u221ad.\u03c1)^2 (1+\u221ad.\u03c1)^2\n\n#### Conversions\nfunction convert(::Type{MarcenkoPastur{T}}, \u03c1::Real) where T<:Real\n    MarcenkoPastur(T(\u03c1))\nend\nfunction convert(::Type{MarcenkoPastur{T}},d::MarcenkoPastur{S}) where {T <: Real, S<: Real}\n    MarcenkoPastur(T(d.\u03c1),check_args=false)\nend\n\n\u03b1(\u03c1) = (1-\u221a\u03c1)^2\n\u03b2(\u03c1) = (1+\u221a\u03c1)^2\n\n### Parameters\nleftbound(d::MarcenkoPastur) = \u03b1(d.\u03c1)\nrightbound(d::MarcenkoPastur) = \u03b2(d.\u03c1)\nparams(d::MarcenkoPastur) = (d.\u03c1)\n\n### Statistics\nmean(d::MarcenkoPastur) = d.\u03c1\nmode(d::MarcenkoPastur) = 2*\u03b1(d.\u03c1)*\u03b2(d.\u03c1)/(\u03b1(d.\u03c1)+\u03b2(d.\u03c1))\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 \u03c1 < 1\n        return pdf(d, d.\u03c1*x)\n    \u221a((\u03b2(d.\u03c1)-x)*(x-\u03b1(d.\u03c1)))/(2\u03c0*x)\nend\n\nfunction logpdf(d::MarcenkoPastur, x::Real)\n    0.5*(log(\u03b2(d.\u03c1)-x)+log(x-\u03b1(d.\u03c1))) - log(2\u03c0*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-\u03b1) 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-\u03b1) 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    \u03c9 = absdev[m]\n    if \u03c9 <= 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        \u03c8 = absdev[i]/\u03c9\n        if abs(\u03c8) >= 1.0\n            z += 1.0\n        else\n            z += \u03c8^2\n            counter += 1\n        end\n    end\n    n*(\u03c9^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-\u03b1) 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\u2264n (no more successes than trials)\")\n    elseif s < 0\n        error(\"binomci requires s\u22650\")\n    elseif n <= 1\n        error(\"binomci requires n\u22652 (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-\u03b1) 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\u2264n (no more successes than trials)\")\n    elseif s < 0\n        error(\"acbinomci requires s\u22650\")\n    elseif n <= 1\n        error(\"acbinomci requires n\u22652 (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-\u03b1) 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 \u03c8 function for each value in the vector `x`.\n\u03c8(x) = max( min(x,bend), -bend).\"\"\"\nfunction hpsi{S <: Real}(x::AbstractArray{S}, bend::Real=1.28)\n    \u03c8 = Array(x)\n    \u03c8[x .> bend] = bend\n    \u03c8[x .< -bend] = -bend\n    \u03c8\nend\n\n\n\"\"\"`onestep(x, bend=1.28)`\n\nCompute one-step M-estimator of location using Huber's \u03c8.\"\"\"\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-\u03b1) 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-\u03b1) confidence interval for the MOM-estimator of location based on Huber's \u03c8.\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 \u03bc=0, \u03c3=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 \u2264 epsilon \u2264 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-\u03b1) confidence interval for a trimmed mean with a trimming fraction of `tr`.\n\nUse `nboot` bootstrap samples and `alpha` for \u03b1.\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 \u2264 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-\u03b1) 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-\u03b1) 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 Base.Test\nusing Einsum\n\n## Test that vars in Main aren't overwritten by einsum\ni = -1\ny = randn(10)\n@einsum x[i] := y[i] \n@test i == -1\n\n## Test with preallocated array ##\n\nA = zeros(5,6,7);\nX = randn(5,2);\nY = randn(6,2);\nZ = randn(7,2);\n\n@einsum A[i,j,k] = X[i,r]*Y[j,r]*Z[k,r]\n\nfor i = 1:5\n    for j = 1:6\n        for k = 1:7\n            s = 0\n            for r = 1:2\n                s += X[i,r]*Y[j,r]*Z[k,r]\n            end\n            @test A[i,j,k] == s\n        end\n    end\nend\n\n## Test without preallocated array ##\n\n@einsum A2[i,j,k] := X[i,r]*Y[j,r]*Z[k,r]\n@test isapprox(A,A2)\n\n# Interesting test case, can throw an error that\n# local vars are declared twice. Solution was to wrap\n# everything in a let statement.\nif true\n    @einsum A[i,j,k] = X[i,r]*Y[j,r]*Z[k,r]\nelse\n    @einsum A[i,j,k] = X[i,r]*Y[j,r]*Z[k,r]\nend\n\n# At one point this threw an error because the lhs\n# had no indices/arguments\nx = randn(10)\ny = randn(10)\n@einsum k := x[i]*y[i]\n@test isapprox(k,dot(x,y))\n\n# Elementwise multiplication (this should create nested loops with no\n# no summation, due to lack of repeated variables.)\nx = randn(10)\ny = randn(10)\n@einsum k[i] := x[i]*y[i]\n@test isapprox(k,x.*y)\n\n# Transpose a block matrix\nz = Any[ rand(2,2) for i=1:2, j=1:2]\n@einsum t[i,j] := transpose(z[j,i])\n@test isapprox(z[1,1], t[1,1]')\n@test isapprox(z[2,2], t[2,2]')\n@test isapprox(z[1,2], t[2,1]')\n@test isapprox(z[2,1], t[1,2]')\n\n# Example from numpy\nA = reshape(collect(1:25),5,5)\n@einsum B[i] := A[i,i]\n@test all(B .== [1,7,13,19,25])\n", "meta": {"hexsha": "3bf8a755c8274104bf36a6debd1a317dccfa7618", "size": 1530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "StephenVavasis/Einsum.jl", "max_stars_repo_head_hexsha": "ba48b745210b29a172c9d27d0f1c331387bfa4ea", "max_stars_repo_licenses": ["MIT"], "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": "StephenVavasis/Einsum.jl", "max_issues_repo_head_hexsha": "ba48b745210b29a172c9d27d0f1c331387bfa4ea", "max_issues_repo_licenses": ["MIT"], "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": "StephenVavasis/Einsum.jl", "max_forks_repo_head_hexsha": "ba48b745210b29a172c9d27d0f1c331387bfa4ea", "max_forks_repo_licenses": ["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.5492957746, "max_line_length": 69, "alphanum_fraction": 0.5790849673, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.7686725614961125}}
{"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 LinearAlgebra\r\nusing Distributions\r\n\r\nfunction kinetic_matrix(num_sites, t)   # one-body matrix, periodic boundary condition\r\n    K_matrix = zeros(num_sites, num_sites)\r\n    for i =  1 : num_sites\r\n        for j = 1 : num_sites\r\n            if abs(i - j) == 1 || abs(i - j) == num_sites - 1\r\n                K_matrix[i, j] = -t\r\n            end\r\n        end\r\n    end\r\n    if flag_background_subtraction == 1\r\n        K_matrix += Diagonal(background_dist) * U\r\n    end\r\n    return K_matrix\r\nend\r\n\r\nfunction auxiliary_field_matrix()\r\n    \u03d5 = rand(Normal(), num_sites)\r\n    coefficent_vector = \u03d5 * AF_coefficient\r\n    AF_matrix = complex(zeros(num_sites, num_sites))\r\n    for i = 1 : num_sites\r\n        AF_matrix[i, i] = coefficent_vector[i]\r\n    end\r\n    if flag_background_subtraction == 1\r\n        background_exponent = sum(-coefficent_vector .* background_dist)\r\n        background_weight = exp(background_exponent)\r\n        return background_weight * exp(AF_matrix)\r\n    elseif flag_background_subtraction == 0\r\n        return exp(AF_matrix)\r\n    end\r\nend\r\n", "meta": {"hexsha": "58a1a315c0811a819c39671099248f0348c85686", "size": 1065, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BoseHubbard/MatrixGenerator.jl", "max_stars_repo_name": "TongSericus/CanonicalAFQMC", "max_stars_repo_head_hexsha": "f4a4cff0c5a547a36094c4d061a888cc7ac05106", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-21T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-23T15:19:57.000Z", "max_issues_repo_path": "BoseHubbard/MatrixGenerator.jl", "max_issues_repo_name": "TongSericus/CanonicalAFQMC", "max_issues_repo_head_hexsha": "f4a4cff0c5a547a36094c4d061a888cc7ac05106", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BoseHubbard/MatrixGenerator.jl", "max_forks_repo_name": "TongSericus/CanonicalAFQMC", "max_forks_repo_head_hexsha": "f4a4cff0c5a547a36094c4d061a888cc7ac05106", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-23T15:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T15:20:51.000Z", "avg_line_length": 31.3235294118, "max_line_length": 87, "alphanum_fraction": 0.6319248826, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7685868378465083}}
{"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+\u03c0/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": "function varianceSD(x)\n\n    n = length(x)\n\n    (1/(n-1)) * sum((x .- meanSD(x)).^2)\n\nend\n", "meta": {"hexsha": "564d68f7b5cc16628050d31adb1061c4e75ad2b0", "size": 89, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/varianceSD.jl", "max_stars_repo_name": "SvenDuve/StatStuff.jl", "max_stars_repo_head_hexsha": "10654aac0da4bdbde30a57297dea85403fc0783a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/varianceSD.jl", "max_issues_repo_name": "SvenDuve/StatStuff.jl", "max_issues_repo_head_hexsha": "10654aac0da4bdbde30a57297dea85403fc0783a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/varianceSD.jl", "max_forks_repo_name": "SvenDuve/StatStuff.jl", "max_forks_repo_head_hexsha": "10654aac0da4bdbde30a57297dea85403fc0783a", "max_forks_repo_licenses": ["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.125, "max_line_length": 40, "alphanum_fraction": 0.5056179775, "num_tokens": 34, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9658995713428387, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.768525817786458}}
{"text": "function calc_phi_deriv_deriv(x,xi,n,nn,c,vars,var_seq)\r\n    phi_der=zeros(nn,n)\r\n    for i=1:nn\r\n        for j=1:n\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\r\n            # 2 r^4\r\n            # phi_der[i,j] = -12*((xi[i,var_seq]-x[j,var_seq])^2)*(r^2) - 2*(r^3)\r\n        \r\n\r\n            # 1 Gaussian\r\n            phi_der[i,j]=-2*exp(-r/c)/c + ((-2*xi[i,var_seq] + 2*x[j,var_seq])^2)*exp(-r/c)/(c^2)\r\n        \r\n        end\r\n    end\r\n    return phi_der\r\nend\r\n\r\n\r\n# phi[i,j]=exp(-dr^2/c^2)*(-2*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] = (-2*r/c[i,j])*exp(-r^2/c[i,j])\r\n# phi[i,j]=tanh.(r/c[i,j])\r\n# phi_der[i,j] = -(r^2)*(2*(xi[i,var_seq]-x[j,var_seq]))\r\n# phi_der[i,j] = -2*exp(-r/c)/c + ((-2*xi[i,var_seq] + 2*x[j,var_seq])^2)*exp(-r/c)/(c^2)\r\n# phi_der[i,j] = exp(-r/c^2)", "meta": {"hexsha": "28dbf032cead5279e837693e81f8bd1d0468175b", "size": 927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calc_phi_deriv_deriv.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_deriv_deriv.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_deriv_deriv.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": 29.9032258065, "max_line_length": 98, "alphanum_fraction": 0.4228694714, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876885, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7685258154493345}}
{"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^\u221e 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, \u03bc) = 4.0 * \u03bc * x * (1.0 - x)\nx_star = compute_fixed_point(x->T(x, 0.3), 0.4)  # (4\u03bc - 1)/(4\u03bc)\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 \u2208 X, u \u2208 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": "@testset \"Field Element Operations\" begin\n    @testset \"Addition\" begin\n        a = ECC.FieldElement(2, 31)\n        b = ECC.FieldElement(15, 31)\n        @test a+b == ECC.FieldElement(17, 31)\n        a = ECC.FieldElement(17, 31)\n        b = ECC.FieldElement(21, 31)\n        @test a+b == ECC.FieldElement(7, 31)\n    end\n    @testset \"Substraction\" begin\n        a = ECC.FieldElement(29, 31)\n        b = ECC.FieldElement(4, 31)\n        @test a-b == ECC.FieldElement(25, 31)\n        a = ECC.FieldElement(15, 31)\n        b = ECC.FieldElement(30, 31)\n        @test a-b == ECC.FieldElement(16, 31)\n    end\n    @testset \"Multiplication\" begin\n        a = ECC.FieldElement(24, 31)\n        b = ECC.FieldElement(19, 31)\n        @test a*b == ECC.FieldElement(22, 31)\n    end\n    @testset \"Power\" begin\n        a = ECC.FieldElement(17, 31)\n        @test a^3 == ECC.FieldElement(15, 31)\n        a = ECC.FieldElement(5, 31)\n        b = ECC.FieldElement(18, 31)\n        @test a^5 * b == ECC.FieldElement(16, 31)\n    end\n    @testset \"Division\" begin\n        a = ECC.FieldElement(3, 31)\n        b = ECC.FieldElement(24, 31)\n        @test a/b == ECC.FieldElement(4, 31)\n        a = ECC.FieldElement(17, 31)\n        @test a^-3 == ECC.FieldElement(29, 31)\n        a = ECC.FieldElement(4, 31)\n        b = ECC.FieldElement(11, 31)\n        @test a^-4*b == ECC.FieldElement(13, 31)\n    end\nend\n", "meta": {"hexsha": "3262624e1930959b3f9f0650ca68ef2cfbc4b10c", "size": 1370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/primefield_tests.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": "test/primefield_tests.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": "test/primefield_tests.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": 33.4146341463, "max_line_length": 49, "alphanum_fraction": 0.5576642336, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235895, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7684737936448855}}
{"text": "@inline function l2_norm(z::AbstractVector)\n    return sqrt(sum(abs2, z))\nend\n\n@inline function l2_distance(x::AbstractVector, y::AbstractVector)\n    z = x - y\n    return l2_norm(z)\nend\n", "meta": {"hexsha": "849ffe9999d1180dff67bc7064bf76d1a866c817", "size": 186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/norm.jl", "max_stars_repo_name": "bcbi/MultivariateMedians.jl", "max_stars_repo_head_hexsha": "0899291a51287fbd5250fea1bb6c87cb8508eee6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-25T02:19:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-25T02:19:47.000Z", "max_issues_repo_path": "src/norm.jl", "max_issues_repo_name": "bcbi/MultivariateMedians.jl", "max_issues_repo_head_hexsha": "0899291a51287fbd5250fea1bb6c87cb8508eee6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-08-25T04:08:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T00:23:06.000Z", "max_forks_repo_path": "src/norm.jl", "max_forks_repo_name": "bcbi/MultivariateMedians.jl", "max_forks_repo_head_hexsha": "0899291a51287fbd5250fea1bb6c87cb8508eee6", "max_forks_repo_licenses": ["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": 66, "alphanum_fraction": 0.7096774194, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7684592603258027}}
{"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": "using Distributions\nusing Plots\n\npopulation = sort(convert(Array{Int64}, rand(Bernoulli(.7), 100)))\npopulation_over_time = []\nn_iter = 100\ngr()\n\nfunction single_reproduction(population::AbstractArray)\n    n = length(population)\n    p\u2090 = sum(population) / length(population)\n    f\u2090 = Bernoulli(p\u2090)\n    sort(convert(Array{Int64}, rand(f\u2090, n)))\nend\n\nfunction multiple_reproductions(seed_array::AbstractArray, population_over_time::AbstractArray, n_iterations::Int64)\n    seed_array = single_reproduction(seed_array)\n    push!(population_over_time, seed_array)\n    if n_iterations == 1\n        hcat(population_over_time...)\n    else\n        multiple_reproductions(seed_array, population_over_time, n_iterations-1)\n    end\nend\n\nfunction plot_many_samples(n_samples::Int64, n_iterations::Int64, N\u2091::Int64, p\u2090::Float64)\n    p = false\n    for i in 1:n_samples\n        population = sort(convert(Array{Int64}, rand(Bernoulli(p\u2090), N\u2091)))\n        population_at_time = multiple_reproductions(population, [], n_iterations)\n        if p\n            display(plot!(dropdims(sum(population_at_time, dims=1), dims=1), legend=false))\n        else\n            display(plot(dropdims(sum(population_at_time, dims=1), dims=1), xlims=(0, n_iterations), ylims=(0, N\u2091)))\n            p = true\n        end\n    end\nend\n\nplot_many_samples(10, 10000, 10000, .5)\n# j = multiple_reproductions(population, population_over_time, n_iter)\n# plot(dropdims(sum(j, dims=1), dims=1))\n# j = multiple_reproductions(population, [], n_iter)\n# plot!(dropdims(sum(j, dims=1), dims=1))\n# j = multiple_reproductions(population, [], n_iter)\n# plot!(dropdims(sum(j, dims=1), dims=1))", "meta": {"hexsha": "bc767592187195715d58588eb261c90c3cc34da1", "size": 1630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simple_model.jl", "max_stars_repo_name": "biothomme/Geosmin", "max_stars_repo_head_hexsha": "5aca27e2471c54108369cde8e7e6c79b11e548db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simple_model.jl", "max_issues_repo_name": "biothomme/Geosmin", "max_issues_repo_head_hexsha": "5aca27e2471c54108369cde8e7e6c79b11e548db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_model.jl", "max_forks_repo_name": "biothomme/Geosmin", "max_forks_repo_head_hexsha": "5aca27e2471c54108369cde8e7e6c79b11e548db", "max_forks_repo_licenses": ["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.4347826087, "max_line_length": 116, "alphanum_fraction": 0.7030674847, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7684491722446283}}
{"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, \u03a3, V = F.U, F.S, F.V\n    @assert size(U, 2) == length(\u03a3) == size(V, 2) == k\n    return U, \u03a3, 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 \u2264 l \u2264 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, \u03a3, V = svd(B)\n    U = Q*W\n    return U[:,1:k], \u03a3[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": "using GalerkinSparseGrids\nusing Base.Test\nusing Cubature\nusing ODE\n\n#--------------------------------------\n# Testing PDE solvers\n#--------------------------------------\n\n# The wave equation, testing conservation of energy\n\n# In the position basis:\n\nimport GalerkinSparseGrids.energy_func_1D\nimport GalerkinSparseGrids.energy_func\n\nprint(\"Testing wave equation solver 1-D position DG basis... \")\n\nk = 4\nlevel = 4\nf0 = x->sin(2*pi*x[1])\nv0 = x->2*pi*cos(2*pi*x[1])\npos_soln = wave_evolve_1D(k, level, f0, v0, 0, 1; basis=\"pos\", order=\"45\")\nenergy_soln = energy_func_1D(k, level, pos_soln; basis=\"pos\")\nfor i in 1:length(energy_soln[2])\n    @test sqrt(energy_soln[2][i]) \u2248 2*pi atol=1.0e-7\nend\n\nprintln(\"Test Passed.\")\n\n# In the hierarchical basis:\n\nprint(\"Testing wave equation solver 1-D hierarchical DG basis... \")\n\nhier_soln  = wave_evolve_1D(k, level, f0, v0, 0, 1; basis=\"hier\", order=\"45\")\nenergy_soln = energy_func_1D(k, level, hier_soln; basis=\"hier\")\nfor i in 1:length(energy_soln[2])\n    @test sqrt(energy_soln[2][i]) \u2248 2*pi atol=1.0e-7\nend\n\nhier_soln  = wave_evolve(1, k, level, f0, v0, 0, 1; order=\"78\")\nenergy_soln = energy_func(1, k, level, hier_soln)\nfor i in 1:length(energy_soln[2])\n    @test sqrt(energy_soln[2][i]) \u2248 2*pi atol=1.0e-7\nend\n\nprintln(\"Test Passed.\")\n\n# 2D Sparse case:\n\nprint(\"Testing wave equation solver on 2-D sparse DG basis... \")\n\nD = 2\nk_used = 3\nn_used = 5\nf0 = x->sin(2*pi*x[1])*sin(2*pi*x[2])\nv0 = x->0\nsparse_soln = wave_evolve(D, k_used, n_used, f0, v0, 0, 1; order=\"78\", scheme=\"sparse\");\nsenergy = energy_func(D, k_used, n_used, sparse_soln)\n@test senergy[2][1]-senergy[2][end] > 0\n@test abs(senergy[2][1]-senergy[2][end]) < 1.0e-8\nfor i in 1:length(senergy[1])\n    @test sqrt(senergy[2][i]) \u2248 sqrt(2)*pi atol=1.0e-4\nend\n\nsparse_soln = wave_evolve(D, k_used, n_used, f0, v0, 0,1; order=\"45\", scheme=\"sparse\");\nsenergy = energy_func(D, k_used, n_used, sparse_soln)\n@test senergy[2][1] > senergy[2][end]\n@test senergy[2][1] \u2248 senergy[2][end] atol=1.0e-8\nfor i in 1:length(senergy[1])\n    @test sqrt(senergy[2][i]) \u2248 sqrt(2)*pi atol=1.0e-4\nend\n\nprintln(\"Test Passed.\")\n\nprint(\"Testing traveling wave example in 2-D... \")\n\nm = [1, 2]\ntruesoln = x -> cos(2*pi*(vecdot(m,x) - sqrt(vecdot(m,m))*0.54))\n\nD = length(m)\nk_used = 3\nn_used = 6\n\nsoln = traveling_wave_solver(k_used, n_used, m, 0, 0.54; order=\"45\")\ndict = V2D(D, k_used, n_used, soln[2][end]; scheme=\"sparse\")\n@test mcerr(x->reconstruct_DG(dict, [x...]), truesoln, D) < 0.05\n\nsoln = traveling_wave_solver(k_used, n_used, m, 0, 0.54; order=\"78\")\ndict = V2D(D, k_used, n_used, soln[2][end]; scheme=\"sparse\")\n@test mcerr(x->reconstruct_DG(dict, [x...]), truesoln, D) < 0.05\n\nprintln(\"Test passed.\")\n", "meta": {"hexsha": "6411ba477f3bb8db088ae7227d10e8e3aa7f51fc", "size": 2693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/solvers.jl", "max_stars_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_stars_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_stars_repo_licenses": ["MIT"], "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/solvers.jl", "max_issues_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_issues_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_issues_repo_licenses": ["MIT"], "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/solvers.jl", "max_forks_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_forks_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_forks_repo_licenses": ["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.6489361702, "max_line_length": 88, "alphanum_fraction": 0.6572595618, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7684491583846522}}
{"text": "# Pentagonal numbers are generated by the formula, Pn=n(3n\u22121)/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 \u2212 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 \u2212 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 Base.binomial{T<:FloatingPoint}(n::T, k::T)\n    exp(lfact(n) - lfact(n - k) - lfact(k))\nend\n\nfunction Base.factorial{T<:FloatingPoint}(n::T, k::T)\n    exp(lfact(n) - lfact(k))\nend\n\n\u229e{T<:Real}(n::T, k::T) = binomial(n, k)\n\u22a0{T<:Real}(n::T, k::T) = factorial(n, n-k)\n", "meta": {"hexsha": "7ef61366b158a4fa9faf251d52d3603a92939a59", "size": 273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/combinations-and-permutations-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/combinations-and-permutations-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/combinations-and-permutations-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": 24.8181818182, "max_line_length": 53, "alphanum_fraction": 0.5860805861, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9688561730622296, "lm_q2_score": 0.7931059560743423, "lm_q1q2_score": 0.7684056014350481}}
{"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\u2013Warshall_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\u0394m = 200\nprintln(\"\u0394m = \", \u0394m)\nA(\u0394m) = 1 + 0.24log10(\u0394m) * exp(-(4 / log10(\u0394m))^4)\na(\u0394m) = 0.44log10(\u0394m) - 0.88\nC(\u0394m) = 0.019 + 0.107log10(\u0394m) + 0.19 * exp(-(4 / log10(\u0394m))^4)\nB, b, c = 0.183, 1.5, 2.4\n\u03b4c = 1.686\nb\u03bd(ln\u03bd) =\n   1 - A(\u0394m) * exp(0.5 * a(\u0394m) * ln\u03bd) / (exp(0.5 * a(\u0394m) * ln\u03bd) + \u03b4c^a(\u0394m)) +\n   B * exp(0.5 * b * ln\u03bd) +\n   C(\u0394m) * exp(0.5 * c * ln\u03bd)\nf0(x) = tinker10MF(x, 0, \u0394m)\nnorm1, err = hquadrature(f0, -50, 5)\nprintln(\"Normalisation(MF) = \", norm1)\nf1(x) = tinker10MF(x, 0, \u0394m) * b\u03bd(x)\nnorm2, err = hquadrature(f1, -50, 5)\nprintln(\"Normalisation(Bias) = \", norm2)\n# %% Plot b(\u03bd)\nx = -2:0.05:2\n\u0394m = 200\nplot(\n   log10.(exp.(x)),\n   log10.(b\u03bd.(x)),\n   xlim = [-0.5, 0.6],\n   ylim = [-0.5, 1.2],\n   xlabel = \"log10(\u03bd)\",\n   ylabel = \"log10(b)\",\n   ls = :dash,\n)\n\u0394m = 1600\nplot!(log10.(exp.(x)), log10.(b\u03bd.(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  \u03b1 ~ Cauchy(0,10)\n  \u03b2 ~ Cauchy(0,10)\n  for i = 1:length(y)\n    y[i] ~ NegativeBinomial(\u03b1, \u03b2)  # \u03b1 > 0, 0 < \u03b2 < 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 / \u03c0)\nend\n\n\nfunction ylmCosSinPolynomial(m::Integer, x::Variable, y::Variable)\n    sum = 0.0 * (x + y)\n    for j = 0:m\u00f72\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)\u00f72\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) \u2208 zip(v1, v2) ], velocity(object, xs) for object \u2208 objects)\n    pots = foldl((v1, v2) -> v1 + v2, potential(object, xs) for object \u2208 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\u03c0) * (x - y(src)) / ((x - y(src))^2 + (y - x(src))^2), str / (2\u03c0) * (y - x(src)) / ((x - y(src))^2 + (y - x(src))^2))\nsource_potential(src :: Singularity2D, x, y) = strength(src) / (4\u03c0) * log((x - y(src))^2 + (y - x(src))^2)\nsource_stream(src :: Singularity2D, x, y) = strength(src) / (2\u03c0) * atan(y - x(src), x - y(src))\n\ndoublet_velocity(dub :: Singularity2D, x, y) = SVector(strength(dub) / (2\u03c0) * ((x - y(dub))^2 - (y - x(dub))^2) / ((x - y(dub))^2 + (y - x(dub))^2)^2, - strength(dub) / (2\u03c0) * 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\u03c0) * (y - x(dub)) / ((x - y(dub))^2 + (y - x(dub))^2)\ndoublet_stream(dub :: Singularity2D, x, y) = -strength(dub) / (2\u03c0) * (y - x(dub)) / ((x - y(dub))^2 + (y - x(dub))^2)\n\nvortex_velocity(vor :: Singularity2D, x, y) = SVector(-strength(vor) / (2\u03c0) * (y - x(vor)) / ((x - y(vor))^2 + (y - x(vor))^2), str / (2\u03c0) * (x - y(vor)) / ((x - y(vor))^2 + (y - x(vor))^2))\nvortex_potential(vor :: Singularity2D, x, y) = strength(vor) / (2\u03c0) * atan(y - x(vor), x - y(vor))\nvortex_stream(vor :: Singularity2D, x, y) = -strength(vor) / (4\u03c0) * 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, \u03b1_deg, \u03b2_deg, \u03a9) where T <: Real = new(V, deg2rad(\u03b1_deg), deg2rad(\u03b2_deg), \u03a9)\nend\n\n\"\"\"\n    Freestream(V, \u03b1, \u03b2, \u03a9)\n    \nA Freestream flow in spherical polar coordinates with magnitude ``V``, angle-of-attack ``\u03b1``, side-slip angle ``\u03b2``, and a quasi-steady rotation vector ``\\\\Omega``.\n\"\"\"\nFreestream(V, \u03b1_deg, \u03b2_deg, \u03a9 :: AbstractVector{T}) where T <: Real = Freestream{T}(V, \u03b1_deg, \u03b2_deg, \u03a9)\n\n# TODO: ForwardDiff testing\n# Freestream(V :: Real, \u03b1_deg, \u03b2_deg, \u03a9 :: AbstractVector{<: Real}) = Freestream{Float64}(V, \u03b1_deg, \u03b2_deg, \u03a9)\n\n\"\"\"\n    Freestream(U, \u03a9)\n\nA Freestream flow in Cartesian coordinates with vector ``U`` and quasi-steady rotation vector ``\\\\Omega``.\n\"\"\"\nFreestream(U :: AbstractVector{T}, \u03a9 :: AbstractVector{T}) where T <: Real = \n    let (V, \u03b1, \u03b2) = cartesian_to_freestream(U); Freestream{T}(V, \u03b1, \u03b2, \u03a9) end\n\n\"\"\"\n    freestream_to_cartesian(r, \u03b8, \u03c6)\n\nConvert freestream flow (spherical polar) coordinates to Cartesian coordinates.\n\"\"\"\nfreestream_to_cartesian(r, \u03b8, \u03c6) = r .* SVector(cos(\u03b8) * cos(\u03c6), -sin(\u03c6), sin(\u03b8) * cos(\u03c6))\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], \u221a(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       \u2207\u00b2(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       \u03b1 = 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) + \u03b1*\u2207\u00b2(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 + \u03b1*\u2207\u00b2(v(x,y,t))]\n\n       domains = [x \u2208 Interval(x_min, x_max),\n                  y \u2208 Interval(y_min, y_max),\n                  t \u2208 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 \u2248 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 \u2248 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 Test, PolynomialBases\n\nufunc(x) = sinpi(x)^2\n\nfunction tolerance(p, T=Float64)\n    if p <= 2\n        1.\n    elseif p <= 4\n        0.78\n    elseif p <= 6\n        0.02\n    elseif p <= 8\n        1.e-4\n    elseif p <= 10\n        if T==Float32\n            4.e-7\n        else\n            1.5e-7\n        end\n    elseif p <= 12\n        if T==Float32\n            3.e-7\n        else\n            9.e-11\n        end\n    elseif p <= 14\n        if T==Float32\n            4.e-7\n        else\n            3.e-14\n        end\n    else\n        if T==Float32\n            5.e-7\n        else\n            5.e-16\n        end\n    end\nend\n\nfor basis_type in subtypes(PolynomialBases.NodalBasis{PolynomialBases.Line})\n    basis_type <: Union{ClosedNewtonCotes,ClenshawCurtis} && continue\n    for p in 3:15, T in (Float32, Float64)\n        basis = basis_type(p, T)\n        u = ufunc.(basis.nodes)\n        @test abs(integrate(u, basis) - 1) < tolerance(p, T)\n        @test abs(integrate(u, basis.weights) - 1) < tolerance(p, T)\n    end\nend\n", "meta": {"hexsha": "0d03183bd5f4ed8582f49f43d8065c8608f9161a", "size": 1016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/integration_test.jl", "max_stars_repo_name": "ranocha/PolynomialBases.jl", "max_stars_repo_head_hexsha": "845531c8eee63f2c1608badd980872796fabbfc9", "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": "test/integration_test.jl", "max_issues_repo_name": "ranocha/PolynomialBases.jl", "max_issues_repo_head_hexsha": "845531c8eee63f2c1608badd980872796fabbfc9", "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": "test/integration_test.jl", "max_forks_repo_name": "ranocha/PolynomialBases.jl", "max_forks_repo_head_hexsha": "845531c8eee63f2c1608badd980872796fabbfc9", "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": 20.32, "max_line_length": 76, "alphanum_fraction": 0.4872047244, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7683793529016484}}
{"text": "using EconPDEs\n\nBase.@kwdef  struct CampbellCochraneModel\n    # consumption process parameters\n    \u03bc::Float64 = 0.0189\n    \u03c3::Float64 = 0.015\n\n    # utility\n    \u03b3::Float64 = 2.0\n    \u03c1::Float64 = 0.116\n\n    # habit\n    \u03bas::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# \u03c1 = 12 * (1 - 0.89^(1/12))\n# \u03bas = 12 * (1 - 0.87^(1/12))\n\nfunction initialize_stategrid(m::CampbellCochraneModel; smin = -300.0, n = 1000)\n    \u03bc = m.\u03bc ; \u03c3 = m.\u03c3 ; \u03b3 = m.\u03b3 ; \u03c1 = m.\u03c1 ; \u03bas = m.\u03bas ; b = m.b\n    Sbar = \u03c3 * sqrt(\u03b3 / (\u03bas - b / \u03b3))\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    \u03bc = m.\u03bc ; \u03c3 = m.\u03c3 ; \u03b3 = m.\u03b3 ; \u03c1 = m.\u03c1 ; \u03bas = m.\u03bas ; 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 = \u03c3 * sqrt(\u03b3 / (\u03bas - b / \u03b3))\n    sbar = log(Sbar)\n    \u03bb = 1 / Sbar * sqrt(1 - 2 * (s - sbar)) - 1\n    \u03bcs = - \u03bas * (s - sbar)\n    \u03c3s = \u03bb * \u03c3\n    \u03c3p = ps / p * \u03c3s\n    \u03bcp = ps / p * \u03bcs + 0.5 * pss / p * \u03c3s^2\n\n    # market price of risk \u03ba\n    \u03ba = \u03b3 * (\u03c3 + \u03c3s)\n\n    # risk free rate  r\n    r = \u03c1 + \u03b3 * \u03bc - (\u03b3 * \u03bas - b) / 2 + b * (sbar - s)\n\n    # PDE\n    pt = p * (1 / p + \u03bc + \u03bcp + \u03c3p * \u03c3 - r - \u03ba * (\u03c3 + \u03c3p))\n    return (pt,), (\u03bcs, ), (p = p, \u03ba = \u03ba, \u03bb = \u03bb, r = r, \u03c3p = \u03c3p, \u03bcs = \u03bcs, \u03c3s = \u03c3s)\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(\u03bc = 0.022, \u03c3 = 0.0086, \u03b3 = 2.0, \u03c1 = 0.073, \u03bas = 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": "function fib20()\n#\n#  test polynomial suggested by Goedecker\n#\n    n = 20;\n    p = fib(n)\n    z = [-.9473885474109854;\n         -.9029230998844866-.2884421994216345*im; -.9029230998844866+.2884421994216345*im;\n         -.7734751441751908-.5504669225440185*im; -.7734751441751908+.5504669225440185*im;\n         -.5705411148090332-.7619498890625472*im; -.5705411148090332+.7619498890625472*im;\n         -.3121525651549263-.9031354642584495*im; -.3121525651549263+.9031354642584495*im;\n         -.02129876087300105-.9602891496489760*im; -.02129876087300105+.9602891496489760*im;\n         .2760438985065760-.9267417870492216*im; .2760438985065760+.9267417870492216*im;\n         .5529956567245064-.8031600819414702*im; .5529956567245064+.8031600819414702*im;\n         .7834063973613306-.5969423289081712*im; .7834063973613306+.5969423289081712*im;\n         .9416394828514235-.3213776783384489*im; .9416394828514235+.3213776783384489*im;\n         1.999999046316589];\n    z = [z ones(n)]\n    p, PolyZeros(z)\nend\n", "meta": {"hexsha": "fc7015c6a05f64bc47cf05186761f3a2189995e9", "size": 1005, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsuit/fib20.m.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": "test/testsuit/fib20.m.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": "test/testsuit/fib20.m.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": 47.8571428571, "max_line_length": 92, "alphanum_fraction": 0.7194029851, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7683793377654571}}
{"text": "#######################\n# Spin Operators Test #\n#######################\n\n# the Pauli spin matrices sigmax, sigmay and sigmaz obey the commutation\n# relations $ [\\sigma_a, \\sigma_b]  = 2i\\epsion_{abc} \\sigma_c $, where\n# $\\epsion_{abc}$ is the Levi-Civita symbol.\n# Hence,\n@assert commute(sigmax, sigmay) == 2*im*sigmaz\n@assert commute(sigmay, sigmaz) == 2*im*sigmax\n@assert commute(sigmaz, sigmax) == 2*im*sigmay\n\n@assert coeffs(commute(sigmax, sigmax)) == spzeros(2,2)\n\n# Moreover, the sigmas fulfill anticommutation relations\n# ${\\sigma_a, \\sigma_b} = 2\\delta_{a,b} I$ with $\\delta_{a,b}$\n# being the Kronecker delta and $I$ the 2x2 identity matrix\n# Thus,\n@assert anticommute(sigmax, sigmax) == 2 * QuArray(speye(2))\n\n@assert spinjp(3.5) == spinjx(3.5) + (im * spinjy(3.5))\n@assert spinjm(3.5) == spinjx(3.5) - (im * spinjy(3.5))\n\n####################################################\n# Position, Displacement & Momentum Operators Test #\n####################################################\n\n# position and momentum operators obey the commutation relation\n# $[x,p] = i I$, where $I$ is the identity operator\n# However, here we just use the fact that for n=2, x~sigmax and\n# p ~ sigmay\np = positionop(2)\nm = momentumop(2)\n@assert coeffs(commute(sigmax, p)) == spzeros(2,2)\n@assert coeffs(commute(sigmay, m)) == spzeros(2,2)\n\n# test coefficients computed by coherentstatevec vs \n# Fock basis coefficients\ncoherentstate_inf = QuBase.coherentstatevec_inf(20,1.0)\ncoherentstate = coherentstatevec(20, 1.0)\n@test_approx_eq_eps coherentstate_inf[1] coherentstate[1] 1e-8\n\n\n############################\n# Squeezing Operators Test #\n############################\n\n@assert squeezingop(2,1.0)== QuArray(eye(2))\n@test_approx_eq coeffs(squeezingop(lowerop(2), QuArray(eye(2)), -2.0)) coeffs(displaceop(2,1.0))\n", "meta": {"hexsha": "5df37e9ea5dbd5572ff13f8f1118af1d3c7c8bf1", "size": 1798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/operatortest.jl", "max_stars_repo_name": "amitjamadagni/QuBase.jl", "max_stars_repo_head_hexsha": "f890e8269e22e844c0ea0a3a6b1a16c6077b1ad8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:05:12.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-09T23:45:36.000Z", "max_issues_repo_path": "test/operatortest.jl", "max_issues_repo_name": "amitjamadagni/QuBase.jl", "max_issues_repo_head_hexsha": "f890e8269e22e844c0ea0a3a6b1a16c6077b1ad8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2015-01-03T20:43:42.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-04T11:51:00.000Z", "max_forks_repo_path": "test/operatortest.jl", "max_forks_repo_name": "amitjamadagni/QuBase.jl", "max_forks_repo_head_hexsha": "f890e8269e22e844c0ea0a3a6b1a16c6077b1ad8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-02-03T21:41:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-18T21:32:23.000Z", "avg_line_length": 35.96, "max_line_length": 96, "alphanum_fraction": 0.6323692992, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7683793365180053}}
{"text": "function genball(R)\n    sphere_side = 2R + 1\n    sphere = zeros(Bool, (sphere_side, sphere_side, sphere_side))\n\n    for i in -R:R\n        for j in -R:R\n            for k in -R:R\n                dist = i^2 + j^2 + k^2\n                if dist < R^2\n                    sphere[k+R+1, j+R+1, i+R+1] = 1\n                end\n            end\n        end\n    end\n\n    return sphere\nend\n\nfunction gendisk(R)\n    sphere  = zeros(Bool, (2R + 1, 2R + 1))\n\n    for i in -R:R\n        for j in -R:R\n            dist = i^2 + j^2\n            if dist < R^2\n                sphere[j+R+1, i+R+1] = 1\n            end\n        end\n    end\n\n    return sphere\nend\n\nfunction gentorus(side, r, R)\n    a = zeros(Bool, (side, side, side))\n    for i in 1:side\n        for j in 1:side\n            for k in 1:side\n                x = i - side\u00f72\n                y = j - side\u00f72\n                z = k - side\u00f72\n                if (x^2 + y^2 + z^2 + R^2 - r^2)^2 < 4R^2*(x^2 + y^2)\n                    a[k,j,i] = 1\n                end\n            end\n        end\n    end\n    \n    return a\nend\n\n@test euler_characteristic(genball(100)) == 1\n@test euler_characteristic(gendisk(100)) == 1\n@test euler_characteristic(ones(Bool, (100, 100, 100))) == 1\n@test euler_characteristic(hcat(ones(Bool, (100, 100, 100)),\n                                zeros(Bool, (100, 100, 100)),\n                                ones(Bool, (100, 100, 100)))) == 2\nlet a = ones(Bool, (100, 100));\n    a[50:60, 50:60] .= 0;\n    @test euler_characteristic(a) == 0\nend\n\nlet a = gentorus(200, 10, 90);\n    b = cat(a[:,:,begin:end-5], a[:,:,begin+5:end]; dims = [3])\n    @test euler_characteristic(b) == -1\nend\n", "meta": {"hexsha": "09a572d49e8137a125bae7062fc37e32ebb93b7a", "size": 1641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/calculation.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": "test/calculation.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": "test/calculation.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": 24.4925373134, "max_line_length": 69, "alphanum_fraction": 0.4515539305, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7683621066196575}}
{"text": "abstract type AbstractAcquisition end\n\nsetparams!(a, model) = nothing\nfunction acquisitionfunction(a, model)\n    x -> begin\n        \u03bc, \u03c3\u00b2 = mean_var(model, x)\n        a.(\u03bc, \u03c3\u00b2)\n    end\nend\n\n\"\"\"\nThe probability of improvement measures the probability that a point `x` leads\nto an improvement upon an incumbent target `\u03c4`. For Gaussian distributions it is\ngiven by\n\n    \u03a6[(\u03bc(x) - \u03c4)/\u03c3(x)]\n\nwhere `\u03a6` is the standard normal cumulative distribution function and `\u03bc(x)`, `\u03c3(x)`\nare mean and standard deviation of the distribution at point `x`.\n\"\"\"\nmutable struct ProbabilityOfImprovement <: AbstractAcquisition\n    \u03c4::Float64\nend\n@inline function (a::ProbabilityOfImprovement)(\u03bc, \u03c3\u00b2)\n    \u03c3\u00b2 == 0 && return float(\u03bc > a.\u03c4)\n    normal_cdf(\u03bc - a.\u03c4, \u03c3\u00b2)\nend\nProbabilityOfImprovement(; \u03c4 = -Inf) = ProbabilityOfImprovement(\u03c4)\n\n\"\"\"\nThe expected improvement measures the expected improvement `x - \u03c4` of a point `x`\nupon an incumbent target `\u03c4`. For Gaussian distributions it is given by\n\n    (\u03bc(x) - \u03c4) * \u03d5[(\u03bc(x) - \u03c4)/\u03c3(x)] + \u03c3(x) * \u03a6[(\u03bc(x) - \u03c4)/\u03c3(x)]\n\nwhere `\u03d5` is the standard normal distribution function and `\u03a6` is the standard\nnormal cumulative function, and `\u03bc(x)`, `\u03c3(x)` are mean and standard deviation\nof the distribution at point `x`.\n\"\"\"\nmutable struct ExpectedImprovement <: AbstractAcquisition\n    \u03c4::Float64\nend\nExpectedImprovement(; \u03c4 = -Inf) = ExpectedImprovement(\u03c4)\nfunction setparams!(a::Union{ExpectedImprovement,ProbabilityOfImprovement}, model)\n    a.\u03c4 = max(maxy(model), a.\u03c4)\nend\n@inline function (a::ExpectedImprovement)(\u03bc, \u03c3\u00b2)\n    \u03c3\u00b2 == 0 && return \u03bc > a.\u03c4 ? \u03bc - a.\u03c4 : 0.\n    abs(\u03bc - a.\u03c4) * normal_cdf(\u03bc - a.\u03c4, \u03c3\u00b2) + \u221a\u03c3\u00b2 * normal_pdf(\u03bc - a.\u03c4, \u03c3\u00b2)\nend\n\nabstract type BetaScaling end\n\"\"\"\nScales `\u03b2t` of `UpperConfidenceBound` as\n\n    \u03b2t = \u221a(2 * log(t^(D/2 + 2) * \u03c0^2/(3\u03b4)))\n\nwhere `t` is the number of observations, `D` is the dimensionality of the input\ndata points and \u03b4 is a small constant (default \u03b4 = 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    \u03b4::Float64\nend\n\"\"\"\nApplies no scaling to `\u03b2t` of `UpperConfidenceBound`.\n\"\"\"\nstruct NoBetaScaling <: BetaScaling end\n\"\"\"\nFor Gaussian distributions the upper confidence bound at `x` is given by\n    \u03bc(x) + \u03b2t * \u03c3(x)\n\nwhere `\u03b2t` 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    \u03b2t::Float64\nend\n\"\"\"\n    UpperConfidenceBound(; scaling = BrochuBetaScaling(.1), \u03b2t = 1)\n\"\"\"\nUpperConfidenceBound(; scaling = BrochuBetaScaling(.1), \u03b2t = 1.) = UpperConfidenceBound(scaling, \u03b2t)\nfunction setparams!(a::UpperConfidenceBound{BrochuBetaScaling}, model)\n    D, nobs = dims(model)\n    nobs == 0 && (nobs = 1)\n    a.\u03b2t = sqrt(2*log(nobs^(D/2 + 2)*\u03c0^2/(3*a.scaling.\u03b4)))\nend\n(a::UpperConfidenceBound)(\u03bc, \u03c3\u00b2) = \u03bc + a.\u03b2t * \u221a\u03c3\u00b2\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 \u03b3\u0302 gives a lower bound for the information on f from the queries\n{x}. For a Gaussian this is\n    \u03b3\u0302 = \u2211\u03c3\u00b2(x)\nand the mutual information at x is\n    \u03bc(x) + \u221a(\u03b1)*(\u221a(\u03c3\u00b2(x)+\u03b3\u0302) - \u221a(\u03b3\u0302))\n\nwhere `\u03bc(x)`, `\u03c3(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\u03b1::Float64\n    \u03b3\u0302::Float64\nend\nMutualInformation(; \u03b1 = 1.0, \u03b3\u0302 = 0.0) = MutualInformation(sqrt(\u03b1), \u03b3\u0302)\nfunction setparams!(a::MutualInformation, model)\n    D, nobs = dims(model)\n    if iszero(nobs)\n        a.\u03b3\u0302 = 0.0\n    else\n        last_x = @view model.x[:, end]\n        \u03bc, \u03c32 = mean_var(model, last_x)\n        a.\u03b3\u0302 += \u03c32\n    end\nend\n(a::MutualInformation)(\u03bc, \u03c3\u00b2) = \u03bc + a.sqrt\u03b1 * (sqrt(\u03c3\u00b2 + a.\u03b3\u0302) - sqrt(a.\u03b3\u0302))\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": "@testset verbose=true \"map2salm\" begin\n    # NOTE: Float16 irfft returns Float32, which leads to type conflicts, so we just don't support\n    # map2salm on Float16\n\n    function sYlm(s::Int, ell::Int, m::Int, theta::T, phi::T) where {T<:Real}\n        # Eqs. (II.7) and (II.8) of https://arxiv.org/abs/0709.0093v3\n        # Note their weird definition w.r.t. `-s`\n        k_min = max(0, m + s)\n        k_max = min(ell + m, ell + s)\n        sin_half_theta, cos_half_theta = sincos(theta / 2)\n        return (-1)^(-s) * sqrt((2 * ell + 1) / (4 * T(\u03c0))) * \n            T(sum(\n                (-1) ^ (k)\n                * sqrt(factorial(big(ell + m)) * factorial(big(ell - m)) * factorial(big(ell - s)) * factorial(big(ell + s)))\n                * (cos_half_theta ^ (2 * ell + m + s - 2 * k))\n                * (sin_half_theta ^ (2 * k - s - m))\n                / (factorial(big(ell + m - k)) * factorial(big(ell + s - k)) * factorial(big(k)) * factorial(big(k - s - m)))\n                for k in k_min:k_max\n            )) *\n            exp(im * m * phi)\n    end\n\n    # Eqs. (II.9) through (II.13) of https://arxiv.org/abs/0709.0093v3\n    m2Y22(iota::T, phi) where T = sqrt(5 / (64 * T(\u03c0))) * (1 + cos(iota)) ^ 2 * exp(im * 2phi)\n    m2Y21(iota::T, phi) where T = sqrt(5 / (16 * T(\u03c0))) * sin(iota) * (1 + cos(iota)) * exp(im * phi)\n    m2Y20(iota::T, phi) where T = sqrt(15 / (32 * T(\u03c0))) * sin(iota) ^ 2\n    m2Y2m1(iota::T, phi) where T = sqrt(5 / (16 * T(\u03c0))) * sin(iota) * (1 - cos(iota)) * exp(im * -1phi)\n    m2Y2m2(iota::T, phi) where T = sqrt(5 / (64 * T(\u03c0))) * (1 - cos(iota)) ^ 2 * exp(im * -2phi)\n\n    @testset \"Input expressions $T\" for T in [BigFloat, Float64, Float32]\n        # These are just internal consistency tests of the sYlm function\n        # above, against the explicit expressions `mY2.`\n        s = -2\n        \u2113 = 2\n        N\u03d1 = 17\n        N\u03c6 = 18\n        for (m, m2Y2m) in [(2, m2Y22), (1, m2Y21), (0, m2Y20), (-1, m2Y2m1), (-2, m2Y2m2)]\n            f1 = mapslices(\u03d5\u03b8 -> sYlm(s, \u2113, m, \u03d5\u03b8[2], \u03d5\u03b8[1]), phi_theta(N\u03c6, N\u03d1, T), dims=[3])\n            f2 = mapslices(\u03d5\u03b8 -> m2Y2m(\u03d5\u03b8[2], \u03d5\u03b8[1]), phi_theta(N\u03c6, N\u03d1, T), dims=[3])\n            @test f1 \u2248 f2 atol=10eps(T) rtol=10eps(T)\n        end\n    end\n\n    @testset \"map2salm $T\" for T in [BigFloat, Float64, Float32]\n        # These test the ability of map2salm to precisely decompose the results of `sYlm`.\n        \u2113max = 7\n        N\u03d1 = 2\u2113max + 1\n        N\u03c6 = 2\u2113max + 2\n        for s in -2:2\n            for \u2113min in 0:abs(s)\n                for \u2113 in abs(s):\u2113max\n                    for m in -\u2113:\u2113\n                        f = mapslices(\u03d5\u03b8 -> sYlm(s, \u2113, m, \u03d5\u03b8[2], \u03d5\u03b8[1]), phi_theta(N\u03c6, N\u03d1, T), dims=[3])\n                        computed = map2salm(f, s, \u2113max; \u2113min)\n                        expected = zeros(Complex{T}, size(computed))\n                        expected[SphericalFunctions.Yindex(\u2113, m, \u2113min)] = one(T)\n                        if \u2249(computed, expected, atol=30eps(T), rtol=30eps(T))\n                            @show T\n                            @show \u2113max\n                            @show N\u03d1\n                            @show N\u03c6\n                            @show s\n                            @show \u2113min\n                            @show \u2113\n                            @show m\n                            println(\"computed = $computed\")\n                            println(\"expected = $expected\")\n                            println(\"max_diff = \", maximum(abs, computed .- expected), \";\")\n                            println()\n                        end\n                        @test computed \u2248 expected atol=30eps(T) rtol=30eps(T)\n                    end\n                end\n            end\n        end\n    end\n\nend\n", "meta": {"hexsha": "25472d8314f426e3dea45cc521431c95144e659f", "size": 3693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/map2salm.jl", "max_stars_repo_name": "moble/Spherical.jl", "max_stars_repo_head_hexsha": "10997165e2e634c3a3d97a120d3627475cc5aad5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-25T01:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T01:17:19.000Z", "max_issues_repo_path": "test/map2salm.jl", "max_issues_repo_name": "moble/Spherical.jl", "max_issues_repo_head_hexsha": "10997165e2e634c3a3d97a120d3627475cc5aad5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-08T03:49:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T20:38:54.000Z", "max_forks_repo_path": "test/map2salm.jl", "max_forks_repo_name": "moble/Spherical.jl", "max_forks_repo_head_hexsha": "10997165e2e634c3a3d97a120d3627475cc5aad5", "max_forks_repo_licenses": ["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.746835443, "max_line_length": 125, "alphanum_fraction": 0.4562686163, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7683620963235662}}
{"text": "cd(@__DIR__); include(\"setups/grid23x22.jl\")\ngr(dpi = 200)\n\n##\nframe = sgwt_frame(W; nf = 6)\nfilters = sgwt_filter_banks(W, \ud835\udecc; nf = 6)\nplot(\ud835\udecc, filters', lw = 3, size = (800, 450), grid = false, frame = :box,\n    legendfontsize = 14, xlab = latexstring(\"\\\\lambda\"), xguidefontsize = 14,\n    lab = [latexstring(\"h(\\\\lambda)\") latexstring(\"g(s_{1}\\\\lambda)\") latexstring(\"g(s_{2}\\\\lambda)\") latexstring(\"g(s_{3}\\\\lambda)\") latexstring(\"g(s_{4}\\\\lambda)\") latexstring(\"g(s_{5}\\\\lambda)\")])\n# plot!(\ud835\udecc, sum(filters, dims = 1)[:]/6, c = :black, lw = 3, lab = \"partition of unity\")\nplt = current()\nsavefig(plt, \"../figs/Grid$(Nx)x$(Ny)_SGWT_filter_banks.png\")\n", "meta": {"hexsha": "fe0ebc751ac48118c1b0b3d86c2fc4ce765b19da", "size": 652, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dissertations/htli/scripts/Figure10.4.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/dissertations/htli/scripts/Figure10.4.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/dissertations/htli/scripts/Figure10.4.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": 50.1538461538, "max_line_length": 199, "alphanum_fraction": 0.6334355828, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7683510220158922}}
{"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, \u03b1, 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 < \u03b1 < 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, \u03b1, 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, \u03b1, 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, \u03b1, 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, \u03b1, 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, \u03b1, end_point, h::Float64, ::RLDiffApprox)\n    #checks(f, \u03b1, 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 \u2208 0:n-1\n        summation += (f(end_point-i*h) - f(end_point-(i+1)*h))*((i+1)^(1-\u03b1) - i^(1-\u03b1))\n    end\n\n    result = ((1-\u03b1)*f(0)/n^\u03b1+summation)*end_point^(-\u03b1)*n^\u03b1/gamma(2-\u03b1)\n    return result\nend\n\nfunction fracdiff(f::FunctionAndNumber, \u03b1::Float64, end_point::AbstractArray, h::Float64, ::RLDiffApprox)::Vector\n    result = map(x->fracdiff(f, \u03b1, x, h, RLDiffApprox()), end_point)\n    return result\nend\n\n\n\n\nfunction fracdiff(f::Union{Function, Number}, \u03b1, 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, \u03b1, h)*f.(tspan)\nend\n\n#Compute the eliminator matrix S\u2096 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 \u2208 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, \u03b1, 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\u0304\u2098\u2096(N, k, \u03b1)*f(k*h)\n    end\n\n    return 1/(gamma(4-\u03b1)h^\u03b1)*result\n\nend\n\nfunction z\u0304\u2098\u2096(m, k, \u03b1)\n    if k \u2264 m-1\n        return c\u0304\u2c7c\u2096(m-1, k, \u03b1)-2*c\u0304\u2c7c\u2096(m, k, \u03b1)+c\u0304\u2c7c\u2096(m+1, k, \u03b1)\n    elseif k == m\n        return -2*c\u0304\u2c7c\u2096(m, k, \u03b1)+c\u0304\u2c7c\u2096(m+1, k, \u03b1)\n    elseif k == m+1\n        return c\u0304\u2c7c\u2096(m+1, k, \u03b1)\n    elseif k > m+1\n        return 0\n    end\nend\n\nfunction c\u0304\u2c7c\u2096(j, k, \u03b1)\n    if k==0\n        return (j-1)^(3-\u03b1)-j^(2-\u03b1)*(j-3+\u03b1)\n    elseif 1 \u2264 k \u2264 j-1\n        return (j-k+1)^(3-\u03b1)-2*(j-k)^(3-\u03b1)+(j-k-1)^(3-\u03b1)\n    elseif k == j\n        return 1\n    end\nend\n\nfunction fracdiff(f::FunctionAndNumber, \u03b1::Float64, end_point::AbstractArray, h::Float64, ::RLLinearSplineInterp)::Vector\n    result = map(x->fracdiff(f, \u03b1, x, h, RLLinearSplineInterp()), end_point)\n    return result\nend\n\nfunction fracdiff(f::FunctionAndNumber, \u03b1, 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-\u03b1)/gamma(j+1)*f(end_point-j*h)\n    end\n\n    return h^(-\u03b1)/gamma(-\u03b1)*result\nend\n\nfunction fracdiff(f::FunctionAndNumber, \u03b1, 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 += \u03c9\u2096\u2099(N, k, \u03b1)*f(point-k*h)\n    end\n\n    return point^(-\u03b1)/gamma(-\u03b1)*result\n\nend\n\nfunction \u03c9\u2096\u2099(n, k, \u03b1)\n    temp = 0\n    if k == 0\n        temp = -1\n    elseif 1 \u2264 k \u2264 n-1\n        temp = 2*k^(1-\u03b1)-(k-1)^(1-\u03b1)-(k+1)^(1-\u03b1)\n    elseif k == n\n        temp = (\u03b1-1)*n^(-\u03b1)-(n-1)^(1-\u03b1)+n^(1-\u03b1)\n    end\n    return n^\u03b1/(\u03b1*(1-\u03b1))*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\u00d75 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 \u22ee\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": "using KNITRO\nusing Compat.Test\n\n#    min  9 - 8x1 - 6x2 - 4x3\n#         + 2(x1^2) + 2(x2^2) + (x3^2) + 2(x1*x2) + 2(x1*x3)\n#    subject to  c[0]:  x1 + x2 + 2x3 <= 3\n#                x1 >= 0\n#                x2 >= 0\n#                x3 >= 0\n#    initpt (0.5, 0.5, 0.5)\n#\n#    Solution is x1=4/3, x2=7/9, x3=4/9, lambda=2/9  (f* = 1/9)\n#\n#  The problem comes from Hock and Schittkowski, HS35.\n\nfunction eval_f(x::Vector{Float64})\n    linear_terms = 9.0 - 8.0*x[1] - 6.0*x[2] - 4.0*x[3]\n    quad_terms = 2.0*x[1]^2 + 2.0*x[2]^2 + x[3]^2 + 2.0*x[1]*x[2] + 2.0*x[1]*x[3]\n    return linear_terms + quad_terms\nend\n\nfunction eval_g(x::Vector{Float64}, cons::Vector{Float64})\n    cons[1] = x[1] + x[2] + 2.0*x[3]\nend\n\nfunction eval_grad_f(x::Vector{Float64}, grad::Vector{Float64})\n    grad[1] = -8.0 + 4.0*x[1] + 2.0*x[2] + 2.0*x[3]\n    grad[2] = -6.0 + 2.0*x[1] + 4.0*x[2]\n    grad[3] = -4.0 + 2.0*x[1]            + 2.0*x[3]\nend\n\nfunction eval_jac_g(x::Vector{Float64}, jac::Vector{Float64})\n    jac[1] = 1.0\n    jac[2] = 1.0\n    jac[3] = 2.0\nend\n\nobjGoal = KTR_OBJGOAL_MINIMIZE\nobjType = KTR_OBJTYPE_QUADRATIC\n\nn = 3\nx_L = zeros(n)\nx_U = [KTR_INFBOUND,KTR_INFBOUND,\nKTR_INFBOUND]\n\nm = 1\nc_Type = [KTR_CONTYPE_LINEAR]\nc_L = [-KTR_INFBOUND]\nc_U = [3.0]\n\njac_con = Int32[0,0,0]\njac_var = Int32[0,1,2]\n\nx       = [0.5,0.5,0.5]\nlambda  = zeros(n+m)\nobj     = [0.0]\n\nkp = createProblem()\nsetOption(kp, \"hessopt\", 6)\ninitializeProblem(kp, objGoal, objType, x_L, x_U, c_Type, c_L, c_U, jac_var, jac_con)\nsetFuncCallback(kp, eval_f, eval_g)\nsetGradCallback(kp, eval_grad_f, eval_jac_g)\nsolveProblem(kp)\n\n# --- test optimal solutions ---\n@testset \"Test optimal solution\" begin\n    @test applicationReturnStatus(kp) == :Optimal\n    @test isapprox(kp.x, [1.3333333, 0.7777777, 0.4444444], atol=1e-5)\n    @test isapprox(kp.obj_val[1], 0.1111111, atol=1e-5)\nend\n\nfreeProblem(kp)\n", "meta": {"hexsha": "80881368dd87db7e64e1b617fdb43234ceab1879", "size": 1860, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/oldinterface/hs035_nohess.jl", "max_stars_repo_name": "dpo/KNITRO.jl", "max_stars_repo_head_hexsha": "433edd8363ae8b66515993a09546763d318cc3bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-14T12:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-14T12:29:13.000Z", "max_issues_repo_path": "examples/hs035_nohess.jl", "max_issues_repo_name": "Artelys/KNITRO.jl", "max_issues_repo_head_hexsha": "47ea3a969d25b8f0c964b8da0f18c43b4bc0a910", "max_issues_repo_licenses": ["MIT"], "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/hs035_nohess.jl", "max_forks_repo_name": "Artelys/KNITRO.jl", "max_forks_repo_head_hexsha": "47ea3a969d25b8f0c964b8da0f18c43b4bc0a910", "max_forks_repo_licenses": ["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.4794520548, "max_line_length": 85, "alphanum_fraction": 0.5908602151, "num_tokens": 838, "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": "#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\u03c3=z\n\t\t\tfor j=1:i-1\n\t\t\t\t\u03c3+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\t\u03c3+=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]-\u03c3)/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, \u03c9::Real;\n    tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2) =\n    sor!(zerox(A, b), A, b, \u03c9; tol=tol, maxiter=maxiter)\n\nfunction sor!(x, A::AbstractMatrix, b, \u03c9::Real;\n        tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)^2)\n\t0 < \u03c9 < 2 || warn(\"\u03c9 = $\u03c9 lies outside the range 0<\u03c9<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\u03c3=z\n\t\t\tfor j=1:i-1\n\t\t\t\t\u03c3+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\t\u03c3+=A[i,j]*xold[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\t\u03c3=(b[i]-\u03c3)/A[i,i]\n\t\t\tx[i]=xold[i]+\u03c9*(\u03c3-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, \u03c9::Real;\n     tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2)) =\n    ssor!(zerox(A, b), A, b, \u03c9; tol=tol, maxiter=maxiter)\n\nfunction ssor!(x, A::AbstractMatrix, b, \u03c9::Real;\n        tol=size(A,2)^3*eps(typeof(real(b[1]))), maxiter=size(A,2))\n\t0 < \u03c9 < 2 || warn(\"\u03c9 = $\u03c9 lies outside the range 0<\u03c9<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\u03c3=z\n\t\t\tfor j=1:i-1\n\t\t\t\t\u03c3+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\t\u03c3+=A[i,j]*xold[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\t\u03c3=(b[i]-\u03c3)/A[i,i]\n\t\t\tx[i]=xold[i]+\u03c9*(\u03c3-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\u03c3=z\n\t\t\tfor j=1:i-1\n\t\t\t\t\u03c3+=A[i,j]*xold[j]\n\t\t\tend\n\t\t\tfor j=i+1:n\n\t\t\t\t\u03c3+=A[i,j]*x[j]\n\t\t\tend\n\t\t\tA[i,i]==0 && throw(SingularError())\n\t\t\t\u03c3=(b[i]-\u03c3)/A[i,i] #This line is missing in the Templates reference\n\t\t\tx[i]=xold[i]+\u03c9*(\u03c3-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 \u2264 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 \u2264 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 \u2264 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 \u2264 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 \u2264 n\n\t\t\t\t\tmat[i,i + k] = fdcoeff1[m][ k]\n\t\t\t\tend\n\t\t\t\tif 1 \u2264 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 \u2264 n\n\t\t\t\t\tmat[i,i + k] = fdcoeff2[m][ k]\n\t\t\t\tend\n\t\t\t\tif 1 \u2264 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": "using TuringModels, StatsFuns\n\nTuring.setadbackend(:reverse_diff);\n#Turing.turnprogress(false);\n\nd = DataFrame(CSV.read(joinpath(@__DIR__, \"..\", \"..\", \"data\", \"chimpanzees.csv\"),\n  delim=';'));\nsize(d) # Should be 504x8\n\n# pulled_left, condition, prosoc_left\n@model m10_3(y, x\u2081, x\u2082) = begin\n    \u03b1 ~ Normal(0, 10)\n    \u03b2p ~ Normal(0, 10)\n    \u03b2pC ~ Normal(0, 10)\n\n    for i \u2208 1:length(y)\n        p = logistic(\u03b1 + (\u03b2p + \u03b2pC * x\u2081[i]) * x\u2082[i])\n        y[i] ~ Binomial(1, p)\n    end\nend;\n\nchns = sample(m10_3(d[:,:pulled_left], d[:,:condition], d[:,:prosoc_left]),\n  Turing.NUTS(0.95), 2000);\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# Describe the draws\n\ndescribe(chns)\n\n# End of m10.03t.jl", "meta": {"hexsha": "f8216d3734049a4f7486f74a2a6bed8eb1d138ff", "size": 893, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/10/m10.03t.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/10/m10.03t.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/10/m10.03t.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": 23.5, "max_line_length": 81, "alphanum_fraction": 0.5789473684, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7683461929791144}}
{"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, \u03d5::Real, origin = (0, 0))\n\nComputes euclidian coordinates from the given polar coordinates coordinates `(r, \u03d5)`.\n\"\"\"\nfunction euclidian(r::Real, \u03d5::Real, origin = (0, 0))\n    r >= 0 || throw(ArgumentError(\"r must be greater or equal to 0.\"))\n    \u03d5 = mod1(\u03d5 + \u03c0, 2\u03c0) - \u03c0\n    return origin .+ r .* (cos(\u03d5), sin(\u03d5))\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": "rtol = 1e-2\n\n# sunrise at equator\ndate = Dates.DateTime(2020, 2, 20, 6, 11, 0)\nlon, lat = [FT(0.0), FT(0.0)]\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test sza \u2248 \u03c0/2 rtol=rtol\n\n# solar noon at equator\ndate = Dates.DateTime(2020, 2, 20, 12, 14, 0)\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test azi \u2248 3\u03c0/2 rtol=rtol\n\n# sunset at equator\ndate = Dates.DateTime(2020, 2, 20, 18, 17, 0)\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test sza \u2248 \u03c0/2 rtol=rtol\n\n# solar noon at equator, eot correction = false\ndate = Dates.DateTime(2020, 2, 20, 12, 0, 0)\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set; eot_correction=false)\n@test azi \u2248 3\u03c0/2 rtol=rtol\n\n# sunset at equator, eot correction = false\ndate = Dates.DateTime(2020, 2, 20, 18, 0, 0)\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set; eot_correction=false)\n@test sza \u2248 \u03c0/2 rtol=rtol\n\n## Test Polar Night\n# polar night NH 1\ndate = Dates.DateTime(2020, 12, 20, 11, 0, 0)\nlon, lat = [FT(0.0), FT(80.0)]\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test sza > \u03c0/2\n\n# polar night NH 2\ndate = Dates.DateTime(2020, 12, 20, 23, 0, 0)\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test sza > \u03c0/2\n\n# polar night SH 1\ndate = Dates.DateTime(2020, 6, 20, 11, 0, 0)\nlon, lat = [FT(0.0), FT(-80.0)]\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test sza > \u03c0/2\n\n# polar night SH 2\ndate = Dates.DateTime(2020, 6, 20, 23, 0, 0)\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test sza > \u03c0/2\n\n## Test Distance\ndate = Dates.DateTime(2000, 3, 22, 0, 0, 0)\nsza, azi, d = instantaneous_zenith_angle(date, lon, lat, param_set)\n@test d \u2248 orbit_semimaj(param_set) rtol=rtol", "meta": {"hexsha": "c37b9ff93369b33d93188cf57aae4cb461818a1d", "size": 1802, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_zenith_angle.jl", "max_stars_repo_name": "claresinger/Insolation.jl", "max_stars_repo_head_hexsha": "d260374e5c893336e9f1826740c8767943c2de9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-16T20:19:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-16T20:19:33.000Z", "max_issues_repo_path": "test/test_zenith_angle.jl", "max_issues_repo_name": "claresinger/Insolation.jl", "max_issues_repo_head_hexsha": "d260374e5c893336e9f1826740c8767943c2de9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-07T22:47:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T18:53:42.000Z", "max_forks_repo_path": "test/test_zenith_angle.jl", "max_forks_repo_name": "claresinger/Insolation.jl", "max_forks_repo_head_hexsha": "d260374e5c893336e9f1826740c8767943c2de9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-24T23:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-24T23:36:51.000Z", "avg_line_length": 32.7636363636, "max_line_length": 89, "alphanum_fraction": 0.6914539401, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7683461893425076}}
{"text": "using PQBaseCamp\nusing DataFrames\nusing CSV\n\n# make an exponential weight model -\nfunction ew(data::DataFrame, map::Pair{Symbol,Symbol})::Array{Float64,1}\n\n    # initialize -\n    \u03c9_array = Array{Float64,1}()\n    \u03b1 = 0.001\n\n    # how many rows do we have?\n    (number_of_rows, _) = size(data)\n    for row_index \u2208 1:(number_of_rows - 1)\n\n        value = (1 - \u03b1)^(row_index - 1)\n        push!(\u03c9_array, value)\n    end\n\n    # scale - so that we sum to 1 \n    T = sum(\u03c9_array)\n    return reverse((1 / T) * \u03c9_array)\nend\n\n# load up a sample data file -\npath_to_data_file = \"$(pwd())/test/data/MRNA.csv\"\ndf = CSV.read(path_to_data_file, DataFrame)\n\n# what is the w?\n\u03c9_array = ew(df, :timestamp => :close)\n\n# build a computation model -\nmodel = LogReturnComputationModel()\nmodel.ticker = \"MRNA\"\nmodel.data = df\nmodel.map = :timestamp => :close\n\u0394_table = \u0394(model)\n", "meta": {"hexsha": "e1abc5357241bde7aec9364f63cd853ff998f128", "size": 853, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_log_return_call.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": "test/test_log_return_call.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": "test/test_log_return_call.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": 22.4473684211, "max_line_length": 72, "alphanum_fraction": 0.6518171161, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451595, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7683435328711838}}
{"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 \u03d5 [deg] and longitude \u03bb [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 \u2229 of polygons\n#TODO Union \u222a 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. * \u221a(5.) ) / 20.\n        b = ( 5. - \u221a(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. + \u221a(5. / 14.) ) / 4.;\n        b3 = ( 1. - \u221a(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    \u03b4(start::Int, stop::Int)\n\nUnit impulse signal\nThis function has the form of :\n\n    \u03b4(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 \u2265 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\u2080)\n\n    \n\n# parameters\n    `s::signal` : signal to be shifted\n    `n\u2080::Int` : shift amount\n\n# returns\n    s'::signal shifted\n\"\"\"\nfunction _sigshift(s::signal, n\u2080::Int)\n    y = s.A;\n    n = s.n .+ n\u2080;\n    s = signal(y, n);\n    return s\n    \nend\n\n\"\"\"\n    sigshift(n\u2080::Int)\n\n# parameters\n    `n\u2080::Int` : shift amount\n\n# returns\n    s:: anonimous  function that shifts a signal (designed to be composable)\n\n\"\"\"\nfunction sigshift(n\u2080::Int)\n    \n    return (sig -> _sigshift(sig, n\u2080))\n    \nend\n\n\n\n\"\"\"\n    realexp(a::Real, n\u2080::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\u2080::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\u2080::Int, nf::Int)\n    s = signal(0.0, n\u2080, 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\u2081::signal  , s\u2082::signal)\n\n    n\u2080 =min(minimum(s\u2081.n), minimum(s\u2082.n)) # find the minimum sample position\n    nf = max(maximum(s\u2081.n), maximum(s\u2082.n)) # find the maximum sample position\n    n=n\u2080:nf; # create the sample position vector\n\n    y\u2081 = signal(0.0, n\u2080, nf); #constructor for initial signal\n    y\u2082 = signal(0.0, n\u2080, nf); #constructor for initial signal\n\n    filter1 = findall((n .\u2265 minimum(s\u2081.n)) .& (n .\u2264 maximum(s\u2081.n)) .== 1)\n    filter2 = findall((n .\u2265 minimum(s\u2082.n)) .& (n .\u2264 maximum(s\u2082.n)) .== 1)\n\n    y\u2081.A[filter1] = s\u2081.A; # fill the signal with the values of s\u2081\n    y\u2082.A[filter2] = s\u2082.A; # fill the signal with the values of s\u2082\n\n    s = signal(0.0, n\u2080, nf); #constructor for initial signal\n    s.A = y\u2081.A + y\u2082.A; # add the two signals\n\n    return s\n\n\n\nend\n\n\n\"\"\"\n    Base.+(s\u2081::signal  , s\u2082::signal)\n\nExtends Base.+ to add two signal objects together.\n\n# Arguments\n\n    `s\u2081::signal` : signal to be added\n    `s\u2082::signal` : signal to be added\n\n\n\n# Returns\n    `s::signal` : signal s1 + s2\n\"\"\"\nfunction +(s\u2081::signal  , s\u2082::signal)\n    s = sigadd(s\u2081 , s\u2082)\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\u2081::signal  , s\u2082::signal)\n\n    n\u2080 =min(minimum(s\u2081.n), minimum(s\u2082.n)) # find the minimum sample position\n    nf = max(maximum(s\u2081.n), maximum(s\u2082.n)) # find the maximum sample position\n    n=n\u2080:nf; # create the sample position vector\n\n    y\u2081 = signal(0.0, n\u2080, nf); #constructor for initial signal\n    y\u2082 = signal(0.0, n\u2080, nf); #constructor for initial signal\n\n    filter1 = findall((n .\u2265 minimum(s\u2081.n)) .& (n .\u2264 maximum(s\u2081.n)) .== 1)\n    filter2 = findall((n .\u2265 minimum(s\u2082.n)) .& (n .\u2264 maximum(s\u2082.n)) .== 1)\n\n    y\u2081.A[filter1] = s\u2081.A; # fill the signal with the values of s\u2081\n    y\u2082.A[filter2] = s\u2082.A; # fill the signal with the values of s\u2082\n\n    s = signal(0.0, n\u2080, nf); #constructor for initial signal\n    s.A = y\u2081.A .* y\u2082.A; # add the two signals\n\n    return s\n\n\n\nend\n\n\n\n\"\"\"\n    *(s\u2081::signal  , s\u2082::signal)\n\nMultiples two signal objects together.\n\n# Arguments\n\n    `s\u2081::signal` : signal to be multiplied\n    `s\u2082::signal` : signal to be Multiples\n\n# Returns\n    `s::signal` : signal s1 * s2\n\n\"\"\"\nfunction *(s\u2081::signal  , s\u2082::signal)\n    s = sigmult(s\u2081 , s\u2082)\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, \u03b1::Real)\n\nEach signal sample is multiple by a scalar \u03b1\n\n# parameters\n    `s::signal` : signal to be scaled\n    `\u03b1::Real` : scalar\n\n# returns\n    `s::signal` : scaled signal\n\"\"\"\nfunction _sigscale(s::signal, \u03b1::Real)\n\n    s1 = signal(s.A .* \u03b1, s.n); #constructor for initial signal\n    \n    return s1\n    \nend\n\n\n\"\"\"\n    sigscale(\u03b1::Real)\n\nEach signal sample is multiple by a scalar \u03b1\n\n# parameters\n    `\u03b1::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(\u03b1::Real)\n    \n    return (sig -> _sigscale(sig, \u03b1))\nend\n\n\n\n\n\"\"\"\n    *(s\u2081::signal  , \u03b1::Real)\n\n    scale signal by scalar.\n\n# Arguments\n\n    `s\u2081::signal` : signal to be multiplied\n    `\u03b1::Real` : scalar\n    \n\n# Returns\n    `s::signal` : signal s1 * \u03b1\n\n\"\"\"\nfunction *(s\u2081::signal  , \u03b1::Real)\n    s = s\u2081 |> sigscale(\u03b1);\n    return s\nend\n\n\n\"\"\"\n    *(\u03b1::Real, s\u2081::signal)\n\nscale signal by scalar.\n\n# Arguments\n\n    `s\u2081::signal` : signal to be multiplied\n    `\u03b1::Real` : scalar\n    \n\n# Returns\n    `s::signal` : signal s1 * \u03b1\n\n\"\"\"\nfunction *(\u03b1::Real, s\u2081::signal)\n    s = s\u2081 |> sigscale(\u03b1);\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, \u03c9::Real, \u03c6::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    `\u03c9::Real` : frequency of the sinusoid in radians\n    `\u03c6::Real` : phase of the sinusoid, in radians\n\n# returns\n    s::sinusoidal signal\n\n\"\"\"\nfunction sinseq(start::Int, stop::Int, \u03c9::Real, \u03c6::Real= 0.0)\n    n = start:stop |> collect; # create the sample position vector\n    y = sin.(n .* \u03c9 .+ \u03c6); # 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, \u03c6::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\u03c0\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, \u03c6::Real= 0.0)\n    n = start:stop |> collect; # create the sample position vector\n    y = sin.(n .* ((M / N)*2\u03c0 .+ \u03c6)); # 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\u2081::signal, s\u2082::signal)\n\nConvolution function\n\n# parameters\n    `s\u2081::signal` : input signal \n    `s\u2082::signal` : impulse response signal\n\n# returns\n    s::convolution signal output\n\n\"\"\"\nfunction conv(s\u2081::signal, s\u2082::signal)\n    n\u2081 = s\u2081.n;\n    n\u2082 = s\u2082.n;\n    A\u2081 = convert(Array{Float64,1}, s\u2081.A) #conv requires more specific type\n    A\u2082 = convert(Array{Float64,1}, s\u2082.A) #conv requires more specific type\n  \n    Nyb = n\u2081[1] + n\u2082[1];\n    Nye = n\u2081[length(A\u2081)] + n\u2082[length(A\u2082)];\n  \n    ny = collect(Nyb: Nye);\n    y = DSP.conv(A\u2081, A\u2082);\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 \u00f7 2):(n\u00f72-1)\n    end\n    return -(n \u00f7 2):(n\u00f72)\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\u00d74 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\u00d74 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\u00d74 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 (\u03c1,\u03b8) 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> \u03c1,\u03b8=cartVecsToPolarGrid(X,Y);\njulia> \u03c1\n4\u00d74 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> \u03b8\n4\u00d74 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    \u03c1 = @. sqrt(X^2 + Y^2);\n    \u03b8 = [atan(y,x) for y in Y, x in X'];\n    return \u03c1, \u03b8\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": "using ModelingToolkit\nusing Test\n\n# Define some variables\n@parameters t \u03c3 \u03c1 \u03b2\n@variables x(t) y(t) z(t)\n@derivatives D'~t\n\n# Define a differential equation\neqs = [D(x) ~ \u03c3*(y-x),\n       D(y) ~ x*(\u03c1-z)-y,\n       D(z) ~ x*y - \u03b2*z]\nde = DiffEqSystem(eqs,t,[x,y,z],[\u03c3,\u03c1,\u03b2])\ngenerate_function(de)\ngenerate_function(de;version=ModelingToolkit.SArrayFunction)\njac_expr = generate_jacobian(de)\njac = calculate_jacobian(de)\nf = ODEFunction(de)\nModelingToolkit.generate_ode_iW(de)\n\n# Differential equation with automatic extraction of variables\nde2 = DiffEqSystem(eqs, t)\n\nfunction test_vars_extraction(de, de2)\n    @test isequal(de.iv, de2.iv)\n    for el in (:dvs, :ps)\n        names2 = sort(collect(var.name for var in getfield(de2,el)))\n        names = sort(collect(var.name for var in getfield(de,el)))\n        @test names2 == names\n    end\nend\ntest_vars_extraction(de, de2)\n\n@testset \"time-varying parameters\" begin\n    @parameters \u03c3\u2032(t)\n    eqs = [D(x) ~ \u03c3\u2032*(y-x),\n           D(y) ~ x*(\u03c1-z)-y,\n           D(z) ~ x*y - \u03b2*z]\n    de = DiffEqSystem(eqs,t,[x,y,z],[\u03c3\u2032,\u03c1,\u03b2])\n    @test begin\n        f = eval(generate_function(de))\n        du = [0.0,0.0,0.0]\n        f(du, [1.0,2.0,3.0], [x->x+7,2,3], 5.0)\n        du \u2248 [12, -3, -7]\n    end\nend\n\n# Conversion to first-order ODEs #17\n@derivatives D3'''~t\n@derivatives D2''~t\n@variables u(t) u_tt(t) u_t(t) x_t(t)\neqs = [D3(u) ~ 2(D2(u)) + D(u) + D(x) + 1\n       D2(x) ~ D(x) + 2]\nde = DiffEqSystem(eqs, t)\nde1 = ode_order_lowering(de)\nlowered_eqs = [D(u_tt) ~ 2u_tt + u_t + x_t + 1\n               D(x_t)  ~ x_t + 2\n               D(u_t)  ~ u_tt\n               D(u)    ~ u_t\n               D(x)    ~ x_t]\n@test de1.eqs == convert.(ModelingToolkit.DiffEq, lowered_eqs)\n@test isequal(de1.dvs, [u_tt, x_t, u_t, u, x])\n@test isequal(de1.iv, t)\ndu = zeros(5)\nODEFunction(de1)(du, ones(5), nothing, 0.1)\n@test du == [5.0, 3.0, 1.0, 1.0, 1.0]\n\n# Internal calculations\na = y - x\neqs = [D(x) ~ \u03c3*a,\n       D(y) ~ x*(\u03c1-z)-y,\n       D(z) ~ x*y - \u03b2*z]\nde = DiffEqSystem(eqs,t,[x,y,z],[\u03c3,\u03c1,\u03b2])\ngenerate_function(de)\njac = calculate_jacobian(de)\nf = ODEFunction(de)\n\n# Define a nonlinear system\neqs = [0 ~ \u03c3*(y-x),\n       0 ~ x*(\u03c1-z)-y,\n       0 ~ x*y - \u03b2*z]\nns = NonlinearSystem(eqs,[x,y,z],[t,\u03c3,\u03c1,\u03b2])\nns2 = NonlinearSystem(eqs)\nfor el in (:vs, :ps)\n    names2 = sort(collect(var.name for var in getfield(ns2,el)))\n    names = sort(collect(var.name for var in getfield(ns,el)))\n    @test names2 == names\nend\n\ngenerate_function(ns)\n\n@derivatives D'~t\n@parameters A B C\n_x = y / C\neqs = [D(x) ~ -A*x,\n       D(y) ~ A*x - B*_x]\nde = DiffEqSystem(eqs,t,[x,y],[A,B,C])\ntest_vars_extraction(de, DiffEqSystem(eqs,t))\ntest_vars_extraction(de, DiffEqSystem(eqs))\n@test begin\n    f = eval(generate_function(de))\n    du = [0.0,0.0]\n    f(du, [1.0,2.0], [1,2,3], 0.0)\n    du \u2248 [-1, -1/3]\nend\n\n# Now nonlinear system with only variables\n@variables x y z\n@parameters \u03c3 \u03c1 \u03b2\n\n# Define a nonlinear system\neqs = [0 ~ \u03c3*(y-x),\n       0 ~ x*(\u03c1-z)-y,\n       0 ~ x*y - \u03b2*z]\nns = NonlinearSystem(eqs, [x,y,z], [\u03c3,\u03c1,\u03b2])\njac = calculate_jacobian(ns)\n@testset \"nlsys jacobian\" begin\n    @test isequal(jac[1,1], \u03c3 * -1)\n    @test isequal(jac[1,2], \u03c3)\n    @test isequal(jac[1,3], 0)\n    @test isequal(jac[2,1], \u03c1 - z)\n    @test isequal(jac[2,2], -1)\n    @test isequal(jac[2,3], x * -1)\n    @test isequal(jac[3,1], y)\n    @test isequal(jac[3,2], x)\n    @test isequal(jac[3,3], -1 * \u03b2)\nend\nnlsys_func = generate_function(ns)\njac_func = generate_jacobian(ns)\nf = @eval eval(nlsys_func)\n\n# Intermediate calculations\n# Define a nonlinear system\neqs = [0 ~ \u03c3*a,\n       0 ~ x*(\u03c1-z)-y,\n       0 ~ x*y - \u03b2*z]\nns = NonlinearSystem(eqs,[x,y,z],[\u03c3,\u03c1,\u03b2])\nnlsys_func = generate_function(ns)\njac = calculate_jacobian(ns)\njac = generate_jacobian(ns)\n", "meta": {"hexsha": "6f7b106504940c7481a1fc43336a9477b3e4d610", "size": 3730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/system_construction.jl", "max_stars_repo_name": "JunpengGao233/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "5ac6f7dce3658a34c80fb2c6f266686a47888ec5", "max_stars_repo_licenses": ["MIT"], "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/system_construction.jl", "max_issues_repo_name": "JunpengGao233/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "5ac6f7dce3658a34c80fb2c6f266686a47888ec5", "max_issues_repo_licenses": ["MIT"], "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/system_construction.jl", "max_forks_repo_name": "JunpengGao233/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "5ac6f7dce3658a34c80fb2c6f266686a47888ec5", "max_forks_repo_licenses": ["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.4539007092, "max_line_length": 68, "alphanum_fraction": 0.5957104558, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8558511451289038, "lm_q1q2_score": 0.768293553096754}}
{"text": "A = matrixdepot(\"toeplitz\", [1,2,3,4,5])\n@test A == matrixdepot(\"toeplitz\", 5)\n\nB = matrixdepot(\"toeplitz\", [1,2,3], [1,4,5])\n@test B[1,3] == 5\n@test B[3,1] == 3\n@test B[1,2] == 4\nprintln(\"'toeplitz' passed test...\")\n\nn = rand(2:10)\nA = matrixdepot(\"prolate\", n)\n@test issym(A)\n\nprintln(\"'prolate' passed test...\")\n", "meta": {"hexsha": "e0048e810cc3f016e0191f095c63416d8dfe2cc1", "size": 315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_toeplitz.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": "test/test_toeplitz.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": "test/test_toeplitz.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": 21.0, "max_line_length": 45, "alphanum_fraction": 0.5936507937, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703476, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7682935430347178}}
{"text": "######################\n# This is SemiLinearHeat but using FFTW\n\nusing FFTW\nx=range(0,stop=2\u03c0,length=100)\nu(x) = sin(x)\nfreqs = fft(u.(x))[ 1 : length(x) \u00f7 2 + 1]  ## \u00f7 this means integer division\nc= 2*abs.(freqs/length(x))\n\n\n######################\n# instead of the above section\nusing ApproxFun\ns = Fourier()\nn = 100\nT = ApproxFun.plan_transform(s,n)\nTi = ApproxFun.plan_itransform(s,n)\n\nx = points(s,n)    # 0  to 2*pi\nr = (T*(cos.(cos.(x.-0.1))))\n\n\nder = Derivative(s,2)\n\n\n\n\n\n\n\n####################\n# PDE-derived ODE\n\n\nusing Sundials\nusing Plots; gr()\nusing ApproxFun\nusing Sundials\nusing LinearAlgebra\nusing LinearMaps\n\nimport Base.At_mul_B!\n\nS = Fourier()\nn=100\nx = points(S,n)\nT = ApproxFun.plan_transform(S,n)\nTi = ApproxFun.plan_itransform(S,n)\n\n\nu0= T*cos.(cos.(x.-0.1))\n\nD2 = Derivative(S,2)\nL = D2[1:n,1:n]\ntspan = (0.0,10.0)\n\n\nfunction heat(du,u,L,t)\n    mul!(du,L,u)\nend\n\nprob = ODEProblem(heat, u0,tspan,L)\nsol = solve(prob)\nplot(x,Ti*sol(0.0))\nplot!(x,Ti*sol(0.5))\nplot!(x,Ti*sol(2.0))\nplot!(x,Ti*sol(3.0))\nplot!(x,Ti*sol(10.0))\n", "meta": {"hexsha": "fef67d18e3b4c9bcbbbb8e92340fda9475a8b800", "size": 1043, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Missing around and learning DifferentialEquations.jl/demos.jl", "max_stars_repo_name": "moustafa-7/Pre-GSoC-2019_period", "max_stars_repo_head_hexsha": "722c565e9069d144585944e46ab903285519a79b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Missing around and learning DifferentialEquations.jl/demos.jl", "max_issues_repo_name": "moustafa-7/Pre-GSoC-2019_period", "max_issues_repo_head_hexsha": "722c565e9069d144585944e46ab903285519a79b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Missing around and learning DifferentialEquations.jl/demos.jl", "max_forks_repo_name": "moustafa-7/Pre-GSoC-2019_period", "max_forks_repo_head_hexsha": "722c565e9069d144585944e46ab903285519a79b", "max_forks_repo_licenses": ["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.115942029, "max_line_length": 76, "alphanum_fraction": 0.6088207095, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.768273420199296}}
{"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\u03c0^2 * f^2 .* (t.-tpoint).^2).*exp.(-\u03c0^2 * f^2 .* (t.-tpoint).^2)\n\n    return (s, t)\nend\n\n\"\"\"\n\n    dampedSinusoid(;A::Float64=1.0, \u03c9::Float64=1.0, \u03d5::Float64=0.0, n::Int64=100, dt::Float64=0.001, \u03bb::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- `\u03c9::Float64`    : Frequency\n- `\u03bb::Float64`    : Decay constant\n- `\u03d5::Float64`    : Phase angle at t=0\n- `\u03b7::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, \u03c9::Float64=1.0, \u03d5::Float64=0.0, \u03b7::Float64=0.0, n::Int64=100, dt::Float64=0.001, t0::Float64=0.0, \u03bb::Float64=2.0)\n    # generate time axis\n    t = timeAxis(dt, t0, n)\n    # damped sinusoidal function\n    s = A*exp.(-\u03bb*abs.(t.-\u03b7)) .* cos.(\u03c9*t .+ \u03d5)\n\n    return (s, t)\nend\n\n\"\"\"\n\n    sinc(;A::Float64=1.0, \u03c9::Float64=1.0, \u03d5::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- `\u03c9::Float64`    : Frequency\n- `\u03d5::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, \u03c9::Float64=1.0, \u03d5::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.(\u03c9.*t.+\u03d5)\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\u2264maxtp && x\u2265mintp), tp)\n    s = [sum(cos.((2\u03c0 ./ 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 [-\u03c0, \u03c0]\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\u03c0).*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 \u00d7 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 \u2265 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 `\u2207f` 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 `\u2207f` 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\u208b\u2081, T\u208b\u2082) = 2*x*T\u208b\u2081 - T\u208b\u2082, T\u208b\u2081\n\n\"Initialize T\u208b\u2081, T\u208b\u2082 for the Chebyshev recurrence.\"\n@inline _chebyshev_recurrence_init{T}(x::T) = x, one(T)\n\nmacro _chebyshev_recurrence!(x, T\u208b\u2081, T\u208b\u2082)\n    T\u208b\u2081 = esc(T\u208b\u2081)\n    T\u208b\u2082 = esc(T\u208b\u2082)\n    :(($(T\u208b\u2081), $(T\u208b\u2082)) = _chebyshev_recurrence($(esc(x)), $(T\u208b\u2081), $(T\u208b\u2082)))\nend\n\nfunction basis!{T}(c::Chebyshev, x::T, b::AbstractVector{T})\n    @argcheck c.n == length(b)\n    T\u208b\u2081, T\u208b\u2082 = _chebyshev_recurrence_init(x)\n    for i in 1:c.n\n        if i == 1\n            b[i] = T\u208b\u2082\n        else\n            if i > 2\n                @_chebyshev_recurrence! x T\u208b\u2081 T\u208b\u2082\n            end\n            b[i] = T\u208b\u2081\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, \u03b8, x::T)\n    T\u208b\u2081, T\u208b\u2082 = _chebyshev_recurrence_init(x)\n    value = zero(T)\n    for i in 1:c.n\n        if i == 1\n            value += T\u208b\u2082*\u03b8[i]\n        else\n            if i > 2\n                @_chebyshev_recurrence! x T\u208b\u2081 T\u208b\u2082\n            end\n            value += T\u208b\u2081*\u03b8[i]\n        end\n    end\n    value\nend\n\nfunction evaluate{T}(c::Chebyshev, \u03b8, vp::ValuePartial{T})\n    ## if T(x) = 2xT\u208b\u2081(x) - T\u208b\u2082(x)\n    ## then T\u2032(x) = 2T\u208b\u2081(x) + 2xT\u2032\u208b\u2081(x) - T\u2032\u208b\u2082(x), with T\u2032\u2082 = 1 and T\u2032\u2081 = 0\n    x = vp.x\n    value = partial = zero(T)\n    T\u208b\u2081 = x\n    T\u208b\u2082 = T\u2032\u208b\u2081 = one(T)\n    T\u2032\u208b\u2082 = zero(T)\n    for i in 1:c.n\n        if i == 1\n            value += T\u208b\u2082*\u03b8[i]\n        else\n            if i > 2\n                @_chebyshev_recurrence! x T\u2032\u208b\u2081 T\u2032\u208b\u2082\n                T\u2032\u208b\u2081 += 2*T\u208b\u2081\n                @_chebyshev_recurrence! x T\u208b\u2081 T\u208b\u2082\n            end\n            value += T\u208b\u2081*\u03b8[i]\n            partial += T\u2032\u208b\u2081*\u03b8[i]\n        end\n    end\n    value, partial\nend\n\nevaluate{T}(c::Chebyshev, \u03b8, x::Partial{T}) = evaluate(c, \u03b8, ValuePartial(x.x))[2]\n\nfunction fit!{T}(c::Chebyshev, ys::AbstractVector{T}, \u03b8::AbstractVector{T})\n    @argcheck c.n == length(ys) == length(\u03b8)\n    x = points(c, T)\n    T\u208b\u2082 = ones(T, c.n)\n    T\u208b\u2081 = copy(x)\n    for i in 1:c.n\n        if i == 1\n            \u03b8[1] = sum(ys) / c.n\n        else\n            if i > 2\n                for j in 1:c.n\n                    @_chebyshev_recurrence! x[j] T\u208b\u2081[j] T\u208b\u2082[j]\n                end\n            end\n            \u03b8[i] = dot(T\u208b\u2081, ys) *2 / c.n\n        end\n    end\n    \u03b8\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\u00e4rkka, 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 \u00f7 2 + 1 - last_remaining(n \u00f7 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": "n = rand(1:10)\nZ = Companion(randn(n))\n\n#Special properties\n@test Matrix(inv(Z)) \u2248 inv(Matrix(Z))\n\n#Matvec product\nb = randn(n)\n@test Z*b \u2248 Matrix(Z)*b\n\nm = rand(1:10)\nA = randn(m, n)\n@test A*Z \u2248 A*Matrix(Z)\n\n# Polynomial construction\nusing Polynomials\np = Polynomial([-1,0,1])\np_c = Companion(p)\nv1 = [1,1]\nv2 = [-1,1]\n@test p_c*v1 == v1\n@test p_c*v2 == -v2\n", "meta": {"hexsha": "bee2a8397108cbd12ba1ce4720c2f933e0d01c90", "size": 359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/companion.jl", "max_stars_repo_name": "JuliaMath/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2018-09-13T10:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T23:21:37.000Z", "max_issues_repo_path": "test/companion.jl", "max_issues_repo_name": "JuliaMath/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-08-17T17:39:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T18:27:05.000Z", "max_forks_repo_path": "test/companion.jl", "max_forks_repo_name": "JuliaMath/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-08-17T16:49:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T10:22:09.000Z", "avg_line_length": 15.6086956522, "max_line_length": 37, "alphanum_fraction": 0.6239554318, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.768260139458213}}
{"text": "using SpecialFunctions, StatsFuns\n\n@testset \"logmvgamma\" begin\n    @testset \"type behavior\" for eltya in (Float32, Float64)\n        p = rand(1:50)\n        a = rand(eltya)\n        # add p since loggamma is only define for positive arguments\n        @test typeof(logmvgamma(p, a + p)) == eltya\n    end\n\n    @testset \"consistent with loggamma\" for eltya in (Float32, Float64)\n        #  \u0393\u2081(a) = \u0393(a), \u0393\u2082(a) = \u221a\u03c0 \u0393(a) \u0393(a - 0.5), etc\n        a = rand(eltya) + 1 # add one since loggamma is only define for positive arguments\n        @test logmvgamma(1, a) \u2248 loggamma(a)\n        @test logmvgamma(2, a) \u2248    eltya(0.5log\u03c0) + loggamma(a) + loggamma(a - eltya(0.5))\n        @test logmvgamma(3, a) \u2248 eltya((3/2)*log\u03c0) + loggamma(a) + loggamma(a - eltya(0.5)) + loggamma(a - one(a))\n    end\n\n    @testset \"consistent with itself\" for eltya in (Float32, Float64)\n        #  \u0393\u1d62(a) = (\u03c0^{i-1/2}) \u0393(a) \u0393\u1d62\u208b\u2081(a - 0.5)\n        for p in 1:50\n            a = rand(eltya) + p # add p since loggamma is only define for positive arguments\n            @test logmvgamma(p, a) \u2248 eltya((p/2-1/2)*log\u03c0) + loggamma(a) + logmvgamma(p - 1, a - eltya(0.5))\n        end\n    end\nend\n", "meta": {"hexsha": "c850d17fcd62b916b2e7e5fd4af6e605e70086e5", "size": 1150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/misc.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/StatsFuns.jl-4c63d2b9-4356-54db-8cca-17b64c39e42c", "max_stars_repo_head_hexsha": "1bdf135628954aa94bca9288641114d1bfcc0617", "max_stars_repo_licenses": ["MIT"], "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/misc.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/StatsFuns.jl-4c63d2b9-4356-54db-8cca-17b64c39e42c", "max_issues_repo_head_hexsha": "1bdf135628954aa94bca9288641114d1bfcc0617", "max_issues_repo_licenses": ["MIT"], "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/misc.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/StatsFuns.jl-4c63d2b9-4356-54db-8cca-17b64c39e42c", "max_forks_repo_head_hexsha": "1bdf135628954aa94bca9288641114d1bfcc0617", "max_forks_repo_licenses": ["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.5925925926, "max_line_length": 114, "alphanum_fraction": 0.5852173913, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098192, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7682601362441343}}
{"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, \u03b1, 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.^\u03b1\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\ud83d\ude05\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(\u03b1[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(\u03b1, n, g)\n    p = length(g)-1\n    b = 1 + \u03b1\n    g0 = g[1]\n    w = Float64[]\n    push!(w, g[1]^\u03b1)\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": "# logistic regression on mnist data\n\nusing MultiStochGrad\n\nusing  LinearAlgebra, Test\nusing Random, Distributions\n\n\ninclude(\"../src/applis/LinearRegression.jl\")\n\n\n# the . means we use the module LinearRegressionMod in the current module, other wise refer toa package!\n\n\nfunction test_linear_regression_scsg()\n    true_coefficients = [13.37, -4.2, 3.14]\n    # sample noise according to a N(0,1)\n    datas = Vector{Vector{Float64}}()\n    values = Vector{Float64}()\n    d = Normal()\n    for i in 1:100\n        v = Vector{Float64}()\n        push!(v,1.)\n        push!(v, rand())\n        push!(v, rand())\n        y = dot(true_coefficients, v) + rand(d)\n        push!(datas, v)\n        push!(values, y)\n    end\n    observations= Observations(datas,values)\n    nbterms = length(observations.datas)\n    # define our evaluations\n    linear_reg_term_value = make_linear_reg_term_value(observations)\n    term_function =  TermFunction{typeof(linear_reg_term_value)}(linear_reg_term_value, nbterms, Dims{1}(3))\n    #\n    linear_reg_term_gradient = make_linear_reg_term_gradient(observations)\n    term_gradient = TermGradient{typeof(linear_reg_term_gradient)}(linear_reg_term_gradient ,nbterms, Dims{1}(3))\n    evaluator = Evaluator{typeof(linear_reg_term_value),typeof(linear_reg_term_gradient)}(term_function,term_gradient) \n    #\n    scsg_pb = SCSG(0.1, 0.3, 1 , 0.7)\n    # solve.\n    nb_iter = 50\n    position = fill(1., 3)\n    initial_error = compute_value(evaluator, position)\n    @info \"\\n initial error \\n\\n\" initial_error\n    position, value = minimize(scsg_pb, evaluator, nb_iter, position)\n    @info \"value , position \" value  position\n    @info \"\\n\\n test_linear_regression_scsg done \\n \\n\"\n    value < 0.65 ? true : false\nend\n\n\n\nfunction test_linear_regression_svrg()\n    true_coefficients = [13.37, -4.2, 3.14]\n    # sample noise according to a N(0,1)\n    datas = Vector{Vector{Float64}}()\n    values = Vector{Float64}()\n    d = Normal()\n    for i in 1:100\n        v = Vector{Float64}()\n        push!(v,1.)\n        push!(v, rand())\n        push!(v, rand())\n        y = dot(true_coefficients, v) + rand(d)\n        push!(datas, v)\n        push!(values, y)\n    end\n    observations= Observations(datas,values)\n    nbterms = length(observations.datas)\n    # define our evaluations \n    linear_reg_term_value = make_linear_reg_term_value(observations)\n    term_function =  TermFunction{typeof(linear_reg_term_value)}(linear_reg_term_value, nbterms, Dims{1}(3))\n    #\n    linear_reg_term_gradient = make_linear_reg_term_gradient(observations)\n    term_gradient = TermGradient{typeof(linear_reg_term_gradient)}(linear_reg_term_gradient ,nbterms, Dims{1}(3))\n    evaluator = Evaluator{typeof(linear_reg_term_value),typeof(linear_reg_term_gradient)}(term_function,term_gradient)\n    #\n    svrg_pb = SVRG(100, 0.2)\n    # solve.\n    nb_iter = 60\n    position = fill(1., 3)\n    initial_error = compute_value(evaluator, position)\n    @info \"\\n initial error \\n\\n\" initial_error\n    position, value = minimize(svrg_pb, evaluator, nb_iter, position)\n    @info \"value , position \", value ,  position\n    @info \"\\n\\n test_linear_regression_svrg done \\n \\n\"\n    value < 0.65 ? true : false\nend", "meta": {"hexsha": "9a1fbf8521833f80becbcdf256042c97cc66fd49", "size": 3174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TestLinearRegression.jl", "max_stars_repo_name": "jean-pierreBoth/MultiStochGrad.jl", "max_stars_repo_head_hexsha": "2ef78aca6fa91971a97827307fea04b6fe753c51", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "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/TestLinearRegression.jl", "max_issues_repo_name": "jean-pierreBoth/MultiStochGrad.jl", "max_issues_repo_head_hexsha": "2ef78aca6fa91971a97827307fea04b6fe753c51", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-23T11:21:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-23T11:21:12.000Z", "max_forks_repo_path": "test/TestLinearRegression.jl", "max_forks_repo_name": "jean-pierreBoth/MultiStochGrad.jl", "max_forks_repo_head_hexsha": "2ef78aca6fa91971a97827307fea04b6fe753c51", "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": 35.6629213483, "max_line_length": 119, "alphanum_fraction": 0.6871455577, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.768260130760694}}
{"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) \u00f7 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\u00f72, 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\u00f72),res,repeat([missing], n-n\u00f72-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\u2013760. \nhttps://doi.org/10.2307/2529140\n\nJosse, J., Pag\u00e8s, J., Husson, F., 2008. Testing the significance of the RV coefficient. \nComputational Statistics & Data Analysis 53, 82\u201391. 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\u2013405. 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\u2013265. 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": "module day05 \n\ninclude(\"inputs.jl\")\ninput = inputs.input_d5()\n\nlookup = Dict('B'=>'1', 'F'=>'0', 'R'=>'1', 'L'=>'0')\n\nfunction parse_bp(bp)\n    row = parse(Int, join(lookup[c] for c in bp[1:7]), base=2)\n    col = parse(Int, join(lookup[c] for c in bp[8:end]), base=2)\n    seat_id = 8*row + col\n    return seat_id\nend\n\n@assert parse_bp(\"BFFFBBFRRR\") == 567\n@assert parse_bp(\"FFFBBBFRRR\") == 119\n@assert parse_bp(\"BBFFBBFRLL\") == 820\n\n# Part 1\nfunction highest_id(input) \n    seat_ids = parse_bp.(input)\n    return maximum(seat_ids)\nend\n@info \"Day 5, Part 1 answer: $(highest_id(input))\"\n\n#Part 2\n# function find_seat(;input=input())\nfunction find_seat(input)\n    seat_ids = parse_bp.(input)\n    lo = minimum(seat_ids)\n    hi = maximum(seat_ids)\n    return [x for x in lo:hi if x \u2209 seat_ids]\nend\n@info \"Day 5, Part 2 answer: $(find_seat(input)[1])\"\n\nend", "meta": {"hexsha": "bf638475ffb64825f53609cca491c51d7957c7b6", "size": 851, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day_05.jl", "max_stars_repo_name": "danjburns/AdventOfCode2020", "max_stars_repo_head_hexsha": "2c7cb0d1cbc41960da26691d55a572b9806bdb32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day_05.jl", "max_issues_repo_name": "danjburns/AdventOfCode2020", "max_issues_repo_head_hexsha": "2c7cb0d1cbc41960da26691d55a572b9806bdb32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day_05.jl", "max_forks_repo_name": "danjburns/AdventOfCode2020", "max_forks_repo_head_hexsha": "2c7cb0d1cbc41960da26691d55a572b9806bdb32", "max_forks_repo_licenses": ["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.6388888889, "max_line_length": 64, "alphanum_fraction": 0.6486486486, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7682501510583802}}
{"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\u03c0*[0:N-1]/N)\n    crl = (1-2r)cr\n    crr = (1+2r)cr\n    dom = \u222a(Segment.(crl,crr))\n    #dom = \u222a(Circle.(cr,ones(length(cr))r))\n    #dom = \u222a(Segment.(crl[1:2:end],crr[1:2:end]) \u222a \u222a(Circle.(cr[2:2:end],ones(length(cr[2:2:end]))r))\n\n    sp = Space(dom)\n    cwsp = CauchyWeight(sp\u2297sp,0)\n    ui\u0393,\u2a0d = Fun(t->ui(real(t),imag(t))+0im,sp),DefiniteLineIntegral(dom)\n\n    G = GreensFun(g1,cwsp;method=:Cholesky)\n\n    \u2202u\u2202n = \u2a0d[G]\\ui\u0393\n\n    us(x,y) = -logkernel(\u2202u\u2202n,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": "# myplotfile.jl\nusing Plots, Distributions\n\t\n\u03bc\u2081 = 10; \u03bc\u2082 = 20; \u03bc = [\u03bc\u2081, \u03bc\u2082]  # mean matrix\n\u03a3 = [1.0 0;0 3];                # covariance matrix (i.e. no correlation between the variables)\nd = Distributions.MvNormal(\u03bc,\u03a3) # multivariate normal distribution\n\n# make a grid\nns = 3\nnx = 21\nny = 31\nX = range(\u03bc\u2081 - ns*\u03a3[1,1], stop=\u03bc\u2081 + ns*\u03a3[1,1],length=nx);\nY = range(\u03bc\u2082 - ns*\u03a3[2,2], stop=\u03bc\u2082 + ns*\u03a3[2,2],length=ny);\n\nZ = permutedims(collect(Iterators.product(X,Y)))\nZ = map(x->pdf(d,collect(x)), Z)\n\n# common plot setting\nplotsettings =  Dict(:xlims=>(0,20), :ylims=>(10,30), \n                 :xlabel=>\"x\", :ylabel=>\"y\")\n\np = plot(surface(X,Y,Z, color=:blues, title=\"surface plot\"),\n         surface(X,Y,Z, color=:blues_r, title=\"surface plot\\n(reversed colors)\"),\n         contourf(X,Y,Z, title=\"contour plot\"),\n         heatmap(X,Y,Z, title=\"heatmap\"), \n         layout=(2,2), size=(1200,1200); plotsettings...)\n\nfor extension in [\"png\",\"pdf\"]\n    savefig(p, \"./img/myplot.$(extension)\")\nend", "meta": {"hexsha": "99d289a848c608fcfd02e0d5bff9f32bf1795462", "size": 986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/myplotfile.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/myplotfile.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/myplotfile.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": 32.8666666667, "max_line_length": 95, "alphanum_fraction": 0.6034482759, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7682495548307248}}
{"text": "# libpurex:\n# Exponential families paramterised by their means\n\ninclude(\"binary_search.jl\");\n\nstruct Gaussian\n    \u03c32;\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,    \u03bc, \u03bb) = (\u03bc-\u03bb)^2/(2*expfam.\u03c32);\nd(expfam::Bernoulli,   \u03bc, \u03bb) = rel_entr(\u03bc, \u03bb) + rel_entr(1-\u03bc, 1-\u03bb);\nd(expfam::Exponential, \u03bc, \u03bb) = \u03bb == 0 ? Inf : \u03bc/\u03bb - log(\u03bc/\u03bb) - 1;\nd(expfam::Poisson,     \u03bc, \u03bb) = rel_entr(\u03bc, \u03bb) - \u03bc + \u03bb;\n\n\n# solution for \u03bb in \\min_\u03bb d(\u03bc, \u03bb) - \u03bb x\n# i.e. \u03bb satisfying (\u03bb - \u03bc)\u03d5''(\u03bb) == x\n\ninvh(expfam::Gaussian,    \u03bc, x) = \u03bc + x*expfam.\u03c32;\ninvh(expfam::Bernoulli,   \u03bc, x) = 2\u03bc/(1-x+sqrt((x-1)^2 + 4*x*\u03bc));\ninvh(expfam::Exponential, \u03bc, x) = x > 0 ? Inf : 2\u03bc/(1 + sqrt(1 - 4*x*\u03bc));\ninvh(expfam::Poisson,     \u03bc, x) = \u03bc/(1-x);\n\nsample(rng, expfam::Gaussian,    \u03bc) = \u03bc + sqrt(expfam.\u03c32)*randn(rng);\nsample(rng, expfam::Bernoulli,   \u03bc) = rand(rng) \u2264 \u03bc;\nsample(rng, expfam::Exponential, \u03bc) = randexp(rng)*\u03bc;\n\n# upward and downward confidence intervals\ndup(expfam::Gaussian, \u03bc, v) = \u03bc + sqrt(2*expfam.\u03c32*v);\nddn(expfam::Gaussian, \u03bc, v) = \u03bc - sqrt(2*expfam.\u03c32*v);\n\nfunction dup(expfam::Bernoulli, \u03bc, v)\n    \u03bc == 1 ? 1. : binary_search(\u03bb -> d(expfam, \u03bc, \u03bb) - v, \u03bc, 1);\nend\n\nfunction ddn(expfam::Bernoulli, \u03bc, v)\n    \u03bc == 0 ? 0. : binary_search(\u03bb -> v - d(expfam, \u03bc, \u03bb), 0, \u03bc);\nend\n\nfunction dup(expfam::Exponential, \u03bc, v)\n    binary_search(\u03bb -> d(expfam, \u03bc, \u03bb) - v, \u03bc, \u03bc*exp(v+1));\nend\n\nfunction ddn(expfam::Exponential, \u03bc, v)\n    binary_search(\u03bb -> v - d(expfam, \u03bc, \u03bb), 0, \u03bc);\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": "module TestCatElements\nusing Test\nusing Catlab, Catlab.Theories, Catlab.Graphs, Catlab.CategoricalAlgebra\n\narr = @acset Graph begin\n  V = 2\n  E = 1\n  src=[1]\n  tgt=[2]\nend\nelarr = elements(arr)\n@testset \"Arrow Elements\" begin\n  @test nparts(elarr, :El)  == 3\n  @test nparts(elarr, :Arr) == 2\n  @test nparts(elarr, :Ob)  == 2\n  @test nparts(elarr, :Hom) == 2\n  @test elarr[:, :\u03c0\u2091]    == [1,1,2]\n  @test elarr[:, :\u03c0\u2090]    == [1,2]\n  @test elarr[:, :src]   == [3,3]\n  @test elarr[:, :tgt]   == [1,2]\n  @test elarr[:, :nameo] == [:V, :E]\n  @test elarr[:, :nameh] == [:src, :tgt]\n  @test elarr[:, :dom]   == [2, 2]\n  @test elarr[:, :cod]   == [1, 1]\nend\n\nb = @acset Graph begin\n  V = 2\n  E = 1\n  src = [1]\n  tgt = [2]\nend\n\nThBPG, obmap, hommap = CatElements.presentation(elements(b))\n@test Symbol.(generators(ThBPG)) == [:E_1, :V_1, :V_2, :tgt_E_1, :src_E_1]\n\n\np\u2080 = @acset Graph begin\n  V = 2\n  E = 2\n  src=[1,2]\n  tgt=[2,1]\nend\n\nThPetri, obmap, hommap = CatElements.presentation(elements(p\u2080))\n@test Symbol.(generators(ThPetri)) == [:E_1, :E_2, :V_1, :V_2, :src_E_2, :tgt_E_1, :tgt_E_2, :src_E_1]\n\n@acset_type Petri(ThPetri)\n\nsir_eltsch = @acset Petri begin\n  V_1 = 3\n  V_2 = 2\n  E_1 = 3\n  E_2 = 3\n\n  src_E_1 = [1,2,2]\n  tgt_E_1 = [1,1,2]\n\n  src_E_2 = [1,1,2]\n  tgt_E_2 = [2,2,3]\nend\n\n@testset \"DiBipartite Elements\" begin\n  @test length(generators(ThPetri)) == 8\n  @test nparts(sir_eltsch, :V_1) == 3 \n  @test nparts(sir_eltsch, :V_2) == 2\n  @test nparts(sir_eltsch, :E_1) == 3\n  @test nparts(sir_eltsch, :E_2) == 3\n  @test sir_eltsch[:, :src_E_2] == [1,1,2]\nend\n\nend\n", "meta": {"hexsha": "fb287d3cf018439f4d6eb30da363dbebb8eec945", "size": 1563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/categorical_algebra/CatElements.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": "test/categorical_algebra/CatElements.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": "test/categorical_algebra/CatElements.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": 21.4109589041, "max_line_length": 102, "alphanum_fraction": 0.5956493922, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7682495523600796}}
{"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{\u03c6}{\u03c4}\\\\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- `\u03c4` is the duration of the pulse (FWHM) and has the default value 18.02fs\n- `t\u2080` is the origin of the time axis and it is 0 by default\n- `z\u2080` is the initial position of the intensity peak and has the default value `-4*\u03c4*c`\n\"\"\"\nGaussProfile\n\nstruct GaussProfile{T,IT,L} <: AbstractTemporalProfile\n    inv_\u03c4::IT\n    t\u2080::T\n    z\u2080::L\nend\n\nfunction GaussProfile(;\u03c4, t\u2080=zero(\u03c4), z\u2080)\n    GaussProfile(inv(\u03c4), t\u2080, z\u2080)\nend\n\n@doc \"\"\"\n    Cos\u00b2Profile{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{\u03c6}{\u03c4}\\\\right)\\\\right]^2, & \\\\text{for } |t - t\u2080| < \u03c4 / 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- `\u03c4` is the duration of the pulse and has the default value 18.02fs\n- `t\u2080` is the origin of the time axis and it is 0 by default\n- `z\u2080` is the initial position of the intensity peak and is 0 by default\n\"\"\"\nCos\u00b2Profile\n\nstruct Cos\u00b2Profile{T,IT,L} <: AbstractTemporalProfile\n    \u03c4::T\n    inv_\u03c4::IT\n    t\u2080::T\n    z\u2080::L\nend\n\nfunction Cos\u00b2Profile(;\u03c4, t\u2080=zero(\u03c4), z\u2080)\n    t\u2080, \u03c4 = promote(t\u2080, \u03c4)\n    Cos\u00b2Profile(\u03c4, inv(\u03c4), t\u2080, z\u2080)\nend\n\n@doc \"\"\"\n    QuasiRectangularProfile{V,T,L}\n\nThis envelope produces a pulse with a predominant constant part of width ``\u0394z``\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{\u03c6 + \u0394t/2}{\u03c4}\\\\right)^2\\\\right], & \\\\text{for } \u03c6 \u2264 \\\\frac{\u0394t}{2}\\\\\\\\\n    1\\\\,, & \\\\text{for } \\\\text{otherwise}\\\\\\\\\n    \\\\exp\\\\left[-\\\\left(\\\\frac{\u03c6 - \u0394t/2}{\u03c4}\\\\right)^2\\\\right], & \\\\ \u03c6 > \\\\frac{\u0394t}{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- `\u03c4` is the duration of the pulse (FWHM) and has the default value 18.02fs\n- `t\u2080` is the origin of the time axis and it is 0 by default\n- `z\u2080` is the initial position of the intensity peak and has the default value `-4*\u03c4*c`\n- `\u0394t` is the duration of the flat part of the profile and the default value `10*\u03c4`\n\"\"\"\nQuasiRectangularProfile\n\nstruct QuasiRectangularProfile{T,IT,L} <: AbstractTemporalProfile\n    inv_\u03c4::IT\n    t\u2080::T\n    z\u2080::L\n    \u0394t::T\nend\n\nfunction QuasiRectangularProfile(;\u03c4, t\u2080=zero(\u03c4), z\u2080, \u0394t=10\u03c4)\n    \u03c4, t\u2080, \u0394t = promote(\u03c4, t\u2080, \u0394t)\n    QuasiRectangularProfile(inv(\u03c4), t\u2080, z\u2080, \u0394t)\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 \u03c9 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- ``\u03c9`` 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    \u03c9 = immutable_cache(laser, :\u03c9)\n\n    exp(im*\u03c9*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_\u03c4, t\u2080, z\u2080 = profile\n    \u03c6 = (t - t\u2080) - (z - z\u2080) * inv_c\n\n    exp(-(\u03c6 * inv_\u03c4)^2)\nend\n\n@inline function envelope(profile::Cos\u00b2Profile, z, t; inv_c)\n    @unpack inv_\u03c4, \u03c4, t\u2080, z\u2080 = profile\n    \u03c6 = \u03c0*((t - t\u2080) - (z - z\u2080) * inv_c)\n\n    if abs(\u03c6) / \u03c0 < \u03c4 / 2\n        cos(-(\u03c6 * inv_\u03c4))^2\n    else\n        zero(t * inv_\u03c4)\n    end\nend\n\n@inline function envelope(profile::QuasiRectangularProfile, z, t; inv_c)\n    @unpack inv_\u03c4, t\u2080, z\u2080, \u0394t = profile\n    \u03c6 = (t - t\u2080/2) - (z - z\u2080/2) * inv_c\n\n    if \u03c6 < -\u0394t/2\n        exp(-((\u03c6 + \u0394t/2) * inv_\u03c4)^2)\n    elseif \u03c6 < \u0394t/2\n        one(\u03c6)\n    else\n        exp(-((\u03c6 - \u0394t/2) * inv_\u03c4)^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) \u2208 \u03a9:= (0,2)\u00d7(0,1)\n# Here a0(x,y)=-1, a1(x,y)=k^2, f(x,y)=0\n# with Neumann boundary conditions \u2202u/\u2202x(x,y)=cos(m\u03c0y) for x = 0 and\n# Robin boundary conditions \u2202u/\u2202x(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*\u03c0)^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*\u03c0*y)*(A[1]*exp(-im*kx*x)+A[2]*exp(im*kx*x))\nderiv_exact_sol(x,y) = [cos(m*\u03c0*y)*(A[1]*(-im)*kx*exp(-im*kx*x)+A[2]*im*kx*exp(im*kx*x)),\n                        -sin(m*\u03c0*y)*(m*\u03c0)*(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*\u03c0*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\u2212r)!), where r\u2264n, n!=n\u00d7(n\u22121)\u00d7...\u00d73\u00d72\u00d71, 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\u2264n\u2264100, 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 Test\n\n# Thin category\n###############\n\nx,y,z = Ob(FreeThinCategory, :x, :y, :z)\nf, g = Hom(:f, x, y), Hom(:g, y, z)\n@test dom(compose(f,g)) == x\n@test codom(compose(f,g)) == z\n\nx,y,z,zz = Ob(FreeThinSymmetricMonoidalCategory, :x, :y, :z, :zz)\nf, g, h= Hom(:f, x, y), Hom(:g, y, z), Hom(:h, otimes(y,y), z)\nj = Hom(:j, y\u2297z, zz)\n@test dom(compose(f,g)) == x\n@test codom(compose(f,g)) == z\n@test dom(otimes(f,g)) == otimes(x,y)\n@test codom(otimes(f,g)) == otimes(y,z)\n@test dom((f\u2297id(y))\u22c5h) == x\u2297y\n@test codom((f\u2297id(y))\u22c5h) == z\n@test dom((f\u2297g)\u22c5j) == x\u2297y\n@test codom((f\u2297g)\u22c5j) == zz\n\n# Preorder\n##########\n\nx,y,z = (El(FreePreorder.El, sym) for sym in (:x, :y, :z))\nf, g = Leq(:f, x, y), Leq(:g, y, z)\n@test lhs(reflexive(x)) == x\n@test rhs(reflexive(x)) == x\n@test lhs(transitive(f,g)) == x\n@test rhs(transitive(f,g)) == z\n", "meta": {"hexsha": "bbaea031a16fac99f9c76939f2effc529a46e5ef", "size": 825, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/theories/Preorders.jl", "max_stars_repo_name": "0x0f0f0f/Catlab.jl", "max_stars_repo_head_hexsha": "667014354ec3ab9fd60d6fcde19a6f907040bac5", "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": "test/theories/Preorders.jl", "max_issues_repo_name": "0x0f0f0f/Catlab.jl", "max_issues_repo_head_hexsha": "667014354ec3ab9fd60d6fcde19a6f907040bac5", "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": "test/theories/Preorders.jl", "max_forks_repo_name": "0x0f0f0f/Catlab.jl", "max_forks_repo_head_hexsha": "667014354ec3ab9fd60d6fcde19a6f907040bac5", "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": 25.78125, "max_line_length": 65, "alphanum_fraction": 0.5418181818, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7681553157928198}}
{"text": "using LinearAlgebra\r\n\r\n# coefficients from PD of \u03c0 functions\r\n\u03c0 = [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 = \u03c0\\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    \u222b_0^1 cosh(zt) / (4a^2/\u03b2^2 - t^2)^(n+3/2) dt\n    \u222b_0^1 sinh(zt) / (4a^2/\u03b2^2 - t^2)^(n+3/2) dt\n\nwhich is:\n\n    \u2211_{m=0}^\u221e C(-n-3/2, m) (-1)^m (\u03b2/2a)^{2n+2m+3} \u222b_0^1 cosh(zt) t^{2m} dt\n    \u2211_{m=0}^\u221e C(-n-3/2, m) (-1)^m (\u03b2/2a)^{2n+2m+3} \u222b_0^1 sinh(zt) t^{2m} dt.\n\nand also substitutes the integrals for:\n\n    \u222b_0^1 cosh(zt) t^{2m} dt = \u2211_{t=0}^\u221e z^{2t} / ((2t+2m+1)\u22c5(2t)!)\n    \u222b_0^1 sinh(zt) t^{2m} dt = \u2211_{t=0}^\u221e z^{2t+1} / ((2t+2m+2)\u22c5(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, \u03b2, 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    \u03b2 = ArbReal(\"$\u03b2\")\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(\u03b2 * arb_binomial(-n - 3/2, m; prec = p) * (-1)^m * (\u03b2 / (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            \u03b2 = ArbReal(\"$\u03b2\")\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# \u03b2 = ArbReal(\"2.0\")\n# \u03b1 = 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(\u03b2^2 / 4 + R * \u03b2 * coth(\u03b2 * v / 2)))\n# z = ArbReal(\"90.61\")\n# n = ArbReal(\"12.0\")\n# @time c = hypergeom_exp(z, n, \u03b2, 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": "using BenchmarkTools\n\n\n# random walk using Julia for loop\nfunction random_walk_for_loop(start, states, n)\n    for _ in 1:n\n        start *= states\n    return start\n    end\nend\n\n# random walk using matrix power\nfunction random_walk_matrix_power(start, states, n)\n    return start * states ^ n\nend\n\n# random walk until stationary state\n# this assumes that there exists a stationary state\nfunction get_stationary_state(start, states)\n    \u03c0 = start\n    prev = 0\n    n = 0\n    while \u03c0 != prev\n      prev = \u03c0\n      \u03c0 *= states\n      n += 1\n    end\n    return n, \u03c0\n  end\n\nfunction get_stationary_state2(start, states)\n    \u03c0 = start\n    prev = start\n    n = 1\n    while true\n        \u03c0 *= states\n        if \u03c0 != prev\n            prev = \u03c0\n        else\n            return n, \u03c0\n        end\n    n += 1\n    end\nend\n", "meta": {"hexsha": "12c8f60aaa5311afc135ef50f38c9005537332b9", "size": 801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/julia/random_walk.jl", "max_stars_repo_name": "lestherll/markov-chains", "max_stars_repo_head_hexsha": "295b932fe2f57898dcf80fdd636b1fb2b750ae85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-01T09:06:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T09:06:27.000Z", "max_issues_repo_path": "src/julia/random_walk.jl", "max_issues_repo_name": "lestherll/markov-chains", "max_issues_repo_head_hexsha": "295b932fe2f57898dcf80fdd636b1fb2b750ae85", "max_issues_repo_licenses": ["MIT"], "max_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/random_walk.jl", "max_forks_repo_name": "lestherll/markov-chains", "max_forks_repo_head_hexsha": "295b932fe2f57898dcf80fdd636b1fb2b750ae85", "max_forks_repo_licenses": ["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.8, "max_line_length": 51, "alphanum_fraction": 0.6029962547, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7681121646020016}}
{"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": "using Test, QBase\n\n@testset \"./src/constructors/brakets.jl\" begin\n\n@testset \"bloch_qubit_ket()\" begin\n    @testset \"complex bloch qubit\" begin\n        \u03c81 = bloch_qubit_ket(\u03c0/2,\u03c0/2)\n\n        @test \u03c81 isa Ket{Complex{Float64}}\n        @test \u03c81 \u2248 [1,im]/sqrt(2)\n\n        \u03c82 = bloch_qubit_ket(\u03c0/2,3\u03c0/2)\n\n        @test \u03c82 isa Ket{Complex{Float64}}\n        @test \u03c82 \u2248 [1,-im]/sqrt(2)\n\n        @test_throws DomainError bloch_qubit_ket(-0.1,\u03c0/2)\n        @test_throws DomainError bloch_qubit_ket(15\u03c0/7,\u03c0/2)\n        @test_throws DomainError bloch_qubit_ket(\u03c0/2,-0.1)\n        @test_throws DomainError bloch_qubit_ket(\u03c0/2,15\u03c0/7)\n    end\n\n    @testset \"real bloch qubit\" begin\n        \u03c81 = bloch_qubit_ket(\u03c0/2)\n\n        @test \u03c81 isa Ket{Float64}\n        @test \u03c81 \u2248 [1,1]/sqrt(2)\n\n        \u03c82 = bloch_qubit_ket(-\u03c0/2)\n\n        @test \u03c82 isa Ket{Float64}\n        @test \u03c82 \u2248 [1,-1]/sqrt(2)\n\n        @test_throws DomainError bloch_qubit_ket(-2\u03c0 - 0.1)\n        @test_throws DomainError bloch_qubit_ket(2\u03c0 + 0.1)\n    end\n\n    @testset \"equivalence between real and complex versions\" for \u03b8 in 0:0.2:2\u03c0\n        @test bloch_qubit_ket(\u03b8) \u2248 bloch_qubit_ket(\u03b8,0)\n        @test isapprox(bloch_qubit_ket(-\u03b8), bloch_qubit_ket(\u03b8,\u03c0), atol=1e-7)\n    end\nend\n\n@testset \"computational_basis_kets()\" begin\n    comp_basis_kets = computational_basis_kets(3)\n    @test comp_basis_kets isa Vector{Ket{Int64}}\n    @test comp_basis_kets == [[1,0,0],[0,1,0],[0,0,1]]\n    @test computational_basis_kets(8) == [\n        [1,0,0,0,0,0,0,0],[0,1,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0],\n        [0,0,0,0,1,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,1]\n    ]\nend\n\n@testset \"mirror_symmetric_qubit_kets()\" begin\n    @test mirror_symmetric_qubit_kets(0) isa Vector{Ket{Float64}}\n\n    @test isapprox(mirror_symmetric_qubit_kets(0), [[1,0],[1,0],[1,0]])\n    @test isapprox(mirror_symmetric_qubit_kets(\u03c0/4), [[1,0],[1,1]/sqrt(2),[1,-1]/sqrt(2)])\n    @test isapprox(mirror_symmetric_qubit_kets(\u03c0/3),[[1,0],[0.5,(sqrt(3)/2)],[0.5,-sqrt(3)/2]])\n    @test isapprox(mirror_symmetric_qubit_kets(\u03c0/2), [[1,0],[0,1],[0,-1]], atol=1e-16)\n\n    @test_throws DomainError mirror_symmetric_qubit_kets(-0.1)\n    @test_throws DomainError mirror_symmetric_qubit_kets(3\u03c0/5)\nend\n\n@testset \"planar_symmetric_qubit_kets()\" begin\n    @testset \"orthogonal qubits\" begin\n        kets = planar_symmetric_qubit_kets(2)\n        @test kets isa Vector{Ket{Float64}}\n        @test isapprox(kets, [[1,0],[0,1]], atol=1e-7)\n    end\n\n    @testset \"scanning over cases verifying right number are computed\" begin\n        for n in 2:100\n            kets = planar_symmetric_qubit_kets(n)\n\n            @test length(kets) == n\n            @test kets isa Vector{Ket{Float64}}\n        end\n    end\n\n    @test_throws(DomainError, planar_symmetric_qubit_kets(1))\nend\n\n@testset \"trine_qubit_kets()\" begin\n    trine_kets = trine_qubit_kets()\n    @test trine_kets isa Vector{Ket{Float64}}\n    @test isapprox(trine_kets, mirror_symmetric_qubit_kets(\u03c0/3), atol=1e-7)\n    @test isapprox(trine_kets, planar_symmetric_qubit_kets(3), atol=1e-7)\nend\n\n@testset \"sic_qubit_kets()\" begin\n    sic_kets = sic_qubit_kets()\n    @test sic_kets isa Vector{Ket{Complex{Float64}}}\n\n    \u03b8_sic = 2*acos(1/sqrt(3))\n\n    @test sic_kets[1] \u2248 bloch_qubit_ket(0, 0)\n    @test sic_kets[2] \u2248 bloch_qubit_ket(\u03b8_sic, 0)\n    @test sic_kets[3] \u2248 bloch_qubit_ket(\u03b8_sic, 2\u03c0/3)\n    @test sic_kets[4] \u2248 bloch_qubit_ket(\u03b8_sic, 4\u03c0/3)\nend\n\n@testset \"bb84_qubit_kets\" begin\n    bb84_kets = bb84_qubit_kets()\n    @test bb84_kets isa Vector{Ket{Float64}}\n    @test isapprox(bb84_kets, planar_symmetric_qubit_kets(4), atol=1e-7)\nend\n\n@testset \"bell_kets()\" begin\n    kets = bell_kets()\n    k0 = [1,0]\n    k1 = [0,1]\n\n    @test kets isa Vector{Ket{Float64}}\n    @test length(kets) == 4\n    @test kets[1] == 1/sqrt(2)*(kron(k0,k0)+kron(k1,k1))\n    @test kets[2] == 1/sqrt(2)*(kron(k0,k0)-kron(k1,k1))\n    @test kets[3] == 1/sqrt(2)*(kron(k0,k1)+kron(k1,k0))\n    @test kets[4] == 1/sqrt(2)*(kron(k0,k1)-kron(k1,k0))\nend\n\n@testset \"generalized_bell_kets()\" begin\n    @testset \"qubit bell states\" begin\n        kets = generalized_bell_kets(2)\n\n        @test kets isa Vector{Ket{Complex{Float64}}}\n        @test isapprox(kets, bell_kets(), atol=1e-7)\n    end\n\n    @testset \"qutrit bell states\" begin\n        kets = generalized_bell_kets(3)\n\n        basis = computational_basis_kets(3)\n        \u03c81 = (kron(basis[1],basis[1]) + kron(basis[2],basis[2]) + kron(basis[3],basis[3]))/sqrt(3)\n        \u03c82 = (kron(basis[1],basis[1]) + exp(im*2*\u03c0/3)*kron(basis[2],basis[2]) + exp(im*4*\u03c0/3)*kron(basis[3],basis[3]))/sqrt(3)\n        \u03c83 = (kron(basis[1],basis[1]) + exp(im*4*\u03c0/3)*kron(basis[2],basis[2]) + exp(im*2*\u03c0/3)*kron(basis[3],basis[3]))/sqrt(3)\n\n        \u03c84 = (kron(basis[1],basis[2]) + kron(basis[2],basis[3]) + kron(basis[3],basis[1]))/sqrt(3)\n        \u03c85 = (kron(basis[1],basis[2]) + exp(im*2*\u03c0/3)*kron(basis[2],basis[3]) + exp(im*4*\u03c0/3)*kron(basis[3],basis[1]))/sqrt(3)\n        \u03c86 = (kron(basis[1],basis[2]) + exp(im*4*\u03c0/3)*kron(basis[2],basis[3]) + exp(im*2*\u03c0/3)*kron(basis[3],basis[1]))/sqrt(3)\n\n        \u03c87 = (kron(basis[1],basis[3]) + kron(basis[2],basis[1]) + kron(basis[3],basis[2]))/sqrt(3)\n        \u03c88 = (kron(basis[1],basis[3]) + exp(im*2*\u03c0/3)*kron(basis[2],basis[1]) + exp(im*4*\u03c0/3)*kron(basis[3],basis[2]))/sqrt(3)\n        \u03c89 = (kron(basis[1],basis[3]) + exp(im*4*\u03c0/3)*kron(basis[2],basis[1]) + exp(im*2*\u03c0/3)*kron(basis[3],basis[2]))/sqrt(3)\n\n        \u03c8_match = [\u03c81,\u03c82,\u03c83,\u03c84,\u03c85,\u03c86,\u03c87,\u03c88,\u03c89]\n\n        @test kets isa Vector{Ket{Complex{Float64}}}\n        @test kets \u2248 \u03c8_match\n    end\nend\n\nend\n", "meta": {"hexsha": "02009f7322c94a57e615fab2da51c51994135ff6", "size": 5568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit/constructors/brakets.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": "test/unit/constructors/brakets.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": "test/unit/constructors/brakets.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": 35.9225806452, "max_line_length": 126, "alphanum_fraction": 0.6260775862, "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7681121555498709}}
{"text": "# elastic-net regularization\n\nexport ElasticNet\n\n\"\"\"\n**Elastic-net regularization**\n\n    ElasticNet(\u03bc=1.0, \u03bb=1.0)\n\nReturns the function\n```math\nf(x) = \u03bc\\\\|x\\\\|_1 + (\u03bb/2)\\\\|x\\\\|^2,\n```\nfor nonnegative parameters `\u03bc` and `\u03bb`.\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 `\u03bc` and `\u03bb` 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 \u21a6 \u03bc||x||_1 + (\u03bb/2)||x||\u00b2\"\nfun_params(f::ElasticNet) = \"\u03bc = $(f.mu), \u03bb = $(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": "function dermatrix(N :: Integer,a :: Number,b :: Number, order = 1)\n\tdermatrix(N+1, N, a, b, order)\nend\n\nfunction dermatrix(Nx :: Integer, Nz :: Integer, a :: Number, b :: Number, order :: Integer)\n\txi,wi = lgwt(Nx,a,b)\n\tif Nz > 1\n\t\tzi,wiz = lgwt(Nz,a,b)\n\telse\n\t\tzi,wiz = (a+b)/2, (b-a);\n\tend\n\tD = dermatrix(xi,zi,order)\n\treturn D,xi,zi\nend\n\nfunction dermatrix(xi :: Array, zi :: Number, order = 1)\n\tdermatrix(xi, [zi], order)\nend\n\nfunction dermatrix(xi :: Array,zi :: Array, order = 1)\n\tD = zeros(length(zi),length(xi))\n\tfor j = 1:length(xi)\n\t\tg = algo_diff(x-> leg_pol(x,xi[:],j), order)\n\t\tfor i = 1:length(zi)\t\t\n\t\t\tD[i,j] = g(zi[i])\n\t\tend\n\tend\n\tD\nend\n\nfunction algo_diff(func :: Function, order :: Integer)\n\tif order == 1\n\t\tg = x-> ForwardDiff.derivative(func,x)\n\t\treturn g\n\telseif order == 2\n\t\tg = x->ForwardDiff.hessian(func,x)\n\t\tg(x) = g([x])\n\t\treturn g\n\t\telse\n\t\t\tprintln(\"no more than 2nd order derivative yet\")\n\tend\nend\n\nfunction dermatrix2(N)\n\txi = cos(pi*(1:1:(N+2))/(N+3))\n\tzi = cos(pi*(1:1:(N))/(N+1))\n\tD = zeros(length(zi),length(xi))\n\tfor j = 1:length(xi)\n\t\tg = algo_diff(x-> leg_pol(x,xi,j),2)\n\t\tfor i = 1:length(zi)\t\t\n\t\t\tD[i,j] = g([zi[i]])\n\t\tend\n\tend\n\treturn D,xi,zi\nend\n", "meta": {"hexsha": "2792ed4655c53b54ef1e3dfb4e9d1da27f8c847c", "size": 1188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivative.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/derivative.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/derivative.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": 21.2142857143, "max_line_length": 92, "alphanum_fraction": 0.6043771044, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7680940599178345}}
{"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\u0304\" => 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": "function test_primes_iscoprime()\n    @test iscoprime(1, 3) == true\n    @test iscoprime(2, 3) == true\n    @test iscoprime(11*13*17, 13*17*19) == false\n    @test iscoprime(2*3, 5*7) == true\nend\n\nfunction test_primes_primes()\n    @test primes(10) == [2, 3, 5, 7]\n    @test primes(11) == [2, 3, 5, 7, 11]\n    @test primes(1, 1) == primes(1:1) == Int[]\n    @test primes(10, 10) == primes(10:10) == Int[]\n    @test primes(10, 20) == primes(10:20) == [11, 13, 17, 19]\n    @test primes(11, 19) == primes(11:19) == [11, 13, 17, 19]\n    @test primes(1000, 1100) == primes(1000:1100) == [1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097]\n    @test eltype(primes(10)) == typeof(2)\n    @test eltype(primes(10, 20)) == eltype(primes(10:20)) == typeof(11)\nend\n\nfunction test_primes_primesmask()\n    @test primesmask(100000) == primesmask(1:100000) == [isprime(i) for i in 1:100000]\n    @test primesmask(2:100000) == [isprime(i) for i in 2:100000]\n    @test primesmask(1000:100000) == [isprime(i) for i in 1000:100000]\n    @test primesmask(1009:100000) == [isprime(i) for i in 1009:100000]\n    @test typeof(primesmask(100000)) == typeof(primesmask(1:100000)) == BitVector\nend\n\nfunction test_primes_primepi()\n    @test primepi(10) == primepi(1:10) == primepi(2:10) == 4\n    @test primepi(11) == primepi(1:11) == primepi(2:11) == 5\n    @test primepi(10000) == primepi(1:10000) == primepi(2:10000) == 1229\n    @test primepi(10, 20) == primepi(10:20) == 4\n    @test primepi(11, 19) == primepi(11:19) == 4\nend\n\nfunction test_primes_nthprime()\n    p = primes(10000)\n    @test [nthprime(i) for i in 1:1000] == [p[i] for i in 1:1000]\n    @test [nthprime(a, a + 100) for a in 1:1000] ==  [nthprime(a:(a+100)) for a in 1:1000] == [p[a:(a+100)] for a in 1:1000]\n    @test typeof(nthprime(100)) == eltype(nthprime(1, 100)) == eltype(nthprime(1:100)) == typeof(100)\nend\n\nfunction test_primes_nextprime()\n    p = primes(2000)\n    @test [nextprime(i) for i in -1:1000] == [first(dropwhile(p -> p <= i, p)) for i in -1:1000]\n    @test typeof(nextprime(3)) == typeof(3)\n    @test typeof(nextprime(big(3))) == typeof(big(3))\nend\n\nfunction test_primes_prevprime()\n    @test prevprime(0) == 0\n    @test prevprime(2) == 0\n    p = reverse(primes(2000))\n    @test [prevprime(i) for i in 3:1000] == [first(dropwhile(p -> p >= i, p)) for i in 3:1000]\n    @test typeof(prevprime(3)) == typeof(3)\n    @test typeof(prevprime(big(3))) == typeof(big(3))\nend\n\nfunction test_primes_twinprimes()\n    @test twinprimes(1000, 1050) == twinprimes(1000:1050) == [1019 1021; 1031 1033]\n    @test length(twinprimes(20, 30)) == 0\nend\n\nfunction test_primes_all()\n    label = \"Math.NumberTheory.Primes...\"\n    print(rpad(label, 50, ' '))\n\n    test_primes_iscoprime()\n    test_primes_primes()\n    test_primes_primesmask()\n    test_primes_primepi()\n    test_primes_nthprime()\n    test_primes_nextprime()\n    test_primes_prevprime()\n    test_primes_twinprimes()\n\n    println(\"PASS\")\nend\n", "meta": {"hexsha": "7e3bdfe6eec922693d800d08b7acf57420571f37", "size": 2971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 37.6075949367, "max_line_length": 149, "alphanum_fraction": 0.6300908785, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7680940514316739}}
{"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 Random, Distributions, JLD2, CSV, DataFrames,LinearAlgebra,Statistics,FreqTables,TexTables\r\n#TexTables wasn't in the instructions but I think it is needed for freqtable\r\n#q1,q2,q3 should run before declaration of q4 since q3 generates \"nlsw88.jld\"\r\n\r\nRandom.seed!(1234)\r\n#Question 1\r\nfunction q1()\r\n    Random.seed!(1234)\r\n    \r\n    #1.a\r\n    #1.a.i\r\n    A=rand(Uniform(-5,10),(10,7))\r\n    \r\n    #1.a.ii\r\n    B=rand(Normal(-2,15),(10,7))\r\n    #1.a.iii\r\n    C= [A[1:5,1:5] B[1:5,6:7]]\r\n    #1.a.iv\r\n    D=(A.<=0).*A\r\n    \r\n    #1.b\r\n    length(A)\r\n    #1.c\r\n    unique(D)\r\n    #1.d\r\n    E=reshape(B,70,1)\r\n    E=vec(B)\r\n    #1.e\r\n    F=cat(A, B;dims=3)\r\n    #1.f\r\n    F=permutedims(F,(3,1,2))\r\n    #1.g\r\n    G=kron(B,C)\r\n    #kron(C,F) is not possible F is not vectorized properly. \r\n    #1.h\r\n    JLD2.@save \"matrixpractice.jld2\" A B C D E F G\r\n    #1.i\r\n    JLD2.@save \"firstmatrix.jld2\" A B C D\r\n    #1.j\r\n    df=DataFrame(C)\r\n    CSV.write(\"Cmatrix.csv\",df)\r\n    #1.k\r\n    dfD=DataFrame(D)\r\n    CSV.write(\"Dmatrix.dat\",df,delim='\\t')\r\n    return A,B,C,D\r\nend \r\n\r\n\r\n\r\n#Question 2\r\nfunction q2(a,b,c)\r\n    #2.a\r\n    n=length(A)\r\n    AB=zeros(size(A))\r\n    \r\n    for i=1:n\r\n        AB[i]=A[i]*B[i]\r\n    end\r\n    AB2=A.*B\r\n\r\n    #2.b\r\n    n=length(C)\r\n    Cprime=[]\r\n    for i=1:n\r\n        if -5<=C[i]<=5\r\n            append!(Cprime,C[i])\r\n        end\r\n    end\r\n\r\n    Cprime2=[x for x in C if -5<=x<=5]\r\n    \r\n    #2.c\r\n    X=permutedims(\r\n    cat(ones(15169,5),  \r\n    [rand(Bernoulli(.75*(6-y)/5)) for x in 1:15169,y in 1:5], \r\n    [rand(Normal(15+y-1,5(y-1))) for x in 1:15169,y in 1:5],\r\n    [rand(Normal(\u03c0*(6-y)/3,1/\u212f)) for x in 1:15169,y in 1:5],\r\n    rand(Binomial(20,0.6),15169,5),\r\n    rand(Binomial(20,0.5),15169,5);\r\n    dims=3),(1,3,2))\r\n    \r\n    #2.d\r\n    \u03b2=hcat([[1+.25*(t-1), log(t), -sqrt(t), \u212f^t-\u212f^(t+1), t, t/3] for t in 1:5]...) \r\n    \r\n    #2.e\r\n    Y=hcat([X[:,:,i]*\u03b2[:,i].+rand(Normal(0,.36)) for i in 1:5]...)\r\n    return\r\nend\r\n\r\n\r\n#Question 3\r\nfunction q3()\r\n    #3.a\r\n    #workspace() not supported on my version anymore\r\n    df=CSV.read(\"nlsw88.csv\"; header=true,missingstring=\"\")\r\n    JLD2.@save \"nlsw88.jld\" df\r\n\r\n    #3.b\r\n    describe(df)\r\n    # the mean of neve_married is 0.104185 and married is {0,1}. so 10.4185% are never_married.\r\n\r\n    #3.c\r\n    tabulate(df,:race)\r\n    #I think taubulate is in TexTables package but it wasn't listed in the required package list.\r\n\r\n    #3.d\r\n    summary_df=describe(df, :mean, :median, :std, :min, :max, :nunique, :q75, :q25)\r\n    summary_df[!, :intq] = summary_df[:, :q75] - summary_df[:, :q25]\r\n    summarystats=Matrix(summary_df[:,Not([:variable,:q25,:q75])])\r\n    #from 3.b there are two observations missing.\r\n\r\n    #3.e\r\n    freqtable(df[:,:industry],df[:,:occupation])\r\n\r\n    #3.f\r\n    df_f=df[:,[:industry, :occupation , :wage]]\r\n    gdf=groupby(df_f,[:industry, :occupation])\r\n    gdf=combine(gdf, valuecols(gdf) .=> mean)\r\n    freqtable(gdf,:wage_mean,:industry,:occupation);\r\n    return\r\nend\r\n\r\nA,B,C,D=q1()\r\nq2(A,B,C)\r\nq3()\r\n\r\n\r\n\r\n\r\n#Question4\r\nfunction q4()\r\n    #4.a\r\n    JLD2.@load \"firstmatrix.jld2\" A B C D\r\n    \r\n    #4.b 4.c 4.e\r\n    function matrixops(a,b)\r\n        #calculate dot product, product and sum of elements for inputs.\r\n        if size(a)==size(b)    \r\n            dProduct=a.*b\r\n            product=a'*b\r\n            sprod=sum(a+b)\r\n            return dProduct, product,sprod\r\n        else\r\n            println(\"inputs must have the same size.\")\r\n        end\r\n    end\r\n    #4.d\r\n    matrixops(A,B)\r\n    #4.f\r\n    matrixops(C,D)\r\n    #4.g\r\n    JLD2.@load \"nlsw88.jld\"\r\n    matrixops(convert(Array,df.ttl_exp),convert(Array,df.wage));\r\nend\r\n    \r\n\r\nq4()", "meta": {"hexsha": "40656a6126a0d25eb5000a368a59d0937597e928", "size": 3661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS1-julia-intro/PS1.jl", "max_stars_repo_name": "kasrakhadem/fall-2020", "max_stars_repo_head_hexsha": "83bd3126db778a1d66a5d2f43c642a4e2b994df7", "max_stars_repo_licenses": ["MIT"], "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/PS1.jl", "max_issues_repo_name": "kasrakhadem/fall-2020", "max_issues_repo_head_hexsha": "83bd3126db778a1d66a5d2f43c642a4e2b994df7", "max_issues_repo_licenses": ["MIT"], "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/PS1.jl", "max_forks_repo_name": "kasrakhadem/fall-2020", "max_forks_repo_head_hexsha": "83bd3126db778a1d66a5d2f43c642a4e2b994df7", "max_forks_repo_licenses": ["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.3184713376, "max_line_length": 98, "alphanum_fraction": 0.5372848948, "num_tokens": 1301, "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 \u2248 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 \u2248 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                         \u03f5       :: Real=\u221aeps(eltype(x)),\n                         #\u03f5       :: 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=>\"\u2016\u2207f\u2016\", :slope=>\"\u2207f\u1d40d\"))\n    f  ::T = obj(nlp,x)\n    \u2207f :: Vector{T} = grad(nlp, x)\n    \n    \u03c4\u2080 = 0.0005\n    \u03c4\u2081 = 0.999\n\n    iter = 0\n    @info log_row(Any[iter, f, norm(\u2207f, Lp)])  \n\n    while (norm(\u2207f, Lp) > \u03f5) && (iter <= maxiter)\n        H = Matrix(Symmetric(hess(nlp, x),:L))\n        \u0394, O = eigen(H)\n        # Boost negative values of \u0394 to 1e-8\n        # devise an adaptative value for \u03b3\n        \u03b3 = 1e-6\n        D = abs.(\u0394) + max.((\u03b3 .- abs.(\u0394)), 0.0) .*ones(n)\n        \n        d = - O*diagm(1.0 ./ D)*O'*\u2207f\n\n        #------------------------------------------\n        # Hard coded line search\n        hp0 = \u2207f'*d\n        t=1.0\n        # Simple Wolfe forward tracking\n        xt = x + t*d\n        \u2207ft = grad(nlp,xt)\n        hp = \u2207ft'*d\n        ft = obj(nlp, xt)\n        #  while  ~wolfe & armijo\n        nbW = 0\n        while (hp <= \u03c4\u2081 * hp0) && (ft <= ( f + \u03c4\u2080*t*hp0)) && (nbW < 10)\n            t *= 5\n            xt = x + t*d\n            \u2207ft = grad(nlp,xt)\n            hp = \u2207ft'*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 + \u03c4\u2080*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   \u2207ft = grad(nlp, xt) end\n        \u2207f = \u2207ft\n        iter += 1\n        \n        @info log_row(Any[iter, f, norm(\u2207f, Lp), t, hp0])\n    end\n    if iter > maxiter @warn \"Maximum d'it\u00e9rations\"\n    end\n    \n    return iter, f, norm(\u2207f, 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]/\u221a(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]/\u221a(A[1,1]*A[2,2])\nz0 = atanh(r0)\nhistogram(Z; norm=true, alpha=0.3, bin=200)\nplot!(Normal(z0, 1/\u221a(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/\u221a2\nz0 = atanh(r0)\nhistogram(Z; norm=true, alpha=0.3, bin=200)\nplot!(Normal(z0, 1/\u221a(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/\u221a2\nz0 = atanh(r0)\nhistogram(Z; norm=true, alpha=0.3, bin=200)\nplot!(Normal(z0, 1/\u221a(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/\u221a2\n    z0 = atanh(r0)\n    histogram(Z; norm=true, alpha=0.3, bin=200)\n    plot!(Normal(z0, 1/\u221a(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*\u03c0) + 1\n\n# that looks close to zero but\n\nx \u2248 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 Manopt, Manifolds, Test\n@testset \"Alternating Gradient Descent\" begin\n    # Note that this is mereely an alternating gradient descent toy example\n    M = Sphere(2)\n    N = M \u00d7 M\n    data = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]\n    function F(N, x)\n        return 1 / 2 *\n               (distance(N[1], x[N, 1], data[1])^2 + distance(N[2], x[N, 2], data[2])^2)\n    end\n    gradF1(N, x) = -log(N[1], x[N, 1], data[1])\n    gradF1!(N, Y, x) = (Y .= -log(N[1], x[N, 1], data[1]))\n    gradF2(N, x) = -log(N[2], x[N, 2], data[2])\n    gradF2!(N, Y, x) = (Y .= -log(N[2], x[N, 2], data[2]))\n    gradF(N, x) = ProductRepr([-log(N[i], x[N, i], data[i]) for i in [1, 2]]...)\n    function gradF!(N, Y, x)\n        log!(N[1], Y[N, 1], x[N, 1], data[1])\n        log!(N[2], Y[N, 2], x[N, 2], data[2])\n        return Y .*= -1\n    end\n    x = ProductRepr([0.0, 0.0, 1.0], [0.0, 0.0, 1.0])\n\n    @testset \"Test gradient access\" begin\n        Pf = AlternatingGradientProblem(N, F, gradF)\n        Pv = AlternatingGradientProblem(N, F, [gradF1, gradF2])\n        Pf! = AlternatingGradientProblem(N, F, gradF!; evaluation=MutatingEvaluation())\n        Pv! = AlternatingGradientProblem(\n            N, F, [gradF1!, gradF2!]; evaluation=MutatingEvaluation()\n        )\n        for P in [Pf, Pv, Pf!, Pv!]\n            Y = zero_vector(N, x)\n            @test get_gradient(P, x)[N, 1] == gradF(N, x)[N, 1]\n            @test get_gradient(P, x)[N, 2] == gradF(N, x)[N, 2]\n            get_gradient!(P, Y, x)\n            @test Y[N, 1] == gradF(N, x)[N, 1]\n            @test Y[N, 2] == gradF(N, x)[N, 2]\n            @test get_gradient(P, 1, x) == gradF(N, x)[N, 1]\n            @test get_gradient(P, 2, x) == gradF(N, x)[N, 2]\n            Y = zero_vector(N, x)\n            get_gradient!(P, Y[N, 1], 1, x)\n            @test Y[N, 1] == gradF(N, x)[N, 1]\n            get_gradient!(P, Y[N, 2], 2, x)\n            @test Y[N, 2] == gradF(N, x)[N, 2]\n        end\n    end\n    @testset \"Test high level interface\" begin\n        y2 = allocate(x)\n        copyto!(N, y2, x)\n        y3 = allocate(x)\n        copyto!(N, y3, x)\n        y = alternating_gradient_descent(\n            N, F, [gradF1!, gradF2!], x; order_type=:Linear, evaluation=MutatingEvaluation()\n        )\n        alternating_gradient_descent!(\n            N,\n            F,\n            [gradF1!, gradF2!],\n            y2;\n            order_type=:Linear,\n            evaluation=MutatingEvaluation(),\n        )\n        @test isapprox(N, y, y2)\n        o = alternating_gradient_descent!(\n            N,\n            F,\n            [gradF1!, gradF2!],\n            y3;\n            evaluation=MutatingEvaluation(),\n            order_type=:Linear,\n            return_options=true,\n        )\n        @test isapprox(N, y, o.x; atol=10^-3)\n    end\nend\n", "meta": {"hexsha": "e410dc28dc4223397eb336a506552cd1487af4a6", "size": 2758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/solvers/test_alternating_gradient.jl", "max_stars_repo_name": "kellertuer/ManifoldValuedImageProcessing.jl", "max_stars_repo_head_hexsha": "e7725773ffc97dcf9276649223ee9d17dbc936bb", "max_stars_repo_licenses": ["MIT"], "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/solvers/test_alternating_gradient.jl", "max_issues_repo_name": "kellertuer/ManifoldValuedImageProcessing.jl", "max_issues_repo_head_hexsha": "e7725773ffc97dcf9276649223ee9d17dbc936bb", "max_issues_repo_licenses": ["MIT"], "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/solvers/test_alternating_gradient.jl", "max_forks_repo_name": "kellertuer/ManifoldValuedImageProcessing.jl", "max_forks_repo_head_hexsha": "e7725773ffc97dcf9276649223ee9d17dbc936bb", "max_forks_repo_licenses": ["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.7733333333, "max_line_length": 92, "alphanum_fraction": 0.4854967368, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275046683696, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7679890647853258}}
{"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, \u00a3, and pence, p, and there are eight coins in general circulation:\n\n1p, 2p, 5p, 10p, 20p, 50p, \u00a31 (100p) and \u00a32 (200p).\nIt is possible to make \u00a32 in the following way:\n\n1\u00d7\u00a31 + 1\u00d750p + 2\u00d720p + 1\u00d75p + 1\u00d72p + 3\u00d71p\nHow many different ways can \u00a32 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\u2081 = 5.730\n\n#Setup\nu\u2080 = 1.0\ntspan = (0.0, 1.0)\n\n#Define the problem\nradioactivedecay(u,p,t) = -C\u2081*u\n\n#Pass to solver\nprob = ODEProblem(radioactivedecay,u\u2080,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\u2081*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    \u03c3   = p.\u03c3\n    r0  = p.r0\n    \u03c9   = p.\u03c9\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    \u03c8_matrix = zeros( Nx , Ny )\n    d\u03c8_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        \u03b8   = atan(y[j] , x[i])\n    \n        \u03c8_matrix[i,j] = A0*cos( m*\u03b8 ) * sin( \u03c9*r ) * exp( - 0.5* ( (r-r0)/ \u03c3)^2 )\n        d\u03c8_matrix[i,j] = A0*cos( m*\u03b8 ) * exp( - 0.5* ( (r-r0)/ \u03c3)^2 ) * ( \u03c9*cos(\u03c9*r) - (r-r0)*sin(\u03c9*r)/\u03c3^2  )\n\n    end\n    \n    \u03c8  = reshape(\u03c8_matrix , Nx*Ny)\n    d\u03c8 = reshape(d\u03c8_matrix , Nx*Ny)\n\n    #Return initial state\n    return \u03c8 , d\u03c8\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 \u2212 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    \u03c1::Float64 = 5.42\n    \u03c3::Float64 = 26.72\n    a::Float64 = 26.72\n    T::Float64 = 100\nend\n\nfunction (m::ArbitrageHoldingCosts)(state::NamedTuple, y::NamedTuple, \u03c4::Number)\n    (; c, r, \u03c1, \u03c3, a, T) = m\n    (; z) = state\n    (; F, Fz_up, Fz_down, Fzz) = y\n    Fz = (z >= 0) ? Fz_up : Fz_down\n    \u03d5 = z * (1 + z^2)^(-1/2)\n    \u03d5z = (1 + z^2)^(-3/2)\n    \u03d5zz = - 3 * z * (1 + z^2)^(-5/2)\n    s\u03c4 = c / r * (1 - exp(- r * (T - \u03c4)))\n    \u03bcL = \u03c1 * z - 0.5 * \u03c3^2 * \u03d5zz / \u03d5z + c / s\u03c4 * (\u03d5 - 1) / \u03d5z\n    iL = 1 / a * (\u03bcL / \u03c3^2 + Fz)\n    \u03bcS = \u03c1 * z - 0.5 * \u03c3^2 * \u03d5zz / \u03d5z + c / s\u03c4 * (\u03d5 + 1) / \u03d5z\n    iS = 1 / a * (\u03bcS / \u03c3^2 + Fz)\n    \u03bc, i  = 0.0, 0.0\n    if iL > 0\n        i = iL\n        \u03bc = \u03bcL\n    elseif iS < 0\n        i = iS\n        \u03bc = \u03bcS\n    end\n    Ft = - ((\u03bc + \u03c3^2 * Fz) * a * i - 0.5 * \u03c3^2 * (a * i)^2 - \u03c1 * z * Fz + 0.5 * \u03c3^2 * (Fzz - Fz^2))\n    return (; Ft)\nend\n\nm = ArbitrageHoldingCosts()\nzn = 200\nd = Normal(0, sqrt(m.\u03c3^2 / (2 * m.\u03c1)))\nstategrid = OrderedDict(:z => range(quantile(d, 0.00001), quantile(d, 0.99999), length = zn))\nyend = OrderedDict(:F => zeros(zn))\n\u03c4s = range(0, m.T, length = 100)\nresult = pdesolve(m, stategrid, yend, \u03c4s)\nresidual_norm = maximum(result.residual_norm)\n\n### reproduce Fig 2\n#d = Normal(0, sqrt(m.\u03c3^2 / (2 * m.\u03c1)))\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\u20d7\u2081, x\u20d7\u2082, and x\u20d7\u2083.\n# The assumed relation of the points may be seen in the diagram below.\n#                 ___x\u20d7\u2083___\n#            ____/        \\____\n#        ___/                  \\\n#     __/                       x\u20d7\u2082\n#   _/\n#  /\n# x\u20d7\u2081\n#\n# NOTE: x\u20d7\u2083 is between x\u20d7\u2081 and x\u20d7\u2082, but not necessarily the midpoint.\n# q(r) = (2r-1)(r-1)x\u20d7\u2081 + r(2r-1)x\u20d7\u2082 + 4r(1-r)x\u20d7\u2083\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\u2081::Point_3D{T},\n                    p\u2082::Point_3D{T},\n                    p\u2083::Point_3D{T}) where {T <: AbstractFloat} = QuadraticSegment_3D((p\u2081, p\u2082, p\u2083))\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\u209c = T(r)\n    return (2r\u209c-1)*(r\u209c-1)*q.points[1] + r\u209c*(2r\u209c-1)*q.points[2] + 4r\u209c*(1-r\u209c)*q.points[3]\nend\n\n#function derivative(q::QuadraticSegment_3D{T}, r::R) where {T <: AbstractFloat, R <: Real}\n#    # dq\u20d7/dr\n#    r\u209c = T(r)\n#    return (4r\u209c - 3)*q.points[1] + (4r\u209c - 1)*q.points[2] + (4 - 8r\u209c)*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 = \u222b ||q\u20d7'(r)||dr  \u2248   \u2211 w\u1d62||q\u20d7'(r\u1d62)||\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\u20d7\u2081 + r(2r-1)x\u20d7\u2082 + 4r(1-r)x\u20d7\u2083\n#    # q(r) = 2r\u00b2(x\u20d7\u2081 + x\u20d7\u2082 - 2x\u20d7\u2083) + r(-3x\u20d7\u2081 - x\u20d7\u2082 + 4x\u20d7\u2083) + x\u20d7\u2081\n#    # Let D\u20d7 = 2(x\u20d7\u2081 + x\u20d7\u2082 - 2x\u20d7\u2083), E\u20d7 = (-3x\u20d7\u2081 - x\u20d7\u2082 + 4x\u20d7\u2083), F\u20d7 = x\u2081\n#    # q(r) = r\u00b2D\u20d7 + rE\u20d7 + F\u20d7\n#    # l(s) = x\u20d7\u2084 + sw\u20d7\n#    # If D\u20d7 \u00d7 w\u20d7 \u2260 0\u20d7\n#    #   x\u20d7\u2084 + sw\u20d7 = r\u00b2D\u20d7 + rE\u20d7 + F\u20d7\n#    #   sw\u20d7 = r\u00b2D\u20d7 + rE\u20d7 + (F\u20d7 - x\u20d7\u2084)\n#    #   0\u20d7 = r\u00b2(D\u20d7 \u00d7 w\u20d7) + r(E\u20d7 \u00d7 w\u20d7) + (F\u20d7 - x\u20d7\u2084) \u00d7 w\u20d7\n#    #   Let A\u20d7 = (D\u20d7 \u00d7 w\u20d7), B\u20d7 = (E\u20d7 \u00d7 w\u20d7), C\u20d7 = (F\u20d7 - x\u20d7\u2084) \u00d7 w\u20d7\n#    #   0\u20d7 = r\u00b2A\u20d7 + rB\u20d7 + C\u20d7\n#    #   0 = (A\u20d7 \u22c5 A\u20d7)r\u00b2 + (B\u20d7 \u22c5 A\u20d7)r + (C\u20d7 \u22c5 A\u20d7)\n#    #   A = (A\u20d7 \u22c5 A\u20d7), B = (B\u20d7 \u22c5 A\u20d7), C = (C\u20d7 \u22c5 A\u20d7)\n#    #   0 = Ar\u00b2 + Br + C\n#    #   r = (-B - \u221a(B\u00b2-4AC))/2A, -B + \u221a(B\u00b2-4AC))/2A)\n#    #   s = ((q(r) - p\u2084)\u22c5w\u20d7/(w\u20d7 \u22c5 w\u20d7)\n#    #   r is invalid if:\n#    #     1) A = 0\n#    #     2) B\u00b2 < 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\u20d7 \u00d7 w\u20d7 = 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\u20d7 = 2*(q.points[1] + q.points[2] - 2*q.points[3])\n#    E\u20d7 = 4*q.points[3] - 3*q.points[1] - q.points[2]\n#    w\u20d7 = l.points[2] - l.points[1]\n#    A\u20d7 = D\u20d7 \u00d7 w\u20d7\n#    B\u20d7 = E\u20d7 \u00d7 w\u20d7\n#    C\u20d7 = (q.points[1] - l.points[1]) \u00d7 w\u20d7\n#    A = A\u20d7 \u22c5 A\u20d7\n#    B = B\u20d7 \u22c5 A\u20d7\n#    C = C\u20d7 \u22c5 A\u20d7\n#    if abs(A) < 1.0e-6\n#        # Line intersection\n#        r = (-C\u20d7 \u22c5 B\u20d7)/(B\u20d7 \u22c5 B\u20d7)\n#        s = (q(r)- l.points[1]) \u22c5 w\u20d7/(w\u20d7 \u22c5 w\u20d7)\n#        points[1] = q(r)\n#        if (0 \u2264 s \u2264 1) && (0 \u2264 r \u2264 1)\n#            bool = true\n#            npoints = 1\n#        end\n#    elseif B^2 \u2265 4A*C\n#        # Quadratic intersection\n#        r\u2081 = (-B - \u221a(B^2-4A*C))/2A\n#        r\u2082 = (-B + \u221a(B^2-4A*C))/2A\n#        points[1] = q(r\u2081)\n#        points[2] = q(r\u2082)\n#        s\u2081 = (points[1] - l.points[1]) \u22c5 w\u20d7/(w\u20d7 \u22c5 w\u20d7)\n#        s\u2082 = (points[2] - l.points[1]) \u22c5 w\u20d7/(w\u20d7 \u22c5 w\u20d7)\n#\n#        # Check points to see if they are valid intersections.\n#        # First r,s valid?\n#        if (0 \u2264 r\u2081 \u2264 1) && (0 \u2264 s\u2081 \u2264 1) && (points[1] \u2248 l(s\u2081))\n#            npoints += 1\n#        end\n#        # Second r,s valid?\n#        if (0 \u2264 r\u2082 \u2264 1) && (0 \u2264 s\u2082 \u2264 1) && (points[2] \u2248 l(s\u2082))\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": "# Sudoku Solver using backtracking\n\n\nfunction ispossible(m::Array{Int, 4}, i::CartesianIndex{4}, n)\n    return !( \n        n \u2208 m[  : ,   : , i[3], i[4]] || # column\n        n \u2208 m[i[1], i[2],   : ,   : ] || # line\n        n \u2208 m[  : , i[2],   : , i[4]]    # cell\n    )\nend\n\n\nfunction sudokusolve!(::Array{Int, 4}, ::Nothing)\n    # after `CartesianIndex(3,3,3,3)`, `iterate` returns `nothing`\n    return true\nend\n\nfunction sudokusolve!(m::Array{Int, 4}, t::Tuple)\n    return sudokusolve!(m, t[1])\nend\n\nfunction sudokusolve!(m::Array{Int, 4}, index::CartesianIndex{4})\n    next_index = iterate(CartesianIndices(m), index)\n\n    if m[index] != 0\n        return sudokusolve!(m, next_index)\n    end\n\n    for n in 1:9\n        if ispossible(m, index, n)\n            m[index] = n\n            if sudokusolve!(m, next_index)\n                return true\n            end\n        end\n    end\n\n    m[index] = 0\n    return false\nend\n\nfunction sudokusolve!(m::Array{Int, 2})\n    sudokusolve!(reshape(m, 3, 3, 3, 3), CartesianIndex(1,1,1,1)) # reshape for easier manipulation\nend\n\nfunction string2matrix(s::String)\n    return permutedims(reshape(parse.(Int, split(s, \"\")), 9, 9))\nend\n\n\n\nm = string2matrix(\"004300209005009001070060043006002087190007400050083000600000105003508690042910300\")\n\nprintln(\"\\nOriginal :\")\nshow(stdout, MIME(\"text/plain\"), m)\n\nsudokusolve!(m)\n\nprintln(\"\\n\\nSolved :\")\nshow(stdout, MIME(\"text/plain\"), m)", "meta": {"hexsha": "1cee4c5eb4e6f76dae1e2afad8ff57e663480bbe", "size": 1408, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algorithms/backtracking/sudoku-solve.jl", "max_stars_repo_name": "ravibitsgoa/julia-1", "max_stars_repo_head_hexsha": "93c9243cdf1417f098b9ca251b3271363f47b98c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-10-08T05:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T09:27:27.000Z", "max_issues_repo_path": "algorithms/backtracking/sudoku-solve.jl", "max_issues_repo_name": "ravibitsgoa/julia-1", "max_issues_repo_head_hexsha": "93c9243cdf1417f098b9ca251b3271363f47b98c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-08T05:44:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T15:33:02.000Z", "max_forks_repo_path": "algorithms/backtracking/sudoku-solve.jl", "max_forks_repo_name": "ravibitsgoa/julia-1", "max_forks_repo_head_hexsha": "93c9243cdf1417f098b9ca251b3271363f47b98c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-10-26T18:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:27:30.000Z", "avg_line_length": 23.4666666667, "max_line_length": 102, "alphanum_fraction": 0.6029829545, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7679553719620961}}
{"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    \u03ba(x,y) = exp(-\u2016x-y\u2016\u00b2/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\u0304 is short for \u2202l / \u2202r\n    function gaussiankernel_pullback(r\u0304)\n        m = r .* r\u0304 # pullback the exponential\n        u\u0304 = v * m'\n        u\u0304 .-= sum(m', dims=1) .* u\n        v\u0304 = u * m\n        v\u0304 .-= sum(m, dims=1) .* v\n        return NO_FIELDS, u\u0304, v\u0304\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), \u221e ). 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": "using GraphPCA\nusing Base.Test\n\n# X matrix\nX1 = 10*randn(20,4)\nX2 = X1 + randn(20,4)\nX = [X1 X2]\n\n#Construct the Laplacian matrix\nL = eye(8)\nfor i in 1:4\n  j = i + 4\n  L[i,j] = -1\n  L[j,i] = -1\nend\n\n\u03bb = eigmax(Symmetric(X'*X))\n\u03b7 = eigmax(Symmetric(L))\neet = ones(8,8)\nn = 8\n\n#Pure PCA\nXtX = Symmetric(I - X'*X/\u03bb)\nDpca,Vpca = eig(XtX, 1:4)\nQpca = Vpca\nUpca = X*Qpca\nXpca = Upca*Qpca'\n\n#Pure Laplacian Embedding\nLn = Symmetric(L/\u03b7)\nDn, Vn = eig(Ln, 1:4)\nQlap = Vn\nUlap = X*Qlap\nXlap = Ulap*Qlap'\n\n#Laplacian Embedding with Offset\n# Lnp = Symmetric(L/\u03b7 + eet/n)\n# Dnp,Vnp = eig(Lnp, 1:4)\n# Qlapp = Vnp\n# Ulapp = X*Qlapp\n# Xlapp = Ulapp*Qlapp'\n\nGLPCA0 = GLPCA(X, 0, L, 4)\nGLPCA1 = GLPCA(X, 1, L, 4)\n@test GLPCA1.U*GLPCA1.Q' \u2248 Xlap\n@test GLPCA0.U*GLPCA0.Q' \u2248 Xpca\n", "meta": {"hexsha": "0c7764289544fa18a841b73fc708809b1311e43d", "size": 759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "mihirparadkar/GraphPCA", "max_stars_repo_head_hexsha": "1b5a7e67b4f5f75a6b83d60b860d6a2a47909f40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-29T01:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T17:15:21.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "mihirparadkar/GraphPCA", "max_issues_repo_head_hexsha": "1b5a7e67b4f5f75a6b83d60b860d6a2a47909f40", "max_issues_repo_licenses": ["MIT"], "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": "mihirparadkar/GraphPCA", "max_forks_repo_head_hexsha": "1b5a7e67b4f5f75a6b83d60b860d6a2a47909f40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-28T10:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T10:44:47.000Z", "avg_line_length": 16.1489361702, "max_line_length": 32, "alphanum_fraction": 0.6205533597, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7679415547994183}}
{"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- `\u03f5::T`: the minimum step length decrease from the initial step length\n\"\"\"\nstruct InterpolationLineSearch{C, T}\n    c::C\n    \u03f5::T\n\n    function InterpolationLineSearch(c, \u03f5)\n        0 < c < 1 || error(\"`c` must be in the open interval (0, 1)\")\n        return new{typeof(c), typeof(\u03f5)}(c, \u03f5)\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- `\u03f5=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, \u03b1\u2080::T) where {T}\n    x = state.x\n    \u03d5\u2080 = state.f\n    \u2207y = state.\u2207f\n    d\u03d5\u2080 = \u2207y\u22c5p\n    \u03b1\u2096 = \u03b1\u2080\n    c = ils.c\n    \u03f5 = ils.\u03f5\n    \u03d5(\u03b1) = f(x + \u03b1 * p)\n    \u03d5\u03b1\u2096 = \u03d5(\u03b1\u2096)\n    \u03b1\u2096\u208a\u2081 = T(-(d\u03d5\u2080 * \u03b1\u2096^2) / (2 * (\u03d5\u03b1\u2096 - \u03d5\u2080 - d\u03d5\u2080 * \u03b1\u2096)))\n    while f(x + \u03b1\u2096\u208a\u2081*p) > \u03d5\u2080 + c*\u03b1\u2096\u208a\u2081*d\u03d5\u2080\n        \u03d5\u03b1\u2096\u208a\u2081 = \u03d5(\u03b1\u2096\u208a\u2081)\n        a, b = [\u03b1\u2096^2 -\u03b1\u2096\u208a\u2081^2; -\u03b1\u2096^3 \u03b1\u2096\u208a\u2081^3] * \n            [\u03d5\u03b1\u2096\u208a\u2081 - \u03d5\u2080 - d\u03d5\u2080*\u03b1\u2096\u208a\u2081; \u03d5\u03b1\u2096 - \u03d5\u2080 - d\u03d5\u2080*\u03b1\u2096] / \n            (\u03b1\u2096^2*\u03b1\u2096\u208a\u2081^2*(\u03b1\u2096\u208a\u2081-\u03b1\u2096))\n        \u03b1\u2096\u208a\u2082 = (-b + sqrt(b^2 - 3a*d\u03d5\u2080)) / (3a)\n        \u03b1\u2096\u208a\u2082 = max(min(\u03b1\u2096\u208a\u2082, \u03b1\u2096\u208a\u2081 - \u03f5), \u03b1\u2096\u208a\u2081/2)\n        \u03b1\u2096 = \u03b1\u2096\u208a\u2081\n        \u03d5\u03b1\u2096 = \u03d5\u03b1\u2096\u208a\u2081\n        \u03b1\u2096\u208a\u2081 = T(\u03b1\u2096\u208a\u2082)\n    end\n    return \u03b1\u2096\u208a\u2081\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 \u2208 invariant, u \u2208 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 \u2208 invariant, u \u2208 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 (-\u03c1(sparsevec([1], [-1.0], 10), sol) > -dmin) &&\n           (-\u03c1(sparsevec([4], [-1.0], 10), sol) > -dmin) &&\n           (-\u03c1(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(\u03b4=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-\u03c1(sparsevec([1], [-1.0], 10), sol_PLAD01_BND42)\n\n-\u03c1(sparsevec([4], [-1.0], 10), sol_PLAD01_BND42)\n\n-\u03c1(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(\u03b4=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-\u03c1(sparsevec([1], [-1.0], 10), sol_PLAD01_BND30)\n\n-\u03c1(sparsevec([4], [-1.0], 10), sol_PLAD01_BND30)\n\n-\u03c1(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": "# Test for gaussjacobi().\ntol = 1e-14\n# Test a small n:\nn = 42\na = -.1\nb = .3\nx, w = gaussjacobi(n, a, b)\n@test all(length(x) == n) && all(length(w) == n)\n@test abs(x[37] - 0.912883347814032) < tol\n@test abs(w[37] - 0.046661910947553) < tol\n\n@test_approx_eq dot(w,exp(x)) 2.7568520361985516\n\n# Test a larger n (using ASY)\na = -.7\nb = 1.3\nn = 251\nx, w = gaussjacobi(n, a, b)\n@test all(length(x) == n) && all(length(w) == n)\n@test abs(x[37] + 0.893103435898983) < tol\n@test abs(w[37] - 1.962534523788093e-04) < tol\n\n@test_approx_eq dot(w,exp(x)) 16.722957039404044\n\n# Test n = 1:\na = 1.0\nb = 2.0\nx, w = gaussjacobi(1, a, b)\n@test abs(x[1] - (b - a) / (a + b + 2)) < tol\n@test abs(w[1] - 2^(a + b + 1) * beta(a + 1, b + 1)) < tol\n\n@test_approx_eq dot(w,ones(x)) 1.3333333333333333\n\nx, w = gaussjacobi(1013, .9, -.1)\n@test abs(x[2] + 0.999986012231899) < tol\n@test abs(x[13] + 0.999225722939832) < tol\n@test abs(w[2] - 9.314674169892358e-05) < tol\n@test abs(w[13] - 4.654651764553262e-04) < tol\n\n@test_approx_eq dot(w,exp(x)) 1.6915068974063106\n\n\nx, w = gaussjacobi(10013, .9, -.1)\n@test abs(x[2]  +0.999999856605293) < tol\n@test abs(x[13]  + 0.999992061552711) < tol\n@test abs(w[2] - 1.509654630405615e-06) < tol\n@test abs(w[13] - 7.548275262993863e-06) < tol\n\n@test_approx_eq dot(w,exp(x)) 1.6915068974063106\n\n\n# tests bug where row vectors were returned\n@test isa(x,Vector{Float64})\n@test isa(w,Vector{Float64})\n\n# test last alpha and beta parameters: \nx, w = gaussjacobi(100, 19., 21.)\n@test abs(x[87] - 0.832211446176040) < tol \n@test abs(w[50] - 0.064530500882703) < tol\n\n# test for small alpha and beta: \nx, w = gaussjacobi(10000, .1, .2)\n@test abs(x[1] - -0.999999963363548) < tol \n@test abs(w[500] - 2.183393039546711e-05) < tol\n\n\n\nx,w=gaussjacobi(20,11.,0.)\n# tests bug where row vectors were returned\n@test isa(x,Vector{Float64})\n@test isa(w,Vector{Float64})\n\n\n", "meta": {"hexsha": "d0d33b502345b9aeeb9533ae7f3237e66826e861", "size": 1868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gaussjacobi.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": "test/test_gaussjacobi.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": "test/test_gaussjacobi.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.2432432432, "max_line_length": 58, "alphanum_fraction": 0.6445396146, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7678660620521646}}
{"text": "# kron.jl\n# test\n\nusing LinearMapsAA: LinearMapAA, LinearMapAM, LinearMapAO\nusing LinearAlgebra: I, Diagonal\nusing Test: @test, @testset\n\n\nM1 = rand(ComplexF64, 3, 3)\nM2 = rand(ComplexF64, 2, 2)\n\nM12 = kron(M1, M2)\nA1 = LinearMapAA(M1)\nA2 = LinearMapAA(M2)\n@testset \"kron basics\" begin\n    @test kron(A1, A1) isa LinearMapAM\n    for pair in ((A1,A2), (A1,M2), (M1,A2)) # all combinations\n        AAk = kron(pair[1], pair[2])\n        @test AAk isa LinearMapAM\n        @test Matrix(AAk) == M12\n        @test Matrix(AAk)' == Matrix(AAk')\n    end\nend\n\nA3 = LinearMapAA(M1 ; odim=(1,size(M1,1)))\nA4 = LinearMapAA(M2 ; idim=(size(M2,2),1))\n@testset \"kron(I,A)\" begin\n    K = kron(I(2), A4)\n    M = kron(I(2), M2)\n    @test K isa LinearMapAO\n       @test Matrix(K) == M\n       @test Matrix(K') == Matrix(K)'\nend\n\n@testset \"kron(A,I)\" begin\n    K = kron(A4, I(2))\n    M = kron(M2, I(2))\n    @test K isa LinearMapAO\n       @test Matrix(K) == M\n       @test Matrix(K') == Matrix(K)'\nend\n\n@testset \"kron(Ao,M)\" begin\n    @test kron(A3, M2) isa LinearMapAO\n    @test kron(M1, A4) isa LinearMapAO\nend\n\n@testset \"kron(Ao,Bo)\" begin\n    K = kron(A3, A4)\n    M = kron(M1, M2)\n    @test K isa LinearMapAO\n       @test Matrix(K) == M\n       @test Matrix(K') == Matrix(K)'\nend\n\n@testset \"kron(A,D)\" begin\n    D = Diagonal(1:3)\n    K = kron(A1, D)\n    @test Matrix(K) == kron(M1, D)\n    K = kron(D, A1)\n    @test Matrix(K) == kron(D, M1)\nend\n", "meta": {"hexsha": "8efd6621ee7678098039a4e0c05d46c8709ebfff", "size": 1422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/kron.jl", "max_stars_repo_name": "JeffFessler/LinearMapsAA.jl", "max_stars_repo_head_hexsha": "65d7fd4eaf0558988ae23ccad2a547778c6111e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-08-09T10:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T02:26:33.000Z", "max_issues_repo_path": "test/kron.jl", "max_issues_repo_name": "JeffFessler/LinearMapsAA.jl", "max_issues_repo_head_hexsha": "65d7fd4eaf0558988ae23ccad2a547778c6111e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2019-08-15T03:31:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T03:02:37.000Z", "max_forks_repo_path": "test/kron.jl", "max_forks_repo_name": "JeffFessler/LinearMapsAA.jl", "max_forks_repo_head_hexsha": "65d7fd4eaf0558988ae23ccad2a547778c6111e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:22:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T16:15:22.000Z", "avg_line_length": 22.5714285714, "max_line_length": 62, "alphanum_fraction": 0.582278481, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7678660602659974}}
{"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# \u2554\u2550\u2561 4a816b10-c188-11ea-3935-1fc7371387ac\nusing Plots\n\n# \u2554\u2550\u2561 62a8f092-c198-11ea-2d26-632729a6bd7f\nusing StatsBase\n\n# \u2554\u2550\u2561 1c0741f0-c17a-11ea-3c6f-31f0c86dd08d\nmd\"\"\"\n# Random Walk Models\n\"\"\"\n\n# \u2554\u2550\u2561 58e6d60e-c17c-11ea-145e-ffdc97ab1f3f\nmd\"Short function definition (one-liner):\"\n\n# \u2554\u2550\u2561 a93d6520-c17c-11ea-2cc7-5ff51f20df2b\njump() = rand( (-1, +1) )\n\n# \u2554\u2550\u2561 bfa68c10-c17c-11ea-281c-25e48e4ab81d\nmd\"Exactly the same\"\n\n# \u2554\u2550\u2561 ccef6d10-c17c-11ea-13e5-432b940ba726\nfunction jump_()\n\treturn rand( (-1, +1) )\nend\n\n# \u2554\u2550\u2561 fea8c400-c17c-11ea-35fc-e98ef849c316\njump()\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0762ce10-c17d-11ea-1f2a-172e4ed0500a\nbegin \n\tlocal t = (-1, +1)\n\ttypeof(t)\nend\n\n# \u2554\u2550\u2561 212df5a0-c186-11ea-0f5c-83f0dd5a1497\nmd\"Side remark: Simple bernoulli function\"\n\n# \u2554\u2550\u2561 8ce720ae-c185-11ea-380c-2df4848fb56a\nbernoulli(p) = rand() < p\n\n# \u2554\u2550\u2561 f52fc0a0-c185-11ea-2126-b10b11defe13\nbernoulli(0.25)\n\n# \u2554\u2550\u2561 891b2f20-c186-11ea-024f-372f0eef600c\nmd\"## Random walks\"\n\n# \u2554\u2550\u2561 15990630-c186-11ea-2059-e1e301040dae\n[jump() for i \u2208 1:10]\n\n# \u2554\u2550\u2561 62d228a2-c186-11ea-3ced-1db44003e269\nfunction walk(n)\n\tx = 0\n\t\n\tfor i \u2208 1:n\n\t\tx += jump() #x = x + jump()\n\tend\n\t\n\treturn x\nend\n\n# \u2554\u2550\u2561 0b66e5a2-c187-11ea-36de-279c4d6aa180\nwalk(10)\n\n# \u2554\u2550\u2561 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 \u2208 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# \u2554\u2550\u2561 131fcc00-c18a-11ea-09dc-0906c430d399\nmd\"\"\"steps = $(@bind steps html\"<input type='range' min=5 max=100>\" ) \"\"\"\n\n# \u2554\u2550\u2561 1afa1280-c18c-11ea-1d1b-7f277d76e68c\nmd\"**$(steps)** steps\"\n\n# \u2554\u2550\u2561 8cfcb9a2-c187-11ea-1129-ff3d55e25de4\ntrajectories = trajectory(steps)\n\n# \u2554\u2550\u2561 3b677390-c188-11ea-1079-01f262b1d76f\nmd\"## Plotting\"\n\n# \u2554\u2550\u2561 643c5510-c188-11ea-2d15-fbf4939ae53c\nbegin \n\tplot(trajectories, m=:o, size=(300, 200))\n\thline!([0], ls=:dash)\nend\n\n# \u2554\u2550\u2561 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 \u2208 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# \u2554\u2550\u2561 eb35c2e0-c18d-11ea-3209-bd013b156820\nmd\"## Precompute the data\"\n\n# \u2554\u2550\u2561 1ec51ce0-c18f-11ea-2166-6923cbcef091\nn = 20\n\n# \u2554\u2550\u2561 2c106ee0-c18f-11ea-21dc-db7d6706f5cb\ntraj = trajectory(n)\n\n# \u2554\u2550\u2561 3ee28c60-c18f-11ea-3297-3d26c8d37627\n@bind traj_steps html\"<input type='range' min=1 max=20>\"\n\n# \u2554\u2550\u2561 1ac71ed0-c190-11ea-2cfe-4d7cfd514800\nmd\"`traj_steps: ` $(traj_steps)\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 55e2ff60-c191-11ea-1b6b-b9a74d8fab5f\nmd\"## Run N walkers simultaneously\"\n\n# \u2554\u2550\u2561 60381bd0-c191-11ea-36a6-69333299f23b\nmd\"Rule: NEVER copy and paste (excpet occasionally)\n\nInstead: Automate \"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6fad5d40-c192-11ea-2573-01f0eb6c17ed\nmd\"`append!` extracts the elements of a vector\"\n\n# \u2554\u2550\u2561 f4e1b4c0-c192-11ea-3782-79f7c856869f\nbegin\n\tlocal v = [1, 2, 3 ,4]\n\t\n\tappend!(v, [5, 6])\nend\n\n# \u2554\u2550\u2561 0a1011c2-c193-11ea-04a2-e71ff37bf002\nmd\"a vector of vectors using an array comprehension\"\n\n# \u2554\u2550\u2561 d8b930b0-c193-11ea-0d53-63e3111f83a3\nn_ = 20\n\n# \u2554\u2550\u2561 c8dad7c0-c193-11ea-04a6-cf21953820d6\nwalkers = [trajectory(n_) for i \u2208 1:100]\n\n# \u2554\u2550\u2561 0f2b2db0-c194-11ea-06a1-6b2192a8e677\nmd\"Use `end` to get the last element in a vector\"\n\n# \u2554\u2550\u2561 61d6a940-c194-11ea-1d9f-4d6550479b45\n[ traj_[end] for traj_ in walkers ] # iterating through walkers, a Vector of Vectors\n\n# \u2554\u2550\u2561 02bf22b0-c195-11ea-2d1b-ddebd9d7a069\nmd\"Convert Vector of Vectors into a matrix:\"\n\n# \u2554\u2550\u2561 13a7bfb0-c195-11ea-13d2-41437b78aae1\nhcat(walkers...) # \"splat\" or like the \"spread\" operator in js\n\n# \u2554\u2550\u2561 188fbdb0-c196-11ea-16c2-0bbd3bd3c5f2\nmd\"a more efficient way:\" \n\n# \u2554\u2550\u2561 b3074f30-c195-11ea-0025-af543bf613be\nwalkers_matrix = reduce(hcat, walkers) \n\n# \u2554\u2550\u2561 2a00013e-c196-11ea-1d45-3d8ff26e1e53\nmd\"las element of the first row:\"\n\n# \u2554\u2550\u2561 f2221830-c195-11ea-09ff-2fb3e85bde34\nwalkers_matrix[1, end] \n\n# \u2554\u2550\u2561 5ed8c0a0-c196-11ea-2e0c-370732384c6b\nmd\"last element of the first and second rows:\"\n\n# \u2554\u2550\u2561 43f2c420-c196-11ea-3bfa-3320a1f4f92e\nwalkers_matrix[1:2, end] \n\n# \u2554\u2550\u2561 6e5598a0-c196-11ea-11d2-8f08d13fb07f\nmd\"get the last element of all of the rows:\"\n\n# \u2554\u2550\u2561 8b5d1592-c196-11ea-2a9f-17fbc031a2bd\nwalkers_matrix[1:end, end]\n\n# \u2554\u2550\u2561 9cbb09a0-c196-11ea-0975-c59ab691f596\nmd\"also:\"\n\n# \u2554\u2550\u2561 a19bf82e-c196-11ea-024c-c7de6f0fbdb2\nfinal_positions = walkers_matrix[:, end]\n\n# \u2554\u2550\u2561 aed262a0-c196-11ea-310c-976af5163b2a\nmd\"## Where are the walkers at last time step?\"\n\n# \u2554\u2550\u2561 e3dc4420-c196-11ea-37be-1388e05cdfc5\nscatter(final_positions)\n\n# \u2554\u2550\u2561 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 \u2208 1:num_walkers]\n\t\n\tfinal_positions_ = [traj_[end] for traj_ \u2208 walkers]\nend\n\n# \u2554\u2550\u2561 a46bcf22-c198-11ea-3496-cfdbdfcac559\nscatter(final_positions_)\n\n# \u2554\u2550\u2561 527b1810-c198-11ea-3634-5f82562c0394\nimport Pkg; Pkg.add(\"StatsBase\")\n\n# \u2554\u2550\u2561 76ce6910-c198-11ea-1a99-e33a29b2860f\ncounts = countmap(final_positions_)\n\n# \u2554\u2550\u2561 c6170a90-c198-11ea-19c6-a377288360bd\nscatter(counts)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25001c0741f0-c17a-11ea-3c6f-31f0c86dd08d\n# \u255f\u250058e6d60e-c17c-11ea-145e-ffdc97ab1f3f\n# \u2560\u2550a93d6520-c17c-11ea-2cc7-5ff51f20df2b\n# \u255f\u2500bfa68c10-c17c-11ea-281c-25e48e4ab81d\n# \u2560\u2550ccef6d10-c17c-11ea-13e5-432b940ba726\n# \u2560\u2550fea8c400-c17c-11ea-35fc-e98ef849c316\n# \u255f\u25009aff5fa0-c185-11ea-145a-c3230681bd4c\n# \u2560\u25500762ce10-c17d-11ea-1f2a-172e4ed0500a\n# \u255f\u2500212df5a0-c186-11ea-0f5c-83f0dd5a1497\n# \u2560\u25508ce720ae-c185-11ea-380c-2df4848fb56a\n# \u2560\u2550f52fc0a0-c185-11ea-2126-b10b11defe13\n# \u255f\u2500891b2f20-c186-11ea-024f-372f0eef600c\n# \u2560\u255015990630-c186-11ea-2059-e1e301040dae\n# \u2560\u255062d228a2-c186-11ea-3ced-1db44003e269\n# \u2560\u25500b66e5a2-c187-11ea-36de-279c4d6aa180\n# \u2560\u2550432008a0-c187-11ea-3606-159ae4ed8460\n# \u255f\u2500131fcc00-c18a-11ea-09dc-0906c430d399\n# \u255f\u25001afa1280-c18c-11ea-1d1b-7f277d76e68c\n# \u2560\u25508cfcb9a2-c187-11ea-1129-ff3d55e25de4\n# \u255f\u25003b677390-c188-11ea-1079-01f262b1d76f\n# \u2560\u25504a816b10-c188-11ea-3935-1fc7371387ac\n# \u2560\u2550643c5510-c188-11ea-2d15-fbf4939ae53c\n# \u2560\u2550b417eaf0-c18c-11ea-3ae7-19f88eab6b9f\n# \u255f\u2500eb35c2e0-c18d-11ea-3209-bd013b156820\n# \u2560\u25501ec51ce0-c18f-11ea-2166-6923cbcef091\n# \u2560\u25502c106ee0-c18f-11ea-21dc-db7d6706f5cb\n# \u255f\u25003ee28c60-c18f-11ea-3297-3d26c8d37627\n# \u255f\u25001ac71ed0-c190-11ea-2cfe-4d7cfd514800\n# \u2560\u2550727357e0-c18e-11ea-24f4-81a80c9e5f36\n# \u255f\u250055e2ff60-c191-11ea-1b6b-b9a74d8fab5f\n# \u255f\u250060381bd0-c191-11ea-36a6-69333299f23b\n# \u2560\u2550e1c193c0-c191-11ea-0c16-67d6d7611c26\n# \u255f\u25006fad5d40-c192-11ea-2573-01f0eb6c17ed\n# \u2560\u2550f4e1b4c0-c192-11ea-3782-79f7c856869f\n# \u255f\u25000a1011c2-c193-11ea-04a2-e71ff37bf002\n# \u2560\u2550d8b930b0-c193-11ea-0d53-63e3111f83a3\n# \u2560\u2550c8dad7c0-c193-11ea-04a6-cf21953820d6\n# \u255f\u25000f2b2db0-c194-11ea-06a1-6b2192a8e677\n# \u2560\u255061d6a940-c194-11ea-1d9f-4d6550479b45\n# \u255f\u250002bf22b0-c195-11ea-2d1b-ddebd9d7a069\n# \u2560\u255013a7bfb0-c195-11ea-13d2-41437b78aae1\n# \u255f\u2500188fbdb0-c196-11ea-16c2-0bbd3bd3c5f2\n# \u2560\u2550b3074f30-c195-11ea-0025-af543bf613be\n# \u255f\u25002a00013e-c196-11ea-1d45-3d8ff26e1e53\n# \u2560\u2550f2221830-c195-11ea-09ff-2fb3e85bde34\n# \u255f\u25005ed8c0a0-c196-11ea-2e0c-370732384c6b\n# \u2560\u255043f2c420-c196-11ea-3bfa-3320a1f4f92e\n# \u255f\u25006e5598a0-c196-11ea-11d2-8f08d13fb07f\n# \u2560\u25508b5d1592-c196-11ea-2a9f-17fbc031a2bd\n# \u255f\u25009cbb09a0-c196-11ea-0975-c59ab691f596\n# \u2560\u2550a19bf82e-c196-11ea-024c-c7de6f0fbdb2\n# \u255f\u2500aed262a0-c196-11ea-310c-976af5163b2a\n# \u2560\u2550e3dc4420-c196-11ea-37be-1388e05cdfc5\n# \u2560\u25508e8a1d20-c197-11ea-2241-7fed80778896\n# \u2560\u2550a46bcf22-c198-11ea-3496-cfdbdfcac559\n# \u2560\u2550527b1810-c198-11ea-3634-5f82562c0394\n# \u2560\u255062a8f092-c198-11ea-2d26-632729a6bd7f\n# \u2560\u255076ce6910-c198-11ea-1a99-e33a29b2860f\n# \u2560\u2550c6170a90-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": "using Test\nimport Calculus\nimport DSP\nimport NonlinearEquations\nimport Random\nimport SparseArrays\n\nRandom.seed!(0)\n\nexorig = :(p[1] * x ^ 2 + p[2] * x + p[3])\nex, d = NonlinearEquations.replacerefswithsyms(exorig)\nexold = NonlinearEquations.replacesymswithrefs(ex, d)\n@test exorig == exold\n\nex = :(p[1] * x[1] ^ 2 + p[2] * x[2 * y + f(z)] + p[3])\ndiffs, refs = NonlinearEquations.differentiatewithrefs(ex, :x)\nfor i = 1:2\n\tif refs[i] == [:(2 * y + f(z))]\n\t\t@test Calculus.simplify(diffs[i]) == :(p[2])\n\telseif refs[i] == [:(1)]\n\t\t@test Calculus.simplify(diffs[i]) == :(p[1] * (2 * x[1]))\n\telse\n\t\terror(\"the refs are bad\")\n\tend\nend\n\n#formulate a quadratic equation\n@NonlinearEquations.equations function quadeq(x, p; asdf=1)\n\tNonlinearEquations.setnumequations(1)\n\tNonlinearEquations.addterm(1, p[1] * x[1] ^ 2 + p[2] * x[1] + p[3])\nend\n\n#solve (x-1)(x+1)\np = [1.0, 0.0, -1.0]\nroot = NonlinearEquations.newton(x->quadeq_residuals(x, p), x->quadeq_x(x, p), [0.01])\n@test root[1] \u2248 1.0\nroot = NonlinearEquations.newton(x->quadeq_residuals(x, p), x->quadeq_x(x, p), [100.0])\n@test root[1] \u2248 1.0\nroot = NonlinearEquations.newton(x->quadeq_residuals(x, p), x->quadeq_x(x, p), [-0.01])\n@test root[1] \u2248 -1.0\nroot = NonlinearEquations.newton(x->quadeq_residuals(x, p), x->quadeq_x(x, p), [-23])\n@test root[1] \u2248 -1.0\n#test the gradient\ng(x, p) = x[1] * (p[1] + 2 * p[2] + 3 * p[3])\ng_x(x, p) = [(p[1] + 2 * p[2] + 3 * p[3])]\ng_p(x, p) = x[1] * [1, 2, 3]\nf_x(x, p) = quadeq_x(x, p)\nf_p(x, p) = quadeq_p(x, p)\ng(p) = (-p[2] - sqrt(p[2] ^ 2 - 4 * p[1] * p[3])) / (2 * p[1]) * (p[1] + 2 * p[2] + 3 * p[3])\nanalytical_gradient = Calculus.gradient(g)\n@test analytical_gradient(p) \u2248 NonlinearEquations.gradient(root, p, g_x, g_p, f_x, f_p)\n\n#solve (2x-3)(7x+5)\np = [14.0, -11.0, -15]\nroot = NonlinearEquations.newton(x->quadeq_residuals(x, p), x->quadeq_x(x, p), [1.0])\n@test root[1] \u2248 3 / 2\nroot = NonlinearEquations.newton(x->quadeq_residuals(x, p), x->quadeq_x(x, p), [0.0])\n@test root[1] \u2248 -5 / 7\n\n#formulate a quadratic equation in a different way\n@NonlinearEquations.equations function quadeq2(x::T, p; asdf=1) where {T}\n\tNonlinearEquations.setnumequations(1)\n\tNonlinearEquations.addterm(1, p[1] * x[1] ^ 2)\n\tNonlinearEquations.addterm(1, p[2] * x[1])\n\tNonlinearEquations.addterm(1, p[3])\nend\n\n#solve (x-1)(x+1)\np = [1.0, 0.0, -1.0]\nroot = NonlinearEquations.newton(x->quadeq2_residuals(x, p), x->quadeq2_x(x, p), [0.01])\n@test root[1] \u2248 1.0\nroot = NonlinearEquations.newton(x->quadeq2_residuals(x, p), x->quadeq2_x(x, p), [100.0])\n@test root[1] \u2248 1.0\nroot = NonlinearEquations.newton(x->quadeq2_residuals(x, p), x->quadeq2_x(x, p), [-0.01])\n@test root[1] \u2248 -1.0\nroot = NonlinearEquations.newton(x->quadeq2_residuals(x, p), x->quadeq2_x(x, p), [-23])\n@test root[1] \u2248 -1.0\n\n#solve (2x-3)(7x+5)\np = [14.0, -11.0, -15]\nroot = NonlinearEquations.newton(x->quadeq2_residuals(x, p), x->quadeq2_x(x, p), [0.0])\n@test root[1] \u2248 -5 / 7\nroot = NonlinearEquations.newton(x->quadeq2_residuals(x, p), x->quadeq2_x(x, p), [1.0])\n@test root[1] \u2248 3 / 2\n\n#formulate the steady-state diffusion equation with a heterogeneous diffusion coefficient\n@NonlinearEquations.equations function diffusion(x, p, n)\n\t@assert length(x) == n\n\t@assert length(p) == n + 1\n\tNonlinearEquations.setnumequations(n)\n\tdx2 = 1 / (n + 1) ^ 2\n\tNonlinearEquations.addterm(1, ((p[1] + p[2]) * x[1] - p[2] * x[2] - p[1]) / dx2)\n\tfor eqnum = 2:n - 1\n\t\tNonlinearEquations.addterm(eqnum, (-p[eqnum] * x[eqnum - 1] + (p[eqnum] + p[eqnum + 1]) * x[eqnum] - p[eqnum + 1] * x[eqnum + 1]) / dx2)\n\tend\n\tNonlinearEquations.addterm(n, ((p[end - 1] + p[end]) * x[end] - p[end - 1] * x[end - 1]) / dx2)\nend\n\n#solve the diffusion equation with head=1 at x=0 and head=0 at x=1 and a homogeneous diffusion coefficient\nn = 10 ^ 3\np = ones(n + 1)\nhead = NonlinearEquations.newton(x->diffusion_residuals(x, p, n), x->diffusion_x(x, p, n), zeros(n); numiters=1)\ndx2 = (1 / (n + 1)) ^ 2\notherhead = SparseArrays.spdiagm(-1=>-ones(n - 1) / dx2, 0=>2 * ones(n) / dx2, 1=>-ones(n - 1) / dx2) \\ [[1 / dx2]; zeros(n - 1)]\n@test head \u2248 otherhead\n\n#solve the diffusion equation with head=1 at x=0 and head=0 at x=1 and a heterogeneous diffusion coefficient\nn = 10 ^ 3\nwindowsize = div(n, 10)\np = exp.(DSP.conv(0.1 * rand(n + windowsize + 1), ones(windowsize))[windowsize + 1:end - windowsize + 1])\nhead = NonlinearEquations.newton(x->diffusion_residuals(x, p, n), x->diffusion_x(x, p, n), zeros(n); numiters=1)\ndx2 = (1 / (n + 1)) ^ 2\notherhead = SparseArrays.spdiagm(-1=>-p[2:n] / dx2, 0=>(p[1:n] + p[2:n + 1]) / dx2, 1=>-p[2:n] / dx2) \\ [[p[1] / dx2]; zeros(n - 1)]\n@test head \u2248 otherhead\n\n\n#formulate the boundary value problem u''(x)=u^2-sin^2(x)-sin(x) with u(0)=0 and u(1)=0, which has u(x)=sin(x) as a solution on the interval [0, \u03c0]\n@NonlinearEquations.equations function nonlinearbvp(u, p, n)\n\tNonlinearEquations.setnumequations(n)\n\tdx2 = (pi / (n + 1)) ^ 2\n\txs = range(0, pi; length=n + 2)[2:end - 1]\n\tNonlinearEquations.addterm(1, -(2 * u[1] - u[2] - 0) / dx2 - u[1] ^ 2 + sin(xs[1]) ^ 2 + sin(xs[1]))\n\tfor eqnum = 2:n - 1\n\t\tNonlinearEquations.addterm(eqnum, -(2 * u[eqnum] - u[eqnum - 1] - u[eqnum + 1]) / dx2 - u[eqnum] ^ 2 + sin(xs[eqnum]) ^ 2 + sin(xs[eqnum]))\n\tend\n\tNonlinearEquations.addterm(n, -(2 * u[n] - u[n - 1] - 0 * sin(1)) / dx2 - u[n] ^ 2 + sin(xs[n]) ^ 2 + sin(xs[n]))\nend\n#now solve the boundary value problem\nn = 10 ^ 4\np = []\nu = NonlinearEquations.newton(x->nonlinearbvp_residuals(x, p, n), x->nonlinearbvp_u(x, p, n), zeros(n); numiters=100)\nu_analytical = map(x->sin(x), collect(range(0, pi; length=n + 2))[2:end - 1])\n@test u \u2248 u_analytical\n", "meta": {"hexsha": "ce7284ee121d7ee637b443c3b287c5d8e705cb99", "size": 5590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "OrchardLANL/NonlinearEquations.jl", "max_stars_repo_head_hexsha": "0a08e6a0fccc32d3cc9cc5475bf5d99bc859c642", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-03T22:05:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T22:05:50.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "OrchardLANL/NonlinearEquations.jl", "max_issues_repo_head_hexsha": "0a08e6a0fccc32d3cc9cc5475bf5d99bc859c642", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-17T23:25:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T23:25:45.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "OrchardLANL/NonlinearEquations.jl", "max_forks_repo_head_hexsha": "0a08e6a0fccc32d3cc9cc5475bf5d99bc859c642", "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": 41.7164179104, "max_line_length": 147, "alphanum_fraction": 0.6322003578, "num_tokens": 2352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7678660546319575}}
{"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') = \u03c3\u00b2(1+\u221a3*d/L + 5d\u00b2/3L\u00b2)exp(-\u221a5*d/L), where d = |x-x'| and L = diag(\u2113\u2081,\u2113\u2082,...)\n# Arguments:\n* `ll::Vector{Float64}`: Log of the length scale \u2113\n* `l\u03c3::Float64`: Log of the signal standard deviation \u03c3\n\"\"\" ->\ntype Mat52Ard <: StationaryARD\n    \u21132::Vector{Float64}   # Log of Length scale \n    \u03c32::Float64           # Log of signal std\n    Mat52Ard(ll::Vector{Float64}, l\u03c3::Float64) = new(exp(2.0*ll), exp(2.0*l\u03c3))\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.\u21132)\n    mat.\u21132 = exp(2.0*hyp[1:d])\n    mat.\u03c32 = exp(2.0*hyp[d+1])\nend\n\nget_params(mat::Mat52Ard) = [log(mat.\u21132)/2.0; log(mat.\u03c32)/2.0]\nget_param_names(mat::Mat52Ard) = [get_param_names(mat.\u21132, :ll); :l\u03c3]\nnum_params(mat::Mat52Ard) = length(mat.\u21132) + 1\n\nmetric(mat::Mat52Ard) = WeightedEuclidean(1.0./(mat.\u21132))\ncov(mat::Mat52Ard, r::Float64) = mat.\u03c32*(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.\u21132\n    r = sqrt(sum(wdiff))\n    exp_r = exp(-sqrt(5)*r)\n    \n    g1 = mat.\u03c32*(5/3)*(1+sqrt(5)*r)*exp_r.*wdiff # dK_d(log \u2113)\n    g2 = 2.0*mat.\u03c32*(1+sqrt(5)*r+(5/3)*r^2)*exp_r  # dK_d(log \u03c3)\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.\u03c32 .* exp_R .* (1.0 + sqrt(5)*R)\n    broadcast!(*, view(stack, :, :, 1:d), (5/3)*mat.\u03c32, 1 + sqrt(5)*R, exp_R, data.dist_stack, reshape(1.0./mat.\u21132, (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\u2081x\u2082x\u2083...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\u03c0i/5) permuted cyclical, 1 \u2266 k \u2266 4\n        w = exp(2.0*\u03c0*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 \u025b^2+3\u025b+1=0\n        \u025b = -1.5 - 0.5 * \u221a5.0 + 0*im\n        extended_sols = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in cyclical([\u025b, 1/\u025b, 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\u03c0i/7) permuted cyclical, 1 \u2266 k \u2266 6\n        w = exp(2.0*\u03c0*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 \u025b^2+5\u025b+1=0\n        \u025b = -2.5 - 0.5 * \u221a21.0 + 0*im\n        extended_sols = vec([ rev ? reverse!(w^k * perm) : w^k * perm for perm in cyclical([\u025b, 1/\u025b, 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*(\u221a7 + 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 GreatCircle\nusing Geodesy: LatLon\nusing Base.Test\n\n# One test decimal degree is 111000m\nlatitude = 40.0\nlongitude = -76.0\nposition = LatLon(lat=latitude, lon=longitude)\n\n\"\"\"\n    Great Circle Tests\n\"\"\"\nazimuth = 90.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone to the right\n@test new_gc[\"longitude\"] > longitude + 0.9\n\na = great_circle(111320., azimuth, 0., 0.)\n@test abs(a[\"latitude\"]-0.)<=eps(typeof(a[\"latitude\"]))\nfor i = 1:2\n    a = great_circle(111320., azimuth, a[\"latitude\"], a[\"longitude\"])\n    @test abs(a[\"latitude\"]-0.)<=eps(typeof(a[\"latitude\"]))\nend\naposition = LatLon(0., 0.)\na = great_circle(111320., azimuth, aposition)\n@test abs(a.lat-0.)<=eps(typeof(a.lat))\nfor i = 1:2\n    a = great_circle(111320., azimuth, a)\n    @test abs(a.lat-0.)<=eps(typeof(a.lat))\nend\n\nazimuth = 270.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone to the left\n@test new_gc[\"longitude\"] < longitude - 0.9\n\nazimuth = 180.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone down\n@test new_gc[\"latitude\"] < latitude - 0.9\n\nazimuth = 0.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone up\n@test new_gc[\"latitude\"] > latitude + 0.9\n\nazimuth = 315.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone up and to the left\n@test new_gc[\"latitude\"] > latitude + 0.45\n@test new_gc[\"longitude\"] < longitude - 0.45\n\nnew_gc = great_circle(111000., azimuth, position)\n@test new_gc.lat > latitude + 0.45\n@test new_gc.lon < longitude - 0.45\n\n\n# One decimal degree is 111000m\nlatitude = collect(40.0:5.:60.0)\nlongitude = collect(-40.0:-5.:-60.0)\n\nazimuth = ones(longitude) * 90.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone to the right\n@test all(new_gc[\"longitude\"] .> longitude + 0.9)\n\nazimuth = 270.\ndistance = 111000. * ones(longitude)\nnew_gc = great_circle(distance, azimuth, latitude, longitude)\n# We should have gone to the left\n@test all(new_gc[\"longitude\"] .< longitude - 0.9)\n\nazimuth = 180.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone down\n@test all(new_gc[\"latitude\"] .< latitude - 0.9)\n\nazimuth = 0.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone up\n@test all(new_gc[\"latitude\"] .> latitude + 0.9)\n\nazimuth = 315.\nnew_gc = great_circle(111000., azimuth, latitude, longitude)\n# We should have gone up and to the left\n@test all(new_gc[\"latitude\"] .> latitude + 0.45)\n@test all(new_gc[\"longitude\"] .< longitude - 0.45)\n\n\"\"\"\n    Great Distance Tests\n\"\"\"\n# One decimal degree at the equator is about 111.32km\nlatitude_start  = 0.\nlatitude_end    = 0.\nlongitude_start = 50.\nlongitude_end   = 52.\ngd = great_distance(latitude_start, longitude_start, latitude_end, longitude_end)\n@test round(gd[\"distance\"] ./ 1000, 2) .== 111.32 .* 2\n\na = LatLon(lat=latitude_start, lon=longitude_start)\nb = LatLon(lat=latitude_end, lon=longitude_end)\ngd = great_distance(a, b)\n@test round(gd[\"distance\"] ./ 1000, 2) .== 111.32 .* 2\n\n# One decimal degree is 111000m\nlatitude_start  = 0.\nlatitude_end    = 0.\nlongitude_start = [49., 75.]\nlongitude_end   = [50., 76.]\ngd = great_distance(latitude_start, longitude_start, latitude_end, longitude_end)\n@test all( round(gd[\"distance\"] ./ 1000, 2) .== 111.32 )\n", "meta": {"hexsha": "f944277a902b98dd0be5f5506e3b49e3a6f05cea", "size": 3358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/GreatCircle.jl-ec58984d-c81a-5818-9de3-f03f207dcefe", "max_stars_repo_head_hexsha": "b7615424e2986fadfc33b57dfcddc82b12f3cc5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-03-25T15:37:07.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-15T08:53:35.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirror/GreatCircle.jl-ec58984d-c81a-5818-9de3-f03f207dcefe", "max_issues_repo_head_hexsha": "b7615424e2986fadfc33b57dfcddc82b12f3cc5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-10-04T11:06:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:28:52.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirror/GreatCircle.jl-ec58984d-c81a-5818-9de3-f03f207dcefe", "max_forks_repo_head_hexsha": "b7615424e2986fadfc33b57dfcddc82b12f3cc5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:13:54.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:31:20.000Z", "avg_line_length": 29.9821428571, "max_line_length": 81, "alphanum_fraction": 0.7036926742, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7678491069606653}}
{"text": "using DiffEqOperators\n# using Plots\n\nn = 10000\n@show n\nx = range(0.0; length = n, stop = 2\u03c0)\ndx = x[2]-x[1]\ny = exp.(\u03c0*x)\ny_ = y[2:(end-1)]\n\nfor dor in 1:4, aor in 2:6\n\n    D1 = CenteredDifference(dor,aor,dx,length(x))\n\n    #test result\n    @show dor\n    @show aor\n    #take derivatives\n    err_abs = abs.(D1*y .- (\u03c0^dor)*y_)\n    err_percent = 100*err_abs./abs.(((\u03c0^dor)*y_))\n    max_error = maximum(err_percent) # test operator with known derivative of exp(kx)\n    avg_error = sum(err_percent)/length(err_percent)\n\n    @show max_error\n    @show avg_error\n    #plot(x[2:(end-1)], err_percent, title=\"Percentage Error, n=$n aor = $aor, dor = $dor\")\n\n    #test result\nend\n", "meta": {"hexsha": "88b9c5790ba2e85397d28ca396ee7f70f4b46efa", "size": 670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DerivativeOperators/error_benchmarking.jl", "max_stars_repo_name": "briochemc/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/error_benchmarking.jl", "max_issues_repo_name": "briochemc/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/error_benchmarking.jl", "max_forks_repo_name": "briochemc/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": 22.3333333333, "max_line_length": 91, "alphanum_fraction": 0.628358209, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7678323584746048}}
{"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": "\nusing ControlSystems;\n\nA=[0 1;1 0];\nB=[0;1];\nQ=[2 2;2 2];\nR=8;\n\nl=lqr(A,B,Q,R)\n\ncare(A,B,Q,R)\n", "meta": {"hexsha": "3fae1be668b60fb19b6983cfa89b33f026a69291", "size": 95, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problems/HW5_P2_i.jl", "max_stars_repo_name": "akshayhiregoudar/Control-System-Design", "max_stars_repo_head_hexsha": "11b4621dc74076da4ff150339e49045744962077", "max_stars_repo_licenses": ["MIT"], "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/HW5_P2_i.jl", "max_issues_repo_name": "akshayhiregoudar/Control-System-Design", "max_issues_repo_head_hexsha": "11b4621dc74076da4ff150339e49045744962077", "max_issues_repo_licenses": ["MIT"], "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/HW5_P2_i.jl", "max_forks_repo_name": "akshayhiregoudar/Control-System-Design", "max_forks_repo_head_hexsha": "11b4621dc74076da4ff150339e49045744962077", "max_forks_repo_licenses": ["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.9166666667, "max_line_length": 21, "alphanum_fraction": 0.5263157895, "num_tokens": 49, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813476288299, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7678191704734009}}
{"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. \u00d8., 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(\u03b1, F\u2081, F\u2082; N)\n    nF\u2082 = opnorm(F\u2082, Inf)\n    \u03bcF\u2081 = logarithmic_norm(F\u2081, Inf)\n\n    \u03b2 = \u03b1 * nF\u2082 / \u03bcF\u2081\n    \u03b5 = t -> \u03b1 * \u03b2^N * (exp(\u03bcF\u2081 * t) - 1)^N\n    return \u03b5\nend\n\n# See Theorem 4.2 in [1]\nfunction convergence_radius_apriori(\u03b1, F\u2081, F\u2082; N)\n    nF\u2082 = opnorm(F\u2082, Inf)\n    \u03bcF\u2081 = logarithmic_norm(F\u2081, Inf)\n\n    if \u03bcF\u2081 < 0\n        return Inf\n    end\n    \u03b2 = \u03b1 * F\u2082 / \u03bcF\u2081\n    T = (1/\u03bcF\u2081) * log(1 + 1/\u03b2)\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\u2080, F\u2081, F\u2082; N)\n    nx\u2080 = norm(x\u2080, Inf)\n    nF\u2081 = opnorm(F\u2081, Inf)\n    nF\u2082 = opnorm(F\u2082, Inf)\n    \u03b2\u2080 = nx\u2080 * nF\u2082 / nF\u2081\n\n    \u03b5 = t -> nx\u2080 * exp(nF\u2081 * t) / (1 - \u03b2\u2080 * (exp(nF\u2081 * t) - 1)) * (\u03b2\u2080 * (exp(nF\u2081 * t) - 1))^N\n    return \u03b5\nend\n\n# See Theorem 4.3 in [1].\nfunction convergence_radius_pseries(x\u2080, F\u2081, F\u2082; N)\n    nx\u2080 = norm(x\u2080, Inf)\n    nF\u2081 = opnorm(F\u2081, Inf)\n    nF\u2082 = opnorm(F\u2082, Inf)\n    \u03b2\u2080 = nx\u2080 * nF\u2082 / nF\u2081\n\n    T = (1/nF\u2081) * log(1 + 1/\u03b2\u2080)\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\u2080, F\u2081, F\u2082; check=true)\n    nx\u2080 = norm(x\u2080, 2)\n    nF\u2082 = opnorm(F\u2082, 2)\n\n    # compute eigenvalues and sort them by increasing real part\n    \u03bb = eigvals(F\u2081, sortby=real)\n    \u03bb\u2081 = last(\u03bb)\n    Re_\u03bb\u2081 = real(\u03bb\u2081)\n    if check\n        @assert Re_\u03bb\u2081 <= 0 \"expected Re(\u03bb\u2081) \u2264 0, got $Re_\u03bb\u2081\"\n    end\n    R = nx\u2080 * nF\u2082 / abs(Re_\u03bb\u2081)\n    return (R, Re_\u03bb\u2081)\nend\n\n# See Lemma 2 in [2]\nfunction error_bound_specabs(x\u2080, F\u2081, F\u2082; N, check=true)\n    (R, Re_\u03bb\u2081) = _error_bound_specabs_R(x\u2080, F\u2081, F\u2082; check=check)\n    if check\n        @assert R < 1 \"expected R < 1, got R = $R; try scaling the ODE\"\n    end\n\n    nx\u2080 = norm(x\u2080, 2)\n    if iszero(Re_\u03bb\u2081)\n        nF\u2082 = opnorm(F\u2082, 2)\n        \u03b5 = t -> nx\u2080 * (nx\u2080 * nF\u2082 * t)^N\n    else\n        \u03b5 = t -> nx\u2080 * R^N * (1 - exp(Re_\u03bb\u2081 * t))^N\n    end\n    return \u03b5\nend\n\n# See Lemma 2 in [2]\nfunction convergence_radius_specabs(x\u2080, F\u2081, F\u2082; check=true)\n    (R, Re_\u03bb\u2081) = _error_bound_specabs_R(x\u2080, F\u2081, F\u2082; check=check)\n\n    if Re_\u03bb\u2081 < 0\n        T = Inf\n    elseif iszero(Re_\u03bb\u2081)\n        nx\u2080 = norm(x\u2080, 2)\n        nF\u2082 = opnorm(F\u2082, 2)\n        \u03b2 = nx\u2080 * nF\u2082\n        T = 1/\u03b2\n    else\n        throw(ArgumentError(\"expected spectral abscissa to be negative or zero, got $Re_\u03bb\u2081\"))\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": "export PRISMA, PrismaParams, PrismaStepsize\n\nfunction PRISMA(x, # starting point\n\t\t\t\tLf, # Lipshitz constant of f\n\t\t\t\tgrad_f,\n\t\t\t\tprox_g,\n\t\t\t\tprox_h,\n\t\t\t\tobj,\n\t\t\t\tparams::OptParams=PrismaParams(PrismaStepsize(), 10))\n\n\t# initialize\n\tssr      = params.stepsizerule\n\tif ssr.initial_stepsize == Inf\n\t\tR = sqrt(obj(x)) # estimate of distance to solution\n\t\tssr.initial_stepsize = 2*R/Lf\n\tend\n\ty        = copy(x)\n\txkpp     = copy(x)\n\tbetakpp  = step(ssr)\n\tLkpp     = Lf + 1/betakpp\n\tthetak   = 1\n\tthetakpp = 1 # XXX see orabona's code\n\n\tif params.verbose > 0\n\t\t@printf(\"%10s%12s\\n\", \"iter\", \"obj\")\n\t\t@printf(\"%10d%12.4e\\n\", 0, obj(xkpp))\n\tend\n\n\t# iterate\n\tfor k=1:params.maxiter\n\t\tbetak, betakpp    = betakpp, step(ssr)\n\t\tLk, Lkpp          = Lkpp, Lf + 1/betakpp\n\t\tthetak, thetakpp  = thetakpp, 2/(1+sqrt(1+4Lkpp/thetak^2/Lk))\n\t\txk, xkpp          = xkpp, prox_h((1-1/Lk/betak)*y - grad_f(y)/Lk + prox_g(y, betak)/Lk/betak, 1/Lk)\n\t\ty                 = xkpp + thetakpp*(1/thetak - 1)*(xkpp - xk)                 \n\t\tif params.verbose > 0\n\t\t\t@printf(\"%10d%12.4e\\n\", k, obj(xkpp))\n\t\tend\n\t\tif stop(params, xk, xkpp)\n\t\t\tbreak\n\t\tend\n\tend\n\n\treturn xkpp\nend\n\ntype PrismaStepsize<:StepSizeRule\n\tinitial_stepsize::AbstractFloat\n\titeration_counter::Int\nend\nfunction step(s::PrismaStepsize, args...; kwargs...)\n\ts.iteration_counter += 1\n\treturn s.initial_stepsize/(s.iteration_counter)\nend\nPrismaStepsize() = PrismaStepsize(Inf)\nPrismaStepsize(initial_stepsize) = PrismaStepsize(initial_stepsize, 0)\n\ntype PrismaParams<:OptParams\n\tstepsizerule::StepSizeRule\n\tmaxiter::Int\n\tverbose::Int\n\treltol::Float64\nend\nPrismaParams(;stepsize::StepSizeRule=PrismaStepsize(),\n\t          maxiter::Int=100,\n\t          verbose::Int=1,\n\t          reltol::Float64=1e-5) = PrismaParams(stepsize,maxiter,verbose,reltol)\nstop(s::PrismaParams, xk, xkpp) = vecnorm(xk - xkpp)/vecnorm(xk) < s.reltol ? true : false\t\n", "meta": {"hexsha": "79f26e726b3f74c97937c80a548ac86571c75ad7", "size": 1871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/PRISMA.jl", "max_stars_repo_name": "madeleineudell/FirstOrderOptimization", "max_stars_repo_head_hexsha": "3a0ad9efcea0d2845c6619a2c3f6fee582d4f32b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-10-27T22:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-27T22:33:45.000Z", "max_issues_repo_path": "src/algorithms/PRISMA.jl", "max_issues_repo_name": "madeleineudell/FirstOrderOptimization.jl", "max_issues_repo_head_hexsha": "3a0ad9efcea0d2845c6619a2c3f6fee582d4f32b", "max_issues_repo_licenses": ["MIT"], "max_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/PRISMA.jl", "max_forks_repo_name": "madeleineudell/FirstOrderOptimization.jl", "max_forks_repo_head_hexsha": "3a0ad9efcea0d2845c6619a2c3f6fee582d4f32b", "max_forks_repo_licenses": ["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.115942029, "max_line_length": 101, "alphanum_fraction": 0.6595403528, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7677740422696488}}
{"text": "#=\nWe check the deposition step (i.e. computing \\rho) works as expected.\n=#\nusing Test\n\n@testset \"PIC deposition : uniform    \" begin\n    using LinearAlgebra\n    using VlasovSolvers\n    # using Plots\n\n    include(\"PIC.jl\")\n\n    function samples_verif1(nsamples, kx::Float64)\n        x0 = Array{Float64}(undef, nsamples)\n        seq = SobolSeq(1)\n        for i = 1:nsamples\n            r = Sobol.next!(seq)\n            x0[i] = 2\u03c0/kx * r[1]\n        end\n        v0 = rand(Uniform(-10, 10), nsamples)\n        wei = 2\u03c0/kx/nsamples .* ones(Float64, nsamples)\n        return x0, v0, wei\n    end\n\n    kx = 0.5\n    L = 2\u03c0 / kx\n    np = 100000 # nb de particules\n    nx = 32   # nb de mailles pour le calcul de l energie\n    mesh1 = OneDGrid(CPU(), nx, 0, L)\n\n    (x0, v0, w0) = samples_verif1(np, kx)\n    p = Particles(x0, v0, w0, np)\n\n    \u03c1, \u03c1_tot = compute_rho(p, mesh1)\n\n    # arrx = mesh1.start:mesh1.step:(mesh1.stop - mesh1.step)\n    # plot(arrx, \u03c1)\n\n    @test maximum(abs.(\u03c1 .- 1.)) < 10^-3\n    @test \u03c1_tot \u2248 1.0\nend\n\n@testset \"PIC deposition : 1 + 0.99cos\" begin\n    using LinearAlgebra, Roots\n    using VlasovSolvers\n    # using Plots\n\n    include(\"PIC.jl\")\n\n    function samples_verif2(nsamples)\n        x0 = Array{Float64}(undef, nsamples)\n        seq = SobolSeq(1)\n        for i = 1:nsamples\n            r = Sobol.next!(seq)\n            resx = find_zero(x-> x + 0.99 / kx * sin(kx*x) - r[1]*2\u03c0/kx, 0.0)\n            x0[i] = resx\n        end\n        v0 = rand(Uniform(-10, 10), nsamples)\n        wei = 2\u03c0/kx/nsamples .* ones(Float64, nsamples)\n        return x0, v0, wei\n    end\n\n    kx = 0.5\n    L = 2\u03c0 / kx\n    np = 100000 # nb de particules\n    nx = 128   # nb de mailles pour le calcul de l energie\n    mesh1 = OneDGrid(CPU(), nx, 0, L)\n\n    (x0, v0, w0) = samples_verif2(np)\n    p = Particles(x0, v0, w0, np)\n\n    \u03c1, \u03c1_tot = compute_rho(p, mesh1)\n\n    arrx = mesh1.start:mesh1.step:(mesh1.stop - mesh1.step)\n    \n    @test maximum(abs.(\u03c1 - (1 .+ 0.99cos.(kx.*arrx)))) < 5.10^-3\n    @test \u03c1_tot \u2248 1.0\nend", "meta": {"hexsha": "e7770875e5046f7c157795de1bca9e7be8af3533", "size": 2009, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_deposition_pic.jl", "max_stars_repo_name": "ylehenaff/VlasovSolvers.jl", "max_stars_repo_head_hexsha": "1e01810153e5bc4c8c417adf1f019582f3521666", "max_stars_repo_licenses": ["MIT"], "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_deposition_pic.jl", "max_issues_repo_name": "ylehenaff/VlasovSolvers.jl", "max_issues_repo_head_hexsha": "1e01810153e5bc4c8c417adf1f019582f3521666", "max_issues_repo_licenses": ["MIT"], "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_deposition_pic.jl", "max_forks_repo_name": "ylehenaff/VlasovSolvers.jl", "max_forks_repo_head_hexsha": "1e01810153e5bc4c8c417adf1f019582f3521666", "max_forks_repo_licenses": ["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.7564102564, "max_line_length": 77, "alphanum_fraction": 0.5609756098, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7677740381129939}}
{"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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9c0dfe82-92af-11eb-3192-49c2deac6e9b\np2 = [r2, a2, v2, (100 - ir)/100, (100 - iv)/100, m2]\n\n# \u2554\u2550\u2561 a1e4ca5e-92af-11eb-1c40-410a8d3abaca\nu02 = [1-I02-R02-V02-D02, I02, R02, V02, D02]\n\n# \u2554\u2550\u2561 ada6253e-92af-11eb-0e32-d9760ab88271\ntspan2 = (0.0, 2000)\n\n# \u2554\u2550\u2561 b08f47b2-92af-11eb-367b-979567aebb4d\nprob2 = ODEProblem(sirvd!,u02,tspan2,p2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 230527fa-92b3-11eb-308f-ffab3777029c\nsol2(0:tmax2, Val{1}, idxs=2)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500430d5134-92af-11eb-1fcc-d71f5216d62a\n# \u255f\u25005adc7e34-92af-11eb-2cfe-67899a4a0291\n# \u255f\u25007a19b238-92af-11eb-30fd-b189d06a0882\n# \u255f\u25007ec0712a-92af-11eb-2144-15d33af27c3d\n# \u255f\u250088b411f0-92af-11eb-2abf-151b2bfb313b\n# \u255f\u2500230527fa-92b3-11eb-308f-ffab3777029c\n# \u255f\u25008f867f9a-92af-11eb-3671-43904aa74d8b\n# \u255f\u250096d8a5c2-92af-11eb-1d3f-9bdd035eafec\n# \u255f\u25009c0dfe82-92af-11eb-3192-49c2deac6e9b\n# \u255f\u2500a1e4ca5e-92af-11eb-1c40-410a8d3abaca\n# \u255f\u2500ada6253e-92af-11eb-0e32-d9760ab88271\n# \u255f\u2500b08f47b2-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": "# Based on an example from\n#\thttps://jump.dev/JuMP.jl/previews/PR2476/examples/Semidefinite%20programs/max_cut_sdp/\n# which in turn uses methods from\n#\tGoemans, M. X., & Williamson, D. P. (1995). Improved approximation\n#\talgorithms for maximum cut and satisfiability problems using semidefinite\n#\tprogramming. Journal of the ACM (JACM), 42(6), 1115-1145.\n\nusing SparseArrays\nusing LinearAlgebra\n\n# Model the max-cut SDP relaxation --------------------------------------------\n\ncut_value(C, cut) =\tsum(C .* (cut * cut'))\nlaplacian(W) = spdiagm(vec(sum(W, dims=1))) - W\n\nfunction extract_cut(X)\n\trnd = normalize(rand(size(X, 1)))\n\n\tfactorization = cholesky(Hermitian(X), Val(true); check=false)\n\tV = (factorization.P * factorization.L)'\n\tvs = map(normalize, eachcol(V))\n\n\tmap(x -> dot(rnd, x) |> sign, vs)\nend\n\nfunction max_cut_sdp_model(weights)\n\tn = size(weights, 1)\n\n\tC = laplacian(weights) / 4\n\tAs = [sparse([i], [i], [1], n, n) for i in 1:n]\n\tb = ones(n) / n\n\n\tC, As, b\nend\n\nfunction solve_maxcut(W)\n\tn = size(W, 1)\n\n\tC, As, b = max_cut_sdp_model(W)\n\tX = sketchy_cgal(normalize(-C), As, b; R=n, info_io=devnull)\n\n\tcut = extract_cut(X)\n\tvalue = cut_value(C, cut)\n\n\tcut, value\nend\n\n# Examples --------------------------------------------------------------------\n\nfunction maxcut_example_1()\n\tW = [\n\t\t0 5;\n\t\t5 0;\n\t]\n\n\tcut, value = solve_maxcut(W)\n\n\t@test isapprox(value, 5)\n\t@test cut[1] != cut[2]\nend\n\nfunction maxcut_example_2()\n\tW = [\n\t\t0 5 7 6;\n\t\t5 0 0 1;\n\t\t7 0 0 1;\n\t\t6 1 1 0;\n\t]\n\n\tcut, value = solve_maxcut(W)\n\n\t@test isapprox(value, 18)\n\t@test cut[1] != cut[2]\n\t@test cut[2] == cut[3] == cut[4]\nend\n\nfunction maxcut_example_3()\n\tW = [\n\t\t0 1 5 0;\n\t\t1 0 0 9;\n\t\t5 0 0 2;\n\t\t0 9 2 0;\n\t]\n\n\tcut, value = solve_maxcut(W)\n\n\t@test isapprox(value, 17)\n\t@test cut[1] == cut[4]\n\t@test cut[2] == cut[3]\n\t@test cut[1] != cut[2]\nend", "meta": {"hexsha": "93af8cf111100f65204c643017b80133f73925fb", "size": 1823, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/maxcut.jl", "max_stars_repo_name": "votroto/SketchyCGAL.jl", "max_stars_repo_head_hexsha": "9b588045cf4b6a926d73266e587e1ce958bae174", "max_stars_repo_licenses": ["MIT"], "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/maxcut.jl", "max_issues_repo_name": "votroto/SketchyCGAL.jl", "max_issues_repo_head_hexsha": "9b588045cf4b6a926d73266e587e1ce958bae174", "max_issues_repo_licenses": ["MIT"], "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/maxcut.jl", "max_forks_repo_name": "votroto/SketchyCGAL.jl", "max_forks_repo_head_hexsha": "9b588045cf4b6a926d73266e587e1ce958bae174", "max_forks_repo_licenses": ["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.032967033, "max_line_length": 88, "alphanum_fraction": 0.6055951728, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7677227295028721}}
{"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!(\u03c9,\u03c8,\u0394x,\u0394y,un,us,ve,vw)\n  \u03c9[:,end] .= 2*((\u03c8[:,end]  - \u03c8[:,end-1] )/(\u0394x^2) .- ve/\u0394x)\n  \u03c9[:,1] .= 2*((\u03c8[:,1]  - \u03c8[:,2]   )/(\u0394x^2) .- vw/\u0394x)\n  \u03c9[end,:] .= 2*((\u03c8[end,:]  - \u03c8[end-1,:] )/(\u0394y^2) .+ us/\u0394y)\n  \u03c9[1,:] .= 2*((\u03c8[1,:]  - \u03c8[2,:]   )/(\u0394y^2) .+ un/\u0394y)\nend\nfunction GaussSiedel!(\u03d5,Ap,An,As,Ae,Aw,Rp,res; \u03bb=1, maxiter = 1000)\n  normRes = 1\n  k = 0\n  Ny,Nx = size(\u03d5)\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        \u03d5P = \u03d5[i,j]\n        \u03d5E = \u03d5[i+0,j+1]\n        \u03d5W = \u03d5[i+0,j-1]\n        \u03d5N = \u03d5[i-1,j+0]\n        \u03d5S = \u03d5[i+1,j+0]\n        res[i,j] = Rp[i,j] - (Ap*\u03d5P\n          + An*\u03d5N\n          + As*\u03d5S\n          + Ae*\u03d5E\n          + Aw*\u03d5W)\n        \u0394\u03d5 = res[i,j]/Ap\n        \u03d5[i,j] = \u03bb*(\u03d5[i,j] + \u0394\u03d5) + (1-\u03bb)*\u03d5[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,\u0394x,\u0394y)\n  # This function returns a (Ny*Nx) \u00d7 (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\u00b2x = sparse(Isx, Jsx, Vsx)\n  D\u00b2y = sparse(Isy, Jsy, Vsy)\n  # D_xx = 1/(\u0394x^2) .* kron(sparse(I,Nx,Nx), D\u00b2x)\n  # D_yy = 1/(\u0394y^2) .* kron(D\u00b2y, sparse(I,Ny,Ny))\n  D_yy = 1/(\u0394y^2) .* kron(sparse(I,Nx,Nx), D\u00b2x)\n  D_xx = 1/(\u0394x^2) .* kron(D\u00b2y, sparse(I,Ny,Ny))\n  Lap = D_xx + D_yy\nend\nfunction BuildAdvectionDiffusionCoefficients(Re,\u0394t,\u0394x,\u0394y)\n  # Time-derivative\n  ap = 1/\u0394t\n  # Diffusion\n  ap += 2/(Re*\u0394x^2) + 2/(Re*\u0394y^2)\n  an = -1/(Re*\u0394y^2)\n  aw = -1/(Re*\u0394x^2)\n  as = -1/(Re*\u0394y^2)\n  ae = -1/(Re*\u0394x^2)\n  return ap,an,as,ae,aw\nend\nfunction BuildAdvectionDiffusionRHS!(Rp,\u03d5,\u03c8,\u0394t,\u0394x,\u0394y,Ny,Nx,Re)\n  # Time derivative\n  Rp .= \u03d5/\u0394t\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      \u03d5E = \u03d5[i+0,j+1]; \u03d5W = \u03d5[i+0,j-1]; \u03d5N = \u03d5[i-1,j+0]; \u03d5S = \u03d5[i+1,j+0]\n      \u03c8E = \u03c8[i+0,j+1]; \u03c8W = \u03c8[i+0,j-1]; \u03c8N = \u03c8[i-1,j+0]; \u03c8S = \u03c8[i+1,j+0]\n\n      u    = (\u03c8N - \u03c8S)/(2\u0394y); v    = -(\u03c8E - \u03c8W)/(2\u0394x)\n      \u2202\u03d5\u2202y = (\u03d5N - \u03d5S)/(2\u0394y); \u2202\u03d5\u2202x = (\u03d5E - \u03d5W)/(2\u0394x)\n\n      Rp[i,j] += - (u*\u2202\u03d5\u2202x + v*\u2202\u03d5\u2202y)\n      # Rp[i,j] += (\u03c8E - \u03c8W)/(2\u0394x) * (\u03d5N - \u03d5S)/(2\u0394y) -\n      #            (\u03c8N - \u03c8S)/(2\u0394y) * (\u03d5E - \u03d5W)/(2\u0394x)\n    end\n  end\nend\n\nfunction RecordHistory!(\u03d5,\u03d5_old,\u03d5_hist)\n  \u0394\u03d5 = norm(\u03d5 - \u03d5_old)\n  \u03d5_old .= \u03d5\n  push!(\u03d5_hist,\u0394\u03d5)\n  return(\u0394\u03d5)\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\u1d40\u03b2\n# Arguments:\n* `\u03b2::Vector{Float64}`: One coefficient for each dimension\n\"\"\" ->\ntype MeanLin <: Mean\n    \u03b2::Vector{Float64}\n    dim::Int\n    MeanLin(\u03b2::Vector{Float64}) = new(\u03b2, length(\u03b2))\nend\n    \nmean(mLin::MeanLin,x::Matrix{Float64}) =  x'mLin.\u03b2\n\nget_params(mLin::MeanLin) = mLin.\u03b2\nget_param_names(::MeanLin) = [:\u03b2]\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.\u03b2 = 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 `\u03c40`  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 `\u03c4`, and the idea is that the\ndistance which minimizes the pairwise difference between each window is considered to be the\nfundamental period `\u03c40` 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 `\u03c4` ranging\nfrom `\u03c4_min=sr/f0_max` to `\u03c4_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/\u03c40` 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\u00e9, 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    \u03c4_min = floor(Int64, sr / f0_max)\n    \u03c4_max = floor(Int64, sr / f0_min)\n\n    frame_times = range(1, length(sig) - w_len - \u03c4_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 + \u03c4_max+ w_len-1) ]\n        df = difference_function(frame, w_len, \u03c4_max)\n        cmdf = cumulative_mean_normalized_difference_function(df)\n        y_refined, \u03c4_refined, \u03c4_indices = refine_local_minima(cmdf)\n        idx_localminimum = absolute_threshold(y_refined, \u03c4_min, \u03c4_max, harmonic_threshold)\n        \u03c40 = \u03c4_refined[idx_localminimum]\n        F0s[i] = sr / \u03c40\n\n    end\n    return  F0s, frame_times\nend\n\n\"\"\"\n    difference_function_original(x, W, \u03c4max) -> df\nComputes the difference function of `x`. `W` is the window size, and `\u03c4max` 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, \u03c4max)\n    df = zeros(eltype(x), \u03c4max+1) #df corresponds to \u03c4 values from 0 to \u03c4_max\n    for \u03c4 in 1:\u03c4max\n        for j in 1:W\n            df[\u03c4+1] += (x[j] - x[j + \u03c4]) ^ 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 \u03c4 values: 0 to \u03c4_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, \u03c4_min, \u03c4_max, harmonic_threshold=0.1)\n    for (idx, localminimum) in enumerate(localminima)\n        if localminimum \u2264 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": "@testset \"Covariances\" begin\n  comps = rand(Composition{5}, 100)\n  data  = reduce(hcat, components.(comps))\n  table = (; zip([:N\u2082,:O\u2082,:CO\u2082,:S,:C], eachrow(data))...)\n\n  \u03a4 = variation(table)\n  \u03a3 = alrcov(table)\n  \u0393 = clrcov(table)\n  A = lrarray(table)\n\n  # Testing matrix forms transformations (Aitchison 1986, pages 82 and 83)\n  ## Test matrix transformation from \u03a4 to \u03a3 (4.25)\n  @test \u03a3 \u2248 -0.5 * F * \u03a4 * F'\n\n  ## Test matrix transformation from \u03a4 to \u0393 (4.26)\n  @test \u0393 \u2248 -0.5 * G * \u03a4 * G\n\n  ## Test matrix transformation from \u03a3 to \u03a4 (4.27)\n  \u0393\u2080 = F' * (inv(H) * \u03a3 * inv(H)) * F\n  @test \u03a4 \u2248 J * Diagonal(\u0393\u2080) + Diagonal(\u0393\u2080) * J - 2 * \u0393\u2080\n\n  ## Test matrix transformation from \u03a3 to \u0393 (4.28)\n  @test \u0393 \u2248 F' * (inv(H) * \u03a3 * inv(H)) * F\n\n  ## Test matrix transformation from \u0393 to \u03a4 (4.29)\n  @test \u03a4 \u2248 J * Diagonal(\u0393) + Diagonal(\u0393) * J - 2 * \u0393\n\n  ## Test matrix transformation from \u0393 to \u03a3 (4.30)\n  @test \u03a3 \u2248 F * \u0393 * F'\nend", "meta": {"hexsha": "79a900cd7e078920b7b2c18d43c3a5b1f1cde14b", "size": 915, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 30.5, "max_line_length": 74, "alphanum_fraction": 0.5912568306, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.767667066580384}}
{"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 \u2192 R_1``\n    `` \u2026``\n    ``f_k : D_k \u2192 R_k``\nthen FunProduct((f1, \u2026, fk)) is F\n    F : D1 \u00d7 \u2026 \u00d7 Dk \u2192 R1 \u00d7 \u2026 \u00d7 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\u2080, u\u2081, \u2026; kwargs...)\n    function expintegrator(A, t::Number, (u\u2080, u\u2081, \u2026); kwargs...)\n    function expintegrator(A, t::Number, (u\u2080, u\u2081, \u2026), algorithm)\n\nCompute ``y = \u03d5\u2080(t*A)*u\u2080 + t*\u03d5\u2081(t*A)*u\u2081 + t^2*\u03d5\u2082(t*A)*u\u2082 + \u2026``, where `A` is a general linear map, i.e. a `AbstractMatrix` or just a general function or callable object and `u\u2080`, `u\u2081` are of any Julia type with vector like behavior. Here, ``\u03d5\u2080(z) = exp(z)`` and ``\u03d5\u2c7c\u208a\u2081 = (\u03d5\u2c7c(z) - 1/j!)/z``. In particular, ``y = x(t)`` represents the solution of the ODE\n``x' = A*x + \u2211\u2c7c t^j/j! u\u2c7c\u208a\u2081`` with ``x(0) = u\u2080``.\n\n!!! note\n    When there are only input vectors `u\u2080` and `u\u2081`, `t` can equal `Inf`, in which the\n    algorithm tries to evolve all the way to the fixed point `y = - A \\\\ u\u2081 + P\u2080 u\u2080` with\n    `P\u2080` 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\u0303 = sign(t) * |t\u0303|`` with ``|t\u0303| < |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\u2080`, `u\u2081`, \u2026 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 = \u03d5\u2080(t\u0303*A)*u\u2080 + t\u0303*\u03d5\u2081(t\u0303*A)*u\u2081 + t\u0303^2*\u03d5\u2082(t\u0303*A)*u\u2082 + \u2026``\n    with ``t\u0303 = sign(t) * |t\u0303|`` with ``|t\u0303| <= |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\u0303`, 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\u0303|`\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\u2080` 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 `\u03f5` on the final result, set `tol = \u03f5/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\u2080`, `u\u2081`, \u2026 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\u2080, us...; kwargs...)\n    alg = eigselector(A, promote_type(typeof(t), eltype(u\u2080), eltype.(us)...); kwargs...)\n    expintegrator(A, t, (u\u2080, 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\u2080 = first(u)\n    \u03b2\u2080 = norm(u\u2080)\n    Au\u2080 = apply(A, u\u2080) # used to determine return type\n    numops = 1\n    T = promote_type(promote_type(eltype(Au\u2080), typeof(\u03b2\u2080), typeof(t)),\n                        promote_type(eltype.(u)...))\n    S = real(T)\n    w\u2080 = copyto!(similar(u\u2080, T), u\u2080)\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    \u03b7::S = alg.tol # tol is per unit time\n    totalerr = zero(\u03b7)\n    sgn = sign(t)\n    \u03c4::S = abs(t)\n    \u0394\u03c4::S = one(\u03c4) # don't try any clever initial guesses, rely on correction mechanism\n    \u03c4\u2080 = zero(\u03c4)\n\n    # safety factors\n    \u03b4::S = 1.2\n    \u03b3::S = 0.8\n\n    # initial vectors\n    w = Vector{typeof(w\u2080)}(undef, p+1)\n    w[1] = w\u2080\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*\u03c4\u2080)^l/lfac, u[j+l+1], w[j+1])\n            lfac *= l+1\n        end\n    end\n    v = similar(w\u2080)\n    \u03b2 = norm(w[p+1])\n    if \u03b2 < alg.tol && p == 1\n        if alg.verbosity > 0\n            @info \"\"\"expintegrate finished after 0 iterations, converged to fixed point up to error = $\u03b2\"\"\"\n        end\n        return w\u2080, ConvergenceInfo(1, zero(\u03c4), \u03b2, 0, numops)\n    end\n    mul!(v, w[p+1], 1/\u03b2)\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 \u03b2 < alg.tol && p == 1 # w\u2080 is fixed point of ODE\n            if alg.verbosity > 0\n                @info \"\"\"expintegrate finished after $numiter iterations, converged to fixed point up to error = $\u03b2\"\"\"\n            end\n            return w\u2080, ConvergenceInfo(1, zero(\u03c4), \u03b2, numiter, numops)\n        end\n\n        numiter += 1\n        \u0394\u03c4 = min(\u0394\u03c4, \u03c4-\u03c4\u2080)\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*\u0394\u03c4)\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        \u03f5 = abs(\u0394\u03c4^p * \u03b2 * normres(fact) * expH[K,K+p+1])\n        \u03c9 = \u03f5 / (\u0394\u03c4 * \u03b7)\n\n        q = K/2\n        while \u03c9 > one(\u03c9)\n            \u03f5_prev = \u03f5\n            \u0394\u03c4_prev = \u0394\u03c4\n            \u0394\u03c4 *= (\u03b3/\u03c9)^(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*\u0394\u03c4)\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            \u03f5 = abs(\u0394\u03c4^p * \u03b2 * normres(fact) * expH[K,K+p+1])\n            \u03c9 = \u03f5 / (\u0394\u03c4 * \u03b7)\n            q = max(zero(q),  log(\u03f5 / \u03f5_prev)/log(\u0394\u03c4 / \u0394\u03c4_prev)-1)\n        end\n\n        # take time step\n        totalerr += \u03f5\n        \u03c4\u2080 += \u0394\u03c4\n        jfac = 1\n        for j = 1:p-1\n            w\u2080 = axpy!((sgn*\u0394\u03c4)^j/jfac, w[j+1], w\u2080)\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\u2080 = axpy!(\u03b2*(sgn*\u0394\u03c4)^p, w[p+1], w\u2080)\n\n        # increase time step for next iteration:\n        if \u03c9 < \u03b3\n            \u0394\u03c4 *= (\u03b3/\u03c9)^(1/(q+1))\n        end\n\n        if alg.verbosity > 1\n            msg = \"expintegrate in iteration $numiter: \"\n            msg *= \"reached time \" * @sprintf(\"%.2e\", \u03c4\u2080)\n            msg *= \", total error = \" * @sprintf(\"%.4e\", totalerr)\n            @info msg\n        end\n\n        if \u03c4\u2080 >= \u03c4\n            if alg.verbosity > 0\n                @info \"\"\"expintegrate finished after $numiter iterations: total error = $totalerr\"\"\"\n            end\n            return w\u2080, ConvergenceInfo(1, zero(\u03c4), 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 = $(\u03c4 - \u03c4\u2080)\"\"\"\n            end\n            return w\u2080, ConvergenceInfo(0, \u03c4-\u03c4\u2080, 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*\u03c4\u2080)^l/lfac, u[j+l+1], w[j+1])\n                    lfac *= l+1\n                end\n            end\n            \u03b2 = norm(w[p+1])\n            mul!(v, w[p+1], 1/\u03b2)\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\u20134245 (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": "import GreyDecision.GreyNumbers.GreyNumber\nimport GreyDecision.GreyNumbers.kernel \n\n@testset \"Grey Numbers\" begin\n\n    @testset \"Kernel\" begin\n        @test kernel(GreyNumber(0.0, 10.0)) == 5.0\n    end\n\n    @testset \"Constructor with single argument\" begin\n        @test GreyNumber(1.0) == GreyNumber{Float64}(1.0, 1.0)\n        @test GreyNumber(0.0) == GreyNumber{Float64}(0.0, 0.0)\n        @test GreyNumber(1)   == GreyNumber{Int64}(1, 1)\n        @test GreyNumber(0)   == GreyNumber{Int64}(0, 0) \n    end\n\n    @testset \"Data structure - Zero Constructor\" begin\n        g = GreyNumber()\n        @test g.a == 0.0\n        @test g.b == 0.0\n    end\n\n    @testset \"Data structure - Constructor\" begin\n        g = GreyNumber(2.0, 5.0)\n        @test g.a == 2.0\n        @test g.b == 5.0\n\n        h = GreyNumber(5.0, 2.0)\n        @test g.a == 2.0\n        @test g.b == 5.0\n    end\n\n    @testset \"Whitenization\" begin\n        g = GreyNumber(10.0, 20.0)\n        w = GreyNumbers.whitenizate(g)\n        @test w == 15.0\n\n        w2 = GreyNumbers.whitenizate(g, t = 1.0)\n        @test w2 == 10.0\n\n        w3 = GreyNumbers.whitenizate(g, t = 0.0)\n        @test w3 == 20.0\n    end\n\n    @testset \"+\" begin\n        @testset \"Grey + Grey\" begin\n            g1 = GreyNumber(1, 2)\n            g2 = GreyNumber(5, 10)\n            greysum = g1 + g2\n            greysum2 = g2 + g1\n            @test greysum isa GreyNumber\n            @test greysum2 isa GreyNumber\n            @test greysum == greysum2\n            @test greysum.a == 6\n            @test greysum.b == 12\n        end\n        @testset \"Grey + scalar\" begin\n            g1 = GreyNumber(1, 2)\n            k = 3\n            result  = g1 + k\n            result2 = k  + g1\n            @test result isa GreyNumber\n            @test result2 isa GreyNumber\n            @test result2 == result\n            @test result.a == 4\n            @test result.b == 5\n        end\n    end\n\n    @testset \"Additive inverse (negatition)\" begin\n        g = GreyNumber(10, 20)\n        ginv = -g\n        @test ginv isa GreyNumber\n        @test ginv.a <= ginv.b\n        @test ginv.a == -20\n        @test ginv.b == -10\n    end\n\n    @testset \"Substraction\" begin\n        @testset \"Grey - Grey\" begin\n            g1 = GreyNumber(10, 20)\n            g2 = GreyNumber(1, 2)\n            gdiff1 = g1 - g2\n            gdiff2 = g2 - g1\n            @test gdiff1 isa GreyNumber\n            @test gdiff2 isa GreyNumber\n            @test gdiff1.a <= gdiff1.b\n            @test gdiff2.a <= gdiff2.b\n            @test gdiff1.a == 8\n            @test gdiff1.b == 19\n            @test gdiff2.a == -19\n            @test gdiff2.b == -8\n        end\n        @testset \"Grey - scalar\" begin\n            g = GreyNumber(10, 20)\n            k = 3\n            result  = g - k    \n            @test result isa GreyNumber\n            @test result.a == 7\n            @test result.b == 17\n        end\n        @testset \"Scalar - Grey\" begin\n            g1 = GreyNumber(100.0, 100.0)\n            k = 30.0\n            g2 = GreyNumber(k, k)\n            @test g1 - k  == g1 - g2\n            @test k - g1  == g2 - g1\n        end  \n    end\n\n    @testset \"Multiplication\" begin\n        g1 = GreyNumber(3, 4)\n        g2 = GreyNumber(5, 10)\n        mult = g1 * g2\n        mult2 = g2 * g1\n        @test mult isa GreyNumber\n        @test mult2 isa GreyNumber \n        @test mult == mult2\n        @test mult.a == 15\n        @test mult.b == 40\n    end\n\n    @testset \"Multiplication by scalar\" begin\n        @testset \"Scalar on the right\" begin\n            g1 = GreyNumber(10, 20)\n            result = g1 * 10\n            @test result isa GreyNumber\n            @test result.a == 100\n            @test result.b == 200\n        end\n        @testset \"Scalar on the left\" begin\n            g1 = GreyNumber(10, 20)\n            result = 10 * g1\n            @test result isa GreyNumber\n            @test result.a == 100\n            @test result.b == 200\n        end\n        @testset \"Negative scalar\" begin\n            g1 = GreyNumber(10, 20)\n            result = -10 * g1\n            @test result isa GreyNumber\n            @test result.a <= result.b\n            @test result.a == -200\n            @test result.b == -100\n        end\n    end\n\n    @testset \"Reciprocal (inverse)\" begin\n        g = GreyNumber(10, 20)\n        repic = inv(g)\n        @test repic isa GreyNumber\n        @test repic.a <= repic.b\n        @test repic.a == 1 / 20\n        @test repic.b == 1 / 10\n    end\n\n    @testset \"Division\" begin\n        @testset \"Division of two numbers\" begin\n            g1 = GreyNumber(3, 4)\n            g2 = GreyNumber(5, 10)\n            division = g1 / g2\n            @test division isa GreyNumber\n            @test division.a <= division.b\n            @test division.a == 0.3\n            @test division.b == 0.8\n        end\n\n        @testset \"Division by scalar\" begin\n            @testset \"Positive scalar\" begin\n                g1 = GreyNumber(30, 40)\n                result = g1 / 10\n                @test result isa GreyNumber\n                @test result.a <= result.b\n                @test result.a == 3\n                @test result.b == 4\n            end\n\n            @testset \"Negative scalar\" begin\n                g1 = GreyNumber(30, 40)\n                result = g1 / -10\n                @test result isa GreyNumber\n                @test result.a <= result.b\n                @test result.a == -4\n                @test result.b == -3\n            end\n        end\n    end\n\n    @testset \"Power\" begin\n        @testset \"All positive\" begin\n            g = GreyNumber(2, 4)\n            powered = g^5\n            @test powered isa GreyNumber\n            @test powered.a == 32\n            @test powered.b == 1024\n        end\n\n        @testset \"Some negative\" begin\n            g = GreyNumber(-5, -4)\n            powered = g^3\n            @test powered isa GreyNumber\n            @test powered.a <= powered.b\n            @test powered.a == -5 * 5 * 5\n            @test powered.b == -4 * 4 * 4\n        end\n    end\n\n    @testset \"sqrt\" begin\n        g = GreyNumber(36, 100)\n        gs = sqrt(g)\n        @test gs isa GreyNumber\n        @test gs.a == 6.0\n        @test gs.b == 10.0\n    end\n\n    @testset \"cbrt\" begin\n        k = 5.0\n        p = 3.0\n        g = GreyNumber(k * k * k, p * p * p)\n        result = cbrt(g)\n\n        @test result isa GreyNumber\n        @test result.a == p\n        @test result.b == k\n    end\n    \n\n    @testset \"abs\" begin\n        @testset \"all positive\" begin\n            g = GreyNumber(4, 5)\n            gabs = abs(g)\n            @test gabs isa GreyNumber\n            @test gabs == g\n        end\n\n        @testset \"all negative\" begin\n            g = GreyNumber(-4, -5)\n            gabs = abs(g)\n            @test gabs isa GreyNumber\n            @test gabs.a == 4\n            @test gabs.b == 5\n        end\n    end\n    \n    \n\n    @testset \"< and >\" begin\n        @test GreyNumber(4, 5) < GreyNumber(7, 8)\n        @test GreyNumber(4, 5) < GreyNumber(7, 10)\n        @test GreyNumber(4, 5) > GreyNumber(1, 2)\n        @test GreyNumber(5, 40) > GreyNumber(4, 5)\n        @test GreyNumber(1, 2) < GreyNumber(1,3)\n        @test GreyNumber(1, 5) > GreyNumber(1,3)\n    end\n\n    @testset \"<= and >=\" begin\n        @test GreyNumber(4, 5) <= GreyNumber(4, 8)\n        @test GreyNumber(4, 5) <= GreyNumber(4, 10)\n        @test GreyNumber(4, 5) >= GreyNumber(1, 5)\n        @test GreyNumber(5, 40) >= GreyNumber(4, 39)\n        @test GreyNumber(1, 2) <= GreyNumber(1,3)\n        @test GreyNumber(1, 20) >= GreyNumber(1,3)\n    end\n\n\n    @testset \"==\" begin\n        @test GreyNumber(4, 5) == GreyNumber(4, 5)\n        @test GreyNumber(4, 5) != GreyNumber(4, 2)\n    end\n\n    @testset \"min\" begin\n        nums = [GreyNumber(1, 20), GreyNumber(2, 20), GreyNumber(3, 20)]\n        @test minimum(nums) == GreyNumber(1, 20)\n    end\n\n    @testset \"max\" begin\n        nums = [GreyNumber(1, 20), GreyNumber(1, 40), GreyNumber(1, 60)]\n        @test maximum(nums) == GreyNumber(1, 60)\n    end\n\n    @testset \"isinteger\" begin\n        @test isinteger(GreyNumber(5, 6))\n    end\n\n    @testset \"isreal\" begin\n        @test isreal(GreyNumber(5.0, 6.0))\n    end\n\n    @testset \"isinf\" begin\n        @test isinf(GreyNumber(0.0, Inf64))\n    end\n\n    @testset \"iszero\" begin\n        @test iszero(GreyNumber())\n        @test iszero(GreyNumber(0, 0))\n        @test iszero(GreyNumber(0.0, 0.0))\n    end\n\n    @testset \"isone\" begin\n        @test isone(GreyNumber(1, 1))\n        @test isone(GreyNumber(1.0, 1.0))\n        @test !isone(GreyNumber())\n    end\n\n    @testset \"iseven\" begin\n        # Base.iseven is defined for integers\n        @test_throws AssertionError iseven(GreyNumber(2.0, 4.0))\n        @test iseven(GreyNumber(2, 4))\n    end\n\n    @testset \"isodd\" begin\n        # Base.isodd is defined for integers\n        @test_throws AssertionError isodd(GreyNumber(1.0, 3.0))\n        @test isodd(GreyNumber(1, 3))\n    end\n    \n\n    @testset \"elttype\" begin\n        @test eltype(GreyNumber(0.0, 0.0)) == Float64\n        @test eltype(GreyNumber(0, 0)) == Int64\n    end\n\n    @testset \"sum\" begin\n        @test sum(GreyNumber()) == 0\n        @test sum(GreyNumber(0, 0)) == 0\n        @test sum(GreyNumber(0.0, 0.0)) == 0.0\n        @test sum(GreyNumber(3.0, 4.0)) == 7.0\n    end\n\n    @testset \"getindex (g[i])\" begin\n        @testset \"Integers\" begin\n            g = GreyNumber(7, 8)\n            @test g[1] isa Int64\n            @test g[2] isa Int64\n            @test g[1] == 7\n            @test g[2] == 8\n        end\n\n        @testset \"Floats\" begin\n            g = GreyNumber(7.0, 8.0)\n            @test g[1] isa Float64\n            @test g[2] isa Float64\n            @test g[1] == 7.0\n            @test g[2] == 8.0\n        end\n    end\n\n    @testset \"first\" begin\n        @testset \"Integer\" begin\n            g = GreyNumber(7, 8)\n            @test g[1] isa Int64\n            @test first(g) == 7\n        end\n\n        @testset \"Float\" begin\n            g = GreyNumber(7.0, 8.0)\n            @test g[1] isa Float64\n            @test first(g) == 7.0\n        end\n    end\n\n\n    @testset \"last\" begin\n        @testset \"Integer\" begin\n            g = GreyNumber(7, 9)\n            @test last(g) == 9\n        end\n\n        @testset \"Floats\" begin\n            g = GreyNumber(7.0, 9.0)\n            @test last(g) == 9.0\n        end\n    end\n    \nend # End of testset GreyNumbers\n\n", "meta": {"hexsha": "441b8780026e86f8f460d4e625703d1548a5c139", "size": 10299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testgreynumber.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": "test/testgreynumber.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": "test/testgreynumber.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": 27.3183023873, "max_line_length": 72, "alphanum_fraction": 0.4889795126, "num_tokens": 3299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7676538414516016}}
{"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 \u2192 R1\n    f2 : D \u2192 R2\n        \u2026\n    fk : D \u2192 Rk\nthen FunTupling((f1, \u2026, fk)) is F\n    F : D \u2192 R1 \u00d7 \u2026 \u00d7 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(; \u03c1::Float64=0.9, \u03f5::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}[\u0394x]_{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    \u03f5::Float64\n    \u03c1::Float64\n    E_g\u00b2_t::AbstractArray\n    E_\u0394x\u00b2_t_1::AbstractArray\n    \u0394x\u00b2_t_1::AbstractArray\nend\n\nfunction Adadelta(; \u03c1::Real=0.9, \u03f5::Real=1e-8)\n    @assert \u03c1 > 0.0 \"\u03c1 must be greater than 0\"\n    @assert \u03f5 > 0.0 \"\u03f5 must be greater than 0\"\n\n    Adadelta(\"Adadelta\", 0, \u03f5, \u03c1, [], [], [])\nend\n\nparams(opt::Adadelta) = \"\u03f5=$(opt.\u03f5), \u03c1=$(opt.\u03c1)\"\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\u00b2_t = zero(g_t)\n        opt.E_\u0394x\u00b2_t_1  = zero(g_t)\n        opt.\u0394x\u00b2_t_1 = zero(g_t)\n    end\n\n    # accumulate gradient\n    opt.E_g\u00b2_t = opt.\u03c1 * opt.E_g\u00b2_t + (one(T) - opt.\u03c1) * (g_t .^ 2)\n\n    # compute update\n    RMS_g_t = sqrt.(opt.E_g\u00b2_t .+ opt.\u03f5)\n    RMS_\u0394x_t_1 = sqrt.(opt.E_\u0394x\u00b2_t_1 .+ opt.\u03f5)\n    \u0394x_t = RMS_\u0394x_t_1 .* g_t ./ RMS_g_t\n\n    # accumulate updates\n    opt.E_\u0394x\u00b2_t_1 = opt.\u03c1 * opt.E_\u0394x\u00b2_t_1 + (one(T) - opt.\u03c1) * (\u0394x_t .^ 2)\n\n    return \u0394x_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": "import FourierTransforms\nimport FourierTransforms: fft_kernel_sizes\nusing Test, LinearAlgebra, OffsetArrays\n\ninclude(\"symbolic.jl\")\n\nfunction testdft(x::AbstractVector{T}) where T<:Union{Real,Complex}\n    Tr = real(float(T))\n    Tc = complex(float(T))\n    y = similar(x, Tc)\n    N = length(x)\n    for (k1, yind) in enumerate(eachindex(y))\n        fct = zero(Tr)\n        yk  = zero(Tc)\n        for xi in x\n            yk  += xi*complex(cos(fct), -sin(fct))\n            fct += one(Tr)/N*(k1 - 1)*2*\u03c0\n        end\n        y[yind] = yk\n    end\n    return y\nend\n\n@testset \"Multiplication of size: $sz\" for sz in [collect(fft_kernel_sizes); 511; 512; 513]\n  @testset \"Real plan\" begin\n      xr = rand(sz)\n      @test FourierTransforms.fft(xr) \u2248 testdft(xr)\n      p = FourierTransforms.plan_fft(xr)\n      @test p*xr == FourierTransforms.fft(xr)\n      @test p\\(p*xr) \u2248 xr\n  end\n\n  @testset \"Complex plan applied to $atype\" for (atype, x) in (\n      (\"Vector\", rand(Complex{Float64}, sz)),\n      (\"OffsetVector\", OffsetArray(rand(Complex{Float64}, sz), 0:(sz - 1)))\n  )\n      p = FourierTransforms.plan_fft(x)\n      @test mul!(similar(x), p, x) == p*x\n      @test p*x \u2248 testdft(x)\n      @test p\\(p*x) \u2248 x\n  end\nend\n", "meta": {"hexsha": "313fd8e9f49ff82383cf413734be9ebddca5a5e5", "size": 1205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "RalphAS/FourierTransforms.jl", "max_stars_repo_head_hexsha": "6a206bcfc8f49a129ca34beaf57d05cdc148dc8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-09-15T23:42:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T11:53:26.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "RalphAS/FourierTransforms.jl", "max_issues_repo_head_hexsha": "6a206bcfc8f49a129ca34beaf57d05cdc148dc8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-08-26T22:33:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-01T19:40:14.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "RalphAS/FourierTransforms.jl", "max_forks_repo_head_hexsha": "6a206bcfc8f49a129ca34beaf57d05cdc148dc8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-05T10:26:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-01T19:23:06.000Z", "avg_line_length": 28.023255814, "max_line_length": 91, "alphanum_fraction": 0.5958506224, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7676538255723413}}
{"text": "using MultipleViewGeometry\nusing Test\n\n\n@testset \"Operators Tests\" begin include(\"operators_tests.jl\") end\n@testset \"Data Normalization Tests\" begin include(\"data_normalization_tests.jl\") end\n@testset \"Transform Tests\" begin include(\"transform_tests.jl\") end\n@testset \"Fundamental Matrix Construction Tests\" begin include(\"construct_fundamentalmatrix_tests.jl\") end\n@testset \"Homography Matrix Construction Tests\" begin include(\"construct_homographymatrix_tests.jl\") end\n@testset \"Essential Matrix Construction Tests\" begin include(\"construct_essentialmatrix_tests.jl\") end\n@testset \"Estimate Fundamental Matrix Tests\" begin include(\"estimate_fundamental_tests.jl\") end\n@testset \"Estimate Homography Matrix Tests\" begin include(\"estimate_homography_tests.jl\") end\n@testset \"Projection Matrix Construction Tests\" begin include(\"construct_projectionmatrix_tests.jl\") end\n@testset \"Projection Matrices Construction Tests\" begin include(\"construct_projectionmatrices_tests.jl\") end\n@testset \"Rotations Tests\" begin include(\"rotations_tests.jl\") end\n@testset \"Cost Function Tests\" begin include(\"cost_functions_tests.jl\") end\n#@testset \"Fundamental Matrix Covariance Test\" begin include(\"fundamental_matrix_covariance_test.jl\") end\n@testset \"Satisfy Epipolar Constraints Test\" begin include(\"satisfy_epipolar_constraints_tests.jl\") end\n@testset \"Triangulate Test\" begin include(\"triangulate_tests.jl\") end\n@testset \"Planar Triangulate Test\" begin include(\"planar_triangulate_tests.jl\") end\n@testset \"Noise Test\" begin include(\"perturb_tests.jl\") end\n", "meta": {"hexsha": "742ff2ed9175de3546cee06d8c87454f960b40c4", "size": 1545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 70.2272727273, "max_line_length": 108, "alphanum_fraction": 0.8278317152, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7675339084136508}}
{"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\u2080 = ellipse.center[1]\n    y\u2080 = ellipse.center[2]\n    \u03b8 = deg2rad(ellipse.ccw_angle)\n\n    # outputs\n    A = a^2 * sin(\u03b8)^2 + b^2 * cos(\u03b8)^2\n    B = 2 * (b^2 - a^2) * sin(\u03b8) * cos(\u03b8)\n    C = a^2 * cos(\u03b8)^2 + b^2 * sin(\u03b8)^2\n    D = -2 * A * x\u2080 - B * y\u2080\n    E = -B * x\u2080 - 2 * C * y\u2080\n    F = A * x\u2080^2 + B * x\u2080 * y\u2080 + C * y\u2080^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    \u0394 = det(A_Q) # -1/4 * (AE\u00b2 + CD\u00b2 + FB\u00b2 -BDE - 4 * ACF)\n\n    A_33 = [A B/2; B/2 C]\n    J = det(A_33) # -1/4 * (B\u00b2 - 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 \u0394, J, I and sq --> semiaxes a and b\n    =#\n\n    a = sqrt(-2 * \u0394 * (I + sq)) / (2*J)\n    b = sqrt(-2 * \u0394 * (I - sq)) / (2*J)\n\n    axis_lengths = [2*a 2*b]\n\n    x\u2080, y\u2080 = inv(A_33) * [-D/2; -E/2]\n\n    center = [x\u2080 y\u2080]\n\n    # all of the angles are mapped onto [-90,90]\n    # as the system has a period of 180\u00b0\n    # i.e. [-280, -100, 80, 260, etc] \u2192 80\n\n    if B == 0\n        if A <= C\n            \u03b8 = 0\n        else\n            \u03b8 = \u03c0/2\n        end\n    else\n        \u03b8 = atan(1/B * (C - A - sq))\n    end\n\n    ccw_angle = rad2deg(\u03b8)\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` \u2264 100, 0 < `n` \u2264 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": "function is_hermitian(M; atol = ATOL)\n\tisapprox(M, M', atol = atol)\nend\n\nfunction is_positive_semidefinite(M; atol = ATOL)\n\t!any(eigvals(M) .< - atol)\nend\n\nfunction is_a_gram_matrix(M; atol = ATOL)\n\tis_hermitian(M, atol = atol) && is_positive_semidefinite(M, atol = atol) && all([isapprox(M[i,i], one(eltype(M)), atol = atol) for i in 1:size(M)[1]])\nend\n\nfunction is_unitary(U; atol = ATOL)\n    isapprox(U' * U, Matrix(I, size(U)), atol = atol)\nend\n\nfunction is_orthonormal(U; atol = ATOL)\n\tfor i = 1:size(U)[2]\n\t\tisapprox(abs(norm(U[:, i])), 1., atol = atol) ? nothing : return false\n\t\tfor j = 1:size(U)[2]\n\t\t\tif j < i\n\t\t\t\tisapprox(abs(dot(U[:, i], U[:, j])), 0., atol = atol) ? nothing : return false\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction is_column_normalized(M; atol = ATOL)\n\n\tfor i = 1:size(M)[2]\n\t\t@test  abs(norm(M[:, i])) \u2248 1. atol = atol\n\tend\nend\n", "meta": {"hexsha": "1bd8a28b1482dfdc6d7847bf0cb338901fb790fe", "size": 849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix_tests.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/matrix_tests.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/matrix_tests.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": 24.9705882353, "max_line_length": 151, "alphanum_fraction": 0.6336866902, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7675265071200996}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Plots\nend;\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.11\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.11\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u25502eb0846a-3b2b-11eb-1154-ff7ca71f3c27\n# \u255f\u2500475ff888-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\u03b3= 2.0 #gamma parameter for CRRA utility\n\u03c1 = 0.05 #the discount rate\n\u03b1 = 0.3 # the curvature of the production function (cobb-douglas)\n\u03b4 = 0.05 # the depreciation rate\nAH = 0.6 #high prodictivity, costs \u03ba\nAL = 0.4 #low prodictivity, free\n\u03ba = 2 #fixed cost\n\nkssH = (\u03b1*AH/(\u03c1+\u03b4))^(1/(1-\u03b1))+\u03ba\nk_st = \u03ba./(1-(AL/AH).^(1/\u03b1))\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.-\u03ba,0).^\u03b1 #high productivity\nyL = AL*k.^\u03b1 #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\u03b5 = 10^(-6)\n\u0394 = 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.^\u03b1).^(1-\u03b3)/(1-\u03b3)/\u03c1\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]-\u03b4.*k_max).^(-\u03b3) # imposes a constraint\n\n    #backward difference\n    dVb[2:H] = (V[2:H] - V[1:H-1])/dk\n    dVb[1] = (y[1]-\u03b4.*k_min).^(-\u03b3)\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/\u03b3)\n\t\u03bcf = y -\u03b4.*k -cf\n    Hf = cf.^(1-\u03b3)/(1-\u03b3) + dVf.*\u03bcf\n\n    # consumption and saving backwards difference\n\n\tcb = max.(dVb,10^(-10)).^(-1/\u03b3)\n\t\u03bcb = y -\u03b4.*k -cb\n    Hb = cb.^(1-\u03b3)/(1-\u03b3) + dVb.*\u03bcb\n\n    #consumption and derivative of the value function at the steady state\n\n    c0 = y- \u03b4.*k\n    dV0 = max.(c0, 10^(-10)).^(-\u03b3)\n\tH0 = c0.^(1-\u03b3)/(1-\u03b3)\n\n    # Upwind scheme chooses between the forward or backward difference\n\tIeither = (1 .- (\u03bcf.>0)) .* (1 .- (\u03bcb.<0))\n\tIunique = (\u03bcb.<0).*(1 .- (\u03bcf.>0)) + (1 .- (\u03bcb.<0)).*(\u03bcf.>0)\n\tIboth = (\u03bcb.<0).*(\u03bcf.>0)\n    If= Iunique.*(\u03bcf .> 0) + Iboth.*(Hf.>=Hb)  #positive drift \u2192 forward difference\n    Ib = Iunique.*(\u03bcb .< 0) + Iboth.*(Hb.>=Hf) #negative drift \u2192 backward difference\n    I0 = Ieither  #at steady state\n\n    global c = cf.*If + cb.*Ib + c0.*I0\n    u = (c.^(1-\u03b3))/(1-\u03b3)\n\n\t# CONSTRUCT MATRIX\n    global X = -\u03bcb.*Ib/dk\n    global Y = - \u03bcf.*If/dk  + \u03bcb.*Ib/dk\n    global Z = \u03bcf.*If/dk\n\n\tglobal A = spdiagm(0=>Y[:], -1=>X[2:end], 1=>Z[1:end-1])\n\n\n  \tB = (1/\u0394 + \u03c1)*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/\u0394)\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].< \u03b5\n      \tprintln(\"Value Function Converged Iteration=\")\n      \tprintln(n)\n      \tbreak\n  \tend\n\nend\n\n# calculate the savings for kk\nkdot = y -\u03b4.*k -c\ndV_upwind = dVf.*If + dVb.*Ib+dV0.*I0\nVerr = c.^(1-\u03b3)/(1-\u03b3) + dV_upwind.*kdot - \u03c1.*V\n\n#plot for consumption\nplot(k, c, ylabel=\"\\$c(k)\\$\", xlabel=\"\\$k\\$\", label=\"Consumption\")\nplot!(k,y-\u03b4.*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 \u2264 L || error(\"chunksize = $chunksize \u2209 (0,L)\")\n    means = zeros(N)\n    for i \u2208 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 \u2208 1:L\n        means[i] = mean(array[j] for j in 1:L if j\u2260i)\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\u03bc, jack\u03c3 = jacknife(smallsample)\n    boot\u03bc, boot\u03c3 = bootstrap(smallsample, fr)\n    jdf = vcat(jdf, DataFrame(i=i,\n                              \u03bc=jack\u03bc,\n                              \u03c3=jack\u03c3))\n    bdf = vcat(bdf, DataFrame(i=i,\n                              fraction=fr,\n                              \u03bc=boot\u03bc,\n                              \u03c3=boot\u03c3))\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  \u03b8 = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-\u03b8)*A.u[idx] + \u03b8*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  \u03b8 = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-\u03b8)*A.u[:,idx] + \u03b8*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\u2080 = idx - 1; i\u2081 = idx; i\u2082 = i\u2081 + 1;\n  else\n    i\u2080 = idx; i\u2081 = i\u2080 + 1; i\u2082 = i\u2081 + 1;\n  end\n  l\u2080 = ((t-A.t[i\u2081])*(t-A.t[i\u2082]))/((A.t[i\u2080]-A.t[i\u2081])*(A.t[i\u2080]-A.t[i\u2082]))\n  l\u2081 = ((t-A.t[i\u2080])*(t-A.t[i\u2082]))/((A.t[i\u2081]-A.t[i\u2080])*(A.t[i\u2081]-A.t[i\u2082]))\n  l\u2082 = ((t-A.t[i\u2080])*(t-A.t[i\u2081]))/((A.t[i\u2082]-A.t[i\u2080])*(A.t[i\u2082]-A.t[i\u2081]))\n  A.u[i\u2080]*l\u2080 + A.u[i\u2081]*l\u2081 + A.u[i\u2082]*l\u2082\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\u2080 = idx - 1; i\u2081 = idx; i\u2082 = i\u2081 + 1;\n  else\n    i\u2080 = idx; i\u2081 = i\u2080 + 1; i\u2082 = i\u2081 + 1;\n  end\n  l\u2080 = ((t-A.t[i\u2081])*(t-A.t[i\u2082]))/((A.t[i\u2080]-A.t[i\u2081])*(A.t[i\u2080]-A.t[i\u2082]))\n  l\u2081 = ((t-A.t[i\u2080])*(t-A.t[i\u2082]))/((A.t[i\u2081]-A.t[i\u2080])*(A.t[i\u2081]-A.t[i\u2082]))\n  l\u2082 = ((t-A.t[i\u2080])*(t-A.t[i\u2081]))/((A.t[i\u2082]-A.t[i\u2080])*(A.t[i\u2082]-A.t[i\u2081]))\n  A.u[:,i\u2080]*l\u2080 + A.u[:,i\u2081]*l\u2081 + A.u[:,i\u2082]*l\u2082\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\u1d62 = A.u[i-1]\n  \u03c3 = 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]) + \u03c3 * (t - A.t[i-1])^2 + C\u1d62\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1a0f56fa-94a9-420f-b318-b6a0f197b140\ndataset = 0.1:0.1:0.6\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ef6a30bf-2f90-486d-879d-a1a089a89c84\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 54890bac-8050-4141-8e7e-2fb603bfe3b8\ndata = CSV.read(\"./datasets/pima-indians-diabetes.data.csv\", DataFrame; \n\t\t\t\theader=false)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0148021c-b8a8-4c47-bcbe-3eae9ef6e75d\nbootstrap(std, data[!, \"Column6\"], BasicSampling(n_iterations))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550303488a5-8102-4077-8cad-12655d8c5777\n# \u255f\u25006790c593-f5d3-4e45-be83-c974e581bbf2\n# \u255f\u25008b12df14-0a1f-4fc4-8677-02f26f16e1d6\n# \u255f\u25001023b0ba-fc8e-4d49-b795-ed3d75004b69\n# \u255f\u250066d8365c-cb3a-4a85-8da3-00eab0e1d1eb\n# \u2560\u25501a0f56fa-94a9-420f-b318-b6a0f197b140\n# \u2560\u25508b712ac8-37fe-4c0e-98c1-495f632ed305\n# \u2560\u2550ef6a30bf-2f90-486d-879d-a1a089a89c84\n# \u255f\u250068ad9943-a5a8-492f-8c5b-93bc7b49d36f\n# \u255f\u25004006c742-dc11-403d-b921-459b64ddd3c2\n# \u2560\u2550e74d5d8f-7d69-4e32-a036-c711194d216e\n# \u2560\u255054890bac-8050-4141-8e7e-2fb603bfe3b8\n# \u2560\u2550b8ccebb7-b303-4315-94fb-8ff253a90271\n# \u2560\u2550bde70fbd-d415-4d6b-b1d0-6eaba93012b9\n# \u2560\u25500148021c-b8a8-4c47-bcbe-3eae9ef6e75d\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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\u00d73) 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\u00d79) matrix, then extract from it the (3\u00d73) matrix obtained by taking the first, then\n\t\tevery third, row and column of your (9\u00d79) 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\u00d73) 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. \u6700\u5c0f\u4e8c\u4e57\u6cd5\u3092\u7528\u3044\u3066\u30e2\u30c7\u30eb\u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u3092\u6700\u9069\u5316\nfunction train!(model::LinearRegression)\n    # \u884c\u5217X\u306b\u300c1\u300d\u306e\u8981\u7d20\u3092\u8ffd\u52a0\n    ndim = model.n_data\n    Z = hcat(model.X, ones(ndim))\n\n    # \u5206\u6bcd\u306e\u8a08\u7b97\n    ZZ = 1 / ndim * Z' * Z\n\n    # \u5206\u5b50\u306e\u8a08\u7b97\n    ZY = 1 / ndim * Z' * model.Y\n\n    # \u30d1\u30e9\u30e1\u30fc\u30bf\u30fcv\u306e\u6700\u9069\u5316\n    # ZZ * v = ZY \u3092\u89e3\u304f\n    v = ZZ \\ ZY\n    model.w = v[1:end-1]\n    model.b = last(v)\n    model\nend\n\n# 3. \u4e88\u6e2c\n# X: \u5165\u529b\u30c7\u30fc\u30bf(\u30c7\u30fc\u30bf\u6570 x \u6b21\u5143\u6570\u306eArray)\npredict(model::LinearRegression, x) = x * model.w .+ model.b\n\n# 4. \u5e73\u65b9\u5e73\u5747\u4e8c\u4e57\u8aa4\u5dee(Root Mean Squared Error)\n# X: \u5165\u529b\u30c7\u30fc\u30bf(\u30c7\u30fc\u30bf\u6570 x \u6b21\u5143\u6570\u306eArray)\n# Y: \u51fa\u529b\u30c7\u30fc\u30bf(\u30c7\u30fc\u30bf\u6570 x 1\u306eArray)\nrmse(model::LinearRegression, x, y) = sqrt.(mean((predict(model, x) - y).^2))\n\n# 5. \u6c7a\u5b9a\u4fc2\u6570\u306e\u8a08\u7b97\n# X: \u5165\u529b\u30c7\u30fc\u30bf(\u30c7\u30fc\u30bf\u6570 x \u6b21\u5143\u6570\u306eArray)\n# Y: \u51fa\u529b\u30c7\u30fc\u30bf(\u30c7\u30fc\u30bf\u6570 x 1\u306eArray)\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\u30ce\u30eb\u30e0\u6b63\u5247\u5316\u6700\u5c0f\u4e8c\u4e57\u6cd5\u3092\u7528\u3044\u3066\u30e2\u30c7\u30eb\u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u3092\u6700\u9069\u5316\n# lamb: \u6b63\u5247\u5316\u306e\u91cd\u307f\u4fc2\u6570(\u5b9f\u6570\u30b9\u30ab\u30e9\u30fc)\nfunction train_regularized!(model::LinearRegression, lamb=0.1)\n    # \u884c\u5217X\u306b\u300c1\u300d\u306e\u8981\u7d20\u3092\u8ffd\u52a0\n    ndim = model.n_data\n    Z = hcat(model.X, ones(ndim))\n\n    # \u5206\u6bcd\u306e\u8a08\u7b97\n    ZZ = 1 / ndim * Z' * Z + lamb * I\n\n    # \u5206\u5b50\u306e\u8a08\u7b97\n    ZY = 1 / ndim * Z' * model.Y\n\n    # \u30d1\u30e9\u30e1\u30fc\u30bf\u30fcv\u306e\u6700\u9069\u5316\n    # ZZ * v = ZY \u3092\u89e3\u304f\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(\u03b4,\u03b5,b0,a1;T=2\u03c0)\n    AMx =  ProportionalMX(t->@SMatrix [0. 1.; -\u03b4-\u03b5*cos(2\u03c0/T*t) -a1]);\n    \u03c41=2\u03c0 # if function is needed, the use \u03c41 = t->foo(t)\n    BMx1 = DelayMX(\u03c41,t->@SMatrix [0. 0.; b0 0.]);\n    cVec = Additive(t->@SVector [0.,sin(4\u03c0/T*t)])\n    LDDEProblem(AMx,[BMx1],cVec)\nend;\n\n\u03c4max=2\u03c0 # the largest \u03c4 of the system\nT=2\u03c0 #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 \u0394t=0.1\n# if P = \u03c4max, then n_steps is automatically calculated\nmapping=DiscreteMapping_1step(mathieu_lddep,method,\u03c4max,\n    n_steps=Int((T+100eps(T))\u00f7method.\u0394t),calculate_additive=true); #The discrete mapping of the system\n\n@show spectralRadiusOfMapping(mapping); # spectral radius \u03c1 of the mapping matrix (\u03c1>1 unstable, \u03c1<1 stable)\nfp=fixPointOfMapping(mapping); # stationary solution of the hayes equation (equilibrium position)\n\n\nplot(0.0:method.\u0394t: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.\u0394t:P,fp[2:2:end],\n    xlabel=L\"-s\",linewidth=3,\n    label=L\"\\dot{x}(t-s)\")\n\nplot!(0.0:method.\u0394t:P,sin.(2*(0.0:method.\u0394t: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\u03b5=1;\n\u03c4max=2\u03c0;\nT=1\u03c0;\nmethod=SemiDiscretization(2,T/40);\n\nfoo(\u03b4,b0) = log(spectralRadiusOfMapping(DiscreteMapping_1step(createMathieuProblem(\u03b4,\u03b5,b0,a1,T=T),method,\u03c4max,\n    n_steps=Int((T+100eps(T))\u00f7method.\u0394t)))); # No additive term calculated\n\naxis=[Axis(-1:0.2:5.,:\u03b4),\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    \u03b1 :: TrackedArray # bias\n    \u03b2 :: TrackedArray # weights\n    LogisticRegression(\u03b1 :: Array, \u03b2 :: Array) = new(param(\u03b1), param(\u03b2))\nend\n\nfunction (m :: LogisticRegression)(X)\n    \u03c3.(m.\u03b1 .+ X*m.\u03b2)\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 \u2218 data \u2218 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(\u03b1s :: Array, \u03b2s :: Array)\n    anim = @animate for (\u03b1, \u03b2) in zip(\u03b1s, \u03b2s)\n        m = LogisticRegression(\u03b1, \u03b2)\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\u03b8 = Flux.params(m.\u03b1, m.\u03b2);\nnumEpochs = 100;\nloss = (x, y) -> mean(binarycrossentropy.(m(x), y));\n\nlosses, \u03b1s, \u03b2s = [], [], []\ncb = () -> begin\n    l = Flux.data(loss(X, y));\n    push!(losses, l);\n    push!(\u03b1s, Flux.data(m.\u03b1));\n    push!(\u03b2s, Flux.data(m.\u03b2));\nend\n\ndataset = repeated((X, y), numEpochs)\nFlux.train!(loss, \u03b8, dataset, Descent(0.1), cb = cb)\n\nplot_loss(losses)\nplot_fit(m)\n\ncreate_animation(\u03b1s, \u03b2s)\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": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 17deace8-9071-11eb-3ff4-e70cf05a1bcb\nbegin\nusing Images, TestImages\nusing ImageQualityIndexes\n\nimg = testimage(\"cameraman\") .|> float64\nnoisy_img = img .+ 0.1 .* randn(size(img))\nassess_ssim(noisy_img, img) # 0.24112\nassess_psnr(noisy_img, img) # 19.9697\n\nkernel = ones(3, 3)./9 # mean filter\ndenoised_img = imfilter(noisy_img, kernel)\nassess_psnr(denoised_img, img) # 28.4249\nassess_ssim(denoised_img, img) # 0.6390\nassess_msssim(denoised_img, img) # 0.8460\n\nimg = testimage(\"fabio\");\ncolorfulness(img) # 68.5530\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u255017deace8-9071-11eb-3ff4-e70cf05a1bcb\n", "meta": {"hexsha": "fc987f4d01d7036c66353a2d82988eee26959ff6", "size": 663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "image_quality.jl", "max_stars_repo_name": "ashwani-rathee/Demos", "max_stars_repo_head_hexsha": "b4980035c9cdf0384bfe1f743c0442d68861238b", "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": "image_quality.jl", "max_issues_repo_name": "ashwani-rathee/Demos", "max_issues_repo_head_hexsha": "b4980035c9cdf0384bfe1f743c0442d68861238b", "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": "image_quality.jl", "max_forks_repo_name": "ashwani-rathee/Demos", "max_forks_repo_head_hexsha": "b4980035c9cdf0384bfe1f743c0442d68861238b", "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.8620689655, "max_line_length": 42, "alphanum_fraction": 0.7330316742, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7674566791133545}}
{"text": "@testset \"Test equations for Rayleigh resolution\" begin\n    f = 100e-3\n    D = 50e-3\n\n    @test rayleigh_criterion(calc_NA(f, D)) \u2248 rayleigh_criterion(f, D)\n    @test rayleigh_criterion(calc_NA(f, D), \u03bb=500e-9) \u2248 rayleigh_criterion(f, D)\n    @test ~(rayleigh_criterion(calc_NA(f, D)) \u2248 rayleigh_criterion(f, D, \u03bb=200e-9))\n\nend\n\n\n@testset \"Calc NA\" begin\n    @test calc_NA(100, 100) \u2248 0.5\n    @test calc_NA(10e-9, 40e-9, 2) \u2248 4\nend\n", "meta": {"hexsha": "40d81e1a03546c924ca1ae943a187f4a903f0bc2", "size": 431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/resolution_equations.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": "test/resolution_equations.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": "test/resolution_equations.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": 26.9375, "max_line_length": 83, "alphanum_fraction": 0.6635730858, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7674566730230751}}
{"text": "using ThreeBodyProblem\nusing LinearAlgebra\nusing Test\n\n\u03bc\u2081 = 398600     # Earth gravitational parameter\n\u03bc\u2082 = 4902       # Moon gravitational paramter\nd = 384400      # Avg distance between Earth and Moon\np = [\u03bc\u2081; \u03bc\u2082; d]\n\u03bc = \u03bc\u2082/(\u03bc\u2081 + \u03bc\u2082)\n@test computeR1R2(\u03bc) == (-\u03bc, 1-\u03bc)\n@test computeL1(\u03bc) == [0.8369247061700067;0;0]\n@test computeL1(p) == [321713.8570517506;0;0]\n@test computeL2(\u03bc) == [1.1556746768583537;0;0]\n@test computeL2(p) == [444241.3457843512;0;0]\n@test computeL3(\u03bc) == [-1.005061834632099;0;0]\n@test computeL3(p) == [-386345.76923257887;0;0]\n@test computeL4(\u03bc) == [0.48785136133154233;0.8660254037844386;0]\n@test computeL4(p) == [187530.06329584488;332900.16521473817;0]\n@test computeL5(\u03bc) == [0.48785136133154233;-0.8660254037844386;0]\n@test computeL5(p) == [187530.06329584488;-332900.16521473817;0]\n\n@test computeLpts(\u03bc,tol=1e-3) != computeLpts(\u03bc)\n@test computeLpts(p,tol=1e-3) != computeLpts(p)\n\nrv = [1,0,0,0,1,0]\n@test computeUeff(rv,p) < 0\n@test computeUeff([-\u03bc;0;0],\u03bc) == -Inf\n\n@test_broken computeC(rv,p) > 0\n@test_broken computeC([-\u03bc;0;0],\u03bc) == Inf\n\n\u03a6 = ones(6,6)\n@test_broken stability_index(\u03d5) > 1\n\nsys = earth_moon()\nLpts = computeLpts(sys)\nrv = vcat(Lpts[1],zeros(3))\nC\u2081 = computeC(rv, sys)\n\nA = [-1. 0.  0.;\n      0. 1.  0.;\n      0. 0. -1.]\n@test det(roty(\u03c0) - A) == 0\n@test det(rotyd(180) - A) == 0\n\n\nmytime = [2000, 11, 17.625065277778]\nmytime2 = [2000,11,17,15,0,5.63999999]\nmytime3 = [1000, 1, 1]\nmytime4 = [1582, 11, 1]\nmytime5 = [1582, 10, 1]\nmytime6 = [1582, 10, 11]\nmytime7 = [1582, 10, 5]\nmytime8 = [1993, 4, 19]\n@test date2mjd(mytime2) == date2mjd(mytime)\n@test date2mjd(mytime3) == -314577.0\n@test date2mjd(mytime4) == -100823.0\n@test date2mjd(mytime5) == -101728.0\n@test date2mjd(mytime6) == -100844.0\n@test isnan(date2mjd(mytime7))\n@test date2mjd(mytime8) == 49096.0\n\n@test_throws ErrorException(\"ut1_date should be [Y,M,D] or [Y,M,D,h,m,s]\") date2mjd(1)\n\n@test wrapto360(314) == 314\n@test wrapto360(372) == 12\n@test wrapto360(721) == 1\n@test wrapto360(-1) == 359\n@test wrapto360(-361) == 359\n\n@test wrapto180(181) == -179\n@test wrapto180(179) == 179\n@test wrapto180(-181) == 179\n\n@test wrapto2pi(2\u03c0) == 2\u03c0\n@test wrapto2pi(3\u03c0) - \u03c0 == 0.\n@test wrapto2pi(-\u03c0) - \u03c0 == 0.\n\n@test wraptopi(\u03c0) == \u03c0\n@test wraptopi(2\u03c0) == 0.\n@test wraptopi(-2\u03c0) == 0.\n\n@test rotlatlon(\u03c0/2,-\u03c0/2,ang_unit=:rad) == I\n@test_throws ErrorException(\"ang_unit should be :deg or :rad\") rotlatlon(0,0,ang_unit=:foo)\n\n@test mjd2gmst(51544.5,ang_unit=:deg) == 280.4606\n@test_throws ErrorException(\"ang_unit should be :deg or :rad\") mjd2gmst(0,ang_unit=:foo)\n\nxyz_sphere,N = deserno_hemisphere(100,[1,0,0])\n@test abs(minimum([norm(xyz_sphere[:,i]) for i = 1:N]) - 1) < 1e-10\n@test abs(maximum([norm(xyz_sphere[:,i]) for i = 1:N]) - 1) < 1e-10\n", "meta": {"hexsha": "b1524fb0df1f5a4af8d5ed871ef1d9d135eee9d4", "size": 2742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/util_tests.jl", "max_stars_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_stars_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-28T01:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-28T22:34:55.000Z", "max_issues_repo_path": "test/util_tests.jl", "max_issues_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_issues_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_issues_repo_licenses": ["MIT"], "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/util_tests.jl", "max_forks_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_forks_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_forks_repo_licenses": ["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.8043478261, "max_line_length": 91, "alphanum_fraction": 0.6659372721, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.767456669967882}}
{"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: \u03c3\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(\u03c0*x) * cos(\u03c0*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 \u2208 IntervalDomain(0.0,t_max),\n        x \u2208 IntervalDomain(x_min,x_max),\n        y \u2208 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\u03b8 = discretization.init\u03b8\n\nacum =  [0;accumulate(+, length.(init\u03b8))]\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": "# example 2\nusing Statistics\nusing Distributions\nusing DelimitedFiles\nusing VegaLite\nusing DataFrames\n\nconst INC_SIZE = 1_000\nconst activity_DIR=\"/home/graham_s/OU/DD226/docs/activities/\"\nincomes = zeros( INC_SIZE )\nfor i in 1:INC_SIZE\n    incomes[i] = 1_000*exp(randn()) # kinda log-normal\nend\nsort!( incomes )\nprintln(\"mean  \", mean(incomes))\nprintln( \"median \", median(incomes))\nprintln( \"kurtosis \", kurtosis(incomes))\n\nwritedlm( \"$activity_DIR/activity_1.csv\", incomes )\n\nincframe = DataFrame( incomes=incomes )\n\nplot_1 = incframe |>\n @vlplot(:bar,\n    x={:incomes, bin={maxbins=40}},\n    y=\"count()\")\n\nsave( \"$activity_DIR/activity_1.svg\", plot_1 )\n\nconst GR_SIZE=100\nincomes = zeros(GR_SIZE)\nperson = zeros(Int8,GR_SIZE)\nfor i in 1:GR_SIZE\n    if rand() < (1/3) # (GR_SIZE \u00f7 3)\n        pt = 2\n        pm = 500.0\n    else\n        pt = 1\n        pm = 1000.0\n    end\n    incomes[i] = pm*exp(randn())\n    person[i] = pt\nend\n\nwritedlm(  \"$activity_DIR/activity_2.csv\", person )\n\nnon_pensioners = 5_000\npensioners = 5_000\npopulaton = non_pensioners + pensioners\nwp = pensioners/ (sum( person.==2))\nwnp = non_pensioners / (sum( person.==1))\n\ngw = population/sum(person)\n\nfor i in 1:GR_SIZE\n    global wp, wnp, pe;\n    if person[i]==2\n          pe += wp\n    else\n         pe += wnp\n    end\nend\n\n\nwnp = 74.6268656716418\n\nwp = 151.515151515151\n\ngw = population/(size(person)[1])\n\n\nprint(sum( person.==1))\n\n\nfunction mapep(p::Integer)::String\n\n    if p == 0\n        return \"Not recorded\"\n    elseif p == 1\n        return \"Self-employed\"\n    elseif p in 2:3\n        return \"Employee\"\n    elseif p in 4:5\n        return \"Unemployed/Training Programme\"\n    elseif p in 6:7\n        return \"Retired/unoccupied\"\n\n    end\nend\n\nlcf = CSV.File( \"/home/graham_s/OU/DD226/docs/activities/activity_3.csv\", delim='\\t' ) |> DataFrame\n\nlcf[!,:economic_position] = mapep.(lcf.economic_pos)\n\nplot_inc_vs_cons = lcf |> @vlplot(\n    mark={:point,size=1,opacity=0.5},\n    opactity=0.5,\n    columns=2,\n    y=:total_consumpt,\n    x=:weekly_net_inc,\n    wrap=:economic_position )\n\n\nsave( \"$activity_DIR/activity_5.svg\", plot_inc_vs_cons )\n\nsave( \"$activity_DIR/activity_5.png\", plot_inc_vs_cons )\n", "meta": {"hexsha": "5db8afbeea605393a58801fbbd392bacbafe560f", "size": 2170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/problem_generation.jl", "max_stars_repo_name": "grahamstark/ScottishTaxBenefitModel", "max_stars_repo_head_hexsha": "894f37c6debec271a0e4e4f09aa7b9599423d563", "max_stars_repo_licenses": ["MIT"], "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/problem_generation.jl", "max_issues_repo_name": "grahamstark/ScottishTaxBenefitModel", "max_issues_repo_head_hexsha": "894f37c6debec271a0e4e4f09aa7b9599423d563", "max_issues_repo_licenses": ["MIT"], "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/problem_generation.jl", "max_forks_repo_name": "grahamstark/ScottishTaxBenefitModel", "max_forks_repo_head_hexsha": "894f37c6debec271a0e4e4f09aa7b9599423d563", "max_forks_repo_licenses": ["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.2803738318, "max_line_length": 99, "alphanum_fraction": 0.6548387097, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7674566603215882}}
{"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": "using LinearAlgebra\n\nexport OrthoMADS\n\n\"\"\"\n    OrthoMADS()\n\nReturn an empty OrthoMADS object.\n\nOrthoMADS implements the poll set generation as described in Audet and Le Digabel 2015\nSection 3.4.\n\"\"\"\nstruct OrthoMADS <: AbstractPoll end\n\n\"\"\"\n    GenerateDirections(p::AbstractProblem, o::OrthoMADS)::Matrix\n\nGenerates the poll directions, using the poll set generation\nas described in Audet and Le Digabel 2015 Section 3.4.\n\"\"\"\n(GenerateDirections(p::AbstractProblem, o::OrthoMADS)::Matrix) =\n    GenerateDirections(p.N, o)\nfunction GenerateDirections(N::Int64, ::OrthoMADS)::Matrix\n    dirs_on_unit_sphere = GenerateDirectionsOnUnitSphere(N)\n    H = HouseholderTransform(dirs_on_unit_sphere)\n\treturn hcat(H, -H)\nend\n\n\"\"\"\n    GenerateDirectionsOnUnitSphere(N::Int64)\n\nReturn an `N` length normalized direction on the unit sphere.\n\"\"\"\nfunction GenerateDirectionsOnUnitSphere(N::Int64)\n    dir = randn(N)\n    return dir ./ norm(dir)\nend\n\n\"\"\"\n    HouseholderTransform(q)\n\nApply the Householder transformation to the vector `q`.\n\"\"\"\nfunction HouseholderTransform(q)\n    nq = norm(q)\n    v = q./nq\n    return nq^2 .* (I - 2*v*v')\nend\n", "meta": {"hexsha": "3ea4b4578b37878f46cde5da29393a9dfbb6e4bd", "size": 1128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OrthoMADS.jl", "max_stars_repo_name": "amazing0844/DirectSearch.jl", "max_stars_repo_head_hexsha": "30dac72073919595ff06bd8bc09b8056995e47f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OrthoMADS.jl", "max_issues_repo_name": "amazing0844/DirectSearch.jl", "max_issues_repo_head_hexsha": "30dac72073919595ff06bd8bc09b8056995e47f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OrthoMADS.jl", "max_forks_repo_name": "amazing0844/DirectSearch.jl", "max_forks_repo_head_hexsha": "30dac72073919595ff06bd8bc09b8056995e47f8", "max_forks_repo_licenses": ["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": 86, "alphanum_fraction": 0.7340425532, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7673966883998284}}
{"text": "\"\"\"\n    rotation_matrix_zyx(\u03b11, \u03b12, \u03b13)\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 (\u03b11, \u03b12, \u03b13) (rad).\n\nFrame b is obtained from frame a performing three intrinsic rotations of magnitude\n\u03b11, \u03b12 and \u03b13 in ZYX order.\n\"\"\"\nfunction rotation_matrix_zyx(\u03b11, \u03b12, \u03b13)\n\n    s\u03b11, c\u03b11 = sin(\u03b11), cos(\u03b11)\n    s\u03b12, c\u03b12 = sin(\u03b12), cos(\u03b12)\n    s\u03b13, c\u03b13 = sin(\u03b13), cos(\u03b13)\n\n    R = @SMatrix [\n        c\u03b12 * c\u03b11   (s\u03b13 * s\u03b12 * c\u03b11 - c\u03b13 * s\u03b11)   (c\u03b13 * s\u03b12 * c\u03b11 + s\u03b13 * s\u03b11)\n        c\u03b12 * s\u03b11   (s\u03b13 * s\u03b12 * s\u03b11 + c\u03b13 * c\u03b11)   (c\u03b13 * s\u03b12 * s\u03b11 - s\u03b13 * c\u03b11)\n        -s\u03b12        s\u03b13 * c\u03b12                       c\u03b13 * c\u03b12\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(\u03c8, \u03b8, \u03d5)\n\nCalculate quaternion representation given the Euler angles (\u03c8, \u03b8, \u03d5) (rad).\n\"\"\"\nfunction quaternions(\u03c8, \u03b8, \u03d5)\n\n    s_\u03c82, c_\u03c82 = sin(\u03c8/2), cos(\u03c8/2)\n    s_\u03b82, c_\u03b82 = sin(\u03b8/2), cos(\u03b8/2)\n    s_\u03d52, c_\u03d52 = sin(\u03d5/2), cos(\u03d5/2)\n\n    q0 = c_\u03c82*c_\u03b82*c_\u03d52 + s_\u03c82*s_\u03b82*s_\u03d52\n    q1 = c_\u03c82*c_\u03b82*s_\u03d52 - s_\u03c82*s_\u03b82*c_\u03d52\n    q2 = c_\u03c82*s_\u03b82*c_\u03d52 + s_\u03c82*c_\u03b82*s_\u03d52\n    q3 = s_\u03c82*c_\u03b82*c_\u03d52 - c_\u03c82*s_\u03b82*s_\u03d52\n\n    return @SVector [q0, q1, q2, q3]\nend\n\n\n\"\"\"\n    euler_angles(q0, q1, q2, q3)\n\nCalculate Euler angles (\u03c8, \u03b8, \u03d5) (rad) given the quaternions ``q_0, q_1, q_2, q_3``.\n\"\"\"\nfunction euler_angles(q0, q1, q2, q3)\n\n    \u03c8 = atan(2 * (q1*q2 + q0*q3), q0*q0 + q1*q1 - q2*q2 - q3*q3)\n    \u03b8 = asin(-2 * (q1*q3 - q0*q2))\n    \u03d5 = atan(2 * (q2*q3 + q0*q1), q0*q0 - q1*q1 - q2*q2 + q3*q3)\n\n    return @SVector [mod2pi(\u03c8), \u03b8, \u03d5]\nend\n\n\n\"\"\"\n    body2horizon(x, y, z, \u03c8, \u03b8, \u03d5)\n\nTransform the vector coordintes (x, y, z) given in body axis to local horizon given the\nEuler angles (\u03c8, \u03b8, \u03d5) (rad).\n\"\"\"\nfunction body2horizon(x, y, z, \u03c8, \u03b8, \u03d5)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(\u03c8, \u03b8, \u03d5) * v\n    return rv\nend\n\n\n\"\"\"\n    horizon2body(x, y, z, \u03c8, \u03b8, \u03d5)\n\nTransform the vector coordintes (x, y, z) given in local horizon axis to body given the\nEuler angles (\u03c8, \u03b8, \u03d5) (rad).\n\"\"\"\nfunction horizon2body(x, y, z, \u03c8, \u03b8, \u03d5)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(\u03c8, \u03b8, \u03d5)) * 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, \u03b1, \u03b2)\n\nTransform the vector coordintes (x, y, z) given in wind axis to body given the angle of\nattack (\u03b1) and the angle of sideslip (\u03b2) (rad).\n\"\"\"\nfunction wind2body(x, y, z, \u03b1, \u03b2)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(-\u03b2, \u03b1, 0)) * v\n    return rv\nend\n\n\n\"\"\"\n    body2wind(x, y, z, \u03b1, \u03b2)\n\nTransform the vector coordintes (x, y, z) given in body axis to wind given the angle of\nattack (\u03b1) and the angle of sideslip (\u03b2) (rad).\n\"\"\"\nfunction body2wind(x, y, z, \u03b1, \u03b2)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(-\u03b2, \u03b1, 0) * v\n    return rv\nend\n\n\n\"\"\"\n    wind2horizon(x, y, z, \u03c7, \u03b3, \u03bc)\n\nTransform the vector coordintes (x, y, z) given in wind axis to local horizon given the\nvelocity angles (\u03c7, \u03b3, \u03bc) (rad).\n\"\"\"\nfunction wind2horizon(x, y, z, \u03c7, \u03b3, \u03bc)\n    v = @SVector [x, y, z]\n    rv = rotation_matrix_zyx(\u03c7, \u03b3, \u03bc) * v\n    return rv\nend\n\n\n\"\"\"\n    horizon2wind(x, y, z, \u03c7, \u03b3, \u03bc)\n\nTransform the vector coordintes (x, y, z) given in local horizon axis to wind given the\nvelocity angles (\u03c7, \u03b3, \u03bc) (rad).\n\"\"\"\nfunction horizon2wind(x, y, z, \u03c7, \u03b3, \u03bc)\n    v = @SVector [x, y, z]\n    rv = transpose(rotation_matrix_zyx(\u03c7, \u03b3, \u03bc)) * 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 - \u03c0/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 - \u03c0/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 \u2208 one(T):limit\n    d\u2081 = divisors(n)\n    p = sum(d\u2081)\n    d\u2082 = divisors(p)\n    s = sum(d\u2082)\n\n    if s == n && d\u2081 \u2260 d\u2082 && s \u2209 t\n      push!(t, s)\n      push!(t, p)\n      push!(v, (n => d\u2081, p => d\u2082))\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\u2081::Any, n\u2082::Any)\n  throw(ArgumentError(\"n\u2081 and n\u2082 should be Integers\"))\nend\n\nfunction is_amicable(n\u2081::DT, n\u2082::DT)::Bool\n  d\u2081 = divisors(n\u2081)\n  d\u2082 = divisors(n\u2082)\n  n\u2082 == sum(d\u2081) && n\u2081 == sum(d\u2082)\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 \u2264 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\u0302,w\u0302  = 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\u0302)\n#     phip      = [jacobian(shandler,x)[1] for x in x\u0302]\n#     plot!(fig,x\u0302,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\u03b8::Vector{T}\n    sin\u03b8::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\u03b8[i], sin\u03b8[i]) forms a rotation matrix\n    ## Gi = [cos\u03b8[i]  -sin\u03b8[i]]\n    ##      [sin\u03b8[i]   cos\u03b8[i]]\n    cos\u03b8 = ones(T, n)\n    sin\u03b8 = 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\u03b8 and sin\u03b8\n        x = H[i, i]\n        y = H[i + 1, i]\n        r = hypot(x, y)\n        ## If r is too small, (cos\u03b8, sin\u03b8) stores the original values (1, 0)\n        if r < eps(T)\n            r = zero(T)\n        else\n            cos\u03b8[i] = x / r\n            sin\u03b8[i] = -y / r\n        end\n        ## Apply the rotation on the left H -> Gi * H\n        ## H[i, :]     <- cos\u03b8[i] * H[i, :] - sin\u03b8[i] * H[i +1, :]\n        ## H[i + 1, :] <- sin\u03b8[i] * H[i, :] + cos\u03b8[i] * H[i +1, :]\n        H[i, i] = r\n        H[i + 1, i] = zero(T)\n        c = cos\u03b8[i]\n        s = sin\u03b8[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\u03b8[i] * H[:, i] - sin\u03b8[i] * H[:, i + 1]\n    ## H[:, i + 1] <- sin\u03b8[i] * H[:, i] + cos\u03b8[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\u03b8[i] * tmp - sin\u03b8[i] * H[j, i + 1]\n            H[j, i + 1] = sin\u03b8[i] * tmp + cos\u03b8[i] * H[j, i + 1]\n        end\n    end\n\n    return HessenbergQR(cos\u03b8, sin\u03b8)\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\u03b8[i], sin\u03b8[i]) forms a rotation matrix\n    ## Gi = [cos\u03b8[i]  -sin\u03b8[i]]\n    ##      [sin\u03b8[i]   cos\u03b8[i]]\n    cos\u03b8 = ones(T, n)\n    sin\u03b8 = zeros(T, n)\n\n    for i = 1:(n - 1)\n        ## Calculate cos\u03b8 and sin\u03b8\n        x = H[i, i]\n        y = H[i + 1, i]\n        r = hypot(x, y)\n        ## If r is too small, (cos\u03b8, sin\u03b8) stores the original values (1, 0)\n        if r < eps(T)\n            r = zero(T)\n        else\n            cos\u03b8[i] = x / r\n            sin\u03b8[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\u03b8[i]\n        s = sin\u03b8[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\u03b8[i] * H[:, i] - sin\u03b8[i] * H[:, i + 1]\n    ## H[:, i + 1] <- sin\u03b8[i] * H[:, i] + cos\u03b8[i] * H[:, i + 1]\n    for i = 1:(n - 1)\n        c = cos\u03b8[i]\n        s = sin\u03b8[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\u03b8, sin\u03b8)\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\u03b8 = qr.cos\u03b8\n    sin\u03b8 = qr.sin\u03b8\n    n = length(cos\u03b8)\n    ## A[:, i]     <- cos\u03b8[i] * A[:, i] - sin\u03b8[i] * A[:, i + 1]\n    ## A[:, i + 1] <- sin\u03b8[i] * A[:, i] + cos\u03b8[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\u03b8[i] * tmp - sin\u03b8[i] * A[j, i + 1]\n            A[j, i + 1] = sin\u03b8[i] * tmp + cos\u03b8[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": "# Test get/set objective coefficients in LP\n\nusing Xpress, Compat.Test\n\n@testset \"Basics 3\" begin\n    # original model\n    #\n    #   maximize  2x + 2y\n    #\n    #   s.t. 0.2 <= x, y <= 1\n\n    model = xpress_model(\n    name=\"lp_03\",\n    sense=:maximize,\n    f=[2.0, 2.0],\n    lb=[0.2, 0.2],\n    ub=[1.0, 1.0])\n\n    lb_ = lowerbounds(model)\n    ub_ = upperbounds(model)\n    c_ = objcoeffs(model)\n\n    @test lb_ == [0.2, 0.2]\n    @test ub_ == [1.0, 1.0]\n    @test c_ == [2.0, 2.0]\n\n    optimize(model)\n\n    ans = get_optiminfo(model)\n    @test ans.status_lp == :optimal\n\n    @test isapprox(get_solution(model), [1, 1]; atol = 1e-3)\n    @test isapprox(get_objval(model), 4; atol = 1e-3)\n\n    # change objective (warm start)\n    #\n    #    maximize x - y\n    #\n    #    s.t. 0.2 <= x, y <= 1\n    #\n\n    set_objcoeffs!(model, [1, -1])\n\n    c_ = objcoeffs(model)\n    @test c_ == [1.0, -1.0]\n\n    optimize(model)\n\n    ans = get_optiminfo(model)\n    @test ans.status_lp == :optimal\n\n    @test isapprox(get_solution(model), [1.0, 0.2]; atol = 1e-3)\n    @test isapprox(get_objval(model), 0.8; atol = 1e-3)\nend", "meta": {"hexsha": "a3aeca31156a9a2c719892d6555c9dc708532003", "size": 1098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/lp_03.jl", "max_stars_repo_name": "JuliaTagBot/Xpress.jl_bkp", "max_stars_repo_head_hexsha": "c868c09040077035b0de2712d29c8e6ea90d54c4", "max_stars_repo_licenses": ["MIT"], "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/lp_03.jl", "max_issues_repo_name": "JuliaTagBot/Xpress.jl_bkp", "max_issues_repo_head_hexsha": "c868c09040077035b0de2712d29c8e6ea90d54c4", "max_issues_repo_licenses": ["MIT"], "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/lp_03.jl", "max_forks_repo_name": "JuliaTagBot/Xpress.jl_bkp", "max_forks_repo_head_hexsha": "c868c09040077035b0de2712d29c8e6ea90d54c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:29:00.000Z", "avg_line_length": 20.3333333333, "max_line_length": 64, "alphanum_fraction": 0.5482695811, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7673751249359678}}
{"text": "\"\"\"\r\n    FrankCopula{d,T}\r\n\r\nFields:\r\n  - \u03b8::Real - parameter\r\n\r\nConstructor\r\n\r\n    FrankCopula(d, \u03b8)\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    \u03b8::T\r\nend\r\nFrankCopula(d,\u03b8) = \u03b8 >= 0 ? FrankCopula{d,typeof(\u03b8)}(\u03b8) : @error \"Theta must be positive\"\r\n\u03d5(  C::FrankCopula,       t) = -log(1+exp(-t)*(exp(-C.\u03b8)-1))/C.\u03b8\r\n\u03d5\u207b\u00b9(C::FrankCopula,       t) = -log((exp(-t*C.\u03b8)-1)/(exp(-C.\u03b8)-1))\r\n\r\nD\u2081 = GSL.sf_debye_1 # sadly, this is C code.\r\n# could be replaced by : \r\n# using QuadGK\r\n# D\u2081(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\u03c4(C::FrankCopula) = 1+4(D\u2081(C.\u03b8)-1)/C.\u03b8\r\nfunction \u03c4\u207b\u00b9(::Type{FrankCopula},\u03c4)\r\n    if \u03c4 == zero(\u03c4)\r\n        return \u03c4\r\n    end\r\n    x\u2080 = (1-\u03c4)/4\r\n    return Roots.fzero(x -> (1-D\u2081(x))/x - x\u2080, 10)\r\nend\r\n    \r\n\r\nradial_dist(C::FrankCopula) = Logarithmic(1-exp(-C.\u03b8))\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": "# Test the finite differencing technique\n@testset \"finite_difference\" begin\n\nfunction f!(fvec, x)\n    fvec[1] = (x[1]+3)*(x[2]^3-7)+18\n    fvec[2] = sin(x[2]*exp(x[1])-1)\nend\n\nr = nlsolve(f!, [ 0.1; 1.2])\n\n@test norm(r.zero - [ 0; 1]) < 1e-8\n\nend", "meta": {"hexsha": "1a2059ab95e040e99bc0d1ebcf5bf6b1e9745ab9", "size": 246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/finite_difference.jl", "max_stars_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_stars_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": "test/finite_difference.jl", "max_issues_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_issues_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": "test/finite_difference.jl", "max_forks_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_forks_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": 18.9230769231, "max_line_length": 40, "alphanum_fraction": 0.5853658537, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.76737512115666}}
{"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\u2014such as the sigmoid function or a piecewise linear function\u2014then 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 \u2014 in effect \u2014 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, \u03c3)` as our model. Now we want to construct multiple layers and chain them together:\n\nlayer1 = Dense(2, 4, \u03c3)\nlayer2 = Dense(4, 3, \u03c3)\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, \u03c3)) # 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, \u03c3), 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": "\"\"\"\n    $(SIGNATURES)\n\nTest by regression that simulated data are consistent with \"true\" outcomes.\n\nRegress simulated on true.\nCheck for 0 intercept, 1 slope.\n\nNote: If data are very far from 0, then intercept can be quite a bit off.\n\n# Arguments\n- trueM\n    true outcome by state\n- simM\n    simulated outcome by state\n- wtM\n    weights (e.g. to downweight rare states or states that cannot be solved precisely)\n    scalar weights are expanded. Provide wtM = []\n- doShow\n    show scatter plot?\n\n# Outputs\ndev = max(abs(beta - [0;1]) / se(beta))\n    how many std deviations are regression coefficient from 45 degree line?\nbetaV\n    regression coefficients; should be [0;1]\nseV\n    std errors\n\nChange:\n    test hypothesis of 0 intercept and unit slope. Return prob of reject\n    GLM cannot do that yet.\n\"\"\"\nfunction regression_test(trueM :: AbstractArray{F1}, simM :: AbstractArray{F1};\n    weights = similar(trueM, 0)) where F1 <: AbstractFloat\n\n    @assert size(trueM) == size(simM)\n    n = length(trueM);\n    @assert n > 2  \"Too few observations: $n\"\n\n    m = fit(LinearModel, hcat(ones(F1, n),  vec(trueM)),  vec(simM);\n        wts = weights);\n    betaV = coef(m);\n    seV = stderror(m);\n    dev = maximum(abs.(betaV .- [zero(F1), one(F1)]) ./ max.(F1(0.01), seV));\n    return dev, betaV, seV\nend\n\n# ---------------\n", "meta": {"hexsha": "25b5c62a5b30da790b6b726d0fd4326fa3cbe21c", "size": 1318, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression_test.jl", "max_stars_repo_name": "hendri54/EconometricsLH", "max_stars_repo_head_hexsha": "1edb41e016738ab47471a264c2c699876f7286e9", "max_stars_repo_licenses": ["MIT"], "max_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_test.jl", "max_issues_repo_name": "hendri54/EconometricsLH", "max_issues_repo_head_hexsha": "1edb41e016738ab47471a264c2c699876f7286e9", "max_issues_repo_licenses": ["MIT"], "max_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_test.jl", "max_forks_repo_name": "hendri54/EconometricsLH", "max_forks_repo_head_hexsha": "1edb41e016738ab47471a264c2c699876f7286e9", "max_forks_repo_licenses": ["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.36, "max_line_length": 86, "alphanum_fraction": 0.660091047, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7673516989638114}}
{"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": "@testset \"Searches\" begin\n    @testset \"Searches: Binary\" begin\n        @testset \"binary_search - first method\" begin\n            sample = [0, 23, 52, 552, 555, 602, 1004]\n            reversed_sample = reverse(sample)\n            unsorted_sample = [124, 53, 21, 163]\n            @test binary_search(sample, 52) == 3:3\n            @test binary_search(sample, 602) == 6:6\n            @test binary_search(reversed_sample, 52; rev=true) == 5:5\n            @test binary_search(reversed_sample, 602; rev=true) == 2:2\n            @test_throws ErrorException binary_search(unsorted_sample, 21)  # throws an error\n        end\n        @testset \"binary_search - second method\" begin\n            # Second method used for exponential search\n            arr = [1, 2, 3, 4, 13, 15, 20]\n            # The next three values used are the result of the while-loop inside `exponential search`\n            @test binary_search(arr, 4, 7, 4) == \"Element present at index 4\"\n            @test binary_search(arr, 4, 7, 10) == \"Element not present in array\"\n        end\n    end\n\n    @testset \"Searches: Linear\" begin\n        array = [1, 3, 4, 7, 8, 11]\n        linear_search(array, 3)\n        linear_search(array, 8)\n        linear_search(array, 12)\n    end\n\n    @testset \"Searches: Exponential\" begin\n        arr = [1, 2, 3, 4, 13, 15, 20]\n        x = 4\n        n = size(arr)[1]\n        l = 1\n        r = n\n        @test exponential_search(arr, 1) == \"Element present at index 1\"\n        @test exponential_search(arr, x) == \"Element present at index 4\"\n        @test exponential_search(arr, 100) == \"Element not present in array\"\n    end\n\n    @testset \"Searches: Interpolation\" begin\n        arr = [1, 2, 3, 4, 13, 15, 20]\n        x = 15\n        n = size(arr)[1]\n        l = 1\n        r = n\n\n        interpolation_search(arr, l, r, x)\n    end\n\n    @testset \"Searches: Jump\" begin\n        arr = [1, 2, 3, 31, 4, 13]\n        x = 31\n        jump = 2 # optimum is sqroot(n)\n        n = size(arr)[1]\n\n        jump_search(arr, x, jump)\n    end\nend\n", "meta": {"hexsha": "6514386e6dcfbd4b3c6a6c1eca40fba770671faf", "size": 2017, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/searches.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": "test/searches.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": "test/searches.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": 34.186440678, "max_line_length": 101, "alphanum_fraction": 0.5557759048, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.7673468891176654}}
{"text": "# # Foundations of Bilevel Programming: Example 2.1\n# This example is from the book _Foundations of Bilevel Programming_ by Stephan\n# Dempe, Chapter 3.2, Page 25. [url](https://www.springer.com/gp/book/9781402006319)\n# Moving the bound on x to lower level\n\n\n# Model of the problem\n\n# First level\n# ```\n# Min 3x + y \n# s.t.\n# 0 <= y <=8\n# ```\n# Second level\n# ```\n# Min -x\n# s.t.\n# x + y <= 8\n# 4x + y >= 8\n# 2x + y <= 13\n# 2x - y <= 0\n# x <= 5\n# ```\n\n\nusing BilevelJuMP\nusing Ipopt\nusing JuMP\nusing Test\n\nmodel = BilevelModel(Ipopt.Optimizer, mode = BilevelJuMP.ProductMode(1e-9))\n\n# First we need to create all of the variables in the upper and lower problems:\n\n@variable(Lower(model), x, start = 3.5 * 8 / 15)\n\n#-\n\n@variable(Upper(model), y, start = 8 / 15)\n\n# Then we can add the objective and constraints of the upper problem:\n\n@objective(Upper(model), Min, 3x + y)\n#-\n\n@constraint(Upper(model), y <= 8)\n@constraint(Upper(model), y >= 0)\n\n# Followed by the objective and constraints of the lower problem:\n\n@objective(Lower(model), Min, -x)\n\n#-\n@constraint(Lower(model), x +  y <= 8)\n@constraint(Lower(model), 4x +  y >= 8)\n@constraint(Lower(model), 2x +  y <= 13)\n@constraint(Lower(model), 2x - 7y <= 0)\n@constraint(Lower(model), x <= 5)\n\n# Now we can solve the problem and verify the solution again that reported by\n# Dempe.\n\noptimize!(model)\n\n@test objective_value(model) \u2248 3 * (3.5 * 8 / 15) + (8 / 15) atol=1e-3\n@test value(x) \u2248 3.5 * 8 / 15 atol=1e-6\n@test value(y) \u2248 8 / 15 atol=1e-6\n\n# TODO: why are these commented out?    #src\n# @test dual(l2) #\u2248 [0] atol=atol       #src\n# @test dual(l4) #\u2248 [0] atol=atol       #src\n", "meta": {"hexsha": "8e007aab44146372f356bc91645efe5b9929cf80", "size": 1630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/FOBP_example2.2.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_example2.2.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_example2.2.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.3287671233, "max_line_length": 84, "alphanum_fraction": 0.6417177914, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7673468881357511}}
{"text": "using Base.Profile;\r\n\r\nfunction print_sudoku(m, n, sudoku)\r\n    println(m, \" \", n);\r\n    println(sudoku);\r\nend\r\n\r\nfunction find_empty(m, n, sudoku)\r\n    for i in 1:m*n, j in 1:m*n\r\n        if sudoku[i, j] == 0\r\n            return (i, j);\r\n        end\r\n    end\r\n    return (m * n + 1, m * n + 1);\r\nend\r\n\r\n# Finds an empty cell using the most constrained variable heuristic\r\nfunction smart_find_empty(m, n, sudoku, used_row, used_col, used_box)\r\n    besti = m * n + 1;\r\n    bestj = m * n + 1;\r\n    best = m * n + 1;\r\n    remaining = 0;\r\n    for i in 1:m*n, j in 1:m*n\r\n        if sudoku[i, j] == 0\r\n            remaining += 1;\r\n            box = div(i-1, m) * m + div(j-1, n) + 1;\r\n            options = 0;\r\n            for v in 1:m*n\r\n                if used_row[i, v] == 0 && used_col[j, v] == 0 &&\r\n                        used_box[box, v] == 0\r\n                    options += 1;\r\n                end\r\n            end\r\n            if options == 0\r\n                return (0, 0);\r\n            end\r\n            if options < best\r\n                besti = i;\r\n                bestj = j;\r\n                best = options;\r\n            end\r\n        end\r\n    end\r\n    if remaining == 0\r\n        return (m * n + 1, m * n + 1);\r\n    end\r\n\r\n    return (besti, bestj)\r\nend\r\n\r\n# Basic backtracking using the arrays storing whether certain digits\r\n# have already appeared to speed up checking.\r\nfunction smart_solve(m, n, sudoku, used_row, used_col, used_box)\r\n\r\n    i, j = smart_find_empty(m, n, sudoku, used_row, used_col, used_box);\r\n    if i == 0\r\n        return false;\r\n    end\r\n    if i > m * n\r\n        return true;\r\n    end\r\n\r\n    bi = div(i-1, m);\r\n    bj = div(j-1, n) + 1;\r\n    box = bi * m + bj;\r\n\r\n    for v in 1:m*n\r\n        if used_row[i, v] == 0 && used_col[j, v] == 0 &&\r\n                used_box[box, v] == 0\r\n            sudoku[i, j] = v;\r\n            used_row[i, v] = 1;\r\n            used_col[j, v] = 1;\r\n            used_box[box, v] = 1;\r\n            if smart_solve(m, n, sudoku, used_row, used_col, used_box)\r\n                return true;\r\n            end\r\n            sudoku[i, j] = 0;\r\n            used_row[i, v] = 0;\r\n            used_col[j, v] = 0;\r\n            used_box[box, v] = 0;\r\n        end\r\n    end\r\n\r\n    return false;\r\nend\r\n\r\n# Setup for the slightly smarter solve\r\n# Initialises arrays storing whether each type of digit has occurred in\r\n# each row, column and box and then passes this into the main function\r\nfunction smart_solve(m, n, sudoku)\r\n    used_row = zeros(Int64, m*n, m*n);\r\n    used_col = zeros(Int64, m*n, m*n);\r\n    used_box = zeros(Int64, m*n, m*n);\r\n\r\n    for i in 1:m*n, j in 1:m*n\r\n        if sudoku[i, j] > 0\r\n            used_row[i, sudoku[i, j]] = 1;\r\n            used_col[j, sudoku[i, j]] = 1;\r\n        end\r\n    end\r\n    for i in 1:n, j in 1:m\r\n        bi = (i-1) * m + 1;\r\n        bj = (j-1) * n + 1;\r\n        box = (i - 1) * m + j;\r\n        for k in bi:bi+m-1, l in bj:bj+n-1\r\n            if sudoku[k, l] > 0\r\n                used_box[box, sudoku[k, l]] = 1;\r\n            end\r\n        end\r\n    end\r\n\r\n    if smart_solve(m, n, sudoku, used_row, used_col, used_box)\r\n        return true;\r\n    end\r\n    return false;\r\nend\r\n\r\n# Dumbest backtracking solver\r\n# Passes over all neighbours each time to check for a colliding value\r\nfunction solve(m, n, sudoku)\r\n    i, j = find_empty(m, n, sudoku);\r\n\r\n    if i > m * n\r\n        return true;\r\n    end\r\n\r\n    for v in 1:m*n\r\n\r\n        # Determine if v is a valid option for this cell\r\n        valid = true;\r\n        for k in 1:m*n\r\n            if (k != j && sudoku[i, k] == v) ||\r\n                    (k != i && sudoku[k, j] == v)\r\n                valid = false;\r\n                break;\r\n            end\r\n        end\r\n        # Check if v has been used in this box\r\n        if valid\r\n            bi = div(i-1, m) * m + 1;\r\n            bj = div(j-1, n) * n + 1;\r\n            for k in bi:bi+m-1, l in bj:bj+n-1\r\n                if sudoku[k, l] == v\r\n                    valid = false;\r\n                    break;\r\n                end\r\n            end\r\n        end\r\n\r\n        if valid\r\n            sudoku[i, j] = v\r\n            if (solve(m, n, sudoku))\r\n                return true;\r\n            end\r\n        end\r\n\r\n    end\r\n\r\n    sudoku[i, j] = 0;\r\n    return false;\r\nend\r\n\r\nfunction try_solve(m, n, sudoku)\r\n    s = copy(sudoku);\r\n    smart_solve(m, n, s);\r\nend\r\n\r\nf = open(\"sudokus/2.sudoku\");\r\nm, n = [parse(Int64, s) for s = split(readline(f), \" \")];\r\n\r\nsudoku_raw = round(Int64, readdlm(f));\r\nclose(f);\r\nsudoku = copy(sudoku_raw);\r\n\r\nprint_sudoku(m, n, sudoku);\r\n\r\nx = smart_solve(m, n, sudoku);\r\nprintln(x);\r\n\r\nprint_sudoku(m, n, sudoku);\r\n\r\n# Actual sudoku solve\r\nf = open(\"sudokus/4.sudoku\");\r\nm, n = [parse(Int64, s) for s = split(readline(f), \" \")];\r\n\r\nsudoku_raw = round(Int64, readdlm(f));\r\nclose(f);\r\n\r\nprint_sudoku(m, n, sudoku_raw);\r\nsudoku = copy(sudoku_raw);\r\n\r\nx = smart_solve(m, n, sudoku);\r\nprintln(x);\r\nprint_sudoku(m, n, sudoku);\r\n", "meta": {"hexsha": "59d8ea94f1cfd1f186ad0ab5b804012009ed872d", "size": 4938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "solver.jl", "max_stars_repo_name": "nick-hiebl/n-doku", "max_stars_repo_head_hexsha": "7fddc409c85157debf679e431620f9af6ba7abb3", "max_stars_repo_licenses": ["MIT"], "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.jl", "max_issues_repo_name": "nick-hiebl/n-doku", "max_issues_repo_head_hexsha": "7fddc409c85157debf679e431620f9af6ba7abb3", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "nick-hiebl/n-doku", "max_forks_repo_head_hexsha": "7fddc409c85157debf679e431620f9af6ba7abb3", "max_forks_repo_licenses": ["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.3230769231, "max_line_length": 73, "alphanum_fraction": 0.4694208181, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7673468820659487}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 0b868b30-6420-11eb-18f9-1592f7542fe6\nbegin\n    using PlutoUI\n    using Plots\n    using Printf\n\tusing SpecialFunctions\nend\n\n# \u2554\u2550\u2561 4c4fff40-64c8-11eb-2c45-57f4793ee997\nmd\"_Parabolic Partial Differential Equation, version 1_\"\n\n# \u2554\u2550\u2561 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(\u0394t,\u0394y,\u03bd)\n\t\tDuFortFrankel(\u0394t,\u0394y,\u03bd)\n\t\tLaasonen(\u0394t,\u0394y,\u03bd)\n\t\tCrankNicolson(\u0394t,\u0394y,\u03bd)\n\nIf the arguments are missing, it will use the default values.\n    \n\t\tFTCS(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\n\t\tDuFortFrankel(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\n\t\tLaasonen(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\n\t\tCrankNicolson(\u0394t=0.002,\u0394y=0.001,\u03bd=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\u2080 and the upper plate is stationary. The equation for the system can be represented by:\n\n$$\\frac{\u2202u}{\u2202t}=\u03b1\\frac{\u2202\u00b2u}{\u2202x\u00b2}$$\n\nBoundary conditions for the system:\n\n$$u=U\u2080=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{\u03b1(\u0394t)}{\u0394x^{2}}$$\n\nFor the stability condition:\n\n$$\\frac{\u03b1(\u0394t)}{\u0394x^{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{\u03b1(\u0394t)}{\u0394x^{2}}$$\n\nFor the stability condition:\n\n$$\\frac{\u03b1(\u0394t)}{\u0394x^{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=\u0394t.\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{\u03b1(\u0394t)}{\u0394x^{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{\u03b1(\u0394t)}{\u0394x^{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# \u2554\u2550\u2561 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(\u0394t,\u0394y,\u03bd)\nIf the arguments are missing, it will use the default values.\n    \n\t\tFTCS(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction FTCS(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\n\t#\u03bd=0.000217 # viscosity [m\u00b2/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#\u0394t = 0.002 # Time increment\n\tNt = T/\u0394t+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#\u0394y = 0.001 # Spacing between node points\n\ty = 0:\u0394y:h # y-coordinates\n\tNx = h/\u0394y+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU\u2080 = 1 # Plate speed\n\td = \u03bd*\u0394t/(\u0394y)^2\n\t#Initializing\n\tu = zeros(Nx,Nt) \n\t\n\t# Boundary Conditions\n\tu[1,:] = [U\u2080 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\u2080\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# \u2554\u2550\u2561 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(\u0394t,\u0394y,\u03bd)\nIf the arguments are missing, it will use the default values.\n    \n\t\tDuFortFrankel(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction DuFortFrankel(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\n\t#\u03bd=0.000217 # viscosity [m\u00b2/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#\u0394t = 0.002 # Time increment\n\tNt = T/\u0394t+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#\u0394y = 0.001 # Spacing between node points\n\ty = 0:\u0394y:h # y-coordinates\n\tNx = h/\u0394y+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU\u2080 = 1 # Plate speed\n\td = \u03bd*\u0394t/(\u0394y)^2\n\t#Initializing\n\tu = zeros(Nx,Nt) \n\t\n\t# Boundary Conditions\n\tu[1,:] = [U\u2080 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\u2080\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# \u2554\u2550\u2561 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(\u0394t,\u0394y,\u03bd)\nIf the arguments are missing, it will use the default values.\n    \n\t\tLaasonen(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction Laasonen(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\n\t#\u03bd=0.000217 # viscosity [m\u00b2/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#\u0394t = 0.002 # Time increment\n\tNt = T/\u0394t+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#\u0394y = 0.001 # Spacing between node points\n\ty = 0:\u0394y:h # y-coordinates\n\tNx = h/\u0394y+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU\u2080 = 1 # Plate speed\n\td = \u03bd*\u0394t/(\u0394y)^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\u2080\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\u2080\n\t\n\tfor ii=2:Nt-1\n\t\t# Boundary Conditions\n\t\tA[1,1] = 1\n\t\tb[1] = U\u2080\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# \u2554\u2550\u2561 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(\u0394t,\u0394y,\u03bd)\nIf the arguments are missing, it will use the default values.\n    \n\t\tCrankNicolson(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\nFurkan Oz,\nfoz@okstate.edu, \n    \n\"\"\"\nfunction CrankNicolson(\u0394t=0.002,\u0394y=0.001,\u03bd=0.000217)\n\t#\u03bd=0.000217 # viscosity [m\u00b2/s]\n\th = 0.04 # Distance between 2 plate [m]\n\tT = 1.25 # Total time [s]\n\t#\u0394t = 0.002 # Time increment\n\tNt = T/\u0394t+1 # Number of time step\n\tNt = round(Int32,Nt)\n\t\n\t#\u0394y = 0.001 # Spacing between node points\n\ty = 0:\u0394y:h # y-coordinates\n\tNx = h/\u0394y+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\t\n\tU\u2080 = 1 # Plate speed\n\td = \u03bd*\u0394t/(\u0394y)^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\u2080\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\u2080\n\t\n\tfor ii=3:Nt-1\n\t\t# Boundary Conditions\n\t\tA[1,1] = 1\n\t\tb[1] = U\u2080\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# \u2554\u2550\u2561 8939c23e-642a-11eb-2de6-ade5ae2f4b4d\nfunction Analytical(t,\u0394y=0.001,\u03bd=0.000217)\n\t#\u03bd=0.000217 # viscosity [m\u00b2/s]\n\th = 0.04 # Distance between 2 plate [m]\n\ty = 0:\u0394y:h\n\tNx = h/\u0394y+1 # Number of Node points\n\tNx = round(Int32,Nx)\n\tU\u2080 = 1 # Plate speed\n\t\u03b7 = [y[i]/(2*sqrt(\u03bd*t)) for i=1:Nx]\n\t\u03b7\u2081= h/(2*sqrt(\u03bd*t))\n\tu = [U\u2080*(erfc(\u03b7[i])-erfc(2*\u03b7\u2081-\u03b7[i])+erfc(2*\u03b7\u2081+\u03b7[i])-erfc(4*\u03b7\u2081-\u03b7[i])+erfc(4*\u03b7\u2081+\u03b7[i])-erfc(8*\u03b7\u2081-\u03b7[i])+erfc(8*\u03b7\u2081+\u03b7[i])-erfc(16*\u03b7\u2081-\u03b7[i])) for i=1:Nx]\n\treturn u,y\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000b868b30-6420-11eb-18f9-1592f7542fe6\n# \u255f\u25004c4fff40-64c8-11eb-2c45-57f4793ee997\n# \u255f\u250056d1f810-64c8-11eb-3e0d-81c0bbafdc62\n# \u255f\u250029683fb0-6419-11eb-05d0-2d7392bc8afa\n# \u255f\u250036be1c60-6442-11eb-204a-b37677c1acfd\n# \u255f\u2500899d6a70-6448-11eb-2870-692c6e93c421\n# \u255f\u25009c410110-644c-11eb-3bd9-93935242ac98\n# \u255f\u25008939c23e-642a-11eb-2de6-ade5ae2f4b4d\n# \u255f\u250070d8c3ee-641f-11eb-1d57-a943a361c397\n# \u255f\u250095697270-6427-11eb-02be-bf3b75fbbd33\n# \u255f\u2500b1e5b270-643f-11eb-1a37-e3227c598177\n# \u255f\u25008c11e680-6440-11eb-076a-0b1e169ef37a\n# \u255f\u250033a79720-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": "using Flux, Flux.Data.MNIST, Statistics, BSON, Random, StatsBase, Plots; pyplot()\nusing Flux: params, onehotbatch, crossentropy, update!\nRandom.seed!(0)\n\nnTrain = 20000\nminiBatchSize = 1000\nimgs   = Flux.Data.MNIST.images()[1:nTrain]\nlabels = Flux.Data.MNIST.labels()[1:nTrain]\n\ntrainData = hcat([vcat(float.(imgs[i])...) for i in 1:nTrain]...)\ntrainLabels = labels\n\ntestImgs = Flux.Data.MNIST.images(:test)\ntestLabels = Flux.Data.MNIST.labels(:test)\nnTest = length(testImgs)\ntestData = hcat([vcat(float.(testImgs[i])...) for i in 1:nTest]...)\n\nW = randn(10,28*28)\nb = randn(10)\n\nlogisticM(imgVec) = softmax(W*imgVec .+ b)\nlogisticMclassifier(imgVec) = argmax(logisticM(imgVec))-1\nloss(x,y) = crossentropy(logisticM(x),onehotbatch(y,0:9))\nopt = ADAM(0.01)\n\nlossValue = 0.0\nlossArray = []\nepochNum = 0\nwhile true\n    global lossValue\n    prevLossValue = lossValue\n    for batch in Iterators.partition(1:nTrain,miniBatchSize)\n      gs = gradient(()->loss(trainData[:,batch],trainLabels[batch]),params(W,b))\n      for p in (W,b)\n          update!(opt,p,gs[p])\n      end\n    end\n    global epochNum += 1\n    lossValue = loss(trainData,trainLabels)\n    push!(lossArray,lossValue)\n    print(\".\")\n    abs(prevLossValue-lossValue) < 5e-4 && break\nend\n\nprintln(\"\\nNumber of epochs: \", epochNum)\nacccuracy = mean([logisticMclassifier(testData[:,k]) for k in 1:nTest]\n                .== testLabels)\nprintln(\"Accuracy: \", acccuracy)\n\nplot(lossArray, xlabel = \"Epoch\", ylabel = \"Cross Entropy Loss\", legend = false)\n", "meta": {"hexsha": "439068fa8492aa632c0cb7ca653b39c60126f4a6", "size": 1504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "9_chapter/logisticRegressionMNIST.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": "9_chapter/logisticRegressionMNIST.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": "9_chapter/logisticRegressionMNIST.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.4901960784, "max_line_length": 81, "alphanum_fraction": 0.6815159574, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7673166951806927}}
{"text": "using Test\nusing CartesianMesh\n# using Revise\nusing CutCellDG\ninclude(\"../useful_routines.jl\")\n\ncm = CutCellDG.CellMap([0.,2.],[3.,3.])\n@test CutCellDG.dimension(cm) == 2\n@test CutCellDG.jacobian(cm) == [1.5,0.5]\n@test allapprox(cm([0.,0.]),[1.5,2.5])\n@test allapprox(cm([1.,0.]),[3.,2.5])\n\nmesh = UniformMesh([0.,0.],[1.,1.],[2,2])\n@test allequal(CutCellDG.elements_per_mesh_side(mesh),[2,2])\ncellmaps = CutCellDG.construct_cell_maps(mesh)\ncm1 = CutCellDG.CellMap([0.,0.],[0.5,0.5])\ncm2 = CutCellDG.CellMap([0.,0.5],[0.5,1.])\ncm3 = CutCellDG.CellMap([0.5,0.],[1.,0.5])\ncm4 = CutCellDG.CellMap([0.5,0.5],[1.,1.])\n@test allequal(cellmaps,[cm1,cm2,cm3,cm4])\n\ncm = CutCellDG.CellMap([0.,0.],[1.,1.])\n@test CutCellDG.determinant_jacobian(cm) \u2248 0.25\n\ncm = CutCellDG.CellMap([1.,1.],[5.,8.])\n@test CutCellDG.determinant_jacobian(cm) \u2248 7.0\n\ncm = CutCellDG.CellMap([2.,1.],[4.,2.])\n@test allapprox(CutCellDG.inverse(cm,[3,1.5]),[0.,0.])\n@test allapprox(CutCellDG.inverse(cm,[4,2.]),[1.,1.])\n@test allapprox(CutCellDG.inverse(cm,[2,1]),[-1.,-1.])\n", "meta": {"hexsha": "627ff22bdbf8479836300c06ddab980c6f00bc81", "size": 1038, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/maps_and_mesh/test_cell_map.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": "test/maps_and_mesh/test_cell_map.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": "test/maps_and_mesh/test_cell_map.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": 32.4375, "max_line_length": 60, "alphanum_fraction": 0.655105973, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.767316691463574}}
{"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 -  \u03c3 = weight on objective function, \u03bc = multipliers on the constraints\r\n####################################################################################################\r\nfunction MathProgSolverInterface.eval_hesslag(d::HS071, H, x, \u03c3, \u03bc)\r\n    # Again, only lower left triangle (since it is symmetric)\r\n    # Objective\r\n    H[1] = \u03c3 * (2*x[4])               # 1,1\r\n    H[2] = \u03c3 * (  x[4])               # 2,1\r\n    H[3] = 0                          # 2,2\r\n    H[4] = \u03c3 * (  x[4])               # 3,1\r\n    H[5] = 0                          # 3,2\r\n    H[6] = 0                          # 3,3\r\n    H[7] = \u03c3* (2*x[1] + x[2] + x[3])  # 4,1\r\n    H[8] = \u03c3 * (  x[1])               # 4,2\r\n    H[9] = \u03c3 * (  x[1])               # 4,3\r\n    H[10] = 0                         # 4,4\r\n\r\n    # First constraint\r\n    H[2] += \u03bc[1] * (x[3] * x[4])  # 2,1\r\n    H[4] += \u03bc[1] * (x[2] * x[4])  # 3,1\r\n    H[5] += \u03bc[1] * (x[1] * x[4])  # 3,2\r\n    H[7] += \u03bc[1] * (x[2] * x[3])  # 4,1\r\n    H[8] += \u03bc[1] * (x[1] * x[3])  # 4,2\r\n    H[9] += \u03bc[1] * (x[1] * x[2])  # 4,3\r\n\r\n    # Second constraint\r\n    H[1]  += \u03bc[2] * 2  # 1,1\r\n    H[3]  += \u03bc[2] * 2  # 2,2\r\n    H[6]  += \u03bc[2] * 2  # 3,3\r\n    H[10] += \u03bc[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": "#!/usr/bin/env julia\n\nfunction part1(elems)\n    [(e \u00f7 3 - 2) for e in elems] |> sum\nend\n\nfunction helper(elem)\n    elem = (elem \u00f7 3) - 2\n    ans = elem\n    while ans >= 0\n        ans = (ans \u00f7 3) - 2\n        if ans > 0\n            elem += ans;\n        end # if\n    end\n    elem\nend # function\n\nfunction part2(elems)\n    [helper(e) for e in elems] |> sum\nend\n\nfunction main()\n    if isempty(ARGS)\n        println(stderr, \"Usage:\\n\\tjulia main.jl <INPUT_FILE>\\nOR\\n\\tmain.jl <INPUT_FILE>\")\n        exit(1)\n    else\n        elems = [parse(Int64, e) for e in read(ARGS[1], String) |> split]\n    end\n\n    println(\"Part 1: $(part1(elems))\")\n    println(\"Part 2: $(part2(elems))\")\nend\n\nmain()\n", "meta": {"hexsha": "f1f0a5d6574b564233a6c20df648b88a5ecbec80", "size": 685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2019/day01/src/main.jl", "max_stars_repo_name": "GrayJack/Advent-Of-Code", "max_stars_repo_head_hexsha": "36384f2b77218cf7d46afe02f7aabb8582a6fe29", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-12-09T02:07:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T04:10:34.000Z", "max_issues_repo_path": "2019/day01/src/main.jl", "max_issues_repo_name": "GrayJack/Advent-Of-Code", "max_issues_repo_head_hexsha": "36384f2b77218cf7d46afe02f7aabb8582a6fe29", "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": "2019/day01/src/main.jl", "max_forks_repo_name": "GrayJack/Advent-Of-Code", "max_forks_repo_head_hexsha": "36384f2b77218cf7d46afe02f7aabb8582a6fe29", "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.0277777778, "max_line_length": 91, "alphanum_fraction": 0.5459854015, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7673166764063303}}
{"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*\u03c0*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\u03b4x   :: FT\n\txc   :: Array{FT}\n\txf   :: Array{FT}\n\tymin :: FT\n\tymax :: FT\n\tny   :: Int\n\t\u03b4y   :: 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)); \u03b4x = (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)); \u03b4y = (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,\u03b4x,xc,xf,\n\t\tymin,ymax,ny,\u03b4y,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 \u2208 [$(g.xmin), $(g.xmax)], y \u2208 [$(g.ymin), $(g.ymin)]\\n\",\n\t\t\"      resolution (nx,ny) : \", (g.nx,g.ny), '\\n',\n\t\t\"    grid spacing (\u03b4x,\u03b4y) : \", (g.\u03b4x,g.\u03b4y), '\\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": "using Graphs\nusing SimpleGraphs\nusing PyPlot\n\nfunction plot_deg_hist(g::GenericGraph, out_fldr::ASCIIString,fname::ASCIIString,ac::Float64)\n    # degree histogram\n    deglst = zeros(num_vertices(g))\n    for i in vertices(g)\n        deglst[i] = out_degree(i,g)\n    end\n    plt_deg_hist(deglst,out_fldr,fname,ac)\nend\n\nfunction plot_deg_hist(g::SimpleGraphs.SimpleGraph, out_fldr::ASCIIString,fname::ASCIIString,ac::Float64)\n    deglst = zeros(NV(g))\n    v_lst = vlist(g)\n    for i=1:NV(g)\n        deglst[i] = deg(g,v_lst[i])\n    end\n    # deglst = deg_hist(g)\n    plt_deg_hist(deglst,out_fldr,fname,ac)\nend\n\nfunction plot_deg_list(g::SimpleGraphs.SimpleGraph, out_fldr::ASCIIString,fname::ASCIIString,ac::Float64)\n    # degree histogram\n    deglst = deg(g)\n    plt_deg_hist(deglst,out_fldr,fname,ac)\nend\n\nfunction plt_deg_hist(deglst::Array{},out_fldr::ASCIIString,fname::ASCIIString,ac::Float64)\n    mu = mean(deglst)\n    sig = std(deglst)\n    PyPlot.clf()\n    plt[:hist](deglst,maximum(deglst),normed=1,alpha=0.75,facecolor=\"green\")\n    PyPlot.axvline(mu,color=\"k\",ls=\"dashed\")\n    PyPlot.axvline(mu-sig,color=\"r\",ls=\"dotted\")\n    PyPlot.axvline(mu+sig,color=\"r\",ls=\"dotted\")\n    title(\"Degree Distribution\")\n    xlabel(\"Degree\")\n    ylabel(\"Proportion\")\n    annotate(@sprintf(\"a(G)=%0.3f\",ac),xy=(0.7,0.8),fontsize=20,xycoords=\"axes fraction\")\n    annotate(@sprintf(\"mu=%0.3f\",mu),xy=(0.7,0.7),fontsize=20,xycoords=\"axes fraction\")\n    annotate(@sprintf(\"std=%0.3f\",sig),xy=(0.7,0.6),fontsize=20,xycoords=\"axes fraction\")\n    fname = joinpath(out_fldr,fname)\n    fname = string(fname,\".pdf\")\n    savefig(fname)\nend\n\nfunction plot_c_hist(c_hist::Array{},out_fldr::ASCIIString,fname::ASCIIString)\n    # connectivity history\n    PyPlot.clf()\n    PyPlot.plot(collect(1:length(c_hist)),c_hist)\n    title(\"Connectivity History\")\n    xlabel(\"Iteration\")\n    ylabel(\"Algebraic Connectivity\")\n    fname = joinpath(out_fldr,fname)\n    fname = string(fname,\".pdf\")\n    savefig(fname)\n    clf()\nend\n\nfunction plot_c_box(c_vals::Array{},n::Int,c_opt::Float64,out_fldr::ASCIIString,fname::ASCIIString)\n    # connectivity distribution vs. optimal\n    PyPlot.clf()\n    boxplot(c_vals)\n    PyPlot.boxplot(c_vals)\n    PyPlot.axhline(c_opt,color=\"r\",ls=\"dotted\")\n    title(\"Optimization Performance\")\n    # xlabel(\"n\")\n    xticks([1,2],[\"Opt\",\"Random\"])\n    ylabel(\"Algebraic Connectivity\")\n    fname = joinpath(out_fldr,fname)\n    fname = string(fname,\".pdf\")\n    savefig(fname)\nend\n", "meta": {"hexsha": "047347bfda14ca0bd38fbe9ef9f1c3d579f47ca2", "size": 2466, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plotting.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": "plotting.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": "plotting.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": 32.4473684211, "max_line_length": 105, "alphanum_fraction": 0.6885644769, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7672452156982329}}
{"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": "# https://adventofcode.com/2020/day/1\n\n# find the two entries that sum to 2020 and then multiply those two numbers together\n\nfunction part1(list_of_numbers, total=2020)\n    for (i, x) in enumerate(list_of_numbers)\n        y = total - x\n        if y in list_of_numbers[(i + 1):end]\n            return x * y\n        end\n    end\nend\n\nexample = [1721, 979, 366, 299, 675, 1456]\n@assert part1(example) == 514579\n\n# Using the above example again, the three entries that sum to 2020 are\n# 979, 366, and 675. Multiplying them together produces the answer, 241861950.\n\nfunction part2(list_of_numbers)\n    for (i, x) in enumerate(list_of_numbers)\n        partial = 2020 - x\n        tmp = filter(y -> y <= partial, list_of_numbers[(i + 1):end])\n        y = part1(tmp, partial)\n        if !isnothing(y)\n            return x * y\n        end\n    end\nend\n\n@assert part2(example) == 241861950\n\nfunction read_array(string::AbstractString)::Vector{Int}\n    return parse.(Int, split(string, '\\n', keepempty=false))\nend\n\ntest = read_array(read(\"data/day-01.txt\", String))\nprintln(\"Part 1: $(result1 = part1(test))\")\nprintln(\"Part 2: $(result2 = part2(test))\")\n\n@assert result1 == 326211\n@assert result2 == 131347190\n\n", "meta": {"hexsha": "53413d2c662b5fbbb28745392adfc693912cb7a9", "size": 1197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/day-01.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-01.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-01.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.2045454545, "max_line_length": 84, "alphanum_fraction": 0.6558061821, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676514011486, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7672452079443987}}
{"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)\u00b2 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": "using Optim\n\n## initial values\nx0 = -5.0*ones(1)\n\n## Our objective function\nobjfun(x) = x[1]^4 - 3.0*x[1]^3 + 2.0\n\n## Find the optimum!\nresult = optimize(objfun, x0, LBFGS())\nprintln(\"minimum value is: \",result.minimizer)\nprintln(\"obj value at minimum is: \",result.minimum)\n\n## Now do Particle Swarm (derivative-free method)\nresult = optimize(objfun, x0, ParticleSwarm())\nprintln(\"minimum value is: \",result.minimizer)\nprintln(\"obj value at minimum is: \",result.minimum)\n", "meta": {"hexsha": "a63664d739ba54f24743696254e15df79a802e92", "size": 471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LectureNotes/14-JuMP/LBFGS.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/LBFGS.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/LBFGS.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": 26.1666666667, "max_line_length": 51, "alphanum_fraction": 0.7070063694, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7672088727935814}}
{"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.\u2218\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 \u2115 \u2192 \u2115 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 \u2208 imagevals])\r\n\r\n\"\"\"\r\n    maxarg(\u03c3::Permutation)\r\n\r\nFind the largest integer which the `Permutation` `\u03c3` 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(\u03b9)\r\n1\r\n```\r\n\"\"\"\r\nmaxarg(\u03c3::Permutation) = length(\u03c3.image)\r\n\r\n\"\"\"\r\n    (\u03c3::Permutation)(x::Int64)\r\n\r\nEvaluate the action of the `Permutation` `\u03c3` on `x`.\r\n\r\n# Examples\r\njulia> \u03c3 = Permutation(4,5,2,1,3)\r\n( 1 4 )( 2 5 3 )\r\n\r\njulia> \u03c3(5)\r\n3\r\n\"\"\"\r\n(\u03c3::Permutation)(x::Int64) = x \u2208 1:maxarg(\u03c3) ? \u03c3.image[x] : x\r\n\r\n\"\"\"\r\n    orbit(\u03c3::Permutation,x::Int64)\r\n\r\nCompute the orbit of `x` under the repeated action of the `Permutation` `\u03c3`.\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(\u03c3::Permutation, x::Int64)\r\n    orb = [x]\r\n    y = \u03c3(x)\r\n    while y != x\r\n        push!(orb,y)\r\n        y = \u03c3(y)\r\n    end\r\n    return orb\r\nend\r\n\r\n\"\"\"\r\n    dcd(\u03c3::Permutation)\r\n\r\nCompute the disjoint cycle decomposition of the `Permutation` `\u03c3`.\r\n\r\nIf an integer is fixed by `\u03c3`, 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(\u03c3::Permutation)\r\n    decomp = Vector{Int64}[]\r\n    unaccounted = trues(maxarg(\u03c3))\r\n    while any(unaccounted)\r\n        x = findfirst(unaccounted)\r\n        xorbit = orbit(\u03c3,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,\u03c3::Permutation)\r\n    toprint = *([ *( \"( \", [\"$y \" for y \u2208 x]... , \")\" ) for x \u2208 dcd(\u03c3)]..., \"\")\r\n    toprint == \"\" && (toprint = \"\u03b9\")\r\n    print(io, toprint)\r\nend\r\n\r\n\"\"\"\r\n    \u03b9\r\n\r\nThe identity `Permutation`.\r\n\r\n# Examples\r\n```julia-repl\r\njulia> \u03b9.(1:10) == 1:10\r\ntrue\r\n```\r\n\"\"\"\r\nconst \u03b9 = Permutation(1)\r\none(::Permutation) = \u03b9\r\none(::Type{Permutation}) = \u03b9\r\n\r\n\"\"\"\r\n    \u2218(\u03c3::Permutation)\r\n    \u2218(\u03c3::Permutation, \u03c4::Permutation)\r\n    \u2218(\u03c3s...::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> \u2218(Permutation(1,2,4,3))\r\n( 3 4 )\r\n\r\njulia> Permutation(5,2,3,1,4) \u2218 Permutation(2,1,4,5,3)\r\n( 1 2 5 3 )\r\n```\r\n\"\"\"\r\n\u2218(\u03c3::Permutation) = \u03c3\r\n\u2218(\u03c3::Permutation, \u03c4::Permutation) = Permutation([\u03c3(\u03c4(x)) for x \u2208 1:max(maxarg(\u03c3),maxarg(\u03c4))])\r\n\u2218(\u03c3::Permutation, \u03c4::Permutation, \u03c5::Permutation...) = \u2218(\u03c3 \u2218 \u03c4, \u03c5...)\r\n\r\ninv(\u03c3::Permutation) = Permutation([findfirst(\u03c3.image .== x) for x \u2208 1:maxarg(\u03c3)])\r\n\r\n\"\"\"\r\n    ^(\u03c3::Permutation,n::Int)\r\n\r\nExponentiate a `Permutation` `\u03c3` 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 ^(\u03c3::Permutation,n::Int64)\r\n    n == 0 && return one(Permutation)\r\n    n < 0 && ((n,\u03c3) = (-n,inv(\u03c3)))\r\n    return \u2218(fill(\u03c3,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\u03b9\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 \u2265 1 || error(\"symmetric group must have a positive parameter\")\r\n    n == 1 && return [\u03b9]\r\n\r\n    permutations = vcat(fill(symmetricgroup(n-1),n)...)\r\n    transpositions = vcat([fill(transposition(i,n),factorial(n-1)) for i \u2208 1:n]...)\r\n    return permutations .\u2218 transpositions\r\nend\r\n\r\n\"\"\"\r\n    parity(\u03c3::Permutation)\r\n\r\nCompute the parity of the `Permutation` `\u03c3`.\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(\u03b9)\r\n1\r\n```\r\n\"\"\"\r\nparity(\u03c3::Permutation) = (-1)^sum([iseven(length(x)) for x \u2208 dcd(\u03c3)])\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\u2099 = symmetricgroup(n)\r\n    return S\u2099[parity.(S\u2099) .== 1]\r\nend\r\n\r\n# Defines equality of permutations, to be used to check \u2209\r\n==(\u03c3::Permutation, \u03c4::Permutation) = (\u03c3.image == \u03c4.image)\r\n\r\n\"\"\"\r\n    generate(\u03c3s::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 \u03b9\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  \u03b9\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(\u03c3s::Permutation...)\r\n    G = [\u03c3s...]\r\n    while true\r\n        newelements = Permutation[]\r\n\r\n        for \u03c3 \u2208 G, \u03c4 \u2208 G\r\n            \u03c5 = \u03c3 \u2218 \u03c4\r\n            \u03c5 \u2209 G && \u03c5 \u2209 newelements && push!(newelements, \u03c5)\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": "using FdeSolver\nusing Test\nusing Statistics\n\n@testset \"FdeSolver.jl\" begin\n\ntSpan = [0, 10]     # [intial time, final time]\nx0 = [1 1]             # intial value\n\u03b2 = 2            # order of the derivative\npar = [16.0, 4.0] # [spring constant for a mass on a spring, inertial mass]\nh = 0.01\n\nfunction F(t, x, par)\n\n      K = par[1]\n      m = par[2]\n\n      - K ./ m .* x\n\nend\n\nt, Yapp = FDEsolver(F, tSpan, x0, \u03b2, par, h = h)\n\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)\n\n@test @isdefined(t)\n@test @isdefined(Yapp)\n@test abs((mean(Yapp) - mean(a))) < 0.05\n\nend\n", "meta": {"hexsha": "9f61fc2c1c58df31eff119b2df7f3991ca686bd3", "size": 639, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/order2_test.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": "test/order2_test.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": "test/order2_test.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": 20.6129032258, "max_line_length": 123, "alphanum_fraction": 0.5508607199, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7671966410989058}}
{"text": "\nusing DiffEqBayes, OrdinaryDiffEq, RecursiveArrayTools, Distributions, Plots, StatsPlots, BenchmarkTools, TransformVariables, CmdStan, DynamicHMC\n\n\nfunction pendulum(du,u,p,t)\n    \u03c9,L = p\n    x,y = u\n    du[1] = y\n    du[2] = - \u03c9*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, \u03b4)\n\nCompute the Sample Entropy[^1] of `x`.\n\nCompute Sample Entropy with template size `m` and tolerance factor `r`.\nIf timestep `\u03b4` is provided, downsample signal `x` with timestep `\u03b4`.\n\n# Examples\n```julia\njulia> sample_entropy([1, 2, 3, 1, 2, 3], m=2, r=0.2, \u03b4=1)\n0.6931471805599453\n```\n\"\"\"\nfunction sample_entropy(x::AbstractArray, m=2, r=0.2, \u03b4=1)\n    #=\n    x -> normalized signal (1d vector)\n    m -> embedding dimension (must be > length of signal)\n    r -> tolerance factor\n    \u03b4 -> delay =#\n    N = length(x)\n    \u03c3 = std(x)\n    tolerance = \u03c3 * 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 - \u03b4)] = x[m + \u03b4:end]\n    matches = matches[:, 1:N + 1 - m - \u03b4]\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, \u03c4=1, m=2, r=0.2, \u03b4=1)\n\n    if \u03c4 == 1\n        sample_entropy(x, m, r, \u03b4)\n    end\n\n    N = length(x)\n    x = x[1:end - (N % \u03c4)]\n    N = length(x)\n    # TODO ordre de dims \u00e0 v\u00e9rifier\n    dims = (\u03c4, Int(N / \u03c4))\n    x = reshape(x, dims)\n    x_mse = mean(x, dims=1)\n\n    sample_entropy(x_mse, m, r, \u03b4)\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": "module CellQuadraturesTests\n\nusing Test\nusing FillArrays\nusing Gridap.Helpers\nusing Gridap.Fields\nusing Gridap.ReferenceFEs\nusing Gridap.Geometry\nusing Gridap.Arrays\nusing Gridap.Integration\nusing Gridap.CellData\n\nusing Gridap.Geometry: GridMock\n\ndegree = 3\nquad = Quadrature(HEX,degree)\ntest_quadrature(quad)\n@test sum(get_weights(quad)) \u2248 1\n\ndegree = (1,2,3)\nquad = Quadrature(HEX,degree)\ntest_quadrature(quad)\n@test sum(get_weights(quad)) \u2248 1\n\ndegree = 3\nquad = Quadrature(TET,degree)\ntest_quadrature(quad)\n@test sum(get_weights(quad)) \u2248 0.5*1/3\n\ntrian = GridMock()\n\ndegree = 3\nquad = CellQuadrature(trian,degree)\nq = get_coordinates(quad)\n@test isa(q,CompressedArray)\nw = get_weights(quad)\n@test isa(w,CompressedArray)\n\nq2x = get_cell_map(trian)\nx = evaluate(q2x,q)\n\n#using Gridap.Visualization\n#writevtk(trian,\"trian\")\n#writevtk(x,\"x\",nodaldata=[\"w\"=>w])\n\ndomain = (0,1,0,1)\npartition = (2,3)\ntrian = CartesianGrid(domain,partition)\nquad = CellQuadrature(trian,degree)\nq = get_coordinates(quad)\n@test isa(q,Fill) || isa(q,CompressedArray)\nw = get_weights(quad)\n@test isa(w,Fill) || isa(w,CompressedArray)\n\nvol = sum(integrate(1,trian,quad))\n@test vol \u2248 1\n\ndomain = (0,2,0,2,0,2)\npartition = (2,3,2)\ntrian = CartesianGrid(domain,partition)\nquad = CellQuadrature(trian,degree)\n\nvol = sum(integrate(1,trian,quad))\n@test vol \u2248 2^3\n\n@test isa(get_array(quad),AbstractArray{<:Quadrature})\n\nend # module\n", "meta": {"hexsha": "94a959766cff3906ecf28a95b23477ca41bb96df", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/GeometryTests/CellQuadraturesTests.jl", "max_stars_repo_name": "barche/Gridap.jl", "max_stars_repo_head_hexsha": "70325414653cf0b9822770b150fb082d1a0a5f78", "max_stars_repo_licenses": ["MIT"], "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/GeometryTests/CellQuadraturesTests.jl", "max_issues_repo_name": "barche/Gridap.jl", "max_issues_repo_head_hexsha": "70325414653cf0b9822770b150fb082d1a0a5f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T08:20:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T08:20:09.000Z", "max_forks_repo_path": "test/GeometryTests/CellQuadraturesTests.jl", "max_forks_repo_name": "barche/Gridap.jl", "max_forks_repo_head_hexsha": "70325414653cf0b9822770b150fb082d1a0a5f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-10T06:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T07:54:42.000Z", "avg_line_length": 20.3188405797, "max_line_length": 54, "alphanum_fraction": 0.7460770328, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7671274085777308}}
{"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 \u03bb and index of refraction n from publication Aspnes 1986\nx = [0.491 0.590]\n\u03bb = [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(\u03bb)\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]), \u03bb = $(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 FindCentroids(X,C)\r\n   m=size(X,1)\r\n   n=size(X,2)\r\n   k=size(C,1)\r\n\r\n   dis=zeros(m,k)\r\n   idx=zeros(m)\r\n    for i=1:k\r\n       dis[:,i]=sqrt.(sum((X.-C[i,:]').^2,dims=2))\r\n    end\r\n    for i=1:m\r\n        idx[i]=argmin(dis[i,:])\r\n    end\r\n\r\n    return idx\r\n\r\n\r\nend\r\n", "meta": {"hexsha": "fe1b0601d79a692788765cd36c88ed78e12b1685", "size": 275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FindCentroids.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/FindCentroids.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/FindCentroids.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": 14.4736842105, "max_line_length": 51, "alphanum_fraction": 0.4618181818, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.8479677641409289, "lm_q1q2_score": 0.7671145002978357}}
{"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": "using StanSample\nusing DataFrames, Tables\nusing Random, Distributions, Test\n\nbegin\n    N = 100\n    df = DataFrame(\n      :h0 => rand(Normal(10,2 ), N),\n      :treatment => vcat(zeros(Int, Int(N/2)), ones(Int, Int(N/2)))\n    );\n    df[!, :fungus] =\n        [rand(Binomial(1, 0.5 - 0.4 * df[i, :treatment]), 1)[1] for i in 1:N]\n    df[!, :h1] =\n        [df[i, :h0] + rand(Normal(5 - 3 * df[i, :fungus]), 1)[1] for i in 1:N]\n    data = Dict(\n        :N => nrow(df),\n        :h0 => df[:, :h0],  \n        :h1 => df[:, :h1],\n        :fungus => df[:, :fungus],\n        :treatment => df[:, :treatment]\n    );\nend;\n\nstan6_7 = \"\ndata {\n  int <lower=1> N;\n  vector[N] h0;\n  vector[N] h1;\n  vector[N] treatment;\n  vector[N] fungus;\n}\nparameters{\n  real a;\n  real bt;\n  real bf;\n  real<lower=0> sigma;\n}\nmodel {\n  vector[N] mu;\n  vector[N] p;\n  a ~ lognormal(0, 0.2);\n  bt ~ normal(0, 0.5);\n  bf ~ normal(0, 0.5);\n  sigma ~ exponential(1);\n  for ( i in 1:N ) {\n    p[i] = a + bt*treatment[i] + bf*fungus[i];\n    mu[i] = h0[i] * p[i];\n  }\n  h1 ~ normal(mu, sigma);\n}\n\";\n\n# \u2554\u2550\u2561 655d0bcb-a4ab-41b4-8525-3e9f066113fd\nbegin\n    m6_7s = SampleModel(\"m6.7s\", stan6_7)\n    rc6_7s = stan_sample(m6_7s; data)\nend;\n\nif success(rc6_7s)\n    nt6_7s = read_samples(m6_7s)\n    df6_7s = read_samples(m6_7s, :dataframe)\n    a6_7s, cnames = read_samples(m6_7s, :array; return_parameters=true);\nend\n\nst = StanSample.convert_a3d(a6_7s, cnames, Val(:table))\n\n# Testing\n\n@test Tables.istable(st) == true\n\nrows = Tables.rows(st)\nfor row in rows\n    rowvals = [Tables.getcolumn(row, col) for col in Tables.columnnames(st)]\nend\n\n@test length(Tables.getcolumn(rows, :a)) == 4000\ncols = Tables.columns(st)\n\n@test Tables.schema(rows) == Tables.schema(cols)\n\n@test size(DataFrame(st)) == (4000, 4)\n", "meta": {"hexsha": "77440d196e93d39d316047bc71f2378d12c584ff", "size": 1755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-tables-interface/ex-02.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": "test/test-tables-interface/ex-02.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": "test/test-tables-interface/ex-02.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": 21.4024390244, "max_line_length": 78, "alphanum_fraction": 0.5806267806, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7671144881026675}}
{"text": "# Fixed Talbot method\n#\n# Abate, J. and Valk\u00f3, P.P.\n# Multi-precision Laplace transform inversion\n# International Journal for Numerical Methods in Engineering, Vol. 60 (Iss. 5-7)  2004  pp 979\u2013993\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-\u03bcI=0`` instead of\n    ``A=0``, where ``\u03bc = \\\\operatorname{tr}(A) / n`` to speed up convergence. See\n    \u00a73.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    # \u00a73: \u201cOur experience indicates that p_max = 8 and m_max = 55 are appropriate choices.\u201d\n    p_max = 8\n    m_max = 55\n    n0 = size(B, 2)\n    if shift\n        \u03bc = tr(A) / n\n        A -= \u03bc * I\n    else\n        \u03bc = zero(float(eltype(A)))\n    end\n    params = parameters(t, A, n0, m_max, p_max, tol)\n    \u03b7 = exp(t * \u03bc / params.s)\n    F = one(\u03b7) * 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 \u2264 tol * _opnormInf(F) && break\n            c1 = c2\n        end\n        F *= \u03b7\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 \u2211 x\u1d62x\u2c7c\n\nover a periodic N\u00d7N 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 = \u2211 x\u1d62\n\nover a periodic N\u00d7N 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 \u00d7 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": "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\nfunction SPT_KhPT(order)\n    order = 2^order\n    triangle = khayyam_triangle(order)\n    x = []\n    y = []\n    for 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\n    end\n    return x, y\nend\n\nmsize = [7,1,0.1]\nolist = [5, 7, 10]\nfor i in 1:3\n    x,y = SPT_KhPT(olist[i])\n    scatter(x,y,markersize = msize[i], legend = false, border=:none, dpi=300)\n    savefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\ComputationalPhysics-Fall2021\\\\ProblemSet1\\\\Figs\\\\Q5\\\\SPTKP-O$(i).png\")\nend\n", "meta": {"hexsha": "9dc6d2b603f607ff5d468b2fce9018da1ce04e65", "size": 1047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet1/Codes/Q5.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/Q5.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/Q5.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": 23.7954545455, "max_line_length": 123, "alphanum_fraction": 0.488061127, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8418256492357359, "lm_q1q2_score": 0.767054448920699}}
{"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\u00e9zout\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\u00e9zout coefficients are *not* uniquely defined. `gcdx` returns the minimal\n    B\u00e9zout 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 \u2265 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) \u00f7 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 \u2264 abs(base) \u2264 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 \u2265 2 or \u2264 -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) \u00f7 (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 \u2208 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\u2081 = 1\n    for i \u2208 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\u2081 *= subjectnum\n        encriptkey\u2081 %= transfnum\n    end\n\n    subjectnum = cardpbk\n    encriptkey\u2082 = 1\n    for i \u2208 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\u2082 *= subjectnum\n        encriptkey\u2082 %= transfnum\n    end\n    return encriptkey\u2081, encriptkey\u2082\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\u03bc1 = \u03bc2 = 0.0\n\n\ud835\udecd = [\n    \u03bc1\n    \u03bc2\n]\n\n\u03c311 = \u03c322 = 1.0\n\u03c312 = \u03c321 = 0.0\n\n\u03a3 = [\n    \u03c311 \u03c312\n    \u03c321 \u03c322\n]\n\nfunction \ud835\udca9(x1, x2; \ud835\udecd = \ud835\udecd, \u03a3 = \u03a3)\n    \ud835\udc31 = [x1, x2]\n    \u039b = inv(\u03a3)\n    D = length(\ud835\udecd)\n    return \u221a(det(\u039b)) * exp(-0.5 * (\ud835\udc31 .- \ud835\udecd)' * \u039b * (\ud835\udc31 .- \ud835\udecd)) / \u221a(2\u03c0)^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 = \ud835\udca9.(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": "using Test\nusing CryptoGroups: @bin_str, @hex_str, ECP, specialize, ECPoint, <|, generator, octet, Hash, gx, gy, order, modinv\nusing CryptoGroups.Specs: octet2int\n\ncurve_spec = ECP(;\n                 p = 6277101735386680763835789423207666416083908700390324961279,\n                 n = 6277101735386680763835789423176059013767194773182842284081,\n                 h = 1,\n                 a = hex\"FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFFFF FFFFFFFC\",\n                 b = hex\"64210519 E59C80E7 0FA7E9AB 72243049 FEB8DEEC C146B9B1\",\n                 G = hex\"03 188DA80E B03090F6 7CBF20EB 43A18800 F4FF0AFD 82FF1012\",\n)\n\n\nP = specialize(ECPoint, curve_spec)\nG = P <| generator(curve_spec) \n\n# Key Generation\n\nd = 651056770906015076056810763456358567190100156695615665659\nQ = d*G\n\n\n@test octet(Q; mode=:compressed) == hex\"02 62B12D60 690CDCF3 30BABAB6 E69763B4 71F994DD 702D16A5\"\n\n# Signature Generation\n\nM = \"abc\"\n#H = Hash(\"sha256\")\nH = Hash(\"SHA1\")\ne = octet2int(H(M))\n\n@test e == 968236873715988614170569073515315707566766479517\n\nk = 6140507067065001063065065565667405560006161556565665656654\n\nR = k*G\n\nx\u2081 = octet(gx(R))\ny\u2081 = octet(gy(R))\n\n@test x\u2081 == hex\"88505238 0FF147B7 34C330C4 3D39B2C4 A89F29B0 F749FEAD\"\n@test y\u2081 == hex\"9CF9FA1C BEFEFB91 7747A3BB 29C072B9 289C2547 884FD835\"\n\n\nx\u0304\u2081 = octet2int(x\u2081)\n\n\n@test x\u0304\u2081 == 3342403536405981729393488334694600415596881826869351677613\n\nn = order(P)\n\nr = x\u0304\u2081 % n\n\n@test r == 3342403536405981729393488334694600415596881826869351677613\n\ns = modinv(k, n) * (e + d*r) % n\n\n@test s == 5735822328888155254683894997897571951568553642892029982342\n\n\nprintln(\"\"\"The signature is:\n    r = $r\n    s = $s\n\"\"\")\n\n\n# Signature verification\n\n(r\u2032, s\u2032) = r, s\n\nM\u2032 = \"abc\"\nH\u2032 = Hash(\"sha256\")\ne\u2032 = octet2int(H(M\u2032))\n\n\n@test 1 < r\u2032 < n - 1\n@test 1 < s\u2032 < n - 1\n\nc = modinv(s\u2032, n)\n\n@test c == 3250964404472526825130516490452346217749189704049629042861\n\n\nu\u2081 = e\u2032*c % n\nu\u2082 = r\u2032*c % n\n\n@test u\u2081 == 2563697409189434185194736134579731015366492496392189760599\n@test u\u2082 == 6266643813348617967186477710235785849136406323338782220568\n\nW = u\u2081*G + u\u2082*Q \nx\u2081 = octet(gx(W))\ny\u2081 = octet(gy(W))\n\n@test x\u2081 == hex\"88505238 0FF147B7 34C330C4 3D39B2C4 A89F29B0 F749FEAD\"\n@test y\u2081 == hex\"9CF9FA1C BEFEFB91 7747A3BB 29C072B9 289C2547 884FD835\"\n\nx\u0304\u2081 = octet2int(x\u2081)\n\n\u03bd = x\u0304\u2081 % n\n\n@test \u03bd == r\u2032\n\n", "meta": {"hexsha": "5b28e36b6bcf8191247d8394886671d106f5c2df", "size": 2291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ecdsa/ecdsa_prime.jl", "max_stars_repo_name": "PeaceFounder/DiffieHellmanGroups.jl", "max_stars_repo_head_hexsha": "69acfb3c991323c9244f71cbb792209fb4f39af0", "max_stars_repo_licenses": ["MIT"], "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/ecdsa/ecdsa_prime.jl", "max_issues_repo_name": "PeaceFounder/DiffieHellmanGroups.jl", "max_issues_repo_head_hexsha": "69acfb3c991323c9244f71cbb792209fb4f39af0", "max_issues_repo_licenses": ["MIT"], "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/ecdsa/ecdsa_prime.jl", "max_forks_repo_name": "PeaceFounder/DiffieHellmanGroups.jl", "max_forks_repo_head_hexsha": "69acfb3c991323c9244f71cbb792209fb4f39af0", "max_forks_repo_licenses": ["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.0288461538, "max_line_length": 115, "alphanum_fraction": 0.7040593627, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7669926972454352}}
{"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\u0302::SVector{3,T}) where {T}\n\tvec_area = vector_area(v123[1], v123[2], v123[3])\n\treturn dot(n\u0302, 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\u03bb = 45.0                                # Conductivity\r\nc = 460.0                               # Specific heat capacitivity\r\n\u03c1 = 7800.0                              # Material density\r\n\u03b1 = \u03bb / (c*\u03c1)                           # Diffusivity\r\n\r\n#Number of spatial discretization points and length of each\r\nN = 11                                 #Discretization points / nodes\r\n\u0394x = L / (N-1)                         # \u0394x = x[i+1] - x[i]\r\n\r\n#Integration from t0 = 0 to tf\r\ntf = 10000.0;                          #Final time\r\n\u0394t = 10^(-1);                          #Sampling period\r\nk = round(Int,tf / \u0394t);                #k = number of steps\r\n\r\n#System's matrix: \u03b8' = A\u03b8 + 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 = (\u03b1/( \u0394x^2)) * A;\r\n\r\n#input matrix\r\nB = spzeros(N);\r\nB[1] = 1;\r\nB = (2/ (c * \u03c1 * \u0394x)) * 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\u03b8init = 273.0\r\n\u03b8ref = 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,\u03b8[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, \u03b8[:,1] .== \u03b8init)\r\n@constraint(mod, y[1] .== \u03b8init)\r\n#System dynamics\r\nfor j in 1:k - 1,i in 1:N\r\n    @constraint(mod,\u03b8[i,j + 1] - (\u03b8[i,j] + \u0394t * ((A[:,i]' * \u03b8[:,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 * \u03b8[:,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] * (\u03b8ref - \u03b8[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 * \u0394t * (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_\u03b8start = zeros(k)\r\nstates_\u03b8end = zeros(k)\r\ninput_u = zeros(k - 1)\r\nfor i = 1 : k-1\r\n    states_\u03b8start[i] = JuMP.value(\u03b8[1,i])\r\n    states_\u03b8end[i] = JuMP.value(\u03b8[end,i])\r\n    input_u[i] = JuMP.value(u[i])\r\nend\r\n\r\nstates_\u03b8end[end] = JuMP.value(\u03b8[end,end])\r\nstates_\u03b8start[end] = JuMP.value(\u03b8[1,end])\r\n\r\nplot(states_\u03b8start,label = \"\u03b81\")\r\nplot!(states_\u03b8end,label=\"y = C\u03b8\")\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, \u03b2[1:p+1])\n\n    # Define constraints - none\n\n    # Define objective function\n    @objective(OLS_model, Min, sum((y[i] - \u03b2[1] - \u03b2[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(\u03b2)\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, \u03b3)\n    @variable(LQS_model, z[1:n], Bin)\n    @variable(LQS_model, \u03bc[1:n])\n    @variable(LQS_model, \u03b2[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] - \u03b2[1] - \u03b2[2:p+1]'*x[i,:])\n    @constraint(LQS_model, [i=1:n], \u03b3 >= a[i] - \u03bc[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], \u03bc[i] <= M*(1 - z[i]))\n    @constraint(LQS_model, sum(z[i] for i=1:n) == q)\n    @constraint(LQS_model, [i=1:n], \u03bc[i] >= 0)\n    \n     # Define objective function\n    @objective(LQS_model, Min, \u03b3)\n#     return(LQS_model)\n\n    # Run the optimization\n    solve(LQS_model)\n    betas = getvalue(\u03b2)\n    qth_residual = getvalue(\u03b3)\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, \u03b2[1:p+1])\n    @variable(LTS_model, r[1:n])\n            \n    # Define constraints\n    @constraint(LTS_model, [i=1:n], \u03b2[1] + \u03b2[2:p+1]'*x[i,:] - y[i] <= r[i] + M*z[i])\n    @constraint(LTS_model, [i=1:n], -\u03b2[1] - \u03b2[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 \u03b2, 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(\u03b2)\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, \u03b2[1:p+1])\n    @variable(LTSR_model, r[1:n])\n            \n    # Define constraints\n    @constraint(LTSR_model, [i=1:n], \u03b2[1] + \u03b2[2:p+1]'*x[i,:] - y[i] <= r[i] + M*z[i])\n    @constraint(LTSR_model, [i=1:n], -\u03b2[1] - \u03b2[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 \u03b2, 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(\u03b2)\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(\u03b1,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    \u03b2_ols = (x_int'*x_int)^-1*x_int'*y\n    e_residuals = y-x_int*\u03b2_ols\n    \u03c3_squared = e_residuals'*e_residuals/(n-p+1)\n    H = x*(x'*x)^-1*x'\n    h = diag(H)\n    \u03b4 = ((e_residuals).^2/(\u03c3_squared*(1 .- h)))*(1/(p+1))*(h./(1 .- h))\n    \u03c3_h = (e_residuals./(1 .- h).^0.5)\n    \u03c3_h_squared = (e_residuals./(1 .- h).^0.5).^2\n#     println(\u03b4)\n    \n    # Define decision variables\n    @variable(BI_model, z[1:n], Bin)\n    @variable(BI_model, \u03b2[1:p+1])\n    @variable(BI_model, r[1:n])\n            \n    # Define constraints\n    @constraint(BI_model, [i=1:n], \u03b2[1] + \u03b2[2:p+1]'*x[i,:] - y[i] <= r[i] + M*z[i])\n    @constraint(BI_model, [i=1:n], -\u03b2[1] - \u03b2[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, \u03b1*sum(r[i]^2 + z[i]*\u03b4[i]^2 for i=1:n) + (1-\u03b1)*sum(z[i] for i=1:n))\n    \n    # Run the optimization\n    solve(BI_model)\n    betas = getvalue(\u03b2)\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": "using Combinatorics\nusing Test\n\ninclude(\"numbers.jl\")\ninclude(\"factorials.jl\")\ninclude(\"combinations.jl\")\ninclude(\"permutations.jl\")\ninclude(\"partitions.jl\")\ninclude(\"multinomials.jl\")\ninclude(\"youngdiagrams.jl\")\n", "meta": {"hexsha": "d79067087a1f218920e3cf7a658dd44349fc5091", "size": 213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Sedictious/Combinatorics.jl", "max_stars_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 165, "max_stars_repo_stars_event_min_datetime": "2016-09-13T17:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:29:52.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "Sedictious/Combinatorics.jl", "max_issues_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86, "max_issues_repo_issues_event_min_datetime": "2016-08-25T18:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T12:58:42.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "Sedictious/Combinatorics.jl", "max_forks_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2016-10-29T00:18:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T10:21:39.000Z", "avg_line_length": 19.3636363636, "max_line_length": 27, "alphanum_fraction": 0.779342723, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7669862447362144}}
{"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_\u03bb_\u03b7(\u03b1, \u03b2,\u03b8, a)\n    \u03bb = -\u03b1 * sin(\u03b8)\n    \u03b7 = (\u03b1^2 - a^2)*cos(\u03b8)^2+\u03b2^2\n    return \u03bb, \u03b7\nend\n\n@inline function get_up_um(\u03bb, \u03b7, a)\n    \u0394_\u03b8  = 1/2*(1-(\u03b7+\u03bb^2)/a^2)\n    up = \u0394_\u03b8 + \u221a(\u0394_\u03b8^2 +\u03b7/a^2)\n    um = \u0394_\u03b8 - \u221a(\u0394_\u03b8^2 +\u03b7/a^2)\n    return up, um\nend\n\nfunction radialroots(\u03bb::Real, \u03b7::Real, a)\n    T = promote_type(typeof(\u03bb), typeof(\u03b7))\n    return radialroots(Complex{T}(\u03bb), Complex{T}(\u03b7), a)\nend\n\n\n\"\"\"\n    $(SIGNATURES)\nFinds the radial roots using the of the geodesic with\nenergy-scaled angular momentum `\u03bb` and carter constant `\u03b7`.\n\"\"\"\n@fastmath function radialroots(\u03bb::Complex, \u03b7::Complex, a)\n    A = a^2 - \u03b7 - \u03bb^2\n    B = 2*(\u03b7+(\u03bb-a)^2)\n    C = -a^2 * \u03b7\n    P = -A^2 / 12 - C\n    Q = -A/3 * ((A/6)^2-C)-B^2/8\n    H = -9*Q + \u221a(12*P^3 + 81*Q^2)\n    z = \u221a((-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(\u03bb), \" \", real(\u03b7))\n    return r1,r2,r3,r4#Tuple(roots[ind])\nend\n\nfunction get_\u039b(\u03b2, \u03c7)\n    s,c = sincos(\u03c7)\n    \u03b3 = 1/sqrt(1-\u03b2^2)\n\n    \u039b00 = \u03b3\n    \u039b01 = -\u03b3*\u03b2*c\n    \u039b03 = -\u03b3*\u03b2*s\n    \u039b11 = (\u03b3-1)*c^2 + 1\n    \u039b13 = (\u03b3-1)*s*c\n    \u039b33 = (\u03b3-1)*s^2 + 1\n    z = zero(typeof(\u03b3))\n    o =  one(typeof(\u03b3))\n    return @SMatrix[\u039b00 \u039b01  z  \u039b03;\n                    \u039b01 \u039b11  z  \u039b13;\n                    z   z    o  z\n                    \u039b03 \u039b13  z  \u039b33\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": "@testset \"Multivariate\" begin\n\n    @testset \"Simple test\" begin\n\n        data = [1.0 1.0   2.0\n                0.0 0.0   4.0\n                7.0 1.5  -4.5\n                2.0 2.0 -17.0 # outlier\n                0.0 8.6  -4.6]\n\n        # This is the most complete way of defining the arguments for model and gmodel!\n        model = (x::Union{Vector{Float64}, SubArray}, \u03b8::Vector{Float64}) -> \u03b8[1] *\n            x[1] + \u03b8[2] * x[2] + \u03b8[3]\n\n        gmodel! = (g::SubArray, x::Union{Vector{Float64}, SubArray},\n                   \u03b8::Vector{Float64}) -> begin\n\n            g[1] = x[1]\n            g[2] = x[2]\n            g[3] = 1.0\n            \n        end\n\n        n = 3\n\n        p = 4\n\n        \u03b8sol = [- 1.0, - 1.0, 4.0]\n        \n        rout = lmlovo(model, gmodel!, data, n, p; \u03b5=1.0e-8)\n\n        @test rout.solution \u2248 \u03b8sol atol=1.0e-4\n        @test rout.outliers == [4]\n\n        rout = raff(model, gmodel!, data, n)\n\n        @test rout.solution \u2248 \u03b8sol atol=1.0e-3\n        @test rout.p == 4\n        @test rout.outliers == [4]\n        \n        # Using automatic differentiation\n        \n        # This is the most complete way of defining the arguments for\n        # model when automatic differentiation is being used\n        model = (x::Union{Vector{Float64}, SubArray}, \u03b8) -> \u03b8[1] *\n            x[1] + \u03b8[2] * x[2] + \u03b8[3]\n\n        rout = lmlovo(model, data, n, p; \u03b5=1.0e-8)\n\n        @test rout.solution \u2248 \u03b8sol atol=1.0e-4\n        @test rout.outliers == [4]\n\n        rout = raff(model, data, n)\n\n        @test rout.solution \u2248 \u03b8sol atol=1.0e-3\n        @test rout.p == 4\n        @test rout.outliers == [4]\n        \n    end\n\n    @testset \"Circle\" begin\n\n        data = [2.0              \t1.0             \t0.0\n                1.766044443118978\t1.6427876096865393\t-3.3306690738754696e-16\n                1.1736481776669305\t1.9848077530122081\t2.220446049250313e-16\n                0.5000000000000002\t1.8660254037844388\t0.0\n                0.06030737921409168\t1.3420201433256689\t-1.1102230246251565e-16\n                0.06030737921409157\t0.6579798566743313\t0.0\n                0.49999999999999956\t0.13397459621556151\t0.0\n                3.17364817766693\t0.015192246987791869\t0.0 # noise\n                1.766044443118978\t0.3572123903134604\t0.0]\n\n        \u03b8sol = [1.0, 1.0, 1.0]\n\n        model = (x::Union{Vector{Float64}, SubArray}, \u03b8) -> (x[1] - \u03b8[1])^2 + (x[2] - \u03b8[2])^2 - \u03b8[3]\n\n        n = 3\n\n        p = 8\n        \n        rout = lmlovo(model, [0.0, 0.0, 2.0], data, n, p; \u03b5=1.0e-8)\n\n        @test rout.solution \u2248 \u03b8sol atol=1.0e-4\n        @test rout.outliers == [8]\n\n        rout = raff(model, data, n; \u03b5=1.0e-8)\n\n        @test rout.p == 8\n        @test rout.outliers == [8]\n        @test rout.solution \u2248 \u03b8sol atol=1.0e-4\n\n    end\n    \nend\n", "meta": {"hexsha": "b9d53f4201e8cb0045504b4c860aad21f1513f6d", "size": 2735, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_multivariate.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/test_multivariate.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/test_multivariate.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.7894736842, "max_line_length": 100, "alphanum_fraction": 0.4976234004, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7669623669702588}}
{"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": "using NonLinearReactionAdvectionDiffusionWithFrontData;\nusing LinearAlgebra;\n\nu_l(t) = -8 + 4*sin(2*\u03c0 / T * t);# \u041f\u0440\u044f\u043c\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0441 \u043d\u0435\u043e\u0434\u043d\u043e\u0440\u043e\u0434\u043d\u044b\u043c\u0438 \u0413\u0423\nu_r(t) =  4 + sin(-2*\u03c0 / T * t);# \u041d\u043e \u0432 \u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c, \u0431\u0443\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0442\u043e\u043b\u044c\u043a\u043e \u043e\u0434\u043d\u043e\u0440\u043e\u0434\u043d\u044b\u0435.\nqf(x) = 4*sin(3 * \u03c0 * x);        # \u041a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442 \u043b\u0438\u043d\u0435\u0439\u043d\u043e\u0433\u043e \u0443\u0441\u0438\u043b\u0435\u043d\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0432 \u043e\u0431\u0440\u0430\u0442\u043d\u043e\u0439\n# \u0437\u0430\u0434\u0430\u0447\u0435 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u043d\u043e \u043f\u0440\u0438 \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u0438 \u0430\u043f\u0440\u0438\u043e\u0440\u043d\u043e\u0439\n# \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u0438 \u043c\u044b \u0437\u0430\u0434\u0430\u0435\u043c \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442, \u043a\u043e\u0442\u043e\u0440\u044b\u0439,\n# \u0441\u043e\u0431\u0441\u0442\u0432\u0435\u043d\u043d\u043e, \u043f\u043e\u0441\u043b\u0435 \u0438\u043c\u0435\u044f \u0430\u043f\u0440\u0438\u043e\u0440\u043d\u0443\u044e \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u0438 \u0431\u0443\u0434\u0435\u043c \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0442\u044c.\n\u03b5 = 0.2;                        # \u041c\u0430\u043b\u044b\u0439 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 \u043f\u0440\u0438 \u0441\u0442\u0430\u0440\u0448\u0435\u0439 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u043e\u0439\na, b = 0, 1;                    # \u041e\u0431\u043b\u0430\u0441\u0442\u044c \u043f\u043e X\nt\u2080, T = 0, 0.28;                # \u041e\u0431\u043b\u0430\u0441\u0442\u044c \u043f\u043e T\nN, M = 50, 80;                  # \u041a\u043e\u043b-\u0432\u043e \u0440\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0439 \u043f\u043e X, T\nh = (b-a)/N;                    # \u0448\u0430\u0433 \u043f\u043e X\n\u03c4 = (T-t\u2080)/M;                   # \u0448\u0430\u0433 \u043f\u043e T\nX\u2099 = [a  + n*h for n in 0:N];   # \u0421\u0435\u0442\u043a\u0430 \u043f\u043e \u0425\nT\u2098 = [t\u2080 + m*\u03c4 for m in 0:M];   # \u0421\u0435\u0442\u043a\u0430 \u043f\u043e \u0422\nq\u2099 =      qf.(X\u2099);               # \u0421\u0435\u0442\u043e\u0447\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u0430 \u043b\u0438\u043d\u0435\u0439\u043d\u043e\u0433\u043e \u0443\u0441\u0438\u043b\u0435\u043d\u0438\u044f\nul\u2098=    u_l.(T\u2098);               # \u0421\u0435\u0442\u043e\u0447\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043b\u0435\u0432\u043e\u0433\u043e  \u0413\u0423\nur\u2098=    u_r.(T\u2098);               # \u0421\u0435\u0442\u043e\u0447\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043f\u0440\u0430\u0432\u043e\u0433\u043e \u0413\u0423\ny\u2080 = u_init.(X\u2099);               # \u041d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0435 \u0443\u0441\u043b\u043e\u0432\u0438\u044f\nnothing #hide\n\n# \u041f\u043e\u0434\u0433\u043e\u0442\u043e\u0432\u0438\u043c \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0432\u044b\u0431\u0440\u043e\u0441\u0438\u0432 \u0433\u0440\u0430\u043d\u0438\u0447\u043d\u044b\u0435 \u0442\u043e\u0447\u043a\u0438\n# \u0432\u0435\u0434\u044c \u0442\u0435\u0441\u0442\u0438\u0440\u0443\u0435\u043c\u0430\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u2014 \u0434\u043b\u044f \u0432\u043d\u0443\u0442\u0440\u0435\u043d\u043d\u0435\u0433\u043e \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f\nqq = q\u2099[2:N];\ny = y\u2080[2:N];\n\ndl, d, du = NonLinearReactionAdvectionDiffusionWithFrontData.DRP_y(y, 1, X\u2099, N, \u03b5, ul\u2098, ur\u2098, qq)\n\n@test length(dl) == N - 2\n@test length(d)  == N - 1\n@test length(du) == N - 2\n\n@test count(x -> x == 0, dl) == 0\n@test count(x -> x == 0, d)  == 0\n@test count(x -> x == 0, du) == 0\n\ntdjac = NonLinearReactionAdvectionDiffusionWithFrontData.\u2202DRP_\u2202y(y, 1, X\u2099, N, \u03b5, ul\u2098, ur\u2098, qq)\n@test typeof(tdjac) <: Tridiagonal\n@test tdjac == Tridiagonal( dl, d, du )\n\n# \u0421\u0440\u0430\u0432\u043d\u0438\u043c \u0441 \u044f\u043a\u043e\u0431\u0438\u0430\u043d\u043e\u043c \u0430\u0432\u0442\u043e\u0434\u0438\u0444\u0444\u0435\u0440\u0435\u043d\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f\njac = NonLinearReactionAdvectionDiffusionWithFrontData.\u2202directRP_\u2202y(y, 1, X\u2099, N, \u03b5, ul\u2098, ur\u2098, qq)\n@test isapprox(tdjac, jac)\n", "meta": {"hexsha": "3dcdebd7719d5c0c0dab72ad237bd8d5e7e0f0bf", "size": 1946, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/direct_jacobian.jl", "max_stars_repo_name": "aborzunov/NonLinearReactionAdvectionDiffusionWithFrontData.jl", "max_stars_repo_head_hexsha": "006aff15ac0dcbd7aaea3d9a23d3c1ff6bd48613", "max_stars_repo_licenses": ["MIT"], "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/direct_jacobian.jl", "max_issues_repo_name": "aborzunov/NonLinearReactionAdvectionDiffusionWithFrontData.jl", "max_issues_repo_head_hexsha": "006aff15ac0dcbd7aaea3d9a23d3c1ff6bd48613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-01-23T12:01:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-11T12:51:34.000Z", "max_forks_repo_path": "test/direct_jacobian.jl", "max_forks_repo_name": "aborzunov/NonLinearReactionAdvectionDiffusionWithFrontData.jl", "max_forks_repo_head_hexsha": "006aff15ac0dcbd7aaea3d9a23d3c1ff6bd48613", "max_forks_repo_licenses": ["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.3043478261, "max_line_length": 97, "alphanum_fraction": 0.6176772867, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7669590185470602}}
{"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(-\u03c0, \u03c0; 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]; \u03c3 = 10.0, \u03c1 = 28.0, \u03b2 = 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]; \u03c3 = 10.0, \u03c1 = 28.0, \u03b2 = 8/3)\n    return CDS(loop, u0, [\u03c3, \u03c1, \u03b2], loop_jac)\nend\nfunction loop(u, p, t)\n    @inbounds begin\n        \u03c3 = p[1]; \u03c1 = p[2]; \u03b2 = p[3]\n        du1 = \u03c3*(u[2]-u[1])\n        du2 = u[1]*(\u03c1-u[3]) - u[2]\n        du3 = u[1]*u[2] - \u03b2*u[3]\n        return SVector{3}(du1, du2, du3)\n    end\nend\nfunction loop_jac(u, p, t)\n    @inbounds begin\n        \u03c3, \u03c1, \u03b2 = p\n        J = @SMatrix [-\u03c3  \u03c3  0;\n        \u03c1 - u[3]  (-1)  (-u[1]);\n        u[2]   u[1]  -\u03b2]\n        return J\n    end\nend\n\nfunction lorenz_iip(u0=[0.0, 10.0, 0.0]; \u03c3 = 10.0, \u03c1 = 28.0, \u03b2 = 8/3)\n    return CDS(liip, u0, [\u03c3, \u03c1, \u03b2], liip_jac)\nend\nfunction liip(du, u, p, t)\n    @inbounds begin\n        \u03c3 = p[1]; \u03c1 = p[2]; \u03b2 = p[3]\n        du[1] = \u03c3*(u[2]-u[1])\n        du[2] = u[1]*(\u03c1-u[3]) - u[2]\n        du[3] = u[1]*u[2] - \u03b2*u[3]\n        return nothing\n    end\nend\nfunction liip_jac(J, u, p, t)\n    @inbounds begin\n    \u03c3, \u03c1, \u03b2 = p\n    J[1,1] = -\u03c3; J[1, 2] = \u03c3; J[1,3] = 0\n    J[2,1] = \u03c1 - 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] = -\u03b2\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\u00f6ssler [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\u00f6ssler, 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 = [\u03c0/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 [\u03b81, d\u03b81/dt, \u03b82, d\u03b82/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=[\u03c0/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\u00e9non\u2013Heiles 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\u00e9non, M. & Heiles, C., The Astronomical Journal **69**, pp 73\u201379 (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 \u2265 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]; \u03c9 = 2.2, f = 27.0, d = 0.2, \u03b2 = 1)\nThe (forced) duffing oscillator, that satisfies the equation\n```math\n\\\\ddot{x} + d\\\\cdot\\\\dot{x} + \u03b2*x + x^3 = f\\\\cos(\\\\omega t)\n```\nwith `f, \u03c9` 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()]; \u03c9 = 2.2, f = 27.0, d = 0.2, \u03b2 = 1)\n\n    J = zeros(eltype(u0), 2, 2)\n    J[1,2] = 1\n    return CDS(duffing_eom, u0, [\u03c9, f, d, \u03b2], duffing_jacob)\nend\n@inbounds function duffing_eom(x, p, t)\n    \u03c9, f, d, \u03b2 = p\n    dx1 = x[2]\n    dx2 = f*cos(\u03c9*t) - \u03b2*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    \u03c9, f, d, \u03b2 = p\n    return @SMatrix [0 1 ;\n    (-\u03b2 - 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); \u03bc = 0.119, \u03bd = 0.1, \u0393 = 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); \u03bc = 0.119, \u03bd = 0.1, \u0393 = 0.9)\n    return CDS(gissinger_eom, u0, [\u03bc, \u03bd, \u0393])\nend\nfunction gissinger_eom(u, p, t)\n    \u03bc, \u03bd, \u0393 = p\n    du1 = \u03bc*u[1] - u[2]*u[3]\n    du2 = -\u03bd*u[2] + u[1]*u[3]\n    du3 = \u0393 - u[3] + u[1]*u[2]\n    return SVector{3}(du1, du2, du3)\nend\n\n\"\"\"\n```julia\nrikitake(u0 = [1, 0, 0.6]; \u03bc = 1.0, \u03b1 = 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\u2013105, (1958)\n\"\"\"\nfunction rikitake(u0 = [1, 0, 0.6]; \u03bc = 1.0, \u03b1 = 1.0)\n    return CDS(rikitake_eom, u0, [\u03bc, \u03b1])\nend\nfunction rikitake_eom(u, p, t)\n    \u03bc, \u03b1 = p\n    x,y,z = u\n    xdot = -\u03bc*x + y*z\n    ydot = -\u03bc*y + x*(z - \u03b1)\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\u03c3s = A \\ b\n\n##\nsum(\u03c3s)\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.(\u03c3s[1:end-1], \u03c3s[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\u03b3s = A \\ b\n\n##\nsum(\u03b3s)\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.(\u03b3s[1:end-1], \u03b3s[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.(\u03c3s[1:end-1], \u03c3s[2:end], \u03b3s[1:end-1], \u03b3s[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(\u03c1)\n\nReturns the generalized Bloch vector ``\\\\mathbf{r}`` for the density operator \u03c1.\n\nIf \u03c1 is a ``N \u00d7 N`` density operator, ``\\\\mathbf{r}`` will be a ``N^2 - 1``\nvector of real values. We follow the formula\n``\u03c1 = \\\\frac{1}{N} (I + \\\\sqrt{N} \\\\mathbf{r} \\\\cdot \\\\mathbf{\u03bb})``\n\"\"\"\nfunction bloch_vector(\u03c1)\n   n = size(\u03c1)[1]\n   \u03bb = sun_generators(n)\n   sqrt(n)/2*real([tr(\u03bb[i] * \u03c1) for i = 1: length(\u03bb)])\nend\n\n\"\"\"\n    density_operator(r)\n\nReturns the density operator \u03c1 corresponding to the Bloch vector `r`.\n\n`vec` must be a vector of ``N^2-1`` real values. We follow the formula\n``\u03c1 = \\\\frac{1}{N} (I + \\\\sqrt{N} \\\\mathbf{r} \\\\cdot \\\\mathbf{\u03bb})``\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   \u03bb = sun_generators(Nq) # Obtain the generators of the SU(N) Hilbert space\n\n   1/Nq*(I + sqrt(Nq) * sum([vec[i] * \u03bb[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    \u03bb = 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(\u03bb[i],\u03bb[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, \u03bb, 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(\u03bb)`,\nand the array of SU(N) generators \u03bb (`sun_generators(n)`).\n\nWhen providing `f`, the calculations are much faster (especially if many\ngenerators have to be evaluated).\n\"\"\"\nfunction igen(f, \u03bb, 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 \u03bb[1:end-nimag]])\n    else\n        ak = real([tr(H*lambda) for lambda in \u03bb])\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(\u03bb)\n\nReturns the totally antisymmetric tensor ``i f_{ijk}`` of the structure constants\nof the list of generators \u03bb, defined as ``f_{ijk} = - 2 i \\\\text{Tr}([\u03bb_i,\u03bb_j]\u03bb_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\u0304.\n(Note that n must be a power of 2 (n = 2\u1d4f))\nReturns:\ny\u0304 - A complex array of size n \n\"\"\"\nfunction FFT(n::Integer, x\u0304::Array{<:Number})\n    # Julia is 1-indexed\n    if n == 1\n        return [x\u0304[1]]\n    end\n\n    evens = [x\u0304[Int(2i)] for i = 1:n/2]\n    odds = [x\u0304[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\u0304 = FFT(Int(n/2), odds)\n    v\u0304 = FFT(Int(n/2), evens)\n    y\u0304 = zeros(Complex, n)\n    for j = 1:n\n        \u03c4 = exp(2\u03c0*im*(j-1)/n) \n        y\u0304[j] = u\u0304[(j-1)%Int(n/2)+1] + \u03c4 * v\u0304[(j-1)%Int(n/2)+1]\n    end\n    y\u0304\nend\n\nn = 4\nx\u0304 = [1 1 0im 2]\ny\u0304 = FFT(n, x\u0304)\ndisplay(y\u0304)\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# \u2554\u2550\u2561 e55010c0-b76d-11eb-2a21-d971845b6910\nbegin\n\tusing Plots,PlutoUI,ForwardDiff\n\tplotlyjs()\nend\n\n# \u2554\u2550\u2561 1b5d7083-faaf-4cdb-8a7f-3ccbf9af47d9\nf(x) = x^2\n\n# \u2554\u2550\u2561 8861d281-5968-482d-8c0c-9d5308335411\nmd\"\"\"\nx\u2080 = $(@bind x\u2080 Slider(-3:0.1:3,default=0,show_value=true))\n\n\u0394x = $(@bind \u0394x Slider(0.01:0.1:1,default=1,show_value=true))\n\"\"\"\n\n# \u2554\u2550\u2561 c10041fe-bbe9-45b5-a405-56cabda81ccf\nbegin\n\tf\u2093(x) = ForwardDiff.derivative(f,x)\n\tL(x) = f\u2093(x\u2080)*(x-x\u2080) + f(x\u2080) \n\tplot(f,label=\"f(x)\",ylim=[-10,10])\n\t# plot!(f\u2093,label=\"f'(x)\")\n\tplot!(L,label=\"L(x)\")\n\tx1 = x\u2080+\u0394x \n\tplot!([(x1,L(x1)),(x1,f(x1))],label=\"\u0394f-df\",with=3)\n\tplot!([(x1,f(x\u2080)),(x1,L(x1))],width=2,label=false,color=:black)\n\tplot!([(x\u2080,f(x\u2080)),(x1,f(x\u2080))],width=2,label=false,color=:black)\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550e55010c0-b76d-11eb-2a21-d971845b6910\n# \u2560\u25501b5d7083-faaf-4cdb-8a7f-3ccbf9af47d9\n# \u255f\u25008861d281-5968-482d-8c0c-9d5308335411\n# \u255f\u2500c10041fe-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\u03a9(x::Vector) = sum((abs.(x) .- 1).^2)\nh(x::Vector) = f(x) + \u03a9(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\u03b1 = 1.0\n\n# Initialize coordinates\n\u03f5 = 1e-3\nx = [-1. - \u03f5, 1. + \u03f5/2, -1. - \u03f5/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\u0142adno\u015b\u0107 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\u00f3rym funkcja f ma przeciwny znak ni\u017c w punkcie b\n    a \u2013 poprzednia warto\u015b\u0107 punktu a, u\u017cywana do wyliczania nast\u0119pnego punktu metod\u0105 siecznych\n    \n    Metoda bisekcji z punkt\u00f3w b i c tworzy punkt m pomi\u0119dzy nimi na \u015brodku przedzia\u0142u.\n    \n    Wyliczany jest ci\u0105g xi, kt\u00f3rego ostatni element oznaczany jest przez x, a poprzedni przez xp.\n    \n    xk - ostatni punkt w ci\u0105gu, kt\u00f3ry ma r\u00f3\u017cny znak ni\u017c x.\n    \n    Punkt x wyliczany jest dwoma metodami:\n        - siecznych\n        - bisekcji\n    i wybierany jest ten obliczony z metody siecznych je\u015bli le\u017cy pomi\u0119dzy punktem b\n    (ze wzgl\u0119d\u00f3w dok\u0142adno\u015bciowych z pewn\u0105 poprawk\u0105) a punktem m wyliczonym z bisekcji.\n\n    Je\u017celi f(x) czy f(xk) le\u017cy bli\u017cej zera i je\u015bli f(x) le\u017cy bli\u017cej zera\n    wtedy b ma warto\u015b\u0107 x, c ma warto\u015b\u0107 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": "\n\"\"\"\nSearch.Circle(x, y, radius)\n\nCreate a `Search.Circle` that can be used for spatial lookup.\n\nSee also `AbstractRegion`\n\"\"\"\nstruct Circle{T <: Real} <: AbstractRegion{T}\n    x::T\n    y::T\n    radius::T\nend\n\n\"\"\"\n    area(circle)\n\nReturns the area of the `circle`.\n\"\"\"\n@inline area(t::Circle) = \u03c0 * t.radius * t.radius\n\nfunction boundingbox(c::Circle{T}) where T\n    xmin, xmax = c.x - c.radius, c.x + c.radius\n    ymin, ymax = c.y - c.radius, c.y + c.radius\n    zmin, zmax = typemin(T), typemax(T)\n    return BoundingBox{T}(xmin, ymin, zmin, xmax, ymax, zmax)\nend\n\nfunction in(p::StaticVector{3,T}, region::Region) where T <: Real where Region <: Circle\n    r\u00b2 = region.radius * region.radius\n    \u0394x = p[1] - region.x\n    \u0394y = p[2] - region.y\n    return \u0394x*\u0394x + \u0394y*\u0394y <= r\u00b2\nend\n\n", "meta": {"hexsha": "cb75dca148189f8b38c30191d1ce069f9c1d48d1", "size": 781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Circle.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/Circle.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/Circle.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": 21.6944444444, "max_line_length": 88, "alphanum_fraction": 0.6235595391, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7667889398877165}}
{"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 \u03bb_2\n    e_vals = eigfact(L,2:2)\n    \u03bb = e_vals.values\n    \u03bd = e_vals.vectors\n    if vecs\n        return \u03bb, \u03bd\n    else\n        return \u03bb\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 \u03bb_2\n    \u03bb = s[2][end-1]\n    \u03bd = s[1][:,end-1]\n    if vecs\n        return \u03bb, \u03bd\n    else\n        return \u03bb\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(\u03bc, \u03a3, clr=\"b\", label=\"\"; alpha=1.0)\n##########################################################\n\n    # calculate eigevanlues\n    E = eigvals(\u03a3)\n    @assert(E[1]<=E[2])\n\n    # calculate eigenvectors, columns are the eigenvectors\n    V = eigvecs(\u03a3)\n\n    \u03d5 = atan(V[2,2], V[1,2]) # was atan2\n\n    if(\u03d5 < 0.0)\n        \u03d5 = \u03d5 + 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.(\u03d5) sin.(\u03d5); -sin.(\u03d5) cos.(\u03d5) ];\n\n\n    # let's rotate the ellipse to angle \u03d5\n    r_ellipse = [ellipse_x_r ellipse_y_r]  * R\n\n    PyPlot.plot(\u03bc[1], \u03bc[2], \"x\", markersize=12, markeredgewidth=4, color=clr, alpha=alpha)\n    PyPlot.plot(r_ellipse[:,1] .+ \u03bc[1], r_ellipse[:,2] .+ \u03bc[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] .+ \u03bc[1], a_pnts[:,2] .+ \u03bc[2], @sprintf(\"--%s\",clr), linewidth=2, alpha=alpha)\n    PyPlot.plot(b_pnts[:,1] .+ \u03bc[1], b_pnts[:,2] .+ \u03bc[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(\u03b8) for \u03b8 in range(\u03c0, 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 \u2208 [-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 \u2264 s \u2264 1 || throw(DomainError(\"s \u2209 [-1,1]\"))\n    T\u208b = s\n    T  = one(S)\n\n    for i in 1:offset\n        T\u208b, T = T, 2s*T - T\u208b\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\u208b, T = T, 2s*T - T\u208b\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 \u2208 [-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 \u2264 s \u2264 1 || throw(DomainError(\"s \u2209 [-1,1]\"))\n    U\u208b = zero(s)\n    U  = one(S)\n\n    for i in 1:offset\n        U\u208b, U = U, 2s*U - U\u208b\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\u208b, U = U, 2s*U - U\u208b\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\u207b\u00b9\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": "@testset \"LTI system kernels tests\" begin\n    N = 10\n    types = [Int32, Int64, Float32, Float64, ComplexF32, ComplexF64]\n    atol = 1e-2\n    \n    @testset \"differentiator tests\" begin\n        \u0394t = 0.1\n        s = Romeo.LTI.Diff{Float64}(1)\n\n        k = Romeo.LTI.kernel(s, N, \u0394t)\n        @test k[1] == 1/\u0394t || \"The first element of the differentiation kernel should be equal to 1/\u0394t\"\n        @test k[2] == -1/\u0394t || \"The second element of the differentiation kernel should be -1/\u0394t\"\n        for i = 3:N\n            @test k[i] == 0 || \"All elements with index \u22653 of the differentiation kernel should be zero.\"\n        end # for\n\n        ys = Romeo.LTI.step_resp(s, N, \u0394t)\n        @test ys[1] == 1/\u0394t || \"The first element of the step response of a differentiator should be 1/\u0394t.\"\n        for i = 2:N\n            @test ys[i] == 0 || \"All elements of the step response of a differentiator should be zero, except the first one.\"\n        end # for        \n    end # testset\n\n    @testset \"identity operator tests\" begin\n        \u0394t = 0.1\n        s = Romeo.LTI.Diff{Float64}(0)\n\n        k = Romeo.LTI.kernel(s, N, \u0394t)\n        @test k[1] == 1 || \"The first element of the identity kernel should be equal to 1\"\n        for i = 2:N\n            @test k[i] == 0 || \"All elements with index \u22652 of the identity kernel should be zero.\"\n        end # for   \n\n        ys = Romeo.LTI.step_resp(s, N, \u0394t)\n        for i = 1:N\n            @test ys[i] == 1 || \"All elements of the step response of the identity kernel should be equal to 1.\"\n        end # for \n    end # testset\n\n    @testset \"integrator tests\" begin\n        \u0394t = 1\n        sinv = Romeo.LTI.Diff{Float64}(-1)\n        k = Romeo.LTI.kernel(sinv, N, \u0394t)\n        for i = 1:N\n            @test k[i] == \u0394t || \"All elements of the integration kernel should be equal to \u0394t.\"\n        end # for\n\n        ys = Romeo.LTI.step_resp(sinv, N, \u0394t)\n        for i = 1:N\n            @test ys[i] == i*\u0394t || \"All elements of the integration kernel should be equal to i*\u0394t.\"\n        end # for\n    end # testset\n\n    @testset \"fractional integrator tests\" begin\n        \u0394t = 1\n        int_0_5 = Romeo.LTI.Diff{Float64}(-0.5)\n        int_1_5 = Romeo.LTI.Diff{Float64}(-0.5)\n\n        ys = Romeo.LTI.impulse_resp(int_0_5, N, \u0394t)\n        yi = Romeo.LTI.impulse_resp(int_1_5, N, \u0394t)\n        \n        @test all(ys .== yi) || \"Step response of half integrator should match impulse response of 1.5 integrator.\"\n    end # testset\n        \nend # testset", "meta": {"hexsha": "7db8a53123c8651a5e8b20175b5e0215b6dbe84a", "size": 2464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/lti/_test_3_lti_kernel.jl", "max_stars_repo_name": "rapaja/Rome.jl", "max_stars_repo_head_hexsha": "bc17e21dcd6a17aabe16d0486348f87d14866999", "max_stars_repo_licenses": ["MIT"], "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/lti/_test_3_lti_kernel.jl", "max_issues_repo_name": "rapaja/Rome.jl", "max_issues_repo_head_hexsha": "bc17e21dcd6a17aabe16d0486348f87d14866999", "max_issues_repo_licenses": ["MIT"], "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/lti/_test_3_lti_kernel.jl", "max_forks_repo_name": "rapaja/Rome.jl", "max_forks_repo_head_hexsha": "bc17e21dcd6a17aabe16d0486348f87d14866999", "max_forks_repo_licenses": ["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.9076923077, "max_line_length": 125, "alphanum_fraction": 0.5710227273, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7667781936196284}}
{"text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n#Pkg.add(\"ForwardDiff\")\n#Pkg.add(\"SpecialFunctions\")\n#Pkg.update()\n#Pkg.checkout(\"ForwardDiff\")\n#Pkg.status()\nusing Printf\nusing SpecialFunctions\nusing ForwardDiff\n\ninclude(\"common.jl\")\n\n# input should be 1 dimensional\nfunction logsumexp(x)\n  mx = maximum(x)\n  log.(sum(exp.(x .- mx))) .+ mx\nend\n\n@inbounds function gmm_objective(alphas,means,icf,x,wishart::Wishart)\n  d = size(x,1)\n  n = size(x,2)\n  CONSTANT = -n*d*0.5*log(2 * pi)\n\n  sum_qs = sum(icf[1:d,:],dims=1)\n  slse = sum(sum_qs)\n  Qs = [get_Q(d,icf[:,ik]) for ik in 1:k]\n  main_term = zeros(eltype(alphas),1,k)\n\n  slse = 0.\n  for ix=1:n\n    for ik=1:k\n      main_term[ik] = -0.5*sum(abs2, Qs[ik] * (x[:,ix] - means[:,ik]))\n    end\n    slse += logsumexp(alphas + sum_qs + main_term)\n  end\n\n  CONSTANT + slse - n*logsumexp(alphas) + log_wishart_prior(wishart, sum_qs, Qs, icf)\nend\n\n# Read instance\nif length(ARGS) < 5\n  throw(\"Too few args\")\nend\n\ndir_in = ARGS[1]\ndir_out = ARGS[2]\nfn = ARGS[3]\nnruns_f = parse(Int,ARGS[4])\nnruns_J = parse(Int,ARGS[5])\nreplicate_point = size(ARGS,1) >= 6 && ARGS[6] == \"-rep\"\n\nfn_in = string(dir_in, fn)\nfn_out = string(dir_out, fn)\n\nalphas,means,icf,x,wishart = read_gmm_instance(string(fn_in,\".txt\"),replicate_point)\nd = size(means,1)\nk = size(means,2)\nn = size(x,2)\n\n# Objective\n# Call once in case of precompilation etc\nerr = gmm_objective(alphas,means,icf,x,wishart)\n\ntf = @elapsed for i in 1:nruns_f\n  gmm_objective(alphas,means,icf,x,wishart)\nend\ntf = tf/nruns_f;\n@printf \"tf: %g\\n\" tf\n#@printf \"err: %f\\n\" err\n\n# Gradient helper\nfunction wrapper_gmm_objective(packed)\n  alphas,means,icf = unpack(d,k,packed)\n  gmm_objective(alphas,means,icf,x,wishart)\nend\n\n# Gradient\ng = x-> ForwardDiff.gradient(wrapper_gmm_objective, x)\n\nJ = g(pack(alphas,means,icf))\n\ntJ = @elapsed for i in 1:nruns_J\n  g(pack(alphas,means,icf))\nend\ntJ = tJ/nruns_J;\n@printf \"tJ: %g\\n\" tJ\n#println(\"J:\")\n#println(J)\n\nname = \"Julia\"\n\nwrite_J(string(fn_out,\"_J_\",name,\".txt\"),J)\nwrite_times(string(fn_out,\"_times_\",name,\".txt\"),tf,tJ)\n\n", "meta": {"hexsha": "b312c02b8b1e8e9129fdbe69bd9179685f9004f4", "size": 2078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tools/Julia/gmm_F.jl", "max_stars_repo_name": "dsyme/ADBench", "max_stars_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58, "max_stars_repo_stars_event_min_datetime": "2019-12-30T16:22:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T12:26:51.000Z", "max_issues_repo_path": "tools/Julia/gmm_F.jl", "max_issues_repo_name": "dsyme/ADBench", "max_issues_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 112, "max_issues_repo_issues_event_min_datetime": "2019-05-25T07:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T13:55:33.000Z", "max_forks_repo_path": "tools/Julia/gmm_F.jl", "max_forks_repo_name": "dsyme/ADBench", "max_forks_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-03-12T16:37:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T10:14:37.000Z", "avg_line_length": 21.4226804124, "max_line_length": 85, "alphanum_fraction": 0.6785370549, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.766778185571263}}
{"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,\u03c8,d\u03c8,Ne,Np,Nq,DFloat)\n\n    #Initialize Global Arrays\n    \u03be_x=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03be_y=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03be_z=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03b7_x=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03b7_y=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03b7_z=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03b6_x=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03b6_y=zeros(DFloat,Nq,Nq,Nq,Ne)\n    \u03b6_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\u03be; dx/d\u03b7; dy/d\u03be; dy/d\u03b7\n        (x_\u03be,x_\u03b7,x_\u03b6)=map_deriv(\u03c8,d\u03c8,x,Np,Nq,DFloat)\n        (y_\u03be,y_\u03b7,y_\u03b6)=map_deriv(\u03c8,d\u03c8,y,Np,Nq,DFloat)\n        (z_\u03be,z_\u03b7,z_\u03b6)=map_deriv(\u03c8,d\u03c8,z,Np,Nq,DFloat)\n\n        #Construct Inverse Mapping: d\u03be/dx; d\u03be/dy; d\u03b7/dx; d\u03b7/dy\n        for k=1:Nq, j=1:Nq, i=1:Nq\n            xj = (x_\u03be[i,j,k]*y_\u03b7[i,j,k]*z_\u03b6[i,j,k] - x_\u03be[i,j,k]*y_\u03b6[i,j,k]*z_\u03b7[i,j,k]) -\n            (y_\u03be[i,j,k]*x_\u03b7[i,j,k]*z_\u03b6[i,j,k] - y_\u03be[i,j,k]*x_\u03b6[i,j,k]*z_\u03b7[i,j,k]) +\n            (z_\u03be[i,j,k]*x_\u03b7[i,j,k]*y_\u03b6[i,j,k] - z_\u03be[i,j,k]*x_\u03b6[i,j,k]*y_\u03b7[i,j,k])  \n\n            \u03be_x[i,j,k,e]= (y_\u03b7[i,j,k]*z_\u03b6[i,j,k]-y_\u03b6[i,j,k]*z_\u03b7[i,j,k])/xj\n            \u03be_y[i,j,k,e]=-(x_\u03b7[i,j,k]*z_\u03b6[i,j,k]-x_\u03b6[i,j,k]*z_\u03b7[i,j,k])/xj\n            \u03be_z[i,j,k,e]= (x_\u03b7[i,j,k]*y_\u03b6[i,j,k]-x_\u03b6[i,j,k]*y_\u03b7[i,j,k])/xj\n            \u03b7_x[i,j,k,e]=-(y_\u03be[i,j,k]*z_\u03b6[i,j,k]-y_\u03b6[i,j,k]*z_\u03be[i,j,k])/xj\n            \u03b7_y[i,j,k,e]= (x_\u03be[i,j,k]*z_\u03b6[i,j,k]-x_\u03b6[i,j,k]*z_\u03be[i,j,k])/xj\n            \u03b7_z[i,j,k,e]= -(x_\u03be[i,j,k]*y_\u03b6[i,j,k]-x_\u03b6[i,j,k]*y_\u03be[i,j,k])/xj\n            \u03b6_x[i,j,k,e]= (y_\u03be[i,j,k]*z_\u03b7[i,j,k] -y_\u03b7[i,j,k]*z_\u03be[i,j,k])/xj\n            \u03b6_y[i,j,k,e]=-(x_\u03be[i,j,k]*z_\u03b7[i,j,k] -x_\u03b7[i,j,k]*z_\u03be[i,j,k])/xj\n            \u03b6_z[i,j,k,e]= (x_\u03be[i,j,k]*y_\u03b7[i,j,k] -x_\u03b7[i,j,k]*y_\u03be[i,j,k])/xj   \n            jac[i,j,k,e]=abs(xj)      \n        end #i, j, k\n    end #e\n\n    return (\u03be_x,\u03be_y,\u03be_z,\u03b7_x,\u03b7_y,\u03b7_z,\u03b6_x,\u03b6_y,\u03b6_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": "@testset \"Measure\" begin\n    Mod.@polyvar x y\n    @test_throws ArgumentError measure([1, 2], [x, x*y, y])\n    @test_throws ArgumentError measure([1, 2, 3, 4], [x, x*y, y])\n    \u03bc = measure([1, 0, 2, 3], [x^2*y^2, y*x^2, x*y*x^2, x*y^2])\n    @test base_functions(\u03bc) == MonomialBasis(monovec([x^3*y, x^2*y^2, x^2*y, x*y^2]))\n    @test base_function.(moments(\u03bc)) == [x^3*y, x^2*y^2, x^2*y, x*y^2]\n    @test MultivariateMoments.moment_value.(moments(\u03bc)) == [2, 1, 0, 3]\n    @test all(nvariables.(moments(\u03bc)) .== 2)\n    @test degree.(moments(\u03bc)) == [4, 4, 3, 3]\n    @test \u03bc.values == [2, 1, 0, 3]\n    @test (-\u03bc).values == [-2, -1, 0, -3]\n    @test (2 * \u03bc).values == [4, 2, 0, 6]\n    @test (\u03bc * 3).values == [6, 3, 0, 9]\n    #@test_throws ArgumentError measure([1], [x]) + measure([1], [y])\n\n    @testset \"Measure MB\" begin\n        Mod.@polyvar x y\n        @test_throws AssertionError measure([1, 0, 2, 3, 0], maxdegree_basis(ChebyshevBasis, [x, y], 2))\n        @test_throws AssertionError measure([1, 0, 2, 3, 0, 4], maxdegree_basis(ChebyshevBasis, [x, y], 3))\n        \u03bc = measure([1, 0, 2, 3, 0, 4], maxdegree_basis(ChebyshevBasis, [x, y], 2))\n        @test base_functions(\u03bc) ==  maxdegree_basis(ChebyshevBasis, [x, y], 2)\n        @test base_function.(moments(\u03bc)) == [2.0x^2 - 1.0, x*y, 2.0y^2 - 1.0, x, y, 1.0]\n        @test MultivariateMoments.moment_value.(moments(\u03bc)) == [1, 0, 2, 3, 0, 4]\n        @test all(nvariables.(moments(\u03bc)) .== 2)\n        @test degree.(moments(\u03bc)) == [2, 2, 2, 1, 1, 0]\n        @test \u03bc.values == [1, 0, 2, 3, 0, 4]\n        @test (-\u03bc).values == -[1, 0, 2, 3, 0, 4]\n        @test (2 * \u03bc).values == [1, 0, 2, 3, 0, 4].*2\n        @test (\u03bc * 3).values == [1, 0, 2, 3, 0, 4].*3\n\n    end\nend\n", "meta": {"hexsha": "80088de372cc4647a10b26d83dd96b537596b1e9", "size": 1709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/measure.jl", "max_stars_repo_name": "tweisser/MultivariateMoments.jl", "max_stars_repo_head_hexsha": "5df0b32562a244f36d1b928be66946b8f9336f87", "max_stars_repo_licenses": ["MIT"], "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/measure.jl", "max_issues_repo_name": "tweisser/MultivariateMoments.jl", "max_issues_repo_head_hexsha": "5df0b32562a244f36d1b928be66946b8f9336f87", "max_issues_repo_licenses": ["MIT"], "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/measure.jl", "max_forks_repo_name": "tweisser/MultivariateMoments.jl", "max_forks_repo_head_hexsha": "5df0b32562a244f36d1b928be66946b8f9336f87", "max_forks_repo_licenses": ["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.2647058824, "max_line_length": 107, "alphanum_fraction": 0.5330602692, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7666621801584488}}
{"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 \"\u03bachn^2 cannot exceed \u03badiv*\u03bacon\"\n\t@assert kcon>=0 \"Negative \u03bacon is not allowed\"\n\t@assert kdiv>=0 \"Negative \u03badiv is not allowed\"\n\t@assert kchn>=0 \"Negative \u03bachn 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 \u201906. Association for Computing Machinery,\nNew York, NY, USA, pp. 287\u2013296. 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 \u201901. Association for Computing Machinery, \nNew York, NY, USA, pp. 274\u2013281. 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 \u201906. Association for Computing Machinery,\nNew York, NY, USA, pp. 287\u2013296. 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 \u2208 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": "using Distributed\nusing StatsPlots\n\naddprocs(4)\n\n@everywhere using CSV\n@everywhere using DataFrames\n@everywhere using StatsFuns: logistic\n@everywhere using Turing\n\n\"\"\"\n    get_data(path, :y_label)\n\nReturns data for the logistic model split by X, y structure. \nRetruns included breast cancer data by default.\n\n# Arguments:\n- `path::String=\"data/breast_cancer.csv\"` path to csv file. \n- `y_label::Symbol=:diagnosis` y label for target/dependent variable\n\n# Returns:\n- `X` Matrix containing X data/exogenous variables.\n- `y` Vector containing y label data/endogenous variables. \n\"\"\"\n@everywhere function get_data(\n        path::String=\"data/breast_cancer.csv\",\n        y_label::Symbol=:diagnosis\n    )\n    df = DataFrame(CSV.File(path))\n    y = df[!, y_label]\n    X = convert(Matrix, select!(df, Not(y_label)))\n    X = (X .- mean(X, dims=1)) ./ std(X, dims=1)\n    return X, y\nend\n\n\"\"\"\n    logistic_regression(x::Matrix{Float64}, y::Vector{Int64})\n\nCreates a logistic model to be used as an input argument in a sampler. \n\n# Arguments:\n- `X::Matrix{Float64}`: Exogenous input data X in matrix format. \n- `y::Vector{Int64}`: Endogenous/dependent variables vector.\n\"\"\"\n@everywhere @model function logistic_regression(\n        X::Matrix{Float64},\n        y::Vector{Int64}\n    )\n    intercept ~ Normal(0, sqrt(25))\n\n    nfeatures = size(X, 2)\n    n = size(X, 1)\n    slopes ~ MvNormal(nfeatures, sqrt(25))\n    p = intercept .+ X * slopes\n    for i = 1:n\n\n        y[i] ~ Bernoulli(logistic(p[i]))\n\n    end\nend\n\n\"\"\"\n    profiler(X::Matrix{Float64}, y::Vector{Int64}, max_iters::Int64=10)\n\n# Arguments:\n- `X::Matrix{Float64}`: Exogenous variables\n- `y::Matrix{Int64}`: Endogenous variables \n- `max_iters::Int64`: The specified number of iterations to execute the sampler for logistic regression.\n\n# Returns:\n- `times::Vector{Any}`: Execution times for each iteration.\n- `trace::Chains{Any}`: The trace generated in the final sample. \n\"\"\"\n@everywhere function profiler(\n        X::Matrix{Float64},\n        y::Vector{Int64},\n        max_iters::Int64=10\n    )\n    times = []\n    for iteration in 1:max_iters\n\n        time = @elapsed global trace = sample(\n                logistic_regression(X, y),\n                NUTS(1000, 0.90),\n                MCMCDistributed(),\n                1000,\n                4\n            )\n        append!(times, time)\n    end\n    return times, trace\nend\n\n@everywhere function main()\n    X, y = get_data()\n    times, traces = profiler(X, y)\n    println(times)\n    return times, trace\nend\n\ntimes, trace = main()\n", "meta": {"hexsha": "7ae8f218212095b12fbc05af0ced851be1218e10", "size": 2527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "shops/pymc3_turing_comparison/turing_test.jl", "max_stars_repo_name": "mtaung/bazaar", "max_stars_repo_head_hexsha": "3b82ffaec3767b3412d5e0460f315b59329d613a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shops/pymc3_turing_comparison/turing_test.jl", "max_issues_repo_name": "mtaung/bazaar", "max_issues_repo_head_hexsha": "3b82ffaec3767b3412d5e0460f315b59329d613a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shops/pymc3_turing_comparison/turing_test.jl", "max_forks_repo_name": "mtaung/bazaar", "max_forks_repo_head_hexsha": "3b82ffaec3767b3412d5e0460f315b59329d613a", "max_forks_repo_licenses": ["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.7745098039, "max_line_length": 104, "alphanum_fraction": 0.6434507321, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.766662167580929}}
{"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": "using StatsBase, Plots ; gr()\n\nfunction proportionFished(gF,sF,n,N,withReplacement = false)\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\nN = 10^6\ngoldFish, silverFish, n = 3, 4, 3\nplot()\nproportionFished(goldFish, silverFish, n, N)\nproportionFished(goldFish, silverFish, n, N, true)\n", "meta": {"hexsha": "17d6dbf885fd43a2e14df6b52106519dec283688", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_chapter/fishing.jl", "max_stars_repo_name": "newptcai/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "ce4d9d00122cee3f7c918c1545c989a39ff1319a", "max_stars_repo_licenses": ["MIT"], "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_chapter/fishing.jl", "max_issues_repo_name": "newptcai/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "ce4d9d00122cee3f7c918c1545c989a39ff1319a", "max_issues_repo_licenses": ["MIT"], "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_chapter/fishing.jl", "max_forks_repo_name": "newptcai/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "ce4d9d00122cee3f7c918c1545c989a39ff1319a", "max_forks_repo_licenses": ["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.2051282051, "max_line_length": 74, "alphanum_fraction": 0.5781818182, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7666621626614498}}
{"text": "\n#=\n\n=#\n\nusing DataStructures\nusing IterTools\nfunction value_iteration(S,A,P,R,\u0398)\n\u03b3 = 0.9\nV\u2080 = DefaultDict{Tuple{Int,Int},Int}(0)\nVk::Array{Any} = [V\u2080]\nk = 1\nV\u2081::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\u2032 -> R(s,a,s\u2032),[S...]))\n            println(broadcast(s\u2032 -> P(s\u2032,s,a),[S...]))=#\n            #push!(Vp,sum(broadcast(s\u2032 -> P(s\u2032,s,a)*R(s,a,s\u2032),[S...])))\n            push!(Vp, sum(broadcast(s\u2032 -> P(s\u2032,s,a)*(R(s,a,s\u2032)+\u03b3*Vk[k-1][s\u2032]),[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]))) < \u0398 && 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\u2032,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\u2032] .== Near) && return 0\n\n    Action[findin(Near,[s\u2032])][1]\n\nend\nfunction R(s,a,s\u2032)\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), (\u03bc, y) -> kl_divergence(y, \u03bc));\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), (\u03bc, y) -> kl_divergence(y, \u03bc))\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\u03bd = sqrt(median(distances[i] for i in CartesianIndices(distances) if i[1] < i[2]))\nkernel = with_lengthscale(GaussianKernel(), \u03bd) \u2297 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": "# Check of handedness\n@test rotationmatrix_normalized(qrotation_x(\u03c0/2)) * [0, 1, 0] \u2248 [0, 0, 1]\n@test rotationmatrix_normalized(qrotation_y(\u03c0/2)) * [1, 0, 0] \u2248 [0, 0, -1]\n@test rotationmatrix_normalized(qrotation_z(\u03c0/2)) * [1, 0, 0] \u2248 [0, 1, 0]\n\n# Simple composition of rotations\n@test qrotation_x(\u03c0/3) * qrotation_x(\u03c0/3) \u2248 qrotation_x(2\u03c0/3)\n@test qrotation_y(\u03c0/3) * qrotation_y(\u03c0/3) \u2248 qrotation_y(2\u03c0/3)\n@test qrotation_z(\u03c0/3) * qrotation_z(\u03c0/3) \u2248 qrotation_z(2\u03c0/3)\n\n# More complex compositions\ncomp = qrotation_y(\u03c0/2) * qrotation_x(\u03c0/2)\n@test rotationmatrix_normalized(comp) * [0, 1, 0] \u2248 [1, 0, 0]\n\ncomp = qrotation_z(\u03c0/2) * qrotation_y(\u03c0/2)\n@test rotationmatrix_normalized(comp) * [0, 0, 1] \u2248 [0, 1, 0]\n", "meta": {"hexsha": "06e1f1d2d3056668b5633fe66fed3d0393781ce3", "size": 706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_quaternions.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": "test/test_quaternions.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": "test/test_quaternions.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": 41.5294117647, "max_line_length": 74, "alphanum_fraction": 0.6827195467, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.766652975264224}}
{"text": "using Printf\nimport Flux: \u03c3\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(\u03c0*x) + 1.0,  \n        c(t, x_min) ~ c(t, x_max)\n        \n]\n\n# Space and time domains\ndomains = [t \u2208 IntervalDomain(0.0,t_max),\n        x \u2208 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, \u03c3),\n                    FastDense(hidden, hidden, \u03c3),\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\u03b8 = discretization.init\u03b8\n\nacum =  [0;accumulate(+, length.(init\u03b8))]\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\u03c0)\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": "# Magic Square Generator\n# ======================\n#\n# # Reference\n#\n# - Moler, Cleve B. Experiments with MATLAB. Society for Industrial and Applied Mathematics, 2011.\n\n# The JuliaLang community is famous for naming their functions as something like\n# `verylongfunctionnamethatistotallyunreadable` and abusing unicode characters all over the source.\n# A more appropriate name for this is probably `is\ud83c\udfa9`, but let's stick with the old style for now.\nfunction is_magic(m::AbstractMatrix{<:Integer})\n    n_r, n_c = size(m)\n    # Is square?\n    if n_r != n_c\n        return false\n    end\n\n    n = n_r\n    magic_const = (1 + n ^ 2) * n \u00f7 2\n\n    # Are all rows equal to magic constant?\n    if !all(sum(m, dims=2) .== magic_const)\n        return false\n    end\n    # Are all columns equal to magic constant?\n    if !all(sum(m, dims=1) .== magic_const)\n        return false\n    end\n    # And the two diagonals?\n    if sum([m[i, i] for i in 1:n]) != magic_const\n        return false\n    end\n    if sum([m[p...] for p in zip(1:n, n:-1:1)]) != magic_const\n        return false\n    end\n\n    true\nend\n\n# Odd ordered magic square generator\n#\n# It is easy to see the correctness of this algorithm. For example, compare the elements in each\n# column with the one to the northeast of itself, there are `n - 1` elements that are 1 less while\n# exactly 1 that is `n - 1` larger, which makes the two columns add up to the same value.\n\n\"Generates a magic square of an odd order `n` using Siamese method (De la Loub\u00e8re method).\"\nfunction odd_magic(n::Integer)\n    @assert isodd(n)\n\n    m = zeros(typeof(n), n, n)\n    r, c = 1, div(n + 1, 2)\n\n    for i in 1 : n*n\n        m[r, c] = i\n\n        # No need to do bounds checking, as only the last one will fall out of the board.\n        p = r + 1, c\n        r, c = mod1(r - 1, n), mod1(c + 1, n)\n        if m[r, c] != 0\n            r, c = p\n        end\n    end\n\n    m\nend\n\n# A vectorized version of `odd_magic`.\nfunction odd_magic_vec(n::Integer)\n    @assert isodd(n)\n    i = 1:n\n    offset = div(n - 3, 2)\n    A = @. mod(i + i' + offset, n)\n    B = @. mod(i + i' * 2 - 2, n)\n    @. n * A + B + 1\nend\n\n# TODO: Even ordered magic square generator\nfunction singly_even_magic(n::Integer)\n    error(\"unimplemented\")\nend\n\nfunction doubly_even_magic(n::Integer)\n    error(\"unimplemented\")\nend\n\nfunction magic(n::Integer)\n    if isodd(n)\n        odd_magic(n)\n    else\n        half_n = div(n, 2)\n        if isodd(half_n)\n            singly_even_magic(n)\n        else\n            doubly_even_magic(n)\n        end\n    end\nend\n\n# Unit tests\nusing Test\n\n@testset \"Odd magic square tests\" begin\n    orders = 1:2:21\n    for n in orders\n        m = odd_magic(n)\n        @test m == odd_magic_vec(n)\n        @test is_magic(m)\n    end\nend\n", "meta": {"hexsha": "2693dd5bb94e5473477f3d9352ef076ce3e99656", "size": 2741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MagicSquare/magicsquare.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": "MagicSquare/magicsquare.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": "MagicSquare/magicsquare.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.9181818182, "max_line_length": 99, "alphanum_fraction": 0.6063480482, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7666529701462901}}
{"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\u03b1 = 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\u039b(x) = forwardLogs(M,x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM),getValue(repeat(x,rep(d)...)),getValue(\u039b(x))),1)\n#\n# Setup and Optimize\ncost(x) =  fidelity(x) + \u03b1*prior(x)\nproximalMaps = [(\u03bb,x) -> proxDistance(M,\u03bb,f,x,2), (\u03bb,x) -> proxTV(M,\u03b1*\u03bb,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)-\u03b1$(replace(string(\u03b1), \".\" => \"-\")).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(\u0394) = Amp*(tanh.((x .- (0.5f0 - \u0394/2))/(\u0394/10)) - tanh.((x .- (0.5f0 + \u0394/2))/(\u0394/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\u0304 = mean(X, dims = 2)\nnoise_magnitude = Float32(2.5e-2)\nX\u2099 = X .+ (noise_magnitude*x\u0304) .* 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\u2099), color = :red,label = [\"Noisy Data\" [nothing for i in 1:Nx-1]...], legend =:bottomright)\n# Create dataset plot\npl_contour = contour(t,x,X\u2099, 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\u2099[:, 1], (t[1], t[end]), p)\n\n\n## Necessary functions\n\nfunction predict_pde(\u03b8, X = X\u2099[:, 1], T = t)\n  # No ReverseDiff if using Flux\n  Array(solve(prob_nn, Vern7(),\n        u0 = X, p = \u03b8, 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\u2099) + 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(\u03b8,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\u0302 = predict_pde(p_trained, X\u2099[:,1], tsample)\n# Trained on noisy data vs real solution\npl_trajectory = plot(tsample, transpose(X\u0302), xlabel = \"t\", ylabel =\"rho(x,t)\", color = :red,\n label = [\"UDE Approximation\" [nothing for i in 1:25]...])\nscatter!(t, transpose(X\u2099), 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\u0302 = similar(X\u0302)\nR\u0304 = similar(X\u0302)\nfor i in 1:size(X\u0302, 1), j in 1:size(X\u0302, 2)\n    R\u0302[i,j] = rx_nn(X\u0302[i,j], p_trained[1:length(p1s)])[1]\n    R\u0304[i,j] = reaction(X\u0302[i,j])\nend\n\npl_reconstruction = plot(tsample, R\u0302', label = [\"UDE Approximation\" [nothing for i in 1:25]...], color = :red, xlabel = \"t\", ylabel = \"Reaction(x,t)\")\nplot!(tsample, R\u0304', label = [\"True Reaction\" [nothing for i in 1:25]...], color = :black)\npl_reconstruction_error = plot(tsample, norm.(eachcol(R\u0302 - R\u0304)), 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\u0302[1:end, :])...)')\nRs = Matrix(vcat(eachrow(R\u0302[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\u03bbs = Float32.(exp10.(-3:0.01:5))\nopt = STLSQ(\u03bbs)\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\u2099, \"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 = \u03c6 - 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# \u2554\u2550\u2561 c07d1eba-ea4c-4ef3-82cd-7db338e40c34\nusing LinearAlgebra, PlutoUI, Plots\n\n# \u2554\u2550\u2561 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, \u0394x::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- \u0394x: search direction\n\n\tOutput:\n\t\t- t: optimal step size\n\t\"\"\"\n\tfunction quadratic_ls(P::AbstractMatrix, q::AbstractVector, \u0394x::AbstractVector,\n\t\t\t\t\t\t\t\t\t\tx::AbstractVector)\n\t\tt = solve_quadratic(\u0394x' * P * \u0394x, \u0394x' * P * x + \u0394x \u22c5 q)\n\t\treturn t\n\tend\n\n\t\"\"\"\n\t\tgradient_descent(P::AbstractArray, q::AbstractVector,\n\t\t\t\tx\u2080::AbstractVector; \u03b2::Real=0.0, \u03f5::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\u2080: starting point\n\t\t- \u03f5: convergence parameter\n\t\t- \u03b2: 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\u2080::AbstractVector; \u03b2::Real=0.0, \u03f5::Real=1e-6,\n\t\t\t\ttrack=false)\n\t\t@assert 0 \u2264 \u03b2 < 1\n\t\tx = x\u2080  # initial value\n\t\t\u0394x = zero(x)  # pre-allocate a vector for the gradient\n\t\ttrack && (path = [copy(x)])\n\t\twhile true\n\t\t\t\u0394x .= (1.0 - \u03b2) * (- P * x .- q) .+ \u03b2 *  \u0394x\n\t\t\tif norm(\u0394x) < \u03f5\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, \u0394x, x)\n\t\t\t# perform step\n\t\t\tx .+= t * \u0394x\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0a9c4cc2-375b-4e0e-85ea-bc5992a92d07\nlet\n\tp = missing\n\tq = missing\n\tr = missing\n\t\n\txstar = missing\nend\n\n# \u2554\u2550\u2561 a7f4f2fe-8a4d-4dcf-af55-d87298b5cace\n# make a plot of the quadratic curve and its solution\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f125cad0-ee03-4474-b535-c1f24c5045a2\nmd\"**Question 1**\n\nWhy is $P$ symmetric?\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8494232c-26ca-4a90-bd35-128a5bde892d\nA = [5 -1; -1 2]\n\n# \u2554\u2550\u2561 9c47ce39-f015-4d51-afe7-3c6cb946d1f0\nisposdef(A)\n\n# \u2554\u2550\u2561 5bd99c99-d60b-4998-8381-c516426607f5\nB = [0.5 3; 3 1]\n\n# \u2554\u2550\u2561 14987a6a-a984-4b04-b951-2db4e79bcac5\nisposdef(B)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6ff5822a-1c4e-491b-b215-b3a1698e2048\nlet\n\tP = missing\n\tq = missing\n\tr = missing\n\t\n\txstar = missing\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7931547d-7e74-45a7-ab83-3212d705dca3\n\"\"\"\n    quadratic_ls(P::AbstractMatrix, q::AbstractVector, \u0394x::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    - \u0394x: search direction\n\nOutput:\n    - t: optimal step size\n\"\"\"\nfunction quadratic_ls(P::AbstractMatrix, q::AbstractVector, \u0394x::AbstractVector,\n                                    x::AbstractVector)\n    t = missing  # compute t\n    return t\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 91e61db9-57b8-4576-9960-bd74984f57b0\n\"\"\"\n    gradient_descent(P::AbstractArray, q::AbstractVector,\n            x\u2080::AbstractVector; \u03f5::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\u2080: starting point\n    - \u03f5: 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\u2080::AbstractVector; \u03f5::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# \u2554\u2550\u2561 3244fd32-30a3-4e5a-9884-dfb89ce867c7\n# solve the system with gradient descent\n\n# \u2554\u2550\u2561 4b7fbd19-8b0f-4097-95a4-778c48833dcc\n@bind \u03b3 Slider(1:0.1:20, default=10)\n\n# \u2554\u2550\u2561 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 $\u03b3.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 44c75163-e7b7-4071-8d61-3a609f01ffbd\n@bind \u03b2 Slider(0:0.05:1, show_value=true, default=0.4)\n\n# \u2554\u2550\u2561 1619f8f3-e638-4ff4-ade0-764840c11215\n\u03b2\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ae161416-fae9-4d75-81a4-dfacb82db055\n\"\"\"\n    gradient_descent_momentum(P::AbstractArray, q::AbstractVector,\n            x\u2080::AbstractVector; \u03b2::Real=0.0, \u03f5::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\u2080: starting point\n    - \u03f5: convergence parameter\n    - \u03b2: 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\u2080::AbstractVector; \u03b2::Real=0.0, \u03f5::Real=1e-6)\n    @assert 0 \u2264 \u03b2 < 0\n    x = x\u2080  # initial value\n    \u0394x = zero(x)  # pre-allocate a vector for the gradient\n    while true\n        \u0394x .= missing\n        if missing\n            break\n        end\n        # determine stepsize using exact line search\n        t = quadratic_ls(P, q, \u0394x, x)\n        # perform step\n        x .+= missing\n    end\n    return x\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8e74c0e1-a2de-4a3b-9e9e-41c006ea4c7f\n\n\n# \u2554\u2550\u2561 3e1f98e8-fea3-40bf-a9dd-9af36afc7877\n\n\n# \u2554\u2550\u2561 742b079b-092c-4907-9029-2aa6916c8d2e\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e5864656-9465-49aa-b997-2c237d16f15b\nmd\"Here are some utility functions and the solutions.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 07f1caf6-db49-4d9f-8ff1-d6e8e6f19db7\nlet\n\tP = [1 0; 0 \u03b3]\n\tq = [0, 0]\n\tr = 0\n\tx\u2080 = [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\u2080), 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# \u2554\u2550\u2561 b3f5a694-dd90-47dd-a2e8-e238f3e8bdc7\nlet\n\t\u03bbs = [0.1, 1.5, 1.6, 1.8, 2]\n\n\tx\u2080 = ones(5)\n\tt = 2 / (maximum(\u03bbs) + minimum(\u03bbs))\n\t# error xstar = 0, x\u2080 = 1\n\terrors = [(1.0 - t * \u03bb)^(2k) * \u03bb * x\u2080\u1d62^2 for k in 0:1000, (\u03bb, x\u2080\u1d62) in zip(\u03bbs, x\u2080)]\n\tcumerrors = cumsum(errors, dims=2)\n\tplot(cumerrors[:,1], fillrange=0, xscale=:log10, color=myblue, fillcolor=myblue, label=\"lam 1 = $(\u03bbs[1])\")\n\tplot!(cumerrors[:,2], fillrange=cumerrors[:,1], color=myred, fillcolor=myred, label=\"lam 2 = $(\u03bbs[2])\")\n\tplot!(cumerrors[:,3], fillrange=cumerrors[:,2], color=mygreen, fillcolor=mygreen, label=\"lam 3 = $(\u03bbs[3])\")\n\tplot!(cumerrors[:,4], fillrange=cumerrors[:,3], color=myorange, fillcolor=myorange, label=\"lam 4 = $(\u03bbs[4])\")\n\tplot!(cumerrors[:,5], fillrange=cumerrors[:,4], color=myyellow, fillcolor=myyellow, label=\"lam 5 = $(\u03bbs[5])\")\n\txlabel!(\"k+1\")\n\tylabel!(\"f(x) - f(x*)\")\n\ttitle!(\"Error of gradient descent\\n(cumulative eigencomponents)\")\nend\n\n# \u2554\u2550\u2561 0170ef68-cf32-46a2-ac39-ff971517dfb4\nlet\n\t\u03bbs = [0.1, 1.5, 1.6, 1.8, 2]\n\n\tx\u2080 = ones(5)\n\tt = 2 / (maximum(\u03bbs) + minimum(\u03bbs))\n\t# error xstar = 0, x\u2080 = 1\n\terrors = [(1.0 - t * \u03bb)^(2k) * \u03bb * x\u2080\u1d62^2 for k in 0:1000, (\u03bb, x\u2080\u1d62) in zip(\u03bbs, x\u2080)]\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 = $(\u03bbs[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# \u2554\u2550\u2561 41c04f53-091e-4e7f-a920-5df2a3366db6\nlet \n\t\u03bas = [1.1, 2.5, 5, 50, 100]\n\n\tbestt(\u03ba) = 2 / (1 + \u03ba)\n\terrors = [(1 - bestt(\u03ba))^(2k) + (1-bestt(\u03ba) * \u03ba)^(2k) * \u03ba for k in 1:10000, \u03ba in \u03bas]\n\n\tplot(errors, color = reshape(mycolors, 1, :),\n\t\t\tlabels = [\" kappa = $\u03ba\" for i in 1:1, \u03ba in \u03bas],\n\t\t\txscale=:log10, yscale=:log10, ylims=(1e-10, 100), lw=2)\n\n\t\u03ba2c(\u03ba) = 1 - 1 / \u03ba\n\tbounds = [exp(log(1+\u03ba) - k * log(1/\u03ba2c(\u03ba))) for k in 1:10000, \u03ba in \u03bas]\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# \u2554\u2550\u2561 575f94d7-dadb-4217-8d54-68aa5ee07236\nlet\n\tP = [1 0; 0 \u03b3]\n\tq = [0, 0]\n\tr = 0\n\tx\u2080 = [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\u2080), track=true)\n\t# with momentum\n\txstar, path_gdm = Solution.gradient_descent(P, q, copy(x\u2080); \u03b2, 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# \u2554\u2550\u2561 f03d9959-321d-4bd6-b062-1bae6fb28d64\nlet\n\tP = [1 0; 0 \u03b3]\n\tq = [0, 0]\n\tr = 0\n\tx\u2080 = [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\u2080), track=true)\n\t# with momentum\n\txstar, path_gdm = Solution.gradient_descent(P, q, copy(x\u2080); \u03b2, 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6590053d-fe91-4401-88e2-03bf29b068ce\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c139044f-83f3-4582-b301-e41ded50da4c\n\"\"\"\n    generate_noisy_measurements(m, n; \u03c3=1.0)\n\nGenerate noisy measurements according to some function f\n\nInputs:\n    - m : number of observations\n    - n : dim of x\n    - \u03c3 : 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; \u03c3=1.0)\n    ind = rand(1:n, m)\n    y = signalfun.(ind, n) .+ randn(m) * \u03c3\n    return y, ind\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5eafacee-4c7b-4cbd-adbb-631223341785\n\"\"\"\n    make_connection_matrix(n, \u03b3=100)\n\nGenerates the kernel matrix and the inverse kernel matrix\n\nUses \u03b3 as a characteristic length scale of the radial basis kernel,\nassumes periodic boundaries.\n\nInputs:\n    - n : number of points\n    - \u03b3 : length scale\n\nOutput:\n    - K\n    - Kinv\n\"\"\"\nfunction make_connection_matrix(n, \u03b3=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 / \u03b3^2) + 1e-2I\n    return K, inv(K)\nend\n\n\n# \u2554\u2550\u2561 bb203652-f242-4d21-97d6-82419b18daad\nK, Kinv = make_connection_matrix(n)\n\n# \u2554\u2550\u2561 d9630c7b-5840-4a87-bde7-c16629665cb2\nheatmap(log10.(K), title=\"Heatmap of K\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500752ced8e-1b80-11ec-298c-050f319f7228\n# \u2560\u2550c07d1eba-ea4c-4ef3-82cd-7db338e40c34\n# \u255f\u2500c7c39058-1035-4b34-8209-cc71837b6b38\n# \u255f\u25000a65fdd9-5579-4a60-a826-d438b6a49caf\n# \u2560\u2550e2309eb6-449d-497e-84f9-2e496f29f5a5\n# \u2560\u25500a9c4cc2-375b-4e0e-85ea-bc5992a92d07\n# \u2560\u2550a7f4f2fe-8a4d-4dcf-af55-d87298b5cace\n# \u255f\u250060e49a4d-a497-4edc-bde1-88161e9edd5b\n# \u2560\u25503850436e-d1d3-463c-8dde-790b40582c4e\n# \u255f\u2500f125cad0-ee03-4474-b535-c1f24c5045a2\n# \u255f\u2500ef216f91-4ee1-4b2c-8ebf-d34fb18d3a1a\n# \u255f\u2500de7ef8bd-04c1-4c86-80ef-4e1f339f8113\n# \u2560\u25508494232c-26ca-4a90-bd35-128a5bde892d\n# \u2560\u25509c47ce39-f015-4d51-afe7-3c6cb946d1f0\n# \u2560\u25505bd99c99-d60b-4998-8381-c516426607f5\n# \u2560\u255014987a6a-a984-4b04-b951-2db4e79bcac5\n# \u255f\u250000220013-46c0-4269-a85b-125255c52de1\n# \u255f\u250016f6f2e8-90d2-499c-a5c8-e69297fb9c42\n# \u2560\u25506ff5822a-1c4e-491b-b215-b3a1698e2048\n# \u255f\u2500da307ee7-55ce-4978-a2d6-7cf3e42a9eca\n# \u255f\u2500dbe09c4b-7ec2-415d-b1ed-c689dca7e8d1\n# \u255f\u250035dce8ae-f61b-4036-baab-ff14796b30be\n# \u255f\u25002e6ab057-669b-4d6b-bff0-4e34056217a4\n# \u255f\u250042541537-2fc5-41cf-9479-e2325c55d67d\n# \u2560\u25507931547d-7e74-45a7-ab83-3212d705dca3\n# \u255f\u250005236a85-dd10-4c10-ab9a-96cee2390d6d\n# \u2560\u255091e61db9-57b8-4576-9960-bd74984f57b0\n# \u2560\u25503244fd32-30a3-4e5a-9884-dfb89ce867c7\n# \u255f\u25008c80e876-55de-414d-81d4-292231b281ad\n# \u255f\u25004b7fbd19-8b0f-4097-95a4-778c48833dcc\n# \u255f\u250007f1caf6-db49-4d9f-8ff1-d6e8e6f19db7\n# \u255f\u25009359bca7-f702-4b9c-a55d-a2a85bda62b7\n# \u255f\u2500b3f5a694-dd90-47dd-a2e8-e238f3e8bdc7\n# \u255f\u25000170ef68-cf32-46a2-ac39-ff971517dfb4\n# \u255f\u2500ec6ef0e2-3589-4c88-90fa-4083739142ce\n# \u255f\u250041c04f53-091e-4e7f-a920-5df2a3366db6\n# \u255f\u250031937c09-736a-40b6-babe-2d386ddb430e\n# \u255f\u2500e206f6f7-c198-438b-99df-7c2942c4cc15\n# \u2560\u25501619f8f3-e638-4ff4-ade0-764840c11215\n# \u255f\u250044c75163-e7b7-4071-8d61-3a609f01ffbd\n# \u255f\u2500575f94d7-dadb-4217-8d54-68aa5ee07236\n# \u255f\u2500f03d9959-321d-4bd6-b062-1bae6fb28d64\n# \u255f\u250058f001c8-460f-42fd-9f96-c2cc9126873b\n# \u2560\u2550ae161416-fae9-4d75-81a4-dfacb82db055\n# \u255f\u250062524ce5-75f1-4ddb-a69c-a219c1c7c50e\n# \u255f\u25002198ca9d-7522-47e1-925a-14c7fdbc7bc5\n# \u2560\u25507894fa71-96a6-4f9e-9bd5-e715975b2fb5\n# \u255f\u250028577dc0-0521-4c07-bf9d-338d4b582bf8\n# \u2560\u2550bb203652-f242-4d21-97d6-82419b18daad\n# \u2560\u2550d9630c7b-5840-4a87-bde7-c16629665cb2\n# \u2560\u255098e95644-913f-46d9-9deb-d78f7102db3b\n# \u255f\u25007cb64961-d94b-4fe7-913d-50bd094553f2\n# \u2560\u25508e74c0e1-a2de-4a3b-9e9e-41c006ea4c7f\n# \u2560\u25503e1f98e8-fea3-40bf-a9dd-9af36afc7877\n# \u2560\u2550742b079b-092c-4907-9029-2aa6916c8d2e\n# \u255f\u2500313f361f-a93d-403a-856f-5ffa9c2557c7\n# \u255f\u2500e5864656-9465-49aa-b997-2c237d16f15b\n# \u2560\u25505beb181b-454c-4314-84e2-ee1d0f220c71\n# \u2560\u2550ed98b0d2-2493-4bb7-aceb-eabab7074c9a\n# \u2560\u25505f0cc86d-0566-4269-b7a9-9a76c7ee5da0\n# \u2560\u25505fba2a78-1d80-4796-9dac-04c299670231\n# \u2560\u25506590053d-fe91-4401-88e2-03bf29b068ce\n# \u2560\u2550a15c0e18-c71c-4e22-9818-50f26b1b6907\n# \u2560\u2550b165fb28-2671-4b0e-8a46-9a008bb6af46\n# \u2560\u2550c139044f-83f3-4582-b301-e41ded50da4c\n# \u2560\u25505eafacee-4c7b-4cbd-adbb-631223341785\n# \u2560\u25501fe7b368-ad79-42b8-a682-94b59cb2f0f6\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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# \u2554\u2550\u2561 de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, DataFrames\n\tRandom.seed!(1)\nend\n\n# \u2554\u2550\u2561 ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.10\"\n\n# \u2554\u2550\u2561 ce43a8fa-1eee-11eb-326b-e777b76f16c6\nbegin\n\tnumbers = 10:25\n\tN = 10^7\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 356e6696-1eef-11eb-0386-8fd3dfe0c86e\nprobThirteen, probFirstIsOne, probSecondIsThree =\n    (numThirteen,numFirstIsOne,numSecondIsThree)./N\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ea086874-1eeb-11eb-2cb0-4186697d4294\nmd\"## End of listing 2.10\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# \u2560\u2550de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# \u2560\u2550e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# \u2560\u2550ce43a8fa-1eee-11eb-326b-e777b76f16c6\n# \u2560\u2550356e29c2-1eef-11eb-2488-6d87c9d7c26f\n# \u2560\u2550356e6696-1eef-11eb-0386-8fd3dfe0c86e\n# \u2560\u2550356ee814-1eef-11eb-3bbe-458402f62f3c\n# \u255f\u2500ea086874-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": "search(\"Julia\",\"uli\") #=> 2:4\ntypeof(1:1000) #=> UnitRange{Int64}\n\na = split(\"A,B,C,D\",\",\")\ntypeof(a) #=> Array{SubString{ASCIIString},1}\nshow(a) #=> SubString{ASCIIString}[\"A\",\"B\",\"C\",\"D\"]\n\narr = [100, 25, 37]\narr[1] #=> 100\narr[end] #=> 37\n# arr[6] #=> BoundsError\nprintln(eltype(arr)) #=> Int64\nprintln(length(arr)) #=> 3\nprintln(ndims(arr)) #=> 1\nprintln(size(arr,1)) #=> 3\nprintln(size(arr)) #=> (3,)\n\narr2 = Array(Int, 5)\nshow arr2 #=> [0,0,0,0,0]\nsizehint(arr2, 10^5)\n\na = Float64[] #=> 0-element Array{Float64,1}\nb = [1:7] #=> 7-element Array{Int64,1}: [1,2,3,4,5,6,7]\njoin(b, \", \") #=> \"1, 2, 3, 4, 5, 6, 7\"\nmatrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]\n\nb[1:3] # => [1, 2, 3]\nb[2:end] # => [2, 3, 4, 5, 6, 7]  , b[2:] is deprecated\nc = [100,200,300]\nappend!(b,c) # Now b is [1, 2, 3, 4, 5, 6, 7, 100, 200, 300]\npop!(b) #=> 300, b is now [1, 2, 3, 4, 5, 6, 7, 100, 200]\npush!(b, 42) # b is now [1, 2, 3, 4, 5, 6, 7, 100, 200, 42]\nshift!(b) #=> 1, b is now [2, 3, 4, 5, 6, 7, 100, 200, 42]\nunshift!(b, 42) # b is now [42, 2, 3, 4, 5, 6, 7, 100, 200, 42]\nsplice!(b,8) #=> 100, b is now [42, 2, 3, 4, 5, 6, 7, 200, 42]\nin(42, b) #=> true\nin(43, b) #=> false\nsort(b) #=> [2,3,4,5,6,7,42,42,200], b is not changed\nsort!(b) #=> b is now changed to [2,3,4,5,6,7,42,42,200]\n\narr = [1, 5, 3]\n# looping\nfor e in arr\n    print(\"$e \")\nend # prints 1 5 3\narr + 2 #=> [3, 7, 5]\narr * 2 #=> [2, 10, 6]\n\nma1 = rand(3, 5)\nndims(ma1) #=> 2\nsize(ma1) #=> (3, 5)\nsize(ma1,1) #=> 3\nsize(ma1,2) #=> 5\nlength(ma1) #=> 15\n\nidm = eye(3)\nzeros(5)\nones(4)\nones(3, 2)\neqa = linspace(0, 10, 5)\nshow(eqa) #=> [0.0,2.5,5.0,7.5,10.0]\nfill!(arr, 42) #=> [42,42,42]\n\nA = [1,2,4,6]\nA0 = A\nshow(A0)\nA[4] = 0\nshow(A) #=> [1,2,4,0]\nshow(A0) #=> [1,2,4,0]\n", "meta": {"hexsha": "8c9b2149892d2b0da110ae247115063c9465a084", "size": 1733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Module 1/Chapter02/Old/arrays.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/Chapter02/Old/arrays.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/Chapter02/Old/arrays.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": 24.7571428571, "max_line_length": 63, "alphanum_fraction": 0.5147143681, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.766553457274151}}
{"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    \u03a6 = X*eigVects*Diagonal(1 ./S)\n    a = Diagonal(S)*eigVects'\n\n    POD = PODBasis(a, \u03a6)\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    \u03a6 = X*eigVects*Diagonal(1 ./S)\n    a = Diagonal(S)*eigVects'\n\n    POD = PODBasis(a, \u03a6)\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\u03c0*s)\nx = @. r*cos(10\u03c0*s)\ny = @. r*sin(10\u03c0*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": "@testset \"Test basis\" begin\n\nusing HDiscontinuousGalerkin\nusing Tensors\n\n#Test Dubiner base\ninterpolation = Dubiner{2,RefTetrahedron,4}()\nquad_rule = QuadratureRule{2,RefTetrahedron}(Strang(),5)\nfor j = 1:15\n    @test integrate(x->(dubiner_basis(x[1],x[2],j) - value(interpolation, j, x))^2,quad_rule) < eps()\n    @test integrate(x->sum((\u2207dubiner_basis(x[1],x[2],j) - gradient_value(interpolation, j, x)).^2),quad_rule) < eps()\nend\n\n# Test nodal points for Lagrange base\nnodal_points, topology = get_nodal_points(RefTetrahedron, Val{2}, 1)\n@test  nodal_points == [Vec{2, Float64}((0.0, 0.0)),\n                        Vec{2, Float64}((1.0, 0.0)),\n                        Vec{2, Float64}((0.0, 1.0))]\n@test topology == Dict(0=>3,1=>0,2=>0)\nnodal_points, topology = get_nodal_points(RefTetrahedron, Val{2}, 2)\n@test nodal_points == [Vec{2, Float64}((0.0, 0.0)),\n                        Vec{2, Float64}((1.0, 0.0)),\n                        Vec{2, Float64}((0.0, 1.0)),\n                        Vec{2, Float64}((0.5, 0.5)),\n                        Vec{2, Float64}((0.0, 0.5)),\n                        Vec{2, Float64}((0.5, 0.0))]\n@test topology == Dict(0=>3,1=>3,2=>0)\nnodal_points, topology = get_nodal_points(RefTetrahedron, Val{2}, 3)\n@test length(nodal_points) == 10\n@test topology == Dict(0=>3,1=>6,2=>1)\n@test nodal_points[10] \u2248 Vec{2, Float64}((1/3, 1/3))\n# Test Lagrange base\nfunction ref_value(i::Int, \u03be::Vec{2})\n    \u03be_x = \u03be[1]\n    \u03be_y = \u03be[2]\n    i == 2 && return \u03be_x\n    i == 3 && return \u03be_y\n    i == 1 && return 1. - \u03be_x - \u03be_y\n    throw(ArgumentError(\"no shape function $i for interpolation $ip\"))\nend\n\ninterpolation = Lagrange{2,RefTetrahedron,1}()\n\u03be_ref = Vec{2}((0.5,0.5))\nfor j = 1:3\n    @test abs(ref_value(j,\u03be_ref) - value(interpolation,j,\u03be_ref)) < eps(Float64)\n    @test norm(gradient(\u03be -> ref_value(j, \u03be), \u03be_ref) - gradient_value(interpolation,j,\u03be_ref), Inf) < eps(Float64)\nend\n\nfunction ref_value1(i::Int, \u03be::Vec{1})\n    \u03be_x = \u03be[1]\n    i == 1 && return 1-\u03be_x\n    i == 2 && return \u03be_x\n    throw(ArgumentError(\"no shape function $i for interpolation $ip\"))\nend\n\u03be_ref = Vec{1}((0.5,))\ninterpolation = Lagrange{1,RefTetrahedron,1}()\nfor j = 1:2\n    @test abs(ref_value1(j,\u03be_ref) - value(interpolation,j,\u03be_ref)) < eps(Float64)\n    @test norm(gradient(\u03be -> ref_value1(j, \u03be), \u03be_ref) - gradient_value(interpolation,j,\u03be_ref), Inf) < eps(Float64)\nend\n\n#Test Legendre basis\nfunction ref_value(i::Int, x::Real)\n    @assert i <= 3\n    if i == 0\n        return 1.0\n    elseif i == 1\n        return sqrt(3)*(2*x - 1)\n    elseif i == 2\n        return sqrt(5)*(6*x^2 - 6*x + 1)\n    else\n        return sqrt(7)*(2*x - 1)*(10*x^2 - 10*x + 1)\n    end\nend\nfunction ref_dvalue(i::Int, x::Real)\n    @assert i <= 3\n    if i == 0\n        return 0\n    elseif i == 1\n        return sqrt(3)*2\n    elseif i == 2\n        return sqrt(5)*(12*x - 6)\n    else\n        return sqrt(7)*12*(5*x^2 - 5*x + 1)\n    end\nend\n\ninterpolation = Legendre{1,RefTetrahedron,3}()\nquad_rule = QuadratureRule{1,RefTetrahedron}(GaussLegendre(),3)\nfor i = 0:3\n    @test integrate(x->(ref_value(i,x[1]) - value(interpolation, i+1, x))^2,quad_rule) < eps()\n    @test integrate(x->(ref_dvalue(i,x[1]) - gradient_value(interpolation, i+1, x)[1])^2,quad_rule) < eps()\nend\n\nend\n", "meta": {"hexsha": "4e6960502ac75db9e8fc5ff0ad851c6367c8e91c", "size": 3232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_basis.jl", "max_stars_repo_name": "Paulms/HDiscontinuousGalerkin.jl", "max_stars_repo_head_hexsha": "cd72728a84762ad1c770a1ff0188d95b6624c2ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-01-08T09:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-13T20:21:05.000Z", "max_issues_repo_path": "test/test_basis.jl", "max_issues_repo_name": "Paulms/HDiscontinuousGalerkin.jl", "max_issues_repo_head_hexsha": "cd72728a84762ad1c770a1ff0188d95b6624c2ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-08T16:03:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-08T16:03:15.000Z", "max_forks_repo_path": "test/test_basis.jl", "max_forks_repo_name": "Paulms/HDiscontinuousGalerkin.jl", "max_forks_repo_head_hexsha": "cd72728a84762ad1c770a1ff0188d95b6624c2ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-20T17:13:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T19:14:21.000Z", "avg_line_length": 33.6666666667, "max_line_length": 117, "alphanum_fraction": 0.5962252475, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7665519890045032}}
{"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": "@testset \"delaydifferentialequation\" begin\n# Tests\n# 1. x'(t) = 2x(t) - exp(1)*x(t - 1) has a double root at \u03bb = 1\n    ev = dde_stability(2, -exp(1), 1)\n    @test count((abs.(real.(ev.values) .- 1) .< 1e-6) .& (abs.(imag.(ev.values)) .< 1e-6)) == 2\n# 2. x'(t) = -x(t - \u03c4) goes unstable at \u03c4=\u03c0/2\n    ev = dde_stability(0, -1, \u03c0/2 - 0.01)\n    @test all(real.(ev.values) .< 0)\n    ev = dde_stability(0, -1, \u03c0/2 + 0.01)\n    @test any(real.(ev.values) .> 0)\n# 3. x'(t) = \u03b1*A*x(t) + (1-\u03b1)*A*x(t-\u03c4)\n#    A = [\n#          50  284   41   23   50   32\n#        -280  -46  -19  -37  -10  -28\n#          35   -1   26  143   35   17\n#          5   -31 -139  -22    5  -13\n#          20  -16   11   -7 -115  137\n#         -10  -46  -19  -37 -145 -163\n#    ]\n#    with \u03b1=0.9 is stable for 3\u03c0/(270*(2*0.9 - 1)) \u2264 \u03c4 \u2264 4\u03c0/270\n#    that is 0.04363323129985824 \u2264 \u03c4 \u2264 0.046542113386515455\n    A = [\n          50  284   41   23   50   32\n        -280  -46  -19  -37  -10  -28\n          35   -1   26  143   35   17\n          5   -31 -139  -22    5  -13\n          20  -16   11   -7 -115  137\n         -10  -46  -19  -37 -145 -163\n    ]\n    \u03b1 = 0.9\n    ev = dde_stability(\u03b1 * A, (1 - \u03b1)*A, 0.043)\n    @test any(real.(ev.values) .> 0)\n    ev = dde_stability(\u03b1 * A, (1 - \u03b1)*A, 0.044)\n    @test all(real.(ev.values) .< 0)\n    ev = dde_stability(\u03b1 * A, (1 - \u03b1)*A, 0.047)\n    @test any(real.(ev.values) .> 0)\nend\n", "meta": {"hexsha": "c2f229e8bf23494bb3c97f0ec8c02212bd7a9179", "size": 1383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_delaydifferentialequation.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": "test/test_delaydifferentialequation.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": "test/test_delaydifferentialequation.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": 36.3947368421, "max_line_length": 95, "alphanum_fraction": 0.4555314534, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7665519803452734}}
{"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    \u2207f(x) = ForwardDiff.gradient(f, x)\r\n    H(x) = ForwardDiff.hessian(f, x)\r\n    m, n = size(H(x))\r\n    \u03b7 = 1e-2\r\n    \u0392 = 1.0e-3\r\n    num_backtrack = 0\r\n    iter = 0\r\n    while norm(\u2207f(x)) > 1e-4\r\n        h = H(x)\r\n\r\n        if minimum(diag(h)) > 0     \r\n            \u03c1 = 0.0\r\n        else\r\n            \u03c1 = -minimum(diag(h)) + \u0392\r\n        end       \r\n\r\n        k = 0  \r\n        while   issuccess(cholesky(h + \u03c1*I, check=false)) == false\r\n                \u03c1 = max(2\u03c1, \u0392)\r\n                k = k+1\r\n        end    \r\n        \r\n        F = cholesky(h + \u03c1*I)\r\n        J = F.L  \r\n        y = - J \\ \u2207f(x)\r\n        M = J'\r\n        d = M \\ y\r\n        \r\n        # Armijo\r\n        \u03b1 = 1.0\r\n        while f(x + \u03b1 * d) \u2265 f(x) + \u03b7 * \u03b1 * dot(d, \u2207f(x))\r\n            \u03b1 = \u03b1 / 2\r\n            num_backtrack = num_backtrack + 1\r\n            if \u03b1 < 1e-8\r\n                error(\"Erro no backtracking\")\r\n            end\r\n        end\r\n        x = x + \u03b1 * 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\u00e7\u00e3oProjeto1.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\u00e7\u00e3oProjeto1.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\u00e7\u00e3oProjeto1.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": "using FastTransforms\nusing Base.Test\n\nc = collect(linspace(-big(1.0),1,16))\n@test norm(fft(c) - fft(map(Float64,c))) < 3Float64(norm(c))*eps()\n@test norm(ifft(c) - ifft(map(Float64,c))) < 3Float64(norm(c))*eps()\n\nc = collect(linspace(-big(1.0),1.0,201))\n@test norm(ifft(fft(c))-c) < 200norm(c)eps(BigFloat)\n\np = plan_dct(c)\n@test norm(dct(c) - p*c) == 0\n\npi = plan_idct!(c)\n@test norm(pi*dct(c) - c) < 400norm(c)*eps(BigFloat)\n\n@test norm(dct(c)-dct(map(Float64,c)),Inf) < 10eps()\n\ncc = cis(c)\n@test norm(dct(cc)-dct(map(Complex{Float64},cc)),Inf) < 10eps()\n", "meta": {"hexsha": "4d3d102555052a469effdd56aef0fc6d100675fe", "size": 558, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fftBigFloattest.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": "test/fftBigFloattest.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": "test/fftBigFloattest.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": 26.5714285714, "max_line_length": 68, "alphanum_fraction": 0.6415770609, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288127, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.766484679559335}}
{"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": "using deSolveDiffEq\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,deSolveDiffEq.lsoda())\nsol = solve(prob,deSolveDiffEq.lsode())\nsol = solve(prob,deSolveDiffEq.lsodes())\nsol = solve(prob,deSolveDiffEq.lsodar())\nsol = solve(prob,deSolveDiffEq.vode())\nsol = solve(prob,deSolveDiffEq.daspk())\nsol = solve(prob,deSolveDiffEq.euler())\nsol = solve(prob,deSolveDiffEq.rk4())\nsol = solve(prob,deSolveDiffEq.ode23())\nsol = solve(prob,deSolveDiffEq.ode45())\nsol = solve(prob,deSolveDiffEq.radau())\nsol = solve(prob,deSolveDiffEq.bdf())\nsol = solve(prob,deSolveDiffEq.bdf_d())\nsol = solve(prob,deSolveDiffEq.adams())\nsol = solve(prob,deSolveDiffEq.impAdams())\nsol = solve(prob,deSolveDiffEq.impAdams_d())\n#sol = solve(prob,deSolveDiffEq.iteration())\n\nsol = solve(prob,deSolveDiffEq.lsoda(),saveat=0.1)\n#using Plots; plot(sol,vars=(1,2,3))\n", "meta": {"hexsha": "b722a85c840f7202bd1eff36c1eed1bdecef73bb", "size": 1013, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "stjordanis/deSolveDiffEq.jl", "max_stars_repo_head_hexsha": "5bfc621d805fbf06549f2148e300e4971cef8236", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-26T11:59:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T03:33:42.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "stjordanis/deSolveDiffEq.jl", "max_issues_repo_head_hexsha": "5bfc621d805fbf06549f2148e300e4971cef8236", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-14T14:19:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T00:19:23.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "stjordanis/deSolveDiffEq.jl", "max_forks_repo_head_hexsha": "5bfc621d805fbf06549f2148e300e4971cef8236", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-26T23:51:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-26T23:51:10.000Z", "avg_line_length": 30.696969697, "max_line_length": 50, "alphanum_fraction": 0.7068114511, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7663912725239237}}
{"text": "@testset \"moments\" begin\n    ind = rand([0,1], 10)\n    @test sum(normalize_indicator(ind)) \u2248 1.\n\n    Ind = diagm(ind)\n    @test sum(normalize_indicator(Ind)) \u2248 1.\n\n    @test to_indicator_matrix(ind) == Ind\n\n    Ind = rand([0,1], 10, 10)\n    @test sum(normalize_indicator(Ind, 1), dims=1) \u2248 ones(Int64, 1, 10)\n    @test sum(normalize_indicator(Ind, 2), dims=2) \u2248 ones(Int64, 10)\n\n    @test diag(union_diagonal!(Ind)) == ones(Int64, 10)\n\n    ind = rand([0,1], 10)\n\n    G = graph_filter(ind, 1)\n    @test G isa SparseVector\n    @test sum(G .!= 0) == sum(ind .!= 0)\n    @test sum(G) \u2248 1.\n\n    G = graph_filter(ind, 2)\n    @test G isa SparseMatrixCSC\n    @test sum(G .!= 0) == sum(ind .!= 0)\n    @test sum(G) \u2248 1.\n\n    adj = rand([0,1], 10, 10)\n\n    G = graph_filter(adj, 1, dims=1)\n    @test G isa SparseMatrixCSC\n    @test sum(G .!= 0, dims=1) == sum(adj .!= 0, dims=1)\n    @test sum(G, dims=1) \u2248 ones(Int64, 1, 10)\n    \n    G = graph_filter(adj, 1, dims=2)\n    @test G isa SparseMatrixCSC\n    @test sum(G .!= 0, dims=2) == sum(adj .!= 0, dims=2)\n    @test sum(G, dims=2) \u2248 ones(Int64, 10)\n\n    adj = [1 0 0; 1 0 1; 1 1 1]\n    blocks = [diagm([1/3, 1/3, 1/3]), diagm([0, 0, 1]), diagm([0, 1/2, 1/2])]\n    @test graph_filter(adj, 2, dims=1) == cat(blocks...,dims=(1,2))\n\n    blocks = [diagm([1, 0, 0]), diagm([1/2, 0, 1/2]), diagm([1/3, 1/3, 1/3])]\n    @test graph_filter(adj, 2, dims=2) == cat(blocks...,dims=(1,2))\n\n    A = rand([0,1], 5, 5)\n    X = rand(5, 10)\n    @test size(moment(A, X, 1, dims=1)) == size(X)\n    @test size(moment(A, Matrix(X'), 1, dims=2)) == size(X')\n    # @test size(moment(A, X, 2, dims=1)) == (size(X, 1), 5*10)\n    # @test size(moment(A, Matrix(X'), 2, dims=2)) == (5*10, size(X, 1))\nend\n", "meta": {"hexsha": "995cafecc946d84b36396732c297de120c32115a", "size": 1713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 31.7222222222, "max_line_length": 77, "alphanum_fraction": 0.5394045534, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7663912725038653}}
{"text": "@testset \"set operations\" begin\n\n    Nsamps = 10^6\n\n    a = interval(0,1) \u222a interval(2,3)\n\n    b = interval(-1, 1) \u222a interval(2,5)\n\n    aSamps = zeros(Nsamps); bSamps = zeros(Nsamps)\n\n    for i = 1: Nsamps\n        if rand() < 0.5\n            aSamps[i] = rand()\n        else\n            aSamps[i] = rand() + 2\n        end\n\n        if rand() < 0.5\n            bSamps[i] = (rand() * 2) -1\n        else\n            bSamps[i] = rand() * 3 + 2\n        end\n    end\n\n    @test all(aSamps .\u2208 a)\n    @test all(bSamps .\u2208 b)\n\n    ac = complement(a)\n\n    @test all(.~(aSamps .\u2208 ac))     # Test all samples are not in complement\n\n    intersec = a \u2229 b                 # Intersect\n\n    aSampsB = aSamps[ aSamps .\u2208 b]\n    bSampsA = bSamps[ bSamps .\u2208 a]\n\n    @test all( aSampsB .\u2208 intersec)\n    @test all( bSampsA .\u2208 intersec)\n\n    diff = a \\ b                 # Set difference\n\n    @test diff[1] == interval(1)\n    @test diff[2] == interval(2)\n\n    bi = bisect(a, 0.5)         # Cut at a = 0.5\n\n    @test bi[1] == interval(0, 0.5)\n    @test bi[2] == interval(0.5, 1)\n    @test bi[3] == interval(2, 3)\n\n    @test a \u2282 interval(0, 3)     # Subset\n    @test !(b \u2282 interval(0, 3))\n\n\nend\n", "meta": {"hexsha": "95884ad00b455297df785bc37899f60c560f1276", "size": 1165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/set_operations.jl", "max_stars_repo_name": "abraunst/IntervalUnionArithmetic.jl", "max_stars_repo_head_hexsha": "c705f489bc40abad815ed38a985de5b42a0edcc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-04-07T13:17:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:46:46.000Z", "max_issues_repo_path": "test/set_operations.jl", "max_issues_repo_name": "abraunst/IntervalUnionArithmetic.jl", "max_issues_repo_head_hexsha": "c705f489bc40abad815ed38a985de5b42a0edcc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2021-04-30T16:25:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T09:48:43.000Z", "max_forks_repo_path": "test/set_operations.jl", "max_forks_repo_name": "abraunst/IntervalUnionArithmetic.jl", "max_forks_repo_head_hexsha": "c705f489bc40abad815ed38a985de5b42a0edcc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-05T18:13:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T17:45:02.000Z", "avg_line_length": 20.8035714286, "max_line_length": 76, "alphanum_fraction": 0.4806866953, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7663912706350968}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.4\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 3e849bdf-f13a-4ea0-aa54-b6ae89894565\nmd\"\"\"\n# \u00c1lgebra lineal b\u00e1sica en Julia\nAutor: Andreas Noack Jensen (MIT) (http://www.econ.ku.dk/phdstudent/noack/)\n(con edici\u00f3n de Jane Herriman)\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 05eff53f-64c5-4833-9eff-11c7d09b9684\nA = rand(1:4,3,3)\n\n# \u2554\u2550\u2561 16ca2d04-2f46-4de7-9481-daebf5112c2f\nmd\"\"\"\nDefinir un vector de unos\n\"\"\"\n\n# \u2554\u2550\u2561 018e028c-43ff-4dbe-bc83-e5f0982d6bb6\nx = fill(1.0, (3))\n\n# \u2554\u2550\u2561 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\u00e1sicas son id\u00e9nticas a otros lenguajes\n\n#### Multiplicaci\u00f3n\n\"\"\"\n\n# \u2554\u2550\u2561 383658c8-9d47-4a1e-ba63-66fa6e7f3311\nb = A*x\n\n# \u2554\u2550\u2561 e2cc7ff7-781c-4102-892c-da24291f0388\nmd\"\"\"\n#### Traspuestas\nComo en otros lenguajes, `A'` es la transpuesta conjugada mientras que `A.'` es s\u00f3lo la traspuesta\n\"\"\"\n\n# \u2554\u2550\u2561 5c3d3b48-6b7c-4a3b-a9b6-d83f7bc03168\nAsym = A + A'\n\n# \u2554\u2550\u2561 88f5c70e-b5b1-4cf0-8f50-d1241f0a769b\nmd\"\"\"\n#### Multiplicaci\u00f3n traspuesta\nJulia nos permite escribir esto sin *\n\"\"\"\n\n# \u2554\u2550\u2561 0691212e-d372-43be-b66e-61f842df09eb\nApd = A'A\n\n# \u2554\u2550\u2561 1445f674-cfa2-44ab-920f-fe4d85d00c2e\nmd\"\"\"\n#### Resolviendo sistemas lineales\nEl problema $Ax=b$ para $A$ cuadrada se resulve con la funci\u00f3n \\.\n\"\"\"\n\n# \u2554\u2550\u2561 c42fc4ae-bf1d-4eb7-9863-a498fb9116b8\nA\\b\n\n# \u2554\u2550\u2561 462e5a23-f323-4158-bf27-cf36bbc5cec5\nmd\"\"\"\n#### Sistemas sobredeterminados\nCuando nuestra matriz es alta (n\u00famero de renglones mayores al n\u00famero de columnas), tenemos un sistema lineal sobredeterminado.\n\n\nEn este caso \\ calcula la de m\u00ednimos cuadrados\n\"\"\"\n\n# \u2554\u2550\u2561 8c87b3e1-b737-4179-9955-defcf0905b1b\nAtall = rand(3, 2)\ndisplay(Atall)\nAtall\\b\n\n# \u2554\u2550\u2561 7dea4ca8-27e0-429e-bbf3-dccf2ca67df3\nmd\"\"\"\nLa funci\u00f3n \\ tambi\u00e9n sirve ocn problemas deficientes de rango de m\u00ednimos cuadrados. En este caso, la soluci\u00f3n no es \u00fanica y Julia regresa el valor con la menor norma.\n\nPara crear un problema de rango deficiente de m\u00ednimos cuadrados, vamos a crear una matriz deficiente en rango con columnas linealmente dependientes\n\"\"\"\n\n# \u2554\u2550\u2561 962df670-f9d1-441d-bf86-f4619f29ab4f\nv = randn(3)\n\n# \u2554\u2550\u2561 306db6d0-193e-11eb-3bee-cbb7d8c4c5c6\nrankdef = [v v]\n\n# \u2554\u2550\u2561 92b4cb6a-47c9-459b-8694-aee9158439dd\nrankdef\\b\n\n# \u2554\u2550\u2561 4c836857-08fc-411a-8b65-6340c6e94c3b\nmd\"\"\"\n#### Sistemas indeterminados\ncuando A es corta (n\u00famero de columnas mayor al n\u00famero de renglones), tenemos un sistema indeterminado\n\nEn este caso \\ regresa la soluci\u00f3n con la norma m\u00ednima\n\"\"\"\n\n# \u2554\u2550\u2561 0784963e-8842-43f6-af98-781aa7e214b6\nAshort = rand(2, 3)\n\n# \u2554\u2550\u2561 3346487c-193e-11eb-15dd-4dd8241ac876\ndisplay(Ashort)\n\n# \u2554\u2550\u2561 3346b974-193e-11eb-2c77-9133e1f9b17b\nAshort\\b[1:2]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f86a1d32-1e1d-461e-ad40-f5b906b04cf9\n\n\n# \u2554\u2550\u2561 22e5c662-6bf6-48d4-b7f9-93d8ac33ffdd\nmd\"\"\"\n10.2 Toma el producto de un vector `v` con s\u00ed mismo.\n\"\"\"\n\n# \u2554\u2550\u2561 403752d3-4a6b-41bf-b4ed-fd6fe7b9ee95\n\n\n# \u2554\u2550\u2561 6b98b27f-f671-4c5c-af5e-6d290f0d158b\nmd\"\"\"\n10.3 Toma el producto de un vector `v` con s\u00ed mismo.\n\"\"\"\n\n# \u2554\u2550\u2561 fd670b40-f44e-440e-90b0-b27522c7adbd\n\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25003e849bdf-f13a-4ea0-aa54-b6ae89894565\n# \u255f\u2500a880f5b4-1f0f-4569-a59c-0e87d21cd203\n# \u2560\u255005eff53f-64c5-4833-9eff-11c7d09b9684\n# \u255f\u250016ca2d04-2f46-4de7-9481-daebf5112c2f\n# \u2560\u2550018e028c-43ff-4dbe-bc83-e5f0982d6bb6\n# \u255f\u25005cc332db-a229-4182-b860-4d276e3042a9\n# \u2560\u2550383658c8-9d47-4a1e-ba63-66fa6e7f3311\n# \u255f\u2500e2cc7ff7-781c-4102-892c-da24291f0388\n# \u2560\u25505c3d3b48-6b7c-4a3b-a9b6-d83f7bc03168\n# \u255f\u250088f5c70e-b5b1-4cf0-8f50-d1241f0a769b\n# \u2560\u25500691212e-d372-43be-b66e-61f842df09eb\n# \u255f\u25001445f674-cfa2-44ab-920f-fe4d85d00c2e\n# \u2560\u2550c42fc4ae-bf1d-4eb7-9863-a498fb9116b8\n# \u255f\u2500462e5a23-f323-4158-bf27-cf36bbc5cec5\n# \u2560\u25508c87b3e1-b737-4179-9955-defcf0905b1b\n# \u255f\u25007dea4ca8-27e0-429e-bbf3-dccf2ca67df3\n# \u2560\u2550962df670-f9d1-441d-bf86-f4619f29ab4f\n# \u2560\u2550306db6d0-193e-11eb-3bee-cbb7d8c4c5c6\n# \u2560\u255092b4cb6a-47c9-459b-8694-aee9158439dd\n# \u255f\u25004c836857-08fc-411a-8b65-6340c6e94c3b\n# \u2560\u25500784963e-8842-43f6-af98-781aa7e214b6\n# \u2560\u25503346487c-193e-11eb-15dd-4dd8241ac876\n# \u2560\u25503346b974-193e-11eb-2c77-9133e1f9b17b\n# \u255f\u250086dc3af8-2f80-48a5-b0d3-caeddc5ae8a8\n# \u2560\u2550f86a1d32-1e1d-461e-ad40-f5b906b04cf9\n# \u255f\u250022e5c662-6bf6-48d4-b7f9-93d8ac33ffdd\n# \u2560\u2550403752d3-4a6b-41bf-b4ed-fd6fe7b9ee95\n# \u255f\u25006b98b27f-f671-4c5c-af5e-6d290f0d158b\n# \u2560\u2550fd670b40-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 \u0394E for switching the spin\n    m      = nspins(grid, x, y) |> sum\n    eplus  = -m - h\n    \u0394E     = -2eplus * grid[x,y]\n\n    # Change spin accordingly\n    if \u0394E <= 0 || rand() < exp(-\u0394E/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": "using CSV, DataFrames, StatsPlots, StanSample\nusing Distributions, Statistics, Random\n\nProjDir = @__DIR__\n\n# Simulate the data\n\n#Random.seed!(123)\n\ncountries = [\"Guatamala\", \"Panama\", \"Kenya\", \"Ethiopia\", \"Papua New Guinea\"]\nbrands = [4, 3, 4, 5, 1]\nintercepts = [500, 300, 600, 700, 900] # Quantity at cheapest price_point\nslopes = [-6, -8, -10, -15, -20] # Assuming constant price elasticity\nprice_points = [12.5, 12.75, 13.02, 14.20, 15.15] # Selected price points\ncosts = [4.0, 4.2, 4.6, 4.7, 5.2]\nchannels = [\"retail\", \"wholesale\", \"shop\"]\n\ndf = DataFrame()\nfor n in 1:1500\n\tyr = 2019\n\twk = rand(1:52)\n\tc_ind = rand(1:length(countries))\n\tp_ind = rand(1:length(price_points))\n\tc = countries[c_ind]\t\t\t\t\t\t\t# country\n\tb = rand(1:brands[c_ind])\t\t\t\t\t\t# brand\n\tch = rand(channels)\t\t\t\t\t\t\t\t# channel\n\tcst = rand(Normal(costs[c_ind], 0.1))\t\t\t# cost\n\tp = price_points[p_ind]\t\t\t\t\t\t\t# ppu\n\tif rand(Bernoulli(0.2))\n\t\tp = rand(Normal(p, 0.07))\n\tend\n\tp = round(p, digits=2)\n\tq = intercepts[c_ind] + slopes[c_ind] * p_ind\t# quantity sold\n\tif rand(Bernoulli(0.2))\n\t\tq = round(rand(Normal(q, 30)))\n\tend\n\tappend!(df, DataFrame(\n\t\tyear=yr, week=wk, \n\t\tcountry=c, brand=b, channel=ch,\n\t\tquantity=q, ppu=p)\n\t)\nend\n\ndf[!, :ppu_l] = log.(df[:, :ppu])\ndf[!, :quantity_l] = log.(df[:, :quantity])\n\n# Clean up\n\ndf = df[df.ppu_l .> 0.04, :]\ndf = df[df.quantity_l .> 0.0, :]\n\nCSV.write(joinpath(ProjDir, \"data\", \"data.csv\"), df)\n\nbglm = \"\ndata {\n  int<lower=0> N;\n  vector[N] q; // Outcome\n  vector[N] p; // Predictor\n}\nparameters {\n  real<lower=0> a;\n  real b;\n  real<lower=0> sigma;\n}\nmodel {\n  vector[N] mu;            \t\t// mu is a vector\n  a ~ normal(2.0, 10.0);\t\t// intercept positive\n  b ~ normal(-2.0, 10.0);\t\t// demand drops as price increases\n  sigma ~ uniform(0, 15);\n  mu = a + b * p;\n  q ~ normal(mu, sigma);\n}\n// generated quantities {\n//    vector[N] mu_pred;\n//    mu_pred = exp(p);\n//  }\n\";\n\nmean_q_l = mean(df[:, :quantity_l])\nmean_p_l = mean(df[:, :ppu_l])\ndata = Dict(\n  :N => size(df, 1),\n  :q => df[:, :quantity_l] .- mean_q_l,\n  :p => df[:, :ppu_l] .- mean_p_l\n)\n\np1 = scatter(df[:, :ppu], df[:, :quantity],\n\txlabel=\"ppu\", ylabel=\"quantity sold\", leg=false)\np2 = scatter(data[:p], data[:q],\n\txlabel=\"log(ppu)\", ylabel=\"log(quantity sold)\", leg=false)\nplot(p1, p2, layout=(2, 1))\nsavefig(joinpath(ProjDir, \"plots\", \"data.png\"))\n\nsm = SampleModel(\"bglm\", bglm)\n\nrc = stan_sample(sm, data=data)\n\nif success(rc)\n\tchns = read_samples(sm)\n\tplot(chns)\n\tsavefig(joinpath(ProjDir, \"plots\", \"chains.png\"))\n\n\tdfs = DataFrame(chns)\n\tshow(chns)\n\n\tp = -0.1:0.01:0.15\n\tp1 = scatter(data[:p], data[:q],\n\t\txlims=(-0.1, 0.15), ylims=(-1, 1),\n\t\txlabel=\"ppu_l\", ylabel=\"quantity_l sold\", leg=false)\n\ta_mean = mean(dfs[:, :a])\n\tb_mean = mean(dfs[:, :b])\n\tmu_q = a_mean .+ b_mean .* p\n\tplot!(p1, p, mu_q)\n\tsavefig(joinpath(ProjDir, \"plots\", \"regression.png\"))\n\n\tprice_points_l = log.(price_points) .- mean(log.(price_points))\n\tscatter(price_points_l, a_mean .+ b_mean .* price_points_l,\n\t\txlims = (-0.1, 0.15), ylims= (-0.1, 0.1), \n\t\tleg=false, xlabel=\"log(ppu)\", ylabel=\"log(quantity sold)\")\n\tselected_rows = rand(1:size(dfs, 1), 75)\n\tfor row in eachrow(dfs[selected_rows,:])\n\t\tplot!(p, row[:a] .+ row[:b] .* p, color=:gray)\n\tend\n\tscatter!(price_points_l, a_mean .+ b_mean .* price_points_l)\n\tsavefig(joinpath(ProjDir, \"plots\", \"sampling.png\"))\nend\n", "meta": {"hexsha": "7cc967efe4d0d8ff12b8b37ae329a6131e454e8a", "size": 3325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "approaches/bayesian_glm_03/bglm_03.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/bayesian_glm_03/bglm_03.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/bayesian_glm_03/bglm_03.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": 26.1811023622, "max_line_length": 76, "alphanum_fraction": 0.6204511278, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.76639126121102}}
{"text": "@testset \"Mincut\" begin\n\n    g = lg.complete_digraph(5)\n    cap1 = [\n       0.0 2.0 2.0 0.0 0.0\n       0.0 0.0 0.0 0.0 3.0\n       0.0 1.0 0.0 3.0 0.0\n       0.0 0.0 0.0 0.0 1.0\n       0.0 0.0 0.0 0.0 0.0\n    ];\n    (part1, part2, value) = LightGraphsFlows.mincut(g,1,5,cap1,LightGraphsFlows.PushRelabelAlgorithm())\n    @test value \u2248 4.0\n    @test part1 == [1]\n    @test sort(part2) == collect(2:5)\n    cap2 = [\n       0.0 3.0 2.0 0.0 0.0\n       0.0 0.0 0.0 0.0 3.0\n       0.0 1.0 0.0 3.0 0.0\n       0.0 0.0 0.0 0.0 1.5\n       0.0 0.0 0.0 0.0 0.0\n    ];\n    (part1, part2, value) = LightGraphsFlows.mincut(g,1,5,cap2,LightGraphsFlows.PushRelabelAlgorithm())\n    @test value \u2248 4.5\n    @test sort(part1) == collect(1:4)\n    @test part2 == [5]\n\n    g2 = lg.DiGraph(5)\n    lg.add_edge!(g2,1,2)\n    lg.add_edge!(g2,1,3)\n    lg.add_edge!(g2,3,4)\n    lg.add_edge!(g2,3,2)\n    lg.add_edge!(g2,2,5)\n\n    (part1, part2, value) = LightGraphsFlows.mincut(g2,1,5,cap1,LightGraphsFlows.PushRelabelAlgorithm())\n    @test value \u2248 3.0\n    @test sort(part1) == [1,3,4]\n    @test sort(part2) == [2,5]\n\n    #non regression test\n    flow_graph = lg.DiGraph(7)\n    capacity_matrix = zeros(7,7)\n    flow_edges = [\n    (1,2,2),(1,3,2),(2,4,4),(2,5,4),\n    (3,5,4),(3,6,4),(4,7,1),(5,7,1),(6,7,1)\n    ]\n    for e in flow_edges\n       u, v, f = e\n    lg.add_edge!(flow_graph, u, v)\n    capacity_matrix[u,v] = f\n    end\n    (part1, part2, value) = LightGraphsFlows.mincut(flow_graph, 1, 7, capacity_matrix, EdmondsKarpAlgorithm())\n    @test value \u2248 3.0\n    @test sort(part1) == [1,2,3,4,5,6]\n    @test sort(part2) == [7]\n\nend\n", "meta": {"hexsha": "1b4cf6915c62375fba771cb2de40a79d28dec350", "size": 1598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mincut.jl", "max_stars_repo_name": "fypc/LightGraphsFlows.jl", "max_stars_repo_head_hexsha": "727ac5958f5d18c590e9539233d2120044da7108", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2018-01-05T17:35:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T16:38:36.000Z", "max_issues_repo_path": "test/mincut.jl", "max_issues_repo_name": "fypc/LightGraphsFlows.jl", "max_issues_repo_head_hexsha": "727ac5958f5d18c590e9539233d2120044da7108", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2018-01-04T19:26:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T08:51:43.000Z", "max_forks_repo_path": "test/mincut.jl", "max_forks_repo_name": "fypc/LightGraphsFlows.jl", "max_forks_repo_head_hexsha": "727ac5958f5d18c590e9539233d2120044da7108", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-08-27T02:42:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T16:52:42.000Z", "avg_line_length": 28.0350877193, "max_line_length": 110, "alphanum_fraction": 0.555068836, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7663912593221928}}
{"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(\u03b1, 1)\nfunction randg(\u03b1::Float64)\n    dpar = (\u03b1 <= 1.0 ? \u03b1 + 1.0 : \u03b1) - 1.0 / 3.0\n    cpar = 1.0 / sqrt(9.0 * dpar)\n    randg2(dpar, cpar) * (\u03b1 > 1.0 ? 1.0 : rand()^(1.0 / \u03b1))\nend\n\nrand(d::Gamma) = d.scale * randg(d.shape)\n\nfunction rand!(d::Gamma, A::Array{Float64})\n    \u03b1 = d.shape\n    dpar = (\u03b1 <= 1.0 ? \u03b1 + 1.0 : \u03b1) - 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 \u03b1 <= 1.0\n        ainv = 1.0 / \u03b1\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": "using MultivariateStats\nusing LinearAlgebra\nusing Test\nusing StatsBase\nimport Statistics: mean, cov\nimport Random\n\n@testset \"Multi-class LDA\" begin\n\n    #Test equivalence of eigenvectors/singular vectors taking into account possible\n    #phase (sign) differences\n    #This may end up in Base.Test; see JuliaLang/julia#10651\n    function test_approx_eq_vecs(a::StridedVecOrMat{S},\n        b::StridedVecOrMat{T}, error=nothing) where {S<:Real, T<:Real}\n        n = size(a, 2)\n        @test n==size(b, 2) && size(a, 1)==size(b, 1)\n        error==nothing && (error=n^3*(eps(S)+eps(T)))\n        for i=1:n\n            ev1, ev2 = a[:, i], b[:, i]\n            deviation = min(abs(norm(ev1-ev2)), abs(norm(ev1+ev2)))\n            if !isnan(deviation)\n                @test isapprox.(deviation, 0.0, atol=error)\n            end\n        end\n    end\n\n    Random.seed!(34568)\n\n    ## prepare data\n    d = 5\n    ns = [10, 15, 20]\n    nc = length(ns)\n    n = sum(ns)\n    Xs = Matrix{Float64}[]\n    ys = Vector{Int}[]\n    Ss = Matrix{Float64}[]\n    cmeans = zeros(d, nc)\n\n    for k = 1:nc\n        R = qr(randn(d, d)).Q\n        nk = ns[k]\n\n        Xk = R * Diagonal(2 * rand(d) .+ 0.5) * randn(d, nk) .+ randn(d)\n        yk = fill(k, nk)\n        uk = vec(mean(Xk, dims=2))\n        Zk = Xk .- uk\n        Sk = Zk * Zk'\n\n        push!(Xs, Xk)\n        push!(ys, yk)\n        push!(Ss, Sk)\n        cmeans[:,k] .= uk\n    end\n\n    X = hcat(Xs...)\n    y = vcat(ys...)\n    mv = vec(mean(X, dims=2))\n    Sw = zeros(d, d)\n    for k = 1:nc\n        Sw += Ss[k]\n    end\n\n    Sb = zeros(d, d)\n    for k = 1:nc\n        dv = cmeans[:,k] - mv\n        Sb += ns[k] * (dv * dv')\n    end\n\n    Z = X .- mv\n    Sa = Z * Z'\n    @test Sw + Sb \u2248 Sa\n\n    @assert size(X) == (d, n)\n    @assert size(y) == (n,)\n\n    ## Stats\n\n    S = multiclass_lda_stats(nc, X, y)\n\n    @test S.dim == d\n    @test S.nclasses == nc\n\n    @test classweights(S) == ns\n    @test classmeans(S) \u2248 cmeans\n    @test mean(S) \u2248 mv\n\n    @test withclass_scatter(S) \u2248 Sw\n    @test betweenclass_scatter(S) \u2248 Sb\n\n    covestimator = SimpleCovariance(corrected=true)\n    Sce = multiclass_lda_stats(nc, X, y; covestimator_between=covestimator, covestimator_within=covestimator)\n\n    Swcorr = Sw * sum(ns)/(sum(ns)-1)\n    Sbcorr = Sb * nc/(nc-1)\n\n    @test withclass_scatter(Sce) \u2248 Swcorr\n    @test betweenclass_scatter(Sce) \u2248 Sbcorr\n\n    ## Solve\n\n    emax = maximum(eigvals(Sw))\n    Sw_c = copy(Sw)\n    Sb_c = copy(Sb)\n\n    lambda = 1.0e-3\n    Sw_r = Sw + (lambda * emax) * Matrix(I, d, d)\n\n    P1 = mclda_solve(Sb, Sw, :gevd, nc-1, lambda)\n    @test P1' * Sw_r * P1 \u2248 Matrix(I, nc-1, nc-1)\n    U = Sb * P1\n    V = Sw_r * P1\n    # test whether U is proportional to V,\n    # which indicates P is the generalized eigenvectors\n    @test U \u2248 V*Diagonal(vec(mean(U./V, dims=1)))\n\n    P2 = mclda_solve(Sb, Sw, :whiten, nc-1, lambda)\n    @test P2' * Sw_r * P2 \u2248 Matrix(I, nc-1, nc-1)\n\n    test_approx_eq_vecs(P1, P2)\n\n\n    ## MC-LDA\n\n    for T in (Float32, Float64)\n        M = fit(MulticlassLDA, nc, convert(Matrix{T}, X), y; method=:gevd, regcoef=convert(T, lambda))\n        @test size(M) == (d, nc - 1)\n        @test projection(M) \u2248 P1\n        @test M.pmeans \u2248 M.proj'cmeans\n        @test predict(M, X) \u2248 M.proj'X\n\n        M = fit(MulticlassLDA, nc, convert(Matrix{T}, X), y; method=:whiten, regcoef=convert(T, lambda))\n        @test size(M) == (d, nc - 1)\n        # @test projection(M) P2  # signs may change\n        @test M.pmeans \u2248 M.proj'cmeans\n        @test predict(M, X) \u2248 M.proj'X\n    end\n\n\n    ## High-dimensional LDA (subspace LDA)\n\n    # Low-dimensional case (no singularities)\n\n    centers = [zeros(5) [10.0;zeros(4)] [0.0;10.0;zeros(3)]]\n\n    # Case 1: 3 groups of 500\n    dX = randn(5,1500);\n    for i = 0:500:1000\n        dX[:,(1:500).+i] .= dX[:,(1:500).+i] .- mean(dX[:,(1:500).+i], dims=2)  # make the mean of each 0\n    end\n    dX1 = dX\n    X1 = [dX[:,1:500].+centers[:,1] dX[:,501:1000].+centers[:,2] dX[:,1001:1500].+centers[:,3]]\n    label1 = [fill(1,500); fill(2,500); fill(3,500)]\n    # Case 2: 3 groups, one with 1000, one with 100, and one with 10\n    dX = randn(5,1110);\n    dX[:,   1:1000] .= dX[:,   1:1000] .- mean(dX[:,   1:1000], dims=2)\n    dX[:,1001:1100] .= dX[:,1001:1100] .- mean(dX[:,1001:1100], dims=2)\n    dX[:,1101:1110] .= dX[:,1101:1110] .- mean(dX[:,1101:1110], dims=2)\n    dX2 = dX\n    X2 = [dX[:,1:1000].+centers[:,1] dX[:,1001:1100].+centers[:,2] dX[:,1101:1110].+centers[:,3]]\n    label2 = [fill(1,1000); fill(2,100); fill(3,10)]\n\n    for (X, dX, label) in ((X1, dX1, label1), (X2, dX2, label2))\n        w = [length(findall(label.==1)), length(findall(label.==2)), length(findall(label.==3))]\n        M = fit(SubspaceLDA, X, label)\n        @test indim(M) == 5\n        @test outdim(M) == 2\n        totcenter = vec(sum(centers.*w', dims=2)./sum(w))\n        @test mean(M) \u2248 totcenter\n        @test classmeans(M) \u2248 centers\n        @test classweights(M) == w\n        x = rand(5)\n        @test predict(M, x) \u2248 projection(M)'*x\n        dcenters = centers .- totcenter\n        Hb = dcenters.*sqrt.(w)'\n        Sb = Hb*Hb'\n        Sw = dX*dX'\n        # When there are no singularities, we need to solve the \"regular\" LDA eigenvalue equation\n        proj = projection(M)\n        @test Sb*proj \u2248 Sw*proj*Diagonal(M.\u03bb)\n        @test proj'*Sw*proj \u2248 Matrix(I,2,2)\n\n        # also check that this is consistent with the conventional algorithm\n        Mld = fit(MulticlassLDA, 3, X, label)\n        for i = 1:2\n            @test abs(dot(normalize(proj[:,i]), normalize(Mld.proj[:,i]))) \u2248 1\n        end\n    end\n\n    # High-dimensional case (undersampled => singularities)\n    X = randn(10^6, 9)\n    label = rand(1:3, 9); label[1:3] = 1:3\n    M = fit(SubspaceLDA, X, label)\n    centers = M.cmeans\n    for i = 1:3\n        flag = label.==i\n        @test centers[:,i] \u2248 mean(X[:,flag], dims=2)\n        @test M.cweights[i] == sum(flag)\n    end\n    dcenters = centers .- mean(X, dims=2)\n    Hb = dcenters*Diagonal(sqrt.(M.cweights))\n    Hw = X - centers[:,label]\n    @test (M.projw'*Hb)*(Hb'*M.projw)*M.projLDA \u2248 (M.projw'*Hw)*(Hw'*M.projw)*M.projLDA*Diagonal(M.\u03bb)\n    Gw = projection(M)'*Hw\n    @test Gw*Gw' \u2248 Matrix(I,2,2)\n\n    # Test that nothing breaks if one class has no members\n    label[1:4] .= 1\n    label[5:9] .= 3  # no data points have label == 2\n    M = fit(SubspaceLDA, X, label)\n    centers = M.cmeans\n    dcenters = centers .- mean(X, dims=2)\n    Hb = dcenters*Diagonal(sqrt.(M.cweights))\n    Hw = X - centers[:,label]\n    @test (M.projw'*Hb)*(Hb'*M.projw)*M.projLDA \u2248 (M.projw'*Hw)*(Hw'*M.projw)*M.projLDA*Diagonal(M.\u03bb)\n\n    # Test normalized LDA\n    function gen_ldadata_2(centers, n1, n2)\n        d = size(centers, 1)\n        X = randn(d, n1+n2)\n        X[:,1:n1]       .-= vec(mean(X[:,1:n1], dims=2))\n        X[:,n1+1:n1+n2] .-= vec(mean(X[:,n1+1:n1+n2], dims=2))\n        dX = copy(X)\n        X[:,1:n1]       .+= centers[:,1]\n        X[:,n1+1:n1+n2] .+= centers[:,2]\n        label = [fill(1,n1); fill(2,n2)]\n        X, dX, label\n    end\n    centers = zeros(2,2); centers[1,2] = 10\n    n1 = 100\n    for n2 in (100, 1000, 10000)\n        X, dX, label = gen_ldadata_2(centers, n1, n2)\n        M = fit(SubspaceLDA, X, label; normalize=true)\n        proj = projection(M)\n        Hb = centers .- mean(centers, dims=2)   # not weighted by number in each cluster\n        Sb = Hb*Hb'\n        Sw = dX*dX'/(n1+n2)\n        @test Sb*proj \u2248 Sw*proj*Diagonal(M.\u03bb)\n    end\n\n    # Test various input data types\n    for (T, nrm) in Iterators.product((Float64, Float32), (false, true))\n        n2 = 100\n        X, dX, label = gen_ldadata_2(centers, n1, n2)\n        M = fit(SubspaceLDA, convert(Matrix{T}, X), label; normalize=nrm)\n        proj = projection(M)\n        @test eltype(proj) === T\n    end\n\nend\n", "meta": {"hexsha": "e9499573c2680529f4c9b9237c643a335c6c3d58", "size": 7743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mclda.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": "test/mclda.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": "test/mclda.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": 30.972, "max_line_length": 109, "alphanum_fraction": 0.5447500969, "num_tokens": 2850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.766360736386771}}
{"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": "# Scikit-Learn:\n#  - Python: https://scikit-learn.org/stable/\n#  - Julia port/wrapper: https://github.com/cstjean/ScikitLearn.jl\n\n# Import libraries\nusing Statistics, StatsPlots, ScikitLearn\nusing ScikitLearn.CrossValidation: cross_val_score\n@sk_import datasets: load_breast_cancer\n@sk_import preprocessing : scale\n@sk_import linear_model: SGDClassifier\n\n# Load and prepare data\ncancer_data = load_breast_cancer()\ny = cancer_data[\"target\"] # Training labels ('malignant = 0', 'benign = 1')\nX = cancer_data[\"data\"] # 30 attributes; https://scikit-learn.org/stable/datasets/index.html#breast-cancer-dataset\nX = scale(X) # scale each data attribute to zero-mean and unit variance\n\n# Plot the first 2 attributes of training points\ncolors = [y == 1 ? \"blue\" : \"red\" for y in y]\nlabels = [y == 1 ? \"benign\" : \"malign\" for y in y]\nscatter(X[:,1],X[:,2], colour=colors, title=\"Classified tumors\",xlabel=\"Tumor Radius\", ylabel=\"Tumor Texture\", group=labels)\n\n\n# Compute cross-validation scores\nalpha = eps():0.005:1 # Range of hyperparameter values 1E-15 to 1 by 0.005\nval_scores = zeros(length(alpha)) # Initialize validation score for each alpha value\nfor (i,a) in enumerate(alpha) # for each alpha value\n    # Set up SVM with hinge loss and l2 norm regularization\n    model = SGDClassifier(loss=\"hinge\", penalty=\"l2\", alpha=a)\n    # Calculate cross validation scores for 5-fold cross-validation\n    score = cross_val_score(model, X, y; cv=5)\n    val_scores[i] = mean(score) # Calculate mean of the 5 scores\nend\n\n# Plot how cross-validation score changes with alpha\nplot(alpha,val_scores,xlims=(0,1), xlabel=\"alpha\",ylabel=\"Mean Cross-Validation Accuracy\",label=\"\")\n\n# Determine the alpha that maximizes the cross-validation score\nind = argmax(val_scores)\nalpha_star = alpha[ind]\nprintln(\"alpha_star = $alpha_star\")\nvline!([alpha_star], label=\"alpha*\")\n\n# Train model with alpha_star\nmodel_star = SGDClassifier(loss=\"hinge\", penalty=\"l2\", alpha=alpha_star)\nmodel_trained = model_star.fit(X,y)\nprint(\"Training Accuracy = $(model_trained.score(X,y))\")\n\n# Plot decision boundary of trained model\nslope = model_trained.coef_[1,2]/-model_trained.coef_[1,1]\nx1 = -10:0.5:10\ny1 = slope*x1\nscatter(X[:,1],X[:,2], colour=colors, title=\"Classified tumors\",xlims=(-4,4),ylims=(-6,6), xlabel=\"Tumor Radius\", ylabel=\"Tumor Texture\", group=labels)\nplot!(x1,y1, linestyle = :dot, label=\"classifier\")\n", "meta": {"hexsha": "37b935da46d2edcd86332160d1c6b1172225e045", "size": 2378, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Unit 01 - Linear Classifiers and Generalizations/recitation01_code_tumorDiagnosisDemo.jl", "max_stars_repo_name": "murtaza777/MITx_6.86x", "max_stars_repo_head_hexsha": "06749245c22ce66c1b51ba2530f7cd309a717997", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187, "max_stars_repo_stars_event_min_datetime": "2020-03-04T00:17:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T11:02:50.000Z", "max_issues_repo_path": "Unit 01 - Linear Classifiers and Generalizations/recitation01_code_tumorDiagnosisDemo.jl", "max_issues_repo_name": "fanyak/MITx_6.86x", "max_issues_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-19T06:31:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-19T08:44:13.000Z", "max_forks_repo_path": "Unit 01 - Linear Classifiers and Generalizations/recitation01_code_tumorDiagnosisDemo.jl", "max_forks_repo_name": "fanyak/MITx_6.86x", "max_forks_repo_head_hexsha": "f6370c3c7f505644b242aa74531c645ece09d6ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 105, "max_forks_repo_forks_event_min_datetime": "2020-03-06T14:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T04:43:06.000Z", "avg_line_length": 43.2363636364, "max_line_length": 151, "alphanum_fraction": 0.7359125315, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7663393138247336}}
{"text": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) \u2209 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\u22650`` and ``0\u2264k\u2264n`` (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 \u2208 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    \u220f(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 \u2208 0:n-1, k \u2208 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 \u2208 Z`` and ``k \u2208 Z``. Behaves like the binomial function in Maple and Mathematica.\n\n``\\\\binom{n}{k} = \\\\lim \\\\limits_{x \\\\rightarrow 1}(\u0393(n + x) / (\u0393(k + x) \u0393(n - k + x))).``\n\n\"\"\"\nfunction Binomial(n::Int, k::Int)\n    0 \u2264 k \u2264 n && return binomial(ZZ(n), ZZ(k))\n    k \u2264 n < 0 && return binomial(ZZ(-k - 1), ZZ(n - k)) * (-1)^(n - k)\n    n < 0 \u2264 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 \u2208 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 \u2208 0:10, k \u2208 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\u0394(T007318(8))\n    println()\n\n    for n \u2208 -10:10\n        println([Binomial(n, k) for k \u2208 -10:10])\n    end\nend\n\n\"\"\"\n\nfor n \u2208 0:10000 Binomial(2*n,n) end\n    0.504729 seconds (10.00 k allocations: 156.266 KiB)\nfor n \u2208 -100:100, k \u2208 -100:100 Binomial(n,k) end\n    0.008669 seconds (55.55 k allocations: 867.984 KiB)\nfor k \u2208 -10000:10000 Binomial(-5,k) end\n    0.005378 seconds (40.00 k allocations: 624.969 KiB)\n\"\"\"\nfunction perf()\n    @time (for n \u2208 0:10000\n        Binomial(2n, n)\n    end)\n    @time (for n \u2208 -100:100, k \u2208 -100:100\n        Binomial(n, k)\n    end)\n    @time (for k \u2208 -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": "# # dempe.mod\tQQR2-MN-4-3\n# # Original AMPL coding by Sven Leyffer\n#\n# # An MPEC from S. Dempe, \"A necessary and sufficient optimality\n# # condition for bilevel programming problems\", Optimization 25,\n# # pp. 341-354, 1992. From book Math. Progr. with Equil. Constr,\n# # by Luo, Pang & Ralph, CUP, 1997, p. 354.\n#\n# # Number of variables:   2 + 1 multipliers\n# # Number of constraints: 2\n# # Nonlinear complementarity constraints\n#\n# var x;\n# var z;\n# var w >= 0;\n#\n# minimize f: (x - 3.5)^2 + (z + 4)^2;\n#\n# subject to\n#     con1:  z - 3 + 2*z*w = 0;\n#     con2:  0 >= z^2 - x     complements  w >= 0;\n#\n# data;\n#\n# # starting point\n# let x := 1;\n# let z := 1;\n# let w := 1;\n#\n#\n# let x :=   0.183193 ;\n# let z := 0.428106;\n# let w := 3.00379;\n\n\nusing JuMP, Complementarity\nusing Ipopt\nusing Test\n\n@testset \"dempe.jl\" begin\n\n    dempe = Model(with_optimizer(Ipopt.Optimizer))\n\n\n    @variable(dempe, x)\n    @variable(dempe, z)\n    @variable(dempe, w>=0)\n\n    @NLobjective(dempe, Min, (x - 3.5)^2 + (z + 4)^2)\n\n    @NLconstraint(dempe, z - 3 + 2*z*w == 0)\n\n    @complements(dempe, 0 >= z^2 - x,  w >= 0, simple)\n\n    # Initial solutions to help reaching the optimality\n    set_start_value(x, 0)\n    set_start_value(z, 0)\n    set_start_value(w, 1e7)\n\n    # (xx, zz, ww) = (-3.999779029254958e-10, 9.852984581857451e-8, 1.5223813031201378e7)\n\n\n    JuMP.optimize!(dempe)\n\n    @show JuMP.objective_value(dempe)\n    @test isapprox(JuMP.objective_value(dempe), 28.25, atol=1e-4)\n\n    xx = JuMP.value(x)\n    zz = JuMP.value(z)\n    ww = JuMP.value(w)\n    @test isapprox(zz - 3 + 2*zz*ww, 0, atol=1e-4)\nend\n", "meta": {"hexsha": "890a9d4ac81d493dd40632ac4f147c1a1db19367", "size": 1597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/mpec/dempe.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Complementarity.jl-a9b2a840-c9d5-5181-a245-8df664c2d6e7", "max_stars_repo_head_hexsha": "c1f95f21f56af259dec56d8bb6a2d82db6995f7f", "max_stars_repo_licenses": ["MIT"], "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/mpec/dempe.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Complementarity.jl-a9b2a840-c9d5-5181-a245-8df664c2d6e7", "max_issues_repo_head_hexsha": "c1f95f21f56af259dec56d8bb6a2d82db6995f7f", "max_issues_repo_licenses": ["MIT"], "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/mpec/dempe.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Complementarity.jl-a9b2a840-c9d5-5181-a245-8df664c2d6e7", "max_forks_repo_head_hexsha": "c1f95f21f56af259dec56d8bb6a2d82db6995f7f", "max_forks_repo_licenses": ["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.8767123288, "max_line_length": 89, "alphanum_fraction": 0.6086412023, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7663392986334355}}
{"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) -> \u0394_q\nReturn the `q` order generalized dimension of the `dataset`, by calculating\nthe [`genentropy`](@ref) for each `\u03b5 \u2208 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 `\u03b5`, where `\u03b5 \u2208 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, \u03b5; q, base) for \u03b5 \u2208 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,\u211d},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{\u211d,Euclidean{Tuple{N},\u211d},<: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{\u211d,Euclidean{Tuple{N},\u211d},MinkowskiMetric},\n    p,\n) where {N}\n    return Diagonal([ones(N - 1)..., -1])\nend\n\nfunction inner(::MetricManifold{\u211d,Euclidean{Tuple{N},\u211d},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\u27e8a,b\u27e9_{\\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\u00e7\u00e3o de substitui\u00e7\u00e3o reversa, onde retorna um x que \u00e9 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": "\"\"\"\nBased on:\nhttps://medium.com/vooban-ai/hyperopt-tutorial-for-optimizing-neural-networks-hyperparameters-e3102814b919\n\"\"\"\nmodule TestVoobanBasic\n\nusing Test\nusing TreeParzen\n\nobjective(params) = params[:x]^2 - params[:x] + 1\nspace = Dict(:x => HP.Uniform(:x, -5.0, 5.0))\nbest = fmin(objective, space, 100)\n@test isapprox(best[:x], 0.5366692707330428, rtol=1e1)\n\nend\ntrue\n", "meta": {"hexsha": "716df6f3d543d5c6eda2265eec1804ad07caa76d", "size": 374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/vooban/basic.jl", "max_stars_repo_name": "lhnguyen-vn/TreeParzen.jl", "max_stars_repo_head_hexsha": "d6b4181a45167663e8844330220f0c62c715c75f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-05-06T09:06:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T22:41:16.000Z", "max_issues_repo_path": "test/vooban/basic.jl", "max_issues_repo_name": "lhnguyen-vn/TreeParzen.jl", "max_issues_repo_head_hexsha": "d6b4181a45167663e8844330220f0c62c715c75f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2020-05-15T14:29:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T15:24:44.000Z", "max_forks_repo_path": "test/vooban/basic.jl", "max_forks_repo_name": "lhnguyen-vn/TreeParzen.jl", "max_forks_repo_head_hexsha": "d6b4181a45167663e8844330220f0c62c715c75f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-09-11T03:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T18:42:50.000Z", "avg_line_length": 22.0, "max_line_length": 106, "alphanum_fraction": 0.7272727273, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.766288223775246}}
{"text": "\n\n@testset \"Computation of c constants\" begin\n    # Testing right boundary\n    # zero order right boundary\n    @test Network_ADER.compute_c(1,0,0,0) == 1\n    # 3 rd order right boundary\n    @test Network_ADER.compute_c(3,1,1,2) == 1\n    @test Network_ADER.compute_c(3,2,0,2) == 11/6\n    \n    # Testing left boundary\n    # left boundary seond order\n    @test Network_ADER.compute_c(2,0,0,1,true) == -1/2\n    # left boundary 4th order\n    @test Network_ADER.compute_c(4,1,1,3,true) == -1/12\n    @test Network_ADER.compute_c(4,2,2,1,true) == -1/2\nend\n\n@testset \"Computation of C matrices\" begin\n    # Testing right boundary\n    # Order 3, r=0 test\n    @test isapprox(Network_ADER.compute_C(3,0) , [1/3 5/6 -1/6;-1 1 0;1 -2 1])\n  \n    # Testing left boundary\n    # Order 3, r=2 test\n    @test isapprox(Network_ADER.compute_C(3,2,true) , [-1/6 5/6 1/3;0 -1 1;1 -2 1])\nend\n\n@testset \"Computation of B matrices\" begin\n    # Testing right boundary\n    # Order 2, r=0 test\n    @test isapprox(Network_ADER.compute_B([3/2 -1/2;-1 1]) , [1 -1; -1 1])\n    # Order 3, r=2 test\n    @test isapprox(Network_ADER.compute_B([1/3 -7/6 11/6;1 -3 2;1 -2 1]) , [4/3 -19/6 11/6; -19/6 25/3 -31/6;11/6 -31/6 10/3])\nend\n\n@testset \"Computation of protoype D coeffiencents\" begin\n    C= Network_ADER.compute_C_constants(5)\n    @test isapprox(Network_ADER.compute_D(2,C) , [2/3; 1/3])\n    @test isapprox(Network_ADER.compute_D(3,C) , [3/10; 3/5 ; 1/10])\nend\n\n@testset \"Computation of a complete protoype D coeffiencent set\" begin\n    C= Network_ADER.compute_C_constants(5)\n    D_expected = Array{Array{Float64,2},1}(undef,2);\n    D_expected[1]=zeros(1,1)\n    D_expected[1][1]=1\n    D_expected[2]=zeros(2,1)\n    D_expected[2][:]=[2/3;1/3]\n    @test isapprox(Network_ADER.compute_D_constants(2,C) , D_expected)\nend", "meta": {"hexsha": "1a652fefc608da281278cbb04e283ac5bcd205e1", "size": 1783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Polynomial_reconstruction_coefficients_tests.jl", "max_stars_repo_name": "Jochen-Kall/Network_ADER.jl", "max_stars_repo_head_hexsha": "21e4de90afee12d86d1bea93f36e87638b2f2f29", "max_stars_repo_licenses": ["MIT"], "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/Polynomial_reconstruction_coefficients_tests.jl", "max_issues_repo_name": "Jochen-Kall/Network_ADER.jl", "max_issues_repo_head_hexsha": "21e4de90afee12d86d1bea93f36e87638b2f2f29", "max_issues_repo_licenses": ["MIT"], "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/Polynomial_reconstruction_coefficients_tests.jl", "max_forks_repo_name": "Jochen-Kall/Network_ADER.jl", "max_forks_repo_head_hexsha": "21e4de90afee12d86d1bea93f36e87638b2f2f29", "max_forks_repo_licenses": ["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.9607843137, "max_line_length": 126, "alphanum_fraction": 0.6545148626, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7662882185480866}}
{"text": "module Issue743\n\nusing Gridap\nusing LinearAlgebra\nusing Gridap.FESpaces\nusing Test\n\nmodel = CartesianDiscreteModel((0,2\u03c0,0,2\u03c0),(10,10);isperiodic=(true,true))\norder = 2\nreffe = ReferenceFE(lagrangian,Float64,order)\nV = TestFESpace(model,reffe;constraint=:zeromean)\nU = TrialFESpace(V)\ndegree = 2*order\n\u03a9 = Triangulation(model)\nd\u03a9 = Measure(\u03a9,degree)\nf(x) = cos(x[1])+sin(x[2])\na(u,v) = \u222b( \u2207(v)\u22c5\u2207(u) )*d\u03a9\nb(v) = \u222b( v*f )*d\u03a9\nop = AffineFEOperator(a,b,U,V)\nuh = solve(op)\nA = get_matrix(op)\n@test cond(Matrix(A)) < 1.e5\n@test abs(sum(\u222b(uh)d\u03a9)) < 1.e-10\n\n#writevtk(\u03a9,\"results\",nsubcells=10,cellfields=[\"uh\"=>uh])\n\nend # module\n", "meta": {"hexsha": "c9137b6a1084fc47ff5ba3c975e0f5a511a7ced2", "size": 623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/GridapTests/issue_743.jl", "max_stars_repo_name": "aerappa/Gridap.jl", "max_stars_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-03-18T06:52:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T11:01:18.000Z", "max_issues_repo_path": "test/GridapTests/issue_743.jl", "max_issues_repo_name": "aerappa/Gridap.jl", "max_issues_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2019-03-17T12:26:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-13T14:53:34.000Z", "max_forks_repo_path": "test/GridapTests/issue_743.jl", "max_forks_repo_name": "aerappa/Gridap.jl", "max_forks_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-17T12:23:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-17T12:23:55.000Z", "avg_line_length": 22.25, "max_line_length": 74, "alphanum_fraction": 0.683788122, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893258, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7662801625842436}}
{"text": "@info \"An\u00e1lise 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\u00e7as aplicadas nos N\u00f3s\nf =[0, 500, 500, 600, 1000, 0]\n# Vetor de deslocamentos nodais\nu = [0, 0, 0, 0, 0, 2]\n\n# N\u00f3s\nA = 1\nB = 2\nC = 3\nD = 4\nE = 5\nF = 6\n\n# Relacionamento entre elementos e n\u00f3s\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\u00e7\u00f5es para achar os deslocamentos nodais\n# \u00e9 retirada da matriz a linha e coluna correspondente ao n\u00f3 que n\u00e3o 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": "# Learn Polynomials\r\n\r\nusing Logging\r\nlogger = SimpleLogger(stdout, Logging.Info)\r\nglobal_logger(logger)\r\n\r\nimport Polynomials\r\nPoly = Polynomials\r\n\r\n\r\npoly = Poly.Polynomial([1, 0, 3, 4])\r\nusing Plots\r\nplotly()\r\nxs = range(0, 10, length=10)\r\nys = @. exp(-xs)\r\nf = Poly.fit(xs,ys) # degree = length(xs) - 1\r\nf2 = Poly.fit(xs,ys, 2) # 2\r\nf3 = Poly.fit(xs,ys, 1)\r\n\r\n#pt = scatter(xs, ys, markerstrokewidth=0, label=\"Data\")\r\npt = plot(xs, ys, seriestype=:scatter, markerstrokewidth=0)\r\n\r\nplot!(pt, f, extrema(xs)..., label=\"Fit\")\r\nplot!(pt, f2, extrema(xs)..., label=\"Quadratic Fit\")\r\nplot!(pt, f3, extrema(xs)..., label=\"Linear Fit\")\r\n\r\ngui(pt)\r\nnothing\r\n", "meta": {"hexsha": "c957f02ab741a4aef842efc07a13cec12a9eff53", "size": 653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "learn/learn_Polynomials.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": "learn/learn_Polynomials.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": "learn/learn_Polynomials.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": 22.5172413793, "max_line_length": 60, "alphanum_fraction": 0.6416539051, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7662707787321958}}
{"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\u03f5 = 0.02f0\nflag_MALA = true\n\n# Run MALA\ntime = @elapsed fval, xLD = langevinSampler(neglogp, nsamples, x0, \u03f5; 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": "import Base: rand, randn\nfunction rand(::Type{SimpleQuaternion{T}}) where T <: Real\n    args = (rand(T) for j=1:4)\n    return SimpleQuaternion(args...)\nend \n\n\"\"\"\n`rand(SimpleQuaternion)` returns a quaternion whose four entries \nare uniform [0,1] random values.\n\"\"\"\nrand(::Type{SimpleQuaternion}) = rand(SimpleQuaternion{Float64})\n\n\"\"\"\n`randn(SimpleQuaternion)` returns a quaternion whose four entries are \nstandard normal random values. \n\"\"\"\nfunction randn(::Type{SimpleQuaternion{T}}) where T\n    args = (randn(T) for j=1:4)\n    return SimpleQuaternion(args...)\nend\n\nrandn(::Type{SimpleQuaternion}) = randn(SimpleQuaternion{Float64})", "meta": {"hexsha": "ad5765db2c70228fc721a9df82e864bfcd9144d2", "size": 634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random.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/random.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/random.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": 28.8181818182, "max_line_length": 70, "alphanum_fraction": 0.7208201893, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.766269671741131}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 1bcf25d8-71c2-11eb-05ca-6fe7c4e1b24f\nbegin\n\tusing Pkg\n\tPkg.activate(\"MLJ_env\", shared=true)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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) # \u2261 2 * feature' * errors\n\tend\nend\n\n# \u2554\u2550\u2561 9dcffb1c-71c1-11eb-2402-39eaa1f1b5e1\nmd\"\"\"\n## Week 2: Multiple Regression (Gradient Descent)\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3e5d907e-71c2-11eb-2eb3-4375fb21b884\nmd\"\"\"\n### Load in house sales data\n\"\"\"\n\n# \u2554\u2550\u2561 4c736078-71c2-11eb-225b-816745199225\nsales = CSV.File(\"../../ML_UW_Spec/C02/data/kc_house_test_data.csv\"; \n\theader=true) |> DataFrame;\n\n# \u2554\u2550\u2561 58e6255a-71c2-11eb-2094-9dbe7fb64151\nfirst(sales, 3)\n\n# \u2554\u2550\u2561 64c97662-71c2-11eb-2894-2d544642b136\ntypeof(sales.bedrooms)\n\n# \u2554\u2550\u2561 80fbf0f8-71c2-11eb-265a-fb539d764180\ntypeof(sales.bathrooms)\n\n# \u2554\u2550\u2561 35b5d05a-71cc-11eb-15a9-852c5a534fab\nmd\"\"\"\n### Convert to Julia Matrix/Vector\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 498b3458-71cc-11eb-3b55-8381d58d04bb\nmd\"\"\"\n### Predicting output given regression weights\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u00d7 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u03b7. 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 \u03f5.\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# \u2554\u2550\u2561 958f81a6-71cc-11eb-13e8-61dddeb014a7\nfunction regression_gradient_descent(f_matrix::Matrix{T}, \n\t\toutput::Vector{T}, init_weights::Vector{T}, \u03b7::T, \u03f5::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        \u2207_sum_squares = 0.0                       # init the gradient sum of squares\n        \n\t\t## Update the weights\n        for ix \u2208 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 \u2207_sum_squares (convergence)\n            \u2207_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] -= \u03b7 * deriv_ix\n\t\tend\n        ##  compute the square-root of the \u2207_sum_squares to get the \u2207 magnitude:\n        \u2207_magnitude = \u221a(\u2207_sum_squares)\n        \u2207_magnitude < \u03f5 && break\n\tend    \n    weights\nend\n\n# \u2554\u2550\u2561 4454239e-71ce-11eb-295e-1755bc0549e6\nmd\"\"\"\n### Running the Gradient Descent as Simple Regression\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03b7 = 7e-12\n\t\u03f5 = 2.5e7\nend\n\n# \u2554\u2550\u2561 9883c1ee-71cf-11eb-3b48-a14df232588f\ngd_weights = regression_gradient_descent(simple_f_matrix, Vector{Float64}(out), init_weights, \u03b7, \u03f5)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 26199ccc-71d0-11eb-0b4e-5f2f8ebc7b76\n(test_s_feature_matrix, test_out) = get_data(sales_test, s_features, s_out);\n\n# \u2554\u2550\u2561 4be11b60-71d0-11eb-1550-6d2854691b05\nmd\"\"\"\nNow compute your predictions using `test_s_feature_matrix` and the `gd_weights` from above.\n\"\"\"\n\n# \u2554\u2550\u2561 65c26930-71d0-11eb-248a-3751d927b2f6\nya_preds = predict_output(test_s_feature_matrix, gd_weights)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03b7\u1d63 = 4e-12\n\t\u03f5\u1d63 = 1e9\nend\n\n# \u2554\u2550\u2561 59a6c7bc-71d1-11eb-2836-71ec957bd538\nmd\"\"\"\nUse the above parameters to estimate the model weights. Record these values for your quiz.\n\"\"\"\n\n# \u2554\u2550\u2561 6a907c30-71d1-11eb-3adb-1355e084f741\nweights_mr = regression_gradient_descent(mr_feature_matrix, \n\tVector{Float64}(mr_output), mr_init_weights, \u03b7\u1d63, \u03f5\u1d63)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 44c15f32-71d2-11eb-2232-5fd5a07b2bfc\nmd\"\"\"\nWhat is the actual price for the 1st house in the test data set?\n\"\"\"\n\n# \u2554\u2550\u2561 4eeb7218-71d2-11eb-1fa7-21fec4e8c846\nsales_test[!, :price][1]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25009dcffb1c-71c1-11eb-2402-39eaa1f1b5e1\n# \u255f\u2500c39f9348-71c1-11eb-1691-1d28c6b1d916\n# \u2560\u25501bcf25d8-71c2-11eb-05ca-6fe7c4e1b24f\n# \u2560\u25501f7ea604-71c2-11eb-028a-a166f6f4dc5d\n# \u255f\u25003e5d907e-71c2-11eb-2eb3-4375fb21b884\n# \u2560\u25504c736078-71c2-11eb-225b-816745199225\n# \u2560\u255058e6255a-71c2-11eb-2094-9dbe7fb64151\n# \u2560\u255064c97662-71c2-11eb-2894-2d544642b136\n# \u2560\u255080fbf0f8-71c2-11eb-265a-fb539d764180\n# \u255f\u250035b5d05a-71cc-11eb-15a9-852c5a534fab\n# \u255f\u2500a2928dc6-71c2-11eb-3724-29dc1448a0f3\n# \u2560\u2550e4da992e-71c2-11eb-36b8-93dd614051c1\n# \u2560\u2550d62e0368-71c2-11eb-16f7-5fda56951d21\n# \u255f\u2500498b3458-71cc-11eb-3b55-8381d58d04bb\n# \u255f\u2500daf8aefc-71c7-11eb-04fa-e71d7b2cde21\n# \u2560\u255002f0c99e-71c5-11eb-1fe1-b3f820998d54\n# \u2560\u25509cd636f2-71c5-11eb-2957-afbaf437aaa5\n# \u255f\u250021635b6e-71c8-11eb-2272-edec98c58339\n# \u2560\u2550f377f6d4-71c9-11eb-0249-f3d63e87062b\n# \u2560\u25501301a4d2-71ca-11eb-339c-d1f747a3ffe7\n# \u2560\u255049ce0c84-71cb-11eb-3947-6141a9498ffb\n# \u255f\u2500239ff6ca-71cc-11eb-341a-df1453d60a15\n# \u2560\u2550958f81a6-71cc-11eb-13e8-61dddeb014a7\n# \u255f\u25004454239e-71ce-11eb-295e-1755bc0549e6\n# \u2560\u25500623d920-71ce-11eb-0936-870685f2e788\n# \u2560\u25506a1ee460-71ce-11eb-1b49-4de942aefe9d\n# \u2560\u25509883c1ee-71cf-11eb-3b48-a14df232588f\n# \u255f\u250006cf79e0-71d0-11eb-3eab-ad040213a64b\n# \u2560\u255026199ccc-71d0-11eb-0b4e-5f2f8ebc7b76\n# \u255f\u25004be11b60-71d0-11eb-1550-6d2854691b05\n# \u2560\u255065c26930-71d0-11eb-248a-3751d927b2f6\n# \u255f\u2500749979f6-71d0-11eb-0b3a-459257d95ca9\n# \u2560\u2550898fa5b2-71d0-11eb-18c3-ad6d0dbf9bf8\n# \u2560\u25505f0bdea2-71d3-11eb-150c-8722eee3f23a\n# \u2560\u25506d6eb4b0-71d3-11eb-24f0-f9f796040473\n# \u255f\u2500e13d4ca6-71d0-11eb-1ad7-119b4bf3c830\n# \u2560\u2550ec505642-71d0-11eb-2619-0f410fee1f94\n# \u255f\u250059a6c7bc-71d1-11eb-2836-71ec957bd538\n# \u2560\u25506a907c30-71d1-11eb-3adb-1355e084f741\n# \u255f\u2500c47ea9ec-71d1-11eb-0491-9ba85adf1e0a\n# \u2560\u2550da6f7c6a-71d1-11eb-381f-5f75054e14e7\n# \u255f\u250005450824-71d2-11eb-0a05-2b895313421f\n# \u2560\u25501706d680-71d2-11eb-3cd6-4d156d964fd7\n# \u255f\u250044c15f32-71d2-11eb-2232-5fd5a07b2bfc\n# \u2560\u25504eeb7218-71d2-11eb-1fa7-21fec4e8c846\n# \u255f\u250084462372-71d2-11eb-1627-1fc0ccb0d650\n# \u255f\u25008ef08466-71d2-11eb-0cbd-17d088b840e0\n# \u2560\u25509db31f5e-71d2-11eb-1527-29c0a844ce47\n# \u255f\u25000d254b32-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": "\"\"\"\nAbstract decomposition of N-mode tensor.\n\"\"\"\nabstract type TensorDecomposition{T<:Number, N} end\n\n\"\"\"\nReturns relative error between the re-composed and the original tensors.\n\"\"\"\nrel_residue{T,N}(recomposed::StridedArray{T, N}, tensor::StridedArray{T, N}) = vecnorm(recomposed - tensor) / vecnorm(tensor)\n\n\"\"\"\nReturns relative error between re-composed and the original tensor.\n\"\"\"\nrel_residue{T,N}(decomp::TensorDecomposition{T, N}, tensor::StridedArray{T, N}) = rel_residue(compose(decomp), tensor)\n\n\"\"\"\nReturns relative tensor decomposition error, NaN if not available.\n\"\"\"\nrel_residue(decomp::TensorDecomposition) = get(decomp.props, :rel_residue, NaN)\n\n_set_rel_residue(decomp::TensorDecomposition, error::Float64) = setindex!(decomp.props, error, :rel_residue)\n\n_set_rel_residue{T,N}(decomp::TensorDecomposition{T,N}, tensor::StridedArray{T,N}) =\n    _set_rel_residue(decomp, rel_residue(decomp, tensor))\n", "meta": {"hexsha": "d08758a6b3cf789af4b41bac80943575192d533c", "size": 915, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/abstract_decomposition.jl", "max_stars_repo_name": "TensorFactorization/TensorDecompositions.jl", "max_stars_repo_head_hexsha": "7e4766cd878905534c7b7295ce9d91dd7dc1bd71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/abstract_decomposition.jl", "max_issues_repo_name": "TensorFactorization/TensorDecompositions.jl", "max_issues_repo_head_hexsha": "7e4766cd878905534c7b7295ce9d91dd7dc1bd71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/abstract_decomposition.jl", "max_forks_repo_name": "TensorFactorization/TensorDecompositions.jl", "max_forks_repo_head_hexsha": "7e4766cd878905534c7b7295ce9d91dd7dc1bd71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-26T23:43:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-26T23:43:37.000Z", "avg_line_length": 36.6, "max_line_length": 125, "alphanum_fraction": 0.7595628415, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7662489272745427}}
{"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\u20132953, 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\u03c3 = 0.2\n\u03b1 = 0.5\n\u03b2 = 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), \u03c3))\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        [-\u03c0, -\u03c0 / 2, 0, \u03c0 / 2, \u03c0],\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, \u03b1, \u03b2, x)\nproxes = (\n    (N, \u03bb, x) -> prox_distance(N, \u03bb, data, x, 2),\n    (N, \u03bb, x) -> prox_TV(N, \u03b1 * \u03bb, x),\n    (N, \u03bb, x) -> prox_TV2(N, \u03b2 * \u03bb, x),\n)\n\no = cyclic_proximal_point(\n    N,\n    F,\n    proxes,\n    data;\n    \u03bb=i -> \u03c0 / (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        [-\u03c0, -\u03c0 / 2, 0, \u03c0 / 2, \u03c0],\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": "using Plots\npyplot() # Use PyPlot as a backend (may already be the default)\n\n#x = collect(1:7)\n#y = []\n\n#for item in x\n    #push!(y, 2 - 2*item + item^2/4)\n#end\n\n\n\n#plot(x,y)\n#plot!(x, y, marker = :diamond, linewidth=2)\n#plot!(title = \"Sample plot\", leg=false)\n\nx = [1 2 3 4 5 6]'\n#y = (x-3).^2/4\ny = []\n\nfor item in x\n    push!(y, (item-3).^2/4)\nend\n\nplot(x,y, marker = :hex, leg=false, linewidth = 2, linecolor=:black)\nplot!(title=\"Plot for graded quiz\")\ngui()    # To show plot on atom", "meta": {"hexsha": "8d5135abee007c0404b74639a2be071a524ca818", "size": 488, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia-Scientific-Programming/w_02_quiz.jl", "max_stars_repo_name": "aliyyousuff/MOOC", "max_stars_repo_head_hexsha": "9d70cb0f17aa238c9b8a59b42daf02765fd8056c", "max_stars_repo_licenses": ["MIT"], "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-Scientific-Programming/w_02_quiz.jl", "max_issues_repo_name": "aliyyousuff/MOOC", "max_issues_repo_head_hexsha": "9d70cb0f17aa238c9b8a59b42daf02765fd8056c", "max_issues_repo_licenses": ["MIT"], "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-Scientific-Programming/w_02_quiz.jl", "max_forks_repo_name": "aliyyousuff/MOOC", "max_forks_repo_head_hexsha": "9d70cb0f17aa238c9b8a59b42daf02765fd8056c", "max_forks_repo_licenses": ["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.0740740741, "max_line_length": 68, "alphanum_fraction": 0.5942622951, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7662489198525404}}
{"text": "\"\"\"\n    RiemannMatrix\n\nType containing information about the Riemann Matrix, for use in computing the Riemann theta function.\n\"\"\"\nstruct RiemannMatrix\n    \u03c4::Array{<:Number} # matrix in Siegel upper-half space\n    g::Integer # genus\n    X::Array{<:Real} # real part of \u03c4\n    Y::Array{<:Real} # imaginary part of \u03c4\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(\u03c4, siegel=false, \u03f5=1.0e-12, nderivs=4)\n\n    Construct a RiemannMatrix type using a matrix \u03c4 in the Siegel upper-half space, for use in computing the Riemann theta function.\n\n    # Arguments\n    - `\u03c4::Array{<:Number}`: 2-dimensional array of complex numbers\n    - `siegel::Bool=false`: do a siegel transformation on \u03c4 if true, and use the input matrix otherwise\n    - `\u03f5::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(\u03c4::Array{<:Number}; siegel::Bool=false, \u03f5::Real=1.0e-12, nderivs::Integer=4)\n        \u03c4 = (siegel ? siegel_transform(\u03c4)[2] : \u03c4);\n        X = real(\u03c4);\n        Y = imag(\u03c4);\n        g = size(Y)[1];\n        T = (g > 1 ? convert(Array{Float64}, cholesky(Symmetric(Y)).U) : sqrt.(Y));\n        \u03c1 = svp(T)[2]*sqrt(\u03c0); # length of shortest vector in lattice generated by \u221a\u03c0*T\n        radius = [radius_ellipsoid(\u03f5, T, Y, \u03c1, 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(\u03c4, 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    \u03c4 = Symmetric((1/2)*(transpose(Mx) + Mx)) + Symmetric(transpose(My)*My)*im; # symmetric real part and psd imaginary part\n    return convert(Array, \u03c4);\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\u0302 = value.(x)\ny\u0302 = 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) \u2248 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": "using LinearAlgebra\n\ninclude(\"../quadrature/quadgrid.jl\")\n\nfunction param_grid_comp(n_param, param_priorInfo)\n    # extract param info\n    thetamin = param_priorInfo.theta.min\n    thetamax = param_priorInfo.theta.max\n    lambdamin = param_priorInfo.lambda.min\n    lambdamax = param_priorInfo.lambda.max\n    n_theta = n_param.theta\n    n_lambda = n_param.lambda\n   \n   # form a 2d theta grid\n   theta1_grid, wt1_theta = quadgrid(thetamin[1], thetamax[1], n_theta[1])\n   theta2_grid, wt2_theta = quadgrid(thetamin[2], thetamax[2], n_theta[2])\n   n_theta_totl = n_theta[1] * n_theta[2]\n   theta_grid = zeros(n_theta_totl, 2)\n   wt_theta = zeros(n_theta_totl)\n   for i in 1:n_theta[1], j in 1:n_theta[2]\n       theta_grid[j + (i-1) * n_theta[2], :] = [theta1_grid[i] theta2_grid[j]]\n       wt_theta[j + (i-1) * n_theta[2]] = wt1_theta[i] * wt2_theta[j]\n   end\n\n   # form a 1d lambda grid\n   lambda_grid, wt_lambda = quadgrid(lambdamin, lambdamax, n_lambda)\n\n   thetaInfo = (grid = theta_grid, wt = wt_theta)\n   lambdaInfo = (grid = lambda_grid, wt = wt_lambda)\n   param_gridInfo = (theta = thetaInfo, lambda = lambdaInfo)\n\n   return param_gridInfo\nend", "meta": {"hexsha": "3ec1a7c03fd54c2fe4e56e1d52bf34dddcedfcf2", "size": 1147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "individual_implementations/BTG_xinran/src/computation/param_grid_comp.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/computation/param_grid_comp.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/computation/param_grid_comp.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": 34.7575757576, "max_line_length": 78, "alphanum_fraction": 0.6974716652, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7662478944652736}}
{"text": "@testset \"distance\" begin\n    p1 = Position([-180, -90])\n    p2 = Position([180, -90])\n    @test distance(p1, p1) == 0\n\n    p3 = Position([-75.343, 39.984])\n    p4 = Position([-75.534, 39.123])\n\n    @test distance(p3, p4, \"radians\") \u2248 0.015 atol=0.001\n    @test distance(p3, p4, \"degrees\") \u2248 0.87 atol=0.01\n    @test distance(p3, p4, \"miles\") \u2248 60.35 atol=0.01\n\n    @test rhumb_distance(p3, p4, \"miles\") \u2248 60.35 atol=0.01\n    @test rhumb_distance(p3, p4, \"degrees\") \u2248 0.87 atol=0.01\n    @test rhumb_distance(p3, p4, \"nauticalmiles\") \u2248 52.44 atol=0.01\n\n    @test rhumb_distance(Point([-75.343, 39.984]), Point([-75.534, 39.123]), \"miles\") == rhumb_distance(p3, p4, \"miles\")\n\n    a =  Point([-75.833, 39.284])\n    b =  Point([-75.6, 39.984])\n    c =  Point([-75.221, 39.125])\n    d =  Point([-75.9221, 39.27])\n    e =  Point([-75.534, 39.123])\n    f = Point([-75.33, 39.44])\n    target = Point([-75.4, 39.4])\n\n    @test nearestpoint(target, [a, b, c, d, e, f]).coordinates == [-75.33, 39.44]\n\n    @test pnorm_distance(Point([2, 0]), Point([0, 0]), 2) == 2\n    @test pnorm_distance(Point([1, 1]), Point([0, 0]), 1) == 2\n\n    mid = midpoint(Point([0, 10]), Point([0, 0]))\n\n    @test distance(Point([0, 10]), mid) \u2248 distance(Point([0, 0]), mid)\n\n    point = Point([0, 0])\n    line = LineString([[1, 1],[-1, 1]])\n\n    @test point_to_line_distance(point, line, \"miles\") \u2248 69.11854715938406 atol=0.05\n\nend\n", "meta": {"hexsha": "cceaeb4d3aa99ba592cb64675c85c0ba5722fa76", "size": 1398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/distance.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": "test/distance.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": "test/distance.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.2857142857, "max_line_length": 120, "alphanum_fraction": 0.5672389127, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.815232480373843, "lm_q1q2_score": 0.766247887398721}}
{"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.\u03c3 * O.\u03c3 / 2) * O.t) / (O.\u03c3 * \u221aO.t)\n    d2 = d1 - O.\u03c3 * \u221aO.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    \u03f5\u1d62, w\u1d62 = gausshermite(n) # approximates exp(-x\u00b2)\n    \u03f5\u1d62   .*= sqrt(2.)        # Normalize \u03f5\u1d62 and w\u1d62 nodes to approximate standard normal\n    w\u1d62   ./= sqrt(\u03c0)\n\n    return \u03f5\u1d62, w\u1d62\nend\n\n\"\"\"\n```\ngausshermite_expectation(f, \u03bc, \u03c3, n = 10)\ngausshermite_expectation(f, \u03bc, \u03a3, n = 10)\ngausshermite_expectation(f, \u03bc, \u03a3, 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, \u03bc, \u03c3)` calculates the mean of ``N(\\\\mu, \\\\sigma)``\n    using 10-point Gauss-Hermite quadrature.\n- `\u03bc::Number` or `\u03bc::AbstractVector`: mean of the Gaussian random variable/vector.\n- `\u03c3::Number`: standard deviation of the Gaussian random variable.\n- `\u03a3::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, \u03bc::Number, \u03c3::Number, n::Int = 10)\n    \u03f5\u1d62, w\u1d62 = gausshermite(n)\n    \u03f5\u1d62   .*= sqrt(2.)  # Normalize \u03f5\u1d62 and w\u1d62 nodes to approximate standard normal\n    # w\u1d62   ./= sqrt(\u03c0) # This step done later to reduce number of computations\n\n    if \u03bc \u2248 0.\n        return sum([w\u1d62[i] * f(\u03f5\u1d62[i] * \u03c3) for i in 1:n]) / sqrt(\u03c0)\n    else\n        return sum([w\u1d62[i] * f(\u03f5\u1d62[i] * \u03c3 + \u03bc) for i in 1:n]) / sqrt(\u03c0)\n    end\n\nend\n\nfunction gausshermite_expectation(f::Function, \u03bc::AbstractVector{S},\n                                  \u03a3::AbstractVector{<: Number}, n::Int = 10) where {S <: Number}\n\n    d = length(\u03bc)\n    @assert length(\u03a3) == d \"The length of \u03bc and \u03a3 must be the same.\"\n    \u03f5, w = gausshermite(n)\n    \u03f5   .*= sqrt(2.)  # Normalize \u03f5 and w nodes to approximate standard normal\n    # w   ./= sqrt(\u03c0) # 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(\u03bc .\u2248 0.)\n        @simd for CI in allCI\n            feval[CI] = f([\u03f5[i] for i in Tuple(CI)] .* \u03a3)\n        end\n    else\n        @simd for CI in allCI\n            feval[CI] = f([\u03f5[i] for i in Tuple(CI)] .* \u03a3 + \u03bc)\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\u1d62 -> f\u1d62 .* 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))...])) / \u03c0^(d / 2)\nend\n\nfunction gausshermite_expectation(f::Function, \u03bc::AbstractVector{S},\n                                  \u03a3::AbstractVector{<: Number}, ns::AbstractVector{Int}) where {S <: Number}\n\n    d = length(\u03bc)\n    @assert length(\u03a3) == d \"The length of \u03bc and \u03a3 must be the same.\"\n    \u03f5 = Dict{Int, Vector{S}}()\n    w = Dict{Int, Vector{S}}()\n    for i in 1:d\n        \u03f5[i], w[i] = gausshermite(ns[i])\n        \u03f5[i]     .*= sqrt(2.)  # Normalize \u03f5 and w nodes to approximate standard normal\n        # w[i]   ./= sqrt(\u03c0) # 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(\u03bc .\u2248 0.)\n        @simd for CI in allCI\n            feval[CI] = f([\u03f5[n_dim][grid\u1d62] for (n_dim, grid\u1d62) in enumerate(Tuple(CI))] .* \u03a3)\n        end\n    else\n        @simd for CI in allCI\n            feval[CI] = f([\u03f5[n_dim][grid\u1d62] for (n_dim, grid\u1d62) in enumerate(Tuple(CI))] .* \u03a3 + \u03bc)\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\u1d62 -> f\u1d62 .* 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))...])) / \u03c0^(d / 2)\nend\n\nfunction gausshermite_expectation(f::Function, \u03bc::AbstractVector{S},\n                                  \u03a3::AbstractVector{<: Number}, ns::NTuple{N, Int}) where {S<: Number, N}\n\n    d = length(\u03bc)\n    @assert length(\u03a3) == d \"The length of \u03bc and \u03a3 must be the same.\"\n    \u03f5 = Dict{Int, Vector{S}}()\n    w = Dict{Int, Vector{S}}()\n    for i in 1:d\n        \u03f5[i], w[i] = gausshermite(ns[i])\n        \u03f5[i]     .*= sqrt(2.)  # Normalize \u03f5 and w nodes to approximate standard normal\n        # w[i]   ./= sqrt(\u03c0) # 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(\u03bc .\u2248 0.)\n        @simd for CI in allCI\n            feval[CI] = f([\u03f5[n_dim][grid\u1d62] for (n_dim, grid\u1d62) in enumerate(Tuple(CI))] .* \u03a3)\n        end\n    else\n        @simd for CI in allCI\n            feval[CI] = f([\u03f5[n_dim][grid\u1d62] for (n_dim, grid\u1d62) in enumerate(Tuple(CI))] .* \u03a3 + \u03bc)\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\u1d62 -> f\u1d62 .* 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))...])) / \u03c0^(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) = \u2211 c\u1d62 x\u2071 by\nstoring the coefficients c\u1d62 (i \u2208 {0,..., deg(P)}) into a 1-dimensional array of\nnumbers. The **degree** of a polynomial is the highest power of the x\u1d62 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, \u03b2_0, \u03b2, sd_e)\n    k = length(\u03b2)\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 -> \u03b2_0 .+ X * \u03b2, \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^\u00b120 or [1/1_000_000, 1_000_000].\nStrongly recommended when any |coordinate| is outside 2^\u00b124 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": "\nusing LinearAlgebra\nusing SparseArrays\nusing Test\nimport Random\n\nusing JuMP\nusing GLPK\nusing LightGraphs\nusing GraphPlot\nimport SCS\nusing Colors: @colorant_str\n\n\n# TODO explain problem\n\n\nfunction compute_cut_value(g::LightGraphs.AbstractGraph, w::AbstractMatrix, vertex_subset)\n    return sum(w[i,j] for i in vertices(g) for j in neighbors(g, i) if in(i, vertex_subset)  != in(j, vertex_subset))\nend\n\n\ng = SimpleGraph(6)\nadd_edge!(g, 1, 2)\nadd_edge!(g, 1, 5)\nadd_edge!(g, 2, 3)\nadd_edge!(g, 2, 5)\nadd_edge!(g, 3, 4)\nadd_edge!(g, 4, 5)\nadd_edge!(g, 4, 6);\n\nGraphPlot.gplot(g, nodelabel=1:6)\n\n\nw = spzeros(6, 6)\n\nfor e in edges(g)\n   (i, j) = Tuple(e)\n   w[i,j] = 1\nend\n\n\n@test compute_cut_value(g, w, (2, 5, 6)) \u2248 5\n@show compute_cut_value(g, w, (2, 5, 6));\n\n\nn = nv(g)\n\nlinear_max_cut = Model(GLPK.Optimizer)\n\n@variable(linear_max_cut, z[1:n,1:n], Bin)\n@variable(linear_max_cut, x[1:n], Bin)\n@constraint(linear_max_cut, [i = 1:n, j = 1:n; (i, j) in edges(g)], z[i,j] <= x[i] + x[j])\n@constraint(linear_max_cut, [i = 1:n, j = 1:n; (i, j) in edges(g)], z[i,j] <= 2 - (x[i] + x[j]))\n\n@objective(linear_max_cut, Max, dot(w, z))\n\noptimize!(linear_max_cut)\n\n@test objective_value(linear_max_cut) \u2248 6.0\n@show objective_value(linear_max_cut);\n\nx_linear = value.(x)\n@show x_linear;\n@show [(i,j) for i in 1:n-1 for j in i+1:n if JuMP.value.(z)[i,j] > 0.5];\n\n\nnodecolor = [colorant\"lightseagreen\", colorant\"orange\"]\nall_node_colors = [nodecolor[round(Int, xi + 1)]  for xi in x_linear]\nGraphPlot.gplot(g, nodelabel=1:6, nodefillc=all_node_colors)\n\n\nsdp_max_cut = Model(optimizer_with_attributes(SCS.Optimizer, \"verbose\" => 0))\n\n@variable(sdp_max_cut, Y[1:n,1:n] in PSDCone())\n@constraint(sdp_max_cut, [i = 1:n], Y[i,i] == 1)\n@objective(sdp_max_cut, Max, 1/4 * sum(w[i,j] * (1 - Y[i,j]) for i in 1:n for j in 1:n))\n\noptimize!(sdp_max_cut)\n\n@test objective_value(linear_max_cut) >= 6.0\n@show objective_value(linear_max_cut);\n\n\nF = svd(value.(Y))\nU = F.U * Diagonal(sqrt.(F.S))\n\nRandom.seed!(33)\n\n\nx = randn(size(U, 2))\nxhat = sign.(U * x) .> 0\n\n@show collect(zip(round.(Int, x_linear), xhat))\n@test LinearAlgebra.norm1(round.(Int, x_linear) .- xhat) == 0 || LinearAlgebra.norm1(round.(Int, x_linear) .- xhat) == n\n\n\nnodecolor = [colorant\"lightseagreen\", colorant\"orange\"]\nall_node_colors = [nodecolor[xi + 1] for xi in xhat]\nGraphPlot.gplot(g, nodelabel=1:6, nodefillc=all_node_colors)\n\n", "meta": {"hexsha": "01a22dfa285ca86db10389cb9524bda9d84369e8", "size": 2375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modelling/maxcut.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/maxcut.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/maxcut.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": 23.2843137255, "max_line_length": 120, "alphanum_fraction": 0.6774736842, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7662396247319695}}
{"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 \u03b8 by 1/2 of the \u03b8 spacing\n\n        # -------- set parameters\n        d\u03b8   = pc*\u03c0/L\n        wd\u03b8  = wd*d\u03b8\n        \u03b8_sh = shift ? d\u03b8/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        \u03b8    = zeros(nx, nx)\n        logr = zeros(nx, nx)\n\n        # -------- loop over l\n        for l = 0:L-1\n            \u03b8_l        = d\u03b8*l+\u03b8_sh\n            theta[l+1] = \u03b8_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                    \u03b8_pix  = mod(atan(sy, sx)+\u03c0 -\u03b8_l, 2*\u03c0)\n                    \u03b8_good = abs(\u03b8_pix-\u03c0) <= wd\u03b8\n\n                    # If this is a pixel we might use, calculate log2(r)\n                    if \u03b8_good\n                        anggood[y, x] = \u03b8_good\n                        \u03b8[y, x]       = \u03b8_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.((\u03b8[angmask].-\u03c0).*(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                \u0394j    = abs.(logr[angmask].-jrad)\n                rmask = (\u0394j .<= 1/c)\n\n        # -------- radial part\n                F_radial = cos.(\u0394j[rmask] .* (c*\u03c0/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 \u03d5 to filter bank, renormalize \u03c8 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": "using Test, Astro\n\n# solve_kepler(mean_anomaly, eccentricity, desired_accuracy = 1e-6)\n\nprintln(\"Kepler's equation\")\nprint(\"Duffett-Smith PA with your Computer, page 116 \")\n\neccentric_anomaly = solve_kepler(deg2rad(201.7292), 0.016718) |> rad2deg\n@test isapprox(eccentric_anomaly, 201.38, atol=.01)\n\neccentric_anomaly = solve_kepler(deg2rad(43.7172), 0.965) |> rad2deg\n@test isapprox(eccentric_anomaly, 98.41, atol=.01)\n\n# circular orbit\neccentric_anomaly = solve_kepler(deg2rad(60), 0.0) |> rad2deg\n@test isapprox(eccentric_anomaly, 60, atol=.001)\n\nprintln(\"passed\")\n", "meta": {"hexsha": "edeaadb52bdfaf356944a5463f8e4018e9a43651", "size": 568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/kepler-tests.jl", "max_stars_repo_name": "cormullion/Astro.jl", "max_stars_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-05T19:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T21:37:33.000Z", "max_issues_repo_path": "test/kepler-tests.jl", "max_issues_repo_name": "cormullion/Astro.jl", "max_issues_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-02-03T15:20:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-07T19:52:09.000Z", "max_forks_repo_path": "test/kepler-tests.jl", "max_forks_repo_name": "cormullion/Astro.jl", "max_forks_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-10T17:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:09:32.000Z", "avg_line_length": 29.8947368421, "max_line_length": 72, "alphanum_fraction": 0.7623239437, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107896491797, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.766239616264641}}
{"text": "using Test\nusing GreyDecision\n\n# Testing Core Library\n@info \"Testing Grey Numbers and their operations\"\ninclude(\"./testgreynumber.jl\")\n\n@info \"Testing Stats\"\ninclude(\"./teststats.jl\")\n\n@info \"Testing utility functions\"\ninclude(\"./testutility.jl\")\n\n@info \"Testing Random module\"\ninclude(\"./testrandom.jl\")\n\n@info \"Linear Algebra operations\"\ninclude(\"./testlinearalgebra.jl\")\n\n\n#\u00a0Testing Grey Decision Methods\n@info \"Testing topsis\"\ninclude(\"./testtopsis.jl\")\n\n@info \"Testing Vikor\"\ninclude(\"./testvikor.jl\")\n\n@info \"Testing Saw\"\ninclude(\"./testsaw.jl\")\n\n@info \"Testing NDS\"\ninclude(\"./testnds.jl\")\n\n@info \"Testing Moora\"\ninclude(\"./testmoora.jl\")\n\n@info \"Testing electre\"\ninclude(\"./testelectre.jl\")\n\n@info \"Testing WPM\"\ninclude(\"./testwpm.jl\")\n\n@info \"Testing Marcos\"\ninclude(\"./testmarcos.jl\")\n\n@info \"Testing Aras\"\ninclude(\"./testaras.jl\")\n\n\n\n", "meta": {"hexsha": "5d0101ac6a76071a84e48ad88079cff4cd4d6e36", "size": 845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 16.568627451, "max_line_length": 49, "alphanum_fraction": 0.7207100592, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7662036336253075}}
{"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": "# Test file of variance.jl in https://github.com/TheAlgorithms/Julia/tree/main/src/statistics\nusing Test\na = 1:10\n@test var(a) == 5.5\n", "meta": {"hexsha": "59ccc470e30c16169edef7e7071252aea10b192c", "size": 134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/variance.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": "test/variance.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": "test/variance.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": 26.8, "max_line_length": 93, "alphanum_fraction": 0.7313432836, "num_tokens": 44, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7662036314561379}}
{"text": "######### CmdStan sample 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 = (N = 10, y = [0, 1, 0, 1, 0, 0, 0, 0, 0, 1],)\n\n# Keep tmpdir identical across multiple runs to avoid re-compilation\nstanmodel = SampleModel(\n  \"bernoulli\", bernoulli_model; tmpdir = tmpdir,\n  method = StanSample.Sample(adapt=StanSample.Adapt(delta=0.85)))\n\nstan_sample(stanmodel, data=bernoulli_data)\n\n# Convert to an MCMCChains.Chains object\nchns = read_samples(stanmodel)\n\n# Show the same output in DataFrame format\nsdf = read_summary(stanmodel)\n  ", "meta": {"hexsha": "bfd1c3a792ddb287d1fe9654a601eb93ead0bb9c", "size": 717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_basic_runs/test_bernoulli_nt.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_nt.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_nt.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.7272727273, "max_line_length": 68, "alphanum_fraction": 0.6806136681, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7661725894140827}}
{"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 StatsBase, JuMP, GLPK, Test\n\nfunction optimal_price_probabilities(\n    price, demand, capacity; verbose = false)\n    revenue = price .* demand\n    model = Model(with_optimizer(GLPK.Optimizer))\n    @variable(model, x[1:length(price)], lower_bound=0)\n    # Objective: maximize profit\n    @objective(model, Max, revenue' * x)\n    # Constraint: can carry all\n    @constraint(model, sum(x) <= 1)\n    #=\n    for i in 1:length(prices)\n        @constraint(model, x[i] <= demand[i])\n    end\n    =#\n    # Solve problem using MIP solver\n    JuMP.optimize!(model)\n    if verbose\n        println(\"Objective is: \", JuMP.objective_value(model))\n        println(\"Solution is:\")\n        for i in 1:length(price)\n            print(\"x[$i] = \", JuMP.value(x[i]))\n            println(\", revenue = \", price[i] * JuMP.value(x[i]))\n        end\n    end\n    @test JuMP.termination_status(model) == MOI.OPTIMAL\n    @test JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n    Weights(JuMP.value.(x))\nend\n", "meta": {"hexsha": "76ea1718fe01334550518d4ea3519550e2c28a57", "size": 980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "approaches/thomson/optimal_price_probabilities/optimal_price_probabilities.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/thomson/optimal_price_probabilities/optimal_price_probabilities.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/thomson/optimal_price_probabilities/optimal_price_probabilities.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": 31.6129032258, "max_line_length": 64, "alphanum_fraction": 0.6204081633, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7661329221653578}}
{"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\u2090 = 1.0; a=0.5; k\u1d66 = 2.0; k\u1d67=3.0\nprintln(\"Talbot algorithm on FractSLS_Zener creep function\")\nJ\u0302(s) = (1/s)*(c\u2090*s^a + k\u1d66)/(c\u2090*s^a*k\u1d66 + k\u1d67*(c\u2090*s^a + k\u1d66))\nprint(\"  scalar value: \")\n@btime InverseLaplace.talbot(s->(1/s)*(c\u2090*s^a + k\u1d66)/(c\u2090*s^a*k\u1d66 + k\u1d67*(c\u2090*s^a + k\u1d66)), t0)\nprint(\"  vector using talbot.: \")\n@btime InverseLaplace.talbot.(s->(1/s)*(c\u2090*s^a + k\u1d66)/(c\u2090*s^a*k\u1d66 + k\u1d67*(c\u2090*s^a + k\u1d66)), t)\nprint(\"  vector using talbotarr: \")\n@btime InverseLaplace.talbotarr(s -> J\u0302(s), t)\nprintln()\n\nprintln(\"Weeks (80) algorithm on FractSLS_Zener creep function\")\nprint(\"  Initialisation: \")\n@btime InverseLaplace.Weeks(J\u0302,80)\nft = InverseLaplace.Weeks(J\u0302,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,  (\u03b7=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\u2090 = 1.0; a=0.5; k\u1d66 = 2.0; k\u1d67=3.0\nprintln(\"Direct function evaluation\")\n@btime k\u1d66*MittagLeffler.mittleff(a, -(k\u1d66/c\u2090)*t0^a) + k\u1d67\n@btime k\u1d66.*MittagLeffler.mittleff.(a, -(k\u1d66./c\u2090).*t.^a) .+ k\u1d67;\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\u2090 = 1.0, a=0.5, k\u1d66 = 2.0, k\u1d67=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\u2090 = 1.0, a=0.5, k\u1d66 = 2.0, k\u1d67=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 \u03bcs (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 \u03bcs (2634 allocations: 110.75 KiB)\n  Scalar value:   1.616 \u03bcs (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 \u03bcs (2 allocations: 8.09 KiB)\n  33.592 ns (1 allocation: 16 bytes)\n  8.153 \u03bcs (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 \u03bcs (15 allocations: 8.53 KiB)\nFrom the RheoModelClass\n  166.950 ns (4 allocations: 160 bytes)\n  64.459 \u03bcs (2 allocations: 8.11 KiB)\nFrom the RheoModel\n  104.457 ns (1 allocation: 16 bytes)\n  59.557 \u03bcs (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 \u03bcs (71 allocations: 30.80 KiB)\n  1.660 ms (72 allocations: 38.81 KiB)\n  1.636 \u03bcs (1 allocation: 16 bytes)\n  1.610 ms (5 allocations: 8.12 KiB)\n\nFrom the RheoModelClass\n  10.674 \u03bcs (101 allocations: 2.64 KiB)\n  10.721 ms (99102 allocations: 2.47 MiB)\nFrom the RheoModel\n  9.535 \u03bcs (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), \u03f5=0.1, \u03b4=0.01, chisq=$(num(0.1, 0.01, bin)), norm=$(num_wh(0.1, 0.01, bin))\")\n      println(\"bin:$(bin), \u03f5=0.5, \u03b4=0.01, chisq=$(num(0.5, 0.01, bin)), norm=$(num_wh(0.5, 0.01, bin))\")\n      println(\"bin:$(bin), \u03f5=0.5, \u03b4=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\u03c0   1.1447298858494001741 log(big(\u03c0))\n@irrational log2\u03c0  1.8378770664093454836 log(big(2.)*\u03c0)\n@irrational log4\u03c0  2.5310242469692907930 log(big(4.)*\u03c0)\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 \u21a6 0`, `b \u21a6 1`, and `c \u21a6 \u221e`.\n* `LFT(a,aa,b,bb,c,cc)`: creates the function with `a \u21a6 aa`, `b \u21a6 bb`, and `c \u21a6 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": "## based on functions in the tests directory of the MUMPS package\nusing Base.Test\nusing SuperLU\n\nddx(n) = spdiagm((-ones(n), ones(n)),[0,1],n,n+1)\n\nfunction getDivGrad(n1,n2,n3)\n    Div = hcat(kron(speye(n3),kron(speye(n2),ddx(n1))),\n               kron(speye(n3),kron(ddx(n2),speye(n1))),\n               kron(ddx(n3),kron(speye(n2),speye(n1))))\n    Div*Div';\nend\n\ndgcube(n) = getDivGrad(n,n,n)\n\nfor n in (8,16,24)\n    A = dgcube(n)\n    b = randn(size(A,1))\n    xumf = A\\b\n    xslu = NCMat(A)\\b\n    @test_approx_eq (A*xumf) b\n    @test_approx_eq (A*xslu) b    \n    gc()\n    umftimes = [@elapsed A\\b for i in 1:10]\n    gc()\n    slutimes = [@elapsed NCMat(A)\\b for i in 1:10]\n    println(\"Times for solving divgrad system of size $(size(A)), nnz = $(nfilled(A))\")\n    showcompact(umftimes)\n    println()\n    showcompact(slutimes)\n    println()\n    println(\"UMFPACK: mean = $(mean(umftimes)), median = $(median(umftimes))\")\n    println(\"SuperLU: mean = $(mean(slutimes)), median = $(median(slutimes))\")    \nend\n", "meta": {"hexsha": "f498fa037871f58a3874e4e79067b6e4e135eafb", "size": 1008, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/divGradTest.jl", "max_stars_repo_name": "JuliaTagBot/SuperLU.jl", "max_stars_repo_head_hexsha": "a14b4df7d306ce94b0ba488e6797ff598d6a6431", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-06T03:30:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-06T03:30:13.000Z", "max_issues_repo_path": "test/divGradTest.jl", "max_issues_repo_name": "JuliaTagBot/SuperLU.jl", "max_issues_repo_head_hexsha": "a14b4df7d306ce94b0ba488e6797ff598d6a6431", "max_issues_repo_licenses": ["MIT"], "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/divGradTest.jl", "max_forks_repo_name": "JuliaTagBot/SuperLU.jl", "max_forks_repo_head_hexsha": "a14b4df7d306ce94b0ba488e6797ff598d6a6431", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-12-04T06:51:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:04.000Z", "avg_line_length": 28.8, "max_line_length": 87, "alphanum_fraction": 0.6001984127, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7661043672586227}}
{"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": "# Activating Julia environment\nusing Pkg\nPkg.activate(\".\")\n\n# Packages\nusing JuMP, Gurobi, Random, Distributions, LinearAlgebra, DataFrames, Plots\n\nn = 10 # Number of facilities\nm = 50 # Number of customers\n\n# Generating random data (please don't change the seeds.)\nfacilities = 0.6.*rand(MersenneTwister(5), n,2) .+ 0.2;\ncustomers = rand(MersenneTwister(2), m, 2); \nc = [LinearAlgebra.norm(customers[i, :] .- facilities[j, :])[1] for j=1:n, i=1:m];\nf = rand(MersenneTwister(3), n)*1 .+ 5;\ns = rand(MersenneTwister(4), n)*2 .+ 15;\nd = rand(MersenneTwister(5), m)*0.5 .+ 0.75\n\n# P matrix\nR_D = 0.25\nP = [0.2*exp(-1/R_D .*LinearAlgebra.norm(customers[i, :] .- customers[j, :])[1]) for j=1:m, i=1:m];\nP = (P .>= 0.2*exp(-1/R_D .* R_D)) .* P \n\n\"\"\" Plots the solution of the facility location model. \nBlue circles are active facilities with different capacities.\nOrange plus signs are other potential facility locations.\nRays describe connections between facilities and demand nodes. \n\"\"\"\nfunction plot_solution(model, x, y, cost = nothing)\n    plt = scatter(facilities[:, 1], facilities[:, 2], markersize = 0.4 .* s .* value.(x))\n    scatter!(facilities[:, 1], facilities[:, 2], markersize = 0.4 .* s, markershape = :+)\n    for i=1:n\n        for j=1:m\n            if value(y[i,j]) >= 1e-10\n                plot!([customers[j, 1], facilities[i,1]], [customers[j,2], facilities[i,2]], linewidth = value(y[i,j]), legend=false)\n            end\n        end\n    end\n    if cost == nothing\n        scatter!(customers[:, 1], customers[:, 2], markersize = 3*d, \n                title = \"Total cost: $(round(objective_value(model), sigdigits=5))\")\n    else\n        scatter!(customers[:, 1], customers[:, 2], markersize = 3*d, \n        title = \"Total cost: $(round(cost,sigdigits=5))\")\n    end\n    println(\"Facility cost: $(value(sum(f[j] * x[j] for j = 1:n)))\")\n    println(\"Transportation cost: $(value(sum(c[i, j] * y[i, j] for i=1:n, j=1:m)))\")\n    return plt\nend", "meta": {"hexsha": "295b619284797ce08d7c34635de25abb722638e6", "size": 1952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "homeworks/HW4/utils.jl", "max_stars_repo_name": "1ozturkbe/ROdemos", "max_stars_repo_head_hexsha": "1e8f41904658a34b88848ecc45bdaa529b992f2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/HW4/utils.jl", "max_issues_repo_name": "1ozturkbe/ROdemos", "max_issues_repo_head_hexsha": "1e8f41904658a34b88848ecc45bdaa529b992f2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW4/utils.jl", "max_forks_repo_name": "1ozturkbe/ROdemos", "max_forks_repo_head_hexsha": "1e8f41904658a34b88848ecc45bdaa529b992f2a", "max_forks_repo_licenses": ["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.8367346939, "max_line_length": 133, "alphanum_fraction": 0.618852459, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871158, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7661043618253461}}
{"text": "include(\"compute_hermite.jl\")\nfunction hermitekernel(n,x)\n    #Compute the Hermite kernel matrix at points x\n    #including degrees from 0 to n inclusive\n    \n    # # Method 1: Direct Computation\n       phi=compute_hermite(n,x);\n       K=phi'*phi;\n       \n    # # Method 2: Christoffel-Darboux\n    #   phinp1 = compute_hermite(n+1,x,false)\n    #   phin = compute_hermite(n,x,false)\n    #   K = phinp1'*phin*sqrt((n+1)/2)\n    #   x = x[:]*ones(1,length(x))\n    #   K = (K-K')./(x-x')\n\n    K\nend\n", "meta": {"hexsha": "2bb6f6207b2fdc4f8e8b9ec2c079d22ed9231dbf", "size": 494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demos/book/5/hermitekernel.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/hermitekernel.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/hermitekernel.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": 26.0, "max_line_length": 50, "alphanum_fraction": 0.5870445344, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7661043607089452}}
{"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": "\u03b4=0.10; \u03c1=0.15; # Param \nz= \u03c1 + \u03b4 +.02     # Need: z > \u03c1 + \u03b4\nI_SS = (z-\u03c1-\u03b4)/(\u03c1+\u03b4)\nK_SS = I_SS/\u03b4\n\nif 1==1\n    a_0(s;\u03b4=\u03b4) = \u03b4*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-\u03b4)*s), valid_actions())  # valid actions @ state=s \n    \"Transition:\" \n    \u03bc(s,a;\u03b4=\u03b4)      = a +(1-\u03b4)*s     \n    \"reward:\" \n    r(s,a;z=z) = z*s -a -0.5*(a^2)\n    \"discount:\"\n    \u03b2 = 1/(1+\u03c1);\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( \u03bc(s,a) ) ),\n        reward     = (s, a) -> r(s,a),\n        discount   = \u03b2\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 = \u03bc(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": "module NumericalAnalysis\nusing Documenter\nusing ForwardDiff\nusing LinearAlgebra\nusing PyCall\nusing Conda\nusing SymPy\nusing Latexify\n\ninclude(\"basic.jl\")\nexport my_f, derivative_my_f, \u03be, absolute_error, relative_error, NthDerivative, TaylorPolynomials\n\n# Write your package code here.\n\ninclude(\"SEq1.jl\")\n\nexport Bisection, fixed_point, Newton, Secant, FalsePos, ModifiedNewton\n\ninclude(\"Polynomial.jl\")\n\nexport Lagrange, Neville, NDDF, NCSpline, CCSpline\n\ninclude(\"NCalculus.jl\")\n\nexport ThreePoint, FivePoint, Trapezoidal, Simpson, Newton_cotes, Romberg,Gaussian_Quad, SimpsonDoubleIntegral, MutipleIntegralSimple, GaussianDoubleIntegral\n\nend\n", "meta": {"hexsha": "d5a7af4e051c9d26b298446d53c465780e8e08c1", "size": 644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumericalAnalysis.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/NumericalAnalysis.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/NumericalAnalysis.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": 23.0, "max_line_length": 157, "alphanum_fraction": 0.8245341615, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7661043586528755}}
{"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-\u03bbC` and `D+\u03bbB` 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-\u03bbD` and `-B+\u03bbE` 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-\u03bbD` and `-B+\u03bbE` 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": "module YaDistances\n\nusing LinearAlgebra\n\nexport cosine_similarity\n\nconst AVT = AbstractArray{T, N} where {T <: Any, N}\n\nfunction cosine_similarity(v\u2081::AVT, v\u2082::AVT)::Float64 # where {T <: Any}\n\tdot(v\u2081, v\u2082) / (norm(v\u2081) * norm(v\u2082))\nend\n\nend  ## Module\n", "meta": {"hexsha": "651939b53aa79fa5b7f34f966ffacf9b05bcf2ef", "size": 250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Data Science From Scratch/src/YaDistances.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/YaDistances.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/YaDistances.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": 17.8571428571, "max_line_length": 72, "alphanum_fraction": 0.692, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620527726579, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7660693710843193}}
{"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 (\u22c5) (\u2295)`\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 \u22c5 b = b \u22c5 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) \u222a [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\u2207L = L_grad(z, x_init)\n\n\tprintln()\n\tfor i = 1:10\n\t\tr_norm = norm(\u2207L)\n\t\tprintln(\"iter ($i)\")\n\t\tprintln(\"\tgrad norm: $(r_norm)\")\n\t\tr_norm < 1.0e-8 && break\n\n\t\t\u2207\u00b2L = L_hess(z, x_init)\n\n\t\t\u0394 = \u2207\u00b2L \\ \u2207L\n\n\t\t\u03b1 = 1.0\n\t\tz\u0302 = z - \u03b1 * \u0394\n\n\t\t\u2207L\u0302 = L_grad(z\u0302, x_init)\n\n\t\titer = 1\n\t\twhile norm(\u2207L\u0302) > norm(\u2207L)\n\t\t\t\u03b1 *= 0.5\n\t\t\tz\u0302 = z - \u03b1 * \u0394\n\t\t\t\u2207L\u0302 = L_grad(z\u0302, 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\u0302\n\t\t\u2207L = \u2207L\u0302\n\tend\n\n\treturn z, \u2207L, L_hess(z, x_init)\nend\n\nz_sol, \u2207L_sol, \u2207\u00b2L_sol = solve(z0, x_init)\nK_direct = (\u2207\u00b2L_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 \u2248 %.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\u2013338.\n# doi:10.1137/s1064827502419154.\n\n#### LTSA type\nstruct LTSA{T <: Real} <: AbstractDimensionalityReduction\n    k::Int\n    \u03bb::AbstractVector{T}\n    proj::Projection{T}\n\n    LTSA{T}(k::Int, \u03bb::AbstractVector{T}, proj::Projection{T}) where T = new(k, \u03bb, proj)\nend\n\n## properties\noutdim(R::LTSA) = size(R.proj, 1)\neigvals(R::LTSA) = R.\u03bb\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        \u03bc = mean(X[:, II], dims=2)\n        \u03b4_x = X[:, II] .- \u03bc\n\n        # Compute orthogonal basis H of \u03b8'\n        \u03b8_t = svd(\u03b4_x).V[:,1:maxoutdim]\n\n        # Construct alignment matrix\n        G = hcat(S, \u03b8_t)\n        B[II, II] .+= diagm(0 => fill(one(T), k)) .- G*transpose(G)\n    end\n\n    # Align global coordinates\n    \u03bb, V = decompose(B, maxoutdim)\n    return LTSA{T}(k, \u03bb, 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": "\"\"\"\n Tests for  https://link.springer.com/article/10.1007/s10543-007-0130-3 with test problems as in the paper.\n RS1, RS2\n and for https://www.sciencedirect.com/science/article/pii/S0377042706003906\n NON, COM, NON2\n\"\"\"\n\nimport Statistics # for mean values of trajectories\nimport LinearAlgebra # for the normn\nusing StochasticDiffEq\nusing Test\nusing Random\nusing DiffEqDevTools\n#using DiffEqGPU\n\nseed = 137475\n\nfunction prob_func(prob, i, repeat)\n    remake(prob,seed=seeds[i])\nend\n\n\"\"\"\n Test non-commutative noise SDEs (iip)\n\"\"\"\n\n@info \"Non-commutative noise\"\n\nu\u2080 = [0.1,0.1]\nfunction f2!(du,u,p,t)\n  du[1] = 5//4*u[2]-5//4*u[1]\n  du[2] = 1//4*u[1]-1//4*u[2]\nend\nfunction g2!(du,u,p,t)\n  du[1,1] = sqrt(3)/2*(u[1]-u[2])\n  du[1,2] = 1//2*(u[1]+u[2])\n  #du[2,1] = 0\n  du[2,2] = u[1]\nend\ndts = 1 .//2 .^(4:-1:1)\ntspan = (0.0,1.0)\n\nh2(z) = z^2 # E(x_i) = 1/10 exp(1/2t) or E(x_1* x_2) = 1/100 exp(2t)\n\nprob = SDEProblem(f2!,g2!,u\u2080,tspan,noise_rate_prototype=zeros(2,2))\nensemble_prob = EnsembleProblem(prob;\n        output_func = (sol,i) -> (h2(sol[end][1]),false),\n        prob_func = prob_func\n        )\n\nnumtraj = Int(3e7)\nRandom.seed!(seed)\nseeds = rand(UInt, numtraj)\n\nsim = test_convergence(dts,ensemble_prob,RS1(),\n    save_everystep=false,trajectories=numtraj,save_start=false,adaptive=false,\n    weak_timeseries_errors=false,weak_dense_errors=false,\n    expected_value=1//100*exp(2)\n    )\n@test abs(sim.\ud835\udcaaest[:weak_final]-2) < 0.3\nprintln(\"RS1:\", sim.\ud835\udcaaest[:weak_final])\n\nsim = test_convergence(dts,ensemble_prob,RS2(),\n    save_everystep=false,trajectories=numtraj,save_start=false,adaptive=false,\n    weak_timeseries_errors=false,weak_dense_errors=false,\n    expected_value=1//100*exp(2)\n    )\n@test abs(sim.\ud835\udcaaest[:weak_final]-2) < 0.3\nprintln(\"RS2:\", sim.\ud835\udcaaest[:weak_final])\n\nsim = test_convergence(dts,ensemble_prob,NON(),\n    save_everystep=false,trajectories=numtraj,save_start=false,adaptive=false,\n    weak_timeseries_errors=false,weak_dense_errors=false,\n    expected_value=1//100*exp(2)\n    )\n@test abs(sim.\ud835\udcaaest[:weak_final]-2) < 0.3\nprintln(\"NON:\", sim.\ud835\udcaaest[:weak_final])\n\nsim = test_convergence(dts,ensemble_prob,NON2(),\n    save_everystep=false,trajectories=numtraj,save_start=false,adaptive=false,\n    weak_timeseries_errors=false,weak_dense_errors=false,\n    expected_value=1//100*exp(2)\n    )\n@test abs(sim.\ud835\udcaaest[:weak_final]-2) < 0.3\nprintln(\"NON2:\", sim.\ud835\udcaaest[:weak_final])\n\nnumtraj = Int(2e7)\nRandom.seed!(seed)\nseeds = rand(UInt, numtraj)\n\nsim = test_convergence(dts,ensemble_prob,COM(),\n    save_everystep=false,trajectories=numtraj,save_start=false,adaptive=false,\n    weak_timeseries_errors=false,weak_dense_errors=false,\n    expected_value=1//100*exp(2)\n    )\n@test abs(sim.\ud835\udcaaest[:weak_final]-2) < 0.3\nprintln(\"COM:\", sim.\ud835\udcaaest[:weak_final])\n# COM tests are passing; problem might be not hard enough..\n", "meta": {"hexsha": "5a4c42473ab80dad552cfe1751819abc3bd31d0c", "size": 2823, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/weak_convergence/weak_strat_non_diagonal.jl", "max_stars_repo_name": "JuliaDiffEq/StochasticDiffEq", "max_stars_repo_head_hexsha": "63b6bf219cf89bb85794ee268cc99915fd4919fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2016-11-08T01:13:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-14T00:15:33.000Z", "max_issues_repo_path": "test/weak_convergence/weak_strat_non_diagonal.jl", "max_issues_repo_name": "ErikQQY/StochasticDiffEq.jl", "max_issues_repo_head_hexsha": "24cbe4a302a68ff2893fa04dd616242c3e4a41aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186, "max_issues_repo_issues_event_min_datetime": "2016-10-28T07:57:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-15T18:05:59.000Z", "max_forks_repo_path": "test/weak_convergence/weak_strat_non_diagonal.jl", "max_forks_repo_name": "ErikQQY/StochasticDiffEq.jl", "max_forks_repo_head_hexsha": "24cbe4a302a68ff2893fa04dd616242c3e4a41aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2016-10-27T18:22:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T20:28:30.000Z", "avg_line_length": 28.806122449, "max_line_length": 107, "alphanum_fraction": 0.7059865391, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7660089852734356}}
{"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# \u2554\u2550\u2561 4ea41550-9313-11eb-1cdf-df6c5527f80f\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(aside=true)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u00f6lder 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# \u2554\u2550\u2561 f8ba4230-9313-11eb-170c-ab58597826f8\nmd\"\n### Examples\n\"\n\n# \u2554\u2550\u2561 7bd6f898-b86c-4670-96e8-9016666ee14f\nnorm(x,1), norm(x), norm(x,Inf)\n\n# \u2554\u2550\u2561 8e1ced3a-d23d-4f5f-8c65-dc13ab392504\nA=rand(-4:4,5,4)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u00f6lder 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# \u2554\u2550\u2561 8261b5ce-9315-11eb-2378-af63c3eb4c02\nmd\"\n### Random matrix\n\"\n\n# \u2554\u2550\u2561 bb6eee61-c3ee-4b6a-ab44-a638fba776b8\nA\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f55a3c60-9315-11eb-027a-dd008031f6f9\nm,n=size(A)\n\n# \u2554\u2550\u2561 c4a1b888-9497-4eb4-aa1c-23671123f426\n# Equivalence of norms\nopnorm(A,Inf)\\ \u221an,opnorm(A), \u221am*opnorm(A,Inf)\n\n# \u2554\u2550\u2561 b46cbb6f-36f4-4a66-b970-8fe9b0506b6a\nopnorm(A), norm(A), \u221an*opnorm(A)\n\n# \u2554\u2550\u2561 254b2df4-f57e-4284-a735-6fd5d4546c52\nopnorm(A,1)\\ \u221am,opnorm(A), \u221an*opnorm(A,1)\n\n# \u2554\u2550\u2561 09fd0923-1987-4a2e-be28-78451aa2c11a\n# Fact 12\nopnorm(A), \u221a(opnorm(A,1)*opnorm(A,Inf))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c765c02e-9316-11eb-146c-ff5d3ba81323\nx\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ec0746a1-41bd-4d61-9deb-8e227106e592\nbegin\n\t# Fact 15\n\tA\u2081=rand(-4:4,7,5)+im*rand(-4:4,7,5)\n\topnorm(A\u2081), opnorm(A\u2081'), norm(A\u2081), norm(A\u2081')\nend\n\n# \u2554\u2550\u2561 d92799f7-1813-450b-8353-9d03078f69f0\n# Unitary invariance - generate random unitary matrix U\nU=qr(rand(ComplexF64,size(A\u2081)));\n\n# \u2554\u2550\u2561 0d58d4c4-16c6-4a5b-bdbd-f3f599d0d648\nopnorm(A\u2081), opnorm(U.Q*A\u2081), norm(A\u2081), norm(U.Q*A\u2081)\n\n# \u2554\u2550\u2561 b1a90c59-8c3e-4530-83ef-6b3e6c6fa687\nbegin\n\t# Spectral radius\n\tA\u2082=rand(ComplexF64,7,7)\n\tmaximum(abs,eigvals(A\u2082)), opnorm(A\u2082,Inf), opnorm(A\u2082,1), opnorm(A\u2082), norm(A\u2082)\nend\n\n# \u2554\u2550\u2561 31e73f82-93e7-448c-940b-5c9f5e573e5c\nbegin\n\t# Fact 18\n\tB\u2082=A\u2082/(maximum(abs,eigvals(A\u2082))+2)\n\tmaximum(abs,eigvals(B\u2082)), norm(B\u2082^100)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u0161gorin 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# \u2554\u2550\u2561 98fade4c-cdcb-495e-9328-96e86ca8e90e\nmd\"\"\"\n## Examples \n\n### Nondiagonalizable matrix\n\"\"\"\n\n# \u2554\u2550\u2561 8f064645-cf1f-4226-add4-53bc72665bf6\nA\u2083=[-3 7 -1; 6 8 -2; 72 -28 19]\n\n# \u2554\u2550\u2561 568366c7-3eee-4948-a096-7bf87537412d\n# (Right) eigenvectors\nX\u2083=eigen(A\u2083)\n\n# \u2554\u2550\u2561 fe46c02b-74bd-4303-8314-3b6e96b9e51a\ncond(X\u2083.vectors)\n\n# \u2554\u2550\u2561 c48aa813-8012-409f-9b08-ce9805da9cb3\n# Left eigenvectors\nY\u2083=eigen(Matrix(A\u2083'))\n\n# \u2554\u2550\u2561 f0bcadb5-882c-4e46-9079-b36097650435\ncond(Y\u2083.vectors)\n\n# \u2554\u2550\u2561 21b412f3-f460-4f60-8b31-85c839566d62\nbegin\n\t# Try k=2,3\n\tk=1\n\tY\u2083.vectors[:,k]'*A\u2083-Y\u2083.values[k]*Y\u2083.vectors[:,k]'\nend\n\n# \u2554\u2550\u2561 6654b8d5-0c31-4a44-a16a-3f71e714ce31\nbegin\n\t\u0394A\u2083=rand(3,3)/20\n\tB\u2083=A\u2083+\u0394A\u2083\nend\n\n# \u2554\u2550\u2561 3fbcbecd-6e69-49d0-94bf-06a4f6704858\nnorm(\u0394A\u2083)\n\n# \u2554\u2550\u2561 210137a6-1b7b-4741-84d2-9d72e18cd999\nZ\u2083=eigen(B\u2083)\n\n# \u2554\u2550\u2561 e946019f-5e75-4195-8991-da371300e9a2\nbegin\n\t# Fact 2\n\tl=1\n\tZ\u2083.values[l]-X\u2083.values[l], Y\u2083.vectors[:,l]'*\u0394A\u2083*X\u2083.vectors[:,l] /(Y\u2083.vectors[:,l]\u22c5X\u2083.vectors[:,l])\nend\n\n# \u2554\u2550\u2561 4723a4f9-af98-4f2d-8628-0ffc58488e62\nmd\"\"\"\n### Jordan form\n\"\"\"\n\n# \u2554\u2550\u2561 f3d63eb6-0174-458c-aeef-46ed6d62db7f\nbegin\n\tn\u2084=6\n\tc=0.5\n\tJ=Bidiagonal(c*ones(n\u2084),ones(n\u2084-1),'U')\nend\n\n# \u2554\u2550\u2561 b9770791-4fa6-4d3f-9688-ac79b7ae7f22\n# Accurately defined eigenvalues\n\u03bb\u2084=eigvals(J)\n\n# \u2554\u2550\u2561 8112bf44-3146-4b9f-953a-54de6f4c8c5b\n# Only one eigenvector\neigvecs(J)\n\n# \u2554\u2550\u2561 6b26afc1-e427-496e-b9a5-4618551aeede\nbegin\n\tx\u2084=eigvecs(J)[:,1]\n\ty\u2084=eigvecs(J')[:,1]\nend\n\n# \u2554\u2550\u2561 b2a07659-cb08-4c53-99ac-32f817485062\ny\u2084'*J-0.5*y\u2084'\n\n# \u2554\u2550\u2561 989b7c60-c673-4b77-ada8-909db2904fa2\n# Just one perturbed element in the lower left corner\n\u0394J=\u221aeps()*[zeros(n\u2084-1);1]*Matrix(I,1,n\u2084)\n\n# \u2554\u2550\u2561 1da2bfee-6792-4aed-8798-91cc058cd540\n\u03bc\u2084=eigvals(J+\u0394J)\n\n# \u2554\u2550\u2561 a6769e47-59f7-430c-9c20-a121a98f19bf\n# Fact 2\nmaximum(abs,\u03bb\u2084-\u03bc\u2084)\n\n# \u2554\u2550\u2561 fab42c40-7d01-4787-a491-3d37cae1768d\ny\u2084'*\u0394J*x\u2084/(y\u2084\u22c5x\u2084)\n\n# \u2554\u2550\u2561 2f783e6e-5b29-477f-8b45-00461013c66f\nmd\"\"\"\nHowever, since $J+\\Delta J$ is diagonalizable, we can apply Bauer-Fike theorem to it: \n\"\"\"\n\n# \u2554\u2550\u2561 9385e7e0-17d6-4840-98a2-fa69d53ebea3\nY\u2084=eigvecs(J+\u0394J)\n\n# \u2554\u2550\u2561 18e6478b-bb8e-482c-bd02-0c85bca6fc7f\ncond(Y\u2084)\n\n# \u2554\u2550\u2561 ae524f6a-3e64-49ea-92e3-671559f85a5f\nopnorm(inv(Y\u2084)*\u0394J*Y\u2084), cond(Y\u2084)*opnorm(\u0394J)\n\n# \u2554\u2550\u2561 9c0c9fcf-9581-479f-8ec5-d885dd3e6665\nmd\"\"\"\n### Normal matrix\n\"\"\"\n\n# \u2554\u2550\u2561 300e0ddd-3ab0-4803-9528-665e754e54ca\nbegin\n\tn\u2085=5\n\tC=Circulant(rand(-5:5,n\u2085))\nend\n\n# \u2554\u2550\u2561 fdecade7-4d5c-460f-a566-d52868c75ec0\neigvals(Matrix(C))\n\n# \u2554\u2550\u2561 01250371-f8ab-4a0a-b283-ffbcffdc2929\n\u0394C=randn(n\u2085,n\u2085)*0.0001\n\n# \u2554\u2550\u2561 0787f637-44bf-4c5c-b8d2-92df842a91b5\nopnorm(\u0394C), eigvals(C+\u0394C)\n\n# \u2554\u2550\u2561 5645f7ea-50e5-43f7-afc3-1c46fbdd7c5b\nmd\"\"\"\n### Hermitian matrix\n\"\"\"\n\n# \u2554\u2550\u2561 51cd2fc5-e295-4b76-9fd1-fdd2b92ce05a\nbegin\n\t# Random matrix with strong column scaling\n\tm\u2086=10\n\tn\u2086=6\n\tD\u2086=Diagonal(exp.(10*randn(n\u2086)))\n\tA\u2086=cor(randn(m\u2086,n\u2086)*D\u2086)\nend\n\n# \u2554\u2550\u2561 bc5a0ee0-931f-11eb-204c-b9e03584c787\nD\u2086\n\n# \u2554\u2550\u2561 1eb12479-0662-410b-9569-c4e8939a291f\n\u0394A\u2086=cor(rand(m\u2086,n\u2086)*D\u2086)*1e-5\n\n# \u2554\u2550\u2561 821f6b8b-0e12-404b-b1dc-57d809ebf79b\nbegin\n\t\u03bb\u2086,U\u2086=eigen(A\u2086) \n\t\u03bc\u2086=eigvals(A\u2086+\u0394A\u2086)\n\t[\u03bb\u2086 \u03bc\u2086]\nend\n\n# \u2554\u2550\u2561 ac3d3677-1160-4a79-a25f-8faa7fd89940\nnorm(\u0394A\u2086)\n\n# \u2554\u2550\u2561 f4051f63-a0d3-4b43-8c61-2bbd08338a72\n# ?round\n\n# \u2554\u2550\u2561 612870ba-75df-4729-a16e-432f70707fb4\nbegin\n\t# Residual bounds - how close is \u03bc, y to \u03bb[2],X[:,2]\n\tk\u2086=3\n\t\u03b6\u2086=round(\u03bb\u2086[k\u2086],sigdigits=2)\n\ty\u2086=round.(U\u2086[:,k\u2086],sigdigits=2)\n\tnormalize!(y\u2086)\nend\n\n# \u2554\u2550\u2561 3ba55b4b-5445-48a3-b327-b7d3af28397a\n\u03b6\u2086\n\n# \u2554\u2550\u2561 6f3da676-c953-4d23-8b9a-bb62b8b8ac94\n# Fact 9\nr\u2086=A\u2086*y\u2086-\u03b6\u2086*y\u2086\n\n# \u2554\u2550\u2561 886ce4f8-73a0-4b57-8d5e-082bcfc1f9aa\nminimum(abs,\u03b6\u2086.-\u03bb\u2086), norm(r\u2086)\n\n# \u2554\u2550\u2561 82a4adaa-3663-4200-9f15-d09fd4cd0259\nbegin\n\t# Fact 10 - \u03bc is Rayleigh quotient\n\t\u03be\u2086=y\u2086\u22c5(A\u2086*y\u2086)\n\t\u03c1\u2086=A\u2086*y\u2086-\u03be\u2086*y\u2086\nend\n\n# \u2554\u2550\u2561 b1025690-4244-4933-9693-9bbd3ad8aedb\n\u03b7\u2086=min(abs(\u03be\u2086-\u03bb\u2086[k\u2086-1]),abs(\u03be\u2086-\u03bb\u2086[k\u2086+1]))\n\n# \u2554\u2550\u2561 5e69cab3-712c-4754-b6b1-579bc3c8e114\n\u03be\u2086-\u03bb\u2086[k\u2086], norm(\u03c1\u2086)^2/\u03b7\u2086\n\n# \u2554\u2550\u2561 3792c478-fbaa-4683-849a-ca0d0cb751f3\nbegin\n\t# Eigenvector bound\n\t# cos(\u03b8)\n\tcos\u03b8=dot(y\u2086,U\u2086[:,k\u2086])\n\t# sin(\u03b8)\n\tsin\u03b8=sqrt(1-cos\u03b8^2)\n\tsin\u03b8,norm(\u03c1\u2086)/\u03b7\u2086\nend\n\n# \u2554\u2550\u2561 0dd080f1-575d-43e0-9285-20279f390d2f\nbegin\n\t# Residual bounds - Fact 13\n\tQ\u2086=round.(U\u2086[:,1:3],sigdigits=2)\n\t# Orthogonalize\n\tF=qr(Q\u2086)\n\tX=Matrix(F.Q)\n\t# Make sure M\u2086 is hermitian\n\tM\u2086=Hermitian(X'*A\u2086*X)\n\t\u03bc\u2098=eigvals(M\u2086)\n\tR\u2086=A\u2086*X-X*M\u2086\nend\n\n# \u2554\u2550\u2561 ea07eea3-bab7-4add-90cc-43acd7c2ec89\n\u03bb\u2086\n\n# \u2554\u2550\u2561 53f2860a-db33-49cd-b95e-3086f76c2592\n\u03bc\u2098\n\n# \u2554\u2550\u2561 8cdffcc2-c8c1-410e-95db-6327931782a1\nM\u2086\n\n# \u2554\u2550\u2561 0e871e72-47ee-4492-9f73-fcfd2ef1aada\n# The entries of \u03bc are not ordered - which algorithm was called?\nissymmetric(M\u2086)\n\n# \u2554\u2550\u2561 108f73bc-b1cf-47ed-80f0-281cb5ebd048\n\u03b7\u2098=\u03bb\u2086[4]-\u03bb\u2086[3]\n\n# \u2554\u2550\u2561 dbc219f9-9fcf-4aac-b7d5-feb8fcafe3e9\nnorm(\u03bb\u2086[1:3]-\u03bc\u2098), norm(R\u2086)^2/\u03b7\u2098\n\n# \u2554\u2550\u2561 7cae5501-8a51-4874-8b23-5825f79624e3\nA\u2086\n\n# \u2554\u2550\u2561 7cb49041-f326-4b2c-90f8-99c4d58178eb\nbegin\n\t# Fact 15\n\tM\u2087=A\u2086[1:3,1:3]\n\tH=A\u2086[4:6,4:6]\n\tE=A\u2086[4:6,1:3]\n\t# Block-diagonal matrix\n\tB\u2087=cat(M\u2087,H,dims=(1,2))\nend\n\n# \u2554\u2550\u2561 75c00141-e691-4f9c-8b7a-ed262b88a62d\nbegin\n\t\u03b7\u2087=minimum(abs,eigvals(M\u2087)-eigvals(H))\n\t\u03bc\u2087=eigvals(B\u2087)\n\t[\u03bb\u2086 \u03bc\u2087]\nend\n\n# \u2554\u2550\u2561 433a0652-912f-4f59-8494-4d0381e22115\n2*norm(E)^2/(\u03b7\u2087+\u221a(\u03b7\u2087^2+4*norm(E)^2))\n\n# \u2554\u2550\u2561 ad6ca597-65b2-4403-a6aa-1394399c3ed8\nbegin\n\t# Eigenspace bounds - Fact 16\n\tB\u2086=A\u2086+\u0394A\u2086\n\t\u03bc,V=eigen(B\u2086)\nend\n\n# \u2554\u2550\u2561 4727c0ba-124e-41a4-861a-57eb5a6d849d\nbegin\n\t# sin(\u0398(U[:,1:3],V[:,1:3]))\n\tX\u2086=U\u2086[:,1:3]\n\tQ=V[:,1:3]\n\tcos\u03b8\u2086=svdvals(\u221a(Q'*Q)*Q'*X\u2086*\u221a(X\u2086'*X\u2086))\n\tsin\u03b8\u2086=sqrt.(1 .-cos\u03b8\u2086.^2)\nend\n\n# \u2554\u2550\u2561 dd00cbef-e1f6-43bc-95b0-1b6694c23583\n# Bound\nM\u2088=Q'*A\u2086*Q\n\n# \u2554\u2550\u2561 99f44a10-b3e1-442c-a042-b2f0afad1797\nR\u2088=A\u2086*Q-Q*M\u2088\n\n# \u2554\u2550\u2561 b6f8f48e-2e80-4999-95a9-701d491411bd\neigvals(M\u2088), \u03bb\u2086\n\n# \u2554\u2550\u2561 7a6554bb-0518-4068-9784-678f846d3b3f\nbegin\n\t\u03b7\u2088=abs(eigvals(M\u2088)[3]-\u03bb\u2086[4])\n\tnorm(sin\u03b8\u2086), norm(R\u2088)/\u03b7\u2088\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25004ea41550-9313-11eb-1cdf-df6c5527f80f\n# \u255f\u25007d3ed16e-50ea-4ede-b968-e32baa56f76f\n# \u255f\u2500da0d7094-fa3e-4f1e-a6f1-9d1b9316f65a\n# \u255f\u2500f8ba4230-9313-11eb-170c-ab58597826f8\n# \u2560\u25504c360009-f01e-45bb-b458-29b15f8cac8f\n# \u2560\u25507bd6f898-b86c-4670-96e8-9016666ee14f\n# \u2560\u25508e1ced3a-d23d-4f5f-8c65-dc13ab392504\n# \u2560\u2550d9ef7b4b-4954-464a-96ac-e3f49800e0b7\n# \u255f\u250090fcd9f5-d98c-4db6-bf30-21e377209681\n# \u255f\u25008261b5ce-9315-11eb-2378-af63c3eb4c02\n# \u2560\u2550bb6eee61-c3ee-4b6a-ab44-a638fba776b8\n# \u2560\u2550060b8d2f-e6f3-4625-9cf6-d4cc504145fa\n# \u2560\u2550f55a3c60-9315-11eb-027a-dd008031f6f9\n# \u2560\u2550c4a1b888-9497-4eb4-aa1c-23671123f426\n# \u2560\u2550b46cbb6f-36f4-4a66-b970-8fe9b0506b6a\n# \u2560\u2550254b2df4-f57e-4284-a735-6fd5d4546c52\n# \u2560\u255009fd0923-1987-4a2e-be28-78451aa2c11a\n# \u2560\u2550dcba6892-b90e-41ad-8d58-53e72d40e882\n# \u2560\u2550c765c02e-9316-11eb-146c-ff5d3ba81323\n# \u2560\u2550d948741f-6748-44d7-ae8c-cf074f7549bd\n# \u2560\u2550ec0746a1-41bd-4d61-9deb-8e227106e592\n# \u2560\u2550d92799f7-1813-450b-8353-9d03078f69f0\n# \u2560\u25500d58d4c4-16c6-4a5b-bdbd-f3f599d0d648\n# \u2560\u2550b1a90c59-8c3e-4530-83ef-6b3e6c6fa687\n# \u2560\u255031e73f82-93e7-448c-940b-5c9f5e573e5c\n# \u255f\u2500909033d9-bb27-4f0e-b07d-574f7fcee700\n# \u255f\u25007ef162c0-5c80-4e96-bcc3-125b302b1d5e\n# \u255f\u25003c8f71a5-0c2f-43a0-bf71-db9df707f84e\n# \u255f\u250098fade4c-cdcb-495e-9328-96e86ca8e90e\n# \u2560\u25508f064645-cf1f-4226-add4-53bc72665bf6\n# \u2560\u2550568366c7-3eee-4948-a096-7bf87537412d\n# \u2560\u2550fe46c02b-74bd-4303-8314-3b6e96b9e51a\n# \u2560\u2550c48aa813-8012-409f-9b08-ce9805da9cb3\n# \u2560\u2550f0bcadb5-882c-4e46-9079-b36097650435\n# \u2560\u255021b412f3-f460-4f60-8b31-85c839566d62\n# \u2560\u25506654b8d5-0c31-4a44-a16a-3f71e714ce31\n# \u2560\u25503fbcbecd-6e69-49d0-94bf-06a4f6704858\n# \u2560\u2550210137a6-1b7b-4741-84d2-9d72e18cd999\n# \u255f\u2500e946019f-5e75-4195-8991-da371300e9a2\n# \u255f\u25004723a4f9-af98-4f2d-8628-0ffc58488e62\n# \u2560\u2550f3d63eb6-0174-458c-aeef-46ed6d62db7f\n# \u2560\u2550b9770791-4fa6-4d3f-9688-ac79b7ae7f22\n# \u2560\u25508112bf44-3146-4b9f-953a-54de6f4c8c5b\n# \u2560\u25506b26afc1-e427-496e-b9a5-4618551aeede\n# \u2560\u2550b2a07659-cb08-4c53-99ac-32f817485062\n# \u2560\u2550989b7c60-c673-4b77-ada8-909db2904fa2\n# \u2560\u25501da2bfee-6792-4aed-8798-91cc058cd540\n# \u2560\u2550a6769e47-59f7-430c-9c20-a121a98f19bf\n# \u2560\u2550fab42c40-7d01-4787-a491-3d37cae1768d\n# \u255f\u25002f783e6e-5b29-477f-8b45-00461013c66f\n# \u2560\u25509385e7e0-17d6-4840-98a2-fa69d53ebea3\n# \u2560\u255018e6478b-bb8e-482c-bd02-0c85bca6fc7f\n# \u2560\u2550ae524f6a-3e64-49ea-92e3-671559f85a5f\n# \u255f\u25009c0c9fcf-9581-479f-8ec5-d885dd3e6665\n# \u2560\u2550300e0ddd-3ab0-4803-9528-665e754e54ca\n# \u2560\u2550fdecade7-4d5c-460f-a566-d52868c75ec0\n# \u2560\u255001250371-f8ab-4a0a-b283-ffbcffdc2929\n# \u2560\u25500787f637-44bf-4c5c-b8d2-92df842a91b5\n# \u255f\u25005645f7ea-50e5-43f7-afc3-1c46fbdd7c5b\n# \u2560\u255051cd2fc5-e295-4b76-9fd1-fdd2b92ce05a\n# \u2560\u2550bc5a0ee0-931f-11eb-204c-b9e03584c787\n# \u2560\u25501eb12479-0662-410b-9569-c4e8939a291f\n# \u2560\u2550821f6b8b-0e12-404b-b1dc-57d809ebf79b\n# \u2560\u2550ac3d3677-1160-4a79-a25f-8faa7fd89940\n# \u2560\u2550f4051f63-a0d3-4b43-8c61-2bbd08338a72\n# \u2560\u2550612870ba-75df-4729-a16e-432f70707fb4\n# \u2560\u25503ba55b4b-5445-48a3-b327-b7d3af28397a\n# \u2560\u25506f3da676-c953-4d23-8b9a-bb62b8b8ac94\n# \u2560\u2550886ce4f8-73a0-4b57-8d5e-082bcfc1f9aa\n# \u2560\u255082a4adaa-3663-4200-9f15-d09fd4cd0259\n# \u2560\u2550b1025690-4244-4933-9693-9bbd3ad8aedb\n# \u2560\u25505e69cab3-712c-4754-b6b1-579bc3c8e114\n# \u2560\u25503792c478-fbaa-4683-849a-ca0d0cb751f3\n# \u2560\u25500dd080f1-575d-43e0-9285-20279f390d2f\n# \u2560\u2550ea07eea3-bab7-4add-90cc-43acd7c2ec89\n# \u2560\u255053f2860a-db33-49cd-b95e-3086f76c2592\n# \u2560\u25508cdffcc2-c8c1-410e-95db-6327931782a1\n# \u2560\u25500e871e72-47ee-4492-9f73-fcfd2ef1aada\n# \u2560\u2550108f73bc-b1cf-47ed-80f0-281cb5ebd048\n# \u2560\u2550dbc219f9-9fcf-4aac-b7d5-feb8fcafe3e9\n# \u2560\u25507cae5501-8a51-4874-8b23-5825f79624e3\n# \u2560\u25507cb49041-f326-4b2c-90f8-99c4d58178eb\n# \u2560\u255075c00141-e691-4f9c-8b7a-ed262b88a62d\n# \u2560\u2550433a0652-912f-4f59-8494-4d0381e22115\n# \u2560\u2550ad6ca597-65b2-4403-a6aa-1394399c3ed8\n# \u2560\u25504727c0ba-124e-41a4-861a-57eb5a6d849d\n# \u2560\u2550dd00cbef-e1f6-43bc-95b0-1b6694c23583\n# \u2560\u255099f44a10-b3e1-442c-a042-b2f0afad1797\n# \u2560\u2550b6f8f48e-2e80-4999-95a9-701d491411bd\n# \u2560\u25507a6554bb-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\u0107 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\u010detak 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\u0107em poretku i \n**\"r\"** za sortiranje u rastu\u0107em poretku\n\"\"\"\nfunction bucketSort(X::Array{Int64},smer::String=\"r\")\n    if smer != \"r\" && smer != \"o\"\n        error(\"Pogre\u0161an 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\u0107na 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 \u2248 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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.15\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.15\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u25500e5aed16-3b2f-11eb-2f7c-01f450cc5336\n# \u2560\u25500e5b22c2-3b2f-11eb-2895-7d6e7267e6b6\n# \u255f\u2500475ff888-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 \u03b4=4m*M/(m+M)^2 #maximum fraction of energy transferable\neq2=@equ Te-Tgas=2qe*E^2/(3\u03b4*me*vm^2) #\u221dp^-2, steady state\n\n#B\nb1=@equ d*N\u0307=N\u0307*\u03b1*d*x\nb2=@equ N\u0307=N\u03070*exp(\u03b1*x)\nb3=@equ i=N\u03070*e*exp(\u03b1*d) # =i0*exp(\u03b1*d) #current leaving the anode #should e be qe?\nb4=@equ i=i0*exp(\u03b1*d)/(1-\u03b3*(exp(\u03b1*d)-1)) #sum of avalances\nb5=@equ \u03b3*exp(\u03b1*d)=\u03b3+1 #1-\u03b3*(exp(\u03b1*d)-1)=0 #breakdown criterion\n\n#C\nc1=@equ \u03b1=A*p*exp(-B*p/E)\nc1b=@equ \u03b1=1/\u03bb*exp(-\u03f5i/(e*E*\u03bb))\nc1c=@equ \u03b1=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/\u03b3))) #breakdown voltage\nc3b=@equ VB=B*p*d/(log(C*p*d))\nc3c=@equ C=A/log(1+1/\u03b3)\nc4=@equ Der(nj,t)+Dot(\u2207,\u0393j)=Sj\nc5=@equ Sj=ne*\u03b1*ue\nc6=@equ E=-\u2207V\nc7=@equ \u2207^2*V=0\n#boundary conditions\nc8=@equ n*\u0393i_anode=0 #ions\nc9=@equ n*\u0393e_cathode=-\u03b3se*n*\u0393i_cathode\n\n#D\nd1=@equ \u0393i=ni*c\u0304i/4 #ion thermal flux\nd1b=@equ c\u0304i=sqrt(8*e*Ti/(pi*mi))\nd2=@equ \u0393e=ne*c\u0304e/4 #electron thermal flux\nd2b=@equ c\u0304e=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/\u03f50 #Poisson's euqation in sheath\ne6=@equ ub=sqrt(e*Te/M)#\u2264us #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 \u03f5i=e*Te/2*log(M/2.3m)#~5.2e*Te #Ion energy to a wall\n\n\n#Week 7\n#B\nb1=@equ \u0394Ef=\u0394E\u03b1+\u0394En\nb2=@equ RDT*\u0394Ef=nD*nT*\u03c3DT*v*\u0394Ef\t#fusion power density, depends on v\nb3=@equ nD*nT*\u03c3v*\u0394Ef=1/4*n^2*\u03c3v*\u0394Ef #whole plasma, avg \u03c3v\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/\u03c4E #losses\nb6=@equ Q=Pf/Pin\nb7=@equ f\u03b1=P\u03b1/(P\u03b1+Pin)\nb8=@equ QE=(Pout_E-Pin_E)/Pin_E #conversion efficiency\nb8b=@equ Pin_E=Pin/\u03b7e\nb8c=@equ Pout_E=\u03b7t*(Pf+Pin)\n\n#C\nc1=@equ El=1/((\u03f5l*\u03f5th)^3*\u03f5c^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/\u03bbtot)\n\n#E\ne1=@equ \u0393r=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\u20135596\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    \u03bb::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.\u03bb\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        \u03bc = mean(VX, dims=2)\n        N = VX .- \u03bc\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    \u03bb, V = decompose(transpose(W)*W, maxoutdim)\n    return HLLE{nntype, T}(\u03bb, 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 \u03b8 (elevation angle) and \u03d5 (azimuth angle)\n# Fields\n$(DocStringExtensions.FIELDS)\n\"\"\"\nstruct dirVector{FT}\n    \u03b8::FT\n    \u03d5::FT\nend\n\n\"\"\"\n    dirVector_\u03bc{FT}\nStruct for spherical coordinate directions in \u03b8 (elevation angle) and \u03d5 (azimuth angle)\"\n# Fields\n$(DocStringExtensions.FIELDS)\n\"\"\"\nstruct dirVector_\u03bc{FT}\n    \u03bc::FT\n    \u03d5::FT\nend \n\n# Define dot product for the directional vector in spherical coordinates:\nLinearAlgebra.dot(\u03a9\u2081::dirVector, \u03a9\u2082::dirVector) = cos(\u03a9\u2081.\u03b8) * cos(\u03a9\u2082.\u03b8) + sin(\u03a9\u2081.\u03b8) * sin(\u03a9\u2082.\u03b8) * cos(\u03a9\u2082.\u03d5 - \u03a9\u2081.\u03d5)\n\n# Define dot product for the directional vector in spherical coordinates:\nLinearAlgebra.dot(\u03a9\u2081::dirVector_\u03bc, \u03a9\u2082::dirVector_\u03bc) = \u03a9\u2081.\u03bc * \u03a9\u2082.\u03bc + sqrt(1-\u03a9\u2081.\u03bc^2)  * sqrt(1-\u03a9\u2082.\u03bc^2) * cos(\u03a9\u2082.\u03d5 - \u03a9\u2081.\u03d5)\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 `\u0394t\u1d62`.\n\"\"\"\nfunction kepler(r::AbstractVector, v::AbstractVector, \u03bc::Number, \u0394t::Number = period(semimajor_axis(r,v,\u03bc), \u03bc); tol=1e-6, max_iter=100) \n\n    e, a, i, \u03a9, \u03c9, \u03bd = keplerian(r, v, \u03bc)\n    T = period(a, \u03bc)\n    conic_section = conic(e)\n\n    # Guess \u03c7\u2080\n    if conic_section == Hyperbolic\n        \u03c7\u2080 = sign(\u0394t) * \u221a(-a) * log(\u212f, (-2 * \u03bc / a * \u0394t) / (r \u22c5 v + (sign(\u0394t) * \u221a(-\u03bc * a) * (1 - norm(r) / a))))\n    elseif conic_section == Parabolic\n        \u03c7\u2080 = \u221a(a) * tan(\u03bd / 2)\n    else\n        \u0394t = mod(\u0394t, T)\n        \u03c7\u2080 = \u221a(\u03bc) * \u0394t / a\n    end\n\n    # Iteratively solve for \u03c7\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    \u03c7\u2099, r\u2099, \u03c8, C\u2082, C\u2083 = \u03c7\u2096(\u03c7\u2080, \u0394t, r, v, a, \u03bc, tol=tol, max_iter=max_iter)\n\n    # Convert to a Orbit\n    f = 1 - \u03c7\u2099^2 / norm(r) * C\u2082\n    f\u0307 = \u221a(\u03bc) / (norm(r) * r\u2099) * \u03c7\u2099 * (\u03c8 * C\u2083 - 1)\n    g = \u0394t - (\u03c7\u2099^3 / \u221a(\u03bc)) * C\u2083\n    g\u0307 = 1 - (\u03c7\u2099^2 / r\u2099) * C\u2082\n\n    return ((f * r) .+ (g * v), (f\u0307 * r) .+ (g\u0307 * v))\nend\n\n\nfunction \u03c7\u2096(\u03c7\u2099, \u0394t, r\u1d62\u2080, v\u1d62\u2080, a, \u03bc; iter=1, tol=1e-14, max_iter=100)\n    \n    r\u2080 = norm(r\u1d62\u2080)\n    \u03c8 = upreferred(\u03c7\u2099^2 / a)\n\n    if \u03c8 > tol\n        C\u2082 = (1 - cos(\u221a(\u03c8))) /  \u03c8\n        C\u2083 = (\u221a(\u03c8) - sin(\u221a(\u03c8))) / \u221a(\u03c8^3)\n    elseif \u03c8 < -tol\n        C\u2082 = (1 - cosh(\u221a(-\u03c8))) / \u03c8\n        C\u2083 = (sinh(\u221a(-\u03c8)) - \u221a(-\u03c8)) / \u221a((-\u03c8)^3)\n    else\n        C\u2082 = 1.0 / 2.0\n        C\u2083 = 1.0 / 6.0\n    end\n\n    r = \u03c7\u2099^2 * C\u2082 + (r\u1d62\u2080 \u22c5 v\u1d62\u2080) * \u03c7\u2099 / \u221a(\u03bc) * (1 - \u03c8*C\u2083) + r\u2080 * (1 - \u03c8 * C\u2082)\n    \u03c7\u2099\u208a\u2081 = \u03c7\u2099 + ((\u221a(\u03bc) * \u0394t - \u03c7\u2099^3 * C\u2083 - (r\u1d62\u2080 \u22c5 v\u1d62\u2080) / \u221a(\u03bc) * \u03c7\u2099^2 * C\u2082 - r\u2080 * \u03c7\u2099 * (1 - \u03c8 * C\u2083)) / r)\n\n    if iter > max_iter\n        @error \"Failed to converge!\"\n        return \u03c7\u2099, r, \u03c8, C\u2082, C\u2083\n    elseif abs(\u03c7\u2099\u208a\u2081 - \u03c7\u2099) < oneunit(\u03c7\u2099) * tol\n        return  \u03c7\u2099, r, \u03c8, C\u2082, C\u2083\n    else\n        return \u03c7\u2096(\u03c7\u2099\u208a\u2081, \u0394t, r\u1d62\u2080, v\u1d62\u2080, a, \u03bc; 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                                \u2208 \u211d\r\n########################################\r\n\r\n# For each layer weight matrix\r\n# J\u2113\u2081 = \u03bb \u2211||W\u1d62\u2c7c||    \u2200 W\u1d62\u2c7c\r\nfunction \u21131_reg_cost(net)\r\n    J\u1d63 = zero(net.dtype)\r\n    for \u2113 in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(\u2113) <: PoolLayer && continue\r\n\r\n        # \u2211||W\u1d62\u2c7c||\r\n        J\u1d63 += sumabs(\u2113.W)\r\n    end\r\n\r\n    # \u03bb \u2211||W\u1d62\u2c7c||\r\n    J\u1d63 *= net.\u03bb\r\nend\r\n\r\n########################################\r\n# L1 Gradient                            \u2208 \u211d^ 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 \u221a(x\u00b2+\u03f5). This would make the function smooth around x=0.\r\n=#\r\n# \u2202J\u2113\u2082/\u2202W\u1d62\u2c7c = \u03bb sign(W\u1d62\u2c7c)    \u2200 W\u1d62\u2c7c\r\n# Added to the gradient in-place\r\nfunction \u21131_reg_grad!(net)\r\n    for \u2113 in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(\u2113) <: PoolLayer && continue\r\n\r\n        # \u2207W := \u03bb sign(W) + \u2207W\r\n        BLAS.axpy!(net.\u03bb, sign(\u2113.W), \u2113.\u2207W)\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                                \u2208 \u211d\r\n########################################\r\n\r\n# J\u2113\u2082 = (\u03bb/2) \u2211||W\u1d62\u2c7c||\u00b2    \u2200 W\u1d62\u2c7c\r\nfunction \u21132_reg_cost(net)\r\n    J\u1d63 = zero(net.dtype)\r\n    for \u2113 in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(\u2113) <: PoolLayer && continue\r\n\r\n        # \u2211||W\u1d62\u2c7c||\u00b2\r\n        J\u1d63 += sumabs2(\u2113.W)\r\n    end\r\n\r\n    # (\u03bb/2) \u2211||W\u1d62\u2c7c||\u00b2\r\n    J\u1d63 *= net.\u03bb * net.dtype(0.5)\r\nend\r\n\r\n########################################\r\n# L2 Gradient                            \u2208 \u211d^ num_feats\r\n########################################\r\n\r\n# \u2202J\u2113\u2082/\u2202W\u1d62\u2c7c = \u03bb W\u1d62\u2c7c    \u2200 W\u1d62\u2c7c\r\n# Added to the gradient in-place\r\nfunction \u21132_reg_grad!(net)\r\n    for \u2113 in net.layers[2:end]\r\n\r\n        # No parameters in pooling layers\r\n        typeof(\u2113) <: PoolLayer && continue\r\n\r\n        # \u2207W := \u03bb W + \u2207W\r\n        BLAS.axpy!(net.\u03bb, \u2113.W, \u2113.\u2207W)\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 => \u21131_reg_cost, :L2 => \u21132_reg_cost)\r\nreg_grad_dict = Dict{Symbol, Function}(:L1 => \u21131_reg_grad!, :L2 => \u21132_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                          \u2208 \u211d\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\u0302\r\nfunction kl_div_sum{F<:AbstractFloat}(p\u0302::Vector{F}, p::F)\r\n    s = F(0)\r\n    for j in eachindex(p\u0302)\r\n        @inbounds s += (p * log(p / p\u0302[j]) +\r\n                        (F(1) - p) * log((F(1) - p) / (F(1) - p\u0302[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 \u2113 in net.layers[2:end-1]\r\n\r\n        # Only for sparse encoder layers\r\n        !(typeof(\u2113) <: SparseEncoderLayer) && continue\r\n\r\n        # \u03b2 \u2211\u02e2 KL(p || p\u0302)\r\n        J += \u2113.\u03b2 * kl_div_sum(\u2113.p\u0302, \u2113.p)\r\n    end\r\n    return J\r\nend\r\n\r\n########################################\r\n# Sparsity Gradient                      \u2208 \u211d^ num_feats\r\n########################################\r\n\r\nfunction delta_sparse!{F<:AbstractFloat}(\u0394::Array{F}, spgrad::Vector{F},\r\n                                         p\u0302::Vector{F}, p::F, \u03b2::F, m::F)\r\n    for j in eachindex(p\u0302)\r\n        @inbounds spgrad[j] = (- p / p\u0302[j] + (F(1) - p) / (F(1) - p\u0302[j])) * \u03b2 / m\r\n    end\r\n    broadcast!(+, \u0394, spgrad, \u0394)\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": "function corrp_test()\n\tx = [1.,2,3,5,10,22,0,1,-3,4,0,8,10,3,4,5,5,5,-10,0];\n\ty = [2.,3,4,5,7,10,10,11,-3,4,1,-1,0,1,2,3,4,4,4,-5];\n\tr1,p1 = corrp(x,y);\n\t# compare to Matlab results ([r,p] = corr(x',y'))\n\t@test r1 \u2248 0.2923 atol = .0001\n\t@test p1 \u2248 0.2111 atol = .0001\n\n\tx[2] = NaN;\n\ty[[2,4]] .= NaN;\n\tr2,p2 = corrp(x,y);\n\t@test r2 \u2248 0.2892 atol = .0001\n\t@test p2 \u2248 0.2444 atol = .0001\nend\n\ncorrp_test();\n", "meta": {"hexsha": "1ac7d4c88a3189dac4efca16f825e929aa5a702f", "size": 404, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/othertest_test.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": "test/othertest_test.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": "test/othertest_test.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": 23.7647058824, "max_line_length": 54, "alphanum_fraction": 0.5420792079, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731115849662, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7659586566132873}}
{"text": "import PolynomialApproximations: Remez\nusing SpecialFunctions: erfcx\nusing PyPlot\n\nT = Float64\n\nfunction g(y::T) where T <: AbstractFloat\n    if -one(T) \u2264 y \u2264 -one(T) + eps(T)\n        return one(T)\n    elseif one(T) - eps(T) \u2264 y \u2264 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": "@testset \"TotalDegree\" begin\n    @test HC.bezout_number([2 1; 2 1; 1 1], [2, 1]) == 8\n    @test HC.bezout_number([2 1 0; 1 1 1; 0 1 1], [1, 1, 1]) == 5\nend\n", "meta": {"hexsha": "01a73f2a62c2b7e0ef694d6fd2f4e9e688b83b4e", "size": 156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "v1/test/totaldegree_test.jl", "max_stars_repo_name": "mbauman/HomotopyContinuation.jl", "max_stars_repo_head_hexsha": "3253f86b2752303b0ed8616e07bccf8bfbb7f24d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-12T02:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T02:41:03.000Z", "max_issues_repo_path": "v1/test/totaldegree_test.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/test/totaldegree_test.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": 31.2, "max_line_length": 65, "alphanum_fraction": 0.5512820513, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.94499471015743, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7658982770616988}}
{"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, \u03bc, \u03c3)\n    simdata = rand(Normal(\u03bc, \u03c3), 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(\u03bc, \u03c3)\n    LL = 0.0\n    LL += logpdf(Normal(0, 1), \u03bc)\n    LL += logpdf(truncated(Cauchy(0, 1), 0, Inf), \u03c3)\n    return LL\nend\n\n# function for initial values\nfunction sample_prior()\n    \u03bc = rand(Normal(0, 1))\n    \u03c3 = rand(truncated(Cauchy(0, 1), 0, Inf))\n    return [\u03bc,\u03c3]\nend\n\n# parameter names\nnames = (:\u03bc,:\u03c3)\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": "\nfunction sudokus_from_file(filename, sep = '\\n')\n    s = open(filename) do file\n        read(file, String)\n    end\n    str_sudokus = split(strip(s), sep)\n    grids = AbstractArray[]\n    for str_sudoku in str_sudokus\n        str_sudoku = strip(replace(str_sudoku, \".\" => \"0\"))\n        if length(str_sudoku) != 81\n            continue\n        end\n        one_line_grid = parse.(Int, split(str_sudoku, \"\"))\n        grid = reshape(one_line_grid, 9, 9)\n        push!(grids, grid)\n    end\n    return grids\nend\n\nfunction create_sudoku_grid!(com, grid)\n    com_grid = Array{CS.Variable,2}(undef, 9, 9)\n    for (ind, val) in enumerate(grid)\n        if val == 0\n            com_grid[ind] = CS.add_var!(com, 1, 9)\n        else\n            com_grid[ind] = CS.add_var!(com, 1, 9; fix = val)\n        end\n    end\n    return com_grid\nend\n\nfunction add_sudoku_constr!(com, grid)\n    for rc in 1:9\n        #row\n        variables = grid[CartesianIndices((rc:rc, 1:9))]\n        CS.add_constraint!(com, CS.all_different([variables...]))\n        #col\n        variables = grid[CartesianIndices((1:9, rc:rc))]\n        CS.add_constraint!(com, CS.all_different([variables...]))\n    end\n\n    for br in 0:2\n        for bc in 0:2\n            variables = grid[CartesianIndices((\n                (br * 3 + 1):((br + 1) * 3),\n                (bc * 3 + 1):((bc + 1) * 3),\n            ))]\n            CS.add_constraint!(com, CS.all_different([variables...]))\n        end\n    end\nend\n\nfunction jump_add_sudoku_constr!(m, x)\n    for rc in 1:9\n        @constraint(m, x[rc, :] in CS.AllDifferent())\n        @constraint(m, x[:, rc] in CS.AllDifferent())\n    end\n    for br in 0:2\n        for bc in 0:2\n            @constraint(\n                m,\n                vec(x[(br * 3 + 1):((br + 1) * 3), (bc * 3 + 1):((bc + 1) * 3)]) in\n                CS.AllDifferent()\n            )\n        end\n    end\nend\n\nfunction moi_add_sudoku_constr!(m, x)\n    for r in 1:9\n        MOI.add_constraint(\n            m,\n            MOI.VectorOfVariables([x[r][c][1] for c in 1:9]),\n            CS.CPE.AllDifferent(9),\n        )\n    end\n    for c in 1:9\n        MOI.add_constraint(\n            m,\n            MOI.VectorOfVariables([x[r][c][1] for r in 1:9]),\n            CS.CPE.AllDifferent(9),\n        )\n    end\n    variables = [MOI.VariableIndex(0) for _ in 1:9]\n    for br in 0:2\n        for bc in 0:2\n            variables_i = 1\n            for i in (br * 3 + 1):((br + 1) * 3), j in (bc * 3 + 1):((bc + 1) * 3)\n                variables[variables_i] = x[i][j][1]\n                variables_i += 1\n            end\n            MOI.add_constraint(m, variables, CS.CPE.AllDifferent(9))\n        end\n    end\nend\n\nfunction jump_fulfills_sudoku_constr(vals)\n    for r in 1:9\n        if !allunique(vals[r, :])\n            println(\"row $r not unique\")\n            return false\n        end\n    end\n    for c in 1:9\n        if !allunique(vals[:, c])\n            println(\"col $c not unique\")\n            return false\n        end\n    end\n    for br in 0:2\n        for bc in 0:2\n            if !allunique(vec(vals[\n                (br * 3 + 1):((br + 1) * 3),\n                (bc * 3 + 1):((bc + 1) * 3),\n            ]))\n                println(\"block $br, $bc not unique\")\n                return false\n            end\n        end\n    end\n    return true\nend\n\nfunction fulfills_sudoku_constr(com_grid)\n    correct = true\n    for rc in 1:9\n        row = com_grid[CartesianIndices((rc:rc, 1:9))]\n        if any(v -> !CS.isfixed(v), row)\n            return false\n        end\n        vals = unique([CS.value(v) for v in row])\n        correct = length(vals) != 9 ? false : correct\n\n        col = com_grid[CartesianIndices((1:9, rc:rc))]\n        if any(v -> !CS.isfixed(v), col)\n            return false\n        end\n        vals = unique([CS.value(v) for v in col])\n        correct = length(vals) != 9 ? false : correct\n    end\n\n    for br in 0:2\n        for bc in 0:2\n            box = com_grid[CartesianIndices((\n                (br * 3 + 1):((br + 1) * 3),\n                (bc * 3 + 1):((bc + 1) * 3),\n            ))]\n            if any(v -> !CS.isfixed(v), box)\n                return false\n            end\n            vals = unique([CS.value(v) for v in box])\n            correct = length(vals) != 9 ? false : correct\n        end\n    end\n    return correct\nend\n\nfunction print_search_space(com_grid; max_length = :default)\n    if max_length == :default\n        if all(v -> CS.isfixed(v), com_grid)\n            max_length = 2\n        else\n            max_length = 20\n        end\n    end\n\n    for y in 1:size(com_grid)[1]\n        line = \"\"\n        for x in 1:size(com_grid)[2]\n            if !CS.isfixed(com_grid[y, x])\n                possible = sort(values(com_grid[y, x]))\n                pstr = join(possible, \",\")\n                space_left = floor(Int, (max_length - length(pstr)) / 2)\n                space_right = ceil(Int, (max_length - length(pstr)) / 2)\n                line *= repeat(\" \", space_left) * pstr * repeat(\" \", space_right)\n            else\n                pstr = string(CS.value(com_grid[y, x]))\n                space_left = floor(Int, (max_length - length(pstr)) / 2)\n                space_right = ceil(Int, (max_length - length(pstr)) / 2)\n                line *= repeat(\" \", space_left) * pstr * repeat(\" \", space_right)\n            end\n        end\n        println(line)\n    end\nend\n", "meta": {"hexsha": "687805db19fb0dad75caa0ca43cc4dd6cf3fa003", "size": 5338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sudoku_fcts.jl", "max_stars_repo_name": "Wikunia/ConstraintSolver.jl", "max_stars_repo_head_hexsha": "2d857b27e6006e587afbd5f337974c82646f0301", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 120, "max_stars_repo_stars_event_min_datetime": "2019-09-05T23:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:04:40.000Z", "max_issues_repo_path": "test/sudoku_fcts.jl", "max_issues_repo_name": "Wikunia/ConstraintSolver.jl", "max_issues_repo_head_hexsha": "2d857b27e6006e587afbd5f337974c82646f0301", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 273, "max_issues_repo_issues_event_min_datetime": "2019-09-05T11:20:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:57:00.000Z", "max_forks_repo_path": "test/sudoku_fcts.jl", "max_forks_repo_name": "Wikunia/ConstraintSolver.jl", "max_forks_repo_head_hexsha": "2d857b27e6006e587afbd5f337974c82646f0301", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-09-13T08:36:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T18:08:03.000Z", "avg_line_length": 28.6989247312, "max_line_length": 83, "alphanum_fraction": 0.4915698764, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7658383534106741}}
{"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\u03c3(du , u , p , t) = du .= sigma.*u\n\u03bc(du , u , p , t) = du .= r.*u\nprob = KolmogorovPDEProblem(\u03bc , \u03c3 , 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\u2080= [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\u2080,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(\u03bc1, \u03bc2, s)\n    cohens_d(n1, \u03bc1, s1, n2, \u03bc2, s2)\n    cohens_d(A::Array, B::Array)\n\nEffect size according to Cohen's d for means `\u03bc1` and `\u03bc2`, number of samples `n1` and `n2`, and standard deviations `s1` and `s2` for respectively group 1 and 2.\n\"\"\"\ncohens_d(\u03bc1, \u03bc2, s) = (\u03bc1 - \u03bc2) / 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, \u03bc1, s1, n2, \u03bc2, s2) = cohens_d(\u03bc1, \u03bc2, 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 \u03bb in 1:Nscales\n        sW[:, \u03bb] .= sgs[\u03bb]()\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 \u03bb in 1:Nscales\n        sW[:, \u03bb] .= sgs[\u03bb]()\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 \u03bb in 1:Nscales\n            origW = W[:, \u03bb]\n            c = f(origW, circshifted_s[:, \u03bb])\n            if c > maxcorrs[\u03bb]\n                maxcorrs[\u03bb] = c\n                optimal_shifts[\u03bb] = i\n            end\n\n            c_mirr = f(origW, circshifted_smirr[:, \u03bb])\n            if c_mirr > maxcorrs_mirr[\u03bb]\n                maxcorrs_mirr[\u03bb] = c_mirr\n                optimal_shifts_mirr[\u03bb] = i\n            end\n        end\n    end\n\n    # Decide which coefficients are retained (either surrogate or mirror surrogate coefficients)\n    for \u03bb in 1:Nscales\n        if maxcorrs[\u03bb] >= maxcorrs_mirr[\u03bb]\n            R[:, \u03bb] .= circshift(sW[:, \u03bb], optimal_shifts[\u03bb])\n        else \n            R[:, \u03bb] .= circshift(sWmirr[:, \u03bb], optimal_shifts_mirr[\u03bb])\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\u0161, 2008)[^Palu\u01612008].\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\u01612008].\n\n[^Palu\u01612008]: Palu\u0161, Milan (2008). Bootstrapping Multifractals: Surrogate Data from Random Cascades on Wavelet Dyadic Trees. Physical Review Letters, 101(13), 134101\u2013. 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\u0303 = zeros(2^(nlevels + 1))\n    if mode == \"zeros\"\n        copyto!(x\u0303, 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\u0303, 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\u209b = 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\u209b = c\u209b,\n        nlevels = nlevels,\n        s\u0303 = similar(x\u0303),\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\u209b, s\u0303, wl, nlevels, Ms, ixs = \n        sg.init.c, sg.init.c\u209b, sg.init.s\u0303, sg.init.wl, sg.init.nlevels, sg.init.Ms, sg.init.ixs\n\n    c\u209b[dyadicdetailrange(0)] = @view c[dyadicdetailrange(0)]\n    c\u209b[dyadicdetailrange(1)] = @view c[dyadicdetailrange(1)]\n\n    for (l, j) = enumerate(2:nlevels-1)\n        c\u2c7c\u208b\u2081 = @view c[dyadicdetailrange(j - 1)]\n        c\u2c7c = @view c[dyadicdetailrange(j)]\n\n        M = Ms[l]\n        ct = 1\n        @inbounds for k = 1:length(c\u2c7c\u208b\u2081)\n            if k % 2 == 0\n                M[ct] = c\u2c7c[2*k] / c\u2c7c\u208b\u2081[k]\n            else \n                M[ct] = c\u2c7c[2*(k+1)] / c\u2c7c\u208b\u2081[k+1]\n            end\n            ct += 1\n        end\n\n        shuffle!(rng, M)\n        new_coeffs!(M, c\u2c7c\u208b\u2081)\n        ix = ixs[l]\n        sortperm!(ix, M)\n        c\u209b[dyadicdetailrange(j-1)] .= @view c\u2c7c\u208b\u2081[ix]\n    end\n    s\u0303 .= idwt(c\u209b, wl, nlevels)\n\n    # Surrogate length must match length of original signal.\n    s .= @view s\u0303[1:length(s)]\n    return s\nend\n\nfunction new_coeffs!(M, c\u2c7c\u208b\u2081)\n    @inbounds for k = 1:length(c\u2c7c\u208b\u2081)\n        M[k] = M[k] * c\u2c7c\u208b\u2081[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 \u2208 \u211c_{i ^ 2}\n    #     I_0 = \u2205\n    #     L_0 = I(n)\n    #     B_0 = A\n    #     B_i \u2208 \u2102_{(n - i) ^ 2}\n    #     B_n = \u2205\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\u2013Banachiewicz_and_Cholesky\u2013Crout_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 \u22c5 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 \u22c5 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(\u03bc) = length(\u03bc) > 1 ? FFTW.plan_r2r!(\u03bc, FFTW.REDFT00) : ones(\u03bc)'\n\n\"\"\"\nCompute nodes of the Clenshaw\u2014Curtis 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\u2014Curtis quadrature rule with modified Chebyshev moments of the first kind ``\\\\mu``.\n\"\"\"\nclenshawcurtisweights(\u03bc::Vector) = clenshawcurtisweights!(copy(\u03bc))\nclenshawcurtisweights!(\u03bc::Vector) = clenshawcurtisweights!(\u03bc, plan_clenshawcurtis(\u03bc))\nfunction clenshawcurtisweights!(\u03bc::Vector{T}, plan) where T\n    N = length(\u03bc)\n    rmul!(\u03bc, inv(N-one(T)))\n    plan*\u03bc\n    \u03bc[1] *= half(T); \u03bc[N] *= half(T)\n    return \u03bc\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\u03b8) coefficients to values at Clenshaw-Curtis nodes except \u00b11\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": "# Test utililties.jl\n\n# Tests could be more comprehensive (of course).  In some cases all\n# that is done is to execute the function in some way just to make\n# sure no exceptions are thrown as a result of something breaking with\n# a new version of Julia.\n\nprintln(\"testing utilites\")\n\nusing PerceptualColourMaps\nusing Test, Statistics\n\n# bbspline\nP = [0 1 2 3\n     0 1 2 3]\nk = 3\nN = 10\nS = bbspline(P, k, N)\n#dx = Base.LinAlg.gradient(S[1,:],1)\n#dy = Base.LinAlg.gradient(S[2,:],1)\n# There seems to be an awkward method ambiguity between Base.LinAlg.gradient and\n# Calculus.gradient, hence the simple replacement code below.\ndx = S[1, 2:end] - S[1, 1:(end-1)]\ndy = S[2, 2:end] - S[2, 1:(end-1)]\n\nslope = dy./dx\n@test maximum(slope .- 1) < 1e-3\n\n# pbspline\nP = [0 1 2 3 0\n     0 1 2 3 0]\nk = 3\nN = 100\nS = pbspline(P, k, N)\n\n# gaussfilt1d\na = zeros(20,1)\na[10] = 1\nsigma = 2\nsa = gaussfilt1d(a, sigma)\n@test abs(sa[10] - 1/(sigma*sqrt(2pi))) < 1e-3\n@test abs(sum(sa) - 1) < 1e-3\n\n# interp1\nx = [0, 2, 7]\ny = 2*x\nxi = [1.1, 0.5, 6]\nyi = interp1(x,y,xi)\n@test maximum(abs.(yi - 2*xi) .< eps())\n\n# normalise\na = rand(5,3)\nan = normalise(a)\n@test isapprox(minimum(an), 0)\n@test isapprox(maximum(an), 1)\n\nreqmean = 5\nreqvar = 7\nan = normalise(a, reqmean, reqvar)\n@test isapprox(mean(an), reqmean)\n@test isapprox(var(an), reqvar)\n\n# histtruncate\nrows = 100;\ncols = 200;\nimg = rand(rows, cols)\nlHistCut = 2\nuHistCut = 4\nhtimg = histtruncate(img, lHistCut, uHistCut)\nminval = minimum(htimg)\nmaxval = maximum(htimg)\n# Check that the number of saturated pixels at each extreme is\n# approximately lHistCut and uHistCut. Note some integer rounding has\n# to occur.\nv = findall(abs.(htimg.-minval).<eps())\n@test abs(length(v)/(rows*cols) * 100 - lHistCut) < 1\n\nv = findall(abs.(htimg.-maxval).<eps())\n@test abs(length(v)/(rows*cols) * 100 - uHistCut) < 1\n\n# sineramp\nsr = sineramp()\nsr = sineramp((256, 512), 12.5, 8, 2)\n\n# circlesineramp\n(img, alpha) = circlesineramp()\n(img, alpha) = circlesineramp(512, pi/10, 8, 2, false)\n", "meta": {"hexsha": "64ae6e50a33dfff637e2af510898e0b6f3a3ef02", "size": 2011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_utilities.jl", "max_stars_repo_name": "peterkovesi/PerceptualColourMaps.jl", "max_stars_repo_head_hexsha": "49c5dbafa9f2a7830531f6e0db877faac740e826", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2016-01-29T13:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:11:03.000Z", "max_issues_repo_path": "test/test_utilities.jl", "max_issues_repo_name": "peterkovesi/PerceptualColourMaps.jl", "max_issues_repo_head_hexsha": "49c5dbafa9f2a7830531f6e0db877faac740e826", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2016-01-17T12:55:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T14:52:30.000Z", "max_forks_repo_path": "test/test_utilities.jl", "max_forks_repo_name": "peterkovesi/PerceptualColourMaps.jl", "max_forks_repo_head_hexsha": "49c5dbafa9f2a7830531f6e0db877faac740e826", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-01-17T02:07:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:01:34.000Z", "avg_line_length": 22.8522727273, "max_line_length": 80, "alphanum_fraction": 0.6633515664, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7658065811208574}}
{"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\u2091_m = 6371008.7714\n\n\"\"\"\n    angular_distance(point\u2081::Point, point\u2082::Point)\n\nReturn the `angular_distance` [deg] of the great circle line between the\npositions `point\u2081` [deg] and `point\u2082` [deg] on a unit sphere.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction angular_distance(point\u2081::Point, point\u2082::Point)\n    \u0394pos = point\u2082 - point\u2081\n    a = sind(\u0394pos.\u03d5/2.0)^2 + cosd(point\u2081.\u03d5)*cosd(point\u2082.\u03d5)*sind(\u0394pos.\u03bb/2.0)^2\n    c = 2.0 * atand(\u221aa, \u221a(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\u2081, arc.point\u2082)\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\u2081 = points[1]\n    dist_deg = 0.0\n    for point\u2082 in points[2:end]\n        dist_deg += angular_distance(point\u2081, point\u2082)\n        point\u2081 = point\u2082\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\u2091_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\u2091_m)\n#     return deg2rad(angular_distance) * radius\n# end\n\n\"\"\"\n    angular_distance(point\u2083::Point, point\u2081::Point, azimuth\u2081\u2082::Float64)\n\nReturn the `angular_distance` [deg] from point\u2083 [deg] to the closest point on a\ngreat circle line starting in `point\u2081` [deg] with `azimuth\u2081\u2082` [deg] from\n`point\u2081` to `point\u2082`. It is assumed that the great circle line does not stop in\n`point\u2082`, 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\u2083::Point, point\u2081::Point, azimuth\u2081\u2082::Float64)\n    angular_distance\u2081\u2083 = angular_distance(point\u2081, point\u2083)\n    azimuth\u2081\u2083 = azimuth(point\u2081, point\u2083)\n    return angular_distance(angular_distance\u2081\u2083, azimuth\u2081\u2083, azimuth\u2081\u2082)\nend\n\n\"\"\"\n    angular_distance(point\u2083::Point, line\u2081::Line)\n\nReturn the `angular_distance` [deg] from point\u2083 [deg] to the closest point on a\ngreat circle line starting in `point\u2081` [deg] with `azimuth\u2081\u2082` [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\u2083::Point, line\u2081::Line) = angular_distance(point\u2083,\nline\u2081.point, line\u2081.azimuth)\n\n\"\"\"\n    angular_distance(angular_distance\u2081\u2083::Float64, azimuth\u2081\u2083::Float64,\n    azimuth\u2081\u2082::Float64)\n\nReturn the `angular_distance` [deg] from point\u2083 [deg] to the closest point on a\ngreat circle line starting in `point\u2081` [deg] with `azimuth\u2081\u2082` [deg]. For the\ncalculation we need the `angular_distance\u2081\u2083` and `azimuth\u2081\u2083` between `point\u2081`\nand `point\u2083` [deg], and the `azimuth\u2081\u2082` from `point\u2081` to `point\u2082` along the\ngreat circle line. It is assumed that the great circle line does not stop in\n`point\u2082`, but continuous around the unit sphere.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction angular_distance(angular_distance\u2081\u2083::Float64, azimuth\u2081\u2083::Float64,\nazimuth\u2081\u2082::Float64)\n    return asind(sind(angular_distance\u2081\u2083) * sind(azimuth\u2081\u2083 - azimuth\u2081\u2082))\nend\n\n\"\"\"\n    angular_distance(point\u2083::Point, point\u2081::Point, point\u2082::Point)\n\nReturn the `angular_distance` [deg] from point\u2083 [deg] to the closest point on a\ngreat circle line section starting in `point\u2081` [deg] and ending in `point\u2082` [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\u2083::Point, point\u2081::Point, point\u2082::Point, tolerance::Float64=tolerance_deg)\n    angular_distance\u2081\u2082 = angular_distance(point\u2081, point\u2082)\n    angular_distance\u2081\u2083 = angular_distance(point\u2081, point\u2083)\n    angular_distance\u2082\u2083 = angular_distance(point\u2082, point\u2083)\n    azimuth\u2081\u2082 = azimuth(point\u2081, point\u2082)\n    angular_distance_line3 = angular_distance(point\u2083, point\u2081, azimuth\u2081\u2082)\n    # along_line_angular_dist = along_line_angular_distance(angular_distance\u2081\u2083,\n    # angular_distance_line3)\n    along_line_pnt_3a = along_line_point(point\u2083, Line(point\u2081, azimuth\u2081\u2082))\n    if abs(angular_distance(along_line_pnt_3a, point\u2081) +\n        angular_distance(along_line_pnt_3a, point\u2082) -\n        angular_distance\u2081\u2082) < tolerance\n        return abs(angular_distance_line3)\n    else\n        return min(angular_distance\u2081\u2083, angular_distance\u2082\u2083)\n    end\nend\n\n\"\"\"\n    angular_distance(point\u2083::Point, points::Vector{Points{T}}) where T<:Float64\n\nReturn the `angular_distance` [deg] from point\u2083 [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\u2083::Point, points::Vector{Point{T}}) where\n    T<:Float64\n    point\u2081 = points[1]\n    point\u2082 = points[2]\n    min_dist = angular_distance(point\u2083, point\u2081, point\u2082)\n    point\u2081 = point\u2082\n    for point\u2082 in points[2:end]\n        min_dist = min(min_dist, angular_distance(point\u2083, point\u2081, point\u2082))\n        point\u2081 = point\u2082\n    end\n    return min_dist\nend\n\n\"\"\"\n    angular_distance(point\u2083::Point, arcs::Arcs)\n\nReturn the `angular_distance` [deg] from point\u2083 [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\u2083::Point, arcs::Arcs) = angular_distance(point\u2083, arcs.points)\n\n\"\"\"\n    angular_distance(point\u2083::Point, polygon::Polygon)\n\nReturn the `angular_distance` [deg] from point\u2083 [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\u2083::Point, polygon::Polygon) = angular_distance(point\u2083,\npolygon.points)\n\n\"\"\"\n    angular_distance(point\u2083::Point, arc\u2081\u2082::Arc)\n\nReturn the `angular_distance` [deg] from point\u2083 [deg] to the closest point on a\ngreat circle line section starting in `point\u2081` [deg] and ending in `point\u2082` [deg].\nThe great circle line section does not continue around the unit sphere.\n\"\"\"\nangular_distance(point\u2083::Point, arc\u2081\u2082::Arc) = angular_distance(point\u2083, arc\u2081\u2082.point\u2081, arc\u2081\u2082.point\u2082)\n\n\"\"\"\n    along_line_angular_distance(angular_distance\u2081\u2083::Float64,\n    angular_distance_line3::Float64)\n\nThe `along_line_angular_distance` from the start `point\u2081` [deg] to the closest\npoint on the great circle line to `point\u2083`. As input we need the\n`angular_distance\u2081\u2083` [deg] between `point\u2081` and `point\u2083` [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\u2081\u2083::Float64,\nangular_distance_line3::Float64)\n    return acosd(cosd(angular_distance\u2081\u2083) / cosd(angular_distance_line3))\nend\n\n\"\"\"\n    along_line_angular_distance(point\u2083::Point, line\u2081::Line)\n\nThe `along_line_angular_distance` from the start `point\u2081` [deg] to the closest\npoint on the great circle line `line\u2081` to `point\u2083`. The distance is\nnon-directional.\n\nSource: www.movable-type.co.uk/scripts/latlong.html\n\"\"\"\nfunction along_line_angular_distance(point\u2083::Point, line\u2081::Line)\n    angular_distance\u2081\u2083 = angular_distance(line\u2081.point, point\u2083)\n    angular_distance_line3 = angular_distance(point\u2083::Point, line\u2081::Line)\n    return along_line_angular_distance(angular_distance\u2081\u2083,\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) \u00d7 (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  \u03bb = one(eltype(ranges)) ./ ranges.^2\n  \u039b = Diagonal(SVector{ndims}(\u03bb))\n\n  # rotation matrix\n  R = rotmat(angles, convention)\n\n  # ellipsoid metric\n  W = Symmetric(R'*\u039b*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 \u2265 n \u2265 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 \u2265 n \u2265 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 \u2264 r \u2264 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    \u2207(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 \u2207 = 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 \u2264 r \u2264 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)(\u03b8)\n    @unpack y, x, = problem    # extract the data\n    @unpack muy, mux = \u03b8     # 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\u03b8 = (muy = 0.0, mux=0.0)\np(\u03b8)\n\n# Write a function to return properly dimensioned transformation.\n\nproblem_transformation(p::clip_9_3_model) =\n    as((muy = as\u211d, mux = as\u211d))\n\n# Wrap the problem with a transformation, then use Flux for the gradient.\n\nP = TransformedLogDensity(problem_transformation(p), p)\n\u2207P = ADgradient(:ForwardDiff, P);\n\n# Tune and sample.\n\nchain, NUTS_tuned = NUTS_init_tune_mcmc(\u2207P, 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, \u2207P; 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; \u03b8=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\u03c80 = state(s, \"0\")\n\u03c8p = state(s, \"+\")\n\nfunction loss(x)\n  U = op(\"Ry\", s; \u03b8=x)\n  U\u03c80 = replaceprime(U * \u03c80, 1 => 0)\n  return -(dag(\u03c8p) * U\u03c80)[]\nend\n\n# Extremely simple gradient descent implementation,\n# where gradients are computing with automatic differentiation\n# using Zygote.\nfunction gradient_descent(f, x0; \u03b3, nsteps, grad_tol)\n  @show \u03b3, nsteps\n  x = x0\n  f_x = f(x)\n  \u2207f_x = f'(x)\n  step = 0\n  @show step, x, f_x, \u2207f_x\n  for step in 1:nsteps\n    x -= \u03b3 * \u2207f_x\n    f_x = f(x)\n    \u2207f_x = f'(x)\n    @show step, x, f_x, \u2207f_x\n    if norm(\u2207f_x) \u2264 grad_tol\n      break\n    end\n  end\n  return x, f_x, \u2207f_x\nend\n\nx0 = 0\n\u03b3 = 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, \u2207loss_x = gradient_descent(loss, x0; \u03b3=\u03b3, nsteps=nsteps, grad_tol=grad_tol)\n\n@show x0, loss(x0)\n@show x, loss(x)\n@show \u03c0 / 2, loss(\u03c0 / 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": "using SpikeStats\nusing Test\n\ntestset = poissonSpikes(10,100,0.001)\n\nprintln(names(SpikeStats))\n\n@testset \"SpikeStats.jl\" begin\n    @test typeof(testset) == Array{Float64,1}\n    @test round(computeCV(diff(testset)), digits=2) == 0.93\n    @test round(computeFano(testset,0.001), digits=2) == 0.90\nend\n", "meta": {"hexsha": "03d61e0115ef81b70b199f1fa2c282e7fc08505f", "size": 299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "neuro-myoung/spikestats.jl", "max_stars_repo_head_hexsha": "7986b7ac8f9bc3a307737722d12d7e4ed18f2d6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-22T19:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T19:20:19.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "neuro-myoung/spikestats.jl", "max_issues_repo_head_hexsha": "7986b7ac8f9bc3a307737722d12d7e4ed18f2d6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-16T01:02:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T01:03:52.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "neuro-myoung/spikestats.jl", "max_forks_repo_head_hexsha": "7986b7ac8f9bc3a307737722d12d7e4ed18f2d6a", "max_forks_repo_licenses": ["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": 61, "alphanum_fraction": 0.7090301003, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7656455364246552}}
{"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": "using jInv.Mesh\nusing jInv.LinearSolvers\nusing SparseArrays\nusing LinearAlgebra\nusing Test\nprintln(\"===  Test Julia wrapper with symmetric (real) matrix ====\");\ndomain = [0.0, 1.0, 0.0, 1.0];\nn      = [33,17];\nMr     = getRegularMesh(domain,n)\nG      = getNodalGradientMatrix(Mr);\nm      = sparse(Diagonal(exp.(randn(size(G,1)))));\nAr     = G'*m*G;\nAr     = Ar + 1e-1*norm(Ar,1)*sparse(1.0I,size(Ar,2),size(Ar,2));\nN      = size(Ar,2);\nb      = Ar*rand(N,1);\nbs     = Ar*rand(N,3);\nBs     = (b,sparse(b),bs,sparse(bs));\n\nsNonSym = getJuliaSolver(sym = 0);\nsSym    = getJuliaSolver(sym = 1);\nsGenSym = getJuliaSolver(sym = 2);\nsols    = (sNonSym,sSym,sGenSym)\n\nfor j=1:length(Bs)\n\tprint(\"nrhs=$(size(Bs[j],2)), issparse(rhs)=$(issparse(Bs[j])) : \")\n\tfor k=1:length(sols)\n\t\tprint(\"sym=$(sols[k].sym), \")\n\t\txtt1,  = solveLinearSystem(Ar,Bs[j],sols[k]);\n\t\t@test norm(Ar*xtt1-Bs[j],Inf)/norm(Bs[j],Inf) < 1e-10\n\tend\n\tprint(\"\\n\")\nend\nprintln(\"\\n\")\n\n\nprintln(\"===  Test Julia wrapper with shifted (complex) Laplacian ====\");\nAr     = G'*m*G +  (1+1im)*sparse(1.0I,size(Ar,2),size(Ar,2));\nb      = Ar*rand(N,1);\nbs     = Ar*rand(N,3);\nBs     = (b,sparse(b),bs,sparse(bs));\n\nsNonSym = getJuliaSolver(sym = 0);\nsSym    = getJuliaSolver(sym = 1);\nsGenSym = getJuliaSolver(sym = 2);\nsols    = (sNonSym,sSym,sGenSym)\n\nfor j=1:length(Bs)\n\tprint(\"nrhs=$(size(Bs[j],2)), issparse(rhs)=$(issparse(Bs[j])) : \")\n\tfor k=1:length(sols)\n\t\tprint(\"sym=$(sols[k].sym), \")\n\t\txtt2,  = solveLinearSystem(Ar,Bs[j],sols[k]);\n\t\t@test norm(Ar*xtt2-Bs[j],Inf)/norm(Bs[j],Inf) < 1e-10\n\tend\n\tprint(\"\\n\")\nend\nprintln(\"\\n\")\n\n\nprintln(\"===  Test Julia Wrapper: nonsymmetric matrices ====\");\nn = 50\nsNonSym  = getJuliaSolver(sym = 0);\nsNonSym  = copySolver(sNonSym);\nA = sprandn(n,n,5/n) + 10*sparse(1.0I,n,n)\nB = randn(n)\n\nX, = solveLinearSystem(A,B,sNonSym,0);\n@test norm(A*X - B)/norm(B) < 1e-10\n\n# multiple sparse rhs - \n# Bs = sprandn(n,10,.3)\n# X, = solveLinearSystem(A,Bs,sNonSym,0);\n# @test norm(A*X - Bs,Inf)/norm(Bs,Inf) < 1e-10\n\n\nX, = solveLinearSystem(A,B,sNonSym,1);\n@test norm(A'*X - B)/norm(B) < 1e-10\n\nX, = solveLinearSystem(A,B,sNonSym,1);\n@test norm(A'*X - B)/norm(B) < 1e-10\n\nX, = solveLinearSystem(A,B,sNonSym,0);\n@test norm(A*X - B)/norm(B) < 1e-10\n\nprintln(\"===  End Test Julia Wrapper ====\");\n", "meta": {"hexsha": "b68658e7ea3fae5a1a52b43c663941f18eb458d0", "size": 2277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/LinearSolvers/testJuliaWrapper.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": "test/LinearSolvers/testJuliaWrapper.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": "test/LinearSolvers/testJuliaWrapper.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": 26.7882352941, "max_line_length": 73, "alphanum_fraction": 0.6091348265, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7655475561840963}}
{"text": "module BVP1D\n\nusing LinearAlgebra\nusing OffsetArrays\n\nexport solve_bvp\n\nfunction solve_bvp(L, f, \u03b30, \u03b3L, P) \n    \u0394x = L / P\n    c = 1 / \u0394x^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 * \u03b30\n    b[P-1] += c * \u03b3L\n    U = OffsetArray{Float64}(undef, 0:P)\n    U[0] = \u03b30\n    U[1:P-1] = A \\ b\n    U[P] = \u03b3L\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": "# Implementation of Blendenpik with Gaussian row mixing for the solution of least squares\n# problem ||Ax - b||\u2082 where A has full column rank.\n#\n# This method for other row mixing strategies is described in\n#\n# Avron, Haim, Petar Maymounkov, and Sivan Toledo. \"Blendenpik: Supercharging LAPACK's\n# least-squares solver.\" SIAM Journal on Scientific Computing 32, no. 3 (2010): 1217-1236.\n#\n# January 2021\n\n\"\"\"\n    blendenpick_gauss(A, b; r)\n\nSolves the least squares problem with coefficient `A` and constant `b`, where `A` has full\ncolumn rank, using the blendenpick method with Gaussian row mixing. The number of sampled\nrows, `r`, defaults to the number of columns.\n\"\"\"\nfunction blendenpick_gauss!(\n    x::Vector{T},\n    A::Matrix{T},  # Coefficient matrix of system\n    b::Vector{T};  # Constant vector of system\n    r::Int=size(A, 2) + 0,  # Size of row sample\n    verbose::Bool=false  #Show stats from lsqr solver\n) where T <: Real\n    m = size(A, 1)              # Number of rows in A\n\n    # Mix rows of a A with Gaussians to generate r by size(A, 2) matrix\n    A_mixed = randn(r, m) * A\n\n    # Generate preconditioner using R\u207b factor of qr decomposition of mixed matrix\n    _, R = qr(A_mixed)\n    Rinv = R \\ I\n\n    # Run lsqr on transformed systems\n    y, stats = lsqr(A * Rinv, b)\n\n    verbose && show(stats)\n\n    # Recover and return solution to original system\n    x = Rinv * y\nend\n", "meta": {"hexsha": "adcc8354f69a701a8b8c60962217c761ebf0edd7", "size": 1391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_solver_routines/blendenpik_gauss.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/blendenpik_gauss.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/blendenpik_gauss.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": 33.119047619, "max_line_length": 90, "alphanum_fraction": 0.6808051761, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7655235492554548}}
{"text": "using Base.Test\nusing TimeIt\nimport NestedSampling: logaddexp, nball_vol_factor, sample\n\n# Test logaddexp()\nx = log(1.e-100)\ny = log(2.e-100)\n@test_approx_eq exp(logaddexp(x, y)) 3.e-100\n\n# Test volume prefactor for an N-ball\n@test_approx_eq nball_vol_factor(4) pi^2 / 2\n@test_approx_eq nball_vol_factor(5) 8pi^2/15\n@test_approx_eq nball_vol_factor(6) pi^3 / 6\n@test_approx_eq nball_vol_factor(7) 16pi^3/105\n\n\n# -----------------------------------------------------------------------------\n# Simple likelihood function\n\n    # gaussians centered at (1, 1) and (-1, -1) with a width of 0.1.\nconst mu1 = [1., 1.]\nconst mu2 = [-1., -1.]\nconst sigma = 0.1\nconst invvar = eye(2) / sigma^2\n\nfunction logl(x)\n    dx1 = x .- mu1\n    dx2 = x .- mu2\n    return logaddexp((dx1' * invvar * dx1)[1] / 2.0,\n                     (dx2' * invvar * dx2)[1] / 2.0)\nend\n\n\n\n# Use a flat prior, over [-5, 5] in both dimensions\nprior(x) = 10.0 .* x .- 5.0\n\nsrand(0)\nres = sample(logl, prior, 2; npoints=100)\n@printf \"evidence = %6.3f +/- %6.3f\\n\" res[\"logz\"] res[\"logzerr\"]\n\n#(Approximate) analytic evidence for two identical Gaussian blobs,\n# over a uniform prior [-5:5][-5:5] with density 1/100 in this domain:\nanalytic_logz = log(2.0 * 2.0*pi*sigma*sigma / 100.)\n@printf \"analytic = %6.3f\\n\" analytic_logz \n\n    # calculate evidence on fine grid.\n    #dx = 0.1\n    #xv = np.arange(-5.0 + dx/2., 5., dx)\n    #yv = np.arange(-5.0 + dx/2., 5., dx)\n    #grid_logz = -1.e300\n    #for x in xv:\n    #    for y in yv:\n    #        grid_logz = np.logaddexp(grid_logz, logl(np.array([x, y])))\n    #grid_logz += np.log(dx * dx / 100.)  # adjust for point density\n    #print \"grid_logz =\", grid_logz\n\n    #assert abs(res.logz - analytic_logz) < 2.0 * res.logzerr\n    #assert abs(res.logz - grid_logz) < 2.0 * res.logzerr\n\n", "meta": {"hexsha": "437479df6fbbbf92f405d4791f578379a88a1abe", "size": 1789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "kbarbary/NestedSampling.jl", "max_stars_repo_head_hexsha": "d7715499f871f17e4bc80172a37c92e4a7a42f28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-22T08:56:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T08:56:52.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "kbarbary/NestedSampling.jl", "max_issues_repo_head_hexsha": "d7715499f871f17e4bc80172a37c92e4a7a42f28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-24T12:08:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T18:59:58.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "kbarbary/NestedSampling.jl", "max_forks_repo_head_hexsha": "d7715499f871f17e4bc80172a37c92e4a7a42f28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-07-01T00:08:29.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-30T21:47:59.000Z", "avg_line_length": 29.3278688525, "max_line_length": 79, "alphanum_fraction": 0.6020122974, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7655235444075785}}
{"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] \u00d7 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 \u00d7 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    minimumAssignmentProblem(C)\n\nSolve minimum assignment problem using vector of costs `C`.\n\"\"\"\nfunction minimumAssignmentProblem(C)\n    @assert ndims(C) == 2 && size(C, 1) == size(C, 2)\n\n    m = size(C, 1)\n    model = Model(solver = CplexSolver(CPXPARAM_ScreenOutput = getProperty(\"minimumAssignmentProblem.cplexLogging\")))\n    @variable(model, x[1:m, 1:m], Bin)\n    @objective(model, Min, vecdot(C, x))\n\n    for constraint in getAssignmentConstraints(m)\n        JuMP.addconstraint(model, constraint(x))\n\tend\n\n    status = solve(model)\n    return map((x) -> Int(x), getvalue(x))\nend\n\n\"\"\"\n    getAssignmentConstraints(m)\n\nReturn a list of constraints defining a set of feasible solutions of a minimum assignment problem.\nEach constraint is function with one parameter, which is variable of a mathematical programming model.\n\"\"\"\nfunction getAssignmentConstraints(m)\n    constraints = []\n    for j in 1:m\n        push!(constraints, x-> @LinearConstraint(sum(x[i,j] for i=1:m)==1))\n    end\n    for i in 1:m\n        push!(constraints, x -> @LinearConstraint(sum(x[i,j] for j=1:m)==1))\n    end\n    constraints\nend\n", "meta": {"hexsha": "d78576c04513bb8eca349e8733cc5e00eb3558a4", "size": 1114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/minimum_assignment_problem.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/minimum_assignment_problem.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/minimum_assignment_problem.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": 29.3157894737, "max_line_length": 117, "alphanum_fraction": 0.6822262118, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7655235303703992}}
{"text": "\n# ------------------------------------------------------------------------------------------\n# # Julia \u4e2d\u7684\u7ebf\u6027\u4ee3\u6570\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# ## \u57fa\u7840\u7ebf\u6027\u4ee3\u6570\u64cd\u4f5c\n# \u5b9a\u4e49\u4e00\u4e2a\u968f\u673a\u77e9\u9635\n# ------------------------------------------------------------------------------------------\n\nA = rand(1:4,3,3)\n\n# ------------------------------------------------------------------------------------------\n# \u5b9a\u4e49\u4e00\u4e2a\u5143\u7d20\u5168\u4e3a 1 \u7684\u5411\u91cf\n# ------------------------------------------------------------------------------------------\n\nx = fill(1.0, (3,)) # = fill(1.0, 3)\n\n# ------------------------------------------------------------------------------------------\n# \u6ce8\u610f $A$ \u7684\u7c7b\u578b\u4e3a `Array{Int64,2}`\uff0c\u800c $x$ \u7684\u7c7b\u578b\u4e3a `Array{Float64,1}`\u3002\n#\n# Julia \u5b9a\u4e49\u5411\u91cf `Vector{Type}` \u7684\u522b\u540d\u4e3a `Array{Type,1}`\uff0c\u77e9\u9635`Matrix{Type}` \u7684\u522b\u540d\u4e3a `Array{Type,2}`\u3002\n#\n# \u8bb8\u591a\u7ebf\u6027\u4ee3\u6570\u7684\u57fa\u7840\u64cd\u4f5c\u548c\u5176\u4ed6\u8bed\u8a00\u4e00\u6837\n#\n# ### \u4e58\u6cd5\n# ------------------------------------------------------------------------------------------\n\nb = A*x\n\n# ------------------------------------------------------------------------------------------\n# ### \u8f6c\u7f6e\n# \u5c31\u50cf\u5728\u5176\u4ed6\u8bed\u8a00\u4e2d `A'` \u8868\u793a\u5bf9 `A` \u8fdb\u884c\u5171\u8f6d\u8f6c\u7f6e\n# ------------------------------------------------------------------------------------------\n\nA'\n\n# ------------------------------------------------------------------------------------------\n# \u6211\u4eec\u8fd8\u53ef\u4ee5\u901a\u8fc7 `transpose` \u51fd\u6570\u83b7\u5f97\u8f6c\u7f6e\u77e9\u9635\n# ------------------------------------------------------------------------------------------\n\ntranspose(A)\n\n# ------------------------------------------------------------------------------------------\n# ### \u8f6c\u7f6e\u7684\u4e58\u6cd5\n# Julia \u4e2d\u67d0\u4e9b\u60c5\u51b5\u4e0b\u53ef\u4ee5\u7701\u7565 `*` \u53f7\n# ------------------------------------------------------------------------------------------\n\nA'A\n\n# ------------------------------------------------------------------------------------------\n# ### \u89e3\u7ebf\u6027\u65b9\u7a0b\u7ec4\n# \u7528\u65b9\u9635 $A$ \u8868\u793a\u7684\u7ebf\u6027\u65b9\u7a0b\u7ec4 $Ax=b$ \u53ef\u4ee5\u7528\u5de6\u9664\u8fd0\u7b97\u7b26\uff08\u51fd\u6570\uff09`\\` \u6c42\u89e3\n# ------------------------------------------------------------------------------------------\n\nA\\b\n\n# ------------------------------------------------------------------------------------------\n# \u8d85\u5b9a\u7ebf\u6027\u65b9\u7a0b\u7ec4\uff08overdetermined linear system\uff09\u7684\u60c5\u51b5\u4e0b `A\\b` \u7ed9\u51fa*\u6700\u5c0f\u4e8c\u4e58\u89e3\uff08least squares solution\uff09*\n# ------------------------------------------------------------------------------------------\n\nAtall = rand(3, 2)\n\nAtall\\b\n\n# ------------------------------------------------------------------------------------------\n# \u7f3a\u79e9\u6700\u5c0f\u4e8c\u4e58\u95ee\u9898\uff08a rank-deficient least squares problem\uff09\u60c5\u51b5\u4e0b\uff0c\u4f1a\u7ed9\u51fa*\u6781\u5c0f\u8303\u6570\u6700\u5c0f\u4e8c\u4e58\u89e3\uff08minimum norm least\n# squares solution\uff09*\n# ------------------------------------------------------------------------------------------\n\nv = rand(3)\nrankdef = hcat(v, v)\n\nrankdef\\b\n\n# ------------------------------------------------------------------------------------------\n# \u6b20\u5b9a\u95ee\u9898\uff08an underdetermined solution\uff09\u4e0b\uff0c\u4f1a\u7ed9\u51fa \u6700\u5c0f\u8303\u6570\u89e3\uff08minimum norm solution\uff09\n# ------------------------------------------------------------------------------------------\n\nbshort = rand(2)\nAshort = rand(2, 3)\n\nAshort\\bshort\n\n# ------------------------------------------------------------------------------------------\n# ## `LinearAlgebra` \u5305\n#\n# \u5982\u4e0a\u6240\u793a\uff0cJulia\u9ed8\u8ba4\u81ea\u5e26\u4e86\u5f88\u591a\u7ebf\u6027\u4ee3\u6570\u64cd\u4f5c\uff0c\u800c\u6807\u51c6\u5e93 `LinearAlgebra` \u63d0\u4f9b\u4e86\u66f4\u591a\u7684\u76f8\u5173\u540d\u8bcd\u548c\u51fd\u6570\u3002\n# \u7279\u522b\u662f\u5b83\u63d0\u4f9b\u4e86\u56e0\u5b50\u5206\u89e3\u548c\u4e00\u4e9b\u7ed3\u6784\u5316\u77e9\u9635\u7c7b\u578b\u3002\n# \u548c\u5176\u4ed6\u5305\u4e00\u6837\uff0c\u53ef\u4ee5\u901a\u8fc7 `using LinearAlgebra` \u5f15\u5165\u8fd9\u4e9b\u989d\u5916\u7684\u7279\u5f81\u3002\n# ------------------------------------------------------------------------------------------\n\nusing LinearAlgebra\n\n# ------------------------------------------------------------------------------------------\n# ## \u7ec3\u4e60\n#\n# ### 10.1\n# \u8ba1\u7b97\u5411\u91cf `v` \u548c\u5b83\u81ea\u5df1\u7684\u5185\u79ef\uff0c\u5e76\u8d4b\u503c\u7ed9 `dot_v`\u3002\n# ------------------------------------------------------------------------------------------\n\nv = [1,2,3]\n\n# \u5728\u6b64\u4f5c\u7b54\ndot_v = v\n\n@assert dot_v == 14\n\n# ------------------------------------------------------------------------------------------\n# ### 10.2\n# \u8ba1\u7b97\u5411\u91cf v \u548c\u5b83\u81ea\u5df1\u7684\u5916\u79ef(Outer product)\uff0c\u5e76\u8d4b\u503c\u7ed9 `outer_v`\u3002\n#\n# \u63d0\u793a\uff1a\u5916\u79ef\u662f\u4e00\u79cd\u514b\u7f57\u5185\u514b\u79ef(Kronecker product)\n#\n# \u8ba1\u7b97\u53c9\u79ef(cross product)\uff0c\u8d4b\u503c\u7ed9 `cross_v`\n# ------------------------------------------------------------------------------------------\n\n# \u5728\u6b64\u4f5c\u7b54\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# \u8bf7\u5728\u5b8c\u6210\u7ec3\u4e60\u8fd0\u884c `@assert` \u5757\u4ee5\u68c0\u6d4b\u7ed3\u679c\u662f\u5426\u6b63\u786e\uff0c\u82e5\u65e0\u62a5\u9519\u5373\u4e3a\u6b63\u786e\u3002\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "9c01888c54b8888ae95595c6b3d2164250750afa", "size": 4427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/11.\u57fa\u672c\u7ebf\u6027\u4ee3\u6570.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.\u57fa\u672c\u7ebf\u6027\u4ee3\u6570.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.\u57fa\u672c\u7ebf\u6027\u4ee3\u6570.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": "using LinearAlgebra\n\nfunction lineq(;m, v, invert=false)\n    s = m \\ v\n    if ! invert\n        return (; bigarrs=(; s, ))\n    else\n        invm=inv(m)\n        detm = det(m)\n        return (; detm, bigarrs=(; s, invm))\n    end\nend\n\nfunction eigval(;m)\n    s = ComplexF64.(eigen(m).values) # result is otherwise type unstable (float or complex), and LabVIEW can't handle it\n    return (; bigarrs=(; s, ))\nend\n\n\nfns = (; lineq, eigval,)\n", "meta": {"hexsha": "6ee257d06a77cf9e12bac198a2fd55b08da5e9c0", "size": 434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LabVIEW/LV2Julia_examples/jl-scripts/06-arrays.jl", "max_stars_repo_name": "Eben60/Labview2Jl.jl", "max_stars_repo_head_hexsha": "71db19eea3fdfafb109b21c30f32da4a80292967", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LabVIEW/LV2Julia_examples/jl-scripts/06-arrays.jl", "max_issues_repo_name": "Eben60/Labview2Jl.jl", "max_issues_repo_head_hexsha": "71db19eea3fdfafb109b21c30f32da4a80292967", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-20T17:55:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T12:15:26.000Z", "max_forks_repo_path": "src/LabVIEW/LV2Julia_examples/jl-scripts/06-arrays.jl", "max_forks_repo_name": "Eben60/Labview2Jl.jl", "max_forks_repo_head_hexsha": "71db19eea3fdfafb109b21c30f32da4a80292967", "max_forks_repo_licenses": ["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": 120, "alphanum_fraction": 0.5783410138, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7655086838842583}}
{"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\u03b1 = 0.013\n\u03b1_q = (1-(1-\u03b1)^3)\nb_param = 0.0124\nd_param = 0.00822\n\u03b2 = 0.98\n\u03b3 = 1.0\n\u03c3 = 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 \u03c4.\n\n\"\"\"\nfunction compute_optimal_quantities(c::AbstractFloat, \u03c4::AbstractFloat)\n    mcm = McCallModel(\u03b1_q,\n                      \u03b2,\n                      \u03b3,\n                      c-\u03c4,                # post-tax compensation\n                      \u03c3,\n                      collect(w_vec-\u03c4),  # post-tax wages\n                      p_vec)\n\n\n    w_bar, V, U = compute_reservation_wage(mcm, return_values=true)\n    \u03bb = \u03b3 * sum(p_vec[w_vec - \u03c4 .> w_bar])\n\n    return w_bar, \u03bb, 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, \u03c4::AbstractFloat)\n    w_bar, \u03bb_param, V, U = compute_optimal_quantities(c, \u03c4)\n\n    # Compute steady state employment and unemployment rates\n    lm = LakeModel(\u03bb=\u03bb_param, \u03b1=\u03b1_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 - \u03c4 .> w_bar)) / sum(p_vec .* (w_vec - \u03c4 .> 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    \u03c4 = brent(steady_state_budget, 0.0, 0.9 * c)\n\n    return \u03c4\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\u03c0, 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\u03c0, Ly = Lx, Lz = Lx,T = Float32)\r\n    #funtion of computing \u2207\u00d7Vector using the fourier method\r\n    # fft(\u2207\u00d7Vector) -> im * k \u00d7 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\u03c0, 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\u03c0, Ly = Lx, Lz = Lx,T = Float32)\r\n    #funtion of computing \u2207\u0307 \u22c5 Vector using the fourier method\r\n    # fft(\u2207\u00b7Vector) -> im * k \u22c5 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\u03c0, 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    \u03a6   = LaplaceSolver(B,grid; Lx=2\u03c0, Ly = Lx, Lz = Lz, T = Float32);\r\n    return \u03a6\r\nend\r\n\r\nfunction LaplaceSolver(B::Array,grid; Lx=2\u03c0, Ly = Lx, Lz = Lz, T = Float32)\r\n    #=\r\n    funtion of computing \u0394\u03a6 = B using the fourier method, must be peroidic condition\r\n    Considering in k-space, k\u00b2 \u03a6' = B', we would get \u03a6 = F(B'/k\u00b2)\r\n    =#\r\n    nx,ny,nz = size(B);\r\n    \u03a6    = 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\u00b2 = x^2 + y^2 + z^2;\r\n       Bh[i,j,k] = Bh[i,j,k]/k\u00b2;\r\n       if k\u00b2 == 0; Bh[i,j,k] = 0; end \r\n    end\r\n    ldiv!(\u03a6, grid.rfftplan, deepcopy(Bh));\r\n    return \u03a6;\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, \u03f5)\n\n``\\\\sqrt{1 + (r/\u03f5)^2}``\n\"\"\"\nmultiquadratic(r, \u03f5) = sqrt(1 + (r/\u03f5)^2)\n\n\"\"\"\n    invmultiquadratic(r, \u03f5)\n\n``\\\\frac{1}{\\\\sqrt{1 + (r/\u03f5)^2}}``\n\"\"\"\ninvmultiquadratic(r, \u03f5) = 1/multiquadratic(r, \u03f5)\n\n\"\"\"\n    gaussian(r, \u03f5)\n\n``e^{-r^2/\u03f5^2}``\n\"\"\"\ngaussian(r, \u03f5) = exp(-r^2/\u03f5^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    \u03f5::T\n    #function weights\n    w::Vector{T}\nend\n\n\"\"\"\n    RBFInterpolator(X, y, \u03f5, 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 \u00d7 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 `\u03f5` scales the radial basis function of choice, `f`, which is [`invmultiquadratic`](@ref) by default. Any function in the form ``\u03d5(r,\u03f5)`` can be passed to the `rbf` argument, where \\$r\\$ is the distance between points and ``\u03f5`` is a scaling factor.\n\"\"\"\nfunction RBFInterpolator(X::AbstractMatrix,\n                         y::AbstractVector,\n                         \u03f5,\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, \u03f5)\n        end\n    end\n    #solve for weights\n    w = Symmetric(A)\\S.y\n    #construct\n    RBFInterpolator(S, rbf, convert(eltype(y), \u03f5), w)\nend\n\nfunction RBF(\u03a6::RBFInterpolator, x)\n    checkdims(x, \u03a6.S.N)\n    y = 0.0\n    for i = 1:\u03a6.S.p\n        #distance\n        r = distance(x, view(\u03a6.S.X,i,:), \u03a6.S.N)\n        #weighted evaluation\n        @inbounds y += \u03a6.w[i]*\u03a6.rbf(r, \u03a6.\u03f5)\n    end\n    return y\nend\n\nfunction (\u03a6::RBFInterpolator)(x::Union{AbstractVector,Tuple})\n    RBF(\u03a6, x)\nend\n\nfunction (\u03a6::RBFInterpolator)(x::Number...)\n    RBF(\u03a6, 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 \u00d7 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(\u03a6::ShepardInterpolator, x)\n    checkdims(x, \u03a6.S.N)\n    n = 0.0\n    d = 0.0\n    for i = 1:\u03a6.S.p\n        #distance\n        r = distance(x, view(\u03a6.S.X,i,:), \u03a6.S.N)\n        #evaluate weighting function\n        f = 1.0/r^\u03a6.a\n        #weigted and unweighted contribution to numertor and denominator\n        @inbounds n += \u03a6.S.y[i]*f\n        d += f\n    end\n    return n/d\nend\n\n(\u03a6::ShepardInterpolator)(x::Union{AbstractVector,Tuple}) = shepard(\u03a6, x)\n\n(\u03a6::ShepardInterpolator)(x::Number...) = shepard(\u03a6, 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": "using Discrete\nusing Base.Test\n\n# write your own tests here\n@test 1 == 1\n\nprintln(\"Differencing tests...\");\nde = (n) -> 2.0^n;\nfor i=1:10000\n  n = rand(0:100);\n  \n  @test de(n) == fdiff(de, n);\n  @test de(n) == fdiff(de, n, order=2);\n  @test de(n) == fdiff(de, n, order=3);\n  @test de(n) == fdiff(de, n, order=4);\n  @test de(n) == fdiff(de, n, order=rand(1:10));\n  @test de(n) == bdiff(de, n);\n  @test de(n) == bdiff(de, n, order=2);\n  @test de(n) == bdiff(de, n, order=3);\n  @test de(n) == bdiff(de, n, order=4);\n  @test de(n) == bdiff(de, n, order=rand(1:10));\nend\n\nf(n)   = n^2;\ndf(n)  = 2*n + 1;\ndbf(n) = 2*n - 1;\nd2f(n) = 2;\nfor i=1:10000\n  n = rand(0:100);\n  \n  @test df(n)  == fdiff(f, n);\n  @test d2f(n) == fdiff(f, n, order=2);\n  @test dbf(n) == bdiff(f, n);\n  @test d2f(n) == bdiff(f, n, order=2);\nend\nprintln(\"Tests passed.\");\n\nprintln(\"Integration tests...\");\nfor n = 4:2:8\n  @test abs(simpsons(x -> 1/x, 1, e, n) - 1.0) < 10.0^(-n/2);\n  @test abs(trapezoid(x -> 1/x, 1, e, n) - 1.0) < 2 * 10.0^(-n/4);\n\n  @test abs(simpsons(x -> sin(x), -\u03c0, \u03c0, n) - 0.0) < 10.0^(-n/2);\n  @test abs(trapezoid(x -> sin(x), -\u03c0, \u03c0, n) - 0.0) < 2 * 10.0^(-n/4);\n  @test abs(simpsons(x -> cos(x), -\u03c0, \u03c0, n) - 0.0) < 10.0^(-n/2);\n  @test abs(trapezoid(x -> cos(x), -\u03c0, \u03c0, n) - 0.0) < 2 * 10.0^(-n/4);\n\n  @test abs(simpsons(x -> x, -1, 1, n) - 0.0) < 10.0^(-n/2);\n  @test abs(trapezoid(x -> x, -1, 1, n) - 0.0) < 3 * 10.0^(-n/4);\n  @test abs(simpsons(x -> x^2, -1, 1, n) - 2/3) < 10.0^(-n/2);\n  @test abs(trapezoid(x -> x^2, -1, 1, n) - 2/3) < 3 * 10.0^(-n/4);\nend\nfor n = 10:2:20\n  @test abs(simpsons(x -> 1/x, 1, e, n) - 1.0) < 5e-5;\n  @test abs(trapezoid(x -> 1/x, 1, e, n) - 1.0) < 5e-2;\n\n  @test abs(simpsons(x -> sin(x), -\u03c0, \u03c0, n) - 0.0) < 5e-5;\n  @test abs(trapezoid(x -> sin(x), -\u03c0, \u03c0, n) - 0.0) < 5e-2;\n  @test abs(simpsons(x -> cos(x), -\u03c0, \u03c0, n) - 0.0) < 5e-5;\n  @test abs(trapezoid(x -> cos(x), -\u03c0, \u03c0, n) - 0.0) < 5e-2;\n\n  @test abs(simpsons(x -> x, -1, 1, n) - 0.0) < 5e-5;\n  @test abs(trapezoid(x -> x, -1, 1, n) - 0.0) < 5e-2;\n  @test abs(simpsons(x -> x^2, -1, 1, n) - 2/3) < 5e-5;\n  @test abs(trapezoid(x -> x^2, -1, 1, n) - 2/3) < 5e-2;\nend\nprintln(\"Tests passed.\");\n", "meta": {"hexsha": "53505a5121dfad3f9eb273cc5e578f23ba23e892", "size": 2172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "grasingerm/Discrete.jl", "max_stars_repo_head_hexsha": "b6a6fda4556fb56226cdb0f65a13d9bed0636b90", "max_stars_repo_licenses": ["MIT"], "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": "grasingerm/Discrete.jl", "max_issues_repo_head_hexsha": "b6a6fda4556fb56226cdb0f65a13d9bed0636b90", "max_issues_repo_licenses": ["MIT"], "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": "grasingerm/Discrete.jl", "max_forks_repo_head_hexsha": "b6a6fda4556fb56226cdb0f65a13d9bed0636b90", "max_forks_repo_licenses": ["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": 70, "alphanum_fraction": 0.4963167587, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7654827210615606}}
{"text": "\"\n  Name     : c4_17_QuantEco_julia.jl\n  Book     : Hands-on Data Science with Anaconda )\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan and James Yan\n  Date     : 1/25/2018\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n\n            https://lectures.quantecon.org/jl/julia_plots.html\n\"\n\nusing QuantEcon: meshgrid\nusing PyPlot:surf\nusing Plots\nn = 50\nx = linspace(-3, 3, n)\ny = x\nz = Array{Float64}(n, n)\nf(x, y) = cos(x^2 + y^2) / (1 + x^2 + y^2)\nfor i in 1:n\n    for j in 1:n\n        z[j, i] = f(x[i], y[j])\n    end\nend\nxgrid, ygrid = meshgrid(x, y)\nsurf(xgrid, ygrid, z',alpha=0.7)", "meta": {"hexsha": "db78181dcf20d1da11d022bb27ae18623eb96a92", "size": 614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter04/c4_17_QuantEcon_julia.jl", "max_stars_repo_name": "andrewjcoxon/Hands-On-Data-Science-with-Anaconda", "max_stars_repo_head_hexsha": "82504a059ecd284b3599fa9af2b3eb6bbd6e28f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-06-25T16:21:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T09:28:29.000Z", "max_issues_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter04/c4_17_QuantEcon_julia.jl", "max_issues_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_issues_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter04/c4_17_QuantEcon_julia.jl", "max_forks_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_forks_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-06-15T02:55:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T15:24:42.000Z", "avg_line_length": 22.7407407407, "max_line_length": 62, "alphanum_fraction": 0.6009771987, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7654827177260866}}
{"text": "export getBoundModel,getBoundModelInv\r\nfunction getBoundModel(m,a,b) \r\n\td = (b-a)./2.0;\r\n\tmid = (b+a)./2.0;\r\n\tv = (1.0./d).*(m - mid);\r\n\ts = d.*(tanh.(v)+1) + a;\r\n\tdsdm = spdiagm(sech.(v).^2)\r\n\treturn s, dsdm\r\nend\r\n\r\nfunction getBoundModelInv(s,a,b)\r\n\td = (b-a)./2.0;\r\n\tmid = (b+a)./2.0;\r\n    m = atanh.((s-a).*(1.0./d)-1) .* d + mid;\r\n\treturn m\r\nend", "meta": {"hexsha": "37b15dbad4d6e51a7ae69f6b6aee6d07c39ad9cf", "size": 350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SeismicUtils/BoundModel.jl", "max_stars_repo_name": "JuliaInv/EikonalInv.jl", "max_stars_repo_head_hexsha": "a80aac59bf2a9ffb32a0d025a718291fed1eed63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-02-14T14:48:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T19:08:33.000Z", "max_issues_repo_path": "src/SeismicUtils/BoundModel.jl", "max_issues_repo_name": "JuliaInv/EikonalInv.jl", "max_issues_repo_head_hexsha": "a80aac59bf2a9ffb32a0d025a718291fed1eed63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-11-24T19:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-24T19:03:28.000Z", "max_forks_repo_path": "src/SeismicUtils/BoundModel.jl", "max_forks_repo_name": "JuliaInv/EikonalInv.jl", "max_forks_repo_head_hexsha": "a80aac59bf2a9ffb32a0d025a718291fed1eed63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-11-24T18:34:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:40.000Z", "avg_line_length": 21.875, "max_line_length": 46, "alphanum_fraction": 0.5257142857, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365572, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7654827131665465}}
{"text": "library( Matrix )\r\n\r\nstr_path <- \"C:\\\\CBIG\\\\ZD\\\\\"\r\n\r\nmyd <- read.csv( paste0( str_path, \"logistic_regression_ex2.csv\" ) )\r\n\r\nx <- as.matrix( myd[, -c( 1 )] )\r\ny <- myd[, c(1)]\r\n\r\n## make sure its rank = # columns\r\nncol( x )\r\nrankMatrix( x )\r\n\r\nmyglm <- glm( y ~ -1 + x, family = binomial( link = logit ) )\r\n\r\nmyglm_coeff <- summary( myglm )$coefficients\r\n\r\nrownames( myglm_coeff ) <- c( paste0( \"beta\", seq( 1, 3 ) ), paste0( \"creative_break_\", seq( 1, 4 ) ) )\r\n\r\nprint( myglm_coeff )\r\n\r\n## using optim to reproduce the estimates\r\n\r\nLoglikelihood <- function( beta )\r\n{\r\n\txbeta <- x %*% beta\r\n\tLi <- -1 * y * xbeta + log( 1 + exp( xbeta )) \r\n\tsum( Li )\r\n}\r\n\r\nbeta_start_value <- as.matrix( rep( 0.0, ncol( x ) ), ncol(x), 1 )\r\n\r\nmyoptim <- optim( beta_start_value, fn = Loglikelihood, gr = NULL, method = \"BFGS\", hessian = TRUE )\r\n\r\nvar_cov_m <- solve( myoptim$hessian )\r\n\r\nbeta_se <- sqrt( diag( var_cov_m ) )\r\n\r\nzvalue <- myoptim$par / beta_se\r\n\r\npvalue <- 2 * ( 1 - pnorm(abs( zvalue ) ) )\r\n\r\ncoeff_outputs <- cbind( myoptim$par, beta_se, zvalue, round( pvalue, 6 ) )\r\n\r\ncolnames( coeff_outputs ) <- c( \"Estimates\", \"Std. Error\", \"z value\", \"Pr(>|z|)\" )\r\nrownames( coeff_outputs ) <- c( paste0( \"beta\", seq( 1, 3 ) ), paste0( \"creative_break_\", seq( 1, 4 ) ) )\r\nprint( coeff_outputs )\r\n\r\nprint( summary( myglm )$coefficients ) \r\n\r\n#######################################################################\r\n\r\n## this is the residual deviance\r\n2 * myoptim$value\r\n\r\n########## since colmn 4 to column 7 are indicators, assuming they are the compaign breaks :)\r\n##### so we want to add penalty function to make the estimates >= 0, using the penalty that Zhiyuan recommended\r\n\r\n## assuming the penalty function is : \r\n\r\na <- c( 1000, 9, 60 )\r\n\r\nPenalized_Loglikelihood <- function( beta )\r\n{\r\n\txbeta <- x %*% beta\r\n\tLi <- -1 * y * xbeta + log( 1 + exp( xbeta ))\r\n\t## constraining beta[3] to beta[7]\r\n\tmyPenValue <- 0\r\n\tfor ( i in 4 : 7 )\r\n\t{\r\n\t\tmyPenValue <- myPenValue + a[1] * exp( -1.0 * a[2] * exp( a[3] * beta[ i ] ) )\r\n\t}\r\n\tsum( Li ) + myPenValue\r\n}\r\n\r\nbeta_start_value <- as.matrix( rep( 0.0, ncol( x ) ), ncol(x), 1 )\r\n\r\nmyoptim_Penalized <- optim( beta_start_value, fn = Penalized_Loglikelihood, gr = NULL, method = \"BFGS\", hessian = TRUE)\r\n\r\nmyoptim_Penalized\r\n\r\nvar_cov_m <- solve( myoptim_Penalized$hessian )\r\n\r\nbeta_se <- sqrt( diag( var_cov_m ) )\r\n\r\nzvalue <- myoptim_Penalized$par / beta_se\r\n\r\npvalue <- 2 * ( 1 - pnorm(abs( zvalue ) ) )\r\n\r\ncoeff_outputs <- cbind( myoptim_Penalized$par, beta_se, zvalue, round( pvalue, 6 ) )\r\n\r\ncolnames( coeff_outputs ) <- c( \"Estimates\", \"Std. Error\", \"z value\", \"Pr(>|z|)\" )\r\nrownames( coeff_outputs ) <- c( paste0( \"beta\", seq( 1, 3 ) ), paste0( \"creative_break_\", seq( 1, 4 ) ) )\r\n\r\nprint( coeff_outputs )\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "b8b9a93f89f311f2bf059f6eb6dab9f8186dff2d", "size": 2769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StatOpt/ex2_for_Lampros.R.jl", "max_stars_repo_name": "werbac/jlib", "max_stars_repo_head_hexsha": "550028b19c4c51a4ba6b27e3b2696ee5cef0a235", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StatOpt/ex2_for_Lampros.R.jl", "max_issues_repo_name": "werbac/jlib", "max_issues_repo_head_hexsha": "550028b19c4c51a4ba6b27e3b2696ee5cef0a235", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/StatOpt/ex2_for_Lampros.R.jl", "max_forks_repo_name": "werbac/jlib", "max_forks_repo_head_hexsha": "550028b19c4c51a4ba6b27e3b2696ee5cef0a235", "max_forks_repo_licenses": ["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.1470588235, "max_line_length": 120, "alphanum_fraction": 0.5911881546, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7654827104583838}}
{"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\u0305, sys.body[i].v\u0305)\n        for j = 1:length(sys.body)\n\n            if i \u2260 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\u0305 .- sys.body[i].r\u0305)\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\u0305, sys.body[i].v\u0305) for i \u2208 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": "let\n    f(X) = (10 - X[1, 1])^2 + (0 - X[1, 2])^2 + (0 - X[2, 1])^2 + (5 - X[2, 2])^2\n\n    function g!(X, S)\n        S[1, 1] = -20 + 2 * X[1, 1]\n        S[1, 2] = 2 * X[1, 2]\n        S[2, 1] = 2 * X[2, 1]\n        S[2, 2] = -10 + 2 * X[2, 2]\n        return\n    end\n\n    res = optimize(f, g!, eye(2), method = GradientDescent())\n\n    @test norm(vec(Optim.minimizer(res) - [10.0 0.0; 0.0 5.0])) < 10e-8\n\n    # TODO: Get finite differencing to work for generic arrays as well\n    # optimize(f, eye(2), method = :gradient_descent)\nend\n", "meta": {"hexsha": "94f7328b8c5e95d83f05e3c3dbdbb8d0074512d9", "size": 530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/array.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": "test/array.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": "test/array.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": 27.8947368421, "max_line_length": 81, "alphanum_fraction": 0.4679245283, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8006919925839876, "lm_q1q2_score": 0.765446611110211}}
{"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; \u03b1, \u03c9) = -x * tand(\u03b1) + 500sin(\u03c9*x)*sin(\u03c9*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; \u03b1 = 0.5, \u03c9 = 2\u03c0/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; \u03b1 = 0.5, \u03c9 = 2\u03c0/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)) \u00f7 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": "using Distributions\nusing IndependentRandomSequences\nusing Base.Test\n\n\n#IID tests\nW = Uniform(-1,1)\nN = 2\nY = IIDRandomSequence(W,N)\n\n@test insupport(Y,[0,0]) == true\n@test insupport(Y,[-1,1]) == true\n@test insupport(Y,[-2,0]) == false\n@test insupport(Y,[0,0,0]) == false\n\n@test pdf(Y,[0., 0.]) == 1/4\n@test pdf(Y,[2., 0.]) == 0.\n@test pdf(Y,[0. 0. ; 2. 0.]') == [1/4, 0.]\n\n@test mean(Y) == [0., 0.]\n@test var(Y) == [1/3, 1/3]\n\n#INID tests, homogenous types\nW,X = Uniform(-1,1),Uniform(0,1)\nY = INIDRandomSequence([W,X])\n\n@test insupport(Y,[0,0]) == true\n@test insupport(Y,[-1,1/2]) == true\n@test insupport(Y,[-2,0]) == false\n@test insupport(Y,[0,0,0]) == false\n\n@test pdf(Y,[0., 1/2]) == 1/2\n@test pdf(Y,[2., 1/2]) == 0.\n@test pdf(Y,[0. 1/2;  2. 0.]') == [1/2, 0.]\n\n@test mean(Y) == [0., 1/2]\n@test var(Y) == [1/3, 1/12]\n\n#INID test, hetergeneous types\nW,X = Binomial(3,.5),Bernoulli(.5)\nY = INIDRandomSequence([W,X])\n\n@test insupport(Y,[3,0]) == true\n@test insupport(Y,[-2,0]) == false\n@test insupport(Y,[0,0,0]) == false\n\n@test cov(Y) == [3/4 0;0 1/4]\n", "meta": {"hexsha": "081610fe5f9a75a4fa0e375cf39786c98f302cea", "size": 1055, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "tkelman/IndependentRandomSequences.jl", "max_stars_repo_head_hexsha": "00ee01326fd32ff7a2b0916d68534268c157177a", "max_stars_repo_licenses": ["MIT"], "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": "tkelman/IndependentRandomSequences.jl", "max_issues_repo_head_hexsha": "00ee01326fd32ff7a2b0916d68534268c157177a", "max_issues_repo_licenses": ["MIT"], "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": "tkelman/IndependentRandomSequences.jl", "max_forks_repo_head_hexsha": "00ee01326fd32ff7a2b0916d68534268c157177a", "max_forks_repo_licenses": ["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.9791666667, "max_line_length": 43, "alphanum_fraction": 0.5744075829, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7654398946138944}}
{"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": "#<----Bayes Theorem---->\n#P = prob, A = prior, B = Evidence,\n\"\"\"\n    ## Bayes Theorem\n    ### Description\n      Bayes theorem takes probability, prior observations, and evidence\n      as percentages and will return a posterior.\\n\n      --------------------\\n\n    ### Input\n      bay_ther(p, a, b)\\n\n      --------------------\\n\n      #### Positional Arguments\n      Float64 - p:: A percentage representing probability.\\n\n      Float64 - a:: A percentage representing prior. <- Float64\\n\n      Float64 - b:: A percentage representing evidence. <- Float64\\n\n      --------------------\\n\n     ### Output\n     P:: Posterior value.\n       \"\"\"\nfunction bay_ther(p,a,b)\n    psterior = (p*(b|a) * p*(a)) / (p*b)\n    return(psterior)\nend\n\"\"\"\n    ## Conditional Probability\n    ### Description\n      Performs Bayesian Conditional Probability with probability, prior, and\n      evidence.\\n\n      --------------------\\n\n      ### Input\n        cond_prob(p, a, b)\\n\n        --------------------\\n\n        #### Positional Arguments\n        Float64 - p:: A percentage representing probability.\\n\n        Float64 - a:: A percentage representing prior. <- Float64\\n\n        Float64 - b:: A percentage representing evidence. <- Float64\\n\n        --------------------\\n\n       ### Output\n       P:: Posterior value.\n       \"\"\"\nfunction cond_prob(p,a,b)\n    psterior = bay_ther(p,a,b)\n    cond = p*(a|b)\n    return(cond)\nend\n", "meta": {"hexsha": "6d9d351a5de829ff68b7c3ddd8c1f853370b2957", "size": 1405, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats/bayesian.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/bayesian.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/bayesian.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": 30.5434782609, "max_line_length": 76, "alphanum_fraction": 0.5338078292, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7654398831383246}}
{"text": "using MPFR_wrap\n\nconst atol = BigFloat(\"1e-100000\")\nconst prec = 333_000\nconst \u03c0_MPFR = BigFloat(\u03c0, 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, \u03c0_prev = big(1.0) / 2, big(4.0)\n    \u03c0_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        \u03c0_next = 2a_next^2 / s_next\n        #println(\"$k -> $pn\")\n        \u03b4\u03c0 = \u03c0_next - \u03c0_prev\n        abs(\u03b4\u03c0) \u2264 atol && break\n        a_prev, b_prev, s_prev, \u03c0_prev = a_next, b_next, s_next, \u03c0_next\n        k += 1\n        p2 *= 2\n    end\n    setprecision(BigFloat, old_prec)\n    @assert isapprox(\u03c0_next, \u03c0_MPFR, atol=atol)\n    (k, \u03c0_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    \u03c0_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    \u03c0_next = BigFloat(precision=prec)\n    \u03b4\u03c0 = 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!(\u03c0_next, a_next)\n        mul_2!(\u03c0_next, \u03c0_next, Int32(1))\n        div!(\u03c0_next, \u03c0_next, s_next)\n\n        sub!(\u03b4\u03c0, \u03c0_next, \u03c0_prev)\n        abs(\u03b4\u03c0) \u2264 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        \u03c0_prev, \u03c0_next = \u03c0_next, \u03c0_prev\n\n        k += Int32(1)\n    end\n    @assert isapprox(\u03c0_next, \u03c0_MPFR, atol=atol)\n    (k, \u03c0_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    \u03c0_prev = BigFloat(0, precision=prec)\n    \u03c0_next = BigFloat(precision=prec)\n    \u03b4\u03c0 = 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!(\u03c0_next, Int32(1), a_next)\n        sub!(\u03b4\u03c0, \u03c0_next, \u03c0_prev)\n        abs(\u03b4\u03c0) \u2264 atol && break\n\n        a_prev, a_next = a_next, a_prev\n        s_prev, s_next = s_next, s_prev\n        \u03c0_prev, \u03c0_next = \u03c0_next, \u03c0_prev\n\n        k += Int32(1)\n    end\n    @assert isapprox(\u03c0_next, \u03c0_MPFR, atol=atol)\n    (k, \u03c0_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": "\nusing GeometricIntegrators.BasisFunctions\nusing GeometricIntegrators.CommonFunctions\nusing Test\n\ninclude(\"vandermonde_tests.jl\")\ninclude(\"lagrange_basis_tests.jl\")\ninclude(\"lagrange_polynomials_tests.jl\")\n", "meta": {"hexsha": "09c0e019ee8d011ca2e899ac380a4474f6dc2f4e", "size": 206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basis_functions/basis_functions_tests.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": "test/basis_functions/basis_functions_tests.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": "test/basis_functions/basis_functions_tests.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": 22.8888888889, "max_line_length": 42, "alphanum_fraction": 0.8640776699, "num_tokens": 52, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7654377170746255}}
{"text": "include(\"./Legendre_polynomials.jl\")\n\nfunction Spherical_harmonics_a!(x::Float64, lmax::Int64;\n                                Y\u2097 = nothing, P\u2097 = nothing) \n    #### Returns an array of size lmax_half. Each cell contains one (even axisymmetric) spherical harmonic at point cos(\u03b8) = 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\u2097)\n        Y\u2097 = zeros(lmax_half) # WIll hold the spherical harmonics\n    end\n    if isnothing(P\u2097)\n        P\u2097 = 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\u2097 = P\u2097)\n\n    # let's compute the spherical harmonics\n    for l_half = 1:lmax_half\n        l = 2 * l_half\n        Y\u2097[l_half] = P\u2097[l_half] * sqrt((2 * l + 1) / (4 * \u03c0)) # Y\u2097\u2080 = P\u2097\u2080 * sqrt((2 l + 1) / 4 \u03c0)\n    end\n\n    return(Y\u2097)\nend\n\nfunction Spherical_harmonics!(\u03b8::Float64, \u03d5::Float64, lmax::Int64; \n                                Y\u2097\u2098 = nothing, P\u2097\u2098 = nothing) \n    #### Returns an array of size lmax_half * (2 lmax + 1). Each cell contains one (even) spherical harmonic at point (\u03b8, \u03d5) ####\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\u2097\u2098)\n        Y\u2097\u2098 = zeros(2 * lmax + 1, lmax_half) # Will hold the spherical harmonics\n    end\n    if isnothing(P\u2097\u2098)\n        P\u2097\u2098 = 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(\u03b8), lmax, P = P\u2097\u2098)\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\u2097\u2098 to Y\u2097\u2098 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\u2097\u2098[lmax + 1 - m, l_half] = (-1)^(m) * sqrt(2) * P\u2097\u2098[m + 1, l_half] * sin(m * \u03d5)\n                Y\u2097\u2098[lmax + 1 + m, l_half] = (-1)^(m) * sqrt(2) * P\u2097\u2098[m + 1, l_half] * cos(m * \u03d5)\n            else\n                Y\u2097\u2098[lmax + 1, l_half] = P\u2097\u2098[1, l_half]\n            end\n        end\n    end\n\n    return(Y\u2097\u2098)\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 [-\u03c0, \u03c0], y \\in [-\u03c0, \u03c0] `` and  `` t \\in [0, 200\u03c0] ``\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\u03c0 ./ (xmax-xmin) .* [0:nx\u00f72-1;nx\u00f72-nx:-1]\n        ky  = 2\u03c0 ./ (ymax-ymin) .* [0:ny\u00f72-1;ny\u00f72-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( -\u03c0, \u03c0, 64, -\u03c0, \u03c0, 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!(-\u03c0,\u03c0)\n       ylims!(-\u03c0,\u03c0)\n        \n    end\n\n    anim\n    \nend\n\n#md # ---\n\nanim = animation( 2\u03c0, 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( -\u03c0, \u03c0, 1024, -\u03c0, \u03c0, 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": "@testset \"DirectPowers\" begin\n\n   \u00d7(a,b) = Groups.DirectPower(a,b)\n\n   @testset \"Constructors\" begin\n      G = PermutationGroup(3)\n\n      @test Groups.DirectPowerGroup(G,2) isa AbstractAlgebra.Group\n      @test G\u00d7G isa AbstractAlgebra.Group\n      @test Groups.DirectPowerGroup(G,2) isa Groups.DirectPowerGroup{2, Generic.PermGroup{Int64}}\n\n      @test (G\u00d7G)\u00d7G == DirectPowerGroup(G, 3)\n      @test (G\u00d7G)\u00d7G == (G\u00d7G)\u00d7G\n\n      GG = DirectPowerGroup(G,2)\n      @test (G\u00d7G)() isa GroupElem\n      @test (G\u00d7G)((G(), G())) isa GroupElem\n      @test (G\u00d7G)([G(), G()]) isa GroupElem\n\n      @test Groups.DirectPowerGroupElem((G(), G())) == (G\u00d7G)()\n      @test GG(G(), G()) == (G\u00d7G)()\n\n      g = perm\"(1,2,3)\"\n\n      @test GG(g, g^2) isa GroupElem\n      @test GG(g, g^2) isa Groups.DirectPowerGroupElem{2, Generic.perm{Int64}}\n\n      h = GG(g,g^2)\n\n      @test h == GG(h)\n\n      @test GG(g, g^2) isa GroupElem\n      @test GG(g, g^2) isa Groups.DirectPowerGroupElem\n\n      @test_throws MethodError GG(g,g,g)\n      @test GG(g,g^2) == h\n\n      @test h[1] == g\n      @test h[2] == g^2\n      h = GG(g, G())\n      @test h == GG(g, G())\n   end\n\n   @testset \"Basic arithmetic\" begin\n      G = PermutationGroup(3)\n      GG = G\u00d7G\n      i = perm\"(1,3)\"\n      g = perm\"(1,2,3)\"\n      \n      h = GG(g,g^2)\n      k = GG(g^3, g^2)\n\n      @test h^2 == GG(g^2,g)\n      @test h^6 == GG()\n\n      @test h*h == h^2\n      @test h*k == GG(g,g)\n\n      @test h*inv(h) == (G\u00d7G)()\n      \n      w = GG(g,i)*GG(i,g)\n      @test w == GG(perm\"(1,2)(3)\", perm\"(2,3)\")\n      @test w == inv(w)\n      @test w^2 == w*w == GG()\n   end\n\n   @testset \"elem/parent_types\" begin\n      G = PermutationGroup(3)\n      g = perm\"(1,2,3)\"\n\n      @test elem_type(G\u00d7G) == DirectPowerGroupElem{2, elem_type(G)}\n      @test elem_type(G\u00d7G\u00d7G) == DirectPowerGroupElem{3, elem_type(G)}\n      @test parent_type(typeof((G\u00d7G)(g,g^2))) == Groups.DirectPowerGroup{2, typeof(G)}\n      @test parent(DirectPowerGroupElem((g,g^2,g^3))) == DirectPowerGroup(G,3)\n\n      F = AdditiveGroup(GF(13))\n\n      @test elem_type(F\u00d7F) == \n         DirectPowerGroupElem{2, Groups.AddGrpElem{AbstractAlgebra.gfelem{Int}}}\n      @test parent_type(typeof((F\u00d7F)(1,5))) == \n         Groups.DirectPowerGroup{2, Groups.AddGrp{AbstractAlgebra.GFField{Int}}}\n      parent((F\u00d7F)(1,5)) == DirectPowerGroup(F,2)\n      \n      F = MultiplicativeGroup(GF(13))\n\n      @test elem_type(F\u00d7F) == \n         DirectPowerGroupElem{2, Groups.MltGrpElem{AbstractAlgebra.gfelem{Int}}}\n      @test parent_type(typeof((F\u00d7F)(1,5))) == \n         Groups.DirectPowerGroup{2, Groups.MltGrp{AbstractAlgebra.GFField{Int}}}\n      parent((F\u00d7F)(1,5)) == DirectPowerGroup(F,2)\n   end\n\n   @testset \"Additive/Multiplicative groups\" begin\n\n      R, x = PolynomialRing(QQ, \"x\")\n      F, a = NumberField(x^3 + x + 1, \"a\")\n      G = PermutationGroup(3)\n\n      @testset \"MltGrp basic functionality\" begin\n         Gr = MltGrp(F)\n         @test Gr(a) isa MltGrpElem\n         g = Gr(a)\n         @test deepcopy(g) isa MltGrpElem\n         @test inv(g) == Gr(a^-1)\n         @test Gr() == Gr(1)\n         @test inv(g)*g == Gr()\n      end\n\n      @testset \"AddGrp basic functionality\" begin\n         Gr = AddGrp(F)\n         @test Gr(a) isa AddGrpElem\n         g = Gr(a)\n         @test deepcopy(g) isa AddGrpElem\n         @test inv(g) == Gr(-a)\n         @test Gr() == Gr(0)\n         @test inv(g)*g == Gr()\n      end\n   end\n\n   @testset \"Direct Product of Multiplicative Groups\" begin\n\n      R, x = PolynomialRing(QQ, \"x\")\n      F, a = NumberField(x^3 + x + 1, \"a\")\n      FF = Groups.DirectPowerGroup(MltGrp(F),2)\n\n      @test FF([a,1]) isa GroupElem\n      @test FF([a,1]) isa DirectPowerGroupElem\n      @test FF([a,1]) isa DirectPowerGroupElem{2, MltGrpElem{elem_type(F)}}\n      @test_throws DomainError FF(1,0)\n      @test_throws DomainError FF([0,1])\n      @test_throws DomainError FF([1,0])\n\n      @test MltGrp(F) isa AbstractAlgebra.Group\n      @test MltGrp(F) isa MultiplicativeGroup\n      @test DirectPowerGroup(MltGrp(F), 2) isa AbstractAlgebra.Group\n      @test DirectPowerGroup(MltGrp(F), 2) isa DirectPowerGroup{2, MltGrp{typeof(F)}}\n\n      F, a = NumberField(x^3 + x + 1, \"a\")\n      FF = DirectPowerGroup(MltGrp(F), 2)\n\n      @test FF(a,a+1) == FF([a,a+1])\n      @test FF([1,a+1])*FF([a,a]) == FF(a,a^2+a)\n      x, y = FF([1,a]), FF([a^2,1])\n      @test x*y == FF([a^2, a])\n      @test inv(x) == FF([1,-a^2-1])\n\n      @test parent(x) == FF\n   end\n\n   @testset \"Direct Product of Additive Groups\" begin\n\n      R, x = PolynomialRing(QQ, \"x\")\n      F, a = NumberField(x^3 + x + 1, \"a\")\n\n      # Additive Group\n      @test AddGrp(F) isa AbstractAlgebra.Group\n      @test AddGrp(F) isa AdditiveGroup\n      @test DirectPowerGroup(AddGrp(F), 2) isa AbstractAlgebra.Group\n      @test DirectPowerGroup(AddGrp(F), 2) isa DirectPowerGroup{2, AddGrp{typeof(F)}}\n\n      FF = DirectPowerGroup(AdditiveGroup(F), 2)\n\n      @test FF([0,a]) isa AbstractAlgebra.GroupElem\n      @test FF(F(0),a) isa DirectPowerGroupElem\n      @test FF(0,0) isa DirectPowerGroupElem{2, AddGrpElem{elem_type(F)}}\n\n      @test FF(F(1),a+1) == FF([1,a+1])\n\n      @test FF([F(1),a+1])*FF([a,a]) == FF(1+a,2a+1)\n\n      x, y = FF([1,a]), FF([a^2,1])\n      @test x*y == FF(a^2+1, a+1)\n      @test inv(x) == FF([F(-1),-a])\n\n      @test parent(x) == FF\n   end\n\n   @testset \"Misc\" begin\n      F = GF(5)\n\n      FF = DirectPowerGroup(AdditiveGroup(F),2)\n      @test order(FF) == 25\n\n      elts = vec(collect(FF))\n      @test length(elts) == 25\n      @test all([g*inv(g) == FF() for g in elts])\n      @test all(inv(g*h) == inv(h)*inv(g) for g in elts for h in elts)\n\n      FF = DirectPowerGroup(MultiplicativeGroup(F), 3)\n      @test order(FF) == 64\n\n      elts = vec(collect(FF))\n      @test length(elts) == 64\n      @test all([g*inv(g) == FF() for g in elts])\n      @test all(inv(g*h) == inv(h)*inv(g) for g in elts for h in elts)\n\n\n      G = PermutationGroup(3)\n      GG = Groups.DirectPowerGroup(G,3)\n      @test order(GG) == 216\n\n      @test isa(collect(GG), Vector{Groups.DirectPowerGroupElem{3, elem_type(G)}})\n      elts = vec(collect(GG))\n\n      @test length(elts) == 216\n      @test all([g*inv(g) == GG() for g in elts])\n      @test all(inv(g*h) == inv(h)*inv(g) for g in elts for h in elts)\n   end\nend\n", "meta": {"hexsha": "120634c0e37be1073c252f52a587124094c02d2d", "size": 6226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DirectPower-tests.jl", "max_stars_repo_name": "mojishoki/Groups.jl", "max_stars_repo_head_hexsha": "9019a3df406e2806061f927bc91ec9378c7c4e5e", "max_stars_repo_licenses": ["MIT"], "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/DirectPower-tests.jl", "max_issues_repo_name": "mojishoki/Groups.jl", "max_issues_repo_head_hexsha": "9019a3df406e2806061f927bc91ec9378c7c4e5e", "max_issues_repo_licenses": ["MIT"], "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/DirectPower-tests.jl", "max_forks_repo_name": "mojishoki/Groups.jl", "max_forks_repo_head_hexsha": "9019a3df406e2806061f927bc91ec9378c7c4e5e", "max_forks_repo_licenses": ["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.6476190476, "max_line_length": 97, "alphanum_fraction": 0.5584645037, "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320945, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7654377056427459}}
{"text": "\"\"\"\n\nThe chemostat steady state impose a contraint over the exchanges:\n\n``intake <= c/\u03be``\n    \nwhere ``c`` is the concentration of the metabolite in the medium and ``\u03be`` is the cell-specific dilution rate.\nTogether with the thermodinamic bound we have\n\nstst_bound(c, \u03be, b) = sign(b) * min(c/ \u03be, abs(b))\n\n\"\"\"\nstst_bound(c, \u03be, b) = sign(b) * min(c/ \u03be, 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": "###\n  Name     : c7_22_optim.jl\n  Book     : Hands-on Data Science with Anaconda )\n  Publisher: Packt Publishing Ltd. \n  Author   : Yuxing Yan and James Yan\n  Date     : 3/15/2018\n  email    : yany@canisius.edu\n             paulyxy@hotmail.com\n###\n\n\n\nusing Optim\nfunction g!(s, x)\n s[1] = -2.0*(1.0-x[1])-400.0*(x[2]-x[1]^2)*x[1]\n s[2] = 200.0*(x[2]-x[1]^2)\nend\nlower = [1.25, -2.1]\nupper = [Inf, Inf]\ninitial_x = [2.0, 2.0]\nod = OnceDifferentiable(f, g!, initial_x)\nresults = optimize(od, initial_x,lower,upper,Fminbox{GradientDescent}())", "meta": {"hexsha": "d42109170c1649d82b83ec132deb0588ac4d1fe9", "size": 539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter07/c7_22_optim.jl", "max_stars_repo_name": "andrewjcoxon/Hands-On-Data-Science-with-Anaconda", "max_stars_repo_head_hexsha": "82504a059ecd284b3599fa9af2b3eb6bbd6e28f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-06-25T16:21:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T09:28:29.000Z", "max_issues_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter07/c7_22_optim.jl", "max_issues_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_issues_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hands-On-Data-Science-with-Anaconda-master/Hands-On-Data-Science-with-Anaconda-master/Chapter07/c7_22_optim.jl", "max_forks_repo_name": "manual123/Nacho-Jupyter-Notebooks", "max_forks_repo_head_hexsha": "e75523434b1a90313a6b44e32b056f63de8a7135", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-06-15T02:55:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T15:24:42.000Z", "avg_line_length": 24.5, "max_line_length": 72, "alphanum_fraction": 0.6103896104, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7654377016384027}}
{"text": "using HypothesisTests, Base.Test\nusing HypothesisTests: default_tail\n\n## ONE SAMPLE T-TEST\n\n# One sample\n@test pvalue(OneSampleTTest(-5:5)) == 1\n\ntst = OneSampleTTest(-5:10)\n@test abs(pvalue(tst) - 0.0530) <= 1e-4\n@test abs(pvalue(tst; tail=:left) - 0.9735) <= 1e-4\n@test abs(pvalue(tst; tail=:right) - 0.0265) <= 1e-4\n@test default_tail(tst) == :both\nshow(IOBuffer(), tst)\n\ntst = OneSampleTTest(mean(-5:10), std(-5:10), 16)\n@test abs(pvalue(tst) - 0.0530) <= 1e-4\n\n@test all(abs.([confint(tst)...;] - [-0.0369, 5.0369]) .<= 1e-4)\n@test all(abs.([confint(tst, 0.1)...;] - [0.4135, 4.5865]) .<= 1e-4)\nc = confint(tst; tail=:left)\n@test c[1] == -Inf\n@test abs(c[2] - 4.5865) .<= 1e-4\nc = confint(tst; tail=:right)\n@test abs(c[1] - 0.4135) .<= 1e-4\n@test c[2] == Inf\nshow(IOBuffer(), tst)\n\ntst = OneSampleTTest(-10:5)\n@test abs(pvalue(tst) - 0.0530) <= 1e-4\n@test abs(pvalue(tst; tail=:left) - 0.0265) <= 1e-4\n@test abs(pvalue(tst; tail=:right) - 0.9735) <= 1e-4\n@test all(abs.([confint(tst)...] - [-5.0369, 0.0369]) .<= 1e-4)\n@test abs.(confint(tst; tail=:left)[2] - (-0.4135)) .<= 1e-4\n@test abs.(confint(tst; tail=:right)[1] - (-4.5865)) .<= 1e-4\nshow(IOBuffer(), tst)\n\n# Paired samples\n@test abs(pvalue(OneSampleTTest([1, 1, 2, 1, 0], [0, 1, 1, 1, 0])) - 0.1778) <= 1e-4\n\n## TWO SAMPLE T-TESTS\n\n# From http://en.wikipedia.org/w/index.php?title=Student%27s_t-test&oldid=526762741\n\na1 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99]\na2 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98]\n\ntst = EqualVarianceTTest(a1, a2)\n@test tst.df == 10\n@test abs(tst.t - 1.959) <= 1e-3\n@test abs(pvalue(tst) - 0.078) <= 1e-3\n@test all(abs.([confint(tst)...] - [-0.0131, 0.2031]) .<= 1e-4)\n@test default_tail(tst) == :both\nshow(IOBuffer(), tst)\n\ntst = UnequalVarianceTTest(a1, a2)\n@test abs(tst.df - 7.03) <= 0.01\n@test abs(tst.t - 1.959) <= 1e-3\n@test abs(pvalue(tst) - 0.091) <= 1e-3\n@test all(abs.([confint(tst)...] - [-0.0196, 0.2096]) .<= 1e-4)\n@test default_tail(tst) == :both\nshow(IOBuffer(), tst)\n", "meta": {"hexsha": "efc735831eedb967ddb0e4520776bdf12515797d", "size": 1981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/t.jl", "max_stars_repo_name": "kalmarek/HypothesisTests.jl", "max_stars_repo_head_hexsha": "b28a4587fe441d1da0479c0791e5f9fd2120cb6b", "max_stars_repo_licenses": ["MIT"], "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/t.jl", "max_issues_repo_name": "kalmarek/HypothesisTests.jl", "max_issues_repo_head_hexsha": "b28a4587fe441d1da0479c0791e5f9fd2120cb6b", "max_issues_repo_licenses": ["MIT"], "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/t.jl", "max_forks_repo_name": "kalmarek/HypothesisTests.jl", "max_forks_repo_head_hexsha": "b28a4587fe441d1da0479c0791e5f9fd2120cb6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T22:55:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T22:55:40.000Z", "avg_line_length": 31.4444444444, "max_line_length": 84, "alphanum_fraction": 0.6102978294, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7654243689817752}}
{"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    (\u03b2,c,\u03b3,\u03b4t) = 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*\u03b4t)\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() < \u03b2\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() < \u03b3\r\n                du[i] = Recovered\r\n            end\r\n        end\r\n    end\r\n    nothing\r\nend\r\n\r\n\u03b4t = 0.1\r\nnsteps = 400\r\ntf = nsteps*\u03b4t\r\ntspan = (0.0,nsteps)\r\nt = 0:\u03b4t:tf;\r\n\u03b2 = 0.05\r\nc = 10.0\r\n\u03b3 = rate_to_proportion(0.25,\u03b4t)\r\np = [\u03b2,c,\u03b3,\u03b4t]\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 = (\u03c0*\u03c0)*(fqdom^2.0)\n\tnt = length(tgrid)\n\t\u03b4t = 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\u03b8=rand(Uniform(-Float64(pi),Float64(pi)))\n\tfor i in eachindex(W)\n\t\tW[i]=W[i]*complex(cos(\u03b8),sin(\u03b8))\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\u03bb::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\u03bb::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\u03bb, 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\u03bb::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\u03bb, 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\u03bb` in the medium.\nThe model has `n\u03bb` wavelengths, and the maximum modeling time is determined by `tmaxfrac`.\n`epsilon` is Courant number.\n\"\"\"\nfunction get_fqdom_tgrid( mod::Medium, n\u03bb::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\u03bbdom=d*inv(real(n\u03bb))\n\n\t# average P velocity\n\tvavg=mod.ref[:vp]\n\n\tfqdom = vavg/\u03bbdom\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\u03b4min = 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\u03b4t=epsilon*\u03b4min/vmax\n\n\t# check if \u03b4t is reasonable\n\t#(\u03b4t > 0.1/fqdom) : error(\"decrease spatial sampling or n\u03bb\")\n\n\ttgrid=range(0.0, stop=tmax, step=\u03b4t)\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": "# test initilization functions\n\nX = rand(8, 12)\n\n# randinit\n\nW, H = NMF.randinit(X, 5)\n@test size(W) == (8, 5)\n@test size(H) == (5, 12)\n@test all(W .>= 0.0)\n@test all(H .>= 0.0)\n\nW, H = NMF.randinit(X, 5; zeroh=true)\n@test size(W) == (8, 5)\n@test size(H) == (5, 12)\n@test all(W .>= 0.0)\n@test all(H .== 0.0)\n\nW, H = NMF.randinit(X, 5; normalize=true)\n@test size(W) == (8, 5)\n@test size(H) == (5, 12)\n@test all(W .>= 0.0)\n@test all(H .>= 0.0)\n@test vec(sum(W, 1)) \u2248 ones(5)\n\n## nndsvd\n\nW, H = NMF.nndsvd(X, 5)\n@test size(W) == (8, 5)\n@test size(H) == (5, 12)\n@test all(W .>= 0.0)\n@test all(H .>= 0.0)\n@test vec(sum(abs2, W, 1)) \u2248 ones(5) atol=1.0e-8\n\nW2, H2 = NMF.nndsvd(X, 5; zeroh=true)\n@test size(W) == (8, 5)\n@test size(H) == (5, 12)\n@test all(W2 .== W)\n@test all(H2 .== 0.0)\n\nW, H = NMF.nndsvd(X, 5; variant=:ar)\n@test all(W .> 0.0)\n# NMF.printf_mat(W)\n", "meta": {"hexsha": "0710e0c158213565168be9aec036cf1d97b349f3", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/initialization.jl", "max_stars_repo_name": "portugueslab/NMF.jl", "max_stars_repo_head_hexsha": "a89658e3492b5e80428da2abec360112ff03b6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-27T19:59:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-27T19:59:46.000Z", "max_issues_repo_path": "test/initialization.jl", "max_issues_repo_name": "portugueslab/NMF.jl", "max_issues_repo_head_hexsha": "a89658e3492b5e80428da2abec360112ff03b6a8", "max_issues_repo_licenses": ["MIT"], "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/initialization.jl", "max_forks_repo_name": "portugueslab/NMF.jl", "max_forks_repo_head_hexsha": "a89658e3492b5e80428da2abec360112ff03b6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-24T18:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-24T18:00:36.000Z", "avg_line_length": 19.4772727273, "max_line_length": 48, "alphanum_fraction": 0.536756126, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7654243485226897}}
{"text": "\"\"\"\n     fdhinfminus(sys,freq) -> (\u03b2, ind, fr)\n\nCompute for a stable descriptor system `sys = (A-\u03bbE,B,C,D)` the `H\u221e-` index `\u03b2` of its\ntransfer function matrix `G(\u03bb)`. If `freq = missing` (default), then `\u03b2` is the \nminimum `H\u221e-norm` of the columns of `G`, `ind` is the index of the minimum-norm column and `fr` is \nthe frequency where the minimum `H\u221e-norm` of the columns is achieved. If `freq` is a real value or \na real vector of frequency values, then `\u03b2` 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   \u03b2 = Inf; ind = 0; f = -1;\n   if ismissing(freq) \n      # evaluate \u03b2 as the minimum of H-infinity norms of the columns of G\n      for j = 1:m\n         temp, fr = ghinfnorm(sys[:,j])\n         \u03b2 <= temp || (\u03b2 = temp; ind = j; f = fr)\n      end\n   else\n      # evaluate \u03b2 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             \u03b2 <= temp || (\u03b2 = 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                 \u03b2 <= temp || (\u03b2 = temp; ind = j; f = freq[i])\n             end\n         end\n      end\n   end\n   return \u03b2, ind, f\nend\n\"\"\"\n     fdhinfmax(sys,freq) -> (\u03b3, ind, fr)\n\nCompute for a descriptor system `sys = (A-\u03bbE,B,C,D)`, `\u03b3` - the maximum norm of the columns of its\ntransfer function matrix `G(\u03bb)`. If `freq = missing` (default), then `\u03b3` is the \nmaximum `H\u221e-norm` of the columns of `G`, `ind` is the index of the maximum-norm column and `fr` is \nthe frequency where the maximum `H\u221e-norm` of the columns is achieved. If `freq` is a real value or \na real vector of frequency values, then `\u03b3` 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   \u03b3 = 0; ind = 0; f = -1;\n   if ismissing(freq) \n      # evaluate \u03b3 as the maximum of H-infinity norms of the columns of G\n      for j = 1:m\n         temp, fr = ghinfnorm(sys[:,j])\n         \u03b3 >= temp || (\u03b3 = temp; ind = j; f = fr)\n      end\n   else\n      # evaluate \u03b3 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             \u03b3 >= temp || (\u03b3 = 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                 \u03b3 >= temp || (\u03b3 = temp; ind = j; f = freq[i])\n             end\n         end\n      end\n   end\n   return \u03b3, 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(\u03bb)`. \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 \u03a9\")\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(\u03bb)`. \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 \u03a9\")\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, \u03b2, \u03b3)\n\nCompute for a stable descriptor system `sysrf = (A-\u03bbE,B,C,D)` with the transfer function matrix `Rf(\u03bb)`, \n`\u03b2` - the H\u221e- index of `Rf(\u03bb)`, `\u03b3` - the maximum of the columns norms of `Rf(\u03bb)` and \n`scond` - the column-gains sensitivity condition evaluated as `scond := \u03b2/\u03b3`. \nIf `freq` is a vector of real frequency values, then `\u03b2` and `\u03b3`\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   \u03b2 = Inf\n   \u03b3 = 0 \n   if ismissing(freq) \n      # evaluate \u03b2 and \u03b3 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         \u03b3 >= temp || (\u03b3 = temp)\n         \u03b2 <= temp || (\u03b2 = temp)\n      end\n   else\n      # evaluate \u03b2 and \u03b3 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             \u03b3 >= temp || (\u03b3 = temp)\n             \u03b2 <= temp || (\u03b2 = 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                 \u03b3 >= temp || (\u03b3 = temp)\n                 \u03b2 <= temp || (\u03b2 = temp)\n             end\n         end\n      end\n   end\n   return \u03b2/\u03b3, \u03b2, \u03b3\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\u03b1tan(T) = 0.5 - 0.2*tanh((T-263)/4)\ndTdt(T, \u03b5 = 0.65, \u03b1=\u03b1tan, s= 1.0) = s*(1 - \u03b1(T)) - 1.6e-10 * \u03b5 * T^4\ndTdt(T; \u03b5 = 0.65, \u03b1=\u03b1tan, s = 1.0) = dTdt(T, \u03b5, \u03b1, s)\nd\u00b2Tdt\u00b2(T, \u03b5) = ForwardDiff.derivative(T -> dTdt(T, \u03b5), T)\nclimate_f(u, p, t) = SVector(dTdt(u[1], p))\nclimate_J(u, p, t) = SMatrix{1,1}(d\u00b2Tdt\u00b2(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\u03b5 = ps[_a:stable1] .- 0.03\narrow1T = xs[_a:stable1] .- 5\nplot(arrow1\u03b5, arrow1T; color = \"C1\", lw = 4.0)\narrow(arrow1\u03b5[end], arrow1T[end], 0, 50; \nwidth = 0.004, head_length = 5.0, color = \"C1\", zorder = 99)\n\n_b = 200\narrow2\u03b5 = ps[unstable1:unstable1+_b] .+ 0.03\narrow2T = xs[unstable1:unstable1+_b] .+ 5\n\nplot(arrow2\u03b5, arrow2T; color = \"C0\", lw = 4.0)\narrow(arrow2\u03b5[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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0cfeea3c-01ee-11eb-26f1-f1815eccdd10\nmd\"Create twenty birthday months\"\n\n# \u2554\u2550\u2561 015393e0-01ee-11eb-2feb-d7db4236368a\nmonths = rand(1:12,20)\n\n# \u2554\u2550\u2561 1a6a603e-01ee-11eb-39f6-efc09168a3ba\ncounts =  [sum(months.==i) for i=1:12]\n\n# \u2554\u2550\u2561 67c25428-0251-11eb-04b0-cb201bbefa6b\nsum(counts)\n\n# \u2554\u2550\u2561 6f1890a6-01ee-11eb-1524-1da938de93f3\nsum(counts.==2),sum(counts.==3)\n\n# \u2554\u2550\u2561 af424780-01ee-11eb-3d5f-4f4ba6a372b4\nsum(counts.==2)==4 & sum(counts.==3)==4\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dea5c880-01ee-11eb-066d-8105b2196548\nbirthday_problem(20_000_000)\n\n# \u2554\u2550\u2561 d74e2646-01f2-11eb-2b25-158bf9419ecd\n@elapsed birthday_problem(20_000_000)\n\n# \u2554\u2550\u2561 006a84ee-01ef-11eb-2db7-5792cb4d0198\nmultinomial(4,4,4) * multinomial(2,2,2,2,3,3,3,3) / 12.0^20\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25009a4603ea-01f2-11eb-00f0-591422bc7142\n# \u255f\u25000cfeea3c-01ee-11eb-26f1-f1815eccdd10\n# \u2560\u2550015393e0-01ee-11eb-2feb-d7db4236368a\n# \u2560\u25501a6a603e-01ee-11eb-39f6-efc09168a3ba\n# \u2560\u255067c25428-0251-11eb-04b0-cb201bbefa6b\n# \u2560\u25506f1890a6-01ee-11eb-1524-1da938de93f3\n# \u2560\u2550af424780-01ee-11eb-3d5f-4f4ba6a372b4\n# \u2560\u2550d8b5158e-01ee-11eb-393f-0d51ea1fc19b\n# \u2560\u2550dea5c880-01ee-11eb-066d-8105b2196548\n# \u2560\u2550d74e2646-01f2-11eb-2b25-158bf9419ecd\n# \u2560\u2550eb68872e-01ee-11eb-22e4-b1f20b71faff\n# \u2560\u2550006a84ee-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": "\n# ------------------------------------------------------------------------------------------\n# # \u5faa\u73af\n#\n# \u8bdd\u9898\uff1a\n# 1. `while`\u5faa\u73af\n# 2. `for`\u5faa\u73af\n#\n#\n# ## `while` \u5faa\u73af\n#\n# `while` \u5faa\u73af\u8bed\u6cd5\uff1a\n#\n# ```julia\n# while <condition>\n#     <loop body>\n# end\n# ```\n#\n# \u4e3e\u4e2a\u4f8b\u5b50\uff0c\u53ef\u4ee5\u4f7f\u7528 `while` \u6765\u6570\u6570\u6216\u8005\u904d\u5386\u4e00\u4e2a\u6570\u7ec4\u3002\n# ------------------------------------------------------------------------------------------\n\nn = 0\nwhile n < 10\n    n += 1\n    println(n)\nend\nn\n\nmyfriends = [\"Ted\", \"Robyn\", \"Barney\", \"Lily\", \"Marshall\"]\n\ni = 1\nwhile i <= length(myfriends)\n    friend = myfriends[i]\n    println(\"Hi $friend, it's great to see you!\")\n    i += 1\nend\n\n# ------------------------------------------------------------------------------------------\n# ## `for` \u5faa\u73af\n#\n# `for` \u5faa\u73af\u8bed\u6cd5\uff1a\n# ```julia\n# for <var> in <loop iterable>\n#     <loop body>\n# end\n# ```\n#\n# \u4e0a\u9762\u4e24\u4e2a\u4f8b\u5b50\u90fd\u53ef\u4ee5\u7528 `for` \u5faa\u73af\u6539\u5199\uff1a\n# ------------------------------------------------------------------------------------------\n\nfor n in 1:10\n    println(n)\nend\n\nmyfriends = [\"Ted\", \"Robyn\", \"Barney\", \"Lily\", \"Marshall\"]\n\nfor friend in myfriends\n    println(\"Hi $friend, it's great to see you!\")\nend\n\n# ------------------------------------------------------------------------------------------\n# \u8ba9\u6211\u4eec\u6765\u8bd5\u8bd5\u7528 `for` \u5faa\u73af\u521b\u5efa\u52a0\u548c\u8868\uff0c\u8868\u7684\u6bcf\u4e2a\u5143\u7d20\u4e3a\u5176\u884c\u7d22\u5f15\u548c\u5217\u7d22\u5f15\u7684\u548c\u3002\n#\n# \u9996\u5148\uff0c\u6765\u521d\u59cb\u5316\u4e00\u4e2a\u5168\u96f6\u7684\u6570\u7ec4\uff08\u77e9\u9635\uff09\u3002\n# ------------------------------------------------------------------------------------------\n\nm, n = 5, 5\nA = fill(0, (m, n))\n\nfor i in 1:m\n    for j in 1:n\n        A[i, j] = i + j\n    end\nend\nA\n\n# ------------------------------------------------------------------------------------------\n# \u8d81\u673a\u4ecb\u7ecd\u4e00\u4e0b\u50cf\u4e0a\u9762\u8fd9\u79cd\u5d4c\u5957 `for` \u5faa\u73af\u7684\u8bed\u6cd5\u7cd6\n# ------------------------------------------------------------------------------------------\n\nB = fill(0, (m, n))\n\nfor i in 1:m, j in 1:n\n    B[i, j] = i + j\nend\nB\n\n# ------------------------------------------------------------------------------------------\n# \u521b\u5efa\u540c\u6837\u7684\u8868\u4f46\u66f4\u5177\u6709\u201cJulia\u201d\u98ce\u683c\u7684\u65b9\u6cd5\u662f\u4f7f\u7528**\u6570\u7ec4\u89e3\u6790\u5f0f\uff08array comprehension\uff09**\u3002\n# ------------------------------------------------------------------------------------------\n\nC = [i + j for i in 1:m, j in 1:n]\n\n# ------------------------------------------------------------------------------------------\n# ## \u7ec3\u4e60\n#\n# ### 4.1\n# \u5faa\u73af\u904d\u5386 1 \u5230 100 \u7684\u6574\u6570\u5e76\u6253\u5370\u5b83\u4eec\u7684\u5e73\u65b9\u3002\n# ------------------------------------------------------------------------------------------\n\n# \u5728\u6b64\u4f5c\u7b54\n\n\n# ------------------------------------------------------------------------------------------\n# ### 4.2\n# \u7ed9\u4e0a\u4e00\u9898\u7684\u4ee3\u7801\u6dfb\u4e00\u70b9\u4ee5\u521b\u5efa\u4e00\u4e2a\u5b57\u5178\uff0c\u4f7f\u5b57\u5178\u5b58\u7740\u6bcf\u4e2a\u6574\u6570\u548c\u5b83\u7684\u5e73\u65b9\u7684\u952e\u503c\u5bf9\uff0c\u5c31\u50cf\u8fd9\u6837\n#\n# ```julia\n# squares[10] == 100\n# ```\n# ------------------------------------------------------------------------------------------\n\n# \u5728\u6b64\u4f5c\u7b54\n\n\n@assert squares[10] == 100\n@assert squares[11] == 121\n\n# ------------------------------------------------------------------------------------------\n# ### 4.3\n# \u7528\u6570\u7ec4\u89e3\u6790\u5f0f\u6765\u521b\u5efa\u4e00\u4e2a\u6570\u7ec4 `squares_arr`\uff0c\u8ba9\u5b83\u5b58\u7740\u4ece1\u5230100\u7684\u6574\u6570\u7684\u5e73\u65b9\u3002\n# ------------------------------------------------------------------------------------------\n\nsquares_arr = [i for i in 1:100]\n\n@assert length(squares_arr) == 100\n@assert sum(squares_arr) == 338350\n\n# ------------------------------------------------------------------------------------------\n# \u8bf7\u5728\u5b8c\u6210\u7ec3\u4e60\u8fd0\u884c `@assert` \u5757\u4ee5\u68c0\u6d4b\u7ed3\u679c\u662f\u5426\u6b63\u786e\uff0c\u82e5\u65e0\u62a5\u9519\u5373\u4e3a\u6b63\u786e\u3002\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "8e68db66516697f6b5d1f6945ba96ba5b3d0a786", "size": 3187, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/04.\u5faa\u73af.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/04.\u5faa\u73af.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/04.\u5faa\u73af.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": 23.962406015, "max_line_length": 92, "alphanum_fraction": 0.2739253216, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070839, "lm_q2_score": 0.9161096158798117, "lm_q1q2_score": 0.7653944984970276}}
{"text": "\nprintln(\"*******************************************************\")\n@testset \"fgmres\" begin\n\t@testset \"real matrix\" begin\n\t\tA  = sprandn(100,100,.1) + SparseMatrixCSC(10.0I, 100, 100)\n\t\tn  = size(A,2)\n\t\tD  = diag(A)\n\t\tM2 = x -> Vector(D.\\x)\n\t\trhs = randn(100)\n\t\ttol = 1e-6;\n\t\t\n\t\t# test printing and behaviour for early stopping\n\t\txtt = fgmres(A,rhs ,3,tol=1e-12,maxIter=3,out=2,storeInterm=true)\n\t\t@test xtt[2]==-1\n\t\t\n\t\t# test behaviour for zero rhs\n\t\txtt = fgmres(A,0*rhs,5,tol=tol,maxIter=10,out=2)\n\t\t@test xtt[2]==-9\n\t\t@test all(xtt[1].==0)\n\t\t@test length(xtt[1])==100\n\t\t@test eltype(xtt[1])==eltype(rhs)\n\n\t\t\n\t\tx1 = fgmres(A,rhs ,5,tol=tol,maxIter=100,out=1)\n\t\tx3 = fgmres(A,rhs,5,tol=tol,maxIter=100,x=randn(size(rhs)),flexible = true)\n\t\tx4 = fgmres(A,rhs,5,tol=tol,maxIter=100,M=M2,flexible = true)\n\t\t\n\t\t@test norm(A*x1[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(A*x3[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(A*x4[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(x3[1]-x1[1])/norm(x1[1]) < 1e-5\n\tend\n\n\t@testset \"complex matrix\" begin\n\t\tA  = sprandn(100,100,.1) + SparseMatrixCSC(10.0I, 100, 100) + 1im*(sprandn(100,100,.1) + SparseMatrixCSC(10.0I, 100, 100) )\n\t\tD  = Vector(diag(A))\n\t\tM3 = x -> x./D\n\t\trhs = complex(randn(100))\n\t\ttol = 1e-6;\n\t\t\n\t\t# test behaviour for zero rhs\n\n\t\txtt = fgmres(A,0.0*rhs,5,tol=tol,maxIter=10,out=2)\n\t\t# @test xtt[2]==-9\n\t\t# @test all(xtt[1].==0)\n\t\t# @test length(xtt[1])==100\n\t\t# @test eltype(xtt[1])==eltype(rhs)\n\t\t\n\t\t\n\t\tx1 = fgmres(A,rhs ,5,tol=tol,maxIter=100)\n\t\tx3 = fgmres(A,rhs,5,tol=tol,maxIter=100,x=randn(size(rhs)))\n\t\tx4 = fgmres(A,rhs,5,tol=tol,maxIter=100,M=M3)\n\t\t\n\t\t@test norm(A*x1[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(A*x3[1]-rhs)/norm(rhs) < tol\n\t\t@test norm(x3[1]-x1[1])/norm(x1[1]) < 1e-5\n\tend\nend", "meta": {"hexsha": "c982ae73d3161c551dc524c10e0e0ebd084ad09c", "size": 1729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testFGMRES.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": "test/testFGMRES.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": "test/testFGMRES.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": 29.8103448276, "max_line_length": 125, "alphanum_fraction": 0.5934065934, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.765394496583443}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 d80342ae-522b-11eb-19c0-cf931fb4ae81\nusing Statistics\n\n# \u2554\u2550\u2561 9c2ef32a-522d-11eb-29e6-29da29e4dec7\nusing Plots\n\n# \u2554\u2550\u2561 88b47ee6-522d-11eb-1a98-ed4dd43dfd11\nBase.@kwdef mutable struct SampleAvg\n    t::Int = 0\n    avg::Float64 = 0.0\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550d80342ae-522b-11eb-19c0-cf931fb4ae81\n# \u2560\u255088b47ee6-522d-11eb-1a98-ed4dd43dfd11\n# \u2560\u25508c94a810-522d-11eb-2024-01ca19bc1984\n# \u2560\u25508fde026e-522d-11eb-2aa1-f3e28c238ea6\n# \u2560\u25509c2ef32a-522d-11eb-29e6-29da29e4dec7\n# \u2560\u2550969b48aa-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\u0394x = 0.01\nLx = 4.0\nxlim = (-Lx/2,Lx/2)\nylim = (-Lx/2,Lx/2)\ng = PhysicalGrid(xlim,ylim,\u0394x)\nRadC = 1.0\n\u0394s = 1.4*cellsize(g)\nbody = Circle(RadC,\u0394s)\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    \u03bc ~ 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(\u03bc[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    \u03bc = Vector{T}(undef, K)\n    for k = 1:K\n        \u03bc[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(\u03bc[z[n]], 1.0)\n    end\nend\n\n# same as gmm_loopy, but with an affine transformation on \u03bc.\n@model function gmm_shifted(x, K, ::Type{T}=Float64) where {T<:Real}\n    N = length(x)\n\n    # Cluster centers.\n    \u03bc = Vector{T}(undef, K)\n    for k = 1:K\n        \u03bc[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\u03bc[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    \u03b1 = 1 / mean(y)\n    \u03bb\u2081 ~ Exponential(\u03b1)\n    \u03bb\u2082 ~ Exponential(\u03b1)\n    \u03c4 ~ DiscreteUniform(1, N)\n    \n    for n in 1:N\n        y[n] ~ Poisson(\u03c4 > n ? \u03bb\u2081 : \u03bb\u2082)\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 \u03b1_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, \u03b1, K)\n    N = length(y)\n    crm = DirichletProcess(\u03b1)\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    \u03bc ~ filldist(Normal(), L)\n\n    # Observations\n    for n = 1:N\n        y[n] ~ Normal(\u03bc[z[n]], 1.0)\n    end\nend\n\nimm_stick_example(y = data_neal, \u03b1 = \u03b1_neal, K = 10) = imm_stick(y, \u03b1, 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": "using ChebyshevQuantum\nusing Test\n\ntol_val = 1e-10\n\n\n@testset \"test particle in box \" begin\n\n    H = ChebyshevQuantum.SolveEig.setup_ham(x->0.0, 40);\n    #    vals, vects =  ChebyshevQuantum.SolveEig.solve(H)\n    vals, vects = eigen( H[2:end-1,2:end-1]);\n    \n\n    @test isapprox(vals[1],   pi^2/8, atol=tol_val)\n    @test isapprox(vals[2], 2^2*pi^2/8, atol=tol_val)\n    @test isapprox(vals[3], 3^2*pi^2/8, atol=tol_val)\n    @test isapprox(vals[4], 4^2*pi^2/8, atol=tol_val)\n    @test isapprox(vals[5], 5^2*pi^2/8, atol=tol_val)\n    \nend\n\n@testset \"test particle in bigger box \" begin\n\n    H = ChebyshevQuantum.SolveEig.setup_ham(x->0.0, 40, a = 0, b = 10);\n#    vals, vects =  ChebyshevQuantum.SolveEig.solve(H)\n    vals, vects = eigen( H[2:end-1,2:end-1]);\n    \n\n    f = (2/10)^2\n    \n    @test isapprox(vals[1],   pi^2/8 * f, atol=tol_val)\n    @test isapprox(vals[2], 2^2*pi^2/8 * f, atol=tol_val)\n    @test isapprox(vals[3], 3^2*pi^2/8 * f, atol=tol_val)\n    @test isapprox(vals[4], 4^2*pi^2/8 * f, atol=tol_val)\n    @test isapprox(vals[5], 5^2*pi^2/8 * f, atol=tol_val)\n    \nend\n\ntol_val = 1e-10\n\n@testset \"test particle in box N=100 \" begin\n\n    H = ChebyshevQuantum.SolveEig.setup_ham(x->0.0, 100);\n#    vals, vects =  ChebyshevQuantum.SolveEig.solve(H)\n    vals, vects = eigen( H[2:end-1,2:end-1]);\n\n    @test isapprox(vals[1],   pi^2/8, atol=tol_val)\n    @test isapprox(vals[2], 2^2*pi^2/8, atol=tol_val)\n    @test isapprox(vals[3], 3^2*pi^2/8, atol=tol_val)\n    @test isapprox(vals[4], 4^2*pi^2/8, atol=tol_val)\n    @test isapprox(vals[5], 5^2*pi^2/8, atol=tol_val)\n    \nend\n\ntol_val = 1e-9\n\n@testset \"test particle in finite box \" begin\n\n    #test edge detection\n    \n    function VV(x)\n        if abs(x) >= 1.0\n            return 10.0\n        else\n            return 0.0\n        end\n    end\n\n\n#    H, S = ChebyshevQuantum.SolveEig.total_ham_piecewise(VV, 30, [-2.0, -1.0, 1.0, 2.0], d2=-0.5)\n    #    H, S, lhs = ChebyshevQuantum.Op.setup(A2=-0.5, A0=VV,a=-2.0,b=2.0, N=30)\n\n    vals, vects = ChebyshevQuantum.SolveEig.solve(V=VV, a=-2.0, b = 2.0)\n\n    #    vals  =  eigvals(H, S)\n#    vals = real.(vals)\n    \n    @test isapprox(vals[1],  0.819848145939759, atol=tol_val) #reference values from chebfun.m (see below)\n    @test isapprox(vals[2],  3.222122379353262, atol=tol_val)\n\nend\n\n\"\"\"\nmatlab code using chebfun\ntic\nx = chebfun('x', [-2 2]);\nV = 10.0*(abs(x)>=1);\nL = chebop(-2,2);\nL.op = @(x,u) -0.5*diff(u,2) + V*u;\nL.bc = 0;\nneigs = 12;\n[EV,D] = eigs(L,neigs);\ndisp(diag(D))\ntoc\n\"\"\"\n\n\nnothing\n", "meta": {"hexsha": "04f42f50cada7d0a4085d4268c0c7145202dc8f1", "size": 2511, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_particle_in_box.jl", "max_stars_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_stars_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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": "test/test_particle_in_box.jl", "max_issues_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_issues_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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": "test/test_particle_in_box.jl", "max_forks_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_forks_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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": 25.3636363636, "max_line_length": 106, "alphanum_fraction": 0.6017522899, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7653921833159026}}
{"text": "using ExpFamily\nusing Base.Test\n\nsrand(123)\n\nC  = [1.0 0.5; 0.5 1.0]\nP  = 2/3 * [2 -1; -1 2]\nm  = [1.0;-0.5]\n\ngNP = GaussianNatParam(mean=m, cov=C)\ngMP = GaussianMeanParam(mean=m, cov=C)\n\n@test isapprox(gNP.theta1, P*m)\n@test isapprox(gNP.theta2, -P)\n@test isapprox(gMP.mu1, m)\n@test isapprox(gMP.mu2, (m*m'+C)/2)\n\n@test isvalid(gNP)\n@test isvalid(gMP)\n\nmpFromNP  = meanparam(gNP)\nmpFromNP2 = meanparam(gNP, 2.0)\nnpFromMP  = natparam(gMP)\n\n@test isapprox(mpFromNP.mu1, gMP.mu1)\n@test isapprox(mpFromNP.mu2, gMP.mu2)\n@test isapprox(npFromMP.theta1, gNP.theta1)\n@test isapprox(npFromMP.theta2, gNP.theta2)\n@test isapprox(cov(mpFromNP2), 2cov(mpFromNP))\n\n@test isapprox(mean(gNP), m)\n@test isapprox(mean(gMP), m)\n@test isapprox(cov(gNP), C)\n@test isapprox(cov(gMP), C)\n@test isapprox(var(gMP), diag(C))\n@test isapprox(var(gNP), diag(C))\n@test isapprox(std(gMP), sqrt.(diag(C)))\n@test isapprox(std(gNP), sqrt.(diag(C)))\n\n@test_throws DomainError GaussianNatParam(mean=m,cov=-C,check=true)\n@test_throws DomainError GaussianMeanParam(mean=m,cov=-C,check=true)\n\ndim = 4\ngNPones = ones(GaussianNatParam, dim)\ngMPones = ones(GaussianMeanParam, dim)\n\n@test isapprox(mean(gNPones), zeros(dim))\n@test isapprox(cov(gNPones),  eye(dim))\n@test isapprox(mean(gMPones), zeros(dim))\n@test isapprox(cov(gMPones),  eye(dim))\n\n@test length(gNPones) == dim\n@test length(gMPones) == dim\n\nrNP = rand(gNPones,5000)\nrMP = rand(gMPones,5000)\n\n@test isapprox(mean(rNP,2), zeros(dim), atol=1e-1)\n@test isapprox(mean(rMP,2), zeros(dim), atol=1e-1)\n@test isapprox(cov(rNP,2),  eye(dim),   atol=1e-1)\n@test isapprox(cov(rMP,2),  eye(dim),   atol=1e-1)\n\ngNP2 = gNP+gNP\ngMP2 = gMP+gMP\n\n@test isapprox(gNP2.theta1, 2gNP.theta1)\n@test isapprox(gNP2.theta2.data, 2gNP.theta2.data)\n@test isapprox(gMP2.mu1, 2gMP.mu1)\n@test isapprox(gMP2.mu2.data, 2gMP.mu2.data)\n\nm1  = randn(dim)\nm2  = randn(dim)\nC1  = randn(dim,dim)\nC1 *= C1'\nC2  = randn(dim,dim)\nC2 *= C2'\n\ngNPa = GaussianNatParam(mean=m1, cov=C1)\ngNPb = GaussianNatParam(mean=m2, cov=C2)\ngMPa = GaussianMeanParam(mean=m1, cov=C1)\ngMPb = GaussianMeanParam(mean=m2, cov=C2)\n\ngNPtest = gNPa + gNPb - natparam(gMPb)\ngMPtest = gMPa + gMPb - meanparam(gNPb)\n\n@test isapprox(gNPtest.theta1, gNPa.theta1)\n@test isapprox(gNPtest.theta2, gNPa.theta2)\n@test isapprox(gMPtest.mu1, gMPa.mu1)\n@test isapprox(gMPtest.mu2, gMPa.mu2)\n\n@test isapprox(gMPtest, gMPa)\n\n@test isapprox(GaussianNatParam(vec(gNPa),dim),gNPa)\n@test isapprox(GaussianMeanParam(vec(gMPa),dim),gMPa)\n\n@test isapprox(2gNPa + gNPa*2 - 3gNPa, gNPa)\n@test isapprox(2gMPa + gMPa*2 - 3gMPa, gMPa)\n@test isapprox(gNPa/2 + gNPa/2, gNPa)\n@test isapprox(gMPa/2 + gMPa/2, gMPa)\n\ngNP = GaussianNatParam(mean=m, cov=C)\n@test isapprox(project(gNP), gNP)\n\nnP = -diagm([1.5, 1e7])\nm  = [1.0;-0.5]\nlm = 1e-6\n\ngNPproj = project(GaussianNatParam(-nP*m, nP), minvar=lm)\ngMPproj = project(GaussianMeanParam(mean=m, cov=inv(-nP)), minvar=lm)\n\nnPthresh = -diagm([1.5, 1./lm])\n\n@test isapprox(gNPproj.theta1, -nPthresh*m)\n@test isapprox(gNPproj.theta2, -diagm([1.5, 1./lm]))\n@test isapprox(gMPproj.mu1, m)\n@test isapprox(cov(gMPproj), diagm([1./1.5, lm]))\n", "meta": {"hexsha": "907aaa018650b7fad5b66e7a2f79d6b454eb8abe", "size": 3104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gaussian_test.jl", "max_stars_repo_name": "tlienart/ExpFamily.jl", "max_stars_repo_head_hexsha": "819e2e338090538b384a77bdabe0d90895a40563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-11-16T02:19:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-30T08:31:18.000Z", "max_issues_repo_path": "test/gaussian_test.jl", "max_issues_repo_name": "tlienart/ExpFamily.jl", "max_issues_repo_head_hexsha": "819e2e338090538b384a77bdabe0d90895a40563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-06-07T13:22:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-19T15:37:48.000Z", "max_forks_repo_path": "test/gaussian_test.jl", "max_forks_repo_name": "tlienart/ExpFamily.jl", "max_forks_repo_head_hexsha": "819e2e338090538b384a77bdabe0d90895a40563", "max_forks_repo_licenses": ["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.5299145299, "max_line_length": 69, "alphanum_fraction": 0.7042525773, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7653921796383637}}
{"text": "using Base.Test\nusing SymEngine\n\nx = symbols(\"x\")\ny = symbols(:y)\n@vars z\n\n# Check Basic conversions\n@test eltype([Basic(u) for u in [1, 1/2, 1//2, pi, e]]) == Basic\n\n# make sure @vars defines in a local scope\nlet\n    @vars w\nend\n@test_throws UndefVarError isdefined(w)\n\na = x^2 + x/2 - x*y*5\nb = diff(a, x)\n@test b == 2*x + 1//2 - 5*y\n\nc = x + Rational(1, 5)\nc = expand(c * 5)\n@test c == 5*x + 1\n\nc = x ^ 5\n@test diff(c, x) == 5 * x ^ 4\n\nc = x ^ y\n@test c != y^x\n\nc = Basic(-5)\n@test abs(c) == 5\n@test abs(c) != 4\n\nshow(a)\nprintln()\nshow(b)\nprintln()\n\n\n## mathfuns\n@test abs(Basic(-1)) == 1\n@test sin(Basic(1)) == subs(sin(x), x, 1)\n@test sin(PI) == 0\n@test subs(sin(x), x, pi) == 0\n@test sind(Basic(30)) == 1 // 2\n\n## calculus\nx,y = symbols(\"x y\")\nn = Basic(2)\nex = sin(x*y)\n@test diff(log(x),x) == 1/x\n@test diff(ex, x) == y * cos(x*y)\n@test diff(ex, x, 2) == diff(diff(ex,x), x)\n@test diff(ex, x, n) == diff(diff(ex,x), x)\n@test diff(ex, x, y) == diff(diff(ex,x), y)\n@test diff(ex, x, y,x) == diff(diff(diff(ex,x), y), x)\n@test series(sin(x), x, 0, 2) == x\n@test series(sin(x), x, 0, 3) == x - x^3/6\n\n## ntheory\n@test mod(Basic(10), Basic(4)) == 2\n@test mod(Basic(10), 4) == 2               # mod(::Basic, ::Number)\n@test_throws MethodError mod(10, Basic(4)) # no mod(::Number, ::Basic)\n@test gcd(Basic(10), Basic(4)) == 2\n@test lcm(Basic(10), Basic(4)) == 20\n@test binomial(Basic(5), 2) == 10\n\n\n## type information\na = Basic(1)\nb = Basic(1//2)\n@test isa(SymEngine.BasicType(a+a), SymEngine.BasicType{Val{:Integer}})\n@test isa(SymEngine.BasicType(a+b), SymEngine.BasicType{Val{:Rational}})\n\n## can we do math with items of BasicType?\na1 = SymEngine.BasicType(a)\ntot = a1\nfor i in 1:100  tot = tot + a1 end\n@test tot == 101\nsin(a1)\n\n## subs\nex = x^2 + y^2\n@test subs(ex, x, 1) == 1 + y^2\n@test subs(ex, (x, 1)) == 1 + y^2\n@test subs(ex, x => 1) == 1 + y^2\n@test subs(ex, (x,1), (y,2)) == 1 + 2^2\n@test subs(ex, x => 1, y => 2) == 1 + 2^2\n\n## lambidfy\n@test_approx_eq lambdify(sin(Basic(1))) sin(1)\nex = sin(x)\n@test_approx_eq lambdify(ex)(1) sin(1)\nex = exp(PI/2*x)\n@test_approx_eq lambdify(ex)(1) exp(pi/2)\n\n## N\na = Basic(1)\n@test N(a) == 1\n@test N(Basic(1//2)) == 1//2\n@test N(Basic(12345678901234567890)) == 12345678901234567890\n\n\n## generic linear algebra\nx = symbols(\"x\")\nA = [x 2; x 1]\n@test det(A) == -x\n@test det(inv(A)) == - 1/x\n(A \\ [1,2])[1] == 3/x\n\n## check that unique work (hash)\nx,y,z = symbols(\"x y z\")\n@test length(SymEngine.free_symbols([x*y, y,z])) == 3\n", "meta": {"hexsha": "33dbf1e882eaedb0fbc4f562d67f9043972cc9e7", "size": 2477, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaPackageMirrors/SymEngine.jl", "max_stars_repo_head_hexsha": "ca9745b3f00cf2d78393236effa0e42bd48cfc8f", "max_stars_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/SymEngine.jl", "max_issues_repo_head_hexsha": "ca9745b3f00cf2d78393236effa0e42bd48cfc8f", "max_issues_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/SymEngine.jl", "max_forks_repo_head_hexsha": "ca9745b3f00cf2d78393236effa0e42bd48cfc8f", "max_forks_repo_licenses": ["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.5391304348, "max_line_length": 72, "alphanum_fraction": 0.578118692, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7653921739769167}}
{"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": "n = 10 # rand(1:10)\n@test matrixdepot(\"lehmer\", Float64, n) == matrixdepot(\"lehmer\", n)\n\nA = ones(n, 1) * [1:n;]'\nA = A./A'\nA = tril(A) + tril(A)' - Matrix(1.0I, n, n)\n\n@test matrixdepot(\"lehmer\", n) \u2248 A\nprintln(\"'lehmer' passed test...\")\n\n", "meta": {"hexsha": "f87cb5abd3997e95cf55a57fda5e4bbad4ceacc0", "size": 240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_lehmer.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_lehmer.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_lehmer.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 21.8181818182, "max_line_length": 67, "alphanum_fraction": 0.5708333333, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7653921719515406}}
{"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\u2082,a\u2080,a,b) -> begin\n         fn = x  ->  a\u2082*x^2 + a\u2080\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\u2082,a\u2080,a,b) -> \n         fn =  x  ->  a\u2082*x^2 + a\u2080\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 \u2208 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": "using Distributions\ndists = [\n    Uniform(10,20),\n    Exponential(3.5),\n    Gamma(0.5,7),\n    Beta(10,0.5),\n    Weibull(10,0.5),\n    Normal(20,3.5),\n    Rayleigh(2.4),\n    Cauchy(20,3.5)]\n\nprintln(\"Distribution \\t\\t\\t Parameters \\t Support\")\nreshape([dists ;  params.(dists) ;\n\t\t((d)->(minimum(d),maximum(d))).(dists) ],\n\t\tlength(dists),3)\n", "meta": {"hexsha": "60c52d38c4a959f30ed0b532645fc0d3367af8ff", "size": 340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/continuousDists.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/continuousDists.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/continuousDists.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": 21.25, "max_line_length": 52, "alphanum_fraction": 0.5911764706, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7653921681910654}}
{"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\u2013Stokes\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\u2093)\n    \u0394x = 2 / (n\u2093 - 1)\n    n\u209c = 20    #n\u209c is the number of timesteps we want to calculate\n    \u0394t = .025  #\u0394t is the amount of time each timestep covers (delta t)\n    c = 1\n\n    u = ones(n\u2093)      #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\u2099 = ones(n\u2093) #initializing our placeholder array, un, to hold the values we calculate for the n+1 timestep\n\n    for n in n\u209c #iterate through time\n        u\u2099 = copy(n) ##copy the existing values of u into un\n        for i in 1:n\u2093\n            u[i] = u\u2099[i] - c * dt / dx * (u\u2099[i] - u\u2099[i-1])\n        end\n    end\n    u\nend\n\nu = linearconv(n\u2093)\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 `\u0394x`.\n# The length `\u0394x` of each grid box is related to the number of total points `n\u2093`, so stability can\n# be enforced if the $\\Delta t$ step size is calculated with respect to the size of `\u0394x`.\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 `\u0394t` depending on the size of `\u0394x`.\n\nfunction linearconv(n\u2093)\n    \u0394x = 2 / (n\u2093 - 1)\n    n\u209c = 20    #nt is the number of timesteps we want to calculate\n    c = 1\n    \u03c3 = .5\n    indexes = Int.((.5/\u0394x):(1/\u0394x))\n\n    \n    \u0394t = \u03c3 * \u0394x\n\n    u = ones(nx)\n    u[indexes] .= 2\n\n    un = ones(nx)\n\n    for n in range(n\u209c):  #iterate through time\n        u\u2099 = copy(u) ##copy the existing values of u into un\n        for i in 1:n\u2093\n            u[i] = u\u2099[i] - c * dt / dx * (u\u2099[i] - u\u2099[i-1])\n        end\n    end\n    u\nend\n        \nplot(range(start = 0, end = 2, length = n\u2093), 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\u209c = 20`,\n# but depending on the value of `n\u2093` and the corresponding values of `\u0394x` and `\u0394t`, 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": "using DiffEqCallbacks, OrdinaryDiffEq, Test\n\n# Non-negative ODE examples\n#\n# Reference:\n# Shampine, L.F., S. Thompson, J.A. Kierzenka, and G.D. Byrne,\n# \"Non-negative solutions of ODEs,\" Applied Mathematics and Computation Vol. 170, 2005,\n# pp. 556-569.\n# https://www.mathworks.com/help/matlab/math/nonnegative-ode-solution.html\n\n\"\"\"\nAbsolute value function\n\n```math\n\\\\frac{du}{dt} = -|u|\n```\nwith initial condition ``u\u2080=1``, and solution\n\n```math\nu(t) = u\u2080*e^{-t}\n```\nfor positive initial values ``u\u2080``.\n\"\"\"\nfunction absval(du,u,p,t)\n    du[1] = -abs(u[1])\nend\nanalytic(u\u2080, p, t) = u\u2080*exp(-t)\nff = ODEFunction(absval,analytic=analytic)\nprob_absval = ODEProblem(ff, [1.0], (0.0, 40.0))\n\n# naive approach leads to large errors\nnaive_sol_absval = solve(prob_absval, BS3())\n@test naive_sol_absval.errors[:l\u221e] > 9e4\n@test naive_sol_absval.errors[:l2] > 1.3e4\n\n# general domain approach\n# can only guarantee approximately non-negative values\nfunction g(resid,u)\n    resid[1] = u[1] < 0 ? -u[1] : 0\nend\ngeneral_sol_absval = solve(prob_absval, BS3(); callback=GeneralDomain(g, [1.0]))\n@test_broken all(x -> x[1] \u2265 -10*eps(), general_sol_absval.u)\n@test general_sol_absval.errors[:l\u221e] < 9.9e-5\n@test general_sol_absval.errors[:l2] < 4.3e-5\n@test general_sol_absval.errors[:final] < 4.3e-18\n\n# test non-autonomous function\ng_t(resid, u, p, t) = g(resid, u)\n\ngeneral_t_sol_absval = solve(prob_absval, BS3(); callback=GeneralDomain(g_t, [1.0]))\n@test general_sol_absval.t \u2248 general_t_sol_absval.t &&\n    general_sol_absval.u \u2248 general_t_sol_absval.u\n\n# positive domain approach\n# can guarantee non-negative values\npositive_sol_absval = solve(prob_absval, BS3(); callback=PositiveDomain([1.0]))\n@test_broken all(x -> x[1] \u2265 0, positive_sol_absval.u)\n@test_broken general_sol_absval.t \u2248 positive_sol_absval.t\n@test general_sol_absval.errors[:l\u221e] \u2248 positive_sol_absval.errors[:l\u221e]\n\n# specify abstol as array or scalar\npositive_sol_absval2 = solve(prob_absval, BS3(); callback=PositiveDomain([1.0], abstol=[1e-6]))\n@test positive_sol_absval.t \u2248 positive_sol_absval2.t &&\n    positive_sol_absval.u \u2248 positive_sol_absval2.u\npositive_sol_absval3 = solve(prob_absval, BS3(); callback=PositiveDomain([1.0], abstol=1e-6))\n@test positive_sol_absval.t \u2248 positive_sol_absval3.t && positive_sol_absval.u \u2248 positive_sol_absval3.u\n\n# specify scalefactor\npositive_sol_absval4 = solve(prob_absval, BS3(); callback=PositiveDomain([1.0], scalefactor=0.2))\n@test length(positive_sol_absval.t) < length(positive_sol_absval4.t)\n@test positive_sol_absval.errors[:l2] > positive_sol_absval4.errors[:l2]\n\n\"\"\"\nKnee problem\n\n```math\n\\\\frac{du}{dt} = \\epsilon^{-1}(1-t-u)u\n```\n\nwith initial condition ``u0=1``, and generally ``0 < \\epsilon << 1``.\nHere ``\\epsilon=1e-6``. Then the solution approaches ``u=1-t`` for ``t<1``\nand ``u=0`` for ``t>1``.\n\"\"\"\nfunction knee(du,u,p,t)\n    du[1] = 1e6*(1-t-u[1])*u[1]\nend\n\nprob_knee = ODEProblem(knee, [1.0], (0.0, 2.0))\n\n# unfortunately callbacks do not work with solver CVODE_BDF which is comparable to ode15s\n# used in MATLAB example, so we use Rodas5\nnaive_sol_knee = solve(prob_knee, Rodas5())\n@test naive_sol_knee[1, end] \u2248 -1.0 atol=1e-5\n\n# positive domain approach\npositive_sol_knee = solve(prob_knee, Rodas5(); callback=PositiveDomain([1.0]))\n@test_broken all(x -> x[1] \u2265 0, positive_sol_knee.u)\n@test positive_sol_knee[1, end] \u2248 0.0\n\n## Now test on out-of-place equations\nr, K = 1.1, 10.0\nlogistic(u,p,t) = u*r*(1-u/K)\nt = (0.0, 20.0)\nlogistic_p = ODEProblem(logistic, 0.02, t)\nlogistic_s = solve(logistic_p, Tsit5())\nlogistic_s_positive = solve(logistic_p, Tsit5(), callback=PositiveDomain())\n", "meta": {"hexsha": "40bdbb43644c4e26afc276310428be80c1499dce", "size": 3604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/domain_tests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqCallbacks.jl-459566f4-90b8-5000-8ac3-15dfb0a30def", "max_stars_repo_head_hexsha": "c78c88e5a82d41e40a8012b1b1f0c4dd66b16ec9", "max_stars_repo_licenses": ["MIT"], "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/domain_tests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqCallbacks.jl-459566f4-90b8-5000-8ac3-15dfb0a30def", "max_issues_repo_head_hexsha": "c78c88e5a82d41e40a8012b1b1f0c4dd66b16ec9", "max_issues_repo_licenses": ["MIT"], "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/domain_tests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqCallbacks.jl-459566f4-90b8-5000-8ac3-15dfb0a30def", "max_forks_repo_head_hexsha": "c78c88e5a82d41e40a8012b1b1f0c4dd66b16ec9", "max_forks_repo_licenses": ["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.6822429907, "max_line_length": 102, "alphanum_fraction": 0.7189234184, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.7653827806172674}}
{"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\u2572  \u211d^(2, 2) -> \u211d^(2, 2)\n\njulia> D*ones(2,2)\n2\u00d72 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) = \"\u2572\"\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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.12\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ae6cb47a-3af7-11eb-0264-bb161b7731a1\nText(\"Upper bound U: $(U(observation)))\")\n\n# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.12\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u2550ae6c7528-3af7-11eb-14a4-4bb1f292614b\n# \u2560\u2550ae6cb47a-3af7-11eb-0264-bb161b7731a1\n# \u255f\u2500475ff888-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# \u2554\u2550\u2561 4b348c51-c844-4e64-85e4-a4f7ea952fc9\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e803d172-2b8a-43b4-b99d-307e64cf29d5\nmd\"# Chapter 9. Markov Chain Monte Carlo.\"\n\n# \u2554\u2550\u2561 77a70403-fa95-4b13-b886-415d1a91f15a\nbegin\n\tdefault(labels=false)\n\tLogging.disable_logging(Logging.Warn);\nend\n\n# \u2554\u2550\u2561 f9ff23ea-fdf2-4d48-bb84-98f40db8603e\nmd\"## 9.1 Good King Markov and his island kingdom.\"\n\n# \u2554\u2550\u2561 821bcd65-4ab5-43e8-837e-8bdf96f24edd\nmd\"### Code 9.1\"\n\n# \u2554\u2550\u2561 0ccba2cd-c10c-4713-80e1-77e4a3e9c85c\nbegin\n\tRandom.seed!(1)\n\tnum_weeks = 10^5\n\tpositions = []\n\tcurrent = 10\nend;\n\n# \u2554\u2550\u2561 b71b59cb-b9ed-4a18-a713-400d8fb48517\nfor i \u2208 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# \u2554\u2550\u2561 62852231-aebe-43bc-a591-ff3c79651739\nmd\"### Code 9.2\"\n\n# \u2554\u2550\u2561 2f603bc2-938d-45b4-a9ed-60daa5847af5\nscatter(positions[1:100], xlab=\"week\", ylab=\"island\")\n\n# \u2554\u2550\u2561 3f745e69-690e-4ab9-934f-b05f24f20a98\nmd\"### Code 9.3\"\n\n# \u2554\u2550\u2561 a88970a9-341c-4e92-891b-6057dbac1e01\nhistogram(positions, xlab=\"island\", ylab=\"number of weeks\")\n\n# \u2554\u2550\u2561 e7569635-07ab-4b69-8014-f26d42955fce\nmd\"## 9.2 Metropolis algorithms\"\n\n# \u2554\u2550\u2561 d4991ad9-4341-47e8-aee4-9c35cbe28e35\nmd\"### Code 9.4\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7d94a7f1-7ce5-4f6a-ba72-0a8a9cde44e9\nmd\"## 9.3 Hamiltonian Monte Carlo\"\n\n# \u2554\u2550\u2561 19d13362-93a0-4a93-b3bb-6e30d3d934a3\nmd\"### Code 9.5\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e3cc237b-9997-41b6-8298-1b79e4444662\nfunction U(q::Vector{Float64}; a=0, b=1, k=0, d=1)::Float64\n    \u03bcy, \u03bcx = q\n    U = sum(normlogpdf.(\u03bcy, 1, y)) + sum(normlogpdf.(\u03bcx, 1, x)) \n    U += normlogpdf(a, b, \u03bcy) + normlogpdf(k, d, \u03bcx)\n    -U\nend\n\n# \u2554\u2550\u2561 cb41155d-43a6-4fef-932f-13cabcdf907a\nmd\"### Code 9.6\"\n\n# \u2554\u2550\u2561 7d29cbaf-2b27-4b4e-8dee-74a049408fba\nfunction \u2207U(q::Vector{Float64}; a=0, b=1, k=0, d=1)::Vector{Float64}\n    \u03bcy, \u03bcx = q\n    G\u2081 = sum(y .- \u03bcy) + (a - \u03bcy) / b^2  # \u2202U/\u2202\u03bcy\n    G\u2082 = sum(x .- \u03bcx) + (k - \u03bcx) / d^2  # \u2202U/\u2202\u03bcx\n    [-G\u2081, -G\u2082]\nend\n\n# \u2554\u2550\u2561 9d674865-3fed-48a6-a970-d997ae9d7443\nmd\"### Codes 9.8 - 9.10 (before 9.7 to define HMC2 function)\"\n\n# \u2554\u2550\u2561 aa9be028-c3dc-4e4a-9405-86be642540ca\nfunction HMC2(U, \u2207U, \u03f5::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 -= \u03f5 .* \u2207U(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 \u2208 1:L\n        q += @. \u03f5 * 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 -= \u03f5 * \u2207U(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 -= \u03f5 * \u2207U(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# \u2554\u2550\u2561 e61d81ed-761a-450b-9ea0-1398a9ac8e22\nmd\"### Code 9.7\"\n\n# \u2554\u2550\u2561 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=\"\u03bcx\", ylab=\"\u03bcy\")\n\n\n\tfor i \u2208 1:n_samples\n\t    Q = HMC2(U, \u2207U, step1, L, Q.q)\n\t    if n_samples < 10 \n\t        cx, cy = [], []\n\t        for j \u2208 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# \u2554\u2550\u2561 4dc8aa1b-7544-4a80-9109-a2c9040d9321\nmd\"## 9.4 Easy HMC: ulam\"\n\n# \u2554\u2550\u2561 e6a3d465-57d2-40aa-b71d-8cca5db234d9\nmd\"### Code 9.11\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 06d5c8b7-7a87-4ddb-9c30-d6d623a71814\nmd\"### Code 9.12\"\n\n# \u2554\u2550\u2561 e29edd1a-890d-4e21-a221-d4311bd845d3\nr\u0304 = mean(dd.rugged_std);\n\n# \u2554\u2550\u2561 200f0e88-b30f-4aac-a733-a25f5a52c5d8\n@model function model_m8_3(rugged_std, cid,  log_gdp_std)\n    \u03c3 ~ Exponential()\n    a ~ MvNormal([1, 1], 0.1)\n    b ~ MvNormal([0, 0], 0.3)\n    \u03bc = @. a[cid] + b[cid] * (rugged_std - r\u0304)\n    log_gdp_std ~ MvNormal(\u03bc, \u03c3)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f67d530a-e56d-408c-8f21-d4e37e8dab42\nmd\"### Code 9.13\"\n\n# \u2554\u2550\u2561 60a185df-0656-4a46-b301-388407073ab6\nmd\"#### For Turing this is not needed\"\n\n# \u2554\u2550\u2561 9d6afd05-6570-44e0-8b49-5e4bc7e8a76f\nbegin\n\tdat_slim = dd[!,[:log_gdp_std, :rugged_std, :cid]]\n\tdescribe(dat_slim)\nend\n\n# \u2554\u2550\u2561 cfe67e9f-41bb-419f-96ba-282926de31a2\nmd\"### Code 9.14\"\n\n# \u2554\u2550\u2561 8409b9f4-7fa5-4f38-9b38-ae34e4c60e83\n@model function model_m9_1(rugged_std, cid,  log_gdp_std)\n    \u03c3 ~ Exponential()\n    a ~ MvNormal([1, 1], 0.1)\n    b ~ MvNormal([0, 0], 0.3)\n    \u03bc = @. a[cid] + b[cid] * (rugged_std - r\u0304)\n    log_gdp_std ~ MvNormal(\u03bc, \u03c3)\nend\n\n# \u2554\u2550\u2561 4e94cf59-81eb-4b99-b048-502f54faee15\nmd\"#### One chain will be produced by default\"\n\n# \u2554\u2550\u2561 76782d05-9e32-424c-a206-8081e0fdd146\nm9_1 = sample(model_m8_3(dd.rugged_std, dd.cid,  dd.log_gdp_std), NUTS(), 1000);\n\n# \u2554\u2550\u2561 e8dd780e-b94d-413c-9b0b-0476817b2094\nmd\"### Code 9.15\"\n\n# \u2554\u2550\u2561 b80e5ff3-445a-465c-9665-697f5b0b897e\nPRECIS(DataFrame(m9_1))\n\n# \u2554\u2550\u2561 b6057787-3948-482c-be7e-69c4231386b6\nmd\"### Code 9.16\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2d2aa3ef-8fb7-4c69-8869-42e1939dc950\nmd\"### Code 9.17\"\n\n# \u2554\u2550\u2561 61b5e6a8-3baa-4101-9a21-5d49af43bfe7\nmd\"#### This shows combined chains statistics. To get information about individual chains, use `m9_1[:,:,1]`\"\n\n# \u2554\u2550\u2561 35f25d1e-234b-481f-9303-3c5973ab1228\nm9_1\n\n# \u2554\u2550\u2561 4e20ad94-3011-4b89-b29e-8a793e733e03\nmd\"### Code 9.18\"\n\n# \u2554\u2550\u2561 ed026592-6cb3-40a3-9f0a-565e14038114\nPRECIS(DataFrame(m9_1[:,:,1]))\n\n# \u2554\u2550\u2561 b25c0b7a-4469-4945-be28-bfb2c22103ca\nmd\"### Code 9.19\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 580db5a8-550a-42d1-9aef-c95f4099a3fa\nmd\"### Code 9.20\"\n\n# \u2554\u2550\u2561 0bd7dbfe-0689-40d4-8fd0-1fd372b2edc2\ntraceplot(m9_1)\n\n# \u2554\u2550\u2561 534f0c53-da8b-4da5-81d4-c0ab3ceb270b\nmd\"### Code 9.21\"\n\n# \u2554\u2550\u2561 a28ee7bb-d9d7-43ea-833f-6460a2cf7579\nhistogram(m9_1)\n\n# \u2554\u2550\u2561 4535c71f-be7c-41e8-940b-57289c83e509\nmd\"## 9.5 Care and feeding of your Markov chain.\"\n\n# \u2554\u2550\u2561 f39cd55f-ed8f-487e-885e-f1e16b78d9dd\nmd\"### Codes 9.22 - 9.23\"\n\n# \u2554\u2550\u2561 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    \u03b1 ~ Normal(0, 1000)\n\t    \u03c3 ~ Exponential(1/0.0001)\n\t    y ~ Normal(\u03b1, \u03c3)\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# \u2554\u2550\u2561 a9febef3-06d0-4552-8590-2f165ce36547\nmd\"### Code 9.23\"\n\n# \u2554\u2550\u2561 7b2588d2-d86d-44fb-9895-d6452875bc47\nplot(\n    traceplot(m9_2),\n    histogram(m9_2),\n    size=(900, 500)\n)\n\n# \u2554\u2550\u2561 cc97f4d9-ad00-4d2c-b520-2071b9cf86f6\nmd\"### Code 9.24\"\n\n# \u2554\u2550\u2561 631bb03b-00a5-466a-be0d-36f86a9721aa\nRandom.seed!(2)\n\n# \u2554\u2550\u2561 95dc66d6-660a-4b0c-b89d-487a22dfec82\n@model function model_m9_3(y)\n    \u03b1 ~ Normal(1, 10)\n    \u03c3 ~ Exponential(1)\n    y ~ Normal(\u03b1, \u03c3)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8f945f6c-2561-433b-aedb-3448d2c4b419\ness_rhat(m9_3)\n\n# \u2554\u2550\u2561 ecd23fa3-fdd2-4ffb-a0e9-ad1feee04d22\nmd\"### Code 9.25 - 9.26\"\n\n# \u2554\u2550\u2561 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    \u03c3 ~ Exponential(1)\n\t    \u03bc = a1 + a2\n\t    y ~ Normal(\u03bc, \u03c3)\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# \u2554\u2550\u2561 4c09eda3-8f4c-4fa2-91ea-99b92cfbb422\ness_rhat(m9_4)\n\n# \u2554\u2550\u2561 1f2c5378-bbcd-4fb7-9130-9c6cebb4c6d4\nplot(m9_4)\n\n# \u2554\u2550\u2561 517d31ba-5843-40a7-ad06-96e7a8ea8845\nmd\"### Code 9.27\"\n\n# \u2554\u2550\u2561 1cc0a6c1-3fcf-4df3-a8d9-ba3454c0a37b\nRandom.seed!(384)\n\n# \u2554\u2550\u2561 9a76593b-c9a9-45cc-aca5-9877432baffd\n@model function model_m9_5(y)\n    a1 ~ Normal(0, 10)\n    a2 ~ Normal(0, 10)\n    \u03c3 ~ Exponential(1)\n    \u03bc = a1 + a2\n    y ~ Normal(\u03bc, \u03c3)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 942e3f19-a5c1-430e-a3be-097c53bc7394\ness_rhat(m9_5)\n\n# \u2554\u2550\u2561 6caa4b75-9ac1-496b-a4b2-38b72b203e59\nplot(m9_5)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500e803d172-2b8a-43b4-b99d-307e64cf29d5\n# \u2560\u25504b348c51-c844-4e64-85e4-a4f7ea952fc9\n# \u2560\u255075ce54b9-b801-412a-b70e-ab5222df137f\n# \u2560\u255077a70403-fa95-4b13-b886-415d1a91f15a\n# \u255f\u2500f9ff23ea-fdf2-4d48-bb84-98f40db8603e\n# \u255f\u2500821bcd65-4ab5-43e8-837e-8bdf96f24edd\n# \u2560\u25500ccba2cd-c10c-4713-80e1-77e4a3e9c85c\n# \u2560\u2550b71b59cb-b9ed-4a18-a713-400d8fb48517\n# \u255f\u250062852231-aebe-43bc-a591-ff3c79651739\n# \u2560\u25502f603bc2-938d-45b4-a9ed-60daa5847af5\n# \u255f\u25003f745e69-690e-4ab9-934f-b05f24f20a98\n# \u2560\u2550a88970a9-341c-4e92-891b-6057dbac1e01\n# \u255f\u2500e7569635-07ab-4b69-8014-f26d42955fce\n# \u255f\u2500d4991ad9-4341-47e8-aee4-9c35cbe28e35\n# \u2560\u25509322d404-9ebd-4dd8-985d-8322f4f77571\n# \u255f\u25007d94a7f1-7ce5-4f6a-ba72-0a8a9cde44e9\n# \u255f\u250019d13362-93a0-4a93-b3bb-6e30d3d934a3\n# \u2560\u255029a1a866-522b-4354-866e-9f121ba378b9\n# \u2560\u2550e3cc237b-9997-41b6-8298-1b79e4444662\n# \u255f\u2500cb41155d-43a6-4fef-932f-13cabcdf907a\n# \u2560\u25507d29cbaf-2b27-4b4e-8dee-74a049408fba\n# \u255f\u25009d674865-3fed-48a6-a970-d997ae9d7443\n# \u2560\u2550aa9be028-c3dc-4e4a-9405-86be642540ca\n# \u255f\u2500e61d81ed-761a-450b-9ea0-1398a9ac8e22\n# \u2560\u2550a74b283d-febc-40b1-9654-3d63b7d014b2\n# \u255f\u25004dc8aa1b-7544-4a80-9109-a2c9040d9321\n# \u255f\u2500e6a3d465-57d2-40aa-b71d-8cca5db234d9\n# \u2560\u2550ff957f53-dbc7-4885-9797-61d10b8dac15\n# \u255f\u250006d5c8b7-7a87-4ddb-9c30-d6d623a71814\n# \u2560\u2550e29edd1a-890d-4e21-a221-d4311bd845d3\n# \u2560\u2550200f0e88-b30f-4aac-a733-a25f5a52c5d8\n# \u2560\u2550fbcda425-2e88-4a49-b24b-17894231642e\n# \u255f\u2500f67d530a-e56d-408c-8f21-d4e37e8dab42\n# \u255f\u250060a185df-0656-4a46-b301-388407073ab6\n# \u2560\u25509d6afd05-6570-44e0-8b49-5e4bc7e8a76f\n# \u255f\u2500cfe67e9f-41bb-419f-96ba-282926de31a2\n# \u2560\u25508409b9f4-7fa5-4f38-9b38-ae34e4c60e83\n# \u255f\u25004e94cf59-81eb-4b99-b048-502f54faee15\n# \u2560\u255076782d05-9e32-424c-a206-8081e0fdd146\n# \u255f\u2500e8dd780e-b94d-413c-9b0b-0476817b2094\n# \u2560\u2550b80e5ff3-445a-465c-9665-697f5b0b897e\n# \u255f\u2500b6057787-3948-482c-be7e-69c4231386b6\n# \u255f\u2500d438bddd-9138-410e-ab98-40f7c90e780f\n# \u2560\u25503f4a3b7c-2db7-4d7b-800a-c14968a02855\n# \u255f\u25002d2aa3ef-8fb7-4c69-8869-42e1939dc950\n# \u255f\u250061b5e6a8-3baa-4101-9a21-5d49af43bfe7\n# \u2560\u255035f25d1e-234b-481f-9303-3c5973ab1228\n# \u255f\u25004e20ad94-3011-4b89-b29e-8a793e733e03\n# \u2560\u2550ed026592-6cb3-40a3-9f0a-565e14038114\n# \u255f\u2500b25c0b7a-4469-4945-be28-bfb2c22103ca\n# \u2560\u25508a0295cc-4f0c-475a-a8c6-ccf2b99ed00f\n# \u255f\u2500580db5a8-550a-42d1-9aef-c95f4099a3fa\n# \u2560\u25500bd7dbfe-0689-40d4-8fd0-1fd372b2edc2\n# \u255f\u2500534f0c53-da8b-4da5-81d4-c0ab3ceb270b\n# \u2560\u2550a28ee7bb-d9d7-43ea-833f-6460a2cf7579\n# \u255f\u25004535c71f-be7c-41e8-940b-57289c83e509\n# \u255f\u2500f39cd55f-ed8f-487e-885e-f1e16b78d9dd\n# \u2560\u2550cd971faa-315a-4cea-a11a-0cb28f3e3997\n# \u255f\u2500a9febef3-06d0-4552-8590-2f165ce36547\n# \u2560\u25507b2588d2-d86d-44fb-9895-d6452875bc47\n# \u255f\u2500cc97f4d9-ad00-4d2c-b520-2071b9cf86f6\n# \u2560\u2550631bb03b-00a5-466a-be0d-36f86a9721aa\n# \u2560\u255095dc66d6-660a-4b0c-b89d-487a22dfec82\n# \u2560\u2550c5570bf1-c04d-41e3-b8ae-6e6dac45cb70\n# \u2560\u25508f945f6c-2561-433b-aedb-3448d2c4b419\n# \u255f\u2500ecd23fa3-fdd2-4ffb-a0e9-ad1feee04d22\n# \u2560\u2550f10e310f-165b-4b4b-b3e0-66af6430ba4f\n# \u2560\u25504c09eda3-8f4c-4fa2-91ea-99b92cfbb422\n# \u2560\u25501f2c5378-bbcd-4fb7-9130-9c6cebb4c6d4\n# \u255f\u2500517d31ba-5843-40a7-ad06-96e7a8ea8845\n# \u2560\u25501cc0a6c1-3fcf-4df3-a8d9-ba3454c0a37b\n# \u2560\u25509a76593b-c9a9-45cc-aca5-9877432baffd\n# \u2560\u25506a7ea8be-bea2-41c4-89ab-9a6bbcfba116\n# \u2560\u2550942e3f19-a5c1-430e-a3be-097c53bc7394\n# \u2560\u25506caa4b75-9ac1-496b-a4b2-38b72b203e59\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "# Test sample functions\n\nusing Distributions\nusing Base.Test\n\nfunction est_p(x, K)\n\th = zeros(Int, K)\n\tfor xi in x\n\t\th[xi] += 1\n\tend\n\tp = h / length(x)\nend\n\n#### sample with replacement\n\nn = 10^5\nx = sample([10,20,30], n)\n@test isa(x, Vector{Int})\n@test length(x) == n\n\nh = [sum(x .== 10), sum(x .== 20), sum(x .== 30)]\n@test sum(h) == n\nph = h / n\np0 = fill(1/3, 3)\n@test_approx_eq_eps ph p0 0.02\n\n\n#### sample without replacement\n\n# case: K == 2\n\nn = 10^5\nx = zeros(Int, 2, n)\nfor i = 1:n\n\tv = sample(11:15, 2; replace=false)\n\t@assert v[1] != v[2]\n\tx[:,i] = v\nend\n@test min(x) == 11\n@test max(x) == 15\n\nx[:] -= 10  # brings x to 1:5\np0 = fill(1/5, 5)\n@test_approx_eq_eps est_p(x, 5) p0 0.02\n\n# case: K == 4 with moderate a (using Fisher-Yates)\n\nn = 10^5\nx = zeros(Int, 4, n)\nfor i = 1 : n\n\tv = sample(11:20, 4; replace=false)\n\tsv = sort(v)\n\t@assert sv[1] < sv[2] < sv[3] < sv[4]\n\tx[:,i] = v\nend\n@test min(x) == 11\n@test max(x) == 20\n\nx[:] -= 10\np0 = fill(0.1, 10)\n@test_approx_eq_eps est_p(x, 10) p0 0.01\n\n# case: K == 4 with very large a (using self-avoid)\n\nn = 10^4\nx = zeros(Int, 4, n)\na = 10^7 + 1\nb = 2 * 10^7\nfor i = 1 : n\n\tv = sample(a:b, 4; replace=false)\n\tsv = sort(v)\n\t@assert sv[1] < sv[2] < sv[3] < sv[4]\n\tx[:,i] = v\nend\n@test min(x) >= a\n@test max(x) <= b\n\n\n#### weighted sampling\n\nw = [2., 5., 3.]\nn = 10^5\nx = wsample([10,20,30], w, n)\n\nh = [sum(x .== 10), sum(x .== 20), sum(x .== 30)]\n@test sum(h) == n\np0 = w / sum(w)\nph = h / n\n@test_approx_eq_eps ph p0 0.02\n\n", "meta": {"hexsha": "84b7d146cfe04e1a7f532fb5476f48fa7a68bbe4", "size": 1481, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sample.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": "test/sample.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": "test/sample.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": 16.2747252747, "max_line_length": 51, "alphanum_fraction": 0.5503038488, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7653204730715958}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mos\u00e8 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": "@testset \"nn\" begin\n    using LinearAlgebra\n    k = NeuralNetworkKernel()\n    v1 = rand(3); v2 = rand(3)\n    @test k(v1,v2) \u2248 asin(v1' * v2 / sqrt((1 + v1' * v1) * (1 + v2' * v2))) atol=1e-5\n\n    # kernelmatrix tests\n    m1 = rand(3,4)\n    m2 = rand(3,4)\n    @test kernelmatrix(k, m1, m1) \u2248 kernelmatrix(k, m1) atol=1e-5\n    @test_broken kernelmatrix(k, m1, m2) \u2248 k(m1, m2) atol=1e-5\n\n\n    x1 = rand()\n    x2 = rand()\n    @test kernelmatrix(k, x1*ones(1,1), x2*ones(1,1))[1] \u2248 k(x1, x2) atol=1e-5\n\n    @test k(v1, v2) \u2248 k(v1, v2) atol=1e-5\n    @test typeof(k(v1, v2)) <: Real\n\n    @test_broken size(k(m1, m2)) == (4, 4)\n    @test_broken size(k(m1)) == (4, 4)\n\n    A1 = ones(4, 4)\n    kernelmatrix!(A1, k, m1, m2)\n    @test A1 \u2248 kernelmatrix(k, m1, m2) atol=1e-5\n\n    A2 = ones(4, 4)\n    kernelmatrix!(A2, k, m1)\n    @test A2 \u2248 kernelmatrix(k, m1) atol=1e-5\n\n    @test size(kerneldiagmatrix(k, m1)) == (4,)\n    A3 = kernelmatrix(k, m1)\n    @test kerneldiagmatrix(k, m1) \u2248 [A3[i, i] for i in 1:LinearAlgebra.checksquare(A3)] atol=1e-5\n\n    A4 = ones(4)\n    kerneldiagmatrix!(A4, k, m1)\n    @test kerneldiagmatrix(k, m1) \u2248 A4 atol=1e-5\n\n    A5 = ones(4,4)\n    @test_throws AssertionError kernelmatrix!(A5, k, m1, m2, obsdim=3)\n    @test_throws AssertionError kernelmatrix!(A5, k, m1, obsdim=3)\n    @test_throws DimensionMismatch kernelmatrix!(A5, k, ones(4,3), ones(3,4))\n\n    @test k([x1], [x2]) \u2248 k(x1, x2) atol=1e-5\n    test_ADs(NeuralNetworkKernel, ADs = [:ForwardDiff, :ReverseDiff])\n    @test_broken \"Zygote uncompatible with BaseKernel\"\nend\n", "meta": {"hexsha": "6d6bb272c695eb55c531d85beed696c742069786", "size": 1545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 31.5306122449, "max_line_length": 97, "alphanum_fraction": 0.5980582524, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7653137081083556}}
{"text": "#--- test linear solve method (Foster PhD)\nusing Plots, Revise, VortexDistributions\n\npv1 = PointVortex(0.1,0.3,1)\nv1 = ScalarVortex(pv1)\n\nx = LinRange(-10,10,256)\ny = x\n\npsi = Torus(one.(x.*y') |> complex,x,y)\n\nvortex!(psi,v1)\n\npsiv = psi.\u03c8\n\nheatmap(x,y,angle.(psiv))\n\n#--- define linear solve (Foster)\n\nfunction vortex_detect2d(psi)\n# Detect vortices in a field psi, on plaquettes of a 2D grid.\n#\n# First we localize vortices on the grid plaquettes using the phase winding\n# algorithm.  After we've found which grid plaquettes contain vortices, we\n# estimate the positions more accurately by solving the equations\n#\n#   real(psi(x,y)) = 0, imag(psi(x,y)) = 0\n#\n# In principle we could do this using the exact psi as computed via spectral\n# interpolation (provided psi is defined in a spectral basis) but that would\n# probably be relatively slow.  Instead, we make a linear approximation over\n# the plaquette for the real and imaginary parts of psi, and find the position\n# where these approximations are mutually zero.  This corresponds to the\n# position of the vortex.\n#\n# The linear approximations are computed from the values of psi at the corners\n# of the plaquette using least squares.\n#\n# Inputs:\n#   psi - complex wavefunction in which to detect vortices.\n#\n# Outputs:\n#   positions - Array of vortex positions with shape 2xN where N is the number\n#               of vortices:  [ x1  x2  x3 ... xN ]\n#                             [ y1  y2  y3 ... yN ]\n#   winding - The vortex winding number of the positions array, +1 or -1.\n\nvorticity = phase_winding2d(angle(psi));\n[iy,ix] = find(vorticity);\npositions = [ix,iy]';\n\nif nargout > 1\n    winding = vorticity(vorticity~=0);\nend\n\n# % Compute least squares estimator for the linear function coefficients on a\n# % plaquette.  Suppose the real part of psi on a plaquette containing a vortex\n# % is\n# %\n# %   [r1 r2;\n# %    r3 r4]\n# %\n# % We want to fit a plane (a*x + b*y + c) to this such that\n# %\n# %   r1 = a*0 + b*0 + c*1\n# %   r2 = a*1 + b*0 + c*1\n# %   r3 = a*0 + b*1 + c*1\n# %   r4 = a*1 + b*1 + c*1\n# %\n# % In matrix form, that would be L * [a;b;c] = [r1;r2;r3;r4], which is the\n# % origin of the mysterious looking matrix below.\n# %\nL = [0 0 1;\n     1 0 1;\n     0 1 1;\n     1 1 1];\nlsEst = inv(L'*L)*L';\n# % (For future reference, lsEst actually turns out to be the following)\n# % lsEst = 1/4 * [-2,  2, -2,  2;\n# %                -2, -2,  2,  2;\n# %                 3,  1,  1, -1];\nfor i = 1:length(ix)\n    # Extract relevant grid plaquette containing the vortex.\n    p = psi(iy(i)+[0,1], ix(i)+[0,1]).'\n    # Compute linear approximations of real & imag parts of p\n    rcoeff = lsEst*real(p[:])\n    icoeff = lsEst*imag(p[:])\n    # Find position where these are mutually zero\n    pos = [rcoeff(1:2), icoeff(1:2)]' \\ -[rcoeff(3); icoeff(3)]\n    positions[:,i] = positions[:,i] + pos;\n    return positions, winding\nend\n", "meta": {"hexsha": "34d64f9e9e9513cd63ee38ec230bed18fbd254f2", "size": 2879, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_linearsolve_detection.jl", "max_stars_repo_name": "mcawte/VortexDistributions.jl", "max_stars_repo_head_hexsha": "6b67e5fad661c196f887a0a15069582617a8ecc5", "max_stars_repo_licenses": ["MIT"], "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_linearsolve_detection.jl", "max_issues_repo_name": "mcawte/VortexDistributions.jl", "max_issues_repo_head_hexsha": "6b67e5fad661c196f887a0a15069582617a8ecc5", "max_issues_repo_licenses": ["MIT"], "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_linearsolve_detection.jl", "max_forks_repo_name": "mcawte/VortexDistributions.jl", "max_forks_repo_head_hexsha": "6b67e5fad661c196f887a0a15069582617a8ecc5", "max_forks_repo_licenses": ["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.9569892473, "max_line_length": 79, "alphanum_fraction": 0.6380687739, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7653137060544081}}
{"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 \u2208 Z}\r\n#the quotient set with respect to Rn, is often denoted by Z/nZ.\r\n#Thus, Z/nZ := {[0], [1], . . . , [n \u2212 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}; \u03b8=Vector(0:(\u03c0/180):\u03c0-\u03c0/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- `\u03b8`: projection angle.(radian)\n- `in_circle`: \n\"\"\"\nfunction radon(f::Matrix{T}; \u03b8=Vector(0:(\u03c0/180):\u03c0-\u03c0/180)::Vector{T}, in_circle=true) where {T<:Real}\n    \u211bf = zeros(maximum(size(f)), length(\u03b8))\n    \n    slim, \u03b8lim = size(\u211bf)\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.(\u03b8)\n    sin_ = sin.(\u03b8)\n\n    s = LinRange(-L/2, L/2, slim)\n    t = LinRange(-L/2, L/2, L)\n    \n    for s\u1d62 \u2208 1:slim, \u03b8\u1d62 \u2208 1:\u03b8lim\n        for l \u2208 1:L\n            x = round(Int64, xlim/2 + s[s\u1d62]*cos_[\u03b8\u1d62] + t[l]*sin_[\u03b8\u1d62])\n            y = round(Int64, ylim/2 - t[l]*cos_[\u03b8\u1d62] + s[s\u1d62]*sin_[\u03b8\u1d62])\n            if 1 \u2264 x \u2264 xlim && 1 \u2264 y \u2264 ylim\n                \u211bf[s\u1d62, \u03b8\u1d62] += f[end-y+1, x]\n            end\n        end\n    end\n    \n    return \u211bf\nend\n\n\"\"\"\n    backprojection(\u211bf)(f::Matrix{T}, \u03b8::Vector{T}) where {T<:Real}\n\nreturn [back projection](https://freshrimpsushi.github.io/posts/back-projection-dual-transform-of-radon-transform/) of `\u211bf`\n\n# Keyword arguments\n\n- `\u211bf`: 2d array w.r.t. Radon transform of 'f'\n- `\u03b8`: projection angle(radian)\n\"\"\"\nfunction backprojection(\u211bf, \u03b8 = 0:\u03c0/180:\u03c0-\u03c0/180)\n    slim, \u03b8lim = size(\u211bf)\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) \u2208 zip(eachcol(\u211bf), \u03b8)\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}, \u03b8::Vector{T}) where {T<:Real}\n\nreturn animation for calculation backprojection of \u211bf\n\n# Keyword arguments\n\n- `\u211bf`: 2d array w.r.t. Radon transform of 'f'\n- `\u03b8`: projection angle(radian)\n\"\"\"\nfunction backprojection_anim(\u211bf)\n    slim, \u03b8lim = size(\u211bf)\n    reconstructed_image = zeros(slim, slim)\n\n    slim, \u03b8lim= size(\u211bf)\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    \u03b8 = 0 : \u03c0/\u03b8lim : \u03c0-\u03c0/\u03b8lim\n    s = range(-L/2, L/2, length=slim)\n\n    anim = Animation()\n    for (value, angle) \u2208 zip(eachcol(\u211bf), \u03b8)\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 _ \u2208 1:80\n        frame(anim, heatmap(reverse(reconstructed_image, dims=1)))\n    end\n    return anim\nend\n\n\"\"\"\n    iradon(\u211bf, method=\"fbp\")\n\nreturn Radon transform of `f`\n\n# Keyword arguments\n\n- `f`: phantom\n- `\u03b8`: projection angle\n\"\"\"\nfunction iradon(\u211bf, method=\"fbp\")\n    \n    if method == \"fbp\"\n        reconstructed_f = fitered_backprojection(\u211bf)\n    end\n\n    return reconstructed_f\nend\n\n\"\"\"\n    fitered_backprojection(\u211bff::Matrix{T}, \u03b8::Vector{T}) where {T<:Real}\nreturn f\n\n# Keyword arguments\n\n- `\u211bf`: 2d array w.r.t. Radon transform of `f`\n- `\u03b8`: projection angle\n\"\"\"\nfunction fitered_backprojection(\u211bf)\n    N = size(\u211bf)[1]\n    \n    \u2131\u211bf = fft(\u211bf, [1])\n    \n    fourier_filter = abs.(fftfreq(N))    \n    filterd_\u2131\u211bf = \u2131\u211bf .* fourier_filter\n\n    \u2131\u207b\u00b9_filterd_\u2131\u211bf = real.(ifft(filterd_\u2131\u211bf, [1]))\n\n    reconstructed_f = (\u03c0/360)*backprojection(\u2131\u207b\u00b9_filterd_\u2131\u211bf)\n    return reconstructed_f\nend\n\n\"\"\"\n    SART(\u211bf)\nreturn Radon transform of `f`\n\n# Keyword arguments\n\n- `\u211bf`: 2d array w.r.t. Radon transform of 'f'\n- `\u03b8`: projection angle\n\"\"\"\nfunction SART(\u211bf)\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 + \u03b5, where W is a matrix, m is a vector and \u03b5 is a noise term\n    # z[n] ~ N(0,I), where I is the identity matrix\n    # \u03b5 ~ 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    \u03b8 = pPCAParams(Matrix{Float64}(undef,D,M), m, 1.0) # \u03b8 holds the parameters\n    Mz = randn(M,N)              # Mz[:,n] = MEAN[z[n]]\n    \u03a3z = [zeros(M,M) for n=1:N]  # \u03a3z[n] = COV[z[n]]\n\n    function eStep!(Mz, \u03a3z)\n        # Update Mz and \u03a3z\n        W = \u03b8.W; v = \u03b8.v\n\n        if has_missing_values\n            for n=1:N\n                _W = W[observed_d[n],:]\n                _x = x_observed[n] - \u03b8.m[observed_d[n]]\n                M_inv = inv(_W'*_W + v*Matrix{Float64}(I, M, M))\n                \u03a3z[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            \u03a3z[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!(\u03b8)\n        # Update W, m, v\n        if has_missing_values\n            m = zero(\u03b8.m)\n            for n=1:N\n                m[observed_d[n]] += x_observed[n] .- (\u03b8.W[observed_d[n],:] * Mz[:,n])[:,1]\n            end\n            m = m ./ (N .- sum(missing_values, dims=2)[:,1])\n            \u03b8.m = m\n\n            for d=1:D\n                A = inv(Mz[:,observed_n[d]]*Mz[:,observed_n[d]]' + sum(\u03a3z[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                \u03b8.W[d,:] = ( A * b )'\n            end\n            W = \u03b8.W\n\n            \u03b8.v = 0.0\n            for n=1:N\n                for d in observed_d[n]\n                    \u03b8.v +=  (X[d,n] .- (W[d,:]'*Mz[:,n])[1] - m[d])^2 + (W[d,:]' * \u03a3z[n] * W[d,:])[1]\n                end\n            end\n            \u03b8.v = \u03b8.v / (N*D-sum(missing_values))\n\n        else\n            # no need to update m\n            W = _X * Mz' * inv(Mz*Mz' + N*\u03a3z[1])\n            \u03b8.W = W\n            \u03b8.v = sum((_X - W*Mz).^2)/(N*D) + tr(W*\u03a3z[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!(\u03b8)\n        eStep!(Mz, \u03a3z)\n    end\n\n    return (\u03b8, 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 \u22c3(Sets...)\n#     return reduce(\u222a, Sets)\n# end\nconst \u22c3 = union\n\nfunction \u2202(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\u2202([1,2,3])\n\u2202([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": "using NURBS\nusing Base.Test\n\n@testset \"bsurface Building\" begin\n    \n\tarr = [-100.0 -100.0 -100.0 -100.0 -100.0 -50.0 -50.0 -50.0 -50.0 -50.0 0.0 0.0 0.0 0.0 0.0 50.0 50.0 50.0 50.0 50.0 100.0 100.0 100.0 100.0 100.0;-100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0 -100.0 -50.0 0.0 50.0 100.0;0.0 0.0 0.0 0.0 0.0 0.0 25.0 50.0 25.0 0.0 0.0 25.0 50.0 25.0 0.0 0.0 25.0 150.0 25.0 0.0 0.0 0.0 0.0 0.0 0.0]\n\n\tres = [-100.0 -100.0 -100.0 -100.0 -25.9259 -25.9259 -25.9259 -25.9259 25.9259 25.9259 25.9259 25.9259 100.0 100.0 100.0 100.0; -100.0 -25.9259 25.9259 100.0 -100.0 -25.9259 25.9259 100.0 -100.0 -25.9259 25.9259 100.0 -100.0 -25.9259 25.9259 100.0; 0.0 0.0 0.0 0.0 0.0 34.8422 34.8422 0.0 0.0 51.3032 51.3032 0.0 0.0 0.0 0.0 0.0]\n\n    resu = [\n        -50.0 -50.0 -50.0 -50.0 -16.6667 -16.6667 -16.6667  -16.6667 16.6667 16.6667 16.6667 16.6667 50.0 50.0 50.0 50.0; \n        -50.0 -16.6667 16.6667 50.0 -50.0 -16.6667 16.6667 50.0 -50.0 -16.6667 16.6667 50.0 -50.0 -16.6667 16.6667 50.0;\n        20.8333 32.6646 32.6646 20.8333 25.6687 41.7905 41.7905 25.6687 31.0185 60.2176 60.2176 31.0185 31.9444 70.9362 70.9362 31.9444\n    ]\n\n    @testset \"B-spline surface using open uniform knot vectors\" begin\n        @test typeof(bsplsurf(arr, 4, 4, 5, 5, 100, 100)) == Tuple{Array{Float64, 2}, Array{Array{Int64, 1}, 1}, Array{Array{Int64, 1}, 1}}\n        @test isapprox(bsplsurf(arr, 4, 4, 5, 5, 4, 4)[1], res; atol = 1e-3)\n    end\n\n    @testset \"B-spline surface using periodic uniform knot vectors\" begin\n        @test typeof(bsplsurfu(arr, 4, 4, 5, 5, 100, 100)) == Tuple{Array{Float64, 2}, Array{Array{Int64, 1}, 1}, Array{Array{Int64, 1}, 1}}\n        @test isapprox(bsplsurfu(arr, 4, 4, 5, 5, 4, 4)[1], resu; atol = 1e-3)\n    end\n        \n    @testset \"B-spline surface and its derivatives using open uniform knot vectors\" begin\n        @test typeof(dbsurf(arr, 4, 4, 5, 5, 100, 100)) == Tuple{Array{Float64,2}, Array{Float64,2}, Array{Float64,2}, Array{Float64,2}, Array{Float64,2}, Array{Float64,2}, Array{Array{Int64, 1}, 1}, Array{Array{Int64, 1}, 1}}\n        @test isapprox(dbsurf(arr, 4, 4, 5, 5, 4, 4)[1], res; atol = 1e-3)\n    end\n\n    @testset \"B-Spline surface over open knot comparison\" begin\n        @test bsplsurf(arr, 4, 4, 5, 5, 100, 100)[1] == dbsurf(arr, 4, 4, 5, 5, 100, 100)[1]\n        @test bsplsurf(arr, 4, 4, 5, 5, 100, 100)[2] == dbsurf(arr, 4, 4, 5, 5, 100, 100)[7]\n        @test bsplsurf(arr, 4, 4, 5, 5, 100, 100)[3] == dbsurf(arr, 4, 4, 5, 5, 100, 100)[8]\n    end\nend\n", "meta": {"hexsha": "4e49d8c38af7d862723e636120ad2faab2f990c7", "size": 2564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bsurfaces.jl", "max_stars_repo_name": "eOnofri04/IN480", "max_stars_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-06T17:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:30:18.000Z", "max_issues_repo_path": "test/bsurfaces.jl", "max_issues_repo_name": "TheChoice04/IN480", "max_issues_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-11-22T18:10:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-07T16:32:36.000Z", "max_forks_repo_path": "test/bsurfaces.jl", "max_forks_repo_name": "TheChoice04/IN480", "max_forks_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-06T17:54:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T17:54:09.000Z", "avg_line_length": 69.2972972973, "max_line_length": 398, "alphanum_fraction": 0.6017940718, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7653136939543339}}
{"text": "\"\"\"\n    function discrete_gamma_rates(\u03b1::T, \u03b2::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(\u03b1::T, \u03b2::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 = \u03b1/\u03b2*k\n\n    if method==:median\n        meanvals .= median_boundaries(\u03b1, \u03b2, k)\n        t = sum(meanvals)\n        meanvals .*= (factor / t)\n    else\n        meanvals .= mean_boundaries(\u03b1, \u03b2, k)\n        @inbounds @simd for i in 1:k-1\n            meanvals[i] = gamma_inc(\u03b1+1,meanvals[i]*\u03b2, 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(\u03b1::T, \u03b2::S, k::Int64)::Array{Float64} where {T<:Real, S<:Real}\n    ch = Chisq((2*\u03b1)/(2*\u03b2))\n    boundaries = Array{Float64, 1}(undef, k)\n    for i in 1:k-1\n        boundaries[i] = quantile(ch, i/k)/(2*\u03b2)\n    end\n    boundaries\nend\n\nfunction median_boundaries(\u03b1::T, \u03b2::S, k::Int64)::Array{Float64} where {T<:Real, S<:Real}\n    ch = Chisq((2*\u03b1)/(2*\u03b2))\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": "using FourierTools\n\n\nf(x) = sin(x * 2\u03c0)\nx = [0.0, 0.2, 0.4, 0.6, 0.8] \n\n@show(f.(x))\n@show(f.(x .- 0.5))\n@show(shift(f.(x), -2.5))\n\n\n\nplot(x, f.(x))\n#plot!(range(0, 1, length=100), resample(f.(x), (100,)))\nplot!(x .- 0.5, f.(x .- 0.5))\nplot!(x .- 0.5, shift(f.(x), -2.5))\n", "meta": {"hexsha": "b5c1581a64fe264c35f71fbcc0842303052547c9", "size": 272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/paper/fft_pixel_shifting.jl", "max_stars_repo_name": "bionanoimaging/FourierTools.jl", "max_stars_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2021-03-30T23:15:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:20:15.000Z", "max_issues_repo_path": "examples/paper/fft_pixel_shifting.jl", "max_issues_repo_name": "bionanoimaging/FourierTools.jl", "max_issues_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-03-28T13:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T09:43:02.000Z", "max_forks_repo_path": "examples/paper/fft_pixel_shifting.jl", "max_forks_repo_name": "bionanoimaging/FourierTools.jl", "max_forks_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_forks_repo_licenses": ["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.0, "max_line_length": 56, "alphanum_fraction": 0.4779411765, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620468, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.765313690133665}}
{"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": "# ---\n# title: 1109. Corporate Flight Bookings\n# id: problem1109\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Array, Math\n# link: <https://leetcode.com/problems/corporate-flight-bookings/description/>\n# hidden: true\n# ---\n# \n# There are `n` flights, and they are labeled from `1` to `n`.\n# \n# We have a list of flight bookings.  The `i`-th booking `bookings[i] = [i, j,\n# k]` means that we booked `k` seats from flights labeled `i` to `j` inclusive.\n# \n# Return an array `answer` of length `n`, representing the number of seats\n# booked on each flight in order of their label.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\n#     Output: [10,55,45,25,25]\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= bookings.length <= 20000`\n#   * `1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000`\n#   * `1 <= bookings[i][2] <= 10000`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "1274a815fbf37983294a9389ac74889a0481861c", "size": 991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1109.corporate-flight-bookings.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_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/1109.corporate-flight-bookings.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "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/unresolved/1109.corporate-flight-bookings.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["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.5227272727, "max_line_length": 79, "alphanum_fraction": 0.595358224, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7653079377755125}}
{"text": "using Base: front, tail\n\n\"\"\"\n    \u2297(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 \u2297(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    \u2297(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\u2297(ts...) = reduce(\u2297, ts; init=Tensor(1))\n\n\"\"\"\n    \u22c5(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 \u22c5(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 '\u00dcberschiebung' 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 \u2297 and \u22c5 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": "\"\"\"\nBased on\nhttps://districtdatalabs.silvrback.com/parameter-tuning-with-hyperopt\n\"\"\"\nmodule TestSimple\n\nusing Test\nusing TreeParzen\n\n# Simple 1\nbest = fmin(params -> params[:x], Dict(:x => HP.Uniform(:x, 0.0, 1.0)), 100)\n@test isapprox(best[:x], 0.00076079610166447, rtol = 1e1)\n\n# Simple 2\nobjective(params) = (params[:x] - 1)^2\nbest = fmin(objective, Dict(:x => HP.Uniform(:x, -2.0, 2.0)), 100)\n@test isapprox(best[:x], 0.9990226896297454, rtol = 1e1)\n\n# fspace\nfspace = Dict(:x => HP.Uniform(:x, -5.0, 5.0))\nobjective(params) = params[:x]^2\nbest = fmin(objective, fspace, 50)\n@test isapprox(best[:x], 0.035669063364728415, rtol = 1e1)\n\nend\ntrue\n", "meta": {"hexsha": "4d0db741b0acaa99191b22b2f8f11f0122cae230", "size": 650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/silvrback.jl", "max_stars_repo_name": "lhnguyen-vn/TreeParzen.jl", "max_stars_repo_head_hexsha": "d6b4181a45167663e8844330220f0c62c715c75f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-05-06T09:06:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T22:41:16.000Z", "max_issues_repo_path": "test/silvrback.jl", "max_issues_repo_name": "lhnguyen-vn/TreeParzen.jl", "max_issues_repo_head_hexsha": "d6b4181a45167663e8844330220f0c62c715c75f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2020-05-15T14:29:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T15:24:44.000Z", "max_forks_repo_path": "test/silvrback.jl", "max_forks_repo_name": "lhnguyen-vn/TreeParzen.jl", "max_forks_repo_head_hexsha": "d6b4181a45167663e8844330220f0c62c715c75f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-09-11T03:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T18:42:50.000Z", "avg_line_length": 24.0740740741, "max_line_length": 76, "alphanum_fraction": 0.6753846154, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7652822846818157}}
{"text": "\"\"\"\n    mode(nums)\n\nFinds mode of a vector of numbers\n\n# Example\n\n```julia\nmode([2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2])        # returns [2]\nmode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2])        # returns [2]\nmode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2])  # returns [2, 4]\nmode([\"x\", \"y\", \"y\", \"z\"])                              # returns [\"y\"]\nmode([\"x\", \"x\" , \"y\", \"y\", \"z\"])                       # returns [\"x\", \"y\"]\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction mode(nums)\n    dict = Dict() # nums => Number of repetitions\n    result = [] # Array of the modes so far\n    max = 0 # Max of repetitions so far\n\n    for i in nums\n        # Add one to the dict[i] entry (create one if none)\n        if i in keys(dict)\n            dict[i] += 1\n        else\n            dict[i] = 1\n        end\n        # Result updated if no of repetitions of i >= max\n        if dict[i] >= max\n            if dict[i] > max\n                empty!(result)\n                max += 1\n            end\n            append!(result, [i])\n        end\n    end\n\n    return result\nend\nprintln(mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))\nprintln(mode((1, 1, 2, 4, 4)))\n", "meta": {"hexsha": "de617d2ed588539e35874a370f13a1d97b8a1426", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/average_mode.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/math/average_mode.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/math/average_mode.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": 27.0909090909, "max_line_length": 75, "alphanum_fraction": 0.4530201342, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.765260085233534}}
{"text": "\"\"\"Length of Longest Common Subsequence problem in Julia\n\nGiven two strings, we have to find the largest common subsequence in Julia\n\nThe problem can be solved using Dynamic Programming\n\"\"\"\n\nfunction lengthoflongestcommonsubsequence(S1, S2)\n    # Build a 2D matrix in Bottom-Up manner. Every element\n    # dp[i][j] contains the length of the longest common subsequence\n    # of S1[0 .. i] and S2[0 .. j].\n    n = length(S1)\n    m = length(S2)\n\n    # Fill every element of the 2D matrix with 0 as value\n    dp = zeros(Int, n + 1, m + 1)\n\n    for i in 1:(n + 1)\n        for j in 1:(m + 1)\n\n            # length of LCS when one of the string is empty is zero\n            if i == 1 || j == 1\n                dp[i,j] = 0\n\n            # If the elements of both the strings match, then\n            # the value of LCS increments by one.\n            elseif S1[i - 1] == S2[j - 1]\n                dp[i,j] = dp[(i - 1),(j - 1)] + 1\n            else\n            # Either include the last element from one string and exclude it from the other and \n            # compare them and vice versa and pick the one giving the maximum length out of the two \n                dp[i,j] = max(dp[(i - 1),j], dp[i,(j - 1)])\n            end\n        end\n    end\n    return dp[(n + 1),(m + 1)]\nend\n\n\nprint(\"Enter the first string: \")\ns1 = readline()\nprint(\"Enter the second string: \")\ns2 = readline()\nres = lengthoflongestcommonsubsequence(s1, s2)\nprint(\"The length of the longest common subsequence is \")\nprint(res)\n\n\n# Time Complexity: O(n * m), where n, m are the size of the given strings\n# Space Complexity: O(n * m)\n\n# SAMPLE INPUT AND OUTPUT\n\n# Enter the first string: cuckoo\n# Enter the second string: cucumber\n# The length of the longest common subsequence is 3\n", "meta": {"hexsha": "a6a11cf520a52aa91dd26ff76e9e71365a5e8b06", "size": 1740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/dp/length_longest_common_subsequence.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/dp/length_longest_common_subsequence.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/dp/length_longest_common_subsequence.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": 30.5263157895, "max_line_length": 100, "alphanum_fraction": 0.6091954023, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.7652600803423266}}
{"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    \u03bc = mean(null)\n    n = length(X)\n    T = (mean(X) - \u03bc)/\u221a(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": "using LinearAlgebra\nusing ProximalOperators\nusing Test\n\n@testset \"HuberLoss\" begin\n\nf = HuberLoss(1.5, 0.7)\n\npredicates_test(f)\n\n@test ProximalOperators.is_smooth(f) == true\n@test ProximalOperators.is_quadratic(f) == false\n@test ProximalOperators.is_set(f) == false\n\nx = randn(10)\nx = 1.6*x/norm(x)\n\ncall_test(f, x)\nprox_test(f, x, 1.3)\ngrad_fx, fx = gradient_test(f, x)\n\n@test abs(fx - f(x)) <= 1e-12\n@test norm(0.7*1.5*x/norm(x) - grad_fx, Inf) <= 1e-12\n\nx = randn(10)\nx = 1.4*x/norm(x)\n\ncall_test(f, x)\nprox_test(f, x, 0.9)\ngrad_fx, fx = gradient_test(f, x)\n\n@test abs(fx - f(x)) <= 1e-12\n@test norm(0.7*x - grad_fx, Inf) <= 1e-12\n\nend", "meta": {"hexsha": "b97c57fb7d9dbcb2ef36c44a21842dfa2a46ed8d", "size": 638, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_huberLoss.jl", "max_stars_repo_name": "kul-forbes/ProximalOperators.jl", "max_stars_repo_head_hexsha": "fcd3d987f6af7d701cd32c61e6c14594baa6289e", "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": "test/test_huberLoss.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": "test/test_huberLoss.jl", "max_forks_repo_name": "kul-forbes/ProximalOperators.jl", "max_forks_repo_head_hexsha": "fcd3d987f6af7d701cd32c61e6c14594baa6289e", "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": 18.2285714286, "max_line_length": 53, "alphanum_fraction": 0.6692789969, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7652354314380817}}
{"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": "import FastTransforms\nimport QuadratureRules: shift_nodes\n\n@testset \"$(rpad(\"Lobatto-Chebyshev\",80))\" begin\n\n    @test_throws ErrorException LobattoChebyshevQuadrature(1)\n\n    for s in 2:10\n        @test LobattoChebyshevQuadrature(s) == ChebyshevQuadrature(s, 2)\n        @test LobattoChebyshevQuadrature(s) == ChebyshevQuadrature(Float64, s, Val(2))\n        \n        @test sum(weights(LobattoChebyshevQuadrature(s))) \u2248 1\n\n        c = shift_nodes(reverse(FastTransforms.chebyshevpoints(Float64, s, Val(2))))\n\n        @test chebyshev_points(Float64, s, Val(2)) \u2248 c\n        @test nodes(LobattoChebyshevQuadrature(s)) \u2248 c\n\n        # TODO test weights\n\n    end\n\nend\n", "meta": {"hexsha": "5611739abc65d46cb0962bfb95ab89a6cf520a4d", "size": 661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_lobatto_chebyshev.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": "test/test_lobatto_chebyshev.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": "test/test_lobatto_chebyshev.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": 27.5416666667, "max_line_length": 86, "alphanum_fraction": 0.6868381241, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7652354229115371}}
{"text": "@doc raw\"\"\"\n    PowerKernel([\u03b3=1])\n\nThe Power Kernel is a negative definite kernel given by:\n```\n    \u03ba(x,y) = \u2016x-y\u2016\u00b2\u1d5e   \u03b3 \u2208 (0,1]\n```\nwhere `\u03b3` 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    \u03b3::T\n    function PowerKernel{T}(\u03b3::Real=T(1)) where {T<:AbstractFloat}\n        @check_args(PowerKernel, \u03b3, one(T) >= \u03b3 > zero(T), \"\u03b3 \u2208 (0,1]\")\n        new{T}(\u03b3)\n    end\nend\nPowerKernel(\u03b3::T=1.0) where {T<:Real} = PowerKernel{promote_float(T)}(\u03b3)\n\n@inline basefunction(::PowerKernel) = SquaredEuclidean()\n\n@inline kappa(\u03ba::PowerKernel{T}, d\u00b2::T) where {T} = d\u00b2^\u03ba.\u03b3\n\nfunction convert(::Type{K}, \u03ba::PowerKernel) where {K>:PowerKernel{T}} where T\n    return PowerKernel{T}(\u03ba.\u03b3)\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) = \u2081F\u2081(a; b; z)`.\n\"\"\"\nfunction _\u2081F\u2081(a, b, z)\n    if real(z) \u2265 0\n        return _\u2081F\u2081maclaurin(a, b, z)\n    else\n        return exp(z)*_\u2081F\u2081(b-a, b, -z)\n    end\nend\n\n\"\"\"\nCompute Kummer's confluent hypergeometric function `M(a, b, z) = \u2081F\u2081(a; b; z)`.\n\"\"\"\nconst M = _\u2081F\u2081\n\n\"\"\"\nCompute Tricomi's confluent hypergeometric function `U(a, b, z) \u223c z\u207b\u1d43 \u2082F\u2080([a, a-b+1]; []; -z\u207b\u00b9)`.\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] \u2265 0, Int)\n@objective(m, Max, sum(PROFIT * projects))\n@constraint(m, sum(COSTS * projects) \u2264 LIMIT)\n@constraint(m, projects[1] + projects[2] \u2264 1) # can only choose one of 1 or 2\n@constraint(m, projects[3] + projects[4] \u2264 1) # can only choose one of 3 or 4\n@constraint(m, projects[3] + projects[4] \u2264 projects[1] + projects[2]) # we can do 3 or 4 only if we do 1 or 2\n@constraint(m, projects .\u2264 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": "module DivConformingFESpacesTests\n\nusing Test\nusing Gridap.Geometry\nusing Gridap.ReferenceFEs\nusing Gridap.FESpaces\nusing Gridap.CellData\nusing Gridap.TensorValues\nusing Gridap.Fields\nusing Gridap.Io\n\ndomain =(0,1,0,1)\npartition = (3,3)\nmodel = CartesianDiscreteModel(domain,partition)\n\norder = 1\n\nu(x) = x\n\nreffe = ReferenceFE(raviart_thomas,order)\n\nV = TestFESpace(model,reffe,dirichlet_tags = [1,6])\ntest_single_field_fe_space(V)\n\nU = TrialFESpace(V,u)\n\nuh = interpolate(u,U)\n\ne = u - uh\n\n\u03a9 = Triangulation(model)\nd\u03a9 = Measure(\u03a9,2*order)\n\nel2 = sqrt(sum( \u222b( e\u22c5e )*d\u03a9 ))\n@test el2 < 1.0e-10\n\n#using Gridap.Visualization\n#\n#writevtk(\u03a9,\"trian\",nsubcells=10,cellfields=[\"uh\"=>uh])\n\norder = 1\n\nreffe = ReferenceFE(TET,raviart_thomas,order)\n\ndomain =(0,1,0,1,0,1)\npartition = (3,3,3)\nmodel = simplexify(CartesianDiscreteModel(domain,partition))\n\nlabels = get_face_labeling(model)\ndir_tags = Array{Integer}(undef,0)\n\nV = FESpace(model,reffe,conformity=DivConformity())\n\nv(x) = VectorValue(-0.5*x[1]+1.0,-0.5*x[2],-0.5*x[3])\nvh = interpolate(v,V)\n\ne = v - vh\n\n\u03a9 = Triangulation(model)\nd\u03a9 = Measure(\u03a9,2*order)\n\nel2 = sqrt(sum( \u222b( e\u22c5e )*d\u03a9 ))\n@test el2 < 1.0e-10\n\n#using Gridap.Visualization\n#\n#writevtk(trian,\"test\",order=3,cellfields=[\"vh\"=>vh])\n\n# Tests on manifold\n\n# Create domain\ndomain = (0,1,0,1,0,1)\ncells  = (2,2,2)\nmodel  = CartesianDiscreteModel(domain,cells)\n\n# Restrict model to cube surface (using new BoundaryDiscreteModel)\nlabels = get_face_labeling(model)\nbgface_to_mask = get_face_mask(labels,\"boundary\",2)\n\u0393face_to_bgface = findall(bgface_to_mask)\nDc2Dp3model = BoundaryDiscreteModel(Polytope{2},model,\u0393face_to_bgface)\n\norder  = 0\ndegree = 1\n\nreffe_rt = ReferenceFE(raviart_thomas,Float64,order)\nV  = FESpace(Dc2Dp3model, reffe_rt ; conformity=:HDiv)\nuh = FEFunction(V,rand(num_free_dofs(V)))\nvh = interpolate_everywhere(uh,V)\n\nT\u2095_K = Triangulation(Dc2Dp3model)\nQ\u2095_K = CellQuadrature(T\u2095_K,degree)\ne=sqrt(sum(\u222b((uh-vh)\u22c5(uh-vh))Q\u2095_K))\n@test e < 1.0e-12\n\nend # module\n", "meta": {"hexsha": "6c674de9a345e57ac4b328f30b734057fffb38d4", "size": 1978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FESpacesTests/DivConformingFESpacesTests.jl", "max_stars_repo_name": "AndiMD/Gridap.jl", "max_stars_repo_head_hexsha": "cdb45ce70be228eb0804d64e0a540b3fbcdad441", "max_stars_repo_licenses": ["MIT"], "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/FESpacesTests/DivConformingFESpacesTests.jl", "max_issues_repo_name": "AndiMD/Gridap.jl", "max_issues_repo_head_hexsha": "cdb45ce70be228eb0804d64e0a540b3fbcdad441", "max_issues_repo_licenses": ["MIT"], "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/FESpacesTests/DivConformingFESpacesTests.jl", "max_forks_repo_name": "AndiMD/Gridap.jl", "max_forks_repo_head_hexsha": "cdb45ce70be228eb0804d64e0a540b3fbcdad441", "max_forks_repo_licenses": ["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.6041666667, "max_line_length": 70, "alphanum_fraction": 0.731041456, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7651485590287309}}
{"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\u2032(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\u2032), 0.0), Roots.Newton())\n    r = Roots.newton(x->(f(x),f(x)/f\u2032(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    \u03b4V =  - 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    \u03b4V =  - 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    \u2202\u00b2P = ForwardDiff.hessian(v, [0.0])\n    return \u2202\u00b2P[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": "@testset \"xlogx, xlogy, and xlog1py\" begin\n    @test iszero(xlogx(0))\n    @test xlogx(2) \u2248 2.0 * log(2.0)\n    @test_throws DomainError xlogx(-1)\n    @test isnan(xlogx(NaN))\n\n    @test iszero(xlogy(0, 1))\n    @test xlogy(2, 3) \u2248 2.0 * log(3.0)\n    @test_throws DomainError xlogy(1, -1)\n    @test isnan(xlogy(NaN, 2))\n    @test isnan(xlogy(2, NaN))\n    @test isnan(xlogy(0, NaN))\n\n    @test iszero(xlog1py(0, 0))\n    @test xlog1py(2, 3) \u2248 2.0 * log1p(3.0)\n    @test_throws DomainError xlog1py(1, -2)\n    @test isnan(xlog1py(NaN, 2))\n    @test isnan(xlog1py(2, NaN))\n    @test isnan(xlog1py(0, NaN))\n\n    # Since we allow complex/negative values, test for them. See comments in:\n    # https://github.com/JuliaStats/StatsFuns.jl/pull/95\n\n    @test xlogx(1 + im) == (1 + im) * log(1 + im)\n    @test isnan(xlogx(NaN + im))\n    @test isnan(xlogx(1 + NaN * im))\n\n    @test xlogy(-2, 3) == -xlogy(2, 3)\n    @test xlogy(1 + im, 3) == (1 + im) * log(3)\n    @test xlogy(1 + im, 2 + im) == (1 + im) * log(2 + im)\n    @test isnan(xlogy(1 + NaN * im, -1 + im))\n    @test isnan(xlogy(0, -1 + NaN * im))\n    @test isnan(xlogy(Inf + im * NaN, 1))\n    @test isnan(xlogy(0 + im * 0, NaN))\n    @test iszero(xlogy(0 + im * 0, 0 + im * Inf))\n\n    @test xlog1py(-2, 3) == -xlog1py(2, 3)\n    @test xlog1py(1 + im, 3) == (1 + im) * log1p(3)\n    @test xlog1py(1 + im, 2 + im) == (1 + im) * log1p(2 + im)\n    @test isnan(xlog1py(1 + NaN * im, -1 + im))\n    @test isnan(xlog1py(0, -1 + NaN * im))\n    @test isnan(xlog1py(Inf + im * NaN, 1))\n    @test isnan(xlog1py(0 + im * 0, NaN))\n    @test iszero(xlog1py(0 + im * 0, -1 + im * Inf))\nend\n\n@testset \"xexpx\" begin\n    for x in (false, 0, 0.0, 0f0, -Inf, -Inf32)\n        @test (@inferred xexpx(x)) === zero(exp(x))\n    end\n    for x in (NaN16, NaN32, NaN64, Inf16, Inf32, Inf64)\n        @test (@inferred xexpx(x)) === x\n    end\n    for x in (1, true, 1.0, 1f0)\n        @test (@inferred xexpx(x)) === exp(x)\n    end\n    for a in (2, 2f0, 2.0), x in -a:a\n        @test (@inferred xexpx(x)) === x * exp(x)\n    end\nend\n\n@testset \"xexpy\" begin\n    for x in (0, 1, 1.0, 1f0, Inf, Inf32), y in (-Inf, -Inf32)\n        @test (@inferred xexpy(x, y)) === zero(x * exp(y))\n    end\n    for x in (0, 1, 1.0, 1f0, Inf, Inf32, -Inf, -Inf32, NaN, NaN32), nan in (NaN, NaN32)\n        @test (@inferred xexpy(x, nan)) === oftype(x * exp(nan), NaN)\n        @test (@inferred xexpy(nan, x)) === oftype(nan * exp(x), NaN)\n    end\n    for x in (2, -2f0, 2.0), y in (1, -1f0, 1.0)\n        @test (@inferred xexpy(x, y)) \u2248 x * exp(y)\n    end\n    for x in (randn(), randn(Float32))\n        @test xexpy(x, x) \u2248 xexpx(x)\n    end\nend\n\n@testset \"logistic & logit\" begin\n    @test logistic(2) \u2248 1.0 / (1.0 + exp(-2.0))\n    @test logistic(-750.0) === 0.0\n    @test logistic(-740.0) > 0.0\n    @test logistic(+36.0) < 1.0\n    @test logistic(+750.0) === 1.0\n    @test iszero(logit(0.5))\n    @test logit(logistic(2)) \u2248 2.0\nend\n\n@testset \"logcosh\" begin\n    for x in (randn(), randn(Float32))\n        @test @inferred(logcosh(x)) isa typeof(x)\n        @test logcosh(x) \u2248 log(cosh(x))\n        @test logcosh(-x) == logcosh(x)\n    end\n\n    # special values\n    for x in (-Inf, Inf, -Inf32, Inf32)\n        @test @inferred(logcosh(x)) === oftype(x, Inf)\n    end\n    for x in (NaN, NaN32)\n        @test @inferred(logcosh(x)) === x\n    end\nend\n\n@testset \"log1psq\" begin\n    @test iszero(log1psq(0.0))\n    @test log1psq(1.0) \u2248 log1p(1.0)\n    @test log1psq(2.0) \u2248 log1p(4.0)\nend\n\n# log1pexp, log1mexp, log2mexp & logexpm1\n\n@testset \"log1pexp\" begin\n    for T in (Float16, Float32, Float64, BigFloat), x in 1:40\n        @test (@inferred log1pexp(+log(T(x)))) \u2248 T(log1p(big(x)))\n        @test (@inferred log1pexp(-log(T(x)))) \u2248 T(log1p(1/big(x)))\n    end\n\n    # special values\n    @test (@inferred log1pexp(0)) \u2248 log(2)\n    @test (@inferred log1pexp(0f0)) \u2248 log(2)\n    @test (@inferred log1pexp(big(0))) \u2248 log(2)\n    @test (@inferred log1pexp(+1)) \u2248 log1p(\u212f)\n    @test (@inferred log1pexp(-1)) \u2248 log1p(\u212f) - 1\n\n    # large arguments\n    @test (@inferred log1pexp(1e4)) \u2248 1e4\n    @test (@inferred log1pexp(1f4)) \u2248 1f4\n    @test iszero(@inferred log1pexp(-1e4))\n    @test iszero(@inferred log1pexp(-1f4))\n\n    # compare to accurate but slower implementation\n    correct_log1pexp(x::Real) = x > 0 ? x + log1p(exp(-x)) : log1p(exp(x))\n    # large range needed to cover all branches, for all floats (from Float16 to BigFloat)\n    for T in (Int, Float16, Float32, Float64, BigInt, BigFloat), x in -300:300\n        @test (@inferred log1pexp(T(x))) \u2248 float(T)(correct_log1pexp(big(x)))\n    end\n    # test BigFloat with multiple precisions\n    for prec in (10, 20, 50, 100), x in -300:300\n        setprecision(prec) do\n            y = big(float(x))\n            @test @inferred(log1pexp(y)) \u2248 correct_log1pexp(y)\n        end\n    end\nend\n\n@testset \"log1mexp\" begin\n    @test log1mexp(-1.0)  \u2248 log1p(- exp(-1.0))\n    @test log1mexp(-10.0) \u2248 log1p(- exp(-10.0))\nend\n\n@testset \"log2mexp\" begin\n    @test log2mexp(0.0)  \u2248 0.0\n    @test log2mexp(-1.0) \u2248 log(2.0 - exp(-1.0))\nend\n\n@testset \"logexpm1\" begin\n    @test logexpm1(2.0)            \u2248  log(exp(2.0) - 1.0)\n    @test logexpm1(log1pexp(2.0))  \u2248  2.0\n    @test logexpm1(log1pexp(-2.0)) \u2248 -2.0\n\n    @test logexpm1(2f0)            \u2248  log(exp(2f0) - 1f0)\n    @test logexpm1(log1pexp(2f0))  \u2248  2f0\n    @test logexpm1(log1pexp(-2f0)) \u2248 -2f0\nend\n\n@testset \"log1pmx\" begin\n    @test iszero(log1pmx(0.0))\n    @test log1pmx(1.0) \u2248 log(2.0) - 1.0\n    @test log1pmx(2.0) \u2248 log(3.0) - 2.0\nend\n\n@testset \"logmxp1\" begin\n    @test iszero(logmxp1(1.0))\n    @test logmxp1(2.0) \u2248 log(2.0) - 1.0\n    @test logmxp1(3.0) \u2248 log(3.0) - 2.0\nend\n\n@testset \"logsumexp\" begin\n    @test logaddexp(2.0, 3.0)     \u2248 log(exp(2.0) + exp(3.0))\n    @test logaddexp(10002, 10003) \u2248 10000 + logaddexp(2.0, 3.0)\n\n    for x in ([1.0], Complex{Float64}[1.0])\n        @test @inferred(logsumexp(x)) == 1.0\n        @test @inferred(logsumexp((xi for xi in x))) == 1.0\n    end\n\n    for x in ([1.0, 2.0, 3.0], Complex{Float64}[1.0, 2.0, 3.0])\n        @test @inferred(logsumexp(x)) \u2248 3.40760596444438\n        @test logsumexp(x .+ 1000) \u2248 1003.40760596444438\n    end\n\n    for x in ((1.0, 2.0, 3.0), map(complex, (1.0, 2.0, 3.0)))\n        @test @inferred(logsumexp(x)) \u2248 3.40760596444438\n    end\n\n    _x = [[1.0, 2.0, 3.0] [1.0, 2.0, 3.0] .+ 1000.]\n    for x in (_x, complex(_x))\n        @test @inferred(logsumexp(x; dims=1)) \u2248 [3.40760596444438 1003.40760596444438]\n        @test @inferred(logsumexp(x; dims=[1, 2])) \u2248 [1003.4076059644444]\n        y = copy(x')\n        @test @inferred(logsumexp(y; dims=2)) \u2248 [3.40760596444438, 1003.40760596444438]\n    end\n\n    # check underflow\n    @test logsumexp([1e-20, log(1e-20)]) \u2248 2e-20\n    @test logsumexp(Complex{Float64}[1e-20, log(1e-20)]) \u2248 2e-20\n\n    let cases = [([-Inf, -Inf], -Inf),   # correct handling of all -Inf\n                 ([-Inf, -Inf32], -Inf), # promotion\n                 ([-Inf32, -Inf32], -Inf32), # Float32\n                 ([-Inf, Inf], Inf),\n                 ([-Inf, 9.0], 9.0),\n                 ([Inf, 9.0], Inf),\n                 ([0, 0], log(2.0))] # non-float arguments\n        for (arguments, result) in cases\n            @test logaddexp(arguments...) \u2261 result\n            @test logsumexp(arguments) \u2261 result\n            @test logsumexp(complex(arguments)) \u2261 complex(result)\n        end\n    end\n\n    @test isnan(logsubexp(Inf, Inf))\n    @test logsubexp(-Inf, -Inf) \u2261 -Inf\n    @test logsubexp(Inf, -Inf) \u2261 Inf\n    @test logsubexp(-Inf, Inf) \u2261 Inf\n    @test logsubexp(Inf, 9.0) \u2261 Inf\n    @test logsubexp(9.0, Inf) \u2261 Inf\n    @test logsubexp(-Inf, 9.0) \u2261 9.0\n    @test logsubexp(9.0, -Inf) \u2261 9.0\n    @test logsubexp(1f2, 1f2) \u2261 -Inf32\n    @test logsubexp(0, 0) \u2261 -Inf\n    @test logsubexp(3, 2) \u2248 2.541324854612918108978\n\n    # NaN propagation\n    for f in (logaddexp, logsubexp)\n        @test isnan(f(NaN, 9.0))\n        @test isnan(f(NaN, Inf))\n        @test isnan(f(NaN, -Inf))\n        @test isnan(f(9.0, NaN))\n        @test isnan(f(Inf, NaN))\n        @test isnan(f(-Inf, NaN))\n    end\n\n    @test isnan(logsumexp([NaN, 9.0]))\n    @test isnan(logsumexp([NaN, Inf]))\n    @test isnan(logsumexp([NaN, -Inf]))\n    @test isnan(logsumexp(Complex{Float64}[NaN, 9.0]))\n    @test isnan(logsumexp(Complex{Float64}[NaN, Inf]))\n    @test isnan(logsumexp(Complex{Float64}[NaN, -Inf]))\n    @test isnan(logsumexp(Complex{Float64}[NaN * im, 9.0]))\n    @test isnan(logsumexp(Complex{Float64}[NaN * im, Inf]))\n    @test isnan(logsumexp(Complex{Float64}[NaN * im, -Inf]))\n\n    # logsumexp with general iterables (issue #63)\n    xs = range(-500, stop = 10, length = 1000)\n    @test @inferred(logsumexp(x for x in xs)) == logsumexp(xs)\n    xs = range(-500 + 0.5im, stop = 10 + 30im, length = 1000)\n    @test @inferred(logsumexp(x for x in xs)) == logsumexp(xs)\n\n    # complex numbers\n    xs = randn(Complex{Float64}, 10, 5)\n    @test @inferred(logsumexp(xs)) \u2248 log(sum(exp.(xs)))\n    @test @inferred(logsumexp(xs; dims=1)) \u2248 log.(sum(exp.(xs); dims=1))\n    @test @inferred(logsumexp(xs; dims=2)) \u2248 log.(sum(exp.(xs); dims=2))\n    @test @inferred(logsumexp(xs; dims=[1, 2])) \u2248 log(sum(exp.(xs); dims=[1, 2]))\n    @test @inferred(logsumexp(x for x in xs)) == logsumexp(xs)\nend\n\n@testset \"softmax\" begin\n    x = [1.0, 2.0, 3.0]\n    r = exp.(x) ./ sum(exp.(x))\n\n    # in-place versions\n    for T in (Float32, Float64)\n        s = Vector{T}(undef, 3)\n        softmax!(s, x)\n        @test s \u2248 r\n\n        fill!(s, zero(T))\n        softmax!(s, x; dims=1)\n        @test s \u2248 r\n\n        s = Matrix{T}(undef, 1, 3)\n        softmax!(s, x)\n        @test s \u2248 permutedims(r)\n\n        @test_throws DimensionMismatch softmax!(s, x; dims=1)\n\n        fill!(s, zero(T))\n        softmax!(s, permutedims(x); dims=2)\n        @test s \u2248 permutedims(r)\n\n        fill!(s, zero(T))\n        softmax!(s, permutedims(x); dims=1:2)\n        @test s \u2248 permutedims(r)\n    end\n    softmax!(x)\n    @test x \u2248 r\n\n    for (S, T) in ((Int, Float64), (Float64, Float64), (Float32, Float32))\n        x = S[1, 2, 3]\n        s = softmax(x)\n        @test s \u2248 r\n        @test eltype(s) === T\n\n        x = repeat(S[1, 2, 3], 1, 3)\n        s = softmax(x; dims=1)\n        @test s \u2248 repeat(r, 1, 3)\n        @test eltype(s) === T\n\n        x = repeat(S[1 2 3], 3, 1)\n        s = softmax(x; dims=2)\n        @test s \u2248 repeat(permutedims(r), 3, 1)\n        @test eltype(s) === T\n\n        x = S[1 2 3]\n        s = softmax(x; dims=1:2)\n        @test s \u2248 permutedims(r)\n        @test eltype(s) === T\n    end\n\n    x = [1//2, 2//3, 3//4]\n    r = exp.(x) ./ sum(exp.(x))\n    s = softmax(x)\n    @test s \u2248 r\n    @test eltype(s) === Float64\n\n    # non-standard indices: #12\n    x = OffsetArray(1:3, -2:0)\n    s = softmax(x)\n    @test s isa OffsetArray{Float64}\n    @test axes(s, 1) == OffsetArrays.IdOffsetRange(-2:0)\n    @test collect(s) \u2248 softmax(1:3)\nend\n", "meta": {"hexsha": "c30a7ae5a33c587d30bc9b59d575142fd585f6f7", "size": 10800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basicfuns.jl", "max_stars_repo_name": "cossio/LogExpFunctions.jl", "max_stars_repo_head_hexsha": "4e50c5441e18beed15720e20d997ead272f1ecc1", "max_stars_repo_licenses": ["MIT"], "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/basicfuns.jl", "max_issues_repo_name": "cossio/LogExpFunctions.jl", "max_issues_repo_head_hexsha": "4e50c5441e18beed15720e20d997ead272f1ecc1", "max_issues_repo_licenses": ["MIT"], "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/basicfuns.jl", "max_forks_repo_name": "cossio/LogExpFunctions.jl", "max_forks_repo_head_hexsha": "4e50c5441e18beed15720e20d997ead272f1ecc1", "max_forks_repo_licenses": ["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.2388059701, "max_line_length": 89, "alphanum_fraction": 0.5519444444, "num_tokens": 4412, "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": "\"\"\"\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    \u03bb\u2081, \u03c6\u2081 = x\n    \u03bb\u2082, \u03c6\u2082 = y\n\n    \u0394\u03bb = \u03bb\u2082 - \u03bb\u2081  # longitudes\n    \u0394\u03c6 = \u03c6\u2082 - \u03c6\u2081  # latitudes\n\n    # haversine formula\n    a = sind(\u0394\u03c6/2)^2 + cosd(\u03c6\u2081)*cosd(\u03c6\u2082)*sind(\u0394\u03bb/2)^2\n\n    # distance on the sphere\n    2 * (dist.radius * asin( min(\u221aa, 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    \u03bb\u2081, \u03c6\u2081 = x\n    \u03bb\u2082, \u03c6\u2082 = y\n\n    \u0394\u03bb = \u03bb\u2082 - \u03bb\u2081  # longitudes\n    \u0394\u03c6 = \u03c6\u2082 - \u03c6\u2081  # latitudes\n\n    # haversine formula\n    a = sin(\u0394\u03c6/2)^2 + cos(\u03c6\u2081)*cos(\u03c6\u2082)*sin(\u0394\u03bb/2)^2\n\n    # distance on the sphere\n    2 * asin( min(\u221aa, 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(), \"\u0394TC\"=> 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, :\u03c3, :sigmoid, :hard\u03c3, :hardsigmoid, :hardtanh, :relu,\n    :leakyrelu, :relu6, :rrelu, :prelu, :elu, :gelu, :swish, :selu,\n    :celu, :softplus, :softsign, :log\u03c3, :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    \u03c3(x)\nStandard sigmoid activation function. Also, this function can be called with `\u03c3`. 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 \u03c3 = 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\u03c3`. 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\u03c3 = 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; \u03b1=0.01) = (x>0) ? x : \u03b1*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; \u03b1=0.01f0) = max(x, \u03b1*x)\n\n@doc raw\"\"\"\n    rrelu(min, max)\nRandomized Rectified Linear Unit. The expression is the as [`leakyrelu`](@ref), but `\u03b1` 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    \u03b1::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.\u03b1*x)\n\n@doc raw\"\"\"\n    prelu(; \u03b1=0.01)\nParametric Ractified LinearUnit. The expression is the as [`leakyrelu`](@ref), but `\u03b1` is determined by learning. Also, when using this function, use [`Dense\u03c3`](@ref) instead of [`Dense`](@ref).\n\"\"\"\nstruct prelu\n    \u03b1::Union{Float64, Float32}\n    prelu(; \u03b1=0.01) = new(\u03b1)\nend\n\n(prelu::prelu)(x) = max(x, prelu.\u03b1*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, \u03b1=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, \u03b1) = \\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; \u03b1=1) = (x<0) ? (exp(x)-1)\u03b1 : x\n\n@doc raw\"\"\"\n    celu(x; \u03b1=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; \u03b1=1) = (x>=0) ? x : \u03b1*(exp(x/\u03b1)-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) = \u03c3(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    \u03bb = oftype(float(x), selu_\u03bb)\n    \u03b1 = oftype(float(x), selu_\u03b1)\n    return ((x > 0) ? x : (exp(x)-1)\u03b1)*\u03bb\nend\n\nconst selu_\u03bb = 1.0507009873554804934193349852946\nconst selu_\u03b1 = 1.6732632423543772848170429916717\n\n@doc raw\"\"\"\n    trelu(x; \u03b8=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; \u03b8=1) = (x<=\u03b8) ? 0 : x\n\n@doc raw\"\"\"\n    log\u03c3(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(\u03c3(x))\nconst log\u03c3 = 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; \u03bb=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; \u03bb=0.5) = min(x+\u03bb, max(x-\u03bb, 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; \u03b2=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; \u03b2=1) = x * \u03c3(\u03b2*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": "using DiffEqSensitivity, OrdinaryDiffEq, DiffEqBase, ForwardDiff\r\nusing Test\r\n\r\nfunction fb(du,u,p,t)\r\n  du[1] = dx = p[1]*u[1] - p[2]*u[1]*u[2]\r\n  du[2] = dy = -p[3]*u[2] + p[4]*u[1]*u[2]\r\nend\r\n\r\nfunction jac(J,u,p,t)\r\n  (x, y, a, b, c) = (u[1], u[2], p[1], p[2], p[3])\r\n  J[1,1] = a + y * b * -1\r\n  J[2,1] = y\r\n  J[1,2] = b * x * -1\r\n  J[2,2] = c * -1 + x\r\nend\r\n\r\nf = ODEFunction(fb,jac=jac)\r\np = [1.5,1.0,3.0,1.0]; u0 = [1.0;1.0]\r\nprob = ODEProblem(f,u0,(0.0,10.0),p)\r\nloss(sol) = sum(sol)\r\nv = ones(4)\r\n\r\nH  = second_order_sensitivities(loss,prob,Vern9(),saveat=0.1,abstol=1e-12,reltol=1e-12)\r\nHv = second_order_sensitivity_product(loss,v,prob,Vern9(),saveat=0.1,abstol=1e-12,reltol=1e-12)\r\n\r\n_loss(p) = loss(concrete_solve(prob,Vern9(),u0,p,saveat=0.1,abstol=1e-12,reltol=1e-12))\r\nH2 = ForwardDiff.hessian(_loss,p)\r\nH2v = H*v\r\n\r\n@test H \u2248 H2\r\n@test Hv \u2248 H2v\r\n", "meta": {"hexsha": "8218d8f25c1fa442e56b5caa72215319d7032026", "size": 864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/second_order.jl", "max_stars_repo_name": "frankschae/DiffEqSensitivity.jl", "max_stars_repo_head_hexsha": "8d8895b920ff0d1203cc69affbe77a072e182c68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-01T10:02:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T10:02:51.000Z", "max_issues_repo_path": "test/second_order.jl", "max_issues_repo_name": "frankschae/DiffEqSensitivity.jl", "max_issues_repo_head_hexsha": "8d8895b920ff0d1203cc69affbe77a072e182c68", "max_issues_repo_licenses": ["MIT"], "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/second_order.jl", "max_forks_repo_name": "frankschae/DiffEqSensitivity.jl", "max_forks_repo_head_hexsha": "8d8895b920ff0d1203cc69affbe77a072e182c68", "max_forks_repo_licenses": ["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": 96, "alphanum_fraction": 0.5810185185, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7651429903523704}}
{"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 \u2265 (maximum(F.table.scale) + F.interval/2.0) return 100.0 end\n    x\u2032 = round2(x)\n    Fx1 = CDF(x\u2032-F.interval, F)\n    Fx = CDF(x\u2032, F)\n    P = 100*(Fx1+(x-x\u2032+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 \u2265 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 \u2264 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    \u03bcX = mean(X.raw); \u03c3X = std(X.raw)\n    \u03bcY = mean(Y.raw); \u03c3Y = std(Y.raw)\n    slope = \u03c3Y/\u03c3X; intercept = \u03bcY - slope*\u03bcX\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    \u03bcX = mean(X.raw)\n    \u03bcY = mean(Y.raw)\n    slope = 1.0; intercept = \u03bcY - \u03bcX\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_\u03b5\", \"sigma2_\u03b7\"]\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_\u03b5\" => observed_variance, \"sigma2_\u03b7\" => 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_\u03b5\")\n    constrain_variance!(model, \"sigma2_\u03b7\")\n    return model\nend\n\nfunction unconstrain_hyperparameters!(model::LocalLevel)\n    unconstrain_variance!(model, \"sigma2_\u03b5\")\n    unconstrain_variance!(model, \"sigma2_\u03b7\")\n    return model\nend\n\nfunction fill_model_system!(model::LocalLevel)\n    model.system.H = get_constrained_value(model, \"sigma2_\u03b5\")\n    model.system.Q[1] = get_constrained_value(model, \"sigma2_\u03b7\")\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, \u03b40, \u0394t, N)\n    # solve the reference trajectory\n    problem = ODEProblem(rhs_fn, x0, (0, N*\u0394t), 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 *= \u03b40 / 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*\u0394t\n        # advance neighboring trajectory\n        p = ODEProblem(rhs_fn, x_test, ((i - 1)*\u0394t, t), params)\n        neighboring_sol = solve(p, solver,  reltol=tol, abstol=tol, dense=true)\n        # compute seperation\n        \u03b4 = norm(neighboring_sol(t) - ref_sol(t))\n        # update result\n        s += log(\u03b4 / \u03b40)\n        # rescale the neighboring trajectory\n        x_ref = ref_sol(t)\n        x_test = x_ref + \u03b40 / \u03b4 * (x_test - x_ref)\n    end\n    # result\n    return s / (\u0394t * N)\nend\n\nfunction lorentz_rhs(du, u, p, t)\n    \u03b2, \u03c3, \u03c1 = p\n    x, y, z = u\n    du[1] = \u03c3 * (y - x)\n    du[2] = - x * z - \u03c1 * x - y\n    du[3] = x * y - \u03b2 * z\nend\n\n\u03b2 = 8 / 3.\n\u03c3 = 10.0\n\u03c1_range = 20:0.1:100\n\u03bbs = [compute_max_lyapunov_exponent(lorentz_rhs, [1.0, 1.0, 1.0],\n           [\u03b2, \u03c3, \u03c1], 1e-5, 0.001, 20)\n     for \u03c1 = \u03c1_range]\nplot(\u03c1_range, \u03bbs)\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": "#\u00a0This 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]) |\u00a0(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    #\u00a0Loop 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": "using LinearAlgebra\n\n\"\"\"\n# Description\nFind the conical hull defined by the following constraints:\n  1\u1d40x = c\n  Ax \u2264 b\n  x \u2265 0\n# Returns\n* `::PolyhedralCone`: conical hull of constraints\n\"\"\"\nfunction cone_from_constraints(A::Matrix{T}, b::Vector{T}, c::T) where T<: Real\n    m, n = size(A)\n    m == length(b) || error(\"A and b must have consistent dimensions\")\n    c > 0 || error(\"c must be strictly positive\")\n    A_poly = Array{T}(undef, m+n, n)\n    A_poly[1:m,:] = broadcast(*, b, ones(T,m,n)) - A\n    A_poly[m+1:n+m,:] = Array{T}(LinearAlgebra.I, n, n)\n    return PolyhedralCone{T}(A_poly)\nend\n\nfunction cone_from_constraints(A::Matrix{T}, b::Vector{T}, c::T) where T <: Rational\n    m, n = size(A)\n    m == length(b) || error(\"A and b must have consistent dimensions\")\n    c > 0 || error(\"c must be strictly positive\")\n    A_poly = Array{T}(undef, m+n, n)\n    A_poly[1:m,:] = broadcast(*, b, ones(T,m,n)) - A\n    A_poly[n+1:n+m,:] = Array{T}(LinearAlgebra.I, n, n)\n    return PolyhedralCone{T}(cones.intmat(A_poly))\nend\n    \n\"\"\"\n# Description\nFinds the conical hull of of the region define\nby the following constraints:\n\n1\u1d40 x = 1\nx \u2264 u\nx \u2265 0\n# Returns\n* `::PolyhedralCone` conical hull from constraints\n\"\"\"\nfunction quota_cone(u::Vector{T}) where T <: Real\n    n = length(u)\n    return cone_from_constraints(Array{T}(LinearAlgebra.I, n, n), u, one(T))\nend\n\nfunction checkRiskRegionArgs(\u03bc::Vector{Float64}, \u03a3::Matrix{Float64},\n                             K::Cone, \u03b1::Float64)\n        if length(\u03bc) != size(\u03a3, 1) ArgumentError(\"\u03bc and \u03a3 must have consistent dimensions\") end\n        if !LinearAlgebra.isposdef(\u03a3) ArgumentError(\"\u03a3 must be a positive definite matrix\") end\n        if length(K) != length(\u03bc) ArgumentError(\"Cone must be in same dimension as mean vector\") end\n        if \u03b1 <= 0 ArgumentError(\"\u03b1 must be strictly positive\") end\nend\n", "meta": {"hexsha": "578aa7fba3fe724eee56558415d21dba0842e255", "size": 1844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "STOR-i/EllipticalScenGen.jl", "max_stars_repo_head_hexsha": "9656ad3b630fe7171e6042f9b436037171010402", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-02-01T14:30:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T17:43:18.000Z", "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "STOR-i/EllipticalScenGen.jl", "max_issues_repo_head_hexsha": "9656ad3b630fe7171e6042f9b436037171010402", "max_issues_repo_licenses": ["MIT"], "max_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": "STOR-i/EllipticalScenGen.jl", "max_forks_repo_head_hexsha": "9656ad3b630fe7171e6042f9b436037171010402", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-19T00:49:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T00:49:15.000Z", "avg_line_length": 33.5272727273, "max_line_length": 100, "alphanum_fraction": 0.6458785249, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7651429737762364}}
{"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 \u2260 i2\n\n# Uninitialized ITensor\nZpZm = ITensor(i1, i2)\n\n# State |Z+\u27e9\u2081|Z-\u27e9\u2082 \u2261 |Z+Z-\u27e9\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+\u27e9\u2081\nZp1 = state(\"Z+\", i1)\n# State |Z+\u27e9\u2082\nZp2 = state(\"Z+\", i2)\n\n# State |Z-\u27e9\u2081\nZm1 = state(\"Z-\", i1)\n# State |Z-\u27e9\u2082\nZm2 = state(\"Z-\", i2)\n\n# State |Z+Z-\u27e9 = |Z+\u27e9\u2081|Z-\u27e9\u2082\nZpZm = Zp1 * Zm2\n\n# State |Z+Z-\u27e9 = |Z-\u27e9\u2082|Z+\u27e9\u2081 = |Z+\u27e9\u2081|Z-\u27e9\u2082\n# Order doesn't matter!\nZpZm = Zm2 * Zp1\n\n# State |Z-Z+\u27e9\nZmZp = Zm1 * Zp2\n\n# State |Z+Z+\u27e9\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-\u27e9|Z-\u27e9\nZmZm = Zm1 * Zm2\n\n# Cat state (|Z+\u27e9|Z-\u27e9 + |Z-\u27e9|Z+\u27e9) / \u221a2\n\n# With element setting:\nCat = ITensor(i1, i2)\nCat[i1 => 1, i2 => 2] = 1 / \u221a2\nCat[i1 => 2, i2 => 1] = 1 / \u221a2\n\n# Or build from single site basis states:\nCat = (Zp1 * Zm2 + Zm1 * Zp2) / \u221a(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\u0304 = .5\nh = .001\n@show Dfwd(u,x\u0304,h) - dudx(x\u0304)\n@show Dback(u,x\u0304,h) - dudx(x\u0304)\n@show D2(u,x\u0304,h) - dudx(x\u0304)\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  \u03b1, \u03b2, \u03b4, \u03b3 = p\r\n  du[1] = dx = \u03b1*x - \u03b2*x*y\r\n  du[2] = dy = -\u03b4*y + \u03b3*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, \u03a9; 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(\u03a9) == 1\n        \u03a9 = diagm(0 => \u03a9)\n    end\n\n    w = inv(\u03a9)  # Weights defined as 1/\u03c3\u00b2\n    X\u1d40 = transpose(X)\n    k\u03c9 = inv(X\u1d40*w*X)*X\u1d40*w\n    coeffs = k\u03c9*y\n    \u03a3 = k\u03c9*\u03a9*k\u03c9'\n    coeffs, \u03a3\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\u1d40 = transpose(X)\n    inv(X\u1d40*X)*X\u1d40*y\nend\n\nfunction plotresiduals(x, y, coefficients; ax=nothing)\n    if ax \u2261 nothing\n        fig, ax = plt.subplots(ncols=2)\n    end\n    p = Poly(coefficients)\n    y\u0302 = p.(y)\n    xrange = range(minimum(x), maximum(x), length=100)\n    y\u0302range = p.(xrange)\n\n    e\u0302 = y\u0302 - y\n    ax[1].scatter(x, y)\n    ax[1].scatter(x, y\u0302)\n    ax[1].plot(xrange, y\u0302range, \"--\")\n    ax[1].set_title(\"Fit\")\n    ax[2].scatter(x, e\u0302)\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        \u03bc = [NaN64 for k in 1:n]\n        \u03b1 = 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        \u03bc[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] * \u03bc[k-1]\n            \u03bc[k] = h[k] / l[k]\n            z[k] = (\u03b1[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] - \u03bc[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\u0119 na odwr\u00f3t kolejno\u015bci to wychodz\u0105 \u0142adne rysunki b\u0142\u0119d\u00f3w\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, \u03b1, facts, e, f)\n    suma = .0\n    for i in 0:e\n        hi = f(pi*(k+i)/2 + \u03b1) / (2*\u03b1)^(k+i+1)\n        fact = facts[i+1]\n        suma += (hi*fact)\n    end\n    return suma / silnia(k)\nend\n\nfunction Xk(k, \u03b1)\n    return Hk(k, \u03b1, ilorazysilni(k)[1], k-1, cos)\nend\nfunction Yk(k, \u03b1)\n    return Hk(k, \u03b1, ilorazysilni(k)[2], k, sin)\nend\n\nfunction Hn(t, n, \u03b1, Hks, c1, c2)\n    suma = .0\n    c = t^2 - \u03b1^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, \u03b1, Xks)\n    return Hn(t, n, \u03b1, Xks, 2*\u03b1, cos(\u03b1))\nend\nfunction Yn(t, n, \u03b1, Xks)\n    return Hn(t, n, \u03b1, Xks, 2*t, t*sin(\u03b1)/\u03b1)\nend\n\n\nfunction arc(n, \u03b1, r)\n    Xks = [Xk(k, \u03b1) for k in 1:n]\n    Yks = [Yk(k, \u03b1) for k in 1:n]\n\n    angles = [t for t in -\u03b1:prec:\u03b1]\n\n    xvalues = r * [Xn(t, n, \u03b1, Xks) for t in angles]\n    yvalues = r * [Yn(t, n, \u03b1, 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, \u03b1 = pi, r = 1)\n    a = arc(n, \u03b1, r)\n    angles, errors = a[1]\n    xvalues, yvalues = a[2]\n\n    if \u03b1 == 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 \u03b1 == 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 \u03b1 == 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, \u03b1 = pi, r = 1)\n    Xks = [Xk(k, \u03b1) for k in 1:n]\n    Yks = [Yk(k, \u03b1) for k in 1:n]\n\n    angles = [t for t in -\u03b1:prec:\u03b1]\n\n    xvalues = r * [Xn(t, n, \u03b1, Xks) for t in angles]\n    yvalues = r * [Yn(t, n, \u03b1, 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": "include(\"euler/euler.jl\")\nusing .Numbers: count_divisors\n\nfunction compute(n::Int)::Int\n    i, triangle = 1, 1\n    while count_divisors(triangle) < n\n        i += 1\n        triangle += i\n    end\n    return triangle\nend\n", "meta": {"hexsha": "c4a6e8394fe1f47ae1e0a050e6bb2bae0be31daa", "size": 219, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/0012/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/0012/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/0012/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": 18.25, "max_line_length": 38, "alphanum_fraction": 0.6255707763, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.765082582158012}}
{"text": "\"\"\"\n    loglik(\u03b7, x)\n\nCompute the simple (linear) birth and death process log-likelihood where\n``\u03b7 = (\u03bb, \u03bc)^{\\\\prime}``, `\u03bb` is the birth rate, `\u03bc` 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 ``\u03b1 = (\u03bc e^{(\u03bb - \u03bc) t} - \u03bc) / (\u03bb e^{(\u03bb - \u03bc) t} - \u03bc)`` and\n``\u03b2 = (\u03bb e^{(\u03bb - \u03bc) t} - \u03bb) / (\u03bb e^{(\u03bb - \u03bc) t} - \u03bc)``. Transition probability\n`p(j | i, t, \u03bb, \u03bc)` is equal to (Bailey, 1964):\n``\\\\sum_{h = 0}^{\\\\min(i, j)} \\\\binom{i}{h} \\\\binom{i + j - h - 1}{i - 1}\n\u03b1^{i - h} \u03b2^{j - h} (1 - \u03b1 - \u03b2)^{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(\u03bb, \u03bc | x) = \\\\log p(n[S] | n[S], T - t[S], \u03bb, \u03bc) +\n\\\\sum_{s = 1}^{S} \\\\log p(n[s] | n[s - 1], t[s] - t[s - 1], \u03bb, \u03bc)``.\nIf we observe `M` independent processes with same parameters `(\u03bb, \u03bc)`, then\n``l(\u03bb, \u03bc | x[1], ..., x[M]) = \\\\sum_{m = 1}^{M} l(\u03bb, \u03bc | x[m]).``\n\nIf the process is observed continously over time period `[0, T]`, log-likelihood\nsimplifies to (Darwin, 1956, Equation (24)):\n``l(\u03bb, \u03bc | x) = B \\\\log \u03bb + D \\\\log \u03bc - (\u03bb + \u03bc) 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  \u03b7::Vector{F},\n  x::ObservationContinuousTime\n)::F where {\n  F <: AbstractFloat\n}\n  x.tot_births * log(\u03b7[1]) +\n  x.tot_deaths * log(\u03b7[2]) -\n  (\u03b7[1] + \u03b7[2]) * x.integrated_jump +\n  x.sum_log_n\nend\n\nfunction loglik(\n  \u03b7::Vector{F},\n  x::Vector{ObservationContinuousTime}\n)::F where {\n  F <: AbstractFloat\n}\n  mapreduce(y -> loglik(\u03b7, y), +, x)\nend\n\nfunction loglik(\n  \u03b7::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, \u03b7), +, itr)\n  end\n\n  sum(l)\nend\n\nfunction loglik(\n  \u03b7::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..., \u03b7), +, itr)\nend\n\nfunction loglik(\n  \u03b7::Vector{F},\n  x::Vector{ObservationDiscreteTimeUneven}\n)::F where {\n  F <: AbstractFloat\n}\n  mapreduce(y -> loglik(\u03b7, 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#   (\u0394 + k^2*I) * u = f\n#\n# in a unit disk |\ud835\udc31| \u2264 1, \n# using orthogonal polynomials (in x and y) in a disk\n# with the weight (1-|\ud835\udc31|^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\u0394 = Z \\ (Laplacian(xy) * W)\nS = Z \\ W # identity\n\n\nk = 20\nL = \u0394 + 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\u2099 = Z[:,Block.(1:N)]\nW\u2099 = W[:,Block.(1:N)]\nL\u2099 = L[Block.(1:N),Block.(1:N)]\n\nu = W\u2099 * (L\u2099 \\ (Z\u2099 \\ f))\ncontourf(u)\n\n\n# We can also do eigenvalues of the Laplacian\nN = 20\n\u0394\u2099 = \u0394[Block.(1:N),Block.(1:N)]\nS\u2099 = S[Block.(1:N),Block.(1:N)]\n\n\u03bb,Q = eigen(Symmetric(Matrix(\u0394\u2099)), Symmetric(Matrix(S\u2099)))\n\ncontourf(W\u2099 * 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\u03c0)\n\nlanczos(w,5)\n\n\n# Marchenco\u2013Pastur 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))/(\u03c0*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\u03c0*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) \u2229 Q(s2, q)| / |Q(s1, q) \u222a 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) \u2229 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) \u2229 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 \u222a 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 MultivariateStats\nusing LinearAlgebra\nusing Test\n\n## testing data\n\nfunction pwdists(X)\n    S = sum(abs2, X, dims=1)\n    D2 = S .+ S' - 2 * (X'X)\n    D2[diagind(D2)] .= 0.0\n    return sqrt.(D2)\nend\n\nX0 = randn(3, 5)\nG0 = X0'X0\nD0 = pwdists(X0)\n\n## conversion between dmat and gram\n\n@assert issymmetric(D0)\n@assert issymmetric(G0)\n\nD = gram2dmat(G0)\n@test issymmetric(D)\n@test D \u2248 D0\n\nG = dmat2gram(D0)\n@test issymmetric(G)\n@test gram2dmat(G) \u2248 D0\n\n## classical MDS\n\nX = classical_mds(D0, 3)\n@test pwdists(X) \u2248 D0\n\n#Test MDS embeddings in dimensions >= number of points\n@test classical_mds([0 1; 1 0], 2, dowarn=false) == [-0.5 0.5; 0 0]\n@test classical_mds([0 1; 1 0], 3, dowarn=false) == [-0.5 0.5; 0 0; 0 0]\n\n\n#10 - dmat2gram produces negative definite matrix\nlet D = [1.0 0.5 0.3181818181818182 0.38095238095238093 0.6111111111111112 0.36363636363636365 0.3333333333333333 0.4444444444444444 0.45454545454545453 0.38095238095238093\n        0.5 1.0 0.3333333333333333 0.4166666666666667 0.32 0.37037037037037035 0.35 0.38461538461538464 0.38461538461538464 0.4\n        0.3181818181818182 0.3333333333333333 1.0 0.38095238095238093 0.125 0.22727272727272727 0.47058823529411764 0.35294117647058826 0.2608695652173913 0.21052631578947367\n        0.38095238095238093 0.4166666666666667 0.38095238095238093 1.0 0.17391304347826086 0.2962962962962963 0.38095238095238093 0.45454545454545453 0.3076923076923077 0.5454545454545454\n        0.6111111111111112 0.32 0.125 0.17391304347826086 1.0 0.5 0.15 0.391304347826087 0.38095238095238093 0.3333333333333333\n        0.36363636363636365 0.37037037037037035 0.22727272727272727 0.2962962962962963 0.5 1.0 0.2857142857142857 0.44 0.4 0.3181818181818182\n        0.3333333333333333 0.35 0.47058823529411764 0.38095238095238093 0.15 0.2857142857142857 1.0 0.42105263157894735 0.45 0.23529411764705882\n        0.4444444444444444 0.38461538461538464 0.35294117647058826 0.45454545454545453 0.391304347826087 0.44 0.42105263157894735 1.0 0.5416666666666666 0.5555555555555556\n        0.45454545454545453 0.38461538461538464 0.2608695652173913 0.3076923076923077 0.38095238095238093 0.4 0.45 0.5416666666666666 1.0 0.4\n        0.38095238095238093 0.4 0.21052631578947367 0.5454545454545454 0.3333333333333333 0.3181818181818182 0.23529411764705882 0.5555555555555556 0.4 1.0],\n    Xt = [-0.27529104101488666 0.006134513718202863 0.33298809606740326 0.2608994458893664 -0.46185275796909575 -0.23734315039370618 0.29972782027671513 0.03827901455843394 -0.04096713097883363 0.07742518984640051\n        -0.08177061420820278 -0.0044504235228030225 -0.3271919093638943 0.28206254638779243 -0.0954706915166714 -0.07137742126520012 -0.30754933764853587 0.18582658369448027 -0.03715307349750036 0.45707434094053534]',\n    M = classical_mds(D, 2)'\n    @test M \u2248 Xt .* cis.(angle.(sum(conj.(Xt) .* M, dims=1)))\nend\n\n#10 - test degenerate problem\n@test classical_mds(zeros(10, 10), 3, dowarn=false) == zeros(3, 10)\n", "meta": {"hexsha": "de953b732d84cd1aa022ef97a0fb923dbe910fd5", "size": 2944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cmds.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": "test/cmds.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": "test/cmds.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": 49.0666666667, "max_line_length": 217, "alphanum_fraction": 0.7659646739, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7650126683867267}}
{"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  - \u03b8::Real - parameter\r\n\r\nConstructor\r\n\r\n    GumbelCopula(d, \u03b8)\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}{\u03b8}}}\r\n```\r\n\"\"\"\r\nstruct GumbelCopula{d,T} <: ArchimedeanCopula{d}\r\n    \u03b8::T\r\nend\r\nGumbelCopula(d,\u03b8) = \u03b8 >= 1 ? GumbelCopula{d,typeof(\u03b8)}(\u03b8) : @error \"Theta must be greater than 1.\"\r\n\u03d5(  C::GumbelCopula,       t) = exp(-t^(1/C.\u03b8))\r\n\u03d5\u207b\u00b9(C::GumbelCopula,       t) = (-log(t))^C.\u03b8\r\n\u03c4(C::GumbelCopula) = (C.\u03b8-1)/C.\u03b8\r\n\u03c4\u207b\u00b9(::Type{GumbelCopula},\u03c4) =1/(1-\u03c4) \r\n\r\nfunction radial_dist(C::GumbelCopula)\r\n    \u03b1 = 1/C.\u03b8\r\n    \u03b2 = 1\r\n    \u03b3 = cos(\u03c0/(2C.\u03b8))^C.\u03b8\r\n    \u03b4 = C.\u03b8 == 1 ? 1 : 0\r\n    AlphaStable([\u03b1,\u03b2,\u03b3,\u03b4]...) # for the type promotion...\r\nend\r\n\r\n\r\n# S(\u03b1, \u03b2, \u03b3 , \u03b4) denotes a stable distribution in\r\n# 1-parametrization [16, p. 8] with characteristic exponent \u03b1 \u2208 (0, 2], skewness \u03b2 \u2208 [\u22121, 1], scale\r\n# \u03b3 \u2208 [0,\u221e), and location \u03b4 \u2208 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": "module day5\n\nusing LinearAlgebra: dot\nreadInput() = readlines(joinpath(@__DIR__, \"input.txt\"))\n\nfunction decode(s, low, high)\n    for char in s\n        if char == 'F' || char == 'L'\n            high = (high + low) \u00f7 2\n        else\n            low = (high + low) \u00f7 2 + 1\n        end\n    end\n    @assert low == high\n    low\nend\n\nfunction decode(s)\n    row = decode(view(s, 1:7), 0, 127)\n    col = decode(view(s, 8:10), 0, 7)\n    row, col\nend\n\npart1(input) = mapreduce(s -> dot(decode(s), (8,1)), max, input)\n\nfunction part2(input)\n    ids = sort!(map(s -> dot(decode(s), (8,1)), input))\n    for i = 1:length(ids) - 1\n        ids[i] + 1 != ids[i+1] && return ids[i] + 1\n    end\nend\n\nend", "meta": {"hexsha": "e5eae5878cb1233ff1e848f3003896d6e60f1f9a", "size": 683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day5/day5.jl", "max_stars_repo_name": "gsoleilhac/aoc20.jl", "max_stars_repo_head_hexsha": "5fd0d7d98fbd68ebc966acc7155436b36a5ce304", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day5/day5.jl", "max_issues_repo_name": "gsoleilhac/aoc20.jl", "max_issues_repo_head_hexsha": "5fd0d7d98fbd68ebc966acc7155436b36a5ce304", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-12-02T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T01:03:31.000Z", "max_forks_repo_path": "src/day5/day5.jl", "max_forks_repo_name": "gsoleilhac/aoc20.jl", "max_forks_repo_head_hexsha": "5fd0d7d98fbd68ebc966acc7155436b36a5ce304", "max_forks_repo_licenses": ["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.696969697, "max_line_length": 64, "alphanum_fraction": 0.5314787701, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7650126611618034}}
{"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\u03b6  = 0.1\n\u03c9  = 1.; \u03c9\u00b2 = \u03c9^2\nP  = tf(\u03c9\u00b2,[1, 2\u03b6*\u03c9, \u03c9\u00b2])*tf(1,[1,1])\n\n\u03a9  = 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,\u03a9)[1]) # Freq. domain constraints\n    Tw    = vec(bode(T,\u03a9)[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!(\u03a9, [Sw Tw] , lab=[\"Sw\" \"Tw\"], subplot=2, xscale=:log10, yscale=:log10, show=false)\n    plot!([\u03a9[1],\u03a9[end]], [Ms,Ms], c = :black, l=:dash, subplot=2, show=false, lab=\"Ms\")\n    plot!([\u03a9[1],\u03a9[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\ud835\udfaa = 1\nu0 = 1/2\nf(t,u) = \ud835\udfaa*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                \u03bcp::DenseVector{T},\n                \u03bcn::DenseVector{T}) where T<:Real\n\n    w = cholesky(C) \\ (\u03bcp - \u03bcn)\n    ap = w \u22c5 \u03bcp\n    an = w \u22c5 \u03bcn\n    c = 2 / (ap - an)\n    LinearDiscriminant(rmul!(w, c), 1 - c * ap)\nend\n\nldacov(Cp::DenseMatrix{T},\n       Cn::DenseMatrix{T},\n       \u03bcp::DenseVector{T},\n       \u03bcn::DenseVector{T}) where T<:Real = ldacov(Cp + Cn, \u03bcp, \u03bcn)\n\n#### interface functions\n\nfunction fit(::Type{LinearDiscriminant}, Xp::DenseMatrix{T}, Xn::DenseMatrix{T};\n             covestimator::CovarianceEstimator = SimpleCovariance()) where T<:Real\n    \u03bcp = vec(mean(Xp, dims=2))\n    \u03bcn = vec(mean(Xn, dims=2))\n    Zp = Xp .- \u03bcp\n    Zn = Xn .- \u03bcn\n    Cp = calcscattermat(covestimator, Zp)\n    Cn = calcscattermat(covestimator, Zn)\n    ldacov(Cp, Cn, \u03bcp, \u03bcn)\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 \u2265 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    \u03bb::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 \u2265 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, \u03a3w, _ = svd(Hw, full=false)\n    keep = \u03a3w .> sqrt(eps(T)) * maximum(\u03a3w)\n    projw = Uw[:,keep]\n    pHb = projw' * Hb\n    pHw = projw' * Hw\n    \u03bb, G = lda_gsvd(pHb, pHw, cweights)\n    SubspaceLDA(projw, G, \u03bb, 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, \u03a3A, 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    \u03bb = diag(Gb * Gb')./diag(Gw * Gw')\n    \u03bb, 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    \u03b2 = 0.9,\n    \u03c3 = 2.0,\n    \u03b3 = 2.0,\n    \u03a0 = 0.5 * ones(2, 2),\n    G = [0.1, 0.2],\n    \u0398 = ones(Float64, 2),\n    transfers = false\n    )\n    function U(c, n)\n        if \u03c3 == 1.0\n            U = log(c)\n        else\n            U = (c.^(1.0 - \u03c3) - 1.0) / (1.0 - \u03c3)\n        end\n        return U - n.^(1 + \u03b3) / (1 + \u03b3)\n    end\n    # Derivatives of utility function\n    Uc(c,n) =  c.^(-\u03c3)\n    Ucc(c,n) = -\u03c3 * c.^(-\u03c3 - 1.0)\n    Un(c,n) = -n.^\u03b3\n    Unn(c,n) = -\u03b3 * n.^(\u03b3 - 1.0)\n    n_less_than_one = false\n    return Model(\u03b2, \u03a0, G, \u0398, 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, \" \u00b1 \", 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": "using Plots\nusing Dash, DashHtmlComponents, DashCoreComponents\n\nplotly()\n\napp = dash()\n\napp.layout = html_div() do\n    dcc_slider(\n        id=\"angle_selector\",\n        min=0,\n        max=2pi,\n        step=0.01,\n        value=pi/2,\n    ),\n    dcc_graph(id=\"plot\")\nend\n\ncallback!(\n        app, \n        Output(\"plot\", \"figure\"), \n        Input(\"angle_selector\", \"value\")) do angle\n    angles = range(0, angle, length=100)\n    x = cos.(angles)\n    y = sin.(angles)\n    fig = plot(\n        x, y,\n        size=(500, 500),\n        xlims=(-1.5, 1.5), ylims=(-1.5, 1.5),\n        legend=:none,\n        framestyle=:none)\n    Plots.plotlybase_syncplot(fig)\n    Plots.backend_object(fig)\nend\n\nrun_server(app)\n", "meta": {"hexsha": "65345c05813b19064506277320e21c4d056758a9", "size": 697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter03/dash_example/dash_example.jl", "max_stars_repo_name": "PacktPublishing/Interactive-Visualization-with-Julia", "max_stars_repo_head_hexsha": "6f9b2f0798784892b7d6965dd56fb2ef42d1012a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-04T16:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T16:28:23.000Z", "max_issues_repo_path": "Chapter03/dash_example/dash_example.jl", "max_issues_repo_name": "PacktPublishing/Interactive-Visualization-with-Julia", "max_issues_repo_head_hexsha": "6f9b2f0798784892b7d6965dd56fb2ef42d1012a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter03/dash_example/dash_example.jl", "max_forks_repo_name": "PacktPublishing/Interactive-Visualization-with-Julia", "max_forks_repo_head_hexsha": "6f9b2f0798784892b7d6965dd56fb2ef42d1012a", "max_forks_repo_licenses": ["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": 50, "alphanum_fraction": 0.5538020086, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7649137399628717}}
{"text": "using Test\nusing WavePropBase\nusing WavePropBase.Geometry\nusing WavePropBase.Interpolation\nusing StaticArrays\n\n@testset \"Generic nodes\" begin\n    cheb_nodes = (n) -> [cos((2*k+1)/2n * \u03c0) for k in 0:n-1]\n    # 1d\n    nodes = cheb_nodes(10)\n    f = x->cos(x)\n    vals = map(f,nodes)\n    p = TensorLagInterp(vals,nodes)\n    xtest = 0.1\n    @test f(xtest) \u2248 p(xtest)\n    # 2d\n    nx = 10\n    ny = 12\n    x   = [0.5+0.5cos((2k-1)*\u03c0/2nx) for k in 1:nx] # Chebyshev nodes\n    y   = [0.5+0.5cos((2k-1)*\u03c0/2ny) for k in 1:ny] # Chebyshev nodes\n    f   = (x) -> cos(x[1]*x[2])\n    vals = [f((x,y)) for x in x, y in y]\n    p   = TensorLagInterp(vals,(x,y))\n    xtest = (0.1,0.2)\n    @test p(xtest) \u2248 f(xtest)\n    # 3d\n    nx,ny,nz = 10, 12, 8\n    x   = [0.5+0.5cos((2k-1)*\u03c0/2nx) for k in 1:nx] # Chebyshev nodes\n    y   = [0.5+0.5cos((2k-1)*\u03c0/2ny) for k in 1:ny] # Chebyshev nodes\n    z   = [0.5+0.5cos((2k-1)*\u03c0/2nz) for k in 1:nz] # Chebyshev nodes\n    f   = (x) -> cos(x[1]*x[2])*x[3]\n    vals = [f((x,y,z)) for x in x, y in y, z in z]\n    p   = TensorLagInterp(vals,(x,y,z))\n    xtest = (0.1,0.2,-0.1)\n    @test p(xtest) \u2248 f(xtest)\nend\n\n@testset \"Cheb nodes\" begin\n    # 1,2,3 dimensions\n    for d in 1:3\n        p = ntuple(i->10+i,d)\n        vals   = zeros(p)\n        nodes1d   = map(p->cheb1nodes(p,-1,1),p)\n        weights1d = map(p->cheb1weights(p),p)\n        poly    = TensorLagInterp(vals,nodes1d,weights1d)\n        f     = x->cos(prod(x))\n        for I in CartesianIndices(poly)\n            vals[I] = f(interpolation_nodes(poly,I))\n        end\n        xtest = ntuple(i->0.1,d)\n        @test f(xtest) \u2248 poly(xtest)\n    end\n    # 1,2,3 dimensions\n    for d in 1:3\n        p = ntuple(i->10+i,d)\n        vals   = zeros(p)\n        nodes1d   = map(p->cheb2nodes(p,-1.3,1.5),p)\n        weights1d = map(p->cheb2weights(p),p)\n        poly    = TensorLagInterp(vals,nodes1d,weights1d)\n        f     = x->cos(prod(x))\n        for I in CartesianIndices(poly)\n            vals[I] = f(interpolation_nodes(poly,I))\n        end\n        xtest = ntuple(i->0.1,d)\n        @test f(xtest) \u2248 poly(xtest)\n        # todo add test when xtest is one of the interpolation points\n    end\nend\n", "meta": {"hexsha": "d74a22b2065fe7a767cb4d49f49bd64492e9e33e", "size": 2162, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Interpolation/tensorlaginterp_test.jl", "max_stars_repo_name": "WaveProp/WavePropBase", "max_stars_repo_head_hexsha": "75c47071ba3e3e2d95733b5f5c679c2203c43c48", "max_stars_repo_licenses": ["MIT"], "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/Interpolation/tensorlaginterp_test.jl", "max_issues_repo_name": "WaveProp/WavePropBase", "max_issues_repo_head_hexsha": "75c47071ba3e3e2d95733b5f5c679c2203c43c48", "max_issues_repo_licenses": ["MIT"], "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/Interpolation/tensorlaginterp_test.jl", "max_forks_repo_name": "WaveProp/WavePropBase", "max_forks_repo_head_hexsha": "75c47071ba3e3e2d95733b5f5c679c2203c43c48", "max_forks_repo_licenses": ["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": 69, "alphanum_fraction": 0.5393154487, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7649137309650762}}
{"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": "using NumericalMethodsforEngineers\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  f1(x::Float64, y::Vector{Float64}) = [y[2], 2.0*y[1]-3.0*y[2]+3.0*x^2]\n  steps = 4\n  h = 0.05\n\n  x = 0.0\n  y = [1.0, 0.0]\n\n  r = Array{Float64,2}[]\n  push!(r, euler(f1, x, y, steps, h))\n  push!(r, modified_euler(f1, x, y, steps, h))\n  push!(r, mid_point_euler(f1, x, y, steps, h))\n  push!(r, runga_kutta_4(f1, x, y, steps, h))\n\n  @test r[1][steps+1,:][:] == [0.2, 1.0272471874999998, 0.3254353125]\n  @test r[2][steps+1,:][:] == [0.2, 1.0338953695013426, 0.3110140747716065]\n  @test r[3][steps+1,:][:] == [0.2, 1.033871576010437, 0.3107074949932251]\n  @test r[4][steps+1,:][:] == [0.2, 1.033615605146455, 0.3112553545583527]\n\nend", "meta": {"hexsha": "c076214231d837d222cdf264e67376493a3206fe", "size": 711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch07_ivp_ex7.3.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_ivp_ex7.3.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_ivp_ex7.3.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": 29.625, "max_line_length": 75, "alphanum_fraction": 0.6047819972, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7649137244020673}}
{"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\u03c0))\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": "using NumericalMethodsforEngineers\nusing Test\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n\n  function f2(x::Float64, y::Vector{Float64})\n    [y[2], 3x^2+4y[1]]\n  end\n\n  (iters, nsteps, converged, res) = shootingmethod(f2, [0.0, 0.0, 1.0, 1.0], [0.0, 1.0], 5)\n\n  if !converged\n    println(\"No conversion achieved.\")\n  elseif iters > 50\n    println(\"Iter limit reached.\")\n  else\n    @test round.(res[:, 2], digits=4)' == [0.0  0.0813  0.1815  0.3313  0.5794  1.0]\n    #println()\n    #res |> display\n  end\n\nend", "meta": {"hexsha": "7d6dce4be3e389a12e7115634d2e355bdcbf1a22", "size": 508, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch07_bvp_ex7.4a.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_bvp_ex7.4a.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_bvp_ex7.4a.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.0869565217, "max_line_length": 91, "alphanum_fraction": 0.6200787402, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7648985245732486}}
{"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.\u03bb, 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": "@testset \"Opt common\" begin\n    function graph_test_setting(d = 0)\n        coeffs = [4.0 - 0.5im, 0.1im, 2.0 - 0.2im]\n        discr = collect(0:9.0) .+ d\n        n = length(discr)\n        A = hcat(ones(n), discr, discr .^ 2)\n        b = coeffs[1] .+ coeffs[2] * discr + coeffs[3] * discr .^ 2\n        return (A, b, coeffs, discr)\n    end\n\n    # Testing generic complex version\n    for linlsqr in [:backslash, :svd, :nrmeq]\n        (A, b, coeffs, discr) = graph_test_setting()\n        x = solve_linlsqr!(A, b, linlsqr, 0.0)\n        @test x \u2248 coeffs\n        @test !isreal(x)\n    end\n    (A, b, coeffs, discr) = graph_test_setting()\n    #testing droptolerance, high = garbage result\n    x = solve_linlsqr!(A, b, :svd, 1e-1)\n    @test norm(x - [4.0, 0.0, 2.0]) > 1\n\n    # Testing to force real solution\n    for linlsqr in [:real_backslash, :real_svd, :real_nrmeq]\n        (A, b, coeffs, discr) = graph_test_setting()\n        A = complex(A)\n        x = solve_linlsqr!(A, b, linlsqr, 0.0)\n        @test x \u2248 real(coeffs)\n        @test isreal(x)\n\n        (A, b, coeffs, discr) = graph_test_setting(0.1im)\n        A = complex(A)\n        x = solve_linlsqr!(A, b, linlsqr, 0.0)\n        @test isreal(x)\n        xx = real(A \\ b)\n        @test norm(A * x - b) < norm(A * xx - b)\n    end\n    (A, b, coeffs, discr) = graph_test_setting()\n    A = complex(A)\n    #testing droptolerance, high = garbage result\n    x = solve_linlsqr!(A, b, :real_svd, 1e-1)\n    @test norm(x - [4.0, 0.0, 2.0]) > 1\n\n    # Testing BigFloat arithmetic\n    (A, b, coeffs, discr) = graph_test_setting()\n    A = big.(A)\n    b = big.(b)\n    x = solve_linlsqr!(A, b, :svd, 0.0)\n    @test x \u2248 coeffs\n\n    (A, b, coeffs, discr) = graph_test_setting()\n    A = big.(A)\n    b = big.(b)\n    x = solve_linlsqr!(A, b, :real_svd, 0.0)\n    @test x \u2248 real(coeffs)\n    @test isreal(x)\nend\n", "meta": {"hexsha": "5f78fc37b55ce526123a66b1f04999a0df896dfa", "size": 1832, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/opt_common.jl", "max_stars_repo_name": "matrixfunctions/GraphMatFun.jl", "max_stars_repo_head_hexsha": "1fac14aa849e7f050ae5281bf6414b4356807199", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-07-09T07:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T22:57:51.000Z", "max_issues_repo_path": "test/opt_common.jl", "max_issues_repo_name": "matrixfunctions/GraphMatFun.jl", "max_issues_repo_head_hexsha": "1fac14aa849e7f050ae5281bf6414b4356807199", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-07-09T17:53:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T14:48:01.000Z", "max_forks_repo_path": "test/opt_common.jl", "max_forks_repo_name": "matrixfunctions/GraphMatFun.jl", "max_forks_repo_head_hexsha": "1fac14aa849e7f050ae5281bf6414b4356807199", "max_forks_repo_licenses": ["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.5862068966, "max_line_length": 67, "alphanum_fraction": 0.5480349345, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7648985206230134}}
{"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\u2013297.\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, \u03b2)\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* `\u03b2`:  incident or reflected angle\n\"\"\"\nfunction angleofrefraction(n1, n2, \u03b2)\n    asin(n1 / n2 * sin(\u03b2))\nend\n\n\"\"\"\n    fresnel_x(n1, n2, \u03b2)\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* `\u03b2`:  incident or reflected angle\n\nhttps://doi.org/10.1103/PhysRevB.59.1263\n\"\"\"\nfunction fresnel_x(n1, n2, \u03b2)\n    \u03b3 = angleofrefraction(n1, n2, \u03b2)\n    2n1 * cos(\u03b3) / (n1 * cos(\u03b3) + n2 * cos(\u03b2))\nend\n\n\"\"\"\n    fresnel_y(n1, n2, \u03b2)\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* `\u03b2`:  incident or reflected angle\n\nhttps://doi.org/10.1103/PhysRevB.59.1263\n\"\"\"\nfunction fresnel_y(n1, n2, \u03b2)\n    \u03b3 = angleofrefraction(n1, n2, \u03b2)\n    2n1 * cos(\u03b2) / (n1 * cos(\u03b2) + n2 * cos(\u03b3))\nend\n\n\"\"\"\n    fresnel_z(n1, n2, n\u2032, \u03b2)\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\u2032`: refractive index of the interface\n* `\u03b2`:  incident or reflected angle\n\nhttps://doi.org/10.1103/PhysRevB.59.1263\n\"\"\"\nfunction fresnel_z(n1, n2, n\u2032, \u03b2)\n    \u03b3 = angleofrefraction(n1, n2, \u03b2)\n    2n2 * cos(\u03b2) / (n1 * cos(\u03b3) + n2 * cos(\u03b2)) * (n1 / n\u2032)^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 \u2265 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 \u2265 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 \u2265 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    \u03b2::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        \u03b2 = inv(X' * X) * (X' * y)\n        new(\u03b2, 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.\u03b2 ./ 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.\u03b2, 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 = (\u03b2 = fit.\u03b2, 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 +  \u2211 Y(k) cos (\u03c0*(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 +  \u2211 Y(k) cos (\u03c0*(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) * \u03c0 * (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 \u2264 -5\n\n4 \u2260 44\n\n1.0 == 1\n\n1.000000000001 == 1\n\n3 < 4 && -15 > -10\n\n3 < 4 || -15 > -10\n\n!(-4 \u2265 4) && (1 > 2 || 1 < 2)\n\n1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5\n\nx = -2.3\n-3 \u2264 x \u2264 4\n\n# Examples of if-else statements\n\nfunction check_x(x)\n    if 0 \u2264 x \u2264 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(\u03c0)\n\ncheck_x(10.000001)\n\ncheck_x(2^63)        # trick question - causes Int64 overflow\n\nx = -3\nif x \u2265 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 \u2265 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\u0304, 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\u03bc = 15.0\n\n\n# potential\nimport FourierGPE.V\nV(x,y,t) = 0.5*(x^2 + y^2)\n\n# TF state\n\u03c8tf(x,y,\u03bc,g) = sqrt(\u03bc/g)*sqrt(max(1.0-V(x,y,0.0)/\u03bc,0.0)+im*0.0)\n\n# make initial state\nx,y = X\n\u03c8i = \u03c8tf.(x,y',\u03bc,g)\n\u03d5i = kspace(\u03c8i,sim)\n\n@pack_Sim! sim\n\n## evolve\nsol = runsim(sim)\n\n## pull out the ground state\n\u03d5g = sol[end]\n\u03c8g = xspace(\u03d5g,sim)\nshowpsi(x,y,\u03c8g)\n\nR(w) = sqrt(2*\u03bc/w^2)\nR(1)\nplot(x, abs2.(\u03c8tf.(x,0.,\u03bc,g)))\nplot!(x, abs2.(\u03c8g[:,128]))\n\n## free expansion\nV(x,y,t) = 0.0\n\n# sim parameters\n\u03b3 = 0.0\ntf = 10.0\nt = LinRange(ti,tf,Nt)\n\u03d5i = \u03d5g\n\nsime = Sim(L,N)\n@pack! sime = tf,t,\u03b3,\u03d5i\n\n## evolve\nsole = runsim(sime)\n\n\u03d5f = sole[end]\n\u03c8f = xspace(\u03d5f,sime)\nshowpsi(x,y,\u03c8f)\n\nanim = @animate for i=1:Nt-6\n    \u03c8 = xspace(sole[i],sime)\n    showpsi(x,y,\u03c8)\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": "using DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"colorscheme.jl\"))\n\nusing GLMakie, InteractiveDynamics, DynamicalSystems, OrdinaryDiffEq, LinearAlgebra\ndiffeq = (alg = Tsit5(), dtmax = 0.02, abstol = 1e-6, reltol = 1e-6)\n\n# Modified version of Rozenweig-MacArthur model for predator-prey\n# See https://arxiv.org/abs/2101.12107\nfunction hassan_alkhayuon(u, p, t) # From talk of Hassan Alkhayuon\n    r, c, \u03bc, \u03bd, \u03b1, \u03b2, \u03c7, \u03b4 = p\n    N, P = u\n    common = \u03b1*N*P/(\u03b2+N)\n    dN = r*N*(1 - (c/r)*N)*((N-\u03bc)/(N+\u03bd)) - common\n    dP = \u03c7*common - \u03b4*P\n    return SVector(dN, dP)\nend\n\nu0 = SVector(8.0, 0.01)\nr1, r2 = 1.7, 2.5\n# r, c, \u03bc, \u03bd, \u03b1, \u03b2, \u03c7, \u03b4 = p\np = [r1, 0.19, 0.03, 0.003, 800, 1.5, 0.004, 2.2]\nds = ContinuousDynamicalSystem(hassan_alkhayuon, u0, p)\n\n# I will re-use code from InteractiveDynamics.jl, so I'll be defining some necessary\n# quantities that may not make perfect sense without looking at the source code.\n# Nevertheless the source code is quite clear and is just used to initialize some\n# interactive observables and stuff.\ntail = 500                  # length of plotted trajectory (in units of `dt`)\nlims = ((0, 15), (0, 0.04)) # limits of state space\ncolor = to_color(\"#1e1528\") # trajectory color\n\nfigure = Figure(resolution = (1000, 800))\npinteg = DynamicalSystems.parallel_integrator(ds, [u0]; diffeq...)\nobs, finalpoints = InteractiveDynamics.init_trajectory_observables(1, pinteg, tail, SVector(1,2), identity)\n\nmain = figure[1,1] = InteractiveDynamics.init_main_trajectory_plot(\n    ds, figure, SVector(1,2), lims, pinteg, [color], obs, NamedTuple(), finalpoints, 1.0\n)\n\n# Plot the stability basin and attractor\nactive_color = to_color(\"#d7800a\")\npassive_color = RGBAf0(0.3, 0.4, 0.4, 0.5)\nr1_color = Observable(active_color)\nr2_color = Observable(passive_color)\n\nfunction plot_limitcycle_basin!(main, r, color)\n    set_parameter!(ds, 1, r)\n    # plot unstable manifold of \"e3\" fixed point\n    zz = SVector(p[3], 0.0)\n    J = ds.jacobian(zz, p, 0)\n    ev = eigvecs(J)\n    # system in reverse time: just negative `f`.\n    pprev = (u, p, t) -> -hassan_alkhayuon(u, p, t)\n    dsrev = ContinuousDynamicalSystem(pprev, SVector(1.0, 1.0), p)\n    e = ev[:, 1] # eigenvector correpsonding to positive eigenvalue\n    tr = trajectory(dsrev, 3.5, zz .+ 1e-3 .* e; dtmax = 0.01)\n    lines!(main, columns(tr)...; linewidth = 2.0, color = color, linestyle = :dash)\n    # plot limit cycle\n    tr = trajectory(ds, 20.0; dt = 0.01, Ttr = 100.0)\n    lines!(main, columns(tr)...; linewidth = 4.0, color = color)\n    return\nend\n\nplot_limitcycle_basin!(main, r2, r2_color)\nplot_limitcycle_basin!(main, r1, r1_color)\n\n# add controls for start/stop and toggle the r value below the figure\nfigure[2, 1] = controllayout = GridLayout(tellwidth = false)\nrunbutton = controllayout[1, 1] = Button(figure; label = \"run\")\nrbutton = controllayout[1, 2] = Button(figure; label = \"toggle r\")\nrun, rtoggle = runbutton.clicks, rbutton.clicks\n\n# Set up interactive part of the application: start/stop time evolution\nisrunning = Observable(false)\non(run) do clicks; isrunning[] = !isrunning[]; end\non(run) do clicks\n    @async while isrunning[]\n        DynamicalSystems.step!(pinteg)\n        ob = obs[1]\n        last_state = DynamicalSystems.get_state(pinteg, 1)\n        ob[] = push!(ob[], last_state) # push and trigger update with `=`\n        finalpoints[] = [x[][end] for x in obs]\n        sleep(0.00001) # use sleep to slow down animation\n        isopen(figure.scene) || break # crucial, ensures computations stop if closed window\n    end\nend\n\n# Set up interactive part of the application: toggle the r value\non(rtoggle) do clicks\n    r = (r1, r2)[mod(clicks, 2)+1]\n    set_parameter!(ds, 1, r)\n    u_modified!(pinteg, true)\n    x, y = r1_color[], r2_color[]\n    r1_color[], r2_color[] = y, x\nend\n\ndisplay(figure)\n", "meta": {"hexsha": "165bb1e73fa810c4d16ebe326558479cc352eee6", "size": 3822, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "animations/12/phase_dependent.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": "animations/12/phase_dependent.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": "animations/12/phase_dependent.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": 38.6060606061, "max_line_length": 107, "alphanum_fraction": 0.6773940345, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.76479964984036}}
{"text": "module MultivariateCalculusTest\n\nusing VarianceComponentModels, LinearAlgebra, Random, Test\n\nRandom.seed!(123)\n\n# test vech\n@testset \"vech\" begin\n  a = reshape(1:9, 3, 3)\n  vecha = vech(a)\n  @test vecha[1] == a[1, 1]\n  @test vecha[2] == a[2, 1]\n  @test vecha[3] == a[3, 1]\n  @test vecha[4] == a[2, 2]\n  @test vecha[5] == a[3, 2]\n  @test vecha[6] == a[3, 3]\n  a = 1.0\n  @test vech(a) == a\nend\n\n# test trilind\n@testset \"trilind\" begin\n  n = 3\n  A = randn(n, n)\n  @test norm(vech(A) - A[trilind(A)]) \u2248 0.0\n  @test norm([2, 3, 6] - trilind(A, -1)) \u2248 0.0\nend\n\n# test triuind\n@testset \"triuind\" begin\n  n = 2\n  idx = triuind(n, n)\n  @test length(idx) == binomial(n + 1, 2)\n  @test idx[1] == 1\n  @test idx[2] == 3\n  @test idx[3] == 4\n  idx = triuind(n)\n  @test length(idx) == binomial(n + 1, 2)\n  @test idx[1] == 1\n  @test idx[2] == 3\n  @test idx[3] == 4\n  idx = triuind(randn(n, n))\n  @test length(idx) == binomial(n + 1, 2)\n  @test idx[1] == 1\n  @test idx[2] == 3\n  @test idx[3] == 4\n  idx = triuind(randn(n, n), 1)\n  @test length(idx) == binomial(n, 2)\n  @test idx[1] == 3\nend\n\n# test commutation\n@testset \"commutation\" begin\n  m, n = 3, 2\n  A = randn(m, n)\n  @test norm(commutation(m, n) * vec(A) - vec(A')) \u2248 0.0\n  @test norm(commutation(A) * vec(A) - vec(A')) \u2248 0.0\n  @test norm(spcommutation(m, n) * vec(A) - vec(A')) \u2248 0.0\n  @test norm(spcommutation(A) * vec(A) - vec(A')) \u2248 0.0\n  B = randn(m, m)\n  @test norm(commutation(m) * vec(B) - vec(B')) \u2248 0.0\n  @test norm(commutation(eltype(B), m) * vec(B) - vec(B')) \u2248 0.0\n  @test norm(spcommutation(eltype(B), m) * vec(B) - vec(B')) \u2248 0.0\nend\n\n# test duplication\n@testset \"duplication\" begin\n  n = 3\n  A = randn(n, n)\n  A = 0.5(A + A') # symmetrize\n  @test norm(duplication(n) * vech(A) - vec(A)) \u2248 0.0\n  @test norm(duplication(A) * vech(A) - vec(A)) \u2248 0.0\n  @test norm(spduplication(n) * vech(A) - vec(A)) \u2248 0.0\n  @test norm(spduplication(A) * vech(A) - vec(A)) \u2248 0.0\nend\n\n# test chol_gradient\n@testset \"chol_gradient\" begin\n  n = 3\n  A = randn(n, n)\n  A = 0.5(A + A') # symmetrize\n  L = tril(randn(n, n))\n  # calculate gradient wrt L using chol_gradient\n  dL1 = chol_gradient(vec(A), L)\n  # alternative way to calculate gradient wrt L\n  dL2 = 2.0vech((A * L) + L' * A' - Matrix(Diagonal(A * L)))\n  @test norm(dL1 - dL2) \u2248 0.0\nend\n\n# test kron_gradient\n@testset \"kron_gradient\" begin\n  n, q, p, r = 2, 3, 4, 5\n  X = randn(n, q)\n  Y = randn(p, r)\n  M = kron(X, Y)\n  # calculate gradient wrt X using kron_gradient\n  dX1 = kron_gradient(vec(M), Y, n, q)\n  # alternative way to calculate gradient wrt X\n  dX2 = zero(X)\n  for j = 1:q\n    for i = 1:n\n      dX2[i, j] = dot(Y, M[(i-1)*p+1:i*p, (j-1)*r+1:j*r])\n    end\n  end\n  @test norm(dX1 - vec(dX2)) < 1e-8\nend\n\n# test duplication\n@testset \"kronaxpy\" begin\n  m, n, p, q = 3, 4, 5, 6\n  A = randn(m, n)\n  X = randn(p, q)\n  Y = zeros(m * p, n * q)\n  kronaxpy!(A, X, Y)\n  @test norm(Y - kron(A, X)) \u2248 0.0\nend\n\n# test bump_diagonal\n@testset \"bump_diag\" begin\n  A = randn(3, 3)\n  B = copy(A)\n  bump_diagonal!(B, 1e-3)\n  @test B[1, 1] - A[1, 1] \u2248 1e-3\n  @test B[2, 2] - A[2, 2] \u2248 1e-3\n  @test B[3, 3] - A[3, 3] \u2248 1e-3\nend\n\n# test clamp_diagonal\n@testset \"clamp_diag\" begin\n  n = 3\n  A = randn(n, n)\n  B = copy(A)\n  clamp_diagonal!(B, 0.0, 1.0)\n  @test all(0.0 .\u2264 diag(B) .\u2264 1.0)\nend\n\n\nend # module MultivariateCalculusTest\n", "meta": {"hexsha": "fc35abd225a0e57460398751da1d5670a0d52b8b", "size": 3308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/multivariate_calculus_test.jl", "max_stars_repo_name": "Hua-Zhou/VarianceComponentModels", "max_stars_repo_head_hexsha": "33115fd2bc341998767c4013c0bd160b47d2a635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-07-08T03:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-17T22:14:55.000Z", "max_issues_repo_path": "test/multivariate_calculus_test.jl", "max_issues_repo_name": "Hua-Zhou/VarianceComponentModels", "max_issues_repo_head_hexsha": "33115fd2bc341998767c4013c0bd160b47d2a635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2016-09-01T23:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T00:11:57.000Z", "max_forks_repo_path": "test/multivariate_calculus_test.jl", "max_forks_repo_name": "Hua-Zhou/VarianceComponentModels", "max_forks_repo_head_hexsha": "33115fd2bc341998767c4013c0bd160b47d2a635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-03-24T23:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-24T12:46:08.000Z", "avg_line_length": 23.7985611511, "max_line_length": 66, "alphanum_fraction": 0.5722490931, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7647940314815767}}
{"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) -> \u03a9::Int64, all_pos, all_generating_matrices\n\nMatrix- and Notation-Generator: Calculate all generating matrices (including PO notations) and the number of generating matrices \u03a9.\n\"\"\"\nfunction construct_generators(n::Int64, k::Int64, prnt = false)\n    # calculate number of possible generating matrices\n    \u03a9 = binomial(n,k)\n    println(\"There are \u03a9 = ($n choose $k) = $\u03a9  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{\u2124\u2082, 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\u2194 AI:\\t \", po2ai(all_pos[1],n), \n            \"\\tA\u00b2 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:\u03a9\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\u2194 AI:\\t \", po2ai(all_pos[end],n), \n                \"\\tA\u00b2 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 \u03a9, 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": "using Graphs\nusing StatsBase: Weights, sample!\n\n\nfunction create_random_topology(n::Int, m::Int = ceil(Int, n / 2) + 1)\n    @assert m > n / 2\n    g = SimpleGraph(n)\n    while ne(g) < m\n        v1, v2 = rand(vertices(g), 2)\n        add_edge!(g, v1, v2)\n    end\n    return g\nend\n\n\nfunction create_small_world_topology(n, k::Int = 2, p::Float64 = 0.05)\n    @assert 1 \u2264 k \u2264 n\n    @assert 0 \u2264 p \u2264 1\n    g = SimpleGraph(n)\n    for v1 in vertices(g)\n        for i = 1:k\n            v2 = mod1(v1 + i, length(vertices(g)))\n            add_edge!(g, v1, v2)\n        end\n    end\n    if p > 0\n        for e in edges(g)\n            if rand() \u2264 p\n                v1 = src(e)\n                rem_edge!(g, e)\n                v2 = rand(vertices(g))\n                add_edge!(g, v1, v2)\n            end\n        end\n    end\n    return g\nend\n\nfunction create_scale_free_topology(n::Int, n0::Int = 3, n1::Int = 2)\n    @assert 2 \u2264 n1 \u2264 n0 \u2264 n\n    g = create_partial_ring(n, n0)\n    _add_scale_free_topopolgy!(g, n0, n1)\n    return g\n\nend\n\nfunction create_scale_free_topology(base_graph::SimpleGraph, n0::Int = 3, n1::Int = 2)\n    @assert 2 \u2264 n1 \u2264 n0 \u2264 length(vertices(base_graph))\n    g = deepcopy(base_graph)\n    _add_scale_free_topopolgy!(g, n0, n1)\n    return g\nend\n\n\n\nfunction create_partial_ring(total_nodes::Int, ring_nodes::Int)\n    g = SimpleGraph(total_nodes)\n    for v1 = 1:ring_nodes\n        v2 = mod1(v1 + 1, length(vertices(g)))\n        add_edge!(g, v1, v2)\n    end\n    return g\nend\n\n\n\nfunction _add_scale_free_topopolgy!(g::SimpleGraph, n0::Int, n1::Int)\n    n = length(vertices(g))\n    neighbors = Vector{Int64}(undef, n1)\n    for v1 = n0+1:n\n        wv = Weights([degree(g, v) for v in vertices(g)])\n        sample!(vertices(g), wv, neighbors, replace = false)\n        for v2 in neighbors\n            add_edge!(g, v1, v2)\n        end\n    end\n    return g\nend\n\nis_tree(g::AbstractGraph) = is_connected(g) && ne(g) === nv(g) - 1\n\n\nfunction flip_edge!(g::AbstractGraph, e::Edge)\n    has_edge(g, e) || throw(error(\"Edge e is not in g!\"))\n    rem_edge!(g, e)\n    add_edge!(g, reverse(e))\n    return g\n\nend", "meta": {"hexsha": "60bd044bda756a154aafbaef1229ea91aa5e8d3b", "size": 2093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/networks/Util.jl", "max_stars_repo_name": "tomtuamnuq/dist-algorithms", "max_stars_repo_head_hexsha": "c7c273179a5aaae0d52c1651a469e2988e59ee93", "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/networks/Util.jl", "max_issues_repo_name": "tomtuamnuq/dist-algorithms", "max_issues_repo_head_hexsha": "c7c273179a5aaae0d52c1651a469e2988e59ee93", "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/networks/Util.jl", "max_forks_repo_name": "tomtuamnuq/dist-algorithms", "max_forks_repo_head_hexsha": "c7c273179a5aaae0d52c1651a469e2988e59ee93", "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.5168539326, "max_line_length": 86, "alphanum_fraction": 0.5699952222, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7647940080122544}}
{"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,\u03b3,\u03bb)\n\nDo Lasso (set \u03b3>0,\u03bb=0), ridge (set \u03b3=0,\u03bb>0) or elastic net regression (set \u03b3>0,\u03bb>0).\n\n\n## Input\n- `Y::Vector`:     T-vector with the response (dependent) variable\n- `Y::VecOrMat`:   TxK matrix of covariates (regressors)\n- `\u03b3::Number`:     penalty on sum(abs.(b))\n- `\u03bb::Number`:     penalty on sum(b.^2)\n\n\"\"\"\nfunction LassoEN(Y,X,\u03b3,\u03bb=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+\u03b3*L3+\u03bb*L4)      #u'u + \u03b3*sum(|b|) + \u03bbsum(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 \u03b3.\n\n\nK = size(X,2)\n\u03b3 = 100\n\n(b,b_ls) = LassoEN(Y,X,\u03b3)\n\nprintln(\"OLS and Lasso coeffs (with \u03b3=$\u03b3)\")\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\u03b3 = 101\n\u03b3M = range(0; stop=600, length=n\u03b3)             #different \u03b3 values\n\nbLasso   = fill(NaN,size(X,2),n\u03b3)       #results for \u03b3M[i] are in bLasso[:,i]\nfor i = 1:n\u03b3\n    bLasso[:,i], = LassoEN(Y,X,\u03b3M[i])\nend\n\n#-\n\nplot(log.(\u03b3M),bLasso',\n     title = \"Lasso regression coefficients\",\n     xlabel = \"log(\u03b3)\",\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 + \u03bb*I)*X'Y`.\n\nn\u03bb = 101\n\u03bbM = range(0; stop=3000, length=n\u03bb)\n\nbRidge  = fill(NaN,size(X,2),n\u03bb)\nfor i = 1:n\u03bb\n    bRidge[:,i], = LassoEN(Y,X,0,\u03bbM[i])\nend\n\n#-\n\nplot(log.(\u03bbM),bRidge',\n     title = \"Ridge regression coefficients\",\n     xlabel = \"log(\u03bb)\",\n     label = permutedims(xNames),\n     size = (600,400))\n\n# # Elastic Net Regression\n\n\u03bb = 200\nprintln(\"redo the Lasso regression, but with \u03bb=$\u03bb: an elastic net regression\")\n\nbEN   = fill(NaN,size(X,2),n\u03b3)\nfor i = 1:n\u03b3\n    bEN[:,i], = LassoEN(Y,X,\u03b3M[i],\u03bb)\nend\n\n#-\n\nplot(log.(\u03b3M),bEN',\n     title = \"Elastic Net regression coefficients\",\n     xlabel = \"log(\u03b3)\",\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, \u222b(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], \u2202(x[i], t) == v[i])\n@constraint(m, [i = 1:2], \u2202(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) \u2266 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 Test, FinancialMonteCarlo,ArrayFire;\n@show \"HestonModel\"\n\nS0=100.0;\nK=100.0;\nr=0.02;\nT=1.0;\nd=0.01;\nD=90.0;\n\nNsim=1000;\nNstep=30;\nsigma=0.2; \nsigma_zero=0.2;\nkappa=0.01;\ntheta=0.03;\nlambda=0.01;\nrho=0.0;\nmc=MonteCarloConfiguration(Nsim,Nstep,FinancialMonteCarlo.AFMode());\nmc1=MonteCarloConfiguration(Nsim,Nstep,FinancialMonteCarlo.AntitheticMC(),FinancialMonteCarlo.AFMode());\ntoll=0.8;\n\nrfCurve=ZeroRate(r);\n\nFwdData=Forward(T)\nEUData=EuropeanOption(T,K)\nAMData=AmericanOption(T,K)\nBarrierData=BarrierOptionDownOut(T,K,D)\nAsianData1=AsianFloatingStrikeOption(T)\nAsianData2=AsianFixedStrikeOption(T,K)\nModel=HestonProcess(sigma,sigma_zero,lambda,kappa,rho,theta,Underlying(S0,d));\n\n@show FwdPrice=pricer(Model,rfCurve,mc,FwdData);\n@show EuPrice=pricer(Model,rfCurve,mc,EUData);\n@show AmPrice=pricer(Model,rfCurve,mc,AMData);\n@show BarrierPrice=pricer(Model,rfCurve,mc,BarrierData);\n@show AsianPrice1=pricer(Model,rfCurve,mc,AsianData1);\n@show AsianPrice2=pricer(Model,rfCurve,mc,AsianData2);\n\n@test abs(FwdPrice-98.72567723404445)<toll\n@test abs(EuPrice-17.62536090688433)<toll\n@test abs(BarrierPrice-11.38748933756886)<toll\n@test abs(AsianPrice1-9.762160560168732)<toll\n\n@show FwdPrice=pricer(Model,rfCurve,mc,FwdData);\n@show EuPrice=pricer(Model,rfCurve,mc,EUData);\n@show AmPrice=pricer(Model,rfCurve,mc,AMData);\n@show BarrierPrice=pricer(Model,rfCurve,mc,BarrierData);\n@show AsianPrice1=pricer(Model,rfCurve,mc,AsianData1);\n@show AsianPrice2=pricer(Model,rfCurve,mc,AsianData2);\ntollanti=0.8\n@test abs(FwdPrice-98.72567723404445)<tollanti\n@test abs(EuPrice-17.62536090688433)<tollanti\n@test abs(BarrierPrice-11.38748933756886)<tollanti\n@test abs(AsianPrice1-9.762160560168732)<tollanti\n\n\n", "meta": {"hexsha": "a7c9902980280c63eb7792f1a2ad049e31de124e", "size": 1698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/af/test_heston_af.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": "test/af/test_heston_af.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": "test/af/test_heston_af.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.275862069, "max_line_length": 104, "alphanum_fraction": 0.800942285, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7647891797103298}}
{"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    \u03b1:    parameter 1 of Beta dist\n    \u03b2:    parameter 2 of Beta dist\n    prob: probabilty of HPD interval\n    \n    Outputs\n    -------\n    HPD interval\n\n\"\"\"\nfunction beta_hpdi(ci0, \u03b1, \u03b2, 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 \u03c0\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_\u03c0 = mean(d_posterior)\n    # median\n    median_\u03c0 = median(d_posterior)\n    # mode\n    mode_\u03c0 = mode(d_posterior)\n    # Analytic Mode for Beta Dist\n    # (a - 1.0) / (a + b - 2.0)\n    # std\n    sd_\u03c0 = std(d_posterior)\n    # credible interval\n    # ci upper boud\n    ci_\u03c0_upper = quantile(d_posterior, prob - (1-prob)/2)\n    # ci lower boud\n    ci_\u03c0_lower = quantile(d_posterior, (1-prob)/2)\n    ci_\u03c0 = [ci_\u03c0_lower, ci_\u03c0_upper]\n\n    posterior_stats = reshape([mean_\u03c0, median_\u03c0, mode_\u03c0, sd_\u03c0, ci_\u03c0], 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  - \u03b8::Real - parameter\r\n\r\nConstructor\r\n\r\n    AMHCopula(d, \u03b8)\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    \u03b8::T\r\nend\r\nAMHCopula(d,\u03b8) = (0 <= \u03b8 <= 1) ? AMHCopula{d,typeof(\u03b8)}(\u03b8) : @error \"Theta must be between 0 and 1\"\r\n\u03d5(  C::AMHCopula,t) = (1-C.\u03b8)/(exp(t)-C.\u03b8)\r\n\u03d5\u207b\u00b9(  C::AMHCopula,t) = log(C.\u03b8 + (1-C.\u03b8)/t)\r\n\r\n\u03c4(C::AMHCopula) = 1 - 2(C.\u03b8+(1-C.\u03b8)^2*log(1-C.\u03b8))/(3C.\u03b8^2) # no closed form inverse...\r\nfunction \u03c4\u207b\u00b9(::Type{AMHCopula},\u03c4)\r\n    if \u03c4 == zero(\u03c4)\r\n        return \u03c4\r\n    end\r\n    if \u03c4 > 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(\u03b8 -> 1 - 2(\u03b8+(1-\u03b8)^2*log(1-\u03b8))/(3\u03b8^2) - \u03c4,0.5)\r\nend\r\n\r\n\r\nradial_dist(C::AMHCopula) = 1 + Distributions.Geometric(1-C.\u03b8)\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": "\"\"\"\n    CrossEntropy(NeuralNetwork)\n\nCross entropy loss function.\n\n    Usage:\n```julia-repl\nCrossEntropy(NeuralNetwork)\n```\nArguments:\n- `NeuralNetwork` : The NeuralNetwork structure.\n\"\"\"\nfunction CrossEntropy(NeuralNetwork)\n    \u03a3Score = 0.0\n\n\tfor i in 1:size(NeuralNetwork.y, 1)\n        \u03a3Score += NeuralNetwork.y[i] * log(1e-15 + NeuralNetwork.output[i])\n    end\n\n    Mean\u03a3Score = 1.0 / size(NeuralNetwork.y, 1) * \u03a3Score\n    loss = -Mean\u03a3Score\n\treturn loss\nend", "meta": {"hexsha": "dcba7129e57ec7290db9fef8ae50d86c9e794f39", "size": 461, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LossFunctions/CrossEntropy.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/CrossEntropy.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/CrossEntropy.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": 20.0434782609, "max_line_length": 75, "alphanum_fraction": 0.6876355748, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7647891691428257}}
{"text": "# the idea of this is to find a basis of the \n# kernel of matrix. This is done using the eigenvalues. \nfunction kernel_basis(A, tol = 1e-5)\n\tB = Array{Float64,1}[]\n\tkernel = nullspace(A);\n\tkernel_size = size(kernel)[2]\n\tfor n = 1:kernel_size\n\t\tpush!(B,kernel[:,n]);\n\tend\n\treturn B\nend\n", "meta": {"hexsha": "f27331dab32b8d215aac0ad2fb381ef5ad403e6e", "size": 285, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_algbra_helper.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/linear_algbra_helper.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/linear_algbra_helper.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": 23.75, "max_line_length": 56, "alphanum_fraction": 0.6842105263, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7647891677521294}}
{"text": "(@__DIR__) \u2209 LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\nmodule SequencesDemo\n\nusing IntegerSequences\n\nprintln(\"\\nProduct 1*2*3\")\np = \u220f([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 \u221an.\")\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\u0394(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 \u2191(20, 80).\") # (a.k.a. Pochhammer)\nrf = 20 \u2191 80\nprintln(rf)\n\nprintln(\"\\nThe falling factorial \u2193(80, 60).\")\nff = 80 \u2193 60\nprintln(ff)\n\nprintln(\"\\nThe number of divisors of n = 25920.\")\nt = \u03c4(25920)\nprintln(t)\n\nprintln(\"\\nThe sum of divisors of n = 25920.\")\ns = \u03c3(25920)\nprintln(s)\n\nprintln(\"\\nNumber of acyclic orientations of the\nTur\u00e1n 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 \u22a5 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(\u22a5(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(\u22a5(m, n)), \" \" ) end\n    println()\nend\n\n# Generating the OLMS logo.\n# \u234a(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 \u234a(n, k)]\n    L = [Int(k \u2208 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_\u2202F\u2202x(func_F,u,\u0394x,dim)\n    U\u2093\u1d38, U\u2093\u1d3f = GeneralFluxLimiter(u,\u0394x)\n    n = size(u,dim)\n    \u2202f\u2202x = copy(u)\n\n    for i=1:n\n        A\u207a , A\u207b = LRJacobian(func_F,u[:,i])\n        \u2202f\u2202x[:,i] = (A\u207b * U\u2093\u1d38[:,i] .+ A\u207a * U\u2093\u1d3f[:,i])\n    end\n    return \u2202f\u2202x\nend\n\nfunction HPDE_\u2202u\u2202t(prob::HPDEProblem,u)\n\n    \u2202F\u2202x = HPDE_\u2202F\u2202x(prob.func_F,u,prob.Grid.\u0394x,2)\n\n    # future extentions\n    #\u2202F\u2202x = HPDE_\u2202F\u2202x(prob.func_F,u,prob.Grid.\u0394x,1)\n    #\u2202G\u2202y = HPDE_\u2202F\u2202x(prob.func_G,u,prob.Grid.\u0394y,2)\n    #\u2202H\u2202z = HPDE_\u2202F\u2202x(prob.func_H,u,prob.Grid.\u0394z,3)\n    #S = prob.func_S(u)\n\n    \u2202G\u2202y = 0\n    \u2202H\u2202z = 0\n    #S = func_S(u)\n    S = 0\n\n    \u2202u\u2202t = S .- (\u2202F\u2202x .+ \u2202G\u2202y .+ \u2202H\u2202z)\n\n    return \u2202u\u2202t\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    \u039b = diagm(eigvals(A))\n    \u039b\u207a = 0.5 .* (\u039b .+ abs.(\u039b))\n    \u039b\u207b = 0.5 .* (\u039b .- abs.(\u039b))\n    P = eigvecs(A)\n    P\u207b\u00b9 = inv(P)\n    A\u207a = P * \u039b\u207a * P\u207b\u00b9\n    A\u207b = P * \u039b\u207b * P\u207b\u00b9\n    return A\u207a, A\u207b\nend\n\nfunction GeneralFluxLimiter(u,\u0394x)\n    \u03f5 = 1.0e-8\n    \u2202u\u2202x(U\u207a,U\u207b) = (U\u207a .- U\u207b) ./ \u0394x\n    func_\u03a8(r) = 0\n    #func_\u03a8(r) = \u03ba_Scheme_new(r,1)\n    func_\u03a8(r) = SuperBee(r)\n    #func_\u03a8(r) = Koren(r)\n    #func_\u03a8(r) = 0\n    func_r(U\u2093\u2081,U\u2093\u2082) = (U\u2093\u2081 .+ \u03f5) ./ (U\u2093\u2082 .+ \u03f5)\n    func_U(\u0394x\u1d62,r,u\u2093) = (\u0394x\u1d62 / 2) .* func_\u03a8(r) .* (u\u2093 .+ \u03f5)\n    U\u1d62\u208b\u2082 = [u[:,1] u[:,1] u[:,1:end-2]]\n    U\u1d62\u208b\u2081 = [u[:,1] u[:,1:end-1]]\n    U\u1d62   = copy(u)\n    U\u1d62\u208a\u2081 = [u[:,2:end] u[:,end]]\n    U\u1d62\u208a\u2082 = [u[:,3:end] u[:,end] u[:,end]]\n\n    U\u2093i\u208a\u00be = \u2202u\u2202x(U\u1d62\u208a\u2082,U\u1d62\u208a\u2081)\n    U\u2093i\u208a\u00bd = \u2202u\u2202x(U\u1d62\u208a\u2081,U\u1d62)\n    U\u2093i\u208b\u00bd = \u2202u\u2202x(U\u1d62,U\u1d62\u208b\u2081)\n    U\u2093i\u208b\u00be = \u2202u\u2202x(U\u1d62\u208b\u2081,U\u1d62\u208b\u2082)\n\n    U\u1d38i\u208a\u00bd = U\u1d62\u208a\u2081 .- func_U(\u0394x,func_r(U\u2093i\u208a\u00bd,U\u2093i\u208a\u00be),U\u2093i\u208a\u00be)\n    U\u1d38i\u208b\u00bd = U\u1d62   .- func_U(\u0394x,func_r(U\u2093i\u208b\u00bd,U\u2093i\u208a\u00bd),U\u2093i\u208a\u00bd)\n    U\u1d3fi\u208a\u00bd = U\u1d62   .+ func_U(\u0394x,func_r(U\u2093i\u208a\u00bd,U\u2093i\u208b\u00bd),U\u2093i\u208b\u00bd)\n    U\u1d3fi\u208b\u00bd = U\u1d62\u208b\u2081 .+ func_U(\u0394x,func_r(U\u2093i\u208b\u00bd,U\u2093i\u208b\u00be),U\u2093i\u208b\u00be)\n\n    U\u2093\u1d38 = (U\u1d38i\u208a\u00bd .- U\u1d38i\u208b\u00bd) ./ \u0394x\n    U\u2093\u1d3f = (U\u1d3fi\u208a\u00bd .- U\u1d3fi\u208b\u00bd) ./ \u0394x\n    #return U\u1d3fi\u208a\u00bd, U\u1d3fi\u208b\u00bd, U\u1d38i\u208a\u00bd , U\u1d38i\u208b\u00bd\n    #return U\u2093i\u208a\u00be, U\u2093i\u208a\u00bd, U\u2093i\u208b\u00bd, U\u2093i\u208b\u00be\n    return U\u2093\u1d38, U\u2093\u1d3f\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 \u03ba_Scheme_new(r,-1)\nend\n\nfunction SCD(r)\n    return \u03ba_Scheme_new(r,1)\nend\n\nfunction UpWind_Q(r)\n    return \u03ba_Scheme_new(r,0.5)\nend\n\nfunction UpWind_C(r)\n    return \u03ba_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": "using NumericalMethodsforEngineers\nusing Test\n\na = [10. 1. -5;-20. 3. 20.;5. 3. 5.]\nb = [1., 2., 6.]\n\nc = a\\b\nf = lu(a);\n(lower, upper) = lufac(a)\nsubfor!(lower, b)\nsubbac!(upper, b)\n\n@test round.(b, digits=10) == round.(c, digits=10)", "meta": {"hexsha": "650063b37a36bd3d13bfb41e9e23cb0df395ad07", "size": 234, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch02_gaussian.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/ch02_gaussian.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/ch02_gaussian.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.0, "max_line_length": 50, "alphanum_fraction": 0.5897435897, "num_tokens": 102, "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\u2080::REALMAT, kernel_struct::Kernel)\n    @assert size(x, 2) == size(x\u2080, 2) \"The number of columns of x and x\u2080 do not match.\"\n    # Dispatch to kernel\n    K = kernel_calculation(x, x\u2080, 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\u2080, k::Linear)\n    K = [dot(x[i1, :], x[i2, :]) for i1 in 1:size(x, 1), i2 in 1:size(x\u2080, 1)]\n    return K * k.\u03c3\nend\n\n# Radial Basis Function (Squared Exponential)\nfunction kernel_calculation(x, x\u2080, k::RBF)\n    K = zeros(size(x, 1), size(x\u2080, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x\u2080, 1)\n            K[i1, i2] = k.\u03c3 * exp(-sum((x[i1, :] .- x\u2080[i2, :]).^2)/(2*k.l^2))\n        end\n    end\n    return K\nend\n\n# Rational Quadratic\nfunction kernel_calculation(x, x\u2080, k::RationalQuadratic)\n    K = zeros(size(x, 1), size(x\u2080, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x\u2080, 1)\n            K[i1, i2] = k.\u03c3 * (1.0 + sum((x[i1, :] .- x\u2080[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\u2080, k::Periodic)\n    K = zeros(size(x, 1), size(x\u2080, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x\u2080, 1)\n            K[i1, i2] = k.\u03c3 * exp(-2 * sin(sum(abs.(x[i1, :] .- x\u2080[i2, :])))^2/k.l^2)\n        end\n    end\n    return K\nend\n\n# Locally Periodic\nfunction kernel_calculation(x, x\u2080, k::LocallyPeriodic)\n    K = zeros(size(x, 1), size(x\u2080, 1))\n    for i1 in 1:size(x, 1)\n        for i2 in 1:size(x\u2080, 1)\n            K[i1, i2] = k.\u03c3 * exp(-2 * sin(sum(abs.(x[i1, :] .- x\u2080[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": "using AbstractAlgebra\nusing Nemo\nusing SymbolicIntegration\nSI = SymbolicIntegration\n\nusing Test\n\n@testset \"Complex fields\" begin   \n    QQx, x = PolynomialRing(Nemo.QQ, :x)\n    k = FractionField(QQx)\n    D0 = BasicDerivation(k)\n    kI, I, D = SI.Complexify(k, D0)\n    kI1, x1, I1, D1 = SI.switch_t_i(kI, D)\n\n    f = (x^2+3x-1)//(x-7)*I + x^2//(1+x^3)\n    f1 = SI.transform(f, x1, I1)\n    f2 = SI.backtransform(f1, x, I)\n    @test f2==f\n\n    fd = D(f)\n    fd1 = SI.transform(fd, x1, I1)\n    f1d = D1(f1)\n    @test fd1==f1d\nend\n\n@testset \"ParametricLogarithmicDerivative complexified\" begin\n    QQx, x = PolynomialRing(Nemo.QQ, :x)\n    k = FractionField(QQx) \n    D0 = SI.BasicDerivation(k)\n    kI, I, D0I = SI.Complexify(k, D0)\n\n    kIt, t = PolynomialRing(kI, :t)\n\n    H = 1//x+0*t\n    D = SI.ExtensionDerivation(kIt, D0I, H)    \n\n    w = -I*1//(x*t^2)\n    u = x^5*t+3*x*I\n    n = 2\n    m = 6\n\n    f = (D(u)//u+m*w)//n    \n    n1, m1, u1, \u03c1 = SI.ParametricLogarithmicDerivative(f, w, D)\n\n    @test n1*f == D(u1)//u1 + m1*w   \nend\n", "meta": {"hexsha": "736a11c17a0d1946885343ae83428c0b54ad16d8", "size": 1030, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_complex_fields.jl", "max_stars_repo_name": "HaraldHofstaetter/SymbolicIntegration.jl", "max_stars_repo_head_hexsha": "bd1c73914d32651f136a9cfdb5ecaf20e7b1c692", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2022-02-01T10:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T10:25:06.000Z", "max_issues_repo_path": "test/test_complex_fields.jl", "max_issues_repo_name": "HaraldHofstaetter/SymbolicIntegration.jl", "max_issues_repo_head_hexsha": "bd1c73914d32651f136a9cfdb5ecaf20e7b1c692", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-01T15:49:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T16:45:09.000Z", "max_forks_repo_path": "test/test_complex_fields.jl", "max_forks_repo_name": "HaraldHofstaetter/SymbolicIntegration.jl", "max_forks_repo_head_hexsha": "bd1c73914d32651f136a9cfdb5ecaf20e7b1c692", "max_forks_repo_licenses": ["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.914893617, "max_line_length": 63, "alphanum_fraction": 0.5757281553, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384733, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7647372352976335}}
{"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": "correct = ( pi/4 + atan(3.0) ) / 2\nfor endpt in [neither, both, left, right]\n    x, w = legendre(40, endpt)\n    Q = sum(w .* 1 ./ ( 1 .+ (2x .- 1).^2))\n    @test Q \u2248 correct\nend\n", "meta": {"hexsha": "48f1762a5ba6147f30ec3a2273e01e879bf848e4", "size": 178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_legendre.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/test_legendre.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/test_legendre.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": 25.4285714286, "max_line_length": 43, "alphanum_fraction": 0.5056179775, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7647154339743026}}
{"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(;\u03bb, \u03b3, step_sizes)\n\nA step schedule decays exponentially by `\u03b3` every step\nin `step_sizes`.\nThe output conforms to\n```text\n\u03bb * \u03b3^{i - 1}\n```\nwhere `sum(step_sizes[1:(i - 1)]) < t <= sum(step_sizes[1:i])`\n\n# Arguments:\n- `start`/`\u03bb`: the starting value\n- `decay`/`\u03b3`: 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(\u03bb, \u03b3, step_size::Integer) = Step(\u03bb, \u03b3, [step_size])\nStep(;\u03bb, \u03b3, step_sizes) = Step(\u03bb, \u03b3, 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(;\u03bb, \u03b3)\n\nA exponential decay schedule at rate `\u03b3`.\nThe output conforms to\n```text\n\u03bb * \u03b3^{t - 1}\n```\n\n# Arguments:\n- `start`/`\u03bb`: the base value\n- `decay`/`\u03b3`: the decay rate\n\"\"\"\nstruct Exp{T}\n    start::T\n    decay::T\nend\nExp(;\u03bb, \u03b3) = Exp(\u03bb, \u03b3)\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(;\u03bb, p, max_iter)\n\nA polynomial schedule decays with degree `p`.\nThe output conforms to\n```text\n\u03bb / (1 - (t - 1) / max_iter)^p\n```\n\n# Arguments\n- `start`/`\u03bb`: 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(;\u03bb, p, max_iter) = Poly(\u03bb, 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(;\u03bb, \u03b3, p)\n\nA decay schedule that inversely decays with rate `\u03b3`.\nThe output conforms to\n```text\n\u03bb / (1 + (t - 1) * \u03b3)^p\n```\n\n# Arguments\n- `start`/`\u03bb`: the base value\n- `decay`/`\u03b3`: 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(;\u03bb, \u03b3, p) = Inv(\u03bb, \u03b3, 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": "using Test, DiscreteExteriorCalculus\nconst DEC = DiscreteExteriorCalculus\n\n@testset \"parametrize_subspace\" begin\n    M, v = [[0,1] [-1,1] [0,1]], [-.5,1]\n    a, b = DEC.parametrize_subspace(M, v)\n    @test M * a \u2248 v\n    @test M * (a + b * [1]) \u2248 v\n    @test M * (a + b * [-2]) \u2248 v\n\n    M, v = [[.5, 1] [-.5, 1] [-.5, 1]], [0.0, 1]\n    a, b = DEC.parametrize_subspace(M, v)\n    @test M * a \u2248 v\n    @test M * (a + b * [1]) \u2248 v\n    @test M * (a + b * [-2]) \u2248 v\n\n    M, v = [[.5, 1] [-.5, 1]], [0.0, 1]\n    a, b = DEC.parametrize_subspace(M, v)\n    @test size(b) == (2,0)\n    @test M * a \u2248 v\nend\n\n@testset \"sign_of_permutation\" begin\n    @test DEC.sign_of_permutation([1],[1]) == 1\n    @test DEC.sign_of_permutation([1,2],[2,1]) == -1\n    @test DEC.sign_of_permutation([1,2],[1,2]) == 1\nend\n", "meta": {"hexsha": "a07eacf94bb2dc30b7d54752c8d8678402dddad4", "size": 787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 28.1071428571, "max_line_length": 52, "alphanum_fraction": 0.5133418043, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7647154236599979}}
{"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,\u03f5)\n    i=0\n    r=b-A*x\n    d=deepcopy(r)\n    \u03b4new = r'*r\n\n    # added by myself\n    r0 = b\n    \u03b40 = r0'*r0\n\n    while i<imax && \u03b4new > \u03f5^2 * \u03b40\n        q = A*d\n        \u03b1 = \u03b4new/(d'*q)\n        x = x + \u03b1*d\n        if mod(i,50) == 0\n            r=b-A*x\n        else\n            r=r-\u03b1*q\n        end\n\n        \u03b4old = deepcopy(\u03b4new)\n        \u03b4new = r'*r\n        \u03b2 = \u03b4new/\u03b4old\n        d = r + \u03b2*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- `\ud835\udef9`: 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> \ud835\udef9, R_mag, R_phase = R_coeff(Zc)\r\n```\r\n\r\n\"\"\"\r\nfunction R_coeff(Zc;len::Int64=1000)\r\n    \ud835\udef9 = range(0.0,\u03c0/2, length = len)\r\n    R_coeff = ( sin.(\ud835\udef9) .- 1/Zc ) ./ ( sin.(\ud835\udef9) .+ 1/Zc )\r\n    THETA = Float32.(\ud835\udef9*180/\u03c0)\r\n    RMAG = Float32.(abs.(R_coeff))\r\n    RPHASE = Float32.(angle.(R_coeff)*180/\u03c0)\r\n    return THETA, RMAG, RPHASE\r\nend\r\n\r\n\r\n#@btime R_coeff(Zc)\r\n#\ud835\udef9, R_mag, R_phase =   R_coeff(Zc)\r\n#plot(\ud835\udef9,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- `\ud835\udef9`: 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> \ud835\udef9, Q_mag, Q_phase = R_coeff(Zc)\r\n```\r\n\r\n\"\"\"\r\nfunction Q_coeff(Zc,R2,f,len=100)\r\n    \u03bb = c0/f\r\n    k = 2*\u03c0/\u03bb\r\n    \ud835\udef9 = range(0,\u03c0/2, length = len)\r\n\r\n    Q_coeff = randn(ComplexF64, (length(\ud835\udef9), 1))\r\n    for i=1:length(\ud835\udef9)\r\n        d = sqrt(1im*k*R2/2) * (1/Zc + sin(\ud835\udef9[i]))\r\n        Fd = 1 + 1im*sqrt(\u03c0)*d*erfcx(-1im*(d))\r\n        Q_coeff[i] = (Zc*sin(\ud835\udef9[i]) - 1 + 2*Fd) / (Zc*sin(\ud835\udef9[i]) + 1)\r\n    end\r\n\r\n    return Float32.(\ud835\udef9*180/\u03c0), Float32.(abs.(Q_coeff[:,1])), Float32.(angle.(Q_coeff[:,1])*180/\u03c0)\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\u2c7c - y\u1d62)/(x\u2c7c - x\u1d62 )). 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, \u03b3 = lpc(x, p)\n    arPoly = Polynomial(reverse([1; arcoefs]))\n    poles = Polynomials.roots(arPoly)\n\n\n    z2f(z) = abs(real((2\u03c0*im)^-1 * log(z)))\n    centerFrequencies = z2f.(poles) .* sf\n\n    f = range(0, 0.5, length = nfreq)\n    f2z(f) = exp(2\u03c0*im * f)\n    z = f2z.(f)\n\n    S = zeros(Complex, length(f), p)\n    \u03b3k(k) = 2\u03b3 / (poles[k] * prod(poles[k] .- poles[1:end .!= k]) * prod(poles[k]^-1 .- poles)) \n    for k in 1:p\n        Sk(z) = ((\u03b3k(k) * poles[k]) / (z^-1 - poles[k]) + \u03b3k(k) + (\u03b3k(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 CSV, TimeSeries, Dates, Statistics, StatsBase, Measures, Plots; pyplot()\n\ndf = CSV.read(\"../data/oneOnEpsilonBlogs.csv\",copycols = true)\ntsA = TimeArray(Date.(df.Day,Dates.DateFormat(\"m/d/y\")),df.Users)\ntsB = moving(mean,tsA,7,padding = true)\ntsC = TimeArray(timestamp(tsA), values(tsA) - values(tsB))\n\ndow = dayofweek.(timestamp(tsA))\ndayDiv = [filter((x)->!isnan(x), values(tsC)[dow .== d]) for d in 1:7]\ndayMeans = mean.(dayDiv)\ndailyCorrection = dayMeans[dow]\nerrs = filter((x)->!isnan(x),values(tsC) - dailyCorrection)\ndiffs = diff(errs)\n\nlags = 1:50\nacc = autocor(diffs,lags)\n\ndefault(legend = false)\np1 = plot(diffs, c=:blue,\n        xlabel=\"Day\",ylabel=\"Difference Between Corrected Days\")\np2 = plot(lags,acc,line=:stem, c=:blue,\n        xlabel=\"Lag\",ylabel=\"Autocorrelation\")\nplot(p1,p2,size=(900,400),margin = 5mm)", "meta": {"hexsha": "eb07542f8bc415ace53456f6b4f7b279e2e9a019", "size": 830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8_chapter/autocorrelation.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/autocorrelation.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/autocorrelation.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": 36.0869565217, "max_line_length": 78, "alphanum_fraction": 0.6891566265, "num_tokens": 267, "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\u03a9xy = S\u00b9(0,2\u03c0) \u00d7 S\u00b9(0,2\u03c0)\nNx = 2^8; Ny = 2^8;\nfourier_grid = create_grid((Nx, Ny), \u03a9xy)\nx, y = fourier_grid.grid\nfourier_transform = Transform(fourier_grid)\n\nnames = (\"\u03d51\", \"\u03d52\", \"\u03d53\", \"\u03d54\")\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\u03d51.data .= f1\n\u03d52.data .= f2\n\u03d53.data .= f3\n\u03d54.data .= f4\n## Check Algebra\nnorm((\u03d51 * \u03d52 - \u03d53).data)/norm((\u03d53).data)\n\nf_\u03d51 = Field(\u03d51, BasicMetaData(\"\u03d51\"))\nf_\u03d52 = Field(\u03d52, BasicMetaData(\"\u03d52\"))\ntt =  2 * f_\u03d51 + f_\u03d52 * f_\u03d51 + 2 + tanh(f_\u03d51) + 2*2\ncompute(a::FourierField) = a\ncompute(tt)\nevaluate(tt)\n\n## Check Calculus\nkx, ky = fourier_grid.wavenumbers\n\u2202x = FourierOperator(im .* kx, FourierOperatorMetaData(\"\u2202x\"))\n\u2202y = FourierOperator(im .* ky, FourierOperatorMetaData(\"\u2202y\"))\n\n\u2202x(\u03d5)\n\n\u2202x(\u03d5) + 1 + (\u2202x^2 + \u2202y^2)(\u03d5)\n##\ndmd = DerivativeMetaData(FourierOperator(im .* kx, FourierOperatorMetaData(\"\u2202x\")), \"x\")\n\u2202x = Operator(nothing, dmd)\n\u2202x(f_\u03d51)\ndmd = DerivativeMetaData(FourierOperator(im .* ky, FourierOperatorMetaData(\"\u2202y\")), \"y\")\n\u2202y = Operator(nothing, dmd)\n\u2202\u02b8\u03d51 = \u2202y(f_\u03d52) * \u2202x(f_\u03d51)\nevaluate(\u2202\u02b8\u03d51)\ntmp = compute(\u2202\u02b8\u03d51)\np1 = plot(tmp)\n\n\na1 = compute(\u2202x)^2\na2 = compute(\u2202x^2)\nnorm(a1.op - a2.op)\n\n\u03941 = compute(\u2202x)^2 + compute(\u2202y)^2\n\u03942 = compute(\u2202x^2+\u2202y^2)\nnorm(\u03941.op - \u03942.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\u2082(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\u1d62=symbols(\"x\u2081 x\u2082 x\u2083\")\ny\u1d62=symbols(\"y\u2081 y\u2082 y\u2083\")\n#T9G9\nA=symbols(\"A\")\n\n# a\u1d62=[y[j]-y[m] for (j,m) in zip([2,3,1],[3,1,2])]\n# b\u1d62=[y[j]-y[m] for (j,m) in zip([2,3,1],[3,1,2])]\n# c\u1d62=[-x[j]+x[m] for (j,m) in zip([2,3,1],[3,1,2])]\na\u1d62=symbols(\"a\u2081 a\u2082 a\u2083\")\nb\u1d62=symbols(\"b\u2081 b\u2082 b\u2083\")\nc\u1d62=symbols(\"c\u2081 c\u2082 c\u2083\")\nL\u1d62=1/2/A .*(a\u1d62 .+b\u1d62 .*x .+c\u1d62 .*y)\nN\u1d64\u1d68\u1d62=[0.5*L\u1d62[i]*(b\u1d62[m]*L\u1d62[j]-b\u1d62[j]*L\u1d62[m]) for (i,j,m) in zip([1,2,3],[2,3,1],[3,1,2])]\nN\u1d65\u1d68\u1d62=[0.5*L\u1d62[i]*(c\u1d62[m]*L\u1d62[j]-c\u1d62[j]*L\u1d62[m]) for (i,j,m) in zip([1,2,3],[2,3,1],[3,1,2])]\n\nN\u1d62=Array{Basic}(undef,2,9)\nfor i in 1:3\n    N\u1d62[:,3i-2:3i]=[L\u1d62[i] 0 N\u1d64\u1d68\u1d62[i];\n                   0 L\u1d62[i] N\u1d65\u1d68\u1d62[i]]\nend\nB=L\u2082(N\u1d62)\nD\u2080=E\u2080/(1-\u03bd\u2080^2)\nD=D\u2080*[1 \u03bd\u2080 0;\n      \u03bd\u2080 1 0;\n      0  0 (1-\u03bd\u2080)/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": "@testset \"Test Spline Basis Evaluation\" begin\n\n    # constuct specific case that we can compute by hand\n\n    n = 5\n    a = 0\n    b = 1\n    params = SplineParams(linspace(a,b,n),0,1)\n\n    x = rand(10000)\n\n    basestr = @inferred BasisMatrices.evalbase(params, x)\n    base = full(basestr)\n\n    # vector of basis functions\n\n    function linBspline(u)\n\n        if u >= 0 && u < 0.25\n\n            return [1-4*u,4*u,0,0,0]\n\n        elseif u >= 0.25 && u < 0.5\n\n            return [0,2*(1 - 2*u),4*u-1,0,0]\n\n        elseif u >= 0.5 && u < 0.75\n\n            return [0,0,3 - 4*u,2*(2*u - 1),0]\n\n        else\n\n            return [0,0,0,4*(1 - u),4*u-3]\n\n        end\n\n    end\n\n    manualbase = Array(Float64,length(x),n)\n\n    for i in 1:length(x)\n\n        manualbase[i,:] = linBspline(x[i])\n\n    end\n\n    @testset \"test evalbase with linear B spline\" begin\n        @test  manualbase  ==  base\n    end\nend\n", "meta": {"hexsha": "3c2f57f294b59fe257de86be81f7e0d7125d4070", "size": 894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/spline.jl", "max_stars_repo_name": "fra100/tesi", "max_stars_repo_head_hexsha": "053c417a8018d924e1b85fb72b023528558d122d", "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/spline.jl", "max_issues_repo_name": "fra100/tesi", "max_issues_repo_head_hexsha": "053c417a8018d924e1b85fb72b023528558d122d", "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/spline.jl", "max_forks_repo_name": "fra100/tesi", "max_forks_repo_head_hexsha": "053c417a8018d924e1b85fb72b023528558d122d", "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.5294117647, "max_line_length": 57, "alphanum_fraction": 0.5201342282, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7645633119648662}}
{"text": "\n@testset \"Algebraic Decision Diagrams\" begin\n    @info \"ADD\"\n    ADD = AlgebraicDecisionDiagrams\n    @show x1 = indicator(Int,1) # equivalent to x1 = Node(1,Base.zero(Int),Base.one(Int))\n    @show one(x1) - x1 \n    @show \u00acx1\n    @show apply(x -> 1-x, x1)\n    @show x1 + (\u00acx1)\n    @show x1 * (\u00acx1)\n    @show x2 = indicator(Int,2)\n    @show x1 + x2\n    @show x1 * x2\n    @show apply(x -> x^2, x1 + x2)\n    @show \u2295(x,y) = (x + y) % 2 # sum mod 2\n    @show apply(\u2295,x1,x2)\n    @show x3 = indicator(Int,3)\n    \n    @info \"Odd Parity Function\"\n    @show apply(\u2295,x1,apply(\u2295,x2,x3))\n    @show apply(max, x1 * x2, x3)\n    \n    @info \"Example from Fig. 1 in Bryant's paper\"\n    @show apply(max, (\u00acx1)*x2, x1*x3)\n\n    @info \"Example in Fig. 5 of Bryant's paper\"\n    A3 = Node(3,zero(Int),one(Int))\n    @show A4 = ADD.reduce(Node(1,Node(2,zero(Int),A3),Node(2,A3,A3)))\n    # for (i,\u03b1) in enumerate(x1*x2)\n    #     println(i, \"\\n\", \u03b1)\n    # end\n    println()\n\n    @info \"Directed Graph ADD\"\n\n    @info \"Example in Fig 1. in Bahar et al. 1997's paper\"\n    x0 = indicator(Int,0)\n    nx0 = indicator(Int,0,true)\n    x1 = indicator(Int,2)\n    nx1 = indicator(Int,2,true)\n    y0 = indicator(Int,1)\n    ny0 = indicator(Int,1,true)\n    y1 = indicator(Int,3)\n    ny1 = indicator(Int,3,true)\n    @show graph = Terminal(2)*nx0*nx1*ny0*y1 + Terminal(2)*nx0*nx1*y0*ny1 + Terminal(2)*nx0*x1*ny0*y1 + Terminal(2)*nx0*x1*y0*ny1 + Terminal(4)*x0*nx1*y0*y1 + Terminal(4)*x0*x1*ny0*y1\n    @info \"Get scope\"\n    # collect nonterminal nodes\n    nt = filter(n -> isa(n,Node), collect(graph))\n    @show scope = mapreduce(index,union,nt) # 0,1,2,3\n    @test length(intersect(scope,[0,1,2,3])) == 4\n    println()\n\n    @info \"Matrix examples in page 9 of Bryant's paper\"\n    @show f = (\u00acx0)*(\u00acy0) + x0*y0\n    @show g = Terminal(4)*nx0 + Terminal(2)*x0\n    @show h = f + g\n    println()\n    @info \"Restriction\"\n    @show restrict(h,0,false)\n    @show h | (1 => true)\n    @show (h | (index(x0) => true)) + (h | (index(x0) => false))\n    @test value((h | (index(x0) => true)) + (h | (index(x0) => false))) == 7\n    @show (h | (index(y0) => true)) + (h | (index(y0) => false))\n    println()\n    @info \"marginalization\"\n    @show marginalize(h, index(x0))\n    @show marginalize(h, index(y0))\n    @show A4\n    @show (A4 | (2 => true)) + (A4 | (2 => false))\n    @show A5 = marginalize(A4, 2)\nend # testset", "meta": {"hexsha": "d5ecb5e431e15651d38dddec50f435f71686ef0b", "size": 2361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/add.jl", "max_stars_repo_name": "denismaua/AlgebraicDecisionDiagrams.jl", "max_stars_repo_head_hexsha": "95655130d309b6ee0c5819b23f28b3aed3f06214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-12T17:12:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T17:12:11.000Z", "max_issues_repo_path": "test/add.jl", "max_issues_repo_name": "denismaua/AlgebraicDecisionDiagrams.jl", "max_issues_repo_head_hexsha": "95655130d309b6ee0c5819b23f28b3aed3f06214", "max_issues_repo_licenses": ["MIT"], "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/add.jl", "max_forks_repo_name": "denismaua/AlgebraicDecisionDiagrams.jl", "max_forks_repo_head_hexsha": "95655130d309b6ee0c5819b23f28b3aed3f06214", "max_forks_repo_licenses": ["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.2535211268, "max_line_length": 183, "alphanum_fraction": 0.5658619229, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7645633089605827}}
{"text": "\"random number between a and b\"\nfunction randin(a::Real, b::Real)\n    -Inf < a \u2264 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 \u2264 w_i < \u221e, 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 \u2264 w < Inf\n        wr -= w\n        if wr \u2264 0\n            return i\n        end\n    end\nend\n\n\n\n\"\"\"\nReturns a random vector x = (x1, x2, ..., xn), such that\nxi \u2265 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 \u2265 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\u2080)/10K) with T\u2080 = 6.3 \u00b0C)\n\n    # constructor with default values, corresponding\n    # to a resting potential of -65 mV and temperature 6.3 \u00b0C\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": "## Contains functions and objects for statistical analysis\nusing Statistics, StatsBase\n\nTABLE_HEADER = [\"Statistic\", \"N\", \"Mean\", \"Min\", \"25 Percentile\", \"Median\", \"75 Percentile\", \"Max\", \"Standard Deviation\", \"Skewness\", \"Kurtosis\"]\n\n\"\"\"\ncomputes the summary statistics of a given data set\n\"\"\"\nfunction summary_data(name, data)\n        n = length(data)\n        \u03bc, \u03c3 = mean_and_std(data)\n        minim, q1, med, q3, maxim = StatsBase.nquantile(data, 4)\n        sk = skewness(data)\n        ku = kurtosis(data)\n        return [name n \u03bc minim q1 med q3 maxim \u03c3 sk ku]\nend\n", "meta": {"hexsha": "8f75931800b622d737c9f29fc3ee43eb51bfa145", "size": 569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tools/jl/DeltaRobot/src/stats.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/DeltaRobot/src/stats.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/DeltaRobot/src/stats.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.4705882353, "max_line_length": 145, "alphanum_fraction": 0.6555360281, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7645122560363307}}
{"text": "using LinearAlgebra: Diagonal\n\n# Loss function should return a pair of (e, \u2202e/\u2202y\u0302).\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\u0302, y) = (0.5 * sum((y - y\u0302) .^ 2), y\u0302 - y)\n\n#=====\n\n**Softmax** turns (multinomial) logit into probability:\n\n    softmax(x)_i = exp(x_i) / \u03a3 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            = -\u03a3 p log(q)\n            = H(p) + D_KL(p || q)\n            = -\u03a3 p log(p) + \u03a3 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(\u0177, y) := cross_entropy(softmax(\u0177), y)\n    logit_binary_cross_entropy(\u0177, y) := binary_cross_entropy(logistic(\u0177), 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  \u27f9\n    \u2202p_i/\u2202y_j = [i = j] p_i - p_i p_j\n\n    \u2202e/\u2202y_j = \u03a3_i \u2202e/\u2202p_i \u22c5 \u2202p_i/\u2202y_j\n\nOr in the form of matrix calculus,\n\n    \u2202e/\u2202y = \u2202e/\u2202p \u22c5 \u2202p/\u2202y\n\nAnd\n\n    e = -sum(y .* log(p)) / n  \u27f9\n    \u2202e/\u2202p = -y / n * (1/p)\n\nAlso note that $\u2202p/\u2202y \u2208 \u211c_{d \u00d7 d}$, so if mini-batch is used it is impossible to be expressed in\nmatrix form. We directly write `\u2202e/\u2202p \u22c5 \u2202p/\u2202y` of one sample as\n\n      (\u2202e/\u2202p) \u22c5 (diag(p) - p \u22c5 p')\n    = \u2207p .* p - sum(\u2207p .* p) * p    # a \u211c_d vector\n\nThe mini-batch case can be written as\n\n    ... = \u2207p .* p - sum(\u2207p .* p, dims=1) .* p    # a \u211c_{d \u00d7 n} matrix\n\n=#\nfunction logit_cross_entropy(\n    y\u0302::AbstractMatrix{Float64},\n    y::AbstractMatrix{Float64},\n)::Tuple{Float64, Matrix{Float64}}\n    n_batches = size(y\u0302, 2)\n    log_p = log_softmax(y\u0302)\n    e = -sum(y .* log_p) / n_batches\n\n    p = softmax(y\u0302)\n    \u2207p = @. -y / n_batches * inv(p)\n    t = \u2207p .* p\n    \u2207y = t - sum(t, dims=1) .* p\n\n    (e, \u2207y)\nend\n\n#=\n    logit_binary_cross_entropy(y\u0302, 0)\n        = -log(1 - logistic(y\u0302))\n        = -log(1 / (1 + exp(y\u0302)))\n        = -(0 - log(1 + exp(y\u0302)))\n        = -(y\u0302 - log(1 + exp(y\u0302))) + y\u0302\n        = -log_logistic(y\u0302) + y\u0302\n=#\nfunction logit_binary_cross_entropy(\n    y\u0302::AbstractMatrix{Float64},\n    y::AbstractMatrix{Bool},\n)::Tuple{Float64, Matrix{Float64}}\n    @assert size(y\u0302, 1) == 1\n    t = -log_logistic.(y\u0302)\n    ny = .!y\n    t[ny] .+= y\u0302[ny]\n    e = sum(t) / size(y\u0302, 2)\n\n    \u2202t_over_\u2202y = -\u2207log_logistic.(y\u0302, -t)\n    \u2202t_over_\u2202y[ny] .+= 1.0\n    \u2207y = \u2202t_over_\u2202y\n\n    (e, \u2207y)\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)} \u2013  \\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": "# Probability computations\n\nusing CommonLH, Random, Test\n\nfunction prob_matrix_test()\n    @testset \"Probability matrix\" begin\n        rng = MersenneTwister(304);\n        n = 4; m = 3;\n        probM = rand(rng, n, m);\n        probM ./= sum(probM);\n        @test validate_prob_matrix(probM)\n\n        # Prob(j)\n        prob_jV = [prob_j(probM, j) for j = 1 : n];\n        prob2_jV = prob_j(probM);\n        @test validate_prob_vector(prob_jV)\n        @test prob_jV \u2248 prob2_jV\n        prob3_jV = prob_j(probM, 1 : n);\n        @test prob3_jV \u2248 prob_jV\n\n        prob_kV = [prob_k(probM, k) for k = 1 : m];\n        prob2_kV = prob_k(probM);\n        @test validate_prob_vector(prob_kV)\n        @test prob_kV \u2248 prob2_kV\n        prob3_kV = prob_k(probM, 1 : m);\n        @test prob3_kV \u2248 prob_kV\n\n        for k = 1 : m\n            prob_j_kV = prob_j_k(probM, 1:n, k);\n            @test isapprox(sum(prob_j_kV), 1.0)\n            # Prob(j,k) for given k\n            prob_jkV = prob_j_kV .* prob_k(probM, k);\n            @test isapprox(prob_jkV, probM[:,k])\n        end \n\n        for j = 1 : n\n            prob_k_jV = prob_k_j(probM, 1:m, j);\n            @test isapprox(sum(prob_k_jV), 1.0)\n            # Prob(j,k) for given j\n            prob_jkV = prob_k_jV .* prob_j(probM, j);\n            @test isapprox(prob_jkV, vec(probM[j,:]))\n        end\n    end\nend\n\n\nfunction ev_test()\n\t@testset \"Expected values\" begin\n        rng = MersenneTwister(304);\n        n = 4; m = 3;\n        probM = rand(rng, n, m);\n        probM ./= sum(probM);\n\n        xM = rand(rng, n, m);\n\n        evV = ev_given_j(xM, probM);\n        @test size(evV) == (n,)\n        for j = 1 : n\n            ev = ev_given_j(xM, probM, j);\n            prV = vec(probM[j,:]);\n            xV = vec(xM[j,:]);\n            ev2 = sum(xV .* prV) / sum(prV);\n            @test isapprox(ev, ev2)\n            @test isapprox(ev, evV[j])\n        end\n\n        evV = ev_given_k(xM, probM);\n        @test size(evV) == (m,)\n        for k = 1 : m\n            ev = ev_given_k(xM, probM, k);\n            prV = probM[:, k];\n            xV = xM[:, k];\n            ev2 = sum(xV .* prV) / sum(prV);\n            @test isapprox(ev, ev2)\n            @test isapprox(ev, evV[k])\n        end\n    end\nend\n\nfunction scale_test()\n    @testset \"Scale prob array\" begin\n        x = rand(4,3,2) ./ 5.0;\n        x[2 : 2 : 8] .= -0.000000001;\n        x ./= sum(x);\n        x .+= 0.000000001;\n        scale_prob_array!(x);\n        @test sum(x) <= 1.0\n        @test all(x .>= 0.0)\n\tend\nend\n\n\n@testset \"Probabilities\" begin\n    ev_test()\n    prob_matrix_test()\nend\n\n# -------------", "meta": {"hexsha": "c51fab75e07ed05db9b5d4b70f9981f84e58f5a5", "size": 2586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/probabilities_test.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": "test/probabilities_test.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": "test/probabilities_test.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": 26.387755102, "max_line_length": 53, "alphanum_fraction": 0.4911059551, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8198933337131077, "lm_q1q2_score": 0.7645122488553473}}
{"text": "# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/\n#  Niccol\u00f2 Antonello <nantonel@idiap.ch>\n\nexport shortest_distance\n\n\"\"\"\n  `shortest_distance(fst[, s=get_initial(fst); filter=arc->true, reverse=false)`\n\nComputes the shortest distance between the state `s` to every other state.\nThe shortest distance between `s` and `i` is defined as the sum of the weights of all paths between these states.\n\nWeights are required to be rigth distributive and k-closed.\n\nIf `fst` has `N` states a `N`-long vector is returned where the `i`-the element contains the shortest distance between the states `s` and `i`.\n\nIf `reversed==true` the shortest distance from the final states is computed.\nIn this case `s` has no effect since a new initial superstate is added to the reversed WFST.\nHere weights are required to be left distributive and k-closed. \n\nSee Mohri \"Semiring framework and algorithms for shortest-distance problems\", Journal of Automata, Languages and Combinatorics 7(3): 321-350, 2002.\n\n\"\"\"\nfunction shortest_distance(fst::WFST{W}, s=get_initial(fst); filter=arc->true, reversed=false) where {W}\n\n  if reversed\n    if !isright(W)\n      throw(ErrorException(\"Weight $W is not right distributive\"))\n    end\n    if !ispath(W)\n      throw(ErrorException(\"Weight $W must satisfy the \\\"path\\\" property\"))\n    end\n\n    rfst = reverse(fst)\n    d = no_check_shortest_distance(rfst,get_initial(rfst);filter=filter)\n    return d[2:end]\n  else\n    if !isleft(W)\n      throw(ErrorException(\"Weight $W is not left distributive\"))\n    end\n    if !ispath(W)\n      throw(ErrorException(\"Weight $W must satisfy the \\\"path\\\" property\"))\n    end\n    return no_check_shortest_distance(fst,s;filter=filter)\n  end\n\nend\n\nfunction no_check_shortest_distance(fst::WFST{W,A,D},\n                                    s::D=get_initial(fst);\n                                    filter=arc->true) where {W,A,D}\n  Ns = size(fst,1)\n  d = zeros(W,Ns) # d[q] estimate of shortest distance between q and s\n  r = zeros(W,Ns) # r[q] total weight added to d[q] since last time q was extracted from S\n  d[s], r[s] = one(W), one(W)\n  S = Queue{D}()\n  enqueue!(S,s)\n  while !isempty(S)\n    q = dequeue!(S) \n    R = r[q]\n    r[q] =  zero(W)\n    for arc in fst[q]\n      if filter(arc)\n        n, w = get_nextstate(arc), get_weight(arc)\n        dn = d[n]\n        if dn != (dn+(R*w))\n          d[n] = dn+(R*w) \n          r[n] = r[n]+(R*w)\n          if !(n in S)\n            enqueue!(S,n)\n          end\n        end\n      end\n    end\n  end\n  d[s] = one(W)\n  return d\nend\n\n", "meta": {"hexsha": "22f4f8f6d9481a015730e8e530e81c9343e3f6cd", "size": 2537, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/shortest_distance.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/algorithms/shortest_distance.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/algorithms/shortest_distance.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": 32.1139240506, "max_line_length": 147, "alphanum_fraction": 0.6440677966, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7645122483425506}}
{"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": "include(\"../src/plotSol.jl\")\ninclude(\"../src/simulate.jl\")\ninclude(\"../src/OrientationConversion.jl\")\nusing Revise\nusing JLD\nclearconsole()\n\nm = 1.0; l = 1.0; r = 0.01 # Mass, length, and radius of bar\n# Assuming bar revolves about Z axis\n# I1 = [m*r^2/2 0 0; 0 m*(l^2/12 + r^2/4) 0; 0 0 m*(l^2/12 + r^2/4)]\nI1 = [m*(l^2/12 + r^2/4) 0 0; 0 m*(l^2/12 + r^2/4) 0; 0 0 m*(l^2/12 + r^2/4)]\n\n# Testing Dynamics with Revolute Joint\n# System looks like this:\n# ====|====     | is the joint axis.\nRbI = InertialFrameAsRB()\nR1 = RigidBody(m,I1,2)\nx0R1 = [0.0;zeros(2);[1;zeros(3)];zeros(3);zeros(4)]\ninitialiseRigidBody!(R1,x0R1)\n\naxis = [0.0 0.0 1.0][:] # Axis about which bar is revolving\n\nrj1 = [0.0 0.0 0.0][:] # Joint Location in body frame of first body\nrj2 = [0 0.0 0.0][:] # Joint location in body frame of second body\n\nj = Joint(RbI,R1,rj1,rj2,type=\"Revolute\",axis=axis)\n\n# External Forces Definition\ng = [0.0;0.0;0.0]\n\n# Simulation\ntEnd = 1.0\ntSpan = 0.01\ntSim, solFinal = simulate(tEnd,tSpan,j,g=g)\n\nsolPend  = solFinal[1]\n\n# After adding solSim\nplotErrNorm(tSim,solPend.\u03b2)\n# Check if joint location has moved\njointLoc = Matrix{Float64}(undef,length(tSim),3)\n\u03c9Sol = Matrix{Float64}(undef,length(tSim),3)\nrEnd = Matrix{Float64}(undef,length(tSim),3)\nendPos = [l/2;0;0]\nfor i=1:length(tSim)\n    R1.dcm = quat2dcm(solFinal[1].\u03b2[i,:])\n    \u03c9Sol[i,:] = angVel(solFinal[1].\u03b2[i,:],solFinal[1].\u03b2dot[i,:])\n    rEnd[i,:] = solPend.r[i,:] + transpose(R1.dcm)*endPos\n    jointLoc[i,:] = solFinal[1].r[i,:] + transpose(R1.dcm)*rj2\nend\nplotPos(tSim,jointLoc)\nplotPos(tSim,solPend.r)\nplotPos(tSim,rEnd)\nplotQuat(tSim,solPend.\u03b2)\nplotAngVel(tSim,\u03c9Sol)\n# plotQuatDot(tSim,solPend.\u03b2dot)\n", "meta": {"hexsha": "38381964c406a5f2126c321d742e7338eae1b850", "size": 1669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "UdKaDyn/Examples/testJoint.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/testJoint.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/testJoint.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": 29.2807017544, "max_line_length": 77, "alphanum_fraction": 0.6560814859, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7645122432127536}}
{"text": "sqrt(sum(x -> x*x, A) / length(A))\n", "meta": {"hexsha": "881332dcfd420188a5c7abebb754502a57060a41", "size": 35, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/averages-root-mean-square-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/averages-root-mean-square-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/averages-root-mean-square-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": 17.5, "max_line_length": 34, "alphanum_fraction": 0.5142857143, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7645116098815882}}
{"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    \u03d5 = zeros(N, bases)\n\n    for i = 1:bases\n\n        if i == 1\n            \u03d5[:, 1] .= 1.0\n        else\n            \u03d5[:, i] .= x.^(i-1)\n        end\n\n    end\n\n    # \u03d5 \u03b2 = y => \u03b2 = \u03d5 \\ y\n\n    return \u03d5 \\ 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    \u03b2 = LinearRegression(x, y; order=order)\n    \n    result = copy(y)\n    total_mean = 0.0\n    for i = 1:bases\n        result .-= \u03b2[i] * x.^(i-1)\n        total_mean += \u03b2[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(\u03b1)\n\t\t\t\tx1 = (this.center - this.l_vertex) * \u03b1 + this.l_vertex\n\t\t\t\tx2 = (this.center - this.r_vertex) * \u03b1 + 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(\u03b1)\n\t\t\t\tx1, x2 = inv(\u03b1)\n\t\t\t\treturn CutMF(x1, x2, \u03b1, 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(\u03b1)\n\t\t\tx1 = this.center - this.sigma*sqrt(-2*log(\u03b1))\n\t\t\tx2 = this.center + this.sigma*sqrt(-2*log(\u03b1))\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(\u03b1)\n\t\t\tx1, x2 = inv(\u03b1)\n\t\t\treturn CutMF(x1, x2, \u03b1, 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(\u03b1)\n\t\t\tx1 = this.c - this.a*((1-\u03b1)/\u03b1)^(1/(2*b))\n\t\t\tx2 = this.c + this.a*((1-\u03b1)/\u03b1)^(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(\u03b1)\n\t\t\treturn (u-l)^3/(12*tol)\n\t\tend\n\t\tthis.cut = function cut(\u03b1)\n\t\t\tx1, x2 = inv(\u03b1)\n\t\t\treturn CutMF(x1, x2, \u03b1, 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(\u03b1)\n\t\t\t\tx1 = (this.l_top_vertex - this.l_bottom_vertex) * \u03b1 + this.l_bottom_vertex\n\t\t\t\tx2 = (this.r_top_vertex - this.r_bottom_vertex) * \u03b1 + 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(\u03b1)\n\t\t\t\tx1, x2 = inv(\u03b1)\n\t\t\t\treturn CutMF(x1, x2, \u03b1, 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(\u03b1)\n\t\t\t\treturn this.c - (1/this.a)*log((1-\u03b1)/\u03b1)\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(\u03b1)\n\t\t\t\tx = inv(\u03b1)\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, \u03b1, 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\u03b1::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, \u03b1::Real, toCutMF::MF)\n\n\t\tthis = new()\n\n\t\tthis.x1 = x1\n\t\tthis.x2 = x2\n\t\tthis.\u03b1 = \u03b1\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.\u03b1\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 >= \u03b1\n\t\t\t\treturn this.toCutMF.mean_at(\u03b1)\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(\u03b1)\n\t\t\tif \u03b1 >= this.\u03b1\n\t\t\t\treturn this\n\t\t\telse\n\t\t\t\treturn this.toCutMF.cut(\u03b1)\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": "# Logistic regression\n\nusing Regression\nimport Regression: solve, Options\n\n\n# Data\n\nd = 3\nn = 1000\n\nw = randn(d+1)\nX = randn(d, n)\ny = sign(X'w[1:d] + w[d+1] + 0.2 * randn(n))\n\n# Solve\n\nret = solve(logisticreg(X, y; bias=1.0),\n            reg=SqrL2Reg(1.0e-2),\n            options=Options(verbosity=:iter, grtol=1.0e-6 * n))\n\nprintln()\n\n# Print results\n\nw_e = ret.sol\n\n@printf(\"corr(truth, estimated) = %.6f\\n\", dot(w, w_e) / (vecnorm(w) * vecnorm(w_e)))\n", "meta": {"hexsha": "bb6fa411acba027799f404c740575c2bea07bba9", "size": 455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/logireg.jl", "max_stars_repo_name": "JuliaPackageMirrors/Regression.jl", "max_stars_repo_head_hexsha": "4827d41c163a9d5bbbb53129b02b29446e6f8fd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2015-01-11T18:03:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T06:16:46.000Z", "max_issues_repo_path": "examples/logireg.jl", "max_issues_repo_name": "JuliaPackageMirrors/Regression.jl", "max_issues_repo_head_hexsha": "4827d41c163a9d5bbbb53129b02b29446e6f8fd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-04-21T14:28:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:29:06.000Z", "max_forks_repo_path": "examples/logireg.jl", "max_forks_repo_name": "JuliaPackageMirrors/Regression.jl", "max_forks_repo_head_hexsha": "4827d41c163a9d5bbbb53129b02b29446e6f8fd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2015-02-02T07:51:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T21:54:27.000Z", "avg_line_length": 15.6896551724, "max_line_length": 85, "alphanum_fraction": 0.5978021978, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.764511598670259}}
{"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), \u03c0= 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., \u03bb::Float64= 1.)\r\n\tontoSimplex!(p1); ontoSimplex!(p2); count= 0\r\n\t\u03b2r= Array{Float64}(undef, length(p1));\r\n\t\u03b3c= ones(size(p2))\t\t# guess a starting value\r\n\tdistMatrix.^= rWasserstein; K= exp.(-\u03bb * distMatrix)\r\n\twhile count < 1000\t\t# Sinkhorn iteration\r\n\t\t\u03b3c= \u03b3c./ (p2'*\u03b3c)\t\t# rescale\r\n\t\t\u03b2r= p1./ (K* \u03b3c)\t\t# vector operation\r\n\t\t\u03b3c= p2./ (K'* \u03b2r)\t\t# vector operation\r\n\t\tcount += 1\t\t\t\t# iteration count\r\n\tend\r\n#\tprintln(\"r=\", \u03b2r, p1'*\u03b2r); println(\"c=\", \u03b3c, p2'*\u03b3c)\r\n\t\u03c0= Diagonal(\u03b2r)*K*Diagonal(\u03b3c)\r\n\treturn (distance= (sum(\u03c0.* distMatrix)) ^(1/rWasserstein), \u03c0= \u03c0)\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., \u03bb::Float64= 1.)\r\n# \tontoSimplex!(p1); ontoSimplex!(p2)\r\n# \t\u03c0= exp.(-\u03bb * (distMatrix.^ rWasserstein))\r\n# \tfor i= 1:100\r\n# \t\t\u03c0.*= (p2'./ sum(\u03c0, dims=1)) # scale to sum of column= 1\r\n# \t\t\u03c0.*= (p1 ./ sum(\u03c0, dims=2)) # scale to sum of lines= 1\r\n# \tend\r\n# \treturn (distance= sum(\u03c0.* distMatrix)^(1/ rWasserstein), \u03c0= \u03c0)\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 \u03bc\u03b7, the derivative of \u03bc w.r.t. \u03b7\n\nabstract Link\n\nimmutable IdentityLink <: Link end\nimmutable InverseLink <: Link end\nimmutable LogLink <: Link end\nimmutable LogitLink <: Link end\n\nlink(::IdentityLink,\u03bc) = \u03bc\ninvlink(::IdentityLink,\u03b7) = \u03b7\n\u03bc\u03b7(::IdentityLink,\u03b7) = one(\u03b7)\n\nlink(::LogitLink,\u03bc) = log(\u03bc/(one(\u03bc)-\u03bc))\ninvlink(::LogitLink,\u03b7) = inv(one(\u03b7) + exp(-\u03b7))\n\u03bc\u03b7(::LogitLink,\u03b7) = (ee = exp(-\u03b7); ee/abs2(one(\u03b7)+ee))\n\nlink(::LogLink,\u03bc) = log(\u03bc)\ninvlink(::LogLink,\u03b7) = exp(\u03b7)\n\u03bc\u03b7(::LogLink,\u03b7) = exp(\u03b7)\n\nlink(::InverseLink,\u03bc) = inv(\u03bc)\ninvlink(::InverseLink,\u03b7) = inv(\u03b7)\n\u03bc\u03b7(::InverseLink,\u03b7) = -inv(abs2(\u03b7))\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\u0394 = Laplacian(S)\n\nf = Fun((x,y)->sin(\u03c0*x)*sin(\u03c0*y),S)\n\nQR1=qr(\u0394)\n    ApproxFun.resizedata!(QR1,:,400)\n    \\(QR1,f; tolerance=1E-10)\nQR1=qr(\u0394)\n    @time \u0394[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)),\u2202(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# \u03f5=0.1\n#\n# u0=Fun(x->exp(-25*(x-.5)^2)*exp(-1.0im/(5*\u03f5)*log(2cosh(5*(x-.5)))),dx)\n# L=1im*\u03f5*Dt+.5*\u03f5^2*Dx^2-V\u22971\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": "module SolverTests\nusing Base.Test;\nusing FactCheck;\nusing ValidatedNumerics;\nusing IntervalLinearEquations;\n\nfunction interval_approx_eq(a_interval :: Interval{Float64}, b_interval :: Interval{Float64})\n    isapprox(a_interval.lo, b_interval.lo) &&\n    isapprox(a_interval.hi, b_interval.hi)\nend\n\n\nfacts(\"Solve 2x2 system with number matrix\") do\n    bVector = [\n        @interval(-2.0, 2.0); @interval(-2.0, 2.0);\n    ] :: Array{Interval{Float64}};\n    aMatrix = [\n        @interval(2, 4) @interval(-2, 1);\n        @interval(-1, 2) @interval(2, 4);\n    ] :: Array{Interval{Float64}};\n\n    result = IntervalLinearEquations.solve(\"G\", eye(aMatrix), bVector, 0.1, 10, 1.0)\n    @fact result --> bVector\nend\n\nfacts(\"Solve 2x2 system with random matrix\") do\n    xVector = [\n        @interval(-1.0, 2.0); @interval(-1.0, 2.0);\n    ] :: Array{Interval{Float64}};\n    aMatrix = [\n        @interval(-2, 4) @interval(-3, 0);\n        @interval(-1, 0) @interval(2, 5);\n    ] :: Array{Interval{Float64}};\n    bVector = aMatrix * xVector\n\n    solution = IntervalLinearEquations.solve(\"G\", aMatrix, bVector, 0.1, 10, 1.0)\n    bFromSolution = aMatrix * solution\n    @fact all(map(interval_approx_eq, bVector, bFromSolution)) --> true\n    @fact all(map(interval_approx_eq, solution, xVector)) --> true\nend\n\nfacts(\"Solve 2x2 system with interval matrix\") do\n    bVector = [\n        @interval(-2.0, 2.0); @interval(-2.0, 2.0);\n    ] :: Array{Interval{Float64}};\n    aMatrix = [\n        @interval(2, 4) @interval(-2, 1);\n        @interval(-1, 2) @interval(2, 4);\n    ] :: Array{Interval{Float64}};\n    preciseX = [\n        @interval(-0.33333333333333337, 0.33333333333333337);\n        @interval(-0.33333333333333337, 0.33333333333333337);\n    ] :: Array{Interval{Float64}};\n\n    solution = IntervalLinearEquations.solve(\"G\", aMatrix, bVector, 0.1, 10, 1.0)\n    bFromSolution = aMatrix * solution\n    @fact all(map(interval_approx_eq, bVector, bFromSolution)) --> true\n    @fact all(map(interval_approx_eq, solution, preciseX)) --> true\nend\n\nend\n", "meta": {"hexsha": "71a224fcbecf99b552d22be207adb882a6999ca4", "size": 2025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_solver.jl", "max_stars_repo_name": "EvgeneOskin/-interval-linear-equations-solver", "max_stars_repo_head_hexsha": "fc71233c800de366cf78f866695458d1ec6bf770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-24T14:57:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-24T14:57:02.000Z", "max_issues_repo_path": "test/test_solver.jl", "max_issues_repo_name": "EvgeneOskin/-interval-linear-equations-solver", "max_issues_repo_head_hexsha": "fc71233c800de366cf78f866695458d1ec6bf770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-06-27T14:53:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:34:30.000Z", "max_forks_repo_path": "test/test_solver.jl", "max_forks_repo_name": "EvgeneOskin/-interval-linear-equations-solver", "max_forks_repo_head_hexsha": "fc71233c800de366cf78f866695458d1ec6bf770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:14:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:33:43.000Z", "avg_line_length": 32.6612903226, "max_line_length": 93, "alphanum_fraction": 0.6404938272, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.764410871374982}}
{"text": "using Test, SpecialFunctions\nimport TruncatedNormal as TruncNorm\n\n@test TruncNorm.tnmom2(-Inf, Inf) == 1\n@test TruncNorm.tnmom2(+Inf, +Inf) == Inf\n@test TruncNorm.tnmom2(-Inf, -Inf) == Inf\n@test TruncNorm.tnmom2(-Inf, 0) == 1\n@test TruncNorm.tnmom2(0, +Inf) == 1\n\n@test isnan(TruncNorm.tnmom2(1, 0))\n@test isnan(TruncNorm.tnmom2(+Inf, 0))\n@test isnan(TruncNorm.tnmom2(0, -Inf))\n@test isnan(TruncNorm.tnmom2(+Inf, -Inf))\n@test isnan(TruncNorm.tnmom2(NaN, NaN))\n@test isnan(TruncNorm.tnmom2(0, NaN))\n@test isnan(TruncNorm.tnmom2(NaN, 0))\n\nfor x = -10:10\n    @test TruncNorm.tnmom2(x, +Inf) \u2248 1 + x * \u221a(2/\u03c0) / erfcx(+x/\u221a2)\n    @test TruncNorm.tnmom2(-Inf, x) \u2248 1 - x * \u221a(2/\u03c0) / erfcx(-x/\u221a2)\nend\n\n@test TruncNorm.tnmom2(-Inf, Inf, 0, 1) == 1\n\nfor x = -10:10\n    @test TruncNorm.tnmom2(x, +Inf, 0, 1) \u2248 TruncNorm.tnmom2(x, +Inf)\n    @test TruncNorm.tnmom2(-Inf, x, 0, 1) \u2248 TruncNorm.tnmom2(-Inf, x)\nend\n\n@test TruncNorm.tnmom2(-1e200, 1e200) \u2248 1\n@test TruncNorm.tnmom2(-1e6, -999000) \u2248 9.9800100000199999999999799599399200002e11\n@test TruncNorm.tnmom2(+1e6, +Inf) \u2248 1.00000000000199999999999800000e12\n@test TruncNorm.tnmom2(-Inf, -1e6) \u2248 1.00000000000199999999999800000e12\n\n@test TruncNorm.tnmom2(-Inf, Inf, 2, 0) \u2248 4\n@test TruncNorm.tnmom2(0, 20, 3, 3//2) \u2248 11.4986153820554548159603543747\n@test TruncNorm.tnmom2(10, 20, 3, 3//2) \u2248 106.111726253622178129044932133\n@test TruncNorm.tnmom2(-10, 20, 3, 3//2) \u2248 11.2499999999999997949173964131\n", "meta": {"hexsha": "a676daa72d4828c51e85fe0fe6e5f5c28cb941ea", "size": 1435, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tnmom2.jl", "max_stars_repo_name": "suzannastep/TruncatedNormal.jl", "max_stars_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_stars_repo_licenses": ["MIT"], "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/tnmom2.jl", "max_issues_repo_name": "suzannastep/TruncatedNormal.jl", "max_issues_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_issues_repo_licenses": ["MIT"], "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/tnmom2.jl", "max_forks_repo_name": "suzannastep/TruncatedNormal.jl", "max_forks_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_forks_repo_licenses": ["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.7948717949, "max_line_length": 82, "alphanum_fraction": 0.6975609756, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.764410869447271}}
{"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    \u0398, \u03a6 = sph_points(N::Integer)\n    \u0398::Vector{Float64}\n    \u03a6::Vector{Float64}\n\nCalculate the locations of points on the sphere when using `N` points\nin the \u03b8 (latitudinal) direction.\n\nIt is `length(\u0398) = N` and `length(\u03a6) = M` where `M = 2N-1`.\n\"\"\"\nfunction sph_points(N::Int)\n    @assert N > 0\n    M = 2 * N - 1\n    return \u03c0 / N * (0.5:(N - 0.5)), 2\u03c0 / 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 \u201cdegenerate\u201d triangle.)\n\n## 1. Write a function named istriangle that takes three integers as arguments, and that prints either \u201cYes\u201d or \u201cNo\u201d, 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": "using COSMO, Test, LinearAlgebra, SparseArrays\n# this is the problem\n# \"sdp_sigma_max_atom\"\n# from the Convex.jl problem set that caused errors in the\n# compact_transformation\n\n# max   \u03c3_max(Y)\n# s.t.  Y[2, 1] <= 4, Y[2, 2] >= 3, sum(Y) >= 12\n# where Y in R_{3x3}\n#\n# which is equivalent to\n#   min t\n#   s.t. [t * I Y; Y' t * I]  \u2ab0 0\n\n# define x := [t; vec(Y)]\n@testset \"Chordal LMI-SDP - Maximum singular value problem\" begin\n    q = [1.0; zeros(9)]\n    con1 = COSMO.Constraint([0 0 -1.0 zeros(1, 7)], 4.0, COSMO.Nonnegatives)\n    con2 = COSMO.Constraint([0 0 0 0 0 1.0 zeros(1, 4)], -3.0, COSMO.Nonnegatives)\n    con3 = COSMO.Constraint([0.0 ones(1, 9)], -12.0, COSMO.Nonnegatives)\n\n    A_lmi1 = [-1.;0; -1; 0; 0; -1; 0; 0; 0; -1; 0; 0; 0; 0; -1; 0; 0; 0; 0; 0; -1]\n    A_lmi2 = spzeros(21, 9)\n    A_lmi2[7, 1] = A_lmi2[8, 2] = A_lmi2[9, 3] = A_lmi2[11, 4] = A_lmi2[12, 5] = A_lmi2[13, 6] = A_lmi2[16, 7] = A_lmi2[17, 8] = A_lmi2[18, 9] = -sqrt(2)\n    A_lmi = [A_lmi1 A_lmi2]\n    con4 = COSMO.Constraint(-A_lmi, zeros(21), COSMO.PsdConeTriangle(21))\n\n    model = COSMO.Model()\n    assemble!(model, spzeros(10, 10), q, [con1; con2; con3; con4], settings = COSMO.Settings(compact_transformation = true, decompose = true))\n    res = COSMO.optimize!(model);\n    Y = reshape(res.x[2:end], 3, 3)\n    # check inequality constraints\n    @test Y[2, 1] <= 4\n    @test Y[2, 2] >= 3\n    @test sum(Y) - 12.0 >= -1e-3\n    # check maximum singular value\n    \u03c3_max = maximum(svd(Y).S)\n    t = res.x[1]\n    @test abs(\u03c3_max - t ) <= 1e-3\n\nend\n", "meta": {"hexsha": "112849535412d9918a340b11fdb4eea8bb330302", "size": 1528, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/UnitTests/nuclear_norm_minimization.jl", "max_stars_repo_name": "msarfati/COSMO.jl", "max_stars_repo_head_hexsha": "c12d46c485ddccba286d3447d60d1cb399402119", "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/nuclear_norm_minimization.jl", "max_issues_repo_name": "msarfati/COSMO.jl", "max_issues_repo_head_hexsha": "c12d46c485ddccba286d3447d60d1cb399402119", "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/nuclear_norm_minimization.jl", "max_forks_repo_name": "msarfati/COSMO.jl", "max_forks_repo_head_hexsha": "c12d46c485ddccba286d3447d60d1cb399402119", "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.380952381, "max_line_length": 153, "alphanum_fraction": 0.5929319372, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7644108600275398}}
{"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\u00d75 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]; \u03bb=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 `\u03bb` 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; \u03bb=550e-9, shift=false)\n    \u03ba = calc_\u03ba(\u03bb) \n    \u0394k\u22a5 = 2 * \u03ba * 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(\u03c0 * \u0394k\u22a5 * 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\u2080, t\u2081, x\u2080, x\u2081, x\u0307\u2080, x\u0307\u2081, t, x)\n_hermite_extrapolation!(t\u2080, t\u2081, x\u2080, x\u2081, x\u0307\u2080, x\u0307\u2081, t, x, x\u0307)\n_hermite_extrapolation!(v, t\u2080, t\u2081, x\u2080, x\u2081, t, x)\n_hermite_extrapolation!(v, t\u2080, t\u2081, x\u2080, x\u2081, t, x, x\u0307)\n```\n\nwhere\n\n* `t\u2080`: first  sample time $t_0$\n* `t\u2081`: second sample time $t_1$\n* `x\u2080`: first  solution value $x_0 = x(t_0)$\n* `x\u2081`: second solution value $x_1 = x(t_1)$\n* `x\u0307\u2080`: first  vector field value $x\u0307_0 = v(t_0, x(t_0))$\n* `x\u0307\u2081`: second vector field value $x\u0307_1 = v(t_1, x(t_1))$\n* `v`:  function to compute vector field with signature `v(t,x,x\u0307)`\n* `t`:  time $t$ to extrapolate\n* `x`:  extrapolated solution value $x(t)$\n* `v`:  extrapolated vector field value $x\u0307(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\u2080::TT, t\u2081::TT, x\u2080::AbstractArray{DT}, x\u2081::AbstractArray{DT}, x\u0307\u2080::AbstractArray{DT}, x\u0307\u2081::AbstractArray{DT}, t::TT, x::AbstractArray{DT}) where {DT,TT}\n    local a\u2080::TT\n    local a\u2081::TT\n    local b\u2080::TT\n    local b\u2081::TT\n    local \u0394t = t\u2081 - t\u2080\n    local s = (t - t\u2080) / \u0394t\n\n    # Interpolate x at t\n    if t == t\u2080\n        x .= x\u2080\n    elseif t == t\u2081\n        x .= x\u2081\n    else\n        a\u2081 = 3s^2 - 2s^3\n        a\u2080 = 1 - a\u2081\n        b\u2081 = s^2*(s-1)\n        b\u2080 = s*(1-s)+b\u2081\n        x .= a\u2080 .* x\u2080 .+ a\u2081 .* x\u2081 .+ b\u2080 .* \u0394t .* x\u0307\u2080 .+ b\u2081 .* \u0394t .* x\u0307\u2081\n    end\n\n    return x\nend\n\nfunction _hermite_extrapolation!(t\u2080::TT, t\u2081::TT, x\u2080::AbstractArray{DT}, x\u2081::AbstractArray{DT}, x\u0307\u2080::AbstractArray{DT}, x\u0307\u2081::AbstractArray{DT}, t::TT, x::AbstractArray{DT}, x\u0307::AbstractArray{DT}) where {DT,TT}\n    local a\u2080::TT\n    local a\u2081::TT\n    local b\u2080::TT\n    local b\u2081::TT\n    local \u0394t = t\u2081 - t\u2080\n    local s = (t - t\u2080) / \u0394t\n\n    _hermite_extrapolation!(t\u2080, t\u2081, x\u2080, x\u2081, x\u0307\u2080, x\u0307\u2081, t, x)\n\n    # Interpolate x\u0307 at t\n    if t == t\u2080\n        x\u0307 .= x\u0307\u2080\n    elseif t == t\u2081\n        x\u0307 .= x\u0307\u2081\n    else\n        a\u2081 = (6s - 6s^2) / \u0394t\n        a\u2080 = - a\u2081\n        b\u2081 = s*(3s-2)\n        b\u2080 = 1-2s+b\u2081\n        x\u0307 .= a\u2080 .* x\u2080 .+ a\u2081 .* x\u2081 .+ b\u2080 .* x\u0307\u2080 .+ b\u2081 .* x\u0307\u2081\n    end\n\n    return (x, x\u0307)\nend\n\nfunction _get_velocities(v::Function, t\u2080::TT, t\u2081::TT, x\u2080::AbstractArray{DT}, x\u2081::AbstractArray{DT}) where {DT,TT}\n    x\u0307\u2080 = zero(x\u2080)\n    x\u0307\u2081 = zero(x\u2081)\n    v(t\u2080, x\u2080, x\u0307\u2080)\n    v(t\u2081, x\u2081, x\u0307\u2081)\n    return (x\u0307\u2080, x\u0307\u2081)\nend\n\nfunction _hermite_extrapolation!(v::Function, t\u2080::TT, t\u2081::TT, x\u2080::AbstractArray{DT}, x\u2081::AbstractArray{DT}, t::TT, x::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(t\u2080, t\u2081, x\u2080, x\u2081, _get_velocities(v, t\u2080, t\u2081, x\u2080, x\u2081)..., t, x)\nend\n\nfunction _hermite_extrapolation!(v::Function, t\u2080::TT, t\u2081::TT, x\u2080::AbstractArray{DT}, x\u2081::AbstractArray{DT}, t::TT, x::AbstractArray{DT}, x\u0307::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(t\u2080, t\u2081, x\u2080, x\u2081, _get_velocities(v, t\u2080, t\u2081, x\u2080, x\u2081)..., t, x, x\u0307)\nend\n\n\n\nstruct HermiteExtrapolation{T} <: Extrapolation\n    t\u2080::T\n    t\u2081::T\n    \u0394t::T\n\n    function HermiteExtrapolation{T}(t\u2080, t\u2081) where {T}\n        new(t\u2080, t\u2081, t\u2081-t\u2080)\n    end\nend\n\nfunction HermiteExtrapolation(t\u2080::T, t\u2081::T) where {T}\n    HermiteExtrapolation{T}(t\u2080, t\u2081)\nend\n\n\nfunction GeometricBase.evaluate!(int::HermiteExtrapolation{TT}, x\u2080::AbstractArray{DT}, x\u2081::AbstractArray{DT}, x\u0307\u2080::AbstractArray{DT}, x\u0307\u2081::AbstractArray{DT}, t::TT, x::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(int.t\u2080, int.t\u2081, x\u2080, x\u2081, x\u0307\u2080, x\u0307\u2081, t, x)\nend\n\nfunction GeometricBase.evaluate!(int::HermiteExtrapolation{TT}, x\u2080::AbstractArray{DT}, x\u2081::AbstractArray{DT}, x\u0307\u2080::AbstractArray{DT}, x\u0307\u2081::AbstractArray{DT}, t::TT, x::AbstractArray{DT}, x\u0307::AbstractArray{DT}) where {DT,TT}\n    _hermite_extrapolation!(int.t\u2080, int.t\u2081, x\u2080, x\u2081, x\u0307\u2080, x\u0307\u2081, t, x, x\u0307)\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": "# ### m8.1t\n\nusing Pkg, DrWatson\n\n@quickactivate \"StatisticalRethinkingTuring\"\nusing Turing\nusing StatisticalRethinking\nTuring.setprogress!(false)\n\n@model ppl8_2(y) = begin\n\n    \u03c3 ~ FlatPos(0.0) # improper prior with probability one everywhere above 0.0\n    \u03b1 ~ Flat() # improper prior with pobability one everywhere\n\n    y .~ Normal(\u03b1, \u03c3)\nend\n\ny = [-1,1];\n\n# Sample\n\nm8_2t = ppl8_2(y)\nnchains = 4; sampler = NUTS(0.65); nsamples=2000\nchns8_2t = mapreduce(c -> sample(m8_2t, sampler, nsamples), chainscat, 1:nchains)\n\n# End of `08/m8.2t.jl`\n", "meta": {"hexsha": "6d32dda879e09a4b500a8e8906f47ac63340b55a", "size": 541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/08/m8.2t.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/08/m8.2t.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/08/m8.2t.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": 20.037037037, "max_line_length": 81, "alphanum_fraction": 0.7024029575, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7643846877860105}}
{"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\u00b1\u03b5)) / exp(l) == 1 - exp(\u00b1l*\u03b5) \u2248 \u2213l*\u03b5.\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])\u00f72]\nsol2p(sol) = [sol.u[i][j] for i in 1:length(sol.u), j in length(sol.u[1])\u00f72+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, \u0394t, 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,   \u0394t = $\u0394t    =====\")\nend\n\n# Solve a single pendulum\n#\nfunction singlependulum(k, integrator, \u0394t; 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=\u0394t)\n    @time local sol = solve(prob, integrator, dt=\u0394t)\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,   \u0394t = $\u0394t    =====\")\nend\n\n\n# Single pendulum\n\nk = rand()\nintegrator = VelocityVerlet()\n\u0394t = 0.1\nsinglependulum(k, integrator, \u0394t, 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\u0394t = 0.1\nsol = solve(prob, integrator, dt=\u0394t)\n@time sol = solve(prob, integrator, dt=\u0394t)\n\nsleep(0.1)\nplotsolenergy(H, integrator, \u0394t, 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\u0394t = 0.1\nfor integrator in SymplecticIntegrators\n    singlependulum(k, integrator, \u0394t)\nend\n\n\nk = 0.999\n\u0394t = 0.01\nfor integrator in SymplecticIntegrators[1:4]\n    singlependulum(k, integrator, \u0394t)\nend\n\n\nk = 0.999\n\u0394t = 0.001\nsinglependulum(k, SymplecticEuler(), \u0394t)\n\n\nk = 0.999\n\u0394t = 0.0001\nsinglependulum(k, SymplecticEuler(), \u0394t)\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,\u03bb = 1.5,\u03b3 = 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] + \u03b3 * 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,\u03bb = 1.5,\u03b3 = 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": "\ufeffusing 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, \u03b8::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 `\u03b8` in a unitform gravitational acceleration `g`.\n\"\"\"\nprojectile_displacement(v_0::Unitful.Velocity, \u03b8::Angle, t::Unitful.Time; g::Acceleration = g_n) =\n    [ v_0 * t * cos(\u03b8), v_0 * t * sin(\u03b8) - 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\"\u00b0\", t, g = g)[2]\n\n\"\"\"\n    projectile_velocity(v_0::Unitful.Velocity, \u03b8::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 `\u03b8` in a unitform gravitational acceleration `g`.\n\"\"\"\nprojectile_velocity(v_0::Unitful.Velocity, \u03b8::Angle, t::Unitful.Time; g::Acceleration = g_n) =\n    [ v_0 * cos(\u03b8), v_0 * sin(\u03b8) - 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\"\u00b0\", g, t)[2]\n\n\"\"\"\n    projectile_flight_time(v_0::Unitful.Velocity, \u03b8::Angle = 90u\"\u00b0\"; g::Acceleration = g_n)\n\t\nCompute total flight time for a projectile launched at angle `\u03b8` 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, \u03b8::Angle = 90u\"\u00b0\"; g::Acceleration = g_n) = 2v_0 * sin(\u03b8) / g |> u\"s\"\n\n\"\"\"\n    projectile_apex(v_0::Unitful.Velocity, \u03b8::Angle = 90u\"\u00b0\"; g::Acceleration = g_n)\n\t\nHorizontal and vertical displacement of a projectile launched at angle `\u03b8` with initial velocity `v_0` in a uniform gravitation acceleration `g` at the apex of its trajectory.\n\nDefault launch angle is 90\u00b0 for maximum height.\n\"\"\"\nprojectile_apex(v_0::Unitful.Velocity, \u03b8::Angle = 90u\"\u00b0\"; g::Acceleration = g_n) = [ v_0^2 * sin(2\u03b8) / 2g,  v_0^2 * sin(\u03b8)^2 / 2g ]\n\n\"\"\"\n    projectile_range(v_0::Unitful.Velocity, \u03b8::Angle = 45u\"\u00b0\"; g::Acceleration = g_n)\n\t\nCompute range of a projectile launched at angle `\u03b8` with initial velocity `v_0` in a uniform gravitation acceleration `g`.\n\nDefault launch angle is 45\u00b0 for maximum range.\n\"\"\"\nprojectile_range(v_0::Unitful.Velocity, \u03b8::Angle = 45u\"\u00b0\"; g::Acceleration = g_n) = (v_0^2 * sin(2\u03b8)) / g\n\n\"\"\"\n    projectile_range(v_0::Unitful.Velocity, y_0::Unitful.Length, \u03b8::Angle = 45u\"\u00b0\"; g::Acceleration = g_n)\n\t\nCompute range of a projectile launched from altitude `y_0` at angle `\u03b8` 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\u00b0 for maximum range.\n\"\"\"\nprojectile_range(v_0::Unitful.Velocity, y_0::Unitful.Length, \u03b8::Angle = 45u\"\u00b0\"; g::Acceleration = g_n) =\n\t(v_0 * cos(\u03b8) / g) * (v_0 * sin(\u03b8) + sqrt((v_0 * sin(\u03b8))^2 + 2g * y_0))\n\t\n\"\"\"\n    projectile_range_planetary(v_0::Unitful.Velocity, r_planet::Unitful.Length = 1u\"Rearth\", \u03b8::Angle = 45u\"\u00b0\"; g::Acceleration = g_n)\n\t\nCompute range of a projectile launched from altitude `y_0` at angle `\u03b8` 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, \u03b8::Angle = 45u\"\u00b0\", 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\u03b8) / g\n\tb = sqrt(1 - (2 - v_rat2) * v_rat2 * cos(\u03b8)^2)\n\t\n\treturn a / b |> u\"m\"\nend\n\nfunction projectile_peak_displacement_planetary(v_0::Unitful.Velocity, \u03b8::Angle = 45u\"\u00b0\", 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(\u03b8) / g\n\tb = 1 - v_rat2 + sqrt(1 - (2 - v_rat2) * v_rat2 * cos(\u03b8)^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\"\u00b0\", 45u\"\u00b0\" + (0.5acos(k) * 1u\"rad\" |> u\"\u00b0\") )\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\"\u00b0\"\n\tb = atan((v_0^2 - sqrt(det)) / (g * d)) * 1u\"rad\" |> u\"\u00b0\"\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\"\u00b0\"\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(\u03b8) = (1.0 - \u03b8[1])^2 + 100.0 * (\u03b8[2] - \u03b8[1]^2)^2\n\u03b8 = 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\u03b8s = zeros(100,2)\nfor i = 1:100\n    #global \u03b8 = optimize(rosenbrock, \u03b8, GradientDescent(), Optim.Options(iterations=1)).minimizer\n    global \u03b8 = optimize(rosenbrock, \u03b8, Newton(), Optim.Options(iterations=1)).minimizer\n    \u03b8s[i,:] = \u03b8'\n    display(scatter!(\u03b8s[1:i,1], \u03b8s[1:i,2], legend=false))\n    sleep(0.1)\nend\n\u03b8s\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 = \u221a(x^2 + y^2) # distance from z-axis\n\n   # 1st loop\n   z\u2081 = z + 0.5*distance\n   k = \u221a(4*r*a / (z\u2081^2 + (a + r)^2) )\n   K, E = ellipke(k)\n   Bz1 = \u03bc\u2080*I1 / (2\u03c0*\u221a(z\u2081^2+(a+r)^2)) * ((a^2-z\u2081^2-r^2)/(z\u2081^2+(r-a)^2)*E + K)\n   Br1 = \u03bc\u2080*z\u2081*I1/(2\u03c0*r*\u221a(z\u2081^2+(a+r)^2))*((z\u2081^2+r^2+a^2)/(z\u2081^2+(r-a)^2)*E - K)\n   Bx1 = Br1 * x / r\n   By1 = Br1 * y / r\n\n   # 2nd loop\n   z\u2082 = z - 0.5*distance\n   k = \u221a(4*r*a / (z\u2082^2 + (a + r)^2) )\n   K, E = ellipke(k)\n   Bz2 = \u03bc\u2080*I1 / (2\u03c0*\u221a(z\u2082^2+(a+r)^2)) * ((a^2-z\u2082^2-r^2)/(z\u2082^2+(r-a)^2)*E + K)\n   Br2 = \u03bc\u2080*z\u2082*I1/(2\u03c0*r*\u221a(z\u2082^2+(a+r)^2))*((z\u2082^2+r^2+a^2)/(z\u2082^2+(r-a)^2)*E - K)\n   Bx2 = Br2 * x / r\n   By2 = Br2 * y / r\n\n   # central loop\n   z\u2083 = z\n   k = \u221a(4*r*b / (z\u2083^2 + (b+r)^2) )\n   K, E = ellipke(k)\n   Bz3 = \u03bc\u2080*I2 / (2\u03c0*\u221a(z\u2083^2+(b+r)^2)) * ((b^2-z\u2083^2-r^2)/(z\u2083^2+(r-b)^2)*E + K)\n   Br3 = \u03bc\u2080*z\u2083*I2/(2\u03c0*r*\u221a(z\u2083^2+(b+r)^2))*((z\u2083^2+r^2+b^2)/(z\u2083^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      \u03b8 = \u03c0/16 + i*\u03c0/8 # angle between the i-th coil and the x-axis\n\n      if abs(sin(\u03b8)) > 0.01\n         r1_ = x/(cos(\u03b8)-sin(\u03b8)*tan(atan(y, x) - \u03b8)) - a - b\n         r1 = \u221a(r1_^2 + z^2)\n         z1 = ((b + a)*cos(\u03b8) + r1_*cos(\u03b8) - x) / sin(\u03b8)\n      else\n         r1_ = x - b - a\n         r1 = \u221a(r1_^2 + z^2)\n         z1 = y\n      end\n\n      k = \u221a(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_ = \u03bc\u2080*ICoils/(2\u03c0*\u221a(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_ = \u03bc\u2080*z1*ICoils/(2\u03c0*r1*\u221a(z1^2+(a+r1)^2))*((z1^2+r1^2+a^2)/(z1^2+(r1-a)^2)*E-K)\n      # normal coordinates\n      Bx1 = -sin(\u03b8)*Bz1_ + Br1_*r1_/r1*cos(\u03b8)\n      By1 = cos(\u03b8)*Bz1_ + sin(\u03b8)*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   \u03c3 = a/3 # parameter of the Gauss curve\n   \u03d5 = atan(y, x)\n   # distance to centre of plasma ring\n   distance = \u221a( z^2 + (x - (a + b)*cos(\u03d5))^2 + (y - (a + b)*sin(\u03d5))^2 )\n   I2_r_plasma = IPlasma * erf(distance/(\u03c3*\u221a2))\n\n   r = hypot(x, y)\n   k = \u221a(4r*(a+b)/(z^2+((a+b)+r)^2))\n   K, E = ellipke(k)\n   Bz_plasma = \u03bc\u2080*I2_r_plasma/(2\u03c0*\u221a(z^2+((a+b)+r)^2))*(((a+b)^2-z^2-r^2)/(z^2+(r-(a+b))^2)*E+K)\n   Br_plasma = \u03bc\u2080*z*I2_r_plasma/(2\u03c0*r*\u221a(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": "# Julia program to check if a number is a power of two.\n\nfunction power_of_two(n)\n    # 0 is not a power of 2\n    if(n != 0)\n        if((n & (n-1)) == false)\n            return true\n        end\n    end\n    return false\nend\n\n\nprint(\"Enter a number: \")\nn = readline()\nn = parse(Int, n)\nres = power_of_two(n)\nif(res)\n    print(\"The given number is a power of 2.\")\nelse\n    print(\"The given number is not a power of 2.\")\nend\n\n\n\"\"\"\nTime Complexity - O(1)\nSpace Complexity - O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\nEnter a number: 4\nThe given number is a power of 2.\n\nSAMPLE II\nEnter a number: 0\nThe given number is not a power of 2.\n\"\"\"\n", "meta": {"hexsha": "9f306297b0d3730b4f225854db3bf5478583c7e8", "size": 632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Bit--Manipulation/power_of_2.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/power_of_2.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/power_of_2.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": 16.2051282051, "max_line_length": 55, "alphanum_fraction": 0.625, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.7643606443381629}}
{"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\u2013256.\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 = \u221a2 )\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 == \u221a2\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\u2013256.\n# \"\"\"\n# type UCB2 <: BanditAlgorithmBase\n#     noOfArms::Int64\n#     noOfSteps::Int64\n#     lastPlayedArm::Int64\n#     \u03b1::Float64\n#\n#     cummReward::Vector{Float64}\n#     count::Vector{Int64}\n#\n#     function UCB2( noOfArms::Int, \u03b1::Float64 )\n#         new( noOfArms,\n#              0,\n#              0,\n#              \u03b1,\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\u2013256.\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\u201324.\n\"\"\"\n\ntype DUCB <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    \u03b3::Float64                      # Discouting factor\n    \u03be::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, \u03b3::Float64, \u03be::Float64 = 0.5 )\n        new( noOfArms,\n             0,\n             0,\n             \u03b3,\n             \u03be,\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.\u03b3                  # Discount for all arms\n    agent.discCumReward[agent.lastPlayedArm] += r   # Update reward to last played arm\n    # Update discounted count\n    agent.discCount *= agent.\u03b3\n    agent.discCount[agent.lastPlayedArm] += 1\n    # Update UCB indices\n    agent.indices   = agent.discCumReward./agent.discCount +\n                        2*sqrt.(agent.\u03be*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.\u03b3, agent.\u03be );\n    else\n        return @sprintf( \"Discounted-UCB(\u03b3 = %4.3f, \u03be = %4.3f)\", agent.\u03b3, agent.\u03be );\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\u201324.\n\"\"\"\n\ntype SWUCB <: BanditAlgorithmBase\n    noOfArms::Int64\n    noOfSteps::Int64\n    lastPlayedArm::Int64\n\n    \u03c4::Int64                        # Window Length\n    \u03be::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, \u03c4::Int64, \u03be::Float64 = 2.0 )\n        new( noOfArms,\n             0,\n             0,\n             \u03c4,\n             \u03be,\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.\u03c4\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.\u03c4 )\n\n    # Update UCB indices\n    agent.indices = agent.swCumRew./agent.swCount +\n                        sqrt.(agent.\u03be*log(min(agent.noOfSteps,agent.\u03c4))./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.\u03c4, agent.\u03be );\n    else\n        return @sprintf( \"SW-UCB(\u03c4 = %3.2f, \u03be = %3.2f)\", agent.\u03c4, agent.\u03be );\n    end\nend\n\n\n\"\"\"\n    UCB-V: Variance Aware UCB Implementation\n    Based on: Audibert, J. Y., Munos, R., & Szepesv\u00e1ri, C. (2009). Exploration-exploitation tradeoff using variance estimates in multi-armed bandits. Theoretical Computer Science, 410(19), 1876\u20131902. 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    \u03b6::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; \u03b6::Real = 1.0, c::Real = 1/3, b::Real = 1.0 )\n        new( noOfArms,\n             0,\n             0,\n             \u03b6,\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    \u03bc = 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-\u03bc)^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.\u03b6*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.\u03b6, agent.c, agent.b )\n    else\n        return @sprintf( \"UCB-V(\u03b6=%3.2f,c=%3.2f,b=%3.2f)\", agent.\u03b6, agent.c, agent.b )\n    end\nend\n\n\n\n\"\"\"\n    Bayes-UCB Implementation\n    Based on: Kaufmann, E., Capp\u00e9, O., & Garivier, A. (2012). On Bayesian upper confidence bounds for bandit problems. International Conference on Artificial Intelligence and Statistics, 592\u2013600.\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    \u03b10::Vector{Int64}\n    \u03b20::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.\u03b10[agent.lastPlayedArm],\n                                                agent.cummFailure[agent.lastPlayedArm]+agent.\u03b20[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; \u03f5 = 1e-5 )\n    lQ = sa/na\n    uQ = min( 1, sa/na+\u221a(log(t)/na/2))      # Applying Pinkser's Inequality\n    q\u0304 = 1.0\n    q  = (lQ+uQ)/2\n    while abs(q\u0304-q) > \u03f5\n        q\u0304  = 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    \u03b3::Float64          # Expoloration parameter\n\n    # Internal\n    \u03c4::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, \u03b3::Float64 )\n        new(\n            noOfArms,\n            0,\n            0,\n            w,\n            b,\n            \u03b3,\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.\u03c4) % floor(agent.noOfArms/agent.\u03b3)\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.\u03c4 = 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.\u03c4             = 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.\u03b3 )\n    else\n        return @sprintf( \"M-UCB( w = %d, b = %4.3f, \u03b3 = %4.3f )\", agent.w, agent.b, agent.\u03b3 )\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": "using SymEngineExtras, SymEngine\nusing Base.Test\n\nx,y,z = symbols(\"x y z\")\n\n## logsimp\n@test logsimp( 2log(x)) == log(x^2)\n@test logsimp(log(x) + log(y)) == log(x*y)\n@test logsimp(log(x) - log(y)) == log(x/y)\n@test logsimp(log(x) + log(2x) - log(y) + x) == x + log(2*x^2/y)\n@test logsimp(3 * log(x)) == log(x^3)\n@test logsimp(y * log(x)) == log(x^y)\n\n## expand_log\n@test expand_log(log(x*y)) == log(x) + log(y)\n@test expand_log(log(x/y)) == log(x) - log(y)\n@test expand_log(x + log(2*x^2)) == x + log(Basic(2)) + 2*log(x)\n@test expand_log(log(x^3)) == 3 * log(x)\n@test expand_log(log(x^y)) == y * log(x)\n\n## powsimp\n@test powsimp(x^2 * x^3) == x^5\n@test powsimp(x^2 * x^y) == x^(2+y)\n@test powsimp(x + log(x^2 * x^y)) == x + log(x^(2 + y))\n@test powsimp(x^2*y^2*2) == 2*(x*y)^2\n@test powsimp(x^3 * y^3) == (x*y)^3 # broken, as it gets put together, taken apart\n\n## powdenest\n@test powdenest(2^(3*x)) == 8^x\n\n\n## expand_power_exp\n@test expand_power_exp(x^(y+z)) == x^y * x^z\n\n\n## expand_power_base\n@test expand_power_base((x*y)^z) == x^z * y^z\n\n\n## rewrite_trig\n@test rewrite_trig(sec(x)) == 1/cos(x)\n@test rewrite_trig(sech(x)) == 1/cosh(x)\n@test rewrite_trig(cos(cot(x))) == cos(1/tan(x))\n\n## expand_trig\n@test expand_trig(sin(x + y)) == sin(x)*cos(y) + sin(y) * cos(x)\n@test expand_trig(sin(2x)) == 2*sin(x) * cos(x)\n@test expand_trig(sin(x/2)^2) == (1-cos(x))/2\n\n@test expand_trig(cos(x + y)) == cos(x)*cos(y) - sin(y) * sin(x)\n@test expand_trig(x*y + cos(x + y)) == x*y + cos(x)*cos(y) - sin(y) * sin(x)\n@test expand_trig(cos(2x)) == cos(x)^2 - sin(x)^2\n@test expand_trig(cos(x/2)^2) == (1+cos(x))/2\n\n@test expand_trig(tan(x + y)) == (tan(x) + tan(y)) / (1 - tan(x)*tan(y))\n@test expand_trig(tan(2x)) == 2*tan(x) / (1 - tan(x)^2)\n@test expand_trig(tan(x/2)) == sin(x) / (1 + cos(x))\n\n@test expand_trig(sinh(x + y)) == sinh(x)*cosh(y) + sinh(y) * cosh(x)\n@test expand_trig(sinh(2x)) == 2 * sinh(x) * cosh(x)\n@test expand_trig(sinh(x/2)^2) == (cosh(x) - 1)/2\n\n\n## trigsimp\n@test trigsimp(2*sin(x)*cos(x)) == sin(2x)\n@test trigsimp(2*sin(sin(x))*cos(sin(x)) * cos(x) * sin(x) * tan(x)) == (1//2)*sin(2*x)*sin(2*sin(x))*tan(x)\nex = sin(sin(sin(2x)))\n@test trigsimp(expand_trig(ex)) == ex\n\n@test trigsimp(2*sinh(exp(x))*cosh(exp(x))) == sinh(2exp(x))\n\nex = sin(x)*cos(y) + sin(y)*cos(x)\n@test trigsimp(ex) == sin(x + y)\n\n\nex = sin(x)*cos(y) - sin(y)*cos(x)\n@test trigsimp(ex) == sin(x - y)\n\n\nex = sin(x)*cos(y) + cos(x)*sin(y)\n@test trigsimp(ex) == sin(x + y)\n\n\nex = cos(x)*cos(y) - sin(x)*sin(y)\n@test trigsimp(ex) == cos(x + y)\n\n\nex = cos(x)*cos(y) + sin(x)*sin(y)\n@test trigsimp(ex) == cos(x - y)\n\nex = sin(cos(x) + cos(y))\n@test trigsimp(expand_trig(ex)) == ex\n\n", "meta": {"hexsha": "a05ed15edd9a32e38c93a1e5b579b732f552a3c7", "size": 2665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-simplify.jl", "max_stars_repo_name": "jverzani/SymEngineExtras.jl", "max_stars_repo_head_hexsha": "d77ea9b7db93efdf77b165292b0e822c0b7a775e", "max_stars_repo_licenses": ["MIT"], "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-simplify.jl", "max_issues_repo_name": "jverzani/SymEngineExtras.jl", "max_issues_repo_head_hexsha": "d77ea9b7db93efdf77b165292b0e822c0b7a775e", "max_issues_repo_licenses": ["MIT"], "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-simplify.jl", "max_forks_repo_name": "jverzani/SymEngineExtras.jl", "max_forks_repo_head_hexsha": "d77ea9b7db93efdf77b165292b0e822c0b7a775e", "max_forks_repo_licenses": ["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.3510638298, "max_line_length": 108, "alphanum_fraction": 0.5759849906, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7643544983192253}}
{"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{\u2102}\n  d::Int\n  dual::Bool\nend\nComplexSpace(d::Int) = ComplexSpace(d, false)\n^(::Type{\u2102},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 ? \"\u2102^$(V.d)*\" : \"\u2102^$(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": "#=\nLet's load some packages\n=#\n\nusing OneHot, CairoMakie, Random, BenchmarkTools\nnothing #hide\n\n#=\nSetup the size of the examples we'll look at\n=#\n\nq = 20\nN = 200\nM = 400\nnothing #hide\n\n#=\nBenchmark normal matrix multiply.\nThis doesn't exploit OneHot structure of `X`.\n=#\n\n@benchmark A * X setup=(A=randn(M,q); X=Array(OneHotArray(rand(1:q, N), q)))\n\n#=\nThis package implements efficient matrix multiply by a `OneHotArray`.\n=#\n\n@benchmark A * X setup=(A=randn(M,q); X=OneHotArray(rand(1:q, N), q))\n\n#=\nThat's about 20x faster!\nWe can also check that these two codes are computing the same thing.\n=#\n\nA = randn(M, q)\nX = OneHotArray(rand(1:q, N), q)\nA * X \u2248 A * Array(X)\n", "meta": {"hexsha": "69280fe7b08783e2646b0d4daac58bc79d4252b3", "size": 670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/literate/matmul.jl", "max_stars_repo_name": "cossio/OneHot.jl", "max_stars_repo_head_hexsha": "cc392e053ffbbeec34543e29bfd8506d983308cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-11T12:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T02:00:01.000Z", "max_issues_repo_path": "docs/src/literate/matmul.jl", "max_issues_repo_name": "cossio/OneHot.jl", "max_issues_repo_head_hexsha": "cc392e053ffbbeec34543e29bfd8506d983308cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-03-03T15:55:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T09:29:14.000Z", "max_forks_repo_path": "docs/src/literate/matmul.jl", "max_forks_repo_name": "cossio/OneHot.jl", "max_forks_repo_head_hexsha": "cc392e053ffbbeec34543e29bfd8506d983308cc", "max_forks_repo_licenses": ["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": 76, "alphanum_fraction": 0.6791044776, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7643544941945346}}
{"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(\u03b1*I,B,C)  or  X = sylvc(\u03b1,B,C)\n\nSolve the matrix equation `X(\u03b1I+B)  = C`.\n\n    X = sylvc(A,\u03b2*I,C)  or  X = sylvc(A,\u03b2,C)\n\nSolve the matrix equation `(A+\u03b2I)X = C`.\n\n    X = sylvc(\u03b1*I,\u03b2*I,C)  or  sylvc(\u03b1,\u03b2,C)\n\nSolve the matrix equation `(\u03b1+\u03b2)X = C`.\n\n    x = sylvc(\u03b1,\u03b2,\u03b3)\n\nSolve the equation `(\u03b1+\u03b2)x = \u03b3`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> X = sylvc(A, B, C)\n2\u00d72 Array{Float64,2}:\n -4.46667   1.93333\n  3.73333  -1.8\n\njulia> A*X + X*B - C\n2\u00d72 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\u2013826, 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+\u03b1) = C or (\u03b1+\u03b2)X = C\nsylvc(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*I+B)\n# solve (A+\u03b2)X = C\nsylvc(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A+B*I)\\C\n# solve (\u03b1+\u03b2)X = C\nsylvc(A::Union{Real,Complex},B::Union{Real,Complex},C::AbstractMatrix) = A+B == 0 ? throw(SingularException(1)) : C/(A+B)\n# solve (\u03b1+\u03b2)x = \u03b3\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(\u03b1*I,B,C)  or  X = sylvd(\u03b1,B,C)\n\nSolve the matrix equation `X(\u03b1B+I)  = C`.\n\n    X = sylvd(A,\u03b2*I,C)   or  X = sylvd(A,\u03b2,C)\n\nSolve the matrix equation `(\u03b2A+I)X = C`.\n\n    X = sylvd(\u03b1*I,\u03b2*I,C)  or  X = sylvd(\u03b1,\u03b2,C)\n\nSolve the matrix equation `(\u03b1\u03b2+1)X = C`.\n\n    x = sylvd(\u03b1,\u03b2,\u03b3)\n\nSolve the equation `(\u03b1\u03b2+1)x = \u03b3`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> X = sylvd(A, B, C)\n2\u00d72 Array{Float64,2}:\n -2.46667  -2.73333\n  2.4       1.86667\n\njulia> A*X*B + X - C\n2\u00d72 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\u2013826, 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(\u03b1B+I) = C or X(\u03b1\u03b2+1) = C\nsylvd(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*B+I)\n# solve (A\u03b2+I)X = C\nsylvd(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A*B+I)\\C\n# solve (\u03b1\u03b2+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 (\u03b1\u03b2+1)x = \u03b3\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-\u03bbC` and `D+\u03bbB` 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,\u03b3*I,E)  or  X = gsylv(A,B,\u03b3,E)\n\nSolve the generalized Sylvester matrix equation `AXB +\u03b3X = E`.\n\n    X = gsylv(A,B,\u03b3*I,D,E)  or  X = gsylv(A,B,\u03b3,D,E)\n\nSolve the generalized Sylvester matrix equation `AXB +\u03b3XD = E`.\n\n    X = gsylv(A,B,C,\u03b4*I,E)  or  X = gsylv(A,B,C,\u03b4,E)\n\nSolve the generalized Sylvester matrix equation `AXB +CX\u03b4 = E`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2\u00d72 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2\u00d72 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X = gsylv(A, B, C, D, E)\n2\u00d72 Array{Float64,2}:\n -0.52094   -0.0275792\n -0.168539   0.314607\n\njulia> A*X*B + C*X*D - E\n2\u00d72 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+\u03b3X = 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+\u03b3X\u03b4 = 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+\u03b3XD = 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\u03b4 = 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-\u03bbD` and `-B+\u03bbE` must be regular and must not have common eigenvalues.\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2\u00d72 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2\u00d72 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2\u00d72 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\u00d72 Array{Float64,2}:\n  1.388  -1.388\n -0.892   0.892\n\njulia> Y\n2\u00d72 Array{Float64,2}:\n -1.788  0.192\n  0.236  0.176\n\njulia> A*X + Y*B - C\n2\u00d72 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\u00d72 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-\u03bbD` and `-B+\u03bbE` must be regular and must not have common eigenvalues.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2\u00d72 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2\u00d72 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2\u00d72 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\u00d72 Array{Float64,2}:\n  2.472  -1.648\n -1.848   1.232\n\njulia> Y\n2\u00d72 Array{Float64,2}:\n -0.496  -0.336\n  0.264   0.824\n\njulia> A*X + D*Y - C\n2\u00d72 Array{Float64,2}:\n  4.44089e-16  0.0\n -3.55271e-15  1.55431e-15\n\njulia> X*B + Y*E - F\n2\u00d72 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\u2013826, 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) \u03b1 and B has eigenvalues(s) \u03b2 such that \u03b1+\u03b2 = 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) \u03b1 and B has eigenvalues(s) \u03b2 such that \u03b1\u03b2 = -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) \u03b1 and B has eingenvalu(s) \u03b2 such that \u03b1\u03b2 = -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\u2013826, 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\u2013826, 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-\u03bbC` and `D+\u03bbB` 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 \u2013 CXD = E and\n       (YA \u2013 DZ, YC\u2013 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\u2013826, 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-\u03bbC` and `D+\u03bbB` 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) \u03b1 and B has eingenvalu(s) \u03b2 such that \u03b1\u03b2 = -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 \u2013 CXD = E and\n       (YA \u2013 DZ, YC\u2013 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\u2013826, 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-\u03bbC and D+\u03bbB 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-\u03bbC and D'+\u03bbB' 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'-\u03bbC' and D+\u03bbB 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'-\u03bbC' and D'+\u03bbB' 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-\u03bbD` and `-B+\u03bbE` 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-\u03bbD` and `-B+\u03bbE` 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 \u0394t = 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, \u03bd=noise_intensity)\n        B_out[1] = +\u03bd*q[2]\n        B_out[2] = -\u03bd*q[1]\n    end\n\n    function kubo_oscillator_sde_B(t, q, B_out::AbstractMatrix, col=1, \u03bd=noise_intensity)\n        B_out[1,col] = +\u03bd*q[2]\n        B_out[2,col] = -\u03bd*q[1]\n    end\n\n\n    function kubo_oscillator_sde_1(q\u2080=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\u2080)\n    end\n\n    function kubo_oscillator_sde_2(q\u2080=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\u2080)\n    end\n\n    function kubo_oscillator_sde_3(q\u2080=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\u2080)\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, \u03bd=noise_intensity)\n        B_out[1,1] = +\u03bd*p[1]\n    end\n\n    function kubo_oscillator_psde_G(t, q, p, G_out, \u03bd=noise_intensity)\n        G_out[1,1] = -\u03bd*q[1]\n    end\n\n\n    function kubo_oscillator_psde_1(q\u2080=q_init_C, p\u2080=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\u2080, p\u2080)\n    end\n\n    function kubo_oscillator_psde_2(q\u2080=q_init_D, p\u2080=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\u2080, p\u2080)\n    end\n\n    function kubo_oscillator_psde_3(q\u2080=q_init_C, p\u2080=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\u2080, p\u2080)\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, \u03bd=noise_intensity)\n        B_out[1,1] = +\u03bd*p[1]\n    end\n\n    function kubo_oscillator_spsde_G1(t, q, p, G_out, \u03bd=noise_intensity)\n        G_out[1,1] = -\u03bd*q[1]\n    end\n\n    function kubo_oscillator_spsde_G2(t, q, p, G_out, \u03bd=noise_intensity)\n        G_out[1,1] = 0\n    end\n\n\n    function kubo_oscillator_spsde_1(q\u2080=q_init_C, p\u2080=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\u2080, p\u2080)\n    end\n\n    function kubo_oscillator_spsde_2(q\u2080=q_init_D, p\u2080=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\u2080, p\u2080)\n    end\n\n    function kubo_oscillator_spsde_3(q\u2080=q_init_C, p\u2080=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\u2080, p\u2080)\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},\u03bb::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* `\u03bb::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},\u03bb::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 \u03bb != 0\n    proxL21!(z, \u03bb, 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}, \u03bb::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)]-\u03bb)/groupNorm[mod1(i,sliceLength)],0 ) for i=1:length(x)]\nend\n\n\"\"\"\n    normL21(x::Vector{T}, \u03bb::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}, \u03bb::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 \u03bb*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 \u2260 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 \u03b1:\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    \u03b1::Float64;\n    norm::Float64;\n    \u03f5::Float64\n\n    @doc raw\"\"\"\n        CauchyWavelet(\u03b1::Real; \u03f5::Real=1e-2)\n\n    Constructs a new Cauchy wavelet, whith the given \u03b1 specifying the time-frequency resolution.\n    The optional keyword arguent \u03f5 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 \u03f5 will increase the precision of the wavelet transform on the cost of longer kernels\n    leading to slower convolutions.\n    \"\"\"\n    function CauchyWavelet(\u03b1::Real; \u03f5::Real=1e-2)\n        norm = exp(-2*log(2\u03c0) - logabsgamma(2\u03b1+1)[1]/2 + logabsgamma(\u03b1+1)[1]\n          + (2\u03b1+2)*log(2)/2 + log(\u03b1));\n        new(\u03b1, norm, \u03f5);\n    end\nend\n\nfunction eval_analysis(wav::CauchyWavelet, t::Float64)\n    (1 - 2im*\u03c0*t/wav.\u03b1)^(-1-wav.\u03b1);\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.\u03b1*log(a) + logabsgamma(2*wav.\u03b1-1)[1] - (1+2*wav.\u03b1)*log(2\u03c0);\n    exp(c) * (1+a-2im*\u03c0*b/wav.\u03b1)^(-1-2*wav.\u03b1);\nend\n\nfunction cutoff_time(wav::CauchyWavelet)\n    wav.\u03b1*sqrt(wav.\u03f5^(-2/(wav.\u03b1+1))-1)/(2\u03c0);\nend;\n\nfunction cutoff_freq(wav::CauchyWavelet)\n    1 + 1/( wav.\u03b1^2 * (wav.\u03f5^(-2 / (wav.\u03b1 + 1)) - 1) / ((2\u03c0)^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, \u03b1::Real, p1::Real, \u03b2::Real)\n    z_1_\u03b1   = Distributions.quantile(Distributions.Normal(), 1 - \u03b1)\n    z_1_\u03b2   = Distributions.quantile(Distributions.Normal(), 1 - \u03b2)\n    napprox = p1*(1 - p1)*( (z_1_\u03b1 + z_1_\u03b2) / (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": "using NumericalAnalysis: Polynomial\nusing Test\n\nx = [1.0, 1.3, 1.6, 1.9, 2.2]\ny = [0.7651977, 0.6200860, 0.4554022, 0.2818186, 0.1103623]\n\nPolynomial.NCSpline([0,1,2,3], [1, exp(1), exp(2), exp(3)])\nPolynomial.CCSpline([0,1,2,3], [1, exp(1), exp(2), exp(3)],[1, exp(3)])\n@testset \"Polynomial test\" begin\n    @test abs(Polynomial.Lagrange(x,y)(1.5) - 0.5118199)<=0.0000001\n    @test abs(Polynomial.NDDF(x,y)(1.5) - 0.5118199)<=0.0000001\n    @test abs(abs(Polynomial.Neville(x,y,1.5) - 0.5118199)<=0.0000001)\nend\n", "meta": {"hexsha": "04fc63dbb82ccfaf6ba8fb879054e8f6f38529ce", "size": 511, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Polynomial_test.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": "test/Polynomial_test.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": "test/Polynomial_test.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": 36.5, "max_line_length": 71, "alphanum_fraction": 0.6457925636, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7642709966832996}}
{"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# Spacetime Discretization methods in Julia\n# Soham 01-2018\n#--------------------------------------------------------------------\n\nfunction testcoordtrans(N::Int, M::Int)\n    xp = chebgrid(N)\n    xp2xg1 = Float64[coordtransL2G(M, 1, chebx(i, N)) for i in 1:N+1]\n    xp2xg2 = Float64[coordtransL2G(M, 2, chebx(i, N)) for i in 1:N+1]\n    xg2xp  = Float64[coordtransG2L(M, 2, xg) for xg in xp2xg2]\n    (xp2xg1[end] == xp2xg2[1]) && (xg2xp \u2248 xp)\nend\n\nfunction testshapeH2L2H(a4N::Array{Float64,4}, Nx::Int, Ny::Int)::Bool\n    shapeL2H(shapeH2L(a4N), Nx-1, Ny-1) == a4N\nend\n\nfunction testshapeH2L2H(b2N::Array{Float64,2}, Nx::Int, Ny::Int)::Bool\n    shapeL2H(shapeH2L(b2N), Nx-1, Ny-1) == b2N\nend\n\nfunction testchebint(Nx::Int, Ny::Int)::Float64\n    X  = chebgrid(Nx)\n    Y  = chebgrid(Ny)\n    B  = Float64[x^2 - y^3 + x^4*y^2 for x in X, y in Y]\n    wx = chebweights(Nx)\n    wy = chebweights(Ny)\n    numint = wx'*B*wy\n    return abs.(numint - 8/5)\nend\n\nfunction testL1norm(Nx::Int, Ny::Int)::Float64\n    X = chebgrid(Nx)\n    Y = chebgrid(Ny)\n    A = Float64[x^2 - y^3 for x in X, y in Y]\n    B = Float64[x^2 - y^3 + x^4*y^2 for x in X, y in Y]\n    errorL1 = L1norm(B, A, chebweights(Nx), chebweights(Ny))\n    exactL1 = 4/15 \n    return abs(errorL1 - exactL1)\nend\n\nfunction testL2norm(Nx::Int, Ny::Int)::Float64\n    X = chebgrid(Nx)\n    Y = chebgrid(Ny)\n    A = Float64[x^2 - y^3 for x in X, y in Y]\n    B = Float64[x^2 - y^3 + x^4*y^2 for x in X, y in Y]\n    errorL2 = L2norm(B, A, chebweights(Nx), chebweights(Ny))\n    exactL2 = 2/sqrt(45)\n    return abs(errorL2 - exactL2)\nend\n\nfunction testarray2dict2array(Nx, Ny, M)::Bool\n    sPatch = rand((Nx+1)*M, (Ny+1)*M)\n    return dict2array(array2dict(sPatch, Nx, Ny, M)) == sPatch\nend\n\n\n@test coordtransL2G(2, 1, -1.0) \u2248 0.0 \n@test coordtransL2G(2, 2,  1.0)  \u2248 0.0\n@test testcoordtrans(8,4) == true\n@test jacobian(12) == 1/12\n@test testshapeH2L2H(randn(4,12,4,12), 4, 12) == true\n@test testshapeH2L2H(randn(6,10), 6, 10) == true\n@test testchebint(12,14)  < 1e-14\n@test testL1norm(14, 11)  < 1e-14\n@test testL2norm(11, 14)  < 1e-14\n@test testarray2dict2array(4,5,3) == true\n", "meta": {"hexsha": "2a8541144eb1580adefdc77bc524d61bc7afe5ae", "size": 2186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/UtilitiesTest.jl", "max_stars_repo_name": "mukherjeesoham/ScalarWave.jl", "max_stars_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_stars_repo_licenses": ["MIT"], "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/UtilitiesTest.jl", "max_issues_repo_name": "mukherjeesoham/ScalarWave.jl", "max_issues_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_issues_repo_licenses": ["MIT"], "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/UtilitiesTest.jl", "max_forks_repo_name": "mukherjeesoham/ScalarWave.jl", "max_forks_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_forks_repo_licenses": ["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.1470588235, "max_line_length": 70, "alphanum_fraction": 0.5873741995, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7642272621091822}}
{"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": "### A Pluto.jl notebook ###\n# v0.14.4\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 dd4498f1-53c4-48e7-b651-70d48ae91379\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 ac129262-c0a8-47d2-af1a-1e1268096451\nbegin\n\t@quickactivate \"NumericalMethodsforEngineers\"\n\tusing Symbolics, SymbolicUtils, Latexify\n\tusing NumericalMethodsforEngineers, Test\nend\n\n# \u2554\u2550\u2561 33c7c64a-7a2c-4beb-9150-74f6c8444f60\nbegin\n\t@variables t \u03b1 \u03c3(..) \u03b2[1:2]\nend;\n\n# \u2554\u2550\u2561 39a8c494-5608-470a-89f6-9f4a68a9a527\n@variables x y;\n\n# \u2554\u2550\u2561 d38b1175-04c2-4f15-a100-ec7cda34c1de\nbegin\n\t@variables b[1:3]\n\t@variables w(..) x1(t) y z(t, \u03b1, x)\n\tb = [2, 5, 9]\nend;\n\n# \u2554\u2550\u2561 b70e72aa-32b9-4ae7-8b5f-83a770e52ac7\nbegin\n\tz1 = x^2 + y\n\tL(z1)\nend\n\n# \u2554\u2550\u2561 2d01cb71-28b8-4c40-804b-68faf4a19890\nbegin\n\texpr = \u03b2[1]* x + y^\u03b1 + \u03c3(3) * (z1 - t) - \u03b2[2] * w(t - 1)\n\tL(expr)\nend\n\n# \u2554\u2550\u2561 fb931ec7-1704-4490-a82a-555a644e1bbc\n@variables A[1:3, 1:3] B[1:3, 1:3];\n\n# \u2554\u2550\u2561 f0c84794-6ecc-49ff-a769-e163ef8c44dc\nx ~ y\n\n# \u2554\u2550\u2561 90cd94e1-602b-49af-9913-bfbcd134f520\nx - y ~ 0\n\n# \u2554\u2550\u2561 28c312b7-b4a9-4d0d-8988-8ef8a16cb786\nA .~ B\n\n# \u2554\u2550\u2561 076d6d44-a552-458c-b4ce-1351090f5353\nA .~ 3x\n\n# \u2554\u2550\u2561 83feb017-91d9-4363-811b-9c2be8f650a2\nA .~ [1 2 3;]' * x\n\n# \u2554\u2550\u2561 2202ac58-f7c6-49bf-beee-c32737a83b89\nA .~ [1, 2, 3] * x\n\n# \u2554\u2550\u2561 7659d23b-58fc-4528-a42f-7a818b364958\nL(A[3,2])\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550dd4498f1-53c4-48e7-b651-70d48ae91379\n# \u2560\u2550ac129262-c0a8-47d2-af1a-1e1268096451\n# \u2560\u2550d38b1175-04c2-4f15-a100-ec7cda34c1de\n# \u2560\u2550b70e72aa-32b9-4ae7-8b5f-83a770e52ac7\n# \u2560\u25502d01cb71-28b8-4c40-804b-68faf4a19890\n# \u2560\u255033c7c64a-7a2c-4beb-9150-74f6c8444f60\n# \u2560\u255039a8c494-5608-470a-89f6-9f4a68a9a527\n# \u2560\u2550fb931ec7-1704-4490-a82a-555a644e1bbc\n# \u2560\u2550f0c84794-6ecc-49ff-a769-e163ef8c44dc\n# \u2560\u255090cd94e1-602b-49af-9913-bfbcd134f520\n# \u2560\u255028c312b7-b4a9-4d0d-8988-8ef8a16cb786\n# \u2560\u2550076d6d44-a552-458c-b4ce-1351090f5353\n# \u2560\u255083feb017-91d9-4363-811b-9c2be8f650a2\n# \u2560\u25502202ac58-f7c6-49bf-beee-c32737a83b89\n# \u2560\u25507659d23b-58fc-4528-a42f-7a818b364958\n", "meta": {"hexsha": "32039ebae09bf4022379a18eebfbdb94ef78f7cc", "size": 1893, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/intros-symbolics/example_02.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/intros-symbolics/example_02.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/intros-symbolics/example_02.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.5357142857, "max_line_length": 57, "alphanum_fraction": 0.7015319599, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7642272569836543}}
{"text": "# Euler's Totient function, \u03c6(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, \u03c6(9)=6.\n# \n# n   Relatively Prime  \u03c6(n)   n/\u03c6(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 / \u03c6(n) for n \u2264 10.\n#\n# Find the value of n \u2264 1,000,000 for which n / \u03c6(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 / \u03c6(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": "\"\"\"\n\tmask_elements(img, threshold, connectivity)\nRemove every element that is below the `threshold` and\nadjacent to more than the `connectivity` amount of other \nelements similarly below the threshold. Returns a mask where \nall elements are 1 for elements that should be kept based on\n`threshold` and `connectivity` criteria.\n\n# Arguments\n- img: array which will be used to determine mask\n- threshold: cutoff value for elements that should be \n    removed\n- connectivity: minimum number of adjacent elements that are \n    required to remove an element\n\"\"\"\nfunction mask_elements(img, threshold, connectivity)\n    mask = img .< threshold\n    label = Images.label_components(mask)\n    n = length(unique(label))\n    indices = []\n    for lbl in 0:(n - 1)\n        lbl_mask = map(x -> x == lbl, label)\n        num = count(lbl_mask)\n        if num < connectivity\n            rmv_indices = findall(x -> x == lbl, label)\n            push!(indices, rmv_indices)\n        end\n    end\n    for i in 1:length(indices)\n        idx = indices[i]\n        mask[idx] .= 0\n    end\n    return iszero.(mask)\nend\n", "meta": {"hexsha": "0b979d274635952becf647e332b1290df1e5fb34", "size": 1088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "Dale-Black/CalciumScoring.jl", "max_stars_repo_head_hexsha": "107a3ef90330ff3fe9e637fc47cf276a42ff64a8", "max_stars_repo_licenses": ["MIT"], "max_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": "Dale-Black/CalciumScoring.jl", "max_issues_repo_head_hexsha": "107a3ef90330ff3fe9e637fc47cf276a42ff64a8", "max_issues_repo_licenses": ["MIT"], "max_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": "Dale-Black/CalciumScoring.jl", "max_forks_repo_head_hexsha": "107a3ef90330ff3fe9e637fc47cf276a42ff64a8", "max_forks_repo_licenses": ["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.0857142857, "max_line_length": 61, "alphanum_fraction": 0.6709558824, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7642272546860686}}
{"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). \u201cA threshold selection method from gray-level histograms\u201d. *IEEE Trans. Sys., Man., Cyber.* 9 (1): 62\u201366. [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": "module SimpleDrawing\nusing Plots, LinearAlgebra\n\nexport newdraw, draw_circle, draw_arc, draw_segment, draw_point, draw_vector\nexport draw_rectangle, 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, ticks = false)\nend\n\nfunction draw() end\n\n\"\"\"\n    draw_circle(x,y,r) \n    \nDraw a circle centered\nat `(x,y)` with radius `r`.\n\nAlso: `draw_circle(z,r)` where `z` is complex.\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...) = draw_circle(real(z), imag(z), r; opts...)\n\n\"\"\"\n    draw_circle(a,b,c)\n\nDraw 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\nexport draw_disc\n\n\"\"\"\n    draw_disc(x,y,r)\n\nDraw a disc centered at `(x,y)` and with radius `r`. May also be invoked as:\n* `draw_disc(z,r)` where `z` is complex.\n* `draw_disc(a,b,c)` where `a,b,c` are complex which gives a disc passing through `a`, `b`, and `c`.\n\nFor example: `draw_disc(0,1,3; color=:yellow, linecolor=:red)`\n\"\"\"\nfunction draw_disc(x::Real, y::Real, r::Real; opts...)\n    draw_circle(x, y, r, seriestype = [:shape], fillalpha = 1; opts...)\nend\n\nfunction draw_disc(z::Complex, r::Real; opts...)\n    draw_disc(real(z), imag(z), r; opts...)\nend\n\nfunction draw_disc(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_disc(x, y, r; opts...)\nend\n\n\n\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\u03c0)\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\n    plot!()\nend\n\n\"\"\"\n`draw_rectangle(x,y,xx,yy)` draws a rectangle with opposite corners\n`(x,y)` and `(xx,yy)`.  May also be called with complex arguments\n`draw_rectangle(w,z)`.\n\"\"\"\nfunction draw_rectangle(x::Real, y::Real, xx::Real, yy::Real; opts...)\n    xlist = [x, xx, xx, x, x]\n    ylist = [y, y, yy, yy, y]\n    plot!(xlist, ylist; opts...)\nend\n\nfunction draw_rectangle(w::Complex, z::Complex; opts...)\n    draw_rectangle(real(w), imag(w), real(z), imag(z); opts...)\nend\n\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, ticks = 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\n\"\"\"\n    resize_gr_window(wide=800, tall=600)\n\nChange the size of the `gr` drawing window. This is particularly \nuseful in VS code.\n\"\"\"\nfunction resize_gr_window(wide::Int = 800, tall::Int = 600)\n    gr(size = (wide, tall))\nend\nexport resize_gr_window\n\n\n\ninclude(\"cubic.jl\")\ninclude(\"curve.jl\")\ninclude(\"my_spy.jl\")\ninclude(\"axes.jl\")\nend\n", "meta": {"hexsha": "48737b718b95d0c08bb376a86215a1bea84b3eee", "size": 6383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SimpleDrawing.jl", "max_stars_repo_name": "scheinerman/SimpleDrawing.jl", "max_stars_repo_head_hexsha": "2d446d715667170e94f81cd0ab87089b7d87fd0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-24T10:11:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T00:58:19.000Z", "max_issues_repo_path": "src/SimpleDrawing.jl", "max_issues_repo_name": "scheinerman/SimpleDrawing.jl", "max_issues_repo_head_hexsha": "2d446d715667170e94f81cd0ab87089b7d87fd0e", "max_issues_repo_licenses": ["MIT"], "max_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": "scheinerman/SimpleDrawing.jl", "max_forks_repo_head_hexsha": "2d446d715667170e94f81cd0ab87089b7d87fd0e", "max_forks_repo_licenses": ["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.031372549, "max_line_length": 100, "alphanum_fraction": 0.6188312706, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7642167942632936}}
{"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": "@testset \"Fitting\" begin\n  wl = geostatsimage(\"WalkerLake\")\n  TI = asarray(wl, :Z)[1:20,1:20]\n  d = georef((z=TI,))\n  g = EmpiricalVariogram(d, :z, maxlag=15.)\n\n  # all fits lead to similar sill\n  \u03b3\u2081 = fit(GaussianVariogram, g)\n  \u03b3\u2082 = fit(SphericalVariogram, g)\n  \u03b3\u2083 = fit(ExponentialVariogram, g)\n  \u03b3\u2084 = fit(MaternVariogram, g)\n  @test isapprox(sill(\u03b3\u2081), 0.054, atol=1e-3)\n  @test isapprox(sill(\u03b3\u2082), 0.054, atol=1e-3)\n  @test isapprox(sill(\u03b3\u2083), 0.058, atol=1e-3)\n  @test isapprox(sill(\u03b3\u2084), 0.057, atol=1e-3)\n\n  # best fit is a Gaussian variogram\n  \u03b3 = fit(Variogram, g)\n  @test \u03b3 isa GaussianVariogram\n  @test isapprox(sill(\u03b3), 0.054, atol=1e-3)\n\n  if visualtests\n    plts = map([\u03b3\u2081,\u03b3\u2082,\u03b3\u2083,\u03b3\u2084]) do \u03b3\n      plot(g, legend=false)\n      plot!(\u03b3, 0., 15.)\n    end\n    @test_reference \"data/fitting.png\" plot(plts...)\n  end\n\n  # make sure convenient methods work\n  \u03b3\u2081 = fit(GaussianVariogram, g, h -> 1/h)\n  \u03b3\u2082 = fit(Variogram, g, h -> 1/h)\n  @test sill(\u03b3\u2081) > 0\n  @test sill(\u03b3\u2082) > 0\n\n  # unitful types\n  wl = geostatsimage(\"WalkerLake\")\n  TI = asarray(wl, :Z)[1:20,1:20]\n  d = georef((z=TI*u\"K\",))\n  g = EmpiricalVariogram(d, :z, maxlag=15.)\n  \u03b3 = fit(Variogram, g)\n  @test unit(sill(\u03b3)) == u\"K^2\"\n  @test unit(nugget(\u03b3)) == u\"K^2\"\nend\n", "meta": {"hexsha": "d87ac23e966311f12747bd3cedf97f30c7cce9ec", "size": 1231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fitting.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": "test/fitting.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": "test/fitting.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": 27.3555555556, "max_line_length": 52, "alphanum_fraction": 0.6238830219, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7642167890982338}}
{"text": "using HACTRep\nusing Test\n\nresults=HJBequation(0.03,0.5)\n\n@test size(results.A)[1]==length(results.a)*length(results.z)\n@test results.c[1]\u22480.0955\n#@test results.c[500]\u22480.35751765597047436\n@test (results.c[500]>=0.2) & (results.c[500]<=0.4)\n#@test results.c[1000]\u22480.3612279938702292\n@test (results.c[1000]>=0.2) & (results.c[1000]<=0.4)\n@test results.c[200]\u22480.24780538173577077\n@test results.v[1]\u2248-143.49029922114445\n@test results.v[500]\u2248-69.22947350451497\n@test results.v[1000]\u2248-68.54369002729676\n@test results.v[200]\u2248-97.12267792948414\n\nresultsKF=KF(results.a, results.z, results.A)\n\n@test resultsKF[1]<=0.01\n@test resultsKF[10]\u22481.4366548720872103\n@test resultsKF[200]\u22480.0\n@test resultsKF[500]\u22480.0\n@test resultsKF[510]\u22481.0320935781711122\n@test resultsKF[550]\u22480.6793836305961967\n@test resultsKF[700]\u2248-0.0\n\n@test equilibriumR(0.5)\u22480.021091194152832025\n@test equilibriumR(0.05)\u22480.03619252443313599\n@test equilibriumR(0.8)\u22480.026094157079133797\n@test equilibriumR(1.0)\u22480.03117997884750366\n@test equilibriumR(1.2)\u22480.034192388057708745\n@test equilibriumR(1.5)\u22480.037621619701385514\n\nresults3=TimeHJBequation(0.03*ones(100),results,100,0.5)\n\n@test results3.v[1,1]\u2248-143.4902993264915\n@test results3.v[200,10]\u2248-97.12267792838718\n@test results3.s[300,50]\u2248-0.11604803029950189\n\nresults4=TimeKF(results3.a,results3.z,results3.A,resultsKF,0.03*ones(100),20)\n\n@test results4[20,20]\u22481.337443770972458\n@test results4[20,50]\u22481.3374437709723683\n@test results4[10,20]\u22481.436654872087002\n@test results4[40,30]\u22480.5845834701237425\n\nresultsS=shockSim()\n\n@test resultsS[1]<=-0.1\n@test resultsS[end]>=0.029\n\nresultsh=HJBequationHousing(0.03,0.5)\n\n@test resultsh.h[200]\u22482.3927855711422845\n@test resultsh.h[1]\u22480.0\n@test resultsh.h[500]\u22485.6126932999996875\n@test resultsh.v[250]\u2248-76.42190579246638\n\nresultsKFT=KFHousing(resultsh.a,resultsh.z,resultsh.A)\n\n@test resultsKFT[1]>=4.0\n@test resultsKFT[2]<=2.0\n@test resultsKFT[end]\u22480.0\n\n#@testset \"Heterogeneous-Agents-Continuous-Time.jl\" begin\n    # Write your own tests here.\n\n#end\n", "meta": {"hexsha": "19c681bd10abc8430393866d8bb9530817111386", "size": 1997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "sebastiangomez87/HACTRep.jl", "max_stars_repo_head_hexsha": "47f59b015b38815bfb372122d523fdefbeccee46", "max_stars_repo_licenses": ["MIT"], "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": "sebastiangomez87/HACTRep.jl", "max_issues_repo_head_hexsha": "47f59b015b38815bfb372122d523fdefbeccee46", "max_issues_repo_licenses": ["MIT"], "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": "sebastiangomez87/HACTRep.jl", "max_forks_repo_head_hexsha": "47f59b015b38815bfb372122d523fdefbeccee46", "max_forks_repo_licenses": ["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.5285714286, "max_line_length": 77, "alphanum_fraction": 0.7611417126, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7642167873199696}}
{"text": "##include( \"../src/lossFunctions.jl\" )\nusing Statistics\nusing Test\n\nprintln( \"running loss functions' unit tests\" );\n\n#== testing for 0,1 labels error functions ==#\na = zeros( Float64, 10000 )\nb = ones( Float64, 10000 )\n\n@test mean( lossFunctions.MSE( a, b ) ) == 1.0\n@test mean( lossFunctions.MSE( a, a ) ) == 0.0\n@test mean( lossFunctions.MSE( b, b ) ) == 0.0\n@test mean( lossFunctions.zeroOneLoss( a, b ) ) == 1.0\n@test mean( lossFunctions.zeroOneLoss( a, a ) ) == 0.0\n@test mean( lossFunctions.zeroOneLoss( b, b ) ) == 0.0 \n\n#== testing for 1,-1 labels error functions ==#\na       = Bool.( rand( 0:1, 10000 ) );\nb       = .!a;\nindex_a = ( a .== false );\na       = Float64.( a );\na[index_a] .= -1.0;\nindex_b     = ( b .== false );\nb           = Float64.( b );\nb[index_b] .= -1.0;\n@test mean( lossFunctions.hingeLoss( a, b ) ) == 2.0\n@test mean( lossFunctions.hingeLoss( a, a ) ) == 0.0\n@test mean( lossFunctions.hingeLoss( b, b ) ) == 0.0\n\n@test lossFunctions.MSE( 1.0, 1.0 ) == 0.0\n@test lossFunctions.MSE( 0.0, 0.0 ) == 0.0\n@test lossFunctions.MSE( 1.0, 0.0 ) == 1.0\n@test lossFunctions.MSE( 0.0, 1.0 ) == 1.0\n@test lossFunctions.MSE( 0.0, 10.0 ) == 100.0\n@test lossFunctions.MSE( 10.0, 0.0 ) == 100.0", "meta": {"hexsha": "6dd0d17890a6c7e0d7a3da50d16ce73d9821c663", "size": 1206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unitTestLossF.jl", "max_stars_repo_name": "hondoRandale/AgnosticBayesEnsemble.jl", "max_stars_repo_head_hexsha": "9118e59e692f8cbfd039e9df9d11112d6dea90d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-26T23:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-16T15:09:44.000Z", "max_issues_repo_path": "test/unitTestLossF.jl", "max_issues_repo_name": "hondoRandale/AgnosticBayesEnsemble.jl", "max_issues_repo_head_hexsha": "9118e59e692f8cbfd039e9df9d11112d6dea90d9", "max_issues_repo_licenses": ["MIT"], "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/unitTestLossF.jl", "max_forks_repo_name": "hondoRandale/AgnosticBayesEnsemble.jl", "max_forks_repo_head_hexsha": "9118e59e692f8cbfd039e9df9d11112d6dea90d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-08T22:18:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T22:18:23.000Z", "avg_line_length": 33.5, "max_line_length": 55, "alphanum_fraction": 0.5986733002, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7642167852022408}}
{"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    \u03c3= 2.0; \u03c1 = 0.05; \u03b4 = 0.05; A = 1.0; \u03b1= 0.3; \r\n\r\n    # Closed form. Doesn't work.\r\n    # \u03c3= 4.0;  \u03b4 = 0.05; A = 1.0; \u03b1= 0.3; \r\n    # \u03c1 = \u03b4*(\u03b1*\u03c3 - 1) # restriction for closed form \r\n    # FOC(v;\u03c3=\u03c3) = abs(v)^(-1.0/\u03c3)                  # FOC, u'^-1()\r\n\r\n    r(c; \u03c3=\u03c3)  = (c^(1-\u03c3))/(1-\u03c3)             # return fcn.      make it r(s,c)\r\n    \u03bc(s,c; \u03b1=\u03b1,\u03b4=\u03b4,A=A) = A*(s^\u03b1) - \u03b4*s -c;  # Transition fcn.  s\u0307=\u03bc(s,c)\r\n\r\n    dr(c;\u03c3=\u03c3) = c^(-\u03c3)                       # derivative of return fcn.\r\n    FOC(v;\u03c3=\u03c3) = v^(-1.0/\u03c3)                  # FOC, u'^-1()\r\n\r\n    \u03bc_inv(s,s\u0307; \u03b1=\u03b1,\u03b4=\u03b4,A=A) = A*(s^\u03b1) - \u03b4*s -s\u0307; # Inv Trans c=\u03bc(s,s\u0307), solve s\u0307=\u03bc(s,c) for c\r\n    # con0(s;\u03b1=\u03b1,\u03b4=\u03b4,A=A)     = A*(s^\u03b1) - \u03b4*s      # solve: s\u0307=\u03bc(s,c) for c(s) if s\u0307=0. \r\n    # \u03bc_inv(s,0) = con0(s)\r\n\r\n    s_ss = (\u03b1*A/(\u03c1+\u03b4))^(1/(1-\u03b1))\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    \u03c3= 2.0; \u03c1 = 0.05; A=0.045; w = 0.1;\r\n    r(c;\u03c3=\u03c3)  = (c^(1-\u03c3))/(1-\u03c3)            # return fcn.\r\n    \u03bc(s,c; w=w,A=A) = w + A*s - c;         # Transition fcn.  s\u0307=\u03bc(s,c)\r\n\r\n    dr(c;\u03c3=\u03c3) = c^(-\u03c3)                     # deriv return fcn.\r\n    FOC(v;\u03c3=\u03c3) = v^(-1.0/\u03c3)                # FOC, u'^-1()\r\n\r\n    \u03bc_inv(s,s\u0307; w=w,A=A) = w + A*s -s\u0307;  # Inv Trans c=\u03bc(s,s\u0307), solve s\u0307=\u03bc(s,c) for c\r\n    # \u03bc_inv(s,0) = con0(s)\r\n    #con0(s;\u03b1=\u03b1,\u03b4=\u03b4,A=A) = w + A*s          # solve: s\u0307=\u03bc(s,c) for c(s) if s\u0307=0. \r\n\r\n    s_min = a_bar\r\n    \u03bc_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\u0394 = 1_000\r\nmaxit = 10_000\r\n\u03b5 = 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(\u03bc_inv(s,0))/\u03c1 #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(\u03bc_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(\u03bc_inv(s_min,0))        # state constraint, for stability\r\n    #dVb[1] = (A*s_min)^(-\u03c3)\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    \u03bc_f = \u03bc.(s, cf)\r\n\r\n    # consumption and savings with backward difference\r\n    cb  = FOC.(dVb)\r\n    \u03bc_b = \u03bc.(s, cb)\r\n\r\n    # c if k\u0307=0 & V = u'(c)\r\n\tc0  = \u03bc_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 = \u03bc_f .> 0\r\n    Ib = \u03bc_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(\u03bc_f, lab=\"dVf\") \r\n    # plot!(\u03bc_b, lab=\"dVb\")\r\n    # plot!(zero(\u03bc_f), lab=\"dV0\")\r\n\r\n    # create the transition matrix\r\n    X = -min.(\u03bc_b,0)/ds\r\n    Y = -max.(\u03bc_f,0)/ds + min.(\u03bc_b,0)/ds\r\n    Z = max.(\u03bc_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 = (\u03c1 + 1/\u0394)*sparse(I,H,H) - AA\r\n    b = u + V./\u0394\r\n\r\n    # Solve: B V = b \r\n    # => (\u03c1 + 1/\u0394)*sparse(I,H,H)*V - AA*V = u + V./\u0394\r\n    # => (\u03c1 + 1/\u0394)*V = u + V./\u0394 +  AA*V\r\n    # => (\u03c1)*V + V./\u0394 = u + V./\u0394 +  AA*V\r\n    # => (\u03c1)*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] .< \u03b5\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 = \u03bc.(s,c)\r\nv_err = r.(c) + dV_Upwind.*s_dot - \u03c1.*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 = \u03bc(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\u03c3= 4.0;  \u03b4 = 0.05; A = 1.0; \u03b1= 0.3; \r\n\u03c1 = \u03b4*(\u03b1*\u03c3 - 1) # restriction for closed form \r\n\r\n# Policy: c = (1-s)(k^\u03b1)\r\ncp(s) = (1-((\u03b1*\u03b4)/(\u03c1+\u03b4)))*s^\u03b1\r\ns_d(s) = (s^\u03b1) - \u03b4*s - cp(s)\r\nplot(s, cp)\r\nplot!(s, s_d)\r\n\r\n#\r\ns_ss = (\u03b1*A/(\u03c1+\u03b4))^(1/(1-\u03b1))\r\nz_ss = (s_ss)^(1-\u03b1)\r\nc_ss = (s_ss)^(\u03b1)  - \u03b4*s_ss\r\n\r\ns_0 = 5;\r\nz_0 = (s_0)^(1-\u03b1)\r\n\r\n\u03bb=(1-\u03b1)*\u03b4\r\nz(t) = z_ss + exp(-\u03bb*t)*(z_0 - z_ss)\r\nkk(t) = z(t)^(1/(1-\u03b1))\r\ncc(t) = (1-((\u03b1*\u03b4)/(\u03c1+\u03b4)))*kk(t)^\u03b1\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} = \u03c3(y-x) \\\\\\\\\n\\\\frac{dy}{dt} = x(\u03c1-z) - y \\\\\\\\\n\\\\frac{dz}{dt} = xy - \u03b2z \\\\\\\\\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    \u03b1 = 0.37\n    \u03b4 = 0.1\n    \u03b2 = 0.95\n    \u03c3 = 1.5\n\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = (c .^ (1-\u03c3) .- 1) ./ (1-\u03c3)\n    u[kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while maximum(abs.(v - vnew)) > tolerance && i <= imax\n        v = vnew;\n        \n        (vnew, cartesianindex) = findmax(u .+ \u03b2*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    \u03b1 = 1.5\n    \u03b4 = 0.1\n    \u03b2 = 0.95\n    \u03c3 = 1.5\n\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = (c .^ (1-\u03c3) .- 1) ./ (1-\u03c3)\n    u[kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while i <= imax\n\n        (vnew, cartesianindex) = findmax(u .+ \u03b2*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    \u03b1 = 1.5\n    \u03b4 = 0.1\n    \u03b2 = 0.95\n    \u03c3 = 0.5\n\n    v = vnew .+ 2*tolerance\n    cartesianindex = Array{CartesianIndex{2}, length(v)}\n    i = 1\n    \n    c = kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid'\n    c[c .< 0] .= 0\n    u = (c .^ (1-\u03c3) .- 1) ./ (1-\u03c3)\n    u[kgrid.^\u03b1 + (1-\u03b4)*kgrid .- kgrid' .< 0] .= -Inf\n\n    while maximum(abs.(v - vnew)) > tolerance && i <= imax\n        v = vnew;\n        \n        (vnew, cartesianindex) = findmax(u .+ \u03b2*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, \u03c0-periodic solutions to the\nangular Mathieu equation.\n\n* `q`: real parameter of Mathieu\u2019s equation\n* `N`: truncated matrix dimension (matrix is N\u00d7N)\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] *= \u221a2\n    return SymTridiagonal(dd,du)\nend\n\n\"\"\"\n    mat_C2(q,N)\n\nGenerate the matrix corresponding to even, 2\u03c0-periodic (\u03c0-antiperiodic)\nsolutions to the angular Mathieu equation.\n\n* `q`: real parameter of Mathieu\u2019s equation\n* `N`: truncated matrix dimension (matrix is N\u00d7N)\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\u03c0-periodic (\u03c0-antiperiodic)\nsolutions to the angular Mathieu equation.\n\n* `q`: real parameter of Mathieu\u2019s equation\n* `N`: truncated matrix dimension (matrix is N\u00d7N)\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, \u03c0-periodic solutions to the\nangular Mathieu equation.\n\n* `q`: real parameter of Mathieu\u2019s equation\n* `N`: truncated matrix dimension (matrix is N\u00d7N)\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    #\u00a01 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    #\u00a0use 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    #\u00a01 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    #\u00a01 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": "using ApproxFun, BandedMatrices, BlockBandedMatrices, LinearAlgebra, BlockArrays, MultivariateOrthogonalPolynomials, Test\nusing SparseVolterraExamples\n\n#############################\n## Tests for Volterra integral operator\n## with Clenshaw Jacobi expansion of the kernel.\n####\n## Includes tests for 1 to x and 1 to 1-x limits of integration.\n#############################\n\n@testset \"Set #1.1 - Volterra, Clenshaw sin kern, flip = true\" begin\n    K(x,y)=sin(x+y);\n    f=Fun(y->y, Jacobi(0,1,0..1));\n    @test triVolterraFullKernelFunP01(f,K,25,true) \u2248 Fun(x->-x*cos(2*x)-sin(x)+sin(2*x), Jacobi(1,0,0..1));\nend\n\n@testset \"Set #1.2 - Volterra, Clenshaw sin kern, flip = false, val test\" begin\n    K(x,y)=sin(x+y);\n    val = rand(0..1);\n    f=Fun(y->y, Jacobi(0,1,0..1));\n    @test triVolterraFullKernelFunP01(f,K,30,false)(val) \u2248 Fun(x->((-1)*cos(1)+x*cos(1)+sin(1)-sin(x)), Jacobi(1,0,0..1))(val);\nend\n\n@testset \"Set #2 - Volterra, Clenshaw sinh kern, flip = true\" begin\n    K(x,y)=(y-x)*sinh(x);\n    f=Fun(y->y, Jacobi(0,1,0..1));\n    @test triVolterraFullKernelFunP01(f,K,25,true) \u2248 Fun(x->-1/6*x^3*sinh(x), Jacobi(1,0,0..1));\nend\n\n@testset \"Set #3 - Volterra, Clenshaw sinh kern, flip = false\" begin\n    K(x,y)=(y-x)*sinh(x^2);\n    f=Fun(y->y, Jacobi(0,1,0..1));\n    @test triVolterraFullKernelFunP01(f,K,25,false) \u2248 Fun(x->(sinh(x^2))/3-3/2*x*sinh(x^2)+2*x^2*sinh(x^2)-5/6*x^3*sinh(x^2), Jacobi(0,1,0..1));\nend\n", "meta": {"hexsha": "798f9024af58a811c125084e73cda411d030fa97", "size": 1413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_VolterraIntegral-FullKernel.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": "test/test_VolterraIntegral-FullKernel.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": "test/test_VolterraIntegral-FullKernel.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": 40.3714285714, "max_line_length": 144, "alphanum_fraction": 0.6171266808, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7641757865876679}}
{"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) => \u03b3\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    \u03b3 = 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\u03b3 = \u03b3\n        \u03b3 = norm(y,1)\n        if \u03b3 <= old\u03b3\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,\u03b3)\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": "export CyclicRange\r\n\r\n#= make CyclicRange For ScaLAPACK =#\r\n\r\nstruct CyclicRange{T <: Integer} <: AbstractRange{T}\r\n    start::T # full array's first\r\n    stop::T # full array's last\r\n    blocksize::T # blocksize\r\n    n_split::T # number of process\r\n    split_index::T # what process\r\n\r\n    CyclicRange(;start::T, stop::T, blocksize::T, n_split::T, split_index::T) where T <: Integer = new{T}(start, stop, blocksize, n_split, split_index)\r\nend\r\n\r\nnumber_element(r::CyclicRange) = r.stop - r.start + 1\r\n\r\nfunction number_element_local(r::CyclicRange)\r\n    n_element = number_element(r)\r\n    n_block_local_min = number_block_local_min(r)\r\n    n_extra_block = number_block_global_extra(r)\r\n\r\n    n_element_local = r.blocksize*n_block_local_min\r\n    n_extra_element = n_element % r.blocksize\r\n\r\n    # add extra block\r\n    if r.split_index <= n_extra_block\r\n        n_element_local += r.blocksize\r\n    end\r\n    # add extra element, \r\n    if r.split_index == n_extra_block + 1 && n_extra_element != 0\r\n        n_element_local += n_extra_element\r\n    end\r\n    return n_element_local\r\nend\r\n\r\nfunction number_block(r::CyclicRange)\r\n    n_element = number_element(r)\r\n    n_block = n_element \u00f7 r.blocksize\r\n    return n_block\r\nend\r\n\r\nfunction number_block_local_min(r::CyclicRange{T}) where T <: Integer\r\n    n_block = number_block(r)\r\n    n_block_local = n_block \u00f7 r.n_split\r\n    return n_block_local\r\nend\r\n\r\nfunction number_block_global_extra(r::CyclicRange{T}) where T <: Integer\r\n    n_block = number_block(r)\r\n    n_extra_block = n_block % r.n_split\r\n    return n_extra_block\r\nend\r\n\r\nfunction local_index(r::CyclicRange, i::Integer)\r\n    i_temp = i - 1\r\n    block_position = i_temp \u00f7 r.blocksize\r\n    local_index = (block_position \u00f7 r.n_split)*r.blocksize + (i_temp % r.blocksize) + 1\r\n    split_index = block_position % r.n_split + 1\r\n    # mpi rank = split_index - 1, in 0-based local index = extra_element - 1\r\n    return split_index, local_index\r\nend\r\n\r\nBase.firstindex(::CyclicRange) = 1\r\n\r\nBase.first(r::CyclicRange) = getindex(r, 1)\r\n\r\nBase.last(r::CyclicRange) = getindex(r, length(r))\r\n\r\nBase.length(r::CyclicRange{T}) where T <: Integer = number_element_local(r)\r\n\r\nBase.getindex(r::CyclicRange, i::Integer) = r.blocksize*(r.split_index-1) + r.n_split*r.blocksize*div(i-1, r.blocksize) + mod(i-1, r.blocksize) + 1\r\n\r\nBase.show(io::IO, r::CyclicRange) = print(io, \"$(r.start):[$(r.split_index) $(r.blocksize) $(r.n_split)]:$(r.stop)\")\r\n\r\n\r\n", "meta": {"hexsha": "568c29e357233b061ce61ca65a453f509a152e9d", "size": 2444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cyclic_range.jl", "max_stars_repo_name": "Soyukke/MPIArrays.jl", "max_stars_repo_head_hexsha": "2a309c8a81f05e14dcd1b555d830abf98121da0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cyclic_range.jl", "max_issues_repo_name": "Soyukke/MPIArrays.jl", "max_issues_repo_head_hexsha": "2a309c8a81f05e14dcd1b555d830abf98121da0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cyclic_range.jl", "max_forks_repo_name": "Soyukke/MPIArrays.jl", "max_forks_repo_head_hexsha": "2a309c8a81f05e14dcd1b555d830abf98121da0a", "max_forks_repo_licenses": ["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.1578947368, "max_line_length": 152, "alphanum_fraction": 0.6828968903, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.764134909842444}}
{"text": "using Revise\nusing Basins\nusing Plots\nusing DynamicalSystems\nusing DifferentialEquations\n\n#\n#\n# \u03c9=1.\n# F = 0.2\n# ds =Systems.duffing([0.1, 0.25]; \u03c9 = \u03c9, f = F, d = 0.15, \u03b2 = -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/\u03c9)\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 [-\u03c0,\u03c0]\nfunction affect!(integrator)\n    if integrator.u[1] < 0\n        integrator.u[1] += 2*\u03c0\n    else\n        integrator.u[1] -= 2*\u03c0\n    end\nend\n\ncondition(u,t,integrator) = (integrator.u[1] < -\u03c0  || integrator.u[1] > \u03c0)\n\ncb = DiscreteCallback(condition,affect!)\n\n#d, F ,w\nF = 1.66\n\u03c9 = 1.\nd=0.2\np=[d, F, \u03c9]\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/\u03c9)\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(\u03c0*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, \u03c0/4) end\n    y = abs(x)\n    convert(T, besselj1(\u03c0*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    \u03b2 = one(T)\n    \u03b1 = -r[1]\n    for k = 1:n-1\n        \u03b2 *= one(T) - \u03b1*\u03b1\n        \u03b1 = -r[k+1]\n        for j = 1:k\n            \u03b1 -= r[k-j+1]*y[j]\n        end\n        \u03b1 /= \u03b2\n        for j = 1:div(k,2)\n            tmp = y[j]\n            y[j] += \u03b1*y[k-j+1]\n            y[k-j+1] += \u03b1*tmp\n        end\n        if isodd(k) y[div(k,2)+1] *= one(T) + \u03b1 end\n        y[k+1] = \u03b1\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    \u03b2 = one(T)\n    \u03b1 = -r[2]/r[1]\n    for k = 1:n-1\n        \u03b2 *= one(T) - \u03b1*\u03b1\n        \u03bc = b[k+1]\n        for j = 2:k+1\n            \u03bc -= r[j]/r[1]*x[k-j+2]\n        end\n        \u03bc /= \u03b2\n        for j = 1:k\n            x[j] += \u03bc*b[k-j+1]\n        end\n        x[k+1] = \u03bc\n        if k < n - 1\n            \u03b1 = -r[k+2]\n            for j = 2:k+1\n                \u03b1 -= r[j]*b[k-j+2]\n            end\n            \u03b1 /= \u03b2*r[1]\n            for j = 1:div(k,2)\n                tmp = b[j]\n                b[j] += \u03b1*b[k-j+1]\n                b[k-j+1] += \u03b1*tmp\n            end\n            if isodd(k) b[div(k,2)+1] *= one(T) + \u03b1 end\n            b[k+1] = \u03b1\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 \u21a6 0 if ||x|| \u2a7d r & all(0 \u2a7d x), +\u221e 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": "n = 1000\ntargets = rand(0:1, n)\nscores = rand(n)\nthres = 0.7\npredicts = scores .>= thres\n\np  = sum(targets .== 1)\nn  = sum(targets .== 0)\ntp = sum(targets .* predicts)\ntn = sum((1 .- targets) .* (1 .- predicts))\nfp = sum((1 .- targets) .* predicts)\nfn = sum(targets .* (1 .- predicts))\n\ncm = ConfusionMatrix(p, n, tp, tn, fp, fn)\ncm2 = ConfusionMatrix(2*p, 2*n, 2*tp, 2*tn, 2*fp, 2*fn)\n\nset_encoding(OneZero())\n\nencs = [\n    OneZero(),\n    OneMinusOne(),\n    OneTwo(),\n    OneVsOne(3,4),\n    OneVsOne(:three,:four),\n    OneVsOne(\"three\",\"four\"),\n    OneVsRest(1, [2,3,4]),\n    OneVsRest(:one, [:two, :three]),\n    OneVsRest(\"one\", [\"two\", \"three\"]),\n    RestVsOne([1,2,3], 4),\n    RestVsOne([:one, :two], :three),\n    RestVsOne([\"one\", \"two\"], \"three\")\n]\n\n\n@testset \"ConfusionMatrix +\" begin\n    @test cm + cm == cm2\nend\n\n\n@testset \"ConfusionMatrix constructors for $enc encoding\" for enc in encs\n    global targets, predicts\n\n    targets = recode.(current_encoding(), enc, targets)\n    predicts = recode.(current_encoding(), enc, predicts)\n    set_encoding(enc)\n\n\n    @test ConfusionMatrix(targets, predicts) == cm\n    @test ConfusionMatrix(enc, targets, predicts) == cm\n    @test ConfusionMatrix(targets, scores, thres) == cm\n    @test ConfusionMatrix(enc, targets, scores, thres) == cm\n    @test ConfusionMatrix(targets, scores, [thres]) == [cm]\n    @test ConfusionMatrix(enc, targets, scores, [thres]) == [cm]\nend", "meta": {"hexsha": "2bac4a2b8d25c5bdace559216059b9d5cee78c53", "size": 1417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/confusion_matrix.jl", "max_stars_repo_name": "KronosTheLate/EvalMetrics.jl", "max_stars_repo_head_hexsha": "5e47a980cf69757160f7b85fde1cd47ed98dd41a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-03-19T12:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T16:48:36.000Z", "max_issues_repo_path": "test/confusion_matrix.jl", "max_issues_repo_name": "KronosTheLate/EvalMetrics.jl", "max_issues_repo_head_hexsha": "5e47a980cf69757160f7b85fde1cd47ed98dd41a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:18:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:09:57.000Z", "max_forks_repo_path": "test/confusion_matrix.jl", "max_forks_repo_name": "KronosTheLate/EvalMetrics.jl", "max_forks_repo_head_hexsha": "5e47a980cf69757160f7b85fde1cd47ed98dd41a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-30T00:53:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T06:46:24.000Z", "avg_line_length": 26.2407407407, "max_line_length": 73, "alphanum_fraction": 0.6203246295, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7640798199394939}}
{"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\u00fa\u00f1ez:\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\u03b1 = 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\u039b(x) = forward_logs(M, x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x, rep(d)...), \u039b(x)), 1)\ncost(x) = (1 / \u03b1) * fidelity(x) + prior(x)\nproxes = ((\u03bb, x) -> prox_distance(M, \u03bb, f, x, 2), (\u03bb, x) -> prox_TV(M, \u03b1 * \u03bb, x, 1))\n\nx0 = f\n@time o = cyclic_proximal_point(\n    M,\n    cost,\n    proxes,\n    x0;\n    \u03bb=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    \u03c3s = similar(x)\n    \u03c3s .= h\n\n    \u03c3s[inds[1]] -= h/T(2)\n\n    \u03c3s[end] -= h/T(2)\n    # accounts for the ends\n    \u03c3s[inds[1]] +=   (x[inds[1]] - x0)*(x[inds[2]] - x0 + h)/(2.0h)\n    \u03c3s[inds[2]] +=  -(x0 - x[inds[1]])^T(2)/(T(2)*h)\n    \u03c3s[end] +=  (xn - x[end])*(xn - x[end-1] + h)/(2h)\n    \u03c3s[end-1] += - (xn - x[end])^T(2)/(T(2)*h)\n\n    return \u03c3s\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    \u03c3s = similar(x).*zero(T)\n    for j in 1:length(inds)\n        \u03c3s[inds[j]] = iseven(j) ? 4.0 : 2.0\n    end\n    \u03c3s = \u03c3s.*(h/3.0)\n\n    # accounts for the ends\n    \u03c3s[inds[1]] = h/3.0\n    \u03c3s[inds[1]] +=  (x[inds[1]] - x0)*(x[inds[2]] - x0 + h)/(2.0h)\n    \u03c3s[inds[2]] +=  - (x0-x[inds[1]])^2.0/(2.0h)\n    \u03c3s[inds[end]] = h/3.0\n    \u03c3s[inds[end]] +=  (xn-x[inds[end]])*(xn - x[inds[end-1]] + h)/(2h)\n    \u03c3s[inds[end-1]] += - (xn-x[inds[end]])^2.0/(2h)\n\n    return \u03c3s\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\u2013Seidel\n#\n###########\n\nusing BlockBandedMatrices, BandedMatrices, ArrayLayouts, FillArrays, LazyBandedMatrices, LazyArrays\n\n\nfunction finitedifference_2d(n)\n    h = 1/n\n    D\u00b2 = BandedMatrix(0 => Fill(-2,n), 1 => Fill(1,n-1), -1 => Fill(1,n-1))/h^2\n    D_xx = BandedBlockBandedMatrix(Kron(D\u00b2, Eye(n)))\n    D_yy = BandedBlockBandedMatrix(Kron(Eye(n), D\u00b2))\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    \u0394t = (1/n^2)/4; @time \u0394 = finitedifference_2d(n);\n    @time A = I - \u0394t*\u0394  # 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\u0303 = sparse(BandedBlockBandedMatrix(L))\n    @time \u0168 = sparse(U)\n    x = copy(b)\n    y = copy(x)\n    @time _gaussseidel2(L\u0303,\u0168, b, x, y, 20)\n\n\u00c3 = sparse(A)\n@time qr(\u00c3);\n@time \u00c3 \\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": "using DelayEmbeddings\nusing Test, Random, DelimitedFiles\n\nprintln(\"\\nTesting pecuzal_method.jl...\")\n@testset \"PECUZAL\" begin\n\n## Test Lorenz example\n# For comparison reasons using Travis CI we carry out the integration on a UNIX\n# OS and save the resulting time series\n# See https://github.com/JuliaDynamics/JuliaDynamics for the storage of\n# the time series used for testing\n#\n# u0 = [0, 10.0, 0.0]\n# lo = Systems.lorenz(u0; \u03c3=10, \u03c1=28, \u03b2=8/3)\n# tr = trajectory(lo, 100; \u0394t = 0.01, Ttr = 100)\ntr = readdlm(joinpath(tsfolder, \"test_time_series_lorenz_standard_N_10000_multivariate.csv\"))\ntr = Dataset(tr)\n\n@testset \"Univariate example\" begin\n\n    s = vec(tr[:, 1]) # input timeseries = x component of lorenz\n    w = estimate_delay(s, \"mi_min\")\n    Tmax = 100\n\n    @time Y, \u03c4_vals, ts_vals, Ls , \u03b5s = pecuzal_embedding(s[1:5000];\n                                        \u03c4s = 0:Tmax , w = w, L_threshold = 0.05, econ=true)\n\n    @test -1.08 < Ls[1] < -1.04\n    @test -0.51 < Ls[2] < -0.47\n    @test -0.18 < Ls[3] < -0.14\n\n    @test \u03c4_vals[2] == 19\n    @test \u03c4_vals[3] == 96\n    @test \u03c4_vals[4] == 80\n    @test length(ts_vals) == 4\n\n    @time Y, \u03c4_vals, ts_vals, Ls , \u03b5s = pecuzal_embedding(s;\n                                        \u03c4s = 0:Tmax , w = w, L_threshold = 0.05)\n    @test -0.95 < Ls[1] < -0.91\n    @test -0.48 < Ls[2] < -0.44\n\n    @test \u03c4_vals[2] == 18\n    @test \u03c4_vals[3] == 9\n    @test length(ts_vals) == 3\n\n    YY1 = DelayEmbeddings.hcat_lagged_values(Dataset(s), s, 21)\n    YY2 = DelayEmbeddings.hcat_lagged_values(YY1, s, 13)\n    @test length(YY1) == length(YY2)\n    @test YY1 == YY2[:,1:2]\n\nend\n\n\n@testset \"Multivariate example\" begin\n    ## Test of the proposed PECUZAL-embedding-method (multivariate case)\n\n    w1 = estimate_delay(tr[:,1], \"mi_min\")\n    w2 = estimate_delay(tr[:,2], \"mi_min\")\n    w3 = estimate_delay(tr[:,3], \"mi_min\")\n    w = w1\n    Tmax = 100\n\n    @time Y, \u03c4_vals, ts_vals, Ls , \u03b5\u2605 = pecuzal_embedding(tr[1:5000,:];\n                                        \u03c4s = 0:Tmax , w = w, econ = true)\n\n    @test length(ts_vals) == 4\n    @test ts_vals[2] == ts_vals[3] == ts_vals[4] == 1\n    @test ts_vals[1] == 3\n    @test \u03c4_vals[1] == 0\n    @test \u03c4_vals[2] == 9\n    @test \u03c4_vals[3] == 64\n    @test \u03c4_vals[4] == 53\n    @test -1.40 < Ls[1] < -1.36\n    @test -0.76 < Ls[2] < -0.72\n    @test -0.1 < Ls[3] < -0.06\n\n    @time Y, \u03c4_vals, ts_vals, Ls , \u03b5\u2605 = pecuzal_embedding(tr[1:5000,:];\n                                        \u03c4s = 0:Tmax , w = w, econ = true, L_threshold = 0.2)\n    @test -1.40 < Ls[1] < -1.36\n    @test -0.76 < Ls[2] < -0.72\n    @test size(Y,2) == 3\n\nend\n\n@testset \"Dummy example\" begin\n    # Dummy input\n    Random.seed!(1234)\n    d1 = randn(1000)\n    d2 = rand(1000)\n    Tmax = 50\n    dummy_set = Dataset(hcat(d1,d2))\n\n    w1 = estimate_delay(d1, \"mi_min\")\n    w2 = estimate_delay(d2, \"mi_min\")\n    w = w1\n\n    @time Y, \u03c4_vals, ts_vals, Ls , \u03b5\u2605 = pecuzal_embedding(dummy_set;\n                                    \u03c4s = 0:Tmax , w = w, econ = true)\n\n    @test size(Y,2) == 1\nend\n\nend\n", "meta": {"hexsha": "582751afff5ef88b74ce857f3837be5dac03e844", "size": 3023, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unified/test_pecuzal_embedding.jl", "max_stars_repo_name": "JuliaDynamics/DelayEmbeddings.jl", "max_stars_repo_head_hexsha": "a266a80222059fd612632989c7dd59c786ee69b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-11-21T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T14:24:47.000Z", "max_issues_repo_path": "test/unified/test_pecuzal_embedding.jl", "max_issues_repo_name": "JuliaDynamics/DelayEmbeddings.jl", "max_issues_repo_head_hexsha": "a266a80222059fd612632989c7dd59c786ee69b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2018-11-09T12:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T14:06:10.000Z", "max_forks_repo_path": "test/unified/test_pecuzal_embedding.jl", "max_forks_repo_name": "JuliaDynamics/DelayEmbeddings.jl", "max_forks_repo_head_hexsha": "a266a80222059fd612632989c7dd59c786ee69b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-05-01T19:08:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T15:58:14.000Z", "avg_line_length": 29.0673076923, "max_line_length": 93, "alphanum_fraction": 0.5640092623, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7640446956932619}}
{"text": "# A simple example to demonstrate the use of cross validation\n#\n# Here, we consider a simple model: using a mean vector to represent\n# a set of samples. The goodness of the model is assessed in terms\n# of the RMSE (root-mean-square-error) evaluated on the testing set\n#\n\nusing MLBase\n\n# functions\n\nfunction compute_center(X::Matrix{Float64})\n\tc = vec(mean(X, 2))\n\t@printf(\"training on %d samples => (%.4f, %.4f)\\n\", \n\t\tsize(X,2), c[1], c[2])\n\treturn c\nend\n\nfunction compute_rmse(c::Vector{Float64}, X::Matrix{Float64}) \n\tv = sqrt(mean(sum(abs2(X .- c),1)))\n\t@printf(\"RMSE on test set: %.6f\\n\\n\", v)\n\treturn v\nend\n\n# data\n\nconst n = 200\nconst data = [2., 3.] .+ randn(2, n)\n\n# cross validation\n\n(c, v, inds) = cross_validate(\n\tinds -> compute_center(data[:, inds]),     \t\t# training function\n\t(c, inds) -> compute_rmse(c, data[:, inds]),    # evaluation function\n\tn,    \t\t\t# total number of samples\n\tKfold(n, 5), \t# cross validation plan: 5-fold \n\tReverse)\t\t# smaller score indicates better model\n\n# display results\n\n@printf(\"best model = (%.4f, %.4f), score = %.6f\\n\", c[1], c[2], v)\n\n", "meta": {"hexsha": "d93ba5fd96f3e410df1a6fe16f0848c883932334", "size": 1085, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/crossval.jl", "max_stars_repo_name": "lendle/MLBase.jl", "max_stars_repo_head_hexsha": "2d360e6f236e813f2276cc6aaaf65bb01d66c4ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176, "max_stars_repo_stars_event_min_datetime": "2015-02-25T19:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:11:41.000Z", "max_issues_repo_path": "examples/crossval.jl", "max_issues_repo_name": "lendle/MLBase.jl", "max_issues_repo_head_hexsha": "2d360e6f236e813f2276cc6aaaf65bb01d66c4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2015-01-10T11:37:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T11:49:30.000Z", "max_forks_repo_path": "examples/crossval.jl", "max_forks_repo_name": "lendle/MLBase.jl", "max_forks_repo_head_hexsha": "2d360e6f236e813f2276cc6aaaf65bb01d66c4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2015-01-14T19:03:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T16:48:55.000Z", "avg_line_length": 25.2325581395, "max_line_length": 70, "alphanum_fraction": 0.6552995392, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7640446956932618}}
{"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\u207a, x, u, w, h)\n    x\u207a - (x + h * f(model, 0.5 * (x + x\u207a), 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\u207a, x, u, w, h, t)\n    midpoint_implicit(model, x\u207a, 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\u03d5(t) = 3t^2 - 2t^3\n\u03c8(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 * \u03d5((x2-x)/h)\n     + y2 * \u03d5((x-x1)/h)\n     - d1*h * \u03c8((x2-x)/h)\n     + d2*h * \u03c8((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 \u2248 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    \u0394(i) = (ys[i+1]-ys[i]) / h(i)\n\n    N = length(xs)\n    ds = similar(xs)\n    if N == 2\n        ds[:] .= \u0394(1)\n    else\n        \u0394l = \u0394(1)\n        hl = h(1)\n        for i \u2208 2:N-1\n            \u0394r = \u0394(i)\n            hr = h(i)\n            if sign(\u0394l) != sign(\u0394r) || \u0394l \u2248 0.0 || \u0394r \u2248 0.0\n                ds[i] = 0.0\n            else\n                wl = 2hl + hr\n                wr = hl + 2hr\n                ds[i] = (wl + wr) / (wl/\u0394l + wr/\u0394r)\n            end\n            \u0394l = \u0394r\n            hl = hr\n        end\n        ds[1] = _edge_derivative(h(1), h(2), \u0394(1), \u0394(2))\n        ds[N] = _edge_derivative(h(N-1), h(N-2), \u0394(N-1), \u0394(N-2))\n    end\n    ds\nend\n\nfunction _edge_derivative(h1, h2, \u03941, \u03942)\n    d = ((2h1 + h2)*\u03941 - h2*\u03942) / (h1 + h2)\n    if sign(d) != sign(\u03941)\n        d = 0.0\n    elseif sign(\u03941) != sign(\u03942)  &&  abs(d) > abs(3\u03941)\n        d = 3\u03941\n    end\n    d\nend\n\nfunction interpolate(xs, ys)\n    xs_ = [x for x \u2208 xs]\n    ys_ = [y for y \u2208 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 AdFem\n\nfor degree in [1, 2]\n    m = 100; n = 100; h = 1/n\n    mesh = Mesh(m, n, h, degree = degree)\n\n    function f(x, y)\n        2 * x^2 + y\n    end\n\n    f_fem = eval_f_on_fem_pts(f, mesh)\n    f_gauss = fem_to_gauss_points(constant(f_fem), mesh)\n    sess = Session(); init(sess)\n    f_gauss = run(sess, f_gauss)\n\n    f_gauss2 = eval_f_on_gauss_pts(f, mesh)\n\n    @show maximum(abs.(f_gauss .- f_gauss2))\nend", "meta": {"hexsha": "739552596a5d27c0213dea58226814d49dc7a886", "size": 413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deps/MFEM/FemToGaussPoints/TestFemToGaussPoints.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": "deps/MFEM/FemToGaussPoints/TestFemToGaussPoints.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": "deps/MFEM/FemToGaussPoints/TestFemToGaussPoints.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": 21.7368421053, "max_line_length": 56, "alphanum_fraction": 0.602905569, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7640446871148846}}
{"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\u03b51, \u03b52, \u0394 = coeffs[1], coeffs[2], coeffs[3]\n\tcos2t, sin2t = cos(2*t), sin(2*t)\n\tg = (\u03b51*cos2t + \u03b52*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] = \u0394/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\u03b51, \u03b52, \u0394 = coeffs[1], coeffs[2], coeffs[3]\n\tcos2t, sin2t = cos(2*t), sin(2*t)\n\tg = (\u03b51*cos2t + \u03b52*sin2t)*(1 - cos(2*pi*t/tf))\n\t\u039bt = \u039b(t,tf)\n\tcosh2\u039b, sinh2\u039b = cosh(2*\u039bt), sinh(2*\u039bt)\n\tW = zeros(Float64, 3)\n\tW[1] = g*cos2t*cosh2\u039b + (\u0394/2 + g)*sinh2\u039b\n\tW[2] = g*sin2t\n\tW[3] = g*cos2t*sinh2\u039b + (\u0394/2 + g)*cosh2\u039b\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*\u039b(t,tf))\n\t\t\t\t\t\t\t\t+ 2*cos(2*t)*sinh(2*\u039b(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*\u039b(t,tf))\n\t\t\t\t\t\t\t\t+ 2*sin(2*t)*sinh(2*\u039b(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*\u039b(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*\u039b(t,tf))\n\t\t\t\t\t\t\t\t+ 2.0*cos(2*t)*cosh(2.0*\u039b(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*\u039b(t,tf))\n\t\t\t\t\t\t\t\t+ 2.0*sin(2*t)*cosh(2.0*\u039b(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*\u039b(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 * \u03c9(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 * \u03c9(4N, 0) * A[1]\n    for k in 2:N\n        B[k] = \u03c9(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 * \u03c9(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 * \u03c9(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 * \u03c9(4Nx, 0) * A[1, j]\n    end\n\n    for j in 1:Ny, i in 2:Nx\n        B[i, j] = \u03c9(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 * \u03c9(4Ny, 0) * C[i, 1]\n    end\n\n    for j in 2:Ny, i in 1:Nx\n        D[i, j] = \u03c9(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\u03c0) \\\\[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\u03c0].\n    M = mod(M,2\u03c0)\n\n    # Initial guess.\n    #\n    # See [1, p. 75].\n    E = (M > \u03c0) ? 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\u03c0].\n    mod(E, 2\u03c0)\nend\n\n\"\"\"\n    M_to_f(e::Number, M::Number, tol::Number = 1e-10)\n\nCompute the true anomaly (0,2\u03c0) \\\\[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\u03c0].\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\u03c0) \\\\[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*\u03c0].\n    mod( 2atan(sqrt(1+e)*sin_Eo2, sqrt(1-e)*cos_Eo2) , 2\u03c0 )\nend\n\n\"\"\"\n    E_to_M(e::Number, E::Number)\n\nCompute the mean anomaly (0,2\u03c0) \\\\[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\u03c0)\n\n################################################################################\n#                              From True Anomaly\n################################################################################\n\n\"\"\"\n    f_to_E(e::Number,f::Number)\n\nCompute the eccentric anomaly (0,2\u03c0) \\\\[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\u03c0 )\nend\n\n\"\"\"\n    f_to_E(orb::Orbit)\n\nCompute the eccentric anomaly (0,2\u03c0) \\\\[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\u03c0) \\\\[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\u03c0].\n    E_to_M(e,E)\nend\n\n\"\"\"\n    f_to_M(orb::Orbit)\n\nCompute the mean anomaly (0,2\u03c0) \\\\[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(\u03b8, \u03d5, r) = begin\n    (\n        x=r * sin(\u03b8)cos(\u03d5),\n        y=r * sin(\u03b8)sin(\u03d5),\n        z=r * cos(\u03b8)\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    \u03b8 = acos(z / r)\n    \u03d5 = atan(y, x)\n    (\n        \u03b8=\u03b8,\n        \u03d5=\u03d5,\n        r=r\n    )\nend\n# convert to domain \u03b8 \u2208[0\u00b0, 180\u00b0], \u03d5\u2208 [-180\u00b0, 180\u00b0]\n# bad implementation\nfunction mod_angle(\u03b8, \u03d5)\n    sign = x -> x >= 0 ? 1 : -1\n    item1 = -sign.(mod2pi.(\u03b8) .- \u03c0)\n    \u03b8_ = mod1.(\u03b8 .* item1, \u03c0)\n    \u03b8_[\u03b8.==0] .= 0\n    \u03d5_ = item1 .* \u03d5 .|> mod2pi\n    (\u03b8_, \u03d5_)\nend\nfunction mod_angle(\u03b8::Number, \u03d5)\n    sign = x -> x >= 0 ? 1 : -1\n    item1 = -sign(mod2pi(\u03b8) - \u03c0)\n    \u03b8_ = (\u03b8==0 ?  0.0 : mod1(\u03b8 * item1, \u03c0))\n    \u03d5_ = (item1 .* \u03d5) .|> mod2pi\n    (\u03b8_, \u03d5_)\nend\n\n# convert to domain \u03b8 \u2208[0\u00b0, 180\u00b0], \u03d5\u2208 [-180\u00b0, 180\u00b0]\nfunction mod_angle_deg(\u03b8::Number, \u03d5)\n    \u03b8_res = 0.\n    \u03d5_res = 0.\n    invert_\u03d5 = false\n    # in domain\n    if \u03b8 >= 0 && \u03b8 <= 180\n        \u03b8_res = \u03b8\n    elseif \u03b8 < 0 && \u03b8 >= -180\n        invert_\u03d5 = true \n        \u03b8_res = -\u03b8\n    else\n        throw(\"\u03b8 = $(\u03b8) is out of range [-180,180]\")\n    end\n\n    if \u03d5 >=-180 && \u03d5 <= 180\n        \u03d5_res = \u03d5\n    elseif \u03d5 > 180 && \u03d5 <=360\n        \u03d5_res = \u03d5 - 360\n    else\n        throw(\"\u03d5 = $(\u03d5) is out of range [-180,360]\")\n    end\n\n    if invert_\u03d5\n        if \u03d5_res <= 0\n            \u03d5_res += 180\n        else\n            \u03d5_res -= 180\n        end\n    end\n    \u03b8_res, \u03d5_res\nend\n\n# not test\nfunction mod_angle_rad(\u03b8::Number, \u03d5)\n    \u03b8_res = 0.\n    \u03d5_res = 0.\n    invert_\u03d5 = false\n    # in domain\n    if \u03b8 >= 0 && \u03b8 <= pi\n        \u03b8_res = \u03b8\n    elseif \u03b8 < 0 && \u03b8 >= -pi\n        invert_\u03d5 = true \n        \u03b8_res = -\u03b8\n    else\n        throw(\"\u03b8 = $(\u03b8) is out of range [-pi, pi]\")\n    end\n\n    if \u03d5 >=-pi && \u03d5 <= pi\n        \u03d5_res = \u03d5\n    elseif \u03d5 > pi && \u03d5 <=2pi\n        \u03d5_res = \u03d5 - 2pi\n    else\n        throw(\"\u03d5 = $(\u03d5) is out of range [-pi, 2pi]\")\n    end\n\n    if invert_\u03d5\n        if \u03d5_res <= 0\n            \u03d5_res += pi\n        else\n            \u03d5_res -= pi\n        end\n    end\n    \u03b8_res, \u03d5_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#\u00a0should/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#\u00a0function 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#\u00a0function 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#\u00a0we 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\u00f73\n    \u03bcs = xs[begin:nmodes]\n    \u03c3s = xs[nmodes+1:2nmodes]\n    ws = xs[2nmodes+1:end]\n    ws = ws ./ sum(ws)\n\n    return truncated(MixtureModel(Normal, zip(\u03bcs, \u03c3s) |> 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                           \u03bc_bounds   = (0.0,  40.0),\n                           \u03c3_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(\u2026)), 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                             \u03bc_bounds = (0.0,  40.0),\n                             \u03c3_bounds = (1e-3, 10.0),\n                             w_bounds = (0.05, 1.0))\n    \u03bc_lo, \u03bc_hi = \u03bc_bounds\n    \u03c3_lo, \u03c3_hi = \u03c3_bounds\n    w_lo, w_hi = w_bounds\n\n    \u03bc_lower = fill(\u03bc_lo, nmodes)\n    \u03c3_lower = fill(\u03c3_lo, nmodes)\n    w_lower = fill(w_lo, nmodes)\n    \u03bc_upper = fill(\u03bc_hi, nmodes)\n    \u03c3_upper = fill(\u03c3_hi, nmodes)\n    w_upper = fill(w_hi, nmodes)\n\n    lower = vcat(\u03bc_lower, \u03c3_lower, w_lower)\n    upper = vcat(\u03bc_upper, \u03c3_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": "import Pkg\nPkg.add(\"Plots\")\nPkg.add(\"PyPlot\")\nimport Plots as plt\nplt.pyplot()\n\ninclude(\"./solver.jl\")\nimport .solver as sol\nimport LinearAlgebra as lina\n\n\n# function f(t::Float64, y::AbstractVector{Float64})::AbstractVector{Float64}\n#     return y\n# end\n\n# a = 0.0\n# b = 10.0\n# h = 0.1\n# y_euler = sol.euler([1.0], f, a, b, h)\n# y_midpoint = sol.midpoint([1.0], f, a, b, h)\n\n# k = ceil(Integer, (b - a) / h)\n# t_range = range(a, stop=b, length=k)\n# y_true = exp.(t_range)\n# p = plt.plot(t_range, y_true, label=\"true\")\n# plt.plot!(t_range, lina.transpose(y_euler), label=\"Euler\")\n# plt.plot!(t_range, lina.transpose(y_midpoint), label=\"midpoint\")\n# plt.png(p, \"solver/exp_plot.png\")\n\nfunction f_lorenz(t::Float64, y::AbstractVector{Float64})::AbstractVector{Float64}\n    return [\n   -y[2] - y[3]\n   y[1] + 0.2 * y[2]\n   0.2 + y[1] * y[3] - 5.7 * y[3]\n ]\nend\n\na = 0.0\nb = 200.0\nh = 0.01\nprintln(\"starting\")\ny_midpoint = sol.midpoint([-1.0; 0; 0], f_lorenz, a, b, h)\nprintln(\"finished\")\ny_trans = lina.transpose(y_midpoint)\np = plt.plot(y_trans[:,1], y_trans[:,2], y_trans[:,3], label=\"\")\nplt.png(p, \"solver/lorenz.png\")", "meta": {"hexsha": "8a5d7aca4aeedadb1a2d785c31ed8617795bd8e5", "size": 1118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ode/solver/main.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/main.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/main.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": 24.3043478261, "max_line_length": 82, "alphanum_fraction": 0.6341681574, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7639989365431592}}
{"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": "using PyPlot\n\n# debug\nfunction say(sth)\n  println(sth)\nend\n\nXI100 = 124.342\nXI80 = 101.879\n\nfunction test_a(;verbose=true)\n  n = 10000\n  bins = 101\n\n  U = rand(n)\n\n  (range, counts) = hist(U, 0:1/bins:1)\n\n  D = sum((counts - n/bins).^2/(n/bins))\n\n  verbose ? say(\"n=$n, bins=$bins, D=$(round(D*1000)/1000) $(D>XI100?\"> $XI100, Reject H0, bad random\":\"< $XI100, Fail to reject H0, good random\")\") : nothing\n\n  D\nend\n\n# dist\nfunction chi_square(x, nu)\n  x.^(nu/2-1).*exp(-x/2)./(2^(nu/2)*gamma(nu/2))\nend\n\nfunction test_c(;verbose=true)\n  n = 10000\n  k0 = 9\n  bins = k0^2\n  ind(x) = floor(x*9)\n\n  U = rand(n,2)\n\n  Data = [Float64(k0 * ind(U[i,1]) + ind(U[i,2])) for i=1:n]\n\n  (range, counts) = hist(Data[:], -1:80)\n\n  D = sum((counts - n/bins).^2/(n/bins))\n\n  verbose ? say(\"n=$n, k0=$k0, bins=$bins, D=$(round(D*1000)/1000) $(D>XI80?\"> $XI80, Reject H0, bad random\":\"< $XI80, Fail to reject H0, good random\")\") : nothing\n\n  D\nend\n", "meta": {"hexsha": "d9bcf5abf6cadd4483aed2b8afeff41fbd9f1234", "size": 929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "common.jl", "max_stars_repo_name": "innerlee/testRand", "max_stars_repo_head_hexsha": "0adcffee0ef61bc2009bfa0623ee3b05b1b9b558", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common.jl", "max_issues_repo_name": "innerlee/testRand", "max_issues_repo_head_hexsha": "0adcffee0ef61bc2009bfa0623ee3b05b1b9b558", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common.jl", "max_forks_repo_name": "innerlee/testRand", "max_forks_repo_head_hexsha": "0adcffee0ef61bc2009bfa0623ee3b05b1b9b558", "max_forks_repo_licenses": ["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.9591836735, "max_line_length": 163, "alphanum_fraction": 0.5834230355, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.76399893259757}}
{"text": "using ClassicalOrthogonalPolynomials, Test\nimport ClassicalOrthogonalPolynomials: OrthogonalPolynomialRatio, recurrencecoefficients\n\n@testset \"OrthogonalPolynomialRatio\" begin\n    P = Legendre()\n    R = OrthogonalPolynomialRatio(P,0.1)\n    @test P[0.1,1:10] ./ P[0.1,2:11] \u2248 R[1:10]\n    R = OrthogonalPolynomialRatio(P,-1)\n    @test R[1:10] \u2248 fill(-1,10)\nend", "meta": {"hexsha": "1730d7e3d2fee56220ced09a701117604344c4a2", "size": 358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_ratios.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": "test/test_ratios.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": "test/test_ratios.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": 35.8, "max_line_length": 88, "alphanum_fraction": 0.7346368715, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.763937643623459}}
{"text": "using IntervalArithmetic, StaticArrays, IntervalRootFinding\nusing Test\n\nfunction rand_vec(n::Int)\n    a = randn(n)\n    A = Interval.(a)\n    mA = MVector{n}(A)\n    sA = SVector{n}(A)\n    return A, mA, sA\nend\n\nfunction rand_mat(n::Int)\n    a = randn(n, n)\n    A = Interval.(a)\n    mA = MMatrix{n, n}(A)\n    sA = SMatrix{n, n}(A)\n    return A, mA, sA\nend\n\n@testset \"Linear Equations\" begin\n\n    As = [[2..3 0..1; 1..2 2..3], ]\n    bs = [[0..120, 60..240], ]\n    xs = [[-120..90, -60..240], ]\n\n    for i in 1:10\n        rand_A = rand_mat(i)[1]\n        rand_x = rand_vec(i)[1]\n        rand_b = rand_A * rand_x\n        push!(As, rand_A)\n        push!(bs, rand_b)\n        push!(xs, rand_x)\n    end\n\n    n = length(As)\n\n\n    for solver in (gauss_seidel_interval, gauss_seidel_contractor, gauss_elimination_interval, \\)\n        @testset \"Solver $solver\" begin\n            #for precondition in (false, true)\n\n                for i in 1:n\n                    soln = solver(As[i], bs[i])\n                    @test all(xs[i] .\u2286 soln)\n\n                end\n            #end\n        end\n    end\nend\n", "meta": {"hexsha": "8b7209989fa021fe72f0ca03c13d16b7059fb5a8", "size": 1083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 21.2352941176, "max_line_length": 97, "alphanum_fraction": 0.5198522622, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409306, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7639376397255788}}
{"text": "using DataStructures\n\nfunction check(x, as)\n    N = length(as)\n    tmps = [(a < x) ? -1 : 1 for a in as]\n    ss = vcat(0, cumsum(tmps))\n    ps = sortperm(ss)\n    bs = FenwickTree{Int}(length(ps))\n\n    q_inv = 0\n    for p in ps\n        q_inv += prefixsum(bs, p)\n        inc!(bs, p, 1)\n    end\n\n    return 2q_inv \u2265 N * (N +1) \u00f7 2\nend\n\nfunction main()\n    N = parse(Int, readline())\n    as = parse.(Int, split(readline()))\n\n    x\u0332, x\u0304 = minimum(as), maximum(as)\n    while x\u0304 - x\u0332 > 1\n        x = (x\u0332 + x\u0304) \u00f7 2\n        \n        if check(x, as)\n            x\u0332 = x\n        else\n            x\u0304 = x\n        end\n    end\n    \n    if check(x\u0304, as)\n        println(x\u0304)\n    else\n        println(x\u0332)\n    end\n\nend\n\nmain()\n", "meta": {"hexsha": "e447d7abbe7fdf96de8eee68db2a0c63217a0ab2", "size": 707, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/chapter06/nicetak/arc101_b.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/arc101_b.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/arc101_b.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": 16.4418604651, "max_line_length": 41, "alphanum_fraction": 0.4540311174, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7639376382319459}}
{"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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.21\"\n\n# \u2554\u2550\u2561 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tcUnif = Uniform(0,2\u03c0)\n\txGrid, N = 0:0.1:2\u03c0, 10^6\nend\n\n# \u2554\u2550\u2561 287be85a-2165-11eb-2609-eba593feae95\nbegin\n\tstephist( rand(N)*2\u03c0, 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:\u03c0/2:2\u03c0;],\n\t\t[\"0\", L\"\\dfrac{\\pi}{2}\", L\"\\pi\", L\"\\dfrac{3\\pi}{2}\", L\"2\\pi\"]))\nend\n\n# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.21\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550287be85a-2165-11eb-2609-eba593feae95\n# \u255f\u250070182cd8-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 \u2208 IntervalDomain(0.0,1.0),\n           x \u2208 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 \u2208 IntervalDomain(t_min,t_max),\n           x \u2208 IntervalDomain(x_min,x_max),\n           y \u2208 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 \u2208 IntervalDomain(0.0,1.0),\n           r \u2208 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": "function GenAmericanBinomialDownOutCall(K, T, S, sig, r, H, N)\n\n        ## as discussed in clewlow and strickland chapter 2, figure 2.12\n        ## deviates as different stepping through the matrix requires sometimes\n        ## to make use of * instead of /\n\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  dpu = disc*pu\n  dpd = disc * pd\n  edxud = exp(dxu - dxd)\n  edxd = exp(dxd)\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] / edxud\n  end\n\n\n  # create Array for options value tree\n\n  P = zeros(Float64, (N+1, N+1))#linspace(1, N+1, N+1)\n\n  # Initialise Option Values at maturity\n\n\nfor j in 1:(N+1)\n\n  if St[j, N+1] > H ## check if market price is above knock out\n\n    C[j, N+1] = max(0.0, St[j, N+1] - K)\n\n  else\n\n    C[j, N+1] = 0.0 ## if below, assign 0 to the call value\n\n  end\n\nend\n\n  # Stepping back through the tree\n\nfor i = linrange(N, 1, N)\n\n  for j in 1:i\n\n    St[j,i] = St[j,i+1] * edxd  ## generating the asset price at node i, j first\n\n    if St[j,i] > H ## checking if asset above knock out\n\n      C[j, i] = dpu * C[j, i+1] + dpd * C[j+1, i+1]\n      C[j, i] = max(C[j, i], St[j,i] - K)\n\n    else\n\n      C[j,i] = 0.0  ## apply 0 if not\n\n    end\n\n  end\n\nend\n\n\n\n\nC, St\nend\n\n", "meta": {"hexsha": "90c1124edd9e0bd12d06bb6f6fd250a916304ec4", "size": 1445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IB/PricingEngines/GenAmericanBinomialDownOutCall.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/GenAmericanBinomialDownOutCall.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/GenAmericanBinomialDownOutCall.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.6219512195, "max_line_length": 80, "alphanum_fraction": 0.5564013841, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7638818209695738}}
{"text": "# Setting up Bayesian inference, plotting distributions and\n# Bayesian linear regression\nusing Plots\nusing Distributions\n\n\n\u03bc = 5.0\n\u03c3 = 4.0\nn = 1000\nlim = 10\nx = range(0, stop = lim, length=1000)\n\nf(\u03bc, \u03c3, x) = \u03bc .+ (\u03c3 * rand(Normal(0,1),lim))\n\ny = f(\u03bc, \u03c3, x)\n\nfunction likelihood!(y, n, sd)\n    yy = repeat(y, outer=(1,n))\n    ran = range(0, stop = length(y), length = n)\n    xx = repeat(ran, outer=(1, length(y)))'\n    likelihood = exp.(-0.5 * sum((yy .- xx ).^2,dims=1) / \u03c3^2)\n    norm_likelihood = likelihood / sum(likelihood)\n    return norm_likelihood\nend\n\nlikelihood = likelihood!(y, n, \u03c3)\n\n\u03c1 = exp.((-0.5 .* (x .- 0 ).^2) / 5^2)\n\u03c1 = \u03c1/sum(\u03c1)\n\nplot(x, likelihood[1,:])\nplot!(x, \u03c1)\nscatter!(y, zeros(n))\n\n#= Linear regression \nUse linear regression to estimate the posterior mean and std \ny = B*x + e\ne = N(0,s^2)\n\ny = N(B^T * x, s^2 * I)\n=#\n\nbeta1 = 1 / \u03c3^2\nbeta2 = 1 / 5^2 \n \npost_\u03c3 = 1 / \u221a(lim * beta1 + beta2)\npost_\u03bc = (lim * beta1 * mean(y) + beta2 * 0) / (lim * beta1 + beta2)\n\nposterior = pdf(Normal(post_\u03bc, post_\u03c3), x)\nposterior = posterior/sum(posterior)\n\nplot!(x, posterior)", "meta": {"hexsha": "cded84e8195f70487ee08fd1f830c5abf7a6af8e", "size": 1088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia_tutorials/Bayesian_model_fitting.jl", "max_stars_repo_name": "PavanChaggar/Bayesian_inference", "max_stars_repo_head_hexsha": "2a00d8f9fc391c6529c001be617a776a6b60c87b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-22T18:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T12:06:50.000Z", "max_issues_repo_path": "julia_tutorials/Bayesian_model_fitting.jl", "max_issues_repo_name": "PavanChaggar/Bayesian_inference", "max_issues_repo_head_hexsha": "2a00d8f9fc391c6529c001be617a776a6b60c87b", "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_tutorials/Bayesian_model_fitting.jl", "max_forks_repo_name": "PavanChaggar/Bayesian_inference", "max_forks_repo_head_hexsha": "2a00d8f9fc391c6529c001be617a776a6b60c87b", "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.9230769231, "max_line_length": 68, "alphanum_fraction": 0.6047794118, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7638818205816218}}
{"text": "using KrylovMethods\nusing Base.Test\n\nprintln(\"=== Testing bicgstb for real matrix === \")\nA  = sprandn(100,100,.1) + 10*speye(100)\nD  = diag(A)\nAf(x) = A*x \nM(x)  = D.\\x\nrhs = randn(100)\n\n# test flag for early stopping\nxt = bicgstb(A,rhs,tol=1e-6,maxIter=3,out=2,storeInterm=true)\n@test xt[2]==-1\n\n# test handling of zero rhs\nxt = bicgstb(A,zeros(size(A,2)),tol=1e-6,maxIter=3,out=2)\n@test  all(xt[1].==0)\n@test xt[2]==-9\n\n\nx0 = bicgstb(full(A),rhs,tol=1e-6)\nx1 = bicgstb(A,rhs,tol=1e-6,out=1)\nx2 = bicgstb(Af,rhs,tol=1e-6)\nx3 = bicgstb(Af,rhs,tol=1e-6,maxIter=100,x=randn(size(rhs)))\nx5 = bicgstb(Af,rhs,tol=1e-6,maxIter=100,M1=M)\n\n@test norm(A*x0[1]-rhs)/norm(rhs) < 1e-6\n@test norm(A*x1[1]-rhs)/norm(rhs) < 1e-6\n@test norm(A*x2[1]-rhs)/norm(rhs) < 1e-6\n@test norm(A*x3[1]-rhs)/norm(rhs) < 1e-6\n@test norm(A*x5[1]-rhs)/norm(rhs) < 1e-6\n@test norm(x2[1]-x1[1])/norm(x1[1]) < 1e-12\n@test norm(x3[1]-x1[1])/norm(x1[1]) < 1e-5\n@test norm(x0[1]-x1[1])/norm(x1[1]) < 1e-5\n\nprintln(\"Testing bicgstb for complex matrix\")\nA  = sprandn(100,100,.1) + 10*speye(100) + im*(sprandn(100,100,.1) + 10*speye(100) )\nD  = diag(A)\nAf(x) = A*x \nM(x)  = D.\\x\nrhs = randn(100) + 1im * randn(100)\n\nx1 = bicgstb(A,rhs,tol=1e-6)\nx2 = bicgstb(Af,rhs,tol=1e-6)\nx3 = bicgstb(Af,rhs,tol=1e-6,maxIter=200,x=randn(size(rhs))+im*randn(size(rhs)))\nx4 = bicgstb(Af,rhs,tol=1e-6,maxIter=200,M1=M)\n\n@test norm(A*x1[1]-rhs)/norm(rhs) < 1e-6\n@test norm(A*x2[1]-rhs)/norm(rhs) < 1e-6\n@test norm(A*x3[1]-rhs)/norm(rhs) < 1e-6\n@test norm(A*x4[1]-rhs)/norm(rhs) < 1e-6\n@test norm(x2[1]-x1[1])/norm(x1[1]) < 1e-12\n@test norm(x3[1]-x1[1])/norm(x1[1]) < 1e-5\n\nprintln(\"=== BICGSTB: All tests passed ===\")", "meta": {"hexsha": "0da0d911ba075db62545c09cb7e53b69303b2c79", "size": 1659, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testBICGSTB.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": "test/testBICGSTB.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": "test/testBICGSTB.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": 30.1636363636, "max_line_length": 84, "alphanum_fraction": 0.6292947559, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7638818135768649}}
{"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": "@testset \"reconstruction_matrix.jl\" begin\n    a = 0.0\n    b = 2\u03c0\n    N = 100\n    M = N\n    \u0394x = (b - a) / N\n\n    # Domains\n    closed_interval = ClosedIntervalDomain(a, b)\n    periodic_interval = PeriodicIntervalDomain(a, b)\n    unknown_domain = UnknownDomain()\n\n\n    ## Identity filter\n    f = IdentityFilter()\n\n    # ClosedIntervalDomain\n    R = reconstruction_matrix(f, closed_interval, M, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N + 1, M + 1)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    R = reconstruction_matrix(f, periodic_interval, M, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N, M)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception reconstruction_matrix(f, unknown_domain, M, N)\n\n\n    ## Top hat filter\n    h\u2080 = 0.05\n    h = x -> h\u2080 * (1 - 1 / 2 * cos(x))\n    f = TopHatFilter(h)\n\n    # ClosedIntervalDomain\n    R = reconstruction_matrix(f, closed_interval, M, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N + 1, M + 1)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    R = reconstruction_matrix(f, periodic_interval, M, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N, M)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception reconstruction_matrix(f, unknown_domain, M, N)\n\n\n    ## Convolutional filter\n    \u03c3 = \u0394x\n    g = GaussianFilter(\u03c3)\n\n    # ClosedIntervalDomain\n    R = reconstruction_matrix(g, closed_interval, M, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N + 1, M + 1)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    R = reconstruction_matrix(g, periodic_interval, M, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N, M)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception reconstruction_matrix(f, unknown_domain, M, N)\n\n\n    ## Constant mesh-wide top hat filter\n    h = x -> \u0394x / 2\n    f = TopHatFilter(h)\n\n    # ClosedIntervalDomain\n    R = reconstruction_matrix_meshwidth(f, closed_interval, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N + 1, N + 1)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    R = reconstruction_matrix_meshwidth(f, periodic_interval, N)\n    @test R isa SparseMatrixCSC\n    @test size(R) == (N, N)\n    @test all(sum(R, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception reconstruction_matrix_meshwidth(f, unknown_domain, N)\nend\n", "meta": {"hexsha": "852db6c65b996fd0f46d595145694eef04d2eee5", "size": 2472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/matrices/reconstruction_matrix.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": "test/matrices/reconstruction_matrix.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": "test/matrices/reconstruction_matrix.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": 26.5806451613, "max_line_length": 80, "alphanum_fraction": 0.6254045307, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399244, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7638818071050647}}
{"text": "using Distributions\r\nusing SDE\r\nusing Base.Test\r\nsrand(8)\r\n# sum([ norm(mean([ sample(MvWiener(d),  linspace(0.,2.,5)).X[1,end] for i in 1:n])) for j in 1:1000] .< r*sqrt(2/n)) \r\n#tests with alpha 0.01\r\n\r\n\r\nn = 1000\r\nd= 2\r\n\r\n#0.99 quantile vor mean of sum of squares of d-dimensional normals\r\n#r = sqrt(quantile(Distributions.Chisq(d), 0.99))\r\nr = sqrt(9.211) # for d = 2\r\n\r\n#  call 'sample(t,MvWiener(d)).X[:,i]' n times\r\nfunction Wn(d, t, n, i)\r\n wn = zeros(d, n)\r\n for j in 1:n\r\n   wn[:, j] = sample(t, Wiener(d)).yy[:,i]\r\n end\r\n wn\r\nend\r\n  \r\n@test size(sample(linspace(3.,4.,2), Wiener(d)).yy) == (d,2)\r\n \r\n# the mean and variance of a Brownian motion at t=2 is 0 and 2\r\n@test norm(mean([ sample(linspace(0.,2.,5),Wiener(d)).yy[:,end] for i in 1:n])) < r*sqrt(2/n) #scale with std(W_2)/sqrt(n)\r\n#chiupper =  quantile(Distributions.Chisq(n), 0.995) #upper 0.005 percentile  \r\n#chilower = quantile(Distributions.Chisq(n), 0.005) #lower 0.005 percentile  \r\n\r\nchiupper = 1119 #n = 1000, 0.995\r\nchilower = 888.5\r\n\r\n@test chiupper > n*var( Wn(1, linspace(0.,2.,5), n, 5))/2 > chilower\r\n\r\n\r\n# check that W(2) has the right covariance matrix\r\n@test (d-> norm(cov( Wn(d, linspace(0.,2.,5), n, 5)') - diagm(2ones(d)))*sqrt(n)/sqrt(d))(50) < 5. # did not figure that out exactly, should fail less then 99 %\r\n@test (d-> norm(cov( Wn(d,[0.,0.1, 0.3, 0.5, 2.], n, 5)') - diagm(2ones(d)))*sqrt(n)/sqrt(d))(50) < 5. # did not figure that out exactly, should fail less then 99 %\r\n\r\n\r\n\r\n\r\nfunction Bn(d, u, v, t, n, i)\r\n wn = zeros(d, n)\r\n for j in 1:n\r\n   wn[:, j] = samplebridge(t, u, t[end], v, Wiener(d)).yy[:,i]\r\n end\r\n wn\r\nend\r\n \r\n\r\n# a \"deterministic\" bridge with only start end endpoint\r\n@test (global t1 = norm(samplebridge( linspace(1.,4.,2), [1.,2.], 4., [5.,7.], Wiener(2)).yy - [1. 5.; 2. 7.])) < eps(10.)\r\n\r\n# Check that the bridge has the right mean and Variance\r\n\r\n# Covariance of a Brownian bridge from t_1 to t_2 (t_2-t)(s-t_1)/(t_2-t_1)\r\n# here (3-0.5)*(0.5-0)/(3) = 0.4166666666666667\r\n\r\n#cq = quantile(Distributions.Chisq(2), 0.99)\r\nqchisq = 9.21034037197618\r\n@test norm(mean(Bn(2,[1.,2.], [5.,7.],[1.,1.1, 1.3, 1.5, 3.], n, 4),2) -  [1.,2.] - ([5.,7.] - [1.,2.])*.5/2) < sqrt(qchisq)*sqrt(0.416/n)\r\n\r\n # (3-0.5)*(0.5-0.1)/(2.9) = 0.3448275862068966\r\n@test  chilower < n*var(Bn(1,[1.], [5.],[0.1, 0.3, 0.5, 3.], n, 3),2 )[1]/0.345  <  chiupper\r\n\r\n\r\n", "meta": {"hexsha": "5d632d7324de9d06dee285f4ac529b3570961b3d", "size": 2356, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsde.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": "test/testsde.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": "test/testsde.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": 33.6571428571, "max_line_length": 165, "alphanum_fraction": 0.5895585739, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7638638176523309}}
{"text": "using DiscreteChoice\nusing JLD2\nusing ForwardDiff\nusing Optim\nusing StatsBase\n\n@load \"example/data/homo.jld2\" Y X \u03b2 \u03be\n\nP = zeros(10)\n[P[i] = mean(Y.==i) for i in 1:10]\nsum(P)\n\nfunction y_prob(X, \u03b2, \u03be)\n    \u03be = vcat(zero(eltype(\u03be)), \u03be)\n    index = exp.(X*\u03b2 .+ \u03be)\n    y_prob = index ./ sum(index)\n    return y_prob\nend\n\n\n\nmodel_1 = DCModel(Y, X; hetero_preference=false)\nmodel_2 = DCModel(Y, X; hetero_preference=false)\n\n# Start from true value\nestDCModel!(model_1; init_guess = vcat(\u03b2, \u03be))\nabs.(Optim.minimizer(model_1.optResults) .- vcat(\u03b2, \u03be)) |> maximum\nupdateCoef!(model_1)\n\nP .- y_prob(model_1.X, model_1.\u03b2, model_1.\u03be)\n\n# Start from random value\nestDCModel!(model_2; init_guess = randn(length(\u03b2)+length(\u03be)))\nupdateCoef!(model_2)\n\ny_emp = y_prob(model_2.X, model_2.\u03b2, model_2.\u03be)\nP .- y_emp \n# Notice that this can perfectly match the data. Why? \n# simple reason is that the number of products is too small !!\n# Because there are only 10 products, essentially only 10 data points, too many dimensions\n# This will get changed if we include individual demographics into the data\n\nabs.(Optim.minimizer(model_2.optResults) .- vcat(\u03b2, \u03be)) |> maximum\nOptim.minimizer(model_2.optResults) .- vcat(\u03b2, \u03be)\n\n\u03b2\n\u03be\n# Why does the random starting value performs poorly? Is this some non-identification issue?\n\nres_homo = opt_homo(Y, X, vcat(\u03b2, \u03be))\n\n\n\n", "meta": {"hexsha": "ebc35580a24f7bbbdaf5ec1e7cd2b8c3782c257a", "size": 1336, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_homo.jl", "max_stars_repo_name": "kdzhang/DiscreteChoice.jl", "max_stars_repo_head_hexsha": "97441db6451239c50a78a5e37a40c81a2160b1b8", "max_stars_repo_licenses": ["MIT"], "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_homo.jl", "max_issues_repo_name": "kdzhang/DiscreteChoice.jl", "max_issues_repo_head_hexsha": "97441db6451239c50a78a5e37a40c81a2160b1b8", "max_issues_repo_licenses": ["MIT"], "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_homo.jl", "max_forks_repo_name": "kdzhang/DiscreteChoice.jl", "max_forks_repo_head_hexsha": "97441db6451239c50a78a5e37a40c81a2160b1b8", "max_forks_repo_licenses": ["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.7407407407, "max_line_length": 92, "alphanum_fraction": 0.7163173653, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7638638147040856}}
{"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) \u03c0^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": "# Part 1\ndata = readlines(\"day13_input.txt\")\nearliest = parse(Int64, first(data))\nids = [parse(Int64, id) for id in split(last(data), \",\") if id != \"x\"]\nwaitingtimes = [ceil(Int, earliest / id) * id - earliest for id in ids]\nprintln(\"Part 1: answer = $(ids[argmin(waitingtimes)] * minimum(waitingtimes))\")\n\n# Part 2 - each id, delta pair fulfils equation t + delta_i = N * id_i\n# i.e. (t + delta_i) (mod id_i) = 0\nfunction findt(deltas)\n    t = first(deltas)[2]\n    modulo = first(deltas)[1]\n    for (id, delta) in deltas[2:end]\n        while (t + delta) % id != 0 t += modulo end\n        modulo = lcm(modulo, id)\n    end\n    t\nend\n\ndeltas = [(parse(Int64, id), i-1) for (i, id) in enumerate(split(last(data), \",\")) if id != \"x\"]\nprintln(\"Part 2: $(findt(deltas))\")", "meta": {"hexsha": "aaf5e1ac4d4a76f6f600100e66fc68cdfd674601", "size": 765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/day13.jl", "max_stars_repo_name": "ericgreveson/adventofcode", "max_stars_repo_head_hexsha": "6671ef8c16a837f697bb3fb91004d1bd892814ba", "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": "2020/day13.jl", "max_issues_repo_name": "ericgreveson/adventofcode", "max_issues_repo_head_hexsha": "6671ef8c16a837f697bb3fb91004d1bd892814ba", "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": "2020/day13.jl", "max_forks_repo_name": "ericgreveson/adventofcode", "max_forks_repo_head_hexsha": "6671ef8c16a837f697bb3fb91004d1bd892814ba", "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.4285714286, "max_line_length": 96, "alphanum_fraction": 0.614379085, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7638638009853894}}
{"text": "using PyPlot\nx=logspace(-2,2,1000)\nclf()\nplot(x,log.(2x),label=L\"$f(x)=\\log{(2x)}$\")\nloglog(x,asinh.(x),label=L\"$f(x)=\\sinh^{-1}{x}$\")\nloglog(x,x,label=L\"$f(x)=x$\")\nlegend(loc=\"upper left\")\nylabel(L\"$f(x)$\")\nxlabel(L\"$x$\")\n", "meta": {"hexsha": "966703307e85cc028ce6a89f49183397081b14e3", "size": 223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/deprecated/figures/asinh_vs_log.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/figures/asinh_vs_log.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/figures/asinh_vs_log.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": 22.3, "max_line_length": 49, "alphanum_fraction": 0.5874439462, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7638637998051316}}
{"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": "       # centroid\n        @test centroid(tri) \u2248 Point2D{T}(1//3, 1//3)\n\n                # centroid\n        @test centroid(tri) \u2248 Point3D{T}(0, 1//3, 1//3)\n\n\n   # centroid\n        @test centroid(quad) \u2248 Point2D{T}(1//2, 1//2)\n\n                    # centroid\n            p\u2081 = Point2D{T}(0, 0)\n            p\u2082 = Point2D{T}(1, 0)\n            p\u2083 = Point2D{T}(0, 1)\n            p\u2084 = Point2D{T}(1//2, 0)\n            p\u2085 = Point2D{T}(1//2, 1//2)\n            p\u2086 = Point2D{T}(0, 1//2)\n            tri6 = QuadraticTriangle(p\u2081, p\u2082, p\u2083, p\u2084, p\u2085, p\u2086)\n            @test centroid(tri6) \u2248 tri6(1//3, 1//3)\n\n\n        # centroid\n        p\u2081 = Point2D{T}(0, 0)\n        p\u2082 = Point2D{T}(1, 0)\n        p\u2083 = Point2D{T}(1, 1)\n        p\u2084 = Point2D{T}(0, 1)\n        p\u2085 = Point2D{T}(1//2,    0)  \n        p\u2086 = Point2D{T}(   1, 1//2)\n        p\u2087 = Point2D{T}(1//2,    1)  \n        p\u2088 = Point2D{T}(   0, 1//2)\n        quad8 = QuadraticQuadrilateral(p\u2081, p\u2082, p\u2083, p\u2084, p\u2085, p\u2086, p\u2087, p\u2088) \n        @test centroid(quad8) \u2248 quad8(1//2, 1//2)\n\n", "meta": {"hexsha": "240c9a2bb611c43b600dd3bb3d48c8aa7b134ec6", "size": 998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/todo/centroid.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": "test/todo/centroid.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": "test/todo/centroid.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": 29.3529411765, "max_line_length": 71, "alphanum_fraction": 0.4258517034, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.763798704335714}}
{"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 DynamicHMCModels, LinearAlgebra, StatsFuns\n\nProjDir = @__DIR__\ncd(ProjDir)\n\ndelim = ';'\ndf = CSV.read(joinpath(\"..\", \"..\", \"data\", \"chimpanzees.csv\"), DataFrame; delim)\ndf.pulled_left = convert(Array{Int64}, df.pulled_left)\ndf.prosoc_left = convert(Array{Int64}, df.prosoc_left)\nfirst(df, 5)\n\nBase.@kwdef mutable struct Chimpanzees{Ty <: AbstractVector,\n  Tx <: AbstractMatrix}\n    \"Observations.\"\n    y::Ty\n    \"Covariates\"\n    x::Tx\n    \"Number of observations\"\n    N::Int\nend\n\n# Write a function to return properly dimensioned transformation.\n\nfunction make_transformation(model::Chimpanzees)\n  as( (\u03b2 = as(Array, size(model.x, 2)), ) )\nend\n\n# Instantiate the model with data and inits.\n\nN = size(df, 1)\nx = hcat(ones(Int64, N), df[:, :prosoc_left]);\ny = df[:, :pulled_left]\nmodel = Chimpanzees(;y=y, x=x, N=N);\n\n# Make the model callable with a single argument.\n\nfunction (model::Chimpanzees)(\u03b8)\n    @unpack y, x, N = model   # extract the data\n    @unpack \u03b2 = \u03b8  # works on the named tuple too\n    ll = 0.0\n    ll += sum(logpdf.(Normal(0, 10), \u03b2)) # a & bp\n    ll += sum([loglikelihood(Binomial(1, logistic(dot(x[i, :], \u03b2))), [y[i]]) for i in 1:N])\n    ll\nend\n\nprintln()\n\u03b8 = (\u03b2 = [1.0, 2.0],)\nmodel(\u03b8)\nprintln()\n\n# Wrap the problem with a transformation, then use Flux for the gradient.\n\nP = TransformedLogDensity(make_transformation(model), model)\n\u2207P = ADgradient(:ForwardDiff, P)\nresults = mcmc_with_warmup(Random.GLOBAL_RNG, \u2207P, 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 0.05103234 0.12579086 0.0019889282 0.0035186307 1000\nbp 0.55711212 0.18074275 0.0028577937 0.0040160451 1000\n\nQuantiles:\n       2.5%        25.0%       50.0%      75.0%      97.5%  \n a -0.19755400 -0.029431425 0.05024655 0.12978825 0.30087758\nbp  0.20803447  0.433720250 0.55340400 0.67960975 0.91466915\n\";\n\n# End of `10/m10.2d.jl`\n", "meta": {"hexsha": "01494c6dfe832a3ee62221f44706b22830b25b06", "size": 2058, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/10/m10.2d.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/10/m10.2d.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/10/m10.2d.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": 26.0506329114, "max_line_length": 91, "alphanum_fraction": 0.6705539359, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7637986955867256}}
{"text": "using NLSolvers, StaticArrays, Test\n@testset \"mixed optimization problems\" begin\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\nf(x) = 100.0 * ((x[3] - 10.0 * theta(x))^2 + (sqrt(x[1]^2 + x[2]^2) - 1.0)^2) + x[3]^2\n\nfunction f\u2207f!(\u2207f, x)\n    if !(\u2207f==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        \u2207f[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        \u2207f[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        \u2207f[3] =  200.0*(x[3]-10.0*theta(x)) + 2.0*x[3];\n    end\n\n    fx = f(x)\n    return \u2207f==nothing ? fx : (fx, \u2207f)\nend\n\nfunction f\u2207f(\u2207f, x)\n    if !(\u2207f == nothing)\n        gx = similar(x)\n        return f\u2207f!(gx, x)\n    else\n        return f\u2207f!(\u2207f, x)\n    end\nend\nfunction f\u2207fs(\u2207f, x)\n    if !(\u2207f == 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        \u2207f = @SVector [s1, s2, s3]\n        return f(x), \u2207f\n    else\n        return f(x)\n    end\nend\nobj_inplace = OnceDiffed(f\u2207f!)\nobj_outofplace = OnceDiffed(f\u2207f)\nobj_static = OnceDiffed(f\u2207fs)\n\nx0 = [-1.0, 0.0, 0.0]\nxopt = [1.0, 0.0, 0.0]\nx0s = @SVector [-1.0, 0.0, 0.0]\n\nprintln(\"Starting  from: \", x0)\nprintln(\"Targeting     : \", xopt)\n\nshortname(::GradientDescent) = \"GD  \"\nshortname(::Inverse) = \"(inverse)\"\nshortname(::Direct) = \" (direct)\"\n\nfunction printed_minimize(f\u2207f, x0, method)\n    res = minimize(f\u2207f, x0, method, OptOptions())\n    print(\"NN  $(shortname(method)) $(shortname(method.approx)): \")\n    @printf(\"%2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nend\nfunction printed_minimize!(obj_inplace, x0, method)\n    res = minimize!(obj_inplace, x0, method, OptOptions())\n    print(\"NN! $(shortname(method)) $(shortname(method.approx)): \")\n    @printf(\"%2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nend\n\nprinted_minimize(obj_inplace, x0, GradientDescent(Inverse()))\nprinted_minimize!(obj_inplace, copy(x0), GradientDescent(Inverse()))\nres = minimize(obj_static, x0s, GradientDescent(Inverse()))\n@printf(\"NN  GD(S) (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\n\nprinted_minimize(obj_inplace, x0, GradientDescent(Direct()))\nprinted_minimize!(obj_inplace, copy(x0), GradientDescent(Direct()))\nres = minimize(obj_static, x0s, GradientDescent(Direct()))\n@printf(\"NN  GD(S)  (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nprintln()\n\nres = minimize(obj_inplace, x0, BFGS(Inverse()), OptOptions())\n@test res[4] == 30\n@printf(\"NN  BFGS    (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), (BFGS(Inverse()), Backtracking()), OptOptions())\n@test res[4] == 30\n@printf(\"NN! BFGS    (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), (BFGS(Inverse()), Backtracking(interp=FFQuadInterp())), OptOptions())\n@test res[4] == 32\n@printf(\"NN! BFGS    (inverse, quad): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, x0s, BFGS(Inverse()))\n@test res[4] == 30\n@printf(\"NN  BFGS(S) (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, x0s, (BFGS(Inverse()), Backtracking(interp=FFQuadInterp())))\n@test res[4] == 32\n@printf(\"NN  BFGS(S) (inverse, quad): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\n\nres = minimize(obj_inplace, x0, BFGS(Direct()), OptOptions())\n@printf(\"NN  BFGS    (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), BFGS(Direct()), OptOptions())\n@printf(\"NN! BFGS    (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, x0s, BFGS(Direct()))\n@printf(\"NN  BFGS(S) (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nprintln()\n# res = optimize(obj_inplace, copy(x0), Optim.BFGS(linesearch=Backtracking()))\n# @time optimize(obj_inplace, copy(x0), Optim.BFGS(linesearch=Backtracking()))\n# @printf(\"OT! BFGS (inverse): %2.2e  %2.2e\\n\", norm(Optim.minimizer(res)-xopt,Inf), Optim.g_residual(res))\n\nres = minimize(obj_inplace, x0, DFP(Inverse()))\n@printf(\"NN  DFP    (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), DFP(Inverse()))\n@printf(\"NN! DFP    (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, x0s, DFP(Inverse()))\n@printf(\"NN  DFP(S) (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_inplace, x0, DFP(Direct()))\n@printf(\"NN  DFP    (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), DFP(Direct()))\n@printf(\"NN! DFP    (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, x0s, DFP(Direct()))\n@printf(\"NN  DFP(S) (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nprintln()\n\nres = minimize(obj_inplace, x0, SR1(Inverse()))\n@printf(\"NN  SR1     (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), SR1(Inverse()))\n@printf(\"NN! SR1     (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, x0s, SR1(Inverse()))\n@printf(\"NN  SR1(S)  (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_inplace, x0, SR1(Direct()))\n@printf(\"NN  SR1     (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), SR1(Direct()))\n@printf(\"NN! SR1     (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, x0s, SR1(Direct()))\n@printf(\"NN  SR1(S)  (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(x0), (SR1(Direct()), NWI()))\n@printf(\"NN! SR1   (direct, NW): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\n\nxrand = rand(3)\nxrands = SVector{3}(xrand)\nprintln(\"\\nFrom a random point: \", xrand)\nres = minimize(obj_inplace, xrand, GradientDescent(Inverse()))\n@printf(\"NN  GD   (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), GradientDescent(Inverse()))\n@printf(\"NN! GD   (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_inplace, xrand, GradientDescent(Direct()))\n@printf(\"NN  GD    (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), GradientDescent(Direct()))\n@printf(\"NN! GD    (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nprintln()\nres = minimize(obj_inplace, xrand, BFGS(Inverse()))\n@printf(\"NN  BFGS (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), (BFGS(Inverse()), Backtracking()))\n@printf(\"NN! BFGS (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), (BFGS(Inverse()), HZAW()))\n@printf(\"NN! BFGS (inverse) HZ: %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_inplace, xrand, BFGS(Direct()))\n@printf(\"NN  BFGS  (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), BFGS(Direct()))\n@printf(\"NN! BFGS  (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_inplace, xrand, DBFGS(Direct()))\n@printf(\"NN  DBFGS  (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), DBFGS(Direct()))\n@printf(\"NN! DBFGS  (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), (DBFGS(Direct()), NWI()))\n@printf(\"NN! DBFGS  (direct, NW): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), (DBFGS(Direct()), Dogleg()))\n@printf(\"NN! DBFGS  (direct, DL): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nprintln()\n\nres = minimize(obj_inplace, xrand, DFP(Inverse()))\n@printf(\"NN  DFP  (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), DFP(Inverse()))\n@printf(\"NN! DFP  (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_inplace, xrand, DFP(Direct()))\n@printf(\"NN  DFP   (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), DFP(Direct()))\n@printf(\"NN! DFP   (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nprintln()\n\nres = minimize(obj_inplace, xrand, SR1(Inverse()))\n@printf(\"NN  SR1  (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), SR1(Inverse()))\n@printf(\"NN! SR1  (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, xrand, SR1(Inverse()))\n@printf(\"NN  SR1(S)   (inverse): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_inplace, xrand, SR1(Direct()))\n@printf(\"NN  SR1   (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), SR1(Direct()))\n@printf(\"NN! SR1   (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize(obj_static, xrand, SR1(Direct()))\n@printf(\"NN  SR1(S)   (direct): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\n\n# res = minimize(obj_inplace, xrand, (SR1(Direct()), NWI()))\n# @printf(\"NN  SR1   (direct, tr): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\nres = minimize!(obj_inplace, copy(xrand), (SR1(Direct()), NWI()))\n@printf(\"NN! SR1   (direct, NW): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\n# res = minimize(obj_static, xrand, (SR1(Direct()), NWI()))\n# @printf(\"NN  SR1(S)   (direct, tr): %2.2e  %2.2e  %d\\n\", norm(res[1]-xopt,Inf), norm(res[3], Inf), res[4])\n\nprintln()\n\n\nfunction himmelblau!(\u2207f, x)\n    if !(\u2207f == nothing)\n        \u2207f[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        \u2207f[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 \u2207f == nothing ? fx : (fx, \u2207f)\nend\n\n\nfunction himmelblaus(\u2207f, x)\n    f = (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2\n    if !(\u2207f == nothing)\n        \u2207f1 = 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        \u2207f2 = 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        return f, @SVector([\u2207f1, \u2207f2])\n    else\n        return f\n    end\nend\n\nfunction himmelblau(\u2207f, x)\n    g = \u2207f == nothing ? \u2207f : similar(x)\n\n    return himmelblau!(g, x)\nend\n\nhim_inplace = OnceDiffed(himmelblau!)\nhim_static = OnceDiffed(himmelblaus)\nhim_outofplace = OnceDiffed(himmelblau)\n\nprintln(\"\\nHimmelblau function\")\nx0 = [3.0, 1.0]\nx0s = SVector{2}(x0)\nres = minimize(him_outofplace, x0, GradientDescent(Inverse()))\n@printf(\"NN  GD    (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), GradientDescent(Inverse()))\n@printf(\"NN! GD    (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_static, x0s, GradientDescent(Inverse()))\n@printf(\"NN  GD(S) (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nprintln()\nres = minimize(him_outofplace, x0, GradientDescent(Direct()))\n@printf(\"NN  GD    (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), GradientDescent(Direct()))\n@printf(\"NN! GD    (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_static, x0s, GradientDescent(Direct()))\n@printf(\"NN  GD(S) (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nprintln()\n\nres = minimize(him_outofplace, x0, BFGS(Inverse()))\n@printf(\"NN  BFGS    (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), BFGS(Inverse()))\n@printf(\"NN! BFGS    (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0s, BFGS(Inverse()))\n@printf(\"NN  BFGS(S) (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nprintln()\nres = minimize(him_outofplace, x0, BFGS(Direct()))\n@printf(\"NN  BFGS    (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), BFGS(Direct()))\n@printf(\"NN! BFGS    (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0s, BFGS(Direct()))\n@printf(\"NN  BFGS(S) (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), (DBFGS(Direct()), NWI()))\n@printf(\"NN! DBFGS  (direct, NW): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), (DBFGS(Direct()), Dogleg()))\n@printf(\"NN! DBFGS  (direct, DL): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\n\nprintln()\n\nres = minimize(him_outofplace, x0, DFP(Inverse()))\n@printf(\"NN  DFP  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), DFP(Inverse()))\n@printf(\"NN! DFP  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0s, DFP(Inverse()))\n@printf(\"NN  DFP(S)  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0, DFP(Direct()))\nprintln()\n@printf(\"NN  DFP   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), DFP(Direct()))\n@printf(\"NN! DFP   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0s, DFP(Direct()))\n@printf(\"NN  DFP(S)   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nprintln()\n\nres = minimize(him_outofplace, x0, SR1(Inverse()))\n@printf(\"NN  SR1  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), SR1(Inverse()))\n@printf(\"NN! SR1  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0s, SR1(Inverse()))\n@printf(\"NN  SR1(S)  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0, SR1(Direct()))\n@printf(\"NN  SR1   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(x0), SR1(Direct()))\n@printf(\"NN! SR1   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, x0s, SR1(Direct()))\n@printf(\"NN  SR1(S)   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nprintln()\nxrand = rand(2)\nxrands = SVector{2}(xrand)\nprintln(\"\\nFrom a random point: \", xrand)\n\nres = minimize(him_outofplace, xrand, GradientDescent(Inverse()))\n@printf(\"NN  GD   (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(xrand), GradientDescent(Inverse()))\n@printf(\"NN! GD   (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, xrand, GradientDescent(Direct()))\n@printf(\"NN  GD    (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(xrand), GradientDescent(Direct()))\n@printf(\"NN! GD    (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\n\nres = minimize(him_outofplace, xrand, BFGS(Inverse()))\n@printf(\"NN   BFGS (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(xrand), BFGS(Inverse()))\n@printf(\"NN!  BFGS (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_static, xrand, BFGS(Direct()))\n@printf(\"NN(S) BFGS (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, xrand, BFGS(Direct()))\n@printf(\"NN  BFGS  (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace, copy(xrand), BFGS(Direct()))\n@printf(\"NN! BFGS  (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\n\nres = minimize(him_outofplace, xrand, DFP(Inverse()))\n@printf(\"NN  DFP  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace,  copy(xrand), DFP(Inverse()))\n@printf(\"NN! DFP  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, xrand, DFP(Direct()))\n@printf(\"NN  DFP   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace,  copy(xrand), DFP(Direct()))\n@printf(\"NN! DFP   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\n\nres = minimize(him_outofplace, xrand, SR1(Inverse()))\n@printf(\"NN  SR1  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace,  copy(xrand), SR1(Inverse()))\n@printf(\"NN! SR1  (inverse): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize(him_outofplace, xrand, SR1(Direct()))\n@printf(\"NN  SR1   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nres = minimize!(him_inplace,  copy(xrand), SR1(Direct()))\n@printf(\"NN! SR1   (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\n\nend\n", "meta": {"hexsha": "0d18be670eb4f851823647c1223c39a6fce819fe", "size": 18067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optimize/mixed_tests.jl", "max_stars_repo_name": "aaowens/NLSolvers.jl", "max_stars_repo_head_hexsha": "8be4390b85bf9b3631659b9d2966760bc722ed9c", "max_stars_repo_licenses": ["MIT"], "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/optimize/mixed_tests.jl", "max_issues_repo_name": "aaowens/NLSolvers.jl", "max_issues_repo_head_hexsha": "8be4390b85bf9b3631659b9d2966760bc722ed9c", "max_issues_repo_licenses": ["MIT"], "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/mixed_tests.jl", "max_forks_repo_name": "aaowens/NLSolvers.jl", "max_forks_repo_head_hexsha": "8be4390b85bf9b3631659b9d2966760bc722ed9c", "max_forks_repo_licenses": ["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.6346153846, "max_line_length": 108, "alphanum_fraction": 0.5876459844, "num_tokens": 7448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7637986880760976}}
{"text": "using ModernRoboticsBook\nusing Test\n\nimport LinearAlgebra\nconst linalg = LinearAlgebra\n\n@testset \"ModernRoboticsBook.jl\" begin\n    @testset \"basic helper functions\" begin\n        @test NearZero(-1e-7)\n        @test Normalize([1, 2, 3]) == [0.2672612419124244,\n                                       0.5345224838248488,\n                                       0.8017837257372732]\n    end\n    @testset \"chapter 3: rigid-body motions\" begin\n        @test RotInv([0 0 1; 1 0 0; 0 1 0]) == [0 1 0; 0 0 1; 1 0 0]\n        @test VecToso3([1, 2, 3]) == [0 -3 2; 3 0 -1; -2 1 0]\n        @test so3ToVec([0 -3 2; 3 0 -1; -2 1 0]) == [1, 2, 3]\n        @test AxisAng3([1, 2, 3]) == ([0.2672612419124244,\n                                       0.5345224838248488,\n                                       0.8017837257372732], 3.7416573867739413)\n\n        @test isapprox(MatrixExp3([ 0 -3  2;\n                                    3  0 -1;\n                                   -2  1  0]),\n                       [-0.694921  0.713521 0.0892929\n                        -0.192007 -0.303785 0.933192 \n                         0.692978  0.63135  0.348107 ]; rtol=1e-6)\n        @test MatrixExp3(zeros(3, 3)) == [1 0 0; 0 1 0; 0 0 1]\n\n        @test isapprox(MatrixLog3([0 0 1;\n                                   1 0 0;\n                                   0 1 0]),\n                       [ 0.0    -1.2092  1.2092\n                         1.2092  0.0    -1.2092\n                        -1.2092  1.2092  0.0   ]; rtol=1e-6)\n        @test MatrixLog3(zeros(3, 3)) == zeros(3, 3)\n        @test MatrixLog3([-3 0 0; 0 1 0; 0 0  1]) == [0 -\u03c0 0; \u03c0 0 0; 0 0 0]\n        @test MatrixLog3([-2 0 0; 0 1 0; 0 0 -1]) == [0 0 \u03c0; 0 0 0; -\u03c0 0 0]\n        @test MatrixLog3([1 0 0; 0 -1 0; 0 0 -1]) == [0 0 0; 0 0 -\u03c0; 0 \u03c0 0]\n\n        @test RpToTrans([1 0  0;\n                         0 0 -1;\n                         0 1  0], [1, 2, 5]) == [1 0  0 1\n                                                 0 0 -1 2\n                                                 0 1  0 5\n                                                 0 0  0 1]\n        @test TransToRp([1 0  0 0;\n                         0 0 -1 0;\n                         0 1  0 3;\n                         0 0  0 1]) == ([1 0  0;\n                                         0 0 -1;\n                                         0 1  0], [0, 0, 3])\n        @test TransInv([1 0  0 0;\n                        0 0 -1 0;\n                        0 1  0 3;\n                        0 0  0 1]) == [1  0 0  0\n                                       0  0 1 -3\n                                       0 -1 0  0\n                                       0  0 0  1]\n        @test VecTose3([1, 2, 3, 4, 5, 6]) == [ 0 -3  2  4\n                                                3  0 -1  5\n                                               -2  1  0  6\n                                                0  0  0  0]\n        @test se3ToVec([ 0 -3  2  4;\n                         3  0 -1  5;\n                        -2  1  0  6;\n                         0  0  0  0]) == [1, 2, 3, 4, 5, 6]\n        @test Adjoint([1  0  0  0;\n                       0  0 -1  0;\n                       0  1  0  3;\n                       0  0  0  1]) == [1  0  0  0  0  0\n                                        0  0 -1  0  0  0\n                                        0  1  0  0  0  0\n                                        0  0  3  1  0  0\n                                        3  0  0  0  0 -1\n                                        0  0  0  0  1  0]\n        @test ScrewToAxis([3; 0; 0], [0; 0; 1], 2) == [0, 0, 1, 0, -3, 2]\n\n        @test AxisAng6([1, 0, 0, 1, 2, 3]) == ([1, 0, 0, 1, 2, 3], 1)\n        @test AxisAng6([0, 0, 0, 0, 0, 4]) == ([0, 0, 0, 0, 0, 1], 4)\n\n        @test MatrixExp6([0    0    0    0   ;\n                          0    0   -\u03c0/2  3\u03c0/4;\n                          0    \u03c0/2  0    3\u03c0/4;\n                          0    0    0    0   ]) \u2248 [1  0  0  0;\n                                                   0  0 -1  0;\n                                                   0  1  0  3;\n                                                   0  0  0  1]\n        @test MatrixLog6([1  0  0  0;\n                          0  0 -1  0;\n                          0  1  0  3;\n                          0  0  0  1]) \u2248 [0    0    0    0   ;\n                                          0    0   -\u03c0/2  3\u03c0/4;\n                                          0    \u03c0/2  0    3\u03c0/4;\n                                          0    0    0    0   ]\n        @test MatrixLog6(Array(linalg.Diagonal(ones(4)))) == zeros(4, 4)\n\n        @test isapprox(ProjectToSO3([ 0.675  0.150  0.720;\n                                      0.370  0.771 -0.511;\n                                     -0.630  0.619  0.472]),\n                       [ 0.679011  0.148945   0.718859\n                         0.373207  0.773196  -0.512723\n                        -0.632187  0.616428   0.469421]; rtol=1e-6)\n        @test ProjectToSO3([-1 0 0; 0 -1 0; 0 0 -1]) == [1 0 0; 0 -1 0; 0 0 -1]\n\n        @test isapprox(ProjectToSE3([ 0.675  0.150  0.720  1.2;\n                                      0.370  0.771 -0.511  5.4;\n                                     -0.630  0.619  0.472  3.6;\n                                      0.003  0.002  0.010  0.9]),\n                                    [ 0.679011  0.148945   0.718859  1.2\n                                      0.373207  0.773196  -0.512723  5.4\n                                     -0.632187  0.616428   0.469421  3.6\n                                      0.0       0.0        0.0       1.0]; rtol=1e-6)\n\n        @test DistanceToSO3([1.0  0.0  0.0 ;\n                             0.0  0.1 -0.95;\n                             0.0  1.0  0.1 ]) == 0.08835298523536149\n\n        @test DistanceToSE3([1.0  0.0  0.0   1.2 ;\n                             0.0  0.1 -0.95  1.5 ;\n                             0.0  1.0  0.1  -0.9 ;\n                             0.0  0.0  0.1   0.98]) == 0.13493053768513638\n        @test DistanceToSE3(Array(reshape(1:9, (3, 3)))) >= 1e+9\n\n        @test !TestIfSO3([1.0  0.0  0.0 ;\n                          0.0  0.1 -0.95;\n                          0.0  1.0  0.1 ])\n        @test !TestIfSE3([1.0  0.0  0.0   1.2 ;\n                          0.0  0.1 -0.95  1.5 ;\n                          0.0  1.0  0.1  -0.9 ;\n                          0.0  0.0  0.1   0.98])\n    end\n    @testset \"chapter 4: forward kinematics\" begin\n        M = [-1  0  0  0 ;\n              0  1  0  6 ;\n              0  0 -1  2 ;\n              0  0  0  1 ]\n\n        Blist = [ 0  0 -1  2  0  0   ;\n                  0  0  0  0  1  0   ;\n                  0  0  1  0  0  0.1 ]'\n\n        Slist = [ 0  0  1  4  0  0   ;\n                  0  0  0  0  1  0   ;\n                  0  0 -1 -6  0 -0.1 ]'\n\n        thetalist = [ \u03c0/2, 3, \u03c0 ]\n\n        @test isapprox(FKinBody(M, Blist, thetalist),\n                       [-1.14424e-17  1.0           0.0  -5.0     ;\n                         1.0          1.14424e-17   0.0   4.0     ;\n                         0.0          0.0          -1.0   1.68584 ;\n                         0.0          0.0           0.0   1.0     ]; rtol=1e-6)\n        @test isapprox(FKinSpace(M, Slist, thetalist),\n                       [-1.14424e-17  1.0           0.0  -5.0     ;\n                         1.0          1.14424e-17   0.0   4.0     ;\n                         0.0          0.0          -1.0   1.68584 ;\n                         0.0          0.0           0.0   1.0     ]; rtol=1e-6)\n    end\n    @testset \"chapter 5: velocity kinematics and statics\" begin\n        Blist = [0 0 1   0 0.2 0.2;\n                 1 0 0   2   0   3;\n                 0 1 0   0   2   1;\n                 1 0 0 0.2 0.3 0.4]'\n\n        Slist = [0 0 1   0 0.2 0.2;\n                 1 0 0   2   0   3;\n                 0 1 0   0   2   1;\n                 1 0 0 0.2 0.3 0.4]'\n\n        thetalist = [0.2, 1.1, 0.1, 1.2]\n\n        @test isapprox(JacobianBody(Blist, thetalist),\n                       [ -0.0452841  0.995004    0.0       1.0 ;\n                          0.743593   0.0930486   0.362358  0.0 ;\n                         -0.667097   0.0361754  -0.932039  0.0 ;\n                          2.32586    1.66809     0.564108  0.2 ;\n                         -1.44321    2.94561     1.43307   0.3 ;\n                         -2.0664     1.82882    -1.58869   0.4 ]; rtol=1e-5)\n        @test isapprox(JacobianSpace(Slist, thetalist),\n                       [0.0  0.980067  -0.0901156   0.957494 ;\n                        0.0  0.198669   0.444554    0.284876 ;\n                        1.0  0.0        0.891207   -0.0452841;\n                        0.0  1.95219   -2.21635    -0.511615 ;\n                        0.2  0.436541  -2.43713     2.77536  ;\n                        0.2  2.96027    3.23573     2.22512  ]; rtol=1e-5)\n    end\n    @testset \"chapter 6: inverse kinematics\" begin\n        Blist = [ 0  0 -1  2  0  0   ;\n                  0  0  0  0  1  0   ;\n                  0  0  1  0  0  0.1 ]'\n\n        Slist = [ 0  0  1  4  0  0   ;\n                  0  0  0  0  1  0   ;\n                  0  0 -1 -6  0 -0.1 ]'\n\n        M = [ -1  0  0  0 ;\n               0  1  0  6 ;\n               0  0 -1  2 ;\n               0  0  0  1 ]\n\n        T = [ 0  1  0     -5 ;\n              1  0  0      4 ;\n              0  0 -1 1.6858 ;\n              0  0  0      1 ]\n\n        thetalist0 = [1.5, 2.5, 3]\n\n        eomg, ev = 0.01, 0.001\n\n        thetalist, success = IKinBody(Blist, M, T, thetalist0, eomg, ev)\n        @test isapprox(thetalist, [1.57074, 2.99967, 3.14154]; rtol=1e-5)\n        @test success\n\n        thetalist, success = IKinSpace(Slist, M, T, thetalist0, eomg, ev)\n        @test isapprox(thetalist, [1.57074, 2.99966, 3.14153]; rtol=1e-5)\n        @test success\n    end\n    @testset \"chapter 8: dynamics of open chains\" begin\n        @test ad([1, 2, 3, 4, 5, 6]) == [ 0.0  -3.0   2.0   0.0   0.0   0.0\n                                          3.0   0.0  -1.0   0.0   0.0   0.0\n                                         -2.0   1.0   0.0   0.0   0.0   0.0\n                                          0.0  -6.0   5.0   0.0  -3.0   2.0\n                                          6.0   0.0  -4.0   3.0   0.0  -1.0\n                                         -5.0   4.0   0.0  -2.0   1.0   0.0 ]\n\n        thetalist = [0.1, 0.1, 0.1]\n        dthetalist = [0.1, 0.2, 0.3]\n        ddthetalist = [2, 1.5, 1]\n        g = [0, 0, -9.8]\n        Ftip = [1, 1, 1, 1, 1, 1]\n        M01 = [1  0  0         0 ;\n               0  1  0         0 ;\n               0  0  1  0.089159 ;\n               0  0  0         1 ]\n        M12 = [0  0  1     0.28 ;\n               0  1  0  0.13585 ;\n              -1  0  0        0 ;\n               0  0  0        1 ]\n        M23 = [1  0  0        0 ;\n               0  1  0  -0.1197 ;\n               0  0  1    0.395 ;\n               0  0  0        1 ]\n        M34 = [1  0  0        0 ;\n               0  1  0        0 ;\n               0  0  1  0.14225 ;\n               0  0  0        1 ]\n        G1 = linalg.Diagonal([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7])\n        G2 = linalg.Diagonal([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393])\n        G3 = linalg.Diagonal([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275])\n        Glist = [G1, G2, G3]\n        Mlist = [M01, M12, M23, M34]\n        Slist = [ 1  0  1      0  1      0 ;\n                  0  1  0 -0.089  0      0 ;\n                  0  1  0 -0.089  0  0.425 ]'\n\n        taulist_actual = InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist)\n\n        @test taulist_actual \u2248 [74.69616155287451, -33.06766015851458, -3.230573137901424]\n\n        @test isapprox(MassMatrix(thetalist, Mlist, Glist, Slist),\n                       [ 22.5433      -0.307147  -0.00718426;\n                         -0.307147     1.96851    0.432157  ;\n                         -0.00718426   0.432157   0.191631  ]; rtol=1e-5)\n\n        @test VelQuadraticForces(thetalist, dthetalist, Mlist, Glist, Slist) \u2248 [  0.26453118054501235 ;\n                                                                                 -0.0550515682891655  ;\n                                                                                 -0.006891320068248911]\n\n        @test GravityForces(thetalist, g, Mlist, Glist, Slist) == [  28.40331261821983  ;\n                                                                    -37.64094817177068  ;\n                                                                     -5.4415891999683605]\n\n        @test EndEffectorForces(thetalist, Ftip, Mlist, Glist, Slist) \u2248 [ 1.4095460782639782;\n                                                                          1.8577149723180628;\n                                                                          1.392409          ]\n\n        taulist = [0.5, 0.6, 0.7]\n        @test ForwardDynamics(thetalist, dthetalist, taulist, g, Ftip, Mlist, Glist, Slist) \u2248 [ -0.9739290670855626;\n                                                                                                25.584667840340558 ;\n                                                                                               -32.91499212478149  ]\n\n        @test hcat(EulerStep([0.1, 0.1, 0.1], [0.1, 0.2, 0.3], [2, 1.5, 1], 0.1)...) \u2248 hcat([0.11, 0.12, 0.13], [0.3, 0.35, 0.4])\n\n        @testset \"inverse dynamics trajectory\" begin\n            thetastart = [0, 0, 0]\n            thetaend = [\u03c0/2, \u03c0/2, \u03c0/2]\n            Tf = 3\n            N = 10\n            method = 5\n\n            traj = JointTrajectory(thetastart, thetaend, Tf, N, method)\n\n            thetamat = copy(traj)\n            dthetamat = zeros(N, 3)\n            ddthetamat = zeros(N, 3)\n\n            dt = Tf / (N - 1)\n\n            for i = 1:size(traj, 1) - 1\n                dthetamat[i + 1, :] = (thetamat[i + 1, :] - thetamat[i, :]) / dt\n                ddthetamat[i + 1, :] = (dthetamat[i + 1, :] - dthetamat[i, :]) / dt\n            end\n\n            Ftipmat = ones(N, 6)\n\n            taumat_actual = InverseDynamicsTrajectory(thetamat, dthetamat, ddthetamat, g, Ftipmat, Mlist, Glist, Slist)\n\n            taumat_expected = [ 1.32297079e+01 -3.62621080e+01 -4.18134100e+00 ;\n                                1.96974217e+01 -3.59188701e+01 -4.07919728e+00 ;\n                                5.11979532e+01 -3.44705050e+01 -3.59488765e+00 ;\n                                9.41368122e+01 -3.14099606e+01 -2.41622731e+00 ;\n                                1.25417579e+02 -2.45283212e+01  5.76295281e-02 ;\n                                1.24948454e+02 -1.85038921e+01  1.94898550e+00 ;\n                                1.01525941e+02 -1.88375820e+01  2.07369432e+00 ;\n                                7.68134579e+01 -2.23610568e+01  1.96172027e+00 ;\n                                6.44365965e+01 -2.46704062e+01  2.07890001e+00 ;\n                                6.72354909e+01 -2.47008371e+01  2.19474783e+00 ]\n\n            @test taumat_actual \u2248 taumat_expected\n        end\n        @testset \"forward dynamics trajectory\" begin\n            taumat = [ 3.63 -6.58 -5.57 ; 3.74 -5.55 -5.5  ;\n                       4.31 -0.68 -5.19 ; 5.18  5.63 -4.31 ;\n                       5.85  8.17 -2.59 ; 5.78  2.79 -1.7  ;\n                       4.99 -5.3  -1.19 ; 4.08 -9.41  0.07 ;\n                       3.56 -10.1  0.97 ; 3.49 -9.41  1.23 ]\n\n            Ftipmat = ones(size(taumat, 1), 6)\n\n            dt = 0.1\n            intRes = 8\n\n            thetamat_expected = [ 0.1         0.1         0.1        ;\n                                  0.10643138  0.2625997  -0.22664947 ;\n                                  0.10197954  0.71581297 -1.22521632 ;\n                                  0.0801044   1.33930884 -2.28074132 ;\n                                  0.0282165   2.11957376 -3.07544297 ;\n                                 -0.07123855  2.87726666 -3.83289684 ;\n                                 -0.20136466  3.397858   -4.83821609 ;\n                                 -0.32380092  3.73338535 -5.98695747 ;\n                                 -0.41523262  3.85883317 -7.01130559 ;\n                                 -0.4638099   3.63178793 -7.63190052 ]\n\n            dthetamat_expected = [ 0.1          0.2          0.3        ;\n                                   0.01212502   3.42975773  -7.74792602 ;\n                                  -0.13052771   5.55997471 -11.22722784 ;\n                                  -0.35521041   7.11775879  -9.18173035 ;\n                                  -0.77358795   8.17307573  -7.05744594 ;\n                                  -1.2350231    6.35907497  -8.99784746 ;\n                                  -1.31426299   4.07685875 -11.18480509 ;\n                                  -1.06794821   2.49227786 -11.69748583 ;\n                                  -0.70264871  -0.55925705  -8.16067131 ;\n                                  -0.1455669   -4.57149985  -3.43135114 ]\n\n            thetamat_actual, dthetamat_actual = ForwardDynamicsTrajectory(thetalist, dthetalist, taumat, g, Ftipmat, Mlist, Glist, Slist, dt, intRes)\n\n            @test thetamat_actual \u2248 thetamat_expected\n            @test dthetamat_actual \u2248 dthetamat_expected\n        end\n    end\n    @testset \"chapter 9: trajectory generation\" begin\n        @test CubicTimeScaling(2, 0.6) == 0.21600000000000003\n        @test QuinticTimeScaling(2, 0.6) == 0.16308\n        @testset \"joint trajectory\" begin\n            thetastart = [1, 0, 0, 1, 1, 0.2, 0,1]\n            thetaend = [1.2, 0.5, 0.6, 1.1, 2, 2, 0.9, 1]\n            Tf = 4\n            N = 6\n            method = 3\n\n            expected = [     1     0      0      1     1    0.2      0 1 ;\n                        1.0208 0.052 0.0624 1.0104 1.104 0.3872 0.0936 1 ;\n                        1.0704 0.176 0.2112 1.0352 1.352 0.8336 0.3168 1 ;\n                        1.1296 0.324 0.3888 1.0648 1.648 1.3664 0.5832 1 ;\n                        1.1792 0.448 0.5376 1.0896 1.896 1.8128 0.8064 1 ;\n                           1.2   0.5    0.6    1.1     2      2    0.9 1 ]\n\n            @test JointTrajectory(thetastart, thetaend, Tf, N, method) \u2248 expected\n        end\n        @testset \"screw trajectory\" begin\n            Xstart = [1 0 0 1 ;\n                      0 1 0 0 ;\n                      0 0 1 1 ;\n                      0 0 0 1 ]\n            Xend = [0 0 1 0.1 ;\n                    1 0 0   0 ;\n                    0 1 0 4.1 ;\n                    0 0 0   1 ]\n\n            Tf = 5\n            N = 4\n            method = 3\n\n            expected =  [[ 1 0 0 1 ;\n                           0 1 0 0 ;\n                           0 0 1 1 ;\n                           0 0 0 1 ],\n                         [ 0.904 -0.25   0.346  0.441 ;\n                           0.346  0.904 -0.25   0.529 ;\n                          -0.25   0.346  0.904  1.601 ;\n                           0      0      0      1     ],\n                         [ 0.346 -0.25   0.904 -0.117 ;\n                           0.904  0.346 -0.25   0.473 ;\n                          -0.25   0.904  0.346  3.274 ;\n                           0      0      0      1     ],\n                         [ 0 0 1 0.1 ;\n                           1 0 0 0   ;\n                           0 1 0 4.1 ;\n                           0 0 0 1   ]]\n\n            actual = ScrewTrajectory(Xstart, Xend, Tf, N, method)\n\n            @test isapprox(actual, expected; rtol=1e-3)\n        end\n        @testset \"cartesian trajectory\" begin\n            Xstart = [ 1 0 0 1 ;\n                       0 1 0 0 ;\n                       0 0 1 1 ;\n                       0 0 0 1 ]\n            Xend = [ 0 0 1 0.1 ;\n                     1 0 0 0   ;\n                     0 1 0 4.1 ;\n                     0 0 0 1   ]\n\n            Tf = 5\n            N = 4\n            method = 5\n\n\n            expected = [[ 1 0 0 1 ;\n                          0 1 0 0 ;\n                          0 0 1 1 ;\n                          0 0 0 1 ],\n                        [ 0.937 -0.214  0.277 0.811 ;\n                          0.277  0.937 -0.214     0 ;\n                         -0.214  0.277  0.937 1.651 ;\n                          0      0      0     1     ],\n                        [ 0.277 -0.214  0.937 0.289 ;\n                          0.937  0.277 -0.214     0 ;\n                         -0.214  0.937  0.277 3.449 ;\n                          0      0      0     1     ],\n                        [ 0 0 1 0.1 ;\n                          1 0 0 0   ;\n                          0 1 0 4.1 ;\n                          0 0 0 1   ]]\n\n            actual = CartesianTrajectory(Xstart, Xend, Tf, N, method)\n\n            @test isapprox(actual, expected; rtol=1e-3)\n        end\n    end\n    @testset \"chapter 11: robot control\" begin\n        thetalist = [0.1, 0.1, 0.1]\n        dthetalist = [0.1, 0.2, 0.3]\n\n        # Initialise robot description (Example with 3 links)\n        g = [0, 0, -9.8]\n\n        M01 = [1  0  0         0 ;\n               0  1  0         0 ;\n               0  0  1  0.089159 ;\n               0  0  0         1 ]\n        M12 = [0  0  1     0.28 ;\n               0  1  0  0.13585 ;\n              -1  0  0        0 ;\n               0  0  0        1 ]\n        M23 = [1  0  0        0 ;\n               0  1  0  -0.1197 ;\n               0  0  1    0.395 ;\n               0  0  0        1 ]\n        M34 = [1  0  0        0 ;\n               0  1  0        0 ;\n               0  0  1  0.14225 ;\n               0  0  0        1 ]\n\n        G1 = linalg.Diagonal([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7])\n        G2 = linalg.Diagonal([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393])\n        G3 = linalg.Diagonal([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275])\n\n        Mlist = [M01, M12, M23, M34]\n        Glist = [G1, G2, G3]\n\n        Slist = [ 1  0  1      0  1      0 ;\n                0  1  0 -0.089  0      0 ;\n                0  1  0 -0.089  0  0.425 ]'\n\n        # Create a trajectory to follow\n        thetaend = [\u03c0 / 2, \u03c0, 1.5 * \u03c0]\n\n        Tf = 1\n        dt = 0.05\n        N = Int(Tf / dt)\n        method = 5\n\n        traj = JointTrajectory(thetalist, thetaend, Tf, N, method)\n\n        thetamatd = copy(traj)\n        dthetamatd = zeros(N, 3)\n        ddthetamatd = zeros(N, 3)\n        dt = Tf / (N - 1)\n\n        for i = 1:size(traj, 1) - 1\n            dthetamatd[i + 1, :] = (thetamatd[i + 1, :] - thetamatd[i, :]) / dt\n            ddthetamatd[i + 1, :] = (dthetamatd[i + 1, :] - dthetamatd[i, :]) / dt\n        end\n\n        # Possibly wrong robot description (Example with 3 links)\n        gtilde = [0.8, 0.2, -8.8]\n\n        Mhat01 = [1 0 0   0;\n                  0 1 0   0;\n                  0 0 1 0.1;\n                  0 0 0   1]\n        Mhat12 = [0 0 1 0.3;\n                  0 1 0 0.2;\n                 -1 0 0   0;\n                  0 0 0   1]\n        Mhat23 = [1 0 0    0;\n                  0 1 0 -0.2;\n                  0 0 1  0.4;\n                  0 0 0    1]\n        Mhat34 = [1 0 0   0;\n                  0 1 0   0;\n                  0 0 1 0.2;\n                  0 0 0   1]\n\n        Ghat1 = linalg.Diagonal([0.1, 0.1, 0.1, 4, 4, 4])\n        Ghat2 = linalg.Diagonal([0.3, 0.3, 0.1, 9, 9, 9])\n        Ghat3 = linalg.Diagonal([0.1, 0.1, 0.1, 3, 3, 3])\n\n        Gtildelist = [Ghat1, Ghat2, Ghat3]\n        Mtildelist = [Mhat01, Mhat12, Mhat23, Mhat34]\n\n        # Other required arguments\n        Ftipmat = ones(size(traj, 1), 6)\n\n        Kp = 20\n        Ki = 10\n        Kd = 18\n        intRes = 8\n\n        taumat_expected = [ -14.2640765   -54.06797429  -11.265448   ;\n                             71.7014572   -17.58330542    3.86417108 ;\n                            208.80692807    6.94442209    8.4352746  ;\n                            269.9223766    14.44412677   11.24081382 ;\n                            316.48343344    6.4020598    10.60970699 ;\n                            327.82241593   -3.98984379   14.31752441 ;\n                            248.33306921  -16.39336633   21.61795095 ;\n                             93.7564835   -28.5575642    28.0092122  ;\n                             13.12918592  -44.38407547   19.04258057 ;\n                             56.35246455   -8.56189073    1.69770764 ;\n                             32.68030349   39.77791901   -5.94800597 ;\n                            -49.85502041   37.95496258  -15.10367806 ;\n                           -104.48630504   24.8129766   -16.25667052 ;\n                           -123.14920836   -3.62727714  -14.4680164  ;\n                            -84.15220471  -25.40152665  -12.85439272 ;\n                            -50.09890916  -33.73575763  -12.38441089 ;\n                            -30.41466046  -34.03362524  -11.30974711 ;\n                            -13.90701987  -26.40700004   -9.50026445 ;\n                              7.93416317  -12.95474009   -6.58132646 ;\n                             44.38627151    4.53534718   -2.32611269 ]\n\n        thetamat_expected = [ 0.1028237  0.10738308 0.07715206 ;\n                              0.10475535 0.11170712 0.05271794 ;\n                              0.11930448 0.13796752 0.12315113 ;\n                              0.1582068  0.21615938 0.27654789 ;\n                              0.22464764 0.35314707 0.51117109 ;\n                              0.31872944 0.54551689 0.81897456 ;\n                              0.4377715  0.78011155 1.21554584 ;\n                              0.57501633 1.03974866 1.71548388 ;\n                              0.72137128 1.30551854 2.2916328  ;\n                              0.87221934 1.56564069 2.84693996 ;\n                              1.0257972  1.841874   3.32092634 ;\n                              1.17352729 2.14460368 3.72255083 ;\n                              1.30459739 2.44287634 4.03953656 ;\n                              1.41155584 2.71108778 4.28079221 ;\n                              1.49166143 2.92224332 4.45724092 ;\n                              1.54707169 3.06503575 4.57357234 ;\n                              1.579692   3.14295613 4.62867261 ;\n                              1.59184568 3.1665363  4.62924012 ;\n                              1.58827951 3.15316968 4.59115503 ;\n                              1.57746305 3.12631855 4.54394792 ]\n\n        taumat_actual, thetamat_actual = SimulateControl(thetalist, dthetalist, g, Ftipmat, Mlist, Glist,\n                                                         Slist, thetamatd, dthetamatd, ddthetamatd, gtilde,\n                                                         Mtildelist, Gtildelist, Kp, Ki, Kd, dt, intRes)\n\n        @test taumat_actual \u2248 taumat_expected\n        @test thetamat_actual \u2248 thetamat_expected\n    end\nend\n", "meta": {"hexsha": "64999d8aced27a0673d6c29e4e46982ac4db245f", "size": 26381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ModernRoboticsBook.jl-5e1d693a-52d4-54aa-90a0-6f94c7384aed", "max_stars_repo_head_hexsha": "21fdc5f28a13233e9f4d8ce4cd05bdb7e12341af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2019-03-01T20:44:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T17:43:59.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ModernRoboticsBook.jl-5e1d693a-52d4-54aa-90a0-6f94c7384aed", "max_issues_repo_head_hexsha": "21fdc5f28a13233e9f4d8ce4cd05bdb7e12341af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-23T12:45:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-23T12:47:36.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "ferrolho/ModernRobotics.jl", "max_forks_repo_head_hexsha": "86eb2d3e40dea3360689555202e91fc8a5b005fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-03-02T07:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T07:47:25.000Z", "avg_line_length": 44.4873524452, "max_line_length": 149, "alphanum_fraction": 0.3507448543, "num_tokens": 9740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7637021645972916}}
{"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": "using ModelingToolkit, MethodOfLines, LinearAlgebra, OrdinaryDiffEq\nusing ModelingToolkit: operation, istree, arguments\nusing DomainSets\nusing NonlinearSolve\n\n# # Define some variables\n@testset \"Heat Equation 1D 2 variables\" begin\n       @parameters t x\n       @variables u(..) v(..)\n       Dt = Differential(t)\n       Dx = Differential(x)\n       Dxx = Differential(x)^2\n       eqs  = [Dt(u(t,x)) ~ Dxx(u(t,x)),\n              Dt(v(t,x)) ~ Dxx(v(t,x))]\n       bcs = [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\n       domains = [t \u2208 Interval(0.0,1.0),\n              x \u2208 Interval(0.0,1.0)]\n\n       @named pdesys = PDESystem(eqs,bcs,domains,[t,x],[u(t,x),v(t,x)])\n       discretization = MOLFiniteDifference([x=>0.1],t;grid_align=edge_align)\n       prob = discretize(pdesys,discretization) # This gives an ODEProblem since it's time-dependent\n       sol = solve(prob,Tsit5())\nend\n\n@testset \"Heat Equation 2D 1 variable\" begin\n       @parameters t x y\n       @variables u(..)\n       Dxx = Differential(x)^2\n       Dyy = Differential(y)^2\n       Dt = Differential(t)\n       t_min= 0.\n       t_max = 2.0\n       x_min = 0.\n       x_max = 2.\n       y_min = 0.\n       y_max = 2.\n\n       # 3D PDE\n       eq  = Dt(u(t,x,y)) ~ Dxx(u(t,x,y)) + Dyy(u(t,x,y))\n\n       analytic_sol_func(t,x,y) = exp(x+y)*cos(x+y+4t)\n       # Initial and boundary conditions\n       bcs = [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\n       domains = [t \u2208 Interval(t_min,t_max),\n              x \u2208 Interval(x_min,x_max),\n              y \u2208 Interval(y_min,y_max)]\n       @named pdesys = PDESystem([eq],bcs,domains,[t,x,y],[u(t,x,y)])\n       # Method of lines discretization\n       dx = 0.1; dy = 0.2\n       discretization = MOLFiniteDifference([x=>dx,y=>dy],t)\n       prob = ModelingToolkit.discretize(pdesys,discretization)\n       sol = solve(prob,Tsit5())\nend\n\n# Diffusion in a sphere\n@testset \"Spherical Diffusion\" begin\n\n       @parameters t r\n       @variables u(..)\n       Dt = Differential(t)\n       Dr = Differential(r)\n       Drr = Dr^2\n       eq  = Dt(u(t,r)) ~ 1/r^2 * Dr(r^2 * Dr(u(t,r)))\n       bcs = [u(0,r) ~ - r * (r-1) * sin(r),\n              Dr(u(t,0)) ~ 0.0, u(t,1) ~ sin(1)]\n\n       domains = [t \u2208 Interval(0.0,1.0),\n              r \u2208 Interval(0.0,1.0)]\n\n       @named pdesys = PDESystem(eq,bcs,domains,[t,r],[u(t,r)])\n       discretization = MOLFiniteDifference([r=>0.1],t)\n       prob = discretize(pdesys,discretization) # This gives an ODEProblem since it's time-dependent\n       sol = solve(prob,Tsit5())\nend\n\n@testset \"RHS = 0\" begin\n       @parameters x, t\n       @variables u(..)\n       Dt = Differential(t)\n       Dx = Differential(x)\n       Dx2 = Differential(x)^2\n       Dx3 = Differential(x)^3\n       Dx4 = Differential(x)^4\n\n       \u03b1 = 1\n       \u03b2 = 4\n       \u03b3 = 1\n       eq = Dt(u(x,t)) + u(x,t)*Dx(u(x,t)) + \u03b1*Dx2(u(x,t)) + \u03b2*Dx3(u(x,t)) + \u03b3*Dx4(u(x,t)) ~ 0\n\n       du(x,t;z = -x/2+t) = 15/2*(tanh(z) + 1)*(3*tanh(z) - 1)*sech(z)^2\n\n       bcs = [u(x,0) ~ x^2,\n              Dx(u(-10,t)) ~ du(-10,t),\n              Dx(u(10,t)) ~ du(10,t)]\n\n       # Space and time domains\n       domains = [x \u2208 Interval(-10.0,10.0),\n              t \u2208 Interval(0.0,0.5)]\n       # Discretization\n       dx = 0.4; dt = 0.2\n\n       discretization = MOLFiniteDifference([x=>dx],t;approx_order=4)\n       @named pdesys = PDESystem(eq,bcs,domains,[x,t],[u(x,t)])\n       prob = discretize(pdesys,discretization)\nend\n\n@testset \"Wave Equation\" begin\n       # Parameters, variables, and derivatives\n       @parameters t x\n       @variables u(..)\n       Dt = Differential(t)             # Required in ICs and equation\n       Dtt = Differential(t)^2           # required in equation\n       Dxxxx = Differential(x)^4       # required in equation\n       Dxx = Differential(x)^2         # required in BCs\n       # some parameters\n       EI  = 291.6667;\n       m = 1.3850;\n       c = 1.;\n       p = 0.01;\n       L = 2.0;\n\n       # 1D PDE and boundaru conditions\n       eq  = m*Dtt(u(t,x)) + c*Dt(u(t,x)) + EI*Dxxxx(u(t,x)) ~0\n\n       ic_bc = [u(0,x) ~ (p*x*(x^3 + L^3 -2*L*x^2)/(24*EI)), #for all 0 < u < L\n              Dt(u(0,x)) ~ 0.,        # for all 0 < u < L\n              u(t,0) ~ 0.,            # for all t > 0,, displacement zero at u=0\n              u(t,2) ~ 0.,            # for all t > 0,, displacement zero at u=L\n              Dxx(u(t,0)) ~ 0.,       # for all t > 0,, curvature zero at u=0\n              Dxx(u(t,2)) ~ 0.]       # for all t > 0,, curvature zero at u=L\n\n       # Space and time domains\n       domains = [t \u2208 Interval(0.0,2.0),\n              x \u2208 Interval(0.0, L)]\n\n       dt = 0.1   # dt related to saving the data.. not actual dt\n       # PDE sustem\n       @named pdesys = PDESystem(eq,ic_bc,domains,[t,x],[u(t,x)])\n\n       # Method of lines discretization\n       dx = 0.1\n       order = 2\n       discretization = MOLFiniteDifference([x=>dx, t=>dt], approx_order=order)\n\n       # Convert the PDE problem into an ODE problem\n       prob = discretize(pdesys,discretization)  \n\n       # Solve the ODE problem\n       sol = NonlinearSolve.solve(prob, NewtonRaphson())\nend\n\n@testset \"Rearranged Robin\" begin\n       @parameters x t\n\n\t@variables c(..)\n\n\t\u2202t  = Differential(t)\n\t\u2202x  = Differential(x)\n\t\u2202\u00b2x = Differential(x) ^ 2\n\n       D\u2080 = 1.\n       R = 0.5\n       c\u2091 = 2.5\n       \u2113 = 2.0\n       \u03b1 = 1/3\n\n\tdiff_eq = \u2202t(c(x, t)) ~ \u2202x((D\u2080 + \u03b1 * c(x, t)) * \u2202x(c(x, t)))\n\n\tbcs = [c(x, 0) \t ~ 0.0,  \t       # initial condition\n                  R * (D\u2080 + \u03b1 * c(0, t)) * \u2202x(c(0, t)) ~ c(0, t) - c\u2091, # Robin\n                  \u2202x(c(\u2113, t)) ~ 0.0]   # no flux\n\n       domains = [t \u2208 Interval(0.0,10.0),\n                  x \u2208 Interval(0.0, \u2113)]\n\n       @named pdesys = PDESystem(diff_eq,bcs,domains,[t,x],[c(x,t)])\n\n       # Method of lines discretization\n       dx = 0.1\n       order = 2\n       discretization = MOLFiniteDifference([x=>dx],t,approx_order=order)\n\n       # Convert the PDE problem into an ODE problem\n       prob = discretize(pdesys,discretization)  \n\n       sol = solve(prob,Rodas4())\nend\n\n@testset \"Array u\" begin\n\t# Dependencies\n\tN = 6 # number of dependent variables\n\t\n\t# Variables, parameters, and derivatives\n\t@parameters x\n\t@variables u[1:N](..)\n\tDx = Differential(x)\n\tDxx = Differential(x)^2\n\t\n\t# Domain edges\n\tx_min= 0.\n\tx_max = 1.\n\n\t# Discretization parameters\n\tdx = 0.1\n\torder = 2\n\n       #u = collect(u)\n\t\n\t# Equations\n\teqs  = Vector{ModelingToolkit.Equation}(undef, N)\n\tfor i = 1:N\n\t\teqs[i] = Dxx(u[i](x)) ~ u[i](x)\n\tend\n\n\t# Initial and boundary conditions\n\tbcs = Vector{ModelingToolkit.Equation}(undef, 2*N)\n\tfor i = 1:N\n\t\tbcs[i] = Dx(u[i](x_min)) ~ 0.\n\tend\t\n\t\n\tfor i = 1:N\n\t\tbcs[i+N] = u[i](x_max) ~ rand()\n\tend\n\t\n\t# Space and time domains\n\tdomains = [x \u2208 Interval(x_min, x_max)]\n\t\n\t# PDE system\n\t@named pdesys = PDESystem(eqs, bcs, domains, [x], collect([u[i](x) for i = 1:N]))\n\t\n\t# Method of lines discretization\n\tdiscretization = MOLFiniteDifference([x=>dx], nothing, approx_order=order)\n\tprob = ModelingToolkit.discretize(pdesys,discretization)\n\t\n\t# # Solution of the ODE system\n\tsol = NonlinearSolve.solve(prob,NewtonRaphson())\nend\n\n@testset \"2D variable connected to 1D variable at boundary #33\" begin\n       @parameters t x r \n       @variables u(..) v(..)\n       Dt = Differential(t)\n       Dx = Differential(x)\n       Dxx = Differential(x)^2\n       Dr = Differential(r)\n       Drr = Differential(r)^2\n\n       s = u(t,x) + v(t,x,1)\n\n       eqs  = [Dt(u(t,x)) ~ Dxx(u(t,x)) + s,\n              Dt(v(t,x,r)) ~ Drr(v(t,x,r))]\n       bcs = [u(0,x) ~ 1,\n       v(0,x,r) ~ 1,\n       Dx(u(t,0)) ~ 0.0, Dx(u(t,1)) ~ 0.0,\n       Dr(v(t,x,0)) ~ 0.0, Dr(v(t,x,1)) ~ s]\n\n       domains = [t \u2208 Interval(0.0,1.0),\n                  x \u2208 Interval(0.0,1.0),\n                  r \u2208 Interval(0.0,1.0)]\n       \n       @named pdesys = PDESystem(eqs,bcs,domains,[t,x,r],[u(t,x),v(t,x,r)])\n\n       # Method of lines discretization\n       dx = 0.1\n       dr = 0.1\n       order = 2\n       discretization = MOLFiniteDifference([x=>dx,r=>dr], t, approx_order=order)\n\n       # Convert the PDE problem into an ODE problem\n       prob = discretize(pdesys,discretization)\n\n       sol = solve(prob, Tsit5())\nend\n\n \n\n\n@testset \"Testing discretization of varied systems\" begin\n\t@parameters x t\n\n\t@variables c(..)\n\n\t\u2202t  = Differential(t)\n\t\u2202x  = Differential(x)\n\t\u2202\u00b2x = Differential(x) ^ 2\n\t\n\tD\u2080 = 1.5\n\t\u03b1 = 0.15\n\t\u03c7 = 1.2\n\tR = 0.1\n\tc\u2091 = 2.0\n\t\u2113 = 1.0\n\t\u0394x = 0.1\n\t\n\tbcs = [\n              # initial condition\n\t\tc(x, 0) ~ 0.0,\n\t\t# Robin BC\n\t\t\u2202x(c(0.0, t)) / (1 + exp(\u03b1 * (c(0.0, t) - \u03c7))) * R * D\u2080 + c\u2091 - c(0.0, t) ~ 0.0,\t\t  \n\t\t# no flux BC\n\t\t\u2202x(c(\u2113, t)) ~ 0.0]\n              \n              \n       # define space-time plane\n       domains = [x \u2208 Interval(0.0, \u2113), t \u2208 Interval(0.0, 5.0)]\n\n       @testset \"Test 01: \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\" begin\n              D = D\u2080 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7)))\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 02: \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\" begin\n              D = 1.0 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7)))\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(D * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n       \n       @testset \"Test 03: \u2202t(c(x, t)) ~ \u2202x(1.0 / (1.0/D\u2080 + exp(\u03b1 * (c(x, t) - \u03c7))/D\u2080) * \u2202x(c(x, t)))\" begin\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(1.0 / (1.0/D\u2080 + exp(\u03b1 * (c(x, t) - \u03c7))/D\u2080) * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n       \n       @testset \"Test 04: \u2202t(c(x, t)) ~ \u2202x(D\u2080 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7))) * \u2202x(c(x, t)))\" begin\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(D\u2080 / (1.0 + exp(\u03b1 * (c(x, t) - \u03c7))) * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 05: \u2202t(c(x, t)) ~ \u2202x(1/x * \u2202x(c(x, t)))\" begin\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(1/x * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 06: \u2202t(c(x, t)) ~ \u2202x(x*\u2202x(c(x, t)))/c(x,t)\" begin\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(x*\u2202x(c(x, t)))/c(x,t)\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 07: \u2202t(c(x, t)) ~ \u2202x(1/(1+c(x,t)) \u2202x(c(x, t)))\" begin\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(1/(1+c(x,t)) * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 08: \u2202t(c(x, t)) ~ c(x, t) * \u2202x(c(x,t) * \u2202x(c(x, t)))\" begin\n              diff_eq = \u2202t(c(x, t)) ~ c(x, t)*\u2202x(c(x,t) * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 09: \u2202t(c(x, t)) ~ c(x, t) * \u2202x(c(x,t) * \u2202x(c(x, t)))/(1+c(x,t))\" begin\n              diff_eq = c(x, t) * \u2202x(c(x,t) * \u2202x(c(x, t)))/(1+c(x,t))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 10: \u2202t(c(x, t)) ~ c(x, t) * \u2202x(c(x,t) * \u2202x(c(x, t)))/(1+c(x,t))\" begin\n              diff_eq = c(x, t) * \u2202x(c(x,t)^(-1) * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\n       @testset \"Test 11: \u2202t(c(x, t)) ~ \u2202x(1/(1+c(x,t)^2) \u2202x(c(x, t)))\" begin\n              diff_eq = \u2202t(c(x, t)) ~ \u2202x(1/(1+c(x,t)^2) * \u2202x(c(x, t)))\n              @named pdesys = PDESystem(diff_eq, bcs, domains, [x, t], [c(x, t)]);\n              discretization = MOLFiniteDifference([x=>\u0394x], t)\n       end\n\nend\n\n", "meta": {"hexsha": "7940b33c48e6ece0f530133fcf7292e70cab31d5", "size": 12588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pde_systems/MOLtest.jl", "max_stars_repo_name": "pfcrowe/MethodOfLines.jl", "max_stars_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_stars_repo_licenses": ["MIT"], "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/pde_systems/MOLtest.jl", "max_issues_repo_name": "pfcrowe/MethodOfLines.jl", "max_issues_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_issues_repo_licenses": ["MIT"], "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/pde_systems/MOLtest.jl", "max_forks_repo_name": "pfcrowe/MethodOfLines.jl", "max_forks_repo_head_hexsha": "ab2a6e1c3e5214821770a67ad604e8d326f7c152", "max_forks_repo_licenses": ["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.5271317829, "max_line_length": 107, "alphanum_fraction": 0.5003177629, "num_tokens": 4572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7637021578879546}}
{"text": "using CSV, GLM, Plots, Random; pyplot()\nRandom.seed!(0)\n\ndf = CSV.read(\"../data/weightHeight.csv\", copycols = true)\nn = size(df)[1]\ndf[shuffle(1:n),:] = df\ndf[[10,40,60,130,140,175,190,200],:Sex] .= \"O1\"\ndf[[9,44,63,132,138,172,192,199],:Sex] .= \"O2\"\n\nmodel = lm(@formula(Height ~ Weight + Sex), df,\n        contrasts=Dict(:Sex=>DummyCoding(base=\"F\",levels=[\"M\",\"O1\",\"O2\",\"F\"])))\nb0, b1, b2, b3, b4  = coef(model)\npred(weight,sex) = b0+b1*weight+b2*(sex==\"M\")+b3*(sex==\"O1\")+b3*(sex==\"O2\")\nprintln(model)\n\nmales = df[df.Sex .== \"M\",:]\nfemales = df[df.Sex .== \"F\",:]\nother = df[(df.Sex .!= \"M\") .& (df.Sex .!= \"F\"),:]\n\nxlim = [minimum(df.Weight), maximum(df.Weight)]\nscatter(males.Weight, males.Height, c=:blue, msw=0, label=\"Males\")\nplot!(xlim, pred.(xlim,\"M\"), c=:blue, label=\"Male model\")\n\nscatter!(females.Weight, females.Height, c=:red, msw=0, label=\"Females\")\nplot!(xlim, pred.(xlim,\"F\"), \n\tc=:red, label=\"Female model\", xlims=(xlim), \n\txlabel=\"Weight (kg)\", ylabel=\"Height (cm)\", legend=:topleft)\n\nscatter!(other.Weight, other.Height, c=:green, msw=0, label=\"Other\")", "meta": {"hexsha": "f017990dc7ffe15d8f32c0ba49bae89df1e85f98", "size": 1072, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8_chapter/multiLinear.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/multiLinear.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/multiLinear.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": 36.9655172414, "max_line_length": 79, "alphanum_fraction": 0.6138059701, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7637021549294297}}
{"text": "@testset \"polynomials\" begin\n    @test DiscretisedFluidQueues.gauss_lobatto_points(2.0,2.5,1)\u2248[2.25]\n    @test DiscretisedFluidQueues.gauss_lobatto_points(2.0,3.0,2)\u2248[2.0;3.0]\n    @test DiscretisedFluidQueues.gauss_lobatto_points(2.0,4.0,3)\u2248[2.0;3.0;4.0]\n    nnodes = 5\n    nodes = DiscretisedFluidQueues.gauss_lobatto_points(-1.0,1.0,nnodes)\n    for n in 1:nnodes\n        en = zeros(nnodes)\n        en[n] = 1.0\n        @test DiscretisedFluidQueues.lagrange_polynomials(nodes,nodes[n])\u2248en atol=sqrt(eps())\n    end\n    @test DiscretisedFluidQueues.lagrange_polynomials([1.0],1.0)\u2248[1.0] atol=sqrt(eps())\n    @test DiscretisedFluidQueues.gauss_lobatto_weights(-1.0,1.0,1)\u2248[2.0]\n    nnodes = 3\n    nodes = DiscretisedFluidQueues.gauss_lobatto_points(-1.0,1.0,nnodes)\n    @test DiscretisedFluidQueues.gauss_lobatto_weights(-1.0,1.0,nnodes)\u2248[1.0,4.0,1.0]./3\n    x4 = x->x^4\n    x4_interp = DiscretisedFluidQueues.lagrange_interpolation(x4,-1.0,1.0,5)\n    x = collect(-3:0.02:3)\n    @test x4_interp.(x)\u2248x4.(x)\n    x4_quad = DiscretisedFluidQueues.gauss_lobatto_quadrature(x4,-1.0,1.0,4)\n    @test x4_quad\u22482/5\n\n    x4_interp_p0 = DiscretisedFluidQueues.lagrange_interpolation(x->1.0-x4(x),-1.0,1.0,1)\n    x = collect(-3:0.02:3)\n    @test x4_interp_p0.(x)\u2248ones(size(x))\n    x4_quad_p0 = DiscretisedFluidQueues.gauss_lobatto_quadrature(x->1.0-x4(x),-1.0,1.0,1)\n    @test x4_quad_p0\u22482.0\nend ", "meta": {"hexsha": "2a6060d9edb247db830bd7b69ff2788046c10d9f", "size": 1380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/polynomials.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": "test/polynomials.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": "test/polynomials.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": 47.5862068966, "max_line_length": 93, "alphanum_fraction": 0.6971014493, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7636999057259188}}
{"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    \u03c0 * 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\u00b2 = cylinder.radius * cylinder.radius\n    \u0394x = p[1] - cylinder.x\n    \u0394y = p[2] - cylinder.y\n    return \u0394x*\u0394x + \u0394y*\u0394y <= r\u00b2 && 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    \u211b(z::Number, tableau::AbstractButcherTableau) :: Number\n    \u211b(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 \u211b(z::Number, tableau::AbstractButcherTableau)\n    @\u2193 A, b, s = tableau\n    e = ones(s)\n    return det(I - z * (A - e * b')) / det(I - z * A)\nend\n\u211b(z::Number, solver::AbstractRungeKuttaSolver) = \u211b(z, solver.tableau)\n\n\"\"\"\n    \u211b(Z::AbstractMatrix, tableau::AbstractButcherTableau) :: AbstractMatrix\n    \u211b(Z::AbstractMatrix, solver::AbstractRungeKuttaSolver) :: AbstractMatrix\n\nreturns the stability function of an [`AbstractRungeKuttaSolver`](@ref).\n\"\"\"\nfunction \u211b(Z::AbstractMatrix, tableau::AbstractButcherTableau)\n    @\u2193 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\u211b(Z::AbstractMatrix, solver::AbstractRungeKuttaSolver) = \u211b(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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, DataFrames, Plots\n\tRandom.seed!(0)\nend;\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.14\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.14\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u2550fba0be84-3b2f-11eb-1e0f-5f8a1f264dba\n# \u255f\u2500475ff888-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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 774fa124-8560-11eb-2317-53b0d106b67a\nmd\"\"\"\n# Local Search\n\"\"\"\n\n# \u2554\u2550\u2561 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 \u2018cooling rate\u2019 and $k$ is the iteration\n    - fast decrease: $T = T_0/k$\n    - boltzmann decrease: $T = T_0/log(k)$   \n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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, \u03b1::Float64=0.005)\n\t\treturn T0*(1-\u03b1)^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(\u0394E/T), which is between 0 (temp = 0) and one (\u0394E for any T \u2260 0).\n\n\tIn the literature you might also find  1/(1 + exp(\u0394E/T)) \u2208 [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- \u03b1: 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, \u03b1::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,\u03b1=\u03b1)\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\u0394E = fitness(next, optimfun) - fitness(current, optimfun)\n\t\t\t\tif \u0394E > 0 \n\t\t\t\t\tcurrent = next\n\t\t\t\telse\n\t\t\t\t\tif rand() < exp(\u0394E/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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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(\u0394E/T). In the literature you might also find  1/(1 + exp(\u0394E/T)) \u2208 [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, \u03b1::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\u0394E = fitness(next, A) - fitness(current, A)\n\t\t\t\tif \u0394E > 0 \n\t\t\t\t\tcurrent = next\n\t\t\t\telse\n\t\t\t\t\tif rand() < exp(\u0394E/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# \u2554\u2550\u2561 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, \u2018elite selection\u2019)\n* a cross-over method (cutting; 50/50 per gene etc.)\n* mutation rate and method\n* \\\\(\\dots\\\\)\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 728b94da-8566-11eb-1b02-e94c64424845\nbegin\n\toptions = Dict(\t:tmax=>1000, :T0=>273.0, :\u03b1=>0.005, \n               \t\t:fitness=>fitness, :optimfun=>f)\n\tx0 = 0.0;\n\tsimulated_annealing(x0; options...)\nend\n\n# \u2554\u2550\u2561 a72d7c3c-8569-11eb-36a3-cb68ab2622cf\nlet\n\tn = 10;\n\tres = SAsearch(x0,n;options...)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ef64ca86-856c-11eb-0cd0-178565e85576\nlet\n\toptions = Dict(:tmax=>1000, :T0=>273.0, :\u03b1=>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# \u2554\u2550\u2561 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, :\u03b1=>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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2019s string is mapped onto the other parent\u2019s 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# \u2554\u2550\u2561 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 \u2209 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 \u2209 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 (\u224810x longer route and only \u22482x 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# \u2554\u2550\u2561 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, \u2018elite selection\u2019 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1a79eb5a-8577-11eb-168e-8fa9230f26fb\n\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500774fa124-8560-11eb-2317-53b0d106b67a\n# \u2560\u2550bca1c92c-8561-11eb-0420-6f0123bacb7f\n# \u2560\u25502b5e6876-8561-11eb-0685-dfe1cca39c45\n# \u2560\u25504e190a2e-8561-11eb-3759-795e3bb4d8d2\n# \u2560\u2550b49f0528-8561-11eb-36a7-fd42574edc81\n# \u2560\u2550d5019d8a-8561-11eb-2a43-a9ce616532f5\n# \u2560\u2550728b94da-8566-11eb-1b02-e94c64424845\n# \u2560\u2550a72d7c3c-8569-11eb-36a3-cb68ab2622cf\n# \u2560\u25500ce6432c-8567-11eb-1465-432d66051360\n# \u255f\u25009c2e2032-8568-11eb-103f-fdc57c11ab1f\n# \u255f\u2500c84f6af2-8568-11eb-06c4-53f7664294ac\n# \u2560\u255046e468e0-8569-11eb-0a30-d11e814ccf7e\n# \u2560\u25507c5282fa-8569-11eb-0dcf-abc7b3b795ef\n# \u2560\u2550eb27eada-8569-11eb-0739-7717087a5240\n# \u2560\u25501692c654-856a-11eb-1b02-77b0ab027c29\n# \u2560\u25503c58cc1a-856a-11eb-17bd-a31c244f6229\n# \u2560\u25507ab96168-856c-11eb-166a-b7531078ac90\n# \u2560\u2550ef64ca86-856c-11eb-0cd0-178565e85576\n# \u2560\u255057726a64-856d-11eb-2b37-877202c47ede\n# \u2560\u2550d70478c8-856d-11eb-3f27-0b565955b6ed\n# \u255f\u2500934aa9e4-856e-11eb-1924-fd1df8fd3fe2\n# \u255f\u25008753fd9a-856f-11eb-2d91-13657e302031\n# \u2560\u255048c05e06-8570-11eb-0367-1f3db0aa20d0\n# \u2560\u25506faf987e-8570-11eb-1861-7de0f661bd63\n# \u2560\u25509cc2fa40-8570-11eb-2eba-c15433dcb90e\n# \u2560\u2550fd95d464-8570-11eb-1a38-879d8079d127\n# \u255f\u250047153f8e-8572-11eb-1310-c932bd478721\n# \u2560\u25501f5d255c-8576-11eb-1463-89f94258168d\n# \u2560\u25507c4ef658-8576-11eb-3f6d-d3587a1af7e8\n# \u255f\u25008b77cf1c-8571-11eb-2ea7-531abac106cc\n# \u2560\u2550712cb76c-8576-11eb-37c3-87beed1c3fa1\n# \u2560\u2550fa780328-8576-11eb-3a16-b7109ffbad63\n# \u2560\u25501a79eb5a-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# \u2554\u2550\u2561 8dbcf370-1dec-11eb-0a2d-e967ec1f2fde\nmd\" ### Nomenclatura\"\n\n# \u2554\u2550\u2561 c4a8db60-1dec-11eb-0c39-73a8aac79092\nmd\"Seja $X$ uma matriz com dimens\u00f5es $n x m$ com $n$ linhas e $m$ colunas que cont\u00e9m nossos exemplos. $x_i^{(j)}$ corresponde ao elemento de $X$ em que $i$ \u00e9 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# \u2554\u2550\u2561 cd532e00-1dec-11eb-06d9-9b7c76e9c1ba\nmd\"Seja $\\theta$ um vetor linha com $m$ elementos tal que $m$ corresponde ao n\u00famero de atributos mais um. $\\theta = [\\theta^{(0)},\\theta^{(1)}, ...,\\theta^{(m)}]$ em que cada elemento corresponde ao j-\u00e9simo par\u00e2metro associado ao j-\u00e9simo atributo. Na nossa linguagem acessamos um elemento por $\\theta[i]$ e o vetor por $\\theta$\"\n\n# \u2554\u2550\u2561 dc365e10-1dec-11eb-0e4f-95624ee468ea\nmd\"Seja $y$ nosso vetor alvo em que representamos o i-\u00e9simo elemento por $y_i$. Na nossa linguagem representamos por $y[i]$.\"\n\n# \u2554\u2550\u2561 571a5ea0-1dee-11eb-0eaf-bf746a6faa86\nmd\"### Algumas libs importantes usadas neste experimento\"\n\n# \u2554\u2550\u2561 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   \u03bc = mean\t\nend\n\n# \u2554\u2550\u2561 f9af3a70-1dec-11eb-34f0-91b7fc591b87\nmd\" ### Hip\u00f3tese e modelo linear\"\n\n# \u2554\u2550\u2561 78d2c0e0-1f98-11eb-06bc-b51c3b4b9f35\nmd\"A seguir descrevemos a hip\u00f3tese que consiste da aplica\u00e7\u00e3o de um modelo (conjunto de par\u00e2metros) em um exemplo. Note que a hip\u00f3tese sempre se refere \u00e0 aplica\u00e7\u00e3o de um \u00fanico exemplo e n\u00e3o ao conjunto de dados todo. \"\n\n# \u2554\u2550\u2561 2e7709e0-1ded-11eb-2abd-d770bf1afe8a\nmd\"$H_{\\theta}(X_i) = \\sum_{j}^{m}{x_{i}^{(j)} \\theta^{(j)}} = X_i\\theta^{T}$\"\n\n# \u2554\u2550\u2561 b05f9930-1f97-11eb-0083-07ebd21313e0\nmd\"Exemplificando o produto de vetores, nossa hip\u00f3tese faria o seguinte c\u00e1lculo para um exemplo $X_i = \\begin{bmatrix} 1 & 500 \\end{bmatrix}$ e um vetor de par\u00e2metros $\\theta^T = \\begin{bmatrix}\n    0.5 \\\\\n    1.0\n\\end{bmatrix}$:\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4cc76c80-1f98-11eb-0c70-29aec0b92ac4\nmd\"Note que o resultado \u00e9 um escalar, pois estamos estimando um valor cont\u00ednuo (problema de regress\u00e3o).\"\n\n# \u2554\u2550\u2561 c0b094a0-1f98-11eb-2efb-07f680447b12\nmd\"### Implementa\u00e7\u00e3o a hip\u00f3tese\"\n\n# \u2554\u2550\u2561 be0deb50-1ded-11eb-06bb-33e94217e815\nH(\u03c7,\u03b8) = \u03c7*\u0398'\n\n# \u2554\u2550\u2561 2f5a6500-1ded-11eb-11dd-bd88bf102b98\nmd\" ### Fun\u00e7\u00e3o de custo\"\n\n# \u2554\u2550\u2561 30972ac0-1ded-11eb-1007-1d3833dfc264\n\nmd\"$J(\\theta)= \\frac{1}{2n}\\sum_{i=1}^{n}{(H_{\\theta}(X_i) - y_i)\u00b2}$\"\n\n\n# \u2554\u2550\u2561 bba6d590-1e1d-11eb-2df6-67bd6c5d4777\nmd\" A seguir estou calculando a fun\u00e7\u00e3o de custo sem loop, apenas por matrizes.Desta maneira, geramos em uma multiplica\u00e7\u00e3o de matrizes, um vetor de predi\u00e7\u00f5es com a mesma dimens\u00e3o da sa\u00edda. Ap\u00f3s isto, subtra\u00edmos elemento a elemento. Ap\u00f3s isto, elevamos cada elemento ao quadrado e depois tiramos uma m\u00e9dia. Explicado na aula anterior.\"\n\n# \u2554\u2550\u2561 9837a3d0-1ded-11eb-3c49-17a45387e46e\nJ(\u0398,\u03c7,\u03b3) = .5\u03bc((\u03c7*\u0398' .- \u03b3).^2)\n\n# \u2554\u2550\u2561 2ebaad22-1dee-11eb-2fb1-f51c49ec13fb\nmd\"### Gradiente descendente\"\n\n# \u2554\u2550\u2561 d1cf31b0-1e17-11eb-22d1-916c9a331700\nmd\"A seguir, mostramos o c\u00e1lculo do gradiente. Como podemos notar, o expoente 2 desce e \u00e9 eliminado pela constante 2 do denominador. Adicionalemente, vemos que \u00e9 uma subtra\u00e7\u00e3o do gradiente, pois estamos minimizando a fun\u00e7\u00e3o de custo. Por isto, estamos caminhando no sentido contr\u00e1rio ao do gradiente. \u00c9 importante tamb\u00e9m ressaltar que o vi\u00e9s j\u00e1 est\u00e1 embutido na matriz $X$ na forma de uma coluna com valores 1. Desta forma, o c\u00e1lculo do gradiente \u00e9 o mesmo para o par\u00e2metro do vi\u00e9s ($\u03b8^{(0)}$) e os demais.\" \n\n# \u2554\u2550\u2561 cbf654c0-1dfa-11eb-0994-85a67ded79b0\nmd\"$\u03b8^{(j)} = \u03b8^{(j)} - \u03b1 \\frac{1}{n} \\sum_{i=1}^{n}{(H_\u03b8(X_i) - y_i)x_{i}^{(j)}}$\"\n\n# \u2554\u2550\u2561 46484b80-1e1d-11eb-2bdc-e50b24f6b530\nmd\"Entretanto, podemos condensar esta f\u00f3rmula usando nota\u00e7\u00e3o de vetores e matrizes. Lembrando que $\\theta$ \u00e9 um vetor agora e os c\u00e1lculos s\u00e3o feitos simultaneamente para cada eleemnto deste. Podemos observar que o \u00edndice da coluna some, pois s\u00e3o processadas automaticamente. A seguir, veja a f\u00f3rmula:\"\n\n# \u2554\u2550\u2561 f1089b10-1e1d-11eb-120e-cdbd993d72dc\nmd\"$\u03b8 = \u03b8 - \u03b1 \\frac{1}{n} \\sum_{i=1}^{n}{(H_\u03b8(X_i) - y_i) \\circ X_{i}}$\"\n\n# \u2554\u2550\u2561 79bc38d0-1e1f-11eb-066c-2929340c479e\nmd\"Cabe observar que $\\circ$ \u00e9 o produto de hadamard.\"\n\n# \u2554\u2550\u2561 f5d33090-1e1f-11eb-3f25-d10f2616803d\nmd\"### Algoritmo \"\n\n# \u2554\u2550\u2561 7a22eab0-1def-11eb-2672-495fb9cf19f8\nfunction train(\u03b8,\u03c7,\u03b3;verbose=false,\u03b1 = 1e-3,\u03f5=1e-5,\u03c4=1e3)\n\t\n\te\u2082  = J(\u03b8,\u03c7,\u03b3) \n\te\u2081  = e\u2082 + .1\n\t#\u0394\u2081,\u0394\u2082 = e\u2081 - e\u2082 + 2\u03f5,e\u2081 - e\u2082\n\t\ud83d\udcbb = [[e\u2082 \u03b8]]\n\ti   = 1\n\twhile e\u2082 < e\u2081 && e\u2082 > \u03f5 && i < \u03c4    \n\t#while \u0394\u2081 > \u0394\u2082  && e\u2082 > \u03f5 && i < \u03c4     \n\t\t\n\t\t\u2207     = \u03bc((\u03c7*\u03b8' .- \u03b3).* \u03c7,dims=1)\n\t\t\u03b8    -= \u03b1 .* \u2207\n\t\t\n\t\te\u2081,e\u2082 = e\u2082,J(\u03b8,\u03c7,\u03b3)\n\t\t#\u0394\u2081,\u0394\u2082 = \u0394\u2082,e\u2081 - e\u2082\n\t\tverbose && if (i%10==0) append!(\ud83d\udcbb,[[e\u2082 \u03b8]]) end\n\t\t\n\t\ti += 1\n\tend\n\t\u03b8,vcat(\ud83d\udcbb...)\nend\t\n\n# \u2554\u2550\u2561 1f0e51f0-1df4-11eb-0feb-b53552fa63c9\nmd\"### Testes de unit\u00e1rios\"\n\n# \u2554\u2550\u2561 58dd7720-1e09-11eb-1904-af5f9991ece5\nmd\" Sempre que for desenvolver suas fun\u00e7\u00f5es, 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\u00e7\u00e3o de c\u00f3digo. Assim, para cada fun\u00e7\u00e3o, fa\u00e7a pelo menos um teste. Elabore casos bons de entrada para suas fun\u00e7\u00f5es de forma que cubra bem o espa\u00e7o de possibilidades. Seus casos devem ser bem simples para que num futuro, se der erro, voc\u00ea consiga rapidamente resolver.\"\n\n# \u2554\u2550\u2561 259ac040-1e39-11eb-3670-f5c5519a1978\nmd\"### Padronizando os Dados \"\n\n# \u2554\u2550\u2561 246cc792-1e39-11eb-3c20-f1623d8ea737\nmd\"O objetivo de padronizar os dados \u00e9 acelerar a converg\u00eancia do m\u00e9todo. Aqui utilizaremos a padroniza\u00e7\u00e3o zscore. Entretanto, para amostras pequenas, a padroniza\u00e7\u00e3o n\u00e3o funciona muito bem.\"\n\n# \u2554\u2550\u2561 c467ca00-1e08-11eb-3d41-75a38532652b\nmd\"### Verificando a curva de erro\"\n\n# \u2554\u2550\u2561 d1a88a00-1f8f-11eb-36b7-f39dabee0657\nmd\"### Veificando o comportamento dos par\u00e2metros\"\n\n# \u2554\u2550\u2561 b405694e-1f8f-11eb-0fad-5d0c3527d206\nmd\"### Verificando o modelo\"\n\n# \u2554\u2550\u2561 d497051e-1f94-11eb-2ccb-a7d3e52570d1\nmd\"Como podemos observar, o gradiente jogou o \u03b8\u2081 para zero (vi\u00e9s, respons\u00e1vel pela transla\u00e7\u00e3o) e ajustou o \u03b8\u2082 (respons\u00e1vel pela rota\u00e7\u00e3o). Cabe ressaltar que estamos trabalhando com os dados padronizados. \u00c9 poss\u00edvel, no entanto, despadronizar e obter predi\u00e7\u00f5es no campo dos n\u00fameros originais.\"\n\n# \u2554\u2550\u2561 37c52e40-1e48-11eb-1e13-7ba1bebfabc4\nmd\"### Depura\u00e7\u00e3o \"\n\n# \u2554\u2550\u2561 44997b82-1e48-11eb-1821-f7f3aecd8093\nmd\" Costumo colocar alguma vari\u00e1veis soltas para que eu veja se est\u00e1 tudo correto. \"\n\n# \u2554\u2550\u2561 a419b220-1e4b-11eb-1299-295bf39df3f4\nmd\"### Solu\u00e7\u00e3o direta por \u00e1lgebra linear\"\n\n# \u2554\u2550\u2561 a39cb9f0-1e4b-11eb-296e-bf19e5438416\ntrain(X,Y) = inv(X'X)X'Y\n\n# \u2554\u2550\u2561 628624c0-1dfa-11eb-2afb-137bf77669e1\nbegin\n\t\u03981 = [0. 4.] \n\t\u03c7 =  [1 50.;1 60.;1 100.; 1 200.]\n\t\u03b3 =  [200  ;   240  ;   400; 800]\n\t@assert J(\u03981,\u03c7,\u03b3) == 0.0\n\t@assert train(\u03981,\u03c7,\u03b3)[1] == [0. 4.] # iniciando com a solu\u00e7\u00e3o, o \u03b8 deve continuar igual\nend\t\n\n# \u2554\u2550\u2561 4c632fee-1e39-11eb-00c6-c3f2a0774005\nbegin \n\t\u03c7\u209a = hcat(ones((4,1)), zscore(\u03c7[:,2:end])) # padronizamos s\u00f3 o que n\u00e3o \u00e9 vi\u00e9s\n\t\u03b3\u209a = zscore(\u03b3)\nend\t\n\n# \u2554\u2550\u2561 d8ab5330-1e47-11eb-06b3-af3d2ee97c7b\n\u03c7\u209a\n\n# \u2554\u2550\u2561 86be2920-1e48-11eb-10f1-6740a2459951\n\u03b3\u209a\n\n# \u2554\u2550\u2561 74604cb2-1e05-11eb-19ef-09fd04dc52e3\n(\u03b8\u1d4f,r) = train([4 5],\u03c7\u209a,\u03b3\u209a,verbose=true,\u03b1 = 1e-3,\u03f5=1e-5,\u03c4=1e5);\n\n# \u2554\u2550\u2561 b7913600-1e0c-11eb-362e-0b4b9ef9d1aa\nplot(1:length(r[:,1]),r[:,1],xlabel=\"itera\u00e7\u00f5es\",ylabel=\"J(\u03b8)\",title=\"An\u00e1lise de erros\",label=\"Erro\")\n\n# \u2554\u2550\u2561 fa0bd460-1e23-11eb-131f-f31bec373c07\nbegin\n\tp = plot(1:length(r[:,2]),r[:,2],xlabel=\"itera\u00e7\u00f5es\",ylabel=\"\u03b8\u2081,\u03b8\u2082\",title=\"An\u00e1lise de par\u00e2metros\",label=\"\u03b8\u2081\")\n\tplot!(p,1:length(r[:,3]),r[:,3],xlabel=\"itera\u00e7\u00f5es\",label=\"\u03b8\u2082\")\nend\t\n\n# \u2554\u2550\u2561 cc73d620-1f8f-11eb-357d-b19b50c19280\nbegin\n\tf(x) = \u03b8\u1d4f[1] + \u03b8\u1d4f[2]*x # o mesmo que H(X) l\u00e1 do in\u00edcio\n\tplot(\u03c7\u209a[:,2],f,xlabel=\"m\u00b2 (padronizado)\",ylabel=\"Pre\u00e7o (padronizado)\",title=\"An\u00e1lise do da predi\u00e7\u00e3o do modelo\",label=\"\u03b8\u2081 + \u03b8\u2082x\")\n\tscatter!(\u03c7\u209a[:,2],\u03b3\u209a,label=\"Dados Coletados\")\nend\t\n\n# \u2554\u2550\u2561 41505b10-1e34-11eb-06db-750eb3ab11cf\nr[end,:]\n\n# \u2554\u2550\u2561 29b04780-1e44-11eb-3bcf-8b5f121d157f\nJ(\u03b8\u1d4f,\u03c7\u209a,\u03b3\u209a)\n\n# \u2554\u2550\u2561 d0de29e0-1e36-11eb-398c-5f0b55ea281e\n\u03b8\u1d4f\n\n# \u2554\u2550\u2561 70775a70-1e4c-11eb-3cec-11fd54e9b637\ntrain(\u03c7\u209a,\u03b3\u209a) \n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25008dbcf370-1dec-11eb-0a2d-e967ec1f2fde\n# \u255f\u2500c4a8db60-1dec-11eb-0c39-73a8aac79092\n# \u255f\u2500cd532e00-1dec-11eb-06d9-9b7c76e9c1ba\n# \u255f\u2500dc365e10-1dec-11eb-0e4f-95624ee468ea\n# \u255f\u2500571a5ea0-1dee-11eb-0eaf-bf746a6faa86\n# \u2560\u2550317bbe60-1ded-11eb-2faa-c3e47c0df176\n# \u255f\u2500f9af3a70-1dec-11eb-34f0-91b7fc591b87\n# \u255f\u250078d2c0e0-1f98-11eb-06bc-b51c3b4b9f35\n# \u255f\u25002e7709e0-1ded-11eb-2abd-d770bf1afe8a\n# \u255f\u2500b05f9930-1f97-11eb-0083-07ebd21313e0\n# \u255f\u2500cbf998e0-1f96-11eb-0a8b-a3bf631bfe02\n# \u255f\u25004cc76c80-1f98-11eb-0c70-29aec0b92ac4\n# \u255f\u2500c0b094a0-1f98-11eb-2efb-07f680447b12\n# \u2560\u2550be0deb50-1ded-11eb-06bb-33e94217e815\n# \u255f\u25002f5a6500-1ded-11eb-11dd-bd88bf102b98\n# \u255f\u250030972ac0-1ded-11eb-1007-1d3833dfc264\n# \u255f\u2500bba6d590-1e1d-11eb-2df6-67bd6c5d4777\n# \u2560\u25509837a3d0-1ded-11eb-3c49-17a45387e46e\n# \u255f\u25002ebaad22-1dee-11eb-2fb1-f51c49ec13fb\n# \u255f\u2500d1cf31b0-1e17-11eb-22d1-916c9a331700\n# \u255f\u2500cbf654c0-1dfa-11eb-0994-85a67ded79b0\n# \u255f\u250046484b80-1e1d-11eb-2bdc-e50b24f6b530\n# \u255f\u2500f1089b10-1e1d-11eb-120e-cdbd993d72dc\n# \u255f\u250079bc38d0-1e1f-11eb-066c-2929340c479e\n# \u255f\u2500f5d33090-1e1f-11eb-3f25-d10f2616803d\n# \u2560\u25507a22eab0-1def-11eb-2672-495fb9cf19f8\n# \u255f\u25001f0e51f0-1df4-11eb-0feb-b53552fa63c9\n# \u255f\u250058dd7720-1e09-11eb-1904-af5f9991ece5\n# \u2560\u2550628624c0-1dfa-11eb-2afb-137bf77669e1\n# \u255f\u2500259ac040-1e39-11eb-3670-f5c5519a1978\n# \u255f\u2500246cc792-1e39-11eb-3c20-f1623d8ea737\n# \u2560\u25504c632fee-1e39-11eb-00c6-c3f2a0774005\n# \u255f\u2500c467ca00-1e08-11eb-3d41-75a38532652b\n# \u2560\u255074604cb2-1e05-11eb-19ef-09fd04dc52e3\n# \u255f\u2500b7913600-1e0c-11eb-362e-0b4b9ef9d1aa\n# \u255f\u2500d1a88a00-1f8f-11eb-36b7-f39dabee0657\n# \u2560\u2550fa0bd460-1e23-11eb-131f-f31bec373c07\n# \u255f\u2500b405694e-1f8f-11eb-0fad-5d0c3527d206\n# \u255f\u2500d497051e-1f94-11eb-2ccb-a7d3e52570d1\n# \u2560\u2550cc73d620-1f8f-11eb-357d-b19b50c19280\n# \u255f\u250037c52e40-1e48-11eb-1e13-7ba1bebfabc4\n# \u255f\u250044997b82-1e48-11eb-1821-f7f3aecd8093\n# \u2560\u255041505b10-1e34-11eb-06db-750eb3ab11cf\n# \u2560\u255029b04780-1e44-11eb-3bcf-8b5f121d157f\n# \u2560\u2550d0de29e0-1e36-11eb-398c-5f0b55ea281e\n# \u2560\u2550d8ab5330-1e47-11eb-06b3-af3d2ee97c7b\n# \u2560\u255086be2920-1e48-11eb-10f1-6740a2459951\n# \u255f\u2500a419b220-1e4b-11eb-1299-295bf39df3f4\n# \u2560\u2550a39cb9f0-1e4b-11eb-296e-bf19e5438416\n# \u2560\u255070775a70-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    \u03b2 = norm(b)\n    qk = copy(b)\n\n    @views for k = 1:m\n        q[:,k] .= qk/\u03b2\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        \u03b2 = norm(qk)\n        h[k+1,k] = \u03b2\n        if \u03b2 < 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    \u03b2 = norm(r)\n    qk = copy(r)\n\n    @views for k = 1:m\n        q[:,k] = qk/\u03b2\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        \u03b2 = norm(qk)\n        h[k+1,k] = \u03b2\n        if \u03b2 < 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    \u03b2 = norm(b)\n    qk = copy(b)\n\n    @views for k = 1:m\n        q[:,k] .= qk/\u03b2\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        \u03b2 = norm(qk)\n        h[k+1,k] = \u03b2\n        if \u03b2 < 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    \u03b2 = norm(r)\n    qk = copy(r)\n\n    @views for k = 1:m\n        q[:,k] = qk/\u03b2\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        \u03b2 = norm(qk)\n        h[k+1,k] = \u03b2\n        if \u03b2 < 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    \u03b2 = norm(r)\n    qk = copy(r)\n\n    @views for k = 1:m\n        q[:,k] = qk/\u03b2\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        \u03b2 = norm(qk)\n        h[k+1,k] = \u03b2\n        if \u03b2 < 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)) \u00f7 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": "# Sum square difference\n\nLIMIT = 100\n\n\nfunction solve()\n    return sum(1:LIMIT)^2 - sum(n^2 for n in 1:LIMIT)\nend\n\n\nprint(Int(solve()))", "meta": {"hexsha": "d7aacb57e647b1fe82e8c29f2d21ffbf87da8a6c", "size": 135, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p006.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/p006.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/p006.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": 12.2727272727, "max_line_length": 53, "alphanum_fraction": 0.6592592593, "num_tokens": 42, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620539235896, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7636424500123147}}
{"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 + \u03c0)\n\nprintln(typeof(\u03c0)) # 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(\"\u221a16 ~~> \", \u221a16)\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    \u03bb::T\n    \u03c3::T\n    p::T\n\n    function Exponential{T}(\u03bb::T, \u03c3::T, p::T) where T\n        \u03bb > 0 || throw(DomainError(\u03bb, \"correlation length \u03bb of exponential covariance cannot be negative or zero\"))\n        \u03c3 > 0 || throw(DomainError(\u03c3, \"marginal standard deviation \u03c3 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}(\u03bb, \u03c3, p)\n    end\nend\n\n\"\"\"\n    Exponential(\u03bb, [\u03c3 = 1], [p = 2])\n\nExponential covariance structure with correlation length `\u03bb`, (optional) marginal standard deviation `\u03c3` and (optional) `p`-norm defined as\n\n``C(x, y) = \u03c3 \\\\exp\\\\left(-\\\\displaystyle\\\\frac{\u03c1}{\u03bb}\\\\right)``\n\nwith ``\u03c1 = ||x - y||_p``.\n\n# Examples\n```jldoctest\njulia> Exponential(0.1)\nexponential (\u03bb=0.1, \u03c3=1.0, p=2.0)\n\njulia> Exponential(1.0, \u03c3=2)\nexponential (\u03bb=1.0, \u03c3=2.0, p=2.0)\n\n```\nSee also: [`Linear`](@ref), [`Spherical`](@ref), [`Whittle`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nExponential(\u03bb::Real; \u03c3::Real=1.0, p::Real=2) = Exponential{promote_type(typeof(\u03bb),typeof(\u03c3),typeof(p))}(promote(\u03bb, \u03c3, p)...)\n\n# evaluate exponential covariance\napply(e::Exponential, x::Real) = exp(-x / e.\u03bb)\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": "using Random, Distributions\nRandom.seed!(0)\n\nlambda = 0.1\ndist = Exponential(1/lambda)\nactualMedian = median(dist)\n\nM = 10^3\nN = 10^4\nnRange = 2:2:10\nalpha = 0.05\n\nfor n in nRange\n    coverageCount = 0\n    for _ in 1:M\n        sampleData = rand(dist, n)\n        bootstrapSampleMeans = [median(rand(sampleData, n)) for _ in 1:N]\n        L = quantile(bootstrapSampleMeans, alpha/2)\n        U = quantile(bootstrapSampleMeans, 1-alpha/2)\n        coverageCount += L < actualMedian && actualMedian < U\n    end\n    println(\"n = \",n,\"\\t coverage = \", coverageCount/M)\nend", "meta": {"hexsha": "61c3889b75af994f165e794a6df69684ad1be8ae", "size": 563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6_chapter/bootstrapCI.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/bootstrapCI.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/bootstrapCI.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.4782608696, "max_line_length": 73, "alphanum_fraction": 0.6447602131, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030094, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7636192572538336}}
{"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 \u03b1, \u03b2, \u03b3, \u03b4, p, q, a, b, A, y\u2080, z\u2080 = 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\u2080\n    z[1] = z\u2080\n\n    # Compute the rest\n    for i in 1:n\n        x = a + i * h\n        y\u1d62\u208a\u2081(x, z\u1d62\u208a\u2081) = (y[i] + h * (\u03b2(A) * z\u1d62\u208a\u2081 + p(x, z\u1d62\u208a\u2081))) / (1 - h * \u03b1(A))\n        z[i+1] = find_zero(\n            (z\u1d62\u208a\u2081) -> -z\u1d62\u208a\u2081 + z[i] + h * (\u03b3(A) * y\u1d62\u208a\u2081(x, z\u1d62\u208a\u2081) + \u03b4(A) * z\u1d62\u208a\u2081 + q(x, z\u1d62\u208a\u2081)),\n            z[i],\n        )\n        y[i+1] = y\u1d62\u208a\u2081(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": "@testset \"Norms\" begin\n    x = [2.0im, 3.0 - 1im, 5.0 + 2.0im]\n    y = [-2.0im, 3.0 - 1im, 5.0 + 2.0im]\n    Norm = HC.InfNorm()\n    @test Norm isa HC.AbstractNorm\n    @test Norm(x) \u2248 abs(5.0 + 2.0im)\n    @test Norm(x, x) \u2248 0.0\n    @test Norm(x, y) \u2248 abs(4im)\n\n    WeightedNorm = HC.WeightedNorm(Norm, x)\n    @test HC.weights(WeightedNorm) == ones(3)\n    WeightedNorm .= 2.0\n    @test HC.weights(WeightedNorm) == [2.0, 2, 2]\n    WeightedNorm[1] = 4.0\n    @test WeightedNorm isa HC.AbstractNorm\n    @test WeightedNorm(x) \u2248 0.5 * abs(5 + 2.0im)\n    @test WeightedNorm(x, x) \u2248 0.0\n    @test WeightedNorm(x, y) \u2248 0.25 * abs(4im)\n\n    Norm = HC.EuclideanNorm()\n    @test Norm isa HC.AbstractNorm\n\n    @test Norm(x) \u2248 LinearAlgebra.norm(x, 2)\n    @test Norm(x, x) \u2248 0.0\n    @test Norm(x, y) \u2248 abs(4im)\n\n    WeightedNorm = HC.WeightedNorm([4.0, 2.0, 2.0], Norm)\n    @test WeightedNorm isa HC.AbstractNorm\n    @test WeightedNorm(x) \u2248 sqrt(abs2(x[1]) / 16 + abs2(x[2]) / 4 + abs2(x[3]) / 4)\n    @test WeightedNorm(x, x) \u2248 0.0\n    @test WeightedNorm(x, y) \u2248 sqrt(abs2(4im) / 16)\nend\n", "meta": {"hexsha": "6d06cf66e34e41ecc07c2135988cdb7adb7db930", "size": 1072, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "v1/test/norms_test.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/test/norms_test.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/test/norms_test.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": 32.4848484848, "max_line_length": 83, "alphanum_fraction": 0.5830223881, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8080672181749421, "lm_q1q2_score": 0.7636192441233702}}
{"text": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing Distributions\nusing Random\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\nfunction sir_sde!(du,u,p,t)\n    (S,I,R) = u\n    (\u03b2,c,\u03b3,\u03b4t) = p\n    N = S+I+R\n    ifrac = \u03b2*c*I/N*S*\u03b4t\n    rfrac = \u03b3*I*\u03b4t\n    ifrac_noise = sqrt(ifrac)*rand(Normal(0,1))\n    rfrac_noise = sqrt(rfrac)*rand(Normal(0,1))\n    @inbounds begin\n        du[1] = S-(ifrac+ifrac_noise)\n        du[2] = I+(ifrac+ifrac_noise) - (rfrac + rfrac_noise)\n        du[3] = R+(rfrac+rfrac_noise)\n    end\n    for i in 1:3\n        if du[i] < 0 du[i]=0 end\n    end\n    nothing\nend;\n\n\n\u03b4t = 0.1\nnsteps = 400\ntmax = nsteps*\u03b4t\ntspan = (0.0,nsteps)\nt = 0.0:\u03b4t:tmax;\n\n\nu0 = [990.0,10.0,0.0]; # S,I,R\n\n\np = [0.05,10.0,0.25,\u03b4t]; # \u03b2,c,\u03b3,\u03b4t\n\n\nRandom.seed!(1234);\n\n\nprob_sde = DiscreteProblem(sir_sde!,u0,tspan,p)\n\n\nsol_sde = solve(prob_sde,solver=FunctionMap);\n\n\ndf_sde = DataFrame(sol_sde')\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\n@benchmark solve(prob_sde,solver=FunctionMap)\n\n\ninclude(joinpath(@__DIR__,\"tutorials\",\"appendix.jl\"))\nappendix()\n\n", "meta": {"hexsha": "18c26e8119972db90bb72f4bfba58b1873c71932", "size": 1137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/sde/sde.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/sde.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/sde.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": 16.2428571429, "max_line_length": 61, "alphanum_fraction": 0.6156552331, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7636192407142723}}
{"text": "using ML\nusing Base.Test\n\n\nx,y = rand(10),rand(10)\n\nk = GaussianKernel(\u03c3=0.3)\n@test k(x,y) \u2248 exp(-norm(x-y)^2/(2*k.\u03c3^2))\n\nk = PolynomialKernel(\u03b1=10.0,c=1.5,\u03be=2.5)\n@test k(x,y) \u2248 (k.\u03b1*dot(x,y) + k.c)^k.\u03be\n\n\n\n\nx_train = linspace(0,1,30)[:,:]'\ny_train = sin(vec(x_train))\nx_test = linspace(0,1,100)[:,:]'\ny_test = sin(vec(x_test))\n\nfor k in ( GaussianKernel(\u03c3=0.5),\n\t\t   PolynomialKernel(\u03b1=5.,c=0.1,\u03be=4.),\n\t\t   ExponentialKernel(\u03c3=10) )\n    m = KRR(x_train,y_train,k=k,\u03bb=1e-8)\n    fit!(m)\n    @test mae(m(x_test),y_test) < 1e-4\nend\n\n\n\n", "meta": {"hexsha": "56e840a434fa95c059fb1aabc1405941b4840e11", "size": 531, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "johncsnyder/ML.jl", "max_stars_repo_head_hexsha": "9e5767a37048d43eb62ae3598c67b5641ba642ee", "max_stars_repo_licenses": ["MIT"], "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": "johncsnyder/ML.jl", "max_issues_repo_head_hexsha": "9e5767a37048d43eb62ae3598c67b5641ba642ee", "max_issues_repo_licenses": ["MIT"], "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": "johncsnyder/ML.jl", "max_forks_repo_head_hexsha": "9e5767a37048d43eb62ae3598c67b5641ba642ee", "max_forks_repo_licenses": ["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.1290322581, "max_line_length": 42, "alphanum_fraction": 0.5913370998, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.763572775152664}}
{"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\u03c0),(abs(x)/max)^.5,1),vals) \nend\n\n\nfunction spherical_plot(fun::Function, n::Int)\n    # n sets the resolution\n    \u03b8 = [0;(0.5:n-0.5)/n;1]\n    \u03c6 = [(0:2n-2)*2/(2n-1);2]\n    x = [cospi(\u03c6)*sinpi(\u03b8) for \u03b8 in \u03b8, \u03c6 in \u03c6]\n    y = [sinpi(\u03c6)*sinpi(\u03b8) for \u03b8 in \u03b8, \u03c6 in \u03c6]\n    z = [cospi(\u03b8) for \u03b8 in \u03b8, \u03c6 in \u03c6]\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    \u1ef9 = y + h / 2 * f(t, y)\n    t + h, y + h * f(t + h / 2, \u1ef9)\nend\n\n# ---\n\n# ## Runge-Kutta 4th order\n\nfunction rk4(f, t, y, dt)\n\n    y\u2081 = dt * f(t, y)\n    y\u2082 = dt * f(t + dt / 2, y + y\u2081 / 2)\n    y\u2083 = dt * f(t + dt / 2, y + y\u2082 / 2)\n    y\u2084 = dt * f(t + dt, y + y\u2083)\n\n    t + dt, y + (y\u2081 + 2 * y\u2082 + 2 * y\u2083 + y\u2084) / 6\n\nend\n\n# ---\n\n# ## Solve function\n\nfunction dsolve(f, method, t\u2080, y\u2080, h, nsteps)\n\n    t = zeros(Float64, nsteps)\n    y = similar(t)\n\n    t[1] = t\u2080\n    y[1] = y\u2080\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\u2080, x\u2080 = 0.0, 0.0\ndt = tfinal / (nsteps - 1)\nf(t, x) = 1 - x\n\nt, y_euler = dsolve(f, euler, t\u2080, x\u2080, dt, nsteps)\n\nt, y_rk2 = dsolve(f, rk2, t\u2080, x\u2080, dt, nsteps)\n\nt, y_rk4 = dsolve(f, rk4, t\u2080, x\u2080, 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\u2080, t = 0.0, (0.0, 5.0)\n\nprob = ODEProblem(f, y\u2080, 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\ud83d\udc01 = \u03b1*\ud83d\udc01  - \u03b2*\ud83d\udc01*\ud83d\udc08\n  d\ud83d\udc08 = -\u03b3*\ud83d\udc08 + \u03b4*\ud83d\udc01*\ud83d\udc08\nend \u03b1 \u03b2 \u03b3 \u03b4\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 = [\u03b1, \u03b2, \u03b4, \u03b3]\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\u2080 = [0, \u03c0 / 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    \u03b8 = u[1]\n    d\u03b8 = u[2]\n    du[1] = d\u03b8\n    du[2] = -(g/L)*\u03b8\nend\n\nprob = ODEProblem(simplependulum, u\u2080, tspan)\nsol = solve(prob, Tsit5(), reltol = 1e-6)\n\n\n# ---\n\n# Analytic and computed solution\nu = u\u2080[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 \u00b1 0.02; # Gravitational constants\nL = 1.00 \u00b1 0.01; # Length of the pendulum\n\n#Initial Conditions\nu\u2080 = [0 \u00b1 0, \u03c0 / 60 \u00b1 0.01] # Initial speed and initial angle\n\n#Define the problem\nfunction simplependulum(du, u, p, t)\n    \u03b8 = u[1]\n    d\u03b8 = u[2]\n    du[1] = d\u03b8\n    du[2] = -(g/L)*\u03b8\nend\n\n#Pass to solvers\nprob = ODEProblem(simplependulum, u\u2080, tspan)\nsol = solve(prob, Tsit5(), reltol = 1e-6);\nnothing # hide\n\n#md # ---\n\n# Analytic solution\nu = u\u2080[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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 12d5824c-0873-49a8-a5d8-f93c73b633ae\nusing PlutoUI; PlutoUI.TableOfContents()\n\n# \u2554\u2550\u2561 20c5c7bc-664f-4c04-8215-8f3a9a2095c9\nbegin\n    using MLCourse\n    MLCourse.list_notebooks(@__FILE__)\nend\n\n# \u2554\u2550\u2561 8217895b-b120-4b08-b18f-d921dfdddf10\nmd\"# Linear Regression\n\n## Wind speed prediction with one predictor\n\"\n\n# \u2554\u2550\u2561 9f84bcc5-e5ab-4935-9076-c19e9bd668e8\nweather = CSV.read(joinpath(@__DIR__, \"..\", \"data\", \"weather2015-2018.csv\"), DataFrame);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8c9ae8f7-81b2-4d60-a8eb-ded5364fe0cc\nfitted_params(m1)\n\n# \u2554\u2550\u2561 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 \u03c3.\n\"\n\n# \u2554\u2550\u2561 9b62c374-c26e-4990-8ffc-790928e62e88\npredict(m1, (LUZ_pressure = [930., 960., 990.],))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 57f352dc-55ee-4e14-b68d-698938a97d92\nrmse(predict(m1, training_set1.X), training_set1.y)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ce536f60-68b3-4901-bd6a-c96378054b12\nrmse(predict(m1, test_set1.X), test_set1.y)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 51c9ea74-3110-4536-a4af-7cc73b45a4a6\nmd\"\u03b2\u2080 = $(@bind \u03b2\u2080 Slider(-1:.02:1, default = .4, show_value = true))\n\n\u03b2\u2081 = $(@bind \u03b2\u2081 Slider(-1:.02:1, default = .2, show_value = true))\n\n\u03b2\u2082 = $(@bind \u03b2\u2082 Slider(-1:.02:1, default = -.6, show_value = true))\n\"\n\n# \u2554\u2550\u2561 0f544053-1b7a-48d6-b18b-72092b124305\nbegin\n    Random.seed!(3)\n\tX = DataFrame(X1 = randn(20), X2 = randn(20))\n    f0(X1, X2, \u03b2\u2080, \u03b2\u2081, \u03b2\u2082) = \u03b2\u2080 + \u03b2\u2081 * X1 + \u03b2\u2082 * X2\n    f0(\u03b2\u2080, \u03b2\u2081, \u03b2\u2082) = (X1, X2) -> f0(X1, X2, \u03b2\u2080, \u03b2\u2081, \u03b2\u2082)\n\tdata_generator(X1, X2; \u03b2\u2080, \u03b2\u2081, \u03b2\u2082, \u03c3 = 0.8) = f0(X1, X2, \u03b2\u2080, \u03b2\u2081, \u03b2\u2082) + \u03c3 * randn()\n\ty = data_generator.(X.X1, X.X2, \u03b2\u2080 = .4, \u03b2\u2081 = .5, \u03b2\u2082 = -.6)\nend;\n\n\n# \u2554\u2550\u2561 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(\u03b2\u2080, \u03b2\u2081, \u03b2\u2082),\n               label = \"function\", title = \"data & function\", color = :green)\n    plot_residuals!(X.X1, X.X2, y, f0(\u03b2\u2080, \u03b2\u2081, \u03b2\u2082))\n    p2 = contour(-1:.1:1, -1:.1:1, (\u03b2\u2080, \u03b2\u2081) -> mean((\u03b2\u2080 .+ \u03b2\u2081 .* X.X1 .+ \u03b2\u2082 .* X.X2 .- y).^2), levels = 100, ylabel = \"\u03b2\u2081\", cbar = false, title = \"loss\")\n    scatter!([\u03b2\u2080], [\u03b2\u2081], label = nothing)\n    p3 = contour(-1:.1:1, -1:.1:1, (\u03b2\u2080, \u03b2\u2082) -> mean((\u03b2\u2080 .+ \u03b2\u2081 .* X.X1 .+ \u03b2\u2082 .* X.X2 .- y).^2), levels = 100, xlabel = \"\u03b2\u2080\", ylabel = \"\u03b2\u2082\")\n    scatter!([\u03b2\u2080], [\u03b2\u2082], label = \"current loss\")\n    plot(p1, plot(p2, p3, layout = (2, 1)), layout = (1, 2),\n         size = (700, 400), legend = false)\nend\n\n# \u2554\u2550\u2561 da6462d8-3343-41d8-82dd-48770176d4ba\nmd\"## Wind speed prediction with multiple predictors\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 99a371b2-5158-4c42-8f50-329352b6c1f2\nmd\"# Error Decomposition\n\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 05354df5-a803-422f-87a3-1c56a34e8a48\nf\u0302(x) = 0.1 + x\n\n# \u2554\u2550\u2561 9e61b4c3-1a9f-41a7-9882-25ed797a7b8d\nexpected_error(f, x) = mean((conditional_generator(x, n = 10^6) .- f(x)).^2);\n\n# \u2554\u2550\u2561 c6a59b85-d031-4ad4-9e24-691494d08cde\nexpected_error(f\u0302, .1)\n\n# \u2554\u2550\u2561 e50b8196-e804-473a-b3b5-e22fdb9d2f45\n(f(.1) - f\u0302(.1))^2\n\n# \u2554\u2550\u2561 f413ea94-36ca-4afc-8ca8-9a7e88101980\nexpected_error(f, .1)\n\n# \u2554\u2550\u2561 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\u0302, label = \"f\u0302\")\n    p2 = plot(grid, expected_error.(f\u0302, grid), label = \"expected error f\u0302\", w = 3)\n    plot!(grid, (f.(grid) .- f\u0302.(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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 72969aca-b203-4d83-8923-74e523aa1c01\nimport TextAnalysis: Corpus, StringDocument, DocumentTermMatrix, lexicon,\n                     update_lexicon!, tf\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c50c529f-d393-4854-b5ed-91e90d557d12\nbegin\n    crps = Corpus(StringDocument.(spamdata.text[1:2000]))\n    update_lexicon!(crps)\n    lexicon(crps)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03b8\u2080 = $(@bind \u03b8\u2080 Slider(-3:3, default = 0, show_value = true))\n\n\u03b8\u2081 = $(@bind \u03b8\u2081 Slider(-8:8, default = 3, show_value = true))\n\n\u03b8\u2082 = $(@bind \u03b8\u2082 Slider(-8:8, default = 0, show_value = true))\n\"\n\n# \u2554\u2550\u2561 fd4165dc-c3e3-4c4c-9605-167b5b4416da\nmd\"## Confusion Matrix, ROC and AUC\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4f89ceab-297f-4c2c-9029-8d2d7fad084f\nlet f(x1, x2) = logistic(\u03b8\u2080 + \u03b8\u2081 * x1 + \u03b8\u2082 * 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# \u2554\u2550\u2561 285c6bfc-5f29-46e0-a2c1-8abbec74501b\nbegin\n    Random.seed!(seed)\n    auc_samples_x = 2 * randn(200)\nend;\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 62ad57e5-1366-4635-859b-ccdab2efd3b8\nmd\"## Multiple Logistic Regression on the spam data\"\n\n# \u2554\u2550\u2561 29e1d9ff-4375-455a-a69b-8dd0c2cac57d\nm3 = fit!(machine(LogisticClassifier(penalty = :none),\n                  normalized_word_counts,\n                  spam_or_ham));\n\n# \u2554\u2550\u2561 1d1a24c6-c166-49a2-aa21-7acf50b55a66\npredict(m3, normalized_word_counts)\n\n# \u2554\u2550\u2561 32bafa9e-a35e-4f54-9857-d269b47f95c3\nconfusion_matrix(predict_mode(m3, normalized_word_counts), spam_or_ham)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 21b66582-3fda-401c-9421-73ae2f455a75\npredict_mode(m3, normalized_word_counts)\n\n# \u2554\u2550\u2561 ba4b5683-5932-415e-8772-8b3eef5eb63d\nmd\"We save also the test data for future usage.\"\n\n# \u2554\u2550\u2561 a30578dd-aecb-46eb-b947-f009282cf2fc\nmd\"Let us evaluate the fit in terms of commonly used losses for binary classification.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dd463687-b73d-4e70-b2cf-97a56a0ad409\nlosses(m3, normalized_word_counts, spam_or_ham)\n\n# \u2554\u2550\u2561 57dcadc0-2da2-4521-aeaf-6fd01f4bd82b\nspam_or_ham\n\n# \u2554\u2550\u2561 935adbcd-48ab-4a6f-907c-b04137ca3abe\nlosses(m3, test_input, test_labels)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7f08fcaa-000d-422d-80b4-e58a2f489d74\nMLCourse.footer()\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u250012d5824c-0873-49a8-a5d8-f93c73b633ae\n# \u2560\u255094f8e29e-ef91-11eb-1ae9-29bc46fa505a\n# \u255f\u25008217895b-b120-4b08-b18f-d921dfdddf10\n# \u2560\u25509f84bcc5-e5ab-4935-9076-c19e9bd668e8\n# \u2560\u255034e527f2-ef80-4cb6-be3a-bee055eca125\n# \u2560\u2550006fc1eb-50d5-4206-8c87-53e873f158f4\n# \u255f\u2500e4712ebe-f395-418b-abcc-e10ada4b05c2\n# \u2560\u25508c9ae8f7-81b2-4d60-a8eb-ded5364fe0cc\n# \u255f\u2500f4f890b6-0ad4-4155-9321-15d673e15489\n# \u2560\u25509b62c374-c26e-4990-8ffc-790928e62e88\n# \u255f\u25007923a0a8-3033-4dde-91e8-22bf540c9866\n# \u2560\u255057f352dc-55ee-4e14-b68d-698938a97d92\n# \u2560\u2550b0de002f-3f39-4378-8d68-5c4606e488b7\n# \u2560\u2550ce536f60-68b3-4901-bd6a-c96378054b12\n# \u255f\u2500c65b81bd-395f-4461-a73b-3535903cb2d7\n# \u255f\u250051c9ea74-3110-4536-a4af-7cc73b45a4a6\n# \u255f\u2500d541a8cd-5aa4-4c2d-bfdf-5e6297bb65a8\n# \u255f\u25000f544053-1b7a-48d6-b18b-72092b124305\n# \u255f\u2500da6462d8-3343-41d8-82dd-48770176d4ba\n# \u2560\u2550753ec309-1363-485d-a2bd-b9fa100d9058\n# \u2560\u2550618ef3c7-0fda-4970-88e8-1dac195545de\n# \u2560\u25502d25fbb6-dc9b-40ad-bdce-4c952cdad077\n# \u2560\u2550c9f10ace-3299-45fb-b98d-023a35dd405a\n# \u255f\u250099a371b2-5158-4c42-8f50-329352b6c1f2\n# \u2560\u2550f10b7cad-eda3-4ec9-99ee-d43ed013a057\n# \u2560\u255005354df5-a803-422f-87a3-1c56a34e8a48\n# \u2560\u25509e61b4c3-1a9f-41a7-9882-25ed797a7b8d\n# \u2560\u2550c6a59b85-d031-4ad4-9e24-691494d08cde\n# \u2560\u2550e50b8196-e804-473a-b3b5-e22fdb9d2f45\n# \u2560\u2550f413ea94-36ca-4afc-8ca8-9a7e88101980\n# \u255f\u2500dbf7fc72-bfd0-4c57-a1a9-fb5881e16e7e\n# \u255f\u2500ad5b293d-c0f4-4693-84f4-88308639a501\n# \u2560\u2550210b977d-7136-407f-a1c9-eeea869d0312\n# \u2560\u255072969aca-b203-4d83-8923-74e523aa1c01\n# \u255f\u25004cbb3057-01f4-4e80-9029-4e80d6c9e5e6\n# \u2560\u2550c50c529f-d393-4854-b5ed-91e90d557d12\n# \u255f\u250072b50cee-d436-42ce-add9-07b0c012cb31\n# \u2560\u2550bf4110a9-31a4-48a3-bd6d-85c404d0e72d\n# \u2560\u2550534681d5-71d8-402a-b455-f491cfbb353e\n# \u255f\u2500ec1c2ea5-29ce-4371-be49-08798305ff50\n# \u2560\u2550681cb7b9-f041-4aea-907e-4d85135c005a\n# \u255f\u2500f7117513-283f-4e32-a2a1-3594c794c94d\n# \u255f\u25004f89ceab-297f-4c2c-9029-8d2d7fad084f\n# \u255f\u2500fd4165dc-c3e3-4c4c-9605-167b5b4416da\n# \u255f\u25007738c156-8e1b-4723-9818-fba364822171\n# \u2560\u25500fcfd7d2-6ea3-4c75-bad3-7d0fdd6fde11\n# \u255f\u25003336ab15-9e9b-44af-a7d5-1d6472241e62\n# \u255f\u2500285c6bfc-5f29-46e0-a2c1-8abbec74501b\n# \u255f\u2500c98524b5-d6b3-469c-82a1-7d231cc792d6\n# \u255f\u250062ad57e5-1366-4635-859b-ccdab2efd3b8\n# \u2560\u255029e1d9ff-4375-455a-a69b-8dd0c2cac57d\n# \u2560\u25501d1a24c6-c166-49a2-aa21-7acf50b55a66\n# \u2560\u255032bafa9e-a35e-4f54-9857-d269b47f95c3\n# \u255f\u25004e4f4adf-364f-49b9-9391-5050a4c1286a\n# \u2560\u255050c035e6-b892-4157-a52f-824578366977\n# \u2560\u255021b66582-3fda-401c-9421-73ae2f455a75\n# \u255f\u2500ba4b5683-5932-415e-8772-8b3eef5eb63d\n# \u255f\u2500a30578dd-aecb-46eb-b947-f009282cf2fc\n# \u2560\u25508ed39cdc-e99e-48ff-9973-66df41aa0f78\n# \u2560\u2550dd463687-b73d-4e70-b2cf-97a56a0ad409\n# \u2560\u255057dcadc0-2da2-4521-aeaf-6fd01f4bd82b\n# \u2560\u2550935adbcd-48ab-4a6f-907c-b04137ca3abe\n# \u255f\u25008b0451bf-59b0-4e71-be84-549e23b5bfe7\n# \u255f\u250020c5c7bc-664f-4c04-8215-8f3a9a2095c9\n# \u255f\u25007f08fcaa-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": "using UnsafeArrays\n\nexport Maxima,\n       Minima\n\nexport peakprom\n\nstruct Maxima; end\nstruct Minima; end\n\nfor (comps, Extrema) in (((:>, minimum, max), Maxima),\n                       ((:<, maximum, min), Minima))\n\n    comp, argcomp1, argcomp2 = comps\n    \n    @eval begin\n        function peakprom(x::AbstractVector{T}, ::$Extrema, w=1, minprom::T=zero(T)) where T\n            if ($Extrema) === Maxima\n                m = maxima(x, w)\n            else\n                m = minima(x, w)\n            end\n\n            M = lastindex(m)\n            lbegin = firstindex(x)\n            lend = lastindex(x)\n            proms = similar(x,M)\n\n            @inbounds for i in eachindex(m)\n                lb, rb = lbegin, lend\n                lcan, rcan = zero(T), zero(T)\n\n                # Find left bound\n                for ii in (i-1):-1:1\n                    if ($comp)(x[m[ii]], x[m[i]])\n                        lb = m[ii]\n                        break\n                    end\n                end\n\n                # Find left bound\n                for ii in (i+1):M\n                    if ($comp)(x[m[ii]], x[m[i]])\n                        rb = m[ii]\n                        break\n                    end\n                end\n\n                lcan = ($argcomp1)(uview(x, lb:(m[i] - 1))) # Slice from lower bound to the index prior to the current extrema\n                rcan = ($argcomp1)(uview(x, (m[i] + 1):rb)) # Slice corollary upper side\n\n                proms[i] = abs(x[m[i]] - ($argcomp2)(lcan, rcan))\n            end\n\n            if minprom != zero(T)\n                matched = findall(x -> x >= minprom, proms)\n                return (m[matched], proms[matched])\n            else\n                return (m, proms)\n            end\n        end\n\n    end\nend\n\n@doc \"\"\"\n    peakprom(x, ::Maxima[, w=1, minprom=0])\n\nFind all local maxima and maxima prominences in `x` matching the conditions `w` and `minprom`.\n`w` sets the minimum allowed distance between maxima. `minprom` sets the minimum prominence\n(inclusive) of returned maxima.\n\nPeak prominence is calculated as the distance between the current maxima and the highest of\nthe minimums of the lower and upper bounds. Bounds extend from the next index from the\ncurrent maxima to the next maxima higher than the current maxima, or the end of the signal,\nwhich ever comes first.\n\n# Examples\n```jldoctest\njulia> x = rand(1000);\n\njulia> ma, pa = peakprom(x, Maxima());\n\njulia> mi, pi = peakprom(-x, Minima());\n\njulia> @assert (mi == ma) && (pa == pi)\n\n```\n\nSee also: [`maxima`](@ref), [`minima`](@ref)\n\"\"\"\npeakprom(x, ::Maxima)\n\n@doc \"\"\"\n    peakprom(x, ::Minima[, w=1, minprom=0])\n\nFind all local minima and minima prominences in `x` matching the conditions `w` and `minprom`.\n`w` sets the minimum allowed distance between minima. `minprom` sets the minimum prominence\n(inclusive) of returned minima.\n\nPeak prominence is calculated as the distance between the current minima and the lowest of\nthe maximums of the lower and upper bounds. Bounds extend from the next index from the\ncurrent minima to the next minima lower than the current minima, or the end of the signal,\nwhich ever comes first.\n\nSee also: [`maxima`](@ref), [`minima`](@ref)\n\"\"\"\npeakprom(x, ::Minima)\n\n", "meta": {"hexsha": "5feec09918fa9bf9ab230b33e3061de5b6422719", "size": 3217, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/peakprom.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Peaks.jl-18e31ff7-3703-566c-8e60-38913d67486b", "max_stars_repo_head_hexsha": "943d5e4ff84fa32f2fc3d20fdd91a66b7a897f1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/peakprom.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Peaks.jl-18e31ff7-3703-566c-8e60-38913d67486b", "max_issues_repo_head_hexsha": "943d5e4ff84fa32f2fc3d20fdd91a66b7a897f1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/peakprom.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Peaks.jl-18e31ff7-3703-566c-8e60-38913d67486b", "max_forks_repo_head_hexsha": "943d5e4ff84fa32f2fc3d20fdd91a66b7a897f1f", "max_forks_repo_licenses": ["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.2454545455, "max_line_length": 126, "alphanum_fraction": 0.553932235, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7634301643790069}}
{"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] = \u221av[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 \u2661 Julia \") # Use \\heartsuit + TAB to get the \u2661 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 `\u03c3` in Julia.\r\n#' Note that Julia actually allows us to use the symbol \u03c3 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\u03c3(x) = 1/(1 + exp(-x))\r\n\u03c3(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 \u03c3 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=\"\u03c3\")\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=\"\u03c3\", 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=\"\u03c3\", 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\u03c3x = x -> 1/(1+exp(-x))\r\n\u03c3x(1)\r\n#' ### Mutating functions: `...!`\r\n#' To generate our plot of \u03c3 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 = \u03c3.(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 \u222a 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 \u2229 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.(\u03c0*x)\n\n@inline function f(du,u,p,t)\n  du .= zero(eltype(u))\n  u\u2083 = @view u[3:end]\n  u\u2082 = @view u[2:end-1]\n  u\u2081 = @view u[1:end-2]\n  @. du[2:end-1] = p.k*((u\u2083 - 2*u\u2082 + u\u2081)/(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 \u2248 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    \u03b1  = u[1]\n    l\u03b1 = u[2]\n    \u03b2  = u[3]\n    l\u03b2 = u[4]\n    udot .=\n    [2(l\u03b1-(1+cos(\u03b2))l\u03b2)/(3-cos(2\u03b2)),\n    -2sin(\u03b1) - sin(\u03b1+\u03b2),\n    2(-(1+cos(\u03b2))l\u03b1 + (3+2cos(\u03b2))l\u03b2)/(3-cos(2\u03b2)),\n    -sin(\u03b1+\u03b2) - 2sin(\u03b2)*(((l\u03b1-l\u03b2)l\u03b2)/(3-cos(2\u03b2))) + 2sin(2\u03b2)*((l\u03b1^2 - 2(1+cos(\u03b2))l\u03b1*l\u03b2 + (3+2cos(\u03b2))l\u03b2^2)/(3-cos(2\u03b2))^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": "# Modified from https://juliagpu.gitlab.io/KernelAbstractions.jl/examples/matmul/\n\nusing KernelAbstractions, Test, CUDAapi, BenchmarkTools\n\nif CUDAapi.has_cuda_gpu()\n    using CuArrays\n    CuArrays.allowscalar(false)\nend\n\n# Simple kernel for matrix multiplication\n@kernel function matmul_kernel!(@Const(a), @Const(b), c)\n    i, j = @index(Global, NTuple)\n\n    # creating a temporary sum variable for matrix multiplication\n    tmp_sum = zero(eltype(c))\n    for k = 1:size(a)[2]\n        tmp_sum += a[i,k] * b[k, j]\n    end\n    c[i,j] = tmp_sum\nend\n\n@kernel function matmul_kernel_nothing!(@Const(a), @Const(b), c)\n    i, j = @index(Global, NTuple)\n\n    # creating a temporary sum variable for matrix multiplication\n    tmp_sum = zero(eltype(c))\n    for k = 1:size(a)[2]\n        tmp_sum += a[i,k] * b[k, j]\n    end\n    c[i,j] = tmp_sum\n    return nothing\nend\n\n\n\n# Simple kernel for matrix multiplication\n@kernel function matmul_kernel_2!(a, b, c)\n   i, j = @index(Global, NTuple)\n\n    # creating a temporary sum variable for matrix multiplication\n    c[i,j] = zero(eltype(c))\n    for k = 1:size(a)[2]\n        c[i,j] += a[i,k] * b[k, j]\n    end\n\nend\n\n@kernel function matmul_kernel_3!(@Const(a), @Const(b), c)\n    i, j = @index(Global, NTuple)\n    # creating a temporary sum variable for matrix multiplication\n    c[i,j] = zero(eltype(c))\n    for k = 1:size(a)[2]\n        c[i,j] += a[i,k] * b[k, j]\n    end\nend\n\n# Creating a wrapper kernel for launching with error checks\nfunction matmul!(a, b, c)\n    if size(a)[2] != size(b)[1]\n        println(\"Matrix size mismatch!\")\n        return nothing\n    end\n    if isa(a, Array)\n        kernel! = matmul_kernel!(CPU(),4)\n    else\n        kernel! = matmul_kernel!(CUDA(),256)\n    end\n    kernel!(a, b, c, ndrange=size(c))\nend\n\nfunction closure_matmul!(matmul_kernel!; cpu_threads = 4, gpu_blocks = 256)\n    # Creating a wrapper kernel for launching with error checks\n    function matmul!(a, b, c)\n        if size(a)[2] != size(b)[1]\n            println(\"Matrix size mismatch!\")\n            return nothing\n        end\n        if isa(a, Array)\n            kernel! = matmul_kernel!(CPU(), cpu_threads)\n        else\n            kernel! = matmul_kernel!(CUDA(), gpu_blocks)\n        end\n        kernel!(a, b, c, ndrange=size(c))\n    end\n    return matmul!\nend\n\n# Creating a wrapper kernel for launching with error checks\nfunction matmul_2!(a, b, c)\n    if size(a)[2] != size(b)[1]\n        println(\"Matrix size mismatch!\")\n        return nothing\n    end\n    if isa(a, Array)\n        kernel! = matmul_kernel_2!(CPU(),4)\n    else\n        kernel! = matmul_kernel_2!(CUDA(),256)\n    end\n    kernel!(a, b, c, ndrange=size(c))\n\nend\n\nfunction matmul_3!(a, b, c)\n    if size(a)[2] != size(b)[1]\n        println(\"Matrix size mismatch!\")\n        return nothing\n    end\n    if isa(a, Array)\n        kernel! = matmul_kernel_3!(CPU(),4)\n    else\n        kernel! = matmul_kernel_3!(CUDA(),256)\n    end\n    kernel!(a, b, c, ndrange=size(c))\nend\n\nfunction matmul_nothing!(a, b, c)\n    if size(a)[2] != size(b)[1]\n        println(\"Matrix size mismatch!\")\n        return nothing\n    end\n    if isa(a, Array)\n        kernel! = matmul_kernel_nothing!(CPU(), 4)\n    else\n        kernel! = matmul_kernel_nothing!(CUDA(),256)\n    end\n    kernel!(a, b, c, ndrange=size(c))\nend\n\na = rand(256,123)\nb = rand(123, 45)\nc = zeros(256, 45)\n\n# beginning CPU tests, returns event\nev = matmul!(a,b,c)\nwait(ev)\n\n@test isapprox(c, a*b)\n\nev = matmul_nothing!(a,b,c)\nwait(ev)\n\n@test isapprox(c, a*b)\n\n#=\n@benchmark wait(matmul!($a, $b, $c))\n@benchmark wait(matmul_2!($a, $b, $c))\n@benchmark wait(matmul_3!($a, $b, $c))\n=#\n\n# beginning GPU tests\nif has_cuda_gpu()\n    d_a = CuArray(a)\n    d_b = CuArray(b)\n    d_c = CuArray(c)\n\n    ev = matmul!(d_a, d_b, d_c)\n    wait(ev)\n\n    @test isapprox(Array(d_c), d_a*d_b)\n    @benchmark wait(matmul!($d_a, $d_b, $d_c))\n    @benchmark wait(matmul_2!($d_a, $d_b, $d_c))\n    @benchmark wait(matmul_3!($d_a, $d_b, $d_c))\nend\n", "meta": {"hexsha": "206355d5b26a6b8ff37ce6207279b025fec6212b", "size": 3956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_algebra/matrix_multiplication.jl", "max_stars_repo_name": "sandreza/Threadicare", "max_stars_repo_head_hexsha": "2a755e03327ae6cc81c4c680336358415c57ed76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-04T20:49:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-04T20:49:50.000Z", "max_issues_repo_path": "linear_algebra/matrix_multiplication.jl", "max_issues_repo_name": "sandreza/Threadicare.jl", "max_issues_repo_head_hexsha": "2a755e03327ae6cc81c4c680336358415c57ed76", "max_issues_repo_licenses": ["MIT"], "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/matrix_multiplication.jl", "max_forks_repo_name": "sandreza/Threadicare.jl", "max_forks_repo_head_hexsha": "2a755e03327ae6cc81c4c680336358415c57ed76", "max_forks_repo_licenses": ["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.1219512195, "max_line_length": 81, "alphanum_fraction": 0.6061678463, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7634166787066277}}
{"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(\u03c1, \u03b8)\n\nA `Drawable` infinte length line having perpendicular length `\u03c1` from\norigin and angle `\u03b8` between the perpendicular and x-axis\n\n\"\"\"\nstruct LineNormal{T<:Real, U<:Real} <: Line\n    \u03c1::T\n    \u03b8::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, \u03c1)\n\nA `Drawable` circle having center `center` and radius `\u03c1`\n\"\"\"\nstruct CirclePointRadius{T<:Real} <: Circle\n    center::Point\n    \u03c1::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, \u03c1x, \u03c1y)\n\nA `Drawable` ellipse with center `center` and parameters `\u03c1x` and `\u03c1y`\n\n\"\"\"\nstruct Ellipse{T<:Real, U<:Real} <: Drawable\n    center::Point\n    \u03c1x::T\n    \u03c1y::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, \u03b8)\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* `\u03b8::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    \u03b8::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(\u03c4::Tuple{Int, Int}) = Point(\u03c4...)\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*\u03f5 )\n\nCompute the normal rank `r` of the transfer function matrix `G(\u03bb)` of the descriptor system `sys = (A-\u03bbE,B,C,D)`. \n\nThe normal rank of `G(\u03bb)` is evaluated as `r = k - n`, where `k` is the normal rank of\nthe system matrix pencil \n\n              | A-\u03bbE | B | \n      S(\u03bb) := |------|---|\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(\u03bb)` is evaluated by counting the singular values of `S(\u03b3)` greater than `max(max(atol1,atol2), rtol*\u03c3\u2081)`, \nwhere `\u03c3\u2081` is the largest singular value of `S(\u03b3)` and `\u03b3` 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(\u03bb)`, 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*\u03f5`, where `\u03f5` 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*\u03f5) \n\nReturn for the descriptor system `sys = (A-\u03bbE,B,C,D)` the complex vector `val` containing the \nfinite and infinite Smith zeros of the system matrix pencil  \n\n               | A-\u03bbE | B | \n       S(\u03bb) := |------|---| .\n               |  C   | D |  \n\nThe values in `val` are called the _invariant zeros_ of the pencil `S(\u03bb)` and are the _transmission zeros_ of the \ntransfer function matrix of `sys` if `A-\u03bbE` is _regular_ and the descriptor system realization \n`sys = (A-\u03bbE,B,C,D)` is _irreducible_.  \n\nThe computation of the zeros is performed by reducing the pencil `S(\u03bb)` 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*\u03f5`, where `n` is the size of `A`, and `\u03f5` 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*\u03f5) \n\nReturn for the descriptor system `sys = (A-\u03bbE,B,C,D)` the complex vector `val` containing \nthe finite and infinite zeros of the system pole pencil `P(\u03bb) := A-\u03bbE`. \nThe values in `val` are the poles of the transfer function matrix of `sys`, if `A-\u03bbE` is _regular_ and the \ndescriptor system realization `sys = (A-\u03bbE,B,C,D)` is _irreducible_. \nIf the pencil `A-\u03bbE` is singular, `val` also contains `NaN` elements,\nwhose number is the rank deficiency of the pencil  `A-\u03bbE`.\n\nFor `E` nonsingular, `val` contains the generalized eigenvalues of the pair `(A,E)`. \nFor `E` singular, `val` contains the zeros of `P(\u03bb)`, which are computed \nby reducing the pencil `P(\u03bb)` 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-\u03bbE` is implicitly checked. If `check_reg = true`, an error message is issued if the pencil   \n`A-\u03bbE` is singular. If `check_reg = false` and the pencil `A-\u03bbE` 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-\u03bbE`. \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*\u03f5`, where `\u03f5` 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*\u03f5, offset = sqrt(\u03f5)) -> (val, info) \n\nReturn for the descriptor system `sys = (A-\u03bbE,B,C,D)` the complex vector `val` containing \nthe finite and infinite Smith zeros of the system matrix pencil `S(\u03bb)` \n\n              | A-\u03bbE | B | \n       S(\u03bb) = |------|---| \n              |  C   | D |  \n\nand the named tuple `info` containing information on the Kronecker structure of the pencil `S(\u03bb)`. \nThe values in `val` are called the _invariant zeros_ of the pencil `S(\u03bb)` and are the _transmission zeros_ of the \ntransfer function matrix of `sys` if `A-\u03bbE` is _regular_ and the descriptor system realization \n`sys = (A-\u03bbE,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 `\u03b2` 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-\u03b2, smarg+\u03b2]`, while in the discrete-time case, these are the finite zeros having moduli in the interva\n`[smarg-\u03b2, smarg+\u03b2]`. 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 `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` 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(\u03bb)` (also the number of finite zeros of `sys`);\n\n`info.niev` is the number of infinite eigenvalues of the pencil `S(\u03bb)`;\n\n`info.nisev` is the number of  _simple_ infinite eigenvalues of the pencil `S(\u03bb)`; \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-\u03b2` 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-\u03b2, smarg+\u03b2]` 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+\u03b2` for a continuous- or discrete-time system, respectively;\n\n`info.nrank` is the normal rank of the pencil `S(\u03bb)`;\n\n`info.miev` is an integer vector, which contains the multiplicities \n          of the infinite eigenvalues of the pencil `S(\u03bb)`  \n           (also the dimensions of the elementary infinite blocks in the\n          Kronecker form of `S(\u03bb)`);\n\n`info.miz` is an integer vector, which contains the information on the  \n           multiplicities of the infinite zeros of `S(\u03bb)` as follows: \n           `S(\u03bb)` has `info.mip[i]` infinite zeros of multiplicity `i`, and \n             is empty if `S(\u03bb)` has no infinite zeros;\n\n`info.rki` is an integer vector, which contains the _right Kronecker indices_ \n         of the pencil `S(\u03bb)` (empty for a regular pencil);\n\n`info.lki` is an integer vector, which contains the _left Kronecker indices_ \n        of the pencil `S(\u03bb)` (empty for a regular pencil);\n\n`info.regular` is set to `true`,  if the pencil `S(\u03bb)` is regular and set to  \n`false`, if the pencil `S(\u03bb)` is singular;\n\n`info.stable` is set to `true`, if the pencil `S(\u03bb)` 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(\u03bb)` 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(\u03bb)` 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*\u03f5`, where `n` is the size of `A` and `\u03f5` 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*\u03f5, offset = sqrt(\u03f5)) -> (val, info) \n\nReturn for the descriptor system `sys = (A-\u03bbE,B,C,D)` the complex vector `val` containing \nthe finite and infinite zeros of the system pole pencil `P(\u03bb) := A-\u03bbE` and the named tuple `info` containing information on \nthe eigenvalue structure of the pole pencil `P(\u03bb)`. The values in `val` are the _poles_ of the \ntransfer function matrix of `sys`, if `A-\u03bbE` is _regular_ and the \ndescriptor system realization `sys = (A-\u03bbE,B,C,D)` is _irreducible_. \nIf the pencil `A-\u03bbE` is singular, `val` also contains `NaN` elements,\nwhose number is the rank deficiency of the pencil  `A-\u03bbE`.\n\nFor stability analysis purposes, a stability margin `smarg` can be specified for the finite eigenvalues,\nin conjunction with a stability domain boundary offset `\u03b2` 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-\u03b2, smarg+\u03b2]`, while in the discrete-time case, these are the finite eigenvalues having moduli in the interval\n`[smarg-\u03b2, smarg+\u03b2]`. 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 `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` 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-\u03bbE` (also the number of finite poles of `sys`);\n\n`info.niev` is the number of infinite eigenvalues of the pencil `A-\u03bbE`;\n\n`info.nisev` is the number of _simple_ infinite eigenvalues of the pencil `A-\u03bbE` (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-\u03b2` 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-\u03b2, smarg+\u03b2]` 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+\u03b2` 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-\u03bbE` is singular);  \n\n`info.nrank` is the normal rank of the pencil `A-\u03bbE`;\n\n`info.miev` is an integer vector, which contains the multiplicities \n          of the infinite eigenvalues of the pencil `A-\u03bbE` 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-\u03bbE` 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-\u03bbE` (empty for a regular pencil);\n\n`info.lki` is an integer vector, which contains the _left Kronecker indices_\n           of the pencil `A-\u03bbE` (empty for a regular pencil);\n\n`info.regular` is set to `true`,  if the pencil `A-\u03bbE` is regular and set to  \n`false`, if the pencil `A-\u03bbE` is singular;\n\n`info.proper` is set to `true`, if the pencil `A-\u03bbE` 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-\u03bbE` is singular or has higher order infinite eigenvalues;\n\n`info.stable` is set to `true`, if the pencil `A-\u03bbE` 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(\u03bb)` are the same, \nbut the multiplicities of infinite eigenvalues of `P(\u03bb)` are in excess with one to the multiplicities of infinite poles.\n\nFor the reduction of the pencil `P(\u03bb)` 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*\u03f5`, where `n` is the size of `P(\u03bb)`, and `\u03f5` 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*\u03f5)\n\nReturn `true` if the descriptor system `sys = (A-\u03bbE,B,C,D)` has a regular pole pencil `A-\u03bbE` and `false` otherwise.  \n\nTo test whether the pencil `A-\u03bbE` is regular (i.e., `det(A-\u03bbE) \u0338\u2261 0`),  \nthe underlying computational procedure reduces the pencil `A-\u03bbE` to an appropriate Kronecker-like form, \nwhich provides information on the rank of `A-\u03bbE`. \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*\u03f5`, where `n` is the size of  `A`, and `\u03f5` 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*\u03f5, fast = true)\n\nReturn `true` if the transfer function matrix `G(\u03bb)` of the descriptor system `sys = (A-\u03bbE,B,C,D)` is proper\nand `false` otherwise.  \n\nFor a descriptor system realization `sys = (A-\u03bbE,B,C,D)` without uncontrollable and unobservable infinite eigenvalues,\nit is checked that the pencil `A-\u03bbE` 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*\u03f5`, where `n` is the order of `A` and `\u03f5` 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*\u03f5, offset = sqrt(\u03f5))\n\nReturn `true` if the descriptor system `sys = (A-\u03bbE,B,C,D)` has only stable poles and `false` otherwise.  \n\nIt is checked that the pole pencil `P(\u03bb) := A-\u03bbE` 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-\u03b2` for a continuous-time system or \nhave moduli less than `smarg-\u03b2` for a discrete-time system, where `smarg` is the stability margin and \n`\u03b2` 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  `\u03b2` to be used to numerically assess the stability of eigenvalues \ncan be specified via the keyword parameter `offset = \u03b2`. \nThe default value used for `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` is the working machine precision. \n\nFor `E` singular, the computation of the poles is performed by reducing the pencil `P(\u03bb)` 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*\u03f5`, where `n` is the order of `A` and `\u03f5` 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    \u03b2 = 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-\u03b2) : all(real.(poles) .< smarg-\u03b2)\nend\n\"\"\"\n    ghanorm(sys, fast = true, atol = 0, atol1 = atol, atol2 = atol, rtol = n*\u03f5) -> (hanorm, hs)\n\nCompute for a proper and stable descriptor system `sys = (A-\u03bbE,B,C,D)` with the transfer function\nmatrix `G(\u03bb)`, 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*\u03f5`, where `\u03f5` 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(\u03f5), atol = 0, atol1 = atol, atol2 = atol, atolinf = atol, rtol = n*\u03f5) \n\nCompute for a descriptor system `sys = (A-\u03bbE,B,C,D)` the `H2` norm of its transfer function  matrix `G(\u03bb)`.\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-\u03bbE` must have real parts less \nthan `-\u03b2` for a continuous-time system or \nhave moduli less than `1-\u03b2` for a discrete-time system, where `\u03b2` is the stability domain boundary offset.\nThe offset  `\u03b2` to be used can be specified via the keyword parameter `offset = \u03b2`. \nThe default value used for `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` 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(\u03bb)` at `\u03bb = \u221e`. \nThe used default value is `atolinf = 0`. \nThe default relative tolerance is `n*\u03f5`, where `\u03f5` 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(\u03f5), atol = 0, atol1 = atol, atol2 = atol, atol3 = atol, atolinf = atol, rtol = n*\u03f5) \n\nCompute for a descriptor system `sys = (A-\u03bbE,B,C,D)` the `L2` norm of its transfer function  matrix `G(\u03bb)`.\nThe `L2` norm is infinite if the _pole pencil_ `A-\u03bbE` 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-\u03bbE` \nmust not have real parts in the interval `[-\u03b2,\u03b2]` for a continuous-time system or \nmust not have moduli in the interval `[1-\u03b2,1+\u03b2]` for a discrete-time system, where `\u03b2` is the stability domain boundary offset.  \nThe offset  `\u03b2` to be used can be specified via the keyword parameter `offset = \u03b2`. \nThe default value used for `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` is the working machine precision. \n\nIf `h2norm = true`, the `H2` norm is computed. \nThe `H2` norm is infinite if the _pole pencil_ `A-\u03bbE` 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-\u03bbE` must have real parts less than `-\u03b2` for a continuous-time system or \nhave moduli less than `1-\u03b2` 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(\u03bb)` at  `\u03bb = \u221e`. \nThe used default value is `atolinf = 0`. \nThe default relative tolerance is `n*\u03f5`, where `\u03f5` 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(\u03f5), atol = 0, atol1 = atol, atol2 = atol, rtol = n*\u03f5) -> (hinfnorm, fpeak)\n\nCompute for a descriptor system `sys = (A-\u03bbE,B,C,D)` with the transfer function  matrix `G(\u03bb)` \nthe `H\u221e` norm `hinfnorm` (i.e.,  the peak gain of `G(\u03bb)`) and \nthe corresponding peak frequency `fpeak`, where the peak gain is achieved. \nThe `H\u221e` norm is infinite if the _pole pencil_ `A-\u03bbE` has unstable zeros (i.e., `sys` has unstable poles). \nTo check the stability, the eigenvalues of the pencil `A-\u03bbE` must have real parts less than `-\u03b2` for a continuous-time system or \nhave moduli less than `1-\u03b2` for a discrete-time system, where `\u03b2` is the stability domain boundary offset.\nThe offset  `\u03b2` to be used can be specified via the keyword parameter `offset = \u03b2`. \nThe default value used for `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` 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*\u03f5`, where `\u03f5` 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(\u03f5), atol = 0, atol1 = atol, atol2 = atol, rtol = n*\u03f5) -> (linfnorm, fpeak)\n\nCompute for a descriptor system `sys = (A-\u03bbE,B,C,D)` with the transfer function  matrix `G(\u03bb)` \nthe `L\u221e` norm `linfnorm` (i.e.,  the peak gain of `G(\u03bb)`) and \nthe corresponding peak frequency `fpeak`, where the peak gain is achieved. \nThe `L\u221e` norm is infinite if the _pole pencil_ `A-\u03bbE` 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-\u03bbE` \nmust not have real parts in the interval `[-\u03b2,\u03b2]` for a continuous-time system or \nmust not have moduli within the interval `[1-\u03b2,1+\u03b2]` for a discrete-time system, where `\u03b2` is the stability domain boundary offset.  \nThe offset  `\u03b2` to be used can be specified via the keyword parameter `offset = \u03b2`. \nThe default value used for `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` 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\u221e` norm is computed. In this case, the stability of the zeros of `A-\u03bbE` is additionally checked and \nthe `H\u221e` norm is infinite for an unstable system.\nTo check the stability, the eigenvalues of the pencil `A-\u03bbE` must have real parts less than `-\u03b2` for a continuous-time system or \nhave moduli less than `1-\u03b2` 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*\u03f5`, where `\u03f5` 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    \u03b2 = 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-\u03b2) && (return Inf, NaN)\n        for i = 1:length(ft)\n            abs(ft[i]) >= 1-\u03b2 && abs(ft[i]) <= 1+\u03b2 && (return Inf, complx ? imag(log(complex(ft[i]))/Ts) : abs(log(complex(ft[i]))/Ts))\n        end\n    else\n        hinfnorm && any(real.(ft) .> -\u03b2) && (return Inf, NaN)\n        for i = 1:length(ft)\n            real(ft[i]) >= -\u03b2 && real(ft[i]) <= \u03b2 && (return Inf, complx ? imag(ft[i]) : abs(imag(ft[i])))\n        end\n    end\n    \n    # compute L\u221e-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\u221e norm computation\n   # It is assumed that A-\u03bbE 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\u221e norm computation\n   # It is assumed that A-\u03bbE 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 = \u03c9, rtolinf = 0.00001, fast = true, offset = sqrt(\u03f5), \n           atol = 0, atol1 = atol, atol2 = atol, rtol = n*\u03f5) -> (nugapdist, fpeak)\n\nCompute the \u03bd-gap distance `nugapdist` between two descriptor systems `sys1 = (A1-\u03bbE1,B1,C1,D1)` and \n`sys2 = (A2-\u03bbE2,B2,C2,D2)` and the corresponding frequency `fpeak` (in rad/TimeUnit), where the \u03bd-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 = \u03c9`, where `\u03c9` is a given vector of real frequency values, the resulting `nugapdist` is a vector \nof pointwise \u03bd-gap distances of the dimension of `\u03c9`, 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,  `\u03b2`, 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 = \u03b2`.\nAccordingly, for a continuous-time system, these are the finite zeros having \nreal parts within the interval `[-\u03b2,\u03b2]`, while for a discrete-time system, \nthese are the finite zeros having moduli within the interval `[1-\u03b2,1+\u03b2]`. \nThe default value used for `\u03b2` is `sqrt(\u03f5)`, where `\u03f5` 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*\u03f5`, where `\u03f5` 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 \u03bd-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 \u03bd-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\u221e loop-shaping and the \u03bd-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 \u03bd-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": "using MathML, EzXML, Symbolics, SpecialFunctions, IfElse, AbstractTrees, Test\n\n# these tests mimic the README examples \nfn = \"data/math.xml\"\ndoc = readxml(fn)\nnum = MathML.parse_node(doc.root)\n@variables compartment k1 S1\ntrue_num = prod([compartment, k1, S1])\n@test isequal(num, [true_num])\n\nfn = \"data/eq.xml\"\ndoc = readxml(fn)\neqs = MathML.parse_node(doc.root)\n@variables T I Par_94 Par_90\ntrue_eqs = [\n    T ~ Par_94,\n    I ~ Par_90,\n]\n@test isequal(eqs, true_eqs)\n\n@variables w x y z a b t\n\nstr = \"<apply><compose/><ci>x</ci><ci>y</ci><ci>z</ci></apply>\"\n@test isequal(MathML.parse_str(str), x \u2218 y \u2218 z)\n\nstr = \"\"\"<cn type=\"rational\">22<sep/>7</cn>\"\"\"\n@test isequal(MathML.parse_str(str), 22 // 7)\n\nstr = \"\"\"<cn type=\"e-notation\">5<sep/>2</cn>\"\"\"\n@test isequal(MathML.parse_str(str), 500)\n\nstr = \"\"\"<cn type=\"complex-polar\"> 2 <sep/> 3.1415 </cn>\"\"\"\n@test isapprox(MathML.parse_str(str), Complex(-2, 0), atol=1e-3)\n\nstr = \"\"\"<cn type=\"complex-cartesian\"> 12.3 <sep/> 5 </cn>\"\"\"\n@test isequal(MathML.parse_str(str), Complex(12.3, 5))\n\n# heaviside and nesting test\nstr = \"\"\"\n<piecewise>\n  <piece>\n    <apply><minus/><ci>x</ci></apply>\n    <apply><lt/><ci>x</ci><cn>0</cn></apply>\n  </piece>\n  <piece>\n    <cn>0</cn>\n    <apply><eq/><ci>x</ci><cn>0</cn></apply>\n  </piece>\n  <piece>\n    <ci>x</ci>\n    <apply><gt/><ci>x</ci><cn>0</cn></apply>\n  </piece>\n</piecewise>\n\"\"\"\n# MathML.parse_str(str) # no <otherwise>\n\nstr = \"\"\"\n<piecewise>\n<piece>\n  <apply>\n      <divide/>\n      <apply>\n        <times/>\n        <ci>x</ci>\n        <apply>\n            <plus/>\n            <ci>y</ci>\n            <apply>\n              <times/>\n              <ci>z</ci>\n              <ci>a</ci>\n            </apply>\n        </apply>\n      </apply>\n      <apply>\n        <minus/>\n        <cn>1</cn>\n        <apply>\n            <times/>\n            <ci>z</ci>\n            <ci>b</ci>\n        </apply>\n      </apply>\n  </apply>\n  <apply>\n      <leq/>\n      <ci>t</ci>\n      <cn>1</cn>\n  </apply>\n</piece>\n<otherwise>\n  <apply>\n      <times/>\n      <ci>x</ci>\n      <ci>y</ci>\n  </apply>\n</otherwise>\n</piecewise>\n\"\"\"\n@test isequal(MathML.parse_str(str), \n  IfElse.ifelse(\n    IfElse.ifelse(1. - t >= 0, 1, 0) > 0.5,\n     x * (y + a * z) * ((1.0 - (b * z))^-1),\n      x * y))\n\n# factorial\nstr = \"<apply><factorial/><ci>x</ci></apply>\"\n@test isequal(MathML.parse_str(str), factorial(x))\n\nstr = \"<apply><factorial/><cn>5</cn></apply>\"\n@test MathML.parse_str(str) == 120\n\n# root\nstr = \"\"\"\n<apply><root/>\n  <degree><ci type=\"integer\">y</ci></degree>\n  <ci>x</ci>\n</apply>\n\"\"\"\n@test isequal(MathML.parse_str(str), x^y)\n\nstr = \"<apply><root/><ci>x</ci></apply>\"\n@test isequal(MathML.parse_str(str), sqrt(x))\n\n#  \nstr = \"\"\"\n<apply><divide/>\n<ci>x</ci>\n<ci>y</ci>\n</apply>\n\"\"\"\n@test isequal(MathML.parse_str(str), x / y)\n\n#  \nstr = \"<apply><max/><cn>2</cn><cn>3</cn><cn>5</cn></apply>\"\n@test isequal(MathML.parse_str(str), 5)\n\n#  \nstr = \"<apply><min/><ci>x</ci><ci>y</ci></apply>\"\n@test isequal(MathML.parse_str(str), min(x, y))\n\n#  \nstr = \"<apply><minus/><cn>3</cn></apply>\"\n@test isequal(MathML.parse_str(str), -3)\n\n#  \nstr = \"<apply><minus/><ci>x</ci><ci>y</ci></apply>\"\n@test isequal(MathML.parse_str(str), x - y)\n\n#  \nstr = \"<apply><plus/><ci>x</ci><ci>y</ci><ci>z</ci></apply>\"\n@test isequal(MathML.parse_str(str), x + y + z)\n\n#  \nstr = \"<apply><rem/><ci>x</ci><ci>y</ci></apply>\"\n@test isequal(MathML.parse_str(str), rem(x, y))\n\n#  \n# str = \"<apply><gcd/><ci>a</ci><ci>b</ci><ci>c</ci></apply>\" # gcd is a ways off, gro\u0308bner bases\n# MathML.parse_str(str)\n# @test isequal(MathML.parse_str(str), )\n\n#  \nstr = \"<apply><abs/><ci>x</ci></apply>\"\n@test isequal(MathML.parse_str(str), abs(x))\n\n#  \n# str = \"\"\"\n# <apply><conjugate/>\n#   <apply><plus/>\n#     <ci>x</ci>\n#     <apply><times/><cn>&#x2148;<!--DOUBLE-STRUCK ITALIC SMALL I--></cn><ci>y</ci></apply>\n#   </apply>\n# </apply>\n# \"\"\"\n# MathML.parse_str(str)\n# @test isequal(MathML.parse_str(str), )\n\n#  lcm\n# str = \"<apply><lcm/><ci>a</ci><ci>b</ci><ci>c</ci></apply>\"\n# MathML.parse_str(str)\n# @test isequal(MathML.parse_str(str), )\n\n# floor and ceil - RoundingMode\n# str = \"<apply><floor/><ci>a</ci></apply>\"\n# MathML.parse_str(str)\n# @test isequal(MathML.parse_str(str), )\n\n#  do we actually want it to evaluate, or maybe just return expr\nstr = \"<apply><gt/><cn>3</cn><cn>2</cn></apply>\"\n@test isequal(MathML.parse_str(str), true)\n\n#  \nstr = \"<apply><lt/><cn>2</cn><cn>3</cn><cn>4</cn></apply>\"\n@test isequal(MathML.parse_str(str), true)\n\n#  \nstr = \"<apply><exp/><ci>x</ci></apply>\"\n@test isequal(MathML.parse_str(str), exp(x))\n\n#  \nstr = \"<apply><ln/><ci>x</ci></apply>\"\n@test isequal(MathML.parse_str(str), log(x))\n\n#  dopee\nstr = \"\"\"\n<vector>\n  <apply><plus/><ci>x</ci><ci>y</ci></apply>\n  <cn>3</cn>\n  <cn>7</cn>\n</vector>\n\"\"\"\n@test isequal(MathML.parse_str(str), [x + y, 3, 7])\n\nstr = \"<bvar><ci>x</ci></bvar>\"\n@test isequal(MathML.parse_str(str), (Num(Variable(:x)), 1))\n\nstr = \"<bvar><ci>x</ci><degree><cn>2</cn></degree></bvar>\"\n@test isequal(MathML.parse_str(str), (Num(Variable(:x)), 2))\n\nstr = \"\"\"\n<apply><diff/>\n  <bvar><ci>x</ci></bvar>\n  <apply><sin/><ci>x</ci></apply>\n</apply>\n\"\"\"\n@test isequal(expand_derivatives(MathML.parse_str(str)), cos(Num(Variable(:x))))\n\nstr = \"\"\"\n<apply><diff/>\n  <bvar><ci>x</ci><degree><cn>2</cn></degree></bvar>\n  <apply><power/><ci>x</ci><cn>4</cn></apply>\n</apply>\n\"\"\"\n@test isequal(expand_derivatives(MathML.parse_str(str)), 12 * Num(Variable(:x))^2)\n\n# macro test\nml = MathML\"\"\"\n<apply><diff/>\n  <bvar><ci>x</ci><degree><cn>2</cn></degree></bvar>\n  <apply><power/><ci>x</ci><cn>4</cn></apply>\n</apply>\n\"\"\"\n@test isequal(expand_derivatives(ml), 12 * Num(Variable(:x))^2)\n\nstr = \"\"\"\n  <lambda>\n    <bvar>\n      <ci> x </ci>\n    </bvar>\n    <bvar>\n      <ci> y </ci>\n    </bvar>\n    <apply>\n      <power/>\n      <ci> x </ci>\n      <ci> y </ci>\n    </apply>\n  </lambda>\n\"\"\"\nf = parse_str(str)\nxml = parsexml(str).root\ng = parse_lambda(xml)\n@test g(3,5) == f(3,5) == [243]\n@test isequal(f(x, y), [x^y])\n\n# parse_apply with <ci> as firstelement problem\n@test_throws KeyError parse_file(\"data/err.xml\")\n", "meta": {"hexsha": "5a021636e153bd2086f8af2e778fca65720e81f1", "size": 6068, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/parse.jl", "max_stars_repo_name": "dannys4/MathML.jl", "max_stars_repo_head_hexsha": "ef5e4952262f354d15517b07b88462405012c279", "max_stars_repo_licenses": ["MIT"], "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/parse.jl", "max_issues_repo_name": "dannys4/MathML.jl", "max_issues_repo_head_hexsha": "ef5e4952262f354d15517b07b88462405012c279", "max_issues_repo_licenses": ["MIT"], "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/parse.jl", "max_forks_repo_name": "dannys4/MathML.jl", "max_forks_repo_head_hexsha": "ef5e4952262f354d15517b07b88462405012c279", "max_forks_repo_licenses": ["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.5576208178, "max_line_length": 97, "alphanum_fraction": 0.5647659855, "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7633884638529159}}
{"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": "@testset \"Mesh\" begin\n\t@testset \"display\" begin include(\"display.jl\") end\n\t@testset \"Constraints\" begin include(\"testConstraints.jl\") end\n\t@testset \"Regular vs. Tensor\" begin include(\"regularVStensor.jl\") end\n\t@testset \"testDiffOps.jl\" begin include(\"testDiffOps.jl\") end\n\t@testset \"testInterpolationMatrix.jl\" begin include(\"testInterpolationMatrix.jl\") end\n\t@testset \"testAvgOps.jl\" begin include(\"testAvgOps.jl\") end\n\t@testset \"testBoundaryNodes.jl\" begin include(\"testBoundaryNodes.jl\") end\n\t@testset \"testPersistency.jl\" begin include(\"testPersistency.jl\") end\n\t@testset \"testIntPolyChain.jl\" begin include(\"testIntPolyChain.jl\") end\n\t@testset \"testMassMatrices.jl\" begin include(\"testMassMatrices.jl\") end\n\t@testset \"testForward.jl\" begin include(\"testForward.jl\") end\nend\n", "meta": {"hexsha": "0d3a269ccb7c9e63fb8490b10ffb28fa28b7ccde", "size": 779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Mesh/runtests.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": "test/Mesh/runtests.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": "test/Mesh/runtests.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": 55.6428571429, "max_line_length": 86, "alphanum_fraction": 0.7792041078, "num_tokens": 233, "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": "## 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  \u2026  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) \u00f7 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\u03c3\n\n# Cost functions\n\nmse(y\u0302, y) = sum((y\u0302 .- y).^2)/length(y)\n\nfunction crossentropy(y\u0302::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\n  @fix -sum(y .* log.(y\u0302) .* weight) / size(y, 2)\nend\n\n@deprecate logloss(x, y) crossentropy(x, y)\n\nfunction logitcrossentropy(logy\u0302::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\n  return -sum(y .* logsoftmax(logy\u0302) .* weight) / size(y, 2)\nend\n\n\"\"\"\n    binarycrossentropy(y\u0302, y)\n\nReturn `-y*log(y\u0302) - (1-y)*log(1-y\u0302)`.\n\n    julia> binarycrossentropy.(\u03c3.([-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\u0302, y) = -y*log(y\u0302) - (1 - y)*log(1 - y\u0302)\n\n\"\"\"\n    logitbinarycrossentropy(log\u0177, y)\n\n`logitbinarycrossentropy(log\u0177, y)` is mathematically equivalent to `binarycrossentropy(\u03c3(log\u0177), 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\u0177, y) = (1 - y)*log\u0177 - log\u03c3(logy\u0302)\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  \u03bc\u2032 = mean(x, 1)\n  \u03c3\u2032 = std(x, 1, mean = \u03bc\u2032)\n  return (x .- \u03bc\u2032) ./ \u03c3\u2032\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": "using Nemo\nusing EllipticCurves\nusing ClassPolynomials\n\nusing Test\n\n######################################################################\n# Testing tools.jl\n######################################################################\n\n#This file should be ok if the tests below pass\n\n\n######################################################################\n# Testing weierstrass.jl\n######################################################################\n\nprint(\"Testing weierstrass.jl... \")\n\nE1 = Weierstrass(QQ(0), QQ(0), QQ(0), QQ(4), QQ(5))\nE2 = ShortWeierstrass(QQ(0), QQ(0), QQ(0), QQ(4), QQ(5))\nE3 = SeparatedWeierstrass(QQ(0), QQ(0), QQ(0), QQ(4), QQ(5))\nE4 = EllipticCurve(QQ(4), QQ(5))\n\n@test base_ring(E1) == QQ\n@test base_ring(E2) == QQ\n@test base_ring(E3) == QQ\n@test E1 == E2 == E3 == E4\n\nE = EllipticCurve(QQ(0), QQ(17))\n@test a_invariants(E) == (QQ(0), QQ(0), QQ(0), QQ(0), QQ(17))\n@test b_invariants(E) == (QQ(0), QQ(0), QQ(68), QQ(0))\n@test c_invariants(E) == (QQ(0), QQ(-14688))\n@test discriminant(E) == QQ(-124848)\n@test j_invariant(E) == QQ(0)\n@test isvalid(E)\n\neq = equation(E)\nY = gen(parent(eq))\nX = gen(base_ring(eq))\n@test eq == Y^2 - X^3 - 17\n\npreq = projective_equation(E)\nX, Y, Z = gens(parent(preq))\n@test preq == Z * Y^2 - X^3 - 17 * Z^3\n\nf3 = divisionpolynomial(E, 3)\nf9 = divisionpolynomial(E, 9)\n@test f9 % f3 == 0\n\nprint(\"done\\n\")\n\n\n######################################################################\n# Testing points.jl\n######################################################################\n\nprint(\"Testing points.jl... \")\n\nE = EllipticCurve(QQ(0), QQ(17))\nP1 = Point(QQ(-2), QQ(3), QQ(1), E)\nP2 = Point(QQ(-4), QQ(6), QQ(2), E)\nP3 = Point(QQ(2), QQ(5), QQ(1), E)\n\n@test coordinates(P1) == (-2, 3, 1)\n@test base_curve(P1) == E\n@test base_ring(P1) == QQ\n@test isvalid(P1)\n@test isvalid(P3)\n\n@test samefields(normalized(P2), P1)\n@test P1 == P2\n\nprint(\"done\\n\")\n\n\n######################################################################\n# Testing weierstrasspoints.jl\n######################################################################\n\nprint(\"Testing weierstrasspoints.jl... \")\n\n#Example is taken from Silverman 1 p.59.\n\nE = EllipticCurve(QQ(0), QQ(17))\nP1 = Point(QQ(-2), QQ(3), QQ(1), E)\nP2 = Point(QQ(-1), QQ(4), QQ(1), E)\nP3 = Point(QQ(2), QQ(5), QQ(1), E)\nPinf = zero(E)\n\n@test P1 + P1 == 2 * P1 == Point(QQ(8), QQ(-23), QQ(1), E)\n@test Pinf + Pinf == 2 * Pinf == Pinf\n@test P1 + Pinf == Pinf + P1 == P1\n@test P2 + P2 == 2 * P2 == Point(QQ(137//64), QQ(-2651//512), QQ(1), E)\n@test P2 + P3 == Point(QQ(-8//9), QQ(-109//27), QQ(1), E)\n@test -P3 == Point(QQ(2), QQ(-5), QQ(1), E)\n@test P3 - P3 == 0 * P3 == Pinf\n@test P1 - P3 == 1 * P1 + (-1) * P3 == Point(QQ(4), QQ(9), QQ(1), E)\n\n@test projective_add(P2, P3) == P2 + P3\n@test projective_scalar_mul(P2, 7) == 7 * P2\n\nE = EllipticCurve(QQ(2), QQ(1))\nP = Point(QQ(1), QQ(2), QQ(1), E)\n@assert projective_add(P, P) == 2 * P\n@assert projective_scalar_mul(P, 17) == 17 * P\nprint(\"done\\n\")\n\n\n######################################################################\n# Testing montgomery.jl\n######################################################################\n\n#Really trivial code, no need for testing\n\n######################################################################\n# Testing montgomerypoints.jl and curves\n######################################################################\n\nprint(\"Testing montgomerypoints.jl... \")\n\nE = Montgomery(QQ(7), QQ(1))\n@test base_ring(E) == QQ\n@test j_invariant(E) == 24918016//45\n@test isvalid(E)\n\nP1 = Point(QQ(1), QQ(3), QQ(1), E)\nP0 = Point(QQ(0), QQ(0), QQ(1), E)\n@test isvalid(P1) & isvalid(P0)\n\nxP1 = XZPoint(P1)\nxP0 = XZPoint(P0)\nxinf = XZzero(E)\n\n@test isfixedtorsion(xP0)\n@test !isfixedtorsion(xP1)\n@test fixedtorsion(E) == xP0\n\n@test xdouble(xP0) == xinf\n@test xdouble(xP1) == xP0\n@test xdouble(xinf) == xinf\n\n@test xadd(xP1, xP0, xP1) == xP1\n\n#Scalar multiplications\n\n@test 0 * xP1 == xinf\n@test 1 * xP1 == xP1\n@test 2 * xP1 == xP0\n@test 1 * xP0 == xP0\n@test 2 * xP0 == xinf\n@test 45 * xinf == xinf\n@test 4 * xP1 == xinf\n\n@test 8 * xP1 == xinf\n\nprint(\"done\\n\")\n\n######################################################################\n# Testing edwards.jl\n######################################################################\n\n#Do we really want to keep this code ?\n\n######################################################################\n# Testing edwardspoints.jl\n######################################################################\n\n#Do we really want to keep this code ?\n\n######################################################################\n# Testing pairings.jl\n######################################################################\n\n#Do we really want to keep this code ?\n\n######################################################################\n# Testing isogenies.jl\n######################################################################\n\nprint(\"Testing isogenies.jl... \")\n\nF, x = FiniteField(101, 1, \"x\")\nE = EllipticCurve(F(1), F(3))\nP = Point(F(3), F(29), F(1), E)\nQ = Point(F(4), F(24), F(1), E) #another point\n\n#P is a point of three-torsion\n@test isvalid(P)\n@test 3 * P == zero(E)\n@test 3 * Q != zero(E)\n\nf3 = divisionpolynomial(E, 3)\n@test f3(P.X) == 0\n\nphi = Isogeny(E, P, 3)\nEprime = image(phi)\n@test domain(phi) == E\n@test Eprime == EllipticCurve(F(24), F(24)) #given by Sage\n@test phi(P) == zero(Eprime)\n@test isvalid(phi(Q))\n@test phi(Q) == Point(F(91), F(20), F(1), Eprime)\n\nK = subgroup(P, 3)\n\n@test kernel(phi) == K\n@test Isogeny(E, K) == phi\n@test Isogeny(E, 3, Eprime) == phi\n\n@test isvalid(phi)\npsi = dual(phi)\n\n\n@test compose(phi, psi) == multiplication_isogeny(E, 3)\n@test multiplication_isogeny(E, 3)(P) == 3 * P\n\nid = Isogeny(E, 1, E)\n@test kernel(id) == 1\n@test id(P) == P\n\n@test isvalid(psi)\n@test isvalid(id)\n\nphix, phiy = rational_fractions(phi)\n@test Isogeny(E, Eprime, phix, phiy) == phi\n\njprime = j_invariant(Eprime)\n@test Isogeny(E, 3, jprime) == phi\n\n#With modular equations\n\nell = 5\nFX, X = PolynomialRing(F, \"X\")\nbb, j1 = any_root(ClassicalModularPolynomial(ell, j_invariant(E), X))\n@test bb\n@test isvalid(Isogeny(E, ell, j1))\n\n@test isvalid(Isogeny(E, ell, j1; USE_ATKIN = true))\nprint(\"done\\n\")\n\n######################################################################\n# Testing finfields.jl\n######################################################################\n\nprint(\"Testing finfields.jl... \")\n\n#Conversions\n\nF, u = FiniteField(233, 1, \"u\")\nG, z = FiniteField(233, 3, \"z\")\n@test convert(G(1), F) == F(1)\n@test convert(F(1), G) == G(1)\n\n#Roots of polynomials\n\nR, X = PolynomialRing(F, \"X\")\n(bool, root) = any_root(X^2 - 1)\n@test bool\n@test root^2 == 1\n\n#Cardinality\n\nE = EllipticCurve(F(3), F(4))\n#@test cardinality(E) == 260: no point counting algorithm yet\n#@test frobeniustrace(E) == -26\nE2 = Montgomery(F(3), F(1))\n#@test cardinality(E2) == 240\n\n#Random points\n\nP = rand(E)\n@test isvalid(P)\n@test 260 * P == zero(E)\nP2 = randXZ(E2)\n@test isvalid(P2)\n@test 240 * P2 == XZzero(E2)\n\n#Torsion points\n\nQ = torsionpoint(E, 13, 260)\n@test Q !== zero(E)\n@test 13 * Q == zero(E)\nQ2 = torsionXZ(E2, 5, 240)\n@test Q2 !== XZzero(E2)\n@test 5 * Q2 == XZzero(E2)\n\n#Base extensions\n\nP = rand(base_extend(E, G))\n@test isvalid(P)\n\n@test card_over_extension(210, 233, 3) == 12652290\n\n#Montgomery models\nE = EllipticCurve(F(204), F(56))\n(bool, Eprime) = has_montgomery(E)\n@test bool\n@test j_invariant(E) == j_invariant(Eprime)\n\nprint(\"done\\n\")\n\nprint(\"\\n\")\n\n\n\n", "meta": {"hexsha": "518ff8bcf2a5db2270d0f5fd64ad572c0fbab128", "size": 7416, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 24.2352941176, "max_line_length": 71, "alphanum_fraction": 0.4936623517, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7633451981324022}}
{"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": "module TestStencil\nusing AnisotropicDiffusion\nusing AnisotropicDiffusion: laplace, dot_grad\nusing Test\n\n@testset \"laplace\" begin\n    x = randn(3,3,3)\n    index = CartesianIndex((2,2,2))\n    @test laplace(x, index) \u2248 x[1,2,2] + x[2,1,2] + x[2,2,1] + x[3,2,2] + x[2,3,2] + x[2,2,3] - 6x[2,2,2]\n    \nend\n\n@testset \"dot_grad\" begin\n    x = randn(3,3,3)\n    y = randn(3,3,3)\n    index = CartesianIndex((2,2,2))\n    @test dot_grad(x,y,index) \u2248 \n        (x[3,2,2] - x[2,2,2])*(y[3,2,2] - y[2,2,2]) +\n        (x[2,3,2] - x[2,2,2])*(y[2,3,2] - y[2,2,2]) +\n        (x[2,2,3] - x[2,2,2])*(y[2,2,3] - y[2,2,2])\nend\n\nend#module\n", "meta": {"hexsha": "e958af791c26f9111887c954db911ebe4ecee49f", "size": 615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_stencil.jl", "max_stars_repo_name": "jw3126/AnisotropicDiffusion.jl", "max_stars_repo_head_hexsha": "f50a1ea45a4d2d33dca5b90bd999fb1d597f9dfb", "max_stars_repo_licenses": ["MIT"], "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_stencil.jl", "max_issues_repo_name": "jw3126/AnisotropicDiffusion.jl", "max_issues_repo_head_hexsha": "f50a1ea45a4d2d33dca5b90bd999fb1d597f9dfb", "max_issues_repo_licenses": ["MIT"], "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_stencil.jl", "max_forks_repo_name": "jw3126/AnisotropicDiffusion.jl", "max_forks_repo_head_hexsha": "f50a1ea45a4d2d33dca5b90bd999fb1d597f9dfb", "max_forks_repo_licenses": ["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.625, "max_line_length": 105, "alphanum_fraction": 0.5349593496, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7633451958587533}}
{"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) * \u03c0 / (2 * n)) for k = n:-1:1], fill(\u03c0 / n, n)\n    elseif kind == 2\n        # Gauss-ChebyshevU quadrature, i.e., w(x) = sqrt(1-x^2)\n        ([cos(k * \u03c0 / (n + 1)) for k = n:-1:1],\n         [\u03c0/(n + 1) * sin(k / (n + 1) * \u03c0)^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) * \u03c0 / (n + .5)) for k = n:-1:1],\n         [2\u03c0 / (n + .5) * cos((k - .5) * \u03c0 / (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 * \u03c0 / (n + .5)) for k = n:-1:1],\n         [2\u03c0 / (n + .5) * sin(k * \u03c0 / (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\u209b\u2071(G::Game, i::Int)\n    \u2211(\u0394\u2095(G, T) / length(T) for T in subsets(G.N) if i \u2208 T)\nend\n\n\"\"\"\nShapey value using permutations\n\"\"\"\nfunction f\u209b(G::SimpleGame)\n    N = length(G.N)\n    N\u03c3 = factorial(N)\n\n    shapley = zeros(N)\n\n    for n in 1:N\u03c3\n        \u03c3 = nthperm(G.N, n)\n        \n        for (i, s) in enumerate(\u03c3)\n            shapley[s] += G.v(\u03c3[1:i]) - G.v(\u03c3[1:i - 1])\n        end\n        \n    end\n\n    return shapley ./ N\u03c3\nend\nf\u209b(G::GraphGame) = f\u209b(graphtoMyerson(G))\n\n\"\"\"\nMyerson solution, it is equivalent to the Shapley value of the Myerson game.\n\"\"\"\n\u03bc(G::SimpleGame, L::Array{NTuple{2,Int}}) = f\u209b(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": "using Distributions\nusing Turing\nusing Test\nusing Random\n\nRandom.seed!(125)\n\nD = [1.0 1.0 4.0 4.0]\n\n@model MoGtest(D) = begin\n  mu1 ~ Normal(1, 1)\n  mu2 ~ Normal(4, 1)\n  z1 ~ Categorical(2)\n  if z1 == 1\n    D[1] ~ Normal(mu1, 1)\n  else\n    D[1] ~ Normal(mu2, 1)\n  end\n  z2 ~ Categorical(2)\n  if z2 == 1\n    D[2] ~ Normal(mu1, 1)\n  else\n    D[2] ~ Normal(mu2, 1)\n  end\n  z3 ~ Categorical(2)\n  if z3 == 1\n    D[3] ~ Normal(mu1, 1)\n  else\n    D[3] ~ Normal(mu2, 1)\n  end\n  z4 ~ Categorical(2)\n  if z4 == 1\n    D[4] ~ Normal(mu1, 1)\n  else\n    D[4] ~ Normal(mu2, 1)\n  end\n  z1, z2, z3, z4, mu1, mu2\nend\n\npmmh = PMMH(500, SMC(10, :z1, :z2, :z3, :z4), MH(1, :mu1, :mu2))\nchain = sample(MoGtest(D), pmmh)\n\n@test mean(chain[:z1]) \u2248 1.0 atol=0.1\n@test mean(chain[:z2]) \u2248 1.0 atol=0.1\n@test mean(chain[:z3]) \u2248 2.0 atol=0.1\n@test mean(chain[:z4]) \u2248 2.0 atol=0.1\n@test mean(chain[:mu1]) \u2248 1.0 atol=0.1\n@test mean(chain[:mu2]) \u2248 4.0 atol=0.1\n", "meta": {"hexsha": "185bf4c67b2b490610001a95121eecc9542266b1", "size": 929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pmmh.jl/pmmh2.jl", "max_stars_repo_name": "mohamed82008/Turing.jl", "max_stars_repo_head_hexsha": "70640d35805bb46a54c04d9ff25e5a90f22eee2b", "max_stars_repo_licenses": ["MIT"], "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/pmmh.jl/pmmh2.jl", "max_issues_repo_name": "mohamed82008/Turing.jl", "max_issues_repo_head_hexsha": "70640d35805bb46a54c04d9ff25e5a90f22eee2b", "max_issues_repo_licenses": ["MIT"], "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/pmmh.jl/pmmh2.jl", "max_forks_repo_name": "mohamed82008/Turing.jl", "max_forks_repo_head_hexsha": "70640d35805bb46a54c04d9ff25e5a90f22eee2b", "max_forks_repo_licenses": ["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.9591836735, "max_line_length": 64, "alphanum_fraction": 0.5640473628, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7633451891248165}}
{"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": "function 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", "meta": {"hexsha": "6bc1af76156a8f7215c208655cf70dce59064e07", "size": 617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/aliquot-sequence-classifications-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/aliquot-sequence-classifications-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/aliquot-sequence-classifications-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": 24.68, "max_line_length": 54, "alphanum_fraction": 0.4424635332, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.763327633428489}}
{"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 \u2192 2 \u2192 3 \u2192 \u22ef \u2192 n \u2192 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] \u2209 \"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] \u2209 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\u00e8 Giordano.\n#\n# Maintainer: Mos\u00e8 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\u2013Scargle 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\u2013Scargle 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\u03c0) \\\\[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\u03c0].\n    M = mod(M, T(2\u03c0))\n\n    # Initial guess.\n    #\n    # See [1, p. 75].\n    E = (M > \u03c0) ? M - e : M + e\n\n    sin_E, cos_E = sincos(E)\n\n    # Check the tolerance.\n    if tol === nothing\n        \u03b4 = eps(T)\n    else\n        \u03b4 = 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) \u2264 \u03b4 && 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\u03c0].\n    return mod(E, T(2\u03c0))\nend\n\n\"\"\"\n    M_to_f(e::T1, M::T2; kwargs...) where {T1, T2}\n\nCompute the true anomaly (0,2\u03c0) \\\\[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\u03c0].\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\u03c0) \\\\[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*\u03c0].\n    return mod(2atan(sqrt(1 + e) * sin_Eo2, sqrt(1 - e) * cos_Eo2), T(2\u03c0))\nend\n\n\"\"\"\n    E_to_M(e::T1, E::T2) where {T1, T2}\n\nCompute the mean anomaly (0,2\u03c0) \\\\[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\u03c0))\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\u03c0) \\\\[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\u03c0) )\nend\n\n\"\"\"\n    f_to_M(e::T1, f::T2) where {T1, T2}\n\nCompute the mean anomaly (0,2\u03c0) \\\\[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\u03c0].\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": "mutable struct Model{T <: Real} \n    y::Vector{Int}\n    X::Matrix{T}\n    threshold::T\n    num_obs::Int\n    beta_hat::Vector{T}\n    pi_hat::Vector{T}\n    y_hat::Vector{Int}\n    dof_log::Int\n    dof_resid::Int\n    dof_total::Int\n    llk::T\n    aic::T\n    bic::T\n    # r2::T\n    dev_residuals::Vector{T}\n    dev_residuals_var::Float64\n    sigma::Matrix{T}\n    std_error::Vector{T}\n    # z_value::Vector{T}\n    # z_test_p_value::Vector{T}\nend", "meta": {"hexsha": "fea3ce60df899478b4b4de18c8187795a8e79885", "size": 438, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/structures.jl", "max_stars_repo_name": "LAMPSPUC/LogisticRegression.jl", "max_stars_repo_head_hexsha": "462c2420346f9f8000f719aea8c1bc8cf7705812", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T17:29:11.000Z", "max_issues_repo_path": "src/structures.jl", "max_issues_repo_name": "LAMPSPUC/LogisticRegression.jl", "max_issues_repo_head_hexsha": "462c2420346f9f8000f719aea8c1bc8cf7705812", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-03T15:52:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-07T16:31:04.000Z", "max_forks_repo_path": "src/structures.jl", "max_forks_repo_name": "LAMPSPUC/LogisticRegression.jl", "max_forks_repo_head_hexsha": "462c2420346f9f8000f719aea8c1bc8cf7705812", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 32, "alphanum_fraction": 0.598173516, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7633025861132087}}
{"text": "using Plots\n\n\nfunction circle(x)\n    \u03b8 = x[1];\n    r = 1/2 + 1/2 * (2*x[2]/(1+x[2]^2));\n    return [1-r*cos(\u03b8), 1-r*sin(\u03b8)];\nend\n", "meta": {"hexsha": "64c91911a11661d842dfbdf19ab17caef6346e04", "size": 129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_function/circle_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/circle_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/circle_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": 14.3333333333, "max_line_length": 40, "alphanum_fraction": 0.4728682171, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.763302584821838}}
{"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*\u03c0*x),0.0]\n\nNflux(\u03d5l::AbstractVector, \u03d5r::AbstractVector) = 0.5*(f(\u03d5l)+f(\u03d5r))\nexact_sol(x, t::Float64) = [0.5*(sin(4*\u03c0*(-t+x))+sin(4*\u03c0*(t+x))),\n0.5*(sin(4*\u03c0*(-t+x))-sin(4*\u03c0*(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#\u03f1 is the number of standard deviations above the means\nfunction feature_indexes_sgns(asset_rtn_sgn, kst, klt, kmom, \u03f1=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    \u03c3_st_6 = sqrt((1.0 / kst) * sum((asset_rtn_sgn[t - d] - sig_1)^2 for d in 0:(kst - 1)))\n    \u03c3_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 - \u03f1 * \u03c3_st_6\n    else\n        sig_6 = sig_1 + \u03f1 * \u03c3_st_6\n    end\n    if sig_2 <= 0\n        sig_7 = sig_2 - \u03f1 * \u03c3_lt_7\n    else\n        sig_7 = sig_2 + \u03f1 * \u03c3_lt_7\n    end\n    \u03c3_st_8 = sqrt((1.0 / kst) * sum((asset_rtn_sgn[t - d] - sig_3)^2 for d in 0:(kst - 1)))\n    \u03c3_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 - \u03f1 * \u03c3_st_8\n    else\n        sig_8 = sig_3 + \u03f1 * \u03c3_st_8\n    end\n    if sig_4 <= 0\n        sig_9 = sig_4 - \u03f1 * \u03c3_lt_9\n    else\n        sig_9 = sig_4 + \u03f1 * \u03c3_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, \u03f1=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": "@testset \"curve_length\" begin\n    f(x) = sin(x)\n\n    sol = 3.8201977890277120179047620821714432919099676146472747210804966567\n    @test isapprox(curve_length(f,0,pi), sol; atol = 1e-10)\n    @test !isapprox(curve_length(f,0,5*pi;rtol=1e-4),5*sol,atol=1e-7)\nend\n\n\n@testset \"curve_fraction\" begin \n    f(x) = sin(x)\n\n    @test isapprox(curve_fraction(f,0,pi,0.5), pi/2; atol = 1e-10)\n    @test !isapprox(curve_fraction(f,0,pi,0.5;rtol=1e-2), pi/2; atol = 1e-9)\nend\n", "meta": {"hexsha": "ce6820fb85768ed78984a374bc5753bd9ca4f10c", "size": 462, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/curve_test.jl", "max_stars_repo_name": "owinter92/RandomTweaks.jl", "max_stars_repo_head_hexsha": "a5c695c25b9460e2bc3ef909195e9dbb71b85d19", "max_stars_repo_licenses": ["MIT"], "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/curve_test.jl", "max_issues_repo_name": "owinter92/RandomTweaks.jl", "max_issues_repo_head_hexsha": "a5c695c25b9460e2bc3ef909195e9dbb71b85d19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-01T22:24:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T12:27:58.000Z", "max_forks_repo_path": "test/curve_test.jl", "max_forks_repo_name": "owinter92/RandomTweaks.jl", "max_forks_repo_head_hexsha": "a5c695c25b9460e2bc3ef909195e9dbb71b85d19", "max_forks_repo_licenses": ["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": 76, "alphanum_fraction": 0.6796536797, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.7632899629356585}}
{"text": "using Test\n\ninclude(\"../src/weightedgraph.jl\")\ninclude(\"../test/utils.jl\")\nusing .WeightedGraphAlgo\nusing .WeightedGraphAlgo: WeightedUndirectedEdge\n\nconst tiny_ewg_p614 = (\n    nv = 8,\n    ne = 16,\n    edges = [\n        (5, 6, 0.35),\n        (5, 8, 0.37),\n        (6, 8, 0.28),\n        (1, 8, 0.16),\n        (2, 6, 0.32),\n        (1, 5, 0.38),\n        (3, 4, 0.17),\n        (2, 8, 0.19),\n        (1, 3, 0.26),\n        (2, 3, 0.36),\n        (2, 4, 0.29),\n        (3, 8, 0.34),\n        (7, 3, 0.40),\n        (4, 7, 0.52),\n        (7, 1, 0.58),\n        (7, 4, 0.93)\n    ]\n)\n\n@testset \"Weighted undirected graph\" begin\n\n    @testset \"Lazy Prim algorithm\" begin\n        g = WeightedUndirectedGraph(tiny_ewg_p614)\n        mst = MST(g, LazyPrimMST)\n        edgeset = Set(mst.result.mstedges)\n        @test sum(mst.result.mstvertices) == g.numvertices\n        @test sumweights(mst) == 1.81\n        @test WeightedUndirectedEdge((1, 8, 0.16)) in edgeset\n        @test WeightedUndirectedEdge((6, 8, 0.28)) in edgeset\n    end\n\n    @testset \"Eager Prim algorithm\" begin\n        g = WeightedUndirectedGraph(tiny_ewg_p614)\n        mst = MST(g, EagerPrimMST)\n        edgeset = Set(mst.result.mstedges)\n        @test sum(mst.result.mstvertices) == g.numvertices\n        @test sumweights(mst) \u2248 1.81\n        @test WeightedUndirectedEdge((1, 8, 0.16)) in edgeset\n        @test WeightedUndirectedEdge((6, 8, 0.28)) in edgeset\n    end\n\n    @testset \"Kruskal's algorithm\" begin\n        g = WeightedUndirectedGraph(tiny_ewg_p614)\n        mst = MST(g, KruskalMST)\n        edgeset = Set(mst.result.mstedges)\n        @test sumweights(mst) == 1.81\n        @test WeightedUndirectedEdge((1, 8, 0.16)) in edgeset\n        @test WeightedUndirectedEdge((6, 8, 0.28)) in edgeset\n    end\n\nend\n\n@testset \"Weighted directed graph\" begin\n    CURRENT_PATH = cd(pwd, \".\")\n    tinyewd = loadewg(joinpath(CURRENT_PATH, \"data/tinyEWD.txt\"))\n\n    @testset \"Dijkstra shortest path\" begin\n        g = WeightedDirectedGraph(tinyewd)\n        sp = SP(g, 1, DijkstraSP)\n        @test distanceto(sp, 2) \u2248 1.05\n        @test distanceto(sp, 3) \u2248 0.26 \n        @test distanceto(sp, 4) \u2248 0.99 \n        @test distanceto(sp, 5) \u2248 0.38 \n        @test distanceto(sp, 6) \u2248 0.73 \n        @test distanceto(sp, 7) \u2248 1.51 \n        @test distanceto(sp, 8) \u2248 0.60 \n    end\n\nend", "meta": {"hexsha": "0a2b39f4725823e2306ff9820204355e91624a1a", "size": 2312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/weightedgraph.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": "test/weightedgraph.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": "test/weightedgraph.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": 28.9, "max_line_length": 65, "alphanum_fraction": 0.5657439446, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7632899593847533}}
{"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\u03c0 * i / 6), sin(2\u03c0 * 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\u2080 = boundary1(mesh)\n    # d\u2081 = boundary2d(mesh)\n    # *\u2081 = hodgestar1(mesh)\n    # *\u2082 = hodgestar2(mesh)\n    # \u0394 = *\u2082 * d\u2081 * *\u2081 * d\u2080\n    \u0394 = laplacian(mesh) # calculate the laplacian operator\n\n    b = [-1 - 10 * sum(\u0394[i, vext]) for i = 1:length(vint)]\n\n    # numerical solution\n    zf = \u0394[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\u00f3n num\u00e9rica 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\u03c0 * i / (50 * r + 1)), sin(2\u03c0 * 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    \u0394 = laplacian(mesh)\n\n    b = [-1 - 10 * sum(\u0394[i, vext]) for i = 1:length(vint)]\n    zf = \u0394[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\u00f3n num\u00e9rica 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\u03c0 * i / (200 * r + 1)), sin(2\u03c0 * 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    \u0394 = laplacian(mesh)\n\n    b = [-1 - 10 * sum(\u0394[i, vext]) for i = 1:length(vint)]\n    zf = \u0394[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\u00f3n num\u00e9rica 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": "@add_problem socp function socp_norm_2_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(2, 1)\n    A = [1 2; 2 1; 3 4]\n    b = [2; 3; 4]\n    p = minimize(norm2(A * x + b))\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0.64888 atol=atol rtol=rtol\n        @test evaluate(norm2(A * x + b)) \u2248 0.64888 atol=atol rtol=rtol\n    end\n\n    x = Variable(2, 1)\n    A = [1 2; 2 1; 3 4]\n    b = [2; 3; 4]\n    lambda = 1\n    p = minimize(norm2(A * x + b) + lambda * norm2(x), x >= 1)\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 14.9049 atol=atol rtol=rtol\n        @test evaluate(norm2(A * x + b) + lambda * norm2(x)) \u2248 14.9049 atol=atol rtol=rtol\n    end\n\n    x = Variable(2)\n\n    p = minimize(norm2([x[1] + 2x[2] + 2; 2x[1] + x[2] + 3; 3x[1]+4x[2] + 4]) + lambda * norm2(x), x >= 1)\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 14.9049 atol=atol rtol=rtol\n        @test evaluate(norm2(A * x + b) + lambda * norm2(x)) \u2248 14.9049 atol=atol rtol=rtol\n    end\n\n    x = Variable(2, 1)\n    A = [1 2; 2 1; 3 4]\n    b = [2; 3; 4]\n    lambda = 1\n    p = minimize(norm2(A * x + b) + lambda * norm_1(x), x >= 1)\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 15.4907 atol=atol rtol=rtol\n        @test evaluate(norm2(A * x + b) + lambda * norm_1(x)) \u2248 15.4907 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_frobenius_norm_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    m = Variable(4, 5)\n    c = [m[3, 3] == 4, m >= 1]\n    p = minimize(norm(vec(m), 2), c)\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 sqrt(35) atol=atol rtol=rtol\n        @test evaluate(norm(vec(m), 2)) \u2248 sqrt(35) atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_quad_over_lin_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(3, 1)\n    A = [2 -3 5; -2 9 -3; 5 -8 3]\n    b = [-3; 9; 5]\n    c = [3 2 4]\n    d = -3\n    p = minimize(quadoverlin(A*x + b, c*x + d))\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 17.7831 atol=atol rtol=rtol\n        @test (evaluate(quadoverlin(A * x + b, c * x + d)))[1] \u2248 17.7831 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_sum_squares_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(2, 1)\n    A = [1 2; 2 1; 3 4]\n    b = [2; 3; 4]\n    p = minimize(sumsquares(A*x + b))\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0.42105 atol=atol rtol=rtol\n        @test (evaluate(sumsquares(A * x + b)))[1] \u2248 0.42105 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_square_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(2, 1)\n    A = [1 2; 2 1; 3 4]\n    b = [2; 3; 4]\n    p = minimize(sum(square(A*x + b)))\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0.42105 atol=atol rtol=rtol\n        @test evaluate(sum(square(A * x + b))) \u2248 0.42105 atol=atol rtol=rtol\n    end\n\n    x = Variable(2, 1)\n    A = [1 2; 2 1; 3 4]\n    b = [2; 3; 4]\n    expr = A * x + b\n    p = minimize(sum(dot(^)(expr,2))) # elementwise ^\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0.42105 atol=atol rtol=rtol\n        @test evaluate(sum(broadcast(^, expr, 2))) \u2248 0.42105 atol=atol rtol=rtol\n    end\n\n    p = minimize(sum(dot(*)(expr, expr))) # elementwise *\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0.42105 atol=atol rtol=rtol\n        @test evaluate(sum((dot(*))(expr, expr))) \u2248 0.42105 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_inv_pos_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(4)\n    p = minimize(sum(invpos(x)), invpos(x) < 2, x > 1, x == 2, 2 == x)\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 2 atol=atol rtol=rtol\n        @test evaluate(sum(invpos(x))) \u2248 2 atol=atol rtol=rtol\n    end\n\n    x = Variable(3)\n    p = minimize(sum(dot(/)([3,6,9], x)), x<=3)\n    handle_problem!(p)\n    if test\n        @test x.value \u2248 fill(3.0, (3, 1)) atol=atol rtol=rtol\n        @test p.optval \u2248 6 atol=atol rtol=rtol\n        @test evaluate(sum((dot(/))([3, 6, 9], x))) \u2248 6 atol=atol rtol=rtol\n    end\n\n    x = Variable()\n    p = minimize(sum([3,6,9]/x), x<=3)\n    handle_problem!(p)\n    if test\n        @test x.value \u2248 3 atol=atol rtol=rtol\n        @test p.optval \u2248 6 atol=atol rtol=rtol\n        @test evaluate(sum([3, 6, 9] / x)) \u2248 6 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_geo_mean_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(2)\n    y = Variable(2)\n    p = minimize(geomean(x, y), x >= 1, y >= 2)\n    # not DCP compliant\n    if test\n        @test vexity(p) == ConcaveVexity()\n    end\n    p = maximize(geomean(x, y), 1 < x, x < 2, y < 2)\n    # Just gave it a vector as an objective, not okay\n    if test\n        @test_throws Exception handle_problem!(p)\n    end\n\n    p = maximize(sum(geomean(x, y)), 1 < x, x < 2, y < 2)\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 4 atol=atol rtol=rtol\n        @test evaluate(sum(geomean(x, y))) \u2248 4 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_sqrt_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable()\n    p = maximize(sqrt(x), 1 >= x)\nend\n\n@add_problem socp function socp_quad_form_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(3, 1)\n    A = [0.8608 0.3131 0.5458; 0.3131 0.8584 0.5836; 0.5458 0.5836 1.5422]\n    p = minimize(quadform(x, A), [x >= 1])\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 6.1464 atol=atol rtol=rtol\n        @test (evaluate(quadform(x, A)))[1] \u2248 6.1464 atol=atol rtol=rtol\n    end\n\n    x = Variable(3, 1)\n    A = -1.0*[0.8608 0.3131 0.5458; 0.3131 0.8584 0.5836; 0.5458 0.5836 1.5422]\n    c = [3 2 4]\n    p = maximize(c*x , [quadform(x, A) >= -1])\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 3.7713 atol=atol rtol=rtol\n        @test (evaluate(quadform(x, A)))[1] \u2248 -1 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_huber_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(3)\n    p = minimize(sum(huber(x, 1)), x >= 2)\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 9 atol=atol rtol=rtol\n        @test evaluate(sum(huber(x, 1))) \u2248 9 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_rational_norm_atom(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    A = [1 2 3; -1 2 3]\n    b = A * ones(3)\n    x = Variable(3)\n    p = minimize(norm(x, 4.5), [A * x == b])\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    # Solution is approximately x = [1, .93138, 1.04575]\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 1.2717 atol=atol rtol=rtol\n        @test evaluate(norm(x, 4.5)) \u2248 1.2717 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_rational_norm_dual_norm(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    v = [0.463339, 0.0216084, -2.07914, 0.99581, 0.889391]\n    x = Variable(5)\n    q = 1.379;  # q norm constraint that generates many inequalities\n    qs = q / (q - 1);  # Conjugate to q\n    p = minimize(x' * v)\n    p.constraints += (norm(x, q) <= 1)\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p) # Solution is -norm(v, q / (q - 1))\n    if test\n        @test p.optval \u2248 -2.144087 atol=atol rtol=rtol\n        @test sum(evaluate(x' * v)) \u2248 -2.144087 atol=atol rtol=rtol\n        @test evaluate(norm(x, q)) \u2248 1 atol=atol rtol=rtol\n        @test sum(evaluate(x' * v)) \u2248 -(sum(abs.(v) .^ qs) ^ (1 / qs)) atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_rational_norm_atom_sum(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    A = [-0.719255  -0.229089\n        -1.33632   -1.37121\n        0.703447  -1.4482]\n    b = [-1.82041, -1.67516, -0.866884]\n    q = 1.5\n    xvar = Variable(2)\n    p = minimize(.5 * sumsquares(xvar) + norm(A * xvar - b, q))\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n    handle_problem!(p)\n    \n    if test\n        # Compute gradient, check it is zero(ish)\n        x_opt = xvar.value\n        margins = A * x_opt - b\n        qs = q / (q - 1);  # Conjugate\n        denom = sum(abs.(margins).^q)^(1/qs)\n        g = x_opt + A' * (abs.(margins).^(q-1) .* sign.(margins)) / denom\n        @test p.optval \u2248 1.7227 atol=atol rtol=rtol\n        @test norm(g, 2) ^ 2 \u2248 0 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_norm_consistent_with_Base_for_matrix_variables(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    A = randn(4, 4)\n    x = Variable(4, 4)\n    x.value = A\n    # Matrix norm\n    if test\n        @test evaluate(opnorm(x)) \u2248 opnorm(A) atol=atol rtol=rtol\n        @test evaluate(opnorm(x, 1)) \u2248 opnorm(A, 1) atol=atol rtol=rtol\n        @test evaluate(opnorm(x, 2)) \u2248 opnorm(A, 2) atol=atol rtol=rtol\n        @test evaluate(opnorm(x, Inf)) \u2248 opnorm(A, Inf) atol=atol rtol=rtol\n    end\n    # Vector norm\n    # TODO: Once the deprecation for norm on matrices is removed, remove the `vec` calls\n    if test\n        @test evaluate(norm(vec(x), 1)) \u2248 norm(vec(A), 1) atol=atol rtol=rtol\n        @test evaluate(norm(vec(x), 2)) \u2248 norm(vec(A), 2) atol=atol rtol=rtol\n        @test evaluate(norm(vec(x), 7)) \u2248 norm(vec(A), 7) atol=atol rtol=rtol\n        @test evaluate(norm(vec(x), Inf)) \u2248 norm(vec(A), Inf) atol=atol rtol=rtol\n    end\nend\n\n\n@add_problem socp function socp_fix_and_free_addition(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable()\n    y = Variable()\n\n    p = minimize(x+y, x>=0, y>=0)\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0 atol=atol rtol=rtol\n    end\n\n    y.value = 4\n    fix!(y)\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 4 atol=atol rtol=rtol\n    end\n\n    free!(y)\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 0 atol=atol rtol=rtol\n    end\nend\n\n@add_problem socp function socp_fix_multiplication(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    a = [1,2,3,2,1]\n    x = Variable(length(a))\n    gamma = Variable(Positive())\n    fix!(gamma, 0.7)\n\n    p = minimize(norm(x-a) + gamma*norm(x[1:end-1] - x[2:end]))\n    handle_problem!(p)\n    if test\n        o1 = p.optval\n        # x should be very close to a\n        @test o1 \u2248 0.7 * norm(a[1:end - 1] - a[2:end]) atol=atol rtol=rtol\n    end\n    # increase regularization\n    fix!(gamma, 1.0)\n    handle_problem!(p)\n    \n    if test\n        o2 = p.optval\n        # x should be very close to mean(a)\n        @test o2 \u2248 norm(a .- mean(a)) atol=atol rtol=rtol\n    end\n\n    if test\n        @test o1 <= o2\n    end\nend\n\n\n@add_problem socp function socp_dual_minimal_norm_solutions(handle_problem!, ::Val{test}, atol, rtol, ::Type{T}) where {T, test}\n    x = Variable(2)\n    A = [1 2; 2 4];\n    b = [3, 6];\n    p = minimize(norm(x, 1), A*x==b)\n\n    if test\n        @test vexity(p) == ConvexVexity()\n    end\n\n    handle_problem!(p)\n    if test\n        @test p.optval \u2248 1.5 atol=atol rtol=rtol\n        @test evaluate(x) \u2248 [0, 1.5] atol=atol rtol=rtol\n        @test evaluate(norm(x, 1)) \u2248 p.optval atol=atol rtol=rtol\n        @test dot(b, p.constraints[1].dual) \u2248 p.optval atol=atol rtol=rtol\n    end\n\n    x = Variable(2)\n    A = [1 2; 2 4];\n    b = [3, 6];\n    p = minimize(norm(x, 2), A*x==b)\n    \n    test && @test vexity(p) == ConvexVexity()\n    \n    handle_problem!(p)\n    \n    if test\n        @test p.optval \u2248 3/sqrt(5) atol=atol rtol=rtol\n        @test evaluate(x) \u2248 [3/5, 6/5] atol=atol rtol=rtol\n        @test evaluate(norm(x, 2)) \u2248 p.optval atol=atol rtol=rtol\n        @test dot(b, p.constraints[1].dual) \u2248 p.optval atol=atol rtol=rtol\n    end\n\n    x = Variable(2)\n    A = [1 2; 2 4];\n    b = [3, 6];\n    p = minimize(norm(x, Inf), A*x==b)\n\n    test && @test vexity(p) == ConvexVexity()\n\n    handle_problem!(p)\n\n    if test\n        @test p.optval \u2248 1.0 atol=atol rtol=rtol\n        @test evaluate(x) \u2248 [1, 1] atol=atol rtol=rtol\n        @test evaluate(norm(x, Inf)) \u2248 p.optval atol=atol rtol=rtol\n        @test dot(b, p.constraints[1].dual) \u2248 p.optval atol=atol rtol=rtol\n    end\nend\n", "meta": {"hexsha": "5269a6d6e1c7f4928ccaec8e3a38bc5817904a83", "size": 13155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem_depot/problems/socp.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": "src/problem_depot/problems/socp.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": "src/problem_depot/problems/socp.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": 30.9529411765, "max_line_length": 147, "alphanum_fraction": 0.5712656784, "num_tokens": 5018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7632899524280167}}
{"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": "using BenchmarkTools, FinancialMonteCarlo, ForwardDiff\n\nS0 = 100.0;\nK = 100.0;\nr = 0.02;\nT = 1.0;\nd = 0.01;\nD = 90.0;\n\nNsim = 100000;\nNstep = 30;\nsigma = 0.2\nmc = MonteCarloConfiguration(Nsim, Nstep);\ntoll = 1e-3;\n\nrfCurve = ZeroRate(r);\n\nFwdData = Forward(T)\nEUData = EuropeanOption(T, K)\nAMData = AmericanOption(T, K)\nBarrierData = BarrierOptionDownOut(T, K, D)\nAsianFloatingStrikeData = AsianFloatingStrikeOption(T)\nAsianFixedStrikeData = AsianFixedStrikeOption(T, K)\nModel = BlackScholesProcess(sigma, Underlying(S0, d));\n\nf__1(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, EuropeanOption(x[5], K));\nx = Float64[sigma, S0, r, d, T]\ng__1 = x -> ForwardDiff.gradient(f__1, x);\ny0 = g__1(x);\n@btime f__1(x);\n@btime g__1(x);\n\nf_(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, AmericanOption(x[5], K));\ng_ = x -> ForwardDiff.gradient(f_, x);\ny0 = g_(x);\n@btime f_(x);\n@btime g_(x);\n", "meta": {"hexsha": "ac3590ad0a05e1e8b0b38ab65a6f791eb6d74448", "size": 970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark/bench_black_forward_diff_grad.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": "benchmark/bench_black_forward_diff_grad.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": "benchmark/bench_black_forward_diff_grad.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": 25.5263157895, "max_line_length": 121, "alphanum_fraction": 0.6845360825, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7632797079441631}}
{"text": "\"\"\"\n\tMMCK(\u03bc, \u03bb, c, k)\n\nT\u1ea1o m\u00f4 h\u00ecnh M/M/c/k\n\"\"\"\nstruct MMCK{T} <:AbstractMMCK\n\t\u03bb::T\n\t\u03bc::T\n\tc::Union{T, Integer}\n\tk::Union{T, Integer}\n\tr::Union{T, Real}\n\t\u03c1::Union{T, Real}\n\tfunction MMCK(\u03bb, \u03bc, c, k)\n\t\tT = Union{typeof(\u03bc), typeof(\u03bb)}\n\t\tnew{T}(\u03bb, \u03bc, c,\tk, \u03bb/\u03bc,\t\u03bb/\u03bc/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) / \u03bbe(m)\nend\n\nfunction Wq(m::MMCK)\n\tLq(m) / \u03bbe(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) \u00f7 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})(\u03c1, \u03b8) where T\n    x = \u03c1^2 - 1\n    return T(\u03c1^abs(z.m) * z.basis(x) * z.trig_func(z.m * \u03b8))\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 = \u221a(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 + \u221a(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 + \u221a(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\u00f72\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(\u221aj - 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, \u03c1, \u03b8[; norm])\n\nZernike polynomial of radial order n and azimuthal order m, evaluated at the\npoint (\u03c1, \u03b8).  No normalization is required of (\u03c1, \u03b8), 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, \u03c1, \u03b8; norm::Bool=true)\n    x = \u03c1^2 - 1\n    n_j = (n - m) / 2\n    am = abs(m)\n    # \u03b1=0, \u03b2=|m|\n    # there is a second syntax where you have x reversed, 1 - \u03c1^2,\n    # in which ase you swap \u03b1 and \u03b2.  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 *= (\u03c1^am * f(m*\u03b8))\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": "using BenchmarkTools\nusing StaticArrays\nusing Test\nusing LoopVectorization\n\nfunction pot(x,y,eps4,sig6,sig12)\n  r2 = (x[1]-y[1])^2 + (x[2]-y[2])^2\n  r6 = r2^3\n  r12 = r6^2\n  return eps4*(sig12/r12 - sig6/r6)\nend\n\nfunction total_pot(p,eps,sig)\n  eps4 = 4*eps\n  sig6 = sig^6\n  sig12 = sig6^2\n  total_pot = 0.\n  for i in 1:length(p)-1\n    @avx for j in i+1:length(p)\n      total_pot = total_pot + pot(p[i],p[j],eps4,sig6,sig12)\n    end\n  end\n  return total_pot\nend\n\neps = 4.\nsig = 1.\np = [ 10*rand(2) for i in 1:10 ]\nr1 = @btime total_pot(p,eps,sig)\n\np = [ SVector(p[i]...) for i in 1:10 ]\nr2 = @btime total_pot(p,eps,sig)\n\n@test r1 \u2248 r2\n\n", "meta": {"hexsha": "f9caeb6791ffd97d89480beda1a3edd82f97787b", "size": 636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "disciplina/codes/ativ13_Static.jl", "max_stars_repo_name": "m3g/kinetics", "max_stars_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-27T19:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T09:24:24.000Z", "max_issues_repo_path": "disciplina/codes/ativ13_Static.jl", "max_issues_repo_name": "m3g/kinetics", "max_issues_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "disciplina/codes/ativ13_Static.jl", "max_forks_repo_name": "m3g/kinetics", "max_forks_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T17:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:20:58.000Z", "avg_line_length": 17.6666666667, "max_line_length": 60, "alphanum_fraction": 0.6226415094, "num_tokens": 276, "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": "#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": "\r\nfunction update_derivs_pos!(state::Vector{Float64}, derivs::Vector{Float64} )\r\n # Input: state = [x,y,vx,vy], a vector of two 2-d positions and velocities for a test particle\r\n # Output: The derivatives of the position are updated in the preallocated array derivs.\r\n  @assert length(state) == 4\r\n  @assert length(derivs) == 4\r\n  v_x = state[3]\r\n  v_y = state[4]\r\n  derivs[1] = v_x\r\n  derivs[2] = v_y\r\n  return derivs;\r\nend\r\n\r\nfunction update_derivs_vel!(state::Vector{Float64}, derivs::Vector{Float64} )\r\n  # Input: state = [x,y,vx,vy], a vector of two 2-d positions and velocities for a test particle\r\n  # Output: The derivatives of the velocity are updated in the preallocated array derivs.  \r\n  @assert length(state) == 4\r\n  @assert length(derivs) == 4\r\n  GM = 1.0\r\n  r_x = state[1]\r\n  r_y = state[2]\r\n  r2 = r_x*r_x+r_y*r_y\r\n  a = -GM/r2\r\n  r = sqrt(r2)\r\n  a_x = a * r_x/r\r\n  a_y = a * r_y/r\r\n  derivs[3] = a_x\r\n  derivs[4] = a_y\r\n  return derivs;\r\nend\r\n\r\nfunction update_derivs!(state::Vector{Float64}, derivs::Vector{Float64} )\r\n  # Input: state = [x,y,vx,vy], a vector of two 2-d positions and velocities for a test particle\r\n  # Output: The derivatives are updated in the preallocated array derivs.  \r\n  update_derivs_vel!(state,derivs)\r\n  update_derivs_pos!(state,derivs)\r\n  return derivs\r\nend\r\n  \r\nfunction advance_leapfrog!(state::Vector{Float64},derivs::Vector{Float64}, dt::Float64; derivs_current::Bool = false)\r\n  # Input/Output: state = array of two 2-d positions and velocities for a test particle\r\n  # Temporary space: The derivatives are updated in the preallocated array derivs.\r\n  # Input: dt is the fixed time step \r\n  # Optional param: derivs_current: whether need to calculate derivatives at beginning\r\n  @assert length(state) == length(derivs)\r\n  \r\n  if !derivs_current \r\n    update_derivs_pos!(state,derivs);\r\n  end\r\n  state[1] += 0.5*dt*derivs[1]\r\n  state[2] += 0.5*dt*derivs[2]\r\n  update_derivs_vel!(state,derivs);\r\n  state[3] += dt*derivs[3]  \r\n  state[4] += dt*derivs[4]   \r\n  update_derivs_pos!(state,derivs);\r\n  state[1] += 0.5*dt*derivs[1]\r\n  state[2] += 0.5*dt*derivs[2]\r\nend\r\n\r\n# Input/Output: state = [x,y,vx,vy], an array of two 2-d positions and velocities for a test particle\r\n# Input: dt is the fixed time step \r\n# Input: duration is the total \r\nfunction integrate_leapfrog!(state::Vector{Float64}, dt::Float64, duration::Float64; max_num_log::Integer = 100000)\r\n  @assert(length(state)==4) \r\n  @assert(dt>0.0)\r\n  @assert(duration>0.0)\r\n  \r\n  # Preallocate array to hold data log (including  initial state)\r\n  nsteps = iceil(duration/dt);\r\n  nskip = (nsteps<max_num_log) ? 1 : iceil(nsteps/(max_num_log-1))\r\n  num_log = iceil(nsteps/nskip)+1   \r\n  log = Array(Float64,(num_log,length(state)));\r\n\r\n  # Pre-allocate and pre-compute derivaties\r\n  derivs = Array(Float64,4);  \r\n  update_derivs!(state,derivs);\r\n\r\n  # Log initial state \r\n  log_pos = 1\r\n  log[log_pos,:] = deepcopy(state) \r\n\r\n  n = 0\r\n  t = 0.0\r\n  while t<duration\r\n    # ensure don't integrate for more than duration\r\n    dt_tmp = (t+dt<=duration) ? dt : duration-t;\r\n\r\n\t# advance system by one time step\r\n    advance_leapfrog!(state,derivs,dt_tmp, derivs_current=true)\r\n    t = t + dt_tmp\r\n    n = n + 1\r\n\r\n    if (n%nskip==0) # Log data\r\n\t   log_pos += 1\r\n   \t   @assert( log_pos<=length(log) )\r\n\t   @assert( length(log[log_pos,:])==length(state) )\r\n\t   log[log_pos,:] = deepcopy(state) \r\n\tend\r\n  end\r\n  return log\r\nend\r\n\r\nfunction calc_error_leapfrog_old(dur::Float64, dt::Float64 = 2pi/200.0)\r\n  state = [1.,0.,0.,1.];  \r\n  integrate_leapfrog!(state,dt,dur*2pi);\r\n  dist = state[1]^2+state[2]^2\r\n  phase = atan2(state[2],state[1])\r\n  offset = sum((state[1:2].-[1.0,0.0]).^2)\r\n  return (dist-1.0,phase,offset)\r\nend\r\n\r\nfunction calc_end_distance_leapfrog(dur::Integer, dt::Float64 = 2pi/200.0, state::Vector{Float64} = [1., 0., 0., 1.] )\r\n  #state = [1.,0.,0.,1.];  \r\n  dist_init = sqrt(state[1]^2+state[2]^2)\r\n  phase_init = atan2(state[2],state[1])\r\n  integrate_leapfrog!(state,dt,dur*2pi);\r\n  # Calculate three metrics of the accuracy of the integration  \r\n  dist = sqrt(state[1]^2+state[2]^2)\r\n  phase = atan2(state[2],state[1])\r\n  offset = sqrt(sum((state[1:2].-[1.0,0.0]).^2))\r\n  return (dist-dist_init,phase-phase_init,offset)\r\nend\r\n\r\nusing Base.Test\r\nfunction test_leapfrog(dur::Integer, dt::Float64 = 2pi/200.0)  \r\n  err = calc_end_distance_leapfrog(dur,dt)\r\n  @test_approx_eq_eps(err[1], 0., 1e-6)\r\n  @test_approx_eq_eps(err[2], 0., 1e-1)\r\n  @test_approx_eq_eps(err[3], 0., 1e-1)\r\nend\r\n\r\n", "meta": {"hexsha": "c4b6f0a1299a2eb0de3dc0c2ffa7d0b9454093fb", "size": 4504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "labs/4/leapfrog_eric.jl", "max_stars_repo_name": "eford/Astro585_2015_Fall_Public", "max_stars_repo_head_hexsha": "11ca3ff267babb27166013699b760fae541ace38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-03-16T07:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T08:55:31.000Z", "max_issues_repo_path": "labs/4/leapfrog_eric.jl", "max_issues_repo_name": "eford/Astro585_2015_Fall_Public", "max_issues_repo_head_hexsha": "11ca3ff267babb27166013699b760fae541ace38", "max_issues_repo_licenses": ["MIT"], "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/4/leapfrog_eric.jl", "max_forks_repo_name": "eford/Astro585_2015_Fall_Public", "max_forks_repo_head_hexsha": "11ca3ff267babb27166013699b760fae541ace38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-11T05:28:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T07:01:53.000Z", "avg_line_length": 34.1212121212, "max_line_length": 119, "alphanum_fraction": 0.6620781528, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.763272109297936}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 f6d978ea-b349-11eb-309e-f5a517efc907\nbegin \n\tusing LinearAlgebra \n\tusing Plots \n\tusing QuadGK\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b11596d4-ee5d-41ec-af8f-96734ba2f579\n# This shows a heirarchy of grids\t\ngrid1 = plot(x,zeros(length(x)),marker=\"*\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u03b8(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 \u03b8_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) * \u03b8_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# \u2554\u2550\u2561 a5f1a911-3f71-4630-a872-99514d52e5f3\nbegin\n\tnk = 12;\n\ta = LinRange(xmin,xmax,nk); \n\tz = \u03b8(a,3,nk);\n\tplot(a,z)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550f6d978ea-b349-11eb-309e-f5a517efc907\n# \u2560\u255099268461-9e3f-4685-b530-e24febfb539e\n# \u2560\u2550b422b21d-b9d3-4aad-b29b-d0669331abc8\n# \u2560\u2550b11596d4-ee5d-41ec-af8f-96734ba2f579\n# \u2560\u2550c1463b68-12e6-4e8c-9902-c2cc7e6caa91\n# \u2560\u2550d5da54e6-0a4f-4f43-a7ab-8791574b32c6\n# \u2560\u2550a5f1a911-3f71-4630-a872-99514d52e5f3\n# \u2560\u2550feba23c9-1b66-400e-9ffb-0dc5fc65896f\n# \u255f\u2500b8b7b670-6039-4bd9-9f95-8652f6e03528\n# \u255f\u2500a217bef6-3c9f-4d12-8b3f-eb937987c709\n# \u2560\u2550f2a7eb59-3617-47fe-be19-f6873d0f3c56\n# \u2560\u2550abf72f94-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": "\n# for plotif. This identifies a vector of colors\nfunction identify_colors(g, xs, colors=(:red, :blue, :black))\n    F = (a,b) -> begin\n        ga,gb=g(a),g(b)\n        ga * gb < 0 && return nothing\n        ga >= 0 && return true\n        return false\n    end\n    find_colors(F, xs, colors)\nend\n\n# F(a,b) returns true, false, or nothing\nfunction find_colors(F, xs, colors=(:red, :blue, :black))\n    n = length(xs)\n    cols = repeat([colors[1]], n)\n    for i in 1:n-1\n        a,b = xs[i], xs[i+1]\n        val = F(a,b)\n        if val == nothing\n            cols[i] = colors[3]\n        elseif val\n            cols[i] = colors[1]\n        else\n            cols[i] = colors[2]\n        end\n    end\n    cols[end] = cols[end-1]\n    cols\nend\n\n\n\n# some plotting utilities\n\"\"\"\n    rangeclamp(f, hi=20, lo=-hi; replacement=NaN)\n\nModify `f` so that values of `f(x)` outside of `[lo,hi]` are replaced by `replacement`.\n\nExamples\n```\nf(x) = 1/x\nplot(rangeclamp(f), -1, 1)\nplot(rangeclamp(f, 10), -1, 1) # no `abs(y)` values exceeding 10\n```\n\"\"\"\nrangeclamp(f, hi=20, lo=-hi; replacement=NaN) = x -> lo < f(x) < hi ? f(x) : replacement\n", "meta": {"hexsha": "094687c8436dd713b62f9538a8d4cacc0f55ed6d", "size": 1115, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plot-utils.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/plot-utils.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/plot-utils.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": 23.2291666667, "max_line_length": 88, "alphanum_fraction": 0.5488789238, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8918110396870287, "lm_q1q2_score": 0.7632574979152758}}
{"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# \u0394u + (E+x_2)u = 0,\n# u|\u0393 = 0,\n# u^i = \u03a6(\u22c5,\u22c5,E)|\u0393\n# u = u^i + u^s.\n# The normal derivative \u2202u/\u2202n of the entire wave is calculated on the sound-soft boundaries.\n# The scattered wave is calculated by convolving \u2202u/\u2202n 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\u03c9 = 2\u03c0\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 = \u222a(Segment.([-10.0-3.0im,5.0,-2+5im],[-5.0+0.0im,10.0-3im,2+5im]))\nsp = Space(dom)\ncwsp = CauchyWeight(sp\u2297sp,0)\nui\u0393,\u2a0d = Fun(t->ui(real(t),imag(t)),sp),DefiniteLineIntegral(dom)\n\n@time G = GreensFun(g3,cwsp;method=:unsplit)\n\n@time \u2202u\u2202n = \u2a0d[G]\\ui\u0393\nprintln(\"The length of \u2202u\u2202n is: \",ncoefficients(\u2202u\u2202n))\nus = (x,y) ->  -linesum(g3,\u2202u\u2202n,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\u2013338.\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    \u03bb::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.\u03bb\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, \u025b::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        \u03bc = mean(VX, dims=2)\n        \u03b4_x = VX .- \u03bc\n\n        # Compute orthogonal basis H of \u03b8'\n        \u03b8_t = svd(\u03b4_x).V[:,1:maxoutdim]\n\n        # Construct alignment matrix\n        G = hcat(S, \u03b8_t)\n        B[II, II] .+= Diagonal(fill(one(T), k)) .- G*transpose(G)\n    end\n\n    # Align global coordinates\n    \u03bb, V = decompose(B, maxoutdim)\n    return LTSA{nntype, T}(\u03bb, 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 \u221a(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\u00f72, maxsize\u00f72)\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, \u221a(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 \u00f7 2\n    left = right = width \u00f7 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": "if !@isdefined TEST\n    using Revise\nend\nusing Mitosis\nusing Random, Test, LinearAlgebra, Statistics\nRandom.seed!(1)\n\n# Prior (as kernel of prior mean)\n\n\u03bc0 = zeros(2)\n\u03c32 = 8.0 # noise\nV0 = 10*I(2)\n\u03a30 = \u03c32*V0 # prior\n\nprior = kernel(Gaussian; \u03bc=ConstantMap(\u03bc0), \u03a3=ConstantMap(\u03a30))\n\n# Data\nx = [18.25 19.75 16.5 18.25 19.50 16.25 17.25 19.00 16.25 17.50][:]\ny = [36 42 33 39 43 34 37 41 27 30][:]\nn = length(x)\n\n# Model\nX = [x ones(n)]\n\u03a3 = Diagonal(\u03c32*ones(n))\nmodel = kernel(Gaussian; \u03bc=LinearMap(X), \u03a3=ConstantMap(\u03a3))\n\n# backward pass\nm2, p2 = backward(BF(), model, y)\nm1, p1 = backward(BF(), prior, p2)\n\nposterior = forward(BF(), prior, m1)()\n\n@show mean(posterior), cov(posterior)\n\n\u03b2\u0302 = X\\y\n@test \u03b2\u0302 \u2248 mean(p2)\n\n@test mean(posterior) \u2248 inv(X'*X + inv(V0))*X'*y\n@test cov(posterior) \u2248 \u03c32*inv(X'*X + inv(V0))\n", "meta": {"hexsha": "89446500a43e2067b8d18f4856e2480788aad320", "size": 809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/regression.jl", "max_stars_repo_name": "cscherrer/Mitosis.jl", "max_stars_repo_head_hexsha": "e11113d392a9ac9c884212acaf177bc4dbb619c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2020-10-08T13:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T13:05:22.000Z", "max_issues_repo_path": "example/regression.jl", "max_issues_repo_name": "frankschae/Mitosis.jl", "max_issues_repo_head_hexsha": "0ab3d7b21a0a6e86cf6fafb097d733c0624e1088", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-12-01T19:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T17:34:41.000Z", "max_forks_repo_path": "example/regression.jl", "max_forks_repo_name": "frankschae/Mitosis.jl", "max_forks_repo_head_hexsha": "0ab3d7b21a0a6e86cf6fafb097d733c0624e1088", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-19T23:32:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T16:06:27.000Z", "avg_line_length": 20.225, "max_line_length": 67, "alphanum_fraction": 0.6390605686, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7631908453942435}}
{"text": "using jInv.LinearSolvers\nusing Test\nusing ConvDiffMIPDECO\nusing jInv.ForwardShare\nusing jInv.Mesh\nusing LinearAlgebra\nusing SparseArrays\nusing MUMPSjInv\n\ndomain = [0 1. 0 1]\n\nN = 2*[16;32;64;128]\nv = randn(2)\nv = v/norm(v)\nV = X -> [v[1]*ones(size(X,1)) v[2]*ones(size(X,1))]\nbc = (:neu,:dir,:neu,:dir)\n\nu  = X -> cos.(pi*X[:,1]).*cos.(pi*X[:,2])\n\nux = X -> -pi*sin.(pi*X[:,1]).*cos.(pi*X[:,2])\nuy = X -> -pi*cos.(pi*X[:,1]).*sin.(pi*X[:,2])\nsig = .001;\n\nf  = X->  +2*sig*pi^2*u(X)+v[1]*ux(X)+v[2]*uy(X)\n\nerr = zeros(length(N))\n\nbicg = (A,b; M=identity,tol=1e-10,maxIter=500,out=1)-> bicgstb(A,b,M1=identity,tol=tol,maxIter=maxIter,out=out)\ntimes = zeros(length(N),3)\nfor j=1:2\n\tfor k=1:length(N)\n\t\tAinvs = (getJuliaSolver(), getMUMPSsolver(), ConvDiffMIPDECO.getBICGSTB(out=1))\n\n\tnk      = [N[k];N[k]]\n\tMk  = getRegularMesh(domain,nk)\n\txck = getCellCenteredGrid(Mk)\n\n\tpFork   = getConvDiffParam(Mk,V,sig=sig,gd=u,gn=ux,bc=bc,Ainv=Ainvs[j])\n\n\tdobsk,pFork = getData(f(xck), pFork)\n\n\tutruek = u(xck)\n\ttimes[k,j]= @elapsed begin\n\t\terr[k] = norm(pFork.Fields - utruek,Inf)/norm(utruek,Inf)\n\tend\n\tprintln(\"err[$k] = $(err[k])\")\nend\n@test all(abs.(diff(log2.(err))).>0.8)\nend\n", "meta": {"hexsha": "4693106d94b2e677a84463ca1dbb0cb845d2adcd", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testConvDiff2D.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": "test/testConvDiff2D.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": "test/testConvDiff2D.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": 23.4, "max_line_length": 111, "alphanum_fraction": 0.6256410256, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7631908402553657}}
{"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| \u2265 |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| \u2265 |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| \u2265 |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| \u2265 |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| \u2265 |b| \u2265 |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| \u2265 |b| \u2265 |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| \u2265 |b| \u2265 |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| \u2265 |b| \u2265 |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| \u2265 |b| \u2265 |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| \u2265 |b| \u2265 |c| \u2265 |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| \u2265 |c| \u2265 |b| \u2265 |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| \u2265 |b| \u2265 |c| \u2265 |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| \u2265 |c| \u2265 |b| \u2265 |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": "using BigCombinatorics\nusing Test\n\n@test Fibonacci(10)==Fibonacci(9)+Fibonacci(8)\n\n@test Factorial(10)==big(factorial(10))\n\n@test FallingFactorial(10,3) == 10*9*8\n@test FallingFactorial(10,10) == Factorial(10)\n@test FallingFactorial(10,12) == 0\n\n@test RisingFactorial(10,3) == 10*11*12\n\n@test DoubleFactorial(9) == 9*7*5*3\n@test DoubleFactorial(10) == 10*8*6*4*2\n\n@test Catalan(12) == 208012\n\n@test Derangements(1) == 0\n@test Derangements(12) == 176214841\n\n@test MultiChoose(10,1) == 10\n@test MultiChoose(10,0) == 1\n@test MultiChoose(10,10) == 92378\n\n@test Multinomial(5,5,5) == div(Factorial(15), Factorial(5)^3)\n@test Multinomial([6,6,6,6]) == Multinomial(6,6,6,6)\n\n@test Bell(10)==115975\n@test sum(Stirling2(10,k) for k=0:10) == Bell(10)\n@test Stirling1(10,10) == 1\n@test Stirling1(10,0) == 0\n@test sum(Stirling1(10,k) for k=0:10) == 0\n\n@test IntPartitions(10) == 42\n@test IntPartitionsDistinct(10) == 10\n\n@test Euler(12) == 2702765\n\n@test PowerSum(10,3) == sum(k^3 for k=1:10)\n\n@test BigCombinatorics.cache_clear(Fibonacci)\n\n@test sum(Eulerian(10,k) for k=1:10) == Factorial(10)\n", "meta": {"hexsha": "60a0d3b9d9acfcb0f773581720464c49e1edab9d", "size": 1083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 24.0666666667, "max_line_length": 62, "alphanum_fraction": 0.6879039705, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7631908337894198}}
{"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 (\u03b2|\u03c3^2 ~ MvNormal, \u03c3^2 ~ InverseGamma)\n\n    Inputs\n    ------\n    y:    data, independent variable (n vector)\n    X:    data, dependent variables (n * k matrix)\n    \u03b20:   mean of conditional prior (multivariate normal \u03b20|\u03c3^2 ~ MvNormal) for coefficients\n    A0:   precision matrix (inverse of \u03a3) of conditional prior for coefficients\n    \u03bd0:   shape parameter of prior for variance of error term\n    \u03bb0:   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_\u03b2: vector of marginal posterior for each coefficients (single \u03b2|D ~ TDist)\n    posterior_\u03c32: posterior for variance of error term (\u03c3^2|D ~ InverseGamma)\n\"\"\"\nfunction regression_stats(y, X, \u03b20, A0, \u03bd0, \u03bb0, prob)\n    XX = X' * X\n    Xy = X' * y\n    # @time XX \\ Xy # fast and efficient\n    # @time inv(XX) * Xy\n    \u03b2_ols = XX \\ Xy # OLS estimator\n    A_star = XX + A0\n    \u03b2_star = A_star \\ (Xy + A0 * \u03b20)\n    C_star = inv(inv(XX) + inv(A0))\n    \u03bd_star = size(y)[1] + \u03bd0\n    ssr = sum((y - X * \u03b2_ols).^2) # SSR sum of squared residual \u6b8b\u5dee\u4e8c\u4e57\u548c\n    # @time (\u03b20 - \u03b2_ols)' * C_star * (\u03b20 - \u03b2_ols)\n    # @time dot(\u03b20 - \u03b2_ols, C_star, \u03b20 - \u03b2_ols) # faster\n    \u03bb_star = ssr + dot(\u03b20 - \u03b2_ols, C_star, \u03b20 - \u03b2_ols) + \u03bb0\n    H_star = (\u03bb_star / \u03bd_star) * inv(A_star)\n    h_star = diag(sqrt(H_star))\n\n    marginal_posterior_\u03b2 = LocationScale.(\u03b2_star, h_star, TDist(\u03bd_star)) # broadcasting through coefficients\n    sd_\u03b2 = std.(marginal_posterior_\u03b2)\n    ci_\u03b2_upper = quantile.(marginal_posterior_\u03b2, prob - (1-prob)/2)\n    ci_\u03b2_lower = quantile.(marginal_posterior_\u03b2, (1-prob)/2)\n    # ci_\u03b2 = [ci_\u03b2_lower, ci_\u03b2_upper]\n    stats_\u03b2 = [\u03b2_star \u03b2_star \u03b2_star sd_\u03b2 ci_\u03b2_lower ci_\u03b2_upper]\n\n    posterior_\u03c32 = InverseGamma(\u03bd_star/2, \u03bb_star/2)\n    mean_\u03c32 = mean(posterior_\u03c32)\n    median_\u03c32 = median(posterior_\u03c32)\n    mode_\u03c32 = mode(posterior_\u03c32)\n    sd_\u03c32 = std(posterior_\u03c32)\n    ci_\u03c32_upper = quantile(posterior_\u03c32, prob - (1-prob)/2)\n    ci_\u03c32_lower = quantile(posterior_\u03c32, (1-prob)/2)\n    # ci_\u03c32 = [ci_\u03c32_lower, ci_\u03c32_upper]\n    stats_\u03c32 = [mean_\u03c32 median_\u03c32 mode_\u03c32 sd_\u03c32 ci_\u03c32_lower ci_\u03c32_upper]\n    stats = [stats_\u03b2; stats_\u03c32]\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_\u03b2, posterior_\u03c32, \u03b2_ols\nend\n\n# Generate moc data\nn = 50\ndim = 1\nRandom.seed!(99)\nu = rand(Normal(0, 0.7), n) # true value \u03c3^2 = 0.49\nx = rand(Uniform(-sqrt(3.0), sqrt(3.0)), n, dim) # x generated from Uniform[-\u221a3, \u221a3]\nX = [ones(n) x] # dependent variable matrix with ones\n\u03b2 = Vector(1:1:dim+1) # true coefficients\ny = X*\u03b2 + u # true data generating process\n\n\n# set prior\nk = size(X, 2)\n\u03b20 = zeros(k)\n\u03c40 = 0.2 # no ridge penalty ... \u03c40 = Inf ?\n\n# \u03c40 = 0.001\n# \u03c40 = 0.01\n# \u03c40 = 0.1\n# \u03c40 = 1\n# \u03c40 = 10\n# \u03c40 = 100\n# \u03c40 = 1000\n\nA0 = \u03c40 * I # Identity matrix\n\u03bd0 = 5.0\n\u03bb0 = 7.0\nH0 = (\u03bb0 / \u03bd0) * 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\u306e\u5bfe\u89d2\u6210\u5206\nmarginal_prior_\u03b2 = LocationScale.(\u03b20, h0, TDist(\u03bd0)) # broadcasting through coefficients\nprior_\u03c32 = InverseGamma(\u03bd0/2, \u03bb0/2)\n\n# calculate posterior\nprob = 0.95\nresults, marginal_posterior_\u03b2, posterior_\u03c32, \u03b2_ols = regression_stats(y, X, \u03b20, A0, \u03bd0, \u03bb0, prob)\nprint(\"$results\\n\")\n\n# Visualize Posterior\nplots = []\n\nfor i = 1:k\n    label_prior = @sprintf(\"marginal prior: T(\u03bd=%.1f, \u03bc=%.1f, \u03c3^2=%.1f)\", params(params(marginal_prior_\u03b2[i])[3])[1], params(marginal_prior_\u03b2[i])[1], params(marginal_prior_\u03b2[i])[2])\n    p = plot(marginal_prior_\u03b2[i], linestyle=:dash, label=label_prior, xlims=(0.0, 3.0), ylims=(0.0, 4.0), xlabel=@sprintf(\"\u03b2%d\", i), ylabel=\"Probability Density\")\n    label_posterior = @sprintf(\"marginal posterior: T(\u03bd=%.1f, \u03bc=%.1f, \u03c3^2=%.1f)\", params(params(marginal_posterior_\u03b2[i])[3])[1], params(marginal_posterior_\u03b2[i])[1], params(marginal_posterior_\u03b2[i])[2])\n    plot!(marginal_posterior_\u03b2[i], linestyle=:solid, label=label_posterior)\n    push!(plots, p)\nend\n\nlabel_prior = @sprintf(\"prior: InverseGamma(\u03b1=%.1f, \u03b8=%.1f)\", params(prior_\u03c32)[1], params(prior_\u03c32)[2])\np = plot(prior_\u03c32, 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(\u03b1=%.1f, \u03b8=%.1f)\", params(posterior_\u03c32)[1], params(posterior_\u03c32)[2])\nplot!(posterior_\u03c32, 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 * \u03b2, label=(@sprintf(\"True: y = %.d + %.dx\", \u03b2[1], \u03b2[2])))\nplot!(x, X * \u03b2_ols, label=(@sprintf(\"OLS: y = %.5f + %.5fx\", \u03b2_ols[1], \u03b2_ols[2])))\n\u03b2_star = results[:, \"Mean\"][1:k]\nplot!(x, X * \u03b2_star, label=(@sprintf(\"Bayes: y = %.5f + %.5fx (\u03c40=%.2f, Ridge)\", \u03b2_star[1], \u03b2_star[2], \u03c40)))\n\n# significance test on coefficients H0: \u03b2j = 0, H1: \u03b2j \u2260 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    \u03b2_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_\u03b2, marginal_prior_\u03b2, 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 # \u03a6(x'\u03b2)\nplot(normcdf.(Vector(-10:0.1:10)))\n# probit function, inverse-cdf of normal distribution # \u03a6^{-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\u03b2 = Vector([0.0, 0.5, -0.5]) # true coefficients\n# V = X * \u03b2 # representative utility, # utility (latent variable) y_star = U = X\u03b2 + \u03f5 = V + \u03f5\np = normcdf.(X * \u03b2) # probability (\u3059\u308b\u78ba\u7387)\ny = rand.(Bernoulli.(p)) # observable choice 0 or 1\n\n# set prior, \u03b2 ~ MvNormal(\u03b20, A0), no \u03c3\u00b2\nn, k = size(X)\n\u03b20 = zeros(k)\nA0 = 0.01 * I\n\n@model function probit_model(X, y)\n    # Set the priors only for \u03b2.\n    \u03b2 ~ MvNormal(\u03b20, 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, :]' * \u03b2))\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\u03b2_chn = chn[n_tune+1:n_draws, :, :] # delete initial and exclude odd (hamiltonian bluh bluh) chain \n\u03b2_chn = group(\u03b2_chn, :\u03b2)\n\nsummarize(\u03b2_chn)\nquantile(\u03b2_chn)\nplot(\u03b2_chn)\n\n# Marginal Effect\n\"\"\"\nMarginal Effect of probit regression for continuous variable\n\n\u2202Pr(Y=1|X)/\u2202X_j = \u2202Pr(\u03a6(X\u03b2))/\u2202X_j \n                = \u03d5(X\u03b2)\u03b2_j, where \u03d5() is standard normal pdf\n\nThe marginal effect on X_j depends on \u03b2_j, X_j and other \u03b2 and X. Therefore, \n\n    \u03b2_chn:          random drawed \u03b2\n    \u03b2_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 \u03b2, ((n_draws - n_tune) * n_chains) matrix\n\"\"\"\nfunction marginal_effect_probit(\u03b2_chn, \u03b2_interest, x)\n    \u03b2_rand = get_params(\u03b2_chn).\u03b2 # get random value\n    \u03b2_rand_interest = \u03b2_chn[\u03b2_interest].data\n    dydxs = []\n    for which_chain = chains(\u03b2_chn)\n        \u03b2_rand_single_chain = reduce(hcat, [\u03b2_rand[j].data[:, which_chain] for j=1:length(\u03b2_rand)])\n        \u03b2_rand_interest_single_chain = \u03b2_rand_interest[:, which_chain]\n        dydx = normpdf.(\u03b2_rand_single_chain * x) .* \u03b2_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(\u03b2_chn, Symbol(\"\u03b2[2]\"), X[100, :])\ndensity(rand_margins)\n\n\"\"\"\nAverage Marginal Effect of all sample.\n\"\"\"\nfunction marginal_effect_probit_mae(\u03b2_chn, \u03b2_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.((\u03b2_chn,), (\u03b2_interest,), [r for r in eachrow(X)]))\nend\n\nrand_mae = marginal_effect_probit_mae(\u03b2_chn, Symbol(\"\u03b2[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(\u03b2_chn::Chains, \u03b2_interest::Symbol, x_interest_theoritical::Vector; at_mean::Bool=false, ci_p::Float64=0.95)\n    interest_dim = findall(x -> x == \u03b2_interest, names(\u03b2_chn))\n    other_dim = findall(x -> x != \u03b2_interest, names(\u03b2_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(\u03b2_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.((\u03b2_chn,), (\u03b2_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.((\u03b2_chn,), (\u03b2_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\", \u03b2_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(\u03b2_chn, Symbol(\"\u03b2[2]\"), x_hypo, at_mean=false)\nplot_marginal_effect(\u03b2_chn, Symbol(\"\u03b2[2]\"), x_hypo, at_mean=true)\nplot_marginal_effect(\u03b2_chn, Symbol(\"\u03b2[2]\"), x_hypo, at_mean=true, ci_p=0.5)\n\nplot_marginal_effect(\u03b2_chn, Symbol(\"\u03b2[3]\"), x_hypo, at_mean=false)\nplot_marginal_effect(\u03b2_chn, Symbol(\"\u03b2[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 \u2264 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": "# Tests for Cost H\u00f6lder DEA Models\n@testset \"CostH\u00f6lderDEAModel\" begin\n\n    # Test using Book data\n    X = [2 2; 1 4; 4 1; 4 3; 5 5; 6 1; 2 5; 1.6 8];\n    Y = [1; 1; 1; 1; 1; 1; 1; 1];\n    W = [1 1; 1 1; 1 1; 1 1; 1 1; 1 1; 1 1; 1 1];\n\n    # Cost H\u00f6lder L1\n    costholderl1 = deacostholder(X, Y, W, l = 1)\n\n    @test typeof(costholderl1) == CostHolderDEAModel\n\n    @test nobs(costholderl1) == 8\n    @test ninputs(costholderl1) == 2\n    @test noutputs(costholderl1) == 1\n    @test ismonetary(costholderl1) == false\n\n    @test efficiency(costholderl1) == efficiency(costholderl1, :Economic)\n    @test efficiency(costholderl1, :Economic)   \u2248 [0.0; 1.0; 1.0; 3.0; 6.0; 3.0; 3.0; 5.6]\n    @test efficiency(costholderl1, :Technical)  \u2248 [0.0; 0.0; 0.0; 2.0; 4.0; 0.0; 1.0; 0.6]\n    @test efficiency(costholderl1, :Allocative) \u2248 [0.0; 1.0; 1.0; 1.0; 2.0; 3.0; 2.0; 5.0]\n    @test normfactor(costholderl1) \u2248 [1.0; 1.0; 1.0; 1.0; 1.0; 1.0; 1.0; 1.0]\n    \n    # With monetary = true\n    costholderl1mom = deacostholder(X, Y, W, l = 1, monetary = true)\n\n    @test ismonetary(costholderl1mom) == true\n\n    @test efficiency(costholderl1mom) \u2248 efficiency(costholderl1) .* normfactor(costholderl1)\n    @test efficiency(costholderl1mom, :Technical) \u2248 efficiency(costholderl1, :Technical) .* normfactor(costholderl1)\n    @test efficiency(costholderl1mom, :Allocative) \u2248 efficiency(costholderl1, :Allocative) .* normfactor(costholderl1)\n\n    # With CRS (Same result in this example)\n    costholderl1crs = deacostholder(X, Y, W, l = 1, rts = :CRS)\n\n    @test efficiency(costholderl1crs, :Economic)   \u2248 [0.0; 1.0; 1.0; 3.0; 6.0; 3.0; 3.0; 5.6]\n    @test efficiency(costholderl1crs, :Technical)  \u2248 [0.0; 0.0; 0.0; 2.0; 4.0; 0.0; 1.0; 0.6]\n    @test efficiency(costholderl1crs, :Allocative) \u2248 [0.0; 1.0; 1.0; 1.0; 2.0; 3.0; 2.0; 5.0]\n\n    # Cost H\u00f6lder L1 Weighted (weakly)\n    costholderl1weight= deacostholder(X, Y, W, l = 1, weight = true)\n\n    @test efficiency(costholderl1weight, :Economic)   \u2248 [0.0; 0.25; 0.25; 0.75; 1.2; 0.5; 0.6; 0.7]\n    @test efficiency(costholderl1weight, :Technical)  \u2248 [0.0; 0.0; 0.0; 0.625; 0.8; 0.0; 0.5; 0.375]\n    @test efficiency(costholderl1weight, :Allocative) \u2248 [0.0; 0.25; 0.25; 0.125; 0.4; 0.5; 0.1; 0.325]\n  \n    # Cost H\u00f6lder L2\n    logs, value = Test.collect_test_logs() do\n        costholderl2 = deacostholder(X, Y, W, l = 2, optimizer = DEAOptimizer(:NLP))\n\n        @test normfactor(costholderl2) \u2248 sqrt(2) .* ones(8)\n        show(IOBuffer(), costholderl2)\n    end\n     \n    # Cost H\u00f6lder L2 Weighted (weakly)\n    logs, value = Test.collect_test_logs() do\n        costholderl2weight = deacostholder(X, Y, W, l = 2, weight = true, optimizer = DEAOptimizer(:NLP))\n\n        @test normfactor(costholderl2weight) \u2248 sqrt.(sum((W .* X).^2, dims = 2))\n        show(IOBuffer(), costholderl2weight)\n    end\n\n    # Cost H\u00f6lder LInf\n    costholderlInf = deacostholder(X, Y, W, l = Inf)\n\n    @test efficiency(costholderlInf, :Economic)   \u2248 [0.0; 0.5; 0.5; 1.5; 3.0; 1.5; 1.5; 2.8]\n    @test efficiency(costholderlInf, :Technical)  \u2248 [0.0; 0.0; 0.0; 4/3; 3.0; 0.0; 1.0; 0.6]\n    @test efficiency(costholderlInf, :Allocative) \u2248 [0.0; 0.5; 0.5; 1/6; 0.0; 1.5; 0.5; 2.2]\n    @test normfactor(costholderlInf) \u2248 [2.0; 2.0; 2.0; 2.0; 2.0; 2.0; 2.0; 2.0]\n\n    # Cost H\u00f6lder LInf Weighted (weakly)\n    costholderlInfweight = deacostholder(X, Y, W, l = Inf, weight = true)\n\n    @test efficiency(costholderlInfweight, :Economic)   \u2248 [0.0; 0.2; 0.2; 3/7; 0.6; 3/7; 3/7; 7/12] \n    @test efficiency(costholderlInfweight, :Technical)  \u2248 [0.0; 0.0; 0.0; 0.4; 0.6; 0.0; 1/3; 3/8]\n    @test efficiency(costholderlInfweight, :Allocative) \u2248 [0.0; 0.2; 0.2; 1/35; 0.0; 3/7; 2/21; 5/24]\n    @test normfactor(costholderlInfweight) \u2248 [4.0; 5.0; 5.0; 7.0; 10.0; 7.0; 7.0; 9.6]\n\n    # Print\n    show(IOBuffer(), costholderl1)\n    show(IOBuffer(), costholderl1weight)\n    show(IOBuffer(), costholderlInf)\n    show(IOBuffer(), costholderlInfweight)\n\n    #\u00a0Test\u00a0errors\n    @test_throws\u00a0DimensionMismatch\u00a0deacostholder([1;\u00a02\u00a0;\u00a03],\u00a0[4\u00a0;\u00a05], [1; 1; 1], l = 1) #\u00a0 Different number of observations\n    @test_throws\u00a0DimensionMismatch deacostholder([1; 2; 3], [4; 5; 6], [1; 2; 3; 4], l = 1) # Different number of observation in prices\n    @test_throws\u00a0DimensionMismatch deacostholder([1 1; 2 2; 3 3 ], [4; 5; 6], [1 1 1; 2 2 2; 3 3 3], l = 1) # Different number of input prices and inputs\n    @test_throws\u00a0ArgumentError\u00a0deacostholder([1; 2; 3], [4; 5; 6], [1; 2; 3], l = 5) # Invalid l\n    @test_throws\u00a0ArgumentError\u00a0deacostholder([1; 2; 3], [4; 5; 6], [1; 2; 3], l = 1, rts = :Error) # Invalid returns to scale\n\nend\n", "meta": {"hexsha": "e3f20e5b0a92a829d4a93e5587df797048db96be", "size": 4593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/deacostholder.jl", "max_stars_repo_name": "joselzofio/BenchmarkingEconomicEfficiency.jl", "max_stars_repo_head_hexsha": "a54b826f0d9178eef694455bacda9bfcf5ea0132", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-12T20:00:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T20:00:49.000Z", "max_issues_repo_path": "test/deacostholder.jl", "max_issues_repo_name": "javierbarbero/BenchmarkingEconomicEfficiency.jl", "max_issues_repo_head_hexsha": "305668ab385aa5f6ce84d1d776a992ca92ebc87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-08T14:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T09:43:38.000Z", "max_forks_repo_path": "test/deacostholder.jl", "max_forks_repo_name": "joselzofio/BenchmarkingEconomicEfficiency.jl", "max_forks_repo_head_hexsha": "a54b826f0d9178eef694455bacda9bfcf5ea0132", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-07T13:57:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T13:57:14.000Z", "avg_line_length": 48.8617021277, "max_line_length": 153, "alphanum_fraction": 0.6205094709, "num_tokens": 2080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7631492012878932}}
{"text": "\nusing Distributions: Normal\n\n\"\"\"\n    MomentumHarmonicWigner(\u03c9, \u03b2)\n\nWigner distribution in a 1D harmonic potential for the momentum\n\"\"\"\nfunction MomentumHarmonicWigner(\u03c9, \u03b2)\n    \u03c3 = sqrt(Q(\u03c9, \u03b2) / \u03b2)\n    Normal(0, \u03c3)\nend\n\n\"\"\"\n    PositionHarmonicWigner(\u03c9, \u03b2)\n\nWigner distribution in a 1D harmonic potential for the position\n\"\"\"\nfunction PositionHarmonicWigner(\u03c9, \u03b2, m; centre=0)\n    \u03c3 = sqrt(Q(\u03c9, \u03b2) / \u03b2 / m) / \u03c9  \n    Normal(centre, \u03c3)\nend\n\n\"\"\"\n    VelocityHarmonicWigner(\u03c9, \u03b2, m)\n\nWigner distribution in a 1D harmonic potential for the velocity\n\"\"\"\nfunction VelocityHarmonicWigner(\u03c9, \u03b2, m)\n    \u03c3 = sqrt(Q(\u03c9, \u03b2) / \u03b2) / m\n    Normal(0, \u03c3)\nend\n\n\"Quantum corrector for the Wigner distribution\"\nfunction Q(\u03c9, \u03b2)\n    half\u03b2\u0127\u03c9 = \u03b2*\u03c9/2\n    return half\u03b2\u0127\u03c9 / tanh(half\u03b2\u0127\u03c9)\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": "cd(@__DIR__)\nPkg.activate(\"..\")\nusing Chordal\nusing JuMP, Hypatia, COSMO\nusing SparseArrays, LinearAlgebra, Random\n\nconst CD = Chordal\n\nrand_seed = 1234\nn = 200\n# optimizer = Hypatia.Optimizer\noptimizer = optimizer_with_attributes(COSMO.Optimizer, \"decompose\" => false)\n\n# min c^Tx st \u03a3F_ix_i + G \u2208 PSDCONE()\n# D is dual variable\nc, F, G, ystar, D = CD.generate_random_sdp(n, rand_seed=rand_seed)\n\n# ------------------------------------------------------\n# ------------------ Standard Form SDP -----------------\n# ------------------------------------------------------\n## Without decomposition\nm3 = Model(optimizer)\nsparse(@variable(m3, X[1:n, 1:n] in PSDCone()))\nfor i in 1:n\n    @constraint(m3, sum(F[i] .* X) - c[i] == 0)\nend\n@objective(m3, Max, -sum(G .* X))\ntime_non_chordal = @elapsed optimize!(m3)\n\nXv = value.(X)\n@info \"termination status: $(termination_status(m3))\"\n@info \"solution status: $(primal_status(m3))\"\n@info \"Optimal value: $(round(objective_value(m3), digits=3))\"\n\n\n## Chordal Setup\nm4 = Model(optimizer)\nperm, iperm, Tls, cliques = get_selectors(sparsity_pattern([F..., G]); verbose=false, ret_cliques=true)\nsp = CD.get_sparsity_pattern_from_cliques(cliques)\nsp_inds = zip(findnz(sp)[1:2]...)\nX = @variable(m4, X[i=1:n, j=1:n; (i,j) in sp_inds])\n\n# TODO: Package this up into a function?\nfor i in 1:length(c)\n    @constraint(m4, CD.tr(F[i][perm, perm], X) == c[i])\nend\n\nfor (p, cl) in enumerate(cliques)\n    len_cl = length(cl)\n    Xp = @variable(m4, [1:len_cl, 1:len_cl], base_name=\"X$p\")\n    for i in 1:len_cl, j in 1:len_cl\n        Xp[i,j] = X[cl[i], cl[j]]\n    end\n    @constraint(m4, Xp in PSDCone())\nend\n\n@objective(m4, Max, -CD.tr(G[perm, perm], X))\n\ntime_chordal = @elapsed optimize!(m4)\n@info \"termination status: $(termination_status(m4))\"\n@info \"solution status: $(primal_status(m4))\"\nmatch = objective_value(m4) \u2248 objective_value(m3)\n@info \"Optimal value: $(round(objective_value(m4), digits=3)), equals: $(match)\"\n@info \"Time with chordal is $(round(time_chordal, digits=3))s vs $(round(time_non_chordal, digits=3))s\"\n\n\nX_ = CD.reconstruct_from_sparse_varref(X, n)\n@assert maximum(X_ - X_') < 1e-8\nX_ = 0.5*(X_ + X_')\nXcomp = maxdet_completion(X_)[iperm, iperm]\n@assert sum(-G .* Xcomp) \u2248 objective_value(m4)\n", "meta": {"hexsha": "12a25d1c64e7548f034897eeed8871041998b79f", "size": 2243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sdp_standard.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/sdp_standard.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/sdp_standard.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": 31.1527777778, "max_line_length": 103, "alphanum_fraction": 0.6379848417, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7630873744610186}}
{"text": "using LinearAlgebra, ForwardDiff\nusing Convex, SCS, ECOS\n\n\"\"\"\n\tprojection onto second-order cone\n\"\"\"\nfunction \u03a0soc(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(\u03a0soc(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\u03c8 = 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, \u03c8)\n\tv' * b + \u03c8' * projection_difference(b, y) + 0.5 * projection_difference(b, y)' * projection_difference(b, y)\nend\n\nfunction r(z, \u03b8)\n\tb = z[1:2]\n\t\u03c8 = z[3:5]\n\ty = \u03b8[1]\n\tv = \u03b8[2:3]\n\n\tlb(w) = lagrangian(v, y, w, \u03c8)\n\t# l\u03c8(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\u03b8 = [y; v]\nrz(x) = r(x, \u03b8)\n\nsol = levenberg_marquardt(rz, ones(5))\nr\u03b8(x) = r(sol, x)\n\ndrdz = ForwardDiff.jacobian(rz, sol)\ndrd\u03b8 = ForwardDiff.jacobian(r\u03b8, \u03b8)\n\n# norm(drdz - drz(z, \u03b8))\n# norm(drd\u03b8 - dr\u03b8(z, \u03b8))\nrank(drdz)\n# eigen(drdz).values\n#\n# rank(drz(z, \u03b8))\n# eigen(drz(z, \u03b8)).values\n\nx1 = (-drdz \\ drd\u03b8)[1:2,:]\nx3 = (-(drdz' * drdz) \\ (drdz' * drd\u03b8))[1:2,:]\n\n\u03c1 = 1.0e-8\nx2 = (-(drdz' * drdz + \u03c1 * I) \\ (drdz' * drd\u03b8))[1:2,:]\nx4 = (-drdz' * ((drdz * drdz' + \u03c1 * I) \\ drd\u03b8))[1:2,:]\n\n# x2 = (-drz(z,\u03b8) \\ dr\u03b8(z,\u03b8))[1:2,:]\n# x4 = (-(drz(z,\u03b8)' * drz(z,\u03b8)) \\ (drz(z, \u03b8)' * dr\u03b8(z, \u03b8)))[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(\u03b1,\u03b8)\n\nThe *Gamma distribution* with shape parameter `\u03b1` and scale `\u03b8` 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    \u03b1::Float64\n    \u03b8::Float64\n\n    function Gamma(\u03b1::Real, \u03b8::Real)\n        @check_args(Gamma, \u03b1 > zero(\u03b1) && \u03b8 > zero(\u03b8))\n        new(\u03b1, \u03b8)\n    end\n    function Gamma(\u03b1::Real)\n        @check_args(Gamma, \u03b1 > zero(\u03b1))\n        new(\u03b1, 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.\u03b1\nscale(d::Gamma) = d.\u03b8\nrate(d::Gamma) = 1.0 / d.\u03b8\n\nparams(d::Gamma) = (d.\u03b1, d.\u03b8)\n\n\n#### Statistics\n\nmean(d::Gamma) = d.\u03b1 * d.\u03b8\n\nvar(d::Gamma) = d.\u03b1 * d.\u03b8^2\n\nskewness(d::Gamma) = 2.0 / sqrt(d.\u03b1)\n\nkurtosis(d::Gamma) = 6.0 / d.\u03b1\n\nfunction mode(d::Gamma)\n    (\u03b1, \u03b8) = params(d)\n    \u03b1 >= 1.0 ? \u03b8 * (\u03b1 - 1.0) : error(\"Gamma has no mode when shape < 1.0\")\nend\n\nfunction entropy(d::Gamma)\n    (\u03b1, \u03b8) = params(d)\n    \u03b1 + lgamma(\u03b1) + (1.0 - \u03b1) * digamma(\u03b1) + log(\u03b8)\nend\n\nmgf(d::Gamma, t::Real) = (1.0 - t * d.\u03b8)^(-d.\u03b1)\n\ncf(d::Gamma, t::Real) = (1.0 - im * t * d.\u03b8)^(-d.\u03b1)\n\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns Gamma gamma \u03b1 \u03b8\n\ngradlogpdf(d::Gamma, x::Float64) =\n    insupport(Gamma, x) ? (d.\u03b1 - 1.0) / x - 1.0 / d.\u03b8 : 0.0\n\nrand(d::Gamma) = StatsFuns.Rmath.gammarand(d.\u03b1, d.\u03b8)\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(\u03b1*I,B,C)  or  X = sylvc(\u03b1,B,C)\n\nSolve the matrix equation `X(\u03b1I+B)  = C`.\n\n    X = sylvc(A,\u03b2*I,C)  or  X = sylvc(A,\u03b2,C)\n\nSolve the matrix equation `(A+\u03b2I)X = C`.\n\n    X = sylvc(\u03b1*I,\u03b2*I,C)  or  sylvc(\u03b1,\u03b2,C)\n\nSolve the matrix equation `(\u03b1+\u03b2)X = C`.\n\n    x = sylvc(\u03b1,\u03b2,\u03b3)\n\nSolve the equation `(\u03b1+\u03b2)x = \u03b3`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> X = sylvc(A, B, C)\n2\u00d72 Array{Float64,2}:\n -4.46667   1.93333\n  3.73333  -1.8\n\njulia> A*X + X*B - C\n2\u00d72 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\u2013826, 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+\u03b1) = C or (\u03b1+\u03b2)X = C\nsylvc(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*I+B)\n# solve (A+\u03b2)X = C\nsylvc(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A+B*I)\\C\n# solve (\u03b1+\u03b2)X = C\nsylvc(A::Union{Real,Complex},B::Union{Real,Complex},C::AbstractMatrix) = A+B == 0 ? throw(SingularException(1)) : C/(A+B)\n# solve (\u03b1+\u03b2)x = \u03b3\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(\u03b1*I,B,C)  or  X = sylvd(\u03b1,B,C)\n\nSolve the matrix equation `X(\u03b1B+I)  = C`.\n\n    X = sylvd(A,\u03b2*I,C)   or  X = sylvd(A,\u03b2,C)\n\nSolve the matrix equation `(\u03b2A+I)X = C`.\n\n    X = sylvd(\u03b1*I,\u03b2*I,C)  or  X = sylvd(\u03b1,\u03b2,C)\n\nSolve the matrix equation `(\u03b1\u03b2+1)X = C`.\n\n    x = sylvd(\u03b1,\u03b2,\u03b3)\n\nSolve the equation `(\u03b1\u03b2+1)x = \u03b3`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n   \njulia> X = sylvd(A, B, C)\n2\u00d72 Array{Float64,2}:\n -2.46667  -2.73333\n  2.4       1.86667\n\njulia> A*X*B + X - C\n2\u00d72 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\u2013826, 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(\u03b1B+I) = C or X(\u03b1\u03b2+1) = C\nsylvd(A::Union{Real,Complex,UniformScaling},B::Union{AbstractMatrix,UniformScaling},C::AbstractMatrix) = C/(A*B+I)\n# solve (A\u03b2+I)X = C\nsylvd(A::AbstractMatrix,B::Union{Real,Complex,UniformScaling},C::AbstractMatrix) = (A*B+I)\\C\n# solve (\u03b1\u03b2+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 (\u03b1\u03b2+1)x = \u03b3\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-\u03bbC` and `D+\u03bbB` 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,\u03b3*I,E)  or  X = gsylv(A,B,\u03b3,E)\n\nSolve the generalized Sylvester matrix equation `AXB +\u03b3X = E`.\n\n    X = gsylv(A,B,\u03b3*I,D,E)  or  X = gsylv(A,B,\u03b3,D,E)\n\nSolve the generalized Sylvester matrix equation `AXB +\u03b3XD = E`.\n\n    X = gsylv(A,B,C,\u03b4*I,E)  or  X = gsylv(A,B,C,\u03b4,E)\n\nSolve the generalized Sylvester matrix equation `AXB +CX\u03b4 = E`.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2\u00d72 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2\u00d72 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> X = gsylv(A, B, C, D, E)\n2\u00d72 Array{Float64,2}:\n -0.52094   -0.0275792\n -0.168539   0.314607\n \njulia> A*X*B + C*X*D - E\n2\u00d72 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+\u03b3X = 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+\u03b3X\u03b4 = 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+\u03b3XD = 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\u03b4 = 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-\u03bbD` and `-B+\u03bbE` must be regular and must not have common eigenvalues.\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2\u00d72 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2\u00d72 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2\u00d72 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\u00d72 Array{Float64,2}:\n  1.388  -1.388\n -0.892   0.892\n\njulia> Y\n2\u00d72 Array{Float64,2}:\n -1.788  0.192\n  0.236  0.176\n\njulia> A*X + Y*B - C\n2\u00d72 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\u00d72 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-\u03bbD` and `-B+\u03bbE` must be regular and must not have common eigenvalues.\n\n# Example\n```jldoctest\njulia> A = [3. 4.; 5. 6.]\n2\u00d72 Array{Float64,2}:\n 3.0  4.0\n 5.0  6.0\n\njulia> B = [1. 1.; 1. 2.]\n2\u00d72 Array{Float64,2}:\n 1.0  1.0\n 1.0  2.0\n\njulia> C = [-1. -2.; 2. -1.]\n2\u00d72 Array{Float64,2}:\n -1.0  -2.0\n  2.0  -1.0\n\njulia> D = [1. -2.; -2. -1.]\n2\u00d72 Array{Float64,2}:\n  1.0  -2.0\n -2.0  -1.0\n\njulia> E = [1. -1.; -2. 2.]\n2\u00d72 Array{Float64,2}:\n  1.0  -1.0\n -2.0   2.0\n\njulia> F = [1. -1.; -2. 2.]\n2\u00d72 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\u00d72 Array{Float64,2}:\n  2.472  -1.648\n -1.848   1.232\n\njulia> Y\n2\u00d72 Array{Float64,2}:\n -0.496  -0.336\n  0.264   0.824\n\njulia> A*X + D*Y - C\n2\u00d72 Array{Float64,2}:\n  4.44089e-16  0.0\n -3.55271e-15  1.55431e-15\n \njulia> X*B + Y*E - F\n2\u00d72 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\u2013826, 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\u2013826, 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\u2013826, 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\u2013826, 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-\u03bbC` and `D+\u03bbB` 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 \u2013 CXD = E and\n       (YA \u2013 DZ, YC\u2013 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\u2013826, 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-\u03bbC and D+\u03bbB 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-\u03bbC and D+\u03bbB 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-\u03bbC and D+\u03bbB 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-\u03bbC and D+\u03bbB 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 \u2013 CXD = E and\n       (YA \u2013 DZ, YC\u2013 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\u2013826, 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-\u03bbC and D+\u03bbB 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-\u03bbC and D+\u03bbB 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-\u03bbC and D+\u03bbB 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-\u03bbC and D+\u03bbB 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-\u03bbD` and `-B+\u03bbE` 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-\u03bbD` and `-B+\u03bbE` 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* `\u03f5::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\u03f5 = 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* `\u03f5::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\u03f5 = 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* `\u03f5::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\u03f5 = 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* `\u03f5::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\u03f5 = 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* `\u03f5::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\u03f5 = 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": "function fibonacci(x::Int)\n  if x <= 1\n      return x\n  else\n      return fibonacci(x - 1) + fibonacci(x - 2)\n  end\n  return 0\nend\n", "meta": {"hexsha": "df7e28194abc6d1f3d8e4a272da101895dd2160c", "size": 131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Mathematics/fibonacci/Julia/fibonacci.jl", "max_stars_repo_name": "iabhimanyu/Algorithms", "max_stars_repo_head_hexsha": "adefcd165e591d2338be8fc8a62629ff072620dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 715, "max_stars_repo_stars_event_min_datetime": "2018-10-01T21:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T09:14:10.000Z", "max_issues_repo_path": "Mathematics/fibonacci/Julia/fibonacci.jl", "max_issues_repo_name": "iabhimanyu/Algorithms", "max_issues_repo_head_hexsha": "adefcd165e591d2338be8fc8a62629ff072620dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157, "max_issues_repo_issues_event_min_datetime": "2018-10-01T20:53:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T07:00:58.000Z", "max_forks_repo_path": "Mathematics/fibonacci/Julia/fibonacci.jl", "max_forks_repo_name": "iabhimanyu/Algorithms", "max_forks_repo_head_hexsha": "adefcd165e591d2338be8fc8a62629ff072620dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1225, "max_forks_repo_forks_event_min_datetime": "2018-10-01T20:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T04:00:27.000Z", "avg_line_length": 14.5555555556, "max_line_length": 48, "alphanum_fraction": 0.5877862595, "num_tokens": 45, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7630873565183288}}
{"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 = [\"\u2192\", \"\u2191\", \"\u2190\", \"\u2193\"] # 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 \u00f7 2 + 1, isodd(ord) ? ord \u00f7 2 + 1 : ord \u00f7 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 ? \" \u2219 \" : \"   \" 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": "using LinearAlgebra\n\n## Iterate Riccati difference equation\nfunction Riccati(A_tld,B_tld,R,Q_tld,tol)\n\n    P = ones(size(A_tld)[2],size(A_tld)[1]);\n    F = ones(size(R)[1],size(W)[1]);\n\n    pDiff = 10;\n    fDiff = 10;\n    iter = 0;\n\n    while pDiff >= tol.*opnorm(P,1) && fDiff > tol.*opnorm(F,1)\n        A = R+B_tld'*P*B_tld;\n\n        P1 = Q_tld+A_tld'*P*A_tld-A_tld'*P*B_tld*(A\\B_tld')*P*A_tld;\n        pDiff = opnorm(P1-P,1);\n\n        F1 = A\\B_tld'*P*A_tld;\n        fDiff = opnorm(F1-F,1);\n\n        iter = iter + 1;\n\n        P = copy(P1)\n        F = copy(F1)\n    end\n\n    return P,F\n\nend\n", "meta": {"hexsha": "cdb89fc1b3fbbf2d110021ea130c9d6c78bf4e6a", "size": 591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ellen/HW1/Riccati.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/Riccati.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/Riccati.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": 19.064516129, "max_line_length": 68, "alphanum_fraction": 0.5363790186, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075733703925, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7630532374144352}}
{"text": "##### ----- Power Law ----- #####\n# Calculate probability density for a residence time \u03c4 given \u03b1 of power law, \n# minimum and maximum residence times \u03c4\u208b and \u03c4\u208a\nfunction E_powerLaw(\u03c4, (q, \u03b1, \u03c4\u208b, \u03c4\u208a, k)) # Note - destructured arguments so that all pdfs have \u03c4 as first argument and p as second\n    if(\u03c4 < \u03c4\u208b)\n        0\n    elseif(\u03c4 > \u03c4\u208a)\n        0\n    else\n        ((\u03c4^(-\u03b1) - \u03c4\u208a^(-\u03b1))*(-\u03b1+1.0)/(\u03c4\u208a^(-\u03b1+1.0)-\u03c4\u208b^(-\u03b1+1.0)-\u03c4\u208a^(-\u03b1)*(\u03c4\u208a - \u03c4\u208b)*(1.0-\u03b1)))\n    end\n    # else\n    #     (\u03b1-1)*\u03c4\u208b^(\u03b1-1)*\u03c4^(-\u03b1)\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(\u03b1, \u03c4\u208b, \u03c4\u208a, V_frac)\n    V_frac/quadgk(\u03c4 -> (\u03c4\u208a^(-\u03b1+1) - \u03c4^(-\u03b1+1)- (\u03c4\u208a^(-\u03b1)*(\u03c4\u208a-\u03c4)*(-\u03b1+1)))/(\u03c4\u208a^(-\u03b1+1) - \u03c4\u208b^(-\u03b1+1)- (\u03c4\u208a^(-\u03b1)*(\u03c4\u208a-\u03c4\u208b)*(-\u03b1+1))), \u03c4\u208b, \u03c4\u208a)[1]\n    # V_frac/quadgk(\u03c4 -> (-\u03c4^(-\u03b1+1))/(- \u03c4\u208b^(-\u03b1+1)), \u03c4\u208b, 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": "function Sigmoid(x)\r\n   g=1 ./ (1 .+exp.(-x))\r\n    return g\r\nend\r\n\r\nfunction SigmoidGradient(x)\r\n\r\n    g=Sigmoid(x).*(1 .- Sigmoid(x))\r\n    return g\r\n\r\nend\r\n", "meta": {"hexsha": "b91fedc2c86e8b05c7a50f1148d756d4f9fecc5f", "size": 157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Sigmoid.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/Sigmoid.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/Sigmoid.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": 13.0833333333, "max_line_length": 36, "alphanum_fraction": 0.5414012739, "num_tokens": 51, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813451206063, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7630516648516291}}
{"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\u00d72 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# \u2554\u2550\u2561 f1d0ed8f-bfd3-4210-84fd-f189bba6ebf9\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(title = \"Contents\")\nend\n\n# \u2554\u2550\u2561 08eadc12-f8e9-11eb-1094-b7adc6936aa1\nmd\"\"\"\n# Permutations\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 524dee4b-6687-44de-af79-b99d3724f9ac\n3 * 4\n\n# \u2554\u2550\u2561 a16202d3-406a-4b43-807e-b60c673d4132\n\"3\" * \"4\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 acf690f4-b65b-4576-9145-1e894d5342f2\nisfour(x::String) = (lowercase(x) \u2208 [\"4\", \"four\"])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 29b729bb-cd1a-4ee1-ae2e-26b55ce744a4\nisfour(x::Any) = false\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03c3 = Permutation([2,3,1,5,4])\n```\n\nIts field will also be accessible through dot notation by:\n```julia\n\u03c3.image\n```\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2208 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# \u2554\u2550\u2561 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 \u2208 imagevals])\n\t\n\t# See section Evaluating a Permutation as a function below\n\tmaxarg(\u03c3::Permutation) = length(\u03c3.image)\n\t(\u03c3::Permutation)(x::Int64) = x \u2208 1:maxarg(\u03c3) ? \u03c3.image[x] : x\n\t\n\t# See section Generating groups with Permutations\n\timport Base.:(==)\n\t==(\u03c3::Permutation, \u03c4::Permutation) = (\u03c3.image == \u03c4.image)\n\t\n\tnothing\nend\n\n# \u2554\u2550\u2561 1d56249e-d86a-4d1e-b7d2-6d63a621bfa8\nisfour(x::Number) = (x == 4)\n\n# \u2554\u2550\u2561 9ab255ff-b40a-4f16-bed8-fe14e4495502\nisfour(4.0)\n\n# \u2554\u2550\u2561 98750bd0-84bd-4cb1-900b-9ee26142e4ec\nisfour(\"Twelve\")\n\n# \u2554\u2550\u2561 4e4508db-47c0-462f-9cec-93e52bbffd7c\nisfour([4])\n\n# \u2554\u2550\u2561 de16f61d-853a-43ed-adf0-fb77ea3c8f4a\n\u03c3 = Permutation(4,5,1,3,2); \u03c3.image\n\n# \u2554\u2550\u2561 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(\u03c3::Permutation)(x::Int64) = \u03c3.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(\u03c3::Permutation) = length(\u03c3.image)\n(\u03c3::Permutation)(x::Int64) = x \u2208 1:maxarg(\u03c3) ? \u03c3.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 `\u03c3` defined above\n\"\"\"\n\n# \u2554\u2550\u2561 ff8ab6b4-34de-44eb-b98a-2f5e0f1c48fc\n\u03c3(4)\n\n# \u2554\u2550\u2561 5ce89616-326b-4404-9f2f-707c91835fa3\nmaxarg(\u03c3)\n\n# \u2554\u2550\u2561 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 `\u03c3` would look like `Permutation([4, 5, 1, 3, 2])`). This isn\u2019t 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# \u2554\u2550\u2561 ee9d45f3-0a25-47f6-8445-8ba733c3a8f6\nfunction orbit(\u03c3::Permutation, x::Int64)\n    orb = [x]\n    y = \u03c3(x)\n    while y != x\n        push!(orb,y)\n        y = \u03c3(y)\n    end\n    return orb\nend\n\n# \u2554\u2550\u2561 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(\u03c3)` are yet to be added to the decomposition. I will iterate until this vector is entirely false\n```julia\nunaccounted = trues(maxarg(\u03c3))\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(\u03c3,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# \u2554\u2550\u2561 e4ce9583-5c18-4df7-a5fb-a46670fe40af\nfunction dcd(\u03c3::Permutation)\n    decomp = Vector{Int64}[]\n    unaccounted = trues(maxarg(\u03c3))\n    while any(unaccounted)\n        x = findfirst(unaccounted)\n        xorbit = orbit(\u03c3,x)\n        unaccounted[xorbit] .= false\n        length(xorbit) > 1 && push!(decomp,xorbit)\n    end\n    return decomp\nend\n\n# \u2554\u2550\u2561 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 \u2208 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 \u2208 x]... , \")\" ) for x \u2208 dcd(\u03c3)]..., \"\")\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 `\u03b9`.\n```julia\ntoprint == \"\" && (toprint = \"\u03b9\")\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# \u2554\u2550\u2561 7a96d2c8-aa9c-405f-b34f-1f3c7c53b6c6\nbegin\n\timport Base.show\n\t\n\tfunction show(io::IO,\u03c3::Permutation)\n\t    toprint = *([ *( \"( \", [\"$y \" for y \u2208 x]... , \")\" ) for x \u2208 dcd(\u03c3)]..., \"\")\n    \ttoprint == \"\" && (toprint = \"\u03b9\")\n\t    print(io, toprint)\n\tend\nend\n\n# \u2554\u2550\u2561 12346644-107b-4c43-aaca-3e404fecc8b3\nmd\"\"\"\nPermutations now have a much more aesthetic and useful display style:\n\"\"\"\n\n# \u2554\u2550\u2561 0afa030a-58ad-44f6-a10f-0ae3baabe6f8\n\u03c3\n\n# \u2554\u2550\u2561 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 `\u03b9` (mirroring the way it is displayed by `show`), and is given by:\n\"\"\"\n\n# \u2554\u2550\u2561 068a9d15-ce46-4aa5-9c13-3f79e70b0eda\nconst \u03b9 = Permutation(1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d614739d-b22f-4991-9722-e8371732bf4b\nbegin\n\timport Base.one\n\tone(::Permutation) = \u03b9\n\tone(::Type{Permutation}) = \u03b9\nend\n\n# \u2554\u2550\u2561 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 `\u2218`. 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\u2218(f) = f\n\u2218(f, g) = ComposedFunction(f, g)\n\u2218(f, g, h...) = \u2218(f \u2218 g, h...)\n```\n\nHence, my methods for `\u2218` are:\n\"\"\"\n\n# \u2554\u2550\u2561 8f925ec6-7cd8-49fe-a467-807711b3425b\nbegin\n\timport Base.\u2218\n\t\u2218(\u03c3::Permutation) = \u03c3\n\t\u2218(\u03c3::Permutation, \u03c4::Permutation) =\n        Permutation([\u03c3(\u03c4(x)) for x \u2208 1:max(maxarg(\u03c3),maxarg(\u03c4))])\n\t\u2218(\u03c3::Permutation, \u03c4::Permutation, \u03c5::Permutation...) = \u2218(\u03c3 \u2218 \u03c4, \u03c5...)\nend\n\n# \u2554\u2550\u2561 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(\u03c3)` in the image vector and let that be the image of the new permutation, which is done by:\n\"\"\"\n\n# \u2554\u2550\u2561 0e710b07-b5db-4ea7-986b-8eb7fc0946b1\nbegin\n\timport Base.inv\n\tinv(\u03c3::Permutation) = Permutation([findfirst(\u03c3.image .== x) for x \u2208 1:maxarg(\u03c3)])\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 59075aa4-dd35-47af-b4d1-40e89b2e599f\nbegin\n\timport Base.^\n\n\tfunction ^(\u03c3::Permutation,n::Int64)\n\t    n == 0 && return one(Permutation)\n\t    n < 0 && ((n,\u03c3) = (-n,inv(\u03c3)))\n\t    return \u2218(fill(\u03c3,n)...)\n\tend\nend\n\n# \u2554\u2550\u2561 764fb693-f4ac-4327-93a3-2171621ad039\nmd\"\"\"\nI can now test these out:\n\"\"\"\n\n# \u2554\u2550\u2561 75e5491a-6536-44b0-a5b9-10cf7f9e5c66\n\u03b9\n\n# \u2554\u2550\u2561 9d43f21c-c60a-4bf8-b1a0-bf3b56b3a97b\n\u03c3\n\n# \u2554\u2550\u2561 b421f174-d554-47a8-a72d-4d5f3ec6ba2e\n\u03c4 = Permutation(4,5,2,3,1)\n\n# \u2554\u2550\u2561 ff82e088-aa60-49fe-bb12-fe39b0430d51\n\u03c3 \u2218 \u03c4\n\n# \u2554\u2550\u2561 7c0c4e99-ebff-409b-87f3-919a6870cccc\n\u03c3^-1\n\n# \u2554\u2550\u2561 029a0c9f-5d32-409d-b6ad-9e0d4e19e854\n\u03c4^5\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 00a61c28-230d-41b0-81ac-e2f0869d6640\ntransposition(3,4)\n\n# \u2554\u2550\u2561 32b52a58-6086-4c2f-a833-e1a7efb69d29\ntransposition(3,3)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1b10a694-a310-4a4e-9831-654e3e9691d1\nparity(\u03c3::Permutation) = (-1)^sum([iseven(length(x)) for x \u2208 dcd(\u03c3)])\n\n# \u2554\u2550\u2561 9812e6fb-9308-4c27-9d57-9fbf71474343\nparity(\u03b9)\n\n# \u2554\u2550\u2561 d69ce761-f489-4728-a19d-783b84b436a5\nparity(\u03c3)\n\n# \u2554\u2550\u2561 a6be1358-652d-4084-9c8e-f3089fb99169\nparity(\u03c4)\n\n# \u2554\u2550\u2561 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\u2019t make sense otherwise)\n```julia\nn \u2265 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 [\u03b9]\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 \u2208 1:n]...)\nreturn permutations .\u2218 transpositions\n```\n\nThe entire function is:\n\"\"\"\n\n# \u2554\u2550\u2561 c70a297d-adb7-4f70-b6bb-949a3d49d3c0\nfunction symmetricgroup(n::Int64)\n    n \u2265 1 || error(\"symmetric group must have a positive parameter\")\n    n == 1 && return [\u03b9]\n\n    permutations = vcat(fill(symmetricgroup(n-1),n)...)\n    transpositions = vcat([fill(transposition(i,n),factorial(n-1)) for i \u2208 1:n]...)\n    return permutations .\u2218 transpositions\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d546b70a-eeaa-45db-8b65-d36cb13b67f6\nfunction alternatinggroup(n::Int64)\n    S\u2099 = symmetricgroup(n)\n    return S\u2099[parity.(S\u2099) .== 1]\nend\n\n# \u2554\u2550\u2561 5dea6f25-65fe-4304-a7e7-2d4b830f4724\nsymmetricgroup(5)\n\n# \u2554\u2550\u2561 13cacc56-7fcc-4a71-9cc5-be298295939b\nalternatinggroup(5)\n\n# \u2554\u2550\u2561 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==(\u03c3::Permutation, \u03c4::Permutation) = (\u03c3.image == \u03c4.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# \u2554\u2550\u2561 3e8b7d82-1d63-4aec-8ed6-0b1f11c5cb33\nfunction generate(\u03c3s::Permutation...)\n    G = [\u03c3s...]\n    while true\n        newelements = Permutation[]\n\n        for \u03c3 \u2208 G, \u03c4 \u2208 G\n            \u03c5 = \u03c3 \u2218 \u03c4\n            \u03c5 \u2209 G && \u03c5 \u2209 newelements && push!(newelements, \u03c5)\n        end\n\n        if isempty(newelements)\n            return G\n        else\n            G = vcat(G,newelements)\n        end\n    end\nend\n\n# \u2554\u2550\u2561 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 `\u2209` uses `==` to determine whether or not `\u03c5` is an element of `G` (or `newelements`), and I have defined what `==` means for a `Permutation`, so `\u2209` will automatically work for permutations without me explicitly telling it how to.\n\nSome demonstrations of the `generate` function are shown below, with `C\u2085`, `D\u2081\u2080`, and `G` the group generated by `\u03c3` and `\u03c4`, which happens to be `S\u2085`:\n\"\"\"\n\n# \u2554\u2550\u2561 4725c3bb-a1c1-49cc-9bf7-a7e443db085c\nC\u2085 = generate(Permutation(2,3,4,5,1))\n\n# \u2554\u2550\u2561 9e84f004-fd88-4a25-bfba-0797d2df0942\nD\u2081\u2080 = generate(Permutation(2,3,4,5,1),Permutation(5,4,3,2,1))\n\n# \u2554\u2550\u2561 bd677d6a-3b42-497d-bcfb-58543dee7ebd\nG = generate(\u03c3,\u03c4)\n\n# \u2554\u2550\u2561 076885f1-61b4-4913-8530-fd65c531f419\nS\u2085 = symmetricgroup(5)\n\n# \u2554\u2550\u2561 738df784-eeb7-4d3b-b19f-6317f2459c6d\nall([g \u2208 G for g \u2208 S\u2085]) && all([g \u2208 S\u2085 for g \u2208 G])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250008eadc12-f8e9-11eb-1094-b7adc6936aa1\n# \u255f\u2500c4d2ff29-2579-4079-a6cb-29015ef5ecd2\n# \u255f\u2500db919e43-6dc8-4e53-8081-d9312446117a\n# \u2560\u2550524dee4b-6687-44de-af79-b99d3724f9ac\n# \u2560\u2550a16202d3-406a-4b43-807e-b60c673d4132\n# \u255f\u250041fc4769-5b67-4503-b1d1-2854a0d9c3a2\n# \u2560\u25501d56249e-d86a-4d1e-b7d2-6d63a621bfa8\n# \u2560\u2550acf690f4-b65b-4576-9145-1e894d5342f2\n# \u2560\u25509ab255ff-b40a-4f16-bed8-fe14e4495502\n# \u2560\u255098750bd0-84bd-4cb1-900b-9ee26142e4ec\n# \u255f\u25009f193c51-b6ea-477f-ab0e-1bc5a4be4b86\n# \u2560\u255029b729bb-cd1a-4ee1-ae2e-26b55ce744a4\n# \u2560\u25504e4508db-47c0-462f-9cec-93e52bbffd7c\n# \u255f\u2500740f8275-ee0c-4aa2-b0c1-76d46fad3ecd\n# \u255f\u250073d93917-b72e-468b-970c-f34ec6d51de4\n# \u255f\u2500c18ae801-b186-44cf-9e42-83188c4781aa\n# \u255f\u250099fe42de-2afa-409f-9416-5c7671e4d0f4\n# \u2560\u2550b9c535e5-3317-4291-9925-696bc6cb0252\n# \u2560\u2550de16f61d-853a-43ed-adf0-fb77ea3c8f4a\n# \u255f\u2500322f2dbc-f8f4-4f62-a9bb-ea6b00a333ae\n# \u2560\u2550ff8ab6b4-34de-44eb-b98a-2f5e0f1c48fc\n# \u2560\u25505ce89616-326b-4404-9f2f-707c91835fa3\n# \u255f\u25009617f0f2-1b45-418f-8818-26df1abde6cb\n# \u2560\u2550ee9d45f3-0a25-47f6-8445-8ba733c3a8f6\n# \u255f\u2500b119e9f0-b8ba-42a3-a76c-82ed2dc170a4\n# \u2560\u2550e4ce9583-5c18-4df7-a5fb-a46670fe40af\n# \u255f\u2500b2ac585a-d84a-4d19-afe5-ad6d288e847f\n# \u2560\u25507a96d2c8-aa9c-405f-b34f-1f3c7c53b6c6\n# \u255f\u250012346644-107b-4c43-aaca-3e404fecc8b3\n# \u2560\u25500afa030a-58ad-44f6-a10f-0ae3baabe6f8\n# \u255f\u25001e8659dc-27d5-429d-8431-d5cfa9006411\n# \u2560\u2550068a9d15-ce46-4aa5-9c13-3f79e70b0eda\n# \u255f\u2500b3151f52-6dd7-4f63-a158-becb5d1aec2e\n# \u2560\u2550d614739d-b22f-4991-9722-e8371732bf4b\n# \u255f\u2500363481da-d185-4846-82ab-c227e9f668f8\n# \u2560\u25508f925ec6-7cd8-49fe-a467-807711b3425b\n# \u255f\u25004552e49c-af66-4fd3-a827-28284215f4f9\n# \u2560\u25500e710b07-b5db-4ea7-986b-8eb7fc0946b1\n# \u255f\u25007c082457-980c-4961-bb10-d91b7248d0f6\n# \u2560\u255059075aa4-dd35-47af-b4d1-40e89b2e599f\n# \u255f\u2500764fb693-f4ac-4327-93a3-2171621ad039\n# \u2560\u255075e5491a-6536-44b0-a5b9-10cf7f9e5c66\n# \u2560\u25509d43f21c-c60a-4bf8-b1a0-bf3b56b3a97b\n# \u2560\u2550b421f174-d554-47a8-a72d-4d5f3ec6ba2e\n# \u2560\u2550ff82e088-aa60-49fe-bb12-fe39b0430d51\n# \u2560\u25507c0c4e99-ebff-409b-87f3-919a6870cccc\n# \u2560\u2550029a0c9f-5d32-409d-b6ad-9e0d4e19e854\n# \u255f\u2500c75f7100-778e-44c6-9d43-675d11175673\n# \u2560\u25500598e94b-a043-4106-bb7b-d032eb67be0b\n# \u2560\u255000a61c28-230d-41b0-81ac-e2f0869d6640\n# \u2560\u255032b52a58-6086-4c2f-a833-e1a7efb69d29\n# \u255f\u250084bd5d92-00eb-4e66-a1c5-c86626b8f7d2\n# \u2560\u25501b10a694-a310-4a4e-9831-654e3e9691d1\n# \u2560\u25509812e6fb-9308-4c27-9d57-9fbf71474343\n# \u2560\u2550d69ce761-f489-4728-a19d-783b84b436a5\n# \u2560\u2550a6be1358-652d-4084-9c8e-f3089fb99169\n# \u255f\u250041cf3bc2-c70c-4053-bed0-74a11f8a5ad5\n# \u2560\u2550c70a297d-adb7-4f70-b6bb-949a3d49d3c0\n# \u255f\u2500eb5640fa-0814-497c-b157-da718df1c129\n# \u2560\u2550d546b70a-eeaa-45db-8b65-d36cb13b67f6\n# \u2560\u25505dea6f25-65fe-4304-a7e7-2d4b830f4724\n# \u2560\u255013cacc56-7fcc-4a71-9cc5-be298295939b\n# \u255f\u250046eeeed1-a8e4-49cc-8d97-6ddfb1fa2b1e\n# \u2560\u25503e8b7d82-1d63-4aec-8ed6-0b1f11c5cb33\n# \u255f\u250079584487-dd19-4014-97e7-7fcc0582efa8\n# \u2560\u25504725c3bb-a1c1-49cc-9bf7-a7e443db085c\n# \u2560\u25509e84f004-fd88-4a25-bfba-0797d2df0942\n# \u2560\u2550bd677d6a-3b42-497d-bcfb-58543dee7ebd\n# \u2560\u2550076885f1-61b4-4913-8530-fd65c531f419\n# \u2560\u2550738df784-eeb7-4d3b-b19f-6317f2459c6d\n# \u255f\u2500f1d0ed8f-bfd3-4210-84fd-f189bba6ebf9\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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') = \u03c3\u00b2(1 + \u221a3|x-x'|/L)\\\\exp(- \u221a3|x-x'|/L)\n```\nwith length scale ``\u2113 = (\u2113\u2081, \u2113\u2082, \u2026)`` and signal standard deviation ``\u03c3`` where\n``L = diag(\u2113\u2081, \u2113\u2082, \u2026)``.\n\"\"\"\nmutable struct Mat32Ard{T} <: MaternARD where {T<:Real}\n    \"Inverse squared length scale\"\n    i\u21132::Vector{T}\n    \"Signal variance\"\n    \u03c32::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\u03c3::T)\n\n# Arguments\n  - `ll::Vector{Real}`: vector of length scales (given on log scale)\n  - `l\u03c3::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat32Ard(ll::Vector{T}, l\u03c3::T) where T = Mat32Ard{T}(exp.(-2 .* ll), exp(2 * l\u03c3), [])\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\u21132 = exp(-2 * hyp[1:(end-1)])\n    mat.\u03c32 = exp(2 * hyp[end])\nend\n\nget_params(mat::Mat32Ard{T}) where T = T[-log.(mat.i\u21132) / 2; log(mat.\u03c32) / 2]\nget_param_names(mat::Mat32Ard) = [get_param_names(mat.i\u21132, :ll); :l\u03c3]\nnum_params(mat::Mat32Ard) = length(mat.i\u21132) + 1\n\ncov(mat::Mat32Ard, r::Number) =\n    (s = \u221a3 * r; mat.\u03c32 * (1 + s) * exp(-s))\n\ndk_dll(mat::Mat32Ard, r::Real, wdiffp::Real) = 3 * mat.\u03c32 * wdiffp * exp(-\u221a3 * 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c693088f-7f80-4cdd-b9b5-65a50da732ac\nbegin\n    using MLCourse\n    import MLCourse: poly, Polynomial\n    MLCourse.list_notebooks(@__FILE__)\nend\n\n\n# \u2554\u2550\u2561 e1077092-f72a-42af-b6e0-a616f938cba8\nusing PlutoUI; PlutoUI.TableOfContents()\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 46827e21-0eea-4ec9-83ed-05e41dda1502\ndata1 = data_generator(seed = 1);\n\n# \u2554\u2550\u2561 6cfc32b3-40c0-4149-ba67-2ec67b3938f3\nmd\"split seed = $(@bind split_seed Slider(1:20, show_value = true))\"\n\n# \u2554\u2550\u2561 1320b9b0-d6fc-4e61-8d62-de3988b8b21d\nidxs = shuffle(MersenneTwister(split_seed), 1:500) # shuffle the indices\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 23e91f72-0124-48d4-8b53-bd5da67b7ac7\nlosses1[4]\n\n# \u2554\u2550\u2561 4461d5b0-bc9b-4c89-aa76-70524a5caa7c\nmd\"Let us repeat the process above for other splits of the data.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b3aed705-5072-4d9b-bb8f-865ac1561bf6\nbegin\n    function cross_validation_sets(idx, K)\n        n = length(idx)\n        r = n \u00f7 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# \u2554\u2550\u2561 6916273a-d116-4173-acaa-2bcac1d1753b\ncross_validation_sets(1:100, 4)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0b81c3d5-277a-4fe6-889b-550e2f83c39d\nmd\"With cross-validation we find often degree = 3 as the optimal one.\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 96b3c070-0c72-44c7-ac98-ff6cb7e82380\nmd\"The optimal degree found with cross-validation on the first 100 data points is:\"\n\n# \u2554\u2550\u2561 bae635b1-6eba-4ba4-80e9-547770612843\nargmin((x -> x.valid).(losses2_cv10))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e2658128-4053-4484-8e1e-229eceb755ab\nmd\"# Resampling Strategies with MLJ\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 967a6e08-f0e6-45b7-988b-d0df237f3ddf\nMLJ.MLJBase.train_test_pairs(CV(nfolds = 10), 1:100)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fc07009a-eeac-4c6b-9559-1e99ae68a6c3\nmd\"MLJ implements the following resampling strategies. With `Holdout` we use the validation set approach.\"\n\n# \u2554\u2550\u2561 42511b31-6d70-495e-8362-01a29143b96e\nsubtypes(ResamplingStrategy)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 59245b3e-ddfc-46c4-ba44-86ce191672ae\nreport(self_tuning_mach)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 eba90af0-bf67-48f8-8d3c-f831b4fc289a\nmd\"Have a look at the best models found for each fold:\"\n\n# \u2554\u2550\u2561 c8d26ab6-86ec-4b37-9540-0f785fd8cdc2\nnested_cv.report_per_fold\n\n# \u2554\u2550\u2561 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    \u00c3 bient\u00f4t\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# \u2554\u2550\u2561 0651292e-3f4e-4263-8235-4caa563403ec\nMLCourse.footer()\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550736856ce-f490-11eb-3349-057c86edfe7e\n# \u255f\u25007eb6a060-f948-4d85-881a-4909e74c15bd\n# \u2560\u25507dd7e9a7-9245-4c64-af0c-8f7d2f62b2bf\n# \u255f\u25005049407c-bf93-41a5-97bd-863a69d7016a\n# \u2560\u255046827e21-0eea-4ec9-83ed-05e41dda1502\n# \u255f\u25006cfc32b3-40c0-4149-ba67-2ec67b3938f3\n# \u2560\u25501320b9b0-d6fc-4e61-8d62-de3988b8b21d\n# \u2560\u25505dc21667-d94f-4c2a-b217-80b9a2262d8c\n# \u255f\u25001fe3f6d1-6336-417e-885e-de3fc5821bdf\n# \u255f\u2500b79fae90-87f3-4f89-933b-d82e76c94d81\n# \u255f\u25007d30f043-2915-4bba-aad5-cb7dbe76a3e5\n# \u2560\u2550ffffa3d0-bffb-4ff8-9966-c3312f952ac5\n# \u2560\u25502e02ac0d-c4d0-47ba-be57-445adeb6ab8b\n# \u255f\u250091eecd2b-af18-4a63-9684-28950e604d1a\n# \u255f\u2500b45b32b1-8a65-4823-b3bb-f0b7cc57604b\n# \u2560\u255023e91f72-0124-48d4-8b53-bd5da67b7ac7\n# \u255f\u25004461d5b0-bc9b-4c89-aa76-70524a5caa7c\n# \u2560\u2550ac3c7e84-6c47-4dc1-b862-de4cfb05dad9\n# \u255f\u250026362233-b006-423d-8fb5-7cd9150405b4\n# \u255f\u25005cff19c7-3426-4d91-b555-f059f5f41886\n# \u2560\u2550df16313f-76be-4d8b-88e7-7cc618ff49d4\n# \u255f\u250046bffe01-1a7c-405b-b3ec-bfe7570b8a3c\n# \u2560\u2550b3aed705-5072-4d9b-bb8f-865ac1561bf6\n# \u2560\u25506916273a-d116-4173-acaa-2bcac1d1753b\n# \u2560\u2550c14c9e49-a993-456e-9115-97da86f8e498\n# \u255f\u25004b435518-2f12-4921-bb1f-fdd049ddfaed\n# \u2560\u25501e584a38-2fef-4877-87f6-92237d71c4b3\n# \u255f\u2500a7c88b3f-92cb-4253-a889-c78683722c1d\n# \u255f\u25000b81c3d5-277a-4fe6-889b-550e2f83c39d\n# \u255f\u25005747d116-1e61-45f0-a87b-89372c6f270f\n# \u2560\u25508204d9da-855d-4c66-b4dd-2c18a17b539b\n# \u255f\u250096b3c070-0c72-44c7-ac98-ff6cb7e82380\n# \u2560\u2550bae635b1-6eba-4ba4-80e9-547770612843\n# \u255f\u2500d9b04582-3a7a-4e19-a0da-d363810883f7\n# \u2560\u25509042e811-9a34-42b8-8069-877f3b3f1e75\n# \u255f\u2500e2658128-4053-4484-8e1e-229eceb755ab\n# \u255f\u2500eaacf529-1727-4743-941b-360c53088b1d\n# \u2560\u2550967a6e08-f0e6-45b7-988b-d0df237f3ddf\n# \u255f\u2500535a11d9-833e-4237-949e-9a3e289c600b\n# \u2560\u25508ae790b3-3987-4f41-8e21-adbb71081eb9\n# \u255f\u2500134df37f-b737-4c80-a5f9-1149aeec970c\n# \u2560\u2550abb71af3-8aae-4806-9d5a-d144c15d22ef\n# \u255f\u25006599d2b4-68f4-4c22-8e40-bf3722597692\n# \u255f\u2500fc07009a-eeac-4c6b-9559-1e99ae68a6c3\n# \u2560\u255042511b31-6d70-495e-8362-01a29143b96e\n# \u255f\u250029683c99-6a6a-4f65-bea2-d592895d887e\n# \u2560\u2550f93f20db-4fed-481f-b085-ca744b68fa8f\n# \u255f\u2500d72609a1-f93f-4ca6-8759-727662233e97\n# \u2560\u255059245b3e-ddfc-46c4-ba44-86ce191672ae\n# \u255f\u2500f8b48f50-09cb-498a-89d1-9ac9b5722d0c\n# \u255f\u250047a2c14b-a02d-43d7-ac8a-4d95a0d91fa8\n# \u255f\u2500cf3841ba-3963-4716-8fc9-8cce1dc4a5fa\n# \u2560\u25503e9c6f1c-4cb6-48d8-8119-07a4b03c2e4b\n# \u255f\u2500eba90af0-bf67-48f8-8d3c-f831b4fc289a\n# \u2560\u2550c8d26ab6-86ec-4b37-9540-0f785fd8cdc2\n# \u255f\u2500ee89c448-1e69-4fd1-a4b8-7297a09f2685\n# \u255f\u2500c693088f-7f80-4cdd-b9b5-65a50da732ac\n# \u255f\u2500e1077092-f72a-42af-b6e0-a616f938cba8\n# \u255f\u25000651292e-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": "using Test\r\nimport DynamicPolynomials: @polyvar\r\n# using Revise\r\nusing PolynomialBasis\r\n\r\nPB = PolynomialBasis\r\n\r\n@polyvar x\r\n\r\nfunction allequal(v1,v2,tol)\r\n    return allequal(v1,v2;tol=tol)\r\nend\r\n\r\nfunction allequal(v1,v2;tol=1e3eps())\r\n    np = length(v1)\r\n    f = length(v2) == np\r\n    return f && all([isapprox(v1[i],v2[i],atol=tol) for i = 1:np])\r\nend\r\n\r\nbasis = PB.CubicHermiteBasis()\r\n@test allequal(basis.points,[-1.0,1.0])\r\n@test allequal(basis(-1.0),[1.0,0.,0.,0.])\r\n@test allequal(basis(1.0),[0.0,0.,1.,0.])\r\n@test allequal(PB.derivative(basis,-1.0),[0.,1.,0.,0.])\r\n@test allequal(PB.derivative(basis,1.0),[0.,0.,0.,1.])\r\n@test allequal(PB.gradient(basis,-1.0),[0.,1.,0.,0.])\r\n@test allequal(PB.gradient(basis,1.0),[0.,0.,0.,1.])\r\n\r\nhess = PB.hessian(basis,-1.0)\r\n@test allequal(hess,[-1.5,-2.0,1.5,-1.0])\r\nhess = PB.hessian(basis,1.0)\r\n@test allequal(hess,[1.5,1,-1.5,2])\r\n", "meta": {"hexsha": "65e70a0801fad777837cccc265fa3703c3d4affe", "size": 887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_hermite_basis.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": "test/test_hermite_basis.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": "test/test_hermite_basis.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": 26.8787878788, "max_line_length": 67, "alphanum_fraction": 0.6290868095, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7629973122009979}}
{"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\u03f5::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\u03f5 \u2208 [-1, 0) \u222a (0, 1]` controls which parts of the spectrum are preserved.\n\n- If `f\u03f5 > 0`, then `f\u03f5` indicates the ratio of high frequency domain to the entire frequency domain.\n    For example, `f\u03f5 = 0.5` preserves 50% of the frequency domain (randomizing the higher\n    frequencies, leaving low frequencies intact).\n- If `f\u03f5 < 0`, then `f\u03f5` indicates ratio of low frequency domain to the entire frequency domain.\n    For example, `f\u03f5 = -0.2` preserves 20% of the frequency domain (leaving higher frequencies intact,\n    randomizing the lower frequencies).\n- If `f\u03f5 \u00b1 1`, then all frequencies are randomized. The method is then equivalent to\n    [`RandomFourier`](@ref).\n\nThe appropriate value of `f\u03f5` 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\u03f5::Real\n\n    function TFTS(f\u03f5::Real)\n        if !(0 < f\u03f5 \u2264 1) && !(-1 \u2264 f\u03f5 < 0)\n            throw(ArgumentError(\"`f\u03f5` must be on the interval [-1, 0) \u222a (0, 1] (positive if preserving high frequencies, negative if preserving low frequencies)\"))\n        end\n        new(f\u03f5)\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 \ud835\udcd5\n    \ud835\udcd5 = forward * x\n\n    # Polar coordinate representation of the Fourier transform\n    rx = abs.(\ud835\udcd5)\n    \u03d5x = angle.(\ud835\udcd5)\n    n = length(\ud835\udcd5)\n\n    # These are updated during iteration procedure\n    \ud835\udcd5new = Vector{Complex{Float64}}(undef, length(\ud835\udcd5))\n    \ud835\udcd5s = Vector{Complex{Float64}}(undef, length(\ud835\udcd5))\n    \u03d5s = Vector{Complex{Float64}}(undef, length(\ud835\udcd5))\n\n    init = (forward = forward, inverse = inverse,\n        rx = rx, \u03d5x = \u03d5x, n = n,\n        \ud835\udcd5new = \ud835\udcd5new, \ud835\udcd5s = \ud835\udcd5s, \u03d5s = \u03d5s)\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\u03f5 = sg.method.f\u03f5\n    L = length(x)\n\n    init_fields = (:forward, :inverse,\n        :rx, :\u03d5x, :n,\n        :\ud835\udcd5new, :\ud835\udcd5s, :\u03d5s)\n\n    forward, inverse,\n        rx, \u03d5x, n,\n        \ud835\udcd5new, \ud835\udcd5s, \u03d5s = 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    \ud835\udcd5s .= forward * s\n    \u03d5s .= angle.(\ud835\udcd5s)\n\n    # Updated spectrum is the old amplitudes with the mixed phases.\n    if f\u03f5 > 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\u03f5 * n))\n        \u03d5s[1:n_preserve] .= \u03d5x[1:n_preserve]\n    elseif f\u03f5 < 0\n        # Do the exact opposite to preserve high-frequencies\n        n_preserve = ceil(Int, abs(f\u03f5 * n))\n        \u03d5s[end-n_preserve+1:end] .= \u03d5x[end-n_preserve+1:end]\n    end\n\n    \ud835\udcd5new .= rx .* exp.(\u03d5s .* 1im)\n    s .= inverse * \ud835\udcd5new\n    \n    return s\nend\n\n\"\"\"\n    TAAFT(f\u03f5)\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\u20134) (1992) 77\u201394.\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\u03f5::Real\n\n    function TAAFT(f\u03f5::Real)\n        f\u03f5 != 0 || throw(ArgumentError(\"`f\u03f5` must be on the interval [-1, 0) \u222a (0, 1] (positive if preserving high frequencies, negative if preserving low frequencies)\"))\n        new(f\u03f5)\n    end\nend\n\nfunction surrogenerator(x, method::TAAFT, rng = Random.default_rng())\n    init = (\n        gen = surrogenerator(x, TFTS(method.f\u03f5), 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\u03f5 = sg.method.f\u03f5\n    L = length(x)\n\n    init_fields = (:forward, :inverse,\n        :rx, :\u03d5x, :n,\n        :\ud835\udcd5new, :\ud835\udcd5s, :\u03d5s)\n\n    forward, inverse,\n        rx, \u03d5x, n,\n        \ud835\udcd5new, \ud835\udcd5s, \u03d5s = 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    \ud835\udcd5s .= forward * s\n    \u03d5s .= angle.(\ud835\udcd5s)\n\n    # Updated spectrum is the old amplitudes with the mixed phases.\n    if f\u03f5 > 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\u03f5 * n))\n        \u03d5s[1:n_preserve] .= @view \u03d5x[1:n_preserve]\n    elseif f\u03f5 < 0\n        # Do the exact opposite to preserve high-frequencies\n        n_preserve = ceil(Int, abs(f\u03f5 * n))\n        \u03d5s[end-n_preserve+1:end] .= @view \u03d5x[end-n_preserve+1:end]\n    end\n\n    \ud835\udcd5new .= rx .* exp.(\u03d5s .* 1im)\n    s .= inverse * \ud835\udcd5new\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\u00e7\u00e3o do Julia demonstrado no README.md\n    Como rodar esse script: $ julia bhaskara.jl\n\n    Objetivo desse script: realizar uma opera\u00e7\u00e3o b\u00e1sica de bhaskara.\n    Refer\u00eancia: https://brasilescola.uol.com.br/matematica/formula-bhaskara.htm\n\n=#\n\n#= \n    Declara\u00e7\u00e3o de vari\u00e1veis a, b e c respectivamente\n    Como visto, vari\u00e1veis no Julia n\u00e3o s\u00e3o tipadas como em algumas linguagens,\n    ou seja, voc\u00ea pode declar\u00e1-las e o inicializador delas assumir\u00e1 o valor\n    que voc\u00ea colocar como atribui\u00e7\u00e3o.\n    Ex.: Em a = 1 (a ser\u00e1 um inteiro) / Em a = 'Ol\u00e1' (a ser\u00e1 uma string)\n=# \na = 1\nb = 0\nc = -16\n\n#   Definindo uma vari\u00e1vel chamada 'delta' que assumir\u00e1 o papel de\n#   uma fun\u00e7\u00e3o onde algo ser\u00e1 executado e o resultado ser\u00e1 armazenado\ndelta = function (a, b, c)\n    return b * b - 4 * a * c\nend\n\n#   Definindo uma vari\u00e1vel chamada 'raiz1' que assumir\u00e1 o papel de\n#   uma fun\u00e7\u00e3o onde algo ser\u00e1 executado e o resultado ser\u00e1 armazenado\nraiz1 = function (a, b, c)\n    return (-b + Base.Math.sqrt(delta(a, b, c))) / 2 * a;\nend\n\n#   Definindo uma vari\u00e1vel chamada 'raiz2' que assumir\u00e1 o papel de\n#   uma fun\u00e7\u00e3o onde algo ser\u00e1 executado e o resultado ser\u00e1 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\u00e7\u00f5es atribu\u00eddos a vari\u00e1vel respectiva.\n#   Coment\u00e1rio para demonstrar o valor que deve ser apresentado.\n#   Seria interessante colocar um assert.equals para ficar mais n\u00edtida a compreens\u00e3o.\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)\u00f72, (n-1)\u00f72))\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\u0303 = fft(x)\n   # Compute the two-sided spectrum amplitude P2.\n   P\u2082 = @. abs(x\u0303/L)\n   # Compute the single-sided spectrum amplitude P1.\n   P\u2081 = P\u2082[1:floor(Int, L/2+1)]\n   P\u2081[2:end-1] .= 2 .* P\u2081[2:end-1]\n\n   f = Fs * (0:(L/2)) / L\n\n   f, P\u2081\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": "using Optim, Random\nobj = build_loss_objective(prob1,Tsit5(),L2Loss(t,data),\n                           maxiters=10000,verbose=false)\n\n### Optim Method\n\nprintln(\"Use Optim Brent to fit the parameter\")\nresult = Optim.optimize(obj, 1.0, 10.0)\n@test_broken result.minimizer[1] \u2248 1.5 atol=3e-1\n\nprintln(\"Use Optim BFGS to fit the parameter\")\nresult = Optim.optimize(obj, [1.0], Optim.BFGS())\n@test result.minimizer[1] \u2248 1.5 atol=3e-1\n#sol_optimized2 = solve(prob)\n#plot!(sol_optimized2,leg=false)\n\ncost_function2 = build_loss_objective(prob2,Tsit5(),L2Loss(t,data),\n                                      maxiters=10000,verbose=false)\nresult_bfgs = Optim.optimize(cost_function2, [1.0,2.5], Optim.BFGS())\n@test_broken result_bfgs.minimizer \u2248 [1.5;3.0] atol=3e-1\n\nRandom.seed!(200)\ncost_function3 = build_loss_objective(prob3,Tsit5(),L2Loss(t,data),\n                                      maxiters=10000,verbose=false)\nresult_bfgs = Optim.optimize(cost_function3, [1.3,0.8,2.8,1.2], Optim.BFGS())\n@test result_bfgs.minimizer \u2248 [1.5;1.0;3.0;1.0] atol=5e-1\n\n#=\nprintln(\"Use Optim NelderMead to fit the parameter\")\nresult_neldermead = Optim.optimize(cost_function2, [1.0,2.5], Optim.NelderMead())\n@test result_neldermead.minimizer \u2248 [1.5;3.0] atol=3e-1\n\nprintln(\"Use Optim SimulatedAnnealing to fit the parameter\")\noptions = Optim.Options(iterations=100_000)\nresult_simulatedannealing = Optim.optimize(obj, [1.0], Optim.SimulatedAnnealing(),options)\n@test result_simulatedannealing.minimizer \u2248 [1.5] atol=3e-1\n\n\nresult_simulatedannealing = Optim.optimize(cost_function2, [1.0,2.5], Optim.SimulatedAnnealing(),options)\n@test result_simulatedannealing.minimizer \u2248 [1.5;3.0] atol=3e-1\n\nprintln(\"Use Optim Particle Swarm Optimization to fit the parameter\")\ninitial_x = [1.0]\nlower = [0.0]\nupper = [5.0]\nn_particles = 4\noptions = Optim.Options(iterations=100)\nresult_pso = Optim.optimize(obj, initial_x, Optim.ParticleSwarm(lower, upper, n_particles), options)\n@test result_pso.minimizer[1] \u2248 1.5 atol=3e-1\n\ninitial_x = [1.0,2.5]\nlower = [0.0,2.0]\nupper = [5.0,10.0]\nn_particles = 4\noptions = Optim.Options(iterations=100)\nresult_pso = Optim.optimize(cost_function2, initial_x, Optim.ParticleSwarm(lower, upper, n_particles), options)\n@test result_pso.minimizer \u2248 [1.5;3.0] atol=3e-1\n=#\n", "meta": {"hexsha": "b6f9d81796f57aaaff10bd8a6b72eee37f289127", "size": 2272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tests_on_odes/optim_test.jl", "max_stars_repo_name": "baggepinnen/DiffEqParamEstim.jl", "max_stars_repo_head_hexsha": "d4e495ebf0e6cc22ce7cb4c156372f4dacd719fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2017-02-26T21:21:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T20:34:20.000Z", "max_issues_repo_path": "test/tests_on_odes/optim_test.jl", "max_issues_repo_name": "baggepinnen/DiffEqParamEstim.jl", "max_issues_repo_head_hexsha": "d4e495ebf0e6cc22ce7cb4c156372f4dacd719fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 103, "max_issues_repo_issues_event_min_datetime": "2016-12-09T19:16:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-24T06:47:56.000Z", "max_forks_repo_path": "test/tests_on_odes/optim_test.jl", "max_forks_repo_name": "baggepinnen/DiffEqParamEstim.jl", "max_forks_repo_head_hexsha": "d4e495ebf0e6cc22ce7cb4c156372f4dacd719fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2016-11-04T12:18:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:43.000Z", "avg_line_length": 38.5084745763, "max_line_length": 111, "alphanum_fraction": 0.7183098592, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7629729686718524}}
{"text": "import SpecialFunctions\nimport SpecialFunctions: besselj\n\n@testset \"Bessel Roots\" begin\n    tol = 1e-11\n\n    # Check if besselj(nu, besselroots(nu, n) ) is small:\n\n    for nu = 0.:0.1:5.\n        let n = 10\n            @test norm( besselj.(nu, besselroots(nu, n) ), Inf ) < tol\n        end\n    end\nend", "meta": {"hexsha": "5356c50798b6878da473c5b22a56dc698466f3b8", "size": 300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_besselroots.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": "test/test_besselroots.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": "test/test_besselroots.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": 21.4285714286, "max_line_length": 70, "alphanum_fraction": 0.5966666667, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7629583721726616}}
{"text": "function haversine(p1, p2; R=6371.0)\n    lon1, lat1 = p1\n    lon2, lat2 = p2\n    \u03c61 = lat1 * \u03c0/180.0\n    \u03c62 = lat2 * \u03c0/180.0\n    \u0394\u03c6 = (lat2-lat1) * \u03c0/180.0\n    \u0394\u03bb = (lon2-lon1) * \u03c0/180.0\n    a = sin(\u0394\u03c6/2.0)^2.0 + cos(\u03c61)*cos(\u03c62) * sin(\u0394\u03bb)^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": "using LinearAlgebra\nusing Test\nusing Random\n\nusing ProximalOperators\nusing ProximalAlgorithms\n\n@testset \"Lasso small (strongly convex, $T)\" for T in [Float32, Float64]\n\n    Random.seed!(777)\n    dim = 5\n    \u03bcf = T(1)\n    Lf = T(10)\n\n    x_star = convert(Vector{T}, 1.5 * rand(T, dim) .- 0.5)\n\n    lam = (\u03bcf + Lf) / 2\n    @test typeof(lam) == T\n\n    D = Diagonal(sqrt(\u03bcf) .+ (sqrt(Lf) - sqrt(\u03bcf)) * rand(T, dim))\n    D[1] = sqrt(\u03bcf)\n    D[end] = sqrt(Lf)\n    Q = qr(rand(T, (dim, dim))).Q\n    A = Q * D * Q'\n    b = A * x_star + lam * inv(A') * sign.(x_star)\n\n    f = LeastSquares(A, b)\n    h = NormL1(lam)\n\n    TOL = T(1e-4)\n\n    @testset \"SFISTA\" begin\n\n        # SFISTA\n\n        x0 =  A \\ b\n        x0_backup = copy(x0)\n        solver = ProximalAlgorithms.SFISTA(tol = TOL)\n        y, it = solver(x0, f = f, h = h, Lf = Lf, \u03bcf = \u03bcf)\n        @test eltype(y) == T\n        @test norm(y - x_star) <= TOL\n        @test it < 200\n        @test x0 == x0_backup\n\n    end\n\nend\n", "meta": {"hexsha": "68db52b2dad2320bc6b3f045d13dc0ae3c4835da", "size": 969, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/problems/test_lasso_small_strongly_convex.jl", "max_stars_repo_name": "lostella/ProximalAlgorithms.jl", "max_stars_repo_head_hexsha": "eb978e03d9c9a927ba1dbaae2e4e9aaf9e668a01", "max_stars_repo_licenses": ["MIT"], "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/problems/test_lasso_small_strongly_convex.jl", "max_issues_repo_name": "lostella/ProximalAlgorithms.jl", "max_issues_repo_head_hexsha": "eb978e03d9c9a927ba1dbaae2e4e9aaf9e668a01", "max_issues_repo_licenses": ["MIT"], "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/problems/test_lasso_small_strongly_convex.jl", "max_forks_repo_name": "lostella/ProximalAlgorithms.jl", "max_forks_repo_head_hexsha": "eb978e03d9c9a927ba1dbaae2e4e9aaf9e668a01", "max_forks_repo_licenses": ["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": 72, "alphanum_fraction": 0.5221878225, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7629583663394861}}
{"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/\u221a\u03c0 \u222b_{0}^{z} \\exp{-t^2}dt,\nthe derivative of which is 2/\u221a\u03c0  \\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!(\u03b4d::AbstractArray{T}, \u03b4m::AbstractArray{T}; m\u2092) where {T<:Real} = \u03b4d .= (2/sqrt( \u03c0 )) .* exp.(-m\u2092.^2) .* \u03b4m", "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\u2081, m\u2081, j\u2082, m\u2082, j\u2083, m\u2083=m\u2081+m\u2082)\n\nCalculate the vector coupling coefficient `\u27e8j\u2081 m\u2081, j\u2082 m\u2082|j\u2083 m\u2083\u27e9`\naccording to the Condon\u2013Shortley phase convention and using the\ndefinition of Eq. (8.1.12) in Varshalovich (1988).\n\"\"\"\nclebsch_gordan_condon_shortley(j\u2081, m\u2081, j\u2082, m\u2082, j\u2083, m\u2083=m\u2081+m\u2082) =\n    powneg1(Int(j\u2081 - j\u2082 + m\u2083))*\u220f(j\u2083)*wigner3j(j\u2081, j\u2082, j\u2083,\n                                              m\u2081, m\u2082, -m\u2083)\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 NSGAIII\nusing Base.Test\n\n\nconst C1 = [2 5 4 7 ; 3 3 5 7 ; 3 8 4 2 ; 6 5 2 5]\nconst C2 = [3 3 6 2 ; 5 3 7 3 ; 5 2 7 4 ; 4 6 3 5]\nconst C3 = [4 2 5 3 ; 5 3 4 3 ; 4 3 5 2 ; 6 4 7 3]\n\nz(x, C) = sum(inds->C[inds...], enumerate(x))\nz(x::Vector{Int}) = z(x, C1), z(x, C2), z(x, C3)\n\nres = unique(nsga(500, 100, ()->randperm(4), z, 15))\ndisplay(res)\n@test length(res) == 7\n\n\nconst d = RealCoding(6, [-10], [10])\nz1(x) = x^2\nz2(x) = (x-2)^2\nz(bits) = begin \n    x = decode(bits, d)[1]\n    z1(x), z2(x)\nend\nseed = encode.([-10 + rand()*20 for _ =1:100] ,d)\nres = nsga(500, 200, ()->rand(Bool, d.nbbitstotal), z, 5, seed = seed)\n\n@test maximum(x -> x.y[1], res) >= 3.99\n@test minimum(x -> x.y[1], res) <= 1e-4\n@test maximum(x -> x.y[2], res) >= 3.99\n@test minimum(x -> x.y[2], res) <= 1e-4\n", "meta": {"hexsha": "681878bc07367259ba2c7cad33fdf704a1890650", "size": 785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 25.3225806452, "max_line_length": 70, "alphanum_fraction": 0.5286624204, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7629583618185215}}
{"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(\u03b1, rmax, Mmax) = Store(\u03b1, rmax, Mmax, Mmax)\n\nfunction Store(\u03b1::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, \u03b1-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                                                                  \u03b1-1)\n        jacobi3[M] = Array{T}(undef, M, 2)\n        jacobi3[M][:,1], jacobi3[M][:,2] = GaussQuadrature.jacobi(M, \u03b1, zero(T))\n        jacobi4[M] = Array{T}(undef, M, 2)\n        jacobi4[M][:,1], jacobi4[M][:,2] = GaussQuadrature.jacobi(M, zero(T), \u03b1)\n        jacobi5[M] = Array{T}(undef, M, 2)\n        jacobi5[M][:,1], jacobi5[M][:,2] = GaussQuadrature.jacobi(M, one(T), \n                                                                  \u03b1-1)\n    end\n    \u03a8  = Array{T}(undef, rmax, ppImax)\n    d\u03a8 = 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(\u03b1, rmax, Mmax, unitlegendre, legendre, \n                 jacobi1, jacobi2, jacobi3, jacobi4, jacobi5,\n                 ppImax, \u03a8, d\u03a8, 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 (\u03b8 = 0.35, # capital share\n    \u03b4 = 0.0464, # depreciation rate\n    \u03b3_z = 0.016, # growth rate of productivity\n    \u03b3_n = 0.015, # growth rate of population\n    \u03b2 = 0.9722, # discount rate\n    \u03b2_hat = \u03b2*(1+\u03b3_n), # detrended discount rate\n    \u03c8 = 2.24, # labor coefficient\n    \u03c1 = 0.2,# autocorr of productivity process\n    \u03c3 = 0.5, # stand. dev. for productivity process\n    nz = 5, # number of states for productivity\n    \u03bc_z = 0.0, # mean of productivity process\n    zGrid = exp.(Tauchen(\u03bc_z,\u03c1,\u03c3,nz)[1]), # grid for productivity process\n    P_z = Tauchen(\u03bc_z,\u03c1,\u03c3,nz)[2]) # transition matrix\n\n## Get the Steady-State level of capital from a Nonlinear solver\nfunction getSS(md)\n    @unpack \u03b8,\u03c8,\u03b4,\u03b2_hat,\u03b3_n,\u03b3_z = md\n\n    function ee!(eq,x)\n        k=(x[1])\n        h=(x[2])\n        eq[1]=\u03b2_hat*(\u03b8*k^(\u03b8-1)*h^(1-\u03b8)+1-\u03b4)-(1+\u03b3_n)*(1+\u03b3_z)\n        eq[2]=(-(\u03c8/(1-h)))+((1-\u03b8)*(k^\u03b8)*(h^(-\u03b8)))/((k^\u03b8)*(h^(1-\u03b8))-(1+\u03b3_n)*(1+\u03b3_z)*k+(1-\u03b4)*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^\u03b8)*((exp(0)*hss)^(1-\u03b8))-(1+\u03b3_n)*(1+\u03b3_z)*kss+(1-\u03b4)*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 \u03b8,\u03c8,\u03b3_n,\u03b3_z,\u03b4,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) = (\u03c8/(1-\u03b8))*((kGrid[i]^\u03b8)*((zGrid[k]*h)^(1-\u03b8))-(1+\u03b3_n)*(1+\u03b3_z)*kGrid[j]+(1-\u03b4)*kGrid[i])+((h-1)*(kGrid[i]^\u03b8)*(zGrid[k]^(1-\u03b8))*(h^(-\u03b8)))\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 \u03b8,\u03c8,\u03b3_n,\u03b3_z,\u03b4,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]^\u03b8)*((zGrid[k]*h_star[i,j,k])^(1-\u03b8))-(1+\u03b3_n)*(1+\u03b3_z)*kGrid[j]+(1-\u03b4)*kGrid[i];\n                if c <= 0\n                    rt[i,j,k] = -100.0;\n                else\n                    rt[i,j,k] = log(c)+\u03c8*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 \u03b8,\u03c8,\u03b3_n,\u03b3_z,\u03b4,nz,zGrid,\u03b2_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].+\u03b2_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]^\u03b8)*(zGrid[j]*hpol[i,j])^(1-\u03b8)-(1+\u03b3_n)*(1+\u03b3_z)*kpol[i,j]+(1-\u03b4)*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\u0394 = .1\nN = 100\n\u03c4 = N*\u0394/5\nran = 0.0:2pi/N:2pi\nfunction fillxs(Ts = 1,N = 100, ini=0.0, fin=100)\n    xs = []\n    \u0394 = fin/N\n    \u03c4 = N*\u0394/5\n\n    for j in 1:Ts\n        for i in ini:\u0394:\u03c4-\u0394\n            push!(xs,1)\n        end\n\n        for i in \u03c4:\u0394: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": "# # Estimate Binomial draw probabilility\n\nusing DynamicHMCModels\n\nRandom.seed!(1356779)\n\n# Define a structure to hold the data.\n\nBase.@kwdef struct BernoulliProblem\n    \"Total number of draws in the data.\"\n    n::Int\n    \"Number of draws ' == 1' \"\n    obs::Vector{Int}\nend;\n\n# Write a function to return properly dimensioned transformation.\n\nmake_transformation(model::BernoulliProblem) =\n    as((p = as\ud835\udd40, ))\n\n# Add data\n\nmodel = BernoulliProblem(; n = 9, obs = rand(Binomial(9, 2/3), 3))\n\n# Make the type callable with the parameters *as a single argument*. \n\nfunction (model::BernoulliProblem)(\u03b8)\n    @unpack n, obs = model        # extract the data\n    @unpack p = \u03b8\n    loglikelihood(Binomial(n, p), obs)\nend\n\n# Use a flat priors (the default, omitted) for \u03b1\n\nP = TransformedLogDensity(make_transformation(model), model)\n\u2207P = ADgradient(:ForwardDiff, P);\n\n# Sample chain\n\nresults = mcmc_with_warmup(Random.GLOBAL_RNG, \u2207P, 1000;\n  reporter = NoProgressReport()\n)\n\nposterior = P.transformation.(results.chain)\n\n# Create Particles NamedTuple object\n\nprintln()\np = as_particles(posterior)\np |> display\n\nprintln()\nDynamicHMC.Diagnostics.EBFMI(results.tree_statistics) |> display\n\nprintln()\nDynamicHMC.Diagnostics.summarize_tree_statistics(results.tree_statistics) |> display\n", "meta": {"hexsha": "61ba91c5c9ea342df6bd1c9e67930c6468e60dbf", "size": 1274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/02/m2.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/02/m2.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/02/m2.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": 22.350877193, "max_line_length": 84, "alphanum_fraction": 0.726844584, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7628168804511632}}
{"text": "module Lecture2\n\nusing Test\n\ninclude(\"../../lib/KTBC.jl\")\nimport .KTBC.CreateKTBC\n\ninclude(\"../../lib/SpecialVectors.jl\")\nusing .SpecialVectors: constants, linear, squares, rampAtK, sines, cosines, exponentials\n\ninclude(\"../../lib/DifferencesMatrix.jl\")\nusing .DifferencesMatrix: backwardDiff, forwardDiff\n\ndims = 4\n\nK, T, B, C = CreateKTBC(dims)\n\nK\u2090 = convert(Array{Int}, K)\n\ncV = constants(dims)\n\n@test (K * cV)[2:3] == [\n  0.0\n  0.0\n]\n\nlV = linear(dims)\n\n@test (K * lV)[2:3] == [\n  0.0\n  0.0\n]\n\nsV = squares(dims)\n\n@test (-K * sV)[2:3] == [\n 2.0\n 2.0\n]\n\nrV = rampAtK(2, dims)\n\n@test (-K * rV)[1:3] == [\n  0.0\n  1.0\n  0.0\n]\n\nt = \u03c0 / 4\nmultiplier = round(2 * cos(t) - 2, digits=2)\n\nsinV = round.(sines(t, dims), digits=2)\n@test round.((-K * sinV)[1:3], digits=1) == round.((multiplier * sinV)[1:3], digits=1)\n\ncosV = round.(cosines(t, dims), digits=2)\n@test round.((-K * cosV)[2:3], digits=1) == round.((multiplier * cosV)[2:3], digits=1)\n\nexpV = round.(exponentials(t, dims), digits=2)\n@test round.((-K * expV)[2:3], digits=1) == round.((multiplier * expV)[2:3], digits=1)\n\n# Matlab experiment\nfunction mathlabExperiment(n::Int)\n    h = 1 / (n + 1)\n    u = cos.(\u03c0 * [1:n...] * h / 2)\n    c = (\u03c0 / 2)^2\n    f = c * u\n\n    K, T, B, C = CreateKTBC(n)\n\n    U = (h^2) * T \\ f\n    e = 1 - U[1]\n    g = [c / 2; f]\n\n    T = backwardDiff(n + 1) * forwardDiff(n + 1)\n\n    V = (h^2) * T \\ g\n    E = 1 - V[1]\n\n    return f, e, T, V, E\nend\n\nf, e, T, V, E = mathlabExperiment(3)\nf, e, T, V, E = mathlabExperiment(7)\nf, e, T, V, E = mathlabExperiment(15)\n\nend\n", "meta": {"hexsha": "e1ef6294e49cb368da2194a184004088f44699bb", "size": 1547, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.AppliedLInearAlgebra/2.DifferentialEqnsAndDifferenceEqns/LectureNotes.jl", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "1.AppliedLInearAlgebra/2.DifferentialEqnsAndDifferenceEqns/LectureNotes.jl", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_issues_repo_licenses": ["MIT"], "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.AppliedLInearAlgebra/2.DifferentialEqnsAndDifferenceEqns/LectureNotes.jl", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 17.7816091954, "max_line_length": 88, "alphanum_fraction": 0.5610859729, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7628168741696992}}
{"text": "# A simple example to demonstrate the use of gridtune\n\nusing MLBase\nusing MultivariateStats\n\n## prepare data\n\nn_tr = 20  # number of training samples\nn_te = 10  # number of testing samples\nd = 5      # dimension of observations\n\ntheta = randn(d)\nX_tr = randn(n_tr, d)\ny_tr = X_tr * theta + 0.1 * randn(n_tr)\nX_te = randn(n_te, d)\ny_te = X_te * theta + 0.1 * randn(n_te)\n\n## tune the model\n\nfunction estfun(regcoef, bias)\n    s = ridge(X_tr, y_tr, regcoef; bias=bias)\n    return bias ? (s[1:end-1], s[end]) : (s, 0.0)\nend\n\nevalfun(m) = msd(X_te * m[1] + m[2], y_te) \n\nr = gridtune(estfun, evalfun, \n            (\"regcoef\", [1.0e-3, 1.0e-2, 1.0e-1, 1.0]), \n            (\"bias\", (true, false)); \n            ord=Reverse,\n            verbose=true)\n\nbest_model, best_cfg, best_score = r\n\n## print results\n\n\u03b8, b = best_model\nprintln(\"Best model:\") \nprintln(\"  \u03b8 = $(\u03b8')\"), \nprintln(\"  b = $b\")\nprintln(\"Best config: regcoef = $(best_cfg[1]), bias = $(best_cfg[2])\")\nprintln(\"Best score: $(best_score)\")\n\n", "meta": {"hexsha": "9af1ebcdad15ffcd131876a52f78095e56c1ab31", "size": 998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gridtune.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MLBase.jl-f0e99cf1-93fa-52ec-9ecc-5026115318e0", "max_stars_repo_head_hexsha": "ded7174c2e2e9e685ca32c6228ea0772e8cc6cd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176, "max_stars_repo_stars_event_min_datetime": "2015-02-25T19:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:11:41.000Z", "max_issues_repo_path": "examples/gridtune.jl", "max_issues_repo_name": "RubinOrlando/MLBase.jl", "max_issues_repo_head_hexsha": "ded7174c2e2e9e685ca32c6228ea0772e8cc6cd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2015-01-10T11:37:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T11:49:30.000Z", "max_forks_repo_path": "examples/gridtune.jl", "max_forks_repo_name": "RubinOrlando/MLBase.jl", "max_forks_repo_head_hexsha": "ded7174c2e2e9e685ca32c6228ea0772e8cc6cd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2015-01-14T19:03:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T16:48:55.000Z", "avg_line_length": 22.6818181818, "max_line_length": 71, "alphanum_fraction": 0.6082164329, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7628168707700977}}
{"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": "using Plots\nusing DSP\nusing FFTW \ninclude(\"RSProject.jl\")\n\nfunction write_binary_file(data,filename::String,dtype::DataType=Matrix{ComplexF32})\n  f = open(filename,\"w\");\n  data = convert(dtype,data)\n  write(f,data)\n  close(f)\nend\n\n\"\"\"\n    exportAndDisplay(u,a,iter,K,m,name)\nExports and displays PCFM algorith results.\n  ...\n# Arguments\n- `u::Vector`: Window Function PSD.\n- `a::Integer`: Log base. If zero use non log version.\n- `iter::Integer`: Number of iterations.\n- `K::Integer`: Oversampling factor.\n- `m::Integer`: Size.\n- `name::String`: Name of window function.\n...\n\"\"\"\nfunction exportAndDisplay(u,a,iter,K,m,name)\n    u[findall(<(-50), 10*log10.(u))] .= 10^-5\n    u = abs.(u).^2\n    result = RSProject.funPcfm(u,a,iter,K)\n    (B,Bb,x) = RSProject.funPcfmHelper(m,K)\n    s = exp.(im.*B*result)\n    # write_binary_file(s,\"data/\"*name*\".bin\")\n    sb = vcat(s, zeros(m-1,1))\n    sbf =  fftshift(fft(sb))\n    sbf = sbf ./maximum(abs.(sbf))\n    display(plot(10*log10.(abs.(sbf).^2),ylim=(-50, 0)))\n    display(plot!(10*log10.(u),ylim=(-50, 0)))\nend\nm = 512\nK=3\na = 10\niter = 1000\n#Guassian Window\nu = gaussian((2*m-1,1),0.1; padding = 0, zerophase = false)\nexportAndDisplay(u,a,iter,K,m,\"Gaussian\")\nu[findall(<(-50), 10*log10.(u))] .= 10^-5\nu = abs.(u).^2\ntime = @time begin\n  result = RSProject.profm(sqrt.(u),iter)\nend\n#time2 = @time begin\n  #result2 = RSProject.funPcfm(u,a,iter,K)\n#end\n#(B,Bb,x) = RSProject.funPcfmHelper(m,K)\n#s = exp.(im.*B*result2)\n#sb = vcat(s, zeros(m-1,1))\n#sbf =  fftshift(fft(sb))\n#sbf = sbf ./maximum(abs.(sbf))\nresPlot = abs.(fftshift(fft(result)))\nresPlot = resPlot./maximum(resPlot)\ndisplay(plot(abs.(resPlot).^2))\n#display(plot!(abs.(sbf).^2))\n#exportAndDisplay(u,a,iter,K,m,\"Guassian\")\n#Hanning Window\n#u = hanning((2*m-1,1); padding = 0, zerophase = false)\n#exportAndDisplay(u,a,iter,K,m,\"Hanning\")\n#Hamming Window\n#u = hamming((2*m-1,1); padding = 0, zerophase = false)\n#exportAndDisplay(u,a,iter,K,m,\"Hamming\")\n#Tukey Window\n# u = tukey((2*m-1,1), 0.5; padding = 0, zerophase = false)\n# u[findall(<(-50), 10*log10.(u))] .= 10^-5\n# u = abs.(u).^2\n# time = @time begin\n#   result = profm(sqrt.(u),iter)\n# end\n# time2 = @time begin\n#   result2 = funPcfm(u,a,iter,K)\n# end\n# (B,Bb,x) = funPcfmHelper(m,K)\n# s = exp.(im.*B*result2)\n# sb = vcat(s, zeros(m-1,1))\n# sbf =  fftshift(fft(sb))\n# sbf = sbf ./maximum(abs.(sbf))\n# resPlot = abs.(fftshift(fft(result)))\n# resPlot = resPlot./maximum(resPlot)\n# display(plot(abs.(resPlot).^2))\n\n# display(plot!(abs.(sbf).^2))\n# #exportAndDisplay(u,a,iter,K,m,\"Tukey\")\n# #Rectangular Window\n\n# #u = rect((2*m-1,1); padding = 0, zerophase = false)\n\n# #exportAndDisplay(u,a,iter,K,m,\"Rectangular\")\n# #Triangular Window\n# #u = triang((2*m-1,1); padding = 0, zerophase = false)\n#u = tukey((2*m-1,1), 0.5; padding = 0, zerophase = false)\n#exportAndDisplay(u,a,iter,K,m,\"Tukey\")\n#Rectangular Window\n#u = rect((2*m-1,1); padding = 0, zerophase = false)\n#exportAndDisplay(u,a,iter,K,m,\"Rectangular\")\n#Triangular Window\n#u = triang((2*m-1,1); padding = 0, zerophase = false)\n# #exportAndDisplay(u,a,iter,K,m,\"Triangular\")", "meta": {"hexsha": "d959fd8e0613ca432e459fc4edd4d679e9f3f1a3", "size": 3087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/pcfmDriver.jl", "max_stars_repo_name": "ShaneFlandermeyer/ece5523-project", "max_stars_repo_head_hexsha": "1a5fb28e398f92ba0350a327c2c61c2764288842", "max_stars_repo_licenses": ["MIT"], "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/pcfmDriver.jl", "max_issues_repo_name": "ShaneFlandermeyer/ece5523-project", "max_issues_repo_head_hexsha": "1a5fb28e398f92ba0350a327c2c61c2764288842", "max_issues_repo_licenses": ["MIT"], "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/pcfmDriver.jl", "max_forks_repo_name": "ShaneFlandermeyer/ece5523-project", "max_forks_repo_head_hexsha": "1a5fb28e398f92ba0350a327c2c61c2764288842", "max_forks_repo_licenses": ["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.4, "max_line_length": 84, "alphanum_fraction": 0.6423712342, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.762816864784149}}
{"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; \u03f5 = 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) < +\u03f5 \"f($(lo))=$(f(lo)) should be negative at low end\";\n    # @assert f(hi) > -\u03f5 \"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 < -\u03f5\n            lo = mid\n        elseif fmid > \u03f5\n            hi = mid;\n        else\n            return mid;\n        end\n    end\n    @warn \"binary_search did not reach tolerance $\u03f5 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 ``\u03bc_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 ``\u03bc_m`` and ``\u03bc_{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| \u2248 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, \u03c0)))\n    @inbounds for ii = 1:2nstep\n        \u03bc = sqrt(one(x) + one(x)/2(ii+1))\n        z = -\u03bc * 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, \u03c0)))\n    @inbounds for ii = 1:2nstep\n        \u03bc = sqrt(one(x) + one(x)/2(ii+1))\n        z = -\u03bc * y * z\n        vals[ii] = z\n    end\n    return vals\nend\n\nfunction recur2(x, nstep)\n    y\u00b2 = -fma(x, x, -one(x))\n    y\u00b9 = sqrt(y\u00b2)\n    vals = zeros(typeof(x), 2nstep)\n    z = inv(sqrt(4oftype(x, \u03c0)))\n    @inbounds for ii = 1:2:2nstep\n        \u03bc\u2081 = sqrt(one(x) + one(x)/2(ii+1))\n        \u03bc\u2082 = sqrt(one(x) + one(x)/2(ii+2))\n        vals[ii] = -\u03bc\u2081 * y\u00b9 * z\n        z = \u03bc\u2081 * \u03bc\u2082 * y\u00b2 * z\n        vals[ii+1] = z\n    end\n    return vals\nend\n\nfunction recur3(x, nstep)\n    y\u00b2 = (one(x) - x) * (one(x) + x)\n    y\u00b9 = sqrt(y\u00b2)\n    vals = zeros(typeof(x), 2nstep)\n    z = inv(sqrt(4oftype(x, \u03c0)))\n    @inbounds for ii = 1:2:2nstep\n        \u03bc\u2081 = sqrt(one(x) + one(x)/2(ii+1))\n        \u03bc\u2082 = sqrt(one(x) + one(x)/2(ii+2))\n        vals[ii] = -\u03bc\u2081 * y\u00b9 * z\n        z = \u03bc\u2081 * \u03bc\u2082 * y\u00b2 * 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 \u2248 1 where catastrophic cancellation is\n# expected without FMA.\nx\u2080 = 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\u2080), nstep)\nend))\n\nv0 = reduce(hcat, recur0.(x\u2080, nstep))\nv1 = reduce(hcat, recur1.(x\u2080, nstep))\nv2 = reduce(hcat, recur2.(x\u2080, nstep))\nv3 = reduce(hcat, recur3.(x\u2080, 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\u2080, 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 \u2014 Baseline\")\nplot_compare(axs[1,2], v1, title=\"v1 \u2014 FMA \\$(1 - x^2)\\$\")\nplot_compare(axs[2,1], v2, title=\"v2 \u2014 FMA + pairwise iteration\")\nplot_compare(axs[2,2], v3, title=\"v3 \u2014 \\$(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\u03b1\u0302_optim = optimize(a -> ols_gmm(a, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-8, iterations=100_000))\nprintln(\u03b1\u0302_optim.minimizer)\n\n# the answers are very close\n# \u03b1\u0302_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(\u03b8, X, y, D)\n\tN=size(X,1)\n\tK=size(X,2)\n\tJ = length(unique(y))\n    \u03b2 = \u03b8[1:end-1]\n    \u03c3 = \u03b8[end]\n    if length(\u03b2)==1\n        \u03b2 = \u03b2[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 \u03b5 draw #\n    # for every guess of \u03b8!               #\n    #### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ###\n    # simulated model moments\n    for d=1:D\n        \u03b5 = \u03c3*randn(N)\n        y\u0303 = X*\u03b2 .+ \u03b5\n        gmodel[1:end-1,d] = y\u0303\n        gmodel[  end  ,d] = var(y\u0303)\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": "using SSpline\nusing Test\n\n@testset \"\" begin\n    \n\nend\n\n@testset \"Nearest Neighbor Spline\" begin\n    x=[0,1,2,3,4]\n    y=[0,1,5,2,2]\n    @test typeof(nearestneighbor(x,y))==NearestNeighborSpline\nend\n\n@testset \"Nearest Neighbor Spline Naming\" begin\n    x=[0,1,2,3,4]\n    y=[0,1,5,2,2]\n    nn1=nearestneighbors(x,y)\n    nn2=stepspline(x,y)\n    nn3=spline0(x,y)\n    @test nn1.a == [0.0,1.0,5.0,2.0,2.0]\n    @test nn1.x == [0.0,1.0,2.0,3.0,4.0]\n\n    @test nn2.a == nn1.a\n    @test nn2.x == nn1.x\n    @test nn3.a == nn1.a\n    @test nn3.x == nn1.x\nend\n\n@testset \"Linear Spline Type\" begin\n    x=[0,1,2,3,4]\n    y=[0,1,5,2,2]\n    @test typeof(linearspline(x,y))==LinearSpline\nend\n\n@testset \"Linear Spline Naming\" begin\n    x=[0,1,2,3,4]\n    y=[0,1,5,2,2]\n\n    lin1=linearspline(x,y)\n    lin2=lspline(x,y)\n    lin3=spline1(x,y)\n\n    # name tests, spline generation\n\n    @test lin1.b == [1.0, 4.0, -3.0, 0.0, 0.0]\n    @test lin1.a == [0.0,1.0,5.0,2.0,2.0]\n    @test lin1.x == [0.0,1.0,2.0,3.0,4.0]\n\n    @test lin2.b == lin1.b\n    @test lin2.a == lin1.a\n    @test lin2.x == lin1.x\n\n    @test lin3.b == lin1.b\n    @test lin3.a == lin1.a\n    @test lin3.x == lin1.x\nend\n\n@testset \"Linear Spline Interpolation\" begin\n    # interpolation test\n    x=[0,1,2,3,4]\n    y=[0,1,5,2,2]\n\n    lin1=linearspline(x,y)\n\n    intlin=interp(lin1,collect(0.0:0.5:4.0))\n\n    @test intlin == ([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], [0.0, 0.5, 1.0, 3.0, 5.0, 3.5, 2.0, 2.0, 2.0])\n\nend\n\n@testset \"Cubic Spline Type\" begin\n    x=[0,1,2,3,4]\n    y=[0,1,5,2,2]\n\n    @test typeof(cubicspline(x,y)) == CubicSpline\nend=\n\n", "meta": {"hexsha": "72b34b82ea3c9d4801bcc0430083593f5c0faca6", "size": 1587, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "m-lohmann/SSpline.jl", "max_stars_repo_head_hexsha": "0286d73bc475c06d56a18fd0b432e851c7a25dce", "max_stars_repo_licenses": ["MIT"], "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": "m-lohmann/SSpline.jl", "max_issues_repo_head_hexsha": "0286d73bc475c06d56a18fd0b432e851c7a25dce", "max_issues_repo_licenses": ["MIT"], "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": "m-lohmann/SSpline.jl", "max_forks_repo_head_hexsha": "0286d73bc475c06d56a18fd0b432e851c7a25dce", "max_forks_repo_licenses": ["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.0886075949, "max_line_length": 114, "alphanum_fraction": 0.5608065532, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7628082778175987}}
{"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\u2080::AbstractMatrix)\n\t\tM,N = size(F\u2080)\n\t\tR = diagm([ sum(F\u2080[i,:]) for i in 1:M ])\n\t\tH = diagm([ sum(F\u2080[:,j]) for j in 1:N ])\n\t\tW = (F\u2080 * H^-1)' * (R^-1 * F\u2080)\n\n\t\treturn W\n    end\n\n\tNBI(SymF\u2080::Symmetric, Nd::Int)::Matrix = NBI(SymF\u2080[1:Nd, Nd+1:end])\n\n\n\t\"\"\"\n\n\t\"\"\"\n\tfunction NWNBI(F\u2080::Matrix, \u03b2::AbstractFloat)::Matrix\n\t\tM,N = size(F\u2080)\n        R  = diagm([ sum(F\u2080[i,:])   for i in 1:M ])\n        H  = diagm([ sum(F\u2080[:,j])   for j in 1:N ])\n        H\u00b4 = diagm([ sum(F\u2080[:,j])^\u03b2 for j in 1:N ])\n        W\u00b4 = (F\u2080 * H^-1)' * (R^-1 * F\u2080 * H\u00b4^-1)\n\n        return W\u00b4\n    end\n\n\tNWNBI(SymF\u2080::Symmetric, Nd::Int, \u03b2::AbstractFloat) = NWNBI(SymF\u2080[1:Nd, Nd+1:end], \u03b2)\n\n\t\"\"\"\n\n\t\"\"\"\n\tfunction SDTNBI(F\u2080::AbstractMatrix)::Matrix\n\t\tk(A, x) = count(r->(r != 0), A[x,:])\t# Degree helper function\n\t\tn_nodes = size(F\u2080, 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\u2080, idx) > 0 ? F\u2080[idx,:] ./ k(F\u2080, 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": "using ModelingToolkit\r\nusing LinearAlgebra\r\n@variables a,b,c,d\r\nX = [a b;c d]\r\ndet(X)\r\nlu(X)\r\ninv(X)\r\n", "meta": {"hexsha": "186a3af06df3f34a52f667b6d94dd637beef9352", "size": 102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/operation_overloads.jl", "max_stars_repo_name": "ranjanan/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "c3d4cbe1de502c28c0d1f250f1bb87c2e799e3cd", "max_stars_repo_licenses": ["MIT"], "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/operation_overloads.jl", "max_issues_repo_name": "ranjanan/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "c3d4cbe1de502c28c0d1f250f1bb87c2e799e3cd", "max_issues_repo_licenses": ["MIT"], "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/operation_overloads.jl", "max_forks_repo_name": "ranjanan/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "c3d4cbe1de502c28c0d1f250f1bb87c2e799e3cd", "max_forks_repo_licenses": ["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.75, "max_line_length": 22, "alphanum_fraction": 0.6568627451, "num_tokens": 33, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7627495466774502}}
{"text": "\nfunction constant_contractor(X, y_val)\n    x, y = X\n    y = y \u2229 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 \u2229 (0..\u221e)\n\n    y = y \u2229 (x^2)\n    x = x \u2229 \u221ay\n\n    return IntervalBox(x, y)\nend\n\nsquare_neg = symmetrise(square_pos, reflect_x(0.0))\nsquare!(X::IntervalBox) = square_pos(X) \u222a 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 \u2229 (0..\u221e)\n\n    y = y \u2229 (x ^ 3)\n    x = x \u2229 Interval(y.lo ^ (1/3), y.hi^(1/3))   # not rigorous!\n\n    return x \u00d7 y\nend\n\ncube_neg = symmetrise(cube_pos, odd)\ncube!(X::IntervalBox) = cube_pos(X) \u222a 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,  \u22c5\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# \u0394u = f  in \u03a9\n# u  = 0  in \u2202\u03a9\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*\u03c0^2*sin(\u03c0*x[1])*sin(\u03c0*x[2])*sin(\u03c0*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\u03a9 = 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              \u2207v = jF.shape_gradient(Wh, q_point, i)\n              fe[i] += fh*v * d\u03a9\n              for j in 1:n_basefuncs\n                  \u2207u = jF.shape_gradient(Wh, q_point, j)\n                  Ke[i, j] += (\u2207v \u22c5 \u2207u) * d\u03a9\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, \u0394t)\n    Q = Q*\u0394t\n    R = R*\u0394t\n    A = A*\u0394t+I\n    B = B*\u0394t \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    \u03b1 :: T\n    \u03b2 :: T\n    R :: TR\n    Q :: TQ\nend\n\nfunction SimpleOG{T <: Real}(;B::Integer=10, M::Integer=5, \u03b1::T=0.5, \u03b2::T=0.9)\n\n    u(c) = c^\u03b1\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, \u03b1, \u03b2, 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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.02\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 88f0e5d6-3b0b-11eb-0af9-b964a1170ff3\nText(\"Using confint() function: $(confint(OneSampleTTest(xBar,s,n),alpha))\")\n\n# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.02\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u255088f0e5d6-3b0b-11eb-0af9-b964a1170ff3\n# \u255f\u2500475ff888-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\u2081 = length(crc.component[1].gauging)\n    n\u2082 = length(crc.component[2].gauging)\n    n = n\u2081 + n\u2082\n    p = 6\n    \n    @assert n>6 \n    \n    \u03c3\u0302\u00b2 = RatingCurves.var(crc)\n    \n    return n\u2081*log(\u03c3\u0302\u00b2[1]) + n\u2082*log(\u03c3\u0302\u00b2[2]) + p*log(n)\n    \nend\n\n\"\"\"\n    cint(crc::CompoundRatingCurve; nboot::Int=100, \u03b1::Real=.05)\n\nCompound rating curve parameter confidence intervals of level `1-\u03b1` obtained by a bootstrap sample of size `nboot`.\n\"\"\"\nfunction cint(crc::CompoundRatingCurve; nboot::Int=100, \u03b1::Real=.05)\n    \n    k = Vector{Float64}(undef, nboot)\n    \n    a\u2081 = Vector{Float64}(undef, nboot)\n    b\u2081 = Vector{Float64}(undef, nboot)\n    c\u2081 = Vector{Float64}(undef, nboot)\n    \n    a\u2082 = Vector{Float64}(undef, nboot)\n    b\u2082 = Vector{Float64}(undef, nboot)\n    c\u2082 = Vector{Float64}(undef, nboot)\n    \n    for i in 1:nboot\n       \n        G\u2081 = RatingCurves.bootstrap(crc.component[1].gauging)\n        G\u2082 = RatingCurves.bootstrap(crc.component[2].gauging)\n        crc\u1d62 = crcfit([G\u2081..., G\u2082...])\n        \n        k[i] = crc\u1d62.threshold[1]\n        \n        a\u2081[i] = crc\u1d62.component[1].a\n        b\u2081[i] = crc\u1d62.component[1].b\n        c\u2081[i] = crc\u1d62.component[1].c\n        \n        a\u2082[i] = crc\u1d62.component[2].a\n        b\u2082[i] = crc\u1d62.component[2].b\n        c\u2082[i] = crc\u1d62.component[2].c\n        \n    end\n    \n    M = hcat(\n            quantile(k, [\u03b1/2, 1-\u03b1/2]),\n            quantile(a\u2081, [\u03b1/2, 1-\u03b1/2]),\n            quantile(b\u2081, [\u03b1/2, 1-\u03b1/2]),\n            quantile(c\u2081, [\u03b1/2, 1-\u03b1/2]),\n            quantile(a\u2082, [\u03b1/2, 1-\u03b1/2]),\n            quantile(b\u2082, [\u03b1/2, 1-\u03b1/2]),\n            quantile(c\u2082, [\u03b1/2, 1-\u03b1/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, \u03b1::Real=0.05, rtol::Real=.05)\n\n`1-\u03b1` 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, \u03b1::Real=0.05, rtol::Real=.05)\n    \n    res = pintlog(crc, level, \u03b1, rtol)\n    \n    return exp.(res)\nend\n\n\n\n\"\"\"\n    pintlog(crc::CompoundRatingCurve, level::Real, \u03b1::Real=0.05, rtol::Real=.05)\n\n`1-\u03b1` 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 \u00b1 1.96*rtol` 95% of the time\n\"\"\"\nfunction pintlog(crc::CompoundRatingCurve, level::Real, \u03b1::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, \u03b1, 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],\" \u2264 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    \u03c3\u0302\u00b2 = Float64[]\n    \n    for rc in crc.component\n        push!(\u03c3\u0302\u00b2, RatingCurves.var(rc)[])\n    end\n    \n    return \u03c3\u0302\u00b2\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": "#Computed using Wolframalpha EllipticK and EllipticE functions.\n@testset \"elliptic integrals\" begin\n    @testset \"complete of 1st kind\" begin\n        @test ellipk(-0.5)  \u2248 1.41573720842595619           rtol=2*eps()\n        @test ellipk(0)     \u2248 1.570796326794896619231322    rtol=2*eps()\n        @test ellipk(0.01)  \u2248 1.57474556151735595           rtol=2*eps()\n        @test ellipk(0.17)  \u2248 1.6448064907988806            rtol=2*eps()\n        @test ellipk(0.25)  \u2248 1.685750354812596             rtol=2*eps()\n        @test ellipk(0.33)  \u2248 1.73186477825209792           rtol=2*eps()\n        @test ellipk(0.45)  \u2248 1.81388393681698264           rtol=2*eps()\n        @test ellipk(0.5)   \u2248 1.854074677301371918          rtol=2*eps()\n        @test ellipk(0.69)  \u2248 2.0608816467301313            rtol=2*eps()\n        @test ellipk(0.75)  \u2248 2.15651564749964323           rtol=2*eps()\n        @test ellipk(0.84)  \u2248 2.3592635547450067            rtol=2*eps()\n        @test ellipk(0.88)  \u2248 2.492635323239715564          rtol=2*eps()\n        @test ellipk(0.92)  \u2248 2.683551406315229344          rtol=2*eps()\n        @test ellipk(1.0) == Inf\n        @test ellipk(Float16(0.92)) \u2248 2.683551406315229344  rtol=2*eps(Float16)\n        @test ellipk(Float32(0.92)) \u2248 2.683551406315229344  rtol=2*eps(Float32)\n        @test_throws MethodError ellipk(BigFloat(0.5))\n        @test_throws DomainError ellipk(1.1)\n    end\n\n    @testset \"complete of 2nd kind\" begin\n        @test ellipe(-0.1)  \u2248 1.6093590249375295            rtol=2*eps()\n        @test ellipe(0)     \u2248 1.570796326794896619231322    rtol=2*eps()\n        @test ellipe(0.01)  \u2248 1.5668619420216682            rtol=2*eps()\n        @test ellipe(0.15)  \u2248 1.5101218320928197            rtol=2*eps()\n        @test ellipe(0.21)  \u2248 1.4847605813318776            rtol=2*eps()\n        @test ellipe(0.3)   \u2248 1.4453630644126652            rtol=2*eps()\n        @test ellipe(0.42)  \u2248 1.3898829914929717            rtol=2*eps()\n        @test ellipe(0.5)   \u2248 1.3506438810476755            rtol=2*eps()\n        @test ellipe(0.66)  \u2248 1.2650125751607508            rtol=2*eps()\n        @test ellipe(0.76)  \u2248 1.2047136418292115            rtol=2*eps()\n        @test ellipe(0.8)   \u2248 1.17848992432783852           rtol=2*eps()\n        @test ellipe(0.865) \u2248 1.1322436887003925            rtol=2*eps()\n        @test ellipe(0.99)  \u2248 1.0159935450252239            rtol=2*eps()\n        @test ellipe(1.0)   \u2248 1.00                          rtol=2*eps()\n        @test ellipe(Float16(0.865)) \u2248 1.1322436887003925   rtol=2*eps(Float16)\n        @test ellipe(Float32(0.865)) \u2248 1.1322436887003925   rtol=2*eps(Float32)\n        @test_throws MethodError ellipe(BigFloat(-1))\n        @test_throws DomainError ellipe(1.2)\n    end\nend\n", "meta": {"hexsha": "89033d2a811dd49928e4b1d831a48451846b499d", "size": 2728, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ellip.jl", "max_stars_repo_name": "augustt198/SpecialFunctions.jl", "max_stars_repo_head_hexsha": "1bb0913fc667d6aebbc2e29fc111cd3cb8629771", "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": "test/ellip.jl", "max_issues_repo_name": "devmotion/SpecialFunctions.jl", "max_issues_repo_head_hexsha": "1bb0913fc667d6aebbc2e29fc111cd3cb8629771", "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": "test/ellip.jl", "max_forks_repo_name": "devmotion/SpecialFunctions.jl", "max_forks_repo_head_hexsha": "1bb0913fc667d6aebbc2e29fc111cd3cb8629771", "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": 60.6222222222, "max_line_length": 79, "alphanum_fraction": 0.5659824047, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.762685459417872}}
{"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\u03b8  = [0, 0.5] # true theta for generating data\n(y, x) = LogitDGP(n, \u03b8) # generate the data\n\n# now define things for estimation\nmodel = \u03b8 -> logit(\u03b8, y, x)\n\u03b8start = 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\u03b8hat, objvalue, V, converged = mleresults(model, \u03b8start, \"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": "import RowEchelon\n\n#=\nHomework 5\nSection 2.2\nProblem 5\n=#\n\n# Adapt system into a matrix\nA = [8 6 ; 5 4]\nb = [2 ;-1]\n\n# Find Ax = b with x = invA(b)\ninvA = inv(A)\nx = invA*b\n\nprintln(\"The solution is:\")\nprint(\"x = \")\nprintln(x)\n", "meta": {"hexsha": "ee49e2c5084cb03f58a44443890ae5c26f62d21b", "size": 227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW5_S2.2_P5.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.2_P5.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.2_P5.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": 11.35, "max_line_length": 30, "alphanum_fraction": 0.6035242291, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7626087563307283}}
{"text": "using PolyChaos, Test, QuadGK\nimport LinearAlgebra: norm\n\nnames = [GaussOrthoPoly, Uniform01OrthoPoly, LogisticOrthoPoly, LegendreOrthoPoly, HermiteOrthoPoly, LaguerreOrthoPoly]\ndeg = 10\ntol = 1e-7\n\n@testset \"Norms of orthgonal polynomials ($names)\" begin\n    for op in names\n        opq = op(deg)\n        s = computeSP2(opq)\n        t = [ quadgk(x->evaluate(d,x,opq)^2*opq.measure.w(x), opq.measure.dom...; order = max(10,10d))[1] for d=0:deg ]\n        u = computeSP2(deg,opq)\n\n        @test isapprox(norm(s-t,Inf)/maximum(s), 0; atol = tol)\n        @test isapprox(norm(s-u,Inf)/maximum(s), 0; atol = tol)\n        @test isapprox(computeSP([0, 0, 0], opq), t[1]; atol = tol)\n        @test isapprox(computeSP([0, 0, 0, 1], opq), 0; atol = tol)\n        @test isapprox(computeSP([0, 0, 0, deg-1, deg-1], opq), s[deg]; atol = tol)\n    end\nend\n\na, b = 1.1:0.5:4, 1.1:0.5:4\nnames = [Beta01OrthoPoly, JacobiOrthoPoly, genHermiteOrthoPoly, genLaguerreOrthoPoly]\n\n@testset \"Norms of orthgonal polynomials ($names)\" begin\n    for \u03b1 in a, \u03b2 in b, name in names\n        opq = \n        if name in [Beta01OrthoPoly, JacobiOrthoPoly]\n            name(deg, \u03b1, \u03b2)\n        elseif name in [genHermiteOrthoPoly, genLaguerreOrthoPoly]\n            name(deg, \u03b1)\n        end\n        \n        s = computeSP2(opq)\n        t = [ quadgk(x->evaluate(d,x,opq)^2*opq.measure.w(x), opq.measure.dom...; order = max(10,10d))[1] for d=0:deg ]\n        u = computeSP2(deg,opq)\n        @test isapprox(norm(s-t,Inf)/maximum(s), 0; atol = tol)\n        @test isapprox(norm(s-u,Inf)/maximum(s), 0; atol = tol)\n        @test isapprox(computeSP([0, 0, 0], opq), t[1]; atol = tol)\n        @test isapprox(computeSP([0, 0, 0, 1], opq), 0; atol = tol)\n        @test isapprox(computeSP([0, 0, 0, deg-1, deg-1], opq), s[deg]; atol = tol)\n    end\nend\n", "meta": {"hexsha": "be89e939bf94953685b8c2e161ae4aecd12cc8a6", "size": 1800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/scalarproducts.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PolyChaos.jl-8d666b04-775d-5f6e-b778-5ac7c70f65a3", "max_stars_repo_head_hexsha": "2e60a0f205c7f32c3987b5d9e1e9ca271fca3186", "max_stars_repo_licenses": ["MIT"], "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/scalarproducts.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PolyChaos.jl-8d666b04-775d-5f6e-b778-5ac7c70f65a3", "max_issues_repo_head_hexsha": "2e60a0f205c7f32c3987b5d9e1e9ca271fca3186", "max_issues_repo_licenses": ["MIT"], "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/scalarproducts.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PolyChaos.jl-8d666b04-775d-5f6e-b778-5ac7c70f65a3", "max_forks_repo_head_hexsha": "2e60a0f205c7f32c3987b5d9e1e9ca271fca3186", "max_forks_repo_licenses": ["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": 119, "alphanum_fraction": 0.6033333333, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7626087531269564}}
{"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": "using FEASTSolver\nusing LinearAlgebra\nusing DelimitedFiles\nusing Random\n\n\n# A = diagm(-1 => fill(-1.0, 99), 0 => fill(2.0, 100), 1 => fill(-1.0, 99))\nRandom.seed!(1551)\nA = randn(ComplexF64, 100, 100)\nC, R = complex(0.0, 0.0), 2.0 # contour\n# C, R = complex(0.1, 0.0), 0.1 # contour\nX = rand(ComplexF64, 100, 20) # initial subspace\n\n# contour = circular_contour_trapezoidal(C, R, 16)\n# contour = rectangular_contour_gauss(-R-im*R, R + R*im, 16)\ncontour = rectangular_contour_trapezoidal(-R-im*R, R + R*im, 32)\nwritedlm(\"test/data/contour.dat\", zip(real.(contour.nodes), imag.(contour.nodes)))\nwritedlm(\"test/data/weights.dat\", zip(real.(contour.weights), imag.(contour.weights)))\n\n# e, v, res = feast!(X, A, c=C, r=R, nodes=8, debug=true, \u03f5=10e-15)\ne, v, res = feast!(X, A, contour, debug=true, \u03f5=10e-14)\n\n# info(e,v,res,C,R)\nconvergence_info(e,v,res,contour)\ndisplay(e)\ne = eigvals(A)\nprintln()\ndisplay(e[abs.(e) .< R])\n", "meta": {"hexsha": "cfe2360bd1389f733168633f8634c75ff7ba9fed", "size": 921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/contour_random.jl", "max_stars_repo_name": "rleegates/FEASTSolver.jl", "max_stars_repo_head_hexsha": "1f226df0ea72ae3cb2eca782439ae672e8488a85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-07-03T21:42:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T11:53:56.000Z", "max_issues_repo_path": "test/contour_random.jl", "max_issues_repo_name": "rleegates/FEASTSolver.jl", "max_issues_repo_head_hexsha": "1f226df0ea72ae3cb2eca782439ae672e8488a85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-06-23T14:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-31T15:56:11.000Z", "max_forks_repo_path": "test/contour_random.jl", "max_forks_repo_name": "rleegates/FEASTSolver.jl", "max_forks_repo_head_hexsha": "1f226df0ea72ae3cb2eca782439ae672e8488a85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-16T09:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-16T09:08:25.000Z", "avg_line_length": 31.7586206897, "max_line_length": 86, "alphanum_fraction": 0.667752443, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7626087426408356}}
{"text": "#=\na ball-packing type problem: choose centers and radii of m 2-norm balls into a box [0, 1]\u207f in\nn-dimensional space, maximizing the sum of the radii\n\nconstraints are nonconvex, so use SOS2 or PWL techniques with extended formulations\n=#\n\nstruct BallPacking <: ExampleInstance\n    m::Int # number of balls\n    n::Int # dimension of space\n    pwl::PWLSOS2 # type of piecewise linear SOS2 formulation to use\n    num_pts::Int # number of points per piecewise linearization\nend\n\nfunction build(inst::BallPacking)\n    (m, n, num_pts) = (inst.m, inst.n, inst.num_pts)\n    @assert m >= 2\n    @assert n >= 2\n    @assert isodd(num_pts) # ensures 0 is included\n    pts = collect(range(-1.0, 1.0, length = num_pts))\n    @assert 0.0 in pts\n    f_pts = abs2.(pts)\n\n    # build model\n    model = JuMP.Model()\n    JuMP.@variable(model, C[1:m, 1:n]) # centers\n    JuMP.@variable(model, 0 <= R[1:m] <= 0.5) # radii\n    JuMP.@objective(model, Max, sum(R))\n\n    JuMP.@constraints(model, begin\n        # balls inside box\n        [i in 1:m, k in 1:n], C[i, k] >= R[i]\n        [i in 1:m, k in 1:n], C[i, k] <= 1 - R[i]\n        # break some symmetry TODO more\n        [i in 1:(m - 1)], C[i, 1] <= C[i + 1, 1]\n    end)\n\n    # for each pair of balls i < j, need R\u1d62 + R\u2c7c \u2264 \u2016C\u1d62 - C\u2c7c\u2016\n    for i in 1:m, j in (i + 1):m\n        # EF variables and linear constraint\n        \u03bb = JuMP.@variable(model, [1:n])\n        Rij = JuMP.@variable(model)\n        JuMP.@constraint(model, Rij == R[i] + R[j])\n        JuMP.@constraint(model, Rij <= sum(\u03bb))\n\n        # 3-dim cone constraints; note C\u1d62 - C\u2c7c \u2208 [-1, 1]\u207f, \u2016C\u1d62 - C\u2c7c\u2016 \u2264 \u221an, Rij \u2208 [0, 1]\n        for k in 1:n\n            # auxiliary variables and SOS2 formulation\n            \u03c3 = JuMP.@variable(model, [1:length(pts)], lower_bound = 0)\n            PWL_SOS2(inst.pwl, model, \u03c3, 1.0)\n\n            # data constraints\n            JuMP.@constraints(model, begin\n                dot(\u03c3, f_pts) == \u03bb[k]\n                sum(\u03c3) == Rij\n                dot(\u03c3, pts) == C[i, k] - C[j, k]\n            end)\n        end\n    end\n\n    # save for use in tests\n    model.ext[:R] = R\n    model.ext[:C] = C\n\n    return model\nend\n\nfunction test_extra(inst::BallPacking, model::JuMP.Model)\n    stat = JuMP.termination_status(model)\n    @test stat in OPT_OR_LIMIT\n    (stat == MOI.OPTIMAL) || return\n\n    R = JuMP.value.(model.ext[:R])\n    C = JuMP.value.(model.ext[:C])\n    # check feasibility for linear constraints\n    tol = eps()^0.4\n    @test all(-tol .<= R .<= 0.5 + tol)\n    @test all(-tol .<= C .<= 1 + tol)\n    # check near-feasibility for nonconvex constraints\n    tol_loose = eps()^0.1\n    approxij(i, j) = (R[i] + R[j] <= norm(C[i, :] - C[j, :]) + tol_loose)\n    @test all(approxij(i, j) for i in 1:(inst.m) for j in 1:(i - 1))\n    return\nend\n", "meta": {"hexsha": "7d97a5cb856b07a6be4a031b018353f2fd7e316e", "size": 2741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ballpacking/model.jl", "max_stars_repo_name": "chriscoey/PajaritoExtras.jl", "max_stars_repo_head_hexsha": "fef84ef356d7e1db46efc894433805b7855f3bbe", "max_stars_repo_licenses": ["MIT"], "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/ballpacking/model.jl", "max_issues_repo_name": "chriscoey/PajaritoExtras.jl", "max_issues_repo_head_hexsha": "fef84ef356d7e1db46efc894433805b7855f3bbe", "max_issues_repo_licenses": ["MIT"], "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/ballpacking/model.jl", "max_forks_repo_name": "chriscoey/PajaritoExtras.jl", "max_forks_repo_head_hexsha": "fef84ef356d7e1db46efc894433805b7855f3bbe", "max_forks_repo_licenses": ["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.2470588235, "max_line_length": 93, "alphanum_fraction": 0.5669463699, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7626087398744663}}
{"text": "\"\"\"\n    Chisq(\u03bd)\nThe *Chi squared distribution* (typically written \u03c7\u00b2) with `\u03bd` 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 `\u03bd` is an integer, then it is the distribution of the sum of squares of `\u03bd` 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    \u03bd::T\n    Chisq{T}(\u03bd::T) where {T} = new{T}(\u03bd)\nend\n\nfunction Chisq(\u03bd::T) where {T <: Real}\n    @check_args(Chisq, \u03bd > zero(\u03bd))\n    return Chisq{T}(\u03bd)\nend\n\nChisq(\u03bd::T, ::NoArgCheck) where {T <: Real} = Chisq{T}(\u03bd)\nChisq(\u03bd::Integer) = Chisq(float(\u03bd))\n\n@distr_support Chisq 0.0 Inf\n\n#### Parameters\n\ndof(d::Chisq) = d.\u03bd\nparams(d::Chisq) = (d.\u03bd,)\n@inline partype(d::Chisq{T}) where {T<:Real} = T\n\n### Conversions\nconvert(::Type{Chisq{T}}, \u03bd::Real) where {T<:Real} = Chisq(T(\u03bd))\nconvert(::Type{Chisq{T}}, d::Chisq{S}) where {T <: Real, S <: Real} = Chisq(T(d.\u03bd))\n\n\n#### Statistics\n\nmean(d::Chisq) = d.\u03bd\n\nvar(d::Chisq) = 2d.\u03bd\n\nskewness(d::Chisq) = sqrt(8 / d.\u03bd)\n\nkurtosis(d::Chisq) = 12 / d.\u03bd\n\nmode(d::Chisq{T}) where {T<:Real} = d.\u03bd > 2 ? d.\u03bd - 2 : zero(T)\n\nfunction median(d::Chisq; approx::Bool=false)\n    if approx\n        return d.\u03bd * (1 - 2 / (9 * d.\u03bd))^3\n    else\n        return quantile(d, 1//2)\n    end\nend\n\nfunction entropy(d::Chisq)\n    h\u03bd = d.\u03bd/2\n    h\u03bd + logtwo + lgamma(h\u03bd) + (1 - h\u03bd) * digamma(h\u03bd)\nend\n\n\n#### Evaluation\n\n@_delegate_statsfuns Chisq chisq \u03bd\n\nmgf(d::Chisq, t::Real) = (1 - 2 * t)^(-d.\u03bd/2)\n\ncf(d::Chisq, t::Real) = (1 - 2 * im * t)^(-d.\u03bd/2)\n\ngradlogpdf(d::Chisq{T}, x::Real) where {T<:Real} =  x > 0 ? (d.\u03bd/2 - 1) / x - 1//2 : zero(T)\n\n\n#### Sampling\n\nrand(rng::AbstractRNG, d::Chisq) =\n    (\u03bd = d.\u03bd; rand(rng, Gamma(\u03bd / 2.0, 2.0one(\u03bd))))\n\nsampler(d::Chisq) = (\u03bd = d.\u03bd; sampler(Gamma(\u03bd / 2.0, 2.0one(\u03bd))))\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\u00d71^2\n# 15 = 7 + 2\u00d72^2\n# 21 = 3 + 2\u00d73^2\n# 25 = 7 + 2\u00d73^2\n# 27 = 19 + 2\u00d72^2\n# 33 = 31 + 2\u00d71^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": "function vandermonde_error(n)\n    a = rand(n)\n    x = rand(n)\n    y = zeros(n)\n    for i = 1:n\n        y[i] = sum(ntuple(j->a[j]*x[i]^(j-1), n))\n    end\n    c = vandermonde(x, y)\n    return maximum(abs.(c - a))\nend\n\nfor n = 1:5\n    @test vandermonde_error(n) < 0.01\nend\n", "meta": {"hexsha": "ef92c44d5f657747b557b68f17fef6160c8cb75e", "size": 270, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_vandermonde.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": "test/test_vandermonde.jl", "max_issues_repo_name": "wordsworthgroup/BasicInterpolators.jl", "max_issues_repo_head_hexsha": "1a43e6e657377ee9de53c721cf58141363036e78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-04T19:19:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-12T01:44:01.000Z", "max_forks_repo_path": "test/test_vandermonde.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": 18.0, "max_line_length": 49, "alphanum_fraction": 0.5259259259, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.762570344184364}}
{"text": "using Base.Test\ninclude(\"splinesSerial.jl\") \n\n@testset \"splines\" begin\n\tpoint = [0.5, 0.7, 1.2]\n\tV = [1.0,3.4,5.5,6.9,2.4,8.0];\n\tFV = [[1,2,4],[2,3,5],[3,5,6],[4,5,7],[5,7,8],[6,8,9]];\n\t@testset \"sel\" begin\n \t\t@test typeof(sel(1)(V))==Float64\n\t\t@test typeof(sel(1)(FV))==Array{Int64,1}\n\t\t@test sel(4)(V)==6.9\n\t\t@test sel(5)(FV)==[5,7,8]\n\tend\n\t@testset \"larBernsteinBasis\" begin\n\t\t@test typeof(larBernsteinBasis(sel(1),3)([0.5,2,7.3]))==Array{Float64,1}\n\t\t@test typeof(larBernsteinBasis(sel(5), 6)(V))==\n\t\tArray{Float64,1}\n\t\tH=[1.2,3.4,5.6,7.8,9.0]\n\t\tF=larBernsteinBasis(sel(4),5)(H)\n\t\t@test length(F)==6\n\tend\n\n\t@testset \"larTensorProdSurface\" begin\n\t\tcontrolpoints = [[[0,0,0],[2,-4,2]],[[0,3,1],[4,0,0]]]\n\t\tbasis = larBernsteinBasis(sel(1), 1)\n\t\tpoint = [0.5, 2, 7.3]\n\t\tT=larTensorProdSurface([basis, basis], controlpoints)(point)\n\t\t@test typeof(T)==Array{Float64,1}\n\t\t@test length(T)==3\n\tend\n\n\t@testset \"larBilinearSurface\" begin\n\t\tcontrolpoints = [[[0,0,0],[2,-4,2]],[[0,3,1],[4,0,0]]]\n\t\tBil=larBilinearSurface(controlpoints)([0.5,0.7])\n\t\t@test typeof(Bil)==Array{Float64,1}\n\t\t@test length(Bil)==3\n\tend\n\n\t@testset \"larBiquadraticSurface\" begin\n\t\tcontrolpoints = [[[0,0,0],[2,0,1],[3,1,1]],[[1,3,-1],[2,2,0],[3,2,0]],[[-2,4,0],[2,5,1],[1,3,2]]]\n\t\tmapping = larBiquadraticSurface(controlpoints)([0.7, 0.2])\n\t\t@test typeof(mapping)==Array{Float64,1}\n\t\t@test length(mapping)==3\n\tend\n\n\t@testset \"larBicubicSurface\" begin\n\t\tcontrolpoints = [[[0,0,0], [0,3,4], [0,6,3], [0,10,0]],[[3,0,2], [2,2.5,5], [3,6,5], [4,8,2]],[[6,0,2], [8,3,5], [7,6,4.5], [6,10,2.5]],[[10,0,0], [11,3,4], [11,6,3], [10,9,0]]]\n\t\tmapping = larBicubicSurface(controlpoints)([0.7,0.2])\n\t\t@test typeof(mapping)==Array{Float64,1}\n\t\t@test length(mapping)==3\t\n\tend\n\n\t@testset \"larBezier\"begin\n\t\tcontroldata = [[0,1],[0,0],[1,1],[1,0]]\n\t\tU = sel(2)\n\t\t@test typeof(larBezier(U, controldata)(point))==\n\t\tArray{Float64,1}\n\t\tG=larBezier(U, controldata)(point)\n\t\t@test length(G)==2\n\t\t@test typeof(larBezier(sel(3), controldata)(point))==\n\t\tArray{Float64,1}\n\t\tF=larBezier(sel(3), controldata)(point)\n\t\t@test length(F)==2\n\tend\n\n\t@testset \"larBezierCurve\" begin\n\t\tcontroldata = [[1,2,-5],[2,-4,2]]\n\t\t@test typeof(larBezierCurve(controldata)(point))==Array{Float64,1}\n\t\t@test length(larBezierCurve(controldata)(point))==3\t\t\n\tend\n\n\t@testset \"bsplineBasis\" begin\n\t\tknots = [0,0,0,1,1,2,2,3,3,4,4,4]\n\t\tncontrols = 9\n\t\tdegree = 2\n\t\tH=bsplineBasis(degree, knots, ncontrols)([0.7,2.5,3.0])\n\t\t@test typeof(bsplineBasis(degree, knots, ncontrols)([0.7,2.5,3.0]))==Array{Float64,1}\n\t\t@test length(bsplineBasis(degree, knots, ncontrols)([0.7,2.5,3.0]))==9\t\n\tend\n\t\n\t\n\t@testset \"larCoonsPatch\" begin\n\t\tSu0 = larBezier(sel(1), [[0,0,0],[10,0,0]])\n\t\tSu1 = larBezier(sel(1), [[0,10,0],[2.5,10,3],[5,10,-3],[7.5,10,3],[10,10,0]])\n\t\tSv0 = larBezier(sel(1), [[0,0,0],[0,0,3],[0,10,3],[0,10,0]])\n\t\tSv1 = larBezier(sel(2), [[10,0,0],[10,5,3],[10,10,0]])\n\t\tpoint = [0.7, 0.2]\n\t\tout = larCoonsPatch([Su0,Su1,Sv0,Sv1])(point)\n\t\t@test typeof(out)==Array{Float64,1}\n\tend\n\n\t@testset \"t_bspline\"begin\n\t\tb1 = larBezier(S1, [[0,1,0],[0,1,5]])\n\t\tb2 = larBezier(S1, [[0,0,0],[0,0,5]])\n\t\tb3 = larBezier(S1, [[1,0,0],[2,-1,2.5],[1,0,5]])\n\t\tb4 = larBezier(S1, [[1,1,0],[1,1,5]])\n\t\tb5 = larBezier(S1, [[0,1,0],[0,1,5]])\n\t\tcontrols = [b1, b2, b3, b4, b5]\n\t\tknots = [0,1,2,3,4,5,6,7]           # periodic B-spline\n\t\tknots = [0,0,0,1,2,3,3,3]           # non-periodic B-spline\n\t\ttbspline = t_bspline(S2, 2, knots, controls) \n\t\tB=tbspline([0.7, 0.2])\n\t\t@test typeof(B)==Array{Float64,1}\n\t\t@test length(B)==3\n\tend\n\n\n\t@testset \"t_nurbs\" begin\n\t\tknots = [0,0,0,1,1,2,2,3,3,4,4,4]\n\t\tp=sqrt(2)/2.0\n\t\tcontrols = [[-1,0,1], [-p,p,p], [0,1,1], [p,p,p],[1,0,1], [p,-p,p],[0,-1,1], [-p,-p,p], [-1,0,1]]\n\t\tc1 = larBezier(S1, [[-1,0,0,1],[-1,0,1,1]])\n\t\tc2 = larBezier(S1, [[-p,p,0,p],[-p,p,p,p]])\n\t\tc3 = larBezier(S1, [[0,1,0,1],[0,1,1,1]])\n\t\tc4 = larBezier(S1, [[p,p,0,p],[p,p,p,p]])\n\t\tc5 = larBezier(S1, [[1,0,0,1],[1,0,1,1]])\n\t\tc6 = larBezier(S1, [[p,-p,0,p],[p,-p,p,p]])\n\t\tc7 = larBezier(S1, [[0,-1,0,1],[0,-1,1,1]])\n\t\tc8 = larBezier(S1, [[-p,-p,0,p],[-p,-p,p,p]])\n\t\tc9 = larBezier(S1, [[-1,0,0,1],[-1,0,1,1]])\n\t\tcontrols = [c1,c2,c3,c4,c5,c6,c7,c8,c9]         \n\t\ttnurbs = t_nurbs(S2,2,knots,controls)\n\t\tN=tnurbs([0.7, 0.2])\n\t\t@test typeof(N)==Array{Float64,1}\n\t\t@test length(N)==3\n\tend\n\t\nend\n\n\n\n", "meta": {"hexsha": "f61a1c57e6b59c6cf2e0d37888b735d8303ddf77", "size": 4303, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unitTestSerial.jl", "max_stars_repo_name": "FrancescaValletti/Splines_Santorsola_Valletti", "max_stars_repo_head_hexsha": "79cf4e816dbaad744db7f90720b0bb562d100dae", "max_stars_repo_licenses": ["MIT"], "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/unitTestSerial.jl", "max_issues_repo_name": "FrancescaValletti/Splines_Santorsola_Valletti", "max_issues_repo_head_hexsha": "79cf4e816dbaad744db7f90720b0bb562d100dae", "max_issues_repo_licenses": ["MIT"], "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/unitTestSerial.jl", "max_forks_repo_name": "FrancescaValletti/Splines_Santorsola_Valletti", "max_forks_repo_head_hexsha": "79cf4e816dbaad744db7f90720b0bb562d100dae", "max_forks_repo_licenses": ["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.5984848485, "max_line_length": 179, "alphanum_fraction": 0.580292819, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7625248686627383}}
{"text": "#=\nTake the number 192 and multiply it by each of 1, 2, and 3:\n\n192 \u00d7 1 = 192\n192 \u00d7 2 = 384\n192 \u00d7 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, \u03b8) = [cos(\u03b8) -sin(\u03b8);sin(\u03b8) cos(\u03b8)] * R\n\nfunction DragonFractal(;order, \u03b8, points)\n    \u03b8\u2081 = \u03b8[1]; \u03b8\u2082 = \u03b8[2]\n    for num in 1:order\n        i = 1\n        while i < length(points)\n            point = (points[i+1] - points[i]) * sin(abs(\u03b8\u2081))\n            point = Rotation(point, \u03b8\u2081)  + points[i]\n            insert!(points,i+1,point)\n            i += 2\n            point = (points[i+1] - points[i]) * sin(abs(\u03b8\u2082))\n            point = Rotation(point, \u03b8\u2082)  + 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                    :\u03b8 => [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                    :\u03b8 => [-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\u00e9vy-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(\u03bc::Real, \u03c3::Real, C::Real)\n\tfunction gausx(x)\n\t\treturn C * pdf(Normal(\u03bc, \u03c3,), x)\n\tend\n\treturn gausx\nend\n\nfunction gausg2(\u03bc1::Real, \u03c31::Real, C1::Real, \u03bc2::Real, \u03c32::Real, C2::Real)\n\tfunction gausx(x)\n\t\treturn C1 * pdf(Normal(\u03bc1, \u03c31,), x) + C2 * pdf(Normal(\u03bc2, \u03c32,), 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, \u03bc, \u03c3  = cfit(gauss1, c, w, p0_bounds, lb, ub)\n\tgx = gausg(\u03bc, \u03c3, CC)\n\treturn FGauss([\u03bc], [\u03c3], [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\u03c3 = std(x)\n\t@debug \"gfit_gauss_fm: \u03c3 = $\u03c3\"\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, \u03c3/10.0]\n    ub = [1.0e+6*sum(w),  \u03c3 * 10.0]\n    p0_bounds = [0.0, \u03c3]\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    \u03c3Y  = sqrt.(Y)\n    lbl = @sprintf \" \u03bc=%5.1f, \u03c3 =%5.1f \" fg.mu[1] fg.std[1]\n    lbl =string(\"gaussian fit:\\n\", lbl)\n    p = scatter(X, Y, yerror=\u03c3Y,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 \"\u03c3 =%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 \"\u03c3t =%4.1f mm, \u03c3 =%4.1f mm\" fg.std[1] fg.std[2]\n\tst  = @sprintf \"\u03c3t =%4.1f mm \" fg.std[1]\n\tsf  = @sprintf \"\u03c3  =%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": "using DiffEqSensitivity, Test, QuasiMonteCarlo\n\n\nfunction ishi_batch(X)\n    A= 7\n    B= 0.1\n    @. sin(X[1,:]) + A*sin(X[2,:])^2+ B*X[3,:]^4 *sin(X[1,:])\nend\nfunction ishi(X)\n    A= 7\n    B= 0.1\n    sin(X[1]) + A*sin(X[2])^2+ B*X[3]^4 *sin(X[1])\nend\n\nfunction linear_batch(X)\n    A= 7\n    B= 0.1\n    @. A*X[1,:]+B*X[2,:]\nend\nfunction linear(X)\n    A= 7\n    B= 0.1\n    A*X[1]+B*X[2]\nend\n\nn = 600000\nlb = -ones(4)*\u03c0\nub = ones(4)*\u03c0\nsampler = SobolSample()\nA,B = QuasiMonteCarlo.generate_design_matrices(n,lb,ub,sampler)\n\nres1 = gsa(ishi,Sobol(order=[0,1,2]),A,B)\nres2 = gsa(ishi_batch,Sobol(),A,B,batch=true)\n\n@test res1.S1 \u2248 [0.3139335358797363, 0.44235918402206326, 0.0, 0.0] atol=1e-4\n@test res2.S1 \u2248 [0.3139335358797363, 0.44235918402206326, 0.0, 0.0] atol=1e-4\n\n@test res1.ST \u2248 [0.5576009081644232, 0.44237102330046346, 0.24366241588532553, 0.0] atol=1e-4\n@test res2.ST \u2248 [0.5576009081644232, 0.44237102330046346, 0.24366241588532553, 0.0] atol=1e-4\n\n\nres1 = gsa(ishi,eFAST(),[[lb[i],ub[i]] for i in 1:4],n=15000)\nres2 = gsa(ishi_batch,eFAST(),[[lb[i],ub[i]] for i in 1:4],n=15000,batch=true)\n\n@test res1.S1 \u2248 [0.307599  0.442412  3.0941e-25  3.42372e-28] atol=1e-4\n@test res2.S1 \u2248 [0.307599  0.442412  3.0941e-25  3.42372e-28] atol=1e-4\n\n@test res1.ST \u2248 [0.556244  0.446861  0.239259  0.027099] atol=1e-4\n@test res2.ST \u2248 [0.556244  0.446861  0.239259  0.027099] atol=1e-4\n\nm = gsa(ishi, Morris(num_trajectory=500000), [[lb[i],ub[i]] for i in 1:4])\n@test m.means_star[1,:] \u2248 [2.25341,4.40246,2.5049,0.0] atol = 5e-2\n@test m.means[1, :] \u2248 [-0.416876, -0.0077712, -0.015714,  0.0] atol = 5e-2\n@test m.means_star[1,:] \u2248 [2.25341,4.40246,2.5049,0.0] atol = 5e-2\n", "meta": {"hexsha": "ce6ca98b61c505416f6ed19019e2b4326483510f", "size": 1660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gsa.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/gsa.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/gsa.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": 30.1818181818, "max_line_length": 93, "alphanum_fraction": 0.6331325301, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465044347828, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7625248508193716}}
{"text": "function log_utility(;\u03b2 = 0.9,\n                      \u03c8 = 0.69,\n                      \u03a0 = 0.5 * ones(2, 2),\n                      G = [0.1, 0.2],\n                      \u0398 = ones(2),\n                      transfers = false)\n    # Derivatives of utility function\n    U(c,n) = log(c) + \u03c8 * log(1 - n)\n    Uc(c,n) = 1 ./ c\n    Ucc(c,n) = -c.^(-2.0)\n    Un(c,n) = -\u03c8 ./ (1.0 - n)\n    Unn(c,n) = -\u03c8 ./ (1.0 - n).^2.0\n    n_less_than_one = true\n    return Model(\u03b2, \u03a0, G, \u0398, 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": "using Test, LinearFractionalTransformations\n\nf = LFT(1,0,0,1)  # identity\n@test f(1+im) == 1+im\n@test f[1+im] == 1+im\n\n\nf = LFT(2,0,0,1)  # f(x) = 2x\n@test f(-im) == -2im\n\ng = inv(f)\n@test g(im) == 0.5im\n\ng = f*f\n@test g(2-im) == 4*(2-im)\n\nf = LFT(1,2+im, 3,0, 1-im,5)\n@test f(1)==2+im\n@test f(3)==0\n@test f(1-im)==5\n\ng = inv(f)\n@test g(0) == 3\n\n@test LFT() == g*f\n\nf = LFT(0,1,1,0)\n@test f(Inf) == 0\n@test isinf(f(0))\n\n\nf = LFT(3-im, 2+im, 6)\n@test f(3-im) == 0\n@test f(2+im) == 1\n@test isinf(f(6))\n", "meta": {"hexsha": "056c160f924bcf6d93e2225840c107d219960922", "size": 500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/LinearFractionalTransformations.jl-8bac944d-a3a1-5789-a62e-204935847c3c", "max_stars_repo_head_hexsha": "c735208938d95068b2343097b685af7cf20bc39a", "max_stars_repo_licenses": ["MIT"], "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/LinearFractionalTransformations.jl-8bac944d-a3a1-5789-a62e-204935847c3c", "max_issues_repo_head_hexsha": "c735208938d95068b2343097b685af7cf20bc39a", "max_issues_repo_licenses": ["MIT"], "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/LinearFractionalTransformations.jl-8bac944d-a3a1-5789-a62e-204935847c3c", "max_forks_repo_head_hexsha": "c735208938d95068b2343097b685af7cf20bc39a", "max_forks_repo_licenses": ["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.8888888889, "max_line_length": 43, "alphanum_fraction": 0.518, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273499, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7625231024562897}}
{"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. * \u221a(5.) ) / 20.\n        b = ( 5. - \u221a(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. + \u221a(5. / 14.) ) / 4.;\n        b3 = ( 1. - \u221a(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, \u03f5::Real)\n\n    L = dot(r, l)\n\n    non_normal = r - L * l\n\n    norm_non_normal = sqrt(norm(non_normal) ^ 2 + \u03f5 ^ 2)\n    nr = sqrt(norm(r) ^ 2 + \u03f5 ^ 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, \u03f5::Real)\n\n    l = r2 - r1\n    nl = norm(l) + 1e-10\n    @. l /= nl\n\n    (_source_f(l, colpt - r2, \u03f5) - _source_f(l, colpt - r1, \u03f5)) / (4 * pi)\n\nend\n\nfunction _gradPhi(r\u20d7::AbstractVector, \u03be\u20d7::AbstractVector, \u03b7\u20d7::AbstractVector, \u03f5::Real)\n\n    rxi = dot(r\u20d7, \u03be\u20d7)\n    reta = dot(r\u20d7, \u03b7\u20d7)\n\n    r = sqrt(norm(r\u20d7) ^ 2 + \u03f5 ^ 2)\n\n    den = (r ^ 2 - rxi ^ 2 + \u03f5 ^ 2) * r\n\n    (\n        (rxi * \u03b7\u20d7 + reta * \u03be\u20d7) * den - (den * r\u20d7 / r ^ 2 + 2 * (r\u20d7 - rxi * \u03be\u20d7) * r) * rxi * reta\n    ) / den ^ 2\n\nend\n\n\"\"\"\nDoublet line influence coefficient\n\"\"\"\nfunction doublet_line(colpt::AbstractVector, r1::AbstractVector, r2::AbstractVector, \u03b7\u20d7::AbstractVector, \u03f5::Real)\n\n    l = r2 - r1\n    nl = norm(l) + 1e-10\n    @. l /= nl\n\n    (_gradPhi(colpt - r2, l, \u03b7\u20d7, \u03f5) - _gradPhi(colpt - r1, l, \u03b7\u20d7, \u03f5)) / (4 * pi)\n\nend\n\n\"\"\"\nPoint doublet influence coefficient\n\"\"\"\nfunction point_doublet_infl(colpt::AbstractVector, pt::AbstractVector, \u03be::AbstractVector, \u03f5::Real)\n\n    r = colpt .- pt\n    nr = sqrt(norm(r) ^ 2 + \u03f5 ^ 2)\n\n    z = \u03be \u22c5 r\n    nprojr = r .- z .* \u03be\n\n    (3 * z) .* nprojr ./ (nr ^ 5 * 4 * \u03c0) .- \u03be .* ((nr ^ 2 - 3 * z ^ 2) / (4 * \u03c0 * nr ^ 5))\n\nend\n\n\"\"\"\nPoint source influence coefficient\n\"\"\"\nfunction point_source_infl(colpt::AbstractVector, pt::AbstractVector, \u03f5::Real)\n\n    r = colpt .- pt\n\n    r ./ (4 * \u03c0 * sqrt(norm(r) + \u03f5 ^ 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 \u03c6(i) return  function (x) sin(\u03c0*i*x) end end\n\n## Coupling strength\n@everywhere \u03bb = 1.0*\u03c0^2/4.0\n\n## Definition of the centered harmonic potential V(x)\n@everywhere function V(x) return \u03bb*(x-0.5)^2 end \n\n## Multiply a potential to calculate <\u03c61|V|\u03c62> \n@everywhere function V\u03c6(i) return  function (x) sin(\u03c0*i*x)*V(x) end end\n\n## Definition of the inner product <\u03c61|\u03c62> \n@everywhere function \u222b(\u03c61::Function,\u03c62::Function)\n    \u03c8(x)=\u03c61(x)*\u03c62(x)::Float64\n    return 2*quadgk(\u03c8,0,1,abstol=1e-8)[1]::Float64\nend\n\n##  Infinite well energies \n@everywhere function \u025b(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] = \u025b(i,j) + \u222b(\u03c6(i),V\u03c6(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)*\u03bb*(1-6/(i*\u03c0)^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] = \u222b(\u03c6(i),\u03c6(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    \u03bb::T\n    \u03c3::T\n    p::T\n\n    function Linear{T}(\u03bb::T, \u03c3::T, p::T) where T\n        \u03bb > 0 || throw(DomainError(\u03bb, \"correlation length \u03bb of linear covariance cannot be negative or zero\"))\n        \u03c3 > 0 || throw(DomainError(\u03c3, \"marginal standard deviation \u03c3 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}(\u03bb, \u03c3, p)\n    end\nend\n\n\"\"\"\n    Linear(\u03bb, [\u03c3 = 1], [p = 2])\n\nLinear covariance structure with correlation length `\u03bb`, (optional) marginal standard deviation `\u03c3` and (optional) `p`-norm, defined as\n\n``C(x, y) = \\\\begin{cases} \u03c3 \\\\left(1 - \\\\displaystyle\\\\frac{\u03c1}{\u03bb}\\\\right) & \\\\text{if }\u03c1 \u2264 \u03bb\\\\\\\\ 0 & \\\\text{if }\u03c1>\u03bb\\\\end{cases}``\n\nwith ``\u03c1 = ||x - y||_p``.\n\n# Examples\n```jldoctest\njulia> Linear(0.1)\nlinear (\u03bb=0.1, \u03c3=1.0, p=2.0)\n\njulia> Linear(1.0, \u03c3=2)\nlinear (\u03bb=1.0, \u03c3=2.0, p=2.0)\n\n```\nSee also: [`Exponential`](@ref), [`Spherical`](@ref), [`Whittle`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nLinear(\u03bb::Real; \u03c3::Real=1.0, p::Real=2) = Linear{promote_type(typeof(\u03bb),typeof(\u03c3),typeof(p))}(promote(\u03bb, \u03c3, p)...)\n\n# evaluate exponential covariance\napply(l::Linear, x::Real) = max(zero(x), 1 - x / l.\u03bb)\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 45d72214-919c-11eb-2e69-23c0786baacb\nmd\"\"\"\n### Functional Programming\n\nSrc: [Julia 1.0 Cookbook -  Bogumi\u0142 Kami\u0144ski , Przemys\u0142aw Szufel - 2018](https://www.packtpub.com/product/julia-1-0-programming-cookbook/9781788998369)\n\"\"\"\n\n# \u2554\u2550\u2561 6d80a12a-9649-4438-9a12-36003a57bf86\nfunction deriv(f::Function)::Function\n\th = \u221aeps()\n\tdf(x) = (f(x + h) - f(x)) / h\n\tdf\nend\n\n# \u2554\u2550\u2561 5e5c6b37-f3ee-42b1-94cc-686d54171833\nmd\"\"\"\nLet us test the `deriv` function. We will use the `UnicodePlots.jl` package to plot a $2\u00d7x\u00d7x + 5\u00d7x - 4$ function and its derivative. \n\"\"\"\n\n# \u2554\u2550\u2561 b3faae61-dcdc-473d-9a06-cc890ae74bd7\nbegin\n\tf(x) = 2x*x + 5x - 4\n\tx = -5.:3.;\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 = \u221a(b * b - 4 * a * c)\n\t((-b - d) / 2a, -(-b + d) / 2a)\nend\n\n# \u2554\u2550\u2561 bd8d4613-c666-41e3-b877-e9ed6882fe04\n@test q_solve(x -> (x - 1) * (x + 7)) == (-7., -1.)\n\n# \u2554\u2550\u2561 b3ee6944-32c7-4dca-ab51-9f1dc0accd91\n@test_throws DomainError q_solve(x -> x * x + 1)  ## no solution in the real domain\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u00d7x^2 + b\u00d7x + c$, and we calculate $f(0)$ to get the $c$ value. \nNext, we calculate `deriv(f)(0)`, which is $(2\u00d7a\u00d7x + 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 \u00d7 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250045d72214-919c-11eb-2e69-23c0786baacb\n# \u2560\u255015b8afb9-ace9-4b5b-894e-dce9dda5bf5f\n# \u2560\u25506d80a12a-9649-4438-9a12-36003a57bf86\n# \u255f\u25005e5c6b37-f3ee-42b1-94cc-686d54171833\n# \u2560\u2550b3faae61-dcdc-473d-9a06-cc890ae74bd7\n# \u2560\u255075442ce9-cf92-4800-b1aa-bfdd4229224c\n# \u255f\u2500a2db212a-02f8-493c-a1f2-43c0e63c31fa\n# \u2560\u2550415677ce-d5d6-4808-8789-f5fa66d7f7df\n# \u2560\u2550bd8d4613-c666-41e3-b877-e9ed6882fe04\n# \u2560\u2550b3ee6944-32c7-4dca-ab51-9f1dc0accd91\n# \u2560\u25506486f3b7-9a29-41d1-8d80-514a9212a174\n# \u255f\u250075a80d9a-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],\u03b1=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) \u2208 (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) \u2208 (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    \u03b6(N::Int, M::Int, \u03c1::T, \u03d5::T) -> Tuple{T,T}\n\nEvaluate Zernike polynomial term ``Z_{n}^{m}(\\\\rho, \\\\phi)``.\n\"\"\"\n@inline function \u03b6(N::Int, M::Int, \u03c1::T, \u03d5::T)::T where {T <: Real}\n    aM = abs(M)\n    if M < 0\n        return normalisation(T, N, M) * R(N, aM, \u03c1) * sin(aM * \u03d5)\n    else\n        return normalisation(T, N, M) * R(N, aM, \u03c1) * cos(aM * \u03d5)\n    end\nend\n\n\"\"\"\n    \u03b4\u03b6(N::Int, M::Int, \u03c1::T, \u03d5::T) -> Tuple{T,T}\n\nEvaluate partial derivatives of Zernike polynomial term ``Z_{n}^{m}(\\\\rho, \\\\phi)``.\n\"\"\"\n@inline function \u03b4\u03b6(N::Int, M::Int, \u03c1::T, \u03d5::T)::Tuple{T, T} where {T <: Real}\n    n = normalisation(T, N, M)\n    aM = abs(M)\n    RNM = R(N, aM, \u03c1)\n    \u03c12 = \u03c1^2\n    \u03b4RNM =\n        (\n            (2 * N * aM * (\u03c12 - 1) + (N - aM) * (aM + N * (2 * \u03c12 - 1))) * RNM -\n            (N + aM) * (N - aM) * R(N - 2, aM, \u03c1)\n        ) / (2 * N * \u03c1 * (\u03c12 - 1))\n    M\u03d5 = aM * \u03d5\n    if M < 0\n        \u03b4\u03c1 = n * \u03b4RNM * sin(M\u03d5)\n        \u03b4\u03d5 = n * RNM * aM * cos(M\u03d5)\n    else\n        \u03b4\u03c1 = n * \u03b4RNM * cos(M\u03d5)\n        \u03b4\u03d5 = n * RNM * aM * -sin(M\u03d5)\n    end\n    return \u03b4\u03c1, \u03b4\u03d5\nend\n\n\"\"\"\n    R(N::Int, M::Int, \u03c1::T) -> T\n\nEvaluate radial polynomial ``R_{n}^{m}(\\\\rho)``.\n\"\"\"\n@inline function R(N::Int, M::Int, \u03c1::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) \u00f7 2)\n        total +=\n            ((-1)^k * factorial(N - k)) / (\n                factorial(k) *\n                factorial((N + M) \u00f7 2 - k) *\n                factorial((N - M) \u00f7 2 - k)\n            ) * \u03c1^(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 <= \u03c1 <= 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\u1d57\u02b0 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(\u03c0), T(\u03c0)))\nend # \u03c1 and \u03d5\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    \u03c1::T,\n    \u03d5::T,\n)::SVector{3, T} where {T <: Real, P, Q, M}\n    pnt = point(z.asp, \u03c1, \u03d5)\n\n    # sum zernike\n    rad = semidiameter(z.asp)\n    r = \u03c1 * 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.\u03b6(R, S, u, \u03d5)\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    \u03c1::T,\n    \u03d5::T,\n)::Tuple{SVector{3, T}, SVector{3, T}} where {T <: Real, P, Q, M}\n    p\u03c1, p\u03d5 = partials(z.asp, \u03c1, \u03d5)\n    # sum zernike partials\n    rad = z.asp.semidiameter\n    n = rad / z.asp.normradius\n    u = \u03c1 * n\n    dhd\u03c1 = zero(T)\n    dhd\u03d5 = zero(T)\n    @inbounds @simd for m in 1:P\n        (R, S, k) = z.coeffs[m]\n        du, d\u03d5 = Zernike.\u03b4\u03b6(R, S, u, \u03d5)\n        dhd\u03c1 += k * du * n # want the derivative wrt \u03c1, not u\n        dhd\u03d5 += k * d\u03d5\n    end\n    return SVector{3, T}(p\u03c1[1], p\u03c1[2], p\u03c1[3] + dhd\u03c1),\n    SVector{3, T}(p\u03d5[1], p\u03d5[2], p\u03d5[3] + dhd\u03d5)\nend\n\nfunction normal(\n    z::ZernikeSurface{T, 3, P, Q, M},\n    \u03c1::T,\n    \u03d5::T,\n)::SVector{3, T} where {T <: Real, P, Q, M}\n    du, dv = partials(z, \u03c1, \u03d5)\n    if \u03c1 == zero(T) && norm(dv) == zero(T)\n        # in cases where there is no \u03b4\u03d5 at \u03c1 = 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    \u03d5 = NaNsafeatan(p[2], p[1])\n    if p[1] == zero(T) && p[2] == zero(T)\n        \u03c1 = zero(T)\n    else\n        \u03c1 = sqrt(p[1]^2 + p[2]^2) / semidiameter(z)\n    end\n    return SVector{2, T}(\u03c1, \u03d5)\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    \u03c1, \u03d5 = uv(surf, p)\n    if \u03c1 > one(T)\n        return false\n    else\n        surfpoint = point(surf, \u03c1, \u03d5)\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    \u03c1, \u03d5 = uv(surf, p)\n    if \u03c1 > one(T)\n        return false\n    else\n        surfpoint = point(surf, \u03c1, \u03d5)\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            \u03c1, \u03d5 = uv(surf, p)\n            surfpoint = point(surf.surface, \u03c1, \u03d5)\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 \u03c1, \u03d5 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\u1d62| <= 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\u0301as-Pe\u0301rez, Hildebrandt, A&A, 558, A118 (2013)\n\n# Arguments\n- `cij::Array{<:AbstractFloat,2}`: symmetric covariance matrix with the dimention of `(n\u03bd, n\u03bd)` where `n\u03bd` 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\u03bd`-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] \u2260 size(cij)[2]\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    elseif size(cij)[1] \u2260 length(a) || size(cij)[1] \u2260 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\u2113, a, B[, \u2113id=3])\n\nThis function returns weights (a `n\u03bd`-by-`n\u2113` matrix) of the Modified ILC Algorith (MILCA) method.\n\nHere, `n\u03bd` is the number of frequency channels and `n\u2113` 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\u0301as-Pe\u0301rez, Hildebrandt, A&A, 558, A118 (2013)\n\n# Arguments\n- `cij\u2113::Array{<:AbstractFloat,3}`: symmetric covariance matrix with the dimention of `(n\u2113, n\u03bd, n\u03bd)`, `(n\u03bd, n\u2113, n\u03bd)` or `(n\u03bd, n\u03bd, n\u2113)` (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\u03bd`-by-`nrc` matrix of the frequency response, for `nrc` components to be nulled.\n\n# Optional Arguments\n- `\u2113id::Integer=3`: location of the index for the `n\u2113` domain. `\u2113id=1` if `cij\u2113[n\u2113,n\u03bd,n\u03bd]`, `\u2113id=2` if `cij\u2113[n\u03bd,n\u2113,n\u03bd]`, and `\u2113id=3` (the default value) if `cij\u2113[n\u03bd,n\u03bd,n\u2113]`.\n\"\"\"\nfunction milca_weights(\n    cij\u2113::Array{T,3},\n    a::Array{T,1},\n    B::Array{T,2},\n    \u2113id::Integer = 3,\n) where {T<:AbstractFloat}\n    if \u2113id > 3 || \u2113id < 1\n        throw(DomainError(\u2113id, \"\u2113id must be 1, 2, or 3\"))\n    end\n    if (\u2113id == 3 && size(cij\u2113)[1] \u2260 size(cij\u2113)[2]) ||\n       (\u2113id == 2 && size(cij\u2113)[1] \u2260 size(cij\u2113)[3]) ||\n       (\u2113id == 1 && size(cij\u2113)[2] \u2260 size(cij\u2113)[3])\n        throw(DimensionMismatch(\"covariance matrix must be a square matrix\"))\n    end\n    n\u2113 = size(cij\u2113)[\u2113id]\n    n\u03bd = ifelse(\u2113id == 3, size(cij\u2113)[1], size(cij\u2113)[3])\n    if length(a) \u2260 n\u03bd || size(B)[1] \u2260 n\u03bd\n        throw(DimensionMismatch(\"dimensions of the covariance matrix and the frequency response vector/matrix do not match\"))\n    end\n    w\u2113 = zeros(n\u03bd, n\u2113) # ILC weights\n    e = zeros(size(B)[2] + 1)\n    e[1] = 1\n    F = [a B]\n    for i\u2113 = 1:n\u2113\n        if \u2113id == 3\n            M = Symmetric(cij\u2113[:, :, i\u2113])\n        elseif \u2113id == 2\n            M = Symmetric(cij\u2113[:, i\u2113, :])\n        else\n            M = Symmetric(cij\u2113[i\u2113, :, :])\n        end\n        w\u2113[:, i\u2113] = inv(M) * F * inv(F' * inv(M) * F) * e\n    end\n    return w\u2113\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": "#  Copyright 2017, Iain Dunning, Joey Huchette, Miles Lubin, and contributors\n#  This Source Code Form is subject to the terms of the Mozilla Public\n#  License, v. 2.0. If a copy of the MPL was not distributed with this\n#  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n#############################################################################\n# JuMP\n# An algebraic modeling language for Julia\n# See http://github.com/JuliaOpt/JuMP.jl\n#############################################################################\n\nusing JuMP, GLPK, Test\n\n\"\"\"\n    example_sudoku(filepath)\nA sudoku solver that uses a MIP to find solutions.\nWe have binary variables x[i, j, k] which, if = 1, say that cell (i, j) contains\nthe number k. The constraints are:\n 1 - Each cell has one value only\n 2 - Each row contains each number exactly once\n 3 - Each column contains each number exactly once\n 4 - Each 3x3 subgrid contains each number exactly once\nWe will take the initial grid as a CSV file at `filepath`, where 0s are blanks.\n\"\"\"\nfunction example_sudoku(filepath)\n    initial_grid = zeros(Int, 9, 9)\n    open(filepath, \"r\") do fp\n        for row in 1:9\n            line = readline(fp)\n            initial_grid[row, :] .= parse.(Int, split(line, \",\"))\n        end\n    end\n\n    model = Model(GLPK.Optimizer)\n\n    @variable(model, x[1:9, 1:9, 1:9], Bin)\n\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    # Initial solution\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\nif length(ARGS) == 1\n    sol = example_sudoku(ARGS[1])\n    print_sudoku_solution(sol)\nelse\n    solution = example_sudoku(joinpath(@__DIR__, \"sudoku.csv\"))\n    @test solution == [\n        3 1 7 9 5 8 2 6 4;\n        4 6 9 3 2 7 8 1 5;\n        8 2 5 1 6 4 7 9 3;\n        2 7 1 6 4 5 3 8 9;\n        9 3 8 7 1 2 5 4 6;\n        5 4 6 8 3 9 1 7 2;\n        1 8 4 2 9 3 6 5 7;\n        6 9 2 5 7 1 4 3 8;\n        7 5 3 4 8 6 9 2 1]\nend", "meta": {"hexsha": "2af182e77a306a5042e341977ec940a805ebc214", "size": 3491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jump/sudoku.jl", "max_stars_repo_name": "cdeil/python-discrete-optimization-examples", "max_stars_repo_head_hexsha": "34e97ee221a6e431e9885609817e10b6f07284b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-04-09T21:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T02:57:33.000Z", "max_issues_repo_path": "jump/sudoku.jl", "max_issues_repo_name": "cdeil/python-discrete-optimization-examples", "max_issues_repo_head_hexsha": "34e97ee221a6e431e9885609817e10b6f07284b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-10T13:02:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T15:27:17.000Z", "max_forks_repo_path": "jump/sudoku.jl", "max_forks_repo_name": "cdeil/python-discrete-optimization-examples", "max_forks_repo_head_hexsha": "34e97ee221a6e431e9885609817e10b6f07284b3", "max_forks_repo_licenses": ["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.7363636364, "max_line_length": 80, "alphanum_fraction": 0.5422515039, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7624902387709407}}
{"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#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n#                                                                             #\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\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\u03a8=P*(v.*a.y)\n\n# get the amplitude spectrum\n\u03a3=abs.(\u03a8)\nbar!(\u03a3[2:end])\n\n# check the amplitude at frequency f and neighbooring bins\npos=f2b(f, sr, t, DC=true)\n\n\u03a3[pos-1]\n\u03a3[pos]\n\u03a3[pos+1]\n\n# The fast way using FourierAnalysis.jl:\n\u03a32=spectra(v, sr, t; tapering=tapering, func=\u221a)\nbar!(\u03a32.y)\n\n# equivalently:\n\u03a32=spectra(v, sr, t; tapering=taper(hann, t), func=\u221a)\nbar!(\u03a32.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\u03a32=spectra(v, sr, t; tapering=rectangular, DC=true, func=\u221a)\nbar!(\u03a32.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=\u03c0/6\nsr, t, = 16, 32\nt\u00bd = t\u00f72\nV=Matrix{Float64}(undef, t, t\u00bd)\nfor i=1:t\u00bd V[:, i]=sinusoidal(10*i, b2f(i, sr, t), sr, t, \u03c0/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\u03a8=P*V\n\u03a8[end, :]*=0.5*2^0.25 # correction for Nyquist frequency\n\u03a3=abs.(\u03a8)\nbar(\u03a3[brange(t, DC=true), :], labels=\"\")\n\n# fast way using FourierAnalysis.jl\n\u03a32=spectra(V, sr, t; tapering=rectangular, func=\u221a, DC=true)\nbar(\u03a32.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\u03a3=spectra(v, sr, t; tapering=rectangular, func=\u221a)\nbar(\u03a3.y, labels=\"rectangular\")\n\n# harris4 window (default)\n\u03a32=spectra(v, sr, t; func=\u221a)\nbar!(\u03a32.y, labels=\"harris4\")\n\n#smooth spectra\n\u03a33=smooth(blackmanSmoother, \u03a32)\nbar!(\u03a33.y, labels=\"smoothed\")\n\n\n######## Check amplitude spectrum obtained with dpss (slepian tapers) ########\nsr, t = 128, 128\nt\u00bd = t\u00f72\nV=Matrix{Float64}(undef, t, t\u00bd)\nfor i=1:t\u00bd 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\u00bd+1, 1:7], color=:gray, legend=false)\n\n\u03a3=spectra(V, sr, t; tapering=taper(slepian, t; \u03b1=2, n=3), func=\u221a)\nplot(\u03a3.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\ud835\udc17=[X1, X2]\n\ud835\udc12=spectra(\ud835\udc17, sr, t; tapering=tapering, slide=sr, func=\u221a)\nplot(\ud835\udc12[1]; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\nplot(\ud835\udc12[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(\ud835\udc17[1]))\n\ud835\udc12_fast=spectra(\ud835\udc17, sr, t; planner=plan, slide=sr, func=\u221a)\n\n# compute the average spectra in the alpha range for all time-series and all subjects\nmean(\ud835\udc12, (8,12))\n\n# compute the average spectra in the alpha range across subjects for all time-series\nmean(mean(\ud835\udc12, (8,12)))\n# compute and plot it\nplot(mean(mean(\ud835\udc12, (8,12))))\n\n# extract spectra in alpha range for all time-series and all subjects\nextract(\ud835\udc12, (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(\ud835\udc12, (0, 12))\nmean(\ud835\udc12, (0, 128))\n\n# extract 4Hz-band-pass average spectra for all electrodes and all subjects\nbands(\ud835\udc12, 4)\n\n# Apply smoothing in the above spectra computations\n\ud835\udc12=spectra(\ud835\udc17, sr, t;\n    tapering=tapering, smoothing=blackmanSmoother, func=\u221a)\nplot(\ud835\udc12[1]; ytitle=\"Amplitude (\\\\muV)\", spectraArgs...)\nplot(\ud835\udc12[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(\ud835\udc12[1].y[:, i] for i=1:size(\ud835\udc12[1].y, 2)))\nplot!(mean(\ud835\udc12[2].y[:, i] for i=1:size(\ud835\udc12[2].y, 2)))\n\n# plot spectra in in 1Hz band-pass regions for all electrodes in \ud835\udc12[1]\nplot(bands(\ud835\udc12[1], 1))\n\n# use slepian multi-tapering on EEG data\nS_sl=spectra(X1, sr, t; tapering=slepians(sr, t, 1.25), func=\u221a)\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=\u221a, 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=\u221a, 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": "# Test pair-wise correlation and covariance functions\nx, y = rand(1000), rand(1000)\n\n@test nancov(x,y) \u2248 cov(x,y)\n@test nancov(x,y, corrected=false) \u2248 cov(x,y, corrected=false)\n@test nancor(x,y) \u2248 cor(x,y)\n\n\n# Test correlation and covariance functions as applied to matrices\nX = rand(100,10)\n\n@test nancov(X) \u2248 cov(X)\n@test nancov(X, dims=1) \u2248 cov(X, dims=1)\n@test nancov(X, dims=2) \u2248 cov(X, dims=2)\n@test nancov(X, corrected=false) \u2248 cov(X, corrected=false)\n\n@test nancor(X) \u2248 cor(X)\n@test nancor(X, dims=1) \u2248 cor(X, dims=1)\n@test nancor(X, dims=2) \u2248 cor(X, dims=2)\n\n# Test NaN-ignoring\nxn = [1,2,3,NaN]\nxnn = [1,2,3]\n@test nancov(xn,xn) \u2248 cov(xnn,xnn) \u2248 1\n@test nancor(xn,xn) \u2248 cor(xnn,xnn) \u2248 1\n", "meta": {"hexsha": "f8f565bdcc05e82eae0eb40d630df163a0638102", "size": 697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testCovCor.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": "test/testCovCor.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": "test/testCovCor.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.8076923077, "max_line_length": 66, "alphanum_fraction": 0.6571018651, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7624680241156495}}
{"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    \u03b1 ~ Normal(100, 10)\n    w ~ filldist(Normal(0, 10), size(B, 2))\n    \u03c3 ~ Exponential(1)\n    \u03bc = \u03b1 .+ B * w\n    doy ~ MvNormal(\u03bc, \u03c3)\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)', [\"\u03b1\"; w_str; \"\u03c3\"])\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)', [\"\u03b1\"; w_str; \"\u03c3\"])\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    \u03bcA = mean(dA)\n    \u03c3A = std(dA)\n    \u03bcB = mean(dB)\n    \u03c3B = std(dB)\n    _pearson_bounds(dA, dB, \u03bcA, \u03bcB, \u03c3A, \u03c3B, n)\nend\nfunction _pearson_bounds(dA::UD, dB::UD, \u03bcA, \u03bcB, \u03c3A, \u03c3B, n)\n    k = 0:1:n\n    a = get_coefs(dA, n)\n    b = get_coefs(dB, n)\n\n    c1 = -\u03bcA * \u03bcB\n    c2 = 1 / (\u03c3A * \u03c3B)\n    kab = factorial.(k) .* a .* b\n    \u03c1_l = c1 * c2 + c2 * sum((-1) .^ k .* kab)\n    \u03c1_u = c1 * c2 + c2 * sum(kab)\n\n    \u03c1_l, \u03c1_u = clampcor.((\u03c1_l, \u03c1_u))\n    (lower = \u03c1_l, upper = \u03c1_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\u00d72 Array{Float64,2}:\n  1.0       -0.762874\n -0.762874   1.0\n\njulia> b.upper\n2\u00d72 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## \u2212x + y \u2264 2\nc1 = MOI.add_constraint(\n    o,\n    -1.0x[1] + x[2],\n    MOI.LessThan(2.0),\n)\n\n## x + 2 y \u2264 4\nc2 = MOI.add_constraint(\n    o,\n    x[1] + 2.0x[2],\n    MOI.LessThan(4.0),\n)\n        \n## \u22122 x \u2212 y \u2264 1\nc3 = MOI.add_constraint(\n    o,\n    -2.0x[1] - x[2],\n    MOI.LessThan(1.0),\n)\n    \n## x \u2212 2 y \u2264 2\nc4 = MOI.add_constraint(\n    o,\n    x[1] - 2.0x[2],\n    MOI.LessThan(2.0),\n)\n    \n## x \u2264 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) \u2229\n    HalfSpace([1, 2], 4) \u2229\n    HalfSpace([-2, -1], 1) \u2229\n    HalfSpace([1, -2], 2) \u2229\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": "function _partition(x::AbstractArray, p::Int, r::Int)::Int\n    @inbounds y = x[r]\n    i = p-1\n    for j \u2208 p:(r-1)\n        @inbounds if x[j] \u2264 y\n            i += 1\n            @inbounds tmp  = x[i]\n            @inbounds x[i] = x[j]\n            @inbounds x[j] = tmp\n        end\n    end\n    @inbounds tmp    = x[i+1]\n    @inbounds x[i+1] = x[r]\n    @inbounds x[r]   = tmp\n    return i+1\nend\n\n\nfunction quicksort!(x::AbstractArray, p::Int, r::Int)\n    if p \u2265 r\n        return nothing\n    end\n    q::Int = _partition(x, p, r)\n    quicksort!(x, p, q-1)\n    quicksort!(x, q+1, r)\nend\n", "meta": {"hexsha": "2e96e36e420697a5ea0e76bd2f02c43995d0673f", "size": 577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sorting/src/quick.jl", "max_stars_repo_name": "tirthasheshpatel/Algorithms.jl", "max_stars_repo_head_hexsha": "d4a8c7d63d3245bc403fe811d6ed36479b0d9415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-14T01:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T01:48:33.000Z", "max_issues_repo_path": "sorting/src/quick.jl", "max_issues_repo_name": "tirthasheshpatel/Algorithms.jl", "max_issues_repo_head_hexsha": "d4a8c7d63d3245bc403fe811d6ed36479b0d9415", "max_issues_repo_licenses": ["MIT"], "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/quick.jl", "max_forks_repo_name": "tirthasheshpatel/Algorithms.jl", "max_forks_repo_head_hexsha": "d4a8c7d63d3245bc403fe811d6ed36479b0d9415", "max_forks_repo_licenses": ["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.3703703704, "max_line_length": 58, "alphanum_fraction": 0.4835355286, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7624259433775182}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.3\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 7dfe963f-3601-4515-a636-4930816a4e6c\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 73d28c7f-8426-4c5a-b166-23dcac5c16ce\nbegin\n\t@quickactivate \"NumericalMethodsforEngineers\"\n\tusing NumericalMethodsforEngineers\n\tusing Test\nend\n\n# \u2554\u2550\u2561 ac233fe5-a00f-412f-ad4a-a1d39ee20517\nmd\" ### f-01-01.jl\"\n\n# \u2554\u2550\u2561 d82838e5-1591-41d9-b5e0-0c49f48d7814\nbegin\n\ta = [10. 5. 6.; 5. 20. 4.; 6. 4. 30.]\n\tx0 = [1., 1., 1.]\n\n\ttol = 1.0e-5\n\tlimit = 100\nend;\n\n# \u2554\u2550\u2561 570d9517-14d8-4d40-8e29-039269a5e37d\n(iters, eigval, eigvec) = nmex(a, x0; tol=tol, limit=limit, show=8)\n\n# \u2554\u2550\u2561 1614c806-1bdc-40bb-ae8c-e02d29d128fe\njeigval, jeigvec = eigen(a)\n\n# \u2554\u2550\u2561 90c91c6a-1b9b-4d34-858a-7535b1090fee\n@test round(maximum(jeigval), digits=3) == round(eigval, digits=3)\n\n# \u2554\u2550\u2561 47256683-e6b6-4fae-916c-f80ba57a232f\nmd\" ### End of f-01-01.jl\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ac233fe5-a00f-412f-ad4a-a1d39ee20517\n# \u2560\u25507dfe963f-3601-4515-a636-4930816a4e6c\n# \u2560\u255073d28c7f-8426-4c5a-b166-23dcac5c16ce\n# \u2560\u2550d82838e5-1591-41d9-b5e0-0c49f48d7814\n# \u2560\u2550570d9517-14d8-4d40-8e29-039269a5e37d\n# \u2560\u25501614c806-1bdc-40bb-ae8c-e02d29d128fe\n# \u2560\u255090c91c6a-1b9b-4d34-858a-7535b1090fee\n# \u255f\u250047256683-e6b6-4fae-916c-f80ba57a232f\n", "meta": {"hexsha": "51fe608077ef8655a0bfcfca352fa7c6302cbe1c", "size": 1208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/01/f-01-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/01/f-01-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/01/f-01-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.16, "max_line_length": 67, "alphanum_fraction": 0.7119205298, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7624259411178086}}
{"text": "\"\"\"\nPackage: DataWrangler\n\nnormalize\\\\[!\\\\]([x]; method)\n\nNormalize values in vector `x` either in-place or returning a copy of `x` with the imputed values\n\n# Parameters\n\n`x`: Vector of type Real with missing values to be imputed\n\n`method`: There are four valid values: \"z-score\", \"min-max\", \"softmax\", \"sigmoid\"\n\n# Description\n\nThe normalization is applied ignoring any missing values in the Array, and it takes place in all the available dimensions of the array. If normalization is required in just some specific dimensions the function `mapslices` can be used to select those dimensions.\n\n# Example\n```julia\nx = [1.,2,3,4,5]\nnormalize!(x; method = \"min-max\")\n\nprintln(x)\n[0.0, 0.25, 0.5, 0.75, 1.0]\n```\n\"\"\"\nfunction normalize!(x::AbstractArray{<:Union{Missing,T}};\n                 method::String = \"z-score\") where T<:Real\n    \n    @assert !(T <: Integer) \" Method `$(typeof(x))` cannot be normalized in-place, use `normalize(x)` instead\"\n\n    @assert method \u2208 [\"z-score\",\"min-max\",\"softmax\",\"sigmoid\"]\n\n    smx = skipmissing(x)\n\n    if method == \"z-score\"\n        \u03bc = mean(smx)\n        \u03c3 = std(smx)\n        for i in CartesianIndices(x)\n            x[i] = (x[i] - \u03bc) / \u03c3\n        end\n    end\n\n    if method == \"min-max\"\n        m,M = extrema(smx)\n        Mm = M-m\n        for i in CartesianIndices(x)\n            x[i] = (x[i] - m) / Mm\n        end\n    end\n\n    if method == \"softmax\"\n        \u03a3e = sum(exp.(smx))\n        for i in CartesianIndices(x)\n            x[i] = exp(x[i]) / \u03a3e\n        end\n    end\n\n    if method == \"sigmoid\"\n        for i in CartesianIndices(x)\n            x[i] = 1/(1+exp(-x[i]))\n        end\n    end\n\nend\n\n\"\"\"\nPackage: DataWrangler\n\nCheck 'normalize! for further information.\n\"\"\"\nfunction normalize(x::AbstractArray{<:Union{Missing,T}};\n                method::String = \"z-score\") where T<:Real    \n\n    P = any(ismissing,x) ? Union{Missing, Base.promote_op(/,T,T)} : Base.promote_op(/,T,T)\n    cx = Array{P}(undef,size(x))\n    cx[:] = x\n    normalize!(cx; method)\n    return cx\n    \nend\n", "meta": {"hexsha": "4e4f84e0a8ab9c14ada345fc94e9dc10b81be3a5", "size": 2016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalize.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/normalize.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/normalize.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": 24.5853658537, "max_line_length": 262, "alphanum_fraction": 0.5892857143, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7624259336114478}}
{"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 \u2208 1:N\n            p.R[i]==p.R[j]+\u03b4(d,N) && return p.L[p.R[i],d]\n            p.R[i]==p.R[j]-\u03b4(d,N) && return p.L[p.R[j],d]\n        end\n        return zero(T)\n    end\nend\n\n@inline \u03b4(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-\u03b4(i,N)]*L[I,i]) for i \u2208 1:N)\n@fastmath @inline multU(I::CartesianIndex{N},L,x) where {N} =\n    sum(@inbounds(x[I+\u03b4(i,N)]*L[I+\u03b4(i,N),i]) for i \u2208 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 \u2208 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: \u222b \u2207\u22c5\u03b2\u2207\u03d5 dv = \u222e \u03b2 \u2202\u03d5/\u2202n da.\n\"\"\"\nfunction Poisson(L::AbstractArray{T}) where T\n    D = zeros(T,Base.front(size(L)))\n    R = inside(D)\n    for I \u2208 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+\u03b4(i,N),i]) for i \u2208 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).*\u03c0 )\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": "module VectorHeatEquationTests\n\nusing Gridap\nusing ForwardDiff\nusing LinearAlgebra\nusing Test\nusing GridapODEs.ODETools\nusing GridapODEs.TransientFETools\nusing Gridap.FESpaces: get_algebraic_operator\n\n# using GridapODEs.ODETools: ThetaMethodLinear\n\nimport Gridap: \u2207\nimport GridapODEs.TransientFETools: \u2202t\n\n\u03b8 = 1.0\n\nu(x,t) = (1.0-x[1])*x[1]*(1.0-x[2])*x[2]*t\nu(t::Real) = x -> u(x,t)\nv(x) = t -> u(x,t)\nf(t) = x -> \u2202t(u)(t)(x)-\u0394(u(t))(x)\n\ndomain = (0,1,0,1)\npartition = (2,2)\nmodel = CartesianDiscreteModel(domain,partition)\n\norder = 2\n\nreffe = ReferenceFE(lagrangian,Float64,order)\nV0 = FESpace(\n  model,\n  reffe,\n  conformity=:H1,\n  dirichlet_tags=\"boundary\"\n)\nU = TransientTrialFESpace(V0,u)\n\n\u03a9 = Triangulation(model)\ndegree = 2*order\nd\u03a9 = Measure(\u03a9,degree)\n\n#\na(u,v) = \u222b(\u2207(v)\u2299\u2207(u))d\u03a9\nb(v,t) = \u222b(v\u22c5f(t))d\u03a9\nm(ut,v) = \u222b(ut\u22c5v)d\u03a9\n\nX = TransientMultiFieldFESpace([U,U])\nY = MultiFieldFESpace([V0,V0])\n\n_res(t,u,ut,v) = a(u,v) + m(ut,v) - b(v,t)\n\nres(t,(u1,u2),(u1t,u2t),(v1,v2)) = _res(t,u1,u1t,v1) + _res(t,u2,u2t,v2)\njac(t,x,xt,(du1,du2),(v1,v2)) = a(du1,v1) + a(du2,v2)\njac_t(t,x,xt,(du1t,du2t),(v1,v2)) = m(du1t,v1) + m(du2t,v2)\n\nop = TransientFEOperator(res,jac,jac_t,X,Y)\n\nt0 = 0.0\ntF = 1.0\ndt = 0.1\n\nU0 = U(0.0)\nX0 = X(0.0)\nuh0 = interpolate_everywhere(u(0.0),U0)\nxh0 = interpolate_everywhere([uh0,uh0],X0)\n\nls = LUSolver()\n# using Gridap.Algebra: NewtonRaphsonSolver\n# nls = NLSolver(ls;show_trace=true,method=:newton) #linesearch=BackTracking())\nodes = ThetaMethod(ls,dt,\u03b8)\nsolver = TransientFESolver(odes)\n\nsol_t = solve(solver,op,xh0,t0,tF)\n\nl2(w) = w\u22c5w\n\n\ntol = 1.0e-6\n_t_n = t0\n\nresult = Base.iterate(sol_t)\n\nfor (xh_tn, tn) in sol_t\n  global _t_n\n  _t_n += dt\n  uh_tn = xh_tn[1]\n  e = u(tn) - uh_tn\n  el2 = sqrt(sum( \u222b(l2(e))d\u03a9 ))\n  @test el2 < tol\nend\n\nend #module\n", "meta": {"hexsha": "bd40b10da55222c268d0fb042306641436d07180", "size": 1776, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TransientFEsTests/VectorHeatEquationTests.jl", "max_stars_repo_name": "sjoerdvanhoof/GridapODEs.jl", "max_stars_repo_head_hexsha": "24beb434ad6c0b315f06b65cc1c9c791c44d4317", "max_stars_repo_licenses": ["MIT"], "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/TransientFEsTests/VectorHeatEquationTests.jl", "max_issues_repo_name": "sjoerdvanhoof/GridapODEs.jl", "max_issues_repo_head_hexsha": "24beb434ad6c0b315f06b65cc1c9c791c44d4317", "max_issues_repo_licenses": ["MIT"], "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/TransientFEsTests/VectorHeatEquationTests.jl", "max_forks_repo_name": "sjoerdvanhoof/GridapODEs.jl", "max_forks_repo_head_hexsha": "24beb434ad6c0b315f06b65cc1c9c791c44d4317", "max_forks_repo_licenses": ["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.0967741935, "max_line_length": 79, "alphanum_fraction": 0.6587837838, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7624097300969614}}
{"text": "\nmodule Testing\n\nimport ..NodalDG\n\nusing Test\n\n# Simple test of JacobiP\n@test NodalDG.JacobiP(0.0, 0, 0, 0) == [1.0 /sqrt(2.0)]\n\n# Test Gauss-Lobatto points\n\nr, w = NodalDG.gausslobatto(3)\n@test isapprox(r, [-1, 0, 1])\n@test isapprox(w, [1/3, 4/3, 1/3])\n\nr,w = NodalDG.gausslobatto(4)\n@test isapprox(r, [-1, -sqrt(1/5), sqrt(1/5), 1])\n@test isapprox(w, [1/6, 5/6, 5/6, 1/6])\n\n# Tests based on p48 in textbook, Fig 3.1\n# This tests JacobiP and LGL points\n\nr, w = NodalDG.gausslobatto(7)\n\n# Fig 3.1d\nVref = [0.707107 -1.22474 1.58114 -1.87083 2.12132 -2.34521 2.54951;\n        0.707107 -1.01681 0.844182 -0.346644 -0.278373 0.807539 -1.05741;\n        0.707107 -0.57422 -0.269222 0.833675 -0.504704 -0.365166 0.846707;\n        0.707107 0.0 -0.790569 -0.0 0.795495 0.0 -0.796722;\n        0.707107 0.57422 -0.269222 -0.833675 -0.504704 0.365166 0.846707;\n        0.707107 1.01681 0.844182 0.346644 -0.278373 -0.807539 -1.05741;\n        0.707107 1.22474 1.58114 1.87083 2.12132 2.34521 2.54951]\n\n@test isapprox( NodalDG.Vandermonde1D(6,r), Vref, atol=1e-5 )\n\n# Tests based on p54, Fig 3.4\n\n# order N = 1\nr, w = NodalDG.gausslobatto(2)\nV = NodalDG.Vandermonde1D(1, r)\n\nDref1 = [-0.5 0.5;\n         -0.5 0.5]\n@test isapprox( NodalDG.Dmatrix1D(1, r, V), Dref1 )\n\n# order N = 2\nr, w = NodalDG.gausslobatto(3)\nV = NodalDG.Vandermonde1D(2, r)\n\nDref2 = [-1.5 2.0 -0.5;\n         -0.5 0.0 0.5;\n         0.5 -2.0 1.5]\n\n@test isapprox( NodalDG.Dmatrix1D(2, r, V), Dref2 )\n\n# order N = 4\nr, w = NodalDG.gausslobatto(5)\nV = NodalDG.Vandermonde1D(4, r)\n\nDref4 = [-5.0 6.7565 -2.66667 1.41016 -0.5;\n         -1.24099 2.51054e-16 1.74574 -0.763763 0.25901;\n         0.375 -1.33658 -0.0 1.33658 -0.375;\n         -0.25901 0.763763 -1.74574 -6.56798e-16 1.24099;\n         0.5 -1.41016 2.66667 -6.7565 5.0]\n\n@test maximum(abs, NodalDG.Dmatrix1D(4, r, V) - Dref4) < 1e-5\n\nend\n", "meta": {"hexsha": "626872747c3488f417399fd80ba8b9a79a67b76f", "size": 1848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/test-utils.jl", "max_stars_repo_name": "bendudson/NodalDG.jl", "max_stars_repo_head_hexsha": "5dcaebd2e7678914bca3525f1ff3bb9beef0a825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-03-05T15:27:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T15:34:58.000Z", "max_issues_repo_path": "tests/test-utils.jl", "max_issues_repo_name": "bendudson/NodalDG.jl", "max_issues_repo_head_hexsha": "5dcaebd2e7678914bca3525f1ff3bb9beef0a825", "max_issues_repo_licenses": ["MIT"], "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/test-utils.jl", "max_forks_repo_name": "bendudson/NodalDG.jl", "max_forks_repo_head_hexsha": "5dcaebd2e7678914bca3525f1ff3bb9beef0a825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-05T15:27:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T16:08:03.000Z", "avg_line_length": 26.4, "max_line_length": 74, "alphanum_fraction": 0.619047619, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7624097265356033}}
{"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 \u2265 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) \u2248 -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": "using Dates\n\neffective_date = Date(2020, 01, 15)\n\ndays = [369, 462, 553, 735, 1100, 1465]\ndf = [0.97678403, 0.97153083, 0.96655364, 0.95695995, 0.93829085, 0.91954718]\ntest_date = effective_date + Day(900)\n\nconst dc_act_360 = QuantLib.Time.Actual360()\n\n# test log-linear interpolation\ntest_curve_loglinear = QuantLib.InterpolatedDiscountCurve(effective_date .+ Day.(days), df, dc_act_360, QuantLib.Math.LogLinear())\ndisc_factor = QuantLib.discount(test_curve_loglinear, test_date)\nx1 = (test_date - test_curve_loglinear.dates[4]).value\ndx = (test_curve_loglinear.dates[5]-test_curve_loglinear.dates[4]).value\ndy = log(test_curve_loglinear.data[5]) - log(test_curve_loglinear.data[4])\ndf_recalc = exp(log(test_curve_loglinear.data[4]) + x1*dy/dx)\n@test disc_factor == df_recalc\n\ntest_curve_linear = QuantLib.InterpolatedDiscountCurve(effective_date .+ Day.(days), df, dc_act_360, QuantLib.Math.LinearInterpolation())\ndisc_factor = QuantLib.discount(test_curve_linear, test_date)\nx1 = (test_date - test_curve_linear.dates[4]).value\ndx = (test_curve_linear.dates[5]-test_curve_linear.dates[4]).value\ndy = (test_curve_linear.data[5]) - (test_curve_linear.data[4])\ndf_recalc = ((test_curve_linear.data[4]) + x1*dy/dx)\n@test disc_factor == df_recalc\n\n# test joint calendars\nconst calendar_nyc = QuantLib.Time.USNYSECalendar()\nconst calendar_target = QuantLib.Time.TargetCalendar()\nconst calendar_lon = QuantLib.Time.UKLSECalendar()\n\ncalendar_nyc_target = QuantLib.Time.JointCalendar(calendar_nyc, calendar_target) # standard constructor\n@test calendar_nyc_target isa QuantLib.Time.BusinessCalendar\ncalendar_nyc_target_lon = QuantLib.Time.JointCalendar(calendar_nyc, calendar_target, calendar_lon) # new constructor\n@test calendar_nyc_target_lon isa QuantLib.Time.BusinessCalendar\n# at least 2 calendars must be specified for JointCalendar\n@test_throws ErrorException QuantLib.Time.JointCalendar(calendar_nyc)\n", "meta": {"hexsha": "38bb87aa5bff92758a5ef61dbf845200762b0aa9", "size": 1903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/curves.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": "test/curves.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": "test/curves.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": 48.7948717949, "max_line_length": 137, "alphanum_fraction": 0.8024172359, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7624094641228989}}
{"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 - \u03c3I, a.k.a. spectrum slicing\n\nInputs:\n    T: A SymTridiagonal{<:Real} matrix\n    \u03c3: The shift parameter\n\nOutputs:\n    \u03bd: 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}, \u03c3::S = zero(S)) where S\n    \u03b1 = T.dv\n    \u03b2 = T.ev\n    n = length(\u03b1)\n    \u03f5 = eps(S)\n    \u03b4 = \u03b1[1] - \u03c3\n    \u03bd = \u03b4 < 0 ? 1 : 0\n    for k = 1:n - 1\n        if \u03b4 == 0\n        info(\"zero in iteration $k\")\n        \u03b4 = \u03f5 * (\u03b2[k]+\u03f5) #Parlett prefers adjusting \u03c3 and starting again\n    end\n        \u03b4 = (\u03b1[k + 1] - \u03c3) - \u03b2[k]*(\u03b2[k]/\u03b4)\n    \u03bd += (\u03b4 < 0)\n    end\n    \u03bd\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": "# ---\n# title: 461. Hamming Distance\n# id: problem461\n# author: Indigo\n# date: 2021-02-04\n# difficulty: Easy\n# categories: Bit Manipulation\n# link: <https://leetcode.com/problems/hamming-distance/description/>\n# hidden: true\n# ---\n# \n# The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between\n# two integers is the number of positions at which the corresponding bits are\n# different.\n# \n# Given two integers `x` and `y`, calculate the Hamming distance.\n# \n# **Note:**  \n# 0 \u2264 `x`, `y` < 231.\n# \n# **Example:**\n# \n#     \n#     \n#     Input: x = 1, y = 4\n#     \n#     Output: 2\n#     \n#     Explanation:\n#     1   (0 0 0 1)\n#     4   (0 1 0 0)\n#            \u2191   \u2191\n#     \n#     The above arrows point to positions where the corresponding bits are different.\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction hamming_distance(x::Int, y::Int)\n    res = 0\n    while x != 0 || y != 0\n        res += (x & 1) \u22bb (y & 1)\n        x >>= 1\n        y >>= 1\n    end\n    res\nend\n## @lc code=end\n", "meta": {"hexsha": "30dfab39bc568fee03e3662a911bf7e80785e547", "size": 1005, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/461.hamming-distance.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/461.hamming-distance.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/461.hamming-distance.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.7058823529, "max_line_length": 85, "alphanum_fraction": 0.5621890547, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7623753355494411}}
{"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}, \u03b1=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}, \u03b1=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}, \u03b1=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}, \u03b1=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}, \u03b1=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}, \u03b1=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}, \u03b1=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}, \u03b1=0.0) where {T <: AbstractFloat}\n    eval = zero(T)\n    for i in eachindex(y)\n        eval += \u03b1 * max(y[i] - p[1,i], zero(T)) + (1 - \u03b1) * 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}, \u03b1=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) \u2248 -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] \u2248 -0.5 * sum(x) #src\n@test size(g[1].Q) == (2, 2)                  #src\n@test g[1].Q[1, 1] \u2248 1.0 atol=1e-6            #src\n@test g[1].Q[1, 2] \u2248 -1.0 atol=1e-6            #src\n@test g[1].Q[2, 2] \u2248 1.0 atol=1e-6            #src\n@test length(g[2].basis.polynomials) == 1     #src\n@test g[2].basis.polynomials[1] \u2248 (x[3] - x[1]) / \u221a2 #src\n@test size(g[2].Q) == (1, 1)                  #src\n@test g[2].Q[1, 1] \u2248 1.0 atol=1e-6            #src\n@test length(g[3].basis.polynomials) == 1     #src\n@test g[3].basis.polynomials[1] \u2248 (x[4] - x[2]) / \u221a2 #src\n@test size(g[3].Q) == (1, 1)                  #src\n@test g[3].Q[1, 1] \u2248 1.0 atol=1e-6            #src\n@test length(g[4].basis.polynomials) == 1     #src\n@test g[4].basis.polynomials[1] \u2248 (-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] \u2248 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(\u03b8, n)\n    [rand.(Exponential(\u03b8[1]),n) rand.(Poisson(\u03b8[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    \u03b8  ~ 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(\u03b8, 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 ? \u03a3 = Symmetric((1. + 1/S)*cov(zs)) : \u03a3 = I\n    z ~ MvNormal(m, \u03a3)\nend;\n\nfunction main(calibrated=true)\n    \u03b8\u2070 = [2.; 3.] # true parameters\n    n = 100 # sample size\n    S = 100 # number of simulation draws\n    # get data and statistics\n    y = dgp(\u03b8\u2070, n)\n    z = moments(y)\n    # sample chains\n    length = 5000\n    burnin = 500\n    chain = sample(abc(z, S, n, calibrated), \n        MH(:\u03b8 => 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] <= \u03b8\u2070[1] && q1[2] >= \u03b8\u2070[1]) \n    println()\n    println(\"is second true parameter inside 95% CI?\")\n    display(q2[1] <= \u03b8\u2070[2] && q2[2] >= \u03b8\u2070[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(\u03bc::Real, \u03c3::Real, C::Real)::Function\nReturn a Gaussian function with parameters \u03bc, \u03c3 and normalisation C.\n\"\"\"\nfunction gausg(\u03bc::Real, \u03c3::Real, C::Real)::Function\n\tfunction gausx(x::Real)\n\t\treturn C * pdf(Normal(\u03bc, \u03c3,), x)\n\tend\n\treturn gausx\nend\n\n\n\"\"\"\n    gausg2(\u03bc1::Real, \u03c31::Real, C1::Real, \u03bc2::Real, \u03c32::Real, C2::Real)\nReturn a function for the sum of two Gaussians with parameters\n    \u03bc1, \u03c31 and \u03bc2, \u03c32 and normalisations C1 and C2.\n\"\"\"\nfunction gausg2(\u03bc1::Real, \u03c31::Real, C1::Real, \u03bc2::Real, \u03c32::Real, C2::Real)::Function\n\tfunction gausx(x::Real)\n\t\treturn C1 * pdf(Normal(\u03bc1, \u03c31,), x) + C2 * pdf(Normal(\u03bc2, \u03c32,), 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, \u03bc, \u03c3), _ = func1dfit(gauss1, c, w, p0, lb, ub)\n\tgx = gausg(\u03bc, \u03c3, CC)\n\treturn FGauss([\u03bc], [\u03c3], [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\u03c3  = std(xx)\n\t@debug \"gfit_gauss_fm: \u03c3 = $\u03c3\"\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, \u03c3 / 10.0]\n    ub = [1.0e+6 * sum(w), \u03c3 * 10.0]\n    p0 = [         sum(w), \u03c3       ]\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    \u03c3Y   = sqrt.(Y)\n    lbl  = @sprintf \" \u03bc=%5.1f, \u03c3 =%5.1f \" fg.mu[1] fg.std[1]\n    lbl  = string(\"gaussian fit:\\n\", lbl)\n    p    = scatter(X, Y, yerror=\u03c3Y,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 \"\u03c3 =%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 \"\u03c3t =%4.1f mm, \u03c3 =%4.1f mm\" fg.std[1] fg.std[2]\n\tst  = @sprintf \"\u03c3t =%4.1f mm \" fg.std[1]\n\tsf  = @sprintf \"\u03c3  =%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\u03a6 = 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        \u03a6[j,k] = asin(Float32(Im));\r\n    else\r\n        \u03a6[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 ? \u03a6[j,k] = asin(Float32(Im)) : \u03a6[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 ? \u03a6[j,k] = asin(Im) : \u03a6[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\u03a6(\", j, \",\", k, \") = \", \u03a6[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(\"\u03a6(\", k, \",\", k, \") = \", \u03a6[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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7m` 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: `\u03b5` - 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.\u03b5\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\u00d7n_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 `\u03b5`.\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    \u03b5 = _estimate_epsilon(nodes, kernel)\r\n    return \u03b5\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\u00d7n_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\u00d7n_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 `\u03b5`.\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    \u03b5 = _estimate_epsilon(nodes, d_nodes, kernel)\r\n    return \u03b5\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\u00e1s, W. Hager, J. J\u00fadice, 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 `\u03b5`.\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    \u03b5 = _estimate_epsilon(Matrix(nodes'), kernel)\r\n    return \u03b5\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 `\u03b5`.\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    \u03b5 = _estimate_epsilon(Matrix(nodes'), Matrix(d_nodes'), kernel)\r\n    return \u03b5\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\u00d7n_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\u00d7n_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\u00d7n_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\u00d7n_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\u00f3\u017cnicowy\n\nDane:\nx \u2013 wektor d\u0142ugo\u015bci n + 1 zawieraj\u0105cy w\u0119z\u0142y x0, ..., xn\n    x[1] = x0, ..., x[n+1] = xn\nf \u2013 wektor d\u0142ugo\u015bci n + 1 zawieraj\u0105cy warto\u015bci interpolowanej funkcji w w\u0119z\u0142ach\n    f(x0), ..., f(xn)\n\nWyniki:\nfx\u2013 wektor d\u0142ugo\u015bci n + 1 zawieraj\u0105cy obliczone ilorazy r\u00f3\u017cnicowe\n    fx[1] = f[x0],\n    fx[2] = f[x0, x1], ..., fx[n] = f[x0, ..., xn\u22121], 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 \u2013 wektor d\u0142ugo\u015bci n + 1 zawieraj\u0105cy w\u0119z\u0142y x0, ..., xn\n    x[1] = x0, ..., x[n+1] = xn\nfx \u2013 wektor d\u0142ugo\u015bci n+ 1 zawieraj\u0105cy ilorazy r\u00f3\u017cnicowe\n    fx[1] = f[x0],\n    fx[2] = f[x0, x1], ..., fx[n] = f[x0, ..., xn\u22121], fx[n+1] =f [x0, ..., xn]\nt \u2013 punkt, w kt\u00f3rym nale\u017cy obliczy\u0107 warto\u015b\u0107 wielomianu\n\nWyniki:\nnt \u2013 warto\u015b\u0107 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 \u2013 wektor d\u0142ugo\u015bci n+ 1 zawieraj\u0105cy w\u0119z\u0142y x0, ..., xn\n    x[1] = x0, ..., x[n+1] = xn\nfx \u2013 wektor d\u0142ugo\u015bci n + 1 zawieraj\u0105cy ilorazy r\u00f3\u017cnicowe\n    fx[1] = f[x0],\n    fx[2] = f[x0, x1], ..., fx[n] = f[x0, ..., xn\u22121], fx[n+1] = f[x0, ..., xn]\n\nWyniki:\na \u2013 wektor d\u0142ugo\u015bci n+ 1 zawieraj\u0105cy obliczone wsp\u00f3\u0142czynniki postaci naturalnej\n    a[1] = a0,\n    a[2] = a1, ..., a[n] = an\u22121, 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\u0105ca wielomian interpolacyjny i interpolowan\u0105 funkcj\u0119 na danym przedziale\n\nDane:\nf \u2013 funkcja f(x) zadana jako anonimowa funkcja,\na, b \u2013 przedzia\u0142 interpolacji\nn \u2013 stopie\u0144 wielomianu interpolacyjnego\nfilename - nazwa pliku wynikowego\n\nWyniki:\n\u2013 funkcja rysuje wielomian interpolacyjny i interpolowan\u0105 funkcj\u0119 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\u0302 = onehot_encode(onecold(y_pred), 1:label_count)\n    return y\u0302 * 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; \u03b2=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 - `\u03b2=1`: the weight of precision in the combined score. If `\u03b2<1`, more weight given to `precision`, while `\u03b2>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; \u03b2=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 + \u03b2^2) * precision_ * recall_ / (precision_ + (\u03b2^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 \u03ba = 1. If there is no agreement among the raters other than what would be expected by chance,\n\u03ba = 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) \u2264 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 - \u221aeps\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\u03c0 / 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": "# Benchmark Optim.jl on logistic regression problems\n\nusing Optim, LineSearches\nusing LogisticOptTools\nusing Plots\n\nconst LOT = LogisticOptTools\n\n# Choose dataset to load\nDATASET = \"covtype.libsvm.binary.bz2\"\n# Choose penalty with given coefficient \u03bb\nPENALTY = LOT.L2Penalty(1e-2)\n\nif !isfile(DATASET)\n    println(\"Download dataset from $LIBSVM_URL\")\n    download(\"$LIBSVM_URL/$DATASET\", DATASET)\nend\n\n# Some plots utilities\n\"Display evolution of gradients along iteration.\"\nfunction display_grad(results::Optim.OptimizationResults,\n                      label::String,\n                      p::Plots.Plot)\n    exectime = [t.metadata[\"time\"] for t in results.trace]\n    exectime .-= exectime[1]\n    grad = [t.g_norm for t in results.trace]\n    plot!(p, exectime, log10.(grad), marker=true, label=label, markersize=1.)\nend\n\n\"Display evolution of functions along iteration.\"\nfunction display_func(results::Optim.OptimizationResults,\n                      f\u266f,\n                      label::String,\n                      p::Plots.Plot)\n    exectime = [t.metadata[\"time\"] for t in results.trace]\n    exectime .-= exectime[1]\n    values = [t.value for t in results.trace]\n    values .-= f\u266f\n    plot!(p, exectime, log10.(values), marker=true, label=label, markersize=1.)\nend\n\n\"Benchmark algorithms from Optim.jl\"\nfunction benchmark(algos, options, logreg)\n    p = LOT.nfeatures(logreg)\n    x = zeros(p)\n    g = zeros(p)\n    f, g!, _, _ = LOT.generate_callbacks(logreg)\n    # Activate precompilation\n    f(x)\n    g!(g, x)\n\n    results = []\n    for algo in algos\n        res = Optim.optimize(f, g!, x, algo, options)\n        push!(results, res)\n    end\n    return results\nend\n\nbfgs1 = BFGS(alphaguess=InitialHagerZhang(\u03b10=1.0),\n             linesearch=LineSearches.HagerZhang())\nbfgs2 = BFGS(alphaguess=InitialStatic(alpha=1.0),\n             linesearch=LineSearches.MoreThuente())\ncg = ConjugateGradient()\n\noptions = Optim.Options(iterations=100, store_trace=true, show_trace=true,\n                        g_tol=1e-5, allow_f_increases=true)\n\n# Load data\ndataset = LOT.LogitData(DATASET, scale_data=true)\n# Build logistic regression\nlogreg = LOT.LogisticRegressor(dataset.X, dataset.y, penalty=PENALTY, fit_intercept=true)\nresults = benchmark([bfgs1, bfgs2, cg], options, logreg)\n\n# Plot evolution of gradient\npg = plot(markershape=:rect)\ndisplay_grad.(results, [\"Optim BFGS HZ\", \"Optim BFGS MT\", \"Optim CG\"], Ref(pg))\nxlabel!(pg, \"Time (s)\")\nylabel!(pg, \"Gradient (log scale)\")\n\n# Plot evolution of function\npf = plot(markershape=:rect)\n# Get optimum\nf\u266f = minimum([res.minimum for res in results])\ndisplay_func.(results, f\u266f, [\"Optim BFGS HZ\", \"Optim BFGS MT\", \"Optim CG\"], Ref(pf))\nxlabel!(pf, \"Time (s)\")\nylabel!(pf, \"log(f - fopt) \")\n", "meta": {"hexsha": "798de8211eeaae9b070df888d79b2d27ed01d47b", "size": 2727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/optim.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": "examples/optim.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": "examples/optim.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": 30.9886363636, "max_line_length": 89, "alphanum_fraction": 0.6710671067, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.762327380224907}}
{"text": "## Packages\nusing Plots\n\n## Files\ninclude(\"FEM_aiyagari.jl\")\ninclude(\"NewtonRoot_mult.jl\")\n\n############ Plot basis functions #################\nplot(x -> \u03c8(x, [0, 1, 3, 6],1), xlim=(0, 6), label = \"\u03c8_1(x)\")\nplot!(x -> \u03c8(x, [0, 1, 3, 6], 2), xlim=(0, 6), label = \"\u03c8_2(x)\")\nplot!(x -> \u03c8(x, [0, 1, 3, 6], 3), xlim=(0, 6), label = \"\u03c8_3(x)\")\nplot!(x -> \u03c8(x, [0, 1, 3, 6], 4), xlim=(0, 6), label = \"\u03c8_4(x)\")\nsavefig(\"figs/linear_basis.png\")\n\n###################### Aiyagari ###########################\nhh = Household()\n\u03b8_init = [hh.aGrid; hh.aGrid .+ 0.5]\n\u03b8_est = NewtonRoot_mult(\u03b8->G(hh,\u03b8),\u03b8_init)\n\nplot(a->a,xlim = (0.0,6.1),label = \"45 degree\", color = :black, linestyle = :dash,legend =:topleft)\nplot!(a->get_apol(hh,a,hh.lGrid[1],\u03b8_est),xlim = (0.0,6.1),label = \"low\")\nplot!(a->get_apol(hh,a,hh.lGrid[2],\u03b8_est),xlim = (0.0,6.1),label = \"high\")\nscatter!(hh.aGrid,\u03b8_est[1:8],label = \"coefficient of basis (Low)\")\nscatter!(hh.aGrid,\u03b8_est[9:16],label = \"coefficient of basis (High)\")\nsavefig(\"figs/aiyagari.png\")\n\n\n\n\n", "meta": {"hexsha": "2f1510e49401f6086932661fae2bd43a6c79601a", "size": 1012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ellen/HW4/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": "Ellen/HW4/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": "Ellen/HW4/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": 33.7333333333, "max_line_length": 99, "alphanum_fraction": 0.557312253, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7623273745128943}}
{"text": "@syms \ud835\udc65\n@polyvar \ud835\udc66\n\nfunction poly(eq, v::Pair)\n    \u03b1, \u03b2 = value(first(v)), last(v)\n    terms = collect_powers(eq, \u03b1)\n\n    if !all(isone, denominator.(collect(keys(terms))))\n        error(\"fractional power not supported\")\n    end\n\n    sum([val*\u03b2^numerator(k) for (k,val) in terms]; init=0)\nend\n\nfunction poly(eq, \u03b2)\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] => \u03b2)\n    end\nend\n\npoly(eq) = poly(eq, \ud835\udc66)\n\nfunction sym(p::AbstractPolynomialLike, v::Pair)\n    \u03b2, \u03b1 = first(v), value(last(v))\n    sum([\u03b1^maxdegree(t,\u03b2)*c for (t,c) in zip(terms(p), coefficients(p))]; init=0)\nend\n\nsym(p::AbstractPolynomialLike, \u03b1) = sym(p, var(p) => \u03b1)\nsym(p::AbstractPolynomialLike) = sym(p, var(p) => \ud835\udc65)\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": "# ### m8.4t\n\nusing Pkg, DrWatson\n\n@quickactivate \"StatisticalRethinkingTuring\"\nusing Turing\nusing StatisticalRethinking\nTuring.setprogress!(false)\n\n# Can't really set a Uniform[-Inf,Inf] on \u03c3 \n\n# Turing model\n@model ppl8_4(y) = begin\n    \u03b1\u2081 ~ Uniform(-3000, 1000)\n    \u03b1\u2082 ~ Uniform(-1000, 3000)\n    \u03c3 ~ truncated(Cauchy(0,1), 0, Inf)\n\n    y .~ Normal(\u03b1\u2081 + \u03b1\u2082, \u03c3)\nend\n\n# Observations\n\ny = rand(Normal(0,1), 100);\n\n# Sample\n\nm8_4t = ppl8_4(y)\nnchains = 4; sampler = NUTS(0.65); nsamples=2000\nchns8_4t = mapreduce(c -> sample(m8_4t, sampler, nsamples), chainscat, 1:nchains)\n\n# Results rethinking\n\nm8_4rethinking = \"\n         mean      sd     5.5%   94.5% n_eff Rhat\n a1    -861.15 558.17 -1841.89  -31.04     7 1.43\n a2     861.26 558.17    31.31 1842.00     7 1.43\n sigma    0.97   0.07     0.89    1.09     9 1.17\n\";\n\n# Describe the posterior samples\n\nchns |> display\n\n# End of `08/m8.4t.jl`\n", "meta": {"hexsha": "ae9f1804a9c75f6d2f91f0cfee14a562f33024f0", "size": 891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/08/m8.4t.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/08/m8.4t.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/08/m8.4t.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": 19.8, "max_line_length": 81, "alphanum_fraction": 0.632996633, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7623253909774309}}
{"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": "using LinearAlgebra\nusing LoopVectorization\nusing BenchmarkTools\nusing StaticArrays\nusing RecursiveFactorization\nfunction cholfact!(A)\n    # fills in lower triangular portion\n    # total flops:\n    #   2*n*(n+1)*(n-1)/6 + n + n*(n+1)/2\n    # total assignments\n    #   n*(n+1)*(n-1)/6 + (n+1)/2\n    n = size(A,1)\n    for j = 1:n\n\n        # (n+1)*(n-1)/6\n        for k = 1:j-1  # loop over columns\n            for i = j:n\n                @inbounds A[i,j] -= A[i,k] * A[j,k]\n            end\n        end\n        ajj = sqrt(A[j,j])  # 1 flop\n\n        # (n+1)/2 flops\n        for i = j:n\n            @inbounds A[i,j] /= ajj\n        end\n    end\n    return A\nend\n\nfunction avxchol!(A)\n    n = size(A,1)\n    for j = 1:n\n\n        # (n+1)*(n-1)/6\n        for k = 1:j-1  # loop over columns\n            @turbo for i = j:n\n                A[i,j] -= A[i,k] * A[j,k]\n            end\n        end\n        ajj = sqrt(A[j,j])  # 1 flop\n\n        # (n+1)/2 flops\n        @turbo for i = j:n\n            A[i,j] /= ajj\n        end\n    end\nend\n\nfunction _chol_expr(j,n)\n    quote\n        for k = 1:$j-1  # loop over columns\n            @turbo for i = $j:$n\n                A[i,$j] -= A[i,k] * A[$j,k]\n            end\n        end\n        ajj = sqrt(A[$j,$j])\n\n        @turbo for i = $j:$n\n            A[i,$j] /= ajj\n        end\n    end\nend\n\n@generated function avxchol_unrolled!(A, ::Val{n}) where n\n    expr = [_chol_expr(j,n) for j = 1:n]\n    quote\n        $(Expr(:block, expr...))\n    end\nend\n\nn = 50\nA = randn(n,n); A = A'A;\nC = zero(A)\nprintln(\"Raw Loop\")\n@btime begin\n    $C .= $A\n    cholfact!($C)\nend\n\nC .= A\navxchol!(C)\nLowerTriangular(C) \u2248 cholesky(A).L\nprintln(\"avxchol\")\n@btime begin\n    $C .= $A\n    cholfact!($C)\nend\n\nprintln(\"LAPACK\")\n@btime begin\n    $C .= $A\n    LAPACK.potrf!('L', $C)\nend\n\nprintln(\"Static Arrays\")\nSM = similar_type(SMatrix{n,n,Float64})\n@btime cholesky($(SM(A)))\n@btime begin\n    Cs = $SM($A) \n    $C .= cholesky(Cs).L\nend\n\np = zeros(Int,n)\nlu = copy(A)\nRecursiveFactorization.lu!(lu, p)\nprintln(\"RF lu\")\n@btime RecursiveFactorization.lu!($lu, $p)", "meta": {"hexsha": "7154b34427a8750b2e71dfe52368812fc7a584c8", "size": 2057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dev/linalg.jl", "max_stars_repo_name": "bjack205/ALTRO.jl", "max_stars_repo_head_hexsha": "4864df2bb8ab8f629f451304cbaaa8e0017932d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dev/linalg.jl", "max_issues_repo_name": "bjack205/ALTRO.jl", "max_issues_repo_head_hexsha": "4864df2bb8ab8f629f451304cbaaa8e0017932d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/linalg.jl", "max_forks_repo_name": "bjack205/ALTRO.jl", "max_forks_repo_head_hexsha": "4864df2bb8ab8f629f451304cbaaa8e0017932d9", "max_forks_repo_licenses": ["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.0462962963, "max_line_length": 58, "alphanum_fraction": 0.490520175, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7623253851298631}}
{"text": "abstract type AbstractGrid end\n\nexport OneDGrid, TwoDGrid\n\n\"\"\"\n    TwoDGrid( dimx, nx, dimy, ny)\n\nGenerate a cartesians mesh on rectangle `dimx`x `dimy` with `nx` x `ny` points\n\n- `nx` : indices are in [1:nx]\n- `ny` : indices are in [1:ny]\n- `dimx = xmax - xmin`\n- `dimy = ymax - ymin`\n- `x, y` : node positions\n- `dx, dy` : step size\n\"\"\"\nstruct TwoDGrid <: AbstractGrid\n    nx::Int\n    ny::Int\n    xmin::Float64\n    xmax::Float64\n    ymin::Float64\n    ymax::Float64\n    dimx::Float64\n    dimy::Float64\n    x::Vector{Float64}\n    y::Vector{Float64}\n    dx::Float64\n    dy::Float64\n\n    function TwoDGrid(xmin, xmax, nx::Int, ymin, ymax, ny::Int)\n        dimx = xmax - xmin\n        dimy = ymax - ymin\n\n        x = collect(LinRange(0, dimx, nx + 1))\n        y = collect(LinRange(0, dimy, ny + 1))\n\n        dx = dimx / nx\n        dy = dimy / ny\n\n        return new(nx, ny, xmin, xmax, ymin, ymax, dimx, dimy, x, y, dx, dy)\n    end\nend\n\nTwoDGrid(dimx, nx::Int, dimy, ny::Int) = TwoDGrid(0.0, dimx, nx, 0.0, dimy, ny)\n\n\"\"\"\n    TwoDGrid( xmin, xmax, nx, ymin, ymax, ny )\n\nSimple structure to store mesh data from 2 dimensions\n\"\"\"\nstruct OneDGrid <: AbstractGrid\n    nx::Int\n    xmin::Float64\n    xmax::Float64\n    dimx::Float64\n    dx::Float64\n    x::Vector{Float64}\n\n    function OneDGrid(xmin, xmax, nx::Int)\n        dimx = xmax - xmin\n        dx = dimx / (nx - 1)\n        x = collect(LinRange(0, dimx, nx + 1))\n\n        return new(nx, xmin, xmax, dimx, dx, x)\n    end\nend\n\nexport get_x\n\n\"\"\"  \n    get_x( mesh, i )\n\nGet position\n\"\"\"\nfunction get_x(m::OneDGrid, i)\n    return m.xmin + (i - 1) * m.dx\nend\n\n\"\"\"  \n    get_cell_and_offset( mesh, x )\n\nGet cell and offset\n\nWe compute the cell indices where the particle is and its relative \nnormalized position inside the cell\n\n\"\"\"\nfunction get_cell_and_offset(m::OneDGrid, x)\n    cell = floor(Int64, ((x - m.xmin) / m.Lx) * m.nx) + 1\n    offset = (x - get_x(m, cell)) / dx\n\n    return cell, offset\nend\n", "meta": {"hexsha": "ac6bb4684e882b0295d2f4c597ac3f35894e658f", "size": 1943, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mesh.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/mesh.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/mesh.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": 20.4526315789, "max_line_length": 79, "alphanum_fraction": 0.5954709213, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7623253846477088}}
{"text": "# ---\n# title: 1362. Closest Divisors\n# id: problem1362\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math\n# link: <https://leetcode.com/problems/closest-divisors/description/>\n# hidden: true\n# ---\n# \n# Given an integer `num`, find the closest two integers in absolute difference\n# whose product equals `num + 1` or `num + 2`.\n# \n# Return the two integers in any order.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: num = 8\n#     Output: [3,3]\n#     Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: num = 123\n#     Output: [5,25]\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: num = 999\n#     Output: [40,25]\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= num <= 10^9`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "bffca44d170e5aafdc9ae052cff135375817d873", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1362.closest-divisors.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/1362.closest-divisors.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/1362.closest-divisors.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.8035714286, "max_line_length": 140, "alphanum_fraction": 0.5451647184, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7623183894543262}}
{"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 \u03b4 if \u03f5 tolerance\n\tas below\n    =#\n    \u03b4::Float64 = 1/10^5\n    \u03f5::Float64 = \u03b4/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) > \u03f5\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 \u03b4 if \u03f5\n    tolerance as below.\n    =#\n    \u03b4::Float64 = 1/10^5\n    \u03f5::Float64 = \u03b4/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) > \u03f5\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": "# load required modules\nusing CategoricalArrays\nusing CSV\nusing DataFrames\nusing Distributions\nusing Random\nusing StatsBase\n\n# set seed for reproducible sequence of numbers\nRandom.seed!(42);\n\n# create a sample dataframe\ndf = DataFrame(\n    Dict(\n        :x1 => rand(Normal(10, 1), 100),\n        :x2 => [sample([\"Good\", \"Better\", \"Best\"], pweights([0.2, 0.5, 0.3])) for i=1:100],\n        :x3 => rand(Pareto(10, 1), 100)\n    )\n)\n\n# get type of df\ntypeof(df)\n\n# access 1 row\ndf[1, :]\n\n# access 1 and 2 row\ndf[[1, 2],:]\n\n# access x1 column vector\ndf[:, :x1]\n\n# access x1 column dataframe\ndf[:,[:x1]]\n\n# access column x1 and x2\ndf[:, [:x1, :x2]]\n\n# slicing dataframe by indeces\ndf[1:2, 1:2]\n\n# slicing dataframe by column names\ndf[1:2, [:x1, :x2]]\n\n# select only x2 == \"Better\"\nmask = [df[i,:x2] == \"Better\" for i=1:nrow(df)]\ndf[mask, :]\n\n# select only x2 == \"Better\" using bit vector\ndf[df[:, :x2] .== \"Better\", :]\n\n# generate random string vector with missing values\narr = [isodd(i) ? \n    sample([\"Good\", \"Better\", \"Best\"], pweights([0.2, 0.4, 0.3])) : \n    missing for i = 1:nrow(df)]\n\n# create categorical array\ncarr = categorical(arr)\n\nlevels(carr)\n\nCSV.write(\"../../data/interim/df.csv\", df)\n\nCSV.read(\"../../data/interim/df.csv\", DataFrame)\n\n# obtain dataframe dimensions\nsize(df)\n\n# obtain dataframe row number\nnrow(df)\n\n# obtain dataframe column number\nncol(df)\n\n# access first 5 rows\nfirst(df, 5)\n\n# access last 5 rows\nlast(df, 5)\n\n# describe dataframe\ndescribe(df)\n\n# describe dataframe column\ndescribe(df[:, :x1])\n\n# describe dataframe column\ndescribe(df[:, [:x1]])\n\n# sort dataframe by x1 ascending\nsort(df, :x1)\n\n# sort dataframe by x1 descending\nsort(df, :x1, rev=true)\n\n# sort by x1 asc and x2 desc\nsort(df, [:x1, :x2], rev=[false, true])\n\n# obtain count group by x2\ncombine(groupby(df, :x2), nrow)\n\n# obtain sum group by x2\ncombine(groupby(df, :x2), :x1 => sum, :x3 => sum)\n\n# obtain aggregates of x1 column\ncombine(df, :x1 => mean, :x1 => median, :x1 => std)\n", "meta": {"hexsha": "a16cd43bb0d08fa87c87ac53ec79a38cb39ec14e", "size": 1973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/202105161858-julia-working-with-data.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/202105161858-julia-working-with-data.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/202105161858-julia-working-with-data.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": 18.4392523364, "max_line_length": 91, "alphanum_fraction": 0.6447034972, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7623183789200729}}
{"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": "#using  NearestNeighbors: Metric\n#import Distances: evaluate\nusing StatsBase: mode\n\n#evaluate(dist::dwt, a, b) = dtw_distance(a, b, dist.w)\n\n\"\"\"\n   `dtw_distance(a, b, w)` is the basic dynamic time wraping function.\nwhere `a` & `b` are the time series matrices and `w` is the percentage \nof window for warping.\n\"\"\"\nfunction dtw_distance(a, b, w)\n    l_a, l_b = length(a), length(b)\n    FloatMax = maxintfloat(Float64)\n    if w <= 0\n        band = max(l_b, l_a)\n    else\n        band = floor(Int, w*max(l_b, l_a))\n    end\n    M = zeros(l_a+1,l_b+1)\n    M[1, 2:end] .= FloatMax\n    M[2:end, 1] .= FloatMax\n    for k=2:l_a \n        M[k, 2:end] =  (a .-  b[k]).^2\n    end\n    for i=2:l_a+1\n        jstart = max(2, i-band)\n        jstop = min(l_b+1, i+band+1)\n        idx_inf_left = i-band-1\n        \n        if idx_inf_left >= 1\n            M[i, idx_inf_left] = FloatMax\n        end\n        for j=jstart:jstop\n            im = i-1\n            jm = j-1\n            M[i,j] = M[i,j] + min(min(M[im,j], M[i,jm]), M[im,jm])\n        end\n        if jstop < l_b + 1\n            M[i,jstop] = FloatMax\n        end\n    end\n    return M[l_a+1,l_b+1]   \nend\n\nfunction Predict_new(m, X::Array, Y::Array, yplane::Array) \n    k = m.n_neighbors\n    n_train, serieslength = size(X)\n    n_test = size(Y, 1)\n    y_pred = zeros(n_test)\n    DistanceMatrix = zeros(n_test, n_train)\n    for i=1:n_test\n        for j=1:n_train\n            DistanceMatrix[i, j] = dtw_distance(X[j,:],Y[i,:], m.metric_params[1])\n        end\n    end\n    index = select_sort(DistanceMatrix, k)\n    y_index = yplane[Int.(index)]\n    for i=1:n_test\n        y_pred[i] = mode(y_index[i, :])\n    end\n    return y_pred, DistanceMatrix\nend\n\nfunction select_sort(A, k) # some times we get consicative indx\n    n_test, n_train = size(A)\n    index = zeros(n_test, k)\n    for l=1:n_test\n        for i=1:n_train\n            if i > k\n                break \n            end\n            min_idx = i \n            for j=i+1:n_train\n                if A[l, min_idx] > A[l, j] \n                    min_idx = j    \n                end             \n            end    \n            A[l, i], A[l, min_idx] = A[l, min_idx], A[l, i]\n            index[l, i] = min_idx\n        end\n    end\n    return index\nend\n\n# Add tuning and fit!, predic interface", "meta": {"hexsha": "ed64534c27ae64c2c6d3e8d7105238b24e639260", "size": 2273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances.jl", "max_stars_repo_name": "ablaom/MLJTime.jl", "max_stars_repo_head_hexsha": "8e304292812860fced71fbedd87263cc01f1407f", "max_stars_repo_licenses": ["MIT"], "max_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": "ablaom/MLJTime.jl", "max_issues_repo_head_hexsha": "8e304292812860fced71fbedd87263cc01f1407f", "max_issues_repo_licenses": ["MIT"], "max_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": "ablaom/MLJTime.jl", "max_forks_repo_head_hexsha": "8e304292812860fced71fbedd87263cc01f1407f", "max_forks_repo_licenses": ["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.4302325581, "max_line_length": 82, "alphanum_fraction": 0.5235371755, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7622882500595696}}
{"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{\u211d,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": "module FESpaceWithConstantFixedTests\nusing Gridap\nusing Gridap.Geometry\nusing Gridap.FESpaces\nusing Gridap.ReferenceFEs\nusing Test\n\ndomain = (0,1,0,1)\npartition = (4,4)\nmodel = CartesianDiscreteModel(domain,partition)\n\ntrian = get_triangulation(model)\n\norder = 2\n\nV = FESpace(model,ReferenceFE(lagrangian,Float64,order);conformity=:L2)\n\nV0 = FESpaceWithConstantFixed(V,true,rand(1:num_free_dofs(V)))\ntest_single_field_fe_space(V0)\n\n@test Gridap.FESpaces.ConstantApproach(V0) == Gridap.FESpaces.FixConstant()\n\nuh0 = interpolate(V0) do x\n    sin(4*pi*(x[1]+x[2]^2)) + 3\nend\nusing Gridap.Visualization\n\n#writevtk(trian,\"trian\",nsubcells=20,cellfields=[\"uh0\"=>uh0])\n\nend # module\n", "meta": {"hexsha": "68c5cb999d93890d47e0e7e3b16250edc70c4ddc", "size": 676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FESpacesTests/FESpacesWithConstantFixedTests.jl", "max_stars_repo_name": "aerappa/Gridap.jl", "max_stars_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 390, "max_stars_repo_stars_event_min_datetime": "2019-05-16T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:17.000Z", "max_issues_repo_path": "test/FESpacesTests/FESpacesWithConstantFixedTests.jl", "max_issues_repo_name": "aerappa/Gridap.jl", "max_issues_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 576, "max_issues_repo_issues_event_min_datetime": "2019-05-16T20:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:21:35.000Z", "max_forks_repo_path": "test/FESpacesTests/FESpacesWithConstantFixedTests.jl", "max_forks_repo_name": "aerappa/Gridap.jl", "max_forks_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2019-12-30T23:35:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:56:24.000Z", "avg_line_length": 21.8064516129, "max_line_length": 75, "alphanum_fraction": 0.7707100592, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7622882452000096}}
{"text": "\"\"\"\n## rod_km!\n\nThis subroutine forms the stiffness matrix of a 1-d \"rod\" fin_el.\n\n### Function\n```julia\nrod_km!(km, ea, length)\n```\n\n### Arguments\n```julia\n* km::Matrix{Float64}       : Element stiffness matrix (Updated)\n* ea::Float64               : Element stiffness\n* ell::Float64              : Element length\n```\n\"\"\"\nfunction rod_km!(km::Matrix{Float64}, ea::Float64, ell::Float64)\n  #\n  # This subroutine forms the stiffness matrix of a 1-d \"rod\" fin_el.\n  #\n km = [1.0 -1.0;-1.0 1.0]\n km *= ea/ell\nend", "meta": {"hexsha": "e2d2a7972e056982921e7c97b55de1438a70b9b8", "size": 509, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PtFEM/Main/rod_km.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/rod_km.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/rod_km.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.2083333333, "max_line_length": 69, "alphanum_fraction": 0.6110019646, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7622882447007703}}
{"text": "using QuasiMonteCarlo, Distributions, Test\nusing Test\n\n#1D\nlb = 0.0\nub = 5.0\nn = 5\nd = 1\nQuasiMonteCarlo.sample(n,lb,ub,GridSample(0.1))\nQuasiMonteCarlo.sample(n,lb,ub,UniformSample())\nQuasiMonteCarlo.sample(n,lb,ub,SobolSample())\nQuasiMonteCarlo.sample(n,lb,ub,LatinHypercubeSample())\nQuasiMonteCarlo.sample(n,lb,ub,LatticeRuleSample())\nQuasiMonteCarlo.sample(20,lb,ub,LowDiscrepancySample(10))\nQuasiMonteCarlo.sample(5,d,Cauchy())\nQuasiMonteCarlo.sample(5,d,Normal(0,4))\n\n#ND\nlb = [0.1,-0.5]\nub = [1.0,20.0]\nn = 5\nd = 2\n\n@testset \"GridSample\" begin\n    #GridSample{T}\n    s = QuasiMonteCarlo.sample(n,lb,ub,GridSample([0.1,0.5]))\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"UniformSample\" begin\n    #UniformSample()\n    s = QuasiMonteCarlo.sample(n,lb,ub,UniformSample())\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"SobolSample\" begin\n    #SobolSample()\n    s = QuasiMonteCarlo.sample(n,lb,ub,SobolSample())\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"LHS\" begin\n    #LHS\n    s = QuasiMonteCarlo.sample(n,lb,ub,LatinHypercubeSample())\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"LatticeRuleSample\" begin\n    #LatticeRuleSample()\n    s = QuasiMonteCarlo.sample(n,lb,ub,LatticeRuleSample())\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"LDS\" begin\n    #LDS\n    s = QuasiMonteCarlo.sample(n,lb,ub,LowDiscrepancySample([10,3]))\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"Distribution 1\" begin\n    #Distribution 1\n    s = QuasiMonteCarlo.sample(n,d,Cauchy())\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"Distribution 2\" begin\n    #Distribution 2\n    s = QuasiMonteCarlo.sample(n,d,Normal(3,5))\n    @test isa(s,Matrix{typeof(s[1][1])}) == true\n    @test size(s) == (d, n)\nend\n\n@testset \"generate_design_matrices\" begin\n    num_mat = 3\n    Ms = QuasiMonteCarlo.generate_design_matrices(n,lb,ub,UniformSample(), num_mat)\n    @test length(Ms) == num_mat\n    A = Ms[1]\n    B = Ms[2]\n    @test isa(A, Matrix{typeof(A[1][1])}) == true\n    @test size(A) == (d, n)\n    @test isa(B, Matrix{typeof(B[1][1])}) == true\n    @test size(B) == (d, n)\nend\n", "meta": {"hexsha": "a15a50692eb40377391ff5622685a44231ab9c25", "size": 2369, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "KirillZubov/QuasiMonteCarlo.jl", "max_stars_repo_head_hexsha": "4cb41dda1703ba853e68f62a16e3e52a905b0ca0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2020-04-15T16:57:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T12:13:39.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "KirillZubov/QuasiMonteCarlo.jl", "max_issues_repo_head_hexsha": "4cb41dda1703ba853e68f62a16e3e52a905b0ca0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-04-15T19:03:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T19:05:12.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "KirillZubov/QuasiMonteCarlo.jl", "max_forks_repo_head_hexsha": "4cb41dda1703ba853e68f62a16e3e52a905b0ca0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-04-15T17:06:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T15:29:01.000Z", "avg_line_length": 26.032967033, "max_line_length": 83, "alphanum_fraction": 0.6416209371, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847496, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7622882408396882}}
{"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# \u2554\u2550\u2561 9e38d21a-f785-11ea-1ce0-5d313a4e9a7e\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 9e393624-f785-11ea-077b-cb4f64059bb3\nbegin\n\t@quickactivate \"StatisticalRethinkingTuring\"\n\tusing StatisticalRethinking\nend\n\n# \u2554\u2550\u2561 4e27a698-f785-11ea-1ded-a548d1953a14\nmd\"## Fig3.1t.jl\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d13a98ea-f785-11ea-0cb5-e51b20ddcdac\nplot(p1, p2, layout=(1,2))\n\n# \u2554\u2550\u2561 9e520366-f785-11ea-1d50-8f7ab0c29c9c\nmd\"## End of Fig3.1t.jl\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25004e27a698-f785-11ea-1ded-a548d1953a14\n# \u2560\u25509e38d21a-f785-11ea-1ce0-5d313a4e9a7e\n# \u2560\u25509e393624-f785-11ea-077b-cb4f64059bb3\n# \u2560\u25509e3b92a2-f785-11ea-090f-a78cbded0a8d\n# \u2560\u25509e43adc0-f785-11ea-2b6a-f11004009094\n# \u2560\u2550d13a98ea-f785-11ea-0cb5-e51b20ddcdac\n# \u255f\u25009e520366-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": "using DataStructures\n# author: Younis Shah\n\n# Gates: H, CNOT, S, Pauli gates\n\nb\u2081 = [0, 1]\nb\u2080 = [1, 0]\n\n# Hadamard gate\n# H = [1\\\u221a2  1\\\u221a2]\n#     [1\\\u221a2 -1\\\u221a2]\nH = round(1/sqrt(2) * [1 1; 1 -1], 3)\n\n# Pauli X gate\n\u03c3\u2093 = [0 1;\n      1 0]\n\n# Pauli Y gate\nY = [0 -im;\n     im 0]\n\n# Pauli Z gate\nZ = [1 0;\n     0 -1]\n\n# Phase gate\n# S= [1 0]\n#    [0 \u03b9]\nS = [1 0;\n     0 im]\n\n# Controlled NOT gate\nCNOT = [1 0 0 0;\n        0 1 0 0;\n        0 0 0 1;\n        0 0 1 0]\n\n# 2x2 Identity matrix\n\u0399 = eye(Int64, 2)\n\ngate_symbol_list = (:X, :Y, :Z, :H, :S)\n\ngate_list = (\"I\", \"H\", \"X\", \"Y\", \"Z\", \"CNOT\", \"S\")\n\n# |0\u27e9 = [1]\n#       [0]\npure_state_0 = [1, 0]\n#|1\u27e9 = [0]\n#      [1]\npure_state_1 = [0, 1]\n\n# Define a new Qubit type\n# Rest -TODO\ntype Qubit\n  index::Int64\n  ket::Array\nend\n\n# Define a QuantumRegister type\n# Rest - TODO\ntype QuantumRegister\n  register::Array{Qubit}\nend\n\n# Define a new Stage output type\ntype StageOutput\n  index::Int64\n  output::Union(Array, SparseMatrixCSC)\nend\n\n# Define a new type to store all the Stage outputs\ntype StageOutputDeque\n  stages::Deque{StageOutput}\nend\n\n# Define a new Gate type using which gates are represnted as matrices\ntype Gate\n  qubit::Int64\n  name::String\n  repr::Array\nend\n\n# Define a new Gates type: the number of gates and qubits\n# Represents total gates per stage\ntype Gates\n  gates::Array{Gate}\n  nqubits::Int64\nend\n\n", "meta": {"hexsha": "c3fb2b78163efba8092b7a61ae1770b775e497f7", "size": 1356, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simulator/CherokeeQuantumGates.jl", "max_stars_repo_name": "younisshah/cherokee", "max_stars_repo_head_hexsha": "4676c3e5a4b23bcd73c6af3f9cd73912b97f8a09", "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": "simulator/CherokeeQuantumGates.jl", "max_issues_repo_name": "younisshah/cherokee", "max_issues_repo_head_hexsha": "4676c3e5a4b23bcd73c6af3f9cd73912b97f8a09", "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": "simulator/CherokeeQuantumGates.jl", "max_forks_repo_name": "younisshah/cherokee", "max_forks_repo_head_hexsha": "4676c3e5a4b23bcd73c6af3f9cd73912b97f8a09", "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.0666666667, "max_line_length": 69, "alphanum_fraction": 0.5995575221, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.762170665804868}}
{"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\u2081 = T / 2 + sqrt((T^2 / 4) - D)\n\tL\u2082 = T / 2 - sqrt((T^2 / 4) - D)\n\tvalues = [L\u2081, L\u2082]\n\n\tglobal vectors = []\n\n\tif !iszero(c)\n\t\tpush!(vectors, [L\u2081 - d, c])\n\t\tpush!(vectors, [L\u2082 - d, c])\n\telseif !iszero(b)\n\t\tpush!(vectors, [b, L\u2081 - a])\n\t\tpush!(vectors, [b, L\u2082 - 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) \u2208 R+ \u00d7 Rn |  ||x|| \u2264 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\u2a25\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    \u03bb, U = LinearAlgebra.eigen(X)\n    D = LinearAlgebra.Diagonal(max.(\u03bb, 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]) + \u212f * 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 \u00b1Inf 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) \u2208 R+ \u00d7 Rn |  ||x|| \u2264 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\u2a25\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    \u03bb, U = LinearAlgebra.eigen(X)\n    Tp = promote_type(T, Float64)\n\n    # if all the eigenvalues are >= 0\n    if all(\u03bbi \u2265 zero(\u03bbi) for \u03bbi in \u03bb)\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(\u03bbi < 1e-4 for \u03bbi in \u03bb)\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\u0303 = unvec_symm(y, dim)\n        B = U' * X\u0303 * 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                    \u03bbpi = max(\u03bb[i], zero(Tp))\n                    \u03bbmj = -min(\u03bb[j], zero(Tp))\n                    @inbounds B[i, j] *= \u03bbpi / (\u03bbmj + \u03bbpi)\n                elseif (i <= k && j > k)\n                    \u03bbmi = -min(\u03bb[i], zero(Tp))\n                    \u03bbpj = max(\u03bb[j], zero(Tp))\n                    @inbounds B[i, j] *= \u03bbpj / (\u03bbmi + \u03bbpj)\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] = \u2202projection_on_set[i] / \u2202v[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) \u2248 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) \u2264 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) \u2264 \u03c4\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(\u03c4)\n\n    @inbounds for i in 1:n-1\n        tsum += u[s_indices[i]]\n        tmax = (tsum - \u03c4) / i\n        if tmax \u2265 u[s_indices[i+1]]\n            bget = true\n            break\n        end\n    end\n    if !bget\n        tmax = (tsum + u[s_indices[n]] - \u03c4) / 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( \u03c1::Real, \u03c3::Real ; Z\u0304::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 `\u03c1` is the auto-reg coefficient, `Z\u0304` is the mean value, `\u03c3` is the std of the error term ``\\\\epsilon_t``\nwhich follows i.i.d. `N(0,\u03c3)`, 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    \u03c1::Real\n    Z\u0304::Real\n    Z0::Union{Real,Distributions.UnivariateDistribution}\n    \u03c3::Real\n    # ---------------\n    function DiscreteTimeAR1( \u03c1::Real, \u03c3::Real ; Z\u0304::Real = 0.0, Z0::Union{Real,Distributions.UnivariateDistribution} = 0.0 )\n        @assert(isfinite(\u03c1), \"rho must be finite\"); @assert(isfinite(Z\u0304), \"the mean value must be finite\")\n        @assert(0<\u03c3<Inf, \"sigma must be non-negative and finite\")\n        isa(Z0, Real) ?  @assert(isfinite(Z0), \"Z0 must be finite\") : nothing\n        # -----\n        return new(\u03c1,Z\u0304,Z0,\u03c3)\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(\u03c1::Real, \u03c3::Real ; m::Int = 9, \u03bb::Int = 3, Z\u0304::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 `\u03c1` is the auto-regression coefficient, `\u03c3` is the standard error of ``\\\\epsilon_t``,\n`m` is the number of the new Markov chain's states, `Z\u0304` is the mean of `Zt`.\n`\u03bb>0` is the absolute maximum deviation of the Markov chain's states,\nit is defined as `max(z) = \u03bb\u03c3`, 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 `\u03bb=3` are enough to approximate an AR(1).\n\"\"\"\nfunction approx_ar1(\u03c1::Real, \u03c3::Real ; m::Int = 9, \u03bb::Real = 3, Z\u0304::Real = 0.0 )\n    # assertions\n    abs(\u03c1) < 1  ?  nothing : @warn(\"the AR(1) process is not stationary becuase abs(\u03c1) >=1\")\n    @assert(0 < \u03c3 < 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 < \u03bb < Inf, \"the absolute deviation must be greater than 0 and finite\")\n    @assert(isfinite(Z\u0304), \"the mean value of Zt must be finite\")\n    # 1. states\n    local w::Vector = zeros(m)\n    w[1] = -\u03bb * \u03c3 / \u221a(1-\u03c1^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]-\u03c1*w[x])/\u03c3 + 0.5 * steplen / \u03c3 )\n        if m>2\n            for y in 2:(m-1)\n                P[x,y] = Distributions.cdf(tmpNorm, (w[y]-\u03c1*w[x])/\u03c3 + 0.5 * steplen / \u03c3 ) -\n                    Distributions.cdf(tmpNorm, (w[y]-\u03c1*w[x])/\u03c3 - 0.5 * steplen / \u03c3 )\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\u0304)::DiscreteMarkovChain # add mean value to state\nend # approx_ar1\n# -------------------\napprox_ar1(ar1::DiscreteTimeAR1 ; m::Int = 9, \u03bb::Real = 3) = begin\n    return approx_ar1(ar1.\u03c1, ar1.\u03c3, m = m, \u03bb = \u03bb, Z\u0304 = ar1.Z\u0304)::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 \u03bcs (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 Test\nusing DiffEqPhysics, ForwardDiff, OrdinaryDiffEq\nusing StaticArrays, LinearAlgebra, Random\n\ntest_solve(prob...) = mapreduce(p->solve(p, VelocityVerlet(), dt=1//2).u, ==, prob)\n\nH(d\u03b8, \u03b8, p) = d\u03b8 / 2 - 9.8 * cos(\u03b8)\np0, q0   = rand(2)\nacc      = (v, x, p, t) -> ForwardDiff.derivative(x -> -H(v[1], x, p), x[1])\nvel      = (v, x, p, t) -> ForwardDiff.derivative(v -> H(v, x[1], p), v[1])\nprob1    = HamiltonianProblem(H, p0, q0, (0., 10.))\nprob_1   = DynamicalODEProblem(acc, vel, p0, q0, (0., 10.))\n@test test_solve(prob1, prob_1)\n\n\np0 = @SVector rand(2)\nq0 = @SVector rand(2)\nH(d\u03b8, \u03b8, p) = d\u03b8[1] / 2 + d\u03b8[2] / 2 - 9.8 * cos(\u03b8[1]) - 9.8 * cos(\u03b8[2])\nprob2    = HamiltonianProblem(H, p0, q0, (0., 10.))\nacc      = (v, x, p, t) -> ForwardDiff.gradient(x -> -H(v, x, p), x)\nvel      = (v, x, p, t) -> ForwardDiff.gradient(v -> H(v, x, p), v)\nprob_2   = DynamicalODEProblem(acc, vel, p0, q0, (0., 10.))\n@test test_solve(prob2, prob_2)\n\n\nH(d\u03b8, \u03b8, p) = (d\u03b8 / 2 - 9.8 * cos.(\u03b8))[1]\np0, q0 = [rand(5) for i in 1:2]\nacc = (dv, v, x, p, t) -> ForwardDiff.gradient!(dv, x -> -H(v, x, p), x)\nvel = (dx, v, x, p, t) -> ForwardDiff.gradient!(dx, v -> H(v, x, p), v)\nprob3  = HamiltonianProblem(H, p0, q0, (0., 10.))\nprob_3 = DynamicalODEProblem(acc, vel, p0, q0, (0., 10.))\n@test test_solve(prob3, prob_3)\n", "meta": {"hexsha": "1337c98069abe167bfb1c8e85de5063b4d50c2a5", "size": 1300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/hamiltonian_test.jl", "max_stars_repo_name": "KlausC/DiffEqPhysics.jl", "max_stars_repo_head_hexsha": "9aa27ba987794c724247f5450b8598607342bd93", "max_stars_repo_licenses": ["MIT"], "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/hamiltonian_test.jl", "max_issues_repo_name": "KlausC/DiffEqPhysics.jl", "max_issues_repo_head_hexsha": "9aa27ba987794c724247f5450b8598607342bd93", "max_issues_repo_licenses": ["MIT"], "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/hamiltonian_test.jl", "max_forks_repo_name": "KlausC/DiffEqPhysics.jl", "max_forks_repo_head_hexsha": "9aa27ba987794c724247f5450b8598607342bd93", "max_forks_repo_licenses": ["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.3939393939, "max_line_length": 83, "alphanum_fraction": 0.57, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7621636564431377}}
{"text": "using LinearAlgebra\n\n\neye(n) = Matrix{Float64}(I,n,n)\neye(n,m) = Matrix{Float64}(I,n,m)\n\nfunction e(i, dims)\n    E = Matrix{Float64}(I, dims, dims)\n    return E[:,i]\nend\n", "meta": {"hexsha": "3f600925ebc24a916a809e3f320e4e9888b86986", "size": 170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MatlabHelper.jl", "max_stars_repo_name": "ueliwechsler/MPCHelper.jl", "max_stars_repo_head_hexsha": "47612810337fb7e38695d4597d060b743ccb2f65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MatlabHelper.jl", "max_issues_repo_name": "ueliwechsler/MPCHelper.jl", "max_issues_repo_head_hexsha": "47612810337fb7e38695d4597d060b743ccb2f65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MatlabHelper.jl", "max_forks_repo_name": "ueliwechsler/MPCHelper.jl", "max_forks_repo_head_hexsha": "47612810337fb7e38695d4597d060b743ccb2f65", "max_forks_repo_licenses": ["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.4545454545, "max_line_length": 38, "alphanum_fraction": 0.6294117647, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7621636560540002}}
{"text": "# canonical data version: 1.3.0\n\nusing Test\n\ninclude(\"complex-numbers.jl\")\n\n@test ComplexNumber <: Number\n\n@test ComplexNumber(0, 1)^2 == ComplexNumber(-1, 0)\n\n@testset \"Arithmetic\" begin\n    @testset \"Addition\" begin\n        @test ComplexNumber(1, 0) + ComplexNumber(2, 0) == ComplexNumber(3, 0)\n        @test ComplexNumber(0, 1) + ComplexNumber(0, 2) == ComplexNumber(0, 3)\n        @test ComplexNumber(1, 2) + ComplexNumber(3, 4) == ComplexNumber(4, 6)\n    end\n\n    @testset \"Subtraction\" begin\n        @test ComplexNumber(1, 0) - ComplexNumber(2, 0) == ComplexNumber(-1, 0)\n        @test ComplexNumber(0, 1) - ComplexNumber(0, 2) == ComplexNumber(0, -1)\n        @test ComplexNumber(1, 2) - ComplexNumber(3, 4) == ComplexNumber(-2, -2)\n    end\n\n    @testset \"Multiplication\" begin\n        @test ComplexNumber(1, 0) * ComplexNumber(2, 0) == ComplexNumber(2, 0)\n        @test ComplexNumber(0, 1) * ComplexNumber(0, 2) == ComplexNumber(-2, 0)\n        @test ComplexNumber(1, 2) * ComplexNumber(3, 4) == ComplexNumber(-5, 10)\n    end\n\n    @testset \"Division\" begin\n        @test ComplexNumber(1, 0) / ComplexNumber(2, 0) == ComplexNumber(0.5, 0)\n        @test ComplexNumber(0, 1) / ComplexNumber(0, 2) == ComplexNumber(0.5, 0)\n        @test ComplexNumber(1, 2) / ComplexNumber(3, 4) \u2248 ComplexNumber(0.44, 0.08)\n    end\nend\n\n@testset \"Absolute value\" begin\n    @test abs(ComplexNumber(5, 0))  == 5\n    @test abs(ComplexNumber(-5, 0)) == 5\n    @test abs(ComplexNumber(0, 5))  == 5\n    @test abs(ComplexNumber(0, -5)) == 5\n    @test abs(ComplexNumber(3, 4))  == 5\nend\n\n@testset \"Complex conjugate\" begin\n    @test conj(ComplexNumber(5, 0))  == ComplexNumber(5, 0)\n    @test conj(ComplexNumber(0, 5))  == ComplexNumber(0, -5)\n    @test conj(ComplexNumber(1, 1))  == ComplexNumber(1, -1)\nend\n\n@testset \"Real part\" begin\n    @test real(ComplexNumber(1, 0)) == 1\n    @test real(ComplexNumber(0, 1)) == 0\n    @test real(ComplexNumber(1, 2)) == 1\nend\n\n@testset \"Imaginary part\" begin\n    @test imag(ComplexNumber(1, 0)) == 0\n    @test imag(ComplexNumber(0, 1)) == 1\n    @test imag(ComplexNumber(1, 2)) == 2\nend\n\n# Bonus A\n@testset \"Complex exponential\" begin\n    @test_skip exp(ComplexNumber(0, \u03c0)) \u2248 ComplexNumber(-1, 0)\n    @test_skip exp(ComplexNumber(0, 0)) == ComplexNumber(1, 0)\n    @test_skip exp(ComplexNumber(1, 0)) \u2248 ComplexNumber(\u212f, 0)\n    @test_skip exp(ComplexNumber(log(2), \u03c0)) \u2248 ComplexNumber(-2, 0)\nend\n\n# Bonus B\n@testset \"Syntax sugar jm\" begin\n    @test_skip ComplexNumber(0, 1)  == jm\n    @test_skip ComplexNumber(1, 0)  == 1 + 0jm\n    @test_skip ComplexNumber(1, 1)  == 1 + 1jm\n    @test_skip ComplexNumber(-1, 0) == jm^2\nend\n", "meta": {"hexsha": "2805a61f57955878c8a138432f83e2cd341f72c6", "size": 2635, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/complex-numbers/runtests.jl", "max_stars_repo_name": "tomerarnon/julia-1", "max_stars_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_stars_repo_licenses": ["MIT"], "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/complex-numbers/runtests.jl", "max_issues_repo_name": "tomerarnon/julia-1", "max_issues_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_issues_repo_licenses": ["MIT"], "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/complex-numbers/runtests.jl", "max_forks_repo_name": "tomerarnon/julia-1", "max_forks_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-11T20:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-11T20:28:18.000Z", "avg_line_length": 33.7820512821, "max_line_length": 83, "alphanum_fraction": 0.6337760911, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7621636540859447}}
{"text": "#Calculate the data transformations to the output\nfunction y_transform(ys::Array{Float64},ml::ML_model) \n    ml.yscale  = mean(ys); ys[:]=ys./ ml.yscale ; ys[:] = log.(ys);     # Scaling and log transform\n #   ml.yscale = std(ys,1); ml.ysmean  =mean(ys,1); ys[:]= (ys.-ml.ysmean)./ml.yscale; # Centering and scaling\n    return ys\nend\n\n#Undo the data transformations to the output\nfunction y_undo_transform(ys::Array{Float64}, ml::ML_model) \n    ys[:] = exp.(ys); ys[:] = ys.*ml.yscale;    # Scaling and log transform\n  #  ys[:]= ys.*ml.yscale.+ml.ysmean;     # Centering and scaling\n    return ys\nend\n\n#Calculate the data transformations to the input x (feature vector)\nfunction X_transform(X::Array{Float64}, ml::ML_model) \n    ml.Xmean = mean(X,1);\n  #  ml.Xstd = std(X,1);  \n  #  ind = (0.==ml.Xstd); ml.Xstd[ind] =1.0;  #replace 0 in std by 1 incase there is a constant feature\n  #  X= (X.-ml.Xmean)./ml.Xstd; # Centering and scaling\n    X= X.-ml.Xmean;\n    sX = size(X);\n    X = [X ones(sX[1],1)]; # Adding the bias term\n    return X\nend\n\n#Apply the saved data transformations to a single data vector x (feature vector)\nfunction x_apply_transform(x::Array{Float64}, ml::ML_model) \n  #  x= (x.-ml.Xmean)./ml.Xstd; # Centering and scaling\n    x =x.-ml.Xmean;\n    x = [x 1];# Adding the bias term\n   return x\nend", "meta": {"hexsha": "a37892e7a0d594f8521aeaafa4af679e638bd945", "size": 1314, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/data_transformations.jl", "max_stars_repo_name": "gowerrobert/MultipleScatteringLearnMoments", "max_stars_repo_head_hexsha": "157cdbf984de9bdb3b4fb035f60a37f10d2a17f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-27T19:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-27T19:19:14.000Z", "max_issues_repo_path": "src/data_transformations.jl", "max_issues_repo_name": "gowerrobert/MultipleScatteringLearnMoments", "max_issues_repo_head_hexsha": "157cdbf984de9bdb3b4fb035f60a37f10d2a17f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-09T16:11:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-09T16:31:20.000Z", "max_forks_repo_path": "src/data_transformations.jl", "max_forks_repo_name": "gowerrobert/MultipleScatteringLearnMoments", "max_forks_repo_head_hexsha": "157cdbf984de9bdb3b4fb035f60a37f10d2a17f9", "max_forks_repo_licenses": ["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.8181818182, "max_line_length": 110, "alphanum_fraction": 0.6506849315, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7621636540859447}}
{"text": "# Solves the scalar, purely nonlinear, eigenvalue problem\n# A(\u03bb) = 0.2*sqrt(\u03bb) - 0.6*sin(2*\u03bb) with both a polynomial\n# and fully rational approach\n\nusing NonlinearEigenproblemsTest\nusing NonlinearEigenproblems\nusing Test\n\nfunction nleigs_scalar()\n    as_matrix(x::Number) = (M = Matrix{eltype(x)}(undef,1,1); M[1] = x; M)\n    n = 1\n    C = [as_matrix(0.2), as_matrix(-0.6)]\n    f = [\u03bb -> sqrt(\u03bb), \u03bb -> sin(2*\u03bb)]\n    nep = SPMF_NEP([C[1], C[2]], [f[1], f[2]])\n\n    \u03a3 = complex([0.01, 4])\n\n    @bench @testset \"Polynomial\" begin\n        lambda, X = nleigs(nep, \u03a3, logger=displaylevel, maxit=100, v=ones(n).+0im, leja=2, isfunm=false)\n\n        # single eigenvalue converges\n        verify_lambdas(1, nep, lambda, X)\n    end\n\n    @bench @testset \"Fully rational\" begin\n        # set of poles candidates\n        \u039e = -10 .^ range(-6, stop = 5, length = 10000)\n\n        lambda, X = nleigs(nep, \u03a3, \u039e=\u039e, logger=displaylevel, maxit=100, v=ones(n).+0im, leja=2, isfunm=false)\n\n        # three eigenvalues converge\n        verify_lambdas(3, nep, lambda, X)\n    end\nend\n\n@testset \"NLEIGS: Scalar\" begin\n    nleigs_scalar()\nend\n", "meta": {"hexsha": "2e4194d7d5de345ceb5d63d9d57f36047ef07c58", "size": 1114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/nleigs/nleigs_scalar.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": "test/nleigs/nleigs_scalar.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": "test/nleigs/nleigs_scalar.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": 28.5641025641, "max_line_length": 109, "alphanum_fraction": 0.6211849192, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741298, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7621636528961641}}
{"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": "const PointTypes = Union{VoronoiDelaunay.AbstractPoint2D, GeometryBasics.Point2}\n\nfunction mean(pts::Vector{T}) where T <: PointTypes\n\tax = 0.0\n\tay = 0.0\n\n\t@simd for p in pts\n\t\tax += getx(p)\n\t\tay += gety(p)\n\tend\n\n\tNp = length(pts)\n\tT(ax/Np, ay/Np)\nend\n\n\nfor name in [:sort, :sort!, :issorted, :sortperm]\n\t@eval begin\n\t\tfunction Base.$name(pts::Vector{T}) where T <: PointTypes\n\t\t\tcenter = mean(pts)\n\t\t\t$name(pts, by = p -> p - center, rev = true)\n\t\tend\n\tend\nend\n\n\n# http://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order\nfunction Base.isless(p::T, q::T) where T <: PointTypes\n\tif getx(p) >= 0.0 && getx(q) < 0.0\n\t\treturn true\n\telseif getx(p) < 0.0 && getx(q) >= 0.0\n\t\treturn false\n\telseif getx(p) == getx(q) == 0.0\n\t\tif gety(p) >= 0.0 || gety(q) >= 0.0\n\t\t\treturn gety(p) > gety(q)\n\t\telse\n\t\t\treturn gety(p) < gety(q)\n\t\tend\n\tend\n\n\tdet = getx(p)*gety(q) - getx(q)*gety(p)\n\tif det < 0.0\n\t\treturn true\n\telseif det > 0.0\n\t\treturn false\n\tend\n\n\t# p and q are on the same line from the center; check which one is\n\t# closer to the origin\n\torigin = T(0.0, 0.0)\n\tabs2(p, origin) > abs2(q, origin)\nend\n", "meta": {"hexsha": "63a7807ce4fd4602755108f87aec33006919d694", "size": 1108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Sort.jl", "max_stars_repo_name": "philbit/VoronoiCells.jl", "max_stars_repo_head_hexsha": "19ac0d1dcc222fbf10c9f27c1afc83dd3c47e8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2016-09-08T07:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T02:03:45.000Z", "max_issues_repo_path": "src/Sort.jl", "max_issues_repo_name": "philbit/VoronoiCells.jl", "max_issues_repo_head_hexsha": "19ac0d1dcc222fbf10c9f27c1afc83dd3c47e8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2017-07-21T21:25:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T20:32:02.000Z", "max_forks_repo_path": "src/Sort.jl", "max_forks_repo_name": "philbit/VoronoiCells.jl", "max_forks_repo_head_hexsha": "19ac0d1dcc222fbf10c9f27c1afc83dd3c47e8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-09-10T05:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T13:06:08.000Z", "avg_line_length": 20.9056603774, "max_line_length": 80, "alphanum_fraction": 0.630866426, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7621562775314865}}
{"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\u2080 = one(T)\n    p\u2081 = 2x\n\n    if p <= 0\n        return p\u2080\n    elseif p == 1\n        return p\u2081\n    end\n\n    for n in 2:p\n        p\u2080, p\u2081 = p\u2081, 2x*p\u2081 - 2*(n-1)*p\u2080\n    end\n\n    p\u2081\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\u2135 = \"world\"\noutput = \"Hello $\u2135, again!\"\nprintln(output)\n\n# this extends to function evaluations as well\n\u03b1 = 2\nprintln(\"The sine of $\u03b1 is $(sin(\u03b1))\")\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(\u03b1)\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, \u201cA new method for gray-level picture thresholding using the entropy of the histogram,\u201d *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    \u03a8\u2098\u2090\u2093 = 0\n    H\u209b = H(pdf)\n    H\u2099 = -1*H\u209b[nbins]\n    P\u209b = cumsum(pdf)\n    threshold_bin = 1\n    for i in 1:nbins\n        P\u1d62 = P\u209b[i]\n        H\u1d62 = -1*H\u209b[i]\n        \u03a8\u1d62 = log(P\u1d62*(1-P\u1d62)) + (H\u1d62/P\u1d62) + ((H\u2099-H\u1d62)/(1-P\u1d62))\n        if \u03a8\u1d62 > \u03a8\u2098\u2090\u2093\n            \u03a8\u2098\u2090\u2093 = \u03a8\u1d62\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": "using LassoPath\nusing Test\nimport UnicodePlots as UnicodePlots\nusing Plots\nusing LinearAlgebra\n\n\nfunction Test1()\n    \"\"\"\n        Test 1, some basic test on a random matrix, copied columns of matrix. \n    \"\"\"\n    deg = 3\n    N = 2000\n    B = rand(N, deg)\n    A = fill(0.0, (N, 2deg))\n    A[:, 1:deg] = B\n    A[:, deg + 1:end] = 2B.^2 + B + 0.1.*randn(size(B))\n\n    b = A*ones(2deg, 1)\n    instance = LassoSCOP(A, b)\n    results, \u03bbs = GetLassoPath(instance)\n    display(results)\n    display(\u03bbs)\n    \n    # Let's plot this, and a global variable will be defined. \n    global Test1Results = results\n\n    ylim = (minimum(Test1Results), maximum(Test1Results))\n    ThePlot = UnicodePlots.lineplot(log2.(\u03bbs), Test1Results[1, :], ylim=ylim, title=\"Lasso Path\")\n\n    for II \u2208 2:size(Test1Results, 1)\n        UnicodePlots.lineplot!(ThePlot, log2.(\u03bbs), Test1Results[II, :])\n    end\n    display(ThePlot)\n    ThePlot = UnicodePlots.heatmap(results[end:-1:begin, :])\n    display(ThePlot)\n\n    # Visualize the path. \n    VisualizeLassoPath(instance)\n\n    # Finding the important weights for it. \n    PrintTitle(\"These are the important weights: \")\n    WeightsIndices = CaptureImportantWeights(instance)\n    println(WeightsIndices)\n    return true\n\nend\n\n\nfunction Test2()\n    \"\"\"\n        Testing the iterator for the lasso path object. \n    \"\"\"\n    PrintTitle(\"Testing the Iterator for the Lasso Path type. \")\n    deg = 3\n    N = 2000\n    B = rand(N, deg)\n    A = fill(0.0, (N, 2deg))\n    A[:, 1:deg] = B\n    A[:, deg + 1:end] = 2B.^2 + B + 0.1.*randn(size(B))\n    \n    # Use this to test the lasso iterate. \n    let A = A, b = A*ones(2deg, 1)\n        l = LassoSCOP(A, b )\n        for (\u03bb, x) \u2208 l\n            println(\u03bb)\n            println(x)\n        end\n    end\n\n    return true\nend\n\n\nfunction Test3()\n    \"\"\"\n        Test proximal Gradient, internal methods\n    \"\"\"\n    PrintTitle(\"Testing the proximal operator with simple regression. \")\n    N, M = 10, 100\n    A = randn(N, M)\n    b = randn(N, 1)\n    instance = LassoPath.BuildPG2NormLasso(A, b, 1/M)  \n    instance.tol= 1e-4\n\n    sol = LassoPath.OptimizeProximalGradient(instance, A\\b)\n    error = norm(A*sol - b)\n    println(\"The error of the solution is: $(error)\")\n    println(\"Non-zero entries: $(sum(sol .!= 0))\")\n    \n    return error != Inf\n\n\nend\n\n\nfunction Test4()\n    \"\"\"\n        Testing the proximal lasso path method. \n    \n    \"\"\"\n    \"\"\"\n    Test 1, some basic test on a random matrix, copied columns of matrix. \n\"\"\"\n    deg = 3\n    N = 2000\n    B = rand(N, deg)\n    A = fill(0.0, (N, 2deg))\n    A[:, 1:deg] = B\n    A[:, deg + 1:end] = 2B.^2 + B + 0.1.*randn(size(B))\n\n    b = A*ones(2deg, 1)\n    instance = Lasso2NormProx(A, b)\n\n    results, \u03bbs = GetLassoPath(instance)\n    display(results)\n    display(\u03bbs)\n\n    # Let's plot this, and a global variable will be defined. \n    global Test1Results = results\n\n    ylim = (minimum(Test1Results), maximum(Test1Results))\n    ThePlot = UnicodePlots.lineplot(log2.(\u03bbs), Test1Results[1, :], ylim=ylim, title=\"Lasso Path\")\n\n    for II \u2208 2:size(Test1Results, 1)\n        UnicodePlots.lineplot!(ThePlot, log2.(\u03bbs), Test1Results[II, :])\n    end\n    display(ThePlot)\n    ThePlot = UnicodePlots.heatmap(results[end:-1:begin, :])\n    display(ThePlot)\n\n    # Visualize the path. \n    VisualizeLassoPath(instance)\n\n    # Finding the important weights for it. \n    PrintTitle(\"These are the important weights: \")\n    WeightsIndices = CaptureImportantWeights(instance)\n    println(WeightsIndices)\n\n    return true\nend\n\nfunction Test5()\n    \"\"\"\n        Test High dimensional Array for the proximal gradient lasso method. \n    \"\"\"\n\n\nend\n\n\n# A set of basic tests for Lasso. \n@testset \"LassoPath.jl\" begin\n    PrintTitle(\"Test Set 1\")\n    @test Test1()\n    @test Test2()\n    @test Test3()\n    @test Test4() \nend\n", "meta": {"hexsha": "90e939c9528cc2dddb4b5d9409ba4597f968c3d0", "size": 3787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "iluvjava/LassoPath.jl", "max_stars_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_stars_repo_licenses": ["MIT"], "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": "iluvjava/LassoPath.jl", "max_issues_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_issues_repo_licenses": ["MIT"], "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": "iluvjava/LassoPath.jl", "max_forks_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_forks_repo_licenses": ["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.66875, "max_line_length": 97, "alphanum_fraction": 0.610245577, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7621562695482107}}
{"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, \u03bb=\u03bb)\n\n    k_B = 1.380649e-23\n    h   = 6.62607015e-34\n    c   = 2.99792458e8\n\n    aux1 = (2.0 * h * c^2) / \u03bb^5\n\n    aux2 = (h * c) / (\u03bb * k_B * T)\n\n    aux1 / (exp(aux2) - 1.0)\n\nend\n\nfunction scaledB(; s=s, T=T, \u03bb=\u03bb)\n\n    s * B(T=T, \u03bb=\u03bb)\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,\u03bb = 500*1e-9); B(T=5555.5,\u03bb = 4000*1e-9);B(T=5555.5,\u03bb = 6000*1e-9)]\n\n    function loss(T)\n\n        local V = map( w -> B(T=T,\u03bb=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, \u03bb=w), wave)\n\n    s = dot(V,Y) / dot(V,V)\n\n    \u03bb = collect(LinRange(100, 10_000, 100)) * 1e-9;\n\n    plot(\u03bb, map(\u03bb -> s*B(T=T,\u03bb=\u03bb), \u03bb), \"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    \u03c3(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,\u03bb = 500*1e-9); B(T=5555.5,\u03bb = 4000*1e-9);B(T=5555.5,\u03bb = 6000*1e-9)]\n\n    function loss(T)\n\n        local V = map( w -> B(T=T,\u03bb=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# \u03bb = collect(LinRange(10,10_000,1000)) * 1e-9;\n# plot(\u03bb, map(\u03bb->B(T=4000.0,\u03bb=\u03bb), \u03bb), \"g.\")\n# plot(\u03bb, map(\u03bb->B(T=5000.0,\u03bb=\u03bb), \u03bb), \"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\u2081::Vector{Float64},p\u2082::Vector{Float64})\n    v\u2081=p\u2081-o\n    v\u2082=p\u2082-o\n    if abs(v\u2081\u22c5v\u2082/norm(v\u2081)/norm(v\u2082))==1\n        error(\"Two vectors should not be parallel!\")\n    end\n    x=v\u2081/norm(v\u2081)\n    z=v\u2081\u00d7v\u2082\n    z=z/norm(z)\n    y=z\u00d7x\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": "# Test factor analysis implementation using a test similar to the one in\n# scikit-learn, so we can directly compare implementations if needed.\n\nusing MultivariateStats\n\nn_samples = 20\nn_features = 5\nn_components = 3\n\nX = readdlm(\"X_fa.csv\", ',')'\nfa, L = fit(FactorAnalysis, X, n_components)\n\nX_t = transform(fa, X)\n\nX_rec = fa.Vbar .+ fa.F*X_t .+ fa.\u03a8.*randn(n_features,n_samples)\n", "meta": {"hexsha": "414e6bcc6b267766ce7bc0876c39afb62be4000b", "size": 382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fa.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": "test/fa.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": "test/fa.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": 23.875, "max_line_length": 72, "alphanum_fraction": 0.7303664921, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7621492700058786}}
{"text": "#=  https://www.damtp.cam.ac.uk/research/dd/files/teaching/MB17Gog.pdf#subsubsection.1.3.4  =#\r\nusing Plots\r\n\r\n\u03b4t = 0.001\r\nT = 1\r\ntimes = 0:\u03b4t: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\u03b2 = 0.005\r\n# Rate of recovery\r\n\u03bd = 4\r\n\r\n# Randomness for \u03c3 > 0\r\n\u03c3 = 1\r\n\r\nfor i \u2208 2:ntimes\r\n    \u03b4S = - \u03b2 * I[i-1] * S[i-1] * \u03b4t\r\n\t\u03b4R = \u03bd * I[i-1] * \u03b4t\r\n\t\u03b4I = - \u03b4S - \u03b4R\r\n    S[i] = max(S[i-1] + \u03b4S * exp(\u03c3 * randn()), 0)\r\n    I[i] = max(I[i-1] + \u03b4I * exp(\u03c3 * randn()), 0)\r\n\tR[i] = max(R[i-1] + \u03b4R * exp(\u03c3 * 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": "\nfunction hard_coded_radau_3()\n    s6 = sqrt(BigFloat(6))\n\n    # https://en.wikipedia.org/wiki/List_of_Runge%E2%80%93Kutta_methods#Radau_IIA_methods\n    a11 = 11 // 45 - s6 * (7 // 360)\n    a12 = 37 // 225 - s6 * (169 // 1800)\n    a13 = -2 // 225 + s6 * (1 // 75)\n    a21 = 37 // 225 + s6 * (169 // 1800)\n    a22 = 11 // 45 + s6 * (7 // 360)\n    a23 = -2 // 225 - s6 * (1 // 75)\n    a31 = 4 // 9 - s6 * (1 // 36)\n    a32 = 4 // 9 + s6 * ( 1 // 36)\n    a33 = 1 // 9\n    A = [a11 a12 a13; a21 a22 a23; a31 a32 a33]\n\n    b = A[end, :]\n\n    c1 = 2 // 5 - s6 * (1 // 10)\n    c2 = 2 // 5 + s6 * (1 // 10)\n    c3 = 1\n    c = [c1, c2, c3]\n\n    # https://github.com/scipy/scipy/blob/14142ff70d84a6ce74044a27919c850e893648f7/scipy/integrate/_ivp/radau.py#L37\n    bi = [ 13//3 + s6 *(7//3) -23//3 - s6 * (22 // 3)  10//3 + 5 * s6;\n    13//3 - s6 * (7//3)  -23//3 + s6 * (22 // 3)  10//3 - 5 * s6;\n    1//3 -8//3 10//3]\n\n    # Practical Implementation of High-Order Multiple Precision Fully Implicit\n    # Runge-Kutta Methods with Step Size Control Using Embedded Formula\n    # (Tomonori Kouya)\n    b\u0302 = b + [-(2 + 3 * s6)/6, -(2-3*s6)/6, -1//3] * find_real_eigenvalue(A)\n\n    return A, b, c, bi, b\u0302\nend\n\nfunction hard_coded_radau_2()\n    a11 = 5 // 12\n    a12 = -1 // 12\n    a21 = 3 // 4\n    a22 = 1 // 4\n    A = [a11 a12; a21 a22]\n\n    B = A[end, :]\n\n    C = [1 // 3,   1]\n\n    return A, B, C\nend\n\n\nbig_eps = eps(BigFloat(1))\n\nn = 2\nA, b, c, d, bi = radau_butcher_table_plus(n)\nA2, B2, C2 = hard_coded_radau_2()\n\n@testset \"Radau Butcher Table 2\" begin\n    tol = 100 * big_eps * 2^2\n    @test sum(abs.(A2 - A)) < tol\n    @test sum(abs.(C2 - c)) < tol\n    @test sum(abs.(B2 - b)) < tol\nend\n\nn = 3\nA, b, c, d, bi = radau_butcher_table_plus(n)\nA3, B3, C3, D3, bi_3 = hard_coded_radau_3()\n\n@testset \"Radau Butcher Table 3\" begin\n    tol = 100 * big_eps * 3^2\n    @test sum(abs.(A3 - A)) < tol\n    @test sum(abs.(B3 - b)) < tol\n    @test sum(abs.(C3 - c)) < tol\n    @test sum(abs.(D3 - d)) < tol\n    @test sum(abs.(bi_3 - bi[2:4])) < tol\n    @test abs(sum(bi) - 1) < tol\n    @test bi[1] == find_real_eigenvalue(A)\nend\n", "meta": {"hexsha": "626d492036e884db92e85e0e4f1811bcf3623111", "size": 2102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 26.6075949367, "max_line_length": 116, "alphanum_fraction": 0.526641294, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7621454784367087}}
{"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": "using Distributions\n\n#export AbstractConvolutionKernel, GaussianConvolutionKernel, GaussianMixtureConvolutionKernel\n\n\"\"\"Convolution kernel using a truncated Gaussian with zero mean and unit width.\nOptionally truncate at limit_kernel_width (defaults to 10).\"\"\"\nstruct GaussianConvolutionKernel{T} <: AbstractConvolutionKernel  where {T<:Number}\n  dist::Normal{T}\n  norm::T\n  limit_kernel_width::Float64\n\n  function GaussianConvolutionKernel(width::T; limit_kernel_width::Number=limit_kernel_width_default) where {T<:Number}\n      @assert width > 0\n      @assert limit_kernel_width > width\n      dist = Normal(zero(T), width)\n      norm = one(T)/(cdf(dist,limit_kernel_width)-cdf(dist,-limit_kernel_width))\n      new{T}(dist, norm, limit_kernel_width)\n  end\nend\n\n\"Evaluate kernel at wavelength(s) x\"\nfunction (kernel::GaussianConvolutionKernel)(x::Number)\n    x < kernel.limit_kernel_width^2 ? kernel.norm*pdf(kernel.dist,x) : zero(x)\nend\n\nfunction (kernel::GaussianConvolutionKernel)(x::A1) where { T1<:Number, A1<:AbstractArray{T1} }\n    kernel.(x)\nend\n\n\"\"\"Convolution kernel using a mixture of Gaussians with zero mean and various width and weights.\nOptionally truncate at limit_kernel_width (defaults to 10).\"\"\"\nstruct GaussianMixtureConvolutionKernel{T1,T2} <: AbstractConvolutionKernel  where {T1<:Number,T2<:Number}\n    dists::Array{Normal{T1},1}\n    weights::Array{T2,1}\n    norm::T2\n    limit_kernel_width::Float64\n\n    function GaussianMixtureConvolutionKernel(kernel_widths::AbstractArray{T1,1}, kernel_weights::AbstractArray{T2,1};\n            limit_kernel_width::Number=limit_kernel_width_default) where {T1<:Number,T2<:Number}\n        @assert size(kernel_widths) == size(kernel_weights)\n        @assert all(kernel_widths .> 0)\n        @assert all(limit_kernel_width .> kernel_widths)\n        @assert sum(kernel_weights) \u2248 one(eltype(kernel_weights))\n        dists = [Normal(zero(kernel_widths[i]),kernel_widths[i]) for i in 1:length(kernel_widths) ]\n        cdf_at_limit(d) = cdf(d,limit_kernel_width)\n        norm = sum(kernel_weights./(cdf_at_limit.(dists))) # assumes components symmetric around zero\n        new{T1,T2}(dists, kernel_weights, norm, limit_kernel_width)\n    end\nend\n\n\"Evaluate kernel at wavelength(s) x\"\nfunction (kernel::GaussianMixtureConvolutionKernel)(x::Number)\n    abs(x) < kernel.limit_kernel_width ?  kernel.norm*sum(kernel.weights.*pdf.(kernel.dists,x)) : zero(x)\nend\n\nfunction (kernel::GaussianMixtureConvolutionKernel)(x::AbstractArray{T}) where T<:Number\n    kernel.(x)\nend\n", "meta": {"hexsha": "daf4079fd0125daad3259a9bf9b9f81b516999fe", "size": 2516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/convolution_kernels.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/convolution_kernels.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/convolution_kernels.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": 42.6440677966, "max_line_length": 119, "alphanum_fraction": 0.7448330684, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7621454715602693}}
{"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\u221e = 3.56995\naxlo.axvline(r\u221e; 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\u00f73\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\u00f6ssler 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)(\u03b8, \u03c6) =\n    ((t.R + t.r*cos(\u03b8)) * cos(\u03c6), (t.R + t.r*cos(\u03b8)) * sin(\u03c6), t.r * sin(\u03b8)) .+\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)(\u03b8, \u03c6)\n    R = at.R\n    r_large = at.r_large\n    r_small = at.r_small\n\n    r = (r_large - r_small) * (cos(\u03c6) + 1)/2 + r_small\n    ((R + r*cos(\u03b8)) * cos(\u03c6), (R + r*cos(\u03b8)) * sin(\u03c6), r*sin(\u03b8)) .+ 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)(\u03b8, \u03c6) =\n    (s.r*cos(\u03b8) * sin(\u03c6), s.r*sin(\u03b8) * sin(\u03c6), s.r*cos(\u03c6)) .+ 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)(\u03b8) = (c.r * cos(\u03b8), c.r * sin(\u03b8)) .+ 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\u03c0 .* 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": "const CLP_SOLVER = ClpSolver()\nconst MAX_SENSE = -1.0\nconst MIN_SENSE = 1.0\n\n## -------------------------------------------------------------------\nfunction fba(S, b, lb, ub, c; solver = CLP_SOLVER)\n    LP = linprog(\n        c, # Opt sense vector \n        S, # Stoichiometric matrix\n        b, # row lb\n        b, # row ub\n        lb, # column lb\n        ub, # column ub\n        solver\n    )\n    return isempty(LP.sol) ? zeros(length(lb)) : LP.sol\nend\n\nfunction fba(S, b, lb, ub, c, idx, sense; kwargs...)\n    bk_c = c[idx]\n    c[idx] = sense\n    try;\n        sol = fba(S, b, lb, ub, c; kwargs...)\n        return sol\n    finally; c[idx] = bk_c end\nend\n\n## -------------------------------------------------------------------\nfunction fva(S, b, lb, ub, c, idx::Integer;  kwargs...)\n    bk_c = c[idx]\n    c[idx] = MIN_SENSE\n    try\n        L = fba(S, b, lb, ub, c; kwargs...)[idx]\n        c[idx] = MAX_SENSE\n        U = fba(S, b, lb, ub, c; kwargs...)[idx]\n        return (first(L), first(U))\n    finally; c[idx] = bk_c end\nend\n\nfunction fva(S, b, lb, ub, c, idxs; kwargs...)\n    L = zeros(length(idxs))\n    U = zeros(length(idxs))\n    for (i, idx) in idxs |> enumerate\n        L[i], U[i] = fva(S, b, lb, ub, c, idx; kwargs...)\n    end\n    return (L, U)\nend", "meta": {"hexsha": "77b3bbed9a4bb40bb5d40d679fc986e821882a90", "size": 1254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Dynamic/LP.jl", "max_stars_repo_name": "josePereiro/Chemostat_InSilico.jl", "max_stars_repo_head_hexsha": "794293c33ea3f346ffdd8275498eaa3ee6f81d8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Dynamic/LP.jl", "max_issues_repo_name": "josePereiro/Chemostat_InSilico.jl", "max_issues_repo_head_hexsha": "794293c33ea3f346ffdd8275498eaa3ee6f81d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Dynamic/LP.jl", "max_forks_repo_name": "josePereiro/Chemostat_InSilico.jl", "max_forks_repo_head_hexsha": "794293c33ea3f346ffdd8275498eaa3ee6f81d8b", "max_forks_repo_licenses": ["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.6808510638, "max_line_length": 70, "alphanum_fraction": 0.4641148325, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.76204200255523}}
{"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 \u00d7 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\u00d77 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\u00d77 DataFrame\n  Row \u2502 Crt1     Crt2     Crt3     Crt4     Crt5     Crt6     Crt7    \n      \u2502 Float64  Float64  Float64  Float64  Float64  Float64  Float64 \n \u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    1 \u2502   6.952    8.0      6.649    7.268    8.0      7.652    6.316\n    2 \u2502   7.319    7.319    6.604    7.319    8.0      7.652    5.313\n    3 \u2502   7.0      7.319    7.652    6.952    7.652    6.952    4.642\n    4 \u2502   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\u010dar, D., Lukovac, V., Bo\u017eani\u0107, 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\u015f A.(2019),Swara Ve Mairca Y\u00f6ntemleri \u0130le Catering Firmas\u0131 Se\u00e7imi,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": "# Arvind Prasadan\n# 2019 January\n# DMF Package\n# Generates a realization of an ARMA process\n\n\"\"\"\n\tgen_arma_sequence(n = 100, ar_comp = [], ma_comp = [], arma_std = 1.0)\n\nGenerates a realization of an ARMA process\n\n# Arguments\n- `n`: Length of process\n- `ar_comp`: List of AR Coefficients; one of this and ma_comp must be non-empty\n- `ma_comp`: List of MA Coefficients; one of this and ar_comp must be non-empty\n- `arma_std`: Noise Standard Deviation\n\n# Outputs\n- `x`: vector of ARMA process realization\n\"\"\"\nfunction gen_arma_sequence(n = 100, ar_comp = [], ma_comp = [], arma_std = 1.0)\n    \n    n = round(abs(n[1])) # Samples\n    n = (1 <= n) ? n : 1\n    \n    arma_std = abs(arma_std[1]) # Standard Deviation\n    \n    if 0 == length(ar_comp) + length(ma_comp)\n\tx = arma_std * randn(n)\n    else\n    \t# Define ARMA object, simulate from this set of parameters\n    \tarma = ARMA(ar_comp, ma_comp, arma_std)   \n    \tx = simulation(arma, ts_length = n)\n    end\n    \n    return x\nend\n\n", "meta": {"hexsha": "c0a8a9a3dc669f21e5d1e1f4896ba91ef3152e8d", "size": 979, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gen_arma_sequence.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/gen_arma_sequence.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/gen_arma_sequence.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": 25.7631578947, "max_line_length": 79, "alphanum_fraction": 0.6547497446, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7620419961454211}}
{"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 `[\u03b1, \u03b2, \u03b3]` 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 `[\u03b1, \u03b2, \u03b3]`\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 `\u03b2`\n- Three dimensions: `p` is treated as 3D cartesian co-ordinates, and the spherical angles `\u03b8` and `\u03c6` are returned as `\u03b2` and `\u03b3`\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 ``\u03b1 \u2208 [0,2\u03c0)``, ``\u03b2 \u2208 [0,\u03c0]``, ``\u03b3 \u2208 [0,2\u03c0)``. 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 `[\u03b1, \u03b2, \u03b3]` 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 \u2248 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, \u2202H\u2202t, x, t, \u0394t)\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 \u0394t) x + \\sin(\\norm{\\dot{x}}_2 \u0394t) \\frac{\\dot{x}}{\\norm{\\dot{x}}_2}\n```\n\n[^1]: Tianran Chen and Tien-Yien Li.\n    \u201cSpherical projective path tracking for homotopy continuation methods\u201d.\n    Communications in Information and Systems 12(3):195-220 (2012)\n\"\"\"\nfunction predict(alg::Spherical, H::AbstractHomotopy, J_H, \u2202H\u2202t, x, t, \u0394t)\n    dot_x = \\([J_H(x,t); x'], [-\u2202H\u2202t(x,t); 0])\n    norm_dot_x = norm(dot_x)\n    # TODO: conditining? i.e. check singular values\n    cos(-norm_dot_x*\u0394t) .* x .+ (sin(-norm_dot_x*\u0394t) / 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    \u0394x = 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        \u0394x .= \\(dx_xt, res)\n        norm_\u0394x = norm(\u0394x)\n        u .= cos(norm_\u0394x) .* u .+ (sin(norm_\u0394x) / norm_\u0394x) .* \u0394x\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)\u00b6\nComputes Weierstrass\u2019s elliptic function\n\nvoid acb_elliptic_inv_p(acb_t res, const acb_t z, const acb_t tau, slong prec)\u00b6\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)\u00b6\nComputes the Weierstrass zeta function\n\nvoid acb_elliptic_sigma(acb_t res, const acb_t z, const acb_t tau, slong prec)\u00b6\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) == \u2212exp(2*(z+\u03c4/2)*weierstrass_zeta(\u03c4/2,\u03c4)) * 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": "\nusing JuPOT\n\n\n             m = 6 # No. of days data\n             returns_data = ARGS[1]\n\t\t\t returns = parse.(split(returns_data, \",\"))\n\t\t\t \n             meanReturns_data =  ARGS[2] # Returns a matrix of size(n) with entries between 0-1s\n\t\t\t meanReturns = parse.(split(meanReturns_data, \",\"))\n\t\t\t \n             tickers_data = ARGS[3]\n\t\t\t tickers = split(tickers_data, \",\")\n\t\t\t \n             n = length(tickers)\n\n             matrix = reshape(returns,m,n)\n             covariance = cov(matrix) #covariance matrix of returns\n\n\n\n             # Assets data structure containing, names, expected returns, covarariance\n             assets = AssetsCollection(tickers, meanReturns, covariance)\n\n             target_ret_test = [0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80]\n\n             function efficientFrontierMVO(assets, target_ret_test)\n\n                 # Create the Arrays to be returned, and set them to be the length of the\n                 # target_ret_test from the input.\n                 n = length(target_ret_test)\n                 risk = Array(Float64,n)\n                 index = Array(Float64,n)\n\n                 for i in 1:n\n                     # Get the target return we want to test.\n                     target_ret = target_ret_test[i]\n\n                     # Setup and Optimize the SimpleMVO with the new Target Return.\n                     mvo = SimpleMVO(assets, target_ret; short_sale=false)\n                     result = optimize(mvo)\n\n                     # Risk is the Objective Value. Index the Target Return.\n                     risk[i] = result[1]\n                     index[i] = target_ret\n                 end\n\n                 # Return as a Tuple of the Arrays\n                 return risk, index\n             end\n\n             efd = efficientFrontierMVO(assets, target_ret_test)", "meta": {"hexsha": "13dba55204301c6c580137ba2201eac765a2c719", "size": 1837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "public/test.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/test.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/test.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": 35.3269230769, "max_line_length": 107, "alphanum_fraction": 0.5362003266, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7619679441961389}}
{"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": "function radixsort(tobesorted::Vector{Int64})\n    arr = deepcopy(tobesorted)\n    for shift in 63:-1:0\n        tmp = Vector{Int64}(undef, length(arr))\n        j = 0\n        for i in 1:length(arr)\n            if (shift == 0) == ((arr[i] << shift) >= 0)\n                arr[i - j] = arr[i]\n            else\n                tmp[j + 1] = arr[i]\n                j += 1\n            end\n        end\n        tmp[j+1:end] .= arr[1:length(tmp)-j]\n        arr = tmp\n    end\n    arr\nend\n\nfunction testradixsort()\n    arrays = [[170, 45, 75, -90, -802, 24, 2, 66], [-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028]]\n    for array in arrays\n        println(radixsort(array))\n    end\nend\n\ntestradixsort()\n", "meta": {"hexsha": "5def93ed197b9b8b920d1b93ce19462616c90ff4", "size": 690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sorting-algorithms-radix-sort.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/sorting-algorithms-radix-sort.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/sorting-algorithms-radix-sort.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.6428571429, "max_line_length": 102, "alphanum_fraction": 0.4782608696, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7619593320736513}}
{"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- \u2113             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(\u2113::LossFunction, n::Int, k::Int, p::Int, SNR, \u03c1)\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] + \u03c1*X[:, i-1]\n  end\n  # rho = \u03c1\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 = \u221a12 * rand(n, p) - (\u221a12)/2\n\n  Y = generate_output(\u2113, noisy_signal(X, indices_true, w_true, SNR))\n\n  return X, Y, indices_true, w_true\nend\n\nfunction hard_data_construction(\u2113::LossFunction, n::Int, k::Int, p::Int, SNR, \u03c1)\n  indices_true, w_true = generate_estimator(p, k)\n\n  indices_true = collect(1:k)\n  w_true = ones(k)./\u221ak #sample(-1:2:1, k)\n\n  #Covariance matrix\n  \u03b8 = (1/\u221ak + 1/k)/2\n  \u03a3 = SparseMatrixCSC{Float64}(I, p, p)\n  for i in 1:k\n    \u03a3[i,k+1] = \u03b8\n    \u03a3[k+1,i] = \u03b8\n  end\n\n  # perm = shuffle(1:p)\n  # indices_true = [findfirst( perm .== i) for i in indices_true]\n  # \u03a3[:,:] = \u03a3[perm, perm]\n\n  d = MvNormal(full(\u03a3))\n\n  X = rand(d, n)'\n\n  Y = generate_output(\u2113, 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(\u2113::Regression, S)\n  return S\nend\n\nfunction generate_output(\u2113::L1SVM, S)\n  P = 1. ./( 1 .+ exp.(-S) )\n  return 1.0*(P .> .5) - 1.0*(P .< .5)\nend\n\nfunction generate_output(\u2113::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": "using DynamicEnergyBudgets, Unitful, Test\nusing DynamicEnergyBudgets: non_growth_flux\n\n@testset \"Half saturation curve\" begin\n    mx = 10.0\n    half = 5.0\n    x = 5.0\n    @test half_saturation(mx, half, x) == 5.0\n\n    # Maximum\n    x = 100000000000000000000000000.0\n    @test half_saturation(mx, half, x) == 10.0\n\n    # Minimum\n    x = 0.0\n    @test half_saturation(mx, half, x) == 0.0\nend\n\n@testset \"Flux\" begin\n    (a, b, c) = non_growth_flux.((0.1,0.2,0.3), (0.2,0.3,0.4), 0.1)\n    @test a \u2248 0.01\n    @test b \u2248 0.04\n    @test c \u2248 0.09\nend\n\n@testset \"Rate\" begin\n    j_E_mai    = 0.003\n    y_E_CH_NO  = 1.0/1.5\n    y_E_EN     = 1.0/0.7\n    y_V_E      = 0.7\n    kap_soma   = 0.6\n    r          = 0.001\n    reserve    = (1.0, 1.0, 1.0)\n    turnover   = ((0.2, 0.2, 0.2) .* 0.05)\n    su = ParallelComplementarySU()\n\n    # rate_formula(r, su, rel_reserve::NTuple{3}, turnover::NTuple{3}, j_E_mai, y_E_Ea, y_E_Eb, y_V_E, \u03basoma) = begin\n    rf = rate_formula(r, su, reserve, turnover, j_E_mai, y_E_CH_NO, y_E_EN, y_V_E, kap_soma)\n\n    @test rf == 0.002874195250659631\n\n    @testset \"test rate with units\" begin\n        j_E_mai   = 0.003u\"mol/mol*d^-1\"\n        turnover = ((0.2u\"mol/mol*d^-1\", 0.2u\"mol/mol*d^-1\", 0.2u\"mol/mol*d^-1\") .* 0.05)\n        mass = (1.0u\"mol/mol\", 1.0u\"mol/mol\", 1.0u\"mol/mol\")\n        r = 0.001u\"mol/mol*d^-1\"\n        @test_nowarn non_growth_flux.(mass, turnover, r)\n        rf = rate_formula(r, su, reserve, turnover, j_E_mai, y_E_CH_NO, y_E_EN, y_V_E, kap_soma)\n        @test rf == 0.002874195250659631u\"mol/mol*d^-1\"\n    end\n\nend\n\nnothing\n", "meta": {"hexsha": "0a9b3c73a191383d50943ec35bd54881c3bf37fd", "size": 1564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/math.jl", "max_stars_repo_name": "JuliaTagBot/DynamicEnergyBudgets.jl", "max_stars_repo_head_hexsha": "a2f26aa50d20df6309d155182ef4f2007fddf81d", "max_stars_repo_licenses": ["MIT"], "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/math.jl", "max_issues_repo_name": "JuliaTagBot/DynamicEnergyBudgets.jl", "max_issues_repo_head_hexsha": "a2f26aa50d20df6309d155182ef4f2007fddf81d", "max_issues_repo_licenses": ["MIT"], "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/math.jl", "max_forks_repo_name": "JuliaTagBot/DynamicEnergyBudgets.jl", "max_forks_repo_head_hexsha": "a2f26aa50d20df6309d155182ef4f2007fddf81d", "max_forks_repo_licenses": ["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.4363636364, "max_line_length": 117, "alphanum_fraction": 0.5895140665, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7619197439632444}}
{"text": "include(\"backwards_activation_functions.jl\")\n\n\"\"\"\nPartial derivates of the components of linear forward function using the linear output (\u03b4Z) and caches of these components (cache).\n\"\"\"\nfunction linear_backward(\u03b4Z, cache)\n    # unpack cache\n    A_prev, W, b = cache\n    m = size(A_prev, 2)\n\n    # partial derivates of each component\n    \u03b4W = \u03b4Z * (A_prev') / m\n    \u03b4b = sum(\u03b4Z, dims = 2) / m\n    \u03b4A_prev = (W') * \u03b4Z\n\n    @assert (size(\u03b4A_prev)[1] == size(A_prev)[1])\n    @assert (size(\u03b4W) == size(W))\n    @assert (size(\u03b4b)[1] == size(b)[1])\n\n    return \u03b4W, \u03b4b, \u03b4A_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(\u03b4A, cache; activation_function=\"relu\")\n    @assert activation_function \u2208 (\"sigmoid\", \"relu\", \"softmax\", \"tanh\", \"swish\")\n\n    linear_cache, cache_activation = cache\n\n    if (activation_function == \"relu\")\n\n        \u03b4Z = relu_backwards(\u03b4A, cache_activation)\n\n    elseif (activation_function == \"sigmoid\")\n\n        \u03b4Z = sigmoid_backwards(\u03b4A, cache_activation)\n\n    elseif (activation_function ==  \"tanh\")\n\n        \u03b4Z = tanh_backwards(\u03b4A, cache_activation)\n\n    elseif (activation_function == \"softmax\")\n\n        \u03b4Z = softmax_backwards(\u03b4A, cache_activation)\n        \n    elseif (activation_function == \"swish\")\n\n        \u03b4Z = swish_backwards(\u03b4A, cache_activation)\n\n    end # if\n\n    \u03b4W, \u03b4b, \u03b4A_prev = linear_backward(\u03b4Z, linear_cache)\n\n    return \u03b4W, \u03b4b, \u03b4A_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": "\n\"\"\"\n    CircularArc3(c::Circle3)\n\nConstructs an arc from a full circle.\n\"\"\"\nCircularArc3(c::Circle3)\n\n\"\"\"\n    CircularArc3(c::Circle3, pt::Point3)\n\nConstructs an arc from a full circle, using `pt` as source and target.\n\n!!! info \"Precondition\"\n\n    `pt` lies on `c`\n\"\"\"\nCircularArc3(c::Circle3, pt::Point3)\n\n\"\"\"\n    CircularArc3(c::Circle3, p::Point3, q::Point3)\n\nThe circular arc constructed from a circle `c`, a source `p`, and a target `q`,\nis defined as the set of points of the circle that lie between the source `p\u2081`\nand the target `p\u2082`, when traversing the circle counterclockwise seen from the\nside of the circle's supporting plane pointed by its *positive* normal vectors.\n\nIn this definition, we say that a normal vector ``(a,b,c)`` is positive if\n``(a,b,c) > (0,0,0)`` (i.e. ``a > 0 \u2228 (a = 0 \u2227 b > 0) \u2228 (b = 0 \u2227 c > 0)``).\n\nConstructs the circular arc supported by `c`, whose source and target are `p`\nand `q`, respectively.\n\n!!! info \"Precondition\"\n\n    `p` and `q` lie on `c` and are different.\n\"\"\"\nCircularArc3(c::Circle3, p::Point3, q::Point3)\n\n\"\"\"\n    CircularArc3(p::Point3, q::Point3, r::Point3)\n\nConstructs an arc that is supported by the circle of type [`Circle3`](@ref)\npassing through points `p`, `q` and `r`.\n\nThe source and target are respectively `p` and `r`, when traversing the\nsupporting circle in the counterclockwise direction seen from the side of the\nplace containing the circle pointed by its *positive* normal vectors.  Note\nthat, depending on the orientation of the point triple `(p,q,r)`, `q` may not\nlie on the arc.\n\n!!! info \"Precondition\"\n\n    `p`, `q`, and `r` are not collinear.\n\"\"\"\nCircularArc3(p::Point3, q::Point3, r::Point3)\n\n\"\"\"\n    supporting_circle(ca::CircularArc3)\n\nReturns the supporting circle of `ca`.\n\"\"\"\nsupporting_circle(ca::CircularArc3)\n\n\"\"\"\n    center(ca::CircularArc3)\n\nReturns the center of `ca`'s supporting circle.\n\"\"\"\ncenter(ca::CircularArc3)\n\n\"\"\"\n    squared_radius(ca::CircularArc3)\n\nReturns the squared radius of `ca`'s supporting circle.\n\"\"\"\nsquared_radius(ca::CircularArc3)\n\n\"\"\"\n    supporting_plane(ca::CircularArc3)\n\nReturns the supporting plane of `ca`'s supporting circle.\n\"\"\"\nsupporting_plane(ca::CircularArc3)\n\n\"\"\"\n    diametral_sphere(ca::CircularArc3)\n\nReturns the diametral_sphere of `ca`'s supporting circle.\n\"\"\"\ndiametral_sphere(ca::CircularArc3)\n\n\"\"\"\n    source(ca::CircularArc3)\n\nReturns the arc's smallest point, supposing its supporting circle is\ntraversed in counterclockwise direction.\n\nWhen the arc was constructed from its (full) underlying circle, then source\nreturns the smallest ``x``-extremal point of the circle if the circle is not\ncontained in a plane ``x = A``, and the smallest ``y``-extremal point otherwise.\n\"\"\"\nsource(ca::CircularArc3)\n\n\"\"\"\n    target(ca::CircularArc3)\n\nReturns the arc's ending point, supposing its supporting circle is traversed\nin counterclockwise direction.\n\nWhen the arc was constructed from its (full) underlying circle, then target\nreturns the smallest ``x``-extremal point of the circle if the circle is not\ncontained in a plane ``x = A``, and the smallest ``y``-extremal point otherwise.\n\"\"\"\ntarget(ca::CircularArc3)\n\n\"\"\"\n    ==(ca\u2081::CircularArc3, ca\u2082::CircularArc3)\n\nTest for equality.\n\nTwo arcs are equal, iff their non-oriented supporting planes are equal, the\ncenters and squared radii of their respective supporting circles are equal, and\ntheir sources and targets are equal.\n\"\"\"\n==(ca\u2081::CircularArc3, ca\u2082::CircularArc3)\n", "meta": {"hexsha": "b5fac67bd216877790b7c762eeb406ca1697a641", "size": 3453, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/circular_arc_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/circular_arc_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/circular_arc_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": 27.188976378, "max_line_length": 80, "alphanum_fraction": 0.7158992181, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7619197339983964}}
{"text": "module DH32ParallelUtils\n\n# package code goes here\nexport split_int, split_int_lengths\n\n\"\"\"\nSplits an integer number N into a set of n_procs contiguous, non-overlapping integer intervals [ix_start[i], ix_end[i]].\n\nInput:\n\n- N: number to be split.\n\n- n_procs: number of processes.\n\nOutput: ix_start, ix_end\n\n- ix_start: int array of start indexes.\n\n- ix_end: int array of end indexes.\n\"\"\"\nfunction split_int(N::Int64, n_procs::Int64)\n    ix_start = zeros(Int64,n_procs)\n    ix_end = zeros(Int64,n_procs)\n    float_bounds = range(1.0, stop=Float64(N), length=n_procs+1)\n    ix_start[1] = 1\n    ix_end[n_procs] = N\n    for i in 2:n_procs\n        ix_start[i] = round(Int64,float_bounds[i])\n        ix_end[i-1] = ix_start[i]-1\n    end\n    ix_start, ix_end\nend\n\n\"\"\"\nSplit a integer N in n_procs integer pieces of approximately the same lengths.\n\nInput: as for split_int.\n\nOutput:\n\n- Array of n_procs integer lengths summing up to N\n    \n\"\"\"\nfunction split_int_lengths(N::Int64, n_procs::Int64)\n    ix_start, ix_end = split_int(N, n_procs)\n    ix_end - ix_start .+ 1 \nend\n                           \nend # module\n", "meta": {"hexsha": "b5a9d64794920e8e02acfbb5681ca58594a04838", "size": 1106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DH32ParallelUtils.jl", "max_stars_repo_name": "DanielHoffmann32/DH32ParallelUtils.jl", "max_stars_repo_head_hexsha": "567d50030f3b81b7fab19e96acd92979dd85cc9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DH32ParallelUtils.jl", "max_issues_repo_name": "DanielHoffmann32/DH32ParallelUtils.jl", "max_issues_repo_head_hexsha": "567d50030f3b81b7fab19e96acd92979dd85cc9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DH32ParallelUtils.jl", "max_forks_repo_name": "DanielHoffmann32/DH32ParallelUtils.jl", "max_forks_repo_head_hexsha": "567d50030f3b81b7fab19e96acd92979dd85cc9a", "max_forks_repo_licenses": ["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": 120, "alphanum_fraction": 0.6844484629, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7619009072572328}}
{"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\u1d6a::Int64=4)\n    \"\"\"\n            is_unstable(z, f\u1d6a)\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\u2093 (Int64): Critical value for sandpile model (Must be > 1)\n    Returns:\n            (bool): Whether grid is stable or unstable.\n    \"\"\"\n    if f\u1d6a <= 1\n        error(\"`f\u1d6a` must be int greater than  1\")\n    end\n    if length(findall(>=(f\u1d6a), z)) > 0\n        return true\n    else\n        return false\n    end\nend\n\nfunction avalanche64!(z::Array{Int64,2}, f\u1d6a=4)\n    \"\"\"\n            avalanche(z, f\u1d6a)\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\u2093 (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\u1d6a), 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\u1d6a::Int64=4)\n    \"\"\"\n            run_sandpile(z, N, f\u1d6a)\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\u2093 (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\u1d6a)\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\u1d6a)\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\u1d62, a\u2081, a\u2082, a\u2083,  b\u2081, b\u2082, b\u2083, \n        c\u2081\u2082, c\u2082\u2083, c\u2081\u2083, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083) -> 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\u00e9vitch, B., Le Bouquin-Jeann\u00e8s, R., & Faucon, G. (2006). Linear and nonlinear \n    causality between signals: methods, examples and neurophysiological \n    applications. Biological Cybernetics, 95(4), 349\u2013369.\n\"\"\"\nfunction eom_nonlinear3d(x, p, n)\n    x\u2081, x\u2082, x\u2083 = (x...,)\n    a\u2081, a\u2082, a\u2083, b\u2081, b\u2082, b\u2083, c\u2081\u2082, c\u2082\u2083, c\u2081\u2083, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083 = (p...,)\n    \u03be\u2081 = rand(Normal(0, \u03c3\u2081))\n    \u03be\u2082 = rand(Normal(0, \u03c3\u2082))\n    \u03be\u2083 = rand(Normal(0, \u03c3\u2083))\n    \n    dx\u2081 = a\u2081*x\u2081*(1-x\u2081)^2 * exp(-x\u2081^2) + b\u2081*\u03be\u2081\n    dx\u2082 = a\u2082*x\u2082*(1-x\u2082)^2 * exp(-x\u2082^2) + b\u2082*\u03be\u2082 + c\u2081\u2082*x\u2081*x\u2082 \n    dx\u2083 = a\u2083*x\u2083*(1-x\u2083)^2 * exp(-x\u2083^2) + b\u2083*\u03be\u2083 + c\u2082\u2083*x\u2082 + c\u2081\u2083*x\u2081^2\n\n    return SVector{3}(dx\u2081, dx\u2082, dx\u2083)\nend\n\nfunction nonlinear3d(u\u1d62, a\u2081, a\u2082, a\u2083,  b\u2081, b\u2082, b\u2083, c\u2081\u2082, c\u2082\u2083, c\u2081\u2083, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083)\n    p = [a\u2081, a\u2082, a\u2083,  b\u2081, b\u2082, b\u2083, c\u2081\u2082, c\u2082\u2083, c\u2081\u2083, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083]\n    s = DiscreteDynamicalSystem(eom_nonlinear3d, u\u1d62, p)\n    return s\nend\n\n\"\"\"\n    nonlinear3d(;u\u1d62 = rand(3), \n        \u03c3\u2081 = 1.0, \u03c3\u2082 = 1.0, \u03c3\u2083 = 1.0, \n        a\u2081 = 3.4, a\u2082 = 3.4, a\u2083 = 3.4, \n        b\u2081 = 0.4, b\u2082 = 0.4, b\u2083 = 0.4, \n        c\u2081\u2082 = 0.5, c\u2082\u2083 = 0.3, c\u2081\u2083 = 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\u00e9vitch, B., Le Bouquin-Jeann\u00e8s, R., & Faucon, G. (2006). Linear and nonlinear \n    causality between signals: methods, examples and neurophysiological \n    applications. Biological Cybernetics, 95(4), 349\u2013369.\n\"\"\"\nnonlinear3d(;u\u1d62 = rand(3), \n        \u03c3\u2081 = 1.0, \u03c3\u2082 = 1.0, \u03c3\u2083 = 1.0, \n        a\u2081 = 3.4, a\u2082 = 3.4, a\u2083 = 3.4, \n        b\u2081 = 0.4, b\u2082 = 0.4, b\u2083 = 0.4, \n        c\u2081\u2082 = 0.5, c\u2082\u2083 = 0.3, c\u2081\u2083 = 0.5) = \n    nonlinear3d(u\u1d62, a\u2081, a\u2082, a\u2083,  b\u2081, b\u2082, b\u2083, c\u2081\u2082, c\u2082\u2083, c\u2081\u2083, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083)\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\u03c1\u03c3 is the matern covariance and G_\u03c3\u03c1 is Gaussian autocovariance model\nexport \u2133_\u03bd, M_\u03bd\u03c1\u03c3, G_\u03c3\u03c1\n\nt\u03bd\ud835\udca6t(t,\u03bd) = t^\u03bd * besselk(\u03bd, t)\n\n\"\"\"\n    \u2133_\u03bd(t, \u03bd)\n\nCompute (\u221a(2\u03bd)*t) ^ \u03bd * \ud835\udca6\u03bd(\u221a(2\u03bd)*t) where \ud835\udca6\u03bd is the modified Bessel function of the second kind of order \u03bd.\n\n# Example\n```julia-repl\njulia> \u2133_\u03bd(0.0, 0.5)\n1.0\n```\n\"\"\"\nfunction \u2133_\u03bd(t, \u03bd)\n\tpt, p\u03bd, p0, p1 = promote(t, \u03bd, 0, 1)\n\treturn (pt==p0) ? p1 : t\u03bd\ud835\udca6t(\u221a(2p\u03bd)*pt,p\u03bd) * 2^(1-p\u03bd) / gamma(p\u03bd)\nend\n\nfunction M_\u03bd\u03c1\u03c3(t; \u03bd, \u03c1, \u03c3)\n\treturn \u03c3 * \u03c3 * \u2133_\u03bd(t/\u03c1, \u03bd)\nend\n\nfunction G_\u03c3\u03c1(t; \u03c3,\u03c1)\n\treturn \u03c3 * \u03c3 *exp(-t^2/\u03c1^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": "# Test rosenbrock pdf gradients\n# Authors: Ali Siahkoohi, alisk@gatech.edu\n# Date: September 2020\n\nusing DrWatson\n@quickactivate :FastApproximateInference\nimport Pkg; Pkg.instantiate()\n\nusing LinearAlgebra\nusing Test\n\n# Input\nn_samples = 1\n\n# Rosenbrock distribution\nRB_dist = RosenbrockDistribution(0f0, 5f-1, ones(Float32, 2, 1))\n\n# samples\nX0 = rand(RB_dist, n_samples)\nX = rand(RB_dist, n_samples)\ndX = X - X0\n\nfunction rosenbrock_nlpdf(RB_dist, x)\n    return nl_pdf(x, RB_dist)[1], nl_pdf_grad(x, RB_dist)\nend\n\n# Gradient test\nf0, \u0394X = rosenbrock_nlpdf(RB_dist, X0)\nh = 0.1f0\nmaxiter = 5\nerr1 = zeros(Float32, maxiter)\nerr2 = zeros(Float32, maxiter)\n\nprint(\"\\nGradient test\\n\")\nfor j=1:maxiter\n    f = rosenbrock_nlpdf(RB_dist, X0 + h*dX)[1]\n    err1[j] = abs(f - f0)\n    err2[j] = abs(f - f0 - h*dot(dX, \u0394X))\n    print(err1[j], \"; \", err2[j], \"\\n\")\n    global h = h/2f0\nend\n\n@test isapprox(err1[end] / (err1[1]/2^(maxiter-1)), 1f0; atol=1f1)\n@test isapprox(err2[end] / (err2[1]/4^(maxiter-1)), 1f0; atol=1f1)\n", "meta": {"hexsha": "298ba60ec5a447d8b3fb635c4818bf735ac18707", "size": 1015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_rosenbrock.jl", "max_stars_repo_name": "slimgroup/Software.siahkoohi2021AABIpto", "max_stars_repo_head_hexsha": "835993aee64d7ad19f03659498a0dfdfd8d6dea9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-11T02:27:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T18:57:01.000Z", "max_issues_repo_path": "test/test_rosenbrock.jl", "max_issues_repo_name": "slimgroup/Software.siahkoohi2021AABIpto", "max_issues_repo_head_hexsha": "835993aee64d7ad19f03659498a0dfdfd8d6dea9", "max_issues_repo_licenses": ["MIT"], "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_rosenbrock.jl", "max_forks_repo_name": "slimgroup/Software.siahkoohi2021AABIpto", "max_forks_repo_head_hexsha": "835993aee64d7ad19f03659498a0dfdfd8d6dea9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-11T02:27:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T12:14:32.000Z", "avg_line_length": 22.5555555556, "max_line_length": 66, "alphanum_fraction": 0.6876847291, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7618808216430141}}
{"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\u2013Stokes\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\u2013Stokes 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 \u2014 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 \u2014 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\u8ba1\u7b97\u6392\u5217\u6570 A_n^m,\u8f93\u5165\u9700\u8981\u662f\u6574\u6570\u7c7b\u578b\uff0c\u8fd4\u56de\u503c\u662fBigInt\u7c7b\u578b\uff0c\u56e0\u4e3a\u6392\u5217\u6570\u5f88\u5bb9\u6613\u53d8\u6210\u5927\u6570\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\u8ba1\u7b97\u7ec4\u5408\u6570\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\u8ba1\u7b97\u4e8c\u9879\u5206\u5e03\u7684\u5217\u8868\n\u5176\u4e2d\u53c2\u6570n\u4e3a\u53d1\u751f\u6b21\u6570\uff0cp\u4e3a\u5355\u6b21\u72ec\u7acb\u4e8b\u4ef6\u7684\u6982\u7387\nBinomial_Distribution(n::Integer, p)\n\u8fd4\u56de\u503c\u662f\u4e00\u4e2a\u5217\u8868\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\u6cca\u677e\u5206\u5e03\n\u03bb\u1d4f\u212f^\u03bb / k!,k=0,1,2\n\u03bb=n\u22c5p\nfunction Poisson_Distribution(num::Integer, \u03bb)\n\"\"\"\nfunction Poisson_Distribution(range::AbstractRange, \u03bb::Real)\n    check_is_nonnegative(\u03bb, range[1])\n    resList = []\n    for k in range\n        push!(resList, \u03bb^k * \u212f^-\u03bb / factorial(big(k)))\n    end\n    return resList\nend\n\n\"\"\"\n    \u51e0\u4f55\u5206\u5e03\n\u4ed6\u7684\u6bcf\u4e00\u9879\u4e3a (1-p)^(k-1)*p\n\u8d77\u59cb\u9879\u4e3ak=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    \u8d85\u51e0\u4f55\u5206\u5e03\n\u4eceN\u4ef6\u4ea7\u54c1\uff08\u5176\u4e2d\u6b21\u54c1M\u4ef6\uff09\u4e2d\u4efb\u53d6n\u4ef6\uff0ck\u4e3a\u53d6\u5230\u7684\u6b21\u54c1\u6570\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    \u6b63\u6001\u5206\u5e03\nfunction Normal_Distribution_pdf(range::AbstractRange, \u03bc, \u03c3)\n\"\"\"\nfunction Normal_Distribution_pdf(range::AbstractRange, \u03bc::Real, \u03c3::Real)\ncheck_not_empty(range)\n    check_is_nonnegative(\u03bc)\n    resList = []\n    for x in range\n        constant = 1 / (sqrt(2\u03c0) * \u03c3)\n        push!(resList, constant * \u212f^(-(x - \u03bc)^2 / (2 * \u03c3^2)))\n    end\n    return resList\nend\n\n\"\"\"\n    \u6307\u6570\u5206\u5e03 \u6982\u7387\u5bc6\u5ea6\u51fd\u6570\n\nfunction Exponential_Distribution(range::AbstractRange, \u03b8::Real)\n\"\"\"\nfunction Exponential_Distribution_pdf(range::AbstractRange, \u03b8::Real)\n    check_not_empty(range)\n    check_is_nonnegative(range[1])\n    resList = []\n    for x in range\n        push!(resList, (1 / \u03b8) * \u212f^(-x / \u03b8))\n    end\n    return resList\nend     \n\n\"\"\"\n    \u6307\u6570\u5206\u5e03\nfunction Exponential_Distribution(range::AbstractRange, \u03b8::Real)\n\"\"\"\nfunction Exponential_Distribution(range::AbstractRange, \u03b8::Real)\n    check_not_empty(range)\n    check_is_nonnegative(range[1])\n    resList = []\n    for x in range\n        push!(resList, 1 - \u212f^(-x / \u03b8))\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*\u03c0, 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\u00fcrmann, M., & Ba\u015far, 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\u2c7c = 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\u2c7c = 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\u2c7cs = 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([\u03c1=1])`\nThe exponentiated kernel is a Mercer kernel given by:\n```\n    \u03ba(x,y) = exp(\u03c1\u00b2x\u1d40y)\n```\n\"\"\"\nstruct ExponentiatedKernel{Tr} <: Kernel{Tr}\n    transform::Tr\nend\n@inline kappa(\u03ba::ExponentiatedKernel, x\u1d40y::T) where {T<:Real} = exp(x\u1d40y)\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(\u03c3::num1,\u03bc::num2) where {num1,num2 <: Number}\n\t\nWhere:\\n\n\t\t\u03c3\t=\tvolatility of the process.\n\t\t\u03bc\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    \u03c3::num\n    \u03bc::num1\n    x0::num2\n    function GeometricBrownianMotion(\u03c3::num, \u03bc::num1, x0::num2) where {num <: Number, num1 <: Number, num2 <: Number}\n        if \u03c3 <= 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)}(\u03c3, \u03bc, x0)\n        end\n    end\nend\n\nexport GeometricBrownianMotion;\n\nfunction simulate!(X, mcProcess::GeometricBrownianMotion, mcBaseData::AbstractMonteCarloConfiguration, T::Number)\n    @assert T > 0\n    \u03c3_gbm = mcProcess.\u03c3\n    mu_gbm = mcProcess.\u03bc\n    \u03bc_bm = mu_gbm - \u03c3_gbm^2 / 2\n    simulate!(X, BrownianMotion(\u03c3_gbm, \u03bc_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": "function modeorthonorm(basis,N,err = 1e-9,\u03c9=1.)\n\nx,w,T = nfieldtrans(N,2,\u03c9=\u03c9)\nNormtest = T'*(T.*(w.*ones(N)))\n\n#check orthonormality is close to identity matrix for the basis\nmaxerr = maximum(abs.(Normtest-eye(Normtest)))\nmaxerr < err\nend\n", "meta": {"hexsha": "d7a643f0900fdd71f73a235a91eb383ddb690cbe", "size": 239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modeorthonorm.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": "test/modeorthonorm.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": "test/modeorthonorm.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": 23.9, "max_line_length": 63, "alphanum_fraction": 0.7071129707, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7618280137587319}}
{"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# \u03bd\u2207\u00b2u + G(u,x) = f(x), x\u2208\u03a9\n#     u = ub,         , x\u2208\u2202\u03a9\n#\n#----------------------------------#\nx1 = m1.x\ny1 = m1.y\n\nfunction G(u,msh::Mesh) # G(u,x\u20d7)\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\u20d7)\n    @unpack x,y = msh\n#   Gdu = @. 3u^2\n    Gdu = @. exp.(-u)\n    return Gdu\nend\n\n\u03bd  = @. 1+0*x1\nu  = @. 0+0*x1 # initial guess (must agree with boundary data)\n\u03b4u = @. 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 \u03b4u\n#----------------------------------#\nfunction residual(v,msh::Mesh)\n    resi  = mass(f,msh)\n    resi -= mass(G(v,msh),msh) .+ \u03bd.*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,\u03bd,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 -= \u03bd.*lapl(u,m1) .+ mass(g,m1) # from LHS\n    b .= mask(b,M1)\n    b .= gatherScatter(b,m1)\n\n    # solve\n    pcg!(\u03b4u,b,opLHS,mult=m1.mult,ifv=false)\n    u .+= \u03b4u\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 \u221e 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}, \u025b=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 <= \u025b\n            if \u025b > 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\u00d74 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\u00d74 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\u00d74 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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.31\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.31\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550f3fb9a0e-2294-11eb-227d-135a8b801a20\n# \u2560\u2550f3fbcc54-2294-11eb-1a96-b1676ddb7772\n# \u255f\u250070182cd8-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# \u2554\u2550\u2561 dba46e66-8704-42de-938c-d576a1336398\nusing PlutoUI, Plots, Graphs, GraphMakie, CairoMakie, NetworkLayout, Test\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d3ee4413-c691-4fba-9f91-f24985fb8a88\nmd\"\"\" The Nussinov matrix for the example RNA looks like this: \"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 aea52dd9-7bcc-4873-9332-36b95592b27b\nmd\"\"\" If we backtrack from $$(i=1,j=n)$$ we get all the pairs in the sequence: \"\"\"\n\n# \u2554\u2550\u2561 31aeff3d-5083-4c26-a556-847fbe76f9d6\nmd\"\"\"\n\n## Tool\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3c7f1384-33ac-4b2d-9a63-4bf412bfa685\nRNA = replace(uppercase(rna), 'T' => 'U')\n\n# \u2554\u2550\u2561 45b4e0ec-5581-4a28-b6c1-c95b8e6a42bb\nRNA\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fd14341c-f195-4b86-9f9c-379477eed4af\nmd\"\"\"\n\nHere is the visualization of the secondary structure:\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2fbe430d-ab80-406e-aa87-c377d6ed30c2\nmd\"\"\"\n\n## Appendix\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0a20eddd-24f7-43c6-a0f3-6c1c138fb90a\nS = Nussinov(RNA)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 43f97b8d-cd9c-4b8f-8821-68542488e49d\npairs = traceback(RNA, S, 1, length(RNA))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f66956d6-6d0d-42d1-b210-4bdf23ccd0b8\nstructure = dotbracket(RNA, pairs)\n\n# \u2554\u2550\u2561 c86cc53d-4675-4cd1-af75-ec4a717fd7fa\nlink = \"http://nibiru.tbi.univie.ac.at/forna/forna.html?id=url/name&sequence=$RNA&structure=$structure\"\n\n# \u2554\u2550\u2561 e25d53b9-0096-4b6c-85cb-fcae261fabcb\nmd\"\"\" $link \"\"\"\n\n# \u2554\u2550\u2561 f4e866fc-8e18-4917-b515-9cc00175a7a4\nbegin\n\tmyblue = \"#304da5\"\n\tmygreen = \"#2a9d8f\"\n\tmyyellow = \"#e9c46a\"\n\tmyred = \"#e76f51\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 06983a7b-efca-4167-be5d-a158a4e0858d\nplotstructure(RNA, pairs)\n\n# \u2554\u2550\u2561 94691ccf-b1ef-4cc3-8eed-72dd543001f5\nmd\"\"\" Unit tests are in the hidden chunk below: \"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25004b3e86ea-6973-11ec-014f-9f2708ba86cf\n# \u2560\u25502d83c447-1d33-496a-8a39-75d1cb9b2de1\n# \u2560\u255045b4e0ec-5581-4a28-b6c1-c95b8e6a42bb\n# \u255f\u2500d3ee4413-c691-4fba-9f91-f24985fb8a88\n# \u2560\u25500a20eddd-24f7-43c6-a0f3-6c1c138fb90a\n# \u255f\u2500a455cfa0-ee29-4a4e-8b26-cf91c36985ec\n# \u2560\u2550463d18c3-e155-4b73-896f-2bbcdb71bbd2\n# \u255f\u2500aea52dd9-7bcc-4873-9332-36b95592b27b\n# \u2560\u255043f97b8d-cd9c-4b8f-8821-68542488e49d\n# \u255f\u250031aeff3d-5083-4c26-a556-847fbe76f9d6\n# \u255f\u2500b2084e43-7914-495f-b93e-cf56a87be3c7\n# \u255f\u250059108cf2-d8a5-4c16-b373-bb6a23d13735\n# \u255f\u2500ed0a3dc5-99d3-4628-ad5c-7d13e699b353\n# \u255f\u25003c7f1384-33ac-4b2d-9a63-4bf412bfa685\n# \u255f\u250042921538-4ff4-4902-aefa-d958f41d1404\n# \u255f\u2500f66956d6-6d0d-42d1-b210-4bdf23ccd0b8\n# \u255f\u2500fd14341c-f195-4b86-9f9c-379477eed4af\n# \u2560\u255006983a7b-efca-4167-be5d-a158a4e0858d\n# \u255f\u2500ca99ac1a-e4da-41fe-8ab6-834e2b7134b7\n# \u255f\u2500e25d53b9-0096-4b6c-85cb-fcae261fabcb\n# \u255f\u25002fbe430d-ab80-406e-aa87-c377d6ed30c2\n# \u2560\u2550dba46e66-8704-42de-938c-d576a1336398\n# \u2560\u2550e5650185-a6bc-488c-a02b-3c1363c52b8c\n# \u2560\u2550b156a4c7-6ed9-4a4d-b3c9-d3c06fbc1faf\n# \u2560\u2550c86cc53d-4675-4cd1-af75-ec4a717fd7fa\n# \u2560\u25502e8fb274-0658-43f8-bfa0-40f2f1daf6f3\n# \u2560\u2550f4e866fc-8e18-4917-b515-9cc00175a7a4\n# \u255f\u250094691ccf-b1ef-4cc3-8eed-72dd543001f5\n# \u255f\u250032755c53-eefc-4d40-bf60-a8b21a545c6d\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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 AdFem\n\nmmesh = Mesh3(20, 20, 20, 1/20)\nxy = gauss_nodes(mmesh)\na = Variable(0.1)\n\u03ba = 1/(a+xy[:,1].^2 + xy[:,2].^2 + xy[:,3].^2)\nK = compute_fem_laplace_matrix1(\u03ba, mmesh)\nrhs = compute_fem_source_term1(ones(get_ngauss(mmesh)), mmesh)\nbd = bcnode(mmesh)\nK, rhs = impose_Dirichlet_boundary_conditions(K, rhs, bd, zeros(length(bd)))\nsol = K\\rhs\nsess = Session(); init(sess)\nSOL = run(sess, sol)\n\n\n\n############## Visualization 1\nusing PyPlot\nusing DelimitedFiles \nidx = falses(mmesh.ndof)\ns = 1\nfor k = 1:21\n    for j = 1:21\n        for i = 1:21\n            if k==11 && j==11\n                idx[s] = true \n            end\n            global s = s + 1\n        end\n    end\nend\nclose(\"all\")\nx0 = LinRange(0,1,21)\nplot(x0, readdlm(\"val.txt\")[:], label = \"FEniCS\")\nplot(x0, SOL[idx], \"o\", label = \"AdFem\")\n\nlegend()\nxlabel(\"x\")\nylabel(\"\\$u(x, 0.5, 0.5)\\$\")\nsavefig(\"section_plot_mfem3d.png\")\n\n\n############## Visualization 2\nvisualize_scalar_on_fem_points(SOL, mmesh)\nvisualize_mesh(mmesh)", "meta": {"hexsha": "3afb5d0003b977597f65c6b44a7512378c3eb65a", "size": 987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deps/MFEM3/FemLaplace1/ftest.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": "deps/MFEM3/FemLaplace1/ftest.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": "deps/MFEM3/FemLaplace1/ftest.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": 21.9333333333, "max_line_length": 76, "alphanum_fraction": 0.5987841945, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428692, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7617799511014939}}
{"text": "push!(LOAD_PATH, string(pwd(),\"/src\"))\n\nusing ModifiedStokesSolver\nusing FastGaussQuadrature\nusing Base.Test\n\npanelorder1 = 32\npanelorder2 = 160\n\nglpoints1, glweights1 = gausslegendre(panelorder1)\nglpoints2, glweights2 = gausslegendre(panelorder2)\n\n@testset \"Upsampling\" begin\n    U = ModifiedStokesSolver.upsampling_matrix(panelorder1, panelorder2)\n    f(x) = @. 1/(x^2+2)\n    fu = U * f(glpoints1)\n    err = fu - f(glpoints2)\n    relerr_inf = norm(err, Inf) / norm(fu, Inf)\n    @test relerr_inf < 2e-14\nend\n\n", "meta": {"hexsha": "b35f7870ad91611bf3926c465ea8ef362ea920bc", "size": 510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/tests/test_upsampling.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/tests/test_upsampling.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/tests/test_upsampling.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.1818181818, "max_line_length": 72, "alphanum_fraction": 0.7176470588, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.761779948739909}}
{"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\u03bc, \u03c3 = 1, 0.1\nmaxdegree = 7\n\n# model equation\nfunction model(x)\n    exp.(\u03bc + \u03c3 * x)\nend\n\n\n# Analytic refernce\nk_values = 0:maxdegree\ncomputeCoefficient_analytic(k::Int) = exp(\u03bc + 0.5*\u03c3^2) * \u03c3^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    \u03b3 = t2.get([k,k])\n    integrate(g, op.quad) / \u03b3\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 \u03a6 with \u03d5(x(i))\n# \u03a6 = Array{Float64}(undef, nSamples, maxdegree+1)\n\u03a6 = [ evaluate(j, X[i], op) for i = 1:nSamples, j = 0:maxdegree]\n\n# Ordinary least squares regression\ny_reg = leastSquares(\u03a6, 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, \u03a6, y_reg)\n# println(\"Determination coefficient R\u00b2 (normalized empicial error): \", 1 - genError)\n\n\u03f5Loo = looError(Y, \u03a6, y_reg)\nprintln(\"Determination coefficient Q\u00b2 (leave-one-out error): \", 1- \u03f5Loo)\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(\u03bc + \u03c3^2/2)\nstd_ana = sqrt(exp(2*\u03bc + \u03c3^2) * (exp(\u03c3^2) - 1))\nskew_ana = sqrt(exp(\u03c3^2) - 1) * (exp(\u03c3^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 (\u0169, \u1e7d) = (-\u2202_y, +\u2202_x) \u03c8\u0303\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": "##########################\n# FunctionCell Interface #\t\n##########################\n\"\"\"\n\tlr(r=0; trans=true, bias=true)\n\nConstructs an untrained cell that when piped data inside (observations and\nresponses) calculates the regularized (ridge) Least-Squares regression \ncoefficients of the data based on the responses and regularization parameter\n`r`.\n\nThe parameter `r` can be a real scalar, a vector or symetric matrix.\n\n# Keyword arguments (same as in `MultivariateStats`)\n  * `trans` whether to use the trasposed form, (default `true` e.g. rows are variables, columns are observations) \n  * `bias` whether to include a bias term (default `true`)\n\nRead the `MultivariateStats.jl` documentation for more information.  \n\"\"\"\nlr(r=0; trans::Bool=true, bias::Bool=true) = \n\tFunctionCell(lr, (r,), ModelProperties(), \n\t      kwtitle(\"Linear regressor\", [(:trans,trans),(:bias,bias)]); \n\t      trans=trans, bias=bias) \n\n\n\n############################\n# DataCell/Array Interface #\t\n############################\n\"\"\"\n\tlr(x,y, [;kwargs])\n\nTrains a Least-Squares regression function cell. Returns the regression coefficients and bias (if available) \n\"\"\"\n# Training\nlr(x::T where T<:CellDataU, r::Union{Real, AbstractArray}=0; trans::Bool=true, bias::Bool=true) =\n\tlr((getx!(x), zeros(nobs(x))), r; trans=trans, bias=bias)\nlr(x::T where T<:CellData, r::Union{Real, AbstractArray}=0; trans::Bool=true, bias::Bool=true) =\n\tlr((getx!(x), gety(x)), r; trans=trans, bias=bias)\nlr(x::Tuple{T,S} where T<:AbstractVector where S<:AbstractArray, r::Union{Real, AbstractArray}=0; trans::Bool=true, bias::Bool=true) =\n\tlr((mat(x[1], LearnBase.ObsDim.Constant{2}()), x[2]), r; trans=trans, bias=bias)\nlr(x::Tuple{T,S} where T<:AbstractMatrix where S<:AbstractArray, r::Union{Real, AbstractArray}=0; trans::Bool=true, bias::Bool=true ) = begin\n\t\n\t@assert nobs(x[1]) == nobs(x[2])\n\n\t# If y vector, leave as is, if matrix, traspose\n\tif x[2] isa Vector \n\t\ttmp = MultivariateStats.ridge(getobs(x[1]), x[2], r, trans=trans, bias=bias)\n\telse\n\t\ttmp = MultivariateStats.ridge(getobs(x[1]), x[2]', r, trans=trans, bias=bias)\n\tend\n\t\n\tif bias\n\t\ta = tmp[1:end-1,:]\n\t\tb = tmp[end,:]\n\telse\n\t\ta = tmp\n\t\tb = zeros(nvars(x[2]))\n\tend\n\n\t# Build model properties \n\tmodelprops = ModelProperties(size(a,1), size(a,2))\n\t\n\t# Returned trained cell\n\tFunctionCell(lr, Model((a,b), modelprops), kwtitle(\"Linear regressor\", [(:trans,trans),(:bias,bias)]))\t \nend\n\n\n\n# Execution\nlr(x::T where T<:CellData, model::Model{<:Tuple{<:AbstractArray, <:AbstractArray}}) =\n\tdatacell(lr(getx!(x), model), gety(x)) \t\nlr(x::T where T<:AbstractVector, model::Model{<:Tuple{<:AbstractArray, <:AbstractArray}}) =\n\tlr(mat(x, LearnBase.ObsDim.Constant{2}()), model) \t\nlr(x::T where T<:AbstractMatrix, model::Model{<:Tuple{<:AbstractArray, <:AbstractArray}}) =\n\tmodel.data[1]'*x .+ model.data[2] # e.g. a\u1d40X+b\n", "meta": {"hexsha": "7b6cb1a5677fe5b76c00db576f748e82e9e70bbb", "size": 2834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib/ext/lr.jl", "max_stars_repo_name": "zgornel/j4pr.jl", "max_stars_repo_head_hexsha": "5b6211facda41d9b9f8bda6724bc7fbc3173b88a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-10-08T13:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T12:09:11.000Z", "max_issues_repo_path": "src/lib/ext/lr.jl", "max_issues_repo_name": "zgornel/j4pr.jl", "max_issues_repo_head_hexsha": "5b6211facda41d9b9f8bda6724bc7fbc3173b88a", "max_issues_repo_licenses": ["MIT"], "max_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/ext/lr.jl", "max_forks_repo_name": "zgornel/j4pr.jl", "max_forks_repo_head_hexsha": "5b6211facda41d9b9f8bda6724bc7fbc3173b88a", "max_forks_repo_licenses": ["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.8051948052, "max_line_length": 141, "alphanum_fraction": 0.6598447424, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7617799414987213}}
{"text": "using JuSwarm, Optim, StaticArrays, Test\n\nfunction spherefunc(x::AbstractVector)\n    return sum(x.^2)\nend\n\nN = 14\nPSOopts = PSOOptions(N; HybridOptimizer = Optim.LBFGS(), Display = \"none\")\n\nsol = psoptimize(spherefunc, PSOopts)\n\n@test sol.fbest <= sol.fbestPSO\n\n@test sol.fbestPSO <= 1.0e-6\n\n@test sol.fbest <= 1.0e-10", "meta": {"hexsha": "b71f724ed95cf5eec3b31fdd20eeba164ae28218", "size": 318, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sphere_function_test.jl", "max_stars_repo_name": "GrantHecht/JuSwarm", "max_stars_repo_head_hexsha": "adc3ff8a0dcd1d4b7db55c636a2b612dbc157fd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-14T14:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T14:58:11.000Z", "max_issues_repo_path": "test/sphere_function_test.jl", "max_issues_repo_name": "GrantHecht/JuSwarm.jl", "max_issues_repo_head_hexsha": "adc3ff8a0dcd1d4b7db55c636a2b612dbc157fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-20T13:46:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T01:30:40.000Z", "max_forks_repo_path": "test/sphere_function_test.jl", "max_forks_repo_name": "GrantHecht/JuSwarm", "max_forks_repo_head_hexsha": "adc3ff8a0dcd1d4b7db55c636a2b612dbc157fd5", "max_forks_repo_licenses": ["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": 74, "alphanum_fraction": 0.7106918239, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133464597459, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7617799389807038}}
{"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, \u2026] / 5040\n# etc\n\nfunction fd_diff2_ord2!(dx2_U, U, dx\u207b\u00b9)\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\u207b\u00b9 ^ 2\n\n    nothing\nend\n\nfunction fd_diff2_ord4!(dx2_U, U, dx\u207b\u00b9)\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\u207b\u00b9 ^ 2\n\n    nothing\nend\n\nfunction fd_diff2_ord6!(dx2_U, U, dx\u207b\u00b9)\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\u207b\u00b9 ^ 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": "#Tests using the NIST Matrix Market\n\nusing IterativeSolvers, MatrixMarket\n@info(\"Testing matrices from the NIST Matrix Market\")\nfor (setname, matname) in [(\"cylshell\", \"s3dkq4m2\")]\n    dl_filename = string(setname, \"_\", filename)\n    isfile(dl_filename) || download(\"ftp://math.nist.gov/pub/MatrixMarket2/misc/$setname/$matname.mtx.gz\", dl_filename)\n\n    vars = matread(dl_filename)\n    A, b = vars[\"Problem\"][\"A\"], vars[\"Problem\"][\"b\"][:]\n\n    #Use direct solve as benchmark\n    println(\"$dl_filename: Direct solve\")\n    tic()\n    x = A \\ b\n    toc()\n\n    @show Aissym = issym(A)\n    @show Aisposdef = isposdef(A)\n    solvers = {}\n    Aissym && Aisposdef && push!(solvers, cg)\n    #push!(solvers, gmres)\n    for solver in solvers\n        println(\"$dl_filename: Iterative solve using $solver\")\n        tic()\n        xs, ch = solver(A, b)\n        toc()\n\tr=norm(x-xs)\n        println(\"Residual: $r matvecs: $(ch.mvps) iters: $(length(ch.residuals))\")\n    end\nend\n\n", "meta": {"hexsha": "0dac5a086301cff23305529324cd2e1bb6f3b3b7", "size": 962, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark/matrixmarket.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/matrixmarket.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/matrixmarket.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": 29.1515151515, "max_line_length": 119, "alphanum_fraction": 0.6288981289, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7617492914180009}}
{"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 Extremes, DataFrames, Gadfly, Test, Distributions\n\ndata = load(\"portpirie\")\n\nx = Variable(\"x\", randn(100))\n\u03bc = 10 .+ x.value\n\u03c3 = 1.0\n\u03be = .1\npd = GeneralizedExtremeValue.(\u03bc, \u03c3, \u03be)\ny = rand.(pd)\n\n\nfm = gevfit(data, :SeaLevel)\nfmns = gevfit(y, locationcov=[x])\n\nprobplot(fm)\nprobplot(fmns)\n\nqqplot(fm)\nqqplot(fmns)\n\nreturnlevelplot(fm)\nreturnlevelplot(fmns)\n\nhistplot(fm)\nhistplot(fmns)\n\ndiagnosticplots(fm)\ndiagnosticplots(fmns)\n\nfm = gevfitbayes(data, :SeaLevel)\nfmns = gevfitbayes(y, locationcov=[x])\n\nprobplot(fm)\nprobplot(fmns)\n\nqqplot(fm)\nqqplot(fmns)\n\nreturnlevelplot(fm)\nreturnlevelplot(fmns)\n\nhistplot(fm)\nhistplot(fmns)\n\ndiagnosticplots(fm)\ndiagnosticplots(fmns)\n\n\n\nys = rand(GeneralizedPareto(1,.1),100)\n\nx = Variable(\"x\", randn(100)/3)\n\u03d5 = x.value\n\u03c3 = exp.(\u03d5)\n\u03be = .1\npd = GeneralizedPareto.(\u03c3, \u03be)\ny = rand.(pd)\n\n\nfm = gpfit(ys)\nfmns = gpfit(y, logscalecov=[x])\n\nprobplot(fm)\nprobplot(fmns)\n\nqqplot(fm)\nqqplot(fmns)\n\nreturnlevelplot(fm)\nreturnlevelplot(fmns)\n\nhistplot(fm)\nhistplot(fmns)\n\ndiagnosticplots(fm)\ndiagnosticplots(fmns)\n\nfm = gpfitbayes(ys)\nfmns = gpfitbayes(y, logscalecov=[x])\n\nprobplot(fm)\nprobplot(fmns)\n\nqqplot(fm)\nqqplot(fmns)\n\nreturnlevelplot(fm)\nreturnlevelplot(fmns)\n\nhistplot(fm)\nhistplot(fmns)\n\ndiagnosticplots(fm)\ndiagnosticplots(fmns)\n", "meta": {"hexsha": "31b4a66c45b2bb734968be24fb93e77b628c0364", "size": 1273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/validationplots/tests_to_integrate.jl", "max_stars_repo_name": "jojal5/Extremes.jl", "max_stars_repo_head_hexsha": "925d9a1bb64e579f97b9d5a1c7357705f7c62d7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-06-20T18:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:33:00.000Z", "max_issues_repo_path": "src/validationplots/tests_to_integrate.jl", "max_issues_repo_name": "jojal5/Extremes.jl", "max_issues_repo_head_hexsha": "925d9a1bb64e579f97b9d5a1c7357705f7c62d7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2020-03-12T23:23:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T00:19:25.000Z", "max_forks_repo_path": "src/validationplots/tests_to_integrate.jl", "max_forks_repo_name": "jojal5/Extremes.jl", "max_forks_repo_head_hexsha": "925d9a1bb64e579f97b9d5a1c7357705f7c62d7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-06-04T15:53:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T14:50:42.000Z", "avg_line_length": 13.2604166667, "max_line_length": 55, "alphanum_fraction": 0.7250589159, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7616681572401218}}
{"text": "using FractionalCalculus\nusing Test\n\n@testset \"Test Fractional Integral\" begin\n    @test isapprox(fracint(x->x^4, 0.5, 0, 1.23, 1e-8, RL_Direct())[1], 1.163931646862977; atol = 0.00001)\n    @test isapprox(fracint(x->x^4, 0.25, 0, 1.23, 1e-8, RL_Direct())[1], 1.64294134724409; atol = 0.00001)\n    @test isapprox(fracint(x->x^4, 0.15, 0, 1.23, 1e-8, RL_Direct())[1], 1.878978485456182; atol = 0.00001)\n    @test isapprox(fracint(x->sin(x), 0.5, 0, 0.97, 1e-8, RL_Direct())[1], 0.6442601778843754; atol = 0.00001)\n    @test isapprox(fracint(x->sin(x), 0.25, 0, 0.97, 1e-8, RL_Direct())[1], 0.7448298999485293; atol = 0.00001)\n    @test isapprox(fracint(x->sin(x), 0.15, 0, 0.97, 1e-8, RL_Direct())[1], 0.7802555196986999; atol = 0.00001)\nend\n\n@testset \"Test Piecewise Fractional Integral\" begin\n    @test isapprox(fracint(x->x^4, 0.5, 1.23, 1e-4, RL_Piecewise()), 1.163931646862977; atol = 1e-5)\n    @test isapprox(fracint(x->x^4, 0.25, 1.23, 1e-4, RL_Piecewise()), 1.64294134724409; atol = 1e-5)\n    @test isapprox(fracint(sin, 0.5, 0.97, 1e-4, RL_Piecewise()), 0.6442601778843754; atol = 1e-5)\nend", "meta": {"hexsha": "eaf1da944239f8b6335657f59e0c6bf2dc159730", "size": 1097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Integral.jl", "max_stars_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "max_stars_repo_licenses": ["MIT"], "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/Integral.jl", "max_issues_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "max_issues_repo_licenses": ["MIT"], "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/Integral.jl", "max_forks_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.5294117647, "max_line_length": 111, "alphanum_fraction": 0.6608933455, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.761665836183339}}
{"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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing DataFrames\n\tusing HCubature\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.33\"\n\n# \u2554\u2550\u2561 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tM = 4.5\n\tmaxD = 10\nend\n\n# \u2554\u2550\u2561 dde25fec-228e-11eb-2ec8-099e48158d12\nf(x) = (2*pi)^(-length(x)/2) * exp(-(1/2)*x'x)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.33\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550dde25fec-228e-11eb-2ec8-099e48158d12\n# \u2560\u2550dde2935e-228e-11eb-3074-f3bddb5149fc\n# \u255f\u250070182cd8-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\u209b= 0\n    while abs(X) != round(Int,L/2)\n        X += sample([1,-1], Weights([P,1-P]))\n        T\u209b+= 1\n    end\n    return T\u209b\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": "using GrupoBeta\nusing Test\n\n@testset \"Algoritmo_QR\" begin\n  E = [1 1 1; 1 2 1; 1 1 3]\n  @test isapprox(autovalores(E), [4.214319 0.0 0.0; 0.0 1.460811 0.0; 0.0 0.0 0.324869], rtol = 1e-4) \n  @test isapprox(autovetores(E), [0.39711 0.23319 -0.88765; 0.52065 0.73923 0.42713; 0.75578 -0.63178 0.17214], rtol = 1e-4)\n  @test isapprox(iteracoes_QR(E), 24, rtol = 1e-1)\nend\n\n@testset \"Metodo_potencias\" begin\n  A = [1 2; 3 2]\n  @test isapprox(autovalor_dominante(A), 4, rtol = 1e-4) \n  @test isapprox(autovetor_dominante(A), [0.55470; 0.83204], rtol = 1e-4)\n  @test isapprox(iteracoes_potencias(A), 10, rtol = 1e-1)\nend ", "meta": {"hexsha": "63d169f630cba30d986774ccb4503765393934ae", "size": 615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "EleonoraAvello/GrupoBetaPacote", "max_stars_repo_head_hexsha": "a39e7a2606b0dc421d4c77670119bacfac729b8a", "max_stars_repo_licenses": ["MIT"], "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": "EleonoraAvello/GrupoBetaPacote", "max_issues_repo_head_hexsha": "a39e7a2606b0dc421d4c77670119bacfac729b8a", "max_issues_repo_licenses": ["MIT"], "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": "EleonoraAvello/GrupoBetaPacote", "max_forks_repo_head_hexsha": "a39e7a2606b0dc421d4c77670119bacfac729b8a", "max_forks_repo_licenses": ["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.4375, "max_line_length": 124, "alphanum_fraction": 0.6682926829, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7616087808179512}}
{"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 ``\u03ba`` up to order given by `max_order`\r\nin terms of raw moments ``\u03bc``. Return a Dictionary mapping from\r\nvector ``\\\\mathbf{i}`` (that indicates the cumulant ``\u03ba_{\\\\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) => \u03bc\u2081\u2080(t)\r\n  (2, 0) => \u03bc\u2082\u2080(t) - ((\u03bc\u2081\u2080(t))^2)\r\n  (0, 1) => \u03bc\u2080\u2081(t)\r\n  (0, 2) => \u03bc\u2080\u2082(t) - ((\u03bc\u2080\u2081(t))^2)\r\n  (1, 1) => \u03bc\u2081\u2081(t) - ((\u03bc\u2080\u2081(t))*(\u03bc\u2081\u2080(t)))\r\n```\r\n\"\"\"\r\nfunction cumulants_to_raw_moments(N::Int, max_order::Int, \u03bc=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 \u03bc == nothing\r\n        \u03bc = define_\u03bc(N, max_order, iter_all)\r\n    else\r\n        @assert (\u03bc isa Dict) && length(\u03bc) == length(iter_all) \"passed arguments are inconsistent (\u03bc vs N & order)\"\r\n    end\r\n\r\n    K = Dict()\r\n    \u03bc_star = Dict()\r\n\r\n    \u03bc_star[Tuple(fill(0, N))] = 1.0\r\n    for i in 1:N\r\n        e\u1d62 = iter_1[i]\r\n        K[e\u1d62] = \u03bc[e\u1d62]\r\n        \u03bc_star[e\u1d62] = -\u03bc[e\u1d62]\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*\u03bc[r.-i]*\u03bc_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])*\u03bc_star[i]\r\n            end\r\n            \u03bc_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 ``\u03ba`` 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 ``\u03ba_{\\\\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    \u03bc = define_\u03bc(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\u1d62 = iter_1[i]\r\n        K[e\u1d62] = \u03bc[e\u1d62]\r\n        M_star[e\u1d62] = 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 -= -\u03bc[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, \u03bc=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\u2081\u2082 = raw_to_central[(1,2)] = 2 \u03bc\u2081\u2080 \u03bc\u2080\u2081\u00b2 - 2\u03bc\u2081\u2081\u03bc\u2080\u2081 - \u03bc\u2080\u2082\u03bc\u2081\u2080 + \u03bc\u2081\u2082\r\n    # note that \u03bc is an optional argument which can be used to pass\r\n    # arbitrary values/symbols for each raw moment (different from default \u03bc\u1d62)\r\n\r\n    iter_all = construct_iter_all(N, order)\r\n    iter_\u03bc = filter(x -> sum(x) == 1, iter_all)\r\n    M = define_M(N, order, iter_all)\r\n    if \u03bc == nothing\r\n        \u03bc = define_\u03bc(N, order, iter_all)\r\n    elseif !(\u03bc isa Dict) || length(\u03bc) != length(iter_all)\r\n        if bernoulli\r\n            iter_all = keys(\u03bc)\r\n        else\r\n            error(\"passed arguments are inconsistent (\u03bc 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 = \u03bc[i.-j]\r\n            for (k, e_k) in zip(1:N, iter_\u03bc)\r\n                term *= (-1)^(j[k])*binomial(i[k], j[k])*\u03bc[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 \u03bc\u2081\u2082 = central_to_raw[(1,2)] = 2 M\u2081\u2081 \u03bc\u2080\u2081 + M\u2080\u2082\u03bc\u2081\u2080 + M\u2081\u2082 + \u03bc\u2081\u2080 \u03bc\u2080\u2081\u00b2\r\n\r\n    iter_all = construct_iter_all(N, order)\r\n    iter_\u03bc = filter(x -> sum(x) == 1, iter_all)\r\n\r\n    M = define_M(N, order, iter_all)\r\n    \u03bc = define_\u03bc(N, order, iter_\u03bc)\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_\u03bc)\r\n                term *= binomial(i[k], j[k])*\u03bc[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\u00e8 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": "using Primes, Printf\nfunction strfactor(n::Integer)\n    n > -2 || return \"-1 \u00d7 \" * strfactor(-n)\n    isprime(n) || n < 2 && return dec(n)\n    f = factor(Vector{typeof(n)}, n)\n    return join(f, \" \u00d7 \")\nend\n\nlo, hi = -4, 40\nprintln(\"Factor print $lo to $hi:\")\nfor n in lo:hi\n    @printf(\"%5d = %s\\n\", n, strfactor(n))\nend\n", "meta": {"hexsha": "0e80053ccbd55cbb62a118352b26fedd22f5d4a7", "size": 320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/count-in-factors.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/count-in-factors.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/count-in-factors.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.8571428571, "max_line_length": 44, "alphanum_fraction": 0.565625, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7615968666812961}}
{"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 \u21a6 0 if \u2016x\u2016_1 \u2a7d r, +\u221e 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 \u03bb\n    L = R(0)\n    U = maximum(abs, x)\n    \u03bb = L\n    v = R(0)\n    maxit = 120\n    for _ in 1:maxit\n        \u03bb = (L + U) / 2\n        v = sum(max.(abs.(x) .- \u03bb, R(0)))\n        # modify lower or upper bound\n        (v < f.r) ? U = \u03bb : L = \u03bb\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) .- \u03bb), 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    \u03b4 = [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 + \u03b4[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                   \u03b41    :: CartesianIndex{N},\n                   \u03b42    :: CartesianIndex{N}) where N\n    uidx = array |> CartesianIndices |> first |> oneunit\n\n    idx1 = uidx\n    idx2 = uidx + \u03b41\n    idx3 = uidx + \u03b42\n    idx4 = uidx + \u03b41 + \u03b42\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 \u2208 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) \u2265 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": "# Test using the Boston housing and neighborhood dataset\n@testset \"Bostonhsg\" begin\n    \n    boston = sdataset(\"Bostonhsg\")\n\n    # ----------------\n    #  Distance  with 3\n    # ----------------\n    Wdist3 = dnearneigh(boston, threshold = 3)\n\n    @test nobs(Wdist3) == 506\n    @test mean(Wdist3) \u2248 44.711462 atol = 1e-5\n    @test median(Wdist3) \u2248 29.0\n    @test minimum(Wdist3) == 0\n    @test maximum(Wdist3) == 122\n    @test nislands(Wdist3) == 4\n    @test islands(Wdist3) == [55, 65, 286, 287]\n\n    # Moran's I\n    mboston = moran(boston.MEDV, Wdist3, permutations = 0)\n\n    # ----------------\n    #  Distance  with 4\n    # ----------------\n    Wdist4 = dnearneigh(boston, threshold = 4)\n\n    @test nobs(Wdist4) == 506\n    @test mean(Wdist4) \u2248 72.225296 atol = 1e-5\n    @test median(Wdist4) \u2248 56.0\n    @test minimum(Wdist4) == 1\n    @test maximum(Wdist4) == 178\n    @test nislands(Wdist4) == 0\n    @test islands(Wdist4) == []\n\n    # Moran's I with 999 permutations\n    mboston = moran(boston.MEDV, Wdist4, rng = StableRNG(1234567), permutations = 999)\n\n    @test score(mboston) \u2248 0.267418 atol = 1e-5\n    @test pvalue(mboston) \u2248 0.001 atol = 1e-5\n    @test std(mboston) \u2248 0.013811 atol = 1e-5\n    @test zscore(mboston) \u2248 19.493602 atol = 1e-5\n\n    # ----------------\n    #  KNN with k = 10\n    # ----------------\n    Wknn10 = knearneigh(boston, k = 10)\n\n    @test nobs(Wknn10) == 506\n    @test mean(Wknn10) == 10\n    @test median(Wknn10) \u2248 10.0\n    @test minimum(Wknn10) == 10\n    @test maximum(Wknn10) == 10\n    @test nislands(Wknn10) == 0\n\n    # Moran I with 999 permutations\n    mboston = moran(boston.MEDV, Wknn10, rng = StableRNG(1234567), permutations = 999)\n\n    @test score(mboston) \u2248 0.530743 atol = 1e-5\n    @test std(mboston) \u2248 0.018956 atol = 1e-5\n    @test zscore(mboston) \u2248 28.080397 atol = 1e-5\n    @test pvalue(mboston) \u2248 0.001 atol = 1e-5\n\n    # Moran's I with 9999 permutations\n    mboston = moran(boston.MEDV, Wknn10, rng = StableRNG(1234567), permutations = 9999)\n\n    @test score(mboston) \u2248 0.530743 atol = 1e-5\n    @test std(mboston) \u2248 0.018541 atol = 1e-5\n    @test zscore(mboston) \u2248 28.727399 atol = 1e-5\n    @test pvalue(mboston) \u2248 0.0001 atol = 1e-5\n\n    # Geary's c I with 9999 permutations\n    cboston = geary(boston.MEDV, Wknn10, rng = StableRNG(1234567), permutations = 9999)\n\n    @test score(cboston) \u2248 0.432582 atol = 1e-5\n    @test std(cboston) \u2248 0.022467 atol = 1e-5\n    @test zscore(cboston) \u2248 -25.249835 atol = 1e-5\n    @test pvalue(cboston) \u2248 0.0001 atol = 1e-5\n\n    #\u00a0Local Moran\n    lmboston = localmoran(boston.MEDV, Wknn10, rng = StableRNG(1234567), permutations = 9999)\n\n    # ----------------\n    #  Plot Recipes\n    # ----------------\n\n    # Test Moran's I distribution\n    @test_nowarn RecipesBase.apply_recipe(Dict{Symbol, Any}(), mboston)\n\n    # Test Moran's Plot\n    @test_nowarn RecipesBase.apply_recipe(Dict{Symbol, Any}(), boston.MEDV, Wknn10)\n    @test_nowarn RecipesBase.apply_recipe(Dict{Symbol, Any}([(:standardize, false)]), boston.MEDV, Wknn10)\n\n    #\u00a0Test LISA Cluster Map with points\n    @test_nowarn RecipesBase.apply_recipe(Dict{Symbol, Any}(), boston, lmboston)\n    @test_nowarn RecipesBase.apply_recipe(Dict{Symbol, Any}(), boston.geometry, lmboston)\n\nend\n", "meta": {"hexsha": "a50b23baada7f49ddc7438ddb6a026b8625dbd53", "size": 3221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bostonhsg.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": "test/bostonhsg.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": "test/bostonhsg.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": 32.8673469388, "max_line_length": 106, "alphanum_fraction": 0.6131636138, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317888, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7615968612646281}}
{"text": "export chebygrid, ischebygrid, chebycoef, cheby, chebyderiv\nexport ChebyshevInterpolator, BichebyshevInterpolator\n\n\u03be2x(\u03be, a, b) = (\u03be + 1)*((b - a)/2) + a\n\nx2\u03be(x, a, b) = 2*(x - a)/(b - a) - 1\n\nx2\u03b8(x, a, b) = acos(x2\u03be(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.(\u03c0*(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) = \u03be2x.(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 \u2208 eachindex(x)\n        \u03be = x2\u03be(x[i], xa, xb)\n        #shift from [-1,1] to [1,3] to avoid issues comparing to zero\n        !isapprox(\u03be+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    \u03be = chebygrid(n)\n    for j \u2208 1:n, k \u2208 1:n\n        @inbounds A[j,k] = cos((k-1)*acos(\u03be[j]))\n    end\n    return A\nend\n\nfunction chebyrecurrance!(T, \u03be, L::Int)::Nothing\n    T\u2096\u208b\u2082 = one(\u03be)\n    T\u2096\u208b\u2081 = \u03be\n    @inbounds T[2] = T\u2096\u208b\u2081\n    for k = 3:L\n        #compute next value\n        T\u2096 = 2\u03be*T\u2096\u208b\u2081 - T\u2096\u208b\u2082\n        #set array value\n        @inbounds T[k] = T\u2096\n        #swaps\n        T\u2096\u208b\u2082 = T\u2096\u208b\u2081\n        T\u2096\u208b\u2081 = T\u2096\n    end\n    nothing\nend\n\nfunction chebyrecurrance(\u03be::U, L::Int) where {U}\n    T = Vector{U}(undef, L)\n    @inbounds T[1] = one(\u03be)\n    chebyrecurrance!(T, \u03be, 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\u1d35 = invertedchebymatrix(n)\n    return A\u1d35*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 \u03be space\n    \u03be = x2\u03be(x, xa, xb)\n    #first two elements of cheby recursion\n    T\u2096\u208b\u2082 = one(\u03be)\n    T\u2096\u208b\u2081 = \u03be\n    #first two terms of dot product\n    @inbounds y = T\u2096\u208b\u2082*coef[1] + T\u2096\u208b\u2081*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\u2096 = 2*\u03be*T\u2096\u208b\u2081 - T\u2096\u208b\u2082\n        #next term in dot product\n        @inbounds y += T\u2096*coef[k]\n        #swaps\n        T\u2096\u208b\u2082 = T\u2096\u208b\u2081\n        T\u2096\u208b\u2081 = T\u2096\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 \u2208 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, \u03d5::ChebyshevInterpolator)\n    print(io, \"$(typeof(\u03d5)) \u2208 [$(\u03d5.xa), $(\u03d5.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 (\u03d5::ChebyshevInterpolator{N,U})(x) where {N,U}\n    #always enforce boundaries\n    \u03d5.boundaries(x, \u03d5.xa, \u03d5.xb)\n    #evaluate the expansion\n    return cheby(\u03d5.a, x, \u03d5.xa, \u03d5.xb)\nend\n\n\"\"\"\n    chebyderiv(\u03d5::ChebyshevInterpolator)\n\nConstruct a ChebyshevInterpolator representing the derivative of a preexisting interpolator.\n\"\"\"\nfunction chebyderiv(\u03d5::ChebyshevInterpolator)\n    #derivative expansion's coefficients\n    coef = Tuple(chebyderiv(\u03d5.a, \u03d5.xa, \u03d5.xb))\n    #new interpolator\n    ChebyshevInterpolator(\u03d5.xa, \u03d5.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 \u03b8y\n    b::Vector{U} # length nx for cosine expansion in \u03b8x\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, \u03d5::BichebyshevInterpolator)\n    print(io, \"$(typeof(\u03d5)) \u2208 [$(\u03d5.xa), $(\u03d5.xb)], [$(\u03d5.ya), $(\u03d5.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    \u03b1 = zeros(T, nx, ny)\n    for j = 1:ny\n        mul!(view(\u03b1,:,j), B, view(Z,:,j))\n    end\n    #then combine \u03b1 and A\n    A = invertedchebymatrix(ny)*\u03b1'\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 (\u03a6::BichebyshevInterpolator{M,N,U})(x::U, y::U) where {M,N,U<:AbstractFloat}\n    #always enforce boundaries for Chebyshev\n    \u03a6.boundaries(x, \u03a6.xa, \u03a6.xb, y, \u03a6.ya, \u03a6.yb)\n    #evaluate Chebyshev polys at the coordinates recursively and in-place\n    \u03bey = x2\u03be(y, \u03a6.ya, \u03a6.yb)\n    chebyrecurrance!(\u03a6.a, \u03bey, M)\n    \u03bex = x2\u03be(x, \u03a6.xa, \u03a6.xb)\n    chebyrecurrance!(\u03a6.b, \u03bex, N)\n    #perform M*b, which interpolates along the first axis, also in-place\n    mul!(\u03a6.c, \u03a6.A, \u03a6.b)\n    #then a'*c interpolates along the second axis\n    return dot(\u03a6.a, \u03a6.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 \ud83d\ude2d.\n=====#\nfunction (\u03a6::BichebyshevInterpolator{M,N,U})(x, y) where {M,N,U}\n    #always enforce boundaries for Chebyshev\n    \u03a6.boundaries(x, \u03a6.xa, \u03a6.xb, y, \u03a6.ya, \u03a6.yb)\n    #coordinates in \u03be space\n    \u03bex, \u03bey = promote(x2\u03be(x, \u03a6.xa, \u03a6.xb), x2\u03be(y, \u03a6.ya, \u03a6.yb))\n    #allocating expansion in the x direction\n    b = chebyrecurrance(\u03bex, N)\n    c = \u03a6.A * b\n    #then perform the y-axis expansion and dot product simulataneously    \n    T\u2096\u208b\u2082 = one(\u03bey)\n    T\u2096\u208b\u2081 = \u03bey\n    @inbounds z = c[1] + \u03bey*c[2]\n    for i = 3:M\n        #compute next value\n        T\u2096 = 2\u03bey*T\u2096\u208b\u2081 - T\u2096\u208b\u2082\n        #update running dot product\n        @inbounds z += c[i]*T\u2096\n        #swaps\n        T\u2096\u208b\u2082 = T\u2096\u208b\u2081\n        T\u2096\u208b\u2081 = T\u2096\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": "@testset \"softmax\" begin\n    X = rand(100,5)\n    max_ = maximum(X, dims=2)\n    exp_ = exp.(X .- max_)\n    @test isapprox(MLJMultivariateStatsInterface.softmax(X), exp_ ./ sum(exp_, dims=2))\n    X_ = MLJMultivariateStatsInterface.softmax!(X)\n    @test X_ === X\n    @test isapprox(X_, exp_ ./ sum(exp_, dims=2))     \nend\n\n", "meta": {"hexsha": "37e30a89633c64d0550f2c89b1854fb6fc5b0c7e", "size": 320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 29.0909090909, "max_line_length": 87, "alphanum_fraction": 0.628125, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422241476944, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7615719672071999}}
{"text": "using MCObservables\n\nfunction test_simpleObservable(numtest, MCS)\n  inform(\"Start testing SimpleObservable\")\n\n  nsigma = 3\n\n  counts = zeros(Int, nsigma)\n\n  for i in 1:numtest\n    obs = SimpleObservable()\n    for j in 1:MCS\n      obs << randn()\n    end\n    m = abs(mean(obs))\n    er = stderror(obs)\n    for isigma in 1:nsigma\n      if m < isigma*er\n        counts[isigma] += 1\n      end\n    end\n  end\n  sigma = counts ./ numtest\n  @show sigma\n\n  @test 0.68 < sigma[1] < 0.69\n  @test 0.95 < sigma[2] < 0.96\n  @test 0.99 < sigma[3]\n  inform(\"Success testing SimpleObservable\")\nend\n\n\nresult_simpleObservable = test_simpleObservable(100_000, 8192)\n", "meta": {"hexsha": "0a10a8f07c0a1bc13890b8cd40a6622d8ca3ec2d", "size": 644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SimpleObservable.jl", "max_stars_repo_name": "JuliaTagBot/MCObservables.jl", "max_stars_repo_head_hexsha": "4f80e251915485ee6589c2d060482e1a3446d884", "max_stars_repo_licenses": ["MIT"], "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/SimpleObservable.jl", "max_issues_repo_name": "JuliaTagBot/MCObservables.jl", "max_issues_repo_head_hexsha": "4f80e251915485ee6589c2d060482e1a3446d884", "max_issues_repo_licenses": ["MIT"], "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/SimpleObservable.jl", "max_forks_repo_name": "JuliaTagBot/MCObservables.jl", "max_forks_repo_head_hexsha": "4f80e251915485ee6589c2d060482e1a3446d884", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:53:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:53:47.000Z", "avg_line_length": 18.9411764706, "max_line_length": 62, "alphanum_fraction": 0.6413043478, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7615719638364853}}
{"text": "using Test\nusing Mods\n\np = 23\n@test Mod(2,p) == Mod(25,p)\n@test Mod(2,p)+Mod(21,p) == Mod(0,p)\n@test Mod(10,p)*Mod(5,p) == Mod(4,p)\n@test Mod(10,p)/Mod(5,p) == Mod(2,p)\n@test Mod(17,p) * inv(Mod(17,p)) == Mod(1,p)\n@test Mod(17^6,p)==Mod(17,p)^6\n@test Mod(17,p)^(-2) == inv(Mod(17,p))^2\n@test Mod(17,p) == 17\n\nq = 91\na = Mod(17,p)\nb = Mod(32,q)\n\nx = CRT(a,b)\n@test Mod(x.val,p)==a\n@test Mod(x.val,q)==b\n@test inv(a)*a == 1\n\np = 9223372036854775783   # This is a big prime\nx = Mod(-2,p)\n@test x*x == 4\n@test x+x == -4\n@test x/x == 1\n@test x^4 == 16\n@test x^(p-1) == 1   # Fermat Little Theorem test\n@test 2x == x+x\n@test x-x == 0\ny = inv(x)\n@test x*y == 1\n@test x+p == x\n@test x*p == 0\n@test p-x == x-2x\n", "meta": {"hexsha": "18390c5deb90e774b18672d52efdbfdc763bf0a0", "size": 702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Mods.jl-7475f97c-0381-53b1-977b-4c60186c8d62", "max_stars_repo_head_hexsha": "7548a312126df0fbfbe80190e8236bea0270e1df", "max_stars_repo_licenses": ["MIT"], "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/Mods.jl-7475f97c-0381-53b1-977b-4c60186c8d62", "max_issues_repo_head_hexsha": "7548a312126df0fbfbe80190e8236bea0270e1df", "max_issues_repo_licenses": ["MIT"], "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/Mods.jl-7475f97c-0381-53b1-977b-4c60186c8d62", "max_forks_repo_head_hexsha": "7548a312126df0fbfbe80190e8236bea0270e1df", "max_forks_repo_licenses": ["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.972972973, "max_line_length": 49, "alphanum_fraction": 0.5427350427, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7615719627715754}}
{"text": "@testset \"Matrix multiplication\" begin\n\n    # test default settings\n    @test get_multiplication_mode() == Dict(:multiplication => :fast)\n\n    A = [2..4 -2..1; -1..2 2..4]\n    set_multiplication_mode(:slow)\n    @test A * A == [0..18 -16..8; -8..16 0..18]\n\n    set_multiplication_mode(:rank1)\n    @test A * A == [0..18 -16..8; -8..16 0..18]\n\n    set_multiplication_mode(:fast)\n    @test A * A == [-2..19.5 -16..10; -10..16 -2..19.5]\n    @test A * mid.(A) == [5..12.5 -8..2; -2..8 5..12.5]\n    @test mid.(A) * A == [5..12.5 -8..2; -2..8 5..12.5]\nend\n", "meta": {"hexsha": "d7c9b9eeb6a18e5b34f33bda26e04decaf89f38f", "size": 548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_multiplication.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": "test/test_multiplication.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": "test/test_multiplication.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": 30.4444444444, "max_line_length": 69, "alphanum_fraction": 0.5364963504, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7615719594008609}}
{"text": "function lgd20()\n#\n#  test polynomial suggested by Goedecker\n#   Legendre polynomial of degree 20\n#\n    p = lgd(20);\n    z = [-.9931285991850949; -.9639719272779138; -.9122344282513259; -.8391169718222188;\n         -.7463319064601508; -.6360536807265150; -.5108670019508271; -.3737060887154196;\n         -.2277858511416451; -.7652652113349733e-1; .7652652113349733e-1; .2277858511416451;\n         .3737060887154196; .5108670019508271; .6360536807265150; .7463319064601508;\n         .8391169718222188; .9122344282513259; .9639719272779138; .9931285991850949]\n    z = [z ones(20)]\n\n    p, PolyZeros(z)\nend\n", "meta": {"hexsha": "a1b637c704361e80e95620d11829d8e91b9579d1", "size": 604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsuit/lgd20.m.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": "test/testsuit/lgd20.m.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": "test/testsuit/lgd20.m.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": 37.75, "max_line_length": 92, "alphanum_fraction": 0.7086092715, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7615580283709035}}
{"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\u2013Warshall_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": "function run_gradient_descent_iterations(func, grad, x0, lr, numiter; rtol = 1e5)\r\n    xprev = copy(x0)\r\n    xnext = copy(x0)\r\n\r\n    g = grad(xprev)\r\n    gnorm = g'*g\r\n    iter = 1\r\n    tol = rtol*eps()\r\n\r\n    while gnorm > tol && iter < numiter\r\n        f = func(xprev)\r\n        g = grad(xprev)\r\n        gnorm = g'*g\r\n\r\n        xnext .= xprev - lr * (f / gnorm) * g\r\n        xprev .= xnext\r\n\r\n        iter += 1\r\n    end\r\n    return xnext\r\nend\r\n", "meta": {"hexsha": "672634b48ddd9a3e197c0433f93f7022e0436f59", "size": 445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gradient_descent.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": "gradient_descent.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": "gradient_descent.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": 20.2272727273, "max_line_length": 82, "alphanum_fraction": 0.4966292135, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7615580125347093}}
{"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 \u2264 1.0\n            hits += 1\n        end\n    end\n    return 4hits/n\nend\n\nestimatepi2(n) = 4count(x-> x \u2264 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": "using PlasmaDispersionFunctions\nusing ArbNumerics, QuadGK, Random, SpecialFunctions, Test\n\nimport SpecialFunctions.erfcx\nerfcx(x::Complex{BigFloat}) = erfcx(ArbComplex(x))\n\n@testset \"Tests\" begin\nRandom.seed!(0)\n\n@testset \"Plasma dispersion function\" begin\n  @test plasma_dispersion_function(0.0) \u2248 im*sqrt(pi) rtol=1e-5\n  @test plasma_dispersion_function(im) \u2248 im*0.757872156141312 rtol=1e-5\n  @test plasma_dispersion_function(ComplexF64(-1.52, 0.47), 0) \u2248\n    ComplexF64(0.6088888957234254, 0.33494583882874024) rtol=1e-5\n  @test plasma_dispersion_function(big(0.0+0im)) \u2248\n    ArbComplex(im*sqrt(pi)) rtol=1e-5\nend\n\n@testset \"using Z\u208b\u2081\" begin\n  Z0 = plasma_dispersion_function(0.0, 0)\n  Z1 = plasma_dispersion_function(0.0, 1)\n  @test Z1 == plasma_dispersion_function(0.0, 1, Z0)\n  Z2 = plasma_dispersion_function(0.0, 2)\n  @test Z2 == plasma_dispersion_function(0.0, 2, Z1)\nend\n\n@testset \"vs quadrature\" begin\n  function test_quad(Z, pow)\n    for z in Z\n      principal(x) = x.^pow .* exp(-x.^2)/sqrt(pi)\n      integrand(x) = principal(x) / (x-z)\n      principalpart = if iszero(imag(z))\n        folded(v) = (principal(v + real(z)) - principal(-v + real(z))) / v\n        QuadGK.quadgk(folded, nextfloat(0.0), Inf, rtol=eps())[1]\n      else\n        QuadGK.quadgk(integrand, -Inf, Inf, rtol=eps())[1]\n      end\n      \u03c3 = imag(z) < 0 ? 2 : imag(z) == 0 ? 1 : 0\n      cauchyresidue = im * (\u03c3 * \u03c0 * principal(z))\n      b = plasma_dispersion_function(z, pow)\n      a = principalpart + cauchyresidue\n      @test real(a) \u2248 real(b) rtol=sqrt(eps()) atol=0.0\n      @test imag(a) \u2248 imag(b) rtol=sqrt(eps()) atol=0.0\n    end\n  end\n  Zs = []\n  push!(Zs,  1.0)\n  push!(Zs, -1.0)\n  push!(Zs,  1.0 + im)\n  push!(Zs, -1.0 + im)\n  push!(Zs,  1.0 - im)\n  push!(Zs, -1.0 - im)\n  for j in 1:10\n    push!(Zs, 4 * (rand() - 0.5) + im * 4 * (rand() - 0.5))\n  end\n  for i in Unsigned.(0:10)\n    @testset \"QuadGK of maxwellian with $(i)th moment\" begin\n      test_quad(Zs, i)\n    end\n  end\nend\n\n@testset \"check errors are caught\" begin\n  @test_throws ArgumentError plasma_dispersion_function(1.0, -1)\nend\n\nend\n", "meta": {"hexsha": "8bbac1a8ce2221af501962c923b55cf58dd6d368", "size": 2087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jwscook/PlasmaDispersionFunctions.jl", "max_stars_repo_head_hexsha": "faaa18f400d244a487f5ebb33e00b6b78d6e8d41", "max_stars_repo_licenses": ["MIT"], "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": "jwscook/PlasmaDispersionFunctions.jl", "max_issues_repo_head_hexsha": "faaa18f400d244a487f5ebb33e00b6b78d6e8d41", "max_issues_repo_licenses": ["MIT"], "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": "jwscook/PlasmaDispersionFunctions.jl", "max_forks_repo_head_hexsha": "faaa18f400d244a487f5ebb33e00b6b78d6e8d41", "max_forks_repo_licenses": ["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.6911764706, "max_line_length": 74, "alphanum_fraction": 0.6430282702, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7615399681289945}}
{"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 -\u221e.\n\n# References\n1. Mathevet, T., Michel, C., Andr\u00e9assian, 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\u2013219.\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 -\u221e.\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\u2019 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 -\u221e.\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\u2013runoff\n        models for low-flow index simulations?\n    Hydrological Sciences Journal 62, 1149\u20131166.\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, \u03f5=1e-2)\n    obj, o, s, \u03f5 = eval(metric), eval(obs), eval(sim), eval(\u03f5)\n    q = obj(o, s)\n    q2 = obj(1.0 ./ (o .+ \u03f5), 1.0 ./ (s .+ \u03f5))\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\u20133408.\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\u2019 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\u2013900.\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\u2013900.\n    https://doi.org/10.13031/2013.23153\n\"\"\"\nfunction RSR(obs, sim)::Float64\n    rmse = RMSE(obs, sim)\n    \u03c3_obs = std(obs)\n    rsr = rmse / \u03c3_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 -\u221e.\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\u2013728.\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 (`\u03b1`), and bias (`\u03b2`) 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`, `\u03b1` and `\u03b2` 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\u201391.\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 \u201chigh-flow\u201d\n        estimation using hydrologic models.\n    Hydrology and Earth System Sciences 23, 2601\u20132614.\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    \u03b1 = std(sim) / std(obs)\n\n    # bias\n    \u03b2 = 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*(\u03b1 - 1)^2 + bs*(\u03b2 - 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 (\u212f\u207b\u02e3) 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 (\u03b2), variability (\u03b3).\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\u2013425, 264\u2013277.\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\u20134591.\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        \u03b3 = 1.0\n    elseif cv_o == 0.0\n        # Use logistic function to indicate distance from 0\n        \u03b3 = 1.0 / exp(cv_s)\n    else\n        \u03b3 = cv_s / cv_o\n    end\n\n    # Magnitude\n    \u03bc_o = mean(obs)\n    \u03bc_s = mean(sim)\n    if \u03bc_o == 0.0\n        # use logistic function to indicate distance from 0 (\u03bc_o)\n        \u03b2 = 1.0 / exp(\u03bc_s)\n    else\n        \u03b2 = \u03bc_s / \u03bc_o\n    end\n\n    rs = scaling[1]\n    \u03b2s = scaling[2]\n    \u03b3s = scaling[3]\n\n    mod_kge = 1.0 - sqrt(rs*(r - 1)^2 + \u03b2s*(\u03b2 - 1)^2 + \u03b3s*(\u03b3 - 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, \u03b1, and \u03b2 (defaults to 1.0)\n- `\u03f5::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\u2013runoff\n        models for low-flow index simulations?\n    Hydrological Sciences Journal 62, 1149\u20131166.\n    https://doi.org/10.1080/02626667.2017.1308511\n\"\"\"\nmean_NmKGE(obs, sim; scaling=nothing, \u03f5=1e-2) = mean([Streamfall.NmKGE(obs, sim; scaling=scaling), Streamfall.NmKGE(1.0 ./ (obs .+ \u03f5), 1.0 ./ (sim .+ \u03f5); 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 (\u03b1), magnitude (\u03b2)\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\u20131953.\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    \u03bc_s = mean(sim)\n    if \u03bc_s == 0.0\n        fdc_sim = repeat([0.0], length(sim))\n    else\n        x = length(sim) * \u03bc_s\n        fdc_sim = sort(sim / x)\n    end\n\n    \u03bc_o = mean(obs)\n    if \u03bc_o == 0.0\n        fdc_obs = repeat([0.0], length(obs))\n    else\n        x = length(obs) * \u03bc_o\n        fdc_obs = sort(obs / x)\n    end\n\n    \u03b1 = 1 - 0.5 * sum(abs.(fdc_sim - fdc_obs))\n\n    # Magnitude\n    if \u03bc_o == 0.0\n        \u03b2 = \u03bc_s == 0.0 ? 1.0 : \u03bc_s\n    else\n        \u03b2 = \u03bc_s / \u03bc_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    \u03b1s = scaling[2]\n    \u03b2s = scaling[3]\n\n    kge = 1 - sqrt(rs*(r - 1)^2 + \u03b1s*(\u03b1 - 1)^2 + \u03b2s*(\u03b2 - 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    \u03bc_o = mean(obs)\n    \u03bc_s = mean(sim)\n    \u03b2 = (\u03bc_s / \u03bc_o)\n\n    r = Statistics.cor(obs, sim)\n    \u03c3_s = std(sim)\n    \u03c3_o = std(obs)\n    \u03b1 = (\u03c3_s / \u03c3_o)\n    k_1 = r * \u03b1\n\n    LME = 1 - sqrt((k_1 - 1)^2 + (\u03b2 - 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\u20133408.\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- \u03f5 : 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\u2013runoff models\n        for low-flow index simulations?\n    Hydrological Sciences Journal 62, 1149\u20131166.\n    https://doi.org/10.1080/02626667.2017.1308511\n\"\"\"\nfunction inverse_metric(obs, sim, metric::Function; comb_method::Function=mean, \u03f5=1e-2)\n    return comb_method([metric(obs, sim), metric(1.0 ./ (obs .+ \u03f5), 1.0 ./ (sim .+ \u03f5))])\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\u20133080. \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": "mutable struct OptimizationParameters\n    d::Int # dimension of embedding\n    # main optimization parameters\n    max_iter::Int\n    lr::Real\n    beta_1::Real\n    beta_2::Real\n    weight_decay::Real\n    eps::Real # adding to denominator of ADAM rescaling\n    # early optimization parameters\n    early_iter::Int\n    early_lr::Real\n    early_beta_1::Real\n    early_beta_2::Real\n    early_compression::Real\n    early_exaggeration::Real\n    # boolean flags\n    dofast::Bool\n    debias::Bool\n    verbose::Bool\nend\n\nfunction OptimizationParameters(; d::Int = 2, max_iter::Int = 1024, lr::Real = 1,\n            beta_1::Real = .9, beta_2::Real = .999, weight_decay::Real = 0,\n            early_iter::Int = 64, early_lr::Real = lr, early_beta_1::Real = 0.5,\n            early_beta_2::Real = 0.9, early_compression::Real = 1,\n            early_exaggeration::Real = 12, eps::Real = 1e-8, verbose::Bool = false,\n            debias::Bool = true, dofast::Bool = size(X, 2) \u2265 fast_algorithm_min_size)\n    early_exaggeration \u2265 1 || throw(DomainMismatch(\"early_exaggeration < 1\"))\n    OptimizationParameters(d, max_iter, lr, beta_1, beta_2, weight_decay, eps,\n                early_iter, early_lr, early_beta_1, early_beta_2, early_compression,\n                early_exaggeration, dofast, debias, verbose)\nend\n", "meta": {"hexsha": "ee2a6b3236cb23be303ed4b5ece1d391bafb3366", "size": 1291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parameters.jl", "max_stars_repo_name": "SebastianAment/StochasticNeighborhoodEmbeddings.jl", "max_stars_repo_head_hexsha": "7a5e75ad3966b1c951797b21e9f2f5758755d6d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-09T21:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T21:11:33.000Z", "max_issues_repo_path": "src/parameters.jl", "max_issues_repo_name": "SebastianAment/StochasticNeighborhoodEmbeddings.jl", "max_issues_repo_head_hexsha": "7a5e75ad3966b1c951797b21e9f2f5758755d6d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-07T09:33:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T09:37:13.000Z", "max_forks_repo_path": "src/parameters.jl", "max_forks_repo_name": "SebastianAment/StochasticNeighborhoodEmbeddings.jl", "max_forks_repo_head_hexsha": "7a5e75ad3966b1c951797b21e9f2f5758755d6d0", "max_forks_repo_licenses": ["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.9705882353, "max_line_length": 85, "alphanum_fraction": 0.6630518978, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7614181421585756}}
{"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    \u03bb::U\n    \u03bd::U\n    R::T\nend\n\nfunction SR3(\u03bb = 1e-1, \u03bd = 1.0)\n    R = NormL1\n    return SR3(\u03bb, \u03bd, R)\nend\n\nfunction set_threshold!(opt::SR3, threshold)\n    opt.\u03bb = threshold^2*opt.\u03bd /2\n    return\nend\n\nget_threshold(opt::SR3) = sqrt(2*opt.\u03bb/opt.\u03bd)\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.\u03bd))\n    X\u0302 = A'*Y\n    for i in 1:maxiter\n        # Solve rigde regression\n        X .= P*(X\u0302+W/(opt.\u03bd))\n        # Add proximal iteration\n        prox!(W, f, X, opt.\u03bd*opt.\u03bb)\n    end\n\n    # This is the effective threshold of the SR3 algorithm\n    # See Unified Framework paper supplementary material S1\n    #\u03b7 = sqrt(2*opt.\u03bb*opt.\u03bd)\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\u03bc0 = randn()\n\u03c30 = rand() + 1\n@info \"Starting guess, mean: $\u03bc0, std: $\u03c30\"\n@variable(mle, \u03bc, start = \u03bc0)\n@variable(mle, \u03c3 >= 0.0, start = \u03c30)\n@NLexpression(mle, loglikelihood,\n    -(n / 2) * (log(2\u03c0) + 2 * log(\u03c3)) - inv(2 * \u03c3^2) * sum((xi - \u03bc)^2 for xi in problem_data)\n)\n\n@NLobjective(mle, Max, loglikelihood)\n\noptimize!(mle)\n\nprintln(\"\u03bc = \", value(\u03bc))\nprintln(\"mean(data) = \", mean(data))\nprintln(\"\u03c3^2 = \", value(\u03c3)^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(\"\u03bc = \", value(\u03bc))\nprintln(\"mean(data) = \", mean(data))\nprintln(\"\u03c3^2 = \", value(\u03c3)^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 \u2202x!(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 \u2208 1:n, i \u2208 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 \u2202y!(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 \u2208 1:n, i \u2208 1:m\n            dudy[i,j] = u[i,j+1] - u[i,j]\n    end\nend\n\n\"\"\" \u2207\u00b2 is the 2nd order centred Laplace-operator \u2202/\u2202x^2 + \u2202/\u2202y^2.\nThe 1/\u0394\u00b2-factor is omitted and moved into the viscosity coefficient.\"\"\"\nfunction \u2207\u00b2!(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 \u2208 1:n\n        for i \u2208 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\"\"\"\u2202x is the 2nd order centred Gradient-operator \u2202/\u2202x with grid spacing \u0394 (default 1).\"\"\"\nfunction \u2202x(u::Array{T,2},\u0394x::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/\u0394x)\n\n\n    @inbounds for j \u2208 1:n\n        for i \u2208 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\"\"\"\u2202y is the 2nd order centred Gradient-operator \u2202/\u2202y with grid spacing \u0394 (default 1).\"\"\"\nfunction \u2202y(u::Array{T,2},\u0394y::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/\u0394y)\n\n    @inbounds for j \u2208 1:n-1\n        for i \u2208 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\"\"\" \u2207\u00b2 is the 2nd order centred Laplace-operator \u2202/\u2202x^2 + \u2202/\u2202y^2 with grid spacing \u0394 (default 1).\"\"\"\nfunction \u2207\u00b2(u::Array{T,2},\u0394::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\u00b2 = T(1/\u0394^2)\n\n    @inbounds for j \u2208 2:n-1\n        for i \u2208 2:m-1\n            du[i-1,j-1] = one_over_dx\u00b2*(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# \u2554\u2550\u2561 d1f4afa8-2501-4447-96a6-7fb93f463e2c\nusing IterativeSolvers, DataFrames\n\n# \u2554\u2550\u2561 57c64cca-55ee-4c2b-ad27-2942a262df7b\nmd\" ### Ex-02-08.jl\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 21a0af0a-7873-45f5-bd59-31c43cbb0f0c\nmd\" ##### Jacobi method:\"\n\n# \u2554\u2550\u2561 137e76a3-ea70-49e0-a1f7-a2eadaac9963\nx_j = [(i=i, j=jacobi(A, a; maxiter=i)) for i in r]\n\n# \u2554\u2550\u2561 31d9aa57-e96b-409b-b1ab-9e5966af6bf5\nx_j[1]\n\n# \u2554\u2550\u2561 70d35d30-1798-4982-9b9e-3812a575d179\nA * x_j[11].j\n\n# \u2554\u2550\u2561 954c3dec-86ad-4a29-9528-a790a9ebf2c0\nmd\" ##### Gauss-Seidel method:\"\n\n# \u2554\u2550\u2561 53491c26-f5d1-48d0-a795-7c20a31b00df\nx_gs = [(i=i, gs=gauss_seidel(A, a; maxiter=i)) for i in r]\n\n# \u2554\u2550\u2561 b2a3e4de-cd59-466a-9872-f72e78bb91ba\nA * x_gs[11].gs\n\n# \u2554\u2550\u2561 df81e70f-ec63-4be6-8517-d962b315dc0f\nmd\" ##### Succesive Over-Relaxation method:\"\n\n# \u2554\u2550\u2561 cebd114d-8a7c-44c0-bbca-e39b124a263e\nx_sor = [(i=i, sor=sor(A, a, 1.0; maxiter=i)) for i in r]\n\n# \u2554\u2550\u2561 9b86fca1-6867-4c70-b7a2-6e648bbfc26e\nA * x_sor[11].sor\n\n# \u2554\u2550\u2561 c1dd5a8b-5256-410f-9abc-58afd36cb1af\nmd\" ##### Sequential Succesive Over-Relaxation method:\"\n\n# \u2554\u2550\u2561 09fd7541-fe59-435b-8f6d-73b72b0c01f0\nx_ssor = [(i=i, ssor=ssor(A, a, 1.0; maxiter=i)) for i in r]\n\n# \u2554\u2550\u2561 96d4ef12-7a35-47c5-a255-5056e582e618\nA * x_ssor[11].ssor\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u250057c64cca-55ee-4c2b-ad27-2942a262df7b\n# \u2560\u2550d1f4afa8-2501-4447-96a6-7fb93f463e2c\n# \u2560\u2550c7b3e4fb-8f17-4e0e-82a5-18d30f8b198a\n# \u255f\u250021a0af0a-7873-45f5-bd59-31c43cbb0f0c\n# \u2560\u2550137e76a3-ea70-49e0-a1f7-a2eadaac9963\n# \u2560\u255031d9aa57-e96b-409b-b1ab-9e5966af6bf5\n# \u2560\u255070d35d30-1798-4982-9b9e-3812a575d179\n# \u255f\u2500954c3dec-86ad-4a29-9528-a790a9ebf2c0\n# \u2560\u255053491c26-f5d1-48d0-a795-7c20a31b00df\n# \u2560\u2550b2a3e4de-cd59-466a-9872-f72e78bb91ba\n# \u255f\u2500df81e70f-ec63-4be6-8517-d962b315dc0f\n# \u2560\u2550cebd114d-8a7c-44c0-bbca-e39b124a263e\n# \u2560\u25509b86fca1-6867-4c70-b7a2-6e648bbfc26e\n# \u255f\u2500c1dd5a8b-5256-410f-9abc-58afd36cb1af\n# \u2560\u255009fd7541-fe59-435b-8f6d-73b72b0c01f0\n# \u2560\u255096d4ef12-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' = \u03bb y\n\nprintln('\\n', \" \"^4, \"> Loading the packages...\")\n\nusing Printf\n\n# Define the value of \u03bb\nconst \u03bb = -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\u2080::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\u2080\n    # Compute the solution\n    for _ in 1:n\n        y += h * \u03bb * y\n    end\n    return y\nend\n\n# Integrate the test equation using the\n# two-step Adams\u2013Bashforth's method, return\n# the value of the solution at the last step\nfunction ab2(\n    y\u2080::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\u2080\n    # Prepare a buffer for previous values\n    y\u2096\u208b\u2081 = y\u2080\n    # Compute the second value of the solution\n    # using the one-step Euler's method\n    y = euler(y\u2080, h, UInt(1))\n    # Compute the rest in two steps\n    for _ in 2:n\n        k = y\n        y += h * \u03bb * (3 / 2 * y - 1 / 2 * y\u2096\u208b\u2081)\n        y\u2096\u208b\u2081 = 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\u2080::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\u2080\n    # Compute the rest in two steps\n    for _ in 1:n\n        k\u2081 = \u03bb * y\n        k\u2082 = \u03bb * (y + h * k\u2081 / 2)\n        k\u2083 = \u03bb * (y + h * k\u2082 / 2)\n        k\u2084 = \u03bb * (y + h * k\u2083)\n        y += h / 6 * (k\u2081 + 2 * k\u2082 + 2 * k\u2083 + k\u2084)\n    end\n    return y\nend\n\n# Integrate the test equation using the\n# three-step Adams\u2013Bashforth'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\u2080::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\u2080\n    # Prepare buffers for previous values\n    y\u2096\u208b\u2081 = y\u2080\n    y\u2096\u208b\u2082 = y\u2080\n    # Compute the second value of the solution\n    # using the one-step Euler's method\n    y = euler(y\u2080, h, UInt(1))\n    # Compute the third value of the solution\n    # using the two-step Adams\u2013Bashforth's method\n    y\u2096\u208b\u2081 = y\n    y = ab2(y\u2080, h, UInt(2))\n    # Compute the rest in two steps\n    for _ in 3:n\n        k = y\n        y += h * \u03bb * (23 / 12 * y - 4 / 3 * y\u2096\u208b\u2081 + 5 / 12 * y\u2096\u208b\u2082)\n        y\u2096\u208b\u2082 = y\u2096\u208b\u2081\n        y\u2096\u208b\u2081 = k\n    end\n    return y\nend\n\n# Integrate the test equation using the\n# three-step Adams\u2013Bashforth'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\u2080::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\u2080\n    # Prepare buffers for previous values\n    y\u2096\u208b\u2081 = y\u2080\n    y\u2096\u208b\u2082 = y\u2080\n    # Compute the second and third values of the solution\n    # using the 4th-order Runge-Kutta's method\n    y\u2096\u208b\u2081 = rk4(y\u2080, h, UInt(1))\n    y = rk4(y\u2080, h, UInt(2))\n    # Compute the rest in two steps\n    for _ in 3:n\n        k = y\n        y += h * \u03bb * (23 / 12 * y - 4 / 3 * y\u2096\u208b\u2081 + 5 / 12 * y\u2096\u208b\u2082)\n        y\u2096\u208b\u2082 = y\u2096\u208b\u2081\n        y\u2096\u208b\u2081 = 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\u2080 = 1.0\n\n# Calculate the analytical solution\ny\u2090 = \u212f^\u03bb\n\n# Print the initial values\nprintln(\n    '\\n',\n    \" \"^6, \"y\u2080: \", y\u2080,\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    \u0394y = [ 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\u1d62 = methods[j](y\u2080, h[i], n[i])\n            \u0394y\u1d62 = abs(y\u2090 - y\u1d62)\n            push!(y[j], y\u1d62)\n            push!(\u0394y[j], \u0394y\u1d62)\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], \u0394y[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": "@testset \"Gauss\u2013Lobatto\" begin\n    # Check error\n    @test_throws DomainError gausslobatto(-1)\n    @test_throws DomainError gausslobatto(0)\n    @test_throws DomainError gausslobatto(1)\n\n    n = 2\n    x,w = gausslobatto(n)\n    @test x[1] \u2248 -1.\n    @test x[2] \u2248 1.\n    @test w[1] \u2248 1.\n    @test w[2] \u2248 1.\n\n    n = 3\n    x,w = gausslobatto(n)\n    @test x[1] \u2248 -1.\n    @test abs(x[2])<1e-15\n    @test x[3] \u2248 1.\n    @test w[1] \u2248 1/3\n    @test w[2] \u2248 4/3\n    @test w[3] \u2248 1/3\n\n    tol = 1e-14\n    n = 42\n    x,w = gausslobatto(n)\n    @test ( length(x) == n) && ( length(w) == n )\n    @test abs(x[37] - 0.922259214258616) < tol\n    @test abs(w[37] - 0.029306411216166) < tol\n    @test ( x[1] == -1 && x[n] == 1 )\n\n    @test dot( w,(x.^2)) \u2248 2/3\n    @test dot( w,exp.(x)) \u2248 exp(1)-exp(-1)\nend", "meta": {"hexsha": "7552a1f5e76bbc29bd6b187c5e3e232717eb02b0", "size": 784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gausslobatto.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": "test/test_gausslobatto.jl", "max_issues_repo_name": "Datseris/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "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": "test/test_gausslobatto.jl", "max_forks_repo_name": "Datseris/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "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": 23.7575757576, "max_line_length": 49, "alphanum_fraction": 0.5102040816, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605945, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7614181344585306}}
{"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 Test, JLD2, LinearAlgebra\n#\n# gradient computation by parial automatic differentiation and adjoint merthods \n# of \n#           E(v) = \u222b |U(v)|\u00b2 dx \n# where \n# A(v) U(v) = F(v) the discrete version of - div(M \u2207 Ua) = Fa\n# and v are the vertices of the voronoi cells \n# \n\n# load polygonal mesh \nfilename, nc = \"Lpolmesh_coarse\", 100\nmesh_filename = \"$(@__DIR__)/data/$(filename)_$(nc).jld2\"\nprintln(\"read file $(mesh_filename)\")\nJLD2.@load(mesh_filename, pv, cellsb, cellsbt, t, pb, tb) \n# boundary points / rhs \nrhs, boundary_condition, meshboundary = if occursin(\"square\", mesh_filename)\n    PolygonalFem.rhs_sqr, PolygonalFem.boundary_condition_sqr, []\nelse\n    EPS = 1e-4\n    PolygonalFem.rhs_L_elas, PolygonalFem.boundary_condition_L_elas, \n    findall(pv[:, 2] .> (1 - EPS))\nend\nnp, \u03b5 = size(pv, 1), 1e-4\nx, dp = pv, 2 * rand(size(pv)...) .- 1\n# IMPORTANT Do not move boundary nodes\ndp[meshboundary, :] .= 0.\nxp, xm = x .+ \u03b5 * dp, x .- \u03b5 * dp\n# finite differences\nf = x -> PolygonalFem.costnormU_elas2D(x, cellsb, t, rhs, boundary_condition, \n                                       meshboundary)\nfp, fm = f(xp), f(xm)\n@time g = PolygonalFem.\u2207costnormU_elas2D(x, cellsb, t, rhs, boundary_condition, \n                                         meshboundary)\n@time g = PolygonalFem.\u2207costnormU_elas2D(x, cellsb, t, rhs, boundary_condition,\n                                         meshboundary)\nprintln(\"\")\nprintln(fp)\nprintln(fm)\nprintln(\" \")\nprintln((fp - fm) / (2 * \u03b5))\nprintln(dot(g, dp))\nprintln(\"\")\n@testset \"test eval gradient dot function for polygonal costnormU_elas2D\" begin \n    @test abs(dot(g, dp) - (fp - fm) / (2 * \u03b5)) < 1e-4\nend", "meta": {"hexsha": "39a734d649eb539c34548b2be6c53a553ce799cc", "size": 1648, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_costnormU_elas2D.jl", "max_stars_repo_name": "edljk/PolygonalFem.jl", "max_stars_repo_head_hexsha": "97c25ce56069ae1e4bfdacfe646896e3ca44611a", "max_stars_repo_licenses": ["MIT"], "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_costnormU_elas2D.jl", "max_issues_repo_name": "edljk/PolygonalFem.jl", "max_issues_repo_head_hexsha": "97c25ce56069ae1e4bfdacfe646896e3ca44611a", "max_issues_repo_licenses": ["MIT"], "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_costnormU_elas2D.jl", "max_forks_repo_name": "edljk/PolygonalFem.jl", "max_forks_repo_head_hexsha": "97c25ce56069ae1e4bfdacfe646896e3ca44611a", "max_forks_repo_licenses": ["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.8260869565, "max_line_length": 80, "alphanum_fraction": 0.6310679612, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7613891209431214}}
{"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, \u03b3 = 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], \u03b3)\n  specificationplot(Pcl, \u03b3; 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\u03c4(x,p) = abs.(p[2])*exp(-x/p[1])\n    x = collect(1:length(a))\n    c = curve_fit(model\u03c4, x, a, ones(2))\n    \u03c4 = c.param[1]\n    return max(one(\u03c4),\u03c4)\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": "######################################################################\n# test counter and mcmc with a standard normal\n######################################################################\n\n\"Normal(0,1) density. Keeps track of simulations. For unit tests.\"\nmutable struct StandardNormalModel\n    counter::Int\nend\n\nlogdensity(::StandardNormalModel, \u03b8) = -0.5*\u03b8[1]^2\n\nsimulate!(p::StandardNormalModel) = p.counter += 1\n\n@testset \"standard normal\" begin\n    p = StandardNormalModel(0)\n    chain, a = mcmc(RWMH(diagm([0.5])), p, [0.0], 1000)\n    @test p.counter == 1000\n    xs = first.(chain)\n    @test mean(xs) \u2248 0 atol = 0.1\n    @test std(xs) \u2248 1 atol = 0.2\nend\n\n######################################################################\n# test mcmc with a transformed \u0393\n######################################################################\n\n@testset \"log transformed \u0393\" begin\n    dist = Gamma(5.0, 1.0)\n    # sample log(x), where x \u223c distribution, apply the Jacobian correction\n    p = DensityWrapper(\u03b8 -> logpdf(dist, exp(\u03b8[1])) + \u03b8[1])\n\n    chain, a = mcmc(RWMH(diagm([2.0])), p, [log(5.0)], 10000)\n    xs = exp.(first.(chain))\n\n    @test mean(xs) \u2248 mean(dist) atol = 0.2\n    test_cdf(dist, xs; ps = 0.1:0.1:0.9, atol = 0.2)\nend\n", "meta": {"hexsha": "9779920f632ad056482d1e6fa4754cb01d1276c5", "size": 1227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-mcmc.jl", "max_stars_repo_name": "JuliaTagBot/HamiltonianABC.jl", "max_stars_repo_head_hexsha": "4e33873cb08bf608ad62ada62e545bda4ee321ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-22T21:08:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T01:42:05.000Z", "max_issues_repo_path": "test/test-mcmc.jl", "max_issues_repo_name": "JuliaTagBot/HamiltonianABC.jl", "max_issues_repo_head_hexsha": "4e33873cb08bf608ad62ada62e545bda4ee321ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-05-23T18:47:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-16T22:24:38.000Z", "max_forks_repo_path": "test/test-mcmc.jl", "max_forks_repo_name": "JuliaTagBot/HamiltonianABC.jl", "max_forks_repo_head_hexsha": "4e33873cb08bf608ad62ada62e545bda4ee321ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-19T09:13:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:48:18.000Z", "avg_line_length": 32.2894736842, "max_line_length": 74, "alphanum_fraction": 0.4865525672, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7613891095291938}}
{"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 \u03ba = 2:dim\n\n        # Replace the i-th vertex of the temporary simplex with `point`\n        temp_simplex[\u03ba] = point\n\n        # Replace the remaining vertices of the temporary simplex\n        # with the original vertices\n        remaining_vertex_idxs = setdiff(1:(dim + 1), \u03ba)\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[\u03ba] = sign(orientation(temp_simplex))\n\n        if !(coefficient_signs[\u03ba-1] == coefficient_signs[\u03ba])\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 \u03ba = 2:dim\n\n        # Replace the i-th vertex of the temporary simplex with `point`\n        temp_simplex[\u03ba] = point\n\n        # Replace the remaining vertices of the temporary simplex\n        # with the original vertices\n        remaining_vertex_idxs = setdiff(1:(dim + 1), \u03ba)\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[\u03ba] = sign(orientation(temp_simplex))\n\n        if !(coefficient_signs[\u03ba-1] == coefficient_signs[\u03ba])\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 SparseArrays, DiffEqOperators, LinearAlgebra, Random,\n      Test, BandedMatrices, FillArrays\n\nRandom.seed!(1234)\n\n\n# These functions create analytic solutions to upwind operators. In the function name,\n# the first number indicates the derivative order, the second number indicates\n# the approximation order,and the last three characters \"Pos\" or \"Neg\" indicating\n# the winding direction. For instance analyticOneTwoPos corresponds to the positive\n# upwind second order approximation of the first derivative.\n\nfunction analyticOneOnePos()\n      A = zeros(5,7)\n      for i in 1:5\n            A[i,i+1:i+2] = [-1 1]\n      end\n      return A\nend\n\nfunction analyticOneOneNeg()\n      A = zeros(5,7)\n      for i in 1:5\n            A[i,i:i+1] = [-1 1]\n      end\n      return A\nend\n\nfunction analyticOneTwoPos()\n      A = zeros(5,7)\n      for i in 1:4\n            A[i,i+1:i+3] = [-3/2 2 -1/2]\n      end\n      A[5,5:7] = [-1/2 0 1/2]\n      return A\nend\n\nfunction analyticOneTwoNeg()\n      A = zeros(5,7)\n      A[1,1:3] = [-1/2 0 1/2]\n      for i in 2:5\n            A[i,i-1:i+1] = [1/2 -2 3/2]\n      end\n      return A\nend\n\nfunction analyticTwoTwoPos()\n      A = zeros(5,7)\n      for i in 1:3\n            A[i,i+1:i+4] = [2 -5 4 -1]\n      end\n      A[4,4:7] = [1 -2 1 0]\n      A[5, 4:7] = [0 1 -2 1]\n      return A\nend\n\nfunction analyticTwoTwoNeg()\n      A = zeros(5,7)\n      A[1,1:4] = [1 -2 1 0]\n      A[2,1:4] = [0 1 -2 1]\n      for i in 3:5\n            A[i,i-2:i+1] = [-1 4 -5 2]\n      end\n      return A\nend\n\nfunction analyticTwoThreePos()\n      A = zeros(7,9)\n      for i in 1:4\n            A[i,i+1:i+5] = [35/12 -104/12 114/12 -56/12 11/12]\n      end\n      A[5,5:9] = [11/12 -20/12 6/12 4/12 -1/12]\n      A[6,5:9] = [-1/12 16/12 -30/12 16/12 -1/12]\n      A[7,5:9] = [-1/12 4/12 6/12 -20/12 11/12]\n      return A\nend\n\nfunction analyticTwoThreeNeg()\n      A = zeros(7,9)\n      A[1,1:5] = [11/12 -20/12 6/12 4/12 -1/12]\n      A[2,1:5] = [-1/12 16/12 -30/12 16/12 -1/12]\n      A[3,1:5] = [-1/12 4/12 6/12 -20/12 11/12]\n      for i in 4:7\n            A[i,i-3:i+1] = [11/12 -56/12 114/12 -104/12 35/12]\n      end\n      return A\nend\n\n# analytically derived upwind operators for the irregular grid:\n# [0.0, 0.08, 0.1, 0.15, 0.19, 0.26, 0.29], and spacing:\n# dx = [0.08, 0.02, 0.05, 0.04, 0.07, 0.03]\n\nfunction analyticOneOnePosIrr()\n      A = zeros(5,7)\n      A[1,2:3] = [-50, 50]\n      A[2,3:4] = [-20, 20]\n      A[3,4:5] = [-25, 25]\n      A[4,5:6] = [-100/7, 100/7]\n      A[5,6:7] = [-100/3, 100/3]\n      return A\nend\n\nfunction analyticOneOneNegIrr()\n      A = zeros(5,7)\n      A[1,1:2] = [-25/2, 25/2]\n      A[2,2:3] = [-50, 50]\n      A[3,3:4] = [-20, 20]\n      A[4,4:5] = [-25, 25]\n      A[5,5:6] = [-100/7, 100/7]\n      return A\nend\n\nfunction analyticOneTwoPosIrr()\n      A = zeros(5,7)\n      A[1,2:4] = [-450/7, 490/7, -40/7]\n      A[2,3:5] = [-280/9, 405/9, -125/9]\n      A[3,4:6] = [-2625/77, 3025/77, -400/77]\n      A[4,5:7] = [-510/21, 1000/21, -490/21]\n      A[5,5:7] = [-90/21, -400/21, 490/21]\n      return A\nend\n\nfunction analyticOneTwoNegIrr()\n      A = zeros(5,7)\n      A[1,1:3] = [-5/2, -75/2, 80/2]\n      A[2,1:3] = [5/2, -125/2, 120/2]\n      A[3, 2:4] = [250/7, -490/7, 240/7]\n      A[4, 3:5] = [80/9, -405/9, 325/9]\n      A[5, 4:6] = [1225/77, -3025/77, 1800/77]\n      return A\nend\n\nfunction analyticTwoTwoPosIrr()\n      A = zeros(5,7)\n      A[1,2:5] = [200000/77, -308000/77, 143000/77, -35000/77]\n      A[2,3:6] = [27500/33, -75000/33, 55000/33, -7500/33]\n      A[3,4:7] = [72500/77, -137500/77, 120000/77, -55000/77]\n      A[4,4:7] = [42500/77, -71500/77, 40000/77, -11000/77]\n      A[5,4:7] = [-10000/77, 44000/77, -100000/77, 66000/77]\n      return A\nend\n\nfunction analyticTwoTwoNegIrr()\n      A = zeros(5,7)\n      A[1,1:4] = [1050/7, -1250/7, -1400/7, 1600/7]\n      A[2,1:4] = [350/7, 6250/7, -9800/7, 3200/7]\n      A[3,1:4] = [-1400/7, 25000/7, -30800/7, 7200/7]\n      A[4,2:5] = [-390000/231, 770000/231, -660000/231, 280000/231]\n      A[5,3:6] = [-38500/77, 161000/77, -165000/77, 42500/77]\n      return A\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 1, Winding = Positive\" begin\n      N = 5\n      L = UpwindDifference(1,1, 1.0, N, 1.0)\n      analyticL = analyticOneOnePos()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) == analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 1, Winding = Negative\" begin\n      N = 5\n      L = UpwindDifference(1,1, 1.0, N, -1.0)\n      analyticL = -1*analyticOneOneNeg()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) == analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 2, Winding = Positive\" begin\n      N = 5\n      L = UpwindDifference(1,2, 1.0, N, 1.0)\n      analyticL = analyticOneTwoPos()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) == analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 2, Winding = Negative\" begin\n      N = 5\n      L = UpwindDifference(1,2, 1.0, N, -1.0)\n      analyticL = -1*analyticOneTwoNeg()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) == analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 2, Approx Order = 2, Winding = Positive\" begin\n      N = 5\n      L = UpwindDifference(2,2, 1.0, N, 1.0)\n      analyticL = analyticTwoTwoPos()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) == analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 2, Approx Order = 2, Winding = Negative\" begin\n      N = 5\n      L = UpwindDifference(2,2, 1.0, N, -1.0)\n      analyticL = -1*analyticTwoTwoNeg()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) == analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n# Here the operators are too big for five grid points, so weird corner cases must be accounted for\n# We should be able to assume that users will not have cases like this.\n@testset \"Test: Derivative Order = 2, Approx Order = 3, Winding = Positive\" begin\n      N = 7\n      L = UpwindDifference(2,3, 1.0, N, 1.0)\n      analyticL = analyticTwoThreePos()\n      x = rand(9)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 2, Approx Order = 3, Winding = Negative\" begin\n      N = 7\n      L = UpwindDifference(2,3, 1.0, N, -1.0)\n      analyticL = -1*analyticTwoThreeNeg()\n      x = rand(9)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 1, Winding = Positive, Grid = Irregular\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(1,1, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, 1.0)\n      analyticL = analyticOneOnePosIrr()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 1, Winding = Negative, Grid = Irregular\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(1,1, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, -1.0)\n      analyticL = -1*analyticOneOneNegIrr()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 2, Winding = Positive, Grid = Irregular\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(1,2, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, 1.0)\n      analyticL = analyticOneTwoPosIrr()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 1, Approx Order = 2, Winding = Negative, Grid = Irregular\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(1,2, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, -1.0)\n      analyticL = -1*analyticOneTwoNegIrr()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 2, Approx Order = 2, Winding = Positive, Grid = Irregular\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(2,2, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, 1.0)\n      analyticL = analyticTwoTwoPosIrr()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Derivative Order = 2, Approx Order = 2, Winding = Negative, Grid = Irregular\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(2,2, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, -1.0)\n      analyticL = -1*analyticTwoTwoNegIrr()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Scaling by dx and Derivative Order in Uniform Case\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(1,2, 0.1, N, 1.0)\n      analyticL = 10.0*analyticOneTwoPos()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\n      L = UpwindDifference(1,2, 0.1, N, -1.0)\n      analyticL = -10.0*analyticOneTwoNeg()\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\n      L = UpwindDifference(2,2, 0.1, N, 1.0)\n      analyticL = 100.0*analyticTwoTwoPos()\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\n      L = UpwindDifference(2,2, 0.1, N, -1.0)\n      analyticL = -100.0*analyticTwoTwoNeg()\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Non-Trivial Coefficient Handling in Uniform Grid Case\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(2,2, 1.0, N, 4.56)\n      analyticL = 4.56*analyticTwoTwoPos()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\n      L = UpwindDifference(2,2, 1.0, N, -4.56)\n      analyticL = -4.56*analyticTwoTwoNeg()\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: dx and Derivative Order Scaling and Non-Trivial Coefficient Handling in Uniform Grid Case\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(2,2, 0.1, N, 4.56)\n      analyticL = 4.56*100.0*analyticTwoTwoPos()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\n      L = UpwindDifference(2,2, 0.1, N, -4.56)\n      analyticL = -4.56*100.0*analyticTwoTwoNeg()\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n\n@testset \"Test: Coefficient Handling in Non-Uniform Grid Case\" begin\n      N = 5\n      # constructor throws an error at the moment\n      L = UpwindDifference(2,2, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, 4.56)\n      analyticL = 4.56*analyticTwoTwoPosIrr()\n      x = rand(7)\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\n      L = UpwindDifference(2,2, [0.08, 0.02, 0.05, 0.04, 0.07, 0.03], N, -4.56)\n      analyticL = -4.56*analyticTwoTwoNegIrr()\n\n      # Test that multiplication agrees with analytic multiplication\n      @test L*x \u2248 analyticL*x\n\n      # Test that concretized multiplication agrees with analytic multiplication\n      @test Array(L)*x \u2248 analyticL*x\n\n      # Test that matrix-free multiplication agrees with concretized multiplication\n      @test L*x \u2248 Array(L)*x\n\n      # Test that concretized matrix agrees with analytic matrix\n      @test Array(L) \u2248 analyticL\n\n      # Test Banded and Sparse concretizations\n      @test Array(L) == BandedMatrix(L)\n      @test Array(L) == SparseMatrixCSC(L)\n      @test typeof(BandedMatrix(L)) <: BandedMatrix\n      @test typeof(SparseMatrixCSC(L)) <: SparseMatrixCSC\n\n      # Test convolutions against bpv\n      bpv = PeriodicBC(Float64)*x[1:N]\n      @test L*bpv \u2248 analyticL*bpv\n\nend\n", "meta": {"hexsha": "cad58971d130b34b3b3599c45e48a1a68b8b34e3", "size": 28293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/upwind_operators_interface.jl", "max_stars_repo_name": "fgerick/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a5bb1df9178db2ed0f7ca603dc51d3ecdb096141", "max_stars_repo_licenses": ["MIT"], "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/upwind_operators_interface.jl", "max_issues_repo_name": "fgerick/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a5bb1df9178db2ed0f7ca603dc51d3ecdb096141", "max_issues_repo_licenses": ["MIT"], "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/upwind_operators_interface.jl", "max_forks_repo_name": "fgerick/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a5bb1df9178db2ed0f7ca603dc51d3ecdb096141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-12T14:42:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T14:42:04.000Z", "avg_line_length": 33.0525700935, "max_line_length": 112, "alphanum_fraction": 0.6429858976, "num_tokens": 8700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7613639284706868}}
{"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": "# \u6ce1\u5229\u7b97\u7b26\r\n\r\nconst \u03c30 = [1 0; 0 1]\r\nconst \u03c3x = [0 1; 1 0]\r\nconst \u03c3y = [0 -im; im 0]\r\nconst \u03c3z = [1 0; 0 -1]\r\nconst \u03c3v = \u03c3x + \u03c3y + \u03c3z\r\n\r\n\"\"\"\r\n    \u2297(x::AbstractVector, y::AbstractVector)\r\n\u5f20\u91cf\u79ef\r\n\"\"\"\r\n\u2297(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    \u2297(x::AbstractMatrix, y::AbstractMatrix)\r\n\u5f20\u91cf\u79ef\r\n\"\"\"\r\n\u2297(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    \u03b8 = range(0, stop=2pi, length=nv(g)+1)[1:end-1]\n    return cos.(\u03b8), sin.(\u03b8)\nend\n\n\"\"\"\n    spring_layout(g; \n                  k = 1 / \u221anv(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/\u221anv(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\u00b2 = 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\u00b2  = (d_x * d_x) + (d_y * d_y)\n                dist = sqrt(dist\u00b2)\n\n                if !(iszero(adj_matrix[i,j]) && iszero(adj_matrix[j,i]) )\n                    # Attractive + repulsive force\n                    # F_d = dist\u00b2 / k - k\u00b2 / dist # original FR algorithm\n                    F_d = dist / k - k\u00b2 / dist\u00b2\n                else\n                    # Just repulsive\n                    # F_d = -k\u00b2 / dist  # original FR algorithm\n                    F_d = -k\u00b2 / dist\u00b2\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        \u03b8 = range(0, stop=2pi, length=length(nodes)+1)[1:end-1]\n        append!(x, radius * cos.(\u03b8))\n        append!(y, radius * sin.(\u03b8))\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# \u2554\u2550\u2561 5057c590-c5a4-11eb-2621-4b67f12ca95d\nmd\"\"\"\n# K Nearest Neighbors\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cb1dd9ac-ca78-4169-b073-943f64160dbc\nmodule tools include(\"../tools.jl\") end\n\n# \u2554\u2550\u2561 f1fa76da-f656-4f12-97d7-a8b847ca0733\nJuTools = tools.JuTools\n\n# \u2554\u2550\u2561 c3ad6021-8080-4870-8350-1337d548f23a\nimport Statistics\n\n# \u2554\u2550\u2561 83864e6e-4b62-45d5-962e-39e36bbcc43d\nimport Random\n\n# \u2554\u2550\u2561 0d7f31a9-7ae2-4be5-81b2-313ac58af62d\nimport LinearAlgebra\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 19b1c000-6fa3-42b7-9fc7-983c7caf44b9\nbegin\nX_data, Y_data = JuTools.data_generate_linear_2d()\nsize(X_data), size(Y_data)\nend\n\n# \u2554\u2550\u2561 063389c7-07b6-4050-9241-ea953c4f4338\nX_data[1:2, :]\n\n# \u2554\u2550\u2561 cf291226-c0a1-4206-a8cb-53bedb67b139\ncosine_sim(X_data[1, :], X_data[2, :])\n\n# \u2554\u2550\u2561 fbf7a012-dcf8-498f-ad29-ec8c4854406c\ncosine_sim(X_data[1, :], X_data[3, :])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c9d27318-5e3d-4c9c-9ba5-556c649baaf9\nmajority_vote([1,1,0])\n\n# \u2554\u2550\u2561 ba24b3c5-f350-4774-a018-9acf1f4597ad\nmd\"\"\"\nOutput ordering is affected by input ordering\n\"\"\"\n\n# \u2554\u2550\u2561 5e564f3b-1bda-41b1-8b22-bdf6d91314d2\nmajority_vote([1,1,0,0])\n\n# \u2554\u2550\u2561 ed575b52-7509-4140-b5e7-295920f73e3d\nmajority_vote([1,1,0,0,0])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 30320c6e-7ada-41b6-a938-f1fd19cc120a\nY_predict = predict_naive(X_test, 5, X_train, Y_train)\n\n# \u2554\u2550\u2561 27b26afb-a91c-47c4-94ef-1d64761f291d\nJuTools.compute_accuracy(Y_predict, Y_test)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c42f2b8a-a88d-4e8c-a1c0-1a371ae6a669\ndist_sim(X_data[1, :], X_data[2, :])\n\n# \u2554\u2550\u2561 158f77bf-2eb8-490a-a062-6364a6ec70e9\ndist_sim(X_data[2, :], X_data[3, :])\n\n# \u2554\u2550\u2561 323e10a0-c68f-433a-afc5-0ac2514a90d1\nmd\"\"\"\nIt's greatly affected by the scale of data!\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 36ceae2a-4c04-4f67-9a6d-19a44cb2fa5b\nJuTools.compute_accuracy(predict_naive_fun(X_test, 5, X_train, Y_train), Y_test)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a76dcf16-060e-4ece-9b8d-76c45deb38c4\nkdtree = create_kdtree(X_data, Y_data)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 569da607-dea8-4994-9ffe-05959071a855\nkdtree_train = create_kdtree(X_train, Y_train)\n\n# \u2554\u2550\u2561 0ea4cb86-6be5-49f1-b9b8-56f6a8cc8ed0\nJuTools.compute_accuracy(predict_kdtree(X_test, kdtree_train, K=10), Y_test)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ffb15055-c887-47a9-88d7-71a33a3c2dba\nballtree = create_balltree(X_data, Y_data)\n\n# \u2554\u2550\u2561 77ed169b-d426-4f3f-8362-809cb0c8dd22\nballtree.X_data\n\n# \u2554\u2550\u2561 79ddb157-8ee4-4c44-b8bf-b4f36f88acce\nballtree.Y_data\n\n# \u2554\u2550\u2561 6c589940-e00a-40c9-b2d9-c10384e4ac62\nballtree.pivot\n\n# \u2554\u2550\u2561 5b5c5f78-75c2-4a85-b918-e7485f492d9e\nballtree.radius\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 06e6d38d-b08e-4583-863a-e6e06726143b\nballtree_train = create_balltree(X_train, Y_train)\n\n# \u2554\u2550\u2561 41e118e2-2172-4910-ba52-12e199737c6a\nJuTools.compute_accuracy(predict_balltree(X_test, balltree_train, K=20), Y_test)\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25005057c590-c5a4-11eb-2621-4b67f12ca95d\n# \u255f\u250074f4afa1-dd5a-4931-ab48-a1d4fc77bbe5\n# \u2560\u2550cb1dd9ac-ca78-4169-b073-943f64160dbc\n# \u2560\u2550f1fa76da-f656-4f12-97d7-a8b847ca0733\n# \u2560\u2550c3ad6021-8080-4870-8350-1337d548f23a\n# \u2560\u255083864e6e-4b62-45d5-962e-39e36bbcc43d\n# \u2560\u25500d7f31a9-7ae2-4be5-81b2-313ac58af62d\n# \u2560\u255073b4e7e0-7294-46dc-9545-9728277df652\n# \u2560\u255019b1c000-6fa3-42b7-9fc7-983c7caf44b9\n# \u2560\u2550063389c7-07b6-4050-9241-ea953c4f4338\n# \u2560\u2550cf291226-c0a1-4206-a8cb-53bedb67b139\n# \u2560\u2550fbf7a012-dcf8-498f-ad29-ec8c4854406c\n# \u2560\u25502cf4e990-f788-44e3-94cc-9e210e47c762\n# \u2560\u2550c9d27318-5e3d-4c9c-9ba5-556c649baaf9\n# \u255f\u2500ba24b3c5-f350-4774-a018-9acf1f4597ad\n# \u2560\u25505e564f3b-1bda-41b1-8b22-bdf6d91314d2\n# \u2560\u2550ed575b52-7509-4140-b5e7-295920f73e3d\n# \u2560\u25508406faec-66f4-46aa-9582-964ebdbecfba\n# \u2560\u25503001da4a-3288-4168-b514-c0b12f552fdd\n# \u2560\u255030320c6e-7ada-41b6-a938-f1fd19cc120a\n# \u2560\u255027b26afb-a91c-47c4-94ef-1d64761f291d\n# \u2560\u25500e1b5c16-f444-41dd-9e44-999969ba647c\n# \u2560\u2550c42f2b8a-a88d-4e8c-a1c0-1a371ae6a669\n# \u2560\u2550158f77bf-2eb8-490a-a062-6364a6ec70e9\n# \u255f\u2500323e10a0-c68f-433a-afc5-0ac2514a90d1\n# \u2560\u255052010e3f-2e4f-4778-b53e-4fad04dd75bf\n# \u2560\u255036ceae2a-4c04-4f67-9a6d-19a44cb2fa5b\n# \u255f\u25002c7f7263-5ba0-4786-8b68-8ca8fb3ffc26\n# \u255f\u2500b2aac2a9-cf86-44f0-ae97-b2a52327b0f9\n# \u2560\u2550b127297e-cb0c-46f5-8551-3ba2c4dae4c6\n# \u2560\u2550c3c4fe2c-6e92-4c98-bce3-e77f394c405d\n# \u2560\u2550a76dcf16-060e-4ece-9b8d-76c45deb38c4\n# \u2560\u25504c3444dd-f2cb-4954-8dad-d2e9466252e8\n# \u2560\u255094c43601-cff7-4c7f-a116-8a82aefed5b0\n# \u2560\u2550569da607-dea8-4994-9ffe-05959071a855\n# \u2560\u25500ea4cb86-6be5-49f1-b9b8-56f6a8cc8ed0\n# \u255f\u250098be952f-0591-45c6-be83-3c0f6cc5d26b\n# \u2560\u2550dc218b5e-73f5-4dc8-b523-62bed53a71e7\n# \u2560\u2550d7cc4b1c-f953-4f64-95bb-09e1d51a38f5\n# \u2560\u2550ffb15055-c887-47a9-88d7-71a33a3c2dba\n# \u2560\u255077ed169b-d426-4f3f-8362-809cb0c8dd22\n# \u2560\u255079ddb157-8ee4-4c44-b8bf-b4f36f88acce\n# \u2560\u25506c589940-e00a-40c9-b2d9-c10384e4ac62\n# \u2560\u25505b5c5f78-75c2-4a85-b918-e7485f492d9e\n# \u2560\u255075368c67-8774-4f67-9163-d31475f4e289\n# \u2560\u2550a14bd64d-4188-4682-8a47-c3999afb0d09\n# \u2560\u255006e6d38d-b08e-4583-863a-e6e06726143b\n# \u2560\u255041e118e2-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#\u00a0 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#\u00a0 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#\u00a0 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": "const tfn = pso.TestFunctions\n\n@testset \"TestFunctions\" begin\n\n    @testset \"sphere function\" begin\n        @test tfn.sphere([0]) == 0\n        @test tfn.sphere([0.0]) == 0\n        @test tfn.sphere(fill(0, 10)) == 0\n        @test tfn.sphere([3.0, 4.0]) == 25\n    end\n    \n    @testset \"euclidean_distance function\" begin\n        @test tfn.euclidean_distance([0]) == 0\n        @test tfn.euclidean_distance([0.0]) == 0\n        @test tfn.euclidean_distance(fill(0, 10)) == 0\n        @test tfn.euclidean_distance([3.0, 4.0]) == 5\n    end\n\n    @testset \"rastrigin function\" begin\n        @test tfn.rastrigin([0]) == 0\n        @test tfn.rastrigin([0.0]) == 0\n        @test tfn.rastrigin(fill(0, 10)) == 0\n        @test tfn.rastrigin([0.0, 0.0], A=-2.3) == 0.0\n    end\n\n    @testset \"ackley's function\" begin\n        @test tfn.ackley([0,0]) == 0\n        @test tfn.ackley([0.0, 0.0]) == 0\n    end\n\n    @testset \"rosenbrock's function\" begin\n        @test tfn.rosenbrock([1.0]) == 0\n        @test tfn.rosenbrock([1, 1]) == 0\n        @test tfn.rosenbrock(fill(1, 10)) == 0.0\n    end\n\n    @testset \"eggholder function\" begin\n        @test tfn.eggholder(512, 404.2319) \u2248 -959.6407 atol=0.0001\n        @test tfn.eggholder([512, 404.2319]) \u2248 -959.6407 atol=0.0001\n    end\n\n    @testset \"beale function\" begin\n        @test tfn.beale(3, 0.5) == 0\n        @test tfn.beale([3, 0.5]) == 0\n    end\n\n    @testset \"square_movingpeak function\" begin\n        @test tfn.square_movingpeak([0, 0]) == 0\n        @test tfn.square_movingpeak([3, 4]) == 25\n        @test tfn.square_movingpeak([1, 1], optimum=[1, 1]) == 0\n        @test tfn.square_movingpeak([2, 2], optimum=[1, 1]) \u2248 2\n    end\n\n    @testset \"ellipse function\" begin\n        @test tfn.ellipse(-0.5, -1.5) == 0\n        @test tfn.ellipse([-0.5, -1.5]) == 0\n    end\n\n    @testset \"stybliski function\" begin\n        for i in 1:5\n            @test tfn.stybliski(fill(-2.903534, i)) \u2248 -39.16616*i atol=0.0001\n        end\n    end\n\n    @testset \"mccormick function\" begin\n        @test tfn.mccormick(0, 0) == 1\n        @test tfn.mccormick([0, 0]) == 1\n        @test tfn.mccormick(-0.54719, -1.54719) \u2248 -1.9133 atol=0.0001\n    end\n\n    @testset \"himmelblau function\" begin\n        @test tfn.himmelblau(-0.270845, -0.923039) \u2248 181.617 atol=0.001\n        @test tfn.himmelblau(3, 2) \u2248 0\n        @test tfn.himmelblau([3, 2]) \u2248 0\n        @test tfn.himmelblau(-2.805118,  3.131312) \u2248 0 atol=0.0001\n        @test tfn.himmelblau(-3.77931 , -3.283186) \u2248 0 atol=0.0001\n        @test tfn.himmelblau( 3.584428, -1.848126) \u2248 0 atol=0.0001\n    end\n\n    @testset \"griewank function\" begin\n        @test tfn.griewank([0, 0]) == 0\n    end\n\n    @testset \"schafferf6 function\" begin\n        @test tfn.schafferf6(0, 0) == 0\n        @test tfn.schafferf6([0, 0]) == 0\n    end\n\nend\n", "meta": {"hexsha": "b0c0f65b24dccfe4eb16571c44f67defaba6d94d", "size": 2785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TestFunctions.jl", "max_stars_repo_name": "control13/ParticleSwarmOptimizer.jl", "max_stars_repo_head_hexsha": "52cd5254c6cfd92bb58a0506610055c934c0ca86", "max_stars_repo_licenses": ["MIT"], "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/TestFunctions.jl", "max_issues_repo_name": "control13/ParticleSwarmOptimizer.jl", "max_issues_repo_head_hexsha": "52cd5254c6cfd92bb58a0506610055c934c0ca86", "max_issues_repo_licenses": ["MIT"], "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/TestFunctions.jl", "max_forks_repo_name": "control13/ParticleSwarmOptimizer.jl", "max_forks_repo_head_hexsha": "52cd5254c6cfd92bb58a0506610055c934c0ca86", "max_forks_repo_licenses": ["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.9444444444, "max_line_length": 77, "alphanum_fraction": 0.5622980251, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7612756472064389}}
{"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        \u03b3 = x[i]^2 + x[i+1]^2\n        fx += \u03b3^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        \u03b3 = x[i]^2 + x[i+1]^2\n        g[i] += 4.0\u03b3*x[i] - 4.0\n        g[i+1] += 4.0\u03b3*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        \u03b3 = x[i]^2 + x[i+1]^2\n        fx += \u03b3^2 + (3.0 - 4.0x[i])\n        g[i] += 4.0\u03b3*x[i] - 4.0\n        g[i+1] += 4.0\u03b3*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 \u2265 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": "using ClassicalOrthogonalPolynomials, ContinuumArrays, QuasiArrays, BandedMatrices, Test\nimport ClassicalOrthogonalPolynomials: Hilbert, StieltjesPoint, ChebyshevInterval, associated, Associated, orthogonalityweight, Weighted, gennormalizedpower, *, dot, PowerLawMatrix, PowKernelPoint, LogKernelPoint\nimport InfiniteArrays: I\n\n@testset \"Associated\" begin\n    T = ChebyshevT()\n    U = ChebyshevU()\n    @test associated(T) \u2261 U\n    @test associated(U) \u2261 U\n    @test Associated(T)[0.1,1:10] == Associated(U)[0.1,1:10] == U[0.1,1:10]\n\n    P = Legendre()\n    Q = Associated(P)\n    x = axes(P,1)\n    u = Q * (Q \\ exp.(x))\n    @test u[0.1] \u2248 exp(0.1)\n    @test grid(Q[:,Base.OneTo(5)]) \u2248 eigvals(Matrix(jacobimatrix(Normalized(Q))[1:5,1:5]))\n\n    w = orthogonalityweight(Q)\n    @test axes(w,1) == axes(P,1)\n    @test sum(w) == 1\nend\n\n\n@testset \"Singular integrals\" begin\n    @testset \"weights\" begin\n        w_T = ChebyshevTWeight()\n        w_U = ChebyshevUWeight()\n        w_P = LegendreWeight()\n        x = axes(w_T,1)\n        H = inv.(x .- x')\n        @test iszero(H*w_T)\n        @test (H*w_U)[0.1] \u2248 \u03c0/10\n        @test (H*w_P)[0.1] \u2248 log(1.1) - log(1-0.1)\n\n        w_T = orthogonalityweight(chebyshevt(0..1))\n        w_U = orthogonalityweight(chebyshevu(0..1))\n        w_P = orthogonalityweight(legendre(0..1))\n        x = axes(w_T,1)\n        H = inv.(x .- x')\n        @test iszero(H*w_T)\n        @test (H*w_U)[0.1] \u2248 (2*0.1-1)*\u03c0\n        @test (H*w_P)[0.1] \u2248 (log(1+(-0.8)) - log(1-(-0.8)))\n    end\n\n    @testset \"LogKernelPoint\" begin\n        wU = Weighted(ChebyshevU())\n        x = axes(wU,1)\n        z = 0.1+0.2im\n        L = log.(abs.(z.-x'))\n        @test L isa LogKernelPoint{Float64,ComplexF64,ComplexF64,Float64,ChebyshevInterval{Float64}}\n\n        @testset \"Real point\" begin\n            U = ChebyshevU()\n            x = axes(U,1)\n\n            t = 2.0\n            @test (log.(abs.(t .- x') )* Weighted(U))[1,1:3] \u2248 [1.0362686329607178,-0.4108206734393296, -0.054364775221816465] #mathematica\n\n            t = 0.5\n            @test (log.(abs.(t .- x') )* Weighted(U))[1,1:3] \u2248 [-1.4814921268505252, -1.308996938995747, 0.19634954084936207] #mathematica\n\n            t = 0.5+0im\n            @test (log.(abs.(t .- x') )* Weighted(U))[1,1:3] \u2248 [-1.4814921268505252, -1.308996938995747, 0.19634954084936207] #mathematica\n        end\n    end\n\n    @testset \"Stieltjes\" begin\n        T = Chebyshev()\n        wT = ChebyshevWeight() .* T\n        x = axes(wT,1)\n        z = 0.1+0.2im\n        S = inv.(z .- x')\n        @test S isa StieltjesPoint{ComplexF64,ComplexF64,Float64,ChebyshevInterval{Float64}}\n\n        @test S * ChebyshevWeight() \u2248 \u03c0/(sqrt(z-1)sqrt(z+1))\n        @test S * JacobiWeight(0.1,0.2) \u2248 0.051643014475741864 - 2.7066092318596726im\n\n        f = wT * [[1,2,3]; zeros(\u221e)];\n        J = T \\ (x .* T)\n\n        @test \u03c0*((z*I-J) \\ f.args[2])[1,1] \u2248 (S*f)[1]\n        @test \u03c0*((z*I-J) \\ f.args[2])[1,1] \u2248 (S*f.args[1]*f.args[2])[1]\n\n        x = Inclusion(0..1)\n        y = 2x .- 1\n        wT2 = wT[y,:]\n        S = inv.(z .- x')\n        f = wT2 * [[1,2,3]; zeros(\u221e)];\n\n        @test (\u03c0/2*(((z-1/2)*I - J/2) \\ f.args[2]))[1] \u2248 (S*f.args[1]*f.args[2])[1]\n\n        @testset \"Real point\" begin\n            t = 2.0\n            T = ChebyshevT()\n            U = ChebyshevU()\n            x = axes(T,1)\n            @test inv.(t .- x') * Weighted(T) \u2248 inv.((t+eps()im) .- x') * Weighted(T)\n            @test (inv.(t .- x') * Weighted(U))[1:10] \u2248 (inv.((t+eps()im) .- x') * Weighted(U))[1:10]\n\n            t = 2\n            @test inv.(t .- x') * Weighted(T) \u2248 inv.((t+eps()im) .- x') * Weighted(T)\n            @test (inv.(t .- x') * Weighted(U))[1:10] \u2248 (inv.((t+eps()im) .- x') * Weighted(U))[1:10]\n\n            t = 0.5\n            @test (inv.(t .- x') * Weighted(T))[1,1:3] \u2248 [0,-\u03c0,-\u03c0]\n            @test (inv.(t .- x') * Weighted(U))[1,1:3] \u2248 [\u03c0/2,-\u03c0/2,-\u03c0]\n\n            t = 0.5+0im\n            @test (inv.(t .- x') * Weighted(T))[1,1:3] \u2248 [0,-\u03c0,-\u03c0]\n            @test (inv.(t .- x') * Weighted(U))[1,1:3] \u2248 [\u03c0/2,-\u03c0/2,-\u03c0]\n        end\n    end\n\n    @testset \"Hilbert\" begin\n        wT = ChebyshevTWeight() .* ChebyshevT()\n        wU = ChebyshevUWeight() .* ChebyshevU()\n        x = axes(wT,1)\n        H = inv.(x .- x')\n        @test H isa Hilbert{Float64,ChebyshevInterval{Float64}}\n\n        @testset \"weights\" begin\n            @test H * ChebyshevTWeight() \u2261 QuasiZeros{Float64}((x,))\n            @test H * ChebyshevUWeight() == \u03c0*x\n            @test (H * LegendreWeight())[0.1] \u2248 log((0.1+1)/(1-0.1))\n        end\n\n        @test (Ultraspherical(1) \\ (H*wT))[1:10,1:10] == diagm(1 => fill(-\u03c0,9))\n        @test (Chebyshev() \\ (H*wU))[1:10,1:10] == diagm(-1 => fill(1.0\u03c0,9))\n\n        # check consistency\n        @test (Ultraspherical(1) \\ (H*wT) * (wT \\ wU))[1:10,1:10] ==\n                    ((Ultraspherical(1) \\ Chebyshev()) * (Chebyshev() \\ (H*wU)))[1:10,1:10]\n\n        @testset \"Other axes\" begin\n            x = Inclusion(0..1)\n            y = 2x .- 1\n            H = inv.(x .- x')\n\n            wT2 = wT[y,:]\n            wU2 = wU[y,:]\n            @test (Ultraspherical(1)[y,:]\\(H*wT2))[1:10,1:10] == diagm(1 => fill(-\u03c0,9))\n            @test (Chebyshev()[y,:]\\(H*wU2))[1:10,1:10] == diagm(-1 => fill(1.0\u03c0,9))\n        end\n\n        @testset \"Legendre\" begin\n            P = Legendre()\n            x = axes(P,1)\n            H = inv.(x .- x')\n            Q = H*P\n            @test Q[0.1,1:3] \u2248 [log(0.1+1)-log(1-0.1), 0.1*(log(0.1+1)-log(1-0.1))-2,-3*0.1 + 1/2*(-1 + 3*0.1^2)*(log(0.1+1)-log(1-0.1))]\n            X = jacobimatrix(P)\n            @test Q[0.1,1:11]'*X[1:11,1:10] \u2248 (0.1 * Array(Q[0.1,1:10])' - [2 zeros(1,9)])\n        end\n\n        @testset \"mapped\" begin\n            T = chebyshevt(0..1)\n            U = chebyshevu(0..1)\n            x = axes(T,1)\n            H = inv.(x .- x')\n            @test U\\H*Weighted(T) isa BandedMatrix\n        end\n    end\n\n    @testset \"Log kernel\" begin\n        T = Chebyshev()\n        wT = ChebyshevWeight() .* Chebyshev()\n        x = axes(wT,1)\n        L = log.(abs.(x .- x'))\n        D = T \\ (L * wT)\n        @test ((L * wT) * (T \\ exp.(x)))[0.] \u2248 -2.3347795490945797  # Mathematica\n\n        x = Inclusion(-1..1)\n        T = Chebyshev()[1x, :]\n        L = log.(abs.(x .- x'))\n        wT = (ChebyshevWeight() .* Chebyshev())[1x, :]\n        @test (T \\ (L*wT))[1:10,1:10] \u2248 D[1:10,1:10]\n\n        x = Inclusion(0..1)\n        T = Chebyshev()[2x.-1, :]\n        wT = (ChebyshevWeight() .* Chebyshev())[2x .- 1, :]\n        L = log.(abs.(x .- x'))\n        u =  wT * (2 *(T \\ exp.(x)))\n        @test u[0.1] \u2248 exp(0.1)/sqrt(0.1-0.1^2)\n        @test (L * u)[0.5] \u2248 -7.471469928754152 # Mathematica\n\n        @testset \"mapped\" begin\n            T = chebyshevt(0..1)\n            x = axes(T,1)\n            L = log.(abs.(x .- x'))\n            @test T[0.2,:]'*((T\\L*Weighted(T)) * (T\\exp.(x))) \u2248 -2.9976362326874373 # Mathematica\n        end\n    end\n\n    @testset \"pow kernel\" begin\n        P = Weighted(Jacobi(0.1,0.2))\n        x = axes(P,1)\n        S = abs.(x .- x').^0.5\n        @test S isa ClassicalOrthogonalPolynomials.PowKernel\n        @test_broken S*P\n    end\n\n    @testset \"Ideal Fluid Flow\" begin\n        T = ChebyshevT()\n        U = ChebyshevU()\n        x = axes(U,1)\n        H = inv.(x .- x')\n\n        c = exp(0.5im)\n\n\n        u = Weighted(U) * ((H * Weighted(U)) \\ imag(c * x))\n\n        \u03b5  = eps();\n        @test (inv.(0.1+\u03b5*im .- x') * u + inv.(0.1-\u03b5*im .- x') * u)/2 \u2248 imag(c*0.1)\n        @test real(inv.(0.1+\u03b5*im .- x') * u ) \u2248 imag(c*0.1)\n\n        v = (s,t) -> (z = (s + im*t); imag(c*z) - real(inv.(z .- x') * u))\n        @test v(0.1,0.2) \u2248 0.18496257285081724 # Emperical\n    end\n\n    @testset \"OffHilbert\" begin\n        @testset \"ChebyshevU\" begin\n            U = ChebyshevU()\n            W = Weighted(U)\n            t = axes(U,1)\n            x = Inclusion(2..3)\n            T = chebyshevt(2..3)\n            H = T \\ inv.(x .- t') * W;\n            @test last(colsupport(H,1)) == 17\n            @test last(colsupport(H,6)) \u2264 40\n            @test T[2.3,1:100]'*(H * (W \\ @.(sqrt(1-t^2)exp(t))))[1:100] \u2248 0.9068295340935111\n            @test T[2.3,1:100]' * H[1:100,1:100] \u2248 (inv.(2.3 .- t') * W)[:,1:100]\n        end\n\n        @testset \"mapped\" begin\n            U = chebyshevu(-1..0)\n            W = Weighted(U)\n            t = axes(U,1)\n            x = Inclusion(2..3)\n            T = chebyshevt(2..3)\n            H = T \\ inv.(x .- t') * W\n            N = 100\n            @test T[2.3,1:N]' * H[1:N,1:N] \u2248 (inv.(2.3 .- t') * W)[:,1:N]\n\n            U = chebyshevu((-2)..(-1))\n            W = Weighted(U)\n            T = chebyshevt(0..2)\n            x = axes(T,1)\n            t = axes(W,1)\n            H = T \\ inv.(x .- t') * W\n            @test T[0.5,1:N]'*(H * (W \\ @.(sqrt(-1-t)*sqrt(t+2)*exp(t))))[1:N] \u2248 0.047390454610749054\n        end\n    end\n\n    #################################################\n    # \u222bf(x)g(x)(t-x)^a dx evaluation where f and g in Legendre\n    #################################################\n\n    @testset \"Pow kernel\" begin\n        @testset \"Multiplication methods\" begin\n            P = Normalized(Legendre())\n            x = axes(P,1)\n            for (a,t) in ((0.1,1.2), (0.5,1.5))\n                @test (t.-x).^a isa PowKernelPoint\n                w = (t.-x).^a\n                @test w .* P isa typeof(P*PowerLawMatrix(P,a,t))\n            end\n            # some functions\n            f = P \\ exp.(x.^2)\n            g = P \\ (sin.(x).*exp.(x.^(2)))\n            # some parameters for (t-x)^a\n            a = BigFloat(\"1.23\")\n            t = BigFloat(\"1.00001\")\n            # define powerlaw multiplication\n            w = (t.-x).^a\n\n            # check if it can compute the integral correctly\n            @test g'*(P'*(w.*P)*f) \u2248 -2.656108697646584 # Mathematica\n        end\n        @testset \"Equivalence to multiplication in integer case\" begin\n            # TODO: overload integer input to make this work\n            P = Normalized(Legendre())\n            x = axes(P,1)\n            a = 1\n            t = 1.2\n            @test_broken PowerLawMatrix(P,Float64(a),t)[1:20,1:20] \u2248 ((t*I-jacobimatrix(P))^a)[1:20,1:20]\n            a = 2\n            t = 1.0001\n            J = ((t*I-jacobimatrix(P)))[1:80,1:80]\n            @test_broken PowerLawMatrix(P,BigFloat(\"$a\"),BigFloat(\"$t\"))[1:60,1:60] \u2248 (J^2)[1:60,1:60]\n        end\n        @testset \"Cached Legendre power law integral operator\" begin\n            P = Normalized(Legendre())\n            a = 2*rand(1)[1]\n            t = 1.0000000001\n            Acached = PowerLawMatrix(P,BigFloat(\"$a\"),BigFloat(\"$t\"))\n            @test size(Acached) == (\u221e,\u221e)\n        end\n        @testset \"PowKernelPoint dot evaluation\" begin\n            @testset \"Set 1\" begin\n                    P = Normalized(Legendre())\n                    x = axes(P,1)\n                    f = P \\ abs.(\u03c0*x.^7)\n                    g = P \\ (cosh.(x.^3).*exp.(x.^(2)))\n                    a = 1.9127\n                    t = 1.211\n                    w = (BigFloat(\"$t\") .- x).^BigFloat(\"$a\")\n                    Pw = P'*(w .* P)\n                    @test w isa PowKernelPoint\n                    @test Pw[1:20,1:20] \u2248 PowerLawMatrix(P,a,t)[1:20,1:20]\n                    # this is slower than directly using PowerLawMatrix but it works\n                    @test dot(f[1:20],Pw[1:20,1:20],g[1:20]) \u2248 5.082145576355614 # Mathematica\n                end\n            @testset \"Set 2\" begin\n                P = Normalized(Legendre())\n                x = axes(P,1)\n                f = P \\ exp.(x.^2)\n                g = P \\ (sin.(x).*exp.(x.^(2)))\n                a = 1.23\n                t = 1.00001\n                W = PowerLawMatrix(P,a,t)\n                @test dot(f,W,g) \u2248 -2.656108697646584 # Mathematica\n            end\n            @testset \"Set 3\" begin\n                P = Normalized(Legendre())\n                x = axes(P,1)\n                t = 1.2\n                a = 1.1\n                W = PowerLawMatrix(P,a,t)\n                f = P \\ exp.(x)\n                g = P \\ exp.(x.^2)\n                @test dot(f,W,g) \u2248 2.916955525390389 # Mathematica\n            end\n            @testset \"Set 4\" begin\n                P = Normalized(Legendre())\n                x = axes(P,1)\n                t = 1.001\n                a = 1.001\n                W = PowerLawMatrix(P,a,t)\n                f = P \\ (sinh.(x).*exp.(x))\n                g = P \\ cos.(x.^3)\n                @test dot(f,W,g) \u2248 -0.1249375144525209 # Mathematica\n            end\n            @testset \"More explicit evaluation tests\" begin\n                # basis\n                a = 2.9184\n                t = 1.000001\n                P = Normalized(Legendre())\n                x = axes(P,1)\n                # operator\n                W = PowerLawMatrix(P,a,t)\n                # functions\n                f = P \\ exp.(x)\n                g = P \\ sin.(x)\n                const1(x) = 1\n                onevec = P \\ const1.(x)\n                # dot() and * methods tests, explicit values via Mathematica\n                @test -2.062500116206712 \u2248 dot(onevec,W,g)\n                @test 2.266485452423447 \u2248 dot(onevec,W,f)\n                @test -0.954305839543464 \u2248 dot(g,W,f)\n                @test 1.544769699288028 \u2248 dot(f,W,f)\n                @test 1.420460011606107 \u2248 dot(g,W,g)\n            end\n        end\n        @testset \"Tests for -1 < a < 0\" begin\n            P = Normalized(Legendre())\n            x = axes(P,1)\n            a = -0.7\n            t = 1.271\n            # operator\n            W = PowerLawMatrix(P,a,t)\n            WB = PowerLawMatrix(P,BigFloat(\"$a\"),BigFloat(\"$t\"))\n            # functions\n            f0 = P \\ exp.(2 .*x.^2)\n            g0 = P \\ sin.(x)\n            @test dot(f0,W,g0) \u2248  dot(f0,WB,g0) \u2248 1.670106472636101 # Mathematica\n            f1 = P \\ ((x.^2)./3 .+(x.^3)./3)\n            g1 = P \\ (x.*exp.(x.^3))\n            @test dot(f1,W,g1) \u2248 dot(f1,WB,g1) \u2248 0.5362428541997497 # Mathematica\n        end\n        @testset \"Lanczos\" begin\n            P = Normalized(Legendre())\n            x = axes(P,1)\n            @time D = ClassicalOrthogonalPolynomials.LanczosData((1.001 .- x).^0.5, P);\n            @time ClassicalOrthogonalPolynomials.resizedata!(D,100);\n        end\n    end\nend\n", "meta": {"hexsha": "cca0903dbc14eab3390f44159aa704194d92d193", "size": 14143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_stieltjes.jl", "max_stars_repo_name": "TSGut/ClassicalOrthogonalPolynomials.jl", "max_stars_repo_head_hexsha": "d7b2997cb16dc83a65dcef5366449232e67d2c49", "max_stars_repo_licenses": ["MIT"], "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_stieltjes.jl", "max_issues_repo_name": "TSGut/ClassicalOrthogonalPolynomials.jl", "max_issues_repo_head_hexsha": "d7b2997cb16dc83a65dcef5366449232e67d2c49", "max_issues_repo_licenses": ["MIT"], "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_stieltjes.jl", "max_forks_repo_name": "TSGut/ClassicalOrthogonalPolynomials.jl", "max_forks_repo_head_hexsha": "d7b2997cb16dc83a65dcef5366449232e67d2c49", "max_forks_repo_licenses": ["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.2641025641, "max_line_length": 212, "alphanum_fraction": 0.4477126494, "num_tokens": 5082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7612756433250467}}
{"text": "immutable Gumbel <: ContinuousUnivariateDistribution\n    \u03bc::Float64   # location\n    \u03b2::Float64 # scale\n\n    function Gumbel(\u03bc::Real, \u03b2::Real)\n        \u03b2 > zero(\u03b2) || error(\"The scale of Gumbel must be positive\")\n        @compat new(Float64(\u03bc), Float64(\u03b2))\n    end\n\n    Gumbel(\u03bc::Real) = Gumbel(\u03bc, 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.\u03bc\nscale(d::Gumbel) = d.\u03b2\nparams(d::Gumbel) = (d.\u03bc, d.\u03b2)\n\n\n#### Statistics\n\nmean(d::Gumbel) = d.\u03bc + d.\u03b2 * 0.57721566490153286\n\nmedian(d::Gumbel) = d.\u03bc + d.\u03b2 * 0.366512920581664327\n\nmode(d::Gumbel) = d.\u03bc\n\nvar(d::Gumbel) = 1.6449340668482264 * d.\u03b2^2\n\nskewness(d::Gumbel) = 1.13954709940464866\n\nkurtosis(d::Gumbel) = 2.4\n\nentropy(d::Gumbel) = 1.57721566490153286 + log(d.\u03b2)\n\n\n#### Evaluation\n\nzval(d::Gumbel, x::Float64) = (x - d.\u03bc) / d.\u03b2\nxval(d::Gumbel, z::Float64) = x * d.\u03b2 + d.\u03bc\n\nfunction pdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    exp(-z - exp(-z)) / d.\u03b2\nend\n\nfunction logpdf(d::Gumbel, x::Float64)\n    z = zval(d, x)\n    - (z + exp(-z) + log(d.\u03b2))\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.\u03bc - d.\u03b2 * log(-log(p))\n\ngradlogpdf(d::Gumbel, x::Float64) = - (1.0 + exp((d.\u03bc - x) / d.\u03b2)) / d.\u03b2\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": "\nusing PyPlot\nPyPlot.svg(true)\n\nx = [1:100]\ny = [i^2 for i in x]\np = plot(x,y)\nxlabel(\"X\")\nylabel(\"Y\")\ntitle(\"Basic plot\")\ngrid(\"on\")\n\nx = linspace(0, 3pi, 1000)\ny = cos(2*x + 3*sin(3*x));\nplot(x, y, color=\"orange\", linewidth=2.0, linestyle=\"--\");\ntitle(\"Another plot using sine and cosine\");\n\n\n\n\n\n\n\nX = linspace(0, 2 * pi, 100)\nYa = sin(X)\nYb = cos(X)\n\nplot(X, Ya)\nplot(X, Yb)\nshow()\n\nPkg.add(\"UnicodePlots\")\n\nusing UnicodePlots\n\nmyPlot = lineplot([1, 2, 3, 7], [1, 2, -5, 7], title=\"My Plot\", border=:dotted)\n\nmyPlot = densityplot([1:100], randn(100), border=:dotted)\n\nusing ASCIIPlots\n\nx = collect(-pi:0.2:pi)\nlineplot(x, sin(x))\n\nusing Vega\n\nx = [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9]\ny = [28, 43, 81, 19, 52, 24, 87, 17, 68, 49, 55, 91, 53, 87, 48, 49, 66, 27, 16, 15]\ng = [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1]\n\na = areaplot(x = x, y = y, group = g, stacked = true)\n\nfruit = [\"peaches\", \"plums\", \"blueberries\", \"strawberries\", \"bananas\"];\nbushels = [100, 32, 180, 46, 21];\npiechart(x = fruit, y = bushels, holesize = 125)\n\nusing Bokeh\nusing Dates # for version 0.3\n\nstart = Date(2015, 6, 21)\ndays = 120\nx = map(d -> start + Dates.Day(d), 1:days)\ny = 15 + randn(days) * 4\nplot(x, y, title=\"A typical British Summer\", legends=[\"Temperature\"])\n\n\n", "meta": {"hexsha": "98f11ee1811e9c9cf41a5305d1634d1976e47110", "size": 1255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter 5/ch05-Pyplot.jl", "max_stars_repo_name": "PacktPublishing/Julia-for-data-science", "max_stars_repo_head_hexsha": "dbdb53aa9294324ef982f1189acbcb78fbd2cb80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2017-01-22T13:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T21:45:32.000Z", "max_issues_repo_path": "Chapter 5/ch05-Pyplot.jl", "max_issues_repo_name": "PacktPublishing/Julia-for-data-science", "max_issues_repo_head_hexsha": "dbdb53aa9294324ef982f1189acbcb78fbd2cb80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 5/ch05-Pyplot.jl", "max_forks_repo_name": "PacktPublishing/Julia-for-data-science", "max_forks_repo_head_hexsha": "dbdb53aa9294324ef982f1189acbcb78fbd2cb80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-10-13T15:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T14:59:57.000Z", "avg_line_length": 18.7313432836, "max_line_length": 84, "alphanum_fraction": 0.5992031873, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7612276927801369}}
{"text": "using Convex1d\nusing Test\n\n@testset \"minimize\" begin\n    res = @inferred minimize(x -> x^2, (-1.1, 1), atol=1e-3)\n    @test res.minimizer \u2248 0 atol=1e-3\n    @test res.minimum === res.minimizer^2\n\n    x = [1,2]\n    y = [2,4]\n    f = c -> sum(abs, c*x - y)\n    sol = minimize(f, (-10, 10), atol=1e-10)\n    @test sol.minimizer \u2248 2 atol=1e-10\n\n    for _ in 1:100\n        x_opt = randn()\n        f_opt = randn()\n        s = 0.1 + 10rand()\n        p = 1 + rand()\n        f = x -> s*abs(x - x_opt)^p + f_opt\n        @assert f(x_opt) \u2248 f_opt\n        atol = eps(x_opt)^(1/3)\n        res = minimize(f, (x_opt - 10rand(), x_opt + 10rand()), atol=atol)\n        @test res.nevals < 100 # quick convergence\n        @test res.xbounds[1] <= res.minimizer <= res.xbounds[2]\n        @test res.xbounds[2] - res.xbounds[1] <= atol\n        # @test res.ybounds[1] <= res.minimum <= res.ybounds[2]\n        # @test res.ybounds[1] <= f_opt <= res.ybounds[2]\n\n        x_res, f_res = res\n        @test x_opt \u2248 x_res atol=atol\n        @test f(x_res) == f_res\n\n        res = minimize(f, (x_opt, x_opt + 10rand()), atol=atol)\n        x_res, f_res = res\n        @test x_opt \u2248 x_res atol=atol\n        @test f(x_res) == f_res\n\n        I = (x_opt-10rand(), x_opt)\n        res = minimize(f, I, atol=atol)\n        x_res, f_res = res\n        if !(isapprox(x_opt, x_res, atol=atol))\n            @show x_opt\n            @show f(x_opt)\n            @show f_opt\n            @show s\n            @show p\n            @show res\n            @show I\n            @show atol\n            error()\n        end\n        @test x_opt \u2248 x_res atol=atol\n        @test f(x_res) == f_res\n    end\nend\n\n@testset \"minimize no domain\" begin\n    for scale in [10^x for x in -10.0:10.0]\n        x_opt = scale*randn()\n        f = x -> abs(x - x_opt)\n        x_lo, x_hi = Convex1d.find_initial_domain(f)\n        @test x_lo <= x_opt <= x_hi\n        @test x_hi - x_lo < 8*(scale+1)\n        sol = minimize(f, atol=sqrt(eps(scale)))\n        @test sol.minimizer \u2248 x_opt atol=sqrt(eps(scale))\n    end\nend\n", "meta": {"hexsha": "fc14a9dd799b1e2d78a4d9e63fdd5c7f9adbb64d", "size": 2028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jw3126/Convex1d.jl", "max_stars_repo_head_hexsha": "c8ff39e29aeb3afcb1a127f7f5ab89df483cb434", "max_stars_repo_licenses": ["MIT"], "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": "jw3126/Convex1d.jl", "max_issues_repo_head_hexsha": "c8ff39e29aeb3afcb1a127f7f5ab89df483cb434", "max_issues_repo_licenses": ["MIT"], "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": "jw3126/Convex1d.jl", "max_forks_repo_head_hexsha": "c8ff39e29aeb3afcb1a127f7f5ab89df483cb434", "max_forks_repo_licenses": ["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.3913043478, "max_line_length": 74, "alphanum_fraction": 0.5128205128, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7612276926114917}}
{"text": "lines = open(\"bitmasks.txt\") do f\n    readlines(f)\nend\n\nmemory = zeros(Int64, 100000)\nzeromask = nothing\nonemask = nothing\nfor l in lines\n    global memory, zeromask, onemask\n    if startswith(l, \"mask = \")\n        mask = match(r\"[10X]+\", l).match\n        onemask = parse(Int, replace(mask, \"X\" => \"0\"); base = 2)\n        zeromask = parse(Int, replace(mask, \"X\" => \"1\"); base = 2)\n    else\n        addr, val = parse.(Int, match(r\"mem\\[(\\d+)\\] = (\\d+)\", l).captures)\n        memory[addr] = val & zeromask | onemask\n    end\nend\n\nprintln(sum(memory))\n\nmemory = Dict{Int64, Int64}()\nonemask = nothing\nxmask = nothing\nfor l in lines\n    global memory, xmask, onemask\n    if startswith(l, \"mask = \")\n        mask = match(r\"[10X]+\", l).match\n        onemask = parse(Int, replace(mask, \"X\" => \"0\"); base = 2)\n        xmask = findall(x -> x == 'X', mask)\n    else\n        addr, val = parse.(Int, match(r\"mem\\[(\\d+)\\] = (\\d+)\", l).captures)\n        res = collect(bitstring(addr | onemask)[end-35:end])\n        for i in 0:(2^length(xmask)-1)\n            floating = bitstring(i)[end-(length(xmask)-1):end]\n            float = collect(res)\n            for i in 1:length(xmask)\n                float[xmask[i]] = floating[i]\n            end\n            memory[parse(Int, join(float); base = 2)] = val\n        end\n    end\nend\n\nprintln(sum(values(memory)))\n", "meta": {"hexsha": "4198348a20621ed8a0e81342637b21afb8fdaead", "size": 1340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day14.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": "day14.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": "day14.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": 29.1304347826, "max_line_length": 75, "alphanum_fraction": 0.55, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7612276924428464}}
{"text": "using Flux, Flux.Data.MNIST, Statistics, BSON, Random, Plots; pyplot()\nusing Flux: onehotbatch, onecold, crossentropy\nRandom.seed!(0)\n\nepochs = 30\neta = 5e-3\nbatchSize = 1000\ntrainRange, validateRange = 1:5000, 5001:10000\n\nfunction minibatch(x, y, indexRange)\n    xBatch = Array{Float32}(undef, size(x[1])..., 1, length(indexRange))\n    for i in 1:length(indexRange)\n        xBatch[:, :, :, i] = Float32.(x[indexRange[i]])\n    end\n    return (xBatch, onehotbatch(y[indexRange], 0:9))\nend\n\ntrainLabels = MNIST.labels()[trainRange]\ntrainImgs = MNIST.images()[trainRange]\nmbIdxs = Iterators.partition(1:length(trainImgs), batchSize)\ntrainSet = [minibatch(trainImgs, trainLabels, bi) for bi in mbIdxs]\n\nvalidateLabels = MNIST.labels()[validateRange]\nvalidateImgs = MNIST.images()[validateRange]\nvalidateSet = minibatch(validateImgs, validateLabels, 1:length(validateImgs))\n\nmodel1= Chain(flatten, Dense(784, 200,relu),Dense(200, 100,tanh),\n\t\t\t\tDense(100, 10,sigmoid), softmax)\n\nmodel2= Chain(Conv((5, 5), 1=>8, relu), MaxPool((2,2)),\n                Conv((3, 3), 8=>16, relu), MaxPool((2,2)),\n                flatten, Dense(400, 10), softmax)\n\nopt1 = ADAM(eta); opt2 = ADAM(eta)\naccuracyPaths = [[],[]]\naccuracy(x, y, model) = mean(onecold(model(x)) .== onecold(y))\nloss(x, y, model) = crossentropy(model(x), y)\ncbF1() = push!(accuracyPaths[1],accuracy(validateSet..., model1))\ncbF2() = push!(accuracyPaths[2],accuracy(validateSet..., model2))\n\nmodel1(trainSet[1][1]); model2(trainSet[1][1])\nfor _ in 1:epochs\n    Flux.train!((x,y)->loss(x,y,model1), params(model1), trainSet, opt1, cb=cbF1)\n    Flux.train!((x,y)->loss(x,y,model2), params(model2), trainSet, opt2, cb=cbF2)\n\tprint(\".\")\nend\n\nprintln(\"\\nModel1 (Dense) accuracy = \", accuracy(validateSet..., model1))\nprintln(\"Model2 (Convolutional) accuracy = \", accuracy(validateSet..., model2))\n# cd(@__DIR__)\n# BSON.@save \"../data/mnistConv.bson\" modelParams=cpu.(params(model2))\nplot(accuracyPaths,label = [\"Dense\" \"Convolutional\"],\n\tylim=(0.7,1.0), xlabel=\"Batch number\", ylabel = \"Validation Accuracy\")", "meta": {"hexsha": "93c2720ad49826d082001cc2410cfb48e9275282", "size": 2052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test1.jl", "max_stars_repo_name": "yoninazarathy/JuliaMLForGRDC", "max_stars_repo_head_hexsha": "081d14b4b4510bca38349c58db6384ffb2b9386b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test1.jl", "max_issues_repo_name": "yoninazarathy/JuliaMLForGRDC", "max_issues_repo_head_hexsha": "081d14b4b4510bca38349c58db6384ffb2b9386b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test1.jl", "max_forks_repo_name": "yoninazarathy/JuliaMLForGRDC", "max_forks_repo_head_hexsha": "081d14b4b4510bca38349c58db6384ffb2b9386b", "max_forks_repo_licenses": ["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.7169811321, "max_line_length": 81, "alphanum_fraction": 0.6837231969, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7612276922742008}}
{"text": "# 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\nX = hcat(xs...)\nY = ts#onehotbatch(ts, 0:1)\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", "meta": {"hexsha": "e386dfe5c7ab22ca0448e8fc539604101ab3f52d", "size": 913, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "turing_data.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": "turing_data.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": "turing_data.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.8529411765, "max_line_length": 62, "alphanum_fraction": 0.5323110624, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7612276921055554}}
{"text": "export PR, auc\n\nstruct PR{T <: Real} <: AbstractBinaryMetric\n  labels::BitVector\n  scores::Vector{T}\n  AUC::T\n  precision::Vector{T}\n  recall::Vector{T}\n  OP::Vector{T}\n  function PR(labels,scores)\n    B = BinaryMetrics(labels, scores)\n    OP = op(B)\n    p = precision(B, OP)\n    r = recall(B,OP)\n    AUC = get_auc([0.0;r], [1.0;p])\n    new{eltype(p)}(B.labels, B.scores, AUC, p, r, OP)\n  end\nend\n\nfunction Base.show(io::IO, B::PR) \n  println(io,\"Precision-Recall (PR) curve\")\n  AUC = round(auc(B),digits=2)\n  print(io,\"Samples:$(length(B)), P:$(positives(B)), N:$(negatives(B)), AUC:$(AUC)\")\nend\n\n\"\"\"\n  PR(labels, scores)\n\nGenerates data for plotting a precision-recall (PR) curve.\n\n* `labels` must be a boolean array e.g. either containing `true`,`false` or `0`,`1`.\n* `scores` must be an array with the same length of `labels` containing the scores of the binary classifier.\n\nYou can generate a plot automatically using the following commands:\n```julia\npr = PR(labels, scores)\n\nusing Plots\nplot(pr)\n```\n\nThe Area Under Curve (AUC) FPR and TPR can be accessed by `auc(pr)`, `fpr(pr)` and `tpr(pr)` respectively.\n\n\"\"\"\nPR(B::BinaryMetrics) = PR(B.labels, B.scores)\n\nauc(curve::PR) = curve.AUC\nppv(curve::PR) = curve.precision\ntpr(curve::PR) = curve.recall\nop(curve::PR) = curve.OP\n\nfunction get_curve(curve::PR)\n  return [0.0;curve.recall], [1.0;curve.precision]\nend\n", "meta": {"hexsha": "b67c5ae9b2f633edc759071921761a83f5e8981a", "size": 1367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pr.jl", "max_stars_repo_name": "nantonel/ROC.jl", "max_stars_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pr.jl", "max_issues_repo_name": "nantonel/ROC.jl", "max_issues_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pr.jl", "max_forks_repo_name": "nantonel/ROC.jl", "max_forks_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_forks_repo_licenses": ["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.8545454545, "max_line_length": 108, "alphanum_fraction": 0.6656912948, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7612276870518664}}
{"text": "# -*- encoding: utf-8 -*-\r\n#\r\n# The MIT License (MIT)\r\n#\r\n# Copyright \u00a9 2021 Matteo Foglieni and Riccardo Gervasoni\r\n#\r\n\r\n\"\"\"\r\n    rotation_x(\u03d1::Float64) :: Transformation\r\n\r\nEncoding a rotation around the x-axis of an angle `\u03d1` _**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 `\u03d1>0` rotation angle. \r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction rotation_x(\u03d1::Float64)\r\n    Transformation(\r\n        [1.0    0.0     0.0     0.0 ;   \r\n         0.0    cos(\u03d1)  -sin(\u03d1) 0.0 ;\r\n         0.0    sin(\u03d1)  cos(\u03d1)  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(\u03d1)  sin(\u03d1)  0.0 ;\r\n         0.0    -sin(\u03d1) cos(\u03d1)  0.0 ;\r\n         0.0    0.0     0.0     1.0]\r\n    )\r\nend\r\n\r\n\"\"\"\r\n    rotation_y(\u03d1::Float64) :: Transformation\r\n\r\nEncoding a rotation around the y-axis of an angle `\u03d1` _**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 `\u03d1>0` rotation angle. \r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction rotation_y(\u03d1::Float64)\r\n    Transformation(\r\n        [cos(\u03d1)     0.0     sin(\u03d1)  0.0 ;\r\n         0.0        1.      0.0     0.0 ;\r\n         -sin(\u03d1)    0.0     cos(\u03d1)  0.0 ;\r\n         0.0        0.0     0.0     1.  ]\r\n         ,\r\n        [cos(\u03d1)     0.0     -sin(\u03d1) 0.0 ;\r\n         0.0        1.      0.0     0.0 ;\r\n         sin(\u03d1)     0.0     cos(\u03d1)  0.0 ;\r\n         0.0        0.0     0.0     1.  ]\r\n    )\r\nend \r\n\r\n\"\"\"\r\n    rotation_z(\u03d1::Float64) :: Transformation\r\n\r\nEncoding a rotation around the z-axis of an angle `\u03d1` _**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 `\u03d1>0` rotation angle. \r\n\r\nSee also: [`Transformation`](@ref)\r\n\"\"\"\r\nfunction rotation_z(\u03d1::Float64)\r\n    Transformation(\r\n        [cos(\u03d1) -sin(\u03d1) 0.0     0.0 ;\r\n         sin(\u03d1) cos(\u03d1)  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(\u03d1)     sin(\u03d1)  0.0     0.0 ;\r\n         -sin(\u03d1)    cos(\u03d1)  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 \u2248 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    \u03b5 = p[:\u03b5]\n    f = x -> 2 - x^2\n    dx[1] = f(\u03b5*x[length(dx)] + (1-\u03b5)*x[1])\n    for i in 2:length(dx)\n        dx[i] = f(\u03b5*x[i-1] + (1-\u03b5)*x[i])\n    end\nend\n\n\"\"\"\n    ulam(D::Int = 10; u\u2080 = rand(D), \u03b5::Real = 0.10) \u2192 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\u2080 = rand(D), \u03b5::Real = 0.10)\n\n    p = LVector(\u03b5 = \u03b5)\n\n    DiscreteDynamicalSystem(eom_ulam, u\u2080, 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": "using CollegeStratBase, Test\n\nfunction present_value_test()\n    x = 3.9;\n    T = 7;\n    R = 1.2;\n    pvFactor = pv_factor(R, T);\n    @test pvFactor > 1.0\n    @test pvFactor < T\n\n    xV = fill(x, T);\n    pValue = present_value(xV, R);\n    @test isapprox(x * pvFactor, pValue)\n\n    xV = LinRange(-0.5, 3.2, T);\n    pValue = present_value(xV, R);\n    pv = sum(xV .* ((1/R) .^ (0 : (T-1))));\n    @test isapprox(pv, pValue)\nend\n\n@testset \"Helpers\" begin\n    present_value_test();\nend\n\n# -----------", "meta": {"hexsha": "4461dca13843b362ebf37fc4ebf93dfba93df830", "size": 493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/helpers_test.jl", "max_stars_repo_name": "hendri54/CollegeStratBase", "max_stars_repo_head_hexsha": "85eb17b367d2ec9fa68ea4225fb5b63690e70602", "max_stars_repo_licenses": ["MIT"], "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/helpers_test.jl", "max_issues_repo_name": "hendri54/CollegeStratBase", "max_issues_repo_head_hexsha": "85eb17b367d2ec9fa68ea4225fb5b63690e70602", "max_issues_repo_licenses": ["MIT"], "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/helpers_test.jl", "max_forks_repo_name": "hendri54/CollegeStratBase", "max_forks_repo_head_hexsha": "85eb17b367d2ec9fa68ea4225fb5b63690e70602", "max_forks_repo_licenses": ["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": 43, "alphanum_fraction": 0.5557809331, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7612276826146528}}
{"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, \u0303x-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": "using MLJ\n\nLinearRegressor = @load LinearRegressor pkg=MLJLinearModels\n\nimport RDatasets: dataset\nimport DataFrames: describe, select, Not, rename!\nboston = dataset(\"MASS\", \"Boston\")\nfirst(boston, 3)\n\ndescribe(boston, :mean, :std, :eltype)\n\ndata = coerce(boston, autotype(boston, :discrete_to_continuous));\n\ny = data.MedV\nX = select(data, Not(:MedV));\n\nmdl = LinearRegressor()\n\nX_uni = select(X, :LStat) # only a single feature\nmach_uni = machine(mdl, X_uni, y)\nfit!(mach_uni)\n\nfp = fitted_params(mach_uni)\n@show fp.coefs\n@show fp.intercept\n\nusing PyPlot\n\nfigure(figsize=(8,6))\nplot(X.LStat, y, ls=\"none\", marker=\"o\")\nXnew = (LStat = collect(range(extrema(X.LStat)..., length=100)),)\nplot(Xnew.LStat, MLJ.predict(mach_uni, Xnew))\n\nmach = machine(mdl, X, y)\nfit!(mach)\n\nfp = fitted_params(mach)\ncoefs = fp.coefs\nintercept = fp.intercept\nfor (name, val) in coefs\n    println(\"$(rpad(name, 8)):  $(round(val, sigdigits=3))\")\nend\nprintln(\"Intercept: $(round(intercept, sigdigits=3))\")\n\ny\u0302 = MLJ.predict(mach, X)\nround(rms(y\u0302, y), sigdigits=4)\n\nfigure(figsize=(8,6))\nres = y\u0302 .- y\nstem(res)\n\nfigure(figsize=(8,6))\nhist(res, density=true)\n\nX2 = hcat(X, X.LStat .* X.Age);\n\nrename!(X2, :x1 => :interaction);\n\nmach = machine(mdl, X2, y)\nfit!(mach)\ny\u0302 = MLJ.predict(mach, X2)\nround(rms(y\u0302, y), sigdigits=4)\n\nX3 = hcat(X.LStat, X.LStat.^2) |> MLJ.table\nmach = machine(mdl, X3, y)\nfit!(mach)\ny\u0302 = MLJ.predict(mach, X3)\nround(rms(y\u0302, y), sigdigits=4)\n\nXnew = (LStat = Xnew.LStat, LStat2 = Xnew.LStat.^2)\n\nfigure(figsize=(8,6))\nplot(X.LStat, y, ls=\"none\", marker=\"o\")\nplot(Xnew.LStat, MLJ.predict(mach, Xnew))\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "2603365854067dca54c9f5b55f1f1cfb7436fcf6", "size": 1687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__site/__generated/ISL-lab-3/tutorial-raw.jl", "max_stars_repo_name": "JuliaAI/DataScienceTutorials.jl", "max_stars_repo_head_hexsha": "76b1d3d1a5045c62b104a8358e4c37049f15ccb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-08-09T11:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:20:43.000Z", "max_issues_repo_path": "__site/__generated/ISL-lab-3/tutorial-raw.jl", "max_issues_repo_name": "alan-turing-institute/MLJTutorials", "max_issues_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-10-22T00:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T14:38:09.000Z", "max_forks_repo_path": "__site/__generated/ISL-lab-3/tutorial-raw.jl", "max_forks_repo_name": "alan-turing-institute/MLJTutorials", "max_forks_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-11-20T16:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T11:55:15.000Z", "avg_line_length": 21.6282051282, "max_line_length": 87, "alphanum_fraction": 0.6828689982, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7612166651509781}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.17\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1aa41898-3afa-11eb-2f49-570853ce6435\nsubGroups = collect(combinations([control;fertilizer],10))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.17\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u25501aa451f0-3afa-11eb-2bb1-65c72b577797\n# \u255f\u2500475ff888-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 \u2297 I \u2297 ... \u2297 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\u00d74 Diagonal{Float64,Array{Float64,1}}:\n 1.0   \u22c5    \u22c5    \u22c5\n  \u22c5   1.0   \u22c5    \u22c5\n  \u22c5    \u22c5   1.0   \u22c5\n  \u22c5    \u22c5    \u22c5   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 \u2297 F \u2297 C` where `A = I^{\u2297 k1}` and `C = I^{\u2297 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^{\u2297 k1} \u2297 F \u2297 I^{\u2297 k2}`, represented as a sparse matrix\nif `F` is sparse.\n\n### Examples\n\n```jldoctest\njulia> F = sparse([0 1; -1 0.])\n2\u00d72 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 \u2297 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 \u2297 F \u2297 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 \u2295 F \u2295 ... \u2295 F := F \u2297 I \u2297 ... \u2297 I + I \u2297 F \u2297 I \u2297 ... \u2297 I + ... + I \u2297 ... \u2297 I \u2297 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 \u2297 I + I \u2297 F``\n- ``k = 3: F \u2297 I \u2297 I + I \u2297 F \u2297 I + I \u2297 I \u2297 F``\n\n```jldoctest\njulia> F = sparse([0 1; -1 0.])\n2\u00d72 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 \u2265 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^(\u2297k1) \u2297 F \u2297 I^(\u2297k2)\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 \u2297 x \u2297 ... \u2297 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^{\u2297 pow}`.\n\n### Examples\n\n```jldoctest\njulia> using DynamicPolynomials\n\njulia> @polyvar x[1:2]\n(PolyVar{true}[x\u2081, x\u2082],)\n\njulia> x\n2-element Vector{PolyVar{true}}:\n x\u2081\n x\u2082\n\njulia> kron_pow(x, 2)\n4-element Vector{Monomial{true}}:\n x\u2081\u00b2\n x\u2081x\u2082\n x\u2081x\u2082\n x\u2082\u00b2\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": "n = 10 # rand(1:10)\nA = matrixdepot(\"invhilb\", n)\n@test issymmetric(A)\n@test isposdef(A)\nprintln(\"'invhilb' passed test...\")\n", "meta": {"hexsha": "56819fbbf44a36ae76c72cbd938bb4fcf423102b", "size": 125, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_invhilb.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_invhilb.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_invhilb.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 20.8333333333, "max_line_length": 35, "alphanum_fraction": 0.664, "num_tokens": 43, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.761196193083506}}
{"text": "#  Copyright 2016, Iain Dunning, Joey Huchette, Miles Lubin, and contributors\n#  This Source Code Form is subject to the terms of the Mozilla Public\n#  License, v. 2.0. If a copy of the MPL was not distributed with this\n#  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n#############################################################################\n# JuMP\n# An algebraic modelling langauge for Julia\n# See http://github.com/JuliaOpt/JuMP.jl\n#############################################################################\n# sudoku.jl\n# A sudoku solver that uses a MIP to find solutions\n#\n# We have binary variables x[i,j,k] which, if = 1, say that cell (i,j)\n# contains the number k\n# The constraints are:\n# 1 - Each cell has one value only\n# 2 - Each row contains each number exactly once\n# 3 - Each column contains each number exactly once\n# 4 - Each 3x3 subgrid contains each number exactly once\n# We will take the initial grid as a CSV file, where 0s are \"blanks\n#############################################################################\n\nusing JuMP\n\n# Load data\nfunction LoadData(filepath)\n    fp = open(filepath, \"r\")\n    initgrid = zeros(Int,9,9)\n    for row in 1:9\n        line = readline(fp)\n        initgrid[row,:] = [parse(Int,s) for s in split(line,\",\")]\n    end\n    return initgrid\nend\n\n# Solve model\nfunction SolveModel(initgrid)\n    m = Model()\n\n    @variable(m, x[1:9, 1:9, 1:9], Bin)\n\n    @constraints m begin\n        # Constraint 1 - Only one value appears in each cell\n        # Constraint 2 - Each value appears in each row once only\n        # Constraint 3 - Each value appears in each column once only\n        cell[i=1:9, j=1:9], sum(x[i,j,:]) == 1\n         row[i=1:9, k=1:9], sum(x[i,:,k]) == 1\n         col[j=1:9, k=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    # Initial solution\n    for row in 1:9, col in 1:9\n        if initgrid[row,col] != 0\n            @constraint(m, x[row, col, initgrid[row, col]] == 1)\n        end\n    end\n\n    # Solve it\n    status = solve(m)\n\n    # Check solution\n    if status == :Infeasible\n        error(\"No solution found!\")\n    else\n        mipSol = getvalue(x)\n        sol = zeros(Int,9,9)\n        for row in 1:9, col in 1:9, val in 1:9\n            if mipSol[row, col, val] >= 0.9\n                sol[row, col] = val\n            end\n        end\n        return sol\n    end\n\nend\n\n# Initialization\nif length(ARGS) != 1\n    error(\"Expected one argument: the initial solution, e.g. julia sudoku.jl sudoku.csv\")\nend\n\n# Solve\nsol = SolveModel(LoadData(ARGS[1]))\n\n# Display solution\nprintln(\"Solution:\")\nprintln(\"[-----------------------]\")\nfor row in 1:9\n    print(\"[ \")\n    for col in 1:9\n        print(\"$(sol[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\nend\n\n", "meta": {"hexsha": "9f627ddb59decec5f1ffa076804a9417d6b025f7", "size": 2993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "public/.julia/v0.5/JuMP/examples/sudoku.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/sudoku.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/sudoku.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": 28.7788461538, "max_line_length": 89, "alphanum_fraction": 0.5402606081, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7611961898353538}}
{"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]) \u00d7 (0, h[2]) \u00d7 \u2026 \u00d7 (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    \u03be = [-1 / \u221a3, 1 / \u221a3]\n    weight = (avg ? one(T) : prod(h)) / 2^d\n    return weight * sum(f, product((\u03be .* 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 `\u03b4[p, q]` (Kronecker).\n\n\"\"\"\nfunction shape(x::NTuple{d,T}, h::NTuple{d,T}) where {d,T<:Number}\n    \u03be = 2 .* x ./ h\n    \u2112 = cell_vertices(d)\n    return [prod((1 + (-1)^p[i] * \u03be[i]) / 2 for i = 1:d) for p in \u2112]\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, \u2026)`.\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    \u03be = 2 .* x ./ h\n    \u2112 = cell_vertices(d)\n    return [\n        prod(j == i ? (-1)^n[j] / h[j] : (1 + (-1)^n[j] * \u03be[j]) / 2 for j = 1:d) for\n        i = 1:d, n in \u2112\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, \u2026, 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\u03b5[i, j] = \u03a3\u2096 \u03a3\u209a 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    \u2112 = 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 \u2208 \u2112\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 \u2208 {1, \u2026, d}` are component indices and `p, q \u2208 CartesianIndices(1:2, \u2026, 1:2)`.\n\n\"\"\"\nfunction stiffness_operator(h::NTuple{d,T}, C::Hooke{d,T}) where {d,T<:Number}\n    \u2112 = cell_vertices(d)\n    function f(x)\n        D = gradient_operator(x, h)\n        B = strain_displacement_operator(x, h)\n        \u03c3\u03b5 = Array{T}(undef, d, fill(2, d)..., d, fill(2, d)...)\n        for i = 1:d, p \u2208 \u2112, j = 1:d, q \u2208 \u2112\n            \u03c3\u03b5[i, p, j, q] =\n                C.\u03bb * D[i, p] * D[j, q] +\n                2C.\u03bc * sum(B[h, k, i, p] * B[h, k, j, q] for h = 1:d, k = 1:d)\n        end\n        return \u03c3\u03b5\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], \u2026, N[d])`, such that the average strain within element `p` reads\n\n```\n\u03b5[i, j, p] = B[i, j, p, k, q] * u[k, q],\n```\n\nwhere\n\n- `i, j, k \u2208 {1, \u2026, d}`: component indices,\n- `p, q \u2208 CartesianIndices(1:N[1], \u2026, 1:N[d])`: node indices,\n- `\u03b5[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    \ud835\udcdb = cell_vertices(d) # Local node indices\n    for p \u2208 CartesianIndices(N)\n        \ud835\udca2 = cell_vertices(p, N) # global node indices\n        for q \u2208 \ud835\udcdb\n            B[:, :, p, :, \ud835\udca2[q]] += Be[:, :, :, q]\n        end\n    end\n    return B\nend\n\n\n\"\"\"\n    global_stiffness_operator(N, h, \u03bc, \u03bd)\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], \u2026, N[d], d, N[1], \u2026, 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 \u2208 {1, \u2026, d}`: component indices,\n- `p, q \u2208 CartesianIndices(1:N[1], \u2026, 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    \ud835\udcdb = cell_vertices(d) # Local node indices\n    for e \u2208 CartesianIndices(N)\n        \ud835\udca2 = cell_vertices(e, N) # global node indices\n        for m \u2208 \ud835\udcdb, n \u2208 \ud835\udcdb\n            K[:, \ud835\udca2[m], :, \ud835\udca2[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\u00b3 + 3Bx\u00b2 + 3Cx + D = 0\n    A, B, C, D = promote(float(a), float(b), float(c), float(d)) ./ (1, 3, 3, 1)\n    \u03b4\u2081 = A * C - B * B\n    \u03b4\u2082 = A * D - B * C\n    \u03b4\u2083 = B * D - C * C\n    d13 = \u03b4\u2081 * \u03b4\u2083\n    d22 = \u03b4\u2082 * \u03b4\u2082\n    \u0394 = 4 * d13 - d22\n    nanvalue = zero(A) / zero(A)\n\n    if \u0394 < 0\n        At = Cb = Db = zero(A)  # A-tilde, C-bar, D-bar\n        if B^3 * D \u2265 A * C^3\n            At, Cb, Db = A, \u03b4\u2081, -2 * B * \u03b4\u2081 + A * \u03b4\u2082\n        else\n            At, Cb, Db = D, \u03b4\u2083, -D * \u03b4\u2082 + 2 * C * \u03b4\u2083\n        end\n        T\u2080 = -copysign(At, Db) * sqrt(-\u0394)\n        T\u2081 = -Db + T\u2080\n        p = cbrt(T\u2081 / 2)\n        q = T\u2081 == T\u2080 ? -p : -Cb / p\n        x\u2081 = Cb \u2264 0 ? p + q : -Db / (p^2 + q^2 + Cb)\n        x, w = B^3 * D \u2265 A * C^3 ? (x\u2081 - B, A) : (-D, x\u2081 + C)\n        return (x/w, nanvalue, nanvalue)\n    else\n        \u03b4\u2081 == \u03b4\u2082 == \u03b4\u2083 == 0 && return (-B/A, -B/A, -B/A)\n        s\u0394 = sqrt(\u0394)\n        \u03b8A, \u03b8D = abs.(atan.((A*s\u0394, 2*B*\u03b4\u2081 - A*\u03b4\u2082, D*s\u0394, D*\u03b4\u2082 - 2*C*\u03b4\u2083)) ./ 3)\n        sCA, sCD = sqrt.(.-min.((\u03b4\u2081, \u03b4\u2083), 0))\n        x\u2081A, x\u2081D = 2 .* (sCA, sCD) .* cos.((\u03b8A, \u03b8D))\n        x\u2083A, x\u2083D = .-((sCA, sCD)) .* (cos.((\u03b8A, \u03b8D)) .+ sqrt(3) .* sin.((\u03b8A, \u03b8D)))\n        xlt = (x\u2081A + x\u2083A > 2 * B) ? x\u2081A : x\u2083A\n        xst = (x\u2081D + x\u2083D < 2 * C) ? x\u2081D : x\u2083D\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": "using Crystallography: Cubic\nusing Tensorial: SymmetricFourthOrderTensor\nusing LinearElasticity.SymmetryCriteria: whichsystem, isisotropic\n\n# Compared with https://ferrite-fem.github.io/Tensors.jl/stable/demos/\n@testset \"Creating the linear elasticity tensor\" begin\n    E = 2\n    \u03bd = 0.3\n    dim = 3\n    \u03bb = E * \u03bd / ((1 + \u03bd) * (1 - 2\u03bd))\n    \u03bc = E / (2(1 + \u03bd))\n    \u03b4(i, j) = i == j ? 1.0 : 0.0\n    f = (i, j, k, l) -> \u03bb * \u03b4(i, j) * \u03b4(k, l) + \u03bc * (\u03b4(i, k) * \u03b4(j, l) + \u03b4(i, l) * \u03b4(j, k))\n    C = StiffnessTensor(SymmetricFourthOrderTensor{3}(f))\n    @test isapprox(\n        C[:, :, 1, 1],\n        [\n            2.69231 0.0 0.0\n            0.0 1.15385 0.0\n            0.0 0.0 1.15385\n        ];\n        rtol = 1e-5,\n    )\n    @test isapprox(\n        C[:, :, 2, 3],\n        [\n            0.0 0.0 0.0\n            0.0 0.0 0.769231\n            0.0 0.769231 0.0\n        ];\n        rtol = 1e-6,\n    )\n    c = StiffnessMatrix(C)\n    @test isapprox(\n        c,\n        [\n            2.69231 1.15385 1.15385 0.0 0.0 0.0\n            1.15385 2.69231 1.15385 0.0 0.0 0.0\n            1.15385 1.15385 2.69231 0.0 0.0 0.0\n            0.0 0.0 0.0 0.769231 0.0 0.0\n            0.0 0.0 0.0 0.0 0.769231 0.0\n            0.0 0.0 0.0 0.0 0.0 0.769231\n        ];\n        rtol = 1e-5,\n    )  # This is an isotropic system\n    @test StiffnessTensor(c) == C\n    S = inv(C)\n    s = ComplianceMatrix(S)\n    @test s \u2248 inv(c)\n    @test inv(s) \u2248 StiffnessMatrix(C)\n    @test whichsystem(c) == Cubic()\n    @testset \"Test for an isotropic system\" begin\n        @test c[1, 1] * s[1, 1] + 2c[1, 2] * s[1, 2] == 1\n        @test c[1, 1] * s[1, 2] + c[1, 2] * s[1, 1] + c[1, 2] * s[1, 2] < eps()\n        @test c[4, 4] * s[4, 4] \u2248 1\n        @test isisotropic(c)\n    end\nend\n\n@testset \"Creating the stresses and strains\" begin\n    \u03c3\u2082\u2082 = 200\n    \u03c3\u2081\u2082 = \u03c3\u2082\u2083 = 141\n    \u03c3 = TensorStress([\n        0 \u03c3\u2081\u2082 0\n        \u03c3\u2081\u2082 \u03c3\u2082\u2082 \u03c3\u2082\u2083\n        0 \u03c3\u2082\u2083 0\n    ])\n    @test EngineeringStress(\u03c3) == EngineeringStress([0, 200, 0, 141, 0, 141])\n    @test TensorStress(EngineeringStress(\u03c3)) == \u03c3\n    E = TensorStrain([\n        0.5 0.3 0.2\n        0.3 -0.2 -0.1\n        0.2 -0.1 0.1\n    ])\n    @test EngineeringStrain(E) == EngineeringStrain([0.5, -0.2, 0.1, -0.2, 0.4, 0.6])\n    @test TensorStrain(EngineeringStrain(E)) == E\nend\n", "meta": {"hexsha": "b6f5e68ea71b2699d09a499e02e8d88625172745", "size": 2261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tensors.jl", "max_stars_repo_name": "singularitti/LinearElasticity.jl", "max_stars_repo_head_hexsha": "4a7521c849728a69133e2d4ea5bbbdfd52988515", "max_stars_repo_licenses": ["MIT"], "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/tensors.jl", "max_issues_repo_name": "singularitti/LinearElasticity.jl", "max_issues_repo_head_hexsha": "4a7521c849728a69133e2d4ea5bbbdfd52988515", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-02-25T09:38:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-27T00:02:56.000Z", "max_forks_repo_path": "test/tensors.jl", "max_forks_repo_name": "singularitti/LinearElasticity.jl", "max_forks_repo_head_hexsha": "4a7521c849728a69133e2d4ea5bbbdfd52988515", "max_forks_repo_licenses": ["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.9871794872, "max_line_length": 91, "alphanum_fraction": 0.4922600619, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634206181515, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.761153754945808}}
{"text": "using JuMP, Ipopt\n\n@testset \"Rosenbrock Ipopt\" begin\n    # min (1-x)^2 + 100*(y-x^2)^2\n    # solution: (x,y) = (1,1)\n    # optimal objective 0\n    rosenbrock = Problem()\n\n    x = MPC.Variable(\"x\", Real)\n    y = MPC.Variable(\"y\", Real)\n    set_objective!(rosenbrock, Base.power_by_squaring((1-x),2) + 100*Base.power_by_squaring((y-Base.power_by_squaring(x,2)),2))\n\n    mysolver = Ipopt.Optimizer\n    m, variables_jump, ctr_jump, ctr_exp = get_JuMP_cartesian_model(rosenbrock, mysolver)\n    optimize!(m)\n\n    sol = get_JuMP_solution(m, variables_jump, rosenbrock)\n\n    @test sol[x] \u2248 1.0 atol=1e-5\n    @test sol[y] \u2248 1.0 atol=1e-5\n    @test get_objective(rosenbrock, sol) \u2248 0.0 atol=1e-5\nend\n\n\n@testset \"QCQP Ipopt\" begin\n    # min x - y\n    # st  x + x^2 + x*y + y^2 <= 1\n    #     -2 <= x, y <= 2\n    # solution: x+y = -1/3\n    # optimal objective -1-4/sqrt(3)\n\n    qcqp = Problem()\n\n    x = MPC.Variable(\"x\", Real)\n    y = MPC.Variable(\"y\", Real)\n\n    set_objective!(qcqp, x - y)\n\n    add_constraint!(qcqp, \"ctr\", (x + Base.power_by_squaring(x, 2) + x*y + Base.power_by_squaring(y,2)) << 1)\n    add_constraint!(qcqp, \"x bounds\", -2 << x << 2)\n    add_constraint!(qcqp, \"y bounds\", -2 << y << 2)\n\n    mysolver = Ipopt.Optimizer\n    m, variables_jump, ctr_jump, ctr_exp = get_JuMP_cartesian_model(qcqp, mysolver)\n    optimize!(m)\n\n    sol = get_JuMP_solution(m, variables_jump, qcqp)\n\n    ## Test for optimal solution\n    @test sol[x] + sol[y] \u2248 -1/3 atol=1e-5\n    @test get_objective(qcqp, sol) \u2248 -1-4/sqrt(3) atol=1e-5\n\n    ## Test slack functions\n    slacks = get_slacks(qcqp, sol)\n    @test real(slacks.coords[MPC.Variable(\"x bounds\", Complex)]) > 0\n    @test real(slacks.coords[MPC.Variable(\"y bounds\", Complex)]) > 0\n\n    @test imag(slacks.coords[MPC.Variable(\"x bounds\", Complex)]) == 0\n    @test imag(slacks.coords[MPC.Variable(\"y bounds\", Complex)]) == 0\n\n    @test get_minslack(qcqp, sol)[1] < 1e-6\nend\n\n\n@testset \"Matpower case9 Ipopt\" begin\n    instancepath = joinpath(pwd(), \"test\", \"instances\")\n    # instancepath = joinpath(Pkg.dir(\"MathProgComplex\"), \"test\", \"instances\")\n    pb_real, ~ = import_from_dat(joinpath(instancepath,\"case9real.dat\"))\n\n    mysolver = Ipopt.Optimizer\n    m, variables_jump = get_JuMP_cartesian_model(pb_real, mysolver)\n    optimize!(m)\n    @test JuMP.objective_value(m) \u2248 1.45883471040144e+003 atol=1e-6\nend\n", "meta": {"hexsha": "9c6cffcf366f504a98fd6e652f827e3865ff792a", "size": 2349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MathProgComplex.jl/test/jump_export.jl", "max_stars_repo_name": "JulieSliwak/OPF_refgen", "max_stars_repo_head_hexsha": "a251ed5b684782caaa005d574cae9a3e20990f41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathProgComplex.jl/test/jump_export.jl", "max_issues_repo_name": "JulieSliwak/OPF_refgen", "max_issues_repo_head_hexsha": "a251ed5b684782caaa005d574cae9a3e20990f41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathProgComplex.jl/test/jump_export.jl", "max_forks_repo_name": "JulieSliwak/OPF_refgen", "max_forks_repo_head_hexsha": "a251ed5b684782caaa005d574cae9a3e20990f41", "max_forks_repo_licenses": ["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.32, "max_line_length": 127, "alphanum_fraction": 0.6402724564, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7611537543123204}}
{"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\u0305 = sample_mean(x)\n    y\u0305 = 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\u00b2 = 1 - SSE / SST\n    s\u00b2 = SSE / (n - 2)\n    \u03b2 = sum_of_squares(x, y) / sum_of_squares(x) \n    \u03b1 = y\u0305 - \u03b2 * x\u0305\n    return Dict([(\"\u03b1\", \u03b1), (\"\u03b2\", \u03b2), (\"s\u00b2\", s\u00b2), (\"R\u00b2\", R\u00b2), (\"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": "A = matrixdepot(\"hankel\", [1:5;])\n@test A == matrixdepot(\"hankel\", 5)\n\nr1 = rand(5)\nr2 = rand(5)\nB = matrixdepot(\"hankel\", r1, r2)\n@test issymmetric(B)\n\nC = matrixdepot(\"hankel\", Int, [1,2,3], [3, 4, 5, 6])\n@test C[3,4] == 6\n@test C[2,4] == C[3,3]\nprintln(\"'hankel' passed test...\")\n", "meta": {"hexsha": "2b815f05a67299a6978fb3718654825bf8ee9039", "size": 283, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_hankel.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_hankel.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_hankel.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 21.7692307692, "max_line_length": 53, "alphanum_fraction": 0.5795053004, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7611264462654909}}
{"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    :\u03c3, :hard\u03c3, :hardtanh, :relu,\n    :leakyrelu, :relu6, :rrelu, :elu, :gelu, :swish, :selu,\n    :celu, :softplus, :softsign, :log\u03c3, :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    \u03c3(x) = 1 / (1 + exp(-x))\n\nClassic [sigmoid](https://en.wikipedia.org/wiki/Sigmoid_function) activation\nfunction.\nUnicode `\u03c3` 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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \n        1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2860\u2824\u2816\u2812\u2812\u280b\u2809\u2809\u2809\u2809\u2809\u2809\u2502 \u03c3(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2880\u2860\u2816\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u28c0\u2814\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u284f\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2854\u280b\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u280a\u2801\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2824\u2824\u2824\u2812\u280a\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \n          \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800     \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800     \n\njulia> sigmoid === \u03c3\ntrue\n```\n\"\"\"\nfunction \u03c3(x)\n    t = exp(-abs(x))\n    ifelse(x \u2265 0, inv(1 + t), t / (1 + t))\nend\n\nconst sigmoid = \u03c3\n\n\"\"\"\n    hard\u03c3(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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \n        1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2816\u280b\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2502 hard\u03c3(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u28c0\u2864\u2812\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2860\u2814\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2857\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u280a\u2801\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2864\u2816\u280b\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2824\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518         \n          \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800         \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800         \n\njulia> lineplot(sigmoid, -5, 5, height=7)\n          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \n        1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2860\u2824\u2816\u2812\u2812\u280b\u2809\u2809\u2809\u2809\u2809\u2809\u2502 \u03c3(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2880\u2860\u2816\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u28c0\u2814\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u284f\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2854\u280b\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u280a\u2801\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2824\u2824\u2824\u2812\u280a\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502     \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \n          \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800     \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800     \n```\n\"\"\"\nhard\u03c3(x) = clamp((x + 3) / 6, 0, 1)\n\n# https://pytorch.org/docs/stable/generated/torch.nn.Hardsigmoid.html\n\nconst hardsigmoid = hard\u03c3\n\n\"\"\"\n    log\u03c3(x)\n\nReturn `log(\u03c3(x))` which is computed in a numerically stable way.\n\n```\njulia> lineplot(logsigmoid, -5, 5, height=7)\n           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \n         0 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2867\u2824\u2814\u2812\u2812\u2812\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2502 log\u03c3(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2816\u280a\u2809\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u2812\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2864\u2816\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u28c0\u2814\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2864\u2816\u280b\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n        -6 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \n           \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800        \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800        \n```\n\"\"\"\nlog\u03c3(x) = -softplus(-x)\n\nconst logsigmoid = log\u03c3\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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510            \n         1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u280b\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2502 hardtanh(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u28c0\u2864\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2880\u2864\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n   f(x)    \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u2864\u2877\u2825\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u2816\u2801\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u2816\u280b\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n        -1 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2814\u280b\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518            \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800            \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\n\njulia> lineplot(tanh, -2, 2, height=7)\n           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \n         1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2860\u2824\u2824\u2812\u2812\u2812\u280a\u2809\u2809\u2809\u2502 tanh(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2880\u2860\u2814\u280a\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2880\u2864\u2812\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n   f(x)    \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u2864\u2877\u2825\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2864\u2816\u2801\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2860\u2814\u280a\u2801\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n        -1 \u2502\u28c0\u28c0\u28c0\u2860\u2824\u2824\u2824\u2816\u2812\u280a\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800        \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800        \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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \n        2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u280b\u2502 relu(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u280a\u2801\u2800\u2800\u2502        \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2864\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2502        \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2864\u2816\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2860\u2816\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2860\u2816\u280b\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c7\u2814\u280b\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \n          \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800        \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800        \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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510       \n         2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u2812\u2809\u2502 #42(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2814\u280a\u2809\u2800\u2800\u2800\u2800\u2502       \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2816\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u28c0\u2824\u2816\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n           \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28e4\u28e4\u2864\u2867\u2836\u282d\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502       \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28c0\u28c0\u2824\u2824\u2812\u2812\u280b\u2809\u2801\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n        -1 \u2502\u28c0\u28c0\u2824\u2824\u2812\u2812\u280a\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518       \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800       \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800       \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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \n        6 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u280e\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2502 relu6(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2854\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2864\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2860\u280e\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2880\u2816\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2854\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2867\u280b\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518         \n          \u2800-10\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u280010\u2800         \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800         \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            \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \n         10 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b8\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2816\u280b\u2502 rrelu(x)\n            \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b8\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2816\u280b\u2801\u2800\u2800\u2800\u2502         \n            \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b8\u2800\u2880\u2860\u2814\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n   f(x)     \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u2864\u2824\u28e4\u28e4\u28a4\u28e4\u28e4\u2824\u2824\u2824\u28bc\u282e\u2825\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502         \n            \u2502\u28f0\u2880\u28c6\u2844\u28c4\u2844\u2860\u2870\u2826\u2837\u285c\u28a2\u2837\u2833\u2822\u280a\u2809\u2809\u2800\u2800\u2801\u2800\u2800\u2800\u2800\u2800\u28b8\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n            \u2502\u2803\u2809\u2819\u2818\u2803\u2808\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b8\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n        -10 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b8\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n            \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518         \n            \u2800-20\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u280010\u2800         \n            \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800         \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, \u03b1=1) = x > 0 ? x : \u03b1 * (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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510       \n         2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u2812\u2809\u2502 elu(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2814\u280a\u2809\u2800\u2800\u2800\u2800\u2502       \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2816\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u28c0\u2824\u2816\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n           \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u2864\u2867\u2836\u282d\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502       \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28c0\u28c0\u2824\u2814\u2812\u280b\u2801\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n        -1 \u2502\u2824\u2824\u2824\u2824\u2814\u2812\u2812\u2812\u280a\u2809\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502       \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518       \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800       \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800       \n\njulia> elu(-10f0)\n-0.9999546f0\n\njulia> elu(-10f0, 2)\n-1.9999092f0\n```\n\"\"\"\nelu(x, \u03b1=1) = ifelse(x \u2265 0, float(x), \u03b1 * (exp(x) - 1))\n\nderiv_elu(\u03a9, \u03b1=1) = ifelse(\u03a9 \u2265 0, one(\u03a9), \u03a9 + \u03b1)\n\n\"\"\"\n    gelu(x) = 0.5x * (1 + tanh(\u221a(2/\u03c0) * (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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \n         2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2814\u280a\u2502 gelu(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u280a\u2801\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u2812\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u28c0\u2860\u2824\u2812\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u28e4\u28e4\u28e4\u28e4\u28e4\u28e4\u28e4\u28e4\u2864\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28e4\u28e4\u28e4\u2864\u2867\u2836\u2836\u282d\u2825\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n        -1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800        \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800        \n```\n\"\"\"\nfunction gelu(x)\n    \u03b1 = oftf(x, 0.044715)\n    \u03bb = oftf(x, gelu_\u03bb)\n    x/2 * (1 + tanh(\u03bb * (x + \u03b1 * x^3)))\nend\n\nconst gelu_\u03bb = \u221a(2 / \u03c0)\n\n\"\"\"\n    swish(x) = x * \u03c3(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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \n         2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2502 swish(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2816\u280b\u2801\u2800\u2502         \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u2816\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2502         \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2880\u28c0\u2864\u2814\u280a\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n           \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u28e4\u28e4\u2864\u2867\u2834\u2836\u282f\u2825\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502         \n           \u2502\u2809\u2811\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2809\u2809\u2809\u2809\u2801\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n        -1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518         \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800         \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800         \n```\n\"\"\"\nswish(x) = x * \u03c3(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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \n        2 \u2502\u2822\u28c4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u2502 lisht(x)\n          \u2502\u2800\u2808\u2811\u28a6\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2864\u280a\u2801\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2808\u2823\u28c4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u2801\u2800\u2800\u2800\u2800\u2502         \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2811\u2886\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u2822\u2844\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2814\u280b\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2813\u2884\u2840\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2880\u2860\u2816\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n        0 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2813\u2826\u28c4\u28c0\u28c0\u28c7\u28c0\u28c0\u2824\u2812\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518         \n          \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800         \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800         \n```\n\"\"\"\nlisht(x) = x * tanh(x)\n\n\"\"\"\n    selu(x) = \u03bb * (x \u2265 0 ? x : \u03b1 * (exp(x) - 1))\n\n    \u03bb \u2248 1.05070...\n    \u03b1 \u2248 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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \n         3 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502 selu(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2860\u2824\u2814\u2812\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28c0\u2824\u2814\u2812\u280b\u2809\u2800\u2800\u2800\u2800\u2800\u2502        \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2880\u28c0\u2864\u2824\u2812\u280a\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u28c9\u2869\u282d\u281b\u284f\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28c0\u28c0\u2864\u2824\u2814\u2812\u280a\u2809\u2801\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n        -2 \u2502\u2812\u2812\u2809\u2809\u2809\u2809\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800        \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800        \n\njulia> selu(-10f0)\n-1.7580194f0\n```\n\"\"\"\nfunction selu(x)\n    \u03bb = oftf(x, selu_\u03bb)\n    \u03b1 = oftf(x, selu_\u03b1)\n    \u03bb * ifelse(x > 0, x, \u03b1 * (exp(x) - 1))\nend\n\nconst selu_\u03bb = 1.0507009873554804934193349852946\nconst selu_\u03b1 = 1.6732632423543772848170429916717\n\nfunction deriv_selu(\u03a9)\n    \u03bb = oftf(\u03a9, selu_\u03bb)\n    \u03b1 = oftf(\u03a9, selu_\u03b1)\n    ifelse(\u03a9 > 0, \u03bb, \u03a9 + \u03b1 * \u03bb)\nend\n\n\"\"\"\n    celu(x, \u03b1=1) = x \u2265 0 ? x : \u03b1 * (exp(x/\u03b1) - 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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \n         2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2824\u2812\u2809\u2502 celu(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2814\u280a\u2809\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2816\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u28c0\u2824\u2816\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u2864\u2867\u2836\u282d\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28c0\u28c0\u2824\u2814\u2812\u280b\u2801\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n        -1 \u2502\u2824\u2824\u2824\u2824\u2814\u2812\u2812\u2812\u280a\u2809\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800        \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800        \n\njulia> celu(-10f0)\n-0.9999546f0\n```\n\"\"\"\ncelu(x, \u03b1=1) = ifelse(x \u2265 0, float(x), \u03b1 * (exp(x/\u03b1) - 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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \n        4 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2816\u280b\u2502 trelu(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2816\u280b\u2801\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2814\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2834\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28e0\u2824\u2812\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u284f\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c7\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502         \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518         \n          \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28004\u2800         \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800         \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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510            \n         1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28c0\u28c0\u28c0\u28c0\u2824\u2824\u2824\u2824\u2824\u2502 softsign(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u28c0\u2864\u2816\u2812\u280b\u2809\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2854\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n   f(x)    \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u286f\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u2801\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28c0\u28c0\u2824\u2824\u2812\u280b\u2801\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n        -1 \u2502\u2812\u2812\u2812\u2812\u2812\u280a\u2809\u2809\u2809\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518            \n           \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800            \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800            \n\njulia> lineplot!(ans, tanh)\n           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510            \n         1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2880\u2864\u2816\u280a\u2809\u2809\u2809\u28c9\u28c9\u28c9\u28c9\u28c9\u282d\u282d\u282d\u282d\u282d\u2502 softsign(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2854\u28c3\u2864\u2816\u2812\u280b\u2809\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502 tanh(x)    \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28e7\u285e\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n   f(x)    \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u286f\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2874\u2803\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28c0\u28c0\u2824\u2824\u2812\u288b\u2815\u2801\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n        -1 \u2502\u28d2\u28d2\u28d2\u28d2\u28d2\u28ca\u28c9\u28c9\u28c9\u28c9\u28c1\u28c0\u28c0\u2860\u2824\u2812\u2801\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518            \n           \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800            \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800            \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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510            \n        4 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502 softplus(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2502            \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2814\u280a\u2801\u2800\u2502            \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2814\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2502            \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u28c0\u2860\u2824\u2812\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28c0\u2867\u2824\u2812\u280a\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2860\u2824\u2824\u2824\u2824\u2814\u2812\u2812\u281a\u2809\u2809\u2801\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518            \n          \u2800-3\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28003\u2800            \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800            \n\njulia> lineplot!(ans, relu)\n          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510            \n        4 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502 softplus(x)\n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28e0\u2502 relu(x)    \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28e0\u2874\u281e\u280b\u2801\u2502            \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28e4\u2874\u281e\u280b\u2801\u2800\u2800\u2800\u2800\u2502            \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u28c0\u2860\u28a4\u2872\u281d\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u28c0\u2867\u2824\u2812\u280a\u28c9\u2825\u281a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n        0 \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28e0\u28e4\u28e4\u28e4\u28e4\u28d4\u28d2\u28d2\u28da\u28c9\u28c9\u28c1\u28c0\u28c7\u2834\u2812\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502            \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518            \n          \u2800-3\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28003\u2800            \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800            \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          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510           \n        5 \u2502\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502 logcosh(x)\n          \u2502\u2809\u2822\u28c4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u280b\u2502           \n          \u2502\u2800\u2800\u2800\u2811\u2822\u28c4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2814\u280a\u2801\u2800\u2800\u2502           \n   f(x)   \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2811\u2826\u28c0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2502           \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2811\u2826\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2864\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502           \n          \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2813\u2826\u2840\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2880\u2864\u2812\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502           \n        0 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2811\u2822\u2884\u28c0\u28c0\u28c7\u28c0\u2860\u2814\u280a\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502           \n          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518           \n          \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800           \n          \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800           \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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \n         5 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2816\u280b\u2502 mish(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2812\u2801\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u2814\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n   f(x)    \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2880\u2860\u2816\u280b\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2880\u2864\u2816\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2502\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28e7\u28d4\u28ca\u28c1\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u28c0\u2502        \n        -1 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2809\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502        \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \n           \u2800-5\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28005\u2800        \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800        \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           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510              \n         3 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502 tanhshrink(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2860\u2824\u2816\u280a\u2502              \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28c0\u2860\u2824\u2812\u280a\u2809\u2801\u2800\u2800\u2800\u2800\u2502              \n   f(x)    \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28a4\u28e4\u2864\u2824\u2824\u2824\u2824\u2824\u2824\u2877\u2836\u2836\u2836\u2836\u2836\u282e\u282d\u2825\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502              \n           \u2502\u2800\u2800\u2800\u2800\u2800\u28c0\u2860\u2834\u2812\u280a\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n           \u2502\u2860\u2834\u2812\u280a\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n        -3 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518              \n           \u2800-3\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28003\u2800              \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800              \n\njulia> tanhshrink.((-10f0, 10f0))\n(-9.0f0, 9.0f0)\n```\n\"\"\"\ntanhshrink(x) = x - tanh(x)\n\n\"\"\"\n    softshrink(x, \u03bb=0.5) =\n        (x \u2265 \u03bb ? x - \u03bb : (-\u03bb \u2265 x ? x + \u03bb : 0))\n\nSee [\"Softshrink Activation Function\"](https://www.gabormelli.com/RKB/Softshrink_Activation_Function).\n\n```\njulia> lineplot(softshrink, -2, 2, height=7)\n           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510              \n         2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2502 softshrink(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28c0\u2864\u2814\u2812\u2809\u2801\u2502              \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2824\u2812\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n   f(x)    \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28e4\u2864\u2824\u2824\u2824\u2824\u2824\u2824\u2867\u2824\u2824\u2824\u2824\u2836\u282e\u282d\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502              \n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28c0\u2824\u2816\u2812\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n           \u2502\u2800\u28c0\u2824\u2814\u2812\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n        -2 \u2502\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518              \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800              \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800              \n\njulia> lineplot!(ans, tanhshrink)\n           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510              \n         2 \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2502 softshrink(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28c0\u2864\u2814\u2812\u28c9\u2861\u2502 tanhshrink(x)\n           \u2502\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28c0\u2864\u2824\u28d2\u28cb\u2825\u2824\u2812\u280a\u2809\u2801\u2800\u2502              \n   f(x)    \u2502\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u28e4\u28e4\u28e4\u28e4\u2864\u2824\u2824\u2824\u2824\u2824\u2824\u2877\u2836\u2836\u2836\u2836\u2836\u283e\u283f\u282f\u282d\u282d\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2502              \n           \u2502\u2800\u2880\u28c0\u2860\u2824\u2816\u2892\u28cb\u282d\u2817\u2812\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n           \u2502\u280a\u28c9\u2824\u2814\u2812\u280b\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n        -2 \u2502\u2809\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2502              \n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518              \n           \u2800-2\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28002\u2800              \n           \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800x\u2800\n\njulia> softshrink.((-10f0, 10f0))\n(-9.5f0, 9.5f0)\n```\n\"\"\"\nsoftshrink(x, \u03bb=oftf(x, 0.5)) = min(max(0, x - \u03bb), x + \u03bb)\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\u03c3(0.2f0)\n0.53333336f0\n```\n\"\"\"\n@inline function sigmoid_fast(x::Real)\n    t = @fastmath exp(-abs(x))\n    y = ifelse(x \u2265 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(\u03a9))),\n    (:\u03c3,            :(conj(\u03a9 * (1 - \u03a9)))),\n    (:elu,          :(deriv_elu(\u03a9))),\n    (:softplus,     :(\u03c3(x))),\n\n    (:tanh_fast,    :(conj(1 - \u03a9^2))),\n    (:sigmoid_fast, :(conj(\u03a9 * (1 - \u03a9)))),\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        \u03a9 = $f.(x)\n        function $pullback(\u0394)\n            x_thunk = InplaceableThunk(\n                dx -> @.(dx += \u0394 * $df),\n                @thunk @.(\u0394 * $df)\n            )\n            NoTangent(), NoTangent(), x_thunk\n        end\n        return \u03a9, $pullback\n    end\nend\n\nBINARY_ACTS = [ # f, df1, df2\n    (:elu, :(deriv_elu(\u03a9, 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        \u03a9 = $f.(x1, x2)\n        function $pullback(\u0394) \n            NoTangent(), NoTangent(), @.(\u0394 * $df1), @.(\u0394 * $df2)\n        end\n        return \u03a9, $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    \u03bb = 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            \u03bb[i] += log(abs(R[i, i]))\n        end\n    end\n    \u03bb./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    \u03bb = 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            \u03bb[i] += log(abs(R[i, i]))\n        end\n    end\n    \u03bb./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\u00e8 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\u00b0 55' 31'').  Its\ncompanion, Alcor, has coordinates (ra, dec) = (13h 25m 13.5s, +54\u00b0 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    \u03bc :: T\n    \u03c3 :: 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    \u03bc, \u03c3 = mean(data), std(data)\n    return ZeroMeanUnitVarianceScaling(\u03bc, \u03c3)\nend\n\nscale(x, s::ZeroMeanUnitVarianceScaling) = (x .- s.\u03bc) / s.\u03c3\nunscale(y, s::ZeroMeanUnitVarianceScaling) = s.\u03c3 * y .+ s.\u03bc\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 = - (\u03c0^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 * \u03c0)\n    else\n        z = -2 * x\u00b2\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, \u03c1 = args    # sample size and AR parameter\n\tx = randn(n)     # an exogenous regressor\n\t# make the AR1 errors\n    \u03f5 = zeros(n)\n    \u03f5[1] = randn()/sqrt(1-\u03c1^2)\n\tfor t = 2:n\n        \u03f5[t] = \u03c1*\u03f5[t-1] + randn()\n    end\n\t# the dep var\n\ty = 1. .+ x .+ \u03f5\n\t# OLS\n\tx = [ones(n) x]\n\t\u03b2_ols = x \\ y\n\t# estimate \u03c1\n\te = y - x*\u03b2_ols\n    # estimating \u03c1 using correlation, to keep in stationary region\n    \u03c1hat = cor(e[1:end-1], e[2:end]) \n\tystar = y - \u03c1hat.*lag(y,1)\n\txstar = x - \u03c1hat*lag(x,1)\n    ystar[1] = sqrt(1-\u03c1hat^2) .*y[1]\n    xstar[1,:] = sqrt(1-\u03c1hat^2) .* x[1,:]\n\t\u03b2_gls = xstar\\ystar\n\t\u03b2_ols, \u03b2_gls\nend\n\n# do the Monte Carlo\nn = 30\n\u03c1 = 0.9\nargs = (n, \u03c1)\nreps = 1000\n\u03b2_ols = zeros(reps,2)\n\u03b2_gls = zeros(reps,2)\nfor i = 1:reps\n    \u03b2_ols[i,:], \u03b2_gls[i,:] = wrapper(args)\nend    \n\n# analyze results\np1 = histogram(\u03b2_ols[:,2],bins=30, legend=false, xlabel=\"OLS\")\np2 = histogram(\u03b2_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": "@doc raw\"\"\"\n    Triangle3\n\nAn object `t` of the type [`Triangle3`](@ref) is a triangle in the\nthree-dimensional Euclidean space ``\u0395^2``.\n\nAs the triangle is not a full-dimensional object, there is only a test whether\na point lies on the triangle or not.\n\"\"\"\nTriangle3\n\n\"\"\"\n    Triangle3(p::Point3, q::Point3, r::Point3)\n\nIntroduces a triangle `t` with vertices `p`, `q` and `r`.\n\"\"\"\nTriangle3(p::Point3, q::Point3, r::Point3)\n\n\"\"\"\n    ==(t\u2081::Triangle3, t\u2082::Triangle3)\n\nTest for equality: two triangles `t\u2081` and `t\u2082` are equal, iff there exists a\ncyclic permutation of the vertices of `t\u2082`, such that  they are equal to the\nvertices of `t\u2081`.\n\"\"\"\n==(t\u2081::Triangle3, t\u2082::Triangle3)\n\n\"\"\"\n    vertex(t::Triangle3, i::Integer)\n\nReturns the `i`\u1d57\u02b0 vertex modulo 3 of `t`.\n\"\"\"\nvertex(t::Triangle3, i::Integer)\n\n\"\"\"\n    supporting_plane(t::Triangle3)\n\nReturns the supporting plane of `t`, with same orientation.\n\"\"\"\nsupporting_plane(t::Triangle3)\n\n\"\"\"\n    is_degenerate(t::Triangle3)\n\nTriangle `t` is degenerate, if the vertices are collinear.\n\"\"\"\nis_degenerate(t::Triangle3)\n\n\"\"\"\n    squared_area(t::Triangle3)\n\nReturns a square of the area of `t`.\n\"\"\"\nsquared_area(t::Triangle3)\n\n\"\"\"\n    bbox(t::Triangle3)\n\nReturns a bounding box containing `t`.\n\"\"\"\nbbox(t::Triangle3)\n\n\"\"\"\n    transform(t::Triangle3, at::AffTransformation3)\n\nReturns the triangle obtained by applying `at` on the three vertices of `t`.\n\"\"\"\ntransform(t::Triangle3, at::AffTransformation3)\n", "meta": {"hexsha": "899ab10c4af47c5c8ca9e8da3ca949c420191050", "size": 1448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/triangle_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/triangle_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/triangle_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": 20.9855072464, "max_line_length": 78, "alphanum_fraction": 0.6878453039, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "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    \u03b3 = zero(T)\n    @inbounds @simd for i in 1:N - k\n        \u03b3 += (z[i + k] - m) * (z[i] - m)\n    end\n    return \u03b3 / 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    \u03b3 = Vector{T}(undef, k)\n    for i in 1:k\n        \u03b3[i] = autocovariance(z, i - 1)\n    end\n    \u0393 = Matrix{T}(undef, k, k)\n    for j in 1:k\n        for i in 1:k\n            \u0393[i,j] = \u03b3[abs(i - j) + 1]\n        end\n    end\n    return \u0393\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    \u03a1 = autocorrelation_matrix(z, k)\n    \u03a1star = copy(\u03a1)\n    \u03a1star[1:k - 1,k] = \u03a1star[2:k,1]\n    \u03a1star[k,k] = autocorrelation(z, k)\n    return det(\u03a1star) / det(cholesky(Symmetric(\u03a1)))\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(\u03c1, V)\n\nCompute the dynamic pressure given density ``\\\\rho`` and speed ``V``.\n\"\"\"\ndynamic_pressure(\u03c1, V) = 1/2 * \u03c1 * 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(\u03a9, V, L)\n\nCompute the non-dimensional angular velocity coefficient given angular speed ``\\\\Omega``, reference speed ``V``, and reference length ``L``.\n\"\"\"\nrate_coefficient(\u03a9, V, L) = \u03a9 * L / 2V\n\n\"\"\"\n    pressure_coefficient(force, \u03c1, V, S)\n\nCompute the pressure coefficient given force, reference density ``\\\\rho``, speed ``V`` and area ``S``.\n\"\"\"\npressure_coefficient(force, \u03c1, V, S) = force_coefficient(force, dynamic_pressure(\u03c1, 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(\u03a9, V, b, c) = rate_coefficient.(\u03a9, V, [b, c, b])\n\n\n\"\"\"\n    aerodynamic_coefficients(force, moment, \u03a9, V, S, b, c, \u03c1)\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, \u03a9, V, S, b, c, \u03c1)\n    q = dynamic_pressure(\u03c1, V)\n\n    [ force_coefficient(force, q, S) \t\t ;\n      moment_coefficient(moment, q, S, b, c) ;\n      rate_coefficient(\u03a9, 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\u0304\", \"q\u0304\", \"r\u0304\" ] ]\n    data = [ coeffs nf_coeffs [ ff_coeffs; fill(\"\u2014\", 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 = [\"\u2202CD\", \"\u2202CY\", \"\u2202CL\", \"\u2202Cl\", \"\u2202Cm\", \"\u2202Cn\"]\n    nf_vars = [ \"$name\" \"\" \"Nearfield\" \"Stability\" \"Derivatives\" \"\" ; \"\" \"\u2202\u03b1, 1/rad\" \"\u2202\u03b2, 1/rad\" \"\u2202p\u0304\" \"\u2202q\u0304\" \"\u2202r\u0304\" ]\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(\u03c1, V, c, \u03bc) = \u03c1 * V * c / \u03bc\nreynolds_number(V, c, \u03bd) = V * c / \u03bd\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": "using Symbolics\n\nfunction lotka_volterra!(du, u, p, t)\n  x, y = u\n  \u03b1, \u03b2, \u03b4, \u03b3 = p\n  du[1] = dx = \u03b1*x - \u03b2*x*y\n  du[2] = dy = -\u03b4*y + \u03b3*x*y\nend\n\n@variables t du[1:2] u[1:2] p[1:4]\nlotka_volterra!(du, u, p, t)\nD = Differential(t)\nf = build_function((@. D(u) ~ du), u, p, t, target=Symbolics.JuliaTarget())\n\nBase.remove_linenums!(f[1])\n\n", "meta": {"hexsha": "4222c3349b9fac603353a321c47292f5463778b5", "size": 333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "research/lv_01.jl", "max_stars_repo_name": "StanJulia/DiffEqBayesStan.jl", "max_stars_repo_head_hexsha": "6287f04fba4f7bf0b1c8d0e6c1dc39e614d7e24d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "research/lv_01.jl", "max_issues_repo_name": "StanJulia/DiffEqBayesStan.jl", "max_issues_repo_head_hexsha": "6287f04fba4f7bf0b1c8d0e6c1dc39e614d7e24d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-07-28T14:51:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T15:04:40.000Z", "max_forks_repo_path": "research/lv_01.jl", "max_forks_repo_name": "StanJulia/DiffEqBayesStan.jl", "max_forks_repo_head_hexsha": "6287f04fba4f7bf0b1c8d0e6c1dc39e614d7e24d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T11:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T11:31:40.000Z", "avg_line_length": 19.5882352941, "max_line_length": 75, "alphanum_fraction": 0.5825825826, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7610754842442857}}
{"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": "\nfunction sp_value_from_primitive_values(x...)\n    #=\n    assume the values provided are x1,x2...\n    generates the list of values for e1,e2...\n    For example, x=1,y=2,z=3\n    Then e1=x+y+z = 6,e2=xy+yz+xz = 11, e3=xyz = 6\n    =#\n    length(x) < 1 && return []\n    p = [1,x[1]]\n    for i = 2:length(x)\n        tmp = [0,x[i]*p...]\n        tmp[1:length(p)] += p\n        p=tmp\n    end\n    return p[2:end]\nend\n\nfunction evaluate_monomial(sp_values,m::semi_elementary_monomial)\n    if !is_elementary(m)\n        throw(ArgumentError(\"currently only support evaluating elementary monomials\"))\n    elseif length(sp_values) != dim(m)\n        throw(DimensionMismatch(\"first argument must have same length\"))\n    end\n    return prod([sp_values[i]^m.powers[i] for i=1:length(sp_values)])\nend\n\nfunction evaluate_polynomial(sp_values,m::semi_elementary_polynomial)\n    return sum([evaluate_monomial(sp_values,k)*v for (k,v) in m.terms])\nend\n", "meta": {"hexsha": "eced4df55d0b3ec86f32925f46ba68479dcb2540", "size": 927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evaluate.jl", "max_stars_repo_name": "yushoteke/SymmetricPolynomials", "max_stars_repo_head_hexsha": "fc721fbd6995e123f246cb69f1fbac2eb1844a2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-28T14:20:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T15:37:23.000Z", "max_issues_repo_path": "src/evaluate.jl", "max_issues_repo_name": "yushoteke/SymmetricPolynomials", "max_issues_repo_head_hexsha": "fc721fbd6995e123f246cb69f1fbac2eb1844a2c", "max_issues_repo_licenses": ["MIT"], "max_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": "yushoteke/SymmetricPolynomials", "max_forks_repo_head_hexsha": "fc721fbd6995e123f246cb69f1fbac2eb1844a2c", "max_forks_repo_licenses": ["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.9032258065, "max_line_length": 86, "alphanum_fraction": 0.6494066882, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7610754812629354}}
{"text": "function factorial(n)\n\tfact = 1\n\tfor i in 1:n\n\t\tfact *= i\n\tend\n\treturn fact \nend\n\nprintln(@time factorial(49))", "meta": {"hexsha": "ebdd23e26c2df442daa8182c338263bf9d4b428d", "size": 110, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "factorial.jl", "max_stars_repo_name": "Antoniii/Sea-Coffe_with_Julia", "max_stars_repo_head_hexsha": "090229e1a68ef1324335b7147a0286b1778ea39f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "factorial.jl", "max_issues_repo_name": "Antoniii/Sea-Coffe_with_Julia", "max_issues_repo_head_hexsha": "090229e1a68ef1324335b7147a0286b1778ea39f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "factorial.jl", "max_forks_repo_name": "Antoniii/Sea-Coffe_with_Julia", "max_forks_repo_head_hexsha": "090229e1a68ef1324335b7147a0286b1778ea39f", "max_forks_repo_licenses": ["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.2222222222, "max_line_length": 28, "alphanum_fraction": 0.6727272727, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259038, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.761075480676859}}
{"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": "using MultipleViewGeometry, Base.Test\nusing MultipleViewGeometry.ModuleCostFunction\nusing MultipleViewGeometry.ModuleTypes\nusing MultipleViewGeometry.ModuleConstraints\nusing MultipleViewGeometry.ModuleConstruct\nusing MultipleViewGeometry.ModuleDraw\nusing MultipleViewGeometry.ModuleTriangulation\nusing BenchmarkTools, Compat\nusing StaticArrays\nusing  MAT, Plots\n\n# Load MATLAB matrices that represent a pair of images and that contain\n# a set of manually matched corresponding points.\nfile = matopen(\"./data/teapot.mat\")\nX = read(file,\"pts3D\")\n# X is a 4 x N matrix, where N is the number of points expressed in homogeneous\n# coordinates.\nX = X[:,1:10:end]\nclose(file)\n\n# Fix random seed.\nsrand(1234)\nplotlyjs()\n\n# Transform the point cloud so that it will be oriented upright and\n# in front of two cameras which we will define next.\nT1 = eye(4)\nT1[:,4] = -mean(X,2)\nT2 = [1 0 0 0;\n      0 1 0 0;\n      0 0 1 -2500;\n      0 0 0 1]\nR = eye(4)\nR[1:3,1:3] = rotx(deg2rad(90))\nX = T2*R*T1*X;\n\n# Convert the 4 x N matrix into a list of 3D points expressed in homogeneous coordinates.\n\ud835\udcb3 = [Point3DH(X[1,i],X[2,i],X[3,i],1.0) for i = 1:size(X,2)]\n\n# Intrinsic and extrinsic parameters of camera one.\n\ud835\udc0a\u2081 = eye(3)\n\ud835\udc11\u2081 =  eye(3)\n\ud835\udc2d\u2081 = [0.0, 0.0, 0.0]\n\ud835\udc1c\u2081 = [0.0, 0.0, 0.0]\n\ud835\udc04\u2081 = [\ud835\udc11\u2081 \ud835\udc2d\u2081]\n\n# Intrinsic and extrinsic parameters of camera two.\n\ud835\udc0a\u2082 = eye(3)\n\ud835\udc11\u2082 = eye(3)\n\ud835\udc2d\u2082 = [450.0,   0.0, 0.0]\n\ud835\udc1c\u2082 = [0.0, 0.0, 0.0]\n\ud835\udc04\u2082 = [\ud835\udc11\u2082 \ud835\udc2d\u2082]\n\n# Camera projection matrices.\n\ud835\udc0f\u2081 = construct(ProjectionMatrix(),\ud835\udc0a\u2081,\ud835\udc11\u2081,\ud835\udc2d\u2081)\n\ud835\udc0f\u2082 = construct(ProjectionMatrix(),\ud835\udc0a\u2082,\ud835\udc11\u2082,\ud835\udc2d\u2082)\n\n# Set of corresponding points.\n\u2133 = project(Pinhole(),\ud835\udc0f\u2081,\ud835\udcb3)\n\u2133\u02b9 = project(Pinhole(),\ud835\udc0f\u2082,\ud835\udcb3)\n\n# Visualise the data points\np1 = Plots.plot(X[1,:],X[2,:],X[3,:],seriestype = :scatter, ms=1,grid = false, box = :none, legend = false)\ndraw!(WorldCoordinateSystem3D(), 1, p1)\ndraw!(Camera3D(), \ud835\udc0a\u2081, \ud835\udc11\u2081, \ud835\udc2d\u2081, 1, p1)\ndraw!(Camera3D(), \ud835\udc0a\u2082, \ud835\udc11\u2082, \ud835\udc2d\u2082, 1, p1)\n\n\n# Plot the projections of the point cloud in the image pair.\np2 =  Plots.plot();\nfor n = 1:length(\u2133)\n    m = \u2133[n]\n    Plots.plot!([m[1]],[m[2]], grid = false, box = :none, legend = false,\n                    seriestype = :scatter, ms = 2, markercolor=:Black,\n                    aspect_ratio = :equal, yflip = true)\nend\n\np3 =  Plots.plot();\nfor n = 1:length(\u2133\u02b9)\n    m\u02b9 = \u2133\u02b9[n]\n    Plots.plot!([m\u02b9[1]],[m\u02b9[2]], grid = false, box = :none, legend = false,\n                    seriestype = :scatter, ms = 2, markercolor=:Black,\n                    aspect_ratio = :equal, yflip = true)\nend\n\n# Visualise the 3D point cloud, as well as the projected images.\nl = @layout [ a; [b c] ]\np4 = Plots.plot(p1,p2, p3, layout = l)\n\n# Estimate of the fundamental matrix and the true fundamental matrix.\n\ud835\udc05 = estimate(FundamentalMatrix(), DirectLinearTransform(), (\u2133, \u2133\u02b9))\n\ud835\udc04 = construct(EssentialMatrix(), \ud835\udc05,  \ud835\udc0a\u2081, \ud835\udc0a\u2082)\n\n\ud835\udc0f\u2081, \ud835\udc0f\u2082 = construct(ProjectionMatrix(), \ud835\udc04, (\u2133, \u2133\u02b9))\n\n\ud835\udcb4 = triangulate(DirectLinearTransform(),\ud835\udc0f\u2081,\ud835\udc0f\u2082,(\u2133,\u2133\u02b9))\nY = reinterpret(Float64,map(SVector{4,Float64},\ud835\udcb4),(4,length(\ud835\udcb4)))\n\n# The point cloud can be reconsructed only up to an unknown scale factor.\np5 = Plots.plot(Y[1,:],Y[2,:],Y[3,:],seriestype = :scatter, ms=1,grid = false, box = :none, legend = false)\ndraw!(WorldCoordinateSystem3D(), 0.002, p5)\ndraw!(Camera3D(), \ud835\udc0a\u2081, \ud835\udc0f\u2081[1:3,1:3], \ud835\udc0f\u2081[:,4], 0.002, p5)\ndraw!(Camera3D(), \ud835\udc0a\u2082, \ud835\udc0f\u2082[1:3,1:3], \ud835\udc0f\u2082[:,4], 0.002, p5)\n\ndisplay(p4)\n#display(p5)\n", "meta": {"hexsha": "d44b6ff4dcf66ac8dcbed5673837b23959724fb4", "size": 3304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/example_unrectified_triangulate.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": "demo/example_unrectified_triangulate.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": "demo/example_unrectified_triangulate.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": 30.8785046729, "max_line_length": 107, "alphanum_fraction": 0.6634382567, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259038, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7610754764323499}}
{"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\u221a(-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": "function calc_width_ngon(a,b)\r\nif length(a) == length(b) && length(a) >= 2\r\n    # SIDES\r\n    v = zeros(length(a)+1);\r\n    v[1] = abs(a[1]+im*b[1]);\r\n    for i = 2:length(a)\r\n        v[i] = abs((a[i]-a[i-1])+im*(b[i]-b[i-1]));\r\n    end\r\n    v[length(a)+1] = abs(a[length(a)]+im*b[length(a)]);\r\n    # HEIGHTS\r\n    h = zeros(length(a)+1);\r\n    # h1\r\n    j = 1;\r\n    while j <= length(a)\r\n        h1 = abs(a[j]*(b[1]-b[j])-b[j]*(a[1]-a[j]))/v[1];\r\n        if h1 > h[1]\r\n            h[1] = h1;\r\n        end\r\n        j = j+1;\r\n    end\r\n    # hi\r\n    for i = 2:length(a)\r\n        h[i] = abs(a[i-1]*b[i]-b[i-1]*a[i])/v[i];\r\n        j = 1;\r\n        while j <= length(a)\r\n            hi = abs((a[i-1]-a[j])*(b[i]-b[j])-(b[i-1]-b[j])*(a[i]-a[j]))/v[i];\r\n            if hi > h[i]\r\n                h[i] = hi;\r\n            end\r\n            j = j+1;\r\n        end\r\n    end\r\n    # hn\r\n    j = 1;\r\n    while j <= length(a)\r\n        hn = abs((a[length(a)]-a[j])*b[j]-(b[length(a)]-b[j])*a[j])/v[length(a)+1];\r\n        if hn > h[length(a)+1]\r\n            h[length(a)+1] = hn;\r\n        end\r\n        j = j+1;\r\n    end\r\n    # WIDTH\r\n    W = minimum(h);\r\n    return W\r\nend\r\nend", "meta": {"hexsha": "71c6e854b2ba9a4e15af35eb34765ed87ed8a06f", "size": 1153, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "calc_width_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": "calc_width_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": "calc_width_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": 25.0652173913, "max_line_length": 84, "alphanum_fraction": 0.3686036427, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7610598149255045}}
{"text": "using LinearAlgebra\ninclude(\"../src/ExactDiagonalization.jl\")\nusing .ExactDiagonalization\nusing Test\n#-------------------------------------------------------------------------------------------------------------------------\n# XY Model\n#-------------------------------------------------------------------------------------------------------------------------\n@testset \"XY\" begin\n    L = 4\n    println(\"------------------------------\")\n    println(\"XY Model with L = $L\")\n    println(\"------------------------------\")\n    basis = projectedbasis(x->sum(x)==2, L)\n    println(\"Basis Vector:\")\n    for i=1:length(basis.I)\n        change!(basis, i) \n        println(\"$i : |$(basis.dgt...)\u27e9\") \n    end\n    X = [0 1; 1 0]\n    Y = [0 -1; 1 0] * 1im\n    mat = div.(real(kron(X, X) + kron(Y, Y)), 2)\n    H = trans_inv_operator(mat, 2, basis)\n    Hmat = Array(H)\n    println(\"\\nMatrix:\")\n    display(Hmat)\n    print(\"\\n\")\n    HXY = [0  1  0  0  1  0; \n           1  0  1  1  0  1; \n           0  1  0  0  1  0; \n           0  1  0  0  1  0; \n           1  0  1  1  0  1; \n           0  1  0  0  1  0]\n    @test Hmat == HXY\nend\n\n#-------------------------------------------------------------------------------------------------------------------------\n# PXP Model\n#-------------------------------------------------------------------------------------------------------------------------\n@testset \"PXP\" begin\n    L = 4\n    println(\"\\n------------------------------\")\n    println(\"PXP Model with L = $L\")\n    println(\"------------------------------\")\n    pxpf(v::Vector{Int}) = all(v[i]==0 || v[mod(i, length(v))+1]==0 for i=1:length(v))\n    basis = projectedbasis(pxpf, L)\n    println(\"Basis Vector:\")\n    for i=1:length(basis.I)\n        change!(basis, i) \n        println(\"$i : |$(basis.dgt...)\u27e9\") \n    end\n    P = Diagonal([1, 1, 1, 0, 1, 1, 0, 0])\n    X = [0 1; 1 0]\n    mat = P * kron(I(2), X, I(2)) * P\n    H = trans_inv_operator(mat, 3, basis)\n    Hmat = Array(H)\n    println(\"\\nMatrix:\")\n    display(Hmat)\n    print(\"\\n\")\n    HPXP = [0  1  1  1  0  1  0; \n            1  0  0  0  1  0  0; \n            1  0  0  0  0  0  1; \n            1  0  0  0  1  0  0; \n            0  1  0  1  0  0  0; \n            1  0  0  0  0  0  1; \n            0  0  1  0  0  1  0]\n    @test Hmat == HPXP\nend\n", "meta": {"hexsha": "2614bc44ed0d9ef3c67ba67e6167e83909d38848", "size": 2279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ProjectedBasisTest.jl", "max_stars_repo_name": "jayren3996/ExactDiagonalization.jl", "max_stars_repo_head_hexsha": "5022d5868f9f5c9604577b1d217b5a51a49bafe3", "max_stars_repo_licenses": ["MIT"], "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/ProjectedBasisTest.jl", "max_issues_repo_name": "jayren3996/ExactDiagonalization.jl", "max_issues_repo_head_hexsha": "5022d5868f9f5c9604577b1d217b5a51a49bafe3", "max_issues_repo_licenses": ["MIT"], "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/ProjectedBasisTest.jl", "max_forks_repo_name": "jayren3996/ExactDiagonalization.jl", "max_forks_repo_head_hexsha": "5022d5868f9f5c9604577b1d217b5a51a49bafe3", "max_forks_repo_licenses": ["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.5147058824, "max_line_length": 122, "alphanum_fraction": 0.3339183853, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094438, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7610598007963182}}
{"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    \u03b1::Real\n    \u025b::Real\n    \u03bb::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.\u03bb\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), \u03b1 = $(R.\u03b1), \u025b = $(R.\u025b))\")\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, \u03b1=1.0, \u025b=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) / \u025b)`: 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* `\u025b::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* `\u03b1::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             \u025b::Real=1.0,\n             kernel::Union{Nothing, Function}=(x, y) -> exp(-sum((x .- y) .^ 2) / convert(T, \u025b)), \n             maxoutdim::Int=2, \n             t::Int=1, \n             \u03b1::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 \u03b1 > 0\n        @assert issymmetric(L)\n    end\n\n    # Calculate Laplacian & normalize it\n    if \u03b1 > 0\n        D = transpose(sum(L, dims=1))\n        L ./= (D * transpose(D)) .^ convert(T, \u03b1)\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\u207b\u1d45 = inv(D^\u03b1)\n    # L\u1d45 = D\u207b\u1d45*L*D\u207b\u1d45\n    # D\u1d45 = Diagonal(vec(sum(L\u1d45, dims=1)))\n    # M = inv(D\u1d45)*L\u1d45\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    \u03bb = real.(F.values) \n    idx = sortperm(\u03bb, rev=true)[2:maxoutdim+1]\n    \u03bb = \u03bb[idx]\n    V = real.(F.vectors[:, idx])\n    Y = (\u03bb .^ t) .* V'\n\n    return DiffMap{T}(t, \u03b1, \u025b, \u03bb, 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0d1581d2-502e-11eb-2b2b-e3cc836fc2b0\n# The Call Stack of Recursion\n\n# \u2554\u2550\u2561 130ca5e8-502e-11eb-3f82-5ff3930f7421\n# Recurrence Relations\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25004aebe8f8-502d-11eb-1925-694f35421317\n# \u2560\u25508c30ca4a-502d-11eb-2c0b-398047ab685f\n# \u2560\u25500d1581d2-502e-11eb-2b2b-e3cc836fc2b0\n# \u2560\u2550130ca5e8-502e-11eb-3f82-5ff3930f7421\n# \u2560\u25501b0fe3ae-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# \u2554\u2550\u2561 750ded6c-f15d-11eb-02ef-5156d6bf3200\nusing BenchmarkTools, CUDA, Images, PlutoUI\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 062c93ab-df7e-485e-a4bc-f7e39c013c3f\nmd\"#### A macro to view stdout\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9da77179-daff-4eb7-b95b-1c5b9da5e524\nmd\"#### The escape/iteration function\"\n\n# \u2554\u2550\u2561 81fa04e2-147d-496d-bea4-cfe14a67868a\nfunction escape(z0, c, maxiter)\n    z = z0\n    for i \u2208 1:maxiter\n        abs2(z) > 4 && return (i-1) % UInt8\n         z = z*z + c\n    end\n    return maxiter % UInt8\nend\n\n# \u2554\u2550\u2561 62c83a9e-d5ba-4479-b3b4-4584bbf2b70f\n@terminal @code_warntype escape(1.0+1im, 0+0.5im, 5)\n\n# \u2554\u2550\u2561 c05f8497-0ab5-4dae-8dac-3df2bfd36355\nmd\"#### Loop through each pixel of the image and count the number of escape iterations.\"\n\n# \u2554\u2550\u2561 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\u2080 = real[x] + imag[y]\n\t\t\tresult[y, x] = escape(z\u2080, c, maxiter)\n\t\tend\n\tend\n    return result\nend\n\n# \u2554\u2550\u2561 55bfc407-6b22-413e-aff5-d17bfd343f87\n@terminal @code_warntype juliaset()\n\n# \u2554\u2550\u2561 58eda8b1-5205-4527-8e0c-69f6a3cb7607\nmd\"#### Plot a nice Julia set image\"\n\n# \u2554\u2550\u2561 4aa12ee7-dce5-4e30-a1b8-569296760cb9\njs = juliaset();\n\n# \u2554\u2550\u2561 6cd3120e-8164-4177-98cf-6b96953f9567\nGray.((js)/maximum(js))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a0cdf4a6-06ce-4379-b683-5c4d67192b21\nmd\"#### Run the single-threaded benchmark on the default image\"\n\n# \u2554\u2550\u2561 49f344df-bc93-4cee-9179-a75214f0f905\njss = @benchmark juliaset()\n\n# \u2554\u2550\u2561 6a9382e4-7e8f-44e8-9ca2-a50d19eb35c1\nmd\"#### Parallelize with threads and benchmark\"\n\n# \u2554\u2550\u2561 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\u2080 = real[x] + imag[y]\n\t\t\tresult[y, x] = escape(z\u2080, c, maxiter)\n\t\tend\n\tend\n    return result\nend\n\n# \u2554\u2550\u2561 2ee833fe-31e2-4784-be9a-1a4331ee10f5\njst = @benchmark juliaset_threads()\n\n# \u2554\u2550\u2561 6ffd8442-f7fc-44bc-b3e4-a7d6ddb0fb1f\nmd\"#### Parallelize with tasks\"\n\n# \u2554\u2550\u2561 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\u2080 = real[x] + imag[y]\n\t\t\tresult[y, x] = escape(z\u2080,c, maxiter)\n\t\tend\n\tend\n    return result\nend\n\n# \u2554\u2550\u2561 c1f94c04-6796-4945-9adf-b97a4ef06d56\njs_image = juliaset_spawn(c=cr+ci*im);\n\n# \u2554\u2550\u2561 0d5b251f-e0bb-46fd-a3ad-6ea3618eed5b\nGray.(js_image/maximum(js_image))\n\n# \u2554\u2550\u2561 d7ffd22f-d634-46d2-92ed-2d8bbacb0ad5\njsp = @benchmark juliaset_spawn()\n\n# \u2554\u2550\u2561 f1620901-49ca-4bb5-90b7-c258c25a3e7a\nhas_cuda() ||\tmd\"#### WARNING: CUDA not available!\"\n\n# \u2554\u2550\u2561 6ddaf0d0-ee62-4f36-94c6-05f3bfb18e49\nfunction run!(in, out, c; maxiter=16)\n    out .= escape.(in, c, maxiter)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25008548f5a7-de5b-44a1-a0f2-55314a6152b3\n# \u2560\u2550750ded6c-f15d-11eb-02ef-5156d6bf3200\n# \u255f\u2500062c93ab-df7e-485e-a4bc-f7e39c013c3f\n# \u2560\u25506d12faf1-d8bc-400a-b934-e2c36a0fcc5c\n# \u255f\u25009da77179-daff-4eb7-b95b-1c5b9da5e524\n# \u2560\u255081fa04e2-147d-496d-bea4-cfe14a67868a\n# \u2560\u255062c83a9e-d5ba-4479-b3b4-4584bbf2b70f\n# \u255f\u2500c05f8497-0ab5-4dae-8dac-3df2bfd36355\n# \u2560\u25501001c583-b7ee-47e0-87ac-2d4be6e8b23b\n# \u2560\u255055bfc407-6b22-413e-aff5-d17bfd343f87\n# \u255f\u250058eda8b1-5205-4527-8e0c-69f6a3cb7607\n# \u2560\u25504aa12ee7-dce5-4e30-a1b8-569296760cb9\n# \u2560\u25506cd3120e-8164-4177-98cf-6b96953f9567\n# \u255f\u25000ee22f75-e720-4fd2-b081-80eed5e57928\n# \u255f\u25007db79200-d9ba-4199-a2ea-4d0862b36015\n# \u255f\u25000d5b251f-e0bb-46fd-a3ad-6ea3618eed5b\n# \u2560\u2550c1f94c04-6796-4945-9adf-b97a4ef06d56\n# \u255f\u2500a0cdf4a6-06ce-4379-b683-5c4d67192b21\n# \u2560\u255049f344df-bc93-4cee-9179-a75214f0f905\n# \u255f\u25006a9382e4-7e8f-44e8-9ca2-a50d19eb35c1\n# \u255f\u2500add716ef-d45b-4aab-8e00-666adaf38c77\n# \u2560\u25502ee833fe-31e2-4784-be9a-1a4331ee10f5\n# \u255f\u25006ffd8442-f7fc-44bc-b3e4-a7d6ddb0fb1f\n# \u2560\u2550b39c8c16-9162-46e7-9fbf-4400eb69dd17\n# \u2560\u2550d7ffd22f-d634-46d2-92ed-2d8bbacb0ad5\n# \u2560\u2550f1620901-49ca-4bb5-90b7-c258c25a3e7a\n# \u2560\u25506ddaf0d0-ee62-4f36-94c6-05f3bfb18e49\n# \u2560\u25506341b004-4426-4e30-9015-b1ee1a75e0da\n# \u2560\u2550509fa4b9-c9a6-45da-a7a5-574f5a57b8cf\n# \u255f\u25003185c612-de1e-4acb-a232-dd5dfd3949d2\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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\u209a = Float64[]\nxe\u2081 = Float64[]\nxe\u2082 = Float64[]\nx\u2081 = Float64[]\nx\u2082 = Float64[]\nq\u2081 = Float64[]\nq\u2082 = 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        \u0394 = 1.0 - 4coeff[1]*coeff[3] / (coeff[2]*coeff[2])\n        if \u0394 < 0.0\n          res[1] = -0.5coeff[2]/coeff[3]+0.5coeff[2]*sqrt(-\u0394)/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(\u0394))*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        \u03d5 = acos(R/sqrt(Q^3))\n        res[1] = P*cos(\u03d5/3)+S\n        res[2] = P*cos((\u03d5+2\u03c0)/3)+S\n        res[3] = P*cos((\u03d5-2\u03c0)/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\u2080 = coeff[1]/coeff[5]\n      a\u2081 = coeff[2]/coeff[5]\n      a\u2082 = coeff[3]/coeff[5]\n      a\u2083 = coeff[4]/coeff[5]\n      y\u2081 = cubic([4a\u2082*a\u2080-a\u2081^2-a\u2083^2*a\u2080, a\u2081*a\u2083-4a\u2080, -a\u2082, 1.0])[1]\n      R = sqrt(0.25a\u2083^2-a\u2082+y\u2081)\n      if R == 0.0\n        A = 0.75a\u2083^2-2a\u2082\n        B = 2*sqrt(y\u2081^2-4a\u2080)\n      else\n        A = 0.75a\u2083^2-R^2-2a\u2082\n        B = (a\u2083*a\u2082-2a\u2081-0.25a\u2083^3)/R\n      end\n      D = sqrt(A+B)\n      E = sqrt(A-B)\n      res[1] = -0.25a\u2083+0.5R+0.5D\n      res[2] = res[1]-D\n      res[3] = -0.25a\u2083-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\u2080::Float64, q::Vector{Taylor1{Float64}}, order::Int, i::Int)\n  q[i].coeffs[2:end] = 0.0\n  q[i].coeffs[1] = q\u2080\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\u2080::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\u2080\n  q[i] = integrate(f(q), q\u2080)\n  for k in 1:order-1\n    q[i] = integrate(f(q), q\u2080)\n  end\n  q[i].coeffs[end]\n  #integrate_ode(f, q\u2080, q, order, i).coeffs[end]\nend\n\nfunction f\u2081(q::Vector)\n  0.01*q[2]\nend\n\nfunction f\u2082(q::Vector)\n  2020.0-100.0*q[1]-100.0*q[2]\nend\n\nfunction test(order::Int, \u0394q::Float64, duration::Float64)\n  \u03bb, P = eig([0.0 0.01; -100.0 -100.0])\n  C = inv(P)*[0.0; 2020.0]\n  E = -C./\u03bb\n  D = -E + inv(P)*[0.0; 20.0]\n  f = [f\u2081, f\u2082]\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\u2099 = [0.0, 0.0]\n  t = 0.0\n  it = [0, 0]\n  start = true\n  while t < duration && sum(it) < 100000\n    t\u2092 = t\n    t, i = findmin(t\u2099)\n    ##println(\"-------- $t\u2099, $i\")\n    j = 3 - i\n    it[i] += 1\n    xe = P*diagm(exp.(\u03bb*t))*inv(P)*[0.0; 20.0]+P*diagm((exp.(\u03bb*t)-1)./\u03bb)*inv(P)*[0.0;2020.0]\n    if t-t\u2092 > 0.0\n      for tt in 0.0:(t-t\u2092)/20:t-t\u2092\n        xe = P*diagm(exp.(\u03bb*(t\u2092+tt)))*inv(P)*[0.0; 20.0]+P*diagm((exp.(\u03bb*(t\u2092+tt))-1)./\u03bb)*inv(P)*[0.0;2020.0]\n        push!(t\u209a, t\u2092+tt)\n        push!(x\u2081, evaluate(x[1], tt))#x[1].coeffs[1])\n        push!(x\u2082, evaluate(x[2], tt))#x[2].coeffs[1])\n        push!(q\u2081, evaluate(q[1], tt))#q[1].coeffs[1])\n        push!(q\u2082, evaluate(q[2], tt))#q[2].coeffs[1])\n        push!(xe\u2081, xe[1])\n        push!(xe\u2082, xe[2])\n      end\n    end\n    x\u2080 = evaluate(x[i], t-t\u2092)\n    x[i] = evaluate(x[i], Taylor1([t-t\u2092, 1.0]))\n    q[i] = evaluate(q[i], Taylor1([t-t\u2092, 1.0]))\n    ##println(\"$t, $i, q = $(q[i])\")\n    q[j] = evaluate(q[j], Taylor1([t-t\u2092, 1.0]))\n    ##println(\"$t, $j, q = $(q[j])\")\n    q[i] = deepcopy(x[i])\n    q[i][end] = 0.0\n    t\u2099[i] = t + (abs(\u0394q/x[i].coeffs[end]))^(1.0/order)\n    #println(\"$t, $i, q = $(q[i])\")\n    #println(\"$t, $i, x = $(x[i])\")\n    x\u2080 = evaluate(x[j], t-t\u2092)\n    x[j] = integrate(f[j](q), x\u2080)\n    #println(\"$t, $j, x = $(x[j])\")\n    p = (x[j]-q[j]).coeffs\n    p[1] -= \u0394q\n    a = roots(p)\n    p[1] += 2\u0394q\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\u2099[j] = t + min_r\n    # t\u2082 = brent(nth_derivative_time, 0.0, t\u2099[j]-t, f[j], deepcopy(q), order, i)\n    # println(\"$(t\u2099[j]), $(t\u2082+t)\")\n    # if t\u2082 > 0.0 && t + t\u2082 < t\u2099[j]\n    #   t\u2099[j] = t + t\u2082\n    # end\n    # if start\n    #   t\u2099[j] = 0.0\n    #   start = false\n    # end\n  end\n  println(it)\nend\n\u03b4 = 1e-6\n@time test(4, \u03b4, 500.0)\n#plot(t\u209a, [abs(x\u2081-xe\u2081), abs(x\u2082-xe\u2082)])\nprintln(\"$(mean(abs.(x\u2081-xe\u2081))), $(maximum(abs.(x\u2081-xe\u2081))), $(mean(abs.(x\u2082-xe\u2082))), $(maximum(abs.(x\u2082-xe\u2082))), $(2\u03b4)\")\n#plot(t\u209a, [x\u2081, q\u2081, xe\u2081, x\u2082, q\u2082, xe\u2082])\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\u03c0. 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": "n=rand(1:10)\nH = Hankel([-n:n])\n@test diag(full(H)) == [-n:2:n]\n", "meta": {"hexsha": "631936fa0b98105f0ea1cb7178ea2da7032970ed", "size": 64, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/hankel.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": "test/hankel.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": "test/hankel.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": 16.0, "max_line_length": 31, "alphanum_fraction": 0.515625, "num_tokens": 27, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7610106500039232}}
{"text": "using IntervalLinearAlgebra, StaticArrays, LazySets\nusing Test\n\nconst IA = IntervalArithmetic\n\ninclude(\"test_classify.jl\")\ninclude(\"test_multiplication.jl\")\ninclude(\"test_utils.jl\")\n\n\ninclude(\"test_eigenvalues/test_interval_eigenvalues.jl\")\ninclude(\"test_eigenvalues/test_verify_eigs.jl\")\ninclude(\"test_solvers/test_enclosures.jl\")\ninclude(\"test_solvers/test_epsilon_inflation.jl\")\ninclude(\"test_solvers/test_precondition.jl\")\ninclude(\"test_solvers/test_oettli_prager.jl\")\n", "meta": {"hexsha": "41a7c982ff1de61b6d6c8ac0dcbdc66d57396e35", "size": 473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "lucaferranti/IntervalLinearAlgebra.jl", "max_stars_repo_head_hexsha": "4592f032b14dfe1fe243ff0f0b4691407dc24374", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-24T16:04:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T21:33:24.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "lucaferranti/IntervalLinearAlgebra.jl", "max_issues_repo_head_hexsha": "4592f032b14dfe1fe243ff0f0b4691407dc24374", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2021-06-01T15:42:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-02T08:03:56.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "lucaferranti/IntervalLinearAlgebra.jl", "max_forks_repo_head_hexsha": "4592f032b14dfe1fe243ff0f0b4691407dc24374", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-24T16:07:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:28:43.000Z", "avg_line_length": 27.8235294118, "max_line_length": 56, "alphanum_fraction": 0.8372093023, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7610106497587946}}
{"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\u00e7\u00e3o LU estar\u00e1 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 \u00e9 $y o valor do x \u00e9 $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    \u0394t = 0.01\n    nt = 1000\n\n    const q\u2080 = [1., 1., 1.]\n    const default_params = (\u03c3 = 10., \u03c1 = 28., \u03b2 = 8/3)\n\n    function lorenz_attractor_v(t, x, v, params=default_params)\n        \u03c3, \u03c1, \u03b2 = params\n        v[1] = \u03c3 * (x[2] - x[1])\n        v[2] = x[1] * (\u03c1 - x[3]) - x[2]\n        v[3] = x[1] * x[2] - \u03b2 * x[3]\n        nothing\n    end\n\n\n    function lorenz_attractor_ode(q\u2080=q\u2080)\n        ODE(lorenz_attractor_v, q\u2080)\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# - `\u03b1` 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 \u00f7 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, \u03b1)\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) + \u03b1 * 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 \u03b1\n# to visualize the effect of regularization on the testing and training loss.\n\n\u03b1s = 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 \u03b1 in \u03b1s\n    w = fit_ridge(model, X_train, y_train, \u03b1)\n    w\u0302 = value.(w)\n    y\u0302_test = X_test * w\u0302 \n    y\u0302_train = X_train * w\u0302 \n    push!(mse_test, norm(y\u0302_test - y_test)^2 / (2 * Ntest * D))\n    push!(mse_train, norm(y\u0302_train - y_train)^2 / (2 * Ntrain * D))\nend\n\n# Visualize the Mean Score Error metric\n\nPlots.plot(\n    \u03b1s, mse_test ./ sum(mse_test),\n    label=\"MSE test\", xaxis = \"\u03b1\", yaxis=\"MSE\", legend=(0.8, 0.2),\n    width=3,\n)\nPlots.plot!(\n    \u03b1s, 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 `\u2202w_i/\u2202\u03b1`, the derivative of the learned solution `\u0302w`\n# w.r.t. the regularization parameter.\n\nfunction compute_dw_d\u03b1(model, w)\n    D = length(w)\n    dw_d\u03b1 = 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\u03b1[i] = MOI.get(\n            model,\n            DiffOpt.ForwardVariablePrimal(), \n            w[i],\n        )\n    end\n    return dw_d\u03b1\nend\n\n# Using `\u2202w_i/\u2202\u03b1` computed with `compute_dw_d\u03b1`,\n# we can compute the derivative of the test loss w.r.t. the parameter \u03b1\n# by composing derivatives.\n\nfunction d_testloss_d\u03b1(model, X_test, y_test, w, w\u0302)\n    N, D = size(X_test)\n    dw_d\u03b1 = compute_dw_d\u03b1(model, w)\n    err_term = X_test * w\u0302 - y_test\n    return sum(eachindex(err_term)) do i\n        dot(X_test[i,:], dw_d\u03b1) * 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(\u03b10, max_iters=100; fixed_step = 0.01, grad_tol=1e-3)\n    \u03b1_s = Float64[]\n    \u2202\u03b1_s = Float64[]\n    test_loss = Float64[]\n    \u03b1 = \u03b10\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, \u03b1)\n        w\u0302 = value.(w)\n        err_term = X_test * w\u0302 - y_test\n        \u2202\u03b1 = d_testloss_d\u03b1(model, X_test, y_test, w, w\u0302)\n        push!(\u03b1_s, \u03b1)\n        push!(\u2202\u03b1_s, \u2202\u03b1)\n        push!(test_loss, norm(err_term)^2 / (2 * N * D))\n        \u03b1 -= fixed_step * \u2202\u03b1\n        if abs(\u2202\u03b1) \u2264 grad_tol\n            break\n        end\n    end\n    return \u03b1_s, \u2202\u03b1_s, test_loss\nend\n\n\u03b1\u0304, \u2202\u03b1\u0304, mse\u0304 = descent(0.10, 500)\niters = 1:length(\u03b1\u0304);\n\n# Visualize gradient descent and convergence\n\nPlots.plot(\n    \u03b1s, mse_test,\n    label=\"MSE test\", xaxis = (\"\u03b1\"),\n    legend=:topleft,\n    width=2,\n)\nPlots.plot!(\n    \u03b1\u0304, mse\u0304,\n    label=\"learned \u03b1\", width = 5,\n    style=:dot,\n)\nPlots.title!(\"Regularizer learning\")\n\n# Visualize the convergence of \u03b1 to its optimal value\n\nPlots.plot(\n    iters, \u03b1\u0304, label = nothing, color = :blue,\n    xaxis = (\"Iterations\"), legend=:bottom,\n    title = \"Convergence of \u03b1\"\n)\n\n# Visualize the convergence of the objective function\n\nPlots.plot(\n    iters, mse\u0304, 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, \u2202\u03b1\u0304, label = nothing, color = :green,\n    xaxis = (\"Iterations\"), legend=:bottom,\n    title = \"Convergence of \u2202\u03b1\"\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": "# Code used to generate closest correlation matrix problems. Save in Testproblems/ClosestCorr with an accurante\n# solution from MOSEK\n\n# Original problem has the following format:\n# min_X   1/2 ||X-C||^2\n# s.t.    Xii = 1\n#         X \u2ab4 0\n\n# workspace()\n# using JLD, JuMP, Mosek, Distributions\n\n# specify number of problems that start with matrix C as a perturbed correlation matrix and problems where C is a random matrix\nnnCorr = 25\nnnRand = 25\nnn = nnCorr+nnRand\n# this function creates a matrix A that slices out the diagonal entries Xii of a vectorized square matrix x=vec(X)\nfunction createDiagonalExtractor(n)\n  A = spzeros(n,n^2)\n  A[1,1] = 1\n  for iii=2:n-1\n    col = (iii-1)*(n+1)\n    A[iii,col+1] = 1\n  end\n  A[n,n^2] = 1\n  return A\nend\n\n# https://stats.stackexchange.com/questions/2746/how-to-efficiently-generate-random-positive-semidefinite-correlation-matrices\n# VINE METHOD to generate random correlation matrices\n#distributed ~ det(S)^eta [or maybe det(S)^(eta-1), not sure]\nfunction randomCorrMatrix(d, eta)\n    \u03b2 = eta + (d-1)/2;\n    P = zeros(d,d);           #storing partial correlations\n    S = eye(d);\n\n    for k = 1:d-1\n        \u03b2 = \u03b2 - 1/2;\n        for i = k+1:d\n            P[k,i] = rand(Beta(\u03b2,\u03b2)) # sampling from \u03b2\n            P[k,i] = (P[k,i]-0.5)*2;     #linearly shifting to [-1, 1]\n            p = P[k,i];\n            for l = (k-1):-1:1 #converting partial correlation to raw correlation\n                p = p * sqrt((1-P[l,i]^2)*(1-P[l,k]^2)) + P[l,i]*P[l,k];\n            end\n            S[k,i] = p;\n            S[i,k] = p;\n        end\n    end\n    return S\nend\n\nrng = MersenneTwister(12345)\ndirPath = \"../DataFiles/Julia/ClosestCorr/\"\n!ispath(dirPath) && mkdir(dirPath)\n\n\n\n for iii =1:1:nn\n  # choose size of problem\n  n = rand(rng,6:40)\n  eta = abs(randn(rng))\n  # create random correlation matrix and perturb it\n  if iii<=nnCorr\n    C = randomCorrMatrix(n,eta)\n    E  = randn(n,n)*1e-1\n    C = C + (E + E')/2\n  else\n    C = randn(rng,n,n)\n  end\n\n\n  c = vec(C)\n\n  isposdef(C) && warn(\"The perturbed correlation matrix is still pos def.\")\n\n  # put problem into solver format\n  # min   x'Ix - 1*t\n  # s.t.  Ax + s1 = 0\n  #       x = s4\n  #       -t <= c'*x <=t\n  # s1 in 0, s2,s3 in R+, s4 in SDPcone\n\n  n2 = n^2\n  m = n+n2\n\n  P = speye(n2)\n  q = -vec(C)\n  r = 0.5*vec(C)'*vec(C)\n  b = [ones(n);zeros(n2)]\n  A = createDiagonalExtractor(n)\n  Aa = [A; -speye(n2)]\n  # specify cone\n  Kf = n\n  Kl = 0\n  Kq = []\n  Ks = [n^2]\n  # # solve accurately once with mosek\n  model = Model(solver=MosekSolver())\n  @variable(model, X[1:n,1:n], SDP)\n  @variable(model, t)\n  x = vec(X)\n  @objective(model, Min, t)\n  @constraint(model, norm(x-c) <= t)\n  @constraint(model, A*x.== b[1:n])\n  status = JuMP.solve(model)\n\n  # correct optimal objective value since slightly different problem is solved\n  objTrue = getobjectivevalue(model)\n  objCorrected = 0.5*objTrue^2\n  solTrue = getvalue(x)\n  # println(\"Objective value: \",objTrue)\n  # println(\"Corrected objective value: \", objCorrected)\n  # println(\"x = \", getvalue(x))\n\n  nr = \"$(iii)\"\n  if iii < 10\n    nr = \"0$(iii)\"\n  end\n\n  fn = \"ClosestCorr\"*nr*\".jld\"\n  problemType = \"Closest Correlation Matrix\"\n  problemName = \"ClosestCorr\"*nr\n\n  JLD.save(dirPath*fn,\"n\",n,\"m\",m,\"A\",Aa,\"b\",b,\"P\",P,\"q\",q,\"r\",r,\"C\",C,\"objTrue\",objCorrected,\"solTrue\",solTrue,\"problemType\",problemType,\"problemName\",problemName,\"Kf\",Kf,\"Kl\",Kl,\"Kq\",Kq,\"Ks\",Ks)\n  println(\"$(iii)/$(nn) completed!\")\nend\n\n\n", "meta": {"hexsha": "cc92a5a57c55893d389d8d279ef052e0351a0947", "size": 3438, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/ClosestCorrMatrix.jl", "max_stars_repo_name": "migarstka/SDP_Benchmark_Problems", "max_stars_repo_head_hexsha": "4b17862e7d5c5749f471262f8eee8582bd730364", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-11T22:06:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T21:02:13.000Z", "max_issues_repo_path": "Code/ClosestCorrMatrix.jl", "max_issues_repo_name": "migarstka/SDP_Benchmark_Problems", "max_issues_repo_head_hexsha": "4b17862e7d5c5749f471262f8eee8582bd730364", "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": "Code/ClosestCorrMatrix.jl", "max_forks_repo_name": "migarstka/SDP_Benchmark_Problems", "max_forks_repo_head_hexsha": "4b17862e7d5c5749f471262f8eee8582bd730364", "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.6511627907, "max_line_length": 196, "alphanum_fraction": 0.605875509, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7609631345278619}}
{"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(\u03a9, \u03b2, \u03b1, v, w)\n\n    R = (v^2 - w^2) / (w^2 * v)\n    a = sqrt(\u03b2^2 / 4 + R * \u03b2 * coth(\u03b2 * v / 2))\n    b = R * \u03b2 / sinh(\u03b2 * v / 2)\n\n    coefficient = 2 * \u03b1 * \u03b2^(3 / 2) * v^3 * sinh(\u03a9 * \u03b2 / 2) / (3 * \u221a\u03c0 * w^3 * sinh(\u03b2 / 2))\n\n    integrand(x) = (sin(\u03a9 * 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(\u03a9, \u03b2, \u03b1, v, w; prec = 64)\n\n    # Initialise precision of ArbReal to prec.\n    setextrabits(0)\n    setprecision(ArbReal, prec + 8)\n\n    \u03a9 = ArbReal(\"$\u03a9\")\n    \u03b2 = ArbReal(\"$\u03b2\")\n    \u03b1 = ArbReal(\"$\u03b1\")\n    v = ArbReal(\"$v\")\n    w = ArbReal(\"$w\")\n\n    R = ArbReal((v^2 - w^2) / (w^2 * v))\n    a = ArbReal(sqrt(\u03b2^2 / 4 + R * \u03b2 * coth(\u03b2 * v / 2)))\n    b = ArbReal(R * \u03b2 / sinh(\u03b2 * v / 2))\n\n    coefficient = ArbReal(\u03b1 * \u03b2^(3/2) * v^3 / (3 * a * \u221a\u03c0 * w^3 * sinh(\u03b2 / 2)))\n\n    \u03b8(z, n) = ArbReal(\u221a\u03c0 * 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(\u03a9 * \u03b2 / 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(\u03a9 + 1), ArbReal(\u03a9 - 1)]\n                even_term += ArbReal(arb_binomial(n, n/2) * s * \u03b8(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(\u03a9 + 1 + v * (n - 2 * k)), ArbReal(\u03a9 - 1 + v * (n - 2 * k)), ArbReal(\u03a9 + 1 - v * (n - 2 * k)), ArbReal(\u03a9 - 1 - v * (n - 2 * k))]\n                k_term += ArbReal(k_coeff * s * \u03b8(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            \u03a9 = ArbReal(\"$\u03a9\")\n            \u03b2 = ArbReal(\"$\u03b2\")\n            \u03b1 = ArbReal(\"$\u03b1\")\n            v = ArbReal(\"$v\")\n            w = ArbReal(\"$w\")\n\n            R = ArbReal((v^2 - w^2) / (w^2 * v))\n            a = ArbReal(sqrt(\u03b2^2 / 4 + R * \u03b2 * coth(\u03b2 * v / 2)))\n            b = ArbReal(R * \u03b2 / sinh(\u03b2 * v / 2))\n\n            coefficient = ArbReal(\u03b1 * \u03b2^(3/2) * v^3 / (3 * a * \u221a\u03c0 * w^3 * sinh(\u03b2 / 2)))\n\n            \u03b8(z, n) = ArbReal(\u221a\u03c0 * 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(\u03a9 * \u03b2 / 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(\u03a9, bits = prec + 8), \". Final result: \", ArbReal(result, bits = prec + 8))\n    ArbReal(result, bits = prec + 8)\nend\n\n\u03a9_range = 0.01:0.5:20.01\n\u03b2 = 2.0\n\u03b1 = 7.0\nv = 5.8\nw = 1.6\n# For \u03a9_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(\u03a9, \u03b2, \u03b1, v, w; prec = 64) for \u03a9 in \u03a9_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(\u03a9, \u03b2, \u03b1, v, w) for \u03a9 in \u03a9_range]\n\ndiff = oscill_expansion .- oscill_integral\n@show(diff)\n# oscill_integral = fill(-5.81034244862553995092)\n# @show(oscill_integral)\n# p = plot(\u03a9_range, abs.(oscill_expansion), yaxis = :log, label = \"Oscillatory\", xlabel = \"\u03a9\", ylabel = \"ReX\")\n# plot!(\u03a9_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": "include(\"../src/AlphaShapes.jl\")\nusing LinearAlgebraicRepresentation\nLar = LinearAlgebraicRepresentation\n\nif VERSION < VersionNumber(\"1.0.0\")\n\tusing Base.Test\nelse\n\tusing Test\nend\n\ninclude(\"deWall.jl\")\ninclude(\"delaunay.jl\")\ninclude(\"alpha_complex.jl\")\ninclude(\"geometry.jl\")\n", "meta": {"hexsha": "7ee15b748c01bd50ee54dc105c9fd8485170a37b", "size": 276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "luigibvl/AlphaShapes.jl", "max_stars_repo_head_hexsha": "f073366f8ab6b15964c9879dad5ccedddd60f2a1", "max_stars_repo_licenses": ["MIT"], "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": "luigibvl/AlphaShapes.jl", "max_issues_repo_head_hexsha": "f073366f8ab6b15964c9879dad5ccedddd60f2a1", "max_issues_repo_licenses": ["MIT"], "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": "luigibvl/AlphaShapes.jl", "max_forks_repo_head_hexsha": "f073366f8ab6b15964c9879dad5ccedddd60f2a1", "max_forks_repo_licenses": ["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.4, "max_line_length": 35, "alphanum_fraction": 0.7753623188, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7609631282424957}}
{"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": "######### Stan optimize example  ###########\n\nusing StanOptimize, Test\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\nstanmodel = OptimizeModel(\"optimize_1\",  bernoulli_model);\n\n(sample_path, log_path) = stan_sample(stanmodel, data=bernoulli_data);\n\nif sample_path !== Nothing\n  optim1, cnames = read_optimize(stanmodel)\n  \n  @test optim1[\"theta\"][end] \u2248 0.3 atol=0.001\nend\n\n# Same with saved iterations\nsm = OptimizeModel(\"optimize_2\", bernoulli_model;\n  method = StanOptimize.Optimize(save_iterations = true));\n\n(sample_path, log_path)  = stan_optimize(sm, data=bernoulli_data);\n\nif sample_path !== Nothing\n  optim2, cnames = read_optimize(sm)\n  @test optim2[\"theta\"][end] \u2248 0.3 atol=0.001\nend\n", "meta": {"hexsha": "defaa98ed76fc6a6cb692e941506fa844b6aa03d", "size": 908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Examples_Stan_Methods/Optimize/optimize.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Stan.jl-682df890-35be-576f-97d0-3d8c8b33a550", "max_stars_repo_head_hexsha": "9391a60eef08e6065240c0c46efe8e9851e151fa", "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/Examples_Stan_Methods/Optimize/optimize.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Stan.jl-682df890-35be-576f-97d0-3d8c8b33a550", "max_issues_repo_head_hexsha": "9391a60eef08e6065240c0c46efe8e9851e151fa", "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/Examples_Stan_Methods/Optimize/optimize.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Stan.jl-682df890-35be-576f-97d0-3d8c8b33a550", "max_forks_repo_head_hexsha": "9391a60eef08e6065240c0c46efe8e9851e151fa", "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.1463414634, "max_line_length": 71, "alphanum_fraction": 0.6685022026, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7609631258085563}}
{"text": "using DataDrivenDiffEq\nusing ModelingToolkit\nusing LinearAlgebra\nusing OrdinaryDiffEq\n\nusing Symbolics: scalarize\n\nfunction cart_pole(u, p, t)\n    du = similar(u)\n    F = -0.2 + 0.5*sin(6*t) # the input\n    du[1] = u[3]\n    du[2] = u[4]\n    du[3] = -(19.62*sin(u[1])+sin(u[1])*cos(u[1])*u[3]^2+F*cos(u[1]))/(2-cos(u[1])^2)\n    du[4] = -(sin(u[1])*u[3]^2 + 9.81*sin(u[1])*cos(u[1])+F)/(2-cos(u[1])^2)\n    return du\nend\n\nu0 = [0.3; 0; 1.0; 0]\ntspan = (0.0, 5.0)\ndt = 0.1\ncart_pole_prob = ODEProblem(cart_pole, u0, tspan)\nsolution = solve(cart_pole_prob, Tsit5(), saveat = dt)\n\n# Create the differential data\nX = solution[:,:]\nDX = similar(X)\nfor (i, xi) in enumerate(eachcol(X))\n    DX[:, i] = cart_pole(xi, [], solution.t[i])\nend\nt = solution.t\n\nddprob = ContinuousDataDrivenProblem(\n    X , t, DX = DX[3:4, :], U = (u,p,t) -> [-0.2 + 0.5*sin(6*t)]\n)\n\n\n\n@variables u[1:4] du[1:2] x[1:1] t\nu = scalarize(u)\ndu = scalarize(du)\nx = scalarize(x)\n\npolys = polynomial_basis(u, 2)\npush!(polys, sin.(u[1]))\npush!(polys, cos.(u[1]))\npush!(polys, sin.(u[1])^2)\npush!(polys, cos.(u[1])^2)\npush!(polys, sin.(u[1]).*u[3:4]...)\npush!(polys, sin.(u[1]).*u[3:4].^2...)\npush!(polys, sin.(u[1]).*cos.(u[1])...)\npush!(polys, sin.(u[1]).*cos.(u[1]).*u[3:4]...)\npush!(polys, sin.(u[1]).*cos.(u[1]).*u[3:4].^2...)\nimplicits = [du;  du[1] .* u; du[2] .* u; du .* cos(u[1]);   du .* cos(u[1])^2; polys]\npush!(implicits, x...)\npush!(implicits, x[1]*cos(u[1]))\npush!(implicits, x[1]*sin(u[1]))\n\nbasis= Basis(implicits, [u; du], controls = x,  iv = t)\n\n# Simply use any optimizer you would use for sindy\n\u03bb = [1e-4;5e-4;1e-3;2e-3;3e-3;4e-3;5e-3;6e-3;7e-3;8e-3;9e-3;1e-2;2e-2;3e-2;4e-2;5e-2;\n6e-2;7e-2;8e-2;9e-2;1e-1;2e-1;3e-1;4e-1;5e-1;6e-1;7e-1;8e-1;9e-1;1;1.5;2;2.5;3;3.5;4;4.5;5;\n6;7;8;9;10;20;30;40;50;100;200];\n\nopt = ImplicitOptimizer(\u03bb)\n# AICC\ng\u0302(x) = x[1] <= 1 ? Inf : 2*x[1]-2*log(x[2])\nres = solve(ddprob, basis, opt, du, maxiter = 1000, g = g\u0302, scale_coefficients = true)\nm = metrics(res)\n\n@test m.Sparsity == 10\n@test m.AICC < 180.0\n@test m.Error < 1.0\n", "meta": {"hexsha": "8cf700844668afc6f09d5a8f1373d47a356c78a2", "size": 2036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sindy/cartpole.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": "test/sindy/cartpole.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": "test/sindy/cartpole.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": 27.5135135135, "max_line_length": 91, "alphanum_fraction": 0.5776031434, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7609631233746165}}
{"text": "using TimeSchemes\nusing Test\n\n##\nM = 1\nB = 1\nK = 1\nv0 = [1.]\nv1 = [0.]\nt = convert(Array{Float64},range(0, stop=1, length=10001))'\nF = zeros(length(t))'\nv, cV = TimeSchemes.newmark(M, B, K, F, v0, v1, t)\n\nsol = 1 / 3 * exp.(- t / 2) .* (sqrt(3) * sin.(sqrt(3) / 2 * t) + 3  * cos.(sqrt(3) / 2 * t))\nsold = - 1 / 6 * exp.(- t / 2) .* (sqrt.(3) * sin.(sqrt(3) / 2 * t) + 3  * cos.(sqrt(3) / 2 * t)) +\n    1 / 3 * exp.(- t / 2) .* (3 / 2 * cos.(sqrt(3) / 2 * t) - 3 * sqrt(3) / 2 * sin.(sqrt(3) / 2 * t))\n@test (maximum(abs.(v[1, :]' - sol)) < 1e-9) && (maximum(abs.(v[2, :]' - sold)) < 1e-9)\nprintln(\"All tests passed.\")\n", "meta": {"hexsha": "e00f57e78ef30f45ea32d1e428b44ab1139d58a7", "size": 619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "ncindea/TimeSchemes.jl", "max_stars_repo_head_hexsha": "cc811775c8c2b6cab29456c8b3daa5c6a8f8c23e", "max_stars_repo_licenses": ["MIT"], "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": "ncindea/TimeSchemes.jl", "max_issues_repo_head_hexsha": "cc811775c8c2b6cab29456c8b3daa5c6a8f8c23e", "max_issues_repo_licenses": ["MIT"], "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": "ncindea/TimeSchemes.jl", "max_forks_repo_head_hexsha": "cc811775c8c2b6cab29456c8b3daa5c6a8f8c23e", "max_forks_repo_licenses": ["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.5789473684, "max_line_length": 102, "alphanum_fraction": 0.4733441034, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7609631153329457}}
{"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 FractionalCalculus\n\nusing QuadGK\nusing SpecialFunctions: gamma\nusing LinearAlgebra, InvertedIndices, SpecialMatrices\nusing SymbolicUtils, SymbolicUtils.Rewriters\nusing Symbolics\n\ninclude(\"./Derivative/Derivative.jl\")\ninclude(\"./Integral/Integral.jl\")\n\nexport FracDiffAlg, FracIntAlg\nexport fracdiff, fracint\n\n# Export symbolics computing APIs\nexport semidiff, semiint\nexport SEMIDIFFRULES, SEMIINTRULES\nexport Incomplete_beta, AuxiliaryFresnelSin, AuxiliaryFresnelCos, Struve, MStruve, Legendre, SinIntegral, HyperSinIntegral, Hypergeometric1F1\n\n# Export fractional derivative releating API\nexport Caputo, GL, RLDiff, Hadamard\n\n# Caputo sense fractional derivative\nexport CaputoDirect, CaputoPiecewise, CaputoDiethelm, CaputoHighPrecision, CaputoHighOrder\n\n# Gr\u00fcnwald Letnikov sense fractional derivative\nexport GLDirect, GLMultiplicativeAdditive, GLLagrangeThreePointInterp, GLFiniteDifference, GLHighPrecision\n\n# Riemann Liouville sense fractional derivative\nexport RLDiffApprox, RLDiffMatrix, RLLinearSplineInterp, RLG1, RLD\n\n# Hadamard sense fractional derivative\nexport HadamardLRect, HadamardRRect, HadamardTrap\n\n# Riesz sense fractional derivative\nexport RieszSymmetric, RieszOrtigueira\n\n# Macros for convenient computing\nexport @fracdiff, @semifracdiff\n\n#Export fractional integral relating API\nexport RLInt, HadamardInt\n\n\nexport RLDirect, RLPiecewise\nexport RLIntApprox, RLLinearInterp, RLIntMatrix\nexport RLIntSimpson, RLIntTrapezoidal, RLIntRectangular, RLIntCubicSplineInterp\n\nexport HadamardMat\n\n# Macros for convenient computing\nexport @fracint, @semifracint\n\n# Auxiliary functions\nexport RieszMatrix, omega, B, genfun, first_order\n\nend", "meta": {"hexsha": "3eaa2a6c9ffd6a239c3616f442b48fa63a5c6e41", "size": 1657, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FractionalCalculus.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/FractionalCalculus.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/FractionalCalculus.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": 29.0701754386, "max_line_length": 141, "alphanum_fraction": 0.847917924, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7609198413560619}}
{"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": "module day1\n\nusing DelimitedFiles\nreadInput() = vec(readdlm(joinpath(@__DIR__, \"input.txt\"), Int))\n\nfuelRequired(x) = x \u00f7 3 - 2\npart1(input) = sum(fuelRequired, input)\n\nfunction fuelRequired2(x)\n    fuel = fuelRequired(x)\n    fuel > 0 ? fuel + fuelRequired2(fuel) : 0\nend\npart2(input) = sum(fuelRequired2, input)\n\nend", "meta": {"hexsha": "fa38caab4756bb44fba3c046967e8ede044b8967", "size": 317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day1/day1.jl", "max_stars_repo_name": "gsoleilhac/aoc19.jl", "max_stars_repo_head_hexsha": "c5293cec6baeb10ed0f6f5ffa605813714893cfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-13T22:26:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-13T22:26:52.000Z", "max_issues_repo_path": "src/day1/day1.jl", "max_issues_repo_name": "gsoleilhac/aoc19.jl", "max_issues_repo_head_hexsha": "c5293cec6baeb10ed0f6f5ffa605813714893cfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day1/day1.jl", "max_forks_repo_name": "gsoleilhac/aoc19.jl", "max_forks_repo_head_hexsha": "c5293cec6baeb10ed0f6f5ffa605813714893cfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-14T18:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-14T18:52:21.000Z", "avg_line_length": 21.1333333333, "max_line_length": 64, "alphanum_fraction": 0.7034700315, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7609116318362915}}
{"text": "sqrt(mean(A.^2.))\n", "meta": {"hexsha": "a7ee4b2c4f3f445af56940355ebe6a37b0ffcbd3", "size": 18, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/averages-root-mean-square-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/averages-root-mean-square-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/averages-root-mean-square-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": 9.0, "max_line_length": 17, "alphanum_fraction": 0.5555555556, "num_tokens": 7, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7609116297593497}}
{"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    \u03b1 = atan(v_INF_ECI[2],v_INF_ECI[1])\n    \u03b4 = asin(v_INF_ECI[3]/norm(v_INF_ECI))\n    return (\u03b1,\u03b4)\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\u00e9rard 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": "# ---\n# title: 29. Divide Two Integers\n# id: problem29\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math, Binary Search\n# link: <https://leetcode.com/problems/divide-two-integers/description/>\n# hidden: true\n# ---\n# \n# Given two integers `dividend` and `divisor`, divide two integers without using\n# multiplication, division, and mod operator.\n# \n# Return the quotient after dividing `dividend` by `divisor`.\n# \n# The integer division should truncate toward zero, which means losing its\n# fractional part. For example, `truncate(8.345) = 8` and `truncate(-2.7335) =\n# -2`.\n# \n# **Note:**\n# \n#   * Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [\u2212231,  231 \u2212 1]. For this problem, assume that your function **returns 2 31 \u2212 1 when the division result overflows**.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: dividend = 10, divisor = 3\n#     Output: 3\n#     Explanation: 10/3 = truncate(3.33333..) = 3.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: dividend = 7, divisor = -3\n#     Output: -2\n#     Explanation: 7/-3 = truncate(-2.33333..) = -2.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: dividend = 0, divisor = 1\n#     Output: 0\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: dividend = 1, divisor = 1\n#     Output: 1\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `-231 <= dividend, divisor <= 231 - 1`\n#   * `divisor != 0`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "7bdd22816f0e456a196f35753f405857aafbe05a", "size": 1542, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/29.divide-two-integers.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/29.divide-two-integers.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/29.divide-two-integers.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.8378378378, "max_line_length": 237, "alphanum_fraction": 0.5869001297, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.7609071955088715}}
{"text": "#=\nIllustrates vectors in the plane.\n\n@author : Spencer Lyon <spencer.lyon@nyu.edu>\n          Victoria Gregory <victoria.gregory@nyu.edu>\n\n@date: 07/09/2014\n=#\n\nusing Plots\npyplot()\nusing LaTeXStrings\n\n\nfunction plane_fig()\n\n  vecs = ([2, 4], [-3, 3], [-4, -3.5])\n  x_vals = zeros(2, length(vecs))\n  y_vals = zeros(2, length(vecs))\n  labels = []\n\n  # Create matrices of x and y values, labels for plotting\n  for i = 1:length(vecs)\n    v = vecs[i]\n    x_vals[2, i] = v[1]\n    y_vals[2, i] = v[2]\n    labels = [labels; (1.1 * v[1], 1.1 * v[2], \"$v\")]\n  end\n\n  plot(x_vals, y_vals, arrow=true, color=:blue,\n       legend=:none, xlims=(-5, 5), ylims=(-5, 5),\n       annotations = labels, xticks=-5:1:5, yticks=-5:1:5)\n  vline!([0], color=:black)\n  hline!([0], color=:black)\n  plot!(foreground_color_axis=:white, foreground_color_text=:white,\n        foreground_color_border=:white)\n\nend\n\n\nfunction scalar_multiply()  # illustrate scalar multiplication\n\n  x = [2, 2]\n  scalars = [-2, 2]\n\n  # Create matrices of x and y values, labels for plotting\n  x_vals = zeros(2, 1 + length(scalars))\n  y_vals = zeros(2, 1 + length(scalars))\n  labels = []\n  x_vals[2, 3] = x[1]\n  y_vals[2, 3] = x[2]\n  labels = [labels; (x[1] + 0.4, x[2] - 0.2, L\"$x$\")]\n\n  # Perform scalar multiplication, store results in plotting matrices\n  for i = 1:length(scalars)\n    s = scalars[i]\n    v = s .* x\n    x_vals[2, i] = v[1]\n    y_vals[2, i] = v[2]\n    labels = [labels; (v[1] + 0.4, v[2] - 0.2, LaTeXString(\"\\$$s x\\$\"))]\n  end\n\n  plot(x_vals, y_vals, arrow=true, color=[:red :red :blue],\n       legend=:none, xlims=(-5, 5), ylims=(-5, 5),\n       annotations = labels, xticks=-5:1:5, yticks=-5:1:5)\n  vline!([0], color=:black)\n  hline!([0], color=:black)\n  plot!(foreground_color_axis=:white, foreground_color_text=:white,\n        foreground_color_border=:white)\n\nend\n\n# Plot the first figure --- three vectors in the plane\n\nplane_fig()\n", "meta": {"hexsha": "f68343db069922000e42dd34e953739903e10104", "size": 1905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_algebra/vecs.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": "linear_algebra/vecs.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": "linear_algebra/vecs.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": 25.0657894737, "max_line_length": 72, "alphanum_fraction": 0.6094488189, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7609071727380888}}
{"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": "using DifferentialForms\n\n# Create a 0-form (a scalar):\ne = one(Form{3})\n@test e[] == 1\n@test collect(e) == [1]\n\n# Create a 1-form (a vector) from a tuple:\nv = Form{3,1}((1, 2, 3))\n@test v[1] == 1\n@test v[2] == 2\n@test v[3] == 3\n@test collect(v) == [1, 2, 3]\n\n# Create a 2-form (an axial vector) from a tuple:\na = Form{3,2}((1, 2, 3))\n@test a[1, 2] == 1\n@test a[1, 3] == 2\n@test a[2, 3] == 3\n@test collect(a) == [1, 2, 3]\n\n# Create a 3-form (a pseudoscalar):\np = Form{3,3}((1,))\n@test p[1, 2, 3] == 1\n@test p[end] == 1\n@test collect(p) == [1]\n\n# Add, subtract, scale\na2 = 2 * a\na3 = a + a2\n@test a3 == 3 * a\n\n# Exterior product (type \\wedge<tab>)\n# q = wedge(v, a)\nq = v \u2227 a\n@test q == Form{3,3}((2,))\n\n# Dot product (type \\cdot<tab>)\n# b = dot(v, v)\nb = v \u22c5 v\n@test b == 14 * one(Form{3})\nc = a \u22c5 a\n@test c == 14 * one(Form{3})\n\n# Cross product (type \\times<tab>)\n# w = cross(a, a)\nw = v \u00d7 v\n@test w == zero(Form{3,1})\n", "meta": {"hexsha": "fe2ab82afe45e2b07076789cccf4cbe96dd720b3", "size": 919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-examples.jl", "max_stars_repo_name": "eschnett/DifferentialForms.jl", "max_stars_repo_head_hexsha": "3c392810163a9024b554966a11444dfda324f349", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-08-19T18:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T02:13:11.000Z", "max_issues_repo_path": "test/test-examples.jl", "max_issues_repo_name": "eschnett/DifferentialForms.jl", "max_issues_repo_head_hexsha": "3c392810163a9024b554966a11444dfda324f349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-09-10T13:00:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T22:43:28.000Z", "max_forks_repo_path": "test/test-examples.jl", "max_forks_repo_name": "eschnett/DifferentialForms.jl", "max_forks_repo_head_hexsha": "3c392810163a9024b554966a11444dfda324f349", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-10T13:01:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T13:01:39.000Z", "avg_line_length": 18.7551020408, "max_line_length": 49, "alphanum_fraction": 0.5310119695, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013549, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7608915346333943}}
{"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": "function triangle_centrality1(A)\n    T = mul(A, A', Semirings.PLUS_TIMES[Float64], mask=A)\n    y = reduce(Monoids.PLUS_MONOID[Float64], T, dims=2)\n    k = reduce(Monoids.PLUS_MONOID[Float64], y)\n    return (3 * mul(A, y) - 2 * mul(T, y) .+ y) ./ k\nend\n\nfunction triangle_centrality2(A)\n    T = mul(A, A', Semirings.PLUS_PAIR, mask=A, desc=Descriptors.S)\n    y = reduce(Monoids.PLUS_MONOID[Float64], T, dims=2)\n    k = reduce(Monoids.PLUS_MONOID[Float64], y)\n    return map(BinaryOps.TIMES, eadd(eadd(3.0 * mul(A, y), 2.0 * mul(T, y, Semirings.PLUS_SECOND), BinaryOps.MINUS), y), 1/k)\nend\n", "meta": {"hexsha": "83ffa920979da72a91fa30c4b62d56408ebe886c", "size": 588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/triangle_centrality.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/triangle_centrality.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/triangle_centrality.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": 42.0, "max_line_length": 125, "alphanum_fraction": 0.6632653061, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7608510698076185}}
{"text": "using Printf, LinearAlgebra\r\nimport FixedPointNumbers: N0f8\r\nimport Images\r\nimport CSV, DataFrames\r\nimport Cairo\r\n\r\ntoRadians(\u03b1::Float64) = \u03b1 / 180.0 * \u03c0\r\ntoDegrees(\u03b1::Float64) = \u03b1 * 180.0 / \u03c0\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\u00b2::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\u00b2 = 1.0 - b*b/(a*a) # or f * (2.0-f)\r\n        e  = sqrt(e\u00b2)\r\n        new(a,b,f,e,e\u00b2)\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    \u03a6    = toRadians(llh.lat)\r\n    \u03bb    = toRadians(llh.lon)\r\n    h    = llh.height\r\n    e\u00b2   = ellipsoid.e\u00b2\r\n    sin\u03a6 = sin(\u03a6)\r\n    cos\u03a6 = cos(\u03a6)\r\n    sin\u03bb = sin(\u03bb)\r\n    cos\u03bb = cos(\u03bb)\r\n    v = ellipsoid.a / sqrt(1.0 - e\u00b2 * sin\u03a6 * sin\u03a6)\r\n    x = (v+h) * cos\u03a6 * cos\u03bb\r\n    y = (v+h) * cos\u03a6 * sin\u03bb\r\n    z = ((1.0 - e\u00b2) * v + h) * sin\u03a6;\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\u00b2       = ellipsoid.e\u00b2\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\u00b2)))\r\n    v        = ellipsoid.a / sqrt(1.0-e\u00b2*sin(lat_init)*sin(lat_init))\r\n    lat      = atan((xyz.z + e\u00b2*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    \u03a6    = toRadians(llh.lat)\r\n    \u03bb    = toRadians(llh.lon)\r\n    h    = llh.height\r\n    cos\u03a6 = cos(\u03a6)\r\n    v    = ellipsioid.r + h\r\n    x    = v * cos\u03a6 * cos(\u03bb)\r\n    y    = v * cos\u03a6 * sin(\u03bb)\r\n    z    = v * sin(\u03a6)\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    \u03c61 = toRadians(p1.lat)\r\n    \u03c62 = toRadians(p2.lat)\r\n    \u0394\u03bb = toRadians(p2.lon-p1.lon)\r\n    y  = sin(\u0394\u03bb)*cos(\u03c62)\r\n    x  = cos(\u03c61)*sin(\u03c62) - sin(\u03c61)*cos(\u03c62)*cos(\u0394\u03bb)\r\n    \u03b8  = atan(y, x)\r\n    return mod(toDegrees(\u03b8) + 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\u00b0N %d\u00b0E - %d\u00b0N %d\u00b0E ... (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*\u03c0),\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*\u03c0)\r\n            throw(DomainError(azimuthDiff, \"Azimuth difference should not exceed 2\u03c0\"))\r\n        end\r\n        if (azimuthMinR > azimuthMaxR)\r\n            azimuthMinR = azimuthMinR - 2.0*\u03c0\r\n        end\r\n        if (azimuthMinR < 0.0 && azimuthMaxR < 0.0)\r\n            azimuthMinR = azimuthMinR + 2.0*\u03c0\r\n            azimuthMaxR = azimuthMaxR + 2.0*\u03c0\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) \u2264 valueTolerance)\r\n                return true\r\n            end\r\n            if (mapValue < value) && ((value - mapValue) \u2264 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 \u00b0\", 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 \u22c5 y)\r\n\r\n    # cross product\r\n    println(cross(x,y))\r\n    println(x \u00d7 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# \u8ca0\u306e\u4e8c\u9805\u5206\u5e03\u306e\u78ba\u7387\u51fd\u6570\u306f\n#\n# $$\n# P(k) = \\binom{k+r-1}{k} p^r (1 - p)^k \\quad (k = 0,1,2,\\ldots)\n# $$\n#\n# \u3067\u3042\u308a, $k$ \u306f\u6210\u529f\u78ba\u7387 $p$ \u306eBernoulli\u8a66\u884c\u3067\u521d\u3081\u3066 $r$ \u56de\u6210\u529f\u3059\u308b\u307e\u3067\u306e\u5931\u6557\u3059\u308b\u56de\u6570\u3092\u610f\u5473\u3057\u3066\u3044\u308b. \n#\n# \u3053\u308c\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092 $r = \\alpha$, $p = 1/(N\\theta)$ \u3068\u304a\u304f\u3068, $N$ \u304c\u5927\u304d\u3044\u3068\u304d $k/N$ \u306f\u8fd1\u4f3c\u7684\u306b\u5206\u5e03 $\\operatorname{Gamma}(\\alpha, \\theta)$ \u306b\u5f93\u3046.\n\n# %%\nfunction plot_scaled_negbin(; \u03b1 = 3, \u03b8 = 5, N = 100)\n    gamma = Gamma(\u03b1, \u03b8)\n    negbin = LocationScale(0, 1/N, NegativeBinomial(\u03b1, 1/(N*\u03b8)))\n    \n    xmax = quantile(gamma, 0.995)\n    plot(; legend=:bottomright)\n    plot!(x -> cdf(negbin, x), 0, xmax; label=\"NegativeBinomial(r = \u03b1, p = 1/(N\u03b8)) scaled by 1/N\")\n    plot!(x -> cdf(gamma, x), 0, xmax; label=\"Gamma(\u03b1 = $\u03b1, \u03b8 = $\u03b8)\", 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\u03b1 = 3\n\u03b8 = 5\nN = 100\ngamma = Gamma(\u03b1, \u03b8)\nnegbin = LocationScale(0, 1/N, NegativeBinomial(\u03b1, 1/(N*\u03b8)))\nX = rand(negbin, 10^5)\n\nxmax = 60\nstephist(X; norm=true, bin=0:xmax, label=\"NegativeBinomial(r = \u03b1, p = 1/(N\u03b8)) scaled by 1/N\")\nplot!(gamma, 0, xmax; label=\"Gamma(\u03b1 = $\u03b1, \u03b8 = $\u03b8)\", ls=:dash)\ntitle!(\"sample of scaled NegativeBinomial distribution for N = $N\"; titlefontsize=10)\n\n# %% [markdown]\n# \u4e8c\u9805\u5206\u5e03\u306e\u78ba\u7387\u51fd\u6570\u306f\n#\n# $$\n# P(k) = \\binom{n}{k} p^k (1 - p)^{n-k} \\quad (k = 0,1,\\ldots,n)\n# $$\n#\n# \u3067\u3042\u308a, $k$ \u306f\u6210\u529f\u78ba\u7387 $p$ \u306e $n$ \u56de\u306eBernoulli\u8a66\u884c\u4e2d\u306e\u6210\u529f\u56de\u6570\u3092\u610f\u5473\u3057\u3066\u3044\u308b.\n#\n# \u3053\u308c\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092 $p = \\lambda/n$ \u3068\u304a\u304f\u3068, $n$ \u304c\u5927\u304d\u3044\u3068\u304d $k$ \u306f\u8fd1\u4f3c\u7684\u306b\u5206\u5e03 $\\operatorname{Poisson}(\\lambda)$ \u306b\u5f93\u3046.\n\n# %%\nfunction plot_bin(; \u03bb = 5, n = 100)\n    poisson = Poisson(\u03bb)\n    bin(n) = Binomial(n, \u03bb/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 = \u03bb/n)\")\n    plot!(x -> cdf(poisson, x), 0, xmax; label=\"Poisson(\u03bb = $\u03bb)\", 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_\u221e`` 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 \u21a6 0 if all(lb \u2a7d x \u2a7d ub), +\u221e 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(\u03b1, dx, dt, xStart, xEnd, n, \u03ba, 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(\u03b1, dx, dt, xStart, xEnd, n, \u03ba, 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^\u03b1)/(dx^2)\n    r = mu * gamma(2-\u03b1)\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-\u03b1) .- j.^(1-\u03b1)\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": "using Stats\nusing Base.Test\n\n@test_approx_eq mean([1, 2, 3]) 2.0\n@test_approx_eq mean(1:3) 2.0\n\n@test_approx_eq geomean([1, 2, 3]) (6.0)^(1/3)\n@test_approx_eq geomean(1:3) (6.0)^(1/3)\n@test_approx_eq geomean([2, 8]) 4.0\n@test_approx_eq geomean([4, 1, 1/32]) 0.5\n@test geomean([1, 0, 2]) == 0.0\n\n@test_approx_eq harmmean([1, 2, 3]) 3 / (1 + 1/2 + 1/3)\n@test_approx_eq harmmean(1:3) 3 / (1 + 1/2 + 1/3)\n@test_approx_eq harmmean([1, 2, 4]) 12 / 7\n\n@test_approx_eq trimmean([-100, 2, 3, 7, 200], 0.0) 22.4\n@test_approx_eq trimmean([-100, 2, 3, 7, 200], 0.4) 4.0\n@test_approx_eq trimmean([-100, 2, 3, 7, 200], 0.8) 3.0\n\n@test_approx_eq wmean([1.0, 2.0, 3.0], [1/3, 1/3, 1/3]) 2.0\n@test_approx_eq wmean([1.0, 2.0, 3.0], [1.0, 0.0, 0.0]) 1.0\n@test_approx_eq wmean([1.0, 2.0, 3.0], [0.0, 1.0, 0.0]) 2.0\n@test_approx_eq wmean([1.0, 2.0, 3.0], [0.0, 0.0, 1.0]) 3.0\n@test_approx_eq wmean([1.0, 2.0, 3.0], [0.5, 0.0, 0.5]) 2.0\n@test_approx_eq wmean([1.0, 2.0, 3.0], [0.5, 0.5, 0.0]) 1.5\n@test_approx_eq wmean([1.0, 2.0, 3.0], [0.0, 0.5, 0.5]) 2.5\n\n@test_approx_eq wmean(1:3, [1/3, 1/3, 1/3]) 2.0\n@test_approx_eq wmean(1:3, [1.0, 0.0, 0.0]) 1.0\n@test_approx_eq wmean(1:3, [0.0, 1.0, 0.0]) 2.0\n@test_approx_eq wmean(1:3, [0.0, 0.0, 1.0]) 3.0\n@test_approx_eq wmean(1:3, [0.5, 0.0, 0.5]) 2.0\n@test_approx_eq wmean(1:3, [0.5, 0.5, 0.0]) 1.5\n@test_approx_eq wmean(1:3, [0.0, 0.5, 0.5]) 2.5\n\n@test_approx_eq mean(1:3, weights([1.0, 1.0, 0.5])) 1.8\n\n", "meta": {"hexsha": "2dcfe2a1015de549957ba74fc85da0dac1ce83df", "size": 1430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/means.jl", "max_stars_repo_name": "rened/Stats.jl", "max_stars_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-20T16:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T16:09:54.000Z", "max_issues_repo_path": "test/means.jl", "max_issues_repo_name": "rened/Stats.jl", "max_issues_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_issues_repo_licenses": ["Xnet", "X11"], "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/means.jl", "max_forks_repo_name": "rened/Stats.jl", "max_forks_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6666666667, "max_line_length": 59, "alphanum_fraction": 0.5986013986, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7607189286359988}}
{"text": "################################################################################\n#                                   SiO\u2082                                       #\n################################################################################\nexport SiO\u2082\n\n\"\"\"\nThis code creates a symbolic representation of the Sellmeier Equation model\nfor the index of refraction of amorphous SiO\u2082.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, \u201cInterspecimen comparison of the refractive index of fused\n    silica,\u201d J. Opt. Soc. Am.55,1205\u20131209 (1965)\nand has been validated from 0.21-6.7 \u03bcm (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\u2082 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\u00b2_SiO\u2082 = (\n    A\u2080 = 1,\n    B\u2081 = 0.6961663,\n    C\u2081 = (0.0684043)^2,     #                           [\u03bcm\u00b2]\n    B\u2082 = 0.4079426,\n    C\u2082 = (0.1162414)^2,     #                           [\u03bcm\u00b2]\n    B\u2083 = 0.8974794,\n    C\u2083 = (9.896161)^2,      #                           [\u03bcm\u00b2]\n    dn_dT = 6.1e-6,         # thermo-optic coefficient  [K\u207b\u00b9]\n    T\u2080 = 20,                # reference temperature     [\u00b0C]\n)\n\nfunction make_SiO\u2082(;p_n\u00b2=p_n\u00b2_SiO\u2082)\n\t@variables \u03bb, T\n\tn = sqrt(n\u00b2_sym_fmt1( \u03bb ; p_n\u00b2...)) + p_n\u00b2.dn_dT  *  ( T - p_n\u00b2.T\u2080  )\n\tn\u00b2 = n^2\n\t\u03b5 \t= diagm([n\u00b2, n\u00b2, n\u00b2])\n\tng = ng_model(n,\u03bb)\n\tgvd = gvd_model(n,\u03bb)\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:\u03b5 \t\t=> \tdiagm([n\u00b2, n\u00b2, n\u00b2]),\n\t])\n\tdefaults =\tDict([\n\t\t:\u03bb\t\t=>\t\t0.8,\t\t# \u03bcm\n\t\t:T\t\t=>\t\tp_n\u00b2.T\u2080,\t# \u00b0C\n\n\t])\n\tMaterial(models, defaults, :SiO\u2082, colorant\"aqua\")\nend\n\n################################################################\n\nSiO\u2082 = make_SiO\u2082()\n# SiO\u2082_num = \n\n# struct NumMaterial{T,F1,F2,F3,TC} where {T, F1<:Function, F2<:Function, F3<:Function, TC}\n# \t\u03b5::T\n# \tf\u03b5::F1\n# \tfng::F2\n# \tfgvd::F3\n# \tf\u03c7\u207d\u00b2\u207e::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    \u03bcp = filter.d.A * b0.\u03bc + filter.d.B * u\n    \u03a3p = filter.d.A * b0.\u03a3 * filter.d.A' + filter.d.W\n    return GaussianBelief(\u03bcp, \u03a3p)\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.\u03a3 * filter.o.C' *\n        inv(filter.o.C * bp.\u03a3 * filter.o.C' + filter.o.V)\n\n    # Predicted measurement\n    yp = measure(filter.o, bp.\u03bc, u)\n\n    # Measurement update\n    \u03bcn = bp.\u03bc + K * (y-yp)\n    \u03a3n = (I - K * filter.o.C) * bp.\u03a3\n    return GaussianBelief(\u03bcn, \u03a3n)\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,\u03c3=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;\u03c3=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,\u03c3=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, \u03c3=0.05, T=1, trials=100_000_000\n    @show bs = C(S_t,t;T=T,K=K,r=r,\u03c3=\u03c3)\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,\u03c3=\u03c3) |> 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, \u03c3=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,\u03c3=\u03c3) |> 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, \u03c3=0.05, T=1, trials=100_000_000\n    @show exact = binary(S_t,t;E=E,r=r,\u03c3=\u03c3,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,\u03c3=\u03c3) |> 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,\u03c3=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": "@testset \"dijkstra (dense)\" begin\n    begin\n        g = AdjacencyMatrix(5)\n        setedge!(g, 1, 2, 10)\n        setedge!(g, 1, 3, 3)\n        setedge!(g, 1, 4, 20)\n        setedge!(g, 2, 4, 5)\n        setedge!(g, 3, 2, 2)\n        setedge!(g, 4, 5, 11)\n        setedge!(g, 3, 5, 15)\n    end\n    @test dijkstra(g, 1) == [0, 5, 3, 10, 18]\nend\n\n@testset \"dijkstra (sparse)\" begin\n    begin\n        g = AdjacencyList(5)\n        setedge!(g, 1, 2, 10)\n        setedge!(g, 1, 3, 3)\n        setedge!(g, 1, 4, 20)\n        setedge!(g, 2, 4, 5)\n        setedge!(g, 3, 2, 2)\n        setedge!(g, 4, 5, 11)\n        setedge!(g, 3, 5, 15)\n    end\n    @test dijkstra(g, 1) == [0, 5, 3, 10, 18]\nend\n\n\n@testset \"jarnik (dense)\" begin\n    begin\n        g = AdjacencyMatrix(6)\n            setedge!(g, 1, 3, 7)\n            setedge!(g, 3, 1, 7)\n            setedge!(g, 1, 5, 9)\n            setedge!(g, 5, 1, 9)\n            setedge!(g, 3, 2, 5)\n            setedge!(g, 2, 3, 5)\n            setedge!(g, 3, 4, 1)\n            setedge!(g, 4, 3, 1)\n            setedge!(g, 3, 6, 2)\n            setedge!(g, 6, 3, 2)\n            setedge!(g, 2, 6, 6)\n            setedge!(g, 6, 2, 6)\n            setedge!(g, 4, 6, 2)\n            setedge!(g, 6, 4, 2)\n            setedge!(g, 5, 6, 1)\n            setedge!(g, 6, 5, 1)\n        result = AdjacencyMatrix(6)\n            setedge!(result, 1, 3, 7)\n            setedge!(result, 3, 1, 7)\n            setedge!(result, 3, 2, 5)\n            setedge!(result, 2, 3, 5)\n            setedge!(result, 3, 4, 1)\n            setedge!(result, 4, 3, 1)\n            setedge!(result, 3, 6, 2)\n            setedge!(result, 6, 3, 2)\n            setedge!(result, 5, 6, 1)\n            setedge!(result, 6, 5, 1)\n    end\n    @test jarnik(g, 1) == result\nend\n", "meta": {"hexsha": "87665c997f8f32aebaf36eb02d8f0bd9b013f882", "size": 1744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/graph_algorithms.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": "test/graph_algorithms.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": "test/graph_algorithms.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": 27.6825396825, "max_line_length": 45, "alphanum_fraction": 0.4220183486, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7607140162904077}}
{"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 Rosenbrock function\n\n# A nonlinear example of the classical Rosenbrock function.\n\nusing JuMP\nimport Ipopt\nimport Test\n\nfunction example_rosenbrock()\n    model = Model(Ipopt.Optimizer)\n    set_silent(model)\n    @variable(model, x)\n    @variable(model, y)\n    @NLobjective(model, Min, (1 - x)^2 + 100 * (y - x^2)^2)\n    optimize!(model)\n\n    Test.@test termination_status(model) == MOI.LOCALLY_SOLVED\n    Test.@test primal_status(model) == MOI.FEASIBLE_POINT\n    Test.@test objective_value(model) \u2248 0.0 atol = 1e-10\n    Test.@test value(x) \u2248 1.0\n    Test.@test value(y) \u2248 1.0\n    return\nend\n\nexample_rosenbrock()\n", "meta": {"hexsha": "5586a9b85026b09dddb2357248107cad5dec79aa", "size": 960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/rosenbrock.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/rosenbrock.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/rosenbrock.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.9677419355, "max_line_length": 84, "alphanum_fraction": 0.66875, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8221891392358014, "lm_q1q2_score": 0.7607140152362205}}
{"text": "using Revise\nusing DifferenceEquations\nusing Distributions\nusing Optim\nusing Random\n\nfunction ar2_transition(u, p, t) # f\n    A = [p[1] p[2]; 1 0] \n    return A * u\nend\n\nfunction ar2_noise(u, p, t, noise::Nothing) # g\n    z = [p[3] * randn(); 0]\n    println(z)\n    return [p[3] * randn(); 0]\nend\n\nfunction ar2_noise(u, p, t, noise) # g\n    return [noise; 0]\nend\n\nfunction ar2_observation(u, p, t, noise) # h\n    # @info \"Observation\" u\n    return [1 0] * u\nend\n\nRandom.seed!(1)\n\np = [0.5, -0.25]\ntspan = (1, 15)\n\nphi1 = 0.5\nphi2 = -0.25\nsigma = 5.0\n\nY = zeros(tspan[2])\nn = sigma .* randn(length(Y))\nY += n\n\nfor t in 3:length(Y)\n    Y[t] += phi1 * Y[t-1] + phi2 * Y[t-2]\nend\n\nu0 = [Y[2]; Y[1]]\n\n# prob = StateSpaceProblem(\n#     ar2_transition, \n#     ar2_noise, \n#     ar2_observation, \n#     MvNormal(1,1), \n#     [0.0, 0.0],\n#     tspan, \n#     nothing, \n#     Y\n# )\n\nprob = StateSpaceProblem(\n    ar2_transition, \n    ar2_noise, \n    ar2_observation, \n    MvNormal(1,1), \n    [0.0, 0.0],\n    tspan, \n    nothing, #n, \n    Y\n)\n\nsol = DifferenceEquations._solve(prob, [phi1, phi2, sigma])\n# target(x) = -DifferenceEquations._solve(prob, x).likelihood\n# res = optimize(target, [0.0, 0.0, 1.0], LBFGS())\n", "meta": {"hexsha": "3f3282372970bfefc21bf6cf1604c73fa8be053d", "size": 1204, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tst.jl", "max_stars_repo_name": "DawievLill/DifferenceEquations.jl", "max_stars_repo_head_hexsha": "14a50c6b6abacbd22e93122f7934b0f787ca721f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tst.jl", "max_issues_repo_name": "DawievLill/DifferenceEquations.jl", "max_issues_repo_head_hexsha": "14a50c6b6abacbd22e93122f7934b0f787ca721f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tst.jl", "max_forks_repo_name": "DawievLill/DifferenceEquations.jl", "max_forks_repo_head_hexsha": "14a50c6b6abacbd22e93122f7934b0f787ca721f", "max_forks_repo_licenses": ["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.9577464789, "max_line_length": 61, "alphanum_fraction": 0.5772425249, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7607140079076276}}
{"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 + \u2211_{i \u2260 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        \u03b1 = A[j, j]\n        for i in 1:size(A, 1)\n            if i \u2260 j\n                \u03b1 += abs(A[i, j])\n            end\n        end\n        if \u03b1 > out\n            out = \u03b1\n        end\n    end\n    return out\nend\n\n# max_i a_ii + \u2211_{j \u2260 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        \u03b1 = A[i, i]\n        for j in 1:size(A, 2)\n            if i \u2260 j\n                \u03b1 += abs(A[i, j])\n            end\n        end\n        if \u03b1 > out\n            out = \u03b1\n        end\n    end\n    return out\nend\n\n# max_j  1/2 * \u03bb\u2c7c(A + A^T)\nfunction logarithmic_norm_2(A::AbstractMatrix)\n    B = A + A'\n    \u03bb = eigvals(B)\n    return maximum(\u03bb) / 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        \u03b4 = e1.v - e2.v\n        return abs(\u03b4)\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(\u03c4, u\u2080, \u03b1, \u03b2)\n    exp\u1d58 = exp(-\u03b2 * \u03c4)\n    u\u2080 * exp\u1d58 + \u03b1 / \u03b2 * (1 - exp\u1d58)\nend\n\nfunction spliced(\u03c4, s\u2080, u\u2080, \u03b1, \u03b2, \u03b3)\n    c = (\u03b1 - u\u2080 * \u03b2) / (\u03b3 - \u03b2)\n    exp\u1d58 = exp(-\u03b2 * \u03c4)\n    exp\u02e2 = exp(-\u03b3 * \u03c4)\n    s\u2080 * exp\u02e2 + \u03b1 / \u03b3 * (1 - exp\u02e2) + c * (exp\u02e2 - exp\u1d58)\nend\n\nfunction mRNA(\u03c4, u\u2080, s\u2080, \u03b1, \u03b2, \u03b3)\n    exp\u1d58, exp\u02e2 = exp(-\u03b2 * \u03c4), exp(-\u03b3 * \u03c4)\n    exp\u1d58\u02e2 = (\u03b1 - u\u2080 * \u03b2) * inv(\u03b3 - \u03b2) * (exp\u02e2 - exp\u1d58)\n    u = u\u2080 * exp\u1d58 + \u03b1 / \u03b2 * (1 - exp\u1d58)\n    s = s\u2080 * exp\u02e2 + \u03b1 / \u03b3 * (1 - exp\u02e2) + exp\u1d58\u02e2\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": "module OrdinalRegr\n\nusing Convex, SCS\n\nstruct OrdinalSVM\n    w\n    b\n    L\nend\n\nfunction fitordinalsvm(y, X, L; C=1e-2)\n    n, p = size(X)\n    l = length(L)\n    w = Variable(p)\n    b = Variable(l - 1)\n    # get indexes of the labels\n    inds = convert(Vector{Int}, indexin(y, L))\n    # compute objective\n    obj = C * sum(w .* w)\n    f = X * w\n    for (j, lj) in enumerate(L[1:end-1])\n        for (i, yi) in enumerate(y)\n            obj += yi \u2264 lj ? max(0.0, 1.0 + (f[i] - b[j])) : max(0.0, 1.0 - (f[i] - b[j]))\n        end\n    end\n    problem = minimize(obj, (b[i] <= b[i+1] for i in 1:l-2)...)\n    solve!(problem, () -> SCS.Optimizer(verbose=false))\n    return OrdinalSVM(w.value[:], b.value[:], L)\nend\n\nfitordinalsvm(y, X; C=1e-2) = fitordinalsvm(y, X, sort!(unique(y)); C=1e-2)\n\n\"\"\"\n    score(model::OrdinalSVM, X::AbstractMatrix)\n\nCompute the scoring using an `OrdinalSVM` model.\n\"\"\"\nfunction score(model::OrdinalSVM, X::AbstractMatrix)\n    X * model.w\nend\n\n\"\"\"\npredict(model::OrdinalSVM, X::AbstractMatrix)\n\nPredict the label using an `OrdinalSVM` model.\n\"\"\"\nfunction predict(model::OrdinalSVM, X::AbstractMatrix)\n    l = [model.L[1] for i in 1:size(X, 1)]\n    for (i, s) in enumerate(score(model, X))\n        for (Lj, bj) in zip(model.L[2:end], model.b)\n            s - bj \u2265 0 && (l[i] = Lj)\n        end\n    end\n    return l\n\nend\n\n\nend", "meta": {"hexsha": "d4be5290c3bb855e5fdc8fe0a4d816bd3fb76cae", "size": 1342, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ordinalregr.jl", "max_stars_repo_name": "lizard-bio/BioLizard.jl", "max_stars_repo_head_hexsha": "dcca2c73b2248fb8aa6373cc07e611adfc171ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ordinalregr.jl", "max_issues_repo_name": "lizard-bio/BioLizard.jl", "max_issues_repo_head_hexsha": "dcca2c73b2248fb8aa6373cc07e611adfc171ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ordinalregr.jl", "max_forks_repo_name": "lizard-bio/BioLizard.jl", "max_forks_repo_head_hexsha": "dcca2c73b2248fb8aa6373cc07e611adfc171ace", "max_forks_repo_licenses": ["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.7457627119, "max_line_length": 90, "alphanum_fraction": 0.5730253353, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7606592692653127}}
{"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\u00f72:N-1-N\u00f72)*(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\u00f72:N-1-N\u00f72)*(\u03c0/max_val)\r\nend\r\n\r\nfunction get_fourier_transform(k_max::Float64,N::Int64,\u03c80)\r\n\t#Calculates the Fourier transform of the given initial profile \u03c80\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 \u03c80s\r\n\t\u03c80s = convert(Matrix{ComplexF64},[ \u03c80(x,y) for x in rs, y in rs])\r\n\r\n\t#Then, we calculate the Fourier transform of \u03c8, which returns a matrix\r\n\t\u03d5s =  (0.5*\u03c0/k_max^2)*ifftshift( fft( fftshift(  ifftshift(fft(fftshift(\u03c80s,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),\u03d5s,extrapolation_bc=0.0)\r\nend\r\n\r\nfunction display_fourier_transform(plot_range::Float64,plot_N::Int64,clim::Float64,\u03d5)\r\n\t#Displays the fourier transform \u03d5. 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(\u03d5(kx,ky)*conj(\u03d5(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,\u03d5)\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] = \u03d5(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*\u03c0/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,\u03d5,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] = \u03d5(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*\u03c0/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,\u03d5)\r\n\t#Displays a propageted beam\r\n\trs = get_dft_interval(r_max,N)\r\n\t\u03c8s = propagate_beam(r_max,N,z,\u03d5)\r\n\r\n\tI = real(\u03c8s.*conj(\u03c8s))\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,\u03d5,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\u03c8s = propagate_beam(r_max,N,z,\u03d5,plan1,plan2)\r\n\r\n\t\tI = real(\u03c8s.*conj(\u03c8s))\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": "# code for Video 4.2:\r\nPkg.add(\"Winston\")\r\nPkg.add(\"Gadfly\")\r\nPkg.add(\"PyPlot\")\r\nusing Winston, Gadfly, PyPlot\r\n\r\nfname = \"iris.csv\"\r\nusing DataFrames\r\ndata = readtable(fname, separator = ',')\r\nhist(data[:sepal_length])  # (4.0:0.5:8.0,[5,27,27,30,31,18,6,6])\r\n\r\n# drawing the histogram with Winston:\r\np = FramedPlot(title=\"Histogram sepal length\", xlabel=\"Sepal Length\", ylabel=\"Frequency\")\r\nadd(p, Winston.Histogram(hist(data[:sepal_length])...))\r\ndisplay(p) # not necessary in the REPL\r\nsavefig(p, \"Winston_Histogram.png\")\r\n\r\n# plotting with Gadfly:\r\nusing Gadfly\r\np = plot(data, x=\"sepal_length\", y=\"petal_length\", color=\"species\", Geom.smooth, \r\n    Guide.title(\"Lengths (\\\"length_width\\\")\"))\r\ndraw(PDF(\"lengths.pdf\", 14cm, 10cm), p)\r\n\r\n# drawing with PyPlot:\r\nusing PyPlot\r\nx = data[:sepal_width]\r\nnbins = 50\r\nax = axes()\r\nh = plt[:hist](x, nbins) # Histogram\r\nPyPlot.grid(\"on\")\r\nPyPlot.xlabel(\"sepal width\")\r\nPyPlot.ylabel(\"frequency\")\r\nPyPlot.title(\"Histogram\")", "meta": {"hexsha": "6ed3df4ad2018f6197d71ef3a05689f73189b2ae", "size": 969, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Section 4/4_2.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_2.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_2.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": 29.3636363636, "max_line_length": 90, "alphanum_fraction": 0.6800825593, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7606592639214844}}
{"text": "\"\"\"\n\tMMC(\u03bc, \u03bb, c)\n\nT\u1ea1o m\u00f4 h\u00ecnh M/M/c\n\"\"\"\nstruct MMC{T} <: AbstractMMCK\n\t\u03bc::Union{T, Real}\n\t\u03bb::Union{T, Real}\n\tc::Union{T, Integer}\n\tr::Union{T, Real}\n\t\u03c1::Union{T, Real}\n\tfunction MMC(\u03bb, \u03bc, c)\n\t\tr = \u03bb / \u03bc\n\t\t\u03c1 = r / c\n\t\tT = Union{typeof(\u03bc), typeof(\u03bb)}\n\t\tnew{T}(\u03bc, \u03bb, c, r, \u03c1) \n\tend\nend\n\nfunction pn(m::MMC, n::Integer)\n\t\u03bc = m.\u03bc\n\t\u03bb = m.\u03bb\n\tc = m.c\n\tr = m.r\n\t\u03c1 = m.\u03c1\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\u03c1 = m.\u03c1\n\tc = m.c\n\tpn(m, 0) * r^c * \u03c1 / factorial(m.c) / (1 - \u03c1)^2\nend\n\nfunction Wq(m::MMC)\n\tLq(m) / m.\u03bb\nend\n\nfunction W(m::MMC)\n\tWq(m) + 1 / m.\u03bc\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": "function fit{C}(m::GaussianNB, X::Matrix{Float64}, y::Vector{C})\n    ensure_data_size(X, y)\n    # updatestats(m.dstats, X)\n    # m.gaussian = MvNormal(mean(m.dstats), cov(m.dstats))\n    # m.n_obs = m.dstats.n_obs\n    n_vars = size(X, 1)\n    for j=1:size(X, 2)\n        c = y[j]\n        m.c_counts[c] += 1\n        updatestats(m.c_stats[c], reshape(X[:, j], n_vars, 1))\n        # m.x_counts[c] .+= X[:, j]\n        # m.x_totals += X[:, j]\n        m.n_obs += 1\n    end\n    # precompute distributions for each class\n    for c in keys(m.c_counts)\n        m.gaussians[c] = MvNormal(mean(m.c_stats[c]), cov(m.c_stats[c]))\n    end\n    return m\nend\n\n\n\"\"\"Calculate log P(x|C)\"\"\"\nfunction logprob_x_given_c{C}(m::GaussianNB, x::Vector{Float64}, c::C)\n    return logpdf(m.gaussians[c], x)\nend\n\n\n\"\"\"Calculate log P(x|C)\"\"\"\nfunction logprob_x_given_c{C}(m::GaussianNB, X::Matrix{Float64}, c::C)\n    ## x_priors_for_c = m.x_counts[c] ./ m.x_totals\n    ## x_probs_given_c = x_priors_for_c .^ x\n    ## logprob = sum(log(x_probs_given_c))\n    ## return logprob\n    return logpdf(m.gaussians[c], X)\nend\n", "meta": {"hexsha": "a3f54fc3543f4ea39e41f88708ce1e96568a7b4e", "size": 1082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gaussian.jl", "max_stars_repo_name": "abieler/NaiveBayes.jl", "max_stars_repo_head_hexsha": "455a29f1254df382911cb768f62dee1f4f18a9c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gaussian.jl", "max_issues_repo_name": "abieler/NaiveBayes.jl", "max_issues_repo_head_hexsha": "455a29f1254df382911cb768f62dee1f4f18a9c3", "max_issues_repo_licenses": ["MIT"], "max_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": "abieler/NaiveBayes.jl", "max_forks_repo_head_hexsha": "455a29f1254df382911cb768f62dee1f4f18a9c3", "max_forks_repo_licenses": ["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.2432432432, "max_line_length": 72, "alphanum_fraction": 0.5998151571, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7606592579219486}}
{"text": "\"\"\"\n    bubble_sorting(array::Array{Int64,1})\n\nThe Bubble sorting algorithm (BSA) is a primitive sorting algorithm that repeatedly steps\nthrough the array by using a double for-loop with n and n-1 size. During the walkthrough,\nthe BSA compares adjacent elements and swaps wrong ordered elements until the array is\nsorted. For more information see: [https://en.wikipedia.org/wiki/Bubble_sort](https://en.wikipedia.org/wiki/Bubble_sort)\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.bubble_sorting(arr)\n[11, 12, 22, 25, 34, 64, 90]\n```\n\"\"\"\nfunction bubble_sorting(array::Array{Int64,1})\n    n = length(array)\n\n    # Traverse through all array elements\n    for i in 1:n\n        # Last i elements are already in place\n        for j in 1:n-i-1\n            # traverse the array from 1 to n-i-1\n            if array[j] > array[j+1]\n                # Swap if the element found is greater than the next element\n                array[j], array[j+1] = array[j+1], array[j]\n            end\n        end\n    end\n    return array\nend\n", "meta": {"hexsha": "8bfb305ee19166bb8d48f516a85a2bb2a91ca282", "size": 1189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SortingAndSearching/BubbleSorting.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/BubbleSorting.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/BubbleSorting.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.2894736842, "max_line_length": 120, "alphanum_fraction": 0.6728343146, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.7606589771790108}}
{"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# \u2554\u2550\u2561 f493fdb0-022f-11eb-34a6-4b133c23a71a\nusing OrdinaryDiffEq\n\n# \u2554\u2550\u2561 c803fe10-0231-11eb-1f84-dbe43fd97eb4\nusing Plots\n\n# \u2554\u2550\u2561 be8523c0-0239-11eb-0439-592e370c5618\nusing LaTeXStrings #rotulos de las figuras bonitos\n\n# \u2554\u2550\u2561 5fe018a0-023b-11eb-1e69-d59b562edc9b\nusing Symbolics\n#alternativamente tambi\u00e9n se puede usar SymEngine pero hay que definir el jacobiano a mano\n\n# \u2554\u2550\u2561 1c0442a0-a993-11eb-1b2d-55eb8b868dc7\n#algunas definiciones \u00fatiles\nbegin\n\tusing Latexify  # si no lo ten\u00e9is 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# \u2554\u2550\u2561 183a6460-a9ca-11eb-340e-872e08f29a9e\nusing LinearAlgebra\n\n# \u2554\u2550\u2561 c900ad60-095f-11eb-3d18-9f187abdb9b3\nusing PlutoUI\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6b1fd530-0a28-11eb-1142-47afd1798c3e\nhtml\"<button onclick=present()>Present</button>\"\n\n# \u2554\u2550\u2561 85c03440-0274-11eb-3c81-514259334750\nmd\"## Simulamos y pintamos\"\n\n# \u2554\u2550\u2561 e3e9d0a0-022c-11eb-04ba-97dcb9ba908a\nmd\"\"\"# Grado relativo \nLa idea es \"derivar hasta que sale u\" \n\"\"\"\n\n# \u2554\u2550\u2561 6831eb02-023b-11eb-0842-fbe8f8eb8937\nmd\"Vamos a usar c\u00e1lculo simb\u00f3lico\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6d535e50-a99a-11eb-08c1-4d98301e53b3\nbegin\n\t#escribir las ecuaciones simb\u00f3licas\n\tx=[x1;x2]\n\tdx1=x2\n\tdx2=-M*g*L/J*sin(x1)+u/J\n\tdx=[dx1;dx2]\nend\n\n# \u2554\u2550\u2561 5525d1a0-a9c7-11eb-1de0-1700c9c20460\ny=x1\n\n# \u2554\u2550\u2561 65893910-a9c7-11eb-2f9f-ebadf375cdbc\ndy=diff(y,x1)*dx1+diff(y,x2)*dx2\n\n# \u2554\u2550\u2561 a0571620-a9c7-11eb-070f-297fa9e406b2\nddy=diff(dy,x1)*dx1+diff(dy,x2)*dx2\n\n# \u2554\u2550\u2561 39ce8af0-023d-11eb-3178-857433b369ae\nmd\"ya aparece u --> grado relativo 2\"\n\n# \u2554\u2550\u2561 4c478bf0-023d-11eb-0dce-439d408010fa\nmd\"\u00bfEs repetitivo podemos hacerlo en general?\n hagamos una **funci\u00f3n**\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 697f24d0-a99a-11eb-26e6-a749fb04cb0f\n#usar la funci\u00f3n\nder=derivada(y,x,dx,2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 65ad8360-a99a-11eb-3764-aded1015107e\nbegin\n\t#definir v\n\tv=0\n\t@variables v\nend\n\n# \u2554\u2550\u2561 4b753d20-a9c8-11eb-320a-d58ec5e3c431\necuaci\u00f3n=der~v\n\n# \u2554\u2550\u2561 6e31c180-a9c8-11eb-3893-f55415fa4fad\nuc=solve_for(ecuaci\u00f3n,u)\n\n# \u2554\u2550\u2561 561e07e2-0250-11eb-1380-4b5dfa861cd6\nmd\"vamos a ver que lo hemos hecho bien\"\n\n# \u2554\u2550\u2561 64db3f40-a99a-11eb-01df-d3ca4846ca33\n#sustituir u en la derivada y ver que sale v\nexpand(subs(der,u=>uc))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c2f97c40-a99a-11eb-30e7-359effec0a1d\n#define z1 y su derivada z2\nz1=y\n\n# \u2554\u2550\u2561 85e1f1f0-a9c9-11eb-2a97-1944f7fcb34b\nz2=derivada(y,x,dx)\n\n# \u2554\u2550\u2561 0db8c9c0-0252-11eb-199c-2d69997c6769\nmd\"veamos que lo hemos hecho bien y la derivada es la corecta\"\n\n# \u2554\u2550\u2561 dd56c0c2-a99a-11eb-0c87-8f8e2c6321a8\nexpand(subs(derivada(z2,x,dx), u=>uc))\n\n# \u2554\u2550\u2561 72e4e740-022d-11eb-3a63-31023b9d464f\nmd\"\"\"# Difeomorfismo\nA partir de ahora controlaremos las **z** pero *OJO* que nuestro objetivo son las **x** \n\n\u00bfAl 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# \u2554\u2550\u2561 f1e0ee80-a99a-11eb-0c06-85f8d7086aac\n#definir el vector z, calcular el jacobiano y derivar\nz=[z1,z2]\n\n# \u2554\u2550\u2561 03abf0e0-a9ca-11eb-339c-5599c951871c\njac=jacobian(z,x)\n\n# \u2554\u2550\u2561 2d9109e0-a9ca-11eb-08a5-7596eee9e4b2\ndet(jac)\n\n# \u2554\u2550\u2561 9ec274e0-022d-11eb-085a-7907b8f1eb93\nmd\"\"\"# Estabilizaci\u00f3n\nEl sitema en las zs es lineal\nPara estabilizar la din\u00e1mica 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\u00edstico\n\n$$s^{(\\gamma)} +d_{\\gamma-1}s+...+d_1s+ d_0  =0$$\n\n## Elecci\u00f3n de polos\n\nHay que hacer que el polinomio sea hurwitz\nLo m\u00e1s f\u00e1cil 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0d736c40-0266-11eb-3433-ad75c1617314\nmd\"Entonces $d_0$ y $d_1$ son 1 y 2 ;)\"\n\n# \u2554\u2550\u2561 454272d0-a9cb-11eb-36db-ffb885a95a52\nstring(uc)\n\n# \u2554\u2550\u2561 f54ff5b2-0266-11eb-1df3-49f3c95729c7\nmd\"Ahora lo ponemos todo junto\"\n\n# \u2554\u2550\u2561 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\u00eds 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# \u2554\u2550\u2561 3b125190-0269-11eb-2473-33cbb7451779\nmd\"Si queremos podemos sustituir todo **ojo a veces no compensa** (por que queda muy largo y dif\u00edcil de depurar) en este caso si\"\n\n# \u2554\u2550\u2561 639dce00-0269-11eb-191e-d16a91f3bcf9\nu_sustituido=subs(uc,[v=>-2*y-3*dy,L=>1,M=>1,g=>1,J=>1])\n\n# \u2554\u2550\u2561 e0b21ca0-0a2c-11eb-0e50-efa6c355e7c5\nmd\"Pero **ojo** se pierde la interpretaci\u00f3n f\u00edsica de lo que hace el control\"\n\n# \u2554\u2550\u2561 f162f3f0-022d-11eb-30d9-55fb6e39c8c0\nmd\"\"\"# Seguimiento\nUna vez linealizado seguir una referencia es f\u00e1cil, 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\u00f1adiendo $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\u00f3n** no solo cambian los signos sino que *los \u00edndices ahora est\u00e1n \"bien\"* ya que $y=e_0$ no como antes que era $z_1$\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u00ed tambi\u00e9n 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\u00e9rminos de las zetas\n\t\n\t\n\tu=J*(v + L*M*g*sin(x1)/J)\n\treturn u\nend\t\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 922bccde-022d-11eb-17f2-270aae61f923\nmd\"\"\"# Din\u00e1mica cero\nEl ejemplo anterior funciona muy bien por dos motivos:\n1) Al derivar obtengo tantos estados como ten\u00eda antes (grado relativo m\u00e1ximo)\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 \u00bfy si no es as\u00ed? \u00bfQu\u00e9 pasa si u aparece \"demasiado pronto\"?\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8839fb60-095a-11eb-063e-85fd960ea83a\nmd\"Ya sabemos hacerlo, vamos al grano\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2a98e6e0-a227-11eb-026a-bb5831f344bb\nlet\n\tx0 = [0.1 0.1]\n\tparametros=[1 1 1 1] # una g un poco rara \u00bfno?\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\u00fan 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\u00f1al 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# \u2554\u2550\u2561 0610d2ee-0958-11eb-2490-19e0efcd3996\ndyb=derivada(yb,xb,dxb,1)\n\n# \u2554\u2550\u2561 52eade10-095b-11eb-0717-a9686481d875\nddyb=expand(derivada(yb,xb,dxb,2))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ab5f1de0-0960-11eb-2cf6-414898fd1323\njacobian([yb;dyb],xb)\n\n# \u2554\u2550\u2561 c7d09f80-0a28-11eb-3548-11dbb05bbbbb\nmd\"\"\"Vamos a seguir *como si nada* a ver que pasa...\n\"\"\"\n\n# \u2554\u2550\u2561 77f78c80-a997-11eb-0b80-8da3a424a52f\nstring(solve_for(ddyb~v,u))\n\n# \u2554\u2550\u2561 706b0500-0a2d-11eb-023e-1de0809fe6cf\nreferencia_2(t)=0*referencia_1_a(t)\n\n# \u2554\u2550\u2561 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\u00e1s 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c8a04540-095c-11eb-0b16-0bbf6ae0b6eb\nmd\"\"\"# \u00a1Funciona!\nPero si cambiamos a=1 por a=-1 \u00bfQu\u00e9 pasar\u00eda?\"\"\"\n\n# \u2554\u2550\u2561 062714d0-0a2e-11eb-073f-6bd47b020c54\n\tconstante_a=1\n\n# \u2554\u2550\u2561 667f8b70-095f-11eb-08a8-0f49a920e3cb\n@bind tf Slider(10:100)\n\n# \u2554\u2550\u2561 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\u00f1al 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# \u2554\u2550\u2561 1f8be93e-0962-11eb-14f4-73a59ba80a72\nmd\"\"\" Que raro... para ver que ha pasado veamos la din\u00e1mica 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\u00eda explica por qu\u00e9 x_1 se aleja del origen (din\u00e1mica cero inestable)\n\"\"\"\n\n# \u2554\u2550\u2561 41656a80-0a7c-11eb-1070-db649ce73728\nmd\"\"\"Para comprobar la teor\u00eda ponemos la referenica a cero, cuando la salida se haga cero lo que queda es \"la dim\u00e1mica cero\" y la teor\u00eda nos dice:\n\n-Din\u00e1mica cero asint\u00f3ticamete estable $\\to$ el sistema es **localmente** estable\n\n-Din\u00e1mica cero inestable $\\to$ el sistema es inestable\n\n**OJO** lo que la teor\u00eda no dice es que pueda seguir una trayectoria, en este caso la sigue pero podr\u00eda 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25005c4af6e0-022e-11eb-152f-2153b9b672c1\n# \u255f\u25006b1fd530-0a28-11eb-1142-47afd1798c3e\n# \u2560\u255085c0d350-022e-11eb-0873-c118ffde014c\n# \u2560\u2550506a20d0-026f-11eb-2bde-f94724bd27f3\n# \u2560\u2550f493fdb0-022f-11eb-34a6-4b133c23a71a\n# \u2560\u2550c803fe10-0231-11eb-1f84-dbe43fd97eb4\n# \u2560\u2550be8523c0-0239-11eb-0439-592e370c5618\n# \u255f\u250085c03440-0274-11eb-3c81-514259334750\n# \u255f\u25002a98e6e0-a227-11eb-026a-bb5831f344bb\n# \u255f\u2500e3e9d0a0-022c-11eb-04ba-97dcb9ba908a\n# \u255f\u25006831eb02-023b-11eb-0842-fbe8f8eb8937\n# \u2560\u25505fe018a0-023b-11eb-1e69-d59b562edc9b\n# \u2560\u25501c0442a0-a993-11eb-1b2d-55eb8b868dc7\n# \u2560\u25503ff84c30-0248-11eb-33ba-f99304ee8672\n# \u2560\u25506d535e50-a99a-11eb-08c1-4d98301e53b3\n# \u2560\u25505525d1a0-a9c7-11eb-1de0-1700c9c20460\n# \u2560\u255065893910-a9c7-11eb-2f9f-ebadf375cdbc\n# \u2560\u2550a0571620-a9c7-11eb-070f-297fa9e406b2\n# \u255f\u250039ce8af0-023d-11eb-3178-857433b369ae\n# \u255f\u25004c478bf0-023d-11eb-0dce-439d408010fa\n# \u255f\u2500b7e08f60-023d-11eb-13cb-ad5285e900d8\n# \u2560\u2550697f24d0-a99a-11eb-26e6-a749fb04cb0f\n# \u255f\u25009ecc5ff0-022d-11eb-3715-51831818d04f\n# \u2560\u255065ad8360-a99a-11eb-3764-aded1015107e\n# \u2560\u25504b753d20-a9c8-11eb-320a-d58ec5e3c431\n# \u2560\u25506e31c180-a9c8-11eb-3893-f55415fa4fad\n# \u255f\u2500561e07e2-0250-11eb-1380-4b5dfa861cd6\n# \u2560\u255064db3f40-a99a-11eb-01df-d3ca4846ca33\n# \u255f\u2500de497f50-0250-11eb-028e-ffe56cf1ba45\n# \u2560\u2550c2f97c40-a99a-11eb-30e7-359effec0a1d\n# \u2560\u255085e1f1f0-a9c9-11eb-2a97-1944f7fcb34b\n# \u255f\u25000db8c9c0-0252-11eb-199c-2d69997c6769\n# \u2560\u2550dd56c0c2-a99a-11eb-0c87-8f8e2c6321a8\n# \u255f\u250072e4e740-022d-11eb-3a63-31023b9d464f\n# \u2560\u2550f1e0ee80-a99a-11eb-0c06-85f8d7086aac\n# \u2560\u255003abf0e0-a9ca-11eb-339c-5599c951871c\n# \u2560\u2550183a6460-a9ca-11eb-340e-872e08f29a9e\n# \u2560\u25502d9109e0-a9ca-11eb-08a5-7596eee9e4b2\n# \u255f\u25009ec274e0-022d-11eb-085a-7907b8f1eb93\n# \u2560\u2550aed8d350-0265-11eb-1223-1dd0651632b6\n# \u255f\u25000d736c40-0266-11eb-3433-ad75c1617314\n# \u2560\u2550454272d0-a9cb-11eb-36db-ffb885a95a52\n# \u255f\u2500f54ff5b2-0266-11eb-1df3-49f3c95729c7\n# \u2560\u25502814f040-0267-11eb-3f4d-2933c0c3528a\n# \u255f\u25003b125190-0269-11eb-2473-33cbb7451779\n# \u2560\u2550639dce00-0269-11eb-191e-d16a91f3bcf9\n# \u255f\u2500e0b21ca0-0a2c-11eb-0e50-efa6c355e7c5\n# \u255f\u2500f162f3f0-022d-11eb-30d9-55fb6e39c8c0\n# \u2560\u2550a7745f70-026b-11eb-1abe-d1944165d231\n# \u2560\u2550a0e6f960-026b-11eb-23c9-410e6d61c4a1\n# \u255f\u2500922bccde-022d-11eb-17f2-270aae61f923\n# \u255f\u2500cc0e02e2-04c9-11eb-2e08-b906aaec3959\n# \u2560\u255097e9d100-04ca-11eb-07ea-3f5f5addbc45\n# \u255f\u25008839fb60-095a-11eb-063e-85fd960ea83a\n# \u2560\u255054523da0-0958-11eb-2730-cbef0823f684\n# \u2560\u25500610d2ee-0958-11eb-2490-19e0efcd3996\n# \u2560\u255052eade10-095b-11eb-0717-a9686481d875\n# \u255f\u25005c70004e-095b-11eb-0068-89e38689515b\n# \u2560\u2550ab5f1de0-0960-11eb-2cf6-414898fd1323\n# \u255f\u2500c7d09f80-0a28-11eb-3548-11dbb05bbbbb\n# \u2560\u255077f78c80-a997-11eb-0b80-8da3a424a52f\n# \u2560\u2550c8abde00-095c-11eb-237c-a9fd2bd95b8a\n# \u2560\u2550706b0500-0a2d-11eb-023e-1de0809fe6cf\n# \u255f\u2500c8a04540-095c-11eb-0b16-0bbf6ae0b6eb\n# \u2560\u2550062714d0-0a2e-11eb-073f-6bd47b020c54\n# \u2560\u2550c900ad60-095f-11eb-3d18-9f187abdb9b3\n# \u2560\u2550667f8b70-095f-11eb-08a8-0f49a920e3cb\n# \u255f\u2500b117ab50-04cc-11eb-1580-fdafb3c3213b\n# \u255f\u25001f8be93e-0962-11eb-14f4-73a59ba80a72\n# \u255f\u250041656a80-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\u221e 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": "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)\nfirst(df2, 5)\n\nheightsmodel = \"\n// Inferring a Rate\ndata {\n  int N;\n  real<lower=0> h[N];\n}\nparameters {\n  real<lower=0> sigma;\n  real<lower=0,upper=250> mu;\n}\nmodel {\n  // Priors for mu and sigma\n  mu ~ normal(178, 20);\n  sigma ~ uniform( 0 , 50 );\n\n  // Observed heights\n  h ~ normal(mu, sigma);\n}\n\";\n\nstanmodel = Stanmodel(name=\"heights\", monitors = [\"mu\", \"sigma\"],model=heightsmodel,\n  output_format=:mcmcchains);\n\nheightsdata = Dict(\"N\" => length(df2[:height]), \"h\" => df2[:height]);\n\nrc, chn, cnames = stan(stanmodel, heightsdata, ProjDir, diagnostics=false,\n  CmdStanDir=CMDSTAN_HOME);\n\nMCMCChains.describe(chn)\n\nserialize(\"m4.1s.jls\", chn)\nchn2 = deserialize(\"m4.1s.jls\")\n\nMCMCChains.describe(chn2)\n\n# end of m4.1s", "meta": {"hexsha": "a540f4f48a6ac59cebe533ec32429d28f6552546", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/04/m4.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/04/m4.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/04/m4.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": 20.4583333333, "max_line_length": 84, "alphanum_fraction": 0.6568228106, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7606589419358206}}
{"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# \u2554\u2550\u2561 a5d4303a-81b0-11ec-1083-ed13a1d29807\nusing PlutoUI, LinearAlgebra, FFTW,Plots, StructuredOptimization, Distributions, FileIO, QuartzImageIO, ImageShow, TestImages , Colors\n\n# \u2554\u2550\u2561 f4cb8cfd-b6b1-4e93-9985-2c71b384093f\nmd\"\"\"\n# Recovering images from a few pixels using compressed sensing (L\u2081-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 \u2208 R\u207f and a transform basis \u03a8 \u2208 R\u207f \u02e3 \u207f\t:\n\n\t\t\t\t\t\t\t\t\tx = \u03a8s\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 97006203-2819-489d-a4dc-cef3af6e72b3\nflower2 = Gray.(flower) #Convert to grayscale\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 * \u03c0 * t) + sin.(3266 * \u03c0 * 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2208 R\u207f and a transform basis \u03a8 \u2208 R\u207f \u02e3 \u207f:\n\n\t\t\t\t\t\t\t\t\tx = \u03a8s [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 \u03a8, it is possible to collect only a few measurements y \u2208 R\u1d56, 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 \u2208 R\u1d56 \u02e3 \u207f 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 \u03a8 (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\u2081 * K * log(n/K) (k\u2081 depends on how incoherent C and \u03a8 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\u03a8s = \u0398s [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\u015d = argmin ||s||\u2080 subject to y = C\u03a8s [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\u2081 norm or Manhattan norm:\n\n\t\t\t\t\t\u015d = argmin ||s||\u2081 subject to y = C\u03a8s [Eq. 5]\n[1]\n\n\n*Note on different norms*\n- *The l\u2080 norm is used to count non-zero elements in a vector*\n- *The l\u2081 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 \u0398 = C\u03a8 that preserves the distance and inner product structure of sparse vectors. We thus seek a measurement matrix C such that \u0398 acts as a near isometry map on sparse vectors. Isometry means that we perform a distance-preservind transformation. If now \u0398 acts as a near isometry, we can solve equation 3 using convex l\u2081 minimization.\n\nIn other words, the measurements C are good measurements if they are incoherent with respect to the columns of the sparsifying basis \u03a8. In this case the rows of C will have a small inner product with the columns of \u03a8. 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 \u03a8 is given by $$\u03bc(C,\u03a8) = \\sqrt{n}*max|\u27e8c_{k},\u03c8_{j}\u27e9|$$ where $$c_{k}$$ is the k-th row of the matrix C and $$\u03c8_{j}$$ is the j-th column of the matrix \u03c8. 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 \u03d5\u2096(t) = \u03b4(t \u2212 k) as C combined with the Fourier basis as \u03a8. This pair has a \u03bc(C,\u03a8) = 1, giving us maximal incoherence. In a second example, we have noiselets for C and wavelet bases as \u03a8. 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 \u03a8 in this case is then about 2 log(n) [8]. This last example is shown below in the code.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u015d = argmin ||s||\u2081 subject to y = C\u03a8s\n\nWe can solve this using the StructuredOptimization.jl package (more details on this package later).\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d32b08c7-8262-4231-9469-df9f667e5c59\n~s\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2082-norm minimization to solve the sparsity problem, we have solved the example for the l\u2082-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\u2081-norm. We are thus not able to reconstruct the original signal using l\u2082-norm minimization (see plot in time domain).\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4d4ec391-7219-459a-9b49-6ba901eeae92\n~s1\n\n# \u2554\u2550\u2561 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\u2081)\")\n\tplot!(freq, ~s1, color=\"green\", label = \"Reconstructed signal (l\u2082)\")\nend\n\n# \u2554\u2550\u2561 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\u2081)\", color=\"orange\")\n\tplot!(t, idct(~s1), label = \"Reconstructed signal (l\u2082)\", color = \"green\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 afb35a7d-1454-4c8f-a230-daabafc8e7a3\nmd\"\"\"\n### Algorithms for l\u2081-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\u2081-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\u015d = argmin (||C\u03a8s - y||\u00b2)/2 + \u03bb||s||\u2081  [Eq. 6]\n\nwhere \u03bb \u2265 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\u2081-norm minimization. The first one is the Alternating Direction Method of Multipliers (ADMM) and the second one is l\u2081-norm minimization via l\u2082-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\u03c1(x, z, y) = f(x) + g(z) + y\u1d40(Ax + Bz - c) + (\u03c1/2)||Ax + Bz - c||\u00b2\u2082\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 \u03c1.\n\n\t\t\t\tx\u1d4f\u207a\u00b9 := argmin(x)  L\u03c1(x, z\u1d4f, y\u1d4f)\n\t\t\t\tz\u1d4f\u207a\u00b9 := argmin(z)  L\u03c1(x\u1d4f\u207a\u00b9, z, y\u1d4f)\n\t\t\t\ty\u1d4f\u207a\u00b9 := y\u1d4f + \u03c1(Ax\u1d4f\u207a\u00b9 + Bz\u1d4f\u207a\u00b9 - c) where \u03c1 > 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\u2081-norm minimization via l\u2082-norm minimization \n\nIn this last paragraph we introduce the state of the art compressed sensing reconstruction algorithm which uses l\u2082-norm minimization to achieve l\u2081-norm minimization. This method makes use of the geometrical interpretation of the minimization problem and the fact that the Euclidean distance between the l\u2081-norm and the l\u2082-norm solutions lie closely to one another. This means that if we can find the l\u2082-norm solution, the direction of the l\u2081-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 \u2208 R\u1d39 and A \u2208 R\u1d39\u02e3\u1d3a with sparsity k\n- Output: x\u02c6 \u2208 R\u1d3a\n- Extra information: Q = l\u2082-norm solution, P = l\u2081-norm minimization\n\n\t\t1: [M, N] <- dim(A)  # initiate the dimension\n\t\t2: \u03b3 <- det(AA\u1d40)\n\t\t3: If \u03b3 = 0 then stop, return x\u02c6<- {}, else continue to step 4\n\t\t4: calculate xQ <-(AA\u1d40)-A\u1d40y  # L2-norm solution\n\t\t5: [U \u03b6] = 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(\u222b(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\u1d40)^(-1)As\u1d40y    # L1-norm solution\n\t\t12: x\u02c6<- xp \n\t\t13: return x\u02c6\n\n\"\"\"\n\n# \u2554\u2550\u2561 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., \u201cDAGAN: Deep De-Aliasing Generative Adversarial Networks for Fast Compressed Sensing MRI Reconstruction,\u201d IEEE Trans. Med. Imaging, vol. 37, no. 6, pp. 1310\u20131321, Jun. 2018.\n\n[3] \u201ck-space (magnetic resonance imaging) - Wikipedia.\u201d [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, \u201cCompressed sensing MRI: A look at how CS can improve on current imaging techniques,\u201d IEEE Signal Process. Mag., vol. 25, no. 2, pp. 72\u201382, 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\u201322. 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\u201330. 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\u2013122. \n\n[10] Home \u00b7 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\u201350. 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550a5d4303a-81b0-11ec-1083-ed13a1d29807\n# \u255f\u2500f4cb8cfd-b6b1-4e93-9985-2c71b384093f\n# \u2560\u255062a8366f-14dc-410b-ba31-a8f695dfe986\n# \u2560\u255097006203-2819-489d-a4dc-cef3af6e72b3\n# \u2560\u25507415fc09-1155-49e5-b523-c9df2bd8d7d7\n# \u2560\u2550bc36eb16-5b31-4639-864c-4ee4b627108e\n# \u255f\u250056a83328-2689-42be-8dfd-8ee38c5a70e0\n# \u255f\u25006e37dfac-5f50-498b-b356-f56fcbd7d02a\n# \u255f\u250068a5c2c4-e1ca-420d-b421-c4f570308884\n# \u255f\u250039f25941-cab4-4776-9167-5b75d555fdbf\n# \u255f\u2500c899003d-bee5-4857-919a-8007d22c9f90\n# \u255f\u2500135c1b29-8e82-4d06-b2f6-ff6fa7e3f031\n# \u255f\u2500832052d7-c34d-4bce-8236-64cdc8f32be5\n# \u255f\u2500df23221a-1dc6-4f45-9f03-35bc12c48e46\n# \u2560\u25507a9864b2-fc6f-4b89-8efa-183d644f8943\n# \u2560\u2550d32b08c7-8262-4231-9469-df9f667e5c59\n# \u255f\u2500c490029b-2b61-42c4-bd5f-72ba844e03b0\n# \u255f\u25007a104d94-6062-47a2-82cb-553513e28a86\n# \u255f\u25002bef7c97-8b88-4203-8825-eda70d5fab56\n# \u2560\u25509c19aaf2-3c25-425b-9e48-4d90d1366ce2\n# \u2560\u25504d4ec391-7219-459a-9b49-6ba901eeae92\n# \u255f\u250057a799e2-68b2-4867-867a-24d8590a84a5\n# \u255f\u25007c3a2e4b-419f-44f1-bea7-20c7a3aa06a3\n# \u255f\u250084e6d7fb-4df6-498b-bd5c-151004756e9e\n# \u255f\u2500afb35a7d-1454-4c8f-a230-daabafc8e7a3\n# \u255f\u2500ef90c37f-0e7e-48d1-8ab3-4ae779c3ed91\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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\u2019s 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, \u03d5; kwargs...)\r\nCalculate daily averaged insolation in W/m\u00b2 at given time and latitude `t, \u03c6`.\r\n`\u03c6` 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\u03b3=23.44\r\n\u03d6=282.95\r\ne=0.017 # eccentricity\r\n```\r\n\"\"\"\r\ninsolation(t::TimeType, \u03c6; kwargs...) = insolation(float(dayofyear(t)), \u03c6; kwargs...)\r\nfunction insolation(t::Real, \u03d5;\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        \u03b3=23.44,\r\n        \u03d6=282.95,\r\n        e=0.017,\r\n    )\r\n\r\n    # convert inputs from degrees to radians\r\n    \u03d5 = \u03d5 * \u03c0 / 180\r\n    \u03b3 = \u03b3 * \u03c0 / 180\r\n    \u03d6 = \u03d6 * \u03c0 / 180\r\n\r\n    # step 1, calculate the mean anomaly at vernal equinox\r\n    \u03b2 = sqrt(1 - e^2)\r\n    M_VE = -\u03d6 + (e + e^3 / 4) * (1 + \u03b2) * sin(\u03d6)\r\n\r\n    # step 2, calculate the mean anomaly\r\n    M = (2 * \u03c0 * (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 + \u03d6\r\n\r\n    # step 6, calculate the declination angle\r\n    \u03b4 = asin(sin(\u03b3) * sin(L_s))\r\n\r\n    # step 7, calculate the sunrise/sunset angle\r\n    T = tan(\u03d5) * tan(\u03b4)\r\n    if T >= 1\r\n        \u03b7_d = \u03c0\r\n    elseif T <= -1\r\n        \u03b7_d = 0.0\r\n    else\r\n        \u03b7_d = acos(-1 * T)\r\n    end\r\n\r\n    # step 8, calculate the daily averaged cos(zenith angle)\r\n    c1 = \u03b7_d * sin(\u03d5) * sin(\u03b4)\r\n    c2 = cos(\u03d5) * cos(\u03b4) * sin(\u03b7_d)\r\n    cosbar = (1 / \u03c0) * (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 \u2014 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| \u2248 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": "\"\"\"\nComputes convex hull of 2D points. Assumes non-degenerate inputs.\n\"\"\"\nmodule ConvexHull\n\nconst Point{T} = Tuple{T, T}\n\nraw\"\"\"\nClassifies whether a point $r$ lies to the left or right of the oriented line $pq$.\n\nReturns:\n\n* -1 if $r$ lies to the left\n* 0 if $r$ lies on the line\n* 1 if $r$ lies to the right\n\n**Warning**: This computation is not robust. See [Robust Predicates for Computational\nGeometry][robust] for details. (If `BigFloat` is used, there is no rounding problems.)\n\n[robust]: http://www.cs.cmu.edu/%7Equake/robust.html\n\"\"\"\nfunction orient(p::Point{T},\n                q::Point{T},\n                r::Point{T})::T where T<:AbstractFloat\n    pr_x = r[1] - p[1]\n    pr_y = r[2] - p[2]\n    rq_x = q[1] - r[1]\n    rq_y = q[2] - r[2]\n    sign(pr_x * rq_y - pr_y * rq_x)\nend\n\n# Graham scan\n#\n# Computational Geometry: Algorithms and Applications, Chapter 1.\nfunction convex_hull_graham_scan!(points::Vector{Point{T}})::Vector{Point{T}} where T<:AbstractFloat\n    @assert length(points) >= 3 \"Too few points\"\n    sort!(points)  # in lexical order\n\n    function build_convex_hull(points::AbstractVector{Point{T}})\n        n = length(points)\n        hull = points[1:2]\n        sizehint!(hull, n)\n\n        for i in 3:n\n            while true\n                if orient(hull[end - 1], hull[end], points[i]) > 0\n                    break\n                else\n                    pop!(hull)\n                    if length(hull) < 2\n                        break\n                    end\n                end\n            end\n            push!(hull, points[i])\n        end\n\n        hull\n    end\n\n    upper_hull = build_convex_hull(points)\n    pop!(upper_hull)\n    lower_hull = build_convex_hull(@view points[end:-1:1])\n    pop!(lower_hull)\n\n    [upper_hull; lower_hull]\nend\n\n# Unsorted version, complexity: O(n^2)\nfunction convex_hull_incremental(points::Vector{Point{T}})::Vector{Point{T}} where T<:AbstractFloat\n    n = length(points)\n    @assert n >= 3 \"Too few points\"\n    hull = points[1:3]\n    if orient(hull[1], hull[2], hull[3]) < 0\n        hull[[1, 2]] .= hull[[2, 1]]\n    end\n    sizehint!(hull, n)\n\n    for i in 4:n\n        p = points[i]\n        # Vertices inside `[start, stop)` will be removed.\n        start::Union{Nothing, Int} = nothing\n        stop::Union{Nothing, Int} = nothing\n        h_len = length(hull)\n        prev_ori = orient(hull[end - 1], hull[end], p) >= 0\n\n        # trying to find two tangent lines\n        for (from, to) in ((mod1(i - 1, h_len), i) for i in 1:h_len)\n            curr_ori = orient(hull[from], hull[to], p) >= 0\n            if !curr_ori && prev_ori\n                start = to  # inclusive\n                if stop != nothing\n                    break\n                end\n            elseif curr_ori && !prev_ori\n                stop = from  # exclusive\n                if start != nothing\n                    break\n                end\n            end\n            prev_ori = curr_ori\n        end\n\n        # Always being on the right side, `p` must be inside the hull.\n        if start == nothing\n            continue\n        end\n        # If `start != nothing`, then `stop != nothing`.\n\n        # Note: `start == stop` means no vertices are removed.\n        if start <= stop\n            splice!(hull, start:(stop - 1), [p])\n        else\n            # The same as\n            #\n            #     hull = [hull[stop:(start - 1)]; p]\n            #\n            # but without allocating extra memory.\n            hull[start] = p\n            resize!(hull, start)\n            deleteat!(hull, 1:(stop - 1))\n        end\n    end\n    hull\nend\n\n#===== Unit Tests =====#\nusing Test\nusing Random: seed!\n\nfunction convex_hull_length(hull::Vector{Point{T}})::T where T<:AbstractFloat\n    hull2 = circshift(hull, -1)\n    map((x, y) -> hypot((x .- y)...), hull2, hull) |> sum\nend\n\n@testset \"Convex Hull\" begin\n    seed!()\n    n = 100\n    a = rand(n, 2)\n    points = [tuple(a[i, :]...) for i in 1:n]\n\n    cvh_increm = convex_hull_incremental(points)\n    cvh_graham = convex_hull_graham_scan!(points)\n    @test convex_hull_length(cvh_increm) \u2248 convex_hull_length(cvh_graham)\nend\nend # module\n", "meta": {"hexsha": "eec643ec13071e2d72c92b18cbe7003b4dc44437", "size": 4116, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ConvexHull/src/ConvexHull.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": "ConvexHull/src/ConvexHull.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": "ConvexHull/src/ConvexHull.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": 28.0, "max_line_length": 100, "alphanum_fraction": 0.5454324587, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7606049309457938}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.26\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.26\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550884176a0-21c0-11eb-06f8-55964a60d533\n# \u2560\u25508841a7b0-21c0-11eb-313a-bfa4eb49f351\n# \u255f\u250070182cd8-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    +(\u0398::DMS, \u03b1::DMS) = DMS(\u0398.seconds + \u03b1.seconds)      \n    -(\u0398::DMS, \u03b1::DMS) = DMS(\u0398.seconds - \u03b1.seconds)\n\n    +(\u0398::Radian, \u03b1::Radian) = Radian(\u0398.radians + \u03b1.radians)\n    -(\u0398::Radian, \u03b1::Radian) = Radian(\u0398.radians - \u03b1.radians)\n\n    function degrees(dms::DMS)\n        minutes = dms.seconds \u00f7 60\n        minutes \u00f7 60\n    end\n\n    function minutes(dms::DMS)\n        minutes = dms.seconds \u00f7 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), \"\u00b0 \", 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 \u00b0 = Degree(1)\n    const rad = Radian(1)\n\n    Base.promote_rule(::Type{Radian}, ::Type{DMS}) = Radian\nend\n# Examples\n# \u03b1 = Degree(90, 30, 45)\n# \u03b2 = \u03b1 + Degree(89, 29, 15)\n# sin(Degree(90))\n# sin(Radian(\u03c0/2))\n# sin(90\u00b0)\n# sin(1.5rad)\n\n# Problem\n# While this works:\n# +(promote(90\u00b0,3.14rad/2)...)\n# 3.140796326794897rad\n# Doing this\n# 90\u00b0+ 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  \u03b1,\u03c3,\u03c1,\u03b2 = p\n  du1 = u[1] + \u03b1*(\u03c3*(u[2]-u[1]))\n  du2 = u[2] + \u03b1*(u[1]*(\u03c1-u[3]) - u[2])\n  du3 = u[3] + \u03b1*(u[1]*u[2] - \u03b2*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  \u03b1,\u03c3,\u03c1,\u03b2 = p\n  du[1] = u[1] + \u03b1*(\u03c3*(u[2]-u[1]))\n  du[2] = u[2] + \u03b1*(u[1]*(\u03c1-u[3]) - u[2])\n  du[3] = u[3] + \u03b1*(u[1]*u[2] - \u03b2*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": "using PenaltyFunctions, LaTeXStrings, Plots\npyplot()\n\n_mkpath(fname) = joinpath(dirname(@__FILE__()), fname)\nsrand(123)\n\n# ---------------------------------------------------------------\n# README Plots\n\nfnt = Plots.Font(\"ubuntu\",8,:hcenter,:vcenter,0.0,\n                 RGB{FixedPointNumbers.Normed{UInt8, 8}}(0.0,0.0,0.0))\ndefault(bg_outside = RGBA(1,1,1,0),\n        grid = false,\n        legendfont = fnt,\n        palette = :darktest,\n        aspect_ratio = 1,\n        size = (400, 400))\n\np = plot(L1Penalty(); ylim = (0, 8))\nfor pen in [L2Penalty(),\n            ElasticNetPenalty(.5),\n            MCPPenalty(1.), SCADPenalty(3.7, 0.4),\n            LogPenalty(1.)]\n    plot!(p, pen)\nend\nplot!(p, xlab = L\"\\theta_1\", ylab = L\"g(\\theta_1)\", xlim = (-4, 4))\n\np[1][1][:linestyle] = :solid\np[1][2][:linestyle] = :solid\np[1][3][:linestyle] = :dash\np[1][4][:linestyle] = :dashdot\np[1][5][:linestyle] = :dash\np[1][6][:linestyle] = :dot\n\nPlots.svg(_mkpath(\"univariate\"))\n\nfunction cont_xy(penalty, stepx = 0.005, stepy = 0.0001)\n    x = -1:stepx:1\n    yp = 0:stepy:1\n    ref = round(value(penalty, [1., 0]), 4)\n    xs = collect(i for j in yp, i in x if round(value(penalty, [i,j]), 4) \u2248 ref)\n    ys = collect(j for j in yp, i in x if round(value(penalty, [i,j]), 4) \u2248 ref)\n    vcat(xs, reverse(xs)), vcat(ys, -ys)\nend\n\ndefault(size = (400, 400))\np = plot(cont_xy(L1Penalty())...)\nplot!(cont_xy(L2Penalty())...)\nplot!(cont_xy(ElasticNetPenalty(0.5))...)\nplot!(cont_xy(MCPPenalty(1.))...)\nplot!(cont_xy(SCADPenalty(3.7, 0.4))...)\nplot!(cont_xy(LogPenalty(1.))...)\nplot!(p, xlab = L\"\\theta_1\", ylab = L\"\\theta_2\",\n         legend = false,\n         xlim = (-1.2, 1.2), ylim = (-1.2, 1.2))\n\np[1][1][:linestyle] = :solid\np[1][2][:linestyle] = :solid\np[1][3][:linestyle] = :dash\np[1][4][:linestyle] = :dashdot\np[1][5][:linestyle] = :dash\np[1][6][:linestyle] = :dot\n\nPlots.svg(_mkpath(\"bivariate\"))\n\n\n", "meta": {"hexsha": "18815d7016fd4b05afc9ef43c162703e6530cfbc", "size": 1887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PenaltyFunctions/createplots.jl", "max_stars_repo_name": "JuliaTagBot/FileStorage", "max_stars_repo_head_hexsha": "2921a01b023682d3ec9731e5a7163fdbb2759254", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-12-02T21:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T06:59:00.000Z", "max_issues_repo_path": "PenaltyFunctions/createplots.jl", "max_issues_repo_name": "JuliaTagBot/FileStorage", "max_issues_repo_head_hexsha": "2921a01b023682d3ec9731e5a7163fdbb2759254", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PenaltyFunctions/createplots.jl", "max_forks_repo_name": "JuliaTagBot/FileStorage", "max_forks_repo_head_hexsha": "2921a01b023682d3ec9731e5a7163fdbb2759254", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T06:59:03.000Z", "avg_line_length": 28.1641791045, "max_line_length": 80, "alphanum_fraction": 0.5638579756, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.7604728002642932}}
{"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\u2091::Integer, N\u1d62::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\u2091); zeros(Bool, N\u1d62)]\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\u2091 = Int(ceil(EI_rate * n / (EI_rate + 1)))\n    else\n        N\u2091 = Int(ceil(EI_rate * n))\n    end\n    N\u1d62 = n - N\u2091\n    return EI(N\u2091, N\u1d62; 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 \u03b4L = 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(\u03b8) \\|_2^2``, ``\\nabla f = J^t r`` and ``\\nabla^2 f = J^t J``\n\nA direct computation gives:\n\n\n```math\n\u03b4L = 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\u03b4L = L(0)-L(h) = \\frac{1}{2} \\langle h, \\mu h - \\nabla f \\rangle\n```\n\"\"\"\nfunction compute_\u03b4L_unconstrained(\u2207f::AbstractVector,\n                                  \u03bc::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,\u2207f_i),)->h_i*(\u03bc*h_i-\u2207f_i),+,zip(h,\u2207f))/2\nend\n\n\n@doc raw\"\"\"\n\nSame idea than [`compute_\u03b4L_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\u03b4L = L(0)-L(h) = \\frac{1}{2} \\langle h, \\mu h + \\tau - \\nabla f \\rangle\n```\n\"\"\"\nfunction compute_\u03b4L_constrained(\u2207f::AbstractVector,\n                                \u03bc::Real,\n                                \u03c4::AbstractVector,\n                                h::AbstractVector)\n    mapreduce(((h_i,\u03c4_i,\u2207f_i),)->h_i*(\u03bc*h_i+\u03c4_i-\u2207f_i),+,zip(h,\u03c4,\u2207f))/2\nend\n\n\n@doc raw\"\"\"\n\nCompute true variation of the real model: ``\u03b4f = \\frac{1}{2}(r^t(\u03b8)r(\u03b8)-r^t(\u03b8+h)r(\u03b8+h))``\n\nContrary to ``\u03b4L`` things are simpler. However a trick is to use an equivalent formulation:\n\n```math\n\u03b4f = \\frac{1}{2}(r^t(\u03b8)r(\u03b8)-r^t(\u03b8+h)r(\u03b8+h)) = \\frac{1}{2}(r(\u03b8)-r(\u03b8+h))^t(r(\u03b8)+r(\u03b8+h))\n```\n\nthat has a better numerical behavior. \n\"\"\"\nfunction compute_\u03b4f(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": "workspace()\n\nusing IntervalArithmetic\nusing EAGOParametricInterval\n\n# Miranda Passed\nX = [Interval(1,3),Interval(1,3)]\nP = [Interval(1,3),Interval(1,3)]\nh(z,p) = [p[1]-z[1]; p[1]+z[1]]\nh1(z,p) = [p[1]-z[1]; p[1]-z[1]]\ntest_mir1 = Miranda(h,X,P)\ntest_mir2 = Miranda(h1,X,P)\nout_mir = h(X,P)\n\n# Miranda Exclusion Test Passed\nEflag_in = false\nex_mir1 = MirandaExc(h,X,P,Eflag_in)\nex_mir2 = MirandaExc(h1,X,P,Eflag_in)\nex_mir_flag_out = Eflag_in\n\n#\nY1 = [Interval(1,3),Interval(1,3)]\nY2 = [Interval(1.5,2.5),Interval(2.5,2.5)]\nY3 = [Interval(-1,2),Interval(-2,2)]\nY4 = [Interval(2,4),Interval(2,4)]\nY5 = [Interval(1.5,2.5),Interval(2.3,2.5)]\nY6 = [Interval(-1,4),Interval(-1,4)]\nY7 = [Interval(1.5,2.5),emptyinterval()]\nY8 = [emptyinterval(),emptyinterval()]\nY9 = [Interval(4,5),Interval(4,5)]\nY10 = [Interval(-2,-1),Interval(-2,-1)]\n\nsXY_flag1 = Strict_XinY(Y1,X)\nsXY_flag2 = Strict_XinY(Y2,X)\nsXY_flag3 = Strict_XinY(Y3,X)\nsXY_flag4 = Strict_XinY(Y4,X)\nsXY_flag5 = Strict_XinY(Y5,X)\nsXY_flag6 = Strict_XinY(Y6,X)\nsXY_flag7 = Strict_XinY(Y7,X)\nsXY_flag8 = Strict_XinY(Y8,X)\nsXY_flag9 = Strict_XinY(Y9,X)\nsXY_flag10 = Strict_XinY(Y10,X)\n\n#=\npartialIncTop(h,X,P,PIflag,incHigh)\n\npartialIncBot(h,X,P,PIflag,incLow)\n\nStrict_XinY(X,Y)\n\nisEqual(X1,X2,atol)\n\nextDivide(A,B,C)\n\nextProcess(N,X,Mii,S1,S2,B,rtol)\n=#\n", "meta": {"hexsha": "17c07647dfb92dd189c1a1a361752661c3eb6489", "size": 1303, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/TestSubFunc.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/EAGOParametricInterval.jl-943bb2e0-4606-56fd-97c8-8e4f771eb881", "max_stars_repo_head_hexsha": "6e82f669c9c3aed003b4fa8c3f5c5a6c1fe8936f", "max_stars_repo_licenses": ["MIT"], "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/TestSubFunc.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/EAGOParametricInterval.jl-943bb2e0-4606-56fd-97c8-8e4f771eb881", "max_issues_repo_head_hexsha": "6e82f669c9c3aed003b4fa8c3f5c5a6c1fe8936f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-03-06T13:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:27:58.000Z", "max_forks_repo_path": "example/TestSubFunc.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/EAGOParametricInterval.jl-943bb2e0-4606-56fd-97c8-8e4f771eb881", "max_forks_repo_head_hexsha": "6e82f669c9c3aed003b4fa8c3f5c5a6c1fe8936f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-03T12:52:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:52:35.000Z", "avg_line_length": 22.8596491228, "max_line_length": 42, "alphanum_fraction": 0.6891788181, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7604162328079234}}
{"text": "using Polylogarithms\nusing SpecialFunctions\nusing Test\nusing DataFrames, CSV\nimport Base.MathConstants: \u03c0, pi, \u212f, e, \u03b3, eulergamma, catalan, \u03c6, golden\ninclude(\"test_defs.jl\")\n\n@testset \"Bernoulli numbers\" begin\n    @testset \"    throws errors\" begin\n        @test_throws DomainError bernoulli(-1)\n        @test_throws DomainError bernoulli(36)\n        @test_throws MethodError bernoulli(1.0)\n    end\n\n    @testset \"    types\" begin\n        @test typeof(bernoulli(2)) == Rational{Int64}\n    end\n    \n    @testset \"    explicit cases\" begin\n        for i=2:34\n            # zeta isn't quite as accurate as we would like\n            @test Float64(bernoulli(i)) \u2248 -i*zeta( 1 - i )\n        end\n    end\n\n    @testset \"    dataset 1\" begin\n        B = Symbol(\"B_n\")\n        data1 = CSV.read(\"../data/bernoulli_test_data_1.csv\", DataFrame)\n        m = size(data1,1)\n        for i=1:m\n            @test bernoulli( data1[i,:n] ) \u2245 parse(Rational{Int64},data1[i,B])\n        end\n    end\nend\n\n\n@testset \"Bernoulli polynomials\" begin\n    @testset \"    throws errors\" begin\n        @test_throws DomainError bernoulli(-1, 0.0)\n        @test_throws MethodError bernoulli(1.0, 0.0)\n        @test_throws MethodError bernoulli(1.0, 1)\n    end\n\n    @testset \"    types\" begin\n        @test typeof(bernoulli(2, 1.0)) == Float64\n    end\n \n    @testset \"    consistency with Bernoulli numbers\" begin\n        for i=0:14\n            @test Float64(bernoulli(i)) \u2245 bernoulli(i, 0.0)\n        end\n        for i=15:34\n            # somewhat reliant here on accuracy of SpecialFunctions, so can't make these better without rewriting that\n            @test Float64(bernoulli(i)) \u2248 bernoulli(i, 0.0)\n        end\n     end\n    \n    @testset \"    explicit cases\" begin\n        X = collect(-2.0 : 0.1 : 3.0)\n        for i=1:length(X)\n            x = X[i]\n            # println(\"   x = $x\")\n            @test bernoulli(0, x) \u2245 1.0\n            @test bernoulli(1, x) \u2245 x   - 0.5\n            @test bernoulli(2, x) \u2245 x^2 -     x   + 1.0/6.0\n            @test bernoulli(3, x) \u2245 x^3 - 1.5*x^2 + 0.5*x\n            @test bernoulli(4, x) \u2245 x^4 - 2.0*x^3 +     x^2 - 1/30.0\n            @test bernoulli(5, x) \u2245 x^5 - 2.5*x^4 + (5.0/3.0)*x^3 - x/6.0\n            # @test bernoulli(6, x) \u2248 x^6 - 3.0*x^5 + (5.0/2.0)*x^4 - 0.5*x^2 + 1/42.0\n            # Hurwitz-zeta doesn't work well enough here\n        end\n    end\n    \n    @testset \"    symmetry identities\" begin\n        X = collect(0.0: 0.1 : 1.0)\n        for i=1:length(X)\n            x = X[i]\n            # for n=1:9\n            for n=1:6\n                # println(\"   n = $n, x = $x\")\n                # start to get errors of order 1.0e-14 for n=5, 1.0e-13 around n=10, ...\n                @test bernoulli(n, 1-x)  \u2248  (-1.0)^n * bernoulli(n, x)\n                @test bernoulli(n, x+1)  \u2248  bernoulli(n, x) + n*x^(n-1)\n                # SpecialFunctions.zeta(-6, -1.0) = NaN (probably should be 2)\n                @test (-1)^n * bernoulli(n, -x)  \u2248   bernoulli(n, x) + n*x^(n-1) \n                \n                # Raabe (1851)\n                m = 6.0\n                k = 0:m-1\n                @test sum( bernoulli.(n, x .+ k./m ) )/m  \u2248  m^(-n)*bernoulli(n, m*x )\n            end\n        end\n    end\n \n    @testset \" dataset 2\" begin \n        B = Symbol(\"B_n(x)\")\n        data2 = CSV.read(\"../data/bernoulli_test_data_2.csv\", DataFrame; delim=\",\", type=String)\n        data2[!,:n] = parse.(Float64, data2[!,:n] )\n        data2[!,:x] = parse.(Float64, data2[!,:x] )\n        data2[!,B] = parse.(Float64, data2[!,B] )\n        m = size(data2,1)\n        for i=1:m\n            @test bernoulli( Int(data2[i,:n]),  data2[i,:x]) \u2248 data2[i,B]\n        end\n    end\n    \n    @testset \" dataset 3\" begin\n        B = Symbol(\"B_n(x)\")\n        data3 = CSV.read(\"../data/bernoulli_test_data_3.csv\", DataFrame; delim=\",\")\n        m = size(data3,1)\n        for i=1:m\n            @test bernoulli( Int(data3[i,:n]),  data3[i,:x]) \u2248 data3[i,B]\n        end\n   end    \nend\n\n", "meta": {"hexsha": "da55231724303e4dafd544e3f077b57ef653e741", "size": 3952, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bernoulli_test.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": "test/bernoulli_test.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": "test/bernoulli_test.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.7777777778, "max_line_length": 118, "alphanum_fraction": 0.5073380567, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7604162284247973}}
{"text": "using IntervalWavelets\nusing Wavelets\nusing Base.Test\n\nprintln(\"Testing dyadic rationals...\")\n\n#=\nTranslation between indices and values for dyadic rationals\n=#\n\np = 2\nS = DaubSupport(-p+1, p)\n\n# Level 0 = integers\nsupportx = dyadic_rationals( S, 0 )\nfor x in round(Int, supportx)\n\t@test supportx[ x2index(x,S) ] == x\nend\n\nfor idx in 1:length(supportx)\n\t@test supportx[idx] == index2x(idx,S)\nend\n\n# Higher level\nR = rand( 1:10 )\n\nsupportx = dyadic_rationals( S, R )\nfor x in supportx\n\t@test supportx[ x2index(x,S,R) ] == x\nend\n\nfor idx in 1:length(supportx)\n\t@test supportx[idx] == index2x(idx,S,R)\nend\n\n", "meta": {"hexsha": "199a43dc198b9398122e7fc81547dbfa9a56e2bc", "size": 604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DyadicPoints.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalWavelets.jl-8574dada-bbe2-5b14-8c04-14b17cae11e5", "max_stars_repo_head_hexsha": "f456d0bbb58d8c4dc53dd307ef28add49176a4f2", "max_stars_repo_licenses": ["MIT"], "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/DyadicPoints.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalWavelets.jl-8574dada-bbe2-5b14-8c04-14b17cae11e5", "max_issues_repo_head_hexsha": "f456d0bbb58d8c4dc53dd307ef28add49176a4f2", "max_issues_repo_licenses": ["MIT"], "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/DyadicPoints.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalWavelets.jl-8574dada-bbe2-5b14-8c04-14b17cae11e5", "max_forks_repo_head_hexsha": "f456d0bbb58d8c4dc53dd307ef28add49176a4f2", "max_forks_repo_licenses": ["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.7777777778, "max_line_length": 59, "alphanum_fraction": 0.6986754967, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7604162266325103}}
{"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 \u21a6 0 if countnz(x) \u2a7d r, +\u221e 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": "using RvSpectraKitLearn\r\n\r\nfunction make_B(p::Integer, q::Integer; frac_active::Float64 = 0.1, bias::Float64 = 0.0, sigma::Float64 = 1.0)\r\n  B = zeros(p,q)\r\n  for i in 1:p, j in 1:q\r\n      if rand() < frac_active\r\n        B[i,j] = bias+sigma*randn()\r\n      end\r\n  end\r\n  return B\r\nend\r\n\r\n# Test sparse regression via  alg\r\nn = 25\r\n p = 100\r\n q = 4\r\n frac_active = 0.1\r\n sigma_x = 0.1\r\n sigma_y = 0.1\r\n X = randn(n,p)\r\n B = make_B(p,q,frac_active=frac_active,bias=1.0,sigma=sigma_x)\r\n Y = X*B + sigma_y*randn(n,q)\r\n X_crossvalid = randn(n,p)\r\n Y_crossvalid = X_crossvalid*B + sigma_y*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_slr_2d(X,Y,stepsize=1.04,max_itterations=1000, min_active=floor(Int64,p*q*frac_active*0.1))\r\n(L0,L1,L2,rmsdelta) = compute_alr_path_stats(Z_list,target=B)\r\n(chisq,chisq_refit,chisq_cv) = compute_alr_path_chisq!(Z_list,X,Y,X_crossvalid,Y_crossvalid)\r\nprint_alr_path(gamma_list, Z_list,X,Y)\r\n\r\n\r\n#=\r\n#Pkg.add(\"PyPlot\")  # Run once if you don't already have PyPlot installed\r\nusing PyPlot\r\n\r\nplt[:loglog](gamma_list,L0,\"y-\")\r\n plt[:loglog](gamma_list,L1/length(B),\"r-\")\r\n plt[:loglog](gamma_list,sqrt(L2),\"g-\")\r\n plt[:loglog](gamma_list,chisq_refit,\"b-\")\r\n plt[:loglog](gamma_list,chisq_refit,\"b.\")\r\n plt[:loglog](gamma_list,chisq_cv,\"m-\")\r\n plt[:loglog](gamma_list,chisq_cv,\"m.\")\r\n\r\nplot(L0,chisq,\"r-\")\r\n plot(L0,chisq,\"r.\")\r\n plot(L0,chisq_refit,\"b-\")\r\n plot(L0,chisq_refit,\"b.\")\r\n plot(L0,chisq_cv,\"m-\")\r\n plot(L0,chisq_cv,\"m.\")\r\n plt[:loglog](L0,chisq_cv,\"m.\")\r\n\r\nplot(L1,chisq,\"r-\")\r\n plot(L1,chisq,\"r.\")\r\n plot(L1,chisq_refit,\"b-\")\r\n plot(L1,chisq_refit,\"b.\")\r\n plot(L1,chisq_cv,\"m-\")\r\n plot(L1,chisq_cv,\"m.\")\r\n plt[:loglog](L1,chisq_cv,\"m.\")\r\n\r\nplot(L0,L1./L0,\"g-\")\r\n plot(L0,L1./L0,\"g.\")\r\n\r\nplot(L0,chisq,\"r-\")\r\n plot(L0,chisq,\"r.\")\r\n plot(L0,chisq_refit,\"b-\")\r\n plot(L0,chisq_refit,\"b.\")\r\n plot(L0,chisq_cv,\"m-\")\r\n plot(L0,chisq_cv,\"m.\")\r\n plt[:loglog](L0,chisq_cv,\"m.\")\r\n\r\n=#\r\n", "meta": {"hexsha": "eb127d062f6314eda841dde588b1833ffb3d1bca", "size": 1987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sparse_regression_ex1.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": "examples/sparse_regression_ex1.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": "examples/sparse_regression_ex1.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": 27.2191780822, "max_line_length": 124, "alphanum_fraction": 0.6416708606, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7604162248402233}}
{"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) \u2208 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) \u2208 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) \u2208 d)\n==(::RealNumbers, ::RealNumbers) = true\n\n\"The set of all rationals.\"\nstruct Rationals <: Domain{Rational{Int}}\nend\n\nin(x, d::Rationals) = x \u2208 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 \u2208 RealNumbers()\n==(::ComplexNumbers, ::ComplexNumbers) = true\n\n\n\"The set of natural numbers.\"\nconst \u2115 = NaturalNumbers()\n\"The set of integers.\"\nconst \u2124 = Integers()\n\"The set of rational numbers.\"\nconst \u211a = Rationals()\n\"The set of real numbers.\"\nconst \u211d = RealNumbers()\n\"The set of complex numbers.\"\nconst \u2102 = ComplexNumbers()\n\n\"The space \u211d^1.\"\nconst \u211d1 = VcatDomain(\u211d)\n\"The space \u211d^2.\"\nconst \u211d2 = VcatDomain(\u211d, \u211d)\n\"The space \u211d^3.\"\nconst \u211d3 = VcatDomain(\u211d, \u211d, \u211d)\n\"The space \u211d^4.\"\nconst \u211d4 = VcatDomain(\u211d, \u211d, \u211d, \u211d)\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": "using Base.Test\nusing PValueAdjust\n\nnewPvalues = padjust([0.05, 0.03, 0.01, 0.5], BenjaminiHochberg)\n@test_approx_eq newPvalues [0.06666666667, 0.06, 0.04, 0.5]\n\n@test_approx_eq padjust([1, 0.5, 0.1, 0.001, 0.0001, 0.002], BenjaminiHochberg) [1.0, 0.6, 0.15, 0.003, 0.0006, 0.004]\n@test_approx_eq padjust([0.05, 0.05, 0.05], BenjaminiHochberg) [0.05, 0.05, 0.05]\n\n@test all(padjust([1,1,1], BenjaminiHochberg) .<= 1)\n\n@test_throws DomainError padjust([-1], BenjaminiHochberg)\n@test_throws DomainError padjust([2], BenjaminiHochberg)\n\n@test padjust([0.5], BenjaminiHochberg) == [0.5]\n", "meta": {"hexsha": "0a9585b5e77cd5c69ed564db9235b7c26876013a", "size": 583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/benjaminiHochberg.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PValueAdjust.jl-34431166-ec0b-5f3d-af82-e2d5065c44b8", "max_stars_repo_head_hexsha": "3ae0c9352d4ceb5cde1ba83ecdc187ebea77a18b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-04-08T18:18:04.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-07T13:03:28.000Z", "max_issues_repo_path": "test/benjaminiHochberg.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PValueAdjust.jl-34431166-ec0b-5f3d-af82-e2d5065c44b8", "max_issues_repo_head_hexsha": "3ae0c9352d4ceb5cde1ba83ecdc187ebea77a18b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-01-02T12:32:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T18:30:16.000Z", "max_forks_repo_path": "test/benjaminiHochberg.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PValueAdjust.jl-34431166-ec0b-5f3d-af82-e2d5065c44b8", "max_forks_repo_head_hexsha": "3ae0c9352d4ceb5cde1ba83ecdc187ebea77a18b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-01-02T15:40:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:14:46.000Z", "avg_line_length": 36.4375, "max_line_length": 118, "alphanum_fraction": 0.7066895369, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7604135739917202}}
{"text": "function tinterval(x, \u03b4, op)\n    \u03bc = mean(x)\n    \u03c3 = std(x, mean=\u03bc)\n    t = 0.0\n    n = length(x)\n    Zygote.ignore() do\n        t = quantile(TDist(n-1), \u03b4)\n    end\n    s = t * \u03c3 / \u221an\n    return op(\u03bc,s)\nend\n\nfunction tdist_ci(;\u03b4=0.05, tail=:both)\n    if tail == :right\n        return x->tinterval(x,\u03b4,(\u03bc,s)->\u03bc-s) # quantile of 0.05 is negative so need to subtract to get upper\n    elseif tail == :left\n        return x->tinterval(x,\u03b4,(\u03bc,s)->\u03bc+s) # need to add to get lower bound\n    else\n        return x->tinterval(x,\u03b4/2,(\u03bc,s)->(\u03bc+s,\u03bc-s))\n    end\nend\n\nfunction andersons_ucb(x, b, \u03b4)\n    n = length(x)\n    \u03f5 = \u221a(log(1/\u03b4)/(2n))\n    r = floor(Int, n*\u03f5)\n    upper = (1/n) * ((r+1)*x[r+1] + sum(view(x, r+1:n))) + \u03f5 * (b - x[r+1])\n    return upper\nend\n\nfunction andersons_lcb(x, a, \u03b4)\n    n = length(x)\n    \u03f5 = \u221a(log(1/\u03b4)/(2n))\n    s = floor(Int, n*\u03f5)\n    lower = (1/n) * (sum(view(x, 1:n-s-1)) + (s+1)*x[n-s]) - \u03f5 * (x[n-s] - a)\n    return lower\nend\n\nfunction andersons_ci(a, b; \u03b4=0.05, tail=:both)\n    if tail == :both\n        function f(x)\n            z = sort(x)\n            upper = andersons_ucb(z, b, \u03b4/2)\n            lower = andersons_lcb(z, a, \u03b4/2)\n            return lower, upper\n        end\n        return f\n    elseif tail == :left\n        return x->andersons_lcb(sort(x), a, \u03b4)\n    elseif tail == :right\n        return x->andersons_ucb(sort(x), b, \u03b4)\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') = \u03c3\u00b2\\\\exp(- (x - x')\u1d40L\u207b\u00b2(x - x')/2)\n```\nwith length scale ``\u2113 = (\u2113\u2081, \u2113\u2082, \u2026)`` and signal standard deviation ``\u03c3`` where\n``L = diag(\u2113\u2081, \u2113\u2082, \u2026)``.\n\"\"\"\nmutable struct SEArd{T<:Real} <: StationaryARD{WeightedSqEuclidean}\n    \"Inverse squared length scale\"\n    i\u21132::Vector{T}\n    \"Signal variance\"\n    \u03c32::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nSquared Exponential Function with ARD\n\n    SEArd(ll::Vector{Real}, l\u03c3::Real)\n\n# Arguments\n  - `ll::Vector{Real}`: vector of length scales (given on log scale)\n  - `l\u03c3::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nSEArd(ll::Vector{T}, l\u03c3::T) where T = SEArd{T}(exp.(-2 .* ll), exp(2 * l\u03c3), [])\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\u21132 = exp(-2 * hyp[1:(end-1)])\n    se.\u03c32 = exp(2 * hyp[end])\nend\n\nget_params(se::SEArd) = [-log.(se.i\u21132) / 2 ; log(se.\u03c32) / 2]\nget_param_names(k::SEArd) = [get_param_names(k.i\u21132, :ll); :l\u03c3]\nnum_params(se::SEArd) = length(se.i\u21132) + 1\n\ncov(se::SEArd, r::Number) = se.\u03c32*exp(-r / 2)\n\n@inline dk_dll(se::SEArd, r::Real, wdiffp::Real) = wdiffp*cov(se,r)\n@inline function dKij_d\u03b8p(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\u03c3(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 \u22bb bit2\n\n\tx = (x << i) | (x << j)\n\n\treturn (n \u22bb 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": "# Function to normalize values\r\nfunction normalize(vec)\r\n    [(x - minimum(vec))/(maximum(vec) - minimum(vec)) for x in vec]\r\nend", "meta": {"hexsha": "bdaab2c29bc8fdf6717ea5a07e4385f6529daac2", "size": 129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "functions/part1_normalize.jl", "max_stars_repo_name": "beyondatlas/emergency-service-districting", "max_stars_repo_head_hexsha": "6c3b5c9c931adbc217959a0bfd41c6c9d90c6983", "max_stars_repo_licenses": ["MIT"], "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/part1_normalize.jl", "max_issues_repo_name": "beyondatlas/emergency-service-districting", "max_issues_repo_head_hexsha": "6c3b5c9c931adbc217959a0bfd41c6c9d90c6983", "max_issues_repo_licenses": ["MIT"], "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/part1_normalize.jl", "max_forks_repo_name": "beyondatlas/emergency-service-districting", "max_forks_repo_head_hexsha": "6c3b5c9c931adbc217959a0bfd41c6c9d90c6983", "max_forks_repo_licenses": ["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.25, "max_line_length": 68, "alphanum_fraction": 0.6821705426, "num_tokens": 30, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.76041356822135}}
{"text": "using Mdp.VI\n@testset \"Dict inputs\" begin\n    # Define simple domains (from Massau Kolobov 2016 book, p.41)\n    S = 1:6 # States\n    A = 1:2\n    T = Dict(   # Transitions, prob = T[(state, action, next_state)]\n        (1,1,3)=>1.,\n        (1,2,2)=>1.,\n        (2,1,3)=>1.,\n        (3,1,5)=>1.,\n        (3,2,2)=>1.,\n        (4,1,5)=>1.,\n        (5,1,6)=>1.,\n        (5,2,6)=>.6,\n        (5,2,4)=>.4,\n        (6,1,6)=>1.,    # Manually added goal state transition\n    )\n    C = Dict( # Costs, cost = C[(state, action, next_state)]\n        (1,1,3)=>1,\n        (1,2,2)=>1,\n        (2,1,3)=>1,\n        (3,1,5)=>1,\n        (3,2,2)=>1,\n        (4,1,5)=>1,\n        (5,1,6)=>5,\n        (5,2,6)=>2,\n        (5,2,4)=>2,\n        (6,1,6)=>0,   # Manually added goal state transition cost\n    )\n\n    V_init = [3.,3.,2.,2.,1.,0.]\n    @testset \"Bellman backup\" begin\n        @test bellman_backup(1, S, A, T, C, V_init)==3.\n        @test bellman_backup(2, S, A, T, C, V_init)==3.\n        @test bellman_backup(3, S, A, T, C, V_init)==2.\n        @test bellman_backup(4, S, A, T, C, V_init)==2.\n        @test bellman_backup(5, S, A, T, C, V_init)==2.8\n        @test bellman_backup(6, S, A, T, C, V_init)==0.\n    end\n\n    @test isapprox(value_iteration(S,A,T,C, \u03f5=0.001, V_old=[3.,3.,2.,2.,1.,0.]), [5.99921,5.99921,4.99969, 4.99969,3.99969,0.], atol=0.001)\nend\n\n@testset \"Function inputs\" begin\n    # Define simple domains (from Massau Kolobov 2016 book, p.41)\n    S = 1:6 # States\n    A = 1:2\n    T = Dict(   # Transitions, prob = T[(state, action, next_state)]\n        (1,1,3)=>1.,\n        (1,2,2)=>1.,\n        (2,1,3)=>1.,\n        (3,1,5)=>1.,\n        (3,2,2)=>1.,\n        (4,1,5)=>1.,\n        (5,1,6)=>1.,\n        (5,2,6)=>.6,\n        (5,2,4)=>.4,\n        (6,1,6)=>1.,    # Manually added goal state transition\n    )\n    C = Dict( # Costs, cost = C[(state, action, next_state)]\n        (1,1,3)=>1,\n        (1,2,2)=>1,\n        (2,1,3)=>1,\n        (3,1,5)=>1,\n        (3,2,2)=>1,\n        (4,1,5)=>1,\n        (5,1,6)=>5,\n        (5,2,6)=>2,\n        (5,2,4)=>2,\n        (6,1,6)=>0,   # Manually added goal state transition cost\n    )\n\n    # V_init = [3.,3.,2.,2.,1.,0.]\n    # @testset \"Bellman backup\" begin\n    #     @test bellman_backup(1, S, A, T, C, V_init)==3.\n    #     @test bellman_backup(2, S, A, T, C, V_init)==3.\n    #     @test bellman_backup(3, S, A, T, C, V_init)==2.\n    #     @test bellman_backup(4, S, A, T, C, V_init)==2.\n    #     @test bellman_backup(5, S, A, T, C, V_init)==2.8\n    #     @test bellman_backup(6, S, A, T, C, V_init)==0.\n    # end\n    #\n    # @test isapprox(value_iteration(S,A,T,C, \u03f5=0.001, V_old=[3.,3.,2.,2.,1.,0.]), [5.99921,5.99921,4.99969, 4.99969,3.99969,0.], atol=0.001)\nend\n", "meta": {"hexsha": "0adc53e7b27b0bc5b15c059b57bfdf30f1246e24", "size": 2699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_vi.jl", "max_stars_repo_name": "BoZenKhaa/Mdp.jl", "max_stars_repo_head_hexsha": "27ad50d6c76b251f4157d2919a1de88a5f8e5347", "max_stars_repo_licenses": ["MIT"], "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_vi.jl", "max_issues_repo_name": "BoZenKhaa/Mdp.jl", "max_issues_repo_head_hexsha": "27ad50d6c76b251f4157d2919a1de88a5f8e5347", "max_issues_repo_licenses": ["MIT"], "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_vi.jl", "max_forks_repo_name": "BoZenKhaa/Mdp.jl", "max_forks_repo_head_hexsha": "27ad50d6c76b251f4157d2919a1de88a5f8e5347", "max_forks_repo_licenses": ["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.7529411765, "max_line_length": 141, "alphanum_fraction": 0.4623934791, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7604135682061534}}
{"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\u2082 = vcat(nodes, x_c)\n  y\u2082 = vcat(values, y_c)\n  is = sortperm(x\u2082)\n\n  x\u2082 = x\u2082[is]\n  y\u2082 = y\u2082[is]\n\n  # Determine where to refine\n  if length(x\u2082) < min_nodes\n    mask = trues(length(x\u2082) - 1)\n  else\n    # Rescale and compute the length of each line segment in the path\n    dx = diff(x\u2082) / ptp(x\u2082)\n    dy = diff(y\u2082) / abs(ptp(y\u2082))\n    ds = sqrt.(abs2.(dx) + abs2.(dy))\n    \n    # Compute the angle between consecutive line segments \u03b8 = acos(a\u22c5b / (|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\u03b8 = 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\u03b8 = 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 \u2248 to accuracy `tol`)\n    mask = 0.5 * d\u03b8 .* (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\u2082, y\u2082, mask; tol=tol, depth=depth+1, min_nodes=min_nodes, max_level=max_level)\n  else\n    return x\u2082, y\u2082\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": "using myJuliaUtils\nusing Test\nusing LinearAlgebra\n\nN = rand(1:100)\nA = genPDmat(N)\ncholA = cholPSD(A)\n@test cholA == cholesky(A).U\n@test cholA'cholA \u2248 A\n\n# test1=0\n# test2=0\n# NoTimes=20\n# for i=1:NoTimes\n# N = round(Int, 1 + rand() * 100)\n# A = randn(N, N)\n# A = A'A\n# cholA = cholPSD(A)\n# test1+=cholA == cholesky(A).U\n# test2+=cholA'cholA \u2248 A\n# end\n# @test test1==NoTimes\n# @test test2==NoTimes\n\nN = rand(2:100)\nK = rand(1:N - 1)\nA = genPDmat(N)\nS, Q = eigen(A)\n# S[1:K] = ones(K) * eps(0.0)\nS[1:K] = zeros(K)\n# A = Q * Diagonal(S) * inv(Q)\nA = Q * Diagonal(S)\nA[:,1:K] = zeros(N, K)\nA .= A / Q\ncholA = cholPSD(A)\nif K > 1\n    @test size(cholA) == (N - K, N)\nelse \n    @test all(size(cholA) .>= (N - K, N)) # this is done to avoid approximation error\nend\n\n@test cholA'cholA \u2248 A\n\n\n# Nseed=round(Int, 1 + rand() * 5000)\n# srand(Nseed)\n# a=randn(1, N) * cholx(A)\n# srand(Nseed)\n# a=randn(1, N) * cholx(A)", "meta": {"hexsha": "9f8f2b6ac88c7543c7f35d9bd4ee9fccf578c035", "size": 904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TestingCholXRandX.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": "test/TestingCholXRandX.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": "test/TestingCholXRandX.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": 18.4489795918, "max_line_length": 85, "alphanum_fraction": 0.5862831858, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7604135662776311}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.2\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 38fdd4ef-c383-4f97-8451-c6f602307e7d\nusing Images\n\n# \u2554\u2550\u2561 3dceca5d-7d1e-425b-9516-24e0a24adaff\nusing LinearAlgebra\n# examples follow:\n\n# \u2554\u2550\u2561 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 \u22c5 v\n\tnear_zero(v::SVector) = squared_length(v) < 1e-5\nend\n\n# \u2554\u2550\u2561 0866add2-9b95-45e7-8081-c01cd2a66911\nmd\"\"\"# Chapter 1: Overview\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 97bb4432-ed41-423b-b4d9-bafc519de641\nmd\"# Chapter 2 - Manipulating images\"\n\n# \u2554\u2550\u2561 84d29423-cf11-41c3-af4d-c5f63b1ef23e\nimg = rand(4, 3)\n\n# \u2554\u2550\u2561 7d26fef0-9a06-479a-ae08-e9d04e455767\nimg_rgb = rand(RGB{Float32}, 4, 4)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 538d1aa5-07f9-4fca-8410-ef63b8a6857b\n# TODO: save as image, e.g. PNG\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 154d736b-8fdc-44af-ae2a-9e5ba6d2c92e\ngradient(200,100)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 961fd749-d439-4dfa-ae21-b1659dc54511\nmd\"# Chapter 3: Linear Algebra\"\n\n# \u2554\u2550\u2561 f8007c75-9487-414a-9592-138a696c2957\n# Dot product (\\cdot) is defined by LinearAlgebra...\n[1; 1] \u22c5 [2; 3]\n\n# \u2554\u2550\u2561 668030c8-24a7-4aa6-b858-cedf8ac5f988\n# Cross product (\\times)\n[0;1;0] \u00d7 [0;0;1]\n\n# \u2554\u2550\u2561 78f209df-d176-4711-80fc-a8054771f105\nt_col = @SVector[0.4f0, 0.5f0, 0.1f0] # Float32 test color\n\n# \u2554\u2550\u2561 e88de775-6904-4182-8209-06db22758470\nt_col[1] # first, i.e. red, component\n\n# \u2554\u2550\u2561 5fd1ec87-3616-448a-ab4d-fede804b26d5\nsquared_length(t_col)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cfbcb883-d12e-4ad3-a084-064749bddcdb\nrgb(t_col)\n\n# \u2554\u2550\u2561 6348c03d-e8ec-4dbb-9f8a-8e4a48bb1cb3\nrgb_gamma2(v::SVector{3,Float32}) = RGB(sqrt.(v)...) # claforte: try to expand?\n\n# \u2554\u2550\u2561 dbc8fc2d-39c2-4ec9-b82d-7c6a8b12dde7\nrgb_gamma2(t_col)\n\n# \u2554\u2550\u2561 53832af1-a9be-4e02-8b71-a70dae63c233\nstruct Ray\n\torigin::SVector{3,Float32}\n\tdir::SVector{3,Float32} # direction (unit vector)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 772674b0-5c40-4457-9526-5b4e81cca711\nmd\"\"\"# Random vectors\nC++'s section 8.1\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 135000d6-a675-4d8b-9385-50853bf9a169\nrandom_vec3(min::Float32, max::Float32) = @SVector[random_between(min,max) for i\u22081:3]\n\n# \u2554\u2550\u2561 7d1146d7-74da-42e6-92c2-1312ed03f70d\nrandom_vec2(min::Float32, max::Float32) = @SVector[random_between(min,max) for i\u22081:2]\n\n# \u2554\u2550\u2561 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\u22c5p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend\n\n# \u2554\u2550\u2561 203a9b25-742a-4d8b-adee-862ce4c67670\nsquared_length(random_vec3_in_sphere())\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u22c5p <= 1\n\t\t\treturn p\n\t\tend\n\tend\nend\n\n# \u2554\u2550\u2561 678214c5-de81-489f-b002-c343d48071c9\nmd\"# Chapter 4: Rays, simple camera, and background\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 14be6068-6a15-4fad-ac0a-f156da71f103\nrgb(@SVector[0.5f0, 0.7f0, 1.0f0]), rgb(@SVector[1.0f0, 1.0f0, 1.0f0])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 655ffa6c-f1e9-4149-8f1d-51145c5a51e4\nmain(200,100, skycolor)\n\n# \u2554\u2550\u2561 9075f8ed-f319-486d-94b2-486806aba3fd\nmd\"# Chapter 5: Add a sphere\"\n\n# \u2554\u2550\u2561 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 \u22c5 r.dir\n\tb = 2oc \u22c5 r.dir\n\tc = (oc \u22c5 oc) - radius*radius\n\tdiscriminant = b*b - 4a*c\n\tdiscriminant > 0\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1d04159d-87bd-4cf8-a73c-817f20ca1026\nmain(200,100,sphere_scene1)\n\n# \u2554\u2550\u2561 fed81f09-e4a0-433f-99e8-261096114b7b\nmd\"# Chapter 6: Surface normals and multiple objects\"\n\n# \u2554\u2550\u2561 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 \u22c5 r.dir\n\tb = 2oc \u22c5 r.dir\n\tc = (oc \u22c5 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# \u2554\u2550\u2561 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\u20d7 = normalize(point(r, t) - sphere_center) # normal vector. typed n\\vec\n\t\treturn 0.5f0n\u20d7 + SVector{3,Float32}(0.5f0,0.5f0,0.5f0) # remap normal to rgb\n\telse\n\t\tskycolor(r)\n\tend\nend\n\n# \u2554\u2550\u2561 ed6ab8be-587c-4cb6-8172-618c74d3f9cc\nmain(200,100,sphere_scene2)\n\n# \u2554\u2550\u2561 a65c68c9-e489-465a-9687-93ae9da14a5e\n\"An object that can be hit by Ray\"\nabstract type Hittable end\n\n# \u2554\u2550\u2561 2c4b4453-1a46-4889-9a14-16b18cc8c240\n\"\"\"Materials tell us how rays interact with a surface\"\"\"\nabstract type Material end\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u20d7::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\u20d7,front_face,mat) = new(t,p,n\u20d7,front_face,mat)\nend\n\n# \u2554\u2550\u2561 138bb5b6-0f45-4f13-8339-5110eb7cd1ff\nstruct Sphere <: Hittable\n\tcenter::SVector{3,Float32}\n\tradius::Float32\n\tmat::Material\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4a396b3f-f920-4ec2-91f6-7d61fe2b9699\n#\"\"\"Equivalent to `hit_record.set_face_normal()`\"\"\"\nfunction ray_to_HitRecord(t, p, outward_n\u20d7, r_dir::SVector{3,Float32}, mat::Material)\n\tfront_face = r_dir \u22c5 outward_n\u20d7 < 0\n\tn\u20d7 = front_face ? outward_n\u20d7 : -outward_n\u20d7\n\trec = HitRecord(t,p,n\u20d7,front_face,mat)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 88e51c27-0f28-4dcc-b9e9-ac44eeb876f5\n#\"Diffuse material\"\nmutable struct Lambertian<:Material\n\talbedo::SVector{3,Float32}\nend\n\n# \u2554\u2550\u2561 7c4a67b2-8208-4cd4-b1ea-16f6f50adfe8\n# \"\"\"Compute reflection vector for v (pointing to surface) and normal n\u20d7.\n\n# \tSee [diagram](https://raytracing.github.io/books/RayTracingInOneWeekend.html#metal/mirroredlightreflection)\"\"\"\nreflect(v::SVector{3,Float32}, n\u20d7::SVector{3,Float32}) = v - (2v\u22c5n\u20d7)*n\u20d7\n\n# \u2554\u2550\u2561 ca649864-5a6d-4ca7-896e-e80e8a48443e\nreflect(@SVector[0.6f0,-0.8f0,0f0], @SVector[0f0,1f0,0f0]) # diagram's example\n\n# \u2554\u2550\u2561 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\u20d7 + random_vec3_on_sphere()\n\tif near_zero(scatter_dir) # Catch degenerate scatter direction\n\t\tscatter_dir = rec.n\u20d7 \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# \u2554\u2550\u2561 c63d10c2-dd43-4836-83ee-61b782545a02\nconst _no_hit = HitRecord() # will be reused \n\n# \u2554\u2550\u2561 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 \u22c5 r.dir # normalized vector - always 1\n    half_b = oc \u22c5 r.dir\n    c = oc\u22c5oc - s.radius^2\n    discriminant = half_b^2 - a*c\n\tif discriminant < 0 return _no_hit end\n\tsqrtd = \u221adiscriminant\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\u20d7 = (p - s.center) / s.radius\n\treturn ray_to_HitRecord(t, p, n\u20d7, r.dir, s.mat)\nend\n\n# \u2554\u2550\u2561 05e57afd-6eb9-42c5-9666-7be3771fa6b8\nstruct HittableList <: Hittable\n    list::Vector{Hittable}\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0bf88264-d4c5-4d5a-babe-d2433e46024d\nmd\"# Metal material\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c299ca47-46c4-42da-9f8b-ae3abbeb6e51\nfunction scatter(mat::Metal, r_in::Ray, rec::HitRecord)::Scatter\n\treflected = normalize(reflect(r_in.dir, rec.n\u20d7) + mat.fuzz*random_vec3_on_sphere())\n\tScatter(Ray(rec.p, reflected), mat.albedo)\nend\n\n# \u2554\u2550\u2561 851c002c-dc23-4999-b28c-a716c5d2d42c\nmd\"# Scenes\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 282a4912-7a6e-44ae-90eb-f2f7c8f3d0f4\nmd\"\"\"# Camera\n\nAdapted from C++'s sections 7.2, 11.1 \"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u00d7 w)\n\tv = w \u00d7 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# \u2554\u2550\u2561 c1aef1be-79d4-4417-be36-ae8416465986\ndefault_camera()\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 813eaa13-2eb2-4302-9e4d-5d1dab0ac7c4\nget_ray(default_camera(), 0.0f0, 0.0f0)\n\n# \u2554\u2550\u2561 891ce2c8-f8b2-472b-a8d9-389dafddcf22\nmd\"# Render\n\n(equivalent to final `main`)\"\n\n# \u2554\u2550\u2561 5f1bae02-d425-4a73-8668-d6383faba79d\nmd\"\"\"# Dielectrics\n\nfrom Section 10.2 Snell's Law:\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fbba5135-7ea3-4471-938a-be13c764feff\nmd\"\"\"\nRefracted angle `sin\u03b8\u2032 = (\u03b7/\u03b7\u2032)\u22c5sin\u03b8`, where \u03b7 (\\eta) are the refractive indices.\n\nSplit the parts of the ray into `R\u2032=R\u2032\u22a5+R\u2032\u2225` (perpendicular and parallel to n\u20d7\u2032).\"\"\"\n\n# \u2554\u2550\u2561 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. \u03b7/\u03b7\u2032 in the figure above\"\"\"\nfunction refract(dir::SVector{3,Float32}, n\u20d7::SVector{3,Float32}, \n\t\t\t\t refraction_ratio::Float32)\n\tcos\u03b8 = min(-dir \u22c5 n\u20d7, 1)\n\tr_out_perp = refraction_ratio * (dir + cos\u03b8*n\u20d7)\n\tr_out_parallel = -\u221a(abs(1-squared_length(r_out_perp))) * n\u20d7\n\tnormalize(r_out_perp + r_out_parallel)\nend\n\n# \u2554\u2550\u2561 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\u03b8 = 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\u03b8, \n\t\tSVector{3,Float32}(0.87519, -0.483779, 0.0); atol=1e-3)\n\n\t# narrower angle\n\tt_refract_narrower\u03b8 = 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\u03b8, \n\t\tSVector{3,Float32}(0.3, -0.953939, 0.0); atol=1e-3)\nend\n\n# \u2554\u2550\u2561 f5c4e502-048c-4fcd-879f-eaeb4430c012\nmutable struct Dielectric <: Material\n\tir::Float32 # index of refraction, i.e. \u03b7.\nend\n\n# \u2554\u2550\u2561 167cc207-7be6-4624-8425-2df81b3f6c3b\nfunction reflectance(cos\u03b8::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\u03b8)^5)\nend\n\n# \u2554\u2550\u2561 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. \u03b7\u1d62/\u03b7\u209c\n\tcos\u03b8 = min(-r_in.dir\u22c5rec.n\u20d7, 1.0f0)\n\tsin\u03b8 = \u221a(1.0f0 - cos\u03b8^2)\n\tcannot_refract = refraction_ratio * sin\u03b8 > 1.0\n\tif cannot_refract || reflectance(cos\u03b8, refraction_ratio) > rand()\n\t\tdir = reflect(r_in.dir, rec.n\u20d7)\n\telse\n\t\tdir = refract(r_in.dir, rec.n\u20d7, refraction_ratio)\n\tend\n\tScatter(Ray(rec.p, dir), attenuation) # TODO: rename reflected -> !absorbed?\nend\n\n# \u2554\u2550\u2561 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\u20d7) # show the normal in RGB\n\t\t# return color_vec3_in_rgb(rec.p + rec.n\u20d7)\n\t\t# return color_vec3_in_rgb(random_vec3_in_sphere())\n\t\t#return color_vec3_in_rgb(rec.n\u20d7 + 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 aa38117f-45e8-4070-a412-958f0ce19aa5\nrender(scene_2_spheres(), default_camera(), 96, 16)\n\n# \u2554\u2550\u2561 9fd417cc-afa9-4f12-9c29-748f0522554c\nrender(scene_4_spheres(), default_camera(), 96, 16)\n\n# \u2554\u2550\u2561 a2221922-31be-42f3-8f70-845fae385d2c\nrender(scene_4_spheres(), default_camera(), 200, 256)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a1564d79-3628-4121-99a9-d3674e16eb04\nrender(scene_diel_spheres(), default_camera(), 96, 16)\n\n# \u2554\u2550\u2561 330a8972-adbd-471b-ade1-15901a258cbb\nrender(scene_diel_spheres(), default_camera(), 200, 64)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0587d381-b957-4c40-b6b7-e5e0fd46267b\nmd\"# Positioning camera\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dcde1539-23af-4abf-96d3-6a903add3ea8\nrender(scene_blue_red_spheres(), default_camera(), 96, 16)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e3ef265c-1911-429d-84be-5d5174d55fa1\nmd\"# Spheres with depth-of-field\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5bc1a6eb-8867-48b4-b141-fc0636d36694\nrender(scene_diel_spheres(), t_cam2, 200, 128)\n\n# \u2554\u2550\u2561 3c54cde0-6509-45e1-a4a0-26c6aa840b8e\nmd\"# Random spheres\"\n\n# \u2554\u2550\u2561 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 \u2208 1:3] .* @SVector[rand() for i \u2208 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 \u2208 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# \u2554\u2550\u2561 541aa3e5-4632-4f74-8088-f08fe24e07f8\nscene_random_spheres()\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 da047747-1845-4c2b-b3cb-eaa6534ce5ff\nrender(scene_random_spheres(), t_cam1, 200, 32) # takes 3.2s\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000866add2-9b95-45e7-8081-c01cd2a66911\n# \u255f\u2500611d5eae-4b09-11ec-27bf-ef4a1ecdcc41\n# \u255f\u250097bb4432-ed41-423b-b4d9-bafc519de641\n# \u2560\u255038fdd4ef-c383-4f97-8451-c6f602307e7d\n# \u2560\u255084d29423-cf11-41c3-af4d-c5f63b1ef23e\n# \u2560\u25507d26fef0-9a06-479a-ae08-e9d04e455767\n# \u2560\u2550f29ad2c0-c3ff-484d-8fdd-dff34d2bb863\n# \u2560\u25502192e695-4378-4b47-8ce0-353636cd2cd1\n# \u2560\u2550538d1aa5-07f9-4fca-8410-ef63b8a6857b\n# \u2560\u25508aeb7373-6bb0-4544-8655-fa941561688c\n# \u2560\u2550154d736b-8fdc-44af-ae2a-9e5ba6d2c92e\n# \u255f\u2500216922d8-613a-4ac1-9559-40878e6587e2\n# \u2560\u2550961fd749-d439-4dfa-ae21-b1659dc54511\n# \u2560\u25503dceca5d-7d1e-425b-9516-24e0a24adaff\n# \u2560\u2550f8007c75-9487-414a-9592-138a696c2957\n# \u2560\u2550668030c8-24a7-4aa6-b858-cedf8ac5f988\n# \u2560\u25503eb50f44-9091-45e8-a7e1-92d25b4b2090\n# \u2560\u255078f209df-d176-4711-80fc-a8054771f105\n# \u2560\u2550e88de775-6904-4182-8209-06db22758470\n# \u2560\u25505fd1ec87-3616-448a-ab4d-fede804b26d5\n# \u2560\u2550a0893bf4-9607-4853-8162-9f34d3337060\n# \u2560\u2550cfbcb883-d12e-4ad3-a084-064749bddcdb\n# \u2560\u25506348c03d-e8ec-4dbb-9f8a-8e4a48bb1cb3\n# \u2560\u2550dbc8fc2d-39c2-4ec9-b82d-7c6a8b12dde7\n# \u2560\u255053832af1-a9be-4e02-8b71-a70dae63c233\n# \u2560\u255081b4c9e4-9f93-45ca-9fa0-7e9686a55e9a\n# \u255f\u2500772674b0-5c40-4457-9526-5b4e81cca711\n# \u2560\u2550709861a3-202a-4bff-a46d-b46c6e14b334\n# \u2560\u2550135000d6-a675-4d8b-9385-50853bf9a169\n# \u2560\u25507d1146d7-74da-42e6-92c2-1312ed03f70d\n# \u2560\u255046a4aa4b-82c1-4941-b36d-dc8c977af2bc\n# \u2560\u2550203a9b25-742a-4d8b-adee-862ce4c67670\n# \u2560\u25502e98c6bd-0289-4105-ad25-24414ecf2750\n# \u2560\u2550c0c23cb3-6a57-487d-943a-af4330a94ffe\n# \u255f\u2500678214c5-de81-489f-b002-c343d48071c9\n# \u2560\u2550cbb6418c-79e9-4359-80a6-40a8fa40679e\n# \u2560\u255014be6068-6a15-4fad-ac0a-f156da71f103\n# \u2560\u255064ef0313-2d2b-49d5-a1a1-3b04426a82f8\n# \u2560\u2550971777a6-f269-4344-8dba-7a55118396e5\n# \u2560\u2550655ffa6c-f1e9-4149-8f1d-51145c5a51e4\n# \u255f\u25009075f8ed-f319-486d-94b2-486806aba3fd\n# \u2560\u2550c00e2004-2002-4dd2-98ed-f898ef2c14f1\n# \u2560\u2550b7399fb8-6205-41ea-9c70-eb62daedcefb\n# \u2560\u25501d04159d-87bd-4cf8-a73c-817f20ca1026\n# \u255f\u2500fed81f09-e4a0-433f-99e8-261096114b7b\n# \u2560\u255024e8740a-8e44-4206-b2b6-c4a55002dad8\n# \u2560\u2550359832af-7598-4c45-8033-c28cb0d86772\n# \u2560\u2550ed6ab8be-587c-4cb6-8172-618c74d3f9cc\n# \u2560\u2550a65c68c9-e489-465a-9687-93ae9da14a5e\n# \u2560\u25502c4b4453-1a46-4889-9a14-16b18cc8c240\n# \u2560\u255098c43f3f-4bfc-49db-806a-850b7d75b5a4\n# \u2560\u25503b570d37-f407-41d8-b8a0-a0af4d85b14d\n# \u2560\u2550138bb5b6-0f45-4f13-8339-5110eb7cd1ff\n# \u255f\u25006b36d245-bf01-45a7-b119-8315226dd4a3\n# \u2560\u25504a396b3f-f920-4ec2-91f6-7d61fe2b9699\n# \u2560\u2550427f247c-055c-459e-9862-26e9f6f3e24f\n# \u2560\u255088e51c27-0f28-4dcc-b9e9-ac44eeb876f5\n# \u2560\u25507c4a67b2-8208-4cd4-b1ea-16f6f50adfe8\n# \u2560\u2550ca649864-5a6d-4ca7-896e-e80e8a48443e\n# \u2560\u2550485f9c5b-4c5d-453c-b190-e84ae0cd1a21\n# \u2560\u2550c63d10c2-dd43-4836-83ee-61b782545a02\n# \u2560\u255078efebc5-53fd-417d-bd9e-667fd504e3fd\n# \u2560\u255005e57afd-6eb9-42c5-9666-7be3771fa6b8\n# \u2560\u255008e18ae5-9927-485e-9644-552f03e06f27\n# \u2560\u2550737e2f87-82f5-45b6-a76c-4f560c29f5b9\n# \u2560\u2550f72214f9-03c4-4ba3-bb84-069256446b31\n# \u2560\u25500bf88264-d4c5-4d5a-babe-d2433e46024d\n# \u2560\u2550555bea1d-5178-48dd-87e6-4e2a2471a5dd\n# \u2560\u2550c299ca47-46c4-42da-9f8b-ae3abbeb6e51\n# \u255f\u2500851c002c-dc23-4999-b28c-a716c5d2d42c\n# \u2560\u255070530f8e-1b29-4588-927f-d38d5d12d5c9\n# \u2560\u2550c5349670-4df4-421f-9d5a-b28c1b9040c2\n# \u255f\u2500282a4912-7a6e-44ae-90eb-f2f7c8f3d0f4\n# \u2560\u2550a0e5a1f3-244f-427b-a335-7e233af1d9d8\n# \u2560\u25505d00f26b-35f2-4071-8e04-227ffc25f184\n# \u2560\u2550c1aef1be-79d4-4417-be36-ae8416465986\n# \u2560\u255094081092-afc6-4359-bd2c-15e8407bf70e\n# \u2560\u2550813eaa13-2eb2-4302-9e4d-5d1dab0ac7c4\n# \u255f\u2500891ce2c8-f8b2-472b-a8d9-389dafddcf22\n# \u2560\u255064104df6-4b79-4329-bfed-14619aa73e3c\n# \u2560\u2550aa38117f-45e8-4070-a412-958f0ce19aa5\n# \u2560\u25509fd417cc-afa9-4f12-9c29-748f0522554c\n# \u2560\u2550a2221922-31be-42f3-8f70-845fae385d2c\n# \u255f\u25005f1bae02-d425-4a73-8668-d6383faba79d\n# \u255f\u250071f3626c-e61d-4838-82b9-ac8a978c0cb4\n# \u255f\u2500fbba5135-7ea3-4471-938a-be13c764feff\n# \u2560\u25509dc64353-c41c-45b4-aacd-12d5d6117c58\n# \u2560\u2550bbfd4db5-3650-4f27-9777-2ff981c3d28b\n# \u2560\u2550f5c4e502-048c-4fcd-879f-eaeb4430c012\n# \u2560\u2550167cc207-7be6-4624-8425-2df81b3f6c3b\n# \u2560\u2550ae3b8f15-985d-4f74-ac8c-86a3ffc3b8b1\n# \u2560\u2550ddf5883c-036a-4a21-908d-bb7cec731f7f\n# \u2560\u2550a1564d79-3628-4121-99a9-d3674e16eb04\n# \u2560\u2550330a8972-adbd-471b-ade1-15901a258cbb\n# \u2560\u25502e9672e3-f2b8-439e-b1f3-3cc60a459885\n# \u255f\u25000587d381-b957-4c40-b6b7-e5e0fd46267b\n# \u2560\u25507c75b0d8-578d-4ca9-8d74-935c1ac582b9\n# \u2560\u2550dcde1539-23af-4abf-96d3-6a903add3ea8\n# \u2560\u2550e7f5c672-0bd9-4cfe-8a47-17cd67aa01f4\n# \u255f\u2500e3ef265c-1911-429d-84be-5d5174d55fa1\n# \u2560\u2550a7d95d91-6571-4696-bad3-2979296d5f84\n# \u2560\u25505bc1a6eb-8867-48b4-b141-fc0636d36694\n# \u255f\u25003c54cde0-6509-45e1-a4a0-26c6aa840b8e\n# \u2560\u2550a52911a2-1e24-4237-81ca-f613913d29c1\n# \u2560\u2550541aa3e5-4632-4f74-8088-f08fe24e07f8\n# \u2560\u2550840d2599-245c-4e6c-8813-4abdcd802b01\n# \u2560\u2550da047747-1845-4c2b-b3cb-eaa6534ce5ff\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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 + \u03b1*y^2 + \u03b2*t\n#  f = \u03b2 - 2 - 2*\u03b1\n###############################################\n\nmodule ft03\n\nusing FenicsPy\n\nT = 2.0            # final time\nnum_steps = 10     # number of time steps\n\u0394t = T / num_steps # time step size\n\u03b1 = 3          # parameter \u03b1\n\u03b2 = 1.2         # parameter \u03b2\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=\u03b1, beta=\u03b2, 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(\u03b2 - 2 - 2*\u03b1)\n\nF = u*v*dx + \u0394t*dot(grad(u), grad(v))*dx - (u_n + \u0394t*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 += \u0394t\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# \u2554\u2550\u2561 e429e976-30d8-11eb-27dd-590119e09f74\nusing DifferentialEquations, PlutoUI\n\n# \u2554\u2550\u2561 167e7be6-30dc-11eb-15de-ad9ff925a787\nusing Plots; gr()\n\n# \u2554\u2550\u2561 cdab643c-30da-11eb-29f6-53bdde7b82f5\n\n\n# \u2554\u2550\u2561 d560f3f6-30da-11eb-31dc-f510ae97bada\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3fa4a936-30dd-11eb-3ef1-8bb442940777\nbegin\np = (a,b,c,d)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f6f9f872-30db-11eb-25d3-f18fdd57d80c\nu0 = [x;y]; tspan = (0.0,10.0)\n\n# \u2554\u2550\u2561 986c0e84-31bd-11eb-27af-d1702ee5442e\nprob = ODEProblem(f,u0,tspan,p);\n\n# \u2554\u2550\u2561 a063e0d0-31bd-11eb-056b-cb400ad0e45b\nsol = solve(prob);\n\n# \u2554\u2550\u2561 1ce67d12-30dc-11eb-3f11-4b72daa20236\nplot(sol,title=\"Population of predator/prey over time\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 49c55e48-30dc-11eb-02be-398a6bd228eb\nplot(sol,title=\"Phase Diagram\",vars=(1,2))\n\n# \u2554\u2550\u2561 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\u2013Volterra_equations\n3. https://observablehq.com/@mbostock/predator-and-prey\n4. https://www.pnas.org/content/6/7/410.full\n\n\n\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550cdab643c-30da-11eb-29f6-53bdde7b82f5\n# \u2560\u2550d560f3f6-30da-11eb-31dc-f510ae97bada\n# \u2560\u2550e429e976-30d8-11eb-27dd-590119e09f74\n# \u2560\u2550c93b2276-30db-11eb-1669-27ae204265d1\n# \u2560\u25503fa4a936-30dd-11eb-3ef1-8bb442940777\n# \u2560\u2550210ce916-30dd-11eb-0321-4fb5cae1d9f3\n# \u2560\u25501ce67d12-30dc-11eb-3f11-4b72daa20236\n# \u2560\u25505a535432-30fe-11eb-3442-817440f3830e\n# \u2560\u2550f6f9f872-30db-11eb-25d3-f18fdd57d80c\n# \u2560\u2550986c0e84-31bd-11eb-27af-d1702ee5442e\n# \u2560\u2550a063e0d0-31bd-11eb-056b-cb400ad0e45b\n# \u255f\u2500167e7be6-30dc-11eb-15de-ad9ff925a787\n# \u2560\u2550d3028ce4-31bd-11eb-1710-d5a7ecba6bfe\n# \u2560\u255049c55e48-30dc-11eb-02be-398a6bd228eb\n# \u2560\u2550a5c27f1a-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 \u00f7 3) - 2\n    return ans + f((x \u00f7 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  \u03b8_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 * \u03b8_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    \u03b8_ML = counts / n\n\n    # Uniform distribution\n    t_k = 1 / length(\u03b8_ML)\n\n    den = (n - 1) * sum((\u03b8_ML .- t_k) .^2)\n    if den < 1e-10\n      return entropy(ProbabilityWeights(\u03b8_ML))\n    else\n      # Regularization parameter\n      \u03bb = (1 - sum(\u03b8_ML .^ 2)) / den\n      return entropy(ProbabilityWeights(\u03bb * t_k .+ (1 - \u03bb) * \u03b8_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\u1d62, hash(x\u1d62)) for (x\u1d62, y\u1d62) \u2208 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(\u03bc=1, \u03bb=1)\n\nReturns the function\n```math\nf(x) = \u03bc\\\\|x\\\\|_1 + (\u03bb/2)\\\\|x\\\\|^2,\n```\nfor nonnegative parameters `\u03bc` and `\u03bb`.\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 `\u03bc` and `\u03bb` 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 \u21a6 \u03bc||x||_1 + (\u03bb/2)||x||\u00b2\"\nfun_params(f::ElasticNet) = \"\u03bc = $(f.mu), \u03bb = $(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\u03bc_female = rand(Normal(178, 20), 10_000)\n\u03bc_male = rand(Normal(178, 20), 10_000) .+ rand(Normal(0, 10), 10_000)\nDataFrame((; \u03bc_female, \u03bc_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    \u03c3 ~ Uniform(0, 50)\n    a ~ filldist(Normal(178, 20), 2)\n    \u03bc = a[sex]\n    height ~ MvNormal(\u03bc, \u03c3)\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    \u03c3 ~ Exponential(1)\n    \u03b1 ~ filldist(Normal(0, 0.5), length(unique(clade_id)))\n    \u03bc = \u03b1[clade_id]\n    K ~ MvNormal(\u03bc, \u03c3)\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    \u03c3 ~ Exponential(1)\n    a ~ filldist(Normal(0, 0.5), length(unique(clade_id)))\n    h ~ filldist(Normal(0, 0.5), length(unique(house)))\n    \u03bc = a[clade_id] + h[house]\n    K ~ MvNormal(\u03bc, \u03c3)\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\u2080 and all observations above the\nthreshold to a value z\u2081, 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, \u201cMoment-preserving thresolding: A new approach,\u201d Computer Vision, Graphics, and Image Processing, vol. 29, no. 3, pp. 377\u2013393, 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, \u03f5; \u03b1=1.0, \u03b2=2.0, \u03b3=0.5)\n    \u0394, y_arr = Inf, f.(S)\n    iteractions = 0\n    while \u0394 > \u03f5\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 + \u03b1*(xm - xh) # reflection point\n        yr = f(xr)\n    \n        if yr < yl\n            xe = xm + \u03b2*(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 \u2264 yh\n                xh, yh, S[end], y_arr[end] = xr, yr, xr, yr\n            end\n            xc = xm + \u03b3*(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        \u0394 = 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 [-\u03c0,\u03c0]\nfunction affect!(integrator)\n    if integrator.u[1] < 0\n        integrator.u[1] += 2*\u03c0\n    else\n        integrator.u[1] -= 2*\u03c0\n    end\nend\n\ncondition(u,t,integrator) = (integrator.u[1] < -\u03c0  || integrator.u[1] > \u03c0)\n\ncb = DiscreteCallback(condition,affect!)\n\n#d, F ,w\nF = 1.66\n\u03c9 = 1.\nd=0.2\np=[d, F, \u03c9]\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/\u03c9)\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\u03b1 = 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: \u03b1= %.2f\\n\", \u03b1 )\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 \u00d7 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\u00d76 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\u00d76 DataFrame\n Row \u2502 Crt1     Crt2     Crt3     Crt4     Crt5     Crt6    \n     \u2502 Float64  Float64  Float64  Float64  Float64  Float64 \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502     3.0     12.5      2.0    120.0     14.0      3.0\n   2 \u2502     5.0     15.0      3.0    110.0     38.0      4.0\n   3 \u2502     3.0     13.0      2.0    120.0     19.0      3.0\n   4 \u2502     4.0     14.0      2.0    100.0     31.0      4.0\n   5 \u2502     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 Test\nusing LinearAlgebra, StaticArrays\nimport ClimaCore.Spaces: Quadratures\n\n\nf(x) = x^3 + 2x^2 + 3x + 4\nfd(x) = 3x^2 + 4x + 3\n\n@testset \"test LGL quadrature\" begin\n    quad = Quadratures.GLL{3}()\n    @test quad isa Quadratures.QuadratureStyle\n    @test Quadratures.polynomial_degree(quad) == 2\n    @test Quadratures.degrees_of_freedom(quad) == 3\n\n    points, weights = Quadratures.quadrature_points(Float64, quad)\n\n    @test eltype(points) === eltype(weights) === Float64\n    @test length(points) == length(weights) == 3\n    @test dot(f.(points), weights) \u2248 28 / 3\nend\n\n@testset \"test GL quadrature\" begin\n    quad = Quadratures.GL{4}()\n    @test quad isa Quadratures.QuadratureStyle\n    @test Quadratures.polynomial_degree(quad) == 3\n    @test Quadratures.degrees_of_freedom(quad) == 4\n\n    points, weights = Quadratures.quadrature_points(Float32, quad)\n\n    @test eltype(points) === eltype(weights) === Float32\n    @test length(points) == length(weights) == 4\n    @test dot(f.(points), weights) \u2248 28 / 3\nend\n\n@testset \"differentiation_matrix\" begin\n    quad = Quadratures.GL{4}()\n    points, weights = Quadratures.quadrature_points(Float64, quad)\n\n    D = Quadratures.differentiation_matrix(Float64, quad)\n    @test D isa SMatrix\n    @test size(D) == (4, 4)\n\n    @test D * f.(points) \u2248 fd.(points)\n\n    quad = Quadratures.GLL{4}()\n    points, weights = Quadratures.quadrature_points(Float64, quad)\n\n    D = Quadratures.differentiation_matrix(Float64, quad)\n    @test D isa SMatrix\n    @test size(D) == (4, 4)\n\n    @test D * f.(points) \u2248 fd.(points)\nend\n\n@testset \"interpolation matrix\" begin\n    quad1 = Quadratures.GL{4}()\n    quad2 = Quadratures.GLL{5}()\n    points1, weights1 = Quadratures.quadrature_points(Float64, quad1)\n    points2, weights2 = Quadratures.quadrature_points(Float64, quad2)\n    I = Quadratures.interpolation_matrix(Float64, quad2, quad1)\n    @test size(I) == (5, 4)\n\n    @test I * f.(points1) \u2248 f.(points2)\n\nend\n", "meta": {"hexsha": "cd2951e8cd9713892f9da6e80e31fce0f9179b49", "size": 1944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/quadrature.jl", "max_stars_repo_name": "aviatesk/ClimaCore.jl", "max_stars_repo_head_hexsha": "44c9cf6b9d6dccaba648f8084fb2185a2c1fa3ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-07-19T20:14:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T00:18:43.000Z", "max_issues_repo_path": "test/quadrature.jl", "max_issues_repo_name": "aviatesk/ClimaCore.jl", "max_issues_repo_head_hexsha": "44c9cf6b9d6dccaba648f8084fb2185a2c1fa3ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 543, "max_issues_repo_issues_event_min_datetime": "2021-07-06T18:21:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:39:02.000Z", "max_forks_repo_path": "test/quadrature.jl", "max_forks_repo_name": "CliMA/ClimateMachineCore.jl", "max_forks_repo_head_hexsha": "73dff5e125aa641b1560f3ca5163db472c1ed07a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-27T16:54:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T16:54:21.000Z", "avg_line_length": 29.4545454545, "max_line_length": 69, "alphanum_fraction": 0.6800411523, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7603389885068116}}
{"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        #\u00a0value 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            #\u00a0g 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": "@testset \"probabilityweightedmoment_gev.jl\" begin\n    n = 5000\n    \u03b8 = [0.0;0.0;.2]\n\n    pd = GeneralizedExtremeValue(\u03b8[1], exp(\u03b8[2]), \u03b8[3])\n    y = rand(pd, n)\n\n    @testset \"gevfitpwm(y)\" begin\n        # stationary model building\n        fm = Extremes.gevfitpwm(y)\n\n        cinterval = cint(fm)\n\n        @test [x[1] for x in cinterval] <= \u03b8\n        @test \u03b8 <= [x[2] for x in cinterval]\n\n    end\n\n    @testset \"gevfitpwm(df, datacol)\" begin\n        # stationary model building\n        df = DataFrame(y = y)\n        fm = Extremes.gevfitpwm(df, :y)\n\n        cinterval = cint(fm)\n\n        @test [x[1] for x in cinterval] <= \u03b8\n        @test \u03b8 <= [x[2] for x in cinterval]\n\n    end\n\n    @testset \"gevfitpwm(model)\" begin\n        # non-stationary warn\n        model = Extremes.BlockMaxima(Variable(\"y\", y), locationcov = [Variable(\"t\", collect(1:n))])\n\n        @test_logs (:warn, \"covariates cannot be included in the model when estimating the\n            paramters by the probability weighted moment parameter estimation.\n            The estimates for the stationary model is returned.\") Extremes.gevfitpwm(model)\n\n        # stationary GEV fit by pwm\n        model = Extremes.BlockMaxima(Variable(\"y\", y))\n\n        fm = Extremes.gevfitpwm(model)\n\n        cinterval = cint(fm)\n\n        @test [x[1] for x in cinterval] <= \u03b8\n        @test \u03b8 <= [x[2] for x in cinterval]\n\n    end\nend\n", "meta": {"hexsha": "b20f9856e05530f52f3f760e383537829e42ab96", "size": 1376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/parameterestimation/probabilityweightedmoment/probabilityweightedmoment_gev_test.jl", "max_stars_repo_name": "jojal5/Extremes.jl", "max_stars_repo_head_hexsha": "925d9a1bb64e579f97b9d5a1c7357705f7c62d7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-06-20T18:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:33:00.000Z", "max_issues_repo_path": "test/parameterestimation/probabilityweightedmoment/probabilityweightedmoment_gev_test.jl", "max_issues_repo_name": "jojal5/Extremes.jl", "max_issues_repo_head_hexsha": "925d9a1bb64e579f97b9d5a1c7357705f7c62d7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2020-03-12T23:23:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T00:19:25.000Z", "max_forks_repo_path": "test/parameterestimation/probabilityweightedmoment/probabilityweightedmoment_gev_test.jl", "max_forks_repo_name": "jojal5/Extremes.jl", "max_forks_repo_head_hexsha": "925d9a1bb64e579f97b9d5a1c7357705f7c62d7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-06-04T15:53:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T14:50:42.000Z", "avg_line_length": 26.9803921569, "max_line_length": 99, "alphanum_fraction": 0.5901162791, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7603389819230587}}
{"text": "export Gaussian_Peak\n\n@doc raw\"\"\"\nGaussian peak\n\n```math\np(x; \u03b8 = [h,\u03bc,\u03c3]) = h e^{-\\frac{1}{2} \\left(\\frac{x-\u03bc}{\u03c3} \\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,\u03b8::AbstractVector)\n    @assert length(\u03b8) == parameter_size(m)\n    @assert length(Y) == length(X)\n    \n    h=\u03b8[1]\n    \u03bc=\u03b8[2]\n    \u03c3=\u03b8[3]\n\n    @. Y += h*exp(-((X-\u03bc)/\u03c3)^2/2)\n\n    Y\nend\n\n# ================================================================\n\nusing StaticArrays: @SVector, SVector\n\nstruct Const_\u03bc_Gaussian_Peak{\u03bc_T <: Real} <: Abstract_Model2Fit_Peak\n    _\u03bc::\u03bc_T\nend\n\n# Visit  ================\n#\nvisit_submodel_size(model::Const_\u03bc_Gaussian_Peak) = 0\n\n# Interface  ================\n#\nparameter_size(::Const_\u03bc_Gaussian_Peak) = 2\n\nfunction accumulate_y!(m::Const_\u03bc_Gaussian_Peak,Y::AbstractVector,X::AbstractVector,\u03b8::AbstractVector{T}) where {T}\n    @assert length(\u03b8) == parameter_size(m)\n    @assert length(Y) == length(X)\n\n    h=\u03b8[1]\n    \u03bc=m._\u03bc\n    \u03c3=\u03b8[2]\n\n    \u03b8\u0302 = @SVector T[h,\u03bc,\u03c3]\n\n    accumulate_y!(Gaussian_Peak(),Y,X,\u03b8\u0302)\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 <= \u03c1_AB <= -0.1\n#     0.4 <= \u03c1_BC <=  0.5\n#\n# We can use the following property of the correlations to determine bounds on\n# \u03c1_AC by solving a SDP:\n#\n#     |  1    \u03c1_AB  \u03c1_AC |\n#     | \u03c1_AB   1    \u03c1_BC |  \u227d 0\n#     | \u03c1_AC  \u03c1_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]) \u2248 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]) \u2248 -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    \u0394r      :: 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        \u03c4_max_1D = L/(2*v)              # Maximum delay 1D domain\n        \u03c4_max_2D = L/(sqrt(2)*v)        # Maximum delay 2D domain\n        \u0394r    = max(1.0,(v*dt)/dx)      # Compute rings width\n        rings1D = 1+floor(O,\u03c4_max_1D/dt) # Number of delay rings (u_max)\n        rings2D = 1+floor(O,\u03c4_max_2D/dt) # Number of delay rings (u_max)\n        \n        new(L,N,dx,dy,x,y,tspan,n,dt,t,v,\u0394r,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": "tol = 1e-11\n\n# Check if besselj(nu, besselroots(nu, n) ) is small: \n\nfor nu = 0.:0.1:5. \n    n = 10\n    @test norm( besselj(nu, besselroots(nu, n) ), Inf ) < tol\n\nend", "meta": {"hexsha": "1277b6ac9a2c03a701fb96bc8cf5f9577e150240", "size": 166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_besselroots.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": "test/test_besselroots.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": "test/test_besselroots.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": 18.4444444444, "max_line_length": 61, "alphanum_fraction": 0.578313253, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.760329723650587}}
{"text": "@testset \"Hermite 5D\" begin\n\n    f(x, y, z, v, w) = cos(x^2 + y^2 + z^2 + v^2 + w^2)\n\n    xmin, xmax, nx = -1, 1, 32\n    ymin, ymax, ny = -1, 1, 32\n    zmin, zmax, nz = -1, 1, 32\n    vmin, vmax, nv = -1, 1, 32\n    wmin, wmax, nw = -1, 1, 32\n\n    \u03f5 = 0.1\n    \u03b3 = 3.0\n\n    hermite_x = Hermite(Chebyshev( xmin, xmax, nx ), \u03f5, \u03b3)\n    hermite_y = Hermite(Chebyshev( ymin, ymax, ny ), \u03f5, \u03b3)\n    hermite_z = Hermite(Chebyshev( zmin, zmax, nz ), \u03f5, \u03b3)\n    hermite_v = Hermite(Chebyshev( vmin, vmax, nv ), \u03f5, \u03b3)\n    hermite_w = Hermite(Chebyshev( wmin, wmax, nw ), \u03f5, \u03b3)\n\n    xk = hermite_x.nodes\n    yk = hermite_y.nodes\n    zk = hermite_z.nodes\n    vk = hermite_v.nodes\n    wk = hermite_w.nodes\n\n    nxe, nye, nze, nve, nwe = 32, 32, 32, 32, 32\n\n    xe = collect(range(xmin, stop=xmax, length=nxe))\n    ye = collect(range(ymin, stop=ymax, length=nye))\n    ze = collect(range(zmin, stop=zmax, length=nze))\n    ve = collect(range(vmin, stop=vmax, length=nve))\n    we = collect(range(wmin, stop=wmax, length=nwe))\n    dx = abs(xe[2] - xe[1])\n    dy = abs(ye[2] - ye[1])\n    dz = abs(ze[2] - ze[1])\n    dv = abs(ve[2] - ve[1])\n    dw = abs(we[2] - we[1])\n\n    fk = [f(x, y, z, v, w) for x in xk, y in yk, z in zk, v in vk, w in wk]\n    fe = [f(x, y, z, v, w) for x in xe, y in ye, z in ze, v in ve, w in we]\n\n    @time s  = interpolate(hermite_x, hermite_y, hermite_z, hermite_v, hermite_w, fk, xe, ye, ze, ve, we)\n\n    max_error = maximum(abs.(s .- fe))\n\n    l2_error  = sqrt(trapz((s - fe).^2, dx, dy, dz, dv, dw))\n\n    println(\" Hermite 5d max error : $max_error \")\n    println(\" Hermite 5d L2  error : $l2_error  \")\n\n    @test true\n\nend\n", "meta": {"hexsha": "35ad4f768bca0eed89ea2d61604d9eb7607c6ddc", "size": 1630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_interpolation5d.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": "test/test_interpolation5d.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": "test/test_interpolation5d.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": 30.1851851852, "max_line_length": 105, "alphanum_fraction": 0.5576687117, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7603297223367196}}
{"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": "include(\"./chapter_1/bisect.jl\")\ninclude(\"./chapter_1/fpi.jl\")\n\n\nf(x::Float64) = x^3-9\n\nx = f(2.0)\nprintln(x)\n\nxc = bisect(f, 2.0, 3.0, 0.000005)\nprintln(\"xc = \", xc)\n\nf(x::Float64) = x + cos(x) -sin(x)\nxc_fpi = fpi(f, 0, 20)\n\nprintln(\"xc_fpi = \", xc_fpi)\n", "meta": {"hexsha": "194277e50e3022100c8a2867c7ebbba7aac10474", "size": 256, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/Numerical Analysis/run.jl", "max_stars_repo_name": "romix5417/CommonScript", "max_stars_repo_head_hexsha": "df8045e5b57625108e48d340f447ec4353fb8eef", "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": "julia/Numerical Analysis/run.jl", "max_issues_repo_name": "romix5417/CommonScript", "max_issues_repo_head_hexsha": "df8045e5b57625108e48d340f447ec4353fb8eef", "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/Numerical Analysis/run.jl", "max_forks_repo_name": "romix5417/CommonScript", "max_forks_repo_head_hexsha": "df8045e5b57625108e48d340f447ec4353fb8eef", "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.0588235294, "max_line_length": 34, "alphanum_fraction": 0.5859375, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7603297215915689}}
{"text": "@testset \"Bronstein Problems\" begin\n    (x, ) = @variables x\n\n    #= ::Package:: =#\n\n    #= ::Title:: =#\n    #=Manuel*Bronstein - Symbolic*Integration*Tutorial*(1998)=#\n\n\n    #= ::Section::Closed:: =#\n    #=2  Algebraic*Functions=#\n\n\n    @test_int [(2*x^8 + 1)*(sqrt(x^8 + 1)/(x^17 + 2*x^9 + x)), x, 6, -(1/(4*sqrt(1 + x^8))) - (1/4)*atanh(sqrt(1 + x^8))]\n    @test_int [1/(1 + x^2), x, 1, atan(x)]\n    @test_int [sqrt(x^8 + 1)/(x*(x^8 + 1)), x, 3, (-(1/4))*atanh(sqrt(1 + x^8))]\n    @test_int [x/sqrt(1 - x^3), x, 3, (2*sqrt(1 - x^3))/(1 + sqrt(3) - x) - (3^(1/4)*sqrt(2 - sqrt(3))*(1 - x)*sqrt((1 + x + x^2)/(1 + sqrt(3) - x)^2)*Elliptic.E(asin((1 - sqrt(3) - x)/(1 + sqrt(3) - x)), -7 - 4*sqrt(3)))/(sqrt((1 - x)/(1 + sqrt(3) - x)^2)*sqrt(1 - x^3)) + (2*sqrt(2)*(1 - x)*sqrt((1 + x + x^2)/(1 + sqrt(3) - x)^2)*Elliptic.F(asin((1 - sqrt(3) - x)/(1 + sqrt(3) - x)), -7 - 4*sqrt(3)))/(3^(1/4)*sqrt((1 - x)/(1 + sqrt(3) - x)^2)*sqrt(1 - x^3))]\n    @test_int [1/(x*sqrt(1 - x^3)), x, 3, (-(2/3))*atanh(sqrt(1 - x^3))]\n    @test_int [x/sqrt(x^4 + 10*x^2 - 96*x - 71), x, 1, (1/8)*log(10001 + 3124*x^2 - 1408*x^3 + 54*x^4 - 128*x^5 + 20*x^6 + x^8 + sqrt(-71 - 96*x + 10*x^2 + x^4)*(781 - 528*x + 27*x^2 - 80*x^3 + 15*x^4 + x^6))]\n\n\n    #= ::Section::Closed:: =#\n    #=3  Elementary*Functions=#\n\n\n    @test_int [(x - tan(x))/tan(x)^2, x, 6, -(x^2/2) - x*cot(x)]\n    @test_int [1 + x*tan(x) + tan(x)^2, x, 7, (im*x^2)/2 - x*log(1 + \u212f^(2*im*x)) + (1/2)*im*PolyLog(2, -\u212f^(2*im*x)) + tan(x)]\n    @test_int [sin(x)/x, x, 1, SinIntegral(x)]\n    @test_int [(3*(x + \u212f^x)^(1/3) + (2*x^2 + 3*x)*\u212f^x + 5*x^2)/(x*(x + \u212f^x)^(1/3)), x, 8, 3*x*(\u212f^x + x)^(2/3) + 3*log(x)]\n\n\n    @test_int [1/x + (1 + 1/x)/(x + log(x))^(3/2), x, 2, log(x) - 2/sqrt(x + log(x))]\n    @test_int [(log(x)^2 + 2*x*log(x) + x^2 + (x + 1)*sqrt(x + log(x)))/(x*log(x)^2 + 2*x^2*log(x) + x^3), x, -3, log(x) - 2/sqrt(x + log(x))]\n\n    @test_int [(2*log(x)^2 - log(x) - x^2)/(log(x)^3 - x^2*log(x)), x, 6, (-(1/2))*log(x - log(x)) + (1/2)*log(x + log(x)) + LogIntegral(x)]\n    #= [log(1 + \u212f^x)^(1/3)/(1 + log(1 + \u212f^x)), x, 0, CannotIntegrate(log(1 + \u212f^x)^(1/3)/(1 + log(1 + \u212f^x)), x)] =#\n    #= [((x^2 + 2*x + 1)*sqrt(x + log(x)) + (3*x + 1)*log(x) + 3*x^2 + x)/((x*log(x) + x^2)*sqrt(x + log(x)) + x^2*log(x) + x^3), x, 0, 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x)))] =#\n\n\n    #= ::Title:: =#\n    #=Manuel*Bronstein - Symbolic*Integration*im; Transcendental*FunctionsTutorial*(2005)=#\n\n\n    #= ::Section::Closed:: =#\n    #=2.8  Rioboo's*Algorithm*for*Real*Rational*Functions=#\n\n\n    @test_int [(x^4 - 3*x^2 + 6)/(x^6 - 5*x^4 + 5*x^2 + 4), x, 1, -atan(sqrt(3) - 2*x) + atan(sqrt(3) + 2*x) + atan((1/2)*x*(1 - 3*x^2 + x^4))]\n    end\n", "meta": {"hexsha": "6e1dac8ba90bec6e75d6161576a0f7e8abece06c", "size": 2689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/0 Independent test suites/Bronstein Problems.jl", "max_stars_repo_name": "gronniger/RubiSymbolics.jl", "max_stars_repo_head_hexsha": "dd117985dea699be7ddf14c3e6bdf4f407bb8da6", "max_stars_repo_licenses": ["MIT"], "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/0 Independent test suites/Bronstein Problems.jl", "max_issues_repo_name": "gronniger/RubiSymbolics.jl", "max_issues_repo_head_hexsha": "dd117985dea699be7ddf14c3e6bdf4f407bb8da6", "max_issues_repo_licenses": ["MIT"], "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/0 Independent test suites/Bronstein Problems.jl", "max_forks_repo_name": "gronniger/RubiSymbolics.jl", "max_forks_repo_head_hexsha": "dd117985dea699be7ddf14c3e6bdf4f407bb8da6", "max_forks_repo_licenses": ["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.78, "max_line_length": 462, "alphanum_fraction": 0.4603941986, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7603126181486884}}
{"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 \u2248 3(\u221a\u03c0)/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(\u03c0)]\n    elseif n \u2264 20\n       # GW algorithm\n       x = hermite_gw(n)\n    elseif n \u2264 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(\u03c0)/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    \u03b8 = acos.(t0)  # convert to \u03b8-variable\n    val = x0\n    for _ in 1:20\n        val = hermpoly_asy_airy(n, \u03b8)\n        d\u03b8 = -val[1]./(sqrt(2).*sqrt(2n+1).*val[2].*sin.(\u03b8))\n        \u03b8 .-= d\u03b8  # Newton update\n        if norm(d\u03b8,Inf) < sqrt(eps(Float64))/10\n           break\n        end\n    end\n    t0 = cos.(\u03b8)\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) \u2265 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) \u2265 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, \u03b8::AbstractVector)\n    # HERMPOLY_ASY evaluation hermite poly using Airy asymptotic formula in \u03b8-space.\n\n    musq = 2n+1\n    cosT = cos.(\u03b8)\n    sinT = sin.(\u03b8)\n    sin2T = 2 .* cosT.*sinT\n    \u03b7 = 0.5 .* \u03b8 .- 0.25 .* sin2T\n    \u03c7 = -(3*\u03b7/2).^(2/3)\n    \u03c6 = (-\u03c7./sinT.^2).^(1/4)\n    C = 2*sqrt(\u03c0)*musq^(1/6)*\u03c6\n    Airy0 = real.(airyai.(musq.^(2/3).*\u03c7))\n    Airy1 = real.(airyaiprime.(musq.^(2/3).*\u03c7))\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.*\u03c6.^6 .+ a1*u0) ./ \u03c7.^2\n    val .+=  B0.*Airy1./musq.^(4/3)\n\n    # third term\n    A1 = (b0*u2.*\u03c6.^12 + b1*u1.*\u03c6.^6 .+ b2*u0) ./ \u03c7.^3\n    val .+= A1.*Airy0/musq.^2\n\n    # fourth term\n    B1 = -(u3.*\u03c6.^18 + a1*u2.*\u03c6.^12 + a2*u1.*\u03c6.^6 .+ a3*u0) ./ \u03c7.^5\n    val .+= B1.*Airy1./musq.^(4/3+2)\n\n    val .= C.*val\n\n    ## Derivative\n    \u03b7 = .5*\u03b8 - .25*sin2T\n    \u03c7 = -(3*\u03b7/2).^(2/3)\n    \u03c6 = (-\u03c7./sinT.^2).^(1/4)\n    C = sqrt(2*\u03c0)*musq^(1/3)./\u03c6\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*\u03c6.^6 .* v1 .+ b1.*v0)./\u03c7\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.*\u03c6.^18 + b1*v2.*\u03c6.^12 + b2*v1.*\u03c6.^6 .+ b3*v0) ./ \u03c7.^4\n    dval = dval + C1.*Airy0/musq.^(2/3+2)\n\n    # fourth term\n    D1 = (a0*v2.*\u03c6.^12 + a1*v1.*\u03c6.^6 .+ a2*v0) ./ \u03c7.^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 \u2265 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)*\u03c0\n        a = .5\n    else\n        m = n>>1\n        # bess = ((0:m-1) .+ 0.5)*\u03c0\n        a = -.5\n    end\n    \u03bd = 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\u03c0/8*(4*(1:m) .- 1))\n\n    airyrts[1:10] .= AIRY_ROOTS[1:10]  # correct first 10.\n\n    x_init = sqrt.(abs.(\u03bd .+ (2^(2/3)).*airyrts.*\u03bd^(1/3) .+ (1/5*2^(4/3)).*airyrts.^2 .* \u03bd^(-1/3) .+\n        (11/35-a^2-12/175).*airyrts.^3 ./ \u03bd .+ ((16/1575).*airyrts.+(92/7875).*airyrts.^4).*2^(2/3).*\u03bd^(-5/3) .-\n        ((15152/3031875).*airyrts.^5 .+ (1088/121275).*airyrts.^2).*2^(1/3).*\u03bd^(-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 \u03c0.\n    # x_init_bess =  bess/sqrt(\u03bd).*sqrt((1+ (bess.^2+2*(a^2-1))/3/\u03bd^2) );\n    Tnk0 = fill(\u03c0/2,m)\n    rhs = ((4m+3) .- 4*(1:m))/\u03bd*\u03c0\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.(\u03bd*tnk - ((tnk.+1/4)./(tnk.-1).^2 .+ (3a^2-1))/3\u03bd)\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 \u2264 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(\u03c0)*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\u00d73 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": "using gss, Test\n\n@testset \"golden section \" begin\n\tf,a,b = x->x^2,-20,20\n\t@test goldss(f,a,b)== (0.0,0.0)\n\tf,a,b = x-> cos(x),-3.5,0.\n\t@test goldss(f,a,b)==(-3.14,-1.0)\n\tf,a,b = x->x^4+3*x^3+x^2,-20.,20.\n\t@test goldss(f,a,b)==(-2.0,-4.0)\n\t\nend", "meta": {"hexsha": "47be7691a01f866fdd11d7995afb9b4d88b1b86f", "size": 243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Aleksandra1818/Golden-section-search-in-julia", "max_stars_repo_head_hexsha": "00db76d7dd4e96dc5bc3df003cb6e7c57372ea85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-22T16:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-22T16:15:39.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "Aleksandra1818/Golden-section-search-in-julia", "max_issues_repo_head_hexsha": "00db76d7dd4e96dc5bc3df003cb6e7c57372ea85", "max_issues_repo_licenses": ["MIT"], "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": "Aleksandra1818/Golden-section-search-in-julia", "max_forks_repo_head_hexsha": "00db76d7dd4e96dc5bc3df003cb6e7c57372ea85", "max_forks_repo_licenses": ["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": 34, "alphanum_fraction": 0.5267489712, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7603126116335955}}
{"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( \u03c1 :: 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 `\u03c1` does not satisfy [`is_density_matrix`](@ref).\n\"\"\"\nfunction von_neumann_entropy(\u03c1 :: AbstractMatrix) :: Float64\n    is_density_matrix(\u03c1) || State(\u03c1)\n\n    \u03bbs = Probabilities(eigvals(\u03c1))\n    entropy = shannon_entropy(\u03bbs)\n\n    entropy\nend\n\n\"\"\"\n    holevo_bound(\n        priors :: AbstractVector,\n        \u03c1_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 `\u03c1 \u2208 \u03c1_states` does not satisfy [`is_density_matrix`](@ref).\n\"\"\"\nfunction holevo_bound(priors::AbstractVector, \u03c1_states::Vector{<:AbstractMatrix}) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n    all(is_density_matrix.(\u03c1_states)) || State.(\u03c1_states)\n\n    \u03c1 = mixed_state(priors, \u03c1_states)\n    \u03c1_ent = von_neumann_entropy(\u03c1)\n\n    \u03c1_states_ent = von_neumann_entropy.(\u03c1_states)\n    \u03c1_sum_ent = sum( priors .* \u03c1_states_ent )\n\n    bound = \u03c1_ent - \u03c1_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        \u03c1_states :: Vector{<:AbstractMatrix},\n        \u03a0 :: 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 `\u03c1 \u2208 \u03c1_states` does not satisfy [`is_density_matrix`](@ref).\n* `\u03a0` does not satisfy [`is_povm`](@ref).\n\"\"\"\nfunction mutual_information(\n    priors::AbstractVector,\n    states::Vector{<:AbstractMatrix},\n    \u03a0::AbstractVector{<:AbstractMatrix}\n) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n\n    if !all(\u03c1 -> \u03c1 isa State, states)\n        states = State.(states)\n    end\n    if !(\u03a0 isa POVM)\n        \u03a0 = POVM(\u03a0)\n    end\n\n    conditionals = measure(\u03a0, states)\n    mutual_information(priors, conditionals)\nend\n\n\"\"\"\n    success_probability(\n        priors::AbstractVector,\n        states::Vector{<:AbstractMatrix},\n        \u03a0::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}, \u03a0::AbstractVector{<:AbstractMatrix}) :: Float64\n    is_probability_distribution(priors) || Probabilities(priors)\n    all(is_density_matrix.(states)) || State.(states)\n    is_povm(\u03a0) || POVM(\u03a0)\n\n    sum(priors .* tr.(states .* \u03a0))\nend\n\n\"\"\"\n    error_probability(\n        priors::AbstractVector,\n        \u03c1_states::Vector{<:AbstractMatrix},\n        \u03a0::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, \u03c1_states::Vector{<:AbstractMatrix}, \u03a0::AbstractVector{<:AbstractMatrix}) :: Float64\n    1 .- success_probability(priors, \u03c1_states, \u03a0)\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 \u2018se3mat\u2019 (an element of Lie Algebra se3)\r\n# from given twist vector (= 6x1 vector) \u2018xi\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 \u2018xi\u2019 from given twist matrix \u2018se3mat\u2019\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 \u2018R\u2019 by\r\n# evaluating matrix exponential of 3x3 skew symmetric matrix \u2018so3mat\u2019\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 \u2018g\u2019 by\r\n# evaluating matrix exponential of 4x4 twist matrix \u2018se3mat\u2019\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 \u2018so3mat\u2019\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 \u2018se3mat\u2019\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    \u2018Twists\u2019 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 \u2018Twists\u2019 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\u03c0 * [ a2[2],-a2[1]] / area\n    b2 = 2\u03c0 * [-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": "using Makie\n\nfunction target_function(a, b; x=\u03c0/2)\n    return a*sin(b*x) + x/3\nend\n\n\"\"\"\nselect mode\nmode should be `:wireframe` or `:surface`\n\"\"\"\nfunction draw_surface(mode)\n    N = 100\n    lspace = range(-2pi, stop=2pi, length=N)\n    z = Float32[target_function(a,b) for a in lspace, b in lspace]\n    r = range(0, stop=2pi, length=N)\n    scene=eval(mode)(r, r, z)\n    axis = scene[Axis]\n    axis[:names][:axisnames] = (\"a\", \"b\", \"a*sin(b*x)+x/3\")\n    scene\nend\n\nfunction main()\n    draw_surface(:wireframe)\nend\n\n", "meta": {"hexsha": "d0e438ff04a145b7002d553b747ac24c843e4022", "size": 513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "makieExer/asinbx.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/surface.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/surface.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": 19.7307692308, "max_line_length": 66, "alphanum_fraction": 0.6218323587, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7602793400262444}}
{"text": "using Base.Test\nusing GLM\n\ndobson = DataFrame(counts=[18.,17,15,20,10,20,25,13,12], outcome=gl(3,1,9), treatment=gl(3,3))\ngm1 = glm(:(counts ~ outcome + treatment), dobson, Poisson());\n@test_approx_eq deviance(gm1) 5.12914107700115\n\n## Example from http://www.ats.ucla.edu/stat/r/dae/logit.htm\nnm = download(\"http://www.ats.ucla.edu/stat/data/binary.csv\", tempname())\ndf = within(readtable(nm),:(rank=compact(PooledDataArray(rank))))\nrm(nm)\n\nrteps = sqrt(eps())\n\ngm2 = glm(:(admit ~ gre + gpa + rank), df, Binomial());\n@test_approx_eq deviance(gm2) 458.5174924758994\n@test sumsqdiff(coef(gm2), [-3.9899786606380734,0.0022644256521549043,0.8040374535155766,-0.6754428594116577,-1.3402038117481079,-1.5514636444657492]) < rteps\n\ngm3 = glm(:(admit ~ gre + gpa + rank), df, Binomial(), ProbitLink());\n@test_approx_eq deviance(gm3) 458.4131713833386\n@test sumsqdiff(coef(gm3), [-2.3867922998680786,0.0013755394922972369,0.47772908362647015,-0.4154125854823675,-0.8121458010130356,-0.9359047862425298]) < rteps\n\ngm4 = glm(:(admit ~ gre + gpa + rank), df, Binomial(), CauchitLink());\n@test_approx_eq deviance(gm4) 459.3401112751141\n\ngm5 = glm(:(admit ~ gre + gpa + rank), df, Binomial(), CloglogLink());\n@test_approx_eq deviance(gm5) 458.89439629612616\n\n", "meta": {"hexsha": "8064ff37a764b7cd86b2d93b3ebc337276140fa5", "size": 1247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/glmFit.jl", "max_stars_repo_name": "lendle/GLM.jl", "max_stars_repo_head_hexsha": "9ab100051ca4e546f035b1869eaa46f229c6e9a6", "max_stars_repo_licenses": ["MIT"], "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/glmFit.jl", "max_issues_repo_name": "lendle/GLM.jl", "max_issues_repo_head_hexsha": "9ab100051ca4e546f035b1869eaa46f229c6e9a6", "max_issues_repo_licenses": ["MIT"], "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/glmFit.jl", "max_forks_repo_name": "lendle/GLM.jl", "max_forks_repo_head_hexsha": "9ab100051ca4e546f035b1869eaa46f229c6e9a6", "max_forks_repo_licenses": ["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.0, "max_line_length": 159, "alphanum_fraction": 0.7289494787, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7602793382054979}}
{"text": "using GeneralizedSampling\nusing Base.Test\n\nprintln(\"Testing miscellaneous functions...\")\n\n#=\nTesting the miscellaneous functions:\n- had!, hadc!, yphad!, conj! should the same result as the standard not in-place functions.\n- isuniform for matrices should return true for output from grid and false otherwise.\n- In 2D the weights/Voronoi areas are known beforehand for some point configurations.\n- For some point configurations, the density is known beforehand.\n- Testing the relevant wavelet names for isdaubechies and ishaar.\n- Assembling the spilt parts should yield the original array.\n=#\n\n# ------------------------------------------------------------\n# had!, hadc!, yphad!, conj!\n\nM = rand(2:10)\nN = rand(2:10)\n\n# had!\nA = rand(M, N)\nB = rand(M, N)\nhadtmp = A.*B\nhad!(A, B)\n@test hadtmp == A\n\n# hadc!\nA = rand(M, N) + im*rand(M,N)\nB = rand(M, N) + im*rand(M,N)\nhadctmp = A.*conj(B)\nhadc!(A, B)\n@test hadctmp == A\n\n# yphad!\na = rand(M)\nb = rand(M)\ny = rand(M)\nyphadtmp = y + a.*b\nyphad!(y, a, b)\n@test yphadtmp == y\n\n# conj!\nconj!(A, B)\n@test A == conj(B)\n\n\n# ------------------------------------------------------------\n# isuniform and grid\n\nfor M in 15:16, scaling in rand(2)\n\tx = grid(M, scaling)\n\t@test isuniform(x)\n\n\tx[1] += 1\n\t@test !isuniform(x)\n\n\t@test !isuniform(rand(M))\n\n\tP = grid( (M,M), scaling )\n\t@test isuniform(P)\n\n\tP[1] += 1\n\t@test !isuniform(P)\n\n\t@test !isuniform(rand(M,2))\nend\n \n\n# ------------------------------------------------------------\n# weights\n\n# A corner in the \"middle\" of each quadrant\nxi = [0.5 0.5 ; -0.5 0.5 ; -0.5 -0.5 ; 0.5 -0.5]\n@test_approx_eq weights(xi, 1.0) ones(4)\n\n\n# ------------------------------------------------------------\n# Density\n\n# 1D: Equidistant points\nfor N in 3:10\n\tx = linspace(-1,1,N)\n\t@test_approx_eq density(x,1) 2/(N-1)\nend\n\n@test density( [-1.0; 1.0], 1 ) == 2.0\n\n# A corner in the \"middle\" of each quadrant\nxi = [0.5 0.5 ; -0.5 0.5 ; -0.5 -0.5 ; 0.5 -0.5]\n@test_approx_eq density(xi, 1.0) sqrt(2)/2\n\n\n# ------------------------------------------------------------\n# ishaar and isdaubechies\n\nfor N in 2:10, prefix in [\"db\", \"DB\", \"Db\", \"dB\"]\n\tname = string(prefix, N)\n\t@test isdaubechies(name)\n\t@test !ishaar(name)\nend\n\n@test ishaar(\"haar\")\n@test ishaar(\"db1\")\n\n@test !isdaubechies(\"ddb2\")\n\n\n# ------------------------------------------------------------\n# Split \n\n# Vector\nx = rand( rand(5:10) )\nL, I, R = split(x,2)\n@test x == vcat(L, I, R)\n\n# Matrix\nA = rand(rand(5:10), rand(5:10))\nS = split(A,2)\n@test A == [ S.LL S.LI S.LR ; S.IL S.II S.IR ; S.RL S.RI S.RR ]\n\n", "meta": {"hexsha": "bfaddd631144541b783060c67bd428535144e6e6", "size": 2533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/misc.jl", "max_stars_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_stars_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": "test/misc.jl", "max_issues_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_issues_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": "test/misc.jl", "max_forks_repo_name": "JuliaPackageMirrors/GeneralizedSampling.jl", "max_forks_repo_head_hexsha": "2ae10851eb690043e1345cc0966ecdaf40911dd1", "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": 20.593495935, "max_line_length": 91, "alphanum_fraction": 0.5408606396, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7602793382054979}}
{"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\u2019s 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\u00d72 Named Array{Text{String},2}\nA \u2572 B \u2502       Male      Female\n\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n11-15 \u2502  16 (14.7)   14 (15.3)\n0-5   \u2502 15 (17.14)  20 (17.85)\n6-10  \u2502 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": "@testset \"MatPolynomial tests\" begin\n    @testset \"MatPolynomial\" begin\n        @polyvar x y\n        P = MatPolynomial{Int}((i,j) -> i + j, [x^2, x*y, y^2])\n        zP = zero(typeof(P))\n        @test isempty(zP.Q)\n        @test zP == 0\n        p = polynomial(P)\n        @test coefficients(p) == [2, 6, 12, 10, 6]\n        @test monomials(p) == [x^4, x^3*y, x^2*y^2, x*y^3, y^4]\n        for i in 1:3\n            for j in 1:3\n                @test P[i, j] == i + j\n            end\n        end\n        for P in (MatPolynomial((i,j) -> i * j, [y, x]),\n                  MatPolynomial((i,j) -> (3-i) * (3-j), monovec([y, x])),\n                  MatPolynomial([1 2; 2 4], [y, x]),\n                  MatPolynomial([4 2; 2 1], monovec([y, x])))\n            @test P.Q.Q == [4, 2, 1]\n            @test P.x[1] == x\n            @test P.x[2] == y\n        end\n        P = MatPolynomial((i,j) -> ((i,j) == (1,1) ? 2 : 0), [x*y, x^2, y^2])\n        Q = MatPolynomial([0 1; 1 0], [x^2, y^2])\n        @test P == Q\n        p = MatPolynomial([2 3; 3 2], [x, y])\n        @test polynomial(p) isa AbstractPolynomial{Int}\n        @test polynomial(p, Float64) isa AbstractPolynomial{Float64}\n\n        @test -2*x + dot(-x - x^2, 0) + MatPolynomial{Int}((i,j)->1, [1,x]) == -(-x^2 - 1)\n        P = MatPolynomial{Int}((i,j) -> i + j, [x^2, x*y, y^2])\n        p = polynomial(P)\n        @test !iszero(P)\n        @test iszero(P-P)\n        @test iszero(P-p)\n        @test iszero(p-P)\n        @test P + P == P + p\n        @test x * P == x * p\n        @test 2 * P == 2 * p\n        @test P * (2x) == (2x) * p\n\n        @test differentiate(MatPolynomial{Int}((i,j)->1, [x]), y) == 0\n        @test differentiate(MatPolynomial{Int}((i,j)->1, [x, y]), y, 1) == 2x + 2y\n        #@inferred differentiate(MatPolynomial{Int}((i,j)->1, [x, y]), y, 0) # FIXME failing at the moment\n\n        @test MatPolynomial([2 3; 3 2], [x, y]) == 2x^2 + 2y^2 + 6x*y\n\n        mp = MatPolynomial{Int}((i,j) -> i+j, [x])\n        @test norm(mp) == norm(mp, 2) == 2.0\n\n        @polyvar v[1:3]\n        P = [1 2 3; 2 4 5; 3 5 6]\n        p = MatPolynomial(P, v)\n        #@inferred p(x => ones(3))\n        @test p(v => ones(3)) == 31\n        #@inferred subs(p, x => ones(3))\n        @test subs(p, v => ones(3)) == 31\n    end\n    @testset \"SOSDecomposition\" begin\n        @polyvar x y\n#       @test isempty(SOSDecomposition(typeof(x)[]))\n#       ps = [1, x + y, x^2, x*y, 1 + x + x^2]\n#       P = MatPolynomial(SOSDecomposition(ps))\n#       P.Q == [2 0 1 0 1; 0 1 0 0 0; 1 0 2 1 1; 0 0 1 1 0; 1 0 1 0 2]\n#       P.x == [x^2, x*y, x, y, 1]\n#       @test P == P\n#       @test isapprox(MatPolynomial(SOSDecomposition(P)), P)\n        @test sprint(show, SOSDecomposition([x+y, x-y])) == \"(x + y)^2 + (x - y)^2\"\n        @testset \"SOSDecomposition equality\" begin\n            @polyvar x y\n            @test !isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x+y]))\n            @test !isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x+y, x+y]))\n            @test isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x+y, x-y]))\n            @test isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x-y, x+y+1e-8]), ztol=1e-7)\n        end\n    end\nend\n", "meta": {"hexsha": "76d3f21efb71d4a9124eb3cf0a2de98a9f9551e4", "size": 3196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/matpoly.jl", "max_stars_repo_name": "mforets/SumOfSquares.jl", "max_stars_repo_head_hexsha": "d98ad9b6e5fef3bac2e4cbaf38faf599cabeada9", "max_stars_repo_licenses": ["MIT"], "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/matpoly.jl", "max_issues_repo_name": "mforets/SumOfSquares.jl", "max_issues_repo_head_hexsha": "d98ad9b6e5fef3bac2e4cbaf38faf599cabeada9", "max_issues_repo_licenses": ["MIT"], "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/matpoly.jl", "max_forks_repo_name": "mforets/SumOfSquares.jl", "max_forks_repo_head_hexsha": "d98ad9b6e5fef3bac2e4cbaf38faf599cabeada9", "max_forks_repo_licenses": ["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.4556962025, "max_line_length": 106, "alphanum_fraction": 0.4715269086, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7602793247480554}}
{"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 \u03b1 and \u03b2 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    \u03b1 = params[1]\n    \u03b2 = params[2]\n    dist = Beta(\u03b1, \u03b2)\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(\u03b1::Real, \u03b2::Real; args...) = beta_moments((\u03b1, \u03b2); 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    \u03b1 = params[1]\n    \u03b2 = params[2]\n    dist = Gamma(\u03b1, \u03b2)\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(\u03b1::Real, \u03b2::Real; args...) = gamma_moments((\u03b1, \u03b2); 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    \u03b1 = params[1]\n    \u03b2 = params[2]\n    dist = InverseGamma(\u03b1, \u03b2)\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(\u03b1::Real, \u03b2::Real; args...) = invgamma_moments((\u03b1, \u03b2); 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": "using Rubin\nusing Tests\nusing Elliptic\nusing HypergeometricFunctions\nusing Polylogarithms\nusing SpecialFunctions\n\n@test integrate(sin(e+f*x)^m*(1+m+-1*sin(e+f*x)^2*(2+m)), x) == :(f^-1*sin(e+f*x)^(1+m)*cos(e+f*x))\n@test integrate(sin(e+f*x)^5*(6+-7*sin(e+f*x)^2), x) == :(f^-1*sin(e+f*x)^6*cos(e+f*x))\n@test integrate(sin(e+f*x)^4*(5+-6*sin(e+f*x)^2), x) == :(f^-1*sin(e+f*x)^5*cos(e+f*x))\n@test integrate(sin(e+f*x)^3*(4+-5*sin(e+f*x)^2), x) == :(f^-1*sin(e+f*x)^4*cos(e+f*x))\n@test integrate(sin(e+f*x)^2*(3+-4*sin(e+f*x)^2), x) == :(f^-1*sin(e+f*x)^3*cos(e+f*x))\n@test integrate((2+-3*sin(e+f*x)^2)*sin(e+f*x), x) == :(f^-1*sin(e+f*x)^2*cos(e+f*x))\n@test integrate(1+-2*sin(e+f*x)^2, x) == :(f^-1*cos(e+f*x)*sin(e+f*x))\n@test integrate(-1*sin(e+f*x)^2*csc(e+f*x), x) == :(f^-1*cos(e+f*x))\n@test integrate(-1*csc(e+f*x)^2, x) == :(f^-1*cot(e+f*x))\n@test integrate(csc(e+f*x)^3*(-2+sin(e+f*x)^2), x) == :(f^-1*cot(e+f*x)*csc(e+f*x))\n@test integrate(csc(e+f*x)^4*(-3+2*sin(e+f*x)^2), x) == :(f^-1*csc(e+f*x)^2*cot(e+f*x))\n@test integrate(csc(e+f*x)^5*(-4+3*sin(e+f*x)^2), x) == :(f^-1*csc(e+f*x)^3*cot(e+f*x))\n@test integrate(sin(e+f*x)^5*(A+C*sin(e+f*x)^2), x) == :(-1*f^-1*(A+C)*cos(e+f*x)+-1//5*f^-1*cos(e+f*x)^5*(A+3C)+1//3*f^-1*cos(e+f*x)^3*(2A+3C)+1//7*C*f^-1*cos(e+f*x)^7)\n", "meta": {"hexsha": "03e93ee0b2dfd6c7960f43c35af6231c7c4a8cfb", "size": 1280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/4 Trig functions/4.1 Sine/4.1.4.1 (a+b sin)^m (A+B sin+C sin^2).jl", "max_stars_repo_name": "bradeneliason/Rubin.jl", "max_stars_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-13T03:00:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T03:00:21.000Z", "max_issues_repo_path": "test/4 Trig functions/4.1 Sine/4.1.4.1 (a+b sin)^m (A+B sin+C sin^2).jl", "max_issues_repo_name": "bradeneliason/Rubin.jl", "max_issues_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_issues_repo_licenses": ["MIT"], "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/4 Trig functions/4.1 Sine/4.1.4.1 (a+b sin)^m (A+B sin+C sin^2).jl", "max_forks_repo_name": "bradeneliason/Rubin.jl", "max_forks_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_forks_repo_licenses": ["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.9523809524, "max_line_length": 169, "alphanum_fraction": 0.540625, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7602793155018783}}
{"text": "# [test/rkadapt_tests.jl]\nusing Test \n\n@testset \"RK Adapt Tests\" begin\n\n    using JLD2\n    import ODEHybrid.rkadapt, ODEHybrid.ODE_SET\n\n    @testset \"No options, default tableau\" begin \n\n        # mat\"\"\"\n        # [$t_mat, $x_mat] = rkadapt(@(t,x) [-x(2); x(1)], [0.0 10.0], [1.0; 0.0]);\n        # \"\"\"\n\n        @load \"solutions/rkadapt_no_opt_default.jld2\" t_mat x_mat\n\n        t_jul, x_jul = rkadapt( (t, x) -> [-x[2]; x[1]], [0.0 10.0], [1.0; 0.0]);\n\n        @test isapprox(t_mat, t_jul, atol = 1e-11)\n        @test isapprox(x_mat, x_jul, atol = 1e-11)\n    end\n\n    @testset \"No options, custom tableau\" begin \n        a = [0   0   0   0;\n            1/2 0   0   0;\n            0   3/4 0   0;\n            2/9 1/3 4/9 0];\n\n        b = [2/9  1/3  4/9  0;     # For the update\n            7/24 1/4  1/3  1/8];   # For the error prediction\n        c = [0 1/2 3/4 1];\n        p = 2.0;                   # The lower of the two orders\n\n        # mat\"\"\"\n        # [$t_mat, $x_mat] = rkadapt(@(t,x) [-x(2); x(1)], [0 10], [1; 0], [], $a, $b, $c, $p);\n        # \"\"\"\n\n        @load \"solutions/rkadapt_no_opt_custom_tab.jld2\" t_mat x_mat\n        \n        t_jul, x_jul = rkadapt( (t, x) -> [-x[2]; x[1]], [0.0 10.0], [1.0; 0.0], a, b, c, p)\n\n        @test isapprox(t_mat, t_jul, atol = 1e-11)\n        @test isapprox(x_mat, x_jul, atol = 1e-11)\n       \n    end\n\n    @testset \"Options, default tableau\" begin \n        # mat\"\"\"\n        #     options = odeset('MaxStep', 0.1, 'InitialStep', 0.05);\n        #     [$t_mat, $x_mat] = rkadapt(@(t,x) [-x(2); x(1)], [0.0 10.0], [1.0; 0.0], options);\n        # \"\"\"\n\n        @load \"solutions/rkadapt_with_opt_default.jld2\" t_mat x_mat\n\n        options = ODE_SET();\n        options.MaxStep = 0.1 \n        options.InitialStep = 0.05\n        t_jul, x_jul = rkadapt( (t, x) -> [-x[2]; x[1]], [0.0, 10.0], [1.0; 0.0], options)\n\n    \n        @test isapprox(t_mat, t_jul, atol = 1e-11)\n        @test isapprox(x_mat, x_jul, atol = 1e-11)\n    end\n\n    @testset \"Full function call\" begin \n\n        a = [0   0   0   0;\n             1/2 0   0   0;\n             0   3/4 0   0;\n             2/9 1/3 4/9 0];\n\n        b = [2/9  1/3  4/9  0;     # For the update\n             7/24 1/4  1/3  1/8];  # For the error prediction\n        c = [0 1/2 3/4 1];\n        p = 2.0;                   # The lower of the two orders\n\n        # mat\"\"\"\n        #     options = odeset('MaxStep', 0.25, 'InitialStep', 0.025);\n        #     [$t_mat, $x_mat] = rkadapt(@(t,x) [-x(2); x(1)], [0.0 10.0], [1.0; 0.0], options, $a, $b, $c, $p);\n        # \"\"\"\n        \n        @load \"solutions/rkadapt_full_func_call.jld2\" t_mat x_mat;\n\n        options = ODE_SET();\n        options.MaxStep = 0.25\n        options.InitialStep = 0.025\n        t_jul, x_jul = rkadapt( (t, x) -> [-x[2]; x[1]], [0.0, 10.0], [1.0; 0.0], options, a, b, c, p)\n\n\n        @test isapprox(t_mat, t_jul, atol = 1e-9)\n        @test isapprox(x_mat, x_jul, atol = 1e-9)\n    end;\n    \nend;\n", "meta": {"hexsha": "ab7d9ce20be280d79da2b886030c63ae2426f04a", "size": 2942, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rkadapt_tests.jl", "max_stars_repo_name": "benjjensen/ODEHybrid.jl", "max_stars_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_stars_repo_licenses": ["MIT"], "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/rkadapt_tests.jl", "max_issues_repo_name": "benjjensen/ODEHybrid.jl", "max_issues_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-18T18:50:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T18:59:30.000Z", "max_forks_repo_path": "test/rkadapt_tests.jl", "max_forks_repo_name": "benjjensen/ODEHybrid.jl", "max_forks_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_forks_repo_licenses": ["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.9684210526, "max_line_length": 112, "alphanum_fraction": 0.4680489463, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7602335952197985}}
{"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}}}, \u03b4t::S) where\r\n        {N, T<:Number, S<:Number} = evaluate.(x, \u03b4t)\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": "# Code from @devmotion\n# https://github.com/devmotion/\\\n# CalibrationErrorsDistributions.jl/blob/main/src/distances/bures.jl\nusing ExactOptimalTransport\n\nusing LinearAlgebra\nusing Random\nusing PDMats\n\n@testset \"bures.jl\" begin\n    function _sqbures(A, B)\n        sqrt_A = sqrt(A)\n        return tr(A) + tr(B) - 2 * tr(sqrt(sqrt_A * B * sqrt_A'))\n    end\n\n    function rand_matrices(n)\n        A = randn(n, n)\n        B = A' * A + I\n        return B, PDMat(B), PDiagMat(diag(B)), ScalMat(n, B[1])\n    end\n\n    for (x, y) in Iterators.product(rand_matrices(10), rand_matrices(10))\n        xfull = Matrix(x)\n        yfull = Matrix(y)\n        @test ExactOptimalTransport.sqbures(x, y) \u2248 _sqbures(xfull, yfull)\n    end\nend\n", "meta": {"hexsha": "2eae61f190a0f9366a41de561d59652e0510fe92", "size": 718, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/bures.jl", "max_stars_repo_name": "JuliaOptimalTransport/ExactOptimalTransport.jl", "max_stars_repo_head_hexsha": "c67137b3be1434da4bb8942a593bee5d4b675599", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-09-05T17:24:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:37:10.000Z", "max_issues_repo_path": "test/bures.jl", "max_issues_repo_name": "juliohm/ExactOptimalTransport.jl", "max_issues_repo_head_hexsha": "1b1d3da31fdbc13f6488c49c10b453ac47baf75c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-09-03T16:55:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T01:05:09.000Z", "max_forks_repo_path": "test/bures.jl", "max_forks_repo_name": "juliohm/ExactOptimalTransport.jl", "max_forks_repo_head_hexsha": "1b1d3da31fdbc13f6488c49c10b453ac47baf75c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-09-06T10:35:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T13:37:30.000Z", "avg_line_length": 25.6428571429, "max_line_length": 74, "alphanum_fraction": 0.635097493, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7602219764120394}}
{"text": "immutable Tradeoff{T} <: Model\n    a::T\n    k::T\n    \u03b3x::T\n    \u03b3t::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, \u03b3x = %.3f, \u03b3t = %.3f)\",\n        m.a,\n        m.k,\n        m.\u03b3x,\n        m.\u03b3t,\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.\u03b3x, m.\u03b3t)\n\nfunction Tradeoff(parameters::Vector)\n    a = exp(parameters[1])\n    k = exp(parameters[2])\n    \u03b3x = exp(parameters[3])\n    \u03b3t = exp(parameters[4])\n    return Tradeoff(a, k, \u03b3x, \u03b3t)\nend\n\n@inline \u03d5(\u03c7, \u03b3) = log(1 + \u03b3 * \u03c7) / \u03b3\n\n@inline \u03d5\u2032(\u03c7, \u03b3) = ((\u03b3 * \u03c7) / (1 + \u03b3 * \u03c7) - log(1 + \u03b3 * \u03c7)) / \u03b3^2\n\n@inline function predict(m::Tradeoff, x2::Real, t2::Real, x1::Real, t1::Real)\n    a, k, \u03b3x, \u03b3t = m.a, m.k, m.\u03b3x, m.\u03b3t\n    \u03b4\u03d5x = \u03d5(x2, \u03b3x) - \u03d5(x1, \u03b3x)\n    \u03b4\u03d5t = \u03d5(t2, \u03b3t) - \u03d5(t1, \u03b3t)\n    z = a * (\u03b4\u03d5x - k * \u03b4\u03d5t)\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, \u03b3x, \u03b3t = m.a, m.k, m.\u03b3x, m.\u03b3t\n    \u03b4\u03d5x = \u03d5(x2, \u03b3x) - \u03d5(x1, \u03b3x)\n    \u03b4\u03d5t = \u03d5(t2, \u03b3t) - \u03d5(t1, \u03b3t)\n    \u03b4\u03d5\u2032x = \u03d5\u2032(x2, \u03b3x) - \u03d5\u2032(x1, \u03b3x)\n    \u03b4\u03d5\u2032t = \u03d5\u2032(t2, \u03b3t) - \u03d5\u2032(t1, \u03b3t)\n    gr = (\n        (\u03b4\u03d5x - k * \u03b4\u03d5t) * a,\n        -a * \u03b4\u03d5t * k,\n        a * \u03b4\u03d5\u2032x * \u03b3x,\n        a * -k * \u03b4\u03d5\u2032t * \u03b3t,\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": "using NumericalMethodsforEngineers\nusing Test\n\nA = Float64[3 -2 1;-2 3 2;1 2 2]\nb = Float64[3, -3, 2]\n\nL, U = lufac(A)\nF = lu(A)\n\n@test round.(U, digits=5) == [3.0 -2.0 1.0;0.0 1.66667 2.66667;0.0 0.0 -2.6]\n", "meta": {"hexsha": "5369357760127f3bc2edb4b93ee8c69e6b8ab06e", "size": 207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch02_lufac.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/ch02_lufac.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/ch02_lufac.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.8181818182, "max_line_length": 76, "alphanum_fraction": 0.6038647343, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897426182322, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7602213480307856}}
{"text": "\"\"\"\n    Tanh(x)\n\nHyperbolic tangent activation function.\n\n    Usage:\n```julia-repl\nTanh(x)\n```\nArguments:\n- `x` : Input value.\n\"\"\"\nfunction Tanh(x::Float64)\n    x\u2081 = tanh(x)\n    return x\u2081\nend", "meta": {"hexsha": "67f108ecbfb7a71a12e874c19beab91b86064a3a", "size": 191, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ActivationFunctions/Tanh.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/ActivationFunctions/Tanh.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/ActivationFunctions/Tanh.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": 11.9375, "max_line_length": 39, "alphanum_fraction": 0.612565445, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7602213478914495}}
{"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": "# SPOT example from file doc/examples/sdsos_example.m\n# of https://github.com/anirudhamajumdar/spotless/tree/spotless_isos\n# See Section 4.1 of [AM17].\n#\n# [AM17] Section 4.1 of\n# A. A. Ahmadi, and A. Majumdar\n# DSOS and SDSOS Optimization: More Tractable Alternatives to Sum of Squares and Semidefinite Optimization\n# 2017\n\nusing Test\nusing SumOfSquares\nusing DynamicPolynomials\n\nfunction quartic_comparison_test(\n    optimizer, config::MOIT.TestConfig,\n    cone::SumOfSquares.PolyJuMP.PolynomialSet, expected_objective_value)\n    atol = config.atol\n    rtol = config.rtol\n\n    @polyvar x[1:3]\n    vx = monomials(x, 4) # Degree 4 homogeneous\n    # Coefficient of polynomial\n    cp = 15:-1:1\n    p = polynomial(cp, vx)\n\n    model = _model(optimizer)\n    @variable(model, \u03b3)\n    @constraint(model, p - \u03b3 * sum(x .* x)^2 in cone)\n    @objective(model, Max, \u03b3)\n    JuMP.optimize!(model)\n    @test JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n    @test JuMP.objective_value(model) \u2248 expected_objective_value atol=atol rtol=rtol\nend\n\nsos_quartic_comparison_test(optimizer, config)   = quartic_comparison_test(optimizer, config, SOSCone(), -0.184667)\nsd_tests[\"sos_quartic_comparison\"]      = sos_quartic_comparison_test\nsdsos_quartic_comparison_test(optimizer, config) = quartic_comparison_test(optimizer, config, SDSOSCone(), -3.172412)\nsoc_tests[\"sdsos_quartic_comparison\"]   = sdsos_quartic_comparison_test\ndsos_quartic_comparison_test(optimizer, config)  = quartic_comparison_test(optimizer, config, DSOSCone(), -11/3)\nlinear_tests[\"dsos_quartic_comparison\"] = dsos_quartic_comparison_test\n", "meta": {"hexsha": "6d450a3b990ddc51849bb5d895b92187f173b23c", "size": 1592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Tests/quartic_comparison.jl", "max_stars_repo_name": "stephentu/SumOfSquares.jl", "max_stars_repo_head_hexsha": "e781643d15fd5cf49b5b4e2cd45b484e0cc45b77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2020-08-12T02:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T17:56:02.000Z", "max_issues_repo_path": "test/Tests/quartic_comparison.jl", "max_issues_repo_name": "stephentu/SumOfSquares.jl", "max_issues_repo_head_hexsha": "e781643d15fd5cf49b5b4e2cd45b484e0cc45b77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 70, "max_issues_repo_issues_event_min_datetime": "2020-07-15T21:49:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:55:33.000Z", "max_forks_repo_path": "test/Tests/quartic_comparison.jl", "max_forks_repo_name": "stephentu/SumOfSquares.jl", "max_forks_repo_head_hexsha": "e781643d15fd5cf49b5b4e2cd45b484e0cc45b77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-08-04T15:04:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T22:12:41.000Z", "avg_line_length": 38.8292682927, "max_line_length": 117, "alphanum_fraction": 0.7594221106, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8354835411997898, "lm_q1q2_score": 0.7602123336906325}}
{"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(\u03b8,a::Any,b::Any)\n    #using SpecialFunctions\n    \u03b8 = \u03b8[1]\n    if 0 < \u03b8 < 1\n        # Numerator\n        num = log(\u03b8)*(a-1) + log(1-\u03b8)*(b-1)\n        # The denominator (Beta-function) can be integrated or made up of Gamma-functions\n        # Since we only treat integer values here, \u0393(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(\u03b8,y)\n    if 0 < \u03b8 < 1 && (y==0 || y==1)    # Only admissible values\n        return y * log(\u03b8) + (1-y) * log(1-\u03b8)\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(\u03b8, y)\n    # Make array s.t. multiple theta values can be input:\n    #likelihood = Array{Float64}(undef,length(\u03b8))\n    # Do that for every theta value requested:\n    #for ii in 1:length(\u03b8)\n    #    # Elementwise application of the log_beronoulli_pdf over outcome vector y, then SUM together:\n    #    likelihood[ii] = sum(log_bernoulli_pdf.(\u03b8[ii],y))\n    #end\n\n    # Un array-ise the output:\n    #if length(\u03b8) == 1\n    #    likelihood = likelihood[1]\n    #end\n\n    \u03b8 = \u03b8[1]\n    likelihood = sum(log_bernoulli_pdf.(\u03b8,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(\u03b8) = log_beta(\u03b8,a,b)\nlog_lklhd(\u03b8) = log_likelihood_fct(\u03b8,y)\nlog_posterior(\u03b8) = log_lklhd(\u03b8) + log_prior(\u03b8)\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(\u03b8) = log_beta(\u03b8,a,b)\nlog_lklhd(\u03b8) = log_likelihood_fct(\u03b8,y)\nlog_posterior(\u03b8) = log_lklhd(\u03b8) + log_prior(\u03b8)\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(\u03b8) = log_beta(\u03b8,a,b)\nlog_lklhd(\u03b8) = log_likelihood_fct(\u03b8,y)\nlog_posterior(\u03b8) = log_lklhd(\u03b8) + log_prior(\u03b8)\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, \u03b3, info = glover_mcfarlane(G::AbstractStateSpace, \u03b3 = 1.1; W1=1, W2=1)\n\nDesign a controller for `G` that maximizes the stability margin \u03f5 = 1/\u03b3 with normalized coprime factor uncertainty using the method of Glover and McFarlane\n```\n\u03b3 = 1/\u03f5 = ||[K;I] inv(I-G*K)*inv(M)||\u221e\nG = inv(M + \u0394M)*(N + \u0394N)\n```\n\u03b3 is given as a relative factor above \u03b3min and must be greater than 1, i.e., if \u03b3 = 1.1, the controller will be designed for \u03b3 = 1.1*\u03b3min.\n\nWe want \u03b3min (which is always \u2265 1) as small as possible, and we usually require that \u03b3min 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, \u03b3, info = glover_mcfarlane(G, 1.1; W1)\n@test info.\u03b3min \u2248 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 $\u03f5_{max} = 1/\u03b3_{min}$ is calculated. If the margin is too small, $\u03f5max < 0.25$, then go back and modify the weights. Otherwise, a \u03b3-suboptimal controller is synthesized. There is usually no advantage to be gained by using the optimal controller. When $\u03f5_{max}$ > 0.25\n    (respectively $\u03b3_{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 \u03f5max 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 \u03b3 is small (\u03f5 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       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    r  \u2502         \u2502    us\u2502        \u2502  u   \u2502        \u2502  y\n   \u2500\u2500\u2500\u25ba\u2502(K*W2)(0)\u251c\u2500\u2500+\u2500\u2500\u25ba\u2502   W1   \u251c\u2500\u2500\u2500\u2500\u2500\u25ba\u2502   G    \u251c\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u25ba\n       \u2502         \u2502  \u2502-  \u2502        \u2502      \u2502        \u2502    \u2502\n       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2502\n                    \u2502                                 \u2502\n                    \u2502                                 \u2502\n                    \u2502   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u2502\n                    \u2502   \u2502        \u2502  ys  \u2502        \u2502    \u2502\n                    \u2514\u2500\u2500\u2500\u2524   K    \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2524   W2   \u2502\u25c4\u2500\u2500\u2500\u2518\n                        \u2502        \u2502      \u2502        \u2502\n                        \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\nKeywords: nfcsyn, coprimeunc\n\"\"\"\nfunction glover_mcfarlane(G::AbstractStateSpace{Continuous}, \u03b3 = 1.1; W1=1, W2=1)\n    \u03b3 > 1 || throw(ArgumentError(\"\u03b3 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\u0304 = A - B*(S\\D'C)\n    Z,_ = MatrixEquations.arec(A\u0304', C', R, B*(Sl\\B'))\n    X,_ = MatrixEquations.arec(A\u0304, B, S, C'*(R\\C))\n\n    \u03b3min = sqrt(1 + \u03c1(X*Z))\n\n    \u03b3 *= \u03b3min\n\n    L = (1-\u03b3^2)*I + X*Z\n    F = -(Sl\\(D'C + B'X))\n    BK = \u03b3^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, \u03c9 = hinfnorm2(Gcl)\n    K = W1*Ks*W2\n    Gcl = extended_gangoffour(G, K)\n    K, \u03b3, (; Gcl, margin = inv(imargin), \u03c9, \u03b3min, Ks, Gs, Z, X)\nend\n\n\"\"\"\n    K, \u03b3, info = glover_mcfarlane(G::AbstractStateSpace{<:Discrete}, \u03b3 = 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\u2032 = 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}, \u03b3 = 1.1; W1=1, W2=1, strictly_proper=false)\n    \u03b3 > 1 || throw(ArgumentError(\"\u03b3 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        \u03b3min = \u03c1(QM)\n        \u03b3 *= \u03b3min\n\n\n        W = (\u03b3^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\u221e 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 = -\u03b3^2*Flq/W # Original paper\n        # F = -\u03b3^2*B'XW*((I + \u03b3^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        \u03b3min = sqrt(1 + \u03c1(X*Z))\n        \u03b3 *= \u03b3min\n\n        W = (\u03b3^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 + \u03b3^2*B*B'XW)\n        \u03b32B = \u03b3^2*B'\n        arne = \u03b32B*XW\n        Ak = hest\\Akf\n        Ck = arne*Ak\n        Bk = hest\\Hkf\n        Dk = arne*Bk\n\n        F0 = -\u03b32B*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, \u03c9 = hinfnorm2(Gcl)\n    K = W1*Ks*W2\n    Gcl = extended_gangoffour(G, K)\n    K, \u03b3, (; Gcl, margin = inv(imargin), \u03c9, \u03b3min, 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, \u03b3, info = glover_mcfarlane_2dof(G::AbstractStateSpace{Continuous}, Tref::AbstractStateSpace{Continuous}, \u03b3 = 1.1, \u03c1 = 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   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2510\nr  \u2502      \u2502   \u2502      \u2502        \u2502      \u2502    \u2502     \u2502\n\u2500\u2500\u25ba\u2502  Wi  \u251c\u2500\u2500\u25ba\u2502  K1  \u251c\u2500\u2500\u2500+\u2500\u2500\u2500\u25ba\u2502  W1  \u251c\u2500\u2500\u2500\u25ba\u2502  G  \u251c\u2500\u2510y\n   \u2502      \u2502   \u2502      \u2502   \u2502    \u2502      \u2502    \u2502     \u2502 \u2502\n   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2502    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n                         \u2502                        \u2502\n                         \u2502    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510            \u2502\n                         \u2502    \u2502      \u2502            \u2502\n                         \u2514\u2500\u2500\u2500\u2500\u2524  K2  \u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                              \u2502      \u2502\n                              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\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- `\u03b3`: Relative \u03b3\n- `\u03c1`: Design parameter, typically 1 < \u03c1 < 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, \u03b31, info1 = glover_mcfarlane(ss(P), 1.1; W1)\nK2dof, \u03b32, 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}, \u03b3 = 1.1, \u03c1 = 1.1; W1=1, Wo = I, match_dc = true, kwargs...)\n    \u03b3 > 1 || throw(ArgumentError(\"\u03b3 must be greater than 1\"))\n    \u03c1 > 1 || throw(ArgumentError(\"\u03c1 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); \u03c1*Wo*Cs -\u03c1^2*Cr]\n    C2 = [zeros(mr,ns+nr); Cs zeros(ls,nr)]\n    D11 = [zeros(ms,mr+ls); zeros(ls,mr) sRs;-\u03c1^2*Dr \u03c1*Wo*sRs]\n    D12 = [I(ms);Ds;\u03c1*Ds]\n    D21 = [\u03c1*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, \u03b3opt = hinfsynthesize(P, \u03b3rel = \u03b3; 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, \u03b3opt, info\nend\n\n\n\n\"Spectral radius\"\nfunction \u03c1(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      \u25b2  \u250c\u2500\u2500\u2500\u2500\u2500\u2510  \u25b2      \u250c\u2500\u2500\u2500\u2500\u2500\u2510\n      \u2502  \u2502     \u2502  \u2502      \u2502     \u2502\nw1\u2500\u2500+\u2500\u2534\u2500\u25ba\u2502  C  \u251c\u2500\u2500\u2534\u2500\u2500\u2500+\u2500\u25ba\u2502  P  \u251c\u2500\u2510\n    \u2502    \u2502     \u2502      \u2502  \u2502     \u2502 \u2502\n    \u2502    \u2514\u2500\u2500\u2500\u2500\u2500\u2518      \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2518 \u2502\n    \u2502                 w2         \u2502\n    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\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, \u03c9 = ncfmargin(P, K)\n\nNormalized coprime factor margin, defined has the inverse H\u221e 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 \u2265 0.25-0.3 is a reasonable for robustness. \n\nIf controller `K` stabilizes `P` with margin `m`, then `K` will also stabilize `P\u0303` if `nugap(P, P\u0303) < 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": "# ------------ #\n# Original API #\n# ------------ #\n\n# splidef.m -- DONE\nfunction splidef(breaks, evennum=0, k::Int=3)\n    p = SplineParams(breaks, evennum, k)\n    return (\n        length(p.breaks),\n        minimum(p.breaks),\n        maximum(p.breaks),\n        Any[p.breaks, 0, k],\n        p\n    )\nend\n\n# splinode.m  -- DONE\nsplinode(breaks::AbstractVector, evennum::Int, k::Int=3) =\n    nodes(SplineParams(breaks, evennum, k))\n\nfunction splidop(breaks, evennum=0, k=3, order=1)\n    D, p = derivative_op(SplineParams(breaks, evennum, k), order)\n    n = length(breaks) + k - 1\n\n    D, n-order, breaks[1], breaks[end], Any[breaks, evennum, k-order]\nend\n\n# splibas.m -- DONE\nfunction splibase(breaks::AbstractVector, evennum, k=3, x=splinode(breaks, evennum, k),\n                  order=0)\n    B = evalbase(SplineParams(breaks, evennum, k), x, order)\n    B, x\nend\n", "meta": {"hexsha": "eab6cd97023e14f0729b928274db0e5c823e16c5", "size": 860, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spli.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CompEcon.jl-1375f997-1772-542d-b6fa-a8ee39124556", "max_stars_repo_head_hexsha": "c70bbca2b052a356aa7f136edbe311c03cac0087", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-01-09T11:16:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T23:01:45.000Z", "max_issues_repo_path": "src/spli.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CompEcon.jl-1375f997-1772-542d-b6fa-a8ee39124556", "max_issues_repo_head_hexsha": "c70bbca2b052a356aa7f136edbe311c03cac0087", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2016-10-25T22:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-16T21:09:38.000Z", "max_forks_repo_path": "src/spli.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CompEcon.jl-1375f997-1772-542d-b6fa-a8ee39124556", "max_forks_repo_head_hexsha": "c70bbca2b052a356aa7f136edbe311c03cac0087", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2016-11-21T08:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:21:15.000Z", "avg_line_length": 25.2941176471, "max_line_length": 87, "alphanum_fraction": 0.5953488372, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7602123175388954}}
{"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(\u03b8,a::Any,b::Any)\n    #using SpecialFunctions\n    \u03b8 = \u03b8[1]\n    if 0 < \u03b8 < 1\n        # Numerator\n        num = log(\u03b8)*(a-1) + log(1-\u03b8)*(b-1)\n        # The denominator (Beta-function) can be integrated or made up of Gamma-functions\n        # Since we only treat integer values here, \u0393(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(\u03b8,y)\n    if 0 < \u03b8 < 1 && (y==0 || y==1)    # Only admissible values\n        return y * log(\u03b8) + (1-y) * log(1-\u03b8)\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(\u03b8, y)\n    # Make array s.t. multiple theta values can be input:\n    #likelihood = Array{Float64}(undef,length(\u03b8))\n    # Do that for every theta value requested:\n    #for ii in 1:length(\u03b8)\n    #    # Elementwise application of the log_beronoulli_pdf over outcome vector y, then SUM together:\n    #    likelihood[ii] = sum(log_bernoulli_pdf.(\u03b8[ii],y))\n    #end\n\n    # Un array-ise the output:\n    #if length(\u03b8) == 1\n    #    likelihood = likelihood[1]\n    #end\n\n    \u03b8 = \u03b8[1]\n    likelihood = sum(log_bernoulli_pdf.(\u03b8,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(\u03b8) = log_beta(\u03b8,a,b)\nlog_lklhd(\u03b8) = log_likelihood_fct(\u03b8,y)\nlog_posterior(\u03b8) = log_lklhd(\u03b8) + log_prior(\u03b8)\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\u03bc = sum(chain)/N\n\n# Mode\n\u03c9 = 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\u03b1 = 0.05;\nidcesForOrder = sortperm(chain) # Indices of the chain which make it sorted\nchain_sorted = chain[idcesForOrder]\n\nleftTailIdx = Int(floor(N*(\u03b1/2)))\nrightTailIdx = Int(ceil(N*(1- \u03b1/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(\u03b8) = log_beta(\u03b8,a,b)\nlog_lklhd(\u03b8) = log_likelihood_fct(\u03b8,y)\nlog_posterior(\u03b8) = log_lklhd(\u03b8) + log_prior(\u03b8)\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 = (\u03bc .> chain2) * 1\n#sum(gt)/N\n\n#%% Method 1.2, questionable...\n#\u03bc2 = sum(chain2)/N\n#\u03c92 = 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\u03b8 = (chain - chain2)\ngtZero = (d\u03b8 .> 0)*1\nsum(gtZero)/N\nhdi(d\u03b8)\n\n#%% Method 3\nd\u03b8 = (chain - chain2)\nd\u03b8 = reshape(d\u03b8,:)      # to get an Array{Float64,1}\nhistogram(d\u03b8, bins=100, normalize=:pdf, label=\"d_theta\")\ndensity!(d\u03b8,linewidth=3,label=\"d_theta\")\n#%%\ndiff_hdi = hdi(d\u03b8)\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\u1d40, bu+1) + tril(pq\u1d40, -bl-1),\n#\n# where bu, bl >= 0. u and v are n \u00d7 ru matrices and p and q are n \u00d7 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 \u2265\u00a0S.bl && return S.L[k,j]\n    j-k \u2265 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\u2019s Conjugate Residual method for linesearch.\n\n\"\"\"A version of Stiefel\u2019s Conjugate Residual method for linesearch.\nCR(A, b, \u03f5a, \u03f5r, itmax; quad) solves the symmetric linear system 'A * x = b'\nor the least-squares problem : 'min \u2016b - A * x\u2016\u00b2'\nIf quad = true, the values of the quadratic model are computed\nA can be positive definite or not.\n\"\"\"\nfunction CRlin(A, b, \u03f5a::Float64=1e-8, \u03f5r::Float64=1e-6, itmax::Int=0, \u03b5::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 \u2016x\u2016\n    r = b # initial residual r = b - Ax = b\n    rNorm = norm(r, 2) # \u2016r\u2016\n    rNorm\u00b2 = rNorm * rNorm\n    pr = rNorm\u00b2\n    s = A * r\n    \u03c1 = dot(r, s)\n    p = r\n    pNorm\u00b2 = rNorm\u00b2\n    q = s\n    \u03f5 = \u03f5a + \u03f5r * rNorm\n    pAp = \u03c1 # = 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\", \"\u2016r\u2016\", \"q\"))\n        @info(loggerCRlin, @sprintf(\"%5d %7.1e %8.1e\", iter, rNorm, m))\n    end\n\n    solved = rNorm \u2264 \u03f5\n    tired = iter \u2265 itmax\n\n    while ! (solved || tired)\n        iter += 1\n\n        if (pAp \u2264 \u03b5 * pNorm\u00b2) || (\u03c1 \u2264 \u03b5 * rNorm\u00b2)\n            @debug(loggerCRlin, @sprintf(\"nonpositive curvature detected: pAp = %8.1e and rAr = %8.1e\", pAp, \u03c1))\n            iter == 1 && return b\n            return x\n        end\n\n        \u03b1 = \u03c1 / dot(q, q) # step\n        x = x + \u03b1 * p\n        xNorm = norm(x, 2)\n        push!(xNorms, xNorm)\n        r = r - \u03b1 * q  # residual\n        rNorm\u00b2 = abs(rNorm\u00b2 - \u03b1 * \u03c1)\n        rNorm = sqrt(rNorm\u00b2)\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 <= \u03f5\n        tired = iter >= itmax\n        (solved || tired) && continue\n\n        s = A * r\n        \u03c1bar = \u03c1\n        \u03c1 = dot(r, s)\n        \u03b2 = \u03c1 / \u03c1bar # step for the direction calculus\n        p = r + \u03b2 * p # descent direction\n        pNorm\u00b2 = rNorm\u00b2 + 2 * \u03b2 * pr - 2 * \u03b2 * \u03b1 * pAp + \u03b2^2 * pNorm\u00b2\n        pr = rNorm\u00b2 + \u03b2 * pr - \u03b2 * \u03b1 * pAp # p\u1d40r\n        q = s + \u03b2 * q\n        pAp = \u03c1 + \u03b2^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": "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", "meta": {"hexsha": "7d18ae91d3f0a5981d5d002428eac78ac982c187", "size": 355, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/ldlt.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/ldlt.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/ldlt.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": 19.7222222222, "max_line_length": 69, "alphanum_fraction": 0.4647887324, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7601662333121026}}
{"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. * \u221a(5.) ) / 20.\n        b = ( 5. - \u221a(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\u2081 = x -> Int(0 \u2264 x < 1)\nB\u2082 = x -> Int(1 \u2264 x < 2)\nB\u2083 = x -> Int(2 \u2264 x < 3)\nB\u2084 = x -> Int(3 \u2264 x < 4)\nB\u2085 = x -> Int(4 \u2264 x \u2264 5)\n\nb1_exact = [B\u2081, B\u2082, B\u2083, B\u2084, B\u2085]\n\nb2 = BSplineBasis(2, big(0):1:big(5))\n\nB\u2081 = x -> 0 \u2264 x < 1 ? -x + 1 : 0*one(x)\nB\u2082 = x -> 0 \u2264 x < 1 ?  x + 0 :\n          1 \u2264 x < 2 ? -x + 2 : 0*one(x)\nB\u2083 = x -> 1 \u2264 x < 2 ?  x - 1 :\n          2 \u2264 x < 3 ? -x + 3 : 0*one(x)\nB\u2084 = x -> 2 \u2264 x < 3 ?  x - 2 :\n          3 \u2264 x < 4 ? -x + 4 : 0*one(x)\nB\u2085 = x -> 3 \u2264 x < 4 ?  x - 3 :\n          4 \u2264 x \u2264 5 ? -x + 5 : 0*one(x)\nB\u2086 = x -> 4 \u2264 x \u2264 5 ?  x - 4 : 0*one(x)\n# 1st derivatives\nB\u2081\u2032 = x -> 0 \u2264 x < 1 ? -1*one(x) : 0*one(x)\nB\u2082\u2032 = x -> 0 \u2264 x < 1 ?  1*one(x) :\n           1 \u2264 x < 2 ? -1*one(x) : 0*one(x)\nB\u2083\u2032 = x -> 1 \u2264 x < 2 ?  1*one(x) :\n           2 \u2264 x < 3 ? -1*one(x) : 0*one(x)\nB\u2084\u2032 = x -> 2 \u2264 x < 3 ?  1*one(x) :\n           3 \u2264 x < 4 ? -1*one(x) : 0*one(x)\nB\u2085\u2032 = x -> 3 \u2264 x < 4 ?  1*one(x) :\n           4 \u2264 x \u2264 5 ? -1*one(x) : 0*one(x)\nB\u2086\u2032 = x -> 4 \u2264 x \u2264 5 ?  1*one(x) : 0*one(x)\n\nb2_exact = [B\u2081 B\u2081\u2032; B\u2082 B\u2082\u2032; B\u2083 B\u2083\u2032; B\u2084 B\u2084\u2032; B\u2085 B\u2085\u2032; B\u2086 B\u2086\u2032]\n\nb3 = BSplineBasis(3, 0//1:5//1)\n\nB\u2081 = x -> 0 \u2264 x < 1 ? 1//1*x^2 - 2//1*x + 1//1 : 0//1*one(x)\nB\u2082 = x -> 0 \u2264 x < 1 ? -3//2*x^2 + 2//1*x        :\n          1 \u2264 x < 2 ?  1//2*x^2 - 2//1*x + 2//1 : 0//1*one(x)\nB\u2083 = x -> 0 \u2264 x < 1 ?  1//2*x^2                 :\n          1 \u2264 x < 2 ? -1//1*x^2 + 3//1*x - 3//2 :\n          2 \u2264 x < 3 ?  1//2*x^2 - 3//1*x + 9//2 : 0//1*one(x)\nB\u2084 = x -> 1 \u2264 x < 2 ?  1//2*x^2 - 1//1*x +  1//2 :\n          2 \u2264 x < 3 ? -1//1*x^2 + 5//1*x - 11//2 :\n          3 \u2264 x < 4 ?  1//2*x^2 - 4//1*x +  8//1 : 0//1*one(x)\nB\u2085 = x -> 2 \u2264 x < 3 ?  1//2*x^2 - 2//1*x +  2//1 :\n          3 \u2264 x < 4 ? -1//1*x^2 + 7//1*x - 23//2 :\n          4 \u2264 x \u2264 5 ?  1//2*x^2 - 5//1*x + 25//2 : 0//1*one(x)\nB\u2086 = x -> 3 \u2264 x < 4 ?  1//2*x^2 -  3//1*x +  9//2 :\n          4 \u2264 x \u2264 5 ? -3//2*x^2 + 13//1*x - 55//2 : 0//1*one(x)\nB\u2087 = x -> 4 \u2264 x \u2264 5 ? 1//1*x^2 - 8//1*x + 16//1 : 0//1*one(x)\n# 1st derivatives\nB\u2081\u2032 = x -> 0 \u2264 x < 1 ? 2//1*x - 2//1 : 0//1*one(x)\nB\u2082\u2032 = x -> 0 \u2264 x < 1 ? -3//1*x + 2//1 :\n           1 \u2264 x < 2 ?  1//1*x - 2//1 : 0//1*one(x)\nB\u2083\u2032 = x -> 0 \u2264 x < 1 ?  1//1*x        :\n           1 \u2264 x < 2 ? -2//1*x + 3//1 :\n           2 \u2264 x < 3 ?  1//1*x - 3//1 : 0//1*one(x)\nB\u2084\u2032 = x -> 1 \u2264 x < 2 ?  1//1*x - 1//1 :\n           2 \u2264 x < 3 ? -2//1*x + 5//1 :\n           3 \u2264 x < 4 ?  1//1*x - 4//1 : 0//1*one(x)\nB\u2085\u2032 = x -> 2 \u2264 x < 3 ?  1//1*x - 2//1 :\n           3 \u2264 x < 4 ? -2//1*x + 7//1 :\n           4 \u2264 x \u2264 5 ?  1//1*x - 5//1 : 0//1*one(x)\nB\u2086\u2032 = x -> 3 \u2264 x < 4 ?  1//1*x -  3//1 :\n           4 \u2264 x \u2264 5 ? -3//1*x + 13//1 : 0//1*one(x)\nB\u2087\u2032 = x -> 4 \u2264 x \u2264 5 ? 2//1*x - 8//1 : 0//1*one(x)\n# 2nd derivatives\nB\u2081\u2032\u2032 = x -> 0 \u2264 x < 1 ? 2//1*one(x) : 0//1*one(x)\nB\u2082\u2032\u2032 = x -> 0 \u2264 x < 1 ? -3//1*one(x) :\n            1 \u2264 x < 2 ?  1//1*one(x) : 0//1*one(x)\nB\u2083\u2032\u2032 = x -> 0 \u2264 x < 1 ?  1//1*one(x) :\n            1 \u2264 x < 2 ? -2//1*one(x) :\n            2 \u2264 x < 3 ?  1//1*one(x) : 0//1*one(x)\nB\u2084\u2032\u2032 = x -> 1 \u2264 x < 2 ?  1//1*one(x) :\n            2 \u2264 x < 3 ? -2//1*one(x) :\n            3 \u2264 x < 4 ?  1//1*one(x) : 0//1*one(x)\nB\u2085\u2032\u2032 = x -> 2 \u2264 x < 3 ?  1//1*one(x) :\n            3 \u2264 x < 4 ? -2//1*one(x) :\n            4 \u2264 x \u2264 5 ?  1//1*one(x) : 0//1*one(x)\nB\u2086\u2032\u2032 = x -> 3 \u2264 x < 4 ?  1//1*one(x) :\n            4 \u2264 x \u2264 5 ? -3//1*one(x) : 0//1*one(x)\nB\u2087\u2032\u2032 = x -> 4 \u2264 x \u2264 5 ? 2//1*one(x) : 0//1*one(x)\n\nb3_exact = [B\u2081 B\u2081\u2032 B\u2081\u2032\u2032; B\u2082 B\u2082\u2032 B\u2082\u2032\u2032; B\u2083 B\u2083\u2032 B\u2083\u2032\u2032; B\u2084 B\u2084\u2032 B\u2084\u2032\u2032; B\u2085 B\u2085\u2032 B\u2085\u2032\u2032; B\u2086 B\u2086\u2032 B\u2086\u2032\u2032; B\u2087 B\u2087\u2032 B\u2087\u2032\u2032]\n\nb4 = BSplineBasis(4, Int128[0,1,2,3,4,5])\n\nB\u2081 = x -> 0 \u2264 x < 1 ? -1//1*x^3 + 3//1*x^2 - 3//1*x + 1//1 : 0//1*one(x)\nB\u2082 = x -> 0 \u2264 x < 1 ?  7//4*x^3 - 9//2*x^2 + 3//1*x        :\n          1 \u2264 x < 2 ? -1//4*x^3 + 3//2*x^2 - 3//1*x + 2//1 : 0//1*one(x)\nB\u2083 = x -> 0 \u2264 x < 1 ? -11//12*x^3 + 3//2*x^2                 :\n          1 \u2264 x < 2 ?   7//12*x^3 - 3//1*x^2 + 9//2*x - 3//2 :\n          2 \u2264 x < 3 ?   -1//6*x^3 + 3//2*x^2 - 9//2*x + 9//2 : 0//1*one(x)\nB\u2084 = x -> 0 \u2264 x < 1 ?  1//6*x^3                      :\n          1 \u2264 x < 2 ? -1//2*x^3 + 2//1*x^2 -  2//1*x +  2//3 :\n          2 \u2264 x < 3 ?  1//2*x^3 - 4//1*x^2 + 10//1*x - 22//3 :\n          3 \u2264 x < 4 ? -1//6*x^3 + 2//1*x^2 -  8//1*x + 32//3 : 0//1*one(x)\nB\u2085 = x -> 1 \u2264 x < 2 ?  1//6*x^3 -  1//2*x^2 +  1//2*x -   1//6 :\n          2 \u2264 x < 3 ? -1//2*x^3 +  7//2*x^2 - 15//2*x +  31//6 :\n          3 \u2264 x < 4 ?  1//2*x^3 - 11//2*x^2 + 39//2*x - 131//6 :\n          4 \u2264 x \u2264 5 ? -1//6*x^3 +  5//2*x^2 - 25//2*x + 125//6 : 0//1*one(x)\nB\u2086 = x -> 2 \u2264 x < 3 ?   1//6*x^3 -  1//1*x^2 +   2//1*x -    4//3 :\n          3 \u2264 x < 4 ? -7//12*x^3 + 23//4*x^2 -  73//4*x + 227//12 :\n          4 \u2264 x \u2264 5 ? 11//12*x^3 - 49//4*x^2 + 215//4*x - 925//12 : 0//1*one(x)\nB\u2087 = x -> 3 \u2264 x < 4 ?  1//4*x^3 -  9//4*x^2 +  27//4*x -  27//4 :\n          4 \u2264 x \u2264 5 ? -7//4*x^3 + 87//4*x^2 - 357//4*x + 485//4 : 0//1*one(x)\nB\u2088 = x -> 4 \u2264 x \u2264 5 ? 1//1*x^3 - 12//1*x^2 + 48//1*x - 64//1 : 0//1*one(x)\n# 1st derivatives\nB\u2081\u2032 = x -> 0 \u2264 x < 1 ? -3//1*x^2 + 6//1*x - 3//1 : 0//1*one(x)\nB\u2082\u2032 = x -> 0 \u2264 x < 1 ? 21//4*x^2 - 9//1*x + 3//1 :\n           1 \u2264 x < 2 ? -3//4*x^2 + 3//1*x - 3//1 : 0//1*one(x)\nB\u2083\u2032 = x -> 0 \u2264 x < 1 ? -11//4*x^2 + 3//1*x        :\n           1 \u2264 x < 2 ?   7//4*x^2 - 6//1*x + 9//2 :\n           2 \u2264 x < 3 ?  -1//2*x^2 + 3//1*x - 9//2 : 0//1*one(x)\nB\u2084\u2032 = x -> 0 \u2264 x < 1 ?  1//2*x^2                  :\n           1 \u2264 x < 2 ? -3//2*x^2 + 4//1*x -  2//1 :\n           2 \u2264 x < 3 ?  3//2*x^2 - 8//1*x + 10//1 :\n           3 \u2264 x < 4 ? -1//2*x^2 + 4//1*x -  8//1 : 0//1*one(x)\nB\u2085\u2032 = x -> 1 \u2264 x < 2 ?  1//2*x^2 -  1//1*x +  1//2 :\n           2 \u2264 x < 3 ? -3//2*x^2 +  7//1*x - 15//2 :\n           3 \u2264 x < 4 ?  3//2*x^2 - 11//1*x + 39//2 :\n           4 \u2264 x \u2264 5 ? -1//2*x^2 +  5//1*x - 25//2 : 0//1*one(x)\nB\u2086\u2032 = x -> 2 \u2264 x < 3 ?  1//2*x^2 -  2//1*x +   2//1 :\n           3 \u2264 x < 4 ? -7//4*x^2 + 23//2*x -  73//4 :\n           4 \u2264 x \u2264 5 ? 11//4*x^2 - 49//2*x + 215//4 : 0//1*one(x)\nB\u2087\u2032 = x -> 3 \u2264 x < 4 ?   3//4*x^2 -  9//2*x +  27//4 :\n           4 \u2264 x \u2264 5 ? -21//4*x^2 + 87//2*x - 357//4 : 0//1*one(x)\nB\u2088\u2032 = x -> 4 \u2264 x \u2264 5 ? 3//1*x^2 - 24//1*x + 48//1 : 0//1*one(x)\n# 2nd derivatives\nB\u2081\u2032\u2032 = x -> 0 \u2264 x < 1 ? -6//1*x + 6//1 : 0//1*one(x)\nB\u2082\u2032\u2032 = x -> 0 \u2264 x < 1 ? 21//2*x - 9//1 :\n            1 \u2264 x < 2 ? -3//2*x + 3//1 : 0//1*one(x)\nB\u2083\u2032\u2032 = x -> 0 \u2264 x < 1 ? -11//2*x + 3//1 :\n            1 \u2264 x < 2 ?   7//2*x - 6//1 :\n            2 \u2264 x < 3 ?  -1//1*x + 3//1 : 0//1*one(x)\nB\u2084\u2032\u2032 = x -> 0 \u2264 x < 1 ?  1//1*x        :\n            1 \u2264 x < 2 ? -3//1*x + 4//1 :\n            2 \u2264 x < 3 ?  3//1*x - 8//1 :\n            3 \u2264 x < 4 ? -1//1*x + 4//1 : 0//1*one(x)\nB\u2085\u2032\u2032 = x -> 1 \u2264 x < 2 ?  1//1*x -  1//1 :\n            2 \u2264 x < 3 ? -3//1*x +  7//1 :\n            3 \u2264 x < 4 ?  3//1*x - 11//1 :\n            4 \u2264 x \u2264 5 ? -1//1*x +  5//1 : 0//1*one(x)\nB\u2086\u2032\u2032 = x -> 2 \u2264 x < 3 ?  1//1*x -  2//1 :\n            3 \u2264 x < 4 ? -7//2*x + 23//2 :\n            4 \u2264 x \u2264 5 ? 11//2*x - 49//2 : 0//1*one(x)\nB\u2087\u2032\u2032 = x -> 3 \u2264 x < 4 ?   3//2*x -  9//2 :\n            4 \u2264 x \u2264 5 ? -21//2*x + 87//2 : 0//1*one(x)\nB\u2088\u2032\u2032 = x -> 4 \u2264 x \u2264 5 ? 6//1*x - 24//1 : 0//1*one(x)\n# 3rd derivatives\nB\u2081\u2032\u2032\u2032 = x -> 0 \u2264 x < 1 ? -6//1 : 0//1*one(x)\nB\u2082\u2032\u2032\u2032 = x -> 0 \u2264 x < 1 ? 21//2 :\n             1 \u2264 x < 2 ? -3//2 : 0//1*one(x)\nB\u2083\u2032\u2032\u2032 = x -> 0 \u2264 x < 1 ? -11//2 :\n             1 \u2264 x < 2 ?   7//2 :\n             2 \u2264 x < 3 ?  -1//1 : 0//1*one(x)\nB\u2084\u2032\u2032\u2032 = x -> 0 \u2264 x < 1 ?  1//1 :\n             1 \u2264 x < 2 ? -3//1 :\n             2 \u2264 x < 3 ?  3//1 :\n             3 \u2264 x < 4 ? -1//1 : 0//1*one(x)\nB\u2085\u2032\u2032\u2032 = x -> 1 \u2264 x < 2 ?  1//1 :\n             2 \u2264 x < 3 ? -3//1 :\n             3 \u2264 x < 4 ?  3//1 :\n             4 \u2264 x \u2264 5 ? -1//1 : 0//1*one(x)\nB\u2086\u2032\u2032\u2032 = x -> 2 \u2264 x < 3 ?  1//1 :\n             3 \u2264 x < 4 ? -7//2 :\n             4 \u2264 x \u2264 5 ? 11//2 : 0//1*one(x)\nB\u2087\u2032\u2032\u2032 = x -> 3 \u2264 x < 4 ?   3//2 :\n             4 \u2264 x \u2264 5 ? -21//2 : 0//1*one(x)\nB\u2088\u2032\u2032\u2032 = x -> 4 \u2264 x \u2264 5 ? 6//1 : 0//1*one(x)\n\nb4_exact = [B\u2081 B\u2081\u2032 B\u2081\u2032\u2032 B\u2081\u2032\u2032\u2032; B\u2082 B\u2082\u2032 B\u2082\u2032\u2032 B\u2082\u2032\u2032\u2032; B\u2083 B\u2083\u2032 B\u2083\u2032\u2032 B\u2083\u2032\u2032\u2032; B\u2084 B\u2084\u2032 B\u2084\u2032\u2032 B\u2084\u2032\u2032\u2032;\n            B\u2085 B\u2085\u2032 B\u2085\u2032\u2032 B\u2085\u2032\u2032\u2032; B\u2086 B\u2086\u2032 B\u2086\u2032\u2032 B\u2086\u2032\u2032\u2032; B\u2087 B\u2087\u2032 B\u2087\u2032\u2032 B\u2087\u2032\u2032\u2032; B\u2088 B\u2088\u2032 B\u2088\u2032\u2032 B\u2088\u2032\u2032\u2032]\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\u2081 = x -> -5.0 \u2264 x < -3.5 ? 4//9*x^2 + 28//9*x + 49//9 : 0//1*one(x)\nB\u2082 = x -> -5.0 \u2264 x < -3.5 ? -43//63*x^2 - 346//63*x - 655//63 :\n          -3.5 \u2264 x < -2.2 ?  25//91*x^2 + 110//91*x + 121//91 : 0//1*one(x)\nB\u2083 = x -> -5.0 \u2264 x < -3.5 ?     5//21*x^2 +    50//21*x +   125//21 :\n          -3.5 \u2264 x < -2.2 ? -365//819*x^2 - 1970//819*x - 1985//819 :\n          -2.2 \u2264 x <  1.0 ?     5//72*x^2 -     5//36*x +     5//72 : 0//1*one(x)\nB\u2084 = x -> -3.5 \u2264 x < -2.2 ?    20//117*x^2 + 140//117*x +  245//117 :\n          -2.2 \u2264 x <  1.0 ? -145//1008*x^2 -  95//504*x + 575//1008 :\n           1.0 \u2264 x <  2.0 ?      5//21*x^2 -   20//21*x +    20//21 : 0//1*one(x)\nB\u2085 = x -> -2.2 \u2264 x < 1.0 ?   25//336*x^2 +  55//168*x + 121//336 :\n           1.0 \u2264 x < 2.0 ? -170//273*x^2 + 470//273*x -  92//273 :\n           2.0 \u2264 x \u2264 3.6 ?   25//104*x^2 -   45//26*x +   81//26 : 0//1*one(x)\nB\u2086 = x ->  1.0 \u2264 x < 2.0 ?     5//13*x^2 -   10//13*x +    5//13 :\n           2.0 \u2264 x \u2264 3.6 ? -525//832*x^2 + 685//208*x - 765//208 : 0//1*one(x)\nB\u2087 = x ->  2.0 \u2264 x \u2264 3.6 ? 25//64*x^2 - 25//16*x + 25//16 : 0//1*one(x)\n# 1st derivatives\nB\u2081\u2032 = x -> -5.0 \u2264 x < -3.5 ? 8//9*x + 28//9 : 0//1*one(x)\nB\u2082\u2032 = x -> -5.0 \u2264 x < -3.5 ? -86//63*x - 346//63 :\n           -3.5 \u2264 x < -2.2 ?  50//91*x + 110//91 : 0//1*one(x)\nB\u2083\u2032 = x -> -5.0 \u2264 x < -3.5 ?    10//21*x +    50//21 :\n           -3.5 \u2264 x < -2.2 ? -730//819*x - 1970//819 :\n           -2.2 \u2264 x <  1.0 ?     5//36*x -     5//36 : 0//1*one(x)\nB\u2084\u2032 = x -> -3.5 \u2264 x < -2.2 ?   40//117*x + 140//117 :\n           -2.2 \u2264 x <  1.0 ? -145//504*x -  95//504 :\n            1.0 \u2264 x <  2.0 ?    10//21*x -   20//21 : 0//1*one(x)\nB\u2085\u2032 = x -> -2.2 \u2264 x < 1.0 ?   25//168*x +  55//168 :\n            1.0 \u2264 x < 2.0 ? -340//273*x + 470//273 :\n            2.0 \u2264 x \u2264 3.6 ?    25//52*x -   45//26 : 0//1*one(x)\nB\u2086\u2032 = x ->  1.0 \u2264 x < 2.0 ?    10//13*x -   10//13 :\n            2.0 \u2264 x \u2264 3.6 ? -525//416*x + 685//208 : 0//1*one(x)\nB\u2087\u2032 = x ->  2.0 \u2264 x \u2264 3.6 ? 25//32*x - 25//16 : 0//1*one(x)\n# 2nd derivatives\nB\u2081\u2032\u2032 = x -> -5.0 \u2264 x < -3.5 ? 8//9*one(x) : 0//1*one(x)\nB\u2082\u2032\u2032 = x -> -5.0 \u2264 x < -3.5 ? -86//63*one(x) :\n            -3.5 \u2264 x < -2.2 ?  50//91*one(x) : 0//1*one(x)\nB\u2083\u2032\u2032 = x -> -5.0 \u2264 x < -3.5 ?    10//21*one(x) :\n            -3.5 \u2264 x < -2.2 ? -730//819*one(x) :\n            -2.2 \u2264 x <  1.0 ?     5//36*one(x) : 0//1*one(x)\nB\u2084\u2032\u2032 = x -> -3.5 \u2264 x < -2.2 ?   40//117*one(x) :\n            -2.2 \u2264 x <  1.0 ? -145//504*one(x) :\n             1.0 \u2264 x <  2.0 ?    10//21*one(x) : 0//1*one(x)\nB\u2085\u2032\u2032 = x -> -2.2 \u2264 x < 1.0 ?   25//168*one(x) :\n             1.0 \u2264 x < 2.0 ? -340//273*one(x) :\n             2.0 \u2264 x \u2264 3.6 ?    25//52*one(x) : 0//1*one(x)\nB\u2086\u2032\u2032 = x ->  1.0 \u2264 x < 2.0 ?    10//13*one(x) :\n             2.0 \u2264 x \u2264 3.6 ? -525//416*one(x) : 0//1*one(x)\nB\u2087\u2032\u2032 = x ->  2.0 \u2264 x \u2264 3.6 ? 25//32*one(x) : 0//1*one(x)\n\nb5_exact = [B\u2081 B\u2081\u2032 B\u2081\u2032\u2032; B\u2082 B\u2082\u2032 B\u2082\u2032\u2032; B\u2083 B\u2083\u2032 B\u2083\u2032\u2032; B\u2084 B\u2084\u2032 B\u2084\u2032\u2032; B\u2085 B\u2085\u2032 B\u2085\u2032\u2032; B\u2086 B\u2086\u2032 B\u2086\u2032\u2032; B\u2087 B\u2087\u2032 B\u2087\u2032\u2032]\n\nb6 = BSplineBasis(4, Rational{Int64}[-5//1, -7//2, -11//5, 1//1, 2//1, 18//5])\n\nB\u2081 = x ->  -5//1 \u2264 x <  -7//2 ? -8//27*x^3 - 28//9*x^2 - 98//9*x - 343//27 : 0//1*one(x)\nB\u2082 = x ->  -5//1 \u2264 x <  -7//2 ? 1429//2646*x^3 + 5339//882*x^2 + 19429//882*x + 69635//2646 :\n           -7//2 \u2264 x < -11//5 ? -125//1274*x^3 - 825//1274*x^2 - 1815//1274*x -  1331//1274 : 0//1*one(x)\nB\u2083 = x ->  -5//1 \u2264 x <  -7//2 ?   -125//441*x^3 -   520//147*x^2 -   2075//147*x -    7750//441 :\n           -7//2 \u2264 x < -11//5 ? 2965//17199*x^3 + 7160//5733*x^2 + 15115//5733*x + 33890//17199 :\n          -11//5 \u2264 x <   1//1 ?     -5//432*x^3 +     5//144*x^2 -      5//144*x +       5//432 : 0//1*one(x)\nB\u2084 = x ->  -5//1 \u2264 x <  -7//2 ?       5//126*x^3 +       25//42*x^2 +      125//42*x +     625//126 :\n           -7//2 \u2264 x < -11//5 ? -5695//54054*x^3 - 16715//18018*x^2 - 42415//18018*x - 68015//54054 :\n          -11//5 \u2264 x <   1//1 ?  1255//33264*x^3 +   185//11088*x^2 -  3065//11088*x +  8825//33264 :\n            1//1 \u2264 x <   2//1 ?     -10//231*x^3 +       20//77*x^2 -       40//77*x +      80//231 : 0//1*one(x)\nB\u2085 = x ->  -7//2 \u2264 x < -11//5 ?       40//1287*x^3 +      140//429*x^2 +      490//429*x +     1715//1287 :\n          -11//5 \u2264 x <   1//1 ? -12535//321552*x^3 - 14585//107184*x^2 + 13385//107184*x + 188599//321552 :\n            1//1 \u2264 x <   2//1 ?   13120//87087*x^3 -  20465//29029*x^2 +  20140//29029*x +   34564//87087 :\n            2//1 \u2264 x \u2264  18//5 ?     -125//3016*x^3 +     675//1508*x^2 -     1215//754*x +       729//377 : 0//1*one(x)\nB\u2086 = x -> -11//5 \u2264 x <   1//1 ?      125//9744*x^3 +      275//3248*x^2 +     605//3248*x +    1331//9744 :\n            1//1 \u2264 x <   2//1 ? -26275//102921*x^3 +   30500//34307*x^2 -  21205//34307*x + 41654//102921 :\n            2//1 \u2264 x \u2264  18//5 ?  89125//313664*x^3 - 368175//156832*x^2 + 459135//78416*x - 153333//39208 : 0//1*one(x)\nB\u2087 = x ->   1//1 \u2264 x <   2//1 ?       25//169*x^3 -       75//169*x^2 +       75//169*x -      25//169 :\n            2//1 \u2264 x <  18//5 ? -42125//86528*x^3 + 145575//43264*x^2 - 155175//21632*x + 53325//10816 : 0//1*one(x)\nB\u2088 = x ->   2//1 \u2264 x \u2264  18//5 ? 125//512*x^3 - 375//256*x^2 + 375//128*x - 125//64 : 0//1*one(x)\n# 1st derivatives\nB\u2081\u2032 = x ->  -5//1 \u2264 x <  -7//2 ? -8//9*x^2 - 56//9*x - 98//9 : 0//1*one(x)\nB\u2082\u2032 = x ->  -5//1 \u2264 x <  -7//2 ?  1429//882*x^2 + 5339//441*x + 19429//882 :\n            -7//2 \u2264 x < -11//5 ? -375//1274*x^2 -  825//637*x - 1815//1274 : 0//1*one(x)\nB\u2083\u2032 = x ->  -5//1 \u2264 x <  -7//2 ?  -125//147*x^2 -   1040//147*x -   2075//147 :\n            -7//2 \u2264 x < -11//5 ? 2965//5733*x^2 + 14320//5733*x + 15115//5733 :\n           -11//5 \u2264 x <   1//1 ?    -5//144*x^2 +       5//72*x -      5//144 : 0//1*one(x)\nB\u2084\u2032 = x ->  -5//1 \u2264 x <  -7//2 ?        5//42*x^2 +      25//21*x +      125//42 :\n            -7//2 \u2264 x < -11//5 ? -5695//18018*x^2 - 16715//9009*x - 42415//18018 :\n           -11//5 \u2264 x <   1//1 ?  1255//11088*x^2 +   185//5544*x -  3065//11088 :\n             1//1 \u2264 x <   2//1 ?      -10//77*x^2 +      40//77*x -       40//77 : 0//1*one(x)\nB\u2085\u2032 = x ->  -7//2 \u2264 x < -11//5 ?        40//429*x^2 +     280//429*x +      490//429 :\n           -11//5 \u2264 x <   1//1 ? -12535//107184*x^2 - 14585//53592*x + 13385//107184 :\n             1//1 \u2264 x <   2//1 ?   13120//29029*x^2 - 40930//29029*x +  20140//29029 :\n             2//1 \u2264 x \u2264  18//5 ?     -375//3016*x^2 +     675//754*x -     1215//754 : 0//1*one(x)\nB\u2086\u2032 = x -> -11//5 \u2264 x <   1//1 ?      125//3248*x^2 +     275//1624*x +     605//3248 :\n             1//1 \u2264 x <   2//1 ?  -26275//34307*x^2 +  61000//34307*x -  21205//34307 :\n             2//1 \u2264 x \u2264  18//5 ? 267375//313664*x^2 - 368175//78416*x + 459135//78416 : 0//1*one(x)\nB\u2087\u2032 = x ->   1//1 \u2264 x <   2//1 ?        75//169*x^2 -      150//169*x +       75//169 :\n             2//1 \u2264 x \u2264  18//5 ? -126375//86528*x^2 + 145575//21632*x - 155175//21632 : 0//1*one(x)\nB\u2088\u2032 = x ->   2//1 \u2264 x \u2264  18//5 ? 375//512*x^2 - 375//128*x + 375//128 : 0//1*one(x)\n# 2nd derivatives\nB\u2081\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ? -16//9*x - 56//9 : 0//1*one(x)\nB\u2082\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ? 1429//441*x + 5339//441 :\n             -7//2 \u2264 x < -11//5 ? -375//637*x -  825//637 : 0//1*one(x)\nB\u2083\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ?  -250//147*x -   1040//147 :\n             -7//2 \u2264 x < -11//5 ? 5930//5733*x + 14320//5733 :\n            -11//5 \u2264 x <   1//1 ?     -5//72*x +       5//72 : 0//1*one(x)\nB\u2084\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ?       5//21*x +      25//21 :\n             -7//2 \u2264 x < -11//5 ? -5695//9009*x - 16715//9009 :\n            -11//5 \u2264 x <   1//1 ?  1255//5544*x +   185//5544 :\n              1//1 \u2264 x <   2//1 ?     -20//77*x +      40//77 : 0//1*one(x)\nB\u2085\u2032\u2032 = x ->  -7//2 \u2264 x < -11//5 ?       80//429*x +     280//429 :\n            -11//5 \u2264 x <   1//1 ? -12535//53592*x - 14585//53592 :\n              1//1 \u2264 x <   2//1 ?  26240//29029*x - 40930//29029 :\n              2//1 \u2264 x \u2264  18//5 ?    -375//1508*x +     675//754 : 0//1*one(x)\nB\u2086\u2032\u2032 = x -> -11//5 \u2264 x <   1//1 ?      125//1624*x +     275//1624 :\n              1//1 \u2264 x <   2//1 ?  -52550//34307*x +  61000//34307 :\n              2//1 \u2264 x \u2264  18//5 ? 267375//156832*x - 368175//78416 : 0//1*one(x)\nB\u2087\u2032\u2032 = x ->   1//1 \u2264 x <   2//1 ?       150//169*x -      150//169 :\n              2//1 \u2264 x \u2264  18//5 ? -126375//43264*x + 145575//21632 : 0//1*one(x)\nB\u2088\u2032\u2032 = x ->   2//1 \u2264 x \u2264  18//5 ? 375//256*x - 375//128 : 0//1*one(x)\n# 3rd derivative\nB\u2081\u2032\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ? -16//9*one(x) : 0//1*one(x)\nB\u2082\u2032\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ? 1429//441*one(x) :\n              -7//2 \u2264 x < -11//5 ? -375//637*one(x) : 0//1*one(x)\nB\u2083\u2032\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ?  -250//147*one(x) :\n              -7//2 \u2264 x < -11//5 ? 5930//5733*one(x) :\n             -11//5 \u2264 x <   1//1 ?     -5//72*one(x) : 0//1*one(x)\nB\u2084\u2032\u2032\u2032 = x ->  -5//1 \u2264 x <  -7//2 ?       5//21*one(x) :\n              -7//2 \u2264 x < -11//5 ? -5695//9009*one(x) :\n             -11//5 \u2264 x <   1//1 ?  1255//5544*one(x) :\n               1//1 \u2264 x <   2//1 ?     -20//77*one(x) : 0//1*one(x)\nB\u2085\u2032\u2032\u2032 = x ->  -7//2 \u2264 x < -11//5 ?       80//429*one(x) :\n             -11//5 \u2264 x <   1//1 ? -12535//53592*one(x) :\n               1//1 \u2264 x <   2//1 ?  26240//29029*one(x) :\n               2//1 \u2264 x \u2264  18//5 ?    -375//1508*one(x) : 0//1*one(x)\nB\u2086\u2032\u2032\u2032 = x -> -11//5 \u2264 x <   1//1 ?      125//1624*one(x) :\n               1//1 \u2264 x <   2//1 ?  -52550//34307*one(x) :\n               2//1 \u2264 x \u2264  18//5 ? 267375//156832*one(x) : 0//1*one(x)\nB\u2087\u2032\u2032\u2032 = x ->   1//1 \u2264 x <   2//1 ?       150//169*one(x) :\n               2//1 \u2264 x \u2264  18//5 ? -126375//43264*one(x) : 0//1*one(x)\nB\u2088\u2032\u2032\u2032 = x ->   2//1 \u2264 x \u2264  18//5 ? 375//256*one(x) : 0//1*one(x)\n\nb6_exact = [B\u2081 B\u2081\u2032 B\u2081\u2032\u2032 B\u2081\u2032\u2032\u2032; B\u2082 B\u2082\u2032 B\u2082\u2032\u2032 B\u2082\u2032\u2032\u2032; B\u2083 B\u2083\u2032 B\u2083\u2032\u2032 B\u2083\u2032\u2032\u2032; B\u2084 B\u2084\u2032 B\u2084\u2032\u2032 B\u2084\u2032\u2032\u2032;\n            B\u2085 B\u2085\u2032 B\u2085\u2032\u2032 B\u2085\u2032\u2032\u2032; B\u2086 B\u2086\u2032 B\u2086\u2032\u2032 B\u2086\u2032\u2032\u2032; B\u2087 B\u2087\u2032 B\u2087\u2032\u2032 B\u2087\u2032\u2032\u2032; B\u2088 B\u2088\u2032 B\u2088\u2032\u2032 B\u2088\u2032\u2032\u2032]\n\nb7 = BSplineBasis(3, Int8[-6,-4,-2,0,0,1,2])\n\nB\u2081 = x -> -6 \u2264 x < -4 ? 1//4*x^2 + 2//1*x + 4//1 : 0//1*one(x)\nB\u2082 = x -> -6 \u2264 x < -4 ? -3//8*x^2 - 7//2*x - 15//2 :\n          -4 \u2264 x < -2 ?  1//8*x^2 + 1//2*x +  1//2 : 0//1*one(x)\nB\u2083 = x -> -6 \u2264 x < -4 ?  1//8*x^2 + 3//2*x + 9//2 :\n          -4 \u2264 x < -2 ? -1//4*x^2 - 3//2*x - 3//2 :\n          -2 \u2264 x <  0 ?  1//8*x^2                 : 0//1*one(x)\nB\u2084 = x -> -4 \u2264 x < -2 ?  1//8*x^2 + 1//1*x + 2//1 :\n          -2 \u2264 x <  0 ? -3//8*x^2 - 1//1*x        : 0//1*one(x)\nB\u2085 = x -> -2 \u2264 x <  0 ? 1//4*x^2 + 1//1*x + 1//1 :\n           0 \u2264 x <  1 ? 1//1*x^2 - 2//1*x + 1//1 : 0//1*one(x)\nB\u2086 = x ->  0 \u2264 x <  1 ? -3//2*x^2 + 2//1*x        :\n           1 \u2264 x \u2264  2 ?  1//2*x^2 - 2//1*x + 2//1 : 0//1*one(x)\nB\u2087 = x ->  0 \u2264 x <  1 ?  1//2*x^2                 :\n           1 \u2264 x \u2264  2 ? -3//2*x^2 + 4//1*x - 2//1 : 0//1*one(x)\nB\u2088 = x ->  1 \u2264 x \u2264  2 ? 1//1*x^2 - 2//1*x + 1//1 : 0//1*one(x)\n# 1st derivatives\nB\u2081\u2032 = x -> -6 \u2264 x < -4 ? 1//2*x + 2//1 : 0//1*one(x)\nB\u2082\u2032 = x -> -6 \u2264 x < -4 ? -3//4*x - 7//2 :\n           -4 \u2264 x < -2 ?  1//4*x + 1//2 : 0//1*one(x)\nB\u2083\u2032 = x -> -6 \u2264 x < -4 ?  1//4*x + 3//2 :\n           -4 \u2264 x < -2 ? -1//2*x - 3//2 :\n           -2 \u2264 x <  0 ?  1//4*x        : 0//1*one(x)\nB\u2084\u2032 = x -> -4 \u2264 x < -2 ?  1//4*x + 1//1 :\n           -2 \u2264 x <  0 ? -3//4*x - 1//1 : 0//1*one(x)\nB\u2085\u2032 = x -> -2 \u2264 x <  0 ? 1//2*x + 1//1 :\n            0 \u2264 x <  1 ? 2//1*x - 2//1 : 0//1*one(x)\nB\u2086\u2032 = x ->  0 \u2264 x <  1 ? -3//1*x + 2//1 :\n            1 \u2264 x \u2264  2 ?  1//1*x - 2//1 : 0//1*one(x)\nB\u2087\u2032 = x ->  0 \u2264 x <  1 ?  1//1*x        :\n            1 \u2264 x \u2264  2 ? -3//1*x + 4//1 : 0//1*one(x)\nB\u2088\u2032 = x ->  1 \u2264 x \u2264  2 ? 2//1*x - 2//1 : 0//1*one(x)\n# 2nd derivatives\nB\u2081\u2032\u2032 = x -> -6 \u2264 x < -4 ? 1//2*one(x) : 0//1*one(x)\nB\u2082\u2032\u2032 = x -> -6 \u2264 x < -4 ? -3//4*one(x) :\n            -4 \u2264 x < -2 ?  1//4*one(x) : 0//1*one(x)\nB\u2083\u2032\u2032 = x -> -6 \u2264 x < -4 ?  1//4*one(x) :\n            -4 \u2264 x < -2 ? -1//2*one(x) :\n            -2 \u2264 x <  0 ?  1//4*one(x) : 0//1*one(x)\nB\u2084\u2032\u2032 = x -> -4 \u2264 x < -2 ?  1//4*one(x) :\n            -2 \u2264 x <  0 ? -3//4*one(x) : 0//1*one(x)\nB\u2085\u2032\u2032 = x -> -2 \u2264 x <  0 ? 1//2*one(x) :\n             0 \u2264 x <  1 ? 2//1*one(x) : 0//1*one(x)\nB\u2086\u2032\u2032 = x ->  0 \u2264 x <  1 ? -3//1*one(x) :\n             1 \u2264 x \u2264  2 ?  1//1*one(x) : 0//1*one(x)\nB\u2087\u2032\u2032 = x ->  0 \u2264 x <  1 ?  1//1*one(x) :\n             1 \u2264 x \u2264  2 ? -3//1*one(x) : 0//1*one(x)\nB\u2088\u2032\u2032 = x ->  1 \u2264 x \u2264  2 ? 2//1*one(x) : 0//1*one(x)\n\nb7_exact = [B\u2081 B\u2081\u2032 B\u2081\u2032\u2032; B\u2082 B\u2082\u2032 B\u2082\u2032\u2032; B\u2083 B\u2083\u2032 B\u2083\u2032\u2032; B\u2084 B\u2084\u2032 B\u2084\u2032\u2032; B\u2085 B\u2085\u2032 B\u2085\u2032\u2032; B\u2086 B\u2086\u2032 B\u2086\u2032\u2032; B\u2087 B\u2087\u2032 B\u2087\u2032\u2032; B\u2088 B\u2088\u2032 B\u2088\u2032\u2032]\n\n# Compare arrays element-wise, and use a non-zero atol\n\u2248\u2091\u2097(x::AbstractArray, y::AbstractArray) = all(x .\u2248\u2091\u2097 y)\n\u2248\u2091\u2097(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": "let\n    n = 5\n    tf = 5\n    t = collect(0:(tf/n):tf)\n    f(t) = sin.(t)\n    fdot(t) = cos.(t)\n\n    x = f(t)\n    spline = CubicSpline(t,x)\n    interpolate(spline, t[1])\n    deriv(spline, t[1])\n    hess(spline, t[1])\n    interpolate(spline, [t[1], t[end]])\n    deriv(spline, [t[1], t[end]])\n    hess(spline, [t[1], t[end]])\n\n    dt = 1.0\n    @test extrapolate(spline, t[end]+dt, 0)[1] == interpolate(spline, t[end])\n    @test extrapolate(spline, t[end]+dt, 1)[1] == interpolate(spline, t[end]) + deriv(spline, t[end])*dt\n    @test extrapolate(spline, t[1]-dt, 0)[1] == interpolate(spline, t[1])\n    @test extrapolate(spline, t[1]-dt, 1)[1] == interpolate(spline, t[1]) - deriv(spline, t[1])*dt\n\n    xdot = fdot(t)\n    spline2 = CubicSpline(t,x,xdot) # prescribe knot tangents directly\n\n    # plt = plot(t_vec, interpolate(spline, t_vec))\n    # plot!(plt, t_vec, interpolate(spline2, t_vec))\n    # plot!(plt, t_vec, f(t_vec))\n    # plot!(plt, t, x, seriestype=:scatter)\nend\nlet\n    n = 10\n    t = collect(0:(1/10):1)\n    x = sin.(t)\n    y = sin.(t)\n    X = hcat(x,y)\n    spline = ParametricSpline(t,X)\n    interpolate(spline, t[1])\n    deriv(spline, t[1])\n    hess(spline, t[1])\n    interpolate(spline, [t[1], t[end]])\n    deriv(spline, [t[1], t[end]])\n    hess(spline, [t[1], t[end]])\nend\n# test turn rate and tangent rate\nlet\n    # circle in the plane\n    tvec = collect(0:.01:2\u03c0)\n    x = cos.(tvec)\n    y = sin.(tvec)\n    dx = -y\n    dy = x\n    ddx = -x\n    ddy = -y\n    z = zeros(length(tvec))\n    dz = z\n    ddz = z\n    r = collect(hcat(x,y,z))\n    dr = collect(hcat(dx,dy,dz))\n    ddr = collect(hcat(ddx,ddy,ddz))\n    spline = ParametricSpline(tvec,r,dr)\n\n    # @show tangent_rate(spline,0.0)\n    # @show tangent_rate(spline,\u03c0/4)\n    #\n    # tvec2 = (1/2)*(tvec[2:end].+tvec[1:end-1])\n    # pts = interpolate(spline,tvec2)\n    # plt = plot(map(pt->pt[1],pts),map(pt->pt[2],pts),aspect_ratio=:equal)\n    # pts = deriv(spline,tvec2)\n    # plot!(plt,map(pt->pt[1],pts),map(pt->pt[2],pts),aspect_ratio=:equal)\n    # pts = hess(spline,tvec2)\n    # plot(map(pt->pt[1],pts),map(pt->pt[2],pts),aspect_ratio=:equal)\nend\n", "meta": {"hexsha": "11600309d36de43d371b3b42c74f999381dd4583", "size": 2115, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_cubic_splines.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": "test/test_cubic_splines.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": "test/test_cubic_splines.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": 28.5810810811, "max_line_length": 104, "alphanum_fraction": 0.5673758865, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.760089460996039}}
{"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, \u03b3=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    \u2207 = (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] .- \u03b3.*\u2207(xgd[:, i-1])\n        xgd[:, i] ./= norm(xgd[:, i])\n\n        # BiasSEGA\n        s .= randn(n)\n        project!(bsega, dot(s, \u2207(xbias[:, i-1])), s)\n        xbias[:, i] .= xbias[:, i-1] .- \u03b3.*gradient(bsega)\n        xbias[:, i] ./= norm(xbias[:, i])        \n\n        # SEGA\n        project!(sega, 1/n, dot(s, \u2207(xsega[:, i-1])), s)\n        unbias!(sega)\n        xsega[:, i] .= xsega[:, i-1] .- \u03b3.*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": "using Test\n\nusing CompScienceMeshes\nusing BEAST\nusing StaticArrays\n\n\u03c9 = 1.0\n\nl1 = meshsegment(1.0,1/2)\nl2 = meshsegment(1.0,1/4)\n\nidcs = BEAST.interior_and_junction_vertices(l1, boundary(l1))\n@test length(idcs) == 3\n\nlag1 = lagrangec0d1(l1, boundary(l1))\nlag2 = lagrangecxd0(l2)\n\nid = Identity()\nG = assemble(id, lag1, lag2)\nH = assemble(id, lag2, lag1)\n\nGt = [\n    3 1 0 0\n    1 3 3 1\n    0 0 1 3] // 16\n\n@test norm(G-H') \u2248 0.0  atol = sqrt(eps()) #G == H'\n@test norm(G-Gt) \u2248 0.0  atol = sqrt(eps())\n\n# Test whether localoperator and localoperator 2 give the same result\n# for test and basis functions defined on the same mesh.\nid = Identity()\nnc = NCross()\n\n#fn = Pkg.dir(\"BEAST\",\"test\",\"sphere2.in\")\nfn = joinpath(dirname(@__FILE__),\"assets\",\"sphere316.in\")\nm = readmesh(fn)\nrt = raviartthomas(m)\n\nG1 = zeros(ComplexF64, numfunctions(rt), numfunctions(rt))\nBEAST.assemble_local_matched!(id, rt, rt, (v,m,n)->(G1[m,n]+=v))\n\nG2 = zeros(ComplexF64, numfunctions(rt), numfunctions(rt))\nBEAST.assemble_local_mixed!(id, rt, rt, (v,m,n)->(G2[m,n]+=v))\n\n# Test wether the gram matrix assembled works for\n# different but overlapping meshes\nm1 = meshrectangle(1.0,1.0,1.0)\nm2 = translate(m1, point(0.5,0.5,0.0))\nI = Identity()\nx1 = lagrangecxd0(m1)\nx2 = lagrangecxd0(m2)\nG = assemble(I,x1,x2)\n@test sum(G) \u2248 1/4\n", "meta": {"hexsha": "5be2f5142cccc36b319199d188708f2dd55544d3", "size": 1305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gram.jl", "max_stars_repo_name": "UnofficialJuliaMirror/BEAST.jl-bb4162c7-ba94-5a20-af32-d8ec4428bdd1", "max_stars_repo_head_hexsha": "b75fcbc7ce1bc00efeaa7ab689e8b20fd286dfa2", "max_stars_repo_licenses": ["MIT"], "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_gram.jl", "max_issues_repo_name": "UnofficialJuliaMirror/BEAST.jl-bb4162c7-ba94-5a20-af32-d8ec4428bdd1", "max_issues_repo_head_hexsha": "b75fcbc7ce1bc00efeaa7ab689e8b20fd286dfa2", "max_issues_repo_licenses": ["MIT"], "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_gram.jl", "max_forks_repo_name": "UnofficialJuliaMirror/BEAST.jl-bb4162c7-ba94-5a20-af32-d8ec4428bdd1", "max_forks_repo_head_hexsha": "b75fcbc7ce1bc00efeaa7ab689e8b20fd286dfa2", "max_forks_repo_licenses": ["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": 69, "alphanum_fraction": 0.677394636, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7600894537018766}}
{"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 @ [\u00b10.0898, \u22130.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*\u221a(sum(x.^2)/d)) - exp(sum(cos.(c.*x))/d) + a + exp(1)\neggholder(x) = -(x[2]+47)sin(\u221aabs(x[2] + x[1]/2 + 47)) - x[1]sin(\u221aabs(x[1]-x[2]+47))\n\n#Example Benchmarks from papers\n#Audet & Dennis 2006 benchmark one, take x\u2080=[-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\u2080=[0,...,0]\n#soln: -\u221a(3)n @ [-\u221a3,...,-\u221a3]\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# \u2554\u2550\u2561 0a57947c-3a56-11ec-1341-534834850daf\nmd\"\"\"\n# Chapter 1\n## Section 3\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 74555744-e6a7-47bd-96b9-7e8909664f42\nnewton(x -> x^2 - 5., x -> 2. * x, 1., 10e-6)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000a57947c-3a56-11ec-1341-534834850daf\n# \u2560\u25508fcfe29e-049c-4df3-9d4b-325d3f4e171e\n# \u2560\u255074555744-e6a7-47bd-96b9-7e8909664f42\n# \u2560\u255040d3098f-4b1b-4ca1-be89-5eb9a18ef3a8\n# \u2560\u25507d023bfd-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\u2264i[dim]\u2264nttb)\n\t\t\t\tx[i] *= sin((i[dim]-1)*kb)\n\t\t\tend\n\t\t\tif(nt-ntte+1\u2264i[dim]\u2264nt)\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 \u2260 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) \u2260 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) \u00f7 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": "module TestThings\nexport foo, bar\n\ngreet() = print(\"Hello World!\")\n\n@doc raw\"\n    foo(xs::Vector{<:Integer})\n\nreturn the maximum of the values in xs, i.e.\n```math\nfoo(xs) = \\{x \\mid x \\geq y \\quad \\forall y \\in xs\\}\n```\n\"\nfoo(xs::Vector{<:Integer}) = foldl((x,y) -> x > y ? x : y, xs)\n\n@doc raw\"\n    bar(xs::Vector{<:Integer})\nLike [`foo`](@ref) but instead returns the *minimum* of the values in xs, i.e.\n```math\nbar(xs) = \\{x \\mid x \\leq y \\quad \\forall y \\in xs\\}\n```\n\"\nbar(xs::Vector{<:Integer}) = -foo(-xs)\n\n\n@doc raw\"\n    foobar(xs)\nreturns the extrema of `xs`\n\"\n\n@doc raw\"\n    foobar(xs::Vector{<:Integer})\nreturns the extrema of a vector of integers\n\"\nfunction foobar(xs::Vector{<:Integer})\n    if length(xs) == 1\n        x = first(xs)\n        return (x,x)\n    end\n    \n    let T = eltype(xs)\n        foldl(((x1,x2),y) -> (ifelse(x1 > y, y, x1), ifelse(x2 > y, x2, y)), xs, init = (typemax(T), typemin(T)))\n    end\nend\n\n@doc raw\"\n    foobar(xs::Vector{<:Real})\nreturns the extrema of a vector of integers\n\"\nfunction foobar(xs::Vector{<:Real})\n    if length(xs) == 1\n        x = first(xs)\n        return (x,x)\n    end\n    \n    let T = eltype(xs)\n        foldl(((x1,x2),y) -> (ifelse(x1 > y, y, x1), ifelse(x2 > y, x2, y)), xs, init = (typemax(T), typemin(T)))\n    end\nend\n\nend # module\n", "meta": {"hexsha": "1401347d63003b8aff21a7c6d8a8a74bacf81ac6", "size": 1293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestThings.jl", "max_stars_repo_name": "under-Peter/TestThings.jl", "max_stars_repo_head_hexsha": "fec7d90ca332d5e1abd8cdbeb3b94a14d65beb90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TestThings.jl", "max_issues_repo_name": "under-Peter/TestThings.jl", "max_issues_repo_head_hexsha": "fec7d90ca332d5e1abd8cdbeb3b94a14d65beb90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TestThings.jl", "max_forks_repo_name": "under-Peter/TestThings.jl", "max_forks_repo_head_hexsha": "fec7d90ca332d5e1abd8cdbeb3b94a14d65beb90", "max_forks_repo_licenses": ["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.8548387097, "max_line_length": 113, "alphanum_fraction": 0.5668986852, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7600894424313497}}
{"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()\u224820.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\u03b3=1.4 #ratio of specific heats\n\u03c1=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*\u03b3/(\u03b3-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\u03c4=0.001 #time delay\ndscrp[\"Flame\"]=(:flame,(\u03b3,\u03c1,Q02U0,x_ref,n_ref,:n,:\u03c4,n,\u03c4)) #flame dynamics\nR=287.05 # J/(kg*K) specific gas constant (air)\nspeedofsound(x,y,z) = z<0. ? sqrt(\u03b3*R*Tu) : sqrt(\u03b3*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+\u0394) as:\n#\n# f(x0+\u0394)\u2248\u2211_n=0^N f_n(x0)\u0394^n\n\n# Let's consider the time delay `\u03c4`. 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 `\u03c9` w.r.t. `\u03c4` by just\n# typing\nperturb_fast!(sol,L,:\u03c4,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,:\u03c4,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 \"\u03c4==0.00125\" based on the 20th order series expansion.\n\u0394=0.00001\n\u03c9_approx=sol(:\u03c4,\u03c4+\u0394,20)\n\n# Let's compare this value to the true solution:\nL.params[:\u03c4]=\u03c4+\u0394 #change parameter\nsol_exact,nn,flag=householder(L,340*2*pi,maxiter=20,tol=1E-11) #solve again\n\u03c9_exact=sol_exact.params[:\u03c9]\nprintln(\" exact=$(\u03c9_exact/2/pi)  vs  approx=$(\u03c9_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\u03c9_approx=sol(:\u03c4,\u03c4+\u0394,1)\nprintln(\" first-order approx=$(\u03c9_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,:\u03c4,30)\n# and then\n\u03c9_approx=sol(:\u03c4,\u03c4+\u0394,30)\nprintln(\" 30th-order approx=$(\u03c9_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 \u0394 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 \u0394 (the shift from the expansion point) is small. This is right\n# and wrong at the same time. Indeed, to classify \u0394 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 \u0394 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,:\u03c4)\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 `:\u03c4`. 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\u03c9_approx=sol(:\u03c4,\u03c4+r[end]+0.001,20)\nL.params[:\u03c4]=\u03c4+r[end]+0.001\nsol_exact,nn,flag=householder(L,340*2*pi,maxiter=20,tol=1E-11) #solve again\n\u03c9_exact=sol_exact.params[:\u03c9]\nprintln(\" exact=$(\u03c9_exact/2/pi)  vs  approx=$(\u03c9_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\u03c9_approx=sol(:\u03c4,\u03c4+r[end]+0.001,30)\nprintln(\" exact=$(\u03c9_exact/2/pi)  vs  approx=$(\u03c9_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\u00e9 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 \u03c9=\u03c9(\u03c4). 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+\u0394)\u2248\u2211_n=0^N f_n(x0)\u0394^n\n# we try something like\n# f(x0+\u0394)\u2248[\u00a0\u2211_l=0^L a_l(x0)\u0394^l ] / [ 1 + \u2211_m=0^M b_m(x0)\u0394^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\u00e9 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\u00e9 coefficients and all of this is build in to the solution type. All you\n# need to know is that the number of Pad\u00e9 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\u00e9 approximant for L=M=10 (a so-called diagonal Pad\u00e9\n# approximant). This is just achieve by an extra argument for the call to our\n# solution object.\n\u03c9_approx=sol(:\u03c4,\u03c4+r[end]+0.001,10,10)\nprintln(\" exact=$(\u03c9_exact/2/pi)  vs  approx=$(\u03c9_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": "@testset \"Interpolate\" begin\n    @testset \"LineSegment\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(1, 1, 1)\n            P\u2082 = Point{3,T}(3, 3, 3)\n            l = LineSegment(P\u2081, P\u2082)\n            @test l(0) \u2248 P\u2081\n            @test l(1) \u2248 P\u2082\n            @test l(1//2) \u2248 Point{3,T}(2, 2, 2)\n        end\n    end\n\n    @testset \"QuadraticSegment\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(0, 0, 0)\n            P\u2082 = Point{3,T}(2, 0, 0)\n            P\u2083 = Point{3,T}(1, 1, 0)\n            q = QuadraticSegment(P\u2081, P\u2082, P\u2083)\n            for r = LinRange{T}(0, 1, 5)\n                @test q(r) \u2248 Point{3,T}(2r, -(2r)^2 + 4r, 0)\n            end\n        end\n    end\n\n    @testset \"Triangle\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(0, 0, 0)\n            P\u2082 = Point{3,T}(0, 1, 0)\n            P\u2083 = Point{3,T}(0, 0, 1)\n            tri = Triangle(P\u2081, P\u2082, P\u2083)\n            @test tri(0, 0) \u2248 P\u2081\n            @test tri(1, 0) \u2248 P\u2082\n            @test tri(0, 1) \u2248 P\u2083\n            @test tri(1//2, 1//2) \u2248 Point{3,T}(0, 1//2, 1//2)\n        end\n    end\n\n    @testset \"Quadrilateral\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(0, 0, 0)\n            P\u2082 = Point{3,T}(0, 1, 0)\n            P\u2083 = Point{3,T}(0, 1, 1)\n            P\u2084 = Point{3,T}(0, 0, 1)\n            quad = Quadrilateral(P\u2081, P\u2082, P\u2083, P\u2084)\n            @test quad(0, 0) \u2248 P\u2081\n            @test quad(1, 0) \u2248 P\u2082\n            @test quad(1, 1) \u2248 P\u2083\n            @test quad(0, 1) \u2248 P\u2084\n            @test quad(1//2, 1//2) \u2248 Point{3,T}(0, 1//2, 1//2)\n        end\n    end\n\n    @testset \"QuadraticTriangle\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(0, 0, 0)\n            P\u2082 = Point{3,T}(0, 1, 0)\n            P\u2083 = Point{3,T}(0, 1, 1)\n            P\u2084 = Point{3,T}(0, 1//2, 0)\n            P\u2085 = Point{3,T}(0, 1, 1//2)\n            P\u2086 = Point{3,T}(0, 1//2, 1//2)\n            tri6 = QuadraticTriangle(P\u2081, P\u2082, P\u2083, P\u2084, P\u2085, P\u2086)\n            @test tri6(0, 0) \u2248 P\u2081\n            @test tri6(1, 0) \u2248 P\u2082\n            @test tri6(0, 1) \u2248 P\u2083\n            @test tri6(1//2, 0) \u2248 P\u2084\n            @test tri6(1//2, 1//2) \u2248 P\u2085\n            @test tri6(0, 1//2) \u2248 P\u2086\n        end\n    end\n\n    @testset \"QuadraticQuadrilateral\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(0, 0, 0)\n            P\u2082 = Point{3,T}(0, 1, 0)\n            P\u2083 = Point{3,T}(0, 1, 1)\n            P\u2084 = Point{3,T}(0, 0, 1)\n            P\u2085 = Point{3,T}(0, 1//2,    0)\n            P\u2086 = Point{3,T}(0,    1, 1//2)\n            P\u2087 = Point{3,T}(0, 1//2,    1)\n            P\u2088 = Point{3,T}(0,    0, 1//2)\n            quad8 = QuadraticQuadrilateral(P\u2081, P\u2082, P\u2083, P\u2084, P\u2085, P\u2086, P\u2087, P\u2088)\n            @test quad8(0, 0) \u2248 P\u2081\n            @test quad8(1, 0) \u2248 P\u2082\n            @test quad8(1, 1) \u2248 P\u2083\n            @test quad8(0, 1) \u2248 P\u2084\n            @test quad8(1//2,    0) \u2248 P\u2085\n            @test quad8(   1, 1//2) \u2248 P\u2086\n            @test quad8(1//2,    1) \u2248 P\u2087\n            @test quad8(   0, 1//2) \u2248 P\u2088\n            @test quad8(1//2, 1//2) \u2248 Point{3,T}(0, 1//2, 1//2)\n        end\n    end\n\n    @testset \"Tetrahedron\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(0, 0, 0)           \n            P\u2082 = Point{3,T}(1, 0, 0)\n            P\u2083 = Point{3,T}(0, 1, 0)\n            P\u2084 = Point{3,T}(0, 0, 1)\n            tet = Tetrahedron(P\u2081, P\u2082, P\u2083, P\u2084)\n            @test tet(0, 0, 0) \u2248 P\u2081\n            @test tet(1, 0, 0) \u2248 P\u2082\n            @test tet(0, 1, 0) \u2248 P\u2083\n            @test tet(0, 0, 1) \u2248 P\u2084\n        end\n    end\n\n    @testset \"Hexahedron\" begin\n        for T in Floats\n            P\u2081 = Point{3,T}(0, 0, 0)\n            P\u2082 = Point{3,T}(1, 0, 0)\n            P\u2083 = Point{3,T}(0, 1, 0)\n            P\u2084 = Point{3,T}(1, 1, 0)\n            P\u2085 = Point{3,T}(0, 0, 1)\n            P\u2086 = Point{3,T}(1, 0, 1)\n            P\u2087 = Point{3,T}(0, 1, 1)\n            P\u2088 = Point{3,T}(1, 1, 1)\n            hex = Hexahedron(P\u2081, P\u2082, P\u2083, P\u2084, P\u2085, P\u2086, P\u2087, P\u2088)\n            @test hex(0, 0, 0) \u2248 P\u2081\n            @test hex(1, 0, 0) \u2248 P\u2082\n            @test hex(1, 1, 0) \u2248 P\u2083\n            @test hex(0, 1, 0) \u2248 P\u2084\n            @test hex(0, 0, 1) \u2248 P\u2085\n            @test hex(1, 0, 1) \u2248 P\u2086\n            @test hex(1, 1, 1) \u2248 P\u2087\n            @test hex(0, 1, 1) \u2248 P\u2088\n        end\n    end\n\n    @testset \"QuadraticTetrahedron\" begin\n        for T in Floats\n            P\u2081  = Point{3,T}(0, 0, 0)\n            P\u2082  = Point{3,T}(1, 0, 0)\n            P\u2083  = Point{3,T}(0, 1, 0)\n            P\u2084  = Point{3,T}(0, 0, 1)\n            P\u2085  = Point{3,T}(1//2,    0,    0)\n            P\u2086  = Point{3,T}(1//2, 1//2,    0)\n            P\u2087  = Point{3,T}(0,    1//2,    0)\n            P\u2088  = Point{3,T}(0,       0, 1//2)\n            P\u2089  = Point{3,T}(1//2,    0, 1//2)\n            P\u2081\u2080 = Point{3,T}(0,    1//2, 1//2)\n            tet10 = QuadraticTetrahedron(P\u2081, P\u2082, P\u2083, P\u2084, P\u2085, P\u2086, P\u2087, P\u2088, P\u2089, P\u2081\u2080)\n            @test tet10(0, 0, 0) \u2248 P\u2081 \n            @test tet10(1, 0, 0) \u2248 P\u2082 \n            @test tet10(0, 1, 0) \u2248 P\u2083 \n            @test tet10(0, 0, 1) \u2248 P\u2084 \n            @test tet10(1//2,    0,    0) \u2248 P\u2085\n            @test tet10(1//2, 1//2,    0) \u2248 P\u2086 \n            @test tet10(0,    1//2,    0) \u2248 P\u2087 \n            @test tet10(0,       0, 1//2) \u2248 P\u2088 \n            @test tet10(1//2,    0, 1//2) \u2248 P\u2089 \n            @test tet10(0,    1//2, 1//2) \u2248 P\u2081\u2080 \n        end\n    end\n    \n    @testset \"QuadraticHexahedon\" begin\n        for T in Floats\n            P\u2081  = Point{3,T}(0, 0, 0)\n            P\u2082  = Point{3,T}(1, 0, 0)\n            P\u2083  = Point{3,T}(1, 1, 0)\n            P\u2084  = Point{3,T}(0, 1, 0)\n            P\u2085  = Point{3,T}(0, 0, 1)\n            P\u2086  = Point{3,T}(1, 0, 1)\n            P\u2087  = Point{3,T}(1, 1, 1)\n            P\u2088  = Point{3,T}(0, 1, 1)\n            P\u2089  = Point{3,T}(1//2,    0,    0)\n            P\u2081\u2080 = Point{3,T}(   1, 1//2,    0)\n            P\u2081\u2081 = Point{3,T}(1//2,    1,    0)\n            P\u2081\u2082 = Point{3,T}(   0, 1//2,    0)\n            P\u2081\u2083 = Point{3,T}(1//2,    0,    1)\n            P\u2081\u2084 = Point{3,T}(   1, 1//2,    1)\n            P\u2081\u2085 = Point{3,T}(1//2,    1,    1)\n            P\u2081\u2086 = Point{3,T}(   0, 1//2,    1)\n            P\u2081\u2087 = Point{3,T}(0, 0, 1//2)\n            P\u2081\u2088 = Point{3,T}(1, 0, 1//2)\n            P\u2081\u2089 = Point{3,T}(1, 1, 1//2)\n            P\u2082\u2080 = Point{3,T}(0, 0, 1//2)\n            hex20 = QuadraticHexahedron(P\u2081,  P\u2082,  P\u2083,  P\u2084,  P\u2085,  P\u2086,  P\u2087,\n                                        P\u2088,  P\u2089,  P\u2081\u2080, P\u2081\u2081, P\u2081\u2082, P\u2081\u2083, P\u2081\u2084, \n                                        P\u2081\u2085, P\u2081\u2086, P\u2081\u2087, P\u2081\u2088, P\u2081\u2089, P\u2082\u2080)\n            @test hex20(0, 0, 0) \u2248 P\u2081\n            @test hex20(1, 0, 0) \u2248 P\u2082\n            @test hex20(1, 1, 0) \u2248 P\u2083\n            @test hex20(0, 1, 0) \u2248 P\u2084\n            @test hex20(0, 0, 1) \u2248 P\u2085\n            @test hex20(1, 0, 1) \u2248 P\u2086\n            @test hex20(1, 1, 1) \u2248 P\u2087\n            @test hex20(0, 1, 1) \u2248 P\u2088\n            @test hex20(1//2,    0,    0)\u2248 P\u2089\n            @test hex20(   1, 1//2,    0)\u2248 P\u2081\u2080    \n            @test hex20(1//2,    1,    0)\u2248 P\u2081\u2081\n            @test hex20(   0, 1//2,    0)\u2248 P\u2081\u2082\n            @test hex20(1//2,    0,    1)\u2248 P\u2081\u2083\n            @test hex20(   1, 1//2,    1)\u2248 P\u2081\u2084\n            @test hex20(1//2,    1,    1)\u2248 P\u2081\u2085\n            @test hex20(   0, 1//2,    1)\u2248 P\u2081\u2086\n            @test hex20(0, 0, 1//2)\u2248 P\u2081\u2087\n            @test hex20(1, 0, 1//2)\u2248 P\u2081\u2088\n            @test hex20(1, 1, 1//2)\u2248 P\u2081\u2089\n            @test hex20(0, 0, 1//2)\u2248 P\u2082\u2080\n        end\n    end\nend\n", "meta": {"hexsha": "2ddc02b3d33c64e2b7d063fb9f0608e53b4f4dcb", "size": 7186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/geometry/polytopes/interpolate.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": "test/geometry/polytopes/interpolate.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": "test/geometry/polytopes/interpolate.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": 35.2254901961, "max_line_length": 81, "alphanum_fraction": 0.3708600056, "num_tokens": 3377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7599911798210769}}
{"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        \u03b2 = 1 / (2 * C) - 1\n        r = n .* rand(Beta(1, \u03b2), S)\n\n        # set r[position of min[\u03b7]] = 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        \u03b2 = 1 / (2 * C) - 1\n        r = n .* rand(Beta(1, \u03b2), S)\n\n        # set r[position of min[\u03b7]] = 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                \u03d5 = exp(-((n[prey] - c[pred]) / (r[pred] / 2)) ^ 2)\n                adj[prey, pred] = rand(Bernoulli(\u03d5), 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 \u03d5_mat(\u03b8, m)\n\n    \u03d5 = fill(0.0, m.S, m.S)\n\n    @inbounds for pred in 1:m.nonbasal\n        for prey in 1:m.S\n            \u03d5[prey, m.basal + pred] = 0.99 * exp(-((\u03b8.n[prey] - \u03b8.c[pred] * \u03b8.n[m.basal + pred]) / (\u03b8.r[pred] / 2)) ^ 2)\n        end\n    end\n\n    return \u03d5\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": "\"\"\"\n    lognormal(x, \u03bc, \u03c3)\n\n```math\n\\\\frac{(x-\u03bc)^2}{2\u03c3^2}\n```\n\"\"\"\nfunction lognormal(x, \u03bc, \u03c3)\n  if \u03c3 == Inf\n    return 0\n  end\n  if \u03c3 \u2248 0\n    return Inf\n  end\n  (x-\u03bc)^2/2/\u03c3^2\nend\n\n\"\"\"\n    logpoisson(n, x...)\n\n```math\n  \u03bb > 0 \\\\\n  \u03bb = sum([x...])\n  \u03bb - n*log(\u03bb) + n*log(n) - n\n```math\n\"\"\"\nfunction logpoisson(n, x...)\n  \u03bb = sum([x...])\n  if \u03bb <= 0\n    return Inf\n  end\n  \u03bb - n*log(\u03bb) + n*log(n) - n\nend\n\n\"\"\"\n    batlog(x)\n\nCompute the natural log, but create bounds to ignore very large\nnumbers / infinities.\n```jldoctest\njulia> batlog.([12.0, 1e6, 0])\n3-element Array{Float64, 1}:\n  2.4849\n  13.8155\n  -100000.0\n```\n\"\"\"\nfunction batlog(x::Float64; up::Float64=1000.0, down::Float64=-1000.0)\n  if x <= 0\n    return -1e8\n  end\n  y = log(x)\n  if y < down\n    @debug \"Batlog hit floor\" y\n  end\n  if y > up\n    @debug \"Batlog hit ceiling\" y\n  end\n  minimum([up, maximum([down, y])])\nend\n", "meta": {"hexsha": "f55aee2ae136f1fbcbf92b5d8c89c0ed648f5d5c", "size": 882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/predefined_functions.jl", "max_stars_repo_name": "lightbearer88/Batman.jl", "max_stars_repo_head_hexsha": "57ba98cfd216055524b8ab7f9da8059120cdda0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/predefined_functions.jl", "max_issues_repo_name": "lightbearer88/Batman.jl", "max_issues_repo_head_hexsha": "57ba98cfd216055524b8ab7f9da8059120cdda0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-02-04T22:54:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-12T16:17:00.000Z", "max_forks_repo_path": "src/predefined_functions.jl", "max_forks_repo_name": "lightbearer88/Batman.jl", "max_forks_repo_head_hexsha": "57ba98cfd216055524b8ab7f9da8059120cdda0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-31T23:28:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T23:28:54.000Z", "avg_line_length": 14.4590163934, "max_line_length": 70, "alphanum_fraction": 0.5453514739, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7599911737704623}}
{"text": "#Array{Float64,1}\na=[168.3,179.2,165.8,170.5,188.2,174.6,162.8,175.5,178.1,177.1]\n\n#get arithmetic mean\n@show mean(a)", "meta": {"hexsha": "8ab835a4bb751e2692e1dc775fb84ee48d883b20", "size": 117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "statExer/mean.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": "statExer/mean.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": "statExer/mean.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.4, "max_line_length": 63, "alphanum_fraction": 0.6837606838, "num_tokens": 58, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7599911734053308}}
{"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 \u00d7 unitz::SVector{3, T}\n   vz ./= hypot(vz[1], vz[2], vz[3])\n   angle = acos(v \u22c5 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, \u03b8)\n   sin\u03b8, cos\u03b8 = sincos(eltype(v)(\u03b8))\n   tmp = 1 - cos\u03b8\n   m =  @SMatrix [\n        cos\u03b8+v[1]^2*tmp         v[1]*v[2]*tmp-v[3]*sin\u03b8 v[1]*v[3]*tmp+v[2]*sin\u03b8;\n        v[1]*v[2]*tmp+v[3]*sin\u03b8 cos\u03b8+v[2]^2*tmp         v[2]*v[3]*tmp-v[1]*sin\u03b8;\n        v[1]*v[3]*tmp-v[2]*sin\u03b8 v[3]*v[2]*tmp+v[1]*sin\u03b8 cos\u03b8+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 \u2248 -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 \u2248 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 \u00d7 v3::SVector{3, T}\n      v2 = v3 \u00d7 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\u2081,y\u2082,y\u2083 = u\n  du[1] = -0.04 * y\u2081 + 1e4 * y\u2082 * y\u2083\n  du[2] =  0.04 * y\u2081 - 1e4 * y\u2082 * y\u2083 - 3e7 * y\u2082^2\n  du[3] =  y\u2081 + y\u2082 + y\u2083 - 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 \u2248 0 means the constraint is fulfilled\ng_rober(z_new) \n\n# Only perturbing the second variable y\u2082\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": "using Printf\n\n@testset \"Hermite 1D\" begin\n\n    for nx in 5:5:35\n\n        \u03f5, \u03b3 = 0.1, 3.0\n        xmin, xmax = -1, 1\n\n        interp = Hermite(Chebyshev(xmin, xmax, nx), 0.1, 3.0)    \n\n        xk = interp.nodes\n        fk = cos.(xk.^2)\n\n\tnxe = 128\n        xe  = collect(range(xmin, stop=xmax, length=nxe))\n        dx  = xe[2]-xe[1]\n        fe  = cos.(xe.^2)\n\n        s   = interpolate( interp, fk, xe )\n\n        l2_error = sqrt(trapz((s - fe).^2, dx))\n        l1_error = maximum(abs.(s .- fe))\n\t@printf( \"%02d points - L2 : %.3e - L\u221e : %.3e \\n\",\n\t        nx, l2_error, l1_error )\n\n\t@test l2_error < max(1.0e-14, 10.0^(-nx\u00f72+1))\n    end\n\nend\n\n@testset \"Radial 1D\" begin\n\n    for nx in 5:5:35\n\n        \u03f5, \u03b3 = 0.1, 3.0\n        xmin, xmax = -1, 1\n\n        interp = Radial(Chebyshev(xmin, xmax, nx), 0.1)    \n\n        xk = interp.nodes\n        fk = cos.(xk.^2)\n\n\tnxe = 128\n        xe  = collect(range(xmin, stop=xmax, length=nxe))\n        dx  = xe[2]-xe[1]\n        fe  = cos.(xe.^2)\n\n        @time s   = interpolate( interp, fk, xe )\n\n        l2_error = sqrt(trapz((s - fe).^2, dx))\n        l1_error = maximum(abs.(s .- fe))\n\t@printf( \"%02d points - L2 : %.3e - L\u221e : %.3e \\n\",\n\t        nx, l2_error, l1_error )\n\n\t@test true\n    end\n\nend\n", "meta": {"hexsha": "cbee3fb5b456d2f57a7fc92804e28b3c919ee02d", "size": 1231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_interpolation1d.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": "test/test_interpolation1d.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": "test/test_interpolation1d.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": 20.5166666667, "max_line_length": 65, "alphanum_fraction": 0.4841592201, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774727, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7599911675320923}}
{"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_\u03b5\", \"sigma2_\u03be\", \"sigma2_\u03b6\"]\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_\u03b5\" => var(model.system.y),\n        \"sigma2_\u03be\" => var(model.system.y),\n        \"sigma2_\u03b6\" => 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_\u03b5\")\n    constrain_variance!(model, \"sigma2_\u03be\")\n    constrain_variance!(model, \"sigma2_\u03b6\")\n    return model\nend\n\nfunction unconstrain_hyperparameters!(model::LocalLinearTrend)\n    unconstrain_variance!(model, \"sigma2_\u03b5\")\n    unconstrain_variance!(model, \"sigma2_\u03be\")\n    unconstrain_variance!(model, \"sigma2_\u03b6\")\n    return model\nend\n\nfunction fill_model_system!(model::LocalLinearTrend)\n    model.system.H = get_constrained_value(model, \"sigma2_\u03b5\")\n    model.system.Q[1] = get_constrained_value(model, \"sigma2_\u03be\")\n    model.system.Q[end] = get_constrained_value(model, \"sigma2_\u03b6\")\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": "using Sobol\nusing Base.Test\n\n# test integrand from Joe and Kuo paper (integrates to 1)\nfunction testfunc(x::Vector{Float64})\n    f = 1.0\n    for j = 1:length(x)\n        cj = j^0.3333333333333333333\n        f *= (abs(4*x[j] - 2) + cj) / (1 + cj)\n    end\n    return f\nend\n\nfunction testint(N, n)\n    s = SobolSeq(N)\n    x = Array(Float64, N)\n    skip(s, n)\n    sum = 0.0\n    for j = 1:n\n        sum += testfunc(next!(s, x))\n    end\n    sum / n\nend\n\n# test results from Joe and Kuo (2003)\nN = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1111]\nn = [1009, 1997, 4001, 8009, 16001, 32003, 64007, 128021]\nJoeKuo = [0.9743 0.9544 0.9838 0.9982 0.9995 0.9976 0.9969 0.9975;\n          1.0157 0.9288 0.9649 0.9866 0.9985 0.9817 0.9955 0.9995;\n          1.1109 0.8877 0.9070 1.0312 1.0216 0.9772 0.9744 0.9925;\n          0.9770 0.8715 0.9305 0.9546 1.0060 0.9712 0.9770 0.9843;\n          1.1780 0.8908 0.9710 0.9527 1.0203 0.9754 0.9779 0.9725;\n          1.0567 0.8548 0.9700 0.9704 0.9768 0.9634 0.9745 0.9670;\n          0.8735 0.7674 1.0130 0.9874 0.9677 0.9416 0.9580 0.9564;\n          0.8752 0.8241 1.0067 1.0078 0.9987 0.9236 0.9517 0.9475;\n          0.9139 0.8822 1.0926 1.0560 1.0210 0.9454 0.9330 0.9359;\n          0.7779 1.0225 1.0593 1.0991 1.0470 0.9115 0.9688 0.9615;\n          0.8348 1.0443 1.0710 1.0862 1.0483 0.9188 0.9735 0.9683;\n          0.7524 0.9139 0.9592 0.9703 1.0116 0.9124 1.0411 0.9904]\n\nfor i = 1:length(N)\n    println(\"testing integrals of dimension $(N[i])\")\n    for j = 1:length(n)\n        println(\"  ... with $(n[j]) samples\")\n        t = testint(N[i], n[j])\n        @test_approx_eq_eps t JoeKuo[i,j] 1e-4\n    end\nend\n", "meta": {"hexsha": "13f9fd4b8ef567dc8bff6fdc4309adab7edc9a9b", "size": 1650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Ken-B/Sobol.jl", "max_stars_repo_head_hexsha": "1be9ebc47e4b28ac217a312f403276446a43fd7e", "max_stars_repo_licenses": ["MIT"], "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": "Ken-B/Sobol.jl", "max_issues_repo_head_hexsha": "1be9ebc47e4b28ac217a312f403276446a43fd7e", "max_issues_repo_licenses": ["MIT"], "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": "Ken-B/Sobol.jl", "max_forks_repo_head_hexsha": "1be9ebc47e4b28ac217a312f403276446a43fd7e", "max_forks_repo_licenses": ["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.6734693878, "max_line_length": 66, "alphanum_fraction": 0.5842424242, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.759982837724751}}
{"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 LinearAlgebra\n\n@testset \"core_nonmutating\" begin\n\n    # Basic Linear Algebra: cross3, dot3, norm3, norm3!\n    a = [1. 2. 9.; 2. 5. 6]\n    b = [4. 5. 7.; 3. 2. 8.]\n    xab = [-31. 29. -3.; 28. 2. -11.]\n    dab = [77., 64.]\n    na = [sqrt(86), sqrt(65)]\n    @test xab \u2248 DER.cross3(a,b)\n    @test dab \u2248 DER.dot3(a,b)\n    @test na \u2248 DER.norm3(a)\n\n    # Edges and Tangents\n    ea = [1. 3. -3.]\n    ta = ea./sqrt(19)\n    @test ea \u2248 DER.edges(a)\n    @test ta \u2248 DER.tangents(a)\n\n    # Parallel transport\n    \u03b8 = [1.0, 0.01, 0.0]\n    ptic_\u03b8 = [(1 - cos(1.0))/sin(1.0)^2, (1 - cos(0.01))/sin(0.01)^2, 0.5]\n\n    s2 = sin.(\u03b8).^2\n    c = cos.(\u03b8)\n    @test ptic_\u03b8 \u2248 DER.ptransport_inner_coefficient.(s2, c)\n\n    t1 = [1. 0. 0.]\n    t2 = [1. 1. 1.]/sqrt(3)\n    v1 = [0. 1. 1.]\n    v2 = [-2. 1. 1.]/sqrt(3)\n    @test DER.ptransport(t1, t1, t2) \u2248 t2\n    @test DER.ptransport(DER.cross3(t1, t2), t1, t2) \u2248 DER.cross3(t1, t2)\n    @test DER.ptransport([v1; v1], [t1; t1], [t2; t2]) \u2248 [v2; v2]\n\n    # Rotations of orthogonal unit vectors\n    v1 = [0. 1. 0.; 0. 0. 1.]\n    v2 = [0. 1. 1.; 0. -1. 1.]/sqrt(2)\n    \u03b8 = \u03c0/4\n    t = [1. 0. 0.]\n    @test DER.rotate_orthogonal_unit(v1, [t; t], [\u03b8; \u03b8]) \u2248 v2\n\n    # Basic Rod update\n    x0 = [0. 0. 0.; 1. 0. 0.; 2. 0. 0.]\n    d0 = [0. 0. 1.; 0. 0. 1.]\n    \u0394x = [0. 0. 0.; 0. 0. 1.; 0. 0. 0.]\n    \u0394\u03b8 = [0., \u03c0/2]\n    x, d = DER.rod_update(x0, d0, \u0394x, \u0394\u03b8)\n    @test x \u2248 x0 + \u0394x\n    @test d \u2248 [-1/sqrt(2) 0. 1/sqrt(2); 0. -1. 0.]\n\n    # Full kinematics\n    l, \u03ba, \u03c4 = DER.full_kinematics(x, d)\n    @test l \u2248 [sqrt(2), sqrt(2)]\n    @test \u03ba \u2248 [-1. 1.]\n    @test \u03c4 \u2248 [\u03c0/2]\nend\n\n@testset \"core_mutating\" begin\n\n    # Basic Linear Algebra: cross3, dot3, norm3, norm3!\n    a = [1. 2. 9.; 2. 5. 6]\n    b = [4. 5. 7.; 3. 2. 8.]\n    xab = [-31. 29. -3.; 28. 2. -11.]\n    dab = [77., 64.]\n    na = [sqrt(86), sqrt(65)]\n    ta = a./na\n\n    c = similar(a)\n    d = zeros(2)\n    cache = similar(a)\n\n    DER.cross3!(c,a,b)\n    @test xab \u2248 c\n\n    DER.dot3!(d,a,b)\n    @test dab \u2248 d\n\n    DER.norm3!(d,a)\n    @test na \u2248 d\n\n    c = copy(a)\n    DER.norm3!(c)\n    @test ta \u2248 c\n\n    # Edges and tangents\n    eb = [-1.0 -3.0 1.0]\n    c = similar(eb)\n    DER.edges!(c,b)\n    @test eb \u2248 c\n\n    tb = eb./sqrt(11)\n    c = similar(tb)\n    DER.tangents!(c,b)\n    @test tb \u2248 c\n\n    # Parallel transport inner coeff: TBD!\n    \u03b8 = [1.0, 0.01, 0.0]\n    ptic_\u03b8 = [(1 - cos(1.0))/sin(1.0)^2, (1 - cos(0.01))/sin(0.01)^2, 0.5]\n\n    s2 = sin.(\u03b8).^2\n    c = cos.(\u03b8)\n    out = similar(\u03b8)\n    DER.ptransport_inner_coefficient!(out, s2, c)\n    @test ptic_\u03b8 \u2248 out\n\n    # Parallel transport\n    t1 = [1. 0. 0.]\n    t2 = [1. 1. 1.]/sqrt(3)\n    v1 = [0. 1. 1.]\n    v2 = [-2. 1. 1.]/sqrt(3)\n    cache = zeros(1, 9)\n\n    val = similar(t1)\n    DER.ptransport!(val, t1, t1, t2, cache)\n    @test val \u2248 t2\n\n    DER.ptransport!(val, DER.cross3(t1, t2), t1, t2, cache)\n    @test val \u2248 DER.cross3(t1, t2)\n\n    cache = zeros(2, 9)\n    val = [v1; v1]\n    DER.ptransport!(val, [v1; v1], [t1; t1], [t2; t2], cache)\n    @test val \u2248 [v2; v2]\n\n    # Rotations of orthogonal unit vectors\n    v1 = [0. 1. 0.; 0. 0. 1.]\n    v2 = [0. 1. 1.; 0. -1. 1.]/sqrt(2)\n    \u03b8 = \u03c0/4\n    t = [1. 0. 0.]\n    cache = zeros(2, 5)\n    DER.rotate_orthogonal_unit!(v1, [t; t], [\u03b8; \u03b8], cache)\n    @test  v1 \u2248 v2\n\n    # Basic Rod update\n    x1 = [0. 0. 0.; 1. 0. 0.; 2. 0. 0.]\n    d1 = [0. 0. 1.; 0. 0. 1.]\n    \u0394x = [0. 0. 0.; 0. 0. 1.; 0. 0. 0.]\n    \u0394\u03b8 = [0., \u03c0/2]\n    x2 = x1 + \u0394x\n    d2 = [-1/sqrt(2) 0. 1/sqrt(2); 0. -1. 0.]\n\n    xout = similar(x1)\n    dout = similar(d1)\n    cache = DER.allocate_cache(DER.rod_update!, Float64, 1)\n    DER.rod_update!(xout, dout, x1, d1, \u0394x, \u0394\u03b8, cache)\n    @test xout \u2248 x2\n    @test dout \u2248 d2\n\n    # Full Kinematics\n    l = zeros(2)\n    \u03ba = zeros(1,2)\n    \u03c4 = zeros(1)\n    caches = DER.allocate_cache(DER.full_kinematics!, Float64, 1)\n    DER.full_kinematics!(l, \u03ba, \u03c4, x2, d2, caches)\n    @test l \u2248 [sqrt(2), sqrt(2)]\n    @test \u03ba \u2248 [-1. 1.]\n    @test \u03c4 \u2248 [\u03c0/2]\n\nend\n\n# Next: Elastic and Gravitational energy\n", "meta": {"hexsha": "437ec9d87a93b165a11ed1976a1f560b4d0638db", "size": 3983, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit_tests.jl", "max_stars_repo_name": "jamesgabbard/DiscreteElasticRods.jl", "max_stars_repo_head_hexsha": "2621bb0b2a126745c0353c9532a6f8ce7560da33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-28T07:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T07:25:55.000Z", "max_issues_repo_path": "test/unit_tests.jl", "max_issues_repo_name": "jamesgabbard/DiscreteElasticRods.jl", "max_issues_repo_head_hexsha": "2621bb0b2a126745c0353c9532a6f8ce7560da33", "max_issues_repo_licenses": ["MIT"], "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/unit_tests.jl", "max_forks_repo_name": "jamesgabbard/DiscreteElasticRods.jl", "max_forks_repo_head_hexsha": "2621bb0b2a126745c0353c9532a6f8ce7560da33", "max_forks_repo_licenses": ["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.2865853659, "max_line_length": 74, "alphanum_fraction": 0.4875721818, "num_tokens": 1904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7599828253893129}}
{"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    \u03bc = 0.0 # mean is zero\n    \u03c3 = sqrt(2) # D=1\n    \u03981 = 1.0\n    \u03982 = 1.0+abs(c)\n\n    W1 = OrnsteinUhlenbeckProcess(\u03981,\u03bc,\u03c3,0.0,1.0)\n    W2 = OrnsteinUhlenbeckProcess(\u03982,\u03bc,\u03c3,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\u2207L = L_grad(z, x_init)\n\n\tprintln()\n\tfor i = 1:10\n\t\tr_norm = norm(\u2207L)\n\t\tprintln(\"iter ($i)\")\n\t\tprintln(\"\tgrad norm: $(r_norm)\")\n\t\tr_norm < 1.0e-8 && break\n\n\t\t\u2207\u00b2L = L_hess(z, x_init)\n\n\t\t\u0394 = \u2207\u00b2L \\ \u2207L\n\n\t\t\u03b1 = 1.0\n\t\tz\u0302 = z - \u03b1 * \u0394\n\n\t\t\u2207L\u0302 = L_grad(z\u0302, x_init)\n\n\t\titer = 1\n\t\twhile norm(\u2207L\u0302) > norm(\u2207L)\n\t\t\t\u03b1 *= 0.5\n\t\t\tz\u0302 = z - \u03b1 * \u0394\n\t\t\t\u2207L\u0302 = L_grad(z\u0302, 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\u0302\n\t\t\u2207L = \u2207L\u0302\n\tend\n\n\treturn z, \u2207L, L_hess(z, x_init)\nend\n\nz_sol, \u2207L_sol, \u2207\u00b2L_sol = solve(z0, x_init)\nK_direct = (\u2207\u00b2L_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\u03a3 = ones(npar, npar)\nfor i = 1:npar\n    for iprime = 1:i\n        if i != iprime\n            \u03a3[i, iprime] = 0.25\n            \u03a3[iprime, i] = 0.25\n        end\n    end\nend\n\nDataDistribution = MvNormal(zeros(npar), \u03a3)\nX = zeros(nobs, npar+1)\nX[:,1] .= 1.\nfor iobs = 1:nobs\n    X[iobs, 2:end] .= rand(DataDistribution)\nend\n\n\u03b2 = 1 .+ rand(npar+1)*3\ny = X*\u03b2 + 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(\u03b2)\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.\u03b3 = 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, \u03a3b = 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\u03a3ols = 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": "# indicator of the zero cone\n\nexport IndZero\n\n\"\"\"\n**Indicator of the zero cone**\n\n    IndZero()\n\nReturns the indicator function of the set containing the origin, the \"zero cone\".\n\"\"\"\nstruct IndZero <: ProximableFunction end\n\nis_separable(f::IndZero) = true\nis_convex(f::IndZero) = true\nis_singleton(f::IndZero) = true\nis_cone(f::IndZero) = true\nis_affine(f::IndZero) = true\n\nfunction (f::IndZero)(x::AbstractArray{C}) where {R <: Real, C <: Union{R, Complex{R}}}\n    for k in eachindex(x)\n        if x[k] != C(0)\n            return R(Inf)\n        end\n    end\n    return R(0)\nend\n\nfunction prox!(y::AbstractArray{C}, f::IndZero, x::AbstractArray{C}, gamma=R(1)) where {R <: Real, C <: Union{R, Complex{R}}}\n    for k in eachindex(x)\n        y[k] = C(0)\n    end\n    return R(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 \u21a6 0 if all(x = 0), +\u221e otherwise\"\nfun_params(f::IndZero) = \"none\"\n\nfunction prox_naive(f::IndZero, x::AbstractArray{C}, gamma=R(1)) where {R <: Real, C <: Union{R, Complex{R}}}\n    return zero(x), R(0)\nend\n", "meta": {"hexsha": "d9ad008dad572036f4549dbc032854c496edf0d4", "size": 1132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indZero.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/indZero.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/indZero.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": 25.7272727273, "max_line_length": 125, "alphanum_fraction": 0.6431095406, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7599765334602525}}
{"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\u00fa\u00f1ez:\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\u03b7 = 0.58\n\u03bb = 0.93\n\u03b1 = 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\u039b(x) = forward_logs(M, x) # on T_xN\nprior(x) = norm(norm.(Ref(pixelM), repeat(x, rep(d)...), \u039b(x)), 1)\n#\n# Setup & Optimize\nprint(\"--- Douglas\u2013Rachford with \u03b7: $(\u03b7) and \u03bb: $(\u03bb) ---\\n\")\ncost(x) = 1 / \u03b1 * fidelity(x[1]) + prior(x[1])\nN = PowerManifold(M, NestedPowerRepresentation(), 5)\nprox1 = (\u03b7, x) -> [prox_distance(M, \u03b7, f, x[1]), prox_parallel_TV(M, \u03b1 * \u03b7, x[2:5])...]\nprox2 = (\u03b7, 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    \u03bb=i -> \u03b7,\n    \u03b1=i -> \u03bb, # 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)-\u03b1$(replace(string(\u03b1), \".\" => \"-\")).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] / \u03b1 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) \u2248 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 RunTests\nusing Base.Test\n\n@testmodule ErrorAnalysisTest begin\n  using MLLibrary\n\n  function test_confusionMatrix()\n    testset = [1 0 1 1 1 1 1 0 0 0 0]\n    predset = [1 1 0 1 1 1 0 1 0 0 0]\n\n    @test MLLibrary.Utils.ErrorAnalysis.generateConfusionMatrix(testset,predset)==[0 0 1;\n                    0 3 2;\n                    1 2 4;]\n\n    testset = [1 2 3 4 1 2 4 1 3 2 1 2]\n    predset = [1 1 4 1 1 2 3 2 3 2 1 4]\n\n    @test MLLibrary.Utils.ErrorAnalysis.generateConfusionMatrix(testset,predset)==[0 1 2 3 4;\n                    1 3 1 0 0;\n                    2 1 2 0 1;\n                    3 0 0 1 1;\n                    4 1 0 1 0;]\n  end\n\n  function test_generateWeightedErrorRate()\n    testset = [1 0 1 1 1 1 1 0 0 0 0]\n    predset = [1 1 0 1 1 1 0 1 0 0 0]\n\n    confusionmatrix =  MLLibrary.Utils.ErrorAnalysis.generateConfusionMatrix(testset,predset)\n\n    @test round(MLLibrary.Utils.ErrorAnalysis.calculateWeightedSuccessRate(confusionmatrix),2) == .63\n\n    testset = [1 2 3 4 1 2 4 1 3 2 1 2]\n    predset = [1 1 4 1 1 2 3 2 3 2 1 4]\n\n    confusionmatrix= MLLibrary.Utils.ErrorAnalysis.generateConfusionMatrix(testset,predset)\n\n    @test round(MLLibrary.Utils.ErrorAnalysis.calculateWeightedSuccessRate(confusionmatrix),2) == .44\n\n  end\n\n  function test_generateErrorRate()\n    testset = [1 0 1 1 1 1 1 0 0 0 0]\n    predset = [1 1 0 1 1 1 0 1 0 0 0]\n\n    @test round(MLLibrary.Utils.ErrorAnalysis.calculateErrorRate(testset,predset),2)==.36\n    #\n    testset = [1 2 3 4 1 2 4 1 3 2 1 2]\n    predset = [1 1 4 1 1 2 3 2 3 2 1 4]\n\n    @test MLLibrary.Utils.ErrorAnalysis.calculateErrorRate(testset,predset)==.5\n\n\n  end\n\n  function test_calculateRootMeanStandardError()\n    y=[1;2;3;4;5;6;1;2;3]\n    observed = [0;4;2;1;5;2;1;6;1]\n\n    @test round(MLLibrary.Utils.ErrorAnalysis.calculateRootMeanStandardError(observed,y),2)==2.38\n\n  end\n\n  function test_calculateWCSS()\n    centroids=[1 2 3 4;5 6 7 8]\n    data=[1 2 1 1;4 1 2 2; 5 2 1 4;3 3 2 1]\n    y=[1;1;2;2]\n    wcss = MLLibrary.Utils.ErrorAnalysis.calculateWCSS(centroids,data,y)\n    println(wcss)\n\n    @test wcss==183\n  end\n\n\nend\n", "meta": {"hexsha": "46c5538bd9addf2f59341add2dbe8e74a0fbac48", "size": 2098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit_tests/Utils/ErrorAnalysis.jl", "max_stars_repo_name": "ajermaky/CustomMLLibrary", "max_stars_repo_head_hexsha": "7bd512aa0bcb6b00f3776b5e9420e3129190ebcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-06T22:17:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-06T22:17:45.000Z", "max_issues_repo_path": "test/unit_tests/Utils/ErrorAnalysis.jl", "max_issues_repo_name": "ajermaky/CustomMLLibrary", "max_issues_repo_head_hexsha": "7bd512aa0bcb6b00f3776b5e9420e3129190ebcf", "max_issues_repo_licenses": ["MIT"], "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/unit_tests/Utils/ErrorAnalysis.jl", "max_forks_repo_name": "ajermaky/CustomMLLibrary", "max_forks_repo_head_hexsha": "7bd512aa0bcb6b00f3776b5e9420e3129190ebcf", "max_forks_repo_licenses": ["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": 101, "alphanum_fraction": 0.6348903718, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7598867574973018}}
{"text": "@testset \"Poisson\" begin\n\n    xmin = 0.0\n    xmax = 2\u03c0\n    ymin = 0.0\n    ymax = 2\u03c0\n\n    nx = 128\n    ny = 128\n\n    ux = zeros(Float64, nx, ny)\n    uy = zeros(Float64, nx, ny)\n\n    omega = zeros(Float64, nx, ny)\n    psi = zeros(Float64, nx, ny)\n\n    ux_exact = zeros(nx, ny)\n    uy_exact = zeros(nx, ny)\n    psi_exact = zeros(nx, ny)\n\n    grid = Grid(xmax-xmin, nx, ymax - ymin, ny)\n\n    poisson = Poisson(grid)\n\n    mode = 2\n    for i = 1:nx, j = 1:ny\n        x = xmin + (i - 1) * (xmax - xmin) / nx\n        y = ymin + (j - 1) * (ymax - ymin) / ny\n        psi_exact[i, j] = mode * sin(mode * x) * cos(mode * y)\n        ux_exact[i, j] = mode^2 * sin(mode * x) * sin(mode * y)\n        uy_exact[i, j] = mode^2 * cos(mode * x) * cos(mode * y)\n        omega[i, j] = 2 * mode^3 * sin(mode * x) * cos(mode * y)\n    end\n\n    rhs = copy(omega)\n    compute_psi!(psi, poisson, rhs)\n    @test psi_exact \u2248 psi\n\n    rhs = copy(omega)\n    compute_velocities!(ux, uy, poisson, rhs)\n    @test ux_exact \u2248 ux\n    @test uy_exact \u2248 uy\n\nend\n", "meta": {"hexsha": "f01bfe33d0185fd3b15bce9d351413d7cd5bdb9b", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_poisson.jl", "max_stars_repo_name": "pnavaro/SurfaceQuasiGeostrophic.jl", "max_stars_repo_head_hexsha": "e9ce1531e8f89e9a46f930b9e39a5f6509cc5743", "max_stars_repo_licenses": ["MIT"], "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_poisson.jl", "max_issues_repo_name": "pnavaro/SurfaceQuasiGeostrophic.jl", "max_issues_repo_head_hexsha": "e9ce1531e8f89e9a46f930b9e39a5f6509cc5743", "max_issues_repo_licenses": ["MIT"], "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_poisson.jl", "max_forks_repo_name": "pnavaro/SurfaceQuasiGeostrophic.jl", "max_forks_repo_head_hexsha": "e9ce1531e8f89e9a46f930b9e39a5f6509cc5743", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 64, "alphanum_fraction": 0.518627451, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7598867565618627}}
{"text": "data = split(strip(read(joinpath(@__DIR__, \"./2.txt\"), String)), '\\n')\n\n#part 1\nposition = Dict(:horizontal => 0, :depth => 0)\n\ncommand = Dict(\"forward\" => (:horizontal,+), \"down\" => (:depth,+), \"up\" => (:depth,-))\n\nfunction executeCommands(data)\n  global position,command\n  direction,distance = split(data,' ')\n  position[command[direction][1]] = command[direction][2](position[command[direction][1]],parse(Int,distance))\nend\n\nexecuteCommands.(data)\nposition[:horizontal]*position[:depth]\n\n\n\n# part 2\nposition = Dict(:horizontal => 0, :depth => 0, :aim => 0)\n\ncommand = Dict(\"forward\" => (:horizontal,+), \"down\" => (:aim,+), \"up\" => (:aim,-))\n\nfunction executeCommands2(data)\n  global position\n  direction,distance = split(data,' ')\n  d = parse(Int,distance)\n  position[command[direction][1]] = command[direction][2](position[command[direction][1]],d)\n  if direction == \"forward\"\n    position[:depth] = position[:depth] + d * position[:aim]\n  end\nend\n\nexecuteCommands2.(data)\nposition[:horizontal]*position[:depth]\n\n\n\n\n", "meta": {"hexsha": "2098db4ec9069b0d395f7d59fb67e8674159b086", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2.jl", "max_stars_repo_name": "benguela/aoc2021", "max_stars_repo_head_hexsha": "5b685c413d0aab1b1933a7223cbc4779909b7796", "max_stars_repo_licenses": ["MIT"], "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.jl", "max_issues_repo_name": "benguela/aoc2021", "max_issues_repo_head_hexsha": "5b685c413d0aab1b1933a7223cbc4779909b7796", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "benguela/aoc2021", "max_forks_repo_head_hexsha": "5b685c413d0aab1b1933a7223cbc4779909b7796", "max_forks_repo_licenses": ["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": 110, "alphanum_fraction": 0.662745098, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7598867524305829}}
{"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    \u2113p(x::AbstractVector, y::AbstractVector, p::Real=2)\n    \u21131(x::AbstractVector, y::AbstractVector)\n    \u21132(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`\u21131(x,y)` is the same as `\u2113p(x,y,1)`, and `\u21132(x,y)` is the same as `\u2113p(x,y,2)`.\n\n# Examples\n```jldoctest; setup = :(using LSHFunctions)\njulia> x = [1, 2, 3];\n\njulia> y = [4, 5, 6];\n\njulia> \u2113p(x,y,2) == (abs(1-4)^2 + abs(2-5)^2 + abs(3-6)^2)^(1/2)\ntrue\n\njulia> \u2113p(x,y,3) == (abs(1-4)^3 + abs(2-5)^3 + abs(3-6)^3)^(1/3)\ntrue\n```\n\nSee also: [`\u2113p_norm`](@ref), [`L1Hash`](@ref), [`L2Hash`](@ref)\n\"\"\"\n\u2113p(x::AbstractVector, y::AbstractVector, p::Real=2) = Lp(x, y, p)\n\n@doc (@doc \u2113p)\n\u21131(x::AbstractVector, y::AbstractVector) = L1(x, y)\n\n@doc (@doc \u2113p)\n\u21132(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 ``\u2113^p`` distance between a pair of vectors ``x`` and ``y``. Identical to `\u2113p(x,y,p)`, `\u21131(x,y)`, and `\u21132(x,y)`, respectively.\n\nSee also: [`\u2113p`](@ref)\n\"\"\"\nfunction Lp(x::AbstractVector{T}, y::AbstractVector, p::Real=2) where T\n    if p \u2264 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 \u221aresult\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 \u2264 x \u2264 1);\n\njulia> Lp(f, g, interval, 1) \u2248 L1(f, g, interval) \u2248 3^(-1)\ntrue\n\njulia> Lp(f, g, interval, 2) \u2248 L2(f, g, interval) \u2248 5^(-1/2)\ntrue\n\njulia> Lp(f, g, interval, 3) \u2248 7^(-1/3)\ntrue\n```\n\nSee also: [`Lp_norm`](@ref), [`\u2113p`](@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 \u2229 B) / length(A \u222a 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 = \u2205, their Jaccard\n        # similarity is zero.\n        Float64(0)\n    else\n        length(A \u2229 B) / length(A \u222a 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 \u2264 x[ii] \u2264 y[ii]\n            intersection += x[ii]\n            union += y[ii]\n        elseif 0 \u2264 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 \u222a 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 \u2229 B)\n\n    # By convention, if A = B = \u2205, 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) \u2248 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 \u2264 x \u2264 \u03c0/2)) \u2248 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 `\u2113p_norm(x,p)`, `\u21131_norm(x)`, and `\u21132_norm(x)`, respectively.\n\nSee also: [`\u2113p_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    \u2113p_norm(x::AbstractVector, p::Real = 2)\n    \u21131_norm(x::AbstractVector)\n    \u21132_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> \u2113p_norm(x, 1) \u2248 \u21131_norm(x) \u2248 (map(u -> abs(u)^1, x) |> sum)^(1/1)\ntrue\n\njulia> \u2113p_norm(x, 2) \u2248 \u21132_norm(x) \u2248 (map(u -> abs(u)^2, x) |> sum)^(1/2)\ntrue\n\njulia> \u2113p_norm(x, 3) \u2248 (map(u -> abs(u)^3, x) |> sum)^(1/3)\ntrue\n```\n\nSee also: [`\u2113p`](@ref), [`Lp_norm`](@ref)\n\"\"\"\n\u2113p_norm(x::AbstractVector, p::Real = 2) = Lp_norm(x, p)\n\n@doc (@doc \u2113p_norm)\n\u21131_norm(x::AbstractVector) = L1_norm(x)\n\n@doc (@doc \u2113p_norm)\n\u21132_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 \u2264 x \u2264 1);\n\njulia> Lp_norm(f, interval, 1) \u2248 L1_norm(f, interval) \u2248 2^(-1/1)\ntrue\n\njulia> Lp_norm(f, interval, 2) \u2248 L2_norm(f, interval) \u2248 3^(-1/2)\ntrue\n\njulia> Lp_norm(f, interval, 3) \u2248 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) = \u221aquadgk(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": "module JMcDM\n\n# Dependencies\nimport DataFrames: DataFrame, DataFrameRow\nimport JuMP: @variable, @objective, @constraint\nimport JuMP: Model, MOI, optimize!, JuMP, objective_value\nimport GLPK\n\n# for Pretty printing\n# of MCDM results\nimport Base.show\n\n# includes \ninclude(\"types.jl\")\ninclude(\"utilities.jl\")\ninclude(\"topsis.jl\")\ninclude(\"vikor.jl\")\ninclude(\"electre.jl\")\ninclude(\"moora.jl\")\ninclude(\"dematel.jl\")\ninclude(\"ahp.jl\")\ninclude(\"nds.jl\")\ninclude(\"singlecriterion.jl\")\ninclude(\"game.jl\")\ninclude(\"dataenvelop.jl\")\ninclude(\"grey.jl\")\ninclude(\"saw.jl\")\ninclude(\"aras.jl\")\ninclude(\"wpm.jl\")\ninclude(\"waspas.jl\")\ninclude(\"edas.jl\")\ninclude(\"marcos.jl\")\ninclude(\"mabac.jl\")\ninclude(\"mairca.jl\")\ninclude(\"copras.jl\")\ninclude(\"promethee.jl\")\ninclude(\"cocoso.jl\")\ninclude(\"critic.jl\")\ninclude(\"entropy.jl\")\ninclude(\"codas.jl\")\n\ninclude(\"summary.jl\")\n\ninclude(\"mcdm.jl\")\ninclude(\"print.jl\")\n\ninclude(\"copeland.jl\")\n\n# export imported functions\nexport DataFrame\n\n# export MCDM methods\nexport MCDMMethod \nexport ArasMethod\nexport CocosoMethod\nexport CodasMethod\nexport CoprasMethod\nexport CriticMethod\nexport EdasMethod\nexport ElectreMethod\nexport GreyMethod\nexport MabacMethod\nexport MaircaMethod\nexport MooraMethod\nexport PrometheeMethod\nexport SawMethod\nexport TopsisMethod\nexport VikorMethod\nexport WPMMethod\nexport WaspasMethod\nexport MarcosMethod\n\nexport MCDMSetting\n\n# export MCDM types\nexport MCDMResult\nexport TopsisResult\nexport VikorResult\nexport ElectreResult\nexport MooraResult\nexport AHPConsistencyResult\nexport AHPResult\nexport NDSResult\nexport GreyResult\nexport SawResult\nexport ARASResult\nexport WPMResult\nexport WASPASResult\nexport EDASResult\nexport MARCOSResult\nexport MABACResult\nexport MAIRCAResult\nexport COPRASResult\nexport PrometheeResult\nexport CoCoSoResult\nexport CRITICResult\nexport EntropyResult\nexport CODASResult\n\n# export game type\nexport GameResult\n\n# \u00a0export SCDM types\nexport SCDMResult\nexport LaplaceResult\nexport MaximinResult\nexport MaximaxResult\nexport MinimaxResult\nexport MiniminResult\nexport SavageResult\nexport HurwiczResult\nexport MLEResult\nexport ExpectedRegretResult\nexport DataEnvelopResult\n\n\n# export utility functions\nexport euclidean\nexport normalize\nexport colmaxs\nexport colmins\nexport unitize\nexport makeDecisionMatrix\nexport reverseminmax\nexport makeminmax\n\n# \u00a0export MCDM tools\nexport topsis\nexport vikor\nexport electre\nexport moora\nexport dematel\nexport ahp_RI, ahp_consistency, ahp\nexport nds\nexport grey\nexport saw\nexport aras\nexport wpm\nexport waspas\nexport edas\nexport marcos\nexport mabac\nexport mairca\nexport copras\nexport promethee, prometLinear, prometVShape, prometUsual, prometQuasi, prometLevel\nexport cocoso\nexport critic\nexport entropy\nexport codas\n\n# \u00a0export SCDM tools\nexport laplace\nexport maximin\nexport maximax\nexport minimax\nexport minimin\nexport savage\nexport hurwicz\nexport mle\nexport expectedregret\n\n# export game solver\nexport game\n\n# export data envelop\nexport dataenvelop\n\n# \u00a0export summary function\nexport summary\nexport mcdm\n\n# export Copeland module\nimport JMcDM.Copeland: copeland\nexport copeland\n\nend # module\n", "meta": {"hexsha": "e30739fb7d6029664bb242eb4c84c9544d36ccd4", "size": 3090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JMcDM.jl", "max_stars_repo_name": "jbytecode/jMCDM", "max_stars_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "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/JMcDM.jl", "max_issues_repo_name": "jbytecode/jMCDM", "max_issues_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "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/JMcDM.jl", "max_forks_repo_name": "jbytecode/jMCDM", "max_forks_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "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": 17.4576271186, "max_line_length": 83, "alphanum_fraction": 0.8223300971, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7598867492347429}}
{"text": "using DiffEqSensitivity, Flux, Optimization, OptimizationFlux, OptimizationOptimJL, OrdinaryDiffEq, Test\n\n\nx = Float32[0.8; 0.8]\ntspan = (0.0f0,10.0f0)\n\nann = Chain(Dense(2,10,tanh), Dense(10,1))\np = Float32[-2.0,1.1]\np2,re = Flux.destructure(ann)\n_p = [p;p2]\n\u03b8 = [x;_p]\n\nfunction dudt2_(u,p,t)\n    x, y = u\n    [(re(p[3:end])(u)[1]),p[1]*y + p[2]*x]\nend\n\nprob = ODEProblem(dudt2_,x,tspan,_p)\nsolve(prob,Tsit5())\n\nfunction predict_rd(\u03b8)\n  Array(solve(prob,Tsit5(),u0=\u03b8[1:2],p=\u03b8[3:end],abstol=1e-7,reltol=1e-5,sensealg=TrackerAdjoint()))\nend\nloss_rd(p) = sum(abs2,x-1 for x in predict_rd(p))\nl = loss_rd(\u03b8)\n\ncb = function (\u03b8,l)\n  @show l\n  # display(plot(solve(remake(prob,u0=Flux.data(_x),p=Flux.data(p)),Tsit5(),saveat=0.1),ylim=(0,6)))\n  false\nend\n\n# Display the ODE with the current parameter values.\ncb(\u03b8,l)\n\nloss1 = loss_rd(\u03b8)\noptfunc = Optimization.OptimizationFunction((x, p) -> loss_rd(x), Optimization.AutoZygote())\noptprob = Optimization.OptimizationProblem(optfunc, \u03b8)\nres = Optimization.solve(optprob, BFGS(initial_stepnorm = 0.01), callback = cb)\nloss2 = res.minimum\n@test 3loss2 < loss1\n\n## Partial Neural Adjoint\n\nu0 = Float32[0.8; 0.8]\ntspan = (0.0f0,25.0f0)\n\nann = Chain(Dense(2,10,tanh), Dense(10,1))\n\np1,re = Flux.destructure(ann)\np2 = Float32[-2.0,1.1]\np3 = [p1;p2]\n\u03b8 = [u0;p3]\n\nfunction dudt_(du,u,p,t)\n    x, y = u\n    du[1] = re(p[1:41])(u)[1]\n    du[2] = p[end-1]*y + p[end]*x\nend\nprob = ODEProblem(dudt_,u0,tspan,p3)\nsolve(prob,Tsit5(),abstol=1e-8,reltol=1e-6)\n\nfunction predict_adjoint(\u03b8)\n  Array(solve(prob,Tsit5(),u0=\u03b8[1:2],p=\u03b8[3:end],saveat=0.0:1:25.0))\nend\nloss_adjoint(\u03b8) = sum(abs2,x-1 for x in predict_adjoint(\u03b8))\nl = loss_adjoint(\u03b8)\n\ncb = function (\u03b8,l)\n  @show l\n  # display(plot(solve(remake(prob,p=Flux.data(p3),u0=Flux.data(u0)),Tsit5(),saveat=0.1),ylim=(0,6)))\n  false\nend\n\n# Display the ODE with the current parameter values.\ncb(\u03b8,l)\n\nloss1 = loss_adjoint(\u03b8)\noptfunc = Optimization.OptimizationFunction((x, p) -> loss_adjoint(x), Optimization.AutoZygote())\noptprob = Optimization.OptimizationProblem(optfunc, \u03b8)\nres1 = Optimization.solve(optprob, ADAM(0.01), callback = cb, maxiters = 100)\n\noptprob = Optimization.OptimizationProblem(optfunc, res1.minimizer)\nres = Optimization.solve(optprob, BFGS(initial_stepnorm = 0.01), callback = cb)\nloss2 = res.minimum\n@test 3loss2 < loss1\n", "meta": {"hexsha": "def123333d29b59fb7f932357ba19667c31b2ef5", "size": 2320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/partial_neural.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/partial_neural.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/partial_neural.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": 26.6666666667, "max_line_length": 104, "alphanum_fraction": 0.6900862069, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7598867485722618}}
{"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\u0302, FWHM) = exp[-4ln(2) * ||x - x\u0302|| / FWHM^2]\n```\nwhere `x\u0302` and `x` are position vectors (indices) `||\u22c5||` 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\u03c3\u00b2) to 1/(2fwhm\u00b2)\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_\u03bc, directional_\u03c3, \u2207directional_\u03c3,\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_\u03bc([[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_\u03bc(data::VDT)::VDT\n  \"\"\"\n  Re-center to have mean 0. across all dim\n  \"\"\"\n  \u03bc\u2080 = \u03bc.(data)\n  map(((d, \u03bc)=t) -> d .- \u03bc, zip(data, \u03bc\u2080))\nend\n\n\n\"\"\"\nReturns the variance of data in the direction of v\n\"\"\"\nfunction directional_\u03c3(data::VDT, v::DT)::Float64\n  dir_v = direction(v)\n  sum(dot(u, dir_v) .^ 2 for u \u2208 data)\nend\n\n\nfunction \u2207directional_\u03c3(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, \u03b7=0.1)::DT\n  # Start with a random guess\n  guess = ones(eltype(data[1]), length(data[1]))\n  for _ \u2208 1:n\n    d\u03c3 = directional_\u03c3(data, guess)\n    \u2207 = \u2207directional_\u03c3(data, guess)\n    guess .+= \u2207 * \u03b7\n  end\n  direction(guess)\nend\n\n\nfunction pca(data::VDT, ncomp::Integer)::VDT\n  comps = VDT{eltype(data[1])}()\n  for _ \u2208 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> \u03bc([1., 3., 2., 4.])\n2.5\n```\n\"\"\"\nfunction \u03bc(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": "using Test, Flux\nusing DiffEqDevTools\nusing DiffEqBase, NeuralNetDiffEq\n\n# Homogeneous on scalar\nf = (du, u, p, t) -> -du+6*u\ntspan = (0.0f0, 1.0f0)\nu0 = 1.0f0\ndu0 = 0.0f0\ndt = 1/5f0\nf_analytic = t -> [1/5 * exp(-3*t) *(3*exp(5*t)+2.0)]\nprob = SecondOrderODEProblem(ODEFunction{false}(f, analytic=f_analytic), u0, du0, tspan)\nchain = Chain(Dense(1,5,\u03c3),Dense(5,1))\nopt = ADAM(1, (0.9, 0.95))\nsol = solve(prob, NeuralNetDiffEq.NNODE2(chain,opt), dt=dt, verbose = true, maxiters = 200)\nerr = sqrt(sum((sol.u - [f_analytic(t)[1] for t in tspan[1]:dt:tspan[2]]).^2)[1])\n@test err< 0.5\n\n\n#Example 2: Test on vector\nf = (du, u, p, t) -> -2*du-5*u+5*t^2+12\ntspan = (0.0f0, 1.0f0)\nu0 = [1.0f0]\ndu0 = [0.0f0]\ndt = 1/5f0\nf_analytic = t -> [1/50 * exp(-t) * (2*exp(t) * (25*t^2 - 20*t + 58) - 13*sin(2*t) - 66*cos(2*t))]\nprob = SecondOrderODEProblem(ODEFunction{false}(f, analytic=f_analytic), u0, du0, tspan)\nchain = Chain(Dense(1,5,\u03c3),Dense(5,1))\nopt = ADAM(0.1, (0.9, 0.95))\nsol = solve(prob, NeuralNetDiffEq.NNODE2(chain,opt), dt=dt, verbose = true, maxiters = 300)\nerr = sqrt(sum((sol.u - [f_analytic(t)[1] for t in tspan[1]:dt:tspan[2]]).^2)[1])\n@test err < 0.5\n\n\n#Example 3: Test on system of 2nd order ODEs\nfunction func(ddu, du, u, p, t)\n\tddu[1] = (-p[3]*u[1]-p[4]*(u[1]-u[2]))/p[1]\n\tddu[2] = (-p[4]*(u[2]-u[1]))/p[2]\nend\nfunction func(du, u, p, t)\n\t[(-p[3]*u[1]-p[4]*(u[1]-u[2]))/p[1], (-p[4]*(u[2]-u[1]))/p[2]]\nend\np = [1.0f0, 1.0f0, 6.0f0, 4.0f0]\nu0 = [1.0f0, 0.0f0]\ndu0 = [2.0f0, 0.0f0]\nprob = SecondOrderODEProblem{false}(func, [u0], [du0], (0.0f0, 3.0f0), p)\ndt = 1/20f0\nopt = ADAM(1e-01)\nchain = Chain(Dense(1,5,\u03c3),Dense(5,2))\nsol = solve(prob, NeuralNetDiffEq.NNODE2(chain, opt), dt=dt, verbose=true, abstol=1e-10, maxiters=50)\n\n", "meta": {"hexsha": "eff6e374f45beea7ab99390ea06e4165fabdd8d1", "size": 1735, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/NNODE2_tests.jl", "max_stars_repo_name": "chinglamchoi/NeuralNetDiffEq.jl", "max_stars_repo_head_hexsha": "6cebe840661ee6472f301bf9bb9e16d4251f820f", "max_stars_repo_licenses": ["MIT"], "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/NNODE2_tests.jl", "max_issues_repo_name": "chinglamchoi/NeuralNetDiffEq.jl", "max_issues_repo_head_hexsha": "6cebe840661ee6472f301bf9bb9e16d4251f820f", "max_issues_repo_licenses": ["MIT"], "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/NNODE2_tests.jl", "max_forks_repo_name": "chinglamchoi/NeuralNetDiffEq.jl", "max_forks_repo_head_hexsha": "6cebe840661ee6472f301bf9bb9e16d4251f820f", "max_forks_repo_licenses": ["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.3653846154, "max_line_length": 101, "alphanum_fraction": 0.6097982709, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7598193657823791}}
{"text": "# Cubic interpolation\na = 4.3\nb = 1.7\nc = 6.2\nd = 5.9\ncfunc = x -> a*x.^3 .+ b*x.^2 .+ c*x .+ d\ncgrad = x -> 3a*x.^2 .+ 2b*x .+ c\nchess = x -> 6a*x .+ 2b\nxg = Float64[1:8;]\ny = cfunc(xg)\n\n# Low-level interface\nyc = copy(y)\ninterp_invert!(yc,BCnan,InterpCubic)\nic = InterpGridCoefs(yc,InterpCubic)\n\nx = 3.7\nset_position(ic, BCnil, true, true, [x])\nyi = interp(ic,yc)\n@test_approx_eq_eps cfunc(x) yi 0.01*(abs(cfunc(x))+abs(yi))\nset_gradient_coordinate(ic, 1)\ngi = interp(ic, yc)\n@test_approx_eq_eps cgrad(x) gi 0.1*(abs(cgrad(x))+abs(yi))\nset_hessian_coordinate(ic, 1, 1)\nhi = interp(ic, yc)\n@test_approx_eq_eps chess(x) hi 0.1*(abs(chess(x))+abs(yi))\n\n# High-level interface\nyi = InterpGrid(y, BCnil, InterpCubic)\n@test_approx_eq_eps yi[x] cfunc(x) 0.01*(abs(cfunc(x))+abs(yi[x]))\nv,g = valgrad(yi,x)\n@test_approx_eq_eps v cfunc(x) 0.01*(abs(cfunc(x))+abs(yi[x]))\n@test_approx_eq_eps g cgrad(x) 0.01*(abs(cgrad(x))+abs(yi[x]))\nv,g,h = valgradhess(yi,x)\n@test_approx_eq_eps v cfunc(x) 0.01*(abs(cfunc(x))+abs(yi[x]))\n@test_approx_eq_eps g cgrad(x) 0.01*(abs(cgrad(x))+abs(yi[x]))\n@test_approx_eq_eps h chess(x) 0.01*(abs(chess(x))+abs(yi[x]))\n\n# Test derivatives with other boundary conditions\nfunc = x -> yi[x]\ngnum = derivative_numer(func,x)\nhnum = derivative2_numer(func,x)\n\nfor BC in (BCnan, BCna)\n    yi = InterpGrid(y, BC, InterpCubic)\n    @test_throws BoundsError yi[1.1,2.8]  # wrong dimensionality\n    func = x -> yi[x]\n    v,g = valgrad(yi,x)\n    gnum = derivative_numer(func,x) \n    @test_approx_eq_eps g gnum 10*cbrt(eps())*(abs(g)+abs(gnum))\n    g = zeros(2)\n    @test_throws ErrorException valgrad(g, yi, x)\n    v,g,h = valgradhess(yi,x)\n    gnum = derivative_numer(func,x)\n    hnum = derivative2_numer(func,x)\n    @test_approx_eq_eps g gnum 10*cbrt(eps())*(abs(g)+abs(gnum))\n    @test_approx_eq_eps h hnum 10*cbrt(eps())*(abs(h)+abs(hnum))\n    g = zeros(1)\n    h = zeros(2,2)\n    @test_throws ErrorException valgradhess(g,h,yi,x)\n    g = zeros(2)\n    h = zeros(1,1)\n    @test_throws ErrorException valgradhess(g,h,yi,x)\nend\n\n# Test derivatives of 2D interpolation\n\ny = rand(7,8)\nyi = InterpGrid(y,BCnan,InterpCubic)\nx = [3.4,6.1]\nv,g = valgrad(yi,x...)\nv2,g2,h2 = valgradhess(yi,x...)\nfunc = (x1,x2) -> yi[x1,x2]\n\ngnum = derivative_numer(func, tuple(x...), 1)\n@test_approx_eq_eps g[1] gnum cbrt(eps())*(abs(g[1])+abs(gnum))\n@test_approx_eq_eps g2[1] gnum cbrt(eps())*(abs(g2[1])+abs(gnum))\n\ngnum = derivative_numer(func, tuple(x...), 2)\n@test_approx_eq_eps g[2] gnum cbrt(eps())*(abs(g[2])+abs(gnum))\n@test_approx_eq_eps g2[2] gnum cbrt(eps())*(abs(g2[2])+abs(gnum))\n\nhnum = derivative2_numer(func, tuple(x...), (1, 1))\n@test_approx_eq_eps h2[1,1] hnum 10*sqrt(sqrt(eps()))*(abs(h2[1,1])+abs(hnum))\nhnum = derivative2_numer(func, tuple(x...), (1, 2))\n@test_approx_eq_eps h2[1,2] hnum 10*sqrt(sqrt(eps()))*(abs(h2[1,2])+abs(hnum))\n@test_approx_eq_eps h2[2,1] hnum 10*sqrt(sqrt(eps()))*(abs(h2[2,1])+abs(hnum))\nhnum = derivative2_numer(func, tuple(x...), (2, 2))\n@test_approx_eq_eps h2[2,2] hnum 10*sqrt(sqrt(eps()))*(abs(h2[2,2])+abs(hnum))\n", "meta": {"hexsha": "e4748f6a8401ff419ece6ddb94c6837800cdbcd6", "size": 3054, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cubic_interpolation.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Grid.jl-03512f2c-8e8a-5728-b518-32bdd82c6646", "max_stars_repo_head_hexsha": "00481b5ab6e07d77b8fb97204a333c3cc68943c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2015-01-05T23:02:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T17:21:04.000Z", "max_issues_repo_path": "test/cubic_interpolation.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Grid.jl-03512f2c-8e8a-5728-b518-32bdd82c6646", "max_issues_repo_head_hexsha": "00481b5ab6e07d77b8fb97204a333c3cc68943c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2015-02-09T10:03:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T15:26:47.000Z", "max_forks_repo_path": "test/cubic_interpolation.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Grid.jl-03512f2c-8e8a-5728-b518-32bdd82c6646", "max_forks_repo_head_hexsha": "00481b5ab6e07d77b8fb97204a333c3cc68943c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2015-02-28T17:31:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:54:45.000Z", "avg_line_length": 33.9333333333, "max_line_length": 78, "alphanum_fraction": 0.6594629993, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7598193625873825}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.06\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.06\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u2550fd06acdc-3b1d-11eb-1d5f-03f5cf0f595a\n# \u2560\u2550fd06e9ae-3b1d-11eb-1646-d9c440ed4b98\n# \u255f\u2500475ff888-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\u2093 F(x)\u1d40F(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": "@testset \"Interval arithmetic\" begin\n    a = -1.5 \u00b1 0.5\n    b = -1..1\n    @test a + b == -3.0..0.0\n    @test a * b == -2.0..2.0\n    @test a * b + a == -4.0..1.0\n    @test a * (b + 1) == -4.0..0.0\nend\n\n@testset \"Interval matrix arithmetic\" begin\n    a = 1.0..1.3; b = 2.0..3.5; c = -0.5 \u00b1 0.5; d = 0.0 \u00b1 0.1\n    a\u208a = 2.0..2.6; b\u208a = 4.0..7.0; c\u208a = -2.0..0.0; d\u208a = -0.2..0.2\n    a\u208b = -0.3..0.3; b\u208b = -1.5..1.5; c\u208b = -1.0..1.0; d\u208b = -0.2..0.2\n    A = IntervalMatrix([a b; c d])\n\n    B = A + A\n    @test B isa IntervalMatrix && B == IntervalMatrix([a\u208a b\u208a; c\u208a d\u208a])\n\n    B = A - A\n    @test B isa IntervalMatrix && B == IntervalMatrix([a\u208b b\u208b; c\u208b d\u208b])\n\n    # multiply interval and interval matrix\n    x = 0.0..2.0\n    @test x * A == A * x ==\n          IntervalMatrix([0.0..2.6 0.0..7.0; -2.0..0.0 -0.2..0.2])\n    # multiply scalar and interval matrix\n    x = 1.0\n    for A2 in [x * A, A * x, A / x]\n        @test A2 == A && typeof(A2) == typeof(A)\n    end\n\n    # arithmetic closure using interval matrices and non-interval matrices\n    Ainf = inf(A)\n    @test A + Ainf isa IntervalMatrix\n    @test Ainf + A isa IntervalMatrix\n    @test A - Ainf isa IntervalMatrix\n    @test Ainf - A isa IntervalMatrix\n    @test A * Ainf isa IntervalMatrix\n    @test Ainf * A isa IntervalMatrix\nend\n\n@testset \"Matrix multiplication\" begin\n\n    # test default settings\n    @test get_multiplication_mode() == Dict(:multiplication => :fast)\n\n    A = IntervalMatrix([2..4 -2..1; -1..2 2..4])\n    set_multiplication_mode(:slow)\n    @test A * A == IntervalMatrix([0..18 -16..8; -8..16 0..18])\n    @test A * mid.(A) == IntervalMatrix([5..12.5 -8..2; -2..8 5..12.5])\n    @test mid.(A) * A == IntervalMatrix([5..12.5 -8..2; -2..8 5..12.5])\n\n    # set_multiplication_mode(:rank1)\n    # @test A * A == [0..18 -16..8; -8..16 0..18]\n\n    set_multiplication_mode(:fast)\n    @test A * A == IntervalMatrix([-2..19.5 -16..10; -10..16 -2..19.5])\n    @test A * mid.(A) == IntervalMatrix([5..12.5 -8..2; -2..8 5..12.5])\n    @test mid.(A) * A == IntervalMatrix([5..12.5 -8..2; -2..8 5..12.5])\nend\n", "meta": {"hexsha": "ef26afd2556236e833884f21348f6b79098768f5", "size": 2051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/arithmetic.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": "test/arithmetic.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": "test/arithmetic.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": 33.6229508197, "max_line_length": 74, "alphanum_fraction": 0.5338859093, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7598193563072302}}
{"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 \u22c5 p, 0.0]) * k1\n    p -= 2.0 * maximum([k2 \u22c5 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 \u22c5 ba) / (ba \u22c5 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": "@testset \"Verbose\" for T in [Float64]\n    using ProximalOperators\n    using ProximalAlgorithms\n    using LinearAlgebra\n\n    A = T[\n        1.0 -2.0 3.0 -4.0 5.0\n        2.0 -1.0 0.0 -1.0 3.0\n        -1.0 0.0 4.0 -3.0 2.0\n        -1.0 -1.0 -1.0 1.0 3.0\n    ]\n    b = T[1.0, 2.0, 3.0, 4.0]\n\n    m, n = size(A)\n\n    R = real(T)\n\n    lam = R(0.1) * norm(A' * b, Inf)\n    @test typeof(lam) == R\n\n    f = Translate(SqrNormL2(R(1)), -b)\n    f2 = LeastSquares(A, b)\n    g = NormL1(lam)\n\n    Lf = opnorm(A)^2\n\n    x_star = T[-3.877278911564627e-01, 0, 0, 2.174149659863943e-02, 6.168435374149660e-01]\n\n    TOL = R(1e-4)\n\n    @testset \"ForwardBackward\" begin\n\n        ## Nonfast/Nonadaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.ForwardBackward(tol = TOL, verbose = true)\n        x, it = solver(x0, f = f2, g = g, Lf = Lf)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 150\n\n        # Nonfast/Adaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.ForwardBackward(\n            tol = TOL,\n            adaptive = true,\n            verbose = true,\n        )\n        x, it = solver(x0, f = f2, g = g)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 300\n\n        # Fast/Nonadaptive\n\n        x0 = zeros(T, n)\n        solver =\n            ProximalAlgorithms.FastForwardBackward(tol = TOL, verbose = true)\n        x, it = solver(x0, f = f2, g = g, Lf = Lf)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 100\n\n        # Fast/Adaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.FastForwardBackward(\n            tol = TOL,\n            adaptive = true,\n            verbose = true,\n        )\n        x, it = solver(x0, f = f2, g = g)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 200\n    end\n\n    @testset \"ZeroFPR\" begin\n\n        # ZeroFPR/Nonadaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.ZeroFPR(tol = TOL, verbose = true)\n        x, it = solver(x0, f = f, A = A, g = g, Lf = Lf)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 20\n\n        # ZeroFPR/Adaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.ZeroFPR(adaptive = true, tol = TOL, verbose = true)\n        x, it = solver(x0, f = f, A = A, g = g)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 20\n\n    end\n\n    @testset \"PANOC\" begin\n\n        # PANOC/Nonadaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.PANOC(tol = TOL, verbose = true)\n        x, it = solver(x0, f = f, A = A, g = g, Lf = Lf)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 20\n\n        ## PANOC/Adaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.PANOC(adaptive = true, tol = TOL, verbose = true)\n        x, it = solver(x0, f = f, A = A, g = g)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 20\n\n    end\n\n    @testset \"PANOCplus\" begin\n\n        # PANOCplus/Nonadaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.PANOCplus(tol = TOL, verbose = true)\n        x, it = solver(x0, f = f, A = A, g = g, Lf = Lf)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 20\n\n        ## PANOCplus/Adaptive\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.PANOCplus(adaptive = true, tol = TOL, verbose = true)\n        x, it = solver(x0, f = f, A = A, g = g)\n        @test eltype(x) == T\n        @test norm(x - x_star, Inf) <= TOL\n        @test it < 20\n\n    end\n\n    @testset \"DouglasRachford\" begin\n\n        # Douglas-Rachford\n\n        x0 = zeros(T, n)\n        solver = ProximalAlgorithms.DouglasRachford(\n            gamma = R(10) / Lf,\n            tol = TOL,\n            verbose = true,\n        )\n        y, z, it = solver(x0, f = f2, g = g)\n        @test eltype(y) == T\n        @test eltype(z) == T\n        @test norm(y - x_star, Inf) <= TOL\n        @test norm(z - x_star, Inf) <= TOL\n        @test it < 30\n\n    end\n\nend\n", "meta": {"hexsha": "46f2b9f390fc8631dcb87392ea3c9f304f683fec", "size": 4175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/problems/test_verbose.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": "test/problems/test_verbose.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": "test/problems/test_verbose.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": 25.303030303, "max_line_length": 90, "alphanum_fraction": 0.4919760479, "num_tokens": 1480, "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": "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": "\"\"\"Julia program to implement Comb Sort\nComb sort is an improvised Bubble sort. Bubble sort removes its inversions one by one whereas In Comb sort,\nmore than one inversion is removed by one swap and hence it is more efficient than Bubble sort.\n\"\"\"\n\nfunction comb_sort(arr, n)\n    flag = 1\n    space = n\n    while (space > 1 || flag == 1)\n        # Here empirically found shrink factor 1.3 is used.\n        space = (space * 10) \u00f7 13\n\n        # Assigning space its minimum value of 1\n        if (space < 1)\n            space = 1\n        end\n        flag = 0\n\n        # Compare elements with the space value\n        for i in 1:(n - space)\n            if (arr[i] > arr[i + space])\n                arr[i], arr[i + space] = arr[i + space], arr[i]\n                flag = 1\n            end\n        end\n    end\nend\n    \n     \n\nprint(\"How many numbers do you want to sort? \")\nn = readline()\nn = parse(Int64, n)\nif (n <= 0)\n    println(\"No numbers to sort!!!\")\n    exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())]\ncomb_sort(arr, n)\nprint(\"The numbers in sorted order is \")\nprint(arr)\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\nHow many numbers do you want to sort? 6\nEnter the numbers: 123 13 42 324 153 43 \nThe numbers in sorted order is [13, 42, 43, 123, 153, 324]\n\"\"\"\n", "meta": {"hexsha": "97618c45173cfc2b354701e6b6ae13af646286df", "size": 1399, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/sort/comb_sort.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/sort/comb_sort.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/sort/comb_sort.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": 24.5438596491, "max_line_length": 107, "alphanum_fraction": 0.6004288778, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8918110555020056, "lm_q1q2_score": 0.7597809342657853}}
{"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# \u03c1(x) in integrand\n\u03c1(x) = 1/sqrt(\u03c0)*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        \u03be = rand(d)\n        Y = samples[i-1] + \u03be\n\n        # Acceptance probability\n        \u03b1 = min(1, \u03c1(Y)/\u03c1(samples[i-1]))\n\n        # Next state\n        if rand() < \u03b1\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(\u03c0)*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\u03bb], 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 #[\u03bb]\n    vv = vv .* 1e3 #[\u03bb]\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\u03bb], 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": "@testset \"Statistics\" begin\n\n    @testset \"Statistics: Ordinary Least Squares\" begin\n        a = [10, 14,17,21,20, 18, 42, 51, 77, 11, 91]\n        b = [0.11,0.7,0.2,0.19,0.09,0.8, 0.71,0.1, 0.6,0.3,0.81]\n        OLSbeta(a, b)\n\n        df = DataFrame(a=a, b=b)\n        ols = GLM.lm(@formula(a ~ b), df)\n        coef(ols) # print coefficients\n\n        # Predict\n        predict(ols) # predict the model\n    end\n\n    @testset \"Statistics: Pearson Correlation\" begin\n        a = 1:10\n        b = 1:10\n        @test pearson_correlation(a, b) == 1\n\n        x = [12,15,17,21,18]\n        y = [6,9,-1,3,1]\n\n        @test pearson_correlation(x, y) ==  -0.5201361507569889\n    end\n\n    @testset \"Statistics: Variance\" begin\n        a = 1:10\n        \n        @test variance(a) == 9.166666666666666\n\n        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n        @test variance(a) == 9.166666666666666\n\n        a = [12, 15, 17, 20]\n\n        @test variance(a) == 11.333333333333334\n\n    end\n\nend\n", "meta": {"hexsha": "5058fae2c86fb96aea06d049133d6a734ddd3e51", "size": 972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/statistics.jl", "max_stars_repo_name": "ErikQQY/Julia", "max_stars_repo_head_hexsha": "a2719896939e8c4f28816d63e1d98298905cba39", "max_stars_repo_licenses": ["MIT"], "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/statistics.jl", "max_issues_repo_name": "ErikQQY/Julia", "max_issues_repo_head_hexsha": "a2719896939e8c4f28816d63e1d98298905cba39", "max_issues_repo_licenses": ["MIT"], "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/statistics.jl", "max_forks_repo_name": "ErikQQY/Julia", "max_forks_repo_head_hexsha": "a2719896939e8c4f28816d63e1d98298905cba39", "max_forks_repo_licenses": ["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.6046511628, "max_line_length": 64, "alphanum_fraction": 0.5164609053, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102580527664, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7597155817485681}}
{"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\u0302[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\u0302[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 \u03c41 and \u03c42\");\n\u03c41 = Float64[];\n\u03c42 = Float64[];\nfor a in [1:5]\n  corra = autocorrelation(N1, v1, a, ns);\n  corra /= corra[1];                          # Normalize\n  push!(\u03c41,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!(\u03c42,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\u03c4\u03021v$i:\\t$(\u03c41[i])\");\nend\nprintln(\"\\n\\tEstimated Autocorrelation Times for N2 = $N2:\\n\");\nfor i in [1:5]\n  println(\"\\t\\t\u03c4\u03022v$i:\\t$(\u03c42[i])\");\nend\nprintln(\"\\n\\tThe estimated autocorrelation times are clearly far better for the larger sample.\");\n\n# Estimate standard deviation\n\u03c31 = Float64[];\n\u03c32 = Float64[];\nprintln(\"\\n\\tCreating estimators \u03c31 for the standard deviation for N1 = $N1\");\nfor a in [1:5]\n  diff1 = v1[:,a] .- mean(v1[:,a]);\n  \u03c31a = sqrt( dot( diff1, diff1 ) / (N1-1) );\n  println(\"\\t\\t\u03c3\u03021[$a] = $\u03c31a\");\n  push!(\u03c31, \u03c31a);\nend\nprintln(\"\\n\\tCreating estimators \u03c32 for the standard deviation for N2 = $N2\");\nfor a in [1:5]\n  diff2 = v2[:,a] .- mean(v2[:,a]);\n  \u03c32a = sqrt( dot( diff2, diff2 ) / (N2-1) );\n  println(\"\\t\\t\u03c3\u03022[$a] = $\u03c32a\");\n  push!(\u03c32, \u03c32a);\nend\n\n# Estimate standard deviation of the sample mean\n\u03c3N1 = sqrt( 2 / N1 .* \u03c41 ) .* \u03c31;\n\u03c3N2 = sqrt( 2 / N2 .* \u03c42 ) .* \u03c32;\nprintln(\"\\n\\tEstimating standard deviations of the sample mean for N1 = $N1:\");\nfor i in [1:5]\n  println(\"\\n\\t\\t\u03c3\u0302N1[$i] = $(\u03c3N1[i])\");\nend\nprintln(\"\\n\\tEstimating standard deviations of the sample mean for N2 = $N2:\");\nfor i in [1:5]\n  println(\"\\n\\t\\t\u03c3\u0302N2[$i] = $(\u03c3N2[i])\");\nend\n\n# Compare to the actual measured values of the standard deviations of the sample mean\nsigmean1 = \u03c3\u03021./\u03c3N1;\nsigmean2 = \u03c3\u03022./\u03c3N2;\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\u03c3\u03021[$i] / \u03c3\u0302N1[$i] = $(sigmean1[i])\");\nend\nprintln(\"\\n\\tFind the ratio for N2 = $N2:\")\nfor i in [1:5]\n  println(\"\\n\\t\\t\u03c3\u03022[$i] / \u03c3\u0302N2[$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\u03041 = zeros(5);\nv\u03042 = zeros(5);\nfor i in [1:5]\n  v\u03041[i] = mean(v1[:,i]);\n  v\u03042[i] = mean(v2[:,i]);\nend\n\n# Finally, compare the normalized covariance matrices \u03c11 and \u03c12 to the true value \u03c1\u0302.\nprintln(\"\\n\\tFinally, estimate the normalized covariance matrices \u03c11 and \u03c12.\\n\");\nprintln(\"\\tEstimating the covariance matrix c1 for sample size N1 = $N1\");\nD1 = v1 - ones(N1) * transpose(v\u03041);\nc1 = transpose(D1) * D1 / N1;\nprintln(\"\\tEstimating the covariance matrix c2 for sample size N2 = $N2\");\nD2 = v2 - ones(N2) * transpose(v\u03042);\nc2 = transpose(D2) * D2 / N2;\n\nprintln(\"\\tEstimating the normalized covariant matrix \u03c11 for N1 = $N1\");\n\u03c11 = c1 ./ ( \u03c31 * transpose(\u03c31) );\nprintln(\"\\tEstimating the normalized covariant matrix \u03c12 for N2 = $N2\");\n\u03c12 = c2 ./ ( \u03c32 * transpose(\u03c32) );\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 \u00b1 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 \u00b1 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 \u00b1 $(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": "@testset \"incomplete objective\" begin\n    function myfun!(F, J, x)\n           if !(F == nothing)\n               F[1] = (x[1]+3)*(x[2]^3-7)+18\n               F[2] = sin(x[2]*exp(x[1])-1)\n           end\n\n           if !(J == nothing)\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\n           end\n    end\n\n    r = nlsolve(only_fj!(myfun!), [0.5, 0.5])\n    @test norm(r.zero - [0.0, 1.0], Inf) < 1e-8\n\n    function myfun(x)\n        F = similar(x)\n        F[1] = (x[1]+3)*(x[2]^3-7)+18\n        F[2] = sin(x[2]*exp(x[1])-1)\n\n\n        J = NLSolversBase.alloc_DF(x, F)\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\n\n        F, J\n    end\n    r = nlsolve(only_fj(myfun), [0.5, 0.5])\n    @test norm(r.zero - [0.0, 1.0], Inf) < 1e-8\nend\n", "meta": {"hexsha": "2fb47867473703fc0f17e75277c2d58e40263adb", "size": 971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/incomplete.jl", "max_stars_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_stars_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": "test/incomplete.jl", "max_issues_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_issues_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": "test/incomplete.jl", "max_forks_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_forks_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": 25.5526315789, "max_line_length": 50, "alphanum_fraction": 0.3717816684, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7596657911428631}}
{"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": "# Test utililties.jl\n\n# Tests could be more comprehensive (of course).  In some cases all\n# that is done is to execute the function in some way just to make\n# sure no exceptions are thrown as a result of something breaking with\n# a new version of Julia.\n\nprintln(\"testing utilites\")\n\n# bbspline\nP = [0 1 2 3\n     0 1 2 3]\nk = 3\nN = 10\nS = bbspline(P, k, N)\ndx = gradient(vec(S[1,:]))\ndy = gradient(vec(S[2,:]))\nslope = dy./dx\n@test maximum(slope - 1) < 1e-3\n\n# pbspline\nP = [0 1 2 3 0\n     0 1 2 3 0]\nk = 3\nN = 100\nS = pbspline(P, k, N)\n\n# gaussfilt1d\na = zeros(20,1)\na[10] = 1\nsigma = 2\nsa = gaussfilt1d(a, sigma)\n@test abs(sa[10] - 0.282) < 1e-3\n@test abs(sum(sa) - 1) < 1e-3\n\n# interp1\nx = [0, 2, 7]\ny = 2*x\nxi = [1.1, 0.5, 6]\nyi = interp1(x,y,xi)\n@test maximum(abs(yi - 2*xi) .< eps())\n\n# normalise\na = rand(5,3)\nan = normalise(a)\n@test isapprox(minimum(an), 0)\n@test isapprox(maximum(an), 1)\n\nreqmean = 5\nreqvar = 7\nan = normalise(a, reqmean, reqvar)\n@test isapprox(mean(an), reqmean)\n@test isapprox(var(an), reqvar)\n\n# histtruncate\nrows = 100;\ncols = 200;\nimg = rand(rows, cols)\nlHistCut = 2\nuHistCut = 4\nhtimg = histtruncate(img, lHistCut, uHistCut)\nminval = minimum(htimg)\nmaxval = maximum(htimg)\n# Check that the number of saturated pixels at each extreme is\n# approximately lHistCut and uHistCut. Note some integer rounding has\n# to occur.\nv = find(abs(htimg-minval).<eps())\n@test abs(length(v)/(rows*cols) * 100 - lHistCut) < 1\n\nv = find(abs(htimg-maxval).<eps())\n@test abs(length(v)/(rows*cols) * 100 - uHistCut) < 1\n\n# sineramp\nsr = sineramp()\nsr = sineramp((256, 512), 12.5, 8, 2)\n\n# circlesineramp\n(img, alpha) = circlesineramp()\n(img, alpha) = circlesineramp(512, pi/10, 8, 2, false)\n\n# meshgrid\nxrange = -3:2\nyrange = 2:.5:6\n(x,y) = meshgrid(xrange, yrange) # two arguments\n(rows,cols) = size(x)\nfor r = 1:rows\n    @test all(x[r:r,:] .== xrange')\nend\nfor c = 1:cols\n    @test all(y[:,c:c] .== yrange)\nend\n\narange = 2:.1:4\n(x,y) = meshgrid(arange)  # one argument\n(rows,cols) = size(x)\nfor r = 1:rows\n    @test all(x[r:r,:] .== arange')\nend\nfor c = 1:cols\n    @test all(y[:,c:c] .== arange)\nend\n", "meta": {"hexsha": "c68280f505cc5ac57e8458ce01a12f788291cf19", "size": 2111, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_utilities.jl", "max_stars_repo_name": "JuliaPackageMirrors/PerceptualColourMaps.jl", "max_stars_repo_head_hexsha": "d58b5d3064ff9ea1a70ad2a17577b8d1c928d317", "max_stars_repo_licenses": ["MIT"], "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_utilities.jl", "max_issues_repo_name": "JuliaPackageMirrors/PerceptualColourMaps.jl", "max_issues_repo_head_hexsha": "d58b5d3064ff9ea1a70ad2a17577b8d1c928d317", "max_issues_repo_licenses": ["MIT"], "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_utilities.jl", "max_forks_repo_name": "JuliaPackageMirrors/PerceptualColourMaps.jl", "max_forks_repo_head_hexsha": "d58b5d3064ff9ea1a70ad2a17577b8d1c928d317", "max_forks_repo_licenses": ["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.6960784314, "max_line_length": 70, "alphanum_fraction": 0.6376125059, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7596428056790352}}
{"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}, \u03bb=one(T))\n    M = nmodes(bas)\n    Q = nquad(bas)\n    \u03d5 = 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 += \u03d5[q,k] * \u03d5[q, i] * wJ[q] \n            end\n            mass[k,i] += m*\u03bb\n            if k != i\n                mass[i,k] += m*\u03bb\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}, \u03bb=one(T))\n\n    M = nmodes(bas)\n    wJ = jacweights(el)\n\n    for i = 1:M\n        mass[i,i] += wJ[i]*\u03bb\n    end\nend\n\n\nmass_matrix{T<:Number}(bas::GenBasis1d, el::Element1d{T}, \u03bb=one(T)) =\n    add_mass_matrix!(bas, el, zeros(T, nmodes(bas), nmodes(bas)), \u03bb)\n\n   \n\nfunction add_mass_matrix!{T<:Number}(bas::SEM1d{T}, el::Element1d, mass::AbstractMatrix{T}, \u03bb::AbstractVector{T})\n\n    M = nmodes(bas)\n    wJ = jacweights(el)\n\n    for i = 1:M\n        mass[i,i] += wJ[i]*\u03bb[i]\n    end\nend\n\nfunction add_mass_matrix!{T<:Number}(bas::GenBasis1d, el::Element1d, mass::AbstractMatrix{T}, \u03bb::AbstractVector{T})\n    M = nmodes(bas)\n    Q = nquad(bas)\n    \u03d5 = 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 += \u03d5[q,k] * \u03d5[q, i] * wJ[q] * \u03bb[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}, \u03bb=one(T))\n    M = nmodes(bas)\n    Q = nquad(bas)\n    d\u03d5 = dqbasis(bas)\n    D = diffmat(bas)\n    wJ = jacweights(el)\n    d\u03bedx = deriv_\u03be(el)\n    for k = 1:M\n        for i = k:M\n            L = zero(T)\n            for q = 1:Q\n                L += d\u03d5[q,i] * d\u03d5[q,k] *wJ[q] * (d\u03bedx[q]^2)*\u03bb\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}, \u03bb=one(T)) =\n    add_stiff_matrix!(bas, el, zeros(T, nmodes(bas), nmodes(bas)), \u03bb)\n\nfunction add_stiff_matrix!{T<:Number}(bas::GenBasis1d, el::Element1d, mat::AbstractMatrix{T},\n                                      \u03bb::AbstractVector{T})\n    M = nmodes(bas)\n    Q = nquad(bas)\n    d\u03d5 = dqbasis(bas)\n    D = diffmat(bas)\n    wJ = jacweights(el)\n    d\u03bedx = deriv_\u03be(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\u03d5[q,i] * d\u03d5[q,k] *wJ[q] * (d\u03bedx[q]^2)*\u03bb[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    \u03d5 = 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] * \u03d5[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 * \u03c0) - 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": "using ModelingToolkit, ParameterizedFunctions\n\n### Capture MATLABDiffEq.jl type issues\n@parameters t a b c d\n@variables x(t) y(t)\nD = Differential(t)\neqs = [D(x) ~ a*x - b*x*y\n       D(y) ~ -c*y + d*x*y]\nsys = ODESystem(eqs)\nequations(sys)\nmatstr = Symbolics.build_function(map(x->x.rhs,equations(sys)),states(sys),\n                                        parameters(sys),independent_variable(sys),\n                                        target = ModelingToolkit.MATLABTarget())\n@test matstr == \"diffeqf = @(t,internal_var___u) [\n  internal_var___p(1) * internal_var___u(1) + -1 * internal_var___p(2) * internal_var___u(1) * internal_var___u(2);\n  -1 * internal_var___p(3) * internal_var___u(2) + internal_var___p(4) * internal_var___u(1) * internal_var___u(2);\n];\n\"\n\nf = @ode_def_bare LotkaVolterra begin\n  dx = a*x - b*x*y\n  dy = -c*y + d*x*y\nend a b c d\np = [1.5,1,3,1]\ntspan = (0.0,10.0)\nu0 = [1.0,1.0]\nprob = ODEProblem(f,u0,tspan,p)\n\nsys = modelingtoolkitize(prob)\n[eq.rhs for eq \u2208 equations(sys)]\nmatstr = Symbolics.build_function(map(x->x.rhs,equations(sys)),states(sys),\n                                        parameters(sys),independent_variable(sys),\n                                        target = ModelingToolkit.MATLABTarget())\n@test matstr == \"diffeqf = @(t,internal_var___u) [\n  internal_var___p(1) * internal_var___u(1) - internal_var___p(2) * internal_var___u(1) * internal_var___u(2);\n  internal_var___u(2) * -(internal_var___p(3)) + internal_var___p(4) * internal_var___u(1) * internal_var___u(2);\n];\n\"\n", "meta": {"hexsha": "4dc98add0a56651b1d812ea844fb97159a2433a7", "size": 1526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/downstream/ParameterizedFunctions_MATLAB.jl", "max_stars_repo_name": "sharanry/Symbolics.jl", "max_stars_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 907, "max_stars_repo_stars_event_min_datetime": "2021-01-22T02:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:13:39.000Z", "max_issues_repo_path": "test/downstream/ParameterizedFunctions_MATLAB.jl", "max_issues_repo_name": "sharanry/Symbolics.jl", "max_issues_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 472, "max_issues_repo_issues_event_min_datetime": "2021-01-21T14:18:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:10:18.000Z", "max_forks_repo_path": "test/downstream/ParameterizedFunctions_MATLAB.jl", "max_forks_repo_name": "sharanry/Symbolics.jl", "max_forks_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2021-01-25T14:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T19:37:30.000Z", "avg_line_length": 39.1282051282, "max_line_length": 115, "alphanum_fraction": 0.6336828309, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7595895779628065}}
{"text": "using Distributions\nusing IndependentRandomSequences\nusing OrderStatistics\nusing Combinatorics\nusing Base.Test\n\n\n\u0393 = gamma\n\n\n#\n#Tests for Uniform Case\n#\nfor N = 3:5\n  U = Uniform()\n  sequence = IIDRandomSequence(U,N)\n\n  #scalar order statistics\n  Vs = orderstatistics(sequence)\n  @test map(mean,Vs) == collect(1:N)/(N+1)\n\n  #joint order statistics\n  fulljoint = sort(sequence)\n  @test jointorderstatistic(fulljoint) == fulljoint\n  @test_approx_eq_eps(pdf(fulljoint,collect(1:N)/(N+1)),\u0393(N+1),10^3*eps())\n  for n=2:N\n    for orders=combinations(N,n)\n      partialjoint = jointorderstatistic(sequence,orders)\n      @test mean(partialjoint ) == orders/(N+1)\n    end\n  end\n\n  #range\n  @test mean(range(sequence)) == (N-1)/(N+1)\n\n  #spacing\n  @test map(mean,spacings(sequence)) == ones(N+1)/(N+1)\n\n  #jointspacing\n  @test mean(jointspacing(sequence)) == ones(N+1)/(N+1)\n\n  #idempotency property\n\nend\n\n\n#\n# Qualitative ordering tests\n#\nN = 5\nfor X = [Uniform(),Normal(),Exponential()]\n  sequence = IIDRandomSequence(X,N)\n\n  #scalar order statistics\n  Ys = orderstatistics(sequence)\n  @test issorted(map(mean,Ys))\n  @test mean(Ys[1]) < mean(X)\n  @test mean(Ys[end]) > mean(X)\n\n  #joint order statistics\n  jYs = jointorderstatistics(sequence)\n  for jY=jYs\n    @test issorted(rand(jY))\n  end\n\nend\n", "meta": {"hexsha": "e8bbe59f750427bbded46c2bad1c7e0a203eb454", "size": 1288, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "gajomi/OrderStatistics.jl", "max_stars_repo_head_hexsha": "ae783ac760b1d27801e57782c1f7af870b1af9ab", "max_stars_repo_licenses": ["MIT"], "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": "gajomi/OrderStatistics.jl", "max_issues_repo_head_hexsha": "ae783ac760b1d27801e57782c1f7af870b1af9ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-08-19T05:21:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-16T21:04:52.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "gajomi/OrderStatistics.jl", "max_forks_repo_head_hexsha": "ae783ac760b1d27801e57782c1f7af870b1af9ab", "max_forks_repo_licenses": ["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.223880597, "max_line_length": 74, "alphanum_fraction": 0.6855590062, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7595895729748758}}
{"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 jInv.Mesh\nusing Test\n\n# setup 3D problem\nnc = [5, 7, 8]\nx0 = rand(3)\ndomain = [x0[1], 4, x0[2], 2, x0[3], 6]\nh   = (domain[2:2:end]-domain[1:2:end])./nc\nh1  = h[1]*ones(nc[1])\nh2  = h[2]*ones(nc[2])\nh3  = h[3]*ones(nc[3])\n\nMt = getTensorMesh3D(h1,h2,h3,x0)\nMr = getRegularMesh(domain,nc)\nMt2 = getTensorMesh3D(h1+rand(nc[1]),h2+rand(nc[2]),h3+rand(nc[3]),x0)\n\nMeshes = (Mt,Mr,Mt2)\n\nfor k=1:length(Meshes)\n\tM = Meshes[k]\n\tprint(\"\\ttesting differential operators for $(typeof(M))...\")\n\t@test norm(getDivergenceMatrix(M)*getCurlMatrix(M),Inf)<1e-12\n\t\n\tLap = getNodalLaplacianMatrix(M)\n\tG   = getNodalGradientMatrix(M)\n\t@test norm(Lap*ones(size(Lap,2))/M.nc) < 1e-10\n\t@test norm(G'*G- Lap,Inf) <1e-12\t\n\tprint(\"passed!\\n\")\nend\n\n\n", "meta": {"hexsha": "1f0f0e9c8d610dcc565cc151b5dcece198811103", "size": 730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Mesh/testDiffOps.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": "test/Mesh/testDiffOps.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": "test/Mesh/testDiffOps.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": 22.8125, "max_line_length": 70, "alphanum_fraction": 0.6397260274, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7595895701320902}}
{"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": "module PeriodicDarcyTests\n\nusing Gridap\nusing Test\nusing LinearAlgebra\n\nu(x) = VectorValue(x[1]*(x[1]-1)*(2x[2]-1.0),-x[2]*(x[2]-1.0)*(2x[1]-1.0))\np(x) = x[2]-0.5\nf(x) = VectorValue(x[1]*(x[1]-1)*(2x[2]-1.0),-x[2]*(x[2]-1.0)*(2x[1]-1.0)+1.0)\ng(x) = 0.0\n\ndomain = (0,1,0,1,0)\norder = 1\npartition = (4,4)\nmodel = CartesianDiscreteModel(domain,partition; isperiodic=(true,false))\n\nV = FESpace(model,ReferenceFE(raviart_thomas,Float64,order),conformity=:Hdiv,\n      dirichlet_tags=collect(1:6))\n\n\nQ = FESpace(model,ReferenceFE(lagrangian,Float64,order);\n      conformity=:L2, constraint=:zeromean)\n\nU = TrialFESpace(V,u)\nP = TrialFESpace(Q)\n\nY = MultiFieldFESpace([V, Q])\nX = MultiFieldFESpace([U, P])\n\ntrian = Triangulation(model)\ndegree = 2*(order)\nd\u03a9 = Measure(trian,degree)\nx = get_physical_coordinate(trian)\n\na((u, p),(v, q)) = \u222b( u\u22c5v - (\u2207\u22c5v)*p + q*(\u2207\u22c5u) )*d\u03a9\n\nb(( v, q)) = \u222b( v\u22c5f + q*g)*d\u03a9\n\n\nop = AffineFEOperator(a,b,X,Y)\nxh = solve(op)\nuh, ph = xh\n\neu = u - uh\nep = p - ph\n\nl2(v) = sqrt(sum(\u222b(v\u22c5v)*d\u03a9))\neu_l2 = l2(eu)\nep_l2 = l2(ep)\n\ntol = 1.0e-9\n@test eu_l2 < tol\n@test ep_l2 < tol\n\n\nend # module\n", "meta": {"hexsha": "8706605c78881dc3b28dcd10a9d28a624eeb0821", "size": 1102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/GridapTests/PeriodicDarcyTests.jl", "max_stars_repo_name": "aerappa/Gridap.jl", "max_stars_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 390, "max_stars_repo_stars_event_min_datetime": "2019-05-16T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:17.000Z", "max_issues_repo_path": "test/GridapTests/PeriodicDarcyTests.jl", "max_issues_repo_name": "aerappa/Gridap.jl", "max_issues_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 576, "max_issues_repo_issues_event_min_datetime": "2019-05-16T20:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:21:35.000Z", "max_forks_repo_path": "test/GridapTests/PeriodicDarcyTests.jl", "max_forks_repo_name": "aerappa/Gridap.jl", "max_forks_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2019-12-30T23:35:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:56:24.000Z", "avg_line_length": 19.3333333333, "max_line_length": 78, "alphanum_fraction": 0.6243194192, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7595392946630874}}
{"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    \u0394x = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h\u2080 = h(x[1])\n\n    all(h.(x) .\u2248 h(x[1])) || error(\"Filter width must be constant\")\n\n    if \u0394x .\u2248 2h\u2080\n        # Three point stencil\n        inds = [-1, 0, 1]\n        stencil = [-1 // 24, 13 // 12, -1 // 24]\n    elseif \u0394x .\u2248 h\u2080\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) \u2208 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    \u0394x = 1 // N * (domain.right - domain.left)\n    h = f.width\n    h\u2080 = h(x[1])\n\n    all(h.(x) .\u2248 h(x[1])) || error(\"Filter width must be constant\")\n    \u0394x .\u2248 2h\u2080 || 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) \u2208 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\u2081::Point_2D, p\u2082::Point_2D, p\u2083::Point_2D) = Triangle_2D(SVector(p\u2081, p\u2082, p\u2083))\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\u209c = Float64(r); s\u209c = Float64(s)\n    return (1 - r\u209c - s\u209c)*tri[1] + r\u209c*tri[2] + s\u209c*tri[3]\nend\n\nfunction area(tri::Triangle_2D)\n    # A = bh/2\n    # Let u\u20d7 = (v\u2082 - v\u2081), v\u20d7 = (v\u2083 - v\u2081)\n    # b = |u\u20d7|\n    # h = |sin(\u03b8) v\u20d7|, where \u03b8 is the angle between u\u20d7 and v\u20d7\n    # u\u20d7 \u00d7 v\u20d7 = |u\u20d7||v\u20d7| sin(\u03b8), hence\n    # A = |u\u20d7 \u00d7 v\u20d7|/2 = bh/2\n    u\u20d7 = tri[2] - tri[1]\n    v\u20d7 = tri[3] - tri[1]\n    # 2D cross product returns a scalar\n    return abs(u\u20d7 \u00d7 v\u20d7)/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 \u2208 1:3\n        npoints, point = l \u2229 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\u2081 = LineSegment_2D(tri[1], tri[2])\n        l\u2082 = LineSegment_2D(tri[2], tri[3])\n        l\u2083 = LineSegment_2D(tri[3], tri[1])\n        lines = [l\u2081, l\u2082, l\u2083]\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 \u2208  T]\n        return convert_arguments(LS, reduce(vcat, [pset[1] for pset \u2208 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 \u2208  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": "using JuliaUtils\nusing Test\n\n@testset \"LinearLS - two datapoints\" begin\n    x = [1, 2]\n    y = [4, 5]\n    ls = linearls(x, y)\n    @test ls.m == 1\n    @test ls.q == 3\nend\n\n@testset \"Newton - exp\" begin\n    f(x) = exp(x) - 1\n    x0 = 2\n    x = newton(f, x0, tol=1e-20, niters=10^3)\n    @test isapprox(x, 0, atol=1e-10)\nend", "meta": {"hexsha": "47e95d01660c4fed5a171bfdc9616da32a4d569e", "size": 320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 18.8235294118, "max_line_length": 45, "alphanum_fraction": 0.55, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871156, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7595392887229537}}
{"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) \u21a6 (x,y)\\\\\nx\u2295y \u2256 a\u2295b and x\u2295y\u2256x\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) \u21a6 (x,y)\\\\\nx\u2295y \u2256 a\u2295b and x\u2295y\u2256x\\\\\n *presumes* |a| \u2265 |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) \u21a6 (x,y)\\\\\nx\u2295y \u2256 a\u229db and x\u2295y\u2256x\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) \u21a6 (x,y)\\\\\nx\u2295y \u2256 a\u229db and x\u2295y\u2256x\\\\\n*presumes* |a| \u2265 |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    \u03b8::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, \u03b8::Vector{Float64}, pos::Vector{Float64}, v::Vector{Float64}, obs::Vector{Float64}; v_init=false)\n    \u03bc,\u03bb=\u03b8\n    l\u03bc=log(\u03bc^2/sqrt(\u03bc^2 + inv(\u03bb)))\n    l\u03c3=sqrt(log(1+(inv(\u03bb)/\u03bc^2)))\n    mod_lnormal=LogNormal(l\u03bc,l\u03c3)\n    log_lh=lps(logpdf.(mod_lnormal, obs))\n    v_init && (v=rand(MvNormal(length(\u03b8),1.)))\n\n    LogNormal_Model(trajectory, i, \u03b8, log_lh, pos, v)\nend\n\nfunction Base.show(io::IO, m::LogNormal_Model; xsteps=100)\n    \u03bc,\u03bb=m.\u03b8\n    l\u03bc=log(\u03bc^2/sqrt(\u03bc^2 + inv(\u03bb)))\n    l\u03c3=sqrt(log(1+(inv(\u03bb)/\u03bc^2)))\n    n=LogNormal(l\u03bc,l\u03c3)\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(\"\u03b8: $(m.\u03b8)\")\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: \u2218\n\nabstract type AbstractMobiusTransformation{T <: Number} <: Function end\n\n\"\"\"\n    MobiusTransformation(a,b,c,d)\n\nM\u00f6bius 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\u00f6bius 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\u00f6bius 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\u00f6biusTransformation{$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\u00f6bius 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\u00f6bius 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\u00f6bius 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) \u2248 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\u00f6bius 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\u00f6bius transformations.\n\"\"\"\n\u2218(f::AbstractMobiusTransformation, g::AbstractMobiusTransformation) = compose(f,g)\n\n\n\"\"\"\n    maptozerooneinf(z1,z2,z3)\n\nCreate the M\u00f6bius 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\u00f6bius 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\u00f6bius 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\u2218f\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\u00f6bius 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 \u2248 0.0\n    return Circle( f(c.center), abs(f.a/f.d)*c.radius )\n  elseif abs(c.center + f.d/f.c) \u2248 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) \u2248 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 \u2248 0.0\n    return Arc( f(c.center), f(c.p1), f(c.p2) )\n  elseif abs(c.center + f.d/f.c) \u2248 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) \u2248 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 \u2248 0.0\n    w1 = f(l.base)\n    return Line( w1, angle(w1-f(l.base+exp(l.angle*im))) )\n  elseif l.base \u2248 -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 \u2248 l.angle || a \u2248 (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 \u2248 0\n    return Line(l.base, l.angle + angle(f.b))\n  else\n    a = angle(l.base)\n    if a \u2248 l.angle || a \u2248 (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 \u2248 0.0\n    return LineSegment( f(l.p1), f(l.p2) )\n  elseif l.p1 \u2248 -f.d/f.c\n    # ToDo! Ray\n  elseif l.p2 \u2248 -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 \u2248 0\n    # ToDo! Ray\n  elseif l.p2 \u2248 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": "function fl(k)\n#\n#  generalization of Farmer-Loizou example:\n#\n#    (x-1)^4k * (x-2)^3k * (x-3)^2K * (x-4)^k\n#\n    p = poly([ones(4*k);2*ones(3*k);3*ones(2*k);4*ones(k)])\n    z = [1.0 4k; 2 4k; 3 2k; 4 k]\n    p, PolyZeros(z)\nend\n", "meta": {"hexsha": "25795e4aeabf0dad3c743f6f2e2de3ec71798c80", "size": 229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsuit/fl.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": "test/testsuit/fl.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": "test/testsuit/fl.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": 20.8181818182, "max_line_length": 59, "alphanum_fraction": 0.519650655, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7595131686395343}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    TaubinSmoothing(n; \u03bb=0.5, \u03bc=-0.5)\n\nPerform `n` iterations of Taubin smoothing with parameters `\u03bb` and `\u03bc`.\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  \u03bb::Float64\n  \u03bc::Float64\nend\n\nfunction TaubinSmoothing(n; \u03bb=0.5, \u03bc=-0.5)\n  @assert n > 0 \"invalid number of iterations\"\n  @assert 0 < \u03bb \u2264 -\u03bc < 1 \"invalid parameters \u03bb and \u03bc\"\n  TaubinSmoothing(n, \u03bb, \u03bc)\nend\n\nfunction smooth(mesh, method::TaubinSmoothing)\n  n = method.n\n  \u03bb = method.\u03bb\n  \u03bc = method.\u03bc\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 + \u03bb*L*V\n    V = V + \u03bc*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\u03b3 = 2 # parameter from CRRA utility\n\u03c6 = .5 # frisch elasticity\n\u03c1 = 0.05 # the discount rate\nr = 0.03\nw = 1.0\n\nz1=.1\nz2 =.2\nz= [z1 z2]\n\n\u03bb1 = 1.5\n\u03bb2 = 1.0\n\n\u03bb = [\u03bb1 \u03bb2]\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\u0394 = 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 \u03bb process\nAswitch = [-1*sparse(I,H,H)*\u03bb[1] sparse(I,H,H)*\u03bb[1]; sparse(I,H,H)*\u03bb[2] -1*sparse(I,H,H)*\u03bb[2]]\n\nx0 = (w*z1)^(\u03c6*(1-\u03b3)/(1+\u03b3*\u03c6)) #inital value for labor\n\n# create function for labor supply\nlabor_solve(l, a, z, w, r, \u03b3, \u03c6) = (l .- ((w*z*l .+ r*a).^(-\u03b3*\u03c6))*(w*z)^\u03c6)\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, \u03b3, \u03c6)\n    l01 = find_zero(l_solve1,x0)\n\n    l_solve2(l) = labor_solve(l, a[i], z2, w, r, \u03b3, \u03c6)\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-\u03b3)/(1-\u03b3)/\u03c1\nv0[:,2] = (w*z[2].*l0[1,2] .+ r.*a).^(1-\u03b3)/(1-\u03b3)/\u03c1\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).^(-\u03b3) # 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).^(-\u03b3)\n\n    # Find consumption and savings with the forward difference\n    cf = dVf.^(-1/\u03b3)\n    lf = (dVf.*w.*zz).^\u03c6\n    sf = w*zz.*lf +r.*aa -cf\n\n    # Find consumption and savings with the backward difference\n    cb= dVb.^(-1/\u03b3)\n    lb = (dVb.*w.*zz).^\u03c6\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.^(-\u03b3)\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-\u03b3)/(1-\u03b3) - l.^(1+1/\u03c6)/(1+1/\u03c6)\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 = (\u03c1 +1/\u0394)*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/\u0394\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": "module CDLagrangianFESpacesTests\n\nusing Test\nusing Gridap.Geometry\nusing Gridap.ReferenceFEs\nusing Gridap.FESpaces\nusing Gridap.CellData\nusing Gridap.TensorValues\nusing Gridap.Fields\n\ndomain =(0,1,0,1)\npartition = (3,3)\nmodel = CartesianDiscreteModel(domain,partition)\ntrian = get_triangulation(model)\n\n# order = 1\norders = (2,1)\norder = 2*max(orders...)\n\nT = VectorValue{2,Float64}\nreffe = LagrangianRefFE(T,QUAD,orders)\nV = FESpace(model=model,reffe=reffe,conformity=CDConformity((DISC,CONT)))#),dirichlet_tags = [1,6])\ntest_single_field_fe_space(V)\n\nu(x) = x\n\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\ntrian = Triangulation(model)\nquad = CellQuadrature(trian,order)\nel2 = sqrt(sum(integrate(inner(e,e),trian,quad)))\n@test el2 < 1.0e-10\n\nreffe = LagrangianRefFE(T,QUAD,2)\nV = FESpace(model=model,reffe=reffe,conformity=CDConformity((CONT,DISC)))\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(integrate(inner(e,e),trian,quad)))\n@test el2 < 1.0e-10\n\nreffe = LagrangianRefFE(T,QUAD,(2,1))\nV = FESpace(model=model,reffe=reffe,conformity=CDConformity((DISC,CONT)))\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(integrate(inner(e,e),trian,quad)))\n@test el2 < 1.0e-10\n\nreffe = LagrangianRefFE(T,QUAD,(2,0))\nV = FESpace(model=model,reffe=reffe,conformity=CDConformity((CONT,DISC)))\nu(x) = VectorValue(x[1],0.0)\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(integrate(inner(e,e),trian,quad)))\n@test el2 < 1.0e-10\n\nreffe = LagrangianRefFE(T,QUAD,(2,0))\nV = FESpace(model=model,reffe=reffe,conformity=CDConformity((DISC,DISC)))\nu(x) = VectorValue(x[1],0.0)\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(integrate(inner(e,e),trian,quad)))\n@test el2 < 1.0e-10\n\n\n# # Skeleton triangulation\n# face_own_dofs = get_face_own_dofs(reffe)\n# strian = SkeletonTriangulation(model,reffe,face_own_dofs)\n# ns = get_normal_vector(strian)\n# writevtk(strian,\"strian\",cellfields=[\"normal\"=>ns])\n#\n# # Random function for visualization purposes\n# model = CartesianDiscreteModel((0,1,0,1),(10,5))\n# V = FESpace(model=model,reffe=reffe,conformity=true)\n# trian = Triangulation(model)\n# vh = FEFunction(V,rand(num_free_dofs(V)))\n# writevtk(trian,\"trian\",nsubcells=20,cellfields=[\"vh\"=>vh])\n\n#using Gridap.Visualization\n#\n#writevtk(trian,\"trian\",nsubcells=10,cellfields=[\"uh\"=>uh])\n\nend # module\n", "meta": {"hexsha": "06541fdf8111b5b89cb88161ebf92b515c6b1c41", "size": 2373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FESpacesTests/CDLagrangianFESpacesTests.jl", "max_stars_repo_name": "barche/Gridap.jl", "max_stars_repo_head_hexsha": "70325414653cf0b9822770b150fb082d1a0a5f78", "max_stars_repo_licenses": ["MIT"], "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/FESpacesTests/CDLagrangianFESpacesTests.jl", "max_issues_repo_name": "barche/Gridap.jl", "max_issues_repo_head_hexsha": "70325414653cf0b9822770b150fb082d1a0a5f78", "max_issues_repo_licenses": ["MIT"], "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/FESpacesTests/CDLagrangianFESpacesTests.jl", "max_forks_repo_name": "barche/Gridap.jl", "max_forks_repo_head_hexsha": "70325414653cf0b9822770b150fb082d1a0a5f78", "max_forks_repo_licenses": ["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.9659090909, "max_line_length": 99, "alphanum_fraction": 0.7243994943, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7594702662485489}}
{"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] \u2208 (: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] \u2208 (: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\u2080, 1.0) on the left and (x\u2081, 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\u2080, x\u2081) == pos_unit(x\u2081, x\u2080)\n\"\"\"\nneg_unit(x0, x1) = :($(1/(x0-x1)) * (x - $x1))\n\"\"\"\nConstruct a symbolic expression for a line between the points (x\u2080, 0.0) on the left and (x\u2081, 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\u2080, x\u2081) == pos_unit(x\u2081, x\u2080)\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) = \u03a3\u1d62(y\u1d62\u22c5g\u1d62(x\u1d62))` where `g\u1d62(x\u2c7c) = \u03b4\u1d62\u2c7c`\nHere in the 1D case, `g\u1d62 = max(0, y\u1d62*min(L1, L2))`, where `L1` and `L2` are the lines \"ramping up\" towards x\u1d62\nand \"ramping down\" away from x\u1d62. 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\u1d62 = :($(y[i]) * max(0, min($L1, $L2)))\n        push!(G, g\u1d62)\n    end\n    # first and last points are special cases that ignore the min\n    g\u2080 = :($(y[1]) * max(0, $(neg_unit(x[1], x[2]))))\n    g\u1d63 = :($(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\u2080)\n    push!(G, g\u1d63)\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 \u2209 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\u2010Distance 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# \u2554\u2550\u2561 0bdd0fc6-9203-11eb-1ea3-9fe58aca7da0\nusing SymPy, LinearAlgebra\n\n# \u2554\u2550\u2561 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 \u2207) \\vec w(x,y,z).$$\n\"\n\n# \u2554\u2550\u2561 c75d36c0-923c-11eb-0477-c3101e21f880\nx,y,z=symbols(:x),symbols(:y),symbols(:z)\n\n# \u2554\u2550\u2561 1b261092-923a-11eb-01d6-7f705b30d46e\nbegin\n\t\u2202x(f::Sym) = diff(f,x)\n\t\u2202y(f::Sym) = diff(f,y)\n\t\u2202z(f::Sym) = diff(f,z)\n\t\u2207=[\u2202x,\u2202y,\u2202z]\nend\n\n# \u2554\u2550\u2561 1ca28980-925d-11eb-2be1-815a5df595ff\nbegin\n\timport Base.*\n\t*(\u2202x::typeof(\u2202x),f::Sym)=\u2202x(f)\n\t*(\u2202y::typeof(\u2202y),f::Sym)=\u2202y(f)\n\t*(\u2202z::typeof(\u2202z),f::Sym)=\u2202z(f)\n\t*(\u2207::Function,f::Sym)=\u2207(f)\n\tgrad(f)=\u2207*f\n\trot(u)=\u2207\u00d7u\n\timport LinearAlgebra.\u22c5\n\t\u22c5(\u2207::Array{Function,1},w::Array{Sym,1})=\u2207[1]*w[1]+\u2207[2]*w[2]+\u2207[3]*w[3]\n\tdiv(u)=\u2207\u22c5u\n\t\u22c5(a::Vector,\u2207::Array{Function,1})=a[1]*\u2207[1]+a[2]*\u2207[2]+a[3]*\u2207[3]\nend\n\n# \u2554\u2550\u2561 c2a476e6-e948-485f-9b2e-b6f821504263\n# Izvedeni operator a\u2207\nbegin\n\ta\u2202x(a::Vector,f::Sym) = a[1]*diff(f,x)\n\ta\u2202y(a::Vector,f::Sym) = a[2]*diff(f,y)\n\ta\u2202z(a::Vector,f::Sym) = a[3]*diff(f,z)\n\ta\u2207(a::Vector,f::Sym)=a\u2202x(a,f)+a\u2202y(a,f)+a\u2202z(a,f)\n\ta\u2207(a::Vector,w::Array{Sym,1})=[a\u2207(a,w[1]),a\u2207(a,w[2]),a\u2207(a,w[3])]\nend\n\n# \u2554\u2550\u2561 bd70ec2e-ad07-4526-aa70-5f25c86b444e\nmd\"\n## Primjeri\n\"\n\n# \u2554\u2550\u2561 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\u010dka\n\tT=(1,-1/2,2)\nend\n\n# \u2554\u2550\u2561 2b00c286-0807-4fa0-a9c2-6b1d56ae3716\nf\n\n# \u2554\u2550\u2561 66b9df0a-06c4-409c-9ae4-79b3cc3833b5\n\u2202x(f)\n\n# \u2554\u2550\u2561 9b816a31-675a-4dea-83e7-67430eeb741e\n\u2202x*f\n\n# \u2554\u2550\u2561 ec770eca-54d2-4394-b359-ad5e47218e92\na\u2207(a,f)\n\n# \u2554\u2550\u2561 3577e5e0-8fa8-4938-9119-b7c14f31e5be\na\u2207(a,u)\n\n# \u2554\u2550\u2561 2a47ed85-0691-4cb2-84b5-52facb4eda0b\n# Gradijent\n\u2207*f\n\n# \u2554\u2550\u2561 26292a50-9627-40a3-bacc-034de0882ac2\ngrad(f)\n\n# \u2554\u2550\u2561 8d4a98d1-414e-4714-9c94-6b6426388bc0\n# Gradijent u zadanoj to\u010dki\nsubs.(\u2207*f,x=>T[1],y=>T[2],z=>T[3])\n\n# \u2554\u2550\u2561 c62f2abe-b330-4e5b-8a73-c2ac5fe32284\n# Divergencija\n\u2207\u22c5u\n\n# \u2554\u2550\u2561 f141e418-574d-4a0f-903c-35ad8d3e6883\ndiv(u)\n\n# \u2554\u2550\u2561 0e012c70-afc3-410f-a73c-978783948cc3\n# Divergencija u zadanoj to\u010dki\nsubs(\u2207\u22c5u,x=>T[1],y=>T[2],z=>T[2])\n\n# \u2554\u2550\u2561 faea848e-f4d7-4476-993f-d9db5c6ca2ee\n# Rotor\n\u2207\u00d7u\n\n# \u2554\u2550\u2561 e3c9e5d1-8542-4940-8dd2-c60849b152c3\nrot(u)\n\n# \u2554\u2550\u2561 0496ef19-9e5c-4f5b-aa4b-22d98cfcf9a0\n# Rotor u zadanoj to\u010dki\nsubs.(\u2207\u00d7u,x=>T[1],y=>T[2],z=>T[3])\n\n# \u2554\u2550\u2561 ad3b7955-cd19-4aaf-8a98-b4727bafe572\n# Primjer svojstva\nrot(f*grad(g))\n\n# \u2554\u2550\u2561 93446240-2427-4964-9e3a-75f2de6b67e6\ngrad(f)\u00d7grad(g)\n\n# \u2554\u2550\u2561 44c1a521-657b-43c4-ac59-7a8e24bf25cc\n# Drugi primjer svojstva\nrot(w\u00d7u)\n\n# \u2554\u2550\u2561 54692583-1661-4b04-8f2c-94689630cff8\nexpand.(w*div(u)-u*div(w)+a\u2207(u,w)-a\u2207(w,u))\n\n# \u2554\u2550\u2561 fadb40e2-6c5e-48b2-a45f-88ea4f8cc4e5\n# Usmjerena derivacija skalarnog polja\na/norm(a)\u22c5grad(f)\n\n# \u2554\u2550\u2561 180512f7-c8e8-4aee-9872-0057d6fe9c5d\n# Usmjerena derivacija skalarnog polja u to\u010dki\nsubs(a/norm(a)\u22c5grad(f),x=>T[1],y=>T[2],z=>T[3])\n\n# \u2554\u2550\u2561 258fbdc7-7c24-4ecf-bc5a-468069f5c482\n# Skalarno polje najbr\u017ee raste u smjeru gradijenta\nsubs(grad(f)/norm(grad(f))\u22c5grad(f),x=>T[1],y=>T[2],z=>T[3])\n\n# \u2554\u2550\u2561 eeb8e757-668e-48c1-b560-076b3f47b5bf\n# Usmjerena derivacija vektorskog polja\na\u2207(a/norm(a),u)\n\n# \u2554\u2550\u2561 694962cc-cca2-4a4d-939d-7eb329de9917\n# Usmjerena derivacija vektorskog polja u to\u010dki\nsubs.(a\u2207(a/norm(a),u),x=>T[1],y=>T[2],z=>T[3])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500aa073e00-323c-11eb-0297-83e3db12248d\n# \u2560\u25500bdd0fc6-9203-11eb-1ea3-9fe58aca7da0\n# \u2560\u2550c75d36c0-923c-11eb-0477-c3101e21f880\n# \u2560\u25501b261092-923a-11eb-01d6-7f705b30d46e\n# \u2560\u25501ca28980-925d-11eb-2be1-815a5df595ff\n# \u2560\u2550c2a476e6-e948-485f-9b2e-b6f821504263\n# \u255f\u2500bd70ec2e-ad07-4526-aa70-5f25c86b444e\n# \u2560\u2550fd3305b2-923a-11eb-15c4-5b79db40bf46\n# \u2560\u25502b00c286-0807-4fa0-a9c2-6b1d56ae3716\n# \u2560\u255066b9df0a-06c4-409c-9ae4-79b3cc3833b5\n# \u2560\u25509b816a31-675a-4dea-83e7-67430eeb741e\n# \u2560\u2550ec770eca-54d2-4394-b359-ad5e47218e92\n# \u2560\u25503577e5e0-8fa8-4938-9119-b7c14f31e5be\n# \u2560\u25502a47ed85-0691-4cb2-84b5-52facb4eda0b\n# \u2560\u255026292a50-9627-40a3-bacc-034de0882ac2\n# \u2560\u25508d4a98d1-414e-4714-9c94-6b6426388bc0\n# \u2560\u2550c62f2abe-b330-4e5b-8a73-c2ac5fe32284\n# \u2560\u2550f141e418-574d-4a0f-903c-35ad8d3e6883\n# \u2560\u25500e012c70-afc3-410f-a73c-978783948cc3\n# \u2560\u2550faea848e-f4d7-4476-993f-d9db5c6ca2ee\n# \u2560\u2550e3c9e5d1-8542-4940-8dd2-c60849b152c3\n# \u2560\u25500496ef19-9e5c-4f5b-aa4b-22d98cfcf9a0\n# \u2560\u2550ad3b7955-cd19-4aaf-8a98-b4727bafe572\n# \u2560\u255093446240-2427-4964-9e3a-75f2de6b67e6\n# \u2560\u255044c1a521-657b-43c4-ac59-7a8e24bf25cc\n# \u2560\u255054692583-1661-4b04-8f2c-94689630cff8\n# \u2560\u2550fadb40e2-6c5e-48b2-a45f-88ea4f8cc4e5\n# \u2560\u2550180512f7-c8e8-4aee-9872-0057d6fe9c5d\n# \u2560\u2550258fbdc7-7c24-4ecf-bc5a-468069f5c482\n# \u2560\u2550eeb8e757-668e-48c1-b560-076b3f47b5bf\n# \u2560\u2550694962cc-cca2-4a4d-939d-7eb329de9917\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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.\u03bb = ((2*\u03c0/(problem.b-problem.a)) * [0:problem.N\u00f72; -(problem.N\u00f72)+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.\u03bb = ((2*\u03c0/(problem.b-problem.a)) * [0:problem.N\u00f72; -(problem.N\u00f72)+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.\u03bb = ((\u03c0/(problem.b-problem.a)) * [0:problem.N\u00f72; -(problem.N\u00f72)+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.\u03bb = ((\u03c0/(problem.b-problem.a)) * [0:problem.N\u00f72; -(problem.N\u00f72)+1:-1])^2;\n\n    # build rhs with odd extension\n    @. problem.rhs[problem.N\u00f72+1:end] = problem.f([problem.a; problem.x]);\n    problem.rhs[1:problem.N\u00f72] .= -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.\u03bb = ((\u03c0/(problem.b-problem.a)) * [0:problem.N\u00f72; -(problem.N\u00f72)+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.\u03bb = ((\u03c0/(problem.b-problem.a)) * [0:problem.N\u00f72; -(problem.N\u00f72)+1:-1])^2;\n\n    # build rhs with even extension\n    @. problem.rhs[problem.N\u00f72+1:end] = problem.f(problem.x[1:end-1]);\n    problem.rhs[1:problem.N\u00f72] .= 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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, StatsPlots, Plots\n\tRandom.seed!(0)\n end\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.18\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.18\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u2550bdabe54e-250a-11eb-1714-25afa772347e\n# \u255f\u2500475ff888-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": "# ### parametric function plot\n# http://docs.juliaplots.org/latest/examples/pyplot/\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\nx\u209c(t) = sin(t)\ny\u209c(t) = sin(2t)\n\nplot(x\u209c, y\u209c, 0, 2\u03c0, leg=false, fill=(0,:orange))\n", "meta": {"hexsha": "302684079c87ef422a4b1c906f627d05ec26dded", "size": 212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/parametric2d.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/parametric2d.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/parametric2d.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": 21.2, "max_line_length": 52, "alphanum_fraction": 0.6603773585, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7593988209106995}}
{"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\u22c5p <= 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 \u2208 1:3]\n@inline random_vec2(min::T, max::T) where T = @inbounds @SVector[random_between(min, max) for i \u2208 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\u22c5p <= 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": "using SimpleDrawing, LinearFractionalTransformations\n\nexport Circle\n\n\"\"\"\n    Circle\n\nRepresents a circle in the plane. Constructors:\n* `circle(x,y,r)` based on center coordinates and radius \n* `circle(z,r)` based on center given as a complex number and a radius\n* `circle(a,b,c)` based on three complex numbers that represent points on the circle\n\"\"\"\nstruct Circle <: Cline\n    x::Float64\n    y::Float64\n    r::Float64\n    function Circle(a::Real, b::Real, rad::Real)\n        rad >= 0 || error(\"Radius must be nonnegative\")\n        new(a, b, rad)\n    end\nend\n\nCircle(z::Complex, r::Real) = Circle(real(z), imag(z), r)\n\nfunction Circle(a::Complex, b::Complex, c::Complex)\n    z = find_center(a, b, c)\n    !isinf(z) || error(\"Cannot construct a circle through three collinear points\")\n    r = abs(a - z)\n    return Circle(z, r)\nend\n\n# copy constructor\nCircle(C::Circle) = Circle(C.x, C.y, C.r)\n\n# standard stuff\n\nexport radius, area, circumference, center\n\n\"\"\"\n    radius(C)\nReturn the radius of the circle.\n\"\"\"\nradius(C::Circle) = C.r\n\n\"\"\"\n    area(C)\nReturn the area of the circle.\n\"\"\"\narea(C::Circle) = \u03c0 * C.r * C.r\n\n\"\"\"\n    circumference(C)\nReturn the circumference of the circle.\n\"\"\"\ncircumference(C::Circle) = 2 * \u03c0 * C.r\n\nimport Plots: center\n\"\"\"\n    center(C)\nReturn the center of the circle as a complex number. \n\"\"\"\ncenter(C::Circle) = Complex(C.x, C.y)\n\n\"\"\"\n    three_points(C)\nReturn a list of three points on the circle `C`.\n\"\"\"\nfunction three_points(C::Circle)\n    z = center(C)\n    r = radius(C)\n    return [z + r * exp(k * (2\u03c0 * im / 3)) for k = 0:2]\nend\nexport three_points\n\nimport SimpleDrawing: draw\nconst _FILL_COLOR = :lightgray\nconst _LINE_COLOR = :black\n\n\"\"\"\n    draw(C::Circle, fill::Bool=false; args...)\nDraw the circle `C`. With `fill=true`, fill in the interior in color.\n\nExample:\n`draw(C,true,color=:yellow, linecolor=:red, fillalpha=0.3)`\n\"\"\"\nfunction draw(C::Circle, fill::Bool = false; args...)\n    if fill\n        draw_disc(\n            center(C),\n            radius(C);\n            linecolor = _LINE_COLOR,\n            color = _FILL_COLOR,\n            args...,\n        )\n    else\n        draw_circle(center(C), radius(C); linecolor = _LINE_COLOR, args...)\n    end\nend\n\n\ninclude(\"operations.jl\")\ninclude(\"kiss.jl\")\ninclude(\"inversion.jl\")\n", "meta": {"hexsha": "fe3e3c4bd94d52bfbc643b392ec5b972307a9311", "size": 2271, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Circles.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/Circles.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/Circles.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.8365384615, "max_line_length": 84, "alphanum_fraction": 0.6358432409, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8289388104343893, "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\u03ba = zeros(T_ret)\n\n# Directly from KV2010\n\u03c3_\u03b7 = 0.01\n\u03c3_z0 = 0.15\n\u03c3_\u03b5 = 0.05\n\nfunction net_labor_income(N, T_ret, \u03c3_\u03b5, \u03c3_\u03b7, \u03c3_z0, \u03ba)\n    Y = zeros(Float64, N, T_ret-1)\n    z_t1 = sqrt(\u03c3_z0) .* randn(N)\n\n    for t in 1:(T_ret-1)\n        z_t = z_t1 + sqrt(\u03c3_\u03b7) .* randn(N)\n        Y[:,t] = exp.( \u03ba[t] .+ z_t + sqrt(\u03c3_\u03b5) .* randn(N) )\n        z_t1 = copy(z_t)\n    end\n    return Y\nend\n\nY_igp = net_labor_income(N, T_ret, \u03c3_\u03b5, \u03c3_\u03b7, \u03c3_z0, \u03ba)\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_\u03b5 = tauchen(19,0.,sqrt(\u03c3_\u03b5))\ntauc_\u03b7 = tauchen(39,0.99999,sqrt(\u03c3_\u03b7))\n\ntauc_\u03b5.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": "module DGHeatEquationTests\n\nusing Gridap\nusing ForwardDiff\nusing LinearAlgebra\nusing Test\nusing GridapODEs.ODETools\nusing GridapODEs.TransientFETools\nusing Gridap.FESpaces: get_algebraic_operator\n\n\u03b8 = 0.2\n\nu(x,t) = (1.0-x[1])*x[1]*(1.0-x[2])*x[2]*t\nu(t::Real) = x -> u(x,t)\nf(t) = x -> \u2202t(u)(x,t)-\u0394(u(t))(x)\n\nL= 1.0\nn = 2\ndomain = (0,L,0,L)\npartition = (n,n)\nmodel = CartesianDiscreteModel(domain,partition)\n\norder = 2\n\nreffe = ReferenceFE(lagrangian,Float64,order)\nV0 = FESpace(\n  model,\n  reffe,\n  conformity=:L2\n)\nU = TransientTrialFESpace(V0)\n\n\u03a9 = Triangulation(model)\ndegree = 2*order\nd\u03a9 = Measure(\u03a9,degree)\n\n\u0393 = BoundaryTriangulation(model)\nd\u0393 = Measure(\u0393,degree)\nnb = get_normal_vector(\u0393)\n\n\u039b = SkeletonTriangulation(model)\nd\u039b = Measure(\u039b,degree)\nns = get_normal_vector(\u039b)\n\na(u,v) = \u222b(\u2207(v)\u22c5\u2207(u))d\u03a9\nb(v,t) = \u222b(v*f(t))d\u03a9\nm(u,v) = \u222b(v*u)d\u03a9\n\nh = 1.0 / n\n\u03b3 = order*(order+1)\na_\u0393(u,v) = \u222b( (\u03b3/h)*v*u - v*(\u2207(u)\u22c5nb) - (\u2207(v)\u22c5nb)*u )d\u0393\nb_\u0393(v,t) = \u222b( (\u03b3/h)*v*u(t) - (\u2207(v)\u22c5nb)*u(t) )d\u0393\n\na_\u039b(u,v) = \u222b( (\u03b3/h)*jump(v*ns)\u2299jump(u*ns) - jump(v*ns)\u2299mean(\u2207(u)) - mean(\u2207(v))\u2299jump(u*ns) )d\u039b\n\n\nres(t,u,v) = a(u,v) + m(\u2202t(u),v) + a_\u0393(u,v) + a_\u039b(u,v) - b(v,t) - b_\u0393(v,t)\njac(t,u,du,v) = a(du,v) + a_\u0393(du,v) + a_\u039b(du,v)\njac_t(t,u,dut,v) = m(dut,v)\n\nop = TransientFEOperator(res,jac,jac_t,U,V0)\n\nt0 = 0.0\ntF = 1.0\ndt = 0.1\n\nU0 = U(0.0)\nuh0 = interpolate_everywhere(u(0.0),U0)\n\nls = LUSolver()\nusing Gridap.Algebra: NewtonRaphsonSolver\node_solver = ThetaMethod(ls,dt,\u03b8)\n\nsol_t = solve(ode_solver,op,uh0,t0,tF)\n\nl2(w) = w*w\n\ntol = 1.0e-6\n_t_n = t0\n\nfor (uh_tn, tn) in sol_t\n  global _t_n\n  _t_n += dt\n  e = u(tn) - uh_tn\n  el2 = sqrt(sum( \u222b(l2(e))d\u03a9 ))\n  @test el2 < tol\nend\n\nend #module\n", "meta": {"hexsha": "b6c90ddcf9aedc93052b911c9cdf381890951dd6", "size": 1665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/TransientFEsTests/DGHeatEquationTests.jl", "max_stars_repo_name": "gridap/GridapTimeStepper.jl", "max_stars_repo_head_hexsha": "01d5e66531f587c973fe37b91cd9df7932dc5219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-31T00:37:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T05:42:11.000Z", "max_issues_repo_path": "test/TransientFEsTests/DGHeatEquationTests.jl", "max_issues_repo_name": "gridap/GridapTimeStepper.jl", "max_issues_repo_head_hexsha": "01d5e66531f587c973fe37b91cd9df7932dc5219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T07:08:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-15T15:03:36.000Z", "max_forks_repo_path": "test/TransientFEsTests/DGHeatEquationTests.jl", "max_forks_repo_name": "gridap/GridapTimeStepper.jl", "max_forks_repo_head_hexsha": "01d5e66531f587c973fe37b91cd9df7932dc5219", "max_forks_repo_licenses": ["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": 93, "alphanum_fraction": 0.6168168168, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7593988075834173}}
{"text": "@testset \"GramMatrix tests\" begin\n    @testset \"GramMatrix\" begin\n        @polyvar x y\n        P = GramMatrix{Int}((i,j) -> i + j, [x^2, x*y, y^2])\n        @test nvariables(P) == 2\n        @test variables(P) == [x, y]\n        Pp1 = 2x^4 + 6x^3*y + 12x^2*y^2 + 10x*y^3 + 6y^4 + 1\n        @test P + 1   == Pp1\n        @test P + 1.0 == Pp1\n        zP = zero(typeof(P))\n        @test isempty(zP.Q)\n        @test zP == 0\n        p = polynomial(P)\n        @test coefficients(p) == [2, 6, 12, 10, 6]\n        @test monomialtype(p) == typeof(x*y)\n        @test monomialtype(typeof(p)) == typeof(x*y)\n        @test monomials(p) == [x^4, x^3*y, x^2*y^2, x*y^3, y^4]\n        for i in 1:3\n            for j in 1:3\n                @test P[i, j] == i + j\n            end\n        end\n        for P in (GramMatrix((i,j) -> i * j, [y, x]),\n                  GramMatrix((i,j) -> (3-i) * (3-j), monovec([y, x])),\n                  GramMatrix([1 2; 2 4], [y, x]),\n                  GramMatrix([4 2; 2 1], monovec([y, x])))\n            @test P.Q.Q == [4, 2, 1]\n            @test P.x[1] == x\n            @test P.x[2] == y\n        end\n        P = GramMatrix((i,j) -> ((i,j) == (1,1) ? 2 : 0), [x*y, x^2, y^2])\n        Q = GramMatrix([0 1; 1 0], [x^2, y^2])\n        @test P == Q\n        p = GramMatrix([2 3; 3 2], [x, y])\n        @test polynomial(p) isa AbstractPolynomial{Int}\n        @test polynomial(p, Float64) isa AbstractPolynomial{Float64}\n\n        @test -2*x + dot(-x - x^2, 0) + GramMatrix{Int}((i,j)->1, [1,x]) == -(-x^2 - 1)\n        P = GramMatrix{Int}((i,j) -> i + j, [x^2, x*y, y^2])\n        p = polynomial(P)\n        @test !iszero(P)\n        @test iszero(P-P)\n        @test iszero(P-p)\n        @test iszero(p-P)\n        @test P + P == P + p\n        @test x * P == x * p\n        @test 2 * P == 2 * p\n        @test P * (2x) == (2x) * p\n\n        @test differentiate(GramMatrix{Int}((i,j)->1, [x]), y) == 0\n        @test differentiate(GramMatrix{Int}((i,j)->1, [x, y]), y, 1) == 2x + 2y\n        #@inferred differentiate(GramMatrix{Int}((i,j)->1, [x, y]), y, 0) # FIXME failing at the moment\n\n        @test GramMatrix([2 3; 3 2], [x, y]) == 2x^2 + 2y^2 + 6x*y\n\n        mp = GramMatrix{Int}((i,j) -> i+j, [x])\n        @test norm(mp) == norm(mp, 2) == 2.0\n\n        @polyvar v[1:3]\n        P = [1 2 3; 2 4 5; 3 5 6]\n        p = GramMatrix(P, v)\n        #@inferred p(x => ones(3))\n        @test p(v => ones(3)) == 31\n        #@inferred subs(p, x => ones(3))\n        @test subs(p, v => ones(3)) == 31\n    end\n    @testset \"SOSDecomposition\" begin\n        @polyvar x y\n#       @test isempty(SOSDecomposition(typeof(x)[]))\n#       ps = [1, x + y, x^2, x*y, 1 + x + x^2]\n#       P = GramMatrix(SOSDecomposition(ps))\n#       P.Q == [2 0 1 0 1; 0 1 0 0 0; 1 0 2 1 1; 0 0 1 1 0; 1 0 1 0 2]\n#       P.x == [x^2, x*y, x, y, 1]\n#       @test P == P\n#       @test isapprox(GramMatrix(SOSDecomposition(P)), P)\n        @test sprint(show, SOSDecomposition([x+y, x-y])) == \"(x + y)^2 + (x - y)^2\"\n        @testset \"SOSDecomposition equality\" begin\n            @polyvar x y\n            @test !isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x+y]))\n            @test !isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x+y, x+y]))\n            @test isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x+y, x-y]))\n            @test isapprox(SOSDecomposition([x+y, x-y]), SOSDecomposition([x-y, x+y+1e-8]), ztol=1e-7)\n        end\n    end\nend\n", "meta": {"hexsha": "2f6ecdbe20beedfa1c193a7957db793d340c8ced", "size": 3423, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gram_matrix.jl", "max_stars_repo_name": "barpit20/SumOfSquares.jl", "max_stars_repo_head_hexsha": "8f64fca496ad29f2dc04241c864038ad2e2b78da", "max_stars_repo_licenses": ["MIT"], "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/gram_matrix.jl", "max_issues_repo_name": "barpit20/SumOfSquares.jl", "max_issues_repo_head_hexsha": "8f64fca496ad29f2dc04241c864038ad2e2b78da", "max_issues_repo_licenses": ["MIT"], "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/gram_matrix.jl", "max_forks_repo_name": "barpit20/SumOfSquares.jl", "max_forks_repo_head_hexsha": "8f64fca496ad29f2dc04241c864038ad2e2b78da", "max_forks_repo_licenses": ["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.8023255814, "max_line_length": 103, "alphanum_fraction": 0.461291265, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.75939880557346}}
{"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# title: 1680. Concatenation of Consecutive Binary Numbers\n# id: problem1680\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math\n# link: <https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/description/>\n# hidden: true\n# ---\n# \n# Given an integer `n`, return _the **decimal value** of the binary string\n# formed by concatenating the binary representations of _`1` _to_`n` _in order,\n# **modulo**_`109 + 7`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 1\n#     Output: 1\n#     Explanation: \"1\" in binary corresponds to the decimal value 1. \n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 3\n#     Output: 27\n#     Explanation: In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\n#     After concatenating them, we have \"11011\", which corresponds to the decimal value 27.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: n = 12\n#     Output: 505379714\n#     **Explanation** : The concatenation results in \"1101110010111011110001001101010111100\".\n#     The decimal value of that is 118505380540.\n#     After modulo 109 + 7, the result is 505379714.\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 105`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "9267c7874f2565af4cb010d6ec6312d83c34f3a4", "size": 1282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1680.concatenation-of-consecutive-binary-numbers.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/1680.concatenation-of-consecutive-binary-numbers.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/1680.concatenation-of-consecutive-binary-numbers.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.3666666667, "max_line_length": 96, "alphanum_fraction": 0.6060842434, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7593985416495453}}
{"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": "using PyPlot, PyCall\n\nnp = pyimport(\"numpy\")\n\norigin = \"lower\"\n\ndelta = 0.025\n\nx = y = np.arange(-3.0, 3.01, delta)\nX, Y = np.meshgrid(x, y)\nZ1 = @. np.exp(-X^2 - Y^2)\nZ2 = @. np.exp(-(X - 1)^2 - (Y - 1)^2)\nZ = (Z1 .- Z2) .* 2\n\nnr, nc = size(Z)\n\n# mask a circle in the middle:\ninterior = @. sqrt(X^2 + Y^2) < 0.5\nZ[interior] .= NaN\n\n# We are using automatic selection of contour levels;\n# this is usually not such a good idea, because they don't\n# occur on nice boundaries, but we do it here for purposes\n# of illustration.\n\nfig1, ax2 = plt.subplots(constrained_layout=true)\nCS = ax2.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin)\n\n# Note that in the following, we explicitly pass in a subset of\n# the contour levels used for the filled contours.  Alternatively,\n# We could pass in additional levels to provide extra resolution,\n# or leave out the levels kwarg to use all of the original levels.\n\nCS2 = ax2.contour(CS, levels=CS.levels[1:2:end], colors=\"r\", origin=origin)\n\nax2.set_title(\"1 masked region\")\nax2.set_xlabel(\"word length anomaly\")\nax2.set_ylabel(\"sentence length anomaly\")\n\n# Make a colorbar for the ContourSet returned by the contourf call.\ncbar = fig1.colorbar(CS)\ncbar.ax.set_ylabel(\"verbosity coefficient\")\n# Add the contour line levels to the colorbar\ncbar.add_lines(CS2)\n\nplt.show()\n\n", "meta": {"hexsha": "8662af5fce8363abf842be2729d1d455308d8bd2", "size": 1312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Python/test_contourf.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": "test/Python/test_contourf.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": "test/Python/test_contourf.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": 27.3333333333, "max_line_length": 75, "alphanum_fraction": 0.7019817073, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7593958884301385}}
{"text": "using ImageFeatures\n\nfunction random_circle_example()\n    dims = rand(100:200,2)\n    img = zeros(dims...)\n    r = rand(10:20)\n    x,y = rand(20:80,2)\n    for i in axes(img)[1]\n        for j in axes(img)[2]\n            if (x-i)^2 + (y-j)^2 <= r^2\n                img[i,j] = 1\n            end\n        end\n    end\n    img, [x,y], r\nend\n\n@testset \"Hough_Transform\" begin\n    @testset \"Hough Line Transform\" begin\n\n    #For images containing a straight line parallel to axes\n        for i in 1:9\n            img = zeros(Bool,9,9)\n            img[i,:] .= true\n            h = hough_transform_standard(img)\n            @test length(h) == 1\n            line = first(h)\n            @test line == (i, pi/2)\n        end\n\n    #For images with diagonal line\n        img = Matrix(Diagonal([true, true ,true]))\n        h = hough_transform_standard(img, angles=range(0,stop=pi,length=100))\n        @test length(h) == 1\n        @test h[1][1] == 0\n\n    #For a square image\n        img = zeros(Bool,10,10)\n        for i in 1:10\n            img[2,i] = img[i,2] = img[7,i] = img[i,9] = true\n        end\n        # h = hough_transform_standard(img,1,\n        h = hough_transform_standard(img, angles=range(0,stop=\u03c0/2,length=100))\n        @test length(h) == 4\n        r = [h[i][1] for i in CartesianIndices(size(h))]\n        @test all(r .== [2,2,7,9])\n        theta = [h[i][2] for i in CartesianIndices(size(h))]\n        er = sum(map((t1,t2) -> abs(t1-t2), theta, [0, \u03c0/2, \u03c0/2, 0]))\n        @test er <= 0.1\n    end\n\n    @testset \"Hough Circle Gradient\" begin\n        for _ in 1:10\n            img, c_truth, r_truth = random_circle_example()\n            img_edges = canny(img, (Percentile(80), Percentile(20)))\n            dx, dy=imgradients(img, KernelFactors.ando5)\n            img_phase = phase(dx, dy)\n            radii = 10:20\n            centers, rs = hough_circle_gradient(img_edges, img_phase, radii)\n            @test length(centers) == length(rs) == 1\n            c_hough = [Tuple(first(centers))...]\n            r_hough = first(rs)\n            @test r_hough \u2248 r_truth atol=4\n            @test c_hough \u2248 c_truth atol=4\n        end\n    end\nend\n", "meta": {"hexsha": "0cd6ee0374fa6fbdb0b1f55fe664183a69d04cf9", "size": 2128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/houghtransform.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ImageFeatures.jl-92ff4b2b-8094-53d3-b29d-97f740f06cef", "max_stars_repo_head_hexsha": "23929967aafe1544484394a965bd9206947ba437", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2016-08-11T07:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T17:46:22.000Z", "max_issues_repo_path": "test/houghtransform.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ImageFeatures.jl-92ff4b2b-8094-53d3-b29d-97f740f06cef", "max_issues_repo_head_hexsha": "23929967aafe1544484394a965bd9206947ba437", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 80, "max_issues_repo_issues_event_min_datetime": "2016-07-03T11:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-25T07:34:14.000Z", "max_forks_repo_path": "test/houghtransform.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ImageFeatures.jl-92ff4b2b-8094-53d3-b29d-97f740f06cef", "max_forks_repo_head_hexsha": "23929967aafe1544484394a965bd9206947ba437", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2017-02-19T22:06:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T04:13:47.000Z", "avg_line_length": 31.2941176471, "max_line_length": 78, "alphanum_fraction": 0.5258458647, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7593958866051478}}
{"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, \u03c4::T) where {T} = cos(\u03c0/2*\u03c4)^2\nevaluate_r(path::PathIntegralTrigonometric, \u03c4::T) where {T} = sin(\u03c0/2*\u03c4)^2\n\nderivative_l(path::PathIntegralTrigonometric, \u03c4::T) where {T} = -\u03c0*sin(\u03c0/2*\u03c4)*cos(\u03c0/2*\u03c4)\nderivative_r(path::PathIntegralTrigonometric, \u03c4::T) where {T} = +\u03c0*sin(\u03c0/2*\u03c4)*cos(\u03c0/2*\u03c4)\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\u03b4(\u03a6, z) = diff(\u03a6) ./ 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\u00b2-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\u00b9-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( \u03b4(a, z), \u03b4(b, z) ))\n\n\"\"\"\n    antiderivative_distance(a, b, z)\n\nComputes the H\u207b\u00b9-norm with respect to z of two vectors:\n\n    d(x, x\u2032) = || 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": "include(\"misc.jl\")\r\n\r\nfunction leastSquares(X,y)\r\n\r\n\t# Add bias column\r\n\tn = size(X,1)\r\n\tZ = [ones(n,1) X]\r\n\r\n\t# Find regression weights minimizing squared error\r\n\tw = (Z'*Z)\\(Z'*y)\r\n\r\n\t# Make linear prediction function\r\n\tpredict(Xtilde) = [ones(size(Xtilde,1),1) Xtilde]*w\r\n\r\n\t# Return model\r\n\treturn LinearModel(predict,w)\r\nend\r\n", "meta": {"hexsha": "1303f3cea0a52c80bfb53d36c1ff3fc17d8c6c6d", "size": 331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a1sol/leastSquares.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/leastSquares.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/leastSquares.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": 18.3888888889, "max_line_length": 53, "alphanum_fraction": 0.6465256798, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7593584982256636}}
{"text": "module Wynn\n    using SymPy\n\n    # data structure to store the epsilon table\n    # \u03f5_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            \u03f5_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(\u03f5_ij)) : push!(etable, (i, j) => \u03f5_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        \u03f5_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(\u03f5_order)\n        else\n            return \u03f5_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\u03b1\u2081(t) = 0\n\u03b1\u2082(t) = -1\n\u03b2\u2081(t) = 1\n\u03b2\u2082(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\u03c6(x) = x\n\u03b1(t) = 1\n\u03b2(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    \u03c4 = T / M\n    \u03bd = \u03c4 / h^2\n    return A * \u03bd \u2264 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, \u03c4, x, t; \u03c3 = 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, :] .= \u03c6.(x)\n    if \u03c3 == 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                           \u03c4 * (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] = (\u03b1(t[k]) + \u03b1\u2082(t[k]) * (4 * um[k, 2] - um[k, 3]) / (2h)) /\n                       (\u03b1\u2081(t[k]) + 3 * \u03b1\u2082(t[k]) / (2h))\n            um[k, N+1] = (\u03b2(t[k]) + \u03b2\u2082(t[k]) * (4 * um[k, N] - um[k, N-1]) / (2h)) /\n                         (\u03b2\u2081(t[k]) + 3 * \u03b2\u2082(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                    [\u03c3 * (p(x[i] - h / 2) / h^2 - b(x[i], t[k]) / (2h)) for i = 2:N]\n                    -\u03b2\u2082(t[k]) / h\n                ],\n                # B's\n                [\n                    \u03b1\u2081(t[k]) + \u03b1\u2082(t[k]) / h\n                    -[1 / \u03c4 + \u03c3 * ((p(x[i] + h / 2) + p(x[i] - h / 2)) / h^2 - c(x[i], t[i])) for i = 2:N]\n                    \u03b2\u2081(t[k]) + \u03b2\u2082(t[k]) / h\n                ],\n                # C's\n                [\n                    -\u03b1\u2082(t[k]) / h\n                    [\u03c3 * (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                \u03b1(t[k])\n                [-um[k-1, i] / \u03c4 - (1 - \u03c3) * L(um, x, t, h, i, k - 1) - f(x[i], t[k] - (1 - \u03c3) * \u03c4) for i = 2:N]\n                \u03b2(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    \u0394u = 0\n    for i = 1:N1, k = 1:M1\n        _\u0394u = abs(u(x[i], t[k]) - um[k, i])\n        if _\u0394u > \u0394u\n            \u0394u = _\u0394u\n        end\n    end\n    return \u0394u\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\u2091 = find_stable.(N)\n    M\u1d62 = 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        \u03c4\u2091 = T / M\u2091[l]\n        \u03c4\u1d62 = T / M\u1d62[l]\n        # Compute the nodes\n        x = [j * h for j = 0:N[l]]\n        t\u2091 = [j * \u03c4\u2091 for j = 0:M\u2091[l]]\n        t\u1d62 = [j * \u03c4\u1d62 for j = 0:M\u1d62[l]]\n        # Solve the problem with the explicit scheme\n        um = solve(N[l], M\u2091[l], h, \u03c4\u2091, x, t\u2091)\n        # Print info about the solution\n        println(\n            '\\n',\n            \" \"^5, \"\u03c3: 0\", '\\n',\n            \" \"^5, \"N: \", N[l], '\\n',\n            \" \"^5, \"M: \", M\u2091[l], '\\n',\n            \" \"^5, \"\u0394u: \", max_difference(um, x, t\u2091)\n        )\n        # Create and write the tables\n        tables(joinpath(dir, \"\u03c3 = 0\"), digits, um, N[l], M\u2091[l])\n        # Solve the problem with the implicit scheme (\u03c3 = 0.5)\n        um = solve(N[l], M\u1d62[l], h, \u03c4\u1d62, x, t\u1d62; \u03c3 = 0.5)\n        # Print info about the solution\n        println(\n            '\\n',\n            \" \"^5, \"\u03c3: 0.5\", '\\n',\n            \" \"^5, \"N: \", N[l], '\\n',\n            \" \"^5, \"M: \", M\u1d62[l], '\\n',\n            \" \"^5, \"\u0394u: \", max_difference(um, x, t\u1d62)\n        )\n        # Create and write the tables\n        tables(joinpath(dir, \"\u03c3 = 0.5\"), digits, um, N[l], M\u1d62[l])\n        # Solve the problem with the implicit scheme (\u03c3 = 1)\n        um = solve(N[l], M\u1d62[l], h, \u03c4\u1d62, x, t\u1d62; \u03c3 = 1.0)\n        # Print info about the solution\n        println(\n            '\\n',\n            \" \"^5, \"\u03c3: 1.0\", '\\n',\n            \" \"^5, \"N: \", N[l], '\\n',\n            \" \"^5, \"M: \", M\u1d62[l], '\\n',\n            \" \"^5, \"\u0394u: \", max_difference(um, x, t\u1d62)\n        )\n        # Create and write the tables\n        tables(joinpath(dir, \"\u03c3 = 1.0\"), digits, um, N[l], M\u1d62[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\u03c6(x) = x^3\n\u03b1(t) = 0\n\u03b2(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": "\"\"\"\n    ellipse(; center::Point, xAxis::Real, yAxis::Real, steps::Integer=64, angle::Real=0., pivot::Union{Point, Nothing}=nothing, units::String=\"kilometers\")\n\nTake a Point and calculates the ellipse polygon given two semi-axes expressed in variable units and steps for precision.\n\n# Examples\n```jldoctest\njulia> center = Point([10, 45])\nPoint([10.0, 45.0])\n\njulia> ellipse(center=center, xAxis=20, yAxis=7.5, steps=10)\nPolygon(Array{Array{Float64,1},1}[[[10.0872, 45.0634], [10.0218, 45.0672], [9.97817, 45.0672], [9.91279, 45.0634], [9.74563, 45.0], [9.91279, 44.9366], [9.97817, 44.9328], [10.0218, 44.9328], [10.0872, 44.9366], [10.2544, 45.0], [10.0872, 45.0634]]])\n```\n\"\"\"\nfunction ellipse(; center::Point, xAxis::Real, yAxis::Real, steps::Integer=64, angle::Real=0., pivot::Union{Point, Nothing}=nothing, units::String=\"kilometers\")\n    pivot == nothing && (pivot = center)\n\n    coords = center.coordinates\n\n    if units === \"degrees\"\n        angle = deg2rad(angle)\n    else\n        xAxis = rhumb_destination(coords, xAxis, 90, units).coordinates\n        yAxis = rhumb_destination(coords, yAxis, 0, units).coordinates\n        xAxis = xAxis[1] - coords[1]\n        yAxis = yAxis[2] - coords[2]\n    end\n\n    elCoords = []\n\n    for i in 1:steps\n        stepAngle = i * (-360 / steps)\n        x = (xAxis * yAxis) / sqrt(yAxis^2 + xAxis^2 * tan(deg2rad(stepAngle))^2)\n        y = (xAxis * yAxis) / sqrt(xAxis^2 + yAxis^2 / tan(deg2rad(stepAngle))^2)\n\n        (stepAngle < -90 && stepAngle >= -270) && (x = -x)\n        (stepAngle < -180 && stepAngle >= -360) && (y = -y)\n\n        if units === \"degrees\"\n            newx = x * cos(angle) + y * sin(angle)\n            newy = y * cos(angle) - x * sin(angle)\n            x = newx\n            y = newy\n        end\n\n        push!(elCoords, [x + coords[1], y + coords[2]])\n    end\n    push!(elCoords, elCoords[1])\n\n    units === \"degrees\" && return Polygon([elCoords])\n\n    return transform_rotate(geojson=Polygon([elCoords]), angle=angle, pivot=pivot)\n\nend\n", "meta": {"hexsha": "3ff0aec4ddb7996adb3ade94e06bbbf3c1c71cc7", "size": 2002, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib/Ellipse.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/Ellipse.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/Ellipse.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": 36.4, "max_line_length": 250, "alphanum_fraction": 0.5994005994, "num_tokens": 652, "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 +  \u221a(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(\"\u03b2_lm estimates:\", bols_lm)\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 3\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nfunction logit(\u03b2, X, y)\n\n    # your turn\n    diff_u = X*\u03b2\n    loglike = sum(y.*diff_u - log.(1 .+ exp.(diff_u)))\n    loglike = -loglike\n\n    return loglike\nend\n\n\u03b2_llk = optimize(\u03b2 -> logit(\u03b2, 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(\u03b2_llk.minimizer)\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 4\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nb_glm = glm(@formula(married ~ age + white + collgrad), df, Binomial(), LogitLink())\nprintln(\"\u03b2_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(\u03b2, 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    \u03b2_big = [reshape(\u03b2,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*\u03b2_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": "using Test, OMEinsum\nusing OMEinsum: IndexGroup, NestedEinsum, parse_nested\n@testset \"einsequence\" begin\n    @test push!(IndexGroup([],1), 'c').inds == IndexGroup(['c'], 1).inds\n    @test isempty(IndexGroup([],1))\n\n    @test_throws ArgumentError parse_nested(\"((ij,jk),km\")\n    @test_throws ArgumentError parse_nested(\"((ij,jk),k1)\")\n\n    a, b, c = rand(2,2), rand(2,2), rand(2,2)\n    abc1 = ein\"(ij,jk),km -> im\"(a,b,c)\n    abc2 = ein\"((ij,jk),km) -> im\"(a,b,c)\n    abc3 = ein\"ij,jk,km -> im\"(a,b,c)\n\n    @test abc1 \u2248 abc2 \u2248 abc3\nend\n\n@testset \"macro\" begin\n    b, c, d = rand(2,2), rand(2,2,2), rand(2,2,2,2)\n    @ein a[i,j] := b[i,k] * c[k,k,l] * d[l,m,m,j]\n    @ein a2[i,j] := b[i,k] * (c[k,k,l] * d[l,m,m,j])\n    @test a \u2248 a2\nend", "meta": {"hexsha": "66046f2015e9c81f69d8853b1db522b9044ebe2a", "size": 734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/einsequence.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/OMEinsum.jl-ebe7aa44-baf0-506c-a96f-8464559b3922", "max_stars_repo_head_hexsha": "54c9a09472ae249b4c574544f5ff4d0bd0cc8fe7", "max_stars_repo_licenses": ["MIT"], "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/einsequence.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/OMEinsum.jl-ebe7aa44-baf0-506c-a96f-8464559b3922", "max_issues_repo_head_hexsha": "54c9a09472ae249b4c574544f5ff4d0bd0cc8fe7", "max_issues_repo_licenses": ["MIT"], "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/einsequence.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/OMEinsum.jl-ebe7aa44-baf0-506c-a96f-8464559b3922", "max_forks_repo_head_hexsha": "54c9a09472ae249b4c574544f5ff4d0bd0cc8fe7", "max_forks_repo_licenses": ["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.9130434783, "max_line_length": 72, "alphanum_fraction": 0.5653950954, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7593184500087261}}
{"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_\u03c3(K) = {\u03c4 \u2208 K : \u03c3 \u2229 \u03c4 = \u2205, \u03c3 \u222a \u03c4 \u2208 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_\u03c4(K) = {\u03c3 \u2208 K : \u03c4 \u228f\u0338 \u03c3}``\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) = {\u03c3 \u2208 K : \u03c3 \u2286 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#  Syntax testing  (uses examples in the doc)\n##################################################\n\n#########  rdiff ###########\n\nm.rdiff( :(x^3) , x=2.)             # first order\nm.rdiff( :(x^3) , order = 3, x=2.)  # orders up to 3\n\nm.rdiff( :(sin(x)) , order=10, x=2.)  # derivatives up to order 10\n\nres = m.rdiff( :(sin(x)) , order=10, x=2.)\n@eval foo(x) = $res\nfoo(2.)\n\nex = :( (1 - x[1])^2 + 100(x[2] - x[1]^2)^2 )  # the rosenbrock function\nres = m.rdiff(ex, x=zeros(2), order=2)\nm.@eval foo(x) = $res\nfoo([0.5, 2.])\n\n#########  rdiff (function) ###########\n\nrosenbrock(x) = (1 - x[1])^2 + 100(x[2] - x[1]^2)^2   # function to be derived\nrosen2 = m.rdiff(rosenbrock, (ones(2),), order=2)       # orders up to 2\nrosen2([1,2])\nrosen2([0.5,2])\n\ntest(x) = exp(x)\nm.rdiff(test, (1.,), order=5)\n\nm.rdiff( :(x^3) , x=2.)             # first order\nm.rdiff( :(x^3) , order = 3, x=2.)  # orders up to 3\n\nm.rdiff( :(sin(x)) , order=10, x=2.)  # derivatives up to order 10\n\nres = m.rdiff( :(sin(x)) , order=10, x=2.)\n@eval foo(x) = $res\nfoo(2.)\n\nex = :( (1 - x[1])^2 + 100(x[2] - x[1]^2)^2 )  # the rosenbrock function\nres = m.rdiff(ex, x=zeros(2), order=2)\nm.@eval foo(x) = $res\nfoo([0.5, 2.])\n\n\n#########  @deriv_rule  ###########\n\nm.@deriv_rule *(x::Real         , y::Real )            y     x * ds\nm.@deriv_rule *(x::Real         , y::AbstractArray)    y     x .* ds\nm.@deriv_rule *(x::AbstractArray, y::Real )            y     sum(x .* ds)\nm.@deriv_rule *(x::AbstractArray, y::AbstractArray)    y     x' * ds\n\n\nfoo(x) = log(1+sin(x))\n\nm.@deriv_rule foo(x)   x   cos(x) / ( 1 + sin(x)) * ds\n\nres = m.rdiff( :( 2 ^ foo(x) ) , x=1)\n@eval myf(x) = $res\n\n(myf(1.0)[1] - myf(0.999)[1]) * 1000\n\n\n######### @typeequiv ############\n\nmodule Sandbox2\n    type Bar\n        x\n        y\n    end\n\n    norm(z::Bar) = z.x*z.x + z.y*z.y\nend\n\nex = quote\n    z = Sandbox2.Bar(2^a, sin(a))\n    Sandbox2.norm(z)\nend\n\nm.@deriv_rule  Sandbox2.Bar(x,y)      x  ds[1]   # Derivative accumulator of x is increased by ds[1]\nm.@deriv_rule  Sandbox2.Bar(x,y)      y  ds[2]   # Derivative accumulator of y is increased by ds[2]\n\nm.@deriv_rule  Sandbox2.norm(z::Sandbox2.Bar)  z  Any[ 2*z.x*ds , 2*z.y*ds ]  # Note : produces a 2-vector since z is a Bar\n\nres = m.rdiff(ex, a=0.)\n@eval df(a) = $res\n\ndf(1)\n\n###### internals - tograph example  ######\n\nm.plot( m.tograph( :(a = sin(x+1) ; 2exp(a)) ))\n\n\n###### higher order   ######\n\nex = :( (1 - x[1])^2 + 100(x[2] - x[1]^2)^2 )  # the rosenbrock function\n\nres = m.rdiff(ex, x=zeros(2), order=2)\nres = m.rdiff(ex, x=zeros(2), order=3)\n", "meta": {"hexsha": "8ef2b9f5e0bd46aa78cc58fbc35ac132a45e763c", "size": 2598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/syntax.jl", "max_stars_repo_name": "JuliaPackageMirrors/ReverseDiffSource.jl", "max_stars_repo_head_hexsha": "89e1c0bf92f2252786d3d34be7ee69d8a204f077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-19T17:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-19T17:19:46.000Z", "max_issues_repo_path": "test/syntax.jl", "max_issues_repo_name": "JuliaPackageMirrors/ReverseDiffSource.jl", "max_issues_repo_head_hexsha": "89e1c0bf92f2252786d3d34be7ee69d8a204f077", "max_issues_repo_licenses": ["MIT"], "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/syntax.jl", "max_forks_repo_name": "JuliaPackageMirrors/ReverseDiffSource.jl", "max_forks_repo_head_hexsha": "89e1c0bf92f2252786d3d34be7ee69d8a204f077", "max_forks_repo_licenses": ["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.7227722772, "max_line_length": 123, "alphanum_fraction": 0.5003849115, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7593184370954935}}
{"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": "@testset \"SVD\" begin\n    for n in [1,3,10]\n\nm = n + rand(0:5)\nA = rand(m, n)\n\nr = polarfact(A, alg = :svd);\n\n\n# Test unitary matrix U\n\nU = r.U\nH = r.H\n\n@test U'*U \u2248 Matrix(I,n,n) atol=1e-7\n\n# Test Hermitian positive semifefinite matrix H\n\n@test issymmetric(H)\n \nfor i in eigvals(H)\n    @test i >= 0.\nend\n\n@test A \u2248 U*H\n\n    end\nend\n\n", "meta": {"hexsha": "cd69c77adae4536f9495255e58a80f7f6f12f559", "size": 333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_svd.jl", "max_stars_repo_name": "weijianzhang/PolarFact.jl", "max_stars_repo_head_hexsha": "6530009072c8774274508fef3c05a1487f09bd60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-03-12T23:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-13T11:35:49.000Z", "max_issues_repo_path": "test/test_svd.jl", "max_issues_repo_name": "weijianzhang/PolarFact.jl", "max_issues_repo_head_hexsha": "6530009072c8774274508fef3c05a1487f09bd60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-12-18T19:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:28:45.000Z", "max_forks_repo_path": "test/test_svd.jl", "max_forks_repo_name": "weijianzhang/PolarFact.jl", "max_forks_repo_head_hexsha": "6530009072c8774274508fef3c05a1487f09bd60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T14:32:06.000Z", "avg_line_length": 11.1, "max_line_length": 47, "alphanum_fraction": 0.5855855856, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7593137573280009}}
{"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# \u03c3(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 Turing\nusing Distributions\nusing Test\n\n@model gdemo(x) = begin\n  s ~ InverseGamma(2, 3)\n  # println(s)\n  m ~ Normal(0, sqrt(s))\n  # println(m)\n  x[1] ~ Normal(m, sqrt(s))\n  x[2] ~ Normal(m, sqrt(s))\n  # println(vi)\n  return s, m\nend\n\nalg = HMC(3000, 0.15, 10)\n\nres = sample(gdemo([1.5, 2.0]), alg)\n\nprintln(mean(res[:s]),\" \u2248 \", 49/24, \"?\")\nprintln(mean(res[:m]),\" \u2248 \", 7/6, \"?\")\n@test mean(res[:s]) \u2248 49/24 atol=0.2\n@test mean(res[:m]) \u2248 7/6 atol=0.2\n", "meta": {"hexsha": "b1f163fe81e0f1535d32e04d69f60a5b92684600", "size": 457, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/hmc.jl/hmc_reverse_diff.jl", "max_stars_repo_name": "mohamed82008/Turing.jl", "max_stars_repo_head_hexsha": "70640d35805bb46a54c04d9ff25e5a90f22eee2b", "max_stars_repo_licenses": ["MIT"], "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/hmc.jl/hmc_reverse_diff.jl", "max_issues_repo_name": "mohamed82008/Turing.jl", "max_issues_repo_head_hexsha": "70640d35805bb46a54c04d9ff25e5a90f22eee2b", "max_issues_repo_licenses": ["MIT"], "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/hmc.jl/hmc_reverse_diff.jl", "max_forks_repo_name": "mohamed82008/Turing.jl", "max_forks_repo_head_hexsha": "70640d35805bb46a54c04d9ff25e5a90f22eee2b", "max_forks_repo_licenses": ["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.0416666667, "max_line_length": 40, "alphanum_fraction": 0.5689277899, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7593137472301473}}
{"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": "module FakeSegmentations\nusing LinearAlgebra\n\nconst ZERO_UINT32 = UInt32(0)\nconst ONE_UINT32 = UInt32(1)\nconst RADIUS = Float32(10)\nconst HEIGHT = 100\nconst THICKNESS = 10\n\nfunction cylinder(;radius::Float32=RADIUS, height::Integer=HEIGHT)\n    width = Int( radius*2 + 1 )\n    center = Int(radius + 1)\n    seg = zeros(UInt32, (width,width,height))\n    for x in Int(center-radius):Int(center+radius)\n        for y in Int(center-radius):Int(center+radius)\n            if norm([x,y].-[center, center]) < radius \n                seg[x,y,:] .= ONE_UINT32 \n            end \n        end \n    end \n    seg\nend\n\nfunction broken_cylinder(;radius::Float32=RADIUS, height::Integer=HEIGHT, \n                         breakStartZ::Integer=div(height,2), \n                         thickness::Integer = THICKNESS )\n    seg = cylinder(radius=radius, height=height)\n    # create a breaking part\n    seg[ :,:, breakStartZ : breakStartZ+10 ] .= ZERO_UINT32\n    seg\nend \n\nfunction ring(; centerLineRadius::Integer = 50, ringRadius::Integer=5)\n    seg = zeros(UInt32, (2*centerLineRadius+2*ringRadius + 5, \n                         2*centerLineRadius+2*ringRadius + 5, 2*ringRadius + 5) )\n    center = [map(x->div(x,2), size(seg))...]\n    for y in 1:size(seg, 2)\n        for x in 1:size(seg, 1)\n            d = norm([x,y] .- center[1:2])\n            if abs(d-centerLineRadius) < 2 \n                # this point is on the center line of the ring\n                for rz in center[3]-ringRadius : center[3]+ringRadius \n                    for ry in y-ringRadius : y+ringRadius \n                        for rx in x-ringRadius : x+ringRadius\n                            d2 = norm([x,y,center[3]] .- [rx,ry,rz])\n                            if d2 <= ringRadius\n                                seg[rx,ry,rz] = ONE_UINT32 \n                            end \n                        end \n                    end \n                end \n            end \n        end \n    end \n    @assert ndims(seg) == 3\n    seg\nend \n\nfunction broken_ring(; centerLineRadius::Integer = 50, ringRadius::Integer=5)\n    seg = ring(; centerLineRadius = centerLineRadius, ringRadius = ringRadius)\n    center = map(x->div(x,2), size(seg))\n    d = div(centerLineRadius, 10)\n    seg[center[1]-d:center[1]+d, :, :] .= ZERO_UINT32 \n    seg[:, center[2]-d:center[2]+d, :] .= ZERO_UINT32 \n    seg\nend \n\nfunction Y_shape()\n    error(\"unimplemented\")\nend \n\nend # module \n", "meta": {"hexsha": "68a96dde59af14f51cc8d0cec1b032a9dfc27998", "size": 2401, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/FakeSegmentations.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/FakeSegmentations.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/FakeSegmentations.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": 32.8904109589, "max_line_length": 81, "alphanum_fraction": 0.5526863807, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7593084610921996}}
{"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 \u2264 k \u2264 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 \u2264 k \u2264 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\u2205\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\u2205\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 \"\u2205\"\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 \u2208 i\n\nReturns true if x \u2208 i and false if x \u2209 i.\nEx:\n```\njulia> i = Interval(-1,true,2)\n]-1,2]\njulia> 0 \u2208 i\ntrue\njulia> 2 \u2208 i\ntrue\njulia> -1 \u2208 i\nfalse\njulia> -0.9999999 \u2208 i\ntrue\n```\n\"\"\"\nfunction \u2208(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 \u2286 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 \u2286 i\ntrue\njulia> k = Interval(0,true,3,true)\n]0,3[\njulia> k \u2286 i\ntrue\njulia> i \u2288 k\ntrue\n```\n\"\"\"\nfunction \u2286(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 \u2229 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 \u2229 j\n]0.8,1[\n```\n\"\"\"\nfunction \u2229(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 \u222a 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 \u222a j\n[0,1.2]\n```\n\"\"\"\nfunction \u222a(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 \u222a 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 \u222a i2\n\tcardu = cardinal(u)\n\tcardu != 0 ? cardinal(i1 \u2229 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 \u2229 i2) / denom : 0\nend\n\n\"\"\"\n\tdice_coefficient(i1,i2)\n\nReturns the S\u00f8rensen\u2013Dice 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 \u2229 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] \u222a 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\u2205\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[ \u222a ]1,2]\"\n```\n\"\"\"\nfunction string(iu::IntervalUnion)\n\tif empty(iu)\n\t\treturn \"\u2205\"\n\telseif number_of_components(iu) == 1\n\t\treturn string(iu.components[1])\n\telse\n\t\treturn reduce((x,y)->\"$(string(x)) \u222a $(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[ \u222a ]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[ \u222a ]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[ \u222a ]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] \u222a [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] \u222a [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] \u222a [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] \u222a [2,3]\njulia> super_complement(i)\n]-Inf,0] \u222a ]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] \u222a [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[ \u222a ]2.5,3] \u222a [3.5,6]\njulia> restricted_complement(j)\n[1,2.5] \u222a ]3,3.5[\n```\n\"\"\"\nfunction restricted_complement(iu::IntervalUnion)\n\tsuperset(iu) \u2229 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] \u222a [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[ \u222a ]2.5,3] \u222a [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 \u2208 iu\n\nReturns true if x \u2208 iu and false if x \u2209 iu.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,true,1,true),Interval(2.5,true,3),Interval(3.5,6)])\n]0,1[ \u222a ]2.5,3] \u222a [3.5,6]\njulia> 0.5 \u2208 i\ntrue\njulia> 1 \u2208 i\nfalse\njulia> 0.9999999 \u2208 i\ntrue\n```\n\"\"\"\nfunction \u2208(x::Real, iu::IntervalUnion)\n\tfor i in iu.components\n\t\tx \u2208 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] \u222a ]c,d] \u222a [e,f[ \u222a ]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[ \u222a ]2.5,3] \u222a [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[ \u222a ]2.5,3] \u222a [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 \u2286 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[ \u222a ]2.5,3] \u222a [3.5,6]\njulia> j = IntervalUnion([Interval(2.6,3),Interval(3.5,4,true)])\n[2.6,3] \u222a [3.5,4[\njulia> j \u2286 i\ntrue\n```\n\"\"\"\nfunction \u2286(iu1::IntervalUnion, iu2::IntervalUnion)\n    for i in iu1.components\n    \t!any([i \u2286 j for j in iu2.components]) && return false\n    end\n    true\nend\n\n\"\"\"\n\tiu1 \u222a 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[ \u222a ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] \u222a ]2.3,4[\njulia> i \u222a j\n[0,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ \u222a [3,4]\njulia> i \u222a k\n[-1,1[ \u222a ]1,2.3] \u222a [3,4]\njulia> i \u222a IntervalUnion()\n[0,1[ \u222a ]1,2.3]\n```\n\"\"\"\nfunction \u222a(iu1::IntervalUnion, iu2::IntervalUnion)\n\tIntervalUnion(vcat(iu1.components,iu2.components))\nend\n\n\"\"\"\n\tiu1 \u2229 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[ \u222a ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] \u222a ]2.3,4[\njulia> i \u2229 j\n\u2205\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ \u222a [3,4]\njulia> j \u2229 k\n[3,4[\njulia> i \u2229 IntervalUnion()\n\u2205\n```\n\"\"\"\nfunction \u2229(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 \u2229 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[ \u222a ]1,Inf[\njulia> j = IntervalUnion([Interval(0,0)])\n[0,0]\njulia> complement(j)\n]-Inf,0[ \u222a ]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[ \u222a ]2,3]\njulia> complement(l)\n]-Inf,0[ \u222a [1,2] \u222a ]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[ \u222a ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] \u222a ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ \u222a [3,4]\njulia> julia> setdiff(j,k)\n[1,1] \u222a ]2.3,3[\n```\n\"\"\"\nfunction setdiff(iu1::IntervalUnion, iu2::IntervalUnion)\n\tcomplement(iu2) \u2229 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[ \u222a ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] \u222a ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ \u222a [3,4]\njulia> symdiff(i,k)\n[-1,1[ \u222a ]1,2.3] \u222a [3,4]\njulia> symdiff(j,k)\n[-1,0[ \u222a [1,1] \u222a ]2.3,3[ \u222a [4,4]\n```\n\"\"\"\nfunction symdiff(iu1::IntervalUnion, iu2::IntervalUnion)\n\tsetdiff(iu1 \u222a iu2, iu1 \u2229 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[ \u222a ]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[ \u222a ]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 \u222a iu2|=0, this function returns 0.\nEx:\n```\njulia> i = IntervalUnion([Interval(0,1,true),Interval(1,true,2.3)])\n[0,1[ \u222a ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] \u222a ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ \u222a [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 \u222a iu2\n\tcardu = cardinal(u)\n\tcardu != 0 ? cardinal(iu1 \u2229 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[ \u222a ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] \u222a ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ \u222a [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 \u2229 iu2) / denom : 0\nend\n\n\"\"\"\n\tdice_coefficient(iu1,iu2)\n\nReturns the S\u00f8rensen\u2013Dice 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[ \u222a ]1,2.3]\njulia> j = IntervalUnion([Interval(1,1),Interval(2.3,true,4,true)])\n[1,1] \u222a ]2.3,4[\njulia> k = IntervalUnion([Interval(-1,0,true),Interval(3,4)])\n[-1,0[ \u222a [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 \u2229 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# \u2554\u2550\u2561 85d5a830-4116-11eb-1479-630b53b50e94\nbegin\n\tusing Pkg\n    Pkg.activate(pwd())\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c73d5420-4126-11eb-19b3-bf6c04aef086\nmd\"\"\"\n# Data Mining\n## Assignment 2 - K-means Clustering\n### Aadam & Obaidullah (CS1945 & CS1947)\n\"\"\"\n\n# \u2554\u2550\u2561 360ab320-411d-11eb-2d11-c9fe7b3137d1\nplotly()\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c7001000-42c6-11eb-23d1-314932816f0a\nfunction big_delta(maskci, distances)\n\tmaximum(distances[maskci, :][:, maskci])\nend\n\n# \u2554\u2550\u2561 c6ca5a00-42c6-11eb-386e-2f13a99d75b6\nfunction delta(maskci, maskcj, distances)\n\tminimum(distances[maskci, :][:, maskcj])\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9accd320-4117-11eb-0fc4-15e8e85040a8\ndatasets = [\"iris\" => \"iris\", \"glass-identification\" => \"glass\"];\n\n# \u2554\u2550\u2561 8b43a9a0-4118-11eb-127d-d57dcea189e1\nmd\"\"\"\nDataset: $(@bind selected_dataset Select(datasets))\n\n\"\"\"\n\n# \u2554\u2550\u2561 73c57b20-4116-11eb-3dba-01c9f7b91fa7\ndata = UCIData.dataset(selected_dataset);\n\n# \u2554\u2550\u2561 5cddc6a0-411c-11eb-2380-1b9442938a9b\nfeatures = collect(Matrix(data[:, 2:end-1])');\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 737b2bb0-4116-11eb-124b-d981032a9638\nresult = kmeans(features, k);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500c73d5420-4126-11eb-19b3-bf6c04aef086\n# \u255f\u250085d5a830-4116-11eb-1479-630b53b50e94\n# \u2560\u25504862c2d0-4116-11eb-3f26-1bdefcb9ce3d\n# \u255f\u2500360ab320-411d-11eb-2d11-c9fe7b3137d1\n# \u2560\u255073936e9e-4116-11eb-0594-1d202bd073cd\n# \u2560\u2550aac40900-41cc-11eb-1103-97d9373bdd65\n# \u2560\u255012615c80-41c7-11eb-2aed-c1eb96003ff1\n# \u2560\u2550c7001000-42c6-11eb-23d1-314932816f0a\n# \u2560\u2550c6ca5a00-42c6-11eb-386e-2f13a99d75b6\n# \u2560\u2550c69d2f80-42c6-11eb-10cf-e70c07e40e97\n# \u255f\u25009accd320-4117-11eb-0fc4-15e8e85040a8\n# \u255f\u25008b43a9a0-4118-11eb-127d-d57dcea189e1\n# \u2560\u255073c57b20-4116-11eb-3dba-01c9f7b91fa7\n# \u2560\u25505cddc6a0-411c-11eb-2380-1b9442938a9b\n# \u255f\u2500bec93fa0-4119-11eb-026e-0be14d6a5779\n# \u2560\u2550737b2bb0-4116-11eb-124b-d981032a9638\n# \u2560\u2550725d2e10-42c2-11eb-3ee7-4ba089ebb440\n# \u255f\u2500ce4134a0-4124-11eb-2a7c-9761e81b2064\n# \u255f\u250073454ea0-4116-11eb-0938-f9a06f3dbaf8\n# \u255f\u25006cd3fe00-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": "using NewtonsMethod\nusing Test\n\n@testset \"NewtonsMethod.jl\" begin\n    atol = 1e-4\n    f1(x) = 2x+1\n    g1(x) = 2\n    f2(x) = (x-1)^2\n    g2(x) = 2(x-1)\n    f3(x) = exp(x)-1\n    g3(x) = exp(x)\n    f4(x) = 2 + x^2\n    g4(x) = 2x\n\n    # Tests for known functions - analytical derivatives\n    @test isapprox(newtonroot(f1, g1; x\u2080 = 10.0).value, -0.5, atol=atol)\n    @test isapprox(newtonroot(f2, g2; x\u2080 = 10.0).value, 1.0, atol=atol)\n    @test isapprox(newtonroot(f3, g3; x\u2080 = 10.0).value, 0.0, atol=atol)\n\n    # Tests for known functions - automatic derivatives\n    @test isapprox(newtonroot(f1; x\u2080 = 10.0).value, -0.5, atol=atol)\n    @test isapprox(newtonroot(f2; x\u2080 = 10.0).value, 1.0, atol=atol)\n    @test isapprox(newtonroot(f3; x\u2080 = 10.0).value, 0.0, atol=atol)\n\n    # Tests using BigFloat\n    @test isapprox(newtonroot(f1, g1; x\u2080 = BigFloat(10.0)).value, -0.5, atol=atol)\n    @test isapprox(newtonroot(f2, g2; x\u2080 = BigFloat(10.0)).value, 1.0, atol=atol)\n    @test isapprox(newtonroot(f3, g3; x\u2080 = BigFloat(10.0)).value, 0.0, atol=atol)\n    @test isapprox(newtonroot(f1; x\u2080 = BigFloat(10.0)).value, -0.5, atol=atol)\n    @test isapprox(newtonroot(f2; x\u2080 = BigFloat(10.0)).value, 1.0, atol=atol)\n    @test isapprox(newtonroot(f3; x\u2080 = BigFloat(10.0)).value, 0.0, atol=atol)\n\n    # Tests for non-convergence handling\n    @test isnothing(newtonroot(f4, g4; x\u2080 = 10.0).value)\n    @test isnothing(newtonroot(f4; x\u2080 = 10.0).value)\n\n    # Tests that maxiter is working\n    @test newtonroot(f4, g4; x\u2080 = 10.0, maxiter = 5).iter == 6\n    @test newtonroot(f4; x\u2080 = 10.0, maxiter = 5).iter == 6\n\n    # Tests that tol is working\n    @test abs(newtonroot(f2, g2; x\u2080 = 10.0, tol = 1e-1).value - 1.0) > \n          abs(newtonroot(f2, g2; x\u2080 = 10.0, tol = 1e-10).value - 1.0)\n    @test abs(newtonroot(f2; x\u2080 = 10.0, tol = 1e-1).value - 1.0) >\n          abs(newtonroot(f2; x\u2080 = 10.0, tol = 1e-10).value - 1.0)\n    @test abs(newtonroot(f3, g3; x\u2080 = 10.0, tol = 1e-1).value) > \n          abs(newtonroot(f3, g3; x\u2080 = 10.0, tol = 1e-10).value)\n    @test abs(newtonroot(f3; x\u2080 = 10.0, tol = 1e-1).value) >\n          abs(newtonroot(f3; x\u2080 = 10.0, tol = 1e-10).value)\nend\n", "meta": {"hexsha": "9313b7c1b10bce3effbaf3d469426496877b9542", "size": 2148, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 42.1176470588, "max_line_length": 82, "alphanum_fraction": 0.6075418994, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7592599564295547}}
{"text": "using Plots\nplotly()\n\nx = 0:0.01:2pi\ny_sin = sin.(x)\ny_cos = cos.(x)\n\nplot(x, [y_sin y_cos], labels=[\"sin\" \"cos\"])\n\n_round(number) = round(number, sigdigits=4)\n_point_label(x, y, fun) = \"$fun($(_round(x))) = $(_round(y))\"\ntooltips_sin = [_point_label(x, y, \"sin\") for (x, y) in zip(x, y_sin)]\ntooltips_cos = [_point_label(x, y, \"cos\") for (x, y) in zip(x, y_cos)]\n\nplot(x, [y_sin y_cos], labels=[\"sin\" \"cos\"], hover=[tooltips_sin tooltips_cos])\n", "meta": {"hexsha": "b4df5bd930163aef33e3ac646d2e616e0bb894fa", "size": 445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter03/Plots_plotly.jl", "max_stars_repo_name": "PacktPublishing/Interactive-Visualization-with-Julia", "max_stars_repo_head_hexsha": "6f9b2f0798784892b7d6965dd56fb2ef42d1012a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-04T16:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T16:28:23.000Z", "max_issues_repo_path": "Chapter03/Plots_plotly.jl", "max_issues_repo_name": "PacktPublishing/Interactive-Visualization-with-Julia", "max_issues_repo_head_hexsha": "6f9b2f0798784892b7d6965dd56fb2ef42d1012a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter03/Plots_plotly.jl", "max_forks_repo_name": "PacktPublishing/Interactive-Visualization-with-Julia", "max_forks_repo_head_hexsha": "6f9b2f0798784892b7d6965dd56fb2ef42d1012a", "max_forks_repo_licenses": ["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.8125, "max_line_length": 79, "alphanum_fraction": 0.6337078652, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7592599559998056}}
{"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    (\u0394,\u0394x,statisitic) = (mySolver::solver)(f::Function, x\u2080::Vector{T}, t\u2080::S, tEnd::S; <options>)\n        where {T<:Number,S<:AbstractFloat}\n\nComputes the grid function `x\u0394` on the grid `\u0394` approximating the solution of the initial value problem\n\n        x\u2032 = f(t,x),  x(t\u2080) = x\u2080\n\non the interval `[t\u2080,tEnd]` (or `[tEnd,t\u2080]` if `tEnd < t\u2080`). 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 \u2267 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\u2080`\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]| \u2266 relativeScaling[i]\u22c5tol & |absoluteError[i]| \u2266 absoluteScaling[i]\u22c5tol\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 \u2266 minimalStepsizeScaling \u2266 newStepsize / oldStepsize \u2266 maximalStepsizeScaling\n\n* `safetyStepsizeSelection::S>0`. Use `safetyStepsizeSelection\u22c5tol` instead of `tol`. Default is `0.25`.\n* `minimumOrder::Int64 \u2267 1` and `maximumOrder::Int64 \u2266 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 \u2266 firstGuessOrder \u2266 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 (`\u0394[end] \u2260 tEnd`). Default is `10`.\n* `maximumSteps::Int64 \u2267 0` is the maximal length of the array `\u0394`. Exceeding this boundary leads to\n    ending the integration prematurely (`\u0394[end] \u2260 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   \u03c9::Array{Rational{BigInt},2}\n   \u03c1::Array{Rational{BigInt},1}\n\n   # weights and scaling factors for internal extrapolation operators (used for error estimate)\n   \u03c92::Array{Rational{BigInt},2}\n   \u03c12::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       \u03c92 = zeros(Rational{BigInt},N,N)\n       \u03c92[1,:] = ones(Rational{BigInt},1,N)\n       for n = 2:N\n           distance = nodes[2:n] .- nodes[n+1]\n           \u03c92[1:(n-1),n] = \u03c92[1:n-1,n-1] .// distance\n           \u03c92[n,n] = 1 // prod(-distance)\n       end\n\n       # compute barycentric weights for extrapolation operators\n       \u03c9 = zeros(Rational{BigInt},N+1,N+1)\n       for n = 1:N\n           \u03c9[n+1,(n+1):(N+1)] = \u03c92[n,n:N] // (nodes[n+1]-nodes[1])\n           \u03c9[1,n] = 1 // prod(nodes[1].-nodes[2:n])\n       end\n       \u03c9[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           \u03c9[1:m,m] = - \u03c9[1:m,m] .// nodes[1:m]\n           if 2 <= m\n               \u03c92[1:m-1,m-1] = - \u03c92[1:m-1,m-1] .// nodes[2:m]\n           end\n       end\n\n       # compute scaling factors for internal extrapolation operators\n       \u03c12 = ones(Rational{BigInt},N)\n       \u03c12[1] = -nodes[2]\n       for n = 1:(N-1)\n           \u03c12[n+1] = -\u03c12[n]*nodes[n+2]\n       end\n\n       # compute scaling factors for extrapolation operators\n       \u03c1 = -nodes[1]*[BigInt(1); \u03c12]\n\n       # initialize structure\n       new(subdividingSequence,\u03c9,\u03c1,\u03c92,\u03c12)\n   end\nend\n\nfunction (mySolver::solver)(\n            f::Function, x\u2080::Vector{T}, t\u2080::S, tEnd::S;\n            tol::S = parse(S,\"1e-3\"),\n            relativeScaling::Vector{S} =ones(S,size(x\u2080)),\n            absoluteScaling::Vector{S} = fill(parse(S,\"1e-3\"),size(x\u2080)),\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\u2080) # systems dimension\n    if 1<= minimumOrder <= maximumOrder <= length(mySolver.\u03c1)-1\n        n_ex, N_ex = minimumOrder, maximumOrder\n    else\n        error(\"Minimal and maximal order must satisfy: 1 \u2266 minimumOrder \u2266 maximumOrder \u2266 $(length(mySolver.\u03c1)-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            \u03c3\u1d63, \u03c3\u2090 = 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        \u0394 = zeros(S, maximumSteps + 1) # time grid\n        x\u0394 = 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    \u03bb = zeros(S, N_ex - n_ex +1) # storage for scaling factors of stepsize. \u03bb[k] contains the scalar for extr. order (k + n_ex - 1)\n    \u03c4_opt =zeros(S, N_ex - n_ex +1) # storage for optimal stepsize. \u03c4_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    \u0394[1], x\u0394[:,1] = t\u2080, x\u2080 # store inital values\n    tRest = tEnd - \u0394[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        \u03c4 = 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    \u03f5_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\u2080 + \u03c4 is saved in x\u0394[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 (\u0394[1:counterStep], x\u0394[:,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 (\u0394[1:counterStep], x\u0394[:,1:counterStep], detailedStatistics ? statistics[:,1:counterStep-1] : statistics)\n        end\n        if abs(\u03c4) <= eps(S)\n            println(\"Stepsize is becoming too small in step $(counterStep)!\")\n            return (\u0394[1:counterStep], x\u0394[:,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\u2080 = f(t\u2080,x\u2080) # the information for the Euler step\n        counterEvaluation = counterEvaluation + 1\n\n        for i = 0:n\n            X[:,i+1] = explicitMidpointRule(t\u2080,x\u2080,f\u2080,f,\u03c4,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 \u2266 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.\u03c9,mySolver.\u03c1')[1:(i+1),(i+1)]) # discretisation of order i\n                xx_i = X[:, 2:(i+1)]*T.(broadcast(*,mySolver.\u03c92,mySolver.\u03c12')[1:i, i]) # its internal counterpart\n            else\n                x_i = T.(mySolver.\u03c1[i+1])*(X[:, 1:(i+1)]*T.(mySolver.\u03c9[1:(i+1), (i+1)]))\n                xx_i = T.(mySolver.\u03c12[i])*(X[:, 2:(i+1)]*T.(mySolver.\u03c92[1:i, i]))\n            end\n            \u03c3 = max.(\u03c3\u2090, \u03c3\u1d63.*abs.(x_i)) # scaling for error estimate\n            \u03f5_i = sqrt(sum((abs.(x_i-xx_i)./\u03c3).^2)/d) # scaled mean square norm of the estimated error\n            \u03bb[i-n_ex+1] = min(p2, max(p1, (tol/\u03f5_i)^(1/(2i+1)))) # factor for optimal stepsize, including safety scaling\n            if i == n\n                x_n, \u03f5_n = x_i, \u03f5_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 \u03f5_n <= tol\n                # accept order n\n                converged = true\n                break\n            elseif \u03f5_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, \u03bb_n and \u03f5_n for new n:\n                X[:,n+1] = explicitMidpointRule(t\u2080,x\u2080,f\u2080,f,\u03c4,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.\u03c9,mySolver.\u03c1')[1:(n+1),(n+1)])\n                    xx_n = X[:, 2:(n+1)]*T.(broadcast(*,mySolver.\u03c92,mySolver.\u03c12')[1:n, n])\n                else\n                    x_n = T.(mySolver.\u03c1[n+1])*(X[:, 1:(n+1)]*T.(mySolver.\u03c9[1:(n+1), (n+1)])) # approximation of extrapolation order n\n                    xx_n = T.(mySolver.\u03c12[n])*(X[:, 2:(n+1)]*T.(mySolver.\u03c92[1:n, n])) # and its internal counterpart\n                end\n                \u03c3 = max.(\u03c3\u2090, \u03c3\u1d63.*abs.(x_n)) # scaling for error estimate\n                \u03f5_n = sqrt(sum((abs.(x_n-xx_n)./\u03c3).^2)/d) # scaled mean square norm of the estimated error\n                \u03bb[n-n_ex+1] = min(p2,max(p1,(tol/\u03f5_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\u2080 + \u03c4 and update statistics\n            \u0394[counterStep+1] = t\u2080 + \u03c4\n            x\u0394[:, counterStep+1] = x_n\n            tRest = tEnd - \u0394[counterStep+1]\n            maximalSteplength = min(abs(tRest),maximalSteplength)\n            if detailedStatistics\n                statistics[:,counterStep] = [n, \u03c4, 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\u2080, x\u2080  = \u0394[counterStep+1], x\u0394[:, counterStep+1] # new inital data\n\n                ## compute optimal order m and stepsize \u03c4 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                \u03c4_opt[temp] = min.(abs(\u03c4)*\u03bb[temp], maximalSteplength) # safety boundary for \u03c4_opt\n                \u03c9 = s[temp]./(\u03c4_opt[temp]) # work per step\n\n                m = argmin(\u03c9) + 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                    \u03bb[n-n_ex+2] = min(p2, max(p1, (tol^(s[n-n_ex+1]/s[n-n_ex+2])/\u03f5_n)^(1/(2n+1))))\n                    # check if work dereases from order m to  m+1\n                    if \u03c9[end] > s[n-n_ex+2]/(\u03c4_opt[n-n_ex+2] = min(abs(\u03c4)*\u03bb[n-n_ex+2], maximalSteplength))\n                        m = m + 1\n                    end\n                end\n                \u03c4 = flipsign(\u03c4_opt[m-n_ex+1],\u03c4) # accomodate backward integration\n\n                counterStep = counterStep + 1\n                converged = false\n                counterEvaluation = 0\n                counterReduction = 0\n                fill!(\u03bb,zero(S))\n                fill!(\u03c4_opt,zero(S))\n            end\n        else\n            counterReduction = counterReduction + 1\n            # compute reduced stepsize \u03c4 for order m. Use latest error estimate \u03f5_n if estimate of order m is not available\n            if n < m\n                 \u03bb[m-n_ex+1] = min(p2,max(p1,(tol^(s[n-n_ex+1]/s[m-n_ex+1])/\u03f5_n)^(1/(2n+1))))\n            end\n            \u03c4_opt[m-n_ex+1] = min(abs(\u03c4)*\u03bb[m-n_ex+1],maximalSteplength) # safety boundary for \u03c4_opt\n            \u03c4 = flipsign(\u03c4_opt[m-n_ex+1],\u03c4) # accomodate backward integration\n        end\n    end # integration loop\n    return (\u0394[1:counterStep+1], x\u0394[:,1:counterStep+1], detailedStatistics ? statistics[:,1:counterStep] : statistics)\nend\n\n\"\"\"\n    explicitMidpointRule(t\u2080,x\u2080,f\u2080,f,\u03c4,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\u2080 + n/N*\u03c4 for n = 0:N]`\nwith the initial data `(t\u2080,x\u2080)` and the right side `f`.\nIn the starting step `f\u2080` is used instead of `f(t\u2080,x\u2080)`.\n\"\"\"\nfunction explicitMidpointRule(t\u2080::S,x\u2080::Vector{T},f\u2080::Vector{T},f::Function,\u03c4::S,N) where{S<:AbstractFloat, T<:Number}\n    \u03c4_n = \u03c4/N\n    x = x\u2080 + \u03c4_n*f\u2080\n    for i = 0:N-2\n        temp = x\n        x = x\u2080+2*\u03c4_n*f(t\u2080+(i+1)*\u03c4_n,x)\n        x\u2080 = 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# \u2554\u2550\u2561 4133e4a2-ed4d-11ea-11cd-0da48c09c2e8\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 54bd3938-ed4d-11ea-29e4-c1c7020c1400\nbegin\n\t@quickactivate \"SR2TuringPluto\"\n\tusing StatisticalRethinking\nend\n\n# \u2554\u2550\u2561 0c5fe59e-ed4f-11ea-35a8-45c3aff83362\nmd\"## Broadcasting.jl\"\n\n# \u2554\u2550\u2561 54ccfc74-ed4d-11ea-366d-b738d54ff79a\np_grid = range(0, 1, length = 5)\n\n# \u2554\u2550\u2561 54d9bce8-ed4d-11ea-279e-3bc3bf465e28\nprior = ones(5)\n\n# \u2554\u2550\u2561 54da91d4-ed4d-11ea-04f5-e9a4f8c659a3\nlikelihood = pdf.(Binomial.(9, p_grid), 6)\n\n# \u2554\u2550\u2561 54e45ff4-ed4d-11ea-0288-e3475c709007\nposterior = likelihood .* prior\n\n# \u2554\u2550\u2561 54e8f906-ed4d-11ea-2fee-316c2df1d8f6\nposterior ./= sum(posterior)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e822d97e-ed4f-11ea-2c18-17ecfc81fdbd\nmd\"## End of broadcasting.jl\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000c5fe59e-ed4f-11ea-35a8-45c3aff83362\n# \u2560\u25504133e4a2-ed4d-11ea-11cd-0da48c09c2e8\n# \u2560\u255054bd3938-ed4d-11ea-29e4-c1c7020c1400\n# \u2560\u255054ccfc74-ed4d-11ea-366d-b738d54ff79a\n# \u2560\u255054d9bce8-ed4d-11ea-279e-3bc3bf465e28\n# \u2560\u255054da91d4-ed4d-11ea-04f5-e9a4f8c659a3\n# \u2560\u255054e45ff4-ed4d-11ea-0288-e3475c709007\n# \u2560\u255054e8f906-ed4d-11ea-2fee-316c2df1d8f6\n# \u255f\u250054f1592c-ed4d-11ea-0210-0be7741d2604\n# \u255f\u2500e822d97e-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 + \u03bd u_{xx}\\$ for numerical integration in Fourier space where \u03bd 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 + \u03bd u_{xx}\\$ for numerical integration in Fourier space where \u03bd 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*\u03c0/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*\u03c0/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 + \u03bd 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); # \u0304u_{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\u03c0 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\u2081(i::Int) = max(6 - abs(i-7), 0)\nh\u2082(i::Int) = h\u2081(i - 8)\nh\u2083(i::Int) = h\u2081(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  \u03f5 = rand(Normal(0,1),(L,c1+c2+c3))\n\n  y = string.(vcat(ones(c1), ones(c2) .+ 1, ones(c3) .+ 2))\n\n  H\u2081 = Array{Float64,2}(undef,L,c1)\n  H\u2082 = Array{Float64,2}(undef,L,c2)\n  H\u2083 = Array{Float64,2}(undef,L,c3)\n  for i in 1:L\n    H\u2081[i,:] .= u * h\u2081(i) + (1 - u) * h\u2082(i)\n    H\u2082[i,:] .= u * h\u2081(i) + (1 - u) * h\u2083(i)\n    H\u2083[i,:] .= u * h\u2082(i) + (1 - u) * h\u2083(i)\n  end\n\n  H = hcat(H\u2081, H\u2082, H\u2083) + \u03f5\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": "using Flux\nusing Statistics\nusing CalibrationErrors\nusing ReliabilityDiagrams\n\n# TODO: Work on GPU friendly implementations of these metrics \n\nfunction get_mean_std_dev(x::AbstractArray; dims = ndims(x))\n    \u03bc = mean(x, dims = dims)\n    \u03c3 = std(x, dims = dims, corrected = false)\n    return \u03bc, \u03c3\nend\n\nfunction calculate_entropy(probs, eps = 1e-6; from_logits = true)\n    if from_logits\n        probs = softmax(probs, dims = 1)\n    end\n    return -sum(probs .* log.(probs .+ eps), dims = 1)\nend\n\nfunction mean_loglikelihood(preds, labels)\n    return mean(log(p[s]) for (s, p) in zip(labels, preds))\nend\n\nfunction brier_score(preds, labels)\n    return mean(\n        sum(abs2(pi - (i == s)) for (i, pi) in enumerate(p)) for\n        (s, p) in zip(labels, preds)\n    )\nend\n\nfunction expected_calibration_error(preds, labels, num_bins = 10; from_logits = true)\n    if from_logits\n        preds = softmax(preds, dims = 1)\n    end\n    preds = cpu(preds)\n    labels = cpu(labels)\n    preds = [x for x in eachcol(preds)]\n    ece_estimator = ECE(UniformBinning(num_bins), SqEuclidean())\n    ece = ece_estimator(preds, labels)\n    return ece\nend\n\n\nfunction prediction_metrics(preds, labels)\n    metrics = Dict()\n    preds = [x for x in eachcol(preds)]\n    # Calulate mean loglikelihood \n    metrics[\"mean_log_likelihood\"] = mean_loglikelihood(preds, labels)\n    # Brier Score \n    metrics[\"brier_score\"] = brier_score(preds, labels)\n    return metrics\nend\n", "meta": {"hexsha": "d56bc24fe881aea9a02fdd10c3bceb3af07bc69a", "size": 1444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metrics.jl", "max_stars_repo_name": "aced-differentiate/DeepUncertainty.jl", "max_stars_repo_head_hexsha": "203a01bd832fe80a58adafeba7bdadc2bd5742e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-09-30T11:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T21:50:29.000Z", "max_issues_repo_path": "src/metrics.jl", "max_issues_repo_name": "aced-differentiate/DeepUncertainty.jl", "max_issues_repo_head_hexsha": "203a01bd832fe80a58adafeba7bdadc2bd5742e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-09-27T09:54:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T07:33:02.000Z", "max_forks_repo_path": "src/metrics.jl", "max_forks_repo_name": "aced-differentiate/DeepUncertainty.jl", "max_forks_repo_head_hexsha": "203a01bd832fe80a58adafeba7bdadc2bd5742e6", "max_forks_repo_licenses": ["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.7407407407, "max_line_length": 85, "alphanum_fraction": 0.6765927978, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.7592227206883304}}
{"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 IntroAlgoCh2\n\nfunction insertionsort!(A::AbstractArray)\n    for j=2:length(A)\n        key = A[j]\n\n        i = j - 1\n        while i > 0 && A[i] > key\n            A[i+1] = A[i]\n            i = i - 1\n        end\n        A[i+1] = key\n    end\n    return A\nend\n\nfunction _merge!(A::Array, p::Int, q::Int, r::Int)\n    n1 = q - p + 1\n    n2 = r - q\n\n    L = A[p:q]\n    R = A[q+1:r]\n\n    i=1\n    j=1\n\n    for k=p:r\n        if L[i] <= R[j]\n            A[k] = L[i]\n            i+=1\n            if i >  n1\n                A[k+1:r] .= R[j:end]\n                break\n            end\n        else\n            A[k] = R[j]\n            j+=1\n\n            if j > n2\n                A[k+1:r] .= L[i:end]\n                break\n            end\n        end\n    end\nend\n\nfunction _mergesort!(A::Array, p::Int, r::Int)\n    if p<r\n        q = (p+r)\u00f72\n        _mergesort!(A,p,q)\n        _mergesort!(A,q+1,r)\n        _merge!(A,p,q,r)\n    end\nend\n\nfunction mergesort!(A::Array)\n    _mergesort!(A, 1, length(A))\n\n    return A\nend\n\nfunction mergesort_iterative!(A::Array)\n    N = length(A)\n    B = similar(A)\n\n    #sorting\n    for k=1:2:N-1\n        if A[k] <= A[k+1]\n            B[k] = A[k]\n            B[k+1] = A[k+1]\n        else\n            B[k] = A[k+1]\n            B[k+1] = A[k]\n        end\n    end\n    if isodd(N)\n        B[N] = A[N]\n    end\n    A, B = B, A #A is nu gesorteerd (deels) en B is garbage\n\n    #merging\n    mergestep = 2\n    while mergestep < N\n        for start = 1:mergestep*2:N\n            if mergestep >= N - start\n                break #er blijft nog maar een partitie over en die is al gesorteerd\n            end\n\n            p = start  #eerst index rij1\n            q = start + mergestep #eerste index rij2\n            r = min(q + mergestep - 1, N) #laatste index rij2\n\n            i = p\n            j = q\n\n            for k=p:r\n                if A[i] <= A[j]\n                    B[k] = A[i]\n                    i+=1\n                    if i >= q\n                        @views B[k+1:r] = A[j:r]\n                        break\n                    end\n                else\n                    B[k] = A[j]\n                    j+=1\n\n                    if j > r\n                        @views B[k+1:r] =  A[i:q-1]\n                        break\n                    end\n                end\n            end\n            A, B = B, A\n        end\n        mergestep *= 2\n    end\n\n    return A\nend\n\nfunction mergesort_iterative_optimized!(A::Array)\n    N = length(A)\n    if N <= 64\n        return insertionsort!(A)\n    end\n\n    B = similar(A)\n\n    #sorting\n    sortrange = 1:64:N-64\n    for i=sortrange\n        insertionsort!(@views A[i:i+64])\n    end\n    insertionsort!(@views A[maximum(sortrange)+1:N])\n    #A is nu gesorteerd (deels) en B is garbage\n\n    #merging\n    mergestep = 64\n    while mergestep < N\n        for start = 1:mergestep*2:N\n            if mergestep >= N - start\n                break #er blijft nog maar een partitie over en die is al gesorteerd\n            end\n\n            p = start  #eerst index rij1\n            q = start + mergestep #eerste index rij2\n            r = min(q + mergestep - 1, N) #laatste index rij2\n\n            i = p\n            j = q\n\n            for k=p:r\n                if A[i] <= A[j]\n                    B[k] = A[i]\n                    i+=1\n                    if i >= q\n                        @views B[k+1:r] = A[j:r]\n                        break\n                    end\n                else\n                    B[k] = A[j]\n                    j+=1\n\n                    if j > r\n                        @views B[k+1:r] =  A[i:q-1]\n                        break\n                    end\n                end\n            end\n            A, B = B, A\n        end\n        mergestep *= 2\n    end\n\n    return A\nend\n\n\n\n\nfunction _binarysearch(S_sorted::Vector{Int}, target::Int, low::Int, high::Int)::Union{Nothing, Int}\n    if low == high\n        return (S_sorted[low] == target ? low : nothing)\n    end\n\n    mid = (low + high)\u00f72\n\n    if S_sorted[mid] == target\n        return mid\n    elseif S_sorted[mid] > target\n        return _binarysearch(S_sorted, target, low, mid)\n    else\n        return _binarysearch(S_sorted, target, mid, high)\n    end\nend\n\nfunction sumfinder(S::Vector{Int}, x::Int)::Union{Nothing, Tuple{Int, Int}}\n    mergesort!(S)\n\n    n = length(S)\n\n    for i=1:n-1\n        idx = let\n            target = x - S[i]\n            low = i+1\n            high = n\n\n            _binarysearch(S, target, low, high)\n        end\n        if idx !== nothing\n            return (i, idx)\n        end\n    end\n\n    return nothing\n\nend\n\nexport insertionsort!, mergesort!, _binarysearch, sumfinder, mergesort_iterative!, mergesort_iterative_optimized!\n\n\nend\n", "meta": {"hexsha": "e136f2b45f337931a0ff860f5c2b3e0e795e1c4a", "size": 4688, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IntroAlgoCh2.jl", "max_stars_repo_name": "Dejan-Ilic/IntroAlgoCh2", "max_stars_repo_head_hexsha": "dcc7a8f83f399e1fcfe55f475e3765f124313e90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IntroAlgoCh2.jl", "max_issues_repo_name": "Dejan-Ilic/IntroAlgoCh2", "max_issues_repo_head_hexsha": "dcc7a8f83f399e1fcfe55f475e3765f124313e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IntroAlgoCh2.jl", "max_forks_repo_name": "Dejan-Ilic/IntroAlgoCh2", "max_forks_repo_head_hexsha": "dcc7a8f83f399e1fcfe55f475e3765f124313e90", "max_forks_repo_licenses": ["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.9285714286, "max_line_length": 113, "alphanum_fraction": 0.4174488055, "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.7592140492632848}}
{"text": "# ---\n# title: 1359. Count All Valid Pickup and Delivery Options\n# id: problem1359\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Math, Dynamic Programming\n# link: <https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/description/>\n# hidden: true\n# ---\n# \n# Given `n` orders, each order consist in pickup and delivery services.\n# \n# Count all valid pickup/delivery possible sequences such that delivery(i) is\n# always after of pickup(i).\n# \n# Since the answer may be too large, return it modulo 10^9 + 7.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 1\n#     Output: 1\n#     Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 2\n#     Output: 6\n#     Explanation: All possible orders: \n#     (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\n#     This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: n = 3\n#     Output: 90\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n <= 500`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "10afa7a6fa2b3ba8bbf696bf6f7c1690fdea8c0b", "size": 1234, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1359.count-all-valid-pickup-and-delivery-options.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/1359.count-all-valid-pickup-and-delivery-options.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/1359.count-all-valid-pickup-and-delivery-options.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.2295081967, "max_line_length": 98, "alphanum_fraction": 0.5883306321, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7592140401148703}}
{"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;\u03bb=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       \u03bc=mean(X,dims=1)\r\n       \u03c3=std(X,dims=1)\r\n       X=(X.-\u03bc)./\u03c3\r\n    else\r\n        \u03bc=zeros(1,n)\r\n        \u03c3=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 (\u03b8)\r\n                    se=(X*\u03b8).-y\r\n                    J=(0.5./m).*((se'*se)+\u03bb*(\u03b8[2:end]'*\u03b8[2:end]))\r\n                    return J\r\n                end\r\n    \u03b8r=zeros(n+1)\r\n    Gradient=function (\u03b8)\r\n             \u03b8r.=\u03b8\r\n             \u03b8r[1]=0\r\n             g=(1/m).*(X'*((X*\u03b8).-y)) .+ ((\u03bb./m).*\u03b8r)\r\n        return g\r\n            end\r\n\r\n    return CostFunction, Gradient, \u03bc, \u03c3\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*\u03c4\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=\u221e`, smooth data),\n- `\u03bb` is the length of spatial localization (default is `\u03bb=\u221e`, 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\u03c0))` if `s=\u221e`, or `w=1/(1+9(|k|L/(2\u03c0))^(s+1/2))` otherwise.\nIf `\u03bb\u2260\u221e`, the function in spatial variables is multiplied by `exp(-|x/\u03bb|^2)`,\nand in any case normalized to have maximum absolute value 1.\n\n\n\"\"\"\nfunction random( x;L=1,s=Inf,\u03bb=Inf,a=1 )\n\n\n    k = Mesh( x ).k\n    if s == Inf\n        w = 10 .^(-abs.(k*L/(2*\u03c0)))\n    else\n        w = 1 ./( 1 .+ 9*abs.(k*L/(2*\u03c0)).^(s+1/2) )\n    end\n    if \u03bb == Inf\n        \u03c6 = zero(x).+1\n    else\n        \u03c6 = exp.(-abs.((x/\u03bb).^2))\n    end\n\n    \u03b8 = 2*\u03c0*rand(Float64,length(x))\n    r = rand(Float64,length(x))\n    Fourier = r.*exp.(-1im.*\u03b8).*w\n    Physic = real.(ifft(Fourier)).*\u03c6\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=\u221e`),\n- `\u03bb` is the length of spatial localization (default is `\u03bb=\u221e`, 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.\u03b7` and `init.v` two samples of `random(x;L,s,\u03bb)`,\nwhere `x` is the set of collocation points generated by `Mesh(param)`.\n\n\"\"\"\nstruct Random <: InitialData\n\n    \u03b7\n    v\n    label :: String\n    info  :: String\n\n    function Random(param;L=1,s=Inf,\u03bb=Inf,a=(1,1))\n        mesh=Mesh(param);x=mesh.x;\n        \u03b7 = random( x; L=L,s=s,\u03bb=\u03bb,a=a[1] )\n        v = random( x; L=L,s=s,\u03bb=\u03bb,a=a[2] )\n        init=Init(x,\u03b7,v)\n        if s == Inf s=\"\u221e\" end\n        if \u03bb == Inf \u03bb=\"\u221e\" end\n        label = \"randomly generated\"\n        info = \"Randomly generated initial data with \\n\\\n        \u251c\u2500\u2500\u2500typical wavelength: L = $L,\\n\\\n        \u251c\u2500\u2500\u2500\u2500\u2500regularity index: s = $s,\\n\\\n        \u251c\u2500spatial localization: \u03bb = $\u03bb,\\n\\\n        \u251c\u2500\u2500\u2500\u2500surface amplitude: $(a[1]),\\n\\\n        \u2514\u2500\u2500\u2500velocity amplitude: $(a[2]).\"\n    \tnew( init.\u03b7,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": "@testset \"sm\" begin\n    v1 = rand(5)\n    v2 = rand(5)\n\n    \u03b1s\u2081 = rand(3)\n    \u03b1s\u2082 = rand(5, 3)\n    \u03b3s = rand(5, 3)\n    \u03c9s = rand(5, 3)\n\n    k1 = spectral_mixture_kernel(\u03b1s\u2081, \u03b3s, \u03c9s)\n    k2 = spectral_mixture_product_kernel(\u03b1s\u2082, \u03b3s, \u03c9s)\n\n    t = v1 - v2\n\n    @test k1(v1, v2) \u2248 sum(\u03b1s\u2081 .* exp.(-(t' * \u03b3s)'.^2) .*\n                           cospi.((t' * \u03c9s)')) atol=1e-5\n\n    @test k2(v1, v2) \u2248 prod(sum(\u03b1s\u2082[i,:]' .* exp.(-(\u03b3s[i,:]' * t[i]).^2) .*\n                                cospi.(\u03c9s[i,:]' * t[i])) for i in 1:length(t)) atol=1e-5\n\n    @test_throws DimensionMismatch spectral_mixture_kernel(rand(5) ,rand(4,3), rand(4,3))\n    @test_throws DimensionMismatch spectral_mixture_kernel(rand(3) ,rand(4,3), rand(5,3))\n    @test_throws DimensionMismatch spectral_mixture_product_kernel(rand(5,3) ,rand(4,3), rand(5,3))\n    # test_ADs(x->spectral_mixture_kernel(exp.(x[1:3]), reshape(x[4:18], 5, 3), reshape(x[19:end], 5, 3)), vcat(log.(\u03b1s\u2081), \u03b3s[:], \u03c9s[:]), dims = [5,5])\n    @test_broken \"No tests passing (BaseKernel)\"\nend\n", "meta": {"hexsha": "daef2bd62f1f5642f2dc6f394c177f471646eb23", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/sm.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": "test/basekernels/sm.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": "test/basekernels/sm.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": 37.7777777778, "max_line_length": 151, "alphanum_fraction": 0.562745098, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7591560343314876}}
{"text": "using ApproxFun, BandedMatrices, BlockBandedMatrices, LinearAlgebra, BlockArrays, MultivariateOrthogonalPolynomials, Test\nusing SparseVolterraExamples\n\n#############################\n## Tests for Volterra integral equations of first and second kind\n## with Clenshaw Jacobi expansion of the kernel.\n####\n## Includes tests for 1 to x and 1 to 1-x limits of integration.\n#############################\n\n@testset \"Volterra Integral Equation 1st kind, could be monomial, flip=true\" begin\n    g(x) = sin(x)-x*cos(x);\n    K(x,y) = y;\n    @test triVolterraEQ1FullKernelSolver(g,K,30,true) \u2248 Fun(x->sin(x),Jacobi(0,1, 0..1))\n    #########################################################################\n    g(x) = 2+x-2*exp(x)+x*exp(x)\n    K(x,y) = x-y;\n    @test triVolterraEQ1FullKernelSolver(g,K,20,true) \u2248 Fun(x->x*exp(x),Jacobi(0,1, 0..1))\nend\n\n@testset \"Volterra Integral Equation 1st kind, could be monomial, flip=false\" begin\n    N = 20\n    g(x) = 3-x-2*exp(1-x)+(1-x)*exp(1-x);\n    K(x,y) = 1-y-x;\n    @test triVolterraEQ1FullKernelSolver(g,K,N,false) \u2248 Fun(x -> x*exp(x), Jacobi(0,1,0..1))\nend\n\n@testset \"Volterra Integral Equation 1st kind, not monomial, flip=false\" begin\n    N = 20;\n    g(x) = 1/12*(4-4*(-1+x)^3+3*(-1+x)^4-4*cos((1-x)^3))\n    K(x,y) = 1+y+sin(y^3);\n    @test triVolterraEQ1FullKernelSolver(g,K,N,false) \u2248 Fun(x->x^2,Jacobi(0,1,0..1))\nend\n\n@testset \"Volterra Integral Equation 2nd kind, could be monomial, flip=false\" begin\n    N = 15;\n    S = Jacobi(0,1,0..1);\n    g = Fun(x -> (x-1)*cos(2*pi*(1-x))/(2*pi)+((4*pi^2+1)/(4*pi^2))*sin(2*pi*(1-x)), S);\n    K(x,y)=y;\n    @test triVolterraEQ2FullKernelSolver(g,K,N,false) \u2248 Fun(x -> sin(2*pi*(1-x)), S)\n    #########################################################################\n    N = 15;\n    S = Jacobi(0,1,0..1);\n    g = Fun(x -> (-17/30)*x^6+2*x^5-(3/2)*x^4-(11/2)*x^3+(15/2)*x^2-(21/10)*x+1/6, S);\n    K(x,y) = 7*x*y+5*y^2;\n    @test triVolterraEQ2FullKernelSolver(g,K,N,false) \u2248 Fun(x -> 1-x^3, S)\nend\n\n@testset \"Volterra Integral Equation 2nd kind, not monomial, flip=true\" begin\n    g = Fun(x->x^2+2*x-exp(x)+2, Jacobi(0,1,0..1));\n    K(x,y) = (y-x)^2;\n    @test triVolterraEQ2FullKernelSolver(g,K,20,true) \u2248 Fun(x->exp(x),Jacobi(0,1,0..1));\nend\n", "meta": {"hexsha": "2a2c24163074b1eaae7f793347fff7baf0ba7179", "size": 2223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_VolterraEqns-FullKernel.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": "test/test_VolterraEqns-FullKernel.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": "test/test_VolterraEqns-FullKernel.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": 41.1666666667, "max_line_length": 121, "alphanum_fraction": 0.5645524067, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7591560337505753}}
{"text": "using BenchmarkTools\nusing LinearAlgebra\n\nfunction progonka!(u,a,b,c,f)\n    N = size(f,1)\n    \u03b1=similar(f)\n    \u03b2=similar(f)\n    \u03b1[2] = -c[1]/b[1]\n    \u03b2[2] = f[1]/b[1]\n    @inbounds @fastmath for i in 2:N-1 #Forward Sweep\n        \u03b1[i+1]=-c[i]/(a[i-1]*\u03b1[i]+b[i])\n        \u03b2[i+1]=(f[i]-a[i-1]*\u03b2[i])/(a[i-1]*\u03b1[i]+b[i])\n    end\n    u[N]=(f[N]-a[N-1]*\u03b2[N])/(a[N-1]*\u03b1[N]+b[N])\n    @inbounds @fastmath for i in N-1:-1:1 #Backward Sweep\n        u[i]=\u03b1[i+1]*u[i+1]+\u03b2[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\u2248upro\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": "using SKTB.FermiContour\nusing Test\n\n# Compare the rate of convergence with the predicted rate.\n# Not a proper unit test, but good enough for our purposes.\n\n@testset \"FermiContour\" begin\n\nE1 = 0\nE2 = 1\n\u03b2 = 10.0\nn = 2:2:18\nx = range(E1,stop=E2,length=100)\n\n# Compute empirical convergence rate\nerror = zeros(length(n))\nfor i = 1:length(n)\n    w,z = fermicontour(E1,E2,\u03b2,n[i])\n    fx = sum(real(w*fermidirac.(z,\u03b2) ./ (z  .- x)) for (w,z) in zip(w,z))\n    error[i] = maximum(abs.(fermidirac.(x,\u03b2) .- fx))\nend\n\n# Compute theoretical convergence rate\nm = E1^2 + \u03c0^2/\u03b2^2\nM = E2^2 + \u03c0^2/\u03b2^2\nk = (sqrt(M/m)-1)/(sqrt(M/m)+1)\nK = SKTB.FermiContour.JacobiFunc.K(k^2)\niK = SKTB.FermiContour.JacobiFunc.iK(k^2)\npredicted = 2 * exp.(-\u03c0*iK/(2K)*n)\n\nprintln(\"n   error    predicted    err/pred\")\ndisplay([n  error predicted error./predicted]); println()\n@test maximum(abs.(error./predicted .- 1.0)) < 0.1\n\n# TODO: implement analogous test for 0T contour!\n\nend\n", "meta": {"hexsha": "ef4fd2e831811cb89543de7d071aef0bae49e58b", "size": 943, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testcontour.jl", "max_stars_repo_name": "Quejiahao/SKTB.jl", "max_stars_repo_head_hexsha": "aee9f9fd5beccfcb36120a0fac4b977304e52a49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-09-11T16:47:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-29T09:53:23.000Z", "max_issues_repo_path": "test/testcontour.jl", "max_issues_repo_name": "Quejiahao/SKTB.jl", "max_issues_repo_head_hexsha": "aee9f9fd5beccfcb36120a0fac4b977304e52a49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2016-08-23T18:25:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-30T12:50:33.000Z", "max_forks_repo_path": "test/testcontour.jl", "max_forks_repo_name": "Quejiahao/SKTB.jl", "max_forks_repo_head_hexsha": "aee9f9fd5beccfcb36120a0fac4b977304e52a49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-27T15:15:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T21:39:17.000Z", "avg_line_length": 24.8157894737, "max_line_length": 73, "alphanum_fraction": 0.6617179215, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7591560283742664}}
{"text": "using ArtificialBeeColony\n\n# initializer for bees' position\nfunction init()\n    rand(1)*20 .- 10   # [-10, 10] \nend\n\n# target function\nfunction target(x::Vector{Float64})\n    x[1]^2+10*sin(2*x[1])\nend\n\nN = 50       # the number of bees\nepoch = 100  # the number of iteration\nflag = true  # time invariant flag\n\nabc = ABC(N, init)\nbest = search!(abc, target; epoch=epoch, time_invariant=flag)\n\nprintln(\"x = \", best[1])\nprintln(\"target(x) = \", target(best))\n", "meta": {"hexsha": "1105ebe618c39420b46b50199b63175a323d0106", "size": 456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/ex.jl", "max_stars_repo_name": "peakbook/ArtificialBeeColony.jl", "max_stars_repo_head_hexsha": "5185bb0ccfb9a3b9f24ed1407df60c7e398e0cf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-28T18:54:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T20:00:31.000Z", "max_issues_repo_path": "example/ex.jl", "max_issues_repo_name": "peakbook/ArtificialBeeColony.jl", "max_issues_repo_head_hexsha": "5185bb0ccfb9a3b9f24ed1407df60c7e398e0cf0", "max_issues_repo_licenses": ["MIT"], "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/ex.jl", "max_forks_repo_name": "peakbook/ArtificialBeeColony.jl", "max_forks_repo_head_hexsha": "5185bb0ccfb9a3b9f24ed1407df60c7e398e0cf0", "max_forks_repo_licenses": ["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.7272727273, "max_line_length": 61, "alphanum_fraction": 0.6578947368, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7591560260012509}}
{"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 \u2264 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": "\"\"\"\nCopyright Marcus Greiff 2020\n\nFull test suite for the aerial vehicle controller generation\n\"\"\"\n\nusing LinearAlgebra, Test, AerialVehicleControl\n\nrecompile()        # Recompile the C-code\nrunAllTests = true # If defined, will not recompile the C-code\n\n@testset \"All tests\" begin\n    @testset \"Math library tests\" begin\n        include(\"controller_math/test_math_functions.jl\")\n        include(\"controller_math/test_SO3_maps.jl\")\n        include(\"controller_math/test_SU2_maps.jl\")\n    end\n    @testset \"Attitude controllers\" begin\n        include(\"controller_implementations/test_FSF_attitude_utils.jl\")\n        include(\"controller_implementations/test_FSF_continuous_SO3.jl\")\n        include(\"controller_implementations/test_FSF_robust_SO3.jl\")\n        include(\"controller_implementations/test_FSF_continuous_SU2.jl\")\n        include(\"controller_implementations/test_FSF_discontinuous_SU2.jl\")\n        include(\"controller_implementations/test_FSF_robust_SU2.jl\")\n        include(\"controller_implementations/test_FOF_continuous_SO3.jl\")\n    end\n    @testset \"General utility functions\" begin\n        include(\"controller_utils/test_power_distribution.jl\")\n    end\n    @testset \"Matrix math functions\" begin\n        include(\"matrix_math/test_matrix_addition_inplace.jl\")\n        include(\"matrix_math/test_matrix_addition.jl\")\n        include(\"matrix_math/test_matrix_eigvals.jl\")\n        include(\"matrix_math/test_matrix_multiplication.jl\")\n        include(\"matrix_math/test_matrix_solve_posdef.jl\")\n        include(\"matrix_math/test_matrix_subtraction_inplace.jl\")\n        include(\"matrix_math/test_matrix_subtraction.jl\")\n        include(\"matrix_math/test_matrix_transposition.jl\")\n    end\nend\n", "meta": {"hexsha": "706445ce58b94f9a925c901bc6c48a0855afda9d", "size": 1697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "mgreiff/AerialVehicleControl.jl", "max_stars_repo_head_hexsha": "4ef385414e92af05518f4449de9080a3a00fcebd", "max_stars_repo_licenses": ["MIT"], "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": "mgreiff/AerialVehicleControl.jl", "max_issues_repo_head_hexsha": "4ef385414e92af05518f4449de9080a3a00fcebd", "max_issues_repo_licenses": ["MIT"], "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": "mgreiff/AerialVehicleControl.jl", "max_forks_repo_head_hexsha": "4ef385414e92af05518f4449de9080a3a00fcebd", "max_forks_repo_licenses": ["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.3902439024, "max_line_length": 75, "alphanum_fraction": 0.7513258692, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7591560168470985}}
{"text": "function solve_008(n::Int64)\n\n    # Hardcode string\n    str = \"7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450\"\n\n    max_prod = 0\n    # Iterate over string and multiply digits\n    for j = 1:(1000-n)\n        sub_str = str[j:j+n]\n        prod = 1\n        for i = 1:n\n            prod *= parse(Int64,sub_str[i])\n        end\n        if prod > max_prod\n            max_prod = prod\n        end\n    end\n\n    return max_prod\nend\n", "meta": {"hexsha": "e168fbabf8e7067eba8b4e27ee2823998473c745", "size": 1374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/008.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/008.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/008.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": 65.4285714286, "max_line_length": 1012, "alphanum_fraction": 0.8668122271, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7591560168470984}}
{"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 \u03b4\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 \u03c0^(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 \u03c0^(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": "# Create example data\nx = LinRange(-2, 2, 40)\nf(t) = t^3 + t^2 + t\ny = f.(x)\n# Plot x and y\nplot(x, y)\n# Plot x using the callable\nplot(x, f)\n# Plot y, using its indices for the x values\nplot(y)\n# Plot two columns\nplot(x, [y 3x.^2 .- 3])\n# Plot various series them with custom line specs\ny2 = 3x.^2 .- 3\nplot(x, y, \"-r\", x, y2, \":*b\")\n", "meta": {"hexsha": "aa3771a6cccdf3934869658746073e6cd6e71973", "size": 335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/docstrings/plot.jl", "max_stars_repo_name": "UnofficialJuliaMirror/GRUtils.jl-0337cf30-a0fd-11e9-31db-a79914c9d7ac", "max_stars_repo_head_hexsha": "0fe8a3950c1af7e2a55106e599c7ca36a990c963", "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/plot.jl", "max_issues_repo_name": "UnofficialJuliaMirror/GRUtils.jl-0337cf30-a0fd-11e9-31db-a79914c9d7ac", "max_issues_repo_head_hexsha": "0fe8a3950c1af7e2a55106e599c7ca36a990c963", "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/plot.jl", "max_forks_repo_name": "UnofficialJuliaMirror/GRUtils.jl-0337cf30-a0fd-11e9-31db-a79914c9d7ac", "max_forks_repo_head_hexsha": "0fe8a3950c1af7e2a55106e599c7ca36a990c963", "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": 20.9375, "max_line_length": 49, "alphanum_fraction": 0.6, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.7590479371791574}}
{"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    sum_of_bit_difference(array::Array{Int64,1})\n\nFor finding the sum of bit differences in all pairs of an array, the array will be\ntransformed into a series of subarrays  for a given bit-length.\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr = [8, 1, 2, 12, 45, 100, 43]\njulia> ClassicAlgorithmsCollections.maximum_xor_subarray(arr)\n104\n```\n\"\"\"\nfunction sum_of_bit_difference(array::Array{Int64,1}, bit = 32)\n    n = length(array)\n    result = 0\n    for i in 1:bit\n        count = 0\n        for j in 1:n\n            if (array[j] & (1 << i)) != 0\n                count += 1\n            end\n        end\n        result += count * (n - count) * 2\n    end\n    return result\nend\n", "meta": {"hexsha": "956f7f7cc07010f824e314f133e7e4babbaefd9a", "size": 769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BitManipulation/SumOfBitDifference.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/SumOfBitDifference.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/SumOfBitDifference.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": 22.6176470588, "max_line_length": 82, "alphanum_fraction": 0.6215864759, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7590433470610772}}
{"text": "\"\"\"\n    TDist(\u03bd)\n\nThe *Students T distribution* with `\u03bd` 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    \u03bd::T\n    TDist{T}(\u03bd::T) where {T <: Real} = new{T}(\u03bd)\nend\n\nfunction TDist(\u03bd::T) where {T <: Real}\n    @check_args(TDist, \u03bd > zero(\u03bd))\n    return TDist{T}(\u03bd)\nend\n\nTDist(\u03bd::T, ::NoArgCheck) where {T<:Real} = TDist{T}(\u03bd)\nTDist(\u03bd::Integer) = TDist(float(\u03bd))\n\n@distr_support TDist -Inf Inf\n\n#### Conversions\nconvert(::Type{TDist{T}}, \u03bd::Real) where {T<:Real} = TDist(T(\u03bd))\nconvert(::Type{TDist{T}}, d::TDist{S}) where {T<:Real, S<:Real} = TDist(T(d.\u03bd), NoArgCheck())\n\n#### Parameters\n\ndof(d::TDist) = d.\u03bd\nparams(d::TDist) = (d.\u03bd,)\n@inline partype(d::TDist{T}) where {T<:Real} = T\n\n\n#### Statistics\n\nmean(d::TDist{T}) where {T<:Real} = d.\u03bd > 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    \u03bd = d.\u03bd\n    isinf(\u03bd) && return one(T)\n    \u03bd > 2 ? \u03bd / (\u03bd - 2) :\n    \u03bd > 1 ? T(Inf) : T(NaN)\nend\n\nskewness(d::TDist{T}) where {T<:Real} = d.\u03bd > 3 ? zero(T) : T(NaN)\n\nfunction kurtosis(d::TDist{T}) where T<:Real\n    \u03bd = d.\u03bd\n    \u03bd > 4 ? 6 / (\u03bd - 4) :\n    \u03bd > 2 ? T(Inf) : T(NaN)\nend\n\nfunction entropy(d::TDist{T}) where T <: Real\n    isinf(d.\u03bd) && return entropy( Normal(zero(T), one(T)) )\n    h = d.\u03bd/2\n    h1 = h + 1//2\n    h1 * (digamma(h1) - digamma(h)) + log(d.\u03bd)/2 + lbeta(h, 1//2)\nend\n\n\n#### Evaluation & Sampling\n\n@_delegate_statsfuns TDist tdist \u03bd\n\nrand(rng::AbstractRNG, d::TDist) = randn(rng) / ( isinf(d.\u03bd) ? 1 : sqrt(rand(rng, Chisq(d.\u03bd))/d.\u03bd) )\n\nfunction cf(d::TDist{T}, t::Real) where T <: Real\n    isinf(d.\u03bd) && return cf(Normal(zero(T), one(T)), t)\n    t == 0 && return complex(1)\n    h = d.\u03bd/2\n    q = d.\u03bd/4\n    complex(2(q*t^2)^q * besselk(h, sqrt(d.\u03bd) * abs(t)) / gamma(h))\nend\n\ngradlogpdf(d::TDist{T}, x::Real) where {T<:Real} = isinf(d.\u03bd) ? gradlogpdf(Normal(zero(T), one(T)), x) : -((d.\u03bd + 1) * x) / (x^2 + d.\u03bd)\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": "using DynamicHMCModels\n\nRandom.seed!(1)\n\ncd(@__DIR__)\ninclude(\"sdt_functions.jl\")\ninclude(\"simulateSDT.jl\")\n\nstruct SDTProblem\n    hits::Int64\n    fas::Int64\n    Nd::Int64\nend\n\nfunction (problem::SDTProblem)(\u03b8)\n    @unpack hits,fas,Nd=problem   # extract the data\n    @unpack d,c=\u03b8\n    logpdf(SDT(d,c),[hits,fas,Nd])+logpdf(Normal(0,1/sqrt(2)),d) +\n    logpdf(Normal(0,1/sqrt(2)),c)\nend\n\n# Define problem with data and inits.\n\ndata = simulateSDT(;Nd=100)\n\np = SDTProblem(data...)\np((d=2.0,c=.0))\n\n# Write a function to return properly dimensioned transformation.\nproblem_transformation(p::SDTProblem) =\n     as((d=as\u211d,c=as\u211d))\n     \n# Use Flux for the gradient.\nP = TransformedLogDensity(problem_transformation(p), p)\n\u2207P = ADgradient(:ForwardDiff, P);\n\n#import Zygote\n#\u2207P = ADgradient(:Zygote, P);\n\n# FSample from the posterior.\nchain, NUTS_tuned = NUTS_init_tune_mcmc(\u2207P, 4000);\n\n# Undo the transformation to obtain the posterior from the chain.\nposterior = TransformVariables.transform.(Ref(problem_transformation(p)),\n  get_position.(chain));\n\nchns = nptochain(posterior,NUTS_tuned)\n", "meta": {"hexsha": "2b98e274f91cce259d260dad9c729f23341360f2", "size": 1085, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/SDT/sdt.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": "benchmarks/SDT/sdt.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": "benchmarks/SDT/sdt.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": 22.6041666667, "max_line_length": 73, "alphanum_fraction": 0.7133640553, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7590433445538658}}
{"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 \u2208 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": "using Test, Astro\n\n# earth tests from meeus chapter 11\n\nprint(\"Geodesic distance\")\n# geodesic distance between Paris and Washington observatories \n# should be 6181.628423726299 km\n\nd = geodesic_distance(deg2rad(dms_to_d(-2, 20, 14)),deg2rad(dms_to_d(48, 50, 11)), deg2rad(dms_to_d(77,3,56)), deg2rad(dms_to_d(38,55,17)))\n@test isapprox(d, 6181.6, atol=.1)\nprintln(\" passed\")\n\nprint(\"Geocentric latitude\")\n# p sin phi and p cos phi \n \nr = geographical_to_geocentric_lat(deg2rad(dms_to_d(33, 21, 22)), 1706)\n# TODO earth-tests.jl Is this accurate enough?\n@test rad2deg(r[1]) \u2248  33.356111 atol= .2# <<<----------------------?\n@test isapprox(r[2], 0.546, atol=.1)\n@test isapprox(r[3], 0.83, atol=.1)\nprintln(\" passed\")\n", "meta": {"hexsha": "036024053130eb494856d9e433185645f354548c", "size": 715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/earth-tests.jl", "max_stars_repo_name": "cormullion/Astro.jl", "max_stars_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-05T19:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T21:37:33.000Z", "max_issues_repo_path": "test/earth-tests.jl", "max_issues_repo_name": "cormullion/Astro.jl", "max_issues_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-02-03T15:20:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-07T19:52:09.000Z", "max_forks_repo_path": "test/earth-tests.jl", "max_forks_repo_name": "cormullion/Astro.jl", "max_forks_repo_head_hexsha": "12115a4b984077dad7647d605d755d0f88cb9ffa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-10T17:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:09:32.000Z", "avg_line_length": 32.5, "max_line_length": 139, "alphanum_fraction": 0.6923076923, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7590308617579279}}
{"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\u00b2, Q\u00b2 = sparsePCE(mop, model; pMax = maxDeg, jMax = interactions)\n\nprintln(\"Basis polynomials: \", Ap)\nprintln(\"PCE coefficients: \", pce)\nprintln(\"Max degree:: \", p)\nprintln(\"R\u00b2 error: \", R\u00b2)\nprintln(\"Q\u00b2 error: \", Q\u00b2)", "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": "using ModelingToolkit, OrdinaryDiffEq, Test\n\n@parameters t \u03b1 \u03b2 \u03b3 \u03b4\n@variables x(t) y(t)\nD = Differential(t)\n\neqs = [D(x) ~ \u03b1*x - \u03b2*x*y,\n       D(y) ~ -\u03b4*y + \u03b3*x*y]\n\nsys = ODESystem(eqs)\n\nu0 = [x => 1.0,\n      y => 1.0]\n\np  = [\u03b1 => 1.5,\n      \u03b2 => 1.0,\n      \u03b4 => 3.0,\n      \u03b3 => 1.0]\n\ntspan = (0.0,10.0)\nprob = ODEProblem(sys,u0,tspan,p)\nsol = solve(prob,Tsit5())\n\nsys2 = liouville_transform(sys)\n@variables trJ\n\nu0 = [x => 1.0,\n      y => 1.0,\n      trJ => 1.0]\n\nprob = ODEProblem(sys2,u0,tspan,p,jac=true)\nsol = solve(prob,Tsit5())\n@test sol[end,end] \u2248 1.0742818931017244\n", "meta": {"hexsha": "98e75b688da57e7d3d09d26e0dfecad895680b00", "size": 574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basic_transformations.jl", "max_stars_repo_name": "paulrschrater/ModelingToolsJulia", "max_stars_repo_head_hexsha": "b1ef12e0d944ce6961fd2500af3652dab67540db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 824, "max_stars_repo_stars_event_min_datetime": "2020-03-29T20:49:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:46:24.000Z", "max_issues_repo_path": "test/basic_transformations.jl", "max_issues_repo_name": "paulrschrater/ModelingToolsJulia", "max_issues_repo_head_hexsha": "b1ef12e0d944ce6961fd2500af3652dab67540db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 920, "max_issues_repo_issues_event_min_datetime": "2020-03-31T18:11:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:21:28.000Z", "max_forks_repo_path": "test/basic_transformations.jl", "max_forks_repo_name": "paulrschrater/ModelingToolsJulia", "max_forks_repo_head_hexsha": "b1ef12e0d944ce6961fd2500af3652dab67540db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 130, "max_forks_repo_forks_event_min_datetime": "2020-04-05T23:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T14:53:11.000Z", "avg_line_length": 16.8823529412, "max_line_length": 43, "alphanum_fraction": 0.5505226481, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7590308573640758}}
{"text": "@testset \"Metropolis Hastings general\" begin\n\n    @testset \"1D\" begin\n        Random.seed!(123456)\n        prop(mu) = MvNormal(mu, 3)\n\n        target(x) = log(pdf(MvNormal([2], 1), x))\n\n\n        samps, acc = metropolis_hastings(target, prop, [2], 2000, 200)\n\n        @test mean(samps) \u2248 2 atol = 0.1\n        @test std(samps) \u2248 1 atol = 0.1\n    end\n\n    @testset \"3D\" begin\n        Random.seed!(123456)\n        prop(mu) = MvNormal(mu, [3 0 0; 0 3 0; 0 0 3])\n\n        target(x) = log(pdf(MvNormal([-2, 2, 0], [1 0.5 0.5; 0.5 1 0.5; 0.5 0.5 1]), x))\n\n        samps, acc = metropolis_hastings(target, prop, [-2, 2, 0], 2000, 200)\n\n        \u03bc = mean(samps, dims = 1)\n        \u03c3 = std(samps, dims = 1)\n        corrs = cor(samps)\n        @test vec(\u03bc) \u2248 [-2; 2; 0] atol = 0.2\n        @test vec(\u03c3) \u2248 [1; 1; 1] atol = 0.1\n        @test corrs \u2248 [1 0.5 0.5; 0.5 1 0.5; 0.5 0.5 1] atol = 0.2\n    end\n\n    @testset \"No logged target\" begin\n        Random.seed!(123456)\n        prop(mu) = MvNormal(mu, [3 0 0; 0 3 0; 0 0 3])\n\n        target(x) = pdf(MvNormal([-2, 2, 0], [1 0.5 0.5; 0.5 1 0.5; 0.5 0.5 1]), x)\n\n        samps, acc = metropolis_hastings(target, prop, [-2, 2, 0], 2000, 200, islogged = false)\n\n        \u03bc = mean(samps, dims = 1)\n        \u03c3 = std(samps, dims = 1)\n        corrs = cor(samps)\n        @test vec(\u03bc) \u2248 [-2; 2; 0] atol = 0.2\n        @test vec(\u03c3) \u2248 [1; 1; 1] atol = 0.1\n        @test corrs \u2248 [1 0.5 0.5; 0.5 1 0.5; 0.5 0.5 1] atol = 0.2\n    end\nend\n\n\n@testset \"Metropolis Hastings simple\" begin\n\n    @testset \"1D\" begin\n        Random.seed!(123456)\n        proprnd(mu) = rand(MvNormal(mu, 3))\n\n        target(x) = log(pdf(MvNormal([2], 1), x))\n\n        samps, acc = metropolis_hastings_simple(target, proprnd, [2], 2000, 200)\n\n        @test mean(samps) \u2248 2 atol = 0.1\n        @test std(samps) \u2248 1 atol = 0.1\n\n    end\n\n    @testset \"3D\" begin\n        Random.seed!(123456)\n        proprnd(mu) = rand(MvNormal(mu, [3 0 0; 0 3 0; 0 0 3]))\n\n        target(x) = log(pdf(MvNormal([-2, 2, 0], [1 0.5 0.5; 0.5 1 0.5; 0.5 0.5 1]), x))\n\n        samps, acc = metropolis_hastings_simple(target, proprnd, [-2,2, 0], 2000, 200)\n\n        \u03bc = mean(samps, dims = 1)\n        \u03c3 = std(samps, dims = 1)\n        corrs = cor(samps)\n        @test vec(\u03bc) \u2248 [-2; 2; 0] atol = 0.2\n        @test vec(\u03c3) \u2248 [1; 1; 1] atol = 0.1\n        @test corrs \u2248 [1 0.5 0.5; 0.5 1 0.5; 0.5 0.5 1] atol = 0.2\n\n    end\n    Random.seed!()\nend\n", "meta": {"hexsha": "2b8076604770c74129474d908c2a37b55ec40203", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mcmc.jl", "max_stars_repo_name": "AnderGray/TransitionalMCMC.jl", "max_stars_repo_head_hexsha": "547862f38a6ccb7880f780f497ab3f04dda34fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-04-08T16:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T21:33:37.000Z", "max_issues_repo_path": "test/mcmc.jl", "max_issues_repo_name": "cscherrer/TransitionalMCMC.jl", "max_issues_repo_head_hexsha": "f6f181cd78c7241badcdc61616d52d0b5a739fb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-04-08T17:08:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T10:59:10.000Z", "max_forks_repo_path": "test/mcmc.jl", "max_forks_repo_name": "cscherrer/TransitionalMCMC.jl", "max_forks_repo_head_hexsha": "f6f181cd78c7241badcdc61616d52d0b5a739fb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-08T19:20:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T20:08:56.000Z", "avg_line_length": 28.9156626506, "max_line_length": 95, "alphanum_fraction": 0.5058333333, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660923657094, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7590308555099627}}
{"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 <= \u03c1_AB <= -0.1\n#  0.4 <= \u03c1_BC <=  0.5\n# We can use the following property of the correlations:\n# [  1    \u03c1_AB  \u03c1_AC ]\n# [ \u03c1_AB   1    \u03c1_BC ]  \u227d 0\n# [ \u03c1_AC  \u03c1_BC   1   ]\n# To determine bounds on \u03c1_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": "using TensorIntegration\nusing Test\nusing LinearAlgebra\n\n@testset \"Expectation of uniform by simpson rule, 1D/2D/3D\" begin \n    # add test for basic integrals\n    N = 5\n    # uniform expectation \n    a = 1. \n    b = 3. \n    pdf(x, a, b) = 1.0 ./ (b-a)\n    grid, weights = TensorIntegration.simpson(a, b, N)\n\n    Exp = dot((grid.*pdf.(grid, a, b)),weights)\n    @test Exp \u2248 (a+b)/2.\n\n\n    # now in 2d\n    N2d = [5, 5]\n    a2d = [1., 1.]\n    b2d = [2., 2.]\n    pdf(x, a, b, d) = 1.0 ./ (b[d]-a[d])\n\n    grid, weights = TensorIntegration.tensor_simpson(a2d, b2d, N2d)\n    Exp1 = dot((grid[:,1].*pdf(grid, a2d, b2d, 1)), weights)\n    Exp2 = dot((grid[:,2].*pdf(grid, a2d, b2d, 2)), weights)\n\n    @test Exp1[1] \u2248 (a2d[1]+b2d[1])/2.\n    @test Exp2[1] \u2248 (a2d[2]+b2d[2])/2.\n\n\n    # now in 3d\n    N3d = [5, 5, 5]\n    a3d = [1., 1., 0.1]\n    b3d = [2., 2., 3.3]\n    pdf(x, a::Array, b::Array) = 1.0 ./ prod(b3d.-a3d)\n\n    grid, weights = TensorIntegration.tensor_simpson(a3d, b3d, N3d)\n    Exp1 = dot((grid[:,1].*pdf(grid, a3d, b3d)), weights)\n    Exp2 = dot((grid[:,2].*pdf(grid, a3d, b3d)), weights)\n    Exp3 = dot((grid[:,3].*pdf(grid, a3d, b3d)), weights)\n\n    @test isapprox(Exp1, (a3d[1]+b3d[1])/2.)\n    @test isapprox(Exp2, (a3d[2]+b3d[2])/2.)\n    @test isapprox(Exp3, (a3d[3]+b3d[3])/2.)\n\n    # now with one dimension only 1 point \n    N3d = [5, 5, 1]\n    a3d = [1., 1., 1.]\n    b3d = [2., 2., 2.]\n    pdf(x, a::Array, b::Array) = 1.0 ./prod(b3d.-a3d)\n\n    grid, weights = TensorIntegration.tensor_simpson(a3d, b3d, N3d)\n    Exp1 = dot((grid[:,1].*pdf(grid, a3d, b3d)), weights)\n    Exp2 = dot((grid[:,2].*pdf(grid, a3d, b3d)), weights)\n    Exp3 = dot((grid[:,3].*pdf(grid, a3d, b3d)), weights)\n\n    @test isapprox(Exp1, (a3d[1]+b3d[1])/2.)\n    @test isapprox(Exp2, (a3d[2]+b3d[2])/2.)\n    @test isapprox(Exp3, (a3d[3]+b3d[3])/2.)\nend", "meta": {"hexsha": "d1be127699238c0037cfdeff642651821a0055a3", "size": 1830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 30.0, "max_line_length": 67, "alphanum_fraction": 0.5448087432, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7589949824784072}}
{"text": "export binary_search\n\nfunction binary_search(array::Vector{T}, target::T) where T\n    left = 1\n    right = length(array)\n\n    while left <= right\n        mid = trunc(Int, left+(right-left)/2)\n        if array[mid] > target\n            right = mid-1\n        elseif array[mid] < target\n            left = mid+1\n        else\n            return mid\n        end\n    end\n\n    return -1\nend\n", "meta": {"hexsha": "9e29be5757ef041677b719e902fbbc650bd19a73", "size": 384, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/binary_search.jl", "max_stars_repo_name": "yuehhua/Algorithm101", "max_stars_repo_head_hexsha": "98591f7f9da98db1942e1b87b43caa555aba3f98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-05T01:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-21T22:22:46.000Z", "max_issues_repo_path": "src/binary_search.jl", "max_issues_repo_name": "yuehhua/Algorithm101", "max_issues_repo_head_hexsha": "98591f7f9da98db1942e1b87b43caa555aba3f98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-04T12:29:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-12T07:04:51.000Z", "max_forks_repo_path": "src/binary_search.jl", "max_forks_repo_name": "foldfelis/Algorithm101", "max_forks_repo_head_hexsha": "46b9038a6b479cad95fc09803e08ed7c837cc5a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-04T14:13:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T14:21:57.000Z", "avg_line_length": 19.2, "max_line_length": 59, "alphanum_fraction": 0.5390625, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7589224763973595}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 c930a0fa-4ef8-4963-b4b2-0d576ecdde7e\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c34bdc36-5013-4096-9cb2-581ad9e02239\nmd\" ## f-03-01.jl\"\n\n# \u2554\u2550\u2561 0b1514c5-eded-4f60-ac31-6f27a4deff1d\nbegin\n\t@variables f x\n\tf = exp(x) - x^4\n\tL(f)\nend\n\n# \u2554\u2550\u2561 7c4288f0-38d9-4c39-b6b1-789aba5465b6\nf_j = build_function(f, [x], expression=Val{false});\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1dd78a44-b910-4bb2-8af0-9a1ab3ee4a51\nRoots.newton(f_j, fp_j, 8)        # 8.6131694564414\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7e2f4bd6-4f9a-4a72-8e70-e5fc56f806ee\nhalley(f_j, fp_j, fpp_j, 8)\n\n# \u2554\u2550\u2561 3e022154-6933-4ba7-8cf9-2d48d3cbb27f\nsecant_method(f_j, [8, 8.5])\n\n# \u2554\u2550\u2561 26cd9127-ae9e-4f09-97e4-d10f514e2164\nmd\" ## End of f-03-01.jl\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500c34bdc36-5013-4096-9cb2-581ad9e02239\n# \u2560\u2550c930a0fa-4ef8-4963-b4b2-0d576ecdde7e\n# \u2560\u2550919b41e5-7e43-45e0-8676-373b77ac6208\n# \u2560\u25500b1514c5-eded-4f60-ac31-6f27a4deff1d\n# \u2560\u25507c4288f0-38d9-4c39-b6b1-789aba5465b6\n# \u2560\u2550c7c87623-9c41-4a68-8673-47a71c67f083\n# \u2560\u25502708dfb1-09dd-458c-8b5f-2e2ec3d800c4\n# \u2560\u25501dd78a44-b910-4bb2-8af0-9a1ab3ee4a51\n# \u2560\u25508054c3fd-3ecb-4c2a-b606-7fd518d750a3\n# \u2560\u25507e2f4bd6-4f9a-4a72-8e70-e5fc56f806ee\n# \u2560\u25503e022154-6933-4ba7-8cf9-2d48d3cbb27f\n# \u255f\u250026cd9127-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": "using NewtonsMethod, LinearAlgebra\nusing Test\n\nf(x)=-x^2; fp(x)=-2x\ng(x)=2(x-4)^3; gp(x) = 6(x-4)^2\nh(x)=x^3-2x^2-11x+12; hp(x)=3x^2-4x-11\nn(x)=x^2+42.0; np(x)=2x\nx\u2080=1.0; xb\u2080=one(BigFloat); x1=2.35287527; x2=2.35284172\ntol=1E-6 # use manual tolerance for known-function tests\n\nfor x in [x\u2080, xb\u2080]\n    @testset \"Fns with known roots\" begin\n        @test norm(newtonroot(f, fp, x)[1]) < tol\n        @test norm(newtonroot(g, gp, x)[1] - 4) < tol\n        #known basins of attraction for h\n        @test norm(newtonroot(h, hp, x1)[1] - 4) < tol\n        @test norm(newtonroot(h, hp, x2)[1] + 3) < tol\n        #nonconvergence\n        @test newtonroot(n, np, x)[1]==nothing\n    end\n\n    @testset \"Autodiff known fns\" begin\n        @test norm(newtonroot(f, x)[1]) < tol\n        @test norm(newtonroot(g, x)[1] - 4.0) < tol\n        @test norm(newtonroot(h, x1)[1] - 4.0) < tol\n        @test norm(newtonroot(h, x2)[1] + 3.0) < tol\n        @test newtonroot(n, x)[1]==nothing # redundant?\n        @test newtonroot(n, x)==newtonroot(n, np, x) # test of f\u2032=Diff(f)\n    end\nend\n\n@testset \"Maxiter, iter, tol\" begin\n    # expected nonconvergence behavior for complicated function and small maxiter\n    @test newtonroot(h, hp, x1, maxiter=5)[1]==nothing\n    @test newtonroot(h, x1, maxiter=5)[1]==nothing\n    # OK to set tol as exactly 0 when NM yields exact root\n    @test newtonroot(h, hp, x1, tol=0.0)[1] == 4.0\n    @test newtonroot(h, x1, tol=0.0)[1] == 4.0\n    # NM cannot get exact root, so tol=0 returns nothing when x has arbitrary precision\n    @test newtonroot(f, fp, one(BigFloat), tol=0.0)[1] == nothing\n    @test newtonroot(f, one(BigFloat), tol=0.0)[1] == nothing\n    # when tol is nonzero, tol' > tol yields less precise estimate\n    @test norm(newtonroot(f, fp, x\u2080, tol=1E-4)[1] - 0) > norm(newtonroot(f, fp, x\u2080, tol=1E-5)[1] - 0)\n    # tests for iter. nonideal logic, i think.\n    @test newtonroot(h, hp, x1, maxiter=0)[3]==1\n    @test newtonroot(h, hp, x1, tol=Inf)[3]==1\nend\n", "meta": {"hexsha": "eb2b6101ff60a4fe420ed91f47da47940ad4137f", "size": 1974, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "maxnorton/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "cbed0238734c6ce1bb13f2426e9720b67f297b12", "max_stars_repo_licenses": ["MIT"], "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": "maxnorton/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "cbed0238734c6ce1bb13f2426e9720b67f297b12", "max_issues_repo_licenses": ["MIT"], "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": "maxnorton/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "cbed0238734c6ce1bb13f2426e9720b67f297b12", "max_forks_repo_licenses": ["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.125, "max_line_length": 101, "alphanum_fraction": 0.6119554205, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7589224646812245}}
{"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": "# Test 0: Solve 1D Burgers Equation\n# u(x,t)_t+(0.5*u\u00b2(x,t))_{x}=0\n# u(0,x) = f0(x)\n\n@testset \"1D Scalar Algorithms\" begin\n\nusing ConservationLawsDiffEq\nusing LinearAlgebra\nusing OrdinaryDiffEq\n\ninclude(\"burgers.jl\")\nCL = ConservationLawsDiffEq\n\nCFL = 0.5\nTend = 1.0\nul = 1.0\nur = 0.0\nx0 = 0.0\n\nprob1 = RiemannProblem(Burgers(), ul, ur, x0, 0.0)\nsol_ana  = get_solution(prob1)\n\n# First define the problem data (Jacobian is optional but useful)\nJf(u) = u           #Jacobian\nf(u) = u^2/2        #Flux function\n\nf0(x) = (x < x0) ? ul : ur\n\n# Now discretizate the domain\nmesh = Uniform1DFVMesh(50, [-3.0, 3.0])\n\nfunction get_problem(alg::CL.AbstractFVAlgorithm, use_threads, mesh, Tend,CFL)\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,[Dirichlet(;side=:Both)]; Df = Jf, use_threads = use_threads,numvars = 1)\n\n  #Compute discrete initial data\n  u0 = getInitialState(mesh,f0,use_threads = true)\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\nfunction test_Scheme(alg, maxerror, threaded_mode=true)\n  println(\"Testing \",split(\"$alg\",\"(\")[1],\": \")\n  prob,cb,dt = get_problem(alg, false, mesh, Tend,CFL)\n  @time sol = solve(prob,SSPRK22(); dt = dt, callback = cb, save_everystep = false)\n  @test get_L1_error(sol_ana, fv_solution(sol,mesh)) < maxerror\n  if threaded_mode\n    println(\"in threaded mode: \")\n    prob,cb,dt = get_problem(alg, true, mesh, Tend,CFL)\n    @time sol1 = solve(prob,SSPRK22(); dt = dt, callback = cb, save_everystep = false)\n    @test get_L1_error(sol_ana, fv_solution(sol1,mesh)) \u2248 get_L1_error(sol_ana, fv_solution(sol,mesh))\n  end\nend\n\n# Test Schemes relative error\ntest_Scheme(FVSKTScheme(), 0.048)\ntest_Scheme(LaxFriedrichsScheme(), 0.24)\ntest_Scheme(LocalLaxFriedrichsScheme(), 0.17, false)\ntest_Scheme(GlobalLaxFriedrichsScheme(), 0.24)\ntest_Scheme(LaxWendroffScheme(), 0.043)\ntest_Scheme(LaxWendroff2sScheme(), 0.088)\ntest_Scheme(FVCompWENOScheme(), 0.045)\ntest_Scheme(FVCompMWENOScheme(), 0.041)\ntest_Scheme(FVSpecMWENOScheme(), 0.028, false)\ntest_Scheme(FVCUScheme(), 0.039)\ntest_Scheme(FVDRCUScheme(), 0.039)\ntest_Scheme(FVDRCU5Scheme(), 0.053)\n\n# Test dt and CFL callback\nprob,cb,dt = get_problem(FVSKTScheme(), false, mesh, Tend,CFL)\n@time sol = solve(prob,SSPRK22(); dt = dt, callback = cb, save_everystep = true)\n@test sol.t == [0.0,0.05999999999999994,0.11999999999999988,0.17999999999999983,0.23999999999999977,\n                0.2999999999999997,0.35999999999999965,0.4199999999999996,0.47999999999999954,\n                0.5399999999999995,0.5999999999999994,0.6599999999999994,0.7199999999999993,\n                0.7799999999999992,0.8399999999999992,0.8999999999999991,0.9599999999999991,1.0]\nend\n", "meta": {"hexsha": "61ed5cb3d240bfd3577d6f15c57a3b9cabe6d808", "size": 2944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test0.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": "test/test0.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": "test/test0.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": 34.6352941176, "max_line_length": 114, "alphanum_fraction": 0.7184103261, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7589127731587453}}
{"text": "module NewtonsMethod\n\nusing ForwardDiff, LinearAlgebra\n\nexport newtonroot\n\nfunction iterativesolver(f, x\u2080, checkconvergence, updatex)\n    xold = x\u2080.*10\n    fold = 10*f(x\u2080)\n    xnew = x\u2080\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\u2032; x\u2080, tol=1e-7, maxiter=1000)\n    res = iterativesolver(f,\n                          x\u2080,\n                          (xold, xnew, fold, fnew, iter) -> norm(xnew - xold) < 1e-4 || iter > maxiter,\n                          (f, x) -> x - f(x) / f\u2032(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\u2080, tol=1e-7, maxiter=1000)\n    return newtonroot(f, x -> ForwardDiff.derivative(f, x); x\u2080, 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. \u03b1: 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(\u03b1; w = ones(size(\u03b1)), d = 0, dims = 1)\n  # compute weighted sum of cos and sin of angles\n  r = sum(w .* cis.(\u03b1); 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. \u03b1: 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- \u03bc: mean direction\n\t- ul: upper 95% confidence limit\n\t- ll: lower 95% confidence limit\n\"\"\"\nfunction circ_mean(\u03b1; w = ones(size(\u03b1)), dims = 1)\n  # compute weighted sum of cos and sin of angles\n  r = sum(w .* cis.(\u03b1); dims)\n\n  # obtain mean by\n  \u03bc = angle.(r)\n  \u03bc = length(\u03bc) == 1 ? \u03bc[1] : \u03bc\n\n  # confidence limits\n  t = circ_confmean(\u03b1; xi = 0.05, w, d = 0, dims)\n  ul = \u03bc .+ t\n  ll = \u03bc .- t\n\n  return (; \u03bc, ul, ll)\nend\n\n\"\"\"\nTransforms p-axial data to a common scale.\n\n  1. \u03b1: sample of angles in radians\n  2. p: number of modes(default=1)\n\n  return: transformed data\n\"\"\"\ncirc_axial(\u03b1, p = 1) = mod2pi.(\u03b1 * p)\n\n\"\"\"\nComputes the median direction for circular data.\n\n  1. \u03b1: sample of angles in radians\n\n  return: median direction\n\"\"\"\nfunction circ_median(\u03b1::AbstractVector)\n  \u03b1 = mod2pi.(\u03b1)\n  n = length(\u03b1)\n\n  dd = circ_dist2(\u03b1)\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(\u03b1[dm.==m]).\u03bc\n  \u03b1\u03bc = circ_mean(\u03b1).\u03bc\n  if abs(circ_dist(\u03b1\u03bc, md)) > abs(circ_dist(\u03b1\u03bc, md + \u03c0))\n    md = mod2pi(md + \u03c0)\n  end\n  return md\nend\n\n\"\"\"\nComputes circular standard deviation for circular data (equ. 26.20, Zar).\n\n\t1. \u03b1: 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(\u03b1; w = ones(size(\u03b1)), d = 0, dims = 1)\n  # compute mean resultant vector length\n  r = circ_r(\u03b1; 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. \u03b1: 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(\u03b1; w = ones(size(\u03b1)), d = 0, dims = 1)\n  # compute mean resultant vector length\n  r = circ_r(\u03b1; 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. \u03b1: 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 \u00b1 d yields upper/lower (1-xi)% confidence limit\n\"\"\"\nfunction circ_confmean(\u03b1; xi = 0.05, w = ones(size(\u03b1)), d = 0, dims = 1)\n  # compute ingredients for conf. lim.\n  r = circ_r(\u03b1; 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. \u03b1: 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(\u03b1; w = ones(size(\u03b1)), dims = 1)\n  # compute neccessary values\n  R = circ_r(\u03b1; w, d = 0, dims)\n  \u03b8 = circ_mean(\u03b1; w, dims).\u03bc\n  _, \u03c1\u2082, \u03bc\u2082 = circ_moment(\u03b1; w, p = 2, cent = false, dims)\n\n  # compute skewness\n  if ndims(\u03b8) > 0\n    \u03b8\u2082 = repeat(\u03b8, outer = Int.(size(\u03b1) ./ size(\u03b8)))\n  else\n    \u03b8\u2082 = \u03b8\n  end\n  b = sum(w .* sin.(2 * circ_dist(\u03b1, \u03b8\u2082)); dims) ./ sum(w; dims)\n  b0 = \u03c1\u2082 .* sin.(circ_dist(\u03bc\u2082, 2\u03b8)) ./ (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. \u03b1: 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(\u03b1; w = ones(size(\u03b1)), dims = 1)\n  # compute mean direction\n  R = circ_r(\u03b1; w, d = 0, dims)\n  \u03b8 = circ_mean(\u03b1; w, dims).\u03bc\n  _, \u03c1\u2082, _ = circ_moment(\u03b1; w, p = 2, cent = true, dims)\n  _, _, \u03bc\u2082 = circ_moment(\u03b1; w, p = 2, cent = false, dims)\n\n  # compute skewness\n  if ndims(\u03b8) > 0\n    \u03b8\u2082 = repeat(\u03b8, outer = Int.(size(\u03b1) ./ size(\u03b8)))\n  else\n    \u03b8\u2082 = \u03b8\n  end\n  k = sum(w .* cos.(2 * circ_dist(\u03b1, \u03b8\u2082)); dims) ./ sum(w; dims)\n  k0 = (\u03c1\u2082 .* cos.(circ_dist(\u03bc\u2082, 2\u03b8)) .- 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. \u03b1: 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  - \u03c1p: magnitude of the p-th moment\n  - \u03bcp: angle of th p-th moment\n\"\"\"\nfunction circ_moment(\u03b1; w = ones(size(\u03b1)), p = 1, cent = false, dims = 1)\n  if cent\n    \u03b8 = circ_mean(\u03b1; w, dims).\u03bc\n    if ndims(\u03b8) > 0\n      v = Int.(size(\u03b1) ./ size(\u03b8))\n      \u03b8 = repeat(\u03b8, outer = v)\n    end\n    \u03b1 = circ_dist(\u03b1, \u03b8)\n  end\n\n  n = size(\u03b1, dims)\n  c\u0304 = sum(cos.(p * \u03b1) .* w; dims) / n\n  s\u0304 = sum(sin.(p * \u03b1) .* w; dims) / n\n  mp = c\u0304 .+ im * s\u0304\n  \u03c1p = abs.(mp)\n  \u03bcp = angle.(mp)\n  mp = length(mp) == 1 ? mp[1] : mp\n  \u03c1p = length(\u03c1p) == 1 ? \u03c1p[1] : \u03c1p\n  \u03bcp = length(\u03bcp) == 1 ? \u03bcp[1] : \u03bcp\n  return (; mp, \u03c1p, \u03bcp)\nend\n\n\n\n\"\"\"\nPairwise difference \u03b1-\u03b2 around the circle computed efficiently.\n\n  1. \u03b1: sample of linear random variable\n  2. \u03b2: sample of linear random variable or one single angle\n\n  return: matrix with differences\n\"\"\"\ncirc_dist(\u03b1, \u03b2) = angle.(cis.(\u03b1) ./ cis.(\u03b2))\n\n\n\"\"\"\nAll pairwise difference \u03b1-\u03b2 around the circle computed efficiently.\n\n  1. \u03b1: sample of linear random variable\n  2. \u03b2: sample of linear random variable\n\n  return: matrix with pairwise differences\n\"\"\"\ncirc_dist2(\u03b1) = circ_dist2(\u03b1, \u03b1)\ncirc_dist2(\u03b1, \u03b2) = angle.(cis.(\u03b1) ./ cis.(\u03b2'))\n\n\n\"\"\"\nComputes descriptive statistics for circular data.\n\n  1. \u03b1: 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(\u03b1::AbstractVector; w = ones(size(\u03b1)), d = 0)\n  # mean\n  mean = circ_mean(\u03b1; w).\u03bc\n  # median\n  median = circ_median(\u03b1)\n  # variance\n  var = circ_var(\u03b1; w, d)\n  # standard deviation\n  std, std0 = circ_std(\u03b1; w, d)\n  # skewness\n  skewness, skewness0 = circ_skewness(\u03b1; w)\n  # kurtosis\n  kurtosis, kurtosis0 = circ_kurtosis(\u03b1; 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. \u03b1: 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(\u03b1; w = ones(size(\u03b1)), d = 0)\n  r = circ_r(\u03b1; 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. \u03b1: 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(\u03b1; sz = deg2rad(1), w = ones(size(\u03b1)))\n  \u03b1 = mod2pi.(\u03b1)\n  n = sum(w)\n  dg = 0:sz:\u03c0\n\n  m1 = zeros(size(dg))\n  m2 = zeros(size(dg))\n  for i = 1:length(dg)\n    m1[i] = sum((\u03b1 .> dg[i]) .& (\u03b1 .< \u03c0 + 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 = \u03c0 * sqrt(n) / 2 / (n - 2m)\n    p = sqrt(2\u03c0) / A * exp(-\u03c0^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 \u03b1 level at which the test would still be significant.\n  If the test is not significant at the \u03b1=0.1 level, we return the critical value for \u03b1 = 0.05 and p = 0.5.\n\n  1. \u03b1: 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(\u03b1)\n  # for the purpose of the test, convert to angles\n  \u03b1 = sort(rad2deg.(\u03b1))\n  n = length(\u03b1)\n\n  # compute test statistic\n  u = 0\n  \u03bb = 360 / n\n  for j = 1:n-1\n    ti = \u03b1[j+1] - \u03b1[j]\n    u += abs(ti - \u03bb)\n  end\n\n  tn = 360 - \u03b1[n] + \u03b1[1]\n  u = 0.5(u + abs(tn - \u03bb))\n\n  getVal = (N, u) -> begin\n      # Table II from Russel and Levitin, 1995\n      \u03b1 = [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 = \u03b1[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. \u03b1: 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(\u03b1; m = 0, w = ones(size(\u03b1)), d = 0)\n  # compute some ingredients\n  r = circ_r(\u03b1; w, d)\n  \u03bc, = circ_mean(\u03b1; 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(\u03bc - 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. \u03b1: sample of angles in radians\n  - md: median to test, default=0\n\n  return: p-value\n\"\"\"\nfunction circ_medtest(\u03b1; md = 0)\n  n = length(\u03b1)\n\n  # compute deviations from median\n  d = circ_dist(\u03b1, 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. \u03b1: 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  - \u03bc: mean\n  - ul: upper (1-xi) confidence level\n  - ll: lower (1-xi) confidence level\n\"\"\"\nfunction circ_mtest(\u03b1; xi = 0.05, m = 0, w = ones(size(\u03b1)), d = 0)\n  # compute ingredients\n  \u03bc, = circ_mean(\u03b1; w)\n  t = circ_confmean(\u03b1; xi, w, d)\n  ul = \u03bc + t\n  ll = \u03bc - t\n\n  # compute test via confidence limits (example 27.3)\n  h = abs(circ_dist2(m, \u03bc)) > t\n\n  return (; h, \u03bc, 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, \u03b1 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. \u03b1: angles in radians\n  2. idx: indicates which population the respective angle in \u03b1 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(\u03b1, idx; w = ones(size(\u03b1)))\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(\u03b1[pidx]; w = w[pidx])\n  end\n\n  r = circ_r(\u03b1; 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  \u03b2 = 1 + 3 / (8 * kk)    # correction factor\n  A = sum(pr .* pn) - r * n\n  B = n - sum(pr .* pn)\n\n  F = \u03b2 * (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. \u03b1: 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(\u03b1, 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(\u03b1)\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(\u03b1[idx]) # R of cell\n    end\n    # R and mean angle for factor 1\n    pr[pp] = sum(p_id) * circ_r(\u03b1[p_id])\n    pm[pp] = circ_mean(\u03b1[p_id]).\u03bc\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(\u03b1[q_id])\n    qm[qq] = circ_mean(\u03b1[q_id]).\u03bc\n    qn[qq] = sum(q_id)\n  end\n\n  # R and mean angle for whole sample (total)\n  tr = n * circ_r(\u03b1)\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      \u03b2 = 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      \u03b2 = 1\n    end\n\n    # compute all test statistics as F = \u03b2 * MS(A) / MS(R)\n    F1 = \u03b2 * ms_1 / ms_r\n    p1 = 1 - cdf(FDist(df_1, df_r), F1)\n\n    F2 = \u03b2 * 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. \u03b1\u2081: sample of angles in radians\n  2. \u03b1\u2082: 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(\u03b1\u2081, \u03b1\u2082)\n  n1 = length(\u03b1\u2081)\n  n2 = length(\u03b1\u2082)\n\n  R1 = n1 * circ_r(\u03b1\u2081)\n  R2 = n2 * circ_r(\u03b1\u2082)\n\n  # make sure that r\u0304 > .7\n  r\u0304 = (R1 + R2) / (n1 + n2)\n\n  if r\u0304 < 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. \u03b1: sample of angles in radians\n\n  return: p-value\n\"\"\"\nfunction circ_symtest(\u03b1)\n  # compute median\n  md = circ_median(\u03b1)\n\n  # compute deviations from median\n  d = circ_dist(\u03b1, 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. \u03b1\u2081: sample of angles in radians\n  2. \u03b1\u2082: 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(\u03b1\u2081, \u03b1\u2082; n = 100)\n  n = length(\u03b1\u2081)\n  m = length(\u03b1\u2082)\n\n  # create cdfs of both samples\n  \u03d5\u2081, cdf1 = circ_samplecdf(\u03b1\u2081; n)\n  _, cdf2 = circ_samplecdf(\u03b1\u2082; 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  \u03b1 = [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 = \u03b1[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. \u03b1\u2081: sample of angles in radians\n  2. \u03b1\u2082: sample of angles in radians\n\n  return:\n  - \u03c1: correlation coefficient\n  - p: p-value\n\"\"\"\nfunction circ_corrcc(\u03b1\u2081, \u03b1\u2082)\n  # compute mean directions\n  n = length(\u03b1\u2081)\n  \u03b1\u0304\u2081 = circ_mean(\u03b1\u2081).\u03bc\n  \u03b1\u0304\u2082 = circ_mean(\u03b1\u2082).\u03bc\n\n  # compute correlation coeffcient from p. 176\n  num = sum(sin.(\u03b1\u2081 .- \u03b1\u0304\u2081) .* sin.(\u03b1\u2082 .- \u03b1\u0304\u2082))\n  den = sqrt(sum(sin.(\u03b1\u2081 .- \u03b1\u0304\u2081) .^ 2) .* sum(sin.(\u03b1\u2082 .- \u03b1\u0304\u2082) .^ 2))\n  \u03c1 = num / den\n\n  # compute pvalue\n  l20 = mean(sin.(\u03b1\u2081 .- \u03b1\u0304\u2081) .^ 2)\n  l02 = mean(sin.(\u03b1\u2082 .- \u03b1\u0304\u2082) .^ 2)\n  l22 = mean((sin.(\u03b1\u2081 .- \u03b1\u0304\u2081) .^ 2) .* (sin.(\u03b1\u2082 .- \u03b1\u0304\u2082) .^ 2))\n\n  ts = sqrt((n * l20 * l02) / l22) * \u03c1\n  p = 2 * (1 - cdf(Normal(), abs(ts)))\n  return (; \u03c1, p)\nend\n\n\n\"\"\"\nCorrelation coefficient between one circular and one linear random variable.\n\n  1. \u03b1: sample of angles in radians\n  2. x: sample of linear random variable\n\n  return:\n  - \u03c1: correlation coefficient\n  - p: p-value\n\"\"\"\nfunction circ_corrcl(\u03b1, x)\n  n = length(\u03b1)\n\n  # compute correlation coefficent for sin and cos independently\n  rxs = cor(x, sin.(\u03b1))\n  rxc = cor(x, cos.(\u03b1))\n  rcs = cor(sin.(\u03b1), cos.(\u03b1))\n\n  # compute angular-linear correlation (equ. 27.47)\n  \u03c1 = sqrt((rxc^2 + rxs^2 - 2 * rxc * rxs * rcs) / (1 - rcs^2))\n\n  # compute pvalue\n  p = 1 - cdf(Chisq(2), n * \u03c1^2)\n  return (; \u03c1, 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. \u03b1: angles in radians OR \u03b1 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(\u03b1; w = ones(size(\u03b1)))\n  N = length(\u03b1)\n\n  if N > 1\n    R = circ_r(\u03b1; w)\n  else\n    R = \u03b1\n  end\n\n  if R < 0.53\n    \u03ba = 2R + R^3 + 5R^5 / 6\n  elseif R >= 0.53 && R < 0.85\n    \u03ba = -0.4 + 1.39R + 0.43 / (1 - R)\n  else\n    \u03ba = 1 / (R^3 - 4R^2 + 3R)\n  end\n\n  if N < 15 && N > 1\n    if \u03ba < 2\n      \u03ba = max(\u03ba - 2 * (N * \u03ba)^-1, 0)\n    else\n      \u03ba = (N - 1)^3 * \u03ba / (N^3 + N)\n    end\n  end\n  \u03ba\nend\n\n\"\"\"\nPerforms a simple agglomerative clustering of angular data.\n\n1. \u03b1: sample of angles in radians\n  - k: number of clusters desired, default=2\n\nreturn:\n- cid: cluster id for each entry of \u03b1\n- \u03b1: sorted angles, matched with cid\n- \u03bc: mean direction of angles in each cluster\n\"\"\"\nfunction circ_clust(\u03b1; k = 2)\n\n  n = length(\u03b1)\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    \u03bc = fill(NaN, n)\n    for j = 1:n\n      if sum(cid .== j) > 0\n        \u03bc[j], = circ_mean(\u03b1(cid .== j))\n      end\n    end\n\n    # find distance between centroids...\n    \u03bcdist = abs.(circ_dist2(\u03bc))\n\n    # find closest pair of clusters/datapoints\n    mindist = minimum(\u03bcdist[tril(ones(size(\u03bcdist), size(\u03bcdist)), -1)==1])\n    row, col = findall(\u03bcdist .== 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  \u03bc = fill(NaN, num_unique)\n  for j = 1:num_unique\n    if sum(cid .== j) > 0\n      \u03bc[j], = circ_mean(\u03b1[cid.==j]')\n    end\n  end\n\n  return (; cid, \u03b1, \u03bc)\nend\n\n\"\"\"\nHelper function for circ_kuipertest. Evaluates CDF of sample.\n\n  1. \u03b1: sample of angles in radians\n    - n: resolution at which the cdf are evaluated\n\n  return:\n  - \u03d5: angles at which CDF are evaluated\n  - c: CDF values at \u03d5\n\"\"\"\nfunction circ_samplecdf(\u03b1; n = 100)\n  \u03d5 = range(0, 2\u03c0, length = n + 1)\n\n  # ensure all points in \u03b1 are on interval [0, 2pi)\n  \u03b1 = sort(mod2pi.(\u03b1))\n\n  dp = 1 / length(\u03b1) # incremental change in probability\n  c = cumsum(map((l, r) -> dp * sum(l .<= \u03b1 .< r), \u03d5[1:end-1], \u03d5[2:end]))\n  \u03d5 = \u03d5[1:end-1]\n\n  return (; \u03d5, 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 \u22c5 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 \u22c5 (illness \u2297 id(I)) \u22c5 \u2207(I)\n\nseir = sei \u22c5 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 \u22c5 \u0394(I) \u22c5 (death \u2297 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 \u03bc=0.0 and \u03c3 = r/3.\n(a value of \u03c3 = 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": "@testset \"$(rpad(\"Lobatto-Legendre\",80))\" begin\n\n    @test_throws ErrorException LobattoLegendreQuadrature(1)\n\n    for s in 2:10\n        @test LobattoLegendreQuadrature(s) \u2248  LobattoLegendreQuadrature(s; fast=true)\n        @test LobattoLegendreQuadrature(s) == LobattoLegendreQuadrature(Float64, s)\n\n        @test sum(weights(LobattoLegendreQuadrature(s))) \u2248 1\n    end\n\nend\n", "meta": {"hexsha": "9b8a53916b803a9a7a0412e5b24bfb2d3d40e235", "size": 374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 28.7692307692, "max_line_length": 85, "alphanum_fraction": 0.7139037433, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7589127604338767}}
{"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#\u00a0Arguments \n- `S::Array{Float64, 2}`: A covariance matrix.\n\n#\u00a0Reference\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#\u00a0Arguments\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#\u00a0Reference\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 \u2209 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 \u2208 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 \u2209 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) \u2286 Set(available)\nend\n\n\n\n# ---------- Math -----------\n\nx = 0:0.1:2\u03c0\n\ncos.(x) == 0.5*(\u212f.^(im*x) + \u212f.^(-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 = \u212f.^(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., \u03a3 = {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) \u2264 4d\n\telseif isodd(d)\n\t\treturn T(4d + 4)\n\t\t# return A_2(2d + 1, d) \u2264 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\u00d77 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(\u212f, ((n * log(\u212f, 1)) / (log(\u212f, 2))) + 1) / log(\u212f, 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 \u2260 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\u2080, U\u2080\u2032 = zeros(2), zeros(2)\nprob = InitialValueProblem(example_9_1_Bathe, (U\u2080, U\u2080\u2032))\n\n# ## Analytic solution\nA = [1/\u221a3  (1/2)*\u221a(2/3);\n     1/\u221a3      -\u221a(2/3)]\nx\u2081(t) = (5 / \u221a3) * (1 - cos(t*\u221a2))\nx\u2082(t) = (2 * \u221a(2/3)) * (-1 + cos(t*\u221a5))\nU(t) = A * [x\u2081(t), x\u2082(t)]\n\n# ## Central difference\n\nsol = solve(prob, CentralDifference(\u0394t=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(\u0394t=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(\u0394t=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(\u0394t=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, \u03bc, \u03c3)\n\nget the pdf of `Normal(\u03bc, \u03c3)` at point `x`.\n\"\"\"\n@i function i_normal_logpdf(out, x::T, \u03bc, \u03c3) where T\n    @zeros T anc1 anc2 anc3\n\n    @routine begin\n        anc1 += x\n        anc1 -= \u03bc\n        anc2 += anc1 / \u03c3  # (x- \u03bc)/\u03c3\n        anc3 += anc2^2 # (x-\u03bc)^2/\u03c3^2\n    end\n\n    out -= anc3 * 0.5 # -(x-\u03bc)^2/2\u03c3^2\n    out -= log(\u03c3) # -(x-\u03bc)^2/2\u03c3^2 - log(\u03c3)\n    out -= log(2\u03c0)/2 # -(x-\u03bc)^2/2\u03c3^2 - log(\u03c3) - log(2\u03c0)/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": "export spgdemo_ex, spgdemo_im\nusing JOLI\n\nfunction spgdemo_ex()\n\n    # Create random m-by-n encoding matric and sparse vector\n    m = 50; n = 128; k = 14\n    A,Rtmp = qr(randn(n,m))\n    A = A'\n    p = randperm(n)\n    p = p[1:k]\n    x0 = zeros(n,1)\n    x0[p] = randn(k,1);\n\n    b = A*x0\n    mytau=convert(Float64,pi)\n\n    # Optionally set the verbosity to level 1\n    opts = spgOptions(verbosity = 1)\n\n    x, r, g, info = spgl1(A, vec(b); tau = mytau, options = opts)\n\n    # Calc the SNR of the recovery\n    SNR = -20*log10(norm(x0-x)/norm(x0));\n\n    return x, r, g, info, SNR\n\nend\n\nfunction spgdemo_im()\n\n    # Create random m-by-n encoding matric and sparse vector\n    m = 50; n = 128; k = 14\n    A,Rtmp = qr(randn(n,m))\n    A = A'\n    p = randperm(n)\n    p = p[1:k]\n    x0 = zeros(n,1)\n    x0[p] = randn(k,1);\n\n    b = A*x0\n    mytau=convert(Float64,pi)\n\n    # LASSO\n    sigma = []\n    x0=[]\n\n    # Optionally set the verbosity to level 1\n    opts = spgOptions(verbosity = 1)\n\n    A_im = joMatrix(A; name=\"A\")\n    x, r, g, info = spgl1(A_im, vec(b); tau = mytau, options = opts)\n\n    # Calc the SNR of the recovery\n    SNR = -20*log10(norm(x0-x)/norm(x0));\n\n    return x, r, g, info, SNR\nend\n", "meta": {"hexsha": "3b08a9ec0803a22fc166527e8f85f100f82bdd61", "size": 1194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Examples/pres/spgdemo.jl", "max_stars_repo_name": "yzhang3198/GenSPGL.jl", "max_stars_repo_head_hexsha": "565e53b8bda4425eb9270536059e1cc194a5bee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-06-10T00:52:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T11:39:38.000Z", "max_issues_repo_path": "src/Examples/pres/spgdemo.jl", "max_issues_repo_name": "yzhang3198/GenSPGL.jl", "max_issues_repo_head_hexsha": "565e53b8bda4425eb9270536059e1cc194a5bee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-10-06T02:13:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-15T02:27:39.000Z", "max_forks_repo_path": "src/Examples/pres/spgdemo.jl", "max_forks_repo_name": "yzhang3198/GenSPGL.jl", "max_forks_repo_head_hexsha": "565e53b8bda4425eb9270536059e1cc194a5bee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-10-05T18:50:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T21:49:56.000Z", "avg_line_length": 20.2372881356, "max_line_length": 68, "alphanum_fraction": 0.567839196, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7588392439728003}}
{"text": "@testset \"basic building blocks\" begin\n    mt = UltimateMortality([0.5,0.5])\n\n    # whole life insurance\n    ins = Insurance(\n            SingleLife(mort = mt,issue_age = 0),\n            Yields.Constant(0.05)\n    ) \n\n    @test all(survival(SingleLife(mort = mt,issue_age = 0)) .== [1.0, 0.5,0.25])\n\n    @test timepoints(ins) == [1.0,2.0]\n    @test survival(ins) == [1.0,0.5]\n    @test discount(ins) == [1.0 / 1.05, 1 / 1.05^2]\n    @test benefit(ins) == [1.0,1.0]\n    @test probability(ins) == [0.5,0.25]\n    @test cashflows(ins) == [0.5,0.25]\n    @test cashflows(ins) == benefit(ins) .* probability(ins)\n    @test present_value(ins)  \u2248 0.5 / 1.05 + 0.5 * 0.5 / 1.05 ^ 2\n    @test present_value(ins) \u2248 LifeContingencies.A(ins.life,ins.int)\n\n    # basic life contingency tests\n    @test survival(LifeContingency(ins),0,1) \u2248 0.5\n    @test survival(LifeContingency(ins),0,2) \u2248 0.25\n    @test discount(LifeContingency(ins),0,1) \u2248 1/1.05\n    @test discount(LifeContingency(ins),0,2) \u2248 1/1.05^2\n\n    # term life insurance\n    ins = Insurance(\n            SingleLife(mort = mt,issue_age = 0),\n            Yields.Constant(0.05),\n            n=1\n    ) \n\n    @test survival(ins) == [1.0]\n    @test discount(ins) == [1.0 / 1.05]\n    @test benefit(ins) == [1.0]\n    @test probability(ins) == [0.5]\n    @test cashflows(ins) == [0.5]\n    @test cashflows(ins) == benefit(ins) .* probability(ins)\n    @test timepoints(ins) == [1.0]\n    @test present_value(ins)  \u2248 0.5 / 1.05\n    \n    # annuity due\n    ins = AnnuityDue(\n            SingleLife(mort = mt,issue_age = 0),\n            Yields.Constant(0.05)\n    ) \n\n    @test survival(ins) == [1.0,0.5,.25]\n    @test discount(ins) == [1.0, 1 / 1.05^1, 1 / 1.05^2]\n    @test benefit(ins) == [1.0,1.0,1.0]\n    @test timepoints(ins) == [0.0,1.0,2.0]  \n    @test probability(ins) == [1.,0.5,0.25]\n    @test cashflows(ins) == [1.0,0.5,0.25]\n    @test cashflows(ins) == benefit(ins) .* probability(ins)\n    @test present_value(ins)  \u2248 1 + 1 * .5 / 1.05 +  1 * .25 / 1.05 ^2\n\n    ins = AnnuityDue(\n        SingleLife(mort = mt,issue_age = 0),\n        Yields.Constant(0.05),\n        n = 2\n) \n    @test present_value(ins)  \u2248 1 + 1 * .5 / 1.05\n\n    ins = AnnuityImmediate(\n        SingleLife(mort = mt,issue_age = 0),\n        Yields.Constant(0.05),\n        n = 1\n    ) \n\n    @test present_value(ins)  \u2248 1 * .5 * 1 / 1.05\n\n    ins = AnnuityDue(\n        SingleLife(mort = mt,issue_age = 0),\n        Yields.Constant(0.05),\n        n = 1,\n        start_time=1\n    ) \n\n    @test timepoints(ins)  == [1.0]\n    @test probability(ins)  == [0.5]\n    @test present_value(ins)  \u2248 1 * .5 * 1 / 1.05\n\nend\n\n@testset \"one  year\" begin\n    ins = LifeContingency(\n        SingleLife(\n            mort = UltimateMortality([0.5]),\n            issue_age = 0\n        ),\n        Yields.Constant(0.05)\n    )\n\n    @test survival(ins,1) \u2248 0.5\n    @test survival(ins,0) \u2248 1.0\n    @test survival(ins.life,0,0.5) \u2248 1 - 0.5 * 0.5\n    @test survival(ins,0.5) \u2248 1 - 0.5 * 0.5\n\n    @test omega(ins) \u2248 1\n    @test present_value(AnnuityDue(ins)) \u2248 1 + 1 * .5 / 1.05\n    @test present_value(AnnuityDue(ins,n=1)) \u2248 1\n    @test present_value(AnnuityDue(ins,n=0)) == 0\n    @test present_value(AnnuityImmediate(ins,n=1)) \u2248 1 * .5 / 1.05\n    @test present_value(AnnuityImmediate(ins,n=0)) == 0\n\n    @test present_value(Insurance(ins)) \u2248 0.5 / 1.05\n    @test present_value(Insurance(ins,n=1)) \u2248 0.5 / 1.05\n    @test present_value(Insurance(ins,n=0)) \u2248 0\n\n\n    ins_jl = LifeContingency(\n        JointLife((ins.life,ins.life),LastSurvivor(),Frasier()),\n        Yields.Constant(0.05)\n    )\n\n    @test omega(ins_jl) \u2248 1\n    @test present_value(AnnuityDue(ins_jl)) \u2248 1 + 1 * .75 / 1.05\n    @test present_value(AnnuityDue(ins_jl,n=1)) \u2248 1\n    @test present_value(AnnuityImmediate(ins_jl,n=1)) \u2248 1 * .75 / 1.05\n    @test present_value(AnnuityDue(ins_jl,n=2)) \u2248 1 + 1 * .75 / 1.05\n    @test present_value(AnnuityDue(ins_jl,n=2;certain=2)) \u2248 1 + 1 / 1.05 \n    @test present_value(AnnuityDue(ins_jl,n=0)) == 0\n\n    @test survival(ins_jl,1) \u2248 .5 + .5 - .5 * .5\n    @test all(survival(JointLife((ins.life,ins.life),LastSurvivor(),Frasier())) .== [1.,.75])\n    @test present_value(Insurance(ins_jl)) \u2248 .25 / 1.05\n    @test present_value(Insurance(ins_jl,n=1)) \u2248 0.25 / 1.05\n    @test present_value(Insurance(ins_jl,n=0)) \u2248 0\nend\n\n@testset \"two year no discount\" begin\n    ins = LifeContingency(\n        SingleLife(\n            mort = UltimateMortality([0.0,0.0]),\n            issue_age = 0\n        ),\n        Yields.Constant(0.00)\n    )\n\n    @test omega(ins) \u2248 2\n    @test present_value(AnnuityDue(ins)) \u2248 3\n    @test present_value(AnnuityDue(ins;start_time=1)) \u2248 2\n    @test present_value(AnnuityDue(ins,n=1)) \u2248 1 \n    @test present_value(AnnuityDue(ins,n=2)) \u2248 2\n    @test_throws BoundsError present_value(AnnuityDue(ins,n=2;start_time=2))\n    @test present_value(AnnuityDue(ins,n=3)) \u2248 3\n    @test present_value(AnnuityDue(ins,n=0)) == 0\n    @test present_value(AnnuityImmediate(ins,n=0)) == 0\n    @test present_value(AnnuityImmediate(ins,n=1)) \u2248 1\n    @test present_value(AnnuityImmediate(ins,n=1;start_time=1)) \u2248 1\n    @test_throws BoundsError  present_value(AnnuityImmediate(ins;start_time=2))\n    @test present_value(AnnuityImmediate(ins,n=2)) \u2248 2\n    @test present_value(AnnuityImmediate(ins)) \u2248 2\n    @test present_value(AnnuityImmediate(ins;certain=0)) \u2248 2\n    @test present_value(AnnuityImmediate(ins;certain=2)) \u2248 2\n\n    @test present_value(Insurance(ins)) \u2248 0\n    @test present_value(Insurance(ins,n=1)) \u2248 0\n    @test present_value(Insurance(ins,n=0)) \u2248 0\n\n    ins_jl = LifeContingency(\n        JointLife(\n            lives = (ins.life,ins.life),\n            contingency = LastSurvivor(),\n            joint_assumption = Frasier()),\n        Yields.Constant(0.00)\n    )\n\n    @test survival(ins_jl,0) \u2248 1.0\n    @test survival(ins_jl,1) \u2248 1\n    @test survival(ins_jl,2) \u2248 1\n\nend\n\n@testset \"two year with interest\" begin\n    ins = LifeContingency(\n        SingleLife(\n            mort = UltimateMortality([0.5,0.5]),\n            issue_age = 0\n        ),\n        Yields.Constant(0.05)\n    )\n\n    @test omega(ins) \u2248 2\n    @test present_value(AnnuityDue(ins)) \u2248 1 + 1 * .5 * 1 / 1.05 +  1 * .25 / 1.05 ^2\n    @test present_value(AnnuityDue(ins,n=1)) \u2248 1 \n    @test present_value(AnnuityDue(ins,n=2)) \u2248 1 + 1 * .5 * 1 / 1.05\n    @test present_value(AnnuityDue(ins,n=3)) \u2248 1 + 1 * .5 * 1 / 1.05 +  1 * .25 / 1.05 ^2\n    @test present_value(AnnuityDue(ins,n=0)) \u2248 0\n    @test present_value(AnnuityImmediate(ins,n=0)) \u2248 0\n    @test present_value(AnnuityImmediate(ins,n=1)) \u2248 1 * .5 * 1 / 1.05\n\n    @test present_value(Insurance(ins)) \u2248 0.5 / 1.05 + 0.5 * 0.5 / 1.05 ^ 2\n    @test present_value(Insurance(ins,n=1)) \u2248 0.5 / 1.05\n    @test present_value(Insurance(ins,n=0)) \u2248 0\n\n    ins_jl = LifeContingency(\n        JointLife(\n            lives = (ins.life,ins.life),\n            contingency = LastSurvivor(),\n            joint_assumption = Frasier()),\n        Yields.Constant(0.05)\n    )\n\n    @test survival(ins_jl,0) \u2248 1.0\n    @test survival(ins_jl,1) \u2248 .5 + .5 - .5 * .5\n    @test survival(ins_jl,2) \u2248 (.25 + .25 - .25 * .25)\n\nend\n\n@testset \"two years\" begin\n    ins = LifeContingency(\n        SingleLife(\n            mort = UltimateMortality([0.5,0.5]),\n            issue_age = 0\n        ),\n        Yields.Constant(0.05)\n    )\n\n    @test omega(ins) \u2248 2\n    @test present_value(AnnuityDue(ins,n=1)) \u2248 1\n    @test present_value(AnnuityDue(ins,n=2)) \u2248 1 + 1 * .5 * 1 / 1.05 \n    @test present_value(AnnuityDue(ins,n=3)) \u2248 1 + 1 * .5 * 1 / 1.05 + 1 * .25 * 1 / 1.05 ^ 2\n    @test present_value(AnnuityDue(ins,n=0)) == 0\n    @test present_value(AnnuityImmediate(ins,n=0)) == 0\n    @test present_value(AnnuityImmediate(ins,n=1)) \u2248 1 * .5 * 1 / 1.05 \n\n    @test present_value(Insurance(ins)) \u2248 0.5 / 1.05 + 0.5 * 0.5 / 1.05 ^ 2\n    @test present_value(Insurance(ins,n=1)) \u2248 0.5 / 1.05\n    @test present_value(Insurance(ins,n=0)) \u2248 0\n\n    ins_jl = LifeContingency(\n        JointLife(\n            lives = (ins.life,ins.life),\n            contingency = LastSurvivor(),\n            joint_assumption = Frasier()),\n        Yields.Constant(0.05)\n    )\n\n    @test omega(ins_jl) \u2248 2\n    @test present_value(AnnuityDue(ins_jl,n=1)) \u2248 1\n    @test present_value(AnnuityDue(ins_jl,n=2)) \u2248 1 + 1 * .75 /1.05\n    @test present_value(AnnuityDue(ins_jl,n=3)) \u2248 1 + 1 * .75 /1.05 + 1 * survival(ins_jl,2) / 1.05 ^ 2\n    @test present_value(AnnuityDue(ins_jl,n=0)) == 0\n    @test present_value(AnnuityImmediate(ins_jl,n=0)) == 0\n    @test present_value(AnnuityImmediate(ins_jl,n=1)) \u2248 1 * .75 /1.05\n\nend\n\n# assumes embedded 'testMort' table in combination with MortalityTables\nt = UltimateMortality(maleMort)\n\n@testset \"demo mortality\" begin\n    i = Yields.Constant(0.05)\n    ins = LifeContingency(SingleLife(mort = t, issue_age = 0), i)\n\n    @test l(ins, 0) \u2248 1.0\n    @test l(ins, 1) \u2248 0.993010000000000\n    @test l(ins, 2) \u2248 0.992566124530000\n\n    @test D(ins, 0) \u2248 1.0\n    @test D(ins, 1) \u2248 0.945723809523809\n    @test D(ins, 2) \u2248 0.900286734267574\n\n    @test N(ins, 0) \u2248 20.113017073119200\n    @test N(ins, 1) \u2248 19.113017073119200\n    @test N(ins, 2) \u2248 18.167293263595400\n\n    @test C(ins, 0) \u2248 0.006657142857142910\n    @test C(ins, 1) \u2248 0.000402608136054441\n    @test C(ins, 2) \u2248 0.000258082197156658\n\n    @test M(ins, 0) \u2248 0.0422372822324182\n    @test M(ins, 1) \u2248 0.0355801393752753\n    @test M(ins, 2) \u2248 0.0351775312392208\n\n    @test present_value(Insurance(ins   )) \u2248 0.04223728223\n    @test present_value(Insurance(ins, n=0)) \u2248 0.0\n    @test present_value(Insurance(ins, n=1)) \u2248 0.0066571428571429\n    @test present_value(AnnuityDue(ins, n=0)) \u2248 0.0\n    @test present_value(AnnuityDue(ins, n=1)) \u2248 1.0 \n    @test present_value(AnnuityDue(ins, n=2)) \u2248 1.0 + survival(ins,1) / 1.05\n    @test present_value(AnnuityImmediate(ins, n=0)) \u2248 0.0\n    @test present_value(AnnuityImmediate(ins, n=1)) \u2248 survival(ins,1) / 1.05\n\n    @test present_value(Insurance(ins, n=30)) \u2248 0.0137761089686975\n\n    @test N(ins, 26) \u2248 5.156762988852310\n    @test D(ins, 26) \u2248 0.275358702015970\n    @test present_value(AnnuityDue(ins, n=26)) \u2248 14.9562540842669\n\n\n\nend ", "meta": {"hexsha": "408a1b6d7dfe9108f097ec5c5426ccce9a67a711", "size": 10089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/simple_mort.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": "test/simple_mort.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": "test/simple_mort.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": 34.0844594595, "max_line_length": 103, "alphanum_fraction": 0.5988700565, "num_tokens": 3879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286373, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7587951698466215}}
{"text": "using Test\nusing HaltonSequences\n\n@testset \"values\" begin\n    @test haltonvalue(1,2) \u2248 0.5\n    @test haltonvalue(111111,2) \u2248 0.876182556152344\n    @test haltonvalue(789,19) \u2248 0.534917626476163\n    @test Halton{Rational}(17)[24] == 120//289\nend\n\n@testset \"integrals\" begin\n    @test sum( Halton(5)[100:20100] )/20000 \u2248 0.5 atol=0.002\n    p = HaltonPoint(4,length=32000)\n    @test sum(p)/32000 \u2248 [0.5,0.5,0.5,0.5] atol=0.001\n    h = Halton{Float32}(29,start=1234,length=22000)\n    @test sum( h.^2 )/22000 \u2248 1/3 atol=0.001\nend\n", "meta": {"hexsha": "68080146da7fda8115c999c9ae6f93e50d0cc208", "size": 524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/HaltonSequences.jl-13907d55-377f-55d6-a9d6-25ac19e11b95", "max_stars_repo_head_hexsha": "dc7e469e44d75cb5faf56a4ef8243964dcd4d4a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-10-12T05:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T02:09:12.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/HaltonSequences.jl-13907d55-377f-55d6-a9d6-25ac19e11b95", "max_issues_repo_head_hexsha": "dc7e469e44d75cb5faf56a4ef8243964dcd4d4a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-10-11T19:51:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-28T20:03:00.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/HaltonSequences.jl-13907d55-377f-55d6-a9d6-25ac19e11b95", "max_forks_repo_head_hexsha": "dc7e469e44d75cb5faf56a4ef8243964dcd4d4a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:51:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:45:06.000Z", "avg_line_length": 29.1111111111, "max_line_length": 60, "alphanum_fraction": 0.6583969466, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.758795169642933}}
{"text": "@testset \"Set distances\" begin\n    @testset \"$n-dimensional orthants\" for n in 1:3:15\n        v = rand(n)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Reals(n)) \u2248 0 atol=eps(Float64)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Zeros(n)) > 0\n        @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Nonnegatives(n)) \u2248 0 atol=eps(Float64)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), -v, MOI.Nonpositives(n)) \u2248 0 atol=eps(Float64)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Nonpositives(n)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), -v, MOI.Nonnegatives(n)) > 0\n    end\n\n    @testset \"Scalar comparisons\" begin\n        values = rand(10)\n        for v in values\n            @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.EqualTo(v)) \u2248 0 atol=eps(Float64)\n            @test MOD.distance_to_set(MOD.DefaultDistance(), -v, MOI.EqualTo(v)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.EqualTo(-v)) \u2248 2v\n            @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.LessThan(v)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.LessThan(v+1)) \u2248 0\n            @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.LessThan(0)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), -v, MOI.GreaterThan(0)) \u2248 v\n            @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.GreaterThan(v)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), v+1, MOI.GreaterThan(v+1)) \u2248 0\n            @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Interval(v,v)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Interval(-v,v)) \u2248 0\n            @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Interval(-v, 0.0)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), -v, MOI.Interval(0.0, v)) \u2248 v\n        end\n    end\n    @testset \"$n-dimensional norm cones\" for n in 2:5:15\n        x = rand(n)\n        tsum = sum(x)\n        vsum = vcat(tsum, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vsum, MOI.NormOneCone(n+1)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), vsum, MOI.NormInfinityCone(n+1)) \u2248 0\n        tmax = maximum(x)\n        vmax = vcat(tmax, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vmax, MOI.NormOneCone(n+1)) > 0\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vmax, MOI.NormInfinityCone(n+1)) \u2248 0 atol=eps(Float64)\n        tmin = 0\n        vmin = vcat(tmin, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vmin, MOI.NormInfinityCone(n+1)) \u2248 tmax\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vmin, MOI.NormOneCone(n+1)) \u2248 tsum\n\n        tvalid = sqrt(n) # upper bound on the norm2\n        vok_soc = vcat(tvalid, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vok_soc, MOI.SecondOrderCone(n+1)) \u2248 0 atol=eps(Float64)\n        vko_soc = vcat(-1.5 * tvalid, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vko_soc, MOI.SecondOrderCone(n+1)) \u2248 sqrt(9/4 * n + LinearAlgebra.norm(x)^2)\n\n        t_ko_rot = u_ko_rot = LinearAlgebra.norm2(x) / 2\n        vko_roc = vcat(t_ko_rot, u_ko_rot, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vko_roc, MOI.RotatedSecondOrderCone(n+2)) \u2248 LinearAlgebra.dot(x,x) / 2\n        vok_roc = vcat(t_ko_rot * 2, u_ko_rot, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vok_roc, MOI.RotatedSecondOrderCone(n+2)) \u2248 0 atol=10eps(Float64)\n    end\n\n    @testset \"Geometric Mean cone dimension $n\" for n in 2:5:15\n        x = rand(n)\n        t = 0.5 * prod(x)^(inv(n))\n        vok = vcat(t, x)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vok, MOI.GeometricMeanCone(n+1)) \u2248 0 atol=eps(Float64)\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vcat(t / 2, x), MOI.GeometricMeanCone(n+1)) \u2248 0 atol=eps(Float64)\n        # negative x always means positive distance\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vcat(t / 2, vcat(x, -1)), MOI.GeometricMeanCone(n+2)) > 0\n        @test MOD.distance_to_set(MOD.DefaultDistance(), vcat(t / 2, -x), MOI.GeometricMeanCone(n+1)) > 0\n    end\n\n    @testset \"Exponential and power cones\" begin\n        for _ in 1:30\n            (x, y, z) = rand(3)\n            y += 1 # ensure y > 0\n            if y * exp(x/y) <= z\n                @test MOD.distance_to_set(MOD.DefaultDistance(), [x, y, z], MOI.ExponentialCone()) \u2248 0 atol=eps(Float64)\n                @test MOD.distance_to_set(MOD.DefaultDistance(), [x, -1, z], MOI.ExponentialCone()) \u2248 1 atol=eps(Float64)\n            else\n                @test MOD.distance_to_set(MOD.DefaultDistance(), [x, y, z], MOI.ExponentialCone()) \u2248 y * exp(x/y) - z\n            end\n            (u, v, w) = randn(3)\n            if u != 0.0 # just in case not to blow up\n                if -u*exp(v/u) < \u212f * w && u < 0\n                    @test MOD.distance_to_set(MOD.DefaultDistance(), [u, v, w], MOI.DualExponentialCone()) \u2248 0 atol=eps(Float64)\n                elseif u < 0\n                    @test MOD.distance_to_set(MOD.DefaultDistance(), [u, v, w], MOI.DualExponentialCone()) \u2248 -u*exp(v/u) - \u212f * w\n                end\n\n            end\n            (x, y) = randn(2)\n            if x < 0 || y < 0\n                for e in  (10 * rand(10) .- 5) # e in [-5, 5]\n                    @test MOD.distance_to_set(MOD.DefaultDistance(), [x, y, 0.0], MOI.PowerCone(e)) > 0\n                end\n            else\n                for e in  (10 * rand(10) .- 5) # e in [-5, 5]\n                    r = x^e * y^(1-e)\n                    for z in -r:-0.5:r\n                        @test MOD.distance_to_set(MOD.DefaultDistance(), [x, y, z], MOI.PowerCone(e)) \u2248 0 atol=eps(Float64)\n                    end\n                    @test MOD.distance_to_set(MOD.DefaultDistance(), [x, y, 3r], MOI.PowerCone(e)) \u2248 MOD.distance_to_set(MOD.DefaultDistance(), [x, y, -3r], MOI.PowerCone(e)) > 0\n                end\n            end\n\n            (u, v, w) = 10 * rand(3)\n            e = rand()\n            if 0 < e < 1 # avoid exponents of negatives\n                @test MOD.distance_to_set(MOD.DefaultDistance(), [u, v, 0.0], MOI.DualPowerCone(e)) \u2248 0 atol = 10eps(Float64)\n                @test MOD.distance_to_set(MOD.DefaultDistance(), [u, v, u^e * v^(1-e) / (e^e * (1-e)^(1-e))], MOI.DualPowerCone(e)) \u2248 0 atol=100eps(Float64)\n                @test MOD.distance_to_set(MOD.DefaultDistance(), [u, v, 1 + u^e * v^(1-e) / (e^e * (1-e)^(1-e))], MOI.DualPowerCone(e)) \u2248 1\n            end\n        end\n    end\nend\n\nstruct DummyDistance <: MOD.AbstractDistance end\n\nMOD.distance_to_set(::DummyDistance, v, s) = MOD.distance_to_set(MOD.DefaultDistance(), v, s) / 2\n\n@testset \"Set non-default distance\" begin\n    for n in 1:3\n        v = rand(n)\n        for s in (MOI.Reals(n), MOI.Zeros(n), MOI.Nonnegatives(n), MOI.Nonpositives(n))\n            @test MOD.distance_to_set(MOD.DefaultDistance(), v, MOI.Reals(n)) \u2248 2 * MOD.distance_to_set(DummyDistance(), v, MOI.Reals(n)) atol=eps(Float64)\n            @test MOD.distance_to_set(MOD.DefaultDistance(), -v, MOI.Reals(n)) \u2248 2 * MOD.distance_to_set(DummyDistance(), -v, MOI.Reals(n)) atol=eps(Float64)\n        end\n    end\nend\n\n@testset \"Distance is composition of projection\" begin\n    for n in (1, 2, 10)\n        @testset \"Second order cone $n\" begin\n            s = MOI.SecondOrderCone(n+1)\n            for _ in 1:10\n                x = randn(n)\n                for t in (-1, 0, 0.5, LinearAlgebra.norm(x), 2LinearAlgebra.norm(x))\n                    v = vcat(t, x)\n                    dist = MOD.distance_to_set(MOD.DefaultDistance(), v, s)\n                    dist_proj = LinearAlgebra.norm2(MOD.projection_on_set(MOD.DefaultDistance(), v, s) - v)\n                    @test dist \u2248 dist_proj atol=10e-5\n                    if dist \u2248 0\n                        @test MOD.distance_to_set(MOD.EpigraphViolationDistance(), v, s) \u2248 0\n                    end\n                end\n            end\n        end\n        @testset \"PSD cone $n\" begin\n            s = MOI.PositiveSemidefiniteConeTriangle(n)\n            X = Matrix{Float64}(undef, n, n)\n            Xm = Matrix{Float64}(undef, n, n)\n            Xp = Matrix{Float64}(undef, n, n)\n            for _ in 1:10\n                X .= randn(n, n)\n                X .= (X .+ X')\n                v = MOD.vec_symm(X)\n                vproj = MOD.projection_on_set(MOD.DefaultDistance(), v, s)\n                dist = MOD.distance_to_set(MOD.DefaultDistance(), v, s)\n                @test LinearAlgebra.norm(v - vproj) \u2248 dist atol=10e-5\n                dist1 = MOD.distance_to_set(MOD.NormedEpigraphDistance{1}(), v, s)\n                @test LinearAlgebra.norm(v - vproj, 1) \u2248 dist1 atol=10e-5\n                \u03bb = LinearAlgebra.eigvals(X)\n                if \u03bb[1] >= 0\n                    Xm = X - (\u03bb[1] + \u03bb[end])/2 * LinearAlgebra.I\n                    v = MOD.vec_symm(Xm)\n                    vproj = MOD.projection_on_set(MOD.DefaultDistance(), v, s)\n                    dist = MOD.distance_to_set(MOD.DefaultDistance(), v, s)\n                    @test LinearAlgebra.norm(v - vproj) \u2248 dist atol=10e-5\n                elseif \u03bb[end] <= 0\n                    Xp = X + (\u03bb[1] + \u03bb[end])/2 * LinearAlgebra.I\n                    v = MOD.vec_symm(Xp)\n                    vproj = MOD.projection_on_set(MOD.DefaultDistance(), v, s)\n                    dist = MOD.distance_to_set(MOD.DefaultDistance(), v, s)\n                    @test LinearAlgebra.norm(v - vproj) \u2248 dist atol=10e-5\n                end\n            end\n        end\n    end\nend\n", "meta": {"hexsha": "fc200ba8cf46c364958e373c62bd933cfa253bf7", "size": 9403, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/distances.jl", "max_stars_repo_name": "tjdiamandis/MathOptSetDistances.jl", "max_stars_repo_head_hexsha": "5c232293b8b1b1f05aee5172d05cf23321a3504d", "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": "test/distances.jl", "max_issues_repo_name": "tjdiamandis/MathOptSetDistances.jl", "max_issues_repo_head_hexsha": "5c232293b8b1b1f05aee5172d05cf23321a3504d", "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": "test/distances.jl", "max_forks_repo_name": "tjdiamandis/MathOptSetDistances.jl", "max_forks_repo_head_hexsha": "5c232293b8b1b1f05aee5172d05cf23321a3504d", "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": 55.6390532544, "max_line_length": 178, "alphanum_fraction": 0.569499096, "num_tokens": 2914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094438, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7587951657099692}}
{"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\u20135596\n\n#### HLLE type\nimmutable HLLE{T <: Real} <: SpectralResult\n    k::Int\n    \u03bb::AbstractVector{T}\n    proj::Projection{T}\n\n    HLLE{T}(k::Int, \u03bb::AbstractVector{T}, proj::Projection{T}) = new(k, \u03bb, proj)\nend\n\n## properties\noutdim(M::HLLE) = size(M.proj, 1)\nprojection(M::HLLE) = M.proj\n\neigvals(M::HLLE) = M.\u03bb\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.\u03bb', 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        \u03bc = mean(X[:,I[:,i]],2)\n        N = X[:,I[:,i]] .- \u03bc\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    \u03bb, V = decompose(W'*W, d)\n    return HLLE{T}(k, \u03bb, 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": "######### CmdStan program example  ###########\n\nusing CmdStan, Test, Statistics\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 = Dict(\"N\" => 1, \"y\" => [0])\n\n  global stanmodel, rc, sim\n  \n  stanmodel = Stanmodel(num_samples=1200, thin=2, name=\"bernoulli\",\n    output_format=:array, model=bernoullimodel);\n\n  rc, sim, cnames = stan(stanmodel, bernoullidata, ProjDir,\n    diagnostics=false, CmdStanDir=CMDSTAN_HOME);\n\n  if rc == 0\n    println()\n    println(\"Test round.(mean(theta), 1) \u2248 0.3 rtol=0.1\")\n    @test round.(mean(sim[:,8,:]), digits=1) \u2248 0.3 rtol=0.1\n  end\nend # cd\n", "meta": {"hexsha": "349b6ebc80d17da88cd9cae59dc8a50ace13090f", "size": 800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/BernoulliScalar/bernoulliscalar.jl", "max_stars_repo_name": "mkshirazi/CmdStan.jl", "max_stars_repo_head_hexsha": "61c90f0dc160b23e691b0563a8f77c51d4f5677d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2018-11-17T10:38:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T17:23:55.000Z", "max_issues_repo_path": "examples/BernoulliScalar/bernoulliscalar.jl", "max_issues_repo_name": "mkshirazi/CmdStan.jl", "max_issues_repo_head_hexsha": "61c90f0dc160b23e691b0563a8f77c51d4f5677d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 93, "max_issues_repo_issues_event_min_datetime": "2018-05-17T04:41:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T15:07:20.000Z", "max_forks_repo_path": "examples/BernoulliScalar/bernoulliscalar.jl", "max_forks_repo_name": "mkshirazi/CmdStan.jl", "max_forks_repo_head_hexsha": "61c90f0dc160b23e691b0563a8f77c51d4f5677d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:34:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-26T20:46:07.000Z", "avg_line_length": 21.0526315789, "max_line_length": 67, "alphanum_fraction": 0.605, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7587951584081717}}
{"text": "\nusing SatisfiabilityInterface, Symbolics\n\n\"Constraints representing different colours for each edge of a graph\"\ndifferent_colours(E, c) = [c[i] \u2260 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] \u2208 colours for i in 1:length(V)]\n        \n        [c[i] \u2260 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 \u2208 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] \u2208 colours for i in 1:length(V)]\n        \n        [c[i] \u2260 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\u03c0 * 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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing6.01\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 07d8c2c0-3b2e-11eb-344d-c14ab2a82d0d\nText(\"Using confint() function: $(confint(OneSampleZTest(xBar,sig,n),alpha))\")\n\n# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing6.01\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u25501aa41898-3afa-11eb-2f49-570853ce6435\n# \u2560\u255007d8c2c0-3b2e-11eb-344d-c14ab2a82d0d\n# \u255f\u2500475ff888-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 \u0394(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\u2081 = Float64[], P\u2082 = Float64[], \u0394 = Float64[], \u0394\u208d\u03bc\u208e = Float64[], Z = Float64[])\n\n    # main loop -\n    for row_index \u2208 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        \u03b4_value = multiplier * log(today_close_price / yesterday_close_price)\n\n        # push! -\n        push!(return_table, (tmp_date, yesterday_close_price, today_close_price, \u03b4_value, 0.0, 0.0))\n    end\n\n    # compute the mean -\n    \u03bc = mean(return_table[!, :\u0394])\n\n    # compute the std -\n    \u03c3 = std(return_table[!, :\u0394])\n\n    # add values to the \u03b4 - \u03bc col -\n    (number_of_rows, _) = size(return_table)\n    for row_index \u2208 1:number_of_rows\n        value = return_table[row_index, :\u0394] - \u03bc\n        return_table[row_index, :\u0394\u208d\u03bc\u208e] = value\n    end\n\n    # add the Z column -\n    for row_index \u2208 1:number_of_rows\n        value = (1 / \u03c3) * (return_table[row_index, :\u0394] - \u03bc)\n        return_table[row_index, :Z] = value\n    end\n\n    # return -\n    return return_table\nend\n\nfunction \u0394(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\u2081 = Float64[], P\u2082 = Float64[], \u0394 = Float64[], \u0394\u208d\u03bc\u208e = Float64[], Z = Float64[])\n\n    # main loop -\n    for row_index \u2208 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        \u03b4_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, \u03b4_value, 0.0, 0.0))\n    end\n\n    # compute the mean -\n    \u03bc = mean(return_table[!, :\u0394])\n\n    # compute the std -\n    \u03c3 = std(return_table[!, :\u0394])\n\n    # add values to the \u03b4 - \u03bc col -\n    (number_of_rows, _) = size(return_table)\n    for row_index \u2208 1:number_of_rows\n        value = return_table[row_index, :\u0394] - \u03bc\n        return_table[row_index, :\u0394\u208d\u03bc\u208e] = value\n    end\n\n    # add the Z column -\n    for row_index \u2208 1:number_of_rows\n        value = (1 / \u03c3) * (return_table[row_index, :\u0394] - \u03bc)\n        return_table[row_index, :Z] = value\n    end\n\n    # return -\n    return return_table\nend\n\nfunction \u0394(models::Array{T,1};\n    multiplier::Float64 = 1.0)::Dict{String,DataFrame} where {T<:AbstractBaseCampComputation}\n\n\n    # initialize -\n    \u0394_dictionary = Dict{String,DataFrame}()\n\n    # compute the returns for each model in the array -\n    for model \u2208 models\n        ticker = model.ticker\n        \u0394_dictionary[ticker] = \u0394(model; multiplier = multiplier)\n    end\n\n    # return -\n    return \u0394_dictionary\nend\n\nfunction \ud835\udc9f(distribution::Type{T}, ticker_symbol_array::Array{String,1}, data::Dict{String, DataFrame}; \n    colkey::Symbol = :\u0394)::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) \u2208 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 \u2208 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 \ud835\udc9f(distribution::Type{T}, data::DataFrame; \n    colkey::Symbol = :\u0394)::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 \ud835\udc9f(distribution::Type{T}, data::DataFrame, weights::Union{Nothing,Array{Float64,1}};\n    colkey::Symbol = :\u0394)::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 \ud835\udc9f(distribution::Type{T}, data::Dict{String, DataFrame}; \n    colkey::Symbol = :\u0394, 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 \ud835\udc9f -\n    for (key,value) \u2208 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 \ud835\udcab(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 \u2208 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 = :\u0394)::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 \u2208 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 \u2208 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 \u03b2(tickers::Array{String,1}, data::Dict{String,DataFrame};\n    key::Symbol = :\u0394, base::String = \"SPY\")::Array{Float64,1}\n\n    # initialize -\n    number_of_tickers = length(tickers)\n    \u03b2_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 \u03b2 -\n    for ticker_index \u2208 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 \u03b2_value -\n        \u03b2_value = cov(return_array_ticker, base_return_array) * (1 / var_base)\n\n        # capture -\n        \u03b2_array[ticker_index] = \u03b2_value\n    end\n\n    # return -\n    return \u03b2_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 \u2208 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 \u2208 1:number_of_steps\n\n\t\ttmp_vector = Array{Float64,1}()\n                \n        # sample the strata ...\n        for strata_index \u2208 1:number_of_strata\n            \n            # compute a number_of_sample_paths draws from tis strata?\n            for _ \u2208 1:number_of_sample_paths\n                \n                # role a random number -\n                r = rand()\n\n                # compute V -\n                V\u2081 = (strata_index - 1)/number_of_strata + r/number_of_strata\n                V\u2082 = (strata_index - 1)/number_of_strata + (1 - r)/number_of_strata\n\n                # compute the quantile for this V -\n                q\u2081 = quantile(model, V\u2081)\n                q\u2082 = quantile(model, V\u2082)\n\n                # grab this value -\n                push!(tmp_vector, q\u2081)\n                push!(tmp_vector, q\u2082)\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) \u2208 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": "\"\"\"\n# module Doolittle\n\n\n\n# Examples\n\n```jldoctest\njulia>\n```\n\"\"\"\nmodule Doolittle\n\nusing LinearAlgebra: I, kron, UpperTriangular\n\nusing APMAE4001.Matrix: issquare\nusing APMAE4001.LUFactorization.Substitution\n\nexport doolittle_lu,\n    polysolve\n\nfunction row_vector(n::Int, k::Int)\n    v = zeros(n)\n    v[k] = one(eltype(v))\n    return v\nend\n\n\"\"\"\n    elimination_factors(n::Int, k::Int, A::AbstractMatrix)\n\nGenerate a vector of factors to eliminate the `k`th column.\nCombine this function with `row_vector` to to generate an general elementary elimination matrix.\n\n# Arguments\n- `n::Integer`: the size of the matrix `A`.\n- `k::Integer`: the step count in the elimination process. It must satisfies `1 \u2264 k \u2264 n - 1`.\n- `A::AbstractMatrix`: the matrix from `(k - 1)`th step of the elimination process.\n\"\"\"\nfunction elimination_factors(n::Int, k::Int, A::AbstractMatrix)\n    v = zeros(promote_type(eltype(A), Float64), n)\n    for j in (k + 1):n\n        v[j] = A[j, k] / A[k, k]  # elimination factor\n    end\n    v\nend\n\n\"\"\"\n    general_elementary_elimination_matrix(lk::AbstractVector, ek::AbstractVector)\n\nElimination matrix ``E_{k}`` do row operations to eliminate the `k`th column.\n\"\"\"\ngeneral_elementary_elimination_matrix(lk::AbstractVector, ek::AbstractVector) = I - kron(lk, transpose(ek))  # `I` is the identity matrix.\n\n\"\"\"\n    doolittle_lu(A::AbstractMatrix; include_l::Bool=true, include_e::Bool=false)\n\nReferenced from [Wikipedia \"LU decomposition\" page](https://en.wikipedia.org/wiki/LU_decomposition#Doolittle_algorithm).\n\"\"\"\nfunction doolittle_lu(A::AbstractMatrix; include_l::Bool = true, include_e::Bool = false)\n    issquare(A) || throw(DimensionMismatch(\"The matrix `A` is not a square matrix!\"))\n    n = size(A, 1)\n\n    intermediate_elementary_elimination_matrices = []\n    for k in 1:(n - 1)\n        Ek = general_elementary_elimination_matrix(elimination_factors(n, k, A), row_vector(n, k))\n        pushfirst!(intermediate_elementary_elimination_matrices, Ek)  # Keep this order!\n        A = Ek * A\n    end\n    # Now `A` is the U matrix.\n    E = prod(*, intermediate_elementary_elimination_matrices)\n    include_e && return E, A\n    include_l && return inv(E), A  # L matrix is `inv(E)`.\n    return A\nend\n\nfunction polysolve(A::AbstractMatrix, b::AbstractVector)\n    E, U = doolittle_lu(A, include_e = true)\n    substitution(UpperTriangular(U), E * b)\nend\n\nend", "meta": {"hexsha": "e126f5b5515dd54ed26259d5edf5e3f793496a7b", "size": 2376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LUFactorization/Doolittle.jl", "max_stars_repo_name": "singularitti/APMAE4001.jl", "max_stars_repo_head_hexsha": "98f41ee9f41423ab177966a23d83b0b66b25dc2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LUFactorization/Doolittle.jl", "max_issues_repo_name": "singularitti/APMAE4001.jl", "max_issues_repo_head_hexsha": "98f41ee9f41423ab177966a23d83b0b66b25dc2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-08T14:18:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T14:18:11.000Z", "max_forks_repo_path": "src/LUFactorization/Doolittle.jl", "max_forks_repo_name": "singularitti/APMAE4001.jl", "max_forks_repo_head_hexsha": "98f41ee9f41423ab177966a23d83b0b66b25dc2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:17:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:17:52.000Z", "avg_line_length": 29.3333333333, "max_line_length": 138, "alphanum_fraction": 0.6990740741, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7587526218890684}}
{"text": "n = 7 # rand(1:7)\n@test matrixdepot(\"sampling\", n) == matrixdepot(\"sampling\", Float64, n)\n\nA = matrixdepot(\"sampling\", n)\nv = sort(eigvals(A))\n@test v \u2248 [0: n - 1;] atol=1e-10\nprintln(\"'sampling' passed test...\")\n", "meta": {"hexsha": "837185b43354eb7ae9207be515bc248c2262c79a", "size": 213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_sampling.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_sampling.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_sampling.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 26.625, "max_line_length": 71, "alphanum_fraction": 0.6291079812, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7587526188498244}}
{"text": "struct Margins\n    # critical frequency\n    \u03c9_c::Float64\n    # gain cross-over frequency\n    \u03c9_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, \u03c9_c_guess=0.001, \u03c9_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 \u03c9_c or \u03c9_g is not found (i.e. if either are `NaN`), but the `bode_plot` clearly shows \na critical/gain crossover frequency, adjust `\u03c9_c_guess` or `\u03c9_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.\u03c9_c # critical freq. (radians / time)\nmargins.\u03c9_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; \u03c9_c_guess::Float64=0.001, \u03c9_g_guess::Float64=0.001)\n    # critical frequency \u2220 G(i \u03c9_c) = -\u03c0\n    \u03c9_c = NaN\n    try\n        \u03c9_c = fzero(\u03c9 -> angle(evaluate(g_ol, im * \u03c9)) + \u03c0, \u03c9_c_guess, atol=2*sqrt(eps()))\n    catch da_error\n        if isa(da_error, Roots.ConvergenceFailed)\n            \u03c9_c = NaN\n        else\n            println(da_error)\n            error(\"something went wrong when computing \u03c9_c\")\n        end\n    end\n    # check for spurious solution (often \u03c9_c d.n.e.) TODO check issue on Roots.jl\n    if ! isapprox(angle(evaluate(g_ol, im * \u03c9_c)), -\u03c0, rtol=0.01)\n        \u03c9_c = NaN\n    end\n\n    # gain cross over frequency | G(i \u03c9_g) | = 1\n    \u03c9_g = NaN\n    try\n        \u03c9_g = fzero(\u03c9 -> abs(evaluate(g_ol, im * \u03c9)) - 1.0, \u03c9_g_guess, atol=2*sqrt(eps()))\n    catch da_error\n        if isa(da_error, Roots.ConvergenceFailed)\n            \u03c9_g = NaN\n        else\n            println(da_error)\n            error(\"something went wrong when computing \u03c9_g\")\n        end\n    end\n    # check for spurious solution (often \u03c9_c d.n.e.) TODO check issue on Roots.jl\n    if ! isapprox(abs(evaluate(g_ol, im * \u03c9_g)), 1.0, rtol=0.01)\n        \u03c9_g = NaN\n    end\n    # gain margin = 1 / | G(i \u03c9_c) |\n    gm = 1 / abs(evaluate(g_ol, im * \u03c9_c))\n    # phase margin = \u2220 G(i \u03c9_g) + \u03c0\n    pm = \u03c0 + angle(evaluate(g_ol, im * \u03c9_g))\n    return Margins(\u03c9_c, \u03c9_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": "#=\nWe can determine how \"out of order\" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.\n\nGiven an array, count the number of inversions it has. Do this faster than O(N^2) time.\n\nYou may assume each element in the array is distinct.\n\nFor example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion.\n=#\n\nusing Test\ninclude(\"Solutions/problem44_count_inversions.jl\")\n\n@test inversions([2, 4, 1, 3, 5]) == 3\n@test inversions([5, 4, 3, 2, 1]) == 10\n", "meta": {"hexsha": "88d41e6992c6ca503604a81ecd44f9d9ce7f70d6", "size": 729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tests/problem44_count_inversions_test.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": "Tests/problem44_count_inversions_test.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": "Tests/problem44_count_inversions_test.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": 45.5625, "max_line_length": 224, "alphanum_fraction": 0.695473251, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7587526106538162}}
{"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 \u2208 IntervalDomain(0.0,1.0),\r\n           x \u2208 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\u00d72 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\u00d71 Matrix{Int64}:\n 8\n\njulia> conv_neg_binomial_rng(.4, 5, 5)\n5\u00d71 Matrix{Int64}:\n 11\n 14 \n 8\n 10\n 13\n\njulia> conv_neg_binomial_rng(.4, 5, (2,2))\n2\u00d72\u00d71 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 \u2208 2:n\n\t\ttsum = 0\n\t\tfor k \u2208 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 \u2208 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 \u2208 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    \u0394t = 1.0 # Time step\r\n    \u0394P = [20.0; 5.0] # Process errors in process covariance matrix\r\n    \u0394 = [25.0; 6.0] # Observation errors\r\n    return X, a, \u0394, \u0394P, \u0394t\r\nend\r\n\r\n## Define the state space model\r\n\r\nfunction define_model(X, a, \u0394, \u0394P, \u0394t)\r\n    m, n = size(X)\r\n    Q = zeros(m, m) # Process noise covariance matrix\r\n    F = [1.0 \u0394t; 0.0 1.0] # Transition matrix\r\n    B = [\u0394t^2/2.0 \u0394t]' # Control-input matrix\r\n    u = 2.0 # # Control vector, acceleration\r\n    R = linalg.Diagonal([\u0394[1]^2 0.0; 0.0 \u0394[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([\u0394P[1]^2 \u0394P[1]*\u0394P[2]; \u0394P[2]*\u0394P[1] \u0394P[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, \u03a3)\r\n    k = length(Xk)\r\n    sm = Vector{kf.RTSSmoother}(undef, k)\r\n    sm[k] = kf.RTSSmoother(Xk[k], \u03a3[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], \u03a3[k-1], \u03a3[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    # \u039b, \u03bb = zeros(size(lsm.F)), zeros(size(lsm.F,1))\r\n    SH = skf[k].S \\ H'\r\n    \u039b, \u03bb = SH*H, -SH*skf[k].y\r\n    sm[k] = kf.MBFSmoother(skf[k].xk, skf[k].P, \u039b, \u03bb)\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, \u0394)\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=\u0394[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=\u0394[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, \u0394)\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=\u0394[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=\u0394[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, \u0394, \u0394P, \u0394t = get_data()\r\nP, Q, R, F, H, B, u, m, n = define_model(X, a, \u0394, \u0394P, \u0394t)\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, \u0394)\r\n\r\n## Rauch Tung Striebel Smoother\r\n\u03a3, Xk2m = kf.unpack_matrix(skf, [:P, :xk])\r\nskfm = run_smoothers_bts(Xk2m, F, \u03a3)\r\nXk2m = kf.unpack(skfm, :xk)\r\np2m = plot_kf_smooth(Xp, Xk, X, Xk2m, \u0394)\r\n\r\n## Modified Bryson\u2013Frazier Smoother\r\nskfmb = run_smoothers_mbf(skf, F, H)\r\nXk2mb = kf.unpack(skfmb, :xk)\r\np2m = plot_kf_smooth(Xp, Xk, X, Xk2mb, \u0394)\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": "\nimport NumDiffTools\nnorm(x) = maximum(abs.(x))\nusing Test\nusing ForwardDiff\n\n@info \"Checking derivative(f,x) of scalar function\"\nerr = NumDiffTools.derivative(sin, 2.0) - cos(2.0)\n@test norm(err) < 1e-12\n\n@info \"Checking derivative(f,x) of vector function\"\nf(x) = [sin(x), cos(x)]\nf!(y,x) = begin\n    y[1] = sin(x)\n    y[2] = cos(x)\n    nothing\nend\ndf(x) = [cos(x), -sin(x)]\nerr = NumDiffTools.derivative(f, 2.0) - df(2.0)\n@test norm(err) < 1e-12\n\n\n@info \"Checking derivative(f!, y, x)\"\ny = zeros(2)\nerr =  NumDiffTools.derivative(f!, y, 2.0) - df(2.0)\n@test norm(err) < 1e-12\n\n\n@info \"Checking derivative!(result, f, x)\"\nresult = zeros(2)\nNumDiffTools.derivative!(result, f, 2.0)\nerr = result - df(2)\n@test norm(err) < 1e-12\n\n@info \"Checking derivative!(result, f, y, x)\"\nNumDiffTools.derivative!(result,f!, y, 2.0)\nerr = result - df(2.0)\n@test norm(err) < 1e-12\n\n@info \"Checking gradient(f,x)\"\nf(x) = prod(cos.(x).^2 - sin.(x).^2)\ngradf(x) = [ - 4*cos(x[1])*sin(x[1])*(cos(x[2])^2 - sin(x[2])^2),\n             - 4*cos(x[2])*sin(x[2])*(cos(x[1])^2 - sin(x[1])^2)\n             ]\nerr = NumDiffTools.gradient(f, [1.5, 2.5]) - gradf([1.5, 2.5])\n@test norm(err) < 1e-12\n\n@info \"Checking gradient!(result, f, x)\"\nNumDiffTools.gradient!(result, f, [1.5, 2.5])\nerr = result - gradf([1.5, 2.5])\n@test norm(err) < 1e-12\n\n@info \"checking jacobian(f, x)\"\nf(x) = [ prod(cos.(x).^2 - sin.(x).^2),\n         sum(cos.(x).^2 - sin.(x).^2)]\nf!(y, x) = begin\n    y .= f(x)\n    nothing\nend\nJ(x) = [-4*cos(x[1])*sin(x[1])*(cos(x[2])^2 - sin(x[2])^2)  -4*cos(x[2])*sin(x[2])*(cos(x[1])^2 - sin(x[1])^2);\n        (-2*cos(x[1])*sin(x[1]) - 2*sin(x[1])*cos(x[1]))  (-2*cos(x[2])*sin(x[2]) - 2*sin(x[2])*cos(x[2]))\n        ]\nerr = NumDiffTools.jacobian(f, [1.5, 2.5]) - J([1.5, 2.5])\n@test norm(err) < 1e-12\n\n@info \"checking jacobian(f!, y, x)\"\nerr = NumDiffTools.jacobian(f!, y, [1.5, 2.5]) - J([1.5, 2.5])\n@test norm(err) < 1e-12\n\n@info \"checking jacobian!(result, f, x)\"\nresult = zeros(2,2)\nNumDiffTools.jacobian!(result, f, [1.5, 2.5])\nerr = result - J([1.5, 2.5])\n@test norm(err) < 1e-12\n\n@info \"Checking jacobian!(result, f!, y, x)\"\nresult = zeros(2,2)\nNumDiffTools.jacobian!(result, f!, y, [1.5, 2.5])\nerr = result - J([1.5, 2.5])\n@test norm(err) < 1e-12\n\n@info \"Checking hessian(f, x) for scalar functions of real numbers\"\nerr = NumDiffTools.hessian(sin, 1.0) + sin(1.0)\n@test norm(err) < 1e-10\n\n@info \"checkking hessian(f, x) for scalar functions of vectors\"\nf(x) = prod(cos.(x).^2 - sin.(x).^2)\n\nerr = NumDiffTools.hessian(f, [1.5, 2.5]) - ForwardDiff.hessian(f, [1.5, 2.5])\n@test norm(err) < 1e-10\n\n@info \"Checking hessian!(result, f, x)\"\nresult = zeros(2,2)\nNumDiffTools.hessian!(result, f, [1.5, 2.5])\nerr = result - ForwardDiff.hessian(f, [1.5, 2.5])\n@test norm(err) < 1e-10\n\n", "meta": {"hexsha": "e4420b803a6334424565f34edebce82f24965458", "size": 2765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 28.2142857143, "max_line_length": 111, "alphanum_fraction": 0.5880650995, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378682, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7586269135594901}}
{"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*\u03c0/(24*3600)\nlat   = \u03c0/4\n\nparams=parameters(\n     H = 2e3, \n    Ly = 600e3, \n    f\u2080 = 2*Omega*cos(lat), \n     g = 10, \n    Lj = 60e3, \n    Uj = 1.0,\n    Ny = 200,\n    dk = 5e-2,\n    k\u2098 = 2e0\n    );\n\nparams.Fr = (params.f\u2080 * params.Lj)^2/(params.g * params.H);\nparams.Ro =  params.Uj/(params.f\u2080 * 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\u2098) / 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     \u03c3 = zeros(Nmodes, Nk);\n     \u03c9 = zeros(Nmodes, Nk);   \n\u03c3modes = 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 \u03c3[:,cnt], \u03c9[:,cnt], \u03c3modes[:,:,cnt] = compute_spectrum(A, k, params, Nmodes);\nend\n\nplot_growth_rates(ks, \u03c3, Nmodes, \"growth_rates_Cartesian_Bickley_jet.png\")\n\nmode_number = 1;\n      \u03c3_max = maximum(\u03c3[mode_number,:]);\n    k_index = sortperm(\u03c3[mode_number,:],rev=true)[1];\n          k = ks[k_index]; # pick wavenumber\n\nplot_1D_streamfunction(k_index, k, y, \u03c3modes, mode_number, \"modes_1D_streamfunction.png\")\nplot_2D_streamfunction(k_index, k, y, \u03c3modes, mode_number, \"modes_2D_streamfunction.png\")\nplot_2D_vorticity( Dy, k_index, k, y, \u03c3modes, 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": "using QIntegrations, Test\n\n@testset \"QIntegrations\" begin\n\n#@test scipy_quad((x)->x,0,1)[1] == 0.5\nres = integrate_1d((x)->exp(-2*x),0,1)\n@test isapprox(res[1], (1-exp(-2))/2, atol=1e-8, rtol=1e-6)\nres = integrate_1d((x)->exp(-2*x),0,Inf)\n@test isapprox(res[1], 0.5, atol=1e-8, rtol=1e-6)\nres = integrate_1d((x)->exp(-x^2),-Inf,Inf)\n@test isapprox(res[1], sqrt(pi), atol=1e-8, rtol=1e-6)\n\nend\n", "meta": {"hexsha": "3c17c5a6c747dd187150367624bdc4cdc30911b9", "size": 393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "neversakura/QIntegration.jl", "max_stars_repo_head_hexsha": "39ef40c76acfbb500c41fb4daddeea2e8e2d73ed", "max_stars_repo_licenses": ["MIT"], "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": "neversakura/QIntegration.jl", "max_issues_repo_head_hexsha": "39ef40c76acfbb500c41fb4daddeea2e8e2d73ed", "max_issues_repo_licenses": ["MIT"], "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": "neversakura/QIntegration.jl", "max_forks_repo_head_hexsha": "39ef40c76acfbb500c41fb4daddeea2e8e2d73ed", "max_forks_repo_licenses": ["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.0714285714, "max_line_length": 59, "alphanum_fraction": 0.6361323155, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7586268990570638}}
{"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,\u03bc)\n    abs(t)^(2*\u03bc)*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(\u03b1,\u03b2)\n    return t->w_beta(t,\u03b1,\u03b2)\nend\n\nfunction w_beta(t,\u03b1,\u03b2)\n    -1 <= t <= 1 ? t^(\u03b1-1)*(1-t)^(\u03b2-1)/beta(\u03b1,\u03b2) : _throwError(t)\nend\n\nfunction build_w_gamma(\u03b1)\n    return t->w_gamma(t,\u03b1)\nend\n\nfunction w_gamma(t,\u03b1)\n    t >= 0. ? (1/gamma(\u03b1)*Float64(t)^(\u03b1-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": "module WeakDivPerpTests\n   using Gridap\n   using GridapGeosciences\n   using Plots\n   using Test\n\n   include(\"ConvergenceAnalysisTools.jl\")\n\n\n   # Nondivergent velocity field tangent to the sphere\n   # Reference:\n   #     Lauritzen et. al. GMD 2012\n   #     Eq. (18) and (19)\n   function W(\u03b8\u03d5)\n     \u03b8,\u03d5 = \u03b8\u03d5\n     u = 2*sin(\u03b8)^2*sin(2*\u03d5) + 2\u03c0/5*cos(\u03d5)\n     v = 2*sin(2*\u03b8)*cos(\u03d5)\n     spherical_to_cartesian_matrix(VectorValue(\u03b8,\u03d5,1.0))\u22c5VectorValue(u,v,0)\n   end\n\n   \"\"\"\n   Spherical divergence on unit sphere applied to perp(W)\n   \"\"\"\n   function divM_perpW(\u03b8\u03d5)\n     n_times_W=(\u03b8\u03d5)->(W(\u03b8\u03d5)\u00d7normal_unit_sphere(\u03b8\u03d5))\n     f=divergence_unit_sphere(n_times_W)\n     f(\u03b8\u03d5)\n   end\n\n   function compute_error_weak_div_perp(model,order,degree)\n     # Setup geometry\n     \u03a9=Triangulation(model)\n     d\u03a9=Measure(\u03a9,degree)\n     n=get_normal_vector(model)\n\n     # Setup H(div) spaces\n     reffe_rt = ReferenceFE(raviart_thomas, Float64, order)\n     V = FESpace(model, reffe_rt ; conformity=:HDiv)\n     U = TrialFESpace(V)\n\n     # H1 spaces\n     reffe_lgn = ReferenceFE(lagrangian, Float64, order+1)\n     S = FESpace(model, reffe_lgn; conformity=:H1)\n     R = TrialFESpace(S)\n\n     # Project the analytical velocity field W onto the H(div) space\n     a1(u,v) = \u222b(v\u22c5u)d\u03a9\n     b1(v)   = \u222b(v\u22c5(W\u2218xyz2\u03b8\u03d5))d\u03a9\n     op      = AffineFEOperator(a1,b1,U,V)\n     wh      = solve(op)\n\n     e = (W\u2218xyz2\u03b8\u03d5)-wh\n     println(sqrt(sum(\u222b(e\u22c5e)d\u03a9)))\n\n     # Compute weak div_perp operator\n     a2(u,v) = \u222b(v*u)d\u03a9\n     b2(v)   = \u222b(\u27c2(\u2207(v),n)\u22c5(-wh) )d\u03a9\n     op      = AffineFEOperator(a2,b2,R,S)\n     divwh   = solve(op)\n     e = divwh-divM_perpW\u2218xyz2\u03b8\u03d5\n\n     sqrt(sum(\u222b(e*e)d\u03a9))\n   end\n   @time ahs0,ak0errors,as0=convergence_study(compute_error_weak_div_perp,generate_n_values(2),0,4)\n   @test round(as0,digits=3) \u2248 2.084\n\n   @time bihs0,bik0errors,bis0=convergence_study(compute_error_weak_div_perp,generate_n_values(2),1,0,4)\n   @test round(bis0,digits=3) \u2248 0.947\n\n   @time biqhs0,biqk0errors,biqs0=convergence_study(compute_error_weak_div_perp,generate_n_values(2),2,0,4)\n   @test round(biqs0,digits=3) \u2248 2.083\n\n\n  #  plotd=plot([ahs0,bihs0,biqhs0],[ak0errors,bik0errors,biqk0errors],\n  #  xaxis=:log, yaxis=:log,\n  #  label=[\"k=0 analytical map\" \"k=0 bilinear map\" \"k=0 biquadratic map\"],\n  #  shape=:auto,\n  #  xlabel=\"h\",ylabel=\"L2 error norm\", legend=:bottomright)\n\n  #  savefig(plotd,\"L2_error_weak_div_perp.png\")\n\nend\n", "meta": {"hexsha": "d49cbceb5120837d8a989606651f09bf687e83c1", "size": 2388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/WeakDivPerpTests.jl", "max_stars_repo_name": "gridapapps/GridapGeosciences.jl", "max_stars_repo_head_hexsha": "6892e56b65e4889f1d4769c0b54521f65098d28c", "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": "test/WeakDivPerpTests.jl", "max_issues_repo_name": "gridapapps/GridapGeosciences.jl", "max_issues_repo_head_hexsha": "6892e56b65e4889f1d4769c0b54521f65098d28c", "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": "test/WeakDivPerpTests.jl", "max_forks_repo_name": "gridapapps/GridapGeosciences.jl", "max_forks_repo_head_hexsha": "6892e56b65e4889f1d4769c0b54521f65098d28c", "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.7710843373, "max_line_length": 107, "alphanum_fraction": 0.6503350084, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7586054797962957}}
{"text": "\nfunction linreg_loss(w, b, x, y)\n    yhat = sum(w .* x) + b\n    loss = sum(abs2(yhat - y))\nend\n\ninputs = [:w => [1.0, 1.0], :b => 2.0, :x => [3.0, 3.0], :y => 4.0]\nvals = ([v for (k,v) in inputs]...)\ndlinreg_loss = xdiff(linreg_loss; inputs...)\ndvals = dlinreg_loss(vals...)\n@test dvals == (16.0, [96.0, 96.0], 32.0, [32.0, 32.0], -32.0)\n\n\n# ReverseDiff doesn't support scalars yet\n# See: https://github.com/JuliaDiff/ReverseDiff.jl/issues/40\n# linreg_loss2(W, b, x, y) = sum(abs2.(y - (W * x .+ b)))\n# test_compare(linreg_loss2; W=randn(1,11), b = rand(), x=randn(11,1000), y=randn(1,1000))\n\n", "meta": {"hexsha": "51c560fca5179c8b6c3a7e1e47b815cbe9b26d34", "size": 594, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/linreg.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": "test/linreg.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": "test/linreg.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": 31.2631578947, "max_line_length": 90, "alphanum_fraction": 0.5824915825, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297142, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7586054695108276}}
{"text": "# ---\n# title: 168. Excel Sheet Column Title\n# id: problem168\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Easy\n# categories: Math\n# link: <https://leetcode.com/problems/excel-sheet-column-title/description/>\n# hidden: true\n# ---\n# \n# Given a positive integer, return its corresponding column title as appear in\n# an Excel sheet.\n# \n# For example:\n# \n#     \n#     \n#         1 -> A\n#         2 -> B\n#         3 -> C\n#         ...\n#         26 -> Z\n#         27 -> AA\n#         28 -> AB \n#         ...\n#     \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: 1\n#     Output: \"A\"\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: 28\n#     Output: \"AB\"\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: 701\n#     Output: \"ZY\"\n#     \n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "ad1dd7d31535fd040ae92ca78a35d9a3c53d0bde", "size": 830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/168.excel-sheet-column-title.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/168.excel-sheet-column-title.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/168.excel-sheet-column-title.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": 14.0677966102, "max_line_length": 78, "alphanum_fraction": 0.4614457831, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7585912465726867}}
{"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 \u2112 = prod(f)\n@show ln\u2112 = sum(log.(f)) \n@show avgln\u2112 = (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": "using Base.Test\nusing ToeplitzMatrices\n\nns = 101\nnl = 2000\n\nxs = randn(ns, 5)\nxl = randn(nl, 5)\n\nprintln(\"Toeplitz\")\nfor (As, Al, st) in ((Toeplitz(0.9.^(0:ns-1), 0.4.^(0:ns-1)),\n                        Toeplitz(0.9.^(0:nl-1), 0.4.^(0:nl-1)),\n                            \"Real general square\"),\n                     (Toeplitz(complex(0.9.^(0:ns-1)), complex(0.4.^(0:ns-1))),\n                        Toeplitz(complex(0.9.^(0:nl-1)), complex(0.4.^(0:nl-1))),\n                            \"Complex general square\"),\n                     (Circulant(0.9.^(0:ns - 1)),\n                        Circulant(0.9.^(0:nl - 1)),\n                            \"Real circulant\"),\n                     (Circulant(complex(0.9.^(0:ns - 1))),\n                        Circulant(complex(0.9.^(0:nl - 1))),\n                            \"Complex circulant\"),\n                     (TriangularToeplitz(0.9.^(0:ns - 1), :U),\n                        TriangularToeplitz(0.9.^(0:nl - 1), :U),\n                            \"Real upper triangular\"),\n                     (TriangularToeplitz(complex(0.9.^(0:ns - 1)), :U),\n                        TriangularToeplitz(complex(0.9.^(0:nl - 1)), :U),\n                            \"Complex upper triangular\"),\n                     (TriangularToeplitz(0.9.^(0:ns - 1), :L),\n                        TriangularToeplitz(0.9.^(0:nl - 1), :L),\n                            \"Real lower triangular\"),\n                     (TriangularToeplitz(complex(0.9.^(0:ns - 1)), :L),\n                        TriangularToeplitz(complex(0.9.^(0:nl - 1)), :L),\n                            \"Complex lower triangular\"))\n    print(\"$st: \")\n    @test_approx_eq As * xs full(As) * xs\n    @test_approx_eq Al * xl full(Al) * xl\n    @test_approx_eq A_ldiv_B!(As, LinAlg.copy_oftype(xs, eltype(As))) full(As) \\ xs\n    @test_approx_eq A_ldiv_B!(Al, LinAlg.copy_oftype(xl, eltype(Al))) full(Al) \\ xl\n    println(\"OK!\")\nend\n\nprint(\"Real general rectangular: \")\nAr1 = Toeplitz(0.9.^(0:nl-1), 0.4.^(0:ns-1))\nAr2 = Toeplitz(0.9.^(0:ns-1), 0.4.^(0:nl-1))\n@test_approx_eq Ar1 * xs full(Ar1) * xs\n@test_approx_eq Ar2 * xl full(Ar2) * xl\nprintln(\"OK!\")\n\nprint(\"Complex general rectangular: \")\nAr1 = Toeplitz(complex(0.9.^(0:nl-1)), complex(0.4.^(0:ns-1)))\nAr2 = Toeplitz(complex(0.9.^(0:ns-1)), complex(0.4.^(0:nl-1)))\n@test_approx_eq Ar1 * xs full(Ar1) * xs\n@test_approx_eq Ar2 * xl full(Ar2) * xl\nprintln(\"OK!\")\n\nprint(\"Symmetric Toeplitz: \")\nAs = SymmetricToeplitz(0.9.^(0:ns-1))\nAb = SymmetricToeplitz(abs(randn(ns)))\nAl = SymmetricToeplitz(0.9.^(0:nl-1))\n@test_approx_eq As * xs full(As) * xs\n@test_approx_eq Ab * xs full(Ab) * xs\n@test_approx_eq Al * xl full(Al) * xl\n@test_approx_eq A_ldiv_B!(As, copy(xs)) full(As) \\ xs\n@test_approx_eq A_ldiv_B!(Ab, copy(xs)) full(Ab) \\ xs\n@test_approx_eq A_ldiv_B!(Al, copy(xl)) full(Al) \\ xl\n@test_approx_eq StatsBase.levinson(As, xs) full(As) \\ xs\n@test_approx_eq StatsBase.levinson(Ab, xs) full(Ab) \\ xs\n@test_approx_eq StatsBase.levinson(Al, xl) full(Al) \\ xl\nprintln(\"OK!\")\n\nprintln(\"\\nHankel\")\nprint(\"Real square: \")\nH = Hankel([1.0,2,3,4,5],[5.0,6,7,8,0])\nx = ones(5)\n@test_approx_eq full(H)*x H*x\n\nHs = Hankel(0.9.^(ns-1:-1:0), 0.4.^(0:ns-1))\nHl = Hankel(0.9.^(nl-1:-1:0), 0.4.^(0:nl-1))\n@test_approx_eq Hs * xs[:,1] full(Hs) * xs[:,1]\n@test_approx_eq Hs * xs full(Hs) * xs\n@test_approx_eq Hl * xl full(Hl) * xl\nprintln(\"OK!\")\n\nprint(\"Complex square: \")\nH = Hankel(complex([1.0,2,3,4,5]), complex([5.0,6,7,8,0]))\nx = ones(5)\n@test_approx_eq full(H)*x H*x\n\nHs = Hankel(complex(0.9.^(ns-1:-1:0)), complex(0.4.^(0:ns-1)))\nHl = Hankel(complex(0.9.^(nl-1:-1:0)), complex(0.4.^(0:nl-1)))\n@test_approx_eq Hs * xs[:,1] full(Hs) * xs[:,1]\n@test_approx_eq Hs * xs full(Hs) * xs\n@test_approx_eq Hl * xl full(Hl) * xl\nprintln(\"OK!\")\n\nprint(\"Real rectangular: \")\nHs = Hankel(0.9.^(ns-1:-1:0), 0.4.^(0:nl-1))\nHl = Hankel(0.9.^(nl-1:-1:0), 0.4.^(0:ns-1))\n@test_approx_eq Hs * xl[:,1] full(Hs) * xl[:,1]\n@test_approx_eq Hs * xl full(Hs) * xl\n@test_approx_eq Hl * xs full(Hl) * xs\nprintln(\"OK!\")\n\nprint(\"Complex rectangular: \")\nHs = Hankel(complex(0.9.^(ns-1:-1:0)), complex(0.4.^(0:nl-1)))\nHl = Hankel(complex(0.9.^(nl-1:-1:0)), complex(0.4.^(0:ns-1)))\n@test_approx_eq Hs * xl[:,1] full(Hs) * xl[:,1]\n@test_approx_eq Hs * xl full(Hs) * xl\n@test_approx_eq Hl * xs full(Hl) * xs\nprintln(\"OK!\")\n\n\nif isdir(Pkg.dir(\"FastTransforms\"))\n    print(\"\\nBigFloat\")\n    using FastTransforms\n    T = Toeplitz(BigFloat[1,2,3,4,5], BigFloat[1,6,7,8,0])\n    @test_approx_eq T*ones(BigFloat,5) [22,24,19,16,15]\n\n    n = 512\n    r = map(BigFloat,rand(n))\n    T = Toeplitz(r,[r[1];map(BigFloat,rand(n-1))])\n    @test_approx_eq T*ones(BigFloat,n) full(T)*ones(BigFloat,n)\n\n    T = TriangularToeplitz(BigFloat[1,2,3,4,5],:L)\n    @test_approx_eq T*ones(BigFloat,5) full(T)*ones(BigFloat,5)\n\n    n = 512\n    r = map(BigFloat,rand(n))\n    T = TriangularToeplitz(r,:L)\n    @test_approx_eq T*ones(BigFloat,n) full(T)*ones(BigFloat,n)\n\n    T = TriangularToeplitz(BigFloat[1,2,3,4,5],:U)\n    @test_approx_eq T*ones(BigFloat,5) full(T)*ones(BigFloat,5)\n\n    n = 512\n    r = map(BigFloat,rand(n))\n    T = TriangularToeplitz(r,:U)\n    @test_approx_eq T*ones(BigFloat,n) full(T)*ones(BigFloat,n)\n    println(\"OK!\")\nend\n\n\nprintln(\"Convert\")\n\nT = Toeplitz(ones(2),ones(2))\n\n@test isa(convert(Matrix{Complex128},T),Matrix{Complex128})\n@test isa(convert(AbstractMatrix{Complex128},T),Toeplitz{Complex128})\n@test isa(convert(AbstractArray{Complex128},T),Toeplitz{Complex128})\n@test isa(convert(ToeplitzMatrices.AbstractToeplitz{Complex128},T),Toeplitz{Complex128})\n@test isa(convert(ToeplitzMatrices.Toeplitz{Complex128},T),Toeplitz{Complex128})\n\nT = SymmetricToeplitz(ones(2))\n\n@test isa(convert(Matrix{Float32},T),Matrix{Float32})\n@test isa(convert(AbstractMatrix{Float32},T),SymmetricToeplitz{Float32})\n@test isa(convert(AbstractArray{Float32},T),SymmetricToeplitz{Float32})\n@test isa(convert(ToeplitzMatrices.AbstractToeplitz{Float32},T),SymmetricToeplitz{Float32})\n@test isa(convert(ToeplitzMatrices.SymmetricToeplitz{Float32},T),SymmetricToeplitz{Float32})\n\nT = Circulant(ones(2))\n\n@test isa(convert(Matrix{Complex128},T),Matrix{Complex128})\n@test isa(convert(AbstractMatrix{Complex128},T),Circulant{Complex128})\n@test isa(convert(AbstractArray{Complex128},T),Circulant{Complex128})\n@test isa(convert(ToeplitzMatrices.AbstractToeplitz{Complex128},T),Circulant{Complex128})\n@test isa(convert(ToeplitzMatrices.Circulant{Complex128},T),Circulant{Complex128})\n\nT = TriangularToeplitz(ones(2),:U)\n\n@test isa(convert(Matrix{Complex128},T),Matrix{Complex128})\n@test isa(convert(AbstractMatrix{Complex128},T),TriangularToeplitz{Complex128})\n@test isa(convert(AbstractArray{Complex128},T),TriangularToeplitz{Complex128})\n@test isa(convert(ToeplitzMatrices.AbstractToeplitz{Complex128},T),TriangularToeplitz{Complex128})\n@test isa(convert(ToeplitzMatrices.TriangularToeplitz{Complex128},T),TriangularToeplitz{Complex128})\n\n\nT = Hankel(ones(2),ones(2))\n\n@test isa(convert(Matrix{Complex128},T),Matrix{Complex128})\n@test isa(convert(AbstractMatrix{Complex128},T),Hankel{Complex128})\n@test isa(convert(AbstractArray{Complex128},T),Hankel{Complex128})\n@test isa(convert(ToeplitzMatrices.Hankel{Complex128},T),Hankel{Complex128})\n", "meta": {"hexsha": "acfb678c8ad0bb23df9100283f0ae6338d8c4dec", "size": 7183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaPackageMirrors/ToeplitzMatrices.jl", "max_stars_repo_head_hexsha": "d26e2c78041af1cfda8d8961e6b93a18a45de4ef", "max_stars_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/ToeplitzMatrices.jl", "max_issues_repo_head_hexsha": "d26e2c78041af1cfda8d8961e6b93a18a45de4ef", "max_issues_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/ToeplitzMatrices.jl", "max_forks_repo_head_hexsha": "d26e2c78041af1cfda8d8961e6b93a18a45de4ef", "max_forks_repo_licenses": ["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.827027027, "max_line_length": 100, "alphanum_fraction": 0.6319086733, "num_tokens": 2536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686199, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7585898787342726}}
{"text": "#RSDeltaSigma: Quantizer functionnality\n#-------------------------------------------------------------------------------\n\n\n#Version from simulateDSM.m\n#-------------------------------------------------------------------------------\n#VERIFYME: Did this one actually get called? Was the other version the one being called??\n\"\"\"`ds_quantize_DSM(y,n)`\n\nQuantize y to:\n - an odd integer in [-n+1, n-1], if n is even, or\n - an even integer in [-n, n], if n is odd.\n\nThis definition gives the same step height for both mid-rise\nand mid-tread quantizers.\n\"\"\"\nfunction ds_quantize_DSM(y, n::Int)\n\tif mod(n,2)==0 #mid-rise quantizer\n\t\tv = 2*floor.(0.5*y) .+ 1\n\telse #mid-tread quantizer\n\t\tv = 2*floor.(0.5*(y .+ 1))\n\tend\n\n\t#Limit the output\n\tfor qi in 1:length(n) #Loop for multiple quantizers\n\t\tL = n[qi]-1\n\t\ti = v[qi,:] .> L\n\t\tif any(i)\n\t\t\tv[qi,i] .= L\n\t\tend\n\t\ti = v[qi,:] .< -L\n\t\tif any(i)\n\t\t\tv[qi,i] .= -L\n\t\tend\n\tend\n\treturn v\nend\n#Pretty sure mod(n,2) code needs to be adapted for Vector:\nds_quantize_DSM(y, n::Vector{Int}) =\n\tthrow(ErrorException(\"ds_quantizer: does not support n::Vector\"))\n\n\n#Version from ds_quantize.m:\n#-------------------------------------------------------------------------------\n#=\nfunction v = ds_quantize(y,n)\n%v = ds_quantize(y,n=2)\n%Quantize y to \n% an odd integer in [-n+1, n-1], if n is even, or\n% an even integer in [-n+1, n-1], if n is odd.\n%This definition gives the same step height for both mid-rise\n%and mid-tread quantizers.\n%n can be a column vector which specifies how to quantize the rows of y\nif nargin<2\n    n=2;\nend\nif length(n)==1\n    n = n*ones(size(y));\nelseif size(n,1)==size(y,1)\n    n = n*ones(1,size(y,2));\nend\n\ni = rem(n,2)==0;\t\nv = zeros(size(y));\nv(i) = 2*floor(0.5*y(i))+1;\t% mid-rise quantizer\nv(~i) = 2*floor(0.5*(y(~i)+1));\t% mid-tread quantizer\n\n% Limit the output\nL = n-1;\nfor m=[-1 1]\n    i = m*v>L;\n    if any(i(:))\n\tv(i) = m*L(i);\n    end\nend\n=#\n\n#Last line\n", "meta": {"hexsha": "ca149d975e84b6df9f989e9eed8b886708f2bbda", "size": 1917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quantizer.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": "src/quantizer.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": "src/quantizer.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": 24.2658227848, "max_line_length": 89, "alphanum_fraction": 0.5545122587, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7585898773521902}}
{"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') = \u03c3\u00b2(1 + \u221a3|x-x'|/\u2113)\\\\exp(-\u221a3|x-x'|/\u2113)\n```\nwith length scale ``\u2113`` and signal standard deviation ``\u03c3``.\n\"\"\"\nmutable struct Mat32Iso{T<:Real} <: MaternIso\n    \"Length scale\"\n    \u2113::T\n    \"Signal variance\"\n    \u03c32::T\n    \"Priors for kernel parameters\"\n    priors::Array\nend\n\n\"\"\"\nMatern 3/2 isotropic covariance function\n    \n    Mat32Iso(ll::T, l\u03c3::T)\n\n# Arguments\n  - `ll::Real`: length scale (given on log scale)\n  - `l\u03c3::Real`: signal standard deviation (given on log scale)  \n\"\"\"\nMat32Iso(ll::T, l\u03c3::T) where T = Mat32Iso{T}(exp(ll), exp(2 * l\u03c3), [])\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.\u2113, mat.\u03c32 = exp(hyp[1]), exp(2 * hyp[2])\nend\n\nget_params(mat::Mat32Iso{T}) where T = T[log(mat.\u2113), log(mat.\u03c32) / 2 ]\nget_param_names(mat::Mat32Iso) = [:ll, :l\u03c3]\nnum_params(mat::Mat32Iso) = 2\n\ncov(mat::Mat32Iso, r::Number) =\n    (s = \u221a3 * r / mat.\u2113; mat.\u03c32 * (1 + s) * exp(-s))\n\n@inline dk_dll(mat::Mat32Iso, r::Real) =\n    (s = \u221a3 * r / mat.\u2113; mat.\u03c32 * 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}, \u03bd::Vector{T}) where {T<:AbstractFloat}\n\tn = length(t)\n\tr = length(\u03bd)\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 \u03b1 \u2208 1:r\n\t\tfor i \u2208 1:n\n\t\t\tV[i,2*\u03b1-1] = cos(\u03c0*\u03bd[\u03b1]*t[i])\n\t\t\tV[i,2*\u03b1  ] = sin(\u03c0*\u03bd[\u03b1]*t[i])\n\t\tend\n\tend\n\treturn V\nend\n\nfunction trigeval(t::Vector{T}, \u03bd::Vector{T}, c::Vector{T}) where {T<:AbstractFloat}\n\tn = length(t)\n\tr = length(\u03bd)\n\tif r == 0\n\t\tthrow(ArgumentError(\"the number of frequencies should be positive\"))\n\tend\n\tif length(c) \u2260 2*r\n\t\tthrow(ArgumentError(\"\u03bd and c are incompatible in size\"))\n\tend\n\tu = zeros(T, length(t))\n\tfor i \u2208 1:n\n\t\tfor \u03b1 \u2208 1:r\n\t\t\tu[i] += c[2*\u03b1-1]*cos(\u03c0*\u03bd[\u03b1]*t[i])+c[2*\u03b1]*sin(\u03c0*\u03bd[\u03b1]*t[i])\n\t\tend\n\tend\n\treturn u\nend\n\nfunction trigrefmask(\u03b7::T, \u03bd::Vector{T}) where {T<:AbstractFloat}\n\tr = length(\u03bd)\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 \u03b1 \u2208 1:r\n\t\tW[2*\u03b1-1,2*\u03b1-1] =  cos(\u03c0*\u03bd[\u03b1]*\u03b7)\n\t\tW[2*\u03b1,  2*\u03b1-1] = -sin(\u03c0*\u03bd[\u03b1]*\u03b7)\n\t\tW[2*\u03b1-1,2*\u03b1  ] =  sin(\u03c0*\u03bd[\u03b1]*\u03b7)\n\t\tW[2*\u03b1,  2*\u03b1  ] =  cos(\u03c0*\u03bd[\u03b1]*\u03b7)\n\tend\n\treturn W\nend\n\nfunction trigrefmask2(\u03bd::Vector{T}) where {T<:AbstractFloat}\n\tr = length(\u03bd)\n\tif r == 0\n\t\tthrow(ArgumentError(\"the number of frequencies should be positive\"))\n\tend\n\tW1 = trigrefmask(convert(T, -1/2), \u03bd)\n\tW2 = trigrefmask(convert(T, 1/2), \u03bd)\n\tW = [W1[:] W2[:]]\n\tW = reshape(W, 2*r, 2*r, 2)\n\treturn W\nend\n\nfunction trigdiffmask(\u03bd::Vector{T}) where {T<:AbstractFloat}\n\tr = length(\u03bd)\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 \u03b1 \u2208 1:r\n\t\tW[2*\u03b1-1,2*\u03b1  ] =  \u03c0*\u03bd[\u03b1]\n\t\tW[2*\u03b1,  2*\u03b1-1] = -\u03c0*\u03bd[\u03b1]\n\tend\n\treturn W\nend\n\nfunction trigdiff(\u03bd::Vector{T}, c::Vector{T}) where {T<:AbstractFloat}\n\tr = length(\u03bd)\n\tif length(c) \u2260 2*r\n\t\tthrow(ArgumentError(\"\u03bd and c are incompatible in size\"))\n\tend\n\td = zeros(T, 2*r)\n\tfor \u03b1 \u2208 1:r\n\t\td[2*\u03b1-1] =  \u03c0*\u03bd[\u03b1]*c[2*\u03b1]\n\t\td[2*\u03b1]   = -\u03c0*\u03bd[\u03b1]*c[2*\u03b1-1]\n\tend\n\treturn d\nend\n\n\nfunction cosfactor(\u03c4::Vector{T}, c::T) where {T<:AbstractFloat}\n\tn = length(\u03c4)\n\tif n == 0\n\t\tthrow(ArgumentError(\"\u03c4 should be nonempty\"))\n\tend\n\tU = zeros(T, 2, n, 2)\n\tfor i \u2208 1:n\n\t\t\u03b1 = c*cos(\u03c4[i])\n\t\t\u03b2 = c*sin(\u03c4[i])\n\t\tU[1,i,1] =  \u03b1\n\t\tU[2,i,1] =  \u03b2\n\t\tU[1,i,2] = -\u03b2\n\t\tU[2,i,2] =  \u03b1\n\tend\n\treturn U\nend\n\nfunction cosdec(\u03c4::Vector{Vector{T}}, c::Vector{T}) where {T<:AbstractFloat}\n\tL = length(\u03c4)\n\tif length(c) \u2260 L\n\t\tthrow(ArgumentError(\"\u03c4 and c should be of the same length\"))\n\tend\n\tn = [ size(\u03c4[\u2113]) for \u2113 \u2208 1:L ]\n\tif any(\u03c4 .== 0)\n\t\tthrow(ArgumentError(\"all elements of \u03c4 should be nonempty\"))\n\tend\n\tU = [ cosfactor(\u03c4[\u2113], c[\u2113]) for \u2113 \u2208 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(\u03bd::Vector{T}, c::Vector{T}, L::Int; major::String=\"last\") where {T<:AbstractFloat}\n\tif major \u2209 (\"first\", \"last\")\n\t\tthrow(ArgumentError(\"major should be either \\\"last\\\" (default) or \\\"first\\\"\"))\n\tend\n\tr = length(\u03bd)\n\tif length(c) \u2260 2*r\n\t\tthrow(ArgumentError(\"\u03bd 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 \u2113 \u2208 1:L\n\t\tU[\u2113+1] = permutedims(trigrefmask2(\u03bd/2^(\u2113-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}, \u03bd::Vector{T}; major::String=\"last\") where {T<:AbstractFloat,N}\n\tif major \u2209 (\"first\", \"last\")\n\t\tthrow(ArgumentError(\"major should be either \\\"last\\\" (default) or \\\"first\\\"\"))\n\tend\n\tif N \u2260 3\n\t\tthrow(ArgumentError(\"only one mode index per factor is currently supported\"))\n\tend\n\tn = length(t)\n\tr = length(\u03bd)\n\tL = declength(U)\n\tp = decrank(U)\n\tp = (major == \"last\") ? p[1] : p[L+1]\n\tif p \u2260 2*r\n\t\tthrow(ArgumentError(\"the \", (major == \"last\") ? \"first\" : \"last\", \" rank of U and the size of \u03bd are incompatible\"))\n\tend\n\tW = trigevalmask(t, \u03bd)\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": "using ForwardDiff\nusing LinearAlgebra\ninclude(\"backtracking_line_search.jl\")\ninclude(\"newton_method.jl\")\ninclude(\"gradient_algorithm_l2.jl\")\ninclude(\"coordinate_algorithm_l1.jl\")\ninclude(\"gradient_algorithm_l2.jl\")\ninclude(\"coordinate_algorithm_l1.jl\")\ndimension = 10 #defult\nepsilon = 0.001 #default\nobjective(x) =  x' * x   #default\nx = rand(dimension) #default, point selection is also an important step\nalpha = 0.1 #default\nbeta = 0.5 #default\nstep = 100 #default\n\n\nx = newton_algo(epsilon,objective,x)\nx = coordinate_algo(dimension,epsilon,objective,x,alpha,beta,step)\n\n\nprint(x) \nprint(objective(x))\n\n#brief readme: rough underestimator. for learning only", "meta": {"hexsha": "9fc02c87bd35fa942941af9062d26b9acb261f47", "size": 661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "descent_method/descent_method_main.jl", "max_stars_repo_name": "zhuhs-q/basic-optimal-method", "max_stars_repo_head_hexsha": "71802dba31c9f1b765f35cba5eca98ac83a90d98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-05T11:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T11:57:07.000Z", "max_issues_repo_path": "descent_method/descent_method_main.jl", "max_issues_repo_name": "Jacob-jinxy/basic-optimal-method", "max_issues_repo_head_hexsha": "f7b3d8ec2a38110ca79d9f83488b894b55ef02cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "descent_method/descent_method_main.jl", "max_forks_repo_name": "Jacob-jinxy/basic-optimal-method", "max_forks_repo_head_hexsha": "f7b3d8ec2a38110ca79d9f83488b894b55ef02cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-05T11:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-05T11:56:39.000Z", "avg_line_length": 26.44, "max_line_length": 71, "alphanum_fraction": 0.7776096823, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8006920116079208, "lm_q1q2_score": 0.7585604383823354}}
{"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    \u03bb::AbstractVector{T}\n    proj::Projection{T}\nend\n\n## properties\noutdim(R::LLE) = size(R.proj, 1)\neigvals(R::LLE) = R.\u03bb\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    \u03bb, V = decompose(M, maxoutdim)\n    return LLE{nntype, T}(NN, C, \u03bb, 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(\u03b1::Float64, \u03b2::Float64) = new(Beta(\u03b1, \u03b2))\n    BetaPrime(\u03b1::Float64) = new(Beta(\u03b1))\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) = ((\u03b1, \u03b2) = params(d); \u03b2 > 1.0 ? \u03b1 / (\u03b2 - 1.0) : NaN)\n\nmode(d::BetaPrime) = ((\u03b1, \u03b2) = params(d); \u03b1 > 1.0 ? (\u03b1 - 1.0) / (\u03b2 + 1.0) : 0.0)\n\nfunction var(d::BetaPrime)\n    (\u03b1, \u03b2) = params(d)\n    \u03b2 > 2.0 ? \u03b1 * (\u03b1 + \u03b2 - 1.0) / ((\u03b2 - 2.0) * (\u03b2 - 1.0)^2) : NaN\nend\n\nfunction skewness(d::BetaPrime)\n    (\u03b1, \u03b2) = params(d)\n    if \u03b2 > 3.0\n        s = \u03b1 + \u03b2 - 1.0\n        2.0 * (\u03b1 + s) / (\u03b2 - 3.0) * sqrt((\u03b2 - 2.0) / (\u03b1 * s))\n    else\n        return NaN\n    end\nend\n\n\n#### Evaluation\n\nfunction logpdf(d::BetaPrime, x::Float64)\n    (\u03b1, \u03b2) = params(d)\n    (\u03b1 - 1.0) * log(x) - (\u03b1 + \u03b2) * log1p(x) - lbeta(\u03b1, \u03b2)\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    (\u03b1, \u03b2) = params(d)\n    rand(Gamma(\u03b1)) / rand(Gamma(\u03b2))\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(\u03b8::Real) = [1 0 0 0; \n        0 cos(\u03b8) -sin(\u03b8) 0; \n        0 sin(\u03b8) cos(\u03b8) 0;\n        0 0 0 1]\n\nRy(\u03b8::Real) = [cos(\u03b8) 0 -sin(\u03b8) 0; \n        0 1 0 0; \n        sin(\u03b8) 0 cos(\u03b8) 0;\n        0 0 0 1]\n\nRz(\u03b8::Real) = [cos(\u03b8) -sin(\u03b8) 0 0;\n        sin(\u03b8) cos(\u03b8) 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\u03c0 = pi\nd = 2\nangToRad(ang::Real) = (\u03c0/180)*ang\n\u03b8(ang::Real = 150) = angToRad(ang) #70\n\u03c9(ang::Real = 160) = angToRad(ang)\n\nB1 = I(4) #nada a fazer\n\n#B2 =  Ry(\u03c0)*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(\u03c0)*Rz(\u03b8())*Ry(\u03c0)*Tx(d)\n\n# tird atom\nc\u03b8,s\u03b8 = (cos(\u03b8()),sin(\u03b8()))\nB3 = zeros(4,4)\nB3[1,1] = -c\u03b8\nB3[1,2] = -s\u03b8\nB3[1,4] = -d*c\u03b8\nB3[2,1] = s\u03b8\nB3[2,2] = -c\u03b8\nB3[2,4] = d*s\u03b8\nB3[3,3] = 1.0\nB3[4,4] = 1.0\n\nfunction torsionmatrix(cos\u03b8,sin\u03b8,cos\u03c9,sin\u03c9,d34,sign::Bool)\n\tif sign == true\n\t\t\n\t\tB=zeros(4,4)\n\t\tB[1,1] = -cos\u03b8\n\t\tB[1,2] = -sin\u03b8\n\t\tB[1,4] = -d34*cos\u03b8\n\t\tB[2,1] = sin\u03b8*cos\u03c9\n\t\tB[2,2] = -cos\u03b8*cos\u03c9\n\t\tB[2,3] = -sin\u03c9\n\t\tB[2,4] = d34*sin\u03b8*cos\u03c9\n\t\tB[3,1] = sin\u03b8*sin\u03c9\n\t\tB[3,2] = -cos\u03b8*sin\u03c9\n\t\tB[3,3] = cos\u03c9\n\t\tB[3,4] = d34*sin\u03b8*sin\u03c9 \n\t\tB[4,4] = 1\n\telse\n\t\t\n\t\tB=zeros(4,4)\n\t\tB[1,1] = -cos\u03b8\n\t\tB[1,2] = -sin\u03b8\n\t\tB[1,4] = -d34*cos\u03b8\n\t\tB[2,1] = sin\u03b8*cos\u03c9\n\t\tB[2,2] = -cos\u03b8*cos\u03c9\n\t\tB[2,3] = sin\u03c9\n\t\tB[2,4] = d34*sin\u03b8*cos\u03c9\n\t\tB[3,1] = -sin\u03b8*sin\u03c9\n\t\tB[3,2] = cos\u03b8*sin\u03c9\n\t\tB[3,3] = cos\u03c9\n\t\tB[3,4] = -d34*sin\u03b8*sin\u03c9 \n\t\tB[4,4] = 1\n\t\t\n\tend\n\treturn B\nend\n\nBi(\u03c9 = \u03c9(), \u03b8 = \u03b8(), d = d) = torsionmatrix(cos(angToRad(\u03b8)), sin(angToRad(\u03b8)), cos(angToRad(\u03c9)), sin(angToRad(\u03c9)), d, false) #Bi(\u03c9 = \u03c9(), \u03b8 = \u03b8(), d = d) = Rx(\u03c9)*Rx(\u03c0)*Rz(\u03b8)*Ry(\u03c0)*Tx(d)\n\nBi\u2032(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, \u03b1 = 1; title = true)\n    if title\n\t\treturn [\"x/|x|\" \"y/|y|\" \"z/|z|\" \"i\"; B*unk*\u03b1]\t\t\n\telse\n\t\treturn B*unk*\u03b1\n\tend\nend\n\nfunction flatProjection(A, x\u0302 = [cos(\u03c0/4) -cos(\u03c0/4)]'*0.5; x :: Bool = true)\n\tif x\n\t\treturn [A[2:3,1]+x\u0302*A[1,1] A[2:3,2]+x\u0302*A[1,2] A[2:3,3]+x\u0302*A[1,3] A[2:3,4]+x\u0302*A[1,4]]\n\telse\n\t\treturn [A[1:2,1]+x\u0302*A[3,1] A[1:2,2]+x\u0302*A[3,2] A[1:2,3]+x\u0302*A[3,3] A[1:2,4]+x\u0302*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(\u03c0/2)*Rx(\u03c0/2)*Rz(-\u03b8(30))*Rx(\u03c0)\n#sysGenerate(flatProjection(rotationFactor*B2*B3*Bi(\u03c9(230),\u03b8(120))), 20)\n#Bo = B2*B3*Bi(\u03c9(230),\u03b8(120))\n#B = Bi(\u03c9(230),\u03b8(120))\n#sysGenerate(flatProjection(rotationFactor*Bo*B*B*B), 20)\n\n# a good initial image \n\n# plotFlatProjection(flatProjection(B1, [-cos(\u03c0/4) -cos(\u03c0/4)]'*0.707))\n# plotFlatProjection(flatProjection(B1*Ry(\u03c0)*Tx(2.5), [-cos(\u03c0/4) -cos(\u03c0/4)]'*0.707), static = true)\n# plotFlatProjection(flatProjection(B1*B2*Rx(\u03c0)*Rz(\u03b8(75))*Ry(\u03c0)*Tx(2.5), [-cos(\u03c0/4) -cos(\u03c0/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": "# This file includes coding methods to map bit streams into symbol streams \n\nexport GrayCoding, invmap\n\nabstract type AbstractCoding end\n\n\"\"\" \n    $TYPEDEF \n\nGray coding. \n\n# Fields\n    $TYPEDFIELDS\n\n# Example\n```julia \njulia> gc = GrayCoding(2) \nGrayCoding(Dict([0, 1] => 2,[1, 1] => 3,[0, 0] => 1,[1, 0] => 4))\n```\n\"\"\"\nstruct GrayCoding <: AbstractCoding \n    pairs::Dict{Vector{Int}, Int}\n    function GrayCoding(M::Int)\n        ispow2(M) || throw(ArgumentError(\"Expected `M` to be a power of 2, got $M instead\"))\n        k = Int(log2(M))\n        m = 0 : 1 << k - 1\n        codes = m .\u22bb (m .>> 1)\n        codes = reverse.(digits.(codes, base=2, pad=k))\n        new(Dict(zip(codes, m .+ 1)))\n    end\nend \n\nshow(io::IO, coding::GrayCoding) = print(io, \"GrayCoding(M:$(length(coding.pairs)))\")\n\n# When a GrayCoding object is called, it maps its input bit stream to coressponding symbol stream.\nfunction (coding::GrayCoding)(stream)\n    codewords = collect(Iterators.partition(stream, Int(log2(constelsize(coding)))))\n    alph = coding.pairs\n    map(codewords) do codeword \n        alph[codeword]\n    end\nend \n\n\"\"\"\n    $SIGNATURES \n\nReturns constellation size of the coding.\n\"\"\"\nconstelsize(coding::GrayCoding) = length(coding.pairs)\n\n\"\"\"\n    $SIGNATURES\n\nReturns the inverse of the mapping. Inverse mapping maps the levels to bit chunks. \n\n# Example\n```julia \njulia> gray = GrayCoding(3)\nGrayCoding(Dict([0, 1, 1] => 3,[0, 0, 1] => 2,[1, 1, 0] => 5,[0, 0, 0] => 1,[1, 0, 0] => 8,[1, 0, 1] => 7,[0, 1, 0] => 4,[1, 1, 1] => 6))\n\njulia> invmap(gray)\nDict{Int64,Array{Int64,1}} with 8 entries:\n  7 => [1, 0, 1]\n  4 => [0, 1, 0]\n  2 => [0, 0, 1]\n  3 => [0, 1, 1]\n  5 => [1, 1, 0]\n  8 => [1, 0, 0]\n  6 => [1, 1, 1]\n  1 => [0, 0, 0]\n```\n\"\"\"\ninvmap(coding::AbstractCoding) = Dict([(v, k) for (k, v) in coding.pairs])\n", "meta": {"hexsha": "3d4c3dcb3dae160ceafcec0fd24e0927c8117af3", "size": 1809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coding.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": "src/coding.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": "src/coding.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": 24.4459459459, "max_line_length": 137, "alphanum_fraction": 0.5914870094, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7585397951483992}}
{"text": "@testset \"Matrix multiplication\" begin\n    @testset \"Matrix-vector\" begin\n        m = @SMatrix [1 2; 3 4]\n        v = @SVector [1, 2]\n        @test m*v === @SVector [5, 11]\n        # More complicated eltype inference\n        v = @SVector [CartesianIndex((1,3)), CartesianIndex((3,1))]\n        x = @inferred(m*v)\n        @test isa(x, SVector{2,CartesianIndex{2}})\n        @test x == @SVector [CartesianIndex((7,5)), CartesianIndex((15,13))]\n\n        m = @MMatrix [1 2; 3 4]\n        v = @MVector [1, 2]\n        @test (m*v)::MVector == @MVector [5, 11]\n\n        m = @SArray [1 2; 3 4]\n        v = @SArray [1, 2]\n        @test m*v === @SArray [5, 11]\n\n        m = @MArray [1 2; 3 4]\n        v = @MArray [1, 2]\n        @test (m*v)::MArray == @MArray [5, 11]\n    end\n\n    @testset \"Vector-matrix\" begin\n        m = @SMatrix [1 2 3 4]\n        v = @SVector [1, 2]\n        @test v*m === @SMatrix [1 2 3 4; 2 4 6 8]\n    end\n\n    @testset \"Matrix-matrix\" begin\n        m = @SMatrix [1 2; 3 4]\n        n = @SMatrix [2 3; 4 5]\n        nc = @SMatrix [CartesianIndex((2,2)) CartesianIndex((3,3));\n                       CartesianIndex((4,4)) CartesianIndex((5,5))]\n        @test m*n  === @SMatrix [10 13; 22 29]\n        @test m*nc === @SMatrix [CartesianIndex((10,10)) CartesianIndex((13,13));\n                                 CartesianIndex((22,22)) CartesianIndex((29,29))]\n\n        @test m'*n === @SMatrix [14 18; 20 26]\n        @test m*n' === @SMatrix [8 14; 18 32]\n        @test m'*n' === @SMatrix [11 19; 16 28]\n        @test m.'*n === @SMatrix [14 18; 20 26]\n        @test m*n.' === @SMatrix [8 14; 18 32]\n        @test m.'*n.' === @SMatrix [11 19; 16 28]\n\n        m = @MMatrix [1 2; 3 4]\n        n = @MMatrix [2 3; 4 5]\n        @test (m*n)::MMatrix == @MMatrix [10 13; 22 29]\n\n        m = @SArray [1 2; 3 4]\n        n = @SArray [2 3; 4 5]\n        @test m*n === @SArray [10 13; 22 29]\n\n        m = @MArray [1 2; 3 4]\n        n = @MArray [2 3; 4 5]\n        @test (m*n)::MArray == @MArray [10 13; 22 29]\n\n        # Alternative methods used between 8 < n <= 14 and n > 14\n        m_array = rand(1:10, 10, 10)\n        n_array = rand(1:10, 10, 10)\n        a_array = m_array*n_array\n\n        m = SMatrix{10,10}(m_array)\n        n = SMatrix{10,10}(n_array)\n        @test m*n === SMatrix{10,10}(a_array)\n\n        m_array = rand(1:10, 16, 16)\n        n_array = rand(1:10, 16, 16)\n        a_array = m_array*n_array\n\n        m = SMatrix{16,16}(m_array)\n        n = SMatrix{16,16}(n_array)\n        @test m*n === SMatrix{16,16}(a_array)\n\n        # Mutating types follow different behaviour\n        m_array = rand(1:10, 10, 10)\n        n_array = rand(1:10, 10, 10)\n        a_array = m_array*n_array\n\n        m = MMatrix{10,10}(m_array)\n        n = MMatrix{10,10}(n_array)\n        @test (m*n)::MMatrix == a_array\n\n        m_array = rand(1:10, 16, 16)\n        n_array = rand(1:10, 16, 16)\n        a_array = m_array*n_array\n\n        m = MMatrix{16,16}(m_array)\n        n = MMatrix{16,16}(n_array)\n        @test (m*n)::MMatrix == a_array\n\n        # Mutating BLAS types follow yet different behaviour\n        m_array = randn(4, 4)\n        n_array = randn(4, 4)\n        a_array = m_array*n_array\n\n        m = MMatrix{4,4}(m_array)\n        n = MMatrix{4,4}(n_array)\n        @test m*n::MMatrix \u2248 a_array\n\n        m_array = randn(10, 10)\n        n_array = randn(10, 10)\n        a_array = m_array*n_array\n\n        m = MMatrix{10,10}(m_array)\n        n = MMatrix{10,10}(n_array)\n        @test m*n::MMatrix \u2248 a_array\n\n        m_array = randn(16, 16)\n        n_array = randn(16, 16)\n        a_array = m_array*n_array\n\n        m = MMatrix{16,16}(m_array)\n        n = MMatrix{16,16}(n_array)\n        @test m*n::MMatrix \u2248 a_array\n    end\n\n    @testset \"A_mul_B!\" begin\n        m = @SMatrix [1 2; 3 4]\n        n = @SMatrix [2 3; 4 5]\n\n        a = MMatrix{2,2,Int,4}()\n        A_mul_B!(a, m, n)\n        @test a::MMatrix{2,2,Int,4} == @MMatrix [10 13; 22 29]\n\n        Ac_mul_B!(a, m, n)\n        @test a::MMatrix{2,2,Int,4} == @MMatrix [14 18; 20 26]\n        A_mul_Bc!(a, m, n)\n        @test a::MMatrix{2,2,Int,4} == @MMatrix [8 14; 18 32]\n        Ac_mul_Bc!(a, m, n)\n        @test a::MMatrix{2,2,Int,4} == @MMatrix [11 19; 16 28]\n        At_mul_B!(a, m, n)\n        @test a::MMatrix{2,2,Int,4} == @MMatrix [14 18; 20 26]\n        A_mul_Bt!(a, m, n)\n        @test a::MMatrix{2,2,Int,4} == @MMatrix [8 14; 18 32]\n        At_mul_Bt!(a, m, n)\n        @test a::MMatrix{2,2,Int,4} == @MMatrix [11 19; 16 28]\n\n        a2 = MArray{(2,2),Int,2,4}()\n        A_mul_B!(a2, m, n)\n        @test a2::MArray{(2,2),Int,2,4} == @MArray [10 13; 22 29]\n\n        # Alternative builtin method used for n > 8\n        m_array = rand(1:10, 10, 10)\n        n_array = rand(1:10, 10, 10)\n        a_array = m_array*n_array\n\n        m = MMatrix{10,10}(m_array)\n        n = MMatrix{10,10}(n_array)\n        a = MMatrix{10,10,Int}()\n        A_mul_B!(a, m, n)\n        @test a == a_array\n\n        # BLAS used for n > 14\n        m_array = randn(4, 4)\n        n_array = randn(4, 4)\n        a_array = m_array*n_array\n\n        m = MMatrix{4,4}(m_array)\n        n = MMatrix{4,4}(n_array)\n        a = MMatrix{4,4,Float64}()\n        A_mul_B!(a, m, n)\n        @test a \u2248 a_array\n\n        m_array = randn(10, 10)\n        n_array = randn(10, 10)\n        a_array = m_array*n_array\n\n        m = MMatrix{10,10}(m_array)\n        n = MMatrix{10,10}(n_array)\n        a = MMatrix{10,10,Float64}()\n        A_mul_B!(a, m, n)\n        @test a \u2248 a_array\n\n        m_array = rand(1:10, 16, 16)\n        n_array = rand(1:10, 16, 16)\n        a_array = m_array*n_array\n\n        m = MMatrix{16,16}(m_array)\n        n = MMatrix{16,16}(n_array)\n        a = MMatrix{16,16,Int}()\n        A_mul_B!(a, m, n)\n        @test a \u2248 a_array\n    end\nend\n", "meta": {"hexsha": "95f3838389a1bf5102874d565aab218f81d1dc24", "size": 5732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/matrix_multiply.jl", "max_stars_repo_name": "JuliaPackageMirrors/StaticArrays.jl", "max_stars_repo_head_hexsha": "c453f137c163fa435659b263d8af8e6f87f07d42", "max_stars_repo_licenses": ["MIT"], "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/matrix_multiply.jl", "max_issues_repo_name": "JuliaPackageMirrors/StaticArrays.jl", "max_issues_repo_head_hexsha": "c453f137c163fa435659b263d8af8e6f87f07d42", "max_issues_repo_licenses": ["MIT"], "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/matrix_multiply.jl", "max_forks_repo_name": "JuliaPackageMirrors/StaticArrays.jl", "max_forks_repo_head_hexsha": "c453f137c163fa435659b263d8af8e6f87f07d42", "max_forks_repo_licenses": ["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.6524064171, "max_line_length": 81, "alphanum_fraction": 0.4972086532, "num_tokens": 2181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7585397904551269}}
{"text": "# Define and register smooth functions\n_cos_wave(t, f, A, st, \u03d5) = A*cos(2*\u03c0*f*(t - st) + \u03d5)\n_sin_wave(t, f, A, st, \u03d5) = A*sin(2*\u03c0*f*(t - st) + \u03d5)\n_damped_sine_wave(t, f, A, st, \u03d5, d) = exp((st-t)*d)*A*sin(2*\u03c0*f*(t-st) + \u03d5)\n_ramp(t, \u03b4, st, et, h) = h/(et-st)*(_xH(t, \u03b4, st) - _xH(t, \u03b4, et))\n_square_wave(t, \u03b4, f, A, st) = A*2atan(sin(2\u03c0*(t-st)*f)/\u03b4)/\u03c0\n_step(t, \u03b4, h, a) = h*(atan((t-a)/\u03b4)/\u03c0 + 0.5)\n_triangular_wave(t, \u03b4, f, A, st) = A*(1-2acos((1 - \u03b4)sin(2\u03c0*(t-st)*f))/\u03c0)\n_xH(t, \u03b4, t\u2092) = (t-t\u2092)*(1+((t-t\u2092)/sqrt((t-t\u2092)^2+\u03b4^2)))/2\n\n@register_symbolic _cos_wave(t, f, A, st, \u03d5)\n@register_symbolic _sin_wave(t, f, A, st, \u03d5)\n@register_symbolic _damped_sine_wave(t, f, A, st, \u03d5, damping)\n@register_symbolic _ramp(t, \u03b4, st, et, h)\n@register_symbolic _square_wave(t, \u03b4, f, A, st)\n@register_symbolic _step(t, \u03b4, h, a)\n@register_symbolic _triangular_wave(t, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, frequency, amplitude, start_time) * _step(t, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, frequency, amplitude, start_time) * _step(t, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, frequency, amplitude, start_time) * _step(t, \u03b4, 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    \u03b4 = 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, \u03b4, 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    \u03b4 = 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, \u03b4, frequency, amplitude, start_time) * _step(t, \u03b4, 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 \u00b11.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": "using MLJ\nusing PrettyPrinting\nimport DataFrames\nimport Statistics\nusing PyPlot\nusing StableRNGs\n\nLGBMRegressor = @load LGBMRegressor\n\nfeatures, targets = @load_boston\nfeatures = DataFrames.DataFrame(features)\n@show size(features)\n@show targets[1:3]\nfirst(features, 3) |> pretty\n\nDataFrames.describe(features)\n\ntrain, test = partition(collect(eachindex(targets)), 0.70, shuffle=true,\n                        rng=StableRNG(52))\n\nlgb = LGBMRegressor() #initialised a model with default params\nlgbm = machine(lgb, features[train, :], targets[train, 1])\nboostrange = range(lgb, :num_iterations, lower=2, upper=500)\ncurve = learning_curve!(lgbm, resampling=CV(nfolds=5),\n                        range=boostrange, resolution=100,\n                        measure=rms)\n\n\nfigure(figsize=(8,6))\nplot(curve.parameter_values, curve.measurements)\nxlabel(\"Number of rounds\", fontsize=14)\nylabel(\"RMSE\", fontsize=14)\n\nlgb = LGBMRegressor() #initialised a model with default params\nlgbm = machine(lgb, features[train, :], targets[train, 1])\nlearning_range = range(lgb, :learning_rate, lower=1e-3, upper=1, scale=:log)\ncurve = learning_curve!(lgbm, resampling=CV(nfolds=5),\n                        range=learning_range, resolution=100,\n                        measure=rms)\n\n\nfigure(figsize=(8,6))\nplot(curve.parameter_values, curve.measurements)\nxscale(\"log\")\nxlabel(\"Learning rate (log scale)\", fontsize=14)\nylabel(\"RMSE\", fontsize=14)\n\nlgb = LGBMRegressor() #initialised a model with default params\nlgbm = machine(lgb, features[train, :], targets[train, 1])\n\nleaf_range = range(lgb, :min_data_in_leaf, lower=1, upper=50)\n\n\ncurve = learning_curve!(lgbm, resampling=CV(nfolds=5),\n                        range=leaf_range, resolution=50,\n                        measure=rms)\n\nfigure(figsize=(8,6))\nplot(curve.parameter_values, curve.measurements)\nxlabel(\"Min data in leaf\", fontsize=14)\nylabel(\"RMSE\", fontsize=14)\n\nr1 = range(lgb, :num_iterations, lower=50, upper=100)\nr2 = range(lgb, :min_data_in_leaf, lower=2, upper=10)\nr3 = range(lgb, :learning_rate, lower=1e-1, upper=1e0)\ntm = TunedModel(model=lgb, tuning=Grid(resolution=5),\n                resampling=CV(rng=StableRNG(123)), ranges=[r1,r2,r3],\n                measure=rms)\nmtm = machine(tm, features, targets)\nfit!(mtm, rows=train);\n\nbest_model = fitted_params(mtm).best_model\n@show best_model.learning_rate\n@show best_model.min_data_in_leaf\n@show best_model.num_iterations\n\npredictions = MLJ.predict(mtm, rows=test)\nrms_score = round(rms(predictions, targets[test, 1]), sigdigits=4)\n\n@show rms_score\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "0329b3dc6731b70c6fd326cb76b505ea72f20e0a", "size": 2632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__site/__generated/EX-boston-lgbm/tutorial-raw.jl", "max_stars_repo_name": "JuliaAI/DataScienceTutorials.jl", "max_stars_repo_head_hexsha": "76b1d3d1a5045c62b104a8358e4c37049f15ccb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-08-09T11:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:20:43.000Z", "max_issues_repo_path": "__site/__generated/EX-boston-lgbm/tutorial-raw.jl", "max_issues_repo_name": "alan-turing-institute/MLJTutorials", "max_issues_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-10-22T00:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T14:38:09.000Z", "max_forks_repo_path": "__site/__generated/EX-boston-lgbm/tutorial-raw.jl", "max_forks_repo_name": "alan-turing-institute/MLJTutorials", "max_forks_repo_head_hexsha": "f1613ac8968fceee0e4fe43d1fdb5b58c8a84bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-11-20T16:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T11:55:15.000Z", "avg_line_length": 31.3333333333, "max_line_length": 87, "alphanum_fraction": 0.7040273556, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8397339616560073, "lm_q1q2_score": 0.758526829294721}}
{"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    \u03b4 = 1/32 # start with 31 points (32 intervals between 0 and 1)\n    p = \u03b4:\u03b4:(1-\u03b4)\n    # for K=1/\u03b4 intervals, there are (K-1) points at c_i\n    # The first points at \u03b4 represents interval (\u03b4/2,3/2\u03b4)\n    # The following picture shows points and intervals for K = 4\n    #---|---|---|---#\n    # |---|---|---| #\n    # we need to add points for \u03b4/4 and 1-\u03b4/4 representing the edges\n    # but their weight is only half, because they represents half an inverval\n    #m = sum(c_i*\u03b4) + el*(\u03b4/2) + er*(\u03b4/2) = (sum(c_i) + er/2 + el/2)*\u03b4\n    s = sum(fun.(d,p))   # sum at points c_i\n    el = fun(d,\u03b4/4)  # \n    er = fun(d,1-\u03b4/4)\n    m = (s + el/2 + er/2)*\u03b4\n    relErr = 1\n    while 1/\u03b4 < maxCnt\n        mPrev = m\n        \u03b4  = \u03b4 / 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 = \u03b4:\u03b4*2:(1-\u03b4) # points at the center of current intervals\n        s += sum(fun.(d,p))\n        el = fun(d,\u03b4/4)\n        er = fun(d,1-\u03b4/4)\n        m = (s + el/2 + er/2)*\u03b4\n        relErr = abs(m - mPrev)/m \n        #println(\"cnt=$(1/\u03b4), 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 / \u221a2, 1 / \u221a2\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) \u00f7 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] \u2264 length(x)\u00f73 && 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 `\u03b5` from a Dataset\n#####################################################################################\n\"\"\"\n    estimate_boxsizes(A::Dataset; kwargs...) \u2192 \u03b5s\nReturn `k` exponentially spaced values: `\u03b5s = base .^ range(lower + w, upper + z; length = k)`,\nthat are a good estimate for sizes \u03b5 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\u208b` be the minimum pair-wise distance in `A` and `d\u208a` the average total length of `A`\nalong each of the dimensions of `A`.\nThen `lower = log(base, d\u208b)` and `upper = log(base, d\u208a)`.\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\u208a/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 \u2265 upper\n        error(\"`lower \u2265 upper`. There must be something fundamentally wrong with dataset.\")\n    elseif lower+w \u2265 upper+z && warning\n        @warn(\n        \"Automatic boxsize determination was inappropriate: `lower+w` was found \u2265 than \"*\n        \"`upper+z`. Returning `base .^ range(lower, upper; length = k)`. \"*\n        \"Please adjust keywords or provide a bigger dataset.\")\n        \u03b5s = 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        \u03b5s = float(base) .^ range(lower+w-we, upper+z-ze; length = k)\n    else\n        \u03b5s = float(base) .^ range(lower+w, upper+z; length = k)\n    end\n    return \u03b5s\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  \u221e = 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 \u2208 1:n\n    m[i,i] = 0\n  end\n  # l is chain length\n  for l \u2208 2:n\n    for i \u2208 1:(n-l+1)\n      j = i + l - 1\n      m[i,j] = \u221e  # this should be replaced?!\n      for k \u2208 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\u00e1ceres (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)\u00f72)])\n        a2 = Polynomial(a.terms[(length(a.terms)\u00f72)+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)\u00f72)])\n        b2 = Polynomial(b.terms[(length(b.terms)\u00f72)+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 \u00f7 a)*s, s\nend\n\nsmod(a::Int,m::Int)::Int = mod(a,m) > m \u00f7 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": "using Test, FinancialMonteCarlo;\n@show \"Black Scholes Model\"\nS0 = 100.0;\nK = 100.0;\nr = 0.02;\nT = 1.0;\nd = 0.01;\nD = 90.0;\n\nNsim = 10000;\nNstep = 30;\nsigma = 0.2;\nmc = MonteCarloConfiguration(Nsim, Nstep);\nmc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());\ntoll = 0.8\n\nrfCurve = ZeroRate(r);\n\nFwdData = Forward(T)\nEUData = EuropeanOption(T, K)\nEUBin = BinaryEuropeanOption(T, K)\nAMData = AmericanOption(T, K)\nAmBin = BinaryEuropeanOption(T, K)\nBarrierData = BarrierOptionDownOut(T, K, D)\nAsianFloatingStrikeData = AsianFloatingStrikeOption(T)\nAsianFixedStrikeData = AsianFixedStrikeOption(T, K)\nModel = BlackScholesProcess(sigma, Underlying(S0, d));\n\ndisplay(Model)\nST = FinancialMonteCarlo.distribution(Model, rfCurve, mc, T);\n@show FwdPrice = exp(-r * T) * sum(ST) / length(ST);\n\n@test abs(FwdPrice - 99.1078451563562) < toll\n", "meta": {"hexsha": "adccf980df5b6988ee3da7a1cb03863cf77e7522", "size": 857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_distribution.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": "test/test_distribution.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": "test/test_distribution.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": 25.2058823529, "max_line_length": 79, "alphanum_fraction": 0.7304550758, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7584810004695599}}
{"text": "# https://adventofcode.com/2020/day/5\n\n# Instead of zones or groups, this airline uses binary space partitioning to seat people.\n# A seat might be specified like FBFBBFFRLR, where F means \"front\", B means \"back\", L\n# means \"left\", and R means \"right\".\n#\n# The first 7 characters will either be F or B; these specify exactly one of the 128 rows\n# on the plane (numbered 0 through 127). Each letter tells you which half of a region the\n# given seat is in. Start with the whole list of rows; the first letter indicates whether\n# the seat is in the front (0 through 63) or the back (64 through 127). The next letter\n# indicates which half of that region the seat is in, and so on until you're left with\n# exactly one row.\n#\n# For example, consider just the first seven characters of FBFBBFFRLR:\n#\n#   Start by considering the whole range, rows 0 through 127.\n#   F means to take the lower half, keeping rows 0 through 63.\n#   B means to take the upper half, keeping rows 32 through 63.\n#   F means to take the lower half, keeping rows 32 through 47.\n#   B means to take the upper half, keeping rows 40 through 47.\n#   B keeps rows 44 through 47.\n#   F keeps rows 44 through 45.\n#   The final F keeps the lower of the two, row 44.\n\nfunction code_to_int(code)\n    code = replace(code, r\"F|L\" => '0')\n    code = replace(code, r\"B|R\" => '1')\n    return parse(Int, code, base=2)\nend\n\n@assert code_to_int(\"BFFFBBFRRR\") == 567\n@assert code_to_int(\"FFFBBBFRRR\") == 119\n@assert code_to_int(\"BBFFBBFRLL\") == 820\n@assert code_to_int(\"FFFFFFFFLL\") == 0\n@assert code_to_int(\"BBBBBBBBRR\") == 1023\n\nfunction part1(codes)\n    highest = 0\n    for code in split(codes, '\\n', keepempty=false)\n        highest = max(highest, code_to_int(code))\n    end\n    return highest\nend\n\nexample = \"\nFFFBBFFFLL\nBFFBBFBBRR\nBBBBBBBBRR\nFFFFFFFFLL\n\"\n\n@assert part1(example) == 1023\n\nfunction find_missing(numbers)\n    return findfirst(diff(numbers) .> 1)\nend\n\n@assert find_missing([1, 2, 3, 4, 6, 7, 8]) == 4\n\nfunction part2(codes)\n    seat_numbers = sort([code_to_int(code) for code in split(codes, '\\n', keepempty=false)])\n    idx = find_missing(seat_numbers)\n    return seat_numbers[idx] + 1\nend\n\ntest = read(\"data/day-05.txt\", String)\nprintln(\"Part 1: $(result1 = part1(test))\")\nprintln(\"Part 2: $(result2 = part2(test))\")\n\n@assert result1 == 913\n@assert result2 == 717\n", "meta": {"hexsha": "75d0eb057ea7f1c6b9636309641a79e8e2c96f62", "size": 2334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/day-05.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-05.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-05.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": 32.4166666667, "max_line_length": 92, "alphanum_fraction": 0.704798629, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7583969054503519}}
{"text": "using BCBIStats.COOccur\nusing StatsBase\n\n#Co-occurrence matrix\noccur_file = \"/Users/isa/Dropbox/BrownAgain/Projects/BCBI/test/occur_sp.jdl\"\nlabels_file = \"/Users/isa/Dropbox/BrownAgain/Projects/BCBI/test/mesh2ind.jdl\"\n\n#Contingency\nx=[1,0,0,1,0,1,1,0,0,1,0,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,0,0,1,0,1]\ny=[1,1,1,0,0,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,0,0]\n\noccur = [x y]\nlabel2ind = Dict(\"x\" => 1, \"y\" => 2)\n\ntry\n  global occur = read_sp_occur(occur_file)\n  global label2ind = read_occur_label_dict(labels_file)\ncatch\n  nothing\nend\n\nCOO = occur2coo(occur, label2ind)\n\ncorr = corrcoef(occur)\npmi = pmi_mat(COO.coo_matrix, sum(occur))\n\n\n\nd = counts(x,y, span(occur))\nstat = chi2_statistic(x,y,span(occur))\n@test isapprox(stat,  0.4057853910795092)\nstat = chi2_statistic(d)\n@test isapprox(stat, 0.4057853910795092)\nstat = chi2_statistic(d, min_freq=6)\n@test isnan(stat)\n", "meta": {"hexsha": "fdc67cf99d7307df627d2e10363e5971025c99cf", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cooccur.jl", "max_stars_repo_name": "bcbi/BCBIStats", "max_stars_repo_head_hexsha": "8b7403585aa759247338379e1a57735e4c33f503", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-12-01T01:35:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-30T08:31:28.000Z", "max_issues_repo_path": "test/cooccur.jl", "max_issues_repo_name": "bcbi/BCBIStats", "max_issues_repo_head_hexsha": "8b7403585aa759247338379e1a57735e4c33f503", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-01T13:48:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-06T14:45:52.000Z", "max_forks_repo_path": "test/cooccur.jl", "max_forks_repo_name": "bcbi/BCBIStats", "max_forks_repo_head_hexsha": "8b7403585aa759247338379e1a57735e4c33f503", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:22:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:22:51.000Z", "avg_line_length": 24.3055555556, "max_line_length": 77, "alphanum_fraction": 0.712, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.7583969015645209}}
{"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": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) \u2209 LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\nmodule LahNumbers\n\nusing Nemo\nexport Lah, LahTriangle\n\n\"\"\"\n\n* Posets: Partially ordered sets (posets) on n elements that consist entirely of k chains (nonempty, linearly ordered subsets).\n\n* Set partitions: Number of ways to split {1,..,n} into an ordered collection of n+1-k nonempty sets that are noncrossing).\n\n* Dyck paths: Dyck n-paths with n+1-k peaks labeled 1,2,..n+1-k in some order.\n\nSee [Lah numbers] (http://olms.onl/Lah/)\n\n* Lah, LahTriangle\n\"\"\"\nconst ModuleLah = \"\"\n\n\"\"\"\n\nReturn the ``n``-th row of the Lah number triangle.\n\"\"\"\nfunction Lah(n)\n    haskey(CacheLah, n) && return CacheLah[n]\n    prevrow = Lah(n-1)\n    row = Array{fmpz,1}(undef, n+1)\n    row[1] = ZZ(0); row[n+1] = ZZ(1)\n    for k in 2:n\n        row[k] = prevrow[k-1] + prevrow[k]*(n+k-2)\n    end\n    CacheLah[n] = row\nend\n\nconst CacheLah = Dict{Int, Array{fmpz,1}}([0 => [fmpz(1)]])\n\n\"\"\"\n\nReturn the ``k``-th term of the ``n``-th row of the Lah number triangle.\n\"\"\"\nLah(n, k) = Lah(n+1)[k+1]\n\n\"\"\"\n\nReturn the unsigned Lah number triangle. (A271703)\n\"\"\"\nfunction LahTriangle(size)\n    length(CacheLah) < size && Lah(size)\n    [CacheLah[n] for n in 0:size-1]\nend\n\n#START-TEST-########################################################\n\nusing Test\n\nSum(itr)     = isempty(itr) ? 0 : sum(itr)\nRowSum(T)    = [Sum(row) for row in T]\nEvenSum(T)   = [Sum(R[r] for r in 1:2:length(R)) for R in T]\nOddSum(T)    = [Sum(R[r] for r in 2:2:length(R)) for R in T]\nAltrowSum(T) = EvenSum(T) - OddSum(T)\n\nfunction test()\n    @testset \"Lah\" begin\n        @test Lah(7) == [0, 5040, 15120, 12600, 4200, 630, 42, 1]\n    end\nend\n\nfunction demo()\n    Lah(7) |> println\n    typeof(Lah(7)) |> println\n    LahTriangle(7) |> println\n    typeof(LahTriangle(7)) |> println\nend\n\nfunction perf()\n    @time Lah(1000)\n    @time RowSum(LahTriangle(1000))\nend\n\nfunction main()\n    test()\n    demo()\n    perf()\nend\n\nmain()\n\nend # module\n", "meta": {"hexsha": "be62f5ffd4ec2bc47156b676e2d5d6521aaa0410", "size": 2021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LahNumbers.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/LahNumbers.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/LahNumbers.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.5, "max_line_length": 127, "alphanum_fraction": 0.611083622, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7583649733739789}}
{"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": "using Optim\nusing ODEOpt\nusing ODE\nusing PyPlot\nusing Base.Test\nusing NLsolve\nusing ForwardDiff\nPLOT = true\nlet\n    ystart = [0.0;1.0]\n    trange = linspace(0,2\u03c0,100)\n    a, b, c = 1.0, 2.0, 3.0\n    foo = secondorder(a,b,c)\n    @test foo(0,[0;1]) == [1.0;-2.0]\nend\n\nlet\n    # Test based on the example at\n    # http://www.sosmath.com/diffeq/second/constantcof/constantcof.html\n    #\n    #     x'' + 2x' + 2x = 0\n    #     x(\u03c0/4) = 2; x'(\u03c0/4) = -2\n    #\n    #     convert to first order using the system\n    #     y[1] = x; y[2] = x'\n    #\n    #     descretize at linspace(\u03c0/4,2\u03c0,100)\n    #\n    # solve the ode numerically then plug into the formulas to\n    # check that the formulas match the ode45 solution.\n    ystart = [2.0;-2.0]\n    trange = linspace(\u03c0/4,2\u03c0,100)\n    a, b, c = 1.0, 2.0, 2.0\n    foo  = secondorder(a,b,c)\n    sol = solve45(foo, ystart, collect(trange))\n    result, formula, deriv = ivp(a,b,c, ystart, \u03c0/4)\n    @show params = result.zero\n    @show result.trace\n    @show result\n    # figure()\n    # test that the computed solution matches the formula\n    form = [formula(t,params...) for t in sol.time]\n    deri = [deriv(t,params...) for t in sol.time]\n    @test norm(form-[y[1] for y in sol.y]) <= 1e-3\n    @test norm(deri-[y[2] for y in sol.y]) <= 1e-3\n    # plot general solution.\n    if PLOT\n        plot(sol.time, form, label=\"formula\")\n        plot(sol.time, deri, label=\"f'\")\n        title(\"parameter fitting \\$ $a \\\\ddot{x} + $b \\\\dot{x} + $c x = 0\\$\") \n        solutionplot(sol)\n    end\nend\n\nlet\n    # parameter fitting for 2nd order linear ode\n    # the equation is ax'' + bx' + cx = 0\n    # we want to recover the coefficients a,b,c as well as the initial values x\u2080,v\u2080\n    # generate \"exact\" solution\n    info(\"Testing Parameter Fitting\")\n    ystart = [2.0;-2.0]\n    trange = linspace(\u03c0/4,2\u03c0,100)\n    a, b, c = 1.0, 2.0, 2.0\n    params = [a,b,c]\n    # initial parameter guess must be fairly close to avoid local optima\n    param\u2080 = 1.5*ones(3)\n    #param\u2080 = params .+ randn(3)/5\n\n    foo  = secondorder(a,b,c)\n    sol = solve45(foo, ystart, collect(trange))\n    result, formula, deriv = ivp(a,b,c, ystart, \u03c0/4)\n    consts = result.zero\n    form = Float64[formula(t,consts...) for t in sol.time]\n    deri = Float64[deriv(t,consts...) for t in sol.time]\n    \n    # add noise to get data as if measured\n    srand(1)\n    noisev = 0.10 * randn(length(form))\n    data = form .+ noisev\n    # x = [y[1] for y in sol.y] \n    # make sure the soserror matches the norm of the measurement noise.\n    # @show sqrt(soserr(sol.time,form, sol.time, data)) norm(noisev) 1e-2\n    tsolve_opt, x\u207a_opt, v_opt, d\u00b2_opt = obj(foo, ystart, sol.time, data)\n    @test_approx_eq_eps sqrt(d\u00b2_opt) norm(noisev) 1e-2\n\n    # fit the parameters to the data \n    @show param\u2080\n    \u03b3(x) = sqrt(obj(secondorder(x...), ystart, sol.time, data)[end])\n    @show res = optimize(\u03b3,\n                         param\u2080,\n                         xtol=1e-12,\n                         ftol=1e-32,\n                         method=ConjugateGradient(),\n                         #method=GradientDescent(),\n                         #method=LBFGS(),\n                         autodiff=false,\n                         show_trace=true,\n                         iterations=1000,\n                         )\n    # report the quality of the fit\n    @show param\u207c = res.minimum\n    @show res.f_minimum d\u00b2_opt\n    tsolve, x\u207a, v\u207a, d\u00b2 = obj(secondorder(param\u207c...), ystart, sol.time, data)\n    if PLOT\n        figure()\n        plot(tsolve, x\u207a, label=\"\\$x^+_o\\$\")\n        plot(sol.time,form,label=\"\\$x_f\\$\")\n        plot(tsolve, x\u207a, label=\"\\$x^+\\$\")\n        plot(sol.time, data, \".\",  label=\"data\")\n        title(\"parameter fitting \\$ $a \\\\ddot{x} + $b \\\\dot{x} + $c x = 0\\$\") \n        legend()\n    end\n    # check that residual is small\n    @show sqrt(soserr(tsolve, x\u207a, sol.time, form))\n    @test_approx_eq_eps \u03b3(res.minimum) sqrt(d\u00b2_opt) 2e-1\n    #check that error is small\n    @show err = norm(param\u207c - params)\n    @test err < 3e-1\nend\n", "meta": {"hexsha": "1690f5c20d743021c5a1a48302a2cde4e6ed8c16", "size": 3999, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 33.325, "max_line_length": 83, "alphanum_fraction": 0.56064016, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7583649711823576}}
{"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 \u03b1, \u03b2 = -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, \u03b1, \u03b2, 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 \u03b1, \u03b2 = 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, \u03b1, \u03b2, 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 \u03b1, t, and b\n#Do I need a best guess for w, as well?\n#\"\"\"\n#function implicit_solve(\u03b1, 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 \u0394t 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, \u0394t, 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 = (\u0394t*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            \u0394t_m = t_mp1 - t_m\n            RHS = u_m + \u0394t_m*fE(t_m,u_m)\n            implicit_solver(-\u0394t_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                \u0394t_m = t_mp1 - t_m\n                u_mp1_k = subvals[m+1]\n                \u0394fE = fE(t_m, u_m_kp1) - fE(t_m, u_m_k)\n                RHS = subvals[m] + \u0394t_m*(\u0394fE - 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(-\u0394t_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, \u0394t)\n        subtimes = (\u0394t*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                \u0394t_m = t_mp1 - t_m\n                RHS = u_m + \u0394t_m*fE(t_m,u_m)\n                implicit_solver(-\u0394t_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                    \u0394t_m = t_mp1 - t_m\n                    u_mp1_k = subvals[m+1]\n                    \u0394fE = fE(t_m, u_m_kp1) - fE(t_m, u_m_k)\n                    RHS = subvals[m] + \u0394t_m*(\u0394fE - 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(-\u0394t_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.\u0394t)\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+\u0394t)\"\n#    )\n#    p = length(T.\u0394times)+1\n#    Plots.plot!(\n#        plot,\n#        title=\"Error Over 1 Timestep Vs No of Corrections \\n\u03bb=$\u03bb, \u0394t=$(T.\u0394t), t_n=$(T.t_n), p=$p (Gauss-Lobatto)\",\n#        xlabel=\"# of Corrections (0 \u27f9 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 \u2208 [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 \u2200 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": "function generate_point(rng = Random.GLOBAL_RNG)\n    thres = rand(rng)\n    if thres >= 0.5\n        rand(rng, LogNormal())\n    else  \n        rand(rng, Uniform(2.0, 3.0))\n    end\nend\n\nmt = Random.MersenneTwister(42)\nxs = [generate_point(mt) for _ in 1:5000]\nbandwidths = [0.05, 0.1, 0.5]\ndensities = [KernelDensity.kde(xs, bandwidth = bw) for bw in bandwidths]\n\np = Plots.plot()\nfor (b,d) in zip(bandwidths, densities)\n    Plots.plot!(p, d.x, d.density, labels = \"bw = $b\")\nend\nPlots.xlims!(p, 0.0, 8.0)\nPlots.title!(\"KDE with Gaussian Kernel\")\nPlots.savefig(joinpath(base_img, \"KDE.pdf\"))\n", "meta": {"hexsha": "7220003ddaae29e9cafff8430a1cf3d494ac3081", "size": 589, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kde_gaussian.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/kde_gaussian.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/kde_gaussian.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": 26.7727272727, "max_line_length": 72, "alphanum_fraction": 0.6502546689, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7583449276795065}}
{"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\u209a = 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\u209a[i], j)\n                C[j] += 1\n            elseif r == -1\n                push!(S\u209a[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\u209a[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\u209a\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\u00e8 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\u00b2 \u00c5).\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": "@testset \"Haar\" begin\n\n    haar_udwt = UDWT_Filter_Haar{Float64}()\n\n    @test \u03d5_filter(haar_udwt) \u2248 [1/2, 1/2]\n    @test tilde\u03d5_filter(haar_udwt) \u2248 [1/2, 1/2]\n\n    @test \u03c8_filter(haar_udwt) \u2248 [-1/2, 1/2]\n    @test tilde\u03c8_filter(haar_udwt) \u2248 [-1/2, 1/2]\n\nend\n\n@testset \"Starck2\" begin\n\n    starck2_udwt = UDWT_Filter_Starck2{Float64}()\n\n    @test fcoef(tilde\u03d5_filter(starck2_udwt)) \u2248 [1]\nend\n\n@testset \"UDWT Transform\" begin\n\n    signal = rand(20)\n\n    for filter in [UDWT_Filter_Haar{Float64}()\n                   UDWT_Filter_Starck2{Float64}()]\n\n        s = 4\n        m = udwt(signal,filter,scale=s)\n        \n        @test size(m.W) == (length(signal),s)\n        @test size(m.V) == (length(signal),)\n        @test scale(m) == s\n        \n        signal_from_inv = inverse_udwt(m)\n        \n        @test signal \u2248 signal_from_inv\n    end\nend \n", "meta": {"hexsha": "3623a8257904374b487add3c679c0245ad4e3d8a", "size": 841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/udwt.jl", "max_stars_repo_name": "vincent-picaud/DirectConvolution", "max_stars_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-04-20T20:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T12:33:45.000Z", "max_issues_repo_path": "test/udwt.jl", "max_issues_repo_name": "vincent-picaud/DirectConvolution", "max_issues_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-11T04:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-17T09:58:07.000Z", "max_forks_repo_path": "test/udwt.jl", "max_forks_repo_name": "vincent-picaud/DirectConvolution", "max_forks_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-01T03:11:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:27:26.000Z", "avg_line_length": 21.5641025641, "max_line_length": 50, "alphanum_fraction": 0.5862068966, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.7583381102421595}}
{"text": "using Base.Test\n\n@testset \"Construction and Initialization\" begin\n# ============================================= #\n@testset \"reshape\" begin\n    a::Array{Float64,3} = Array{Float64,3}(3,3,3)\n\n    # - reshape - #\n    a = reshape(1:27,3,3,3)\n    # - same as the code below\n    # value::Int64 = 1\n    # for k in 1:3\n    #     for j in 1:3\n    #         for i in 1:3\n    #             a[i,j,k] = value\n    #             value += 1\n    #         end\n    #     end\n    # end\n    @test a[1,1,1] \u2248 1.\n    @test isapprox(a[2,1,1], 2.)\n    @test a[3,3,3] \u2248 27.\nend\n# ============================================= #\n# - Comprehension - #\n@testset \"Comprehensions\" begin\n    # a =\n    # [1.0 4.0 7.0;\n    #  2.0 5.0 8.0;\n    #  3.0 6.0 9.0]\n    # [10.0 13.0 16.0;\n    #  11.0 14.0 17.0;\n    #  12.0 15.0 18.0]\n    # [19.0 22.0 25.0;\n    #  20.0 23.0 26.0;\n    #  21.0 24.0 27.0]\n    a::Array{Float64,3} = Float64[i+3(j-1)+9(k-1) for i=1:3, j=1:3, k=1:3]\n    @test a[1,1,1] \u2248 1.\n    @test isapprox(a[2,1,1], 2.)\n    @test a[3,3,3] \u2248 27.\nend\n# ============================================= #\nend\n", "meta": {"hexsha": "4d586d55ff2c59be4ec19fb4ac51d798ce976915", "size": 1082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/std_array.jl", "max_stars_repo_name": "ykyang/Allnix.jl", "max_stars_repo_head_hexsha": "55806e3507d6584b15d4141d7272218ce2d3b809", "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/std_array.jl", "max_issues_repo_name": "ykyang/Allnix.jl", "max_issues_repo_head_hexsha": "55806e3507d6584b15d4141d7272218ce2d3b809", "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/std_array.jl", "max_forks_repo_name": "ykyang/Allnix.jl", "max_forks_repo_head_hexsha": "55806e3507d6584b15d4141d7272218ce2d3b809", "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.5909090909, "max_line_length": 74, "alphanum_fraction": 0.4011090573, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7583007051010744}}
{"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": "# This file includes portions from JuliaMath/Combinatorics.jl in modified form.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) \u2209 LOAD_PATH && push!(LOAD_PATH, (@__DIR__))\n\nmodule CombinationsIterator\n\nusing IterTools\n\nexport ModuleCombinationsIterator\nexport Combinations\n\n\"\"\"\n* Combinations\n\"\"\"\nconst ModuleCombinationsIterator = \"\"\n\n#The combinations iterator\nstruct combinations\n    n::Int\n    t::Int\nend\n\nfunction Base.iterate(c::combinations, s=[min(c.t - 1, i) for i in 1:c.t])\n    if c.t == 0 # special case to generate 1 result for t==0\n        isempty(s) && return (s, [1])\n        return\n    end\n    for i in c.t:-1:1\n        s[i] += 1\n        if s[i] > (c.n - (c.t - i))\n            continue\n        end\n        for j in i + 1:c.t\n            s[j] = s[j - 1] + 1\n        end\n        break\n    end\n    s[1] > c.n - c.t + 1 && return\n    (s, s)\nend\n\nBase.length(c::combinations) = binomial(c.n, c.t)\nBase.eltype(::Type{combinations}) = Vector{Int}\n\n\"\"\"\nGenerate all Combinations of ``n`` elements from an indexable object ``a``. Because the number of Combinations can be very large, this function returns an iterator object.\n Use 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    reorder(c) = [a[ci] for ci in c]\n    (reorder(c) for c in combinations(length(a), t))\nend\n\n\"\"\"\nGenerate Combinations of the elements of ``a`` of all orders. Chaining of order iterators is eager, but the sequence at each order is lazy.\n\"\"\"\nCombinations(a) = Iterators.flatten([Combinations(a, k) for k = 1:length(a)])\n\n#START-TEST-########################################################\n\nusing Test, SeqUtils\n\nfunction test()\n    C = collect(Combinations([2, 3, 5]))\n    @testset \"Combinations\" begin\n        @test C == [[2], [3], [5], [2, 3], [2, 5], [3, 5], [2, 3, 5]]\n    end\nend\n\nfunction demo()\n    Println([Combinations(\"abcd\", 3)...])\n\n    D = [2, 3, 4, 5]\n    for c in Combinations(D)\n        println(c)\n    end\n\n    println()\n    C = collect(Combinations([2, 3, 5]))\n    Println(C)\nend\n\nfunction perf() end\n\nfunction main()\n    test()\n    demo()\n    perf()\nend\n\nmain()\n\nend # module\n\n#=\n\nArray{Char,1}[['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'c', 'd'], ['b', 'c', 'd']]\n\n[2][3]\n[4]\n[5]\n[2, 3]\n[2, 4]\n[2, 5]\n[3, 4]\n[3, 5]\n[4, 5]\n[2, 3, 4]\n[2, 3, 5]\n[2, 4, 5]\n[3, 4, 5]\n[2, 3, 4, 5]\n\n=#\n", "meta": {"hexsha": "499fb310ea5a8da4a7249f283b711168032a7a48", "size": 2454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CombinationsIterator.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/CombinationsIterator.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/CombinationsIterator.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": 20.45, "max_line_length": 171, "alphanum_fraction": 0.5713121434, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7583006925917284}}
{"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} \u03c0(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\u00e9journ\u00e9, T., Feydy, J., Vialard, F.-X., Trouv\u00e9, A., Peyr\u00e9, 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\u201319. 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\u00e9journ\u00e9, T., Feydy, J., Vialard, F.-X., Trouv\u00e9, A., Peyr\u00e9, 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\u201319. 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() \u2218 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_\u03f5 = find_good_stepsize(hamiltonian, initial_params)\nintegrator = Leapfrog(initial_\u03f5)\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() \u2218 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(\u2113::typeof(loglik_train), params)\n    return \u2113(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() \u2218 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() \u2218 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() \u2218 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\u03b80 = randn(2)\nopt = Optim.optimize(loss_function(x_train, y_train), \u03b80, 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() \u2218 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\u00ba 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": "using GlobalDiffEq, OrdinaryDiffEq, LinearAlgebra\nusing Test\n\nl = 1.0                             # length [m]\nm = 1.0                             # mass[m]\ng = 9.81                            # gravitational acceleration [m/s\u00b2]\n\nfunction pendulum!(du,u,p,t)\n    du[1] = u[2]                    # \u03b8'(t) = \u03c9(t)\n    du[2] = -3g/(2l)*sin(u[1]) + 3/(m*l^2)*p(t) # \u03c9'(t) = -3g/(2l) sin \u03b8(t) + 3/(ml^2)M(t)\nend\n\n\u03b8\u2080 = 0.01                           # initial angular deflection [rad]\n\u03c9\u2080 = 0.0                            # initial angular velocity [rad/s]\nu\u2080 = [\u03b8\u2080, \u03c9\u2080]                       # initial state vector\ntspan = (0.0,10.0)                  # time interval\n\nM = t->0.1sin(t)                    # external torque [Nm]\n\nprob = ODEProblem(pendulum!,u\u2080,tspan,M)\n\nv0 = solve(prob, Tsit5(), dt=0.1, reltol=1e-12, abstol=0).(1:10)\nve = solve(prob, GlobalRichardson(SSPRK33()), dt=0.2, reltol=1e-12, abstol=0).(1:10)\n@test norm(ve - v0) / norm(v0) < 1e-10\n", "meta": {"hexsha": "6eb2be762589ef4a9ee9649064c237372dcb2a32", "size": 950, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "SciML/GlobalDiffEq.jl", "max_stars_repo_head_hexsha": "ec20377d2b31d42fb30c1748816071d3c817055c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-22T22:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-24T17:53:48.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "SciML/GlobalDiffEq.jl", "max_issues_repo_head_hexsha": "ec20377d2b31d42fb30c1748816071d3c817055c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-09-21T06:50:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T15:21:49.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "SciML/GlobalDiffEq.jl", "max_forks_repo_head_hexsha": "ec20377d2b31d42fb30c1748816071d3c817055c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-19T21:55:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T03:04:38.000Z", "avg_line_length": 38.0, "max_line_length": 90, "alphanum_fraction": 0.4768421053, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7582405484345549}}
{"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) * (\u03c0 / (4B))) / (2j + 1)\n    end\n    \n    s *= (2/B) * sin(\u03c0 * (2k + 1) / (4B))\nend\n\nfunction S\u2081(f::Function, B::Int, k::Int, j\u2082::Int)\n    \u03b2 = \u03c0 * (2k + 1) / (4B)\n    \u03b3 = (2\u03c0 * j\u2082) / (2B)\n    \n    A = [exp(-im * ((2\u03c0 * j\u2081) / (2B)) * (B - 1)) * f(O3((2\u03c0 * j\u2081) / (2B), \u03b2, \u03b3)) for j\u2081 in 0:2B-1]\n    A\u2032 = ifft(A)\nend\n\nfunction S\u2082(f::Function, B::Int, k::Int)\n    S = [S\u2081(f, B, k, j\u2082) for j\u2082 in 0:2B-1]\n    A = Vector{Vector{Complex128}}(2B)\n    A\u2032 = Vector{Vector{Complex128}}(2B)\n    \n    for M\u2032 in -(B-1):B\n        A[M\u2032 + B] = [exp(-im * ((2\u03c0 * j\u2082) / (2B)) * (B - 1)) * S[j\u2082 + 1][M\u2032 + B] for j\u2082 in 0:2B-1]\n        A\u2032[M\u2032 + B] = ifft(A[M\u2032 + B])\n    end\n    \n    return hcat(A\u2032...)\nend\n\nfunction fast_fourier_coeffs(f::Function, B::Int)\n    S = [S\u2082(f, B, k) for k in 0:2B-1]\n    f\u0302 = [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\u2032 in -l:l\n            for k in 0:2B-1\n                \u03b2 = \u03c0 * (2k + 1) / (4B)\n                f\u0302[l + 1][M\u2032 + l + 1, M + l + 1] += wigner_d\u0303(l, M, M\u2032, \u03b2) * w(B, k) * S[k + 1][M\u2032 + B, M + B] / sqrt(2 / (2l + 1))\n            end\n        end\n    end\n    \n    return f\u0302\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 \u2208 1:n\n\t\tout[i, 1] = y[i]\n\tend\n\tfor i \u2208 2:n\n\t\tfor j \u2208 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": "module GmshDiscreteModelsTests\n\nusing Gridap\nusing GridapGmsh\nusing Gridap.Geometry\nusing Gridap.Helpers\nusing Test\n\nfunction check_interpolation(model)\n  order = 2\n  reffe = ReferenceFE(lagrangian,Float64,order)\n  V = FESpace(model,reffe)\n  if num_dims(model) == 2\n    u = x -> x[1]^2 + 2*x[2]^2\n  elseif num_dims(model) == 3\n    u = x -> x[1]^2 + 2*x[2]^2 + 3*x[3]^2\n  else\n    @unreachable\n  end\n  uh = interpolate(u,V)\n  e = u - uh\n  \u03a9 = Triangulation(model)\n  d\u03a9 = Measure(\u03a9,2*order)\n  @test sum(\u222b( e*e )d\u03a9) < 1.0e-9\nend\n\nmshfile = joinpath(@__DIR__,\"t1.msh\")\nmodel = GmshDiscreteModel(mshfile)\ntest_discrete_model(model)\nwritevtk(model,\"model\")\ncheck_interpolation(model)\n\nmshfile = joinpath(@__DIR__,\"twoTetraeder.msh\")\nmodel = GmshDiscreteModel(mshfile; renumber=true)\ntest_discrete_model(model)\ncheck_interpolation(model)\n\nmshfile = joinpath(@__DIR__,\"..\",\"demo\",\"demo.msh\")\nmodel = GmshDiscreteModel(mshfile)\ntest_discrete_model(model)\ncheck_interpolation(model)\n\nmshfile = joinpath(@__DIR__,\"square.msh\")\nmodel = GmshDiscreteModel(mshfile)\ntest_discrete_model(model)\ncheck_interpolation(model)\n\nmshfile = joinpath(@__DIR__,\"cube.msh\")\nmodel = GmshDiscreteModel(mshfile)\ntest_discrete_model(model)\ncheck_interpolation(model)\n\nmshfile = joinpath(@__DIR__,\"periodic.msh\")\nmodel = GmshDiscreteModel(mshfile)\ntest_discrete_model(model)\nu(x) = 2*x[1]\nreffe = ReferenceFE(lagrangian,Float64,1)\nV = TestFESpace(model,reffe,dirichlet_tags=[\"L\",\"PL\"])\nU = TrialFESpace(V,u)\n\u03a9 = Triangulation(model)\n\u0393 = BoundaryTriangulation(model,tags=\"R\")\nn_\u0393 = get_normal_vector(\u0393)\nd\u03a9 = Measure(\u03a9,2)\nd\u0393 = Measure(\u0393,2)\na(u,v) = \u222b( \u2207(u)\u22c5\u2207(v) )d\u03a9\nl(v) = \u222b( n_\u0393\u22c5(v*\u2207(u)) )d\u0393\nop = AffineFEOperator(a,l,U,V)\nuh = solve(op)\n#writevtk(\u03a9,\"sol\",cellfields=[\"uh\"=>uh,\"u\"=>u,\"e\"=>u-uh,\"zh\"=>zero(U)])\n@test sum( \u222b(abs2(u - uh))d\u03a9 ) < 1.0e-9\n\nend # module\n", "meta": {"hexsha": "78a74ee1e3854ae11f041114e7f9ffa08fb77816", "size": 1830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/GmshDiscreteModelsTests.jl", "max_stars_repo_name": "ConnorMallon/GridapGmsh.jl", "max_stars_repo_head_hexsha": "5a1455943219eb7146478a904f3d5d1553b697f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2019-07-31T15:02:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T12:47:51.000Z", "max_issues_repo_path": "test/GmshDiscreteModelsTests.jl", "max_issues_repo_name": "ConnorMallon/GridapGmsh.jl", "max_issues_repo_head_hexsha": "5a1455943219eb7146478a904f3d5d1553b697f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2019-07-31T15:27:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:01:32.000Z", "max_forks_repo_path": "test/GmshDiscreteModelsTests.jl", "max_forks_repo_name": "ConnorMallon/GridapGmsh.jl", "max_forks_repo_head_hexsha": "5a1455943219eb7146478a904f3d5d1553b697f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:14:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T01:56:42.000Z", "avg_line_length": 25.0684931507, "max_line_length": 71, "alphanum_fraction": 0.7120218579, "num_tokens": 691, "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": "# 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\u00edsica Enrique Garc\u00eda @FiQuiPedia www.fiquipedia.es\n# C\u00f3digo por Samuel G\u00f3mez @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 \u03bcC, se encuentra situada en\n# el origen de coordenadas, tal y como se muestra en la figura. Una\n# segunda carga q1 = 1 \u03bcC 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\u00b7109 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\u00f3n\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\u3067return\r\n    # \u5de6\u4e0a\u3068\u53f3\u4e0b\u306e\u5ea7\u6a19\u3092\u6574\u6570\u3067\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    # \u5de6\u4e0a\u306e\u70b9\u306e\u30e2\u30fc\u30c8\u30f3\u7a7a\u9593\u756a\u53f7\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    # \u53f3\u4e0b\u306e\u70b9\u306e\u30e2\u30fc\u30c8\u30f3\u7a7a\u9593\u756a\u53f7\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    # \u6392\u4ed6\u7684\u8ad6\u7406\u548c 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    # \u6240\u5c5e\u7a7a\u9593\u306e\u30c1\u30a7\u30c3\u30af\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                             # \u30eb\u30fc\u30c8\u7a7a\u9593\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                             # \u30eb\u30fc\u30c8\u7a7a\u9593\r\n        elseif temp_morton[4] == 1 || temp_morton[3] == 1\r\n            morton_belong = 1                             # \u89aa\u7a7a\u9593\r\n        elseif temp_morton[2] == 1 || temp_morton[1] == 1\r\n            morton_belong = 2                             # \u5b50\u7a7a\u9593\r\n        else\r\n            morton_belong = 3                             # \u5b6b\u7a7a\u9593\r\n        end\r\n        =#\r\n        ite += 1\r\n    end\r\n    \r\n    # \u6240\u5c5e\u7a7a\u9593\u756a\u53f7\r\n    temp_morton = zeros(Int8,10)\r\n    if morton_belong == 0                             # \u30eb\u30fc\u30c8\u7a7a\u9593\r\n        morton_num = 0\r\n    elseif morton_belong == 1                         # \u89aa\u7a7a\u9593\r\n        s_even = 2*(n_div)\r\n        s_odd = 2*(n_div) - 1\r\n\r\n        # 4\u53f3\u30b7\u30d5\u30c8\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                         # \u5b50\u7a7a\u9593\r\n\r\n        s_even = 2*(n_div)\r\n        s_odd = 2*(n_div) - 1\r\n        \r\n        # 2\u53f3\u30b7\u30d5\u30c8\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                         # \u5b6b\u7a7a\u9593\r\n        s_even = 2*(n_div)\r\n        s_odd = 2*(n_div) - 1\r\n        \r\n        # 0\u53f3\u30b7\u30d5\u30c8\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                         # \u5b6b\u7a7a\u9593\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    # \u4e21\u65b9\u306e\u63a2\u67fb\u3092\u884c\u3046\u305f\u3081\uff0c\u7169\u96d1\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    # \u30eb\u30fc\u30c8\u7a7a\u9593\uff1as0\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    # \u89aa\u7a7a\u9593\uff1as1\r\n    for i in 1:4\r\n        search1[i,1] = 1\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000# \u30eb\u30fc\u30c8\u7a7a\u9593\r\n        search1[i,2] = i+1                           # \u89aa\u7a7a\u9593\r\n        for j in 1:4\r\n            search1[i,j+2] = 6 + 4*(i-1) + (j-1)     # \u5b50\u7a7a\u9593\r\n        end\r\n        for j in 1:16\r\n            search1[i,j+6] = 22 + 16*(i-1) + (j-1)   # \u5b6b\u7a7a\u9593\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)   # \u3072\u5b6b\u7a7a\u9593\r\n            end\r\n        end\r\n    end\r\n    \r\n    # \u5b50\u7a7a\u9593\uff1as2\r\n    for i in 1:16\r\n        search2[i,1] = 1                             # \u30eb\u30fc\u30c8\u7a7a\u9593\r\n        search2[i,2] = div(i-1,4) + 2                # \u89aa\u7a7a\u9593\r\n        search2[i,3] = i+5                           # \u5b50\u7a7a\u9593\r\n        for j in 1:4\r\n            search2[i,j+3] = 22 + 4*(i-1) + (j-1)    # \u5b6b\u7a7a\u9593\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)    # \u5b6b\u7a7a\u9593\r\n            end\r\n        end\r\n    end\r\n    \r\n    # \u5b6b\u7a7a\u9593\r\n    for i in 1:64\r\n        search3[i,1] = 1                             # \u30eb\u30fc\u30c8\u7a7a\u9593\r\n        search3[i,2] = div(i-1,16) + 2               # \u89aa\u7a7a\u9593\r\n        search3[i,3] = div(i-1,4) + 6                # \u5b50\u7a7a\u9593\r\n        search3[i,4] = 22 + (i-1)                    # \u5b6b\u7a7a\u9593\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)    # \u5b6b\u7a7a\u9593\r\n            end\r\n        end\r\n    end\r\n    \r\n    # \u3072\u5b6b\u7a7a\u9593\r\n    if n_div >=4\r\n        for i in 1:256\r\n            search4[i,1] = 1                             # \u30eb\u30fc\u30c8\u7a7a\u9593\r\n            search4[i,2] = div(i-1,64) + 2               # \u89aa\u7a7a\u9593\r\n            search4[i,3] = div(i-1,16) + 6                # \u5b50\u7a7a\u9593\r\n            search4[i,4] = div(i-1,4) + 22                # \u5b6b\u7a7a\u9593\r\n            search4[i,5] = 86 + (i-1)                    # \u5b6b\u7a7a\u9593\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\u03b8::Float64,  n::Int64)\n    x, y, \u03b8 = 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(\u03b8), yd*cos(\u03b8)\n        \u03b8 += d\u03b8\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) \u2208 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\u2020`: generalized inverse of `E`\n\"\"\"\nfunction seasonal_matrices(fcycle,t,overtones=1)\n\n    \u03c9 = 2\u03c0 * fcycle # day^{-1} , seasonal frequency\n    nt = length(t)\n    freqs = overtones+1\n        \n    # times 2 for sines and cosines \n    n\u03b2 = 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\u03b2)\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*\u03c9*t)))\n        E[:,i+1] = sin.(i*\u03c9*t)\n        E[:,i+freqs+1] = cos.(i*\u03c9*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\u2020`: 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\u03b2 = 2\n\n    # would be neat to return whatever type goes in\n    E = zeros(Float32,nt,n\u03b2)\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": "function find_max_subarray(A, start, finish)\n    max_sum = -Inf\n    sum = 0\n    max_index = -1\n\n    start > finish ? step = -1 : step = 1\n\n    for i in range(start, finish, step = step)\n        sum += A[i]\n        if sum > max_sum\n            max_sum = sum\n            max_index = i\n        end\n    end\n\n    return (max_index, max_sum)\nend\n\nfunction find_max_crossing_subarray(A, low, mid, high)\n    max_left, left_sum = find_max_subarray(A, mid, low)\n    max_right, right_sum = find_max_subarray(A, mid+1, high)\n\n    return (max_left, max_right, left_sum + right_sum)\nend\n\nfunction find_maximum_subarray(A, low, high)\n    # base case only one elem\n    if high == low\n        return (low, high, A[low])\n    end\n\n    mid = floor(Int, (low + high) / 2)\n\n    left_low, left_high, left_sum = find_maximum_subarray(A, low, mid)\n    right_low, right_high, right_sum = find_maximum_subarray(A, mid+1, high)\n    x_low, x_high, x_sum = find_max_crossing_subarray(A, low, mid, high)\n\n    if left_sum \u2265 right_sum && left_sum \u2265 x_sum\n        return (left_low, left_high, left_sum)\n    elseif right_sum \u2265 left_sum && right_sum \u2265 x_sum\n        return (right_low, right_high, right_sum)\n    else\n        return (x_low, x_high, x_sum)\n    end\nend\n\nusing Test\n\n@testset \"max sub array\" begin\n    input = [13 -3 -25 20 -3 -16 -23 18 20 -7 12 -5 -22 15 -4 7]\n    output = (8, 11, 43)\n    @test find_maximum_subarray(input, 1, length(input)) == output\nend", "meta": {"hexsha": "c1e8ff61d228c9e604088e262b31a52384d1d594", "size": 1435, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/max_subarray.jl", "max_stars_repo_name": "blallen/CodePractice", "max_stars_repo_head_hexsha": "b7bc8684a2fb1c4eff9f57ccfe5d84d86d48cfe5", "max_stars_repo_licenses": ["MIT"], "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/max_subarray.jl", "max_issues_repo_name": "blallen/CodePractice", "max_issues_repo_head_hexsha": "b7bc8684a2fb1c4eff9f57ccfe5d84d86d48cfe5", "max_issues_repo_licenses": ["MIT"], "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/max_subarray.jl", "max_forks_repo_name": "blallen/CodePractice", "max_forks_repo_head_hexsha": "b7bc8684a2fb1c4eff9f57ccfe5d84d86d48cfe5", "max_forks_repo_licenses": ["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.0754716981, "max_line_length": 76, "alphanum_fraction": 0.6348432056, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642533380189, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7582102486986605}}
{"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        \u03bb = 0                   # normalize the scores\n        for i = 1:n\n            if abs(score[i]) > \u03bb\n                \u03bb = score[i]\n            end\n        end\n        if \u03bb == 0\n            error(\"power iteration cannot converge\")\n            break\n        else\n            maxdiff = 0.\n            for i = 1:n\n                score[i] /= \u03bb\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.\u03f5 * (u[2] - 2*u[1] + problem.left_bc.u_bc)/problem.\u0394x^2 +  u[1] * (1-u[1]^2);\n\n    for i in 2:problem.n-1\n        problem.F[i]= problem.\u03f5 * (u[i+1] - 2*u[i] +u[i-1])/problem.\u0394x^2 +u[i] * (1-u[i]^2);\n    end\n    problem.F[end] = problem.\u03f5 * (problem.right_bc.u_bc - 2*u[end] + u[end-1])/problem.\u0394x^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, \u03c3::Real, \u03bc::Real)\n    return exp(-0.5((x-\u03bc)/\u03c3)^2) / (\u03c3 * sqrt(2\u03c0))\nend\n\nf(\u03c3::Real, \u03bc::Real) = x -> f(x, \u03c3, \u03bc)\n\nsurface(range::AbstractRange; \u03c3=1, \u03bc=0) = f(\u03c3, \u03bc).(range) * f(\u03c3, \u03bc).(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": "using Test, SpecialFunctions\nimport TruncatedNormal as TN\n\n@test TN.tnmean(-Inf, Inf) == 0\n@test TN.tnmean(0, +Inf) \u2248 +\u221a(2/\u03c0)\n@test TN.tnmean(-Inf, 0) \u2248 -\u221a(2/\u03c0)\n@test TN.tnmean(-Inf, -Inf) == -Inf\n@test TN.tnmean(+Inf, +Inf) == +Inf\n\nfor x = -10:10\n    @test TN.tnmean(x, +Inf) \u2248 +\u221a(2/\u03c0) / erfcx(+x/\u221a2)\n    @test TN.tnmean(-Inf, x) \u2248 -\u221a(2/\u03c0) / erfcx(-x/\u221a2)\nend\n\nfor x = exp.(-100:100)\n    @test TN.tnmean(-x, x) \u2248 0\n    @test TN.tnmean(0, x) \u2248 -\u221a(2/\u03c0) * expm1(-x^2 / 2) / erf(x / \u221a2)\nend\n\n@test TN.tnmean(1e-44, 1e-43) \u2248 5.4999999999999999999999999999999999999999e-44\n\n@test TN.tnmean(-Inf, Inf, 0, 1) == TN.tnmean(-Inf, Inf)\nfor x = -100:100\n    @test TN.tnmean(x, +Inf, 0, 1) \u2248 TN.tnmean(x, +Inf)\n    @test TN.tnmean(-Inf, x, 0, 1) \u2248 TN.tnmean(-Inf, x)\nend\n\n@test TN.tnmean(-1e4, 1e4, 0, 1) == TN.tnmean(-1e4, 1e4)\n\nfor x = -100:100, y = x + 1 : 100\n    @test TN.tnmean(x, y, 0, 1) == TN.tnmean(x, y)\nend\n\n@test TN.tnmean(100, 115) \u2248 100.00999800099926070518490239457545847490332879043\n@test TN.tnmean(-1e6, -999000) \u2248 -999000.00000100100100099899498898098\n@test TN.tnmean(+1e6, +Inf) \u2248 +1.00000000000099999999999800000e6\n@test TN.tnmean(-Inf, -1e6) \u2248 -1.00000000000099999999999800000e6\n\n@test TN.tnmean(-1e200, 1e200) \u2248 0\n@test TN.tnmean(0, +1e200) \u2248 +0.797884560802865355879892119869\n@test TN.tnmean(-1e200, 0) \u2248 -0.797884560802865355879892119869\n\n@test TN.tnmean(50, 70, -2, 3) \u2248 50.171943499898757645751683644632860837133138152489\n@test TN.tnmean(-100.0, 0.0, 0.0, 2.0986317998643735) \u2248 -1.6744659119217125058885983754999713622460154892645\n@test TN.tnmean(0.0, 0.9, 0.0, 0.07132755843183151) \u2248 0.056911157632522598806524588414964004271754161737065\n@test TN.tnmean(-100.0, 100.0, 0.0, 17.185261847875548) \u2248 0\n@test TN.tnmean(-100.0, 0.5, 0.0, 0.47383322897860064) \u2248 -0.1267981330521791493635176736743283314399\n@test TN.tnmean(-100.0, 100.0, 0.0, 17.185261847875548) \u2248 0\n\nfor x = 1e1 .^ (-400:100:400)\n    @test TN.tnmean(-x, x) == TN.tnmean(-x, x) || isnan(TN.tnmean(-x, x)) && isnan(TN.tnmean(-x, x))\nend\n\nfor a = exp.(-10:10), b = exp.(-10:10)\n    a \u2264 b || continue\n    @test a \u2264 TN.tnmean(a, b) \u2264 b\nend\n\n# https://github.com/JuliaStats/Distributions.jl/issues/827\n@test TN.tnmean(0, 1000, 1000000, 1) \u2248 999.99999899899899900100501101901899090472046236710608108591983\n", "meta": {"hexsha": "5e29d570036ade134c465254e950956b460cdb2a", "size": 2275, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tnmean.jl", "max_stars_repo_name": "cossio/TruncatedNormal.jl", "max_stars_repo_head_hexsha": "cb0b28224296e569fc976711efe17db83513a932", "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": "test/tnmean.jl", "max_issues_repo_name": "cossio/TruncatedNormal.jl", "max_issues_repo_head_hexsha": "cb0b28224296e569fc976711efe17db83513a932", "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": "test/tnmean.jl", "max_forks_repo_name": "cossio/TruncatedNormal.jl", "max_forks_repo_head_hexsha": "cb0b28224296e569fc976711efe17db83513a932", "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": 37.2950819672, "max_line_length": 108, "alphanum_fraction": 0.6685714286, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.758188571786494}}
{"text": "#  Unit \"QnLogLike.jl\" of the Diagonalization.jl Package for Julia language\n#\n#  MIT License\n#  Copyright (c) 2020-2021,\n#  Marco Congedo\u00b0, Ronald Phlypo, CNRS, UGA, Grenoble-INP, France\n#  Alexandre Gramfort\u00a8, INRIA, U. Paris Saclay, France\n#  \u00b0 https://sites.google.com/site/marcocongedo/\n#  \u00a8 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., \ud835\udc00\n#\n#  ADVANCED QnLogLike algorithm (no PRIMITIVE version is available):\n#  The algorithm takes as input a vector of k real symmetric matrices\n#  \ud835\udc02 and find a non-singular matrix B such that the congruences\n#  B'*\ud835\udc02_\u03ba*B are as diagonal as possible for all \u03ba=1:k.\n#\n#  `w` is an optional vector of k positive weights for each matrix in \ud835\udc02.\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 \ud835\udc02.\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 \ud835\udc02 is\n#  computed (using the PosDefManifold.jl package) and the matrices in \ud835\udc02\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#  \u03ba=1:k of the diagonal elements of B'*\ud835\udc02_\u03ba*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#  `\ud835\udf06min` is used to reguarize Hessian coefficients; all coefficients smaller\n#  than \ud835\udf06min  will be set to \ud835\udf06min. 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 \ud835\udc02 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(\ud835\udc02)*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 \ud835\udc03;\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 \ud835\udc03)\n#  we form a m\u00b7m 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, \ud835\udc02)\n\tif w isa Function w=[w(C) for C\u2208\ud835\udc02] end\n\treturn w./mean(w)\nend\n\nfunction qnLogLike( \ud835\udc02::Union{Vector{Hermitian}, Vector{Symmetric}};\n\t\t\t\tw           :: \tTwf   = \u25cb,\n\t\t\t\tpreWhite    :: \tBool = false,\n\t\t\t\tsort        :: \tBool = true,\n\t\t\t\tinit        :: \tUnion{Matrix, Nothing} = \u25cb,\n\t\t\t\ttol         :: \tReal = 1e-6,\n\t\t\t\tmaxiter     :: \tInt  = 1000,\n\t\t\t\t\ud835\udf06min        ::\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(\ud835\udc02) \u2265 2*thr && thr>1\n\t\t\t\t\t\t\tend,\n\t\t\teVar     :: TeVaro = \u25cb,\n\t\t\teVarMeth :: Function = searchsortedfirst)\n\n\t# # # # # # # # #  internal functions\n\t# half sum of mean of log of Diagonals\n\thsmld(\ud835\udc00) = 0.5*sum(mean(log, [\ud835\udd3b(A) for A \u2208 \ud835\udc00]))\n\thsmld(\ud835\udc00, \ud835\udece) = 0.5*sum(mean(log, [\ud835\udd3b(A)*\u03bd for (A, \u03bd) \u2208 zip(\ud835\udc00, \ud835\udece)]))\n\n\t# minus log abs det\n\tmlad(A) = -logabsdet(A)[1]\n\n\t# line search: update B and \ud835\udc03\n\t@inline function _linesearch!(B, B\u208a, M, \ud835\udc03, \ud835\udc03\u208a, \ud835\udc9f, \ud835\udc2f, loss, lsmax)\n\t    for i \u2208 1:lsmax\n\t        M[:] = (1.0/i * \ud835\udc9f) + I\n\t\t\tB\u208a[:] = B * M\n\t\t\t### \ud835\udc03\u208a = [Hermitian(M'*D*M) for D in \ud835\udc03]\n\t\t\t@threads for j \u2208 eachindex(\ud835\udc03) \ud835\udc03\u208a[j] = Hermitian(M'*\ud835\udc03[j]*M) end\n\t\t\t### iter>2 && (loss\u208a = w===\u25cb ? mlad(B\u208a)+hsmld(\ud835\udc03\u208a) : mlad(B\u208a)+hsmld(\ud835\udc03\u208a, \ud835\udc2f))\n\t\t\tloss\u208a = w===\u25cb ? mlad(B\u208a)+hsmld(\ud835\udc03\u208a) : mlad(B\u208a)+hsmld(\ud835\udc03\u208a, \ud835\udc2f)\n\t        loss\u208a < loss && break\n\t    end\n\t\tB[:] = B\u208a\n\t\t\ud835\udc03[:] = \ud835\udc03\u208a\n\t    return loss\u208a\n\tend\n\t# # # # # # # # #\n\n\t# pre-whiten or initialize or nothing\n\tW, \ud835\udc03 = _preWhiteOrInit(\ud835\udc02, preWhite, Jeffrey, eVar, eVarMeth, init, :Hvector)\n\t\ud835\udc2f = w===\u25cb ? \u25cb : _qnlogLikeWeights!(w, \ud835\udc02) # if w is `nonD` function, apply it to the original input \ud835\udc02\n\n\t# set variables\n\titer, conv, \ud83d\ude0b, sqrtn, loss\u208a = 1, Inf, false, \u221asize(\ud835\udc03[1], 1), Inf\n\tB, \u2a6b = Matrix{eltype(\ud835\udc03[1])}(I, size(\ud835\udc03[1])), similar\n\tB\u208a, \ud835\udc9f, M, \u2207, \u210c, \ud835\udc03\u208a = \u2a6b(B), \u2a6b(B), \u2a6b(B), \u2a6b(B), \u2a6b(B), \u2a6b(\ud835\udc03)\n\t\ud835\udd6f = [zeros(eltype(\ud835\udc03[1]), size(\ud835\udc03[1], 1)) for i = 1:length(\ud835\udc03)]\n\tloss = w===\u25cb ? \thsmld(\ud835\udc03) : hsmld(\ud835\udc03, \ud835\udc2f) #loss = Inf\n\n\tverbose && println(\"Iterating quasi-Newton LogLike algorithm...\")\n\twhile true\n\t\tfor j \u2208 eachindex(\ud835\udc03) \ud835\udd6f[j] = diag(\ud835\udc03[j]) end\n\t    #\ud835\udd6f = [diag(D) for D \u2208 \ud835\udc03]\n\n\t    # gradient\n\t\tw===\u25cb ? \u2207[:] = mean(D./\ud835\udd21 for (D, \ud835\udd21) \u2208 zip(\ud835\udc03, \ud835\udd6f)) - I :\n\t\t\t\t\u2207[:] = mean(v.*(D./\ud835\udd21) for (v, D, \ud835\udd21) \u2208 zip(\ud835\udc2f, \ud835\udc03, \ud835\udd6f)) - I\n\t    conv = norm(\u2207)/sqrtn # relative norm of \u2207 with respect to the identity : ||\u2207-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    (\ud83d\ude0b = conv <= tol) || overRun==true ? break : iter += 1\n\n\t\t# Hessian Coefficients\n\t\tw===\u25cb ? \u210c[:] = mean(\ud835\udd21'./\ud835\udd21 for \ud835\udd21 \u2208 \ud835\udd6f) :\n\t\t\t\t\u210c[:] = mean(v.*(\ud835\udd21'./\ud835\udd21) for (v, \ud835\udd21) \u2208 zip(\ud835\udc2f, \ud835\udd6f))\n\n\t\t# Quasi-Newton Direction \ud835\udc9f\n\t    \ud835\udc9f[:] = -(\u2207' .* \u210c - \u2207)./replace(x -> x<\ud835\udf06min ? \ud835\udf06min : x, @. (\u210c'*\u210c) - 1.)\n\n\t    loss = _linesearch!(B, B\u208a, M, \ud835\udc03, \ud835\udc03\u208a, \ud835\udc9f, \ud835\udc2f, loss, lsmax) # Line Search\n\tend\n\tverbose && @info(\"Convergence has \"*(\ud83d\ude0b ? \"\" : \"not \")*\"been attained.\\n\\n\")\n\n\t# scale and permute the vectors of B\n\t\u03bb = sort ? _permute!(_scale!(B, mean(\ud835\udd3b(D) for D \u2208 \ud835\udc03), size(\ud835\udc03[1], 1))...) :\n\t            diag(mean(\ud835\udd3b(D) for D \u2208 \ud835\udc03))\n\n\treturn preWhite ? (W.F*B, pinv(B)*W.iF, \u03bb, iter, conv) :\n\t                  (B, pinv(B), \u03bb, 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(\u03bc::Real, \u03c3::Real, z::Number)\n    if isinf(z) && iszero(\u03c3)\n        \u03bc + one(\u03c3) * z\n    else\n        \u03bc + \u03c3 * z\n    end\nend\nzval(\u03bc::Real, \u03c3::Real, x::Number) = (x - \u03bc) / \u03c3\n\n# pdf\nnormpdf(z::Number) = exp(-abs2(z)/2) * invsqrt2\u03c0\nfunction normpdf(\u03bc::Real, \u03c3::Real, x::Number)\n    if iszero(\u03c3)\n        if x == \u03bc\n            z = zval(\u03bc, one(\u03c3), x)\n        else\n            z = zval(\u03bc, \u03c3, x)\n            \u03c3 = one(\u03c3)\n        end\n    else\n        z = zval(\u03bc, \u03c3, x)\n    end\n    normpdf(z) / \u03c3\nend\n\n# logpdf\nnormlogpdf(z::Number) = -(abs2(z) + log2\u03c0)/2\nfunction normlogpdf(\u03bc::Real, \u03c3::Real, x::Number)\n    if iszero(\u03c3)\n        if x == \u03bc\n            z = zval(\u03bc, one(\u03c3), x)\n        else\n            z = zval(\u03bc, \u03c3, x)\n            \u03c3 = one(\u03c3)\n        end\n    else\n        z = zval(\u03bc, \u03c3, x)\n    end\n    normlogpdf(z) - log(\u03c3)\nend            \n\n# cdf\nnormcdf(z::Number) = erfc(-z * invsqrt2)/2\nfunction normcdf(\u03bc::Real, \u03c3::Real, x::Number)\n    if iszero(\u03c3) && x == \u03bc\n        z = zval(zero(\u03bc), \u03c3, one(x))\n    else        \n        z = zval(\u03bc, \u03c3, x)        \n    end\n    normcdf(z)\nend\n# ccdf\nnormccdf(z::Number) = erfc(z * invsqrt2)/2\nfunction normccdf(\u03bc::Real, \u03c3::Real, x::Number)\n    if iszero(\u03c3) && x == \u03bc\n        z = zval(zero(\u03bc), \u03c3, one(x))\n    else        \n        z = zval(\u03bc, \u03c3, 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(\u03bc::Real, \u03c3::Real, x::Number)\n    if iszero(\u03c3) && x == \u03bc\n        z = zval(zero(\u03bc), \u03c3, one(x))\n    else        \n        z = zval(\u03bc, \u03c3, 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(\u03bc::Real, \u03c3::Real, x::Number)\n    if iszero(\u03c3) && x == \u03bc\n        z = zval(zero(\u03bc), \u03c3, one(x))\n    else        \n        z = zval(\u03bc, \u03c3, x)        \n    end\n    normlogccdf(z)\nend\n\nnorminvcdf(p::Real) = -erfcinv(2*p) * sqrt2\nnorminvcdf(\u03bc::Real, \u03c3::Real, p::Real) = xval(\u03bc, \u03c3, norminvcdf(p))\n\nnorminvccdf(p::Real) = erfcinv(2*p) * sqrt2\nnorminvccdf(\u03bc::Real, \u03c3::Real, p::Real) = xval(\u03bc, \u03c3, 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(\u03bc::Real, \u03c3::Real, lp::Real) = xval(\u03bc, \u03c3, 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(\u03bc::Real, \u03c3::Real, lp::Real) = xval(\u03bc, \u03c3, 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": "function InverseLUSolve(A::Array,B::Vector)\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    v = size(B,1)\r\n    if m != n\r\n        error(\"Matrix must be squared\")\r\n    elseif m != v\r\n        error(\"Vector Length must be equal to Matrix\")\r\n    end\r\n\r\n    N,P=InverseLU(A)\r\n\r\n    X=N*(P*B)\r\n\r\n    return X\r\nend\r\n", "meta": {"hexsha": "0a9895468bab0c7627c545fffa76885f80a959e1", "size": 398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InverseLUSolve.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/InverseLUSolve.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/InverseLUSolve.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": 22.1111111111, "max_line_length": 58, "alphanum_fraction": 0.567839196, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7581885507941977}}
{"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 \u03c9 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    \u03c9  :: 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\u00b0\",i)\n        elseif occursin(\"capacity\", lines[l])\n            line = split(lines[l],\"+\")\n            momkp.\u03c9[i] = floor(Int, parse(Float64, line[2]))\n            !verbose ? nothing : println(\"\u03c9[\",i,\"]=\",momkp.\u03c9[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": "__precompile__()\n\nmodule MultiscaleGraphSignalTransforms\n\ninclude(\"GraphSignal.jl\")\ninclude(\"GraphPartition.jl\")\ninclude(\"BasisSpecification.jl\")\ninclude(\"common.jl\")\ninclude(\"GHWT.jl\")\ninclude(\"GHWT_2d.jl\")\ninclude(\"GHWT_tf_1d.jl\")\ninclude(\"GHWT_tf_2d.jl\")\ninclude(\"HGLET.jl\")\ninclude(\"GraphSig_Plot.jl\")\ninclude(\"gplot.jl\")\ninclude(\"partition_fiedler.jl\")\n\nusing Reexport\n@reexport using .GraphSignal, .GraphPartition, .BasisSpecification, .GHWT, .GHWT_2d, .GHWT_tf_1d, .GHWT_tf_2d, .HGLET\n\nexport dvec2dmatrix, dmatrix2dvec, levlist2levlengths!, bsfull, bs_haar, bs_level, bs_walsh, dvec_Threshold, rs_to_region, GraphSig_Plot, gplot, gplot!, partition_fiedler\nexport cost_functional, dmatrix_flatten, dmatrix_ldb_flatten\n\n## export functions of NGWP.jl\nusing LinearAlgebra, SparseArrays, LightGraphs, SimpleWeightedGraphs, Clustering\nusing JuMP, Clp, Optim, Statistics, QuadGK, Arpack\nimport Plots: plot, plot!, scatter, scatter!\nimport StatsBase: crosscor\n\ninclude(\"dualgraph.jl\")\ninclude(\"eigDAG_Distance.jl\")\ninclude(\"eigHAD_Distance.jl\")\ninclude(\"eigROT_Distance.jl\")\ninclude(\"eigsROT_Distance.jl\")\ninclude(\"eigTSD_Distance.jl\")\ninclude(\"helpers.jl\")\ninclude(\"LP-HGLET.jl\")\ninclude(\"LP-NGWP.jl\")\ninclude(\"natural_distances.jl\")\ninclude(\"utils.jl\")\ninclude(\"varimax.jl\")\ninclude(\"NGWF.jl\")\ninclude(\"NGWP.jl\")\ninclude(\"PC-NGWP.jl\")\ninclude(\"SunFlowerGraph.jl\")\ninclude(\"VM-NGWP.jl\")\n\nexport eigDAG_Distance, eigHAD_Distance, eigHAD_Affinity\nexport eigROT_Distance, ROT_Distance, eigEMD_Distance\nexport eigsROT_Distance\nexport eigTSD_Distance, K_functional\nexport natural_eigdist\nexport SunFlowerGraph, dualgraph\nexport pc_ngwp, pairclustering, mgslp\nexport vm_ngwp, varimax\nexport lp_ngwp, rising_cutoff, find_pairinds, pair_inds_shadding, lp_ngwp_analysis\nexport LPHGLET_Synthesis, LPHGLET_Analysis_All, HGLET_dictionary, LPHGLET_dictionary\nexport HGLET_DST4_Synthesis, LPHGLET_DST4_Synthesis, HGLET_DST4_dictionary, LPHGLET_DST4_dictionary\nexport HGLET_DST4_Analysis, LPHGLET_DST4_Analysis\nexport unitary_folding_operator, keep_folding!\nexport ngwp_analysis, ngwp_bestbasis, NGWP_jkl\nexport natural_eigdist\nexport nat_spec_filter, ngwf_all_vectors, rngwf_all_vectors, ngwf_vector, frame_approx, rngwf_lx\nexport scatter_gplot, scatter_gplot!, stem, stem!\nexport standardize_eigenvectors!, spike, characteristic, \u03c7, sort_wavelets, transform2D\nexport getall_expansioncoeffs, approx_error_plot, getall_expansioncoeffs2, approx_error_plot2\n\nend\n", "meta": {"hexsha": "070f8944461d3232ab9ee8a50d6b1d4f9808cf64", "size": 2448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MultiscaleGraphSignalTransforms.jl", "max_stars_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_stars_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-23T01:01:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T01:01:53.000Z", "max_issues_repo_path": "src/MultiscaleGraphSignalTransforms.jl", "max_issues_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_issues_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "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/MultiscaleGraphSignalTransforms.jl", "max_forks_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_forks_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "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": 35.4782608696, "max_line_length": 170, "alphanum_fraction": 0.8284313725, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7581770704967518}}
{"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) \u2248 1 atol=atol\n@test value(y) \u2248 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": "using Symbolics\nusing Test\nusing Latexify\nusing ReferenceTests\n\n@variables x y z u(x)\nDx = Differential(x)\n\n# issue 260\n@test Symbolics._toexpr(3*x/y) == :((3x) / y)\n@test Symbolics._toexpr(3*x^y) == :(3x^y)\n\n@test_reference \"latexify_refs/inverse.txt\" latexify(x^-1)\n\n@test_reference \"latexify_refs/frac1.txt\" latexify((z + x*y^-1) / sin(z))\n@test_reference \"latexify_refs/frac2.txt\"  latexify((3x - 7y*z^23) * (z - z^2) / x)\n\n@test_reference \"latexify_refs/minus1.txt\" latexify(x - y)\n@test_reference \"latexify_refs/minus2.txt\" latexify(x - y * z)\n@test_reference \"latexify_refs/minus3.txt\" latexify(sin(x+y-z))\n\n@test_reference \"latexify_refs/unary_minus1.txt\" latexify(-y)\n@test_reference \"latexify_refs/unary_minus2.txt\" latexify(-y * z)\n\n@test_reference \"latexify_refs/derivative1.txt\" latexify(Dx(y))\n@test_reference \"latexify_refs/derivative2.txt\" latexify(Dx(u))\n@test_reference \"latexify_refs/derivative3.txt\" latexify(Dx(x^2 + y^2 + z^2))\n\n@test_reference \"latexify_refs/stable_mul_ordering1.txt\" latexify(x * y)\n@test_reference \"latexify_refs/stable_mul_ordering2.txt\" latexify(y * x)\n\n@test_reference \"latexify_refs/equation1.txt\" latexify(x ~ y + z)\n@test_reference \"latexify_refs/equation2.txt\" latexify(x ~ Dx(y + z))\n\n@test_reference \"latexify_refs/equation_vec1.txt\" latexify([\n    x ~   y +  z\n    y ~   x - 3z\n    z ~ -5x + 4y\n])\n@test_reference \"latexify_refs/equation_vec2.txt\" latexify([\n    Dx(u) ~   z\n    Dx(y) ~   y*x\n])\n", "meta": {"hexsha": "396b557d62959cfba13f4c94ba752cf8f2bfee18", "size": 1448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/latexify.jl", "max_stars_repo_name": "sharanry/Symbolics.jl", "max_stars_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_stars_repo_licenses": ["MIT"], "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/latexify.jl", "max_issues_repo_name": "sharanry/Symbolics.jl", "max_issues_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_issues_repo_licenses": ["MIT"], "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/latexify.jl", "max_forks_repo_name": "sharanry/Symbolics.jl", "max_forks_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 83, "alphanum_fraction": 0.7237569061, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7580890696075013}}
{"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\u03b1 = 0.3\n\u03b4 = 0.1\n\u03b2 = 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]^\u03b1 + (1-\u03b4)*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) .+ \u03b2*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": "x = randn(10)\ny = randn(10)\nr = x .- y\n\n@testset \"Robust Loss\" begin\n    \u03b4 = 0.5\n    rl\u03b4 = RobustLoss(Huber(\u03b4))\n    @test rl\u03b4 isa RobustLoss{HuberRho{\u03b4}}\n    @test rl\u03b4(r) == rl\u03b4(x, y) == sum(ifelse(abs(r\u1d62)\u2264\u03b4, r\u1d62^2/2, \u03b4*(abs(r\u1d62)-\u03b4/2)) for r\u1d62 in r)\n\n    rl\u03b4 = RobustLoss(Andrews(\u03b4))\n    p1(z) = -cos(\u03c0 * z/\u03b4)/(\u03c0/\u03b4)^2\n    p2(z) = p1(\u03b4)\n    @test rl\u03b4(r) \u2248 sum(ifelse(abs(r\u1d62)\u2264\u03b4, p1.(r\u1d62), p2.(r\u1d62)) for r\u1d62 in r)\n\n    rl\u03b4 = RobustLoss(Bisquare(\u03b4))\n    p1(z) = \u03b4^2/6 * (1-(1-(z/\u03b4)^2)^3)\n    p2(z) = p1(\u03b4)\n    @test rl\u03b4(r) \u2248 sum(ifelse(abs(r\u1d62)\u2264\u03b4, p1.(r\u1d62), p2.(r\u1d62)) for r\u1d62 in r)\n\n    rl\u03b4 = RobustLoss(Logistic(\u03b4))\n    @test rl\u03b4(r) \u2248 sum(\u03b4^2 * log(cosh(r\u1d62/\u03b4)) for r\u1d62 in r)\n\n    rl\u03b4 = RobustLoss(FairRho(\u03b4))\n    @test rl\u03b4(r) \u2248 sum(\u03b4^2 * (abs(r\u1d62)/\u03b4 - log(1+abs(r\u1d62/\u03b4))) for r\u1d62 in r)\n\n    rl\u03b4 = RobustLoss(Talwar(\u03b4))\n    p1(z) = z^2/2\n    p2(z) = p1(\u03b4)\n    @test rl\u03b4(r) \u2248 sum(ifelse(abs(r\u1d62)\u2264\u03b4, p1.(r\u1d62), p2.(r\u1d62)) for r\u1d62 in r)\nend\n", "meta": {"hexsha": "10c288abe52c4aee2b873b0c61d14483317dbc4c", "size": 913, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/loss-penalty/robust.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MLJLinearModels.jl-6ee0df7b-362f-4a72-a706-9e79364fb692", "max_stars_repo_head_hexsha": "202e058a2a6fe98871c74c85f3e0a8c1cd7d0a7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-21T03:05:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-21T03:05:43.000Z", "max_issues_repo_path": "test/loss-penalty/robust.jl", "max_issues_repo_name": "Erensu/MLJLinearModels.jl", "max_issues_repo_head_hexsha": "202e058a2a6fe98871c74c85f3e0a8c1cd7d0a7e", "max_issues_repo_licenses": ["MIT"], "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/loss-penalty/robust.jl", "max_forks_repo_name": "Erensu/MLJLinearModels.jl", "max_forks_repo_head_hexsha": "202e058a2a6fe98871c74c85f3e0a8c1cd7d0a7e", "max_forks_repo_licenses": ["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.53125, "max_line_length": 92, "alphanum_fraction": 0.5279299014, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7580786235872028}}
{"text": "\nusing EasyFit\nusing Plots\n\nx = sort(rand(10)) .- 0.5\ny = sort(rand(10)) .- 0.5\n\nplot(layout=(3,2))\nplot!(framestyle=:box,grid=false)\n\nsp=1\nplot!(title=\"Linear fit\",subplot=sp)\nscatter!(x,y,label=\"\",subplot=sp)\nfit = fitlinear(x,y)\nplot!(fit.x,fit.y,label=\"\",linewidth=2,subplot=sp)\n\nsp=2\ny2 = y.^2\nplot!(title=\"Quadratic fit\",subplot=sp)\nscatter!(x,y2,label=\"\",subplot=sp)\nfit = fitquad(x,y2)\nplot!(fit.x,fit.y,label=\"\",linewidth=2,subplot=sp)\n\nsp=3\ny2 = y.^3\nplot!(title=\"Cubic fit\",subplot=sp)\nscatter!(x,y2,label=\"\",subplot=sp)\nfit = fitcubic(x,y2)\nplot!(fit.x,fit.y,label=\"\",linewidth=2,subplot=sp)\n\nsp=4\ny2 = 0.3*exp.(5*y)\nplot!(title=\"Mono-exponential fit\",subplot=sp)\nscatter!(x,y2,label=\"\",subplot=sp)\nfit = fitexp(x,y2)\nplot!(fit.x,fit.y,label=\"\",linewidth=2,subplot=sp)\n\nsp=5\ny2 = 0.3*exp.(5*y) + 0.7*exp.(3*y2)\nplot!(title=\"Bi-exponential fit\",subplot=sp)\nscatter!(x,y2,label=\"\",subplot=sp)\nfit = fitexp(x,y2,n=2)\nplot!(fit.x,fit.y,label=\"\",linewidth=2,subplot=sp)\n\nsp=6\ny2 = y.^5\nplot!(title=\"Spline fit\",subplot=sp)\nscatter!(x,y2,label=\"\",subplot=sp)\nfit = fitexp(x,y2,n=2)\nplot!(fit.x,fit.y,label=\"\",linewidth=2,subplot=sp)\n\nplot!(size=(600,600))\n\n\n\n", "meta": {"hexsha": "d2a56c12e29077e0b93951ca5db0ea375f16951e", "size": 1165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/plots.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": "docs/plots.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": "docs/plots.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": 20.8035714286, "max_line_length": 50, "alphanum_fraction": 0.6660944206, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7580786206658344}}
{"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(\u03bc, link::LogLink) = log_inverse_link.(\u03bc)\n\napply_inverse_link(\u03bc, link::IdentityLink) = identity_inverse_link.(\u03bc)\n\napply_inverse_link(\u03bc, link::SqrtLink) = sqrt_inverse_link.(\u03bc)\n\napply_inverse_link(\u03bc, link::ProbitLink) = probit_inverse_link.(\u03bc)\n\napply_inverse_link(\u03bc, link::LogitLink) = logit_inverse_link.(\u03bc)\n\napply_inverse_link(\u03bc, link::InverseLink) = inverse_inverse_link.(\u03bc)\n\napply_inverse_link(\u03bc, link::CauchitLink) = cauchit_inverse_link.(\u03bc)\n\napply_inverse_link(\u03bc, link::CloglogLink) = cloglog_inverse_link.(\u03bc)\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": "using vOptGeneric\nusing Test, LinearAlgebra\nusing GLPK, GLPKMathProgInterface\n\nfunction run_tests()\n        m = vModel(solver = GLPKSolverMIP())\n\n        @variable(m, x[1:6,1:6], Bin)\n        @variable(m, y, Bin)\n        M = 50\n        p1 =   [M 4 5 M M M;\n                M M 2 1 2 7;\n                M M M 5 2 M;\n                M M 5 M M 3;\n                M M M M M 4;\n                M M M M M M]\n        p2 =   [M 3 1 M M M;\n                M M 1 4 2 2;\n                M M M 1 7 M;\n                M M 1 M M 2;\n                M M M M M 2;\n                M M M M M M]\n\n        @addobjective(m, Min , sum(x[i,j]*p1[i,j] for i=1:6, j=1:6))\n        @addobjective(m, Min , sum(x[i,j]*p2[i,j] for i=1:6, j=1:6))\n        @constraint(m, sum(x[1,j] for j = 1:6) == 1)\n        @constraint(m, sum(x[i,6] for i = 1:6) == 1)\n        @constraint(m, cstr[i=2:5], sum(x[i,j] for j = 1:6) - sum(x[j,i] for j =1:6) == 0)\n\n        solve(m, method=:epsilon)\n\n        Y_N = getY_N(m)\n        f1 = map(x -> x[1], Y_N)\n        f2 = map(x -> x[2], Y_N)\n\n        @test f1 == [8.0,10.0,11.0,13.0]\n        @test f2 == [9.0,7.0,5.0,4.0]\n        @test getvalue(x, 1) == [0.0 1.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 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 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0]\n        printX_E(m)\n\n        writeMOP(m, \"test.txt\")\n        m = parseMOP(\"test.txt\", solver = GLPKSolverMIP())\n        solve(m, method=:dichotomy)\n        Y_N = getY_N(m)\n        f1 = map(x -> x[1], Y_N)\n        f2 = map(x -> x[2], Y_N)\n        @test f1 == [8.0, 11.0, 13.0]\n        @test f2 == [9.0, 5.0, 4.0]\n\n        m = vModel(solver = GLPKSolverMIP())\n        # using CPLEX\n        # m = vModel(solver = CplexSolver())\n\n        p1 = [77,94,71,63,96,82,85,75,72,91,99,63,84,87,79,94,90,60,69,62]\n        p2 = [65,90,90,77,95,84,70,94,66,92,74,97,60,60,65,97,93,60,69,74]\n        w = [80,87,68,72,66,77,99,85,70,93,98,72,100,89,67,86,91,79,71,99]\n        c = 900\n        size = length(p1)\n\n        @variable(m, x[1:size], Bin)\n        @addobjective(m, Max, dot(x, p1))\n        @addobjective(m, Max, dot(x, p2))\n        @constraint(m, dot(x, w) <= c)\n\n        solve(m, method=:chalmet)\n\n        Y_N = getY_N(m)\n        f1 = map(x -> x[1], Y_N)\n        f2 = map(x -> x[2], Y_N)\n\n        @test f1 == [918.0, 924.0, 927.0, 934.0, 935.0, 940.0, 943.0, 948.0, 949.0, 952.0, 955.0]\n        @test f2 == [984.0, 975.0, 972.0, 971.0, 947.0, 943.0, 940.0, 939.0, 915.0, 909.0, 906.0]\n        @test getvalue(x, 1) == [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0]\n\n\n        solve(m, method=:lex)\n        Y_N = getY_N(m)\n        @test Y_N == [[955.0, 906.0], [918.0, 984.0]]\nend\n\nrun_tests()", "meta": {"hexsha": "ed8b54e1297c2b57e6d53c836415190b54856175", "size": 2737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaTagBot/vOptGeneric.jl", "max_stars_repo_head_hexsha": "d3cdc0508fb4bdbcbcb72d826773d93c8278002a", "max_stars_repo_licenses": ["MIT"], "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": "JuliaTagBot/vOptGeneric.jl", "max_issues_repo_head_hexsha": "d3cdc0508fb4bdbcbcb72d826773d93c8278002a", "max_issues_repo_licenses": ["MIT"], "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": "JuliaTagBot/vOptGeneric.jl", "max_forks_repo_head_hexsha": "d3cdc0508fb4bdbcbcb72d826773d93c8278002a", "max_forks_repo_licenses": ["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.7901234568, "max_line_length": 182, "alphanum_fraction": 0.4508586043, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7580786127825163}}
{"text": "#using FemAdjoint\nusing Test, JLD2, UnicodePlots\nusing LinearAlgebra, ForwardDiff, Arpack\nusing SparseArrays, SparseDiffTools, Symbolics \nusing FemAdjoint\n\n# load mesh and data for tests\nmeshfile = \"$(@__DIR__)/data/diskmesh.jld2\"\nJLD2.@load(meshfile, p, t)\nnp, nt = size(p, 1), size(t, 1)\n\u03b5 = 1e-5\nu, v = 2 * rand(np) .- 1, 2 * rand(np) .- 1\nx, dp = p, 2 * rand(size(p)...) .- 1\nxp, xm = p .+ \u03b5 * dp, p .- \u03b5 * dp\nSK, SM = FemAdjoint.assembKM_P12D(p, t)\nIK, JK = FemAdjoint.indKM_sparse(t)\nIM, JM = FemAdjoint.indKM_sparse(t)\nK = sparse(IK, JK, SK, np, np)\nM = sparse(IM, JM, SM, np, np)\n\n@testset \"mesh data\" begin   \n    @test size(p, 1) == 560\n    @test size(t, 1) == 1045 \nend\n\n@testset \"first assembly\" begin   \n    @test length(IK) == length(JK)\n    @test length(IK) == length(SK)\n    @test length(IM) == length(JM)\n    @test length(IM) == length(SM)\nend\n\n\n@testset \"test eval function\" begin   \n    u, v = 2 * rand(np) .- 1, 2 * rand(np) .- 1\n    @test abs(dot(K * u, v) - FemAdjoint.costKproduv(p, t, u, v)) < 1e-8\nend\n\nf = x -> FemAdjoint.costKproduv(x, t, u, v)\nfp, fm = f(xp), f(xm)\n@time g = ForwardDiff.gradient(f, x)\n@time g = ForwardDiff.gradient(f, x)\n\n@testset \"test eval gradient dot function\" begin \n    @test abs(dot(g, dp) - (fp - fm) / (2 * \u03b5)) < 1e-4\nend\ndisplay(K)\nprint(\"\\n\")\nprintln(\"directional derivative $(abs(dot(g, dp)))\")\n\n#-------------------------------------------------------------------------------\n# square mesh / eigenvalue test\nmeshfile = \"$(@__DIR__)/data/squaremesh.jld2\"\nJLD2.@load(meshfile, p, t, jacK, jacM, ps, ts, jacKs, jacMs)\nnp, nt = size(p, 1), size(t, 1)\nSK, SM = FemAdjoint.assembKM_P12D(p, t)\nIK, JK = FemAdjoint.indKM_sparse(t)\nIM, JM = FemAdjoint.indKM_sparse(t)\nK = sparse(IK, JK, SK, np, np)\nM = sparse(IM, JM, SM, np, np)\nIb = unique(FemAdjoint.btri(t)[:])\nK += sparse(Ib, Ib, fill(1e8, length(Ib)), np, np) # Dirichlet conditions\n\n\u03bb, U = eigs(K, M, nev = 10, which = :SM, tol = 0., maxiter = 30_000)\n@testset \"test eigenvalue\" begin\n    @test abs(\u03bb[1] - pi ^ 2 / 2) < 1e-2\nend\n# plot\nFemAdjoint.plotunicode(U[:, 4])\n\n#-------------------------------------------------------------------------------\n#p, t, jac = ps, ts, jacs\ny = similar(FemAdjoint.assembKM_P12D(p, t)[1])\nSK, SM = FemAdjoint.assembKM_P12D(p, t)\nSKi, SMi = similar(SK), similar(SM)\nFemAdjoint.assembK_P12D_inplace!(p, t, SKi)\nFemAdjoint.assembM_P12D_inplace!(p, t, SMi)\n@testset \"test in place assemble\" begin\n    @test maximum(abs.(SK .- SKi)) < 1e-8\n    @test maximum(abs.(SM .- SMi)) < 1e-8\nend\nfK(y, x) = FemAdjoint.assembK_P12D_inplace!(x, t, y)\n# to speedup test use a precomputed jac matrix\n#@time sparsity_pattern = Symbolics.jacobian_sparsity(fs, y, p[:])\n#jacK = Float64.(sparse(sparsity_pattern))\ncolors = matrix_colors(jacK)\n@time J = forwarddiff_color_jacobian!(jacK, fK, p[:], colorvec = colors)\n@time J = forwarddiff_color_jacobian!(jacK, fK, p[:], colorvec = colors)\ndisplay(J)\n\n#-------------------------------------------------------------------------------\n# test adjoint approach for costKproduv cost function\ninclude(\"test_costKproduv.jl\")\n#-------------------------------------------------------------------------------\n# test adjoint approach for costnormU cost function\ninclude(\"test_costnormU.jl\")\n#-------------------------------------------------------------------------------\n# test direct adjoint approach for costnormU cost function (definitely simpler!!)\ninclude(\"test_costnormU_direct.jl\")", "meta": {"hexsha": "a20b5154e2c30fd0903e69231c234fc895cbd7f5", "size": 3446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "edljk/FemAdjoint.jl", "max_stars_repo_head_hexsha": "ec1b6704aae33a194b9ccae00d4dfffb15c9b799", "max_stars_repo_licenses": ["MIT"], "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": "edljk/FemAdjoint.jl", "max_issues_repo_head_hexsha": "ec1b6704aae33a194b9ccae00d4dfffb15c9b799", "max_issues_repo_licenses": ["MIT"], "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": "edljk/FemAdjoint.jl", "max_forks_repo_head_hexsha": "ec1b6704aae33a194b9ccae00d4dfffb15c9b799", "max_forks_repo_licenses": ["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.8080808081, "max_line_length": 81, "alphanum_fraction": 0.5861868833, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7580786114221288}}
{"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| \u2265 |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\u00f8ller, Quasi double-precision in floating-point addition, BIT\n      Numerical Mathematics 5, pp. 37\u201350, 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| \u2265 |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\u2013242, 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(\u03c6\u2080, \u03bb\u2080, \u03c6, \u03bb)\n\nCoordinate transformation between geographic and plane rectangular coordinates on the Gauss-Kr\u00fcger 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- \u03c6\u2080, \u03bb\u2080 : latitude of origin and central meridian\n- \u03c6 , \u03bb  : 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(\u03c6\u2080, \u03bb\u2080, \u03c6, \u03bb)\n\n    \u03c6\u2080 = deg2rad(\u03c6\u2080)\n    \u03bb\u2080 = deg2rad(\u03bb\u2080)\n    \u03c6 = deg2rad(\u03c6)\n    \u03bb = deg2rad(\u03bb)\n\n    S\u0305\u03c6\u2080 = arclength(\u03c6\u2080)\n\n    ncoef1 = 2sqrt(n)/(1+n)\n\n    t = sinh(atanh(sin(\u03c6)) - ncoef1*atanh(ncoef1*sin(\u03c6)))\n    t\u0305 = sqrt(1+t^2)\n    \u03bbc = cos(\u03bb-\u03bb\u2080)\n    \u03bbs = sin(\u03bb-\u03bb\u2080)\n    \u03be\u2032 = atan(t,\u03bbc)\n    \u03b7\u2032 = atanh(\u03bbs/t\u0305)\n\n    # \u03b1 terms\n    \u03b1coef = [1/2   -2/3    5/16        41/180     -127/288; # \u03b1\u2081\n             0.0  13/48    -3/5      557/1440      281/630; # \u03b1\u2082\n             0.0    0.0  61/240      -103/140  15061/26880; # \u03b1\u2083\n             0.0    0.0     0.0  49561/161280     -179/168; # \u03b1\u2084\n             0.0    0.0     0.0           0.0  34729/80460; # \u03b1\u2085\n            ]\n    \u03b1j = \u03b1coef * [n^k for k=1:5]\n\n    N = A\u0305*(\u03be\u2032 + sum([\u03b1j[j]sin(2j*\u03be\u2032)cosh(2j*\u03b7\u2032) for j=1:5])) - S\u0305\u03c6\u2080\n    E = A\u0305*(\u03b7\u2032 + sum([\u03b1j[j]cos(2j*\u03be\u2032)sinh(2j*\u03b7\u2032) for j=1:5]))\n\n    return [N E]\nend\n# -------------------------------------\n\"\"\"\n    E, N = lonlat2xy(\u03bb\u2080, \u03c6\u2080, \u03bb, \u03c6)\n\nSee [`lanlon2yx`](@ref)\n\"\"\"\nlonlat2xy(\u03bb\u2080, \u03c6\u2080, \u03bb, \u03c6) = reverse(latlon2yx(\u03c6\u2080, \u03bb\u2080, \u03c6, \u03bb), dims=2)\n\n# -------------------------------------\nfunction latlon2yx_ja(zone::Integer, \u03c6, \u03bb)\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,:]..., \u03c6, \u03bb)\nend\n# -------------------------------------\nlonlat2xy_ja(zone::Integer, \u03bb, \u03c6)  = reverse(latlon2yx_ja(zone, \u03c6, \u03bb), 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 two27 = Float64(1<<27)\nconst two12 = Float32(1<<12)\nconst two6  = Float16(1<<6)\n\n\"\"\"\n    extractscalar\n\nSplit a value relative to an integral power of 2\n\nhi is the high order part of p, lo is the residual part\nhi + lo === p\n\"\"\"\n\nfor (T,P) in ((:Float64, 53), (:Float32, 24), (:Float16, 11))\n  @eval begin\n    @inline function extractscalar(value::$T)\n        powoftwo =  ldexp(one($T), ($P- exponent(value)) >> 1) # P == precision(Float64)\n        return extractscalar(powoftwo, value)\n    end\n  end\nend\n\nfunction extractscalar(powoftwo::T, value::T) where {T}\n   hi = (powoftwo + value) - powoftwo\n   lo = value - hi\n   return hi, lo\nend\n\n\n\n\"\"\"\n    two_cube(a)\n    \nComputes `s = fl(a*a*a)` and `e1 = err(a*a*a)`.\n\"\"\"\nfunction two_cube(value::T) where {T}\n    hi, lo = extractscalar(value)\n    hhh  = three_prod(hi, hi, hi)\n    hhl  = three_prod(hi, hi, 3*lo)\n    hll  = three_prod(hi, 3*lo, lo)\n    lll  = three_prod(lo, lo, lo)\n    \n    himh = four_sum(hhh[1], hhl[1], hhh[2], hll[1])\n    mllo = four_sum(hhl[2], hll[2], lll[1], lll[2])\n    hilo = four_sum(himh[1], himh[2], mllo[1], mllo[2])\n\n    return hilo[1], hilo[2]\nend\n\n\"\"\"\n    three_cube(a)\n    \nComputes `s = fl(a*a*a)` and `e1 = err(a*a*a), e2 = err(e1)`.\n\"\"\"\nfunction three_cube(value::T) where {T}\n    hi, lo = extractscalar(value)\n    hhh  = three_prod(hi, hi, hi)\n    hhl  = three_prod(hi, hi, 3*lo)\n    hll  = three_prod(hi, 3*lo, lo)\n    lll  = three_prod(lo, lo, lo)\n    \n    himh = four_sum(hhh[1], hhl[1], hhh[2], hll[1])\n    mllo = four_sum(hhl[2], hll[2], lll[1], lll[2])\n    hilo = four_sum(himh[1], himh[2], mllo[1], mllo[2])\n\n    return hilo[1], hilo[2], hilo[3]\nend\n\n\"\"\"\n    four_cube(a)\n    \nComputes `s = fl(a*a*a)` and `e1 = err(a*a*a), e2 = err(e1), e3 = err(e2)`.\n\"\"\"\nfunction three_cube(value::T) where {T}\n    hi, lo = extractscalar(value)\n    hhh  = three_prod(hi, hi, hi)\n    hhl  = three_prod(hi, hi, 3*lo)\n    hll  = three_prod(hi, 3*lo, lo)\n    lll  = three_prod(lo, lo, lo)\n    \n    himh = four_sum(hhh[1], hhl[1], hhh[2], hll[1])\n    mllo = four_sum(hhl[2], hll[2], lll[1], lll[2])\n    hilo = four_sum(himh[1], himh[2], mllo[1], mllo[2])\n\n    return hilo\nend\n", "meta": {"hexsha": "aeb225fa4289905b14bd677ee70353ec911a247b", "size": 2157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/extractscalar.jl", "max_stars_repo_name": "UnofficialJuliaMirror/ErrorfreeArithmetic.jl-90fa49ef-747e-5e6f-a989-263ba693cf1a", "max_stars_repo_head_hexsha": "2012b1372d7182ed28a739e2901c7426f5b093c2", "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/extractscalar.jl", "max_issues_repo_name": "UnofficialJuliaMirror/ErrorfreeArithmetic.jl-90fa49ef-747e-5e6f-a989-263ba693cf1a", "max_issues_repo_head_hexsha": "2012b1372d7182ed28a739e2901c7426f5b093c2", "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/extractscalar.jl", "max_forks_repo_name": "UnofficialJuliaMirror/ErrorfreeArithmetic.jl-90fa49ef-747e-5e6f-a989-263ba693cf1a", "max_forks_repo_head_hexsha": "2012b1372d7182ed28a739e2901c7426f5b093c2", "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": 24.7931034483, "max_line_length": 88, "alphanum_fraction": 0.5767269356, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7580672551025237}}
{"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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.22\"\n\n# \u2554\u2550\u2561 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tlambda, N = 1, 10^6\n\txGrid = 0:6\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.22\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u255084a73e9a-2165-11eb-3620-d7ddf9c07aff\n# \u2560\u255084a76f3c-2165-11eb-0eeb-1bb55507bb51\n# \u255f\u250070182cd8-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\u1d40x'/\u2113\u00b2\n```\nwith length scale ``\u2113``.\n\"\"\"\nmutable struct LinIso <: Kernel\n    \"Squared length scale\"\n    \u21132::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.\u21132\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\u21132 = 1/lin.\u21132\n    @inbounds @simd for I in eachindex(cK,data.XtX)\n        cK[I] = data.XtX[I]*i\u21132\n    end\n    return cK\nend\n\nget_params(lin::LinIso) = Float64[log(lin.\u21132) / 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.\u21132 = exp(2 * hyp[1])\nend\n\n@inline dk_dll(lin::LinIso, xTy::Float64) = -2 * _cov(lin,xTy)\n@inline function dKij_d\u03b8p(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\u03b8p(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!(\u2207f, x)\n    \u2207f[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    \u2207f[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    \u2207f\nend\n\nfunction himmelblau_fg!(\u2207f, x)\n    \u2207f = himmelblau_g!(\u2207f, x)\n    fx = himmelblau!(x)\n    return fx, \u2207f\nend\nfunction himmelblau_fgh!(\u2207f, \u2207\u00b2f, x)\n    \u2207\u00b2f = himmelblau_h!(\u2207\u00b2f, x)\n    fx, \u2207f = himmelblau_fg!(\u2207f, x)\n    return fx, \u2207f, \u2207\u00b2f\nend\nfunction himmelblau_h!(\u2207\u00b2f, x)\n    \u2207\u00b2f[1, 1] = 12.0 * x[1]^2 + 4.0 * x[2] - 44.0 + 2.0\n    \u2207\u00b2f[1, 2] = 4.0 * x[1] + 4.0 * x[2]\n    \u2207\u00b2f[2, 1] = \u2207\u00b2f[1, 2]\n    \u2207\u00b2f[2, 2] = 2.0 + 4.0 * x[1] + 12.0 * x[2]^2 - 28.0\n    return \u2207\u00b2f\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\u00e5 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": "using Test\nusing Bigsimr\nusing LinearAlgebra\nusing Distributions\n\n@testset \"Correlation Functions\" begin\n\n    r_negdef = [\n        1.00 0.82 0.56 0.44\n        0.82 1.00 0.28 0.85\n        0.56 0.28 1.00 0.22\n        0.44 0.85 0.22 1.00\n    ]\n\n    @testset \"Nearest positive definite correlation matrix\" begin\n        r = cor_nearPD(r_negdef)\n        @test Bigsimr.iscorrelation(r)\n\n        # Must respect input eltype\n        for T in [Float64, Float32, Float64]\n            @test eltype(cor_nearPD(Matrix{T}(r_negdef))) === T\n        end\n    end\n\n    @testset \"Nearest positive semi-definite correlation matrix\" begin\n        r = cor_nearPD(r_negdef, 0.0)\n        \u03bb = eigvals(r)\n        @test issymmetric(r)\n        @test all(\u03bb .\u2265 0)\n        @test all(diag(r) .== 1.0)\n        @test all(-1.0 .\u2264 r .\u2264 1.0)\n    end\n\n    @testset \"Fast near positive definite correlation matrix\" begin\n        r = cor_fastPD(r_negdef)\n        @test Bigsimr.iscorrelation(r)\n\n        # Must respect input eltype\n        test_types = [Float64, Float32, Float16]\n        for T in test_types\n            @test eltype(cor_fastPD(Matrix{T}(r_negdef))) === T\n        end\n    end\nend\n\n@testset \"Random Correlation Generation\" begin\n    \n    @testset \"Random postive definite correlation matrix\" begin\n        r = cor_randPD(100)\n        @test Bigsimr.iscorrelation(r)\n\n        # The element type must be respected\n        test_types = [Float64, Float32, Float16]\n        for T in test_types\n            @test eltype(cor_randPD(T, 4)) === T\n        end\n\n        # Must work for numbers with integer representations\n        test_types = [Float64, Float32, Float16, Rational, Int64, Int32, Int16]\n        for T in test_types\n            @test_nowarn cor_randPD(T(4))\n            @test_nowarn cor_randPD(Float64, T(4))\n            @test_nowarn cor_randPD(Float32, T(4))\n            @test_nowarn cor_randPD(Float16, T(4))\n            \n            for S in test_types\n                @test_nowarn cor_randPD(T(4), S(3))\n                @test_nowarn cor_randPD(Float64, T(4), S(3))\n                @test_nowarn cor_randPD(Float32, T(4), S(3))\n                @test_nowarn cor_randPD(Float16, T(4), S(3))\n            end\n        end\n\n        # `d` must not be less than 1\n        @test_throws AssertionError cor_randPD(-1)\n        @test_throws AssertionError cor_randPD(Float64, -1)\n        @test_throws AssertionError cor_randPD(Float32, -1)\n        @test_throws AssertionError cor_randPD(Float16, -1)\n\n        # `k` must not be larger than `d`\n        @test_throws AssertionError cor_randPD(4, 5)\n        @test_throws AssertionError cor_randPD(Float64, 4, 5)\n        @test_throws AssertionError cor_randPD(Float32, 4, 5)\n        @test_throws AssertionError cor_randPD(Float16, 4, 5)\n\n        # `k` must not be less than 1\n        @test_throws AssertionError cor_randPD(4, 0)\n        @test_throws AssertionError cor_randPD(Float64, 4, 0)\n        @test_throws AssertionError cor_randPD(Float32, 4, 0)\n        @test_throws AssertionError cor_randPD(Float16, 4, 0)\n    end\n\n    @testset \"Random positive semi-definite correlation matrix\" begin\n        r = cor_randPSD(100)\n        \u03bb = eigvals(r)\n        @test issymmetric(r)\n        @test all(\u03bb .\u2265 0)\n        @test all(diag(r) .== 1.0)\n        @test all(-1.0 .\u2264 r .\u2264 1.0)\n\n        # The element type must be respected\n        test_types = [Float64, Float32, Float16]\n        for T in test_types\n            @test eltype(cor_randPSD(T, 4)) === T\n        end\n\n        # Must work for numbers with integer representations\n        test_types = [Float64, Float32, Float16, Rational, Int64, Int32, Int16]\n        for T in test_types\n            @test_nowarn cor_randPSD(T(4))\n            @test_nowarn cor_randPSD(Float64, T(4))\n            @test_nowarn cor_randPSD(Float32, T(4))\n            @test_nowarn cor_randPSD(Float16, T(4))\n            \n            for S in test_types\n                @test_nowarn cor_randPSD(T(4), S(3))\n                @test_nowarn cor_randPSD(Float64, T(4), S(3))\n                @test_nowarn cor_randPSD(Float32, T(4), S(3))\n                @test_nowarn cor_randPSD(Float16, T(4), S(3))\n            end\n        end\n\n        # `d` must not be less than 1\n        @test_throws AssertionError cor_randPSD(-1)\n        @test_throws AssertionError cor_randPSD(Float64, -1)\n        @test_throws AssertionError cor_randPSD(Float32, -1)\n        @test_throws AssertionError cor_randPSD(Float16, -1)\n\n        # `k` must not be larger than `d`\n        @test_throws AssertionError cor_randPSD(4, 5)\n        @test_throws AssertionError cor_randPSD(Float64, 4, 5)\n        @test_throws AssertionError cor_randPSD(Float32, 4, 5)\n        @test_throws AssertionError cor_randPSD(Float16, 4, 5)\n\n        # `k` must not be less than 1\n        @test_throws AssertionError cor_randPSD(4, 0)\n        @test_throws AssertionError cor_randPSD(Float64, 4, 0)\n        @test_throws AssertionError cor_randPSD(Float32, 4, 0)\n        @test_throws AssertionError cor_randPSD(Float16, 4, 0)\n    end\n\nend\n\n@testset \"Correlation Utilities\" begin\n\n    cor_types = (Pearson, Spearman, Kendall)\n\n    @testset \"Correlation calculation\" begin\n        # Must work for any floating point matrix or vector pair\n        test_types = [Float64, Float32, Float16]\n        for T in test_types\n            A = rand(T, 200, 4)\n            x, y = rand(T, 100), rand(T, 100)\n\n            for C in cor_types\n                @test_nowarn cor(A, C)\n                @test_nowarn cor(x, y, C)\n\n                @test_nowarn cor_fast(A, C)\n            end\n        end\n\n    end\n\n    @testset \"Correlation to correlation conversion\" begin\n\n        # Converting type A -> A must result in the same matrix\n        for C in cor_types\n            r = cor_randPD(4)\n            @test r == cor_convert(r, C, C)\n        end\n\n        # Must map (-1, 0, 1) onto itself within numerical error\n        for C1 in cor_types\n            for C2 in cor_types\n                @test cor_convert( 0.0, C1, C2)  == 0.0\n                @test cor_convert( 1.0, C1, C2)   \u2264 1.0\n                @test cor_convert( 1.0, C1, C2)   \u2248 1.0\n                @test cor_convert(-1.0, C1, C2)  \u2265 -1.0\n                @test cor_convert(-1.0, C1, C2)  \u2248 -1.0\n            end\n        end\n\n        # Must work for each type\n        test_types = [Float64, Float32, Float16, Rational]\n        for T in test_types\n            for C1 in cor_types\n                for C2 in cor_types\n                    @test_nowarn cor_convert(T(0.5), C1,  C2)\n                end\n            end\n        end\n\n        # Must respect these input eltypes\n        test_types = [Float64, Float32, Float16]\n        for T in test_types\n            for C1 in cor_types\n                for C2 in cor_types\n                    @test eltype(cor_convert(T(0.5), C1,  C2))  === T\n                end\n            end\n        end\n    end\n\n    @testset \"Constrain to Correlation\" begin\n        test_types = [Float64, Float32, Float16]\n        for T in test_types\n            A = rand(T, 10, 10)\n            @test_nowarn cor_constrain(A)\n            @test eltype(cor_constrain(A)) === T\n        end\n    end\n\n    @testset \"Covariance to Correlation\" begin\n        test_types = [Float64, Float32, Float16]\n        for T in test_types\n            R = cor_randPSD(T, 4, 3)\n            @test_nowarn cov2cor(R)\n            @test eltype(cov2cor(R)) === T\n        end\n    end\n\n    @testset \"Correlation Bounds\" begin\n        A, B = NegativeBinomial(20, 0.2), LogNormal(3, 1)\n        dist_types = (A, B)\n\n        # Must work for any univariate distribution and correlation type\n        for D1 in dist_types\n            for D2 in dist_types\n                for C in cor_types\n                    @test_nowarn cor_bounds(D1, D2, C)\n                end\n            end\n        end\n\n        # Must work for any number with an integer representation\n        test_types = [Float64, Float32, Float16, Int64, Int32, Int16]\n        for T in test_types\n            @test_nowarn cor_bounds(A, B, n_samples=T(10_000))\n        end\n\n        test_types = [Float64, Float32]\n        for T in test_types\n            @test_throws InexactError cor_bounds(A, B, n_samples=T(10_000.5))\n        end \n    end\n\nend\n", "meta": {"hexsha": "44ea4535361dbaeb7325d95b3c7e97982cd1f262", "size": 8181, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Correlation.jl", "max_stars_repo_name": "adknudson/MvSim.jl", "max_stars_repo_head_hexsha": "6c3085289a5e23441f5f0db90f2b3cbbb9b49afc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-12T12:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T12:27:15.000Z", "max_issues_repo_path": "test/Correlation.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": "test/Correlation.jl", "max_forks_repo_name": "adknudson/bigsimr.jl", "max_forks_repo_head_hexsha": "1843a0607bcaee9b7724842df22aa42e176c910c", "max_forks_repo_licenses": ["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.8554216867, "max_line_length": 79, "alphanum_fraction": 0.5753575358, "num_tokens": 2366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7580444237239315}}
{"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": "\nusing Random\nusing LinearAlgebra\n\nusing JuMP\nimport GLPK\nusing Plots\n\n\nRandom.seed!(314)\n\nm = 12  # number of clients\nn = 5  # number of facility locations\n\n# Clients' locations\nXc = rand(m)\nYc = rand(m)\n\n# Facilities' potential locations\nXf = rand(n)\nYf = rand(n)\n\n# Fixed costs\nf = ones(n);\n\n# Distance\nc = zeros(m, n)\nfor i in 1:m\n    for j in 1:n\n        c[i, j] = norm([Xc[i] - Xf[j], Yc[i] - Yf[j]], 2)\n    end\nend\n\n\n# Display the data\nscatter(Xc, Yc, label = \"Clients\", markershape=:circle, markercolor=:blue)\nscatter!(Xf, Yf, label=\"Facility\", \n    markershape=:square, markercolor=:white, markersize=6,\n    markerstrokecolor=:red, markerstrokewidth=2\n)\n\n\n# Create a JuMP model\nufl = Model(GLPK.Optimizer)\n\n# Variables\n@variable(ufl, y[1:n], Bin);\n@variable(ufl, x[1:m, 1:n], Bin);\n\n# Each client is served exactly once\n@constraint(ufl, client_service[i in 1:m],\n    sum(x[i, j] for j in 1:n) == 1\n);\n\n# A facility must be open to serve a client\n@constraint(ufl, open_facility[i in 1:m, j in 1:n],\n    x[i, j] <= y[j]\n)\n\n# Objective\n@objective(ufl, Min, f'y + sum(c .* x));\n\n\n# Solve the uncapacitated facility location problem with GLPK\noptimize!(ufl)\nprintln(\"Optimal value: \", objective_value(ufl))\n\nx_ = value.(x) .> 1 - 1e-5\ny_ = value.(y) .> 1 - 1e-5\n\n# Display clients\np = scatter(Xc, Yc, markershape=:circle, markercolor=:blue, label=nothing)\n\n# Show open facility\nmc = [(y_[j] ? :red : :white) for j in 1:n]\nscatter!(Xf, Yf, \n    markershape=:square, markercolor=mc, markersize=6,\n    markerstrokecolor=:red, markerstrokewidth=2,\n    label=nothing\n)\n\n# Show client-facility assignment\nfor i in 1:m\n    for j in 1:n\n        if x_[i, j] == 1\n           plot!([Xc[i], Xf[j]], [Yc[i], Yf[j]], color=:black, label=nothing)\n        end\n    end\nend\n\ndisplay(p)\n\n\n# Demands\na = rand(1:3, m);\n\n# Capacities\nq = rand(5:10, n);\n\n\n# Display the data\nscatter(Xc, Yc, label=nothing,\n    markershape=:circle, markercolor=:blue, markersize= 2 .*(2 .+ a)\n)\n\nscatter!(Xf, Yf, label=nothing, \n    markershape=:rect, markercolor=:white, markersize= q,\n    markerstrokecolor=:red, markerstrokewidth=2\n)\n\n\n# Create a JuMP model\ncfl = Model(GLPK.Optimizer)\n\n# Variables\n@variable(cfl, y[1:n], Bin);\n@variable(cfl, x[1:m, 1:n], Bin);\n\n# Each client is served exactly once\n@constraint(cfl, client_service[i in 1:m], sum(x[i, :]) == 1)\n\n# Capacity constraint\n@constraint(cfl, capacity, x'a .<= (q .* y))\n\n# Objective\n@objective(cfl, Min, f'y + sum(c .* x));\n\n\n# Solve the problem\noptimize!(cfl)\nprintln(\"Optimal value: \", objective_value(cfl))\n@test termination_status(cfl) == MOI.OPTIMAL\n\n\nx_ = value.(x) .> 1 - 1e-5\ny_ = value.(y) .> 1 - 1e-5\n\n# Display the solution\np = scatter(Xc, Yc, label=nothing,\n    markershape=:circle, markercolor=:blue, markersize= 2 .*(2 .+ a)\n)\n\nmc = [(y_[j] ? :red : :white) for j in 1:n]\nscatter!(Xf, Yf, label=nothing, \n    markershape=:rect, markercolor=mc, markersize=q,\n    markerstrokecolor=:red, markerstrokewidth=2\n)\n\n# Show client-facility assignment\nfor i in 1:m\n    for j in 1:n\n        if x_[i, j] == 1\n            plot!([Xc[i], Xf[j]], [Yc[i], Yf[j]], color=:black, label=nothing)\n            break\n        end\n    end\nend\n\ndisplay(p)\n", "meta": {"hexsha": "840cff31f1b410d11020be5a87951c9f04e6f80c", "size": 3171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modelling/facility_location.jl", "max_stars_repo_name": "mthelm85/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "b2285a74d05dc0c0e99df2ac999277c34e670afd", "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": "test/modelling/facility_location.jl", "max_issues_repo_name": "mthelm85/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "b2285a74d05dc0c0e99df2ac999277c34e670afd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-04T18:36:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-04T18:36:58.000Z", "max_forks_repo_path": "test/modelling/facility_location.jl", "max_forks_repo_name": "mthelm85/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "b2285a74d05dc0c0e99df2ac999277c34e670afd", "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": 19.81875, "max_line_length": 78, "alphanum_fraction": 0.637653737, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7580135345756662}}
{"text": "module KrylovMethods\n\t\n\timport Base.BLAS\n\t\n\tinclude(\"cg.jl\")\n\tinclude(\"blockCG.jl\")\n\tinclude(\"cgls.jl\")\n\tinclude(\"bicgstb.jl\")\n\tinclude(\"blockBiCGSTB.jl\")\n\tinclude(\"gmres.jl\")\t\n\tinclude(\"lanczosBidiag.jl\")\n\tinclude(\"ssor.jl\")\t\n\tinclude(\"lsqr.jl\")\t\n\tinclude(\"lanczosTridiag.jl\")\n\tinclude(\"lanczos.jl\")\n\tinclude(\"minres.jl\")\n\tinclude(\"gs.jl\")\nend", "meta": {"hexsha": "6e1653b0d6074b99985593fbcafff2f210f8a317", "size": 344, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/KrylovMethods.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/KrylovMethods.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/KrylovMethods.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": 19.1111111111, "max_line_length": 29, "alphanum_fraction": 0.6976744186, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693631290971, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7580135197559031}}
{"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\u03be= 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*\u03be[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*\u03be[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    \u2208(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 \u2208(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] \u2209 A[i, j]\n                return false\n            end\n        end\n    end\n    return true\nend\n\n\"\"\"\n    \u2286(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] \u2286 B[i, j]` for all `i, j`.\n\"\"\"\nfunction \u2286(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] \u2286 B[i, j])\n            return false\n        end\n    end\n    return true\nend\n\n\"\"\"\n    \u2229(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] \u2229 B[i, j]` for each `i` and `j`.\n\"\"\"\nfunction \u2229(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 \u2229 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 [`\u222a`](@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    \u222a(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] \u222a B[i, j]` for each `i` and `j`.\n\"\"\"\n\u222a(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": "function ncsize!(S, present, g, i, j)\r\n\t!present[i] && return 0\r\n\tS[i] != 0 && error(\"the graph is not acyclic\")\r\n\tS[i] = 1\r\n\tfor k in neighbors(g,i)\r\n\t\tif k != j && present[k]\r\n\t\t\tS[i] += ncsize!(S, present, g, k, i)\r\n\t\tend\r\n\tend\r\n\treturn S[i]\r\nend\r\n\r\n\"\"\"\r\nOptimally break tree until the giant component size is less than threshold.\r\n\"\"\"\r\nfunction tree_break!(present, g, threshold)\r\n    S = zeros(Int, nv(g))\r\n    H = MutableBinaryMaxHeap{Tuple{Int64,Int64}}()\r\n    for i in vertices(g)\r\n        if present[i] && S[i] == 0\r\n            push!(H, (ncsize!(S, present, g, i, nothing), i))\r\n        end\r\n    end\r\n\r\n    attack_nodes = Int[]\r\n    scomps = Int[]\r\n    while !isempty(H)\r\n        scomp, i = pop!(H)\r\n        sender = nothing\r\n        while true\r\n            sizes = [(S[k],k) for k in neighbors(g,i) if k != sender && present[k]]\r\n            isempty(sizes) && break\r\n            M, largest = maximum(sizes)\r\n            if M <= scomp/2\r\n                for k in neighbors(g,i)\r\n                    if S[k] > 1 && present[k]\r\n                        push!(H, (S[k],k))\r\n                    end\r\n                end\r\n                present[i] = false\r\n                push!(attack_nodes, i)\r\n                push!(scomps, scomp)\r\n                break\r\n            end\r\n            S[i] = 1\r\n            for k in neighbors(g,i)\r\n                if k != largest && present[k]\r\n                    S[i] += S[k]\r\n                end\r\n            end\r\n            sender, i = i, largest\r\n        end\r\n\t\tscomp <= threshold && break\r\n    end\r\n    return attack_nodes, scomps\r\nend\r\n", "meta": {"hexsha": "cfac8857a88528d55b856eb351dbbc6287bf6ba3", "size": 1585, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tree_break.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/tree_break.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/tree_break.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": 27.8070175439, "max_line_length": 84, "alphanum_fraction": 0.4504731861, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7579941118086739}}
{"text": "using Test, PolyChaos\n\n@test nw(EmptyQuad()) |> typeof == Array{Float64,2}\n@test nw(EmptyQuad()) |> length == 0\n\nnodes, weights = gauss(rm_legendre01(5)...)\nmyQuad = Quad(\"myQuad\", length(nodes), nodes, weights)\nfoo(x) = 6*x^5\nres = 1\n@test isapprox(integrate(foo, nodes, weights), res)\n@test isapprox(integrate(foo, myQuad), res)\n@test_throws DomainError integrate(foo, EmptyQuad())\n@test isapprox(integrate(foo, Uniform01OrthoPoly(4)), res)\n\nfoo(x) = 5*x^4\nres = 1\n@test isapprox(integrate(foo, Uniform_11OrthoPoly(4)), res)\n\nd, nunc = 5, 10\nop = genLaguerreOrthoPoly(d,1.23,addQuadrature = false)\nopq = genLaguerreOrthoPoly(d,1.23)\nmop = MultiOrthoPoly([op for i in 1:nunc],d)\nmopq = MultiOrthoPoly([opq for i in 1:nunc],d)\n@testset \"dimenions\" begin\n    @test isequal(PolyChaos.dim(op), d + 1)\n    @test isequal(PolyChaos.dim(opq), d + 1)\n    @test isequal(PolyChaos.dim(mop), factorial(d + nunc) / (factorial(d) * factorial(nunc)))\nend\n\n@testset \"degrees\" begin\n    @test isequal(PolyChaos.deg(op),d)\n    @test isequal(PolyChaos.deg(opq),d)\n    @test isequal(PolyChaos.deg(mop),d)\nend\n\nNW = [ opq.quad.nodes opq.quad.weights ]\n@testset \"nodes and weights\" begin\n    @test PolyChaos.nw(opq) == NW\n    @test PolyChaos.nw([opq for i in 1:nunc])[1] == [NW[:,1] for i in 1:nunc]\n    @test PolyChaos.nw([opq for i in 1:nunc])[2] == [NW[:,2] for i in 1:nunc]\n    @test PolyChaos.nw(mopq)[1] == [NW[:,1] for i in 1:nunc]\n    @test PolyChaos.nw(mopq)[2] == [NW[:,2] for i in 1:nunc]\nend\n\nc = [ op.\u03b1 op.\u03b2 ]\n@testset \"coefficients\" begin\n    @test PolyChaos.coeffs(op) == c\n    @test PolyChaos.coeffs(opq) == c\n    @test PolyChaos.coeffs([op for i in 1:nunc])[1] == [ c[:,1] for i in 1:nunc ]\n    @test PolyChaos.coeffs([op for i in 1:nunc])[2] == [ c[:,2] for i in 1:nunc ]\n    @test PolyChaos.coeffs([opq for i in 1:nunc])[1] == [ c[:,1] for i in 1:nunc ]\n    @test PolyChaos.coeffs([opq for i in 1:nunc])[2] == [ c[:,2] for i in 1:nunc ]\n    @test PolyChaos.coeffs(mop)[1] == [ c[:,1] for i in 1:nunc ]\n    @test PolyChaos.coeffs(mop)[2] == [ c[:,2] for i in 1:nunc ]\nend\n\n@test issymmetric(op) == issymmetric(opq)\n\n## Accounting for StaticArrays\nusing StaticArrays\n\nmax_degree = 4\n\nop = Uniform01OrthoPoly(max_degree; Nrec = max_degree + 3)\nnodes, weights = SVector(op.quad.nodes...), SVector(op.quad.weights...)\n\nmyfun(t) = t^2\n\n@test integrate(myfun, op) == integrate(myfun, nodes, weights)\n\nn_multi = 4\nmop = MultiOrthoPoly([op for i in 1:n_multi], max_degree)\nL = size(mop.ind)[1]\n\ntest_vector = [ rand(0:L-1) for i in 0:L ]\nreference = multi2uni(test_vector, mop.ind)\n\n@testset \"multi2uni for StaticArrays\" begin\n    @test multi2uni(SVector(test_vector...), mop.ind) == reference\n    @test multi2uni(test_vector, SMatrix{size(mop.ind)...}(mop.ind)) == reference\n    @test multi2uni(SVector(test_vector...), SMatrix{size(mop.ind)...}(mop.ind)) == reference\nend\n\ntensor_dim = 2\ntensor_entries = computeTensorizedSP(tensor_dim, mop)\nmy_getentry(row, entries) = getentry(row, tensor_entries, entries, tensor_dim)\n\nif VERSION >= VersionNumber(\"1.1.1\")\n    @testset \"getentry for StaticArrays\" begin\n        for row in eachrow(rand(0:L-1, L, tensor_dim))\n            reference = my_getentry(Vector(row), mop.ind)\n            @test my_getentry(row, mop.ind) == reference\n            @test my_getentry(row, SMatrix{size(mop.ind)...}(mop.ind)) == reference\n            @test my_getentry(Vector(row), SMatrix{size(mop.ind)...}(mop.ind)) == reference\n        end\n    end\nend\n", "meta": {"hexsha": "d191cc008f02920ddfccc4aefde006e6e5ca7362", "size": 3467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/auxfuns.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": "test/auxfuns.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": "test/auxfuns.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": 35.3775510204, "max_line_length": 93, "alphanum_fraction": 0.6602249784, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7579941113194981}}
{"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\u00b9\nexport U1\n\n\n\"\"\"\n    Represents a point in a one-sphere.\n\"\"\"\nabstract type S\u00b9 end\n\n\n\"\"\"\n    Represents a point in U(1).\n\nfield: \u03b1.\n\"\"\"\nstruct U1 <: S\u00b9\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        \u03b8 = angle(z) \u2265 0 ? angle(z) : \u03c0 + angle(z)\n        new(\u03b8)\n    end\n    U1(\u03b1::Real) = begin\n        #@assert(-pi \u2264 \u03b1 \u2264 pi, \"The phase angle must be in the interval [-\u03c0, \u03c0].\")\n        new(float(\u03b1))\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# \u2554\u2550\u2561 a82f22e4-f35b-461a-b481-1dff43722e44\nusing StaticArrays\n\n# \u2554\u2550\u2561 d42f842d-6c2a-40db-b0c4-e936244a9e7c\nusing BenchmarkTools\n\n# \u2554\u2550\u2561 99b5c818-a825-4939-849e-1cade802f63d\nusing Measurements\n\n# \u2554\u2550\u2561 d6564250-f646-40de-9463-a956af1a5b1d\nusing ForwardDiff\n\n# \u2554\u2550\u2561 d2f4d622-8e35-4be3-b421-39b28a748cab\nusing CellListMap\n\n# \u2554\u2550\u2561 f049ab19-7ecf-4c65-bf6d-21352c1fe767\nusing FastPow\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 febe8c06-b3aa-4db1-a3ea-fdc2a81bdebd\nusing Printf\n\n# \u2554\u2550\u2561 a756dd18-fac6-4527-944e-c16d8cc4bf95\nbegin\n    using PlutoUI\n    TableOfContents()\nend\n\n# \u2554\u2550\u2561 a87fad48-73c1-4a08-a6f1-aae759b3c6fc\nmd\"\"\"\n# Particle Simulations with Julia\n\nLeandro Mart\u00ednez\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u00d7M` 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# \u2554\u2550\u2561 8c444ee4-8c77-413a-bbeb-9e5ae2428876\nstruct Vec2D{T} <: FieldVector{2,T}\n    x::T\n    y::T\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7a1db355-bba9-4322-9fb4-a6d7b7bdd60d\nimport LinearAlgebra: norm\n\n# \u2554\u2550\u2561 cc49ef04-08d8-42bb-9170-9db64e275a51\nmd\"\"\"\nThe energy and force functions are clear to read:\n\"\"\"\n\n# \u2554\u2550\u2561 d00e56f2-9d3a-4dd3-80eb-3201eff39b96\nmd\"\"\"\nAnd for a unidimensional case, with a defined cutoff, look like:\n\"\"\"\n\n# \u2554\u2550\u2561 b5c09cd3-6063-4a36-96cd-2d128aa11b82\nconst cutoff = 5.\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 144119ad-ab88-4165-883a-f2fc2464a838\nmd\"\"\"\nLet us create some points to explain how the function will be called. \n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2093(x,y,cutoff)`. Thus, it is consistent with the internal call of `f\u2093` of `forces!`, and *closes over* the additional parameter `cutoff` required for the computation. \n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 66c7d960-7e05-4613-84e8-2a40fe40dc3d\nmd\"\"\"\n## Let us run the simulation!\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 02d9bf3b-708c-4293-b198-9043b334ff7e\nmd\"\"\"\nThis allows writting the force computation now as:\n\"\"\"\n\n# \u2554\u2550\u2561 0a5282ee-c88a-4bcc-aca2-477f28e9e04d\nmd\"\"\"\nOur box has a side of 100:\n\"\"\"\n\n# \u2554\u2550\u2561 b2a4a505-47ff-40bb-9a6d-a08d91c53217\nconst side = 100.\n\n# \u2554\u2550\u2561 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\u2093` function in the *closure* definition:\n\"\"\"\n\n# \u2554\u2550\u2561 14867ffd-cde5-43f8-8399-01169ee29b73\nmd\"\"\"\nA relevant detail here is that we could use the same `f\u2093` 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# \u2554\u2550\u2561 c4798182-de75-4b59-8be7-f7cf1051364d\nmd\"\"\"\nWhile plotting the trajectory, we will wrap the coordinates:\n\"\"\"\n\n# \u2554\u2550\u2561 22fb0386-d4fa-47b9-ac31-decf2731cbc1\nmd\"\"\"\n## Benchmarking\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 26d5c6e9-a903-4792-a0e0-dec1a2e86a01\nstruct Vec3D{T} <: FieldVector{3,T}\n    x::T\n    y::T\n    z::T\nend\n\n# \u2554\u2550\u2561 2aef27bd-dea6-4a93-9d0f-b9249c9dd2cd\nmd\"\"\"\nThat is enough such that we can run the simulations in 3D:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e4657169-1bb2-4d4a-ac9d-adc80499d07d\nstruct MyMeasurement{T}\n    x::T\n    \u0394x::T\nend\n\n# \u2554\u2550\u2561 5d395353-5681-4780-983e-902fdb89eaf2\nmd\"\"\"\nand we will overload the printing of this variables to make things prettier:\n\"\"\"\n\n# \u2554\u2550\u2561 e9376a4b-3d60-42eb-8681-cd2bcec13fe8\nBase.show(io::IO,m::MyMeasurement) = println(io,\" $(m.x) \u00b1 $(m.\u0394x)\")\n\n# \u2554\u2550\u2561 c5cdd71f-5ded-482f-9205-c13f01a14d0b\nm = MyMeasurement(1.0,0.1)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4e7f8db4-b5cc-4a3e-9fa7-e62d8f2a36ac\nbegin\n    import Base: -, +, *, /, ^, sqrt\n    +(m1::MyMeasurement,m2::MyMeasurement) = MyMeasurement(m1.x+m2.x,m1.\u0394x+m2.\u0394x)\n    -(m1::MyMeasurement,m2::MyMeasurement) = MyMeasurement(m1.x-m2.x,m1.\u0394x+m2.\u0394x)\n    *(\u03b1,m::MyMeasurement) = MyMeasurement(\u03b1*m.x,sign(\u03b1)*\u03b1*m.\u0394x)\n    *(m::MyMeasurement,\u03b1) = \u03b1*m\n    /(m::MyMeasurement,\u03b1) = inv(\u03b1)*m\n    sqrt(m::MyMeasurement{T}) where T = MyMeasurement(sqrt(m.x),inv(2*sqrt(m.x))*m.\u0394x)\n    ^(m::MyMeasurement{T},n) where T = MyMeasurement{T}(m.x^n,n*m.x^(n-1)*m.\u0394x)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 df33b999-4a42-4133-bf59-5a65240790cf\nfunction energy(x::T,y::T,cutoff) where T\n    \u0394v = y - x\n    d = norm(\u0394v)\n    if d > cutoff\n        energy = zero(T)\n    else\n        energy = (d - cutoff)^2\n    end\n    return energy\nend\n\n# \u2554\u2550\u2561 0f52365d-34f4-46ed-923e-3ea31c6db0ca\nfunction f\u2093(x::T,y::T,cutoff) where T\n    \u0394v = y - x\n    d = norm(\u0394v)\n    if d > cutoff\n        f\u2093 = zero(T)\n    else\n        f\u2093 = 2*(d - cutoff)*(\u0394v/d)\n    end\n    return f\u2093\nend\n\n# \u2554\u2550\u2561 f58769a6-a656-42a3-8bc6-c204d4cfd897\nfunction forces!(f::Vector{T},x::Vector{T},f\u2093::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\u1d62 = f\u2093(i,j,x[i],x[j])\n            f[i] += f\u1d62 \n            f[j] -= f\u1d62\n        end\n    end\n    return f\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0967b90d-ac88-476d-a57a-7c38dfa82204\nfunction f\u2093(x::T,y::T,cutoff,side) where T\n    \u0394v = wrap.(y - x, side)\n    d = norm(\u0394v)\n    if d > cutoff\n        f\u2093 = zero(T)\n    else\n        f\u2093 = 2*(d - cutoff)*(\u0394v/d)\n    end\n    return f\u2093\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70eb2e0a-a5c8-4975-8f6c-589035bea29c\nsqrt((2*(m + 4*m)^2/3))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d32743c0-fc80-406f-83c5-4528e439589a\nx = Vec2D(MyMeasurement(1.0,0.1),MyMeasurement(2.0,0.2))\n\n# \u2554\u2550\u2561 98478246-5940-4828-a8f1-9c9fa990676d\nmd\"\"\"\nAnd now operations on this point propagate the uncertainties of the componentes as well:\n\"\"\"\n\n# \u2554\u2550\u2561 310f247e-3fe8-4621-ae0b-b5ee38d2ee89\n2*x .+ sqrt.(x)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ce916139-221a-462e-877f-88212663c05e\nmd\"\"\"\n### Using `Measurements`\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 418f31bb-81d5-459b-b402-4fd4e3f4ab27\nmd\"\"\"\nWe need to redefine your initial random point generator only:\n\"\"\"\n\n# \u2554\u2550\u2561 05402cbd-78c6-4234-8680-c351c8c37778\nfunction random_point(::Type{Vec2D{Measurement{T}}},range,\u0394) where T    \n    p = Vec2D(\n        range[begin] + rand(T)*(range[end]-range[begin]) \u00b1 rand()*\u0394,\n        range[begin] + rand(T)*(range[end]-range[begin]) \u00b1 rand()*\u0394\n    )\n    return p\nend\n\n# \u2554\u2550\u2561 356ac5a4-c94e-42cb-a085-0198b29c7e52\nx0 = [ random_point(Vec2D{Float64},(0,100)) for _ in 1:100] \n\n# \u2554\u2550\u2561 d23b4a92-055e-4ed7-bd46-8a3c59312993\nf = similar(x0)\n\n# \u2554\u2550\u2561 e6e29d1e-9a93-49db-a358-6b66f0bc3433\nforces!(\n    f,\n    x0, \n    (i,j,x,y) -> f\u2093(x,y,cutoff) # closure\n) \n\n# \u2554\u2550\u2561 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\u2093(p1,p2,cutoff))\n)...)\n\n# \u2554\u2550\u2561 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\u2093(p1,p2,cutoff,side))\n)...)\n\n# \u2554\u2550\u2561 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\u2093(p1,p2,cutoff,side))\n)...)\n\n# \u2554\u2550\u2561 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\u2093(p1,p2,cutoff,side))\n)...)\n\n# \u2554\u2550\u2561 4e97f24c-c237-4117-bc57-e4e88c8fb8d2\nmd\"\"\"\nWhich generates random points carrying an initial uncertainty we defined:\n\"\"\"\n\n# \u2554\u2550\u2561 b31da90d-7165-42de-b18d-90584affea03\nrandom_point(Vec2D{Measurement{Float64}},(-50,50),1e-5)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 63eb391f-0238-434a-bc3a-2fa8ed41448e\nmd\"\"\"\n### Planetary motion\n\nPerhaps this is more interesting to see in a planetary trajectory:\n\"\"\"\n\n# \u2554\u2550\u2561 7b9bb0fd-34a5-42e1-bc35-7259447b73d0\nfunction gravitational_force(i,j,x,y,mass)\n    G = 0.00049823382528 # MKm\u00b3 / (10\u00b2\u2074kg days\u00b2)\n    dr = y - x\n    r = norm(dr)\n    return G*mass[i]*mass[j]*dr/r^3\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c91862dd-498a-4712-8e3d-b77e088cd470\nplanets_x0 = [\n    Vec2D(  0.0 \u00b1  1.39    , 0. \u00b1  1.39    ), # \"Sun\"\n    Vec2D( 57.9 \u00b1  4.879e-3, 0. \u00b1  4.879e-3), # \"Mercury\"\n    Vec2D(108.2 \u00b1 12.104e-3, 0. \u00b1 12.104e-3), # \"Venus\"\n    Vec2D(149.6 \u00b1 12.756e-3, 0. \u00b1 12.756e-3), # \"Earth\"\n    Vec2D(227.9 \u00b1  6.792e-3, 0. \u00b1  6.792e-3), # \"Mars\"\n]\n\n# \u2554\u2550\u2561 a08d6e6d-ddc4-40aa-b7c4-93ea03191415\nplanets_v0 = [\n    Vec2D(0. \u00b1 0.,   0.0 \u00b1 0.), # \"Sun\"\n    Vec2D(0. \u00b1 0.,  4.10 \u00b1 0.), # \"Mercury\"\n    Vec2D(0. \u00b1 0.,  3.02 \u00b1 0.), # \"Venus\"\n    Vec2D(0. \u00b1 0.,  2.57 \u00b1 0.), # \"Earth\"\n    Vec2D(0. \u00b1 0.,  2.08 \u00b1 0.)  # \"Mars\"  \n]\n\n# \u2554\u2550\u2561 a356e2cc-1cb1-457a-986c-998cf1efe008\nmd\"\"\"\nAnd the masses are given in units of $10^{24}$ kg:\n\"\"\"\n\n# \u2554\u2550\u2561 57141f7c-9261-4dc5-98e4-b136a15f86fc\nconst masses = [ 1.99e6, 0.330, 4.87, 5.97, 0.642 ]\n\n# \u2554\u2550\u2561 055e32d7-073c-40db-a267-750636b9f786\nmd\"\"\"\nLet us see the planets orbiting the sun:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4870b1f3-3134-4ddc-a59d-fa806b456a23\nmd\"\"\"\nWe can see that our current data results in a significant error:\n\"\"\"\n\n# \u2554\u2550\u2561 fda6171c-9675-4f2e-b226-7ccf100529cd\nerror_in_orbit()\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 107aec28-ecb5-4007-95e5-25d0a7f0c465\nForwardDiff.derivative(error_in_orbit,149.6)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b8320f78-323c-49a9-a9f9-2748d19ecb35\nerror_derivative(x) = ForwardDiff.derivative(error_in_orbit,x)\n\n# \u2554\u2550\u2561 92737d73-676c-4c96-a321-831ecaf37690\nmd\"\"\"\nAnd now we can call the `gradient_descent` function directly:\n\"\"\"\n\n# \u2554\u2550\u2561 931a9c5f-8f91-4e88-956b-50c0efc9c58b\nbest_x0 = gradient_descent(149.6,error_in_orbit,error_derivative,1e-4,1000)\n\n# \u2554\u2550\u2561 b5b96082-efde-464f-bcd4-f2e0a84befcd\nmd\"\"\"\nThe result is reasonable: the error in the orbit has significantly being disminished:\n\"\"\"\n\n# \u2554\u2550\u2561 7658a32c-d3da-4ec9-9d96-0d30bb18f08c\nerror_in_orbit(best_x0[1])\n\n# \u2554\u2550\u2561 e61981d5-5448-45e9-81dc-320ac87ba813\nmd\"\"\"\nLet us see our trajectory now with the new initial condition:\n\"\"\"\n\n# \u2554\u2550\u2561 31e1bb51-c531-4c4a-8634-5caafb7e9e51\nearth_traj_0 = earth_orbit(149.6)\n\n# \u2554\u2550\u2561 b0b81da4-6788-45c4-b618-188a02b5e09c\nearth_traj_best = earth_orbit(best_x0[1])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 826693ff-9a9b-46b1-aeb3-767a5e6f9441\nmd\"\"\"\n# Accelerating with CellListMap.jl\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 53cedd26-3742-4c23-a8b8-8a1f2bdfa135\nmd\"\"\"\n## The naive algorithm is too slow O(n\u00b2)\n\"\"\"\n\n# \u2554\u2550\u2561 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\u00b2) algorithm is already too slow. Typical simulations involve tenths of thousands to millions of particles.\n\"\"\"\n\n# \u2554\u2550\u2561 670a01e3-82f8-4c7f-8577-852081d91ed7\nmd\"\"\"\nHere, we will simulate 1000 particles to start:\n\"\"\"\n\n# \u2554\u2550\u2561 fce1e3e0-cdf7-453f-b913-964c10fa85a6\nconst n_large = 1000\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 542a9ef5-d9ee-49bd-9d31-61e28b80b5cb\nconst box_side = sqrt(n_large / (100/100^2))\n\n# \u2554\u2550\u2561 8bada25c-b586-42b4-851d-232ccca8a456\nmd\"\"\"\nWe only need to generate the coordinates and run:\n\"\"\"\n\n# \u2554\u2550\u2561 7600c6dc-769e-4c77-8526-281a1bcec079\nx0_large = [ Vec2D(box_side*rand(),box_side*rand()) for _ in 1:n_large ] \n\n# \u2554\u2550\u2561 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\u2093(p1,p2,cutoff,box_side))\n)...)\n\n# \u2554\u2550\u2561 0ee7fc18-f41f-4179-a75e-1e1d56b2db29\nmd\"\"\" \nRunning time of naive algorithm: $t_naive seconds\n\"\"\"\n\n# \u2554\u2550\u2561 0d0374ed-5150-40e6-b5a4-9a344b6ca47a\nmd\"\"\"\n## Using cell lists\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4fc5ef4d-e072-41f7-aef9-b42730c8313c\nbox = Box([box_side,box_side],cutoff)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7dcadd85-2986-4e42-aa84-67128a8f666d\ncl = CellList(x0_large,box)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 91b5eac1-4799-4a72-ac6a-e2b117b787d5\nfunction fpair_cl(x,y,i,j,d2,f,box::Box)\n    \u0394v = y - x\n    d = sqrt(d2)\n    f\u2093 = 2*(d - box.cutoff)*(\u0394v/d)\n    f[i] += f\u2093\n    f[j] -= f\u2093\n    return f\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 76b8695e-64dc-44bc-8938-ce22c4a9e4d0\nmd\"\"\"\n## Energy minimization: the Packmol strategy\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7280e368-c68a-48a5-91fe-93c76607c144\nmd\"\"\"\nThe function that computes the energy associated to one pair of particles is, then:\n\"\"\"\n\n# \u2554\u2550\u2561 755fae26-6db9-45a0-a60d-d0e9c063f8aa\nfunction ulj_pair(r2,u,\u03b5,\u03c3)\n    @fastpow u += \u03b5*(\u03c3^12/r2^6 - 2*\u03c3^6/r2^3)\n    return u\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ffbeae5f-8aec-4473-a446-5b73bd911733\nfunction ulj(x,\u03b5,\u03c3,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,\u03b5,\u03c3),\n        zero(eltype(\u03c3)), box, cl,\n        parallel=false\n    )\n    return u\nend\n\n# \u2554\u2550\u2561 3738e40f-9596-469d-aa58-a4b28d8a22f8\nmd\"\"\"\nand we implement the corresponding functions that updates the forces:\n\"\"\"\n\n# \u2554\u2550\u2561 5f1054b8-2337-43c1-a086-26233e95d42b\nfunction flj_pair!(x,y,i,j,r2,f,\u03b5,\u03c3)\n    @fastpow \u2202u\u2202x = 12*\u03b5*(\u03c3^12/r2^7 - \u03c3^6/r2^4)*(y-x)\n    f[i] -= \u2202u\u2202x\n    f[j] += \u2202u\u2202x\n    return f\nend\n\n# \u2554\u2550\u2561 bd719619-bdd4-4c3c-8d66-1df0f210c595\nfunction flj!(f::Vector{T},x,\u03b5,\u03c3,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,\u03b5,\u03c3),\n        f, box, cl, \n        parallel=false\n    )\n    return f\nend\n\n# \u2554\u2550\u2561 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/\u00c5\u00b3, which is roughly the atomic density of liquid water. \n\nThe Lennard-Jones parameters for Neon are:\n\"\"\"\n\n# \u2554\u2550\u2561 878ab5f7-28c1-4832-9c58-cb36b360766f\nconst \u03b5 = 0.0441795 # kcal/mol\n\n# \u2554\u2550\u2561 a0dcd888-059d-4abe-bb6b-958d2879101c\nconst \u03c3 = 2*1.64009 # \u212b\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cd1102ac-1500-4d79-be83-72ac9180c7ce\nconst n_Ne = 10_000\n\n# \u2554\u2550\u2561 f21604f4-e4f7-4d43-b3d9-32f429df443e\nconst box_side_Ne = (10_000/0.1)^(1/3)\n\n# \u2554\u2550\u2561 59b1dbce-64af-4868-8c9d-23792c4a3a9f\nmd\"\"\"\nInitial coordinates, box and cell lists. A typical cutoff for Lennard-Jones interactions in MD simulations is 12\u212b. \n\"\"\"\n\n# \u2554\u2550\u2561 10826a95-16f8-416d-b8c1-0ef3347c9b20\nx0_Ne = [random_point(Vec3D{Float64},(0,box_side_Ne)) for _ in 1:n_Ne ]\n\n# \u2554\u2550\u2561 c46a4f97-78e4-42fd-82b3-4dc6ce99abac\nmd\"\"\"\nGiven the initial coordinates, we can initialize the system box and cell lists:\n\"\"\"\n\n# \u2554\u2550\u2561 7c433791-a653-4836-91e2-084355c01d90\nconst box_Ne = Box([box_side_Ne for _ in 1:3],12.)\n\n# \u2554\u2550\u2561 410b9da4-7848-4385-bffc-a3d9bd03cf19\nconst cl_Ne = CellList(x0_Ne,box_Ne)\n\n# \u2554\u2550\u2561 c08fff28-520e-40af-951c-fe3c324f67e0\nmd\"\"\"\n### First, let us try to minimize the energy\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e3cc3c77-71ad-4006-8e27-fabaa1ae9cfb\nmd\"\"\"\nThe obtained energy (after 500 steps of stepest descent) is:\n\"\"\"\n\n# \u2554\u2550\u2561 739c9a8a-13a5-4a33-a441-f5bc6cb35e82\nmd\"\"\"\n### Packing the atoms\n\"\"\"\n\n# \u2554\u2550\u2561 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 \u03c3/2. Since only very short-ranged interactions have to be computed, and the function is well behaved, the optimization is fast:\n\"\"\"\n\n# \u2554\u2550\u2561 5ff9c89a-d999-4af2-8e7e-fb99d4948c36\nmd\"\"\"\nLet us initialize again the system, considering the smaller cutoff:\n\"\"\"\n\n# \u2554\u2550\u2561 0f2f55f6-060b-475e-bef7-eaa99da4d99f\nbox_pack = Box([box_side_Ne for _ in 1:3],\u03c3/2)\n\n# \u2554\u2550\u2561 415ad590-247b-4a5d-b21e-7af4d0c17493\ncl_pack = CellList(x0_Ne,box_pack)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 79169f89-fedc-466b-8170-fff99b98e147\nmd\"\"\"\nGiven the packing energy and gradient, we can solve the packing problem:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b0dc1c2b-82b7-488d-8074-1ef9f59a15e5\nmd\"\"\"\nThe energy, on the other side, is not necessarily small:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 10c86547-d4f4-4c3f-8906-ac18ce93f3b6\nmd\"\"\"\n# Acknowledgements\n\nThe author thanks [Mos\u00e8 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\u0159ej \u010cert\u00edk](Ond\u0159ej \u010cert\u00edk) for the kind invitation and great contributions for the developement of a modern community and tools around Fortran.\n\"\"\"\n\n# \u2554\u2550\u2561 2871aca3-e6b4-4a2d-868a-36562e9a274c\nmd\"\"\"\n# Some notebook options and setup\n\"\"\"\n\n# \u2554\u2550\u2561 2a2e9155-1c77-46fd-8502-8431573f94d0\nmd\"\"\"\n## Default plot setup\n\"\"\"\n\n# \u2554\u2550\u2561 b557a646-8c3c-4dc7-8788-bf98aec8c5c0\nmd\"\"\"\nUse Printf to print some data.\n\"\"\"\n\n# \u2554\u2550\u2561 260d5753-6cc2-4137-8a2c-8d8a47585ecf\nmd\"\"\"\nWe can set this to false to avoid ploting everything. \n\"\"\"\n\n# \u2554\u2550\u2561 a9981931-4cc9-4d16-a6d2-34b4071a84d7\nconst build_plots = true\n\n# \u2554\u2550\u2561 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\u2093.(0.,r,cutoff),xlabel=\"Distance\",ylabel=\"Force\",subplot=2)\nend    \n\n# \u2554\u2550\u2561 43e6b146-ee35-40f1-b540-3da22b9e1b1b\nbuild_plots && scatter([(x.x, x.y) for x in x0])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2093(p1,p2,cutoff,side))\n)...) )\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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.,\u03b5,\u03c3),\n\t\txlabel=\"Distance / \u00c5\", ylabel=\"Potential energy / kcal/mol\"\n\t)\nend\n\n# \u2554\u2550\u2561 b4154fb7-e0b0-4211-8490-8a8fe47cd2da\nmd\"\"\"\n## Gradient descent for vectors\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 357c6621-b2b8-4f30-ba41-ffc1ae6f031b\nt_min = @elapsed x_min = gradient_descent!(\n    copy(x0_Ne),\n    (x) -> ulj(x,\u03b5,\u03c3,box_Ne,cl_Ne),\n    (g,x) -> -flj!(g,x,\u03b5,\u03c3,box_Ne,cl_Ne)\n)\n\n# \u2554\u2550\u2561 58eb5b4b-76ad-4f7a-b86b-0494a857dca1\nulj(x_min,\u03b5,\u03c3,box_Ne,cl_Ne)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 06526edf-911a-4ecc-a350-6d932ca56cd5\nmd\"\"\"\n**Time required for packing: $t_pack seconds**\n\"\"\"\n\n# \u2554\u2550\u2561 c48210e0-1a04-4f84-a4e2-f6b5d34a603d\nu_pack(x_pack,box_pack,cl_pack)\n\n# \u2554\u2550\u2561 0471b987-f987-4656-b961-285e32d0a5e1\nulj(x_pack,\u03b5,\u03c3,box_Ne,cl_Ne)\n\n# \u2554\u2550\u2561 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,\u03b5,\u03c3,box_Ne,cl_Ne)\n)...)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b5008faf-fd43-45dd-a5a1-7f51e0b4ede5\nmd\"\"\"\n## Table of Contents\n\"\"\"\n\n# \u2554\u2550\u2561 555d1f62-b95b-4377-a8e2-9e442ee7526d\n\n\n# \u2554\u2550\u2561 f5510c1e-9b9f-49f0-bc7e-0fd8e79a5760\nmd\"\"\"\n## 2D packing example\n\"\"\"\n\n# \u2554\u2550\u2561 5d9a40b5-4050-47d2-9855-e9b62d56e8df\nside_test = 50\n\n# \u2554\u2550\u2561 7f556f7c-cdb0-4f91-a359-2f933bbc5b68\nxtest = [ random_point(Vec2D{Float64},(-side_test,side_test)) for _ in 1:1000 ]\n\n# \u2554\u2550\u2561 0fc843d2-ac4f-4717-a298-92a476223112\ntol_test = 2\n\n# \u2554\u2550\u2561 fc7f665b-00d9-431b-a97e-d2ff7253221a\nbox_test = Box([side_test,side_test],tol_test)\n\n# \u2554\u2550\u2561 aadf6e48-0cbf-4973-86a1-173b6648d1df\ncl_test = CellList(xtest,box_test)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500a87fad48-73c1-4a08-a6f1-aae759b3c6fc\n# \u255f\u2500172227c2-b27a-40db-91f4-9566c2f6cf52\n# \u255f\u25004b484cf6-4888-4f04-b3fd-94862822b0c0\n# \u2560\u2550a82f22e4-f35b-461a-b481-1dff43722e44\n# \u2560\u25508c444ee4-8c77-413a-bbeb-9e5ae2428876\n# \u255f\u2500a0de01b5-779a-48c0-8d61-12b02a5f527e\n# \u2560\u2550f87e4036-8f82-41c7-90c1-daa5f677488d\n# \u255f\u2500532eb3bc-5522-4348-afa5-5336ec6752c7\n# \u255f\u2500dc5f7484-3dc3-47a7-ad4a-30f97fc14d11\n# \u255f\u2500ab3ff21b-bf82-4d8c-abd1-c27418956ed8\n# \u2560\u25507a1db355-bba9-4322-9fb4-a6d7b7bdd60d\n# \u255f\u2500cc49ef04-08d8-42bb-9170-9db64e275a51\n# \u2560\u2550df33b999-4a42-4133-bf59-5a65240790cf\n# \u2560\u25500f52365d-34f4-46ed-923e-3ea31c6db0ca\n# \u255f\u2500d00e56f2-9d3a-4dd3-80eb-3201eff39b96\n# \u2560\u2550b5c09cd3-6063-4a36-96cd-2d128aa11b82\n# \u255f\u2500374f239b-6470-40ed-b068-a8ecaace4f09\n# \u255f\u25007719b317-e85b-4583-b401-a8614d4b2373\n# \u2560\u2550f58769a6-a656-42a3-8bc6-c204d4cfd897\n# \u255f\u2500144119ad-ab88-4165-883a-f2fc2464a838\n# \u2560\u2550356ac5a4-c94e-42cb-a085-0198b29c7e52\n# \u255f\u250043e6b146-ee35-40f1-b540-3da22b9e1b1b\n# \u255f\u2500dd9e4332-2908-40ef-b461-6b571df56cf4\n# \u2560\u2550d23b4a92-055e-4ed7-bd46-8a3c59312993\n# \u2560\u2550e6e29d1e-9a93-49db-a358-6b66f0bc3433\n# \u255f\u2500017cd6a8-712d-4ec5-b31f-7f1f507764f2\n# \u255f\u2500b5206dd5-1f46-4437-929b-efd68393b12b\n# \u2560\u2550eb5dc224-1491-11ec-1cae-d51c93cd292c\n# \u255f\u2500594ba1d6-2dae-4f20-9546-f52fac17c2f0\n# \u255f\u250066c7d960-7e05-4613-84e8-2a40fe40dc3d\n# \u255f\u2500e717a8d9-ccfb-4f89-b2a2-f244f108b48d\n# \u2560\u25503755a4f3-1842-4de2-965e-d294c06c54c7\n# \u255f\u2500505ef5ab-f131-4ab3-a723-795b5eb5dc0f\n# \u255f\u2500eab7b195-64d5-4587-8687-48a673ab091b\n# \u255f\u250034dc72dc-4864-47c0-b730-183f67e7aea3\n# \u2560\u2550beeb3335-5c49-47de-a1d3-3eef5f9479f1\n# \u255f\u250002d9bf3b-708c-4293-b198-9043b334ff7e\n# \u2560\u25500967b90d-ac88-476d-a57a-7c38dfa82204\n# \u255f\u25000a5282ee-c88a-4bcc-aca2-477f28e9e04d\n# \u2560\u2550b2a4a505-47ff-40bb-9a6d-a08d91c53217\n# \u255f\u2500fcff6973-012a-40fc-a618-f6262266287a\n# \u2560\u2550985b4ffb-7964-4b50-8c2f-e5f45f352500\n# \u255f\u250014867ffd-cde5-43f8-8399-01169ee29b73\n# \u255f\u2500c4798182-de75-4b59-8be7-f7cf1051364d\n# \u2560\u2550efc586a2-0946-4dc5-ab3a-3902a811f3ad\n# \u255f\u250022fb0386-d4fa-47b9-ac31-decf2731cbc1\n# \u255f\u25008e23a3ea-3039-4a5f-b37f-c4710153938e\n# \u2560\u2550d42f842d-6c2a-40db-b0c4-e936244a9e7c\n# \u2560\u25501ad401b5-20b2-489b-b2aa-92f729b1d725\n# \u255f\u25002a3e7257-63ad-4761-beda-cec18b91f99c\n# \u255f\u250049b1f040-929a-4238-acd9-6554757b592c\n# \u2560\u255026d5c6e9-a903-4792-a0e0-dec1a2e86a01\n# \u255f\u25002aef27bd-dea6-4a93-9d0f-b9249c9dd2cd\n# \u2560\u25500546ee2d-b62d-4c7a-8172-ba87b3c1aea4\n# \u255f\u25004a498c18-406f-4437-b378-aa9fdc75b919\n# \u255f\u2500b6dcb9a3-59e3-4eae-9399-fb072c704f1a\n# \u2560\u2550e4657169-1bb2-4d4a-ac9d-adc80499d07d\n# \u255f\u25005d395353-5681-4780-983e-902fdb89eaf2\n# \u2560\u2550e9376a4b-3d60-42eb-8681-cd2bcec13fe8\n# \u2560\u2550c5cdd71f-5ded-482f-9205-c13f01a14d0b\n# \u255f\u2500a0993a1f-60a6-45b5-815e-676c49a9f049\n# \u2560\u25504e7f8db4-b5cc-4a3e-9fa7-e62d8f2a36ac\n# \u255f\u250036da3e92-000c-4d4b-9abf-4cd588b3a354\n# \u2560\u255070eb2e0a-a5c8-4975-8f6c-589035bea29c\n# \u255f\u2500b4646a29-3efd-4bd1-bffc-3575559de937\n# \u2560\u2550d32743c0-fc80-406f-83c5-4528e439589a\n# \u255f\u250098478246-5940-4828-a8f1-9c9fa990676d\n# \u2560\u2550310f247e-3fe8-4621-ae0b-b5ee38d2ee89\n# \u255f\u25008267220a-f06e-4761-b310-00f8ba44e4b1\n# \u255f\u2500ce916139-221a-462e-877f-88212663c05e\n# \u2560\u255099b5c818-a825-4939-849e-1cade802f63d\n# \u255f\u25008e2903be-4975-4e14-84ed-6e712f47fe47\n# \u255f\u2500418f31bb-81d5-459b-b402-4fd4e3f4ab27\n# \u2560\u255005402cbd-78c6-4234-8680-c351c8c37778\n# \u255f\u25004e97f24c-c237-4117-bc57-e4e88c8fb8d2\n# \u2560\u2550b31da90d-7165-42de-b18d-90584affea03\n# \u255f\u25005f37640b-ffd9-4877-a78c-a699b2671919\n# \u2560\u2550d87c22d1-d595-4d43-ab1c-f28d282a3485\n# \u255f\u25001d6eedfd-d013-4557-9cf2-103f8fb7b72a\n# \u255f\u2500bf0a5303-f5ce-4711-b9ee-a12ce2d8a397\n# \u255f\u2500c003a61d-a434-4d7b-9214-5b52aa044248\n# \u2560\u2550e24ce081-e367-4feb-8a79-66b8654a0b3a\n# \u255f\u250063eb391f-0238-434a-bc3a-2fa8ed41448e\n# \u2560\u25507b9bb0fd-34a5-42e1-bc35-7259447b73d0\n# \u255f\u25006a4e0e2e-75c5-4cab-987d-3d6b62f9bb06\n# \u2560\u2550c91862dd-498a-4712-8e3d-b77e088cd470\n# \u2560\u2550a08d6e6d-ddc4-40aa-b7c4-93ea03191415\n# \u255f\u2500a356e2cc-1cb1-457a-986c-998cf1efe008\n# \u2560\u255057141f7c-9261-4dc5-98e4-b136a15f86fc\n# \u255f\u2500055e32d7-073c-40db-a267-750636b9f786\n# \u2560\u2550aaa97ce4-a5ff-4332-89a2-843cee2e5b6d\n# \u255f\u25001067527e-76b7-4331-b3ab-efd72fb99dfc\n# \u255f\u250093697e4d-369b-48e9-8b28-a0ff58604d02\n# \u255f\u2500c4344e64-aa22-4328-a97a-71e44bcd289f\n# \u255f\u2500827bda6f-87d4-4d36-8d89-f144f4595240\n# \u255f\u25001ff4077a-4742-4c5e-a8d6-c4699469a683\n# \u2560\u25504a75498d-8f4e-406f-8b01-f6a5f153919f\n# \u255f\u25003ae783ce-d06e-4cc2-b8a3-94512e8f1490\n# \u2560\u255013e7da81-8581-4f32-9fdb-2599dd36a12c\n# \u255f\u25004870b1f3-3134-4ddc-a59d-fa806b456a23\n# \u2560\u2550fda6171c-9675-4f2e-b226-7ccf100529cd\n# \u255f\u2500a862f8a3-0131-4644-bc90-246bf3120790\n# \u2560\u2550d6564250-f646-40de-9463-a956af1a5b1d\n# \u255f\u2500eee3ac4b-4ddb-4699-b6e6-f0ffcc562c07\n# \u2560\u2550107aec28-ecb5-4007-95e5-25d0a7f0c465\n# \u255f\u25001394e4c6-c371-47c0-8ca8-f0830d63d8ec\n# \u2560\u2550535716e6-9c1c-4324-a4cd-b1214df3c01d\n# \u255f\u2500b8edfb4e-6780-4ce7-94c1-4073ff7fa832\n# \u2560\u2550b8320f78-323c-49a9-a9f9-2748d19ecb35\n# \u255f\u250092737d73-676c-4c96-a321-831ecaf37690\n# \u2560\u2550931a9c5f-8f91-4e88-956b-50c0efc9c58b\n# \u255f\u2500b5b96082-efde-464f-bcd4-f2e0a84befcd\n# \u2560\u25507658a32c-d3da-4ec9-9d96-0d30bb18f08c\n# \u255f\u2500e61981d5-5448-45e9-81dc-320ac87ba813\n# \u2560\u255031e1bb51-c531-4c4a-8634-5caafb7e9e51\n# \u2560\u2550b0b81da4-6788-45c4-b618-188a02b5e09c\n# \u255f\u250047c205c3-ceae-4e12-9ade-753df1608deb\n# \u255f\u25004cef9cea-1e84-42b9-bff6-b9a8b3bfe8da\n# \u255f\u2500826693ff-9a9b-46b1-aeb3-767a5e6f9441\n# \u255f\u2500d231842d-9b7a-4711-b71b-5d54041ebc1f\n# \u255f\u250053cedd26-3742-4c23-a8b8-8a1f2bdfa135\n# \u255f\u2500889f837d-2e26-4261-b276-5fd91efdda6a\n# \u255f\u2500670a01e3-82f8-4c7f-8577-852081d91ed7\n# \u2560\u2550fce1e3e0-cdf7-453f-b913-964c10fa85a6\n# \u255f\u250069a92ac6-833c-4605-b3d0-9400e4572886\n# \u2560\u2550542a9ef5-d9ee-49bd-9d31-61e28b80b5cb\n# \u255f\u25008bada25c-b586-42b4-851d-232ccca8a456\n# \u2560\u25507600c6dc-769e-4c77-8526-281a1bcec079\n# \u2560\u255029dbc47b-3697-4fdf-8f34-890ab4d0cdae\n# \u255f\u25000ee7fc18-f41f-4179-a75e-1e1d56b2db29\n# \u255f\u2500e5b557d7-0952-4409-ae4c-a0c8ce736e03\n# \u255f\u25000d0374ed-5150-40e6-b5a4-9a344b6ca47a\n# \u2560\u2550d2f4d622-8e35-4be3-b421-39b28a748cab\n# \u255f\u2500f7cf613e-be9d-4f62-a778-cc4375eb99df\n# \u255f\u25005be87c6f-5c31-4d14-a8cb-4e63ef39d538\n# \u255f\u25000c07edd3-c0a1-4f72-a16a-74badb7a6123\n# \u2560\u25504fc5ef4d-e072-41f7-aef9-b42730c8313c\n# \u255f\u250019c5cc9d-8304-4e36-a3ea-a1151f28f71d\n# \u2560\u25507dcadd85-2986-4e42-aa84-67128a8f666d\n# \u255f\u25000b5c6ede-bceb-499a-a9a8-3c6a75ed340a\n# \u2560\u255091b5eac1-4799-4a72-ac6a-e2b117b787d5\n# \u255f\u25000f86ab3c-29aa-472b-8194-228c736ee940\n# \u2560\u25500b8a2292-c0d6-44e4-b560-32d9d579a008\n# \u255f\u2500d6585cca-78bf-41d1-aea3-01d9831d76cb\n# \u2560\u25501b7b7d48-79d2-4317-9045-5b7e7bd073e5\n# \u255f\u25003f9dad58-294c-405c-bfc4-67855bb1e825\n# \u255f\u250030d2f39e-5df2-4f38-8032-e5f8492ba335\n# \u255f\u25006d61b58f-b88f-48f4-8bdd-0bb1a8bc1c82\n# \u255f\u250076b8695e-64dc-44bc-8938-ce22c4a9e4d0\n# \u255f\u2500372637ff-9305-4d45-bf6e-e6531dadbd14\n# \u255f\u25003b2c08a6-b27e-49be-a0b0-e5cb3d5546e0\n# \u2560\u2550f049ab19-7ecf-4c65-bf6d-21352c1fe767\n# \u255f\u25007280e368-c68a-48a5-91fe-93c76607c144\n# \u2560\u2550755fae26-6db9-45a0-a60d-d0e9c063f8aa\n# \u255f\u25009a8d8012-ba54-4d9b-8c4c-fe6358508f2a\n# \u2560\u2550ffbeae5f-8aec-4473-a446-5b73bd911733\n# \u255f\u25003738e40f-9596-469d-aa58-a4b28d8a22f8\n# \u2560\u25505f1054b8-2337-43c1-a086-26233e95d42b\n# \u2560\u2550bd719619-bdd4-4c3c-8d66-1df0f210c595\n# \u255f\u2500f289955b-0239-4b8d-ba08-2edf0a7284c2\n# \u2560\u2550878ab5f7-28c1-4832-9c58-cb36b360766f\n# \u2560\u2550a0dcd888-059d-4abe-bb6b-958d2879101c\n# \u255f\u25002634feff-7442-4d8f-b8e5-c11113136980\n# \u255f\u2500b1c5b7e5-cfbf-4d93-bd79-2924d957ae14\n# \u2560\u2550cd1102ac-1500-4d79-be83-72ac9180c7ce\n# \u2560\u2550f21604f4-e4f7-4d43-b3d9-32f429df443e\n# \u255f\u250059b1dbce-64af-4868-8c9d-23792c4a3a9f\n# \u2560\u255010826a95-16f8-416d-b8c1-0ef3347c9b20\n# \u255f\u2500c46a4f97-78e4-42fd-82b3-4dc6ce99abac\n# \u2560\u25507c433791-a653-4836-91e2-084355c01d90\n# \u2560\u2550410b9da4-7848-4385-bffc-a3d9bd03cf19\n# \u255f\u2500c08fff28-520e-40af-951c-fe3c324f67e0\n# \u255f\u2500eb0f9080-2523-4633-be21-3a2281a1629e\n# \u2560\u2550357c6621-b2b8-4f30-ba41-ffc1ae6f031b\n# \u255f\u2500e3cc3c77-71ad-4006-8e27-fabaa1ae9cfb\n# \u2560\u255058eb5b4b-76ad-4f7a-b86b-0494a857dca1\n# \u255f\u2500574047fa-6626-4cd0-8317-32118129711e\n# \u255f\u2500739c9a8a-13a5-4a33-a441-f5bc6cb35e82\n# \u255f\u25004e059cb8-6dac-450d-9f46-b3e657d9c3cf\n# \u255f\u25005ff9c89a-d999-4af2-8e7e-fb99d4948c36\n# \u2560\u25500f2f55f6-060b-475e-bef7-eaa99da4d99f\n# \u2560\u2550415ad590-247b-4a5d-b21e-7af4d0c17493\n# \u255f\u250053c2e16e-b7f5-4df2-96f4-08402b5f8979\n# \u2560\u255016cdbc18-e846-4d0a-b7e6-87f07c0c52d9\n# \u255f\u250079169f89-fedc-466b-8170-fff99b98e147\n# \u2560\u2550224336e2-522c-44af-b9a1-307e2ffff0f9\n# \u255f\u250006526edf-911a-4ecc-a350-6d932ca56cd5\n# \u255f\u2500b5e258cd-5542-4a4c-ae0f-91c2fee426db\n# \u2560\u2550c48210e0-1a04-4f84-a4e2-f6b5d34a603d\n# \u255f\u2500b0dc1c2b-82b7-488d-8074-1ef9f59a15e5\n# \u2560\u25500471b987-f987-4656-b961-285e32d0a5e1\n# \u255f\u250097b8b15b-75c7-4321-999d-b067ed2a04f9\n# \u255f\u2500d9f254dc-ae4a-40b3-b682-f8a501e10a2d\n# \u255f\u2500591e6a9c-444c-471f-a56b-4dfbc9111989\n# \u255f\u25001f265576-824a-4764-a738-685554068079\n# \u2560\u2550339487cd-8ee8-4d1d-984b-b4c5ff00bae3\n# \u255f\u25009cb29b01-7f49-4145-96d8-c8fd971fe1c8\n# \u255f\u2500ac52a71b-1138-4f1b-99c3-c174d9f09187\n# \u255f\u25001e099e1f-6494-419b-8517-5bded3e18aa6\n# \u255f\u250010c86547-d4f4-4c3f-8906-ac18ce93f3b6\n# \u255f\u25002871aca3-e6b4-4a2d-868a-36562e9a274c\n# \u255f\u25002a2e9155-1c77-46fd-8502-8431573f94d0\n# \u2560\u25507c792b6b-b6ee-4e30-88d5-d0b8064f2734\n# \u255f\u2500b557a646-8c3c-4dc7-8788-bf98aec8c5c0\n# \u2560\u2550febe8c06-b3aa-4db1-a3ea-fdc2a81bdebd\n# \u255f\u2500260d5753-6cc2-4137-8a2c-8d8a47585ecf\n# \u2560\u2550a9981931-4cc9-4d16-a6d2-34b4071a84d7\n# \u255f\u2500b4154fb7-e0b0-4211-8490-8a8fe47cd2da\n# \u2560\u25508ac7b1bf-c958-4eb5-8376-f802b372e796\n# \u255f\u2500b5008faf-fd43-45dd-a5a1-7f51e0b4ede5\n# \u2560\u2550a756dd18-fac6-4527-944e-c16d8cc4bf95\n# \u2560\u2550555d1f62-b95b-4377-a8e2-9e442ee7526d\n# \u2560\u2550f5510c1e-9b9f-49f0-bc7e-0fd8e79a5760\n# \u2560\u25507f556f7c-cdb0-4f91-a359-2f933bbc5b68\n# \u2560\u25505d9a40b5-4050-47d2-9855-e9b62d56e8df\n# \u2560\u25500fc843d2-ac4f-4717-a298-92a476223112\n# \u2560\u2550fc7f665b-00d9-431b-a97e-d2ff7253221a\n# \u2560\u2550aadf6e48-0cbf-4973-86a1-173b6648d1df\n# \u2560\u2550452e1ea7-98be-4910-ba6b-c0881fb251b2\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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(\ud835\udf12\u207b\u00b9(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 = \ud835\udf12\u207b\u00b9(edge,x)\n#@show p\n\nmacro do_quad_ref2d_\u03941(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, \u03c7, 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}, \u03c7, 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, \u03c7, tol)\n        ld, ru = trg_svd(ld_ru, \u03c7, 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": "@testset \"HamiltonianProblem Test\" begin\n\n    @testset \"Scalar case test\" begin\n        H(d\u03b8, \u03b8, p) = d\u03b8 / 2 - 9.8 * cos(\u03b8)\n        p0, q0   = rand(2)\n        acc      = (v, x, p, t) -> ForwardDiff.derivative(x -> -H(v[1], x, p), x[1])\n        vel      = (v, x, p, t) -> ForwardDiff.derivative(v -> H(v, x[1], p), v[1])\n\n        prob1    = HamiltonianProblem(H, p0, q0, (0., 10.))\n        prob_1   = DynamicalODEProblem(acc, vel, p0, q0, (0., 10.))\n\n        @test test_solve(prob1, prob_1)\n    end\n\n    @testset \"Static Vector case test\" begin\n        p0 = @SVector rand(2)\n        q0 = @SVector rand(2)\n        H(d\u03b8, \u03b8, p) = d\u03b8[1] / 2 + d\u03b8[2] / 2 - 9.8 * cos(\u03b8[1]) - 9.8 * cos(\u03b8[2])\n        prob1    = HamiltonianProblem(H, p0, q0, (0., 10.))\n        acc      = (v, x, p, t) -> ForwardDiff.gradient(x -> -H(v, x, p), x)\n        vel      = (v, x, p, t) -> ForwardDiff.gradient(v -> H(v, x, p), v)\n        prob_1   = DynamicalODEProblem(acc, vel, p0, q0, (0., 10.))\n        @test test_solve(prob1, prob_1)\n    end\n\n    @testset \"Vector case test\" begin\n        H(d\u03b8, \u03b8, p) = (d\u03b8 / 2 - 9.8 * cos.(\u03b8))[1]\n        p0, q0 = [rand(5) for i in 1:2]\n        acc = (dv, v, x, p, t) -> ForwardDiff.gradient!(dv, x -> -H(v, x, p), x)\n        vel = (dx, v, x, p, t) -> ForwardDiff.gradient!(dx, v -> H(v, x, p), v)\n        prob2  = HamiltonianProblem(H, p0, q0, (0., 10.))\n        prob_2 = DynamicalODEProblem(acc, vel, p0, q0, (0., 10.))\n        @test test_solve(prob2, prob_2)\n    end\nend", "meta": {"hexsha": "3c058ba96707242910258b042dee723e112f0f5c", "size": 1478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/hamiltonian_test.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqPhysics.jl-055956cb-9e8b-5191-98cc-73ae4a59e68a", "max_stars_repo_head_hexsha": "674a4fc45c08b456dadb9e8944b5569729475dfe", "max_stars_repo_licenses": ["MIT"], "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/hamiltonian_test.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqPhysics.jl-055956cb-9e8b-5191-98cc-73ae4a59e68a", "max_issues_repo_head_hexsha": "674a4fc45c08b456dadb9e8944b5569729475dfe", "max_issues_repo_licenses": ["MIT"], "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/hamiltonian_test.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DiffEqPhysics.jl-055956cb-9e8b-5191-98cc-73ae4a59e68a", "max_forks_repo_head_hexsha": "674a4fc45c08b456dadb9e8944b5569729475dfe", "max_forks_repo_licenses": ["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.2285714286, "max_line_length": 84, "alphanum_fraction": 0.4939106901, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.757960820419561}}
{"text": "# permutations\n@test collect(permutations(\"abc\")) == Any[['a','b','c'],['a','c','b'],['b','a','c'],\n                                          ['b','c','a'],['c','a','b'],['c','b','a']]\n\n@test collect(Iterators.filter(x->(iseven(x[1])),permutations([1,2,3]))) == Any[[2,1,3],[2,3,1]]\n@test collect(Iterators.filter(x->(iseven(x[3])),permutations([1,2,3]))) == Any[[1,3,2],[3,1,2]]\n\n@test length(permutations(0)) == 1\n\n@test collect(permutations(\"abc\", 4)) == Any[]\n@test collect(permutations(\"abc\", 2)) == Any[['a','b'],['a','c'],['b','a'],\n                                             ['b','c'],['c','a'],['c','b']]\n@test collect(permutations(\"abc\", 0)) == Any[Char[]]\n@test collect(permutations(\"abc\", -1)) == Any[]\n@test collect(permutations(\"\", 1)) == Any[]\n@test collect(permutations(\"\", 0)) == Any[Char[]]\n@test collect(permutations(\"\", -1)) == Any[]\n\n@inferred first(permutations(\"abc\", 2))\n\n# multiset_permutations\n@test collect(multiset_permutations(\"aabc\", 5)) == Any[]\n@test collect(multiset_permutations(\"aabc\", 2)) == Any[['a','a'],['a','b'], ['a','c'],['b','a'],\n                                                       ['b','c'],['c','a'],['c','b']]\n@test collect(multiset_permutations(\"aabc\", 0)) == Any[Char[]]\n@test collect(multiset_permutations(\"aabc\", -1)) == Any[]\n@test collect(multiset_permutations(\"\", 1)) == Any[]\n@test collect(multiset_permutations(\"\", 0)) == Any[Char[]]\n@test collect(multiset_permutations(\"\", -1)) == Any[]\n@test length(multiset_permutations(\"aaaaaaaaaaaaaaaaaaaaab\", 21)) == 22\n\n#nthperm!\nfor n = 0:7, k = 1:factorial(n)\n    p = nthperm!([1:n;], k)\n    @test isperm(p)\n    @test nthperm(p) == k\nend\n#Euler Problem #24\n@test nthperm!([0:9;],1000000) == [2,7,8,3,9,1,5,4,6,0]\n\n@test_throws ArgumentError nthperm([0, 1, 2], 0)\n@test nthperm([0, 1, 2], 1) == [0, 1, 2]\n@test nthperm([0, 1, 2], 3) == [1, 0, 2]\n@test nthperm([0, 1, 2], 6) == [2, 1, 0]\n@test_throws ArgumentError nthperm([0, 1, 2], 7)\n\n@test_throws ArgumentError nthperm([0:20;], big(0))\n@test nthperm([0:20;], big(1)) == [0:20;]\n@test nthperm([0:20;], factorial(big(20))) == [0; 20:-1:1]\n@test nthperm([0:20;], factorial(big(21))) == [20:-1:0;]\n@test_throws ArgumentError nthperm([0:20;], factorial(big(21)) + 1)\n\n# Immutable AbstractArrays\n@test nthperm(1:5, 1) == [1,2,3,4,5]\n\n@test_throws ArgumentError parity([0])\n@test_throws ArgumentError parity([1,2,3,3])\n@test levicivita([1,1,2,3]) == 0\n@test levicivita([1]) == 1 && parity([1]) == 0\n@test map(levicivita, collect(permutations([1,2,3]))) == [1, -1, -1, 1, 1, -1]\n@test let p = [3, 4, 6, 10, 5, 2, 1, 7, 8, 9]; levicivita(p) == 1 && parity(p) == 0; end\n@test let p = [4, 3, 6, 10, 5, 2, 1, 7, 8, 9]; levicivita(p) == -1 && parity(p) == 1; end\n\n@test Combinatorics.nsetpartitions(-1) == 0\n@test collect(permutations([])) == Vector[[]]\n", "meta": {"hexsha": "cc564df4f087def6e3f26ce814ea1d6bd68ffec0", "size": 2797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/permutations.jl", "max_stars_repo_name": "Sedictious/Combinatorics.jl", "max_stars_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 165, "max_stars_repo_stars_event_min_datetime": "2016-09-13T17:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:29:52.000Z", "max_issues_repo_path": "test/permutations.jl", "max_issues_repo_name": "Sedictious/Combinatorics.jl", "max_issues_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86, "max_issues_repo_issues_event_min_datetime": "2016-08-25T18:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T12:58:42.000Z", "max_forks_repo_path": "test/permutations.jl", "max_forks_repo_name": "Sedictious/Combinatorics.jl", "max_forks_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2016-10-29T00:18:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T10:21:39.000Z", "avg_line_length": 42.3787878788, "max_line_length": 96, "alphanum_fraction": 0.5591705399, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7579608195943424}}
{"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 \u03c0^(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\u00e9nyi 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\u00e9nyi 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 = \u03c0^(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 \u2208 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\u03b2 = 0.99;\n\u03c3 = 2;\n\u03b3 = 1;\n\n## Utility functions\nu(x) = x^(1 - \u03c3) / (1 - \u03c3);\nv(x) = x^(1 + 1/\u03b3) / (1 + 1/\u03b3);\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 \u03b8\ninclude(\"Tauchen.jl\")\ng, Pg = Tauchen(0.95, (1.2/15)^2, 5, (1 - 0.95) * log(0.15));\n\u03b8, P\u03b8 = Tauchen(0.95, (2/400)^2, 5, (1 - 0.95) * log(1));\ns = vec(collect(Iterators.product(\u03b8, g)));\nPs = kron(Pg, P\u03b8)\n\ninclude(\"NewtonRoot.jl\");\n\n## This function calculates Ramsey Allocation, given \u03a6 and initial state s0 \nfunction RamseyAllocation(\u03a6::Real, s0::Tuple)\n\n    function time1_allocation(s::Tuple)\n        log_\u03b8, log_g = s[1], s[2];\n        \u03b8, g = exp(log_\u03b8), exp(log_g);\n        n(c::Real) = (g + c) / \u03b8;\n        res1(c::Real) = (1 + \u03a6) * (Uc(c) + Un(n(c))) + \u03a6 * (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_\u03b8, log_g = s[1], s[2];\n        \u03b8, g = exp(log_\u03b8), exp(log_g);\n        n(c::Real) = (g + c) / \u03b8;\n        b0(c::Real) = 4 * \u03b8 * n(c);\n        res0(c::Real) = (1 + \u03a6) * (Uc(c) + Un(n(c))) + \u03a6 * (c * Ucc(c) + n(c) * Unn(n(c))) - \u03a6 * 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 \u03a6:\nc_time1, n_time1, c_time0, n_time0 = RamseyAllocation(0.12615792845184043, s[1])\n\nsum_mat = inv(1.0I - \u03b2 * 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 - \u03b2 * sum([Ps[1,i] * sum_mat[i] for i in 1:length(sum_mat)]);\n\nb_time1 = sum_mat ./ Uc.(c_time1);\n\n\u03c4_time1 = 1.0 .+ Un.(n_time1) ./ Uc.(c_time1);\n\n## Root finding method for \u03a6\n\nfunction search_\u03a6(\u03a6::Real, s0::Tuple)\n    c_time1, n_time1, c_time0, n_time0 = RamseyAllocation(\u03a6, s0);\n    \n    i_s0 = findfirst(isequal(s0), s);\n\n    sum_mat = inv(1.0I - \u03b2 * 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 - \u03b2 * sum([Ps[i_s0,i] * sum_mat[i] for i in 1:length(sum_mat)]);\n\n    return implementCons\n\nend\n\n\u03a6_est = NewtonRoot(x -> search_\u03a6(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\u03c4_sim = [\u03c4_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(\u03c4_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  (\u03b2,\u03b3) = p\n  (S0,I0) = u0\n   return [S(0)-S0,\n           I(0)-I0,\n           S' + \u03b2*S*I,\n           I' - \u03b2*S*I + \u03b3*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]; # \u03b2,\u03b3\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 Test, CopEnt\nusing LinearAlgebra: det\n\n@testset \"Entropy of univraite normal\" begin\n    for \u03c3 in [1, 2, 3]\n        x = randn(1_000) * \u03c3\n        ent = 1 / 2 * log(2 * \u03c0 * \u212f * \u03c3^2)\n        @test entropy_knn(x) \u2248 ent atol=0.1\n    end\nend\n\n@testset \"Entropy of bivariate normal\" begin\n    for \u03c31 in [1, 2, 3], \u03c32 in [1, 2, 3]\n        x = randn(2, 1_000) .* [\u03c31, \u03c32] \n        ent = 1 / 2 * log(det(2 * \u03c0 * \u212f * [\u03c31^2 0; 0 \u03c32^2]))\n        @test entropy_knn(x) \u2248 ent atol=0.1\n    end\nend\n\n@testset \"Checking against pycopent\" begin\n    x = hcat(\n        [-0.89395472, -1.48611224],\n        [ 0.82243227, -1.5848612 ],\n        [-1.26209653, -0.24610746],\n        [-0.20907981,  1.51772724],\n        [-0.59596898, -0.24640368],\n        [-0.28688517,  0.6399274 ],\n        [-1.32899876, -1.13641078],\n        [-0.36206995, -0.42210696],\n        [ 0.21879637,  1.21598259],\n        [-0.48603486, -1.84245597],\n    )\n\n    cpy = hcat(\n        [0.3, 0.3],\n        [1. , 0.2],\n        [0.2, 0.7],\n        [0.8, 1. ],\n        [0.4, 0.6],\n        [0.7, 0.8],\n        [0.1, 0.4],\n        [0.6, 0.5],\n        [0.9, 0.9],\n        [0.5, 0.1],\n    )\n    entpy_euclidean = 2.884534529955401\n    entpy_chebyshev = 2.9414966444360235\n    copentpy_euclidean = 0.7167856845750248\n    copentpy_chebyshev = 0.6760921005096859\n\n    @test empirical_copula(x) == cpy\n    @test entropy_knn(x; dist=Euclidean()) \u2248 entpy_euclidean\n    @test entropy_knn(x; dist=Chebyshev()) \u2248 entpy_chebyshev\n    @test copula_entropy(x; dist=Euclidean()) \u2248 copentpy_euclidean\n    @test copula_entropy(x; dist=Chebyshev()) \u2248 copentpy_chebyshev\nend\n", "meta": {"hexsha": "7a2cca09dc40aa57356301576cce5b964834df82", "size": 1600, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "xukai92/CopEnt.jl", "max_stars_repo_head_hexsha": "7accf24117c8a813fa27165d417b8ffaaf98ac3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-23T21:30:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T11:33:57.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "xukai92/CopEnt.jl", "max_issues_repo_head_hexsha": "7accf24117c8a813fa27165d417b8ffaaf98ac3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-13T06:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-13T06:53:22.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "xukai92/CopEnt.jl", "max_forks_repo_head_hexsha": "7accf24117c8a813fa27165d417b8ffaaf98ac3c", "max_forks_repo_licenses": ["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.0701754386, "max_line_length": 66, "alphanum_fraction": 0.54375, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.75793239011607}}
{"text": "using SymPy\nusing Test\nusing SpecialFunctions\n\n@testset \"Math\" begin\n    \u03c1 = symbols(\"rho\", positive=true)\n    \u03d5 = symbols(\"phi\", real=true)\n    x = symbols(\"x\")\n\n    @test simplify(hypot(\u03c1*cos(\u03d5), \u03c1 * sin(\u03d5))) == \u03c1\n    @test simplify(hypot(\u03c1*cos(\u03d5), 3)) == sqrt(\u03c1^2*cos(\u03d5)^2 + 9)\n\n    @test atan(Sym(1), 1) == PI/4\n    @test atan(Sym(1), -1) == 3PI/4\n\n    @test factorial(Sym(0)) == 1\n    @test factorial(Sym(7)) == 5040\n\n    @test sympy.factorial2(Sym(5)) == 15\n    @test sympy.factorial2(Sym(-5)) == Sym(1)/3\n\n    @test erf(Sym(0)) == 0\n    @test erf(Sym(oo)) == 1\n    @test diff(erf(x), x) == 2*exp(-x^2)/sqrt(PI)\n\n\n    @test sinc(Sym(0)) == 1\n    # test consistency with Julia's sinc\n    @test sinc(Sym(1)) == 0\n    @test N(sinc(Sym(0.2))) \u2248 sinc(0.2)\n\n    @test flipsign(Sym(3), 2.0) == 3\n    @test flipsign(Sym(3), 0.0) == 3\n    @test flipsign(Sym(3), -0.0) == -3\n    @test flipsign(Sym(3), -2.0) == -3\n\n    @test eps(Sym) == 0\n    #@test rewrite(sinc(x), \"jn\") == jn(0, PI * x)\n\n    @test abs2(x) == conj(x)*x\n    @test abs(x) == sqrt(conj(x)*x)\nend\n", "meta": {"hexsha": "dd1648a3426456c790df4674bc2d231bb92d7be1", "size": 1058, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-math.jl", "max_stars_repo_name": "benneti/SymPy.jl", "max_stars_repo_head_hexsha": "6a28bfd5286e6214ac3fec0f0ca2bdea4c0e1442", "max_stars_repo_licenses": ["MIT"], "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-math.jl", "max_issues_repo_name": "benneti/SymPy.jl", "max_issues_repo_head_hexsha": "6a28bfd5286e6214ac3fec0f0ca2bdea4c0e1442", "max_issues_repo_licenses": ["MIT"], "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-math.jl", "max_forks_repo_name": "benneti/SymPy.jl", "max_forks_repo_head_hexsha": "6a28bfd5286e6214ac3fec0f0ca2bdea4c0e1442", "max_forks_repo_licenses": ["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.6046511628, "max_line_length": 64, "alphanum_fraction": 0.5359168242, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.757932388909788}}
{"text": "@testset \"ch06\" begin\n    Random.seed!(1234)\n    rng = MersenneTwister(1234)\n    function create_toy_data(func, n_samples::Int64, std = 1.0, domain = [0.0, 1.0])\n        x = collect(range(domain[1], domain[2], length = n_samples))\n        shuffle!(rng, x)\n        noise = rand(Uniform(-std, std), n_samples)\n        return x, func.(x) + noise\n    end\n\n    function sinusoidal(x)\n        return sin.(2 * pi .* x)\n    end\n\n    @testset \"ch06_1\" begin\n        x_train, y_train = create_toy_data(sinusoidal, 10, 0.2)\n\n        x_train = reshape(x_train, 1, size(x_train)[1])\n        model = GaussianProcessRegressor(PolynomialKernel(3, 1.0), 1e10)\n        fitting(model, x_train, y_train)\n\n        x = reshape(collect(range(0.0, 1.0, length = 100)), 1, 100)\n        y, y_sigmas = predict(model, x, true)\n    end\n\n    @testset \"ch06_2\" begin\n        x_train, y_train = create_toy_data(sinusoidal, 7, 0.1, [0.0, 0.7])\n        x_train = reshape(x_train, 1, size(x_train)[1])\n        model = GaussianProcessRegressor(RBFKernel([1.0, 15.0]), 100)\n        fitting(model, x_train, y_train)\n\n        x = reshape(collect(range(0.0, 1.0, length = 100)), 1, 100)\n        y, y_sigmas = predict(model, x, true)\n\n        y_std = sqrt.(reshape(y_sigmas, length(y_sigmas)))\n    end\nend\n", "meta": {"hexsha": "b37d48a536885cf73b5b637bfb252b889796a6cb", "size": 1265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch06.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": "test/ch06.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": "test/ch06.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": 33.2894736842, "max_line_length": 84, "alphanum_fraction": 0.6031620553, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8006920116079208, "lm_q1q2_score": 0.7579323884250916}}
{"text": "using PhysicalConstants.CODATA2018: FineStructureConstant, ReducedPlanckConstant, ElectronMass, SpeedOfLightInVacuum\n\n\"\"\"\ncomptonShift(\u03b8, 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 `\u03b8` radians.\n\"\"\"\ncomptonShift(\u03b8, E) = 1.0 / (1.0 + (E / m\u2091) * (1.0 - cos(\u03b8)))\ncomptonShift(\u03b8, cxr::CharXRay) = comptonShift(\u03b8, energy(cxr))\n\n\"\"\"\ncomptonEnergy(\u03b8, 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 `\u03b8` radians.\n\"\"\"\ncomptonEnergy(\u03b8, E) = E * comptonShift(\u03b8, E)\ncomptonEnergy(\u03b8, cxr::CharXRay) = comptonEnergy(\u03b8, energy(cxr))\n\n\"\"\"\ncomptonAngular(\u03b8, E)\n\nThe angular distribution function of Compton scattered X-rays of incident energy `E` scattered to an angle `\u03b8`.\n\nBased on the Klein-Nishina formula for Compton scattering. It has been normalized so that the integral over d\u03a9 = 2\u03c0\u22c5sin(\u03b8) d\u03b8 equals one.\n\"\"\"\nfunction comptonAngular(\u03b8, E)\n  p = comptonShift(\u03b8, E)\n  den = (4\u03c0*m\u2091*((E*(E^3 + 9*E^2*m\u2091 + 8*E*m\u2091^2 + 2*m\u2091^3))/(2E +m\u2091)^2 + (E^2 - 2*E*m\u2091 - 2*m\u2091^2)*atan(E/(E + m\u2091))))/E^3\n  return p^2*(p + 1.0/p - sin(\u03b8)^2)/den\nend\ncomptonAngular(\u03b8, cxr::CharXRay) = comptonAngular(\u03b8, energy(cxr))\n\n\n\"\"\"\n  comptonDifferential(\u03b8, E)\n\nDifferential crosssection d\u03c3/d\u03a9 = d\u03c3/(sin(\u03b8) d\u03b8 d\u03d5) for Compton scattering in cm\u00b2.\n\"\"\"\nfunction comptonDifferential(\u03b8, E) \n  \u03b1, rc =  convert(Float64,FineStructureConstant), convert(Float64,(ReducedPlanckConstant/(ElectronMass*SpeedOfLightInVacuum))/u\"cm\")\n  p = comptonShift(\u03b8, E)\n  return 0.5*(\u03b1*rc*p)^2*(p + 1.0/p - sin(\u03b8)^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": "using LinearAlgebra\nusing DataFrames\nusing Test\nprintln(\"LATHE.PREPROCESS TESTS\")\nprintln(\"......................\")\n# DECOMPOSITION\nusing Lathe.preprocess: SVD\n@testset \"svd test for $T\" for T in (Float32, Float64)\n  A = randn(T, 100, 100)\n  x = SVD(A)\n  tol = T == Float32 ? 1e-5 : 1e-10\n  @test (norm(A - (x.U * diagm(0 => x.S) * x.V'), 2) / norm(A, 2)) <= tol\nend\nusing Lathe.preprocess: OneHotEncoder, FloatEncoder, OrdinalEncoder\n# ENCODING\ndf = DataFrame(:A => [5, 10, 15, 20], :B => [\"test\", \"test2\", \"test2\", \"test\"])\n@testset \"OneHotEncoder Tests\" begin\nencoder = OneHotEncoder()\nant = size(df)[2]\ndata = encoder.predict(df, :A)\nlen = Set(df[!, :A])\n@test size(data)[2] - ant == length(len)\n\nend\n@testset \"OrdinalEncoder Tests\" begin\nencoder = OrdinalEncoder(df[!, :B])\nencoded = encoder.predict(df[!, :B])\ninverse = [z => x for (x, z) in encoder.lookup]\nencoded = [inverse[i] for i in encoded]\nfor (i, c) in zip(encoded, df[!, :B])\n  @test i == c\nend\nend\n@testset \"FloatEncoder Tests\" begin\n  encoder = FloatEncoder()\n  FloatEncoder.predict(df[!, :B])\n  @test typeof(df[!, :B][1]) == Float64\nend\n", "meta": {"hexsha": "0b8538404cb64629af4be20b13ea8127c5b1bffa", "size": 1106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/src/preprocesstests.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": "test/src/preprocesstests.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": "test/src/preprocesstests.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": 28.358974359, "max_line_length": 79, "alphanum_fraction": 0.6374321881, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739774, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7579323737128157}}
{"text": "using SpecialMatrices\nusing Base.Test  \n\ninclude(\"companion.jl\") #Companion matrix\ninclude(\"frobenius.jl\") #Frobenius matrix\ninclude(\"strang.jl\") #Strang matrix\ninclude(\"hankel.jl\") #Hankel matrix\ninclude(\"hilbert.jl\") #Hilbert matrix\ninclude(\"toeplitz.jl\") #Toeplitz matrix\ninclude(\"vandermonde.jl\") #Vandermonde matrix\n", "meta": {"hexsha": "10e83161402b4ac0567b5c361e5195e66799857a", "size": 321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 29.1818181818, "max_line_length": 45, "alphanum_fraction": 0.7788161994, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897542390752, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7579305178595582}}
{"text": "## test_plot.jl : test plotting commands\n\n## 1D ##\nm = Matern(0.75,1,p=1.)\ncov = CovarianceFunction(1,m)\npts = 0:0.01:1\ngrf1 = GaussianRandomField(cov,KarhunenLoeve(500),pts)\nplot(grf1,n=10); close()\n\n## 2D ##\ne = Exponential(0.01)\ncov = CovarianceFunction(2,e)\npts = 0:0.05:1\ngrf2 = GaussianRandomField(cov,KarhunenLoeve(10),pts,pts)\nplot(grf2)\nsurf(grf2)\ncontourf(grf2)\ncontour(grf2)\n\n## 3D ##\nm = Exponential(0.5)\ncov = CovarianceFunction(3,m)\npts = 0:0.1:1\ngrf3 = GaussianRandomField(cov,KarhunenLoeve(10),pts,pts,pts)\nplot(grf3); close()\nplot(grf3,ix=1); close()\n\n## Separable ##\ne1 = Exponential(0.1,p=1)\ne2 = Exponential(0.01,p=1)\ne3 = Exponential(0.001,p=1)\nsp1 = SeparableCovarianceFunction(e1)\nsp2 = SeparableCovarianceFunction(e1,e2)\nsp3 = SeparableCovarianceFunction(e1,e2,e3)\npts = 0:0.01:1\nsg1 = GaussianRandomField(sp1,KarhunenLoeve(10),pts)\nsg2 = GaussianRandomField(sp2,KarhunenLoeve(10),pts,pts)\nsg3 = GaussianRandomField(sp3,KarhunenLoeve(10),pts,pts,pts)\n\n## Eigenvalues/functions ##\nplot_eigenvalues(grf1); close()\nplot_eigenvalues(grf2); close()\nplot_eigenvalues(sg2); close()\nplot_eigenfunction(grf1,1); close()\nplot_eigenfunction(grf2,1); close()\nplot_eigenfunction(grf3,1); close()\nplot_eigenfunction(sg1,1); close()\nplot_eigenfunction(sg2,1); close()\nplot_eigenfunction(sg3,1); close()\n", "meta": {"hexsha": "5b680f89f0d376dee341e153d1ccae75b94eac45", "size": 1312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_plot.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": "test/test_plot.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": "test/test_plot.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": 26.24, "max_line_length": 61, "alphanum_fraction": 0.7370426829, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7579305116520203}}
{"text": "include(\"differencial.jl\")\r\n\"\"\"\r\n`RK4(F,A,dt)`\r\nRunge-Kutta\u6cd5\u3067\u523b\u307f\u6642\u9593`dt`\u79d2\u5f8c\u306eF\u306e\u5024\u3092\u8a08\u7b97\u3059\u308b\u95a2\u6570\r\n## Arguments\r\n- `F::Any`: \u8a08\u7b97\u3057\u305f\u3044\u6642\u9593`t`\u306e\u95a2\u6570\u306e`t`\u79d2\u6642\u70b9\u306e\u5024 \u95a2\u6570`dif`\u3067\u5fae\u5206\u5024\u3092\u6c42\u3081\u3089\u308c\u308b\u3082\u306e\r\n- `A::Any`:\u5fae\u5206\u8a08\u7b97\u306b\u5fc5\u8981\u306a\u5b9a\u6570\u306e\u7d44\r\n- `dt::Number`  :\u523b\u307f\u6642\u9593\r\n## Returns\r\n- `dt`\u79d2\u5f8c\u306eF\u306e\u5024\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    \ud835\udf12\u00b2 = pearson_chi(bincounts, bin_expected)\n\n    # calculate X2/DF and return it\n    return \ud835\udf12\u00b2 / nbins\nend\n\nfunction pearson_chi(\n    observed::AbstractVector{T},\n    expected::AbstractVector{T}\n) where {T <: Integer}\n    \u03c7\u00b2 = 0\n    for i = 1:length(observed)\n        \u03c7\u00b2 += (observed[i] - expected[i])^2 / expected[i]\n    end\n    return \u03c7\u00b2\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": "\"\"\"\n    Circumsphere(simplex)\n\nCompute the circumsphere of a simplex (a matrix whose columns represent the vertices of the\nsimplex). Returns a column vector where the first entry is the radius of the circumsphere\nand the remaining entries represent the centroid.\n\n\"\"\"\nfunction Circumsphere(simplex)\n    n::Int = size(simplex, 1) # Dimension of the space the simplex lives in\n    centroid = simplex * ones(n + 1, 1) / (n + 1)\n    centroidmatrix = repeat(centroid, 1, n + 1)\n\n    radius::Float64 = sqrt(maximum(ones(1, n) * ((simplex - centroidmatrix).^2)))\n\n    return [radius; centroid]\nend\n", "meta": {"hexsha": "be64ac0f5e382a1cd54a9fff20e94f0b431914d0", "size": 591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/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/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/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": 32.8333333333, "max_line_length": 91, "alphanum_fraction": 0.7089678511, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7579305032492833}}
{"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        \u03bc = [NaN64 for k in 1:n]\n        \u03b1 = 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        \u03bc[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] * \u03bc[k-1]\n            \u03bc[k] = h[k] / l[k]\n            z[k] = (\u03b1[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] - \u03bc[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\u00f3wnania 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\u00f3w 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": "# ---\n# title: 902. Numbers At Most N Given Digit Set\n# id: problem902\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Hard\n# categories: Math, Dynamic Programming\n# link: <https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/>\n# hidden: true\n# ---\n# \n# Given an array of `digits` which is sorted in **non-decreasing** order. You\n# can write numbers using each `digits[i]` as many times as we want. For\n# example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`,\n# `'551'`, and `'1351315'`.\n# \n# Return _the number of positive integers that can be generated_ that are less\n# than or equal to a given integer `n`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\n#     Output: 20\n#     Explanation:\n#     The 20 numbers that can be written are:\n#     1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: digits = [\"1\",\"4\",\"9\"], n = 1000000000\n#     Output: 29523\n#     Explanation:\n#     We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n#     81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n#     2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\n#     In total, this is 29523 integers that can be written using the digits array.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: digits = [\"7\"], n = 8\n#     Output: 1\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= digits.length <= 9`\n#   * `digits[i].length == 1`\n#   * `digits[i]` is a digit from `'1'` to `'9'`.\n#   * All the values in `digits` are **unique**.\n#   * `digits` is sorted in  **non-decreasing** order.\n#   * `1 <= n <= 109`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "71d25d92a23d28c8f882cc5bcfef1f6c7de89ff4", "size": 1830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/902.numbers-at-most-n-given-digit-set.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/902.numbers-at-most-n-given-digit-set.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/902.numbers-at-most-n-given-digit-set.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.7746478873, "max_line_length": 87, "alphanum_fraction": 0.5836065574, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7579187542590831}}
{"text": "\"\"\"Julia program to implement Quick sort\nQuick Sort is a Divide and Conquer strategy based sorting algoithm, that partitions the array\naround a selected pivot element. In the below implemented version of Quick Sort we always took the \nlast element as the pivot element.\n\n\"\"\"\nfunction  partition(arr, low, high)\n    # Select the last element as pivot\n    pivot = arr[high]\n    i = low - 1\n    for j in low:high\n        # Check if there is any element less than the pivot element\n        if(arr[j] < pivot)\n            i = i + 1\n            # Swap such an element with the to the start position\n            arr[i], arr[j] = arr[j], arr[i]\n        end\n    end\n    # Now place the pivot to its original position\n    arr[i+1], arr[high] = arr[high], arr[i+1]\n    return (i+1)\nend\n\nfunction quick_sort(arr, low, high)\n    if (low < high)\n        pi = partition(arr, low, high)\n        # Recursively call quick_sort function\n        quick_sort(arr, low, pi - 1)\n        quick_sort(arr, pi + 1, high)\n    end\nend\n       \n\n\nprint(\"How many numbers do you want to sort? \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n    println(\"No numbers to sort!!!\")\n    exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())]\nquick_sort(arr, 1, n)\nprint(\"The numbers in sorted order is \")\nprint(arr)\n\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\nHow many numbers do you want to sort? 5\nEnter the numbers: 4 2 5 1 3\nThe numbers in sorted order is [1, 2, 3, 4, 5]\n\n\"\"\"\n", "meta": {"hexsha": "245e06846a171ed8b18a31d9c5ca63af4f1d09f8", "size": 1576, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/sort/quick_sort.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/sort/quick_sort.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/sort/quick_sort.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": 25.0158730159, "max_line_length": 99, "alphanum_fraction": 0.635786802, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8670357546485407, "lm_q1q2_score": 0.757856226588584}}
{"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        \u03b8 = 2\u03c0 * rand()\n        push!(points, (r * sin(\u03b8) + noise * rand(), r * cos(\u03b8) + 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": "\"\"\"Julia program to implement Bubble Sort\nIn Bubble Sort we compare the adjacent elements and swap them such that the greater\nelement among them comes in the right-side. After each iteration, one smallest element\ngoes towars the end of the array.\n\"\"\"\n\nfunction bubble_sort(arr, n)\n    # Iterate the entire array\n    for i in 1:n\n        # Iterate till the concerned part only.\n        for j in 1:(n-i)\n            # Swap adjacent elements if they are in wrong order\n            if(arr[j] > arr[j+1])\n                arr[j], arr[j+1] = arr[j+1], arr[j]\n            end\n        end\n    end\nend\n            \n\nprint(\"How many numbers do you want to sort? \")\nn = readline()\nn = parse(Int64, n)\nif (n <= 0)\n    println(\"No numbers to sort!!!\")\n    exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())]\nbubble_sort(arr, n)\nprint(\"The numbers in sorted order is \")\nprint(arr)\n\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\nHow many numbers do you want to sort? 5\nEnter the numbers: 4 2 5 1 3\nThe numbers in sorted order is [1, 2, 3, 4, 5]\n\n\"\"\"\n", "meta": {"hexsha": "2c5547bd28e026ee80964510d28a4bf6c265719d", "size": 1167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/sort/bubble_sort.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/sort/bubble_sort.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/sort/bubble_sort.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": 23.8163265306, "max_line_length": 86, "alphanum_fraction": 0.6349614396, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.7578562108666481}}
{"text": "using HypothesisTests, Base.Test\nusing Distributions\n\n# This is always the null in our tests.\nnull = Normal(0.0, 1.0)\n\n## ONE SAMPLE T-TEST\n\n# One sample\nx = -5:5\n@test pvalue(OneSampleZTest(x)) == 1\n\nx = -5:10\nm, s, n = mean(x), std(x), length(x)\nse = s / sqrt(n)\nz = (m - 0) / se\n\ntst = OneSampleZTest(x)\n@test_approx_eq(pvalue(tst), 2 * min(cdf(null, z), ccdf(null, z)))\n@test_approx_eq(pvalue(tst; tail=:left), cdf(null, z))\n@test_approx_eq(pvalue(tst; tail=:right), ccdf(null, z))\nshow(IOBuffer(), tst)\n\ntst = OneSampleZTest(m, s, n)\n@test_approx_eq(pvalue(tst), 2 * min(cdf(null, z), ccdf(null, z)))\n@test_approx_eq(ci(tst)[1], m + quantile(null, 0.05 / 2) * se)\n@test_approx_eq(ci(tst)[2], m + cquantile(null, 0.05 / 2) * se)\n@test_approx_eq(ci(tst, 0.10)[1], m + quantile(null, 0.10 / 2) * se)\n@test_approx_eq(ci(tst, 0.10)[2], m + cquantile(null, 0.10 / 2) * se)\n@test_approx_eq(ci(tst; tail=:left)[1], -Inf)\n@test_approx_eq(ci(tst; tail=:left)[2], m + cquantile(null, 0.05) * se)\n@test_approx_eq(ci(tst; tail=:right)[1], m + quantile(null, 0.05) * se)\n@test_approx_eq(ci(tst; tail=:right)[2], Inf)\nshow(IOBuffer(), tst)\n\nx = -10:5\nm, s, n = mean(x), std(x), length(x)\nse = s / sqrt(n)\nz = (m - 0) / se\n\ntst = OneSampleZTest(x)\n@test_approx_eq(pvalue(tst), 2 * min(cdf(null, z), ccdf(null, z)))\n@test_approx_eq(pvalue(tst; tail=:left), cdf(null, z))\n@test_approx_eq(pvalue(tst; tail=:right), ccdf(null, z))\nshow(IOBuffer(), tst)\n\ntst = OneSampleZTest(m, s, n)\n@test_approx_eq(pvalue(tst), 2 * min(cdf(null, z), ccdf(null, z)))\n@test_approx_eq(ci(tst)[1], m + quantile(null, 0.05 / 2) * se)\n@test_approx_eq(ci(tst)[2], m + cquantile(null, 0.05 / 2) * se)\n@test_approx_eq(ci(tst, 0.10)[1], m + quantile(null, 0.10 / 2) * se)\n@test_approx_eq(ci(tst, 0.10)[2], m + cquantile(null, 0.10 / 2) * se)\n@test_approx_eq(ci(tst; tail=:left)[1], -Inf)\n@test_approx_eq(ci(tst; tail=:left)[2], m + cquantile(null, 0.05) * se)\n@test_approx_eq(ci(tst; tail=:right)[1], m + quantile(null, 0.05) * se)\n@test_approx_eq(ci(tst; tail=:right)[2], Inf)\nshow(IOBuffer(), tst)\n\n# Paired samples\nx, y = [1, 1, 2, 1, 0], [0, 1, 1, 1, 0]\nm, s, n = mean(x - y), std(x - y), length(x - y)\nse = s / sqrt(n)\nz = (m - 0) / se\ntst = OneSampleZTest(x, y)\n@test_approx_eq(pvalue(tst), 2 * min(cdf(null, z), ccdf(null, z)))\n\n## TWO SAMPLE Z-TESTS\n\na1 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99]\na2 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98]\n\ntst = EqualVarianceZTest(a1, a2)\nm1, s1sq, n1 = mean(a1), var(a1), length(a1)\nm2, s2sq, n2 = mean(a2), var(a2), length(a2)\nxbar = (m1 - m2)\navg_var = (n1 - 1) / (n1 + n2 - 2) * s1sq + (n2 - 1) / (n1 + n2 - 2) * s2sq\nse = sqrt(avg_var / n1 + avg_var / n2)\nz = xbar / se\n\n@test_approx_eq(tst.z, z)\n@test_approx_eq(pvalue(tst), 2 * min(cdf(null, z), ccdf(null, z)))\n@test_approx_eq(pvalue(tst; tail=:left), cdf(null, z))\n@test_approx_eq(pvalue(tst; tail=:right), ccdf(null, z))\n@test_approx_eq(ci(tst)[1], xbar + quantile(null, 0.05 / 2) * se)\n@test_approx_eq(ci(tst)[2], xbar + cquantile(null, 0.05 / 2) * se)\nshow(IOBuffer(), tst)\n\ntst = UnequalVarianceZTest(a1, a2)\nse = sqrt(s1sq / n1 + s2sq / n2)\nz = xbar / se\n@test_approx_eq(tst.z, z)\n@test_approx_eq(pvalue(tst), 2 * min(cdf(null, z), ccdf(null, z)))\n@test_approx_eq(pvalue(tst; tail=:left), cdf(null, z))\n@test_approx_eq(pvalue(tst; tail=:right), ccdf(null, z))\n@test_approx_eq(ci(tst)[1], xbar + quantile(null, 0.05 / 2) * se)\n@test_approx_eq(ci(tst)[2], xbar + cquantile(null, 0.05 / 2) * se)\nshow(IOBuffer(), tst)\n", "meta": {"hexsha": "5ce637e5e22c1f409e7033f6dd00fed754a6ea39", "size": 3489, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/z.jl", "max_stars_repo_name": "bjarthur/HypothesisTests.jl", "max_stars_repo_head_hexsha": "a964ed55157664c8c8bc3b01cc48f71fef1c90ce", "max_stars_repo_licenses": ["MIT"], "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/z.jl", "max_issues_repo_name": "bjarthur/HypothesisTests.jl", "max_issues_repo_head_hexsha": "a964ed55157664c8c8bc3b01cc48f71fef1c90ce", "max_issues_repo_licenses": ["MIT"], "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/z.jl", "max_forks_repo_name": "bjarthur/HypothesisTests.jl", "max_forks_repo_head_hexsha": "a964ed55157664c8c8bc3b01cc48f71fef1c90ce", "max_forks_repo_licenses": ["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.6020408163, "max_line_length": 75, "alphanum_fraction": 0.6316996274, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7577533495543869}}
{"text": "#=\nUsing names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.\n\nFor example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 \u00d7 53 = 49714.\n\nWhat is the total of all the name scores in the file?\n=#\n\nusing DelimitedFiles\n\nfunction namescore(name, index)\n  total = 0\n  for i in 1:length(name)\n    total += convert(Int64, name[i])-64\n  end\n  total *= index\nend\n\nfunction calc()\n  x = sort!(vec(readdlm(dirname(@__FILE__()) * \"/../Resources/p22.txt\", ',', AbstractString)))\n  total = 0\n  for i in 1:length(x)\n    total += namescore(x[i], i)\n  end\n  total\nend\n@time println(calc())\n", "meta": {"hexsha": "598f267dbf3c714ffa5e1c325cbca4c8831e3531", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p22.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/p22.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/p22.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.5357142857, "max_line_length": 303, "alphanum_fraction": 0.7028753994, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595161, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7577533474011279}}
{"text": "using RungeKutta: name, order, nstages, coefficients, weights, nodes\n\n@testset \"$(rpad(\"Explicit Tableaus\",80))\" begin\n\n    @test typeof(TableauExplicitEuler()) <: Tableau\n    @test order(TableauExplicitEuler()) == 1\n    @test nstages(TableauExplicitEuler()) == 1\n\n    @test  isexplicit(TableauExplicitEuler())\n    @test !isimplicit(TableauExplicitEuler())\n    @test !isdiagnonallyimplicit(TableauExplicitEuler())\n    @test !isfullyimplicit(TableauExplicitEuler())\n    \n    @test TableauExplicitEuler() == TableauExplicitEuler()\n\n    @test typeof(TableauExplicitMidpoint()) <: Tableau\n    @test order(TableauExplicitMidpoint()) == 2\n    @test nstages(TableauExplicitMidpoint()) == 2\n\n    @test  isexplicit(TableauExplicitMidpoint())\n    @test !isimplicit(TableauExplicitMidpoint())\n    @test !isdiagnonallyimplicit(TableauExplicitMidpoint())\n    @test !isfullyimplicit(TableauExplicitMidpoint())\n\n    @test typeof(TableauHeun2()) <: Tableau\n    @test order(TableauHeun2()) == 2\n    @test nstages(TableauHeun2()) == 2\n\n    @test typeof(TableauHeun3()) <: Tableau\n    @test order(TableauHeun3()) == 3\n    @test nstages(TableauHeun3()) == 3\n\n    @test typeof(TableauRalston2()) <: Tableau\n    @test order(TableauRalston2()) == 2\n    @test nstages(TableauRalston2()) == 2\n\n    @test typeof(TableauRalston3()) <: Tableau\n    @test order(TableauRalston3()) == 3\n    @test nstages(TableauRalston3()) == 3\n\n    @test typeof(TableauRunge()) <: Tableau\n    @test order(TableauRunge()) == 2\n    @test nstages(TableauRunge()) == 2\n\n    @test TableauRunge2() == TableauRunge()\n\n    @test typeof(TableauKutta()) <: Tableau\n    @test order(TableauKutta()) == 3\n    @test nstages(TableauKutta()) == 3\n\n    @test TableauKutta3() == TableauKutta()\n\n    @test typeof(TableauRK416()) <: Tableau\n    @test order(TableauRK416()) == 4\n    @test nstages(TableauRK416()) == 4\n\n    @test TableauRK4() == TableauRK416()\n\n    @test  isexplicit(TableauRK4())\n    @test !isimplicit(TableauRK4())\n    @test !isdiagnonallyimplicit(TableauRK4())\n    @test !isfullyimplicit(TableauRK4())\n    \n    @test typeof(TableauRK438()) <: Tableau\n    @test order(TableauRK438()) == 4\n    @test nstages(TableauRK438()) == 4\n\n    @test typeof(TableauSSPRK2()) <: Tableau\n    @test order(TableauSSPRK2()) == 2\n    @test nstages(TableauSSPRK2()) == 2\n\n    @test typeof(TableauSSPRK3()) <: Tableau\n    @test order(TableauSSPRK3()) == 3\n    @test nstages(TableauSSPRK3()) == 3\n\nend\n\n\n@testset \"$(rpad(\"Diagonally Implicit Tableaus\",80))\" begin\n\n    @test typeof(TableauCrankNicolson()) <: Tableau\n    @test order(TableauCrankNicolson()) == 2\n    @test nstages(TableauCrankNicolson()) == 2\n    @test issymmetric(TableauCrankNicolson())\n\n    @test !isexplicit(TableauCrankNicolson())\n    @test  isimplicit(TableauCrankNicolson())\n    @test  isdiagnonallyimplicit(TableauCrankNicolson())\n    @test !isfullyimplicit(TableauCrankNicolson())\n    \n    @test typeof(TableauCrouzeix()) <: Tableau\n    @test order(TableauCrouzeix()) == 3\n    @test nstages(TableauCrouzeix()) == 2\n\n    @test !isexplicit(TableauCrouzeix())\n    @test  isimplicit(TableauCrouzeix())\n    @test  isdiagnonallyimplicit(TableauCrouzeix())\n    @test !isfullyimplicit(TableauCrouzeix())\n    \n    @test typeof(TableauKraaijevangerSpijker()) <: Tableau\n    @test order(TableauKraaijevangerSpijker()) == 2\n    @test nstages(TableauKraaijevangerSpijker()) == 2\n\n    @test typeof(TableauQinZhang()) <: Tableau\n    @test order(TableauQinZhang()) == 2\n    @test nstages(TableauQinZhang()) == 2\n    @test issymplectic(TableauQinZhang())\n\nend\n\n\n@testset \"$(rpad(\"Fully Implicit Tableaus\",80))\" begin\n\n    @test typeof(TableauImplicitEuler()) <: Tableau\n    @test order(TableauImplicitEuler()) == 1\n    @test nstages(TableauImplicitEuler()) == 1\n\n    @test !isexplicit(TableauImplicitEuler())\n    @test  isimplicit(TableauImplicitEuler())\n    @test !isdiagnonallyimplicit(TableauImplicitEuler())\n    @test  isfullyimplicit(TableauImplicitEuler())\n\n    @test TableauBackwardEuler() == TableauImplicitEuler()\n\n    @test typeof(TableauImplicitMidpoint()) <: Tableau\n    @test order(TableauImplicitMidpoint()) == 2\n    @test nstages(TableauImplicitMidpoint()) == 1\n    @test issymplectic(TableauImplicitMidpoint())\n    @test issymmetric(TableauImplicitMidpoint())\n\n    @test !isexplicit(TableauImplicitMidpoint())\n    @test  isimplicit(TableauImplicitMidpoint())\n    @test !isdiagnonallyimplicit(TableauImplicitMidpoint())\n    @test  isfullyimplicit(TableauImplicitMidpoint())\n\n    @test typeof(TableauSRK3()) <: Tableau\n    @test order(TableauSRK3()) == 4\n    @test nstages(TableauSRK3()) == 3\n    @test issymplectic(TableauSRK3())\n    @test issymmetric(TableauSRK3())\n    \nend\n", "meta": {"hexsha": "e7d59d1860547dbed2a7fea4cd5b5f4a9c202129", "size": 4679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_tableaus.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": "test/test_tableaus.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": "test/test_tableaus.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": 32.7202797203, "max_line_length": 68, "alphanum_fraction": 0.6890361188, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7577533415808716}}
{"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' \u00e9 a estrutura MathOptNLPModel do problema.\n###################################################\n\n# carrega pacotes necess\u00e1rios\nusing JuMP, NLPModels, NLPModelsJuMP, Printf, LinearAlgebra\n\n\n# FUN\u00c7\u00c3O 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\u00e3o para convergencia (opcional, padr\u00e3o=1.0e-6)\n    # maxiter : n\u00famero m\u00e1ximo de itera\u00e7\u00f5es (opcional, padr\u00e3o=1000)\n    # saidas  : mensagens na tela?\n\n    # DADOS DE SA\u00cdDA\n    # x       : \u00faltimo iterando\n    # f       : f(x)\n    # gradnorm: norma do infinito do gradiente de f\n    # iter    : n\u00famero de itera\u00e7\u00f5es\n    # status  : 0=sucesso, 1=falha\n\n    iter   = 0\n    status = 1\n\n    # par\u00e2metro busca linear inexata (Armijo)\n    eta = 0.5\n\n    # define ponto inicial caso n\u00e3o 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\u00e3o 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\u00e7alho sa\u00eddas\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\u00e7\u00e3o descida\n        d = -gradf\n\n        # retorna novo iterando ap\u00f3s 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\u00e7\u00e3o 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\u00edda\n    if saidas\n        println(\"\\n\\n*******************************\")\n        if status == 0\n            println(\"PROBLEMA RESOLVIDO COM SUCESSO!\")\n        else\n            println(\"FALHA NA RESOLU\u00c7\u00c3O.\")\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 / \u03c4) * exp(-(t - lastspike - \u03c4) / \u03c4) \u0398(t - lastspike)`\n  (where `\u0398` 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    \u0394 = t - lastspike\n\n    return (\u0394 >= 0 && \u0394 < Inf) * \u0394 * (q / tau) * exp(-(\u0394 - tau) / tau)\nend\nfunction alpha(t::Real, lastspike::AbstractArray{<:Real}, q::AbstractArray{<:Real}, tau::AbstractArray{<:Real})\n    \u0394 = t .- lastspike\n    I = @. \u0394 * (q / tau) * exp(-(\u0394 - tau) / tau)\n\n    return map((\u03b4, i) -> (\u03b4 >= 0) && (\u03b4 < Inf) ? \u03b4 * i : zero(i), \u0394, I)\nend\nfunction alpha(t::Real, lastspike::CuVecOrMat{<:Real}, q::CuVecOrMat{<:Real}, tau::CuVecOrMat{<:Real})\n    \u0394 = t .- lastspike\n\n    return @. (\u0394 >= 0) * (\u0394 < Inf) * \u0394 * (q / tau) * exp(-(\u0394 - 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": "\n\n# In this test we classify integers accoring to their divisor\nfunction divisortest()\n    @testset \"divisortest\" begin\n        ar=[1:100...]\n        r=Repo(ar,4)\n        for i in 1:100\n            a=mod(r[i],2)\n            b=mod(r[i],3)\n            if a==0 && b!=0 setclass!(r,i,2); end    #dividble by 2 but not 3\n            if a!=0 && b==0 setclass!(r,i,3); end    #dividble by 3 but not 2\n            if a==0 && b==0 setclass!(r,i,4); end    #dividble by 6\n        end\n        divble=class(r,4)\n        @test length(divble)==16    # 16 numbers<=100 muliples of 6\n        N=0\n        for x in divble\n            N+=1\n            @test mod(x,6)==0\n        end\n        @test N==16\n    end\n    return true\nend\n", "meta": {"hexsha": "f4c44eec5c76640ee21d9216108c008586880f0e", "size": 711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/usecase.jl", "max_stars_repo_name": "bridgewalker/Repos.jl", "max_stars_repo_head_hexsha": "a36b9b2bac79da05ac20b878fdd7829538fca023", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-04T00:47:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T16:13:04.000Z", "max_issues_repo_path": "test/usecase.jl", "max_issues_repo_name": "bridgewalker/Repos.jl", "max_issues_repo_head_hexsha": "a36b9b2bac79da05ac20b878fdd7829538fca023", "max_issues_repo_licenses": ["MIT"], "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/usecase.jl", "max_forks_repo_name": "bridgewalker/Repos.jl", "max_forks_repo_head_hexsha": "a36b9b2bac79da05ac20b878fdd7829538fca023", "max_forks_repo_licenses": ["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.3461538462, "max_line_length": 77, "alphanum_fraction": 0.4866385373, "num_tokens": 242, "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 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(\u03c0)/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) \u2265 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) \u2265 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": "using MultivariateStats\nusing Base.Test\n\nsrand(34568)\n\n## FA with zero mean\n\nX = randn(5, 10)\nY = randn(3, 10)\n\nW = qr(randn(5, 5))[1][:, 1:3]\n\u03a8 = fill(0.1, 5)\nM = FactorAnalysis(Float64[], W, \u03a8)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test mean(M) == zeros(5)\n@test loadings(M) == W\n@test var(M) == \u03a8\n\nT = inv(I+W'*diagm(1./var(M))*W)*W'*diagm(1./var(M))\n@test transform(M, X[:,1]) \u2248 T * X[:,1]\n@test transform(M, X) \u2248 T * X\n\nR = cov(M)*W*inv(W'W)\n@test reconstruct(M, Y[:,1]) \u2248 R * Y[:,1]\n@test reconstruct(M, Y) \u2248 R * Y\n\n\n## PCA with non-zero mean\n\nmv = rand(5)\nM = FactorAnalysis(mv, W, \u03a8)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test mean(M) == mv\n@test loadings(M) == W\n@test var(M) == \u03a8\n\n@test transform(M, X[:,1]) \u2248 T * (X[:,1] .- mv)\n@test transform(M, X) \u2248 T * (X .- mv)\n\n@test reconstruct(M, Y[:,1]) \u2248 R * Y[:,1] .+ mv\n@test reconstruct(M, Y) \u2248 R * Y .+ mv\n\n\n## prepare training data\n\nd = 5\nn = 1000\n\nR = qr(randn(d, d))[1]\n@test R'R \u2248 eye(5)\nscale!(R, sqrt.([0.5, 0.3, 0.1, 0.05, 0.05]))\n\nX = R'randn(5, n) .+ randn(5)\nmv = vec(mean(X, 2))\nZ = X .- mv\n\n# facm (default) & faem\nfa_methods = [:cm, :em]\n\nfas = FactorAnalysis[]\nfor method in fa_methods\n    M = fit(FactorAnalysis, X, method=method, tot=5000)\n    P = projection(M)\n    W = loadings(M)\n    push!(fas,M)\n\n    @test indim(M) == 5\n    @test outdim(M) == 4\n    @test mean(M) == mv\n    @test P'P \u2248 eye(4)\n    @test all(isapprox.(cov(M), cov(X, 2), atol=1e-3))\n\n    M = fit(FactorAnalysis, X; mean=mv, method=method)\n    @test loadings(M) \u2248 W\n\n    M = fit(FactorAnalysis, Z; mean=0, method=method)\n    @test loadings(M) \u2248 W\n\n    M = fit(FactorAnalysis, X; maxoutdim=3, method=method)\n    P = projection(M)\n\n    @test indim(M) == 5\n    @test outdim(M) == 3\n    @test P'P \u2248 eye(3)\nend\n\n# compare two algorithms\nM1, M2 = fas\n@test all(isapprox.(cov(M1), cov(M2), atol=1e-3)) # noise\nLL(m, x) = (-size(x,2)/2)*(size(x,1)*log(2\u03c0) + log(det(cov(m))) + trace(inv(cov(m))*cov(x,2)))\n@test LL(M1, X) \u2248 LL(M2, X) # log likelihood\n\n# test that fit works with Float32 values\nX2 = convert(Array{Float32,2}, X)\n# Float32 input\nM = fit(FactorAnalysis, X2; method=:cm, maxoutdim=3)\nM = fit(FactorAnalysis, X2; method=:em, maxoutdim=3)\n", "meta": {"hexsha": "babb6f2a26101f2c138fc52136f3b34f95efac03", "size": 2193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fa.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": "test/fa.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": "test/fa.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": 21.5, "max_line_length": 94, "alphanum_fraction": 0.5772913817, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7577100098173553}}
{"text": "using vOptSpecific\n\nusing Test\n\nprintln(\"Testing 2LAP...\")\nC1 = [3 9 0 0 6 10 7 5 16 11 ;\n16 0 6 12 19 8 17 10 9 18 ;\n2 7 11 15 8 10 10 12 8 6 ;\n4 11 7 16 3 13 18 11 11 7 ;\n14 19 7 0 4 19 8 13 9 10 ;\n11 4 17 14 19 5 16 2 17 4 ;\n8 14 7 15 2 11 0 1 14 11 ;\n8 8 3 15 8 7 14 9 0 16 ;\n11 3 12 8 9 11 6 5 5 15 ;\n2 5 1 9 0 4 12 13 5 6 ]\n\nC2 = [16 5 6 19 12 7 18 19 16 10 ;\n15 7 13 7 7 2 10 5 0 8 ;\n1 2 13 2 3 6 6 16 19 3 ;\n14 7 8 1 7 13 8 17 12 16 ;\n8 19 15 1 18 14 16 8 0 8 ;\n8 1 10 14 15 5 0 14 1 11 ;\n9 16 10 10 9 17 3 17 15 15 ;\n5 15 14 0 16 12 14 4 12 6 ;\n12 1 19 14 15 15 0 7 1 13 ;\n10 10 1 0 0 10 10 3 19 17 ]\n\nid = set2LAP(10, C1, C2)\nz1,z2,solutions = vSolve(id)\n\n@test z1 == [18,19,28,35,43,54,66,22,26,34,51]\n@test solutions[1,:] == [3, 2, 1, 5, 4, 10, 7, 9, 8, 6]\n\nid = load2LAP(\"../examples/2AP10-1A100.dat\")\nz1,z2,solutions = vSolve(id)\n\n@test z1 == [146, 155, 185, 271, 363, 478, 572, 149, 220, 267, 307, 402, 433]\n@test solutions[1,:] == [6, 3, 7, 9, 2, 10, 1, 5, 4, 8]\n\n\n\nprintln(\"\\nTesting 2UKP...\")\nid = set2UKP([1,2,3], [4,5,6], [7,8,9], 16)\nz1, z2, w, solutions = vSolve(id)\n\n@test z1 == [4]\n@test w == [16]\n@test solutions == [[1, 0, 1]]\n\nid = load2UKP(\"../examples/2KP500-1A.DAT\")\nz1, z2, w, solutions = vSolve(id)\n@assert length(z1) == 1682\n@assert extrema(z1) == (16028, 20360)\n@assert allunique(solutions)\n\n\nprintln(\"\\nTesting 2UMFLP...\")\nid = load2UMFLP(\"../examples/F50-51.txt\")\nz1, z2, facility_res, X, isEdge = vSolve(id)\n@test length(z1) == 198\n@test count(!iszero, X[21]) == 91\n@test count(isEdge) == 188\n\n\nprintln(\"\\nTesting 2OSP...\")\nid = set2OSP(4, [2, 4, 3, 1], [1, 2, 4, 6])\nz1, z2 , S = vSolve(id)\n\nfor i = 1:length(S)\n    println(\"(\", z1[i], \", \", z2[i], \") : \", S[i])\nend\n\n@test z1 == [20, 21, 27]\n@test z2 == [8, 6, 5]\n@test S == [[4, 1, 3, 2], [4, 1, 2, 3], [1, 2, 3, 4]]\n", "meta": {"hexsha": "01c97089b804196a817fff6bae9bce64bf6be31e", "size": 1807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "vOptSolver/vOptSpecific", "max_stars_repo_head_hexsha": "9705cf4fde20dfb14c7f7f6e32b7df1d597b383d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-10-06T06:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-15T13:23:44.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "vOptSolver/vOptSpecific", "max_issues_repo_head_hexsha": "9705cf4fde20dfb14c7f7f6e32b7df1d597b383d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-02-09T17:14:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-24T14:10:09.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "vOptSolver/vOptSpecific", "max_forks_repo_head_hexsha": "9705cf4fde20dfb14c7f7f6e32b7df1d597b383d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-08-28T22:28:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:33.000Z", "avg_line_length": 23.7763157895, "max_line_length": 77, "alphanum_fraction": 0.5628112894, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7577100030660363}}
{"text": "function compute_log_return_table(data_table::DataFrame,  date_key::Symbol, data_key::Symbol)::DataFrame\n    \n    # get the size of the table -\n    (number_of_rows, number_of_cols) = size(data_table)\n\n    # initialize -\n    return_array = Array{Float64,1}()\n    date_array = Array{Date,1}()\n\n    # compute -\n    for row_index = 2:number_of_rows\n        \n        # setup -\n        today_index = row_index\n        yesterday_index = row_index - 1\n    \n        # compute the return -\n        close_price_today = data_table[today_index,data_key]\n        close_price_yesterday = data_table[yesterday_index,data_key]\n        value = log(close_price_today/close_price_yesterday)\n        push!(return_array, value)\n\n        # grab te date -\n        today_timestamp = data_table[today_index,date_key]\n        push!(date_array, today_timestamp)\n    end\n\n    # build data frame and return -\n    return_table = DataFrame(timestamp=date_array, log_return=return_array)\n    return return_table\nend", "meta": {"hexsha": "753624e08da5c9dc497933a0743e8ebb4a7062ce", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Compute.jl", "max_stars_repo_name": "Pooksoft/BinomialEquityAssetPriceModel", "max_stars_repo_head_hexsha": "a4f5c0e12241dff112e7e3c3b34d452ed6f9bf02", "max_stars_repo_licenses": ["MIT"], "max_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": "Pooksoft/BinomialEquityAssetPriceModel", "max_issues_repo_head_hexsha": "a4f5c0e12241dff112e7e3c3b34d452ed6f9bf02", "max_issues_repo_licenses": ["MIT"], "max_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": "Pooksoft/BinomialEquityAssetPriceModel", "max_forks_repo_head_hexsha": "a4f5c0e12241dff112e7e3c3b34d452ed6f9bf02", "max_forks_repo_licenses": ["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.6774193548, "max_line_length": 104, "alphanum_fraction": 0.6761710794, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.757697728524957}}
{"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 : \u2211_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 \u21a6 0 if \u2016x\u2016_1 \u2a7d r, +\u221e 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 \u03bb\n  L = 0.0\n  U = maximum(abs, x)\n  \u03bb = L\n  v = 0.0\n  maxit = 120\n  for iter in 1:maxit\n    \u03bb = 0.5*(L + U)\n    v = sum(max.(abs.(x) .- \u03bb, 0.0))\n    # modify lower or upper bound\n    (v < f.r) ? U = \u03bb : L = \u03bb\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) .- \u03bb), 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, \u03bb_\u03bcm) computes the refractive index for a given wavelength in \u03bcm.\n\"\"\"\nrefindex{T}(::IndexFormula{T}, \u03bb_\u03bcm::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  \u03bbn::Bool\n  function SellmeierFormula(A,B,C,\u03bbn=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,\u03bbn)\n    end\n  end\nend\n\n\nfunction refindex{T}(formula::SellmeierFormula{T}, \u03bb_\u03bcm::T)\n  nsq=one(T)+formula.A\n  \u03bbsq = \u03bb_\u03bcm^2\n  for i = 1:formula.n\n    num = i==formula.n && !formula.\u03bbn ? formula.B[i] : formula.B[i] * \u03bbsq\n    nsq += num/(\u03bbsq - 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    \u03bc = 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, \u03c3)\n    #---------------------------------------------\n\n        sum(logpdf(MvNormal(\u03bc, W*W' + \u03c3*\u03c3*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 \u03c3 = exp(param[end]) + 1e-8\n\n        return W, \u03c3\n\n    end\n\n\n    #---------------------------------------------\n    function objective(param)\n    #---------------------------------------------\n\n        @assert(length(param) == D*Q + 1)\n\n        local W, \u03c3 = unpack(param)\n\n        try\n\n            return -1.0 * marginalLogLikelihood(W, \u03c3)\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, \u03c3   = unpack(result.minimizer)\n\n    # @show W, \u03bc, \u03c3\n    #\n    # #---------------------------------------------\n    # # Define projections\n    # #---------------------------------------------\n    #\n    # M = W'*W  + \u03c3*\u03c3*I # eq. (12.41) in Bishop\n    #\n    # proj(x::Array{T,1} where T<:Real) = vec(M \\ (W'*(x - \u03bc)))[1]\n    #\n    # fwd(z::Real) = vec(W*z + \u03bc)\n\n    return W, \u03bc, \u03c3#, 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    \u03f5::T\n\n    function QuadraticFit{T}(\u03f5) where {T}\n        0 < \u03f5 < 1 ? new{T}(\u03f5) : error(\"`\u03f5` must be in the interval (0, 1)\")\n    end\nend\n\n\"\"\"\n    QuadraticFit([\u03f5=0.01])\n\nInitialize quadratic fit search algorithm with optional argument `\u03f5` in the interval \n(0, 1) to choose a midpoint as `mid = \u03f5 * lower + (1 - \u03f5) * upper`.\n\"\"\"\nQuadraticFit(\u03f5=0.5) = QuadraticFit{typeof(\u03f5)}(\u03f5)\n\nfunction _optimize(f, lower::T, upper::T, alg::QuadraticFit; \n        reltol, abstol, maxiter) where {T}\n    \u03f5 = alg.\u03f5\n    mid = T(\u03f5 * lower + (1 - \u03f5) * 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 \u00d7 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\u00d74 DataFrame\n Row \u2502 x        y        z        q       \n     \u2502 Float64  Float64  Float64  Float64 \n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502     9.0      7.0      6.0      7.0\n   2 \u2502     8.0      7.0      9.0      6.0\n   3 \u2502     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\u0130\u015fletmeciler, M\u00fchendisler ve Y\u00f6neticiler i\u00e7in Operasyonel, Y\u00f6netsel ve Stratejik Problemlerin\n\u00c7\u00f6z\u00fcm\u00fcnde \u00c7ok Kriterli Karar verme Y\u00f6ntemleri, Edit\u00f6rler: Bahad\u0131r Fatih Y\u0131ld\u0131r\u0131m ve Emrah \u00d6nder,\nDora, 2. Bas\u0131m, 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": "#   Unit examples of the FourierAnalysis Package for julia language\n#   v 0.0.1 - last update 24th of September 2019\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 example show how to compute coherence\n#   and how to extract inforation from them.\n\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n#                                                                             #\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n\n\nusing FourierAnalysis, FFTW, LinearAlgebra, Statistics, Plots\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#############################################################\n# test coherence using sinusoids with same frequency and different phase.\nusing FourierAnalysis, FFTW, LinearAlgebra, Statistics, Plots\nt=32\nsr=32\nf=2\nnoise=1000\ntapering=rectangular\nv=sinusoidal(10, f, sr, t*4, 0).+[randn()/noise for i=1:t*4]\nw=sinusoidal(10, f, sr, t*4, \u03c0/4).+[randn()/noise for i=1:t*4]\ny=sinusoidal(10, f, sr, t*4, \u03c0/2).+[randn()/noise for i=1:t*4]\nz=sinusoidal(10, f, sr, t*4, \u03c0).+[randn()/noise for i=1:t*4]\nX=[v w y z]\n# as compared to v, w is out-of-phase, y is in between and z is at phase opposition\nplot(v)\nplot!(w)\nplot!(y)\nplot!(z)\n\n\ud835\ude3e=coherence(X, sr, t; tapering=tapering, tril=true)\n\ud835\ude3e=coherence(X, sr, t; tapering=tapering, tril=false)\n# get all five kinds of coherences\n\ud835\ude3e\u2081, \ud835\ude3e\u2082, \ud835\ude3e\u2083, \ud835\ude3e\u2084, \ud835\ude3e\u2085=coherence(X, sr, t; tapering=tapering, tril=true, allkinds=true)\n\ud835\ude3e\u2081, \ud835\ude3e\u2082, \ud835\ude3e\u2083, \ud835\ude3e\u2084, \ud835\ude3e\u2085=coherence(X, sr, t; tapering=tapering, tril=false, allkinds=true)\n# check result against cross-spectra\n\ud835\udc12=crossSpectra(X, sr, t; tapering=tapering, tril=true)\n# compute coherence from a CrossSpectra object (lower triangles only)\n\ud835\ude3e=coherence(\ud835\udc12)\n\n\ud835\udc12=crossSpectra(X, sr, t; tapering=tapering, tril=false)\n# compute coherence from a CrossSpectra object (full matrices)\n\ud835\ude3e=coherence(\ud835\udc12)\n\n# compute all five kinds of coherence from a CrossSpectra object\n\ud835\ude3e\u2081, \ud835\ude3e\u2082, \ud835\ude3e\u2083, \ud835\ude3e\u2084, \ud835\ude3e\u2085=coherence(\ud835\udc12, allkinds=true)\n\n# average full coherence in range 4:8Hz\nY=mean(\ud835\ude3e, (4, 8))\n\n# full coherence matrices in range 4:8Hz\nE=extract(\ud835\ude3e, (4, 8))\n\n# average coherence in 1Hz-bands\nZ=bands(\ud835\ude3e, 1)\n\n# smooth coherence a-posteriori\n\ud835\ude3e2=smooth(blackmanSmoother, \ud835\ude3e)\nC=\ud835\ude3e.y\nD=\ud835\ude3e2.y\n\n# or get directly smoothed coherence\n\ud835\ude3e3=coherence(X, sr, t; tapering=tapering, smoothing=hannSmoother, tril=true)\n\n############################################\n# coherence of several data matrices at once\n\n# Compute the coherence altogether\n\ud835\udcd2=coherence(\ud835\udc17, sr, t; tapering=slepians(sr, t))\n\n# get all five kinds of coherences\n\ud835\udcd2\u2081, \ud835\udcd2\u2082, \ud835\udcd2\u2083, \ud835\udcd2\u2084, \ud835\udcd2\u2085=coherence(\ud835\udc17, sr, t; tapering=slepians(sr, t), allkinds=true)\n", "meta": {"hexsha": "07e262bfaef9ee1aa30bd6a4a6f8792d2aa71c12", "size": 2985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example_coherence.jl", "max_stars_repo_name": "laborg/FourierAnalysis.jl", "max_stars_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_stars_repo_licenses": ["MIT"], "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_coherence.jl", "max_issues_repo_name": "laborg/FourierAnalysis.jl", "max_issues_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_issues_repo_licenses": ["MIT"], "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_coherence.jl", "max_forks_repo_name": "laborg/FourierAnalysis.jl", "max_forks_repo_head_hexsha": "7ef12fa0dc8254fdcd501d41a1d93e9d5317ab71", "max_forks_repo_licenses": ["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.8021978022, "max_line_length": 84, "alphanum_fraction": 0.640201005, "num_tokens": 1125, "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 \u2208 \u211d^n: s\u1d62\u1d40z \u2264 r\u1d62,~i = 1, \u2026, N\\\\}.\n```\nwhere ``s\u1d62 \u2208 \u211d^n, s\u1d62 \u2260 0``, and ``r\u1d62 \u2208 \u211d``.\nAssume ``\u03c1(s\u1d62,Q)`` is defined for ``i = 1, \u2026, N``. Then,\n\n```math\nP \u2296 Q = \\\\{z \u2208 \u211d^n: s\u1d62\u1d40z \u2264 r\u1d62 - \u03c1(s\u1d62,Q),~i = 1, \u2026, N\\\\}.\n```\n\nwhere ``\u2296`` is defined as ``P \u2296 Q = \\\\{z \u2208 \u211d^n: z + v \u2208 P  ~\u2200~v \u2208 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] - \u03c1(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(\u03bc) = length(\u03bc) > 1 ? FFTW.plan_r2r!(\u03bc, FFTW.REDFT00) : fill!(similar(\u03bc),1)'\n\n\"\"\"\nCompute nodes of the Clenshaw\u2014Curtis quadrature rule.\n\"\"\"\nclenshawcurtisnodes(::Type{T}, N::Int) where T = chebyshevpoints(T, N; kind = 2)\n\n\"\"\"\nCompute weights of the Clenshaw\u2014Curtis quadrature rule with modified Chebyshev moments of the first kind ``\\\\mu``.\n\"\"\"\nclenshawcurtisweights(\u03bc::Vector) = clenshawcurtisweights!(copy(\u03bc))\nclenshawcurtisweights!(\u03bc::Vector) = clenshawcurtisweights!(\u03bc, plan_clenshawcurtis(\u03bc))\nfunction clenshawcurtisweights!(\u03bc::Vector{T}, plan) where T\n    N = length(\u03bc)\n    rmul!(\u03bc, inv(N-one(T)))\n    plan*\u03bc\n    \u03bc[1] *= half(T); \u03bc[N] *= half(T)\n    return \u03bc\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": "using Plots, LaTeXStrings, Statistics,  Distributions,StatsPlots, JLD\nTotalNum=10000\nNList=[5,10,100,1000]\nData=[[] for i in 1:length(NList)]\nfor N in 1:length(NList)\n    for i in 1:TotalNum\n        push!(Data[N], sum(rand(NList[N])))\n    end\nend\nplots=[]\ncolors=[:silver, :lightblue,:pink2,:mediumpurple3]\nfor i in 1:length(NList)\n    plt=begin\n        histogram(Data[i],color=colors[i],normalize = true, label=L\"Histogram\\ of\\ Samples\", alpha=0.9)\n        plot!(Normal(mean(Data[i]),std(Data[i])), c = :black, label= L\"Normal(\\mu = %$(round(mean(Data[i]),digits = 2)), \\sigma = %$(round(std(Data[i]),digits = 2)))\")\n    end\n    push!(plots, plt)\nend\nplot(plots..., size = (1000,1000), plot_title = \"Normalized Distribution of Samples\", dpi=600)\nsave(\"../../chapter6/6.3/samples.jld\",\"Samples\", Data)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter6\\\\6.3\\\\Figs\\\\N_Distribution.png\")\n", "meta": {"hexsha": "d6f95b4be4ace96e43938e2c30bf40c3d4ce11ea", "size": 914, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter6/6.3/6.3.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": "chapter6/6.3/6.3.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": "chapter6/6.3/6.3.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": 41.5454545455, "max_line_length": 167, "alphanum_fraction": 0.6663019694, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7576720556783868}}
{"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\u03c0*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": "module TestSpectralRadius\nusing Test\nusing EcologicalNetworks\n\n# All examples are from Figure 1 of SK&A 2013\n\nA = [1 1 1 1; 1 1 1 1; 1 1 1 0; 1 1 0 0; 1 1 0 0; 1 1 0 0]\nN = BipartiteNetwork(A.>0)\n@test \u03c1(N; range=EcologicalNetworks.\u03c1_raw) \u2248 3.82 atol = 0.01\n\nA = [0 1 1 1; 1 0 1 1; 1 1 0 1; 1 1 1 0; 1 1 1 0; 1 0 0 1]\nN = BipartiteNetwork(A.>0)\n@test \u03c1(N; range=EcologicalNetworks.\u03c1_raw) \u2248 3.515 atol = 0.01\n\nA = [1 1 1 1; 1 1 1 0; 1 1 1 0; 1 1 1 0; 1 1 1 0; 1 0 0 0]\nN = BipartiteNetwork(A.>0)\n@test \u03c1(N; range=EcologicalNetworks.\u03c1_raw) \u2248 3.944 atol = 0.01\n\nA = [1 0 1 1; 1 1 0 1; 1 1 1 0; 1 1 1 0; 1 1 1 0; 0 1 0 1]\nN = BipartiteNetwork(A.>0)\n@test \u03c1(N; range=EcologicalNetworks.\u03c1_raw) \u2248 3.595 atol = 0.01\n\nend\n", "meta": {"hexsha": "54d855be1898ab863f550ee3b70830c4e1768cac", "size": 713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/community/spectralradius.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": "test/community/spectralradius.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": "test/community/spectralradius.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": 29.7083333333, "max_line_length": 62, "alphanum_fraction": 0.6283309958, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7576720512339752}}
{"text": "# Test Fishing Problem - Switched Nonlinear System\nfunction nonlinsystest(solver=IpoptSolver(tol=1e-04, max_iter = 25); objtol = 1e-3, primaltol = 1e-3)\n  println(\"Testing Switched Nonlinear Systems Optimization \", string(typeof(solver)))\n\n  # Define Time Interval\n  t0 = 0.0; tf = 12.0\n\n  uvec = [repmat([0.0; 1.0], 4, 1); 0.0]'  # Input Vector\n\n  # Cost Funcction Matrix\n  C = [1.0 0.0 -1.0 0.0;\n       0.0 1.0 0.0  -1.0]\n  Q = C'*C\n\n  # Define Initial State\n  x0 = [0.5; 0.7; 1; 1]\n\n  ### Define System Dynamics\n  function nldyn(x::Array{Float64,1}, u::Array{Float64,1})\n    n = length(x)\n    f = zeros(n)\n    f[1] = x[1] - x[1]*x[2] - 0.4*x[1]*u[1]\n    f[2] = -x[2] + x[1]*x[2] - 0.2*x[2]*u[1]\n    return f\n\n  end\n\n  function nldyn_deriv(x::Array{Float64,1}, u::Array{Float64,1})\n    df = [1.0-x[2]-0.4*u[1]       -x[1]                   0    0;\n          x[2]                     -1+x[1]-0.2*u[1]       0    0;\n          0                        0                      0    0;\n          0                        0                      0    0]\n  end\n\n  m = stoproblem(x0, nldyn, nldyn_deriv, uvec, ngrid = 300, t0=t0, tf=tf, Q=Q, solver=solver)\n\n\n  solve!(m)\n  # @test getstat(m) == :Optimal\n\n  # Test Optimal Solution\n  tauopt = gettau(m)\n  @test_approx_eq_eps tauopt[1] 2.4434718158206916 primaltol\n  @test_approx_eq_eps tauopt[2] 4.122362522221089 primaltol\n  @test_approx_eq_eps tauopt[3] 4.433072844726073 primaltol\n  @test_approx_eq_eps tauopt[4] 4.68252002334405  primaltol\n  @test_approx_eq_eps tauopt[5] 5.201667827750571 primaltol\n  @test_approx_eq_eps tauopt[6] 5.369908894975762 primaltol\n  @test_approx_eq_eps tauopt[7] 6.376845190917198 primaltol\n  @test_approx_eq_eps tauopt[8] 6.47160340206027 primaltol\n\n  # Test Optimal Value\n  @test_approx_eq_eps getobjval(m) 1.3454355602054182 objtol\n\n  println(\"Passed\")\nend\n", "meta": {"hexsha": "df42d8f029a6a432fd22372308d1df42783656e5", "size": 1834, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/nonlinsys.jl", "max_stars_repo_name": "JuliaPackageMirrors/SwitchTimeOpt.jl", "max_stars_repo_head_hexsha": "712c9cf2c5f4cab89311eef0b159b93f3d7f3739", "max_stars_repo_licenses": ["MIT"], "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/nonlinsys.jl", "max_issues_repo_name": "JuliaPackageMirrors/SwitchTimeOpt.jl", "max_issues_repo_head_hexsha": "712c9cf2c5f4cab89311eef0b159b93f3d7f3739", "max_issues_repo_licenses": ["MIT"], "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/nonlinsys.jl", "max_forks_repo_name": "JuliaPackageMirrors/SwitchTimeOpt.jl", "max_forks_repo_head_hexsha": "712c9cf2c5f4cab89311eef0b159b93f3d7f3739", "max_forks_repo_licenses": ["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.1754385965, "max_line_length": 101, "alphanum_fraction": 0.6025081788, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065794, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7576720480687972}}
{"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": "import RowEchelon\nimport LinearAlgebra\n\n#=\nHomework 7\nSection 3.1\nProblems 13\n=#\n\nA = [ 4 0 -7 3 -5 ;\n     0 0 2 0 0;\n     7 3 -6 4 -8;\n     5 0 5 2 -3;\n     0 0 9 -1 2]\n\ndetA = LinearAlgebra.det(A)\n\nprintln(\"Original Matrix:\")\nprintln(A)\nprintln(\"Determinate:\")\nprintln(detA)\n", "meta": {"hexsha": "51680f74e8e24a9fadb89378114d8ce6bb4ccab9", "size": 277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW7_S3.1_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": "HW7_S3.1_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": "HW7_S3.1_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": 12.5909090909, "max_line_length": 27, "alphanum_fraction": 0.6064981949, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7576692947652411}}
{"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(\u03d5s, \u03d5_stars)\n    \u03d51, \u03d52 = \u03d5s\n    \u03d51_star, \u03d52_star = \u03d5_stars\n    \u03a3 = []\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] = \u03d51_star + \u03d51 * indicator(val1, 0)\n            A[1, 2] = \u03d52_star + \u03d52 * indicator(val2, 0)\n            push!(\u03a3, A)\n        end\n    end\n    return Vector{Array{Float64, 2}}(\u03a3)\n    # NOTE \u03a3 is of form where \u03a3[1] is with y\u209c\u208b\u2081,y\u209c\u208b\u2082 \u2265 0, \u03a3[2] is with y\u209c\u208b\u2081 \u2265 0 and y\u209c\u208b\u2082 < 0, \u03a3[3] is with y\u209c\u208b\u2081 < 0 and y\u209c\u208b\u2082 \u2265 0\n    # and \u03a3[4] is with y\u209c\u208b\u2081,y\u209c\u208b\u2082 < 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\u03a34 = 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(\u03a34)\n##\n# We then have the discrete system\ns4 = discreteswitchedsystem(\u03a34, 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(\u03d5s, \u03d5_stars)\n    \u03d51, \u03d52 = \u03d5s\n    \u03d51_star, \u03d52_star = \u03d5_stars\n    \u03a3 = []\n    vals = [1, -1]\n    for val in vals\n        A = zeros(3, 3); A[2, 1] = 1; A[1, 2] = \u03d52_star; A[1, 3] = \u03d52\n        A[1, 1] = \u03d51_star + \u03d51 * indicator(val, 0)\n        A[3, 1] = indicator(val, 0)\n        push!(\u03a3, A)\n    end\n    return Vector{Array{Float64, 2}}(\u03a3)\n\n    # NOTE \u03a3 has form s.t. \u03a3[1] is with y\u209c\u208b\u2081 \u2265 0 and \u03a3[2] is with y\u209c\u208b\u2081 < 0\nend\n\n\u03a32 = AR2_to_companion([0.4, 0.2], [0.2, 0.1])\n\u03a32st = [\u03a32[1], \u03a32[2], \u03a32[1], \u03a32[2]]\n##\n# `\u03a32` consists of the two matrices and `\u03a32st` corresponds to the same partitioning of the state space as for `\u03a34`.\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(\u03a32)\ns2st = discreteswitchedsystem(\u03a32st, 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 `\u03a32`, the constrained joint spectral radius (CJSR) of `(\u03a34, G)`, and the state-constrained joint spectral radii (SCJSR) of `(\u03a34, G, X4)` and `(\u03a32st, G, X2)` all agree in value, up to 4 significant figures:\n##\n@show \u03b3_jsr2 = jsr(s2)\n@show \u03b3_cjsr4 = cjsr(s4)\n@show \u03b3_scjsr4 = sosbound_\u03b3(s4, 2)\n@show \u03b3_scjsr2 = sosbound_\u03b3(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, \u03a3, T, \u03c3)  # for companion form\n    y = zeros(3, T)\n    y[:, 1] = y0\n    for t in 1:T-1\n        \u03f5_t = [rand(Normal(0, \u03c3)), 0., 0.]\n        if y[1, t] \u2265 0.\n            y[:, t+1] = \u03a3[1]*y[:, t] + \u03f5_t\n        else\n            y[:, t+1] = \u03a3[2]*y[:, t] + \u03f5_t\n        end\n    end\n    return y\nend\n\nfunction plot_AR2(y0, \u03a3, T, \u03c3; N = 20, row=1)\n    ys = []\n    ens_means = zeros(T)\n    for i in 1:N\n        y = simulate_AR2(y0, \u03a3, T, \u03c3)\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, \u03a3, 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), \u03a32, 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\u03a3 = AR2_to_companion([0.5, -0.47], [0.5, -0.5])\nplot_AR2(3*ones(3), \u03a3, 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\u03a3 = 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(\u03a3)\ns = discreteswitchedsystem(\u03a3, G, X)\n@show \u03b3_jsr = jsr(s)  # > 1\n@show \u03b3_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 \u03b3_scjsr = sosbound_\u03b3(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\u03a3 = AR2_to_companion([0.6, -0.6], [0.6, -0.6])\nplot_AR2(3*ones(3), \u03a3, 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\u03a3 = AR2_to_TAR([0.6, -0.6], [0.6, -0.6])\ns = discreteswitchedsystem(\u03a3, G, X)\n@show \u03b3_cjsr = cjsr(s)\n@show \u03b3_scjsr = sosbound_\u03b3(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_\u03b5, N_\u03b5 ,d\nEstimate the [Fractal Dimension](@ref) `d` of the boundary between basins of attraction using\nthe box-counting algorithm.\n\nThe output `N_\u03b5` is a vector with the number of the balls of radius `\u03b5` (in pixels)\nthat contain at least two initial conditions that lead to different attractors. `V_\u03b5`\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_\u03b5)`\nvs `log.(1/V_\u03b5)` curve. However it is recommended to analyze the curve directly\nfor more accuracy.\n\n## Keyword arguments\n* `range_\u03b5 = 2:maximum(size(basins))\u00f720` 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_\u03b5` boxes of size\n`\u03b5` in pixels.\n\"\"\"\nfunction basins_fractal_dimension(basins::AbstractArray; range_\u03b5 = 3:maximum(size(basins))\u00f720)\n\n    dims = size(basins)\n    num_step = length(range_\u03b5)\n    N_u = zeros(Int, num_step) # number of uncertain box\n    N = zeros(Int, num_step) # number of boxes\n    V_\u03b5 = zeros(1, num_step) # resolution\n\n    # Naive box counting estimator\n    for (k,eps) in enumerate(range_\u03b5)\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_\u03b5[k] = eps\n    end\n    N_\u03b5 = N_u\n    # remove zeros in case there are any:\n    ind = N_\u03b5 .> 0.0\n    N_\u03b5 = N_\u03b5[ind]\n    V_\u03b5 = V_\u03b5[ind]\n    # get exponent via liner regression on `f_\u03b5 ~ \u03b5^\u03b1`\n    b, d = linreg(vec(-log10.(V_\u03b5)), vec(log10.(N_\u03b5)))\n    return V_\u03b5, N_\u03b5, d\nend\n\n\"\"\"\n    uncertainty_exponent(basins; kwargs...) -> \u03b5, N_\u03b5 ,\u03b1\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_\u03b5` is a vector with the number of the balls of radius `\u03b5` (in pixels)\nthat contain at least two initial conditions that lead to different attractors.\nThe ouput `\u03b1` is the estimation of the uncertainty exponent using the box-counting\ndimension of the boundary by fitting a line in the `log.(N_\u03b5)` vs `log.(1/\u03b5)` curve.\nHowever it is recommended to analyze the curve directly for more accuracy.\n\n## Keyword arguments\n* `range_\u03b5 = 2:maximum(size(basins))\u00f720` 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 `\u03b5` at random. If there are a least two initial conditions that lead to different\nattractors, a ball is tagged \"uncertain\". `f_\u03b5` 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_\u03b5 ~ \u03b5^\u03b1`. The number that characterizes this scaling is called the\nuncertainty exponent `\u03b1`.\n\nNotice that the uncertainty exponent and the box counting dimension of the boundary are\nrelated. We have `\u0394\u2080 = D - \u03b1` where `\u0394\u2080` 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_\u03b5 = 2:maximum(size(basins))\u00f720)\n    V_\u03b5, N_\u03b5, d = basins_fractal_dimension(basins; range_\u03b5)\n    return V_\u03b5, N_\u03b5, 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": "# export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH\nusing TensorFlowDiffEq\nusing Base.Test\n\nusing Plots; plotly()\nusing DiffEqBase, ParameterizedFunctions\nusing DiffEqProblemLibrary, DiffEqDevTools\n\n# Toy problem 1\n\nf = (t,u) -> -u/5 + exp(-t/5).*cos(t)\n(::typeof(f))(::Type{Val{:analytic}},t,u0) =  exp(-t/5)*(u0 + sin(t))\nprob = ODEProblem(f,Float32(0.0),(Float32(0.0),Float32(2.0)))\nsol = solve(prob,odetf(),dt=0.02)\n\nsol(0.5)\nsol(0.5,idxs=1)\nplot(sol,plot_analytic=true)\n\nprob = ODEProblem(f,0.0,(0.0,2.0))\nsol = solve(prob,odetf(),dt=0.02)\n\nsol = solve(prob,odetf(hl_width=[128,64,32,64,128]),dt=0.02,maxiters=Int(1e5))\n\ndts = 1./2.^(8:-1:2) #14->7 good plot\nprob = ODEProblem(f,0.0,(0.0,1.0))\nsim  = test_convergence(dts,prob,odetf(hl_width=[128,64,32,64,128]))\n@test abs(sim.\ud835\udcaaest[:l2]-1) < 0.2\n\n# Standard Convergence Problem\n\ndts = 1./2.^(14:-1:7) #14->7 good plot\nsim_linear  = test_convergence(dts,prob_ode_linear,odetf(),maxiters=Int(1e5))\n@test abs(sim_linear.\ud835\udcaaest[:l2]-1) < 0.2\n\n# Problem 2\n\nfunction lotka_voltera_tf(t,u)\n  du1 = 1.5 .* u[:,1] - 1.0 .* u[:,1].*u[:,2]\n  du2 = -3 .* u[:,2] + u[:,1].*u[:,2]\n  [du1 du2]\nend\nprob = ODEProblem(lotka_voltera_tf,Float32[1.0,1.0],(Float32(0.0),Float32(10.0)))\nsol = solve(prob,odetf(hl_width=[256]),dt=0.01,maxiters=Int(1e4),progress_steps=500)\n\nsol(0.5,idxs=1)\nsol([0.5,0.52])\nplot(sol)\n\nsol = solve(prob,odetf(hl_width=[128,128]),dt=0.01,maxiters=Int(1e4),progress_steps=500)\nplot(sol)\n\nsol = solve(prob,odetf(hl_width=[128,64, 64]),dt=0.01,maxiters=Int(1e4),progress_steps=500)\nplot(sol)\n\n# Toy problem 3\n\nfunction lorenz_tf(t,u)\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\n    [du1 du2 du3]\nend\nprob = ODEProblem(lorenz_tf,Float32[1.0,0.0,0.0],(Float32(0.0),Float32(100.0)))\nsol = solve(prob,odetf(hl_width=256),dt=0.1,maxiters=Int(1e5),progress_steps=500)\n\nplot(sol,vars=(1,2,3))\n\n# Macro Usage\n\ng = @ode_def LorenzExample begin\n  dx = \u03c3*(y-x)\n  dy = x*(\u03c1-z) - y\n  dz = x*y - \u03b2*z\nend \u03c3=10.0 \u03c1=28.0 \u03b2=(8/3)\n\n# g.vector_ex and g.vector_ex_return are vectorized forms\n# g(Val{:vec},t,u,du) and g(Val{:vec},t,u)\n", "meta": {"hexsha": "7af89788e83d5a3e9b3f27b4d9a5ea394e9796f8", "size": 2154, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaDiffEq/TensorFlowDiffEq.jl", "max_stars_repo_head_hexsha": "8f0096daf8b13cc75c9b5581f3d0b1b4b379e715", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-05-18T21:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-25T03:34:00.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "SciML/TensorFlowDiffEq.jl", "max_issues_repo_head_hexsha": "8f0096daf8b13cc75c9b5581f3d0b1b4b379e715", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-05-16T14:29:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-24T06:07:24.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "JuliaDiffEq/TensorFlowDiffEq.jl", "max_forks_repo_head_hexsha": "8f0096daf8b13cc75c9b5581f3d0b1b4b379e715", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-16T14:13:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:37:37.000Z", "avg_line_length": 26.925, "max_line_length": 91, "alphanum_fraction": 0.6485608171, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.843895098628499, "lm_q1q2_score": 0.7575606616907492}}
{"text": "using Plots\nusing BenchmarkTools\n#2(a)\nfunction vfsolvex(vnew, kgrid, tolerance, imax, \u03c3=1.5)\n    \u03b2=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 \u03c3==1\n      u = log.(c)\n    else\n      u = (c.^(1-\u03c3).-1)./(1-\u03c3)\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 .+ \u03b2*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, \u03c3=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, \u03c3=$x\"))\n  end\n#as \u03c3->1, the value function is getting closer to log utility value function\n#the vfsolvex autometically compute log utility solution when \u03c3=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\u00b2)` 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) = \u03d5Yt + Zt\n\nThe process `Zt ~ WN(0, \u03c3\u00b2)`\n\n\"\"\"\nar1_eq_direct(\u03d5, y, z) = \u03d5*y + z\n\n# In state space notation.\nstruct AR1Model\n    \u03d5\n    F\n    G\n\n    function AR1Model(\u03d5)\n        F = reshape([\u03d5], 1, 1)\n        G = ones(eltype(\u03d5), 1, 1)\n        return new(\u03d5, 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) = \u03d5Yt + Zt + \u03b8Z(t-1)\n\nThe process `Zt ~ WN(0, \u03c3\u00b2)`\n\n\"\"\"\narma11_eq_direct(\u03d5, \u03b8, y, zt, ztm1) = \u03d5*y + z + \u03b8*ztm1\n\n# In State Space notation\nstruct ARMA11Model\n    \u03d5  # AR param\n    \u03b8  # MA param\n    F  # state transition matrix\n    G  # observation transition matrix\n\n    function ARMA11Model(\u03d5, \u03b8)\n        F = [0 1; 0 \u03d5]\n        G = [\u03b8 1]\n        return new(\u03d5, \u03b8, 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": "\"\"\"\n    add_intercept(A)\n\nInsert an intercept column (column of ones) at the beginning of a 2d array. \n\n# Arguments \n\n- A = 2d array of floats\n\n# Value \n\nReturns A with an intercept column\n\n\"\"\"\nfunction add_intercept(A::AbstractArray{Float64,2})\n    \n    # Check that the first column isn't a column of ones\n    if all(A[:,1].==1)\n        print(\"The first column of this array is already a column of ones. Are you sure you wanted to add an intercept?\")\n    end\n    \n    # Concatenate a column of ones to the beginning of A\n    return hcat(ones(size(A,1)), A)\nend\n\n\n\"\"\"\n    remove_intercept(A)\n\nRemove the intercept column, assumed to be the first column of a 2d array. \n\n# Arguments \n\n- A = 2d array of floats\n\n# Value \n\nReturns A without the intercept column\n\n\"\"\"\nfunction remove_intercept(A::AbstractArray{Float64,2})\n    \n    # Check that the first column is a column of ones\n    if any(A[:,1].!=1)\n        print(\"The first column of this array does not look like an itercept \n               since it is not a column of ones. Are you sure you wanted to \n               remove it?\")\n    end\n    \n    # Remove the first column of A\n    return A[:,2:end]\nend\n\n\n\"\"\"\n    shuffle_rows(A)\n\nShuffles rows of a 2d array \n\n# Arguments \n\n- A = 2d array of floats\n\n# Value\n\nReturns A with rows shuffled\n\n\"\"\"\nfunction shuffle_rows(A::AbstractArray{Float64,2})\n    \n    return A[Random.shuffle(1:size(A,1)),:]\nend\n\n\n\"\"\"\n    shuffle_cols(A)\n\nShuffles columns of a 2d array \n\n# Arguments \n\n- A = 2d array of floats\n\n# Value\n\nReturns A with columns shuffled\n\n\"\"\"\nfunction shuffle_cols(A::AbstractArray{Float64,2})\n    \n    return A[:,Random.shuffle(1:size(A,2))]\nend", "meta": {"hexsha": "87cbde938e604aac37ef0c38f86db9f6a20311a4", "size": 1652, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc_helpers.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/misc_helpers.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/misc_helpers.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": 17.9565217391, "max_line_length": 121, "alphanum_fraction": 0.6573849879, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8976952825278492, "lm_q1q2_score": 0.7575606525115685}}
{"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*\u03c0))\nend\n\nfunction Cosine_Kernel(t)\n  if abs(t)>0\n    return 0\n  else\n    return (\u03c0*cos(\u03c0*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/(\u03c0*(exp(t)+exp(-t)))\nend\n\nfunction Silverman_Kernel(t)\n  sin(abs(t)/2+\u03c0/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": "s1 = StreamingStats(Float64)\ns2 = StreamingStats(10,Float64)\n\nntestelements = 1000\nx1 = randn(ntestelements)\nx2 = randn(10,ntestelements)\nm1,v1 = streamingstats(x1)\nm2,v2 = streamingstats(x2)\n\nfor i=1:ntestelements\n    update!(s1,x1[i])\n    update!(s2,x2[:,i])\n    #test the results of the update function against ground truth\n    @test_approx_eq_eps mean(s1) mean(x1[1:i]) 1e-10\n    @test_approx_eq_eps var(s1) var(x1[1:i]) 1e-10\n    @test_approx_eq_eps std(s1) std(x1[1:i]) 1e-10\n    @test_approx_eq_eps mean(s2) mean(x2[:,1:i],2) 1e-10\n    @test_approx_eq_eps var(s2) var(x2[:,1:i],2) 1e-10\n    @test_approx_eq_eps std(s2) std(x2[:,1:i],2) 1e-10\n    #test the results of the streamstats function\n    @test_approx_eq_eps m1[i] mean(s1) 1e-10\n    @test_approx_eq_eps v1[i] var(s1) 1e-10\n    @test_approx_eq_eps m2[:,i] mean(s2) 1e-10\n    @test_approx_eq_eps v2[:,i] var(s2) 1e-10\nend\n\n\nprintln(\"==================\")\nprintln(\"Test show function\")\nprintln(\"==================\")\nshow(s1)\nshow(s2)\nprintln(\"=============\")\nprintln(\"End test show\")\nprintln(\"=============\")\n", "meta": {"hexsha": "c38b8d075e4bed2a43bd7e650f46bd2403d9fc66", "size": 1070, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit/analysis.jl", "max_stars_repo_name": "QuantifyingUncertainty/GMHPhotoReceptor.jl", "max_stars_repo_head_hexsha": "9298c91358210747353352b09dd3f2d814758cf8", "max_stars_repo_licenses": ["MIT"], "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/unit/analysis.jl", "max_issues_repo_name": "QuantifyingUncertainty/GMHPhotoReceptor.jl", "max_issues_repo_head_hexsha": "9298c91358210747353352b09dd3f2d814758cf8", "max_issues_repo_licenses": ["MIT"], "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/unit/analysis.jl", "max_forks_repo_name": "QuantifyingUncertainty/GMHPhotoReceptor.jl", "max_forks_repo_head_hexsha": "9298c91358210747353352b09dd3f2d814758cf8", "max_forks_repo_licenses": ["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.7222222222, "max_line_length": 65, "alphanum_fraction": 0.6476635514, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7574975794068531}}
{"text": "using ProximalOperators\n\nA = [  1.0  -2.0   3.0  -4.0  5.0;\n       2.0  -1.0   0.0  -1.0  3.0;\n      -1.0   0.0   4.0  -3.0  2.0;\n      -1.0  -1.0  -1.0   1.0  3.0]\nb = [1.0, 2.0, 3.0, 4.0]\n\nm, n = size(A)\n\nf = Translate(LogisticLoss(ones(m)), -b)\nlam = 0.1\ng = NormL1(lam)\n\nx_star = [0, 0, 2.114635341704963e-01, 0, 2.845881348733116e+00]\n\n# Nonfast/Adaptive\n\nx0 = zeros(n)\n@time it, x, sol = ProximalAlgorithms.FBS(x0; fs=f, As=A, g=g, tol=1e-6, adaptive=true)\n@test norm(x - x_star, Inf) <= 1e-4\n@test it < 1700\nprintln(sol)\n\n# Fast/Adaptive\n\nx0 = zeros(n)\n@time it, x, sol = ProximalAlgorithms.FBS(x0; fs=f, As=A, g=g, tol=1e-6, adaptive=true, fast=true)\n@test norm(x - x_star, Inf) <= 1e-4\n@test it < 500\nprintln(sol)\n\n# ZeroFPR/Adaptive\n\nx0 = zeros(n)\n@time it, x, sol = ProximalAlgorithms.ZeroFPR(x0; fs=f, As=A, g=g, tol=1e-6, adaptive=true)\n@test norm(x - x_star, Inf) <= 1e-4\n@test it < 25\nprintln(sol)\n\n# PANOC/Adaptive\n\nx0 = zeros(n)\n@time it, x, sol = ProximalAlgorithms.PANOC(x0; fs=f, As=A, g=g, tol=1e-6, adaptive=true)\n@test norm(x - x_star, Inf) <= 1e-4\n@test it < 35\nprintln(sol)\n\n", "meta": {"hexsha": "e707c88902d28e9cbe2bf4922e783f22d7dfe16a", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_l1logreg_small.jl", "max_stars_repo_name": "nantonel/ProximalAlgorithms.jl", "max_stars_repo_head_hexsha": "29629f31ccd179ad581bdf514f6969e5e28d1b92", "max_stars_repo_licenses": ["MIT"], "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_l1logreg_small.jl", "max_issues_repo_name": "nantonel/ProximalAlgorithms.jl", "max_issues_repo_head_hexsha": "29629f31ccd179ad581bdf514f6969e5e28d1b92", "max_issues_repo_licenses": ["MIT"], "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_l1logreg_small.jl", "max_forks_repo_name": "nantonel/ProximalAlgorithms.jl", "max_forks_repo_head_hexsha": "29629f31ccd179ad581bdf514f6969e5e28d1b92", "max_forks_repo_licenses": ["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.4489795918, "max_line_length": 98, "alphanum_fraction": 0.6045454545, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7574975742586186}}
{"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 \u2661 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\u03c3(w*x) = 1/ (1+e^(-w*x))\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 1\n#\n# Use the first syntax given above to define the function `\u03c3` in Julia. Note that Julia\n# actually allows us to use the symbol \u03c3 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 \u03c3 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(\u03c3, -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 -> \u03c3(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 \u03c3 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) = \u221at + 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": "@testset \"646.maximum-length-of-pair-chain.jl\" begin\n    @test find_longest_chain([(1, 2), (2, 3), (3, 4), (1, 3)]) == 2\n    @test find_longest_chain([(1, 2), (1, 2), (1, 2)]) == 1\n    @test find_longest_chain([(1, 2), (2, 3)]) == 1\n    @test find_longest_chain([(1, 2), (2, 3), (3, 4)]) == 2\n    @test find_longest_chain(Tuple{Int, Int}[]) == 0\nend\n\n", "meta": {"hexsha": "22497ab9eb577e135ee60a7fdbc14e8bd4973ee8", "size": 351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/problems/646.maximum-length-of-pair-chain.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": "test/problems/646.maximum-length-of-pair-chain.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": "test/problems/646.maximum-length-of-pair-chain.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": 39.0, "max_line_length": 67, "alphanum_fraction": 0.5527065527, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8615382165412808, "lm_q1q2_score": 0.7574185272461929}}
{"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\u2208rng, the result is a point x\u2080 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": "\nusing FractalTools \nusing Makie \nusing Makie\nimport Makie.GeometryBasics: TriangleFace \n\n# Construct delaunay \np1, p2, p3 = [-1., \u221a3.], [-1., -\u221a3], [2., 0.]\ntridln = TriDelaunay(p1, p2, p3, addboundarypoints=true)\n\nwhile npoints(tridln) \u2264 1000 \n    addpoint!(tridln) \nend \n\nfinegrain!(tridln, 100)\n\n# Define function \nf(x, y) = x^2 + y^2\n\n# Plot the result \nfig, ax, plt = tridelaunayplotf(tridln, f, vmarkersize=10)\nwireframe!(tomesh(tridln.delaunay), linewidth=3)\ndisplay(fig)\n", "meta": {"hexsha": "258b630197f024145f762a4803b276fba4f38eca", "size": 480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/stash/mesh/stash/tessplotf.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/tessplotf.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/tessplotf.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": 20.0, "max_line_length": 58, "alphanum_fraction": 0.6895833333, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7574132193345304}}
{"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": "using PolyFit\nusing Test,Polynomials,LinearAlgebra\n\n@testset \"no errors\" begin\n    # Should get the same answer as Polynomials.polyfit\n    x = 1:10\n\n    for m = 1:5\n\t    y = x .^ m\n\t    for n = 1:m\n\t\t    P = polyfit(PolyFit.linear_system_type(length(x),n),x,y,n)\n\t\t    P2 = Polynomials.polyfit(x,y,n)\n\t\t    @test P \u2248 P2\n\t\tend\n\tend\nend\n\n@testset \"same errors\" begin\n    # Should get the same answer as Polynomials.polyfit\n    x = 1:5\n\ty = x .^ 2\n\t    \n    P = polyfit(x,y,2,1)\n    P2 = Polynomials.polyfit(x,y,2)\n    @test P \u2248 P2\n\n    P = polyfit(x,y,2,I)\n\t@test P \u2248 P2\nend\n\n@testset \"independent errors\" begin\n    # Should get the same answer as Polynomials.polyfit\n    x = 1:5\n\ty = x .^ 2\n\t    \n    P = polyfit(x,y,2,ones(length(x)))\n    P2 = Polynomials.polyfit(x,y,2)\n    @test P \u2248 P2\n\n\tP = polyfit(x,y,2,Diagonal(ones(length(x))))\n\t@test P \u2248 P2\n\n\tP = polyfit(x,y,2,Diagonal(2ones(length(x))))\n\t@test P \u2248 P2\nend\n\n@testset \"covariance matrix\" begin\n    x = 1:5\n\ty = x .^ 2\n\n\t# Should get the same answer as Polynomials.polyfit\n\tP = polyfit(x,y,2,Array(Diagonal(ones(length(x)))))\n\tP2 = Polynomials.polyfit(x,y,2)\n    @test P \u2248 P2\nend", "meta": {"hexsha": "ebca13ebae97e1484b7191abd8ce9506f06b8329", "size": 1135, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jishnub/PolyFit.jl", "max_stars_repo_head_hexsha": "ed415fe2a227c45b028ed82776bb211d8bcc59ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-12-27T13:36:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T12:52:52.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "jishnub/PolyFit.jl", "max_issues_repo_head_hexsha": "ed415fe2a227c45b028ed82776bb211d8bcc59ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-23T04:54:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-25T13:09:06.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "jishnub/PolyFit.jl", "max_forks_repo_head_hexsha": "ed415fe2a227c45b028ed82776bb211d8bcc59ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T16:58:53.000Z", "avg_line_length": 20.6363636364, "max_line_length": 64, "alphanum_fraction": 0.6114537445, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7574132136544088}}
{"text": "########################################################################\nfunction ppca_given_b(X, b; Q=1)\n########################################################################\n\n    D, N = size(X)\n\n    @assert(length(b) == D)\n\n    JITTER = 1e-8\n\n    numparam = D*Q        +   1     +  1\n    #    linear mapping    scale    noise\n\n    @printf(\"Running PPCA_given_b for %d number of data items of dimension %d, projected to %d components\\n\", N, D, Q)\n\n\n    #---------------------------------------------\n    function marginalLogLikelihood(W, \u03bc, \u03c3)\n    #---------------------------------------------\n\n        sum(logpdf(MvNormal(\u03bc, W*W' + \u03c3*\u03c3*I + JITTER*I), X))\n\n    end\n\n\n    #---------------------------------------------\n    function unpack(param)\n    #---------------------------------------------\n\n        local W = reshape(param[1:end-2], D, Q)\n\n        local s = exp(param[end-1])\n\n        local \u03c3 = exp(param[end])\n\n        return W, s, \u03c3\n\n    end\n\n\n    #---------------------------------------------\n    function objective(param)\n    #---------------------------------------------\n\n        @assert(length(param) == numparam)\n\n        local W, s, \u03c3 = unpack(param)\n\n        return -1.0 * marginalLogLikelihood(W, s * b, \u03c3)\n\n    end\n\n\n    #---------------------------------------------\n    # Run optimiser\n    #---------------------------------------------\n\n    opt    = Optim.Options(show_trace = true, iterations = 10_000)\n\n    result = optimize(objective, [randn(D*Q); randn()*3; randn()*3], LBFGS(), opt, autodiff=:forward)\n\n    W, s, \u03c3 = unpack(result.minimizer)\n\n\n    #---------------------------------------------\n    # Return results\n    #---------------------------------------------\n\n    return W, s, \u03c3\n\nend\n", "meta": {"hexsha": "dbb10d46a51fe4d4b7165969a2e6c447742449e1", "size": 1724, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OLD/clean/PPCA/ppca_given_b.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/clean/PPCA/ppca_given_b.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/clean/PPCA/ppca_given_b.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": 23.9444444444, "max_line_length": 118, "alphanum_fraction": 0.3497679814, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.757413206792797}}
{"text": "using StatsBase\nusing Base.Test\n\na = rand(5, 6)\nb = rand(5, 6)\n\n@test_approx_eq sqL2dist(a, b) sum(abs2(a - b))\n@test_approx_eq L2dist(a, b)   sqrt(sqL2dist(a, b))\n@test_approx_eq L1dist(a, b)   sum(abs(a - b))\n@test_approx_eq Linfdist(a, b) maximum(abs(a - b))\n\n@test_approx_eq gkldiv(a, b) sum(a .* log(a ./ b) - a + b)\n\n@test_approx_eq meanad(a, b) mean(abs(a - b))\n@test_approx_eq maxad(a, b)  maximum(abs(a - b))\n@test_approx_eq msd(a, b)    mean(abs2(a - b))\n@test_approx_eq rmsd(a, b)   sqrt(msd(a, b))\n@test_approx_eq rmsd(a, b; normalize=true)  rmsd(a, b) / (maximum(a) - minimum(a))\n@test_approx_eq psnr(a, b, 2)  10 * log10(4 / msd(a, b))   \n\n", "meta": {"hexsha": "0cf54a37fe6a6c0602df5356d2e352ea6bd543bf", "size": 654, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/deviation.jl", "max_stars_repo_name": "wildart/StatsBase.jl", "max_stars_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_stars_repo_licenses": ["MIT"], "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/deviation.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": "test/deviation.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": 31.1428571429, "max_line_length": 82, "alphanum_fraction": 0.6422018349, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7574131999596012}}
{"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 \u00d7 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# \u2554\u2550\u2561 60941eaa-1aea-11eb-1277-97b991548781\nbegin \n    using PlutoUI,GridVisualize,SimplexGridFactory,Triangulate,ExtendableGrids,VoronoiFVM,PlutoVista,PlutoUI,PyPlot\nend\n\n# \u2554\u2550\u2561 de468cb9-b34d-4d2e-b911-9b93920caca1\nmd\"\"\"\n# Flux reconstruction and visualization for the Laplace operator\n\"\"\"\n\n# \u2554\u2550\u2561 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\u03c0,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# \u2554\u2550\u2561 49f425a4-455c-40f5-b939-da704032cb88\nmd\"\"\"\nGenerate & plot grid\n\"\"\"\n\n# \u2554\u2550\u2561 bc304085-69c3-4974-beb4-6f2b981ac0f1\ngrid=swiss_cheese_2d()\n\n# \u2554\u2550\u2561 ad0367e6-7308-46bc-a7ff-9c17dcfe470d\ngridplot(grid,Plotter=PlutoVista)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f4ebe6ad-4e04-4f33-9a66-6bec977adf4d\nmd\"\"\"\nDefine a finite volume system with Dirichlet boundary conditions at some of the holes\n\"\"\"\n\n# \u2554\u2550\u2561 934a98f1-9734-45bc-848e-4d4d8ad80e4e\nphysics=VoronoiFVM.Physics(flux=flux)\n\n# \u2554\u2550\u2561 f3af20fb-c3cc-41af-9782-d40adf2371f7\nsystem=VoronoiFVM.System(grid,physics)\n\n# \u2554\u2550\u2561 50ea0a7e-97e0-428d-b4ec-6bd4d7aef31f\nenable_species!(system,1,[1])\n\n# \u2554\u2550\u2561 49d3c96b-f6b4-4581-8600-8aaf50bb07fc\nboundary_dirichlet!(system,1,2,10.0)\n\n# \u2554\u2550\u2561 fa5200ff-713e-48fb-b452-c6ee96935cfc\nboundary_dirichlet!(system,1,3,0.0)\n\n# \u2554\u2550\u2561 6b09f75a-521b-40d9-9636-155e62ab0cac\nmd\"\"\"\nAt hole #11, the value will be bound to a slider defined below\n\"\"\"\n\n# \u2554\u2550\u2561 d86c43f3-ec2f-4fae-88d2-1068603e7044\nmd\"\"\"\nSolve, and trigger solution upon boundary value change\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 17be52fb-f55b-4b3d-85e5-33f36134046b\nvis=GridVisualizer(Plotter=PlutoVista,dim=2,resolution=(400,400));vis\n\n# \u2554\u2550\u2561 03f582ec-4e95-4ca4-8482-9c797027810d\nmd\"\"\"\n``v_{11}:`` $(@bind  val11 Slider(0:0.1:10,default=5,show_value=true))\n\"\"\"\n\n# \u2554\u2550\u2561 e8ae2b22-ac60-449b-952f-d2c55852677c\nboundary_dirichlet!(system,1,11,val11)\n\n# \u2554\u2550\u2561 27efdcac-8ee4-47e4-905d-8d8c7313ddd1\nval11; sol=solve(unknowns(system,inival=0),system)\n\n# \u2554\u2550\u2561 41f427c1-b6ad-46d4-9151-1d872b4efeb6\nnf=nodeflux(system,sol)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 531edb71-6d32-4231-b117-5e36416d2fb1\nmyplot(vis)\n\n# \u2554\u2550\u2561 e0b92e00-dd0b-448b-baae-5cd4e0a2059a\nmd\"\"\"\nPlot with PyPlot: $(@bind use_pyplot CheckBox(default=false))\n\"\"\"\n\n# \u2554\u2550\u2561 1495eb67-12ec-4662-b0e7-049ffef569c0\nif use_pyplot\n\tpyvis=GridVisualizer(Plotter=PyPlot,resolution=(400,400))\n\tmyplot(pyvis)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500de468cb9-b34d-4d2e-b911-9b93920caca1\n# \u2560\u255060941eaa-1aea-11eb-1277-97b991548781\n# \u2560\u2550928a70c5-4706-40a1-9387-abcb71c09443\n# \u255f\u250049f425a4-455c-40f5-b939-da704032cb88\n# \u2560\u2550bc304085-69c3-4974-beb4-6f2b981ac0f1\n# \u2560\u2550ad0367e6-7308-46bc-a7ff-9c17dcfe470d\n# \u2560\u2550236d6cd5-c190-49c7-98fe-021fae224455\n# \u255f\u2500f4ebe6ad-4e04-4f33-9a66-6bec977adf4d\n# \u2560\u2550934a98f1-9734-45bc-848e-4d4d8ad80e4e\n# \u2560\u2550f3af20fb-c3cc-41af-9782-d40adf2371f7\n# \u2560\u255050ea0a7e-97e0-428d-b4ec-6bd4d7aef31f\n# \u2560\u255049d3c96b-f6b4-4581-8600-8aaf50bb07fc\n# \u2560\u2550fa5200ff-713e-48fb-b452-c6ee96935cfc\n# \u255f\u25006b09f75a-521b-40d9-9636-155e62ab0cac\n# \u2560\u2550e8ae2b22-ac60-449b-952f-d2c55852677c\n# \u255f\u2500d86c43f3-ec2f-4fae-88d2-1068603e7044\n# \u2560\u255027efdcac-8ee4-47e4-905d-8d8c7313ddd1\n# \u255f\u250041bd1230-c87c-47b0-8e58-67ad55609fd3\n# \u2560\u255041f427c1-b6ad-46d4-9151-1d872b4efeb6\n# \u2560\u2550c9b9fdb1-5734-430f-949a-6e6126d2f091\n# \u2560\u255017be52fb-f55b-4b3d-85e5-33f36134046b\n# \u255f\u250003f582ec-4e95-4ca4-8482-9c797027810d\n# \u2560\u2550531edb71-6d32-4231-b117-5e36416d2fb1\n# \u255f\u2500e0b92e00-dd0b-448b-baae-5cd4e0a2059a\n# \u2560\u25501495eb67-12ec-4662-b0e7-049ffef569c0\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "using Plots\n\nfunction calc_midpoints(edges::AbstractVector)::Vector{Float64}\n    return Float64[0.5 * (edges[i] + edges[i+1]) for i \u2208 1:length(edges)-1]\nend\n\nfunction bin_data(data::AbstractVector, bins::Integer)\n    low, high = extrema(data)\n    edges = collect(range(low, stop = high, length = bins + 1))\n    midpoints = calc_midpoints(edges)\n    buckets = Int[max(2, min(searchsortedfirst(edges, x), length(edges))) - 1 for x \u2208 data]\n    counts = zeros(Int, length(midpoints))\n    for b in buckets\n        counts[b] += 1\n    end\n    return edges, midpoints, buckets, counts\nend\n\nrectangle(x, y, w, h) = Shape(x .+ [0, w, w, 0], y .+ [0, 0, h, h])\n\nfunction myhistogram(data; bins = 10, norm = true, alpha = 0.5)\n    edges, midpoints, buckets, _counts = bin_data(data, bins)\n    if norm\n        tot = length(data)\n        counts = _counts ./ tot\n    else\n        counts = _counts\n    end\n    p = plot()\n    for i = 1:length(midpoints)\n        emin, emax = edges[i], edges[i+1]\n        c = Float64(counts[i])\n        r = rectangle(emin, zero(c), emax - emin, c)\n        plot!(p, r, legend = false, color = :blue, alpha = alpha)\n    end\n    p = plot(p)\n    return p\nend\n\nfunction main()\n    data = randn(1000)\n    dmin, dmax = extrema(data)\n    bins = 10\n    norm = true\n    p = myhistogram(data, bins = bins, norm = norm, alpha = 1)\nend\n", "meta": {"hexsha": "39a16d90d6a76314d59ad537fc1bd18dd2262112", "size": 1338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plotExer/histhack.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": "plotExer/histhack.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": "plotExer/histhack.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.4680851064, "max_line_length": 91, "alphanum_fraction": 0.6016442451, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676514011486, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7573819129936487}}
{"text": "# An implementation of CGLS for the solution of the\n# over-determined linear least-squares problem\n#\n#  minimize \u2016Ax - b\u2016\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\u00f6rck, 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 \u2016b - Ax\u2016\u2082\u00b2 + \u03bb \u2016x\u2016\u2082\u00b2\n\nusing the Conjugate Gradient (CG) method, where \u03bb \u2265 0 is a regularization\nparameter. This method is equivalent to applying CG to the normal equations\n\n  (A'A + \u03bbI) x = A'b\n\nbut is more stable.\n\nCGLS produces monotonic residuals \u2016r\u2016\u2082 but not optimality residuals \u2016A'r\u2016\u2082.\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)), \u03bb :: 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  \u03b3 = @kdot(n, s, s)  # Faster than \u03b3 = dot(s, s);\n  iter = 0;\n  itmax == 0 && (itmax = m + n);\n\n  rNorm  = bNorm;\n  ArNorm = sqrt(\u03b3);\n  rNorms = [rNorm;];\n  ArNorms = [ArNorm;];\n  \u03b5 = atol + rtol * ArNorm;\n  verbose && @printf(\"%5s  %8s  %8s\\n\", \"Aprod\", \"\u2016A'r\u2016\", \"\u2016r\u2016\")\n  verbose && @printf(\"%5d  %8.2e  %8.2e\\n\", 1, ArNorm, rNorm);\n\n  status = \"unknown\";\n  on_boundary = false\n  solved = ArNorm <= \u03b5;\n  tired = iter >= itmax;\n\n  while ! (solved || tired)\n    q = A * p;\n    \u03b4 = @kdot(m, q, M * q)   # Faster than \u03b1 = \u03b3 / dot(q, q);\n    \u03bb > 0 && (\u03b4 += \u03bb * @kdot(n, p, p))\n    \u03b1 = \u03b3 / \u03b4;\n\n    # if a trust-region constraint is give, compute step to the boundary\n    \u03c3 = radius > 0.0 ? maximum(to_boundary(x, p, radius)) : \u03b1\n    if (radius > 0.0) & (\u03b1 > \u03c3)\n      \u03b1 = \u03c3\n      on_boundary = true\n    end\n\n    @kaxpy!(n,  \u03b1, p, x)     # Faster than x = x + \u03b1 * p;\n    @kaxpy!(m, -\u03b1, q, r)     # Faster than r = r - \u03b1 * q;\n    s = A' * M * r;\n    \u03bb > 0 && @kaxpy!(n, -\u03bb, x, s)   # s = A' * r - \u03bb * x;\n    \u03b3_next = @kdot(n, s, s)  # Faster than \u03b3_next = dot(s, s);\n    \u03b2 = \u03b3_next / \u03b3;\n    @kscal!(n, \u03b2, p)\n    @kaxpy!(n, 1.0, s, p)    # Faster than p = s + \u03b2 * p;\n    # The combined BLAS calls tend to trigger some gc.\n    #  BLAS.axpy!(n, 1.0, s, 1, BLAS.scal!(n, \u03b2, p, 1), 1);\n    \u03b3 = \u03b3_next;\n    rNorm = @knrm2(m, r)  # Marginally faster than norm(r);\n    ArNorm = sqrt(\u03b3);\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 <= \u03b5) | 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": "cd(@__DIR__); include(\"setups/grid23x22.jl\")\ngr(dpi = 200)\n\n## assemble frames\nframe = sgwt_frame(W; nf = 6)\nSGWT = reshape(frame, (N, :))\nSGWT_dual = (SGWT * SGWT') \\ SGWT\n\nrNGWF, dic_l2x = rngwf_all_vectors(D, \ud835\udebd; \u03c3 = 0.2 * maximum(D), thres = 0.15)\nrNGWF_dual = (rNGWF * rNGWF') \\ rNGWF\n\u0393 = rngwf_lx(dic_l2x)\n\n## (a)\nf = digit_img[:]\nplt = heatmap(reshape(f, (Nx, Ny))', c = :viridis, ratio = 1,\n        frame = :none, xlim = [1, Nx], size = (600, 500))\nsavefig(plt, \"../figs/grid23x22_fdigit3.png\")\n\n## (b)\nrel_approx_sgwt, f_approx_sgwt = frame_approx(f, SGWT, SGWT_dual; num_kept = 3 * N)\nrel_approx_rngwf, f_approx_rngwf = frame_approx(f, rNGWF, rNGWF_dual; num_kept = 3 * N)\nplot(0:length(rel_approx_rngwf)-1, [rel_approx_sgwt rel_approx_rngwf],\n    grid = false, lw = 2, c = [:blue :green],\n    xlab = \"Number of Coefficients Retained\",\n    ylab = \"Relative Approximation Error\", yaxis = :log,\n    lab = [\"SGWT\" \"rNGWF\"])\nplt = plot!(xguidefontsize = 14, yguidefontsize = 14, legendfontsize = 11, size = (600, 500))\nsavefig(plt, \"../figs/grid23x22_approx_fdigit3.png\")\n", "meta": {"hexsha": "61280eeeb8c01f57cb60f38904f89625c3943a09", "size": 1077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dissertations/htli/scripts/Figure10.7.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/dissertations/htli/scripts/Figure10.7.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/dissertations/htli/scripts/Figure10.7.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": 37.1379310345, "max_line_length": 93, "alphanum_fraction": 0.661095636, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7573734326553732}}
{"text": "\n\"\"\"\nReverse plus\n\"\"\"\nfunction plus_rev(a::Interval, b::Interval, c::Interval)  # a = b + c\n    # a = a \u2229 (b + c)  # add this line for plus contractor (as opposed to reverse function)\n    b_new = b \u2229 (a - c)\n    c_new = c \u2229 (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 \u2229 (a + c)\n    c_new = c \u2229 (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 \u2229 (-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 \u2209 a) || (0.0 \u2209 b)) && (c = c \u2229 (a / b))\n    # ((0.0 \u2209 a) || (0.0 \u2209 c)) && (b = b \u2229 (a / c))\n\n    # a = a \u2229 (b * c)  # ?\n\n    if 0 \u2208 b\n        temp = c .\u2229 extended_div(a, b)\n        c\u2032 = union(temp[1], temp[2])\n\n    else\n        c\u2032 = c \u2229 (a / b)\n    end\n\n    if 0 \u2208 c\n        temp = b .\u2229 extended_div(a, c)\n        b\u2032 = union(temp[1], temp[2])\n\n    else\n        b\u2032 = b \u2229 (a / c)\n    end\n\n    return a, b\u2032, c\u2032\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 \u2229 (a * c)\n    c = c \u2229 (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 \u2229 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 = \u221aa\n        b1 = b \u2229 root\n        b2 = b \u2229 (-root)\n\n    elseif iseven(n)\n        root = a^(1//n)\n\n        b1 = b \u2229 root\n        b2 = b \u2229 (-root)\n\n    elseif isodd(n)\n        pos_root = (a \u2229 (0..\u221e)) ^ (1//n)\n        neg_root = -( ( (-a) \u2229 (0..\u221e) ) ^ (1//n) )\n\n        b1 = b \u2229 pos_root\n        b2 = b \u2229 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 \u2229 ( a^(inv(c) ))\n    c_new = c \u2229 (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 \u2229 (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 \u2229 root\n    x2 = x \u2229 (-root)\n\n    return (c, hull(x1, x2))\nend\n\nsqr_rev(c) = sqr_rev(c, -\u221e..\u221e)\n\n\"\"\"\nReverse abs\n\"\"\"\nfunction abs_rev(y, x)   # y = abs(x); refine x\n\n    y_new = y \u2229 (0..\u221e)\n\n    x1 = y_new \u2229 x\n    x2 = -(y_new \u2229 (-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 \u2229 (0..\u221e)\n    (a == 0.0) && b = b \u2229 (0.0..0.0)\n    (a == -1.0) && b = b \u2229 (-\u221e..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- `\u2218_rev1(b, c, x)` is the subset of `x` such that `x \u2218 b` is defined and in `c`;\n- `\u2218_rev2(a, c, x)` is the subset of `x` such that `a \u2218 x` is defined and in `c`\n\nWhen `\u2218` is commutative, these agree and we write `\u2218_rev(b, c, x)`.\n\"\"\"\n\nfunction mul_rev_IEEE1788(b, c, x)   # c = b*x\n    return x \u2229 (c / b)\nend\n\nfunction pow_rev1(b, c, x)   # c = x^b\n    return x \u2229 c^(1/b)  # replace by 1//b\nend\n\nfunction pow_rev2(a, c, x)   # c = a^x\n    return x \u2229 (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": "# ---\n# title: 1201. Ugly Number III\n# id: problem1201\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math, Binary Search\n# link: <https://leetcode.com/problems/ugly-number-iii/description/>\n# hidden: true\n# ---\n# \n# Write a program to find the `n`-th ugly number.\n# \n# Ugly numbers are **  positive integers** which are divisible by `a`  **or**\n# `b`  **or** `c`.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: n = 3, a = 2, b = 3, c = 5\n#     Output: 4\n#     Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.\n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: n = 4, a = 2, b = 3, c = 4\n#     Output: 6\n#     Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: n = 5, a = 2, b = 11, c = 13\n#     Output: 10\n#     Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: n = 1000000000, a = 2, b = 217983653, c = 336916467\n#     Output: 1999999984\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `1 <= n, a, b, c <= 10^9`\n#   * `1 <= a * b * c <= 10^18`\n#   * It's guaranteed that the result will be in range `[1, 2 * 10^9]`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "83a8c06e81e2a2d0d14f779c486ca0b050f72999", "size": 1320, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/1201.ugly-number-iii.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/1201.ugly-number-iii.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/1201.ugly-number-iii.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.7014925373, "max_line_length": 84, "alphanum_fraction": 0.5045454545, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7573734238001885}}
{"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    \u03bc::Float64\n    \u03c3::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(\u03bc, \u03c3, 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(\u03bc, \u03c3, Q)\n    gdist = Distributions.Gamma(1/Q^2,1)\n    GenGamma(\u03bc, \u03c3, 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 \u03c0 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    \u03bc = log(a) + (log(abs(d)) - log(abs(p)))/p\n    \u03c3 = 1 / sqrt(p*d)\n    Q = sqrt(p/d) * sign(p)\n    GenGamma(\u03bc,\u03c3,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.\u03bc + p.\u03c3 * 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.\u03c3 / p.Q) * exp(p.\u03bc)\n    a * gamma(iQs + p.\u03c3/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.\u03c3 * dt.Q)\n    p = (dt.Q)/(dt.\u03c3)\n    a = abs(dt.Q)^(2/p)*exp(dt.\u03bc)\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.\u03bc, d.\u03c3, 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 \u2211\u1d62 \u03c1((A*sol - b)\u1d62) using the specified MEstimator for \u03c1 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 \u2208 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, \u03d5, \u03b1, \u03c4, tspan = FDDE\n    t = collect(0:h:tspan)\n    maxn = length(t)\n    yp = zeros(maxn)\n    y = copy(t)\n    y[1] = \u03d5(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, \u03b1, h)*f(t[j], y[j], v(\u03d5, j, \u03c4, h, y, yp)...)\n        end\n        yp[n+1] = yp[n+1]/gamma(\u03b1)+\u03d5(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, \u03b1, h)*f(t[j], y[j], v(\u03d5, j, \u03c4, h, y, yp)...)\n        end\n\n        y[n+1] = y[n+1]/gamma(\u03b1)+h^\u03b1*f(t[n+1], yp[n+1], v(\u03d5, n+1, \u03c4, h, y, yp)...)/gamma(\u03b1+2) + \u03d5(0)\n    end\n\n    V = []\n    for n = 1:maxn\n        push!(V, v(\u03d5, n, \u03c4, h, y, yp))\n    end\n\n    delayed = zeros(length(\u03c4), 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, \u03b1, h)\n    if j == n+1\n        result = 1\n    elseif j == 0\n        result = n^(\u03b1+1)-(n-\u03b1)*(n+1)^\u03b1\n    elseif j == n\n        result = 2*(2^(\u03b1+1)-1)\n    else\n        result = (n-j+2)^(\u03b1+1) + (n-j)^(\u03b1+1) - 2*(n-j+1)^(\u03b1+1)\n    end\n    return result*h^\u03b1 / (\u03b1*(\u03b1 + 1))\nend\n\nfunction b(j, n, \u03b1, h)\n    return h^\u03b1/\u03b1*((n-j+1)^\u03b1 - (n-j)^\u03b1)\nend\n\nfunction v(\u03d5, n, \u03c4, h, y, yp)\n    if maximum(\u03c4) > n*h\n        return \u03d5.((n-1)*h.-\u03c4)\n    else\n        m = floor.(Int, \u03c4./h)\n        \u03b4 = m.-\u03c4./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] = \u03b4[i]*y[n-m[i]+2]+(1-\u03b4[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": "# ---\n# title: 537. Complex Number Multiplication\n# id: problem537\n# author: Indigo\n# date: 2021-06-23\n# difficulty: Medium\n# categories: Math, String\n# link: <https://leetcode.com/problems/complex-number-multiplication/description/>\n# hidden: true\n# ---\n# \n# Given two strings representing two [complex\n# numbers](https://en.wikipedia.org/wiki/Complex_number).\n# \n# You need to return a string representing their multiplication. Note i2 = -1\n# according to the definition.\n# \n# **Example 1:**  \n# \n#     \n#     \n#     Input: \"1+1i\", \"1+1i\"\n#     Output: \"0+2i\"\n#     Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n#     \n# \n# **Example 2:**  \n# \n#     \n#     \n#     Input: \"1+-1i\", \"1+-1i\"\n#     Output: \"0+-2i\"\n#     Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n#     \n# \n# **Note:**\n# \n#   1. The input strings will not have extra blank.\n#   2. The input strings will be given in the form of **a+bi** , where the integer **a** and **b** will both belong to the range of [-100, 100]. And **the output should be also in this form**.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction complex_number_multiply(num1::String, num2::String)\n    Ct = Complex{Int}\n    mult = parse(Ct, num1) * parse(Ct, num2)\n    return \"$(mult.re)+$(mult.im)i\"\nend\n## @lc code=end\n", "meta": {"hexsha": "47d51d6d690878cc11ba6835f7b7ae3667252eb6", "size": 1366, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/537.complex-number-multiplication.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/537.complex-number-multiplication.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/537.complex-number-multiplication.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.7843137255, "max_line_length": 192, "alphanum_fraction": 0.6046852123, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107966642557, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7573293191380284}}
{"text": "# Kochenderfer, Mykel J.. Algorithms for Optimization (The MIT Press)\n\nfunction branin(x; a=1, b=5.1/(4\u03c0^2), c=5/\u03c0, r=6, s=10, t=1/(8\u03c0))\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\u03c0)\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": "# This file includes and example file for 2D interpolation \n\nusing FractalTools \nusing GeometryBasics\nusing CairoMakie\n\n# Generate data \nf(x, y) = x^2 + y^2 + 1\nngon = Triangle(\n    Point(BigFloat(0.), BigFloat(0.)), \n    Point(BigFloat(1.), BigFloat(0.)), \n    Point(BigFloat(0.5), BigFloat(1.)))\nnpts = 100\npts = getdata(f, ngon, npts)\ninterp = interpolate(pts, Interp2D(0.01))\n\nfunction err(x, y)\n    fval = f(x, y) \n    ival = interp(x, y) \n    abs(fval - ival) / abs(fval) * 100\nend\n\ntpts = getdata(ngon, npts)\n\nfig, ax, plt = trisurf(tpts, f, meshcolor3=:red)\ntrisurf!(ax, tpts, interp, meshcolor3=:blue)\nfig, ax, plt = trisurf(tpts, err, meshcolor3=:red)\n", "meta": {"hexsha": "4f0743b5a608627e6cf1b491bf8dae344869dd1a", "size": 662, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/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": "example/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": "example/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": 23.6428571429, "max_line_length": 59, "alphanum_fraction": 0.6555891239, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7573222937445836}}
{"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": "using svopt\nusing Test\n\n\n\u03f5 = 1e-5\n\n@testset \"ratio helpers\" begin\n    a = -5\n    b = 10\n    @test svopt.fw1(a, b) - a == b - svopt.fw2(a, b)\nend # testset\n\n\n@testset \"optfun\" begin\n    f1(x) = x^2\n    f2(x) = (x-1)^2*10 + 10\n    f3(x) = (x+10)^2 - 10\n    f4(x) = x^2 - 1\n    f5(x) = x^2/3 + 2x - sin(x)\n\n    @test isapprox(optfun(f1, -3, 10), 0, atol=\u03f5)\n    @test isapprox(optfun(f2, -3, 10), 1, atol=\u03f5)\n    @test isapprox(optfun(f3, -30, 30), -10, atol=\u03f5)\n    @test isapprox(optfun(f4, -10, 30), 0, atol=\u03f5)\n    @test isapprox(optfun(f5, -10, 5), -3.99083, atol=\u03f5)\nend\n", "meta": {"hexsha": "b73c9a0db6e127dd8b14ad2e960f963009d73292", "size": 569, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "not7cd/svopt", "max_stars_repo_head_hexsha": "5a8476bbaf175182e8c7bed97926a079aa90e97b", "max_stars_repo_licenses": ["MIT"], "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": "not7cd/svopt", "max_issues_repo_head_hexsha": "5a8476bbaf175182e8c7bed97926a079aa90e97b", "max_issues_repo_licenses": ["MIT"], "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": "not7cd/svopt", "max_forks_repo_head_hexsha": "5a8476bbaf175182e8c7bed97926a079aa90e97b", "max_forks_repo_licenses": ["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.0740740741, "max_line_length": 56, "alphanum_fraction": 0.5342706503, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7573222878819886}}
{"text": "using Diagonalizations, LinearAlgebra, PosDefManifold, Test\n\n# Method (1) real\nn, t=10, 100\nX=genDataMatrix(n, t)\nC=(X*X')/t\npC=pca(Hermitian(C); simple=true)\n# or, shortly\npC=pca(\u210d(C); simple=true)\n\n# Method (1) complex\nXc=genDataMatrix(ComplexF64, n, t)\nCc=(Xc*Xc')/t\npCc=pca(Hermitian(Cc); simple=true)\n\n\n# Method (2) real\npX=pca(X; simple=true)\n@test C\u2248pC.F*pC.D*pC.iF\n@test C\u2248pC.F*pC.D*pC.F'\n@test pX\u2248pC\n\n# Method (2) complex\npXc=pca(Xc; simple=true)\n@test Cc\u2248pCc.F*pCc.D*pCc.iF\n@test Cc\u2248pCc.F*pCc.D*pCc.F'\n@test pXc\u2248pCc\n\n\n# Method (3) real\nk=10\nXset=[genDataMatrix(n, t) for i=1:k]\n\n# pca on the average covariance matrix\np=pca(Xset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.5\np=pca(Xset; eVar=0.5)\n\n# ... averaging the covariance matrices using the logEuclidean metric\np=pca(Xset; metric=logEuclidean, eVar=0.5)\n\n# ... giving weights `w` to the covariance matrices\np=pca(Xset; metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# ... subtracting the mean\np=pca(Xset; meanX=nothing, metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# pca on the average of the covariance matrices computed along dims 1\np=pca(Xset; dims=1)\n\n# explained variance\np.eVar\n\n# name of the filter\np.name\n\nusing Plots\n# plot regularized accumulated eigenvalues\nplot(p.arev)\n\n# plot the original covariance matrix and the rotated covariance matrix\n Cmax=maximum(abs.(C));\n h1 = heatmap(C, clim=(-Cmax, Cmax), yflip=true, c=:bluesreds, title=\"C\");\n D=pC.F'*C*pC.F;\n Dmax=maximum(abs.(D));\n h2 = heatmap(D, clim=(0, Dmax), yflip=true, c=:amp, title=\"F'*C*F\");\n \ud83d\udcc8=plot(h1, h2, size=(700, 300))\n# savefig(\ud83d\udcc8, homedir()*\"\\\\Documents\\\\Code\\\\julia\\\\Diagonalizations\\\\docs\\\\src\\\\assets\\\\FigPCA.png\")\n\n# Method (3) complex\nk=10\nXcset=[genDataMatrix(ComplexF64, n, t) for i=1:k]\n\n# pca on the average covariance matrix\npc=pca(Xcset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.5\npc=pca(Xcset; eVar=0.5)\n\n# ... averaging the covariance matrices using the logEuclidean metric\npc=pca(Xcset; metric=logEuclidean, eVar=0.5)\n\n# ... giving weights `w` to the covariance matrices\npc=pca(Xcset; metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# ... subtracting the mean\npc=pca(Xcset; meanX=nothing, metric=logEuclidean, w=abs2.(randn(k)), eVar=0.5)\n\n# pca on the average of the covariance matrices computed along dims 1\npc=pca(Xcset; dims=1)\n\n# explained variance\npc.eVar\n\n# name of the filter\npc.name\n", "meta": {"hexsha": "c0095b428e52e07b571596ab30b44b3dda9a1864", "size": 2424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/PCA.jl", "max_stars_repo_name": "ericphanson/Diagonalizations.jl", "max_stars_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/PCA.jl", "max_issues_repo_name": "ericphanson/Diagonalizations.jl", "max_issues_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/PCA.jl", "max_forks_repo_name": "ericphanson/Diagonalizations.jl", "max_forks_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": 24.7346938776, "max_line_length": 99, "alphanum_fraction": 0.7070957096, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7573222870912956}}
{"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 \u2265 0\nwhere `a` is a given nonnegative scalar.\nThe analytical expression is available:\n    y = { x  if  x \u2265 \u221a2a,  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 \u2265 0,    1 \u22c5 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 \u2265 0,    1 \u22c5 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    \u03b1 = 1 / stat.n\n    stat.m = (1 - \u03b1) * stat.m + \u03b1 * 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\u0304::PVector{T,N}) where {T,N}\n    ranges = ProjectiveVectors.dimension_indices(v\u0304)\n    for range in ranges\n        \u03bb = zero(eltype(x))\n        @inbounds for i in range\n            \u03bb += v\u0304[i] * x[i]\n        end\n        \u03bb\u207b\u00b9 = @fastmath inv(\u03bb)\n        for i in range\n            x[i] *= \u03bb\u207b\u00b9\n        end\n    end\n    x\nend\n\nfunction evaluate_patch!(u, v\u0304::PVector{S,N}, x::PVector{T,N}) where {S,T,N}\n    ranges = ProjectiveVectors.dimension_indices(v\u0304)\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\u0304[i] * x[i]\n        end\n        u[n+k] = out\n    end\n    nothing\nend\n\nfunction jacobian_patch!(U, v\u0304::PVector{S,N}, x::PVector) where {S,T,N}\n    ranges = ProjectiveVectors.dimension_indices(v\u0304)\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\u0304[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": "import MaximumLikelihoodProblems\n\nimport GLM\nimport Statistics\nimport Test\n\n\u03c3_true = 0.5\n\u03b2_true = [1.0, 2.0, -1.0]\n\n# @show \u03c3_true\n# @show \u03c3_hat\n# @show \u03b2_true\n# @show \u03b2_hat\n\nTest.@test typeof(\u03c3_hat) == typeof(\u03c3_true)\nTest.@test \u03c3_hat isa Real\nTest.@test \u03c3_true isa Real\nTest.@test isfinite(\u03c3_hat)\nTest.@test \u03c3_hat > 0.1\nTest.@test abs(\u03c3_hat - \u03c3_true) < 0.03\nTest.@test abs2(\u03c3_hat - \u03c3_true) < 1e-3\n\nTest.@test typeof(\u03b2_hat) == typeof(\u03b2_true)\nTest.@test ndims(\u03b2_hat) == ndims(\u03b2_true)\nTest.@test size(\u03b2_hat) == size(\u03b2_true)\nabsolute_error = abs.(\u03b2_hat - \u03b2_true)\nsquare_error = abs2.(\u03b2_hat - \u03b2_true)\nabsolute_error_proportional = absolute_error ./ abs.(\u03b2_true)\nsquare_error_proportional = square_error ./ abs.(\u03b2_true)\nTest.@test sum(absolute_error) < 0.030\nTest.@test sum(square_error) < 1e-3\nTest.@test sum(absolute_error_proportional) < 0.030\nTest.@test sum(square_error_proportional) < 1e-3\nTest.@test maximum(absolute_error) < 0.013\nTest.@test maximum(square_error) < 1e-3\nTest.@test maximum(absolute_error_proportional) < 0.013\nTest.@test maximum(square_error_proportional) < 1e-3\nTest.@test Statistics.mean(absolute_error) < 0.010\nTest.@test Statistics.mean(square_error) < 1e-3\nTest.@test Statistics.mean(absolute_error_proportional) < 0.007\nTest.@test Statistics.mean(square_error_proportional) < 1e-3\n\ngradient_vector_at_\u03b8_hat = MaximumLikelihoodProblems.Internal.gradient_vector(transformed_gradient_problem,\n                                                                              \u03b8_hat)\nhessian_matrix_at_\u03b8_hat = MaximumLikelihoodProblems.Internal.hessian_matrix(transformed_gradient_problem,\n                                                                            \u03b8_hat)\nTest.@test MaximumLikelihoodProblems.Internal._is_approximately_zero(gradient_vector_at_\u03b8_hat)\nTest.@test MaximumLikelihoodProblems.Internal._is_approximately_hermitian(hessian_matrix_at_\u03b8_hat)\nTest.@test MaximumLikelihoodProblems.Internal._is_approximately_negative_definite(hessian_matrix_at_\u03b8_hat;\n                                                                                  fuzz_factor = 10)\nTest.@test MaximumLikelihoodProblems.Internal._is_approximately_positive_definite(-hessian_matrix_at_\u03b8_hat;\n                                                                                  fuzz_factor = 10)\n\nn, p = size(X)\nbeta_hat_ols = ( X' * X )\\( X' * y )\nbeta_hat_mle = beta_hat_ols\ny_hat_ols = X * beta_hat_ols\nepsilon_hat_ols = y - y_hat_ols\nS_ols = epsilon_hat_ols' * epsilon_hat_ols\nsigma_2_hat_ols = (S_ols) / (n - p) # OLS estimator for \u03c3\u00b2\nsigma_2_hat_mle = (n - p) / (n) * sigma_2_hat_ols # MLE estimator for \u03c3\u00b2\nsigma_hat_ols = sqrt(sigma_2_hat_ols)\nsigma_hat_mle = sqrt(sigma_2_hat_mle)\nTest.@test isapprox(\u03c3_hat, sigma_hat_ols; atol = 1e-4)\nTest.@test isapprox(\u03c3_hat, sigma_hat_mle; atol = 1e-4)\nTest.@test isapprox(\u03b2_hat, beta_hat_ols)\nTest.@test isapprox(\u03b2_hat, beta_hat_mle)\n\nexternal_model_glm = GLM.lm(X, y)\nsigma_hat_external_model_glm = GLM.dispersion(external_model_glm)\nTest.@test isapprox(\u03c3_hat, sigma_hat_external_model_glm; atol = 1e-4)\nbeta_hat_external_model_glm = GLM.coef(external_model_glm)\nTest.@test isapprox(\u03b2_hat, beta_hat_external_model_glm)\n", "meta": {"hexsha": "a39502e58734e3cb575cabdb45daefa3e1afff2c", "size": 3170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 42.8378378378, "max_line_length": 107, "alphanum_fraction": 0.7157728707, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7573206792220931}}
{"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\u03b2 = Vector([0.0, 0.5, -0.5]) # true coefficients\n# \u30dd\u30a2\u30bd\u30f3\u5206\u5e03\u306e\u5e73\u5747\u3092\u30e2\u30c7\u30eb\u5316\n\u03bb = exp.(X*\u03b2)\ny = rand.(Poisson.(\u03bb)) # observable choice 0 or 1\n\n# set prior, \u03b2 ~ MvNormal(\u03b20, A0), no \u03c3\u00b2\nn, k = size(X)\n\u03b20 = zeros(k)\nA0 = 0.01 * I\n\n@model function poisson_regression_model(X, y)\n    # Set the priors only for \u03b2.\n    \u03b2 ~ MvNormal(\u03b20, 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, :]' * \u03b2))\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\u03b2_chn = chn[n_tune+1:n_draws, :, :] # delete initial and exclude odd (hamiltonian bluh bluh) chain \n\u03b2_chn = group(\u03b2_chn, :\u03b2)\n\nsummarize(\u03b2_chn)\nquantile(\u03b2_chn)\nplot(\u03b2_chn)\n\n# Marginal effect ... interpret \u03b2 just like as ln(y) = \u03b2x model (equivalent with \u03bb = 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# Log Function\n\n```julia\nlog(ts::TS, complex::Bool = false)\n```\n\nThis method computes the log value of non-index columns in the TS\nobject.\n\n# Examples\n```jldoctest; setup = :(using TSx, DataFrames, Dates, Random, Statistics)\njulia> using Random\njulia> random(x) = rand(MersenneTwister(123), x...);\njulia> ts = TS(random(([1, 2, 3, 4, missing], 10)))\njulia> show(ts)\n(10 x 1) TS with Int64 Index\n\n Index  x1\n Int64  Int64?\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n     1  missing\n     2        2\n     3        2\n     4        3\n     5        4\n     6        3\n     7        3\n     8  missing\n     9        2\n    10        3\n\njulia> log(ts)\n(10 x 1) TS with Int64 Index\n\n Index  x1_log\n Int64  Float64?\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n     1  missing\n     2        0.693147\n     3        0.693147\n     4        1.09861\n     5        1.38629\n     6        1.09861\n     7        1.09861\n     8  missing\n     9        0.693147\n    10        1.09861\n\n```\n\"\"\"\nfunction Base.log(ts::TS)\n    df = select(ts.coredata, :Index,\n                Not(:Index) .=> (x -> log.(x))\n                => colname -> string(colname, \"_log\"))\n    TS(df)\nend\n", "meta": {"hexsha": "7ab5681ab9454d1dcce0e16949298c43b47ce9d2", "size": 1105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/log.jl", "max_stars_repo_name": "xKDR/TSx.jl", "max_stars_repo_head_hexsha": "82189a7475159b3c1ded8448c548e79b0e14b25b", "max_stars_repo_licenses": ["MIT"], "max_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.jl", "max_issues_repo_name": "xKDR/TSx.jl", "max_issues_repo_head_hexsha": "82189a7475159b3c1ded8448c548e79b0e14b25b", "max_issues_repo_licenses": ["MIT"], "max_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.jl", "max_forks_repo_name": "xKDR/TSx.jl", "max_forks_repo_head_hexsha": "82189a7475159b3c1ded8448c548e79b0e14b25b", "max_forks_repo_licenses": ["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.0517241379, "max_line_length": 73, "alphanum_fraction": 0.4832579186, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7573206693970064}}
{"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, \u03c3\u00b2::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) * \u03c3\u00b2\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    \u03b81 = u[3]\n    \u03b82 = u[4]\n\n    h1 = p1*p2*sin(\u03b81-\u03b82)/(l1*l2*(m1+m2*sin(\u03b81-\u03b82)^2))\n    h2 = (m2*l2^2*p1^2 + (m1 + m2) * l1^2 * p2^2 - 2*m2*l1*l2*p1*p2*cos(\u03b81-\u03b82))/(2 * l1^2 * l2^2 *(m1 + m2*sin(\u03b81-\u03b82)^2)^2)\n\n    d_p1 = -(m1 + m2)* g*l1*sin(\u03b81) - h1 + h2*sin(2*(\u03b81-\u03b82))\n    d_\u03b81 = (l2*p1 - l1*p2*cos(\u03b81-\u03b82))/(l1^2 * l2*(m1 + m2*sin(\u03b81 - \u03b82)^2))\n    d_p2 = -m2*g*l2*sin(\u03b82) + h1 - h2*sin(2*(\u03b81-\u03b82))\n    d_\u03b82 = (-m2*l2*p1*cos(\u03b81 - \u03b82) + (m1 + m2)*l1*p2) / (m2*l1*l2^2*(m1 + m2*sin(\u03b81-\u03b82)^2))\n\n\n    du .= [d_p1, d_p2, d_\u03b81, d_\u03b82]\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, \u03b8, 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(\u03b8[1]-\u03b8[2]) ) /\n        (2*m2*l1^2*l2^2*(m1+m2*sin(\u03b8[1]-\u03b8[2])^2)) -\n        (m1+m2)*g*l1*cos(\u03b8[1]) - m2*g*l2*cos(\u03b8[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 \u03c3\u00b2 = 0.49\nx = rand(Uniform(-sqrt(3.0), sqrt(3.0)), n, dim) # x generated from Uniform[-\u221a3, \u221a3]\nX = [ones(n) x] # dependent variable matrix with ones\n\u03b2 = Vector(1:1:dim+1) # true coefficients\ny = X*\u03b2 + u # true data generating process\n\n# set prior (normal for \u03b2, InverseGamma for \u03c3\u00b2)\nk = size(X)[2]\n\u03b20 = zeros(k)\n\u03c40 = 0.2\nA0 = \u03c40 * I # Identity matrix\n\u03bd0 = 5.0\n\u03bb0 = 7.0\n# H0 = (\u03bb0 / \u03bd0) * 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\u306e\u5bfe\u89d2\u6210\u5206\nsd0 = diag(sqrt(Matrix(A0, k, k))) # the parameter for conditional prior for \u03b2|\u03c3\u00b2 ~ N_k(\u03b20, \u03c3\u00b2*inv(A0)), (inv(A0) part)\n\n@model function multiple_regression(X, y)    \n    # Set variance priors\n    \u03c3\u00b2 ~ InverseGamma(\u03bd0/2, \u03bb0/2)\n\n    # Set the priors on our coefficients. (No conditions about \u03c3\u00b2)\n    nfeatures = size(X, 2)\n    \u03b2 ~ MvNormal(\u03b20, inv(A0))\n\n    # Write likelihood.\n    y ~ MvNormal(X * \u03b2, \u03c3\u00b2 * 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 MathToolkit\nusing Base.Test\n\n@test recvec([1,2,3,4,5,6,7,8,9,10]) == [1,-2,1]\n@test recvec([0,1,1,2,3,5,8,13], output=Float64) == [1.0,-1.0,-1.0]\n@test recvec([2^k for k=0:7], compute=Int128) == [1,-2]\n@test recvec([1//2^k for k=0:7], compute=Int128, output=Float64) == [2.0,-1.0]\n@test recvec([1]) == []\n@test recvec([1,2,3,4,5,6,7,8,9,10,42]) == []\n@test recvec([BigInt(2)^k + k%16 for k=1:64]) == \n        [1,-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,2]\n\n\n@test abs(transpose([0.75,BigFloat(1)])*pslq([0.75, 1],1e-10))[1] < 1e-10\n@test abs(transpose([0.5,BigFloat(1)])*pslq([0.5, 1],1e-10))[1] < 1e-10\n", "meta": {"hexsha": "20ea2a2737002499e8567e5afde5d2353f9cc8d0", "size": 603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MathToolkit.jl-a6c510a4-1742-563a-9b70-2e3db6ca4e08", "max_stars_repo_head_hexsha": "6b76856a8ff7de4e9803c4084b09356b41c313d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-03-03T19:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T05:58:40.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MathToolkit.jl-a6c510a4-1742-563a-9b70-2e3db6ca4e08", "max_issues_repo_head_hexsha": "6b76856a8ff7de4e9803c4084b09356b41c313d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-04T17:12:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:31:33.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MathToolkit.jl-a6c510a4-1742-563a-9b70-2e3db6ca4e08", "max_forks_repo_head_hexsha": "6b76856a8ff7de4e9803c4084b09356b41c313d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-03-07T04:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:15:19.000Z", "avg_line_length": 37.6875, "max_line_length": 78, "alphanum_fraction": 0.5655058043, "num_tokens": 316, "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*\u03c0*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*\u03c0\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(\u03b1::Real, \u03b2::Real, x::Real) = exp(betalogpdf(\u03b1, \u03b2, x))\n\nbetalogpdf(\u03b1::Real, \u03b2::Real, x::Real) = betalogpdf(promote(\u03b1, \u03b2, x)...)\nfunction betalogpdf(\u03b1::T, \u03b2::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(\u03b1 - 1, y) + xlog1py(\u03b2 - 1, -y) - logbeta(\u03b1, \u03b2)\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": "using JuMP, FactCheck, AmplNLWriter\n\n## Solve test problem with sind and cosd functions\n #\n #  min   (7 - (3*cosd(x1) + 5*cosd(x2)))^2 + (0 - (3*sind(x1) + 5*sind(x2)))^2\n #  s.t.  x1, x2 continuous\n #\n #  The optimal objective value is 0\n ##\n\n# Allow resolving the model from multiple starts after NLP changes in JuMP 0.12\nEnableNLPResolve()\n\nif !isdefined(:solver); solver = CouenneNLSolver(); end\n\nm = Model(solver=solver)\n@variable(m, x[1:2])\n\n@NLobjective(m, Min, (7 - (3*cosd(x[1]) + 5*cosd(x[2])))^2 + (0 - (3*sind(x[1]) + 5*sind(x[2])))^2)\n\ncontext(\"example: jump_nltrig\") do\n    setvalue(x[1], 30)\n    setvalue(x[2], -50)\n    @fact solve(m) --> :Optimal\n    @fact getvalue(x)[:] --> roughly([38.21321, -21.78678], 1e-5)\n    @fact getobjectivevalue(m) --> roughly(0.0, 1e-5)\n    # Now try from the other side\n    setvalue(x[1], -30)\n    setvalue(x[2], 50)\n    @fact solve(m) --> :Optimal\n    @fact getvalue(x)[:] --> roughly([-38.21321, 21.78678], 1e-5)\n    @fact getobjectivevalue(m) --> roughly(0.0, 1e-5)\nend\n", "meta": {"hexsha": "3fef503bb4f1a4ce2983ac775aed48d9c5938ecd", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/jump_nltrig.jl", "max_stars_repo_name": "JuliaPackageMirrors/AmplNLWriter.jl", "max_stars_repo_head_hexsha": "6889d77c3984b02c1c02b6ff2ce583f014f43d81", "max_stars_repo_licenses": ["MIT"], "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/jump_nltrig.jl", "max_issues_repo_name": "JuliaPackageMirrors/AmplNLWriter.jl", "max_issues_repo_head_hexsha": "6889d77c3984b02c1c02b6ff2ce583f014f43d81", "max_issues_repo_licenses": ["MIT"], "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/jump_nltrig.jl", "max_forks_repo_name": "JuliaPackageMirrors/AmplNLWriter.jl", "max_forks_repo_head_hexsha": "6889d77c3984b02c1c02b6ff2ce583f014f43d81", "max_forks_repo_licenses": ["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.0, "max_line_length": 99, "alphanum_fraction": 0.6098039216, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7572955185215379}}
{"text": "@testset \"Single Life\" begin\n    @testset \"issue age 116\" begin\n        t = MortalityTables.table(\"2001 VBT Residual Standard Select and Ultimate - Male Nonsmoker, ANB\")\n        i = Yields.Constant(0.05)\n        lc = LifeContingency(SingleLife(mort = t.ultimate, issue_age = 116), i)\n\n\n        @test l(lc, 0) \u2248 1.0\n        @test l(lc, 1) \u2248 0.200120000000000\n        @test l(lc, 2) \u2248 0.030764447600000\n\n        @test D(lc, 0) \u2248 1.0\n        @test D(lc, 1) \u2248 0.190590476190476\n        @test D(lc, 2) \u2248 0.027904260861678\n\n        @test N(lc, 0) \u2248 1.221415195080500\n        @test N(lc, 1) \u2248 0.221415195080502\n        @test N(lc, 2) \u2248 0.030824718890026\n\n        @test C(lc, 0) \u2248 0.761790476190476000\n        @test C(lc, 1) \u2248 0.153610478367347000\n        @test C(lc, 2) \u2248 0.023794627623916200\n\n        @test M(lc, 0) \u2248 0.9418373716628330\n        @test M(lc, 1) \u2248 0.1800468954723570\n        @test M(lc, 2) \u2248 0.0264364171050101\n\n        @test present_value(Insurance(lc)) \u2248 0.9418373716628330\n        @test present_value(AnnuityDue(lc)) \u2248 1.2214151950805000\n        \n        qs = t.ultimate[116:118]\n        @test present_value(Insurance(lc, n=3)) \u2248 sum(qs .* [1;cumprod(1 .- qs[1:2])] .* [1.05 ^ -t for t in 1:3])\n        @test present_value(AnnuityDue(lc, n=3)) \u2248 sum([1;cumprod(1 .- qs[1:2])] .* [1.05 ^ -t for t in 0:2])\n        \n        @test LifeContingencies.V(lc,1) == reserve_premium_net(lc,1)\n        @test LifeContingencies.v(lc,1) == Yields.discount(lc,1)\n        @test LifeContingencies.A(lc) == present_value(Insurance(lc))\n        @test LifeContingencies.a\u0308(lc) == present_value(AnnuityDue(lc))\n        @test LifeContingencies.a(lc) == present_value(AnnuityImmediate(lc))\n        @test LifeContingencies.P(lc) == premium_net(lc)\n        @test LifeContingencies.\u03c9(lc) == omega(lc)\n    end\n\n    @testset \"issue age 30\" begin\n        t = MortalityTables.table(\"2001 VBT Residual Standard Select and Ultimate - Male Nonsmoker, ANB\")\n        i = Yields.Constant(0.05)\n        life = SingleLife(mort = t.select[30], issue_age = 30)\n        ins = LifeContingency(life, i)\n\n        @test life.issue_age == SingleLife(mort = t.select[30]).issue_age\n        @test life.issue_age == SingleLife(t.select[30]).issue_age\n        @test life.issue_age == SingleLife(t.select,issue_age= 30).issue_age\n\n\n        @test l(ins, 0) \u2248 1.0\n        @test l(ins, 1) \u2248 0.999670000000000\n        @test l(ins, 2) \u2248 0.999210151800000\n\n\n        @test D(ins, 0) \u2248 1.0\n        @test D(ins, 1) \u2248 0.952066666666667\n        @test D(ins, 2) \u2248 0.906313062857143\n\n\n        @test N(ins, 0) \u2248 18.673525637928100\n        @test N(ins, 1) \u2248 17.673525637928100\n        @test N(ins, 2) \u2248 16.721458971261400\n\n        @test C(ins, 0) \u2248 0.000314285714285764\n        @test C(ins, 1) \u2248 0.000417095873015874\n        @test C(ins, 2) \u2248 0.000474735413877510\n\n        @test M(ins, 0) \u2248 0.1107844934319970\n        @test M(ins, 1) \u2248 0.1104702077177110\n        @test M(ins, 2) \u2248 0.1100531118446950\n\n        @test present_value(Insurance(ins)) \u2248 0.1107844934319970\n        @test present_value(AnnuityDue(ins)) \u2248 18.6735256379281000\n        @test premium_net(ins) \u2248 0.0059327036350854\n        @test reserve_premium_net(ins, 1) \u2248 0.0059012862412992\n        @test reserve_premium_net(ins, 2) \u2248 0.0119711961204193\n\n        qs = t.select[30][30:55]\n        @test present_value(Insurance(ins, n=26)) \u2248 sum(qs .* [1;cumprod(1 .- qs[1:25])] .* [1.05 ^ -t for t in 1:26])\n        @test present_value(AnnuityDue(ins, n=26)) \u2248 sum([1;cumprod(1 .- qs[1:25])] .* [1.05 ^ -t for t in 0:25])\n\n        @test premium_net(ins, 26) \u2248 LifeContingencies.A(ins, 26) /  LifeContingencies.a\u0308(ins, 26) \n\n    end\nend", "meta": {"hexsha": "b1eeb4ef173f724e4d2e282a75700efcc8014346", "size": 3636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/single_life.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": "test/single_life.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": "test/single_life.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": 40.4, "max_line_length": 118, "alphanum_fraction": 0.6036853685, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491108, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7572955181268727}}
{"text": "@testset \"Basic Utilities Tests\" begin\n  @testset \"Utils\" begin\n    \u03f5 = log(3); \u03b4 = 0.05\n\n    @test gaussianMechConstant(\u03f5, \u03b4) \u2248 1.7563398731147597 atol=1e-10\n    tmp = gaussianMechConstant2(\u03f5, \u03b4)\n    @test tmp[1] \u2248 1.7563398731147597 atol=1e-10\n    @test tmp[2] \u2248 2.3095249420840473 atol=1e-10\n  end\n\n  @testset \"Basic mechanisms\" begin\n    \u03f5 = log(2); \u03b4 = 0.04\n\n    Random.seed!(12345)  # reseed the RNG\n    D = Random.rand(100)\n    @test gaussianMech(D, Distributions.mean, 2.0/100, \u03f5, \u03b4)[1] == 0.4764940748202759\n    @test laplaceMech(D, Distributions.mean, 2.0/100, \u03f5)[1] == 0.5366973705020675\n    @test mean_dp(D, \u03f5, \u03b4) == 0.47514367413387\n    @test mean_dp(D, \u03f5, 0.0) == 0.4920613726730682\n    @test mean_dp(D, \u03f5) == 0.4886977015049402\n\n    Random.seed!(12345)  # reseed the RNG\n    f(x) = [x[1]^2*x[2], sqrt(x[1]), x[2]^3]\n    x0 = [3, 4]\n    l1sens = 0.5\n    r,a = truncatedLaplaceMech(x0, f, l1sens, \u03f5, \u03b4)\n    @test r[1] == 36.090422106340114\n    @test r[2] == 2.50473361660456\n    @test r[3] == 63.800895516558114\n    @test a == 2.020992083320228\n  end\nend\n", "meta": {"hexsha": "ccae64545163c5dae6cd0b6b8a2621ac9b29060c", "size": 1068, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basics_tests.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": "test/basics_tests.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": "test/basics_tests.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": 32.3636363636, "max_line_length": 85, "alphanum_fraction": 0.6264044944, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.7905303236047048, "lm_q1q2_score": 0.7572586993856226}}
{"text": "@doc raw\"\"\"\n    Euclidean{T<:Tuple,\ud835\udd3d} <: Manifold\n\nEuclidean vector space.\n\n# Constructor\n\n    Euclidean(n)\n\nGenerate the $n$-dimensional vector space $\u211d^n$.\n\n    Euclidean(n\u2081,n\u2082,...,n\u1d62; field=\u211d)\n    \ud835\udd3d^(n\u2081,n\u2082,...,n\u1d62) = Euclidean(n\u2081,n\u2082,...,n\u1d62; field=\ud835\udd3d)\n\nGenerate the vector space of $k = n_1 \\cdot n_2 \\cdot \u2026 \\cdot n_i$ values, i.e. the\nmanifold $\ud835\udd3d^{n_1, n_2, \u2026, n_i}$ whose\nelements are interpreted as $n_1 \u00d7 n_2 \u00d7 \u2026 \u00d7 n_i$ arrays.\nFor $i=2$ we obtain a matrix space.\nThe default `field=\u211d` can also be set to `field=\u2102`.\nThe dimension of this space is $k \\dim_\u211d \ud835\udd3d$, where $\\dim_\u211d \ud835\udd3d$ is the\n[`real_dimension`](@ref) of the field $\ud835\udd3d$.\n\"\"\"\nstruct Euclidean{N,\ud835\udd3d} <: Manifold where {N<:Tuple, \ud835\udd3d<:AbstractNumbers} end\n\nfunction Euclidean(n::Vararg{Int,I}; field::AbstractNumbers = \u211d) where {I}\n    return Euclidean{Tuple{n...},field}()\nend\n\n^(\ud835\udd3d::AbstractNumbers, n) = Euclidean(n...; field = \ud835\udd3d)\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 `\u2102`.\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,\ud835\udd3d}, n::NTuple{N,Int}) where {T,\ud835\udd3d,N}\n    return Euclidean{Tuple{T.parameters...,n...},\ud835\udd3d}()\nend\n\nfunction allocation_promotion_function(\n    M::Euclidean{<:Tuple,\u2102},\n    ::Union{typeof(get_vector),typeof(get_coordinates)},\n    args::Tuple,\n)\n    return complex\nend\n\nfunction check_manifold_point(M::Euclidean{N,\ud835\udd3d}, p) where {N,\ud835\udd3d}\n    if (\ud835\udd3d === \u211d) && !(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 (\ud835\udd3d === \u2102) && !(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,\ud835\udd3d}, p, X; check_base_point = true, kwargs...) where {N,\ud835\udd3d}\n    if check_base_point\n        mpe = check_manifold_point(M, p; kwargs...)\n        mpe === nothing || return mpe\n    end\n    if (\ud835\udd3d === \u211d) && !(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 (\ud835\udd3d === \u2102) && !(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, \u03be::CoTFVector, p, X::TFVector) = copyto!(\u03be, X)\n\nfunction get_basis(M::Euclidean{<:Tuple,\u211d}, 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,\u2102}, 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,\u211d}, 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,\u2102}, 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,\u211d}, 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,\u2102}, 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 $\u221e$.\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 \u00d7 n_2  \u00d7  \u2026  \u00d7 n_i$, i.e.\n\n````math\ng_p(X,Y) = \\sum_{k \u2208 I} \\overline{X}_{k} Y_{k},\n````\nwhere $I$ is the set of vectors $k \u2208 \u2115^i$, such that for all\n$1 \u2264 j \u2264 i$ it holds $1 \u2264 k_j \u2264 n_j$.\n\nFor the special case of $i \u2264 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,\ud835\udd3d}) where {N,\ud835\udd3d}\n    return _product_of_dimensions(M) * real_dimension(\ud835\udd3d)\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, \u03c3)\n\nNormal distribution in ambient space with standard deviation `\u03c3`\nprojected to tangent space at `p`.\n\"\"\"\nfunction normal_tvector_distribution(M::Euclidean{Tuple{N}}, p, \u03c3) where {N}\n    d = Distributions.MvNormal(zero(p), \u03c3)\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, \u03be)\n\nTransform the cotangent vector `\u03be` 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, \u03be::CoTFVector) = copyto!(X, \u03be)\n\nfunction show(io::IO, ::Euclidean{N,\ud835\udd3d}) where {N,\ud835\udd3d}\n    print(io, \"Euclidean($(join(N.parameters, \", \")); field = $(\ud835\udd3d))\")\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, \u03c1)\n\n\u00a76.2: Fisher Model with Homogeneous Consumers. `form` specifies which utility\nfunction consumers use, among `:linear`, `:CES`, `:cobb_douglas`, and `:leontief`. `\u03c1` 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                           \u03c1::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        \u03c1 = 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]) \u2264 supplies[j])\n\n    if form == :linear || \u03c1 > .97\n        if form != :linear\n            @warn \"\u03c1 > .97 tends to fail, so assuming linear\"\n        end\n        # Very bad results if you allow the default scaling \ud83d\udc38\u2615\ufe0f\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 \u2264 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] ^ \u03c1 for j in 1:m) ^ (1 / \u03c1)) for i in 1:n))\n    end\n\n        # Explicit Cobb\u2013Douglas; 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, \u03c1, \u03c00;\n                \u03b7=1e-4, \u03b4=0.5, \u03b1=0.5, verbose=false, maxit=1000, tol=1e-5)\n\n\u00a76.3.1.B: The Discrete Ta\u0302tonnement 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: `\u03c0 .*= exp.(\u03b4 * Z * k ^ -\u03b1)`. This works pretty well.\n\n`\u03b7` is a lower bound on the prices before normalization.\n\"\"\"\nfunction tatonnement(endowments ::AbstractArray{<:AbstractFloat,2},\n                     A          ::AbstractArray{<:AbstractFloat,2},\n                     \u03c1          ::AbstractArray{<:AbstractFloat,1},\n                     \u03c00         ::Union{AbstractArray{<:AbstractFloat,1}, Nothing};\n                     \u03b7          ::AbstractFloat=1e-4,\n                     \u03b4          ::AbstractFloat=0.5,\n                     \u03b1          ::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(\u03c1)\n    @assert all(\u03c1 .< 1)\n    @assert all(0 .< (tol, \u03b7, \u03b4, \u03b1) .< 1)\n\n    if \u03c00 == nothing\n        \u03c00 = rand(m)\n    end\n\n    @assert (m, )  == size(\u03c00)\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    \u03c3 = 1 ./ (1 .- \u03c1)\n    \u03c0_LB = \u03b7 / (4 * n)\n    \u03c0_UB = 1 + \u03c0_LB\n    \u03c0_LB_tight = \u03b7 / (2 * n)\n\n    \u03c0 = copy(\u03c00)\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] ^ \u03c3[i] * sum(\u03c0[k] * W[i, k] for k in 1:m) /\n                       (\u03c0[j] ^ \u03c3[i] * sum((A[i, k] * \u03c0[k] ^ -\u03c1[i]) ^ \u03c3[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.(\u03c0, 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(\u03c0_LB .\u2264 \u03c0 .\u2264 \u03c0_UB)\n            verbose ? println(\"  Step toward equilibrium\") : nothing\n            \u03c0 .*= exp.(\u03b4 * Z * k ^ -\u03b1)\n        else                             # Bottom of p. 144\n            verbose ? println(\"  Regularization step\") : nothing\n            for j in 1:m\n                if \u03c0[j] > 1\n                    \u03c0[j] = 1\n                elseif \u03c0[j] < \u03c0_LB_tight\n                    \u03c0[j] = \u03c0_LB_tight\n                end\n            end\n        end\n    end\n\n    return \u03c0 ./ sum(\u03c0), D\nend\n\n\n\"\"\"\n    exchange(endowments, A, \u03c1=:linear)\n\n\u00a76.4: Convex programs for linear and CES exchange economies. Note that unlike `homogeneousfisher()`,\nhere `\u03c1` is a vector of CES parameters used by each player. Or pass `\u03c1=:linear` for linear model.\n\"\"\"\nfunction exchange(endowments::Array{Float64,2},\n                  A::Array{Float64,2},\n                  \u03c1::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 \u03c1 == :linear\n        # set_optimizer_attribute(model, \"nlp_scaling_method\", \"none\")\n\n        @variable(model, \u03c8[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) \u2265\n                        A[i, j] * sum(endowments[i, k] * exp(\u03c8[k] - \u03c8[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.(\u03c8))\n        demands = value.(X)\n\n    else\n        @assert size(\u03c1) == (n, )                   \"Dim mismatch between A and \u03c1\"\n        @assert all(-1 .\u2264 \u03c1 .< 0)                  \"Need \u03c1 \u2208 [-1, 0)\"\n\n        @variable(model, \u03c3[1:m], lower_bound=0)\n        @NLconstraint(model, Supply[j in 1:m], sum(A[i, j] ^ (1 / (1 - \u03c1[i])) *\n                                               sum(\u03c3[k] ^ 2 * endowments[i, k] for k in 1:m) /\n                                               (\n                                                   \u03c3[j] ^ ((\u03c1[i] - 2) / (1 - \u03c1[i])) *\n                                                   sum(A[i, k] ^ (1 / (1 - \u03c1[i])) * \u03c3[k] ^ ((-2 * \u03c1[i]) / (1 - \u03c1[i]))\n                                                       for k in 1:m)\n                                               )\n                                               for i in 1:n) \u2264 \u03c3[j] * sum(endowments[i, j] for i in 1:n))\n\n        optimize!(model)\n\n        prices = value.(\u03c3) .^ 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 - \u03c1[i])) * sum(prices[k] * endowments[i, k] for k in 1:m) /\n                        (\n                            prices[j] ^ (1 / 1 - \u03c1[i]) *\n                            sum(A[i, k] ^ (1 / (1 - \u03c1[i])) * prices[k] ^ (-\u03c1[i] / (1 - \u03c1[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             \u03c1_consumers, \u03c1_producers, o_producers)\n\n\u00a76.6: Models with production. `\u03c1_consumers` describes\neach consumer's CES utility function, while `\u03c1_producers` describes the CES\nproduction function. Convergence is very iffy, but best when `A_consumers` is\ntall and entries of `\u03c1` 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                    \u03c1_consumers::Array{Float64,1},\n                    \u03c1_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(\u03c1_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(\u03c1_consumers) == (n, )    \"Dim mismatch between A_consumers and \u03c1_consumers\"\n    @assert size(o_producers) == (l, )    \"Dim mismatch between o and \u03c1_producers\"\n    @assert all(0 .< \u03c1_consumers .< 1)    \"Need \u03c1 \u2208 (0, 1)\"\n    @assert all(0 .< \u03c1_producers .< 1)    \"Need \u03c1 \u2208 (0, 1)\"\n\n    A = vcat(A_producers, A_consumers)\n    w = hcat(endowments, zeros(n, l))\n    \u03c1 = vcat(\u03c1_consumers, \u03c1_producers)\n    \u03c3 = 1 ./ (1 .- \u03c1)\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, \u03c8[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(\u03c8[m + i]) * x[m + i] \u2265 # or ==\n                    sum(exp(\u03c8[j]) * w[i, j] for j in 1:m))\n    @NLconstraint(model, ProducerSolvency[k in 1:l + n],                  # 6.11\n                    q[k] \u2264\n                    sum(A[k, j] * x[j] ^ \u03c1[k] for j in 1:m) ^ (1 / \u03c1[k]))\n    @NLconstraint(model, ProducerRationality[k in 1:l + n],               # 6.12\n                    exp(\u03c8[o[k]] * (1 - \u03c3[k])) \u2265\n                    sum(A[k, j] ^ \u03c3[k] * exp(\u03c8[j] * (1 - \u03c3[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) \u2264\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] \u2264 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(\u03c8[j]) * Z[k, j] for j in 1:m) == exp(\u03c8[o[k]]) * q[k])\n\n    optimize!(model)\n    prices = exp.(value.(\u03c8)[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": "# # dempe.mod\tQQR2-MN-4-3\n# # Original AMPL coding by Sven Leyffer\n#\n# # An MPEC from S. Dempe, \"A necessary and sufficient optimality\n# # condition for bilevel programming problems\", Optimization 25,\n# # pp. 341-354, 1992. From book Math. Progr. with Equil. Constr,\n# # by Luo, Pang & Ralph, CUP, 1997, p. 354.\n#\n# # Number of variables:   2 + 1 multipliers\n# # Number of constraints: 2\n# # Nonlinear complementarity constraints\n#\n# var x;\n# var z;\n# var w >= 0;\n#\n# minimize f: (x - 3.5)^2 + (z + 4)^2;\n#\n# subject to\n#     con1:  z - 3 + 2*z*w = 0;\n#     con2:  0 >= z^2 - x     complements  w >= 0;\n#\n# data;\n#\n# # starting point\n# let x := 1;\n# let z := 1;\n# let w := 1;\n#\n#\n# let x :=   0.183193 ;\n# let z := 0.428106;\n# let w := 3.00379;\n\n\nusing JuMP, Complementarity\nusing Ipopt\n\nm = Model(solver=IpoptSolver())\n\n\n@variable(m, x)\n@variable(m, z)\n@variable(m, w>=0)\n\n@NLobjective(m, Min, (x - 3.5)^2 + (z + 4)^2)\n\n@NLconstraint(m, z - 3 + 2*z*w == 0)\n\n@complements(m, 0 >= z^2 - x,  w >= 0, simple)\n\n# setvalue(x, 50)\n# setvalue(z, 50)\n# setvalue(w, 1e5)\n\nsolve(m)\n\n@show getobjectivevalue(m)\n@assert isapprox(getobjectivevalue(m), 28.25, atol=1e-4)\n", "meta": {"hexsha": "4a21026e67cb6a4b74c476406cec69b06ddb0d47", "size": 1157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/mpec/dempe.jl", "max_stars_repo_name": "JuliaPackageMirrors/Complementarity.jl", "max_stars_repo_head_hexsha": "7e9522fb6f9ee0e11d884de5075f76a37385bcab", "max_stars_repo_licenses": ["MIT"], "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/mpec/dempe.jl", "max_issues_repo_name": "JuliaPackageMirrors/Complementarity.jl", "max_issues_repo_head_hexsha": "7e9522fb6f9ee0e11d884de5075f76a37385bcab", "max_issues_repo_licenses": ["MIT"], "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/mpec/dempe.jl", "max_forks_repo_name": "JuliaPackageMirrors/Complementarity.jl", "max_forks_repo_head_hexsha": "7e9522fb6f9ee0e11d884de5075f76a37385bcab", "max_forks_repo_licenses": ["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.2833333333, "max_line_length": 65, "alphanum_fraction": 0.5989628349, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7572244552153045}}
{"text": "function Coherence(B::Array{Float64,2})\n    u=Inf\n    for k=1:size(B,2)\n        for j=1:(k-1)\n            len=(sum(B[:,k].^2).^.5)*(sum(B[:,j].^2).^.5)\n            innerProd=abs(sum(B[:,k].*B[:,j]))\n            u= minimum([u,innerProd/len])\n        end\n    end\n    return u\nend\n\nCoherence(B) = Coherence(convert(Array{Float64,2},B))", "meta": {"hexsha": "6b84b5c271db0d0ae26d445a224c44b82a6a0408", "size": 332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Coherence.jl", "max_stars_repo_name": "dahlend/CompressedSensing", "max_stars_repo_head_hexsha": "cf0ff23ccaa1f768ba3c5ca3c1b2c30bad4a7345", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-05-04T22:01:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T04:09:56.000Z", "max_issues_repo_path": "src/Coherence.jl", "max_issues_repo_name": "tmellan/CompressedSensingJuliaV1", "max_issues_repo_head_hexsha": "9f69baf0f95f330b8f3e85fe4135cc95332efcd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-02-20T14:15:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-22T18:12:37.000Z", "max_forks_repo_path": "src/Coherence.jl", "max_forks_repo_name": "tmellan/CompressedSensingJuliaV1", "max_forks_repo_head_hexsha": "9f69baf0f95f330b8f3e85fe4135cc95332efcd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-04-16T19:00:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:32:12.000Z", "avg_line_length": 25.5384615385, "max_line_length": 57, "alphanum_fraction": 0.5, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091157, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7572244486358432}}
{"text": "\"\"\"\nSmooth jump function ``\\\\Phi_{\\\\omega, T}(t)``\n\n    Returns a planned trajectory.\n\n    smoothjump(t :: Real, T:: Real; \u03c9 = 2.0 :: Real)\n\n`t` : actual time\n\n`T` : final time\n\n`\u03c9` : steepness factor of trajectory\n\"\"\"\nfunction smoothjump(t :: Real, T:: Real; \u03c9 = 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, \u03c9=\u03c9), 0, t)\n        denom, err2 = quadgk(x-> pulsebell(x, T, \u03c9=\u03c9), 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`\u03c9` : steepness factor of trajectory\n\"\"\"\nfunction pulsebell(t :: Real, T:: Real; \u03c9 = 2.0 :: Real)\n\n    if t < 0 || t > T\n        return 0\n    else\n        exp( -1 / ( (1 - t/T)*(t/T))^\u03c9 )\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": "# Tests for the conditional mutual information function\n\n# Test conditional mutual information formula\n@test get_conditional_mutual_information(arr1, arr2, arr3) \u2248 get_entropy(arr1, arr3) + get_entropy(arr2, arr3) - get_entropy(arr1, arr2, arr3) - get_entropy(arr3)\nprintln(\"Conditional mutual information formula passed.\")\n", "meta": {"hexsha": "f493b148fb430f0c396c01c5461a567f3ede2f92", "size": 324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testConditionalMutualInformation.jl", "max_stars_repo_name": "alavendelm/InformationMeasures.jl", "max_stars_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_stars_repo_licenses": ["MIT"], "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/testConditionalMutualInformation.jl", "max_issues_repo_name": "alavendelm/InformationMeasures.jl", "max_issues_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_issues_repo_licenses": ["MIT"], "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/testConditionalMutualInformation.jl", "max_forks_repo_name": "alavendelm/InformationMeasures.jl", "max_forks_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_forks_repo_licenses": ["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.0, "max_line_length": 162, "alphanum_fraction": 0.8024691358, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133464597459, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7572244467610622}}
{"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 .\u2265 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  \u03b1, \u03b2, \u03b3, \u03b4  = p\n  du[1] = (\u03b1 - \u03b2*y)x # dx =\n  du[2] = (\u03b4*x - \u03b3)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    \u03b1 ~ Uniform()\n    \u03b2 ~ Uniform()\n    \u03b3 ~ Uniform()\n    \u03b4 ~ Uniform()\n\n    # p = [2\u03b1+0.5,2\u03b2,3\u03b3+1,2\u03b4]\n    p = [20\u03b1+0.5,20\u03b2,30\u03b3+1,20\u03b4]\n    prob = remake(ode, p=p)\n    predicted = solve(prob,Tsit5(),saveat=0.1)\n        \n    data ~ For(Array(predicted)) do \u03bb Poisson(\u03bb) 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.\u03b1 + 0.5,2 * x.\u03b2,3 * x.\u03b3 + 1,2 * x.\u03b4]\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": "using ProgressMeter, Plots, StatsBase, Statistics, LaTeXStrings, JLD\n\nfunction TRW_CD(L,P,X0)\n    surf = zeros(L+2); surf[X0] = 1.0\n    TimePassed = 0\n    while surf[1] + surf[end] < 0.99\n        Altsurf = copy(surf)\n        for i \u2208 2:L+1\n            Altsurf[i+1] += surf[i]*(1-P)\n            Altsurf[i-1] += surf[i]*P\n            Altsurf[i] -= surf[i]\n        end\n        surf = Altsurf\n        TimePassed += 1\n    end\n    return TimePassed\nend\n\nL = 40\nPList = hcat(0:0.01:1)\nX0List = hcat(1:L+2)\n\nData = zeros(length(X0List),length(PList))\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        Data[i,j] = mean(TRW_CD(L,P,X0))\n    end\nend\n\nsave(\"../../Data/Q6/Q6-LT.jld\", \"Data\", Data)\nData = load(\"../../Data/Q6/Q6-LT.jld\")[\"Data\"]\n\nP1 = heatmap(0:0.01:1, 1:L+2,Data, xaxis=nothing,legend = nothing,title = L\"Life\\ time\")\nP2 = contour(0:0.01:1, 1:L+2,Data, fill = true ,legend = nothing,xlabel = L\"P\")\nP3 = plot(P1,P2,layout = (2,1),ylabel = L\"X_{init}\",link = :y)\nCBar = heatmap((0:1650).*ones(1651,1),xlabel =\"\",legend=:none, xticks=:none, yticks=(1:165:1651, string.(0:165:1651)))\n\nplot([P3]...,CBar,layout = @layout[grid(1,1) a{0.04w}], size = (600,500))\nsavefig(\"../../Figs/Q6/Q6-LT.pdf\")\n\nX0List[21]\n\n\nX0Plot = []\nfor X0 in [11,21,31]\n    PLT = begin\n        plot(PList,Data[X0,:,1], c = :black,linewidth = 3)\n        plot!(PList,Data[X0,:,1], linewidth = 2, c = :purple, fill = (0, 0.5))\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], c = :black, linewidth = 3)\n        plot!(X0List,Data[:,P], linewidth = 2, c = :steelblue,  fill = (0, 0.5))\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/Q6/Q6-scat.pdf\")\n", "meta": {"hexsha": "81d47c7a43b22e8fa528bac23ba3acefee98d82a", "size": 2252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet4/Codes/Q6/Q6-TRW-Census.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/Q6/Q6-TRW-Census.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/Q6/Q6-TRW-Census.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": 29.6315789474, "max_line_length": 123, "alphanum_fraction": 0.5634991119, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7571893286689603}}
{"text": "# ---\n# title: 813. Largest Sum of Averages\n# id: problem813\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Dynamic Programming\n# link: <https://leetcode.com/problems/largest-sum-of-averages/description/>\n# hidden: true\n# ---\n# \n# We partition a row of numbers `A` into at most `K` adjacent (non-empty)\n# groups, then our score is the sum of the average of each group. What is the\n# largest score we can achieve?\n# \n# Note that our partition must use every number in A, and that scores are not\n# necessarily integers.\n# \n#     \n#     \n#     **Example:**\n#     Input: \n#     A = [9,1,2,3,9]\n#     K = 3\n#     Output: 20\n#     Explanation: \n#     The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\n#     We could have also partitioned A into [9, 1], [2], [3, 9], for example.\n#     That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n#     \n# \n# \n# \n# **Note:**\n# \n#   * `1 <= A.length <= 100`.\n#   * `1 <= A[i] <= 10000`.\n#   * `1 <= K <= A.length`.\n#   * Answers within `10^-6` of the correct answer will be accepted as correct.\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "51bd416b26c12d30eab88ac236dd63e82f37749d", "size": 1207, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/813.largest-sum-of-averages.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/813.largest-sum-of-averages.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/813.largest-sum-of-averages.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.6808510638, "max_line_length": 109, "alphanum_fraction": 0.594034797, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7571893215529506}}
{"text": "# ---\n# title: 307. Range Sum Query - Mutable\n# id: problem307\n# author: zhwang\n# date: 2022-03-12\n# difficulty: Medium\n# categories: Binary Indexed Tree, Segment Tree\n# link: <https://leetcode.com/problems/range-sum-query-mutable/description/>\n# hidden: true\n# ---\n# \n# Given an integer array _nums_ , find the sum of the elements between indices\n# _i_ and _j_ ( _i_ \u2264 _j_ ), inclusive.\n# \n# The _update(i, val)_ function modifies _nums_ by updating the element at index\n# _i_ to _val_.\n# \n# **Example:**\n# \n#     \n#     \n#     Given nums = [1, 3, 5]\n#     \n#     sumRange(0, 2) -> 9\n#     update(1, 2)\n#     sumRange(0, 2) -> 8\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * The array is only modifiable by the _update_ function.\n#   * You may assume the number of calls to _update_ and _sumRange_ function is distributed evenly.\n#   * `0 <= i <= j <= nums.length - 1`\n# \n# \n## @lc code=start\nusing LeetCode\n\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## @lc code=end\n\n## @lc test=start\n@testset \"307.range-sum-query-mutable.jl\" begin\n    @testset \"307 case 1\" begin\n        ST = SegmentTree([1, 3, 5])\n        @test sum_range(ST, 1, 3) == 9\n        update!(ST, 2, 2)\n        @test sum_range(ST, 1, 3) == 8\n    end\nend\n## @lc test=end\n\n## @lc info=start\n# link: [solution to 307]()\n## @lc info=end", "meta": {"hexsha": "b0667319f3db0017c2ef0bd1c85e1cfbf0533d79", "size": 2259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/submited/date-04/04-01/307.range-sum-query-mutable.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-04/04-01/307.range-sum-query-mutable.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-04/04-01/307.range-sum-query-mutable.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": 23.0510204082, "max_line_length": 99, "alphanum_fraction": 0.5582115981, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.7571893122051964}}
{"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": "export Xcorr\n#TODO make more efficient\n\n\"\"\"\n`Xcorr([domainType=Float64::Type,] dim_in::Tuple, h::AbstractVector)`\n\n`Xcorr(x::AbstractVector, h::AbstractVector)`\n\nCreates a `LinearOperator` which, when multiplied with an array `x::AbstractVector`, returns the cross correlation between `x` and `h`. Uses `xcross`. \n\n\"\"\"\nstruct Xcorr{T,H <:AbstractVector{T}} <: LinearOperator\n\tdim_in::Tuple{Int}\n\th::H\nend\n\n# Constructors\nfunction Xcorr(DomainType::Type, DomainDim::NTuple{N,Int},  h::H) where {H<:AbstractVector, N} \n\teltype(h) != DomainType && error(\"eltype(h) is $(eltype(h)), should be $(DomainType)\")\n\tN != 1 && error(\"Xcorr treats only SISO, check Filt and MIMOFilt for MIMO\")\n\tXcorr{DomainType,H}(DomainDim,h)\nend\nXcorr(x::H, h::H) where {H} = Xcorr(eltype(x), size(x), h)\n\n# Mappings\n\nfunction mul!(y::H,A::Xcorr{T,H},b::H) where {T,H}\n\ty .= xcorr(b,A.h)\nend\n\nfunction mul!(y::H,L::AdjointOperator{Xcorr{T,H}},b::H) where {T,H}\n    A = L.A\n\tl =floor(Int64,size(A,1)[1]/2)\n\tidx = l+1:l+length(y)\n\ty .= conv(b,A.h)[idx]\nend\n\n# Properties\n\ndomainType(L::Xcorr{T}) where {T} = T\ncodomainType(L::Xcorr{T}) where {T} = T\n\n#TODO find out a way to verify this, \nis_full_row_rank(L::Xcorr)    = true\nis_full_column_rank(L::Xcorr) = true\n\nsize(L::Xcorr) = ( 2*max(L.dim_in[1], length(L.h))-1, ), L.dim_in\n\nfun_name(A::Xcorr)  = \"\u25ce\"\n", "meta": {"hexsha": "042392ca920166150663119449ac23806551cc1b", "size": 1329, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearoperators/Xcorr.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractOperators.jl-d9c5613a-d543-52d8-9afd-8f241a8c3f1c", "max_stars_repo_head_hexsha": "4d9cf0b281ba8d6a8dd971263fc7c2f601fda78c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linearoperators/Xcorr.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractOperators.jl-d9c5613a-d543-52d8-9afd-8f241a8c3f1c", "max_issues_repo_head_hexsha": "4d9cf0b281ba8d6a8dd971263fc7c2f601fda78c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linearoperators/Xcorr.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractOperators.jl-d9c5613a-d543-52d8-9afd-8f241a8c3f1c", "max_forks_repo_head_hexsha": "4d9cf0b281ba8d6a8dd971263fc7c2f601fda78c", "max_forks_repo_licenses": ["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.58, "max_line_length": 151, "alphanum_fraction": 0.6659142212, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.757180542710188}}
{"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 \u21a6 0 if <a,x> \u2a7d b, +\u221e 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    \u03b8 = \u03c0/3\n    add_constraint!(problem, \"ineq_rot\", real(z*exp(-im*\u03b8)) >> 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    \u03b81 = \u03c0/3\n    add_constraint!(problem, \"eq_rot1\", (cos(\u03b81)*x1+sin(\u03b81)*x2) == 0)\n    # \u03b82 = -\u03c0/3\n    # add_constraint!(problem, \"ineq_rot2\", (cos(\u03b82)*x1+sin(\u03b82)*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*\u00b2 = x2*\u00b2 = 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_\u03b8_\u03d5_for_all_m_n\nexport \u03c0\u2098\u2099_\u03c4\u2098\u2099_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, \u03b8, \u03d5 in one call\n# This should be more stable and faster, as it employs recurrence relations in calculating \u03c0\u2098\u2099 and \u03c4\u2098\u2099\n# using recurrence relations in calculating \u03c0\u2098\u2099 and \u03c4\u2098\u2099\n\n#############################################################################################\n# calculate \u03c0(\u03b8) and \u03c4(\u03b8) using recurrence relations\nfunction \u03c0\u2098\u2099_\u03c4\u2098\u2099_all_all_m_n(n_max::I, \u03b8::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 \u03c0\u2098\u2099 with recurrence relation\n    \u03c0\u2098\u2099_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        \u03c0\u2098\u2099_all[single_index_from_m_n(m, n)] = m * A[m] * sin(\u03b8)^(m - 1)\n        if verbose; println(\"m=$m, n=$n, \u03c0\u2098\u2099_all=$(\u03c0\u2098\u2099_all[single_index_from_m_n(m, n)])\"); end\n\n        # calculate \u03c0\u208b\u2098\u2099 from \u03c0\u2098\u2099\n        if m != 0\n            \u03c0\u2098\u2099_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * \u03c0\u2098\u2099_all[single_index_from_m_n(m, n)]\n            if verbose; println(\"m=$(-m), n=$n, \u03c0\u2098\u2099_all=$(\u03c0\u2098\u2099_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                \u03c0\u2098\u2099_all[single_index_from_m_n(m, n)] = 1 / sqrt(n^2 - m^2) * ((2n - 1) * cos(\u03b8) * \u03c0\u2098\u2099_all[single_index_from_m_n(m, n - 1)])\n                if verbose; println(\"m=$m, n=$n, \u03c0\u2098\u2099_all=$(\u03c0\u2098\u2099_all[single_index_from_m_n(m, n)])\"); end\n            else\n                \u03c0\u2098\u2099_all[single_index_from_m_n(m, n)] = 1 / sqrt(n^2 - m^2) * ((2n - 1) * cos(\u03b8) * \u03c0\u2098\u2099_all[single_index_from_m_n(m, n - 1)]) - sqrt((n - 1)^2 - m^2) * \u03c0\u2098\u2099_all[single_index_from_m_n(m, n - 2)]\n                if verbose; println(\"m=$m, n=$n, \u03c0\u2098\u2099_all=$(\u03c0\u2098\u2099_all[single_index_from_m_n(m, n)])\"); end\n            end\n\n            # calculate \u03c0\u208b\u2098\u2099 from \u03c0\u2098\u2099\n            if m != 0\n                \u03c0\u2098\u2099_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * \u03c0\u2098\u2099_all[single_index_from_m_n(m, n)]\n                if verbose; println(\"m=$(-m), n=$n, \u03c0\u2098\u2099_all=$(\u03c0\u2098\u2099_all[single_index_from_m_n(-m, n)])\"); end\n            end\n        end\n    end\n    \u03c4\u2098\u2099_all = 0 # TODO: add the code for it\n    return \u03c0\u2098\u2099_all, \u03c4\u2098\u2099_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\u2099(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\u2099(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\u1d50\u2099(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\u1d50\u2099(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_\u2202wignerd_for_all_s(s_max::I, m::I, n::I, \u03b8::R; get_derivatives=true, verbose=false) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate d\u02e2\u2098\u2099(\u03b8) and \u2202(d\u02e2\u2098\u2099(\u03b8))/\u2202\u03b8 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 \u03be from eq. B.16\n    if n >= m\n        \u03be_mn = 1\n    else\n        \u03be_mn = (-1)^(m - n)\n    end\n\n    x = cos(\u03b8)\n\n    # calculate d^s_min__m_n(\u03b8) from eq. B.24\n    d_smin_m_n =\n        \u03be_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 \u2202(d\u02e2\u2098\u2099(\u03b8))/\u2202\u03b8\n    if get_derivatives\n        \u2202d_\u2202\u03b8 = SortedDict(\n            s_min - 1 => 0.0,\n            s_min   => 0.0\n        )\n\n        sin_theta = sin(\u03b8)\n\n        for s = s_min:s_max\n            if verbose; println(\"s=$s\"); end\n            \u2202d_\u2202\u03b8[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, \u2202d_\u2202\u03b8\n    else\n        return d\n    end\n\n\nend\n\n#############################################################################################\n# calculate \u03c0(\u03b8) and \u03c4(\u03b8) using Wigner-d that was calculated using recurrence relations\nfunction \u03c0\u2098\u2099_\u03c4\u2098\u2099_all_all_m_n_using_wigner(n_max::I, \u03b8::R; verbose=false) where {R <: Real, I <: Integer}\n    \u03c0\u2098\u2099_all = zeros(get_max_single_index_from_n_max(n_max))\n    \u03c4\u2098\u2099_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, \u2202d_\u2202\u03b8_rec_all_n  = wignerd_and_\u2202wignerd_for_all_s(n_max, 0, m, \u03b8)\n        for n = m:n_max\n            if n != 0\n                if verbose; println(\"m=$m, n=$n, calculate \u03c0\u2098\u2099_all, \u03c4\u2098\u2099_all\"); end\n                \u03c0\u2098\u2099_all[single_index_from_m_n(m, n)] = m / sin(\u03b8) * d_rec_all_n[n]\n                \u03c4\u2098\u2099_all[single_index_from_m_n(m, n)] = \u2202d_\u2202\u03b8_rec_all_n[n]\n\n                if m != 0\n                    \u03c0\u2098\u2099_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * \u03c0\u2098\u2099_all[single_index_from_m_n(m, n)]\n                    \u03c4\u2098\u2099_all[single_index_from_m_n(-m, n)] = (-1)^(m)   * \u03c4\u2098\u2099_all[single_index_from_m_n(m, n)]\n                end\n            end\n        end\n    end\n    return \u03c0\u2098\u2099_all, \u03c4\u2098\u2099_all\nend\n\nfunction B_C_mn_of_\u03b8_for_all_m_n(n_max::I, \u03b8::R) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate B\u2099\u2098(\u03b8), C\u2099\u2098(\u03b8), P\u2099\u2098(\u03b8) 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    \u03c0\u2098\u2099_all, \u03c4\u2098\u2099_all = \u03c0\u2098\u2099_\u03c4\u2098\u2099_all_all_m_n_using_wigner(n_max, \u03b8)\n    B = (_ -> zero(SVector{3,Complex})).(\u03c0\u2098\u2099_all)\n    C = (_ -> zero(SVector{3,Complex})).(\u03c0\u2098\u2099_all)\n    for idx in eachindex(\u03c0\u2098\u2099_all)\n        B[idx] = [0,      \u03c4\u2098\u2099_all[idx], im * \u03c0\u2098\u2099_all[idx] ]\n        C[idx] = [0, im * \u03c0\u2098\u2099_all[idx], -1 * \u03c4\u2098\u2099_all[idx] ]\n    end\n\n    return B, C\nend\n\nfunction P_mn_of_\u03b8_for_all_m_n(n_max::I, \u03b8::R) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate P\u2099\u2098(\u03b8) 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_\u2202wignerd_for_all_s(n_max, 0, m, \u03b8; 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_\u03b8_\u03d5_for_all_m_n(n_max::I, \u03b8::R, \u03d5::R) where {R <: Real, I <: Integer}\n    \"\"\"\n    Calculate B\u2099\u2098(\u03b8,\u03d5), C\u2099\u2098(\u03b8,\u03d5), P\u2099\u2098(\u03b8,\u03d5) for all m and n\n    \"\"\"\n    B_of_\u03b8, C_of_\u03b8 = B_C_mn_of_\u03b8_for_all_m_n(n_max, \u03b8)\n    P_of_\u03b8 = P_mn_of_\u03b8_for_all_m_n(n_max, \u03b8)\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 * \u03d5)\n            B_of_\u03b8[single_index_from_m_n(m, n)] *= factor\n            C_of_\u03b8[single_index_from_m_n(m, n)] *= factor\n            P_of_\u03b8[single_index_from_m_n(m, n)] *= factor\n        end\n    end\n\n    return B_of_\u03b8, C_of_\u03b8, P_of_\u03b8\nend\n\nfunction M_N_wave_all_m_n(n_max::I, kr::NN, \u03b8::R, \u03d5::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_\u03b8_\u03d5, C_of_\u03b8_\u03d5, P_of_\u03b8_\u03d5  = B_C_P_mn_of_\u03b8_\u03d5_for_all_m_n(n_max, \u03b8, \u03d5)\n\n    M = 0 .* B_of_\u03b8_\u03d5\n    N = 0 .* B_of_\u03b8_\u03d5\n\n    for n = 1:n_max\n        for m = -n:n\n            M[single_index_from_m_n(m, n)] = convert(R, \u03b3_mn(m, n)) * radial_function(n, kr) * C_of_\u03b8_\u03d5[single_index_from_m_n(m, n)]\n            N[single_index_from_m_n(m, n)] = convert(R, \u03b3_mn(m, n)) * (\n                n * (n + 1) / kr * radial_function(n, kr)    * P_of_\u03b8_\u03d5[single_index_from_m_n(m, n)]\n                + (radial_function_special_derivative(n, kr) * B_of_\u03b8_\u03d5[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": "using jInv.Mesh\nusing Test\n\n# setup 3D problem\nnc = [5, 7, 8]\nx0 = rand(3)\ndomain = [x0[1], 4, x0[2], 2, x0[3], 6]\nh   = (domain[2:2:end]-domain[1:2:end])./nc\nh1  = h[1]*ones(nc[1])\nh2  = h[2]*ones(nc[2])\nh3  = h[3]*ones(nc[3])\n\nMt = getTensorMesh3D(h1,h2,h3,x0)\nMr = getRegularMesh(domain,nc)\nM2D = getRegularMesh(domain[1:4],nc[1:2])\nMt2 = getTensorMesh3D(h1+rand(nc[1]),h2+rand(nc[2]),h3+rand(nc[3]),x0)\n\nMeshes = (Mt,Mr,Mt2,M2D)\n\nfor k=1:length(Meshes)\n\tM = Meshes[k]\n\tprint(\"\\ttesting nodal averaging for $(typeof(M))...\")\n\tAv = getNodalAverageMatrix(M)\n\txn = getNodalGrid(M)\n\txc = getCellCenteredGrid(M)\n\t@test norm(Av*xn-xc,Inf)<1e-12\n\t\n\tprint(\"passed!\\n\")\nend\n\n\n\n", "meta": {"hexsha": "0367e428b946eaf3c1de5f76b77a519205e9d3b5", "size": 671, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Mesh/testAvgOps.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": "test/Mesh/testAvgOps.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": "test/Mesh/testAvgOps.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.3333333333, "max_line_length": 70, "alphanum_fraction": 0.6318926975, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7571554281588002}}
{"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": "using CSV, DataFrames, StatsPlots, StanSample, Statistics\n\nProjDir = @__DIR__\n\nold_df = CSV.read(joinpath(ProjDir, \"data\", \"data_final.csv\"), delim=' ')\n\ndf = DataFrame()\nfor row in eachrow(old_df)\n\tvals = split(row[1], \"\\t\")\n\tyr = Meta.parse(row[1][1:4])\n\twk = Meta.parse(row[1][5:6])\n\ts = Meta.parse(vals[2])\n\tp = Meta.parse(vals[3])\n\tq = Meta.parse(vals[4])\n\tappend!(df, DataFrame(year=yr, week=wk, store=s, quantity=q, price=p))\nend\n\ndf[!, :ppu] = df[:, :price] ./ df[:, :quantity]\ndf[!, :ppu_l] = log.(df[:, :ppu])\ndf[!, :quantity_l] = log.(df[:, :quantity])\n\n# Clean up\n\ndf = df[df.ppu_l .> 0.04, :]\ndf = df[df.quantity_l .> 0.0, :]\n\nCSV.write(joinpath(ProjDir, \"data\", \"data.csv\"), df)\n\np1 = scatter(df[:, :ppu], df[:, :quantity],\n\txlabel=\"ppu\", ylabel=\"quantity sold\")\np2 = scatter(df[:, :ppu_l], df[:, :quantity_l],\n\txlabel=\"log(ppu)\", ylabel=\"log(quantity sold)\")\nplot(p1, p2, layout=(2, 1))\nsavefig(joinpath(ProjDir, \"plots\", \"data.png\"))\n\nbglm = \"\ndata {\n  int<lower=0> N;\n  vector[N] q; // Outcome\n  vector[N] p; // Predictor\n}\nparameters {\n  real<lower=0> a;\n  real b;\n  real<lower=0> sigma;\n}\nmodel {\n  vector[N] mu;            \t\t// mu is a vector\n  a ~ normal(2.0, 10.0);\t\t// intercept positive\n  b ~ normal(-2.0, 10.0);\t\t// demand drops as price increases\n  sigma ~ uniform(0, 15);\n  mu = a + b * p;\n  q ~ normal(mu, sigma);\n}\n\";\n\ndata = Dict(\n  :N => size(df, 1),\n  :q => df[:, :quantity_l],\n  :p => df[:, :ppu_l]\n)\n\nsm = SampleModel(\"bglm\", bglm)\n\nrc = stan_sample(sm, data=data)\n\nif success(rc)\n\tchns = read_samples(sm)\n\tplot(chns)\n\tsavefig(joinpath(ProjDir, \"plots\", \"chains.png\"))\n\n\tdfs = DataFrame(chns)\n\tshow(chns)\n\n\tp = 0.6:0.01:2.0\n\tp1 = scatter(df[:, :ppu_l], df[:, :quantity_l],\n\t\txlabel=\"ppu_l\", ylabel=\"quantity_l sold\")\n\ta_mean = mean(dfs[:, :a])\n\tb_mean = mean(dfs[:, :b])\n\tmu_q = a_mean .+ b_mean .* p\n\tplot!(p1, p, mu_q)\n\tsavefig(joinpath(ProjDir, \"plots\", \"regression.png\"))\n\n\tprice_points_l = [1.05, 1.35, 1.5, 1,6, 1.78]\n\tscatter(price_points_l, a_mean .+ b_mean .* price_points_l,\n\t\txlims = (0.6, 2.0), ylims= (0, 7), leg=false,\n\t\txlabel=\"log(ppu)\", ylabel=\"log(quantity sold)\")\n\tfor row in eachrow(dfs)\n\t\tplot!(p, row[:a] .+ row[:b] .* p, color=:gray)\n\tend\n\tscatter!(price_points_l, a_mean .+ b_mean .* price_points_l)\n\tsavefig(joinpath(ProjDir, \"plots\", \"sampling.png\"))\nend\n", "meta": {"hexsha": "18ebe6fee27498ca6c0a51f4c5feadf01b0c2b73", "size": 2315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "approaches/bayesian_glm_01/bglm_01.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/bayesian_glm_01/bglm_01.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/bayesian_glm_01/bglm_01.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": 24.6276595745, "max_line_length": 73, "alphanum_fraction": 0.6095032397, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7570632710380139}}
{"text": "@testset \"Prim\" begin\n    g4 = CompleteGraph(4)\n\n    distmx = [\n      0  1  5  6\n      1  0  4  10\n      5  4  0  3\n      6  10  3  0\n    ]\n\n    vec_mst = Vector{Edge}([Edge(1, 2), Edge(2, 3), Edge(3, 4)])\n    for g in testgraphs(g4)\n        # Testing Prim's algorithm\n        mst = @inferred(prim_mst(g, distmx))\n        @test mst == vec_mst\n    end\n\n    #second test\n    distmx_sec = [\n        0       0       0.26    0       0.38    0       0.58    0.16\n        0       0       0.36    0.29    0       0.32    0       0.19\n        0.26    0.36    0       0.17    0       0       0.4     0.34\n        0       0.29    0.17    0       0       0       0.52    0\n        0.38    0       0       0       0       0.35    0.93    0.37\n        0       0.32    0       0       0.35    0       0       0.28\n        0.58    0       0.4     0.52    0.93    0       0       0\n        0.16    0.19    0.34    0       0.37    0.28    0       0\n    ]\n\n    vec2 = Vector{Edge}([Edge(8, 2), Edge(1, 3), Edge(3, 4), Edge(6, 5), Edge(8, 6), Edge(3, 7), Edge(1, 8)])\n    gx = SimpleGraph(distmx_sec)\n    for g in testgraphs(gx)\n        mst2 = @inferred(prim_mst(g, distmx_sec))\n        @test mst2 == vec2\n    end\n\n    \n    # Third test: Example from\n    #   https://en.wikipedia.org/wiki/Kruskal%27s_algorithm#Example\n    # Adapted from networkx\n    #   https://github.com/networkx/networkx/blob/master/networkx/algorithms/tree/tests/test_mst.py\n    edges_w = [(0, 1, 7), (0, 3, 5), (1, 2, 8), (1, 3, 9), (1, 4, 7),\n               (2, 4, 5), (3, 4, 15), (3, 5, 6), (4, 5, 8), (4, 6, 9),\n               (5, 6, 11)]\n    n = 7\n\n    if false    # verify the example, visually\n        for e in edges_w\n            println(\"$('A' + e[1]) -- $('A' + e[2]): $(e[3])\")\n        end\n    end\n\n    gx = LightGraphs.SimpleGraph([Edge(e[1]+1, e[2]+1) for e in edges_w])\n\n    @test nv(gx) == n\n    @test ne(gx) == length(edges_w)\n\n    distmx3 = zeros(Float64, n, n)\n    for e in edges_w\n        distmx3[e[1]+1, e[2]+1] = e[3]\n        distmx3[e[2]+1, e[1]+1] = e[3]\n    end\n    mst3 = @inferred(prim_mst(gx, distmx3))\n\n    expected3 = [Edge(e[1]+1, e[2]+1)\n                 for e in [(0, 1, 7),\n                           (0, 3, 5),\n                           (1, 4, 7),\n                           (2, 4, 5),\n                           (3, 5, 6),\n                           (4, 6, 9)]]\n\n    \"\"\"\n    The cost of the edge selection `es` given the distance matrix `distmx`\n    \"\"\"\n    edge_costs(es, distmx) =\n        sum(distmx[e.src, e.dst] for e in es)\n\n    @test edge_costs(mst3, distmx3) == edge_costs(expected3, distmx3)\n\n    # maximum spanning tree\n    mst3n = @inferred(prim_mst(gx, -distmx3))\n    expected3n = [Edge(e[1]+1, e[2]+1)\n                  for e in [(0, 1, 7),\n                            (1, 2, 8),\n                            (1, 3, 9),\n                            (3, 4, 15),\n                            (4, 6, 9),\n                            (5, 6, 11)]]\n    @test edge_costs(mst3n, distmx3) == edge_costs(expected3n, distmx3)\nend\n", "meta": {"hexsha": "7b95df423676cc68f758a4ed35c9fd99e5e1b456", "size": 3015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/spanningtrees/prim.jl", "max_stars_repo_name": "EQt/LightGraphs.jl", "max_stars_repo_head_hexsha": "763726bcf7ad3a9a0165a9861ea30b3a352e5925", "max_stars_repo_licenses": ["MIT"], "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/spanningtrees/prim.jl", "max_issues_repo_name": "EQt/LightGraphs.jl", "max_issues_repo_head_hexsha": "763726bcf7ad3a9a0165a9861ea30b3a352e5925", "max_issues_repo_licenses": ["MIT"], "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/spanningtrees/prim.jl", "max_forks_repo_name": "EQt/LightGraphs.jl", "max_forks_repo_head_hexsha": "763726bcf7ad3a9a0165a9861ea30b3a352e5925", "max_forks_repo_licenses": ["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.7717391304, "max_line_length": 109, "alphanum_fraction": 0.4155887231, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7570632668074584}}
{"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 \u03a3 so that x \u2286 \u03a3, 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 \u27e8A\u27e9 of the given matrix A according to the definition\n\u27e8A\u27e9_ii = mig(A_ii)\n\u27e8A\u27e9_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": "# Find the slope of two point\nfind_slope(x1, y1, x2, y2) = (y2 - y1) / (x2 - x1)\n\n# Find the closest whole numbers on both sides of a x\nneighbors(x) = round(x), ceil(x)\n\n# Find the predicted value of y given a value x\nfunction find_y(x, known_x)\n    # Check if the given value is exactly one in the known list\n    if round(x) == x\n        return known_x[x]\n    end\n\n    left_x, right_x = neighbors(x)\n\n    left_y = known_x[left_x]\n    right_y = known_x[right_x]\n\n    slope = find_slope(left_x, left_y, right_x, right_y)\n\n    return left_y + (slope * (x - left_x))\nend\n\nprintln(find_slope(2, 3, 5, 6))\nprintln(neighbors(4.5))\nprintln(find_y(2, [3, 4, 5, 9]))\n", "meta": {"hexsha": "b46fb4545dedd1a8a4243324a68ffca896a19c6e", "size": 658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "main.jl", "max_stars_repo_name": "JakeRoggenbuck/colorgradient-julia", "max_stars_repo_head_hexsha": "14568a5025c467b936be2ea77def74848c7bc095", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-11T11:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:00:02.000Z", "max_issues_repo_path": "main.jl", "max_issues_repo_name": "JakeRoggenbuck/colorgradient-julia", "max_issues_repo_head_hexsha": "14568a5025c467b936be2ea77def74848c7bc095", "max_issues_repo_licenses": ["MIT"], "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": "JakeRoggenbuck/colorgradient-julia", "max_forks_repo_head_hexsha": "14568a5025c467b936be2ea77def74848c7bc095", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-15T06:16:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T06:16:33.000Z", "avg_line_length": 24.3703703704, "max_line_length": 63, "alphanum_fraction": 0.6504559271, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7569966969173396}}
{"text": "#=\n\n    deterministic.jl\n\n    Contains code to solve the deterministic ODE model\n\n           \u03b2     \u03bb    p\u03b2\n        T --\u2192 S --\u2192 E --\u2192 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,[\u03bb,\u03b2,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,\u03b8::Vector)\n    \u03bb,\u03b2,p = \u03b8\n    A = (exp(-t*\u03b2)*(exp(-t*((-1+p)*\u03b2+\u03bb))*(-1+p)*p*\u03b2^3*\u03bb-(-1+p)*(\u03b2-\u03bb)*\u03bb*(p*\u03b2+\u03bb)^2+exp(t*\u03b2)*((-1+p)*\u03b2+\u03bb)*(\u03bb^2*(\u03b2+\u03bb)+p^2*\u03b2*(-\u03bb^2+\u03b2^2*(1+t*\u03bb)+\u03b2*\u03bb*(1+t*\u03bb))+p*\u03bb*(-\u03bb^2+\u03b2^2*(1+t*\u03bb)+\u03b2*\u03bb*(1+t*\u03bb)))))/((\u03b2+\u03bb)*((-1+p)*\u03b2+\u03bb)*(p*\u03b2+\u03bb)^2)\n    S = (exp(-t*(p*\u03b2+\u03bb))*\u03b2*((-1+p)*\u03b2*\u03bb+exp(t*(p*\u03b2+\u03bb))*p*(\u03b2+\u03bb)*((-1+p)*\u03b2+\u03bb)-exp(t*((-1+p)*\u03b2+\u03bb))*(-1+p)*\u03bb*(p*\u03b2+\u03bb)))/((\u03b2+\u03bb)*((-1+p)*\u03b2+\u03bb)*(p*\u03b2+\u03bb))\n    I = A - S\n    return [A,I]\nend\nsolve_ode_model(t,\u03bb,\u03b2,p) = solve_ode_model(t,[\u03bb,\u03b2,p])\n\n\n\"\"\"\n    solve_ode_model_all_vars(t,[\u03bb,\u03b2,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,\u03b8::Vector)\n    \u03bb,\u03b2,p = \u03b8\n    M = [-\u03b2 0 0 0; \u03b2 -\u03bb p*\u03b2 0; 0 \u03bb -p*\u03b2 0; 0 0 p*\u03b2 0]\n    x\u2080 = [\u03bb/(\u03bb+\u03b2),\u03b2/(\u03bb+\u03b2),0,0]\n    return exp(M*t) * x\u2080\nend\nsolve_ode_model_all_vars(t,\u03bb,\u03b2,p) = solve_ode_model_all_vars(t,[\u03bb,\u03b2,p])\n\n\n\"\"\"\n    solve_alt_ode_model(t,[\u03b3,\u03bb,\u03b2,p])\n\nSolve the alternate ODE model where antibody binds to receptors at constant rate \u03b3.\n\"\"\"\nfunction solve_alt_ode_model(t,\u03b8::Vector)\n    \u03b3,\u03bb,\u03b2,p = \u03b8\n    M = [-\u03b2 0 0 0 0; \u03b2 -\u03b3 0 p*\u03b2 0; 0 \u03b3 -\u03bb 0 0; 0 0 \u03bb -p*\u03b2 0; 0 0 0 p*\u03b2 0]\n    x\u2080 = [\u03bb/(\u03bb+\u03b2),\u03b2/(\u03bb+\u03b2),0,0,0]\n    x = exp(M*t) * x\u2080\n    A = sum(x[3:5])\n    I = sum(x[4:5])\n    return [A,I]\nend\nsolve_alt_ode_model(t,\u03b3,\u03bb,\u03b2,p) = solve_alt_ode_model(t,[\u03b3,\u03bb,\u03b2,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": "using DataFrames\n\n# Create test data\nINCIDENCE_MAT = [0 1 0 1 1 0 0 0 0 0;\n\t\t 0 1 1 0 0 0 1 0 0 0;\n\t\t 1 1 0 1 1 0 0 0 1 1;\n\t\t 1 0 0 1 0 1 0 0 1 1;\n\t\t 0 0 1 1 0 0 0 1 0 0]\n\nC_MAT = INCIDENCE_MAT'INCIDENCE_MAT\n\n@testset \"Similarity methods tests\" begin\n\n\t# Check inputs:\n\t@test_throws MethodError similarity(DataFrame(INCIDENCE_MAT), method=\"jaccard\", orientation=\"colwise\") # non-matrix input\n\t@test_throws MethodError get_rca(INCIDENCE_MAT[:, 1], method=\"jaccard\", orientation=\"colwise\") # One-dim array\n\t@test_throws MethodError similarity([\"1\" \"2\"; \"3\" \"4\"], method=\"jaccard\", orientation=\"colwise\") # non-numeric matrix\n\t@test_throws AssertionError\n\tsimilarity(INCIDENCE_MAT, method=\"abc\", orientation=\"colwise\") # wrong method\n\t@test_throws MethodError \n\tsimilarity(INCIDENCE_MAT, method=\"jaccard\", orientation=\"abc\") # wrong orientation\n\n\t# Check output type:\n\t@test typeof(similarity(INCIDENCE_MAT, method=\"jaccard\", orientation=\"colwise\")) == Array{Float64, 2}\n\t@test typeof(similarity(INCIDENCE_MAT, method=\"jaccard\", orientation=\"rowwise\")) == Array{Float64, 2}\n\t@test typeof(similarity(INCIDENCE_MAT, method=\"association\", orientation=\"colwise\")) == Array{Float64, 2}\n\n\t# Check output result:\n\t# Methods\n\t@test similarity(INCIDENCE_MAT, method=\"association\", orientation=\"colwise\")[2, 4] == C_MAT[2, 4] / (C_MAT[2, 2] * C_MAT[4, 4])\n\t@test similarity(INCIDENCE_MAT, method=\"association\", orientation=\"colwise\")[9, 10] == C_MAT[9, 10] / (C_MAT[9, 9] * C_MAT[10, 10])\n\t@test similarity(INCIDENCE_MAT, method=\"cosine\", orientation=\"colwise\")[2, 4] == C_MAT[2, 4] / sqrt(C_MAT[2, 2] * C_MAT[4, 4])\n\t@test similarity(INCIDENCE_MAT, method=\"cosine\", orientation=\"colwise\")[9, 10] == C_MAT[9, 10] / sqrt(C_MAT[9, 9] * C_MAT[10, 10])\n\t@test similarity(INCIDENCE_MAT, method=\"inclusion\", orientation=\"colwise\")[2, 4] == C_MAT[2, 4] / min(C_MAT[2, 2], C_MAT[4, 4])\n\t@test similarity(INCIDENCE_MAT, method=\"inclusion\", orientation=\"colwise\")[9, 10] == C_MAT[9, 10] / min(C_MAT[9, 9], C_MAT[10, 10])\n\t@test similarity(INCIDENCE_MAT, method=\"jaccard\", orientation=\"colwise\")[2, 4] == C_MAT[2, 4] / (C_MAT[2, 2] + C_MAT[4, 4] - C_MAT[2, 4])\n\t@test similarity(INCIDENCE_MAT, method=\"jaccard\", orientation=\"colwise\")[9, 10] == C_MAT[9, 10] / (C_MAT[9, 9] + C_MAT[10, 10] - C_MAT[9, 10])\n\t@test similarity(INCIDENCE_MAT, method=\"proximity\", orientation=\"colwise\")[2, 4] == C_MAT[2, 4] / max(C_MAT[2, 2], C_MAT[4, 4])\n\t@test similarity(INCIDENCE_MAT, method=\"proximity\", orientation=\"colwise\")[9, 10] == C_MAT[9, 10] / max(C_MAT[9, 9], C_MAT[10, 10])\n\n\t# Orientation\n\t@test similarity(INCIDENCE_MAT, method=\"association\", orientation=\"rowise\") == similarity(INCIDENCE_MAT', method=\"association\", orientation=\"colwise\")\nend\n\n@testset \"Density tests\" begin\n\n\t# Define \n\tJACCARD_SIM = similarity(INCIDENCE_MAT, orientation=\"colwise\", method = \"jaccard\")\n\t# Check inputs:\n\t@test_throws MethodError density(M = DataFrame(INCIDENCE_MAT), SIM = JACCARD_SIM) # INCIDENCE_MAT should be a matrix\n\t@test_throws MethodError density(M = INCIDENCE_MAT, SIM = DataFrame(JACCARD_SIM)) # SIM should be a matrix\n\t@test_throws AssertionError density(M = INCIDENCE_MAT, SIM = vcat(JACCARD_SIM, JACCARD_SIM)) # SIM should be square\n\t@test_throws AssertionError density(M = INCIDENCE_MAT, SIM = hcat(JACCARD_SIM, JACCARD_SIM[:, 1])) # number of cols in M should be == number of cols and rows in SIM\n\n\t# Check output:\n\t# Check that output is a matrix\n\t@test typeof(density(M = INCIDENCE_MAT, SIM = JACCARD_SIM)) == Array{Float64, 2}\n\t# Check that output is symmetrical\n\t@test size(density(M = INCIDENCE_MAT, SIM = JACCARD_SIM), 1) == size(density(M = INCIDENCE_MAT, SIM = JACCARD_SIM), 2)\n\n\t# Check output result:\n\t@test density(\n\t\t      M = INCIDENCE_MAT,\n\t\t      SIM = JACCARD_SIM\n\t\t      )[2, 5] == sum(INCIDENCE_MAT[2, :] .* JACCARD_SIM[5, :]) / sum(JACCARD_SIM[5,:])\n\n\t@test density(\n\t\t      M = INCIDENCE_MAT,\n\t\t      SIM = JACCARD_SIM\n\t\t      )[5, 9] == sum(INCIDENCE_MAT[5, :] .* JACCARD_SIM[9, :]) / sum(JACCARD_SIM[9, :])\n\nend\n", "meta": {"hexsha": "a22e5cbbee4497b6f5b2fefc5d3d9430f763d8b8", "size": 4006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/relatedness-tests.jl", "max_stars_repo_name": "sbpost/compost", "max_stars_repo_head_hexsha": "616d1e123bea38ef5adbcdcf857b6f0b8ddbca44", "max_stars_repo_licenses": ["MIT"], "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/relatedness-tests.jl", "max_issues_repo_name": "sbpost/compost", "max_issues_repo_head_hexsha": "616d1e123bea38ef5adbcdcf857b6f0b8ddbca44", "max_issues_repo_licenses": ["MIT"], "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/relatedness-tests.jl", "max_forks_repo_name": "sbpost/compost", "max_forks_repo_head_hexsha": "616d1e123bea38ef5adbcdcf857b6f0b8ddbca44", "max_forks_repo_licenses": ["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.8767123288, "max_line_length": 165, "alphanum_fraction": 0.6962056915, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7569403759840487}}
{"text": "using Random\n\n# CVIT - Create itr and itst indeces for k-fold-cv\n#\n#    Description\n#     [ITR,ITST]=CVITR(N,K) returns 1xK cell arrays ITR and ITST holding \n#      cross-validation indeces for train and test sets respectively. \n#      K-fold division is balanced with all sets having floor(N/K) or \n#      ceil(N/K) elements.\n#\n#     [ITR,ITST]=CVITR(N,K,RS) with integer RS=true also makes random \n#      permutation, using substream RS. This way different permutations \n#      can be produced with different RS values, but same permutation is \n#      obtained when called again with same RS. Function restores the \n#      previous random stream before exiting.\n#\n\n\n# Copyright (c) 2010 Aki Vehtari\n\n# This software is distributed under the GNU General Public\n# License (version 2 or later); please refer to the file\n# License.txt, included with the software, for details.\n    \nfunction cvit(n, k=10, rsubstream=false)\n\n    a = k-rem(n,k)\n    b = floor(Int, n/k);\n\n    itst = Any[]\n    itr = Any[]\n\n    for cvi in 1:a\n        push!(itst, collect(1:b) .+ (cvi-1) * b)\n        push!(itr, setdiff(1:n,itst[cvi])) \n    end\n    for cvi in (a+1):k\n        push!(itst, (a * b) + collect(1:(b + 1)) + (cvi - a - 1) * (b + 1)) \n        push!(itr, setdiff(1:n,itst[cvi])) \n    end  \n\n    if rsubstream\n        rng = MersenneTwister()\n        rii = randperm(rng, n)\n        for cvi in 1:k\n            itst[cvi] = rii[itst[cvi]]\n            itr[cvi] = rii[itr[cvi]]\n        end\n    end\n    itr, itst\nend\n\n", "meta": {"hexsha": "b757f961598f583094f0adf516214207a9c66bff", "size": 1495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cvit.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": "test/cvit.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": "test/cvit.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": 28.2075471698, "max_line_length": 76, "alphanum_fraction": 0.6107023411, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7569403729749078}}
{"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), (\u03bc, y) -> kl_divergence(y, \u03bc))\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), (\u03bc, y) -> kl_divergence(y, \u03bc))\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\u03bb = sqrt(median(distances[i] for i in CartesianIndices(distances) if i[1] < i[2]))\nkernel = (GaussianKernel() \u2218 ScaleTransform(inv(\u03bb))) \u2297 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 \u2299, hadamard, hadamard!\nexport \u2297, tensor, tensor!\nexport \u22a1, boxdot, boxdot!\n\n\"\"\"\n    hadamard(a, b)\n    a \u2299 b\n\nFor arrays `a` and `b`, perform elementwise multiplication.\n`a` and `b` must have identical `axes`.\n\n`\u2299` 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 \u2299 b\n2-element Array{$Int,1}:\n 10\n 21\n\njulia> a \u2299 [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 \u2299 = hadamard\n\n\"\"\"\n    hadamard!(dest, A, B)\n\nSimilar to `hadamard(A, B)` (which can also be written `A \u2299 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 \u2297 B\n\nCompute the tensor product of `A` and `B`.\nIf `C = A \u2297 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 \u2297 v)` or `w \u2297 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 \u2297 b\n2\u00d73 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 \u2297 = 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 \u2297 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, \u22a1, boxdot!\n\n\"\"\"\n    boxdot(A,B) = A \u22a1 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 \u22a1 B)\n(3, 4, 6, 7)\n\njulia> typeof(rand(5) \u22a1 rand(5))\nFloat64\n\njulia> try B \u22a1 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 \u22a1 y)' == y' \u22a1 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 \u22a1 M')\nArray{Float64,1}\n\njulia> typeof(M \u22a1 v')  # adjoint of the previous line\nAdjoint{Float64,Array{Float64,1}}\n\njulia> typeof(v' \u22a1 M')  # same as *, and equal to adjoint(M \u22a1 v)\nAdjoint{Float64,Array{Float64,1}}\n\njulia> typeof(v' \u22a1 v)\nFloat64\n```\nSee also `boxdot!(Y,A,B)`, which is to `\u22a1` 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 \u22a1 = 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 \u22a1 vec(B)\nboxdot(A::AbstractVector, B::TransposeAbsVec) = A \u22a1 vec(B)\n\nboxdot(A::AdjointAbsVec, B::AdjointAbsVec) = adjoint(adjoint(B) \u22a1 adjoint(A))\nboxdot(A::AdjointAbsVec, B::TransposeAbsVec) = vec(A) \u22a1 vec(B)\nboxdot(A::TransposeAbsVec, B::AdjointAbsVec) = vec(A) \u22a1 vec(B)\nboxdot(A::TransposeAbsVec, B::TransposeAbsVec) = transpose(transpose(B) \u22a1 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' \u22a1 A')'\nboxdot(A::AbstractMatrix, B::TransposeAbsVec) = transpose(transpose(B) \u22a1 transpose(A))\n\n# ... and with higher-dim (returning a plain array)\nboxdot(A::AdjointAbsVec, B::AbstractArray) = vec(A) \u22a1 B\nboxdot(A::TransposeAbsVec, B::AbstractArray) = vec(A) \u22a1 B\n\nboxdot(A::AbstractArray, B::AdjointAbsVec) = A \u22a1 vec(B)\nboxdot(A::AbstractArray, B::TransposeAbsVec) = A \u22a1 vec(B)\n\n\n\"\"\"\n    boxdot!(Y, A, B, \u03b1=1, \u03b2=0)\n\nIn-place version of `boxdot`, i.e. `Y .= (A \u22a1 B) .* \u03b2 .+ Y .* \u03b1`.\nLike 5-argument `mul!`, the use of `\u03b1, \u03b2` 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, \u03b1::Number=true, \u03b2::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), \u03b1, \u03b2)\n        Y\n    end\n\n    # For boxdot!, only where mul! behaves differently:\n    boxdot!(Y::AbstractArray, A::AbstractArray, B::AdjOrTransAbsVec,\n        \u03b1::Number=true, \u03b2::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 \u22a1 y)' == y' \u22a1 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 \u22a1 v')\n(3, 4)\n\njulia> let var\"'\" = TensorCore._adjoint\n         v \u22a1 T3' \u2248 (T3 \u22a1 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 \u2208 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\u1d40 = Matrix{Sym}(hcat(X_...))\n    X = transpose(X\u1d40)\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\u0302(X) = X * w\nE(X) = 1 / 2 * (dot(y, y) - 2 * dot(y, y\u0302(X)) + dot(y\u0302(X), y\u0302(X)))\n\n@info \"calc-gradient\"\n\n\u2207E = gradient(Params([w])) do\n    E(X)\nend\n\n@info \"solve\"\nsolution = solve(\u2207E[w], w)\nsolution = [solution[k] for k in w]\n@info \"solve-with-norma-equation\"\n# solve w\u0302 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": "# [test/rkfixed_tests.jl]\nusing Test \n\n@testset \"RK Fixed Tests\" begin\n\n    using JLD2\n    import ODEHybrid.rkfixed, ODEHybrid.ODE_SET\n\n    @testset \"Example from Code Comments\" begin \n        a = [0   0   0  0; \n            0.5 0   0  0; \n            0   0.5 0  0; \n            0   0   1  0];\n        b = [1 2 2 1]/6;\n        c = [0 0.5 0.5 1];\n\n        ts = [0.0 10.0]\n        x0 = [1.0; 0.0]\n        dt = 0.1\n\n        # mat\"\"\"\n        # [$t_mat, $x_mat] = rkfixed(@(t,x) [-x(2); x(1)], $ts, [1; 0], $dt, $a, $b, $c);\n        # % rkfixed(@(t,x) [-x(2); x(1)], $ts, $x0, $dt, $a, $b, $c)\n        # \"\"\"\n    \n        @load \"solutions/rkfixed_example_from_code.jld2\" t_mat x_mat;\n\n        t_jul, x_jul = rkfixed( (t, x) -> [-x[2]; x[1]], ts, x0, dt, a, b, c)\n\n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\n    @testset \"Default tableau values\" begin \n        ts = [0.0 10.0]\n        x0 = [1.0; 0.0]\n        dt = 0.1\n\n        # mat\"\"\"\n        # [$t_mat, $x_mat] = rkfixed(@(t,x) [-x(2); x(1)], $ts, $x0, $dt);\n        # \"\"\"\n\n        @load \"solutions/rkfixed_default_tab.jld2\" t_mat x_mat\n\n        t_jul, x_jul = rkfixed( (t, x) -> [-x[2]; x[1]], ts, x0, dt)\n\n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\n    @testset \"Function with time\" begin\n        ts = [-5.0 5.0]\n        x0 = [5.0; 2.5; 0.0; -2.5; 5.0]\n        dt = 0.25\n\n        # mat\"\"\"\n        # [$t_mat, $x_mat] = rkfixed(@(t,x) [-t * x(2); x(3); -x(4); x(5); -x(1)], $ts, $x0, $dt);\n        # \"\"\"\n\n        @load \"solutions/rkfixed_func_with_time.jld2\" t_mat x_mat\n        \n        t_jul, x_jul = rkfixed( (t, x) -> [-t * x[2]; x[3]; -x[4]; x[5]; -x[1]], ts, x0, dt)\n\n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\n    @testset \"Negative time step\" begin \n        ts = [12.0 -5.0]\n        x0 = [1.0; -1.0; 1.0; -1.0]\n        dt = -0.25\n\n        # mat\"\"\"\n        #     [$t_mat, $x_mat] = rkfixed(@(t,x) [-t * x(2); t * x(3); -t * x(4); t * x(1)], $ts, $x0, $dt);\n        # \"\"\"\n\n        @load \"solutions/rkfixed_neg_time_step.jld2\" t_mat x_mat\n\n        t_jul, x_jul = rkfixed( (t, x) -> [-t * x[2]; t * x[3]; -t * x[4]; t * x[1]], ts, x0, dt)\n\n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\n    # Plot currently supressed\n    @testset \"ODE_SET with output function\" begin \n        ts = [-10.0 0]\n        x0 = [1.0; -1.0]\n        dt = 0.25 \n\n        # mat\"\"\"\n        #     ode = @(t, x) [-x(2); x(1)];\n        #     % options = odeset('OutputFcn', @odeplot);\n        #     options = odeset();\n        #     options.MaxStep = $dt;\n        #     [$t_mat, $x_mat] = rkfixed(ode, $ts, $x0, options)\n        # \"\"\"\n\n        @load \"solutions/rkfixed_odeset_with_output.jld2\" t_mat x_mat\n\n        options = ODE_SET()\n        # options.OutputFcn = odeplot \n        options.MaxStep = dt\n\n        t_jul, x_jul = rkfixed( (t, x) -> [-x[2]; x[1]], ts, x0, options)\n\n        @test isapprox(x_mat, x_jul, atol = 1e-12)\n        @test isapprox(t_mat, t_jul, atol = 1e-12)\n    end;\n\nend;\n", "meta": {"hexsha": "d68adaf451f3802c592620c2ef4bc3a220b55055", "size": 3186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rkfixed_tests.jl", "max_stars_repo_name": "benjjensen/ODEHybrid.jl", "max_stars_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_stars_repo_licenses": ["MIT"], "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/rkfixed_tests.jl", "max_issues_repo_name": "benjjensen/ODEHybrid.jl", "max_issues_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-18T18:50:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T18:59:30.000Z", "max_forks_repo_path": "test/rkfixed_tests.jl", "max_forks_repo_name": "benjjensen/ODEHybrid.jl", "max_forks_repo_head_hexsha": "b39309be49747f1a5a2d56eeef11b5f138255a3b", "max_forks_repo_licenses": ["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.4464285714, "max_line_length": 107, "alphanum_fraction": 0.459824231, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7569034303352963}}
{"text": "using Makie\nusing AbstractPlotting: textslider\nusing Distributions: Normal, pdf\n\nfunction single()\n    s_\u03bc, obs_\u03bc = textslider(range(-1., stop=1., length=101), \"\u03bc\", start=0)\n    \u03c3 = 1\n    #=\n    pos = lift(obs_\u03bc) do \u03bc\n            d = Normal(\u03bc, \u03c3)\n            [Point2f0(x, pdf(d, x)) for x in -5.:0.02:5.]\n        end\n    =#\n\n    pos = lift(\u03bc ->begin\n                        d = Normal(\u03bc, \u03c3)\n                        [Point2f0(x, pdf(d, x)) for x in -5.:0.02:5.]\n                   end,\n                obs_\u03bc\n           )\n\n    p = lines(pos)\n    RecordEvents(\n        hbox(\n            p, \n            vbox(s_\u03bc), \n            parent=Scene()\n        ),\n        \"output\"\n    )\nend\n\nfunction main()\n    s_\u03bc, obs_\u03bc = textslider(range(-1., stop=1., length=101), \"\u03bc\", start=0)\n    s_\u03c3, obs_\u03c3 = textslider(range(0.1, stop=5.1, length=101), \"\u03c3\", start=1)\n    \n    #=\n    params = lift(tuple, obs_\u03bc, obs_\u03c3)\n    pos = lift(params) do (\u03bc, \u03c3)\n        d = Normal(\u03bc, \u03c3)\n        map(LinRange(-5, 5, 100)) do x\n            Point2f0(x, pdf(d, x))\n        end\n    end\n    =#\n\n    #=\n    pos = lift((\u03bc, \u03c3) -> begin\n                            d = Normal(\u03bc, \u03c3)\n                            [Point2f0(x, pdf(d, x)) \n                                for x in -5.:0.02:5.]\n                         end,\n               obs_\u03bc, obs_\u03c3)\n    =#\n\n    pos = lift(lift(tuple, obs_\u03bc, obs_\u03c3)) do (\u03bc, \u03c3)\n            d = Normal(\u03bc, \u03c3)\n            [Point2f0(x, pdf(d, x)) for x in -5.:0.02:5.]\n        end\n    p = lines(pos)\n\n    RecordEvents(\n        hbox(\n            p, \n            vbox(s_\u03bc, s_\u03c3), \n            parent=Scene()\n        ),\n        \"output\"\n    )\n\nend\n\nmain()", "meta": {"hexsha": "db3bd8409afa17d0143569e60ac17997580c95f0", "size": 1634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "makieExer/interact/gaussian.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/interact/gaussian.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/interact/gaussian.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": 22.3835616438, "max_line_length": 75, "alphanum_fraction": 0.4106487148, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.756903429042849}}
{"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\u00abThe 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.\u00bb\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\u2080 and residual r\u2080.\n  x = zeros(T, n) # x\u2080\n  r = copy(b)     # r\u2080\n  # Compute \u03c1\u2080 = < r\u2080,r\u2080 > and residual norm \u2016r\u2080\u2016\u2082.\n  \u03c1 = @kdot(n, r, r)\n  rNorm = sqrt(\u03c1)\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  \u03b5 = atol + rtol * rNorm\n  verbose && @printf(\"%5d  %7.1e\\n\", iter, rNorm)\n\n  # Set up workspace.\n  u = copy(r)  # u\u2080\n  p = copy(r)  # p\u2080\n  q = zeros(n) # q\u208b\u2081\n\n  # Stopping criterion.\n  solved = rNorm \u2264 \u03b5\n  tired = iter \u2265 itmax\n  status = \"unknown\"\n\n  while !(solved || tired)\n\n    y = M * p                 # y\u2098 = M\u207b\u00b9p\u2098\n    v = A * y                 # v\u2098 = Ay\u2098\n    \u03c3 = @kdot(n, v, b)        # \u03c3\u2098 = < AM\u207b\u00b9p\u2098,r\u2080 >\n    \u03b1 = \u03c1 / \u03c3                 #\u00a0\u03b1\u2098 = \u03c1\u2098 / \u03c3\u2098\n    @. q = u - \u03b1 * v          # q\u2098 = u\u2098 - \u03b1\u2098 * AM\u207b\u00b9p\u2098\n    @kaxpy!(n, 1.0, q, u)     # u\u2098\u208a\u00bd = u\u2098 + q\u2098\n    z = M * u                 # z\u2098 = M\u207b\u00b9u\u2098\u208a\u00bd\n    @kaxpy!(n, \u03b1, z, x)       # x\u2098\u208a\u2081 = x\u2098 + \u03b1\u2098 * M\u207b\u00b9(u\u2098 + q\u2098)\n    w = A * z                 # w\u2098 = AM\u207b\u00b9(u\u2098 + q\u2098)\n    @kaxpy!(n, -\u03b1, w, r)      # r\u2098\u208a\u2081 = r\u2098 - \u03b1\u2098 * AM\u207b\u00b9(u\u2098 + q\u2098)\n    \u03c1_next = @kdot(n, r, b)   # \u03c1\u2098\u208a\u2081 = < r\u2098\u208a\u2081,r\u2080 >\n    \u03b2 = \u03c1_next / \u03c1            # \u03b2\u2098 = \u03c1\u2098\u208a\u2081 / \u03c1\u2098\n    @. u = r + \u03b2 * q          # u\u2098\u208a\u2081 = r\u2098\u208a\u2081 + \u03b2\u2098 * q\u2098\n    @kaxpby!(n, 1.0, q, \u03b2, p) # p\u2098\u208a\u2081 = u\u2098\u208a\u2081 + \u03b2\u2098 * (q\u2098 + \u03b2\u2098 * p\u2098)\n    @kaxpby!(n, 1.0, u, \u03b2, p)\n\n    # Update \u03c1.\n    \u03c1 = \u03c1_next # \u03c1\u2098 \u2190 \u03c1\u2098\u208a\u2081\n\n    # Update iteration index.\n    iter = iter + 1\n\n    #\u00a0Compute residual norm \u2016r\u2098\u2016\u2082.\n    rNorm = @knrm2(n, r)\n    push!(rNorms, rNorm)\n\n    # Update stopping criterion.\n    solved = rNorm \u2264 \u03b5\n    tired = iter \u2265 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(\u03c0, 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(\u03c0, 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 \u2208 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": "using FractionalCalculus\nusing Test\n\n@testset \"FractionalCalculus\" begin\n    include(\"./Derivative.jl\")\n    include(\"./Integral.jl\")\nend", "meta": {"hexsha": "7c57f10ace7a62d8882c6ac45025390708398494", "size": 136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "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": "test/runtests.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": "test/runtests.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": 19.4285714286, "max_line_length": 35, "alphanum_fraction": 0.7426470588, "num_tokens": 35, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.756869019696972}}
{"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": "using LowRankModels\nusing FactCheck\n\nTOL = 1e-3\n\nfacts(\"Classification Losses\") do\n\n  context(\"logistic loss\") do\n    l = LogisticLoss()\n    l1 = 1.31326168\n    l0 = 0.3132616875\n    # 1 is true\n    # -1 and 0 are both false\n    # anything else is an error\n    @fact evaluate(l, 1, true) --> roughly(l0, TOL)\n    @fact evaluate(l, 1, false) --> roughly(l1, TOL)\n    @fact evaluate(l, -1, true) --> roughly(l1, TOL)\n    @fact evaluate(l, -1, false) --> roughly(l0, TOL)\n    @fact evaluate(l, 1, 1) --> roughly(l0, TOL)\n    @fact evaluate(l, 1, -1) --> roughly(l1, TOL)\n    @fact evaluate(l, 1, 0) --> roughly(l1, TOL)\n    @fact evaluate(l, -1, 1) --> roughly(l1, TOL)\n    @fact evaluate(l, -1, -1) --> roughly(l0, TOL)\n    @fact evaluate(l, -1, 0) --> roughly(l0, TOL)\n\n    @fact evaluate(3*l, 1, false) --> roughly(3*l1, TOL)\n  end\n\n  context(\"hinge loss\") do\n    l = HingeLoss()\n    # 1 is true\n    # -1 and 0 are both false\n    # anything else is an error\n    @fact evaluate(l, 1, true) --> roughly(0, TOL)\n    @fact evaluate(l, 1, false) --> roughly(2, TOL)\n    @fact evaluate(l, -1, true) --> roughly(2, TOL)\n    @fact evaluate(l, -1, false) --> roughly(0, TOL)\n    @fact evaluate(l, 1, 1) --> roughly(0, TOL)\n    @fact evaluate(l, 1, -1) --> roughly(2, TOL)\n    @fact evaluate(l, 1, 0) --> roughly(2, TOL)\n    @fact evaluate(l, -1, 1) --> roughly(2, TOL)\n    @fact evaluate(l, -1, -1) --> roughly(0, TOL)\n    @fact evaluate(l, -1, 0) --> roughly(0, TOL)\n\n    @fact evaluate(3*l, 1, false) --> roughly(3*2, TOL)\n\n    @fact grad(l, -1, true) --> roughly(-1, TOL)\n    @fact grad(l, 2, true) --> roughly(0, TOL)\n    @fact grad(l, -2, false) --> roughly(0, TOL)\n    @fact grad(l, 2, false) --> roughly(1, TOL)\n  end\n\nend\n", "meta": {"hexsha": "c9a799273179f7cbca07006b77d442376fa02fde", "size": 1721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/quantitative_tests/test_loss.jl", "max_stars_repo_name": "heyi19931225/Lowrankmodels", "max_stars_repo_head_hexsha": "b87cadec54dd0e431c0b901ae405dcc490bdc79a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 169, "max_stars_repo_stars_event_min_datetime": "2015-01-07T20:07:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T17:17:10.000Z", "max_issues_repo_path": "test/quantitative_tests/test_loss.jl", "max_issues_repo_name": "heyi19931225/Lowrankmodels", "max_issues_repo_head_hexsha": "b87cadec54dd0e431c0b901ae405dcc490bdc79a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91, "max_issues_repo_issues_event_min_datetime": "2015-05-25T21:51:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-16T19:20:47.000Z", "max_forks_repo_path": "test/quantitative_tests/test_loss.jl", "max_forks_repo_name": "heyi19931225/Lowrankmodels", "max_forks_repo_head_hexsha": "b87cadec54dd0e431c0b901ae405dcc490bdc79a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2015-03-03T18:57:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T14:34:54.000Z", "avg_line_length": 31.8703703704, "max_line_length": 56, "alphanum_fraction": 0.5665310866, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320945, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7568690090698972}}
{"text": "using MieScatter\nusing Test\n\n\n@testset \"Cross sections\" begin\n\n    # These tests are made compared to the FORTRAN77 Mie code\n    # written by Karri Muinonen to the precision of the output\n    # of that code.\n    \n    # Test computation of scattering, extinction and absorbsion\n    # cross sections.\n    \n    # Size parameter 2, refractive index 1.33\n    S, Qsca, Qext, Qback = compute_mie(2.0, 1.33, 181)\n    Qabs = Qext-Qsca\n    @test isapprox(Qsca, 0.71295 ; atol = 6)\n    @test isapprox(Qext, 0.71295 ; atol = 6)\n    @test isapprox(Qabs, 0.0 ; atol = 10)\n    \n    # Size parameter 2, refractive index 1.6\n    S, Qsca, Qext, Qback = compute_mie(2.0, 1.6, 181)\n    Qabs = Qext-Qsca\n    @test isapprox(Qsca, 2.4834 ; atol = 5)\n    @test isapprox(Qext, 2.4834 ; atol = 5)\n    @test isapprox(Qabs, 0.0 ; atol = 10)\n    \n    # Size parameter 20, refractive index 1.33\n    S, Qsca, Qext, Qback = compute_mie(20.0, 1.33, 181)\n    Qabs = Qext-Qsca\n    @test isapprox(Qsca, 0.21401E+01 ; atol = 6)\n    @test isapprox(Qext, 0.21401E+01 ; atol = 6)\n    @test isapprox(Qabs, 0.66613E-14 ; atol = 6)\n    \n    # Size parameter 20, refractive index 1.6\n    S, Qsca, Qext, Qback = compute_mie(20.0, 1.6, 181)\n    Qabs = Qext-Qsca\n    @test isapprox(Qsca, 0.26115E+01 ; atol = 6)\n    @test isapprox(Qext, 0.26115E+01 ; atol = 6)\n    @test isapprox(Qabs, 0.39968E-14 ; atol = 6)\n\nend # cross section testset\n\n\n@testset \"Return types and NaN\" begin\n    S, Qsca, Qext, Qback = compute_mie(20.0, 1.6, [pi/2])\n    @test typeof(S) == Array{Float64,2}\n    @test size(S) == (1,4)\n    @test typeof(Qsca) == Float64\n    @test typeof(Qext) == Float64\n    @test typeof(Qback) == Float64\n    @test isnan(Qext)\n    @test isnan(Qback)\n    @test !isnan(Qsca)\nend\n", "meta": {"hexsha": "3a27d4185ae734680e09f85d0306e7ad5eadf3bc", "size": 1732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MieScatter/test/runtests.jl", "max_stars_repo_name": "aluque/CloudScat.jl", "max_stars_repo_head_hexsha": "6691533eb8c4bbed683e052409a49d6fc5f96804", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-06-30T10:40:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T20:16:45.000Z", "max_issues_repo_path": "src/MieScatter/test/runtests.jl", "max_issues_repo_name": "aluque/CloudScat.jl", "max_issues_repo_head_hexsha": "6691533eb8c4bbed683e052409a49d6fc5f96804", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-16T01:37:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T08:56:57.000Z", "max_forks_repo_path": "src/MieScatter/test/runtests.jl", "max_forks_repo_name": "aluque/CloudScat.jl", "max_forks_repo_head_hexsha": "6691533eb8c4bbed683e052409a49d6fc5f96804", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:22:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T14:41:59.000Z", "avg_line_length": 30.9285714286, "max_line_length": 63, "alphanum_fraction": 0.6252886836, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7568690081318847}}
{"text": "using Plots\ngr()\n\nusing LaTeXStrings\n\nusing Unitful\nusing Unitful: N, mm, inch, m, cm, MPa\nUnitful.preferunits(u\"mm, s\"...)\n\nusing DataFrames\n\nusing LinearAlgebra\n\n\u03b8 = LinRange(0, 2\u03c0, 100)\ny = sin.(\u03b8)\n\np1 = plot(\u03b8, y, \n\ttitle = L\"sin(\\theta)\",\n\txlabel = L\"\\theta\",\n\tylabel = L\"Amplitude\",\n\txlim = [0, 2\u03c0],\n\tylim = [-1, 1],\n\tlegend = false\n);\n\ndisplay(p1)\n\np2 = scatter(\u03b8, y,\n\talpha = 0.5,\n\tcolor = :jet1,\n\tmarker_z = y,\n\tmarker = :hexagon,\n\tmarkersize = 5,\n\tlegend = false\n);\ndisplay(p2)\n\nF = [1000, 3200, -4000, 4300, -2750, 6630]N\nr = [300mm, 400mm, 10inch, 15cm, 0.188m, 27cm] .|> mm\n\ndf = DataFrame(r=r, F=F)\n\n\n\n\n\n", "meta": {"hexsha": "8673ab7e6625ad86a28292b239c43bc2c5a46b0d", "size": 618, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "warmup.jl", "max_stars_repo_name": "tim-au/pluto_test1", "max_stars_repo_head_hexsha": "f9b6cb45c66d208a035e76d733a09eaf524fa85b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "warmup.jl", "max_issues_repo_name": "tim-au/pluto_test1", "max_issues_repo_head_hexsha": "f9b6cb45c66d208a035e76d733a09eaf524fa85b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "warmup.jl", "max_forks_repo_name": "tim-au/pluto_test1", "max_forks_repo_head_hexsha": "f9b6cb45c66d208a035e76d733a09eaf524fa85b", "max_forks_repo_licenses": ["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.1489361702, "max_line_length": 53, "alphanum_fraction": 0.6100323625, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.815232480373843, "lm_q1q2_score": 0.7568690060480348}}
{"text": "\"\"\"\n    sum_of_sines(domain, c, \u03c9, \u03d5)\n\nCreate initial condition function `u\u2080` and an antiderivative `U\u2080`.\nThe function is a sum of sines of amplitudes `c`, frequencies `\u03c9` and phase-shifts `\u03d5`.\n\"\"\"\nfunction sum_of_sines(domain, c, \u03c9, \u03d5)\n    \u03c6(\u03c9, \u03d5, x) = sin(\u03c9 * x - \u03d5) \n    \u03a6(\u03c9, \u03d5, x) = \u03c9 \u2248 0 ? -sin(\u03d5) * x : -cos(\u03c9 * x - \u03d5) / \u03c9 \n    u\u2080(x) = sum(c .* \u03c6.(\u03c9, \u03d5, x))\n    U\u2080(x) = sum(c .* \u03a6.(\u03c9, \u03d5, x))\n    u\u2080, U\u2080\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": "\nusing Statistics\ninclude(\"dsp.jl\")\n\nfunction sdnn(nn_interval::Vector{<:Real})\n\n    sdnn = std(nn_interval)\n    return sdnn\nend\n\n\nfunction sdann_asdnn(nn_interval::Vector{<:Real}, index_array::Vector{<:Integer},\n    duration::Integer, min_number_of_interval::Integer = 3)\n\n    if length(nn_interval) < min_number_of_interval\n        return nothing, nothing\n    end\n\n    segment_index = get_segment_index(index_array, duration)\n\n    average_array::Vector{Float64} = []\n    std_array::Vector{Float64} = []\n\n    start_idx = 1\n    for end_idx in segment_index\n        landmark = @view nn_interval[start_idx:end_idx]\n\n        if length(landmark) >= min_number_of_interval\n            push!(average_array, mean(landmark))\n            push!(std_array, std(landmark))\n        end\n        start_idx = end_idx\n    end\n\n    if length(average_array) >= min_number_of_interval\n        \n        sdann = std(average_array)\n        asdnn = mean(std_array)\n        return sdann, asdnn\n    end\n\n    return nothing, nothing\nend", "meta": {"hexsha": "62fa44eb40c024f16e493409b6967850de05a71e", "size": 1009, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "utils/metric.jl", "max_stars_repo_name": "44REAM/ecg_diagnosis", "max_stars_repo_head_hexsha": "820218e16805c90f77c611eb6d1a7491612f9d13", "max_stars_repo_licenses": ["MIT"], "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/metric.jl", "max_issues_repo_name": "44REAM/ecg_diagnosis", "max_issues_repo_head_hexsha": "820218e16805c90f77c611eb6d1a7491612f9d13", "max_issues_repo_licenses": ["MIT"], "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/metric.jl", "max_forks_repo_name": "44REAM/ecg_diagnosis", "max_forks_repo_head_hexsha": "820218e16805c90f77c611eb6d1a7491612f9d13", "max_forks_repo_licenses": ["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.4651162791, "max_line_length": 81, "alphanum_fraction": 0.6660059465, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7568043991623714}}
{"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 \u2265 maxrank \u2265 1 || throw(DomainError(maxrank,\"maxrank must be \u2265 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 \u2299 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) \u2264 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 \u2208 \u211d\u207f | \u27e8c, x\u27e9 \u2264 1, x \u2265 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.:(*)(\u03bb::Real, F::PosSimplexFace) = \u03bb*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": "using PolynomialBasis\nusing Test\n# using Revise\nusing CutCellDG\ninclude(\"../useful_routines.jl\")\n\npolyorder = 1\nnumqp = 2\n\nbasis = LagrangeTensorProductBasis(2,1)\ndim,numpts = size(interpolation_points(basis))\nmesh = CutCellDG.CGMesh([0.0, 0.0], [3.0, 1.0], [3, 1], numpts)\n\nx0 = [1.5,0.0]\nnormal = [1.,0.]\ndistancefunc(x) = plane_distance_function(x,normal,x0)\nlevelset = CutCellDG.LevelSet(distancefunc,mesh,basis)\nCutCellDG.load_coefficients!(levelset,1)\n@test allapprox(levelset.interpolater.coeffs,[-1.5,-1.5,-0.5,-0.5]')\n@test levelset([0.,0.]) \u2248 -1.0\n\nCutCellDG.update_coefficients!(levelset,2,[-0.6,-0.6,0.4,0.4])\n@test allapprox(CutCellDG.coefficients(levelset,2),[-0.6,-0.6,0.4,0.4])\n@test allapprox(CutCellDG.coefficients(levelset,1),[-1.5,-1.5,-0.6,-0.6])\n@test allapprox(CutCellDG.coefficients(levelset,3),[0.4,0.4,1.5,1.5])\n\n\nbasis = HermiteTensorProductBasis(2)\nnumqp = required_quadrature_order(3)\nquad = tensor_product_quadrature(2,numqp)\ndim,numpts = size(interpolation_points(basis))\nmesh = CutCellDG.CGMesh([0.,0.],[1.,1.],[2,2],numpts)\nx0 = [0.75,0.0]\nnormal = [1.0,0.0]\ndistancefunc(x) = plane_distance_function(x,normal,x0)\n\nlevelset = CutCellDG.LevelSet(distancefunc,mesh,basis)\n\ncoeffs1 = CutCellDG.coefficients(levelset,1)\ntestcoeffs = [-0.75  -0.75  -0.25  -0.25\n               0.0    0.0    0.0    0.0\n               0.25   0.25   0.25   0.25\n               0.0    0.0    0.0    0.0]\ntestcoeffs = vec(testcoeffs)\n@test allapprox(coeffs1,testcoeffs,1e3eps())\n\nx0 = [1.0,0.5]\nnormal = [1.0,1.0]/sqrt(2)\n\nfunction testcubic(v)\n    x,y = v\n    return 8x^3*y^3 + 4x^2*y^3 + 17*x*y + 11\nend\n\nlevelset = CutCellDG.LevelSet(testcubic,mesh,basis)\ntestcellid = 4\nCutCellDG.load_coefficients!(levelset,testcellid)\ncellmap = CutCellDG.cell_map(mesh,testcellid)\nxrange = range(-1,stop=1,length=5)\ntestp = ImplicitDomainQuadrature.tensor_product_points(xrange',xrange')\nspatialtestp = cellmap(testp)\n\nvals = vec(mapslices(levelset,testp,dims=1))\ntestvals = vec(mapslices(testcubic,spatialtestp,dims=1))\n@test allapprox(vals,testvals,1e4eps())\n", "meta": {"hexsha": "ca86e2bf08ca3e725693573581403554fa86787d", "size": 2057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/miscellaneous/test_levelset.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": "test/miscellaneous/test_levelset.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": "test/miscellaneous/test_levelset.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": 31.1666666667, "max_line_length": 73, "alphanum_fraction": 0.7024793388, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7567936709006444}}
{"text": "@testset \"no linesearch\" begin\n\nfunction f_nolin!(fvec, x)\n    fvec[1] = (x[1]+3)*(x[2]^3-7)+18\n    fvec[2] = sin(x[2]*exp(x[1])-1)\nend\n\nr = nlsolve(f_nolin!, [ -0.5; 1.4], autodiff = :forward, method = :newton, linesearch = LineSearches.Static())\n@test converged(r)\n\nend\n", "meta": {"hexsha": "40774633e1d009d7a6a640ecc1fa929fd320fc81", "size": 272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/no_linesearch.jl", "max_stars_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_stars_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": "test/no_linesearch.jl", "max_issues_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_issues_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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": "test/no_linesearch.jl", "max_forks_repo_name": "UnofficialJuliaMirror/NLsolve.jl-2774e3e8-f4cf-5e23-947b-6d7e65073b56", "max_forks_repo_head_hexsha": "159ca54d5a68553ad9f1dee461767649e095d0d8", "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.6666666667, "max_line_length": 110, "alphanum_fraction": 0.6176470588, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7567936685742719}}
{"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/\u221a2    0   -1/\u221a2\n                                        -im/\u221a2   0    -im/\u221a2\n                                        ])\n\nhelicity_polar_conversion(\u03b8, \u03d5) = HelicitySphericalPolarConversionMatrix\npolar_helicity_conversion(\u03b8, \u03d5) = helicity_polar_conversion(\u03b8, \u03d5)'\n\nfunction helicity_spherical_conversion(\u03b8, \u03d5)\n    cis\u03d5 = cis(\u03d5)\n    sin\u03b8, cos\u03b8 = sincos(\u03b8)\n    invsqrt2 = 1/\u221a2\n    sin\u00b2\u03b8by2 = (1 - cos\u03b8)/2\n    cos\u00b2\u03b8by2 = (1 + cos\u03b8)/2\n    SMatrix{3,3}((\n        cos\u00b2\u03b8by2 * cis\u03d5,\n        -sin\u03b8 * invsqrt2,\n        sin\u00b2\u03b8by2 * conj(cis\u03d5),\n\n        sin\u03b8 * invsqrt2 * cis\u03d5,\n        cos\u03b8,\n        -sin\u03b8 * invsqrt2 * conj(cis\u03d5),\n\n        sin\u00b2\u03b8by2 * cis\u03d5,\n        sin\u03b8 * invsqrt2,\n        cos\u00b2\u03b8by2 * conj(cis\u03d5),\n        ))\nend\nspherical_helicity_conversion(\u03b8, \u03d5) = helicity_spherical_conversion(\u03b8, \u03d5)'\n\nfunction helicity_cartesian_conversion(\u03b8, \u03d5)\n    sin\u03b8, cos\u03b8 = sincos(\u03b8)\n    sin\u03d5, cos\u03d5 = sincos(\u03d5)\n    invsqrt2 = 1/\u221a2\n\n    SMatrix{3,3}((\n        (cos\u03b8 * cos\u03d5 + im * sin\u03d5) * invsqrt2,\n        (cos\u03b8 * sin\u03d5 - im * cos\u03d5) * invsqrt2,\n        -sin\u03b8 * invsqrt2,\n\n        sin\u03b8 * cos\u03d5,\n        sin\u03b8 * sin\u03d5,\n        cos\u03b8,\n\n        -(cos\u03b8 * cos\u03d5 - im * sin\u03d5) * invsqrt2,\n        -(cos\u03b8 * sin\u03d5 + im * cos\u03d5) * invsqrt2,\n        sin\u03b8 * invsqrt2,\n        ))\nend\ncartesian_helicity_conversion(\u03b8, \u03d5) = helicity_cartesian_conversion(\u03b8, \u03d5)'\n\nfunction spherical_polar_conversion(\u03b8, \u03d5)\n    invsqrt2 = 1/\u221a2\n    invsqrt2cis\u03d5 = invsqrt2 * cis(\u03d5)\n    sin\u03b8, cos\u03b8 = sincos(\u03b8)\n    normsin\u03b8cis\u03d5 = sin\u03b8 * invsqrt2cis\u03d5\n    normcos\u03b8cis\u03d5 = cos\u03b8 * invsqrt2cis\u03d5\n    SMatrix{3,3}((\n        conj(normsin\u03b8cis\u03d5),\n        conj(normcos\u03b8cis\u03d5),\n        -im * conj(invsqrt2cis\u03d5),\n\n        cos\u03b8,\n        -sin\u03b8,\n        0,\n\n        -normsin\u03b8cis\u03d5,\n        -normcos\u03b8cis\u03d5,\n        -im * invsqrt2cis\u03d5,\n        ))\nend\npolar_spherical_conversion(\u03b8, \u03d5) = spherical_polar_conversion(\u03b8, \u03d5)'\n\nconst SphericalCartesianConversionMatrix = SMatrix{3,3}((\n        1/\u221a2,\n        -im/\u221a2,\n        0,\n\n        0,\n        0,\n        1,\n\n        -1/\u221a2,\n        -im/\u221a2,\n        0,\n        ))\n\nspherical_cartesian_conversion(\u03b8, \u03d5) = SphericalCartesianConversionMatrix\ncartesian_spherical_conversion(\u03b8, \u03d5) = spherical_cartesian_conversion(\u03b8, \u03d5)'\n\nfunction cartesian_polar_conversion(\u03b8, \u03d5)\n    sin\u03b8, cos\u03b8 = sincos(\u03b8)\n    sin\u03d5, cos\u03d5 = sincos(\u03d5)\n    SMatrix{3,3}((\n        sin\u03b8*cos\u03d5,\n        cos\u03b8*cos\u03d5,\n        -sin\u03d5,\n\n        sin\u03b8*sin\u03d5,\n        cos\u03b8*sin\u03d5,\n        cos\u03d5,\n\n        cos\u03b8,\n        -sin\u03b8,\n        0,\n        ))\nend\npolar_cartesian_conversion(\u03b8, \u03d5) = cartesian_polar_conversion(\u03b8, \u03d5)'\n\n\"\"\"\n    basisconversionmatrix(B1, B2, \u03b8, \u03d5)\n\nReturn the matrix that converts the components of a vector from the basis `B1` to the basis `B2`\nat the point `(\u03b8,\u03d5)`.\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> \u03b8, \u03d5 = pi/2, 0\n(1.5707963267948966, 0)\n\njulia> M = VectorSphericalHarmonics.basisconversionmatrix(Cartesian(), Polar(), \u03b8, \u03d5)\n3\u00d73 StaticArrays.SMatrix{3, 3, Float64, 9} with indices SOneTo(3)\u00d7SOneTo(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, \u03b8, \u03d5\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, \u03b8, \u03d5) where {T<:Basis} = I\nbasisconversionmatrix(::HelicityCovariant, ::SphericalCovariant, \u03b8, \u03d5) = helicity_spherical_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::SphericalCovariant, ::HelicityCovariant, \u03b8, \u03d5) = spherical_helicity_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::HelicityCovariant, ::Polar, \u03b8, \u03d5) = helicity_polar_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::Polar, ::HelicityCovariant, \u03b8, \u03d5) = polar_helicity_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::HelicityCovariant, ::Cartesian, \u03b8, \u03d5) = helicity_cartesian_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::Cartesian, ::HelicityCovariant, \u03b8, \u03d5) = cartesian_helicity_conversion(\u03b8, \u03d5)\n\nbasisconversionmatrix(::SphericalCovariant, ::Polar, \u03b8, \u03d5) = spherical_polar_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::Polar, ::SphericalCovariant, \u03b8, \u03d5) = polar_spherical_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::SphericalCovariant, ::Cartesian, \u03b8, \u03d5) = spherical_cartesian_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::Cartesian, ::SphericalCovariant, \u03b8, \u03d5) = cartesian_spherical_conversion(\u03b8, \u03d5)\n\nbasisconversionmatrix(::Cartesian, ::Polar, \u03b8, \u03d5) = cartesian_polar_conversion(\u03b8, \u03d5)\nbasisconversionmatrix(::Polar, ::Cartesian, \u03b8, \u03d5) = polar_cartesian_conversion(\u03b8, \u03d5)\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(\u03bb::T) where T <: Real\n    # TODO: numerically robust version\n    if \u03bb == 0.0 || \u03bb == -1.0\n        return 0.0\n    elseif -1.0 < \u03bb < 0.0\n        return (1.0 + \u03bb) * log(1.0 + \u03bb) - \u03bb * log(-\u03bb)\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\u03bc_j = mean(x_j)\n\u03c3_j = std(x_j)\nx_j^+ =  (x_j - \u03bc_j) / \u03c3_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    \u03bc = mean(X, dims=1)\n    \u03c3 = std(X, dims=1)\n\n    @inbounds for i in 1:d\n        X[:, i] .= (X[:, i] .- \u03bc[i]) ./ \u03c3[i]\n    end\nend\n\nfunction scale!(::NormalScaler, X::AbstractSparseMatrix{T, Int}) where T\n    n, d = size(X)\n    \u03c3 = std(X, dims=1)\n    @inbounds for i in 1:d\n        X[:, i] ./= \u03c3[i]\n    end\nend\n\n\"\"\"\nFormat labels `y = [y_1, ..., y_n]` to ensure that `y_i \u2208 { -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                                 \u03b5 = 0.008,\n                                 \u03b5_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, \u03b5_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\u1d9c = complement(B_int)\n\n    # define modes\n    aut = LightAutomaton(3)\n    outside = @system(x' = lotka_volterra!(x), dim: 2, x \u2208 B_int\u1d9c)\n    inside = @system(x' = lotka_volterra!(x), dim: 2, x \u2208 B_ext)\n    outside_unconstrained = @system(x' = lotka_volterra!(x), dim: 2, x \u2208 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 \u2208 B_ext)\n    T_in_out = @map(x -> x, dim:2, x \u2208 B_int\u1d9c)\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-\u03b5, 1.], high=[1.3+\u03b5, 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, \u03b5_ext=1e-4, n_int = 30, \u03b5 = 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 \u00f7 5 + zeta(x \u00f7 5) : 0\n    lo, hi = K, 5 * K + 1\n    while lo < hi\n        mid = (lo + hi) \u00f7 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": "using AbstractLogic\nusing Test\nusing Suppressor\n\n@test LogicalCombo() |> nfeasible == 0\n\nlogicset = @suppress logicalparse(\"a,b,c,d,e in 1:2\")\n@test logicset[1,1] == 1\n@test logicset[4^3,3] == 2\n@test logicset[:,:a] == logicset[:,1]\n\nlogicset = @suppress logicalparse(\"a.1,a.2,a.3,b.1,b.2,b.3 in 1:3 || {{j}}.1 != {{j}}.2, {{j}}.3 &&& {{j}}.2 != {{j}}.3\")\n@test nfeasible(logicset) == 36\n@test @suppress nfeasible(logicalparse(\"a,b,c in 1:3 || {{i}}!={{>i}}\")) == nfeasible(logicalparse(\"a,b,c in unique\"))\n\nlogicset = @suppress logicalparse(\"a,b,c in 1:3 || {{i}}!={{!i}}\")\n@test AbstractLogic.operatoreval(\"a^=b\",logicset) |> nfeasible == 0\n@test AbstractLogic.operatoreval(\"a|=b\",logicset) |> nfeasible == 0\n@test AbstractLogic.operatoreval(\"a!|=b\",logicset) |> nfeasible == 6\n@test AbstractLogic.operatoreval(\"a<=b\",logicset) |> nfeasible == 3\n@test AbstractLogic.operatoreval(\"a<<b\",logicset) |> nfeasible == 1\n@test AbstractLogic.operatoreval(\"a>=b\",logicset) |> nfeasible == 3\n@test AbstractLogic.operatoreval(\"a>>b\",logicset) |> nfeasible == 1\n@test AbstractLogic.operatoreval(\"a % 3 ==0\",logicset) |> nfeasible == 2\n\n\n@test @suppress logicalparse(\"{{<3|>3}}=1\", logicset) |> nfeasible  == 0\n\n@test @suppress search(\"{{i+4}}=1\", logicset)[1] === missing\n\n@test @suppress logicalparse(\"a,b \u2208 0:1; a==a === b==b; a == b !=> b != a\") |> nfeasible == 4\n\nx = @suppress logicalparse(\"a,b in 1:5; true &&& true ||| false ==> true <== false ||| true ^^^ false\")\n@test nfeasible(x) == 25\n\nx = @suppress logicalparse(\"a,b in 1:5; true &&&& true |||| false ===> true <=== false |||| true ^^^^ false\")\n@test nfeasible(x) == 25\n\nlogicset = @suppress logicalparse(\"a, b in 1; a != b\")\n@test @suppress( search(\"=1\", logicset)) === missing\n@test  @suppress(checkfeasible(\"a=1\", logicalparse(\"a, b in 1; a != b\")) === missing)\n\n@test AbstractLogic.definelogicalset(\"a \u2208 1\") |> nfeasible == 1\n@test AbstractLogic.definelogicalset(\"a,b,c \u2208 1,2,3 || unique\") |> nfeasible == 6\n\n@test expand(LogicalCombo(), [:a => 1:2, :b => 1:3]) |> nfeasible == 6\n\nlogicset = @suppress logicalparse(\"a, b, c in 1:3; a > b\")\n@test @suppress !dependenton(\"a \u22a5 b\", logicset)\n@test @suppress dependenton(\"a !\u22a5 b\", logicset)\n\n@test @suppress !dependenton(\"a \u22a5 b\", logicset)\n@test @suppress dependenton(\"a !\u22a5 b\", logicset)\n@test @suppress dependenton(\"a \u22a5 c\", logicset)\n\n@test @suppress !setcompare(\"a \u2282 b\", logicset)\n@test @suppress setcompare(\"a !\u2282 b\", logicset)\n@test @suppress setcompare(\"c \u2283 b\", logicset)\n@test @suppress setcompare(\"b !\u2283 c\", logicset)\n@test @suppress setcompare(\"a,b \u22c2 b,c\", logicset)\n@test @suppress !setcompare(\"a !\u22c2 c\", logicset)\n\n@test logicset |> showfeasible == logicset[:,:,true]\n\n@test @suppress(logicalparse(\"a,b,c,d,e in 1:2; {{i}}!={{i+1}}\") |> nfeasible) == 2\n@test @suppress(logicalparse(\"a,b,c,d,e in 1:2; {{i}}!={{i-1}}\") |> nfeasible) == 2\n@test @suppress(logicalparse(\"a,b in 1:2; {{i}}!={{>i}}\") |> nfeasible) == 2\n\n@test @capture_out(help()) |> length > 500\n@test @capture_out(help(\"\")) |> length > 500\n@test @capture_out(help(\"in\")) |> length > 250\n@test @capture_out(help(\"back\")) |> length > 50\n@test @capture_out(help(\"!=\")) |> length > 50\n@test @capture_out(help(\"!==\")) |> length > 430\n@test @capture_out(help(\"!===\")) |> length > 440\n@test @capture_out(help(\"{{i}}\")) |> length > 370\n\n@test @suppress(checkfeasible(\"{{i}}=1\", logicalparse(\"a,b in 1:2\")))[1] == .25\n@test @capture_out(logicalparse(\"a,b in 1:2; error\"))[(end-16):end] == \"not interpreted!\\n\"\n\nx = @suppress logicalparse(\"a,b in 1:2; a==b\")\n@test @suppress(AbstractLogic.back(x) |> nfeasible) == 4\n\n@test @suppress nfeasible(logicalparse([\"a,b in 1:2\",\"a==b\"])) == nfeasible(x)\n\n@test @suppress(logicalparse(\"a, b \u2208 0:1; a | b ||| a & b\")) |> nfeasible == 3\n", "meta": {"hexsha": "c3de3bbec64e8f1cfca0c42a0cc5c51ed2ce7865", "size": 3738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/logicalparse.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractLogic.jl-bd85187e-0531-4a3e-9fea-713204a818a2", "max_stars_repo_head_hexsha": "1b8adac10854471ec7ce83b9039cdeb1e43c0208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-09-24T23:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T18:03:25.000Z", "max_issues_repo_path": "test/logicalparse.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractLogic.jl-bd85187e-0531-4a3e-9fea-713204a818a2", "max_issues_repo_head_hexsha": "1b8adac10854471ec7ce83b9039cdeb1e43c0208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2019-08-08T19:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-10T01:13:59.000Z", "max_forks_repo_path": "test/logicalparse.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractLogic.jl-bd85187e-0531-4a3e-9fea-713204a818a2", "max_forks_repo_head_hexsha": "1b8adac10854471ec7ce83b9039cdeb1e43c0208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-22T01:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T01:12:36.000Z", "avg_line_length": 42.9655172414, "max_line_length": 121, "alphanum_fraction": 0.626270733, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.756793656683073}}
{"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": "using Distributions, Plots; pyplot()\n\ninclude(\"../data/mvParams.jl\")\nbiNorm = MvNormal(meanVect,covMat)\n\nN = 10^3\npoints = rand(MvNormal(meanVect,covMat),N)\n\nsupport = 15:0.5:40\nz = [ pdf(biNorm,[x,y]) for y in support, x in support ]\n\np1 = scatter(points[1,:], points[2,:], ms=0.5, c=:black, legend=:none)\np1 = contour!(support, support, z, \n\t\tlevels=[0.001, 0.005, 0.02], c=[:blue, :red, :green], \n\t\txlims=(15,40), ylims=(15,40), ratio=:equal, legend=:none, \n\t\txlabel=\"x\", ylabel=\"y\")\np2 = surface(support, support, z, lw=0.1, c=cgrad([:blue, :red]),\n\t\t legend=:none, xlabel=\"x\", ylabel=\"y\",camera=(-35,20))\n\nplot(p1, p2, size=(800, 400))", "meta": {"hexsha": "03ff530ef3494bf5499c2612bd262daba42e076e", "size": 640, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/bivariateNormal.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/bivariateNormal.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/bivariateNormal.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.0, "max_line_length": 70, "alphanum_fraction": 0.6328125, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7567840059387481}}
{"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(\u03b1,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,-\u03b1/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# \u2554\u2550\u2561 b7433dc1-846b-4173-ad51-f7598cd263a1\nusing FFTW, Plots, SampledSignals\n\n# \u2554\u2550\u2561 37f59728-aeae-4b15-ba8c-a90368dfa8f0\nbegin\n    fs = 48000\n\tfreqs = Array(LinRange(0, 2*pi*200, fs))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ef073029-a63e-4625-aecf-0cde96af5686\ntone = SampleBuf(note.(freqs), fs)\n\n# \u2554\u2550\u2561 9997ac3d-3cae-4bb5-8290-6ca53f431533\nplotfreqs(tone, \"Frequencies of a single 200 Hz note\")\n\n# \u2554\u2550\u2561 dcd90ce9-dfc0-42ed-990a-55710c32b34e\nmd\"## Intervals\nIf we play two unrelated notes at the same time we get two harmonic series\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9e45b6c3-a674-4b1f-b93e-11b4a99a22da\ndissonant = SampleBuf((note.(freqs) + note.(ratio*freqs))/2, fs) \n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3813605c-e5c8-4bd3-9813-f553d22d47b2\nbegin\n   plotfreqs(note.(freqs), \"\")\n   plotfreqs!(note.(2*freqs), \"Octave\")\nend\n\n# \u2554\u2550\u2561 6a831a92-a222-48e8-abfb-72bc9f3e0fb9\noctave = SampleBuf(note.(freqs)/2 + note.(2*freqs)/2, fs)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a4882ae0-32ed-4db4-ba0c-165081128f2d\nfunction odd(t)\n\tt = t/pi%2-1\n\tt = 4*t*(abs(t)-1)\nend\n\n# \u2554\u2550\u2561 e3faa985-c01a-471c-ae10-0aaaee8a6b43\nodd_octave = SampleBuf(odd.(freqs) + odd.(2*freqs)/8 + odd.(4*freqs)/64, fs) \n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 14af9192-4b8a-49c3-9775-b4dfef343780\ntritive = SampleBuf(note.(freqs)/2 + note.(3*freqs)/2, fs)\n\n# \u2554\u2550\u2561 02a98eb5-4021-4ea0-a0f8-b43c811d87b2\nblend_tritive = SampleBuf(note.(freqs)/2 + note.(3*freqs)/8, fs)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 82582e9b-fcc0-49ae-9f3b-558e70d8f0b8\nfifth = SampleBuf(note.(freqs)/2 + note.(3/2*freqs)/2, fs)\n\n# \u2554\u2550\u2561 db7c4951-972b-43db-a647-6e61c8ebdf03\nbegin\n   plotfreqs(note.(freqs), \"\")\n   plotfreqs!(note.(3/2*freqs), \"Fifth\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 df7e7e47-fe34-4250-bb0b-670fee0b56de\nfourth = SampleBuf(note.(freqs)/2 + note.(freqs*4/3)/2, fs)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550b7433dc1-846b-4173-ad51-f7598cd263a1\n# \u2560\u255037f59728-aeae-4b15-ba8c-a90368dfa8f0\n# \u2560\u2550cfc3b26d-d2da-4128-9ef2-a9494c4c25e5\n# \u2560\u2550b70c60fd-b29a-46f3-8daf-e6d7277156ca\n# \u255f\u2500baafd0a2-b449-11eb-0654-172c64b81fd6\n# \u2560\u25507a4f0f06-6b37-4a3c-81e4-8004462da33a\n# \u2560\u2550ef073029-a63e-4625-aecf-0cde96af5686\n# \u255f\u25009997ac3d-3cae-4bb5-8290-6ca53f431533\n# \u255f\u2500dcd90ce9-dfc0-42ed-990a-55710c32b34e\n# \u255f\u25007f363c48-a194-4494-bb59-d5e00db70bd2\n# \u2560\u25509e45b6c3-a674-4b1f-b93e-11b4a99a22da\n# \u255f\u250007312f0d-59d9-45ee-b60a-c6ecfc2bc0df\n# \u255f\u2500bfd2d6b6-2863-41ee-9b6a-c99ed19f8d7d\n# \u255f\u25003813605c-e5c8-4bd3-9813-f553d22d47b2\n# \u2560\u25506a831a92-a222-48e8-abfb-72bc9f3e0fb9\n# \u255f\u25000b9c89bf-291e-4b93-8632-f2d5117d25a4\n# \u2560\u2550a4882ae0-32ed-4db4-ba0c-165081128f2d\n# \u2560\u2550e3faa985-c01a-471c-ae10-0aaaee8a6b43\n# \u2560\u25506049ed44-b19f-41a9-b017-860e80d62017\n# \u255f\u2500ccb62252-fcf1-4fc8-b486-1df69ea0c1e3\n# \u2560\u255014af9192-4b8a-49c3-9775-b4dfef343780\n# \u2560\u255002a98eb5-4021-4ea0-a0f8-b43c811d87b2\n# \u255f\u250031b44424-b3f9-4ea0-8d99-28738f1fc857\n# \u2560\u255082582e9b-fcc0-49ae-9f3b-558e70d8f0b8\n# \u255f\u2500db7c4951-972b-43db-a647-6e61c8ebdf03\n# \u255f\u250053773643-1b58-4eee-ac11-bb30b7535fec\n# \u255f\u2500151b3663-524e-465f-9426-3f85689e9e27\n# \u255f\u250024e5caba-ce1c-4436-8ca2-647b5438658a\n# \u255f\u25008adb4c0a-a29e-4cee-bb49-ee285f90ff70\n# \u255f\u25008378910d-3a2c-441e-a3b3-716d819eced9\n# \u255f\u2500732ab799-970e-4ae7-a81d-cda4c79873f4\n# \u2560\u2550df7e7e47-fe34-4250-bb0b-670fee0b56de\n# \u255f\u2500518f1a8b-977b-4008-b1b7-667f0475b42c\n# \u2560\u2550849e0964-2c80-4fa6-9320-5fa0c595d79a\n# \u255f\u250006b01905-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\u03bc = Viscosity(Air)\n\u03c1 = Density(Air)\n\u03f5 = Height(0.0005u\"ft\")\ng = Gravity()\n#=\nNow let's calculate the flow velocity in the original design\n=#\nA = Area(\u03c0/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(\u03f5/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(\u03c1*V*D/\u03bc)\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 \u2208 U(a, b)} \u27e8C, P\u27e9\n```\nand the dual potentials using the network simplex method.\n\n# References\n\nPeyr\u00e9, 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            \u03b8min = P[LightGraphs.dst(e), LightGraphs.src(e) - n]\n            kmin = 1\n            for k in 3:2:length(path)\n                e = path[k]\n                \u03b8 = P[LightGraphs.dst(e), LightGraphs.src(e) - n]\n                if \u03b8 < \u03b8min\n                    \u03b8min = \u03b8\n                    kmin = k\n                end\n            end\n\n            # update the transport map\n            P[i, j] += \u03b8min\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] -= \u03b8min\n                    end\n                else\n                    P[LightGraphs.src(e), LightGraphs.dst(e) - n] += \u03b8min\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 \u2264 n && j \u2264 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 \u2264 n\n                r = T(a[i])\n            end\n        end\n\n        if iszero(c)\n            j += 1\n            if j \u2264 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\u2080 :: AbstractVector;\n                         \u03c4\u2080 :: Float64 = 0.0005,\n                         \u03f5  :: Float64 = 1e-6,\n                         maxiter :: Int = 200)\n\n    x = copy(x\u2080)\n    iter = 0\n    f, g = obj(nlp,x), grad(nlp, x)\n\n    while (norm(g, Inf) > \u03f5) && (iter <= maxiter)\n        H    = Matrix(Symmetric(hess(nlp, x),:L))\n        \u0394, O = eigen(H)\n\n        # Boost negative values of \u0394 to 1e-8\n        D = \u0394 .+ max.((1e-8 .- \u0394), 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 + \u03c4\u2080*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": "# Linear regression (using iterative update)\n\nusing Regression\nimport Regression: solve, Options\n\n\n# Data\n\nd = 5\nk = 3\nn = 1000\n\nW = randn(k, d+1)\nX = randn(d, n)\nY = (W[:, 1:d] * X .+ W[:,d+1]) + 0.2 * randn(k, n)\n\n# Solve\n\nret = solve(linearreg(X, Y; bias=1.0);\n            solver=GD(),\n            reg=SqrL2Reg(1.0e-3),\n            options=Options(verbosity=:iter, grtol=1.0e-6 * n))\n\nprintln()\n\n# Print results\n\nW_est = ret.sol\n@printf(\"relative error = %.4e\\n\", sumabs2(W_est - W) / sumabs2(W))\n", "meta": {"hexsha": "5779ae05b17a9266ac18e88bb5c6e799f6d6bb72", "size": 500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/linearreg.jl", "max_stars_repo_name": "JuliaPackageMirrors/Regression.jl", "max_stars_repo_head_hexsha": "4827d41c163a9d5bbbb53129b02b29446e6f8fd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2015-01-11T18:03:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T06:16:46.000Z", "max_issues_repo_path": "examples/linearreg.jl", "max_issues_repo_name": "JuliaPackageMirrors/Regression.jl", "max_issues_repo_head_hexsha": "4827d41c163a9d5bbbb53129b02b29446e6f8fd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-04-21T14:28:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:29:06.000Z", "max_forks_repo_path": "examples/linearreg.jl", "max_forks_repo_name": "JuliaPackageMirrors/Regression.jl", "max_forks_repo_head_hexsha": "4827d41c163a9d5bbbb53129b02b29446e6f8fd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2015-02-02T07:51:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T21:54:27.000Z", "avg_line_length": 16.6666666667, "max_line_length": 67, "alphanum_fraction": 0.578, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030095, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7566497059062935}}
{"text": "\n\nfunction bisection(f, xmin::T, xmax::T; config = Options()) where {T <: Number}\n    local x\u2080 = xmin\n    local x\u2081 = xmax\n    local x  = zero(T)\n\n    x\u2080 < x\u2081 || begin x\u2080, x\u2081 = x\u2081, x\u2080 end\n\n    local y\u2080 = f(x\u2080)\n    local y\u2081 = f(x\u2081)\n    local y  = zero(y\u2080)\n\n    # y\u2080 * y\u2081 \u2264 0 || error(\"Either no or multiple real roots in [xmin,xmax]\")\n\n    for j in 1:config.max_iterations\n        x = (x\u2080 + x\u2081) / 2\n        y = f(x)\n\n        # println(\"j = \", j, \" , x\u2080 = \", x\u2080, \" , x\u2081 = \", x\u2081)\n\n        !isapprox(y, zero(y), atol=config.f_abstol) || break\n\n        if y\u2080 * y > 0\n            x\u2080 = x  # Root is in the right half of [x\u2080,x\u2081].\n            y\u2080 = y\n        else\n            x\u2081 = x  # Root is in the left half of [x\u2080,x\u2081].\n            y\u2081 = y\n        end\n\n        !isapprox(x\u2081 - x\u2080, zero(x), atol=config.x_abstol) || break\n    end\n\n    # println(\"\u03b1=\", x, \", f(\u03b1)=\", y, \", ftol=\", config.f_abstol, \", abs(x\u2081-x\u2080)=\", abs(x\u2081-x\u2080), \", 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": "using DataFrames, RDatasets, Clustering\n\niris = data(\"datasets\", \"iris\")\n\nk = length(unique(iris[:, \"Species\"]))\n\nclusters = k_means(matrix(iris[:, 2:5]), k)\n\ndf = DataFrame()\ndf[\"Cluster\"] = clusters.assignments\ndf[\"Label\"] = iris[:, \"Species\"]\nhead(df)\n\n# Clustering doesn't work well using some of the numeric features\n# Let's try subsets of them to see what happens\ndf = DataFrame()\ndf[\"AllCluster\"] = k_means(matrix(iris[:, 2:5]), k).assignments\ndf[\"SepalCluster\"] = k_means(matrix(iris[:, 2:3]), k).assignments\ndf[\"PetalCluster\"] = k_means(matrix(iris[:, 4:5]), k).assignments\ndf[\"Label\"] = iris[:, \"Species\"]\n\nby(df, [\"Label\", \"AllCluster\", \"SepalCluster\", \"PetalCluster\"], nrow)\n\n# Beyond the k-means algorithm we can also use dp-means\nclusters = dp_means(matrix(iris[:, 2:5]), 5.0)\n", "meta": {"hexsha": "d9454c145f333288018915e2662c3ed58d4ed524", "size": 791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/obsoleted/iris.jl", "max_stars_repo_name": "pluskid/Clustering.jl", "max_stars_repo_head_hexsha": "99d8400b044cf8117143e34545ae0cb55a8f23e9", "max_stars_repo_licenses": ["MIT"], "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/obsoleted/iris.jl", "max_issues_repo_name": "pluskid/Clustering.jl", "max_issues_repo_head_hexsha": "99d8400b044cf8117143e34545ae0cb55a8f23e9", "max_issues_repo_licenses": ["MIT"], "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/obsoleted/iris.jl", "max_forks_repo_name": "pluskid/Clustering.jl", "max_forks_repo_head_hexsha": "99d8400b044cf8117143e34545ae0cb55a8f23e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-19T09:37:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-19T09:37:20.000Z", "avg_line_length": 30.4230769231, "max_line_length": 69, "alphanum_fraction": 0.6826801517, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7566496974572803}}
{"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 \u2208 \\\\mathbb{N}`` for which ``p^{(n)}_{i,i} > 0``.\nWritten more succinctly,\n```math\nd_i = \\\\text{gcd}\\\\{ n \u2208 \\\\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\u00d72 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": "using ModelingToolkit, ModelingToolkitStandardLibrary, OrdinaryDiffEq\nusing ModelingToolkitStandardLibrary.Blocks\n\n@parameters t\n\n#=\nTesting strategy:\nThe general strategy is to test systems using simple intputs where the solution\nis known on closed form. For algebraic systems (without differential variables),\nan integrator with a constant input is often used together with the system under test. \n=#\n\n@testset \"Constant\" begin\n    @named c = Constant(; k=1)\n    @named int = Integrator()\n    @named iosys = ODESystem(connect(c.output, int.input), t, systems=[int, c])\n    sys = structural_simplify(iosys)\n    prob = ODEProblem(sys, Pair[int.x=>1.0], (0.0, 1.0))\n    sol = solve(prob, Rodas4())\n    @test sol[int.output.u][end] \u2248 2\nend\n\n@testset \"Derivative\" begin\n    @named source = Sine(; frequency=1)\n    @named int = Integrator(; k=1)\n    @named der = Derivative(; k=1, T=0.001)\n    @named iosys = ODESystem([\n        connect(source.output, der.input),\n        connect(der.output, int.input),\n        ],\n        t,\n        systems=[int, source, der],\n    )\n    sys = structural_simplify(iosys)\n    prob = ODEProblem(sys, Pair[int.x=>0.0], (0.0, 10.0))\n    sol = solve(prob, Rodas4())\n    @test isapprox(sol[source.output.u], sol[int.output.u], atol=1e-1)\nend\n\n@testset \"PT1\" begin\n    pt1_func(t, k, T) = k * (1 - exp(-t / T)) # Known solution to first-order system\n    \n    k, T = 1.0, 0.1\n    @named c = Constant(; k=1)\n    @named pt1 = FirstOrder(; k=k, T=T)\n    @named iosys = ODESystem(connect(c.output, pt1.input), t, systems=[pt1, c])\n    sys = structural_simplify(iosys)\n    prob = ODEProblem(sys, Pair[], (0.0, 100.0))\n    sol = solve(prob, Rodas4())\n    @test sol[pt1.output.u] \u2248 pt1_func.(sol.t, k, T) atol=1e-3\nend\n\n@testset \"PT2\" begin\n    # Known solution to second-order system\n    function pt2_func(t, k, w, d)\n        y = if d==0\n            -k*(-1 + cos(t*w))\n        else\n            d = complex(d)\n            real(k*(1 + (-cosh(sqrt(-1 + d^2)*t*w) - (d*sinh(sqrt(-1 + d^2)*t*w))/sqrt(-1 + d^2))/exp(d*t*w)))\n        end\n    end\n\n    k, w, d = 1.0, 1.0, 0.5\n    @named c = Constant(; k=1)\n    @named pt2 = SecondOrder(; k=k, w=w, d=d)\n    @named iosys = ODESystem(connect(c.output, pt2.input), t, systems=[pt2, c])\n    sys = structural_simplify(iosys)\n    prob = ODEProblem(sys, Pair[], (0.0, 100.0))\n    sol = solve(prob, Rodas4())\n    @test sol[pt2.output.u] \u2248 pt2_func.(sol.t, k, w, d) atol=1e-3\nend\n\n@testset \"StateSpace\" begin\n    A = [0 1;-1 -0.5]\n    B = [0, 1]\n    C = [0.9 1;]\n    D = [0;;]\n    @named ss = StateSpace(;A,B,C,D,x_start=zeros(2))\n    @named c = Constant(; k=1)\n    @named model = ODESystem(\n        [\n           connect(c.output, ss.input),\n        ], \n        t, \n        systems=[ss, c]\n    )\n    sys = structural_simplify(model)\n    prob = ODEProblem(sys, Pair[], (0.0, 100.0))\n    sol = solve(prob, Rodas4())\n    # equilibrium point is at [1, 0]\n    @test sol[ss.x[1]][end] \u2248 1 atol=1e-3\n    @test sol[ss.x[2]][end] \u2248 0 atol=1e-3\nend\n\n\"\"\"Second order demo plant\"\"\"\nfunction Plant(;name, x_start=zeros(2))\n    @named input = RealInput()\n    @named output = RealOutput()\n    D = Differential(t)\n    sts = @variables x1(t)=x_start[1] x2(t)=x_start[2]\n    eqs= [\n        D(x1) ~ x2\n        D(x2) ~ -x1 - 0.5 * x2 + input.u\n        output.u ~ 0.9 * x1 + x2\n    ]\n    compose(ODESystem(eqs, t, sts, []; name), [input, output])\nend\n\n@testset \"PI\" begin\n    @named ref = Constant(; k=2)\n    @named pi_controller = PI(k=1, T=1)\n    @named plant = Plant()\n    @named fb = Feedback()\n    @named model = ODESystem(\n        [\n            connect(ref.output, fb.input1), \n            connect(plant.output, fb.input2),\n            connect(fb.output, pi_controller.err_input), \n            connect(pi_controller.ctr_output, plant.input), \n        ], \n        t, \n        systems=[pi_controller, plant, ref, fb]\n    )\n    sys = structural_simplify(model)\n    prob = ODEProblem(sys, Pair[], (0.0, 100.0))\n    sol = solve(prob, Rodas4())\n    @test sol[ref.output.u - plant.output.u][end] \u2248 0 atol=1e-3 # zero control error after 100s\nend\n\n@testset \"PID\" begin\n    @named ref = Constant(; k=2)\n    @named pid_controller = PID(k=3, Ti=0.5, Td=100)\n    @named plant = Plant()\n    @named fb = Feedback()\n    @named model = ODESystem(\n        [\n            connect(ref.output, fb.input1), \n            connect(plant.output, fb.input2),\n            connect(fb.output, pid_controller.err_input), \n            connect(pid_controller.ctr_output, plant.input), \n        ], \n        t, \n        systems=[pid_controller, plant, ref, fb]\n    )\n    sys = structural_simplify(model)\n    prob = ODEProblem(sys, Pair[], (0.0, 100.0))\n    sol = solve(prob, Rodas4())\n    @test sol[ref.output.u - plant.output.u][end] \u2248 0 atol=1e-3 # zero control error after 100s\nend\n\n@test_skip begin \n    k = 2\n    Ti = 0.5\n    Td = 0.7\n    wp = 1\n    wd = 1\n    Ni = \u221a(Td / Ti)\n    Nd = 12\n    y_max = Inf\n    y_min = -Inf\n    u_r = sin(t)\n    u_y = 0\n    function solve_with_input(; u_r, u_y, \n        controller = PID(; k, Ti, Td, wp, wd, Ni, Nd, y_max, y_min, name=:controller)\n    )\n        @test count(ModelingToolkit.isinput, states(controller)) == 5 # 2 in PID, 1 sat, 1 I, 1 D\n        @test count(ModelingToolkit.isoutput, states(controller)) == 4\n        # TODO: check number of unbound inputs when available, should be 2\n        @named iosys = ODESystem([controller.u_r~u_r, controller.u_y~u_y], t, systems=[controller])\n        sys = structural_simplify(iosys)\n        prob = ODEProblem(sys, Pair[], (0.0, 10.0))\n        sol = solve(prob, Rodas4(), saveat=0:0.1:10)\n        controller, sys, sol\n    end\n\n    # linearity in u_r\n    controller, sys, sol1 = solve_with_input(u_r=sin(t), u_y=0)\n    controller, sys, sol2 = solve_with_input(u_r=2sin(t), u_y=0)\n    @test sum(abs, sol1[controller.ea]) < eps() # This is the acutator model error due to saturation\n    @test 2sol1[controller.y] \u2248 sol2[controller.y] rtol=1e-3 # linearity in u_r\n\n    # linearity in u_y\n    controller, sys, sol1 = solve_with_input(u_y=sin(t), u_r=0)\n    controller, sys, sol2 = solve_with_input(u_y=2sin(t), u_r=0)\n    @test sum(abs, sol1[controller.ea]) < eps() # This is the acutator model error due to saturation\n    @test 2sol1[controller.y] \u2248 sol2[controller.y] rtol=1e-3 # linearity in u_y\n\n    # zero error\n    controller, sys, sol1 = solve_with_input(u_y=sin(t), u_r=sin(t))\n    @test sum(abs, sol1[controller.y]) \u2248 0 atol=sqrt(eps()) \n\n    # test saturation\n    controller, sys, sol1 = solve_with_input(; u_r=10sin(t), u_y=0, \n        controller = PID(; k, Ti, Td, wp, wd=0, Ni, Nd, y_max=10, y_min=-10, name=:controller)\n    )\n    @test extrema(sol1[controller.y]) == (-10, 10)\n\n\n    # test P set-point weighting\n    controller, sys, sol1 = solve_with_input(; u_r=sin(t), u_y=0, \n        controller = PID(; k, Ti, Td, wp=0, wd, Ni, Nd, y_max, y_min, name=:controller)\n    )\n    @test sum(abs, sol1[controller.ep]) \u2248 0 atol=sqrt(eps()) \n\n    # test D set-point weighting\n    controller, sys, sol1 = solve_with_input(; u_r=sin(t), u_y=0, \n        controller = PID(; k, Ti, Td, wp, wd=0, Ni, Nd, y_max, y_min, name=:controller)\n    )\n    @test sum(abs, sol1[controller.ed]) \u2248 0 atol=sqrt(eps()) \n\n\n    # zero integral gain\n    controller, sys, sol1 = solve_with_input(; u_r=sin(t), u_y=0, \n        controller = PID(; k, Ti=false, Td, wp, wd, Ni, Nd, y_max, y_min, name=:controller)\n    )\n    @test isapprox(sum(abs, sol1[controller.I.y]), 0, atol=sqrt(eps()))\n    \n\n    # zero derivative gain\n    @test_skip begin # During the resolution of the non-linear system, the evaluation of the following equation(s) resulted in a non-finite number: [5]\n        controller, sys, sol1 = solve_with_input(; u_r=sin(t), u_y=0, \n            controller = PID(; k, Ti, Td=false, wp, wd, Ni, Nd, y_max, y_min, name=:controller)\n        )\n        @test isapprox(sum(abs, sol1[controller.D.y]), 0, atol=sqrt(eps()))\n    end\n\n    # Tests below can be activated when the concept of unbound_inputs exists in MTK\n    # @test isequal(Set(unbound_inputs(controller)), @nonamespace(Set([controller.u_r, controller.u_y])))\n    # @test isempty(unbound_inputs(sys))\n    # @test isequal(bound_inputs(sys), inputs(sys))\n    # @test isequal(\n    #     Set(bound_inputs(sys)),\n    #     Set([controller.u_r, controller.u_y, controller.I.u, controller.D.u, controller.sat.u])\n    #     )\nend\n\n@testset \"LimPI\" begin\n    @named ref = Constant(; k=1)\n    @named pi_controller_lim = LimPI(k=3, T=0.5, u_max=1.5, u_min=-1.5, Ta=0.1)\n    @named pi_controller = PI(k=3, T=0.5)\n    @named sat = Limiter(y_max=1.5, y_min=-1.5)\n    @named plant = Plant()\n    @named fb = Feedback()\n\n    # without anti-windup measure\n    sol = let\n        @named model = ODESystem(\n            [\n                connect(ref.output, fb.input1), \n                connect(plant.output, fb.input2),\n                connect(fb.output, pi_controller.err_input), \n                connect(pi_controller.ctr_output, sat.input), \n                connect(sat.output, plant.input), \n            ], \n            t, \n            systems=[pi_controller, plant, ref, fb, sat]\n        )\n        sys = structural_simplify(model)\n        prob = ODEProblem(sys, Pair[], (0.0, 20.0))\n        sol = solve(prob, Rodas4())\n    end\n\n    # with anti-windup measure\n    sol_lim = let\n        @named model = ODESystem(\n            [\n                connect(ref.output, fb.input1), \n                connect(plant.output, fb.input2),\n                connect(fb.output, pi_controller_lim.err_input), \n                connect(pi_controller_lim.ctr_output, sat.input), \n                connect(sat.output, plant.input), \n            ], \n            t, \n            systems=[pi_controller_lim, plant, ref, fb, sat]\n        )\n        sys = structural_simplify(model)\n        prob = ODEProblem(sys, Pair[], (0.0, 20.0))\n        sol = solve(prob, Rodas4())\n    end\n\n    @test sol[ref.output.u - plant.output.u][end] \u2248 0 atol=1e-3 # zero control error after 100s\n    @test sol_lim[ref.output.u - plant.output.u][end] \u2248 0 atol=1e-3 # zero control error after 100s\n\n    # Plots.plot(sol; vars=[plant.output.u]) # without anti-windup measure\n    # Plots.plot!(sol_lim; vars=[plant.output.u]) # with anti-windup measure\nend\n\n@testset \"LimPID\" begin\n    @named ref = Constant(; k=1)\n    @named pid_controller = LimPID(k=3, Ti=0.5, Td=100, u_max=1.5, u_min=-1.5, Ni=0.1/0.5)\n    @named plant = Plant()\n    @named model = ODESystem(\n        [\n            connect(ref.output, pid_controller.reference), \n            connect(plant.output, pid_controller.measurement),\n            connect(pid_controller.ctr_output, plant.input), \n        ], \n        t, \n        systems=[pid_controller, plant, ref]\n    )\n    sys = structural_simplify(model)\n    prob = ODEProblem(sys, Pair[], (0.0, 100.0))\n    sol = solve(prob, Rodas4())\n\n    # Plots.plot(sol, vars=[plant.output.u, plant.input.u])\n    @test sol[ref.output.u - plant.output.u][end] \u2248 0 atol=1e-3 # zero control error after 100s\nend", "meta": {"hexsha": "cadc5fb08ae84166b6e5487fb58ac47658c0c528", "size": 10974, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Blocks/continuous.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": "test/Blocks/continuous.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": "test/Blocks/continuous.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": 35.6298701299, "max_line_length": 151, "alphanum_fraction": 0.5954073264, "num_tokens": 3439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.756617257068267}}
{"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\u2019s Optim package, which is a function MINIMIZER.\n    Thus, if we want to \ufb01nd the maximum of f(x), we need to minimize \u2212f(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\u2019re familiar with how Optim\u2019s optimize() function works, lets try it on some real-world data.\n    # Speci\ufb01cally, let\u2019s 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\u2019s 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\u2019t 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\ufb01ne 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 \u00b7 6 coef\ufb01cients, where K is the number of covariates in X.\n    It may help to transform the parameter vector into a K \u00d76 matrix (to more easily reference the \u03b1 j \u2019s for each j)\n\n    # You should reset the tolerance of the gradient (g tol) to be 10 to the \u22125.\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[\u22121,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, \u201cWhy don\u2019t we just use Stata or R, then?\u201d\n    The reason is because the models we will get to later in the course are much more dif\ufb01cult to implement in those languages, because they can\u2019t 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": "#******************************************************************************#\n#                               Introduction                                   #\n#******************************************************************************#\n\n# PyPlot is package for Julia that able you to use matplotlib library.\n\n# First step to start plotting in Julia using Pyplot is install PyPlot package.\n# You should do it only once.\n\nENV[\"PYTHON\"] = \"\"\nPkg.add(\"PyPlot\")\n\n# And start using PyPlot module.\nusing PyPlot\n\n# Now you can working.\n\n# To do plot use plot(): \n\nx = linspace(-2*\u03c0, 2*\u03c0, 2000) # Generating 2000 sclars from -2\u03c0 to 2\u03c0\ny = sin(x)\nplot(x,y)\n\n# If you need two lines in one plot:\n\nx = linspace(-2*\u03c0, 2*\u03c0, 2000) # Generating 2000 sclars from -2\u03c0 to 2\u03c0\ny = sin(x)\nz = cos(x)\nplot(x,y)\nplot(x,z)\n\n# But it's only raw chart. Let's describe it:\n\nplot(x,y, color = \"green\", linewidth = \"2.0\")\nplot(x,z, color = \"red\", linewidth = \"2.0\", \"--\")\ntitle(\"Sine wave\")\nylabel(\"Amplitude\")\nxlabel(\"Time\")\ngrid(true)\ntext(0, 0, \"0\")\nlegend([\"sin(x)\",\"cos(x)\"], loc = \"lower left\", fontsize = 12, borderpad = 0.3,\n    handlelength=3) \n\n# You can do subplots using subplot(nrows,ncols, plot_number):\n\nsinh = sinh(x)\ncosh = cosh(x)\n\nsubplot(221)\n    plot(x,y)\n    legend([\"sin(x)\"], fontsize = 8,  loc = \"best\" )\nsubplot(222)\n    plot(x,z)\n    legend([\"cos(x)\"], fontsize = 8,  loc = \"best\"  )\nsubplot(223)\n    plot(x,sinh)\n    legend([\"sinh(x)\"], fontsize = 8,  loc = \"best\"  )\nsubplot(224)\n    plot(x,cosh)\n    legend([\"cosh(x)\"], fontsize = 8,  loc = \"best\"  )\n    \n#******************************************************************************#\n#                               Scatter plots                                  #\n#******************************************************************************#    \n    \nn = 1024\nX = rand(1,1,n)\nY = rand(1,1,n)\ncolors = rand(1,1,n)\n\nscatter(X,Y, s = 50 ,c = colors) \nscatter(X,Y, s = 50 ,c = colors, marker = \"^\", alpha = .5) \n\n#******************************************************************************#\n#                                  Bar plots                                   #\n#******************************************************************************#\n    \nn = 15\nX = range(0,n)\nY1 = (1-X/n) * rand(1:n)\nY2 = (1-X/n) * rand(1:n)\naxes([0.025,0.025,0.95,0.95])\nbar(X, +Y1, facecolor=\"#9999ff\", edgecolor=\"white\")\nbar(X, -Y2, facecolor=\"#ff9999\", edgecolor=\"white\")    \nmargins(0.05) # 5% margins\n\n# Code below generating describe under or above each bar.\n\nfor (x,y) in zip(X,Y1)\n    text(x+0.4, y+0.05, \"$(round(y,2))\", ha=\"center\", va= \"bottom\")\nend\n\n\nfor (x,y) in zip(X,Y2)\n    text(x+0.4, -y-0.05, \"$(round(y,2))\",  ha=\"center\", va= \"top\")\nend\n    \n#******************************************************************************#\n#                               Contour plots                                  #\n#******************************************************************************#    \n\nf(x,y) = (1-x/2+x^5+y^3)*exp(-x^2-y^2)    \nn = 256\nx = linspace(-3,3,n) \ny = linspace(-3,3,n)   \nz = zeros(n,n)\nfor i in 1:n\n    for j in 1:n\n        z[i,j] = f(x[j],y[i])\n    end\nend\nX = repmat(x',n,1)\nY = repmat(y,1,n)    \n\ncontourf(X, Y, z, 8, alpha=.75, cmap=\"jet\")\n \n# Easier way to get contour plots is to use Gadfly package:\nPkg.add(\"Gadfly\")\n\nusing Gadfly\n\nplot((x,y) -> (1-x/2+x^5+y^3)*exp(-x^2-y^2), -4, 4, -4, 4)\n\n# You can use more parameters. To get more information about Gadfly contour \n# plots check this topic: https://github.com/dcjones/Gadfly.jl/issues/293\n\nplot((x,y) -> (1-x/2+x^5+y^3)*exp(-x^2-y^2), -4, 4, -4, 4, \n    Stat.contour(samples = 200, levels = linspace(-1,1,25)))\n    \n# In this example we used levels = linspace(-1,1,25) to show 25 lines from -1 \n# to 1 include 0. If you want to see more lines you can precise it in \n# levels parameter.\n    \n#******************************************************************************#\n#                                Pie charts                                    #\n#******************************************************************************#  \n\n# Back to using PyPlot\n\nusing PyPlot\n\nlabels = [\"PyPlot\";\"Plots\";\"Gadfly\"]\ncolors = [\"yellowgreen\";\"lightskyblue\";\"lightcoral\"]\nsizes = NaN*zeros(3)\nexplode = zeros(length(sizes))\nexplode[2] = 0.1 # Move slice 2 out by 0.1\nsizes = [80,15,10]\nfont = Dict(\"fontname\"=>\"Sans\",\"weight\"=>\"semibold\")\naxes([0.025,0.025,0.95,0.95])\npie(sizes,\n    labels=labels,\n    shadow=true,\n    startangle=90,\n    explode=explode,\n    colors=colors,\n    autopct=\"%1.1f%%\",\n    textprops=font\n)\n    \n#******************************************************************************#\n#                                   3D Plots                                   #\n#******************************************************************************#\n\n# Example no. 1\n\nf(x) = (x[1]^2 + x[2]^2)\n\nn = 100\nx = linspace(-1, 1, n)\ny = linspace(-1,1,n)\n\nxgrid = repmat(x',n,1)\nygrid = repmat(y,1,n)\n\nz = zeros(n,n)\n\nfor i in 1:n\n    for j in 1:n\n        z[i:i,j:j] = f([x[i],y[j]])\n    end\nend\n\n\nplot_wireframe(xgrid,ygrid,z) \n\n# Example no. 2\n\nf(x,y) = sin(x)*cos(y)\n\nn = 100\nx = linspace(-2, 2, n)\ny = linspace(-1, 1,n)\n\nxgrid = repmat(x',n,1)\nygrid = repmat(y,1,n)\n\nz = zeros(n,n)\nfor i in 1:n\n    for j in 1:n\n        z[i,j] = f(x[j],y[i])\n    end\nend\n\nplot_surface(xgrid,ygrid,z, rstride=1, cstride=1, cmap=\"coolwarm\",\n                       linewidth=0) \n                       \n# More 3D plots examples you can find there:\n# http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html\n \n#******************************************************************************#\n#                               Plots package                                  #\n#******************************************************************************#    \n    \n# You can use simpliest package - Plots.  \nPkg.add(\"Plots\")\n\nusing Plots\n\nx = linspace(-2*\u03c0, 2*\u03c0, 2000) # Generating 2000 scalars from -2\u03c0 to 2\u03c0\ny = sin(x)\nz = cos(x)\nplot(x,y)\nplot!(x,z)\n\n# You can find more about plots there:\n# https://en.wikibooks.org/wiki/Introducing_Julia/Plotting.\n\n# To master skill in PyPlot you should visit this link:\n# http://matplotlib.org/contents.html\n# If you prefer Gadfly, visit manual page:\n# http://gadflyjl.org/stable/\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    ", "meta": {"hexsha": "d00cdc204471898e3ad001693170dfcab726e73f", "size": 6305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plotting.jl", "max_stars_repo_name": "plon-io/Plotting-in-Julia", "max_stars_repo_head_hexsha": "630d2c7b6824267d4dd997b93a1c40069d18baff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plotting.jl", "max_issues_repo_name": "plon-io/Plotting-in-Julia", "max_issues_repo_head_hexsha": "630d2c7b6824267d4dd997b93a1c40069d18baff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plotting.jl", "max_forks_repo_name": "plon-io/Plotting-in-Julia", "max_forks_repo_head_hexsha": "630d2c7b6824267d4dd997b93a1c40069d18baff", "max_forks_repo_licenses": ["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.0537190083, "max_line_length": 84, "alphanum_fraction": 0.4459952419, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.756606036496812}}
{"text": "using Test\nusing LinearAlgebra\nusing NonNegLeastSquares\nusing SparseArrays\n\n#test specific\nusing Random\nusing PyCall\nconst pyopt = pyimport_conda(\"scipy.optimize\", \"scipy\")\n\nfunction test_algorithm(fh, \u03b5=1e-5)\n\t# Solve A*x = b for x, subject to x >=0\n\tA = [ 0.53879488  0.65816267\n\t      0.12873446  0.98669198\n\t      0.24555042  0.00598804\n\t      0.80491791  0.32793762 ]\n\n\tb = [0.888,  0.562,  0.255,  0.077]\n\tx = [0.15512102, 0.69328985] # approx solution from scipy\n\t@test norm(fh(A,b)-x) < \u03b5\n\n\t## A second test case\n\tA2 = [ -0.24  -0.82   1.35   0.36   0.35\n\t       -0.53  -0.20  -0.76   0.98  -0.54\n\t        0.22   1.25  -1.60  -1.37  -1.94\n\t       -0.51  -0.56  -0.08   0.96   0.46\n\t        0.48  -2.25   0.38   0.06  -1.29 ]\n\tb2 = [-1.6,  0.19,  0.17,  0.31, -1.27]\n\tx2 = [2.2010416, 1.19009924, 0.0, 1.55001345, 0.0]\n\t@test norm(fh(A2,b2)-x2) < \u03b5\n\n\t## Test a bunch of random cases\n\tfor i = 1:100\n\t\tm,n = rand(1:10),rand(1:10)\n\t\tA3 = randn(m,n)\n\t\tb3 = randn(m)\n\t\tx3,resid = pyopt.nnls(A3,b3)\n\t\tif resid > \u03b5\n\t        @test norm(fh(A3,b3)-x3) < \u03b5\n\t    else\n\t    \t@test norm(A3*fh(A3,b3)-b3) < \u03b5\n\t    end\n\tend\nend\n\nnnls(A,b) = nonneg_lsq(A, b; alg=:nnls)\nnnls_gram(A,b) = nonneg_lsq(A'*A, A'*b; alg=:nnls, gram=true)\nfnnls(A,b) = nonneg_lsq(A, b; alg=:fnnls)\nfnnls_gram(A,b) = nonneg_lsq(A'*A, A'*b; alg=:fnnls, gram=true)\npivot(A,b) = nonneg_lsq(A, b; alg=:pivot)\npivot_comb(A,b) = nonneg_lsq(A, b; alg=:pivot, variant=:comb)\npivot_cache(A,b) = nonneg_lsq(A, b; alg=:pivot, variant=:cache)\n\nalgs = [nnls, nnls_gram, fnnls, fnnls_gram, pivot, pivot_comb, pivot_cache]\nerrs = fill(1e-5, length(algs))\n\nfor (f, \u03b5) in zip(algs, errs)\n \tprint(\"testing \")\n \t@show f\n \ttest_algorithm(f, \u03b5)\n \tprintln(\"done\")\nend\n\n@testset \"NNLS\" begin include(\"nnls_test.jl\") end\n@testset \"FNNLS\" begin include(\"fnnls_test.jl\") end\n@testset \"Pivot\" begin include(\"pivot_test.jl\") end\n@testset \"Sparse\" begin include(\"sparse_test.jl\") end\n@testset \"CoordinateDescent\" begin include(\"cd_test.jl\") end\n", "meta": {"hexsha": "11185ff3d6720ef416fd6a4d8c05251ca4dd77ba", "size": 1981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "caseykneale/NonNegLeastSquares.jl", "max_stars_repo_head_hexsha": "0e368e9e989a00fb170018c80d48c6d739b07034", "max_stars_repo_licenses": ["MIT"], "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": "caseykneale/NonNegLeastSquares.jl", "max_issues_repo_head_hexsha": "0e368e9e989a00fb170018c80d48c6d739b07034", "max_issues_repo_licenses": ["MIT"], "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": "caseykneale/NonNegLeastSquares.jl", "max_forks_repo_head_hexsha": "0e368e9e989a00fb170018c80d48c6d739b07034", "max_forks_repo_licenses": ["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.7101449275, "max_line_length": 75, "alphanum_fraction": 0.6234225139, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.756606028016947}}
{"text": "#  function survivor_prob(evals,sp,nsvt)\n#  \n#    n = size(evals)[1]\n#    l = size(evals)[2]\n#    pdt = zeros(Float64, n, l)\n#\n#    for i in 1:l\n#      for j in 1:n\n#        if evals[j,i] == 0\n#          pdt[j,i] = 0\n#        else\n#          pdt[j,i] = evals[j,i] / sp[j,i]\n#        end \n#      end\n#    end\n#    final = sum(pdt,dims=2) / nsvt\n#    return final\n#\n#  end\n#\n\n  function survivor_prob(evals,sp,nsvt)\n    ev = sum(evals,dims=2) / nsvt  \n    ea = sum(sp, dims=2) / nsvt\n   \n    l     = length(ev)\n    final = zeros(Float64, l) \n\n    for i in 1:l\n      if ev[i]==0\n        final[i] = 0.\n      else\n        final[i] = ev[i] / ea[i]\n      end\n    end\n\n   # final = ev ./ ea   \n    return final\n  end\n\n", "meta": {"hexsha": "3c919210d946c41f1e252dfa42a6cfd21b63008c", "size": 710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/survivor_prob.jl", "max_stars_repo_name": "viniciuspiccoli/ResidenceTime.jl", "max_stars_repo_head_hexsha": "6bdb829a434206b4fc2ae5292d641048e7d53126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/survivor_prob.jl", "max_issues_repo_name": "viniciuspiccoli/ResidenceTime.jl", "max_issues_repo_head_hexsha": "6bdb829a434206b4fc2ae5292d641048e7d53126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-06-11T16:27:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T14:23:25.000Z", "max_forks_repo_path": "src/survivor_prob.jl", "max_forks_repo_name": "viniciuspiccoli/ResidenceTime.jl", "max_forks_repo_head_hexsha": "6bdb829a434206b4fc2ae5292d641048e7d53126", "max_forks_repo_licenses": ["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.3170731707, "max_line_length": 42, "alphanum_fraction": 0.4591549296, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7566060276629747}}
{"text": "\n\nsrand(1)\n\nlet\n@testset \"orthogonality $((m, n))\" for (m, n) in ((5, 5), (10, 4), (3, 7)) \n    X = randorth(m, n)\n    @test isorth(X)\nend\n\n\n@testset \"singular values $((m, n))\" for (m, n) in ((5, 5), (10, 4), (3, 7)) \n    sv = [0.01; 1.0; 0.1]\n    k = min(m, n)\n    X = randrealsv(sv, m, n)\n    U, S, V = svd(X)\n    @test S \u2248 sort([sv; zeros(k-length(sv))], rev=true)\n    @test size(U) == (m, k)\n    @test size(V) == (n, k)\nend\n\n@testset \"sparse matrices $((m, n, k))\" for (m, n, k) in ((10, 5, 3), (5, 10, 4))\n    X = randsparse(m, n, k, 0.3)\n    @test count(diag(qrfact(X).R) .!= 0) == k\nend\n\n\nend # let\n\n", "meta": {"hexsha": "0ccfdc8c16eb7fbd4814d703006311517bdfa518", "size": 608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/randutils.jl", "max_stars_repo_name": "KlausC/LinAlgExtensions.jl", "max_stars_repo_head_hexsha": "23b549d5ddd5f75bc012eb8f784cb7f3a14ff49f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-02T22:33:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-08T08:00:44.000Z", "max_issues_repo_path": "test/randutils.jl", "max_issues_repo_name": "KlausC/LinAlgExtensions.jl", "max_issues_repo_head_hexsha": "23b549d5ddd5f75bc012eb8f784cb7f3a14ff49f", "max_issues_repo_licenses": ["MIT"], "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/randutils.jl", "max_forks_repo_name": "KlausC/LinAlgExtensions.jl", "max_forks_repo_head_hexsha": "23b549d5ddd5f75bc012eb8f784cb7f3a14ff49f", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 81, "alphanum_fraction": 0.4753289474, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7565812228869998}}
{"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\u211cD(x::Float64, y::Float64, v::Float64, w::Float64, \u03b2::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 \u03b1 Frohlich coupling. \u03b2 is the reduced thermodynamical beta = \u0127\u03c9/kT with k being Boltzman's constant.\n\"\"\"\nfunction \u211cD(x, y, v, w, \u03b2)\n    R = (v^2 - w^2) / (w^2 * v)\n    P = 1 / (exp(v * \u03b2) - 1)\n    w^2 / v^2 * (\n        R * cos(v * x) * (exp(-v * y) + 2 * P * cosh(v * y)) - (x^2 - y^2) / \u03b2 - y -\n        R * (2 * P + 1)\n    )\nend\n\n\"\"\"\n\u2111D(x::Float64, y::Float64, v::Float64, w::Float64, \u03b2::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 \u03b1 Frohlich coupling. \u03b2 is the reduced thermodynamical beta = \u0127\u03c9/kT with k being Boltzman's constant.\n\"\"\"\nfunction \u2111D(x, y, v, w, \u03b2)\n    R = (v^2 - w^2) / (w^2 * v)\n    P = 1 / (exp(v * \u03b2) - 1)\n    w^2 / v^2 * (R * sin(v * x) * (exp(-v * y) - 2 * P * sinh(v * y)) - x * (2 * y / \u03b2 - 1))\nend\n\n# Create a complex number from the real and imaginary parts of D(u).\n\nD(x, y, v, w, \u03b2) = \u211cD(x, y, v, w, \u03b2) + 1im * \u2111D(x, y, v, w, \u03b2)\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\u03bb,\n       charA,\n       charB\n\"\"\"\nchar\u03bb(q,\u03bd,k)\n\nchar value \u03bb_(\u03bd+k) for Mathieu's equation\n\ny'' + (\u03bb_(\u03bd+k) - 2 q cos( 2z )) y = 0\n\nwhere\n\nq \u2208 \u211d       - parameter\n\u03bd \u2208 [-1,1]  - fractional part of the non-integer order\nk \u2208 \u2124\u207a      - range of integer parts of the order\n\n\"\"\"\nfunction char\u03bb(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 \u2208 \u211d  - parameter\nk \u2208 \u2124\u207a - 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\u03bb(abs(q), 0.0; k = k1)[ie]\n    if q>=0\n        a[io] = char\u03bb(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\u03bb(abs(q), one(q); k = k[2]:last(k))[io[2:end]]\n        else\n            a[io] = char\u03bb(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 \u2208 \u211d  - parameter\nk \u2208 \u2124  - 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\u03bb(q,0.0,k=k)[ie]\n    if q>=0\n        b[io] = char\u03bb(q,1.0,k=k)[io]\n    else\n        b[io] = char\u03bb(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.(\u03c0 .* x) .* sin.(\u03c0 .* y) .* sin.(\u03c0 .* z)\n\nfunction advection_dominated(;N = 50, \u03b2 = 1000.0)\n    # Problem: \u0394u + \u03b2u\u2093 = f\n    # u = 0 on the boundaries\n    # f(x, y, z) = exp(xyz) sin(\u03c0x) sin(\u03c0y) sin(\u03c0z)\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    \u0394 = laplace_matrix(Float64, N, 3) ./ -h^2\n\n    # And the dx bit.\n    \u2202x_1d = spdiagm(-1 => fill(-\u03b2 / 2h, N - 1), 1 => fill(\u03b2 / 2h, N - 1))\n    \u2202x = kron(speye(N^2), \u2202x_1d)\n\n    # Final matrix and rhs.\n    A = \u0394 + \u2202x\n    b = reshape([f(x, y, z) for x \u2208 xs, y \u2208 xs, z \u2208 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 \u00f7 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) \u00f7 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        \u03bc = 1\n        k = 1\n        while x != 0\n            if x & 1 == 1\n                d \u00f7= p[k]\n                \u03bc = -\u03bc\n            end\n            x >>= 1\n            k += 1\n        end\n        s += q^d * \u03bc\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": "# first example 2D\n\nusing ApproxManifoldProducts\nusing Test\n\nconst AMP = ApproxManifoldProducts\n\n\u039b1 = 1.0\n\u039b2 = 0.25\n\u039b3 = 5/4.0\n\n\u03bc1 = 1.0\n\u03bc2 = 4.0\n\u03bc3 = 2.4\n\n\n@testset \"basic linear 1D find mu and Lambdas Gaussian product test...\" begin\n\nLambdas = [\u039b1; \u039b2]\nmus = [\u03bc1; \u03bc2]\n\nresid2DLinear(0.0, mus, Lambdas)\n\nresid2DLinear(8/5, mus, Lambdas)\n\n\u03bc = get2DMu(mus, Lambdas)\n\u039b = get2DLambda(Lambdas)\n\n@test abs(\u03bc[1] - 8/5) < 1e-10\n\n@test abs(\u039b - 5/4) < 1e-10\n\nend\n\n## These work, but we are not sure about how to get the scale for product of more than 2 elements\n\n# preS = nullspace(Lambdas*(Lambdas'))\n#\n# sc = sum(abs.(preS)) / abs(\u03bc1-\u03bc2)\n#\n# mu = vec(preS / sc)\n# \u039b = get\u039b(Lambdas)\n#\n#\n# u,s,v = svd(Lambdas*(Lambdas'))\n#\n# s[1,1]*u[:,2]\n\n@testset \"test 1D with 3 components on basic Euclidean line...\" begin\n\nLambdas = [\u039b1; \u039b2; \u039b3]\nmus = [\u03bc1; \u03bc2; \u03bc3]\n\n\u03bc = get2DMu(mus, Lambdas)\n\u039b = get2DLambda(Lambdas)\n\n@test abs(\u03bc[1] - 2.0) < 1e-10\n\n@test abs(\u039b - 10/4) < 1e-10\n\n\nend\n\n\n\n\n#\n", "meta": {"hexsha": "a9ca8c5fd0b06437f810462aa8cf7edf8c719161", "size": 969, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ex_1D.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": "test/ex_1D.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": "test/ex_1D.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": 14.25, "max_line_length": 97, "alphanum_fraction": 0.6357069143, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7565812077578941}}
{"text": "using FractionalCalculus\nusing Plots, LaTeXStrings\n\ns=\"\\$(x^2)'=2x\\$\"\n\ntspan=collect(0:0.01:3)\n\nresult=fracdiff(x->x^2, 1, 3, 0.01, RLDiff_Matrix())\n\nplot(tspan, result, title=s, legend=:bottomright)", "meta": {"hexsha": "b5f2acc394867466e64d642fcd4b1f707c5661b0", "size": 199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/integer_order_derivative_example.jl", "max_stars_repo_name": "ERIKQQY6/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "cbe7489aec9bc51cf7387767eeec687837e4a7ac", "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": "example/integer_order_derivative_example.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": "example/integer_order_derivative_example.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": 19.9, "max_line_length": 52, "alphanum_fraction": 0.7035175879, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8104789178257653, "lm_q1q2_score": 0.7565259965901828}}
{"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": "function disc_phantom(img, a, b, r)\n    height, width = size(img)\n    #find the possibility which has most surrounding pixels\n    disc = zeros(Float64, (height,width))\n    for x = 1:width\n        for y = 1:height\n            disc[y,x] = (x-a)^2 + (y-b)^2 < r^2 ? 1.0 : 0.0\n        end\n    end\n    return disc\nend\n", "meta": {"hexsha": "0d9e34aafc77cfae3e347badb3ba1507c70fd750", "size": 313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contrib/phantoms/simple_phantoms.jl", "max_stars_repo_name": "JuliaTomo/DynamicTomographyWithFlow", "max_stars_repo_head_hexsha": "54ba084a96e399bb275c1eb14d7574a49f75e6c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-05T15:35:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T04:57:11.000Z", "max_issues_repo_path": "contrib/phantoms/simple_phantoms.jl", "max_issues_repo_name": "JuliaTomo/DynamicTomographyWithFlow", "max_issues_repo_head_hexsha": "54ba084a96e399bb275c1eb14d7574a49f75e6c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-02-07T08:36:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-23T10:06:06.000Z", "max_forks_repo_path": "contrib/phantoms/simple_phantoms.jl", "max_forks_repo_name": "JuliaTomo/DynamicTomographyWithFlow", "max_forks_repo_head_hexsha": "54ba084a96e399bb275c1eb14d7574a49f75e6c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-23T18:56:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-23T18:56:11.000Z", "avg_line_length": 26.0833333333, "max_line_length": 59, "alphanum_fraction": 0.5623003195, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7565259923171969}}
{"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(\u2264(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] \u2260 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 \u03bcs (45 allocations: 5.47 KiB)\n939490236001473\n\njulia> @btime time_stamp_CRG(list[2])\n  15.109 \u03bcs (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\u1d62 x\u1d62,   \u2200 i=1:length(x) s.th. x\u1d62 > 0`\n\nare equivalent to \n    `t = n\u2081x\u2081 = n\u2082x\u2082 - 1 = \u22ef = n\u1d62x\u1d62 - i + 1,     \u2200 i, with x\u1d62 > 0`\n\nAnd we know that `x\u2081 > 0`. Hence we just iterate over `i` to find\n\n    `For i = 1:\n        n\u2081\u00b9 = 1\n    For i = 2:\n        n\u2082\u00b2 such that n\u2082\u00b2x\u2082 - 1 = jn\u2081\u00b9x\u2081\n        n\u2081\u00b2 = j\u2082\u00b2n\u2081\u00b9\n    For i = 3:\n        n\u2083\u00b3 such that n\u2083\u00b3x\u2082 - 2 = jn\u2081\u00b2x\u2081\n        n\u2081\u00b2 = jn\u2081\u00b2\n    `n\u2081 such that t = n\u2081 x\u2081`\n    `n\u2082 such that n\u2082x\u2082 - 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\u2081); t = x\u2082-1 (mod x\u2082); \u2026 t = x\u1d62+1-i (mod x\u1d62); \u2026`\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\u1d62) = a\u1d62, \u2200i=1,\u2026,n, if 0 \u2264 a\u1d62< x\u1d62 \n    and the x\u1d62 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": "\n\nfunction inner_product(a1, a2)\n  somme = 0\n  for (word1, count1) in a1\n    for (word2, count2) in a2\n      if word2 == word1\n        somme += count1 * count2\n        break\n      end\n    end\n  end\n  return somme\nend\n\nfunction len(a)\n  return \u221a(innter_product(a, a))\nend\n\nfunction \u03b8(a1, a2)\n  cos\u03b8 = inner_product(a1, a2) / \u221a(inner_product(a1, a1) * inner_product(a2, a2))\n  return acos(cos\u03b8)\nend\n\n\n", "meta": {"hexsha": "d1ce4fabc879e40ca034bf89511cef80e7f7d425", "size": 399, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mit/6.006/2011/fall/recitations/02-doc_dist/docdist1.jl", "max_stars_repo_name": "phunc20/algorithms", "max_stars_repo_head_hexsha": "04674829311cde7bb173252b8a41620aae4b14ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mit/6.006/2011/fall/recitations/02-doc_dist/docdist1.jl", "max_issues_repo_name": "phunc20/algorithms", "max_issues_repo_head_hexsha": "04674829311cde7bb173252b8a41620aae4b14ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mit/6.006/2011/fall/recitations/02-doc_dist/docdist1.jl", "max_forks_repo_name": "phunc20/algorithms", "max_forks_repo_head_hexsha": "04674829311cde7bb173252b8a41620aae4b14ba", "max_forks_repo_licenses": ["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.3461538462, "max_line_length": 81, "alphanum_fraction": 0.6165413534, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7565259809991217}}
{"text": "using StructuresKit\n\nE = 29000.0\n\u03c3y = 50.0                   #steel yield stress\n\u03c3y1 = 50.0                  #steel yield stress\n\u03c3u = 65.3                   #steel ultimate stress\n\u03c3f=\u03c3y * (1 + 0.10)      #steel fracture stress#\n\u03f5y = \u03c3y / E              #steel yield strain\n\u03f5y1 = \u03c3y / E * 10    #steel strain at end of yield plateau\n\u03f5u = 0.18             #steel ultimate strain\n\u03f5f = 0.21             #steel fracture strain\nn = 11\n\n\n\n\u03c3, \u03f5  = MaterialModels.steel(\u03c3y, \u03c3y1, \u03c3u, \u03c3f, \u03f5y, \u03f5y1, \u03f5u, \u03f5f, n)\n\nusing Plots\nplot(\u03c3, \u03f5, 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": "@testset \"Testing matrix_eqn.jl\" begin\n    rough_kwargs = Dict(:atol => 1e-7, :rtol => 1e-7)\n\n    @testset \"simple test where X is all zero\" begin\n        A = Matrix(I, 4, 4) .* .95\n        B = zeros(4, 4)\n\n        X = solve_discrete_lyapunov(A, B)\n\n        @test X == (B)\n    end\n\n    @testset \"simple test where X is same as B\" begin\n        A = fill(0.5, 2, 2)\n        B = [.5 -.5; -.5 .5]\n\n        X = solve_discrete_lyapunov(A, B)\n\n        @test X == (B)\n    end\n\n    @testset \"simple_ones lyap\" begin\n        A = zeros(4, 4)\n        B = ones(4, 4)\n\n        sol = solve_discrete_lyapunov(A, B)\n\n        @test sol == (B)\n    end\n\n    @testset \"scalars lyap\" begin\n        a, b = 0.5, 0.75\n        sol = solve_discrete_lyapunov(a, b)\n\n        @test sol == ones(1, 1)\n    end\n\n    @testset \"testing ricatti golden_num_float\" begin\n        val = solve_discrete_riccati(1.0, 1.0, 1.0, 1.0)\n        gold_ratio = (1 + sqrt(5)) / 2.\n        @test isapprox(val[1], gold_ratio; rough_kwargs...)\n    end\n\n    @testset \"testing ricatti golden_num_2d\" begin\n        If64 = Matrix{Float64}(I, 2, 2)\n        A, B, R, Q = If64, If64, If64, If64\n        gold_diag = If64 .* (1 + sqrt(5)) ./ 2.\n        val = solve_discrete_riccati(A, B, Q, R)\n        @test isapprox(val, gold_diag; rough_kwargs...)\n    end\n\n    @testset \"test tjm 1\" begin\n        A = [0.0 0.1 0.0\n             0.0 0.0 0.1\n             0.0 0.0 0.0]\n        B = [1.0 0.0\n             0.0 0.0\n             0.0 1.0]\n        Q = [10^5 0.0 0.0\n             0.0 10^3 0.0\n             0.0 0.0 -10.0]\n        R = [0.0 0.0\n             0.0 1.0]\n        X = solve_discrete_riccati(A, B, Q, R)\n        Y = diagm(0 => [1e5, 1e3, 0.0])\n\n        @test isapprox(X, Y; rough_kwargs...)\n    end\n\n    @testset \"test tjm 2\" begin\n        A = [0.0 -1.0\n             0.0 2.0]\n        B = [1.0 0.0\n             1.0 1.0]\n        Q = [1.0 0.0\n             0.0 0.0]\n        R = [4.0 2.0\n             2.0 1.0]\n        X = solve_discrete_riccati(A, B, Q, R)\n        Y = zeros(2, 2)\n        Y[1, 1] = 1\n        @test isapprox(X, Y; rough_kwargs...)\n    end\n\n    @testset \"test tjm 3\" begin\n        r = 0.5\n        Im = Matrix{Float64}(I, 2, 2)\n        A = [2.0+r^2 0.0\n             0.0     0.0]\n        B = Im\n        R = [1.0 r\n             r   r*r]\n        Q = Im - A' * A + A' * ((R + Im) \\ A)\n        X = solve_discrete_riccati(A, B, Q, R)\n        Y = Im\n        @test isapprox(X, Y; rough_kwargs...)\n    end\n\nend  # @testset\n", "meta": {"hexsha": "19d4e10aae6705454974a45ffd4266e841cd545c", "size": 2457, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_matrix_eqn.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": "test/test_matrix_eqn.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": "test/test_matrix_eqn.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.57, "max_line_length": 59, "alphanum_fraction": 0.452991453, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7565259786329621}}
{"text": "\"\"\"\nBetina Robust Sampled based Formulation\n\nFurther information:\n  - Fernandes, B., Street, A., ValladA\u02dc \u00a3o, 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 \u2013 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    \u03b8 = @variable(model, \u03b8)\n    # convex hull\n    @constraint(model, sum(formulation.sampled_returns * w , dims=2) .>= \u03b8)\n\n    return \u03b8\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, \u03be, \u03b7)\n        X, Y = tan(\u03c0 * \u03be / 4), tan(\u03c0 * \u03b7 / 4)\n        \u03b61 = sR / sqrt(X^2 + Y^2 + 1)\n        \u03b62, \u03b63 = X * \u03b61, Y * \u03b61\n        \u03b61, \u03b62, \u03b63\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\u03be\u00b9, \u03c9\u00b9 = GaussQuadrature.legendre(N, GaussQuadrature.both)\n\u03be\u00b2 = copy(\u03be\u00b9)\n\u03be\u00b3 = copy(\u03be\u00b9)\n\nNe = 12\nvertices = collect(range(-1, 1, length = Ne + 1))\nx\u00b9 = zeros(N, Ne)\nx\u00b2 = copy(x\u00b9)\nx\u00b3 = copy(x\u00b9)\n\nfor e in 1:Ne\n    @. x\u00b9[:, e] = (\u03be\u00b9 + 1) / 2 * (vertices[e+1] - vertices[e]) + vertices[e]\n    @. x\u00b2[:, e] = (\u03be\u00b9 + 1) / 2 * (vertices[e+1] - vertices[e]) + vertices[e]\n    @. x\u00b3[:, e] = (\u03be\u00b9 + 1) / 2 * (vertices[e+1] - vertices[e]) + vertices[e]\nend\n\nNex = Ney = Ne\nface1 = [(x\u00b9[1], x\u00b2[j, ex], x\u00b3[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\u00b9[end], x\u00b2[j, ex], x\u00b3[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\u00b9[j, ey], x\u00b2[1], x\u00b3[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\u00b9[j, ey], x\u00b2[end], x\u00b3[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\u00b9[j, ex], x\u00b2[k, ey], x\u00b3[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\u00b9[j, ex], x\u00b2[k, ey], x\u00b3[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], (\u03c0/12, \u03c0, 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, \u03bc_G[g in set_generators]>= 0)\n@variable(m, \u03bc_D[d in set_demands]>= 0)\n@variable(m, \u03b7_lower[link in links]>= 0)\n@variable(m, \u03b7_upper[link in links]>= 0)\n@variable(m, \u03bb[set_nodes])\n@variable(m, \u03b3)\n\n@objective(m, Min,     sum(\u03bc_D[d]*demands[d,load_node]  for d in set_demands) +\n                       sum(\u03bc_G[g]*generators[g,capacity]  for g in set_generators)+\n                       sum(F_max_dict[j]*(\u03b7_lower[j]+\u03b7_upper[j])   for j in links)\n                       )\n\n\n@constraint(m, constraint1[d in set_demands], -demands[d,utility_node]+ \u03bc_D[d]+\u03bb[MapD[d][2]]>= 0)\n\n@constraint(m, constraint2[g in set_generators], generators[g,varcost]+ \u03bc_G[g]-\u03bb[MapG[g][2]]>= 0)\n\n#@constraint(m, constraint3[n in set_nodes_ref],     sum(B_dict[j]*(\u03bb[j[1]]-\u03bb[j[2]]+\u03b7_upper[j] -\u03b7_lower[j]) for j in links if n == j[1])\n#                                                     +\u03b3 == 0)\n\n@constraint(m, constraint3[n in set_nodes_ref],     sum(B_dict[j]*(\u03bb[j[1]]-\u03bb[j[2]]+\u03b7_upper[j] -\u03b7_lower[j]) for j in links if n == j[1])\n                                                      +sum(B_dict[j]*(-\u03b7_upper[j] +\u03b7_lower[j]) for j in links_rev if n == j[2] )+\u03b3 == 0)\n\n#@constraint(m, constraint4[n in set_nodes_noref],  sum(B_dict[j]*(\u03bb[j[1]]-\u03bb[j[2]]+\u03b7_upper[j] -\u03b7_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]*(\u03bb[j[1]]-\u03bb[j[2]]+\u03b7_upper[j] -\u03b7_lower[j]) for j in links if n == j[1])\n                                                      +sum(B_dict[j]*(-\u03b7_upper[j] +\u03b7_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\u03bb_value=zeros(length(set_nodes))\nfor n in set_nodes\n  \u03bb_value[n]=JuMP.value.(\u03bb[n])\nend\nprintln(\"Electricity Price:\",\u03bb_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,\u03bb_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\u00e5\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": "using ValidatedNumerics\nusing FactCheck\n\n\nA =\n    [\n        @interval( 2, 4)    @interval(-2, 1) ;\n        @interval(-1, 2)    @interval( 2, 4)\n    ]\n\nb =\n    [\n        @interval(-2, 2),\n        @interval(-2, 2)\n    ]\n\n\nfacts(\"Linear algebra with intervals tests\") do\n\n    @fact A * b -->\n        [\n            @interval(-12, 12),\n            @interval(-12, 12)\n        ]\n\n    # Example from Moore et al., Introduction to Interval Analysis (2009), pg. 88:\n\n    @fact A \\ b -->\n        [\n            @interval(-5, 5),\n            @interval(-4, 4)\n        ]\n\nend\n", "meta": {"hexsha": "3437b8bdbb0392a5e210b12acc165b21e794bb7b", "size": 561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interval_tests/linear_algebra.jl", "max_stars_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_stars_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/interval_tests/linear_algebra.jl", "max_issues_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_issues_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/interval_tests/linear_algebra.jl", "max_forks_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_forks_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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.0285714286, "max_line_length": 82, "alphanum_fraction": 0.4509803922, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7565086183564051}}
{"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": "using ModelingToolkit, OrdinaryDiffEq, Test\r\n\r\n@parameters t g e b\r\n@variables v(t) w(t) F(t)\r\n@derivatives D'~t\r\nsingle_neuron_eqs = [\r\n    D(v) ~ min(max(-2 - v, v), 2 - v) - w + F, # add the flux term\r\n    D(w) ~ e * (v - g * w + b)\r\n]\r\nn1 = ODESystem(single_neuron_eqs, t, [v,w,F],[g,e,b], name = :n1)\r\nn2 = ODESystem(single_neuron_eqs, t, [v,w,F],[g,e,b], name = :n2)\r\n@parameters D Dk\r\nconnections = [\r\n    0 ~ n1.F - D * Dk * max(n1.v - n2.v, 0)\r\n    0 ~ n2.F - D * max(n2.v - n1.v, 0)\r\n]\r\nconnected = ODESystem(connections,t,[],[D,Dk],systems=[n1,n2],name=:connected)\r\n\r\nu0 = [\r\n    n1.v => -2,\r\n    n1.w => -2/3,\r\n    n1.F => 0,\r\n    n2.v => -2,\r\n    n2.w => -.7,\r\n    n2.F => 0,\r\n]\r\ntspan = (0.0, 1750.0)\r\np0 = [\r\n    n1.g => 0.8,\r\n    n1.e => 0.04,\r\n    n1.b => 0,\r\n    n2.g => 0.8,\r\n    n2.e => 0.04,\r\n    n2.b => 0.2,\r\n    D => 0.047,\r\n    Dk => 1\r\n]\r\n\r\nprob = ODEProblem(connected, u0, tspan, p0)\r\nsol = solve(prob,Rodas5(),initializealg=BrownFullBasicInit())\r\n@test prob.u0 == sol[1]\r\nsol = solve(prob,Rodas5(),initiailizealg=ShampineCollocationInit())\r\n@test prob.u0 == sol[1]\r\n", "meta": {"hexsha": "09f2aa0bc798b01dac113987b881bdf568f4f429", "size": 1094, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interface/dae_initialize_integration.jl", "max_stars_repo_name": "ordicker/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "6fdc99fa4da79633e0161f0bb8aaff3f39cd39bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216, "max_stars_repo_stars_event_min_datetime": "2020-04-09T12:02:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:51:07.000Z", "max_issues_repo_path": "test/interface/dae_initialize_integration.jl", "max_issues_repo_name": "ordicker/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "6fdc99fa4da79633e0161f0bb8aaff3f39cd39bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 989, "max_issues_repo_issues_event_min_datetime": "2016-10-28T08:06:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-24T21:58:37.000Z", "max_forks_repo_path": "test/interface/dae_initialize_integration.jl", "max_forks_repo_name": "ordicker/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "6fdc99fa4da79633e0161f0bb8aaff3f39cd39bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 109, "max_forks_repo_forks_event_min_datetime": "2016-10-27T18:21:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-21T10:38:08.000Z", "avg_line_length": 24.8636363636, "max_line_length": 79, "alphanum_fraction": 0.5228519196, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7564444050119571}}
{"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 \u03b1 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    \u03b1_candidates = start:step:stop\n    mel = melscale_vector(fs, numpoints)\n    distances = [rms_distance(mel, warping_vector(\u03b1, numpoints)) for\n                 \u03b1 in \u03b1_candidates]\n    return \u03b1_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(\u03b1::Float64, len::Integer)\n    step = \u03c0 / len\n    \u03c9 = step .* (1:len)\n    num = (1-\u03b1*\u03b1) * sin(\u03c9)\n    den = (1+\u03b1*\u03b1) * cos(\u03c9) - 2*\u03b1\n    warpfreq = atan(num./den)\n    warpfreq[warpfreq .< 0] += \u03c0\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\u2032,j\u2032,k\u2032) where k\u2032 \u2225 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 \u00d7 k::SVector{3, T}\n   if axis[1] == axis[2] == 0\n      return tensor\n   else\n      normalize!(axis)\n      angle = acos(v \u22c5 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\u0302 = normalize(v)\nangle = deg2rad(-74)\nR = getRotationMatrix(v\u0302, angle)\n```\n\"\"\"\nfunction getRotationMatrix(v::AbstractVector{<:AbstractFloat}, \u03b8)\n   sin\u03b8, cos\u03b8 = sincos(eltype(v)(\u03b8))\n   tmp = 1 - cos\u03b8\n   m =  @SMatrix [\n        cos\u03b8+v[1]^2*tmp         v[1]*v[2]*tmp-v[3]*sin\u03b8 v[1]*v[3]*tmp+v[2]*sin\u03b8;\n        v[1]*v[2]*tmp+v[3]*sin\u03b8 cos\u03b8+v[2]^2*tmp         v[2]*v[3]*tmp-v[1]*sin\u03b8;\n        v[1]*v[3]*tmp-v[2]*sin\u03b8 v[3]*v[2]*tmp+v[1]*sin\u03b8 cos\u03b8+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] \u22c5 e2[:,1]\n      r12 = e1[:,1] \u22c5 e2[:,2]\n      r13 = e1[:,1] \u22c5 e2[:,3]\n      r21 = e1[:,2] \u22c5 e2[:,1]\n      r22 = e1[:,2] \u22c5 e2[:,2]\n      r23 = e1[:,2] \u22c5 e2[:,3]\n      r31 = e1[:,3] \u22c5 e2[:,1]\n      r32 = e1[:,3] \u22c5 e2[:,2]\n      r33 = e1[:,3] \u22c5 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": "function delta(n)\n# DELTA calculates the sun's declination angle\n# y = DELTA(jd) gets the Julian day (jd) and calculate declination of the sun\n\nd=(asin(-sin(23.45/180*pi).*cos(360/365.25*(n+10)/180*pi)));\n\nreturn d\n\nend\n", "meta": {"hexsha": "330abe316a5f4fb64effb05983fae29cb34a9cde", "size": 220, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "delta.jl", "max_stars_repo_name": "gaelforget/AOGCM1D.jl", "max_stars_repo_head_hexsha": "f59bf53a5bb7208e76d8dda9cf48d0bdbda17d9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "delta.jl", "max_issues_repo_name": "gaelforget/AOGCM1D.jl", "max_issues_repo_head_hexsha": "f59bf53a5bb7208e76d8dda9cf48d0bdbda17d9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "delta.jl", "max_forks_repo_name": "gaelforget/AOGCM1D.jl", "max_forks_repo_head_hexsha": "f59bf53a5bb7208e76d8dda9cf48d0bdbda17d9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-22T13:08:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T13:08:45.000Z", "avg_line_length": 22.0, "max_line_length": 77, "alphanum_fraction": 0.7045454545, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9697854111860906, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7564257305354867}}
{"text": "using Iterators, Base.Test\n\n# count\n# -----\n\ni = 0\nfor j = count(0, 2)\n\t@test j == i*2\n\ti += 1\n\ti <= 10 || break\nend\n\n# take\n# ----\n\ni = 0\nfor j = take(0:2:8, 10)\n\t@test j == i*2\n\ti += 1\nend\n@test i == 5\n\ni = 0\nfor j = take(0:2:100, 10)\n\t@test j == i*2\n\ti += 1\nend\n@test i == 10\n\n# drop\n# ----\n\ni = 0\nfor j = drop(0:2:10, 2)\n\t@test j == (i+2)*2\n\ti += 1\nend\n@test i == 4\n\n# cycle\n# -----\n\ni = 0\nfor j = cycle(0:3)\n\t@test j == i % 4\n\ti += 1\n\ti <= 10 || break\nend\n\n# repeated\n# --------\n\ni = 0\nfor j = repeated(1, 10)\n\t@test j == 1\n\ti += 1\nend\n@test i == 10\ni = 0\nfor j = repeated(1)\n\t@test j == 1\n\ti += 1\n\ti <= 10 || break\nend\n\n# chain\n# -----\n\n@test collect(chain(1:2:5, 0.2:0.1:1.6)) == [1:2:5, 0.2:0.1:1.6]\n\n# product\n# -------\n\nx1 = 1:2:10\nx2 = 1:5\n@test collect(product(x1, x2)) == vec([(y1, y2) for y1 in x1, y2 in x2])\n\n# distinct\n# --------\n\nx = [5, 2, 2, 1, 2, 1, 1, 2, 4, 2]\n@test collect(distinct(x)) == unique(x)\n\n# partition\n# ---------\n\n@test collect(partition(take(count(1), 6), 2)) == [(1,2), (3,4), (5,6)]\n@test collect(partition(take(count(1), 4), 2, 1)) == [(1,2), (2,3), (3,4)]\n@test collect(partition(take(count(1), 8), 2, 3)) == [(1,2), (4,5), (7,8)]\n\n# imap\n# ----\n\nfunction test_imap(expected, input...)\n  result = collect(imap(+, input...))\n  @test result == expected\nend\n\n\n# Empty arrays\ntest_imap(\n  {},\n  []\n)\n\n# Simple operation\ntest_imap(\n  {1,2,3},\n  [1,2,3]\n)\n\n# Multiple arguments\ntest_imap(\n  {5,7,9},\n  [1,2,3],\n  [4,5,6]\n)\n\n# Different-length arguments\ntest_imap(\n  {2,4,6},\n  [1,2,3],\n  count(1)\n)\n\n\n# groupby\n# -------\n\nfunction test_groupby(input, expected)\n  result = collect(groupby(input, x -> x[1]))\n  @test result == expected\nend\n\n\n# Empty arrays\ntest_groupby(\n  [],\n  {}\n)\n\n# Singletons\ntest_groupby(\n  [\"xxx\"],\n  {[\"xxx\"]}\n)\n\n# Typical operation\ntest_groupby(\n  [\"face\", \"foo\", \"bar\", \"book\", \"baz\"],\n  {[\"face\", \"foo\"], [\"bar\", \"book\", \"baz\"]}\n)\n\n# Trailing singletons\ntest_groupby(\n  [\"face\", \"foo\", \"bar\", \"book\", \"baz\", \"xxx\"],\n  {[\"face\", \"foo\"], [\"bar\", \"book\", \"baz\"], [\"xxx\"]}\n)\n\n# Leading singletons\ntest_groupby(\n  [\"xxx\", \"face\", \"foo\", \"bar\", \"book\", \"baz\"],\n  {[\"xxx\"], [\"face\", \"foo\"], [\"bar\", \"book\", \"baz\"]}\n)\n\n# Middle singletons\ntest_groupby(\n  [\"face\", \"foo\", \"xxx\", \"bar\", \"book\", \"baz\"],\n  {[\"face\", \"foo\"], [\"xxx\"], [\"bar\", \"book\", \"baz\"]}\n)\n\n\n# subsets\n\n@test collect(subsets({})) == {{}}\n\n@test collect(subsets([:a])) == {Symbol[], Symbol[:a]}\n\n@test collect(subsets([:a, :b, :c])) ==\n      {Symbol[], Symbol[:a], Symbol[:b], Symbol[:a, :b], Symbol[:c],\n       Symbol[:a, :c], Symbol[:b, :c], Symbol[:a, :b, :c]}\n\n# every n'th element\n@test collect(everynth([], 10)) == []\n@test_throws ArgumentError everynth([], 0)\n@test collect(everynth(10:20, 3)) == [12,15,18]\n@test collect(everynth(10:20, 1)) == [10:20]\n\n\n", "meta": {"hexsha": "1076cda53a708f2cd238f312adf1612770db1940", "size": 2779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test.jl", "max_stars_repo_name": "Futrell/Iterators.jl", "max_stars_repo_head_hexsha": "6a5211f26102e1378dfe5b0d6cd01cbff28cd055", "max_stars_repo_licenses": ["MIT"], "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": "Futrell/Iterators.jl", "max_issues_repo_head_hexsha": "6a5211f26102e1378dfe5b0d6cd01cbff28cd055", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "Futrell/Iterators.jl", "max_forks_repo_head_hexsha": "6a5211f26102e1378dfe5b0d6cd01cbff28cd055", "max_forks_repo_licenses": ["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.6263157895, "max_line_length": 74, "alphanum_fraction": 0.517452321, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.7563982254655002}}
{"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    \u03bb,v = newton([eltype],nep::NEP;[errmeasure,][tol,][maxit,][\u03bb,][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(\u03bb)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> \u03bb,v=newton(nep);\njulia> minimum(svdvals(compute_Mder(nep,\u03bb)))\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                    \u03bb::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 \u03bb and v are of type T\n        \u03bb=T(\u03bb)\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,\u03bb,v)\n\n            push_iteration_info!(logger,k,err=err,\u03bb=\u03bb,v=v,continues=true);\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (\u03bb,v)\n            end\n\n            # Compute NEP matrix and derivative\n            M = compute_Mder(nep,\u03bb)\n            Md = compute_Mder(nep,\u03bb,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            \u0394v=Vector{T}(delta[1:size(nep,1)]);\n            \u0394\u03bb=T(delta[size(nep,1)+1]);\n\n            (\u0394\u03bb,\u0394v,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          \u03bb,v,\u0394\u03bb,\u0394v,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[:] += \u0394v\n            \u03bb = \u03bb+\u0394\u03bb\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(\u03bb,v,err,msg))\n    end\n\n    ############################################################################\n\"\"\"\n    \u03bb,v = resinv([eltype],nep::NEP;[errmeasure,][tol,][maxit,][\u03bb,][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> \u03bb,v=resinv(nep,\u03bb=-2,v=ones(size(nep,1)))\njulia> typeof(\u03bb)\nComplex{Float64}\njulia> norm(compute_Mlincomb(nep,\u03bb,v))\n6.688224435370382e-12\njulia> \u03bb,v=resinv(Float64,nep,\u03bb=-2,v=ones(size(nep,1)))\njulia> typeof(\u03bb)\nFloat64\njulia> norm(compute_Mlincomb(nep,\u03bb,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                    \u03bb::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 \u03bb and v are of type T\n        \u03bb::T=T(\u03bb)\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,\u03bb)\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        \u03c3::T=\u03bb;\n        err=Inf;\n\n\n        for k=1:maxit\n            # Normalize\n            v[:] = v/norm(v);\n\n            err=estimate_error(errmeasure,\u03bb,v)\n\n            if (use_v_as_rf_vector)\n                c[:]=v;\n            end\n\n\n            push_iteration_info!(logger,k,err=err,\u03bb=\u03bb,v=v,continues=true);\n\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (\u03bb,v)\n            end\n\n            # Compute eigenvalue update\n            \u03bb_vec = compute_rf(T, nep, v, inner_solver, y=c, \u03bb=\u03bb, target=\u03c3)\n            local \u03bb1::T = closest_to(\u03bb_vec,  \u03bb)\n            \u0394\u03bb=\u03bb1-\u03bb\n\n\n            # Compute eigenvector update\n            \u0394v = -lin_solve(linsolver,compute_Mlincomb(nep,\u03bb1,reshape(v,n,1))) #M*v);\n\n            (\u0394\u03bb,\u0394v,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          \u03bb,v,\u0394\u03bb,\u0394v,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            \u03bb+=\u0394\u03bb\n            v[:] += \u0394v;\n\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(\u03bb,v,err,msg))\n    end\n\n\n\n\n\n    # New augnewton\n\"\"\"\n    augnewton([eltype], nep::NEP; [errmeasure,][tol,][maxit,][\u03bb,][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 `(\u03bb,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 `\u03bb` 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> \u03bb1,v1=newton(nep,maxit=20,v=ones(size(nep,1)),\u03bb=0)\njulia> \u03bb2,v2=augnewton(nep,maxit=20,v=ones(size(nep,1)),\u03bb=0)\njulia> \u03bb1-\u03bb2\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                       \u03bb::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 \u03bb and v are of type T\n        \u03bb=T(\u03bb)\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,\u03bb,v)\n            push_iteration_info!(logger,k,err=err,\u03bb=\u03bb,v=v,continues=true);\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (\u03bb,v)\n            end\n            # tempvec =  (M(\u03bb_k)^{-1})*M'(\u03bb_k)*v_k\n            # \u03b1 = 1/(c'*(M(\u03bb_k)^{-1})*M'(\u03bb_k)*v_k);\n\n            z::AbstractVector=compute_Mlincomb(nep,\u03bb,v,[T(1.0)],1)\n\n            linsolver = create_linsolver(linsolvercreator,nep,\u03bb)\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            \u03b1 = T(1)/ dot(c,tempvec);\n\n            \u0394\u03bb=-\u03b1\n            \u0394v=\u03b1*tempvec-v;\n\n            (\u0394\u03bb,\u0394v,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          \u03bb,v,\u0394\u03bb,\u0394v,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            \u03bb+=\u0394\u03bb\n            v[:]+=\u0394v\n\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(\u03bb,v,err,msg))\n    end\n\n\n\"\"\"\n    quasinewton([T=ComplexF64],nep,[errmeasure,][tol,][maxit,][\u03bb,][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(\u03bb)``, where ``\u03bb`` is constant.\nThe vector `ws` is a representation of the normalization, in the sense that ``c^T=w_s^TM(\u03bb)``,\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> \u03bb,v=quasinewton(nep,\u03bb=1.0,v=ones(size(nep,1)));\njulia> norm(compute_Mlincomb(nep,\u03bb,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                         \u03bb::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 \u03bb and v are of type T\n        \u03bb=T(\u03bb)\n        v=Vector{T}(v)\n        ws=Vector{T}(ws) # Left vector such that c'=w'M(\u03bb) 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,\u03bb)\n\n\n        for k=1:maxit\n            err=estimate_error(errmeasure,\u03bb,v)\n            push_iteration_info!(logger,k,err=err,\u03bb=\u03bb,v=v,continues=true);\n            if (err< tol)\n                push_info!(logger,\"\")\n                return (\u03bb,v)\n            end\n\n\n            # Compute u=M(\u03bb)v and w=M'(\u03bb)v\n            u[:] = compute_Mlincomb(nep,\u03bb,v,[T(1)],0);\n            w[:] = compute_Mlincomb(nep,\u03bb,v,[T(1)],1);\n\n            # Intermediate quantities\n            \u0394\u03bb=-dot(ws,u)/dot(ws,w);\n            z=\u0394\u03bb*w+u;\n            # Throws an error if lin_solve returns incorrect type.\n            local \u0394v::Vector{T}= -lin_solve(linsolver, z, tol=tol)\n\n            norm\u0394v=norm(\u0394v);\n            push_info!(logger,2,\" norm(\u0394v)=$norm\u0394v\",continues=true)\n\n            (\u0394\u03bb,\u0394v,j,scaling)=armijo_rule(nep,errmeasure,err,\n                                          \u03bb,v,\u0394\u03bb,\u0394v,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            \u03bb += \u0394\u03bb\n            v[:] += \u0394v; # eigvec update\n\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(\u03bb,v,err,msg))\n    end\n\n\n\"\"\"\n    \u03bb,v = newtonqr([eltype],nep::NEP;[errmeasure,][tol,][maxit,][\u03bb,][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(\u03bb)``, 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(\u03bb)``\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> \u03bb,v=newtonqr(nep,v=ones(size(nep,1)));\njulia> norm(compute_Mlincomb(nep,\u03bb,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 \u03bb-matrices, SIAM J. Numer. Anal. 7, 532\u2013537\n* G\u00fcttel, 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                      \u03bb::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 \u03bb and v are of type T\n        \u03bb=T(\u03bb)\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,\u03bb);\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,\u03bb),2); # Frobenius norm\n            err=estimate_error(errmeasure,\u03bb,v);\n\n\n            push_iteration_info!(logger,k,err=err,\u03bb=\u03bb,v=v);\n            if(err < tol)\n                return \u03bb,v,w;\n            end\n\n\n            d = dot(Q[:,n],compute_Mlincomb(nep,\u03bb,reshape(v,n,1),[T(1)],1));\n            #d = dot(Q[:,n],compute_Mder(nep,\u03bb,1)*P*[-p;T(1.0)]);\n            \u03bb = \u03bb - R[n,n]/d;\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(\u03bb,v,err,msg))\n    end\n\n\n\"\"\"\n    \u03bb,v = implicitdet([eltype],nep::NEP;[errmeasure,][tol,][maxit,][\u03bb,][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(\u03bb))/det(G(\u03bb)) = 0``, where ``G(\u03bb)`` is a saddle point matrix with ``M(\u03bb)``\nin the (1,1) block. The (2,1) and (1,2) blocks of ``G(\u03bb)`` are set to\n``c^H`` and ``c`` respectively. Note that ``G(\u03bb) `` can be non-singular even when ``M(\u03bb) ``\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> \u03bb,v=implicitdet(nep,v=ones(size(nep,1)));\njulia> norm(compute_Mlincomb(nep,\u03bb,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\u20138\n* G\u00fcttel, 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                         \u03bb=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,\u03bb);\n            AA = [A b;c' 0];#The matrix G(\u03bb)\n\n            F = lu(AA);\n\n            v[:] = F\\([zeros(T,n);T(1)]);\n            vp[:] = F\\([-1*compute_Mder(nep,\u03bb,1)*v[1:n];0]);\n\n            #err = estimate_error(errmeasure,\u03bb,v[1:n]);\n            err = abs(v[n+1])/norm(compute_Mder(nep,\u03bb),2); # Frobenius norm based error\n            push_iteration_info!(logger,k,err=err,\u03bb=\u03bb,v=v);\n            if(err < tol)\n                return \u03bb,v[1:n];\n            end\n\n            \u03bb = \u03bb - v[n+1]/vp[n+1];#Newton update for the equation det(M(\u03bb))/det(G(\u03bb)) = 0\n        end\n\n        msg=\"Number of iterations exceeded. maxit=$(maxit).\"\n        throw(NoConvergenceException(\u03bb,v,NaN,msg))\n    end\n\n\n    # Armijo rule implementation\n    function armijo_rule(nep,errmeasure,err0,\u03bb,v,\u0394\u03bb,\u0394v,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,\u03bb+\u0394\u03bb,v+\u0394v)>err0 && j<armijo_max)\n                j=j+1;\n                \u0394v=\u0394v*armijo_factor;\n                \u0394\u03bb=\u0394\u03bb*armijo_factor;\n            end\n        end\n        return  (\u0394\u03bb,\u0394v,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\u0394t = 0.1 # \u0394t 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, \u0394t)\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*\u0394t)\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.\u03bc[2]\nconfidence_array[1] = 2*sqrt(initial_guess.\u03a3.mat[2,2])\nfor i in x_data\n    current_state = filtered_state.state[i]\n    population_array[i+1] = current_state.\u03bc[2]\n    confidence_array[i+1] = 2*sqrt(current_state.\u03a3.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.\u03bc[1]\nconfidence_array[1] = initial_guess.\u03a3.mat[1,1]\nfor i in x_data\n    current_state = filtered_state.state[i]\n    growth_rate_array[i+1] = current_state.\u03bc[1]\n    confidence_array[i+1] = 2*sqrt(current_state.\u03a3.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    \u03bc1::Float64\n    \u03bc2::Float64\n\n    function Skellam(\u03bc1::Float64, \u03bc2::Float64)\n        \u03bc1 > 0.0 && \u03bc2 > 0.0 || error(\"\u03bc1 and \u03bc2 must be positive.\")\n        new(\u03bc1, \u03bc2)\n    end\n\n    @compat Skellam(\u03bc1::Real, \u03bc2::Real) = Skellam(Float64(\u03bc1), Float64(\u03bc2))\n\n    Skellam(\u03bc::Real) = Skellam(\u03bc, \u03bc)\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.\u03bc1, d.\u03bc2)\n\n\n### Statistics\n\nmean(d::Skellam) = d.\u03bc1 - d.\u03bc2\n\nvar(d::Skellam) = d.\u03bc1 + d.\u03bc2\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    \u03bc1, \u03bc2 = params(d)\n    - (\u03bc1 + \u03bc2) + (x / 2.0) * log(\u03bc1 / \u03bc2) + log(besseli(x, 2.0 * sqrt(\u03bc1) * sqrt(\u03bc2)))\nend\n\npdf(d::Skellam, x::Int) = exp(logpdf(d, x))\n\nfunction mgf(d::Skellam, t::Real)\n    \u03bc1, \u03bc2 = params(d)\n    exp(-(\u03bc1 + \u03bc2) + \u03bc1 * exp(t) + \u03bc2 * exp(-t))\nend\n\nfunction cf(d::Skellam, t::Real)\n    \u03bc1, \u03bc2 = params(d)\n    exp(-(\u03bc1 + \u03bc2) + \u03bc1 * cis(t) + \u03bc2 * cis(-t))\nend\n\n### Sampling\n\nrand(d::Skellam) = rand(Poisson(d.\u03bc1)) - rand(Poisson(d.\u03bc2))\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\u03c0, kappa=1e-2, nsteps=1000, dev=CPU())\n   \u03c4 = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * \u03c4 # 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, \u03c3 = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2\u03c3^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant \u03ba\n  tfinal = nsteps*dt\n  \u03c3t = sqrt(2*kappa*tfinal + \u03c3^2)\n  cfinal = @. c0ampl*\u03c3/\u03c3t * exp(-g.x^2/(2*\u03c3t^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\u03c0, kappa=1e-2, nsteps=1000, dev=CPU())\n   \u03c4 = 1/kappa  # time-scale for diffusive decay\n  dt = 1e-9 * \u03c4 # 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, \u03c3 = 0.01, 0.2\n  c0func(x) = @. c0ampl*exp(-x^2/(2\u03c3^2))\n  c0 = c0func.(g.x)\n\n  # analytic solution for for 1D heat equation with constant \u03ba\n  tfinal = nsteps*dt\n  \u03c3t = sqrt(2*kappa[1]*tfinal + \u03c3^2)\n  cfinal = @. c0ampl*\u03c3/\u03c3t * exp(-g.x^2/(2*\u03c3t^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(\u03b8, radius, transposed)\n\n    \u03b8_count = iround(2\u03c0/\u03b8)\n    \u03b8 = 2\u03c0/\u03b8_count\n    angles = (0:\u03b8_count)*\u03b8\n\n    # x and y offset of points at specified radius and angles\n    # from each reference position.\n\n    if transposed\n        # \u03b8\u2032 = -\u03c0/2 - \u03b8\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 \u03b8, xoffs, yoffs\nend\n\n_discretize_angle(angle::FloatingPoint, inv\u03b8) = \n    angle < 0 ? iround((angle + 2\u03c0)*inv\u03b8)+1 : iround(angle*inv\u03b8)+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    \u03b8, xoffs, yoffs = _calc_discrete_offsets(theta, radius, transposed)\n    i\u03b8 = 1/\u03b8\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\u03b8)   # 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": "using DiffEqOperators, SparseArrays, LinearAlgebra\n\nx = 0.0:0.01:\u03c0\nx_ = x[2:end-1]\ndx = diff(x)\ny = sin.(2x)\ny_ = y[2:(end-1)]\ndy = [2cos.(2x_),-4sin.(2x_),-8cos.(2x_),16y_,32cos.(2x_)]\n\n\n\n# test concretization against regular grid operator\nfor dor in 1:4, aor in 2:2:6\n    Dr = CenteredDifference(dor,aor,dx[1],length(x)-2)\n    Dir = CenteredDifference(dor,aor,dx,length(x)-2)\n\n    @test sparse(Dr)\u2248sparse(Dir)\n    @test Array(Dr)\u2248Array(Dir)\n\nend\n\n# test irregular grid operator with regular grid\nfor dor in 1:4, aor in 2:6\n\n    D1 = CenteredDifference(dor,aor,dx,length(x)-2)\n\n    #take derivative\n    yprime1 = D1*y\n\n    #test result\n    @test yprime1 \u2248 dy[dor] atol = 10.0^(1-aor)#2test operator with known derivative of exp(kx)\n\n    #TODO: implement specific tests for the left and right boundary regions, waiting until after update\nend\n\n\n# test irregular grid\n\nx = sin.(0.0:0.05:\u03c0)\nx = cumsum(x)\nx = x/x[end]*\u03c0\nx_ = x[2:end-1]\ndx = diff(x)\ny  = sin.(2x)\ny_ = y[2:(end-1)]\ndy = [2cos.(2x_), -4sin.(2x_), -8cos.(2x_), 16y_, 32cos.(2x_)]\n\nfor dor in 1:4, aor in 4:10\n\n    D1 = CenteredDifference(dor,aor,dx,length(x)-2)\n\n    #take derivative\n    yprime1 = D1*y\n\n    #test result\n    tol = 2*10.0^(2-aor)*maximum(dx)^(2-dor)\n    # error estimate is fairly difficult for high order derivatives and small dx.\n\n    # err = norm(yprime1.-dy[dor])\n    # @show err\n    # @show tol\n\n    @test yprime1 \u2248 dy[dor] atol = tol #2test operator with known derivative of exp(kx)\n\n    #TODO: implement specific tests for the left and right boundary regions, waiting until after update\nend\n", "meta": {"hexsha": "77119b351e5b28e36197d03194729aaa86778b93", "size": 1575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DerivativeOperators/generic_operator_validation.jl", "max_stars_repo_name": "briochemc/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/generic_operator_validation.jl", "max_issues_repo_name": "briochemc/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/generic_operator_validation.jl", "max_forks_repo_name": "briochemc/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": 23.5074626866, "max_line_length": 103, "alphanum_fraction": 0.6565079365, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8267117983401362, "lm_q1q2_score": 0.7563594061323927}}
{"text": "export pivotedqr\n\nfunction pivotedqr(\u03c8::AbstractMatrix{T}, u::AbstractVector{T}; invert::Bool=true, verbose::Bool = true, \u03f5rel::Float64 = 1e-1, maxterms::Int64=typemax(Int64)) where {T}\n\n    m, n = size(\u03c8)\n\n    # Compute a pivoted QR decomposition of \u03c8, use the pivot for the sensor placement\n\n    F = qr(\u03c8, Val(true))\n\n    residue = copy(u)\n    idxset = Int64[]\n    dict = collect(1:n)\n    \u03f5u = norm(u)\n    \u03f5hist = [\u03f5u]\n    \u03f5rel *= \u03f5u\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(\u03c8,:,idxset)\\u\n        residue = u - view(\u03c8,:,idxset)*c\n\n        # Calculate stopping critera\n        \u03f5 = norm(residue)\n        if verbose == true\n            push!(\u03f5hist, copy(\u03f5))\n        end\n        if \u03f5 < \u03f5rel || 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(\u03c8,:, idxset)\\u\n            return idxset, c, \u03f5hist\n        else\n            return idxset, \u03f5hist\n        end\n    else\n        if invert == true\n            c = zeros(length(idxset))\n            c .= view(\u03c8,:, 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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, StatsPlots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.11\"\n\n# \u2554\u2550\u2561 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\ndist1 = TriangularDist(0,10,5)\n\n# \u2554\u2550\u2561 75c334f0-2134-11eb-132d-dfcb59e14474\ndist2 = DiscreteUniform(1,5)\n\n# \u2554\u2550\u2561 75c37638-2134-11eb-150e-a5788c7f72a7\ntheorMean1, theorMean2 = mean(dist1), mean(dist2)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 de66cfee-2134-11eb-2c7a-add4bee67341\ndensity(data1, lab=\"Triangukar density\")\n\n# \u2554\u2550\u2561 a315bbee-2134-11eb-0249-17f3c6af3543\ndensity!(data2, lab=\"Discrete Uniform density\")\n\n# \u2554\u2550\u2561 75cedfbc-2134-11eb-3b3c-5bdc69e4735a\nText(\"Symmetric Triangular Distiribution on [0,10] has mean $theorMean1\n\t(estimated: $estMean1)\")\n\n# \u2554\u2550\u2561 75cf627a-2134-11eb-0dc9-e5e3d869f4a8\nText(\"Discrete Uniform Distiribution on {1,2,3,4,5} has mean $theorMean2\n\t(estimated: $estMean2)\")\n\n# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.11\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u255075c334f0-2134-11eb-132d-dfcb59e14474\n# \u2560\u255075c37638-2134-11eb-150e-a5788c7f72a7\n# \u2560\u255075c3fa78-2134-11eb-0259-699e1c89a023\n# \u2560\u2550de66cfee-2134-11eb-2c7a-add4bee67341\n# \u2560\u2550a315bbee-2134-11eb-0249-17f3c6af3543\n# \u2560\u255075cedfbc-2134-11eb-3b3c-5bdc69e4735a\n# \u2560\u255075cf627a-2134-11eb-0dc9-e5e3d869f4a8\n# \u255f\u250070182cd8-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 \u00f7 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) \u00f7 2)\n    1 + _collatz_steps(n\u00f72)\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": "# # ImageInspector\r\n\r\n# ImageInspector is a small package for educational purposes. Its main goal is not presenting functionality, but presenting package structure. This is its short documentation created in the package [Literate](https://fredrikekre.github.io/Literate.jl/v2) which uses the [Markdown](https://www.markdownguide.org/cheat-sheet) syntax.\r\n\r\n# To use the package, we need to load first the required packages.\r\n\r\nusing ImageInspector\r\nusing Plots\r\n\r\n# ## Grayscale images\r\n\r\n# As a test example, we create the real matrix `img1` representing a circle. We first discretize the domain $[-1,1]$ in `xs`. We assign black colour whenever $x^2 + y^2 \\le 1$. Since the white colour is represented by `[1; 1; 1]` and the black colour by `[0; 0; 0]`, we can do it by the following code:\r\n\r\nxs = -1:0.001:1\r\nimg1 = [x^2+y^2>1 for x in xs, y in xs];\r\n\r\n# This is a two-dimensional matrix, which represents a grayscale image. We convert it to an image by calling `image` and then we plot it.\r\n\r\nplot(image(img1); axis = nothing, border = :none)\r\n\r\n# We can convert it to a three-dimensinal representation by the `reshape` function. The resulting plot is the same even though a different method for the `image` function is called. \r\n\r\nimg2 = reshape(img1, (size(img1)..., 1))\r\n\r\nplot(image(img2); axis = nothing, border = :none)\r\n\r\n# ## Coloured images\r\n\r\n# We can repeat a similar procedure for coloured images. We create again a three-dimensional matrix, convert it to an image and then plot it. \r\n\r\nimg2 = ones(size(img1)..., 3)\r\nimg2[:,:,2:3] .= [x^2+y^2>1 for x in xs, y in xs]\r\n\r\nplot(image(img2); axis = nothing, border = :none)\r\n\r\n", "meta": {"hexsha": "05934603cfca3b4555cd79bf58b7a60041ef9051", "size": 1640, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "report/report.jl", "max_stars_repo_name": "JuliaTeachingCTU/ImageInspector.jl", "max_stars_repo_head_hexsha": "825dbba4304d54491ac8ffb497c5e64c14945fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report.jl", "max_issues_repo_name": "JuliaTeachingCTU/ImageInspector.jl", "max_issues_repo_head_hexsha": "825dbba4304d54491ac8ffb497c5e64c14945fa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.jl", "max_forks_repo_name": "JuliaTeachingCTU/ImageInspector.jl", "max_forks_repo_head_hexsha": "825dbba4304d54491ac8ffb497c5e64c14945fa3", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 332, "alphanum_fraction": 0.7079268293, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7563537552861709}}
{"text": "# This file is part of IntegerSequences.\n# Copyright Peter Luschny. License is MIT.\n\n(@__DIR__) \u2209 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 \u2208 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 \u2208 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 \u2208 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 \u2208 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 \u2208 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) \u2208 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) \u2208 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) \u2208 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) \u2208 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 \u2208 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 \u2208 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 \u2208 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 \u2208 0:degree(P(n))] for n \u2208 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 \u2208 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 \u2208 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 \u2208 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 \u2208 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 \u2208 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 \u2208 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 \u2208 1:n)\n        end\n        recP(m, n)\n    end\n\n    # ... given a polynomial p:\n    for m \u2208 0:4, n \u2208 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 \u2208 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": "# Tests for the total correlation function\n\n# Test total correlation formula\n@test get_total_correlation(arr1, arr2, arr3) \u2248 get_entropy(arr1) + get_entropy(arr2) + get_entropy(arr3) - get_entropy(arr1, arr2, arr3)\nprintln(\"Total correlation formula passed.\")\n", "meta": {"hexsha": "a6e953de69f5333c0ff2c4ab8d69ee8e2931c02f", "size": 260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testTotalCorrelation.jl", "max_stars_repo_name": "alavendelm/InformationMeasures.jl", "max_stars_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_stars_repo_licenses": ["MIT"], "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/testTotalCorrelation.jl", "max_issues_repo_name": "alavendelm/InformationMeasures.jl", "max_issues_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_issues_repo_licenses": ["MIT"], "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/testTotalCorrelation.jl", "max_forks_repo_name": "alavendelm/InformationMeasures.jl", "max_forks_repo_head_hexsha": "09e48dad700c6bf78cdc83a679dd741ead123990", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 137, "alphanum_fraction": 0.7807692308, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7563537494106473}}
{"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, \u201cA new method for gray-level picture thresholding using the entropy of the histogram,\u201d *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\u00d72 Matrix{Int64}:\n 1  2\n 3  4\n\njulia> nanstd(A, dims=1)\n1\u00d72 Matrix{Float64}:\n 1.41421  1.41421\n\njulia> nanstd(A, dims=2)\n2\u00d71 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 \u2208 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\u03bb = 1\nRf(\u03b2, \u03b1) = [   \u03b2        \u03bb; \n            -\u03b1*\u03b2 (1 - \u03b1*\u03bb)]\n\n\u03b1 = 0.05\n\u03b2 = 0.4\n\n\u03f5 = 8\nS = inv([ 1  0 ;\n          \u03b1  1 ])\n\nfunction err(k)\n    R = Rf(\u03b2, \u03b1)\n    sum( ( ((R^(k-i))*([\u03f5; -\u03b1*\u03f5]) )[2] )^2 for i = 1:k )\nend\n\nfunction err2(k, \u03b1, \u03b2)\n    R = Rf(\u03b2, \u03b1)\n    x = [\u03f5; -\u03b1*\u03f5]\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  \u039b, U = eig(R)\n  (b,k) -> begin; \n    \u039bsum = (1./(1 - \u039b)).*(1 - \u039b.^k); \n    real(U*(\u039bsum.*(U\\b))); \n  end\nend\n\nfunction runmomentum(A,b,k, \u03f5)\n  z = zeros(length(b))\n  w = 3*ones(length(b))\n  for i = 1:k\n    z = \u03b2*z + (A*w - b) + \u03f5*randn(1)\n    w = w - \u03b1*z\n  end\n  return (z[1],w[1])\nend\n\nfunction runmomentum2(A,b,k, \u03f5)\n  z = zeros(length(b))\n  w = 3*ones(length(b))\n  fx = []\n  for i = 1:k\n    z = \u03b2*z + (A*w - b) + \u03f5*randn(1)\n    w = w - \u03b1*z\n    push!(fx, w[1]*w[1])\n  end\n  return fx\nend\n\nk = 150\nd = mean([runmomentum2(1,0, k, \u03f5) 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\u0142 Kami\u0144ski, 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\u00e8 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\u00b0 55' 31'').  Its\ncompanion, Alcor, has coordinates (ra, dec) = (13h 25m 13.5s, +54\u00b0 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": "############################################\n# Developer: Luiz Henrique Nogueira Lorena #\n# 15/01/22                                 #\n############################################\n\nusing Random\nusing CSV, DataFrames, Statistics\nusing JuMP, CPLEX\nusing PyCall, PyPlot\nusing ScikitLearn\nusing ScikitLearn.CrossValidation: train_test_split\n@sk_import linear_model: LinearRegression\n@sk_import metrics: r2_score\n\npy\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef printCorrelationMatrix(corr):\n\n    sns.set_theme(style=\"white\")\n\n    # Generate a mask for the upper triangle\n    mask = np.triu(np.ones_like(corr, dtype=bool))\n\n    # Set up the matplotlib figure\n    f, ax = plt.subplots(figsize=(14, 12))\n    ax.set_title('Pearson Correlation')\n\n    # Draw the heatmap with the mask and correct aspect ratio\n    sns.heatmap(corr, \n                mask=mask, \n                cmap=\"coolwarm\", \n                vmax=1, \n                vmin = -1, \n                center=0.5,\n                square=True, \n                linewidths=.5, \n                cbar_kws={\"shrink\": .4},\n                annot = True,\n                annot_kws = {\"size\": 13})\n\ndef printParetoFront(XX,XY):\n    sns.set_theme(style=\"white\",font_scale=3)\n\n    # Set up the matplotlib figure\n    f, ax = plt.subplots(figsize=(14, 12))\n    ax.set_title('Pareto Front')\n\n    d = {'Total X-X correlations': XX, 'Total X-Y correlations': XY}\n    df = pd.DataFrame(data=d)\n    \n    sns.lineplot(data = df, \n                 x='Total X-X correlations', \n                 y='Total X-Y correlations',\n                 markers=True,\n                 marker='o',\n                 markersize = 12)\n\ndef printR2(X,Y):\n    sns.set_theme(style=\"whitegrid\",font_scale=3)\n    d = {'Points': X, 'r2': Y}\n    df = pd.DataFrame(data=d)\n    f, ax = plt.subplots(figsize=(14, 12))\n    sns.barplot(x=\"Points\", y=\"r2\", data=df)\n\"\"\"\n\nfunction loadData(dataset)\n    df = CSV.read(dataset, DataFrame)\n    \u03c1 = cor(Matrix(df))                # Pearson correlation   \n    py\"printCorrelationMatrix\"(\u03c1)\n    display(gcf())\n    savefig(\"results/correlationMatrix.pdf\")\n    \u03c1 = abs.(cor(Matrix(df)))\n    return Matrix(df[:,1:end-1]), Vector(df[:,end]), \u03c1[1:end-1,1:end-1], \u03c1[1:end-1,end]\nend\n\nmutable struct Solution\n    id\n    obj\n    variables\n    \u03b8\n    \u03c6\n    r2\nend\n\nfunction executeVariableSelectModel(\u03c1ij, \u03c10i, \u03b1)\n    \n    N = size(\u03c1ij,1)\n\n    m = Model(CPLEX.Optimizer)\n\n    @variable(m, u[i in 1:N], Bin)\n    @variable(m, v[i in 1:N, j in 1:N; i<j])\n\n    @objective(m, Max, \u03b1 * sum( abs(\u03c10i[i]) * u[i] for i in 1:N ) - (1-\u03b1) * sum( abs(\u03c1ij[i,j]) * v[i,j] for i in 1:N-1, j in i+1:N))\n\n    for i in 1:N-1\n        for j in i+1:N\n            @constraint(m, v[i,j] >= 0)\n            @constraint(m, v[i,j] >= u[i] + u[j] - 1)\n        end\n    end\n\n    set_silent(m)\n\n    optimize!(m)\n    u_opt = JuMP.value.(u)\n    v_opt = JuMP.value.(v)\n    obj = JuMP.objective_value(m)\n\n    \u03c6 = 0.0\n    M = zeros(Bool,N)\n    for i in 1:N-1\n        for j in i+1:N\n            if v_opt[i,j] > 0.5\n                M[i] = M[j] = true\n                \u03c6 += \u03c1ij[i,j]\n            end\n        end\n    end\n\n    \u03b8 = 0.0\n    variaveis = []\n    for i in 1:N\n        if M[i]\n            push!(variaveis,i)\n        end\n        if u_opt[i] > 0.5\n            \u03b8 += \u03c10i[i]\n        end\n    end\n\n    return Solution(0, obj, variaveis, \u03b8, \u03c6, 0.0)\nend\n\nfunction executeRegression(X,y)\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)\n    lin_reg = fit!(LinearRegression(), X_train, y_train)\n    y_predict = predict(lin_reg, X_test)\n    r2 = r2_score(y_test, y_predict)\n    return r2\nend\n\nfunction executeNair(dataset)\n    \n    # Load data\n    X, y, \u03c1ij, \u03c10i = loadData(dataset)\n\n    # Total of variables\n    n = size(X,2)\n\n    # Array to store Pareto front solutions\n    solutionID = 1\n    solutions = Solution[]\n    solutionsTested = []\n\n    ###########################\n    # Get initial SS0 and SSF #\n    ###########################\n\n    #######################################\n    # SS0 - variable with higher \u03c10i value\n    bestvariable = sortperm(\u03c10i, rev = true)[1]\n    \u03b8q = \u03c10i[bestvariable]\n    \u03c6q = 0\n    \n    # r2 for SS0\n    X_new = reshape(X[:,bestvariable], length(X[:,bestvariable]), 1)\n    r2_SS0 = executeRegression(X_new,y)\n\n    ######################\n    # SSF - all variables\n    \u03b8r = sum(\u03c10i)\n    \u03c6r = 0.0\n    for i in 1:n-1\n        for j in i+1:n\n            \u03c6r += \u03c1ij[i,j]\n        end\n    end\n\n    # r2 for SSF\n    r2_SSF = executeRegression(X,y)\n    \n    # \u03b1l for the first iteration\n    \u03b1l = (\u03c6q - \u03c6r)/(\u03b8q + \u03c6q - \u03b8r - \u03c6r)\n\n    # Objective value for SS0 and SSF\n    z\u03b1 = (\u03b1l * \u03b8q) - ( (1-\u03b1l) * \u03c6q )\n\n    # Store solutions from pareto frontier SSO and SSF\n    push!(solutions, Solution(solutionID,z\u03b1, [bestvariable], \u03b8q, \u03c6q, r2_SS0))\n    solutionID += 1\n    push!(solutions, Solution(solutionID, z\u03b1, collect(1:n), \u03b8r, \u03c6r, r2_SSF))\n    solutionID += 1\n    push!(solutionsTested,(solutions[1].id,solutions[2].id))\n\n    #######################################\n    # Solve the ILP with the calculated \u03b1l\n    solution = executeVariableSelectModel(\u03c1ij, \u03c10i, \u03b1l)\n\n    if solution.obj > z\u03b1\n        # Execute r2 for the new point\n        X_new = X[:,solution.variables]\n        solution.r2 = executeRegression(X_new,y)\n        solution.id = solutionID \n        solutionID += 1\n        insert!(solutions, 2, solution)\n    end\n\n    if size(solutions,1) == 3\n        \n        pointinserted = true\n\n        while pointinserted == true\n            \n            pointinserted = false\n\n            i = 1\n            totalpontos = size(solutions,1)\n\n            while i < totalpontos\n\n                solution1 = solutions[i]\n                solution2 = solutions[i+1]\n\n                if (solution1.id, solution2.id) \u2209 solutionsTested\n\n                    # Calculate \u03b1l\n                    \u03b1l = (solution1.\u03c6 - solution2.\u03c6)/(solution1.\u03b8 + solution1.\u03c6 - solution2.\u03b8 - solution2.\u03c6)\n\n                    # Calculate z\u03b1 for SS0\n                    z\u03b1 = (\u03b1l * solution1.\u03b8) - ( (1-\u03b1l) * solution1.\u03c6 )\n\n                    # Solve the ILP with the calculated \u03b1l\n                    solutionNEW = executeVariableSelectModel(\u03c1ij, \u03c10i, \u03b1l)\n\n                    #if solutionNEW.obj > z\u03b1\n                    if solutionNEW.obj - z\u03b1 > 0.0001\n                        # Execute r2 for the new point\n                        X_new = X[:,solutionNEW.variables]\n                        solutionNEW.r2 = executeRegression(X_new,y)\n                        solutionNEW.id = solutionID\n                        solutionID += 1\n                        insert!(solutions,i+1,solutionNEW)\n                        pointinserted = true\n                        totalpontos += 1\n\n                        push!(solutionsTested,(solution1.id, solution2.id))\n                    end\n\n                end\n\n                i += 1 \n            end\n\n        end\n\n    end\n\n    # Plot Pareto Front\n    XX = []\n    XY = []\n    for sol in solutions\n        push!(XX,sol.\u03c6)\n        push!(XY,sol.\u03b8)\n    end\n    py\"printParetoFront\"(XX,XY)\n    display(gcf())\n    savefig(\"results/paretoFront.pdf\")\n\n    py\"printR2\"(collect(1:size(solutions,1)), [sol.r2 for sol in solutions])\n    display(gcf())\n    savefig(\"results/r2.pdf\")\n\n    df = DataFrame(\n        Point = collect(1:size(solutions,1)),\n        Obj = [sol.obj for sol in solutions],\n        Variables = [Int.(sol.variables) for sol in solutions],\n        \u03b8 = [sol.\u03b8 for sol in solutions],\n        \u03c6 = [sol.\u03c6 for sol in solutions],\n        r2 = [sol.r2 for sol in solutions]\n    )  \n\n    CSV.write(\"results/resultado.csv\",df)\n\n    print(df)\n\n    return solutions\nend\n\n#Random.seed!(0)\nsolutions = executeNair(\"datasets/2.txt\");\n", "meta": {"hexsha": "1ab9b9ca4f3122da975883693e56deea746dc6ce", "size": 7719, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "main.jl", "max_stars_repo_name": "luizlorena54/LinearRegression", "max_stars_repo_head_hexsha": "2fa727f278760557945d8feb5858fc6866935607", "max_stars_repo_licenses": ["MIT"], "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": "luizlorena54/LinearRegression", "max_issues_repo_head_hexsha": "2fa727f278760557945d8feb5858fc6866935607", "max_issues_repo_licenses": ["MIT"], "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": "luizlorena54/LinearRegression", "max_forks_repo_head_hexsha": "2fa727f278760557945d8feb5858fc6866935607", "max_forks_repo_licenses": ["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.0777027027, "max_line_length": 132, "alphanum_fraction": 0.5251975645, "num_tokens": 2200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7563391096954829}}
{"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), \u201cA New Criterion for Automatic Multilevel Thresholding\u201d, 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": "using DataStructures\nentropy(s::AbstractString) = -sum(x -> x / length(s) * log2(x / length(s)), values(counter(s)))\n\nfunction fibboword(n::Int64)\n    # Initialize the result\n    r = Array{String}(n)\n    # First element\n    r[1] = \"0\"\n    # If more than 2, set the second element\n    if n \u2265 2 r[2] = \"1\" end\n    # Recursively create elements > 3\n    for i in 3:n\n        r[i] = r[i - 1] * r[i - 2]\n    end\n    return r\nend\n\nfunction testfibbo(n::Integer)\n    fib = fibboword(n)\n    for i in 1:length(fib)\n        @printf(\"%3d%9d%12.6f\\n\", i, length(fib[i]), entropy(fib[i]))\n    end\n    return 0\nend\n\nprintln(\"  n\\tlength\\tentropy\")\ntestfibbo(37)\n", "meta": {"hexsha": "e5f7436b3b908f2eb3ec53c0e89e77155f6e930b", "size": 647, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/fibonacci-word.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/fibonacci-word.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/fibonacci-word.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.1071428571, "max_line_length": 95, "alphanum_fraction": 0.5904173107, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7563391043943279}}
{"text": "# tests for functors\n\nusing Base.Test\nusing NumericExtensions\n\n## basic operators\n\n@test evaluate(Negate(),   2) == -2\n@test evaluate(Add(),      2, 3) == 5\n@test evaluate(Subtract(), 2, 3) == -1\n@test evaluate(Multiply(), 2, 3) == 6\n@test evaluate(Divide(),   2, 3) == 2 / 3\n@test evaluate(Modulo(),   5, 3) == 2\n@test evaluate(Pow(),      2, 3) == 8\n\n@test evaluate(Greater(),      2, 3) == false\n@test evaluate(Greater(),      2, 2) == false\n@test evaluate(GreaterEqual(), 2, 3) == false\n@test evaluate(GreaterEqual(), 2, 2) == true\n\n@test evaluate(Less(),      3, 2) == false\n@test evaluate(Less(),      3, 2) == false\n@test evaluate(LessEqual(), 3, 2) == false\n@test evaluate(LessEqual(), 2, 2) == true\n\n@test evaluate(Equal(), 3, 2)    == false\n@test evaluate(Equal(), 2, 2)    == true\n@test evaluate(NotEqual(), 3, 2) == true\n@test evaluate(NotEqual(), 2, 2) == false\n\n@test evaluate(Not(), true)  == false\n@test evaluate(Not(), false) == true\n@test evaluate(And(), true, false) == false\n@test evaluate(Or(),  true, false) == true\n\n@test evaluate(BitwiseNot(), 1) == ~1\n@test evaluate(BitwiseAnd(), 3, 6) == 2\n@test evaluate(BitwiseOr(),  3, 6) == 7\n@test evaluate(BitwiseXor(), 3, 6) == 5\n\n# elementary math\n\nx = 0.8\ny = 0.6\nz = 1.2\n\n@test evaluate(MinFun(), x, y) == min(x, y)\n@test evaluate(MaxFun(), x, y) == max(x, y)\n\n@test evaluate(AbsFun(), -0.5) == 0.5\n@test evaluate(Abs2Fun(), x) == abs2(x)\n@test evaluate(SqrFun(),  x) == sqr(x)\n@test evaluate(SqrtFun(), x) == sqrt(x)\n@test evaluate(CbrtFun(), x) == cbrt(x)\n@test evaluate(RcpFun(),  x) == rcp(x)\n@test evaluate(RsqrtFun(), x) == rsqrt(x)\n@test evaluate(RcbrtFun(), x) == rcbrt(x)\n\n@test evaluate(HypotFun(), x, y) == hypot(x, y)\n\n@test evaluate(IsfiniteFun(), 1.0) == true\n@test evaluate(IsfiniteFun(), Inf) == false\n@test evaluate(IsfiniteFun(), NaN) == false\n\n@test evaluate(IsinfFun(), 1.0) == false\n@test evaluate(IsinfFun(), Inf) == true\n@test evaluate(IsinfFun(), NaN) == false\n\n@test evaluate(IsnanFun(), 1.0) == false\n@test evaluate(IsnanFun(), Inf) == false\n@test evaluate(IsnanFun(), NaN) == true\n\n@test evaluate(FloorFun(), x) == floor(x)\n@test evaluate(CeilFun(), x)  == ceil(x)\n@test evaluate(RoundFun(), x) == round(x)\n@test evaluate(TruncFun(), x) == trunc(x)\n\n@test evaluate(IfloorFun(), x) == ifloor(x)\n@test evaluate(IceilFun(), x)  == iceil(x)\n@test evaluate(IroundFun(), x) == iround(x)\n@test evaluate(ItruncFun(), x) == itrunc(x)\n\n@test evaluate(ModFun(), x, y) == mod(x, y)\n@test evaluate(RemFun(), x, y) == rem(x, y)\n@test evaluate(FldFun(), x, y) == fld(x, y)\n@test evaluate(DivFun(), 8, 6) == 1\n\n@test evaluate(ExpFun(), x)   == exp(x)\n@test evaluate(Exp2Fun(), x)  == exp2(x)\n@test evaluate(Exp10Fun(), x) == exp10(x)\n@test evaluate(Expm1Fun(), x) == expm1(x)\n\n@test evaluate(LogFun(), x)   == log(x)\n@test evaluate(Log2Fun(), x)  == log2(x)\n@test evaluate(Log10Fun(), x) == log10(x)\n@test evaluate(Log1pFun(), x) == log1p(x)\n\n@test evaluate(SinFun(), x) == sin(x)\n@test evaluate(CosFun(), x) == cos(x)\n@test evaluate(TanFun(), x) == tan(x)\n@test evaluate(AsinFun(), x) == asin(x)\n@test evaluate(AcosFun(), x) == acos(x)\n@test evaluate(AtanFun(), x) == atan(x)\n@test evaluate(Atan2Fun(), x, y) == atan2(x, y)\n\n# ternary functors\n\n@test evaluate(FMA(), x, y, z) == (x + y * z)\n@test evaluate(IfelseFun(), true, y, z) == y\n@test evaluate(IfelseFun(), false, y, z) == z\n\n# Test unary functors\n\nfor e in [\n    (Negate, -),\n    (AbsFun, abs), (Abs2Fun, abs2), (SqrtFun, sqrt), (CbrtFun, cbrt), \n    (FloorFun, floor), (CeilFun, ceil), (RoundFun, round), (TruncFun, trunc), \n    (ExpFun, exp), (Exp2Fun, exp2), (Exp10Fun, exp10), (Expm1Fun, expm1),\n    (LogFun, log), (Log2Fun, log2), (Log10Fun, log10), (Log1pFun, log1p),\n    (SinFun, sin), (CosFun, cos), (TanFun, tan), (AsinFun, asin), (AcosFun, acos), (AtanFun, atan),\n    (SinhFun, sinh), (CoshFun, cosh), (TanhFun, tanh), (AsinhFun, asinh), (AcoshFun, acosh), (AtanhFun, atanh), \n    (ErfFun, erf), (ErfcFun, erfc), (GammaFun, gamma), (LgammaFun, lgamma), (DigammaFun, digamma), \n    (IsfiniteFun, isfinite), (IsinfFun, isinf), (IsnanFun, isnan)]\n\n    T = e[1]\n    f = e[2]\n\n    @test evaluate(T(), 1.0) === f(1.0)\n    @test evaluate(T(), 1) === f(1)\nend\n\n# Test binary functors\n\nfor e in [\n    (Add, +), \n    (Subtract, -), \n    (Multiply, *), \n    (Divide, /), \n    (Pow, ^), \n    (MaxFun, max),\n    (MinFun, min),\n    (HypotFun, hypot),\n    (Atan2Fun, atan2),\n    (Greater, >), \n    (GreaterEqual, >=),\n    (Less, <), \n    (LessEqual, <=), \n    (Equal, ==), \n    (NotEqual, !=)]\n\n    T = e[1]\n    f = e[2]\n\n    @test evaluate(T(), 2.0, 3.0) === f(2.0, 3.0)\n    @test evaluate(T(), 2, 3) === f(2, 3)\n    @test evaluate(T(), 2.0, 3) === f(2.0, 3)\n    @test evaluate(T(), 2, 3.0) === f(2, 3.0)\nend\n\n\n\n", "meta": {"hexsha": "3df866835fd2d11827059ae088c620230f9bb1c4", "size": 4748, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/functors.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": "test/functors.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": "test/functors.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": 29.3086419753, "max_line_length": 112, "alphanum_fraction": 0.5884582982, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7563390996917769}}
{"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               (\u0394z_u, \u0394z_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 ``(\u03b1_u,~ \u03b1_l)`` for the upper and lower surfaces (not necessarily of the same lengths), trailing-edge displacement values ``(\u0394z_u,~ \u0394z_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    # \u03bb-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 \u2208 xs ]\n    lower_surf = [ bernie(x, alpha_l, dz_l, LE_l) for x \u2208 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(\u03b1_c, \u03b1_t,\n               (\u0394z_u, \u0394z_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 ``(\u03b1_c,~ \u03b1_t)`` for the upper and lower surfaces, trailing-edge spacing values ``(\u0394z_u,~\u0394z_l)``, and a coefficient for the leading edge modifications at the nose.\n\"\"\"\nfunction camber_CST(\u03b1_cam, \u03b1_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    # \u03bb-function for Bernstein polynomials\n    bernie(x, \u03b1s, dz = 0.) = CST_coordinates(y -> bernstein_class(y, N1, N2), bernstein_basis, x, \u03b1s, dz, coeff_LE)\n\n    # Upper and lower surface generation\n    cam   = [ bernie(x, \u03b1_cam) for x \u2208 xs ]\n    thicc = [ bernie(x, \u03b1_thicc, dz_thicc) for x \u2208 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 \u2218 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 \u03b1 = \u03b2 = 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": "using Clustering, RDatasets, Random, Measures, Plots; pyplot()\nRandom.seed!(0)\n\nK = 3\ndf = dataset(\"cluster\", \"xclara\")\ndata = copy(convert(Array{Float64}, df)')\n\nseeds = initseeds(:rand, data, K)\nxclaraKmeans = kmeans(data, K, init = seeds)\n\nprintln(\"Number of clusters: \", nclusters(xclaraKmeans))\nprintln(\"Counts of clusters: \", counts(xclaraKmeans))\n\ndf.Group  = assignments(xclaraKmeans)\n\np1 = scatter(df[:, :V1], df[:, :V2], c=:blue, msw=0)\n     scatter!(df[seeds, :V1], df[seeds, :V2], markersize=12, c=:red, msw=0)\n\np2 = scatter( df[df.Group .== 1, :V1], df[df.Group .== 1, :V2], c=:blue, msw=0)\n     scatter!( df[df.Group .== 2, :V1], df[df.Group .== 2, :V2], c=:red, msw=0)\n     scatter!( df[df.Group .== 3, :V1], df[df.Group .== 3, :V2], c=:green, msw=0)\n\nplot(p1,p2,legend=:none,ratio=:equal,\n    size=(800,400), xlabel=\"V1\", ylabel=\"V2\", margin = 5mm)", "meta": {"hexsha": "7d022eebb443280a6c294ba54deff5c34bcab633", "size": 864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "9_chapter/kMeans.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": "9_chapter/kMeans.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": "9_chapter/kMeans.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": 36.0, "max_line_length": 81, "alphanum_fraction": 0.6238425926, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7563119363543226}}
{"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": "using RAFF\n\n#\n# This example is the \"Basic Usage\" example in the documentation\n#\n\n# Matrix with data\nA=[-2.0  5.0;\n   -1.5  3.25;\n   -1.0  2.0 ;\n   -0.5  1.25;\n    0.0  1.0 ;\n    0.5  2.55;\n    1.0  2.0 ;\n    1.5  3.25;\n    2.0  5.0 ;]\n\n# Define the model to fit data\nmodel(x, \u03b8) = \u03b8[1] * x[1]^2 + \u03b8[2]\n\n# Number of parameters in the model\nn = 2\n\n# Run RAFF\noutput = raff(model, A, n)\n\n# Print output\nprintln(output)\n\n", "meta": {"hexsha": "28ec0d580a343e9a7841fd209d158dad7d2ddb76", "size": 418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/basic_usage.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": "examples/basic_usage.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": "examples/basic_usage.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": 13.9333333333, "max_line_length": 64, "alphanum_fraction": 0.5502392344, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7562811161571057}}
{"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_\u03b2(\u03b2, \u03b7, D, R)\n    \u03b1 = 2.0 .- \u03b2 .^ (-  \u03b7 - 1.0 )\n    mask = R .<= 1.0 ./ \u03b1\n    s = 1.0 / (\u03b7 + 1.0)\n    \u03b2q = [ mask[i] ?  (R[i] * \u03b1[i])^s : (1.0 / (2.0 - R[i]*\u03b1[i]))^s for i in 1:D]\n    \u03b2q\nend\n\nfunction SBX_crossover(vector1, vector2, bounds, \u03b7=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    \u0394 = max.(eps(), y2 - y1)\n\n\n    R = rand(D)\n\n    \u03b2 = @. 1.0 + (2.0 * (y1 - xl) / \u0394)\n    \u03b2q = gen_\u03b2(\u03b2, \u03b7, D, R) \n    c1 = @. 0.5*(y1 + y2 -  \u03b2q*\u0394)\n\n    \u03b2 = @. 1.0 + (2.0 * (y1 - xl) / \u0394)\n    \u03b2q = gen_\u03b2(\u03b2, \u03b7, D, R) \n    c2 = @. 0.5*(y1 + y2 +  \u03b2q*\u0394)\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, \u03b7=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    \u03b41 = (x - xl) ./ (xu - xl)\n    \u03b42 = (xu - x) ./ (xu - xl)\n\n    D = length(xu)\n    R = rand(D)\n    mask = R .< 0.5\n    s = \u03b7+1.0\n    mut_pow = 1.0 / (\u03b7 + 1.0)\n    \u03b4q = [ mask[i] ?\n            ^(2.0R[i] + (1. - 2.0R[i]) * ^(1.0 - \u03b41[i], s), mut_pow) - 1.0 :\n            1.0 - (2.0 * (1.0 - R[i]) + 2.0 * (R[i] - 0.5) * ^(1.0 - \u03b42[i], s))^mut_pow\n            for i in 1:D\n        ]\n\n    vector[do_mutation] = x + \u03b4q .* ( 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": "using ApproxFun, Base.Test\n\n\n## ODEs\n\nd=Interval(-20000.,20000.)\nx=Fun(identity,d)\nu=[dirichlet(d);Derivative(d)^2+I]\\[1.,0.]\nu=[dirichlet(d);Derivative(d)^2+I]\\[1.,0.]\n@time u=[dirichlet(d);Derivative(d)^2+I]\\[1.,0.]\nprintln(\"Cos/Sin: should be ~0.017\")\n\n\nd=Interval(-1000.,5.)\nx=Fun(identity,d)\nu=[dirichlet(d);Derivative(d)^2-x]\\[1.,0.]\nu=[dirichlet(d);Derivative(d)^2-x]\\[1.,0.]\n@time u=[dirichlet(d);Derivative(d)^2-x]\\[1.,0.]\nprintln(\"Airy: 0.014356 seconds (1.08 k allocations: 8.015 MB)\")\n\nM=cache(ApproxFun.InterlaceOperator([dirichlet(d);Derivative(d)^2-x]);padding=true)\n@time ApproxFun.resizedata!(M,12500,:)\nprintln(\"Airy construct op: 0.005417 seconds (81 allocations: 5.279 MB)\")\n\n\n\nS=Chebyshev()\nx=Fun(identity,S)\nD=Derivative(S)\nL=D^2+(7+2x+6x^2)\nB=dirichlet(S)\nn=20000\nrhs=ones(n+2)\nu=[B;L]\\rhs\nu=[B;L]\\rhs\n@time u=[B;L]\\rhs\nprintln(\"Poly: should be ~0.025\")\n\n\nS=Chebyshev()\nx=Fun(identity,S)\nD=Derivative(S)\nL=D^2+cos(x)\nB=dirichlet(S)\nn=2000\nrhs=ones(n+2)\nu=linsolve([B;L],rhs;maxlength=Inf)\nu=linsolve([B;L],rhs;maxlength=Inf)\n@time u=linsolve([B;L],rhs;maxlength=Inf)\nprintln(\"Cos: should be ~0.0075\")\n\nS=Chebyshev()\nx=Fun(identity,S)\nD=Derivative(S)\nL=D^2+sin(x)\nB=dirichlet(S)\nn=2000\nrhs=ones(n+2)\nu=linsolve([B;L],rhs;maxlength=Inf)\nu=linsolve([B;L],rhs;maxlength=Inf)\n@time u=linsolve([B;L],rhs;maxlength=Inf)\nprintln(\"Sin: should be ~0.008663 seconds (660 allocations: 2.987 MB)\")\n\n\n## Piecewise\n\nx=Fun(identity,[-20.,-10.,-5.,0.,1.,15.])\nsp=space(x)\nD=Derivative(sp)\n\nu=[dirichlet(sp);\n    D^2-x]\\[airyai(-20.)];\n@time u=[dirichlet(sp);\n    D^2-x]\\[airyai(-20.)];\n\nprintln(\"Piecewise Airy: should be ~0.008\")\n\n\n## Vector\nd=Interval()\nD=Derivative(d);\nB=ldirichlet();\nBn=lneumann();\n\nf=Fun(x->[exp(x),cos(x)],d)\n\nA=[B 0;\n   Bn 0;\n   0 B;\n   D^2-I 2.0I;\n   0 D+I];\n\nu=A\\Any[0.,0.,0.,f]\n@time u=A\\Any[0.,0.,0.,f]\nprintln(\"Systems: should be ~0.0008\")\n\n\nd=Interval(-300.,5.)\nx=Fun(identity,d)\nA=Derivative(d)^2-x\nu=nullspace(A)\n@test_approx_eq A[1:10,1:10] (A.')[1:10,1:10].'\n@time u=nullspace(A)\nprintln(\"Nullspace Airy: 0.052730 seconds (75.21 k allocations: 56.736 MB)\")\n", "meta": {"hexsha": "34a1ed84d56c7090495ab46319d933ef75f31926", "size": 2098, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SpeedODETest.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": "test/SpeedODETest.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": "test/SpeedODETest.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": 19.980952381, "max_line_length": 83, "alphanum_fraction": 0.6530028599, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.756281113721643}}
{"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, \u03b8, p)\n    bh2o = p.bh2o_0 - z / cos(\u03b8)\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\u00e9vy, 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  \ud835\udca9 = 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 = \ud835\udca9(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(\ud835\udca9(i))\n      for k in 1:length(js)\n        j\u208b, j, j\u208a = js[k-1], js[k], js[k+1]\n        v\u1d62, v\u2c7c =  v[i],  v[j]\n        v\u208b, v\u208a = v[j\u208b], v[j\u208a]\n        \u03b1\u1d62\u2c7c = \u2220(v\u2c7c, v\u208b, v\u1d62)\n        \u03b2\u1d62\u2c7c = \u2220(v\u1d62, v\u208a, v\u2c7c)\n        L[i,j] = cot(\u03b1\u1d62\u2c7c) + cot(\u03b2\u1d62\u2c7c)\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": "module TestReturns\n\nusing Base.Test\nusing TimeData\nusing Econometrics\nusing DataFrames\nusing Dates\n\n## println(\"\\n Running return function tests\\n\")\n\n#########################\n## disc2log / log2disc ##\n#########################\n\n## percentage returns\n##-------------------\n\nret = Timematr(DataFrame(returns = [2, 3]))\n\n## log2disc(disc2log(x)) = x\nret2 = Econometrics.log2disc(Econometrics.disc2log(ret, percent=true),\n                             percent=true)\n\n@test_approx_eq TimeData.core(ret) TimeData.core(ret2)\n\n## no percentage returns\n##----------------------\n\nret = Timematr(DataFrame(returns = [0.2, 0.3]))\nret2 = Econometrics.log2disc(Econometrics.disc2log(ret, percent=false),\n                             percent=false)\n\n@test_approx_eq TimeData.core(ret) TimeData.core(ret2)\n\n\n###############\n## price2ret ##\n###############\n\nprices = testcase(TimeData.Timenum, 2)\nlogRet = Econometrics.price2ret(prices, log = true)\n\n## manually determine expected result\n##-----------------------------------\n\nidxs = prices.idx[2:end]\nexpTn = TimeData.Timenum(DataFrame(prices1 = @data([NA, 20, 30, 30]),\n                                   prices2 = @data([10, NA, 10, NA])),\n                         idxs)\n\n## test\n@test isequal(logRet, expTn)\n\n## test Timematr\n##--------------\n\nprices = testcase(TimeData.Timematr, 1)\nlogRet = Econometrics.price2ret(prices, log = true)\n\nidxs = prices.idx[2:end]\nexpTn = TimeData.Timematr(DataFrame(prices1 = [20, -10, 60],\n                                    prices2 = [10, -20, 30]),\n                          idxs)\n\n## test\n@test isequal(logRet, expTn)\n\n\n## same for discrete returns\n##--------------------------\n\nprices = TimeData.testcase(TimeData.Timenum, 2)\ndiscRet = Econometrics.price2ret(prices, log = false)\n\n@test_approx_eq ((140-120) / 120) TimeData.core(discRet[2, 1])\n@test_approx_eq ((120-110) / 110) TimeData.core(discRet[1, 2])\n@test isna(TimeData.core(discRet[2, 2])[1])\n\n\n###############\n## ret2price ##\n###############\n\n##################################\n## 1. example: NAs at beginning ##\n##################################\n\nprices = @data([NA, NA, 3, 4, 6])\n\n## using log returns\n##------------------\n\nlogRet = Econometrics.price2ret(prices, log = true)\nexpRets = @data([NA, NA, 1, 2])\n@test isequal(logRet, expRets)\n\nnormedPrices = Econometrics.ret2price(logRet, log = true)\nexpNormed = @data([NA, NA, 0, 1, 3])\n@test isequal(normedPrices, expNormed)\n\n## using dicrete returns\n##----------------------\n\ndiscRet = Econometrics.price2ret(prices, log = false)\nexpRets = @data([NA, NA, 1/3, 0.5])\n@test isequal(discRet, expRets)\n\nnormedPrices = Econometrics.ret2price(discRet, log = false)\nexpNormed = @data([NA, NA, 1, 1+1/3, 2])\n@test isequal(normedPrices, expNormed)\n\n################################\n## 2. example: NAs in between ##\n################################\n\nprices = @data([110, 120, NA, 130, NA])\n\n## using log returns\n##------------------\n\nlogRet = Econometrics.price2ret(prices, log = true)\nexpRets = @data([10, NA, 10, NA])\n@test isequal(logRet, expRets)\n\nnormedPrices = Econometrics.ret2price(logRet, log = true)\nexpNormed = @data([0, 10, NA, 20, NA])\n@test isequal(normedPrices, expNormed)\n\n## using dicrete returns\n##----------------------\n\ndiscRet = Econometrics.price2ret(prices, log = false)\nexpRets = @data([10/110, NA, 10/120, NA])\n@test isequal(discRet, expRets)\n\nnormedPrices = Econometrics.ret2price(discRet, log = false)\nexpNormed = @data([1, 1+10/110, NA, 1+20/110, NA])\n@test_approx_eq normedPrices[[1,2,4]] expNormed[[1,2,4]]\n\n########################\n## 3. example: no NAs ##\n########################\n\nprices = @data([100, 120, 110, 170, 160])\n\n## using log returns\n##------------------\n\nlogRet = Econometrics.price2ret(prices, log = true)\nexpRets = @data([20, -10, 60, -10])\n@test isequal(logRet, expRets)\n\nnormedPrices = Econometrics.ret2price(logRet, log = true)\nexpNormed = @data([0, 20, 10, 70, 60])\n@test isequal(normedPrices, expNormed)\n\n## using dicrete returns\n##----------------------\n\ndiscRet = Econometrics.price2ret(prices, log = false)\nexpRets = @data([0.2, -10/120, 60/110, -10/170])\n@test isequal(discRet, expRets)\n\nnormedPrices = Econometrics.ret2price(discRet, log = false)\nexpNormed = @data([1, 1.2, 1.1, 1.7, 1.6])\n@test_approx_eq normedPrices[[1,2,4]] expNormed[[1,2,4]]\n\n\n\n############################\n## same tests for Timenum ##\n############################\n\ndf = DataFrame()\ndf[:prices1] = @data([100, 120, 110, 170, 160])\ndf[:prices2] = @data([110, 120, NA, 130, NA])\ndf[:prices3] = @data([NA, NA, 3, 4, 6])\n\ndats = [Date(2010,1,1):Date(2010,1,5)]\nprices = Timenum(df, dats)\n\n## using log returns\n##------------------\n\nlogRet = Econometrics.price2ret(prices, log = true)\nnormedPrices = Econometrics.ret2price(logRet, log = true)\noriginalPrices = Econometrics.ret2price(logRet, prices, log = true)\n@test isequal(prices, originalPrices)\n\n## using dicrete returns\n##----------------------\n\ndiscRet = Econometrics.price2ret(prices, log = false)\nnormedPrices = Econometrics.ret2price(discRet, log = false)\noriginalPrices = Econometrics.ret2price(discRet, prices, log = false)\n@test isapprox(prices, originalPrices)\n\n\n########################\n## tests for Timematr ##\n########################\n\ndf = DataFrame()\ndf[:prices1] = @data([100, 120, 110, 170, 160])\ndats = [Date(2010,1,1):Date(2010,1,5)]\nprices = Timenum(df, dats)\n\n## using log returns\n##------------------\n\nlogRet = Econometrics.price2ret(prices, log = true)\nnormedPrices = Econometrics.ret2price(logRet, log = true)\noriginalPrices = Econometrics.ret2price(logRet, prices, log = true)\n@test isequal(prices, originalPrices)\n\n## using dicrete returns\n##----------------------\n\ndiscRet = Econometrics.price2ret(prices, log = false)\nnormedPrices = Econometrics.ret2price(discRet, log = false)\noriginalPrices = Econometrics.ret2price(discRet, prices, log = false)\n@test isapprox(prices, originalPrices)\n\nend\n", "meta": {"hexsha": "d7762f10ea87c39c27c74a2fe626e470ec651879", "size": 5874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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.1066666667, "max_line_length": 71, "alphanum_fraction": 0.5966973102, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7562811062660032}}
{"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\u2032(P, promote(collect(x), collect(y))..., deg; weights = weights, var = var)\n\n#  avoid issue  214\nfit\u2032(P::Type{<:AbstractPolynomial}, x, y, args...;kwargs...) = throw(MethodError(\"x and y do not produce abstract   vectors\"))\nfit\u2032(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} = \u27d2(P)(conj(coeffs(p)), p.var)\nLinearAlgebra.adjoint(p::P) where {P <: AbstractPolynomial} = \u27d2(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} = \u27d2(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 (-\u221e, \u221e), 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 \u2265 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 \u2264 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} = \u27d2(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} = \u27d2(P)(ones(eltype(P),1), var)  # assumes  p\u2080 = 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    \u27d2(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\u2080, r\u2081 = p1, p2\n    iter = 1\n    itermax = length(r\u2081)\n\n    while !iszero(r\u2081) && iter \u2264 itermax\n        _, rtemp = divrem(r\u2080, r\u2081)\n        r\u2080 = r\u2081\n        r\u2081 = truncate(rtemp; atol=atol, rtol=rtol)  \n        iter += 1\n    end\n    return r\u2080\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    \u0394  = norm(p1-p2)\n    if isfinite(\u0394)\n        return \u0394 <= 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, \u27d2(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, \u201cSplitting algorithms for the sum of two nonlinear\n# operators,\u201d SIAM Journal on Numerical Analysis, vol. 16, pp. 964\u2013979 (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, \u201cSplitting algorithms for the sum of two nonlinear operators,\u201d SIAM Journal on Numerical Analysis, vol. 16, pp. 964\u2013979 (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": "using Tau\nusing Base.Test\n\n@test tau == 2*pi\n@test float32(tau) == 2*float32(pi)\n@test float64(float32(tau)) == float64(2*float32(pi))\n@test big(tau) == 2(big(pi))\n@test isa(tau, MathConst)\n\n# degree-based trig functions\nfor T = (Float32,Float64)\n    for x = -2:0.1:2\n        @test_approx_eq_eps sintau(convert(T,x))::T convert(T,sin(tau*x)) eps(tau*convert(T,x))\n        @test_approx_eq_eps costau(convert(T,x))::T convert(T,cos(tau*x)) eps(tau*convert(T,x))\n    end\n    for x = 0.0:1.0:4.0\n        @test sintau(convert(T,x)) === zero(T)\n        @test sintau(-convert(T,x)) === -zero(T)\n    end\nend\n\n# check type stability\nfor T = (Float32,Float64,BigFloat)\n    for f = (sintau,costau)\n        @test Base.return_types(f,(T,)) == [T]\n    end\nend\n\n# Taken from /julia/test/mod2pi.jl\n@test_throws ErrorException modtau(int64(2)^60-1)\n\n@test_approx_eq modtau(10)          mod(10, tau)\n@test_approx_eq modtau(-10)         mod(-10, tau)\n@test_approx_eq modtau(355)         3.1416227979431572\n@test_approx_eq modtau(int32(355))  3.1416227979431572\n@test_approx_eq modtau(355.0)       3.1416227979431572\n@test_approx_eq modtau(355.0f0)     3.1416228f0\n@test modtau(int64(2)^60) == modtau(2.0 ^ 60)\n\n", "meta": {"hexsha": "e96b098326a16ca9900657accc049b22c33af877", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaPackageMirrors/Tau.jl", "max_stars_repo_head_hexsha": "47bd64c7e391bd0128b74fcee6f0747fe6c24545", "max_stars_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Tau.jl", "max_issues_repo_head_hexsha": "47bd64c7e391bd0128b74fcee6f0747fe6c24545", "max_issues_repo_licenses": ["MIT"], "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": "JuliaPackageMirrors/Tau.jl", "max_forks_repo_head_hexsha": "47bd64c7e391bd0128b74fcee6f0747fe6c24545", "max_forks_repo_licenses": ["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": 95, "alphanum_fraction": 0.6526845638, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7562628841689812}}
{"text": "FsumSq(x)=([sum(x.*x)],nothing) # must always return an array for the value\nFsumSq_inplace(value,auxvalue,x)=copy!(value,sum(x.*x))\n\nfunction FsumSq(x...)\n    tmp=0.0\n    for i in 1:length(x)\n        tmp+=sum(x[i].*x[i])\n    end\n    return ([tmp],nothing) # must always return an array for the value\nend\n\nfunction FsumSq_inplace(value,auxvalue,x...) # inplace\n    tmp=0.0\n    for i in 1:length(x)\n        tmp+=sum(x[i].*x[i])\n    end\n    copy!(value,tmp)\nend\n\n\nDsumSq(derivativeIDX,f_c,faux_c,grad_c,grad_n,x_n...)=axpy!(2.0,grad_c.*x_n[derivativeIDX],grad_n)\n\n\nif PROC==\"GPU\"\n    function FsumSq(x::CudaArray...)\n        tmp=CudaArray(zeros(1))\n        for i in 1:length(x)\n            CUBLAS.gemv!('T',1.0,flatten(Float64,x[i]),vec(x[i]),1.0,tmp)\n        end\n    return (tmp,nothing) # must always return an array for the value\n    end\n    \n    function FsumSq_inplace(value,auxvalue,x::CudaArray...) # inplace\n        fill!(value,0.0)\n        for i in 1:length(x)\n            CUBLAS.gemv!('T',1.0,flatten(Float64,x[i]),vec(x[i]),1.0,value);\n        end\n    end\n\n    function DsumSq(derivativeIDX,f_c,faux_c,grad_c,grad_n,x_n::CudaArray...)\n        alphaaxpy!(2.0,grad_c,x_n[derivativeIDX],grad_n)\n    end\n\nend\n\nInplace[FsumSq]=FsumSq_inplace\nDerivative[FsumSq]=DsumSq\n\nsumSq(n::ADnode)=ADnode(FsumSq,n)\n\nfunction sumSq(n::ArrayADnode)\n    return ADnode(FsumSq,n)\nend\n\nsumSquare=sumSq\n\nexport sumSq\nexport sumSquare\n", "meta": {"hexsha": "8e674aac99822b3e4c0ba4f5c667852a97e826eb", "size": 1418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/FsumSq.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/FsumSq.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/FsumSq.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": 24.0338983051, "max_line_length": 98, "alphanum_fraction": 0.6431593794, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.756262880107879}}
{"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\u2032(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\u2032), 0.0), Roots.Newton())\n    r = Roots.newton(x->(f(x),f(x)/f\u2032(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    \u03b4V =  - 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    \u03b4V =  - 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    \u2202\u00b2P = ForwardDiff.hessian(v, [0.0])\n    return \u2202\u00b2P[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 \u00b1 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 \u2208 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 \u2208 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": "\nf = x -> x^2 + 2x - 1\n\n\n# ---------------\nusing Plots\nplot(f, 0, 10, xlabel=\"x\", ylabel=\"y\")\n\nfunction myplot(x, y; style=:solid, width=1, color=:black)\n    plot(x, y, style=style, width=width, color=color)\nend\n\n\nx = collect(0:10)\ny = f.(x)\nmyplot(x,y)\nmyplot(x, y, style=:dot, color=:blue)\n\n\n\n\n# ---------- let Blocks --------\n\nx, y, z = -1, -1, -1\n\n@show x y z;\n\nlet x = 1, z\n    @show x y z;\nend\n\n@show x y z;\n\n# ---------- Tasks (aka Coroutines) --------\n\n#=\n    A task is a control structure that can pass control cooperatively\n    without returning.  A task is implemented as a function having as its first\n    argument a Channel object.  A Channel is used to pass values from the\n    function to a calee.\n=#\n\n\n\"\"\"\n    fib(c::Channel)\n\n    Generates a Fibonacci sequence.  Suspended after each call to put!.\n\"\"\"\nfunction fib(c::Channel)\n    a = 0\n    b = 1\n    put!(c, a)        # suspends, waits for channel to clear\n    while true\n        put!(c, b)    #suspends\n        (a, b) = (b, a+b)\n    end\nend\n\nfibgen = Channel(fib);\ntake!(fibgen)\ntake!(fibgen)\ntake!(fibgen)\ntake!(fibgen)\ntake!(fibgen)\ntake!(fibgen)\ntake!(fibgen)\ntake!(fibgen)\n\nfor val in Channel(fib)\n    print(val, \" \")\n    val > 30 && break\nend\n\n\n\n# ------- Types --------\n\n\n\n#=\n    A concrete type consisting of just bits is a primitive type.\n    Julia allows you to declare your own primitive types.\n\n    The standard types are defined as:\n\n    primitive type Float64 <: AbstractFloat 64 end\n    primitive type  Bool <: Integer 8 end\n    primitive type Char <: AbstractChar 32 end\n    primitive type Int64 <: Signed 64 end\n=#\n\n# Create primitive type Byte and constructor\nprimitive type Byte 8 end\nByte(val::UInt8) = reinterpret(Byte,val)\n\nb = Byte(0x1d);\ntypeof(b)\n@show b;\n\n# c = Byte(0xfff) # ERROR: MethodError: no method matching Byte(::UInt16)\n\n\n# Parametric types\n\nstruct Point{T<:Real}\n    x::T\n    y::T\n    Point{T}(x,y) where {T<:Real} = new(x,y)   # same as default inner constructor\nend\n\n\"\"\"\n    default outer constructor.\n    x, y have same type\n\"\"\"\nPoint(x::T, y::T) where {T<:Real} = Point{T}(x,y)\n\n\n\n\n\np = Point(0.0, 0.0)\nq = Point(3, 4)\n\n#=\nstruct Point{T<:Int64}\n    x::T\n    y::T\nend     #invalid redefinition of constant Point\n=#\n\n\nmp = IntPoint(3, 4)\n# Type Unions\n\n#  Efficient code can be generated when a type union has a small number of types\nIntOrString = Union{Int64, String}\n150 :: IntOrString\n\"Hello World\" :: IntOrString\n# 150 :: String      # TypeError\n\n# -------- Methods ----------\n\n# -------- Parametric Methods -------\nisintpoint(p::Point{T}) where {T} = (T === Int64)\nq\np\nisintpoint(q)\nisintpoint(p)\n\n# -------- Functors ---------\n\nstruct Polynomial{R}\n    coeff::Vector{R}\nend\n\n# Define a functor on instances of Polynomial\nfunction (p::Polynomial)(x)\n    val = p.coeff[end]\n    for coeff in p.coeff[end-1:-1:1]\n        val = val * x + coeff\n    end\n    val\nend\n\n\n# p(x) = 100x\u00b2 + 10x + 1\np = Polynomial([1,10,100])\np(3)\n\n\n\n#= -------- Conversion and Promotion ---------- =#\n\n# Conversion\nx = 12\ntypeof(x)\n\ny = convert(UInt8, x)\n\ntypeof(y)\ny\ntypeof(x)\nx\n\n\nPoint{Int64} isa Type{Point{Int64}}\n#Point{Int64} isa Point{Int64}\n#typeof(Point{Int64})\n\nBase.convert(::Type{Point{T}}, x::Array{T, 1}) where {T<:Real} = Point(x...)\nc = convert(Point{Int64}, [1,2]);\nc\n\n# Promotion\n\npromote(1, 2.5, 3)\n\n# specify promotion behavior using promote_rule\n\n# promote_rule(::Type{Float64}, ::Type{Int32}) = Float64\n", "meta": {"hexsha": "2973a29a95a0611b1468a11b6bb31c9308cf766e", "size": 3410, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ch19.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": "ch19.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": "ch19.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": 16.9651741294, "max_line_length": 82, "alphanum_fraction": 0.6105571848, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912749233991, "lm_q2_score": 0.8856314677809303, "lm_q1q2_score": 0.7562520014609488}}
{"text": "## Whittle.jl : implementation of Whittle covariance function\n\n## Whittle ##\nstruct Whittle{T} <: IsotropicCovarianceStructure{T}\n    \u03bb::T\n    \u03c3::T\n    p::T\n\n    function Whittle{T}(\u03bb::T, \u03c3::T, p::T) where T\n        \u03bb > 0 || throw(DomainError(\u03bb, \"correlation length \u03bb of Whittle covariance cannot be negative or zero\"))\n        \u03c3 > 0 || throw(DomainError(\u03c3, \"marginal standard deviation \u03c3 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}(\u03bb, \u03c3, p)\n    end\nend\n\n\"\"\"\n    Whittle(\u03bb, [\u03c3 = 1], [p = 2])\n\nWhittle covariance structure with correlation length `\u03bb`, (optional) marginal standard deviation `\u03c3` and (optional) `p`-norm, defined as\n    \n``C(x, y) = \u03c3 \\\\displaystyle\\\\frac{\u03c1}{\u03bb} K\u2081\\\\left(\\\\frac{\u03c1}{\u03bb}\\\\right)``\n\nwith ``\u03c1 = ||x-y||_p``.\n\n# Examples\n```jldoctest\njulia> Whittle(0.1)\nWhittle (\u03bb=0.1, \u03c3=1.0, p=2.0)\n\njulia> Whittle(1.0, \u03c3=2)\nWhittle (\u03bb=1.0, \u03c3=2.0, p=2.0)\n\n```\nSee also: [`Exponential`](@ref), [`Linear`](@ref), [`Spherical`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref), [`Matern`](@ref)\n\"\"\"\nWhittle(\u03bb::Real; \u03c3::Real=1.0, p::Real=2) = Whittle{promote_type(typeof(\u03bb),typeof(\u03c3),typeof(p))}(promote(\u03bb, \u03c3, p)...)\n\n# evaluate Whittle covariance\nfunction apply(w::Whittle, x::Real)\n    if iszero(x)\n        float(one(x))\n    else\n        \u03c1 = x / w.\u03bb\n        \u03c1 * besselk(1, \u03c1)\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": "using Test, BalancedIncompleteBlockDesigns\n\nn = 3\nb = n*n+n+1\nv = b\nk = n+1\nr = n+1\nl = 1\n\nA = prime_plane(3)\n@test BIBD_check(A) == (b,v,r,k,l)\n", "meta": {"hexsha": "80e43d4ca2c40c0cc4659ecb91b8384279ed6879", "size": 145, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 12.0833333333, "max_line_length": 42, "alphanum_fraction": 0.6137931034, "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566342024724488, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.756248340930855}}
{"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": "# This is an example script demonstrating how PARDISO works on a small,\n# sparse, real symmetric matrix. It computes the m solutions X to the\n# collection of linear systems\n#\n#    A * X = B\n#\n# using the PARDISO solver, where A is a symmetric n x n matrix, B is an\n# n x m matrix, and X is another n x m matrix.\nusing Pardiso\nusing SparseArrays\nusing Random\nusing Printf\nusing Test\n\n# Script parameters.\n# -----------------\nverbose = false\nn       = 4  # The number of equations.\nm       = 3  # The number of right-hand sides.\n\nA = sparse([ 1. 0 -2  3\n             0  5  1  2\n            -2  1  4 -7\n             3  2 -7  5 ])\n\n# Generate a random collection of right-hand sides.\nB = rand(n,m)\n\n# Initialize the PARDISO internal data structures.\n# ps = PardisoSolver()\nps = MKLPardisoSolver()\n\nif verbose\n    set_msglvl!(ps, Pardiso.MESSAGE_LEVEL_ON)\nend\n\n# If we want, we could just solve the system right now.\n# Pardiso.jl will automatically detect the correct matrix type,\n# solve the system and free the data\nX1 = solve(ps, A, B)\n\n# We also show how to do this in incremental steps.\n\n# ps = PardisoSolver()\nps = MKLPardisoSolver()\n\n# First set the matrix type to handle general real symmetric matrices\nset_matrixtype!(ps, Pardiso.REAL_SYM_INDEF)\n\n# Initialize the default settings with the current matrix type\npardisoinit(ps)\n\n# Remember that we pass in a CSC matrix to Pardiso, so need\n# to set the transpose iparm option.\nfix_iparm!(ps, :N)\n\n# Get the correct matrix to be sent into the pardiso function.\n# :N for normal matrix, :T for transpose, :C for conjugate\nA_pardiso = get_matrix(ps, A, :N)\n\n# Analyze the matrix and compute a symbolic factorization.\nset_phase!(ps, Pardiso.ANALYSIS)\nset_perm!(ps, randperm(n))\npardiso(ps, A_pardiso, B)\n@printf(\"The factors have %d nonzero entries.\\n\", get_iparm(ps, 18))\n\n# Compute the numeric factorization.\nset_phase!(ps, Pardiso.NUM_FACT)\npardiso(ps, A_pardiso, B)\n@printf(\"The matrix has %d positive and %d negative eigenvalues.\\n\",\n        get_iparm(ps, 22), get_iparm(ps, 23))\n\n# Compute the solutions X using the symbolic factorization.\nset_phase!(ps, Pardiso.SOLVE_ITERATIVE_REFINE)\nX = similar(B) # Solution is stored in X\npardiso(ps, X, A_pardiso, B)\n@printf(\"PARDISO performed %d iterative refinement steps.\\n\", get_iparm(ps, 7))\n\n# Compute the residuals.\nR = maximum(abs.(A*X - B))\n@printf(\"The maximum residual for the solution X is %0.3g.\\n\", R)\n@test R < 1e-10\n\n# Free the PARDISO data structures.\nset_phase!(ps, Pardiso.RELEASE_ALL)\npardiso(ps)\n", "meta": {"hexsha": "4cf47cd7ca082921af449684b8b76f363d59ff69", "size": 2509, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/examplesym.jl", "max_stars_repo_name": "j-fu/Pardiso.jl", "max_stars_repo_head_hexsha": "81c8391e86cebaf71e936363664d878b22b1fd9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 87, "max_stars_repo_stars_event_min_datetime": "2015-08-06T13:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T22:48:18.000Z", "max_issues_repo_path": "examples/examplesym.jl", "max_issues_repo_name": "j-fu/Pardiso.jl", "max_issues_repo_head_hexsha": "81c8391e86cebaf71e936363664d878b22b1fd9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2015-05-29T14:15:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T15:08:36.000Z", "max_forks_repo_path": "examples/examplesym.jl", "max_forks_repo_name": "j-fu/Pardiso.jl", "max_forks_repo_head_hexsha": "81c8391e86cebaf71e936363664d878b22b1fd9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2015-08-06T13:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T23:49:11.000Z", "avg_line_length": 28.8390804598, "max_line_length": 79, "alphanum_fraction": 0.7090474293, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7562270116464073}}
{"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        \u03b1 = targDen/targPrevious * propPrevious/propDen     # General formula for acceptance probability\n\n        accepted = \u03b1 >= 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        \u03b1 =  min(0, targDen - targPrevious)\n\n        accepted = \u03b1 >= 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": "# Functions related to the counting bound.\n# This version uses log-transformed numbers (but doesn't\n# use analytic approximations to binomial coefficients).\n# All logs are natural, unless otherwise noted.\n\nmodule LogCountingBound\n\nexport logNumMaximalCliques\n\n\"\"\"\n  Log of the 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: (natural log of) the number of maximal hypercliques.\n\t\tThis is approximate, as it's the expected number, and multiplies\n\t\tfloating point by adding logarithms.\n\"\"\"\nfunction logNumMaximalCliques(k, r, n)\n  k = BigInt(k)\n  r = BigInt(r)\n  n = BigInt(n)\n\n  # log of probability that one of those is\n\t# not covered by a larger clique\n  a = BigInt(2) ^ binomial(r, k-1)\n\t# ??? will this have enough significant figures?\n\tlogP = (log(a-1) - log(a)) * (n - r)\n\n    # number of possible cliques of this size\n\t\t(log(binomial(n, r))\n    # P(clique is present ...)\n\t\t+ (- log(BigInt(2)) * binomial(r, k))\n    # P( ... and not covered by a larger clique)\n    + logP)\nend\n\nend\n\n", "meta": {"hexsha": "145d1848e7dd94dca2d93c901e07d88fd2e99ea0", "size": 1214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "countingBound/julia/LogCountingBound.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/LogCountingBound.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/LogCountingBound.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": 28.9047619048, "max_line_length": 70, "alphanum_fraction": 0.6985172982, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254526, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7562264549354852}}
{"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\u03c0)\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\u03c0/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 \u2264 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 \u2264 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\u2013137.\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    \u03b2 = m/n\n    \u03c9 = (8*\u03b2) / (\u03b2+1+sqrt(\u03b2^2+14\u03b2+1))\n    c = sqrt(2*(\u03b2+1)+\u03c9)\n\n    if known_noise\n        return c\n    else\n        median = median_marcenko_pastur(\u03b2)\n        return c / sqrt(median)\n    end\nend\n\nfunction marcenko_pastur_density(t, lower, upper, beta)\n    sqrt((upper-t).*(t-lower))./(2\u03c0*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 \u2248 zero(eltype(gamma))\n        i, \u03f5 = quadgk(x->(x^gamma)*marcenko_pastur(x), x, upper)\n        return i\n    else\n        i, \u03f5 = 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    \u03c4 = optimal_svht(m,n)\n    inds = S .>= \u03c4*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    \u03c4 = optimal_svht(m,n)\n    inds = S .>= \u03c4*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\u2080 = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y\u2080[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\u2080 = conv(filterCoeffs[end:-1:1], paddedX)\n\t\t\ty[i,:] = y\u2080[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 \u2286 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-\u03ba-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    \u03b3::Vector{Float64} \n    \u03ba::Int # the number of possible colors\n    graph::Graph # the underlying graph which should be colored\n\n    function MaxKColSubgraphPhaseSeparationGate(\u03b3::Float64, \u03ba::Integer, graph::Graph)\n        \u03ba > 0 || throw(ArgumentError(\"Parameter `\u03ba` must be a positive integer.\"))\n        length(graph.edges) > 0 || throw(ArgumentError(\"Graph `graph` must have at least one edge.\"))\n        new([\u03b3], \u03ba, graph)\n    end\nend\n\n@memoize function max_k_col_subgraph_phase_separation_hamiltonian(graph::Graph, \u03ba::Int)\n    z = matrix(Z)\n    \n    # Implementation of Eq. (17)\n    # one-hot encoding: n * \u03ba vector. Index (a-1)*n + (b-1) corresponds to vertex a, color b.\n    H_P_enc = sum(\n        kron((color == a && vertex \u2208 edge ? z : I(2) for vertex \u2208 1:graph.n for color \u2208 1:\u03ba)...) # Z_{u,a} Z_{v,a}\n        for a \u2208 1:\u03ba for edge \u2208 graph.edges # \u03a3_{(u,v) = edge \u2208 E} \u03a3_{a=1..\u03ba}\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.\u03ba)\n\n    # Implementation of one-hot phase seperator, A.3.1, p. 34\n    U_P = exp(-im * g.\u03b3[] * H_P_enc)\n\n    U_P\nend\n\nQaintessent.adjoint(g::MaxKColSubgraphPhaseSeparationGate) = MaxKColSubgraphPhaseSeparationGate(-g.\u03b3[], g.\u03ba, g.graph)\n\nQaintessent.sparse_matrix(g::MaxKColSubgraphPhaseSeparationGate) = sparse(matrix(g))\n\n# Number of wires (\u03ba * n in the one-hot encoding)\nQaintessent.num_wires(g::MaxKColSubgraphPhaseSeparationGate)::Int = g.\u03ba * 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# \u2554\u2550\u2561 d66df1f3-c14a-440b-8148-7f5daa006f7c\nusing CSV\n\n# \u2554\u2550\u2561 bff18246-4ea2-43c0-9dca-69e855f06b7d\nusing Colors\n\n# \u2554\u2550\u2561 2c21b237-c4b7-4de2-b0ce-287bdf252081\nusing Plots\n\n# \u2554\u2550\u2561 25c8d94d-0393-4382-bbf4-500135b12f25\nusing LinearAlgebra\n\n# \u2554\u2550\u2561 34039790-f50e-11eb-0b84-25496cba179e\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(title = \"Contents\")\nend\n\n# \u2554\u2550\u2561 814a424a-96c4-4449-b002-f2e3122cb56d\nmd\"\"\"\n# Voronoi diagrams\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2208 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d7e145f0-afd7-4f7b-a570-a20f54444c06\nxs, ys = getpoints(\"voronoipoints.txt\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2208 1:1000\n        for x \u2208 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 \u2208 1:1000, y \u2208 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# \u2554\u2550\u2561 16ee482f-2d14-4fa4-84c4-fb02e29e4e5f\nbruteforcevoronoi(xs,ys)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 _ \u2208 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5619eeaa-d0ae-4752-987a-abc6b9236725\nmd\"\"\"\n## Constructing the Voronoi diagram geometrically\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f50845c7-45b1-46a0-9c7f-35303080b036\nbegin\n\tdiagram\u2081 = 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\u2081,\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\u2081,\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\u2081,\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\u2081,\n\t\t1.0865*cos.(0:0.01\u03c0:2.01\u03c0) .+ 85/12,\n\t\t1.0865*sin.(0:0.01\u03c0:2.01\u03c0) .+ 5/12,\n\t\tc = :gray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram\u2081,\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\u2081,\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\u2081,\n\t\t[(98/15,7/20),(131/20,17/30)],\n\t\tc = :grey\n\t)\n\t\n\tplot!(\n\t\tdiagram\u2081,\n\t\t[(104/15,19/20),(143/20,29/30)],\n\t\tc = :grey\n\t)\n\t\n\tplot!(\n\t\tdiagram\u2081,\n\t\t[(38/5,37/60),(449/60,4/5)],\n\t\tc = :grey\n\t)\n\t\n\tplot!(\n\t\tdiagram\u2081,\n\t\tShape([(3,-2),(5,-2),(5,3),(3,3)]),\n\t\tc = :white,\n\t\tlinecolor = :white\n\t)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7c392155-a7b1-4dfb-b6bb-bb52e8f071f7\nbegin\n\tdiagram\u2082 = 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\u2082,\n\t\t[(-2,0),(10,1)],\n\t\tc = :lightgray,\n\t\tlinestyle = :dash\n\t)\n\t\n\tplot!(\n\t\tdiagram\u2082,\n\t\t[(4.5,6.5/12),(5,7/12)],\n\t\tc = :black\n\t)\n\t\n\tscatter!(\n\t\tdiagram\u2082,\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c5553b17-c7a6-4c3d-92e2-9dff80c28867\nbegin\n\tdiagram\u2083 = 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\u2083,\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\u2083,\n\t\t[(0.75,1),(1.25,0.75)],\n\t\tc = :black,\n\t\tarrow = arrow(:closed)\n\t)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 283f5b27-6bd6-4cc2-98b7-d72377505626\nbegin\n\tdiagram\u2084 = 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\u2084,\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\u2084,\n\t\t[(0.75,1),(65/36,17/36)],\n\t\tc = :black\n\t)\n\t\n\tplot!(\n\t\tdiagram\u2084,\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\u2084,\n\t\t[(65/36,17/36),(2,-0.5)],\n\t\tc = :black,\n\t\tarrow = arrow(:closed)\n\t)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 00d09735-0b30-465c-9c39-81209d36265f\nVoronoiPoint(4,5)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4b3fc852-caae-4b8d-8582-f308a9a255ca\npos(p::VoronoiPoint) = [p.x, p.y]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 951bea47-8e23-45f9-b935-882566d3fdc3\nfunction circumcentre(p::VoronoiPoint, q::VoronoiPoint, r::VoronoiPoint)\n    (x\u2081, v\u2081) = perpbisector(p,q)\n    (x\u2082, v\u2082) = perpbisector(p,r)\n    det([v\u2081 v\u2082]) == 0 && return [Inf, Inf]\n    M = [v\u2081 v\u2082]^-1\n    t\u2081 = (M * (x\u2082 - x\u2081))[1]\n    return x\u2081 + t\u2081*v\u2081\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2208 q.neighbours\n        r \u2208 [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# \u2554\u2550\u2561 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 \u2208 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u1d62` (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\u1d62\u208b\u2081` and `q\u1d62\u208a\u2081` 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\u1d62\u208b\u2081` from the end and `q\u1d62\u208a\u2081` 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# \u2554\u2550\u2561 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 \u2208 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 \u2208 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# \u2554\u2550\u2561 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 \u2208 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\u2076\u00b3 - 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# \u2554\u2550\u2561 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 \u2208 2:length(xs)\n        push!(points,addpoint(xs[i],ys[i],points))\n    end\n    return points\nend\n\n# \u2554\u2550\u2561 cf3ddbb7-7a8c-4f4f-8970-c61fffe5f2b7\nmd\"\"\"\nThe data `xs` and `ys` result in the following list of `VoronoiPoint`s:\n\"\"\"\n\n# \u2554\u2550\u2561 4b153157-0ba1-4042-bea9-904e946a6ca2\npoints = voronoipoints(xs,ys)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b63bd719-a709-4a10-be7a-ac075d3ff3c4\npoints[1].neighbours\n\n# \u2554\u2550\u2561 6977e1e5-50f0-4da2-9acc-877d4140fa7c\npoints[12].neighbours\n\n# \u2554\u2550\u2561 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\u2081`, `v\u2082`, 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\u2082` in `t\u2082vals` and `t\u2081` in `t\u2081vals` modulo 4.\n```julia\nt\u2081index = findfirst(==(t\u2081),t\u2081vals)\nt\u2082index = findfirst(==(t\u2082),t\u2082vals)\nindexdifference = mod(t\u2082index - t\u2081index,4)\n```\n\nAs I know which indices correspond to which edges, I work around from the edge that t\u2081index corresponds to fill in each of the corners on the way to the edge that t\u2082index corresponds to.\n```julia\ncorners = [(0,0), (1000,0), (1000,1000), (0,1000)]\nfor j \u2208 1:indexdifference\n    push!(vertices,corners[mod(t\u2081index+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# \u2554\u2550\u2561 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 \u2208 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\u2081, v\u2081 = perpbisector(p.neighbours[n-1],p)\n            x\u2081, v\u2081 = Rational{Int64}.(x\u2081), Rational{Int64}.(v\u2081)\n            t\u2081vals =\n\t\t\t\t[-x\u2081[2]/v\u2081[2], (1000-x\u2081[1])/v\u2081[1], (1000-x\u2081[2])/v\u2081[2], -x\u2081[1]/v\u2081[1]]\n            t\u2081 = minimum(t\u2081vals[t\u2081vals .> 0])\n            push!(vertices,Tuple(x\u2081 + t\u2081*v\u2081))\n\n            x\u2082, v\u2082 = perpbisector(p,p.neighbours[2])\n            x\u2082, v\u2082 = Rational{Int64}.(x\u2082), Rational{Int64}.(v\u2082)\n            t\u2082vals =\n\t\t\t\t[-x\u2082[2]/v\u2082[2], (1000-x\u2082[1])/v\u2082[1], (1000-x\u2082[2])/v\u2082[2], -x\u2082[1]/v\u2082[1]]\n            t\u2082 = minimum(t\u2082vals[t\u2082vals .> 0])\n\n            t\u2081index = findfirst(==(t\u2081),t\u2081vals)\n            t\u2082index = findfirst(==(t\u2082),t\u2082vals)\n            indexdifference = mod(t\u2082index - t\u2081index,4)\n            corners = [(0,0), (1000,0), (1000,1000), (0,1000)]\n            for j \u2208 1:indexdifference\n                push!(vertices,corners[mod(t\u2081index+j, 1:4)])\n            end\n\n            push!(vertices,Tuple(x\u2082 + t\u2082*v\u2082))\n\n        else\n            startindex, endindex = 1, n\n        end\n\n        for j \u2208 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# \u2554\u2550\u2561 1520465f-d0f8-43b4-bb07-3daaa8c3e715\nbegin\n\tnamescam, xscam, yscam = getpoints(\"cambridgecolleges.txt\",true)\n\tvoronoi(xscam, yscam; names = namescam)\nend\n\n# \u2554\u2550\u2561 a278f976-7446-4c0a-8026-00ac80343759\nmd\"\"\"\nTrying it out on the sample data gives exactly the diagram I hoped for:\n\"\"\"\n\n# \u2554\u2550\u2561 bb9e1fc6-0ff6-46ce-aae7-9926841e6917\nvoronoi(xs,ys)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2208 1:m],\n        legend = false,\n        xticks = 1:m,\n        yticks = 0:0.1:1\n    )\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2c7a67e0-3ead-4988-9633-db0ad673b0a6\nn = 1000\n\n# \u2554\u2550\u2561 80360e43-0038-40b3-ae9c-28ad88959a97\nvoronoi(rand(1:100//n:1000, n),rand(1:100//n:1000, n))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 `\u03c3` to each point, rounded off to keep the coordinates rational. Then, I generate bar graphs using `voronoidistribution` as before.\n\"\"\"\n\n# \u2554\u2550\u2561 0ebcb0f4-159a-4f12-ba9d-f9887762b6e3\nfunction randomlattice(shape::Symbol, n::Int64, \u03c3::Rational{Int64})\n\tif shape == :square\n\t\tcoords = [(x,y) for x \u2208 1:n, y \u2208 1:n]\n\telseif shape == :hexagonal\n\t\tcoords = hcat([(x,(6//7)*y) for x \u2208 1:n, y \u2208 1:2:n],\n\t\t\t[(x+1//2,(6//7)*y) for x \u2208 1:n, y \u2208 2:2:n])\n\telse\n\t\terror(\"Invalid shape\")\n\tend\n\t\n\txs,ys = [xy[1] for xy \u2208 coords[:]], [xy[2] for xy \u2208 coords[:]]\n\trandxs = xs .+ \u03c3 * round.(Int64, n * randn(n^2))//n\n\trandys = ys .+ \u03c3 * round.(Int64, n * randn(n^2))//n\n\treturn voronoidistribution(voronoipoints(randxs,randys))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 08d69e9e-958e-4feb-adb8-9dd9019b2bf1\n\u03c3list = [1//1, 1//2, 1//5, 1//10]\n\n# \u2554\u2550\u2561 11949d3b-86cc-4969-b56e-1096f1a102b0\nmd\"\"\"\nFor the square lattice, a sample is:\n\"\"\"\n\n# \u2554\u2550\u2561 1bf7c58c-813a-4a21-a667-46a2e0758616\nplot(\n\t[randomlattice(:square, 30, \u03c3) for \u03c3 \u2208 \u03c3list]...,\n\ttitle = hcat([\"\u03c3 = $\u03c3\" for \u03c3 \u2208 \u03c3list]...),\n\tlayout = (2,2)\n)\n\n# \u2554\u2550\u2561 269b4fab-c944-425e-9cc1-7f43b03d9505\nmd\"\"\"\nAnd for the hexagonal lattice, with the same standard deviations:\n\"\"\"\n\n# \u2554\u2550\u2561 2e5d4be6-53d9-46b0-a5f4-29be3bd55142\nplot(\n\t[randomlattice(:hexagonal, 30, \u03c3) for \u03c3 \u2208 \u03c3list]...,\n\ttitle = hcat([\"\u03c3 = $\u03c3\" for \u03c3 \u2208 \u03c3list]...),\n\tlayout = (2,2)\n)\n\n# \u2554\u2550\u2561 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 `\u03c3`.\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 `\u03c3 = 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500814a424a-96c4-4449-b002-f2e3122cb56d\n# \u255f\u250026bf6d61-25e8-4558-97ea-72185b7dc963\n# \u255f\u2500a1f023ab-e2ab-4d74-8067-e364ddeaa7ed\n# \u2560\u25501520465f-d0f8-43b4-bb07-3daaa8c3e715\n# \u255f\u2500e9845cba-d61a-4150-9698-6dffbdde3138\n# \u255f\u25002b2f564c-03f1-4da0-941e-c08bff8203fc\n# \u2560\u2550d66df1f3-c14a-440b-8148-7f5daa006f7c\n# \u255f\u25003683349f-55da-4725-937c-882d620261ac\n# \u2560\u255000f99f29-fd88-4bdd-875a-83e892cf4182\n# \u255f\u250066f26cb1-958e-44e1-8ff2-0e65065347cd\n# \u2560\u2550d7e145f0-afd7-4f7b-a570-a20f54444c06\n# \u255f\u2500fa9cce06-5c0d-46d8-82a8-110777450737\n# \u2560\u2550bff18246-4ea2-43c0-9dca-69e855f06b7d\n# \u255f\u2500a5bae7fe-6bd8-49f8-9ccb-3567c4dceeee\n# \u2560\u25502c21b237-c4b7-4de2-b0ce-287bdf252081\n# \u255f\u250020a6f5d1-1df1-402f-bdb0-770e373a2caf\n# \u2560\u255004f8030e-a838-4e32-91c5-af63b50b8ef2\n# \u2560\u255016ee482f-2d14-4fa4-84c4-fb02e29e4e5f\n# \u255f\u2500c7ce5d31-c823-433e-90c7-474e5c64a25e\n# \u2560\u25500ecd4b67-aee6-4dfb-94e5-7cc8cae0c01d\n# \u255f\u25006ae8754a-9fb3-43a1-adcc-42411be63467\n# \u2560\u2550ac20813e-57ec-4f40-bbaa-eeed7557f2f5\n# \u255f\u25006f1c21bc-2803-4f10-ae1a-47fa6a883f19\n# \u255f\u25005619eeaa-d0ae-4752-987a-abc6b9236725\n# \u255f\u250035546877-09ce-4294-acd3-6150a2b3637d\n# \u255f\u2500f50845c7-45b1-46a0-9c7f-35303080b036\n# \u255f\u250026dfe1aa-9e61-46dd-953b-3164c4470458\n# \u255f\u25007c392155-a7b1-4dfb-b6bb-bb52e8f071f7\n# \u255f\u2500406599de-7141-4c59-a294-bffb79973098\n# \u255f\u2500c5553b17-c7a6-4c3d-92e2-9dff80c28867\n# \u255f\u250098e6d6c3-1623-403a-b066-bdd280aaee4e\n# \u255f\u2500283f5b27-6bd6-4cc2-98b7-d72377505626\n# \u255f\u250074fe0258-6c8e-4383-9aad-ffcb890e9612\n# \u255f\u25004ff3a96d-14dd-4af8-820a-bbb30c3fca15\n# \u2560\u25507d80b224-03ad-4034-af2d-7975b6e0e7a9\n# \u255f\u250026502d5d-54c6-4d57-9be4-5e8971635560\n# \u2560\u25508c07108a-49e0-4ef3-873c-e5d6576c99cc\n# \u2560\u255000d09735-0b30-465c-9c39-81209d36265f\n# \u255f\u2500ada943f1-077e-4fa0-9024-915e7d23c2e2\n# \u2560\u255025c8d94d-0393-4382-bbf4-500135b12f25\n# \u255f\u2500d3b2bb40-359e-4696-a74d-030afcf4f9c7\n# \u2560\u25504b3fc852-caae-4b8d-8582-f308a9a255ca\n# \u255f\u2500fc64f356-5550-4d43-8564-0d2002dc8316\n# \u2560\u25509b35606b-9175-40a5-99e8-62251e72f3a4\n# \u255f\u2500f2b1cc32-370f-465c-bab8-15365cf5de69\n# \u2560\u2550951bea47-8e23-45f9-b935-882566d3fdc3\n# \u255f\u25003ffacdd0-510f-4ef5-b934-4ff15b536b7c\n# \u2560\u2550c6ff22c9-16d8-494a-8b82-997a61ecf38c\n# \u255f\u25008f9286e4-f49d-4227-9611-9793f484d5dd\n# \u255f\u25003acc9ae8-c107-4434-b72d-590a1abc8130\n# \u255f\u2500e39cf938-c946-4a65-bb20-3c5c73bb0ef2\n# \u2560\u2550aee35cf6-8ef4-4550-b65f-a546416d642f\n# \u255f\u250011cd1d8b-6c81-4b15-b0ef-544bd477baed\n# \u2560\u25501883f53f-dc01-4eda-9ea6-a1d27bf17cdb\n# \u255f\u2500cf3ddbb7-7a8c-4f4f-8970-c61fffe5f2b7\n# \u2560\u25504b153157-0ba1-4042-bea9-904e946a6ca2\n# \u255f\u2500bbe2a7ab-24aa-4ebb-9323-a10cb4739f03\n# \u2560\u2550b63bd719-a709-4a10-be7a-ac075d3ff3c4\n# \u2560\u25506977e1e5-50f0-4da2-9acc-877d4140fa7c\n# \u255f\u250086b670fb-6a4c-406c-abdd-e9e81c460c57\n# \u2560\u2550d319f1c6-c329-4148-95c2-51e8814bcb56\n# \u255f\u2500a278f976-7446-4c0a-8026-00ac80343759\n# \u2560\u2550bb9e1fc6-0ff6-46ce-aae7-9926841e6917\n# \u255f\u250019d2d573-0857-456e-bd5b-e52962ce0e50\n# \u255f\u2500cdc7af5b-abcf-4b65-8a7c-274ad64a4bd3\n# \u2560\u2550f464f35c-0d4d-4d70-9632-6a09b1928695\n# \u255f\u250003348ff9-e422-4908-bd27-db4257511635\n# \u2560\u25502c7a67e0-3ead-4988-9633-db0ad673b0a6\n# \u2560\u255080360e43-0038-40b3-ae9c-28ad88959a97\n# \u2560\u2550716d84bf-0271-4f0c-a38f-3cf265dcc99f\n# \u255f\u25002939781c-0c22-4d10-9aa6-2218b00c4705\n# \u2560\u25500ebcb0f4-159a-4f12-ba9d-f9887762b6e3\n# \u255f\u250086663fe9-e192-4876-a61f-22e7647d8abe\n# \u2560\u255008d69e9e-958e-4feb-adb8-9dd9019b2bf1\n# \u255f\u250011949d3b-86cc-4969-b56e-1096f1a102b0\n# \u2560\u25501bf7c58c-813a-4a21-a667-46a2e0758616\n# \u255f\u2500269b4fab-c944-425e-9cc1-7f43b03d9505\n# \u2560\u25502e5d4be6-53d9-46b0-a5f4-29be3bd55142\n# \u255f\u250074dcc761-2448-4d74-af28-756fa473f3ea\n# \u255f\u250034039790-f50e-11eb-0b84-25496cba179e\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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_\u03bd} \u03bd \\nabla^{2 n_\u03bd}``, \n# with ``\u03bd`` the viscosity coefficient and ``n_\u03bd`` 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   \u03bd :: T         # Hyperviscosity coefficient\n  n\u03bd :: 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 `\u03b7` and their Fourier transforms `uh`, `vh`, and `\u03b7h`.\n\nstruct Vars{Aphys, Atrans} <: AbstractVars\n   u :: Aphys\n   v :: Aphys\n   \u03b7 :: Aphys\n  uh :: Atrans\n  vh :: Atrans\n  \u03b7h :: 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 \u03b7\n  @devzeros Dev Complex{T} grid.nkr uh vh \u03b7h\n  \n  return Vars(u, v, \u03b7, uh, vh, \u03b7h)\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.\u03b7h = sol[:, 3]\n  \n  @. N[:, 1] =   params.f * vars.vh - im * grid.kr * params.g * vars.\u03b7h    #  + f v - g \u2202\u03b7/\u2202x\n  @. N[:, 2] = - params.f * vars.uh                                        #  - f u\n  @. N[:, 3] = - im * grid.kr * params.H * vars.uh                         #  - H \u2202u/\u2202x\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.\u03bd * grid.kr^(2*params.n\u03bd)\n  \n  L[:, 1] .= D # for u equation\n  L[:, 2] .= D # for v equation\n  L[:, 3] .= D # for \u03b7 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.\u03b7h = 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.\u03b7, 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\u03b7!(prob, u0, v0, \u03b70)\nSets the state variable `prob.sol` as the Fourier transforms of `u0`, `v0`, and `\u03b70`\nand update all variables in `prob.vars`.\n\"\"\"\nfunction set_uv\u03b7!(prob, u0, v0, \u03b70)\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.\u03b7h, grid.rfftplan, A(\u03b70)) # A(\u03b70) converts u0 to the same type as vars expects (useful if \u03b70 is a CPU array while working on the GPU)\n\n  @. sol[:, 1] = vars.uh\n  @. sol[:, 2] = vars.vh\n  @. sol[:, 3] = vars.\u03b7h\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\u207b\u00b2)\nH  = 200.0      # Fluid depth (m)\nf  = 1e-2       # Coriolis parameter (s\u207b\u00b9)\n\u03bd  = 100.0      # Viscosity (m\u00b2 s\u207b\u00b9)\nn\u03bd = 1          # Viscosity order (n\u03bd = 1 means Laplacian \u2207\u00b2)\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(\u03bd, n\u03bd, 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 = \"\u03b7 [m]\",\n     title = \"A gaussian bump with half-width \u2248 \"*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 \u03b7(x,t=0) (m)\n\u03b7_noise = noise_amplitude * Random.randn(size(grid.x))\n@. \u03b7_noise *= mask    # mask the noise\n\nplot_noise = plot(grid.x/1e3, \u03b7_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 = \"\u03b7 [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\u03b7!()` to set the initial condition to the problem `prob`.\n\n\u03b70 = @. gaussian_bump + \u03b7_noise\nu0 = zeros(grid.nx)\nv0 = zeros(grid.nx)\n\nset_uv\u03b7!(prob, u0, v0, \u03b70)\n\nplot(grid.x/1e3, \u03b70,    # 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 = \"\u03b7 [m]\",\n     title = \"initial surface elevation, \u03b7(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_\u03b7 = plot(grid.x/1e3, vars.\u03b7,         # 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 = \"\u03b7 [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\u207b\u00b9]\")\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\u207b\u00b9]\")\n\n  Ld = @sprintf \"%.2f\" sqrt(g*H)/f /1e3     # divide with 1e3 to convert m -> km\n  plottitle = \"Deformation radius \u221a(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_\u03b7, 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.\u03b7    # updates the plot for \u03b7\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 \u2202\u03b7/\u2202y = 0\nv_geostrophic = params.g / params.f * irfft(im * grid.kr .* vars.\u03b7h, grid.nx)  #g/f \u2202\u03b7/\u2202x\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 \u2202\u03b7/\u2202y\"],\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\u207b\u00b9]\")\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 \u2202\u03b7/\u2202x\"],\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\u207b\u00b9]\")\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 DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing CSV\n# using DataFrames\nusing StatsBase\nusing Distributions\nusing Plots\nusing StatsPlots\nusing Optim\nusing Turing\n\n# include(srcdir(\"quap.jl\"))\n\n# %%\nd = CSV.read(datadir(\"exp_raw/Howell_1.csv\"), copycols = true)\nd2 = filter(row -> row.age >= 18, d)\nd2 = d[d.age .>= 18, :]\n\n# %%\n@model height(heights) = begin\n    \u03bc ~ Normal(178, 20)\n    # \u03c3 ~ Uniform(0, 50)\n    # heights .~ Normal(\u03bc, \u03c3)\n    heights .~ Normal(\u03bc, 5.0)\nend\n\n@model line(x, y) = begin\n    #priors\n    alpha ~ Normal(178.0, 100.0)\n    beta ~ Normal(0.0, 10.0)\n    s ~ Uniform(0, 50)\n\n    #model\n    mu = alpha .+ beta*x\n    y .~ Normal.(mu, s)\nend\n\nm = height(d2.height)\nm2 = line(d2.weight, d2.height)\n\n\n# %%\nsample(m, NUTS(0.65), 1000)\n\n\nopt = optimize(m, MAP(), [178.0, 25.0])\ncoeftable(opt)\ninformationmatrix(opt)\n\nusing LinearAlgebra\nfunction quap(model::Turing.Model, args...; kwargs...)\n    opt = optimize(model, MAP(), args...; kwargs...)\n\n    map = opt.values.array\n    var_cov_matrix = informationmatrix(opt)\n    sym_var_cov_matrix = Symmetric(var_cov_matrix)  # lest MvNormal complains, loudly\n    converged = Optim.converged(opt.optim_result)\n\n    distr = if length(map) == 1\n        Normal(map[1], \u221asym_var_cov_matrix[1])  # Normal expects stddev\n    else\n        @show sym_var_cov_matrix\n        MvNormal(map, sym_var_cov_matrix)       # MvNormal expects variance matrix\n    end\n\n    (coef = map, vcov = sym_var_cov_matrix, converged = converged, distr = distr)\nend\n\nr = quap(m)\nr2 = quap(m2, Optim.NelderMead())\n\nrand(MvNormal([0.0], [0.5]), 10000) |> histogram\n\nrand(MvNormal([0.0], [0.5]), 10000)' |> histogram\nrand(Normal(0.0, 0.5), 10000) |> histogram\n\nMvNormal([0.0], [0.5])\n\n\nI now also return a normal distribution to sample from since the 1D case had the `Normal(MAP[1], vcov[1])` pitfall which would incorrectly use the variance instead of the std dev.\n", "meta": {"hexsha": "c427ea46cd13e98df998bce861ad1b0e085618c7", "size": 1894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_research/snippet_04_quap.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": "_research/snippet_04_quap.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": "_research/snippet_04_quap.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.8192771084, "max_line_length": 179, "alphanum_fraction": 0.6531151003, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.756120085471689}}
{"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\u03bcs = [[0., 0.], [5., 5.]]\nx1 = rand(MvNormal(\u03bcs[1], 1.), N)\nx2 = rand(MvNormal(\u03bcs[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    \u03bc = 0.\n    \u03c3 = 1.\n    \u03bc1 ~ Normal(\u03bc, \u03c3)\n    \u03bc2 ~ Normal(\u03bc, \u03c3)\n    locs = [\u03bc1, \u03bc2]\n    \u03b1 = 1.\n    weights ~ Dirichlet(K, \u03b1)  # 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, :\u03bc1, :\u03bc2, :weights)  # Hamiltonian Monte Carlo (continuous)\n    # HMC(0.05, 10, :\u03bc1, :\u03bc2, )  # 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(\"\u03bc\", 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, \u03bc)\n    # Use log-sum-exp trick for numeric stability.\n    return Turing.logaddexp(\n        log(w[1]) + logpdf(MvNormal([\u03bc[1], \u03bc[1]], 1.), [x, y]),\n        log(w[2]) + logpdf(MvNormal([\u03bc[2], \u03bc[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[:\u03bc1].value), mean(chain[:\u03bc2].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 = \u03c4inv*(v +  a - b*w)\nend a b \u03c4inv 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": "using Stats\nusing Base.Test\n\n## moments\n\nwv = weights(ones(5) * 2.0)\n\n@test_approx_eq skewness(1:5) 0.0\n@test_approx_eq skewness([1, 2, 3, 4, 5]) 0.0\n@test_approx_eq skewness([1, 2, 2, 2, 5]) 1.1731251294063556\n@test_approx_eq skewness([1, 4, 4, 4, 5]) -1.1731251294063556\n\n@test_approx_eq skewness([1, 2, 2, 2, 5], wv) 1.1731251294063556\n\n@test_approx_eq kurtosis(1:5) -1.3\n@test_approx_eq kurtosis([1, 2, 3, 4, 5]) -1.3\n@test_approx_eq kurtosis([1, 2, 3, 3, 2]) -1.1530612244897953\n\n@test_approx_eq kurtosis([1, 2, 3, 4, 5], wv) -1.3\n\n## variability\n\n@test_approx_eq variation([1:5]) 0.527046276694730\n\n@test_approx_eq sem([1:5]) 0.707106781186548\n\n@test_approx_eq mad([1:5], 3) 1.4826\n@test_approx_eq mad([1:5]) 1.4826\n@test_approx_eq mad(1:5) 1.4826\n\n# min/max related\n\n@test minmax(1:5) == (1,5)\n@test minmax([3, 2, 7, 1, 4]) == (1,7)\n@test minmax([3.0, NaN, 1.0, NaN, 2.0]) == (1.0, 3.0)\n\n@test_approx_eq midrange([1, 2, 3, 4, 5]) 3.0\n@test_approx_eq midrange([1, 2, 2, 2, 5]) 3.0\n@test_approx_eq midrange([1, 4, 4, 4, 5]) 3.0\n@test_approx_eq midrange([1:5]) 3.0\n\n@test_approx_eq range([1, 2, 3, 4, 5]) 4.0\n@test_approx_eq range([1, 2, 2, 2, 5]) 4.0\n@test_approx_eq range([1, 4, 4, 4, 5]) 4.0\n@test_approx_eq range([1:15]) 14.0\n\n# quantile & friends\n\n@test_approx_eq quantile(1:5) [1:5]\n@test_approx_eq nquantile(1:5, 2) [1, 3, 5]\n@test_approx_eq nquantile(1:5, 4) [1:5] \n\n@test_approx_eq percentile([1:5], 25) 2.0\n@test_approx_eq percentile([1:5], [25, 50, 75]) [2.0, 3.0, 4.0]\n@test_approx_eq iqr(1:5) 2.0\n\n# mode & modes\n\n@test mode([1, 2, 3, 3, 2, 2, 1], 1:3) == 2\n@test modes([1, 2, 3, 3, 2, 2, 1], 1:3) == [2]\n@test modes([1, 3, 2, 3, 3, 2, 2, 1], 1:3) == [2, 3]\n\n@test mode([1, 2, 3, 3, 2, 2, 1]) == 2\n@test modes([1, 2, 3, 3, 2, 2, 1]) == [2]\n@test sort(modes([1, 3, 2, 3, 3, 2, 2, 1])) == [2, 3]\n\n# summarystats\n\ns = summarystats(1:5)\n@test isa(s, Stats.SummaryStats)\n@test s.min == 1.0\n@test s.max == 5.0\n@test_approx_eq s.mean 3.0\n@test_approx_eq s.median 3.0\n@test_approx_eq s.q25 2.0\n@test_approx_eq s.q75 4.0\n\n\n", "meta": {"hexsha": "df864578ddf4f11ca96019c7f7aa41591804d8bc", "size": 2031, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/scalarstats.jl", "max_stars_repo_name": "rened/Stats.jl", "max_stars_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-20T16:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T16:09:54.000Z", "max_issues_repo_path": "test/scalarstats.jl", "max_issues_repo_name": "rened/Stats.jl", "max_issues_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_issues_repo_licenses": ["Xnet", "X11"], "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/scalarstats.jl", "max_forks_repo_name": "rened/Stats.jl", "max_forks_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7088607595, "max_line_length": 64, "alphanum_fraction": 0.6287543082, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.7560856013755111}}
{"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": "using KrylovMethods\nusing Base.Test\ninclude(\"getDivGrad.jl\")\n\n\nprintln(\"=== Testing SSOR for real matrix ===\")\n# small full system\n\n# CG: test sparse Laplacian\nA = getDivGrad(32,32,32)\nrhs = randn(size(A,1))\ntol = 1e-2\n\n# tests with A being matrix\nx1,flag1,relres1,iter1,resvec1       = ssor(A,rhs,tol=tol,maxIter=100)\nx2,flag2,relres2,iter2,resvec2       = ssor(A,rhs,tol=tol,maxIter=100,omega=2/3,out=1)\nx3,flag3,relres3,iter3,resvec3     = ssor(A,rhs,tol=tol,maxIter=100,omega=1/2,out=1,storeInterm=true)\n\n# test relative residuals\n@test norm(A*x1-rhs)/norm(rhs) <= tol\n@test norm(A*x2-rhs)/norm(rhs) <= tol\n@test norm(A*x3[:,end]-rhs)/norm(rhs) <= tol\n\nprintln(\"=== Testing SSOR as Preconditioner ===\")\nomega = 1.2;\nd = omega./diag(A);\nx = zeros(length(rhs)) # pre allocation for the preconditioner result.\nPC = r -> (x[:]=0.0; return ssorPrecTrans!(A,x,r,d));\ny = KrylovMethods.cg(A,rhs,tol=1e-12,maxIter=200,M=PC,out=1)[1]\n@test norm(A*y-rhs)/norm(rhs) <= 1e-12\n\nprintln(\"=== Testing SSOR for complex matrix ===\")\n# small full system\n\n# CG: test sparse Laplacian\nA = getDivGrad(32,32,32) \nA += 1im*speye(size(A,1))\nrhs = randn(size(A,1)) + 1im * randn(size(A,1))\ntol = 1e-2\n\n#\nx0,flag0,relres0,iter0,resvec0       = ssor(A,rhs,tol=tol,maxIter=3,out=2)\n@test flag0==-1\n@test iter0==3\n@test length(resvec0)==3\n\n# tests with A being matrix\nx1,flag1,relres1,iter1,resvec1       = ssor(A,rhs,tol=tol,maxIter=100)\nx2,flag2,relres2,iter2,resvec2       = ssor(A,rhs,tol=tol,maxIter=100,omega=2/3,out=1)\nx3,flag3,relres3,iter3,resvec3       = ssor(A,rhs,tol=tol,maxIter=100,omega=1/2,out=1)\n\n# test relative residuals\n@test norm(A*x1-rhs)/norm(rhs) <= tol\n@test norm(A*x2-rhs)/norm(rhs) <= tol\n@test all(diff(resvec1).<0)\n@test all(diff(resvec2).<0)\n@test all(diff(resvec3).<0)\n\nprintln(\"=== SSOR : All tests passed. ====\")\n", "meta": {"hexsha": "a70fc0ef26bf2a6aaaa3e694f40927f275a4459b", "size": 1821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testSSOR.jl", "max_stars_repo_name": "Pbellive/KrylovMethods.jl", "max_stars_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_stars_repo_licenses": ["MIT"], "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/testSSOR.jl", "max_issues_repo_name": "Pbellive/KrylovMethods.jl", "max_issues_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_issues_repo_licenses": ["MIT"], "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/testSSOR.jl", "max_forks_repo_name": "Pbellive/KrylovMethods.jl", "max_forks_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_forks_repo_licenses": ["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.35, "max_line_length": 101, "alphanum_fraction": 0.6765513454, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7560855861419664}}
{"text": "using DSGE\nusing Base.Test\n\n# Test `hessizero` in context of Rosenbrock function\nfunction rosenbrock(x::Vector)\n    a = 100\n    b = 1\n    return a*(x[2]-x[1]^2.0)^2.0 + b*(1-x[1])^2.0\nend\n\nfunction rosenbrock_hessian(x::Vector)\n    H = zeros(eltype(x), 2, 2)\n    H[1,1] = 2.0 - 400.0 * x[2] + 1200.0 * x[1]^2.0\n    H[1,2] = -400.0 * x[1]\n    H[2,1] = -400.0 * x[1]\n    H[2,2] = 200.0\n    return H\nend\n\n# At the min, ensure no negatives in diagonal\nx0 = [1.0, 1.0]\nhessian_expected = rosenbrock_hessian(x0)\nhessian, _ = DSGE.hessizero(rosenbrock, x0; check_neg_diag=true)\n@testset \"Check valid hessian at the minimum\" begin\n    @test_matrix_approx_eq hessian_expected hessian\nend\n\n# Not at the min (indeed, we are at max), ensure throws error\nx1 = [1.0, 1.0]\nrosenbrock_neg(x) = -rosenbrock(x)\n@testset \"Throw error for hessian calculation not at the min\" begin\n    @test_throws Exception hessian, _ = DSGE.hessizero(rosenbrock_neg, x1; check_neg_diag=true)\nend\n\n# Not at the min, check matches closed form\nx1 = Vector[[0.5, 1.5], [-1.0, -1.0]]\n@testset \"Check closed-form of the hessian\" begin\n    for x in x1\n        hessian_expected = rosenbrock_hessian(x)\n        hessian, _ = DSGE.hessizero(rosenbrock, x)\n        @test @test_matrix_approx_eq hessian_expected hessian\n    end\nend\n", "meta": {"hexsha": "67ddf3c51b295c0ab4a5a75907046e79b57ae70c", "size": 1284, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/estimate/hessizero.jl", "max_stars_repo_name": "wegamekinglc/DSGE.jl", "max_stars_repo_head_hexsha": "9681dcdd6c33fa39fcb8e9f67fd284015d071c27", "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/estimate/hessizero.jl", "max_issues_repo_name": "wegamekinglc/DSGE.jl", "max_issues_repo_head_hexsha": "9681dcdd6c33fa39fcb8e9f67fd284015d071c27", "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/estimate/hessizero.jl", "max_forks_repo_name": "wegamekinglc/DSGE.jl", "max_forks_repo_head_hexsha": "9681dcdd6c33fa39fcb8e9f67fd284015d071c27", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-18T17:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T17:27:27.000Z", "avg_line_length": 29.1818181818, "max_line_length": 95, "alphanum_fraction": 0.6721183801, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7560855815435066}}
{"text": "\"\"\"\n    conductance(h::Hypergraph, subset::Set{Int})::Float64\n\nCalculate unweighted hypergraph conductance of `subset`.\nnote: \u2205 \u228a `subset` \u228a `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.\u03a3\n    P_p_inv = inv(P_p)\n\n    G = x_curr.\u03a3 * Ah' * P_p_inv\n\n    smoothed_mean = x_curr.\u03bc + G * (x_next_smoothed.\u03bc - x_pred.\u03bc)\n    smoothed_cov =\n        (X_A_Xt(x_curr.\u03a3, (I - G * Ah)) + X_A_Xt(Qh, G) + X_A_Xt(x_next_smoothed.\u03a3, 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.\u03a3\n    P_p_inv = inv(P_p)\n\n    G = x_curr.\u03a3 * Ah' * P_p_inv\n\n    smoothed_mean = x_curr.\u03bc + G * (x_next_smoothed.\u03bc - x_pred.\u03bc)\n\n    _R = [\n        x_curr.\u03a3.squareroot' * (I - G * Ah)'\n        Qh.squareroot' * G'\n        x_next_smoothed.\u03a3.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.\u03a3 * Ah' * P_p_inv\n    P_p_chol = Cholesky(x_pred.\u03a3.squareroot, :L, 0)\n    G = rdiv!(_matmul!(G1, x_curr.\u03a3.mat, Ah'), P_p_chol)\n\n    x_curr.\u03bc .+= G * (x_next.\u03bc .- x_pred.\u03bc)\n\n    # Joseph-Form:\n    M, L = C2.mat, C2.squareroot\n    D = length(x_pred.\u03bc)\n\n    _matmul!(G2, G, Ah)\n    copy!(view(L, 1:D, 1:D), x_curr.\u03a3.squareroot)\n    _matmul!(view(L, 1:D, 1:D), G2, x_curr.\u03a3.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.\u03a3.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.\u03a3.squareroot, QL)\n    _matmul!(x_curr.\u03a3.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 \u2264 x[1:2] \u2264 10)\n@disjunction(\n    m,\n    begin\n        con1[i=1:2], 0 \u2264 x[i] \u2264 [3,4][i]\n    end,\n    begin\n        con2[i=1:2], [5,4][i] \u2264 x[i] \u2264 [9,6][i]\n    end,\n    reformulation = :big_m,\n    name = :y\n)\nprint(m)\n\n# \u250c 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# \u250c 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\u03c3 = 0.007\n# Do the weight matrix computation\nW007 = image_Gaussian_affinity(matrix, r, \u03c3)    \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 \u03c3 value\n\u03c3 = 0.07\nW07 = image_Gaussian_affinity(matrix, r, \u03c3)    \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 (\u03c3 = 0.07)\", \n      \"eGHWT (\u03c3 = 0.07)\", \"Graph Haar (\u03c3 = 0.007)\", \n      \"eGHWT (\u03c3 = 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": "module CompactBasisFunctions\n\n    using ContinuumArrays\n    using StaticArrays\n\n    import Base: *\n    import ContinuumArrays: Mul, QMul2, QuasiAdjoint, (..), @simplify\n\n    export Derivative, \u2135\u2081\n\n    include(\"vandermonde_matrix.jl\")\n\n    export Basis, basis, nbasis, grid, degree, order\n\n    include(\"basis.jl\")\n\n    export Bernstein, BernsteinDerivative,\n           Chebyshev, ChebyshevDerivative,\n           ChebyshevT, ChebyshevTDerivative,\n           ChebyshevU, ChebyshevUDerivative,\n           Lagrange, LagrangeDerivative,\n           LagrangeGau\u00df, LagrangeLobatto,\n           Legendre, LegendreDerivative\n\n    include(\"bernstein.jl\")\n    include(\"chebyshev.jl\")\n    include(\"lagrange.jl\")\n    include(\"legendre.jl\")\n\nend\n", "meta": {"hexsha": "a97bf6362827585bf35550d9dc80ef223e1c387d", "size": 729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CompactBasisFunctions.jl", "max_stars_repo_name": "JuliaGNI/CompactBasisFunctions.jl", "max_stars_repo_head_hexsha": "5a76714aca25c399d0856643aff3683d8e0f103a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CompactBasisFunctions.jl", "max_issues_repo_name": "JuliaGNI/CompactBasisFunctions.jl", "max_issues_repo_head_hexsha": "5a76714aca25c399d0856643aff3683d8e0f103a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-11T18:50:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T16:34:58.000Z", "max_forks_repo_path": "src/CompactBasisFunctions.jl", "max_forks_repo_name": "JuliaGNI/CompactBasisFunctions.jl", "max_forks_repo_head_hexsha": "5a76714aca25c399d0856643aff3683d8e0f103a", "max_forks_repo_licenses": ["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.5161290323, "max_line_length": 69, "alphanum_fraction": 0.6762688615, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.756016683578924}}
{"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   \u03a6 = shape_funcs(r, \u03be)\n\nReturns shape functions `\u03a6[i,j] = \u03a6_(i-1)(\u03be[j])`.\n\"\"\"\nfunction shape_funcs(r::Int64, \u03be::AbstractVector{T}\n                    ) where { T <: AbstractFloat }\n    J = length(\u03be)\n    \u03a6 = zeros(T, r, J)\n    for j = 1:J\n        \u03a6[1,j] = ( 1 - \u03be[j] ) / 2\n        \u03a6[2,j] = ( 1 + \u03be[j] ) / 2\n    end\n    P = Array{T}(undef, r, J)\n    legendre_polys!(P, \u03be) # P[i,j] = P_(i-1)(\u03be[j])\n    for j = 1:J, i = 3:r\n        a = convert(T, 2(2i-3))\n        \u03a6[i,j] = ( P[i,j] - P[i-2,j] ) / sqrt(a)\n    end\n    return \u03a6\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] \u2265 2\n        global_DoF[p] = Array{Integer}(undef, r[p])\n        total += r[p]\n        if r[p] \u2265 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                               \u03ba::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] =  \u03ba / 2\n    S[2, 1] = S[1, 2] = -\u03ba / 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] = \u03ba\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                            \u03ba::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, \u03ba)\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 \u2264 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                              \u03a6::Matrix{T}, pt::Vector{T}, wt::Vector{T}\n                             ) where { T <: AbstractFloat }\n    r = length(Fp)\n    J = length(pt)\n    @argcheck size(\u03a6,1) \u2264 r  DimensionMismatch\n    @argcheck size(\u03a6,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) * \u03a6[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    \u03a6 = 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, \u03a6, pt, wt)\n        for i = 1:length(gdof[p])\n            gi = gdof[p][i]\n            if gi \u2264 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                         \u03be::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(\u03be)\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 - \u03be[j] ) * x[p-1] + (1 + \u03be[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 - \u03be[j] ) * x[p-1] + (1 + \u03be[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                              \u03be::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(\u03be)\n    \u03a6 = shape_funcs(max_r, \u03be)\n    n = 0\n    if Nx == 1 + P * ( pts_per_interval - 1 ) # \u03be[1] = -1, \u03be[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 \u2264 nfree\n                        Uvals[n] += U[gpi] * \u03a6[i,j]\n                    end\n                end\n            end\n        end\n        n += 1\n        gpi = gdof[P][2]\n        if gpi \u2264 nfree\n            Uvals[n] = U[gpi] \n        end\n    elseif Nx == P * pts_per_interval  # \u03be[1] > -1 or \u03be[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 \u2264 nfree\n                        Uvals[n] += U[gpi] * \u03a6[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    \u03be = collect( range(-one(T), stop=one(T), length=pts_per_interval) )\n    xvals = zeros(T, Nx)\n    spatial_points!(xvals, grid, \u03be)\n    Uvals = zeros(T, Nx)\n    evaluate_fem1d_soln!(Uvals, U, grid, \u03be)\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    \u03c4 = range(-one(T), stop=one(T), length=pts_per_time_interval)\n    \u03be = range(-one(T), stop=one(T), length=pts_per_space_interval)\n    xvals, pcwise_t, pcwise_U = evaluate_pcwise_poly(U, t, grid, \u03c4, \u03be)\n    return xvals, pcwise_t, pcwise_U\nend\n\nfunction evaluate_pcwise_poly(U::Array{T}, t::OffsetVector{T}, \n                              grid::SpatialGrid{T},\n                              \u03c4::AbstractVector{T}, \n                              \u03be::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(\u03be)\n    pts_per_time_interval = length(\u03c4)\n    @argcheck axes(t, 1) == 0:N\n    if \u03be[1] > -1.0 || \u03be[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, \u03be)\n    \u03a8 = Array{Float64}(undef, rt, pts_per_time_interval)\n    legendre_polys!(\u03a8, \u03c4)\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-\u03c4[i])*t[n-1] + (1+\u03c4[i])*t[n] ) / 2\n            for k = 1:rt\n                evaluate_fem1d_soln!(Uvals, U[:,k,n], grid, \u03be)\n                pcwise_U[:,i,n] .+= Uvals * \u03a8[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                              \u03c4::Vector{T}, w::Vector{T}, \n                              \u03a8::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    \u0394t = In[2] - In[1]\n    for i = 1:length(\u03c4)\n        ti = ( ( 1 - \u03c4[i] ) * In[1] + ( 1 + \u03c4[i] ) * In[2] ) / 2\n        assembled_load_vector!(Fni, grid, x -> f(x,ti))\n        for j = 1:rt\n            Fn[:,j] += (\u0394t/2) * w[i] * Fni * \u03a8[j,i]\n        end\n    end\nend\n\nfunction PDEDG(\u03ba::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, \u03ba)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    \u03a8_at_minus1 = Vector{Float64}(undef, rt)\n    legendre_polys!(\u03a8_at_minus1, -1.0)\n    \u03c4, w = GaussQuadrature.legendre(Mt)\n    \u03a8 = Array{Float64}(undef, rt, Mt)\n    legendre_polys!(\u03a8, \u03c4)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, \u03c4, w, \u03a8)\n    b = Fn[1:nfree*rt] + kron(\u03a8_at_minus1, M*U0) \n    \u0394t1 = t[1] - t[0]\n    G_kron_M = kron(G, M)\n    H_kron_S = kron(H, S)\n    A = G_kron_M + \u0394t1 * H_kron_S\n    U[:,1] = A \\ b\n    K_kron_M = kron(K, M)\n    for n = 2:N\n        \u0394tn = t[n] - t[n-1]\n        dynamic_load_vector!(Fn, t[n-1:n], grid, f, \u03c4, w, \u03a8)\n        b = Fn[1:nfree*rt] + K_kron_M * U[:,n-1]\n        A = G_kron_M + \u0394tn * H_kron_S\n        U[:,n] = A \\ b\n    end\n    return reshape(U, nfree, rt, N)\nend\n\n\"\"\"\n    t, U = PDEDG(\u03ba, f, U0, grid, N, rt, num_Gauss_pts)\n\nFaster version for uniform time steps.\n\"\"\"\nfunction PDEDG(\u03ba::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, \u03ba)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    \u03a8_at_minus1 = Vector{Float64}(undef, rt)\n    legendre_polys!(\u03a8_at_minus1, -1.0)\n    \u03c4, w = GaussQuadrature.legendre(Mt)\n    \u03a8 = Array{Float64}(undef, rt, Mt)\n    legendre_polys!(\u03a8, \u03c4)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, \u03c4, w, \u03a8)\n    b = Fn[1:nfree*rt] + kron(\u03a8_at_minus1, M*U0) \n    \u0394t = max_t / N\n    G_kron_M = kron(G, M)\n    H_kron_S = kron(H, S)\n    A = G_kron_M + \u0394t * 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, \u03c4, w, \u03a8)\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_\u03c4 = maxerr(\u03c4, U, t, u, \u03be, grid, cutoff=0.0)\n\nReturns err_\u03c4[i] = max |U(x,t)-u(x,t)| over x values in each spatial\ninterval corresponding to \u03be the values in [-1,1], and over the t value \nin each time subinterval corresponding to \u03c4[i] in [-1,1], except for time \nintervals with t[n] \u2264 cutoff.\n\"\"\"\nfunction maxerr(\u03c4:: AbstractVector{Float64}, U::Array{Float64}, \n                t::OffsetVector{Float64}, u::Function,\n                \u03be::AbstractVector{Float64}, grid::SpatialGrid, \n                cutoff=0.0)\n    xvals, pcwise_t, pcwise_U = evaluate_pcwise_poly(U, t, grid, \u03c4, \u03be)\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_\u03c4 = zeros(pts_per_time_interval)\n    for n = 1:N\n        if t[n] \u2264 cutoff\n            continue\n        end\n        for i = 1:pts_per_time_interval\n            for p = 1:Nx\n                err_\u03c4[i] = max(abs(pcwise_err[p,i,n]), err_\u03c4[i])\n            end\n        end\n    end\n    return err_\u03c4\nend\n\n\"\"\"\n    U = FPDEDG(\u03ba, f, U0, grid, t, rt, num_t_Gauss_pts)\n\nDG solver for fractional PDE.\n\"\"\"\nfunction FPDEDG(\u03ba::Float64, f::Function, U0::Vector{Float64}, \n               grid::SpatialGrid{Float64}, t::OffsetVector{Float64},\n               rt::Int64, Mt::Int64, store::Store{Float64})\n    \u03b1 = store.\u03b1\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    \u03c4, w\u03c4 = rule(store.legendre[Mt])\n    \u03a8 = view(store.\u03a8, 1:rt, 1:Mt)\n    legendre_polys!(\u03a8, \u03c4)\n\n    U = zeros(nfree*rt, Nt)\n    Fn = zeros(nfree, rt)\n    M, S = assembled_matrices(grid, \u03ba)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    \u03a8_at_minus1 = Array{Float64}(undef, rt)\n    legendre_polys!(\u03a8_at_minus1, -1.0)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, \u03c4, w\u03c4, \u03a8)\n    b = Fn[1:nfree*rt] + kron(\u03a8_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, \u03c4, w\u03c4, \u03a8)\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(\u03ba, f, U0, grid, max_t, N, rt, num_t_Gauss_pts)\n\nSpecialised version for uniform time steps.\n\"\"\"\nfunction FPDEDG(\u03ba::Float64, f::Function, U0::Vector{Float64}, \n                grid::SpatialGrid{Float64}, max_t::Float64, \n                N::Int64, rt::Int64, Mt::Int64, store::Store{Float64})\n    \u03b1 = store.\u03b1\n    x, gdof = grid.x, grid.global_DoF\n    nfree, nfixed = grid.nfree, grid.nfixed\n\n    \u0394t = 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, \u03ba)\n    M = M[1:nfree,1:nfree]\n    S = S[1:nfree,1:nfree]\n    \u03a8_at_minus1 = Vector{Float64}(undef, rt)\n    legendre_polys!(\u03a8_at_minus1, -1.0)\n    \u03c4, w = GaussQuadrature.legendre(Mt)\n    \u03a8 = Array{Float64}(undef, rt, Mt)\n    legendre_polys!(\u03a8, \u03c4)\n    dynamic_load_vector!(Fn, t[0:1], grid, f, \u03c4, w, \u03a8)\n    b = Fn[1:nfree*rt] + kron(\u03a8_at_minus1, M*U0) \n    G_kron_M = kron(G, M)\n    Hnn_kron_S = kron(H[0], S)\n    A = G_kron_M + \u0394t^\u03b1 * 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 .+ \u0394t^\u03b1 * Hnl_kron_S * U[:,l]\n        end\n        dynamic_load_vector!(Fn, t[n-1:n], grid, f, \u03c4, w, \u03a8)\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                    \u03be::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(\u03be)\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 \u03b1, \u03b2 = rm_compute(w,lb,ub;Nquad=200,Npoly=N)\n# analytical solution\n\u03b1_ana = zeros(N)\n\u03b2_ana = [ \u221a\u03c0; [0.5*k for k=1:N-1] ]\n# compare\ndisplay(\"Deviation for \u03b1: $(\u03b1-\u03b1_ana)\")\ndisplay(\"Deviation for \u03b2: $(\u03b2-\u03b2_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 \u03b1, \u03b2 = rm_compute(v,lb,ub;Nquad=2000,Npoly=N)\n# analytical solution\n\u03b1_ana = [-0.5; zeros(N-1) ]\n\u03b2_ana = [ \u03c0; [0.25 for k=1:N-1] ]\n# compare\ndisplay(\"Deviation for \u03b1: $(\u03b1-\u03b1_ana)\")\ndisplay(\"Deviation for \u03b2: $(\u03b2-\u03b2_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\u2081 = reshape(nn_params[1:6], 3, 2);   \n    b\u2081 = reshape(nn_params[7:9], 3)\n    \n    W\u2082 = reshape(nn_params[10:15], 2, 3); \n    b\u2082 = reshape(nn_params[16:17], 2)\n    \n    W\u2092 = reshape(nn_params[18:19], 1, 2); \n    b\u2092 = reshape(nn_params[20:20], 1)   \n    return W\u2081, b\u2081, W\u2082, b\u2082, W\u2092, b\u2092\nend\n\n# Construct a neural network using Flux and return a predicted value.\nfunction nn_forward(xs, nn_params::AbstractVector)\n    W\u2081, b\u2081, W\u2082, b\u2082, W\u2092, b\u2092 = unpack(nn_params)\n    nn = Chain(Dense(W\u2081, b\u2081, tanh),\n               Dense(W\u2082, b\u2082, tanh),\n               Dense(W\u2092, b\u2092, \u03c3))\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\u03bc = randn(length(q))\n\u03c9 = -1 .* ones(length(q))\n\nq = AdvancedVI.update(q, \u03bc, exp.(\u03c9));\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, :\u03c3)]\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(\u03b8::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(\u03b8[index:last_index_w], rows, cols))\n        push!(biases, reshape(\u03b8[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, \u03b8::AbstractVector, network_shape::AbstractVector)\n    weights, biases = unpack(\u03b8, 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    \u03b8 ~ MvNormal(zeros(num_params), sig .* ones(num_params))\n    preds = nn_forward(xs, \u03b8, 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 \u03b8 parameters from the sampled chain.\nparams2 = MCMCChains.group(ch2, :\u03b8).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": "\n# --------------------------------------------------------------------------\n# ACE.jl and SHIPs.jl: Julia implementation of the Atomic Cluster Expansion\n# Copyright (c) 2019 Christoph Ortner <christophortner0@gmail.com>\n# Licensed under ASL - see ASL.md for terms and conditions.\n# --------------------------------------------------------------------------\n\n\n@testset \"Clebsch-Gordan\" begin\n\n@info(\"Testset Clebsch-Gordan\")\n\n#---\n\nusing PyCall, Test, ACE, ACE.SphericalHarmonics, JuLIP.Testing, StaticArrays\nusing JuLIP: evaluate\nusing ACE.SphericalHarmonics: index_y\nusing ACE.RPI.Rotations3D: ClebschGordan\n\n#---\n\n\ntry\n\tsympy = pyimport(\"sympy\")\n\tspin = pyimport(\"sympy.physics.quantum.spin\")\n\n\n\tpycg(j1, m1, j2, m2, j3, m3, T=Float64) =\n      \t\tspin.CG(j1, m1, j2, m2, j3, m3).doit().evalf().__float__()\n\n\tcg = ClebschGordan()\n\n\n\t@info(\"compare implementation against `sympy`\")\n\tlet ntest = 0\n   \t\twhile ntest < 200\n      \t\t\tj1 = rand(0:10)\n      \t\t\tj2 = rand(0:10)\n      \t\t\tJ = rand(abs(j1-j2):min(10,(j1+j2)))\n      \t\t\tm1 = rand(-j1:j1)\n      \t\t\tfor m2 = -j2:j2\n         \t\t\tM = m1+m2\n         \t\t\tif abs(M) <= J\n            \t\t\t\tntest += 1\n            \t\t\t\tprint_tf(@test cg(j1,m1, j2,m2, J,M) \u2248 pycg(j1,m1, j2,m2, J,M))\n            \t\t\t\t# print_tf(@test clebschgordan(j1,m1, j2,m2, J,M) \u2248 )\n         \t\t\tend\n      \t\t\tend\n   \t\tend\n\tend\n\tprintln()\n\n\t##\n\n\t@info(\"Checking the SphH expansion in terms of CG coeffs\")\n\t# expansion coefficients of a product of two spherical harmonics in terms a\n\t# single spherical harmonic\n\t# see e.g. https://en.wikipedia.org/wiki/Clebsch\u2013Gordan_coefficients\n\t# this is the magic formula that we need, on which everything else is based\n\tfor ntest = 1:200\n   \t\t# two random Ylm  ...\n   \t\tl1, l2 = rand(1:10), rand(1:10)\n   \t\tm1, m2 = rand(-l1:l1), rand(-l2:l2)\n   \t\t# ... evaluated at random spherical coordinates\n   \t\t\u03b8 = rand() * \u03c0\n   \t\t\u03c6 = (rand()-0.5) * 2*\u03c0\n   \t\tR = SVector( cos(\u03c6)*sin(\u03b8), sin(\u03c6)*sin(\u03b8), cos(\u03b8) )\n   \t\t# evaluate all relevant Ylms (up to l1 + l2)\n   \t\tYlm = evaluate(SHBasis(l1+l2), R)\n   \t\t# evaluate the product p = Y_l1_m1 * Y_l2_m2\n   \t\tp = Ylm[index_y(l1,  m1)] * Ylm[index_y(l2,m2)]\n   \t\t# and its expansion in terms of CG coeffs\n   \t\tp2 = 0.0\n   \t\tM = m1 + m2  # all other coeffs are zero\n\n   \t\tfor L = abs(M):(l1+l2)\n      \t\t\tp2 += sqrt( (2*l1+1)*(2*l2+1) / (4 * \u03c0 * (2*L+1)) ) *\n            \t\tcg(l1,  0, l2,  0, L, 0) *\n            \t\tcg(l1, m1, l2, m2, L, M) *\n            \t\tYlm[index_y(L, M)]\n   \t\tend\n   \t\tprint_tf((@test (p \u2248 p2) || (abs(p-p2) < 1e-15)))\n\tend\n\tprintln()\n\n\ncatch e   # try importing some python packages\n\t@warn \"sympy didn't import, No Clebsch-Gordan tests are running\"\nend\n\n#---\n\nend # @testset\n", "meta": {"hexsha": "da33ca06e0d1486edeab6caba868742baa00947d", "size": 2676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rpi/test_cg.jl", "max_stars_repo_name": "casv2/ACE.jl", "max_stars_repo_head_hexsha": "121a2a835198c4ed368648b65affe37fd6b7c320", "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/rpi/test_cg.jl", "max_issues_repo_name": "casv2/ACE.jl", "max_issues_repo_head_hexsha": "121a2a835198c4ed368648b65affe37fd6b7c320", "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/rpi/test_cg.jl", "max_forks_repo_name": "casv2/ACE.jl", "max_forks_repo_head_hexsha": "121a2a835198c4ed368648b65affe37fd6b7c320", "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": 28.4680851064, "max_line_length": 79, "alphanum_fraction": 0.553064275, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7560166752529108}}
{"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 \u2014 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\u00b2 = (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\u00b2 >= 1 && continue\n        count += 1\n        numerator += xi^2 * (1 - ui\u00b2)^4\n        denominator += (1 - ui\u00b2) * (1 - 5 * ui\u00b2)\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\u00b2 = (xi / (ce.c * MADx))^2\n        vi\u00b2 = (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\u00b2) * (1 - 5 * ui\u00b2)\n        ay = (1 - vi\u00b2) * (1 - 5 * vi\u00b2)\n        anum = xi * (1 - ui\u00b2)^2 * yi * (1 - vi\u00b2)^2\n\n        denominator_x += ifelse(ui\u00b2 < 1, ax, zero(denominator_x))\n        denominator_y += ifelse(vi\u00b2 < 1, ay, zero(denominator_y))\n        i_count, i_numerator = ifelse(ui\u00b2 < 1 && vi\u00b2 < 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 \u2208 (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\u00b2 = @. (Xc / (ce.c * MAD))^2\n\n    onesubu\u00b2 = max.((1 .- u\u00b2), 0)\n    a = @. Xc * onesubu\u00b2^2\n    numerator = a' * a\n\n    a[:, :] .= @. onesubu\u00b2 * (1 - 5 * u\u00b2)  # 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\u00b2 .> 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": "remap(x, from, to) = (x - from[1]) * (to[2] - to[1]) / (from[2] - from[1]) + to[1]", "meta": {"hexsha": "b13158a6e1e47488f0d64bb503f102ebd4ade92b", "size": 82, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "serenity4/ProceduralNoise.jl", "max_stars_repo_head_hexsha": "4b2959d97f73d956a77ca162d4d4db8149f294de", "max_stars_repo_licenses": ["MIT"], "max_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": "serenity4/ProceduralNoise.jl", "max_issues_repo_head_hexsha": "4b2959d97f73d956a77ca162d4d4db8149f294de", "max_issues_repo_licenses": ["MIT"], "max_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": "serenity4/ProceduralNoise.jl", "max_forks_repo_head_hexsha": "4b2959d97f73d956a77ca162d4d4db8149f294de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.0, "max_line_length": 82, "alphanum_fraction": 0.4512195122, "num_tokens": 43, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768604361742, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7559948652058022}}
{"text": "module TestShapeDiagrams\nusing Test\n\nusing Catlab.Theories, Catlab.CategoricalAlgebra.ShapeDiagrams\n\nA, B, C = Ob(FreeCategory, :A, :B, :C)\n\n# Spans.\nf, g = Hom(:f, C, A), Hom(:g, C, B)\nspan = Span(f,g)\n@test apex(span) == C\n@test left(span) == f\n@test right(span) == g\nf = Hom(:f, A, B)\n@test_throws Exception Span(f,g)\n\n# Cones.\nf, g = Hom(:f, C, A), Hom(:g, C, B)\ncone = Cone(C,[f,g])\n@test apex(cone) == C\n@test leg(cone,1) == f\n@test leg(cone,2) == g\nf = Hom(:f, A, B)\n@test_throws Exception Cone(C,[f,g])\n\n# Cospans.\nf, g = Hom(:f, A, C), Hom(:g, B, C)\ncospan = Cospan(f,g)\n@test base(cospan) == C\n@test left(cospan) == f\n@test right(cospan) == g\n\n# Cocones.\nf, g = Hom(:f, A, C), Hom(:g, B, C)\ncocone = Cocone(C,[f,g])\n@test base(cocone) == C\n@test leg(cocone,1) == f\n@test leg(cocone,2) == g\nf = Hom(:f, A, B)\n@test_throws Exception Cocone(C,[f,g])\n\n# Diagrams.\n\nf, g, h = Hom(:f, A, C), Hom(:g, B, C), Hom(:h, A, B)\ndiag = Diagram([A,B,C],[(1,3,f),(2,3,g),(1,2,h)])\n@test_throws Exception Diagram([A,B,C],[(1,2,f),(2,3,g),(1,2,h)])\n\nend\n", "meta": {"hexsha": "72a170f64b9478036872a736d0f90965500f411d", "size": 1046, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/categorical_algebra/ShapeDiagrams.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": "test/categorical_algebra/ShapeDiagrams.jl", "max_issues_repo_name": "philzook58/Catlab.jl", "max_issues_repo_head_hexsha": "bb96fa51914239ef4a1548c172d87b849c4064c1", "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": "test/categorical_algebra/ShapeDiagrams.jl", "max_forks_repo_name": "philzook58/Catlab.jl", "max_forks_repo_head_hexsha": "bb96fa51914239ef4a1548c172d87b849c4064c1", "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.3469387755, "max_line_length": 65, "alphanum_fraction": 0.5783938815, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653855, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7559948572123502}}
{"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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, StatsPlots, LaTeXStrings\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.9\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.9\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550a715f0ac-2034-11eb-029c-9be9db193aed\n# \u255f\u250070182cd8-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    \u03d50 = 49 * (\u03c0/180)\n    \u03bb0 = -2 * (\u03c0/180)\n\n\n    \u03d51 = (N - N0)/a*F0 + \u03d50\n    n=(a-b)/(a+b)\n    M_function(\u03d5) = b*F0*( (1 + n + 5/4*n^2 + 5/4*n^3) * (\u03d5-\u03d50)\n        - (3*n + 3*n^2 + 21/8*n^3) * sin(\u03d5-\u03d50) * cos(\u03d5+\u03d50)\n        + (15/8*n^2 + 15/8*n^3) * sin(2*(\u03d5-\u03d50)) * cos(2*(\u03d5+\u03d50))\n        - 35/24*n^3 * sin(3*(\u03d5-\u03d50))*cos(3*(\u03d5+\u03d50)))\n    residual(M) = (N-N0-M)\n    M = M_function(\u03d51)\n\n\n    while residual(M) > 0.00000001\n        \u03d51 = (residual(M)/a*F0) + \u03d51\n        M = M_function(\u03d51)\n    end\n\n    \u03d51 / (\u03c0/180)\n\n    \u03bd = a * F0 * abs(1-e2*sin(\u03d51)^2)^(-0.5) # \\nu\n    \u03c1 = a * F0 * (1-e2) * (1-e2*sin(\u03d51)^2)^(-1.5)\n    \u03b72 = \u03bd/\u03c1-1\n\n    VII = tan(\u03d51)/(2*\u03c1*\u03bd)\n    VIII = tan(\u03d51)/(24*\u03c1*\u03bd^3) * (5 + 3*tan(\u03d51)^2 + \u03b72 - 9*(tan(\u03d51)^2)*\u03b72)\n    IX = tan(\u03d51)/(720*\u03c1*\u03bd^5) * (61 + 90*tan(\u03d51)^2 + 45*(tan(\u03d51)^4))\n    X = sec(\u03d51)/\u03bd\n    XI = sec(\u03d51)/(6*\u03bd^3) * (\u03bd/\u03c1 + 2*tan(\u03d51)^2)\n    XII = sec(\u03d51)/(120*\u03bd^5) * (5 + 28*tan(\u03d51)^2 + 24*tan(\u03d51)^4)\n    XIIA = sec(\u03d51)/(5040*\u03bd^7) * (61 + 662*tan(\u03d51)^2 + 1320*tan(\u03d51)^4 + 720*tan(\u03d51)^6)\n\n    \u03d5 = \u03d51 - VII*(E-E0)^2 + VIII*(E-E0)^4 - IX*(E-E0)^6\n    \u03bb = \u03bb0 + X*(E-E0) - XI*(E-E0)^3 + XII*(E-E0)^5 - XIIA*(E-E0)^7\n\n    return \u03d5/(\u03c0/180), \u03bb/(\u03c0/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": "using NonLinearReactionAdvectionDiffusionWithFrontData;\n\n@testset \"\u0414\u0435\u043b\u044c\u0442\u0430-\u0444\u0443\u043d\u043a\u0446\u0438\u044f                                   \" begin\n    N = 20;\n    X = [i/N for i in 0:N];\n\n    d = [ delta(x, X, 0.5) for x in X ]\n\n    @testset \"\u0444\u043e\u0440\u043c\u0443\u043b\u0430 \u043f\u0440\u044f\u043c\u043e\u0443\u0433\u043e\u043b\u044c\u043d\u0438\u043a\u043e\u0432\" begin\n        I = 0.0;\n        for n in 1:N\n            \u03b4x = X[n+1] - X[n]\n            I += d[n] * \u03b4x\n        end\n        @test isapprox(I, 1.0)\n    end\n\n    @testset \"\u0444\u043e\u0440\u043c\u0443\u043b\u0430 \u0442\u0440\u0430\u043f\u0435\u0446\u0438\u0439\" begin\n        I = 0.0;\n        for n in 1:N\n            \u03b4x = X[n+1] - X[n]\n            I += ((d[n] + d[n+1]) / 2.0) * \u03b4x\n        end\n        @test isapprox(I, 1.0)\n    end\n\n    # \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u0442\u043e\u043b\u044c\u043a\u043e \u043e\u0434\u0438\u043d \u043d\u0435\u043d\u0443\u043b\u0435\u0432\u043e\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\n    @test length( filter( x -> x != 0, d) ) == 1\n\n    @testset \"\u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0434\u0435\u043b\u044c\u0442\u0430-\u0444\u0443\u043d\u043a\u0446\u0438\u0438\" begin\n        @test_throws DomainError delta(-2, X, 0.5)\n        @test_throws DomainError delta(2, X, 0.5)\n        @test_throws DomainError delta(0.5, X, -2)\n        @test_throws DomainError delta(0.5, X, 2)\n        @test_throws DomainError delta(0.5, X, 1.0)\n    end\n\nend\n", "meta": {"hexsha": "339210feb6668b6bf63eb12da3d774271e9d68f8", "size": 1033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/delta_check.jl", "max_stars_repo_name": "aborzunov/NonLinearReactionAdvectionDiffusionWithFrontData.jl", "max_stars_repo_head_hexsha": "006aff15ac0dcbd7aaea3d9a23d3c1ff6bd48613", "max_stars_repo_licenses": ["MIT"], "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/delta_check.jl", "max_issues_repo_name": "aborzunov/NonLinearReactionAdvectionDiffusionWithFrontData.jl", "max_issues_repo_head_hexsha": "006aff15ac0dcbd7aaea3d9a23d3c1ff6bd48613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-01-23T12:01:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-11T12:51:34.000Z", "max_forks_repo_path": "test/delta_check.jl", "max_forks_repo_name": "aborzunov/NonLinearReactionAdvectionDiffusionWithFrontData.jl", "max_forks_repo_head_hexsha": "006aff15ac0dcbd7aaea3d9a23d3c1ff6bd48613", "max_forks_repo_licenses": ["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": 66, "alphanum_fraction": 0.5159728945, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.7558775732276071}}
{"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)) \u00f7 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)) \u00f7 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": "using ModelingToolkit, MethodOfLines, LinearAlgebra, OrdinaryDiffEq\nusing DomainSets\n\n@test_broken begin #@testset \"Inviscid Burgers equation, 1D, u(0, x) ~ x\" begin\n    @parameters x t\n    @variables u(..)\n    Dx = Differential(x)\n    Dt = Differential(t)\n    x_min = 0.0\n    x_max = 1.0\n    t_min = 0.0\n    t_max = 1.0\n\n    analytic_u(t, x) = x / (t + 1)\n\n    eq = Dt(u(t, x)) + u(t, x) * Dx(u(t, x)) ~ 0\n\n    bcs = [u(0, x) ~ x,\n        u(t, x_min) ~ analytic_u(t, x_min),\n        u(t, x_max) ~ analytic_u(t, x_max)]\n\n    domains = [t \u2208 Interval(t_min, t_max),\n        x \u2208 Interval(x_min, x_max)]\n\n    dx = 0.05\n\n    @named pdesys = PDESystem(eq, bcs, domains, [t, x], [u(t, x)])\n\n    disc = MOLFiniteDifference([x => dx], t, upwind_order=1)\n\n    prob = discretize(pdesys, disc)\n\n    sol = solve(prob, Tsit5())\n\n    grid = get_discrete(pdesys, disc)\n    x_disc = grid[x]\n    solu = [map(d -> sol[d][i], grid[u(t, x)]) for i in 1:length(sol[t])]\n\n    for (i, t) in enumerate(sol.t[5:end])\n        u_analytic = analytic_u.([t], x_disc)\n        u_disc = solu[i+4]\n        @test_broken all(isapprox.(u_analytic, u_disc, atol=1e-3))\n    end\nend\n\n@test_broken begin #@testset \"Inviscid Burgers equation, 1D, u(0, x) ~ x, Non-Uniform\" begin\n    @parameters x t\n    @variables u(..)\n    Dx = Differential(x)\n    Dt = Differential(t)\n    x_min = 0.0\n    x_max = 1.0\n    t_min = 0.0\n    t_max = 1.0\n\n    analytic_u(t, x) = x / (t + 1)\n\n    eq = Dt(u(t, x)) + u(t, x) * Dx(u(t, x)) ~ 0\n\n    bcs = [u(0, x) ~ x,\n        u(t, x_min) ~ analytic_u(t, x_min),\n        u(t, x_max) ~ analytic_u(t, x_max)]\n\n    domains = [t \u2208 Interval(t_min, t_max),\n        x \u2208 Interval(x_min, x_max)]\n\n    @named pdesys = PDESystem(eq, bcs, domains, [t, x], [u(t, x)])\n\n    dx = 0:0.05:1\n    dx = collect(dx)\n    dx[2:end-1] .= dx[2:end-1] .+ rand([0.001, -0.001], length(dx[2:end-1]))\n\n    disc = MOLFiniteDifference([x => dx], t, upwind_order=1)\n\n    prob = discretize(pdesys, disc)\n\n    sol = solve(prob, Tsit5())\n\n    grid = get_discrete(pdesys, disc)\n    x_disc = grid[x]\n    solu = [map(d -> sol[d][i], grid[u(t, x)]) for i in 1:length(sol[t])]\n\n    for (i, t) in enumerate(sol.t[5:end])\n        u_analytic = analytic_u.([t], x_disc)\n        u_disc = solu[i+4]\n        @test_broken all(isapprox.(u_analytic, u_disc, atol=1e-3))\n    end\nend\n\n# # Exact solutions from: https://www.sciencedirect.com/science/article/pii/S0898122110003883\n# @test_broken begin# @testset \"Test 01: Burger's 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#        R = 80.0\n\n#        x_min = y_min = t_min = 0.0\n#        x_max = y_max = 1.0\n#        t_max = 0.05\n\n#        u_exact(x,y,t) = 3/4 - 1/(4*(1+exp(R*(-t-4x+4y)/32)))\n#        v_exact(x,y,t) = 3/4 + 1/(4*(1+exp(R*(-t-4x+4y)/32)))\n\n#        eq = [Dt(u(x,y,t)) + u(x,y,t)*Dx(u(x,y,t)) + v(x,y,t)*Dy(u(x,y,t)) ~ 1/R *(Dxx(u(x,y,t)) + Dyy(u(x,y,t))),\n#              Dt(v(x,y,t)) + u(x,y,t)*Dx(v(x,y,t)) + v(x,y,t)*Dy(v(x,y,t)) ~ 1/R *(Dxx(v(x,y,t)) + Dyy(v(x,y,t)))]\n\n#        domains = [x \u2208 Interval(x_min, x_max),\n#                   y \u2208 Interval(y_min, y_max),\n#                   t \u2208 Interval(t_min, t_max)]\n\n#        bcs = [u(x,y,0) ~ u_exact(x,y,0),\n#               u(0,y,t) ~ u_exact(0,y,t),\n#               u(x,0,t) ~ u_exact(x,0,t),\n#               u(1,y,t) ~ u_exact(1,y,t),\n#               u(x,1,t) ~ u_exact(x,1,t),\n\n#               v(x,y,0) ~ v_exact(x,y,0),\n#               v(0,y,t) ~ v_exact(0,y,t),\n#               v(x,0,t) ~ v_exact(x,0,t),\n#               v(1,y,t) ~ v_exact(1,y,t),\n#               v(x,1,t) ~ v_exact(x,1,t)]\n\n#        @named pdesys = PDESystem(eq,bcs,domains,[t,x,y],[u(x,y,t),v(x,y,t)])\n\n#        # Method of lines discretization\n#        dx = 0.05\n#        dy = 0.05\n\n\n#        order = 4\n\n#        discretization = MOLFiniteDifference([x=>dx, y=>dy], t, approx_order=order)\n\n#        # Convert the PDE problem into an ODE problem\n#        prob = discretize(pdesys,discretization)\n\n#        sol = solve(prob,Tsit5())\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\u2032 = reshape([sol[u[(i-1)*Ny+j]][k] for i in 1:Nx for j in 1:Ny],(Nx,Ny))\n#        #        solv\u2032 = reshape([sol[v[(i-1)*Ny+j]][k] for i in 1:Nx for j in 1:Ny],(Nx,Ny))\n#        #        heatmap(solu\u2032)\n#        # end\n#        # gif(anim, \"plots/Burgers2Dsol.gif\", fps = 5)\n\n\n#        solu\u2032 = reshape([sol[u[(i-1)*Ny+j]][end] for i in 1:Nx for j in 1:Ny],(Nx,Ny))\n#        solv\u2032 = reshape([sol[v[(i-1)*Ny+j]][end] for i in 1:Nx for j in 1:Ny],(Nx,Ny))\n\n#        r_space_x = x_min:dx:x_max\n#        r_space_y = y_min:dy:y_max\n\n#        asfu = reshape([u_exact(t_max,r_space_x[i],r_space_y[j]) for j in 1:Ny for i in 1:Nx],(Nx,Ny))\n#        asfv = reshape([v_exact(t_max,r_space_x[i],r_space_y[j]) for j in 1:Ny for i in 1:Nx],(Nx,Ny))\n\n#        asfu[1,1] = asfu[1, end] = asfu[end, 1] = asfu[end, end] = 0.\n#        asfv[1,1] = asfv[1, end] = asfv[end, 1] = asfv[end, end] = 0.\n\n#        # anim = @animate for T in t\n#        #        asfu = reshape([u_exact(T,r_space_x[i],r_space_y[j]) for j in 1:Ny for i in 1:Nx],(Nx,Ny))\n#        #        asfv = reshape([v_exact(T,r_space_x[i],r_space_y[j]) for j in 1:Ny for i in 1:Nx],(Nx,Ny))\n\n#        #        heatmap(asfu)\n#        # end\n#        # gif(anim, \"plots/Burgers2Dexact.gif\", fps = 5)\n\n\n#        mu = max(asfu...)\n#        mv = max(asfv...)\n#        @test_broken asfu / mu \u2248 solu\u2032 / mu  atol=0.2\n#        @test_broken asfv / mv \u2248 solv\u2032 / mv  atol=0.2\n# end\n", "meta": {"hexsha": "9c0af38a7cc8a2ae0660343d4dc978e33a5697fb", "size": 5830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pde_systems/burgers_eq.jl", "max_stars_repo_name": "xtalax/MethodOfLines.jl", "max_stars_repo_head_hexsha": "855edcd693b05feec2de6a6fff2f1c9f8364da50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-23T18:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T18:07:50.000Z", "max_issues_repo_path": "test/pde_systems/burgers_eq.jl", "max_issues_repo_name": "xtalax/MethodOfLines.jl", "max_issues_repo_head_hexsha": "855edcd693b05feec2de6a6fff2f1c9f8364da50", "max_issues_repo_licenses": ["MIT"], "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/pde_systems/burgers_eq.jl", "max_forks_repo_name": "xtalax/MethodOfLines.jl", "max_forks_repo_head_hexsha": "855edcd693b05feec2de6a6fff2f1c9f8364da50", "max_forks_repo_licenses": ["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.6847826087, "max_line_length": 115, "alphanum_fraction": 0.5104631218, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7558775678215436}}
{"text": "export AbstractNLS # TODO: do not export\nexport parameter_size, residue_size\nexport eval_r, eval_r_J\nexport eval_nls_fobj, eval_nls_\u2207fobj, eval_nls_\u2207\u2207fobj\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_\u03b8}\\mapsto \\mathbf{r}(\\mathbf{\\theta})\\in\\mathbb{R}^{n_S}\n``` \nwhere:\n- ``\\mathbf{r}(\\mathbf{\u03b8})\u2208\\mathbb{R}^{n_S}`` is the residue vector,\n- ``\\mathbf{\u03b8}\u2208\\mathbb{R}^{n_\u03b8}`` is the parameter vector to be optimized\n\nThe objective function to minimize is:\n\n```math\nf(\u03b8)=\\frac{1}{2}\\| \\mathbf{r}(\u03b8) \\|^2\n``` \n\nThe classical approach uses a linear approximation of ``\\mathbf{r}``:\n```math\n\\mathbf{r}(\\mathbf{\u03b8}+\u03b4\\mathbf{\u03b8})\\approx \\mathbf{r}(\\mathbf{\u03b8}) + \\mathbf{J}(\\mathbf{\u03b8})\\cdot \u03b4\\mathbf{\u03b8}\n``` \nwhere ``\\mathbf{J}`` is the Jacobian:\n```math\n\\mathbf{J}_{i,j}=\\partial_j r^i(\\mathbf{\u03b8}),\\ i\\in[1,n_S],\\ j\\in[1,n_\u03b8]\n```\nThis leads to\n```math\nf(\\mathbf{\u03b8}+\u03b4\\mathbf{\u03b8})\\approx f(\\mathbf{\u03b8}) + \\langle \\nabla f, \u03b4\\mathbf{\u03b8} \\rangle + \\frac{1}{2}  \\langle \\nabla^2 f \\cdot \u03b4\\mathbf{\u03b8},  \u03b4\\mathbf{\u03b8} \\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_\u03b8``\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_\u03b8`` of the parameter vector ``\u03b8``.\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        \u03b8::AbstractVector) -> r\n```\n\nCompte the residual vector ``\\mathbf{r}``\n\"\"\"\neval_r(nls::AbstractNLS,\n       \u03b8::AbstractVector) = @assert(false,\"To implement\")\n\n@doc raw\"\"\" \n```julia\neval_r_J(nls::AbstractNLS,\u03b8::AbstractVector) -> (r,J)\n```\n\nCompute the residual the vector ``\\mathbf{r}`` and its Jacobian ``\\mathbf{J}`` \n\"\"\"\neval_r_J(nls::AbstractNLS,\n         \u03b8::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(\u03b8)\n```\n\nCompute ``f(\u03b8)=\\frac{1}{2}\\| \\mathbf{r}(\\mathbf{\u03b8}) \\|^2``\n\"\"\"\neval_nls_fobj(r::AbstractVector) = dot(r,r)/2\n\n@doc raw\"\"\"\n```julia\neval_nls_\u2207fobj(r,J) -> \u2207fobj\n```\n\nCompute the gradient: ``\\nabla f(\\mathbf{\u03b8}) = \\mathbf{J}^t\\mathbf{r}``\n\"\"\"\nfunction eval_nls_\u2207fobj(r::AbstractVector, J::AbstractMatrix)\n    J'*r\nend\n    \n@doc raw\"\"\"\n```julia\neval_nls_\u2207\u2207fobj(J) -> \u2207\u2207fobj\n```\n\nCompute the (approximate) Hessian: ``\\nabla^2 f(\\mathbf{\u03b8}) = \\mathbf{J}^t\\mathbf{J}``\n\"\"\"\nfunction eval_nls_\u2207\u2207fobj(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 \u00d7 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\u0304 using a linear combination of evaluations at x_i.\"\n\nfunction fdcoeffV(k,x\u0304,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\u0304)^(i-1) / factorial(i-1) # \u2211 a_i * (x_i - x\u0304)^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": "#!/usr/bin/env julia\n\nexport pe15\n\npe15(n::Integer=20)=binomial(2n,n)\n\nif !haskey(ENV,\"PROJECT_EULER_WITHOUT_RESULT\")\n    pe15()|>print\nend\n", "meta": {"hexsha": "291867d4724d6975225f11350c0455f2fed11784", "size": 140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "15. Lattice paths/15.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": "15. Lattice paths/15.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": "15. Lattice paths/15.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.0, "max_line_length": 46, "alphanum_fraction": 0.7142857143, "num_tokens": 50, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505428129515, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7558206427634445}}
{"text": "using Test\n\nusing MarkovChains\n@testset \"solve\" begin\n    @testset \"irreducible1\" begin\n        chain = ContMarkovChain()\n        n0 = add_state!(chain)\n        n1 = add_state!(chain)\n        n2 = add_state!(chain)\n        n3 = add_state!(chain)\n        add_transition!(chain, n0, n1, 1.0)\n        add_transition!(chain, n1, n2, 1.0)\n        add_transition!(chain, n2, n3, 1.0)\n        add_transition!(chain, n3, n2, 3.0)\n        add_transition!(chain, n2, n1, 2.0)\n        add_transition!(chain, n1, n0, 1.0)\n        init_prob = [0.1, 0.9, 0.0, 0.0]\n        ts_sol = solve(chain, init_prob, 0.0)\n        @test ts_sol.prob \u2248 [0.1, 0.9, 0.0, 0.0]\n        @test ts_sol.cumtime \u2248 [0.0, 0.0, 0.0, 0.0]\n\n        ss_sol = solve(chain, init_prob, Inf)\n        @test ss_sol.prob \u2248 [0.375, 0.375, 0.1875, 0.0625]\n        @test ss_sol.cumtime == [Inf, Inf, Inf, Inf]\n    end\n    @testset \"acyclic1\" begin\n    chain = ContMarkovChain()\n    n1 = add_state!(chain)\n    n2 = add_state!(chain)\n    n3 = add_state!(chain)\n    add_transition!(chain, n1, n2, 2.0)\n    add_transition!(chain, n2, n3, 4.0)\n    init_prob = [1.0, 0.0, 0.0]\n    ts_sol = solve(chain, init_prob, 0.0)\n    @test ts_sol.prob \u2248 [1.0, 0.0, 0.0]\n\n    ts_sol = solve(chain, init_prob, 1.0)\n    @test state_prob(ts_sol, 1) < 1.0\n    @test state_prob(ts_sol, 2) > 0.0\n    @test state_prob(ts_sol, 3) > 0.0\n\n    ss_sol = solve(chain, init_prob, Inf)\n    @test state_cumtime(ss_sol, 1) == 0.5\n    @test state_cumtime(ss_sol, 2) == 0.25\n    @test state_cumtime(ss_sol, 3) == Inf\n    @test ss_sol.prob \u2248 [0.0, 0.0, 1.0]\n\n    end\nend\n", "meta": {"hexsha": "3dd032ba0f0644f9def916666b656f169375575c", "size": 1580, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/solve.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MarkovChains.jl-bbc22021-04b3-5587-aeab-b7019f0e8a6b", "max_stars_repo_head_hexsha": "dce38dd98cf72e6bc0a417afb01811bb062ae3ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-07-23T20:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T08:31:16.000Z", "max_issues_repo_path": "test/solve.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MarkovChains.jl-bbc22021-04b3-5587-aeab-b7019f0e8a6b", "max_issues_repo_head_hexsha": "dce38dd98cf72e6bc0a417afb01811bb062ae3ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-07-31T18:09:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T21:27:19.000Z", "max_forks_repo_path": "test/solve.jl", "max_forks_repo_name": "wangnangg/MarkovChains.jl", "max_forks_repo_head_hexsha": "1b1c4b87123016fa9728ac5c2ba3e30262cd8b4a", "max_forks_repo_licenses": ["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": 58, "alphanum_fraction": 0.5784810127, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129515, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7558206390576767}}
{"text": "using LinearAlgebraicRepresentation, ViewerGL, SparseArrays\nLar = LinearAlgebraicRepresentation; GL = ViewerGL\n\nusing Revise, OhMyREPL\n\nwall = Lar.svg2lar(\"../../test/svg/assembly/wall.svg\", flag=false)\nopenings = Lar.svg2lar(\"../../test/svg/assembly/openings.svg\", flag=false)\nrectangle = Lar.svg2lar(\"../../test/svg/assembly/rectangle.svg\", flag=false)\nbox = Lar.svg2lar(\"../../test/svg/assembly/box.svg\", flag=false)\n\nassembly = Lar.Struct([wall , openings, rectangle, box])\nV,EV = Lar.struct2lar(assembly)\nGL.VIEW([ GL.GLFrame2, GL.GLGrid(V,EV, GL.COLORS[1],1) ]);\nW, copEV, copFE, boolmatrix = Lar.bool2d(assembly)\n@show Matrix(boolmatrix)\n\ninnerpoints = Lar.internalpoints2d(W,copEV,copFE[1:end,:])\npoints = convert(Array{Float64,2}, hcat(innerpoints...)')\nGL.VIEW([ GL.GLFrame2, GL.GLGrid(V,EV, GL.COLORS[1],1), GL.GLPoints(points) ]);\n\n\nA = boolmatrix[:,1]\nB = boolmatrix[:,2]\nC = boolmatrix[:,3]\nD = boolmatrix[:,4]\nexpr = ( D .& .!(.&(A, .!B, .!C)) )# A - B - C\nformula = Matrix(copFE)' * Int.(expr) # coord vector of Faces\nV = convert(Lar.Points,W')\nEV = Lar.cop2lar(copEV)\nEVmin = [ev for (k,ev) in enumerate(EV) if abs(formula[k])==1 ]\nV = Lar.normalize(V)\nV = Lar.normalize(V)\nGL.VIEW([ GL.GLFrame2, GL.GLGrid(V,EVmin, GL.COLORS[1],1) ]);\n\nVV = [[k] for k in 1:size(V,2)];\nmodel = (V,[VV, EV])\nGL.VIEW( GL.numbering(.1)( model,GL.COLORS[1],0.1 ) );\n", "meta": {"hexsha": "370a5f3cd6ed19f5f5f053f8e15eaf20a19aa1e4", "size": 1363, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/2d/dwelling.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/2d/dwelling.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/2d/dwelling.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": 35.8684210526, "max_line_length": 79, "alphanum_fraction": 0.6713132795, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7558206372047926}}
{"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, \u03bd, L1 = p\n\treturn -L1 * u .+ (l .* u .+ \u03bd .* u.^2 .- u.^3)\nend\n\nfunction dF_sh(u, p)\n\t@unpack l, \u03bd, L1 = p\n\treturn -L1 .+ spdiagm(0 => l .+ 2 .* \u03bd .* u .- 3 .* u.^2)\nend\n\nd2F_sh(u, p, dx1, dx2) = (2 .* p.\u03bd .* 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\u0394, D2x = Laplacian2D(Nx, Ny, lx, ly, :Neumann)\nL1 = (I + \u0394)^2\npar = (l = -0.1, \u03bd = 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 \u2209 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 \u2208 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) = \u03b2\n# Arguments:\n* `\u03b2::Float64`: Constant\n\"\"\" ->\ntype MeanConst <: Mean\n    \u03b2::Float64\n    MeanConst(\u03b2::Float64) = new(\u03b2)\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.\u03b2, size(x,2))\n\nget_params(mConst::MeanConst) = Float64[mConst.\u03b2]\nget_param_names(::MeanConst) = [:\u03b2]\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.\u03b2 = 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\u00e7\u00e3o de elimina\u00e7\u00e3o retorna U, depois de fazer a decomposi\u00e7\u00e3o LU.\n#Fun\u00e7\u00e3o faz pivotamento.\n\n\n############\n#Observa\u00e7\u00e3o#\n############\n\n# Para usar essa fun\u00e7\u00e3o \u00e9 necessario mandar uma matriz AA que seja do tipo float\n# tentei fazer a convers\u00e3o de tipo porem os resultados saiam como se fossem um n\u00famero 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": "# ------------------------------------------------------------\n# Reconstruction of impulse responses\n\nusing GeneralizedSampling\n\nJ = 3\nM = 2^(J+1)\nwname = \"db2\"\n\nxi = GeneralizedSampling.grid(M, 0.5)\nf = FourScalingFunc(xi, wname, J)\n\nT = Freq2Wave(xi, wname, J)\nwcoef = T \\ f\n\nprintln(\"Reconstructing a \", wname, \" function from its Fourier measurements.\")\nprintln(\"Reconstructed coefficients is a unit vector:\")\ndisplay(wcoef)\n\n\n# ------------------------------------------------------------\n# Plot reconstruction\n\nusing IntervalWavelets\n\nx, yw = weval( real(wcoef), wname, 10 )\n\nusing Plots\n\np = plot(x, yw, label=wname)\ndisplay(p)\n\n", "meta": {"hexsha": "65e05457e2e16e3559de0e6272e84e1e084f37af", "size": 636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/impulse.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/impulse.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/impulse.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": 19.2727272727, "max_line_length": 79, "alphanum_fraction": 0.572327044, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7557829139053799}}
{"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    \u03bca, \u03c3a = params(a)\n    \u03bcb, \u03c3b = params(b)\n    return abs2(\u03bca - \u03bcb) + abs2(\u03c3a - \u03c3b)\nend\n\nfunction (::SqWasserstein)(a::AbstractMvNormal, b::AbstractMvNormal)\n    \u03bc1 = mean(a)\n    \u03bc2 = mean(b)\n    \u03a31 = cov(a)\n    \u03a32 = cov(b)\n    return Distances.sqeuclidean(\u03bc1, \u03bc2) + OT.sqbures(\u03a31, \u03a32)\nend\n\nfunction (::SqWasserstein)(a::MvNormal, b::MvNormal)\n    \u03bca, \u03a3a = params(a)\n    \u03bcb, \u03a3b = params(b)\n    return Distances.sqeuclidean(\u03bca, \u03bcb) + OT.sqbures(\u03a3a, \u03a3b)\nend\n\n# evaluations for Laplace distributions\nfunction (::SqWasserstein)(a::Laplace, b::Laplace)\n    \u03bca, \u03b2a = params(a)\n    \u03bcb, \u03b2b = params(b)\n    return abs2(\u03bca - \u03bcb) + 2 * abs2(\u03b2a - \u03b2b)\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\u03f5 = 0.001\nf(t,y) = cos(t .+ \u03f5*y)\n\nt0 = 0\ntf = 256*\u03c0\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\u03b3 = \u03f5/(1 + sqrt(1 - \u03f5^2))\n\u03b1 = 2*\u03f5/(1 - \u03f5 + sqrt(1 - \u03f5^2))\n\u03b2 = tan(\u03f5*y0/2)/(1 + \u03b1)\n\u03d5(t) = 0.5*(1 - \u03b3*\u03f5)*t\n\u03c3(t) = \u03b1*(sin(\u03d5(t)) + \u03b2*cos(\u03d5(t)))\ny(t) = -\u03b3*t + (2/\u03f5)*atan((\u03b2 + \u03c3(t)*cos(\u03d5(t)))/(1 + \u03c3(t)*sin(\u03d5(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": "module TestMetaInfo_VariableTimestep\n\nusing Test\nusing Mimi\n\nimport Mimi: \n    compdef, reset_compdefs, first_period, last_period\n\nreset_compdefs()\n\n@defcomp ch4forcing1 begin\n    c_N2Oconcentration = Parameter(index=[time],unit=\"ppbv\")\n    c_CH4concentration = Parameter(index=[time],unit=\"ppbv\")\n    f0_CH4baseforcing = Parameter(unit=\"W/m2\")\n    fslope_CH4forcingslope = Parameter(unit=\"W/m2\")\n    c0_baseN2Oconc = Parameter(unit=\"ppbv\")\n    c0_baseCH4conc = Parameter(unit=\"ppbv\")\n    f_CH4forcing = Variable(index=[time],unit=\"W/m2\")\n    over_baseoverlap = Variable(unit=\"W/m2\")\n    over = Variable(index=[time],unit=\"W/m2\")\n\n    function run_timestep(p, v, d, t)\n        #from p.16 in Hope 2009\n        if is_first(t)\n            #calculate baseline forcing overlap in first time period\n            v.over_baseoverlap = -0.47 * log(1 + 2.0e-5 * (p.c0_baseN2Oconc * p.c0_baseCH4conc)^0.75 + 5.3e-15 * p.c0_baseCH4conc * (p.c0_baseCH4conc * p.c0_baseN2Oconc)^1.52)\n        end\n    \n        v.over[t] = -0.47 * log(1 + 2.0e-5 * (p.c_CH4concentration[t] * p.c0_baseN2Oconc)^0.75 + 5.3e-15 * p.c_CH4concentration[t] * (p.c0_baseN2Oconc * p.c_CH4concentration[t])^1.52)\n        v.f_CH4forcing[t] = p.f0_CH4baseforcing + p.fslope_CH4forcingslope * (sqrt(p.c_CH4concentration[t]) - sqrt(p.c0_baseCH4conc)) + v.over[t] - v.over_baseoverlap\n    end\nend\n\n@Mimi.defmodel test_model begin\n    index[time] = [2010:2100; 2105:5:2200]\n    component(ch4forcing1)\n    component(ch4forcing1, ch4forcing2) # add another one with a different name\nend\n\nc1 = compdef(test_model, :ch4forcing1)\nc2 = compdef(test_model, :ch4forcing2)\n\n@test c1 == compdef(:ch4forcing1)\n@test_throws ErrorException compdef(:missingcomp)\n\n@test c2.comp_id.module_name == :TestMetaInfo_VariableTimestep\n@test c2.comp_id.comp_name == :ch4forcing1\n@test c2.name == :ch4forcing2\n\nvars = Mimi.variable_names(c2)\n@test length(vars) == 3\n\npars = Mimi.parameter_names(c2)\n@test length(pars) == 6\n\n@test first_period(test_model.md, c1) == 2010\n@test last_period(test_model.md, c1) == 2200\n\nend # module\n", "meta": {"hexsha": "baebe2954545a92733bde29619f638a6b5eecd17", "size": 2056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_metainfo_variabletimestep.jl", "max_stars_repo_name": "fredrikekre/Mimi.jl", "max_stars_repo_head_hexsha": "1da0535145e7b406df29c2a44a7a3e0ced5dc6be", "max_stars_repo_licenses": ["MIT"], "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_metainfo_variabletimestep.jl", "max_issues_repo_name": "fredrikekre/Mimi.jl", "max_issues_repo_head_hexsha": "1da0535145e7b406df29c2a44a7a3e0ced5dc6be", "max_issues_repo_licenses": ["MIT"], "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_metainfo_variabletimestep.jl", "max_forks_repo_name": "fredrikekre/Mimi.jl", "max_forks_repo_head_hexsha": "1da0535145e7b406df29c2a44a7a3e0ced5dc6be", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 183, "alphanum_fraction": 0.704766537, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7557829037557653}}
{"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": "using MAT\nusing PyPlot\nusing LinearAlgebra\nusing ADCME\nusing AdFem\nusing Distributions\n\nsigma = 0.01\nq = (1e-1)^2\nm = n = 20\nh = 0.1\n\n\nfor sigma in [0.0 0.01]\n\nr = (1e-2)^2 \n\nd = matread(\"simdata/nn2-data-$sigma.mat\")\ny_, hs, H, s, u_est, kappa = d[\"yobs\"], d[\"hs\"], d[\"H\"], d[\"s\"], d[\"u_est\"], d[\"kappavalue\"]\n\nR = r*diagm(0=>ones(length(hs)))\nQ = q*diagm(0=>ones(length(s)))\n\u03bc, \u03a3 = uqnlin(y_, hs, H, R, s, Q)\n\u03c3 = diag(\u03a3)\n\n\n\numax = maximum(u_est)\nxc = LinRange(0, umax, 100)|>Array\nu2 = @. 0.1 + 1/(1+xc^2) + 100xc^2\nfigure()\nplot(xc, u2, \"-\", linewidth=2, label=\"Referencee\")\n\n# k = s[1:4:end]\nu1 = fem_to_fvm(u_est, m, n, h)\n# Is = sortperm(u1)\n# plot(u1[Is], k[Is], \"+--\")\n\n\n\nz1 = \u03bc[1:4:end]\n\u03c31 = 2\u03c3[1:4:end]\nu1 = u1[Is]\nz1 = z1[Is]\n\u03c31 = \u03c31[Is]\nplot(u1, z1, \"--\", linewidth=2, label=\"Posterior Mean\")\nfill_between(u1, z1-\u03c31, z1+\u03c31, alpha=0.3, color=\"orange\", label=\"Uncertainty Region\")\n\nxlim(minimum(u1), maximum(u1))\n\nxlabel(\"\\$u\\$\")\nylabel(\"\\$K(u)\\$\")\nlegend()\nsavefig(\"nn2-uq$sigma-1.png\")\n\n\nclose(\"all\")\nplot(u1, \u03c31, \"+\")\nxlabel(\"\\$u\\$\")\nylabel(\"Standard Deviation\")\nsavefig(\"nn2-uq$sigma-2.png\")\n\nend", "meta": {"hexsha": "8ba11aa4040109e7485d75139009740642ef86cf", "size": 1110, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "AdFemResearch/flow-model/nn2_analysis.jl", "max_stars_repo_name": "ADCMEMarket/ADCMEImages", "max_stars_repo_head_hexsha": "d89df7050f53e56f3c509ff737199068410dbbc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdFemResearch/flow-model/nn2_analysis.jl", "max_issues_repo_name": "ADCMEMarket/ADCMEImages", "max_issues_repo_head_hexsha": "d89df7050f53e56f3c509ff737199068410dbbc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdFemResearch/flow-model/nn2_analysis.jl", "max_forks_repo_name": "ADCMEMarket/ADCMEImages", "max_forks_repo_head_hexsha": "d89df7050f53e56f3c509ff737199068410dbbc2", "max_forks_repo_licenses": ["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.619047619, "max_line_length": 92, "alphanum_fraction": 0.5954954955, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.755782898976244}}
{"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    \u0394t \u2265 0, (start = 1/n) # Time step\n    # State variables\n    v[1:n] \u2265 0            # Velocity\n    h[1:n] \u2265 h_0          # Height\n    m_f \u2264 m[1:n] \u2264 m_0    # Mass\n    # Control\n    0 \u2264 T[1:n] \u2264 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, \u0394t * n)\n\n# Dynamics\nfor j in 2:n\n    # h' = v\n    \n    # Rectangular integration\n    # @NLconstraint(rocket, h[j] == h[j - 1] + \u0394t * v[j - 1])\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        h[j] == h[j - 1] + 0.5 * \u0394t * (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] + \u0394t *(\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 * \u0394t * (\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] - \u0394t * T[j - 1] / c)\n    \n    # Trapezoidal integration\n    @NLconstraint(rocket,\n        m[j] == m[j - 1] - 0.5 * \u0394t * (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.(\u0394t), y = value.(h)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Altitude\"))\nm_plot = plot(x = (1:n) * value.(\u0394t), y = value.(m)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Mass\"))\nv_plot = plot(x = (1:n) * value.(\u0394t), y = value.(v)[:], Geom.line,\n                Guide.xlabel(\"Time (s)\"), Guide.ylabel(\"Velocity\"))\nT_plot = plot(x = (1:n) * value.(\u0394t), 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    \u03c9(M, k)\n\nReturn the `M`th root of unity raised to the `k`th power.\n\"\"\"\n@inline \u03c9(M, k) = exp(-2im*\u03c0*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": "using Plots\n#pyplot()\n#plotlyjs()\n#gui()\n\nprintln(\"Plotting sine\")\nh = plot(sin, -2pi, pi, label = \"sine function\")\n#h = plot(cos, -2pi, pi, label = \"sine function\")\n#plot(tan, -2pi, pi, label = \"sine function\")\n#show(h)\n", "meta": {"hexsha": "c79cf5441934a72325b630e7ac72ff50869149ac", "size": 221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorial/Plotting.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": "tutorial/Plotting.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": "tutorial/Plotting.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": 20.0909090909, "max_line_length": 49, "alphanum_fraction": 0.6334841629, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7557706112695931}}
{"text": "\nusing DifferentialEquations, Plots, ParameterizedFunctions\ngr()\nlorenz = @ode_def Lorenz begin\n  dx = \u03c3*(y-x)\n  dy = \u03c1*x-y-x*z\n  dz = x*y-\u03b2*z\nend \u03c3 \u03b2 \u03c1\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    \u03bc::Tv\n    Q::Tm\n    L::Tl\nend\n\nfunction GMRF(\u03bc, Q)#::AbstractVector, Q::AbstractMatrix)\n    n = LinearAlgebra.checksquare(Q)\n    length(\u03bc) == n || DimensionMismatch(\"The dimensions of \u03bc and Q are inconsistent.\")\n    L, P = cholesky_ldl(Q)\n    return GMRF(\u03bc, 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(\u03bc::AbstractVector, F::LDLFactorization)\n\tP = F.P\n\tL = cholesky(F)\n\tQ = (L * L')[invperm(P), invperm(P)]\n    return GMRF(\u03bc, 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.\u03bc)\n    ld = logdet_from_chol(d.L)\n    x0 = x .- d.\u03bc\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.\u03bc\n\n# Uses the recursive method of Rue (2005)\n# Finds the \"future\" non-zero indices\nfunction \u2110(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 \u03a3, otherwise get zero below\n\tif (i > j)\n\t\t (j, i) = (i, j)\n\tend\n\t\u03a3ij = (i == j) ? 1 / L[i, i]^2 : zero(L[i, i])\n\tfor k in \u2110(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\u03a3ij -= 1 / L[i, i] * L[k, i] * cov_element(L, k, j)\n\tend\n\t\u03a3ij\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": "export project_rank!\n\nfunction project_rank!(\n                      x :: Array{TF,2},\n                      r :: TI,\n                      mode #not an option for matrices\n                      ) where {TF<:Real,TI<:Integer}\n\"\"\"\nProject the matrix X onto the set of rank-r ( need r<min(n1,n2) ) matrices\noutputs a vector. Uses singular value decomposition\n\"\"\"\n  F  = svd(x)\n  x .= F.U[:,1:r] * diagm(0 => F.S[1:r])* F.Vt[1:r,:]\n  x  = vec(x)\nend\n\nfunction project_rank!(\n                      x :: Array{TF,3},\n                      r :: TI,\n                      mode ::Tuple{String,String}\n                      ) where {TF<:Real,TI<:Integer}\n\"\"\"\nProject each slice (x,y or z) of the tensor (3D model) onto the set of rank-r ( need r<min(n1,n2) ) matrices\noutputs a vector. Uses singular value decomposition\n\"\"\"\nif mode[1] == \"slice\"\n  if mode[2] == \"x\" #project y-z slices, so one slice per gridpoint in the x direction\n    Threads.@threads for i=1:size(x,1)\n      F = svd(view(x,i,:,:))\n      @inbounds x[i,:,:] .= F.U[:,1:r] * diagm(0 => F.S[1:r])* F.Vt[1:r,:]\n    end\n  elseif mode[2] == \"y\"\n    Threads.@threads for i=1:size(x,2)\n      F = svd(view(x,:,i,:))\n      @inbounds x[:,i,:] .= F.U[:,1:r] * diagm(0 => F.S[1:r])* F.Vt[1:r,:]\n    end\n  elseif mode[2] == \"z\"\n    Threads.@threads for i=1:size(x,3)\n      F=svd(view(x,:,:,i))\n      @inbounds x[:,:,i] .= F.U[:,1:r] * diagm(0 => F.S[1:r])* F.Vt[1:r,:]\n    end\n  end #end if mode[2]\nelse\n error(\"mode[1] for rank projections can only be: slice\")\nend #if mode[1]\n\n  x=vec(x)\nend\n", "meta": {"hexsha": "f8a402fc0ab161675d8b2dd8b029159dc10c9684", "size": 1539, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/projectors/project_rank!.jl", "max_stars_repo_name": "slimgroup/SetIntersectionProjection", "max_stars_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "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_rank!.jl", "max_issues_repo_name": "slimgroup/SetIntersectionProjection", "max_issues_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "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_rank!.jl", "max_forks_repo_name": "slimgroup/SetIntersectionProjection", "max_forks_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "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": 31.4081632653, "max_line_length": 108, "alphanum_fraction": 0.5159194282, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7557337441022423}}
{"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 \u2264 n_dim \u2264 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 \u22c5 R \u2208 2\u03c0 \u2124 for all R in the lattice.\n\"\"\"\nfunction compute_recip_lattice(lattice::AbstractMatrix{T}) where {T}\n    2T(\u03c0) * 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(\u03c3, \u03be, \u03ba)\n\n*EGPpower* corresponds to the first extended GP model of Naveau et al. (2016), with the power law distribution G(v)\u2009=\u2009v^\u03ba.\n\nIt is a three parameters family: \u03ba controls the shape of the lower tail, \u03c3 is a scale parameter, and \u03be controls the rate of upper tail decay.\n\n```julia\nEGPpower(\u03c3, \u03be, \u03ba)   # EGP of Naveau et al. (2016) (type 1) with scale parameter \u03c3, rate of upper tail decay \u03be and shape of the lower tail \u03ba.\n\nparams(d)           # Get the parameters, i.e. (\u03c3, \u03be, \u03ba)\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\u2013 2769, doi:10.1002/2015WR018552.\n\"\"\"\nstruct EGPpower{T<:Real} <: ContinuousUnivariateDistribution\n    \u03c3::T    # scale parameter\n    \u03be::T    # rate of upper tail decay\n    \u03ba::T    # shape of the lower tail\n\n    function EGPpower{T}(\u03c3::T, \u03be::T, \u03ba::T) where {T <: Real}\n        new{T}(\u03c3, \u03be, \u03ba)\n    end\nend\n\nfunction EGPpower(\u03c3::T, \u03be::T, \u03ba::T; check_args=true) where {T <: Real}\n    check_args && @check_args(EGPpower, \u03c3 > zero(\u03c3) && \u03ba > zero(\u03ba))\n    return EGPpower{T}(\u03c3, \u03be, \u03ba)\nend\n\nEGPpower(\u03c3::Real, \u03be::Real, \u03ba::Real) = EGPpower(promote(\u03c3, \u03be, \u03ba)...)\nEGPpower(\u03c3::Integer, \u03be::Integer, \u03ba::Integer) = EGPpower(float(\u03c3), float(\u03be), float(\u03ba))\n\n\nminimum(d::EGPpower) = 0.0\nmaximum(d::EGPpower) = Inf * (d.\u03be >= 0) - ( d.\u03c3 / d.\u03be ) * (d.\u03be < 0)\ninsupport(d::EGPpower, x::Real) = minimum(d) <= x <= maximum(d)\n\n\n#### Parameters\n\nscale(d::EGPpower) = d.\u03c3\ndecay(d::EGPpower) = d.\u03be    # noms \u00e0 v\u00e9rifier...\nshape(d::EGPpower) = d.\u03ba\n\nparams(d::EGPpower) = (d.\u03c3, d.\u03be, d.\u03ba)\npartype(::EGPpower{T}) where {T} = T\n\n\n#### Evaluation\n\nfunction logpdf(d::EGPpower{T}, x::Real) where T<:Real\n    \u03bc = 0\n    (\u03c3, \u03be, \u03ba) = params(d)\n\n    pd = GeneralizedPareto(\u03bc, 1, \u03be)\n\n    lg(v::Real) = log(\u03ba) + (\u03ba-1)*log(v)\n\n    p = -log(\u03c3) + Distributions.logpdf(pd, x/\u03c3) + lg(Distributions.cdf(pd, x/\u03c3))\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    # \u00c0 v\u00e9rifier\n    \u03bc = 0\n    (\u03c3, \u03be, \u03ba) = params(d)\n\n    pd = GeneralizedPareto(\u03bc, 1, \u03be)\n\n    #G(v::Real, \u03ba::Real) = v^\u03ba\n    #lG(v::Real, \u03ba::Real) = \u03ba*log(v)\n\n    p = \u03ba*Distributions.logcdf(pd, x/\u03c3)\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    (\u03c3, \u03be, \u03ba) = params(d)\n\n    invG(p::Real, \u03ba::Real) = p^(1/\u03ba)\n\n    x = (\u03c3/\u03be)*(((1 - invG(p,\u03ba))^(-\u03be)) - 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, \u03ba::Real) = p^(1/\u03ba)\n\n    return (d.\u03c3/d.\u03be)*(((1 - invG(u,d.\u03ba))^(-d.\u03be)) - 1)\nend\n\nsampler(d::EGPpower) = d    # \u00e0 v\u00e9rifier\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 Distributions\ndist = TriangularDist(0,2,1)\n\nprintln(\"Parameters: \\t\\t\\t\",params(dist))\nprintln(\"Central descriptors: \\t\\t\",mean(dist),\"\\t\",median(dist))\nprintln(\"Dispersion descriptors: \\t\", var(dist),\"\\t\",std(dist))\nprintln(\"Higher moment shape descriptors: \",skewness(dist),\"\\t\",kurtosis(dist))\nprintln(\"Range: \\t\\t\\t\\t\", minimum(dist),\"\\t\",maximum(dist))\nprintln(\"Mode: \\t\\t\\t\\t\", mode(dist), \"\\tModes: \",modes(dist))", "meta": {"hexsha": "c4e40bc1e6c184777be04decd1b9076b63ad1aaa", "size": 426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/distributionDescriptors.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/distributionDescriptors.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/distributionDescriptors.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": 47.3333333333, "max_line_length": 79, "alphanum_fraction": 0.6948356808, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7557337291844314}}
{"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(\u211d, nodes*\u221a2, weights/\u221a\u03c0)\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(\ud835\udd40, 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\u2013338.\n# doi:10.1137/s1064827502419154.\n\n#### LTSA type\nstruct LTSA{T <: AbstractFloat} <: SpectralResult\n    k::Int\n    \u03bb::AbstractVector{T}\n    proj::Projection{T}\n\n    LTSA{T}(k::Int, \u03bb::AbstractVector{T}, proj::Projection{T}) where T = new(k, \u03bb, proj)\nend\n\n## properties\noutdim(M::LTSA) = size(M.proj, 1)\nprojection(M::LTSA) = M.proj\n\neigvals(M::LTSA) = M.\u03bb\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.\u03bb), 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        \u03bc = mean(X[:,I[:,i]], dims=2)\n        \u03b4_x = X[:,I[:,i]] .- \u03bc\n\n        # Compute orthogonal basis H of \u03b8'\n        \u03b8_t = svd(\u03b4_x).V[:,1:d]\n\n        # Construct alignment matrix\n        G = hcat(ones(k)./sqrt(k), \u03b8_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    \u03bb, V = decompose(B, d)\n    return LTSA{T}(k, \u03bb, 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. (\ud835\ude02 \u00d7 \ud835\ude03 = \ud835\udfec).\n# For \ud835\uddf9\u2081(r) = \ud835\ude05\u2081 + r\ud835\ude02 and \ud835\uddf9\u2082(s) = \ud835\ude05\u2082 + s\ud835\ude03\n# 1) \ud835\ude05\u2081 + r\ud835\ude02 = \ud835\ude05\u2082 + s\ud835\ude03                  subtracting \ud835\ude05\u2081 from both sides\n# 2) r\ud835\ude02 = (\ud835\ude05\u2082-\ud835\ude05\u2081) + s\ud835\ude03                  \ud835\ude04 = \ud835\ude05\u2082-\ud835\ude05\u2081\n# 3) r\ud835\ude02 = \ud835\ude04 + s\ud835\ude03                        cross product with \ud835\ude03 (distributive)\n# 4) r(\ud835\ude02 \u00d7 \ud835\ude03) = \ud835\ude04 \u00d7 \ud835\ude03 + s(\ud835\ude03 \u00d7 \ud835\ude03)        \ud835\ude03 \u00d7 \ud835\ude03 = \ud835\udfec\n# 5) r(\ud835\ude02 \u00d7 \ud835\ude03) = \ud835\ude04 \u00d7 \ud835\ude03                   let \ud835\ude04 \u00d7 \ud835\ude03 = \ud835\ude05 and \ud835\ude02 \u00d7 \ud835\ude03 = \ud835\ude07\n# 6) r\ud835\ude07 = \ud835\ude05                             dot product \ud835\ude07 to each side\n# 7) r\ud835\ude07 \u22c5 \ud835\ude07 = \ud835\ude05 \u22c5 \ud835\ude07                     divide by \ud835\ude07 \u22c5 \ud835\ude07\n# 8) r = (\ud835\ude05 \u22c5 \ud835\ude07)/(\ud835\ude07 \u22c5 \ud835\ude07)\n# We need to ensure r, s \u2208 [0, 1], hence we need to solve for s too.\n# 1) \ud835\ude05\u2082 + s\ud835\ude03 = \ud835\ude05\u2081 + r\ud835\ude02                     subtracting \ud835\ude05\u2082 from both sides\n# 2) s\ud835\ude03 = -\ud835\ude04 + r\ud835\ude02                          cross product with \ud835\ude04\n# 3) s(\ud835\ude03 \u00d7 \ud835\ude04) = -\ud835\ude04 \u00d7 \ud835\ude04 + r(\ud835\ude02 \u00d7 \ud835\ude04)          \ud835\ude04 \u00d7 \ud835\ude04 = \ud835\udfec \n# 4) s(\ud835\ude03 \u00d7 \ud835\ude04) = r(\ud835\ude02 \u00d7 \ud835\ude04)                   using \ud835\ude02 \u00d7 \ud835\ude04 = -(\ud835\ude04 \u00d7 \ud835\ude02), likewise for \ud835\ude03 \u00d7 \ud835\ude04\n# 5) s(\ud835\ude04 \u00d7 \ud835\ude03) = r(\ud835\ude04 \u00d7 \ud835\ude02)                   let \ud835\ude04 \u00d7 \ud835\ude02 = \ud835\ude06. use \ud835\ude04 \u00d7 \ud835\ude03 = \ud835\ude05\n# 6) s\ud835\ude05 = r\ud835\ude06                               dot product \ud835\ude05 to each side\n# 7) s(\ud835\ude05 \u22c5 \ud835\ude05) = r(\ud835\ude06 \u22c5 \ud835\ude05)                   divide by (\ud835\ude05 \u22c5 \ud835\ude05)\n# 9) s = r(\ud835\ude05 \u22c5 \ud835\ude06)/(\ud835\ude05 \u22c5 \ud835\ude05)\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 = (\ud835\ude05 \u22c5 \ud835\ude07)/(\ud835\ude07 \u22c5 \ud835\ude07) = x\u2083/z\u2083 \n# s = r(\ud835\ude05 \u22c5 \ud835\ude06)/(\ud835\ude05 \u22c5 \ud835\ude05) = y\u2083/z\u2083 \nfunction Base.intersect(l\u2081::LineSegment{Point{2,T}}, \n                        l\u2082::LineSegment{Point{2,T}}) where {T} \n    \ud835\ude04 = l\u2082[1] - l\u2081[1]\n    \ud835\ude02\u2081= l\u2081[2] - l\u2081[1] \n    \ud835\ude02\u2082= l\u2082[2] - l\u2082[1] \n    z = \ud835\ude02\u2081 \u00d7 \ud835\ude02\u2082\n    r = (\ud835\ude04 \u00d7 \ud835\ude02\u2082)/z\n    s = (\ud835\ude04 \u00d7 \ud835\ude02\u2081)/z\n    valid = 0 \u2264 r && r \u2264 1 && 0 \u2264 s && s \u2264 1\n    return valid ? l\u2082(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# \u2554\u2550\u2561 876e6928-abdc-11eb-0fea-d51de2d4b971\nmd\"\"\" ### Quick Julia tutorial...\n\"\"\"\n\n# \u2554\u2550\u2561 9e95da34-fc21-4e7e-99a9-aea83edacd19\n# global variable\nexample = 9.5\n\n# \u2554\u2550\u2561 34282b28-b73f-4aa7-96be-31dd6700084f\nareaofcircle(r) = pi * r^2\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3f2ba373-77c6-4462-b30b-94fc8602298e\nmodule Bleep\n\texample = 1\n\tfoo() = example\nend\n\n# \u2554\u2550\u2561 6315a551-f39b-40be-8c84-d3fbf34de4d0\nBleep.foo()\n\n# \u2554\u2550\u2561 fa32bf73-e41a-4db5-ab2a-3e5a9e383aef\nmd\"\"\"\nAnd this new module's independent scope is separate from the caller's global scope:\n\"\"\"\n\n# \u2554\u2550\u2561 0cd019ae-3521-4323-9371-020190603204\nmodule Deeee\n\tbeh = example\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 92713261-8080-4797-8e48-0f0c2ce0e391\nfunction changer!(bees)\n    bees .+= 1\n    return\nend\n\n# \u2554\u2550\u2561 997f3fe0-d920-4055-b81e-b259fce128a3\nty = [1.0,2.0,3.0]\n\n# \u2554\u2550\u2561 b6fa822c-7a55-46fe-b3a3-f191fe3ebd3d\nbegin\n\tchanger!(ty)\n\tty\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 dc423ed7-c9ee-416a-a0b2-a3c1408221cd\nbegin\n\tblip = [1,2,3]\n\tbehhh = blip\nend\n\n# \u2554\u2550\u2561 b9aab8cc-c738-4f3c-a845-52f5078d1478\nbehhh[2] = 4\n\n# \u2554\u2550\u2561 0b04f67a-e413-4c9a-b298-610a294561b8\nblip\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b03cc059-d281-4973-a22a-fabeb5de06e0\n(zoot, beef, crr, drrt, efff, fooop)\n\n# \u2554\u2550\u2561 c423ec0a-dbf7-4400-99f9-8357ac59edd1\nmd\"\"\"\n#### Working with arrays, concatenation, and plotting...\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d50d1e34-9ef2-41de-8dac-bb763685fd5f\nfruits = hcat(apples, oranges, pears, bananas)\n\n# \u2554\u2550\u2561 2f248615-aaca-44ce-a0d9-0ac31e12ba52\nbegin\n\tusing Plots\n\tplot(years, fruits, layout=(4, 1), legend=false)\nend\n\n# \u2554\u2550\u2561 6658d1dc-aefd-449b-8d81-f2b9f6a6fe3c\nsort(fruits, dims=2)\n\n# \u2554\u2550\u2561 3bc93ea9-0718-47b9-ae4c-d1286641c9f2\nall(i->(4<=i<=6), [4,5,6])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cca3129b-8ccb-4747-b75d-cb34f3ff5b23\nstruct Limbs\n\thands :: Float64\n\tleg :: Integer\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 26730fa4-254c-4bef-81e5-39803ebcaa2e\nbegin\n\tjoseph = boy(2.,1)\n\tjoseph.body_parts.hands\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 39d444ec-f84a-4d1b-9ba4-19af636bf3dd\n\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500876e6928-abdc-11eb-0fea-d51de2d4b971\n# \u2560\u25509e95da34-fc21-4e7e-99a9-aea83edacd19\n# \u2560\u255034282b28-b73f-4aa7-96be-31dd6700084f\n# \u2560\u2550451499e9-76d9-4088-af2f-f35a9222afca\n# \u255f\u25001a3a323e-3f6b-4d65-bcbe-7c1c98aeb150\n# \u2560\u25503f2ba373-77c6-4462-b30b-94fc8602298e\n# \u2560\u25506315a551-f39b-40be-8c84-d3fbf34de4d0\n# \u255f\u2500fa32bf73-e41a-4db5-ab2a-3e5a9e383aef\n# \u2560\u25500cd019ae-3521-4323-9371-020190603204\n# \u255f\u250092cfd5a5-09ef-401d-a4a6-53d2576b314f\n# \u2560\u255092713261-8080-4797-8e48-0f0c2ce0e391\n# \u2560\u2550997f3fe0-d920-4055-b81e-b259fce128a3\n# \u2560\u2550b6fa822c-7a55-46fe-b3a3-f191fe3ebd3d\n# \u255f\u2500883334fb-f81b-4c24-9527-571a26ce7ce8\n# \u2560\u2550dc423ed7-c9ee-416a-a0b2-a3c1408221cd\n# \u2560\u2550b9aab8cc-c738-4f3c-a845-52f5078d1478\n# \u2560\u25500b04f67a-e413-4c9a-b298-610a294561b8\n# \u255f\u2500251313ac-b425-47c5-aae8-d78e5167b052\n# \u255f\u25009f9fb7dd-b0f6-4bb8-b523-6053b5bc39dc\n# \u2560\u2550b03cc059-d281-4973-a22a-fabeb5de06e0\n# \u255f\u2500c423ec0a-dbf7-4400-99f9-8357ac59edd1\n# \u2560\u2550d5e187ee-c6b0-4490-80e0-12a47e809d27\n# \u2560\u2550d50d1e34-9ef2-41de-8dac-bb763685fd5f\n# \u2560\u25506658d1dc-aefd-449b-8d81-f2b9f6a6fe3c\n# \u2560\u25502f248615-aaca-44ce-a0d9-0ac31e12ba52\n# \u2560\u25503bc93ea9-0718-47b9-ae4c-d1286641c9f2\n# \u255f\u250028108af6-a838-417b-85a5-5e3fff0ae49b\n# \u2560\u2550cca3129b-8ccb-4747-b75d-cb34f3ff5b23\n# \u2560\u2550b1ce5d0c-c3f6-411c-8f04-c44854fa89b1\n# \u2560\u255026730fa4-254c-4bef-81e5-39803ebcaa2e\n# \u255f\u2500921051ca-54dc-4563-a116-0756cca43557\n# \u255f\u25008a3ee669-bad2-4086-b90a-1744b85dcf76\n# \u2560\u255039d444ec-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 + \u03bb 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 \u03c0 x / Lx ) cos( k \u03c0 y / Ly )\n#\n#                      2               2\n#      \u03bb = ( n \u03c0 / Lx )  + ( k \u03c0 / 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\u03bb = Float64[]\nfor n = 1:nev, k = 0:nev-1\n    push!(\u03bb, (n*pi/Lx)^2+(k*pi/Ly)^2)\nend\n\nsort!(\u03bb)\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|\", \"\u03bb_$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-\u03bb[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": "@testset \"MatrixDepot\" begin\ndebit = [ (\"hilb\", 5),  (\"cauchy\",4), (\"invhilb\",4), (\"moler\",7),(\"pascal\",6),(\"pei\",100),(\"tridiag\",100),(\"lehmer\",100),(\"poisson\",12),(\"wathen\",10)] \n\nfor k=1:length(debit)\n\tA   = matrixdepot(debit[k][1],debit[k][2])\n\trhs = randn(size(A,1))\n\t@printf \"%s\\tn=[%d,%d]\\t\" debit[k][1] size(A,1) size(A,2)\n\n\txt  = A\\rhs\n\t\n\tx3, = gmres(A,rhs,10,maxIter=50*length(rhs),tol=1e-16,out=0)\t\n\t@test norm(xt-x3)/norm(xt) < 1e-3\n\t@printf \" gmres is OK \"\n\tx1, = cg(A,rhs,maxIter=length(rhs),tol=1e-16,out=-1)\n\t@test norm(xt-x1)/norm(xt) < 1e-3\n\t@printf \"cg is OK\\n\"\nend\n\t\nend", "meta": {"hexsha": "d434b14d4b7e765d2f3c07a2afbadc159c32b8af", "size": 590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testMatrixDepot.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": "test/testMatrixDepot.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": "test/testMatrixDepot.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": 31.0526315789, "max_line_length": 151, "alphanum_fraction": 0.5915254237, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7556176824676855}}
{"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 \u2265 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": "import Random\nrng0 = Random.MersenneTwister(1234);\n\nconst Mat = Matrix{Float64}\nconst Vec = Vector{Float64}\n\nstruct RNN\n    Wx :: Mat  # Transform input to hidden\n    Wh :: Mat  # Transform hidden to hidden\n    b  :: Vec  # Bias hidden to hidden\nend\n\n# RNN model: Given input sequence xs, compute output sequence\nfunction rnn(weights :: RNN, xs :: Array{Vec}) :: Array{Vec}\n    h = rand(rng, length(weights.b))\n    [\n      h = tanh.(weights.Wh * h) + tanh.(weights.Wx * x) + weights.b\n         for x in xs \n    ]\nend\n\n# RNN model: Given input sequence xs, compute output sequence\nfunction rnn2(weights :: RNN, xs :: Array{Vec})\n    h = rand(rng, length(weights.b))\n    show(h)\n    out = []\n    for x in xs\n        h = tanh.(weights.Wh * h) + tanh.(weights.Wx * x) + weights.b\n        push!(out, h)\n    end\n    out\nend\n\nweights = RNN(rand(5,3), rand(5,5), rand(5))\n\nxs = [rand(rng, 3) for i in 1:5];\n\nrng = copy(rng0);\nr1 = rnn(weights, xs)\n\nrng = copy(rng0);\nr2 = rnn2(weights, xs)\n", "meta": {"hexsha": "f4c94ea6990cb0b735f409e845e4233b13669bc9", "size": 982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/dl-rnn/dl-rnn.jl", "max_stars_repo_name": "tomjaguarpaw/knossos-ksc", "max_stars_repo_head_hexsha": "8fa75e67c0db8f632b135379740051cd10ff31f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2021-09-09T16:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T02:15:19.000Z", "max_issues_repo_path": "examples/dl-rnn/dl-rnn.jl", "max_issues_repo_name": "tomjaguarpaw/knossos-ksc", "max_issues_repo_head_hexsha": "8fa75e67c0db8f632b135379740051cd10ff31f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2021-08-06T14:30:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T08:49:52.000Z", "max_forks_repo_path": "examples/dl-rnn/dl-rnn.jl", "max_forks_repo_name": "tomjaguarpaw/knossos-ksc", "max_forks_repo_head_hexsha": "8fa75e67c0db8f632b135379740051cd10ff31f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-08-06T11:20:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T19:39:40.000Z", "avg_line_length": 22.8372093023, "max_line_length": 69, "alphanum_fraction": 0.6099796334, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7556176722695983}}
{"text": "@testset \"Maximum weighted matching\" begin\n    function neighbors(sym_matrix, i)\n        return findall(v -> v != 0, sym_matrix[:, i])\n    end\n\n    @testset \"Bipartite example\" begin\n\n        # from slide 65 of https://www.slideshare.net/KuoE0/acmicpc-bipartite-matching\n        # but set 1 <-> 4 to 4.9 to avoid matching 1 <-> 4 and 3 <-> 5 which also sums to 10\n        weight_matrix = [\n            0 0 0 4.9 0 2\n            0 0 0 3 1 -2\n            0 0 0 0 5 0\n            4.9 3 5 0 0 0\n            0 1 0 0 0 0\n            2 -2 0 0 0 0\n        ]\n        n = 6\n\n        m = Model(CSJuMPTestOptimizer())\n        @variable(m, x[1:n, 1:n], Bin)\n        for i in 1:n, j in 1:n\n            if weight_matrix[i, j] == 0 || i > j\n                @constraint(m, x[i, j] == 0)\n            end\n        end\n        for i in 1:n\n            @constraint(\n                m,\n                sum(x[min(i, j), max(i, j)] for j in neighbors(weight_matrix, i)) <= 1\n            )\n        end\n\n        @objective(m, Max, sum(weight_matrix .* x))\n        optimize!(m)\n        @test JuMP.objective_value(m) \u2248 10\n        @test JuMP.value(x[1, 6]) == 1\n        @test JuMP.value(x[2, 4]) == 1\n        @test JuMP.value(x[3, 5]) == 1\n        @test sum(JuMP.value.(x[1, 1:6])) == 1\n        @test sum(JuMP.value.(x[2, 1:6])) == 1\n        @test sum(JuMP.value.(x[3, 1:6])) == 1\n        @test sum(JuMP.value.(x[4, 1:6])) == 0\n        @test sum(JuMP.value.(x[5, 1:6])) == 0\n        @test sum(JuMP.value.(x[6, 1:6])) == 0\n    end\nend\n", "meta": {"hexsha": "38972ecc4621f4765f7a3d77b26b635d0f3376e3", "size": 1504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/maximum_weight_matching.jl", "max_stars_repo_name": "Azzaare/ConstraintSolver.jl", "max_stars_repo_head_hexsha": "feec0320d9c26e16c2ced59bf11877ac7141ce8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 120, "max_stars_repo_stars_event_min_datetime": "2019-09-05T23:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:04:40.000Z", "max_issues_repo_path": "test/maximum_weight_matching.jl", "max_issues_repo_name": "Azzaare/ConstraintSolver.jl", "max_issues_repo_head_hexsha": "feec0320d9c26e16c2ced59bf11877ac7141ce8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 273, "max_issues_repo_issues_event_min_datetime": "2019-09-05T11:20:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:57:00.000Z", "max_forks_repo_path": "test/maximum_weight_matching.jl", "max_forks_repo_name": "Azzaare/ConstraintSolver.jl", "max_forks_repo_head_hexsha": "feec0320d9c26e16c2ced59bf11877ac7141ce8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-09-13T08:36:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T18:08:03.000Z", "avg_line_length": 31.3333333333, "max_line_length": 92, "alphanum_fraction": 0.4640957447, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384731, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7556176718190483}}
{"text": "export intersection_params, line_segment_point, each_intersect, find_juncts, find_connect, connections\n\n\"\"\"\n```julia\nintersection_params(w\u2081::Line, w\u2082::Line)\n```\nGiven two lines computes the parameters `[t,s]` so that \nthe intersection of the lines occurs at \n`(w\u2081.p\u2082-w\u2081.p\u2081)t+w\u2081.p\u2081==(w\u2082.p\u2082-w\u2082.p\u2081)s+w\u2082.p\u2081`. 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\u2264t\u22641` and `0\u2264s\u22641`.\n\"\"\"\nfunction intersection_params(w\u2081::Line, w\u2082::Line)\n    hcat(w\u2081.p\u2082-w\u2081.p\u2081,w\u2082.p\u2081-w\u2082.p\u2082)\\(w\u2082.p\u2081-w\u2081.p\u2081)\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\u2082*t+(1-t)p\u2081` \nis the parametric equation of the line. \n\"\"\"\nfunction line_segment_point(t::T, w::Line) where T<:Real \n    w.p\u2082*t+(1-t)*w.p\u2081\nend\n\n\"\"\"\n```julia\neach_intersect(f!,arr\u2081,arr\u2082,dims,arg)\n```\n    Executes `f!(i\u2081,i\u2082,arr\u2081,arr\u2082,dims,ps,p,arg)` for any intersection between pairs of \n    lines in `arr\u2081` and `arr\u2082`. `i\u2081` and `i\u2082` are the indices of the lines in `arr\u2081` \n    and `arr\u2082` respectively, `ps` is the vector of line intersection parameters as \n    computed by `intersection_params(arr\u2081[i\u2081],arr\u2082[i\u2082])`, and `p` is the point at which \n    the intersection occurs.\n\"\"\"\nfunction each_intersect(f!, arr\u2081::Array{Line{S,N}}, arr\u2082::Array{Line{S,N}}, dims::SVector{N,S}, arg) where {S,N}\n    for i\u2081 \u2208 eachindex(arr\u2081)\n        for i\u2082 \u2208 eachindex(arr\u2082)\n            ps = intersection_params(arr\u2081[i\u2081],arr\u2082[i\u2082])\n            if (0.0 \u2264 ps[1] \u2264 1.0) && (0.0 \u2264 ps[2] \u2264 1.0)\n                p = line_segment_point(ps[1],arr\u2081[i\u2081])\n                if sum( zero(SVector{N, S}) .\u2264 p .\u2264 dims ) == N\n                    f!(i\u2081,i\u2082,arr\u2081,arr\u2082,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\u2081,i\u2082,arr,dims,ps,p,arg)` for any intersection between pairs of \n    lines in `arr`. `i\u2081` and `i\u2082` 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\u2081],arr[i\u2082])`, 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\u2081 \u2208 2:(n)\n        for i\u2082 \u2208 1:(i\u2081-1)\n            ps = intersection_params(arr[i\u2081],arr[i\u2082])\n            if (0.0 \u2264 ps[1] \u2264 1.0) && (0.0 \u2264 ps[2] \u2264 1.0)\n                p = line_segment_point(ps[1],arr[i\u2081])\n                if sum( zero(SVector{N, S}) .\u2264 p .\u2264 dims ) == N\n                    f!(i\u2081,i\u2082,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\u2081,i\u2082,arr,dims,ps,p,juncts\n        push!(juncts,(p,(i\u2081,i\u2082)))\n    end\nend\n\n\"\"\"\n```julia\nfind_connect(net)\n```\nGiven an `StickNetwork` object finds all pairs `(i\u2081,i\u2082)` with an intersection between lines `i\u2081` and `i\u2082` 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\u2081,i\u2082,arr,dims,ps,p,connects\n        push!(connects,(i\u2081,i\u2082))\n    end\nend\n\n\"\"\"\n```julia\nconnections(arr\u2081,arr\u2082,dims)\n```\nFinds all connections between arrays of `Line`s `arr\u2081` and `arr\u2082`. \nReturns `Tuple{Vector{Int},Vector{Int}}` with each vector representing the source and destination line indices for each connection.\n\"\"\"\nfunction connections(arr\u2081::Array{Line{S,N}}, arr\u2082::Array{Line{S,N}}, dims::SVector{N,S}) where {S,N}\n    each_intersect(arr\u2081, arr\u2082, dims, (Int[],Int[])) do i\u2081,i\u2082,arr\u2081,arr\u2082,dims,ps,p,connects\n        push!(connects[1],i\u2081)\n        push!(connects[2],i\u2082)\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\u2081,i\u2082,arr,dims,ps,p,connects\n        push!(connects[1],i\u2081)\n        push!(connects[2],i\u2082)\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\u00a0=\u00a0cat(y1,y2,y3,y4,y5,y6,dims=2)\u00a0\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": "\"\"\"\n\tstationarydist(c::MarkovChain)\n\nPh\u00e2n ph\u1ed1i d\u1eebng c\u1ee7a x\u00edch markov\n\"\"\"\nfunction stationarydist(c::MarkovChain)\n\tP = m.P\n\tn = size(P, 1)\n\tA = [(transpose(p) - I)[1:end-1, :]; ones(1, n)]\n\tB = [zeros(n - 1); 1]\n\tinv(A) * B\nend\n\nfunction Base.show(io::IO, m::MarkovChain)\n\tdisplay(\"X\u00edch Markov v\u1edbi ma tr\u1eadn chuy\u1ec3n\")\n\tdisplay(m.P)\nend\n", "meta": {"hexsha": "a973a915755bd941dd9c212988b0ed2bf40ce293", "size": 331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/markovchain.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/markovchain.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/markovchain.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": 18.3888888889, "max_line_length": 49, "alphanum_fraction": 0.6374622356, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7556121142191246}}
{"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": "# Testing:\n#\n#  - computation of sufficient statistics\n#  - distribution fitting (i.e. estimation)\n#\n\nusing Distributions\nusing Base.Test\n\nn0 = 100\nN = 10^5\n\nw = rand(n0)\n\n# DiscreteUniform\n\nx = rand(DiscreteUniform(10, 15), n0)\nd = fit(DiscreteUniform, x)\n@test isa(d, DiscreteUniform)\n@test minimum(d) == minimum(x)\n@test maximum(d) == maximum(x)\n\nd = fit(DiscreteUniform, rand(DiscreteUniform(10, 15), N))\n@test minimum(d) == 10\n@test maximum(d) == 15\n\n\n# Bernoulli\n\nx = rand(Bernoulli(0.7), n0)\n\nss = suffstats(Bernoulli, x)\n@test isa(ss, Distributions.BernoulliStats)\n@test ss.cnt0 == n0 - countnz(x)\n@test ss.cnt1 == countnz(x)\n\nss = suffstats(Bernoulli, x, w)\n@test isa(ss, Distributions.BernoulliStats)\n@test_approx_eq ss.cnt0 sum(w[x .== 0])\n@test_approx_eq ss.cnt1 sum(w[x .== 1])\n\nd = fit(Bernoulli, x)\np = countnz(x) / n0\n@test isa(d, Bernoulli)\n@test_approx_eq mean(d) p\n\nd = fit(Bernoulli, x, w)\np = sum(w[x .== 1]) / sum(w)\n@test isa(d, Bernoulli)\n@test_approx_eq mean(d) p \n\nd = fit(Bernoulli, rand(Bernoulli(0.7), N))\n@test isa(d, Bernoulli)\n@test_approx_eq_eps mean(d) 0.7 0.01\n\n\n# Beta\n\nd = fit(Beta, rand(Beta(1.3, 3.7), N))\n@test isa(d, Beta)\n@test_approx_eq_eps d.\u03b1 1.3 0.1\n@test_approx_eq_eps d.\u03b2 3.7 0.1\n\n\n# Binomial\n\nx = rand(Binomial(100, 0.3), n0)\n\nss = suffstats(Binomial, (100, x))\n@test isa(ss, Distributions.BinomialStats)\n@test_approx_eq ss.ns sum(x)\n@test ss.ne == n0\n@test ss.n == 100\n\nss = suffstats(Binomial, (100, x), w)\n@test isa(ss, Distributions.BinomialStats)\n@test_approx_eq ss.ns dot(Float64[xx for xx in x], w)\n@test_approx_eq ss.ne sum(w)\n@test ss.n == 100\n\nd = fit(Binomial, (100, x))\n@test isa(d, Binomial)\n@test ntrials(d) == 100\n@test_approx_eq succprob(d) sum(x) / (n0 * 100)\n\nd = fit(Binomial, (100, x), w)\n@test isa(d, Binomial)\n@test ntrials(d) == 100\n@test_approx_eq succprob(d) dot(x, w) / (sum(w) * 100)\n\nd = fit(Binomial, 100, rand(Binomial(100, 0.3), N))\n@test isa(d, Binomial)\n@test ntrials(d) == 100\n@test_approx_eq_eps succprob(d) 0.3 0.01\n\n\n# Categorical\n\np = [0.2, 0.5, 0.3]\nx = rand(Categorical(p), n0)\n\nss = suffstats(Categorical, (3, x))\nh = Float64[countnz(x .== i) for i = 1 : 3]\n@test isa(ss, Distributions.CategoricalStats)\n@test_approx_eq ss.h h\n\nd = fit(Categorical, (3, x))\n@test isa(d, Categorical)\n@test d.K == 3\n@test_approx_eq probs(d) h / sum(h)\n\nd2 = fit(Categorical, x)\n@test isa(d2, Categorical)\n@test probs(d2) == probs(d)\n\nss = suffstats(Categorical, (3, x), w)\nh = Float64[sum(w[x .== i]) for i = 1 : 3]\n@test isa(ss, Distributions.CategoricalStats)\n@test_approx_eq ss.h h\n\nd = fit(Categorical, (3, x), w)\n@test isa(d, Categorical)\n@test_approx_eq probs(d) h / sum(h)\n\nd = fit(Categorical, suffstats(Categorical, 3, x, w))\n@test isa(d, Categorical)\n@test_approx_eq probs(d) (h / sum(h))\n\nd = fit(Categorical, rand(Categorical(p), N))\n@test isa(d, Categorical)\n@test_approx_eq_eps probs(d) p 0.01\n\n\n# Exponential\n\nx = rand(Exponential(0.5), n0)\n\nss = suffstats(Exponential, x)\n@test isa(ss, Distributions.ExponentialStats)\n@test_approx_eq ss.sx sum(x)\n@test ss.sw == n0\n\nss = suffstats(Exponential, x, w)\n@test isa(ss, Distributions.ExponentialStats)\n@test_approx_eq ss.sx dot(x, w)\n@test ss.sw == sum(w)\n\nd = fit(Exponential, x)\n@test isa(d, Exponential)\n@test_approx_eq scale(d) mean(x)\n\nd = fit(Exponential, x, w)\n@test isa(d, Exponential)\n@test_approx_eq scale(d) dot(x, w) / sum(w)\n\nd = fit(Exponential, rand(Exponential(0.5), N))\n@test isa(d, Exponential)\n@test_approx_eq_eps scale(d) 0.5 0.01\n\n\n# Normal\n\n\u03bc = 11.3\n\u03c3 = 3.2\n\nx = rand(Normal(\u03bc, \u03c3), n0)\n\nss = suffstats(Normal, x)\n@test isa(ss, Distributions.NormalStats)\n@test_approx_eq ss.s sum(x)\n@test_approx_eq ss.m mean(x)\n@test_approx_eq ss.s2 sum((x .- ss.m).^2)\n@test_approx_eq ss.tw n0\n\nss = suffstats(Normal, x, w)\n@test isa(ss, Distributions.NormalStats)\n@test_approx_eq ss.s dot(x, w)\n@test_approx_eq ss.m dot(x, w) / sum(w)\n@test_approx_eq ss.s2 dot((x .- ss.m).^2, w)\n@test_approx_eq ss.tw sum(w)\n\nd = fit(Normal, x)\n@test isa(d, Normal)\n@test_approx_eq d.\u03bc mean(x)\n@test_approx_eq d.\u03c3 sqrt(mean((x .- d.\u03bc).^2))\n\nd = fit(Normal, x, w)\n@test isa(d, Normal)\n@test_approx_eq d.\u03bc dot(x, w) / sum(w)\n@test_approx_eq d.\u03c3 sqrt(dot((x .- d.\u03bc).^2, w) / sum(w))\n\nd = fit(Normal, rand(Normal(\u03bc, \u03c3), N))\n@test isa(d, Normal)\n@test_approx_eq_eps d.\u03bc \u03bc 0.1\n@test_approx_eq_eps d.\u03c3 \u03c3 0.1\n\nimport Distributions.NormalKnownMu, Distributions.NormalKnownSigma\n\nss = suffstats(NormalKnownMu(\u03bc), x)\n@test isa(ss, Distributions.NormalKnownMuStats)\n@test ss.\u03bc == \u03bc\n@test_approx_eq ss.s2 sum((x .- \u03bc).^2)\n@test_approx_eq ss.tw n0\n\nss = suffstats(NormalKnownMu(\u03bc), x, w)\n@test isa(ss, Distributions.NormalKnownMuStats)\n@test ss.\u03bc == \u03bc\n@test_approx_eq ss.s2 dot((x .- \u03bc).^2, w)\n@test_approx_eq ss.tw sum(w)\n\nd = fit_mle(Normal, x; mu=\u03bc)\n@test isa(d, Normal)\n@test d.\u03bc == \u03bc\n@test_approx_eq d.\u03c3 sqrt(mean((x .- d.\u03bc).^2))\n\nd = fit_mle(Normal, x, w; mu=\u03bc)\n@test isa(d, Normal)\n@test d.\u03bc == \u03bc\n@test_approx_eq d.\u03c3 sqrt(dot((x .- d.\u03bc).^2, w) / sum(w))\n\n\nss = suffstats(NormalKnownSigma(\u03c3), x)\n@test isa(ss, Distributions.NormalKnownSigmaStats)\n@test ss.\u03c3 == \u03c3\n@test_approx_eq ss.sx sum(x)\n@test_approx_eq ss.tw n0\n\nss = suffstats(NormalKnownSigma(\u03c3), x, w)\n@test isa(ss, Distributions.NormalKnownSigmaStats)\n@test ss.\u03c3 == \u03c3\n@test_approx_eq ss.sx dot(x, w)\n@test_approx_eq ss.tw sum(w)\n\nd = fit_mle(Normal, x; sigma=\u03c3)\n@test isa(d, Normal)\n@test d.\u03c3 == \u03c3\n@test_approx_eq d.\u03bc mean(x)\n\nd = fit_mle(Normal, x, w; sigma=\u03c3)\n@test isa(d, Normal)\n@test d.\u03c3 == \u03c3\n@test_approx_eq d.\u03bc dot(x, w) / sum(w)\n\n\n# Uniform\n\nx = rand(Uniform(1.2, 5.8), n0)\nd = fit(Uniform, x)\n@test isa(d, Uniform)\n@test 1.2 <= minimum(d) <= maximum(d) <= 5.8\n@test minimum(d) == minimum(x)\n@test maximum(d) == maximum(x)\n\nd = fit(Uniform, rand(Uniform(1.2, 5.8), N))\n@test 1.2 <= minimum(d) <= maximum(d) <= 5.8\n@test_approx_eq_eps minimum(d) 1.2 0.02\n@test_approx_eq_eps maximum(d) 5.8 0.02\n\n\n# Gamma\n\nx = rand(Gamma(3.9, 2.1), n0)\n\nss = suffstats(Gamma, x)\n@test isa(ss, Distributions.GammaStats)\n@test_approx_eq ss.sx sum(x)\n@test_approx_eq ss.slogx sum(log(x))\n@test_approx_eq ss.tw n0\n\nss = suffstats(Gamma, x, w)\n@test isa(ss, Distributions.GammaStats)\n@test_approx_eq ss.sx dot(x, w)\n@test_approx_eq ss.slogx dot(log(x), w)\n@test_approx_eq ss.tw sum(w)\n\nd = fit(Gamma, rand(Gamma(3.9, 2.1), N))\n@test isa(d, Gamma)\n@test_approx_eq_eps shape(d) 3.9 0.1\n@test_approx_eq_eps scale(d) 2.1 0.2\n\n\n# Geometric\n\nx = rand(Geometric(0.3), n0)\n\nss = suffstats(Geometric, x)\n@test isa(ss, Distributions.GeometricStats)\n@test_approx_eq ss.sx sum(x)\n@test_approx_eq ss.tw n0\n\nss = suffstats(Geometric, x, w)\n@test isa(ss, Distributions.GeometricStats)\n@test_approx_eq ss.sx dot(x, w)\n@test_approx_eq ss.tw sum(w)\n\nd = fit(Geometric, x)\n@test isa(d, Geometric)\n@test_approx_eq succprob(d) inv(1. + mean(x))\n\nd = fit(Geometric, x, w)\n@test isa(d, Geometric)\n@test_approx_eq succprob(d) inv(1. + dot(x, w) / sum(w))\n\nd = fit(Geometric, rand(Geometric(0.3), N))\n@test isa(d, Geometric)\n@test_approx_eq_eps succprob(d) 0.3 0.01\n\n\n# Laplace\n\nd = fit(Laplace, rand(Laplace(5.0, 3.0), N))\n@test isa(d, Laplace)\n@test_approx_eq_eps location(d) 5.0 0.1\n@test_approx_eq_eps scale(d) 3.0 0.2\n\n\n# Poisson\n\nx = rand(Poisson(8.2), n0)\n\nss = suffstats(Poisson, x)\n@test isa(ss, Distributions.PoissonStats)\n@test_approx_eq ss.sx sum(x)\n@test_approx_eq ss.tw n0\n\nss = suffstats(Poisson, x, w)\n@test isa(ss, Distributions.PoissonStats)\n@test_approx_eq ss.sx dot(x, w)\n@test_approx_eq ss.tw sum(w)\n\nd = fit(Poisson, x)\n@test isa(d, Poisson)\n@test_approx_eq mean(d) mean(x)\n\nd = fit(Poisson, x, w)\n@test isa(d, Poisson)\n@test_approx_eq mean(d) dot(Float64[xx for xx in x], w) / sum(w)\n\nd = fit(Poisson, rand(Poisson(8.2), N))\n@test isa(d, Poisson)\n@test_approx_eq_eps mean(d) 8.2 0.2\n\n", "meta": {"hexsha": "bf4961c17431b4377a889b1088eb8002f2030f92", "size": 7741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fit.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": "test/fit.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": "test/fit.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.5685131195, "max_line_length": 66, "alphanum_fraction": 0.6810489601, "num_tokens": 2723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7555609492150942}}
{"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\u1d40 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 \u2208 (: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  \u03bc = mean(X, dims=1)\n  Y = X .- \u03bc\n\n  # eigenanalysis of covariance\n  S, S\u207b\u00b9 = eigenmatrices(transform, Y)\n\n  # project the data\n  Z = Y * S\n\n  # table with transformed columns\n  \ud835\udcaf = (; zip(names, eachcol(Z))...)\n  newtable = \ud835\udcaf |> Tables.materializer(table)\n\n  newtable, (\u03bc, S, S\u207b\u00b9)\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  \u03bc, S, S\u207b\u00b9 = cache\n\n  # undo projection\n  Y = Z * S\u207b\u00b9\n\n  # undo centering\n  X = Y .+ \u03bc\n\n  # table with original columns\n  \ud835\udcaf = (; zip(names, eachcol(X))...)\n  \ud835\udcaf |> 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  \u03bc, S, S\u207b\u00b9 = cache\n\n  # center the data\n  Y = X .- \u03bc\n\n  # project the data\n  Z = Y * S\n\n  # table with transformed columns\n  \ud835\udcaf = (; zip(names, eachcol(Z))...)\n  \ud835\udcaf |> Tables.materializer(table)\nend\n\nfunction eigenmatrices(transform, Y)\n  proj = transform.proj\n\n  \u03a3 = cov(Y)\n  \u03bb, V = eigen(\u03a3)\n\n  if proj == :V\n    S   = V\n    S\u207b\u00b9 = transpose(V)\n  elseif proj == :VD\n    \u039b   = Diagonal(sqrt.(\u03bb))\n    S   = V * inv(\u039b)\n    S\u207b\u00b9 = \u039b * transpose(V)\n  elseif proj == :VDV\n    \u039b   = Diagonal(sqrt.(\u03bb))\n    S   = V * inv(\u039b) * transpose(V)\n    S\u207b\u00b9 = V * \u039b * transpose(V)\n  end\n\n  S, S\u207b\u00b9\nend\n\n\"\"\"\n    PCA()\n\nThe PCA transform is a shortcut for\n`ZScore() \u2192 EigenAnalysis(:V)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\"\"\"\nPCA() = ZScore() \u2192 EigenAnalysis(:V)\n\n\"\"\"\n    DRS()\n\nThe DRS transform is a shortcut for\n`ZScore() \u2192 EigenAnalysis(:VD)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\"\"\"\nDRS() = ZScore() \u2192 EigenAnalysis(:VD)\n\n\"\"\"\n    SDS()\n\nThe SDS transform is a shortcut for\n`ZScore() \u2192 EigenAnalysis(:VDV)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\"\"\"\nSDS() = ZScore() \u2192 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": "function spectralClustering(A::Array{Float64,2}, nEigen::Int)\n\n\tD = Diagonal(sum(A, dims=1)[:])\n\tL = D-A\n\tNL = D^(-1/2) * L * D^(-1/2)\n\tvals, vects = eigen(NL)\n\tX = vects[:,1:nEigen]\n\tXX = fill(0.0,size(X))\n\t\n\tfor i in 1:size(X,1)\n\t\tXX[i,:] = X[i,:] ./ sqrt(sum(X[i,:].^2))\n\tend\n\t\n\treturn vals, XX\nend\n", "meta": {"hexsha": "fe198ec579803abc80c2abb5b1e84a9c8da158b2", "size": 302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spectralClustering.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/spectralClustering.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/spectralClustering.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": 18.875, "max_line_length": 61, "alphanum_fraction": 0.5529801325, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.7981867801399695, "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, \u039b_m, M) = (1 + 0.6t_c / x_c + 100t_c^4) * (1.34M^0.18 * cos(\u039b_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 / \u221a(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, \u03c1, M, \u03bc)\n\t# Skin-friction coefficients\n\tRe_c \t\t= reynolds_number.(\u03c1, V, mean_chords, \u03bc)\n\tRe_xtr \t\t= reynolds_number.(\u03c1, V, mean_chords .* x_tr, \u03bc)\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, \u03c1, a_ref = 330., \u03bc = 1.5e-5)\n\t# Chord processing\n\tmean_chords = (fwdsum \u2218 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, \u03c1, M, \u03bc)\nend\n\nprofile_drag_coefficient(wing :: HalfWing, x_tr, V, rho_ref, a_ref, area_ref, \u03bc) = wetted_area_drag(wing, x_tr, V, rho_ref, a_ref, \u03bc) / area_ref\nprofile_drag_coefficient(wing :: Wing, x_tr, V, rho_ref, a_ref, area_ref, \u03bc) = profile_drag_coefficient(left(wing), x_tr, V, rho_ref, a_ref, area_ref, \u03bc) + profile_drag_coefficient(right(wing), x_tr, V, rho_ref, a_ref, area_ref, \u03bc)\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": "include(\"smear_FD.jl\")\ninclude(\"calc_entropy.jl\")\n\nfunction test_main(kT::Float64)\n    Nstates = 5\n    ev = Array{Float64}(Nstates)\n    ev = [-2.4, -1.0, -0.5, -0.2, -0.19]\n    efermi = 0.5*(ev[3] + ev[4])\n    println(\"\\nkT = \", kT)\n    for spinpol in [true,false]\n        println(\"\\nspinpol = \", spinpol)\n        Focc = smear_FD(ev, efermi, kT, is_spinpol=spinpol)\n        for ist = 1:Nstates\n            @printf(\"%18.10f %18.10f\\n\", ev[ist], Focc[ist])\n        end\n        @printf(\"sum(Focc) = %18.10f\\n\", sum(Focc))\n        @printf(\"Entropy (-TS) = %18.10f\\n\", calc_entropy(Focc, kT, is_spinpol=spinpol))\n    end\nend\n\n\ntest_main(0.001)\ntest_main(0.01)\ntest_main(0.1)\n", "meta": {"hexsha": "6a8b68bbf0a1f5780dcbf861478e469d597e4b9f", "size": 670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PW/dft_02/test_smearFD.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/test_smearFD.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/test_smearFD.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": 26.8, "max_line_length": 88, "alphanum_fraction": 0.5731343284, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7555547633811388}}
{"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\u2032 = 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\u1d40 J\n# S_j`. After applying a symop defined by (R, T), the bond b=(i,j) maps to a\n# transformed bond b\u2032=(i\u2032,j\u2032). This new bond must carry an exchange interaction\n# of the form `S_{i\u2032}\u1d40 J\u2032 S_{j\u2032}`, where J\u2032 is related to J, as we will now\n# show. Besides mapping the atom j to a new position j\u2032, the symop also\n# transforms its spin vector from `S_j` to `S\u2032_{j\u2032} = R S_j`. Similarly, `S_i\u1d40`\n# maps to `S\u2032_{i\u2032}\u1d40 = S_i\u1d40 R\u1d40`. The energy along a bond, however, is invariant\n# under the symmetry transformation, so we require `S_i\u1d40 J S_j = S\u2032_{i\u2032}\u1d40 J\u2032\n# S\u2032_{j\u2032}`, or\n#\n#   `S_i\u1d40 J S_j = S_i\u1d40 R\u1d40 J\u2032 R S_j`.\n#\n# This equation must be valid for arbitrary `S_i` and `S_j`, which implies `J =\n# R\u1d40 J\u2032 R`, or equivalently,\n#\n#   J\u2032 = R J R\u1d40\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\u2032\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\u1d40   or   (2)  J\u1d40 = R J R\u1d40\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\u1d40 - J` or `F J = R J\n# R\u1d40 - J\u1d40`. Here, we are viewing the 3\u00d73 matrix J as a flattened 9-dimensional\n# vector, and F as a 9x9 matrix. In the first case, `F = R\u2297R - 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 \u03a3 V\u1d40\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\u1d40\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]/\u221a2,\n         [0 0 1\n          0 0 0\n          1 0 0]/\u221a2,\n         [0 0 0\n          0 0 1\n          0 1 0]/\u221a2,]\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]/\u221a2,\n         [ 0  0 -1\n           0  0  0\n           1  0  0]/\u221a2,\n         [ 0  0  0\n           0  0  1\n           0 -1  0]/\u221a2]\n    SMatrix{9, 3, Float64}(hcat(reshape.(b, 9)...))\nend\n\n@assert sym_basis * sym_basis' + asym_basis * asym_basis' \u2248 I\n\n\n# Given an m\u00d7n 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\u00d73`` 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\u1d40 = J` or `R J R\u1d40\n    # = J\u1d40` 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 \u00b1c 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": "using CSDP\n\n#=\n# Example copied from `example/example.c`\n   An example showing how to call the easy_sdp() interface to CSDP.  In\n   this example, we solve the problem\n\n      max tr(C*X)\n          tr(A1*X)=1\n          tr(A2*X)=2\n          X >= 0       (X is PSD)\n\n   where\n\n    C=[2 1\n       1 2\n           3 0 1\n           0 2 0\n           1 0 3\n                 0\n                   0]\n\n   A1=[3 1\n       1 3\n           0 0 0\n           0 0 0\n           0 0 0\n                 1\n                   0]\n\n   A2=[0 0\n       0 0\n           3 0 1\n           0 4 0\n           1 0 5\n                 0\n                   1]\n\n  Notice that all of the matrices have block diagonal structure.  The first\n  block is of size 2x2.  The second block is of size 3x3.  The third block\n  is a diagonal block of size 2.\n\n=#\n\nC = BlockMatrix(\n   [2 1\n    1 2],\n        [3 0 1\n         0 2 0\n         1 0 3],\n      Diagonal([0,\n                  0]))\n\nb = [1.0, 2.0]\n\nA1 = ConstraintMatrix(1,\n   [3 1\n    1 3],\n          [0 0 0\n           0 0 0\n           0 0 0],\n       Diagonal([1,\n                   0]))\n\nA2 = ConstraintMatrix(2,\n      [0 0\n       0 0],\n          [3 0 1\n           0 4 0\n           1 0 5],\n       Diagonal([0,\n                   1]))\n\nconstraints = [A.csdp for A in [A1, A2]]\n\nCSDP.write_prob(\"prob.dat-s\", C, b, constraints)\n\nX, y, Z = initsoln(C, b, constraints)\n\npobj, dobj = easy_sdp(C, b, constraints, X, y, Z)\n\n# Fails on Windows\n#CSDP.write_sol(\"prob.sol\", X, y, Z)\n", "meta": {"hexsha": "ae84c669b22871929c35a703ee860fe6a97e4e81", "size": 1474, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example.jl", "max_stars_repo_name": "blegat/CSDP.jl", "max_stars_repo_head_hexsha": "2ba112eca05c32fe8246d262e35a9ed3ea9fb57b", "max_stars_repo_licenses": ["MIT"], "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": "blegat/CSDP.jl", "max_issues_repo_head_hexsha": "2ba112eca05c32fe8246d262e35a9ed3ea9fb57b", "max_issues_repo_licenses": ["MIT"], "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": "blegat/CSDP.jl", "max_forks_repo_head_hexsha": "2ba112eca05c32fe8246d262e35a9ed3ea9fb57b", "max_forks_repo_licenses": ["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.5476190476, "max_line_length": 75, "alphanum_fraction": 0.4199457259, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7555547602900445}}
{"text": "using EffectiveWaves\n\nusing Plots\n# unicodeplots() # alternative plot backend\nheight=500\npyplot(linewidth=3, size=(2.0*height,height))\n\n# for fixed total volfrac fraction\nmedium = Medium(\u03c1=3200.0,c = 2595.0)\n\u03c9s = 2.0*pi*LinRange(1.0e1,1.0e7,100)\n\nvolfrac = 0.12\nr1 = 30.0e-8\nr2 = 2*30.0e-6\n\nsp1 = Specie(\u03c1=2329.,r=r1,c=8433.,volfrac = 0.06)\nsp2 = Specie(\u03c1=2329.,r=r2,c=8433.,volfrac = volfrac-0.06)\n\nvol = pi*sp1.num_density*sp1.r^2\n\nrhoeff =  medium.\u03c1*(medium.\u03c1 + sp1.\u03c1 - vol*(medium.\u03c1 - sp1.\u03c1))/\n(medium.\u03c1 + sp1.\u03c1 + vol*(medium.\u03c1 - sp1.\u03c1))\n\n# rhoeff =  medium.\u03c1*(1.0-vol) + vol*sp1.\u03c1\n# rhoeff =  medium.\u03c1*(1 + volfrac)/(1 - volfrac)\n\nkTs = [ wavenumber_low_volfrac(\u03c9, medium, [sp1,sp2]) for \u03c9 in \u03c9s]\nkTaprx =[ two_species_approx_wavenumber(\u03c9, medium, [sp1,sp2]) for \u03c9 in \u03c9s]\n\nkTSs =[ wavenumber_low_volfrac(\u03c9, medium, [sp1]) for \u03c9 in \u03c9s]\nkTLs = [\n  begin\n    mS = Medium(\u03c1=rhoeff, c= \u03c9s[i]/kTSs[i])\n    wavenumber_low_volfrac(\u03c9s[i], mS, [sp2])\n  end\nfor i in eachindex(\u03c9s)];\n\n# speed_arr = [ [\u03c9s./real(kTs)], [0.029 .+ \u03c9s./real(kTLs)]]\nspeed_arr = [ \u03c9s./real(kTs), \u03c9s./real(kTLs), \u03c9s./real(kTaprx)]\natten_arr = imag([kTs,kTLs, kTaprx])\n\nlabs = reshape([\"kT\",\"kTL\", \"kTaprx\"] ,1, 3);\np1 = plot(r1.*(\u03c9s./real(medium.c))/(2pi), speed_arr, labels=labs, xlabel=\"a/\u03bb\", ylabel=\"wave speed\");\np2 = plot(r1.*(\u03c9s./real(medium.c))/(2pi), atten_arr, labels=labs, xlabel=\"a/\u03bb\", ylabel=\"attenuation\");\nplot(p1,p2)\ngui()\n\nspeed_arr = [abs.(1 .- real(kTLs)./real(kTs))]\np1 = plot(r1.*(\u03c9s./real(medium.c))/(2pi), speed_arr, labels=labs, xlabel=\"a/\u03bb\", ylabel=\"relative wave speed\");\n", "meta": {"hexsha": "46ca19ad70dae33cf3611ad2a7de4096004dd83b", "size": 1567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/compare_two/compare_one_species.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": "docs/src/examples/compare_two/compare_one_species.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": "docs/src/examples/compare_two/compare_one_species.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": 31.34, "max_line_length": 110, "alphanum_fraction": 0.6496490108, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7555547568738036}}
{"text": "using Test, DiffEqOperators, SpecialFunctions\n\n@testset \"None BC DerivativeOperator\" begin\n    N = 10\n    d_order = 1\n    approx_order = 2\n    A = DerivativeOperator{Float64}(d_order,approx_order,1.0,N,:None,:None)\n    Amat = convert(Array,A)\n\n    @test Amat[1,1:3] \u2248 [-1.5, 2.0, -0.5]\n    for row = 2:N-1\n        @test Amat[row,row-1:row+1] \u2248 [-0.5, 0.0, 0.5]\n    end\n    @test Amat[end,end-2:end] \u2248 [0.5, -2.0, 1.5]\n\n    d_order = 2\n    A = DerivativeOperator{Float64}(d_order,approx_order,1.0,N,:None,:None)\n    Amat = convert(Array,A)\n\n    @test Amat[1,1:4] \u2248 [2.0, -5.0, 4.0, -1.0]\n    for row = 2:N-1\n        @test Amat[row,row-1:row+1] \u2248 [1.0, -2.0, 1.0]\n    end\n    @test Amat[end,end-3:end] \u2248 [-1.0, 4.0, -5.0, 2.0]\n\n    N = 10\n    d_order = 1\n    approx_order = 3\n    A = DerivativeOperator{Float64}(d_order,approx_order,1.0,N,:None,:None)\n    Amat = convert(Array,A)\n\n    @test Amat[1,1:4] \u2248 [-11/6, 3, -3/2, 1/3]\n    for row = 3:N-2\n        @test Amat[row,row-1:row+1] \u2248 [-1/2, 0, 1/2]\n    end\n    @test Amat[end,end-3:end] \u2248 [-1/3, 3/2, -3, 11/6]\n\nend\n\n@testset \"None BC FiniteDifference Operator\" begin\n    N = 10\n    d_order = 1\n    approx_order = 2\n    A = FiniteDifference{Float64}(d_order,approx_order,ones(N-1),N,:None,:None)\n    Amat = convert(Array,A)\n\n    @test Amat[1,1:3] \u2248 [-1.5, 2.0, -0.5]\n    for row = 2:N-1\n        @test Amat[row,row-1:row+1] \u2248 [-0.5, 0.0, 0.5]\n    end\n    @test Amat[end,end-2:end] \u2248 [0.5, -2.0, 1.5]\n\n    d_order = 2\n    A = FiniteDifference{Float64}(d_order,approx_order,ones(N-1),N,:None,:None)\n    Amat = convert(Array,A)\n\n    @test Amat[1,1:4] \u2248 [2.0, -5.0, 4.0, -1.0]\n    for row = 2:N-1\n        @test Amat[row,row-1:row+1] \u2248 [1.0, -2.0, 1.0]\n    end\n    @test Amat[end,end-3:end] \u2248 [-1.0, 4.0, -5.0, 2.0]\n\n    N = 10\n    d_order = 1\n    approx_order = 3\n    A = FiniteDifference{Float64}(d_order,approx_order,ones(N-1),N,:None,:None)\n    Amat = convert(Array,A)\n\n    @test Amat[1,1:4] \u2248 [-11/6, 3, -3/2, 1/3]\n    for row = 3:N-2\n        @test Amat[row,row-1:row+1] \u2248 [-1/2, 0, 1/2]\n    end\n    @test Amat[end,end-3:end] \u2248 [-1/3, 3/2, -3, 11/6]\n\nend\n\n\n@testset \"FiniteDifference Operator sin(x)==d/dx^4 sin(x)\" begin\n    N = 10\n    n = 1000\n    x = erf.(range(-2,stop=2,length=n))*2\u03c0\n    x .+=abs(x[1])\n    dx = diff(x)\n\n    A = DiffEqOperators.FiniteDifference{Float64}(4,4,dx,length(x),:None,:None)\n    boundary_points = A.boundary_point_count\n\n    y = @. sin(x)+2 #avoid 0.0\n    res = A*y\n    @test res[boundary_points[1] .+ 1: N - boundary_points[2]] .+ 2.0 \u2248 y[boundary_points[1] .+ 1: N - boundary_points[2]] atol=10.0^-1;\n\nend\n", "meta": {"hexsha": "5438321b35efbe6993ee51f08397f8b66f13be4b", "size": 2587, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/none.jl", "max_stars_repo_name": "asinghvi17/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "0f73d529b94a4206929d6c1a99a20236054545b2", "max_stars_repo_licenses": ["MIT"], "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/none.jl", "max_issues_repo_name": "asinghvi17/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "0f73d529b94a4206929d6c1a99a20236054545b2", "max_issues_repo_licenses": ["MIT"], "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/none.jl", "max_forks_repo_name": "asinghvi17/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "0f73d529b94a4206929d6c1a99a20236054545b2", "max_forks_repo_licenses": ["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.8172043011, "max_line_length": 136, "alphanum_fraction": 0.5628140704, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7555547527660758}}
{"text": "######### StanSample example  ###########\n\nusing StanSample, Test\n\nbernoulli_model = \"\ndata { \n  int<lower=1> N; \n  array[N] int<lower=0,upper=1> y;\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 = [\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]),\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 0, 1, 0, 0, 0, 0, 1]),\n  Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 1, 0]),\n  Dict(\"N\" => 10, \"y\" => [0, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n]\n\nsm = SampleModel(\"bernoulli\", bernoulli_model)\nrc = stan_sample(sm; data=bernoulli_data, delta=0.85, num_threads=1)\nif success(rc)\n\n  # Fetch the same output in the `sdf` ChainDataFrame\n  sdf = read_summary(sm)\n\n  @test sdf[sdf.parameters .== :theta, :mean][1] \u2248 0.33 rtol=0.05\n  \nend", "meta": {"hexsha": "a109b3d456188c389b7e34626332e927e880e0e2", "size": 796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_basic_runs/test_bernoulli_array_dict_1.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": "test/test_basic_runs/test_bernoulli_array_dict_1.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": "test/test_basic_runs/test_bernoulli_array_dict_1.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": 22.7428571429, "max_line_length": 68, "alphanum_fraction": 0.5477386935, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7555513308303135}}
{"text": "# assert file to test polynomial implementation\nusing Base.Test\nusing Polynomials\n\npNULL = Poly(Float32[])\np0 = Poly([0])\np1 = Poly([1,0,0,0,0,0,0,0,0,0,0,0,0,0])\np2 = Poly([1,1,0,0])\np3 = Poly([1,2,1,0,0,0,0])\np4 = Poly([1,3,3,1,0,0])\np5 = Poly([1,4,6,4,1,0,0,0,0,0,0,0,0,0,0,0,0,0])\npN = Poly([276,3,87,15,24,0])\npR = Poly([3//4, -2//1, 1//1])\np1000 = Poly(randn(1000))\n\n@test length(pNULL) == 0\n@test length(p1000) == 1000\nsprint(show, p1000)\nsprint(show, pNULL)\n\n@test p3 == Poly([1,2,1])\n@test pN*10 == Poly([2760, 30, 870, 150, 240])\n@test pN/10 == Poly([27.6, 0.3, 8.7, 1.5, 2.4])\n@test 10*pNULL + pN == pN\n@test 10*p0 + pN == pN\n@test p5 + 2*p1 == Poly([3,4,6,4,1])\n@test 10*pNULL - pN == -pN\n@test p0 - pN == -pN\n@test p5 - 2*p1 == Poly([-1,4,6,4,1])\n@test p2*p2*p2 == p4\n@test p2^4 == p5\n@test pNULL^3 == pNULL\n@test pNULL*pNULL == pNULL\n\n@test polyval(pN, -.125) == 276.9609375\n@test polyval(pNULL, 10) == 0\n@test polyval(p0, -10) == 0\n@test polyval(poly([1//2, 3//2]), 1//2) == 0//1\n@test polyder(polyint(pN)) == pN\n@test polyder(pR) == Poly([-2//1,2//1])\n@test polyint(pNULL,1) == p1\n@test polyint(Poly(Rational[1,2,3])) == Poly(Rational[0, 1, 1, 1])\n@test polyder(p3) == Poly([2,2])\n@test polyder(p1) == polyder(p0) == polyder(pNULL) == pNULL\n\n@test poly([-1,-1]) == p3\n@test roots(p0)==roots(p1)==roots(pNULL)==[] \n@test roots(p2) == [-1]\na_roots = copy(pN.a)\n@test all(abs(sort(roots(poly(a_roots))) - sort(a_roots)) .< 1e6)\n@test length(roots(p5)) == 4\n@test roots(pNULL) == []\n@test roots(pR) == [1//2, 3//2]\n\n@test pNULL + 2 == p0 + 2 == 2 + p0 == Poly([2])\n@test p2 - 2 == -2 + p2 == Poly([-1,1])\n@test 2 - p2 == Poly([1,-1])\n\np0 = Poly([0])\np1 = Poly([1])\np2 = Poly([5, 6, -3, 2 ,4])\np3 = Poly([7, -3, 2, 6])\np4 = p2 * p3\n@test divrem(p4, p2) == (p3, zero(p3))\n@test p3%p2 == p3\n@test all((abs((p2/p3 - Poly([1/9,2/3])).a)) .< eps())\n@test divrem(p0,p1) == (p0,p0)\n@test divrem(p1,p1) == (p1,p0)\n@test divrem(p2,p2) == (p1,p0)\n@test divrem(pR, pR) == (one(pR), zero(pR))\n@test_throws p1/p0\n@test_throws divrem(p0,p0)\n\n#Tests for multivariable support\npX = Poly([1, 2, 3, 4, 5])\npS1 = Poly([1, 2, 3, 4, 5], \"s\")\npS2 = Poly([1, 2, 3, 4, 5], 's')\npS3 = Poly([1, 2, 3, 4, 5], :s)\n@test pX != pS1\n@test pS1 == pS2\n@test pS1 == pS3\n@test_throws pS1 + pX\n@test_throws pS1 - pX\n@test_throws pS1 * pX\n@test_throws pS1 / pX\n@test_throws pS1 % pX\n", "meta": {"hexsha": "98dc4c764aa76b58a09dea6cc6cf60449feaa7e6", "size": 2357, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tests.jl", "max_stars_repo_name": "tkelman/Polynomials.jl", "max_stars_repo_head_hexsha": "cb9e6a392707c6abcfcc08bb95d582e3458d6d58", "max_stars_repo_licenses": ["MIT"], "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.jl", "max_issues_repo_name": "tkelman/Polynomials.jl", "max_issues_repo_head_hexsha": "cb9e6a392707c6abcfcc08bb95d582e3458d6d58", "max_issues_repo_licenses": ["MIT"], "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/tests.jl", "max_forks_repo_name": "tkelman/Polynomials.jl", "max_forks_repo_head_hexsha": "cb9e6a392707c6abcfcc08bb95d582e3458d6d58", "max_forks_repo_licenses": ["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.091954023, "max_line_length": 66, "alphanum_fraction": 0.5697921086, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7555196366911692}}
{"text": "function noisy_circle_data(N, \u03c3)\n    r = 1 .+ \u03c3*randn(1,N)\n    \u03b8 = rand(Uniform(0, 2\u03c0), (1,N))\n\n    rcos\u03b8 = r .* cos.(\u03b8)\n    rsin\u03b8 = r .* sin.(\u03b8)\n\n    data = [rcos\u03b8; rsin\u03b8]\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": "using QuantizedStateSystems\nusing LinearAlgebra\nusing Test\n\n@testset \"QSS1 for scalar systems with no input\" begin\n    @test begin\n        a = -1.0\n        f = (x,u,t) -> a*x\n        x\u2080 = 10.0\n        tspan = (0.0,1.0)\n        \u0394q = 0.01\n        txarray,xarray,tqarray,qarray = qss1(f,x\u2080,tspan,\u0394q,[],[])\n        xtrue(t) = x\u2080*exp(a*t)\n        xtruearray = xtrue.(txarray)\n        relerror = (xarray-xtruearray)./xtruearray\n        norm(relerror)<0.01\n    end\nend\n\n@testset \"QSS1 for scalar systems with (control) inputs\" begin\n    @test begin\n        f = (x,u,t) -> -1.0*x + u\n        x\u2080 = 10.0\n        tspan = (0.0,5.0)\n        tuarray = [1.76]\n        uarray = [10.0]\n        \u0394q = 0.01\n        heaviside(t,\u03c4) = t>=\u03c4 ? 1.0 : 0.0\n        xtrue(t) = x\u2080*exp(-t) + 10.0*(heaviside(t,1.76)*(1.0-exp(-t+1.76)))\n        (txarray,xarray,tqarray,qarray) = qss1(f,x\u2080,tspan,\u0394q,tuarray,uarray)\n        xtruearray = xtrue.(txarray)\n        relerror = (xarray-xtruearray)./xtruearray\n        norm(relerror)<0.05\n    end\nend\n", "meta": {"hexsha": "aaefacd82a71734118015cee19e1db11bc64fb0e", "size": 1010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "hurak/QuantizedStateSystems", "max_stars_repo_head_hexsha": "ccd290cc5dc719aae3c85109023a29c23e8ad7c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-30T08:47:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T08:47:13.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "hurak/QuantizedStateSystems", "max_issues_repo_head_hexsha": "ccd290cc5dc719aae3c85109023a29c23e8ad7c0", "max_issues_repo_licenses": ["MIT"], "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": "hurak/QuantizedStateSystems", "max_forks_repo_head_hexsha": "ccd290cc5dc719aae3c85109023a29c23e8ad7c0", "max_forks_repo_licenses": ["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.0555555556, "max_line_length": 76, "alphanum_fraction": 0.5455445545, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7555117276190865}}
{"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) = \"\u300e\"\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": "# Column sampling sketch of a matrix\n# LinearTimeSVD - Drineas, et  al. \"Fast monte carlo algorithms for matrices ii: computing a low rank approximation to a matrix\", SIAM Journal of Computing, 2006.\n#\n# Danny Perry (dperry@cs.utah.edu)\n# April 2015\n\nusing Debug\n\n@debug function LinearTimeSVD(A, num_cols)\n\tn = size(A,1)\n\td = size(A,2)\n\tc = num_cols\n\n\tC = zeros(c,d)\n\tnorm_est = 0\n\tfor i=1:n\n\t\tnormi = norm(A[i,:])^2\n\t\tnorm_est += normi\n\t\tpc = normi/norm_est\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\tU,S2,V = svd(C*C')\n\tS = sqrt(S2) # S are the approximate singular values of A\n\tH = (C' * V' * pinv(diagm(S)))  # H is an approximate right singular vector of A (left singular vector of A').\n\treturn H,S\nend\n\n# same but using leverage scores\n@debug function LeverageLinearTimeSVD(A, Uk,k, num_cols)\n\tn = size(A,1)\n\td = size(A,2)\n\tc = num_cols\n\n\trow_lev = sum(Uk.^2,2) ./ k\n\n\tC = zeros(c,d)\n\tfor i=1:n\n\t\tpc = row_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\tU,S2,V = svd(C*C')\n\tS = sqrt(S2) # S are the approximate singular values of A\n\tH = (C' * V' * pinv(diagm(S)))  # H is an approximate right singular vector of A (left singular vector of A').\n\treturn H,S\nend\n\n\n", "meta": {"hexsha": "3005977ec29327420096f0a689e82ced8d2af38b", "size": 1287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ColumnSampling.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/ColumnSampling.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/ColumnSampling.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": 22.1896551724, "max_line_length": 162, "alphanum_fraction": 0.6309246309, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7555117254776857}}
{"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\u2081 = polygon.points[1]\n    area_polygon_unit_sphere = 0.0\n    for point\u2082 in polygon.points[2:end]\n        n_intersections\u1d62 = length(intersection_points(Arc(polygon.inside_point, \n        midpoint(point\u2081, point\u2082)), polygon))\n        isodd(n_intersections\u1d62) ? area_polygon_unit_sphere += \n        area(polygon.inside_point, point\u2081, point\u2082) : area_polygon_unit_sphere -= \n        area(polygon.inside_point, point\u2081, point\u2082)\n        \n        point\u2081 = point\u2082\n    end\n    return area_polygon_unit_sphere * radius^2\nend\n\n\"\"\"\n    area(angular_distance\u2081\u2082::Float64, angular_distance\u2082\u2083::Float64, angular_distance\u2081\u2083::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\u2081\u2082::Float64, angular_distance\u2082\u2083::Float64, angular_distance\u2081\u2083::Float64,\n    radius::Float64=1.0)\n    return deg2rad(spherical_excess(angular_distance\u2081\u2082, angular_distance\u2081\u2083, angular_distance\u2082\u2083))*radius^2\nend\n\n\"\"\"\n    area(point\u2081::Point, point\u2082::Point, point\u2083::Point, radius::Float64=1.0)\n\nReturn the area of the spherical triangle 123 based on the points point\u2081 - point\u2082 - point\u2083. Without given radius\na unit sphere is assumed.\n\nSource: mathworld.wolfram.com/SphericalTriangle.html\n\"\"\"\narea(point\u2081::Point, point\u2082::Point, point\u2083::Point, radius::Float64=1.0) = \narea(angular_distance(point\u2081, point\u2082), angular_distance(point\u2082, point\u2083), angular_distance(point\u2083, point\u2081),\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\u03a3 = DefiniteIntegral(d)\n\u03f5 = 2.0\nK = LowRankFun((x,y)->-1./(x+y+2\u03f5).^2+12(x+\u03f5)./(x+y+2\u03f5).^3-12(x+\u03f5).^2./(x+y+2\u03f5).^4,d2)\nL = H2[w] + \u03a3[K*(w/\u03c0)]\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": "# SPDX-License-Identifier: MIT\n\n@testset \"logaddexp\" begin\n    @test (@inferred MarkovModels.Semirings.logaddexp(2.0, 3.0)) \u2248 log(exp(2.0) + exp(3.0))\n    @test (@inferred MarkovModels.Semirings.logaddexp(10002.0, 10003.0)) \u2248\n        10000 + MarkovModels.Semirings.logaddexp(2.0, 3.0)\nend\n\n", "meta": {"hexsha": "b6e0c8a7d06a87b0c7ced69665dbc8b5fbaa55f9", "size": 290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_semirings.jl", "max_stars_repo_name": "MartinKocour/MarkovModels.jl", "max_stars_repo_head_hexsha": "d0d70e303e40941dbc5ff900905ea19d63584f3c", "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": "test/test_semirings.jl", "max_issues_repo_name": "MartinKocour/MarkovModels.jl", "max_issues_repo_head_hexsha": "d0d70e303e40941dbc5ff900905ea19d63584f3c", "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": "test/test_semirings.jl", "max_forks_repo_name": "BUTSpeechFIT/ProbabilisticFSMs", "max_forks_repo_head_hexsha": "d20cef8eca0ed43b6e340349da0c3f1939ecf347", "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": 32.2222222222, "max_line_length": 91, "alphanum_fraction": 0.6896551724, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.7931059438487662, "lm_q1q2_score": 0.7554921998037931}}
{"text": "\"\"\"This function returns the successor of any given positive integer.\"\"\"\r\nfunction succ(n :: Int64) :: Int64\r\n    return n + 1;\r\nend;\r\n\r\n\r\n\"\"\"This function implements the fast exponentiation algorithm\"\"\"\r\nfunction fast_expo(n :: Int64, exp :: Int64) :: Int64\r\n    if expo == 0\r\n        return n\r\n    elseif expo % 2 == 0\r\n        let res = fast_expo(n, div(exp, 2))\r\n        return (res * res)\r\n    else\r\n        let res = fast_expo(n, div(exp, 2))\r\n        return (res * res * n)\r\n    end\r\nend\r\n\r\n", "meta": {"hexsha": "217ad17441b03b488883a0338d1df639b4ffa4b8", "size": 498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "arithlib.jl", "max_stars_repo_name": "Sup3Legacy/pjulia-packages", "max_stars_repo_head_hexsha": "e11e9d9823dd0654c752b25693e947c5ea3bcae2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-24T09:20:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T10:31:55.000Z", "max_issues_repo_path": "arithlib.jl", "max_issues_repo_name": "Sup3Legacy/pjulia-packages", "max_issues_repo_head_hexsha": "e11e9d9823dd0654c752b25693e947c5ea3bcae2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arithlib.jl", "max_forks_repo_name": "Sup3Legacy/pjulia-packages", "max_forks_repo_head_hexsha": "e11e9d9823dd0654c752b25693e947c5ea3bcae2", "max_forks_repo_licenses": ["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": 73, "alphanum_fraction": 0.5722891566, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7554667783209982}}
{"text": "@testset \"LaguerrePolynomial\" begin\n    @testset \"LaguerrePolynomial\" begin\n        # test construction of LaguerrePolynomial\n        orders = [0,2,3]\n        coeffs = [1.0, 2, 0.5]\n        L = LaguerrePolynomial(orders, coeffs)\n        @test L.orders == orders\n        @test all(isapprox.(coeffs, L.coeffs))\n        # test single Laguerre Polynomial\n        L = LaguerrePolynomial(2, 1 // 2)\n        @test L.orders == [2]\n        @test L.coeffs == [1 // 2]\n\n        # Laguerre Polynomial L3 with coefficient 1.\n        L = LaguerrePolynomial(3)\n        @test L.orders == [3]\n        @test L.coeffs == [1]\n        # test throw\n        @test_throws DimensionMismatch LaguerrePolynomial([1,2], [2,3,2])\n        @test_throws DomainError LaguerrePolynomial(-2, 1)\n        # test string representation\n        L = LaguerrePolynomial([2,3], [1,2])\n        st = Laguerre.lashow(L)\n        @test st == \"(1)L2 + (2)L3\"\n    end\n\n\n    @testset \"LaguerrePolynomial addition\" begin\n        L1 = LaguerrePolynomial(2, 1 // 2)\n        L2 = LaguerrePolynomial(3, 1.0)\n        L = L1 + L2\n        @test typeof(L) == LaguerrePolynomial{typeof(1.0)}\n        @test L.orders == [2, 3]\n        @test all(isapprox.(L.coeffs, [1 / 2, 1.0]))\n        # \n        L1 = LaguerrePolynomial(2, 1)\n        L2 = LaguerrePolynomial(2, 1 // 3)\n        L = L1 + L2\n        @test typeof(L) == LaguerrePolynomial{typeof(1 // 3)}\n        @test L.orders == [2]\n        @test L.coeffs == [1 + 1 // 3]\n        \n        # test subtraction\n        L = L1 - L2\n        @test L.orders == [2]\n        @test L.coeffs == [1 - 1 // 3]\n        \n    end\n\n\n\n    @testset \"LaguerrePolynomial * number\" begin\n        orders = [0,2,3]\n        coeffs = [1, 2, 2]\n        L1 = LaguerrePolynomial(orders, coeffs)\n        L2 = L1 * 3\n        # multiplication by a number\n        @test L2.orders == [0,2,3]\n        @test L2.coeffs == 3 * coeffs\n        # division by a number\n        @test_throws ErrorException L1 / 0\n        L3 = L1 / 2\n        @test L3.orders == L1.orders\n        @test L3.coeffs == L1.coeffs / 2\n    end\n\n    @testset \"LaguerrePolynomials product\" begin\n        k = 5\n        L2 = LaguerrePolynomial(2, 1.0)\n        Lk = LaguerrePolynomial(k, 1.0)\n        L = L2 * Lk\n        # L2Lk = k(k-1)/2 L_{k-2} -2k(k-1)L_{k-1}\n        #   +(3k^2-k)L_k -2k(k+1)L_{k+1} \n        #   (k+1)(k+2)/2 L_{k+2}\n        res = k * (k - 1) / 2 * LaguerrePolynomial(k - 2)  -\n        2 * k * (k - 1) * LaguerrePolynomial(k - 1) +\n        (3 * k^2 - k) * LaguerrePolynomial(k) -\n        2 * k * (k + 1) * LaguerrePolynomial(k + 1) +\n        (k + 1) * (k + 2) / 2 * LaguerrePolynomial(k + 2)\n        @test L == res\n\n        # L1Lk = k L_{k-1} -2k L_k +(k+1) L_{k+1}\n        L1 = LaguerrePolynomial(1, 1.0)\n        Lk = LaguerrePolynomial(k, 1.0)\n        L = L1 * Lk\n        res = k * LaguerrePolynomial(k - 1) - 2 * k * LaguerrePolynomial(k) + (k + 1) * LaguerrePolynomial(k + 1)\n        @test L ==  res\n        @test Lk * LaguerrePolynomial(0) == Lk\n    end\nend", "meta": {"hexsha": "db0c59d5a197ca8806bc67435bc9548a20782d1b", "size": 2998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_lpoly.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": "test/test_lpoly.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": "test/test_lpoly.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": 33.3111111111, "max_line_length": 113, "alphanum_fraction": 0.5143428953, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7554667680403976}}
{"text": "n = 10 # rand(1:10)\nA = ones(Float64, n, n)\n@test matrixdepot(\"circul\", ones(Float64,n)) \u2248 A\n\nx = [1:n;];\nA = matrixdepot(\"circul\", x)\n# test symmetry\n@test A + A' == (A + A')'\nB = matrixdepot(\"circul\", n)\nC = matrixdepot(\"circul\", [1:n;], n)\n@test B \u2248 C\n\nprintln(\"'circul' passed test...\" )\n", "meta": {"hexsha": "9d4a2f4bfe299d5d7d951ae366183b94024a19c3", "size": 292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_circul.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_circul.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_circul.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 20.8571428571, "max_line_length": 48, "alphanum_fraction": 0.5787671233, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7554667676601404}}
{"text": "# sort an array - aplying a function to the sort process\na1 = [1, 2, 0, -2, 7, 3, -11, 12, -43]\nres = sort(a1, by=abs) # sort on the basis of the elements absolute value ...\nprintln(\"$a1  / $res\")\n\n# is this array sorted\na2 = [1, 3, 6, 3]\nprintln(issorted(a1))\n\na3 = [(1, 2), (2, 4), (3, 1), (5, 2)]\nprintln(issorted(a3, by=x -> x[1])) # is this array sorted on the basis of the lambda function provided - get the first element of each tuple\n\n# sorting custom types (structs)\nstruct Rect\n    length::Int\n    width::Int\nend\n\na4 = [Rect(12, 22), Rect(10, 18), Rect(7, 12), Rect(9, 30)]\n\n# create a custom sort function\nfunction comparearea(r1::Rect, r2::Rect)\n    area1 = r1.length * r1.width\n    area2 = r2.length * r2.width\n\n    return area1 < area2\nend\n\nsort!(a4, lt=comparearea) # sort 'in place', provide a 'less than' function (lt)\nprintln(a4)", "meta": {"hexsha": "41120753ba9fb962103b0bfe25e377ee531801b9", "size": 847, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sorting.jl", "max_stars_repo_name": "rpillar/JuliaExamples", "max_stars_repo_head_hexsha": "261c629de45ed573ae6c3888f21b88e1238d6954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sorting.jl", "max_issues_repo_name": "rpillar/JuliaExamples", "max_issues_repo_head_hexsha": "261c629de45ed573ae6c3888f21b88e1238d6954", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "rpillar/JuliaExamples", "max_forks_repo_head_hexsha": "261c629de45ed573ae6c3888f21b88e1238d6954", "max_forks_repo_licenses": ["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.2333333333, "max_line_length": 141, "alphanum_fraction": 0.6434474616, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7554667669729453}}
{"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\u00f72)\n    else\n        return p*(p*p)^((n-1)\u00f72)\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\u0394t = 86400.0*365u\"s\"\n\u03bc = 398600.4418u\"km^3/s^2\"\nrv0 = ArrayPartition(r0,v0)\n\nfunction f(dy, y, \u03bc, t)\n    r = norm(y.x[1])\n    dy.x[1] .= y.x[2]\n    dy.x[2] .= -\u03bc .* y.x[1] / r^3\nend\n\nprob = ODEProblem(f,rv0,(0.0u\"s\",1.0u\"s\"),\u03bc)\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": "# Tests for partial information decomposition function\n\n# Test partial information decomposition for AND gate\narr_and = [arr1[i] >= 0.5 && arr2[i] >= 0.5 ? 1.0 : 0.0 for i in 1:length(arr1)]\npid = get_partial_information_decomposition(arr1, arr2, arr_and)\n@test pid[\"redundancy\"] \u2248 0.3 atol = 0.1\n@test pid[\"unique_1\"] \u2248 0 atol = 0.1\n@test pid[\"unique_2\"] \u2248 0 atol = 0.1\n@test pid[\"synergy\"] \u2248 0.5 atol = 0.1\nprintln(\"Partial information decomposition with AND gate passed.\")\n\npid = get_partial_information_decomposition(arr1, arr2, arr_and, all_orientations = true)\n@test pid[\"z\"][\"redundancy\"] \u2248 0.3 atol = 0.1\n@test pid[\"z\"][\"unique_1\"] \u2248 0 atol = 0.1\n@test pid[\"z\"][\"unique_2\"] \u2248 0 atol = 0.1\n@test pid[\"z\"][\"synergy\"] \u2248 0.5 atol = 0.1\nprintln(\"Partial information decomposition with AND gate (all orientations) passed.\")\n\n# Test redundancy for AND gate\nredundancy = get_redundancy(arr1, arr2, arr_and)\n@test redundancy \u2248 0.3 atol = 0.1\nprintln(\"Redundancy with AND gate passed.\")\n\nredundancy = get_redundancy(arr1, arr2, arr_and, all_orientations = true)[1]\n@test redundancy \u2248 0.3 atol = 0.1\nprintln(\"Redundancy with AND gate (all orientations) passed.\")\n\n# Test unique information for AND gate\nmutual_information = get_mutual_information(arr1, arr_and)\n@test apply_unique_information_formula(mutual_information, redundancy) \u2248 0 atol = 0.1\nprintln(\"Unique information with AND gate passed.\")\n\n# Test synergy for AND gate\ninteraction_information = get_interaction_information(arr1, arr2, arr_and)\n@test apply_synergy_formula(interaction_information, redundancy) \u2248 0.5 atol = 0.1\nprintln(\"Synergy with AND gate passed.\")\n", "meta": {"hexsha": "222c0c8f6b25600078693e21c2ca0a9a5a33da9a", "size": 1624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testPartialInformationDecomposition.jl", "max_stars_repo_name": "invenia/InformationMeasures.jl", "max_stars_repo_head_hexsha": "3acea4d0e29d56bc5c1214a4f22b00b1d057489e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2016-11-02T16:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T17:01:12.000Z", "max_issues_repo_path": "test/testPartialInformationDecomposition.jl", "max_issues_repo_name": "invenia/InformationMeasures.jl", "max_issues_repo_head_hexsha": "3acea4d0e29d56bc5c1214a4f22b00b1d057489e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-06-07T09:18:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T21:18:50.000Z", "max_forks_repo_path": "test/testPartialInformationDecomposition.jl", "max_forks_repo_name": "invenia/InformationMeasures.jl", "max_forks_repo_head_hexsha": "3acea4d0e29d56bc5c1214a4f22b00b1d057489e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-11-02T00:18:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:46:01.000Z", "avg_line_length": 43.8918918919, "max_line_length": 89, "alphanum_fraction": 0.7401477833, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7553471637085469}}
{"text": "# # Some Radial Functions\n\n# The **Gaussian** is defined by ``\u03c6(\u03c1) = \\exp \\left( - (\u03b1\u03c1)^2 \\right)``, where \n# ``\u03b1`` is a shape parameter to fine-tune the function.\n\n\"\"\"\n    Gaussian( \u03b1 = 1 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    \u03c6(\u03c1) = \\\\exp( - (\u03b1 \u03c1)^2 ).\n```\n\"\"\"\n@with_kw struct Gaussian{R<:Real} <: RadialFunction \n    \u03b1 :: R = 1\n    @assert \u03b1 > 0 \"The shape parameter `\u03b1` must be positive.\"\nend\n\nfunction ( \u03c6 :: Gaussian )( \u03c1 :: Real )\n    exp( - (\u03c6.\u03b1 * \u03c1)^2 )\nend\n\ncpd_order( :: Gaussian ) = 0 \ndf(\u03c6 :: Gaussian, \u03c1 :: Real) = - 2 * \u03c6.\u03b1^2 * \u03c1 * \u03c6( \u03c1 )\n\n# The **Multiquadric** is ``\u03c6(\u03c1) = - \\sqrt{ 1 + (\u03b1\u03c1)^2 }`` and also has a positive shape \n# parameter. We can actually generalize it to the following form:\n\n\"\"\"\n    Multiquadric( \u03b1 = 1, \u03b2 = 1//2 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    \u03c6(\u03c1) = (-1)^{ \\\\lceil \u03b2 \\\\rceil } ( 1 + (\u03b1\u03c1)^2 )^\u03b2\n```\n\"\"\"\n@with_kw struct Multiquadric{R<:Real,S<:Real} <: RadialFunction\n    \u03b1 :: R  = 1     # shape parameter \n    \u03b2 :: S  = 1//2  # exponent \n\n    @assert \u03b1 > 0 \"The shape parameter `\u03b1` must be positive.\"\n    @assert \u03b2 % 1 != 0 \"The exponent must not be an integer.\"\n    @assert \u03b2 > 0 \"The exponent must be positive.\"\nend\n\nfunction ( \u03c6 :: Multiquadric )( \u03c1 :: Real )\n    (-1)^(ceil(Int, \u03c6.\u03b2)) * ( 1 + (\u03c6.\u03b1 * \u03c1)^2 )^\u03c6.\u03b2\nend\n\ncpd_order( \u03c6 :: Multiquadric ) = ceil( Int, \u03c6.\u03b2 ) \ndf(\u03c6 :: Multiquadric, \u03c1 :: Real ) = (-1)^(ceil(Int, \u03c6.\u03b2)) * 2 * \u03c6.\u03b1 * \u03c6.\u03b2 * \u03c1 * ( 1 + (\u03c6.\u03b1 * \u03c1)^2 )^(\u03c6.\u03b2 - 1)\n\n# Related is the **Inverse Multiquadric** `` \u03c6(\u03c1) = (1+(\u03b1\u03c1)^2)^{-\u03b2}``:\n\"\"\"\n    InverseMultiquadric( \u03b1 = 1, \u03b2 = 1//2 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    \u03c6(\u03c1) = ( 1 + (\u03b1\u03c1)^2 )^{-\u03b2}\n```\n\"\"\"\n@with_kw struct InverseMultiquadric{R<:Real,S<:Real} <: RadialFunction\n    \u03b1 :: R  = 1\n    \u03b2 :: S  = 1//2\n\n    @assert \u03b1 > 0 \"The shape parameter `\u03b1` must be positive.\"\n    @assert \u03b2 > 0 \"The exponent must be positive.\"\nend\n\nfunction ( \u03c6 :: InverseMultiquadric )( \u03c1 :: Real )\n   ( 1 + (\u03c6.\u03b1 * \u03c1)^2 )^(-\u03c6.\u03b2)\nend\n\ncpd_order( :: InverseMultiquadric ) = 0\ndf(\u03c6 :: InverseMultiquadric, \u03c1 :: Real ) = - 2 * \u03c6.\u03b1^2 * \u03c6.\u03b2 * \u03c1 * ( 1 + (\u03c6.\u03b1 * \u03c1)^2 )^(-\u03c6.\u03b2 - 1)\n\n# The **Cubic** is ``\u03c6(\u03c1) = \u03c1^3``. \n# It can also be generalized: \n\"\"\"\n    Cubic( \u03b2 = 3 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    \u03c6(\u03c1) = (-1)^{ \\\\lceil \u03b2 \\\\rceil /2 } \u03c1^\u03b2\n```\n\"\"\"\n@with_kw struct Cubic <: RadialFunction \n    \u03b2 :: Int = 3\n\n    @assert \u03b2 > 0 \"The exponent `\u03b2` must be positive.\"\n    @assert \u03b2 % 2 != 0 \"The exponent `\u03b2` must not be an even number.\"\nend \n\nfunction ( \u03c6 :: Cubic )( \u03c1 :: Real )\n    (-1)^ceil(Int, \u03c6.\u03b2/2 ) * \u03c1^\u03c6.\u03b2\nend\n\ncpd_order( \u03c6 :: Cubic ) = ceil( Int, \u03c6.\u03b2/2 )\ndf(\u03c6 :: Cubic, \u03c1 :: Real ) = (-1)^(ceil(Int, \u03c6.\u03b2/2)) * \u03c6.\u03b2 * \u03c1^(\u03c6.\u03b2 - 1)\n\n# The thin plate spline is usually defined via \n# ``\u03c6(\u03c1) = \u03c1^2 \\log( \u03c1 )``. \n# We provide a generalized version, which defaults to \n# ``\u03c6(\u03c1) = - \u03c1^4 \\log( \u03c1 )``.\n\"\"\"\n    ThinPlateSpline( k = 2 ) <: RadialFunction\n\nA `RadialFunction` with \n```math \n    \u03c6(\u03c1) = (-1)^{k+1} \u03c1^{2k} \\\\log(\u03c1)\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 (\u03c6 :: ThinPlateSpline )( \u03c1 :: T ) where T<:Real\n    \u03c1 == 0 ? zero(T) : (-1)^(\u03c6.k+1) * \u03c1^(2*\u03c6.k) * log( \u03c1 )\nend\n\ncpd_order( \u03c6 :: ThinPlateSpline ) = \u03c6.k + 1\ndf(\u03c6 :: ThinPlateSpline, \u03c1 :: Real ) = \u03c1 == 0 ? 0 : (-1)^(\u03c6.k+1) * \u03c1^(2*\u03c6.k - 1) * ( 2 * \u03c6.k * log(\u03c1) + 1)\n\n# !!! note \n#     The thin plate spline with `k = 1` is not differentiable at `\u03c1=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": "using .PDMats: PDMat\n\nexport kernelpdmat\n\n\"\"\"\n    kernelpdmat(k::Kernel, X::AbstractVector)\n\nCompute a positive-definite matrix in the form of a `PDMat` matrix (see [PDMats.jl](https://github.com/JuliaStats/PDMats.jl)),\nwith the Cholesky decomposition precomputed.\nThe algorithm adds a diagonal \"nugget\" term to the kernel matrix which is increased until positive\ndefiniteness is achieved. The algorithm gives up with an error if the nugget becomes larger than 1% of the largest value in the kernel matrix.\n\"\"\"\nfunction kernelpdmat(\u03ba::Kernel, X::AbstractVector)\n    K = kernelmatrix(\u03ba, X)\n    Kmax = maximum(K)\n    \u03b1 = eps(eltype(K))\n    while !isposdef(K + \u03b1 * I) && \u03b1 < 0.01 * Kmax\n        \u03b1 *= 2.0\n    end\n    if \u03b1 >= 0.01 * Kmax\n        error(\n            \"Adding noise on the diagonal was not sufficient to build a positive-definite\" *\n            \" matrix:\\n\\t- Check that your kernel parameters are not extreme\\n\\t- Check\" *\n            \" that your data is sufficiently sparse\\n\\t- Maybe use a different kernel\",\n        )\n    end\n    return PDMat(K + \u03b1 * I)\nend\n\n\"\"\"\n    kernelpdmat(k::Kernel, X::AbstractMatrix; obsdim)\n\nIf `obsdim=1`, equivalent to `kernelpdmat(k, RowVecs(X))`.\nIf `obsdim=2`, equivalent to `kernelpdmat(k, ColVecs(X))`.\n\nSee also: [`ColVecs`](@ref), [`RowVecs`](@ref)\n\"\"\"\nfunction kernelpdmat(\u03ba::Kernel, X::AbstractMatrix; obsdim::Union{Int,Nothing}=defaultobs)\n    return kernelpdmat(\u03ba, vec_of_vecs(X; obsdim=obsdim))\nend\n", "meta": {"hexsha": "190444a08e1c083d60f8a307352eb470de58abd1", "size": 1451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/kernelpdmat.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/matrix/kernelpdmat.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/matrix/kernelpdmat.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": 35.3902439024, "max_line_length": 142, "alphanum_fraction": 0.6788421778, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7553471578860553}}
{"text": "using ChaosTools, Test\n\nlo = Systems.logistic(r = 3.5)\nreg = trajectory(lo, 10000; Ttr = 1000)\nset_parameter!(lo, 1, 3.97)\ncha = trajectory(lo, 10000)\ntestchaos01(cha)\n\nprintln(\"\\nTesting 0-1 chaos test...\")\n@testset \"logistic\" begin\n    lo = Systems.logistic(r = 3.5)\n    reg = trajectory(lo, 10000; Ttr = 1000)\n    set_parameter!(lo, 1, 3.97)\n    cha = trajectory(lo, 10000)\n\n    @test testchaos01(cha)\n    @test !testchaos01(reg)\n\n    cs = range(0.1, \u03c0-0.1, length = 20)\n\n    @test testchaos01(cha, cs)\n    @test !testchaos01(reg, cs)\n\nend\n\n\n@testset \"Standard Map\" begin\n    ds = Systems.standardmap(k = 0.9)\n    cs = range(0.1, \u03c0-0.1, length = 20)\n    @testset \"chaotic\" begin\n        cha = trajectory(ds, 10000)[:, 1]\n        @test testchaos01(cha)\n        @test testchaos01(cha, cs)\n    end\n    @testset \"regular\" begin\n        reg = trajectory(ds, 20000, [\u03c0, 0.2rand()])[:, 1]\n        @test !testchaos01(reg)\n        @test !testchaos01(reg, cs)\n    end\nend\n\nusing OrdinaryDiffEq\n\n@testset \"henonheiles\" begin\n    sp = [0, .295456, .407308431, 0] #stable periodic orbit: 1D torus\n    qp = [0, .483000, .278980390, 0] #quasiperiodic orbit: 2D torus\n    ch = [0, -0.25, 0.42081, 0] # chaotic orbit\n    tt = 3000\n    dt = 0.8 # <- very important!\n    ds = Systems.henonheiles()\n    diffeq = Dict(:Ttr => 10, :abstol=>1e-9, :reltol=>1e-9, :solver => Vern9())\n    cs = range(0.1, \u03c0/3-0.1, length = 50)\n\n    @testset \"stable\" begin\n        tr = trajectory(ds, tt, sp; dt = dt, diffeq...)[:, 1]\n        @test !testchaos01(tr)\n        @test !testchaos01(tr, cs)\n    end\n    @testset \"quasiperidic\" begin\n        tr = trajectory(ds, tt, qp; dt = dt, diffeq...)[:, 1]\n        @test !testchaos01(tr)\n        @test !testchaos01(tr, cs)\n    end\n    @testset \"chaotic\" begin\n        tr = trajectory(ds, tt, ch; dt = dt, diffeq...)[:, 1]\n        @test testchaos01(tr, cs)\n    end\nend\n", "meta": {"hexsha": "b3321f2adf685aaee26e672a4a51b8797fad3f53", "size": 1876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/01test.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": "test/01test.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": "test/01test.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": 27.1884057971, "max_line_length": 79, "alphanum_fraction": 0.5879530917, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7553471578788378}}
{"text": "using MDP\n\nconst rate        = [0.3 0.7 0.9]\nconst arrivalRate = 0.5\n\nconst serviceCost = [6 10 20]\nconst holdingCost = 1\nconst dropPenalty = 100_000\n\nconst M = 100\nconst A = size(rate,2)\n\n\nP = [ spzeros(Float64, M+1, M+1) for u = 1:A]\nC = zeros(Float64, M+1, A)\n\n# Initialize cost matrix\nC[1,:] = 0 \n\nfor x = 2:M\n    for u = 1:A\n        C[x,u] = (x-1) * holdingCost + serviceCost[u] \n    end\nend\n\n# Add expected cost for dopping packets\nfor u = 1:A \n    C[M+1,u] = M * holdingCost + serviceCost[u] + arrivalRate * dropPenalty\nend\n\n# Initialize Probability matrix\nfor x = 2:M\n    for u = 1:A\n        P[u][x, x-1] = (1 - arrivalRate) * rate[u]\n        P[u][x, x]   = (1 - arrivalRate) * (1 - rate[u]) + arrivalRate * rate[u]\n        P[u][x, x+1] = arrivalRate * ( 1 - rate[u])\n    end\nend\n\nfor u = 1:A\n    P[u][1,1] = (1 - arrivalRate) \n    P[u][1,2] = arrivalRate\n\n    P[u][M+1, M+1] = (1 - rate[u])\n    P[u][M+1, M  ] = rate[u]\nend\n\nmodel = ProbModel(C, P; objective=:Min)\n\n@time (v,g) = valueIteration(model; discount=0.9)\n\nusing StatsBase\n\nprintln(rle(g))\n", "meta": {"hexsha": "30229c63495ae67f0628135aee0464ff86200220", "size": 1059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/queueing.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/queueing.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/queueing.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": 19.2545454545, "max_line_length": 80, "alphanum_fraction": 0.5703493862, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8267117940706735, "lm_q1q2_score": 0.7553471539851474}}
{"text": "# Test Rand index\n\nusing Test\nusing Clustering\n\n@testset \"randindex() (Rand index)\" begin\n\na1 = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]\na2 = [1, 1, 1, 1, 2, 2, 2, 2, 2, 2]\na3 = [3, 3, 3, 2, 2, 2, 1, 1, 1, 1]\n\n(ARI, RI, MI, HI) = randindex(a1, a1)\n\n@test ARI \u2248 1.0 atol=1.0e-12\n@test RI  \u2248 1.0 atol=1.0e-12\n@test MI  \u2248 0.0 atol=1.0e-12\n@test HI  \u2248 1.0 atol=1.0e-12\n\n\n(ARI, RI, MI, HI) = randindex(a1, a3)\n\n@test ARI \u2248 1.0 atol=1.0e-12\n@test RI  \u2248 1.0 atol=1.0e-12\n@test MI  \u2248 0.0 atol=1.0e-12\n@test HI  \u2248 1.0 atol=1.0e-12\n\n\n(ARI, RI, MI, HI) = randindex(a1, a2)\n\n@test ARI \u2248 0.403669 atol=1.0e-5\n@test RI  \u2248 0.711111 atol=1.0e-5\n@test MI  \u2248 0.288888 atol=1.0e-5\n@test HI  \u2248 0.422222 atol=1.0e-5\n\n@test randindex(a1, a2) == randindex(a2, a1)\n\nend\n", "meta": {"hexsha": "d3b8303308cb2c96b957a268d425ed7370997c60", "size": 736, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 19.3684210526, "max_line_length": 44, "alphanum_fraction": 0.5774456522, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7553471500986743}}
{"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* (\u0394(X,k,dt) - dxdt)' * (D)^(-1) * (\u0394(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 \u0394(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": "module MyInterpolations\n\n  export LinearInterpolation\n\n  immutable LinearInterpolation \n    grid::Array\n    vals::Array\n\u3000end\n\n\u3000function (f::LinearInterpolation)(x)\n    i = searchsortedlast(f.grid, x)\n    if i == 0 || ( i == length(f.grid) && f.grid[end] !=  x )\n        return 0\n \u3000\u3000end\n    if x == f.grid[end]\n        return f.vals[end] \n    end\n    interpolated_value = (f.vals[i+1]-f.vals[i])/(f.grid[i+1]-f.grid[i])*(x-f.grid[i])+f.vals[i]\n    return interpolated_value\n\u3000\u3000\u3000\n\u3000end\n\u3000\u3000\n\nend", "meta": {"hexsha": "ada2724d9714579ff48d0ca5729a8b9c300e92f2", "size": 489, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MyInterpolations.jl", "max_stars_repo_name": "ellenjunghyunkim/MyInterpolations.jl", "max_stars_repo_head_hexsha": "df95b96d50056c2549802688c394b29b5109f645", "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": "ellenjunghyunkim/MyInterpolations.jl", "max_issues_repo_head_hexsha": "df95b96d50056c2549802688c394b29b5109f645", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-22T01:44:21.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-23T00:26:11.000Z", "max_forks_repo_path": "src/MyInterpolations.jl", "max_forks_repo_name": "ellenjunghyunkim/MyInterpolations.jl", "max_forks_repo_head_hexsha": "df95b96d50056c2549802688c394b29b5109f645", "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.375, "max_line_length": 96, "alphanum_fraction": 0.609406953, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774727, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7553308652896281}}
{"text": "#Hermite-Gaussian Modes\r\nHG(n,m,x,y) = hermiteh(n,\u221a2*x)*hermiteh(m,\u221a2*y)*exp(-x^2-y^2);\r\n\r\nfunction \u03b8(x,y)\r\n\t#\u03b8 \u2208 [-\u03c0,\u03c0]\r\n\tif x \u2265 0\r\n\t\tatan(y/x)\r\n\telse\r\n\t\tif y\u2265 0\r\n\t\t\tatan(y/x) + \u03c0\r\n\t\telse\r\n\t\t\tatan(y/x) - \u03c0\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*\u03b8(x,y))\r\n    end\r\nend\r\n\r\nfunction airy_beam(x,\u03b1)\r\n\t#Airy beam (in a single direction)\r\n\tairyai(x)*exp(\u03b1*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(\u03bc = [0, 0], \u03c3 = [1, 1], nsamples = [10000, 10000])\n    m   = \u03bc[1] - \u03bc[2]\n    s   = \u03c3 .* \u03c3\n    ps  = nsamples .* s\n    \u03b8   = sqrt(s[1] * (ps[1] / (ps[1] + 1)) + s[2] * (ps[2] / (ps[2] + 1)))\n    (\u03b8 * sqrt(2 / \u03c0) * exp((-m^2) / (2 * \u03b8^2)) + m * erf(m / (\u03b8 * sqrt(2))) - abs(m)) / 2\nend\n\nfunction evsi_sim(\u03bc = [0, 0], \u03c3 = [1, 1], nsamples = [10000, 10000]; nsims = 1000000)\n  \n    ndists        = length(\u03bc)\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(\u03bc[dist], \u03c3[dist]), nsims)\n        prior_weight[dist]   = (1 / \u03c3[dist]) / (nsamples[dist] + (1 / \u03c3[dist]))\n        sample_weight[dist]  = nsamples[dist] / (nsamples[dist] + (1 / \u03c3[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] = \u03bc[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(\u03bc)\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\u00e8 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        \u03bb_1 = ra1\n        \u03bb_2 = ra2\n        \u03c6_1 = dec1\n        \u03c6_2 = dec2\n    elseif units == 1\n        # Right ascensions are in hours, declinations in degrees.\n        \u03bb_1 = ra1*pi/12.0\n        \u03bb_2 = ra2*pi/12.0\n        \u03c6_1 = deg2rad(dec1)\n        \u03c6_2 = deg2rad(dec2)\n    elseif units == 2\n        # Right ascensions and declinations are in degrees.\n        \u03bb_1 = deg2rad(ra1)\n        \u03bb_2 = deg2rad(ra2)\n        \u03c6_1 = deg2rad(dec1)\n        \u03c6_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    \u0394\u03c6_2 = (\u03c6_2 - \u03c6_1) * 0.5\n    \u0394\u03bb_2 = (\u03bb_2 - \u03bb_1) * 0.5\n    \u0394\u03c3 = 2asin(sqrt(abs2(sin(\u0394\u03c6_2)) + cos(\u03c6_1) * cos(\u03c6_2) * abs2(sin(\u0394\u03bb_2))))\n    if units == 0\n        return \u0394\u03c3\n    else\n        return rad2sec(\u0394\u03c3)\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\u00e1nchez\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, \u03d5, \u03b8) = (a.r, a.\u03b8, \u03c0/2 - a.\u03d5)   # (radius, azimuth, colatitude)\n\tY = computeYlm(\u03b8, \u03d5; 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 \u2a26\u03c3 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 (\u03c3-bound-test)\n\nTests if approximately 68% of state values lie within the \u2a26\u03c3 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\u03c3-bound-test)\n\nTests if approximately 95% of state values lie within the \u2a262\u03c3 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 \u03b1 = 0.05\n\nCalculates confidence interval [r1 r2] and tests Prob{ \u2211 NIS values)} \u2208 [r1 r2] \u2223 H_0 ) = 1 - \u03b1\nwith Hypothesis H_0: N * \u2211 NIS values \u223c \u03c7^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    \u03a0 = prod(n)\n    mod(sum(ai * invmod(\u03a0 \u00f7 ni, ni) * (\u03a0 \u00f7 ni) for (ni, ai) in zip(n, a)), \u03a0)\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(\u03bc,\u03c1,\u03c3,n)\n    n==1 && (return [\u03bc],[1.0])\n\n\tmu_eps=0\n\tq = (\u03c1+1)/2\n\tnu = ((n-1)/(1-\u03c1^2))^(1/2) * \u03c3\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-\u03c1).-nu,mu_eps/(1-\u03c1).+nu,n);].+\u03bc\n\treturn x,P\nend\n\nfunction cdf_normal(x) :inline\n    c = 0.5 * erfc(-x/sqrt(2))\nend\n\nfunction tauchen(\u03bc,\u03c1,\u03c3,N,m=3)\n\tif N==1\n\t\treturn [\u03bc],[1.0]\n\tend\n\tZ     = zeros(N)\n\tZprob = zeros(N,N)\n\ta     = (1-\u03c1)*\u03bc\n\n\tZ[N]  = m * sqrt(\u03c3^2 / (1 - \u03c1^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-\u03c1)\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 - \u03c1 * Z[j] + zstep / 2) / \u03c3)\n\t        elseif k == N\n\t            Zprob[j,k] = 1 - cdf_normal((Z[N] - a - \u03c1 * Z[j] - zstep / 2) / \u03c3)\n\t        else\n\t            Zprob[j,k] = cdf_normal((Z[k] - a - \u03c1 * Z[j] + zstep / 2) / \u03c3) - cdf_normal((Z[k] - a - \u03c1 * Z[j] - zstep / 2) / \u03c3)\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": "n, p = 500, 5\n((X, y, \u03b8), (X1, y1, \u03b81)) = generate_binary(n, p; seed=52)\n\n@testset \"Logreg\" begin\n    # No intercept\n    \u03bb = 5.0\n    lr = LogisticRegression(\u03bb; fit_intercept=false)\n    J  = objective(lr, X, y)\n    o  = LogisticLoss() + \u03bb * L2Penalty()\n    @test J(\u03b8) == o(y, X*\u03b8, \u03b8)\n    \u03b8_newton   = fit(lr, X, y, solver=Newton())\n    \u03b8_newtoncg = fit(lr, X, y, solver=NewtonCG())\n    \u03b8_lbfgs    = fit(lr, X, y, solver=LBFGS())\n    @test isapprox(J(\u03b8),          282.09960, rtol=1e-5)\n    @test isapprox(J(\u03b8_newton),   280.37472, rtol=1e-5) # <- ref value\n    @test isapprox(J(\u03b8_newtoncg), 280.37472, rtol=1e-5)\n    @test isapprox(J(\u03b8_lbfgs),    280.37472, rtol=1e-5)\n\n    # With intercept\n    lr1 = LogisticRegression(\u03bb; penalize_intercept=true)\n    J   = objective(lr1, X, y1)\n    \u03b8_newton   = fit(lr1, X, y1, solver=Newton())\n    \u03b8_newtoncg = fit(lr1, X, y1, solver=NewtonCG())\n    \u03b8_lbfgs    = fit(lr1, X, y1, solver=NewtonCG())\n    @test isapprox(J(\u03b81),         213.80970, rtol=1e-5)\n    @test isapprox(J(\u03b8_newton),   209.32539, rtol=1e-5) # <- ref value\n    @test isapprox(J(\u03b8_newtoncg), 209.32539, rtol=1e-5)\n    @test isapprox(J(\u03b8_lbfgs),    209.32539, rtol=1e-5)\n\n    # with intercept and not penalizing it\n    lr1 = LogisticRegression(\u03bb)\n    J   = objective(lr1, X, y1)\n    \u03b8_newton   = fit(lr1, X, y1, solver=Newton())\n    \u03b8_newtoncg = fit(lr1, X, y1, solver=NewtonCG())\n    \u03b8_lbfgs    = fit(lr1, X, y1, solver=NewtonCG())\n    @test isapprox(J(\u03b81),         212.29192, rtol=1e-5)\n    @test isapprox(J(\u03b8_newton),   207.71595, rtol=1e-5) # <- ref value\n    @test isapprox(J(\u03b8_newtoncg), 207.71595, rtol=1e-5)\n    @test isapprox(J(\u03b8_lbfgs),    207.71595, rtol=1e-5)\n\n    if DO_COMPARISONS\n        # This checks that the parameters recovered using Sklearn lead\n        # to a similar loss than the one given by our code to verify the\n        # correctness of the code.\n        lr_sk_ncg = SKLEARN_LM.LogisticRegression(C=1.0/\u03bb, solver=\"newton-cg\")\n        lr_sk_ncg.fit(X, y1)\n        \u03b81_sk_ncg = vcat(lr_sk_ncg.coef_[:], lr_sk_ncg.intercept_)\n        lr_sk_lbfgs = SKLEARN_LM.LogisticRegression(C=1.0/\u03bb, solver=\"lbfgs\")\n        lr_sk_lbfgs.fit(X, y1)\n        \u03b81_sk_lbfgs = vcat(lr_sk_lbfgs.coef_[:], lr_sk_lbfgs.intercept_)\n        # Comparing with ours\n        @test isapprox(J(\u03b81_sk_ncg),   207.71595, rtol=1e-5)\n        @test isapprox(J(\u03b81_sk_lbfgs), 207.71595, rtol=1e-5)\n    end\nend\n\nn, p, c = 500, 5, 4\n((X, y, \u03b8), (X1, y1, \u03b81)) = generate_multiclass(n, p, c; seed=525)\n\n@testset \"Multinomial\" begin\n    # No intercept\n    \u03bb = 5.0\n    mnr = MultinomialRegression(\u03bb; fit_intercept=false)\n    J   = objective(mnr, X, y; c=c)\n    \u03b8_newtoncg = fit(mnr, X, y, solver=NewtonCG())\n    \u03b8_lbfgs    = fit(mnr, X, y, solver=R.LBFGS())\n    @test isapprox(J(\u03b8),          419.67795, rtol=1e-5)\n    @test isapprox(J(\u03b8_newtoncg), 384.33810, rtol=1e-5) # <- ref value\n    @test isapprox(J(\u03b8_lbfgs),    384.33810, rtol=1e-5)\n\n    #  With intercept\n    mnr = MultinomialRegression(\u03bb; penalize_intercept=true)\n    J   = objective(mnr, X, y1; c=c)\n    \u03b8_newtoncg = fit(mnr, X, y1, solver=NewtonCG())\n    \u03b8_lbfgs    = fit(mnr, X, y1, solver=R.LBFGS())\n    @test isapprox(J(\u03b8),          1244.46404, rtol=1e-5)\n    @test isapprox(J(\u03b8_newtoncg),  388.75018, rtol=1e-5) # <- ref value\n    @test isapprox(J(\u03b8_lbfgs),     388.75018, rtol=1e-5)\n\n    mnr = MultinomialRegression(\u03bb)\n    J   = objective(mnr, X, y1; c=c)\n    \u03b8_newtoncg = fit(mnr, X, y1, solver=NewtonCG())\n    \u03b8_lbfgs    = fit(mnr, X, y1, solver=R.LBFGS())\n    @test isapprox(J(\u03b8),          1242.70990, rtol=1e-5)\n    @test isapprox(J(\u03b8_newtoncg),  383.93018, rtol=1e-5) # <- ref value\n    @test isapprox(J(\u03b8_lbfgs),     383.93018, rtol=1e-5)\n\n    if DO_COMPARISONS\n        lr_sk_ncg = SKLEARN_LM.LogisticRegression(C=1.0/\u03bb, solver=\"newton-cg\",\n                                             multi_class=\"multinomial\")\n        lr_sk_ncg.fit(X, y1)\n        \u03b81_sk_ncg = vec(vcat(lr_sk_ncg.coef_', lr_sk_ncg.intercept_'))\n        lr_sk_lbfgs = SKLEARN_LM.LogisticRegression(C=1.0/\u03bb, solver=\"lbfgs\",\n                                               multi_class=\"multinomial\")\n        lr_sk_lbfgs.fit(X, y1)\n        \u03b81_sk_lbfgs = vec(vcat(lr_sk_ncg.coef_', lr_sk_ncg.intercept_'))\n        # Comparing with ours\n        @test isapprox(J(\u03b81_sk_ncg),   385.67895, rtol=1e-5)\n        @test isapprox(J(\u03b81_sk_lbfgs), 385.67895, rtol=1e-5)\n    end\nend\n\nn, p = 500, 100\n(_, (X, y, \u03b8)) = generate_binary(n, p;  seed=52551, sparse=0.1)\n\n@testset \"Logreg/EN\" begin\n    \u03c1 = 0.8\n    \u03b1 = 0.03\n    \u03bb = \u03b1 * (1 - \u03c1) * n\n    \u03b3 = \u03b1 * \u03c1 * n\n    enlr = LogisticRegression(\u03bb, \u03b3; penalize_intercept=true)\n    J    = objective(enlr, X, y)\n    \u03b8_fista = fit(enlr, X, y)\n    \u03b8_ista  = fit(enlr, X, y, solver=ISTA())\n    @test isapprox(J(\u03b8),       271.43962, rtol=1e-5)\n    @test isapprox(J(\u03b8_fista), 250.46547, rtol=1e-5) # <- ref values\n    @test isapprox(J(\u03b8_ista),  250.46547, rtol=1e-5)\n    # sparsity\n    @test nnz(\u03b8)       == 7  # generating \u03b8\n    @test nnz(\u03b8_fista) == 18\n    @test nnz(\u03b8_ista)  == 18\n\n    # pure l1 regularization (unclear how sklearn does the mixing of l1/l2 for logreg)\n    enlr = LogisticRegression(\u03b3; penalty=:l1)\n    J    = objective(enlr, X, y)\n    \u03b8_fista = fit(enlr, X, y)\n    @test isapprox(J(\u03b8),       263.76834, rtol=1e-5)\n    @test isapprox(J(\u03b8_fista), 245.65841, rtol=1e-5) # <- ref value\n    @test nnz(\u03b8_fista) == 17\n\n    if DO_COMPARISONS\n        # NOTE: this algorithm is stochastic so can't have hard tests\n        PY_RND.seed(1531)\n        enlr_sk = SKLEARN_LM.LogisticRegression(penalty=\"elasticnet\", C=1.0/\u03b3, l1_ratio=1, solver=\"saga\")\n        enlr_sk.fit(X, y)\n        \u03b8_sk = vcat(enlr_sk.coef_[:], enlr_sk.intercept_)\n        @test isapprox(J(\u03b8_sk), 245.658, rtol=1e-3)\n        @test 17 \u2264 nnz(\u03b8_sk) \u2264 19\n    end\nend\n\nn, p, c = 1000, 100, 3\n(_, (X, y, \u03b8)) = generate_multiclass(n, p, c;  seed=33, sparse=0.1)\n\n@testset \"Multin/EN\" begin\n    \u03bb = 10\n    \u03b3 = 50\n    enmnr = MultinomialRegression(\u03bb, \u03b3; penalize_intercept=true)\n    J     = objective(enmnr, X, y; c=c)\n    \u03b8_fista = fit(enmnr, X, y)\n    \u03b8_ista  = fit(enmnr, X, y)\n    @test isapprox(J(\u03b8),       1574.61741, rtol=1e-5)\n    @test isapprox(J(\u03b8_fista),  922.36776, rtol=1e-5) # <- ref value\n    @test isapprox(J(\u03b8_ista),   922.36776, rtol=1e-5)\n    @test nnz(\u03b8_fista) == 15\n    @test nnz(\u03b8_ista)  == 15\n\n    # pure l1 regularization for sklearn comp\n    enmnr = MultinomialRegression(\u03b3; penalty=:l1)\n    J     = objective(enmnr, X, y; c=c)\n    \u03b8_fista = fit(enmnr, X, y)\n    @test isapprox(J(\u03b8),       1432.37281, rtol=1e-5)\n    @test isapprox(J(\u03b8_fista),  912.25297, rtol=1e-5) # <- ref value\n    @test nnz(\u03b8_fista) == 16\n\n    if DO_COMPARISONS\n        # NOTE: this algorithm is stochastic\n        PY_RND.seed(1531)\n        enmnr_sk = SKLEARN_LM.LogisticRegression(penalty=\"elasticnet\", C=1.0/\u03b3, l1_ratio=1,\n                                            solver=\"saga\", multi_class=\"multinomial\")\n        enmnr_sk.fit(X, y)\n        \u03b8_sk = enmnr_sk.coef_'[:]\n        @test isapprox(J(\u03b8_sk), 912.39215, rtol=1e-3)\n        @test 14 \u2264 nnz(\u03b8_sk) \u2264 16\n    end\nend\n", "meta": {"hexsha": "65bdb8e832fe1e4342079f01771ce29f0494a0ef", "size": 7071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fit/logistic-multinomial.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MLJLinearModels.jl-6ee0df7b-362f-4a72-a706-9e79364fb692", "max_stars_repo_head_hexsha": "202e058a2a6fe98871c74c85f3e0a8c1cd7d0a7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-21T03:05:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-21T03:05:43.000Z", "max_issues_repo_path": "test/fit/logistic-multinomial.jl", "max_issues_repo_name": "Erensu/MLJLinearModels.jl", "max_issues_repo_head_hexsha": "202e058a2a6fe98871c74c85f3e0a8c1cd7d0a7e", "max_issues_repo_licenses": ["MIT"], "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/fit/logistic-multinomial.jl", "max_forks_repo_name": "Erensu/MLJLinearModels.jl", "max_forks_repo_head_hexsha": "202e058a2a6fe98871c74c85f3e0a8c1cd7d0a7e", "max_forks_repo_licenses": ["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.9491525424, "max_line_length": 105, "alphanum_fraction": 0.5983594965, "num_tokens": 2793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7552975024570509}}
{"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 .\u2248 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(; \u03b7::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    \u03b7::Float64\nend\n\nfunction VanillaGradDescent(; \u03b7::Real=0.01)\n    @assert \u03b7 > 0.0 \"\u03b7 must be greater than 0\"\n\n    VanillaGradDescent(\"Vanilla Gradient Descent\", 0, \u03b7)\nend\n\nparams(opt::VanillaGradDescent) = \"\u03b7=$(opt.\u03b7)\"\n\nfunction update(opt::VanillaGradDescent, g_t::AbstractArray{T}) where {T<:Real}\n    # update timestep\n    opt.t += 1\n    return opt.\u03b7 * 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": "println(\"\\n\\n\\nRunning tests ...\") \n\npush!(LOAD_PATH, joinpath(@__DIR__, \"../..\"))\nusing InformedDifferentialEvolution\nusing Test, Statistics\n\noptimum = [-2 4]'\ncostf(x) = (r = sqrt(sum((x-optimum).^2)); sin(r)^2+r/2)\ncostf2(x, ignore) = (r = sqrt(sum((x-optimum).^2)); sin(r)^2+r/2)\n\nbest, info = DE(costf, [-10,-10], [10,10])\n@test best == optimum\n\nbest, info = DE(costf2, [-10,-10], [10,10], data = 1)\n@test best == optimum\n\nf(x) = sum(abs.(x))\npredictor(r,pop,costs) = r[:] = vcat(mean(pop,dims=1), mean(pop,dims=1))\nmi = [-1,-1]; ma = [1,1]\n\nbest, info = DE(f, mi, ma, predictors = [predictor, :default])\n@test maximum(abs.(best)) < 0.000001\n\nfunction g(x, previouscost = Inf)\n    r = 0.\n    for i = -5:5\n        r += abs.(x[1])+abs.(x[2]+i)\n        if r > previouscost\n            break\n        end\n    end\n    r\nend\nbest, info = DE(g, [-100,-100], [100,100])\n@test best == [0 0]'\n\nprintln(\"   done running tests!\")\n", "meta": {"hexsha": "9f8148565291d8a8d60380fd6b3ec11a3e5fa35b", "size": 922, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/InformedDifferentialEvolution.jl-281102dc-23b7-58f9-8736-e3566ed2adc3", "max_stars_repo_head_hexsha": "1c232d9ae02ad3a32cdc0a8fced57fe7e14a43ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-10-20T07:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-16T09:52:47.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/InformedDifferentialEvolution.jl-281102dc-23b7-58f9-8736-e3566ed2adc3", "max_issues_repo_head_hexsha": "1c232d9ae02ad3a32cdc0a8fced57fe7e14a43ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-04T16:42:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:30:34.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/InformedDifferentialEvolution.jl-281102dc-23b7-58f9-8736-e3566ed2adc3", "max_forks_repo_head_hexsha": "1c232d9ae02ad3a32cdc0a8fced57fe7e14a43ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:14:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:10:55.000Z", "avg_line_length": 24.2631578947, "max_line_length": 72, "alphanum_fraction": 0.5661605206, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7552975006560173}}
{"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.\u00f7 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": "using Distributions, Plots, LaTeXStrings; pyplot()\n\ncUnif = Uniform(0,2\u03c0)\nxGrid, N = 0:0.1:2\u03c0, 10^6\n\nstephist( rand(N)*2\u03c0, bins=xGrid, \n\tnormed=:true, c=:blue, \n\tlabel=\"MC Estimate\")\nplot!( xGrid, pdf.(cUnif,xGrid), \n\tc=:red,ylims=(0,0.2),label=\"PDF\", ylabel=\"Density\",xticks=([0:\u03c0/2:2\u03c0;],\n\t[\"0\", L\"\\dfrac{\\pi}{2}\", L\"\\pi\", L\"\\dfrac{3\\pi}{2}\", L\"2\\pi\"]))", "meta": {"hexsha": "b4865b6dc9283fad42f4891905db3b6360d44593", "size": 354, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/continuousUniform.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/continuousUniform.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/continuousUniform.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.1818181818, "max_line_length": 72, "alphanum_fraction": 0.6129943503, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7552974949909952}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mos\u00e8 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\u00b2 \u00c5).\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# \u2554\u2550\u2561 cac0bc38-ead9-4f99-a939-fc2645874efd\nmd\"\"\"\n# Types in Julia\n\"\"\"\n\n# \u2554\u2550\u2561 ecb2b8d9-ceda-4008-8137-b29bd7ef3ba9\n# Uses of types.jl\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0ece0b55-ede7-4db1-9b48-61e1d4534761\nmd\"\"\"\n### What is a type?\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0d352bcc-dfc1-429f-ad6c-40dc8c4cd038\nbegin\n\tx = 1\n\ty = 1.3\nend\n\n# \u2554\u2550\u2561 81863f06-8dac-48fd-a6e1-cf5df30c63f6\nsizeof(x), sizeof(y)\n\n# \u2554\u2550\u2561 3de40205-6b5d-4d99-b886-1a1dc6a07955\ntypeof(x), typeof(y)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7082e444-6268-4721-a278-2511a22daf68\nbitstring(x)\n\n# \u2554\u2550\u2561 43538919-4349-43f1-a196-759fe65d3be3\nbitstring(z)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e6281275-0b87-47f4-a081-bb366ced3466\nmd\"\"\"\n## Algorithmic differentiation\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b3b15bf5-115d-4831-9115-36c88e9b899c\nmd\"\"\"\n### Defining a composite type\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 82c79506-68ea-41dd-888d-840371c08430\nstruct MyType\n    a\n    b::Int\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f2421fbf-5cfc-4332-be60-b61fa4e02d8c\nmd\"\"\"\nCreating an object of that type is accomplished as follows:\n\"\"\"\n\n# \u2554\u2550\u2561 710612bd-4856-4e51-b2d6-2bdc972f196d\nx1 = MyType(3, 4)\n\n# \u2554\u2550\u2561 70eb5167-6288-4f84-b140-21b4b329cb45\nmd\"\"\"\nWe can extract information as follows:\n\"\"\"\n\n# \u2554\u2550\u2561 9fb42f3c-c7ff-4f31-b5e6-9e96de16bac5\nx1.a\n\n# \u2554\u2550\u2561 07808ac8-c910-4e92-ac34-c9ff225f4be8\ntypeof(x1.a)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5488c55f-8d0a-4c9b-8f8b-40ed4fe14e67\nstruct Dual\n    value::Float64\n    deriv::Float64\nend\n\n# \u2554\u2550\u2561 4f5e5eea-13df-477e-baea-c37ab6074aea\nx_D = Dual(3, 4)\n\n# \u2554\u2550\u2561 da932afe-990f-4ca7-aa81-9d85e1ca3bac\nmethods(Dual)\n\n# \u2554\u2550\u2561 fac29cb2-dc57-4a06-9728-567169ac3768\nconvert(Float64, 3)\n\n# \u2554\u2550\u2561 4118613c-e58a-4f63-81d1-0e197e66cf98\n# this raises an error\nconvert(Float64, \"hello\")\n\n# \u2554\u2550\u2561 ac8fa4de-d8ef-44f2-b709-aceb1e0ecb04\ny_D = Dual(5, 6)\n\n# \u2554\u2550\u2561 92aa5678-478c-4cb6-9187-3285534aac8c\nx_D + y_D\n\n# \u2554\u2550\u2561 04a21e57-a45c-4e4b-977a-42c6ee228b4a\nnewadd(x::Dual, y::Dual) = Dual(x.value + y.value, x.deriv + y.deriv)\n\n# \u2554\u2550\u2561 915bfb27-7234-43ea-a052-093f89d7bdcd\nnewadd(x_D, y_D)\n\n# \u2554\u2550\u2561 9b213fb9-382a-4c5b-93fe-22252d29d0c6\nmd\"\"\"\n## Implementing arithmetic for a type\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 62a97a4b-dfa6-404d-958b-b7b4ab7d25ca\n# +(x::Dual, y::Dual) = Dual(x.value + y.value, x.deriv + y.deriv)\n\n# \u2554\u2550\u2561 9b0d361a-8c30-4ec0-a183-ac3890895f0e\n# Base.+(x::Dual, y::Dual) = Dual(x.value + y.value, x.deriv + y.deriv)\n\n# \u2554\u2550\u2561 9b8f41b5-9ade-4f34-8d09-cb548bd6c242\n# or\n# +(x::Dual, y::Dual) = add(x, y)\n\n# \u2554\u2550\u2561 5b29f183-bda6-4ffb-bb78-5199980039d3\n# or\n# function +(x::Dual, y::Dual)\n#    return add(x, y)\n# end\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 abcbc0a1-33e7-430f-b0a8-e8b65c8666b2\n@which +(3)\n\n# \u2554\u2550\u2561 17498a94-5db9-4c5e-9268-e588fddeae54\n-(3)\n\n# \u2554\u2550\u2561 c847f0c2-1eac-4900-b80c-7f89846b2924\nmethods(+)\n\n# \u2554\u2550\u2561 6caea9da-3edc-4309-bad8-f348693960b2\nx\n\n# \u2554\u2550\u2561 17cce3ab-1b4f-402d-bcc3-c7905360a441\ny\n\n# \u2554\u2550\u2561 526a204c-6a72-4cde-900a-568667e45c64\nx + y\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 86141559-f6f4-43a6-8291-550adf31b25b\n\n\n# \u2554\u2550\u2561 cee6af83-0079-4acd-9e14-cd7b7eb6947f\nbegin\n\tvalue(f::Dual) = f.value\n\tderiv(f::Dual) = f.deriv\nend\n\n# \u2554\u2550\u2561 4e222c6a-054b-41e6-bef4-b0726344ee94\nlet\n\t\u2202(f::Dual) = f.deriv\n\t*(f::Dual, g::Dual) = Dual(value(f) * value(g),\n    \t                     value(f) * \u2202(g) + \u2202(f) * value(g))\n\t42 # return this to avoid conflict\nend\n\n# \u2554\u2550\u2561 a1b1b945-ba2e-4668-8698-4df02660d379\nmd\"\"\"\n(Try using `@code_llvm`)\n\"\"\"\n\n# \u2554\u2550\u2561 8857e0aa-da38-4ae6-8ef9-efa66dd51cfc\nbegin\n\tf = Dual(3.0, 4.0)\n\tg = Dual(5.0, 6.0)\nend\n\n# \u2554\u2550\u2561 ad671591-a625-4de2-9b18-84c7773cb4b8\nf, g\n\n# \u2554\u2550\u2561 053e90a7-5fa6-4063-9634-63d48ee16690\nf + g\n\n# \u2554\u2550\u2561 d521f0e3-1636-4e8b-b8f3-639a90780690\nf * g\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d67fa8a9-f43e-4eca-bb0e-1603c9f7da5d\nbegin\n\ta = 3.0\n\txx = Dual(a, 1.0)  # \"the identity function x \u21a6 x, with derivative 1\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fd34be78-af76-4d46-bdbd-19fd19155785\nmd\"\"\"\n#### Exercise 3\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6418d0a4-8dd3-4816-8e5b-092cb769ebb6\na = 3.0\nxx = Dual(a, 1.0)\n\n# \u2554\u2550\u2561 8ebb42e9-11ec-434d-87c9-4259c26f6526\nxx + xx\n\n# \u2554\u2550\u2561 84b6a870-4515-4e6c-b306-d6b6d2a0fb8d\nxx * xx\n\n# \u2554\u2550\u2561 a0865cb0-7077-44ff-a130-eb73cbbc3179\nxx * xx + xx  # the function x \u21a6 x^2 + x,  derivative 2x + 1\n\n# \u2554\u2550\u2561 f1fc7637-4804-4fc1-81ac-14874e66f9d6\nff(x) = x*x*x + x*x + x*x  # x^3 + 2x^2\n\n# \u2554\u2550\u2561 ded7adc0-619f-4735-bd93-9c26c4c21858\nff(xx)\n\n# \u2554\u2550\u2561 1284374b-ab26-46b8-a74e-119655f5112e\nff(a)\n\n# \u2554\u2550\u2561 4e06b4f6-9753-4847-8c6c-120208520dc5\nn = 4\nfff(x) = x^n\n\n# \u2554\u2550\u2561 420c0ef0-3f7e-4044-be30-c2873636c6e8\ndff(x) = 3x^2 + 4x\n\n# \u2554\u2550\u2561 f426bed2-05f1-4598-9817-bb90262911ef\ndff(a)\n\n# \u2554\u2550\u2561 09bfa122-ca5b-4b4a-a9eb-09b1b5482a76\nfff(x) = x^2\n\n# \u2554\u2550\u2561 d08a434c-c816-4f43-9c93-2d0eda57723c\nfff(xx)\n\n# \u2554\u2550\u2561 131373df-8e58-49b0-be5f-3cd8d8deb61d\nfff(xx)\n\n# \u2554\u2550\u2561 76a7a87b-0283-4a85-9d88-0eec06ef689f\nfff4(x) = x^4\n\n# \u2554\u2550\u2561 d608bc38-5653-4ad5-b6e4-6b2236299e4c\nfff4(xx)\n\n# \u2554\u2550\u2561 bf697142-0eaf-4717-9434-eaa89946beb4\nmd\"\"\"\n`Base.literal_pow`\n\"\"\"\n\n# \u2554\u2550\u2561 108212df-c86f-4b75-8576-65f3964687e9\nmd\"\"\"\n#### Exercise 4\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d7f6c80a-4922-42be-9bce-e493e603c373\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5011cf98-128e-4c94-bae0-109016427c50\nmd\"\"\"\n### Parametric types\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 df1c033c-8a99-4b45-bc9c-3287a3a959ec\nstruct MyType2{T}\n    a::T\n    b::T\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ccc258fa-c928-4175-a48e-bd72b7d22f31\nx_M = MyType2(3, 4)\n\n# \u2554\u2550\u2561 c9f3dde8-7989-45e8-9831-894d82e57e90\ny_M = MyType2(3.1, 4.2)\n\n# \u2554\u2550\u2561 2d3876d6-5fcf-4bfb-8dba-4bdf252c73fc\nz_M = MyType2(1, 5.3)\n\n# \u2554\u2550\u2561 a0d7a33a-e067-4e69-9c70-14005f41a2c6\nstruct MyType3{S,T}\n    a::S\n    b::T\nend\n\n# \u2554\u2550\u2561 812149d8-0040-4d67-b2a2-f1304af4b225\nx_M2 = MyType3(1, 5.3)\n\n# \u2554\u2550\u2561 75fa60fe-6583-4a6a-b6b0-06fb81006218\nmd\"\"\"\nNote that `x` and `y` have *different* types.\n\"\"\"\n\n# \u2554\u2550\u2561 4146cf8f-ab2f-457d-97ef-e6d39e93246e\nmd\"\"\"\nWe can define functions acting on parametric types without necessarily talking about the type parameter:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 907f65aa-e1a1-4838-a1a0-cdaa0a1cfa45\nstruct DualReal\n    value::Real\n    deriv::Real\nend\n    \n\n# \u2554\u2550\u2561 fc5839ce-935a-46aa-bbe7-01f203b0fdb5\nDualReal(big(1.0), big\"1.4\")\n\n# \u2554\u2550\u2561 c445bab5-c012-4890-89bc-e7d6950fa7b4\nDualReal(3.1, big\"1.4\")\n\n# \u2554\u2550\u2561 9008cc1d-e7c2-4b24-ad08-968c085baa36\nstruct DualUntyped\n    value\n    deriv\nend\n    \n\n# \u2554\u2550\u2561 d5cb6844-6f9d-422e-a241-96450aff70f5\nDualUntyped(\"hello\", \"David\")\n\n# \u2554\u2550\u2561 7b2f03b4-d3dd-4fa6-a569-c878fc9f6557\nstruct DualBig\n    value::BigFloat\n    deriv::BigFloat\nend\n    \n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4bdb5bfc-82c2-4de5-982a-4a69872749d1\nDual3(\"a\", \"b\")\n\n# \u2554\u2550\u2561 9c05cca8-76d9-4abd-8774-28e7f41d3b09\nDual3(big\"1.0\", big\"1.4\")\n\n# \u2554\u2550\u2561 05db96f7-3eeb-47aa-a4dc-dd67b0f02a2b\nDual3(1, 3.1)\n\n# \u2554\u2550\u2561 b490d647-85f5-4b82-ab29-2d18ce1c7db4\nmethods(Dual3)\n\n# \u2554\u2550\u2561 d981b89c-4833-4e38-9f80-246ed5f09445\nDual3(3, 4.5)\n\n# \u2554\u2550\u2561 9bfe7470-afec-4a24-9f96-43272e2f9ecd\npromote(1, 3.4)\n\n# \u2554\u2550\u2561 61cc131f-2d02-4de1-b79a-9105d6decc15\n@which promote_type(Int, Float64)\n\n# \u2554\u2550\u2561 a5c1c463-2393-499d-852c-16e69549819a\nComplex(3, 4.5)\n\n# \u2554\u2550\u2561 749ba068-6deb-4a7d-a650-412e5fbdb670\n@which Complex(3, 4.5)\n\n# \u2554\u2550\u2561 226f5af6-702f-431c-a269-5dd4cafa2699\nv = Dual(3, 4)\n\n# \u2554\u2550\u2561 c3831c37-8e09-4846-963d-27e1d4a824ac\nv isa Number\n\n# \u2554\u2550\u2561 fd8bf8f8-68dd-4925-aa9b-8eca1937c577\nsubtypes(Real)\n\n# \u2554\u2550\u2561 e3d64165-170e-4ee0-a9bc-ef759ce6afd7\nsubtypes(AbstractFloat)\n\n# \u2554\u2550\u2561 713dc49e-6038-40b7-a917-299277f7ea7a\nsubtypes(Float64)\n\n# \u2554\u2550\u2561 68d54b7c-4003-49e8-b2f9-666b882a5737\nisconcretetype(Float64)\n\n# \u2554\u2550\u2561 7ae57ebb-d6bc-4b9b-913a-f9c4bb11d380\nq = 3.1\n\n# \u2554\u2550\u2561 99dd8229-8658-4efe-9133-3eb8cd00b6b3\ntypeof(q)\n\n# \u2554\u2550\u2561 ef28ca54-38dd-4e8e-a5e8-897c802f81e1\nq isa AbstractFloat\n\n# \u2554\u2550\u2561 a31cfb26-9914-441c-aea8-6f341f2635fb\ngg(x::AbstractFloat) = sqrt(x)\n\n# \u2554\u2550\u2561 b05dcbc4-0149-48a3-8533-1bd6515d0b32\ngg(x::T) where {T <: AbstractFloat} = sqrt(x)\n\n# \u2554\u2550\u2561 f44efbd4-7ce2-44db-ac0e-eeb4aeafef70\ngg(\u03c0)\n\n# \u2554\u2550\u2561 7df9a91e-01d4-471f-9ad5-55ac56c245d3\nstruct Hello{T}\n    a::T\n    b::T\n    c::T\nend\n\n# \u2554\u2550\u2561 ef1c3d05-7020-4339-b431-63ad63b244cc\nadd(x::Hello, y::Hello) = x.a + y.a, x.b + y.b, ...\n\n# \u2554\u2550\u2561 186148a4-698e-460b-82dd-7b203698de45\nw = Hello(3, 4, 45)\n\n# \u2554\u2550\u2561 b9ac03c2-d93e-4372-a3cb-4568baf015bb\nmyfields = fieldnames(typeof(w))\n\n# \u2554\u2550\u2561 522a7a5c-8400-4e1b-9ebd-6d76b33cb87f\ngetfield(w, :a)\n\n# \u2554\u2550\u2561 d70384a3-51fc-4f71-a3d6-d14b03719495\nx\n\n# \u2554\u2550\u2561 ab382c7f-933e-4611-af23-fe31967ff8cc\n[getfield(x, name) for name in myfields]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 babed906-7888-431b-8b11-d6e5889073fa\ngetfield.(myfields)\n\n# \u2554\u2550\u2561 d7e3e2b2-6f3f-4761-9141-924ae1448343\n\n\n# \u2554\u2550\u2561 ce4bd2c6-6269-47e3-8f43-50969a19487a\nx::Dual ^ n::Integer = ..\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 eea59dfb-acc7-4d56-82b2-59f0ed40afc7\nimport Base: +, *\n\n# \u2554\u2550\u2561 b0c794fb-0d77-4667-9d47-0bcdfaa8fecb\nbegin\n\timport Base: ^\n\t^(x::Dual, n::Integer) = Base.power_by_squaring(x, n)\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500cac0bc38-ead9-4f99-a939-fc2645874efd\n# \u2560\u2550ecb2b8d9-ceda-4008-8137-b29bd7ef3ba9\n# \u255f\u2500b4f0668c-8b25-4588-9176-52bc7bfe797b\n# \u255f\u25000ece0b55-ede7-4db1-9b48-61e1d4534761\n# \u255f\u25006dcc01fe-c551-43d2-930b-ff1c93d15077\n# \u2560\u25500d352bcc-dfc1-429f-ad6c-40dc8c4cd038\n# \u2560\u255081863f06-8dac-48fd-a6e1-cf5df30c63f6\n# \u2560\u25503de40205-6b5d-4d99-b886-1a1dc6a07955\n# \u2560\u2550d4c280cf-910c-4bbf-8dca-b01b14711296\n# \u2560\u25507082e444-6268-4721-a278-2511a22daf68\n# \u2560\u255043538919-4349-43f1-a196-759fe65d3be3\n# \u255f\u2500e0c1df0c-ff62-4982-8f3d-3ccbb44b8d2f\n# \u255f\u2500e6281275-0b87-47f4-a081-bb366ced3466\n# \u255f\u25006056ff4a-858f-447c-85cc-0f3f6e0e53ca\n# \u255f\u2500db17c624-91b6-44b1-bd10-4d72f4cb9776\n# \u255f\u2500b3b15bf5-115d-4831-9115-36c88e9b899c\n# \u255f\u250070843c81-6abe-40b2-8d0b-8d779fccedc8\n# \u2560\u255082c79506-68ea-41dd-888d-840371c08430\n# \u255f\u2500291315e0-ad0e-4a57-b100-2baa5af04c04\n# \u255f\u2500f2421fbf-5cfc-4332-be60-b61fa4e02d8c\n# \u2560\u2550710612bd-4856-4e51-b2d6-2bdc972f196d\n# \u255f\u250070eb5167-6288-4f84-b140-21b4b329cb45\n# \u2560\u25509fb42f3c-c7ff-4f31-b5e6-9e96de16bac5\n# \u2560\u255007808ac8-c910-4e92-ac34-c9ff225f4be8\n# \u255f\u25008777c6a7-90e3-4dc7-ab61-3d12531f2ea9\n# \u2560\u25505488c55f-8d0a-4c9b-8f8b-40ed4fe14e67\n# \u2560\u25504f5e5eea-13df-477e-baea-c37ab6074aea\n# \u2560\u2550da932afe-990f-4ca7-aa81-9d85e1ca3bac\n# \u2560\u2550fac29cb2-dc57-4a06-9728-567169ac3768\n# \u2560\u25504118613c-e58a-4f63-81d1-0e197e66cf98\n# \u2560\u2550ac8fa4de-d8ef-44f2-b709-aceb1e0ecb04\n# \u2560\u255092aa5678-478c-4cb6-9187-3285534aac8c\n# \u2560\u255004a21e57-a45c-4e4b-977a-42c6ee228b4a\n# \u2560\u2550915bfb27-7234-43ea-a052-093f89d7bdcd\n# \u255f\u25009b213fb9-382a-4c5b-93fe-22252d29d0c6\n# \u255f\u25008eed2b5c-dde2-437e-8383-4ed206ce72de\n# \u2560\u2550eea59dfb-acc7-4d56-82b2-59f0ed40afc7\n# \u2560\u255062a97a4b-dfa6-404d-958b-b7b4ab7d25ca\n# \u2560\u25509b0d361a-8c30-4ec0-a183-ac3890895f0e\n# \u2560\u25509b8f41b5-9ade-4f34-8d09-cb548bd6c242\n# \u2560\u25505b29f183-bda6-4ffb-bb78-5199980039d3\n# \u255f\u2500fc624260-ba8a-4057-8a1f-2659e2343654\n# \u2560\u2550abcbc0a1-33e7-430f-b0a8-e8b65c8666b2\n# \u2560\u255017498a94-5db9-4c5e-9268-e588fddeae54\n# \u2560\u2550c847f0c2-1eac-4900-b80c-7f89846b2924\n# \u2560\u25506caea9da-3edc-4309-bad8-f348693960b2\n# \u2560\u255017cce3ab-1b4f-402d-bcc3-c7905360a441\n# \u2560\u2550526a204c-6a72-4cde-900a-568667e45c64\n# \u255f\u250086aa82b1-caae-4124-b48a-14497420f471\n# \u255f\u2500e359dd62-65f0-4033-98c2-aff400ed0bb7\n# \u2560\u255086141559-f6f4-43a6-8291-550adf31b25b\n# \u2560\u2550cee6af83-0079-4acd-9e14-cd7b7eb6947f\n# \u2560\u2550555aa973-a5ce-41f9-aab7-261a697758cc\n# \u2560\u25504e222c6a-054b-41e6-bef4-b0726344ee94\n# \u255f\u2500a1b1b945-ba2e-4668-8698-4df02660d379\n# \u2560\u25508857e0aa-da38-4ae6-8ef9-efa66dd51cfc\n# \u2560\u2550ad671591-a625-4de2-9b18-84c7773cb4b8\n# \u2560\u2550053e90a7-5fa6-4063-9634-63d48ee16690\n# \u2560\u2550d521f0e3-1636-4e8b-b8f3-639a90780690\n# \u255f\u2500b7b81d9d-354d-4ec0-b50c-302dbcb8f0c4\n# \u2560\u2550d67fa8a9-f43e-4eca-bb0e-1603c9f7da5d\n# \u255f\u25003bc3d5a3-9b9f-4d07-9d59-f24d5c005038\n# \u255f\u2500fd34be78-af76-4d46-bdbd-19fd19155785\n# \u255f\u2500caccd695-118c-46a8-b59f-376e4cbc83ce\n# \u2560\u25506418d0a4-8dd3-4816-8e5b-092cb769ebb6\n# \u2560\u25508ebb42e9-11ec-434d-87c9-4259c26f6526\n# \u2560\u255084b6a870-4515-4e6c-b306-d6b6d2a0fb8d\n# \u2560\u2550a0865cb0-7077-44ff-a130-eb73cbbc3179\n# \u2560\u2550f1fc7637-4804-4fc1-81ac-14874e66f9d6\n# \u2560\u2550ded7adc0-619f-4735-bd93-9c26c4c21858\n# \u2560\u25501284374b-ab26-46b8-a74e-119655f5112e\n# \u2560\u2550420c0ef0-3f7e-4044-be30-c2873636c6e8\n# \u2560\u2550f426bed2-05f1-4598-9817-bb90262911ef\n# \u2560\u255009bfa122-ca5b-4b4a-a9eb-09b1b5482a76\n# \u2560\u2550d08a434c-c816-4f43-9c93-2d0eda57723c\n# \u2560\u2550b0c794fb-0d77-4667-9d47-0bcdfaa8fecb\n# \u2560\u25504e06b4f6-9753-4847-8c6c-120208520dc5\n# \u2560\u2550131373df-8e58-49b0-be5f-3cd8d8deb61d\n# \u2560\u255076a7a87b-0283-4a85-9d88-0eec06ef689f\n# \u2560\u2550d608bc38-5653-4ad5-b6e4-6b2236299e4c\n# \u2560\u2550ce4bd2c6-6269-47e3-8f43-50969a19487a\n# \u255f\u2500bf697142-0eaf-4717-9434-eaa89946beb4\n# \u255f\u2500108212df-c86f-4b75-8576-65f3964687e9\n# \u255f\u2500eb94cc27-ac9e-4202-acdc-248809eebdb9\n# \u2560\u2550d7f6c80a-4922-42be-9bce-e493e603c373\n# \u255f\u250070ec3ada-f7ae-4526-be35-5aa8cd4533ca\n# \u255f\u25005011cf98-128e-4c94-bae0-109016427c50\n# \u255f\u2500d57937d8-3f1e-4f85-bf6b-afc8cfe3e99d\n# \u2560\u2550df1c033c-8a99-4b45-bc9c-3287a3a959ec\n# \u255f\u2500b0902a74-01e0-456a-a027-a5030d494d7f\n# \u255f\u25009226e5a3-4445-4420-9b54-be31468e6b07\n# \u2560\u2550ccc258fa-c928-4175-a48e-bd72b7d22f31\n# \u2560\u2550c9f3dde8-7989-45e8-9831-894d82e57e90\n# \u2560\u25502d3876d6-5fcf-4bfb-8dba-4bdf252c73fc\n# \u2560\u2550a0d7a33a-e067-4e69-9c70-14005f41a2c6\n# \u2560\u2550812149d8-0040-4d67-b2a2-f1304af4b225\n# \u255f\u250075fa60fe-6583-4a6a-b6b0-06fb81006218\n# \u255f\u25004146cf8f-ab2f-457d-97ef-e6d39e93246e\n# \u255f\u25003e61a354-ca21-410b-b422-92ea362b8c10\n# \u2560\u2550907f65aa-e1a1-4838-a1a0-cdaa0a1cfa45\n# \u2560\u2550fc5839ce-935a-46aa-bbe7-01f203b0fdb5\n# \u2560\u2550c445bab5-c012-4890-89bc-e7d6950fa7b4\n# \u2560\u25509008cc1d-e7c2-4b24-ad08-968c085baa36\n# \u2560\u2550d5cb6844-6f9d-422e-a241-96450aff70f5\n# \u2560\u25507b2f03b4-d3dd-4fa6-a569-c878fc9f6557\n# \u2560\u255097097783-2948-4e9c-b769-8085c7943227\n# \u2560\u25504bdb5bfc-82c2-4de5-982a-4a69872749d1\n# \u2560\u25509c05cca8-76d9-4abd-8774-28e7f41d3b09\n# \u2560\u255005db96f7-3eeb-47aa-a4dc-dd67b0f02a2b\n# \u2560\u2550b490d647-85f5-4b82-ab29-2d18ce1c7db4\n# \u2560\u2550d981b89c-4833-4e38-9f80-246ed5f09445\n# \u2560\u25509bfe7470-afec-4a24-9f96-43272e2f9ecd\n# \u2560\u255061cc131f-2d02-4de1-b79a-9105d6decc15\n# \u2560\u2550a5c1c463-2393-499d-852c-16e69549819a\n# \u2560\u2550749ba068-6deb-4a7d-a650-412e5fbdb670\n# \u2560\u2550226f5af6-702f-431c-a269-5dd4cafa2699\n# \u2560\u2550c3831c37-8e09-4846-963d-27e1d4a824ac\n# \u2560\u2550fd8bf8f8-68dd-4925-aa9b-8eca1937c577\n# \u2560\u2550e3d64165-170e-4ee0-a9bc-ef759ce6afd7\n# \u2560\u2550713dc49e-6038-40b7-a917-299277f7ea7a\n# \u2560\u255068d54b7c-4003-49e8-b2f9-666b882a5737\n# \u2560\u25507ae57ebb-d6bc-4b9b-913a-f9c4bb11d380\n# \u2560\u255099dd8229-8658-4efe-9133-3eb8cd00b6b3\n# \u2560\u2550ef28ca54-38dd-4e8e-a5e8-897c802f81e1\n# \u2560\u2550a31cfb26-9914-441c-aea8-6f341f2635fb\n# \u2560\u2550f44efbd4-7ce2-44db-ac0e-eeb4aeafef70\n# \u2560\u2550b05dcbc4-0149-48a3-8533-1bd6515d0b32\n# \u2560\u25507df9a91e-01d4-471f-9ad5-55ac56c245d3\n# \u2560\u2550ef1c3d05-7020-4339-b431-63ad63b244cc\n# \u2560\u2550186148a4-698e-460b-82dd-7b203698de45\n# \u2560\u2550b9ac03c2-d93e-4372-a3cb-4568baf015bb\n# \u2560\u2550522a7a5c-8400-4e1b-9ebd-6d76b33cb87f\n# \u2560\u2550d70384a3-51fc-4f71-a3d6-d14b03719495\n# \u2560\u2550ab382c7f-933e-4611-af23-fe31967ff8cc\n# \u2560\u25508df1bf08-5ee2-4cfe-a273-62c71dc9b8fb\n# \u2560\u2550babed906-7888-431b-8b11-d6e5889073fa\n# \u2560\u2550d7e3e2b2-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\u2096 = X[k, :]\n        # ignore if the k-th row is zeros\n        all(iszero, x\u2096) && continue\n\n        # w\u2096 is the column indices where the k-th row of x\u2096 is non-zero,\n        # which is equivalent to [i for i in N if x\u2096[i] != 0]\n        w\u2096 = findall(!iszero, x\u2096)\n\n        # E\u2096 * \u03a9\u2096 implies a selection of error columns that\n        # correspond to examples that use the atom D[:, k]\n        E\u2096 = error_matrix(Y, D, X, k)\n        \u03a9\u2096 = sparse(w\u2096, 1:length(w\u2096), ones(length(w\u2096)), N, length(w\u2096))\n        # Note that S is a vector that contains diagonal elements of\n        # a matrix \u0394 such that E\u2096 * \u03a9\u2096 == U * \u0394 * V.\n        # Non-zero entries of X are set to\n        # the first column of V multiplied by \u0394(1, 1)\n        U, S, V = svd(E\u2096 * \u03a9\u2096, full=true)\n        D[:, k] = U[:, 1]\n        X[k, w\u2096] = 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 \u2248 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\u00f6ssler-Lorenz system.\nThe 3D R\u00f6ssler attractor is coupled to  a 3D Lorenz attractor such that the\nsecond component  (``x_2``) of the R\u00f6ssler 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\u2081`, `a\u2082`, `a\u2083`, `b\u2081`, `b\u2082`, `b\u2083`. The default\nvalues of these constants are as defined in Krakovsk\u00e1 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\u00e1, 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\u2081, a\u2082, a\u2083, b\u2081, b\u2082, b\u2083, c = (p...,)\n    x\u2081, x\u2082, x\u2083, y\u2081, y\u2082, y\u2083 = (u...,)\n\n    dx\u2081 = a\u2081*(x\u2082 + x\u2083)\n    dx\u2082 = a\u2082*(x\u2081 + 0.2*x\u2082)\n    dx\u2083 = a\u2082*(0.2 + x\u2083*(x\u2081 - a\u2083))\n    dy\u2081 = b\u2081*(y\u2082 - y\u2081)\n    dy\u2082 = y\u2081*(b\u2082 - y\u2083) - y\u2082 + c*x\u2082^2\n    dy\u2083 = y\u2081*y\u2082 - b\u2083*y\u2083\n    return SVector{6}(dx\u2081, dx\u2082, dx\u2083, dy\u2081, dy\u2082, dy\u2083)\nend\n\nfunction rossler_lorenz(u\u2080, a\u2081, a\u2082, a\u2083, b\u2081, b\u2082, b\u2083, c)\n    p = [a\u2081, a\u2082, a\u2083, b\u2081, b\u2082, b\u2083, c]\n    ContinuousDynamicalSystem(eom_rossler_lorenz, u\u2080, p)\nend\n\n\"\"\"\n    rossler_lorenz(;u\u2080 = rand(6), a\u2081 = -6, a\u2082 = 6, a\u2083 = 2.0,\n        b\u2081 = 10, b\u2082 = 28, b\u2083 = 8/3, c = 2) -> ContinuousDynamicalSystem\n\nInitialise a R\u00f6ssler-Lorenz system consisting of two independent 3D subsystems:\none R\u00f6ssler attractor and one Lorenz attractor. They are coupled such that the\nsecond component (`x\u2082`) of the R\u00f6ssler system unidirectionally forces the\nsecond component (`y\u2082`) of the Lorenz system.\n\nThe implementation here allows for tuning the parameters of each subsystem by\nintroducing the constants `a\u2081`, `a\u2082`, `a\u2083`, `b\u2081`, `b\u2082`, `b\u2083`. The default\nvalues are as in Krakovsk\u00e1 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\u00e1, 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\u2080 = rand(6), a\u2081 = -6, a\u2082 = 6, a\u2083 = 2.0, b\u2081 = 10, b\u2082 = 28, b\u2083 = 8/3, c = 2) =\n    rossler_lorenz(u\u2080, a\u2081, a\u2082, a\u2083, b\u2081, b\u2082, b\u2083, 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, \u03c9 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,\u03c9,M0)\n\t\tmean_anom = t*2\u03c0/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(\u03c9+true_anom)+e*cos(\u03c9))\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 \u2265 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 \u2265 x\n  @assert n \u2265 y\n\n  return (x, y)\nend\n\n\n#Construct a permutation matrix for a `n \u00d7 n` matrix\n#in vector form where we transpose in `l \u00d7 l` blocks.\n\nfunction partialtransposematrix(n::Integer, l::Integer)\n  @assert n % l == 0 \"l should divide n\"\n  @assert n \u2265 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(\u03c1::Union{AbstractArray, AbstractExpr}, systems::Vector, dim::Vector)\n  result = \u03c1\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(\u03c1::Union{AbstractArray, AbstractExpr}, sys::Integer = 2, dim::Vector = [])\n  # do naive partial transposition\n  if dim == []\n    l = round(Int, sqrt(size(\u03c1)[1]))\n    if sys == 2\n      return partialtranspose(\u03c1, l, naive = true)\n    else\n      dim = [l; l]\n    end\n  end\n\n\n  @assert 1 \u2264 sys \u2264 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(\u03c1, 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 \u00d7 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(\u03c1::Union{AbstractArray, AbstractExpr}, systems::Integer = 2, dim::Vector = []; naive::Bool = false)\n  if naive\n    return partialtransposenaive(\u03c1, systems)\n  end\n\n  return partialtransposesystem(\u03c1, 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 \u00d7 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(\u03c1::Union{AbstractExpr, AbstractArray, Convex.Variable}, l::Integer)\n  # if the input is sparse, keep the output sparse as well\n  if !isa(\u03c1, Convex.Variable) && !isa(\u03c1, AbstractExpr) && issparse(\u03c1)\n    vectorised = sparsevec(\u03c1)\n  else\n    vectorised = vec(\u03c1)\n  end\n  n = size(\u03c1)[1]\n\n  @assert n % l == 0 \"l should divide n\"\n  @assert n \u2265 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 Test, Flux, NeuralNetDiffEq\r\nusing DiffEqDevTools\r\n\r\n# Run a solve on scalars\r\nlinear = (u,p,t) -> cos(2pi*t)\r\ntspan = (0.0f0, 1.0f0)\r\nu0 = 0.0f0\r\nprob = ODEProblem(linear, u0 ,tspan)\r\nchain = Flux.Chain(Dense(1,5,\u03c3),Dense(5,1))\r\nopt = Flux.ADAM(0.1, (0.9, 0.95))\r\nsol = solve(prob, NeuralNetDiffEq.NNODE(chain,opt), dt=1/20f0, verbose = true,\r\n            abstol=1e-10, maxiters = 200)\r\n\r\n# Run a solve on vectors\r\nlinear = (u,p,t) -> [cos(2pi*t)]\r\ntspan = (0.0f0, 1.0f0)\r\nu0 = [0.0f0]\r\nprob = ODEProblem(linear, u0 ,tspan)\r\nchain = Flux.Chain(Dense(1,5,\u03c3),Dense(5,1))\r\nopt = Flux.ADAM(0.1, (0.9, 0.95))\r\nsol = solve(prob, NeuralNetDiffEq.NNODE(chain,opt), dt=1/20f0, abstol=1e-10,\r\n            verbose = true, maxiters=200)\r\n\r\n#Example 1\r\nlinear = (u,p,t) -> @. t^3 + 2*t + (t^2)*((1+3*(t^2))/(1+t+(t^3))) - u*(t + ((1+3*(t^2))/(1+t+t^3)))\r\nlinear_analytic = (u0,p,t) -> [exp(-(t^2)/2)/(1+t+t^3) + t^2]\r\nprob = ODEProblem(ODEFunction(linear,analytic=linear_analytic),[1f0],(0.0f0,1.0f0))\r\nchain = Flux.Chain(Dense(1,5,\u03c3),Dense(5,1))\r\nopt = Flux.ADAM(0.1, (0.9, 0.95))\r\nsol  = solve(prob,NeuralNetDiffEq.NNODE(chain,opt),verbose = true, dt=1/5f0)\r\nerr = sol.errors[:l2]\r\nsol  = solve(prob,NeuralNetDiffEq.NNODE(chain,opt),verbose = true, dt=1/20f0)\r\nsol.errors[:l2]/err < 0.5\r\n\r\n#=\r\ndts = 1f0 ./ 2f0 .^ (6:-1:2)\r\nsim = test_convergence(dts, prob, NeuralNetDiffEq.NNODE(chain, opt))\r\n@test abs(sim.\ud835\udcaaest[:l2]) < 0.1\r\n@test minimum(sim.errors[:l2]) < 0.5\r\n=#\r\n\r\n#Example 2\r\nlinear = (u,p,t) -> -u/5 + exp(-t/5).*cos(t)\r\nlinear_analytic = (u0,p,t) ->  exp(-t/5)*(u0 + sin(t))\r\nprob = ODEProblem(ODEFunction(linear,analytic=linear_analytic),0.0f0,(0.0f0,1.0f0))\r\nchain = Flux.Chain(Dense(1,5,\u03c3),Dense(5,1))\r\nopt = Flux.ADAM(0.1, (0.9, 0.95))\r\nsol  = solve(prob,NeuralNetDiffEq.NNODE(chain,opt),verbose = true, dt=1/5f0)\r\nerr = sol.errors[:l2]\r\nsol  = solve(prob,NeuralNetDiffEq.NNODE(chain,opt),verbose = true, dt=1/20f0)\r\nsol.errors[:l2]/err < 0.5\r\n\r\n#=\r\ndts = 1f0 ./ 2f0 .^ (6:-1:2)\r\nsim = test_convergence(dts, prob, NeuralNetDiffEq.NNODE(chain, opt))\r\n@test abs(sim.\ud835\udcaaest[:l2]) < 0.5\r\n@test minimum(sim.errors[:l2]) < 0.1\r\n=#\r\n", "meta": {"hexsha": "506a02d7a12d88a38ef39f95f5f15d2ff68f9585", "size": 2132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/NNODE_tests.jl", "max_stars_repo_name": "alhajri/NeuralNetDiffEq.jl", "max_stars_repo_head_hexsha": "8a4c289a6a6cb633077c93f018bfac675901bcff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-17T17:17:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-17T17:17:20.000Z", "max_issues_repo_path": "test/NNODE_tests.jl", "max_issues_repo_name": "alhajri/NeuralNetDiffEq.jl", "max_issues_repo_head_hexsha": "8a4c289a6a6cb633077c93f018bfac675901bcff", "max_issues_repo_licenses": ["MIT"], "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/NNODE_tests.jl", "max_forks_repo_name": "alhajri/NeuralNetDiffEq.jl", "max_forks_repo_head_hexsha": "8a4c289a6a6cb633077c93f018bfac675901bcff", "max_forks_repo_licenses": ["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.1355932203, "max_line_length": 101, "alphanum_fraction": 0.6191369606, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7551914523087402}}
{"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    \u03bc = 0.0 # mean is zero\n    \u03c3 = sqrt(2) # D=1\n    \u03981 = 1.0\n    \u03982 = 1.0+abs(c)\n\n    W1 = OrnsteinUhlenbeckProcess(\u03981,\u03bc,\u03c3,0.0,1.0)\n    W2 = OrnsteinUhlenbeckProcess(\u03982,\u03bc,\u03c3,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\u03b4 = 0.1\n\nA, \u03c6, yrec = hants(\n    y, fet, dod, \u03b4; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=nothing\n)\ny_reconstruct = reconstruct(A, \u03c6, nbase)\n\nA_Hi, \u03c6_Hi, yrec_Hi = hants(\n    y, fet, dod, \u03b4; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=:Hi\n)\ny_reconstruct_Hi = reconstruct(A_Hi, \u03c6_Hi, nbase)\n\nA_Lo, \u03c6_Lo, yrec_Lo = hants(\n    y, fet, dod, \u03b4; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=:Lo\n)\ny_reconstruct_Lo = reconstruct(A_Lo, \u03c6_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": "using Test\nusing TestSetExtensions\nusing Qaintessent\nusing StatsBase\nusing LinearAlgebra\n\n@testset ExtendedTestSet \"util pauli_vector\" begin\n    n1, n2, n3 = sample(1:15, 3, replace=true)\n    @test all(Qaintessent.pauli_vector(n1, n2, n3) .\u2248 matrix(X) * n1 + matrix(Y) * n2 + matrix(Z) * n3)\nend\n\n@testset ExtendedTestSet \"util intlog2\" begin\n    @test_throws ErrorException(\"Logarithm of 0 is undefined\") Qaintessent.intlog2(0)\n    @test_throws ErrorException(\"Logarithm of negative number is undefined\") Qaintessent.intlog2(-30)\n    N = rand(1:50)\n    @test Qaintessent.intlog2(2^N) == N\n    N = rand(1:200)    \n    @test Qaintessent.intlog2(N) <= log(2, N)\n    @test Qaintessent.intlog2(N) >= (log(2, N) - 1)\nend\n\n@testset ExtendedTestSet \"util binary_digits\" begin\n    n1 = abs(rand(Int, 1)[])\n    # n1 = 5\n    M = Qaintessent.intlog2(n1) + 1\n    bd = Qaintessent.binary_digits(M, n1)\n    x = 0\n    count = 0\n    \n    for i in bd\n        x+= i * 2^count\n        count += 1\n    end\n\n    @test x \u2248 n1\n    @test Qaintessent.binary_to_int(bd) \u2248 n1\nend\n\n@testset ExtendedTestSet \"util binary_digits!\" begin\n    # n1 = abs(rand(Int, 1)[])\n    n1 = 5\n    M = Qaintessent.intlog2(n1) + 1\n    m = BitArray{1}(undef, M)\n    bd = Qaintessent.binary_digits!(m, n1)\n    x = 0\n    count = 0\n    \n    for i in bd\n        x+= i * 2^count\n        count += 1\n    end\n\n    @test x \u2248 n1\nend\n\n\n@testset ExtendedTestSet \"util quaternary_digits\" begin\n    n1 = abs(rand(Int, 1)[])\n    M = Qaintessent.intlog2(n1)\n    qd = Qaintessent.quaternary_digits(M, n1)\n    x = 0\n    count = 0\n    for i in qd\n        x+= i * 4^count\n        count += 1\n    end\n    @test x \u2248 n1\nend\n\n@testset ExtendedTestSet \"util quaternary_digits!\" begin\n    n1 = abs(rand(Int, 1)[])\n    M = Qaintessent.intlog2(n1)\n    m = Vector{Int}(undef, M)\n    qd = Qaintessent.quaternary_digits!(m, n1)\n    x = 0\n    count = 0\n    for i in qd\n        x+= i * 4^count\n        count += 1\n    end\n    @test x \u2248 n1\nend\n\n@testset ExtendedTestSet \"util gramm_schmidt!\" begin \n    N = rand(4:10)\n\n    @testset \"util gramm_schmidt! complex\" begin\n        a = rand(ComplexF64, (N,N))\n\n        Qaintessent.gramm_schmidt!(a)\n\n        for i in 1:N\n            for j in (i+1):N\n                @test norm(dot(a[:, i], a[:, j])) < 1e-12\n            end\n            @test dot(a[:, i], a[:, i]) \u2248 1\n        end\n    end\n\n    @testset \"util gramm_schmidt! float\" begin\n        a = rand(Float64, (N,N))\n\n        Qaintessent.gramm_schmidt!(a)\n\n        for i in 1:N\n            for j in (i+1):N\n                @test norm(dot(a[:, i], a[:, j])) < 1e-12\n            end\n            @test dot(a[:, i], a[:, i]) \u2248 1\n        end\n    end\nend\n\n##==----------------------------------------------------------------------------------------------------------------------\n\n\n@testset ExtendedTestSet \"util reduced density matrix\" begin\n    N = 4\n    \u03c8 = randn(ComplexF64, 2^N)\n    \u03c7 = randn(ComplexF64, 2^N)\n    # full density matrix |\u03c8\u27e9\u27e8\u03c7|\n    \u03c1 = reshape(kron(conj(\u03c7), \u03c8), 2^N, 2^N)\n\n    id = Matrix{ComplexF64}(I, 2, 2)\n    A = randn(ComplexF64, 2, 2)\n    B = randn(ComplexF64, 2, 2)\n    @testset ExtendedTestSet \"reduced density matrix correctness\" begin\n        @test sum(kron(A, B) .* rdm(N, (4, 2), \u03c8, \u03c7)) \u2248 sum(kron(B, id, A, id) .* \u03c1)\n    end\n\n    @testset ExtendedTestSet \"reduced density matrix exceptions\" begin\n        @test_throws ErrorException(\"Need at least one wire to act on.\") rdm(N, (), \u03c8, \u03c7)\n        @test_throws ErrorException(\"Number of gate wires cannot be larger than total number of wires.\") rdm(N, (1, 2, 3, 4, 5), \u03c8, \u03c7)\n        @test_throws ErrorException(\"Wire indices must be unique.\") rdm(N, (2, 2), \u03c8, \u03c7)\n        @test_throws ErrorException(\"Wire index cannot be smaller than 1.\") rdm(N, (-1, 2), \u03c8, \u03c7)\n        @test_throws ErrorException(\"Wire index cannot be larger than total number of wires.\") rdm(N, (5, 1), \u03c8, \u03c7)\n    end\nend", "meta": {"hexsha": "a5ec27c8c56146de76cc5c866b5f6bcd0c37314a", "size": 3875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_util.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": "test/test_util.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": "test/test_util.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": 28.0797101449, "max_line_length": 134, "alphanum_fraction": 0.5672258065, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7551914462951792}}
{"text": "import PyPlot\nconst plt = PyPlot\n\nfunction eval_LF1d_p( \u03b1::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[\u03b1])/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 \u03b1 = 1:Nbasis\n        for l = 1:Nbasis\n            k = -N + (l-1)\n            x = grid_x[\u03b1]\n            T[\u03b1,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    \u03c9 = 2*pi/L\n    f = cos(\u03c9*x)*sin(2*\u03c9*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( \u03b1, T, x )\n#    Nbasis = size(T)[1]\n#    f = 0.0 + im*0.0\n#    for l = 1:Nbasis\n#        f = f + T'[l,\u03b1]*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 \u03b1 = 1:Nbasis\n        grid_x[\u03b1] = L/Nbasis*(\u03b1-N-1)\n    end\n    \u0394 = 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(\u0394))\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(\u0394), L, grid_x, x) )\n\n    FBR_ex_coefs = inv(T)*ex_coefs*sqrt(\u0394)\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": "@testset \"Construction\" begin\n\n    # basic constructor\n    xs = [1,2,3]\n    f(x) = x^2\n    q = fit(Newton, xs, f)\n    @test all(f.(xs) .\u2248 q.(xs)) \n    \n    # test tableau\n    @test all(q.tableau .\u2248   [1 3 1; 0 4 5; 0 0 9])\n\n    # test one, zero, variable\n    x = variable()\n    @test one(q)(x) == one(x)\n    @test iszero(zero(q))\n    @test variable(q)(x) == x\n    \nend\n\n@testset \"Conversion\" begin\n\n    xs = [1,2,3]\n    f(x) = x^2\n    p = fit(Newton, xs, f)\n    q = convert(Polynomial, p)\n    @test coeffs(q)  == [0,0,1]\n\nend\n\n@testset \"Evaluation\" begin\n\n    xs = sort(rand(5))\n    ys = sin.(xs)\n    p = fit(Newton, xs, sin)\n    @test p.(xs) \u2248 sin.(xs)\n    us = rand(5)\n    @test maximum(abs.([p(x) - sin(x) for x in us])) <= 1e-1\n\nend\n\n\n@testset \"Arithmetic\" begin\n\n    p = fit(Newton, [1,2,3], x -> x^2)\n    q = fit(Newton, [2,3,4,5], x -> x^3)\n\n    us = rand(5)\n\n    @test all(p.(us) + q.(us) .\u2248 (p + q).(us))\n    @test p.(us) .* q.(us) \u2248 (p * q).(us)  \n\n\nend\n\n@testset \"Elementwise operations\" begin\n\n    p = fit(Newton, [1,2,3,4], x -> x^2)\n    p + 1\n    -p\n    2p\n\nend\n\n\n\n\n@testset \"roots\" begin\n\n    q = fit(Newton, [2,3,4,5], x -> (x-1)*(x-1/2)*(x+1/2))\n    @test all(roots(q) .\u2248 [-1/2, 1/2, 1])\n\nend\n", "meta": {"hexsha": "33b8191fa8037b759cd9a2dac19106e08c9ac588", "size": 1210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Newton.jl", "max_stars_repo_name": "rurz/SpecialPolynomials.jl", "max_stars_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_stars_repo_licenses": ["MIT"], "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/Newton.jl", "max_issues_repo_name": "rurz/SpecialPolynomials.jl", "max_issues_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_issues_repo_licenses": ["MIT"], "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": "rurz/SpecialPolynomials.jl", "max_forks_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_forks_repo_licenses": ["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.5753424658, "max_line_length": 60, "alphanum_fraction": 0.4851239669, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7551644885788565}}
{"text": "using MultipleViewGeometry, Test, LinearAlgebra\nusing MultipleViewGeometry.ModuleTypes\nusing StaticArrays, Calculus, GeometryTypes\nusing MultipleViewGeometry.ModuleSyntheticData\n\n# Fix random seed.\nRandom.seed!(1234)\n# Construct two camera matrices and parametrise two planar surfaces.\nf = 50\nimage_width = 640 / 10\nimage_height = 480 / 10\n\ud835\udc0a\u2081 = @SMatrix [f 0 0 ;\n               0 f 0 ;\n               0 0 1 ]\n\ud835\udc11\u2081 = SMatrix{3,3,Float64,9}(rotxyz(0, 25*(pi/180), 0))\n\ud835\udc2d\u2081 = [-30.0, 0.0, -5.0]\n\n\ud835\udc0a\u2082 = @SMatrix [f 0 0 ;\n               0 f 0 ;\n               0 0 1 ]\n\n\ud835\udc11\u2082 = SMatrix{3,3,Float64,9}(rotxyz(0, -25*(pi/180), 0))\n\ud835\udc2d\u2082 = [30.0, 0.0, 5.0]\n\n# Normals and distance from origin\n\ud835\udc27\u2081 = [0.0, 0.0, 1.0]\nd\u2081 = 55.0\n\n# Normals and distance from origin\n\ud835\udc27\u2081 = [0.0, 0.0, 1.0]\nd\u2081 = 55.0\n\n\ud835\udc27\u2082 = [0.5, -0.2, 2.0]\nd\u2082 = 145.0\n\n\ud835\udcb3\u2081 = generate_planar_points(\ud835\udc27\u2081,d\u2081, 20, 50)\n\ud835\udcb3\u2082 = generate_planar_points(\ud835\udc27\u2082,d\u2082, 20, 50)\n\n\nworld_basis = (Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0), Vec(0.0, 0.0, 1.0))\ncamera_basis = (Point(0.0, 0.0, 0.0), Vec(-1.0, 0.0, 0.0), Vec(0.0, -1.0, 0.0), Vec(0.0, 0.0, 1.0))\npicture_basis = (Point(0.0, 0.0), Vec(-1.0, 0.0), Vec(0.0, -1.0))\n\ncamera\u2081 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\ncamera\u2082 = Pinhole(image_width, image_height, f, camera_basis..., picture_basis...)\nrelocate!(camera\u2081, \ud835\udc11\u2081, \ud835\udc2d\u2081)\nrelocate!(camera\u2082, \ud835\udc11\u2082, \ud835\udc2d\u2082)\n\n\ud835\udc11\u2081\u2032, \ud835\udc2d\u2081\u2032 = ascertain_pose(camera\u2081, world_basis... )\n\ud835\udc0a\u2081\u2032 = obtain_intrinsics(camera\u2081, CartesianSystem())\n\ud835\udc11\u2082\u2032, \ud835\udc2d\u2082\u2032 = ascertain_pose(camera\u2082, world_basis... )\n\ud835\udc0a\u2082\u2032 = obtain_intrinsics(camera\u2082, CartesianSystem())\n\n\ud835\udc0f\u2081 = construct(ProjectionMatrix(),\ud835\udc0a\u2081\u2032,\ud835\udc11\u2081\u2032,\ud835\udc2d\u2081\u2032)\n\ud835\udc0f\u2082 = construct(ProjectionMatrix(),\ud835\udc0a\u2082\u2032,\ud835\udc11\u2082\u2032,\ud835\udc2d\u2082\u2032)\n\n# Set of corresponding points.\n\u2133\u2081 = project(camera\u2081,\ud835\udc0f\u2081,\ud835\udcb3\u2081)\n\u2133\u2081\u02b9= project(camera\u2082,\ud835\udc0f\u2082,\ud835\udcb3\u2081)\n\u2133\u2082 = project(camera\u2081,\ud835\udc0f\u2081,\ud835\udcb3\u2082)\n\u2133\u2082\u02b9= project(camera\u2082,\ud835\udc0f\u2082,\ud835\udcb3\u2082)\n\n\ud835\udc07\u2081 = estimate(HomographyMatrix(), DirectLinearTransform(), (\u2133\u2081, \u2133\u2081\u02b9))\n\ud835\udc07\u2082 = estimate(HomographyMatrix(), DirectLinearTransform(), (\u2133\u2082, \u2133\u2082\u02b9))\n\n\nfor i = zip(\u2133\u2081,\u2133\u2081\u02b9)\n    m, m\u02b9 =  i\n    \ud835\udc26  = hom(m)\n    \ud835\udc26\u02b9 = hom(m\u02b9)\n    residual = vec2antisym(\ud835\udc26\u02b9)*\ud835\udc07\u2081*\ud835\udc26\n    @test isapprox(sum(residual), 0.0; atol = 1e-7)\nend\n\nfor i = zip(\u2133\u2082,\u2133\u2082\u02b9)\n    m, m\u02b9 =  i\n    \ud835\udc26  = hom(m)\n    \ud835\udc26\u02b9 = hom(m\u02b9)\n    residual = vec2antisym(\ud835\udc26\u02b9)*\ud835\udc07\u2082*\ud835\udc26\n    @test isapprox(sum(residual), 0.0; atol = 1e-7)\nend\n\n# Tests for homography matrix estimation\n#\n# # Normal to the planar surface.\n# \ud835\udc27 = [0.0, 0.0, -1.0]\n# # Distance of the plane from the origin.\n# d = 100\n# # Sample points on the planar surface.\n# \ud835\udcb3 = [Point3D(x,y,d) for x = -100:5:100 for y = -100:5:100]\n# \ud835\udcb3 = \ud835\udcb3[1:50:end]\n# # Intrinsic and extrinsic parameters of camera one.\n# \ud835\udc0a\u2081 = Matrix{Float64}(I,3,3)\n# \ud835\udc11\u2081 = Matrix{Float64}(I,3,3)\n# \ud835\udc2d\u2081 = [0.0, 0.0, 0.0]\n#\n# # Intrinsic and extrinsic parameters of camera two.\n# \ud835\udc0a\u2082 = Matrix{Float64}(I,3,3)\n# \ud835\udc11\u2082 = Matrix{Float64}(I,3,3)\n# \ud835\udc2d\u2082 = [100.0, 2.0, -100.0]\n#\n# # Camera projection matrices.\n# \ud835\udc0f\u2081 = construct(ProjectionMatrix(),\ud835\udc0a\u2081,\ud835\udc11\u2081,\ud835\udc2d\u2081)\n# \ud835\udc0f\u2082 = construct(ProjectionMatrix(),\ud835\udc0a\u2082,\ud835\udc11\u2082,\ud835\udc2d\u2082)\n#\n# # Set of corresponding points.\n# \u2133 = project(Pinhole(),\ud835\udc0f\u2081,\ud835\udcb3)\n# \u2133\u02b9 = project(Pinhole(),\ud835\udc0f\u2082,\ud835\udcb3)\n#\n# # Estimate of the homography matrix and the true homography matrix.\n# \ud835\udc07 = estimate(HomographyMatrix(), DirectLinearTransform(), (\u2133, \u2133\u02b9))\n# \ud835\udc07\u2080 = construct(HomographyMatrix(),\ud835\udc0a\u2081,\ud835\udc11\u2081,\ud835\udc2d\u2081,\ud835\udc0a\u2082,\ud835\udc11\u2082,\ud835\udc2d\u2082,\ud835\udc27,d)\n#\n# \ud835\udc07\u2080 = \ud835\udc07\u2080 / norm(\ud835\udc07\u2080)\n# \ud835\udc07\u2080 = \ud835\udc07\u2080 / sign(\ud835\udc07\u2080[3,3])\n#\n# \ud835\udc07 = \ud835\udc07 / norm(\ud835\udc07)\n# \ud835\udc07 = \ud835\udc07 / sign(\ud835\udc07[3,3])\n#\n# for i = zip(\u2133,\u2133\u02b9)\n#     m, m\u02b9 =  i\n#     \ud835\udc26  = hom(m)\n#     \ud835\udc26\u02b9 = hom(m\u02b9)\n#     residual = vec2antisym(\ud835\udc26\u02b9)*\ud835\udc07\u2080*\ud835\udc26\n#     @test isapprox(sum(residual), 0.0; atol = 1e-7)\n# end\n#\n# for i = zip(\u2133,\u2133\u02b9)\n#     m, m\u02b9 =  i\n#     \ud835\udc26  = hom(m)\n#     \ud835\udc26\u02b9 = hom(m\u02b9)\n#     residual = vec2antisym(\ud835\udc26\u02b9)*\ud835\udc07*\ud835\udc26\n#     @show residual\n#     @test isapprox(sum(residual), 0.0; atol = 1e-7)\n# end\n#\n\n#@test isapprox(sum(residual), 0.0; atol = 1e-7)\n#dot(\ud835\udcb3[10],\ud835\udc27) + d\n", "meta": {"hexsha": "b0460660e33c8b4d25741612f50be5a2b925464c", "size": 3775, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/estimate_homography_tests.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": "test/estimate_homography_tests.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": "test/estimate_homography_tests.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": 26.9642857143, "max_line_length": 99, "alphanum_fraction": 0.6241059603, "num_tokens": 1826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7551644845771064}}
{"text": "# ### parametric function plot 3d\n# https://jp.mathworks.com/matlabcentral/fileexchange/35263-matlab-plot-gallery-function-plot-3d?focused=7851891&tab=example\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\nt = range(0, stop=10, length=1000)\nx = cos.(t)\ny = sin.(t)\nz = sin.(5t)\n\nplot(x, y, z)\n", "meta": {"hexsha": "38bb53bf9c3c6586e5805bda480faacf6e9cf08f", "size": 293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/parametric3d.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/parametric3d.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/parametric3d.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": 24.4166666667, "max_line_length": 124, "alphanum_fraction": 0.7030716724, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7551644809077958}}
{"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\u0302, you could add any integer multiple of 2\u03c0q\u0302 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 \u03c0.  The\nchoice of the `z` direction is arbitrary; the \"vector\" component of the\nreturned quaternion could be \u03c0 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\ud835\udc22 + 1.2\ud835\udc23 + 0.0\ud835\udc24\n\njulia> log(Quaternion(exp(7)))\n7.0 + 0.0\ud835\udc22 + 0.0\ud835\udc23 + 0.0\ud835\udc24\n\njulia> log(Quaternion(-exp(7)))\n7.0 + 0.0\ud835\udc22 + 0.0\ud835\udc23 + 3.141592653589793\ud835\udc24\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, \u03c0)\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, \u03c0)\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*\u03c0/4)  # Rotation through \u03c0/2 (note the extra 1/2) about the x axis\n0.7071067811865476 + 0.7071067811865475\ud835\udc22 + 0.0\ud835\udc23 + 0.0\ud835\udc24\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 \u2014 in which case the result is simply\nthe zero quaternion \u2014 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 = \u221aq;\n\njulia> sqrtq^2 \u2248 q\ntrue\n\njulia> \u221aQuaternion(4)\n2.0 + 0.0\ud835\udc22 + 0.0\ud835\udc23 + 0.0\ud835\udc24\n\njulia> \u221aQuaternion(-4)\n0.0 + 0.0\ud835\udc22 + 0.0\ud835\udc23 + 2.0\ud835\udc24\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 \u2014 as in `q*v*conj(q)` \u2014 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 \u2014\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> \u03b8=1.2;\n\njulia> R=exp(\u03b8 * 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 \u2264 eps(typeof(absolutevec))\n        if q.w < 0\n            # log(q) \u2248 \u03c0\ud835\udc24\n            sin_\u03c0s, cos_\u03c0s = sincospi(oftype(absolutevec, s))\n            return Rotor{eltype(q)}([cos_\u03c0s, 0, 0, sin_\u03c0s])\n        end\n        # log(q) \u2248 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 \u2265 0 ? Base.power_by_squaring(q, s) : inv(Base.power_by_squaring(q, -s)))\nBase.:^(q::QuatVec, s::Integer) = (s \u2265 0 ? Base.power_by_squaring(q, s) : inv(Base.power_by_squaring(q, -s)))\nBase.:^(q::Rotor, s::Integer) = (s \u2265 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": "using DiffEqEnvironments\nusing DifferentialEquations\nusing LinearAlgebra\nusing ControlSystems\nusing Test\nusing ReinforcementLearningBase\nusing Plots\n\n\"\"\"\nThis test defines an SISO system of form\n    s\u0307 = A*s + B*a\n    o = C*s\nfor the rocket car problem, where\n    s = [p, p\u0307]  ,\np being the position of the car.\nThe action used as an input to the system is \nthe car's acceleration p\u0308 \u2208 [-1, 1]. Therefore\n    s\u0307 = [p\u0307, p\u0308] = [0 1; 0 0] * s + [0; 1] * u .\nFull observation of the state is given, as\n    o = s   .\n\"\"\"\nT = Float32\n\n# System matrices\nA = [0 1; 0 0]\nB = [0, 1]\n\n# weights for quadratic cost function\nQ = I * 10\nR = I\n\n# Set range of control input\na_lb = -1.0; a_ub = 1.0\n\n# Set IC & tspan for integration\ns0 = [-0.75, 0.0]\ntspan = (0f0, 5f0)\n\n# Define ODEProblem of SISO LTI system\nfunction lti(s, a, t) \n    s\u0307 = A * s + B * a\nend\nprob_lti = ODEProblem(lti, s0, tspan)\n\n# Use ControlSystems.jl to solve continuous algebraic Riccati eq.\nP = care(A, B, Q, R) # P encodes value function as v(s)= -s'*P*s/2\nK = -R \\ B' * P\nprintln(\"K=\", K)\n\nv_lqr(s) = -s' * P * s / 2\n\u03c0_lqr(s) = clamp.(K * s, a_lb, a_ub) #  LQR controller w/ saturation\n\n\n# Define closed-loop ODE for system with input saturations\nfunction cl_ode(s, \u03c0, t)\n    a = \u03c0(s) \n    s\u0307 = lti(s, a, t)\nend\n\nfunction plot_value(v; levels=10)\n    ps = range(-1, 1, length=100)\n    p\u0307s = range(-1, 1, length=100)\n    vp(p, p\u0307) = v([p,p\u0307]) \n\n    contour(ps, p\u0307s, vp, levels=levels,\n        xlabel=\"p\", ylabel=\"p\u0307\",\n        fill=true, show=true)\nend\n\np = plot_value(v_lqr)\n\n# Plot LQR Solution\nprob_lqr = ODEProblem(cl_ode, s0, tspan, \u03c0_lqr)\nsol_lqr = solve(prob_lqr, Tsit5())\n\nfunction plot_phase_portrait!(plt, \u03c0; n=20, scale=0.075)\n    s\u0307(s) = lti(s, \u03c0(s), 0) * scale\n    s\u0307(p, p\u0307) = s\u0307([p,p\u0307])\n\n    ps = range(-1, 1, length=n)\n    p\u0307s = range(-1, 1, length=n)\n\n    pps = [p for p in ps for p\u0307 in p\u0307s]\n    p\u0307p\u0307s = [p\u0307 for p in ps for p\u0307 in p\u0307s]\n    quiver!(pps, p\u0307p\u0307s, quiver=s\u0307, lw=1, c=:black,\n        xlim=(-1, 1), ylim=(-1, 1),\n        arrow=(style = :closed; headlength = 0.1))\nend\n\nfunction plot_trajectory!(plt, s0, \u03c0; c=:black)\n    prob = ODEProblem(cl_ode, s0, tspan, \u03c0)\n    sol = solve(prob, Tsit5(), saveat=0.01)\n\n    plot!(plt, sol[1,:], sol[2,:], lw=3, c=c,\n        xlim=(-1, 1), ylim=(-1, 1), line=:arrow,\n        legend=false, show=true)\nend\n\np2 = plot_phase_portrait!(p, \u03c0_lqr)\np3 = plot_trajectory!(p, s0, \u03c0_lqr)\n\ndisplay(p)\n\n# Define DiffEqEnv\nr = QuadraticRewardFunction(Q, R)\nn_actions = 1\ndt = 0.1\nenv = DiffEqEnv(prob_lti, r, n_actions, dt, a_lb=a_lb, a_ub=a_ub)", "meta": {"hexsha": "61264f612944fee0dce7e514211a0a4374dee9b9", "size": 2548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/quadrLTI.jl", "max_stars_repo_name": "adrhill/DiffEqEnvironments.jl", "max_stars_repo_head_hexsha": "f5e3d16459f21af9a6b65ed401c64f4c76c1c3c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-01T18:33:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T18:33:58.000Z", "max_issues_repo_path": "docs/src/quadrLTI.jl", "max_issues_repo_name": "adrhill/DiffEqEnvironments.jl", "max_issues_repo_head_hexsha": "f5e3d16459f21af9a6b65ed401c64f4c76c1c3c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-11T11:01:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-13T19:16:07.000Z", "max_forks_repo_path": "docs/src/quadrLTI.jl", "max_forks_repo_name": "adrhill/DiffEqEnvironments.jl", "max_forks_repo_head_hexsha": "f5e3d16459f21af9a6b65ed401c64f4c76c1c3c3", "max_forks_repo_licenses": ["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.5925925926, "max_line_length": 68, "alphanum_fraction": 0.6071428571, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7551644772384848}}
{"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,:] \u2a00 [B_1(x[1]) \u2a02 B_2(x[2]) \u2a02 ... \u2a02 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": "@testset \"NelsonSiegelSvensson\" begin\n\n    # Per this technical note, the target/source rates should be interpreted as continuous rates: \n    # https://www.ecb.europa.eu/stats/financial_markets_and_interest_rates/euro_area_yield_curves/html/technical_notes.pdf\n    \n    # EURAAA_20191111 at https://www.ecb.europa.eu/stats/financial_markets_and_interest_rates/euro_area_yield_curves/html/index.en.html\n    euraaa_zeros = Continuous.([-0.602009,-0.612954,-0.621543,-0.627864,-0.632655,-0.610565,-0.569424,-0.516078,-0.455969,-0.39315,-0.33047,-0.269814,-0.21234,-0.158674,-0.109075,-0.063552,-0.021963,0.015929,0.050407,0.081771,0.110319,0.136335,0.160083,0.181804,0.201715,0.220009,0.23686,0.252419,0.26682,0.280182,0.292608,0.304191,0.31501] ./ 100)\n    euraaa_pars = Continuous.([-0.601861,-0.612808,-0.621403,-0.627731,-0.63251,-0.610271,-0.568825,-0.515067,-0.454526,-0.391338,-0.328412,-0.26767,-0.210277,-0.156851,-0.107632,-0.062605,-0.021601,0.015642,0.049427,0.080073,0.107892,0.133178,0.156206,0.17722,0.196444,0.214073,0.230281,0.245221,0.259027,0.271818,0.283696,0.294753,0.305069] ./ 100)\n    euraaa_maturities = vcat([0.25, 0.5, 0.75], 1:30)\n    \n    @testset \"NelsonSiegel\" begin\n        @testset \"EURAAA_20191111\" begin\n            c_param = Yields.NelsonSiegelCurve(0.6202603126029489 /100, -1.1621281759833935 /100, -1.930016080035979 /100, 3.0)\n            c = Yields.Zero(NelsonSiegel(),euraaa_zeros, euraaa_maturities)\n            # @testset \"parameter: $param\" for param in [:\u03b2\u2080, :\u03b2\u2081, :\u03b2\u2082, :\u03c4\u2081]\n            #     @test getfield(c, param) \u2248 getfield(c_param, param)\n            # end\n\n            @testset \"zero rates: $t\" for (t, r) in zip(euraaa_maturities, euraaa_zeros)\n                @test Yields.zero(c, t) \u2248 r   atol = 0.001\n            end\n\n            @testset \"par rates: $t\" for (t, r) in zip(euraaa_maturities, euraaa_pars)\n                @test Yields.zero(c, t) \u2248 r   atol = 0.001\n            end\n\n            @test discount(c,0) == 1.0\n            @test discount(c,10) \u2248 1 / accumulation(c,10)\n\n            # test that rates as floats work\n            fzeros = Yields.rate.(euraaa_zeros)\n            c_fzero = Yields.Zero(NelsonSiegel(),fzeros, euraaa_maturities)\n            @test c_fzero == c\n        end\n\n        # Nelson-Siegel-Svensson package example at https://nelson-siegel-svensson.readthedocs.io/en/latest/usage.html\n        @testset \"pack\" begin\n            pack_yields = Continuous.([0.01, 0.011, 0.013, 0.016, 0.019, 0.021, 0.026, 0.03, 0.035, 0.037, 0.038, 0.04])\n            pack_maturities = [10e-5, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0]\n            c_param = Yields.NelsonSiegelCurve(0.04495841387198023, -0.03537510042719209, 0.0031561222355027227, 5.0)\n            c = Yields.Zero(NelsonSiegel(),pack_yields, pack_maturities)\n\n            @testset \"zero rates: $t\" for (t, r) in zip(pack_maturities, pack_yields)\n                @test Yields.zero(c, t) \u2248 r   atol = 0.003\n            end\n        end\n    end\n\n    @testset \"NelsonSiegelSvensson\" begin\n\n        @testset \"EURAAA_20191111\" begin\n            c_zero = Yields.Zero(NelsonSiegelSvensson(),euraaa_zeros, euraaa_maturities)\n            c_par = Yields.Par(NelsonSiegelSvensson(),euraaa_pars, euraaa_maturities)\n\n            @testset \"par and zero constructors\" for c in [c_zero,c_par]\n                @testset \"zero rates: $t\" for (t, r) in zip(euraaa_maturities, euraaa_zeros)\n                    @test Yields.zero(c, t) \u2248 r   atol = 0.0001\n                end\n\n                @testset \"par rates: $t\" for (t, r) in zip(euraaa_maturities, euraaa_pars)\n                    # are the target rates on the ECB site continuous rates or periodic/bond-equivalent?\n                    @test Yields.par(c, t) \u2248 r   atol = 0.0001\n                end\n            end\n\n            # test that rates as floats work\n            fzeros = Yields.rate.(euraaa_zeros)\n            c_fzero = Yields.Zero(NelsonSiegelSvensson(),fzeros, euraaa_maturities)\n            @test c_fzero == c_zero\n\n        end\n        @testset \"EURAAA_20191111 w parms given\" begin\n            c = Yields.NelsonSiegelSvenssonCurve(0.629440 / 100, -1.218082 /100, \t12.114098 /100, -14.181117 /100, 2.435976, 2.536963)\n\n            @testset \"zero rates: $t\" for (t, r) in zip(euraaa_maturities, euraaa_zeros)\n                @test Yields.zero(c, t) \u2248 r   atol = 0.0001\n            end\n\n            @testset \"par rates: $t\" for (t, r) in zip(euraaa_maturities, euraaa_pars)\n                # are the target rates on the ECB site continuous rates or periodic/bond-equivalent?\n                @test Yields.par(c, t) \u2248 r atol = 0.0001\n            end\n\n            @test Yields.zero(c,30) \u2248 last(euraaa_zeros) atol = 0.0001 \n            @test discount(c,0) == 1.0\n            @test discount(c,10) \u2248 1 / accumulation(c,10)\n        end\n    end\n\nend\n", "meta": {"hexsha": "e8bd63021866f80fdfe603283cbcf1ea88a7557c", "size": 4833, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/NelsonSiegelSvensson.jl", "max_stars_repo_name": "alecloudenback/Yields.jl", "max_stars_repo_head_hexsha": "dd853e7de50fdc588ee8241a26bbcb057d6f1daa", "max_stars_repo_licenses": ["MIT"], "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/NelsonSiegelSvensson.jl", "max_issues_repo_name": "alecloudenback/Yields.jl", "max_issues_repo_head_hexsha": "dd853e7de50fdc588ee8241a26bbcb057d6f1daa", "max_issues_repo_licenses": ["MIT"], "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/NelsonSiegelSvensson.jl", "max_forks_repo_name": "alecloudenback/Yields.jl", "max_forks_repo_head_hexsha": "dd853e7de50fdc588ee8241a26bbcb057d6f1daa", "max_forks_repo_licenses": ["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.1098901099, "max_line_length": 350, "alphanum_fraction": 0.6149389613, "num_tokens": 1700, "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": "using Revise\nusing Statistics\nusing LaTeXStrings\nusing PyPlot\nusing LinearAlgebra\nusing Infiltrator\nusing Bem2d\n\n\n\"\"\"\n    discretized_arc(\u03b8start, \u03b8end, radius, n_pts)\n\nGenerate regularly spaced eleemnts along an curved arc.\n\"\"\"\nfunction discretized_arc(\u03b8start, \u03b8end, radius, n_pts)\n    # Create geometry of discretized arc\n    \u03b8range = collect(LinRange(\u03b8start, \u03b8end, n_pts + 1))\n    x = @. radius * cos(\u03b8range)\n    y = @. radius * sin(\u03b8range)\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_\u03b1 = [  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_\u03b2 = [  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(_\u03b1),\n            LinearAlgebra.LowerTriangular(_\u03b2)\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(_\u03b1),\n        LinearAlgebra.LowerTriangular(_\u03b2)\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    \u03b1 = scheme.alpha\n    \u03b2h = 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 \u03b1[i,j]!=0.0\n                    initialised ? (v[:,i+1]+=v[:,j]*\u03b1[i,j]) : (v[:,i+1]=v[:,j]*\u03b1[i,j]; initialised=true)\n                end\n                if \u03b2h[i,j]!=0.0\n                    initialised ? (v[:,i+1]+=vD[:,j]*\u03b2h[i,j]) : (v[:,i+1]=vD[:,j]*\u03b2h[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(\u03bc,\u03c1,\u03c3,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(\u03bc, \u03c1, \u03c3, n)\n    n == 1 && (return [\u03bc], [1.0])\n\n    mu_eps = 0\n    q = (\u03c1 + 1) / 2\n    nu = ((n - 1) / (1 - \u03c1^2))^(1 / 2) * \u03c3\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 - \u03c1) .- nu, mu_eps / (1 - \u03c1) .+ nu, n);] .+ \u03bc\n    return x, P\nend\n\n\"\"\"\n     tauchen(\u03bc,\u03c1,\u03c3,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(\u03bc, \u03c1, \u03c3, N, m = 3)\n    cdf_normal(x) = 0.5 * erfc(-x / sqrt(2))\n    if N == 1\n        return [\u03bc], [1.0]\n    end\n    Z     = zeros(N)\n    Zprob = zeros(N, N)\n    a     = (1 - \u03c1) * \u03bc\n\n    Z[N]  = m * sqrt(\u03c3^2 / (1 - \u03c1^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 - \u03c1)\n\n    for j = 1:N\n        for k = 1:N\n            if k == 1\n                Zprob[j,k] = cdf_normal((Z[1] - a - \u03c1 * Z[j] + zstep / 2) / \u03c3)\n            elseif k == N\n                Zprob[j,k] = 1 - cdf_normal((Z[N] - a - \u03c1 * Z[j] - zstep / 2) / \u03c3)\n            else\n                Zprob[j,k] = cdf_normal((Z[k] - a - \u03c1 * Z[j] + zstep / 2) / \u03c3) - cdf_normal((Z[k] - a - \u03c1 * Z[j] - zstep / 2) / \u03c3)\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# \u2554\u2550\u2561 de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Combinatorics, Plots, LaTeXStrings\n\tRandom.seed!(123)\nend\n\n# \u2554\u2550\u2561 ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.5\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6285dea2-1ee5-11eb-2b6a-f9906c0d3351\nmd\"## End of listing 2.5\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# \u2560\u2550de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# \u2560\u2550e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# \u2560\u2550d212f38c-1ee4-11eb-360a-b7d524890c8f\n# \u2560\u25506263427a-1ee5-11eb-12d1-1d576fa18461\n# \u2560\u255062637f3a-1ee5-11eb-34e2-77e37f188fe5\n# \u2560\u25506263f402-1ee5-11eb-20e1-5d1ebc78f310\n# \u2560\u25506276d39e-1ee5-11eb-23cc-2fe5377e6ce9\n# \u2560\u255062781fb2-1ee5-11eb-0ba1-035fa45106f5\n# \u255f\u25006285dea2-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) = \u03c4, x \u2265 0}.\n\n   projsplx!(b, \u03c4)\n\nIn-place variant of `projsplx`.\n\"\"\"\nfunction projsplx!{T}(b::Vector{T}, \u03c4::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 - \u03c4)/i\n        if tmax \u2265 b[idx[i+1]]\n            bget = true\n            break\n        end\n    end\n\n    if !bget\n        tmax = (tsum + b[idx[n]] - \u03c4) / 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, \u03c4)\n\nThis projects b (in-place) onto the unit simplex weighted by c.\n\"\"\"\nfunction projsplx!{T}(b::Vector{T}, c::Vector{T}, \u03c4::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 - \u03c4) / 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 - \u03c4) / 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, \u03c4) -> x\n\nVariant of `projsplx`.\n\"\"\"\nfunction projsplx(b::Vector, \u03c4)\n    x = copy(b)\n    projsplx!(x, \u03c4)\n    return x\nend\n\n\"\"\"\nProjection onto the weighted simplex.\n\n    projsplx(b, c, \u03c4) -> x\n\nVariant of `projsplx!`.\n\"\"\"\nfunction projsplx(b::Vector, c::Vector, \u03c4)\n    x = copy(b)\n    projsplx!(x, c, \u03c4)\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] \u2265 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||\u2081 \u2264 \u03c4 }.\n\nIn-place variant of `projnorm1`.\n\"\"\"\nfunction projnorm1!(b::Vector, \u03c4::Real)\n    norm(b,1) > \u03c4 || return\n    s = sign_abs!(b)\n    projsplx!(b, \u03c4)\n    set_sign!(b, s)\nend\n\n\"\"\"\nProjection onto the weighted 1-norm ball\n\n    {x | ||diag(c)x||\u2081 \u2264 \u03c4 }, c > 0.\n\nIn-place variant of `projnorm1`.\n\"\"\"\nfunction projnorm1!(b::Vector, c::Vector, \u03c4::Real)\n    norm(b,1) > \u03c4 || return\n    s = sign_abs!(b)\n    projsplx!(b, c, \u03c4)\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, \u03c4::Real)\n    x = copy(b)\n    projnorm1!(x, c, \u03c4)\n    return x\nend\n\n\"\"\"\nProjection onto the 1-norm ball.\n\nVariant of `projnorm1!`.\n\"\"\"\nfunction projnorm1(b::Vector, \u03c4::Real)\n    x = copy(b)\n    projnorm1!(x, \u03c4)\n    return x\nend\n\n\"\"\"\nProximal map of the scaled infinity norm.\n    prox_inf(x,\u03bb) = x - proj(x | \u03bb\ud835\udd39\u2081)\n     env_inf(x,\u03bb) = (1/2\u03bb)||x||\u00b2 - (1/2\u03bb)dist\u00b2(x | \u03bb\ud835\udd39\u2081)\nModifies `x` in place; returns the envelope.\n\"\"\"\nfunction proxinf!(x::Vector, \u03bb::Real)\n  \u03bb == 0 && return norm(x, Inf)\n  nrmx2 = dot(x,x)\n  xp = projnorm1(x, \u03bb)\n  BLAS.axpy!(-1., xp, x) # x <- x - xp\n  return nrmx2/(2\u03bb) - dot(x,x)/(2\u03bb)\nend\n\n\"\"\"\nProximal map of the scaled infinity norm.\nReturn variant of `proxinf!`\n\"\"\"\nfunction proxinf(x::Vector, \u03bb::Real)\n    z = copy(x)\n    proxinf!(z, \u03bb)\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 \u211d\u00b3\nexport cross\n\n\n\"\"\"\n    Represents a point in \u211d\u00b3.\n\nfield: a.\n\"\"\"\nstruct \u211d\u00b3 <: VectorSpace\n    a::Array{Float64}\n    \u211d\u00b3(x\u2081::Real, x\u2082::Real, x\u2083::Real) = new(float.([x\u2081; x\u2082; x\u2083]))\n    \u211d\u00b3(a::Array) = begin\n        @assert(length(a) == 3, \"The input vector must contain exactly three elements.\")\n        \u211d\u00b3(a...)\n    end\nend\n\n\n\n## Unary Operators ##\n\n\n+(r::\u211d\u00b3) = r\n-(r::\u211d\u00b3) = \u211d\u00b3(-vec(r))\n\n\n## Binary Operators ##\n\n\n+(r1::\u211d\u00b3, r2::\u211d\u00b3) = \u211d\u00b3(vec(r1) + vec(r2))\n-(r1::\u211d\u00b3, r2::\u211d\u00b3) = \u211d\u00b3(vec(r1) - vec(r2))\n*(r::\u211d\u00b3, \u03bb::Real) = \u211d\u00b3(\u03bb .* vec(r))\n*(\u03bb::Real, r::\u211d\u00b3) = r * \u03bb\n\n\n\"\"\"\n    cross(r1, r2)\n\nPerform a cross product with the given vectors `r1` and `r2`.\n\"\"\"\ncross(r1::\u211d\u00b3, r2::\u211d\u00b3) = begin\n    M = transpose(reshape([vec(r1); vec(r1); vec(r2)], :, length(r1)))\n    M = convert(Array{Float64}, M)\n    \u211d\u00b3(map(x -> cofactor(M, 1, x), 1:length(r1)))\nend\n\n\nBase.isapprox(a::Array{\u211d\u00b3},\n              b::Array{\u211d\u00b3};\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": "using FractionalSystems, ControlSystems\nusing Test\n\n@testset \"Test FOTF\" begin\n    a = fotf([1, 2], [1, 2], [1, 2], [1, 2])\n\n    @test isa(a, FOTF)\n    @test fotfdata(a) == ([1, 2], [1, 2], [1, 2], [1, 2], 0)\n    @test iszero(a) == false\n    @test fotf(\"s\") == fotf([1], [1], [1], [0], 0)\nend\n\nG = fotf([1, 2, 3], [0.1, 0.2, 0.34], [4, 5, 6], [0.65, 0.67, 0.78])\nnum = zeros(34+1)\nnum[34+1] = 3\nnum[20+1] = 2\nnum[10+1] = 1\nnum = num[end:-1:1]\n\nden = zeros(78+1)\nden[78+1] = 6\nden[67+1] = 5\nden[65+1] = 4\nden = den[end:-1:1]\n\n@testset \"Test base_order\" begin\n    @test base_order(G) == 0.01\nend\n\n@testset \"Test fotf2cotf\" begin\n    @test fotf2cotf(G) == tf(num, den)\nend\n\n@testset \"Test Polyuniq\" begin\n    @test polyuniq([2, 2], [4, 4], 0.0001) == ([4], [4])\nend\n#=\n@testset \"Test simplify\" begin\n    g = fotf([2, 2], [4, 4], [6, 6], [8, 8])\n    sg = fotf( 4, 0, 12, 4)\n    @test fotfdata(simplify(g)) == fotfdata(sg)\nend\n=#\n\n\n@testset \"Test basic operations\" begin\n    a=fotf([5, 6], [7, 8], [1, 2], [3, 4])\n    b=fotf([1, 2], [1, 2], [1, 2], [1, 2])\n\n    aplusb = fotf([1, 5, 2, 6], [5, 4, 1, 0], [1, 2], [0, 1])\n    @test a+b == aplusb\nend\n\n#=\n@testset \"Test inv operation\" begin\n    \nend\n=#\n\n@testset \"Test freqresp\" begin\n    a = fotf([1, 2], [1, 2], [1, 2], [1, 2])\n    @test freqresp([1; 2; 3], a) == [1.0; 1.0; 1.0]\nend\n\n@testset \"Test polyshow\" begin\n    @test polyshow([1, 2], [1, 2]) == \"2s^{2}+s\"\n    @test polyshow([1, -2], [0, 2.2]) == \"-2s^{2.2}+1\"\nend", "meta": {"hexsha": "45e19d9f424d64ab04c3ea3df6cb5e29082475d1", "size": 1467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fotf.jl", "max_stars_repo_name": "SciFracX/FractionalSystems.jl", "max_stars_repo_head_hexsha": "e2fded2ed59b86eb00d0fa266dfea69d54527a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-22T15:24:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T20:53:17.000Z", "max_issues_repo_path": "test/fotf.jl", "max_issues_repo_name": "SciFracX/FractionalSystems.jl", "max_issues_repo_head_hexsha": "e2fded2ed59b86eb00d0fa266dfea69d54527a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-25T06:35:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T13:23:24.000Z", "max_forks_repo_path": "test/fotf.jl", "max_forks_repo_name": "SciFracX/FractionalSystems.jl", "max_forks_repo_head_hexsha": "e2fded2ed59b86eb00d0fa266dfea69d54527a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-22T15:24:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T15:24:07.000Z", "avg_line_length": 21.5735294118, "max_line_length": 68, "alphanum_fraction": 0.509202454, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7551644655656736}}
{"text": "@testset \"thermalization.jl\" begin\n    \n    @testset \"_weights_canonical\" begin\n        # check weighting\n        range = collect(1:15)\n        @test XXZNumerics._weights_canonical(log.(range), -1) \u2248 range./sum(range)\n        @test XXZNumerics._weights_canonical(log.(range), -2) \u2248 range.^2 ./ sum(range .^ 2)\n\n        # check extreme cases\n        @test .!(any(isnan, XXZNumerics._weights_canonical(exp.(range), 100)))\n        @test XXZNumerics._weights_canonical(exp.(range), 0) \u2248 ones(length(range))/length(range)\n        @test XXZNumerics._weights_canonical(exp.(range), 1) \u2248 XXZNumerics._weights_canonical(sort!(-exp.(range)), -1)[end:-1:1]\n    end\n\n    @testset \"find\u03b2\" begin\n        @test find\u03b2([1,2,3,4], 2.5) \u2248 0\n        @test find\u03b2([1,2,3,4], 3) < 0\n        @test find\u03b2([1,2,3,4], 2) > 0\n        @test find\u03b2([1,2,3,4], 2.5-0.7) \u2248 -find\u03b2([1,2,3,4], 2.5+0.7) # should be symmetric around the average energy as spectrum is symmetric\n        # can't think of other good tests...\n    end\n\n    @testset \"canonical_ensemble\" begin\n        l = 10\n        states = sort!(rand(l)*10 .- 5)\n        @test canonical_ensemble(states, states[1]) \u2248 vcat(1, zeros(l-1))\n        @test canonical_ensemble(states, states[end]) \u2248 vcat(zeros(l-1), 1)\n        @test canonical_ensemble(states, mean(states)) \u2248 ones(l)/l\n    end\n\n    @testset \"microcanonical_ensemble\" begin\n        @test microcanonical_ensemble([-2, -1, 0.5, 1, 2], 0, 1.1) \u2248 [0,1,1,1,0]/3\n        @test microcanonical_ensemble([-2, -1, 0.5, 1, 2], 0, 0.9) \u2248 [0,0,1,0,0]\n        @test microcanonical_ensemble([-2, -1, 0.5, 1, 2], 0, 0) \u2248 [0,0,1,0,0] # choose closest state\n        @test microcanonical_ensemble([-2, -1, 0.5, 1, 2], -0.6, 0) \u2248 [0,1,0,0,0]\n\n        @test microcanonical_ensemble([-40, -1, 0.5, 1, 40], 0.7) \u2248 [0,0,1,1,0]/2 # default arg -> \u0394E = 80*0.5% = 0.4\n    end\nend", "meta": {"hexsha": "eb820a242e363b375c5612a6a19460fb7643a19d", "size": 1838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 47.1282051282, "max_line_length": 141, "alphanum_fraction": 0.5914036997, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7551529067360611}}
{"text": "# A test problem coming from LSQR.\n\nusing LinearOperators\n\n\nfunction lstp(nrow :: Int, ncol :: Int, ndupl :: Int, npower :: Int, \u03bb :: Real, x :: Array)\n\n  # LSTP  generates a sparse least-squares test problem of the form\n  #\n  #   minimize \u2016 [A ] x - [b] \u2016\n  #            \u2016 [\u03bbI]     [0] \u2016\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\u03c0;\n  fourpi = 4 * 3.141592;    # This is the approximation used in Mike's original subroutine.\n  \u03b1 = fourpi / nrow;        # 4\u03c0 / nrow;\n  \u03b2 = fourpi / ncol;        # 4\u03c0 / ncol;\n  hy = map(sin, [1:nrow;] * \u03b1)\n  hz = map(cos, [1:ncol;] * \u03b2)\n\n  \u03b1 = norm(hy); hy /= \u03b1; HY = opHouseholder(hy);  # HY is nrow x nrow.\n  \u03b2 = norm(hz); hz /= \u03b2; 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, \u221alength(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 \u2208 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 \u2208 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\u00f2 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` \u00d7 `Ns` matrix), initial probabilities `a` (`Ns`-vector) and observation probabilities `y` (a `Ns`\u00d7`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 ``\u03bc`` 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(\u03bc::AbstractFloat, x::Vector)\n    n = length(x) \n    x\u0305 = sample_mean(x)\n    s = \u221a(sample_variance(x))\n    T = (x\u0305 - \u03bc) / (s / \u221a(n))\n    return T\nend\n\n\n\"\"\"\nCalculates the reference variable for ``\u03bc`` when the elements in vector ``x`` comes from a normal distribution.\nThis time the variance ``\u03c3\u00b2`` has to be known for the distribution.\nSee also: [`sample_mean`](@ref).\n\"\"\"\nfunction normal_reference_mu_known_variance(\u03bc::AbstractFloat, \u03c3\u00b2::AbstractFloat, x::Vector)\n    n = length(x) \n    x\u0305 = sample_mean(x)\n    \u03c3 = \u221a(\u03c3\u00b2)\n    T = (x\u0305 - \u03bc) / (\u03c3 / \u221a(n))\n    return T \nend\n\n\n\"\"\"\nReference variable for ``\u03c3\u00b2`` when the elements in vector ``x`` comes from a normal distribution.\nSee also: [`sample_variance`](@ref).\n\"\"\"\nfunction normal_reference_sigma(\u03c3\u00b2::AbstractFloat, x::Vector)\n    n = length(x)\n    s\u00b2 = sample_variance(x)\n    T = (n - 1) * s\u00b2 / \u03c3\u00b2\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(\u03bc\u1d6a::AbstractFloat, \u03bc\u1d67::AbstractFloat, \u03c3\u00b2\u1d6a::AbstractFloat, \u03c3\u00b2\u1d67::AbstractFloat, x::Vector, y::Vector)\n    n\u1d6a = length(x)\n    n\u1d67 = length(y)\n    x\u0305 = sample_mean(x) \n    y\u0305 = sample_mean(x)\n    T = ((x\u0305 - y\u0305) - (\u03bc\u1d6a - \u03bc\u1d67)) / \u221a(\u03c3\u00b2\u1d6a / n\u1d6a + \u03c3\u00b2\u1d67 / n\u1d67)\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(\u03bc\u1d6a::AbstractFloat, \u03bc\u1d67::AbstractFloat, x::Vector, y::Vector)\n    n\u1d6a = length(x)\n    n\u1d67 = length(y)\n    x\u0305 = sample_mean(x) \n    y\u0305 = sample_mean(x)\n    s = \u221a(two_sample_variance(x, y))\n    T = ((x\u0305 - y\u0305) - (\u03bc\u1d6a - \u03bc\u1d67)) / (s * \u221a(1 / n\u1d6a + 1 / n\u1d67))  \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(\u03bc\u1d6a::AbstractFloat, \u03bc\u1d67::AbstractFloat, x::Vector, y::Vector)\n    n\u1d6a = length(x)\n    n\u1d67 = length(y)\n    x\u0305 = sample_mean(x) \n    y\u0305 = sample_mean(x)\n    s\u00b2\u1d6a = sample_variance(x)\n    s\u00b2\u1d67 = sample_variance(y)\n    T = ((x\u0305 - y\u0305) - (\u03bc\u1d6a - \u03bc\u1d67)) / \u221a(s\u00b2\u1d6a / n\u1d6a + s\u00b2\u1d67 / n\u1d67)\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\u1d6a = length(x)\n    n\u1d67 = length(y)\n    s\u00b2\u1d6a = sample_variance(x)\n    s\u00b2\u1d67 = sample_variance(y)\n    first = 1 / (n\u1d6a - 1)\n    second = (n\u1d67 * s\u00b2\u1d6a)^2 / (n\u1d67 * s\u00b2\u1d6a + n\u1d6a * s\u00b2\u1d67)^2\n    third = 1 / (n\u1d67 - 1)\n    fourth = (n\u1d6a * s\u00b2\u1d67)^2 / (n\u1d67 * s\u00b2\u1d6a + n\u1d6a * s\u00b2\u1d67)^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, \u03b1::AbstractFloat)\n    n = length(x)\n    z = y .- x \n    z\u0305 = sample_mean(z)\n    dist = tDistribution(n-1)  \n    t = quantile_finder(dist, \u03b1)\n    s = \u221a(sample_variance(z))\n    I = [z\u0305 - t * s / \u221a(n), z\u0305 + t * s / \u221a(n)]  \n    return I\nend\n\n\nfunction normal_interval_mu_unknown_variance(\u03bc::AbstractFloat, x::Vector, \u03b1::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_mu_known_variance(\u03bc::AbstractFloat, \u03c3\u00b2::AbstractFloat, x::Vector, \u03b1::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_sigma(x::Vector, \u03b1::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_two_sample_mu_known_variance(\u03bc\u1d6a::AbstractFloat, \u03bc\u1d67::AbstractFloat, \u03c3\u00b2\u1d6a::AbstractFloat, \u03c3\u00b2\u1d67::AbstractFloat, x::Vector, y::Vector, \u03b1::AbstractFloat)\n    \nend\n\n\nfunction normal_interval_two_sample_mu_unknown_equal_variance(\u03bc\u1d6a::AbstractFloat, \u03bc\u1d67::AbstractFloat, x::Vector, y::Vector, \u03b1::AbstractFloat)\n    \nend\n\n\nfunction exp_reference_mu(\u03bc::AbstractFloat, x::Vector)\n    n = length(n)\n    x\u0305 = sample_mean(x)\n    T = (x\u0305 - \u03bc) / (\u03bc / \u221a(n)) \n    return T\nend\n\n\nfunction exp_interval_mu(\u03bc::AbstractFloat, x::Vector, \u03b1::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    \u03c9::Float64\nend\n\nOscillator(n::Int64) = Oscillator(n,1.0)\nindex(b::Oscillator) = 1:b.n\nspectrum(b::Oscillator) = (0:b.n-1)*b.\u03c9\nqnumbers(b::Oscillator) = 0:b.n-1\n\nfunction hermite(x,n)\n    @assert n >= 1\n    h1 = exp(-x^2 / 2) * (1 / \u03c0)^(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 \u2208 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,\u03c9) = hermite(\u221a\u03c9 * x,n) * \u03c9 ^ ( 1 / 4 )\n\nfunction (b::Oscillator)(x::Array{Float64,1})\n    @unpack \u03c9,n = b\n    T = x * ones(1, n) |> zero\n    T[:,1] = @. hermite(x,1,\u03c9)\n    n >= 2 && (T[:,2] = @. sqrt(2 * \u03c9) * x * T[:,1])\n    for j \u2208 index(b)[3:end]\n        m = qnumbers(b)[j]\n        T[:,j] = @. sqrt(2 / m) * (\u221a\u03c9 * 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.\u03c9)\n\nfunction hermite_polar(x,n,\u03c9)\n    p = Progress(n,.1,\"Precomputing...\",20)   # minimum update interval: 1 second\n    T = zeros(size(x)...,n)\n    T[:,:,1] = @. hermite(x,1,\u03c9)\n    next!(p)\n    n >= 2 && (T[:,:,2] = @. sqrt(2 * \u03c9) * x * T[:,:,1])\n    next!(p)\n    for j in 3:n\n        T[:,:,j] = @. sqrt(2 / (j-1)) * (\u221a\u03c9 * 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,\u03c9)\n    p = Progress(N,.1,\"Filtering...\",20)\n    H = Oscillator(N,\u03c9)(x)\n    T = inv(H'*H)\n    F\u0302 = 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\u0302[m,n]*H[:,n]'\n            end\n        end\n    return psiF\nend\n\n# covert to polar coords\nfunction slowpolar(psi,x,N,\u03c9)\n    H = Oscillator(N,\u03c9)(x)\n    T = inv(H'*H)\n    F\u0302 = T*H'*psi*H*T\n\n    Nx = length(x)\n    \u03b8 = LinRange(0,2*pi,2*Nx)\n    r = LinRange(0,last(x),Nx/2 |> Int)'\n\n    psiP = zero(\u03b8*r)\n    for m = 1:N, n = 1:(N + 1 - m)\n        @. psiP += hermite(r*cos(\u03b8),m) * F\u0302[m,n] * hermite(r*sin(\u03b8),n)\n    end\n    return psiP\nend\n\nfunction init_polar(x,N,\u03c9)\n    Nx = length(x)\n    \u03b8 = LinRange(0,2*pi,2*Nx)\n    r = LinRange(0,last(x),Nx/2 |> Int)'\n    hx = hermite_polar((@. r*cos(\u03b8)),N,\u03c9)\n    hy = hermite_polar((@. r*sin(\u03b8)),N,\u03c9)\n    return hx,hy\nend\n\nfunction polar(psi,x,\u03c9,Hx,Hy)\n    N = size(Hx)[3]\n    p = Progress(N,1,\"Polar transform...\",20)\n    H = Oscillator(N,\u03c9)(x)\n    T = inv(H'*H)\n    F\u0302 = T*H'*psi*H*T\n\n    Nx = length(x)\n    N\u03b8 = 2*Nx\n    Nr = Nx/2 |> Int\n    \u03b8 = LinRange(0,2*pi,N\u03b8+1)[1:N\u03b8]\n    r = LinRange(0,last(x),Nr)'\n\n    psiFP = zeros(eltype(psi),N\u03b8,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\u0302[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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.04\"\n\n# \u2554\u2550\u2561 fa68607e-22e5-11eb-0558-c9a4d9f77426\nn, N, alpha = 3, 10^7, 0.1\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0a990730-3a99-11eb-0e9d-439c6e34d87c\nText(\"Quantile from Monte Carlo: $(mcQuantile)\")\n\n# \u2554\u2550\u2561 0a998098-3a99-11eb-209b-2f467a34d644\nText(\"Analytic qunatile: $(analyticQuantile)\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.04\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u25500a6fcc80-3a99-11eb-3de9-13429e2152ee\n# \u2560\u25500a990730-3a99-11eb-0e9d-439c6e34d87c\n# \u2560\u25500a998098-3a99-11eb-209b-2f467a34d644\n# \u2560\u25500a9fd40c-3a99-11eb-387b-05b58e298e6e\n# \u255f\u2500475ff888-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\u1d62 = k | f\u1d62) = \u03b8\u1d4f\\\\exp(-\u03b8)/k!\n```\nfor ``k \u2208 N\u2080``, where ``\u03b8 = \\\\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": "@testset \"Newton\" begin\n    for n in [1,3,10]\n\nA = rand(n,n)\n\nr = polarfact(A, alg = :newton);\n\n# Test unitary matrix U\n\nU = r.U\nH = r.H\n\n@test U'*U \u2248 Matrix(I,n,n) atol=1e-7\n\n# Test Hermitian positive semifefinite matrix H\n\n@test ishermitian(H)\n \nfor i in eigvals(H)\n    @test i >= 0.\nend\n\n@test A \u2248 U*H\n\n    end\nend\n", "meta": {"hexsha": "62ac512b1f5507042264560341ea7fdc45d7cbcb", "size": 318, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_newton.jl", "max_stars_repo_name": "weijianzhang/PolarFact.jl", "max_stars_repo_head_hexsha": "6530009072c8774274508fef3c05a1487f09bd60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-03-12T23:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-13T11:35:49.000Z", "max_issues_repo_path": "test/test_newton.jl", "max_issues_repo_name": "weijianzhang/PolarFact.jl", "max_issues_repo_head_hexsha": "6530009072c8774274508fef3c05a1487f09bd60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-12-18T19:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:28:45.000Z", "max_forks_repo_path": "test/test_newton.jl", "max_forks_repo_name": "weijianzhang/PolarFact.jl", "max_forks_repo_head_hexsha": "6530009072c8774274508fef3c05a1487f09bd60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T14:32:06.000Z", "avg_line_length": 11.7777777778, "max_line_length": 47, "alphanum_fraction": 0.606918239, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7550541034161579}}
{"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\u03b8 = (0.5:N-0.5)/N\n\n# The longitudinal grid (mod $\\pi$):\nM = 2*N-1\n\u03c6 = (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 = (\u03b8,\u03c6) -> [sinpi(\u03b8)*cospi(\u03c6), sinpi(\u03b8)*sinpi(\u03c6), cospi(\u03b8)]\n\n# Our initial guess for $\\lambda$:\n\u03bb = 1.0\n\n# Then we run Newton iteration and grab an espresso:\nfor _ in 1:7\n    F = [sin(\u03bb*(k\u22c5r(\u03b8,\u03c6))) for \u03b8 in \u03b8, \u03c6 in \u03c6]\n    F\u03bb = [(k\u22c5r(\u03b8,\u03c6))*cos(\u03bb*(k\u22c5r(\u03b8,\u03c6))) for \u03b8 in \u03b8, \u03c6 in \u03c6]\n    U = P\\(PA*F)\n    U\u03bb = P\\(PA*F\u03bb)\n    global \u03bb = \u03bb - (norm(U)^2-1)/(2*sum(U.*U\u03bb))\n    println(\"\u03bb: $(rpad(\u03bb, 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 \u2014 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 \u2014 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` \u2014 a 3D array of the model grid, filled with `1`'s at \"wet\" grid boxes and `0`'s and \"land\" grid boxes.\n# - `grd` \u2014 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` \u2014 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 `\u03c4`, via\n\nfunction sink_age(age, p)\n    \u03c4 = p.\u03c4\n    return age .* (z .< 20u\"m\") / \u03c4\nend\n\n#md # !!! note\n#md #     Julia allows you to use unicode for your functions and variables, like for `\u03c4`.\n#nb # > **Note**\n#nb # > Julia allows you to use unicode for your functions and variables, like for `\u03c4`.\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, `\u03c4`, in this case.\n# We will chose the value for `\u03c4` 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, :\u03c4, 1u\"s\")   # add the parameter we want (\u03c4 = 1s)\ninitialize_Parameters_type(t, \"IdealAgeParameters\")  # Generate the parameter type\nt\n\n# Note, in particular, that we gave our parameter `\u03c4` 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\u2080 = 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\u2080` as a parameters vector, since it has only one element, `\u03c4`, 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\u2080`, let's create a state `x\u2080` to start with.\n# The vector `x\u2080` 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\u2080 = 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, \u2207\u2093F = state_function_and_Jacobian(T_matrices, sources_minus_sinks, nb) # generates the state function (and its Jacobian!)\nF(x\u2080,p\u2080)\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 \u2014 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 \u2014 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` \u2014 the numerical version of the **state function**, $\\boldsymbol{F}$, of our model of the mean age, and\n# - `\u2207\u2093F` \u2014 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\u2080` and parameter vector `p\u2080`.\n\n# #### Solving for the steady-state\n#--------------------------\n\n# The Jacobian, `\u2207\u2093F` 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, \u2207\u2093F, x\u2080, p\u2080)\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 \u2014 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": "using ExploratoryDataAnalysis\nusing Test\n\nusing StatsBase\nusing FreqTables\n\na = [1, 2, 3, 1, 2, 3, 1, 1, 2, 2]\nb = [11, 11, 12, 12, 11, 11, 12, 12, 11, 12]\n\n@testset \"Cramer's V\" begin\n    @test round(cramerv(a, b), digits = 7) == 0.4472136\n    @test round(cramerv(counts(a, b)), digits = 7) == 0.4472136\n    @test round(cramerv(freqtable(a, b)), digits = 7) == 0.4472136\n    @test round(cramerv(freqtable(a, b).array), digits = 7) == 0.4472136\nend\n\n@testset \"infovalue\" begin\n    @test round(infovalue(counts(a, b)), digits = 7) == 0.8788898\n    @test round(infovalue(freqtable(a, b)), digits = 7) == 0.8788898\n    @test round(infovalue(freqtable(a, b).array), digits = 7) == 0.8788898\nend\n\n@testset \"mutual info\" begin\n    @test round(mutualinfo(a, b), digits = 7) == 0.1046496\n    @test round(mutualinfo(counts(a, b)), digits = 7) == 0.1046496\n    @test round(mutualinfo(freqtable(a, b)), digits = 7) == 0.1046496\n    @test round(mutualinfo(freqtable(a, b).array), digits = 7) == 0.1046496\nend\n", "meta": {"hexsha": "8dad879cdecdb12b7bb5c28ae5cce16bb41190ef", "size": 997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 34.3793103448, "max_line_length": 75, "alphanum_fraction": 0.6399197593, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.80563219364797, "lm_q1q2_score": 0.7550471886142931}}
{"text": "\n# # Rossby Parameter\n#\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/notebooks/example_beta.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/notebooks/example_beta.ipynb)\n#\n# [from wikipedia:](https://en.wikipedia.org/wiki/Rossby_parameter)\n#\n# The Rossby parameter `\u03b2` arises due to the variation of the Coriolis\n# force `f(\u03c6)` as a function of latitude `\u03c6`. It is important\n# in the generation of Rossby waves and given by\n#\n# $$\\beta(\\varphi) = 2\\Omega / R * cos(\\varphi)$$\n\nusing PhysicalOceanography\nisapprox(\u03b2(45),1.61687441686e-11)\n", "meta": {"hexsha": "d930b7f91b7b8d9a85d32f8e41165be8b3d7d528", "size": 612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Parameters/example_beta.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_beta.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_beta.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": 36.0, "max_line_length": 119, "alphanum_fraction": 0.7303921569, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7550471879753554}}
{"text": "using ModelingToolkit\nusing ModelingToolkit: sys2bigraph\nusing DiffEqBase\nusing Test\n\n# Define some variables\n@parameters t L g\n@variables x(t) y(t) w(t) z(t) T(t) x\u02cdt(t) y\u02cdt(t)\n@derivatives D'~t\n\neqs2 = [D(D(x)) ~ T*x,\n        D(D(y)) ~ T*y - g,\n        0 ~ x^2 + y^2 - L^2]\npendulum2 = ODESystem(eqs2, t, [x, y, T], [L, g], name=:pendulum)\nlowered_sys = ModelingToolkit.ode_order_lowering(pendulum2)\n\nlowered_eqs = [D(x\u02cdt) ~ T*x,\n               D(y\u02cdt) ~ T*y - g,\n               0 ~ x^2 + y^2 - L^2,\n               D(x) ~ x\u02cdt,\n               D(y) ~ y\u02cdt]\n@test ODESystem(lowered_eqs, t, [x\u02cdt, y\u02cdt, x, y, T], [L, g]) == lowered_sys\n@test isequal(lowered_sys.eqs, lowered_eqs)\n\n# Simple pendulum in cartesian coordinates\neqs = [D(x) ~ w,\n       D(y) ~ z,\n       D(w) ~ T*x,\n       D(z) ~ T*y - g,\n       0 ~ x^2 + y^2 - L^2]\npendulum = ODESystem(eqs, t, [x, y, w, z, T], [L, g], name=:pendulum)\n\nedges, vars, vars_asso = sys2bigraph(pendulum)\n@test ModelingToolkit.matching(edges, length(vars), vars_asso .== 0) == [0, 0, 0, 0, 1, 2, 3, 4, 0]\n\nedges, assign, vars_asso, eqs_asso = ModelingToolkit.pantelides(pendulum)\n\n@test sort.(edges) == sort.([\n [5, 3],               # 1\n [6, 4],               # 2\n [7, 9, 1],            # 3\n [8, 9, 2],            # 4\n [2, 1],               # 5\n [2, 1, 6, 5],         # 6\n [5, 3, 10, 7],        # 7\n [6, 4, 11, 8],        # 8\n [2, 1, 6, 5, 11, 10], # 9\n])\n#                  [1, 2, 3, 4, 5,  6,  7,  8,  9, 10,   11]\n#                  [x, y, w, z, x', y', w', z', T, x'', y'']\n@test vars_asso == [5, 6, 7, 8, 10, 11, 0,  0,  0,  0,    0]\n#1: D(x) ~ w\n#2: D(y) ~ z\n#3: D(w) ~ T*x\n#4: D(z) ~ T*y - g\n#5: 0 ~ x^2 + y^2 - L^2\n# ----\n#6: D(5) -> 0 ~ 2xx'+ 2yy'\n#7: D(1) -> D(D(x)) ~ D(w)\n#8: D(2) -> D(D(y)) ~ D(z)\n#9: D(6) -> 0 ~ 2xx'' + 2x'x' + 2yy'' + 2y'y'\n#                 [1, 2, 3, 4, 5, 6, 7, 8, 9]\n@test eqs_asso == [7, 8, 0, 0, 6, 9, 0, 0, 0]\n", "meta": {"hexsha": "3d96613e773d3f2ee1feaca9f9c8af5f82280b40", "size": 1886, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/index_reduction.jl", "max_stars_repo_name": "adediego/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "192441f42b2e49b264ea5cfceac093d3b44df9be", "max_stars_repo_licenses": ["MIT"], "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/index_reduction.jl", "max_issues_repo_name": "adediego/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "192441f42b2e49b264ea5cfceac093d3b44df9be", "max_issues_repo_licenses": ["MIT"], "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/index_reduction.jl", "max_forks_repo_name": "adediego/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "192441f42b2e49b264ea5cfceac093d3b44df9be", "max_forks_repo_licenses": ["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.46875, "max_line_length": 99, "alphanum_fraction": 0.453340403, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7550471879753554}}
{"text": "using ChebyshevQuantum\nusing Test\nusing SpecialFunctions\n\ntol_var=1e-8\n\n@testset \"bessel eq test\" begin\n\n\n    a=0.0;\n    b= 5.520078110588564; #second zero of besselj0\n\n    #solve bessels equation between 0 and 2nd zero of besselj0 with Direchlet b.c.'s.\n    t = ChebyshevQuantum.DiffEq.solve(bc1 = [:a,0, 1.0], bc2 = [:b,0,0.0], A0=x->x^2, A1= x->x, A2 = x->(x^2) ,B = 0.0, N=20,  a=a, b= b);\n\n    x = a:.01:b\n\n    @test maximum(abs.(besselj0.(x) - t.(x))) < tol_var\n    @test maximum(abs.(x.^2 .* t''.(x) + x .* t'.(x) + (x.^2 ).*t.(x))) < tol_var #test diffeq directly\n\n                  \n    a=1.0;\n #   b= 3.8319091796875; #first zero of besselj1\n    b=   3.8317059218883514\n    #solve bessels equation \u03b1 = 1.0  between 1 and zero of besselj1 with Direchlet b.c.'s.\n    t = ChebyshevQuantum.DiffEq.solve(bc1 = [:a,0, besselj1(a)], bc2 = [:b,0,besselj1(b)], A0=x->(x^2 - 1.0), A1= x->x, A2 = x->x^2  ,B = 0.0, N=20,  a=a, b= b);\n\n    x = a:.01:b\n\n    @test maximum(abs.(besselj1.(x) - t.(x))) < tol_var\n    @test maximum(abs.(x.^2 .* t''.(x) + x .* t'.(x) + (x.^2 .- 1 ).*t.(x))) < tol_var #test diffeq directly\n\n\n    \nend\n\n\n\n@testset \"heat eq test\" begin\n\n\n    a=0.0;\n    b= 1.0; \n\n    #solve heat equation\n    t = ChebyshevQuantum.DiffEq.solve(bc1 = [:a,0,1.0], bc2 = [:b,0,0.5], A2 = 0.5 , N=20,  a=a, b= b);\n\n    x = a:.01:b\n\n    function f(x) #solution is a line\n        1.0 - 0.5*x\n    end\n    \n    @test maximum(abs.(f.(x) - t.(x))) < tol_var\n    \n\nend\n\n@testset \"SHO test\" begin\n\n\n    a=0.0;\n    b=2*pi; \n\n    #solve simple harmonic oscillator equation, neuman b.c.'s\n    t = ChebyshevQuantum.DiffEq.solve(bc1 = [:a,0,1.0], bc2 = [:a,1,0.0], A2 = 1.0, A0=1.0 , N=20,  a=a, b= b);\n\n    x = a:.01:b\n\n    function f(x) #solution is a cosine\n        cos(x)\n    end\n    \n    @test maximum(abs.(f.(x) - t.(x))) < tol_var\n    \n\nend\n\n\n@testset \"Decay Exp test\" begin\n\n\n    a=0.0;\n    b=2*pi; \n\n    #solve decaying exp equation, neuman b.c.'s\n    t = ChebyshevQuantum.DiffEq.solve(bc1 = [:a,0,1.0], bc2 = [:a,1,-1.0], A2 = 1.0, A0=-1.0 , N=20,  a=a, b= b);\n\n    x = a:.01:b\n\n    function f(x) #solution is a decaying exp\n        exp(-x)\n    end\n    \n    @test maximum(abs.(f.(x) - t.(x))) < tol_var\n    \n\nend\n\n@testset \"First order Decay Exp\" begin\n\n\n    a=0.0;\n    b=10.0; \n\n    #solve decaying exp equation, first order\n    t = ChebyshevQuantum.DiffEq.solve(bc1 = [:a,0,1.0],  A1 = 1.0, A0=1.0 , N=20,  a=a, b= b);\n\n    x = a:.01:b\n\n    function f(x) #solution is a decaying exp\n        exp(-x)\n    end\n    \n    @test maximum(abs.(f.(x) - t.(x))) < tol_var\n    @test maximum(abs.(  t'.(x) .+ t.(x))) < tol_var #test diffeq directly\n    \n\nend\n\n\n", "meta": {"hexsha": "2b36aeb451817cd08ec07e923523519edae2f2ae", "size": 2649, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_diffeq.jl", "max_stars_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_stars_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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": "test/test_diffeq.jl", "max_issues_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_issues_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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": "test/test_diffeq.jl", "max_forks_repo_name": "kfgarrity/ChebyshevQuantum.jl", "max_forks_repo_head_hexsha": "d8d0828fbb4973d529f9a743c777848ef1e1b95b", "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.7131147541, "max_line_length": 161, "alphanum_fraction": 0.537183843, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7550471879753552}}
{"text": "using CartesianFDM\nusing Test\n\n@testset \"1D identities\" begin\n    n = (5,)\n    top = (periodic(),)\n\n    ctx = cartesianfdmcontext(top, n)\n\n    # assumes 1D\n    ((\u03b4\u207b,), (\u03b4\u207a,)) = getproperty(ctx, :\u03b4)\n    ((\u03c3\u207b,), (\u03c3\u207a,)) = getproperty(ctx, :\u03c3)\n    ((\u03c4\u207b,), (\u03c4\u207a,)) = getproperty(ctx, :\u03c4)\n\n    \u03a8, \u03a6 = scalar(:\u03a8, n), scalar(:\u03a6, n)\n\n    @testset \"2x identity 53\" begin\n        id = (\u03c3\u207a * (\u03b4\u207b * \u03a6)) .- (\u03b4\u207a * (\u03c3\u207b * \u03a6))\n        @test all(iszero, Symbolics.expand.(id))\n\n        id = (\u03c3\u207b * (\u03b4\u207a * \u03a6)) .- (\u03b4\u207b * (\u03c3\u207a * \u03a6))\n        @test all(iszero, Symbolics.expand.(id))\n    end\n\n    @testset \"2x identity 56\" begin\n        id = (\u03c3\u207a * (\u03a8 .* (\u03b4\u207b * \u03a6))) .+ (2\u03a6 .* (\u03b4\u207a * \u03a8)) .- (\u03b4\u207a * (\u03a8 .* (\u03c3\u207b * \u03a6)))\n        @test all(iszero, expand.(id))\n\n        id = (\u03c3\u207b * (\u03a8 .* (\u03b4\u207a * \u03a6))) .+ (2\u03a6 .* (\u03b4\u207b * \u03a8)) .- (\u03b4\u207b * (\u03a8 .* (\u03c3\u207a * \u03a6)))\n        @test all(iszero, expand.(id))\n    end\n\n    @testset \"2x identity 57\" begin\n        id = (\u03a6 .* ((\u03b4\u207a * (\u03a8 .* (\u03c3\u207b * \u03a6))) .+ (\u03c3\u207a * (\u03a8 .* (\u03b4\u207b * \u03a6))))) .-\n            (\u03b4\u207a * (\u03a8 .* ((\u03a6 .* (\u03c4\u207b * \u03a6)) .+ ((\u03c4\u207b * \u03a6) .* \u03a6))))\n        @test all(iszero, expand.(id))\n\n        id = (\u03a6 .* ((\u03b4\u207b * (\u03a8 .* (\u03c3\u207a * \u03a6))) .+ (\u03c3\u207b * (\u03a8 .* (\u03b4\u207a * \u03a6))))) .-\n            (\u03b4\u207b * (\u03a8 .* ((\u03a6 .* (\u03c4\u207a * \u03a6)) .+ ((\u03c4\u207a * \u03a6) .* \u03a6))))\n        @test all(iszero, expand.(id))\n    end\n\n    @testset \"2x identity 59\" begin\n        id = (((\u03c3\u207a * \u03a8) .* (\u03b4\u207a * \u03a6)) .+ ((\u03c3\u207a * \u03a6) .* (\u03b4\u207a * \u03a8))) - (2\u03b4\u207a * (\u03a8 .* \u03a6))\n        @test all(iszero, expand.(id))\n\n        id = (((\u03c3\u207b * \u03a8) .* (\u03b4\u207b * \u03a6)) .+ ((\u03c3\u207b * \u03a6) .* (\u03b4\u207b * \u03a8))) - (2\u03b4\u207b * (\u03a8 .* \u03a6))\n        @test all(iszero, expand.(id))\n    end\nend\n\n@testset \"star stencil\" begin\n    using SparseArrays\n\n    n = (3, 4, 5)\n    top = (periodic(), nonperiodic(), periodic())\n\n    ctx = cartesianfdmcontext(top, n)\n    (\u03c4\u207b, \u03c4\u207a) = getproperty(ctx, :\u03c4)\n\n    X = scalar(:X, n)\n\n    ###\n    F = rand(prod(n)) .* X\n    for i in eachindex(top)\n        F .+= \u03c4\u207b[i] * (rand(prod(n)) .* X)\n    end\n    for i in eachindex(top)\n        F .+= \u03c4\u207a[i] * (rand(prod(n)) .* X)\n    end\n\n    ###\n    sym = linearize(star, ctx, F, X)\n\n    num = Dict{Int,Vector{Float64}}()\n    for (key, val) in sym\n        num[key] = eval(first(build_function(val)))()\n    end\n\n    A = spdiagm(num...)\n\n    ###\n    @test all(iszero, F .- A * X)\nend\n\n", "meta": {"hexsha": "b16e1659a8d33d461e199684a014da50e601f1ac", "size": 2204, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaCutCell/CartesianFDM.jl", "max_stars_repo_head_hexsha": "bb1b2812c9649b2b46b62ba30b3cbf60f702b3ac", "max_stars_repo_licenses": ["MIT"], "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": "JuliaCutCell/CartesianFDM.jl", "max_issues_repo_head_hexsha": "bb1b2812c9649b2b46b62ba30b3cbf60f702b3ac", "max_issues_repo_licenses": ["MIT"], "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": "JuliaCutCell/CartesianFDM.jl", "max_forks_repo_head_hexsha": "bb1b2812c9649b2b46b62ba30b3cbf60f702b3ac", "max_forks_repo_licenses": ["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.6279069767, "max_line_length": 82, "alphanum_fraction": 0.4092558984, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7550471826926874}}
{"text": "using ProjectedGPE, ApproxFun, FastGaussQuadrature, PyPlot, Combinatorics\nM=350\ntol = 1e-14\n#c=Vector{BigFloat}(randn(M))+im*Vector{BigFloat}(randn(M))\n#c=randn(M)+im*randn(M)\nc=zeros(M)\nc[end]=1.\nN1=sum(abs.(c).^2)\n\n#evaluate modes using BigFloats\n#can then use ApproxFun.jl for polynomials, applying correct normalization.\n#Combinatorics.jl needed to evaluate factorial of Vector.\n\nn=0:BigFloat(M)-1;\nHnorm = sqrt(BigFloat(\u03c0))*BigFloat(2).^n.*factorial.(n)\n\n#Inserting norm.\nf=Fun(Hermite(),c./sqrt.(Hnorm))\nf2=Fun(GaussWeight(Hermite()),c./sqrt.(Hnorm))\nx=linspace(-1.5sqrt(2M),1.5sqrt(2M),1000)\nplot(x,abs.(f.(x)).^2.*exp.(-x.^2))\n\nx,w=gausshermite(M)\n\nN2=sum(w.*abs.(f.(x)).^2)\nN3=sum(w.*abs.(f2.(x).*exp.(x.^2)).^2)\n\nFloat64(N2)\n\nabs((N1-N2)/N1)\n\n\n3*M*tol\n\n#block to create T matrix\nM=10\nx,w=gausshermite(M)\nT=zeros(x*ones(1,M))\nn=0:BigFloat(M)-1;\nHnorm = sqrt.(BigFloat(\u03c0))*BigFloat(2).^n.*factorial.(n)\n\nfor j = 0:M-1\n  c=zeros(M)\n  c[j+1]=1.\n  #Hn=Fun(Hermite(),c./sqrt(Hnorm));\n  #T[:,j+1]=Hn.(x).*exp(-x.^2/2)\n  Hn=Fun(GaussWeight(Hermite()),c)\n  T[:,j+1]=Hn.(x).*exp.(x.^2/2)\nend\n\nx1,y1,T1=nfieldtrans(\"Hermite\",M,2,2)\n\nmind = M\nmaximum(abs.(T1[:,mind]-T[:,mind]))\n\nT2=eigmat(\"Hermite\",M,x,2)\nmaximum(abs.(T1[:,mind]-T2[:,mind]))\n\n#-------------------------------\n#Make and test Laguerre transform and quadrature\nM=27\n\u03b1 = 0.\n\u03c9 = 1.\nx,w=gausslaguerre(M,\u03b1)\nT=zeros(x*ones(1,M))\nn=0:M-1;\nLnorm = exp.(lgamma.(n+\u03b1+1)-lgamma.(n+1))/\u03c9\n\nfor j = 0:M-1\n  c=zeros(M)\n  c[j+1]=1.\n  Lna=Fun(Laguerre(\u03b1),c./sqrt(Lnorm));\n  T[:,j+1]=Lna.(sqrt(\u03c9)*x).*exp.(-sqrt(\u03c9)*x/2).*(sqrt(\u03c9)*x).^(\u03b1/2)\nend\n\nc=zeros(M);\nc[end]=BigFloat(1.)\n\n#Gauss Laguerre quadrature can absorb the factor x^\u03b1/2 using associated Laguerre\n#c=randn(M)+im*rand(M)\nN1 = sum(abs.(c).^2)\nL=Fun(Laguerre(\u03b1),c./sqrt(Lnorm))\n\n\n\n\nL2=Fun(WeightedLaguerre(\u03b1),c./sqrt(Lnorm))\nN2=sum(w.*abs(L.(sqrt(\u03c9)*x)).^2)\n\n\n\nN3=sum(w.*abs(L2.(sqrt(\u03c9)*x).*exp.(sqrt(\u03c9)*x)./(sqrt(\u03c9)x).^(\u03b1/2)).^2)\nx=linspace(0,20sqrt(M),1000)\nplot(x,abs.(L.(x)).^2.*exp.(-x).*x.^\u03b1)\n\nLnorm\n\n#------------------------------------\n#test Laguerre\nM=26\n\u03b1 = 0.\n\u03c9 = 1.\n#x,w=gausslaguerre(M,\u03b1)\n\n#T = eigmat(\"Laguerre\",M,x/\u03c9,\u03c9,\u03b1)\n\nx,w,T=nfieldtrans(M,2;basis=\"Laguerre\")\n#norm test\n\nc=zeros(M);\nc[end]=1.\nN1 = sum(abs(c).^2)\n\nLn = T*c\n\n\nN2=sum(w.*abs(Ln).^2)\nf1 = Fun(GaussWeight(Hermite()),[1])\n\n#------------------------------------\n#test Hermite\nM=21\n\n\u03c9 = 10\n#x,w=gausslaguerre(M,\u03b1)\n\n#T = eigmat(\"Laguerre\",M,x/\u03c9,\u03c9,\u03b1)\n\nx,w,T=nfieldtrans(\"Hermite\",M,2,\u03c9)\n#norm test\n\nc=zeros(M);\nc[end]=1.\nN1 = sum(abs(c).^2)\n\nHn = T*c\n\n\nN2=sum(w.*abs(Hn).^2)\n", "meta": {"hexsha": "d4ece279b8c718ef80dd3c603f2de9624406d19d", "size": 2559, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testtransforms.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": "test/testtransforms.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": "test/testtransforms.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": 18.2785714286, "max_line_length": 80, "alphanum_fraction": 0.598671356, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7550471801369362}}
{"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    \u03bc, \u03c3 = mean(scores_train), std(scores_train)\n    @assert \u03c3 > 0 \"Cannot normalize scores if they are all equal\"\n    f = scores -> clamp.(erf.((scores .- \u03bc) ./ (\u03c3 * \u221a2)), 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\u2207f!(\u2207f, x)\n        if !(\u2207f==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            \u2207f[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            \u2207f[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            \u2207f[3] =  200.0*(x[3]-10.0*theta(x)) + 2.0*x[3];\n        end\n\n        fx = f(x)\n        return \u2207f==nothing ? fx : (fx, \u2207f)\n    end\n    function f\u2207f(\u2207f, x)\n        if !(\u2207f == nothing)\n            gx = similar(x)\n            return f\u2207f!(gx, x)\n        else\n            return f\u2207f!(\u2207f, x)\n        end\n    end\n    function f\u2207fs(\u2207f, x)\n        if !(\u2207f == 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            \u2207f = @SVector [s1, s2, s3]\n            return f(x), \u2207f\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\u2207f!, x0, (SR1(DirectApprox()), NearlyNewton.NWI()), I+0.0*x0*x0')\n    res = NearlyNewton.minimize!(f\u2207f!, x0, (BFGS(DirectApprox()), NearlyNewton.NWI()), I+0.0*x0*x0')\n    res = NearlyNewton.minimize!(f\u2207f!, 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!(\u2207f, x)\n        if !(\u2207f == nothing)\n            \u2207f[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            \u2207f[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 \u2207f == nothing ? fx : (fx, \u2207f)\n    end\n\n    function himmelblau!(\u2207\u00b2f, \u2207f, x)\n        if !(\u2207\u00b2f == nothing)\n            \u2207\u00b2f[1, 1] = 12.0 * x[1]^2 + 4.0 * x[2] - 42.0\n            \u2207\u00b2f[1, 2] = 4.0 * x[1] + 4.0 * x[2]\n            \u2207\u00b2f[2, 1] = 4.0 * x[1] + 4.0 * x[2]\n            \u2207\u00b2f[2, 2] = 12.0 * x[2]^2 + 4.0 * x[1] - 26.0\n        end\n        if !(\u2207f == nothing)\n            \u2207f[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            \u2207f[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 \u2207f == nothing && \u2207\u00b2f == nothing\n            return fx\n        elseif \u2207\u00b2f == nothing\n            return fx, \u2207f\n        else\n            return fx, \u2207f, \u2207\u00b2f\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)(\u2207f::AbstractVector{T}, H, \u0394, p;kwargs...) where T\n    x, info = trs(Symmetric(H), \u2207f, \u0394)\n    p .= x[:,1]\n    m = dot(\u2207f, p) + dot(p, H * p)/2\n    interior = norm(p, 2) \u2264 \u0394\n    return (p=p, mz=m, interior=interior, \u03bb=info.\u03bb, 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!(\u2207\u00b2f, \u2207f, x)\n        if !isa(\u2207f, Nothing)\n            \u2207f[1] = -2.0 * (10.0 - x[1])\n            \u2207f[2] = -4.0 * (7.0 - x[2])^3\n            \u2207f[3] = -4.0 * (108.0 - x[3])^3\n        end\n        if !isa(\u2207\u00b2f, Nothing)\n            \u2207\u00b2f[1, 1] = 2.0\n            \u2207\u00b2f[1, 2] = 0.0\n            \u2207\u00b2f[1, 3] = 0.0\n            \u2207\u00b2f[2, 1] = 0.0\n            \u2207\u00b2f[2, 2] = 12.0 * (7.0 - x[2])^2\n            \u2207\u00b2f[2, 3] = 0.0\n            \u2207\u00b2f[3, 1] = 0.0\n            \u2207\u00b2f[3, 2] = 0.0\n            \u2207\u00b2f[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 \u2207f == nothing && \u2207\u00b2f == nothing\n            return fx\n        elseif \u2207\u00b2f == nothing\n            return fx, \u2207f\n        else\n            return fx, \u2207f, \u2207\u00b2f\n        end\n    end\n    function polynomial!(\u2207f, x)\n        if !isa(\u2207f, Nothing)\n            \u2207f[1] = -2.0 * (10.0 - x[1])\n            \u2207f[2] = -4.0 * (7.0 - x[2])^3\n            \u2207f[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 \u2207f == nothing\n            return fx\n        else\n            return fx, \u2207f\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(\u2207\u00b2f, \u2207f, x)\n            if !isa(\u2207f, Nothing)\n                \u2207f[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1]\n                \u2207f[2] = 200.0 * (x[2] - x[1]^2)\n            end\n            if !isa(\u2207\u00b2f, Nothing)\n                \u2207\u00b2f[1, 1] = 2.0 - 400.0 * x[2] + 1200.0 * x[1]^2\n                \u2207\u00b2f[1, 2] = -400.0 * x[1]\n                \u2207\u00b2f[2, 1] = -400.0 * x[1]\n                \u2207\u00b2f[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 \u2207f == nothing && \u2207\u00b2f == nothing\n                return fx\n            elseif \u2207\u00b2f == nothing\n                return fx, \u2207f\n            else\n                return fx, \u2207f, \u2207\u00b2f\n            end\n        end\n\n\n        function rosenbrock(\u2207f, x)\n            if !isa(\u2207f, Nothing)\n                \u2207f[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1]\n                \u2207f[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 \u2207f == nothing\n                return fx\n            else\n                return fx, \u2207f\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    (\u03b2,c,\u03b3) = p\n    N = S+I+R\n    infection = \u03b2*c*I/N*S\n    recovery = \u03b3*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\u03b4t = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:\u03b4t: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]; # \u03b2,c,\u03b3\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(\u03b2)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[\u03b2,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(\u03b2)\n    prob = remake(prob_ode,u0=[990.0,10.0,0.0,0.0],p=[\u03b2,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,\u03b2) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000-I,I,0.0,0.0],p=[\u03b2,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,\u03b2) = x\n    I = i0*1000.0\n    prob = remake(prob_ode,u0=[1000-I,I,0.0,0.0],p=[\u03b2,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 \u6d4b\u8bd5\u51fd\u6570\u7684\u7279\u70b9:\n- \u6709\u56fa\u5b9a\u7684 2 \u4e2a\u76ee\u6807\n- \u6709\u786e\u5b9a\u7684 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\u03c0*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\u03c0*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\u03c0*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\u00b2 = 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] [\u221ac\u00b2; 0; 0]] # the eight points in a matrix\n\n# define the functions for cyclooctane:\nF1 = [(Z[:, i] - Z[:, i+1]) \u22c5 (Z[:, i] - Z[:, i+1]) - c\u00b2 for i in 1:7]\nF2 = [(Z[:, i] - Z[:, i+2]) \u22c5 (Z[:, i] - Z[:, i+2]) - 8c\u00b2/3 for i in 1:6]\nF3 = (Z[:, 7] - Z[:, 1]) \u22c5 (Z[:, 7] - Z[:, 1]) - 8c\u00b2/3\nF4 = (Z[:, 8] - Z[:, 2]) \u22c5 (Z[:, 8] - Z[:, 2]) - 8c\u00b2/3\nf = [F1; F2; F3; F4]\n\nn = 2 # dimension of the cyclooctane variety\nN = 17 # ambient dimension\n@polyvar A\u1d65[1:n, 1:N] b\u1d65[1:n] # variables for the linear equations\np = [vec(A\u1d65); b\u1d65] # parameters\nF = [f; A\u1d65 * z_vec - b\u1d65] # 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\u2080 = randn(ComplexF64, n, N)\nb\u2080 = randn(ComplexF64, n)\np\u2080 = [vec(A\u2080); b\u2080]\n\nF\u2080 = [subs(F\u1d62, p => [vec(A\u2080); b\u2080]) for F\u1d62 in F]\ncomplex_result = solve(F\u2080)\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\u2080 <= up, start = 1.0)\n    @variable(m, lb <= A\u1d64[1:n] <= up, start = 1.0)\n    @variable(m, lb <= A\u2097[1:n] <= up, start = -1.0)\n    @expression(m, yuc[j=1:n_up], cst_C(c1,c2,xu[j])*( A\u2080*cst_S(n,0,xu[j])+sum(A\u1d64[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\u2080*cst_S(n,0,xl[j])+sum(A\u2097[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\u2080), value.(A\u1d64), value.(A\u2097), 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": "\nfunction get_GLRK_\u03c9_matrix(s)\n    \u03c9 = zeros(s, s+1)\n    g = TableauGauss(s)\n    \u03c9[s,s+1] = 1\n    for i in 1:s-1\n        for j in 1:s\n            \u03c9[i,j] = g.b[j] * g.c[j]^(i-1)\n        end\n    end\n    return \u03c9\nend\n", "meta": {"hexsha": "5d454348aa037ff9c6be285a0adc678a49fe7974", "size": 214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tableaus/coefficients_glrk.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_glrk.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_glrk.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": 16.4615384615, "max_line_length": 42, "alphanum_fraction": 0.4579439252, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7550137043307915}}
{"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 (\u201chot-start\u201d). \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": "using TensorDecompositions\n\nfunction tensordecomp2(\u039b::AbstractArray{T,3}, p::Int=5;\n    scaleout::Bool=true) where T\n    \u039b=convert(Array{Float64}, \u039b)\n    size(\u039b)\n    \ud835\udcaf=TensorDecompositions.candecomp(\u039b, p,  (randn(size(\u039b,1), k), randn(size(\u039b,2), k), randn(size(\u039b,3), k)), compute_error=true, method=:ALS);\n    # \ud835\udcaf=TensorToolbox.cp_als(\u039b,p)\n    \ud835\udd4f=TensorDecompositions.compose(\ud835\udcaf)\n    A=mean(\ud835\udd4f[:,:,i] for i=1:size(\ud835\udd4f,3))\n    if scaleout\n    A ./=maximum(abs.(A))\n    end\n    return A\nend\n\n\n\n#=\nu = randn(10); v = randn(20); w = randn(30)\nT = cat(map(x -> x * u * v', w)..., dims=3) + 0.2 * randn(10, 20, 30)\nk=2\nF = candecomp(T, k, (randn(10, k), randn(20, k), randn(30, k)), compute_error=true, method=:ALS);\n\n\n# https://juliapackages.com/p/ntfk\n\nimport NTFk\nimport TensorDecompositions\n\ncsize = (2, 3, 4)\ntsize = (5, 10, 15)\ntucker_orig = NTFk.rand_tucker(csize, tsize; factors_nonneg=true, core_nonneg=true)\n\nT_orig = TensorDecompositions.compose(tucker_orig)\nT_orig .*= 1000\n\nsizes = [csize, (1,3,4), (3,3,4), (2,2,4), (2,4,4), (2,3,3), (2,3,5)]\ntucker_estimated, csize_estimated = NTFk.analysis(T_orig, sizes, 3; eigmethod=[false,false,false], progressbar=false, tol=1e-16, max_iter=100000, lambda=0.);\n=#\n", "meta": {"hexsha": "64e7a5d9f394aa3c6ec0fa3c1009b50e19220d0a", "size": 1206, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tensordecomp2.jl", "max_stars_repo_name": "jamesjcai/ScTenifold", "max_stars_repo_head_hexsha": "9a3742771d15b2d920dd4209944cec5580a035be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-14T16:47:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T16:47:20.000Z", "max_issues_repo_path": "src/tensordecomp2.jl", "max_issues_repo_name": "jamesjcai/ScTenifold", "max_issues_repo_head_hexsha": "9a3742771d15b2d920dd4209944cec5580a035be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-10T20:55:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T15:58:31.000Z", "max_forks_repo_path": "src/tensordecomp2.jl", "max_forks_repo_name": "jamesjcai/ScTenifold", "max_forks_repo_head_hexsha": "9a3742771d15b2d920dd4209944cec5580a035be", "max_forks_repo_licenses": ["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.4146341463, "max_line_length": 157, "alphanum_fraction": 0.6509121061, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7549493116683467}}
{"text": "@testset \"Newton\" begin\n    function himmelblau!(\u2207f, x)\n        if !(\u2207f == nothing)\n            \u2207f[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            \u2207f[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 \u2207f == nothing ? fx : (fx, \u2207f)\n    end\n\n    function himmelblau!(\u2207\u00b2f, \u2207f, x)\n        if !(\u2207\u00b2f == nothing)\n            \u2207\u00b2f[1, 1] = 12.0 * x[1]^2 + 4.0 * x[2] - 42.0\n            \u2207\u00b2f[1, 2] = 4.0 * x[1] + 4.0 * x[2]\n            \u2207\u00b2f[2, 1] = 4.0 * x[1] + 4.0 * x[2]\n            \u2207\u00b2f[2, 2] = 12.0 * x[2]^2 + 4.0 * x[1] - 26.0\n        end\n        if !(\u2207f == nothing)\n            \u2207f[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            \u2207f[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 \u2207f == nothing && \u2207\u00b2f == nothing\n            return fx\n        elseif \u2207\u00b2f == nothing\n            return fx, \u2207f\n        else\n            return fx, \u2207f, \u2207\u00b2f\n        end\n    end\n\n    res = minimize!(himmelblau!, copy([2.0,2.0]), Newton(DirectApprox()))\n    @test norm(res[3], Inf) < 1e-8\n    @printf(\"NN! Newton (direct): %2.2e  %d\\n\", norm(res[3], Inf), res[4])\nend\n", "meta": {"hexsha": "048248993200181356b040beb8dfe13bb78c5a76", "size": 1448, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/newton.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/newton.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/newton.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.4761904762, "max_line_length": 74, "alphanum_fraction": 0.3549723757, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7549493116683467}}
{"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    \u03b5::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 * \u03b5\n        return S2 + (S2 - S) / 15\n    end\n    res1 = adaptivesimpsons_inner(\n        f,\n        a,\n        c,\n        \u03b5 / 2,\n        Sleft,\n        fa,\n        fc,\n        fd,\n        bottom - 1\n    )\n    res2 = adaptivesimpsons_inner(\n        f,\n        c,\n        b,\n        \u03b5 / 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) = \u221a(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] \u2264 a \u2264 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, \u03c3) = \u0393((\u03bd + 1)/2)/[\u0393(\u03bd/2)\u221a(\u03c0\u03bd)\u03c3](1 + 1/\u03bd((y - f)/\u03c3)\u00b2)^{-(\u03bd + 1)/2}\n```\nwith degrees of freedom ``\u03bd \u2208 N\u2080``, where scale ``\u03c3`` is a non-fixed hyperparameter and\n``f`` is the latent Gaussian process.\n\"\"\"\nmutable struct StuTLik <: Likelihood\n    \"Degrees of freedom\"\n    \u03bd::Int\n    \"Scale\"\n    \u03c3::Float64\n    \"Priors for likelihood parameters\"\n    priors::Array\n\n    \"\"\"\n        StuTLik(\u03bd::Int, l\u03c3::Float64)\n\n    Create a `StuTLik` with degrees of freedom `\u03bd` and scale `exp(l\u03c3)`.\n    \"\"\"\n    StuTLik(\u03bd::Int, l\u03c3::Float64) = new(\u03bd, exp(l\u03c3), [])\nend\n\n#log of probability density\nfunction log_dens(studentT::StuTLik, f::VecF64, y::VecF64)\n    \u03bd = studentT.\u03bd\n    \u03c3 = studentT.\u03c3\n    c = lgamma(0.5*(\u03bd+1)) - lgamma(0.5*\u03bd) - 0.5*log(pi*\u03bd) - log(\u03c3)\n    return [c - (0.5*(\u03bd+1))*log(1+(1/\u03bd)*((yi-fi)/\u03c3)^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    \u03bd = studentT.\u03bd\n    \u03c3 = studentT.\u03c3\n    return [(\u03bd+1)*(yi-fi)/(\u03bd*\u03c3^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\u03b8(studentT::StuTLik, f::VecF64, y::VecF64)\n    \u03bd = studentT.\u03bd\n    \u03c3 = studentT.\u03c3\n    return \u03c3*[-1/\u03c3+(\u03bd+1)*(yi-fi)^2/(\u03bd*\u03c3^3 + \u03c3*(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.\u03c3^2*(studentT.\u03bd/(studentT.\u03bd-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.\u03c3 = exp(hyp[])\nend\n\nget_params(studentT::StuTLik) = Float64[log(studentT.\u03c3)]\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": "@testset \"SIP Res\" begin\n    # Define semi-infinite program\n    f(x) = (1/3)*x[1]^2 + x[2]^2 + x[1]/2\n    gSIP(x,p) = (1.0 - (x[1]^2)*(p[1]^2))^2 - x[1]*p[1]^2 - x[2]^2 + x[2]\n\n    x_l = Float64[-1000.0, -1000.0]\n    x_u = Float64[1000.0, 1000.0]\n    p_l = Float64[0.0]\n    p_u = Float64[1.0]\n\n    sip_result = sip_solve(SIPRes(), x_l, x_u, p_l, p_u, f, Any[gSIP], abs_tolerance = 1E-3)\n\n    @test isapprox(sip_result.lower_bound, 0.19446619886176916, atol = 1E-3)\n    @test isapprox(sip_result.upper_bound, 0.19500611503848964, atol = 1E-3)\n    @test isapprox(sip_result.xsol[1], -0.7500000115038946, atol = 1E-2)\n    @test isapprox(sip_result.xsol[2], -0.6184706298867955, atol = 1E-2)\nend\n#=\n@testset \"SIP ResRev\" begin\n    # Define semi-infinite program\n    f(x) = (1/3)*x[1]^2 + x[2]^2 + x[1]/2\n    gSIP(x,p) = (1.0 - (x[1]^2)*(p[1]^2))^2 - x[1]*p[1]^2 - x[2]^2 + x[2]\n\n    x_l = Float64[-1000.0, -1000.0]\n    x_u = Float64[1000.0, 1000.0]\n    p_l = Float64[0.0]\n    p_u = Float64[1.0]\n\n    sip_result = sip_solve(SIPResRev(), x_l, x_u, p_l, p_u, f, Any[gSIP], abs_tolerance = 1E-3)\n\n    @test isapprox(sip_result.lower_bound, 0.19446619886176916, atol = 1E-3)\n    @test isapprox(sip_result.upper_bound, 0.19500611503848964, atol = 1E-3)\n    @test isapprox(sip_result.xsol[1], -0.7500000115038946, atol = 1E-2)\n    @test isapprox(sip_result.xsol[2], -0.6184706298867955, atol = 1E-2)\nend\n=#\n@testset \"SIP Hybrid\" begin\n    # Define semi-infinite program\n    f(x) = (1/3)*x[1]^2 + x[2]^2 + x[1]/2\n    gSIP(x,p) = (1.0 - (x[1]^2)*(p[1]^2))^2 - x[1]*p[1]^2 - x[2]^2 + x[2]\n\n    x_l = Float64[-1000.0, -1000.0]\n    x_u = Float64[1000.0, 1000.0]\n    p_l = Float64[0.0]\n    p_u = Float64[1.0]\n\n    sip_result = sip_solve(SIPHybrid(), x_l, x_u, p_l, p_u, f, Any[gSIP], abs_tolerance = 1E-3)\n\n    @test isapprox(sip_result.lower_bound, 0.19446619886176916, atol = 1E-3)\n    @test isapprox(sip_result.upper_bound, 0.19500611503848964, atol = 1E-3)\n    @test isapprox(sip_result.xsol[1], -0.7500000115038946, atol = 1E-2)\n    @test isapprox(sip_result.xsol[2], -0.6184706298867955, atol = 1E-2)\nend", "meta": {"hexsha": "e915574343f7cbd5f0d31bc0e868ff43d5fb3ac9", "size": 2093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "solver_benchmarking/EAGO.jl-SIPextension/test/semiinfinite.jl", "max_stars_repo_name": "PSORLab/RSActivationFunctions", "max_stars_repo_head_hexsha": "0bf8b4500b21144c076ea958ce93dbdd19a53314", "max_stars_repo_licenses": ["MIT"], "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_benchmarking/EAGO.jl-SIPextension/test/semiinfinite.jl", "max_issues_repo_name": "PSORLab/RSActivationFunctions", "max_issues_repo_head_hexsha": "0bf8b4500b21144c076ea958ce93dbdd19a53314", "max_issues_repo_licenses": ["MIT"], "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_benchmarking/EAGO.jl-SIPextension/test/semiinfinite.jl", "max_forks_repo_name": "PSORLab/RSActivationFunctions", "max_forks_repo_head_hexsha": "0bf8b4500b21144c076ea958ce93dbdd19a53314", "max_forks_repo_licenses": ["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.4905660377, "max_line_length": 95, "alphanum_fraction": 0.6177735308, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7549307093567559}}
{"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# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.15\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 57e2a694-3af9-11eb-0f9e-7d8df75869e6\nText(\"Probability of Type I error: $(ccdf(dist0,tau))\")\n\n# \u2554\u2550\u2561 57e2e668-3af9-11eb-0e7c-033e27bf1e92\nText(\"Probability of Type II error: $(cdf(dist1,tau))\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.15\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u255057e2a694-3af9-11eb-0f9e-7d8df75869e6\n# \u2560\u255057e2e668-3af9-11eb-0e7c-033e27bf1e92\n# \u2560\u255057e37538-3af9-11eb-1477-b9387969d828\n# \u255f\u2500475ff888-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\u03c1 = 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 = \u03c1 / 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] \u2265 0)\n@objective(m, Min, sum(COSTS .* x))\n@constraint(m, sum(x, dims=2) .\u2264 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": "using Rubin\nusing Tests\nusing Elliptic\nusing HypergeometricFunctions\nusing Polylogarithms\nusing SpecialFunctions\n\n@test integrate(x^2*SpecialFunctions.expint(1,b*x), x) == :(-1//3*x^3*SpecialFunctions.expint(-2,b*x)+1//3*x^3*SpecialFunctions.expint(1,b*x))\n@test integrate(x*SpecialFunctions.expint(1,b*x), x) == :((1/2)*x^2*SpecialFunctions.expint(1,b*x)+-1//2*x^2*SpecialFunctions.expint(-1,b*x))\n@test integrate(SpecialFunctions.expint(1,b*x), x) == :(-1*b^-1*SpecialFunctions.expint(2,b*x))\n@test integrate(x^-2*SpecialFunctions.expint(1,b*x), x) == :(x^-1*SpecialFunctions.expint(2,b*x)+-1*x^-1*SpecialFunctions.expint(1,b*x))\n@test integrate(x^-3*SpecialFunctions.expint(1,b*x), x) == :((1/2)*x^-2*SpecialFunctions.expint(3,b*x)+-1//2*x^-2*SpecialFunctions.expint(1,b*x))\n@test integrate(x^-4*SpecialFunctions.expint(1,b*x), x) == :(-1//3*x^-3*SpecialFunctions.expint(1,b*x)+1//3*x^-3*SpecialFunctions.expint(4,b*x))\n@test integrate(x^2*SpecialFunctions.expint(2,b*x), x) == :(-1//4*x^3*SpecialFunctions.expint(-2,b*x)+1//4*x^3*SpecialFunctions.expint(2,b*x))\n@test integrate(x*SpecialFunctions.expint(2,b*x), x) == :(-1//3*x^2*SpecialFunctions.expint(-1,b*x)+1//3*x^2*SpecialFunctions.expint(2,b*x))\n@test integrate(SpecialFunctions.expint(2,b*x), x) == :(-1*b^-1*SpecialFunctions.expint(3,b*x))\n@test integrate(x^-1*SpecialFunctions.expint(2,b*x), x) == :(-1*SpecialFunctions.expint(1,b*x)+SpecialFunctions.expint(2,b*x))\n@test integrate(x^-3*SpecialFunctions.expint(2,b*x), x) == :(x^-2*SpecialFunctions.expint(3,b*x)+-1*x^-2*SpecialFunctions.expint(2,b*x))\n@test integrate(x^-4*SpecialFunctions.expint(2,b*x), x) == :((1/2)*x^-3*SpecialFunctions.expint(4,b*x)+-1//2*x^-3*SpecialFunctions.expint(2,b*x))\n@test integrate(x^-5*SpecialFunctions.expint(2,b*x), x) == :(-1//3*x^-4*SpecialFunctions.expint(2,b*x)+1//3*x^-4*SpecialFunctions.expint(5,b*x))\n@test integrate(x^2*SpecialFunctions.expint(3,b*x), x) == :(-1//5*x^3*SpecialFunctions.expint(-2,b*x)+1//5*x^3*SpecialFunctions.expint(3,b*x))\n@test integrate(x*SpecialFunctions.expint(3,b*x), x) == :(-1//4*x^2*SpecialFunctions.expint(-1,b*x)+1//4*x^2*SpecialFunctions.expint(3,b*x))\n@test integrate(SpecialFunctions.expint(3,b*x), x) == :(-1*b^-1*SpecialFunctions.expint(4,b*x))\n@test integrate(x^-1*SpecialFunctions.expint(3,b*x), x) == :((1/2)*SpecialFunctions.expint(3,b*x)+-1//2*SpecialFunctions.expint(1,b*x))\n@test integrate(x^-2*SpecialFunctions.expint(3,b*x), x) == :(x^-1*SpecialFunctions.expint(3,b*x)+-1*x^-1*SpecialFunctions.expint(2,b*x))\n@test integrate(x^-4*SpecialFunctions.expint(3,b*x), x) == :(x^-3*SpecialFunctions.expint(4,b*x)+-1*x^-3*SpecialFunctions.expint(3,b*x))\n@test integrate(x^-5*SpecialFunctions.expint(3,b*x), x) == :((1/2)*x^-4*SpecialFunctions.expint(5,b*x)+-1//2*x^-4*SpecialFunctions.expint(3,b*x))\n@test integrate(x^-6*SpecialFunctions.expint(3,b*x), x) == :(-1//3*x^-5*SpecialFunctions.expint(3,b*x)+1//3*x^-5*SpecialFunctions.expint(6,b*x))\n@test integrate(x^3*SpecialFunctions.expint(-1,b*x), x) == :((1/2)*x^4*SpecialFunctions.expint(-1,b*x)+-1//2*x^4*SpecialFunctions.expint(-3,b*x))\n@test integrate(x^2*SpecialFunctions.expint(-1,b*x), x) == :(x^3*SpecialFunctions.expint(-1,b*x)+-1*x^3*SpecialFunctions.expint(-2,b*x))\n@test integrate(x*SpecialFunctions.expint(-1,b*x), x) == :(b^-2*expintegralei(-1*b*x)+-1*b^-2*exp(-1*b*x))\n@test integrate(SpecialFunctions.expint(-1,b*x), x) == :(-1*b^-2*x^-1*exp(-1*b*x))\n@test integrate(x^-1*SpecialFunctions.expint(-1,b*x), x) == :((1/2)*SpecialFunctions.expint(1,b*x)+-1//2*SpecialFunctions.expint(-1,b*x))\n@test integrate(x^-2*SpecialFunctions.expint(-1,b*x), x) == :(-1//3*x^-1*SpecialFunctions.expint(-1,b*x)+1//3*x^-1*SpecialFunctions.expint(2,b*x))\n@test integrate(x^-3*SpecialFunctions.expint(-1,b*x), x) == :(-1//4*x^-2*SpecialFunctions.expint(-1,b*x)+1//4*x^-2*SpecialFunctions.expint(3,b*x))\n@test integrate(x^4*SpecialFunctions.expint(-2,b*x), x) == :((1/2)*x^5*SpecialFunctions.expint(-2,b*x)+-1//2*x^5*SpecialFunctions.expint(-4,b*x))\n@test integrate(x^3*SpecialFunctions.expint(-2,b*x), x) == :(x^4*SpecialFunctions.expint(-2,b*x)+-1*x^4*SpecialFunctions.expint(-3,b*x))\n@test integrate(x^2*SpecialFunctions.expint(-2,b*x), x) == :(-2*b^-3*exp(-1*b*x)+2*b^-3*expintegralei(-1*b*x)+-1*b^-1*x^2*SpecialFunctions.expint(-1,b*x))\n@test integrate(x*SpecialFunctions.expint(-2,b*x), x) == :(x^2*SpecialFunctions.expint(-1,b*x)+-1*x^2*SpecialFunctions.expint(-2,b*x))\n@test integrate(SpecialFunctions.expint(-1,b*x), x) == :(-1*b^-2*x^-1*exp(-1*b*x))\n@test integrate(x^-1*SpecialFunctions.expint(-2,b*x), x) == :(-1//3*SpecialFunctions.expint(-2,b*x)+1//3*SpecialFunctions.expint(1,b*x))\n@test integrate(x^-2*SpecialFunctions.expint(-2,b*x), x) == :(-1//4*x^-1*SpecialFunctions.expint(-2,b*x)+1//4*x^-1*SpecialFunctions.expint(2,b*x))\n@test integrate(x^-3*SpecialFunctions.expint(-2,b*x), x) == :(-1//5*x^-2*SpecialFunctions.expint(-2,b*x)+1//5*x^-2*SpecialFunctions.expint(3,b*x))\n@test integrate(x^5*SpecialFunctions.expint(-3,b*x), x) == :((1/2)*x^6*SpecialFunctions.expint(-3,b*x)+-1//2*x^6*SpecialFunctions.expint(-5,b*x))\n@test integrate(x^4*SpecialFunctions.expint(-3,b*x), x) == :(x^5*SpecialFunctions.expint(-3,b*x)+-1*x^5*SpecialFunctions.expint(-4,b*x))\n@test integrate(x^3*SpecialFunctions.expint(-3,b*x), x) == :(-6*b^-4*exp(-1*b*x)+6*b^-4*expintegralei(-1*b*x)+-1*b^-1*x^3*SpecialFunctions.expint(-2,b*x)+-3*b^-2*x^2*SpecialFunctions.expint(-1,b*x))\n@test integrate(x^2*SpecialFunctions.expint(-3,b*x), x) == :(x^3*SpecialFunctions.expint(-2,b*x)+-1*x^3*SpecialFunctions.expint(-3,b*x))\n@test integrate(x*SpecialFunctions.expint(-3,b*x), x) == :((1/2)*x^2*SpecialFunctions.expint(-1,b*x)+-1//2*x^2*SpecialFunctions.expint(-3,b*x))\n@test integrate(SpecialFunctions.expint(-1,b*x), x) == :(-1*b^-2*x^-1*exp(-1*b*x))\n@test integrate(x^-1*SpecialFunctions.expint(-3,b*x), x) == :(-1//4*SpecialFunctions.expint(-3,b*x)+1//4*SpecialFunctions.expint(1,b*x))\n@test integrate(x^-2*SpecialFunctions.expint(-3,b*x), x) == :(-1//5*x^-1*SpecialFunctions.expint(-3,b*x)+1//5*x^-1*SpecialFunctions.expint(2,b*x))\n@test integrate(x^-3*SpecialFunctions.expint(-3,b*x), x) == :(-1//6*x^-2*SpecialFunctions.expint(-3,b*x)+1//6*x^-2*SpecialFunctions.expint(3,b*x))\n@test integrate(x^3*SpecialFunctions.expint(-3,b*x), x) == :(-6*b^-4*exp(-1*b*x)+6*b^-4*expintegralei(-1*b*x)+-1*b^-1*x^3*SpecialFunctions.expint(-2,b*x)+-3*b^-2*x^2*SpecialFunctions.expint(-1,b*x))\n@test integrate(x^2*SpecialFunctions.expint(-2,b*x), x) == :(-2*b^-3*exp(-1*b*x)+2*b^-3*expintegralei(-1*b*x)+-1*b^-1*x^2*SpecialFunctions.expint(-1,b*x))\n@test integrate(x*SpecialFunctions.expint(-1,b*x), x) == :(b^-2*expintegralei(-1*b*x)+-1*b^-2*exp(-1*b*x))\n@test integrate(SpecialFunctions.expint(0,b*x), x) == :(b^-1*expintegralei(-1*b*x))\n@test integrate(x^m*SpecialFunctions.expint(n,x), x) == :(x^(1+m)*(m+n)^-1*SpecialFunctions.expint(n,x)+-1*x^(1+m)*(m+n)^-1*SpecialFunctions.expint(-1m,x))\n@test integrate(x^m*SpecialFunctions.expint(n,b*x), x) == :(x^(1+m)*(m+n)^-1*SpecialFunctions.expint(n,b*x)+-1*x^(1+m)*(m+n)^-1*SpecialFunctions.expint(-1m,b*x))\n@test integrate((d*x)^m*SpecialFunctions.expint(n,x), x) == :(d^-1*(d*x)^(1+m)*(m+n)^-1*SpecialFunctions.expint(n,x)+-1*d^-1*(d*x)^(1+m)*(m+n)^-1*SpecialFunctions.expint(-1m,x))\n@test integrate((d*x)^m*SpecialFunctions.expint(n,b*x), x) == :(d^-1*(d*x)^(1+m)*(m+n)^-1*SpecialFunctions.expint(n,b*x)+-1*d^-1*(d*x)^(1+m)*(m+n)^-1*SpecialFunctions.expint(-1m,b*x))\n@test integrate(x^2*SpecialFunctions.expint(n,b*x), x) == :(x^3*(2+n)^-1*SpecialFunctions.expint(n,b*x)+-1*x^3*(2+n)^-1*SpecialFunctions.expint(-2,b*x))\n@test integrate(x*SpecialFunctions.expint(n,b*x), x) == :(x^2*(1+n)^-1*SpecialFunctions.expint(n,b*x)+-1*x^2*(1+n)^-1*SpecialFunctions.expint(-1,b*x))\n@test integrate(SpecialFunctions.expint(n,b*x), x) == :(-1*b^-1*SpecialFunctions.expint(1+n,b*x))\n@test integrate(x^-1*SpecialFunctions.expint(n,b*x), x) == :((1+-1n)^-1*SpecialFunctions.expint(1,b*x)+-1*(1+-1n)^-1*SpecialFunctions.expint(n,b*x))\n@test integrate(x^-2*SpecialFunctions.expint(n,b*x), x) == :(x^-1*(2+-1n)^-1*SpecialFunctions.expint(2,b*x)+-1*x^-1*(2+-1n)^-1*SpecialFunctions.expint(n,b*x))\n@test integrate(x^-3*SpecialFunctions.expint(n,b*x), x) == :(x^-2*(3+-1n)^-1*SpecialFunctions.expint(3,b*x)+-1*x^-2*(3+-1n)^-1*SpecialFunctions.expint(n,b*x))\n@test integrate((c+d*x)^3*SpecialFunctions.expint(1,a+b*x), x) == :(-1*b^-1*(c+d*x)^3*SpecialFunctions.expint(2,a+b*x)+-6*b^-4*d^3*SpecialFunctions.expint(5,a+b*x)+-6*b^-3*d^2*(c+d*x)*SpecialFunctions.expint(4,a+b*x)+-3*d*b^-2*(c+d*x)^2*SpecialFunctions.expint(3,a+b*x))\n@test integrate((c+d*x)^2*SpecialFunctions.expint(1,a+b*x), x) == :(-1*b^-1*(c+d*x)^2*SpecialFunctions.expint(2,a+b*x)+-2*b^-3*d^2*SpecialFunctions.expint(4,a+b*x)+-2*d*b^-2*(c+d*x)*SpecialFunctions.expint(3,a+b*x))\n@test integrate((c+d*x)*SpecialFunctions.expint(1,a+b*x), x) == :(-1*d*b^-2*SpecialFunctions.expint(3,a+b*x)+-1*b^-1*(c+d*x)*SpecialFunctions.expint(2,a+b*x))\n@test integrate(SpecialFunctions.expint(1,a+b*x), x) == :(-1*b^-1*SpecialFunctions.expint(2,a+b*x))\n@test integrate((c+d*x)^-2*SpecialFunctions.expint(1,a+b*x), x) == :(-1*d^-1*(c+d*x)^-1*SpecialFunctions.expint(1,a+b*x)+-1*b*d^-1*(b*c+-1*a*d)^-1*expintegralei(-1a+-1*b*x)+b*d^-1*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^-3*SpecialFunctions.expint(1,a+b*x), x) == :(-1//2*d^-1*(c+d*x)^-2*SpecialFunctions.expint(1,a+b*x)+-1//2*b^2*d^-1*(b*c+-1*a*d)^-2*expintegralei(-1a+-1*b*x)+(1/2)*b^2*d^-1*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1//2*b*d^-1*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1//2*b^2*d^-2*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^-4*SpecialFunctions.expint(1,a+b*x), x) == :(-1//3*d^-1*(c+d*x)^-3*SpecialFunctions.expint(1,a+b*x)+-1//3*b^3*d^-1*(b*c+-1*a*d)^-3*expintegralei(-1a+-1*b*x)+-1//3*b^2*d^-1*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+-1//3*b^3*d^-2*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1//6*b*d^-1*(c+d*x)^-2*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+1//3*b^3*d^-1*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+1//6*b^2*d^-2*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+1//6*b^3*d^-3*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^3*SpecialFunctions.expint(2,a+b*x), x) == :(-1*b^-1*(c+d*x)^3*SpecialFunctions.expint(3,a+b*x)+-6*b^-4*d^3*SpecialFunctions.expint(6,a+b*x)+-6*b^-3*d^2*(c+d*x)*SpecialFunctions.expint(5,a+b*x)+-3*d*b^-2*(c+d*x)^2*SpecialFunctions.expint(4,a+b*x))\n@test integrate((c+d*x)^2*SpecialFunctions.expint(2,a+b*x), x) == :(-1*b^-1*(c+d*x)^2*SpecialFunctions.expint(3,a+b*x)+-2*b^-3*d^2*SpecialFunctions.expint(5,a+b*x)+-2*d*b^-2*(c+d*x)*SpecialFunctions.expint(4,a+b*x))\n@test integrate((c+d*x)*SpecialFunctions.expint(2,a+b*x), x) == :(-1*d*b^-2*SpecialFunctions.expint(4,a+b*x)+-1*b^-1*(c+d*x)*SpecialFunctions.expint(3,a+b*x))\n@test integrate(SpecialFunctions.expint(2,a+b*x), x) == :(-1*b^-1*SpecialFunctions.expint(3,a+b*x))\n@test integrate((c+d*x)^-3*SpecialFunctions.expint(2,a+b*x), x) == :(-1//2*d^-1*(c+d*x)^-2*SpecialFunctions.expint(2,a+b*x)+(1/2)*b*d^-2*(c+d*x)^-1*SpecialFunctions.expint(1,a+b*x)+(1/2)*b^2*d^-2*(b*c+-1*a*d)^-1*expintegralei(-1a+-1*b*x)+-1//2*b^2*d^-2*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^-4*SpecialFunctions.expint(2,a+b*x), x) == :(-1//3*d^-1*(c+d*x)^-3*SpecialFunctions.expint(2,a+b*x)+1//6*b*d^-2*(c+d*x)^-2*SpecialFunctions.expint(1,a+b*x)+1//6*b^3*d^-2*(b*c+-1*a*d)^-2*expintegralei(-1a+-1*b*x)+-1//6*b^3*d^-2*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+1//6*b^2*d^-2*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+1//6*b^3*d^-3*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^3*SpecialFunctions.expint(3,a+b*x), x) == :(-1*b^-1*(c+d*x)^3*SpecialFunctions.expint(4,a+b*x)+-6*b^-4*d^3*SpecialFunctions.expint(7,a+b*x)+-6*b^-3*d^2*(c+d*x)*SpecialFunctions.expint(6,a+b*x)+-3*d*b^-2*(c+d*x)^2*SpecialFunctions.expint(5,a+b*x))\n@test integrate((c+d*x)^2*SpecialFunctions.expint(3,a+b*x), x) == :(-1*b^-1*(c+d*x)^2*SpecialFunctions.expint(4,a+b*x)+-2*b^-3*d^2*SpecialFunctions.expint(6,a+b*x)+-2*d*b^-2*(c+d*x)*SpecialFunctions.expint(5,a+b*x))\n@test integrate((c+d*x)*SpecialFunctions.expint(3,a+b*x), x) == :(-1*d*b^-2*SpecialFunctions.expint(5,a+b*x)+-1*b^-1*(c+d*x)*SpecialFunctions.expint(4,a+b*x))\n@test integrate(SpecialFunctions.expint(3,a+b*x), x) == :(-1*b^-1*SpecialFunctions.expint(4,a+b*x))\n@test integrate((c+d*x)^-4*SpecialFunctions.expint(3,a+b*x), x) == :(-1//3*d^-1*(c+d*x)^-3*SpecialFunctions.expint(3,a+b*x)+-1//6*b^2*d^-3*(c+d*x)^-1*SpecialFunctions.expint(1,a+b*x)+-1//6*b^3*d^-3*(b*c+-1*a*d)^-1*expintegralei(-1a+-1*b*x)+1//6*b*d^-2*(c+d*x)^-2*SpecialFunctions.expint(2,a+b*x)+1//6*b^3*d^-3*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^4*SpecialFunctions.expint(-1,a+b*x), x) == :(-8*b^-5*d^4*exp(-1a+-1*b*x)+-1*b^-1*(a+b*x)^-1*(c+d*x)^4*exp(-1a+-1*b*x)+-8*b^-4*d^3*(c+d*x)*exp(-1a+-1*b*x)+-4*b^-5*d^2*(b*c+-1*a*d)^2*exp(-1a+-1*b*x)+-4*b^-5*d^3*(b*c+-1*a*d)*exp(-1a+-1*b*x)+-4*b^-3*d^2*(c+d*x)^2*exp(-1a+-1*b*x)+4*d*b^-5*(b*c+-1*a*d)^3*expintegralei(-1a+-1*b*x)+-4*b^-4*d^2*(c+d*x)*(b*c+-1*a*d)*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^3*SpecialFunctions.expint(-1,a+b*x), x) == :(-3*b^-4*d^3*exp(-1a+-1*b*x)+-1*b^-1*(a+b*x)^-1*(c+d*x)^3*exp(-1a+-1*b*x)+-3*b^-4*d^2*(b*c+-1*a*d)*exp(-1a+-1*b*x)+-3*b^-3*d^2*(c+d*x)*exp(-1a+-1*b*x)+3*d*b^-4*(b*c+-1*a*d)^2*expintegralei(-1a+-1*b*x))\n@test integrate((c+d*x)^2*SpecialFunctions.expint(-1,a+b*x), x) == :(-2*b^-3*d^2*exp(-1a+-1*b*x)+-1*b^-1*(a+b*x)^-1*(c+d*x)^2*exp(-1a+-1*b*x)+2*d*b^-3*(b*c+-1*a*d)*expintegralei(-1a+-1*b*x))\n@test integrate((c+d*x)*SpecialFunctions.expint(-1,a+b*x), x) == :(d*b^-2*expintegralei(-1a+-1*b*x)+-1*b^-1*(a+b*x)^-1*(c+d*x)*exp(-1a+-1*b*x))\n@test integrate(SpecialFunctions.expint(-1,a+b*x), x) == :(-1*b^-1*(a+b*x)^-1*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^-1*SpecialFunctions.expint(-1,a+b*x), x) == :(-1*d*(b*c+-1*a*d)^-2*expintegralei(-1a+-1*b*x)+-1*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+d*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1*b^-1*(a+b*x)^-1*(c+d*x)^-1*exp(-1a+-1*b*x)+-1*d*b^-1*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^-2*SpecialFunctions.expint(-1,a+b*x), x) == :((c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1*b^-1*(a+b*x)^-1*(c+d*x)^-2*exp(-1a+-1*b*x)+-2*b*d*(b*c+-1*a*d)^-3*expintegralei(-1a+-1*b*x)+-2*b*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-2*d*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+b*d^-1*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1*d*b^-1*(c+d*x)^-2*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+2*b*d*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^-3*SpecialFunctions.expint(-1,a+b*x), x) == :((c+d*x)^-2*(-2*a*d+2*b*c)^-1*exp(-1a+-1*b*x)+-1*b^-1*(a+b*x)^-1*(c+d*x)^-3*exp(-1a+-1*b*x)+-3*d*b^2*(b*c+-1*a*d)^-4*expintegralei(-1a+-1*b*x)+-3*b^2*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-3//2*d*(c+d*x)^-2*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+3//2*b*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+-1*d*b^-1*(c+d*x)^-3*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-3*b*d*(c+d*x)^-1*(b*c+-1*a*d)^-3*exp(-1a+-1*b*x)+3*d*b^2*(b*c+-1*a*d)^-4*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1//2*b*d^-1*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1//2*b^2*d^-2*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+3//2*b^2*d^-1*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^4*SpecialFunctions.expint(-2,a+b*x), x) == :(-1*b^-1*(c+d*x)^4*SpecialFunctions.expint(-1,a+b*x)+-12*b^-5*d^4*exp(-1a+-1*b*x)+-12*b^-5*d^3*(b*c+-1*a*d)*exp(-1a+-1*b*x)+-12*b^-4*d^3*(c+d*x)*exp(-1a+-1*b*x)+12*b^-5*d^2*(b*c+-1*a*d)^2*expintegralei(-1a+-1*b*x)+-4*d*b^-2*(a+b*x)^-1*(c+d*x)^3*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^3*SpecialFunctions.expint(-2,a+b*x), x) == :(-1*b^-1*(c+d*x)^3*SpecialFunctions.expint(-1,a+b*x)+-6*b^-4*d^3*exp(-1a+-1*b*x)+6*b^-4*d^2*(b*c+-1*a*d)*expintegralei(-1a+-1*b*x)+-3*d*b^-2*(a+b*x)^-1*(c+d*x)^2*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^2*SpecialFunctions.expint(-2,a+b*x), x) == :(-1*b^-1*(c+d*x)^2*SpecialFunctions.expint(-1,a+b*x)+2*b^-3*d^2*expintegralei(-1a+-1*b*x)+-2*d*b^-2*(a+b*x)^-1*(c+d*x)*exp(-1a+-1*b*x))\n@test integrate((c+d*x)*SpecialFunctions.expint(-2,a+b*x), x) == :(-1*b^-1*(c+d*x)*SpecialFunctions.expint(-1,a+b*x)+-1*d*b^-2*(a+b*x)^-1*exp(-1a+-1*b*x))\n@test integrate(SpecialFunctions.expint(-2,a+b*x), x) == :(-1*b^-1*SpecialFunctions.expint(-1,a+b*x))\n@test integrate((c+d*x)^-1*SpecialFunctions.expint(-2,a+b*x), x) == :(-1*b^-1*(c+d*x)^-1*SpecialFunctions.expint(-1,a+b*x)+-1*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+2*d^2*(b*c+-1*a*d)^-3*expintegralei(-1a+-1*b*x)+-2*d^2*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+2*d*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+d*b^-2*(a+b*x)^-1*(c+d*x)^-2*exp(-1a+-1*b*x)+b^-2*d^2*(c+d*x)^-2*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1*d*b^-1*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+2*b^-1*d^2*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^-2*SpecialFunctions.expint(-2,a+b*x), x) == :((c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1*b^-1*(c+d*x)^-2*SpecialFunctions.expint(-1,a+b*x)+-3*b*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-3*d*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+6*b*d^2*(b*c+-1*a*d)^-4*expintegralei(-1a+-1*b*x)+6*d^2*(c+d*x)^-1*(b*c+-1*a*d)^-3*exp(-1a+-1*b*x)+b*d^-1*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1*d*b^-1*(c+d*x)^-2*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-6*b*d^2*(b*c+-1*a*d)^-4*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+2*d*b^-2*(a+b*x)^-1*(c+d*x)^-3*exp(-1a+-1*b*x)+2*b^-2*d^2*(c+d*x)^-3*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+3*b^-1*d^2*(c+d*x)^-2*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+6*b*d*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^-3*SpecialFunctions.expint(-2,a+b*x), x) == :((c+d*x)^-2*(-2*a*d+2*b*c)^-1*exp(-1a+-1*b*x)+-1*b^-1*(c+d*x)^-3*SpecialFunctions.expint(-1,a+b*x)+-6*b^2*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-2*d*(c+d*x)^-2*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+2*b*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+6*d^2*(c+d*x)^-2*(b*c+-1*a*d)^-3*exp(-1a+-1*b*x)+12*b^2*d^2*(b*c+-1*a*d)^-5*expintegralei(-1a+-1*b*x)+-1*d*b^-1*(c+d*x)^-3*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-12*b^2*d^2*(b*c+-1*a*d)^-5*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-6*b*d*(c+d*x)^-1*(b*c+-1*a*d)^-3*exp(-1a+-1*b*x)+2*b^2*d^-1*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+3*d*b^-2*(a+b*x)^-1*(c+d*x)^-4*exp(-1a+-1*b*x)+3*b^-2*d^2*(c+d*x)^-4*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+4*b^-1*d^2*(c+d*x)^-3*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+12*b*d^2*(c+d*x)^-1*(b*c+-1*a*d)^-4*exp(-1a+-1*b*x)+12*d*b^2*(b*c+-1*a*d)^-4*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1//2*b*d^-1*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1//2*b^2*d^-2*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^4*SpecialFunctions.expint(-3,a+b*x), x) == :(-1*b^-1*(c+d*x)^4*SpecialFunctions.expint(-2,a+b*x)+-24*b^-5*d^4*exp(-1a+-1*b*x)+-4*d*b^-2*(c+d*x)^3*SpecialFunctions.expint(-1,a+b*x)+24*b^-5*d^3*(b*c+-1*a*d)*expintegralei(-1a+-1*b*x)+-12*b^-3*d^2*(a+b*x)^-1*(c+d*x)^2*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^3*SpecialFunctions.expint(-3,a+b*x), x) == :(-1*b^-1*(c+d*x)^3*SpecialFunctions.expint(-2,a+b*x)+6*b^-4*d^3*expintegralei(-1a+-1*b*x)+-3*d*b^-2*(c+d*x)^2*SpecialFunctions.expint(-1,a+b*x)+-6*b^-3*d^2*(a+b*x)^-1*(c+d*x)*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^2*SpecialFunctions.expint(-3,a+b*x), x) == :(-1*b^-1*(c+d*x)^2*SpecialFunctions.expint(-2,a+b*x)+-2*d*b^-2*(c+d*x)*SpecialFunctions.expint(-1,a+b*x)+-2*b^-3*d^2*(a+b*x)^-1*exp(-1a+-1*b*x))\n@test integrate((c+d*x)*SpecialFunctions.expint(-3,a+b*x), x) == :(-1*d*b^-2*SpecialFunctions.expint(-1,a+b*x)+-1*b^-1*(c+d*x)*SpecialFunctions.expint(-2,a+b*x))\n@test integrate(SpecialFunctions.expint(-3,a+b*x), x) == :(-1*b^-1*SpecialFunctions.expint(-2,a+b*x))\n@test integrate((c+d*x)^-1*SpecialFunctions.expint(-3,a+b*x), x) == :(-1*b^-1*(c+d*x)^-1*SpecialFunctions.expint(-2,a+b*x)+-1*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-6*d^3*(b*c+-1*a*d)^-4*expintegralei(-1a+-1*b*x)+d*b^-2*(c+d*x)^-2*SpecialFunctions.expint(-1,a+b*x)+-6*d^2*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+3*d*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+6*d^3*(b*c+-1*a*d)^-4*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+b^-2*d^2*(c+d*x)^-2*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1*d*b^-1*(c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-6*b^-1*d^3*(c+d*x)^-1*(b*c+-1*a*d)^-3*exp(-1a+-1*b*x)+-3*b^-2*d^3*(c+d*x)^-2*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+-2*b^-3*d^2*(a+b*x)^-1*(c+d*x)^-3*exp(-1a+-1*b*x)+-2*b^-3*d^3*(c+d*x)^-3*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+3*b^-1*d^2*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x))\n@test integrate((c+d*x)^-2*SpecialFunctions.expint(-3,a+b*x), x) == :((c+d*x)^-1*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-1*b^-1*(c+d*x)^-2*SpecialFunctions.expint(-2,a+b*x)+-24*b*d^3*(b*c+-1*a*d)^-5*expintegralei(-1a+-1*b*x)+-24*d^3*(c+d*x)^-1*(b*c+-1*a*d)^-4*exp(-1a+-1*b*x)+-4*b*(b*c+-1*a*d)^-2*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-4*d*(c+d*x)^-1*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+2*d*b^-2*(c+d*x)^-3*SpecialFunctions.expint(-1,a+b*x)+12*d^2*(c+d*x)^-1*(b*c+-1*a*d)^-3*exp(-1a+-1*b*x)+b*d^-1*(b*c+-1*a*d)^-1*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-1*d*b^-1*(c+d*x)^-2*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+-24*b*d^2*(b*c+-1*a*d)^-4*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+-12*b^-1*d^3*(c+d*x)^-2*(b*c+-1*a*d)^-3*exp(-1a+-1*b*x)+-8*b^-2*d^3*(c+d*x)^-3*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+-6*b^-3*d^2*(a+b*x)^-1*(c+d*x)^-4*exp(-1a+-1*b*x)+-6*b^-3*d^3*(c+d*x)^-4*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+2*b^-2*d^2*(c+d*x)^-3*(b*c+-1*a*d)^-1*exp(-1a+-1*b*x)+4*b^-1*d^2*(c+d*x)^-2*(b*c+-1*a*d)^-2*exp(-1a+-1*b*x)+12*b*d*(b*c+-1*a*d)^-3*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x))+24*b*d^3*(b*c+-1*a*d)^-5*exp(-1a+b*c*d^-1)*expintegralei(-1*b*d^-1*(c+d*x)))\n@test integrate((c+d*x)^3*SpecialFunctions.expint(n,a+b*x), x) == :(-1*b^-1*(c+d*x)^3*SpecialFunctions.expint(1+n,a+b*x)+-6*b^-4*d^3*SpecialFunctions.expint(4+n,a+b*x)+-6*b^-3*d^2*(c+d*x)*SpecialFunctions.expint(3+n,a+b*x)+-3*d*b^-2*(c+d*x)^2*SpecialFunctions.expint(2+n,a+b*x))\n@test integrate((c+d*x)^2*SpecialFunctions.expint(n,a+b*x), x) == :(-1*b^-1*(c+d*x)^2*SpecialFunctions.expint(1+n,a+b*x)+-2*b^-3*d^2*SpecialFunctions.expint(3+n,a+b*x)+-2*d*b^-2*(c+d*x)*SpecialFunctions.expint(2+n,a+b*x))\n@test integrate((c+d*x)*SpecialFunctions.expint(n,a+b*x), x) == :(-1*d*b^-2*SpecialFunctions.expint(2+n,a+b*x)+-1*b^-1*(c+d*x)*SpecialFunctions.expint(1+n,a+b*x))\n@test integrate(SpecialFunctions.expint(n,a+b*x), x) == :(-1*b^-1*SpecialFunctions.expint(1+n,a+b*x))\n@test integrate(x^3*expintegralei(b*x), x) == :(1//4*x^4*expintegralei(b*x)+3//2*b^-4*exp(b*x)+-3//2*x*b^-3*exp(b*x)+-1//4*b^-1*x^3*exp(b*x)+3//4*b^-2*x^2*exp(b*x))\n@test integrate(x^2*expintegralei(b*x), x) == :(-2//3*b^-3*exp(b*x)+1//3*x^3*expintegralei(b*x)+-1//3*b^-1*x^2*exp(b*x)+2//3*x*b^-2*exp(b*x))\n@test integrate(x*expintegralei(b*x), x) == :((1/2)*b^-2*exp(b*x)+(1/2)*x^2*expintegralei(b*x)+-1//2*x*b^-1*exp(b*x))\n@test integrate(expintegralei(b*x), x) == :(x*expintegralei(b*x)+-1*b^-1*exp(b*x))\n@test integrate(x^-2*expintegralei(b*x), x) == :(b*expintegralei(b*x)+-1*x^-1*exp(b*x)+-1*x^-1*expintegralei(b*x))\n@test integrate(x^-3*expintegralei(b*x), x) == :(-1//2*x^-2*expintegralei(b*x)+-1//4*x^-2*exp(b*x)+1//4*b^2*expintegralei(b*x)+-1//4*b*x^-1*exp(b*x))\n@test integrate(x^-4*expintegralei(b*x), x) == :(-1//3*x^-3*expintegralei(b*x)+-1//9*x^-3*exp(b*x)+1//18*b^3*expintegralei(b*x)+-1//18*b*x^-2*exp(b*x)+-1//18*b^2*x^-1*exp(b*x))\n@test integrate(x^2*expintegralei(b*x)^2, x) == :(-5//6*b^-3*exp(2*b*x)+1//3*x^3*expintegralei(b*x)^2+4//3*b^-3*expintegralei(2*b*x)+-4//3*b^-3*exp(b*x)*expintegralei(b*x)+1//3*x*b^-2*exp(2*b*x)+-2//3*b^-1*x^2*exp(b*x)*expintegralei(b*x)+4//3*x*b^-2*exp(b*x)*expintegralei(b*x))\n@test integrate(x*expintegralei(b*x)^2, x) == :((1/2)*b^-2*exp(2*b*x)+(1/2)*x^2*expintegralei(b*x)^2+-1*b^-2*expintegralei(2*b*x)+b^-2*exp(b*x)*expintegralei(b*x)+-1*x*b^-1*exp(b*x)*expintegralei(b*x))\n@test integrate(expintegralei(b*x)^2, x) == :(x*expintegralei(b*x)^2+2*b^-1*expintegralei(2*b*x)+-2*b^-1*exp(b*x)*expintegralei(b*x))\n@test integrate((d*x)^m*expintegralei(b*x), x) == :(d^-1*(d*x)^(1+m)*(1+m)^-1*expintegralei(b*x)+-1*b^-1*(d*x)^m*(-1*b*x)^(-1m)*(1+m)^-1*SpecialFunctions.gamma(1+m,-1*b*x))\n@test integrate(x^3*expintegralei(a+b*x), x) == :(1//4*x^4*expintegralei(a+b*x)+3//2*b^-4*exp(a+b*x)+(1/2)*a*b^-4*exp(a+b*x)+-3//2*x*b^-3*exp(a+b*x)+-1//4*a^4*b^-4*expintegralei(a+b*x)+-1//4*b^-1*x^3*exp(a+b*x)+1//4*a^2*b^-4*exp(a+b*x)+1//4*a^3*b^-4*exp(a+b*x)+3//4*b^-2*x^2*exp(a+b*x)+-1//2*a*x*b^-3*exp(a+b*x)+-1//4*x*a^2*b^-3*exp(a+b*x)+1//4*a*b^-2*x^2*exp(a+b*x))\n@test integrate(x^2*expintegralei(a+b*x), x) == :(-2//3*b^-3*exp(a+b*x)+1//3*x^3*expintegralei(a+b*x)+-1//3*a*b^-3*exp(a+b*x)+-1//3*a^2*b^-3*exp(a+b*x)+-1//3*b^-1*x^2*exp(a+b*x)+1//3*a^3*b^-3*expintegralei(a+b*x)+2//3*x*b^-2*exp(a+b*x)+1//3*a*x*b^-2*exp(a+b*x))\n@test integrate(x*expintegralei(a+b*x), x) == :((1/2)*b^-2*exp(a+b*x)+(1/2)*x^2*expintegralei(a+b*x)+(1/2)*a*b^-2*exp(a+b*x)+-1//2*x*b^-1*exp(a+b*x)+-1//2*a^2*b^-2*expintegralei(a+b*x))\n@test integrate(expintegralei(a+b*x), x) == :(-1*b^-1*exp(a+b*x)+b^-1*(a+b*x)*expintegralei(a+b*x))\n@test integrate(x^-2*expintegralei(a+b*x), x) == :(-1*x^-1*expintegralei(a+b*x)+-1*b*a^-1*expintegralei(a+b*x)+b*a^-1*exp(a)*expintegralei(b*x))\n@test integrate(x^-3*expintegralei(a+b*x), x) == :(-1//2*x^-2*expintegralei(a+b*x)+(1/2)*a^-2*b^2*expintegralei(a+b*x)+(1/2)*a^-1*b^2*exp(a)*expintegralei(b*x)+-1//2*b*a^-1*x^-1*exp(a+b*x)+-1//2*a^-2*b^2*exp(a)*expintegralei(b*x))\n@test integrate(x^2*expintegralei(a+b*x)^2, x) == :(-5//6*b^-3*exp(2a+2*b*x)+1//3*x^3*expintegralei(a+b*x)^2+4//3*b^-3*expintegralei(2a+2*b*x)+2*a*b^-3*expintegralei(2a+2*b*x)+2*a^2*b^-3*expintegralei(2a+2*b*x)+-4//3*b^-3*exp(a+b*x)*expintegralei(a+b*x)+-2//3*a*b^-3*exp(2a+2*b*x)+1//3*x*b^-2*exp(2a+2*b*x)+-2//3*a*b^-3*exp(a+b*x)*expintegralei(a+b*x)+-2//3*a^2*b^-3*exp(a+b*x)*expintegralei(a+b*x)+-2//3*b^-1*x^2*exp(a+b*x)*expintegralei(a+b*x)+-1//3*x*a^2*b^-2*expintegralei(a+b*x)^2+1//3*a^2*b^-3*expintegralei(a+b*x)^2*(a+b*x)+4//3*x*b^-2*exp(a+b*x)*expintegralei(a+b*x)+2//3*a*x*b^-2*exp(a+b*x)*expintegralei(a+b*x))\n@test integrate(x*expintegralei(a+b*x)^2, x) == :((1/2)*b^-2*exp(2a+2*b*x)+(1/2)*x^2*expintegralei(a+b*x)^2+-1*b^-2*expintegralei(2a+2*b*x)+b^-2*exp(a+b*x)*expintegralei(a+b*x)+-2*a*b^-2*expintegralei(2a+2*b*x)+a*b^-2*exp(a+b*x)*expintegralei(a+b*x)+(1/2)*a*x*b^-1*expintegralei(a+b*x)^2+-1*x*b^-1*exp(a+b*x)*expintegralei(a+b*x)+-1//2*a*b^-2*expintegralei(a+b*x)^2*(a+b*x))\n@test integrate(expintegralei(a+b*x)^2, x) == :(2*b^-1*expintegralei(2a+2*b*x)+b^-1*expintegralei(a+b*x)^2*(a+b*x)+-2*b^-1*exp(a+b*x)*expintegralei(a+b*x))\n@test integrate(x^2*expintegralei(d*(a+b*log(c*x^n))), x) == :(1//3*x^3*expintegralei(d*(a+b*log(c*x^n)))+-1//3*x^3*(c*x^n)^(-3*n^-1)*exp(-3*a*b^-1*n^-1)*expintegralei(b^-1*n^-1*(3+b*d*n)*(a+b*log(c*x^n))))\n@test integrate(x*expintegralei(d*(a+b*log(c*x^n))), x) == :((1/2)*x^2*expintegralei(d*(a+b*log(c*x^n)))+-1//2*x^2*(c*x^n)^(-2*n^-1)*exp(-2*a*b^-1*n^-1)*expintegralei(b^-1*n^-1*(2+b*d*n)*(a+b*log(c*x^n))))\n@test integrate(expintegralei(d*(a+b*log(c*x^n))), x) == :(x*expintegralei(d*(a+b*log(c*x^n)))+-1*x*(c*x^n)^(-1*n^-1)*exp(-1*a*b^-1*n^-1)*expintegralei(b^-1*n^-1*(1+b*d*n)*(a+b*log(c*x^n))))\n@test integrate(x^-1*expintegralei(d*(a+b*log(c*x^n))), x) == :(b^-1*n^-1*(a+b*log(c*x^n))*expintegralei(d*(a+b*log(c*x^n)))+-1*b^-1*d^-1*n^-1*(c*x^n)^(b*d)*exp(a*d))\n@test integrate(x^-2*expintegralei(d*(a+b*log(c*x^n))), x) == :(-1*x^-1*expintegralei(d*(a+b*log(c*x^n)))+x^-1*(c*x^n)^(n^-1)*exp(a*b^-1*n^-1)*expintegralei(-1*b^-1*n^-1*(1+-1*b*d*n)*(a+b*log(c*x^n))))\n@test integrate(x^-3*expintegralei(d*(a+b*log(c*x^n))), x) == :(-1//2*x^-2*expintegralei(d*(a+b*log(c*x^n)))+(1/2)*x^-2*(c*x^n)^(2*n^-1)*exp(2*a*b^-1*n^-1)*expintegralei(-1*b^-1*n^-1*(2+-1*b*d*n)*(a+b*log(c*x^n))))\n@test integrate((e*x)^m*expintegralei(d*(a+b*log(c*x^n))), x) == :(e^-1*(e*x)^(1+m)*(1+m)^-1*expintegralei(d*(a+b*log(c*x^n)))+-1*e^-1*(c*x^n)^(-1*n^-1*(1+m))*(e*x)^(1+m)*(1+m)^-1*exp(-1*a*b^-1*n^-1*(1+m))*expintegralei(b^-1*n^-1*(a+b*log(c*x^n))*(1+m+b*d*n)))\n@test integrate(x^-3*exp(b*x)*expintegralei(b*x), x) == :(2*b^2*expintegralei(2*b*x)+-1//4*x^-2*exp(2*b*x)+1//4*b^2*expintegralei(b*x)^2+-1*b*x^-1*exp(2*b*x)+-1//2*x^-2*exp(b*x)*expintegralei(b*x)+-1//2*b*x^-1*exp(b*x)*expintegralei(b*x))\n@test integrate(x^-2*exp(b*x)*expintegralei(b*x), x) == :((1/2)*b*expintegralei(b*x)^2+-1*x^-1*exp(2*b*x)+2*b*expintegralei(2*b*x)+-1*x^-1*exp(b*x)*expintegralei(b*x))\n@test integrate(x^-1*exp(b*x)*expintegralei(b*x), x) == :((1/2)*expintegralei(b*x)^2)\n@test integrate(exp(b*x)*expintegralei(b*x), x) == :(-1*b^-1*expintegralei(2*b*x)+b^-1*exp(b*x)*expintegralei(b*x))\n@test integrate(x*exp(b*x)*expintegralei(b*x), x) == :(b^-2*expintegralei(2*b*x)+-1//2*b^-2*exp(2*b*x)+-1*b^-2*exp(b*x)*expintegralei(b*x)+x*b^-1*exp(b*x)*expintegralei(b*x))\n@test integrate(x^2*exp(b*x)*expintegralei(b*x), x) == :(-2*b^-3*expintegralei(2*b*x)+5//4*b^-3*exp(2*b*x)+2*b^-3*exp(b*x)*expintegralei(b*x)+-1//2*x*b^-2*exp(2*b*x)+b^-1*x^2*exp(b*x)*expintegralei(b*x)+-2*x*b^-2*exp(b*x)*expintegralei(b*x))\n@test integrate(x^3*exp(b*x)*expintegralei(b*x), x) == :(-4*b^-4*exp(2*b*x)+6*b^-4*expintegralei(2*b*x)+-6*b^-4*exp(b*x)*expintegralei(b*x)+2*x*b^-3*exp(2*b*x)+-1//2*b^-2*x^2*exp(2*b*x)+b^-1*x^3*exp(b*x)*expintegralei(b*x)+-3*b^-2*x^2*exp(b*x)*expintegralei(b*x)+6*x*b^-3*exp(b*x)*expintegralei(b*x))\n@test integrate(x^3*exp(a+b*x)*expintegralei(c+d*x), x) == :(-6*b^-4*exp(a+b*x)*expintegralei(c+d*x)+-6*b^-3*(b+d)^-1*exp(a+c+x*(b+d))+-3*b^-2*(b+d)^-2*exp(a+c+x*(b+d))+-2*b^-1*(b+d)^-3*exp(a+c+x*(b+d))+6*b^-4*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x))+b^-1*x^3*exp(a+b*x)*expintegralei(c+d*x)+-1*b^-1*x^2*(b+d)^-1*exp(a+c+x*(b+d))+-3*b^-2*x^2*exp(a+b*x)*expintegralei(c+d*x)+2*x*b^-1*(b+d)^-2*exp(a+c+x*(b+d))+3*x*b^-2*(b+d)^-1*exp(a+c+x*(b+d))+6*x*b^-3*exp(a+b*x)*expintegralei(c+d*x)+b^-1*c^3*d^-3*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x))+-1*c*b^-1*d^-1*(b+d)^-2*exp(a+c+x*(b+d))+-1*b^-1*c^2*d^-2*(b+d)^-1*exp(a+c+x*(b+d))+-3*c*b^-2*d^-1*(b+d)^-1*exp(a+c+x*(b+d))+3*b^-2*c^2*d^-2*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x))+6*c*b^-3*d^-1*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x))+c*x*b^-1*d^-1*(b+d)^-1*exp(a+c+x*(b+d)))\n@test integrate(x^2*exp(a+b*x)*expintegralei(c+d*x), x) == :(b^-1*(b+d)^-2*exp(a+c+x*(b+d))+-2*b^-3*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x))+2*b^-3*exp(a+b*x)*expintegralei(c+d*x)+2*b^-2*(b+d)^-1*exp(a+c+x*(b+d))+b^-1*x^2*exp(a+b*x)*expintegralei(c+d*x)+-1*x*b^-1*(b+d)^-1*exp(a+c+x*(b+d))+-2*x*b^-2*exp(a+b*x)*expintegralei(c+d*x)+c*b^-1*d^-1*(b+d)^-1*exp(a+c+x*(b+d))+-1*b^-1*c^2*d^-2*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x))+-2*c*b^-2*d^-1*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x)))\n@test integrate(x*exp(a+b*x)*expintegralei(c+d*x), x) == :(b^-2*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x))+-1*b^-1*(b+d)^-1*exp(a+c+x*(b+d))+-1*b^-2*exp(a+b*x)*expintegralei(c+d*x)+x*b^-1*exp(a+b*x)*expintegralei(c+d*x)+c*b^-1*d^-1*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x)))\n@test integrate(exp(a+b*x)*expintegralei(c+d*x), x) == :(b^-1*exp(a+b*x)*expintegralei(c+d*x)+-1*b^-1*exp(a+-1*b*c*d^-1)*expintegralei(d^-1*(b+d)*(c+d*x)))\n@test integrate(x^2*logintegral(b*x), x) == :(-1//3*b^-3*expintegralei(4*log(b*x))+1//3*x^3*logintegral(b*x))\n@test integrate(x*logintegral(b*x), x) == :((1/2)*x^2*logintegral(b*x)+-1//2*b^-2*expintegralei(3*log(b*x)))\n@test integrate(logintegral(b*x), x) == :(x*logintegral(b*x)+-1*b^-1*expintegralei(2*log(b*x)))\n@test integrate(x^-1*logintegral(b*x), x) == :(log(b*x)*logintegral(b*x)+-1*b*x)\n@test integrate(x^-2*logintegral(b*x), x) == :(b*log(log(b*x))+-1*x^-1*logintegral(b*x))\n@test integrate(x^-3*logintegral(b*x), x) == :((1/2)*b^2*expintegralei(-1*log(b*x))+-1//2*x^-2*logintegral(b*x))\n@test integrate((d*x)^m*logintegral(b*x), x) == :(d^-1*(d*x)^(1+m)*(1+m)^-1*logintegral(b*x)+-1*b*d^-2*(b*x)^(-2+-1m)*(d*x)^(2+m)*(1+m)^-1*expintegralei((2+m)*log(b*x)))\n@test integrate(x^2*logintegral(a+b*x), x) == :(-1//3*b^-3*expintegralei(4*log(a+b*x))+1//3*x^3*logintegral(a+b*x)+a*b^-3*expintegralei(3*log(a+b*x))+-1*a^2*b^-3*expintegralei(2*log(a+b*x))+1//3*a^3*b^-3*logintegral(a+b*x))\n@test integrate(x*logintegral(a+b*x), x) == :((1/2)*x^2*logintegral(a+b*x)+-1//2*b^-2*expintegralei(3*log(a+b*x))+a*b^-2*expintegralei(2*log(a+b*x))+-1//2*a^2*b^-2*logintegral(a+b*x))\n@test integrate(logintegral(a+b*x), x) == :(-1*b^-1*expintegralei(2*log(a+b*x))+b^-1*(a+b*x)*logintegral(a+b*x))\n", "meta": {"hexsha": "fd501e4a4de32e7946ad192653152c183deff48b", "size": 33235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/8 Special functions/8.3 Exponential integral functions.jl", "max_stars_repo_name": "bradeneliason/Rubin.jl", "max_stars_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-13T03:00:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T03:00:21.000Z", "max_issues_repo_path": "test/8 Special functions/8.3 Exponential integral functions.jl", "max_issues_repo_name": "bradeneliason/Rubin.jl", "max_issues_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_issues_repo_licenses": ["MIT"], "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/8 Special functions/8.3 Exponential integral functions.jl", "max_forks_repo_name": "bradeneliason/Rubin.jl", "max_forks_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 207.71875, "max_line_length": 1171, "alphanum_fraction": 0.5895291109, "num_tokens": 15340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7549260694438651}}
{"text": "using SatisfiabilityInterface: subscript\n\n\n@testset \"Sudoku\" begin\n\n\n    function all_different(v)\n        vv = vec(v)\n        n = length(vv)\n\n        return [vv[i] \u2260 vv[j] for i in 1:n for j in i+1:n]\n    end\n\n\n\n    function make_matrix(name, T, m, n)\n        return [T(Symbol(name, subscript(i), \",\", subscript(j))) \n            for i in 1:m, j in 1:n]\n    end\n\n    n = 9\n    M = make_matrix(:M, BoundedInteger{n}, n, n)\n\n    m = Model()\n\n    push!(m, vec(M)...)\n\n\n    for i in 1:n\n        append!(m.constraints, all_different(M[:, i]))  # columns\n        append!(m.constraints, all_different(M[i, :]))  # rows\n    end\n\n    # blocks:\n    for i in 0:2, j in 0:2\n        append!(m.constraints, all_different(M[3i+1:3i+3, 3j+1:3j+3]))\n    end\n\n    i, j = 0, 0\n    all_different(M[3i+1:3i+3, 3j+1:3j+3])\n\n    ## initial condition from https://www.juliaopt.org/notebooks/JuMP-Sudoku.html\n\n    initial = [\n    5 3 -1 -1 7 -1 -1 -1 -1\n    6 -1 -1 1 9 5 -1 -1 -1\n    -1 9 8 -1 -1 -1 -1 6 -1\n    8 -1 -1 -1 6 -1 -1 -1 3\n    4 -1 -1 8 -1 3 -1 -1 1\n    7 -1 -1 -1 2 -1 -1 -1 6\n    -1 6 -1 -1 -1 -1 2 8 -1\n    -1 -1 -1 4 1 9 -1 -1 5\n    -1 -1 -1 -1 8 -1 -1 7 9\n    ]\n\n    for i in 1:9, j in 1:9\n        if initial[i, j] > 0 \n            push!(m.constraints, M[i, j] ~ initial[i, j])\n        end\n    end\n\n    @time status, results = solve(m);\n\n    output = [results[M[i, j]] for i in 1:9, j in 1:9]\n\n    @test output == [\n        5  3  4  6  7  8  9  1  2\n        6  7  2  1  9  5  3  4  8\n        1  9  8  3  4  2  5  6  7\n        8  5  9  7  6  1  4  2  3\n        4  2  6  8  5  3  7  9  1\n        7  1  3  9  2  4  8  5  6\n        9  6  1  5  3  7  2  8  4\n        2  8  7  4  1  9  6  3  5\n        3  4  5  2  8  6  1  7  9\n    ]\n\nend", "meta": {"hexsha": "fd2ea115f0ed6a2b6c56f3a9be2b31974b5d765f", "size": 1727, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/sudoku.jl", "max_stars_repo_name": "blegat/SatisfiabilityInterface.jl", "max_stars_repo_head_hexsha": "62c21f55636eb41f2568c02a953bc01095815b49", "max_stars_repo_licenses": ["MIT"], "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/sudoku.jl", "max_issues_repo_name": "blegat/SatisfiabilityInterface.jl", "max_issues_repo_head_hexsha": "62c21f55636eb41f2568c02a953bc01095815b49", "max_issues_repo_licenses": ["MIT"], "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/sudoku.jl", "max_forks_repo_name": "blegat/SatisfiabilityInterface.jl", "max_forks_repo_head_hexsha": "62c21f55636eb41f2568c02a953bc01095815b49", "max_forks_repo_licenses": ["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.141025641, "max_line_length": 81, "alphanum_fraction": 0.4568616097, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659996, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7549260678874057}}
{"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, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    sign * (spot * exp((b-r) * \u03c4) * cdf(std_normal, sign * d1) - strike * exp(-r * \u03c4) * cdf(std_normal, sign * d2))\nend\n\nfunction blackScholesDelta(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    if isCall\n        exp((b-r) * \u03c4) * cdf(std_normal, d1)\n    else\n        exp((b-r) * \u03c4) * (cdf(std_normal, d1) - 1.0)\n    end\nend\n\nfunction blackScholesGamma(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    pdf(std_normal, d1) * exp((b-r) * \u03c4) / spot / \u03c3 / sqrt(\u03c4)\nend\n\nfunction blackScholesVega(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    spot * exp((b-r) * \u03c4) * pdf(std_normal, d1) * sqrt(\u03c4)\nend\n\nfunction blackScholesTheta(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    term1 = -spot * exp((b-r) * \u03c4) * pdf(std_normal, d1) * \u03c3 / 2 / sqrt(\u03c4)\n    term2 = -sign * (b-r) * spot * exp((b-r) * \u03c4) * cdf(std_normal, sign * d1)\n    term3 = -sign * r * strike * exp(-r * \u03c4) * cdf(std_normal, sign * d2)\n\n    term1 + term2 + term3\nend\n\nfunction blackScholesVanna(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    -d2 * pdf(std_normal, d1) / \u03c3 * exp((b-r) * \u03c4)\nend\n\nfunction blackScholesCharm(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    term1 = pdf(std_normal, d1) * (b / \u03c3 / sqrt(\u03c4) - d2 / 2 / \u03c4)\n    term2 = sign * (b - r) * cdf(std_normal, sign * d1)\n\n    -exp((b-r) * \u03c4) * (term1 + term2)\nend\n\nfunction blackScholesVolga(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    blackScholesVega(isCall, spot, strike, \u03c4, r, b, \u03c3) * d1 * d2 / \u03c3\nend\n\nfunction blackScholesSpeed(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n\n    -1.0 * blackScholesGamma(isCall, spot, strike, \u03c4, r, b, \u03c3) / spot * (1 + d1 / \u03c3 / sqrt(\u03c4))\nend\n\nfunction blackScholesZomma(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    blackScholesGamma(isCall, spot, strike, \u03c4, r, b, \u03c3) * (d1 * d2 - 1.0) / \u03c3\nend\n\nfunction blackScholesColor(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    blackScholesGamma(isCall, spot, strike, \u03c4, r, b, \u03c3) * (r - b + b * d1 / \u03c3 / sqrt(\u03c4) + (1 - d1 * d2) / 2 / \u03c4)\nend\n\nfunction blackScholesDriftlessTheta(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    println(pdf(std_normal, d1))\n    -spot * pdf(std_normal, d1) * \u03c3 / 2 / sqrt(\u03c4)\nend\n\nfunction blackScholesRho(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where {T}\n    sign = isCall ? 1 : -1\n\n    d1 = (log(spot / strike) + (b + 0.5 * \u03c3^2) * \u03c4) / (\u03c3 * sqrt(\u03c4))\n    d2 = d1 - \u03c3 * sqrt(\u03c4)\n\n    sign * \u03c4 * strike * exp(-r * \u03c4) * cdf(std_normal, sign * d2)\nend\n\nfunction blackScholesRhoFutures(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::T) where{T}\n    -1.0 * \u03c4 * blackScholesValue(isCall, spot, strike, \u03c4, r, b, \u03c3)\nend\n\nfunction blackScholesTouchProb(isCall::Bool, spot::T, strike::T, \u03c4::T, r::T, b::T, \u03c3::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    \u03bc = (b - \u03c3^2 / 2) / (\u03c3 * \u03c3)\n    \u03bb = sqrt(\u03bc^2 + 2 * r / (\u03c3 * \u03c3))\n    z = log(strike / spot) / \u03c3 / sqrt(\u03c4) + \u03bb * \u03c3 * sqrt(\u03c4)\n\n    (strike / spot) ^ (\u03bc + \u03bb) * cdf(std_normal, sign * z) + (strike / spot) ^ (\u03bc - \u03bb) * cdf(std_normal, sign * (z - 2 * \u03bb * \u03c3 * sqrt(\u03c4)))\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` = \u03d5\u2081 - \u03d5\u2082 where \u03d5\u2081 = 2*asin(sqrt(P)) and \u03d5\u2082 = 2*asin(sqrt(c)). The option\n`alternative` is `two.sided` for H\u2080: \u03d5\u2081 = \u03d5\u2082 vs H\u2081: \u03d5\u2081 \u2260 \u03d5\u2082, `less` for H\u2081: \u03d5\u2081 < \u03d5\u2082, and `greater`\nfor H\u2081: \u03d5\u2081 > \u03d5\u2082.\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` = \u03d5\u2081 - \u03d5\u2082 where \u03d5\u2081 = 2*asin(sqrt(P)) and \u03d5\u2082 = 2*asin(sqrt(c)). The option\n`alternative` is `two.sided` for H\u2080: \u03d5\u2081 = \u03d5\u2082 vs H\u2081: \u03d5\u2081 \u2260 \u03d5\u2082, `less` for H\u2081: \u03d5\u2081 < \u03d5\u2082, and `greater`\nfor H\u2081: \u03d5\u2081 > \u03d5\u2082.\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` = \u03d5\u2081 - \u03d5\u2082 where \u03d5\u2081 = 2*asin(sqrt(P)) and \u03d5\u2082 = 2*asin(sqrt(c)). The option\n`alternative` is `two.sided` for H\u2080: \u03d5\u2081 = \u03d5\u2082 vs H\u2081: \u03d5\u2081 \u2260 \u03d5\u2082, `less` for H\u2081: \u03d5\u2081 < \u03d5\u2082, and `greater`\nfor H\u2081: \u03d5\u2081 > \u03d5\u2082.\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` = \u03d5\u2081 - \u03d5\u2082 where \u03d5\u2081 = 2*asin(sqrt(P)) and \u03d5\u2082 = 2*asin(sqrt(c)).\nThe option `alternative` is `two.sided` for H\u2080: \u03d5\u2081 = \u03d5\u2082 vs H\u2081: \u03d5\u2081 \u2260 \u03d5\u2082, `less` for H\u2081: \u03d5\u2081 < \u03d5\u2082, and `greater`\nfor H\u2081: \u03d5\u2081 > \u03d5\u2082.\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` = \u03d5\u2081 - \u03d5\u2082 where \u03d5\u2081 = 2*asin(sqrt(P)) and \u03d5\u2082 = 2*asin(sqrt(c)).\nThe option `alternative` is `two.sided` for H\u2080: \u03d5\u2081 = \u03d5\u2082 vs H\u2081: \u03d5\u2081 \u2260 \u03d5\u2082, `less` for H\u2081: \u03d5\u2081 < \u03d5\u2082, and `greater`\nfor H\u2081: \u03d5\u2081 > \u03d5\u2082.\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 normalization(x)\n    return (x .- minimum(x))./(maximum(x).-minimum(x))\nend\n", "meta": {"hexsha": "d0241ad32d09016ed812cde23a106ac65b962821", "size": 85, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/normalization.jl", "max_stars_repo_name": "arubhardwaj/BasicStats.jl", "max_stars_repo_head_hexsha": "962d027c66eded5cd562b1446c94d4b74332f498", "max_stars_repo_licenses": ["MIT"], "max_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": "arubhardwaj/BasicStats.jl", "max_issues_repo_head_hexsha": "962d027c66eded5cd562b1446c94d4b74332f498", "max_issues_repo_licenses": ["MIT"], "max_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": "arubhardwaj/BasicStats.jl", "max_forks_repo_head_hexsha": "962d027c66eded5cd562b1446c94d4b74332f498", "max_forks_repo_licenses": ["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": 54, "alphanum_fraction": 0.6588235294, "num_tokens": 23, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7549137782272172}}
{"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": "function f(x::Array{Float64,2})\n  x[1]^2 + x[2]^2\nend\nfunction gradient(x::Array{Float64,2})\n  [2*x[1] 2*x[2]]\nend\n\nx = [1.0 3.0]\ndd = DifferentiableDensity(f,gradient)\n@assert dd.f(x) == 10.0\n@assert dd.gradient(x) == [2.0 6.0]\n", "meta": {"hexsha": "23150fe3e07104fa13b823efeb6fa643e6c4fd37", "size": 229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/density.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": "test/density.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": "test/density.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": 19.0833333333, "max_line_length": 38, "alphanum_fraction": 0.6200873362, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7549137645698104}}
{"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\u03bc = [11.5; 9.5; 6]/100          #expected returns\n\u03a3  = [166  34  58;              #covariance matrix\n       34  64   4;\n       58   4 100]/100^2\n\nn = length(\u03bc)                   #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\u03bc = (6 .+ (11.5-6)*rand(n))/100             #mean\nA = randn(n,n)\n\u03a3 = (A * A' + diagm(0=>rand(n)))/500;       #covariance matrix\n=#\n\n# First we solve without any bounds on $w$\n\nN = 101\n\u03bb_vals = range(0.01,stop=0.99,length=N)\n\nw    = Variable(n)\nret  = dot(w,\u03bc)\nrisk = quadform(w,\u03a3)\n\nMeanVarA = zeros(N,2)                    \nfor i = 1:N\n    \u03bb = \u03bb_vals[i]\n    p = minimize( \u03bb*risk - (1-\u03bb)*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    \u03bb = \u03bb_vals[i]\n    p = minimize( \u03bb*risk - (1-\u03bb)*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(\u03a3)),\u03bc,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    \u03bb = \u03bb_vals[i]\n    p = minimize( \u03bb*risk - (1-\u03bb)*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(\u03a3)),\u03bc,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-\u03b8\u2081)\n# r_2 = 10(\u03b8\u2082-\u03b8\u2081\u00b2)\n#\n# Jacobian is: [[-1, 0],[-20, 10]]\n#\n# Minimum for \u03b8=(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,\u03b8::AbstractVector{T}) where T\n    @assert length(\u03b8)==parameter_size(nls)\n\n    T[ 1-\u03b8[1], 10*(\u03b8[2]-\u03b8[1]^2) ]\nend\n\nfunction eval_r_J(nls::Rosenbrock,\u03b8::AbstractVector{T}) where T\n    @assert length(\u03b8)==parameter_size(nls)\n\n    r = T[ 1-\u03b8[1], 10*(\u03b8[2]-\u03b8[1]^2) ]\n    J = T[ -1 0; -20*\u03b8[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,\u03b8::AbstractVector{T}) where T\n#     @assert length(\u03b8)==parameter_size(nls)\n\n#     r = @SVector T[1-\u03b8[1],\n#                    10*(\u03b8[2]-\u03b8[1]^2)]\n# end\n\n# function eval_r_J(nls::Rosenbrock_Static,\u03b8::AbstractVector{T}) where T\n#     @assert length(\u03b8)==parameter_size(nls)\n\n#     r = eval_r(nls,\u03b8)\n\n#     # CAVEAT: SMatrix are filled column by column\n#     #\n#     # The Jacobian\n#     #\n#     # | \u22021r1, \u22022r1 |\n#     # | \u22021r2, \u22022r2 |\n#     #\n#     # must be created by\n#     #\n#     # SMatrix(\u22021r1,\u22021r2, # col 1\n#     #         \u22022r1,\u22022r2) # 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;     # \u22021r1, \u22022r1\n#                          -20*\u03b8[1]  +10]     # \u22021r2, \u22022r2\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(\u03bd1::Real, \u03bd2::Real, x::Number) = sqrt((\u03bd1 * x)^\u03bd1 * \u03bd2^\u03bd2 / (\u03bd1 * x + \u03bd2)^(\u03bd1 + \u03bd2)) / (x * beta(\u03bd1 / 2, \u03bd2 / 2))\n\n# logpdf for numbers with generic types\nfdistlogpdf(\u03bd1::Real, \u03bd2::Real, x::Number) = (\u03bd1 * log(\u03bd1 * x) + \u03bd2 * log(\u03bd2) - (\u03bd1 + \u03bd2) * log(\u03bd1 * x + \u03bd2)) / 2 - log(x) - lbeta(\u03bd1 / 2, \u03bd2 / 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(\u2205::EmptySet) = \u2205\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\u1d57\u02b0 order\n#  INPUTS:\n# Type T - ?????\n# order - Integer defining the desired Legendre polynomial order\n#  OUTPUTS:\n# P\u2099(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\u2099(x)=(2n-1)P\u2099\u208b\u2081(x)-(n-1)P\u2099\u208b\u2082(x)\n# Compute P\u1d62\u208a\u2081 from P\u1d62 and P\u1d62\u208b\u2081 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\u1d62\u208a\u2081 in a pseudo recursive manner\n        P[1] = P[2] #here we save P\u1d62 for next iteration\n        P[2] = Ptmp #here we save P\u1d62\u208a\u2081 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": "using ApproxFunSingularities, ApproxFunOrthogonalPolynomials, ApproxFunBase, IntervalSets, Random, LinearAlgebra, Test\n    import ApproxFunBase: testfunctional, testbandedbelowoperator, testbandedoperator\n\n\n@testset \"Integral equations\" begin\n    @time for S in (JacobiWeight(-0.5,-0.5,Chebyshev()),\n                JacobiWeight(-0.5,-0.5,Chebyshev(Segment(1.0,2.0+im))),\n                JacobiWeight(0.5,0.5,Ultraspherical(1,Segment(1.0,2.0+im))))\n        testfunctional(DefiniteLineIntegral(S))\n    end\n\n    @testset \"three segment bug\" begin\n        dom = Segment(-1.0,1) \u222a Segment(1.0+im,1+2im) \u222a Segment(-2.0+im,-1+2im)\n\n\n        \u2a0d = DefiniteLineIntegral(dom)\n        S = domainspace(\u2a0d)\n        @test ApproxFunBase.blockbandwidths(\u2a0d) == (0,0)\n\n        f = Fun(S,rand(20))\n\n        @test DefiniteLineIntegral(component(dom,1))*component(f,1) \u2248 linesum(component(f,1))\n        @test DefiniteLineIntegral(component(dom,2))*component(f,2) \u2248 linesum(component(f,2))\n        @test DefiniteLineIntegral(component(dom,3))*component(f,3) \u2248 linesum(component(f,3))\n\n        @test \u2a0d*f \u2248 linesum(f)\n    end\n\n    @testset \"integral equation\" begin\n        #The first test checks the solution of the integral equation\n        # u(x) + \\int_{-1}^{+1} \\frac{e^{y} u(y)}{\\sqrt{1-y^2}} dy = f\n        # on the interval -1..1.\n\n        x = Fun(identity)\n        w = 1/sqrt(1-x^2)\n        d = domain(x)\n\n        \u03a3 = DefiniteIntegral(d)\n        @test bandwidths(\u03a3) == (0,0)\n\n        @test domainspace(\u03a3) ==\n            JacobiWeight{Chebyshev{ChebyshevInterval{Float64}},ChebyshevInterval{Float64},Float64,Float64}(-0.5,-0.5,Chebyshev())\n\n        L = I+\u03a3[exp(x)*w]\n        testbandedoperator(L)\n        usol = sin(2x)\n        f = L*usol\n\n        @time u = L\\f\n        @test norm(u-usol) <= 10eps()\n    end\n\n    @testset \"integro-differential equation\" begin\n        #The second test checks the solution of the integro-differential equation\n        # u'(x) + x u(x) + \\int_{-2}^{+2} sin(y-x) u(y) \\sqrt{4-y^2} dy = f\n        # on the interval -2..2, with u(-2) = 1.\n\n        x = Fun(identity,-2..2)\n        w = sqrt(4-x^2)\n        d = domain(x)\n\n        D = Derivative(d)\n        B = ldirichlet(d)\n        \u03a3 = DefiniteIntegral(.5,.5,d)\n\n        @test domainspace(\u03a3) ==\n            JacobiWeight{Ultraspherical{Int,ClosedInterval{Int},Float64},ClosedInterval{Float64},Float64,Float64}(.5,.5,Ultraspherical(1,d))\n\n        K = LowRankFun((x,y)->sin(y-x)*w(y),Ultraspherical(1,d),domainspace(\u03a3))\n\n        L = D+x+\u03a3[K]\n        usol = cospi(20x)\n        f = L*usol\n        @time u = [B;L]\\[1.;f]\n\n\n        @test norm(u-usol) \u2264 200eps()\n    end\n    \n    @testset \"arcs\" begin\n        d = exp(im*Segment(0.1,0.2))\n        x = Fun(d)\n        @time w=1/(sqrt(abs(leftendpoint(d)-x))*sqrt(abs(rightendpoint(d)-x)))\n\n        @test linesum(w) \u2248 DefiniteLineIntegral()*w\n    end\n\n    @testset \"Volterra integral equation\" begin\n        d = 0.0..1.0\n        V = Volterra(d)\n        K = LowRankFun((x,y)->sin(y-x),d^2)\n        L = I-V[K]\n        # broken due to gbmv inconsistency\n        # testbandedoperator(L)\n        f = Fun(exp,d)\n        @test domainspace(L) == Legendre(d)\n        @test rangespace(L) == Legendre(d)\n        @test bandrange(V) == -1:0\n        @time u = L\\f\n        @test norm(L*u-f) \u2264 20eps()\n    end\n\n    @testset \"DefiniteIntegral\" begin\n        @time for S in (JacobiWeight(0.5,0.5,Ultraspherical(1,Segment(-2,-1))),\n                  JacobiWeight(0.5,0.5,Ultraspherical(1,Segment(-2,-1+2im))),\n                  JacobiWeight(1.5,1.5,Ultraspherical(2,Segment(-2,-1+2im))),\n                  JacobiWeight(-0.5,-0.5,Chebyshev(Segment(-2,-1+2im))),\n                  JacobiWeight(0.67,0.123,Chebyshev(Segment(-2,-1+2im))),\n                  JacobiWeight(0.67,0.123,Ultraspherical(1,Segment(-2,-1+2im))))\n            f=Fun(S,[1.,2.,3.])\n            @test DefiniteIntegral(space(f))*f \u2248 sum(f)\n            @test DefiniteLineIntegral(space(f))*f \u2248 linesum(f)\n        end\n    end\n\n    @testset \"Fredholm integral\" begin\n        K=LowRankFun((x,y)->cos(x-y),ChebyshevInterval()^2)\n        \u03a3=DefiniteIntegral(Chebyshev())\n        testbandedbelowoperator(\u03a3[K])\n\n\n        \u03a3 = DefiniteIntegral(Chebyshev()); x=Fun();\n        L=I+exp(x)*\u03a3[cos(x)]\n        testbandedbelowoperator(L)\n    end\n\n    @testset \"union domain\" begin\n        dom = ApproxFunBase.UnionDomain(0..1, 2..3)\n        \u2a0d = DefiniteLineIntegral(union(JacobiWeight.(-0.5,-0.5,ChebyshevDirichlet{1,1}.(components(dom)))...))\n\n        x = Fun(dom)\n        f = exp(x)/(sqrt(x*abs(1-x))*sqrt(abs(2-x)*abs(3-x)))\n        @test sum(f) \u2248 Number(\u2a0d*f)\n    end\nend\n", "meta": {"hexsha": "b0e91d5994d18c01aad911f016dc230dcd467946", "size": 4597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/IntegralEquationsTest.jl", "max_stars_repo_name": "putianyi889/ApproxFunSingularities.jl", "max_stars_repo_head_hexsha": "624c40bcde0480bba2efad6e843239e4867a1e36", "max_stars_repo_licenses": ["MIT"], "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/IntegralEquationsTest.jl", "max_issues_repo_name": "putianyi889/ApproxFunSingularities.jl", "max_issues_repo_head_hexsha": "624c40bcde0480bba2efad6e843239e4867a1e36", "max_issues_repo_licenses": ["MIT"], "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/IntegralEquationsTest.jl", "max_forks_repo_name": "putianyi889/ApproxFunSingularities.jl", "max_forks_repo_head_hexsha": "624c40bcde0480bba2efad6e843239e4867a1e36", "max_forks_repo_licenses": ["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.8014705882, "max_line_length": 140, "alphanum_fraction": 0.5708070481, "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7546874462624229}}
{"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(\u03bc::AbstractFloat,\u03c1::AbstractFloat,\u03c3::AbstractFloat,n::Int64,\u03bb::AbstractFloat)\r\n    #output is xgrid, xprob\r\n    # x_t+1 = \u03bc + \u03c1 x_t + \u03c3 e_{t+1}, e_t+1 \u223c N(0,1)\r\n    xhi = \u03bc/(1-\u03c1) + \u03bb*sqrt(\u03c3^2/(1-\u03c1)^2)\r\n    xlo = \u03bc/(1-\u03c1) - \u03bb*sqrt(\u03c3^2/(1-\u03c1)^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(\u03bc+\u03c1*xgrid[i],\u03c3)\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\u03b1 = 0.3                         # capital share\r\nH = 1.0                         # aggregate hours worked\r\n\u03b4  = 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\u03b3 = 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\u03b7 = 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\u03c1B = 0.5 # persistence of discount factor shock\r\n\u03c1G = 0.5 # persistence of govt spending shock\r\n\u03c1Z = 0.5 # persistence of tfp growth shock\r\n\u03c1\u03bc = 0.5 # persistence of investment shock\r\n\u03c1lamw = 0.5 # persistence of wage mkup shock\r\n\u03c1lamf = 0.5 # persistence of price mkup shock\r\n\u03c1mon = 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\u03d5h   = 2.                        # inverse frisch elasticity\r\n\u03a6w   = 10.                       # rotemberg cost for wages\r\nlamf = 1.5                       # price markup\r\n\u03a6p   = 1.                       # rotemberg cost for prices\r\n\u03c1R   = 0.75                      # persistence in taylor rule\r\n\u03c8\u03c0   = 1.5                      # weight on inflation in taylor rule\r\n\u03c8y   = 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 + \u03b4                               # rental rate on capital\r\n\u03c9 = (\u03b1^(\u03b1/(1-\u03b1)))*(1-\u03b1)*Rk^(-\u03b1/(1-\u03b1))    # real wage\r\nkl = (\u03b1/(1-\u03b1))*(\u03c9/Rk)*\u212f^\u03b3                # capital/labor ratio\r\nk = kl*H                                 # capital\r\nx = (1-(1-\u03b4)*\u212f^(-\u03b3))*k                   # investment\r\ny = (\u212f^(-\u03b1*\u03b3))*(k^\u03b1)*H^(1-\u03b1)             # gdp\r\nbg = BoverY*y                            # govt debt\r\nT = Rk*k*\u212f^(-\u03b3) - x - (1-(1/g))*y - ((1+r)*\u212f^(-\u03b3)-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, \u03c9::AbstractFloat, H::AbstractFloat, r::AbstractFloat, \u03b7::AbstractFloat, \u03b3::AbstractFloat,\r\n                   T::AbstractFloat, zlo::AbstractFloat, na::Int)\r\n    smin = minimum(sgrid)*zlo                           # lowest possible skill\r\n    alo_ss = \u03c9*smin*H - (1+r)*\u03b7*\u212f^(-\u03b3) + T + sgrid[1]*\u03c9*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 = \u03c9*smin*H - (1+r)*\u03b7*\u212f^(-\u03b3) + T + sgrid[1]*\u03c9*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, \u03c9, H, r, \u03b7, \u03b3, 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\u03c3e = 0.01\r\n(legrid, fe, sscale) = tauchen86(0.0,0.0,\u03c3e,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, \u03b2::AbstractFloat, R::AbstractFloat,\r\n                     \u03c9::AbstractFloat,\r\n                     H::AbstractFloat,\r\n                     \u03b7::AbstractFloat,\r\n                     T::AbstractFloat,\r\n                     \u03b3::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 = \u03b2*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]+\u03b7)\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,\u03b2,R,\u03c9,H,\u03b7,T,\u03b3,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,\u03c9,H,\u03b7,T,\u03b3,qfunction,agrid,sgrid,bp,f)\r\n    return (c,bp,Wout,tr)\r\nend\r\n\r\nfunction parameterized_expectations(na::Int,ns::Int, \u03b2::AbstractFloat, R::AbstractFloat, \u03c9::AbstractFloat,\r\n                                    H::AbstractFloat, \u03b7::AbstractFloat, T::AbstractFloat, \u03b3::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*(\u212f^(-\u03b3))*bp[na*(iss-1)+ia] - T)/(\u03c9*H*sgrid[isp]))*f[iss,isp] ./ sgrid[isp]\r\n                end\r\n            end\r\n            l_out[na*(iss-1)+ia] = (\u03b2*R*(\u212f^(-\u03b3))/\u03c9*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, \u03c9::AbstractFloat,\r\n                        H::AbstractFloat, \u03b7::AbstractFloat, T::AbstractFloat, \u03b3::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*(\u212f^(-\u03b3))*bp[na*(iss-1)+ia] - T)/(\u03c9*H*sgrid[isp]))*f[iss,isp] ./ (\u03c9*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\u03b2lo = 0.5*(\u212f^\u03b3)/R # excess should be -ve\r\n\u03b2hi = (\u212f^\u03b3)/R # excess should be +ve\r\n\r\n\u03b2 = (\u03b2lo+\u03b2hi)/2.0\r\n\r\nfunction findss(na::Int, ns::Int, \u03b2lo::AbstractFloat,\r\n                \u03b2hi::AbstractFloat, R::AbstractFloat,\r\n                     \u03c9::AbstractFloat,\r\n                     H::AbstractFloat,\r\n                     \u03b7::AbstractFloat,\r\n                     T::AbstractFloat,\r\n                     \u03b3::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        \u03b2 = (\u03b2lo+\u03b2hi)/2.0\r\n        Win_guess = ones(n) # or Win\r\n        (c, bp, Win, KF) = sspolicy(na, ns, \u03b2, R, \u03c9, H, \u03b7, T, \u03b3, 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([\u03b2lo \u03b2 \u03b2hi])\r\n        println(excess)\r\n        report[counter,1] = \u03b2 # 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            \u03b2hi=\u03b2\r\n        elseif excess<0\r\n            \u03b2lo = \u03b2\r\n        end\r\n        counter += 1\r\n    end\r\n    return (Win, c, m, \u03b2, report)\r\nend\r\n\r\ntic()\r\n(ell, c, m, \u03b2, report) = findss(na, ns, \u03b2lo, \u03b2hi, R, \u03c9, H, \u03b7, T, \u03b3, 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": "@testset \"Limited Length Cycles\" begin\n    completedg = CompleteDiGraph(4)\n    pathdg = PathDiGraph(5)\n    cycledg = CycleDiGraph(5)\n\n    @test length(simplecycles_limited_length(completedg, 0)) == 0\n    @test length(simplecycles_limited_length(completedg, 1)) == 0\n    @test length(simplecycles_limited_length(completedg, 2)) == 6\n    @test length(simplecycles_limited_length(completedg, 3)) == 14\n    @test length(simplecycles_limited_length(completedg, 4)) == 20\n    @test length(simplecycles_limited_length(completedg, 4, 10)) == 10\n    @test length(simplecycles_limited_length(completedg, 4, typemax(Int))) == 20\n\n    @test length(simplecycles_limited_length(pathdg, 1)) == 0\n    @test length(simplecycles_limited_length(pathdg, 2)) == 0\n    @test length(simplecycles_limited_length(pathdg, 3)) == 0\n    @test length(simplecycles_limited_length(pathdg, 4)) == 0\n    @test length(simplecycles_limited_length(pathdg, 5)) == 0\n\n    @test length(simplecycles_limited_length(cycledg, 1)) == 0\n    @test length(simplecycles_limited_length(cycledg, 2)) == 0\n    @test length(simplecycles_limited_length(cycledg, 3)) == 0\n    @test length(simplecycles_limited_length(cycledg, 4)) == 0\n    @test length(simplecycles_limited_length(cycledg, 5)) == 1\n\n    selfloopg = DiGraph([\n        0 1 0 0;\n        0 0 1 0;\n        1 0 1 0;\n        0 0 0 1;\n    ])\n    cycles = simplecycles_limited_length(selfloopg, nv(selfloopg))\n    @test [3] in cycles\n    @test [4] in cycles\n    @test [1, 2, 3] in cycles || [2, 3, 1] in cycles || [3, 1, 2] in cycles\n    @test length(cycles) == 3\n\n    octag = smallgraph(:octahedral)\n    octadg = DiGraph(octag)\n    octalengths, _ = simplecycleslength(octadg)\n    for k = 1:6\n        @test sum(octalengths[1:k]) == length(simplecycles_limited_length(octag, k))\n        @test sum(octalengths[1:k]) == length(simplecycles_limited_length(octadg, k))\n    end\nend\n", "meta": {"hexsha": "72207aafd9698d43fdb44cd958503c7ae71c188d", "size": 1880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cycles/limited_length.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": "test/cycles/limited_length.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": "test/cycles/limited_length.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": 40.8695652174, "max_line_length": 85, "alphanum_fraction": 0.6829787234, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7546874370118934}}
{"text": "@testset \"Kabsch algorithm\" begin\n\n    @testset \"Test I\" begin\n        a = [1  1 0\n             2  1 0\n             1+cos(pi/4) 1-sin(pi/4) 0\n             1  0 0 ]\n        b = [1 1 0\n             1 2 0\n             1+cos(pi/4) 1+sin(pi/4)  0 ] # mean(b,1) 1.2357  1.56904  0.0\n        sa = a[1:3, :]\n        ma = mean(sa, dims=1) # mean x, y, z for a[1:3,:]\n\n        # Center b, sa, a\n        center!(b)\n        sa[:,:] = sa .- ma\n        a[:,:]  = a  .- ma # center != 0\n\n        @test isapprox(vec(mean(b, dims=1)), [0.0, 0.0, 0.0], atol=1e-13)\n        @test isapprox(vec(mean(sa, dims=1)), [0.0, 0.0, 0.0], atol=1e-13)\n\n        F = kabsch(b, sa) # Reference: b\n        R = sa * F\n        RR = a * F\n\n        @test R \u2248 b\n        @test RR[1:3,:] \u2248 b\n\n        @test RR[4,:] .- RR[1,:] \u2248 [1.0, 0.0, 0.0]\n        @test sqrt((RR[1,1] - RR[4,1])^2 + (RR[1,2] - RR[4,2])^2) \u2248 1.0\n\n        @test isapprox(PDB.rmsd(R, b), 0.0, atol=1e-13)\n        @test isapprox(PDB.rmsd(RR[1:3,:], b), 0.0, atol=1e-13)\n    end\n\n    @testset \"BiomolecularStructures' test\" begin\n\n        P = [51.65 -1.90 50.07\n             50.40 -1.23 50.65\n             50.68 -0.04 51.54\n             50.22 -0.02 52.85]\n        Q = [51.30 -2.99 46.54\n             51.09 -1.88 47.58\n             52.36 -1.20 48.03\n             52.71 -1.18 49.38] # P and Q are from BiomolecularStructures.jl' kabsch tests\n        Qdistances = Float64[ sqrt(sum(abs2, Q[j,:] .- Q[i,:])) for i in 1:4, j in 1:4 ]\n\n        center!(P)\n        center!(Q)\n\n        @test isapprox(vec(mean(P, dims=1)), zeros(3), atol=1e-13)\n        @test isapprox(vec(mean(Q, dims=1)), zeros(3), atol=1e-13)\n\n        rotationmatrix = kabsch(P, Q)\n        rotated = Q * rotationmatrix\n\n        @test PDB.rmsd(P, rotated) \u2248 0.0030426652601371583\n\n        # Internal distances mustn't change\n        @test Float64[sqrt(sum(abs2, Q[j,:] .- Q[i,:])) for i in 1:4, j in 1:4] \u2248 Qdistances # Translated\n        @test Float64[sqrt(sum(abs2, rotated[j,:] .- rotated[i,:])) for i in 1:4, j in 1:4] \u2248 Qdistances # Translated  and rotated\n    end\n\n    @testset \"Test II\" begin\n        P = [-1. 0. 0.\n             0. 2. 0.\n             0. 1. 0.\n             0. 1. 1]\n        Q = [0. -1. -1.\n             0. -1. 0\n             0. 0. 0.\n             -1. 0. 0.]\n\n        center!(P)\n        center!(Q)\n        rotated = Q * kabsch(P, Q)\n        @test isapprox(PDB.rmsd(P, rotated), 0.695, atol=0.001)\n    end\n\n    @testset \"RMSF\" begin\n        A = [ -1. -1. -1.\n              -1.  0.  1. ]\n        B = [  1.  1.  1.\n              -1.  0.  1. ]\n        w = [ .25 , .75 ]\n\n        @test_throws ArgumentError mean_coordinates(Matrix{Float64}[A[1:1,:], B])\n        @test_throws ArgumentError mean_coordinates(Matrix{Float64}[A[:,1:2], B])\n        @test_throws ArgumentError mean_coordinates(Matrix{Float64}[A])\n        @test_throws ArgumentError mean_coordinates(Matrix{Float64}[A,  B'])\n        @test_throws ArgumentError mean_coordinates(Matrix{Float64}[A', B'])\n\n        @test mean_coordinates(Matrix{Float64}[A, B]) == [ 0. 0. 0.\n                                                          -1. 0. 1. ]\n\n        @test mean_coordinates(Matrix{Float64}[A, B], w) == [ 0.5 0.5 0.5\n                                                             -1.  0.  1. ]\n\n        @test mean_coordinates(Matrix{Float64}[A, B], reverse(w)) == [ -0.5 -0.5 -0.5\n                                                                       -1.   0.   1. ]\n\n        @test rmsf(Matrix{Float64}[A, B]) == [sqrt(3), 0.]\n        @test rmsf(Matrix{Float64}[A, B], w) == [sqrt(0.25*6.75 + 0.75*0.75), 0.]\n    end\n\n    @testset \"Superimpose PDBs\" begin\n\n        hemoglobin = read(joinpath(pwd(),\"data\",\"2hhb.pdb.gz\"),PDBFile,group=\"ATOM\",model=\"1\")\n\n        \u03b11 = @residues hemoglobin model \"1\" chain \"A\" group \"ATOM\" residue All\n        \u03b12 = @residues hemoglobin model \"1\" chain \"C\" group \"ATOM\" residue All\n        \u03b21 = @residues hemoglobin model \"1\" chain \"B\" group \"ATOM\" residue All\n        \u03b22 = @residues hemoglobin model \"1\" chain \"D\" group \"ATOM\" residue All\n\n        a1, a2, r\u03b1 = superimpose(\u03b11, \u03b12)\n\n        @test isapprox(r\u03b1, 0.230, atol=0.001) # Bio3D RMSD\n\n        _, _, r\u03b12 = superimpose(\u03b11, \u03b12, zip(1:length(\u03b11), 1:length(\u03b12)))\n        @test r\u03b12 == r\u03b1\n\n        _, _, r\u03b12 = superimpose(\u03b11, \u03b12, zip(1:2, 1:2))\n        @test r\u03b12 < r\u03b1/10  # aligning only 2 points is accurate\n\n        b1, b2, r\u03b2 = superimpose(\u03b21, \u03b22)\n\n        @test isapprox(r\u03b2, 0.251, atol=0.001) # Bio3D & Chimera's MatchMaker RMSD\n\n        @test length(a1) == length(\u03b11)\n        @test length(a2) == length(\u03b12)\n        @test length(b1) == length(\u03b21)\n        @test length(b2) == length(\u03b22)\n\n        @test a1 != \u03b11\n        @test a2 != \u03b12\n\n        @test b1 != \u03b21\n        @test b2 != \u03b22\n\n        @testset \"Vector{PDBResidue}\" begin\n\n            @test isapprox(PDB.rmsd(\u03b11, \u03b12), 0.230, atol=0.001)\n            @test isapprox(PDB.rmsd(\u03b21, \u03b22), 0.251, atol=0.001)\n\n            @test isapprox(PDB.rmsd(a1, a2, superimposed=true), 0.230, atol=0.001)\n            @test isapprox(PDB.rmsd(b1, b2, superimposed=true), 0.251, atol=0.001)\n\n            ca_a1 = CAmatrix(a1)\n            ca_a2 = CAmatrix(a2)\n            ca_b1 = CAmatrix(b1)\n            ca_b2 = CAmatrix(b2)\n\n            @testset \"Centered\" begin\n                @test isapprox(mean(ca_a1, dims=1), zeros(1,3), atol=1e-13)\n                @test isapprox(mean(ca_a2, dims=1), zeros(1,3), atol=1e-13)\n                @test isapprox(mean(ca_b1, dims=1), zeros(1,3), atol=1e-13)\n                @test isapprox(mean(ca_b2, dims=1), zeros(1,3), atol=1e-13)\n\n                @test PDB._iscentered(ca_a1)\n                @test PDB._iscentered(ca_a2)\n                @test PDB._iscentered(ca_b1)\n                @test PDB._iscentered(ca_b2)\n            end\n\n            @testset \"RMSD\" begin\n\n                @test r\u03b1 == PDB.rmsd(ca_a1, ca_a2)\n                @test r\u03b2 == PDB.rmsd(ca_b1, ca_b2)\n            end\n        end\n\n        @testset \"coordinatesmatrix and centered...\" begin\n\n            @test coordinatesmatrix(centeredresidues(\u03b11)) \u2248 coordinatesmatrix(a1)\n            @test coordinatesmatrix(centeredresidues(\u03b21)) \u2248 coordinatesmatrix(b1)\n\n            @test centeredcoordinates(\u03b11) \u2248 coordinatesmatrix(a1)\n            @test centeredcoordinates(\u03b21) \u2248 coordinatesmatrix(b1)\n        end\n\n        @testset \"Superimpose with centered PDBs\" begin\n\n            b12, b22, r\u03b22 = superimpose(b1, b2)\n            @test r\u03b22 \u2248 r\u03b2\n        end\n\n        @testset \"RMSF\" begin\n\n            @test rmsf(Vector{PDBResidue}[\u03b11,\u03b12]) == rmsf(Vector{PDBResidue}[\u03b11,\u03b12],[.5,.5])\n            @test rmsf(Vector{PDBResidue}[\u03b21,\u03b22]) == rmsf(Vector{PDBResidue}[\u03b21,\u03b22],[.5,.5])\n        end\n    end\n\n    @testset \"PDBResidue without alpha-carbon\" begin\n        small_2WEL = read(joinpath(pwd(), \"data\", \"2WEL_D_region.pdb\"), PDBFile)\n        small_6BAB = read(joinpath(pwd(), \"data\", \"6BAB_D_region.pdb\"), PDBFile)\n\n        aln_2WEL, aln_6BAB, RMSD = superimpose(small_2WEL, small_6BAB)\n        @test length(aln_2WEL) == 3\n        @test length(aln_6BAB) == 3\n        @test small_2WEL[2].atoms[1].coordinates \u2249 aln_2WEL[2].atoms[1].coordinates\n        @test small_6BAB[2].atoms[1].coordinates \u2249 aln_6BAB[2].atoms[1].coordinates\n        @test RMSD < 1.0e-14 # e.g. 6.9e-15, 3.7e-15 & 1.6e-15\n\n        @testset \"PDB without CA\" begin\n\n            filter!(atom -> atom.atom != \"CA\", small_2WEL[1].atoms)\n            filter!(atom -> atom.atom != \"CA\", small_6BAB[3].atoms)\n            @test_throws ArgumentError superimpose(small_2WEL, small_6BAB)\n        end\n    end\nend\n", "meta": {"hexsha": "134d646b0fab6e008dc2eea8275d02355286d92e", "size": 7525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/PDB/Kabsch.jl", "max_stars_repo_name": "diegozea/MIToS.jl", "max_stars_repo_head_hexsha": "51c3b5050bb441d886a1e6581c5d95cb525a6d91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2015-08-13T02:11:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T12:22:31.000Z", "max_issues_repo_path": "test/PDB/Kabsch.jl", "max_issues_repo_name": "diegozea/MIToS.jl", "max_issues_repo_head_hexsha": "51c3b5050bb441d886a1e6581c5d95cb525a6d91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2015-06-19T22:44:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T15:40:25.000Z", "max_forks_repo_path": "test/PDB/Kabsch.jl", "max_forks_repo_name": "diegozea/MIToS.jl", "max_forks_repo_head_hexsha": "51c3b5050bb441d886a1e6581c5d95cb525a6d91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2015-08-11T02:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T00:13:20.000Z", "avg_line_length": 35.3286384977, "max_line_length": 130, "alphanum_fraction": 0.5134883721, "num_tokens": 2740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7546874351617875}}
{"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": "\"\"\"\n    assigndist_beta(\u03b1, \u03b2; trunc_lower = -Inf, trunc_upper = Inf)\n\nAssign parameters to a Beta distribution with parameters `\u03b1` and `\u03b2`, optionally \ntruncating the distribution.\n\"\"\" \nfunction assigndist_beta(\u03b1, \u03b2; trunc_lower = -Inf, trunc_upper = Inf)\n    Truncated(Beta(\u03b1, \u03b2), trunc_lower, trunc_upper)\nend\n\nexport assigndist_beta\n", "meta": {"hexsha": "6f76390ae1fbb998b36f634dc880a4fc5d3a427b", "size": 336, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/uncertain_values/distributions/assigndist_beta.jl", "max_stars_repo_name": "JuliaTagBot/UncertainData.jl", "max_stars_repo_head_hexsha": "4d9dc513b97f04a1d761e0a94eab3e3b11cc4c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/uncertain_values/distributions/assigndist_beta.jl", "max_issues_repo_name": "JuliaTagBot/UncertainData.jl", "max_issues_repo_head_hexsha": "4d9dc513b97f04a1d761e0a94eab3e3b11cc4c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/uncertain_values/distributions/assigndist_beta.jl", "max_forks_repo_name": "JuliaTagBot/UncertainData.jl", "max_forks_repo_head_hexsha": "4d9dc513b97f04a1d761e0a94eab3e3b11cc4c8a", "max_forks_repo_licenses": ["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": 81, "alphanum_fraction": 0.7380952381, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7546731810978279}}
{"text": "include(\"spline_kernel.jl\")\n\n# Removing t = 0, such that \u03a3 is invertible\nt = Vector(0.1:0.1:1); p = 2;\n\n# Creating generators U,V that result in a positive-definite matrix \u03a3\nU, V = spline_kernel(t, p);\n\u03a3    = spline_kernel_matrix(U, V);\nchol = cholesky(\u03a3)\n\n# Creating a symmetric extended generator representable semiseperable matrix\nK = SymSemiseparable(U,V)\n# Calculating its Cholesky factorization\nL = SymSemiseparableChol(K)\n# Creating a test vector\nxt = ones(K.n);\n\n# Testing multiplication\n@test isapprox(L*xt, chol.L*xt, atol=1e-6)\n@test isapprox(L'*xt, chol.U*xt, atol=1e-6)\n\n# Testing inverses (Using Cholesky factorizations)\n@test isapprox(L'\\(L\\xt), chol.U\\(chol.L\\xt), atol=1e-6)\n@test isapprox(inv(L), chol.U\\(chol.L\\Diagonal(ones(K.n))), atol=1e-6)\n@test isapprox(inv(L,xt),  chol.U\\(chol.L\\xt), atol=1e-6)\n\n# Testing logdet\n@test isapprox(logdet(L), logdet(chol.L), atol=1e-10)\n@test isapprox(logdet(L'), logdet(chol.U), atol=1e-10)\n\n# Testing the Cholesky as a lower triangular matrix\nC = SymSemiseparableChol(U,V);\n@test isapprox(C*xt, tril(U*V')*xt)\n\n# Testing going from Cholesky back to the matrix K\nKl = SymSemiseparable(L)\n@test isapprox(K*x, Kl*x)\n", "meta": {"hexsha": "3f52f06d83a3ed211a514502074927420741a330", "size": 1171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_symsepchol.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SymSemiseparableMatrices.jl-c927be06-f564-11e9-2e25-11633cdb9fcb", "max_stars_repo_head_hexsha": "b5d7d3a338151204fe2d78f1780420b302b6c66f", "max_stars_repo_licenses": ["MIT"], "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_symsepchol.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SymSemiseparableMatrices.jl-c927be06-f564-11e9-2e25-11633cdb9fcb", "max_issues_repo_head_hexsha": "b5d7d3a338151204fe2d78f1780420b302b6c66f", "max_issues_repo_licenses": ["MIT"], "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_symsepchol.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SymSemiseparableMatrices.jl-c927be06-f564-11e9-2e25-11633cdb9fcb", "max_forks_repo_head_hexsha": "b5d7d3a338151204fe2d78f1780420b302b6c66f", "max_forks_repo_licenses": ["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.8157894737, "max_line_length": 76, "alphanum_fraction": 0.7164816396, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7546731810978278}}
{"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\u0394Init = B_Init - A_Init\n\u0394Year = B_Year - A_Year\n\u0394IRR(x) = \u0394Init + presentWorthFactor(x, 1) * \u0394Year\n\u0394IRR_ans = find_zero(\u0394IRR, 0.05)\n\n# Because \u0394IRR_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": "#== INCLUDE files ==#\ninclude(\"aggregate.jl\")\ninclude(\"twoassets.jl\")\n\ninclude(\"solveHJB.jl\")\ninclude(\"solveKFE.jl\")\n\n#== Instance of prices ==#\npr = Prices(0.0, 0.04, 0.03, 0.09, 8.0)\n\n#== Instance of TwoAssetProblem ==#\ntwoap = TwoAssetsProb2(pr; \u03b3 = 2.0, \u03c1 = 0.06, \u03be = 0.10, \u03c7\u2080 = 0.08, \u03c7\u2081= 3.0, \u03c4 = 0.0, T = 0.0)\n\n#== Create and FiniteDifference Structure ==#\nfde = FDExp(twoap; z = [.8, 1.3], \u03bb = [-1/3 1/3; 1/3 -1/3],\nfixed\u0394a = true, fixed\u0394b = false, bn = 100, bmin = -2.0, bmax = 40.0, an =70, amax = 70.0, inv\u0394\u1d37 = 0.05)\n\n#== Solve the HJB equation ==#\nsolve_hjb!(twoap, fde, fde.sol)\n\n#== Solve the KF equation ==#\nsolve_fp!(fde, fde.sol, maxit = 4000, tolFK = 1e-9)\n\ninclude(\"main_fig.jl\");\n\n#== Policies ==#\n# fig_pol(fde)\n#== Distributions ==#\nfig_dens(fde)\n", "meta": {"hexsha": "696c3371eb0fc2915af974706222650746b7d5f9", "size": 768, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture13/felipe_alves_codes/testing.jl", "max_stars_repo_name": "snowdj/quantecon_nyu_2016", "max_stars_repo_head_hexsha": "57ea2d8457f6cddeae1bf253edb38cf88e78f84d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 118, "max_stars_repo_stars_event_min_datetime": "2016-01-16T17:47:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:13:36.000Z", "max_issues_repo_path": "lecture13/felipe_alves_codes/testing.jl", "max_issues_repo_name": "snowdj/quantecon_nyu_2016", "max_issues_repo_head_hexsha": "57ea2d8457f6cddeae1bf253edb38cf88e78f84d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2016-01-29T14:06:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-27T03:29:20.000Z", "max_forks_repo_path": "lecture13/felipe_alves_codes/testing.jl", "max_forks_repo_name": "snowdj/quantecon_nyu_2016", "max_forks_repo_head_hexsha": "57ea2d8457f6cddeae1bf253edb38cf88e78f84d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87, "max_forks_repo_forks_event_min_datetime": "2016-01-29T14:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T20:35:08.000Z", "avg_line_length": 25.6, "max_line_length": 103, "alphanum_fraction": 0.6041666667, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7546731763947808}}
{"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!(\u03c3::Vector{Int})::Vector{Int}\n  n = length(\u03c3)\n  result = Int[]\n  for i in 1:n-1\n    for j = n-1:-1:i\n      if \u03c3[j+1] < \u03c3[j]\n        \u03c3[j], \u03c3[j+1] = \u03c3[j+1], \u03c3[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] \u21a6 [3,2,1]\n\nSee also: `decompose_permutation_by_bubble_sort!`\n\"\"\"\nfunction decompose_permutation_by_insertion_sort!(\u03c3::Vector{Int})::Vector{Int}\n  n = length(\u03c3)\n  result = Int[]\n  for i in 2:n\n    for j in i:-1:2\n      if \u03c3[j-1] > \u03c3[j]\n        \u03c3[j-1], \u03c3[j] = \u03c3[j], \u03c3[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(\u03c3::Vector{Int}, xs::Vector; sort::Symbol=:insertion)\n  permutation_to_expr!(copy(\u03c3), copy(xs); sort=sort)\nend\nfunction permutation_to_expr!(\u03c3::Vector{Int}, xs::Vector; sort::Symbol=:insertion)\n  n = length(\u03c3)\n  @assert length(xs) == n\n  \n  transpositions = if sort == :bubble\n    decompose_permutation_by_bubble_sort!(\u03c3)\n  elseif sort == :insertion\n    decompose_permutation_by_insertion_sort!(\u03c3)\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 \u03c4\n    layer = [\n      \u03c4 > 1 ? id(otimes(xs[1:\u03c4-1])) : nothing,\n      braid(xs[\u03c4], xs[\u03c4+1]),\n      \u03c4+1 < n ? id(otimes(xs[\u03c4+2:n])) : nothing,\n    ]\n    xs[\u03c4], xs[\u03c4+1] = xs[\u03c4+1], xs[\u03c4]\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": "@testset \"Calculation Tools\" begin\n    @testset \"Test radial_mean\" begin \n        a = rr((10,10)) .< 5.0\n        (rm, ax) = MicroscopyTools.radial_mean(a)\n        @test rm[1] \u2248 1.0\n        @test rm[5] \u2248 1.0\n        @test rm[6] \u2248 0.0\n        @test ax[1] == 0.5\n        @test ax[end] == 7.5\n    end\n\n    @testset \"\u0394_phase\" begin \n        @test MicroscopyTools.\u0394_phase([1,1im,-1,-1im,1], 1) \u2248 -pi/2 .* ones(4)\n    end\n\n\n    @testset \"moment projection\" begin\n        @test MicroscopyTools.moment_proj([1 3; 2 4], 2, pdims = (1,)) == [0.25 0.25] \n        @test MicroscopyTools.moment_proj_normed([1 3; 2 4], 2, pdims = (1,)) == [0.5 0.5]\n    end\nend\n", "meta": {"hexsha": "b5982b2726f9b62ad4d6d57751b41400231eb9bc", "size": 646, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/calculation_tools.jl", "max_stars_repo_name": "JuliaMicroscopy/MicroscopyTools", "max_stars_repo_head_hexsha": "56e7c8a95e4cb67ca463984647d8421d234a6dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T19:46:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T19:46:00.000Z", "max_issues_repo_path": "test/calculation_tools.jl", "max_issues_repo_name": "JuliaMicroscopy/MicroscopyTools", "max_issues_repo_head_hexsha": "56e7c8a95e4cb67ca463984647d8421d234a6dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-26T21:37:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T02:28:47.000Z", "max_forks_repo_path": "test/calculation_tools.jl", "max_forks_repo_name": "JuliaMicroscopy/MicroscopyTools.jl", "max_forks_repo_head_hexsha": "56e7c8a95e4cb67ca463984647d8421d234a6dec", "max_forks_repo_licenses": ["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.3636363636, "max_line_length": 90, "alphanum_fraction": 0.5325077399, "num_tokens": 268, "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": "\nimport Rates\nusing Test\n\n@testset \"Continuous Compounding\" begin\n    r = 0.1\n    t = 1.5\n\n    @test Rates.erf(Rates.Continuous, r, t) \u2248 exp(r*t)\n    @test Rates.discountfactor(Rates.Continuous, r, t) \u2248 1.0/exp(r*t)\n    @test Rates.erf_to_rate(Rates.Continuous, exp(r*t), t) \u2248 r\n    @test Rates.discountfactor_to_rate(Rates.Continuous, 1.0/exp(r*t), t) \u2248 r\n    @test_throws AssertionError Rates.discountfactor(Rates.Continuous, r, -0.1)\n    @test_throws AssertionError Rates.discountfactor_to_rate(Rates.Continuous, 1.0, -0.1)\nend\n\n@testset \"Simple Compounding\" begin\n    r = 0.1\n    t = 1.5\n\n    @test Rates.erf(Rates.Simple, r, t) \u2248 1+r*t\n    @test Rates.discountfactor(Rates.Simple, r, t) \u2248 1.0/(1+r*t)\n    @test Rates.erf_to_rate(Rates.Simple, 1+r*t, t) \u2248 r\n    @test Rates.discountfactor_to_rate(Rates.Simple, 1.0/(1+r*t), t) \u2248 r\n    @test_throws AssertionError Rates.discountfactor(Rates.Simple, r, -0.1)\n    @test_throws AssertionError Rates.discountfactor_to_rate(Rates.Simple, 1.0, -0.1)\nend\n\n@testset \"Exponential Compounding\" begin\n    r = 0.1\n    t = 1.5\n\n    @test Rates.erf(Rates.Exponential, r, t) \u2248 (1+r)^t\n    @test Rates.discountfactor(Rates.Exponential, r, t) \u2248 1.0/((1+r)^t)\n    @test Rates.erf_to_rate(Rates.Exponential, (1+r)^t, t) \u2248 r\n    @test Rates.discountfactor_to_rate(Rates.Exponential, 1.0/((1+r)^t), t) \u2248 r\n    @test_throws AssertionError Rates.discountfactor(Rates.Exponential, r, -0.1)\n    @test_throws AssertionError Rates.discountfactor_to_rate(Rates.Exponential, 1.0, -0.1)\nend\n", "meta": {"hexsha": "77c7dc687737227fcafadb8f2f74f461c1ac6956", "size": 1514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 37.85, "max_line_length": 90, "alphanum_fraction": 0.6882430647, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7546576019479249}}
{"text": "using FastTransforms\nusing Compat.Test\nimport FastTransforms.pochhammer\n\nconst sqrtpi = 1.772453850905516027298\n\n@testset \"Pochhammer\" begin\n    @test pochhammer(2,3) == 24\n    @test pochhammer(0.5,3) == 0.5*1.5*2.5\n    @test pochhammer(0.5,0.5) == 1/sqrtpi\n    @test pochhammer(0,1) == 0\n    @test pochhammer(-1,2) == 0\n    @test pochhammer(-5,3) == -60\n    @test pochhammer(-1,-0.5) == 0\n    @test 1.0/pochhammer(-0.5,-0.5) == 0\n    @test pochhammer(-1+0im,-1) == -0.5\nend\n", "meta": {"hexsha": "4d77f955c2ee7082c83db78d343d103b0f9b86cb", "size": 475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/specialfunctionstests.jl", "max_stars_repo_name": "putianyi889/FastTransforms.jl", "max_stars_repo_head_hexsha": "491716260d0b8de4aa3b9bab15c98a8f8ce59970", "max_stars_repo_licenses": ["MIT"], "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/specialfunctionstests.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": "test/specialfunctionstests.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": 26.3888888889, "max_line_length": 42, "alphanum_fraction": 0.6315789474, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.754657597120541}}
{"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 \u27e9 = 1/\u221a2 * ( | 0 \u27e9 + | 1 \u27e9 )\n# H | 1 \u27e9 = 1/\u221a2 * ( | 0 \u27e9 - | 1 \u27e9 )\n#\n@rep_op \" H | n > = 1/\u221a2 * ( | 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 \u27e9) -> | 0, j - 1 \u27e9\n# shift_ket(| 1, j \u27e9) -> | 1, j + 1 \u27e9\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 \u27e9.\"\"\")\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": "#' ---\n#' title: Sensitivity analysis on Hill Model\n#' author: Shao-Ting Chiu (r07945001@ntu.edu.tw)\n#' date: 2020/08/27\n#' ---\n\n#' # Introduction\n#' We are going to explore the\n\nusing PyCall\nusing Plots\nusing Parameters\n\ninclude(\"../src/Sens.jl\")\ninclude(\"../src/Model.jl\")\nsp = pyimport(\"sympy\")\n\n#' Model: Hill Formula\n\n\n\ns = sp.symbols(\"s\", nonnegative=true) # Output / input\nk, n = sp.symbols(\"k n\", nonnegative=true) # dissociation coefficient constant and Hill coefficient\n\nmodel = Model.hill(k=k, n=n)\nX = model(s)\n\n# Local Sensitivity\nSens.localSens(X, s)\n\nrs = Sens.responseCoef(X, s)\n\n\n\nfrac = Sens.actFrac(X, X.subs(s,0), X.subs(s,1) )\n\n\nrs\nsp.solve(rs-n,frac)\n", "meta": {"hexsha": "0ba73430b6334cf44698f034b83076893c8964de", "size": 673, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Sens_analysis_of_Hill_equation.jl", "max_stars_repo_name": "stevengogogo/EstimHill.jl", "max_stars_repo_head_hexsha": "1c32cec8cf959b5fcbb6ec9da83915215861aacd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-01T08:41:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T08:41:52.000Z", "max_issues_repo_path": "test/Sens_analysis_of_Hill_equation.jl", "max_issues_repo_name": "stevengogogo/EstimHill.jl", "max_issues_repo_head_hexsha": "1c32cec8cf959b5fcbb6ec9da83915215861aacd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-11-13T10:10:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-30T00:32:45.000Z", "max_forks_repo_path": "test/Sens_analysis_of_Hill_equation.jl", "max_forks_repo_name": "stevengogogo/EstimHill.jl", "max_forks_repo_head_hexsha": "1c32cec8cf959b5fcbb6ec9da83915215861aacd", "max_forks_repo_licenses": ["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": 99, "alphanum_fraction": 0.6716196137, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7546575855693376}}
{"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), \u03b3=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- `\u03b3=1.0`: where `\u03b3 > 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 `\u03b3=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], \u03b3=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    \u03b3=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 -= \u03b3 * 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": "\nusing TravelingSalesmanExact, GLPK\nusing TravelingSalesmanHeuristics\nusing TravelingSalesmanExact: ATT, euclidean_distance\nusing TravelingSalesmanBenchmarks\nusing Plots\nusing Random\ngr(fmt=:svg)\n\n\nRandom.seed!(758)\nN = 50\ncost = 100*rand(N, N)\ncost = (cost + transpose(cost) )/2\n\n\nt_exact, c_exact = get_optimal_tour(cost, with_optimizer(GLPK.Optimizer))\n\nc(q) = solve_tsp(cost; quality_factor = q)[2]\n\nqs = range(10, stop = 100, step = 10)\n\nplot(qs, c, xlabel=\"quality\", ylabel=\"Cost\", label=\"solve_tsp 1\", title=\"random symmetric cost matrix\")\nfor j = 2:5\n    plot!(qs, c, label=\"solve_tsp $j\")\nend\nhline!([c_exact], label=\"Exact cost\")\n\n\nfile = @isdefined(WEAVE_ARGS) ? WEAVE_ARGS[:file] : nothing\nTravelingSalesmanBenchmarks.bench_footer(file)\n\n", "meta": {"hexsha": "357ec60b25c518c6c65c57cc317997e997c7ba32", "size": 750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/random_50_symmetric_cost_vs_quality.jl", "max_stars_repo_name": "ericphanson/TravelingSalesmanBenchmarks", "max_stars_repo_head_hexsha": "d5d9a328a16b200dd3efabef3b00ade96a2b2a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-15T15:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T01:56:35.000Z", "max_issues_repo_path": "script/random_50_symmetric_cost_vs_quality.jl", "max_issues_repo_name": "ericphanson/TravelingSalesmanBenchmarks.jl", "max_issues_repo_head_hexsha": "d5d9a328a16b200dd3efabef3b00ade96a2b2a36", "max_issues_repo_licenses": ["MIT"], "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/random_50_symmetric_cost_vs_quality.jl", "max_forks_repo_name": "ericphanson/TravelingSalesmanBenchmarks.jl", "max_forks_repo_head_hexsha": "d5d9a328a16b200dd3efabef3b00ade96a2b2a36", "max_forks_repo_licenses": ["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.7272727273, "max_line_length": 103, "alphanum_fraction": 0.7413333333, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.754653264082739}}
{"text": "\"\"\"\n\u8907\u6570\u306e\u5909\u6570\u306b\u5bfe\u3057\u3066\uff0c\u4efb\u610f\u306e q \u5024\u306b\u5bfe\u3059\u308b\u30d1\u30fc\u30bb\u30f3\u30bf\u30a4\u30eb\u5024\u3092\u6c42\u3081\u308b\u306b\u306f\uff0c\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u95a2\u6570\u3092\u5b9a\u7fa9\u3059\u308c\u3070\u3088\u3044\u3002\n\nmissing \u3092\u9664\u53bb\u3057\u3066\u8a08\u7b97\u3055\u308c\u308b\u3002\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\u4f7f\u7528\u4f8b\n\njulia> using RDatasets, Statistics\n\n\njulia> iris = dataset(\"datasets\", \"iris\");\n\n\n\njulia> quantile2(iris[:, 1:4])\n4\u00d77 DataFrame\n Row \u2502 variable     n      min      q25      median   q75      max\n     \u2502 String       Int64  Float64  Float64  Float64  Float64  Float64\n\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n   1 \u2502 SepalLength    150      4.3      5.1     5.8       6.4      7.9\n   2 \u2502 SepalWidth     150      2.0      2.8     3.0       3.3      4.4\n   3 \u2502 PetalLength    150      1.0      1.6     4.35      5.1      6.9\n   4 \u2502 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\u2217 = (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": "using Test\r\nimport GeneralizedSVD:GenSVD, gsvd\r\nusing LinearAlgebra\r\nusing DataFrames\r\nusing CSV\r\n\r\n\"\"\"\r\n    test(m, p, n)\r\n\r\nThis function tests the time performance\r\nand backward stability of Generalized Singular Value Decomposition (GSVD)\r\n\r\nFirst, we generate a m by n random matrix A and p by n random matrix B,\r\nCreate a copy of A and B, respectively (original A and B will be overwritten)\r\n\r\nThen, we call gsvd function, return U, V, Q, C, S, R, k, l.\r\nCalculate and print time elapsed for computing GSVD.\r\n\r\nCompute:\r\n\r\n      res_a = ||U' * A_ * Q - C * R||/(max(m,n)* ||A_|| * eps)\r\n\r\n      res_b = ||V' * B_ * Q - S * R||/(max(p,n)* ||B_|| * eps)\r\n\r\n      orthog_u = ||U' * U - I||/(m * eps)\r\n\r\n      orthog_v = ||V' * V - I||/(p * eps)\r\n\r\n      orthog_q = ||Q' * Q - I||/(n * eps)\r\n\r\n# Arguments\r\n- m: num of rows in A\r\n- p: num of rows in B\r\n- n: num of cols in A, B\r\n\r\nno return\r\n\"\"\"\r\nfunction computemetric(F::GenSVD, A, B)\r\n    e = eps(Float64)\r\n    m, n = size(A)\r\n    p = size(B)[1]\r\n    res_a = opnorm(F.U'*A*F.Q - F.C*F.R, 1)/(max(m,n)*opnorm(A, 1)*e)\r\n    res_b = opnorm(F.V'*B*F.Q - F.S*F.R, 1)/(max(p,n)*opnorm(B, 1)*e)\r\n    orthog_cs = opnorm(I - F.C'*F.C - F.S'*F.S, 1)/((F.k+F.l)*e)\r\n    orthog_u = opnorm(I - F.U'*F.U, 1)/(m*e)\r\n    orthog_v = opnorm(I - F.V'*F.V, 1)/(p*e)\r\n    orthog_q = opnorm(I - F.Q'*F.Q, 1)/(n*e)\r\n    return res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q\r\nend\r\n\r\nfunction computemetric(F::GeneralizedSVD, A, B)\r\n    e = eps(Float64)\r\n    m, n = size(A)\r\n    p = size(B)[1]\r\n    res_a = opnorm(F.U'*A*F.Q - F.D1*F.R0, 1)/(max(m,n)*opnorm(A, 1)*e)\r\n    res_b = opnorm(F.V'*B*F.Q - F.D2*F.R0, 1)/(max(p,n)*opnorm(B, 1)*e)\r\n    orthog_cs = opnorm(I - F.D1'*F.D1 - F.D2'*F.D2, 1)/((F.k+F.l)*e)\r\n    orthog_u = opnorm(I - F.U'*F.U, 1)/(m*e)\r\n    orthog_v = opnorm(I - F.V'*F.V, 1)/(p*e)\r\n    orthog_q = opnorm(I - F.Q'*F.Q, 1)/(n*e)\r\n    return res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q\r\nend\r\n\r\nfunction test(m, p, n)\r\n    A = randn(m, n)\r\n    B = randn(p, n)\r\n    F = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F, A, B)\r\n    return F.k, F.l, res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q\r\nend\r\n\r\nfunction test()\r\n    df = DataFrame(m = Int64[], p = Int64[], n = Int64[], k = Int64[], l = Int64[], res_a = Float64[],\r\n    res_b = Float64[], orthog_cs = Float64[], orthog_u = Float64[],\r\n    orthog_v = Float64[], orthog_q = Float64[])\r\n\r\n    # case 1: m >= n & p >= n\r\n    println(\"=======================Case 1============================\")\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(60, 50, 40)\r\n        push!(df, [60 50 40 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(300, 250, 200)\r\n        push!(df, [300 250 200 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(900, 750, 600)\r\n        push!(df, [900 750 600 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(1500, 1250, 1000)\r\n        push!(df, [1500 1250 1000 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n\r\n    # case 2: m >= n > p\r\n    println(\"=======================Case 2================================\")\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(60, 40, 50)\r\n        push!(df, [60 40 50 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(300, 200, 250)\r\n        push!(df, [300 200 250 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(900, 600, 750)\r\n        push!(df, [900 600 750 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(1500, 1000, 1250)\r\n        push!(df, [1500 1000 1250 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n\r\n    # case 3: p >= n > m\r\n    println(\"=======================Case 3==============================\")\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(40, 60, 50)\r\n        push!(df, [40 60 50 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(200, 300, 250)\r\n        push!(df, [200 300 250 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(600, 900, 750)\r\n        push!(df, [600 900 750 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(1000, 1500, 1250)\r\n        push!(df, [1000 1500 1250 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n\r\n    # case 4: n > m & n > p\r\n    println(\"=====================Case 4============================\")\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(20, 30, 60)\r\n        push!(df, [20 30 60 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(200, 300, 600)\r\n        push!(df, [200 300 600 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(400, 600, 1200)\r\n        push!(df, [400 600 1200 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n    for i = 1:20\r\n        a, b, c, d, e, f, g, h = test(1000, 1500, 3000)\r\n        push!(df, [1000 1500 3000 a b c d e f g h])\r\n        println(\"---------------------------------------------------------------\")\r\n    end\r\n\r\n    CSV.write(\"gsvd_rand_matrix_test.csv\", df, append=true)\r\n    return df\r\nend\r\n\r\n# Example 1 from Ch.4 of Jenny's Thesis\r\nfunction test1()\r\n    A  = Float64[1 2 1 0; 2 3 1 1; 3 4 1 2;4 5 1 3;5 6 1 4]\r\n    B = Float64[6 7 1 5;7 1 -6 13;-4 8 9 -2]\r\n    @time F1 = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F1, A, B)\r\n    println(\"--------Residual of gsvd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    println([A; B] \u2248 [F1.U*F1.C; F1.V*F1.S]*F1.R*F1.Q')\r\n\r\n    F2 = svd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F2, A, B)\r\n    println(\"--------Residual of svd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    return F1, F2\r\nend\r\n\r\n# Example 2 from Ch.4 of Jenny's Thesis\r\n# It turns out this example is wrong\r\n\r\n# This thus is used as Example 2 in working notes\r\nfunction test2()\r\n    A = [1. 2 1 0;2 3 1 1;3 4 1 2]\r\n    B = [4. 5 1 3;5 6 1 4;6 7 1 5;7 1 -6 13]\r\n    F1 = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F1, A, B)\r\n    println(\"--------Residual of gsvd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    println([A; B] \u2248 [F1.U*F1.C; F1.V*F1.S]*F1.R*F1.Q')\r\n\r\n    F2 = svd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F2, A, B)\r\n    println(\"--------Residual of svd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    return F1, F2\r\nend\r\n\r\nfunction test2_wrapper()\r\n    A = [1. 2 1 0;2 3 1 1;3 4 1 2];\r\n    B = [4. 5 1 3;5 6 1 4;6 7 1 5;7 1 -6 13];\r\n    return U, V, Q, D1, D2, k, l, R = gsvdwrapper(A, B)\r\nend\r\n\r\n# Example 1 in working notes\r\nfunction test3()\r\n    A = [1. 2 3 0; 5 4 2 1; 0 3 5 2; 2 1 3 3; 2 0 5 3];\r\n    B = [1. 0 3 -1; -2 5 0 1; 4 2 -1 2];\r\n    F1 = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F1, A, B)\r\n    println(\"--------Residual of gsvd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    println([A; B] \u2248 [F1.U*F1.C; F1.V*F1.S]*F1.R*F1.Q')\r\n\r\n    F2 = svd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F2, A, B)\r\n    println(\"--------Residual of svd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    return F1, F2\r\nend\r\n\r\nfunction test3_wrapper()\r\n    A = [1. 2 3 0; 5 4 2 1; 0 3 5 2; 2 1 3 3; 2 0 5 3];\r\n    B = [1. 0 3 -1; -2 5 0 1; 4 2 -1 2];\r\n    return U, V, Q, D1, D2, k, l, R = gsvdwrapper(A, B)\r\nend\r\n\r\n# Example 4 in working notes\r\nfunction test4()\r\n    A = [1. 4 2 3 0;3 4 0 -2 1;4 7 5 6 3];\r\n    B = [1. 4 2 3 0;2 5 3 4 1;3 6 4 5 2;0 1 -1 3 1];\r\n    F1 = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F1, A, B)\r\n    println(\"--------Residual of gsvd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    println([A; B] \u2248 [F1.U*F1.C; F1.V*F1.S]*F1.R*F1.Q')\r\n\r\n    F2 = svd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F2, A, B)\r\n    println(\"--------Residual of svd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    return F1, F2\r\nend\r\n\r\n# Early exit after preprocessing\r\nfunction test5()\r\n    # rank(A) = 3, rank(B) = 1, rank([A;B]) = 4\r\n    A = [1. 2 3 4;3 5 2 1;4 6 2 1];\r\n    B = [0 0 3. 0;0 0 0 0;0 0 2. 0; 0 0 0 0];\r\n    F1 = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F1, A, B)\r\n    println(\"--------Residual of gsvd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    println([A; B] \u2248 [F1.U*F1.C; F1.V*F1.S]*F1.R*F1.Q')\r\n\r\n    F2 = svd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F2, A, B)\r\n    println(\"--------Residual of svd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    return F1, F2\r\nend\r\n\r\n# Early exit in CSD\r\nfunction test6()\r\n    # rank(A) = 4, rank(B) = 1, rank([A;B]) = 4\r\n    A = [1.0 2 3 4;2 5 2 1;4 2 3 1;2 4 5 1];\r\n    B = [1. 1 0 0;0 0 0 0; 0 0 0 0; 0 0 0 0];\r\n    F1 = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F1, A, B)\r\n    println(\"--------Residual of gsvd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    println([A; B] \u2248 [F1.U*F1.C; F1.V*F1.S]*F1.R*F1.Q')\r\n\r\n    F2 = svd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F2, A, B)\r\n    println(\"--------Residual of svd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    return F1, F2\r\nend\r\n\r\n# Example in the document GSVD.jl VS. gsvd.m\r\nfunction test7()\r\n    U = [1/2 0 sqrt(3)/2 0;\r\n        0 -sqrt(3)/2 0 1/2;\r\n        sqrt(3)/2 0 -1/2 0;\r\n        0 1/2 0 sqrt(3)/2]\r\n    V = [1/2 0 sqrt(3)/2 0;\r\n        0 -sqrt(3)/2 0 1/2;\r\n        sqrt(3)/2 0 -1/2 0;\r\n        0 1/2 0 sqrt(3)/2]\r\n    Q = [1/2 0 sqrt(3)/2 0;\r\n        0 -sqrt(3)/2 0 1/2;\r\n        sqrt(3)/2 0 -1/2 0;\r\n        0 1/2 0 sqrt(3)/2]\r\n    R = [0 1 0 0;0 0 1 0;0 0 0 1]\r\n    C = [sqrt(3)/2 0 0;0 1/2 0;0 0 0;0 0 0]\r\n    S = [1/2 0 0;0 sqrt(3)/2 0;0 0 1;0 0 0]\r\n    A = U*C*R*Q'\r\n    B = V*S*R*Q'\r\n    F1 = gsvd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F1, A, B)\r\n    println(\"--------Residual of gsvd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    println([A; B] \u2248 [F1.U*F1.C; F1.V*F1.S]*F1.R*F1.Q')\r\n\r\n    F2 = svd(A, B)\r\n    res_a, res_b, orthog_cs, orthog_u, orthog_v, orthog_q = computemetric(F2, A, B)\r\n    println(\"--------Residual of svd---------\")\r\n    println(\"res_a: \", res_a)\r\n    println(\"res_b: \", res_b)\r\n    println(\"orthog_cs: \", orthog_cs)\r\n    println(\"orthog_u: \", orthog_u)\r\n    println(\"orthog_v: \", orthog_v)\r\n    println(\"orthog_q: \", orthog_q)\r\n    return F1, F2\r\nend\r\n\r\n# function profiling_function(m, p, n)\r\n#     maxI = 50\r\n#     t_pre = 0.0\r\n#     t_qr = 0.0\r\n#     t_csd = 0.0\r\n#     t_all = 0.0\r\n#     for i = 1:maxI\r\n#         println(\"---$i-th run---\")\r\n#         A = randn(m, n)\r\n#         B = randn(p, n)\r\n#         ans = @timed gsvd(A, B)\r\n#         t_pre = t_pre + ans[1][1]\r\n#         t_qr = t_qr + ans[1][2]\r\n#         t_csd = t_csd + ans[1][3]\r\n#         t_all = t_all + ans[2]\r\n#     end\r\n#     t_pre = t_pre/maxI\r\n#     t_qr = t_qr/maxI\r\n#     t_csd = t_csd/maxI\r\n#     t_all = t_all/maxI\r\n#     p_pre = 100*t_pre/t_all\r\n#     p_qr = 100*t_qr/t_all\r\n#     p_csd = 100*t_csd/t_all\r\n#     return m, p, n, t_pre, p_pre, t_qr, p_qr, t_csd, p_csd, t_all\r\n# end\r\n#\r\n# function test_profiling()\r\n#     df = DataFrame(m = Int64[], p = Int64[], n = Int64[],\r\n#     t_pre = Float64[], p_pre = Float64[],\r\n#     t_qr = Float64[], p_qr = Float64[],\r\n#     t_csd = Float64[], p_csd = Float64[],\r\n#     t_all = Float64[])\r\n#\r\n#     # case 1: m >= n & p >= n\r\n#     println(\"=======================Case 1============================\")\r\n#     t1a = profiling_function(1500, 1200, 1000)\r\n#     push!(df, [t1a[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t1b = profiling_function(500, 500, 500)\r\n#     push!(df, [t1b[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t1c = profiling_function(650, 310, 230)\r\n#     push!(df, [t1c[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t1d = profiling_function(430, 610, 210)\r\n#     push!(df, [t1d[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     # case 2: m >= n > p\r\n#     println(\"=======================Case 2================================\")\r\n#     t2a = profiling_function(1500, 1000, 1200)\r\n#     push!(df, [t2a[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t2b = profiling_function(720, 220, 540)\r\n#     push!(df, [t2b[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t2c = profiling_function(440, 180, 440)\r\n#     push!(df, [t2c[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t2d = profiling_function(370, 290, 350)\r\n#     push!(df, [t2d[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     # case 3: p >= n > m\r\n#     println(\"=======================Case 3==============================\")\r\n#     # Catch LAPACK Exception: DBDSDC did not converge\r\n#     t3a = profiling_function(1000, 1500, 1200)\r\n#     push!(df, [t3a[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t3b = profiling_function(250, 300, 300)\r\n#     push!(df, [t3b[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t3c = profiling_function(360, 660, 600)\r\n#     push!(df, [t3c[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t3d = profiling_function(130, 520, 480)\r\n#     push!(df, [t3d[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     # case 4: n > m & n > p\r\n#     println(\"=====================Case 4============================\")\r\n#     # Catch LAPACK Exception: DBDSDC did not converge\r\n#     # t4a = profiling_function(1000, 1200, 1500)\r\n#     t4a = profiling_function(1300, 1200, 1500)\r\n#     push!(df, [t4a[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t4b = profiling_function(260, 600, 770)\r\n#     push!(df, [t4b[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     # Might early exit\r\n#     # t4c = profiling_function(370, 250, 700)\r\n#     t4c = profiling_function(370, 500, 700)\r\n#     push!(df, [t4c[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     # Might early exit\r\n#     # t4d = profiling_function(120, 120, 400)\r\n#     t4d = profiling_function(220, 220, 400)\r\n#     push!(df, [t4d[i] for i in 1:10])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     CSV.write(\"LAPACK-JuliaX.X-profiling.csv\", df, append=true)\r\n#     return df\r\n# end\r\n#\r\n# function wrapper_profiling_function(m, p, n)\r\n#     maxI = 20\r\n#     t_dggsvp3 = 0.0\r\n#     t_dtgsja = 0.0\r\n#     t_all = 0.0\r\n#     for i = 1:maxI\r\n#         println(\"---$i-th run---\")\r\n#         A = randn(m, n)\r\n#         B = randn(p, n)\r\n#         ans = @timed gsvdwrapper(A, B)\r\n#         t_dggsvp3 = t_dggsvp3 + ans[1][1]\r\n#         t_dtgsja = t_dtgsja + ans[1][2]\r\n#         t_all = t_all + ans[2]\r\n#     end\r\n#     t_dggsvp3 = t_dggsvp3/maxI\r\n#     t_dtgsja = t_dtgsja/maxI\r\n#     t_all = t_all/maxI\r\n#     p_dggsvp3 = 100*t_dggsvp3/t_all\r\n#     p_dtgsja = 100*t_dtgsja/t_all\r\n#     return m, p, n, t_dggsvp3, p_dggsvp3, t_dtgsja, p_dtgsja, t_all\r\n# end\r\n#\r\n# function test_wrapper_profiling()\r\n#     df = DataFrame(m = Int64[], p = Int64[], n = Int64[],\r\n#     t_dggsvp3 = Float64[], p_dggsvp3 = Float64[],\r\n#     t_dtgsja = Float64[], p_dtgsja = Float64[],\r\n#     t_all = Float64[])\r\n#\r\n#     # case 1: m >= n & p >= n\r\n#     println(\"=======================Case 1============================\")\r\n#     t1a = wrapper_profiling_function(1500, 1200, 1000)\r\n#     push!(df, [t1a[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t1b = wrapper_profiling_function(500, 500, 500)\r\n#     push!(df, [t1b[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t1c = wrapper_profiling_function(650, 310, 230)\r\n#     push!(df, [t1c[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t1d = wrapper_profiling_function(430, 610, 210)\r\n#     push!(df, [t1d[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     # case 2: m >= n > p\r\n#     println(\"=======================Case 2================================\")\r\n#     t2a = wrapper_profiling_function(1500, 1000, 1200)\r\n#     push!(df, [t2a[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t2b = wrapper_profiling_function(720, 220, 540)\r\n#     push!(df, [t2b[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t2c = wrapper_profiling_function(440, 180, 440)\r\n#     push!(df, [t2c[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t2d = wrapper_profiling_function(370, 290, 350)\r\n#     push!(df, [t2d[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     # case 3: p >= n > m\r\n#     println(\"=======================Case 3==============================\")\r\n#     t3a = wrapper_profiling_function(1000, 1500, 1200)\r\n#     push!(df, [t3a[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t3b = wrapper_profiling_function(250, 300, 300)\r\n#     push!(df, [t3b[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t3c = wrapper_profiling_function(360, 660, 600)\r\n#     push!(df, [t3c[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t3d = wrapper_profiling_function(130, 520, 480)\r\n#     push!(df, [t3d[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     # case 4: n > m & n > p\r\n#     println(\"=====================Case 4============================\")\r\n#     t4a = wrapper_profiling_function(1300, 1200, 1500)\r\n#     push!(df, [t4a[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t4b = wrapper_profiling_function(260, 600, 770)\r\n#     push!(df, [t4b[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t4c = wrapper_profiling_function(370, 500, 700)\r\n#     push!(df, [t4c[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#     t4d = wrapper_profiling_function(220, 220, 400)\r\n#     push!(df, [t4d[i] for i in 1:8])\r\n#     println(\"---------------------------------------------------------------\")\r\n#\r\n#     CSV.write(\"Julia1.3-profiling.csv\", df, append=true)\r\n#     return df\r\n# end\r\n", "meta": {"hexsha": "909f9edcac5710da35f3cce34b918e85369d0899", "size": 22933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 38.935483871, "max_line_length": 103, "alphanum_fraction": 0.4397592988, "num_tokens": 7847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7546436215408353}}
{"text": "function nlp_cvx_205_010(\n    optimizer,\n    objective_tol,\n    primal_tol,\n    dual_tol,\n    termination_target = TERMINATION_TARGET_LOCAL,\n    primal_target = PRIMAL_TARGET_LOCAL,\n)\n    # Test Goals:\n    # - linear objective\n    # - intersection convex quadratic constraints\n    # - exponential cones\n    # Variants\n    #   010 - intersection set\n\n    model = Model(optimizer)\n\n    @variable(model, x)\n    @variable(model, y >= 0, start = 0.1)\n    @variable(model, z)\n\n    @objective(model, Max, y)\n    @NLconstraint(model, y * exp(x / y) <= z)\n    @NLconstraint(model, y * exp(-x / y) <= z)\n    @NLconstraint(model, x^2 + y^2 <= -z + 5)\n\n    optimize!(model)\n\n    check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target)\n    check_objective(model, 1.7912878443121907, tol = objective_tol)\n    return check_solution(\n        [x, y, z],\n        [0.0, 1.7912878443121907, 1.7912878443121907],\n        tol = primal_tol,\n    )\nend\n", "meta": {"hexsha": "e1bbf64e0195912bb9503876ce40be0f1ffbbfd5", "size": 945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nlp-cvx/205_010.jl", "max_stars_repo_name": "jump-dev/MINLPTests.jl", "max_stars_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-04T22:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T15:49:34.000Z", "max_issues_repo_path": "src/nlp-cvx/205_010.jl", "max_issues_repo_name": "jump-dev/MINLPTests.jl", "max_issues_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-06-14T16:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:32:27.000Z", "max_forks_repo_path": "src/nlp-cvx/205_010.jl", "max_forks_repo_name": "jump-dev/MINLPTests.jl", "max_forks_repo_head_hexsha": "9dc2b751de7470dcb4d9a726e11339a8e0bf745c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-24T16:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T02:23:53.000Z", "avg_line_length": 25.5405405405, "max_line_length": 76, "alphanum_fraction": 0.6391534392, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.754643614077793}}
{"text": "\"\"\" Julia program to Check if a number is a Palindrome Number or not.\nA palindrome number is a number such that the reverse of the number is equal to the number itself \n\"\"\"\n\nfunction check_palindrome(num)\n    temp = num\n    rev = 0\n    while (temp > 0)\n        rem = temp % 10\n        rev = (rev * 10) + rem\n        temp = temp \u00f7 10;\n    end\n    if (num == rev)\n        return true\n    else\n        return false\n    end\nend\n\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\nres = check_palindrome(abs(num))\nif res\n    println(\"The given number $num is a Palindrome Number.\")\nelse\n    println(\"The given number $num is not a Palindrome Number.\")\nend\n\n\n\"\"\"\nTime Complexity: O(log(num)), where 'num' is the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the number: 121\nThe given number 121 is a Palindrome Number.\n\nSAMPLE 2\nEnter the number: 1234\nThe given number 1234 is not a Palindrome Number.\n\n\"\"\"\n", "meta": {"hexsha": "490a3106512c059f14b1b48612426ea4cec9485c", "size": 949, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/check_palindrome.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/check_palindrome.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/check_palindrome.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": 20.1914893617, "max_line_length": 98, "alphanum_fraction": 0.6617492097, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.7545239712337974}}
{"text": "using BenchmarkTools\n\nA = rand(1000,1000)\nB = rand(1000,1000)\nC = rand(1000,1000)\n\nfunction fused(A,B,C)\n    A .+ B .+ C\nend\n@btime fused(A,B,C)\n\u03b4 = rand(10,10)\nD = zeros(1000,1000)\nfunction fused_1!(D,A,B,C)\n    D = A .+ B .+ C # equiv to tmp = A .+ B .+ C; D = tmp\nend\n\u03b4 = fused_1!(D,A,B,C)\n@btime fused_1!(D,A,B,C)\n\nD = zeros(1000,1000)\nfunction fused_2!(D,A,B,C)\n    for j in 1:2000, i in 1:2000\n        D[i,j] = A[i,j] + B[i,j] + C[i,j]\n    end\n    return D\nend\n\u03b4 = fused_2!(D,A,B,C)\n\nD = zeros(1000,1000)\nfunction fused_3!(D,A,B,C)\nD .= A .+ B .+ C\nend\nfused_3!(D,A,B,C)\n\u03b4 = fused_3!(D,A,B,C)\n@btime fused_2!(D,A,B,C)\n@btime fused_3!(D,A,B,C)\n\na = [1,2,3]\nfunction f!(a)\na[1] = 10\nend\nf!(a)\na # a = [10,2,3]\nfunction g!(a)\na = [1,2]\nend\ng!(a)\na # a = [10,2,3]\n\n@btime f!(a) # a[1] = 10\n@btime g!(a) # a = [1,2]\n\nfunction g!(a)\n    deleteat!(a, 3)\n    a[:] = [1,2]\nend\ng!(a)\na # a = [10,2,3]\n\nfunction f_alloc(A)\n    B = A[1:5,1:5]\nend\n\nfunction f_point(A)\n    B = @view A[1:5,1:5]\nend\n\n@btime f_alloc(A) # allocate array, 80 ns\n@btime f_point(A)\n\nA = rand(1000,1000) # Bind A to 1000x1000 rand matrix\nB = f_alloc(A) # Copy 5x5 slice of A to new allocation, B\nA .= zeros(1000,1000) # change contents of A\nB # B is unchanged\n\nA = rand(1000,1000) # Bind A to new 1000x1000 rand matrix\nB = f_point(A) # Bind B to a pointer, which points at 5x5 slice of A\nA .= zeros(1000,1000) # change contents of A\n\nfunction f!(B)\n    B[1,2]=10\nend\n\nf!(B)\n\nB[1,2]\n\nA[1,2]\n\nN = 1000000\nfunction f(x,y,N)\n    z=0\n    for i=1:N\n        z += x*y\n    end\n end\n\n @btime f(0.0,3.0)\n\n function f(x,y)\n     z=0\n     for i=1:10\n         z += x*y\n     end\n  end\n\n  @btime f(2,3)\n\n\n@code_llvm f(2,5)\n\n@code_llvm f(2.0,5.0)\n\n@code_typed f(2,5.0)\n@code_llvm f(2,5.0)\n\nff(x::Int,y::Int) = 2x + y\nff(x::Float64,y::Float64) = x/y\n@show ff(2,5)\n@show ff(2.0,5.0)\n\n\n\nff(x::Number,y::Number) = 2x\nff(x::Union{Int,Float64},y::Union{Int,Float64}) = 10 + x\n\nff(2.0,5)\ntypeof(2.0) <: Int\n\nff(x::Float64,y::Number) = 5x + 2y\nff(x::Number,y::Int) = x - y\nff(2.0,5)\n\nfunction h()\n    a = [1,2,3]\nend\n@btime h()\n\nfunction hh()\n    a = [0.0,0.3183098861837,3.0]\nend\n@btime hh()\n\nfunction no_prealloc(A,B)\n    C = rand(1000,1000) # preallocate array inside of function\n    for j in 1:1000, i in 1:1000\n        val = A[i,j] + B[i,j]\n        C[i,j] = val\n    end\nend\n@btime no_prealloc(A,B) # 3 ms, 2 allocations\n\n\nC = zeros(1000,1000) # preallocate array outside of function\nfunction w_prealloc!(C,A,B)\n    for j in 1:1000, i in 1:1000\n        val = A[i,j] + B[i,j]\n        C[i,j] = val\n    end\nend\n@btime w_prealloc!(C,A,B) # 2 ms, 0 allocations\n\nw_prealloc!(C,A,B)\n\nC\n\na = [0 0 0]\nv = [1 2 3]\nfunction f!(a,v)\n    for i=1:100\n        a .+= v\n    end\nend\n\n@btime f!(a,v)\n\nv = @SVector [1, 2, 3]\nfunction g!(a,v)\n    for i=1:100\n        a' .+= v\n    end\nend\n\n@btime g!(a,v)\n\nA.+B.+C./10\n\n\nfunction unfused(A,B,C)\n    A + B + C\nend\n@btime unfused(A,B,C) # same as no_broadcast()\nD\nfunction fused(A,B,C,D)\n    tmp = A .+ B\n     tmp .+= C\nend\n@btime fused(A,B,C)\n\nb = rand(100)\nfunction dothis(b)\n    a = sin.(b)\nend\n\ndothis(b)\n", "meta": {"hexsha": "67d8bd43e3b042303a7fb79a50d871ccda4e068d", "size": 3081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test4.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/test4.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/test4.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": 15.0292682927, "max_line_length": 68, "alphanum_fraction": 0.5624797144, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7545239435776975}}
{"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\u03c0/(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)\u00f72, -N\u00f72:-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": "# using Revise, Test\n# using Plots\nusing BifurcationKit, OrdinaryDiffEq, ForwardDiff\n\t# using Zygote, DiffEqSensitivity\n\tusing LinearAlgebra, Parameters\n\nnorminf = x -> norm(x, Inf)\n\nfunction Fsl!(f, u, p, t)\n\t@unpack r, \u03bc, \u03c9, c3 = p\n\tu1 = u[1]\n\tu2 = u[2]\n\n\tua = u1^2 + u2^2\n\n\tf[1] = r * u1 - \u03c9 * u2 - ua * (c3 * u1 - \u03bc * u2)\n\tf[2] = r * u2 + \u03c9 * u1 - ua * (c3 * u2 + \u03bc * u1)\n\n\treturn f\nend\n\nFsl(x, p) = Fsl!(similar(x), x, p, 0.)\ndFsl(x, dx, p) = ForwardDiff.derivative(t -> Fsl(x .+ t .* dx, p), 0.)\n\n# function to compute differentials\nfunction diffAD(f, x, dx)\n\t# Zygote.pullback(t->f(x .+ t.* dx), 0.)[1]\n\tForwardDiff.derivative(t->f(x .+ t.* dx), 0.)\nend\n\n####################################################################################################\npar_sl = (r = 0.1, \u03bc = 0., \u03c9 = 1.0, c3 = 1.0,)\nu0 = [.001, .001]\n\u03b4 = 1e-8\nprob = ODEProblem(Fsl!, u0, (0., 100.), par_sl)\nalgsl = KenCarp4()#Rodas4P()\n####################################################################################################\nsol = solve(prob, algsl, abstol =1e-9, reltol=1e-6)\n# plot(sol[1,:], sol[2,:])\n\nfunction flowTS(x, t, pb = prob; alg = algsl, kwargs...)\n\t_pb = remake(pb; u0 = x, tspan = (zero(eltype(t)), t) )\n\tsol = DiffEqBase.solve(_pb, alg; abstol =1e-10, reltol=1e-9, save_everystep = false, kwargs...)\n\treturn sol.t, sol\nend\nflowDE = (x, t, pb = prob; alg = algsl, kwargs...) -> flowTS(x, t, pb = pb; alg = alg, kwargs...)[2][end]\n\n\ndflowDE = (x, dx, ts; kwargs...) -> diffAD(z -> flowDE(z, ts; kwargs...), x, dx)\ndflowDEfd = (x, dx, ts) -> (flowDE(x .+ \u03b4 .* dx, ts) - flowDE(x, ts)) ./ \u03b4\n\n@test dflowDE(u0,u0,1.) .- dflowDEfd(u0,u0,1.) |> norminf < 10\u03b4\n####################################################################################################\n# defining the Poincare Map\nnormals = [[-1., 0.]]\ncenters = [zeros(2)]\n\nsectionH(x, c, n) = dot( x .- c[1], n[1])\npSection(u, t, integrator) = sectionH(u, centers, normals) * (integrator.iter > 1)\naffect!(integrator) = terminate!(integrator)\ncb = ContinuousCallback(pSection, affect!; affect_neg! = nothing)\n\n\u03a0(x) = flowDE(x, Inf; callback = cb, save_everystep = false) # Poincar\u00e9 return map\nT(x) = flowTS(x, Inf64; callback = cb)[1][end] # time to section\nd\u03a0(x, dx) = diffAD(\u03a0, x, dx)\nd\u03a0FD(x, dx) = (\u03a0(x .+ \u03b4 .* dx) .- \u03a0(x)) ./ \u03b4\n\nfunction DPoincare(x, dx, p, normal, center, _cb; verbose = false)\n\tverbose && printstyled(color=:blue, \"\\nEntree dans DPoincare\\n\")\n\tabs(dot(normal, dx)) > 1e-12 && @warn \"Vector does not belong to hyperplane!  dot(normal, dx) = $(abs(dot(normal, dx))) and $(dot(dx, dx))\"\n\t# compute the Poincare map from x\n\t_t\u03a3, _sol\u03a3 = flowTS(x, Inf; callback = _cb, save_everystep = false)\n\tt\u03a3, sol\u03a3 = _t\u03a3[end], _sol\u03a3[end]\n\n\tz = Fsl(sol\u03a3, p)\n\tverbose && @show z t\u03a3 sol\u03a3\n\t# solution of the variational equation at time t\u03a3\n\t# We need the callback to be INACTIVE here!!!\n\ty = dflowDE(x, dx, t\u03a3; callback = nothing)\n\tverbose && @show y\n\tout = y .- (dot(normal, y) / dot(normal, z)) .* z\nend\n\n# vecteurs for the flow and the variational flow\nu0 = [0, 1.]\ndu0 = [0, -1.]\n\n# check that we cross the sections the way we want\nts, ss = flowTS([0., 1], Inf; callback = cb, save_everystep = true, save_at = LinRange(0,1,20))\n# plot(ts,ss[:,:]')\n# plot(ss[1,:], ss[2,:], label=\"flow\");scatter!(ss[1,[1]], ss[2,[1]]);plot!(sol[1,:], sol[2,:], label=\"sol\")\n\n# these vectors should be the same\n# println(\"--> d\u03a0 using Forward Diff\")\n# res = d\u03a0(u0, du0); show(res)\n\n# println(\"--> d\u03a0 using Zygote\")\n# gives completely wrong answer\n# Zygote.pullback(t->\u03a0(u0 .+ t.* du0), 0.)[1] |> Base.show\n\nprintln(\"--> d\u03a0 using Analytical formula\")\nresAna = DPoincare(u0, du0, par_sl, normals[1], centers[1], cb);show(resAna)\n\nprintln(\"--> d\u03a0 using Finite differences\")\nresFD = d\u03a0FD(u0, du0);show(resFD)\n\nprintln(\"--> Norm of the difference = \", resAna - resFD |> norminf)\n@test resAna - resFD |> norminf < 1000\u03b4\n####################################################################################################\n# matrix of the Poincare map, analytical formula\nconst FD = ForwardDiff\nconst BK = BifurcationKit\n\nt\u03a3, sol\u03a3 = flowTS(u0, Inf64; callback = cb)\n\tt\u03a3 = t\u03a3[end]; sol\u03a3 = sol\u03a3[end]\nd\u03d5 = FD.jacobian( x -> flowTS(x, t\u03a3)[2][end], (u0))\nF = Fsl(\u03a0(u0), par_sl)\nnormal = normals[1]\n\ndTfd = BK.finiteDifferences(T, u0; \u03b4 = 1e-8)\ndT = -normal' * d\u03d5 ./ dot(normal, F)\n@test norm(dTfd - dT, Inf) < 1e-5\n\nJtmp = d\u03d5 .- F * normal' * d\u03d5 #./ dot(F, normal)\nd\u03a0fd = BK.finiteDifferences(\u03a0, u0; \u03b4 = 1e-8)\nJtmp = d\u03d5 .- F * normal' * d\u03d5 ./ dot(F, normal)\n@test norm(d\u03a0fd - Jtmp, Inf) < 2e-5\n####################################################################################################\n# comparison with BK\nusing BifurcationKit\nconst BK = BifurcationKit\n\nfunction FslMono!(f, x, p, t)\n\tu = x[1:2]\n\tdu = x[3:4]\n\tFsl!(view(f,1:2), u, p, t)\n\tf[3:4] .= dFsl(u, du, p)\nend\nprobMono = ODEProblem(FslMono!, vcat(u0, u0), (0., 100.), par_sl)\n\nprobHPsh = BK.PoincareShootingProblem(\n\t\tprob, algsl,\n\t\t# probMono, Rodas4P(autodiff=false),\n\t\tnormals, centers; abstol =1e-10, reltol=1e-10)\n\n@show BK.diffPoincareMap(probHPsh, u0, par_sl, du0, 1)\n\n\nresDP = DPoincare(u0, du0, par_sl, normals[1], centers[1], cb; verbose = true)\nresDPBK = BK.diffPoincareMap(probHPsh, u0, par_sl, du0, 1)\n@test norminf(resDP - resDPBK) < 1e-6\n", "meta": {"hexsha": "22a8f6c61723d98491ccc98d33271c17bfe9d3fc", "size": 5253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/poincareMap.jl", "max_stars_repo_name": "free-Gift-card/BifurcationKit.jl", "max_stars_repo_head_hexsha": "07938db6909fa00b10736f916750d19f92b87e22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2019-01-25T04:31:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T11:44:04.000Z", "max_issues_repo_path": "test/poincareMap.jl", "max_issues_repo_name": "free-Gift-card/BifurcationKit.jl", "max_issues_repo_head_hexsha": "07938db6909fa00b10736f916750d19f92b87e22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-01-25T04:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T13:04:19.000Z", "max_forks_repo_path": "test/poincareMap.jl", "max_forks_repo_name": "rveltz/PseudoArcLengthContinuation.jl", "max_forks_repo_head_hexsha": "61935866594ac0b669a343895b294eec1c93bed6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-01-25T04:34:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T18:53:31.000Z", "avg_line_length": 34.5592105263, "max_line_length": 140, "alphanum_fraction": 0.5642490006, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7545162198669778}}
{"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    \u03be1, \u03be2 = rand(), rand()\n    return d.location + (\u03be1 - \u03be2) * 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 10164e58-86ab-11eb-24c7-630872bf513d\n# to use the fft algorithms, import them as follows:\nusing FFTW\n\n# \u2554\u2550\u2561 76e9a7f6-86a6-11eb-2741-6b8759be971b\nmd\"\"\"\n## \u00a72 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# \u2554\u2550\u2561 04b54946-86a7-11eb-1de0-2f61e7b8f790\nmd\"\"\"\n## \u00a72.1 The Fast Fourier Transform \n\n### The Discrete Fourier Transform\n\nRecall from \u00a71 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# \u2554\u2550\u2561 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\u2013Tukey_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# \u2554\u2550\u2561 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 * \u03c0 / 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) \u00f7 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fc6671fa-8748-11eb-3d6b-e50f405b446f\nmd\"Finally, let's compare the Timing of DFT vs FFT (times in seconds):\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u0302) = sum( real(F\u0302\u2096 * exp(im * x * k))\n\t\t\t\t\t\t  for (F\u0302\u2096, k) in zip(F\u0302, kgrid(length(F\u0302) \u00f7 2)) )\nend \n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a18b061c-86b5-11eb-3c44-0bc846854b1b\nlet f = x -> sin(2*x) / (0.1 + cos(x)^2)\n\txp = range(0, 2*\u03c0, length=500)\n\tX = xgrid(_N1)\n\tF\u0302 = triginterp(f, _N1)\n\tplot(xp, f.(xp), lw=4, label = L\"f\", size = (500, 300))\n\tplot!(xp, evaltrig.(xp, Ref(F\u0302)), 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e02f56bc-86b6-11eb-3a66-0d0b94677262\nlet f = x -> exp( - abs(sin(x)) )\n\tN2 = 2^_p2\n\txp = range(0, 2*\u03c0, length=1000)\n\tX = xgrid(N2)\n\tF\u0302 = triginterp(f, N2)\n\tplot(xp, f.(xp), lw=4, label = L\"f\", size = (500, 300))\n\tplot!(xp, evaltrig.(xp, Ref(F\u0302)), 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# \u2554\u2550\u2561 240250ae-86b7-11eb-1046-7f29472897fd\nmd\"\"\"\n\n## \u00a72.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# \u2554\u2550\u2561 5ebefefe-86b7-11eb-227f-3d5e02a142fd\nmd\"\"\"\n\n## \u00a72.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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f3c1ba14-8e64-11eb-33ea-4341480e50b3\n_\u00dbex2 = let N = 100, f = _ffun2\n\t\tF\u0302 = triginterp(f, N)\n\t\tK = kgrid(N) \n\t\tF\u0302 ./ (1 .+ K.^2)\n\tend ;\n\n# \u2554\u2550\u2561 b5359ee2-86de-11eb-1446-b10b9815f448\nlet N = _N2, f = _ffun2\n\tF\u0302 = triginterp(f, N)\n\tK = kgrid(N) \n\tU\u0302 = F\u0302 ./ (1 .+ K.^2)\n\txp = range(0, 2\u03c0, length=200)\n\tplot(xp, evaltrig.(xp, Ref(_U\u0302ex2)), lw=4, label = L\"u\", size = (400, 300), \n\t\ttitle = L\"N = %$N\", xlabel = L\"x\")\n\tplot!(xp, evaltrig.(xp, Ref(\u00db)), lw=3, label = L\"u_N\", size = (400, 300))\t\t\t\t\n\tplot!(xgrid(N), evaltrig.(xgrid(N), Ref(U\u0302)), lw=0, ms=3, m=:o, c=2, label = \"\")\nend \n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03c0, 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# \u2554\u2550\u2561 9a6facbe-876b-11eb-060a-7b7e717237be\nmd\"\"\"\nTry reaching machine precision with a finite difference or finite element method!\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03c0, length = 1_234)\n\tfor N in NN \n\t\tF\u0302 = triginterp(f, N) \n\t\tpush!(err, norm(f.(xerr) - evaltrig.(xerr, Ref(F\u0302)), Inf))\n\tend\n\tata_table( (NN, L\"N\"), (err, L\"\\|f - f_N\\|\") )\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u0302 = triginterp(f, N) \n\tK = kgrid(N)\n\tplot(abs.(K), abs.(F\u0302), 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6deea4c4-86b7-11eb-0fe7-5d6d0f3007ef\nmd\"\"\"\n\n## \u00a72.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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u00db0 = triginterp(u0, N)\n\t\u00db1 = \u00db0  # zero initial velocity \n\t@gif for n = 1:ceil(Int, Tfinal / dt)\n    \t\u00db0, \u00db1 = \u00db1, 2 * \u00db1 - \u00db0 - dt^2 * k.^2 .* \u00db1 \n\t    plot(xp, evaltrig.(xp, Ref(U\u03021)), lw = 3, label = \"\", size = (400, 300), \n\t\t\t xlims = [0, 2*\u03c0], ylims = [-0.1, 1.1] )\n\tend every 5\t\t\t\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 00f2a760-8907-11eb-3ed1-376e9bf97fa8\nlet N = 256,  dt = \u03c0/(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\u0302 = 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\u0302 .* fft(V) ) ) \n\t\n\tfunction plot_soln(t, X, v, c)\n\t\tP = plot( xaxis = ([0, 2*\u03c0], ), 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\u0302 .* 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7d7d43e2-8a71-11eb-2031-f76c30b64f5e\n# using SIAMFANLEquations  # we use this package to solve nonlinear systems\n\n# \u2554\u2550\u2561 f2dab6a0-890a-11eb-1e48-a747d18f6c93\nlet N = 30, \u03f5 = 0.1\n\tfunction burger(U)\n\t\tN = length(U) \u00f7 2 \n\t\tk = kgrid(N)\n\t\tU\u0302 = fft(U) \n\t\tF = sin.(xgrid(N))\n\t\treturn real.(U .* ifft( im * k .* U\u0302 ) + \u03f5 * ifft( k.^2 .* U\u0302 ) .+ 0.1*F)\n\tend\n\tU0 = sin.(xgrid(N))\n\tU = nsoli(burger, U0, maxit = 1_000)\n\tU\u0302 = fft(U) / (2N)\n\tplot(x -> evaltrig(x, U\u0302), -\u03c0, \u03c0, 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# \u2554\u2550\u2561 7b5b1e6c-86b7-11eb-2b32-610393a24da4\nmd\"\"\"\n\n## \u00a72.5 Outlook: PDEs in higher dimension\n\nJust one example; more in \u00a74 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# \u2554\u2550\u2561 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\u00db0 = fft(U0)\n\t\u00db1 = \u00db0  # zero initial velocity \n\tdt = 0.2 / N \n\t@gif for n = 1:4_000\n\t\t\u00db0, \u00db1 = \u00db1, 2 * \u00db1 - \u00db0 - dt^2 * (Kx.^2 + Ky.^2) .* \u00db1 \n\t\tPlots.surface(x, x, real.(ifft(\u00db1)), zlims = [-0.3, 0.3], color=:viridis, \n\t\t\t\t\t  size = (400, 300))\n\tend every 5\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25003f1cfd12-7b86-11eb-1371-c5795b87ef5b\n# \u255f\u250076e9a7f6-86a6-11eb-2741-6b8759be971b\n# \u255f\u250004b54946-86a7-11eb-1de0-2f61e7b8f790\n# \u255f\u2500d57bead8-86b3-11eb-3095-1fee9108c6b1\n# \u2560\u255010164e58-86ab-11eb-24c7-630872bf513d\n# \u2560\u25507b0578ee-8744-11eb-0bf1-555f11fbb0fd\n# \u2560\u255013e8fc40-86ab-11eb-1f63-9d2ed7538e7e\n# \u2560\u2550c3e57120-86ab-11eb-2268-4f7338540556\n# \u255f\u2500fc6671fa-8748-11eb-3d6b-e50f405b446f\n# \u255f\u250096d114ee-8748-11eb-05f8-a72869439a84\n# \u255f\u25006da69574-86b4-11eb-3300-9b1d62ede475\n# \u2560\u25503c81eca4-86b5-11eb-0e54-d53593b063bc\n# \u255f\u2500c93dbae2-86b5-11eb-1468-bd709534e1af\n# \u255f\u2500a18b061c-86b5-11eb-3c44-0bc846854b1b\n# \u255f\u2500bc30cf3c-86b6-11eb-1f21-ff29b647a839\n# \u255f\u2500e02f56bc-86b6-11eb-3a66-0d0b94677262\n# \u255f\u2500240250ae-86b7-11eb-1046-7f29472897fd\n# \u255f\u25005ebefefe-86b7-11eb-227f-3d5e02a142fd\n# \u255f\u2500452c65b2-8806-11eb-2d7a-3f4312071cd1\n# \u255f\u2500503b45d0-8e65-11eb-0e77-15314d82de1a\n# \u255f\u2500f3c1ba14-8e64-11eb-33ea-4341480e50b3\n# \u2560\u2550b5359ee2-86de-11eb-1446-b10b9815f448\n# \u255f\u25000c84dcde-86e0-11eb-1877-932742501593\n# \u255f\u2500bb33932c-8769-11eb-0fb7-a39703fa96cc\n# \u2560\u2550a0e33748-8769-11eb-26b4-416a32282bc2\n# \u255f\u25009a6facbe-876b-11eb-060a-7b7e717237be\n# \u255f\u2500f63dcd36-8ac8-11eb-3831-57f0a5088c98\n# \u255f\u250033f2ab24-8ac9-11eb-220e-e71d3ebb93fa\n# \u255f\u2500a0797ece-8ac9-11eb-2922-e3f0295d4787\n# \u255f\u2500057c7508-8aca-11eb-0718-21826e314bc7\n# \u255f\u250059485024-8aca-11eb-2e65-3962c096e9df\n# \u255f\u2500c9a6c2ce-876b-11eb-182c-d90997ea2cab\n# \u255f\u25005b3e4e06-8e6e-11eb-0f31-5546b0ae450a\n# \u255f\u25006deea4c4-86b7-11eb-0fe7-5d6d0f3007ef\n# \u255f\u25007620d684-88fe-11eb-212d-efcbc1803608\n# \u2560\u255042513412-88fb-11eb-2591-c90c16e91d6e\n# \u255f\u2500ae55b0e4-88ff-11eb-36f0-152089e43c93\n# \u2560\u255000f2a760-8907-11eb-3ed1-376e9bf97fa8\n# \u255f\u2500babc0fae-88ff-11eb-0516-6b7841fc0a6a\n# \u2560\u25507d7d43e2-8a71-11eb-2031-f76c30b64f5e\n# \u2560\u2550f2dab6a0-890a-11eb-1e48-a747d18f6c93\n# \u255f\u25007b5b1e6c-86b7-11eb-2b32-610393a24da4\n# \u2560\u2550b90093f6-8906-11eb-2e69-6d4b807866a4\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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,\u03c9vec,ntrans,nattr,nres,y_init)\n    n\u03c9 = length(\u03c9vec) # no. of driving frequencies (control parameter)\n    amp_vec = zeros(n\u03c9)    # oscillation amplitudes (to be computed)\n    ds = Systems.duffing(; d, f = a)\n\n    for i\u03c9 = 1:n\u03c9\n        \u03c9 = \u03c9vec[i\u03c9]\n        set_parameter!(ds, 1, \u03c9) # sets the \u03c9 parameter\n        period = 2\u03c0/\u03c9\n        \u0394t = period/nres\n        tr = trajectory(ds, nattr*period, y_init; Ttr = ntrans*period)\n        amp_vec[i\u03c9] = 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\u03c9vec = [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,\u03c9vec,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(\u03c9vec,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)\udbc0\udc001 and HXTY.\r\n  3. While kZkk 6= 0\r\n     gk = gk\udbc0\udc001 +t (or gk = gk\udbc0\udc001t).\r\n     Bk = HXTY+H(Zk\udbc0\udc001\udbc0\udc00Uk\udbc0\udc001).\r\n     Zk = SVTgk (Bk+Uk\udbc0\udc001). (Record Zk at each iteration.)\r\n  Uk = Uk\udbc0\udc001+Bk\udbc0\udc00Uk\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 \u2208 eachindex(x), j \u2208 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 \u2208 eachindex(x,y), j \u2208 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      \u0394n = zeros(Tv,dim)\n      for i=1:maxiter\n         (D, U) = eigen(Rprev)\n         Dn .= D\n         Dn[ D .< tol ] .= 2*mineig\n         \u0394n .= Dn * (sum(D)/sum(Dn))\n         Rn .= Rprev - ((Rprev - U*diagm(\u0394n)*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": "################################################################################\r\n#                                 Type recipes                                 #\r\n################################################################################\r\n\r\nfunction to_plottable(A::AbstractInterpolation; plotdensity = 10_000, denseplot = true)\r\n  t = sort(A.t)\r\n  start = t[1]; stop = t[end]\r\n  if denseplot\r\n    plott = collect(range(start,stop=stop,length=plotdensity))\r\n  else\r\n    plott = t\r\n  end\r\n  output = A.(plott)\r\n  plott, output\r\nend\r\n\r\n@recipe function f(A::AbstractInterpolation; plotdensity = 10_000, denseplot = true)\r\n    to_plottable(A; plotdensity = plotdensity, denseplot=denseplot)\r\nend\r\n\r\n################################################################################\r\n#                                Series recipes                                #\r\n################################################################################\r\n\r\n############################################################\r\n#                      Interpolations                      #\r\n############################################################\r\n\r\n########################################\r\n#         Linear Interpolation         #\r\n########################################\r\n\r\n@recipe function f(::Type{Val{:linear_interp}}, x, y, z; plotdensity = 10_000, denseplot = true)\r\n\r\n    seriestype := :path\r\n\r\n    label --> \"Linear fit\"\r\n\r\n    nx, ny = to_plottable(LinearInterpolation(y, x); plotdensity = plotdensity, denseplot = denseplot)\r\n\r\n    x := nx\r\n    y := ny\r\nend\r\n\r\n########################################\r\n#       Quadratic Interpolation        #\r\n########################################\r\n\r\n@recipe function f(::Type{Val{:quadratic_interp}}, x, y, z; plotdensity = 10_000, denseplot = true)\r\n\r\n    seriestype := :path\r\n\r\n    label --> \"Quadratic fit\"\r\n\r\n    nx, ny = to_plottable(\r\n        QuadraticInterpolation(\r\n            T.(y),\r\n            T.(x)\r\n        );\r\n        plotdensity = plotdensity,\r\n        denseplot = denseplot\r\n    )\r\n    x := nx\r\n    y := ny\r\nend\r\n\r\n########################################\r\n#           Quadratic Spline           #\r\n########################################\r\n\r\n@recipe function f(::Type{Val{:quadratic_spline}}, x, y, z; plotdensity = 10_000, denseplot = true)\r\n\r\n    seriestype := :path\r\n\r\n    label --> \"Quadratic Spline\"\r\n\r\n    T = promote_type(eltype(y), eltype(x))\r\n\r\n    nx, ny = to_plottable(\r\n        QuadraticSpline(\r\n            T.(y),\r\n            T.(x)\r\n        );\r\n        plotdensity = plotdensity,\r\n        denseplot = denseplot\r\n    )\r\n\r\n    x := nx\r\n    y := ny\r\nend\r\n\r\n########################################\r\n#        Lagrange Interpolation        #\r\n########################################\r\n\r\n@recipe function f(::Type{Val{:lagrange_interp}},\r\n                    x, y, z;\r\n                    n = length(x) - 1,\r\n                    plotdensity = 10_000,\r\n                    denseplot = true\r\n                )\r\n\r\n    seriestype := :path\r\n\r\n    label --> \"Lagrange Fit\"\r\n\r\n    T = promote_type(eltype(y), eltype(x))\r\n\r\n    nx, ny = to_plottable(\r\n        LagrangeInterpolation(\r\n            T.(y),\r\n            T.(x),\r\n            n\r\n        );\r\n        plotdensity = plotdensity,\r\n        denseplot = denseplot\r\n    )\r\n\r\n    x := nx\r\n    y := ny\r\nend\r\n\r\n########################################\r\n#             Cubic Spline             #\r\n########################################\r\n\r\n@recipe function f(::Type{Val{:cubic_spline}}, x, y, z; plotdensity = 10_000, denseplot = true)\r\n\r\n    seriestype := :path\r\n\r\n    label --> \"Cubic Spline\"\r\n\r\n    T = promote_type(eltype(y), eltype(x))\r\n\r\n    nx, ny = to_plottable(\r\n        CubicSpline(\r\n            T.(y),\r\n            T.(x)\r\n        );\r\n        plotdensity = plotdensity,\r\n        denseplot = denseplot\r\n    )\r\n    x := nx\r\n    y := ny\r\nend\r\n\r\n\r\n@recipe function f(::Type{Val{:bspline_interp}},\r\n                x, y, z;\r\n                d = 5,\r\n                pVec=:ArcLen,\r\n                knotVec = :Average,\r\n                plotdensity = length(x) * 6,\r\n                denseplot = true\r\n            )\r\n\r\n        seriestype := :path\r\n\r\n        label --> \"B-Spline\"\r\n\r\n        @show x y eltype(x)\r\n\r\n        # T = promote_type(eltype(y), eltype(x))\r\n\r\n        nx, ny = to_plottable(\r\n            BSplineInterpolation(\r\n                T.(y),\r\n                T.(x),\r\n                d,\r\n                pVec,\r\n                knotVec\r\n            );\r\n            plotdensity = plotdensity,\r\n            denseplot = denseplot\r\n        )\r\n        x := nx\r\n        y := ny\r\nend\r\n\r\n########################################\r\n#       B-spline (approximation)       #\r\n########################################\r\n\r\n@recipe function f(::Type{Val{:bspline_approx}},\r\n                    x, y, z;\r\n                    d = 5,\r\n                    h = length(x) - 1,\r\n                    pVec = :ArcLen,\r\n                    knotVec = :Average,\r\n                    plotdensity = length(x) * 6,\r\n                    denseplot = true\r\n                )\r\n\r\n        seriestype := :path\r\n\r\n        label --> \"B-Spline\"\r\n\r\n        T = promote_type(eltype(y), eltype(x))\r\n\r\n        nx, ny = to_plottable(\r\n            BSplineApprox(\r\n                T.(y),\r\n                T.(x),\r\n                d,\r\n                h,\r\n                pVec,\r\n                knotVec\r\n            );\r\n            plotdensity = plotdensity,\r\n            denseplot = denseplot\r\n        )\r\n        x := nx\r\n        y := ny\r\nend\r\n\r\n########################################\r\n#          Akima intepolation          #\r\n########################################\r\n\r\n@recipe function f(::Type{Val{:akima}}, x, y, z; plotdensity = length(x) * 6, denseplot = true)\r\n\r\n        seriestype := :path\r\n\r\n        label --> \"Akima\"\r\n\r\n        T = promote_type(eltype(y), eltype(x))\r\n\r\n        nx, ny = to_plottable(\r\n            AkimaInterpolation(\r\n                T.(y),\r\n                T.(x)\r\n            );\r\n            plotdensity = plotdensity,\r\n            denseplot = denseplot\r\n        )\r\n        x := nx\r\n        y := ny\r\nend\r\n\r\n\r\n################################################################################\r\n#                                  Shorthands                                  #\r\n################################################################################\r\n\r\n\"\"\"\r\n    akima(u, t)\r\n    akima!(u, t)\r\n\r\nPlot the Akima interpolation of the given data.\r\n\"\"\"\r\n@shorthands akima\r\n", "meta": {"hexsha": "28f5f8b8f357d015445e6fdf2ed92ec05d9b6a9e", "size": 6470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plot_rec.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/plot_rec.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/plot_rec.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": 25.6746031746, "max_line_length": 103, "alphanum_fraction": 0.3547140649, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.754487382956967}}
{"text": "using LinearAlgebra, DiffEqOperators, Random, Test, BandedMatrices, SparseArrays\n\n# 4th derivative, 4th order\nfunction fourth_deriv_approx_stencil(N)\n    A = zeros(N,N+2)\n    A[1,1:8] = [3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3]\n    A[2,1:8] = [2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6]\n\n    A[N-1,N-5:end] = reverse([2/3 -11/6 0.0 31/6 -22/3 4.5 -4/3 1/6], dims=2)\n    A[N,N-5:end] = reverse([3.5 -56/3 42.5 -54.0 251/6 -20.0 5.5 -2/3], dims=2)\n\n    for i in 3:N-2\n        A[i,i-2:i+4] = [-1/6 2.0 -13/2 28/3 -13/2 2.0 -1/6]\n    end\n    return A\nend\n\nfunction second_deriv_fourth_approx_stencil(N)\n    A = zeros(N,N+2)\n    A[1,1:6] = [5/6 -15/12 -1/3 7/6 -6/12 5/60]\n    A[N,N-3:end] = [1/12 -6/12 14/12 -4/12 -15/12 10/12]\n    for i in 2:N-1\n        A[i,i-1:i+3] = [-1/12 4/3 -5/2 4/3 -1/12]\n    end\n    return A\nend\n\nfunction second_derivative_stencil(N)\n  A = zeros(N,N+2)\n  for i in 1:N, j in 1:N+2\n      (j-i==0 || j-i==2) && (A[i,j]=1)\n      j-i==1 && (A[i,j]=-2)\n  end\n  A\nend\n\n@test_skip begin\n@testset \"Test Constructor, Multiplication, and Concretization\" begin\n    # Generate random parameters\n    al = rand()\n    bl = rand()\n    cl = rand()\n\n    ar = rand()\n    br = rand()\n    cr = rand()\n    dx = rand()\n\n    Q = RobinBC((al, bl, cl), (ar, br, cr), dx)\n    N = 20\n    L = CenteredDifference(4, 4, dx, N)\n    L2 = CenteredDifference(2,4, dx, N)\n    L1 = UpwindDifference(1, 1, dx, N, 1.)\n\n    function coeff_func(du,u,p,t)\n        du .= u\n    end\n\n    cL = coeff_func*L\n    coeffs = rand(N)\n    DiffEqOperators.update_coefficients!(cL,coeffs,nothing,0.0)\n    cA = cL*Q\n    DiffEqOperators.update_coefficients!(cA,coeffs,nothing,0.0)\n    @test cL.coefficients == coeffs == cA.L.coefficients\n\n    cL1 = coeff_func*L1\n    coeffs = rand(N)\n    DiffEqOperators.update_coefficients!(cL1,coeffs,nothing,0.0)\n    cA1 = cL1*Q\n    DiffEqOperators.update_coefficients!(cA1,coeffs,nothing,0.0)\n    @test cL1.coefficients == coeffs == cA1.L.coefficients\n\n    A = L*Q\n    c2A = coeff_func*A\n    DiffEqOperators.update_coefficients!(c2A,coeffs,nothing,0.0)\n    @test coeffs == c2A.L.coefficients\n\n\n    # Test GhostDerivativeOperator constructor by *\n    u = rand(N)\n    A = L*Q\n    A1 = L1*Q\n\n    # Test for consistency of GhostDerivativeOperator*u with L*(Q*u)\n    @test A == L * Q\n    @test A*u \u2248 L*(Q*u)\n    @test A1 == L1 * Q\n    @test A1*u \u2248 L1*(Q*u)\n\n    # Test for consistency of c*GhostDerivativeOperator*u with alternative methods\n    c = 2.1\n    @test c * A == (c * L) * Q == c * (L * Q)\n    @test c * A * u \u2248 (c * L) * (Q * u) \u2248 c * (L * Q) * u\n    @test c * A1 == (c * L1) * Q == c * (L1 * Q)\n    @test c * A1 * u \u2248 (c * L1) * (Q * u) \u2248 c * (L1 * Q) * u\n\n    # check A + B, where A and B are GhostDerivativeOperators\n    B = c * A\n    B1 = c * A1\n    @test (A + B) * u == (A + c * A) * u == (B + A) * u == (c * A + A) * u\n    @test (A + B) * u == A * u + B * u\n    @test (A1 + B1) * u == (A1 + c * A1) * u == (B1 + A1) * u == (c * A1 + A1) * u\n    @test (A1 + B1) * u == A1 * u + B1 * u\n\n    # Check (L + L) * Q works\n    LLQ = (L + L) * Q\n    LLQ1 = (L1 + L1) * Q\n    @test LLQ * u == A * u + A * u == (A + A) * u\n    @test LLQ1 * u == A1 * u + A1 * u == (A1 + A1) * u\n\n    # Test for consistency of c*GhostDerivativeOperator*u when c is a vector\n    c = rand(N)\n    L = CenteredDifference(4, 4, dx, N)\n    L1 = UpwindDifference(1, 1, 1., N, 1.)\n    A1 = L1 * Q\n    cA = c * A\n    cL = c * L\n    cLQ = (c * L) * Q\n    cA1 = c * A1\n    cL1 = c * L1\n    cLQ1 = (c * L1) * Q\n    @test cA.L == cL\n    @test cA.L.coefficients == cL.coefficients == cLQ.L.coefficients\n    @test c * A == (c * L) * Q == c * (L * Q)\n    @test c * A * u \u2248 (c * L) * (Q * u) \u2248 c * (L * Q) * u\n    @test cA1.L.coefficients == cL1.coefficients == cLQ1.L.coefficients\n    @test c * A1 == (c * L1) * Q == c * (L1 * Q)\n    @test c * A1 * u \u2248 (c * L1) * (Q * u) \u2248 c * (L1 * Q) * u\n\n    # check A + B, where A and B are GhostDerivativeOperators\n    B = c * A\n    B1 = c * A1\n    # @test (A + B) == A + c * A == B + A == c * A + A # uncomment if we want to implement and test for equality of linear combinations of operators\n    @test (A + B) * u == (A + c * A) * u == (B + A) * u == (c * A + A) * u\n    @test (A + B) * u == A * u + B * u\n    # @test (A1 + B1) == A + c * A1 == B1 + A1 == c * A1 + A1\n    @test (A1 + B1) * u == (A1 + c * A1) * u == (B1 + A1) * u == (c * A1 + A1) * u\n    @test (A1 + B1) * u == A1 * u + B1 * u\n\n    # Test for consistency of GhostDerivativeOperator*M with L*(Q*M)\n\n    M = rand(N,10)\n    Qx = MultiDimBC{1}(Q, size(M))\n    Am = L*Qx\n    LQM = zeros(N,10)\n    for i in 1:10\n        mul!(view(LQM,:,i), L, Q*M[:,i])\n    end\n    ghost_LQM = Am*M\n    @test ghost_LQM \u2248 LQM\n\n    u = rand(N + 2)\n    @test (L + L2) * u \u2248 convert(AbstractMatrix,L + L2) * u \u2248 (BandedMatrix(L) + BandedMatrix(L2)) * u\n\n    # Test concretization\n    @test Array(A)[1] \u2248 (Array(L)*Array(Q,N)[1], Array(L)*Array(Q,N)[2])[1]\n    @test Array(A)[2] \u2248 (Array(L)*Array(Q,N)[1], Array(L)*Array(Q,N)[2])[2]\n    @test SparseMatrixCSC(A)[1] \u2248 (SparseMatrixCSC(L)*SparseMatrixCSC(Q,N)[1], SparseMatrixCSC(L)*SparseMatrixCSC(Q,N)[2])[1]\n    @test SparseMatrixCSC(A)[2] \u2248 (SparseMatrixCSC(L)*SparseMatrixCSC(Q,N)[1], SparseMatrixCSC(L)*SparseMatrixCSC(Q,N)[2])[2]\n    @test sparse(A)[1] \u2248 (sparse(L)*sparse(Q,N)[1], sparse(L)*sparse(Q,N)[2])[1]\n    @test sparse(A)[2] \u2248 (sparse(L)*sparse(Q,N)[1], sparse(L)*sparse(Q,N)[2])[2]\n    # BandedMatrix not implemented for boundary operator\n    @test_broken BandedMatrix(A)[1] \u2248 (BandedMatrix(L)*BandedMatrix(Q,N)[1], BandedMatrix(L)*BandedMatrix(Q,N)[2])[1]\n    @test_broken BandedMatrix(A)[2] \u2248 (BandedMatrix(L)*BandedMatrix(Q,N)[1], BandedMatrix(L)*BandedMatrix(Q,N)[2])[2]\n\n    # Test that concretization works with multiplication\n    u = rand(N)\n    @test Array(A)[1]*u + Array(A)[2] \u2248 L*(Q*u) \u2248 A*u\n    @test sparse(A)[1]*u + sparse(A)[2] \u2248 L*(Q*u) \u2248 A*u\nend\n\n@testset \"Test Constructor, Multiplication, and Concretization (Non-uniform grid)\" begin\n    # Generate random parameters\n    al = rand()\n    bl = rand()\n    cl = rand()\n\n    ar = rand()\n    br = rand()\n    cr = rand()\n    N = 20\n    dx = rand(N + 2)\n\n    Q = RobinBC((al, bl, cl), (ar, br, cr), dx)\n    L = UpwindDifference(1, 1, dx, N + 1, 1.)\n    L2 = CenteredDifference(2, 2, dx, N)\n    L4 = CenteredDifference(4, 4, dx, N - 2)\n\n    function coeff_func(du,u,p,t)\n        du .= u\n    end\n\n    cL = coeff_func*L\n    coeffs = rand(N + 1)\n    DiffEqOperators.update_coefficients!(cL,coeffs,nothing,0.0)\n    cA = cL*Q\n    DiffEqOperators.update_coefficients!(cA,coeffs,nothing,0.0)\n    @test cL.coefficients == coeffs == cA.L.coefficients\n\n    cL2 = coeff_func*L2\n    coeffs = rand(N)\n    DiffEqOperators.update_coefficients!(cL2,coeffs,nothing,0.0)\n    cA2 = cL2*Q\n    DiffEqOperators.update_coefficients!(cA2,coeffs,nothing,0.0)\n    @test cL2.coefficients == coeffs == cA2.L.coefficients\n\n    cL4 = coeff_func*L4\n    coeffs = rand(N - 2)\n    DiffEqOperators.update_coefficients!(cL4,coeffs,nothing,0.0)\n    cA4 = cL4*Q\n    DiffEqOperators.update_coefficients!(cA4,coeffs,nothing,0.0)\n    @test cL4.coefficients == coeffs == cA4.L.coefficients\n\n    # Test GhostDerivativeOperator constructor by *\n    u = rand(N + 1)\n    u2 = rand(N)\n    u4 = rand(N - 2)\n    A = L*Q\n    A2 = L2*Q\n    A4 = L4*Q\n\n    # Test for consistency of GhostDerivativeOperator*u with L*(Q*u)\n    @test A == L * Q\n    @test A*u \u2248 L*(Q*u)\n    @test A2 == L2 * Q\n    @test A2*u2 \u2248 L2*(Q*u2)\n    @test A4 == L4 * Q\n    @test A4*u4 \u2248 L4*(Q*u4)\n\n    # Test for consistency of c*GhostDerivativeOperator*u with alternative methods\n    c = 2.1\n    cA = c * A\n    cL = c * L\n    @test c * A == (c * L) * Q == c * (L * Q)\n    @test c * A * u \u2248 (c * L) * (Q * u) \u2248 c * (L * Q) * u\n    @test c * A2 == (c * L2) * Q == c * (L2 * Q)\n    @test c * A2 * u2 \u2248 (c * L2) * (Q * u2) \u2248 c * (L2 * Q) * u2\n    @test c * A4 == (c * L4) * Q == c * (L4 * Q)\n    @test c * A4 * u4 \u2248 (c * L4) * (Q * u4) \u2248 c * (L4 * Q) * u4\n\n    # check A + B, where A and B are GhostDerivativeOperators\n    B = c * A\n    B2 = c * A2\n    B4 = c * A4\n    @test (A + B) * u == (A + c * A) * u == (B + A) * u == (c * A + A) * u\n    @test (A + B) * u == A * u + B * u\n    @test (A2 + B2) * u2 == (A2 + c * A2) * u2 == (B2 + A2) * u2 == (c * A2 + A2) * u2\n    @test (A2 + B2) * u2 == A2 * u2 + B2 * u2\n    @test (A4 + B4) * u4 == (A4 + c * A4) * u4 == (B4 + A4) * u4 == (c * A4 + A4) * u4\n    @test (A4 + B4) * u4 == A4 * u4 + B4 * u4\n\n    # Check (L + L) * Q works\n    LLQ = (L + L) * Q\n    LLQ2 = (L2 + L2) * Q\n    LLQ4 = (L4 + L4) * Q\n    @test LLQ * u == A * u + A * u == (A + A) * u\n    @test LLQ2 * u2 == A2 * u2 + A2 * u2 == (A2 + A2) * u2 # this comparison fails, even though the operators seem alike\n    @test LLQ4 * u4 == A4 * u4 + A4 * u4 == (A4 + A4) * u4\n\n    # Test for consistency of c*GhostDerivativeOperator*u when c is a vector\n    c = rand(N + 1)\n    L1 = L\n    A1 = L1 * Q\n    cA = c * A\n    cL = c * L\n    cLQ = (c * L) * Q\n    cA1 = c * A1\n    cL1 = c * L1\n    cLQ1 = (c * L1) * Q\n    @test cA.L == cL\n    @test cA.L.coefficients == cL.coefficients == cLQ.L.coefficients\n    @test c * A == (c * L) * Q == c * (L * Q)\n    @test c * A * u \u2248 (c * L) * (Q * u) \u2248 c * (L * Q) * u\n    @test cA1.L.coefficients == cL1.coefficients == cLQ1.L.coefficients\n    @test c * A1 == (c * L1) * Q == c * (L1 * Q)\n    @test c * A1 * u \u2248 (c * L1) * (Q * u) \u2248 c * (L1 * Q) * u\n\n    # check A + B, where A and B are GhostDerivativeOperators\n    B = c * A\n    # @test (A + B) == A + c * A == B + A == c * A + A # uncomment if implement equality of combinations of linear operators\n    @test (A + B) * u == (A + c * A) * u == (B + A) * u == (c * A + A) * u\n    @test (A + B) * u == A * u + B * u\n\n    # Test for consistency of GhostDerivativeOperator*M with L*(Q*M)\n    M = rand(N+1,10)\n    LQM = zeros(N+1,10)\n    for i in 1:10\n        mul!(view(LQM,:,i), L, Q*M[:,i])\n    end\n    ghost_LQM = A*M\n    @test ghost_LQM \u2248 LQM\n\n    # Test concretization for UpwindDifference\n    @test Array(A)[1] \u2248 (Array(L)*Array(Q,N + 1)[1], Array(L)*Array(Q,N + 1)[2])[1]\n    @test Array(A)[2] \u2248 (Array(L)*Array(Q,N + 1)[1], Array(L)*Array(Q,N + 1)[2])[2]\n    @test SparseMatrixCSC(A)[1] \u2248 (SparseMatrixCSC(L)*SparseMatrixCSC(Q,N + 1)[1], SparseMatrixCSC(L)*SparseMatrixCSC(Q,N + 1)[2])[1]\n    @test SparseMatrixCSC(A)[2] \u2248 (SparseMatrixCSC(L)*SparseMatrixCSC(Q,N + 1)[1], SparseMatrixCSC(L)*SparseMatrixCSC(Q,N + 1)[2])[2]\n    @test sparse(A)[1] \u2248 (sparse(L)*sparse(Q,N + 1)[1], sparse(L)*sparse(Q,N + 1)[2])[1]\n    @test sparse(A)[2] \u2248 (sparse(L)*sparse(Q,N + 1)[1], sparse(L)*sparse(Q,N + 1)[2])[2]\n    # BandedMatrix not implemeted for boundary operator\n    @test_broken BandedMatrix(A)[1] \u2248 (BandedMatrix(L)*BandedMatrix(Q,N + 1)[1], BandedMatrix(L)*BandedMatrix(Q,N + 1)[2])[1]\n    @test_broken BandedMatrix(A)[2] \u2248 (BandedMatrix(L)*BandedMatrix(Q,N + 1)[1], BandedMatrix(L)*BandedMatrix(Q,N + 1)[2])[2]\n\n    # Test concretization for CenteredDifference\n    A2 = L2 * Q\n    @test Array(A2)[1] \u2248 (Array(L2)*Array(Q,N)[1], Array(L2)*Array(Q,N)[2])[1]\n    @test Array(A2)[2] \u2248 (Array(L2)*Array(Q,N)[1], Array(L2)*Array(Q,N)[2])[2]\n    @test SparseMatrixCSC(A2)[1] \u2248 (SparseMatrixCSC(L2)*SparseMatrixCSC(Q,N)[1], SparseMatrixCSC(L2)*SparseMatrixCSC(Q,N)[2])[1]\n    @test SparseMatrixCSC(A2)[2] \u2248 (SparseMatrixCSC(L2)*SparseMatrixCSC(Q,N)[1], SparseMatrixCSC(L2)*SparseMatrixCSC(Q,N)[2])[2]\n    @test sparse(A2)[1] \u2248 (sparse(L2)*sparse(Q,N)[1], sparse(L2)*sparse(Q,N)[2])[1]\n    @test sparse(A2)[2] \u2248 (sparse(L2)*sparse(Q,N)[1], sparse(L2)*sparse(Q,N)[2])[2]\n    # BandedMatrix not implemeted for boundary operator\n    @test_broken BandedMatrix(A2)[1] \u2248 (BandedMatrix(L2)*BandedMatrix(Q,N)[1], BandedMatrix(L2)*BandedMatrix(Q,N)[2])[1]\n    @test_broken BandedMatrix(A2)[2] \u2248 (BandedMatrix(L2)*BandedMatrix(Q,N)[1], BandedMatrix(L2)*BandedMatrix(Q,N)[2])[2]\n\n    # Test that concretization works with multiplication, UpwindDifference\n    u = rand(N + 1)\n    @test Array(A)[1]*u + Array(A)[2] \u2248 L*(Q*u) \u2248 A*u\n    @test sparse(A)[1]*u + sparse(A)[2] \u2248 L*(Q*u) \u2248 A*u\n\n    # Test that concretization works with multiplication, CenteredDifference\n    u = rand(N)\n    @test Array(A2)[1]*u + Array(A2)[2] \u2248 L2*(Q*u) \u2248 A2*u\n    @test sparse(A2)[1]*u + sparse(A2)[2] \u2248 L2*(Q*u) \u2248 A2*u\nend\n\n@testset \"Test Left Division L2 (second order)\" begin\n    # Test \\ Homogenous BC\n    # f(x) = -x^2 + x\n    # f''(x) = -2.0\n    # f'(0) = f'(1) = 0\n    f(x) = -x^2 + x\n    f2(x) = -2.0\n\n    dx = 0.01\n    x = dx:dx:1.0-dx\n    N = length(x)\n\n    L = CenteredDifference(2, 2, dx, N)\n    Q = RobinBC((1.0, 0.0, 0.0), (1.0, 0.0, 0.0), dx)\n    A = L*Q\n\n    analytic_L = second_derivative_stencil(N) ./ dx^2\n    analytic_QL = [transpose(zeros(N)); Diagonal(ones(N)); transpose(zeros(N))]\n    analytic_AL = analytic_L*analytic_QL\n\n    analytic_QM = zeros((length(x)+2)*2, length(x)*2)\n    interior = CartesianIndices(Tuple([2:length(x)+1, 1:2]))\n    I1 = CartesianIndex(1,0)\n    for I in interior\n        i = DiffEqOperators.cartesian_to_linear(I, (length(x)+2, 2)) #helper function, see utils.jl\n        j = DiffEqOperators.cartesian_to_linear(I-I1, (length(x), 2))\n        analytic_QM[i,j] = 1.0\n    end\n    analytic_Am = kron(Diagonal(ones(2)), analytic_L)*analytic_QM\n\n    # No affine component to the this system\n    analytic_f = analytic_AL \\ f2.(x)\n    ghost_f = A \\ f2.(x)\n\n    # Check that A\\f2.(x) is consistent with analytic_AL \\ f2.(x)\n    @test analytic_f \u2248 ghost_f\n\n    # Additionally test that A\\f2.(x) \u2248 f.(x)\n    @test f.(x) \u2248 ghost_f \u2248 analytic_f\n\n    # Check that left division with matrices works\n    M = [f2.(x) f2.(x)]\n    Qx = MultiDimBC{1}(Q, size(M))\n\n    Am = L*Qx\n    ghost_fM = Am \\ M\n    s = size(M)\n    analytic_fM = analytic_Am \\ reshape(M, prod(s))\n    @test ghost_fM \u2248 reshape(analytic_fM, s)\n\n    fM_temp = zeros(N,2)\n\n    # Test \\ Inhomogenous BC\n    # f(x) = -x^2 + x + 4.0\n    # f''(x) = -2.0\n    # f'(0) = f'(1) = 0\n    f(x) = -x^2 + x + 4.0\n    f2(x) = -2.0\n\n    dx = 0.01\n    x = dx:dx:1.0-dx\n    N = length(x)\n\n    L = CenteredDifference(2, 2, dx, N)\n    Q = RobinBC((1.0, 0.0, 4.0), (1.0, 0.0, 4.0), dx)\n    A = L*Q\n\n    analytic_L = second_derivative_stencil(N) ./ dx^2\n    analytic_QL = [transpose(zeros(N)); Diagonal(ones(N)); transpose(zeros(N))]\n    analytic_Qb = [4.0; zeros(N); 4.0]\n    analytic_AL = analytic_L*analytic_QL\n    analytic_Ab = analytic_L*analytic_Qb\n    analytic_Lm = kron(Diagonal(ones(3)), analytic_L)\n\n    analytic_f = analytic_AL \\ (f2.(x) - analytic_Ab)\n    ghost_f = A \\ f2.(x)\n\n    # Check that A\\f2.(x) is consistent with analytic_AL \\ f2.(x)\n    @test analytic_f \u2248 ghost_f\n\n    # Additionally test that A\\f2.(x) \u2248 f.(x)\n    @test f.(x) \u2248 ghost_f \u2248 analytic_f\n\n    # Check \\ for Matrix\n    M2 = [f2.(x) 2.0*f2.(x) 10.0*f2.(x)]\n\n    s = size(M2)\n    Qx = MultiDimBC{1}(Q, size(M2))\n\n    analytic_QLm, analytic_Qbm = Array(Qx, s)\n\n    analytic_ALm = analytic_Lm*analytic_QLm\n    analytic_Abm = analytic_Lm*analytic_Qbm\n\n    Am = L*Qx\n    analytic_M = analytic_ALm \\ (reshape(M2 , prod(s)).- analytic_Abm)\n    ghost_M = Am \\ M2\n    @test reshape(analytic_M, s) \u2248 ghost_M\n\n    # Additionally test that A\\M2 \u2248 [f, 2.0(f-4.0)+4.0, 10.0(f-4.0)+4.0]\n    M = [f.(x) 2.0*(f.(x) .- 4.0).+4.0 10.0*(f.(x) .- 4.0).+4.0]\n    @test M \u2248 reshape(analytic_M, s) \u2248 ghost_M\nend\n\n@testset \"Test Left Division L4 (fourth order)\" begin\n\n    # Test \\ homogenous and inhomogenous BC\n    dx = 0.01\n    x = 0.01:dx:0.2\n    N = length(x)\n    u = sin.(x)\n\n    L = CenteredDifference(4, 4, dx, N)\n    Q = RobinBC((1.0, 0.0, 0.0), (1.0, 0.0, sin(0.2+dx)), dx)\n    A = L*Q\n\n    analytic_L = fourth_deriv_approx_stencil(N) ./ dx^4\n    analytic_QL = [transpose(zeros(N)); Diagonal(ones(N)); transpose(zeros(N))]\n    analytic_AL = analytic_L*analytic_QL\n    analytic_Qb = [zeros(N+1); sin(0.2+dx)]\n    analytic_Ab = analytic_L*analytic_Qb\n\n\n    analytic_QM = zeros((length(x)+2)*3, length(x)*3)\n    interior = CartesianIndices(Tuple([2:length(x)+1, 1:3]))\n    I1 = CartesianIndex(1,0)\n    for I in interior\n        i = DiffEqOperators.cartesian_to_linear(I, (length(x)+2, 3)) #helper function, see utils.jl\n        j = DiffEqOperators.cartesian_to_linear(I-I1, (length(x), 3))\n        analytic_QM[i,j] = 1.0\n    end\n    analytic_Am = kron(Diagonal(ones(3)), analytic_L)*analytic_QM\n\n    analytic_u = analytic_AL \\ Vector(u .- analytic_Ab)\n    ghost_u = A \\ u\n\n    As_l, As_b = sparse(A, length(u))\n\n    @test As_l \u2248 analytic_AL #This is true\n    @test As_b \u2248  analytic_Ab #This is true\n    @test Vector(u .- analytic_Ab) \u2248 Vector(u .- As_b) #this is true\n    u_translated = u .- analytic_Ab |> Vector\n    # TODO validate analytic_AL as having reasonable condition (what is reasonable condition?)\n    @test norm(analytic_AL \\ u_translated - As_l \\ u_translated) / norm(analytic_AL \\ u_translated) < cond(analytic_AL)*eps()\n\n    sp_u = As_l\\Vector(u .- As_b)\n    # Check that A\\u.(x) is consistent with analytic_AL \\ u.(x)\n    @test ghost_u \u2248 sp_u\n    # TODO make cond function in ghost_derivative_operator?\n    # however, note: ArgumentError: 2-norm condition number is not implemented for sparse matrices, try cond(Array(A), 2) instead\n    # so the actual function would probably just propagate that error\n    _cond(A::GhostDerivativeOperator, u) = cond(sparse(A,length(u))[1] |> Array)\n    @test norm(analytic_u - ghost_u) / norm(ghost_u) < _cond(A,u) * eps() #\n\n    M2 = [u 2.0*u 10.0*u]\n    s = size(M2)\n    Qx = MultiDimBC{1}(Q, size(M2))\n    Am = L*Qx\n    #Somehow the operator is singular\n    @test_broken analytic_M = analytic_Am \\ (reshape(M2, prod(s)) .- repeat(analytic_Ab, 3))\n    @test_broken ghost_M = Am \\ M2\n    @test_broken reshape(analytic_M, s) \u2248 ghost_M\n\nend\n\n@testset \"Test Operator and BC combinations\" begin\n    N = 40\n    x = range(-pi, stop = pi, length=N)\n    \u0394x = x[2]-x[1]\n    u\u2080=1.0\n    \u0393=1.0\n    Dx=u\u2080*CenteredDifference{1}(1,4,\u0394x,N)\n    Dxx=\u0393*CenteredDifference{1}(2,4,\u0394x,N)\n    Q=NeumannBC((2x[1]+2, 2x[end]+2), \u0394x, 6)\n\n    A = Dx*Q + Dxx*Q\n\n    y = A*(x.^2)\n    analytic_y = 2x.+2\n\n    @test_broken y \u2248 analytic_y\nend\nend\n", "meta": {"hexsha": "ddd5a52c7c77ea4257d4bde2150dfcf259235900", "size": 18044, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DerivativeOperators/bc_coeff_compositions.jl", "max_stars_repo_name": "briochemc/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/bc_coeff_compositions.jl", "max_issues_repo_name": "briochemc/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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": "test/DerivativeOperators/bc_coeff_compositions.jl", "max_forks_repo_name": "briochemc/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a94114887f6d1b543bd83c5c08d0f72e61213685", "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.3803921569, "max_line_length": 148, "alphanum_fraction": 0.5648969186, "num_tokens": 7200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7544208243219062}}
{"text": "using Distributions, LinearAlgebra, Compat, Expectations\n\n# A default utility function\n\nfunction u(c, \u03c3)\n    if c > 0\n        return (c^(1 - \u03c3) - 1) / (1 - \u03c3)\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    \u03b1::TF         # Job separation rate\n    \u03b2::TF         # Discount rate\n    \u03b3::TF         # Job offer rate\n    c::TF         # Unemployment compensation\n    \u03c3::TF         # Utility parameter\n    w_vec::TAV    # Possible wage values\n\n    McCallModel(\u03b1::TF = 0.2,\n                \u03b2::TF = 0.98,\n                \u03b3::TF = 0.7,\n                c::TF = 6.0,\n                \u03c3::TF = 2.0,\n                w_vec::TAV = default_w_vec,\n                ) where {TF, TAV} =\n        new{TF, TAV}(\u03b1, \u03b2, \u03b3, c, \u03c3, w_vec)\nend\n\nfunction update_bellman!(mcm, V, V_new, U, E)\n    # Simplify notation\n    \u03b1, \u03b2, \u03c3, c, \u03b3 = mcm.\u03b1, mcm.\u03b2, mcm.\u03c3, mcm.c, mcm.\u03b3\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, \u03c3) + \u03b2 * ((1 - \u03b1) * V[w_idx] + \u03b1 * U)\n    end\n\n    U_new = u(c, \u03c3) + \u03b2 * (1 - \u03b3) * U +\n            \u03b2 * \u03b3 * 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": "using CellularAutomata\nusing Test\n\n# Function to test Conway's blinker oscillator and toad oscillator\nfunction blinker_test()\n    init = Array{Int}(zeros(10,10))\n\n    # 'Toad Oscillator'\n    init[6, 4] = 1\n    init[6, 5] = 1\n    init[6, 6] = 1\n\n    init[7, 5] = 1\n    init[7, 6] = 1\n    init[7, 7] = 1\n\n    ca = CA2d([3], [2,3], init, 9);\n\n    @test ca.cells[:, :, 3] == ca.cells[:, :, 1]\n    @test ca.cells[:, :, 5] == ca.cells[:, :, 3]\n    @test ca.cells[:, :, 4] == ca.cells[:, :, 2]\n    @test ca.cells[:, :, 8] == ca.cells[:, :, 6]\n\n    # 'Blinker Oscillator'\n    init[6, 4] = 0\n    init[6, 5] = 0\n    init[6, 6] = 0\n\n    ca = CA2d([3], [2,3], init, 9)\n\n    @test ca.cells[:, :, 3] == ca.cells[:, :, 1]\n    @test ca.cells[:, :, 5] == ca.cells[:, :, 3]\n    @test ca.cells[:, :, 4] == ca.cells[:, :, 2]\n    @test ca.cells[:, :, 8] == ca.cells[:, :, 6]\nend\n\n# Function to test Conway's turbine automota which repeats every ninth step\nfunction turbine_test()\n    init = zeros(Int, 20, 20)\n    init[4, 4:9] .= 1\n    init[5, 4:9] .= 1\n\n    init[4:9, 11] .= 1\n    init[4:9, 12] .= 1\n\n    init[11, 7:12] .= 1\n    init[12, 7:12] .= 1\n\n    init[7:12, 4] .= 1\n    init[7:12, 5] .= 1\n\n    ca = CA2d([3], [2,3], init, 18)\n\n    for i in 9:18\n        @test ca.cells[:, :, i] == ca.cells[:, :, i-8]\n    end\nend\n\nturbine_test()\n\nblinker_test()\n", "meta": {"hexsha": "adecb9cfb988751930e5a8b00c8651ccbaafc862", "size": 1331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "wherrera10/CellularAutomata.jl", "max_stars_repo_head_hexsha": "2e94acb65bf5c15df27efb25335071646cc5249d", "max_stars_repo_licenses": ["MIT"], "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": "wherrera10/CellularAutomata.jl", "max_issues_repo_head_hexsha": "2e94acb65bf5c15df27efb25335071646cc5249d", "max_issues_repo_licenses": ["MIT"], "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": "wherrera10/CellularAutomata.jl", "max_forks_repo_head_hexsha": "2e94acb65bf5c15df27efb25335071646cc5249d", "max_forks_repo_licenses": ["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.4677419355, "max_line_length": 75, "alphanum_fraction": 0.4928625094, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8459424450764199, "lm_q1q2_score": 0.7544208114589892}}
{"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# - `\u03b1` 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\u0302, b\u0302 = 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\u0302 + b\u0302, ma * w\u0302 + b\u0302], 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 \u03b8 in the expression:\n# ```math\n# e_i = (y_{i} + \\theta_{y_i}) - w (x_{i} + \\theta_{x_{i}}) - b\n# ```\n\n\u2207 = 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    \u2207[i] = abs(dw)\nend\n\nnormalize!(\u2207);\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 \u2207],\n    markersize = [25 * abs(x) for x in \u2207],\n    label = \"\"\n)\nmi, ma = minimum(X), maximum(X)\nPlots.plot!(p, [mi, ma], [mi * w\u0302 + b\u0302, ma * w\u0302 + b\u0302], 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    \u03bc = sum(X) ./ N\n    return \u03bc\nend\n\n\"\"\"\n    sample covariance\n\"\"\"\nfunction sample_covariance(X, \u03b2)\n    N = length(X)\n    \u03bc = sample_mean(X)\n    P = sum([(X[i] - \u03bc) * (X[i] - \u03bc)' for i = 1:N]) ./ (2.0 * \u03b2^2.0)\n    return P\nend\n\n\"\"\"\n    deterministic sampling\n\"\"\"\nfunction resample(X, \u03b2)\n    n = length(X[1])\n    \u03bc = sample_mean(X)\n    P = sample_covariance(X, \u03b2)\n    cols = sqrt(P)\n    Xs = [\u03bc + s * \u03b2 * cols[:,i] for s in [-1.0, 1.0] for i = 1:n]\n    return Xs\nend\n\nfunction resample_vec(X, n, N, \u03b2)\n    _X = [X[(i - 1) * n .+ (1:n)] for i = 1:N]\n    return vcat(resample(_X, \u03b2)...)\nend\n\nfunction resample_vec(X, n, N, \u03b2, k)\n    _X = [X[(i - 1) * n .+ (1:n)] for i = 1:N]\n    Xs = resample(_X, \u03b2)\n    return Xs[k]\nend\n\nfunction resample(\u03bc, P, \u03b2::T) where T\n    n = length(\u03bc)\n    cols = sqrt(P)\n    Xs = [\u03bc + s * \u03b2 * 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# \u2554\u2550\u2561 51ab86a0-af67-11eb-2542-018f2a541d80\nbegin\n\tusing LinearAlgebra\n\tusing Plots\n\tusing Printf\n\tusing IJulia\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 de0276af-306d-4758-96b0-d76e024a5291\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nfunction generate_b(n)\n\tb = ones(n);\n\treturn b;\nend\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b17e0683-c34c-43e7-9170-cd8a5a293a17\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\nfunction jacobi_\u03c9(A,b,x0,\u03c9)\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] = (\u03c9/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# \u2554\u2550\u2561 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\u03c9 = 0.5;\n\t\u03c91 = 1.7;\n\t\u03c9_range = 0.1:0.2:1;\n\t\u03c91_range = 0.1:0.3:2; \nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 944d3e05-1ddc-422c-9207-a819f5341254\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nfunction gauss_\u03c9(A,b,x0,\u03c9)\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] = (\u03c9/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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3d9f8d64-c18f-40e4-8510-be3619caa190\n# Weighted Jacobi and Gauss Methods \nbegin\n\ty_j,RES_ja = jacobi_\u03c9(A,b,IC,\u03c9);\n\tplot(domain,RES_ja,xaxis=:log,label=\"Weighted Jacobi\");\n\ty_gr,RES_ga = gauss_\u03c9(A,b,IC,\u03c91);\n\tplot!(domain,RES_ga,xaxis=:log,label=\"Weighted Gauss\");\nend\n\n# \u2554\u2550\u2561 2e83adfa-c254-4a4f-9681-c140ed64b0dd\nbegin\n\ty_,R = jacobi_\u03c9(A,b,IC,\u03c9_range[1]);\n\tp1 = plot!(domain,R,xaxis=:log);\nend\n\n# \u2554\u2550\u2561 7c9839b6-171d-4039-b5cb-7cf2a8278fac\nbegin\n\ty_1,R1 = gauss_\u03c9(A,b,IC,\u03c9_range[5]);\n\tp2 = plot!(domain,R1,xaxis=:log);\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u255051ab86a0-af67-11eb-2542-018f2a541d80\n# \u2560\u255013dac5b4-d8bb-4668-9aa8-1d2a5ce6b59d\n# \u2560\u2550de0276af-306d-4758-96b0-d76e024a5291\n# \u2560\u2550ae0165b3-6a37-4da5-bb07-22c3cce19a7b\n# \u2560\u2550acb70cc7-8a6c-4eb2-8451-c3637a36b129\n# \u2560\u2550b17e0683-c34c-43e7-9170-cd8a5a293a17\n# \u2560\u2550944d3e05-1ddc-422c-9207-a819f5341254\n# \u2560\u2550b38689ac-e045-4ae6-845f-e11a8a902a39\n# \u2560\u2550827ecd18-8b80-4fe6-b6e1-ed19fcb071cc\n# \u2560\u25504240bfe8-eaef-454a-8113-68572ef822f2\n# \u2560\u25503d9f8d64-c18f-40e4-8510-be3619caa190\n# \u2560\u25502e83adfa-c254-4a4f-9681-c140ed64b0dd\n# \u2560\u25507c9839b6-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__) \u2209 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    \u025b::T\n    K::AbstractMatrix{T}\n    proj::Projection{T}\n\n    DiffMap{T}(t::Int, \u025b::T, K::AbstractMatrix{T}, proj::Projection{T})  where T = new(t, \u025b, 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), \u025b = $(R.\u025b))\")\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, \u025b::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, \u025b))\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, \u025b), 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 \u0394HA 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    \u0394HA::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 \u0394HA/\u0394HD/\u0394SV 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    \u0394HA::FT\n    \"Deactivation energy\"\n    \u0394HD::FT\n    \"Entropy factor\"\n    \u0394SV::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\u2010limited 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\u2013C4 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\u0393StarTDBernacchi(FT)       = Arrhenius{FT}(T_25(), 4.33164375, 37830.0);\n\u0393StarTDCLM(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\u0397CTDJohnson(FT)                    = ArrheniusPeak{FT}(T_25(), 1.0 , 0.0    , 220000.0, 710.0 );\n\u0397LTDJohnson(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    \u03bc1 = 1/(scv_desired+1) #mean parameter \n    p = (scv_desired-1)/(scv_desired+1+2/(\u03bc1^2)-4/\u03bc1)\n    \u03bc2 = (1-p)/(1-p/\u03bc1) #mean parameter\n    \u03b1 = zeros(2)'\n    \u03b1[1] = p\n    \u03b1[2] = 1-p\n\n    T = zeros(2,2)\n    T[1,1] = -1/\u03bc1\n    T[2,2] = -1/\u03bc2\n    return PHDist(\u03b1, (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 \u2265 1.0 && error(\"SCV must be less than 1\")\n\n    n = Int(ceil(1/scv))\n\n    \u03bd1 = n/(1+sqrt((n-1)*(n*scv-1)))\n    # \u03bd2 = \u03bd1*(n-1)/(\u03bd1-1)\n    \u03bd2 = -(n-1)/(1-\u03bd1)\n\n    \u03b1 = zeros(n)'\n    \u03b1[1] = 1\n    T = zeros(n,n)\n    T[1,1] = -\u03bd1\n    T[1,2] = \u03bd1\n\n    for i = 2:(n-1)\n        T[i,i] = -\u03bd2\n        T[i,i+1] = \u03bd2\n    end\n\n    T[n,n] = -\u03bd2\n\n    return PHDist(\u03b1, (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 \u22c5 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 \u22c5 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# \u2554\u2550\u2561 d3435ffa-6910-11eb-1169-5f99095f1fdf\nbegin\n\tusing PlutoUI\n\tusing Test\n\tusing Printf\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 b8800646-8364-4cd9-8ab5-c010c666fb65\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# \u2554\u2550\u2561 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 \u2264 minute < 60, \"Minute is not between 0 and 60.\")\n        @assert(0 \u2264 second < 60, \"Second is not between 0 and 60.\")\n\t\t\n        new(hour, minute, second)\n    end\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d522cea2-6911-11eb-026f-4be6aec6f3de\nt\u2081 = YaTime(19, 58, 24)\n\n# \u2554\u2550\u2561 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\u2019t use an if statement.*\n\"\"\"\n\n# \u2554\u2550\u2561 37c16a0c-6912-11eb-07c3-733e4066b898\nis_after(t\u2081::YaTime, t\u2082::YaTime) = t\u2081.hour > t\u2082.hour || t\u2081.minute > t\u2082.minute || t\u2081.second > t\u2082.second\n\n# \u2554\u2550\u2561 91dcec8c-6912-11eb-1c04-f781c60db1ae\nbegin\n\tt\u2093, t\u209c = (YaTime(11, 11, 54), YaTime(10, 11, 54)) \n\t@test is_after(t\u2093, t\u209c)\n\t\n\t(t\u2083, t\u2084) = (YaTime(11, 11, 56), YaTime(11, 11, 55)) \n\t@test is_after(t\u2083, t\u2084)\n\t\n\tt\u2085 = YaTime(11, 10, 54) \n\t@test is_after(t\u2083, t\u2085)\n\t\n\tt\u2086= YaTime(12, 11, 54)\n\t@test !is_after(t\u2093, t\u2086)    ## negation\nend\n\n# \u2554\u2550\u2561 a64a66e4-6913-11eb-29cb-85ce1f785caa\nmd\"\"\"\n#### Pure Function\n\"\"\"\n\n# \u2554\u2550\u2561 50166aec-6914-11eb-2bda-cde28024c50f\nbegin\n\nimport Base: +, ==, isless\n\nfunction +(t\u2081::YaTime, t\u2082::YaTime)::YaTime\n    \"\"\"\n    Creates a new YaTime Struct, initializes its fields, and returns a reference to it\n    \"\"\"\n    sec  = t\u2081.second + t\u2082.second\n    min  = t\u2081.minute + t\u2082.minute\n    hour = t\u2081.hour + t\u2082.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\u2081::YaTime, t\u2082::YaTime)::Bool\n\tt\u2081.hour == t\u2082.hour && t\u2081.minute == t\u2082.minute && t\u2081.second == t\u2082.second\nend\n\t\nfunction isless(t\u2081::YaTime, t\u2082::YaTime)::Bool\n    (t\u2081.hour, t\u2081.minute, t\u2081.second) < (t\u2082.hour, t\u2082.minute, t\u2082.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\u2081::Integer, u\u2082::Integer, mod::Integer=60)\n    if u\u2081 > mod\n        u\u2081 -= 60\n        u\u2082 += 1\n    end\n    (u\u2081, u\u2082)\nend\n\t\nend\n\n# \u2554\u2550\u2561 eff6c928-6917-11eb-2720-918204039f0e\nwith_terminal() do\n\tprintln(methods(+))\nend\n\n# \u2554\u2550\u2561 de8be752-6914-11eb-2061-21ec29439e96\nbegin\n\t(t\u2090, t\u2092) = (YaTime(12, 11, 54), YaTime(11, 11, 54)) \n\tnt = t\u2090 + t\u2092\nend\n\n# \u2554\u2550\u2561 1ced8ab4-6915-11eb-1de5-3de099efa35c\n@test YaTime(10, 30, 54) + YaTime(9, 11, 44) == YaTime(19, 42, 38)\n\n# \u2554\u2550\u2561 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 \u2014 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# \u2554\u2550\u2561 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\u2082 = YaTime(24, 0, 0)\n\t@test time_to_int(nts\u2082) == 86_400 # \"24h is 86400s\"\n\t\n\tnts\u2083 = YaTime(24, 0, 0) + 11\n\t@test time_to_int(nts\u2083) == 86_411 # \"24h and 11s is 86411s\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250057e617da-6910-11eb-0e3f-33b08ab72b7a\n# \u2560\u2550d3435ffa-6910-11eb-1169-5f99095f1fdf\n# \u255f\u2500b8800646-8364-4cd9-8ab5-c010c666fb65\n# \u2560\u25507d6fa0de-6910-11eb-00df-39e0c9733dd2\n# \u255f\u2500a5a13cf2-6910-11eb-1db3-392525cb52dc\n# \u2560\u2550b5c2de12-6910-11eb-3ade-73ae4245aaf9\n# \u255f\u25000e1ecf32-6912-11eb-3eff-4bbfc6d00980\n# \u2560\u2550030e96a8-6911-11eb-3c5f-b103f63ecb8f\n# \u2560\u25505777439a-6911-11eb-3cd0-cdd3a66c15a6\n# \u2560\u25506f3db41e-6911-11eb-016d-11a7e82f072d\n# \u2560\u2550d522cea2-6911-11eb-026f-4be6aec6f3de\n# \u255f\u250022d86fa0-6912-11eb-13f6-1125998a1df7\n# \u2560\u255037c16a0c-6912-11eb-07c3-733e4066b898\n# \u2560\u255091dcec8c-6912-11eb-1c04-f781c60db1ae\n# \u255f\u2500a64a66e4-6913-11eb-29cb-85ce1f785caa\n# \u2560\u255050166aec-6914-11eb-2bda-cde28024c50f\n# \u2560\u2550eff6c928-6917-11eb-2720-918204039f0e\n# \u2560\u2550de8be752-6914-11eb-2061-21ec29439e96\n# \u2560\u25501ced8ab4-6915-11eb-1de5-3de099efa35c\n# \u255f\u2500e4bc1df8-6915-11eb-130f-e1b1bdd1e940\n# \u2560\u25506526d230-6916-11eb-07f2-63fe39f294c7\n# \u255f\u2500d2836738-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": "@testset \"set length and range\" begin\n    ks = 1:10\n    rs = set_range.(Chebyshev(), ks)\n    @test rs[1:4] == [1:1, 2:3, 4:5, 6:9]\n    @test all(@. last(rs[1:(end - 1)]) + 1 == first(rs[2:end])) # contiguous\n    @test length.(rs) == set_length.(Chebyshev(), ks)           # consistent with length\nend\n\n@testset \"gridpoint sets\" begin\n    @test gridpoint_set(Chebyshev(), 1) == [0]\n    @test gridpoint_set(Chebyshev(), 2) == [-1, 1]\n    @test gridpoint_set(Chebyshev(), 3) \u2248 [-\u221a2, \u221a2]./2\n    @test issorted(gridpoint_set(Chebyshev(), 4))\n    x = sort(mapreduce(k -> gridpoint_set(Chebyshev(), k), vcat, 1:5))\n    @test allunique(x)\n    @test length(x) == 2^4 + 1\n    @test x \u2248 cospi.((16:-1:0) ./ 16)\nend\n\n@testset \"Chebyshev polynomials\" begin\n    J = 19\n    x = rand(J) .* 2 .- 1\n    N = 7\n    Z = @inferred evaluate(N, Chebyshev(), x)\n    @test size(Z) == (J, N)\n    @test Z \u2248 ((t, n) -> cos(n * t)).(acos.(x), (0:(N-1))')\n    @test @inferred(evaluate(N, Chebyshev(), first(x))) == Z[1, :]\n\n    @test size(evaluate(0, Chebyshev(), x)) == (J, 0)\n    @test evaluate(1, Chebyshev(), x) == ones(J, 1)\n    @test evaluate(2, Chebyshev(), x) == hcat(ones(J, 1), x)\nend\n", "meta": {"hexsha": "bf2a74eb15b417f86bd390509f2d96e576b5b970", "size": 1164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_chebyshev.jl", "max_stars_repo_name": "JuliaTagBot/SmolyakInterpolation.jl", "max_stars_repo_head_hexsha": "75acc9140411c6c98d117afb98ea3a1071defa10", "max_stars_repo_licenses": ["MIT"], "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_chebyshev.jl", "max_issues_repo_name": "JuliaTagBot/SmolyakInterpolation.jl", "max_issues_repo_head_hexsha": "75acc9140411c6c98d117afb98ea3a1071defa10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-11-15T09:35:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:08:56.000Z", "max_forks_repo_path": "test/test_chebyshev.jl", "max_forks_repo_name": "JuliaTagBot/SmolyakInterpolation.jl", "max_forks_repo_head_hexsha": "75acc9140411c6c98d117afb98ea3a1071defa10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:49:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:49:05.000Z", "avg_line_length": 35.2727272727, "max_line_length": 88, "alphanum_fraction": 0.5524054983, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7543217450245843}}
{"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\u03b3 = 2 # CRRA utility\nr = 0.035 #return on asset\n\u03b1 = 1/3 # parameter for cobb-douglas production function\n\u03b7 = 0.2 # for our benefit function\np = 1 #price\n\u03d5 = 2 # coefficient of a in the budget constraint\nhmin = 2.3 #lower threshold for houses\n\u03b4 = 0.05 # captal depreciation\n\u03c1 = 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\u03bb_1 = .5 # prob of transitioning from state 1 to 2\n\u03bb_2 = .5  # state 2 to 1\n\u03bb = [\u03bb_1 \u03bb_2]\nz_ave = (z_1*\u03bb_2 + z_2*\u03bb_1)/(\u03bb_1 + \u03bb_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)*\u03bb[1] sparse(I,H,H)*\u03bb[2] ; sparse(I,H,H)*\u03bb[1] -sparse(I,H,H)*\u03bb[2]]\n\n# Paramters for the simulation\nmaxit = 120\ncrit = 10^(-10)\n\u0394 = 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.((\u03b1*\u03b7/(r*p))^(1/(1-\u03b1)) + hmin, \u03d5*aa/p)\nh = h.*(h.>=hmin)\nf = \u03b7*(max.(h.-hmin,0)).^\u03b1 - r*p*h\n\nv0 = (zz + r*aa).^(1-\u03b3)/(1-\u03b3)/\u03c1\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).^(-\u03b3)\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).^(-\u03b3)\n\n\t# caculate consumption and savings\n\t# First the forward difference case\n\tcf = (max.(Vaf,10^(-10))).^(-1/\u03b3)\n\tssf = zz + f + r.*aa -cf\n\tHf = cf.^(1-\u03b3)/(1/\u03b3) + Vaf.*ssf\n\n\t# consumption and savings for the backward difference\n\tcb = (max.(Vab,10^(-10))).^(-1/\u03b3)\n\tssb = zz + f + r.*aa -cb\n\tHb = cb.^(1-\u03b3)/(1-\u03b3) + Vab.*ssb\n\n\t#Consumption and V' at the steady state\n\tc0 = zz + f + r.*aa\n\tVa0 = c0.^(-\u03b3)\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 \u2192 forward difference\n    Ib = Iunique.*(ssb .< 0) + Iboth.*(Hb.>=Hf) #negative drift \u2192 backward difference\n    I0 = Ieither  #at steady state\n\n\tglobal c = cf.*If + cb.*Ib + c0.*I0\n    u = (c.^(1-\u03b3))/(1-\u03b3)\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/\u0394 + \u03c1)*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/\u0394\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/\u03d5\n\nobj, index = findmin(abs.(astar.-a))\n\nc2 = c - \u03b7*max.(h.-hmin,0).^\u03b1\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\u03bc = 25.0\n## potential\nimport FourierGPE.V\nV(x,t) = 0.5*x^2\n\n## TF state\n\u03c80(x,\u03bc,g) = sqrt(\u03bc/g)*sqrt(max(1.0-V(x,0.0)/\u03bc,0.0)+im*0.0)\n\n## initial state\nx = X[1]\n\u03c8i = \u03c80.(x,\u03bc,g)\n\u03d5i = kspace(\u03c8i,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\u03d5g = sol[end]\n\u03c8g = xspace(\u03d5g,sim)\nplot(x,one.(x)*\u03bc,ls=:solid,c=:gray,w=1)\nplot!(x,V.(x,0.0),c=:red,w=4,alpha=0.4)\nplot!(x,g*abs2.(\u03c8g),c=c3,w=2,fill=(0,0.4,c3),size=(600,200))\nxlims!(-10,10); ylims!(0,1.3*\u03bc)\ntitle!(L\"\\textrm{local}\\; \\mu(x)\")\nxlabel!(L\"x/a_x\"); ylabel!(L\"\\mu(x)/\\hbar\\omega_x\")\n\n## imprint dark soliton\n\u03c8f = xspace(sol[end],sim)\nc = sqrt(\u03bc)\n\u03be = 1/c\nv = 0.5*c\nxs = 0.\nf = sqrt(1-(v/c)^2)\n\n\u03c8s = \u03c8f.*(f*tanh.(f*(x .-xs)/\u03be).+im*v/c);\nshowpsi(x,\u03c8s)\nxlims!(-10,10)\n\n## set simulation parameters\n\u03b3 = 0.0\ntf = 8*pi/sqrt(2); t = LinRange(ti,tf,Nt)\n\n# define new simulation using previous parameters\nsimSoliton = Sim(sim;\u03b3=\u03b3,tf=tf,t=t)\n\u03d5i = kspace(\u03c8s,simSoliton)\n@pack! simSoliton = \u03d5i\n\n## evolve in k space\nsols = runsim(simSoliton)\n\n## plot\n\n\u03d5f = sols[end-3]\n\u03c8f = xspace(\u03d5f,simSoliton)\nshowpsi(x,\u03c8f)\n\nanim = @animate for i in 1:length(t)-3\n    \u03c8 = xspace(sols[i],simSoliton)\n    y = g*abs2.(\u03c8)\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*\u03bc)\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": "const zangwill = let res_init=zeros(3), jac_init=zeros(3,3), x_init=[100., -1., 2.5]\n\n    function res(x, r)\n        r[1] = x[1] - x[2] + x[3]\n        r[2] = -x[1] + x[2] + x[3]\n        r[3] = x[1] + x[2] - x[3]\n        return r\n    end\n\n    function jac(x, jac)\n        jac[:] .= 0.0\n        for k = 1:3, i = 1:3\n            jac[i, k] = 1.0\n        end\n        jac[1, 2] = -1.0\n        jac[2, 1] = -1.0\n        jac[3, 3] = -1.0\n        return jac\n    end\n\n    f(;scale=1, verbose=false, print_steps=false) = testone(\"zangwill\", res, jac,\n                                                   res_init, jac_init, x_init;\n                                                   scale=scale, verbose=verbose,\n                                                   print_steps=print_steps)\nend\n", "meta": {"hexsha": "e0630b51ba6fd334f7065c97dbaffc13ee024ca9", "size": 779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/zangwill.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/zangwill.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/zangwill.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.9615384615, "max_line_length": 84, "alphanum_fraction": 0.3889602054, "num_tokens": 258, "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((\u03b2 = as(Array, size(model.x, 2)), \u03c3 = as\u211d\u208a))\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)(\u03b8)\n    @unpack y, x = problem   # extract the data\n    @unpack \u03b2, \u03c3 = \u03b8            # 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), \u03c3)\n    ll += loglikelihood(Normal(0, \u03c3), y .- x*\u03b2)\n    ll\nend\n\nprintln()\nmodel((\u03b2 = [1.0, 2.0, 1.0, 2.0], \u03c3 = 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\u2207P = ADgradient(:ForwardDiff, P);\n\n# Tune and sample.\n\nresults = mcmc_with_warmup(Random.GLOBAL_RNG, \u2207P, 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": "module TestFinCats\nusing Test\n\nusing Catlab, Catlab.Theories, Catlab.CategoricalAlgebra, Catlab.Graphs\nusing Catlab.Graphs.BasicGraphs: TheoryGraph, TheoryReflexiveGraph\n\n# Discrete categories\n#####################\n\nC = FinCat(FinSet(3))\n@test C isa FinCat{Int,Int}\n@test collect(ob_generators(C)) == 1:3\n@test isempty(hom_generators(C))\n@test (dom(C, 1), codom(C, 1)) == (1, 1)\n@test (id(C, 2), compose(C, 2, 2)) == (2, 2)\n\n# Categories on graphs\n######################\n\n# Free categories\n#----------------\n\ng = parallel_arrows(Graph, 3)\nC = FinCat(g)\n@test graph(C) == g\n@test Ob(C) == FinSet(2)\n@test is_free(C)\n@test hom(C, 1) == Path(g, 1)\n@test ob_generators(C) == 1:2\n@test hom_generators(C) == 1:3\n\nh = Graph(4)\nadd_edges!(h, [1,1,2,3], [2,3,4,4])\nD = FinCat(h)\nf = id(D, 2)\n@test (src(f), tgt(f)) == (2, 2)\n@test isempty(edges(f))\nf = compose(D, 1, 3)\n@test edges(f) == [1,3]\n\n# Functors between free categories.\nC = FinCat(parallel_arrows(Graph, 2))\nF = FinFunctor((V=[1,4], E=[[1,3], [2,4]]), C, D)\n@test dom(F) == C\n@test codom(F) == D\n@test is_functorial(F)\n@test Ob(F) == FinFunction([1,4], FinSet(4))\n\n@test ob_map(F, 2) == 4\n@test hom_map(F, 1) == Path(h, [1,3])\n@test collect_ob(F) == [1,4]\n@test collect_hom(F) == [Path(h, [1,3]), Path(h, [2,4])]\n\n# Composition of functors.\ng, h, k = path_graph(Graph, 2), path_graph(Graph, 3), path_graph(Graph, 5)\nC, D, E = FinCat(g), FinCat(h), FinCat(k)\nF = FinFunctor([1,3], [[1,2]], C, D)\nG = FinFunctor([1,3,5], [[1,2],[3,4]], D, E)\n@test is_functorial(G)\n@test hom_map(G, Path(h, [1,2])) == Path(k, [1,2,3,4])\n@test F\u22c5G == FinFunctor([1,5], [[1,2,3,4]], C, E)\n@test id(C)\u22c5F == F\n@test F\u22c5id(D) == F\n\n# Free diagrams\n#--------------\n\nC = FinCat(parallel_arrows(Graph, 2))\nf, g = FinFunction([1,3], 3), FinFunction([2,3], 3)\nF = FinDomFunctor([FinSet(2), FinSet(3)], [f,g], C)\n@test is_functorial(F)\n@test dom(F) == C\n@test codom(F) isa TypeCat{<:FinSet{Int},<:FinFunction{Int}}\n@test ob_map(F, 1) == FinSet(2)\n@test hom_map(F, 2) == g\n\n# `FreeDiagrams` interop.\ndiagram = FreeDiagram(ParallelPair(f, g))\n@test FreeDiagram(F) == diagram\n@test FinDomFunctor(diagram) == F\n\n# Diagram interface.\n@test diagram_type(F) <: Tuple{FinSet{Int},FinFunction{Int}}\n@test cone_objects(F) == [FinSet(2), FinSet(3)]\n@test cocone_objects(F) == [FinSet(2), FinSet(3)]\n@test ob(limit(F)) == FinSet(1)\n@test ob(colimit(F)) == FinSet(2)\n\n# Commutative square as natural transformation.\nC = FinCat(path_graph(Graph, 2))\nF = FinDomFunctor([FinSet(4), FinSet(2)], [FinFunction([1,1,2,2])], C)\n\u03b1\u2080, \u03b1\u2081 = FinFunction([3,4,1,2]), FinFunction([2,1])\n\u03b1 = FinTransformation([\u03b1\u2080, \u03b1\u2081], F, F)\n@test is_natural(\u03b1)\n@test (\u03b1[1], \u03b1[2]) == (\u03b1\u2080, \u03b1\u2081)\n@test components(\u03b1) == [\u03b1\u2080, \u03b1\u2081]\n@test \u03b1\u22c5\u03b1 == FinTransformation([FinFunction(1:4), FinFunction(1:2)], F, F)\n\n# Path equations\n#---------------\n\n# Simplex category truncated to one dimension.\n\u0394\u00b9_graph = Graph(2)\nadd_edges!(\u0394\u00b9_graph, [1,1,2], [2,2,1])\n\u0394\u00b9 = FinCat(\u0394\u00b9_graph, [ [1,3] => empty(Path, \u0394\u00b9_graph, 1),\n                        [2,3] => empty(Path, \u0394\u00b9_graph, 1) ])\n@test graph(\u0394\u00b9) == \u0394\u00b9_graph\n@test length(equations(\u0394\u00b9)) == 2\n@test !is_free(\u0394\u00b9)\n\n# Symbolic categories\n#####################\n\n@present Simplex1D(FreeCategory) begin\n  (V, E)::Ob\n  (\u03b4\u2080, \u03b4\u2081)::Hom(V, E)\n  \u03c3\u2080::Hom(E, V)\n\n  \u03b4\u2080 \u22c5 \u03c3\u2080 == id(V)\n  \u03b4\u2081 \u22c5 \u03c3\u2080 == id(V)\nend\n\n\u0394\u00b9 = FinCat(Simplex1D)\n@test \u0394\u00b9 isa FinCat{FreeCategory.Ob,FreeCategory.Hom}\n@test ob(\u0394\u00b9, :V) isa FreeCategory.Ob\n@test hom(\u0394\u00b9, :\u03b4\u2080) isa FreeCategory.Hom\n@test first.(ob_generators(\u0394\u00b9)) == [:V, :E]\n@test first.(hom_generators(\u0394\u00b9)) == [:\u03b4\u2080, :\u03b4\u2081, :\u03c3\u2080]\n@test length(equations(\u0394\u00b9)) == 2\n@test !is_free(\u0394\u00b9)\n\n# Graph as set-valued functor on a free category.\nF = FinDomFunctor(TheoryGraph, path_graph(Graph, 3))\nC = dom(F)\n@test is_functorial(F)\n@test ob_map(F, :V) == FinSet(3)\n@test hom_map(F, :src) == FinFunction([1,2], 3)\n@test F(ob(C, :E)) == FinSet(2)\n@test F(hom(C, :tgt)) == FinFunction([2,3], 3)\n@test F(id(ob(C, :E))) == id(FinSet(2))\n\n# Reflexive graph as set-valued functor on a category with equations.\nG = FinDomFunctor(TheoryReflexiveGraph, path_graph(ReflexiveGraph, 3))\n@test is_functorial(G)\n\n# Graph homomorphisms as natural transformations.\ng = parallel_arrows(Graph, 2)\nadd_edges!(g, [2,2], [2,2])\nG = FinDomFunctor(TheoryGraph, g)\n\u03b1 = FinTransformation(F, G, V=FinFunction([1,2,2]), E=FinFunction([1,3],4))\n@test dom_ob(\u03b1) == C\n@test codom_ob(\u03b1) isa TypeCat{<:FinSet{Int},<:FinFunction{Int}}\n@test is_natural(\u03b1)\n@test \u03b1[:V](3) == 2\n\u03c3 = FinTransformation(G, G, V=id(FinSet(2)), E=FinFunction([2,1,4,3]))\n@test \u03c3\u22c5\u03c3 == FinTransformation(G, G, V=id(FinSet(2)), E=FinFunction(1:4))\n@test \u03b1\u22c5\u03c3 == FinTransformation(F, G, V=FinFunction([1,2,2]), E=FinFunction([2,4]))\n\n# Pullback data migration by pre-whiskering.\n\u03b9V = FinFunctor([:V], [], FinCat(1), FinCat(TheoryGraph))\n\u03b1V = \u03b9V * \u03b1\n@test ob_map(dom(\u03b1V), 1) == ob_map(F, :V)\n@test ob_map(codom(\u03b1V), 1) == ob_map(G, :V)\n@test component(\u03b1V, 1) == component(\u03b1, :V)\n\n# Post-whiskering and horizontal composition.\n\u03b9E = FinFunctor([:E], [], FinCat(1), FinCat(TheoryGraph))\n\u03d5 = FinTransformation([:src], \u03b9E, \u03b9V)\n@test is_natural(\u03d5)\n@test component(\u03d5*F, 1) == hom_map(F, :src)\n@test component(\u03d5*\u03b1, 1) == hom_map(F, :src) \u22c5 \u03b1[:V]\n\nend\n", "meta": {"hexsha": "f7eb768caf85e39b39b48d7c1c8d6ca43d91e7ea", "size": 5184, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/categorical_algebra/FinCats.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": "test/categorical_algebra/FinCats.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": "test/categorical_algebra/FinCats.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": 29.7931034483, "max_line_length": 82, "alphanum_fraction": 0.6288580247, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7543217371506551}}
{"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 \u03c3 = 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 \u2248 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 \u2264 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, \u2294\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.\u0394\n    nS = length(S)\n    nT = length(T)\n    \u03d5 = 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            \u03d5[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] -= \u03d5[i]\n            end\n            for s in out\n                # TODO: accomodate multiplicites here\n                du[s] += \u03d5[i]\n            end\n        end\n        return du\n    end\n    return f\nend\n\nu\u2080(m::Petri.Model) = begin\n    zeros(Float64, length(m.S))\nend\n\nu\u2080(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\u03b2 = [10/sum(u0), 1/5]\n\ntspan = (0,100.0)\nprob = ODEProblem(fluxes(m), u0, tspan, \u03b2)\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\u03b2 = [10/sum(u0), 1/5, 1/10]\n\ntspan = (0,100.0)\nprob = ODEProblem(fluxes(m), u0, tspan, \u03b2)\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\u03b2 = [10/sum(u0), 1/2, 1/5]\n\ntspan = (0,100.0)\nprob = ODEProblem(fluxes(m), u0, tspan, \u03b2)\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    \u03b2seird = [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": "include(\"lasso.jl\")\ninclude(\"utils.jl\")\n\nusing Test\nusing UnicodePlots\nusing Plots\n\nTest1Results = 0\n\nfunction Test1()\n    \"\"\"\n        Test 1, some basic test on a random matrix, copied columns of matrix. \n    \"\"\"\n    deg = 3\n    N = 2000\n    B = rand(N, deg)\n    A = fill(0.0, (N, 2deg))\n    A[:, 1:deg] = B\n    A[:, deg + 1:end] = 2B.^2 + B + 0.1.*randn(size(B))\n\n    b = A*ones(2deg, 1)\n    instance = LassoSCOP(A, b)\n    results, \u03bbs = LassoPath(instance)\n    display(results)\n    display(\u03bbs)\n    \n    # Let's plot this\n    global Test1Results = results\n\n    ylim = (minimum(Test1Results), maximum(Test1Results))\n    ThePlot = lineplot(log2.(\u03bbs), Test1Results[1, :], ylim=ylim, title=\"Lasso Path\")\n\n    for II \u2208 2:size(Test1Results, 1)\n        lineplot!(ThePlot, log2.(\u03bbs), Test1Results[II, :])\n    end\n    display(ThePlot)\n    ThePlot = UnicodePlots.heatmap(results[end:-1:begin, :])\n    display(ThePlot)\n\n    # Visualize the path. \n    VisualizeLassoPath(instance)\n\n    # Finding the important weights for it. \n    PrintTitle(\"These are the important weights: \")\n    WeightsIndices = CaptureImportantWeights(instance)\n    println(WeightsIndices)\n    return true\n\nend\n\n@test Test1()\n\n\nfunction Test2()\n    N = 10\n    deg = 10\n    xgrid = collect(LinRange(-2\u03c0, 2\u03c0, N))\n    f(x) = sin.(x)\n    y = f(xgrid) + 0.1.*rand(N)\n    V = VanderMonde(reshape(xgrid, (N, 1)), deg)\n    instance = LassoSCOP(V, reshape(y, (N, 1)))\n    results, \u03bbs = LassoPath(instance)\n    \u03bbs = log2.(\u03bbs)\n    display(results)\n\n    ylim = (minimum(results), maximum(results))\n    ThePlot = lineplot(\u03bbs, results[1, :], ylim=ylim)\n    for II \u2208 2:size(results, 1)\n        lineplot!(ThePlot, \u03bbs ,results[II, :])\n    end\n    display(ThePlot)\n\n    YHat = V*results[:, end]\n    ThePlot = lineplot(xgrid, y)\n    scatterplot!(ThePlot, xgrid, YHat)\n    display(ThePlot)\n    display(UnicodePlots.heatmap(results[end:-1:begin, :]))\n    \n    return true\nend\n\n@test Test2()", "meta": {"hexsha": "aa6b5212dd403d3c51fc067355ca7d15eccd848c", "size": 1930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "prototype/lasso_test.jl", "max_stars_repo_name": "iluvjava/LassoPath.jl", "max_stars_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/lasso_test.jl", "max_issues_repo_name": "iluvjava/LassoPath.jl", "max_issues_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/lasso_test.jl", "max_forks_repo_name": "iluvjava/LassoPath.jl", "max_forks_repo_head_hexsha": "55dd61f28a8b58d698d6642d00f88fb5fea6e562", "max_forks_repo_licenses": ["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.5365853659, "max_line_length": 84, "alphanum_fraction": 0.6139896373, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8267117855317473, "lm_q1q2_score": 0.7543217254431418}}
{"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 \u2208 [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# \u2554\u2550\u2561 889697ff-7f5a-4106-95f7-ca7a294faeb3\nbegin\n\tusing JSServe\n\tPage()\nend\n\n# \u2554\u2550\u2561 6946373c-8035-485b-9048-7b4d0fc6428f\nusing WGLMakie, Distributions, LinearAlgebra\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 592cb2f4-7c38-4ecd-b0fc-50d9e409f928\n# Landmark position\ns = [0.0;0.0]\n\n# \u2554\u2550\u2561 3f91f4e8-e0c9-4f1f-a5a0-7cdfc8bb9d6b\n# Covariance matrix\nQ = [1.0 0.0;\n\t0.0 1.0]\n\n# \u2554\u2550\u2561 4c06bac4-05b8-4883-b3ca-3da505783fdc\n# Distribution of observations\nd = MvNormal(s,Q)\n\n# \u2554\u2550\u2561 54ec7d97-477e-4887-a73a-502eeba97910\n# Number of observations\nN = 10\n\n# \u2554\u2550\u2561 7c36f709-7bb0-4986-8337-e6dea6fc7690\n# Observation data set\nZ = rand(d,N)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e4b53a36-860b-4c3a-b9c9-6f6eafcaeeb9\n# Compute the maximum likelihood estimator\ns\u0302 = mean(Z,dims=2)[:,1]\n\n# \u2554\u2550\u2561 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\u0302],color=:orange)\n\tfig2\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u0302 = mean(Z,dims=2)[:,1]\n    \n    # Return the distance between s and s\u0302\n    sqrt(sum(abs2,s .- s\u0302))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f4751245-b653-45fb-8950-0043fdc20018\nbegin\n\t\u03bc\u2080 = [0.0;0.0]\n\t\u03a3\u2080 = [100.0 0.0;0.0 100.0]\n\tp\u2080 = MvNormal(\u03bc\u2080,\u03a3\u2080)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8a174193-2916-4a01-a2c9-8663e7f4aca2\nfunction update(p\u2080,z,Q)\n\t\u03bc\u2080,\u03a3\u2080 = p\u2080.\u03bc,p\u2080.\u03a3\n    \u03a3\u2081 = inv(inv(Q) + inv(\u03a3\u2080))\n    \u03bc\u2081 = \u03a3\u2081 * (Q\\z + \u03a3\u2080\\\u03bc\u2080)\n    MvNormal(\u03bc\u2081,\u03a3\u2081)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 329dae9e-a9b4-4608-bc6e-88953679ea1a\nQi = inv(Q)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 bd6bbe7d-5e46-4bab-8d75-6439614a747d\nbegin\n\t\u039b\u2080 = inv(\u03a3\u2080)\n\tj\u2080 = \u03a3\u2080\\\u03bc\u2080\n\tq\u2080 = MvNormalCanon(j\u2080,\u039b\u2080)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 68107d23-f41e-46cc-b6ac-b3195651c35b\nfunction update(q\u2080::D,z,Qi) where {D <: MvNormalCanon}\n\tj\u2080,\u039b\u2080 = q\u2080.h,q\u2080.J\n\t\n\tj\u2081 = j\u2080 + Qi*z\n\t\u039b\u2081 = \u039b\u2080 + Qi\n\tMvNormalCanon(j\u2081,\u039b\u2081)\nend\n\n# \u2554\u2550\u2561 55a37b10-7163-4887-942c-1b2d42b7330b\nbegin\n\tZs = Point2[Z[:,i] for i in 1:N]\n\tps = [p\u2080;accumulate((p,z) -> update(p,z,Q),Zs,init=p\u2080)]\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 5b07dc5d-6676-4d93-bb4a-7296beded4c3\nmd\"\"\"\nAnd apply our new parameterization to our data set.\n\"\"\"\n\n# \u2554\u2550\u2561 18cb7c76-5721-4023-b475-edaf410ea1da\nqs = [q\u2080;accumulate((q,z) -> update(q,z,Qi),Zs,init=q\u2080)]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550889697ff-7f5a-4106-95f7-ca7a294faeb3\n# \u2560\u25506946373c-8035-485b-9048-7b4d0fc6428f\n# \u255f\u2500cf1c3faa-1973-11ec-04bf-1f53406ce76b\n# \u2560\u2550592cb2f4-7c38-4ecd-b0fc-50d9e409f928\n# \u2560\u25503f91f4e8-e0c9-4f1f-a5a0-7cdfc8bb9d6b\n# \u2560\u25504c06bac4-05b8-4883-b3ca-3da505783fdc\n# \u2560\u255054ec7d97-477e-4887-a73a-502eeba97910\n# \u2560\u25507c36f709-7bb0-4986-8337-e6dea6fc7690\n# \u255f\u2500bc925405-7574-46d4-aa59-7e32bc1acaf7\n# \u255f\u250094c08534-71fd-4265-9212-edf76b4517bf\n# \u2560\u2550e4b53a36-860b-4c3a-b9c9-6f6eafcaeeb9\n# \u255f\u25008b342e24-759b-4ce4-9349-1c46aebe6cad\n# \u255f\u2500dbf4d333-b34a-40ce-b6cf-3a17a20cda8f\n# \u2560\u25506312899f-e92b-42d6-977a-fe8fe8b63011\n# \u2560\u255062c45184-2e26-4186-9f16-0b4d33944053\n# \u255f\u250020610ddc-5160-458d-badd-850046a087e2\n# \u255f\u250012a3d2e5-7f9f-4b8b-94d4-87911e8ad699\n# \u2560\u2550f4751245-b653-45fb-8950-0043fdc20018\n# \u255f\u2500de7b4d82-f035-4f26-989a-bbe0f5d6daa6\n# \u2560\u25508a174193-2916-4a01-a2c9-8663e7f4aca2\n# \u255f\u250090007f4c-1ded-4a08-afa7-a5c344b6c03b\n# \u2560\u255055a37b10-7163-4887-942c-1b2d42b7330b\n# \u255f\u25002985b01b-c602-4cb5-80b2-b39457f3686d\n# \u255f\u2500ab3b1a1b-8e74-47cf-9b95-df044e2fb86b\n# \u2560\u2550329dae9e-a9b4-4608-bc6e-88953679ea1a\n# \u255f\u2500b00453b8-beb5-4e5f-ac75-ec0d4acc8e72\n# \u2560\u2550bd6bbe7d-5e46-4bab-8d75-6439614a747d\n# \u255f\u2500cd9b1e2a-8049-4c44-8d52-c7dcd146708f\n# \u2560\u255068107d23-f41e-46cc-b6ac-b3195651c35b\n# \u255f\u25005b07dc5d-6676-4d93-bb4a-7296beded4c3\n# \u2560\u255018cb7c76-5721-4023-b475-edaf410ea1da\n# \u255f\u2500a098c5b0-6734-4bd2-90d7-5daf69cfd111\n# \u255f\u250051369139-452b-4fe9-a441-9f0f13713faf\n# \u255f\u2500b7c5a266-8264-4829-a040-7d11fe635b8a\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "import Base:show\nimport JGraph: Edge, EdgeIter\n\nabstract type AbstractGraph end\n\nmutable struct Graph{T <: Integer} <: AbstractGraph\n    ne::T\n    adjlist::Vector{Vector{T}}\n\n    function Graph()\n        new{Int64}(0, [])\n    end\nend\n\n\"\"\"\n    Graph(n, m)\n\ngenerate a graph with n vertices and m edges. Return a graph G.\n\"\"\"\nfunction Graph(n, m)\n    g = Graph();\n    add_vertex!(g, n);\n    num_vertice = 0\n\n    while num_vertice < m\n        s = rand(1:n)\n        t = rand(1:n)\n        if s != t && !has_edge(g, s, t)\n            add_edge!(g, s, t);\n            num_vertice += 1\n        end\n    end\n    return g\nend\n\nnv(G::AbstractGraph) = length(G.adjlist)\n\nne(G::AbstractGraph) = G.ne\n\n\"\"\"\n    has_edge(G::AbstractGraph, u::T, v::T)\n\nTest if egde(u,v) exist in the graph G.\n\"\"\"\nfunction has_edge(G::AbstractGraph, u::T, v::T) where T <: Integer\n    if max(u,v) > nv(G)\n        return false\n    elseif v in G.adjlist[u]\n        return true\n    else\n        return false\n    end\nend\n\nhas_edge(G::AbstractGraph, e::Edge) = has_edge(G, src(e), dst(e))\n\n\"\"\"\n    add_edge(G::AbstractGraph, u::T, v::T)\n\nAdd the egde(u,v) in the graph G. Return False is the edge already exit, true otherwise.\n\"\"\"\nfunction add_edge!(G::AbstractGraph, u::T, v::T) where T <: Integer\n    if has_edge(G, u, v)\n        return false\n    end\n    if nv(G) < max(u,v)\n        add_vertex!(G, max(u,v));\n    end\n    push!(G.adjlist[u], v);\n    push!(G.adjlist[v], u);\n    G.ne += 1;\n    return true\nend\n\nadd_edge!(G::AbstractGraph, e::Edge) = add_edge(G, src(e), dst(e))\n\n\"\"\"\n    add_edge(G::AbstractGraph, num_vertex)\n\nAdd \"num_vertex\" vertices to the graph G.\n\"\"\"\nfunction add_vertex!(G::AbstractGraph, num_vertex::T) where T <: Integer\n    while nv(G) < num_vertex\n        add_vertex!(G);\n    end\n    return true\nend\n\nfunction add_vertex!(G::AbstractGraph)\n    return push!(G.adjlist, Vector{Int}());\nend\n\nfunction remove_edge!(G::AbstractGraph, u, v)\n    if has_edge(G, u, v)\n        G.adjlist[u] = deleteat!(G.adjlist[u], findall(x-> x == v, G.adjlist[u]));\n        G.adjlist[v] = deleteat!(G.adjlist[v], findall(x-> x == u, G.adjlist[v]));\n        return true\n    else\n        return false\n    end\nend\n\nremove_edge!(G::AbstractGraph, e::Edge) = remove_edge!(G, src(e), dst(e))\n\nfunction remove_vertex!(G::AbstractGraph, s)\n    for t in neighbors(G, s)\n        remove_edge!(G, s, t)\n    end\n    return true\nend\n\n\"\"\"\n    degree(G::Graph)\n\nReturn the list of nodes degree.\n\"\"\"\nfunction degree(G::Graph)\n    degree_list = []\n    for u in G.adjlist\n        push!(degree_list, length(u))\n    end\n    degree_list\nend\n\n\"\"\"\n    neighbors(G::Graph, u)\n\nreturn the neighbors list adjacent to the node u\n\"\"\"\nfunction neighbors(G::Graph, u)\n    return copy(G.adjlist[u])\nend\n\n\"\"\"\n    vertices(G::Graph)\n\nvertices itertor\n\"\"\"\nvertices(G::Graph) = Base.OneTo(nv(G))\n\nedges(g::AbstractGraph) = EdgeIter(g)\n\n\"\"\"\n    fadj(G::Graph)\n\nreturn the adjacency list of the graph\n\"\"\"\nfadj(G::Graph) = G.adjlist\nfadj(G::Graph, v::Integer) = G.adjlist[v]\n\nshow(io::IO, G::Graph) = print(io, \"Undirected Graph G(V,E) with |V|=$(nv(G)), |E|=$(ne(G))\");\n", "meta": {"hexsha": "1afa31f9c25be5ca53b479b8c6e6b52ae2d39854", "size": 3095, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core.jl", "max_stars_repo_name": "vgauthier/JGraph.jl", "max_stars_repo_head_hexsha": "08e71070081da7f306b2ce35ca0b0ecae70cb0a3", "max_stars_repo_licenses": ["MIT"], "max_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": "vgauthier/JGraph.jl", "max_issues_repo_head_hexsha": "08e71070081da7f306b2ce35ca0b0ecae70cb0a3", "max_issues_repo_licenses": ["MIT"], "max_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": "vgauthier/JGraph.jl", "max_forks_repo_head_hexsha": "08e71070081da7f306b2ce35ca0b0ecae70cb0a3", "max_forks_repo_licenses": ["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.3618421053, "max_line_length": 94, "alphanum_fraction": 0.6025848142, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7543017386122992}}
{"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": "targetSystem = Sys.WORD_SIZE;\nprintln(\"Sys.WORD_SIZE indicates whether the target system is 32-bit or 64-bit. ['$targetSystem']\");\n\nintegerType = typeof(1);\nprintln(\"integerType is ['$integerType']\");\n\n#Unsigned integers are input and output using the 0x prefix and \n#hexadecimal (base 16) digits 0-9a-f (the capitalized digits A-F also work for input). \nunsignedValue = 0x1;\nunsignedValuesType = typeof(unsignedValue);\nprintln(\"unsignedValue(0x1) has value: ['$unsignedValue'] and is of type $unsignedValuesType\");\n\n#over-flow behavior\nmaxInt = typemax(Int64);\nprintln(\"Max integer value: [$maxInt]\");\n\noverflowResult = maxInt + 1; #overflow by 1\nprintln(\"Max integer after an overflow by 1: [$overflowResult]\");\n\nprintln(\"floating-point literals:\");\nprintln(\"------------------------\");\n\nvalue = 1.0;\nprintln(\"1.0 -> $value\");\n\nvalue = 1.;\nprintln(\"1. -> $value\");\n\nvalue = 0.5;\nprintln(\"0.5 -> $value\");\n\nvalue = .5;\nprintln(\".5 -> $value\");\n\nvalue = -1.23;\nprintln(\"-1.23 -> $value\");\n\nvalue = 1e10;\nprintln(\"1e10 -> $value\");\n\nvalue = 2.5e-4;\nprintln(\"2.5e-4 -> $value\");\n\nprintln(typeof(value));\n\nprintln();\nprintln(\"Hexadecimal floating-point literals, only have Float64 values, with p preceding the base-2 exponent\");\n\nhexValue = 0x1p0;\nprintln(\"0x1p0 -> $hexValue\");\n\nhexValue = 0x1.8p3;\nprintln(\"0x1.8p3 -> $hexValue\");\n\nhexValue = 0x.4p-1;\nprintln(\"0x.4p-1 -> $hexValue\");\n\nprintln();\nprintln(\"Underscores can be used as a digit seperator (10,000 would be 10_000)\");\nseperatedDigit = 10_000;\nprintln(\"10_0000 -> $seperatedDigit\");\n\nprintln();\nprintln(\"Floating-Point zero\");\n\nareZerosEqual = 0.0 == -0.0;\nprintln(\"0.0 == -0.0 -> $areZerosEqual\");\nprintln(\"0.0 -> \" * bitstring(0.0));\nprintln(\"-0.0 -> \" * bitstring(-0.0));\n\nprintln();\nprintln(\"Numeric Literal Coefficients\");\nx = 3;\n\nanswer = 2x^2 - 3x + 1;\nprintln(\"2x^2 - 3x + 1 = \" * string(answer));\n\nanswer = 1.5x^2 - .5x + 1;\nprintln(\"1.5x^2 - .5x + 1 = \" * string(answer));\n\nanswer = 2(x-1)^2 - 3(x -1) + 1;\nprintln(\"2(x-1)^2 - 3(x -1) + 1 = \" * string(answer));\n\nprintln();\nprintln(\"Literal zero and one\");\nprintln(\"zero(Float32) -> \" * string(zero(Float32)));\nprintln(\"zero(1.0) -> \" * string(zero(1.0)));\nprintln(\"one(Int64) -> \" * string(one(Int64)));\nprintln(\"one(BigFloat) -> \" * string(one(BigFloat)));\n", "meta": {"hexsha": "43ec45027e4d140c919cf34de89da769b0469956", "size": 2278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2-integers-and-floating-point-numbers.jl", "max_stars_repo_name": "CubicleJockey/julia-playground", "max_stars_repo_head_hexsha": "18c8929842c298d212cb03e6a9b93b3414246126", "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": "2-integers-and-floating-point-numbers.jl", "max_issues_repo_name": "CubicleJockey/julia-playground", "max_issues_repo_head_hexsha": "18c8929842c298d212cb03e6a9b93b3414246126", "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": "2-integers-and-floating-point-numbers.jl", "max_forks_repo_name": "CubicleJockey/julia-playground", "max_forks_repo_head_hexsha": "18c8929842c298d212cb03e6a9b93b3414246126", "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": 25.3111111111, "max_line_length": 111, "alphanum_fraction": 0.650570676, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.9005297841157157, "lm_q1q2_score": 0.7543017320521285}}
{"text": "using Test, SpecialFunctions\nimport TruncatedNormal as TruncNorm\n\n@test TruncNorm.tnmean(-Inf, Inf) == 0\n@test TruncNorm.tnmean(0, +Inf) \u2248 +\u221a(2/\u03c0)\n@test TruncNorm.tnmean(-Inf, 0) \u2248 -\u221a(2/\u03c0)\n@test TruncNorm.tnmean(-Inf, -Inf) == -Inf\n@test TruncNorm.tnmean(+Inf, +Inf) == +Inf\n\nfor x = -10:10\n    @test TruncNorm.tnmean(x, +Inf) \u2248 +\u221a(2/\u03c0) / erfcx(+x/\u221a2)\n    @test TruncNorm.tnmean(-Inf, x) \u2248 -\u221a(2/\u03c0) / erfcx(-x/\u221a2)\nend\n\nfor x = exp.(-100:100)\n    @test TruncNorm.tnmean(-x, x) \u2248 0\n    @test TruncNorm.tnmean(0, x) \u2248 -\u221a(2/\u03c0) * expm1(-x^2 / 2) / erf(x / \u221a2)\nend\n\n@test TruncNorm.tnmean(1e-44, 1e-43) \u2248 5.4999999999999999999999999999999999999999e-44\n\n@test TruncNorm.tnmean(-Inf, Inf, 0, 1) == TruncNorm.tnmean(-Inf, Inf)\nfor x = -100:100\n    @test TruncNorm.tnmean(x, +Inf, 0, 1) \u2248 TruncNorm.tnmean(x, +Inf)\n    @test TruncNorm.tnmean(-Inf, x, 0, 1) \u2248 TruncNorm.tnmean(-Inf, x)\nend\n\n@test TruncNorm.tnmean(-1e4, 1e4, 0, 1) == TruncNorm.tnmean(-1e4, 1e4)\n\nfor x = -100:100, y = x + 1 : 100\n    @test TruncNorm.tnmean(x, y, 0, 1) == TruncNorm.tnmean(x, y)\nend\n\n@test TruncNorm.tnmean(100, 115) \u2248 100.00999800099926070518490239457545847490332879043\n@test TruncNorm.tnmean(-1e6, -999000) \u2248 -999000.00000100100100099899498898098\n@test TruncNorm.tnmean(+1e6, +Inf) \u2248 +1.00000000000099999999999800000e6\n@test TruncNorm.tnmean(-Inf, -1e6) \u2248 -1.00000000000099999999999800000e6\n\n@test TruncNorm.tnmean(-1e200, 1e200) \u2248 0\n@test TruncNorm.tnmean(0, +1e200) \u2248 +0.797884560802865355879892119869\n@test TruncNorm.tnmean(-1e200, 0) \u2248 -0.797884560802865355879892119869\n\n@test TruncNorm.tnmean(50, 70, -2, 3) \u2248 50.171943499898757645751683644632860837133138152489\n@test TruncNorm.tnmean(-100.0, 0.0, 0.0, 2.0986317998643735) \u2248 -1.6744659119217125058885983754999713622460154892645\n@test TruncNorm.tnmean(0.0, 0.9, 0.0, 0.07132755843183151) \u2248 0.056911157632522598806524588414964004271754161737065\n@test TruncNorm.tnmean(-100.0, 100.0, 0.0, 17.185261847875548) \u2248 0\n@test TruncNorm.tnmean(-100.0, 0.5, 0.0, 0.47383322897860064) \u2248 -0.1267981330521791493635176736743283314399\n@test TruncNorm.tnmean(-100.0, 100.0, 0.0, 17.185261847875548) \u2248 0\n\nfor x = 1e1 .^ (-400:100:400)\n    @test TruncNorm.tnmean(-x, x) == TruncNorm.tnmean(-x, x) || isnan(TruncNorm.tnmean(-x, x)) && isnan(TruncNorm.tnmean(-x, x))\nend\n\nfor a = exp.(-10:10), b = exp.(-10:10)\n    a \u2264 b || continue\n    @test a \u2264 TruncNorm.tnmean(a, b) \u2264 b\nend\n\n# https://github.com/JuliaStats/Distributions.jl/issues/827\n@test TruncNorm.tnmean(0, 1000, 1000000, 1) \u2248 999.99999899899899900100501101901899090472046236710608108591983\n", "meta": {"hexsha": "1adb40ee235633df22c8d9c200a1de126deacd2a", "size": 2555, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tnmean.jl", "max_stars_repo_name": "suzannastep/TruncatedNormal.jl", "max_stars_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_stars_repo_licenses": ["MIT"], "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/tnmean.jl", "max_issues_repo_name": "suzannastep/TruncatedNormal.jl", "max_issues_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_issues_repo_licenses": ["MIT"], "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/tnmean.jl", "max_forks_repo_name": "suzannastep/TruncatedNormal.jl", "max_forks_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_forks_repo_licenses": ["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.8852459016, "max_line_length": 128, "alphanum_fraction": 0.7048923679, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7543017298975015}}
{"text": "using Sundials, Test, SparseArrays\n\n# Test for Jacobian usage\nfunction Lotka(du, u, p, t)\n  du[1] = u[1] - u[1] * u[2] # REPL[7], line 3:\n  du[2] = -3 * u[2] + 1 * u[1] * u[2]\n  nothing\nend\n\njac_called = false\nfunction Lotka_jac(J,u,p,t)\n  global jac_called\n  jac_called = true\n  J[1,1] = 1.0 - u[2]\n  J[1,2] = -u[1]\n  J[2,1] = 1 * u[2]\n  J[2,2] = -3 + u[1]\n  nothing\nend\n\nLotka_f = ODEFunction(Lotka,jac=Lotka_jac)\nprob = ODEProblem(Lotka_f,ones(2),(0.0,10.0))\ngood_sol = solve(prob,CVODE_BDF())\n@test jac_called == true\n\nLotka_f = ODEFunction(Lotka,jac=Lotka_jac,\n                      jac_prototype = sparse([1,2,1,2],[1,1,2,2],zeros(4)))\n\nprob = ODEProblem(Lotka_f,ones(2),(0.0,10.0))\njac_called = false\nsol9 = solve(prob,CVODE_BDF(linear_solver=:KLU))\n@test jac_called == true\n\nfunction f2!(res, du, u, p, t)\n    res[1] = 1.01du[1]\n    return\nend\n\njac_called = false\nfunction f2_jac!(out, du, u, p, gamma, t)\n    global jac_called\n    jac_called = true\n    out[1] = 1.01\nend\n\nf2_f = DAEFunction(f2!,jac=f2_jac!)\n\nu0 = [0.]\ntspan = (0.0, 10.)\ndu0 = [0.]\ndae_prob = DAEProblem(f2_f,du0, u0,tspan, differential_vars=[true])\ngood_sol = solve(dae_prob,IDA())\n@test jac_called == true\n\nfunction testjac(res, du, u, p, t)\n  res[1] = du[1] - 1.5 * u[1] + 1.0 * u[1]*u[2]\n  res[2] = du[2] +3 * u[2] - u[1]*u[2]\nend\n\njac_called = false\nfunction testjac_jac(J, du, u, p, gamma, t)\n  global jac_called\n  jac_called = true\n  J[1,1] = gamma - 1.5 + 1.0 * u[2]\n  J[1,2] = 1.0 * u[1]\n  J[2,1] = - 1 * u[2]\n  J[2,2] = gamma + 3 - u[1]\n  nothing\nend\n\ntestjac_f = DAEFunction(testjac,jac=testjac_jac)\n\nprob3 = DAEProblem(testjac_f,[0.5,-2.0],ones(2),(0.0,10.0),differential_vars=[true,true])\nsol3 = solve(prob3, IDA())\n\n@test jac_called == true\njac_called = false\nprob4 = DAEProblem(testjac,[0.5,-2.0],ones(2),(0.0,10.0))\nsol4 = solve(prob4, IDA())\n\n@test jac_called == false\n\nprintln(\"Jacobian vs no Jacobian difference:\")\nprintln(maximum(sol3-sol4))\n@test maximum(sol3-sol4) < 1e-6\n", "meta": {"hexsha": "8c19fd73252f33d3bce91f41a53c7063b73c77b6", "size": 1970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/common_interface/jacobians.jl", "max_stars_repo_name": "lcontento/Sundials.jl", "max_stars_repo_head_hexsha": "78bed72ca0943e27e2201191031da2e027ed1580", "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": "test/common_interface/jacobians.jl", "max_issues_repo_name": "lcontento/Sundials.jl", "max_issues_repo_head_hexsha": "78bed72ca0943e27e2201191031da2e027ed1580", "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": "test/common_interface/jacobians.jl", "max_forks_repo_name": "lcontento/Sundials.jl", "max_forks_repo_head_hexsha": "78bed72ca0943e27e2201191031da2e027ed1580", "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.9069767442, "max_line_length": 89, "alphanum_fraction": 0.6243654822, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7543017286646889}}
{"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\u0303 = W \\ (W \\ A)'\n    W\u0303 = diagm(L\u0303 * ones(size(L\u0303, 1)))\n\n    println(\"Laplacian sparsity = $(sparsity(W\u0303 \\ (W\u0303 - L\u0303)))\")\n    return sparse(W\u0303 \\ (W\u0303 - L\u0303))\nend\n\n\n\"\"\"\n    gaussian_similarity(X, \u03c3=1)\n\nCompute similarity using Gaussian kernel. Enforces sparsity by setting the similarity of\ndistant points to zero.\n\"\"\"\nfunction gaussian_similarity(X, \u03c3=1)\n    \ud835\udca6 = pairwise(Euclidean(), X, dims=2)\n    n = size(X, 2)\n    for i in 1:n\n        for j in i+1:n\n            \ud835\udca6[j, i] = \ud835\udca6[j, i] <= 3\u03c3 ? exp(-(\ud835\udca6[j,i]/\u03c3)^2) : 0\n            \ud835\udca6[i, j] = \ud835\udca6[j, i]\n        end\n    end\n    \ud835\udca6[diagind(\ud835\udca6)] .= 1\n\n    s = sparsity(\ud835\udca6)\n    if s < 0.8\n        println(\"Warning. sparsity = $s\")\n    end\n\n    return \ud835\udca6\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": "using Pkg\nPkg.install([\"LinearAlgebra\", \"Plots\", \"PlotThemes\", \"ScikitLearn\"])\nusing LinearAlgebra\n\nm = [1 2 3 4; 4 3 2 1; 1 1 1 1; 0 0 0 0]\ntranspose(m)\n\n", "meta": {"hexsha": "7935abca28b9af8c85b23c80dbbac71f6150b4f6", "size": 155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/website/test data/julia.jl", "max_stars_repo_name": "Fennec2000GH/OmniJupyter", "max_stars_repo_head_hexsha": "4f4429722fb773b6006ddfdceee9dda27c43614c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/website/test data/julia.jl", "max_issues_repo_name": "Fennec2000GH/OmniJupyter", "max_issues_repo_head_hexsha": "4f4429722fb773b6006ddfdceee9dda27c43614c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/website/test data/julia.jl", "max_forks_repo_name": "Fennec2000GH/OmniJupyter", "max_forks_repo_head_hexsha": "4f4429722fb773b6006ddfdceee9dda27c43614c", "max_forks_repo_licenses": ["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.375, "max_line_length": 68, "alphanum_fraction": 0.6580645161, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7543013387635652}}
{"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 \u2264 \", hi, \" is \", i, \".\")\n    break\nend\n\nfor i in reverse(primes(hi))\n    isrtruncprime(i) || continue\n    println(\"The largest right truncatable prime \u2264 \", 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": "using Test\nusing WavePropBase\nusing StaticArrays\nusing WavePropBase.Geometry\nusing WavePropBase.Integration\nusing LinearAlgebra\nusing Random\nRandom.seed!(1)\n\n@testset \"Reference segment\" begin\n    qstd = Fejer(20)\n    d     = domain(qstd)\n    # simple test on smooth integrand\n    for shand in [IMT(), Kress(), KressP()]\n        q     = SingularQuadratureRule(qstd,shand)\n        @test isapprox(integrate(cos,q),sin(1),rtol=1e-2)\n    end\n    # non-smooth integrand, singularity at 0\n    f     = (x) -> log(abs(x))\n    Ie    = -1\n    for shand in [IMT(), Kress(),KressP()]\n        q     = SingularQuadratureRule(qstd,shand)\n        Ia    = integrate(f,q)\n        @test isapprox(Ia,Ie,rtol=1e-4)\n        # check that the `naive` integration woudl have failed the test\n        Istd    = integrate(f,qstd)\n        @test !isapprox(Istd,Ie,rtol=1e-4)\n    end\n    # test that KressP() can handle singularity at both endpoints, and Kress() cannot\n    f     = (x) -> log(x) + log(1-x)\n    Ie    = -2\n    q     = SingularQuadratureRule(qstd,KressP())\n    Ia    = integrate(f,q)\n    @test isapprox(Ia,Ie,rtol=1e-5)\n    q     = SingularQuadratureRule(qstd,Kress())\n    Ia    = integrate(f,q)\n    @test !isapprox(Ia,Ie,rtol=1e-5)\n    # non-smooth integrand with singularity inside\n    s     = 0.1\n    f     = (x) -> log(abs(x-s))\n    Ie    = -1.32508297337145\n    # FIXME: for the time being, usign IMT with a singular quadrature rule for\n    # interior points yields a rounding problem because the change of variables\n    # accumulates points very quickly around zero. That is OK when the\n    # singularity is at zero, but shifting such nodes to another point s \u2208 (0,1]\n    # has to be done with care since these can get rounded to `s`, which in turn\n    # yields a singular value for the integrand. Note that the same can happen\n    # with other singularity handler types, but IMT is worse due to the\n    # exponential nature of the change of variables.\n    for shand in [Kress(),KressP()]\n        q     = SingularQuadratureRule(qstd,shand)\n        x,w  = q(s) # singular nodes and weights which depend on s\n        Ia    = integrate(f,x,w)\n        @test isapprox(Ia,Ie,rtol=1e-5)\n        # check that the `naive` integration woudl have failed the test\n        Istd    = integrate(f,qstd)\n        @test !isapprox(Istd,Ie,rtol=1e-5)\n    end\nend\n\n@testset \"Duffy\" begin\n    q1d   = Fejer(5)\n    qstd  = TensorProductQuadrature(q1d,q1d)\n    duffy = Duffy()\n    qsin  = SingularQuadratureRule(qstd,duffy)\n    x,w  = qsin()\n    # regular kernel\n    k    = x -> cos(x[1])*sin(x[2])\n    Ie   = 1/2*(sin(1)-cos(1))\n    Ia   = integrate(k,qsin)\n    @test isapprox(Ie,Ia,rtol=1e-4)\n    # singular kernel at right vertex\n    s    = SVector(1,0)\n    k    = x -> 1/norm(x-s)\n    Ia   = integrate(k,qsin)\n    Ie   = acosh(sqrt(2))\n    @test isapprox(Ie,Ia,rtol=1e-5)\n    # singular kernel at wrong vertex (should not be accurate, see test below)\n    s    = SVector(0,1)\n    k    = x -> 1/norm(x-s)\n    Ie   = acosh(sqrt(2))\n    Ia   = integrate(k,qsin)\n    @test !isapprox(Ie,Ia,rtol=1e-5)\nend\n\n@testset \"2d Kress\" begin\n    q1d   = Fejer{10}()\n    qstd  = TensorProductQuadrature(q1d,q1d)\n    s1d   = Kress(order=2)\n    sing_handler = TensorProductSingularityHandler(s1d,s1d)\n    qsin = SingularQuadratureRule(qstd,sing_handler)\n    x,w  = qsin()\n    # regular kernel\n    k = (x) -> cos(x[1])\n    Ie   = sin(1)\n    Isin = sum(k.(x).*w)\n    @test isapprox(Ie,Isin,rtol=1e-6)\n    # singular kernel at origin\n    k  = (x) -> 1/norm(x)\n    Ie = 1/2*log(17 + 12*sqrt(2)) # Wolfram alpha is your friend ;-)\n    Isin = sum(k.(x).*w)\n    @test isapprox(Ie,Isin,rtol=1e-2)\nend\n", "meta": {"hexsha": "ac8a42684ae689061438ae100ffa302b07de712b", "size": 3644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Integration/singularquadrule_test.jl", "max_stars_repo_name": "WaveProp/WavePropBase", "max_stars_repo_head_hexsha": "75c47071ba3e3e2d95733b5f5c679c2203c43c48", "max_stars_repo_licenses": ["MIT"], "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/Integration/singularquadrule_test.jl", "max_issues_repo_name": "WaveProp/WavePropBase", "max_issues_repo_head_hexsha": "75c47071ba3e3e2d95733b5f5c679c2203c43c48", "max_issues_repo_licenses": ["MIT"], "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/Integration/singularquadrule_test.jl", "max_forks_repo_name": "WaveProp/WavePropBase", "max_forks_repo_head_hexsha": "75c47071ba3e3e2d95733b5f5c679c2203c43c48", "max_forks_repo_licenses": ["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.0384615385, "max_line_length": 85, "alphanum_fraction": 0.6163556531, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7543013372588078}}
{"text": "#\n# Simple Pendulum Problem\n#\nusing OrdinaryDiffEq, Plots\n\n#Constants\nconst g = 9.81\nL = 1.0\n\n#Initial Conditions\nu\u2080 = [0,\u03c0/2]\ntspan = (0.0,6.3)\n\n#Define the problem\nfunction simplependulum(du,u,p,t)\n    \u03b8  = u[1]\n    d\u03b8 = u[2]\n    du[1] = d\u03b8\n    du[2] = -(g/L)*sin(\u03b8)\nend\n\n#Pass to solvers\nprob = ODEProblem(simplependulum,u\u2080, 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(\u03b8)  = -\u2211log\u03c3(yX\u03b8) + \u03bb|\u03b8|\u2082\u00b2/2\n# -> \u2207f(\u03b8)  =  X'(y(w-1)) + \u03bb\u03b8\n# -> \u2207\u00b2f(\u03b8) =  X' Diag(w(1-w)) X + \u03bbI\n# NOTE:\n# * w = \u03c3(yX\u03b8)\n# * y\u1d62 \u2208 {\u00b11} so that y\u00b2 = 1\n# * -\u03c3(-x) == (\u03c3(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    \u03bb    = getscale(glr.penalty)\n    if glr.fit_intercept\n        (f, g, H, \u03b8) -> begin\n            X\u03b8 = scratch.n\n            apply_X!(X\u03b8, X, \u03b8)                       # -- X\u03b8 = apply_X(X, \u03b8)\n            # precompute \u03c3(yX\u03b8)\n            w    = scratch.n2\n            w   .= \u03c3.(X\u03b8 .* y)                       # -- w  = \u03c3.(X\u03b8 .* 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 .+= \u03bb .* \u03b8\n                glr.penalize_intercept || (g[end] -= \u03bb * \u03b8[end])\n            end\n            H === nothing || begin\n                # NOTE: we could try to be clever to reduce the allocations for\n                # \u039bX 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                      # \u03c3(yX\u03b8)(1-\u03c3(yX\u03b8))\n                a    = 1:p\n                \u039bX   = t .* X                         # !! big allocs\n                mul!(view(H, a, a), X', \u039bX)           # -- H[1:p,1:p] = X'\u039bX\n                \u039bXt1   = view(scratch.p, a)\n                \u039bXt1 .*= 0\n                @inbounds for i in a, j in 1:n\n                    \u039bXt1[i] += \u039bX[j, i]               # -- (\u039bX)'1\n                end\n                @inbounds for i in a\n                    H[i, end] = H[end, i] = \u039bXt1[i]   # -- H[:,p+1] = (\u039bX)'1\n                end\n                H[end, end] = sum(t)                  # -- 1'\u039b1'\n                add_\u03bbI!(H, \u03bb, glr.penalize_intercept) # -- H = -X'\u039bX + \u03bbI\n            end\n            f === nothing || return J(y, X\u03b8, view_\u03b8(glr, \u03b8))\n        end\n    else\n        # see comments above, same computations just no additional things for\n        # fit_intercept\n        (f, g, H, \u03b8) -> begin\n            X\u03b8 = scratch.n\n            apply_X!(X\u03b8, X, \u03b8)\n            w    = scratch.n2\n            w   .= \u03c3.(y .* X\u03b8)\n            g === nothing || begin\n                t  = scratch.n3\n                t .= y .* w .- y\n                apply_Xt!(g, X, t)\n                g .+= \u03bb .* \u03b8\n            end\n            H === nothing || begin\n                t  = scratch.n3\n                t .= w .- w.^2\n                mul!(H, X', t .* X)\n                add_\u03bbI!(H, \u03bb)\n            end\n            f === nothing || return J(y, X\u03b8, \u03b8)\n        end\n    end\nend\n\nfunction Hv!(glr::GLR{LogisticLoss,<:L2R}, X, y, scratch)\n    n, p = size(X)\n    \u03bb    = getscale(glr.penalty)\n    if glr.fit_intercept\n        # H = [X 1]'\u039b[X 1] + \u03bb I\n        # rows a 1:p = [X'\u039bX + \u03bbI | X'\u039b1]\n        # row  e end = [1'\u039bX      | sum(a)+\u03bb]\n        (Hv, \u03b8, v) -> begin\n            X\u03b8 = scratch.n\n            apply_X!(X\u03b8, X, \u03b8)                       # -- X\u03b8 = apply_X(X, \u03b8)\n            w   = scratch.n2\n            w  .= \u03c3.(X\u03b8 .* y)                        # -- w  = \u03c3.(X\u03b8 .* y)\n            w .-= w.^2                               # -- w  = w(1-w)\n            # view on the first p rows\n            a    = 1:p\n            Hv\u2090  = view(Hv, a)\n            v\u2090   = view(v,  a)\n            Xt\u039b1 = view(scratch.p, 1:p)\n            mul!(Xt\u039b1, X', w)                        # -- X'\u039b1; O(np)\n            v\u2091   = v[end]\n            # update for the first p rows -- (X'X + \u03bbI)v[1:p] + (X'1)v[end]\n            Xv\u2090  = scratch.n\n            mul!(Xv\u2090, X, v\u2090)\n            Xv\u2090 .*=  w                               # --  \u039bXv\u2090\n            mul!(Hv\u2090, X', Xv\u2090)                       # -- (X'\u039bX)v\u2090\n            Hv\u2090 .+= \u03bb .* v\u2090 .+ Xt\u039b1 .* v\u2091\n            # update for the last row -- (X'1)'v + n v[end]\n            Hv[end] = dot(Xt\u039b1, v\u2090) +\n                        (sum(w) + \u03bb_if_penalize_intercept(glr, \u03bb)) * v\u2091\n        end\n    else\n        (Hv, \u03b8, v) -> begin\n            X\u03b8 = scratch.n\n            apply_X!(X\u03b8, X, \u03b8)\n            w   = scratch.n2\n            w  .= \u03c3.(X\u03b8 .* y)                # -- \u03c3(yX\u03b8)\n            w .-= w.^2\n            Xv  = scratch.n\n            mul!(Xv, X, v)\n            Xv .*= scratch.n2               # -- \u039bXv\n            mul!(Hv, X', Xv)                # -- X'\u039bXv\n            Hv .+= \u03bb .* v\n        end\n    end\nend\n\n# ----------------------------------- #\n#  -- L1/Elnet Logistic Regression -- #\n# ----------------------------------- #\n# ->  J(\u03b8)  = f(\u03b8) + r(\u03b8)\n# ->  f(\u03b8)  = LL + \u03bb|\u03b8|\u2082\u00b2  // smooth (LL = LogisticLoss)\n# ->  r(\u03b8)  = \u03b3|\u03b8|\u2081        // non-smooth with prox\n# -> \u2207f(\u03b8)  = \u2207LL + \u03bb\u03b8\n# -> \u2207\u00b2f(\u03b8) = \u2207\u00b2LL + \u03bbI\n# -> prox_r = soft-thresh\n# ---------------------------------------------------------\n\nfunction smooth_fg!(glr::GLR{LogisticLoss,<:ENR}, X, y, scratch)\n    smooth = get_smooth(glr)\n    (g, \u03b8) -> fgh!(smooth, X, y, scratch)(0.0, g, nothing, \u03b8)\nend\n\n# ---------------------------------- #\n#  -- Multinomial Regression (L2) -- #\n# ---------------------------------- #\n# ->  c is the number of classes, \u03b8 has dims p * c\n# ->  P = X * \u03b8\n# -> Z\u1d62 = \u2211 exp(P\u1d62)\n# -> \u039b  = Diagonal(-Z)\n# ->  f(\u03b8)   = \u2211(log Z\u1d62 - P[i, y[i]]) +  \u03bb|\u03b8|\u2082\u00b2\n# -> \u2207f(\u03b8)   = reshape(X'\u039bM, c * p)\n# -> \u2207\u00b2f(\u03b8)v = via R operator\n# NOTE:\n# * y\u1d62 \u2208 {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    \u03bb    = getscale(glr.penalty)\n    (f, g, \u03b8) -> begin\n        P  = scratch.nc\n        apply_X!(P, X, \u03b8, 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            \u039bM  = scratch.nc3\n            \u039bM .= 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            \u2211\u039bM = sum(\u039bM, dims=1)\n            \u2211Q  = sum(Q, dims=1)\n            R   = \u039bM\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] = \u2211\u039bM[k] - \u2211Q[k]\n                end\n            else\n                mul!(G, X', R)\n            end\n            g  .= reshape(G, (p + Int(glr.fit_intercept)) * c)\n            g .+= \u03bb .* \u03b8\n            glr.fit_intercept &&\n                (glr.penalize_intercept || (g[end] -= \u03bb * \u03b8[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            \u039bM  = scratch.nc2  # note that _NC is already linked to P\n            \u039bM .= M ./ ems\n            ss  = sum(\u039bM, 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_\u03b8(glr, \u03b8))\n        end\n    end\nend\n\nfunction Hv!(glr::GLR{<:MultinomialLoss,<:L2R}, X, y, scratch)\n    p = size(X, 2)\n    \u03bb = 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, \u03b8, v) -> begin\n        P  = apply_X(X, \u03b8, c)     # P_ik = <x_i, \u03b8_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        \u03c1  = 1 ./ sum(M, dims=2)  # \u03c1_i = 1/Z_i = 1/\u2211_k exp<x_i, w_k>\n        \u03ba  = sum(MQ, dims=2)      # \u03ba_i  = \u2211_k exp<x_i, w_k><x_i, v_k>\n        \u03b3  = \u03ba .* \u03c1.^2            # \u03b3_i  = \u03ba_i / Z_i^2\n        # computation of Hv\n        U      = (\u03c1 .* MQ) .- (\u03b3 .* 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 .+= \u03bb .* v\n        glr.fit_intercept && (glr.penalize_intercept || (Hv[end] -= \u03bb * v[end]))\n    end\nend\n\n# -------------------------------------- #\n#  -- L1/Elnet Multinomial Regression -- #\n# -------------------------------------- #\n# ->  J(\u03b8)  = f(\u03b8) + r(\u03b8)\n# ->  f(\u03b8)  = MN + \u03bb|\u03b8|\u2082\u00b2  // smooth (MN = MultinomialLoss)\n# ->  r(\u03b8)  = \u03b3|\u03b8|\u2081        // non-smooth with prox\n# -> \u2207f(\u03b8)  = \u2207MN + \u03bb\u03b8\n# -> \u2207\u00b2f(\u03b8) = \u2207\u00b2MN + \u03bbI\n# -> prox_r = soft-thresh\n# ---------------------------------------------------------\n\nfunction smooth_fg!(glr::GLR{<:MultinomialLoss,<:ENR}, X, y, scratch)\n    smooth = get_smooth(glr)\n    (g, \u03b8) -> fg!(smooth, X, y, scratch)(0.0, g, \u03b8)\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": "# generate test plots of scores\n#    matching https://en.wikipedia.org/wiki/Scoring_rule\n#\n#\nusing RatPack\nusing PyPlot\n\nx = collect( 0 : 0.01 : 1.0 )\nnorm = false\nnorm = true\n\nrule_log = ScoreLogarithmic(; normalise=norm )\ny_log = zeros(size(x))\nfor i=1:length(x)\n    y_log[i] = scoring_function( rule_log, [x[i], 1-x[i]], 1 ) \nend\n\nrule_brier = ScoreBrier(; normalise=norm )\ny_brier = zeros(size(x))\nfor i=1:length(x)\n    y_brier[i] = scoring_function( rule_brier, [x[i], 1-x[i]], 1 ) \nend\n\nrule_quad = ScoreQuadratic(; normalise=norm )\ny_quad = zeros(size(x))\nfor i=1:length(x)\n    y_quad[i] = scoring_function( rule_quad, [x[i], 1-x[i]], 1 ) \nend\n\nrule_sphere = ScoreSpherical(; normalise=norm )\ny_sphere = zeros(size(x))\nfor i=1:length(x)\n    y_sphere[i] = scoring_function( rule_sphere, [x[i], 1-x[i]], 1 ) \nend\n\n\nfigure(1)\nclf()\nplot(x, y_log) \nplot(x, y_brier) \nplot(x, y_quad) \nplot(x, y_sphere) \nylim([-3, 1])\n\n\n\n\n\n# test scoring on cases\n\n", "meta": {"hexsha": "53d88c0f77393da1bf6cb269be042e51706ff93c", "size": 950, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_score_1.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": "test/test_score_1.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": "test/test_score_1.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": 18.6274509804, "max_line_length": 69, "alphanum_fraction": 0.6610526316, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7543010056502748}}
{"text": "using BenchmarkTools\ninclude(\"../src/ZZDiffusionBridge.jl\")\nstruct BB <: AbstractModel\n    # optional precompiled factors\nend\n\ndependence_strucute(::BB) = FullIndependence()\nsampling_scheme(::BB) = Regular()\n\n#Poisson rates\n\"\"\"\nobtaining waiting time for Inhomogeneous Poisson Process\nwith rate of the form \u03bb(t) = (a + b*t)^+, `a`,`b` \u2208 R, `u` random variable\n\"\"\"\nfunction wait_gengaus(a,b,u)\n    if b > 0\n        if a < 0\n            \u03c4 = sqrt(-log(u)*2.0/b) - a/b\n        else #a[i]>0\n            \u03c4 = sqrt((a/b)^2 - log(u)*2.0/b) - a/b\n        end\n    elseif  b == 0\n        if a > 0\n            \u03c4 = -log(u)/a\n        else #a[i] <= 0\n            \u03c4 = Inf\n        end\n    else #b[i] < 0\n        if a <= 0\n            \u03c4 = Inf\n        elseif -log(u) <= -a^2/b + a^2/(2*b)\n            \u03c4 = - sqrt((a/b)^2 - log(u)*2.0/b) - a/b\n        else\n            \u03c4 = Inf\n        end\n    end\nend\n\n\nfunction \u03bbbar(n, S::System, ::BB , u::Float64, v::Float64, t::Float64)\n    return wait_gengaus(S.\u03be[n]*S.\u03b8[n], 1.0, rand())\nend\n\n#This function will not be necessary after fixing issue #4\nfunction update_events!(n::Int64, \u03c40::Float64, S::System, X::AbstractModel, ::Regular, ::FullIndependence, acc::Bool, u::Float64, v::Float64, t::Float64)\n    S.\u03c4[n] = \u03bbbar(n, S, X , u, v, t)\n    for i in 1:(n-1)\n        S.\u03c4[i] -= \u03c40\n    end\n    for i in  (n + 1): length(S.\u03d5)\n        S.\u03c4[i] -=  \u03c40\n    end\nend\n\nusing Random\nRandom.seed!(1)\nfunction runall(SHORT = false)\n    T = 1.0\n    clock = 300.0\n    L = 6\n    u = 0.0\n    v = 0.0\n    XX = zz_sampler(BB(), T, L, u, v, clock)\n    if SHORT == false\n        burning = 10.0    #burning\n        f = clock - 1.0; n =100\n        db = (f-burning)/n\n        b =  burning:db:f\n        p = plotmixing(XX, b, T, L, u, v)\n        xaxis!(p, \"t\")\n        yaxis!(p, \"X_t\")\n        display(p)\n        #plot the mean of the process\n    end\nend\n\n\n\n\nerror(\"STOP HERE\")\n\nrunall()\n\nsavefig(\"../../output/bm00.pdf\")\n", "meta": {"hexsha": "6c4f1b9832e6c52a879372ecf31197ac8b4c6bc6", "size": 1916, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "auxiliary/zzbb.jl", "max_stars_repo_name": "SebaGraz/ZZDiffusionBridge", "max_stars_repo_head_hexsha": "0ffb12385d09e8a95cd64141de0e683058891448", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "auxiliary/zzbb.jl", "max_issues_repo_name": "SebaGraz/ZZDiffusionBridge", "max_issues_repo_head_hexsha": "0ffb12385d09e8a95cd64141de0e683058891448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-16T21:14:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-16T21:14:50.000Z", "max_forks_repo_path": "auxiliary/zzbb.jl", "max_forks_repo_name": "SebaGraz/ZZDiffusionBridge", "max_forks_repo_head_hexsha": "0ffb12385d09e8a95cd64141de0e683058891448", "max_forks_repo_licenses": ["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.5411764706, "max_line_length": 153, "alphanum_fraction": 0.5151356994, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.754300999851194}}
{"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    \u03a3y::S\n end\n\n# constructor\nfunction AbstractGPSurrogate(x, y; gp = GP(Matern52Kernel()), \u03a3y = 0.1)\n    AbstractGPSurrogate(x, y, gp, posterior(gp(x, \u03a3y),y), \u03a3y)\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.\u03a3y), 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": "using Symbolics\nusing Test\n\n@variables x, y, z\n\n@test isequal(degree(1), 0)\n@test isequal(degree(x), 1)\n@test isequal(degree(x, x), 1)\n@test isequal(degree(x, y), 0)\n\n@test isequal(degree(x*y, y), 1)\n@test isequal(degree(x*y, x), 1)\n@test isequal(degree(x*y, x*y), 1)\n@test isequal(degree(x*y, z), 0)\n\n@test isequal(degree(x*y^2+2*x+y^3*x^3), 6)\n@test isequal(degree(x*y^2+2*x+y^3*x^3, y), 3)\n@test isequal(degree(x*y^2+2*x+y^3*x^6, x), 6)\n\n@test isequal(degree(x*y^2+2*x+y^3*x^6, z), 0)\n@test isequal(degree(x*y^2+2*x+y^3*x^6+z, z), 1)\n@test isequal(degree(x*y^2+2*x+y^3*x^6*z, z), 1)\n\n@test isequal(degree(x^2 + y^2 +z^2, sin(z)), 0)\n@test isequal(degree(sin(z), z), 0)\n@test isequal(degree(sin(z)), 1)\n\n@test isequal(degree(x^2*sin(z), x), 2)\n@test isequal(degree(x+exp(z), x), 1)\n\n@test isequal(degree((x - y)^2*((y + x*y)^3)), 8)\n@test isequal(degree((x + z)*((y + x*y)^3), x), 4)", "meta": {"hexsha": "d666e2619f9722d637b16d8127d24b4fbb747356", "size": 885, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/degree.jl", "max_stars_repo_name": "sharanry/Symbolics.jl", "max_stars_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 907, "max_stars_repo_stars_event_min_datetime": "2021-01-22T02:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:13:39.000Z", "max_issues_repo_path": "test/degree.jl", "max_issues_repo_name": "sharanry/Symbolics.jl", "max_issues_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 472, "max_issues_repo_issues_event_min_datetime": "2021-01-21T14:18:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:10:18.000Z", "max_forks_repo_path": "test/degree.jl", "max_forks_repo_name": "sharanry/Symbolics.jl", "max_forks_repo_head_hexsha": "eeee4366850459b929b46c438a7d6f63e027b4ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2021-01-25T14:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T19:37:30.000Z", "avg_line_length": 27.65625, "max_line_length": 50, "alphanum_fraction": 0.609039548, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.754282285154514}}
{"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                      \u03c3_f::Float64, l::Float64)\n    re = \u03c3_f^2 * exp((x1 - x2)^2 / -2)\nend\n\nfunction K(x::Array{Float64}, \u03c3_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], \u03c3_f, l)\n        end\n    end\n    re\nend\n\nfunction K(x1::Array{Float64}, x2::Float64, \u03c3_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, \u03c3_f, l)\n    end\n    re\nend\n\nfunction K(x::Float64, \u03c3_f::Float64, l::Float64)\n    kernel_trick(x, x, \u03c3_f, l)\nend\n\nfunction marginal_likelihood(tr_x::Array{Float64}, tr_y::Array{Float64},\n                             \u03c3_f::Float64, l::Float64, \u03c3_n::Float64)\n    A = K(tr_x, \u03c3_f, l) + \u03c3_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    \u03c3_f, l, \u03c3_n= DE_evolution(f, 10, 3, 50)[1]\n    A = K(tr_x, \u03c3_f, l) + \u03c3_n * UniformScaling(length(tr_x))\n    while !isposdef(A)\n        \u03c3_f, l, \u03c3_n= DE_evolution(f, 10, 3, 50)[1]\n        A = K(tr_x, \u03c3_f, l) + \u03c3_n * UniformScaling(length(tr_x))\n    end\n\n    L = cholesky(A)\n    \u03b1 = L.U\\(L.L\\tr_y)\n    return \u03c3_f, l, L, \u03b1\nend\n\nfunction predict(\u03c3_f::Float64, l::Float64, L::Cholesky, \u03b1::Array{Float64},\n                 tr_x::Array{Float64}, pr_x::Float64)\n    k_s = K(tr_x, pr_x, \u03c3_f, l)\n    k_ss = K(pr_x, \u03c3_f, l)\n    mean = k_s' \u22c5 \u03b1\n    v = L\\k_s\n    vari = k_ss - v' \u22c5 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(\u03bd, \u03bc)\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(\u03bd, \u03bc)\n    n = length(\u03bd)\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, :]) == \u03bc[k])\n        @constraint(m, sum(p[:, k]) == \u03bd[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": "@testset \"Kalman filter system test\" begin\n    start_pt = 19\n    start_vel = 2\n    start_acc = 1\n    \u03c3_acc_noise = 0.0001\n    \u03c3_meas_noise = 0.25\n    \u0394t = 0.1\n\n    function measure(state, \u0394t, \u03c3_meas_noise, \u03c3_acc_noise)\n        s, v, a = state[1], state[2], state[3]\n        a_next = a + randn() * \u03c3_acc_noise\n        v_next = v + a * \u0394t\n        s_next = a * \u0394t^2 / 2 + v * \u0394t + s\n        s_next + randn() * \u03c3_meas_noise, (s_next, v_next, a_next)\n    end\n\n    # State space matrices of discretized white noise acceleration model\n    F = [1 \u0394t \u0394t^2/2; 0 1 \u0394t; 0 0 1]\n    H = [1, 0, 0]'\n    Q = [\u0394t^2/2; \u0394t; 1] * [\u0394t^2/2 \u0394t 1] * \u03c3_acc_noise^2\n    R = \u03c3_meas_noise^2\n\n    # Initialization\n    maxiter = 20000\n    counter = 1\n    x_init = [0.0, 0.0, 0.0]\n    P_init = [2.5 0.25 0.1; 0.25 2.5 0.2; 0.1 0.2 2.5]\n    y\u0303_over_time = Vector{Float64}(undef, maxiter)\n    S_over_time = Vector{Float64}(undef, maxiter)\n    states = (start_pt, start_vel, start_acc)\n    s_over_time = Vector{Float64}(undef, maxiter)\n    z_over_time = Vector{Float64}(undef, maxiter)\n    s\u0303_over_time = Vector{Float64}(undef, maxiter)\n    # run Kalman Filter\n    tu = time_update(x_init, P_init, F, Q)\n    for i = 1:maxiter\n        measurement, states = measure(states, \u0394t, \u03c3_meas_noise, \u03c3_acc_noise)\n        mu = measurement_update(get_state(tu), get_covariance(tu), measurement, H, R)\n        tu = time_update(get_state(mu), get_covariance(mu), F, Q)\n\n        #s\u0303_over_time[counter] = state(mu)[1]\n        #s_over_time[counter] = states[1]\n        #z_over_time[counter] = measurement\n        y\u0303_over_time[counter] = get_innovation(mu)\n        S_over_time[counter] = get_innovation_covariance(mu)\n        counter += 1\n    end\n    #using PyPlot\n    #figure()\n    #plot(s_over_time)\n    #plot(z_over_time)\n    #plot(s\u0303_over_time)\n    #plot(y\u0303_over_time)\n    #plot(s_over_time .- s\u0303_over_time)\n    #legend((\"Ground truth\", \"Messung\", \"Sch\u00e4tzung\", \"Innovation\", \"Error\"))\n\n    # Statistical consistency testing\n    @test sigma_bound_test(y\u0303_over_time[4:end], S_over_time[4:end]) == true\n    @test two_sigma_bound_test(y\u0303_over_time[4:end], S_over_time[4:end]) == true\n\n    window_start = 4\n    window_length = 400\n    window = window_start:window_start + window_length - 1\n    dof = length(window) * size(y\u0303_over_time[window_start], 1)\n    nis_over_time_sys = map((x, \u03c3\u00b2) -> calc_nis(x, \u03c3\u00b2), y\u0303_over_time[window], S_over_time[window])\n    result_nis_test = nis_test(nis_over_time_sys, dof)\n    @test result_nis_test == true\nend\n", "meta": {"hexsha": "c7e5e4c7c627daa0bc24000c1846589f86464cc6", "size": 2492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/system.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": "test/system.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": "test/system.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": 36.115942029, "max_line_length": 98, "alphanum_fraction": 0.636035313, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.754282272167145}}
{"text": "\"\"\"\n    TanhDerivative(x)\n\nDerivative of the hyperbolic tangent activation function.\n\n    Usage:\n```julia-repl\nTanhDerivative(x)\n```\nArguments:\n- `x` : Input value.\n\"\"\"\nfunction TanhDerivative(x::Float64)\n    x\u2081 = 1 - tanh2(x)\n    return x\u2081\nend", "meta": {"hexsha": "97a1fc9601065b57934496f291e8f5d1eeac738f", "size": 244, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ActivationFunctionDerivatives/TanhDerivative.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/ActivationFunctionDerivatives/TanhDerivative.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/ActivationFunctionDerivatives/TanhDerivative.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": 15.25, "max_line_length": 57, "alphanum_fraction": 0.6721311475, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7542775240117866}}
{"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,\u03bc::Float64)\n    abs(t)^(2*\u03bc)*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(\u03b1,\u03b2)\n    @assert \u03b1>-0. && \u03b2>-0. \"Invalid shape parameters\"\n    return t->w_beta(t,\u03b1,\u03b2)\nend\nfunction w_beta(t,\u03b1,\u03b2)\n    # 0. <=t<= 1. ? (t^(\u03b1-1)*(1-t)^(\u03b2-1)/beta(\u03b1,\u03b2)) : (error(\"$t not in support\"))\n    t^(\u03b1-1)*(1-t)^(\u03b2-1)/beta(\u03b1,\u03b2)\nend\n\n\n\nfunction build_w_gamma(\u03b1)\n    @assert \u03b1>0 \"Invalid shape parameter\"\n    return t->w_gamma(t,\u03b1)\nend\nfunction w_gamma(t,\u03b1)\n    t>=0. ? (1/gamma(\u03b1)*Float64(t)^(\u03b1-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 \u03b4(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 = \u03b4\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\u03b4(i->i, j->j, Np1sq)\n    a += \u03b4(i->mod1(i+1, Np1sq), j->j, Np1sq)\n    a += \u03b4(i->mod1(i-1, Np1sq), j->j, Np1sq)\n    a += \u03b4(i->mod1(i+N+1, Np1sq), j->j, Np1sq)\n    a += \u03b4(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, \u03b2::Array{Int,1})\n\n    ndims(A) == 2 || error(\"operator matrix must be 2-d\")\n    length(\u03b2) == 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(\u03b2)\n        \u03b2[i] == 1 ? B[:,i] = A[:,i] : F[:,i] = A[:,i]\n    end\n    return F, B\n\nend\n\n# \u03b2[i] = 1 iff \u03d5[i] is a boundary condition\nfunction rhoeff(\u03c1::Array, \u0394b::Array, \u03d5b::Array, \u03b2::Array{Int,1})\n    return (\u03c1 + \u0394b*\u03d5b) .* (1 .- \u03b2)\nend\n\n# Cancel out bound rows to get \u0394effective\nfunction deltaeff(\u0394f, \u03b2::Array{Int,1})\n    return \u0394f .* (1 .- \u03b2)\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, \u03b3, 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`). `\u03b3` 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\u00b0 (received $(lon)\u00b0). 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, \u03b3, 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`). `\u03b3` 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\u00b0 (calculated $(lon)\u00b0). 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) \u2202f/\u2202x = 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, \u03b1, to prevent any x\u1d62 from going negative\n            \u03b1 = minimum(x[ind] ./ (x[ind] - s[ind]))\n\n            # update solution (pushes some x\u1d62 to zero)\n            x += \u03b1*(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 :\u2102\n    - :Dual or :Grassmann\n    - :Grassmann2D or :G2\n    - :Grassmann3D or :G3\n    - :Quaternions or :\u210d\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, :\u2102)\n        return CliffordAlgebra(0, 1, 0, (:i,))\n    elseif a in (:Dual, :Grassmann)\n        return CliffordAlgebra(0, 0, 1, (:\u03b5,))\n    elseif a in (:Grassmann2D, :G2)\n        return CliffordAlgebra(0, 0, 2, (:\u03b5\u2081, :\u03b5\u2082))\n    elseif a in (:Grassmann3D, :G3)\n        return CliffordAlgebra(0, 0, 3, (:\u03b5\u2081, :\u03b5\u2082, :\u03b5\u2083))\n    elseif a in (:Quaternions, :\u210d)\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\u208a, :e\u208b))\n    elseif a in (:CGA3D, :Conformal3D)\n        return CliffordAlgebra(4, 1, 0, (:e1, :e2, :e3, :e\u208a, :e\u208b))\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\u2081, :t\u2082, :e\u208a\u2081, :e\u208a\u2082, :x\u2081, :x\u2082, :y\u2081, :y\u2082, :z\u2081, :z\u2082, :e\u208b\u2081, :e\u208b\u2082))\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) \u00f7 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(:\ud835\udfcf)\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  \u03b8 = 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  \u03b8 = 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\u2080 = idx - 1; i\u2081 = idx; i\u2082 = i\u2081 + 1;\n  else\n    i\u2080 = idx; i\u2081 = i\u2080 + 1; i\u2082 = i\u2081 + 1;\n  end\n  dl\u2080 = (2t - A.t[i\u2081] - A.t[i\u2082]) / ((A.t[i\u2080] - A.t[i\u2081]) * (A.t[i\u2080] - A.t[i\u2082]))\n  dl\u2081 = (2t - A.t[i\u2080] - A.t[i\u2082]) / ((A.t[i\u2081] - A.t[i\u2080]) * (A.t[i\u2081] - A.t[i\u2082]))\n  dl\u2082 = (2t - A.t[i\u2080] - A.t[i\u2081]) / ((A.t[i\u2082] - A.t[i\u2080]) * (A.t[i\u2082] - A.t[i\u2081]))\n  A.u[i\u2080] * dl\u2080 + A.u[i\u2081] * dl\u2081 + A.u[i\u2082] * dl\u2082\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\u2080 = idx - 1; i\u2081 = idx; i\u2082 = i\u2081 + 1;\n  else\n    i\u2080 = idx; i\u2081 = i\u2080 + 1; i\u2082 = i\u2081 + 1;\n  end\n  dl\u2080 = (2t - A.t[i\u2081] - A.t[i\u2082]) / ((A.t[i\u2080] - A.t[i\u2081]) * (A.t[i\u2080] - A.t[i\u2082]))\n  dl\u2081 = (2t - A.t[i\u2080] - A.t[i\u2082]) / ((A.t[i\u2081] - A.t[i\u2080]) * (A.t[i\u2081] - A.t[i\u2082]))\n  dl\u2082 = (2t - A.t[i\u2080] - A.t[i\u2081]) / ((A.t[i\u2082] - A.t[i\u2080]) * (A.t[i\u2082] - A.t[i\u2081]))\n  @views @. A.u[:, i\u2080] * dl\u2080 + A.u[:, i\u2081] * dl\u2081 + A.u[:, i\u2082] * dl\u2082\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  \u03c3 = 1//2 * (A.z[i] - A.z[i - 1]) / (A.t[i] - A.t[i - 1])\n  A.z[i-1] + 2\u03c3 * (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 Test, Plasmo, MadNLP, MadNLPTests, MadNLPGraph\n\n@testset \"MadNLPGraphs test\" begin\n    \n    n_nodes=2\n    M = 200\n    d = sin.((0:M*n_nodes).*pi/100)\n    \n    graph = OptiGraph()\n    @optinode(graph,nodes[1:n_nodes])\n\n    #Node models\n    nodecnt = 1\n    for (i,node) in enumerate(nodes)\n        @variable(node, x[1:M])\n        @variable(node, -1<=u[1:M]<=1)\n        @constraint(node, dynamics[i in 1:M-1], x[i+1] == x[i] + u[i])\n        @objective(node, Min, sum(x[i]^2 - 2*x[i]*d[i+(nodecnt-1)*M] for i in 1:M) +\n            sum(u[i]^2 for i in 1:M))\n        nodecnt += 1\n    end\n    n1 = getnode(graph,1)\n    @constraint(n1,n1[:x][1] == 0)\n    for i=1:n_nodes-1\n        @linkconstraint(graph, nodes[i+1][:x][1] == nodes[i][:x][M] + nodes[i][:u][M],attach=nodes[i+1])\n    end\n\n    #First node gets initial condition\n    kwargs_collection = [\n        (\"default\",Dict(:print_level=>MadNLP.ERROR)),\n        (\"schur\",Dict(:linear_solver=>MadNLPSchur,  :schur_custom_partition=>true,:print_level=>MadNLP.ERROR)),\n        (\"schwarz\",Dict(:linear_solver=>MadNLPSchwarz,:schwarz_custom_partition=>true,:print_level=>MadNLP.ERROR))\n    ]\n    for (name,kwargs) in kwargs_collection\n        @testset \"plasmo-$name\" begin\n            MadNLP.optimize!(graph;kwargs...);\n            @test MadNLP.termination_status(graph.optimizer) == MOI.LOCALLY_SOLVED\n            @test solcmp([0.0,0.03137979101284875,0.0627286139604959,0.09401553133948139,0.12520966673966746,0.15628023531552773,0.18719657416707308,0.21792817260043182,0.24844470223822107,0.2787160469499936], value.(getnode(graph,1)[:x][1:10]))\n            @test solcmp([-0.0627595821831224,-0.06269764605256355,-0.06257383491492904,-0.06238827095686386,-0.06214113730759117,-0.06183267785818605,-0.06146319702088434,-0.06103305942866446,-0.06054268957539879,-0.05999257139692946], dual.(getnode(graph,1)[:dynamics][1:10]))\n            @test solcmp([-1.574246826343827e-10,-1.5726901766520537e-10,-1.5695784406668639e-10,-1.5649147434189076e-10,-1.5587037679839438e-10,-1.5509517501550025e-10,-1.541666471342132e-10,-1.5308572497187857e-10,-1.5185349296508524e-10,-1.504711869423148e-10], dual.(UpperBoundRef.(getnode(graph,1)[:u][1:10])))\n            @test solcmp([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0], dual.(LowerBoundRef.(getnode(graph,1)[:u][1:10])))\n        end\n    end\nend\n", "meta": {"hexsha": "ebf6b602877cc2c7b0c351968810bad9be39042c", "size": 2332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lib/MadNLPGraph/test/runtests.jl", "max_stars_repo_name": "sshin23/MadNLP", "max_stars_repo_head_hexsha": "5f0a21d55c953e4cb970691651f058a523d6078a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2020-09-17T15:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T00:04:04.000Z", "max_issues_repo_path": "lib/MadNLPGraph/test/runtests.jl", "max_issues_repo_name": "sshin23/MadNLP", "max_issues_repo_head_hexsha": "5f0a21d55c953e4cb970691651f058a523d6078a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 85, "max_issues_repo_issues_event_min_datetime": "2020-09-25T13:20:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:21:34.000Z", "max_forks_repo_path": "lib/MadNLPGraph/test/runtests.jl", "max_forks_repo_name": "sshin23/MadNLP", "max_forks_repo_head_hexsha": "5f0a21d55c953e4cb970691651f058a523d6078a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-09-17T17:25:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T01:25:09.000Z", "avg_line_length": 51.8222222222, "max_line_length": 315, "alphanum_fraction": 0.6578044597, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7542748426558173}}
{"text": "function li_ikegami(grid, vals)\n    n = length(grid)\n    m = length(vals)\n\n    if n != m\n        print(\"grid size and value siza is not equal\")\n    end\n\n    mat = [grid vals]\n    mat = sortrows(mat, by = x->(x[1]))\n    mat = transpose(mat)\n\n    grid = mat[1, :]\n    vals = mat[2, :]\n\n    slope = Array(Float64, n-1)\n    for i in 1: (n-1)\n        temp_slope = (vals[i] - vals[i+1]) / (grid[i] - grid[i+1])\n        slope[i] = temp_slope\n    end\n    function approx(x_val)\n\n        if x_val > maximum(grid)\n            return print(\"too big value ...\")\n        end\n\n        if x_val < minimum(grid)\n            return print(\"too small value ...\")\n        end\n\n        interval = 1\n        for j in 1:(n-1)\n            if x_val > grid[j+1]\n                interval += 1\n            else break\n            end\n        end\n        return slope[interval] * (x_val - grid[interval]) + vals[interval]\n    end\n\n    function approx{T<:Real}(x::AbstractVector{T})\n        n = length(x)\n        out = Array(Float64, n)\n        for i in 1:n\n            out[i] = approx(x[i])\n        end\n        return out\n    end\n\n    return approx\nend\n", "meta": {"hexsha": "fedc924d6daf12d965f6d9d1a77012b75bec0d50", "size": 1123, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_interp.jl", "max_stars_repo_name": "keiikegami/Linear---Interpolation-", "max_stars_repo_head_hexsha": "1513f775aff91aeda0fe1cc2d7e6dd99e24852f0", "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": "linear_interp.jl", "max_issues_repo_name": "keiikegami/Linear---Interpolation-", "max_issues_repo_head_hexsha": "1513f775aff91aeda0fe1cc2d7e6dd99e24852f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-05-22T01:52:56.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-23T07:07:05.000Z", "max_forks_repo_path": "linear_interp.jl", "max_forks_repo_name": "keiikegami/Linear---Interpolation-", "max_forks_repo_head_hexsha": "1513f775aff91aeda0fe1cc2d7e6dd99e24852f0", "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.5961538462, "max_line_length": 74, "alphanum_fraction": 0.4915405165, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8080672181749421, "lm_q1q2_score": 0.7542748418202232}}
{"text": "using CSV\nusing LinearAlgebra: dot, I\nusing CairoMakie\n\nconst \u03a3 = [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 \u03c3\u00b2 = 1\n\nconst \u03a32 = -0.95 * v * v' + I(3)\n\nf(x) = abs2(dot(v, \u03a3 * x)) / (dot(x, \u03a3 * x) + \u03c3\u00b2 * dot(x, x))\n\ng(x) = abs2(dot(v, \u03a32 * x)) / (dot(x, \u03a32 * x) + \u03c3\u00b2 * 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\u03a9 = Triangulation(model)\n\u0393 = BoundaryTriangulation(model)\nd\u03a9 = LebesgueMeasure(\u03a9,degree)\nd\u0393 = LebesgueMeasure(\u0393,degree)\n\n# Manufactured solution\nu(x) = x[1]+x[2]\n\n# Parameter-dependent weak form\na(p,u,v) = \u222b( (p*p)*\u2207(v)\u22c5\u2207(u) )*d\u03a9\nl(v) = \u222b( -v*\u0394(u) )*d\u03a9\n\n# Objective function in terms of primal solution\n# (squared distance wrt exact solution u on \u03a9 and \u0393\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) = \u222b( abs2(u-v) )*d\u03a9 + \u222b( abs2(u-v) )*d\u0393\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, \u2207fp = f_\u2207f(p)\nfunction f_\u2207f(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 = \u2207(j)(u) # autodiff\n  b = assemble_vector(dj_du,V)\n  \u03bb = FEFunction(V,A\\b) # assuming A self-adjoint\n  # we want to have something like this\n  # op_t = AdjointFEOperator(op, \u2207(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  \u2202a_\u2202p = \u2207(x -> a(x,u,\u03bb))(p) # Autodiff\n  \u2207fp = -1*assemble_vector(\u2202a_\u2202p,P)\n  fp, \u2207fp\nend\n\n# run for a given realization of p\np = FEFunction(P,rand(num_free_dofs(P)).+1)\nfp, \u2207fp = f_\u2207f(p)\n# Print results\n@show fp\nwritevtk(\u03a9,\"trian\",cellfields=[\"\u2207fp\"=>FEFunction(P,\u2207fp)])\n\nfunction df_dp(uvec,pvec,\u03bbvec)\n  da(p,u,v,dp) = (2*p*dp)*\u2207(v)\u22c5\u2207(u)\n  uh = FEFunction(U,uvec)\n  ph = FEFunction(P,pvec)\n  \u03bbh = FEFunction(V,\u03bbvec)\n  t = FESource((dp)->da(ph,uh,\u03bbh,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": "g(a,b) = 3a+2b", "meta": {"hexsha": "ee35afc1a395831cd28c1b4a3df3947b2ab4af71", "size": 14, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/g().jl", "max_stars_repo_name": "arubhardwaj/CeterisParibus.jl", "max_stars_repo_head_hexsha": "ae0a24f50af4fcd0ec79ecec9ad2ccb65a1f3dd7", "max_stars_repo_licenses": ["MIT"], "max_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": "arubhardwaj/CeterisParibus.jl", "max_issues_repo_head_hexsha": "ae0a24f50af4fcd0ec79ecec9ad2ccb65a1f3dd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/g().jl", "max_forks_repo_name": "arubhardwaj/CeterisParibus.jl", "max_forks_repo_head_hexsha": "ae0a24f50af4fcd0ec79ecec9ad2ccb65a1f3dd7", "max_forks_repo_licenses": ["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": 14, "alphanum_fraction": 0.5, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7542748364953741}}
{"text": "using Test, SimplePadics, SimplePolynomials\n\n\nx = Padic{5}(-1)\n\n@test x * x == 1\n@test x == -1\n\ny = sqrt(x)\n@test y * y == -1\n\n@test x + x == 2x\n@test x + 1 == 0\n@test x - 1 == -Padic{5}(2)\n@test valuation(x) == 0\n@test valuation(x / 5) == -1\n@test valuation(5x) == 1\n@test base(x) == 5\n@test x // 5 == x / 5\n@test x / x == 1\n@test x // x == Padic{5}(1)\n\ny = exp(5x)\n@test log(y) == -5\n\n@test Padic{5}(2 // 3) * 3 == 2\n\ns = string(x)\n@test s[1] == '\u2026'\n@test s[end-5:end] == \".0_{5}\"\n\na = Padic{17}(1000)\nd = digits(a)\n@test d[1] + 17 * d[2] + 17^2 * d[3] == 1000\n\nset_precision(20)\n@test get_precision() == 20\n\na = Padic{5}(100)\n@test abs(a) == 1 / 25\n@test abs(a) == abs(-a)\n@test abs(0a) == 0\n\n\nx = getx()\nF = x^2 + 1\n@test has_p_root(F, 5)[1]\nt = p_root(F, 5)\n@test F(t) == 0\n", "meta": {"hexsha": "4e774dfddec89a54e2fbcce5673a72d262eee660", "size": 779, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "scheinerman/SimplePadics.jl", "max_stars_repo_head_hexsha": "69c27fd6fef9f04c7ee171d39c718188ba281a4d", "max_stars_repo_licenses": ["MIT"], "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": "scheinerman/SimplePadics.jl", "max_issues_repo_head_hexsha": "69c27fd6fef9f04c7ee171d39c718188ba281a4d", "max_issues_repo_licenses": ["MIT"], "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": "scheinerman/SimplePadics.jl", "max_forks_repo_head_hexsha": "69c27fd6fef9f04c7ee171d39c718188ba281a4d", "max_forks_repo_licenses": ["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.58, "max_line_length": 44, "alphanum_fraction": 0.514762516, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7542748336773081}}
{"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# \u03c4      - 1/learning rate\nfunction lca(s::Vector{Float64}, D::Matrix{Float64}; T_soft::Float64=0.1,\n             iter::Int=10000, \u03c4::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        \u0394u = (b  - u - G*a)/\u03c4; \n        u += \u0394u;\n\n        if(norm(\u0394u) < 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": "const TreesMap = BitArray{2}\n\nfunction readinput(strs)\n    TreesMap(transpose(hcat([[c == '#' for c \u2208 l] for l \u2208 strs]...)))\nend\n\n\n# First Half\n\nfunction treesencountered\u2081(tmap)\n    #= =========================================================================\n    The trees map of the problem can be projected on cilindrical discrete plane\n    where cilinder's height and perimeter are respectively map\u2095 and map\u2097.\n    The movement happens on a line on a discrete plane.\n    The equation for a line starting at (0,0) in a cilindrical semi-infinite\n    discrete plane is x = m * y mod map\u2097, where x, y are integers,\n    slope m is a rational and m * y is rounded to the nearest integer.\n    In our case m = m\u2095 / m\u1d65 (right slope / down slope) and the path is not\n    this line, but only the dots on this line with vertical coordinate\n    multiple of m\u1d65 (jumping).\n    ========================================================================= =#\n        \n    m\u2095 = 3\n    m\u1d65 = 1\n    m = m\u2095 // m\u1d65\n    map\u2095, map\u2097 = size(tmap)\n    f(y) = tmap[y + 1, Int(m * y) % map\u2097 + 1] # Arrays in Julia start from 1\n    count(f, 0:m\u1d65:map\u2095 - 1) # Arrays in Julia start from 1\nend\n\npuzzleinput = readlines(\"inputs/day03.txt\")\ntreesmap = readinput(puzzleinput)\n\ntreesencountered\u2081(treesmap)\n\n\n# Second Half\n\nfunction treesencountered\u2082(tmap)\n\n    m\u2095 = [1, 3, 5, 7, 1]\n    m\u1d65 = [1, 1, 1, 1, 2]\n    M = collect(zip(m\u2095, m\u1d65))\n    map\u2095, map\u2097 = size(tmap)\n    f(m) = y -> tmap[y + 1, Int(m[1] // m[2] * y) % map\u2097 + 1]\n    [count(f(m), 0:m[2]:map\u2095 - 1) for m \u2208 M]\nend\n\npuzzleinput = readlines(\"inputs/day03.txt\")\ntreesmap = readinput(puzzleinput)\n\nprod(treesencountered\u2082(treesmap))\n# Multiply together the number of trees encountered on each of the listed slopes\n", "meta": {"hexsha": "b16a28bd720db364182296095389a50e5c94a76a", "size": 1729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day03.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": "day03.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": "day03.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": 32.0185185185, "max_line_length": 80, "alphanum_fraction": 0.5974551764, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7542748310340124}}
{"text": "using JuSwarm, StaticArrays, Test\nimport Optim\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\nN = 2\nopts = PSOOptions(N; SwarmSize = 1000, \n                     HybridOptimizer = Optim.LBFGS(),\n                     Display = \"none\",\n                     UseParallel = true)\n\nsol = psoptimize(rosenbrockfunc,opts)\n\n@test sol.fbest <= sol.fbestPSO\n\n@test sol.fbestPSO <= 1.0e-6\n\n@test sol.fbest <= 1.0e-10", "meta": {"hexsha": "301408d94940c7ea0d480fc28330b722a2b06945", "size": 527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rosenbrock_function_test.jl", "max_stars_repo_name": "GrantHecht/JuSwarm", "max_stars_repo_head_hexsha": "adc3ff8a0dcd1d4b7db55c636a2b612dbc157fd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-14T14:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T14:58:11.000Z", "max_issues_repo_path": "test/rosenbrock_function_test.jl", "max_issues_repo_name": "GrantHecht/JuSwarm.jl", "max_issues_repo_head_hexsha": "adc3ff8a0dcd1d4b7db55c636a2b612dbc157fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-20T13:46:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T01:30:40.000Z", "max_forks_repo_path": "test/rosenbrock_function_test.jl", "max_forks_repo_name": "GrantHecht/JuSwarm", "max_forks_repo_head_hexsha": "adc3ff8a0dcd1d4b7db55c636a2b612dbc157fd5", "max_forks_repo_licenses": ["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.9583333333, "max_line_length": 55, "alphanum_fraction": 0.5673624288, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7542748280411761}}
{"text": "module TargetPlot\nimport Base.MathConstants as cons\nimport Plots as plt\nplt.pyplot()\n\nfunction f(x, y)\n    return -20.0 * exp(-0.2 * sqrt(0.5 * (x^2 + y^2))) -\n  exp(0.5 * (cos(2.0 * pi * x) + cos(2.0 * pi * y))) +  cons.e + 20.0\n  #  ((1.0 - y) * sin(x))^2 + (y * (2.0 - x))^2\nend\n\nconst plot = function ()\n    x = -5.0:0.1:5.0\n    y = -5.0:0.1:5.0\n    # plt.heatmap(x, y, f)\n    plt.plot(x, y, f, st=:wireframe)\n    plt.png(\"my-plots/wireframe.png\")\nend\n\nend", "meta": {"hexsha": "baf88def9881f8c21436daed0a29275ee0f31435", "size": 460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "my-plots/MyPlots/target-plot.jl", "max_stars_repo_name": "applied-math-coding/heuristic", "max_stars_repo_head_hexsha": "b1ebb17c1f3026eef9b553625d6a77952b88dee7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "my-plots/MyPlots/target-plot.jl", "max_issues_repo_name": "applied-math-coding/heuristic", "max_issues_repo_head_hexsha": "b1ebb17c1f3026eef9b553625d6a77952b88dee7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my-plots/MyPlots/target-plot.jl", "max_forks_repo_name": "applied-math-coding/heuristic", "max_forks_repo_head_hexsha": "b1ebb17c1f3026eef9b553625d6a77952b88dee7", "max_forks_repo_licenses": ["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": 69, "alphanum_fraction": 0.5347826087, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7542690463306492}}
{"text": "using Test\nusing Solvent\nusing StaticArrays\nusing LinearAlgebra\nusing SparseArrays\nusing Random\nusing Printf\n\n# Creates a Laplacian matrix based on the code from: http://math.mit.edu/~stevenj/18.303/lecture-10.html\n# construct the (M+1)xM matrix D, not including the 1/dx factor\nsdiff1(M) = [ [1.0 spzeros(1, M-1)]; spdiagm(1=>ones(M-1)) - I ]\n\n# make the discrete -Laplacian in 2d, with Dirichlet boundaries\nfunction Laplacian(Nx, Ny, Lx, Ly)\n    dx = Lx / (Nx+1)\n    dy = Ly / (Ny+1)\n    Dx = sdiff1(Nx) / dx\n    Dy = sdiff1(Ny) / dy\n    Ax = Dx' * Dx\n    Ay = Dy' * Dy\n    return kron(spdiagm(0=>ones(Ny)), Ax) + kron(Ay, spdiagm(0=>ones(Nx)))\nend\n\n@testset \"Solvent Laplacian: CG\" begin\n    T = Float64\n    Lx = 1\n    Ly = 1\n    Nx = 10\n    Ny = 10\n    A = Laplacian(Nx, Ny, Lx, Ly)\n    n, _ = size(A)\n    @info \"Size of matrix A: ($n, $n)\"\n    b = rand(T, n)\n    x = rand(T, n)\n\n    mulbyA!(y, x) = (y .= A * x)\n\n    rtol = sqrt(eps(T))\n    atol = eps(T)\n    solver_type = ConjugateGradientMethod(M = 100)\n    linearsolver = LinearSolver(\n        mulbyA!,\n        solver_type,\n        x;\n        rtol = rtol,\n        atol = atol,\n    )\n\n    x0 = copy(x)\n    linearsolve!(linearsolver, x, b)\n    @test norm(A * x - b) < rtol * norm(A * x0 - b)\n\nend\n\n\n# Tests effectiveness of Jacobi preconditioner using specially designed matrix from:\n# http://www.math.iit.edu/~fass/477577_Chapter_16.pdf\n@testset \"Solvent Preconditioned Jacobi: CG\" begin\n    T = Float64\n    n = 1000\n    dv0 = .5 .+ .\u221a(1:n)\n    dv1 = ones(n - 1)\n    dv2 = ones(n - 100)\n    A = spdiagm(0=>dv0) + spdiagm(1=>dv1) + spdiagm(-1=>dv1) + \n        spdiagm(100=>dv2) + spdiagm(-100=>dv2)\n    @info \"Size of matrix A: ($n, $n)\"\n    b = ones(T, 1000)\n    x = rand(T, n)\n\n    mulbyA!(y, x) = (y .= A * x)\n\n    rtol = sqrt(eps(T))\n    atol = eps(T)\n    solver_type = ConjugateGradientMethod(M = 100)\n    identitysolver = LinearSolver(\n        mulbyA!,\n        solver_type,\n        x;\n        rtol = rtol,\n        atol = atol,\n    )\n    jacobisolver = LinearSolver(\n        mulbyA!,\n        solver_type,\n        x;\n        pc_alg = Jacobi(),\n        rtol = rtol,\n        atol = atol,\n    )\n\n    x0 = copy(x)\n    jacobiiters = linearsolve!(jacobisolver, x, b)\n    @test norm(A * x - b) < rtol * norm(A * x0 - b)\n    identityiters = linearsolve!(identitysolver, x0, b)\n    @test jacobiiters < identityiters\nend", "meta": {"hexsha": "f97e429ff9f3e96625116048cb6d9cb1e740823f", "size": 2370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cg.jl", "max_stars_repo_name": "CliMA/SystemSolvers", "max_stars_repo_head_hexsha": "366d997df3acfbd1d5b412b3aeb71a8cc964f259", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-08-05T18:20:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-07T07:41:07.000Z", "max_issues_repo_path": "test/cg.jl", "max_issues_repo_name": "CliMA/SystemSolvers", "max_issues_repo_head_hexsha": "366d997df3acfbd1d5b412b3aeb71a8cc964f259", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-08-05T17:59:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T20:52:30.000Z", "max_forks_repo_path": "test/cg.jl", "max_forks_repo_name": "CliMA/Solvent.jl", "max_forks_repo_head_hexsha": "366d997df3acfbd1d5b412b3aeb71a8cc964f259", "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.6875, "max_line_length": 104, "alphanum_fraction": 0.570464135, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723354, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7542690444099475}}
{"text": "\nusing FFTW\nusing Plots\n\na = 1        # Thermal diffusivity constant\nL = 100      # 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 = zeros(N)\nu0[(L/2 - L/10)/dx:(L/2 + L/10)/dx] = 1\n\n# Simulate in Fourier frequency domain\n# t = 0:0.1:10\n# [t,uhat]=ode45(@(t,uhat)rhsHeat(t,uhat,kappa,a),t,fft(u0));\n\n# for k = 1:length(t) # iFFT to return to spatial domain\n#     u(k,:) = ifft(uhat(k,:))\n# end\n\n\n# Plot solution in time\nfigure, waterfall((u(1:10:end,:)));\nfigure, imagesc(flipud(u));\n\n%% FIGURES (PRODUCTION)\nfigure\nCC = colormap(jet(100));\ndt = 0.1;\nfor k = 1:100\n    u(k,:) = ifft(uhat(k,:));\n    if(mod(k-1,10)==0)\n        plot(x,u(k,:),'Color',CC(k,:),'LineWidth',1.5)\n        hold on, grid on, drawnow\n    end   \nend\n% xlabel('Spatial variable, x')\n% ylabel('Temperature, u(x,t)')\naxis([-50 50 -.1 1.1])\nset(gca,'LineWidth',1.2,'FontSize',12);\nset(gcf,'Position',[100 100 550 220]);\nset(gcf,'PaperPositionMode','auto')\n% print('-depsc2', '-loose', '../../figures/FFTHeat1');\n\n%\nfigure\nsubplot(1,2,1)\nh=waterfall(u(1:10:end,:));\nset(h,'LineWidth',2,'FaceAlpha',.5);\ncolormap(jet/1.5)\nview(22,29)\nset(gca,'LineWidth',1.5)\nset(gca,'XTick',[0 500 1000],'XTickLabels',{})\nset(gca,'ZTick',[0 .5 1],'ZTickLabels',{})\nset(gca,'YTick',[0 5 10],'YTickLabels',{})\n\nsubplot(1,2,2)\nimagesc(flipud(u));\nset(gca,'LineWidth',1.5)\nset(gca,'XTick',[0 500 1000],'XTickLabels',{})\nset(gca,'YTick',[0 50 100],'YTickLabels',{})\n\ncolormap jet\nset(gcf,'Position',[100 100 600 250])\nset(gcf,'PaperPositionMode','auto')\n% print('-depsc2', '-loose', '../../figures/FFTHeat2');", "meta": {"hexsha": "6f4de800bb1a515d4ded0c299bbd93323b926653", "size": 1752, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH02/CH02_SEC03_1_FFTHeat.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_1_FFTHeat.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_1_FFTHeat.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.3333333333, "max_line_length": 61, "alphanum_fraction": 0.6221461187, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7542572431369786}}
{"text": "@testset \"argmax\" begin\n    arg, val = GeometryTypes.argmax(sin, range(0, stop=\u03c0, length=101))\n    @test arg \u2248 \u03c0/2\n    @test val \u2248 1\n\n    arg, val = GeometryTypes.argmax(cos, range(0, stop=\u03c0, length=101))\n    @test arg \u2248 0  # 0, not \u03c0, because argmax requires a subsequent value to be *strictly better* than the current best\n    @test val \u2248 1.0\n\n    @test @allocated(GeometryTypes.argmax(sin, range(0, stop=\u03c0, length=101))) == 0\n\n    @test_throws ArgumentError GeometryTypes.argmax(identity, [])\nend\n\n@testset \"extrema\" begin\n    xs = [GeometryTypes.Vec2f0(1f0, 1f0), GeometryTypes.Vec2f0(0.5f0, 1.5f0)]\n    extr = extrema(xs)\n\n    @test extr[1] \u2248 GeometryTypes.Vec2f0(0.5f0, 1f0)\n    @test extr[2] \u2248 GeometryTypes.Vec2f0(1f0, 1.5f0)\n\n    @testset \"minimum\" begin\n        val = minimum(xs)\n        @test val \u2248 extr[1]\n    end\n\n    @testset \"maximum\" begin\n        val = maximum(xs)\n        @test val \u2248 extr[2]\n    end\nend\n", "meta": {"hexsha": "2aba87985d7c50005b5c98518a5b326fd2a5a9e3", "size": 922, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/baseutils.jl", "max_stars_repo_name": "goretkin/GeometryTypes.jl", "max_stars_repo_head_hexsha": "c42a2b336ac0e8135f71f4c0a48f3766ce5127e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2015-03-18T00:48:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T13:43:26.000Z", "max_issues_repo_path": "test/baseutils.jl", "max_issues_repo_name": "goretkin/GeometryTypes.jl", "max_issues_repo_head_hexsha": "c42a2b336ac0e8135f71f4c0a48f3766ce5127e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 163, "max_issues_repo_issues_event_min_datetime": "2015-04-17T03:54:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T12:12:39.000Z", "max_forks_repo_path": "test/baseutils.jl", "max_forks_repo_name": "goretkin/GeometryTypes.jl", "max_forks_repo_head_hexsha": "c42a2b336ac0e8135f71f4c0a48f3766ce5127e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51, "max_forks_repo_forks_event_min_datetime": "2015-06-23T21:49:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T00:01:22.000Z", "avg_line_length": 28.8125, "max_line_length": 119, "alphanum_fraction": 0.636659436, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7542572389840907}}
{"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, \u0127, 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(\u03c1::Unitful.Density, g::Unitful.Acceleration)\n\t\nRadius of a spherical planet of density `\u03c1` with surface gravitational acceleration of `g`.\n\"\"\"\nplanetary_radius(\u03c1::Unitful.Density, g::Unitful.Acceleration) = 3g / (4G * \u03c0 * \u03c1) |> u\"m\"\n\n\"\"\"\n\tplanetary_radius(\u03c1::Unitful.Density, ve::Unitful.Velocity)\n\t\nRadius of a spherical planet of density `\u03c1` with surface escape velocity `ve`.\n\"\"\"\nplanetary_radius(\u03c1::Unitful.Density, ve::Unitful.Velocity) = sqrt(3ve^2 / (8G * \u03c0 * \u03c1)) |> 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\u03c0^2r^3}{Gm}}``\n\"\"\"\norbital_period(m::Unitful.Mass, r::Unitful.Length) = sqrt((4\u03c0^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\u03c0^2}}``\n\"\"\"\norbital_radius(m::Unitful.Mass, t::Unitful.Time) = cbrt((t^2 * G * m)/(4\u03c0^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\u03c0 * 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\u03c0a}{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\u03c0 * 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\u03c0^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\u03c0^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, \u03c1_primary::Unitful.Density, \u03c1_satellite::Unitful.Density)\n   \nRigid body approximation of the Roche limit for a body with radius `r_primary` and density `\u03c1_primary`, approached by a body with density `\u03c1_satellite`.\n\n``r_r = r\\\\sqrt[2]{\\\\frac{2\u03c1_p}{\u03c1_s}}``\n\nwhere ``r`` and ``\u03c1_p`` are the radius and density of the central body, and \u03c1_s is the density of the orbiting body.\n\"\"\"\nroche_limit(r_primary::Unitful.Length, \u03c1_primary::Unitful.Density, \u03c1_satellite::Unitful.Density) = r_primary * cbrt(2\u03c1_primary / \u03c1_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\u03bc = G * (m1 + m2)\n\tw = 1/x0 - v0^2/2\u03bc\n\t\n\treturn (asin(sqrt(w * x)) - sqrt(w * x * (1 - w * x))) / sqrt(2\u03bc * 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\u03bc = G * (m1 + m2)\n\tw = 1/x0 - v0^2/2\u03bc\n\tp = cbrt(9\u03bc * 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\u03bc = G * (m1 + m2)\n\tw = 1/x0 - v0^2/2\u03bc\n\tp = cbrt(9\u03bc * 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\u03bc = ustrip(G) * (m1 + m2)\n\tw = 1/x0 - v0^2/2\u03bc\n\tp = cbrt(9\u03bc * 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    \u03b8 ~ Beta(1, 1)\n    k ~ Binomial(n, \u03b8)\n    return k, \u03b8\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 StatsBase\nusing Base.Test\n\nn = 5000\n\n# 1D integer counts\n\nx = rand(1:5, n)\nw = weights(rand(n))\n\nc = counts(x, 5)\n@test size(c) == (5,)\nc0 = Int[countnz(x .== i) for i in 1 : 5]\n@test c == c0\n@test counts(x .+ 1, 2:6) == c0\n@test_approx_eq proportions(x, 1:5) (c0 ./ n)\n\nc = counts(x)\n@test size(c) == (5,)\nc0 = Int[countnz(x .== i) for i in 1 : 5]\n@test c == c0\n@test counts(x .+ 1, 2:6) == c0\n@test_approx_eq proportions(x) (c0 ./ n)\n\nc = counts(x, 5, w)\n@test size(c) == (5,)\nc0 = Float64[sum(w.values[x .== i]) for i in 1 : 5]\n@test_approx_eq c c0\n@test_approx_eq counts(x .+ 1, 2:6, w) c0\n@test_approx_eq proportions(x, 1:5, w) (c0 ./ sum(w))\n\nc = counts(x, w)\n@test size(c) == (5,)\nc0 = Float64[sum(w.values[x .== i]) for i in 1 : 5]\n@test_approx_eq c c0\n@test_approx_eq counts(x .+ 1, 2:6, w) c0\n@test_approx_eq proportions(x, w) (c0 ./ sum(w))\n\n# 2D integer counts\n\nx = rand(1:4, n)\ny = rand(1:5, n)\nw = weights(rand(n))\n\nc = counts(x, y, (4, 5))\n@test size(c) == (4, 5)\nc0 = Int[countnz((x .== i) & (y .== j)) for i in 1 : 4, j in 1 : 5]\n@test c == c0\n@test counts(x .+ 2, y .+ 3, (3:6, 4:8)) == c0\n@test_approx_eq proportions(x, y, (1:4, 1:5)) (c0 ./ n)\n\nc = counts(x, y)\n@test size(c) == (4, 5)\nc0 = Int[countnz((x .== i) & (y .== j)) for i in 1 : 4, j in 1 : 5]\n@test c == c0\n@test counts(x .+ 2, y .+ 3, (3:6, 4:8)) == c0\n@test_approx_eq proportions(x, y,) (c0 ./ n)\n\nc = counts(x, y, (4, 5), w)\n@test size(c) == (4, 5)\nc0 = Float64[sum(w.values[(x .== i) & (y .== j)]) for i in 1 : 4, j in 1 : 5]\n@test_approx_eq c c0\n@test_approx_eq counts(x .+ 2, y .+ 3, (3:6, 4:8), w) c0\n@test_approx_eq proportions(x, y, (1:4, 1:5), w) (c0 ./ sum(w))\n\nc = counts(x, y, w)\n@test size(c) == (4, 5)\nc0 = Float64[sum(w.values[(x .== i) & (y .== j)]) for i in 1 : 4, j in 1 : 5]\n@test_approx_eq c c0\n@test_approx_eq counts(x .+ 2, y .+ 3, (3:6, 4:8), w) c0\n@test_approx_eq proportions(x, y, w) (c0 ./ sum(w))\n\n\n# count map\n\nx = [\"a\", \"b\", \"a\", \"a\", \"b\", \"c\"]\nw = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5]\n\ncm = countmap(x)\n@test cm[\"a\"] == 3\n@test cm[\"b\"] == 2\n@test cm[\"c\"] == 1\npm = proportionmap(x)\n@test_approx_eq pm[\"a\"] (1/2)\n@test_approx_eq pm[\"b\"] (1/3)\n@test_approx_eq pm[\"c\"] (1/6)\n\ncm = countmap(x, weights(w))\n@test cm[\"a\"] == 5.5\n@test cm[\"b\"] == 4.5\n@test cm[\"c\"] == 3.5\npm = proportionmap(x, weights(w))\n@test_approx_eq pm[\"a\"] (5.5 / 13.5)\n@test_approx_eq pm[\"b\"] (4.5 / 13.5)\n@test_approx_eq pm[\"c\"] (3.5 / 13.5)\n", "meta": {"hexsha": "7a0b742beb1ac4b5be84a8ef78c6841cbbee52d3", "size": 2422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/counts.jl", "max_stars_repo_name": "JuliaPackageMirrors/StatsBase.jl", "max_stars_repo_head_hexsha": "99ee7c3d3638dfa18a104c89b9de00baa663abc2", "max_stars_repo_licenses": ["MIT"], "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/counts.jl", "max_issues_repo_name": "JuliaPackageMirrors/StatsBase.jl", "max_issues_repo_head_hexsha": "99ee7c3d3638dfa18a104c89b9de00baa663abc2", "max_issues_repo_licenses": ["MIT"], "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/counts.jl", "max_forks_repo_name": "JuliaPackageMirrors/StatsBase.jl", "max_forks_repo_head_hexsha": "99ee7c3d3638dfa18a104c89b9de00baa663abc2", "max_forks_repo_licenses": ["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.2291666667, "max_line_length": 77, "alphanum_fraction": 0.5474814203, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.754200124963038}}
{"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 Entropia\nusing Test\n\ntol = 1e-3\n\n@testset \"bandt and pompe\"  begin\n    x = [4, 7, 9, 10, 6, 11, 3]\n\n    @testset \"test 00\" begin\n        e = bandt_and_pompe(x, 2)\n        @test abs(e - 0.918) <= tol\n    end\n    \n    @testset \"test 01\" begin\n        e = bandt_and_pompe(x, 3)\n        @test abs(e - 1.522) <= tol\n    end\nend\n\n@testset \"bandt and pompe normal\" begin\n    n = 2048\n    t = [i/n for i in 0:n]\n\n    @testset \"test 00\" begin\n        x = sin.(2\u03c0 * 15 * t)\n        e = bandt_and_pompe_normal(x, 6)\n        @test abs(e - 0.1579) <= tol\n    end\n    \n    @testset \"test 01\" begin\n        x = (0.5*sin.(2\u03c0*5*t).+1) .* (sin.(2\u03c0*50*t.^2+2\u03c0*10*t))\n        e = bandt_and_pompe_normal(x, 6)\n        @test abs(e - 0.2625) <= tol\n    end    \nend\n\n@testset \"weight entropy\" begin\n    @testset \"test 00\" begin\n        x = [4, 7, 9, 10, 6, 11, 3]\n        e = weight_entropy(x)\n        @test abs(e - 0.9801) <= tol\n    end\nend\n\n@testset \"complexity_entropy\" begin\n    @testset \"test 00\" begin\n        x = [4, 7, 9, 10, 6, 11, 3]\n        e, jsd, cjs = complexity_entropy(x)\n        @test abs(e - 0.5888) <= tol\n        @test abs(jsd - 0.2235) <= tol\n        @test abs(cjs - 0.2900) <= tol\n    end\nend", "meta": {"hexsha": "15907a51fcb37d480b335eb544c1a214c45d2e79", "size": 1197, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jbarberia/Entropia.jl", "max_stars_repo_head_hexsha": "a5ceacf2c654b1abdfb13ad6b87fe50fa97cceaa", "max_stars_repo_licenses": ["MIT"], "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": "jbarberia/Entropia.jl", "max_issues_repo_head_hexsha": "a5ceacf2c654b1abdfb13ad6b87fe50fa97cceaa", "max_issues_repo_licenses": ["MIT"], "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": "jbarberia/Entropia.jl", "max_forks_repo_head_hexsha": "a5ceacf2c654b1abdfb13ad6b87fe50fa97cceaa", "max_forks_repo_licenses": ["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.5849056604, "max_line_length": 63, "alphanum_fraction": 0.5137844612, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7541962838244187}}
{"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\u00e1metros 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 \u00e9sta se le agrega la asunci\u00f3n 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\u00e9todo de resoluci\u00f3n y tiempo al cual parar.\nprob_neuralode = NeuralODE(dudt2, tspan, Tsit5(), saveat = tsteps)\n\n# Funciones que guardar\u00e1n la predicci\u00f3n 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\u00f3n con par\u00e1metros reales.\n# \u00c9sto se hace en dos pasos, primero con el optimizador ADAM para acercarnos r\u00e1pidamente\n# al m\u00ednimo, y una vez cerca utilizamos Limited-memory BFGS para un ajuste m\u00e1s 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": "using DelimitedFiles\n\nfunction ReadData(fname::AbstractString)\n    return vec(readdlm(fname, ',', Int))\nend\n\nfunction Median(data::Array)\n    if isodd(length(data))\n        x0 = sort(data)[div(length(data)-1,2)]\n        x1 = sort(data)[div(length(data)+1,2)]\n\n        return x0, x1\n    else\n        x0 = sort(data)[div(length(data),2)]\n        return x0\n    end\nend\n\n    \n# the optimal position will be the median\nfunction Part1(data::Array)\n    if isodd(length(data))\n        x0, x1 = Median(data)\n\n        c0 = sum(abs(x0-x) for x in data)\n        c1 = sum(abs(x1-x) for x in data)\n\n        return min(c0, c1)\n    else\n        x0 = Median(data)\n        return sum(abs(x0-x) for x in data)\n    end\nend\n\n# the optimal position will be somewhere between the average and the median\nfunction Part2(data::Array)\n    xAvg = round(Int, sum(data)/length(data))\n    xMed = isodd(length(data)) ? min(Median(data)) : Median(data)\n\n    # search between xAvg and xMed for the minimum\n    x0, x1 = min(xAvg, xMed), max(xAvg, xMed)\n    cMin = sum(data)*(sum(data)+1)\n    cost = x -> div(sum(abs(y-x)*(1+abs(y-x)) for y in data),2)\n    for x in x0:x1\n        c = cost(x)\n        cMin = c < cMin ? c : cMin\n    end\n\n    return cMin\nend\n\n\n#data = [16,1,2,0,4,2,7,1,2,14]\ndata = ReadData(\"../data/day7.txt\")\n\nprintln(Part1(data))\nprintln(Part2(data))\n", "meta": {"hexsha": "9c339d54f69f70478e159f7c61d1c88e5f0f873e", "size": 1333, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day7.jl", "max_stars_repo_name": "andrew0796/AdventOfCode_2021", "max_stars_repo_head_hexsha": "9d2e6f19cb555f89dac141cc081da4ce58558a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day7.jl", "max_issues_repo_name": "andrew0796/AdventOfCode_2021", "max_issues_repo_head_hexsha": "9d2e6f19cb555f89dac141cc081da4ce58558a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day7.jl", "max_forks_repo_name": "andrew0796/AdventOfCode_2021", "max_forks_repo_head_hexsha": "9d2e6f19cb555f89dac141cc081da4ce58558a2d", "max_forks_repo_licenses": ["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.9827586207, "max_line_length": 75, "alphanum_fraction": 0.5986496624, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7541962739724082}}
{"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": "#=\n  Fixed Point Convergence\n  Fixed Point Existance\n  Fixed Point Uniqueness\n  Newtons Method\n  Bisection Method\n=#\n\nfunction testConvergence(f,p0,TOL,N0)\n  # takes starting point, tolerance, maximum iterations\n  i = 1\n  while i <= N0\n    p = g(p0)\n    if abs(p-p0) < TOL\n      return true\n    else\n      i += 1\n      p0 = p\n    end\n  end\n  return false\n  println(\"Failure: N0 tries\")\n\n\nfunction testExistance(f,a,b)\n  # interval [a,b]\n  if f(a) * f(b) <0\n    return true\n    #does this make asusmptions\n  else\n    return false\n  end\n\n\nfunction testUniqueness(f,a,b)\n  # interval [a,b]\n  if derivative(f,a) * derivative(f,b) < 0\n    return true\n    #does this make assumptions\n  else\n    return false\n  end\n  \n\nfunction newtonsMethod(f,p0,TOL,N0)\n  if testConvergence(f) == true\n    i = 1\n    while i <= N0\n        p = p0 - (derivative(f,p0) / f(p0)\n        if abs(p-p0) < TOL\n          return p\n        else\n          i += 1\n          p0 = p\n        end\n    end\n  else\n    #return eror e\n  end\n\n\nfunction secantMethod()\n\n\nfunction bisectionMethod(f,a,b,DOA,NO)\n  # interval [a,b], DOA degree of accuracy\n  if testConvergence(f) == true\n    i = 1\n    while i <= N0\n      m = (1/2)(a + b)\n      if f(m) = 0 | abs(f(m)) < DOA\n        return m\n      elseif f(m) * f(a) < 0\n        a = m\n      elseif f(m) * f(b) < 0\n        b = m\n      else\n        #return eror e\n      end\n    end\n    return m\n  else\n    #return error e\n  end\n  \n        \n      \n      \n      \n        \n      \n      \n\n", "meta": {"hexsha": "966274ad8f05174e6a42bfe34585a71f4bfa2c10", "size": 1483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fixed-point-iteration.jl", "max_stars_repo_name": "K-P-S/Julia-Scientific-Computing", "max_stars_repo_head_hexsha": "a5b2a2fa436316e0016d9559b90c69c278c90731", "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": "fixed-point-iteration.jl", "max_issues_repo_name": "K-P-S/Julia-Scientific-Computing", "max_issues_repo_head_hexsha": "a5b2a2fa436316e0016d9559b90c69c278c90731", "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": "fixed-point-iteration.jl", "max_forks_repo_name": "K-P-S/Julia-Scientific-Computing", "max_forks_repo_head_hexsha": "a5b2a2fa436316e0016d9559b90c69c278c90731", "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.7765957447, "max_line_length": 55, "alphanum_fraction": 0.5333782873, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.7905303211371899, "lm_q1q2_score": 0.7541391234210875}}
{"text": "using TailRiskScenGen\nusing Cones\nusing LinearAlgebra: I\nusing Distributions\n\nd = 30\n\u03b2 = 0.95\nnum_scen = 5000\nA = rand(d,d)/sqrt(d)\ndist = MvNormal(0.1*rand(d)-0.05, A'A)\n\nK = PolyhedralCone(Array{Float64}(I, d, d))\n\u03a9_gen = EllipticalRiskRegion(dist, K, \u03b2)\n\u03a9_mono = MonotonicEllipticalRiskRegion(dist, K, \u03b2)\n\u03a9_mono.max_frontier_points = d*5\n\nrights = 0\nwrongs = 0\nfor i in 1:200\n    x = rand(dist)\n    mon = x \u2208 \u03a9_mono\n    gen = x \u2208 \u03a9_gen\n    if mon == gen\n        rights+=1\n    else\n        wrongs+=1\n    end\n    \n    if i % 10 == 1\n        println(\"i = \", i, \", num risk frontier points: \", length(\u03a9_mono.risk_frontier),\n              \", num nonrisk frontier points: \", length(\u03a9_mono.nonrisk_frontier))\n    end\nend\n\nprintln(\"Correct decisions: \", rights)\nprintln(\"Wrong decisions: \", wrongs)\n\n\nx = rand(dist)\n\nx \u2208 \u03a9_gen\nx \u2208 \u03a9_mono\ny = rand(dist)\ny \u2208 \u03a9_gen\ny \u2208 \u03a9_mono\n\n\u03a9_mono.risk_frontier\n\u03a9_mono.nonrisk_frontier\n\u03a9=\u03a9_mono\n\nprint(\"EllipticalRiskRegion...\")\ntic()\nTailRiskScenGen._aggregation_sampling(dist, \u03a9_gen, num_scen)\ntoc()\n\nprint(\"MonotonicEllipticalRiskRegion...\")\ntic()\nTailRiskScenGen._aggregation_sampling(dist, \u03a9_mono, num_scen)\ntoc()\n\nprintln(\"Num non-risk frontier points: \", length(\u03a9_mono.risk_frontier))\nprintln(\"Num risk frontier points: \", length(\u03a9_mono.nonrisk_frontier))\n", "meta": {"hexsha": "640cbe8d347eb723ae13c2e477dbf08ab7278b25", "size": 1292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_monotonic_elliptical.jl", "max_stars_repo_name": "STOR-i/EllipticalScenGen.jl", "max_stars_repo_head_hexsha": "9656ad3b630fe7171e6042f9b436037171010402", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-02-01T14:30:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T17:43:18.000Z", "max_issues_repo_path": "test/test_monotonic_elliptical.jl", "max_issues_repo_name": "STOR-i/EllipticalScenGen.jl", "max_issues_repo_head_hexsha": "9656ad3b630fe7171e6042f9b436037171010402", "max_issues_repo_licenses": ["MIT"], "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_monotonic_elliptical.jl", "max_forks_repo_name": "STOR-i/EllipticalScenGen.jl", "max_forks_repo_head_hexsha": "9656ad3b630fe7171e6042f9b436037171010402", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-19T00:49:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T00:49:15.000Z", "avg_line_length": 20.5079365079, "max_line_length": 88, "alphanum_fraction": 0.6880804954, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7541167978652766}}
{"text": "using DiscriminantAnalysis, Gadfly, Colors\n\n\n### Helper functions ###\n\nfunction rotationmatrix2D{T<:AbstractFloat}(\u03b8::T)\n    T[cos(\u03b8) -sin(\u03b8);\n      sin(\u03b8)  cos(\u03b8)]\nend\n\n# Generates two normally distributed variables\nfunction boxmuller(n::Integer)\n    u1 = rand(n)\n    u2 = rand(n)\n    Z = Float64[(\u221a(-2log(u1)) .* cos(2\u03c0*u2)) (\u221a(-2log(u1)) .* sin(2\u03c0*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    \u03b4 = DiscriminantAnalysis.discriminants(model, is_quad ? hcat(Z, Z.^2, Z[:,1] .* Z[:,2]) : Z)\n    Z = reshape(\u03b4[:,1] - \u03b4[:,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\u03c31 = [0.5 2.0]\nX1 = ((Z1 .* \u03c31) .- [0.0 4.25]) * rotationmatrix2D(\u03c0/4) \n\nZ2 = boxmuller(n)\n\u03c32 = [3.0 1.5]\nX2 = ((Z2 .* \u03c32) .+ [0.0 2.25]) * rotationmatrix2D(\u03c0/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) \u2265 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": "import RowEchelon\n\n#=\nHomework 5\nSection 2.1\nProblem 1\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(\"-2A:\")\nprintln(-2*A)\n\nprintln(\"B-2A:\")\nprintln(B-(2*A))\n\n# After this point, products may not exist\n# Use try/catch to find nonexistent products.\nprintln(\"AC:\")\ntry\n\tprintln(A*C)\ncatch\n\tprintln(\"AC cannot be computed.\")\nend\n\nprintln(\"CD:\")\ntry\n\tprintln(C*D)\ncatch\n\tprintln(\"CD cannot be computed.\")\nend\n", "meta": {"hexsha": "65e5bb13334bbb40bc11bad22e64cadb5171b399", "size": 489, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW5_S2.1_P1.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_P1.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_P1.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.2162162162, "max_line_length": 45, "alphanum_fraction": 0.6237218814, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7541167872168295}}
{"text": "#-------------------------------------------------------------------------------\n#conversions between spectral units\n\nexport \u03bd2f, f2\u03bd, \u03bd2\u03bb, \u03bb2\u03bd, \u03bb2f, f2\u03bb\n\n\"\"\"\nConvert wavenumber [cm``^{-1}``] to frequency [1/s]\n\"\"\"\n\u03bd2f(\u03bd) = 100.0*\ud835\udc1c*\u03bd\n\n\"\"\"\nConvert frequency [1/s] to wavenumber [cm``^{-1}``]\n\"\"\"\nf2\u03bd(f) = f/(100.0*\ud835\udc1c)\n\n\"\"\"\nConvert wavenumber [cm``^{-1}``] to wavelength [m]\n\"\"\"\n\u03bd2\u03bb(\u03bd) = 0.01/\u03bd\n\n\"\"\"\nConvert wavelength [m] to wavenumber [cm``^{-1}``]\n\"\"\"\n\u03bb2\u03bd(\u03bb) = 0.01/\u03bb\n\n\"\"\"\nConvert wavelength [m] to frequency [1/s]\n\"\"\"\n\u03bb2f(\u03bb) = \ud835\udc1c/\u03bb\n\n\"\"\"\nConvert frequency [1/s] to wavelength [m]\n\"\"\"\nf2\u03bb(f) = f/\ud835\udc1c\n\n#-------------------------------------------------------------------------------\nexport planck, normplanck, dplanck, stefanboltzmann, equilibriumtemperature\n\n\"\"\"\n    planck(\u03bd, 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* `\u03bd`: wavenumger [cm``^{-1}``]\n* `T`: temperature [Kelvin]\n\"\"\"\nfunction planck(\u03bd, T)\n    \u03bd\u2098 = 100.0*\u03bd #convert from cm^-1 to m^-1\n    x = \ud835\udc21*\ud835\udc1c*\u03bd\u2098/(\ud835\udc24*T) #exponent\n    p = 2*\ud835\udc21*\ud835\udc1c^2*\u03bd\u2098^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(\u03bd, 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(\u03bd,T)/\u03c3T^4\n```\n\nyielding units of 1/cm``^{-1}``/sr.\n\n# Arguments\n* `\u03bd`: wavenumger [cm``^{-1}``]\n* `T`: temperature [Kelvin]\n\"\"\"\nnormplanck(\u03bd, T) = planck(\u03bd, T)/stefanboltzmann(T)\n\n\"\"\"\n    dplanck(\u03bd, T)\n\nEvaluates ``\\\\frac{\\\\partial B}{\\\\partial T}``\n\"\"\"\nfunction dplanck(\u03bd, T)\n    \u03bd\u2098 = 100.0*\u03bd #convert from cm^-1 to m^-1\n    x = \ud835\udc21*\ud835\udc1c*\u03bd\u2098/(\ud835\udc24*T) #exponent\n    y = exp(x)\n    if isinf(y)\n        return zero(y) #fail accurately, Inf/(Inf - 1)^2 \u2192 0\n    end\n    p = 2*\ud835\udc21^2*\ud835\udc1c^3*\u03bd\u2098^4/(\ud835\udc24*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, ``\u03c3T^4`` [W/m``^2``].\n\"\"\"\nstefanboltzmann(T) = \ud835\uded4*(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*\ud835\uded4))^(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*\ud835\uded4*\u03c0*R^2))^(1/4)\n\n#-------------------------------------------------------------------------------\nexport d\u03c4dP, transmittance, schwarzschild, absorption, emission\n\n\"\"\"\n    d\u03c4dP(\u03c3, g, \u03bc)\n\nEvaluate the differential increase in optical depth in pressure coordinates, equivalent to the [`schwarzschild`](@ref) equation without Planck emission.\n\n``\\\\frac{d\u03c4}{dP} = \u03c3\\\\frac{\\\\textrm{N}_A}{g \u03bc}``\n\nwhere ``N_A`` is Avogadro's number.\n\n# Arguments\n* `\u03c3`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `\u03bc`: mean molar mass [kg/mole]\n\"\"\"\nd\u03c4dP(\u03c3, g, \u03bc) = 1e-4*\u03c3*\ud835\udc0d\ud835\udc1a/(\u03bc*g)\n\n\"\"\"\n    transmittance(\u03c4)\n\nEvaluate transmittance from optical depth, ``t = e^{-\u03c4}``\n\"\"\"\ntransmittance(\u03c4) = exp(-\u03c4)\n\n\"\"\"\n    schwarzschild(I, \u03bd, \u03c3, 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} = \u03c3\\\\frac{P}{k_B T}[B_\u03bd(T) - I]``\n\nwhere ``B_\u03bd`` is [`planck`](@ref)'s law.\n\n# Arguments\n* `I`: radiative intensity [W/m``^2``/cm``^{-1}``/sr]\n* `\u03bd`: radiation wavenumber [cm``^{-1}``]\n* `\u03c3`: absorption cross-section [cm``^2``/molecule]\n* `T`: temperature [K]\n* `P`: pressure [Pa]\n\"\"\"\nschwarzschild(I, \u03bd, \u03c3, T, P) = 1e-4*\u03c3*(P/(\ud835\udc24*T))*(planck(\u03bd,T) - I)\n\n\"\"\"\n    schwarzschild(I, \u03bd, \u03c3, g, \u03bc, 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} = \u03c3\\\\frac{\\\\textrm{N}_A}{g \u03bc}[B_\u03bd(T) - I]``\n\nwhere ``B_\u03bd`` 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* `\u03bd`: radiation wavenumber [cm``^{-1}``]\n* `\u03c3`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `\u03bc`: mean molar mass [kg/mole]\n* `T`: temperature [K]\n\"\"\"\nschwarzschild(I, \u03bd, \u03c3, g, \u03bc, T) = 1e-4*\u03c3*(\ud835\udc0d\ud835\udc1a/(\u03bc*g))*(planck(\u03bd,T) - I)\n\n\"\"\"\n    absorption(I, \u03c3, g, \u03bc)\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} = -\u03c3\\\\frac{\\\\textrm{N}_A}{g \u03bc}I``\n\nwhere ``N_A`` is Avogadro's number.\n\n# Arguments\n* `I`: radiative intensity [W/m``^2``/cm``^{-1}``/sr]\n* `\u03c3`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `\u03bc`: mean molar mass [kg/mole]\n\"\"\"\nabsorption(I, \u03c3, g, \u03bc) = -1e-4*\u03c3*(\ud835\udc0d\ud835\udc1a/(\u03bc*g))*I\n\n\"\"\"\n    emission(I, \u03bd, \u03c3, g, \u03bc, 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} = -\u03c3\\\\frac{\\\\textrm{N}_A}{g \u03bc}B_\u03bd(T)``\n\nwhere ``B_\u03bd`` is [`planck`](@ref)'s law\n\n# Arguments\n* `I`: radiative intensity [W/m``^2``/cm``^{-1}``/sr]\n* `\u03c3`: absorption cross-section [cm``^2``/molecule]\n* `g`: gravitational acceleration [m/s``^2``]\n* `\u03bc`: mean molar mass [kg/mole]\n\"\"\"\nemission(\u03bd, \u03c3, g, \u03bc, T) = 1e-4*\u03c3*(\ud835\udc0d\ud835\udc1a/(\u03bc*g))*planck(\u03bd,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": "@testset \"matern\" begin\n    rng = MersenneTwister(123456)\n    x = rand(rng) * 2\n    v1 = rand(rng, 3)\n    v2 = rand(rng, 3)\n    @testset \"MaternKernel\" begin\n        \u03bd = 2.1\n        k = MaternKernel(; \u03bd=\u03bd)\n        matern(x, \u03bd) = 2^(1 - \u03bd) / gamma(\u03bd) * (sqrt(2\u03bd) * x)^\u03bd * besselk(\u03bd, sqrt(2\u03bd) * x)\n        @test MaternKernel(; nu=\u03bd).\u03bd == [\u03bd]\n        @test kappa(k, x) \u2248 matern(x, \u03bd)\n        @test kappa(k, 0.0) == 1.0\n        @test metric(MaternKernel()) == Euclidean()\n        @test metric(MaternKernel(; \u03bd=2.0)) == Euclidean()\n        @test repr(k) == \"Matern Kernel (\u03bd = $(\u03bd), metric = Euclidean(0.0))\"\n\n        k2 = MaternKernel(; \u03bd=\u03bd, metric=WeightedEuclidean(ones(3)))\n        @test metric(k2) isa WeightedEuclidean\n        @test k2(v1, v2) \u2248 k(v1, v2)\n\n        # Standardised tests.\n        TestUtils.test_interface(k, Float64)\n        test_ADs(() -> MaternKernel(; nu=\u03bd))\n\n        test_params(k, ([\u03bd],))\n    end\n    @testset \"Matern32Kernel\" begin\n        k = Matern32Kernel()\n        @test kappa(k, x) \u2248 (1 + sqrt(3) * x)exp(-sqrt(3) * x)\n        @test k(v1, v2) \u2248 (1 + sqrt(3) * norm(v1 - v2))exp(-sqrt(3) * norm(v1 - v2))\n        @test kappa(Matern32Kernel(), x) == kappa(k, x)\n        @test metric(Matern32Kernel()) == Euclidean()\n        @test repr(k) == \"Matern 3/2 Kernel (metric = Euclidean(0.0))\"\n\n        k2 = Matern32Kernel(; metric=WeightedEuclidean(ones(3)))\n        @test metric(k2) isa WeightedEuclidean\n        @test k2(v1, v2) \u2248 k(v1, v2)\n\n        # Standardised tests.\n        TestUtils.test_interface(k, Float64)\n        test_ADs(Matern32Kernel)\n    end\n    @testset \"Matern52Kernel\" begin\n        k = Matern52Kernel()\n        @test kappa(k, x) \u2248 (1 + sqrt(5) * x + 5 / 3 * x^2)exp(-sqrt(5) * x)\n        @test k(v1, v2) \u2248\n            (\n            1 + sqrt(5) * norm(v1 - v2) + 5 / 3 * norm(v1 - v2)^2\n        )exp(-sqrt(5) * norm(v1 - v2))\n        @test kappa(Matern52Kernel(), x) == kappa(k, x)\n        @test metric(Matern52Kernel()) == Euclidean()\n        @test repr(k) == \"Matern 5/2 Kernel (metric = Euclidean(0.0))\"\n\n        k2 = Matern52Kernel(; metric=WeightedEuclidean(ones(3)))\n        @test metric(k2) isa WeightedEuclidean\n        @test k2(v1, v2) \u2248 k(v1, v2)\n\n        # Standardised tests.\n        TestUtils.test_interface(k, Float64)\n        test_ADs(Matern52Kernel)\n    end\n    @testset \"Coherence Materns\" begin\n        @test kappa(MaternKernel(; \u03bd=0.5), x) \u2248 kappa(ExponentialKernel(), x)\n        @test kappa(MaternKernel(; \u03bd=1.5), x) \u2248 kappa(Matern32Kernel(), x)\n        @test kappa(MaternKernel(; \u03bd=2.5), x) \u2248 kappa(Matern52Kernel(), x)\n    end\nend\n", "meta": {"hexsha": "025cb141bfb44cedb2311eba4c98edcb086ccf10", "size": 2593, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basekernels/matern.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": "test/basekernels/matern.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": "test/basekernels/matern.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": 38.1323529412, "max_line_length": 89, "alphanum_fraction": 0.5503278056, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7541167830948742}}
{"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 + \u221a(x\u00b2 + 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,\u03b4a1,\u03b4a2,err;lr=1)\n    w1 .-= \u03b4a1 * x' .* lr\n    w2 .-= \u03b4a2 * 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        \u03b4a2 = (w3' * err) .* dlogis(a2)\n        \u03b4a1 = (w2' * \u03b4a2) .* dlogis(a1)\n        updateW!(w1,w2,w3,x,h1,h2,\u03b4a1,\u03b4a2,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        \u03b4a2 = (B2.*err) .* dlogis(a2) \n        \u03b4a1 = (B1.*\u03b4a2) .* dlogis(a1) \n        updateW!(w1,w2,w3,x,h1,h2,\u03b4a1,\u03b4a2,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        \u03b4a2 = (B2.*err) .* dlogis(a2) \n        \u03b4a1 = (B1.*err) .* dlogis(a1) \n        updateW!(w1,w2,w3,x,h1,h2,\u03b4a1,\u03b4a2,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        \u03b4a1 = (B1.*err) .* dlogis(a1) \n        \u03b4a2 = (w2 * \u03b4a1) .* dlogis(a2) \n        updateW!(w1,w2,w3,x,h1,h2,\u03b4a1,\u03b4a2,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}, \u03bb::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* `\u03bb::Float64`                  - regularization paramter\n* `sparseTrafo::Trafo=nothing`  - sparsifying transform to apply\n\"\"\"\nfunction proxL1!(x::AbstractArray{Tc}, \u03bb::T; sparseTrafo::Trafo=nothing, kargs...) where {T, Tc <: Union{T, Complex{T}}}\n  \u03b5 = eps(T)\n\n  if sparseTrafo != nothing\n    z = sparseTrafo*x\n    z .= max.((abs.(z).-\u03bb),0) .* (z.+\u03b5)./(abs.(z).+\u03b5)\n    x .= adjoint(sparseTrafo)*z\n  else\n    x .= max.((abs.(x).-\u03bb),0) .* (x.+\u03b5)./(abs.(x).+\u03b5)\n  end\n\n  return x\nend\n\n\"\"\"\n    normL1(x::Array{T}, \u03bb::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, \u03bb::Float64; sparseTrafo::Trafo=nothing, kargs...) where T<:AbstractArray\n  if sparseTrafo != nothing\n    l1Norm = \u03bb*norm(sparseTrafo*x,1)\n  else\n    l1Norm = \u03bb*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": "# Michelle Medina\n# July 16, 2020\n# Testing 2D cases for Nodal and Hierarchical Bases\n\n# Testing calculating Nodal Basis function in 2D\nxVal = collect(range(0.0, stop=1.0, length = 5))\nyVal = collect(range(0.0, stop=1.0, length = 5))\nnodal = calcNodal2D((x,y)->exp(x)*exp(y), xVal, yVal)\nnodal2 = calcNodal2D((x,y)->exp(x)*sin(pi*y), xVal, yVal)\n\n# Plotting 2D functions\nusing PyPlot\ncontourf(nodal.values)\ncolorbar()\nshow()\n\ncontourf(nodal2.values)\ncolorbar()\nshow()\n\n# Going from nodal to hierarchical grid and sparse grid\nmodal = Nodal_2_H(nodal)\nsparse = Nodal_2_H_sparse(nodal,3)\nfor l in 0:2, m in 0:2\n\tdisplay(modal.levels[l+1,m+1].coefficients)\n\tdisplay(sparse.levels[l+1,m+1].coefficients)\n\tprintln()\nend\n\n# Going back and forth between nodal and modal\nback = H_2_Nodal(modal)\n@test isapprox(nodal.values,back.values)\n\n# Using interpolation instead of evaluate\nmodal2 = Nodal_2_H_new(nodal)\n\n# Testing how coefficients fall off as level increases\nusing LinearAlgebra\nA = []\nfor l in 0:maxlevel(modal,1)\n\tappend!(A, norm(modal.levels[l+1].coefficients))\nend\n\nusing PyPlot\nplot(A)\nshow()\n\n\n\t\n\t\n\n\n", "meta": {"hexsha": "cedf24d493332eaa0f8c81e68ff33534207f89bd", "size": 1103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/2D_BasisTest.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/2D_BasisTest.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/2D_BasisTest.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": 20.8113207547, "max_line_length": 57, "alphanum_fraction": 0.7316409791, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7541062491869207}}
{"text": "export find\u03b2, 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(\u03b2, evals)\nCompute the distribution of eigenstates with given energies at temperature 1/\u03b2.\nP(E) \u221d \u2211\u1d62exp(-\u03b2 E\u1d62)\n\nEnergy values are assumed to be sorted!\n\"\"\"\nfunction _weights_canonical(evals, \u03b2)\n    # assume sorted evals!\n    regulator = \u03b2 < 0 ? evals[end] : evals[1]\n    _softmax(@. -\u03b2 * (evals - regulator))\nend\n\n_\u0394E(evals, E_0, \u03b2) = abs((evals \u22c5 _weights_canonical(evals, \u03b2)) - E_0)\n\n# TODO: How to optimize best? The function is pretty well behaved...\n\"\"\"\n    find\u03b2(evals, E\u2080; \u03b2_0=0)\nCompute the inverse temperature \u03b2 s. t. the thermal expectation value of the energy matches E\u2080.\n\"\"\"\nfind\u03b2(evals, E_0; \u03b2_0 = 0) = Optim.optimize(\u03b2 -> _\u0394E(evals, E_0, \u03b2[1]), [float(\u03b2_0)], Optim.Newton(linesearch = LineSearches.HagerZhang())).minimizer[1]\n\n\"\"\"\n    canonical_ensemble(evals, E\u2080; \u03b2\u2080 = 0)\nCompute the weights of the state assuming a canonical ensemble of temperature 1/\u03b2. \u03b2\u2080 is taken as starting value for the computation.\nA state is assigned the weight \u221d exp(-\u03b2 E\u1d62)\n\nEnergy values are assumed to be sorted!\n\"\"\"\ncanonical_ensemble(evals, E_0; \u03b2_0 = 0) = _weights_canonical(evals, find\u03b2(evals, E_0; \u03b2_0))\n\n\n\"\"\"\n    microcanonical_ensemble(evals, E\u2080[, \u0394E])\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\u1d62-E_0| < \u0394E.\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, \u0394E)::Vector{Float64}\n    micro = @. (evals < E_0+\u0394E) & (evals > E_0-\u0394E)\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 \u2190 size(A, 1)\n    n \u2190 size(A, 2)\n    @invcheckoff branch_keeper \u2190 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 \u2190 A.colptr[j]\n        ib1 \u2190 B.colptr[j]\n        ia2 \u2190 A.colptr[j+1]\n        ib2 \u2190 B.colptr[j+1]\n        ia \u2190 ia1\n        ib \u2190 ib1\n        @inbounds for i=1:ia2-ia1+ib2-ib1-1\n            ra \u2190 A.rowval[ia]\n            rb \u2190 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] \u22bb= @const ia == ia2-1 || ra > rb\n            ra \u2192 A.rowval[ia]\n            rb \u2192 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] \u22bb= @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 \u2192 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": "using StatsFuns, StatsModels, DataFrames, LinearAlgebra\n\n\"\"\"\n    ols(y,x)\n\nCompute the ordinary least squares regresssion coefficients, and report results. Can also compute OLS subject to linear restrictions.\n\nols() with no arguments will run an example, execute edit(ols,()) to see the code.\n\n\"\"\"\nfunction ols()\n    y = rand(100,1)\n    x = [ones(100,1) rand(100,3)]\n    names = [\"const\" \"x2\"  \"x3\" \"x4\"]\n    ols(y,x)\n    ols(y,x,names=names)\n    ols(y,x,names=names, vc=\"nw\")\n    b,junk,junk,junk = ols(y,x,silent=true)\n    show(b)\n    # restricted LS\n    R = [1 0 0 0]\n    r = 1\n    ols(y,x,R=R,r=r)\n    # using dataframe\n    println(\"using a formula and dataframe\")\n    d = DataFrame(x=rand(10),y=rand(10),z=rand(10))\n    f = @formula(y ~ 1+x+z+x*z)\n    ols(f,d)\n    return\nend\n\n\n# version for dataframe and formula\nfunction ols(f::Formula, df::DataFrame; R=[], r=[], names=\"\", vc=\"white\", silent=false)\n    y = df[f.lhs]\n    mf = ModelFrame(f,df)\n    x = ModelMatrix(mf).m\n    ols(y, x, names=coefnames(mf))\nend\n\nfunction ols(y::Array{Float64}, x::Array{Float64,2}; R=[], r=[], names=\"\", vc=\"white\", silent=false)\n    n,k = size(x)\n    if names==\"\"\n        names = 1:k\n        names = names'\n    end\n    b, fit, e = lsfit(y,x)\n    df = n-k\n    sigsq = (e'*e/df)[1,1]\n    xx_inv = inv(x'*x)\n    ess = (e' * e)[1,1]\n    # Restricted LS?\n    if R !=[]\n        q = size(R,1)\n        P_inv = inv(R*xx_inv*R')\n        b = b .- xx_inv*R'*P_inv*(R*b.-r)\n        e = y-x*b;\n        ess = (e' * e)[1,1]\n        df = n-k-q\n        sigsq = ess/df\n        A = Matrix{Float64}(I, k, k) .- xx_inv*R'*P_inv*R;  # the matrix relating b and b_r\n    end\n    # Ordinary or het. consistent variance estimate\n    if vc==\"white\"\n        xe = x.*e\n        varb = xx_inv*xe'xe*xx_inv\n    elseif vc==\"nw\"\n        xe = x.*e\n        lags = Int(max(round(n^0.25),1.0))\n        varb = n*xx_inv*NeweyWest(xe,lags)*xx_inv\n    else\n        varb= xx_inv.*sigsq\n    end\n    # restricted LS?\n    if R !=[]\n        varb = A*varb*A'\n    end\n    # common to both ordinary and restricted\n    seb = sqrt.(diag(varb))\n    seb = seb.*(seb.>1e-16) # round off to zero when there are restrictions\n    t = b ./ seb\n    tss = y .- mean(y)\n    tss = (tss'*tss)[1,1]\n    rsq = (1.0 - ess / tss)\n    if !silent\n        println()\n        PrintDivider()\n        if R==[]\n            @printf(\"  OLS estimation, %d observations\\n\", n)\n        else\n            @printf(\"  Restricted LS estimation, %d observations\\n\", n)\n        end\n        @printf(\"  R\u00b2: %f   \u03c3\u00b2: %f\\n\", rsq, sigsq)\n        p = 2.0 .- 2.0*tdistcdf.(df, abs.(t))\n        results = [b seb t p]\n        if vc==\"white\"\n            println(\"  White's covariance estimator\")\n\n        elseif vc==\"nw\"\n            println(\"  Newey-West covariance estimator\")\n        end\n        println()\n        PrintEstimationResults(results, names)\n        PrintDivider()\n    end\n    return b, varb, e, ess, rsq\nend\n", "meta": {"hexsha": "2ffc46c98e729a350ccbfbae5de5f4c4a9d1ea3e", "size": 2912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearRegression/ols.jl", "max_stars_repo_name": "manuelmontesinos/Econometrics", "max_stars_repo_head_hexsha": "d4176e1f737bcb2b3163b5b381d0bf9773013742", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearRegression/ols.jl", "max_issues_repo_name": "manuelmontesinos/Econometrics", "max_issues_repo_head_hexsha": "d4176e1f737bcb2b3163b5b381d0bf9773013742", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearRegression/ols.jl", "max_forks_repo_name": "manuelmontesinos/Econometrics", "max_forks_repo_head_hexsha": "d4176e1f737bcb2b3163b5b381d0bf9773013742", "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": 26.962962963, "max_line_length": 133, "alphanum_fraction": 0.5377747253, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7540983298846652}}
{"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 \u03b2-divergence for different values of \u03b2\n#### #################################################################################################################\n\n\u03b2ys = [-1, 0, 1, 2]\n\u03b2zs = [-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    \u03b2y = \u03b2ys[sp]\n    \u03b2z = \u03b2zs[sp]\n\n    if \u03b2z < 1\n\tX = h:h:8\n    else\n\tX = h:h:4\n    end\n\n    Y = [\u03b2_divergence(hcat([1.]), hcat([x]), \u03b2y) for x in X]\n    Z = [\u03b2_divergence(hcat([1.]), hcat([x]), \u03b2z) for x in X]\n\n    plot!(\n\tX, \n\thcat(Y, Z), \n\ttitle = titles[sp],\n\tlabels = [\"\\$\\\\beta = $(\u03b2y)\\$\" \"\\$\\\\beta = $(\u03b2z)\\$\" ],\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, \u03b1=0.49609375)\n\nSplit the interval `X` at position \u03b1; \u03b1=0.5 corresponds to the midpoint.\nReturns a tuple of the new intervals.\n\"\"\"\nfunction bisect(X::Interval, \u03b1=where_bisect)\n    @assert 0 \u2264 \u03b1 \u2264 1\n\n    m = mid(X, \u03b1)\n\n    return (Interval(X.lo, m), Interval(m, X.hi))\nend\n\n\"\"\"\n    bisect(X::IntervalBox, \u03b1=0.49609375)\n\nBisect the `IntervalBox` `X` at position \u03b1 \u2208 [0,1] along its longest side.\n\"\"\"\nfunction bisect(X::IntervalBox, \u03b1=where_bisect)\n    i = argmax(diam.(X))  # find longest side\n\n    return bisect(X, i, \u03b1)\nend\n\n\"\"\"\n    bisect(X::IntervalBox, i::Integer, \u03b1=0.49609375)\n\nBisect the `IntervalBox` in side number `i`.\n\"\"\"\nfunction bisect(X::IntervalBox, i::Integer, \u03b1=where_bisect)\n\n    x1, x2 = bisect(X[i], \u03b1)\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": "constants = Constants()\n\n# Monteith, John L., et Mike H. Unsworth. 2013. \u00ab\u00a0Chapter 13 - Steady-State Heat Balance: (i)\n# Water Surfaces, Soil, and Vegetation\u00a0\u00bb. In Principles of Environmental Physics (Fourth Edition),\n# edited by John L. Monteith et Mike H. Unsworth, 217\u201147. Boston: Academic Press.\n\n# p 230:\n\n# In Monteith and Unsworth (2013) p.230, they say at a standard pressure of 101.3 kPa,\n# \u03bb has a value of about 66 Pa K\u22121 at 0 \u25e6C increasing to 67 Pa K\u22121 at 20 \u25e6C:\n@testset \"Psychrometer constant\" begin\n    \u03bb\u2080 = latent_heat_vaporization(0.0, constants.\u03bb\u2080)\n    @test psychrometer_constant(101.3, \u03bb\u2080) * 1000 \u2248 65.9651894869062 # in Pa K-1\n    \u03bb\u2082\u2080 = latent_heat_vaporization(20.0, constants.\u03bb\u2080)\n    @test psychrometer_constant(101.3, \u03bb\u2082\u2080) * 1000 \u2248 67.23680111943287 # in Pa K-1\nend;\n\n@testset \"Black body\" begin\n    # Testing that both calls return the same value with default parameters:\n    @test black_body(25.0, constants.K\u2080, constants.\u03c3) == black_body(25.0)\n    @test black_body(25.0, constants.K\u2080, constants.\u03c3) \u2248 448.07517457669354 # checked\nend;\n\n\n@testset \"grey body\" begin\n    # Testing that both calls return the same value with default parameters:\n    @test grey_body(25.0, 0.96, constants.K\u2080, constants.\u03c3) == grey_body(25.0, 0.96)\n    @test grey_body(25.0, 0.96, constants.K\u2080, constants.\u03c3) \u2248 430.1521675936258\nend;\n\n\n@testset \"R\u2097\u2097\" begin\n    # Testing that both calls return the same value with default parameters:\n    @test net_longwave_radiation(25.0, 20.0, 0.955, 1.0, 1.0, constants.K\u2080, constants.\u03c3) ==\n            net_longwave_radiation(25.0, 20.0, 0.955, 1.0, 1.0)\n    # Example from Cengel (2003), Example 12-7 (p. 627):\n    # Cengel, Y, et Transfer Mass Heat. 2003. A practical approach. New York, NY, USA: McGraw-Hill.\n    @test net_longwave_radiation(526.85, 226.85000000000002, 0.2, 0.7, 1.0, constants.K\u2080, constants.\u03c3) \u2248 -3625.6066521315793\n    # NB: we compute it opposite (negative when energy is lost, positive for a gain)\nend;\n\n\n\n@testset \"energy_balance(LeafModels{.,Monteith{Float64,Int64},Fvcb{Float64},Medlyn{Float64},.})\" begin\n    # Reference value:\n    ref = (Rn = 21.497353195073416, skyFraction = 1.0, d = 0.03, T\u2097 = 17.587096944187294,\n            R\u2097\u2097 = 7.750353195073414, H = -125.37135199797042, \u03bbE = 146.86870519304384,\n            C\u209b = 349.0241705592342, C\u1d62 = 330.36134887038975, A = 34.31323392636316,\n            G\u209b = 1.807060287311702, Gb\u2095 = 0.02137773821516218, D\u2097 = 0.49288571959517546,\n            Gbc = 0.67312752539388, PPFD = 1500.0)\n\n    meteo = Atmosphere(T = 20.0, Wind = 1.0, P = 101.3, Rh = 0.65)\n    leaf = LeafModels(energy = Monteith(),\n                photosynthesis = Fvcb(),\n                stomatal_conductance = Medlyn(0.03, 12.0),\n                R\u209b = 13.747, skyFraction = 1.0, PPFD = 1500.0, d = 0.03)\n\n    non_mutating = energy_balance(leaf, meteo)\n\n    for i in keys(ref)\n        @test non_mutating[i] \u2248 ref[i]\n    end\n\n    # Mutating the leaf:\n    energy_balance!(leaf, meteo)\n    for i in keys(ref)\n        @test leaf.status[i] \u2248 ref[i]\n    end\nend;\n\n\n\n# meteo = Atmosphere(T = 20.0, Wind = 1.0, P = 101.3, Rh = 0.65)\n# leaf = LeafModels(energy = Monteith(),\n#             photosynthesis = Fvcb(),\n#             stomatal_conductance = Medlyn(0.03, 12.0),\n#             R\u209b = 13.747, skyFraction = 1.0, PPFD = 1500.0, d = 0.03)\n\n# res = DataFrame(:PPFD => Float64[], :A => Float64[])\n# for i in 1:10:1500\n#     leaf.status.PPFD = i\n#     energy_balance!(leaf, meteo)\n#     push!(res, (PPFD = leaf.status.PPFD, A = leaf.status.A))\n# end\n\n\n# plot(res.PPFD,res.A)\n# ylabel!(\"A\")\n# xlabel!(\"PPFD\")\n\n\n# Add tests for several components and/or several meteo time-steps (Weather)\n", "meta": {"hexsha": "6780d8546f6883fa1e95378203bc51c064ad6980", "size": 3650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/energy_balance.jl", "max_stars_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_stars_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_stars_repo_licenses": ["MIT"], "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/energy_balance.jl", "max_issues_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_issues_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_issues_repo_licenses": ["MIT"], "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/energy_balance.jl", "max_forks_repo_name": "SimonTreillou/PlantBiophysics.jl", "max_forks_repo_head_hexsha": "70688f412467a379ed59fac34995f05f88ba8762", "max_forks_repo_licenses": ["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.247311828, "max_line_length": 124, "alphanum_fraction": 0.6545205479, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7540983248270702}}
{"text": "@testset \"The Hyperbolic Manifold\" begin\n    M = Hyperbolic(2)\n    @test typicalDistance(M) == sqrt(2)\n    @test getValue(HnPoint(1.)) == 1.\n    @test getValue(HnTVector(0.)) == 0.\n    x = HnPoint([0.,0.,1])\n    @test getValue(x) == [0., 0., 1.]\n    \u03be = HnTVector([1.,1.,0,])\n    @test getValue(\u03be) == [1., 1., 0.]\n    @test_throws ErrorException validateMPoint(M, HnPoint([1.,0.]))\n    @test_throws ErrorException validateMPoint(M, HnPoint([0., 0., 0.]))\n    @test_throws ErrorException validateMPoint(M, HnPoint([2., 0., 3.])) # -5 instead of -1\n    @test validateTVector(M, x, \u03be)\n    @test_throws ErrorException validateTVector(M,x, HnTVector([0.,0.])) # Dimensions don't agree\n    @test_throws ErrorException validateTVector(M,x, HnTVector(getValue(x))) # Not orthogonal\n    y = exp(M, x, \u03be)\n    @test distance(M, x, y) \u2248 norm(M, x, \u03be)\n    @test norm(M, x, \u03be) \u2248 sqrt(dot(M,x,\u03be,\u03be))\n    @test distance(M, exp(M,x,log(M,x,y)), y) \u2248 0\n    @test distance(M, exp(M,x,zeroTVector(M,x)), x) \u2248 0\n    @test norm(M, x, log(M,x,x)) \u2248 0\n    #\n    @test manifoldDimension(x) == 2\n    @test manifoldDimension(M) == 2\n    @test parallelTransport(M,x,x,\u03be) == \u03be\n    @test norm(M, y, parallelTransport(M,x,y,\u03be)+log(M,y,x)) \u2248 0 atol=5*10^(-15)\n    #\n    @test typeofTVector(typeof(x)) == HnTVector{Float64}\n    @test typeofMPoint(typeof(\u03be)) == HnPoint{Float64}\n    @test typeofTVector(x) == HnTVector{Float64}\n    @test typeofMPoint(\u03be) == HnPoint{Float64}\n\n    @test \"$(M)\" == \"The 2-Hyperbolic Space.\"\n    @test \"$(x)\" == \"Hn([0.0, 0.0, 1.0])\"\n    @test \"$(\u03be)\" == \"HnT([1.0, 1.0, 0.0])\"\nend", "meta": {"hexsha": "dec4c15813c0be265443e973b71845d11b29f274", "size": 1574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/manifolds/testHn.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": "test/manifolds/testHn.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": "test/manifolds/testHn.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": 43.7222222222, "max_line_length": 97, "alphanum_fraction": 0.5965692503, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8499711737573763, "lm_q1q2_score": 0.7540983248147641}}
{"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 Test, DelayEmbeddings\n\nprintln(\"\\nTesting delay embeddings...\")\n\n@testset \"embedding\" begin\n\n    data = Dataset(rand(10001,3))\n    s = data[:, 1]; N = length(s)\n\n    @testset \"standard\" begin\n\n    \t@testset \"D = $(D), \u03c4 = $(\u03c4)\" for D in [2,3], \u03c4 in [2,3]\n    \t\tR = embed(s, D, \u03c4)\n    \t\t@test R[(1+\u03c4):end, 1] == R[1:end-\u03c4, 2]\n    \t\t@test size(R) == (length(s) - \u03c4*(D-1), D)\n    \tend\n    end\n\n    @testset \"weighted\" begin\n    \t@testset \"D = $(D), \u03c4 = $(\u03c4)\" for D in [2,3], \u03c4 in [2,3]\n\n            w = 0.1\n    \t\tR1 = embed(s, D, \u03c4)\n    \t\tR2 = embed(s, D, \u03c4, w)\n            for \u03b3 in 0:D-1\n                @test  (w^\u03b3) * R1[1, \u03b3+1][1] == R2[1, \u03b3+1]\n                @test  (w^\u03b3) * R1[5, \u03b3+1][1] == R2[5, \u03b3+1]\n            end\n    \tend\n    end\n\n    @testset \"multi-time\" begin\n        D = 3\n        \u03c41 = [2, 4]\n        \u03c42 = [4, 8]\n\n        R0 = embed(s, D, 2)\n        R1 = embed(s, D, \u03c41)\n        R2 = embed(s, D, \u03c42)\n\n        @test R1 == R0\n\n        R2y = R2[:, 2]\n        @test R2y == R0[5:end, 1]\n        @test R2[:, 1] == R0[1:end-4, 1]\n        @test size(R2) == (N-maximum(\u03c42), 3)\n\n        @test_throws ArgumentError embed(s, 4, \u03c41)\n    end\n\nend\n\nprintln(\"\\nTesting generalized embedding...\")\n@testset \"genembed\" begin\n    \u03c4s = (0, 2, -7)\n    js = (1, 3, 2)\n    ge = GeneralizedEmbedding(\u03c4s, js)\n    s = Dataset(rand(20, 3))\n    x, y, z = columns(s)\n    \u03c4r = \u03c4range(s, ge)\n    @testset \"univariate\" begin\n        w = rand(20)\n        em = genembed(w, \u03c4s, js)\n        @test em == genembed(w, \u03c4s)\n        @test em[1:3, 3] == w[1:3]\n        @test em[1:3, 1] == w[1+7:3+7]\n        @test em[1:3, 2] == w[1+7+2:3+7+2]\n    end\n    @testset \"multivariate\" begin\n        em = genembed(s, \u03c4s, js)\n        @test em[1:3, 1] == x[1+7:3+7]\n        @test em[1:3, 2] == z[1+7+2:3+7+2]\n        @test em[1:3, 3] == y[1:3]\n    end\n    @testset \"weighted\" begin\n        ws = (1, 0, 0.1)\n        em = genembed(s, \u03c4s, js; ws)\n        @test em[1:3, 1] == x[1+7:3+7]\n        @test em[1:3, 2] == 0 .* z[1+7+2:3+7+2]\n        @test em[1:3, 3] == 0.1 .* y[1:3]\n    end\n    @testset \"weighted integer\" begin\n        ws = (1, 0, -0.1)\n        x = collect(1:100)\n        ge = GeneralizedEmbedding(\u03c4s, js, ws)\n        em = genembed(x, \u03c4s, js; ws)\n        @test em[1:3, 1] == x[1+7:3+7]\n        @test em[1:3, 2] == 0 .* x[1+7+2:3+7+2]\n        @test em[1:3, 3] == -0.1 .* x[1:3]\n    end\nend\n", "meta": {"hexsha": "40511670d68b0e069e09078ae89c1a8c75cfa405", "size": 2361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/embedding_tests.jl", "max_stars_repo_name": "kahaaga/DelayEmbeddings.jl", "max_stars_repo_head_hexsha": "786c9cbdb98495629b68f7adaf380a9824826bea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-11-21T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T14:24:47.000Z", "max_issues_repo_path": "test/embedding_tests.jl", "max_issues_repo_name": "kahaaga/DelayEmbeddings.jl", "max_issues_repo_head_hexsha": "786c9cbdb98495629b68f7adaf380a9824826bea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2018-11-09T12:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T14:06:10.000Z", "max_forks_repo_path": "test/embedding_tests.jl", "max_forks_repo_name": "kahaaga/DelayEmbeddings.jl", "max_forks_repo_head_hexsha": "786c9cbdb98495629b68f7adaf380a9824826bea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-05-01T19:08:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T15:58:14.000Z", "avg_line_length": 25.6630434783, "max_line_length": 61, "alphanum_fraction": 0.4417619653, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7540087881525178}}
{"text": "using Distributions, Plots; pyplot()\n\ndist = TriangularDist(4,6,5)\nN = 10^6\ndata = rand(dist,N)\nyData=(data .- 5).^2\n\nprintln(\"Mean: \", mean(yData), \" Variance: \", var(data))\n\np1 = histogram(data, xlabel=\"x\", bins=80, normed=true, ylims=(0,1.1))\np2 = histogram(yData, xlabel=\"y\", bins=80, normed=true, ylims=(0,15))\nplot(p1, p2, ylabel=\"Proportion\", size=(800, 400), legend=:none)", "meta": {"hexsha": "25d4bb794496e794694c43a010249be57e307b84", "size": 380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/varianceTransformation.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/varianceTransformation.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/varianceTransformation.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.6666666667, "max_line_length": 69, "alphanum_fraction": 0.6578947368, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7540087838874245}}
{"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, \u03c9 = 2*\u03c0*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!(\u03a6, 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 \u03a6[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    \u03a6 = zeros(N, M)\n\n    calculaterbfbasis!(\u03a6, x, gridpoints, r)\n\n    return \u03a6\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) \u2192 nothing\n\nRotates the diagonal elements between R[from:to,from:to]\nsuch that the eigenvalue at R[to,to] \u2192 R[from,from]\nand all the others move R[i,i] \u2192 R[i+1,i+1].\n\nAssumes that `from` and `to` refer to the first index of the 2\u00d72 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) \u2192 nothing\n\nRotates the diagonal elements between R[from:to,from:to]\nsuch that the eigenvalue at R[from,from] \u2192 R[to,to]\nand all the others move R[i,i] \u2192 R[i-1,i-1].\n\nAssumes that `from` and `to` refer to the first index of the 2\u00d72 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) \u2192 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 \u2190 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 \u2190 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) \u2192 X, singular\n\nSolve A * X - X * B = C for X, where A and B are 1\u00d71 or 2\u00d72 matrices.\n\nIt works by recasting the Sylvester equation to a linear system \n(I \u2297 A + B\u1d40 \u2297 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) \u2192 c\u2081, s\u2081, c\u2082, s\u2082, c\u2083, s\u2083, c\u2084, s\u2084\n\nConstruct two sets of two Given's rotations that transform\n```\n  -x\u2081\u2081 -x\u2081\u2082\n  -x\u2082\u2081 -x\u2082\u2082\n   1    .\n   .    1\n```\nto upper triangular form:\n```\n  x x  \u21d2  x x  \u21d2  * *  \u21d2  x x  \u21d2  x x\n  x x  \u21d2  * *  \u21d2  . *  \u21d2  . x  \u21d2  . *\n  1 .  \u21d2  . *  \u21d2  . x  \u21d2  . *  \u21d2  . .\n  . 1  \u21d2  . 1  \u21d2  . 1  \u21d2  . .  \u21d2  . .\n```\n\"\"\"\nfunction swap22_rotations(X::SMatrix{2,2,T}) where {T}\n    # Upper triangulize first column of X\n    c\u2081, s\u2081, nrm\u2081 = givensAlgorithm(-X[2,1], T(1))\n    c\u2082, s\u2082, nrm\u2082 = givensAlgorithm(-X[1,1], nrm\u2081)\n\n    # Apply the Givens rotations to the second column of X\n    X22 = c\u2081 * -X[2,2] # + s\u2081 * 0\n    X32 = -s\u2081' * -X[2,2] # + c\u2081 * 0\n    # X12 = c\u2082 * -X[1,2] + s\u2082 * X22 # aint gonna need it!\n    X22 = -s\u2082' * -X[1,2] + c\u2082 * X22\n\n    # Upper triangularize the second column of X\n    c\u2083, s\u2083, nrm\u2083 = givensAlgorithm(X32, T(1))\n    c\u2084, s\u2084, nrm\u2084 = givensAlgorithm(X22, nrm\u2083)\n\n    return c\u2081, s\u2081, c\u2082, s\u2082, c\u2083, s\u2083, c\u2084, s\u2084\nend\n\n\"\"\"\n    swap12_rotations(X) \u2192 c\u2081, s\u2081, c\u2082, s\u2082\n\nConstruct two Given's rotations that transform\n```\n  -x\u2081\u2081 -x\u2081\u2082\n   1    .\n   .    1\n```\nto upper triangular form:\n```\n  x x  \u21d2  * *  \u21d2  x x\n  1 .  \u21d2  . *  \u21d2  . *\n  . 1  \u21d2  . 1  \u21d2  . .\n```\n\"\"\"\nfunction swap12_rotations(X::SMatrix{1,2,T}) where {T}\n    # Upper triangulize first column of X\n    c\u2081, s\u2081, nrm\u2081\u2081 = givensAlgorithm(-X[1,1], T(1))\n\n    # Apply the Givens rotations to the second column of X\n    # X12 = c\u2081\u2081 * -X[1,2] # + s\u2081\u2081 * 0 # ain't gonna need it!\n    X22 = -s\u2081' * -X[1,2] # + c\u2081\u2081 * 0\n\n    # Upper triangularize the second column of X\n    c\u2082, s\u2082, nrm\u2081\u2082 = givensAlgorithm(X22, T(1))\n\n    return c\u2081, s\u2081, c\u2082, s\u2082\nend\n\n\n\"\"\"\n    swap21_rotations(X) \u2192 c\u2081, s\u2081, c\u2082, s\u2082\n\nConstruct two Given's rotations that transform\n```\n  -x\u2081\u2081 \n  -x\u2082\u2081\n   1\n```\nto upper triangular form:\n```\n  x  \u21d2  x  \u21d2  x\n  x  \u21d2  *  \u21d2  .\n  1  \u21d2  .  \u21d2  .\n```\n\"\"\"\nfunction swap21_rotations(X::SMatrix{2,1,T}) where {T}\n    c\u2081, s\u2081, nrm\u2081 = givensAlgorithm(-X[2,1], T(1))\n    c\u2082, s\u2082, nrm\u2082 = givensAlgorithm(-X[1,1], nrm\u2081)\n    return c\u2081, s\u2081, c\u2082, s\u2082\nend\n\n\"\"\"\n    swap22!(R, i) \u2192 R\n\nSwap a 2\u00d72 block with a 2\u00d72 block in R[i:i+4,i:i+4] via unitary transformations.\n```\n    i\n    \u2193\ni \u2192 x x * *  \u21d2  y y * *\n    x x * *  \u21d2  y y * *\n    . . y y  \u21d2  . . x x\n    . . y y  \u21d2  . . 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\u2081,s\u2081, c\u2082,s\u2082, c\u2083,s\u2083, c\u2084,s\u2084 = swap22_rotations(X)\n        G\u2081 = Rotation3(c\u2081, s\u2081, c\u2082, s\u2082, i+0)\n        G\u2082 = Rotation3(c\u2083, s\u2083, c\u2084, s\u2084, i+1)\n\n        # Apply to R\n        lmul!(G\u2081, R, i, n)\n        rmul!(R, G\u2081, 1, i+3)\n        lmul!(G\u2082, R, i, n)\n        rmul!(R, G\u2082, 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\u2081)\n        rmul!(Q, G\u2082)\n    end\n\n    R\nend\n\n\"\"\"\n    swap21!(R, i) \u2192 R\n\nSwap a 1\u00d71 block with a 2\u00d72 block in R[i:i+3,i:i+3] via unitary transformations\n```\n    i\n    \u2193\ni \u2192 x x *  \u21d2  y * *\n    x x *  \u21d2  . x x\n    . . y  \u21d2  . 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\u2081,s\u2081, c\u2082,s\u2082 = swap21_rotations(X)\n        G\u2081 = Rotation3(c\u2081, s\u2081, c\u2082, s\u2082, i)\n\n        # Apply rotations\n        lmul!(G\u2081, R, i, n)\n        rmul!(R, G\u2081, 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\u2081)\n    end\n    \n    R\nend\n\n\"\"\"\n    swap12!(R, i) \u2192 R\n\nSwap a 1\u00d71 block with a 2\u00d72 block in R[i:i+3,i:i+3] via unitary transformations\n```\n    i\n    \u2193\ni \u2192 y * *  \u21d2  x x *\n    . x x  \u21d2  x x *\n    . x x  \u21d2  . . 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\u2081,s\u2081, c\u2082,s\u2082 = swap12_rotations(X)\n        G\u2081 = Rotation2(c\u2081, s\u2081, i+0)\n        G\u2082 = Rotation2(c\u2082, s\u2082, i+1)\n\n        # Apply rotations\n        lmul!(G\u2081, R, i, n)\n        rmul!(R, G\u2081, 1, i+2)\n        lmul!(G\u2082, R, i, n)\n        rmul!(R, G\u2082, 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\u2081)\n        rmul!(Q, G\u2082)\n    end\n    \n    R\nend\n\n\"\"\"\n    swap11!(R, i) \u2192 R\n\nSwap a 1\u00d71 block with a 1\u00d71 block in R[i:i+1,i:i+1] via unitary transformations\n    i\n    \u2193\ni \u2192 x *  \u21d2  y *\n    . y  \u21d2  . x\n\"\"\"\nfunction swap11!(R::AbstractMatrix, i::Integer, Q = NotWanted())\n    m, n = size(R)\n\n    @inbounds begin\n        R\u2081\u2081 = R[i+0,i+0]\n        R\u2081\u2082 = R[i+0,i+1]\n        R\u2082\u2082 = 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\u2081\u2082, R\u2082\u2082 - R\u2081\u2081, 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\u2082\u2082\n        R[i+1,i+1] = R\u2081\u2081\n\n        # Accumulate\n        rmul!(Q, G)\n    end\n\n    R\nend\n\n\"\"\"\n    swap!(R, i, curr_11, next_11, Q) \u2192 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": "using HypothesisTests, Distributions, Base.Test\n\n# One sample test\nn = 1000\nsrand(1984948)\n\nx = rand(Normal(), n)\nt = OneSampleADTest(x, Normal())\n@test_approx_eq_eps t.A\u00b2 0.2013 0.1^4\n@test_approx_eq_eps pvalue(t) 0.8811 0.1^4\n\nx = rand(DoubleExponential(), n)\nt = OneSampleADTest(x, Normal())\n@test_approx_eq_eps t.A\u00b2 10.7439 0.1^4\n@test_approx_eq_eps pvalue(t) 0.0 0.1^4\n\nx = rand(Cauchy(), n)\nt = OneSampleADTest(x, Normal())\n@test pvalue(t) < 1e-100\n\nx = rand(LogNormal(), n)\nt = OneSampleADTest(x, Normal())\n@test pvalue(t) < 1e-100\n\n# k-sample test\nsamples = Any[\n    [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0],\n    [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8],\n    [34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0],\n    [34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]\n]\n\nt = KSampleADTest(samples...)\n@test_approx_eq_eps t.A\u00b2k 8.3926 0.1^4\n@test_approx_eq_eps t.\u03c3 1.2038 0.1^4\n@test_approx_eq_eps pvalue(t) 0.0020 0.1^4\n\nt = KSampleADTest(samples..., modified = false)\n@test_approx_eq_eps t.A\u00b2k 8.3559 0.1^4\n@test_approx_eq_eps t.\u03c3 1.2038 0.1^4\n@test_approx_eq_eps pvalue(t) 0.0021 0.1^4\n\nsrand(31412455)\nsamples = Any[rand(Normal(), 50), rand(Normal(0.5), 30)]\nt = KSampleADTest(samples...)\n@test pvalue(t) < 0.05\n\nsamples = Any[rand(Normal(), 50), rand(Normal(), 30), rand(Normal(), 20)]\nt = KSampleADTest(samples...)\n@test pvalue(t) > 0.05\n\n@test pvalue(OneSampleADTest(vcat(rand(Normal(),500), rand(Beta(2,2),500)), Beta(2,2))) == 0\n", "meta": {"hexsha": "1ae2296c1ad14802288c89e063832f1d704b8baa", "size": 1455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/anderson_darling.jl", "max_stars_repo_name": "bjarthur/HypothesisTests.jl", "max_stars_repo_head_hexsha": "a964ed55157664c8c8bc3b01cc48f71fef1c90ce", "max_stars_repo_licenses": ["MIT"], "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/anderson_darling.jl", "max_issues_repo_name": "bjarthur/HypothesisTests.jl", "max_issues_repo_head_hexsha": "a964ed55157664c8c8bc3b01cc48f71fef1c90ce", "max_issues_repo_licenses": ["MIT"], "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/anderson_darling.jl", "max_forks_repo_name": "bjarthur/HypothesisTests.jl", "max_forks_repo_head_hexsha": "a964ed55157664c8c8bc3b01cc48f71fef1c90ce", "max_forks_repo_licenses": ["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.4528301887, "max_line_length": 92, "alphanum_fraction": 0.6597938144, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7540087789059914}}
{"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\u00f7b\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#\u00a0Returns distance from cylinder center, squared\n#\u00a0query: DenseVector for which to compute cylindrical norm\n#\u00a0d\u2080: Direction of the cylinder\n#\u00a0center: Center of cylinder goes through this point\nfunction cylindrical_norm_squared{T}(query::DenseVector{T}, d\u2080::DenseVector{T}, center::DenseVector{T})\n    @assert length(d\u2080) == length(center) == length(query)\n    @assert norm(d\u2080, 1) > 1e-8\n    q\u2080 = query - center\n    q\u27c2 = q\u2080 - (q\u2080\u22c5d\u2080)d\u2080 / (d\u2080\u22c5d\u2080)\n    q\u27c2\u22c5q\u27c2\nend\n\n#\u00a0True if query point is inside cylinder\n#\u00a0query: DenseVector for which to compute cylindrical norm\n#\u00a0d\u2080: Direction of the cylinder\n#\u00a0center: Center of cylinder goes through this point\n#\u00a0radius: of the cylinder\nfunction is_in_pipe{T}(query::DenseVector{T}, d\u2080::DenseVector{T}, center::DenseVector{T}, radius::T)\n    cylindrical_norm_squared(query, d\u2080, center) <= (radius^2)\nend\n\n#\u00a0True if in half-space defined by normal and offset\n#\u00a0query: DenseVector for which to compute condition\n#\u00a0d\u2080: Normal to the plane defining the half-space\n#\u00a0origin: Origin of the plane defining the half-space\nfunction is_in_half_space{T}(query::DenseVector{T}, d\u2080::DenseVector{T}, origin::DenseVector{T})\n    @assert length(d\u2080) == length(origin) == length(query)\n    @assert norm(d\u2080, 1) > 1e-8\n    (query - origin)\u22c5d\u2080 >= 0\nend\n\n\n#\u00a0True if in sphere defined by center and radius\n#\u00a0query: 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\u2080 = center - query\n    q\u2080\u22c5q\u2080 <= 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": "######################################################\n### This test implements example 13.5 in Greene (2012)\n######################################################\n\n# this is the data from Example C.1 in Greene 2012\nincome_data = [20.5, 31.5, 47.7, 26.2, 44, 8.28, 30.8, 17.2, 19.9, 9.96,\n               55.8, 25.2, 29, 85.5, 15.1, 28.5, 21.4, 17.7, 6.42, 84.9]\n\nfunction g_gamma(\u03b8)\n    P, \u03bb = \u03b8[1], \u03b8[2]\n    hcat(income_data - P / \u03bb,\n         income_data.^2 - P*(P+1) / (\u03bb^2),\n         log(income_data) + log(\u03bb) - digamma(P),\n         1./income_data - \u03bb/(P - 1))\nend\n\ntwo_step = GMM.gmm(g_gamma, [2.40, 0.08], [0.0, 0.0], [Inf, Inf], eye(4);\n                   mgr=GMM.TwoStepGMM())\n", "meta": {"hexsha": "502334c196f8d38fb8ebc8462ee9c44e023426c7", "size": 685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/gamma_dist.jl", "max_stars_repo_name": "sglyon/GMM.jl", "max_stars_repo_head_hexsha": "532afcc73d60168b9286d0d46ba5e3aed5be8f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-27T07:42:15.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-27T07:42:15.000Z", "max_issues_repo_path": "test/gamma_dist.jl", "max_issues_repo_name": "spencerlyon2/GMM.jl", "max_issues_repo_head_hexsha": "532afcc73d60168b9286d0d46ba5e3aed5be8f1d", "max_issues_repo_licenses": ["MIT"], "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/gamma_dist.jl", "max_forks_repo_name": "spencerlyon2/GMM.jl", "max_forks_repo_head_hexsha": "532afcc73d60168b9286d0d46ba5e3aed5be8f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:26:59.000Z", "avg_line_length": 36.0526315789, "max_line_length": 73, "alphanum_fraction": 0.4437956204, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7539749569472242}}
{"text": "include(\"../functions/Functions.jl\")\ninclude(\"../evaluate/Evaluate.jl\")\ninclude(\"../opt/pgd.jl\")\ninclude(\"../data/data.jl\")\ninclude(\"../plot/Plotting.jl\")\n\n#using Plotting\n\nX, y = getOldData()\n\nx0 = zeros(size(X,2),1)\n\nlambda = 0\n\niter = 1000\nstep = 0.01\n\nf = f_logreg(X,y,x0,lambda)\ng = g_logreg(X,y,x0,0)\n\n#f = f_svm(X,y,x0,lambda)\n#g = sub_g_svm()\n\nprox_operator = SqrNormL2(lambda/2)\n\n@time (theta,state,val_array,stop_array) = pgd(X,y,x0,f,g,1e-8,lambda,iter,step,size(X,1),prox_operator)\n\n#plotArray(val_array, \"sgd1.svg\")\n\ngrad = g(theta)\ngrad_norm = norm(grad, Inf)\n@printf(\"Inf-Norm of gradient is %f.\\n\",grad_norm)\nprintln(evaluate(X,y,theta,\"logreg\",false))\n", "meta": {"hexsha": "54cd848cab56892f67145f08a7a56eddc6ce88a5", "size": 669, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test/pgd_test.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/test/pgd_test.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/test/pgd_test.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": 19.6764705882, "max_line_length": 104, "alphanum_fraction": 0.6816143498, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7539749519233703}}
{"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 \u2265 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 \u2265 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\u03bbmap(p)\nSends a point on a 3-sphere to a point in the plane x\u2084=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\u00b3 \u21a6 R\u00b3\n\"\"\"\nfunction \u03bbmap(p)\n    [real(p[1]), imag(p[1]), real(p[2])] ./ (1 - imag(p[2]))\nend\n\n\n\"\"\"\n\u03bb\u207b\u00b9map(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 \u03bb\u207b\u00b9map(p)\n    x\u2081 = 2p[1] / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    x\u2082 = 2p[2] / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    x\u2083 = 2p[3] / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    x\u2084 = (-1 + p[1]^2 + p[2]^2 + p[3]^2) / (1 + p[1]^2 + p[2]^2 + p[3]^2)\n    [Complex(x\u2081, x\u2082), Complex(x\u2083, x\u2084)]\nend\n\n\n\"\"\"\nS\u00b9action(\u03b1, 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\u00b9action(\u03b1, p)\n    [exp(im * \u03b1) * p[1], exp(im * \u03b1) * 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          \u03d5 = atan(p[2] / p[1])\n    elseif p[2] > 0\n          \u03d5 = atan(p[2] / p[1]) + pi\n    else\n          \u03d5 = atan(p[2] / p[1]) - pi\n    end\n    \u03b8 = asin(p[3] / r)\n    [\u03d5, \u03b8]\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 = \u03bb\u207b\u00b9map(convert_to_cartesian(point))\n    A = \u03bbmap(S\u00b9action(pi / 6, b))\n    B = \u03bbmap(S\u00b9action(pi / 4, b))\n    C = \u03bbmap(S\u00b9action(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\u2081 = (Q[1] + (R + r * cos(longitude)) * cos(latitude)) / R\n            x\u2082 = (Q[2] + (R + r * cos(longitude)) * sin(latitude)) / R\n            x\u2083 = (Q[3] + r * sin(longitude)) / R\n            manifold[i, j, :] = rotate3D_cartesian([x\u2081, x\u2082, x\u2083], 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\u03d5 = Node(0.0)\nq = @lift(Quaternion(sin($\u03d5)*u[1],\n                     sin($\u03d5)*u[2],\n                     sin($\u03d5)*u[3],\n                     cos($\u03d5)))\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\u2081, x\u2082, x\u2083 = convert_to_cartesian($rotated)\n        fill(RGBAf0(rand()/3+2x\u2081/3, rand()/3+2x\u2082/3, rand()/3+2x\u2083/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        \u03d5[] = 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\u2207F(X::Array{Float64,2}) = -sum([log(M, X, B) for B in A]) / m\n\n@time quasi_Newton(\n    M,\n    F,\n    \u2207F,\n    x;\n    memory_size=100,\n    stopping_criterion=StopWhenGradientNormLess(norm(M, x, \u2207F(x)) * 10^(-6)),\n    debug=[:Iteration, \" \", :Cost, \"\\n\", 1, :Stop],\n)\n\n# B1 = quasi_Newton(M,F,\u2207F,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": "@testset \"Elliptic Curve Point Operations\" begin\n    @testset \"Integer Type\" begin\n        @testset \"Not Equal\" begin\n            a = ECC.Point(3, -7, 5, 7)\n            b = ECC.Point(18, 77, 5, 7)\n            @test a != b\n            @test !(a != a)\n        end\n        @testset \"On Curve?\" begin\n            @test_throws DomainError ECC.Point(-2, 4, 5, 7)\n            @test typeof(ECC.Point(3, -7, 5, 7)) <: ECC.Point\n            @test typeof(ECC.Point(18, 77, 5, 7)) <: ECC.Point\n        end\n        @testset \"Addition\" begin\n            @testset \"Base Case\" begin\n                a = ECC.Point(\u221e, \u221e, 5, 7)\n                b = ECC.Point(2, 5, 5, 7)\n                c = ECC.Point(2, -5, 5, 7)\n                @test a + b == b\n                @test b + a == b\n                @test b + c == a\n            end\n\n            @testset \"Case 1\" begin\n                a = ECC.Point(3, 7, 5, 7)\n                b = ECC.Point(-1, -1, 5, 7)\n                @test a + b == ECC.Point(2, -5, 5, 7)\n            end\n\n            @testset \"Case 2\" begin\n                a = ECC.Point(-1, 1, 5, 7)\n                @test a + a == ECC.Point(18, -77, 5, 7)\n            end\n        end\n    end;\n\n    @testset \"FiniteElement Type\" begin\n        @testset \"On curve?\" begin\n            \ud835\udc5d = 223\n            \ud835\udc4e, \ud835\udc4f = ECC.FieldElement(0, \ud835\udc5d), ECC.FieldElement(7, \ud835\udc5d)\n\n            valid_points = ((192, 105), (17, 56), (1, 193))\n            invalid_points = ((200, 119), (42, 99))\n\n            for \ud835\udc43 \u2208 valid_points\n                \ud835\udc65 = ECC.FieldElement(\ud835\udc43[1], \ud835\udc5d)\n                \ud835\udc66 = ECC.FieldElement(\ud835\udc43[2], \ud835\udc5d)\n                @test typeof(ECC.Point(\ud835\udc65, \ud835\udc66, \ud835\udc4e, \ud835\udc4f)) <: ECC.Point\n            end\n\n            for \ud835\udc43 \u2208 invalid_points\n                \ud835\udc65 = ECC.FieldElement(\ud835\udc43[1], \ud835\udc5d)\n                \ud835\udc66 = ECC.FieldElement(\ud835\udc43[2], \ud835\udc5d)\n                @test_throws DomainError ECC.Point(\ud835\udc65, \ud835\udc66, \ud835\udc4e, \ud835\udc4f)\n            end\n        end\n        @testset \"Addition\" begin\n            \ud835\udc5d = 223\n            \ud835\udc4e = ECC.FieldElement(0, \ud835\udc5d)\n            \ud835\udc4f = ECC.FieldElement(7, \ud835\udc5d)\n\n            additions = (\n                (192, 105, 17, 56, 170, 142),\n                (47, 71, 117, 141, 60, 139),\n                (143, 98, 76, 66, 47, 71),\n                )\n\n            for \ud835\udc5b \u2208 additions\n                \ud835\udc43 = ECC.Point(ECC.FieldElement(\ud835\udc5b[1],\ud835\udc5d),ECC.FieldElement(\ud835\udc5b[2],\ud835\udc5d),\ud835\udc4e,\ud835\udc4f)\n                \ud835\udc44 = ECC.Point(ECC.FieldElement(\ud835\udc5b[3],\ud835\udc5d),ECC.FieldElement(\ud835\udc5b[4],\ud835\udc5d),\ud835\udc4e,\ud835\udc4f)\n                \ud835\udc45 = ECC.Point(ECC.FieldElement(\ud835\udc5b[5],\ud835\udc5d),ECC.FieldElement(\ud835\udc5b[6],\ud835\udc5d),\ud835\udc4e,\ud835\udc4f)\n                @test \ud835\udc43 + \ud835\udc44 == \ud835\udc45\n            end\n        end\n        @testset \"Scalar Multiplication\" begin\n            \ud835\udc5d = 223\n            \ud835\udc4e = ECC.FieldElement(0, \ud835\udc5d)\n            \ud835\udc4f = ECC.FieldElement(7, \ud835\udc5d)\n\n            multiplications = (\n                (2, 192, 105, 49, 71),\n                (2, 143, 98, 64, 168),\n                (2, 47, 71, 36, 111),\n                (4, 47, 71, 194, 51),\n                (8, 47, 71, 116, 55),\n                (21, 47, 71, \u221e, \u221e)\n                )\n\n            for \ud835\udc5b \u2208 multiplications\n                \u03bb = \ud835\udc5b[1]\n                i = 2\n                fieldelements = []\n                while i < 6\n                    if \ud835\udc5b[i] == \u221e\n                        push!(fieldelements, \u221e)\n                    else\n                        push!(fieldelements, ECC.FieldElement(\ud835\udc5b[i],\ud835\udc5d))\n                    end\n                    i += 1\n                end\n                \ud835\udc43 = ECC.Point(fieldelements[1],fieldelements[2],\ud835\udc4e,\ud835\udc4f)\n                \ud835\udc45 = ECC.Point(fieldelements[3],fieldelements[4],\ud835\udc4e,\ud835\udc4f)\n                @test \u03bb * \ud835\udc43 == \ud835\udc45\n            end\n        end\n    end;\nend\n", "meta": {"hexsha": "eda270f0f8b0eb7c4c20416d904e6422868f2b5c", "size": 3564, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/point_tests.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": "test/point_tests.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": "test/point_tests.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": 33.0, "max_line_length": 84, "alphanum_fraction": 0.3992704826, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133554, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.753884400715229}}
{"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": "# diagonal operators: joDiag\n\nexport joDiag\n\"\"\"\n    julia> op = joDiag(v;[makecopy=...,][DDT=...,][RDT=...,][name=...])\n\nDiagonal matrix with elements from given vector\n\n# Signature\n\n    function joDiag(v::LocalVector{EDT};makecopy::Bool=true,\n        DDT::DataType=EDT,RDT::DataType=promote_type(EDT,DDT),name::String=\"joDiag\") where {EDT}\n\n# Arguments\n\n- `v`: vector of diagonal elements\n- keywords\n    - `DDT`: domain data type\n    - `RDT`: range data type\n    - `name`: custom name\n\n# Examples\n\n    joDiag(rand(m))\n\nexamples with DDT/RDT\n\n    joDiag(rand(m); DDT=Float32)\n    joDiag(rand(m); DDT=Float32,RDT=Float64)\n\n\"\"\"\nfunction joDiag(v::LocalVector{EDT};makecopy::Bool=true,\n    DDT::DataType=EDT,RDT::DataType=promote_type(EDT,DDT),name::String=\"joDiag\") where {EDT}\n\n    vc= makecopy ? Base.deepcopy(v) : v\n    \n    return joMatrix(Diagonal(vc);DDT=DDT,RDT=RDT,name=name)\nend\n\n", "meta": {"hexsha": "9dcf99c6cdadfcaf437dff70db36f27975704f1b", "size": 887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/joMatrixConstructors/joDiag.jl", "max_stars_repo_name": "slimgroup/JOLI.jl", "max_stars_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-02-28T21:50:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T16:03:45.000Z", "max_issues_repo_path": "src/joMatrixConstructors/joDiag.jl", "max_issues_repo_name": "slimgroup/JOLI.jl", "max_issues_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-08-03T21:02:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T20:17:27.000Z", "max_forks_repo_path": "src/joMatrixConstructors/joDiag.jl", "max_forks_repo_name": "slimgroup/JOLI.jl", "max_forks_repo_head_hexsha": "c1f669e34353394fd9a4711dc0038cf697bc0ad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-11-11T02:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T16:06:20.000Z", "avg_line_length": 22.175, "max_line_length": 96, "alphanum_fraction": 0.6651634724, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7538675472185368}}
{"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# \u2554\u2550\u2561 0f6cd296-6cb8-4a9d-a21f-02b689dfe4e9\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(aside=true)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9ab98160-3e37-44c3-b219-a3e1bf95fd68\nusing Arpack\n\n# \u2554\u2550\u2561 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\u010dica Miro\u0161evi\u0107.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1bc20329-3a6e-435d-a25c-8cce79fb7d9d\nmd\"\n## Examples\n\n### Small term-by- document matrix\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1a8b6f7b-4098-4cd2-adad-8ee788b47333\nmynames=[\"Term 1\";\"Term 2\";\"Term 3\";\"Term 4\";\"Term 5\";\"Doc 1\";\"Doc 2\"]\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d5d8ee5d-9cce-45fc-a31b-b2ed8237cc86\nW=WeightMatrix(tn,dn,wn)\n\n# \u2554\u2550\u2561 86fd4f5a-af57-490d-a17f-2339a9414057\nMatrix(W)\n\n# \u2554\u2550\u2561 1f53b5cf-ab6a-4107-b53b-9ce96afcdb7f\nbegin\n\tL=Laplacian(W)\n\tMatrix(L)\nend\n\n# \u2554\u2550\u2561 63403411-cca4-4d71-8a76-8dea8638f69f\nL\u2099=NormalizedLaplacian(L)\n\n# \u2554\u2550\u2561 3cf471bc-d316-4de9-af63-71db9b035c40\nbegin\n\tA=W[1:5,6:7]\n\t\u0394\u2081=sqrt.(sum(A,dims=2))\n\t\u0394\u2082=sqrt.(sum(A,dims=1))\n\tA\u2099=[A[i,j]/(\u0394\u2081[i]*\u0394\u2082[j]) for i=1:size(A,1), j=1:size(A,2)]\nend\n\n# \u2554\u2550\u2561 ac0b5eda-299c-4ae2-ae78-bda92b378f19\n# The partitioning - explain the results!\nU,\u03c3,V=svd(A\u2099)\n\n# \u2554\u2550\u2561 9bf6bbca-f96c-4b38-a4fd-5188ec29a2a2\nU[:,2]\n\n# \u2554\u2550\u2561 aa51688c-21a0-40f4-a6d6-01d441bfd4b7\nV[:,2]\n\n# \u2554\u2550\u2561 5f27f1a2-80de-41d1-b1e2-da3a99493217\nmd\"\n### Sets of points\n\"\n\n# \u2554\u2550\u2561 e1149b05-d594-4d75-ae56-1ce18bd0f60d\nspy(Matrix(B))\n\n# \u2554\u2550\u2561 b95d4070-c127-4db0-987b-5fc17421b667\n# The structure of singular vectors reflects the block\nS,rest\u2080=svds(B,nsv=3);\n\n# \u2554\u2550\u2561 57d472c1-548d-4678-b884-85f863771aa7\n# S is a structure\nS.S\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e4487f35-5de0-492e-96f1-69318d7d8e8b\nmd\"\"\"\n__Question.__ Given D, can we recover C?\n\n__Answer.__ Yes (with spectral partitioning)!\n\"\"\"\n\n# \u2554\u2550\u2561 81d99f24-82b9-4216-8d17-6a18317beb77\nS\u2099,rest=svds(D,nsv=3);\n\n# \u2554\u2550\u2561 8f925ff7-90b4-4fe4-a869-86dec693c0f4\n# K-means on rows of U \noutU=kmeans(Matrix(transpose(S\u2099.U)),3)\n\n# \u2554\u2550\u2561 d446724a-97d1-403f-baaf-d0619203f351\n# K-means on Vt\noutV=kmeans(S\u2099.Vt,3)\n\n# \u2554\u2550\u2561 7572c241-dbcc-4094-97e3-ee3172255294\nsortperm(outU.assignments)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25000f6cd296-6cb8-4a9d-a21f-02b689dfe4e9\n# \u255f\u250089299cb7-a4eb-48f3-b3f1-ab2b5c6cfa2e\n# \u255f\u2500a92d0e70-479d-444e-b06d-e47d2e385b10\n# \u255f\u2500fddcc2a7-f718-4900-a135-764eb36496a7\n# \u255f\u2500b3b44560-203a-11eb-2782-170e4c12627a\n# \u255f\u25001be90f30-203b-11eb-34da-c3116523ec3a\n# \u255f\u25005211ce2e-203b-11eb-0b6f-55e809177fb9\n# \u255f\u250038333a20-203c-11eb-2b28-59e07b3e50ee\n# \u255f\u25001bc20329-3a6e-435d-a25c-8cce79fb7d9d\n# \u2560\u2550646a9fc2-3a73-4f8d-a952-2cdcf0e6287a\n# \u2560\u2550b9d0830a-0a33-40c1-a08a-49538cf7a879\n# \u2560\u2550b6d41ab1-24f2-417d-b604-3e12384e65f8\n# \u2560\u2550f6492dfe-faac-407f-9a0e-5dcf321a4f2d\n# \u2560\u25501a8b6f7b-4098-4cd2-adad-8ee788b47333\n# \u2560\u25504079aa8e-2bb5-4d51-bca8-04d0997db2bf\n# \u2560\u2550d5d8ee5d-9cce-45fc-a31b-b2ed8237cc86\n# \u2560\u255086fd4f5a-af57-490d-a17f-2339a9414057\n# \u2560\u25501f53b5cf-ab6a-4107-b53b-9ce96afcdb7f\n# \u2560\u255063403411-cca4-4d71-8a76-8dea8638f69f\n# \u2560\u25503cf471bc-d316-4de9-af63-71db9b035c40\n# \u2560\u2550ac0b5eda-299c-4ae2-ae78-bda92b378f19\n# \u2560\u25509bf6bbca-f96c-4b38-a4fd-5188ec29a2a2\n# \u2560\u2550aa51688c-21a0-40f4-a6d6-01d441bfd4b7\n# \u255f\u25005f27f1a2-80de-41d1-b1e2-da3a99493217\n# \u2560\u25507cd3af86-f459-4e4b-8e35-c29bc6966eed\n# \u2560\u2550e1149b05-d594-4d75-ae56-1ce18bd0f60d\n# \u2560\u25509ab98160-3e37-44c3-b219-a3e1bf95fd68\n# \u2560\u2550b95d4070-c127-4db0-987b-5fc17421b667\n# \u2560\u255057d472c1-548d-4678-b884-85f863771aa7\n# \u2560\u25504806378b-63cb-445a-8c71-583458fce846\n# \u2560\u2550a08c99a3-9c10-47be-9dc6-987d92a85087\n# \u2560\u25506888e8a9-f306-4490-9147-2460fbda4889\n# \u2560\u25503bd5ad15-31cd-4efd-b4e3-7cf7ede3edae\n# \u255f\u2500e4487f35-5de0-492e-96f1-69318d7d8e8b\n# \u2560\u255081d99f24-82b9-4216-8d17-6a18317beb77\n# \u2560\u25508f925ff7-90b4-4fe4-a869-86dec693c0f4\n# \u2560\u2550d446724a-97d1-403f-baaf-d0619203f351\n# \u2560\u25507572c241-dbcc-4094-97e3-ee3172255294\n# \u2560\u255022e90c11-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 = 10 # rand(1:10)\nA = matrixdepot(\"minij\", n)\n@test issymmetric(A)\n@test isposdef(A)\nprintln(\"'minij' passed test...\")\n", "meta": {"hexsha": "f19a4ba0f46bb06f23bf4e186c298831a28cb069", "size": 121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_minij.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-01-16T15:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:33:08.000Z", "max_issues_repo_path": "test/test_minij.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2017-12-01T11:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:41:57.000Z", "max_forks_repo_path": "test/test_minij.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-12T17:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-13T00:28:37.000Z", "avg_line_length": 20.1666666667, "max_line_length": 33, "alphanum_fraction": 0.652892562, "num_tokens": 41, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7538675429341034}}
{"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 test_diagnosticsteps(dev::Device=CPU(); nsteps=100, freq=1, ndata=ceil(Int, (nsteps+1)/freq))\n  prob = Problem(nx=6, Lx=2\u03c0, dev=dev)\n  getone(prob) = 1\n  d = Diagnostic(getone, prob, nsteps=nsteps, freq=freq, ndata=ndata)\n  stepforward!(prob, d, nsteps)\n  expectedsteps = cat([0], freq:freq:nsteps, dims=1)\n  d.steps[1:d.i] == expectedsteps\nend\n\nfunction test_scalardiagnostics(dev::Device=CPU(); nx=6, Lx=2\u03c0, kappa=1e-2, nsteps=100, freq=1, ndata=ceil(Int, (nsteps+1)/freq))\n  k1 = 2\u03c0/Lx\n   \u03c4 = 1/(kappa*k1^2) # time-scale for diffusive decay\n  dt = 1e-4 * \u03c4 # dynamics are resolved.\n\n  prob = Problem(nx=nx, Lx=Lx, kappa=kappa, dt=dt, stepper=\"ETDRK4\", dev=dev)\n  g = prob.grid\n\n  ct(t) = exp(-kappa*k1^2*t)\n\n  t1 = dt*nsteps\n  c0 = @. sin(k1*g.x)\n  c1 = @. ct(t1) * c0 # analytical solution\n\n  set_c!(prob, c0)\n\n  variance(prob) = parsevalsum2(prob.sol, prob.grid) / Lx\n  d = Diagnostic(variance, prob, nsteps=nsteps, freq=freq, ndata=ndata)\n\n  stepforward!(prob, d, nsteps)\n\n  da = @. 0.5*ct(d[:t])^2\n  isapprox(d[:data], da)\nend\n\nfunction test_basicdiagnostics(dev::Device=CPU(); nx=6, Lx=2\u03c0, kappa=1e-2)\n  k1 = 2\u03c0/Lx\n   \u03c4 = 1/(kappa*k1^2) # time-scale for diffusive decay\n  dt = 1e-2 * \u03c4 # dynamics are resolved.\n\n  prob = Problem(nx=nx, Lx=Lx, kappa=kappa, dt=dt, stepper=\"ETDRK4\", dev=dev)\n  g = prob.grid\n\n  c0(x) = sin(k1*x)\n  set_c!(prob, c0)\n\n  getsol(prob) = prob.sol\n  soldiag = Diagnostic(getsol, prob, nsteps=1)\n\n  stepforward!(prob, soldiag, 1)\n\n  isapprox(soldiag.data[soldiag.i], prob.sol)\nend\n", "meta": {"hexsha": "0a77e31cda8b1b754081db7cead12d8dbe759183", "size": 1522, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_diagnostics.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_diagnostics.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_diagnostics.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": 28.7169811321, "max_line_length": 129, "alphanum_fraction": 0.6550591327, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7538594452869058}}
{"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#\u00a0i.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#\u00a0i.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": "using PartialSvdStoch, Test\n\nusing LowRankApprox\n\n\nfunction testvrpca_withLowRankApprox(mat, k)\n    #\n    normMat = norm(mat)\n    # get initial spectrum from psvd\n    opts = LRAOptions(rank=k, rtol=0.001)\n    @info \"testvrpca_withLowRankApprox : initialization\"\n    @time Uguess, Sguess, Vguess = psvd(mat,opts)\n    matGuess = Uguess * diagm(Sguess) * transpose(Vguess)\n    deltaMatGuess = norm(matGuess - mat)\n    @info \"rank obtained : \" size(Uguess)[2]\n    @info \" residual Error , initial L2 norm \" deltaMatGuess normMat\n    @info \" relative error at initialization \" deltaMatGuess/normMat\n    #\n    eta = 0.01\n    batchSize = 20\n    @info \"doing vrpca svd  with rank initialization...\" eta batchSize\n    pcaPb = VrPCA(mat, k) \n    @time iterateVrPCA(pcaPb, eta, batchSize)\n    U = PartialSvdStoch.getindex(pcaPb,:U)\n    S = PartialSvdStoch.getindex(pcaPb,:S)\n    Vt = PartialSvdStoch.getindex(pcaPb,:Vt)\n    # it happens that the obtained rank is less than asked for\n    obtainedRank = pcaPb.k\n    matVrpca = U.value * diagm(S.value) * Vt.value\n    deltaMatIter = norm(matVrpca - mat)\n    normMat = norm(mat)\n    @info \"deltaS after vr\"  norm(matVrpca - mat) normMat\n    relErr = deltaMatIter/normMat\n    @info \" relative error after vrpca iterations : \" deltaMatIter/normMat\n    relErr < 0.05 ? true : false\nend\n\n\n\"\"\"\n# function testvrpca_withepsil(mat, epsil)\n\nThis test extracts the rank to get approximation at given precision epsil\nsee test : vrpca_epsil\n\"\"\"\nfunction testvrpca_withepsil(mat, epsil)\n    #\n    normMat = norm(mat)\n    @info \"testvrpca_withepsil : doing vrpca initialization with epsil\" epsil\n    pcaPb = VrPCA(mat, epsil) \n    #\n    eta = 0.01\n    batchSize = 20\n    @info \"doing vrpca svd iteration\" eta batchSize\n    @time iterateVrPCA(pcaPb, eta, batchSize)\n    #\n    U = PartialSvdStoch.getindex(pcaPb,:U)\n    S = PartialSvdStoch.getindex(pcaPb,:S)\n    Vt = PartialSvdStoch.getindex(pcaPb,:Vt)\n    matVrpca = U.value * diagm(S.value) * Vt.value\n    relErr = norm(matVrpca - mat)/normMat\n    @info \"residual error after vr\"  norm(matVrpca - mat) normMat relErr\n    relErr < 0.05 ? true : false\nend", "meta": {"hexsha": "e0429006558f304f98c88101aca63107d50d50f4", "size": 2126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testvrpca.jl", "max_stars_repo_name": "jean-pierreBoth/PartialSvdStoch.jl", "max_stars_repo_head_hexsha": "81b60062448199ba88f0e6050ea1664a02fa17f1", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-01T16:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T15:16:36.000Z", "max_issues_repo_path": "test/testvrpca.jl", "max_issues_repo_name": "jean-pierreBoth/PartialSvdStoch.jl", "max_issues_repo_head_hexsha": "81b60062448199ba88f0e6050ea1664a02fa17f1", "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": "test/testvrpca.jl", "max_forks_repo_name": "jean-pierreBoth/PartialSvdStoch.jl", "max_forks_repo_head_hexsha": "81b60062448199ba88f0e6050ea1664a02fa17f1", "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": 33.746031746, "max_line_length": 77, "alphanum_fraction": 0.6890874882, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7538594358755707}}
{"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": "using Distributions\n\n######################################################################\n# utility functions\n######################################################################\n\n\"\"\"\nA wrapper for sampling from a given log density.\n\nUseful for testing MCMC.\n\"\"\"\nstruct DensityWrapper{T}\n    \"Log density function.\"\n    \u2113::T\nend\n\nlogdensity(dw::DensityWrapper, \u03b8) = dw.\u2113(\u03b8)\n\nsimulate!(::DensityWrapper) = nothing\n\n\"\"\"\n    normalize_logdensity(logdensity, x, xmin, xmax)\n\nReturn a logdensity function from an unnormalized `logdensity`.\n\n`x` should be a point where the density had a value that is not far\nform the typical region (eg the mode or the mean will be fine). This\nis used to correct the value *before* calculating the integral, for\nbetter accuracy.\n\n`xmin` and `xmax` are integration bounds.\n\"\"\"\nfunction normalize_logdensity(logdensity, x, xmin, xmax)\n    c = logdensity(x)\n    C, _ = hquadrature(x -> exp(logdensity(x)-c), xmin, xmax)\n    c += log(C)\n    x -> logdensity(x)-c\nend\n\npdf2cdf(pdf, xmin) =  x ->  hquadrature(pdf, xmin, x)[1]\n\n\"\"\"\n    test_cdf(density, xs[; ps, atol])\n\nCompare the random values `xs` to the given `cdf` (cumulative density)\nfunction. Comparison is made at `ps`, with absolute tolerance `atol`\n(in probability space). Useful for testing distributions.\n\"\"\"\nfunction test_cdf(cdf, xs; ps = 0.1:0.1:0.9, atol = 0.05)\n    for (p, x) in zip(ps, quantile(xs, ps))\n        @test p \u2248 cdf(x) atol = atol\n    end\nend\n\nfunction test_cdf(dist::Distribution{Univariate, Continuous}, xs; args...)\n    test_cdf(x ->  cdf(dist, x), xs; args...)\nend\n", "meta": {"hexsha": "d3ad6d1a2a66cffd3a780d2d440205b82da102ac", "size": 1576, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/utilities.jl", "max_stars_repo_name": "JuliaTagBot/HamiltonianABC.jl", "max_stars_repo_head_hexsha": "4e33873cb08bf608ad62ada62e545bda4ee321ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-22T21:08:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T01:42:05.000Z", "max_issues_repo_path": "test/utilities.jl", "max_issues_repo_name": "JuliaTagBot/HamiltonianABC.jl", "max_issues_repo_head_hexsha": "4e33873cb08bf608ad62ada62e545bda4ee321ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-05-23T18:47:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-16T22:24:38.000Z", "max_forks_repo_path": "test/utilities.jl", "max_forks_repo_name": "JuliaTagBot/HamiltonianABC.jl", "max_forks_repo_head_hexsha": "4e33873cb08bf608ad62ada62e545bda4ee321ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-19T09:13:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:48:18.000Z", "avg_line_length": 27.1724137931, "max_line_length": 74, "alphanum_fraction": 0.6262690355, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7538312017640124}}
{"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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03b1_\u03c4 =(1-\u03b2\u2082) * \u03b1_\u03c4 + \u03b2\u2082 * \u03c4\u2082 + \u03d5 * (log(r\u2081) - log(\u03c4\u2081)) + \u03c3\u2082 * shock_short * r\u2081^\u03b8\n```\n- **Dynamic and robust plotting libaraies** - `Plots.jl` in this case\n\n\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 63507e40-ea34-11ea-00c3-31bd881aa1bc\n@bind \u03c4\u2081 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2cc3d3b0-ea3c-11ea-2c4f-4bd1db712846\nmd\"### Scenario Visualization\"\n\n# \u2554\u2550\u2561 9a6a036e-b4f1-40a8-b3ea-724a1542fb26\nmd\"\n#### Long Rate Statistics:\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 844a9e50-f128-11ea-10b1-a1d7792c8fc4\nmd\"Example of one of the the scenarios:\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f15e18e0-ea3a-11ea-3868-d9236a4810a1\nmd\"The starting curve is based on 12/31/2020:\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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(\u03c4\u2081=0.035,vol=0.11489\n\t) = (\n\t\u03c4\u2081 = \u03c4\u2081,   # Long term rate (LTR) mean reversion\n\t\u03b2\u2081 = 0.00509, # Mean reversion strength for the log of the LTR\n\t\u03b8 = 1,\n\t\u03c4\u2082 = 0.01,    # Mean reversion point for the slope\n\t\u03b2\u2082 = 0.02685, # Mean reversion strength for the slope\n\t\u03c3\u2082 = 0.04148, # Volatitlity of the slope\n\t\u03c4\u2083 = 0.0287,  # mean reversion point for the vol of the log of LTR\n\t\u03b2\u2083 = 0.04001, # mean reversion strength for the log of the vol of the log of LTR\n\t\u03c3\u2083 = vol, # vol of the stochastic vol process\n\t\u03c1\u2081\u2082 = -0.19197, # correlation of shocks to LTR and slope (long - short)\n\t\u03c1\u2081\u2083 = 0.0,  # correlation of shocks to long rate and volatility\n\t\u03c1\u2082\u2083 = 0.0,  # correlation of shocks to slope and volatility\n\t\u03c8 = 0.25164,\n\t\u03d5 = 0.0002,\n\tr\u2082_min = 0.01, # soft floor on the short rate\n\tr\u2082_max = 0.4, # unused - maximum short rate\n\tr\u2081_min = 0.015, # soft floor on long rate before random shock\n\tr\u2081_max = 0.18, # soft cap on long rate before random shock\n\t\u03ba = 0.25, # unused - when the short rate would be less than r\u2082_min it was \u03ba * long \n\t\u03b3 = 0.0, # unused - don't change from zero\n\t\u03c3_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# \u2554\u2550\u2561 1a5bb1b0-ea33-11ea-3514-e1c85b65d356\nparams = full_params(\u03c4\u2081,vol)\n\n# \u2554\u2550\u2561 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 \u03c4\u2081,\u03b2\u2081,\u03b8,\u03c4\u2082,\u03b2\u2082,\u03c3\u2082,\u03c4\u2083,\u03b2\u2083,\u03c3\u2083,\u03c1\u2081\u2082,\u03c1\u2081\u2083,\u03c1\u2082\u2083,\u03c8,\u03d5,r\u2082_min,r\u2082_max,r\u2081_min,r\u2081_max,\u03ba,\u03b3,\u03c3_init,months,rate_floor,maturities = params\n\t\n    # some constants\n\tconst1 =  \u221a(1-\u03c1\u2081\u2082^2)\n\tconst2 = (\u03c1\u2082\u2083-\u03c1\u2081\u2082*\u03c1\u2081\u2083)/(const1)\n\tconst3 = \u221a(1-((\u03c1\u2082\u2083 - \u03c1\u2081\u2082*\u03c1\u2081\u2083)^2)/(1\u03c1\u2081\u2082^2)-\u03c1\u2081\u2083^2)\n\tconst4 = \u03b2\u2083 * log(\u03c4\u2083)\n\tconst5 = \u03b2\u2081 * log(\u03c4\u2081)\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_\u03c4 = log(\u03c3_init) # long rate log vol\n\t\u03c3_longvol = \u03c3_init\n\t\u03b1_\u03c4 = start_curve[9]-start_curve[3]\n\tpertubation = 1.0\n\t\n\tr\u2081 = start_curve[9]\n\tr\u2082 = max(r\u2082_min,start_curve[3])\n    \n    b\u2081 = (r\u2082 - r\u2081) / (ns_interp[3] - ns_interp[9])\n    b\u2080 = r\u2082 - b\u2081 * ns_interp[3]\n\n\t\n\tns_fitted .= b\u2080 .+ b\u2081 .* 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] * \u03c1\u2081\u2082 + shock[2] * const1\n\t\tshock_vol   = shock[1] * \u03c1\u2081\u2083 + shock[2] * const2 + shock[3] * const3\n\t\t\t\n\t\t## Generator Process\n\t\tv_\u03c4 =(1-\u03b2\u2083) * v_\u03c4 + const4 + \u03c3\u2083 * shock_vol\n\t\t\u03c3_longvol = exp(v_\u03c4)\n\t\t\n        # moved this after r\u2081 because it uses the prior val\n        \n        \n        \u03b1_\u03c4_prior = \u03b1_\u03c4\n        \u03b1_\u03c4 =(1-\u03b2\u2082) * \u03b1_\u03c4 + \u03b2\u2082 * \u03c4\u2082 + \u03d5 * (log(r\u2081) - log(\u03c4\u2081)) + \u03c3\u2082 * shock_short * r\u2081^\u03b8\n\t\t\n        ## Generator Results\n        \n        r_pre = (1-\u03b2\u2081)*log(r\u2081)+const5+\u03c8*(\u03c4\u2082-\u03b1_\u03c4_prior)\n\t\tr\u2081 = exp(clamp(r_pre,log(r\u2081_min),log(r\u2081_max)) + \u03c3_longvol * shock_long)\n\t\t\n\t\t\n\t\tr\u2082 = max(r\u2081 - \u03b1_\u03c4,r\u2082_min)\n        \n        \n\t\t## Nelson-Siegel Fitted Curve\n\t\tns_fitted .= b\u2080 .+ b\u2081 .* ns_interp\n\t\t\n        b\u2081 = (r\u2082 - r\u2081) / (ns_interp[3] - ns_interp[9])\n        b\u2080 = r\u2082 - b\u2081 * 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# \u2554\u2550\u2561 c5078e00-e8b6-11ea-105b-9731d9852664\nscenarios = ThreadsX.map(i -> scenario(start_curve,params), 1:n_scenarios);\n\n# \u2554\u2550\u2561 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 \u00f7 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 \u00f7 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 \u00f7 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 783904d0-f128-11ea-22f9-43d6dc7b8439\nscenarios[1]\n\n# \u2554\u2550\u2561 c684fec1-0e7c-4c74-be96-c9b1d8c4c9af\nplot(sum(hcat([s[:,9] for s in scenarios]...),dims=2) ./ n_scenarios)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500f04b8ce0-ea39-11ea-05ad-a996c592cc82\n# \u255f\u2500018237f0-ea3c-11ea-387e-abf5110ac1fa\n# \u255f\u2500dabece20-ea37-11ea-2e6a-61eda948928f\n# \u255f\u250063507e40-ea34-11ea-00c3-31bd881aa1bc\n# \u255f\u250013c9baf0-ea37-11ea-16d5-f9f87c35e4f4\n# \u255f\u25002cc3d3b0-ea3c-11ea-2c4f-4bd1db712846\n# \u255f\u25009a6a036e-b4f1-40a8-b3ea-724a1542fb26\n# \u255f\u2500076facc0-e9f5-11ea-2fa5-91cfaa965d08\n# \u255f\u25007f7a2280-ea2d-11ea-2ee8-79bc4c3a72ec\n# \u255f\u250056f67070-ea3c-11ea-31f5-b7d1f7182a31\n# \u255f\u2500844a9e50-f128-11ea-10b1-a1d7792c8fc4\n# \u255f\u2500783904d0-f128-11ea-22f9-43d6dc7b8439\n# \u255f\u250023cba4a0-ea3b-11ea-2b62-8dfc856875b7\n# \u2560\u25507056a580-e8b6-11ea-2ac9-ad6ced139615\n# \u255f\u2500f15e18e0-ea3a-11ea-3868-d9236a4810a1\n# \u2560\u255079cfe060-e9f4-11ea-2fc8-b769419cc4fd\n# \u255f\u25001a5bb1b0-ea33-11ea-3514-e1c85b65d356\n# \u2560\u255049419d10-e861-11ea-36e0-e19ece503681\n# \u2560\u25504ff1ccc0-e8b6-11ea-20be-d7992829086d\n# \u2560\u2550c5078e00-e8b6-11ea-105b-9731d9852664\n# \u2560\u2550c684fec1-0e7c-4c74-be96-c9b1d8c4c9af\n# \u255f\u250069730d30-ea37-11ea-05be-8350df76fd06\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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, \u03b4f, x0...)\n    x = [x0...]\n    y0 = f(x...)\n    @assert length(y0) == 1 \"Scalar functions only\"\n    y, \u2207f = \u03b4f(x...)\n    @assert isapprox(y0, y) \"Return values do not match\"\n    #    @assert typeof(y0) === typeof(y) \"Return type doesn't match\"\n    \u2202x = \u2207f()\n    #    @assert typeof(x0) === typeof(\u2202x) \"Gradient type doesn't match\"\n    checkgrad(f, x, \u2202x)\nend\n\nfunction checkgrad(f, x, \u2202x, h = 1e-8, atol = 1e-8)\n    for k = 1:length(x)\n        \u2202x\u2096 = length(x) == 1 ? \u2202x : \u2202x[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 * \u2202x\u2096, y2-y1, atol=atol) || error(\"gradient for argument #$k doesn't match by $((y2-y1)/(2h*\u2202x\u2096))\")\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 * \u2202x\u2096[l], y2-y1, atol=atol) || error(\"gradient for argument #$k element $l doesn't match by $((y2-y1)/(2h*\u2202x\u2096[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,\u03c3)\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, \u03c3=1\n```\n\"\"\"\nstruct NormalSample{T <: Number} <: AbstractNormalSample{T}\n    Z::T\n    \u03c3::T\nend\n\nfunction NormalSample(Z::T) where {T<:Number}\n    NormalSample(Z, one(T))\nend\n\nNormalSample(Z::Number, \u03c3::Number) = NormalSample(promote(Z, \u03c3)...)\n\nresponse(s::NormalSample) = s.Z\nStatistics.var(s::NormalSample) = s.\u03c3^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}, \u03c3s::AbstractVector{T}) where T\n    NormalSamples{T}((Zs, \u03c3s))\nend\n\nresponse(ss::NormalSamples) = ss.Z\nStatistics.var(ss::NormalSamples) = ss.\u03c3 .^ 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, \u03b1, 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, \u03b1)*f(t0+i*h, y[i+1])\n        end\n        middle = middle/gamma(\u03b1+1)\n        y[j] = u0 + middle*h^\u03b1\n    end\n    t = collect(t0:h:T)\n    return FODESolution(t, y)\nend\n\nfunction acoefficients(n, \u03b1)\n    if n == 0\n        return 1\n    else\n        return ((n-1)^(\u03b1+1)-2*n^(\u03b1+1)+(n+1)^(\u03b1+1))\n    end\nend\n\nbcoefficients(n, \u03b1) = ((n+1)^\u03b1-n^\u03b1)", "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": "# source: https://gist.github.com/denizyuret/bf74f737ba8a7076a7f43c5080555a9a\n\nusing AutoGrad, CuArrays, Knet, Test\nusing AutoGrad: @gcheck\nusing CuArrays: @cufunc\n\nconst GConstant01 = sqrt(2/pi)\nconst GConstant02 = 0.044715 * sqrt(2/pi)\nconst GConstant03 = GConstant01 / 2\n\n# Main definition, broadcasted version works on Arrays\n\ngelu(x::T) where T = (x/2)*(1 + tanh(T(GConstant02)*x^3 + T(GConstant01)*x))\ngeluback(x::T,dy::T) where T = dy*(T(0.5)*tanh(T(GConstant02)*x^3 + T(GConstant01)*x) + (T(0.0535161)*x^3 + T(GConstant03)*x)*(1/cosh(T(GConstant02)*x^3 + T(GConstant01)*x))^2 + T(0.5))\n\n\n# This defines gelu for AutoGrad\n\n@primitive  gelu(x),dy  geluback.(x,dy)\n\n\n# This makes broadcasted gelu work for CuArray, directly compiling a CUDA kernel from Julia code.\n# @cufunc necessary to use a GPU compatible version of tanh etc.\n# https://github.com/JuliaGPU/CuArrays.jl/issues/253\n\n@cufunc gelu(x::T) where T = (x/2)*(1 + tanh(T(GConstant02)*x^3 + T(GConstant01)*x))\n@cufunc geluback(x::T,dy::T) where T = dy*(T(0.5)*tanh(T(GConstant02)*x^3 + T(GConstant01)*x) + (T(0.0535161)*x^3 + T(GConstant03)*x)*(1/cosh(T(GConstant02)*x^3 + T(GConstant01)*x))^2 + T(0.5))\n\n\n# This defines gelu for KnetArray\nimport Base.Broadcast: broadcasted\nimport Knet: KnetArray\n\nfunction KnetArray(x::CuArray{T,N}) where {T,N}\n    p = Base.bitcast(Knet.Cptr, x.ptr)\n    k = Knet.KnetPtr(p, sizeof(x), gpu(), x) \n    KnetArray{T,N}(k, size(x))\nend\n\nbroadcasted(::typeof(gelu),x::KnetArray) = KnetArray(gelu.(CuArray(x)))\nbroadcasted(::typeof(geluback),x::KnetArray,dy::KnetArray) = KnetArray(geluback.(CuArray(x),CuArray(dy)))\n\n\n# This tests all of the above\n# julia -L gelu.jl -e 'testgelu()'\nfunction testgelu()\n    @testset \"gelu\" begin\n        x = rand(10)\n        a = Param(x)\n        c = Param(CuArray(x))\n        k = Param(KnetArray(x))\n        @test @gcheck gelu.(a)\n        @test @gcheck gelu.(c)\n        @test @gcheck gelu.(k)\n    end\nend\n\n\"\"\"\n    gelu(x)\n    \n    Gaussian Error Linear Unit Activation Function\n    https://arxiv.org/abs/1606.08415\n\n    returns: \n        0.5x * (1 + tanh(\u221a(2/\u03c0) * (x + 0.044715x^3)))\n\"\"\"\ngelu", "meta": {"hexsha": "da7f63771c7972b761cf75882e7ce2512eb6d3f5", "size": 2119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gelu.jl", "max_stars_repo_name": "alisafaya/SHA-RNN.jl", "max_stars_repo_head_hexsha": "ebd62afb7be69e13e6e19886d7311b93773888fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-03-24T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:44:06.000Z", "max_issues_repo_path": "src/gelu.jl", "max_issues_repo_name": "alisafaya/SHA-RNN.jl", "max_issues_repo_head_hexsha": "ebd62afb7be69e13e6e19886d7311b93773888fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gelu.jl", "max_forks_repo_name": "alisafaya/SHA-RNN.jl", "max_forks_repo_head_hexsha": "ebd62afb7be69e13e6e19886d7311b93773888fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-24T18:11:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T01:48:41.000Z", "avg_line_length": 31.6268656716, "max_line_length": 193, "alphanum_fraction": 0.6597451628, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7538233227312878}}
{"text": "@testset \"Eigenvalues of interval matrices\" begin\n\n    # symmetrix matrix\n    A = Symmetric([-1 0 -1..1;\n         0 -1 -1..1;\n         -1..1 -1..1 0.1])\n\n    evrohn = eigenbox(A)\n    @test interval_isapprox(evrohn, -2.4143..1.5143; atol=1e-3)\n\n    evhertz = eigenbox(A, Hertz())\n    @test interval_isapprox(evhertz, -1.9674..1.0674; atol=1e-3)\n\n    # real matrix\n    A = [-3.. -2 4..5 4..6 -1..1.5;\n         -4.. -3 -4.. -3 -4.. -3 1..2;\n         -5.. -4 2..3 -5.. -4 -1..0;\n         -1..0.1 0..1 1..2 -4..2.5]\n\n    ev = eigenbox(A)\n    @test interval_isapprox(real(ev), -8.8221..3.4408; atol=1e-3)\n    @test interval_isapprox(imag(ev), -10.7497..10.7497; atol=1e-3)\n\n    evhertz = eigenbox(A, Hertz())\n    @test interval_isapprox(real(evhertz), -7.3691..3.2742; atol=1e-3)\n    @test interval_isapprox(imag(evhertz), -8.794..8.794; atol=1e-3)\n\n    # hermitian matrix\n    A = Hermitian([1..2 (5..9)+(2..5)*im (3..5)+(2..4)im;\n        (5..9)+(-5.. -2)*im 2..3 (7..8)+(6..10)im;\n        (3..5)+(-4.. -2)*im (7..8)+(-10.. -6)*im 3..4])\n\n    ev = eigenbox(A)\n    @test interval_isapprox(ev, -15.4447..24.3359; atol=1e-3)\n\n    # complex matrix\n    A = [(1..2)+(3..4)*im 3..4;1+(2..3)*im 4..5]\n\n    ev = eigenbox(A)\n    @test interval_isapprox(real(ev), -1.28812..7.28812; atol=1e-3)\n    @test interval_isapprox(imag(ev), -2.04649..5.54649; atol=1e-3)\nend\n", "meta": {"hexsha": "fb1b560944e4aba51b2d646edae7fc1d3abfd35e", "size": 1349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_eigenvalues/test_interval_eigenvalues.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": "test/test_eigenvalues/test_interval_eigenvalues.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": "test/test_eigenvalues/test_interval_eigenvalues.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": 31.3720930233, "max_line_length": 70, "alphanum_fraction": 0.538176427, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7538233210994543}}
{"text": "using ValidatedNumerics\nusing FactCheck\n\nfacts(\"Tests with rational intervals\") do\n\n    a = Interval(1//2, 3//4)\n    b = Interval(3//7, 9//12)\n\n    @fact a + b --> Interval(13//14, 3//2)  # exact\n\n    @fact sqrt(a + b) --> Interval(0.9636241116594314, 1.2247448713915892)\n\n    X = Interval(1//3)\n    @fact sqrt(X) --> Interval(0.5773502691896257, 0.5773502691896258)\n\nend\n\nsetprecision(Interval, 64)\n\nfacts(\"Rounding rational intervals\") do\n\n    X = Interval(big(1)//3)\n    Y = Interval(big\"5.77350269189625764452e-01\", big\"5.77350269189625764561e-01\")\n    @fact sqrt(X) --> Y\nend\n\nfacts(\"Tests with float intervals\") do\n\n    c = @floatinterval(0.1, 0.2)\n\n    @fact isa(@floatinterval(0.1), Interval) --> true\n    @fact c --> Interval(0.09999999999999999, 0.2)\n\n    @fact widen(c) --> Interval(0.09999999999999998, 0.20000000000000004)\n\n    @fact @floatinterval(pi) --> Interval(3.141592653589793, 3.1415926535897936)\nend\n\nfacts(\"Testing functions of intervals\") do\n    f(x) = x + 0.1\n\n    c = @floatinterval(0.1, 0.2)\n    @pending f(c) --> Interval(0.19999999999999998, 0.30000000000000004)\n\n    d = @interval(0.1, 0.2)\n    @pending f(d) --> Interval(1.9999999999999998e-01, 3.0000000000000004e-01)\nend\n\nfacts(\"Testing conversions\") do\n    f = @interval(0.1, 0.2)\n    @pending @floatinterval(f) --> Interval(0.09999999999999999, 0.2)\n\n    g = @floatinterval(0.1, 0.2)\n    @pending @interval(g) --> Interval(9.9999999999999992e-02, 2.0000000000000001e-01)\nend\n", "meta": {"hexsha": "d7da36d2de746165d2b2ab0d06531320cc51f6a0", "size": 1460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/interval_tests/non_BigFloat.jl", "max_stars_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_stars_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/interval_tests/non_BigFloat.jl", "max_issues_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_issues_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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/interval_tests/non_BigFloat.jl", "max_forks_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_forks_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "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.0714285714, "max_line_length": 86, "alphanum_fraction": 0.6636986301, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7538233145721205}}
{"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\u2080::Float64, y\u2080::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\u2080), deepcopy(y\u2080)\n\t\tK[1] = f(t,y)\n\n\t\tinit\u2260Void && 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\u2260Void && 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": "@testset \"Misc/NumberField\" begin\n  @testset \"is_subfield\" begin\n    Qx, x = FlintQQ[\"x\"]\n    K, a = NumberField(x^2 + 1, \"a\")\n    L, b = NumberField(x^4 + 1, \"b\")\n\n    c, KtoL = is_subfield(K, L)\n    @test c == true\n    @test parent(KtoL(a)) == L\n\n    c, KtoL = Hecke.is_subfield_normal(K, L)\n    @test c == true\n    @test parent(KtoL(a)) == L\n\n    OK = maximal_order(K)\n    OL = maximal_order(L)\n    c, KtoL = is_subfield(K, L)\n    @test c == true\n    @test parent(KtoL(a)) == L\n  end\n\n  @testset \"is_isomorphic\" begin\n    Qx, x = FlintQQ[\"x\"]\n    f = x^5 + 12x - 92\n    K, a = NumberField(f, \"a\")\n\n    g = x^5 - 172x^4 + 7024x^3 + 8656448x^2 + 55735552x + 45796197888\n    K2, a2 = NumberField(g, \"a2\")\n\n    c, KtoK2 = is_isomorphic_with_map(K, K2)\n    @test c == true\n    @test parent(KtoK2(a)) == K2\n\n    OK = maximal_order(K)\n    OK2 = maximal_order(K2)\n    c, KtoK2 = is_isomorphic_with_map(K, K2)\n    @test c == true\n    @test parent(KtoK2(a)) == K2\n\n    h = f - 1\n    K3, a3 = NumberField(h, \"a3\")\n    @test !is_isomorphic(K, K3)\n  end\nend\n", "meta": {"hexsha": "dfd80b8dd0827f580c155198dbb2a406900570fe", "size": 1048, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Misc/NumberField.jl", "max_stars_repo_name": "StevellM/Hecke.jl", "max_stars_repo_head_hexsha": "64938b616109da05d1e294e87b2ca3e0ad41fb8e", "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": "test/Misc/NumberField.jl", "max_issues_repo_name": "StevellM/Hecke.jl", "max_issues_repo_head_hexsha": "64938b616109da05d1e294e87b2ca3e0ad41fb8e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-09T10:13:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T10:13:38.000Z", "max_forks_repo_path": "test/Misc/NumberField.jl", "max_forks_repo_name": "YvonneNeuy/Hecke.jl", "max_forks_repo_head_hexsha": "df2596ef4ccde73759cdf29ac347fb9738090234", "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.2888888889, "max_line_length": 69, "alphanum_fraction": 0.5610687023, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7538233110594931}}
{"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\u03c0)\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": "using JuMP: @variable, @constraint, @objective, Model, with_optimizer, optimize!, value\nusing CPLEX\n\nfunction find_feasible_point(A::Matrix{T}, b::Vector{T}, r_min::T=zero(T), r_max::T=T(Inf)) where T\n\t# Attempts to solve the feasibility problem\n\t# find       x\n\t# such that  Ax \u2264 b\n\t#            r_min \u2264 \u2016x\u2016 \u2264 r_max\n\n\t# First use CPLEX to find the solution x_min of\n\t# minimize     x'x\n\t# subject to   Ax \u2264 b\n\tm, n = size(A)\n\tmodel = Model(with_optimizer(CPLEX.Optimizer))\n    @variable(model, x[1:n])\n    @objective(model, Min, dot(x, x))\n\t@constraint(model, A*x .<= b)\n\toptimize!(model)\n    x_min = value.(x)\n\t# Check that x_min is feasible and \u2016x_min\u2016 \u2264 r_max\n\t@assert norm(x_min) <= r_max string(\"The problem is infeasible. Min radius:\", norm(x_min))\n\t@assert maximum(A*x_min - b) <= 1e-11 string(\"Min-radius solution returned by Gurobi violates constraints by:\", maximum(A*x_min - b))\n\n\t# Use GeneralQP to find a solution x\n\t# maximize     x'x\n\t# subject to   Ax \u2264 b\n\t# that has radius less than or equal to (r_min + r_max)/2\n\tx = GeneralQP.solve(Matrix(-one(T)*I, n, n), zeros(T, n), A, b, x_min; r_max=(r_min+r_max)/2, printing_interval=5000)\n\t# Check that r_min \u2264 \u2016x\u2016 \u2264 r_max and Ax \u2264 b\n\t@assert norm(x) - r_min >= -1e-9 \"Failed to find a feasible point\"\n\t@assert norm(x) - r_max <= 1e-9 \"Failed to find a feasible point\"\n\t@assert maximum(A*x - b) <= 1e-9 \"Failed to find a feasible point\"\n\n\treturn x\nend", "meta": {"hexsha": "538b721972223232f76815a5c7e457d0ab90faab", "size": 1413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/find_feasible_point.jl", "max_stars_repo_name": "oxfordcontrol/QPnorm.jl", "max_stars_repo_head_hexsha": "746eaed3901b47622c0337cde615e82321707eba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-02T20:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T05:18:47.000Z", "max_issues_repo_path": "src/find_feasible_point.jl", "max_issues_repo_name": "oxfordcontrol/QPnorm.jl", "max_issues_repo_head_hexsha": "746eaed3901b47622c0337cde615e82321707eba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-31T20:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-03T02:58:07.000Z", "max_forks_repo_path": "src/find_feasible_point.jl", "max_forks_repo_name": "oxfordcontrol/QPnorm.jl", "max_forks_repo_head_hexsha": "746eaed3901b47622c0337cde615e82321707eba", "max_forks_repo_licenses": ["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.3714285714, "max_line_length": 134, "alphanum_fraction": 0.6631280962, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7537766044577336}}
{"text": "# randint\nn = 1000\nx = zeros(Int, n)\nfor i=1:n\n    k = randint([0.1,0.1,0.8])\n    x[i] = k\n    @test 1 <= k <= 3\nend\n@test count(k->k==3, x) > n/2\n\nfor i=1:n\n    k = randint([0.2,0.0,0.8])\n    @test 1 <= k <= 3\n    @test k != 2\nend\n\nfor i=1:n\n    k = randint([1.0,0.0,0.])\n    @test k == 1\nend\n\n@test 0 == randint([0.0,0.0,0.])\n\n# DiscreteDistribution\nn = 1000\nx = zeros(Int, n)\nd = DiscreteDistribution([0.1,0.1,0.8])\nfor i=1:n\n    k = rand(d)\n    x[i] = k\n    @test 1 <= k <= 3\nend\n@test count(k->k==3, x) > n/2\n\nd = DiscreteDistribution([0.2,0.,0.8])\nfor i=1:n\n    k = rand(d)\n    @test 1 <= k <= 3\n    @test k != 2\nend\n\nd = DiscreteDistribution([1.0,0.0,0.])\nfor i=1:n\n    k = rand(d)\n    @test k == 1\nend\n", "meta": {"hexsha": "74f4c25c82f3065b13af8255413695c7253b4d92", "size": 710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Random/discrete_distribution.jl", "max_stars_repo_name": "JuliaTagBot/LittleScienceTools", "max_stars_repo_head_hexsha": "bc9badcebdb80b21698f864107fa74c7686428e4", "max_stars_repo_licenses": ["MIT"], "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/Random/discrete_distribution.jl", "max_issues_repo_name": "JuliaTagBot/LittleScienceTools", "max_issues_repo_head_hexsha": "bc9badcebdb80b21698f864107fa74c7686428e4", "max_issues_repo_licenses": ["MIT"], "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/Random/discrete_distribution.jl", "max_forks_repo_name": "JuliaTagBot/LittleScienceTools", "max_forks_repo_head_hexsha": "bc9badcebdb80b21698f864107fa74c7686428e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:56:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:56:10.000Z", "avg_line_length": 15.1063829787, "max_line_length": 39, "alphanum_fraction": 0.4985915493, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7537397764343597}}
{"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        \u03b1 = 2.0(x[i]^2 - x[1])\n        \u03b3 = x[i]-1\n        fx += \u03b1^2 + \u03b3^2\n    end\n    return fx\nend\n\ng! = (g, x) -> begin\n    for i in firstindex(x):lastindex(x)\n        \u03b1 = 2.0(x[i]^2 - x[1])\n        \u03b3 = x[i]-1\n        g[i] = 8.0x[i]\u03b1 + 2.0\u03b3\n        g[1] -= 4.0\u03b1\n    end\n    return g\nend\n\nfg! = (g, x) -> begin\n    fx = 0.0\n    for i in firstindex(x):lastindex(x)\n        \u03b1 = 2.0(x[i]^2 - x[1])\n        \u03b3 = x[i]-1\n        fx += \u03b1^2 + \u03b3^2\n        g[i] = 8.0x[i]\u03b1 + 2.0\u03b3\n        g[1] -= 4.0\u03b1\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([\u03c1=1.0])`\n\nThe squared exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = exp(-\u03c1\u00b2\u2016x-y\u2016\u00b2)\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(\u03ba::SqExponentialKernel, d\u00b2::Real) = exp(-d\u00b2)\n@inline iskroncompatible(::SqExponentialKernel) = true\n\n## Aliases ##\nconst RBFKernel = SqExponentialKernel\nconst GaussianKernel = SqExponentialKernel\n\n\"\"\"\n`ExponentialKernel([\u03c1=1.0])`\nThe exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = exp(-\u03c1\u2016x-y\u2016)\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(\u03ba::ExponentialKernel, d::Real) = exp(-d)\n@inline iskroncompatible(::ExponentialKernel) = true\n\n## Alias ##\nconst LaplacianKernel = ExponentialKernel\n\n\"\"\"\n`GammaExponentialKernel([\u03c1=1.0,[gamma=2.0]])`\nThe \u03b3-exponential kernel is an isotropic Mercer kernel given by the formula:\n```\n    \u03ba(x,y) = exp(-\u03c1^(2\u03b3)\u2016x-y\u2016^(2\u03b3))\n```\n\"\"\"\nstruct GammaExponentialKernel{T,Tr,T\u1d67<:Real} <: Kernel{T,Tr}\n    transform::Tr\n    metric::SqEuclidean\n    \u03b3::T\u1d67\n    function GammaExponentialKernel{T,Tr,T\u1d67}(transform::Tr,\u03b3::T\u1d67) where {T,Tr<:Transform,T\u1d67<:Real}\n        return new{T,Tr,T\u1d67}(transform,SqEuclidean(),\u03b3)\n    end\nend\n\nparams(k::GammaExponentialKernel) = (params(transform),\u03b3)\nopt_params(k::GammaExponentialKernel) = (opt_params(transform),\u03b3)\n\nfunction GammaExponentialKernel(\u03c1::T\u2081=1.0,gamma::T\u2082=2.0) where {T\u2081<:Real,T\u2082<:Real}\n    @check_args(GammaExponentialKernel, gamma, gamma >= zero(T\u2082), \"gamma > 0\")\n    GammaExponentialKernel{T\u2081,ScaleTransform{T\u2081},T\u2082}(ScaleTransform(\u03c1),gamma)\nend\n\nfunction GammaExponentialKernel(\u03c1::AbstractVector{T\u2081},gamma::T\u2082=2.0) where {T\u2081<:Real,T\u2082<:Real}\n    @check_args(GammaExponentialKernel, gamma, gamma >= zero(T\u2082), \"gamma > 0\")\n    GammaExponentialKernel{T\u2081,ARDTransform{T\u2081,length(\u03c1)},T\u2082}(ARDTransform(\u03c1),gamma)\nend\n\nfunction GammaExponentialKernel(t::Tr,gamma::T\u2081=2.0) where {Tr<:Transform,T\u2081<:Real}\n    @check_args(GammaExponentialKernel, gamma, gamma >= zero(T\u2081), \"gamma > 0\")\n    GammaExponentialKernel{eltype(Tr),Tr,T\u2081}(t,gamma)\nend\n\n@inline kappa(\u03ba::GammaExponentialKernel, d\u00b2::Real) = exp(-d\u00b2^\u03ba.\u03b3)\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": "\u03b1 = 0.025\n\n@testset \"transform marginals\" begin\n  x1 = [0.2 0.4; 0.4 0.6; 0.6 0.8]\n  convertmarg!(x1, TDist, [[10],[10]])\n  @test x1 \u2248 [-0.879058  -0.260185; -0.260185 0.260185; 0.260185 0.879058] atol=1.0e-5\n  Random.seed!(43)\n  x = rand(10000, 2)\n  convertmarg!(x, Normal, [[0., 2.],[0., 3.]])\n  @test pvalue(ExactOneSampleKSTest(x[:,1],Normal(0,2))) > \u03b1\n  @test pvalue(ExactOneSampleKSTest(x[:,2],Normal(0,3))) > \u03b1\n  Random.seed!(43)\n  @test_throws AssertionError convertmarg!(randn(1000, 2), Normal)\nend\n\n@testset \"generate corelation matrix\" begin\n  Random.seed!(43)\n  if VERSION <= v\"1.7\"\n    @test random_unit_normal_vector(2) \u2248 [0.2414027539276207, 0.9704250153392381]\n  else\n    @test random_unit_normal_vector(2) \u2248 [0.19041035339908666; -0.9817045876018076]\n  end\n\n  Random.seed!(43)\n  if VERSION <= v\"1.7\"\n    @test cormatgen(2) \u2248 [1.0 0.660768; 0.660768 1.0] atol=1.0e-5\n  else\n    @test cormatgen(2) \u2248 [1.0 0.278807; 0.278806 1.0] atol=1.0e-5\n  end\n\n  @test cormatgen_constant(3, 0.3) == [1 0.3 0.3; 0.3 1 0.3; 0.3 0.3 1]\n  @test cormatgen_toeplitz(3, 0.3) == [1 0.3 0.09; 0.3 1 0.3; 0.09 0.3 1]\n  @test cormatgen_two_constant(4, 0.5, 0.2) == [1. .5 .2 .2; .5 1. .2 .2; .2 .2 1. .2; .2 .2 .2 1.]\n\n  @test cormatgen_constant_noised(10, 0.2, \u03f5=0.) == cormatgen_constant(10, 0.2)\n  @test all(eigvals(cormatgen_constant_noised(10, 0.2)) .> 0)\n  @test diag(cormatgen_constant_noised(10, 0.2)) \u2248 ones(10)\n\n  @test cormatgen_toeplitz_noised(10, 0.2, \u03f5=0.) == cormatgen_toeplitz(10, 0.2)\n  @test all(eigvals(cormatgen_toeplitz_noised(10, 0.2)) .> 0)\n  @test diag(cormatgen_toeplitz_noised(10, 0.2)) \u2248 ones(10)\n\n  @test cormatgen_two_constant_noised(10, 0.8, 0.2, \u03f5=0.) == cormatgen_two_constant(10, 0.8, 0.2)\n  @test all(eigvals(cormatgen_two_constant_noised(10, 0.8, 0.2)) .> 0)\n  @test diag(cormatgen_two_constant_noised(10, 0.8, 0.2)) \u2248 ones(10)\n\n  Random.seed!(43)\n  if VERSION <= v\"1.7\"\n    @test cormatgen_rand(2) \u2248 [1.0 0.879086; 0.879086 1.0] atol=1.0e-5\n  else\n    @test cormatgen_rand(2) \u2248 [1.0 0.723043; 0.723043 1.0] atol=1.0e-5\n  end\n  @test all(eigvals(cormatgen_rand(10)) .> 0)\n  @test diag(cormatgen_rand(10)) \u2248 ones(10)\n\nend\n", "meta": {"hexsha": "f1d3cc0ad83f3ea9b2fb46199dd202bf9dfe50a9", "size": 2147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/marg_cor_tests.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": "test/marg_cor_tests.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": "test/marg_cor_tests.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": 37.6666666667, "max_line_length": 99, "alphanum_fraction": 0.6511411272, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7537397580103742}}
{"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": "# ## Line style\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\nPlots.supported_styles()\n\n#-\n\n## ref https://jp.mathworks.com/matlabcentral/fileexchange/35230-matlab-plot-gallery-standard-line-styles?focused=6792901&tab=example\n\nusing SpecialFunctions\n\nstyle = Plots.supported_styles()[2:end]\nstyle = reshape(style, 1, length(style))\nx = 0:0.2:10;\ny0 = besselj.(0,x);\ny1 = besselj.(1,x);\ny2 = besselj.(2,x);\ny3 = besselj.(3,x);\ny4 = besselj.(4,x);\n\nplot(x, [y0 y1 y2 y3 y4], line=(3, style))\n", "meta": {"hexsha": "337e96830b8b8e0761dbb18ce6550a762d8cf9fe", "size": 491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/line_style.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/line_style.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/line_style.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": 21.347826087, "max_line_length": 133, "alphanum_fraction": 0.6904276986, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7536388069783884}}
{"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        \u03b2 = Float64(hp.\u03b2)\n        @constraint m dot(a, c) == \u03b2\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        \u03b2 = Float64(hs.\u03b2)\n        @constraint m dot(a, c) + r[i] * norm(a, 2) <= \u03b2\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\u2212(((x\u2212a1*b1)\u2212a2*b1)\u2212a1*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, \u03c3)\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 * \u03c3^2)*(T))/(\u03c3*sqrt(T))\r\n    d2 = d1 - \u03c3*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, \u03c3, 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 * \u03c3^2)*(T))/(\u03c3*sqrt(T))\r\n    d2 = d1 - \u03c3*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\u1d62,y\u1d62 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 \u2208\u211c\u207f\u02e3\u207f 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\u2c7c with the numerical value of y[j]\n            str = replace(str,\"x\"*string(j)=>\"$x\"*\"[\"*string(j)*\"]\") #replaces into str, the string x\u2c7c 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\u2081x\u207f\u207b\u00b9+c\u2082x\u207f\u207b\u00b2+...+c\u2099\u208b\u2081x+c\u2099\n\nfunction vandpoly(x,y) #used to return a polynomial of degree n-1 out of n datapoints in \u211c\u00b2\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\u2081x\u00b9+c\u2082\n        c1 = @genvandpoly(1, 2,:($x),:($y)) #c1 is the coefficient of x\u00b9\n        c2 = @genvandpoly(2, 2,:($x),:($y)) #c2 is the coefficient of x\u2070\n        return Polynomial([c2,c1]) #Return the polynomial c\u2081x\u00b9+c\u2082\n\n    elseif xLength == 3 #if we have only 3 points we fit y=c\u2081x\u00b2+c\u2082x\u00b9+c\u2083\n        c1 = @genvandpoly(1, 3,:($x),:($y)) #c1 is the coefficient of x\u00b2\n        c2 = @genvandpoly(2, 3,:($x),:($y)) #c2 is the coefficient of x\u00b9\n        c3 = @genvandpoly(3, 3,:($x),:($y)) #c3 is the coefficient of x\u2070\n        return Polynomial([c3,c2,c1]) #Return the polynomial c\u2081x\u00b2+c\u2082x\u00b9+c\u2083\n\n    elseif xLength == 4 #if we have only 4 points we fit y=c\u2081x\u00b3+c\u2082x\u00b2+c\u2083x\u00b9+c\u2084\n        c1 = @genvandpoly(1, 4,:($x),:($y)) #c1 is the coefficient of x\u00b3\n        c2 = @genvandpoly(2, 4,:($x),:($y)) #c2 is the coefficient of x\u00b2\n        c3 = @genvandpoly(3, 4,:($x),:($y)) #c3 is the coefficient of x\u00b9\n        c4 = @genvandpoly(4, 4,:($x),:($y)) #c4 is the coefficient of x\u2070\n        return Polynomial([c4,c3,c2,c1]) #Return the polynomial c\u2081x\u00b3+c\u2082x\u00b2+c\u2083x\u00b9+c\u2084\n\n    elseif xLength == 5 #if we have only 5 points we fit y=c\u2081x\u2074+c\u2082x\u00b3+c\u2083x\u00b2+c\u2084x\u00b9+c\u2085\n        c1 = @genvandpoly(1, 5,:($x),:($y)) #c1 is the coefficient of x\u2074\n        c2 = @genvandpoly(2, 5,:($x),:($y)) #c2 is the coefficient of x\u00b3\n        c3 = @genvandpoly(3, 5,:($x),:($y)) #c3 is the coefficient of x\u00b2\n        c4 = @genvandpoly(4, 5,:($x),:($y)) #c4 is the coefficient of x\u00b9\n        c5 = @genvandpoly(5, 5,:($x),:($y)) #c5 is the coefficient of x\u2070\n        return Polynomial([c5,c4,c3,c2,c1]) #Return the polynomial c\u2081x\u2074+c\u2082x\u00b3+c\u2083x\u00b2+c\u2084x\u00b9+c\u2085\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       \u03b1 = 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) + \u03b1*(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 + \u03b1*(Dxx(v(x,y,t)) + Dyy(v(x,y,t)))]\n\n       domains = [x \u2208 Interval(x_min, x_max),\n                  y \u2208 Interval(y_min, y_max),\n                  t \u2208 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": "module MatrixDepotTemplate\n\nusing LinearAlgebra\nusing MatrixDepot\nusing MatrixDepot: include_generator, FunctionName, Group, publish_user_generators\n\n\"\"\"\nrandom Orthogonal matrix\n========================\n*Input options:*\n+ n: the dimension of the matrix\n\"\"\"\nrandorth(n) = Matrix(qr(randn(n,n)).Q)\n\n\"\"\"\nrandom symmetric matrix\n=======================\n*Input options:* \n+ n: the dimension of the matrix\n\"\"\"\nfunction randsym(n)\n    A = zeros(n, n)\n    for j = 1:n\n    for i = j:n\n        A[i,j] = randn()\n        if i != j; A[j,i] = A[i,j] end\n    end\n    end\n    return A\nend\n\nfunction __init__()\n    include_generator(FunctionName, \"randsym\", randsym)\n    include_generator(FunctionName, \"randorth\", randorth)\n    include_generator(Group, :symmetric, randsym)\n    include_generator(Group, :random, randsym)\n    publish_user_generators()\nend\n\nend\n", "meta": {"hexsha": "e97fefa01b6486b4bd0151c10f1802a1a5538395", "size": 845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MatrixDepotTemplate.jl", "max_stars_repo_name": "KlausC/MatrixDepotTemplates.jl", "max_stars_repo_head_hexsha": "9c1d1fa63274abf2b01c0755d1d9b46c4447550e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MatrixDepotTemplate.jl", "max_issues_repo_name": "KlausC/MatrixDepotTemplates.jl", "max_issues_repo_head_hexsha": "9c1d1fa63274abf2b01c0755d1d9b46c4447550e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MatrixDepotTemplate.jl", "max_forks_repo_name": "KlausC/MatrixDepotTemplates.jl", "max_forks_repo_head_hexsha": "9c1d1fa63274abf2b01c0755d1d9b46c4447550e", "max_forks_repo_licenses": ["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.6097560976, "max_line_length": 82, "alphanum_fraction": 0.6520710059, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7535452707173946}}
{"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": "@testset \"autoencoder\" begin\n\n    # autoencoder cost: sum of squared error\n    # function 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\n    # end\n    \n    function autoencoder_cost(We1, We2, Wd, b1, b2, x)\n        firstLayer = We1 * x .+ b1\n        encodedInput = We2 * firstLayer .+ b2\n        reconstructedInput = Wd * encodedInput\n        cost = sum((reconstructedInput .- x) .^ 2.0)\n        return cost\n    end\n    \n    \n    # @rdcmp autoencoder_cost We1=rand(4,5) We2=rand(3,4) Wd=rand(5,3) b1=rand(4) b2=rand(3) x=rand(5)\n    test_compare(autoencoder_cost; We1=rand(4,5), We2=rand(3,4), Wd=rand(5,3),\n                 b1=rand(4), b2=rand(3), x=rand(5))\n    \n    \n    \n    # slightly different version that uncovered a bug in previous version\n    function autoencoder_cost2(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\n    end\n    \n    # @rdcmp autoencoder_cost We1=rand(4,5) We2=rand(3,4) Wd=rand(5,3) b1=rand(4) b2=rand(3) x=rand(5)\n    test_compare(autoencoder_cost2; We1=rand(4,5), We2=rand(3,4), Wd=rand(5,3),\n                 b1=rand(4), b2=rand(3), x=rand(5))\n    \n    \n    # and the most simple autoencoder\n    function autoencoder_cost3(We, Wd, x)\n        y = We * x\n        xd = Wd * y\n        cost = sum(xd .- x)\n        return cost\n    end\n    test_compare(autoencoder_cost3; We=rand(3,4), Wd=rand(4,3), x=rand(4,2))\n    \nend\n", "meta": {"hexsha": "2fbfce927906a5ffad03cb549011112a3d5d63a0", "size": 1795, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/autoencoder.jl", "max_stars_repo_name": "UnofficialJuliaMirror/XGrad.jl-c48004fe-d13f-5df9-98d5-0c1ab8e45fa0", "max_stars_repo_head_hexsha": "2c10e04f0cf7a1a737f00552c78d160a784c29aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-12-14T17:22:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T17:50:01.000Z", "max_issues_repo_path": "test/autoencoder.jl", "max_issues_repo_name": "UnofficialJuliaMirror/XGrad.jl-c48004fe-d13f-5df9-98d5-0c1ab8e45fa0", "max_issues_repo_head_hexsha": "2c10e04f0cf7a1a737f00552c78d160a784c29aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2017-09-30T18:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-01T16:43:33.000Z", "max_forks_repo_path": "test/autoencoder.jl", "max_forks_repo_name": "UnofficialJuliaMirror/XGrad.jl-c48004fe-d13f-5df9-98d5-0c1ab8e45fa0", "max_forks_repo_head_hexsha": "2c10e04f0cf7a1a737f00552c78d160a784c29aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:42:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-07T07:21:03.000Z", "avg_line_length": 35.1960784314, "max_line_length": 102, "alphanum_fraction": 0.5838440111, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7535452634485011}}
{"text": "import Pkg\nPkg.activate(\"..\")\n\nusing CrimsonSkyline\nusing Distributions: Normal, truncated, Poisson, InverseWishart, MvNormal, Dirichlet, Categorical\nusing Logging\nusing StatsBase: mean, std\nusing Random: seed!\nusing PrettyPrint: pprintln\n\nseed!(2021)\n\nfunction eye(d :: Int)\n    mat = zeros(Float64, d, d)\n    for i in 1:d\n        mat[i, i] = 1.0\n    end\n    mat\nend\n\nfunction clustering(t :: Trace, data :: Array{Float64, 2}, cluster_guess :: Int)\n    # data has shape (D, N), where D is dimensionalty and N is num observations\n    D = size(data, 1)\n    N = size(data, 2)\n    # first, choosing the number of clusters. Prior penalizes high number of clusters\n    cluster_guess = max(cluster_guess, 1)\n    n_clusters = sample(t, :n_clusters, truncated(Poisson(cluster_guess), 1, Inf))\n    # second, given the number of clusters, define loc and cov for each\n    covs = Array{Array{Float64, 2}, 1}()\n    locs = Array{Array{Float64, 1}, 1}()\n    id_mat = eye(D)\n    for c in 1:n_clusters\n        cov = sample(t, (:cov, c), InverseWishart(D + 1, id_mat))\n        push!(covs, id_mat)\n        loc = sample(t, (:loc, c), MvNormal(zeros(D), cov))\n        push!(locs, loc)\n    end\n    # third, for each datapoint, assign to a cluster\n    # note that each datapoint has its own local rv -- we could introduce an amortized model\n    # that learns a mapping from datapoint features to cluster\n    for n in 1:N\n        cluster_prob = sample(t, (:cluster_prob, n), Dirichlet(n_clusters, 1.0))\n        this_cluster = sample(t, (:this_cluster, n), Categorical(cluster_prob))\n        observe(t, (:data, n), MvNormal(locs[this_cluster], covs[this_cluster]), data[:, n])\n    end\nend\n\n\nfunction main()\n    @info \"Open-universe clustering inference\"\n    D = 4\n    n1 = 5\n    n2 = 12\n    data1 = rand(D, n1)\n    data2 = rand(D, n2) .+ 6\n    data = hcat(data1, data2)\n    @info \"True number of clusters is 2\"\n    # pretend we don't know dgp, bias it to be higher than ground truth\n    n_clusters_guess = 5\n    @time results = mh(clustering; params = (data, n_clusters_guess), burn=2000, thin=100, num_iterations=100000)\n    mean_n_clusters = mean(results, :n_clusters)\n    std_n_clusters = std(results, :n_clusters)\n    @info \"posterior n_clusters \u2248 $mean_n_clusters \u00b1 $std_n_clusters\"\nend\n\nmain()", "meta": {"hexsha": "9408e7a3622a594b5dc623596d1ef3afaa653faa", "size": 2274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/clustering.jl", "max_stars_repo_name": "daviddewhurst/CrimsonSkyline.jl", "max_stars_repo_head_hexsha": "89661f5ed3c0fa4a0753f9ec8f3a24542b574cb8", "max_stars_repo_licenses": ["MIT"], "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/clustering.jl", "max_issues_repo_name": "daviddewhurst/CrimsonSkyline.jl", "max_issues_repo_head_hexsha": "89661f5ed3c0fa4a0753f9ec8f3a24542b574cb8", "max_issues_repo_licenses": ["MIT"], "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/clustering.jl", "max_forks_repo_name": "daviddewhurst/CrimsonSkyline.jl", "max_forks_repo_head_hexsha": "89661f5ed3c0fa4a0753f9ec8f3a24542b574cb8", "max_forks_repo_licenses": ["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.4545454545, "max_line_length": 113, "alphanum_fraction": 0.662708883, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.753545259804906}}
{"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    \u03a9 = f.U * f.Vt\n    # Now translate and rotated the reordered data towards `pts1`\n    return Translation(com1).(\u03a9 * 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\u1d9c = mid.(A)\n    B = inv(A\u1d9c)\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\u00b9 = 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] \u2229 Z[1]), x[i] \u2229 Z[2])\n        end\n        if all(x .== x\u00b9)\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\u00b9 = copy(x)\n        x = x .\u2229 (inv_diagA * (b - extdiagA * x))\n        if all(x .== x\u00b9)\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 \u2208 A[i, i] # diagonal matrix is not invertible\n            p .= entireinterval(b[1])\n            return p .\u2229 x  # return x?\n        end\n\n        for j in (i+1):n\n            \u03b1 = A[j, i] / A[i, i]\n            b[j] -= \u03b1 * b[i]\n\n            for k in (i+1):n\n                A[j, k] -= \u03b1 * 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 .\u2229 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, \u03be) 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\u2081 = one(T)\n    c\u2084 = x[0] - \u03be\n\n    c .= zero(T)\n    c[0,0] = 1\n\n    for i = 1:nd\n        mn = min(i,m)\n        c\u2082 = one(T)\n        c\u2085 = c\u2084\n        c\u2084 = x[i] - \u03be\n        for j = 0:i-1\n            c\u2083 = x[i] - x[j]\n            c\u2082 *= c\u2083\n            for k = mn:-1:1\n                c[i,k] = c\u2081*(k*c[i-1,k-1] - c\u2085*c[i-1,k])/c\u2082\n            end\n            c[i,0] = -c\u2081*c\u2085*c[i-1,0]/c\u2082\n            for k = mn:-1:1\n                c[j,k] = (c\u2084*c[j,k] - k*c[j,k-1])/c\u2083\n            end\n            c[j,0] = c\u2084*c[j,0]/c\u2083\n        end\n        c\u2081 = c\u2082\n    end\n    c\nend\n\nfunction fornberg_weights(x, \u03be::T, m::Integer) where T\n    c = zeros(promote_type(eltype(x),T), length(x), m+1)\n    fornberg_weights!(c, x, \u03be)\n    c\nend\n\nfunction fornberg_all_weights!(c::AbstractArray{T,3}, x, \u03be) 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\u2081 = one(T)\n    c\u2084 = x[0] - \u03be\n\n    for i = 1:nd\n        mn = min(i,m)\n        c\u2082 = one(T)\n        c\u2085 = c\u2084\n        c\u2084 = x[i] - \u03be\n        for j = 0:i-1\n            c\u2083 = x[i] - x[j]\n            c\u2082 *= c\u2083\n            c[j,i,0] = c\u2084*c[j,i-1,0]/c\u2083\n            for k = 1:mn\n                c[j,i,k] = (c\u2084*c[j,i-1,k] - k*c[j,i-1,k-1])/c\u2083\n            end\n        end\n        c[i,i,0] = -c\u2081*c\u2085*c[i-1,i-1,0]/c\u2082\n\n        for k = 1:mn\n            c[i,i,k] = c\u2081*(k*c[i-1,i-1,k-1] - c\u2085*c[i-1,i-1,k])/c\u2082\n        end\n        c\u2081 = c\u2082\n    end\n    c\nend\n\nfunction fornberg_all_weights(x, \u03be::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, \u03be)\n    c\nend\n\nfunction fornberg_test_driver(x, \u03be)\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, \u03be, 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, \u03be, 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": "\"\"\"\n    sum_of_postive_gradients(array::Array{Int64,1}, m = nothing, n = nothing)\n\nEstimates the sum of all positive gradients in array-sequence, calling the function itself\nrecursively. Every time if the `array[j] > array[i]` will be check, it will test the\nmonotony of the previous of the following elements.\n\n\n# Arguments\n- `array::Array{Int64,1}`: Unsorted array\n- `m::Int64`: index for the nested `for-loops`; optional\n- `n::Int64`: index for the nested `for-loops`; optional\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr =  arr = [100, 180, 260, 310, 40, 535, 695]\njulia> ClassicAlgorithmsCollections.sum_of_postive_gradients(arr)\n865\n```\n\"\"\"\nfunction sum_of_postive_gradients(array::Array{Int64,1}, m = nothing, n = nothing)\n\n    if isnothing(m) && isnothing(n)\n        m = 1\n        n = length(array)\n    end\n    gradient = 0\n\n    for i in m:n\n        for j in (i+1):n\n            if array[j] > array[i]\n                tmp_gradient =\n                    array[j] - array[i] +\n                    sum_of_postive_gradients(array, m, i - 1) +\n                    sum_of_postive_gradients(array, j + 1, n)\n\n                if tmp_gradient > gradient\n                    gradient = tmp_gradient\n                end\n            end\n        end\n    end\n\n    return gradient\nend\n", "meta": {"hexsha": "2c713c8281ead0f573654f3800fa4d9bd256f4b6", "size": 1315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StringAndArray/SumOfPositiveGradients.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/SumOfPositiveGradients.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/SumOfPositiveGradients.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.3958333333, "max_line_length": 90, "alphanum_fraction": 0.6114068441, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7535398788609176}}
{"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=\u03bd)\n    MaternVariogram(ball; sill=s, nugget=n, order=\u03bd)\n\nA Mat\u00e9rn variogram with range `r`, sill `s` and nugget `n`.\nThe parameter `\u03bd` 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 (\u03b3::MaternVariogram)(h::T) where {T}\n  r = radius(\u03b3.ball)\n  s = \u03b3.sill\n  n = \u03b3.nugget\n  \u03bd = \u03b3.order\n\n  # shift lag by machine precision to\n  # avoid explosion at the origin\n  h\u2032 = sqrt(2\u03bd)*(h + eps(T)) / r\n  \u0392  = besselk(\u03bd, h\u2032)\n  \u0393  = gamma(\u03bd)\n\n  (s - n) * (1 - 2^(1 - \u03bd) / \u0393 * h\u2032^\u03bd * \u0392) + (h\u2032 > 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(\u03c8)\n  \u03c8H\u03c8 = inner(\u03c8', H, \u03c8)\n\n  # Alternative:\n  # H\u03c8 = apply(H, \u03c8)\n  # \u03c8H\u03c8 = inner(\u03c8, H\u03c8)\n\n  \u03c8\u03c8 = inner(\u03c8, \u03c8)\n  return \u03c8H\u03c8 / \u03c8\u03c8\nend\n\n# Extremely simple gradient descent.\n# Better to use a library like `OptimKit.jl` in general.\nfunction minimize(f, \u2202f, x; nsteps, \u03b3)\n  for n in 1:nsteps\n    println(\"n = \", n, \", f_x = \", f(x))\n\n    # Gradient descent step with step size `\u03b3`\n    x = x - \u03b3 * \u2202f(x)\n  end\n  return x\nend\n\n# Use the cat state as a starting state\n\u03c8\u2080 = (Zp1 * Zp2 + Zm1 * Zm2) / \u221a2\n\n# Minimize the energy!\n\u2202E(\u03c8) = gradient(E, \u03c8)[1]\n\u03c8 = minimize(E, \u2202E, \u03c8\u2080; nsteps=10, \u03b3=0.1)\n\n@show E(\u03c8\u2080), norm(\u2202E(\u03c8\u2080))\n@show E(\u03c8), norm(\u2202E(\u03c8))\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(\u03bb=1, dim=1)\n\nReturns the function\n```math\nf(X) = \u03bb\u22c5\u2211_i\\\\|x_i\\\\|\n```\nfor a nonnegative `\u03bb`, 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 \u03bb 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 \u21a6 \u03bbsum(||x_i||)\"\nfun_params(f::NormL21) = \"\u03bb = $(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 Test\nusing MultivariateBases\n\n@testset \"Orthogonal\" begin\n    orthogonal_test(ChebyshevBasis, x -> [\n        1,\n        x,\n        2x^2 - 1,\n        4x^3 - 3x,\n        8x^4 - 8x^2 + 1\n    ], true)\n    orthogonal_test(ChebyshevBasisSecondKind, x -> [\n        1,\n        2x,\n        4x^2 - 1,\n        8x^3 - 4x,\n        16x^4 - 12x^2 + 1\n    ], true)\nend\n\n@testset \"API degree = $degree\" for degree in 0:3\n    api_test(ChebyshevBasis, degree)\n    api_test(ChebyshevBasisSecondKind, degree)\nend\n", "meta": {"hexsha": "d56ad7ee9a26e9e452080e7a6b829e6eeeb2c5b4", "size": 498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/chebyshev.jl", "max_stars_repo_name": "JuliaAlgebra/PolynomialBases", "max_stars_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-24T07:15:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:13:46.000Z", "max_issues_repo_path": "test/chebyshev.jl", "max_issues_repo_name": "JuliaAlgebra/PolynomialBases", "max_issues_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-01-30T12:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T22:17:19.000Z", "max_forks_repo_path": "test/chebyshev.jl", "max_forks_repo_name": "JuliaAlgebra/PolynomialBases", "max_forks_repo_head_hexsha": "d81c13f09e394c36651517c8721b56a6e5559520", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-01-15T15:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T15:10:30.000Z", "avg_line_length": 19.92, "max_line_length": 52, "alphanum_fraction": 0.5562248996, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7534849453016135}}
{"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        \u03ba::Kernel,\n        X::AbstractMatrix;\n        obsdim::Int = defaultobs\n        )\n    K = kernelmatrix(\u03ba,X,obsdim=obsdim)\n    Kmax =maximum(K)\n    \u03b1 = eps(eltype(K))\n    while !isposdef(K+\u03b1*I) && \u03b1 < 0.01*Kmax\n        \u03b1 *= 2.0\n    end\n    if \u03b1 >= 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+\u03b1*I)\nend\n\nkernelpdmat(\u03ba::Kernel,X::AbstractVector{<:Real};obsdim=defaultobs) = kernelpdmat(\u03ba,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\nfunction can_use_greedy(coins::Array{Int, 1})::Bool\n\tdivisible::Bool = true\n\tfor i in 1 : length(coins) - 1\n\t\tdivisible &= (coins[i] % coins[i + 1]) == 0\n\tend\n\n\treturn divisible\nend\n\n\nfunction min_coins_greedy(coins::Array{Int, 1}, value::Int)::Int\n\tamt_coins::Int = 0\n\n\tfor i in coins\n\t\tamt_coins += fld(value, i)\n\t\tvalue %= i\n\tend\n\n\treturn amt_coins\nend\n\n\nfunction min_coins_dynamic(coins::Array{Int, 1}, value::Int)::Int\n\tamt_coins = fld(value, coins[length(coins)])\n\n\tfor i in length(coins) : -1 : 1\n\t\ttemp = min_coins_greedy(coins[i : length(coins)], value)\n\t\tif temp < amt_coins\n\t\t\tamt_coins = temp\n\t\tend\n\tend\n\n\treturn amt_coins\nend\n", "meta": {"hexsha": "8045b19bfcc5f214e51a0e545e126b5d73d8e302", "size": 641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "18Host/TDT4120/AtomProjectFolder/Project1/Oving7/Ov7.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/Oving7/Ov7.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/Oving7/Ov7.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.3243243243, "max_line_length": 65, "alphanum_fraction": 0.6770670827, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7534849436275078}}
{"text": "using Catalyst, Test\nusing LinearAlgebra\n\ninclude(\"test_networks.jl\")\n\nrn = @reaction_network begin\n    (1, 2), A + B <--> C \n    (3, 2), D <--> E \n    (0.1, 0.2), E <--> F\n    6, F --> G\n    7, H --> G\n    5, 0 --> K\n    3, A + B --> Z + C\nend\n\nS = netstoichmat(rn)\nC = conservationlaws(S)\n\n@test size(C,1) == 3\n\nb = [ 0, 0, 0, 1, 1, 1, 1, 1, 0, 0 ]\n@test any(b == C[i,:] for i in 1:size(C,1))\n\n# For the A + B <--> C subsystem one of these must occur\n# as a conservation law\nD = [ 1 -1 0 0 0 0 0 0 0 0;\n      -1 1 0 0 0 0 0 0 0 0\n      0  1 1 0 0 0 0 0 0 0 ]\n@test any(D[j,:] == C[i,:] for i in 1:size(C,1), j in 1:size(D,1))\n\nSs_standard = map(netstoichmat, reaction_networks_standard)\nCs_standard = map(conservationlaws, Ss_standard)\n@test all(size(C, 1) == 0 for C in Cs_standard)\n\nSs_hill = map(netstoichmat, reaction_networks_hill)\nCs_hill = map(conservationlaws, Ss_hill)\n@test all(size(C, 1) == 0 for C in Cs_hill)\n\nfunction consequiv(A, B)\n    rank([A; B]) == rank(A) == rank(B)\nend\n\nSs_constraint = map(netstoichmat, reaction_networks_constraint)\nCs_constraint = map(conservationlaws, Ss_constraint)\n\n@test all(consequiv.(Matrix{Int}.(Cs_constraint), reaction_network_constraints))\n", "meta": {"hexsha": "f136f76e77fa3ca56fef3b291468d3ca9fd04622", "size": 1193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/conslaws.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": "test/conslaws.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": "test/conslaws.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": 25.3829787234, "max_line_length": 80, "alphanum_fraction": 0.6227996647, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7534849425084491}}
{"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 \u2264 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) \u2264 abs(b)\n    @assert a \u2264 0 \u2264 b || 0 < a < b\n\n    \u0394 = (b - a) * middle(a, b)\n    #\u0394 = one(\u0394m1) + \u0394m1\n\n    if a \u2264 0 \u2264 b\n        m = \u221a(2/\u03c0) * expm1(-\u0394) * exp(-a^2 / 2) / erf(b/\u221a2, a/\u221a2)\n    elseif 0 < a < b\n        z = exp(-\u0394) * erfcx(b/\u221a2) - erfcx(a/\u221a2)\n        iszero(z) && return middle(a, b)\n        m = \u221a(2/\u03c0) * expm1(-\u0394) / z\n    end\n    return clamp(m, a, b)\nend\n\n\"\"\"\n    tnmean(a, b, \u03bc, \u03c3)\n\nMean of the truncated normal distribution, where \u03bc, \u03c3 are the mean and standard\ndeviation of the untruncated distribution.\n\"\"\"\nfunction tnmean(a, b, \u03bc, \u03c3)\n    \u03b1 = (a - \u03bc) / \u03c3\n    \u03b2 = (b - \u03bc) / \u03c3\n    return \u03bc + tnmean(\u03b1, \u03b2) * \u03c3\nend\n\n\"\"\"\n    tnmean(a, b)\n\nMean of the truncated standard normal distribution.\n\n    tnmean(a, b, \u03bc, \u03c3)\n\nMean of the truncated normal distribution, where \u03bc, \u03c3 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 \u2264 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) \u2264 abs(b)\n    @assert a \u2264 0 \u2264 b || 0 < a < b\n\n    \u0394 = (b - a) * middle(a, b)\n    m = (1/\u221a2) * expm1(-\u0394) / (dawson(a/\u221a2) * exp(-\u0394) - dawson(b/\u221a2))\n    return clamp(m, a, b)\nend\n\n\"\"\"\n    tnmom1i(a, b, \u03bc, \u03c3)\n\nMean of the normal distribution with variance -\u03c3^2 and mean \u03bc,\ntruncated to [a,b].\n\"\"\"\ntnmom1i(a, b, \u03bc, \u03c3) = \u03bc + \u03c3 * tnmom1i((a - \u03bc)/\u03c3, (b - \u03bc)/\u03c3)\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": "@testset \"filter_matrix.jl\" begin\n    a = 0.0\n    b = 2\u03c0\n    N = 100\n    M = N\n    \u0394x = (b - a) / M\n\n    # Domains\n    closed_interval = ClosedIntervalDomain(a, b)\n    periodic_interval = PeriodicIntervalDomain(a, b)\n    unknown_domain = UnknownDomain()\n\n\n    ## Identity filter\n    f = IdentityFilter()\n\n    # ClosedIntervalDomain\n    W = filter_matrix(f, closed_interval, M, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (M + 1, N + 1)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    W = filter_matrix(f, periodic_interval, M, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (M, N)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception filter_matrix(f, unknown_domain, M, N)\n\n\n    ## Top hat filter\n    h\u2080 = 0.05\n    h = x -> h\u2080 * (1 - 1 / 2 * cos(x))\n    f = TopHatFilter(h)\n\n    # ClosedIntervalDomain\n    W = filter_matrix(f, closed_interval, M, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (M + 1, N + 1)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    W = filter_matrix(f, periodic_interval, M, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (M, N)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception filter_matrix(f, unknown_domain, M, N)\n\n\n    ## Convolutional filter\n    g = GaussianFilter(h\u2080)\n\n    # ClosedIntervalDomain\n    W = filter_matrix(g, closed_interval, M, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (M + 1, N + 1)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    W = filter_matrix(g, periodic_interval, M, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (M, N)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception filter_matrix(g, unknown_domain, M, N)\n\n\n    ## Constant mesh-wide top hat filter\n    h = x -> \u0394x / 2\n    f = TopHatFilter(h)\n\n    # ClosedIntervalDomain\n    W = filter_matrix_meshwidth(f, closed_interval, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (N + 1, N + 1)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # PeriodicIntervalDomain\n    W = filter_matrix_meshwidth(f, periodic_interval, N)\n    @test W isa SparseMatrixCSC\n    @test size(W) == (N, N)\n    @test all(sum(W, dims = 2) .\u2248 1)\n\n    # Unknown domain\n    @test_throws Exception filter_matrix_meshwidth(f, unknown_domain, N)\nend\n", "meta": {"hexsha": "b5ec8b64cea13c49ef9f6b3142c47daad43a9ef1", "size": 2358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/matrices/filter_matrix.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": "test/matrices/filter_matrix.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": "test/matrices/filter_matrix.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.6304347826, "max_line_length": 72, "alphanum_fraction": 0.6106870229, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8080672043084051, "lm_q1q2_score": 0.7534849323717151}}
{"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": "module BiharmonicTests\n\nusing Test\nusing Gridap\n\n# Analytical manufactured solution\nu(x) = x[1]*(x[1]-1)*x[2]*(x[2]-1)\nf(x) = \u0394(\u0394(u))(x)\ng(x) = \u0394(u)(x)\n@test f(VectorValue(0.5,0.5)) == 8.0\n@test g(VectorValue(0.5,0.5)) == -1\n\n# Domain\ndomain = (0,1,0,1)\npartition = (4,4)\nmodel = CartesianDiscreteModel(domain,partition)\n\n# FE space\norder = 2\nV = TestFESpace(model,ReferenceFE(lagrangian,Float64,order),dirichlet_tags=\"boundary\")\nU = TrialFESpace(V,u)\n\n# Triangulation\n\u03a9 = Triangulation(model)\n\u0393 = BoundaryTriangulation(model)\n\u039b = SkeletonTriangulation(model)\ndegree = 2*order\nd\u03a9 = Measure(\u03a9,degree)\nd\u0393 = Measure(\u0393,degree)\nd\u039b = Measure(\u039b,degree)\nn\u0393 = get_normal_vector(\u0393)\nn\u039b = get_normal_vector(\u039b)\n\n# Weak form\nconst h = (domain[2]-domain[1]) / partition[1]\nconst \u03b3 = 1\na(u,v) = \u222b( \u0394(u)*\u0394(v) )d\u03a9 +\n         \u222b( - mean(\u0394(u))*jump(\u2207(v)\u22c5n\u039b) - jump(\u2207(u)\u22c5n\u039b)*mean(\u0394(v)) + \u03b3/h*jump(\u2207(u)\u22c5n\u039b)*jump(\u2207(v)\u22c5n\u039b) )d\u039b\nl(v) = \u222b( v*f )d\u03a9 + \u222b( g*(\u2207(v)\u22c5n\u0393) )d\u0393\nop = AffineFEOperator(a,l,U,V)\n\nu\u2095 = solve(op)\n\n# Error\ne = u - u\u2095\nl2(u) = sqrt(sum( \u222b( u\u2299u )*d\u03a9 ))\nh1(u) = sqrt(sum( \u222b( u\u2299u + \u2207(u)\u2299\u2207(u) )*d\u03a9 ))\nel2 = l2(e)\neh1 = h1(e)\ntol = 1.0e-10\n@test el2 < tol\n@test eh1 < tol\n\nend\n", "meta": {"hexsha": "bc73d382e248bf6a06095a55974f491699088700", "size": 1161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/GridapTests/BiharmonicTests.jl", "max_stars_repo_name": "aerappa/Gridap.jl", "max_stars_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 390, "max_stars_repo_stars_event_min_datetime": "2019-05-16T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:17.000Z", "max_issues_repo_path": "test/GridapTests/BiharmonicTests.jl", "max_issues_repo_name": "aerappa/Gridap.jl", "max_issues_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 576, "max_issues_repo_issues_event_min_datetime": "2019-05-16T20:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:21:35.000Z", "max_forks_repo_path": "test/GridapTests/BiharmonicTests.jl", "max_forks_repo_name": "aerappa/Gridap.jl", "max_forks_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2019-12-30T23:35:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:56:24.000Z", "avg_line_length": 21.1090909091, "max_line_length": 103, "alphanum_fraction": 0.6158484065, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7534766265689111}}
{"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 (\u2208 [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 \u2208 [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\u00e9tit!\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 \u03bb = x\r\n\r\n    ### Approximate \u0393(n+c+s\u22121)/\u0393(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 = ((\u212f^(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": "# 1D diffusion problem\n\n# Packages and inclusions\nusing ModelingToolkit,DiffEqOperators,LinearAlgebra,Test,OrdinaryDiffEq, DomainSets\nusing ModelingToolkit: Differential\n\n# Tests\n@testset \"Dt(u(t,x)) ~ Dxx(u(t,x)), 0 ~ Dxx(v(t,x)) + sin(x), Dirichlet BCs\" begin\n    # Method of Manufactured Solutions\n    u_exact = (x,t) -> exp.(-t) * cos.(x)\n    v_exact = (x,t) -> exp.(-t) * sin.(x)\n\n    # Parameters, variables, and derivatives\n    @parameters t x\n    @variables u(..) v(..)\n    Dt = Differential(t)\n    Dx = Differential(x)\n    Dxx = Dx^2\n\n    # 1D PDE and boundary conditions\n    eqs = [Dt(u(t,x)) ~ Dxx(u(t,x)),\n           0 ~ Dxx(v(t,x)) + exp(-t)*sin(x)]\n    bcs = [u(0,x) ~ cos(x),\n           v(0,x) ~ sin(x),\n           u(t,0) ~ exp(-t),\n           Dx(u(t,1)) ~ -exp(-t) * sin(1),\n           Dx(v(t,0)) ~ exp(-t),\n           v(t,1) ~ exp(-t) * sin(1)]\n\n    # Space and time domains\n    domains = [t \u2208 Interval(0.0,1.0),\n               x \u2208 Interval(0.0,1.0)]\n\n    # PDE system\n    @named pdesys = PDESystem(eqs,bcs,domains,[t,x],[u(t,x),v(t,x)])\n\n    # Method of lines discretization\n    l = 20\n    dx = range(0.0,1.0,length=l)\n    order = 2\n    discretization = MOLFiniteDifference([x=>dx],t)\n\n    # Convert the PDE problem into an ODE problem\n    prob = discretize(pdesys,discretization)\n\n    # Solve ODE problem\n    sol = solve(prob,Rodas4(),saveat=0.1)\n\n    x_sol = dx\n    t_sol = sol.t\n\n    @variables u[1:l](..) v[1:l](..)\n\n    # Test against exact solution\n    for i in 1:l\n        @test all(isapprox.(u_exact(x_sol[i], t_sol), sol[u[i](t)], atol=0.01))\n        @test all(isapprox.(v_exact(x_sol[i], t_sol), sol[v[i](t)], atol=0.01))\n    end\nend\n", "meta": {"hexsha": "57a319c462f57194083c3942b0716b77ff72dbb2", "size": 1662, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MOL/MOL_1D_PDAE.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": "test/MOL/MOL_1D_PDAE.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": "test/MOL/MOL_1D_PDAE.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": 27.7, "max_line_length": 83, "alphanum_fraction": 0.559566787, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.7533904481191142}}
{"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": "# Test corr.jl\n#\n# Many test cases are migrated from test/01.jl in the old version\n# The reference results are generated from R. \n#\n\nusing Stats\nusing Base.Test\n\n\n# random data for testing\n\nx = [-2.133252557240862    -.7445937365828654;\n\t   .1775816414485478   -.5834801838041446;\n\t  -.6264517920318317   -.68444205333293;\n\t  -.8809042583216906    .9071671734302398;\n\t   .09251017186697393 -1.0404476733379926;\n\t  -.9271887119115569   -.620728578941385;\n\t  3.355819743178915    -.8325051361909978;\n\t  -.2834039258495755   -.22394811874731657;\n\t   .5354280026977677    .7481337671592626;\n\t   .39182285417742585   .3085762550821047]\n\nx1 = x[:, 1]\nx2 = x[:, 2]\n\n# autocov & autocorr\n\n@test_approx_eq autocov([1:5]) [2.0, 0.8, -0.2, -0.8, -0.8]\n@test_approx_eq autocor([1, 2, 3, 4, 5]) [1.0, 0.4, -0.1, -0.4, -0.4]\n\nracovx1 =  [1.839214242630635709475, \n           -0.406784553146903871124, \n            0.421772254824993531042, \n            0.035874943792884653182,\n           -0.255679775928512320604, \n            0.231154400105831353551, \n           -0.787016960267425180753, \n            0.039909287349160660341,\n           -0.110149697877911914579, \n           -0.088687020167434751916]\n\n@test_approx_eq autocov(x1) racovx1\n@test_approx_eq autocov(x) [autocov(x1) autocov(x2)]\n\nracorx1 = [0.999999999999999888978, \n          -0.221173011668873431557,  \n           0.229321981664153962122,  \n           0.019505581764945757045,\n          -0.139015765538446717242, \n           0.125681062460244019618, \n          -0.427909344123907742219,  \n           0.021699096507690283225,\n          -0.059889541590524189574, \n          -0.048220059475281865091]\n\n@test_approx_eq autocor(x1) racorx1\n@test_approx_eq autocor(x) [autocor(x1) autocor(x2)]\n\n\n# crosscov & crosscor\n\nrcov0 = [0.320000000000000006661,\n        -0.319999999999999951150,\n         0.080000000000000029421,\n        -0.479999999999999982236,\n         0.000000000000000000000,\n         0.479999999999999982236,\n        -0.080000000000000029421,\n         0.319999999999999951150,\n        -0.320000000000000006661]\n\n@test_approx_eq crosscov([1, 2, 3, 4, 5], [1, -1, 1, -1, 1]) rcov0\n@test_approx_eq crosscov([1:5], [1:5]) [-0.8, -0.8, -0.2, 0.8, 2.0, 0.8, -0.2, -0.8, -0.8]\n\nc11 = crosscov(x1, x1)\nc12 = crosscov(x1, x2)\nc21 = crosscov(x2, x1)\nc22 = crosscov(x2, x2)\n\n@test_approx_eq crosscov(x,  x1) [c11 c21]  \n@test_approx_eq crosscov(x1, x)  [c11 c12]\n@test_approx_eq crosscov(x,  x)  cat(3, [c11 c21], [c12 c22])\n\nrcor0 = [0.230940107675850,\n        -0.230940107675850,\n         0.057735026918963,\n        -0.346410161513775,\n         0.000000000000000,\n         0.346410161513775,\n        -0.057735026918963,\n         0.230940107675850,\n        -0.230940107675850]\n\n@test_approx_eq crosscor([1, 2, 3, 4, 5], [1, -1, 1, -1, 1]) rcor0        \n@test_approx_eq crosscor([1:5], [1:5]) [-0.4, -0.4, -0.1, 0.4, 1.0, 0.4, -0.1, -0.4, -0.4]\n\nc11 = crosscor(x1, x1)\nc12 = crosscor(x1, x2)\nc21 = crosscor(x2, x1)\nc22 = crosscor(x2, x2)\n\n@test_approx_eq crosscor(x,  x1) [c11 c21]  \n@test_approx_eq crosscor(x1, x)  [c11 c12]\n@test_approx_eq crosscor(x,  x)  cat(3, [c11 c21], [c12 c22])\n\n\n## pacf\n\nrpacfr =  [-0.218158122381419,\n            0.195015316828711,\n            0.144315804606139,\n           -0.199791229449779]\n\n@test_approx_eq pacf(x[:,1], 1:4) rpacfr\n\nrpacfy = [-0.221173011668873,\n           0.189683314308021,\n           0.111857020733719,\n          -0.175020669835420]\n\n@test_approx_eq pacf(x[:,1], 1:4, method=:yulewalker) rpacfy\n\n", "meta": {"hexsha": "a32fdd3112400ff29315657f6aca0ae1ce9a28fd", "size": 3499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/corr.jl", "max_stars_repo_name": "rened/Stats.jl", "max_stars_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-20T16:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T16:09:54.000Z", "max_issues_repo_path": "test/corr.jl", "max_issues_repo_name": "rened/Stats.jl", "max_issues_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_issues_repo_licenses": ["Xnet", "X11"], "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/corr.jl", "max_forks_repo_name": "rened/Stats.jl", "max_forks_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2177419355, "max_line_length": 90, "alphanum_fraction": 0.6338953987, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7533904430094323}}
{"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    \u03bb::Real\n    \u03d5::Real\nend\n\n\nfunction HaversineDistance(p1::GeoLocation, p2::GeoLocation)::Float64\n    \u03bb1, \u03d51 = p1.\u03bb, p1.\u03d5\n    \u03bb2, \u03d52 = p2.\u03bb, p2.\u03d5\n    \u0394\u03d5 = \u03d52 - \u03d51\n    \u0394\u03bb = \u03bb2 - \u03bb1\n    a = sind(\u0394\u03d5 / 2)^2 + cosd(\u03d51) * cosd(\u03d52) * sind(\u0394\u03bb / 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    \u03bb1, \u03d51 = p1.\u03bb, p1.\u03d5\n    \u03bb2, \u03d52 = p2.\u03bb, p2.\u03d5\n    \u0394\u03bb = \u03bb2 - \u03bb1\n    \u03b8 = atand(sind(\u0394\u03bb) * cosd(\u03d52), cosd(\u03d51) * sind(\u03d52) - sind(\u03d51) * cosd(\u03d52) * cosd(\u0394\u03bb))\n    return \u03b8\nend\n\n\nfunction HaversineDestination(geopoint::GeoLocation, \u03b8::Real, d::Real)::GeoLocation\n    \u03bb1, \u03d51 = geopoint.\u03bb, geopoint.\u03d5\n    \u03b4 = d / R\n    \u03d52 = asind(sind(\u03d51) * cos(\u03b4) + cosd(\u03d51) * sin(\u03b4) * cosd(\u03b8))\n    \u03bb2 = \u03bb1 + atand(sind(\u03b8) * sin(\u03b4) * cosd(\u03d51), cos(\u03b4) - sind(\u03d51) * sind(\u03d52))\n    return GeoLocation(\u03bb=\u03bb2, \u03d5=\u03d52)\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        \u03b8::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), \u03b8, d)\n    end\n    return broadcast((x, y, z) -> HaversineDestination(x, y, z), p, \u03b8, 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  \u03b8 = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-\u03b8)*A.u[idx] + \u03b8*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  \u03b8 = (t - A.t[idx])/ (A.t[idx+1] - A.t[idx])\n  (1-\u03b8)*A.u[:,idx] + \u03b8*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\u2080 = idx - 1; i\u2081 = idx; i\u2082 = i\u2081 + 1;\n  else\n    i\u2080 = idx; i\u2081 = i\u2080 + 1; i\u2082 = i\u2081 + 1;\n  end\n  l\u2080 = ((t-A.t[i\u2081])*(t-A.t[i\u2082]))/((A.t[i\u2080]-A.t[i\u2081])*(A.t[i\u2080]-A.t[i\u2082]))\n  l\u2081 = ((t-A.t[i\u2080])*(t-A.t[i\u2082]))/((A.t[i\u2081]-A.t[i\u2080])*(A.t[i\u2081]-A.t[i\u2082]))\n  l\u2082 = ((t-A.t[i\u2080])*(t-A.t[i\u2081]))/((A.t[i\u2082]-A.t[i\u2080])*(A.t[i\u2082]-A.t[i\u2081]))\n  A.u[i\u2080]*l\u2080 + A.u[i\u2081]*l\u2081 + A.u[i\u2082]*l\u2082\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\u2080 = idx - 1; i\u2081 = idx; i\u2082 = i\u2081 + 1;\n  else\n    i\u2080 = idx; i\u2081 = i\u2080 + 1; i\u2082 = i\u2081 + 1;\n  end\n  l\u2080 = ((t-A.t[i\u2081])*(t-A.t[i\u2082]))/((A.t[i\u2080]-A.t[i\u2081])*(A.t[i\u2080]-A.t[i\u2082]))\n  l\u2081 = ((t-A.t[i\u2080])*(t-A.t[i\u2082]))/((A.t[i\u2081]-A.t[i\u2080])*(A.t[i\u2081]-A.t[i\u2082]))\n  l\u2082 = ((t-A.t[i\u2080])*(t-A.t[i\u2081]))/((A.t[i\u2082]-A.t[i\u2080])*(A.t[i\u2082]-A.t[i\u2081]))\n  A.u[:,i\u2080]*l\u2080 + A.u[:,i\u2081]*l\u2081 + A.u[:,i\u2082]*l\u2082\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\u1d62 = A.u[i-1]\n  \u03c3 = 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]) + \u03c3 * (t - A.t[i-1])^2 + C\u1d62\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": "using Test\nusing DeepShiba\n\nfunction numerical_diff(f::Function, x::Real; e=10e-4)\n    return (f(x + e) - f(x - e)) / 2e\nend\n\nfunction numerical_diff(f::Function, xs::AbstractArray; e=1e-4)\n    grads = zeros(length(xs)) \n    for idx in 1:length(xs)\n        tmp_val = xs[idx]\n        xs[idx] = tmp_val + e\n        fxh1 = f(xs...)\n        xs[idx] = tmp_val - e\n        fxh2 = f(xs...)\n        grads[idx] = (fxh1 - fxh2) / 2e\n        xs[idx] = tmp_val\n    end\n    return grads\nend\n\nfunction isAbout(x, y; e=10e-4)\n    return y - e <= x <= y + e\nend\n\n\n\n\n@testset \"NumericalDiffTest\" begin\n    f(x) = 2x^3 + x^2 + 3x + 2\n    f\u2032(x) = 6x^2 + 2x + 3\n    for i in 0:0.1:1\n        num_diff = numerical_diff(f, i)\n        @test isAbout(num_diff, f\u2032(i)) \n    end\nend\n\n\n@testset \"OperatorTest\" begin\n    operators = [+, -, *, /]\n    basic_func(a, b, c) = (a^2 - 4b^2 + 10) / c\n    # This simple function contains all the basic operators.\n    @testset \"OperatorForwardTest\" begin\n        a, b = rand(2)\n        shiba_a, shiba_b = variable.((a, b))\n        for op in operators\n            y = op(a, b)\n            shiba_y = op(shiba_a, shiba_b)\n            @test y == shiba_y.data\n        end\n    end\n\n    @testset \"OparatorBackwardTest\" begin\n        a, b = rand(2)\n        shiba_a, shiba_b = variable.((a, b))\n        for op in operators\n            cleargrad!(shiba_a)\n            cleargrad!(shiba_b)\n            y = op(a, b)\n            shiba_y = op(shiba_a, shiba_b)\n            backward!(shiba_y)\n            shiba_a_grad = shiba_a.grad.data\n            shiba_b_grad = shiba_b.grad.data\n            numerical_grads = numerical_diff(op, [a, b])\n            @test isAbout(shiba_a_grad, numerical_grads[1])\n            @test isAbout(shiba_b_grad, numerical_grads[2])\n        end\n    end\n\n\n    @testset \"BasicFunBackwardTest\" begin\n        a, b, c = rand(3)\n        shiba_a, shiba_b, shiba_c = variable.((a, b, c))\n        grads = numerical_diff(basic_func, [a, b, c])\n        shiba_y = basic_func(shiba_a, shiba_b, shiba_c)\n        backward!(shiba_y)\n        for (shiba_grad, numerical_grad) in zip([shiba_a, shiba_b, shiba_c], [a, b, c])\n            @test isAbout(numerical_grad, shiba_grad.data)\n        end\n    end\n\nend\n\n\n@testset \"MathFuncTest\" begin\n    math_funcs = [sin, cos, tan, tanh]\n    @testset \"OneOrgMathFuncForwardTest\" begin\n        x = rand()\n        shiba_x = variable(x)\n        for func in math_funcs\n            y = func(x)\n            shiba_y = func(shiba_x)\n            @test isAbout(y, shiba_y.data)\n        end\n    end\n    @testset \"OneOrgMathFuncBackwardTest\" begin\n        x = rand()\n        shiba_x = variable(x)\n        for func in math_funcs\n            cleargrad!(shiba_x)\n            shiba_y = func(shiba_x)\n            backward!(shiba_y)\n            numerical_grad = numerical_diff(func, x)\n            @test isAbout(shiba_x.grad.data, numerical_grad)\n        end\n    end\nend\n", "meta": {"hexsha": "ed2cd5126f9cec2da4b3cfd6d4d9a2e149ecdae0", "size": 2897, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "terasakisatoshi/DeepShiba.jl", "max_stars_repo_head_hexsha": "de4c7503bd4bb24d8d76d864cc171439f3cdfa56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-10T02:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T12:00:33.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "terasakisatoshi/DeepShiba.jl", "max_issues_repo_head_hexsha": "de4c7503bd4bb24d8d76d864cc171439f3cdfa56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2020-05-20T07:44:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-20T10:28:35.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "terasakisatoshi/DeepShiba.jl", "max_forks_repo_head_hexsha": "de4c7503bd4bb24d8d76d864cc171439f3cdfa56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-29T12:32:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T12:32:31.000Z", "avg_line_length": 26.8240740741, "max_line_length": 87, "alphanum_fraction": 0.5554021401, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7533904375287046}}
{"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) (`\u211d` for short) and [`ComplexNumbers`](@ref) (`\u2102`).\n\"\"\"\nabstract type AbstractNumbers end\n\n\"\"\"\n    \u211d = RealNumbers()\n\nThe field of real numbers.\n\"\"\"\nstruct RealNumbers <: AbstractNumbers end\n\n\"\"\"\n    \u2102 = ComplexNumbers()\n\nThe field of complex numbers.\n\"\"\"\nstruct ComplexNumbers <: AbstractNumbers end\n\n\"\"\"\n    \u210d = QuaternionNumbers()\n\nThe division algebra of quaternions.\n\"\"\"\nstruct QuaternionNumbers <: AbstractNumbers end\n\nconst \u211d = RealNumbers()\nconst \u2102 = ComplexNumbers()\nconst \u210d = QuaternionNumbers()\n\nBase.show(io::IO, ::RealNumbers) = print(io, \"\u211d\")\nBase.show(io::IO, ::ComplexNumbers) = print(io, \"\u2102\")\nBase.show(io::IO, ::QuaternionNumbers) = print(io, \"\u210d\")\n\n^(\ud835\udd3d::AbstractNumbers, n) = Euclidean(n...; field = \ud835\udd3d)\n\n@doc doc\"\"\"\n    real_dimension(\ud835\udd3d::AbstractNumbers)\n\nReturn the real dimension $\\dim_\u211d \ud835\udd3d$ of the [`AbstractNumbers`] system `\ud835\udd3d`.\nThe real dimension is the dimension of a real vector space with which a number in `\ud835\udd3d` 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(\ud835\udd3d::AbstractNumbers)\n    error(\"real_dimension not defined for number system $(\ud835\udd3d)\")\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\u0307 = 10.0*(y - x)\n    y\u0307 = x*(28.0-z) - y\n    z\u0307 = x*y - (8/3)*z\n    return [x\u0307, y\u0307, z\u0307]\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\u03c4 = DataDrivenDiffEq.optimal_svht(m,n)\nr = length(S[S .> \u03c4*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,\u03b2)=3/\u03b2*( log(v/w) - 1/2*log(2*\u03c0*\u03b2) - log(sinh(v*\u03b2/2)/sinh(w*\u03b2/2)))\n\n# 62d\nY(x,v,\u03b2)=1/(1-exp(-v*\u03b2))*(1+exp(-v*\u03b2)-exp(-v*x)-exp(v*(x-\u03b2)))\n# 62c integrand\nf(x,v,w,\u03b2)=(exp(\u03b2-x)+exp(x))/(w^2*x*(1-x/\u03b2)+Y(x,v,\u03b2)*(v^2-w^2)/v)^(1/2)\n# 62c\nB(v,w,\u03b2,\u03b1) = \u03b1*v/(sqrt(\u03c0)*(exp(\u03b2)-1)) * quadgk(x->f(x,v,w,\u03b2),0,\u03b2/2)[1]\n#62e\nC(v,w,\u03b2)=3/4*(v^2-w^2)/v * (coth(v*\u03b2/2)-2/(v*\u03b2))\n\nF(v,w,\u03b2,\u03b1)=-(A(v,w,\u03b2)+B(v,w,\u03b2,\u03b1)+C(v,w,\u03b2)) #(62a)\n\n# Can now evaluate, e.g.\n# F(v,w,\u03b2,\u03b1)=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 \u03b1 in 1:5\n        @printf(\"\u03b1=%d\\t\\t\",\u03b1)\n    end\n    @printf(\"\\n\")\n\n    for \u03b2 in 1:0.25:3.0\n        v=w=4\n        print(\"\u03b2: $\u03b2  \\t||\")\n        for \u03b1 in 1:5\n            @printf(\"%f\\t\",F(v,w,\u03b2,\u03b1))\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\u03b1=1.0\n\t\u03b2=1.0\n\n\tfor v=6:0.1:8\n    \t@printf(\"%f %f\\n\",v,F(v,w,\u03b2,\u03b1))\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,\u03b2,\u03b1))\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 \u03b1 in 1:5\n\t\t@printf(\"\u03b1=%d\\t\\t\",\u03b1)\n\tend\n\t@printf(\"\\n\")\n\n\tfor \u03b2 in 1:0.25:3.0\n\t\tprint(\"\u03b2: $\u03b2  \\t||\")\n\t\tfor \u03b1 in 1:5\n\t\t\tmyf(x) = F(x[1],x[2],\u03b2,\u03b1)\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 \u03b1 in 1:5\n\t\t\t@printf(\"\u03b1=%d\\t\\t\",\u03b1)\n\t\tend\n\t\t@printf(\"\\n\")\n\n\t\tfor \u03b2 in 1:0.25:3.0\n\t\t\tprint(\"\u03b2: $\u03b2  \\t||\")\n\t\t\tfor \u03b1 in 1:5\n\t\t\t\tmyf(x) = F(x[1],x[2],\u03b2,\u03b1)\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": "function main()\n    N, K = parse.(Int, split(readline()))\n\n    f(N, K) = min(K-1, 2N + 1 - K) * (2 \u2264 K \u2264 2N)\n\n    ans = 0\n    for x in 2:2N\n        ans += f(N, x) * f(N, x - K)\n    end\n\n    println(ans)\n   \nend\n\nmain()\n\n", "meta": {"hexsha": "e2b8ec98016ecbb3aa46a7637abc61024a4b6b58", "size": 220, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "virtual/0724/nicetak/arc107_b.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": "virtual/0724/nicetak/arc107_b.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": "virtual/0724/nicetak/arc107_b.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": 12.9411764706, "max_line_length": 49, "alphanum_fraction": 0.4272727273, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7533904288605694}}
{"text": "using Statistics:quantile\n\n\"\"\"\n    classify_percentile(threshold)\n\nCreate a percentile-based classifiction function that converts `scores_train::Scores` and `scores_test::Scores` to an\narray of classes with `\"normal\"` indicating normal data and `\"outlier\"` indicating outliers. The conversion is based on\npercentiles of the training data, i.e. all datapoints above the `threshold` percentile are considered outliers.\n\nParameters\n----------\n    threshold::Real\nThe score threshold (number between 0 and 1) used to classify the samples into inliers and outliers.\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----------\n    classes::AbstractVector{String}\nThe vector of classes consisting of `\"outlier\"` and `\"normal\"` elements.\n\nExamples\n----------\n    classify = classify_percentile(0.9)\n    scores_train, scores_test = ([1, 2, 3], [4, 3, 2, 1, 0])\n    classify(scores_train, scores_train) # [1, 1, -1]\n    classify(scores_train, scores_test) # [-1, -1, 1, 1, 1]\n\"\"\"\nfunction classify_percentile(threshold::Real)\n    function percentile(scores_train::Scores, scores_test::Scores)::Tuple{Labels, Labels}\n        @assert 0 < threshold < 1\n        t = quantile(scores_train, threshold)\n        f = scores -> ifelse.(scores .> t, CLASS_OUTLIER, CLASS_NORMAL)\n        f(scores_train), f(scores_test)\n    end\n    return percentile\nend\n", "meta": {"hexsha": "06feb8a2b30a8e3f26e42ccdee91eb3d60d77951", "size": 1560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/classification.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/classification.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/classification.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": 37.1428571429, "max_line_length": 119, "alphanum_fraction": 0.7121794872, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7533904254541145}}
{"text": "using MultipleViewGeometry, Base.Test\nusing MultipleViewGeometry.ModuleCostFunction\nusing MultipleViewGeometry.ModuleTypes\nusing MultipleViewGeometry.ModuleConstraints\nusing MultipleViewGeometry.ModuleConstruct\nusing MultipleViewGeometry.ModuleDraw\nusing BenchmarkTools, Compat\nusing StaticArrays\nusing  MAT, Plots\n\n# Load MATLAB matrices that represent a pair of images and that contain\n# a set of manually matched corresponding points.\nfile = matopen(\"./data/teapot.mat\")\nX = read(file,\"pts3D\")\nX = X[:,1:10:end]\nclose(file)\n\n# Fix random seed.\nsrand(1234)\nplotlyjs()\n\n#\ud835\udcb3 = [Point3DH(x,y,z,1.0) for x=-1:0.5:10 for y=-1:0.5:10 for z=2:-0.1:1]\n\n\ud835\udcb3 = [Point3DH(X[1,i],X[2,i],X[3,i],1.0) for i = 1:size(X,2)]\n\n#X = reinterpret(Float64,map(SVector{4,Float64},\ud835\udcb3),(4,length(\ud835\udcb3)))\n#Z = reinterpret(SVector{4,Float64},(3000,4))\n# reinterpret(SVector{4,Float64}, X, (size(X,2),))#\n# reinterpret(SVector{4,Float64}, Z, (size(Z,2),))#\n# reinterpret(SVector{4,Float64}, X, (3000,1))\n\n# Intrinsic and extrinsic parameters of camera one.\n\ud835\udc0a\u2081 = eye(3)\n\ud835\udc11\u2081 = eye(3)\n\ud835\udc2d\u2081 = [-250.0, 0.0, 2500.0]\n\ud835\udc1c\u2081 = [0.0, 0.0, 0.0]\n\ud835\udc04\u2081 = [\ud835\udc11\u2081 \ud835\udc2d\u2081]\n\n# Intrinsic and extrinsic parameters of camera two.\n\ud835\udc0a\u2082 = eye(3)\n\ud835\udc11\u2082 =  eye(3)\n\ud835\udc2d\u2082 = [250.0,   0.0, 2500.0]\n\ud835\udc1c\u2082 = [0.0, 0.0, 0.0]\n\ud835\udc04\u2082 = [\ud835\udc11\u2082 \ud835\udc2d\u2082]\n\n# Camera projection matrices.\n\ud835\udc0f\u2081 = construct(ProjectionMatrix(),\ud835\udc0a\u2081,\ud835\udc11\u2081,\ud835\udc2d\u2081)\n\ud835\udc0f\u2082 = construct(ProjectionMatrix(),\ud835\udc0a\u2082,\ud835\udc11\u2082,\ud835\udc2d\u2082)\n\n# Set of corresponding points.\n\u2133 = project(Pinhole(),\ud835\udc0f\u2081,\ud835\udcb3)\n\u2133\u02b9 = project(Pinhole(),\ud835\udc0f\u2082,\ud835\udcb3)\n\n# Estimate of the fundamental matrix and the true fundamental matrix.\n\ud835\udc05 = estimate(FundamentalMatrix(), DirectLinearTransform(), (\u2133, \u2133\u02b9))\n\n# Convert the array of Point3DH into a 4 x N matrix to simplify\n# the plotting of the data points.\n#X = reinterpret(Float64,map(SVector{4,Float64},\ud835\udcb3),(4,length(\ud835\udcb3)))\n\n# Visualise the data points\np1 = Plots.plot(X[1,:],X[2,:],X[3,:],seriestype = :scatter, ms=1,grid = false, box = :none, legend = false)\ndraw!(WorldCoordinateSystem3D(), 450, p1)\ndraw!(Camera3D(), \ud835\udc0a\u2081, \ud835\udc11\u2081, \ud835\udc2d\u2081, 250, p1)\ndraw!(Camera3D(), \ud835\udc0a\u2082, \ud835\udc11\u2082, \ud835\udc2d\u2082, 250, p1)\n\n\n# Plot the projections of the point cloud in the image pair.\np2 =  Plots.plot();\nfor n = 1:length(\u2133)\n    m = \u2133[n]\n    Plots.plot!([m[1]],[m[2]], grid = false, box = :none, legend = false,\n                    seriestype = :scatter, ms = 2, markercolor=:Black,\n                    aspect_ratio = :equal)\nend\n\np3 =  Plots.plot();\nfor n = 1:length(\u2133\u02b9)\n    m\u02b9 = \u2133\u02b9[n]\n    Plots.plot!([m\u02b9[1]],[m\u02b9[2]], grid = false, box = :none, legend = false,\n                    seriestype = :scatter, ms = 2, markercolor=:Black,\n                    aspect_ratio = :equal)\nend\n\n# Visualise the 3D point cloud, as well as the projected images.\nl = @layout [ a; [b c] ]\np4 = Plots.plot(p1,p2, p3, layout = l)\n\n\n\ud835\udcb4 = triangulate(DirectLinearTransform(),\ud835\udc0f\u2081,\ud835\udc0f\u2082,(\u2133,\u2133\u02b9))\n\nY = reinterpret(Float64,map(SVector{4,Float64},\ud835\udcb4),(4,length(\ud835\udcb4)))\n# Visualise the data points\np5 = Plots.plot(Y[1,:],Y[2,:],Y[3,:],seriestype = :scatter, ms=1,grid = false, box = :none, legend = false)\ndraw!(WorldCoordinateSystem3D(), 450, p1)\ndraw!(Camera3D(), \ud835\udc0a\u2081, \ud835\udc11\u2081, \ud835\udc2d\u2081, 250, p1)\ndraw!(Camera3D(), \ud835\udc0a\u2082, \ud835\udc11\u2082, \ud835\udc2d\u2082, 250, p1)\n\n\n# \ud835\udc05 = construct(FundamentalMatrix(),\ud835\udc0a\u2081,\ud835\udc11\u2081,\ud835\udc2d\u2081,\ud835\udc0a\u2082,\ud835\udc11\u2082,\ud835\udc2d\u2082)\n#\n# # To triangulate the corresponding points using the Fundamental matrix, we first\n# # have to factorise the Fundamental matrix into a pair of Camera matrices. Due\n# # to projective ambiguity, the camera matrices are not unique, and so the\n# # triangulated 3D points will most probably not match the original 3D points.\n# # However, when working with noiseless data, the projections of the triangulated\n# # points should satisfy the epipolar constraint. We can use this fact to\n# # validate that the triangulation is correctly implemented.\n# \ud835\udcb4 = triangulate(DirectLinearTransform(),\ud835\udc05,(\u2133,\u2133\u02b9))\n# Y = reinterpret(Float64,map(SVector{4,Float64},\ud835\udcb4),(4,length(\ud835\udcb4)))\n# p6 = Plots.plot(Y[1,:],Y[2,:],Y[3,:],seriestype = :scatter, ms=1,grid = false, box = :none, legend = false)\n#\n# \ud835\udc10\u2081, \ud835\udc10\u2082 = construct(ProjectionMatrix(),\ud835\udc05)\n", "meta": {"hexsha": "ff8a19224c98a8dc1b04ad7fc8a9b1e344d13888", "size": 3959, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/example_uncalibrated_triangulate.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": "demo/example_uncalibrated_triangulate.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": "demo/example_uncalibrated_triangulate.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": 34.7280701754, "max_line_length": 109, "alphanum_fraction": 0.6794645112, "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7533904250830694}}
{"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 \u00f7 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 \u00f7 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 \u03b1 \u03b2 \u03c1 \u03b4 \u03c3 \u03a9_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 = [\u03b1, \u03b2, \u03c1]\n    p_f = [\u03b4, \u03c3, \u03a9_1]\n\n    H = [1 / c - (\u03b2 / c_p) * (\u03b1 * exp(z_p) * k_p^(\u03b1 - 1) + (1 - \u03b4)),\n         c + k_p - (1 - \u03b4) * k - q,\n         q - exp(z) * k^\u03b1,\n         z_p - \u03c1 * z,\n         i - (k_p - (1 - \u03b4) * k)]\n\n    x\u0304 = [k_ss ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1)), z_ss ~ 0]\n    y\u0304 = [c_ss ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)) -\n                \u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1)),\n         q_ss ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)),\n         i_ss ~ \u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1))]\n\n    x\u0304_iv = [z_ss ~ 0, k_ss ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1))]\n    y\u0304_iv = [q_ss ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)),\n            c_ss ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)) -\n                    \u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1)),\n            i_ss ~ \u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1))]\n\n    n_\u03f5 = 1\n    n_z = 2\n    n_x = length(x)\n    n_y = length(y)\n    n_p = length(p)\n    \u0393 = reshape([\u03c3], n_\u03f5, n_\u03f5)\n    \u03b7 = reshape([0; -1], n_x, n_\u03f5) # \u03b7 is n_x * n_\u03f5 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    \u03a9 = [\u03a9_1, \u03a9_1]\n\n    return H, (; x, y, x\u0304, y\u0304, \u0393, \u03b7, p_f, p, x\u0304_iv, y\u0304_iv, \u03a9, 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 Plots, Images; pyplot()\n\nimg = load(\"../data/stars.png\")\ngImg = red.(img)*0.299 + green.(img)*0.587 + blue.(img)*0.114\nrows, cols = size(img)\n\nprintln(\"Highest intensity pixel: \", findmax(gImg))\n\nfunction boxBlur(image,x,y,d)\n    if x<=d || y<=d || x>=cols-d || y>=rows-d\n        return image[x,y]\n    else\n        total = 0.0\n        for xi = x-d:x+d\n            for yi = y-d:y+d\n                total += image[xi,yi]\n            end\n        end\n        return total/((2d+1)^2)\n    end\nend\n\nblurImg = [boxBlur(gImg,x,y,5) for x in 1:cols, y in 1:rows]\n\nyOriginal, xOriginal = argmax(gImg).I\nyBoxBlur, xBoxBlur   = argmax(blurImg).I\n\np1 = heatmap(gImg, c=:Greys, yflip=true)\np1 = scatter!((xOriginal, yOriginal), ms=60, ma=0, msw=4, msc=:red) \np2 = heatmap(blurImg, c=:Greys, yflip=true)\np2 = scatter!((xBoxBlur, yBoxBlur), ms=60, ma=0, msw=4, msc=:red)\n\nplot(p1, p2, size=(800, 400), ratio=:equal, xlims=(0,cols), ylims=(0,rows), \n\tcolorbar_entry=false, border=:none, legend=:none)\n", "meta": {"hexsha": "63b2911b3e7085aa11c094aa99bad91be60f9d3b", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1_chapter/imageProcessing.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/imageProcessing.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/imageProcessing.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.2571428571, "max_line_length": 76, "alphanum_fraction": 0.593528817, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.753291848410946}}
{"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": "using ParametricMachinesDemos, Flux\n  \npoly(x, y) = (2x-1)^2 + 2y + x * y - 3\npoly((x, y)) = poly(x, y)\nrg = 0:0.01:1\nN = length(rg)\nflat = hcat(repeat(rg, inner=N), repeat(rg, outer=N))\ntruth = map(poly, eachrow(flat))\n\n## Let us generate a `6 x 6` trainig grid.\n\nN_train = 6\nrg_train = range(0, 1, length=N_train)\nX_train = hcat(repeat(rg_train, inner=N_train), repeat(rg_train, outer=N_train)) |> permutedims\nY_train = map(poly, eachcol(X_train)) |> permutedims\n\ndimensions = [2, 4, 4, 4]\n\nmachine = DenseMachine(dimensions, sigmoid)\n\nmodel = Flux.Chain(machine, Dense(sum(dimensions), 1)) |> f64\n\nfunction loss(X_train, Y_train)\n    Flux.Losses.mse(model(X_train), Y_train)\nend\n\nopt = ADAM(0.1)\nps = Flux.params(model)\n\n# check that learning happens correctly\n\nN = 14\nrg = range(0, 1, length=N)\nX = hcat(repeat(rg, inner=N), repeat(rg, outer=N)) |> permutedims\nY = map(poly, eachcol(X)) |> permutedims\n\nfor i in 1:10000\n    gs = gradient(ps) do\n        loss(X_train, Y_train)\n    end\n    Flux.Optimise.update!(opt, ps, gs)\n    if i % 500 == 0\n        @show loss(X_train, Y_train)\n        @show loss(X, Y)\n    end\nend\n", "meta": {"hexsha": "6a0d393d334ff12c43b4621adf2c97a8ef421d3c", "size": 1121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/poly.jl", "max_stars_repo_name": "BeaverResearch/ParametricMachines.jl", "max_stars_repo_head_hexsha": "65bb87b45dc375dbeb7412b0a7012afc02a19d8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-30T09:44:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:37:20.000Z", "max_issues_repo_path": "examples/poly.jl", "max_issues_repo_name": "BeaverResearch/ParametricMachines.jl", "max_issues_repo_head_hexsha": "65bb87b45dc375dbeb7412b0a7012afc02a19d8e", "max_issues_repo_licenses": ["MIT"], "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/poly.jl", "max_forks_repo_name": "BeaverResearch/ParametricMachines.jl", "max_forks_repo_head_hexsha": "65bb87b45dc375dbeb7412b0a7012afc02a19d8e", "max_forks_repo_licenses": ["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.8510638298, "max_line_length": 95, "alphanum_fraction": 0.6520963426, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7532918452428415}}
{"text": "data() = readlines(\"day05.txt\")\n\n# This is really just the binary representation of an integer in disguise!\nrow(s) = parse(Int, replace(replace(s[1:7], \"F\"=>\"0\"), \"B\"=>\"1\"); base = 2)\ncol(s) = parse(Int, replace(replace(s[8:10], \"L\"=>\"0\"), \"R\"=>\"1\"); base = 2)\nid(s) = row(s) * 8 + col(s)\n\n# quick test\n# row(\"BFFFBBFRRR\")\n# col(\"BFFFBBFRRR\")\n# id(\"BFFFBBFRRR\")\n\n# id(\"FFFBBBFRRR\") == 119\n# id(\"BBFFBBFRLL\") == 820\n\n# read data\nboarding_passes = id.(data())\n\n# part 1\npart1() = maximum(boarding_passes)  # 980\n\n# part 2\nfunction part2()\n    sorted = sort(boarding_passes)\n    idx = argmax([sorted[i] - sorted[i-1] > 1 for i in 2:length(sorted)])  # 567\n    return sorted[idx] + 1\nend\n\n# using BenchmarkTools\n\n# From Aaron on Discord. The mapfoldl function is awesome in terms of performance!\nseatnumber(line) = mapfoldl(c->c in \"BR\", (x, y)->2x+y, line, init=0)\nseatnumber(\"BFFFBBFRRR\")\n", "meta": {"hexsha": "7c4899db5a2b5d5f9a4b801231ff65f7b43035f4", "size": 887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day05.jl", "max_stars_repo_name": "tk3369/AdventOfCode2020", "max_stars_repo_head_hexsha": "ebd9d7b7fd48987bcfa6f1389e335d870d1a0ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-26T23:26:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:14:58.000Z", "max_issues_repo_path": "day05.jl", "max_issues_repo_name": "tk3369/AdventOfCode2020", "max_issues_repo_head_hexsha": "ebd9d7b7fd48987bcfa6f1389e335d870d1a0ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day05.jl", "max_forks_repo_name": "tk3369/AdventOfCode2020", "max_forks_repo_head_hexsha": "ebd9d7b7fd48987bcfa6f1389e335d870d1a0ea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-18T03:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T03:18:47.000Z", "avg_line_length": 26.0882352941, "max_line_length": 82, "alphanum_fraction": 0.6392333709, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.753291845196971}}
{"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, \u03bd_grid::Vector)\n\nProduce the black-body planck spectrum (mW/m\u00b2-sr-cm\u207b\u00b9), given the temperature (K) \nand calculation grid (\u03bd in cm\u207b\u00b9)\n\n\"\"\"\nfunction planck_spectrum_wn(T::Real, \u03bd_grid::Vector)\n\n    c1 = 1.1910427 * 10^(-5)    # mW/m\u00b2-sr-cm\u207b\u00b9\n    c2 = 1.4387752              # K\u22c5cm\n\n    # L(\u03bd, T) = c1\u22c5\u03bd\u00b3/(exp(c2\u22c5\u03bd/T) - 1)\n    radiance = c1 .* (\u03bd_grid.^3) ./ (exp.(c2 * \u03bd_grid / T) .- 1)\n\n    return radiance\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(T::Real, \u03bb_grid::Vector)\n\nProduce the black-body planck spectrum (W/m\u00b2-sr-\u03bcm), given the temperature (K) \nand calculation grid (\u03bb in \u03bcm)\n\n\"\"\"\nfunction planck_spectrum_wl(T::Real, \u03bb_grid::Vector)\n\n    c1 = 1.1910427 * 10^8    # W/m\u00b2-sr-\u03bcm\n    c2 = 1.4387752 * 10^4    # K\u22c5\u03bcm\n\n    # L(\u03bd, T) = c1\u22c5\u03bd\u00b3/(exp(c2\u22c5\u03bd/T) - 1)\n    radiance = c1 ./ (\u03bb_grid.^5 .* (exp.(c2 ./ (\u03bb_grid * T)) .- 1))\n\n    return radiance\nend\n\n# W/m\u00b2-sr-\u03bcm to Ph/s-m\u00b2-sr-um\n# \u03bb_grid in micron\nfunction watts_to_photons(\u03bb_grid::Vector, radiance::Vector)\n\n    h = 6.62607015e-34 # J\u22c5Hz\u22121\n    c = 299792458 # m/s\n\n    E_per_\u03bb = h * c ./ (\u03bb_grid / 1e6)\n    photons = radiance ./ E_per_\u03bb\n\n    return photons\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(T::Real; stride_length::Integer = 100)\n\nProduce the black-body planck spectrum (mW/m\u00b2-sr-cm\u207b\u00b9), given the temperature (K). \nUse a unit calculation grid and check for convergence every `stride_length` cm\u207b\u00b9 until the \nspectrum dies off. \n\n\"\"\"\nfunction planck_spectrum_wn(T::Real; stride_length::Integer = 100)\n\n    # \u03bds, starting with \u03bd0 = 1.0 cm\u207b\u00b9\n    \u03bds = [1.0]\n\n    # radiances corresponding with \u03bds\n    radiances = planck_spectrum_wn(T, \u03bds)\n\n    # Loop until convergence\n    while true \n        \n        # Add the next \u03bd\n        \u03bds = vcat(\u03bds, collect(\u03bds[end] + 1 : \u03bds[end] + stride_length))\n\n        # Compute the next radiance\n        radiances = vcat(radiances, planck_spectrum_wn(T, \u03bds[(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 [\u03bds[1:(end-1)] radiances[1:(end-1)]]\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(solar, \u03bd_grid)\n\nInterpolate a solar linelist to the \u03bd_grid\n\"\"\"\nfunction itp_solar_to_\u03bd_grid(solar, \u03bd_grid)\n\n    solar_idx_start = maximum((argmin(abs.(solar[:, 1] .- minimum(\u03bd_grid))) - 10, 1))\n    solar_idx_end   = minimum((argmin(abs.(solar[:, 1] .- maximum(\u03bd_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.(\u03bd_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, \u03bd_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                                      \u03bd_grid::Union{AbstractRange{<:Real}, AbstractArray})\n\n    solar = solar_transmission_from_file(file_name)\n    return itp_solar_to_\u03bd_grid(solar, \u03bd_grid)\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(\u03bd_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(\u03bd_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(\u03bd_grid, solar_transmission_from_file(filename, \u03bd_grid))\nend\n\n\"\"\"\n    $(FUNCTIONNAME)(\u03bd_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(\u03bd_grid::Union{AbstractRange{<:Real}, AbstractArray} = 600.0:0.01:26316.0)\n\n    T = 5777 # K\n    \u03bb_grid = reverse(1e4 ./ \u03bd_grid) # Wavenumber to micron\n    black_body = reverse(SolarModel.watts_to_photons(\u03bb_grid, planck_spectrum_wl(T, \u03bb_grid) * 2.1629e-05 * pi))\n    solar_transmission = default_solar_transmission(\u03bd_grid)[:,2]\n\n    return hcat(\u03bd_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": "using Random, Distributions, FreqTables, Statistics\nusing LinearAlgebra\nusing JLD2, JLD, CSV, DataFrames\n\nRandom.seed!(1234);\n\nfunction q1()\n    #Initializing variables and practice with basic matrix operations\n    # 1a\n    A = rand(Uniform(-5,10), 10,7)\n\n    # i\n    B = rand(Normal(-2, 15), 10, 7)\n\n    # ii\n    C = [A[1:5, 1:5] B[1:5, end-1:end:-1]] #TODO Check latter\n\n    # iii\n    D = copy(A)\n    D[A .> 0] .= 0\n    D\n\n    length(A)\n\n    # 1c\n    unique(D) |> length\n\n    # 1d\n    E = reshape(B, (length(B),1))\n\n    # 1e\n    F = cat(A, B, dims=3)\n\n    # 1f\n    #F = permutedims(F, (3,1,2))\n\n    # 1g\n    G = kron(B, C)\n    #kron(C,F)\n\n    # 1h\n    save(\"./PS1-julia-intro/matrixpractice.jld\", \n        \"A\", A,\n        \"B\", B, \n        \"C\", C, \n        \"D\", D, \n        \"E\", E, \n        \"F\", F,\n        \"G\", G)\n\n    # 1i\n    save(\"./PS1-julia-intro/firstmatrix.jld\", \"A\", A,\"B\", B, \"C\", C, \"D\", D)\n\n    # 1j\n    convert(DataFrame, C) |> CSV.write(\"./PS1-julia-intro/Cmatrix.csv\", )\n\n    # 1k\n    convert(DataFrame, D) |> CSV.write(\"./PS1-julia-intro/Dmatrix.csv\", delim=\"\\t\")\n\n    return A, B, C, D\n\nend\n\n\nfunction q2(A,B,C)\n#  Practice with loops and comprehensions\n# 2a\n    AB = [x*y for (x,y) in zip(A, B)]\n\n    AB2 = A .* B\n\n    # 2b\n\n    Cprime = Vector{Float64}()\n    for i in C\n        if  -5 <= i  <= 5.0\n            append!(Cprime, i)\n        end\n    end\n\n    Cprime2 = C[-5 .<= C .<= 5]\n\n    # 2c\n    N = 15169\n    K = 6\n    T = 5\n    X = zeros(N,K,T)\n    for t in 1:T\n        X[:,1,t] .= ones(N) # stationary over time.\n        X[:,2,t] .= rand(Bernoulli(.75*(6-t)/5), N)\n        X[:,3,t] .= rand(Normal(15+t-1, 5*(t-1)), N)\n        X[:,4,t] .= rand(Normal(\u03c0*(6-t)/3, 1/\u212f), N)\n        X[:,5,t] .= rand(Binomial(20, 0.6), N)\n        X[:,6,t] .= rand(Binomial(20,0.5),N) # Discrete normal stationary over time.\n    end\n    # 2d\n\n    \u03b2 = zeros(K,T)\n    \u03b2[1,:] .= [1 + t*(.25) for t in 1:T] # d1\n    \u03b2[2,:] .= [log(t) for t in 1:T] # d2\n    \u03b2[3,:] .= [-sqrt(t) for t in 1:T] # d3\n    \u03b2[4,:] .= [(\u212f^(t)  - \u212f^(t+1)) for t in 1:T] # d4\n    \u03b2[5,:] .= [t for t in 1:T] # d5\n    \u03b2[6,:] .= [t/3 for t in 1:T] # d6\n\n    # 2e\n    Y = zeros(N,T)\n    for t in 1:T # How to use comprehensions in this case?\n       Y[:,t] .= X[:,:,t]*\u03b2[:,t] + rand(Normal(0, .36), N)\n    end\nend\n\n# 3\nfunction q3()\n    df = CSV.read(\"./PS1-julia-intro/nlsw88.csv\")# |> dropmissing\n    save(\"./PS1-julia-intro/nlsw88.jld.jld\", \"df\", df)\n    # 3b\n    println((df.never_married |> sum)*100/nrow(df) |> round,\"% sample has never been married\")\n    println((df.collgrad |> sum)*100/nrow(df) |> round,\"% are college graduates\")\n\n    # 3c\n    freqtable(df.race) |> prop\n    # 3d \n    summarystats = describe(df)\n    println(df.grade .|> ismissing |> sum, \" grades observations are missing\")\n\n    # 3e\n    freqtable(df.occupation, df.industry) |> prop\n\n    # 3f\n    gdf = groupby(df, [\"occupation\",\"industry\"], sort=true) \n    combine(gdf, :wage => mean => :avg_ind_occ_wage) |> dropmissing \n    return nothing\nend\n\n\n# Practice with functions\n# 4a Load firstmatrix.jld.\nfunction q4()\n    load(\"./PS1-julia-intro/firstmatrix.jld\")\n\n    function matrixops(m1,m2)\n        if size(m1) != size(m2)\n            error(\"inputs must have the same size.\")\n        end\n        #=\n        Takes as inputs the matrices A and B from question (a) of problem 1 and has three outputs: \n            (i) the element-by-element product of the inputs, \n            (ii) the product A'B, and \n            (iii) the sum of all the elements of A + B.\n        =#\n        return m1 .* m2, m1' * m2, m1 + m2\n    end\n\n    a,b, c = matrixops(A, B);\n\n    df = CSV.read(\"./PS1-julia-intro/nlsw88.csv\") |> dropmissing\n    convert(Array,df.ttl_exp); convert(Array,df.wage);\n    matrixops(\n        df.ttl_exp, \n        df.wage);\n    return nothing\nend\n\nA, B, C, D = q1();\nq2(A,B,C)\nq3()\nq4()", "meta": {"hexsha": "73c5b54fba540090f1b74bae883dd4a5285b1538", "size": 3831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS1-julia-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/PS1-julia-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/PS1-julia-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": 22.8035714286, "max_line_length": 99, "alphanum_fraction": 0.5152701644, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7532918404448148}}
{"text": "abstract type SpectralEstimate{D,T} <: AbstractVector{T} end\n\n@doc raw\"\"\"\n    Periodogram(timeseries, \u0394)\n\nCompute the periodogram for the provided timeseries with sampling rate \u0394.\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- `\u0394`: A positive real number.\n\nThe periodogram is defined as\n```math\n\\boldsymbol I(\u03c9)&=\\boldsymbol J(\u03c9) \\boldsymbol J(\u03c9)^H \\quad \\text{where} \\quad \\boldsymbol J(\u03c9) = \\sqrt{\\frac{\u0394}{2\u03c0 n}}\\sum_{t=0}^{n-1} \\boldsymbol{P}_{t\u0394}e^{-it\u0394 \u03c9}\n```\n\nNote the periodogram is in terms of angular frequency here, and uses the normalisation ``\u0394/2\u03c0``.\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    \u03a9::V\n    ordinates::Vector{T}\n    function Periodogram(timeseries::Matrix{T}, \u0394::Real) where {T}\n        \u0394 > 0 || throw(ArgumentError(\"\u0394 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, :]'.*(\u0394 / (2\u03c0 * n))) for ii \u2208 1:size(J,1)]\n        \u03a9 = fftshift(fftfreq(n, 2\u03c0/\u0394))\n        new{D, eltype(ordinates), typeof(\u03a9)}(\u03a9, ordinates)\n    end\n    function Periodogram(timeseries::Vector{T}, \u0394::Real) where {T}\n        \u0394 > 0 || throw(ArgumentError(\"\u0394 should be a positive.\"))\n        J = fftshift(fft(timeseries, 1),1)\n        n = size(J,1)\n        ordinates = abs.(J.^2).*(\u0394 / (2\u03c0 * n))\n        \u03a9 = fftshift(fftfreq(n, 2\u03c0/\u0394))\n        new{1, eltype(ordinates), typeof(\u03a9)}(\u03a9, ordinates)\n    end\n    function Periodogram(\u03a9, ordinates::Vector{T}) where {T}\n        new{size(ordinates[1],1), T, typeof(\u03a9)}(\u03a9, ordinates)\n    end\nend\n\n@doc raw\"\"\"\n    BartlettPeriodogram(timeseries, \u0394, segmentlength)\n\nCompute the Bartlett periodogram for the provided timeseries with sampling rate \u0394.\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- `\u0394`: 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    \u03a9::V\n    ordinates::Vector{T}\n    function BartlettPeriodogram(timeseries::Matrix{T}, \u0394::Real, segmentlength::Int = Int(100\u00f7\u0394)) where {T}\n        nsegments = size(timeseries, 1) \u00f7 segmentlength\n        P = Periodogram(timeseries[1:segmentlength, :], \u0394)\n        \n        for ii = 1:nsegments-1\n            P += Periodogram(timeseries[segmentlength*ii.+(1:segmentlength), :], \u0394)\n        end\n        \n        BartlettPeriodogram(P/nsegments)\n    end\n    function BartlettPeriodogram(timeseries::Vector{T}, \u0394::Real, segmentlength::Int = Int(100\u00f7\u0394)) where {T}\n        nsegments = size(timeseries, 1) \u00f7 segmentlength\n        P = Periodogram(timeseries[1:segmentlength], \u0394)\n        \n        for ii = 1:nsegments-1\n            P += Periodogram(timeseries[segmentlength*ii.+(1:segmentlength)], \u0394)\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.\u03a9)}(p.\u03a9, p.ordinates)\n    end\n    function BartlettPeriodogram(\u03a9, ordinates::Vector{T}) where {T}\n        new{size(ordinates[1],1), T, typeof(\u03a9)}(\u03a9, ordinates)\n    end\nend\n\nstruct CoherancyEstimate{D,T,V} <: SpectralEstimate{D,T}\n    \u03a9::V\n    ordinates::Vector{T}\n\n    function CoherancyEstimate(timeseries::Matrix{T}, \u0394::Real, segmentlength::Int = Int(100\u00f7\u0394)) where {T}\n        S = BartlettPeriodogram(timeseries, \u0394, 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 \u2208 1:D, j \u2208 1:D] for s \u2208 S.ordinates]\n        new{D,eltype(newordinates),typeof(S.\u03a9)}(S.\u03a9, newordinates)\n    end\n\n    function CoherancyEstimate(\u03a9, ordinates::Vector{T}) where {T}\n        new{size(ordinates[1],1), T, typeof(\u03a9)}(\u03a9, ordinates)\n    end\nend\n\nndims(::SpectralEstimate{D,T}) where {D,T} = D\nsize(s\u0302::SpectralEstimate) = (length(getfreq(s\u0302)),)\ngetindex(s\u0302::T, inds) where {T<:SpectralEstimate} = getconstructor(T)(getfreq(s\u0302)[inds], getordinate(s\u0302)[inds])\ngetindex(s\u0302::SpectralEstimate, ind::Int) = (getfreq(s\u0302)[ind],getordinate(s\u0302)[ind])\nlog10(s\u0302::T) where {T<:SpectralEstimate} = getconstructor(T)(getfreq(s\u0302), log10.(getordinate(s\u0302)))\ngetfreq(p::Periodogram) = p.\u03a9\ngetfreq(b::BartlettPeriodogram) = b.\u03a9\ngetfreq(c::CoherancyEstimate) = c.\u03a9\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\u0302::SpectralEstimate)\n    HermitianPlot(getfreq(s\u0302), getordinate(s\u0302))\nend\n\n@recipe function f(s\u0302::SpectralEstimate{1,T}) where {T} # univariate plotting\n    getfreq(s\u0302), getordinate(s\u0302)\nend\n\nfunction Base.:+(s\u0302\u2081::T, s\u0302\u2082::T) where {T<:SpectralEstimate}\n    getfreq(s\u0302\u2081) == getfreq(s\u0302\u2082) || error(\"Frequencies must be the same to add spectral estimates.\")\n    getconstructor(T)(getfreq(s\u0302\u2081), getordinate(s\u0302\u2081) .+ getordinate(s\u0302\u2082))\nend\n\nfunction Base.:/(s\u0302::T, a::Real) where {T<:SpectralEstimate}\n    getconstructor(T)(getfreq(s\u0302), getordinate(s\u0302)./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": "#=\nAgent dynamics in the lake model\n=#\n\nusing QuantEcon\nusing Plots\npyplot()\ninclude(\"lake_model.jl\")\n\nsrand(42)\nlm = LakeModel(d=0, b=0)\nT = 5000     # Simulation length\n\nalpha, lambda = lm.alpha, lm.lambda\nP = [(1 - lambda) lambda; alpha (1 - alpha)]\n\nmc = MarkovChain(P, [0; 1])     # 0=unemployed, 1=employed\nxbar = rate_steady_state(lm)\n\ns_path = simulate(mc, T; init=2)\ns_bar_e = cumsum(s_path) ./ (1:T)\ns_bar_u = 1 - s_bar_e\ns_bars = [s_bar_u s_bar_e]\n\ntitles = [\"Proportion of time unemployed\" \"Proportion of time employed\"]\ndates = collect(1:T)\n\nplot(dates, s_bars, layout=(2, 1), title=titles, legend=:none)\nhline!(reverse(xbar)', layout=(2, 1), color=:red, linestyle=:dash)\n", "meta": {"hexsha": "b5a3219e6874ca40376361a3b2d410503290bcbe", "size": 685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lake_model/lake_agent_dynamics.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": "lake_model/lake_agent_dynamics.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": "lake_model/lake_agent_dynamics.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": 22.8333333333, "max_line_length": 72, "alphanum_fraction": 0.6802919708, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7532915084517738}}
{"text": "# Returns a partitioning of `range` into sub-ranges of length `partition_size`.\n# If `range` is not divisible by `partition_size`, the last sub-range will be\n# of length `range` mod `partition_size`.\nfunction partition_range(range::UnitRange, partition_size::Int)\n    n_partitions = ceil(Int, last(range) / partition_size)\n    partitions = Vector{UnitRange{Int}}(undef, n_partitions)\n\n    for p in 1:n_partitions\n        l::Int = first(range) + (p-1) * partition_size\n        r::Int = min(l - 1 + partition_size, last(range))\n        partitions[p] = l:r\n    end\n\n    return partitions\nend\n\nfunction calculate_sample_weights(targets::T) where {T <: AbstractVector}\n    t = targets\n    N = length(t)\n    \u03c8\u2080 = sum(t .!= 1) / N\n    \u03c8\u2081 = sum(t .== 1) / N\n    \u03c8 = [q == 1 ? \u03c8\u2081 : \u03c8\u2080 for q in t]\nend\n\nfunction gaussian_projection_matrix(::Type{T},\n                                    n_neurons::Int,\n                                    n_features::Int) where {T <: Number}\n    randn(T, n_neurons, n_features) ./ sqrt(n_features)\nend\n\nfunction project(samples::T\u2081,\n                 weights::T\u2082,\n                 activation_functions::Vector{T\u2083}) where {T\u2081 <: AbstractMatrix,\n                                                          T\u2082 <: AbstractMatrix,\n                                                          T\u2083 <: ActivationFunction}\n    X = samples\n    W = weights\n    fs = activation_functions\n    L = length(fs)\n\n    H = W * X\n    for l in 1:L\n        H[l,:] .= fs[l].(H[l,:])\n    end\n\n    H\nend\n", "meta": {"hexsha": "fc5ae2d8d1c5c3b8368abf6609b79a4994382126", "size": 1495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/common.jl", "max_stars_repo_name": "rjww/AdvancedTopics.jl", "max_stars_repo_head_hexsha": "76207f6b17d37129324c671c4f3e4da5bd5704dd", "max_stars_repo_licenses": ["MIT"], "max_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": "rjww/AdvancedTopics.jl", "max_issues_repo_head_hexsha": "76207f6b17d37129324c671c4f3e4da5bd5704dd", "max_issues_repo_licenses": ["MIT"], "max_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": "rjww/AdvancedTopics.jl", "max_forks_repo_head_hexsha": "76207f6b17d37129324c671c4f3e4da5bd5704dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-07T02:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:20:11.000Z", "avg_line_length": 31.1458333333, "max_line_length": 83, "alphanum_fraction": 0.5511705686, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.8244619177503206, "lm_q1q2_score": 0.7532915064489206}}
{"text": "using PkgSRA, Test, Random\nRandom.seed!(13)\n\n###\n### First, Lorenz\n###\ninclude(\"../examples/example_lorenz.jl\")\ndat = Array(solve_lorenz_system())\ntrue_grad = core_dyn_true(dat)\n\n# Numerical derivative: the main function to be tested\nnumerical_grad = numerical_derivative(dat, ts)\n\n# Basic\n@test !isempty(numerical_grad)\n@test size(numerical_grad) == size(true_grad)\n\n# Accuracy\n@test isapprox(numerical_grad, true_grad, rtol=1e-2)\n@test !isapprox(numerical_grad, true_grad, rtol=1e-3)\n\n\n###\n### Second, SIR\n###\ninclude(\"../examples/example_sir.jl\")\ndat = Array(solve_sir_system())\ntrue_grad = core_dyn_true(dat)\n\n# Numerical derivative: the main function to be tested\nnumerical_grad = numerical_derivative(dat, ts)\n\n# Basic\n@test !isempty(numerical_grad)\n@test size(numerical_grad) == size(true_grad)\n\n# Accuracy\n@test isapprox(numerical_grad, true_grad, rtol=1e-2)\n@test !isapprox(numerical_grad, true_grad, rtol=1e-3)\n\n# Check why the above doesn't work...\nplot(numerical_grad[1,:], label=\"numerical\");\n    plot!(true_grad[1,:], label=\"true\")\n\ndt = ts[2] - ts[1]\nbad_grad = (dat[:,2:end] .- dat[:,1:end-1]) / dt\nplot(ts, numerical_grad[1,:], label=\"numerical\");\n    plot!(ts, bad_grad[1,:], label=\"one-step\")\n    plot!(ts, true_grad[1,:], label=\"true\")\n", "meta": {"hexsha": "36a8c070ff9234551035d2c00f652441c8ddb70f", "size": 1256, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/deriv_test.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": "test/deriv_test.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": "test/deriv_test.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.12, "max_line_length": 54, "alphanum_fraction": 0.7125796178, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7532830127846688}}
{"text": "using JuMP, AmplNLWriter, MathOptInterfaceToMathProgBase, Test, Ipopt\nusing Random, Statistics, Test\n\nconst MOI = JuMP.MOI\n\nmodel = JuMP.Model(\n    with_optimizer(\n        MathOptInterfaceToMathProgBase.Optimizer,\n        solver = AmplNLWriter.AmplNLSolver(Ipopt.amplexe)\n    )\n)\n\nN = 1000\nh = 1/N\nalpha = 350\n\n@variables(model, begin\n    -1 <= t[1:(N + 1)] <= 1\n    -0.05 <= x[1:(N + 1)] <= 0.05\n    u[1:(N + 1)]\nend)\n@NLobjective(model, Min, sum(0.5 * h * (u[i + 1]^2 + u[i]^2) +\n    0.5 * alpha * h * (cos(t[i + 1]) + cos(t[i])) for i in 1:N)\n)\n@NLconstraint(model, [i = 1:N],\n    x[i + 1] - x[i] - 0.5 * h * (sin(t[i + 1]) + sin(t[i])) == 0\n)\n@constraint(model, [i = 1:N],\n    t[i + 1] - t[i] - 0.5 * h * u[i + 1] - 0.5 * h * u[i] == 0\n)\nJuMP.optimize!(model)\n\n@test JuMP.termination_status(model) == MOI.OPTIMAL\n@test JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n@test JuMP.objective_value(model) \u2248 350.0\n\nfunction example_mle(; verbose = true)\n    n = 1_000\n    Random.seed!(1234)\n    data = randn(n)\n\n    model = JuMP.Model(\n        with_optimizer(\n            MathOptInterfaceToMathProgBase.Optimizer,\n            solver = AmplNLWriter.AmplNLSolver(Ipopt.amplexe)\n        )\n    )\n\n    @variable(model, \u03bc, start = 0.0)\n    @variable(model, \u03c3 >= 0.0, start = 1.0)\n    @NLobjective(model, Max, n / 2 * log(1 / (2 * \u03c0 * \u03c3^2)) -\n        sum((data[i] - \u03bc)^2 for i in 1:n) / (2 * \u03c3^2)\n    )\n    JuMP.optimize!(model)\n    if verbose\n        println(\"\u03bc = \", JuMP.value(\u03bc))\n        println(\"mean(data) = \", mean(data))\n        println(\"\u03c3^2 = \", JuMP.value(\u03c3)^2)\n        println(\"var(data) = \", var(data))\n        println(\"MLE objective: \", JuMP.objective_value(m))\n    end\n    @test JuMP.value(\u03bc) \u2248 mean(data) atol = 1e-3\n    @test JuMP.value(\u03c3)^2 \u2248 var(data) atol = 1e-2\n\n    # constrained MLE?\n    @NLconstraint(model, \u03bc == \u03c3^2)\n\n    JuMP.optimize!(model)\n    if verbose\n        println(\"\\nWith constraint \u03bc == \u03c3^2:\")\n        println(\"\u03bc = \", JuMP.value(\u03bc))\n        println(\"\u03c3^2 = \", JuMP.value(\u03c3)^2)\n        println(\"Constrained MLE objective: \", JuMP.objective_value(model))\n    end\n    @test JuMP.value(\u03bc) \u2248 JuMP.value(\u03c3)^2\nend\n\nexample_mle(verbose = false)\n", "meta": {"hexsha": "7ee17522bb5745b3b3fd42f4391d3e47acdaa477", "size": 2163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/AmplNLWriter_test.jl", "max_stars_repo_name": "odow/MathOptInterfaceToMathProgBase.jl", "max_stars_repo_head_hexsha": "42c837d79abace0ed1f34f437983e41273111ebf", "max_stars_repo_licenses": ["MIT"], "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/AmplNLWriter_test.jl", "max_issues_repo_name": "odow/MathOptInterfaceToMathProgBase.jl", "max_issues_repo_head_hexsha": "42c837d79abace0ed1f34f437983e41273111ebf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-10T20:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-10T20:01:30.000Z", "max_forks_repo_path": "test/AmplNLWriter_test.jl", "max_forks_repo_name": "odow/MathOptInterfaceToMathProgBase.jl", "max_forks_repo_head_hexsha": "42c837d79abace0ed1f34f437983e41273111ebf", "max_forks_repo_licenses": ["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.3797468354, "max_line_length": 75, "alphanum_fraction": 0.5714285714, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7532830088944208}}
{"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+\u2026Z+\u27e9\nZp = MPS(i, \"Z+\")\n\n# Product state |Z-Z-Z-\u2026Z-\u27e9\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) / \u221a2\n#\n# Performs a truncated MPS addition,\n# returns an MPS approximate up to some tolerance.\nCat = (Zp + Zm) * (1 / \u221a2)\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 \u00f7 2\nX\u2c7c = op(\"X\", i[j])\nX\u2c7cZp = apply(X\u2c7c, Zp)\n\nX\u2c7cZp = MPS(i, [k == j ? \"Z-\" : \"Z+\" for k in 1:n])\n@show inner(X\u2c7cZp, apply(X\u2c7c, 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(\u03c8)\n  \u03c8H\u03c8 = inner(\u03c8', H, \u03c8)\n  \u03c8\u03c8 = inner(\u03c8, \u03c8)\n  return \u03c8H\u03c8 / \u03c8\u03c8\nend\n\nfunction minimize(f, \u2202f, x; nsteps, \u03b3, kwargs...)\n  for n in 1:nsteps\n    println(\"n = \", n, \", f_x = \", f(x))\n    x = -(x, \u03b3 * \u2202f(x); kwargs...)\n  end\n  return x\nend\n\n\u03c8\u2070 = MPS(i, \"Z+\")\n\u2202E(x) = gradient(E, x)[1]\n\u03c8 = minimize(E, \u2202E, \u03c8\u2070; nsteps=50, \u03b3=0.1, maxdim=10, cutoff=1e-5)\n\n# TODO: change to:\n# \u03c8 /= norm(\u03c8)\n\u03c8 *= inv(norm(\u03c8))\n\nE\u1d48\u1d50\u02b3\u1d4d, \u03c8\u1d48\u1d50\u02b3\u1d4d = dmrg(H, \u03c8\u2070; nsweeps=10, maxdim=10, cutoff=1e-5)\n\n@show maxlinkdim(\u03c8\u2070)\n@show maxlinkdim(\u03c8)\n@show maxlinkdim(\u03c8\u1d48\u1d50\u02b3\u1d4d)\n@show E(\u03c8\u2070), norm(\u2202E(\u03c8\u2070))\n@show E(\u03c8), norm(\u2202E(\u03c8))\n@show E(\u03c8\u1d48\u1d50\u02b3\u1d4d), norm(\u2202E(\u03c8\u1d48\u1d50\u02b3\u1d4d))\n\n#\n# Circuit optimization\n#\n\n# Form the circuit from parameters\nRy_layer(\u03b8, i) = [op(\"Ry\", i[j]; \u03b8=\u03b8[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(\u03b8, i; nlayers)\n  n = length(i)\n  U\u1dbf = Ry_layer(\u03b8[1:n], i)\n  for l in 1:(nlayers - 1)\n    U\u1dbf = [U\u1dbf; CX_layer(i)]\n    U\u1dbf = [U\u1dbf; Ry_layer(\u03b8[(1:n) .+ l * n], i)]\n  end\n  return U\u1dbf\nend\n\nnlayers = 6\nmaxdim = 10\ncutoff = 1e-5\n\n# Find the circuit `U(\u03b8)` that minimizes:\n# E(\u03b8) = \u27e80|U(\u03b8)\u2020 H U(\u03b8)|0\u27e9 = \u27e8\u03b8|H|\u03b8\u27e9\nfunction E(\u03b8)\n  # Apply the circuit:\n  # |\u03b8\u27e9 = U(\u03b8)|0\u27e9\n  \u03c8\u1dbf = apply(U(\u03b8, i; nlayers=nlayers), \u03c8\u2070; maxdim=maxdim, cutoff=cutoff)\n\n  # Compute the expecation value: \u27e8\u03b8|H|\u03b8\u27e9\n  # No need to normalize!\n  return inner(\u03c8\u1dbf', H, \u03c8\u1dbf)\nend\n\nprintln()\nprintln(\"Circuit optimization\")\n\u03b8\u2070 = zeros(nlayers * n)\n\u2202E(\u03c8) = gradient(E, \u03c8)[1]\n\u03b8 = minimize(E, \u2202E, \u03b8\u2070; nsteps=20, \u03b3=0.1)\n\n\u03c8\u1dbf = apply(U(\u03b8, i; nlayers=nlayers), \u03c8\u2070; maxdim=maxdim, cutoff=cutoff)\n\n@show maxlinkdim(\u03c8\u2070)\n@show maxlinkdim(\u03c8\u1dbf)\n@show E(\u03b8\u2070), norm(\u2202E(\u03b8\u2070))\n@show E(\u03b8), norm(\u2202E(\u03b8))\n\n# TODO: Finish this implementation\n# Example of preparing the ground state\n# Find `U(\u03b8)` that minimizes\n#\n# F(\u03b8) = -|\u27e8\u03c8|U(\u03b8)|0\u27e9|\u00b2\nfunction F(\u03b8)\n  # Apply the circuit:\n  # |\u03b8\u27e9 = U(\u03b8)|0\u27e9\n  \u03c8\u1dbf = apply(U(\u03b8, i; nlayers=nlayers), \u03c8\u2070; maxdim=maxdim, cutoff=cutoff)\n\n  # -|\u27e8\u03c8|\u03b8\u27e9|\u00b2\n  return -abs(inner(\u03c8, \u03c8\u1dbf))^2\nend\n\nprintln()\nprintln(\"State preparation\")\n\u03b8\u2070 = zeros(nlayers * n)\n\u2202F(\u03c8) = gradient(F, \u03c8)[1]\n\u03b8 = minimize(F, \u2202F, \u03b8\u2070; nsteps=20, \u03b3=0.1)\n\n\u03c8\u1dbf = apply(U(\u03b8, i; nlayers=nlayers), \u03c8\u2070; maxdim=maxdim, cutoff=cutoff)\n\n@show maxlinkdim(\u03c8\u2070)\n@show maxlinkdim(\u03c8\u1dbf)\n@show F(\u03b8\u2070), norm(\u2202F(\u03b8\u2070))\n@show F(\u03b8), norm(\u2202F(\u03b8))\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\u03c0 * x)  + 1\ng(x) = cos(2\u03c0 * 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\u03c0 * xi) - cos(2\u03c0 * xf)) / (2\u03c0) + (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(\u1d5b(x))(constant)\n    y = Variable{T}(\u1d5b(x) .+ C, x.backprop)\n    if x.backprop\n        function matAddScalarBackward()\n            if need2compute\u03b4!(x)\n                \u03b4(x) .+= \u03b4(y)\n            end\n            ifNotKeep\u03b4ThenFree\u03b4!(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(\u1d5b(x))(constant)\n    y = Variable{T}(\u1d5b(x) .- C, x.backprop)\n    if x.backprop\n        function matMinusScalarBackward()\n            if need2compute\u03b4!(x)\n                \u03b4(x) .+= \u03b4(y)\n            end\n            ifNotKeep\u03b4ThenFree\u03b4!(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(\u1d5b(x))(constant)\n    y = Variable{T}(C .- \u1d5b(x), x.backprop)\n    if x.backprop\n        function scalarMinusMatBackward()\n            if need2compute\u03b4!(x)\n                \u03b4(x) .-= \u03b4(y)\n            end\n            ifNotKeep\u03b4ThenFree\u03b4!(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(\u1d5b(x))(constant)\n    y = Variable{T}(\u1d5b(x) .* C, x.backprop)\n    if x.backprop\n        function matMulScalarBackward()\n            if need2compute\u03b4!(x)\n                \u03b4(x) .+= \u03b4(y) .* constant\n            end\n            ifNotKeep\u03b4ThenFree\u03b4!(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    # \u77e9\u9635\u3001\u5217\u5411\u91cf\u4e0e\u5e38\u6570\u6309\u5143\u7d20\u505a\u5e42\u6307\u6570\u8fd0\u7b97\n    n = eltype(\u1d5b(x))(n)\n    y = Variable{T}(\u1d5b(x) .^ n, x.backprop)\n    if x.backprop\n        function powerBackward()\n            if need2compute\u03b4!(x)\n                \u03b4(x) .+= n .* \u1d5b(y) ./ \u1d5b(x) .* \u03b4(y);\n            end\n            ifNotKeep\u03b4ThenFree\u03b4!(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}(\u1d5b(x) + \u1d5b(y), backprop)\n   if backprop\n       function add2varBackward()\n           if need2compute\u03b4!(x) \u03b4(x) .+= \u03b4(z) end\n           if need2compute\u03b4!(y) \u03b4(y) .+= \u03b4(z) end\n           ifNotKeep\u03b4ThenFree\u03b4!(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}(\u1d5b(x) - \u1d5b(y), backprop)\n    if backprop\n        function minus2varBackward()\n            if need2compute\u03b4!(x) \u03b4(x) .+= \u03b4(z) end\n            if need2compute\u03b4!(y) \u03b4(y) .-= \u03b4(z) end\n            ifNotKeep\u03b4ThenFree\u03b4!(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}(\u1d5b(x) .+ \u1d5b(y), backprop)\n    if backprop\n        function dotAddBackward()\n            if need2compute\u03b4!(x) \u03b4(x) .+= \u03b4(z) end\n            if need2compute\u03b4!(y) \u03b4(y) .+= \u03b4(z) end\n            ifNotKeep\u03b4ThenFree\u03b4!(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}(\u1d5b(x) .* \u1d5b(y), backprop)\n    if backprop\n        function dotMulBackward()\n            if need2compute\u03b4!(x) \u03b4(x) .+= \u03b4(z) .* \u1d5b(y) end\n            if need2compute\u03b4!(y) \u03b4(y) .+= \u03b4(z) .* \u1d5b(x) end\n            ifNotKeep\u03b4ThenFree\u03b4!(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    # \u77e9\u9635\u76f8\u4e58 Y[i,j] = sum(W[i,k]*X[k,j],k=...)\n    # W -- \u6743\u91cd\u77e9\u9635\n    # X -- n\u4e2a\u8f93\u5165\u5217\u5411\u91cf\u7ec4\u6210\u7684\u77e9\u9635\n    # Y -- n\u4e2a\u8f93\u51fa\u5217\u5411\u91cf\u7ec4\u6210\u7684\u77e9\u9635\n    @assert T1 <: T2 || T1 >: T2\n    T = T1 <: T2 ? T1 : T2\n    backprop = (W.backprop || X.backprop)\n    Y = Variable{T}(\u1d5b(W) * \u1d5b(X), backprop)\n    if backprop\n        function matMulBackward()\n            if need2compute\u03b4!(W) \u03b4(W) .+= \u03b4(Y)  * \u1d5b(X)' end\n            if need2compute\u03b4!(X) \u03b4(X) .+= \u1d5b(W)' * \u03b4(Y)  end\n            ifNotKeep\u03b4ThenFree\u03b4!(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 -- \u5145\u5f53\u548c\u8282\u70b9\uff0c\u975e\u5b66\u4e60\u7684\u53c2\u6570\n    # V -- \u504f\u7f6e\u5217\u5411\u91cf\uff0c\u8981\u5b66\u4e60\u7684\u53c2\u6570\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}(\u1d5b(M) .+ \u1d5b(V), backprop)\n    if backprop\n        function matAddVecBackward()\n            if need2compute\u03b4!(M)\n                \u03b4(M) .+= \u03b4(Z)\n            end\n            if need2compute\u03b4!(V)\n                \u03b4(V) .+= sum(\u03b4(Z), dims=2)\n            end\n            ifNotKeep\u03b4ThenFree\u03b4!(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 -- \u4e00\u822c\u5145\u5f53\u6fc0\u6d3b\u8282\u70b9\uff0c\u975e\u7f51\u7edc\u9700\u8981\u5b66\u4e60\u7684\u53c2\u6570\n    # V -- \u5217\u5411\u91cf\uff0c\u5faa\u73af\u6743\u91cd\uff0c\u662f\u7f51\u7edc\u9700\u8981\u5b66\u4e60\u7684\u53c2\u6570\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}(\u1d5b(M) .* \u1d5b(V), backprop)\n    if backprop\n        function matMulVecBackward()\n            if need2compute\u03b4!(M) \u03b4(M) .+=     \u03b4(Z) .* \u1d5b(V)          end\n            if need2compute\u03b4!(V) \u03b4(V) .+= sum(\u03b4(Z) .* \u1d5b(M), dims=2) end\n            ifNotKeep\u03b4ThenFree\u03b4!(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(\u03b8, u)\n    X = ae(u, config, \u03b8) + 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 - \u03c6\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\u03c6 = @. (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\u03c6 = \u03c6[2:end-1]\n\u03b8 = 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, \u03b8, u0)\nX_pred = ae(collect(LinRange(0.0,0.25,100)), config, \u03b8) + 1.0\n\nsess = Session(); init(sess)\nBFGS!(sess, loss, grad, \u03b8)\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 \u03b8,\u03c8,\u03b4,\u03b3_n,\u03b3_z,\u03c1,\u03b2_hat = md\n\n    f(x::Vector) = log((x[1]^\u03b8)*((exp(x[2])*x[5])^(1-\u03b8))-(1+\u03b3_n)*(1+\u03b3_z)*x[4]+(1-\u03b4)*x[1])+\u03c8*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 \u03c1 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(\u03b2_hat)*(A-B*(R\\W'));\n    B_tld = sqrt(\u03b2_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": "using CSV\r\nusing Plots\r\nusing StatPlots\r\nusing DataFrames\r\nusing GLM\r\n\r\ngr()\r\ncd(raw\"D:\\workspace\\github\\blog-py\\blog\\static\\essay_resources\\Notes_on_Computer_Age_Statistical_Inference\") \r\n\r\nkidney = CSV.read(\"kidney.csv\", nullable=false)\r\n@df kidney scatter(:age, :Tot)\r\n\r\nX = hcat(ones(nrow(kidney)), kidney[:age])\r\ny = kidney[:Tot]\r\nOLS = fit(LinearModel, X, y)\r\n# GLM.LinearModel{GLM.LmResp{Array{Float64,1}},GLM.DensePredChol{Float64,Base.LinAlg.Cholesky{Float64,Array{Float64,2}}}}:\r\n\r\n# Coefficients:\r\n#        Estimate Std.Error  t value Pr(>|t|)\r\n# x1      2.86067  0.359561  7.95603   <1e-12\r\n# x2   -0.0786009 0.0090557 -8.67972   <1e-14\r\n\r\nage_samples = collect(20:10:90)\r\nXtest = hcat(ones(length(age_samples)), age_samples)\r\npred = predict(OLS, Xtest, :confint)\r\n\r\nfor i in 1:size(pred, 1)\r\n    y_pred, y_lower, y_upper = pred[i, :]\r\n    display(plot!([age_samples[i],age_samples[i]], [ y_lower, y_upper], linewidth = 3))\r\nend\r\n\r\nplot!(age_samples[[1, end]], pred[[1, end], 1], legend=:none, linewidth=3)\r\nsavefig(\"Figure_1_1.png\")", "meta": {"hexsha": "004d19b2751e0dd632d925aadfed789d83747725", "size": 1045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/essays/Notes_on_Computer_Age_Statistical_Inference/script.jl", "max_stars_repo_name": "findmyway/TianJun.jl", "max_stars_repo_head_hexsha": "4d833669ea0948cf700f8cfc9783b7764ff522a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-08-13T16:09:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T16:58:37.000Z", "max_issues_repo_path": "docs/src/essays/Notes_on_Computer_Age_Statistical_Inference/script.jl", "max_issues_repo_name": "findmyway/TianJun.jl", "max_issues_repo_head_hexsha": "4d833669ea0948cf700f8cfc9783b7764ff522a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-17T03:11:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T04:28:43.000Z", "max_forks_repo_path": "docs/src/essays/Notes_on_Computer_Age_Statistical_Inference/script.jl", "max_forks_repo_name": "findmyway/TianJun.jl", "max_forks_repo_head_hexsha": "4d833669ea0948cf700f8cfc9783b7764ff522a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-25T03:37:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T03:37:35.000Z", "avg_line_length": 31.6666666667, "max_line_length": 123, "alphanum_fraction": 0.6832535885, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8006919925839876, "lm_q1q2_score": 0.7532828162780596}}
{"text": "module SpectralMethodsTrefethen\n\n# Analogs for named functions in the book.\nexport cheb, chebfft, clencurt, gauss\n\n# Required by the scripts, so must be in parent scope\neval(module_parent(current_module()),:(using PyPlot, Dierckx, Polynomials, LaTeXStrings, SpecialFunctions))\n\n# Required to define view() below\nusing PyPlot: gca\n\n# See if MATLAB is available/working.\nis_matlab_running = try\n    using MATLAB\n    true\ncatch exc\n    warn(\"MATLAB is not available. Continuing without MATLAB.\");\n    false\nend\n\n# Now see if it can find our files. We have to prevent the compiler from\n# dealing with the MATLAB package functions, if that was not loaded successfully.\nset_dir = quote\n    is_matlab_running = try\n        local d = joinpath(Pkg.dir(\"SpectralMethodsTrefethen\"),\"matlab\");\n        eval_string(\"mfiledir = cd('$d');\");\n        @mget mfiledir;\n        # At some point MATLAB started warning for 2D 'cubic' interp.\n        eval_string(\"warning off MATLAB:griddedInterpolant:CubicUniformOnlyWarnId\");\n        true\n    catch\n        warn(\"MATLAB cannot find package files. Continuing without MATLAB.\");\n        false\n    end\nend;\n\nif is_matlab_running\n    eval(set_dir)\nend\n\n## Analogs of functions from the book.\n\n\"\"\"\n    cheb(N)\n\nChebyshev differentiation matrix and grid.\n\"\"\"\nfunction cheb(N)\n    N==0 && return 0,1;\n    x = [ cos(pi*k/N) for k=0:N ];\n    c = [2;ones(N-1);2] .* (-1).^(0:N);\n    dX = x .- x';\n    D  = (c*(1./c)') ./ (dX+eye(N+1));      # off-diagonal entries\n    D  = D - diagm(squeeze(sum(D,2),2));    # diagonal entries\n    return D,x\nend\n\n\n\"\"\"\n    chebfft(v)\n\nDifferentiate values given at Chebyshev points via the FFT.\n\"\"\"\nfunction chebfft(v)\n    # Simple, not optimal. If v is complex, delete \"real\" commands.\n    N = length(v)-1;\n    N==0 && return 0;\n    x = [ cos(pi*k/N) for k=0:N ];\n    ii = collect(0:N-1);\n    V = [v; flipdim(v[2:N],1)];              # transform x -> theta\n    U = real(fft(V));\n    W = real(ifft(1im*[ii;0;1-N:-1].*U));\n    w = zeros(N+1);\n    w[2:N] = -W[2:N]./sqrt.(1-x[2:N].^2);    # transform theta -> x\n    w[1] = sum(ii.^2.*U[ii+1])/N + .5*N*U[N+1];\n    w[N+1] = sum((-1).^(ii+1).*ii.^2.*U[ii+1])/N + .5*(-1)^(N+1)*N*U[N+1];\n    return w\nend\n\n\"\"\"\n    clencurt(N)\n\nNodes and weights for Clenshaw-Curtis quadrature\n\"\"\"\nfunction clencurt(N)\n    \u03b8 = [ pi*i/N for i=0:N ];\n    x = cos.(\u03b8);\n    w = zeros(N+1);\n    ii = 2:N;\n    v = ones(N-1);\n    if mod(N,2)==0\n        w[1] = w[N+1] = 1/(N^2-1);\n        for k = 1:N/2-1\n            v = v - 2*cos.(2*k*\u03b8[ii]) / (4*k^2-1);\n        end\n        v = v - cos.(N*\u03b8[ii]) / (N^2-1);\n    else\n        w[1] = w[N+1] = 1/N^2;\n        for k = 1:(N-1)/2\n            v = v - 2*cos.(2*k*\u03b8[ii]) / (4*k^2-1);\n        end\n    end\n    w[ii] = 2*v/N;\n    return x,w\nend\n\n\"\"\"\n    gauss(N)\n\nNodes and weights for Gauss quadrature\n\"\"\"\nfunction gauss(N)\n    \u03b2 = [ .5/sqrt(1-1/(2*i)^2) for i = 1:N-1 ];\n    T = diagm(\u03b2,1) + diagm(\u03b2,-1);\n    (x,V) = eig(T);\n    i = sortperm(x);\n    w = 2*V[1,i].^2;\n    return x[i],w\nend\n\n## Stand-ins for native functions in MATLAB.\nimport Base.view\nexport toeplitz, view\n\"\"\"\n    toeplitz(col[,row])\n\nConstruct Toeplitz matrix from first column and first row. If the row is not\ngiven, the result is symmetric.\n\"\"\"\nfunction toeplitz(col,row=col)\n    m,n = length(col),length(row);\n    col[1]==row[1] || warn(\"Column wins conflict on the diagonal.\");\n    x = [ row[end:-1:2]; col ];\n    return [ x[i-j+n] for i=1:m, j=1:n ]\nend\n\n\"\"\"\n    view(az,el)\n\nSets the 3D viewing orientation azimuth and elevation (in degrees).\n\"\"\"\nfunction view(az::Real,el::Real)\n    gca()[:view_init](el,az-90);\nend\n\n## Create callable functions for each of the Julia scripts.\n\nexport p1, p2, p3, p4, p5, p6, p7, p8, p9, p10\nexport p11, p12, p13, p14, p15, p16, p17, p18, p19, p20\nexport p21, p22, p23, p24, p25, p26, p27, p28, p29, p30\nexport p31, p32, p33, p34, p35, p36, p37, p38, p39, p40\nexport p6u, p23a, p24fine, p28b, p30b, p30c\nfor (root, dirs, files) in walkdir(joinpath(Pkg.dir(\"SpectralMethodsTrefethen\"),\"src\",\"scripts\"))\n    for file in filter(x->endswith(x,\".jl\"),files)\n        basename = file[1:end-3];\n        fundef = quote\n            function $(Symbol(basename))(;julia=true,matlab=$is_matlab_running,source=false)\n                println(join([\"Running script \",$basename,\"...\"]));\n                if julia\n                    # Packages are needed in Main scope for include()\n                    println(\"Julia version:\");\n                    close(\"all\")\n                    tic(); include(joinpath($root,$file)); t=toc();\n                end\n                if matlab\n                    println(\"MATLAB version:\");\n                    eval_string(\"close all\");\n                    tic(); eval_string($basename); t=[t;toc()];\n                end\n                if source\n                    julia ? edit(joinpath($root,$file)) : nothing;\n                    matlab ? edit(joinpath($root,\"..\",\"..\",\"matlab\",$basename * \".m\")) : nothing;\n                end\n                return t\n\n            end\n        end\n        eval(fundef);\n    end\nend\n\nend\n", "meta": {"hexsha": "526648aa6fc4b67c5ac1310280afee46988ba838", "size": 5064, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SpectralMethodsTrefethen.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/SpectralMethodsTrefethen.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/SpectralMethodsTrefethen.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": 27.6721311475, "max_line_length": 107, "alphanum_fraction": 0.5600315956, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.7532617140172155}}
{"text": "\"\"\"\n    PGeneralizedGaussian(\u03b1, \u03bc, p)\n\nThe *p-Generalized Gaussian distribution*, more commonly known as the exponential\npower or the generalized normal distribution, with scale `\u03b1`, location `\u03bc`, 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 \u2192 \u221e`,\nthe distribution approaches the Uniform distribution on `[\u03bc-\u03b1, \u03bc+\u03b1]`.\n\n```julia\nPGeneralizedGaussian()           # GGD with shape 2, scale 1, location 0, (the Normal distribution)\nPGeneralizedGaussian(\u03b1, \u03bc, p)    # GGD with location \u03b1, scale \u03bc, and shape p\n\nparams(d)                       # Get the parameters, i.e. (\u03b1, \u03bc, p)\nshape(d)                        # Get the shape parameter, p\nscale(d)                        # Get the scale parameter, \u03b1\nlocation(d)                     # Get the location parameter, \u03bc\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    \u03bc::T1\n    \u03b1::T2\n    p::T3\n    PGeneralizedGaussian{T1,T2,T3}(\u03bc::T1,\u03b1::T2,p::T3) where {T1<:Real, T2<:Real, T3<:Real} = new{T1,T2,T3}(\u00b5, \u03b1, p)\nend\n\nfunction PGeneralizedGaussian(\u03bc::T1,\u03b1::T2,p::T3; check_args::Bool=true) where {T1<:Real, T2<:Real, T3<:Real}\n    check_args && @check_args(PGeneralizedGaussian, \u03b1 > zero(\u03b1) && p > zero(p))\n    return PGeneralizedGaussian{T1,T2,T3}(\u03bc,\u03b1,p)\nend\n\n\"\"\"\n    PGeneralizedGaussian(p)\n\nBuilds a p-generalized Gaussian with `\u03bc=0.0, \u03b1=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 `\u03bc=0.0, \u03b1=\u221a2, p=2.0`, corresponding\nto the normal distribution with `\u03bc=0.0, \u03c3=1.0`.\n\"\"\"\nPGeneralizedGaussian() = PGeneralizedGaussian(0.0, \u221a2, 2.0, check_args=false) # approximate scale with unity std deviation and shape 2\n\n#### Conversions\n\nconvert(::Type{PGeneralizedGaussian{T1,T2,T3}}, \u03bc::S1, \u03b1::S2, p::S3) where {T1 <: Real, T2 <: Real, T3 <:Real, S1 <: Real, S2 <: Real, S3 <: Real} = PGeneralizedGaussian(T1(\u03bc),T2(\u03b1),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.\u03bc), T2(d.\u03b1), 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.\u03bc, d.\u03b1, d.p)\nlocation(d::PGeneralizedGaussian) = d.\u03bc\nshape(d::PGeneralizedGaussian) = d.p\nscale(d::PGeneralizedGaussian) = d.\u03b1\n\n\n#### Statistics\n\nmean(d::PGeneralizedGaussian) = d.\u03bc\nmedian(d::PGeneralizedGaussian) = d.\u03bc\nmode(d::PGeneralizedGaussian) = d.\u03bc\n\nvar(d::PGeneralizedGaussian) = (d.\u03b1^2) * (gamma(3.0 * inv(d.p)) / gamma(inv(d.p)))\nstd(d::PGeneralizedGaussian) = (d.\u03b1) * 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.\u03b1 * gamma(inv(d.p))))\n\n\n#### Evaluation\n\nfunction pdf(d::PGeneralizedGaussian, x::Real)\n    (\u03bc, \u03b1, p) = params(d)\n    return ( p / ( 2.0 * \u03b1 * gamma(1 / p) ) ) * exp( -( abs(x - \u03bc) / \u03b1 )^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/\u0393(a) normalization.\n\"\"\"\nfunction cdf(d::PGeneralizedGaussian, x::Real)\n    (\u03bc, \u03b1, p) = params(d)\n    v = cdf(Gamma(inv(p), 1), (abs(x - \u03bc) / \u03b1)^p) * inv(2)\n    return typeof(v)(1/2) + sign(x - \u03bc) * 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\u00edguez-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.\u03bc + inv(sqrt(d.\u03b1)) * 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(\u03b8) = 1 + cos(\u03b8) * sin(\u03b8)^2\nPlots.plot(r, 0, 2\u03c0, proj=:polar, lims=(0,1.5))\n\nr(\u03b8) = 1 + cos(\u03b8) * sin(\u03b8)^2\n\u03b8 = range(0, stop=2\u03c0, length=50)\nPlots.plot(\u03b8, r.(\u03b8), proj=:polar, lims=(0,1.5), c=:steelblue,  linewidth=2)\n\n\n# Polar with markers\n\n\u0398 = range(0, stop = 2\u03c0, length = 100)\npr = abs.(0.1 * randn(100) + sin.(3\u0398))\nPlots.plot(\u0398, 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 * \u03c0 * 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 * \u03c0 * 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( (\u03c0 * 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": "# ---\n# title: 1491. Average Salary Excluding the Minimum and Maximum Salary\n# id: problem1491\n# author: zhwang\n# date: 2022-03-18\n# difficulty: Easy\n# categories: Array, Sort\n# link: <https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/description/>\n# hidden: true\n# ---\n# \n# Given an array of **unique** integers `salary` where `salary[i]` is the salary\n# of the employee `i`.\n# \n# Return the average salary of employees excluding the minimum and maximum\n# salary.\n# \n# \n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: salary = [4000,3000,1000,2000]\n#     Output: 2500.00000\n#     Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\n#     Average salary excluding minimum and maximum salary is (2000+3000)/2= 2500\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: salary = [1000,2000,3000]\n#     Output: 2000.00000\n#     Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\n#     Average salary excluding minimum and maximum salary is (2000)/1= 2000\n#     \n# \n# **Example 3:**\n# \n#     \n#     \n#     Input: salary = [6000,5000,4000,3000,2000,1000]\n#     Output: 3500.00000\n#     \n# \n# **Example 4:**\n# \n#     \n#     \n#     Input: salary = [8000,9000,2000,3000,6000,1000]\n#     Output: 4750.00000\n#     \n# \n# \n# \n# **Constraints:**\n# \n#   * `3 <= salary.length <= 100`\n#   * `10^3 <= salary[i] <= 10^6`\n#   * `salary[i]` is unique.\n#   * Answers within `10^-5` of the actual value will be accepted as correct.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction average_salary_excluding_mami(salary::Vector{Int})\n    return (sum(salary) - minimum(salary) - maximum(salary)) / (length(salary) - 2)\nend\n## @lc code=end\n", "meta": {"hexsha": "3a43d1babe7abb5020cdd15cd0edf379677eff8e", "size": 1711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/1491.average-salary-excluding-the-minimum-and-maximum-salary.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/1491.average-salary-excluding-the-minimum-and-maximum-salary.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/1491.average-salary-excluding-the-minimum-and-maximum-salary.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": 23.4383561644, "max_line_length": 108, "alphanum_fraction": 0.6282875511, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7532567114218184}}
{"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\u03c3  = 0.1;\r\nb_samp = repeat(b_e,1,nsamp)+\u03c3*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": "import RowEchelon\nimport LinearAlgebra\n\n#=\nHomework 7\nSection 3.2\nProblems 10\n=#\n\nA = [1 3 -1 0 -2 ;\n     0 2 -4 -1 -6 ;\n     -2 -6 2 3 9 ;\n     3 7 -3 8 -7 ;\n     3 5 5 2 7]\n\ndetA = LinearAlgebra.det(A)\n\nprintln(\"Original Matrix:\")\nprintln(A)\nprintln(\"Determinate:\")\nprintln(detA)\n", "meta": {"hexsha": "032158fcb818cbe0a5c6fcf944073fee30f4139d", "size": 282, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW7_S3.2_P10.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": "HW7_S3.2_P10.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": "HW7_S3.2_P10.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": 12.8181818182, "max_line_length": 27, "alphanum_fraction": 0.5957446809, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7532475238691737}}
{"text": "function draw_wireframe_sphere(pos, r; npts=11, color=(255,255,255), name=nothing, opacity=1.)\n    \u03d5s = range(0, stop=2\u03c0, length=npts)\n    \u03b8s = range(-\u03c0/2, stop=\u03c0/2, length=npts)\n    # vertical\n    v_xs = [[r * cos(\u03b8) * sin(\u03d5) + pos[1] for \u03b8 in \u03b8s] for \u03d5 in \u03d5s[1:end-1]]\n    v_ys = [[r * cos(\u03b8) * cos(\u03d5) + pos[2] for \u03b8 in \u03b8s] for \u03d5 in \u03d5s[1:end-1]]\n    v_zs = [[r * sin(\u03b8) + pos[3] for \u03b8 in \u03b8s] for \u03d5 in \u03d5s[1:end-1]]\n    # horizontal\n    h_xs = [[r * cos(\u03b8) * sin(\u03d5) + pos[1] for \u03d5 in \u03d5s] for \u03b8 in \u03b8s]\n    h_ys = [[r * cos(\u03b8) * cos(\u03d5) + pos[2] for \u03d5 in \u03d5s] for \u03b8 in \u03b8s]\n    h_zs = [[r * sin(\u03b8) + pos[3] for \u03d5 in \u03d5s] for \u03b8 in \u03b8s] \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": "n = rand(1:10)\n\nA = rand(n,n)\n\nr = polarfact(A, alg = :newton);\n\n# Test unitary matrix U\n\nU = r.U\nH = r.H\n\n@test_approx_eq_eps U'*U eye(n) 1e-7\n\n# Test Hermitian positive semifefinite matrix H\n\n@test issym(H)\n \nfor i in eigvals(H)\n    @test i >= 0.\nend\n\n@test_approx_eq A U*H\n\nprintln(\"Newton method passed test...\")\n", "meta": {"hexsha": "a38a24f1e3a6846b0ebc76165e10b728ff864e44", "size": 317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_newton.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_stars_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_stars_repo_licenses": ["MIT"], "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_newton.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_issues_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_issues_repo_licenses": ["MIT"], "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_newton.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_forks_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_forks_repo_licenses": ["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.68, "max_line_length": 47, "alphanum_fraction": 0.6466876972, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7532153746427279}}
{"text": "# Test script to test solver for a qp\n\nusing Test\nusing COSMO, SparseArrays, LinearAlgebra\n\n# Quadratic program example from OSQP Doc\n# min 0.5 * x'Px +  q'x\n# s.t. l <= Ax <= u\nq = [1; 1.]\nP = sparse([4. 1; 1 2])\nA = [1. 1; 1 0; 0 1]\nl = [1.; 0; 0]\nu = [1; 0.7; 0.7]\n\n# Define the constraint l <= Ax <= u with the help of a Nonnegatives set\nAa = [-A; A]\nba = [u; -l]\nconstraint1 = COSMO.Constraint(Aa, ba, COSMO.Nonnegatives)\n\n# define example problem\nsettings = COSMO.Settings(verbose=true, eps_abs = 1e-4, eps_rel = 1e-4)\n\n\nmodel = COSMO.Model()\nassemble!(model, P, q, constraint1, settings = settings)\nres = COSMO.optimize!(model);\n\n# solve again by defining the constraints with the help of a box\nconstraint1 = COSMO.Constraint(A, zeros(3), COSMO.Box(l, u))\n\nmodel = COSMO.Model()\nassemble!(model, P, q, constraint1, settings = settings)\nres_box = COSMO.optimize!(model);\n\n\n@testset \"QP Problem\" begin\n  @test norm(res.x[1:2] - [0.3; 0.7], Inf) < 1e-3\n  @test norm(res_box.x[1:2] - [0.3; 0.7], Inf) < 1e-3\n  @test abs(res.obj_val - 1.88) < 1e-3\n  @test abs(res_box.obj_val - 1.88) < 1e-3\nend\nnothing\n", "meta": {"hexsha": "aa9bcd74214213ee392331d77b854a3f3521a57e", "size": 1105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/qp.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": "examples/qp.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": "examples/qp.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": 25.6976744186, "max_line_length": 72, "alphanum_fraction": 0.650678733, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7532153741924252}}
{"text": "@testset \"Product with non-commutative monomials and variables\" begin\n    Mod.@ncpolyvar x y z\n    m1 = x * (y * x)\n    @test variables(m1)[1] == x\n    @test variables(m1)[2] == y\n    @test variables(m1)[3] == x\n    @test all(exponents(m1) .== 1)\n    m2 = y * (y * x)\n    @test variables(m2)[1] == y\n    @test variables(m2)[2] == x\n    @test collect(exponents(m2)) == [2, 1]\n    for m3 in [(x*x)*(y^2*x), (x*x*y)*(y*x), x*(x*y^2*x), (x^2*y^2)*x]\n        @test variables(m3)[1] == x\n        @test variables(m3)[2] == y\n        @test variables(m3)[3] == x\n        @test collect(exponents(m3)) == [2, 2, 1]\n    end\n    mv = monovec([x, y, x*y])\n    @test x * mv == [x^2, x*y, x^2*y]\n    @test mv * x == [x^2, y*x, x*y*x]\n    @test y^2 * mv == [y^2*x, y^3, y^2*x*y]\n    @test mv * y^2 == [x*y^2, y^3, x*y^3]\n    m4 = y*x^2\n    @test variables(m4)[1] == y\n    @test variables(m4)[2] == x\n    @test collect(exponents(m4)) == [1, 2]\n\n    @test (x*y) * (3x^2 + 2x*y + 4y^2) == 3x*y*x^2 + 2x*y*x*y + 4x*y^3\n\n    P = [2 3 4;\n         3 4 5;\n         4 5 6]\n    Q = [4 3 5;\n         3 2 4\n         5 4 6]\n    p = @inferred polynomial(P, [x*y, x^2, y^2])\n    @test coefficients(p) == [4, 3, 5, 4, 3, 2, 6, 5, 4]\n    @test monomials(p) == [x^4, x^3*y, x^2*y^2, x*y^3, x*y*x^2, x*y*x*y, y^4, y^2*x^2, y^2*x*y]\n    p = @inferred polynomial(Q, monovec([x*y, x^2, y^2]))\n    @test coefficients(p) == [4, 3, 5, 4, 3, 2, 6, 5, 4]\n    @test monomials(p) == [x^4, x^3*y, x^2*y^2, x*y^3, x*y*x^2, x*y*x*y, y^4, y^2*x^2, y^2*x*y]\n    q = @inferred polynomial(zeros(Float64, 0, 0), emptymonovec(x))\n    @test q isa AbstractPolynomialLike{Float64}\n    @test q == 0\nend\n@testset \"Noncommutative quadratic\" begin\n    Mod.@ncpolyvar x[1:2]\n    Q = Hermitian([1 2 + 3im; 2 - 3im 4])\n    p = 1x[1]^2 + (2 + 3im) * x[1] * x[2] + (2 - 3im) * x[2] * x[1] + 4x[2]^2\n    @test polynomial(Q, x) == p\n    @test polynomial(Q, monovec(x)) == p\nend\n", "meta": {"hexsha": "4625f4ff69ba839b3121cb507f25663858226413", "size": 1909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ncoperators.jl", "max_stars_repo_name": "Timeroot/MultivariatePolynomials.jl", "max_stars_repo_head_hexsha": "899791779b9037043be5c80372f9d00a9fe858ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85, "max_stars_repo_stars_event_min_datetime": "2017-09-27T12:38:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:17:12.000Z", "max_issues_repo_path": "test/ncoperators.jl", "max_issues_repo_name": "Timeroot/MultivariatePolynomials.jl", "max_issues_repo_head_hexsha": "899791779b9037043be5c80372f9d00a9fe858ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 115, "max_issues_repo_issues_event_min_datetime": "2017-10-13T07:47:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:21:08.000Z", "max_forks_repo_path": "test/ncoperators.jl", "max_forks_repo_name": "Timeroot/MultivariatePolynomials.jl", "max_forks_repo_head_hexsha": "899791779b9037043be5c80372f9d00a9fe858ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:30:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T15:49:36.000Z", "avg_line_length": 36.0188679245, "max_line_length": 95, "alphanum_fraction": 0.4887375589, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7532153704261554}}
{"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    \u03bb = Vector{Float64}(undef, n+1)\n    \u03bb[n+1] = d[p[n]]\n    for i in n:-1:2\n        \u03bb[i] = d[p[i-1]] - d[p[i]]\n    end\n    \u03bb[1] = 1.0 - sum(\u03bb[2:end])\n    return \u03bb\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, \u03bb = simplex(T, x)\n    B = _to_belief.(V)\n    valid =  \u03bb .> sqrt(eps())\n    return B[valid], \u03bb[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\u00e8 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\u00b2 \u00c5) 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\u00b2 \u00c5).\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 (\u03b3::CubicVariogram)(h::T) where {T}\n  r = radius(\u03b3.ball)\n  s = \u03b3.sill\n  n = \u03b3.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 \u2265 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": "function Test_AdaptiveSteppers(t0, tf)\r\n    function func(t, y)\r\n        [exp(t)]\r\n    end\r\n\r\n    y0, exact = [exp(t0)], exp(tf)\r\n    methods = DopriStep, CarpStep, RKFStep\r\n\r\n    for a=methods\r\n        ts, ys = AdaptiveStepper(func, a, t0, copy(y0), tf)\r\n        println(\"Actual error of \", a, \": \", abs(exact - ys[end][1]))\r\n    end\r\nend\r\n\r\n#Test_AdaptiveSteppers(20, 21)\r\n\r\n#### Systems ####\r\n\r\nfunction SimpleSystem(t, y)\r\n    [cos(t)]\r\nend\r\n\r\nfunction HarmonicOscillator(t, y)\r\n    y1, ydot = y\r\n    [ydot, 100*cos(20*t) - ydot/4.0 - y1]\r\nend\r\n\r\nfunction FourthOrderSystem(t, y)\r\n    y1, ydot, yddot, ydddot = y\r\n    [ydot, yddot, ydddot, exp(t)*cos(100*t)-7*ydddot-17*yddot-17*ydot-6*y1]\r\nend\r\n\r\n\r\n#t0, tf = 0, 15\r\n#y0 = [0, 0, 0, 0]\r\n\r\n#ts, ys = Stepper(FourthOrderSystem, BackwardEulerStep, t0, y0, tf, 0.01)\r\n#ts, ys = MultiStepper(FourthOrderSystem, AdamsBash4, t0, y0, tf, 0.001)\r\n#plot(ts, [a[1] for a=ys], \"o-\")", "meta": {"hexsha": "5641baba745cea29e2e06c17ed42b29c3f23b852", "size": 924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia_Code/TestAndSystems.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/TestAndSystems.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/TestAndSystems.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": 23.6923076923, "max_line_length": 76, "alphanum_fraction": 0.5844155844, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7532153589021935}}
{"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    \u2207leaky_relu!(y.grad, x.data, x.grad, eltype(x)(alpha))\nend\n\nfunction \u2207leaky_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": "#towel map:\nprintln(\"Testing discrete system evolution...\")\nusing StaticArrays, Base.Test, DynamicalSystems\n\n@testset \"Logistic Map\" begin\n\n  d1 = Systems.logistic(0.1)\n  d2 = DiscreteDS1D(0.1, d1.eom)\n  d3 = DiscreteDS1D(big(0.1), d1.eom, d1.deriv)\n\n  @testset \"Evolution & Timeseries\" begin\n    dd1 = evolve!(d1)\n    dd2 = evolve!(d2)\n    dd3 = evolve!(d3)\n    @test dd1.state == dd2.state\n    @test dd1.state \u2248 dd3.state\n    @test typeof(dd3.state) == BigFloat\n    ts1 = timeseries(dd1, 100, mutate = false)\n    ts3 = timeseries(dd3, 100, mutate = false)\n    @test ts1[10] \u2248 ts3[10]\n    @test eltype(ts3) == BigFloat\n  end\n  @testset \"Derivatives\" begin\n    f1 = d1.deriv(d1.state)\n    f2 = d2.deriv(d2.state)\n    f3 = d3.deriv(d3.state)\n    @test isapprox(f1, f2;rtol = 1e-12)\n    @test isapprox(f1, f3;rtol = 1e-12)\n    @test typeof(f3) == BigFloat\n  end\nend\n\n@testset \"Folded-Towel Map\" begin\n\n  s1 = Systems.towel(0.1ones(3))\n  s2 = DiscreteDS(0.1ones(3), s1.eom)\n  s4 = DiscreteDS(round.(big.(0.1ones(3)),3), s1.eom, s1.jacob)\n\n  @testset \"Evolution & Timeseries\" begin\n    st1 = evolve(s1)\n    st2 = evolve(s2)\n    st4 = evolve(s4)\n\n    @test isapprox.(st1, st2; rtol = 1e-12) == trues(s1.state)\n    @test isapprox.(st1, st4; rtol = 1e-12) == trues(s1.state)\n\n    evolve!(s1); evolve!(s2); evolve!(s4);\n    @test s1.state \u2248 s2.state\n    @test s2.state \u2248 s4.state\n\n    ts = timeseries(s1, 100; mutate = false)\n    @test size(ts) == (100, 3)\n    ts4 = timeseries(s4, 100; mutate = false)\n    @test size(ts4) == (100, 3)\n    @test eltype(ts4) == BigFloat\n    @test isapprox.(ts[10, :],ts4[10, :]) == trues(3)\n  end\n  @testset \"Jacobians\" begin\n\n    J1 = jacobian(s1)\n    @test typeof(J1) <: SMatrix\n    J2 = jacobian(s2)\n    J4 = jacobian(s4)\n    @test typeof(J4) <: SMatrix\n\n    @test isapprox.(J1, J2; rtol = 1e-6) == trues(J1)\n    @test isapprox.(J1, J4; rtol = 1e-6) == trues(J1)\n    @test eltype(J4) == BigFloat\n  end\nend\n", "meta": {"hexsha": "80120aa73d3fa02859a5114bf1c71d20058a2481", "size": 1933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/discrete_systems.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/discrete_systems.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/discrete_systems.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": 27.2253521127, "max_line_length": 63, "alphanum_fraction": 0.6114847387, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7531886525874845}}
{"text": "using MultivariateStats\nusing Base.Test\n\nsrand(34568)\n\n## PCA with zero mean\n\nX = randn(5, 10)\nY = randn(3, 10)\n\nP = qr(randn(5, 5))[1][:, 1:3]\npvars = [5., 4., 3.]\nM = PCA(Float64[], P, pvars, 15.0)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test mean(M) == zeros(5)\n@test projection(M) == P\n@test principalvars(M) == pvars\n@test principalvar(M, 2) == pvars[2]\n@test tvar(M) == 15.0\n@test tprincipalvar(M) == 12.0\n@test tresidualvar(M) == 3.0\n@test principalratio(M) == 0.8\n\n@test_approx_eq transform(M, X[:,1]) P'X[:,1]\n@test_approx_eq transform(M, X) P'X\n\n@test_approx_eq reconstruct(M, Y[:,1]) P * Y[:,1]\n@test_approx_eq reconstruct(M, Y) P * Y\n\n\n## PCA with non-zero mean\n\nmv = rand(5)\nM = PCA(mv, P, pvars, 15.0)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test mean(M) == mv\n@test projection(M) == P\n@test principalvars(M) == pvars\n@test principalvar(M, 2) == pvars[2]\n@test tvar(M) == 15.0\n@test tprincipalvar(M) == 12.0\n@test tresidualvar(M) == 3.0\n@test principalratio(M) == 0.8\n\n@test_approx_eq transform(M, X[:,1]) P' * (X[:,1] .- mv)\n@test_approx_eq transform(M, X) P' * (X .- mv)\n\n@test_approx_eq reconstruct(M, Y[:,1]) P * Y[:,1] .+ mv\n@test_approx_eq reconstruct(M, Y) P * Y .+ mv\n\n\n## prepare training data\n\nd = 5\nn = 1000\n\nR = qr(randn(d, d))[1]\n@test_approx_eq R'R eye(5)\nscale!(R, sqrt([0.5, 0.3, 0.1, 0.05, 0.05]))\n\nX = R'randn(5, n) .+ randn(5)\nmv = vec(mean(X, 2))\nZ = X .- mv\n\nC = cov(X; vardim=2)\npvs0 = sort(eigvals(C); rev=true)\ntv = sum(diag(C))\n\n## pcacov (default using cov when d < n)\n\nM = fit(PCA, X)\nP = projection(M)\npvs = principalvars(M)\n\n@test indim(M) == 5\n@test outdim(M) == 5\n@test mean(M) == mv\n@test_approx_eq P'P eye(5)\n@test_approx_eq C * P scale(P, pvs)\n@test issorted(pvs; rev=true)\n@test_approx_eq pvs pvs0\n@test_approx_eq tvar(M) tv\n@test_approx_eq sum(pvs) tvar(M)\n@test_approx_eq reconstruct(M, transform(M, X)) X\n\nM = fit(PCA, X; mean=mv)\n@test_approx_eq projection(M) P\n\nM = fit(PCA, Z; mean=0)\n@test_approx_eq projection(M) P\n\nM = fit(PCA, X; maxoutdim=3)\nP = projection(M)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test_approx_eq P'P eye(3)\n@test issorted(pvs; rev=true)\n\nM = fit(PCA, X; pratio=0.85)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test_approx_eq P'P eye(3)\n@test issorted(pvs; rev=true)\n\n## pcastd\n\nM = fit(PCA, X; method=:svd)\nP = projection(M)\npvs = principalvars(M)\n\n@test indim(M) == 5\n@test outdim(M) == 5\n@test mean(M) == mv\n@test_approx_eq P'P eye(5)\n@test_approx_eq_eps C * P scale(P, pvs) 1.0e-3\n@test issorted(pvs; rev=true)\n@test_approx_eq_eps pvs pvs0 1.0e-3\n@test_approx_eq_eps tvar(M) tv 1.0e-3\n@test_approx_eq sum(pvs) tvar(M)\n@test_approx_eq reconstruct(M, transform(M, X)) X\n\nM = fit(PCA, X; method=:svd, mean=mv)\n@test_approx_eq projection(M) P\n\nM = fit(PCA, Z; method=:svd, mean=0)\n@test_approx_eq projection(M) P\n\nM = fit(PCA, X; method=:svd, maxoutdim=3)\nP = projection(M)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test_approx_eq P'P eye(3)\n@test issorted(pvs; rev=true)\n\nM = fit(PCA, X; method=:svd, pratio=0.85)\n\n@test indim(M) == 5\n@test outdim(M) == 3\n@test_approx_eq P'P eye(3)\n@test issorted(pvs; rev=true)\n\n", "meta": {"hexsha": "8024c076611f842b4a3471fe99a0bf6b42d0cefa", "size": 3103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pca.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": "test/pca.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": "test/pca.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": 20.8255033557, "max_line_length": 56, "alphanum_fraction": 0.643570738, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.753188642856709}}
{"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": "module AffineFEOperatorsTests\n\nusing Test\nusing Gridap.Arrays\nusing Gridap.Algebra\nusing Gridap.TensorValues\nusing Gridap.ReferenceFEs\nusing Gridap.Geometry\nusing Gridap.Fields\nusing Gridap.FESpaces\nusing LinearAlgebra\nusing Gridap.CellData\n\ndomain =(0,1,0,1)\npartition = (2,2)\nmodel = CartesianDiscreteModel(domain,partition)\norder = 1\nreffe = ReferenceFE(lagrangian,Float64,order)\nV = FESpace(model,reffe;dirichlet_tags=[1,10])\nU = V\n\ntrian = get_triangulation(model)\ndegree = 4\nquad = CellQuadrature(trian,degree)\n\n#f(x) = x[2]\n#v = get_cell_shapefuns(V)\n#u = get_cell_shapefuns_trial(U)\n#\n#cellmat = integrate(\u2207(v)\u2299\u2207(u),quad)\n#cellvec = integrate(v*f,quad)\n#cellids = collect(1:num_cells(trian))\n#\n#assem = SparseMatrixAssembler(U,V)\n#matdata = ([cellmat],[cellids],[cellids])\n#vecdata = ([cellvec],[cellids])\n#A =  assemble_matrix(assem,matdata)\n#b =  assemble_vector(assem,vecdata)\n#\n#op = AffineFEOperator(U,V,A,b)\n#@test A === get_matrix(op)\n#@test b === get_vector(op)\n#\n#x = ones(length(b))\n#r = A*x - b\n#\n#test_fe_operator(op,x,r,\u2248,jac=A)\n#@test isa(get_algebraic_operator(op), AffineOperator)\n\n#\n\ntol = 1.0e-9\n\nu_sol(x) = x[1]+x[2]\nf_fun(x) = 0\n\nV = FESpace(model,reffe;dirichlet_tags=\"boundary\")\nU = TrialFESpace(V,u_sol)\n\nd\u03a9 = Measure(quad)\n\na(u,v) = \u222b(\u2207(v)\u2299\u2207(u))*d\u03a9\nl(v) = \u222b(v*f_fun)*d\u03a9\n\nassem = SparseMatrixAssembler(U,V)\n\nop = AffineFEOperator(U,V,assem) do u,v\n  \u222b(\u2207(v)\u2299\u2207(u))*d\u03a9, \u222b(v*f_fun)*d\u03a9\nend\nuh = solve(op)\ne = u_sol - uh\n\n@test sum(\u222b(e*e)*d\u03a9) < tol\n@test \u2211(\u222b(e*e)*d\u03a9) < tol\n\nop = AffineFEOperator(U,V) do u,v\n  \u222b(\u2207(v)\u2299\u2207(u))*d\u03a9, \u222b(v*f_fun)*d\u03a9\nend\nuh = solve(op)\ne = u_sol - uh\n@test sum(\u222b(e*e)*d\u03a9) < tol\n\nop = AffineFEOperator(a,l,U,V)\nuh = solve(op)\ne = u_sol - uh\n@test sum(\u222b(e*e)*d\u03a9) < tol\n\nend # module\n", "meta": {"hexsha": "451f066169c712c739563d88a3383847a7cdc1b0", "size": 1731, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FESpacesTests/AffineFEOperatorsTests.jl", "max_stars_repo_name": "Omega-xyZac/Gridap.jl", "max_stars_repo_head_hexsha": "c9f0ca39a0c84646ea9e4b57fd39d3a6db59c044", "max_stars_repo_licenses": ["MIT"], "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/FESpacesTests/AffineFEOperatorsTests.jl", "max_issues_repo_name": "Omega-xyZac/Gridap.jl", "max_issues_repo_head_hexsha": "c9f0ca39a0c84646ea9e4b57fd39d3a6db59c044", "max_issues_repo_licenses": ["MIT"], "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/FESpacesTests/AffineFEOperatorsTests.jl", "max_forks_repo_name": "Omega-xyZac/Gridap.jl", "max_forks_repo_head_hexsha": "c9f0ca39a0c84646ea9e4b57fd39d3a6db59c044", "max_forks_repo_licenses": ["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.4494382022, "max_line_length": 54, "alphanum_fraction": 0.6776429809, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7531886347831241}}
{"text": "using Statistics\nusing Random\n\n\n################################################################\n\n\n\nobj(Y, X, b) = mean((Y .- X * b) .^ 2.0) # objective to minimize\n\n# modified example from GradDescent.jl documentation\n@testset \"linreg\" begin\n\n    Random.seed!(1) # set seed\n    n = 1000 # number of observations\n    d = 10   # number of covariates\n    X = randn(n, d) # simulated covariates\n    b = randn(d)    # generated coefficients\n    \u03f5 = randn(n) * 0.1 # noise\n    Y = X * b + \u03f5 # observed outcome\n\n    epochs = 100 # number of epochs\n\n    \u03b8 = randn(d) # initialize model parameters\n\n    loss_first, g = grad(obj, Y, X, \u03b8)\n    loss_last = loss_first\n    for i in 1:epochs\n        loss_last, g = grad(obj, Y, X, \u03b8)\n        # println(\"Epoch: $i; loss = $loss_last\")\n        \u03b4 = 0.01 * g[4]\n        \u03b8 -= \u03b4\n    end\n    @test loss_last < loss_first / 10   # loss reduced at least 10 times\n\nend\n\n\nmutable struct Linear2{T}\n    W::AbstractMatrix{T}\n    b::AbstractVector{T}\nend\n\nlinear_loss(m::Linear2, X, y) = mean((m.W * X .+ m.b .- y) .^ 2.0)\n\n@testset \"linreg 2\" begin\n\n    n_vars = 10\n    n_out = 2\n    n_obs = 1000\n    X = randn(n_vars, n_obs)\n    W_true = rand(n_out, n_vars)\n    b_true = rand(n_out)\n    \u03f5 = randn(n_out, n_obs) * 0.1 # noise\n    Y = W_true * X .+ b_true .+ \u03f5\n\n    m = Linear2(rand(n_out, n_vars), rand(n_out))\n\n    epochs = 100\n\n    for i in 1:epochs\n        val, g = grad(linear_loss, m, X, Y)\n        # println(\"Epoch: $i; loss = $val\")\n        update!(m, g[2], (x, gx) -> x - 0.1 * gx)\n    end\n\n    @test isapprox(m.W, W_true; atol=0.1)\n    @test isapprox(m.b, b_true; atol=0.1)\n\nend\n", "meta": {"hexsha": "37d2cbef6437e0306dc15aeaa62440acffe9c5f7", "size": 1612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_examples.jl", "max_stars_repo_name": "dfdx/Gendo.jl", "max_stars_repo_head_hexsha": "7bc3e672cd1aed9a2e4f32aa87fc4632b8e196d9", "max_stars_repo_licenses": ["MIT"], "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_examples.jl", "max_issues_repo_name": "dfdx/Gendo.jl", "max_issues_repo_head_hexsha": "7bc3e672cd1aed9a2e4f32aa87fc4632b8e196d9", "max_issues_repo_licenses": ["MIT"], "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_examples.jl", "max_forks_repo_name": "dfdx/Gendo.jl", "max_forks_repo_head_hexsha": "7bc3e672cd1aed9a2e4f32aa87fc4632b8e196d9", "max_forks_repo_licenses": ["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.7042253521, "max_line_length": 72, "alphanum_fraction": 0.5496277916, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7531886305493103}}
{"text": "export elu\n\ndoc\"\"\"\n    elu(x::Var)\n\nExponential Linear Unit.\n\n# References\n* Clevert et al., [\"Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)\"](https://arxiv.org/abs/1511.07289), arXiv 2015.\n\n```math\nf(x) =\n\\begin{cases}\nx & x > 0 \\\\\n\\alpha (e^{x}-1) & x\\leq0\n\\end{cases}\n```\nwhere ``\\alpha=1``.\n\"\"\"\nelu(x::Var) = Var(elu.(x.data), (elu,x))\nelu(x::T) where T = x > zero(T) ? x : exp(x)-1\nelu(x::Node) = Node(elu, x)\n\nfunction addgrad!(y::Var, ::typeof(elu), x::Var)\n    isvoid(x.grad) && return\n    \u2207elu!(y.data, y.grad, x.data, x.grad)\nend\n\nfunction \u2207elu!(y::Array{T}, gy::Array{T}, x::Array{T}, gx::Array{T}) where T\n    alpha = one(T)\n    @inbounds for i = 1:length(x)\n        gx[i] += x[i] > zero(T) ? gy[i] : gy[i]*(y[i]+alpha)\n    end\nend\n", "meta": {"hexsha": "d6eab8c89037c40cd1d27febef0bfb0048d02002", "size": 773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/activation/elu.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/elu.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/elu.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": 22.0857142857, "max_line_length": 143, "alphanum_fraction": 0.5808538163, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.753188628498077}}
{"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, \u03b6::arb) = ((2*\u03b6)^(n + 1//2))//Sqrt(Gamma(2*n + One(n)))\nSlaterON(n::Real, \u03b6::Real) = SlaterON(RF(n), RF(\u03b6))\n\nfunction SlaterON(n1::arb, n2::arb, \u03c1::arb, \u03c4::arb)\n    res1 = ((\u03c1*(One(\u03c4)+\u03c4))^(n1 + 1//2)) * ((\u03c1*(One(\u03c4)-\u03c4))^(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, \u03c1::Real, \u03c4::Real) = SlaterON(RF(n1), RF(n2), RF(\u03c1), RF(\u03c4))\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, \u03ba::Int) = ifelse(\u03ba < 0, Abs(\u03ba), Sqrt(\u03ba^2 + (2*n + 1)))\nSlaterSF(n::Real, \u03ba::Int) = SlaterSF(RF(n), \u03ba)\n###########################################################################################################\t\n############################################## COEFFICIENT A ##############################################\n################# Normalization coeeficients so called A^{\\beta}_{n\\kappa}\nSlaterSA(\u03b2::Int, n::arb, \u03ba::Int) = ifelse(\u03ba < 0, (\u03b2*\u03ba)//(2*n), (\u03b2//2)*(SlaterSF(n, \u03ba)-\u03ba) - (RF(1)//RF(2)))\nSlaterSA(\u03b2::Int, n::Real, \u03ba::Int) = SlaterSA(\u03b2, RF(n), RF(\u03ba))\n###########################################################################################################\t\n############################################## COEFFICIENT B ##############################################\n################# Normalization coeeficients so called B^{\\beta}_{n\\kappa}\nSlaterSB(\u03b2::Int, n::arb, \u03ba::Int) = ifelse(\u03ba < 0, Zero(RF), -\u03b2*((SlaterSF(n, \u03ba) - \u03ba)//(2*n + 1)))\nSlaterSB(\u03b2::Int, n::Real, \u03ba::Int) = SlaterSB(\u03b2, RF(n), RF(\u03ba))\n###########################################################################################################\t\n############################################## COEFFICIENT N ##############################################\n################# 1/Sqrt(N) part, the dominator is used for both wave and charge density\nfunction SlaterSN(\u03b2::Int, n::arb, \u03ba::Int)\n    res1 = SlaterSA(\u03b2, n, \u03ba) * SlaterSA(\u03b2, n, \u03ba) * Gamma(2*n + RF(1))\n    res2 = SlaterSA(\u03b2, n, \u03ba) * SlaterSB(\u03b2, n, \u03ba) * Gamma(2*n + RF(2))\n    res3 = SlaterSB(\u03b2, n, \u03ba) * SlaterSB(\u03b2, n, \u03ba) * (Gamma(2*n + RF(3)) // 4)\n    res1 + res2 + res3\nend\nSlaterSN(\u03b2::Int, n::Real, \u03ba::Int) = SlaterSN(\u03b2, RF(n), \u03ba)\n\nSlaterSN(\u03b2::Int, n::arb, \u03ba::Int, \u03b6::arb) = ((2*\u03b6)^(n + 1//2))//Sqrt(SlaterSN(\u03b2, n, \u03ba))\nSlaterSN(\u03b2::Int, n::Real, \u03ba::Int, \u03b6::Real) = SlaterSN(\u03b2, RF(n), \u03ba, RF(\u03b6))\n\nfunction SlaterON(\u03b21::Int, n1::arb, \u03ba1::Int, \u03b22::Int, n2::arb, \u03ba2::Int, \u03c1::arb, \u03c4::arb)\n    res1 = ((\u03c1*(One(\u03c4)+\u03c4))^(n1 + 1//2)) * ((\u03c1*(One(\u03c4)-\u03c4))^(n2 + 1//2))\n    res2 = Sqrt(SlaterSN(\u03b21, n1, \u03ba1) * SlaterSN(\u03b22, n2, \u03ba2)) \n    res1 // res2\nend\nSlaterSN(\u03b21::Int, n1::Real, \u03ba1::Int, \u03b22::Int, n2::Real, \u03ba2::Int, \u03c1::Real, \u03c4::Real) =\nSlaterSN(\u03b21, RF(n1), \u03ba1, \u03b22, RF(n2), \u03ba2, RF(\u03c1), RF(\u03c4))\n\nfunction SlaterSX(\u03b21::Int, n1::arb, \u03ba1::Int, \u03b61::arb, \u03b22::Int, n2::arb, \u03ba2::Int, \u03b62::arb)\n    a1 = SlaterSA(\u03b21, n1, \u03ba1)\n    a2 = SlaterSA(\u03b22, n2, \u03ba2)\n    b1 = SlaterSB(\u03b21, n1, \u03ba1)\n    b2 = SlaterSB(\u03b22, n2, \u03ba2)\n\n    x1 = \u03b61 * \u03b61 * a1 * a2\n    x2 = \u03b61 * \u03b62 * b1 * a2\n    x3 = \u03b61 * \u03b62 * a1 * b2\n    x4 = \u03b62 * \u03b62 * b1 * b2\n\n    x = [x1, x2, x3, x4]\n    x = transpose(x)\n    return x\nend\nSlaterSX(\u03b21::Int, n1::Real, \u03ba1::Int, \u03b61::Real, \u03b22::Int, n2::Real, \u03ba2::Int, \u03b62::Real) =\nSlaterSX(\u03b21, RF(n1), \u03ba1, RF(\u03b61), \u03b22, RF(n2), \u03ba2, RF(\u03b62))", "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, \u03b2\n\n\u03a9 = 7.2921 * 10^(-5) #rad/s\nR = 6.3781 * 10^(6) #m\n\n\"\"\"\n    f(\u03c6)\n\nCoriolis Parameter\n\"\"\"\nf(\u03c6) = 2\u03a9 * sind(\u03c6)\n\n\"\"\"\n    \u03b2(\u03c6)\n\nRossby Parameter\n\"\"\" \n\u03b2(\u03c6) = 2\u03a9 / R * cosd(\u03c6)\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": "# # Tutorial: missing value handling\n#\n# This tutorial illustrates the usage of Transducers.jl by stepping\n# through various handling of missing values.\n\nusing Transducers\n\n# ## Dot product\n#\n# Here is a simple way to compute a dot product using\n# [`mapfoldl`](@ref) and [`MapSplat`](@ref):\n\nmapfoldl(MapSplat(*), +, zip(1:3, 10:2:14))\n\n# Let's see what it does step by step.  First we create a \"printer\"\n# transducer using the following function (see [`Map`](@ref)):\n\nxf_printer(label) = Map() do x\n    println(label, \": \", x)\n    return x  # just return it as-is\nend\nnothing  # hide\n\n# This transducer just pass-through the input while printing its value\n# (prefixed by a `label`).  Let's sandwich the previous `MapSplat(*)`\n# with it:\n\nmapfoldl(\n    xf_printer(\" input\") |> MapSplat(*) |> xf_printer(\"output\"),\n    +, zip(1:3, 10:2:14))\nflush(stdout)  # hide\n\n# You can see that the input tuple `(1, 10)` is splatted into function\n# `*` by `MapSplat` which then outputs `10`.  This is repeated for all\n# inputs.\n\n# Perhaps unfortunately, this way of computing a dot product\n# propagates any missing values contained in the input arrays to the\n# result (which may actually be desired in certain cases).\n\nxs = [1, missing, 3, 2]\nys = [10, 14, missing, 12]\nmapfoldl(MapSplat(*), +, zip(xs, ys))\n\n# However, it is very simple to ignore any missing values using\n# [`OfType`](@ref):\n\nxf_mdot = OfType(Tuple{Vararg{Number}}) |> MapSplat(*)\nmapfoldl(xf_mdot, +, zip(xs, ys))\n\n# Here, `Tuple{Vararg{Number}}` is a type that matches with a tuple of\n# any length with numbers.  It does not match with a tuple if it has a\n# `missing`.\n\n@assert (1, 0.5) isa Tuple{Vararg{Number}}\n@assert (1, 0.5, 2im) isa Tuple{Vararg{Number}}\n@assert !((1, missing) isa Tuple{Vararg{Number}})\n\n# ## Covariance\n#\n# Transducer `xf_mdot` above can also be used to compute the\n# covariance.  First, we need the number of pairs of elements in `xs`\n# and `ys` that _both_ of them are not `missing`:\n\nnonmissings = mapfoldl(OfType(Tuple{Vararg{Number}}) |> Count(),\n                       right,\n                       zip(xs, ys);\n                       init = 0)\nnonmissings  # hide\n#-\n@assert nonmissings == 2  # hide\n\n# We do this by using [`Count`](@ref) and [`right`](@ref).  `Count`\n# ignores input and count the number of times the input is provided.\n# Since `OfType(Tuple{Vararg{Number}})` provides the inputs to the\n# downstream transducer only if there is no `missing` values, this\n# correctly counts the number of non-missing pairs.  Function `right`\n# is simply defined as `right(l, r) = r` (and `right(r) = r`).  Thus,\n# the whole `mapfoldl` returns the last output of `Count`.  In case\n# `Count` never gets called (i.e., there are no non-missing pairs), we\n# pass `init=0`.\n\nans =  # hide\nmapfoldl(OfType(Tuple{Vararg{Number}}) |> Count(),\n         right,\n         zip(Int[], Int[]);\n         init = 0)\nans  # hide\n#-\n@assert ans == 0  # hide\n\n# Finally, we have to pre-process the input to `xf_mdot` by\n# subtracting the average.  It's easy to do with `Map`:\n\nusing Statistics: mean\n\nfunction xf_demean(xs, ys)\n    xmean = mean(skipmissing(xs))\n    ymean = mean(skipmissing(ys))\n    return Map(((x, y),) -> (x - xmean, y - ymean))\nend\n\nmapfoldl(xf_demean(xs, ys) |> xf_mdot, +, zip(xs, ys)) / nonmissings\n\n# ## Addition\n#\n# How do we use transducers for vector-to-vector transformation?  Here\n# is a function to calculate ``y = x + y`` while ignoring missing\n# values in ``x``.  First, mandatory input shape check:\n\nfunction add_skipmissing!(ys, xs)\n    length(ys) == length(xs) || error(\"length(ys) != length(xs)\")\n    firstindex(ys) == 1 || error(\"firstindex(ys) != 1\")\n#+\n# For filtering out missing values from `xs` while tracking indices,\n# we use [`Enumerate`](@ref) and [`Filter`](@ref).  To iterate over\n# the output of the transducer, [`foreach`](@ref) is used instead of\n# [`mapfoldl`](@ref) since mutating an array is better expressed as a\n# side-effect than a fold.\n\n    foreach(Enumerate() |> Filter(!(ismissing \u2218 last)), xs) do (i, xi)\n        @inbounds ys[i] += xi\n    end\n#+\n# We then return the mutated value to behave like the rest of Julia\n# functions (`push!`, `mul!`, etc.):\n\n    return ys\nend\nnothing  # hide\n\n# Example:\n\nans =  # hide\nadd_skipmissing!([100, 110, 120], [1, missing, 2])\n#-\n@assert ans == [101, 110, 122]  # hide\n\n# ## Vectorized reduction\n#\n# `foldl`, `mapfoldl`, etc. in `Base` support `dims` argument.\n# Transducers.jl does not support this argument as of writing.\n# However, this can easily be emulated using `eachcol`, `eachrow`, or\n# `eachslice` iterators in `Base`.\n\nxs = [\n    0       missing 1       2\n    3       4       5       missing\n    missing 6       7       missing\n]\n\nfunction xf_sum_columns(prototype)\n    T = Base.nonmissingtype(eltype(prototype)) # subtract Missing from type\n    dims = size(prototype)\n    return Scan(add_skipmissing!, CopyInit(zeros(T, dims)))\nend\nnothing  # hide\n\n# We use [`CopyInit`](@ref) here to allocate the \"output array\"\n# into which the columns are added by `add_skipmissing!`.\n\nif VERSION >= v\"1.1-\"  # eachcol not in Julia 1.0  #src\nans =  # hide\nmapfoldl(xf_sum_columns(xs[:, 1]), right, eachcol(xs))\n#-\n@assert ans == [3, 12, 13]  # hide\n\n# Above computation returns the sum over each row without taking into\n# account the relationship within a column.  Another possibly useful\n# reduction is the sum of the columns with no missing values.  This\n# can easily be done by prepending a filter:\n\nans =  # hide\nmapfoldl(Filter(x -> !any(ismissing, x)) |> xf_sum_columns(xs[:, 1]),\n         right, eachcol(xs))\n#md ans  # hide\n#src `#md ans` is a hack to avoid Literate.jl to put `continued = true`.\n#-\n@assert ans == [1, 5, 7]  # hide\n\n# Note that above combination of `Scan` and `right` is redundant.  For\n# example, we can simply pass `add_skipmissing!` to \"normal\" `foldl`:\n\nans =  # hide\nfoldl(add_skipmissing!, eachcol(xs), init=zeros(Int, size(xs, 1)))\n#-\n@assert ans == [3, 12, 13]  # hide\n\n# However, packaging it as a transducer is sometimes useful as it can\n# be composed with other transducers and \"bottom\" reducing function.\n# For example, vectorized version of `cumsum` can easily obtained by\n# composing it with `append!` (and then `reshape` after `mapfoldl`):\n\nresult = mapfoldl(\n    xf_sum_columns(xs[:, 1]),\n    Completing(append!),\n    eachcol(xs);\n    init = Int[])\nans =  # hide\nreshape(result, (size(xs, 1), :))\n#-\n@assert ans == [      # hide\n    0  0   1   3      # hide\n    3  7  12  12      # hide\n    0  6  13  13      # hide\n]                     # hide\nend  # if VERSION >= v\"1.1-\"  #src\n\n# Note that we need [`Completing`](@ref) here since `append!` does not\n# have the unary method used for [`complete`](@ref\n# Transducers.complete) protocol.\n\n# ## Argmax\n#\n# Another useful operation to do ignoring missing values is\n# `argmax`/`argmin`.  It can be implemented using `Enumerate() |>\n# Filter(!(ismissing \u2218 last))` (see also `add_skipmissing!` above)\n# composed with [`ScanEmit`](@ref).  We first need to define a\n# function to be called by `ScanEmit`:\n\n##                     ,--- current state\n##                     |\n##                     |              ,-- input\n##                     |              |\nfunction argmax_step((argmax, max), (index, value))\n    argmax, max = value > max ? (index, value) : (argmax, max)\n    return argmax, (argmax, max)\n    ##       \\        \\\n    ##        \\        \\__ next state\n    ##         \\\n    ##          \\__ output\nend\nnothing  # hide\n\n# This function is passed to `ScanEmit` with the initial state:\n\nxf_argmax = Enumerate() |> Filter(!(ismissing \u2218 last)) |>\n    ScanEmit(argmax_step, (0, typemin(Int)))\n##                          |\n##                   initial state\nnothing  # hide\n\n\n# As [`ScanEmit`](@ref) is one of the most complex (and powerful)\n# transducer, it may require some comments on how above code works:\n#\n# * The state `(argmax, max)` is initialized to `(0, typemin(Int))` in\n#   `xf_argmax`.  This is the first value passed to the first argument\n#   `(argmax, max)` of `argmax_step`.\n#\n# * The upstream transducer `Enumerate()` provides `(index,\n#   value)`-pair which becomes the input (the second argument) of\n#   `argmax_step`.\n#\n# * Function `argmax_step` must return a pair.  The first item becomes\n#   the output of `ScanEmit`.  In this case that's the index of the\n#   largest item seen so far.\n#\n# * The second item in the returned pair is fed back to `argmax_step`\n#   in the next call.\n#\n# We have the argmax function by extracting the last output of\n# `xf_argmax`:\n\nmapfoldl(xf_argmax, right, [1, 3, missing, 2])\n\n# Side note: We use `typemin(Int)` as the initial value of `max` for\n# simplicity.  In practice, it should be\n# `typemin(eltype(input_array))`.  A more generic solution is to\n# special-case the first invocation by using a singleton like\n# `nothing`.  Julia can handle small `Union` type such as this (see\n# the next section).  Another solution is to use `Init(>)` from\n# InitialValues.jl.\n\n# ## Extrema\n#\n# Transducer `xf_argmax` in the previous section only outputs the\n# index of the maximum element so far.  To output the maximum element\n# as well, we can simply use [`Scan`](@ref).  Also, while we are at\n# it, let's support both argmax and argmin.  To this end, we\n# parametrize the function passed to `Scan` by the comparison function\n# `>` and `<`.  Another problem with `xf_argmax` is that it does not\n# handle non-`Int` input types.  To properly handle different input\n# types, we initialize `Scan`'s state with `nothing` and special-case\n# the first invocation to return the input as-is.  Following function\n# `argext_step` takes the function `>` or `<` and return a function\n# appropriate for `Scan.`\n\nargext_step(should_update) =\n    (old, (index, value)) ->\n        if old === nothing || should_update(old[2], value)\n            (index, value)\n        else\n            old\n        end\nnothing  # hide\n\nxf_scanext(should_update) = Scan(argext_step(should_update), nothing)\nnothing  # hide\n\n# Passing `<` gives us the argmax transducer:\n\n@time begin  #src\nans = # hide\nmapfoldl(\n    Enumerate() |> OfType(Tuple{Integer, Number}) |> xf_scanext(<),\n    right, [1.0, 3.0, missing, 2.0])\nend  #src\n#-\n@assert ans === (2, 3.0) # hide\n@show ans  #src\n\n# We now have transducers `xf_scanext(<)` and `xf_scanext(>)` for\n# argmax and argmin, respectively.  We can compute them concurrently\n# by [`Zip`](@ref)'ing them together:\n\nxf_fullextrema = Enumerate() |> OfType(Tuple{Integer, Number}) |>\n    Zip(xf_scanext(>), xf_scanext(<))\n\n@time begin  #src\nans = # hide\nmapfoldl(xf_fullextrema, right, [1.0, 3.0, -1.0, missing, 2.0])\nend  #src\n#-\n@assert ans === ((3, -1.0), (2, 3.0))  # hide\n@show ans  #src\n\n# This transducer produces a tuple `((argmin, min), (argmax, max))`.\n# To output only indices, append an appropriate `Map`:\n\nxf_argextrema =\n    xf_fullextrema |> Map() do ((argmin, min), (argmax, max))\n        (argmin, argmax)\n    end\n\n@time begin  #src\nans = # hide\nmapfoldl(xf_argextrema, right, [1.0, 3.0, -1.0, missing, 2.0])\nend  #src\n#-\n@assert ans === (3, 2)  # hide\n@show ans  #src\n", "meta": {"hexsha": "c39699eb39508cb782fa334f0bd878413fdb8354", "size": 11090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/tutorial_missings.jl", "max_stars_repo_name": "atthom/Transducers.jl", "max_stars_repo_head_hexsha": "73c90d9e99cb4256c1471e8596710c8fae26a211", "max_stars_repo_licenses": ["MIT"], "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/tutorial_missings.jl", "max_issues_repo_name": "atthom/Transducers.jl", "max_issues_repo_head_hexsha": "73c90d9e99cb4256c1471e8596710c8fae26a211", "max_issues_repo_licenses": ["MIT"], "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/tutorial_missings.jl", "max_forks_repo_name": "atthom/Transducers.jl", "max_forks_repo_head_hexsha": "73c90d9e99cb4256c1471e8596710c8fae26a211", "max_forks_repo_licenses": ["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.332361516, "max_line_length": 75, "alphanum_fraction": 0.6470694319, "num_tokens": 3308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7531774085778397}}
{"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\u03d5 &= (\\\\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, \u03d5 = (u...,)\n    \u03b1, s, \u03c9 = (p...,)\n    dx = \u03b1*(1 - s*cos(2*pi*\u03d5))*x*(1 - x)\n    d\u03d5 = (\u03d5 + \u03c9) % 1\n\n    return SVector{2}(dx, d\u03d5)\nend\n\nfunction anishchenko1(u\u2080, \u03b1, s, \u03c9)\n    p = [\u03b1, s, \u03c9]\n    DiscreteDynamicalSystem(eom_anishchenko1, u\u2080, p)\nend\n\n\"\"\"\n    anishchenko1(;u\u2080 = rand(2), \u03b1 =3.277, s=0.1, \u03c9=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\u03d5 &= (\\\\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\u2080 = rand(2), \u03b1 =3.277, s=0.1, \u03c9=0.5*(sqrt(5)-1)) =\n    anishchenko1(u\u2080, \u03b1, s, \u03c9)\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        \u0177::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        \u0177::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        \u0177::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        \u0177::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        \u0177::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        \u0177::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    \u0177::Vector\n\n    function mse(y, \u0177)\n        return mean((y - \u0177).^2)\n    end\nend\n\nstruct mae{T<:AbstractFloat}\n    y::Vector\n    \u0177::Vector\n\n    function mae(y, \u0177)\n        return mean(abs.(y - \u0177))\n    end\nend\n\nstruct rmse{T<:AbstractFloat}\n    y::Vector\n    \u0177::Vector\n\n    function rmse(y, \u0177)\n        return sqrt(mse(y, \u0177))\n    end\nend\n\nstruct rmae{T<:AbstractFloat}\n    y::Vector\n    \u0177::Vector\n\n    function rmae(y, \u0177)\n        return sqrt(mae(y, \u0177))\n    end\nend\n\nstruct rmsle{T<:AbstractFloat}\n    y::Vector\n    \u0177::Vector\n\n    function rmsle(y, \u0177)\n        return sqrt(mean((log.(y .+ 1) - log.(\u0177 .+ 1)).^2))\n    end\nend\n\nstruct r2score{T<:AbstractFloat}\n    y::Vector\n    \u0177::Vector\n\n    function r2score(y, \u0177)\n        squares = sum(y.^2)\n        residuals = sum(y - \u0177).^2\n        return 1 - residuals/squares\n    end\nend\n\nstruct binarycrossentropy{T<:AbstractFloat}\n    y::Vector\n    \u0177::Vector\n\n    function binarycrossentropy(y::Vector, \u0177::Vector)\n        \u03b5 = 1e-10\n        return -mean(y.*log2.(\u0177 .+ \u03b5) + (1 .- y).*log2.(1 .- \u0177 .+ \u03b5))\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\u0394Init = aInit - bInit\n\u0394Annual = aAnnual - bAnnual\n\u0394IRR(x) = \u0394Init + \u0394Annual * seriesPresentAmountFactor(x, N)\n\u0394IRR_ans = find_zero(\u0394IRR, 0.05)\n\nif \u0394IRR_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": "using KrylovMethods\nusing LinearOperators\nusing MatrixDepot\nusing Base.Test\n\nprintln(\"=== Testing LSQR ===\")\n\n# small test\nA   = [1 1; 0 -1; 1 0.]\nr1  = A[:,1]   # compatible\nr2  = randn(3) # incompatible\nr3  = [1;1;-1.] # in the nullpace of A'\n\nx1 = lsqr(A,r1,out=2,atol=1e-8,doBidiag=true,storeInterm=true)\n@test norm(x1[1][:,end]-[1;0])<1e-10\n@test x1[2]==1\nx2 = lsqr(A,r2,out=1,atol=1e-8)\n@test x2[2]==2\nx3 = lsqr(A,r3,out=2)\n@test all(x3[1].==0)\n\n\n# test with sparse random matrix\nA   = sprandn(100,10,.2)\nrhs = randn(100)\nxgt = full(A)\\rhs\nAf = (flag,x,a=0.0,v=0.0) -> ((flag=='F') ? A*x +a*v : A'*x+a*v)\n\nx1  = lsqr(LinearOperator(A),rhs,atol=1e-10,btol=1e-10,condlim=1e5,maxIter=10,out=1)\nx2  = lsqr(A,rhs,atol=1e-10,btol=1e-10,condlim=1e5,maxIter=10)\nx3  = lsqr(Af,rhs,atol=1e-10,btol=1e-10,condlim=1e5,maxIter=10)\n\n@test norm(xgt-x1[1])/norm(xgt) < 1e-6\n@test norm(xgt-x2[1])/norm(xgt) < 1e-6\n@test norm(xgt-x3[1])/norm(xgt) < 1e-6\n@test norm(x1[1]-x2[1])/norm(x1[1]) < 1e-12\n@test norm(x2[1]-x3[1])/norm(x3[1]) < 1e-12\n\n# test with dense hilbert matrix\nA   = matrixdepot(\"hilb\",3,3)\nrhs = [1;0;0.]\nxgt = A\\rhs\n\nx1  = lsqr(LinearOperator(A),rhs,atol=1e-10,btol=1e-10,condlim=1e5,maxIter=10)\nx2  = lsqr(A,rhs,atol=1e-10,btol=1e-10,condlim=1e5,maxIter=10)\n\n@test norm(xgt-x1[1])/norm(xgt) < 1e-6\n@test norm(xgt-x2[1])/norm(xgt) < 1e-6\n@test norm(x1[1]-x2[1])/norm(x1[1]) < 1e-12\nconA = norm(vec(A))*norm(vec(pinv(A)))\n@test norm(conA-x1[3][end,end])/conA < 1e-12\n@test norm(conA-x2[3][end,end])/conA < 1e-12\n\nprintln(\"=== LSQR: All tests passed. ===\")", "meta": {"hexsha": "0e72934d16d154ef2d74aa9600c3ce1d55312968", "size": 1559, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testLSQR.jl", "max_stars_repo_name": "Pbellive/KrylovMethods.jl", "max_stars_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_stars_repo_licenses": ["MIT"], "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/testLSQR.jl", "max_issues_repo_name": "Pbellive/KrylovMethods.jl", "max_issues_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_issues_repo_licenses": ["MIT"], "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/testLSQR.jl", "max_forks_repo_name": "Pbellive/KrylovMethods.jl", "max_forks_repo_head_hexsha": "5f2d111827b72e551cc84b9c7469a72c64e26b42", "max_forks_repo_licenses": ["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.8703703704, "max_line_length": 84, "alphanum_fraction": 0.6337395767, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7531376759499753}}
{"text": "\nfunction getwraparoundDFTfreqs(N::Int, fs::T, \u03bd_begin::T) where T\n\n    U0 = getDFTfreqrange(N, fs)\n    out, inds = wrapfreqrange(U0, \u03bd_begin, fs)\n\n    return U0, out, inds\nend\n\n\n# Assumes U0 is sorted in ascending order.\nfunction wrapfreqrange(U0, \u03bd_begin::T, fs::T) where T <: Real\n\n    N = length(U0)\n    ind = findfirst(xx->(xx>\u03bd_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, \u039b)::Complex{T} where T <: Real\n\n    # debug_array = zeros(Complex{T}, length(\u039b))\n    # debug_array2 = zeros(Complex{T}, length(\u039b))\n    # fs = 1/(\u039b[2]-\u039b[1])\n\n    running_sum = zero(T)\n    for i = 1:length(\u039b)\n        x = \u039b[i]\n\n        running_sum += h[i]*exp(-im*2*\u03c0*u*x)\n\n\n        # # debug.\n        # debug_array[i] = h[i]*exp(-im*2*\u03c0*u*x)\n        #\n        # #debug_array2[i] = h[i]*exp(-im*2*\u03c0*u*x +im*35*2*pi)\n        # debug_array2[i] = h[i]*exp(-im*2*\u03c0*(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": "\"plotVF!(fx,fy,x,y) plot vector field\"\r\nfunction plotVF!(p,fx::Function,fy::Function,xbase::Union{Array,UnitRange,StepRangeLen},ybase::Union{Array,UnitRange,StepRangeLen};map_speed = true,log_speed = false)\r\n\r\n\r\n    dxbase = xbase[2] - xbase[1]\r\n    dybase = ybase[2] - ybase[1]\r\n    dxybase = sqrt(dxbase^2+dybase^2)\r\n    cprod = collect.(collect(Base.product(xbase,ybase))) # not writing for-loop, use Cartesian product of x base and y base, cprod is a permutation set\r\n    cprod = vec(cprod)\r\n    x = map(x->x[1],cprod)\r\n    y = map(x->x[2],cprod)\r\n    dx=map(x->fx(x[1],x[2]),cprod)\r\n    dy=map(x->fy(x[1],x[2]),cprod)\r\n    speed = sqrt.(dx.^2 .+ dy.^2)#[sqrt(dx[i]^2+dy[i]^2) for i in 1:length(dx)]\r\n\r\n    if log_speed\r\n        speed = log.(speed)\r\n        dx=log.(dx)\r\n        dy = log.(dy)\r\n    end\r\n\r\n    #normalization\r\n    dx ./=maximum(abs.(dx))\r\n    dx .*=dxbase\r\n    dy ./=maximum(abs.(dy))\r\n    dy .*=dybase\r\n    #show(dx);show(dy)\r\n    #how(speed)\r\n\r\n    if map_speed\r\n        return quiver!(p,x,y,quiver = (dx,dy))#;markerstrokecolor = qcMap_def(speed))\r\n    end\r\n    return quiver!(p,x,y,quiver = (dx,dy))\r\nend\r\n\r\n\r\n#fx(x,y)=x;fy(x,y)=y\r\n#plotVF!(plot(),fx,fy,collect(-3:1.0:3),collect(-3:1.0:3))\r\n\r\n#quiver(1:10,1:10,quiver=(10:-1:1,10:-1:1),markerstrokecolor = qcMap_def(1:10))\r\n\r\n\"plotGradient!(p,x) - autonomous\"\r\nfunction plotGradient!(p,fx::Function,xbase;t = 0:1.0:5,map_speed = true,log_speed = false,normalize = true)\r\n    if t==Missing\r\n        t = 1:1.0:length(x)\r\n    end\r\n    dt = t[2]-t[1]\r\n    dx = xbase[2] - xbase[1]\r\n\r\n\r\n\r\n    if isinteger(t[1])\r\n        t = Float64.(t)\r\n    end\r\n    if isinteger(xbase[1])\r\n        xbase = Float64.(xbase)\r\n    end\r\n    \r\n    dtbase = t[2] - t[1]\r\n    dxbase = xbase[2] - xbase[1]\r\n    dbase = sqrt(dt^2+dt^2)\r\n    cprod = collect.(collect(Base.product(t,xbase))) # not writing for-loop, use Cartesian product of x base and y base, cprod is a permutation set\r\n    cprod = vec(cprod)\r\n    x = map(x->x[2],cprod)\r\n    t = map(x->x[1],cprod)\r\n    dt= repeat([dtbase],length(t))\r\n    dx=map(x->fx(x[2]),cprod)\r\n    speed = sqrt.(dt.^2 .+ dx.^2)#[sqrt(dt[i]^2+dx[i]^2) for i in 1:length(dt)]\r\n    \r\n    if log_speed\r\n        speed = log.(speed)\r\n        dt=log.(dt)\r\n        dx = log.(dx)\r\n    end\r\n    \r\n    #normalization\r\n    if normalize\r\n        dx ./=maximum(abs.(dx))\r\n        dx .*=dxbase\r\n        #shrinks t vec also so that gradient is preserved\r\n\r\n        dt ./=maximum(abs.(dx))\r\n        dt .*-dtbase\r\n    end\r\n    #show(dt);show(dx)\r\n    #how(speed)\r\n    \r\n    if map_speed\r\n        return quiver!(p,t,x,quiver = (dt,dx))#;markerstrokecolor = qcMap_def(speed))\r\n    end\r\n    return quiver!(p,t,x,quiver = (dt,dx))    \r\nend\r\n\r\n\r\n\"plotNullCline(fx,fy)\"\r\nfunction plotNullCline!(p,fx::Function,fy::Function,xbase,ybase;tol = 1e-3)\r\n    p=contour!(p,xbase,ybase,[fx(xi,yi) for yi in ybase, xi in xbase],levels = [-tol,tol],color = :red,alpha = .3)#,key = \"x NullCline est\")\r\n    p=contour!(p,xbase,ybase,[fy(xi,yi) for yi in ybase, xi in xbase],levels = [-tol,tol],color =:blue ,alpha = .3)#,key = \"y NullCline est\")\r\n    return p\r\nend\r\n\r\n#contour(1:2,1:2,[.11 .02;.1 0],levels = [-.1,.1])\r\n\r\n\r\n\r\n\"plotValongCycle!(p,fx::Function,fy::Function,cycle with r) works for 2d system only\"\r\nfunction plotValongCycle!(p,fx::Function,fy::Function,Cycle::Function;theta = 0.0:.3:2*pi)\r\n    xl = zeros(length(theta))\r\n    yl = similar(xl)\r\n    dxl =similar(yl)\r\n    dyl =similar(dxl)\r\n    for i in 1:length(theta)\r\n        err = \"\"\r\n        try\r\n            x,y = Cycle(theta[i])\r\n            xl[i] = x\r\n            yl[i] = y\r\n            dxl[i] = fx(x,y)\r\n            dyl[i] = fy(x,y)\r\n        catch err\r\n            println(\"Singularity?\")\r\n        end\r\n    end\r\n    p = quiver!(p,xl,yl,quiver = (dxl,dyl))\r\n    p = plot!(p,xl,yl;alpha = .3,key = false)\r\n    return p\r\nend\r\n\r\nfunction circularCycle(theta;center = (0.0,0.0),r = 1.0)\r\n    [center[1]+ r * cos(theta), center[2] + r * sin(theta) ]\r\nend\r\n\r\nfunction plotValongCycle!(p,fx::Function,fy::Function;r = 1.0,center = (0.0,0.0),theta = .3:.3:2*pi)\r\n    cycle(theta) = circularCycle(theta;center = center,r=r)\r\n    return plotValongCycle!(p,fx,fy,cycle;theta = .3:.3:2*pi)\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "916f29f6769b0dc584ff312d83674f77169a86be", "size": 4203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plotGradient.jl", "max_stars_repo_name": "HaoLi111/VisDyn.jl", "max_stars_repo_head_hexsha": "8efcb95e49ca35d0c902bc77055fdf4deca10493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-04T07:09:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T03:55:48.000Z", "max_issues_repo_path": "src/plotGradient.jl", "max_issues_repo_name": "HaoLi111/VisDyn.jl", "max_issues_repo_head_hexsha": "8efcb95e49ca35d0c902bc77055fdf4deca10493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plotGradient.jl", "max_forks_repo_name": "HaoLi111/VisDyn.jl", "max_forks_repo_head_hexsha": "8efcb95e49ca35d0c902bc77055fdf4deca10493", "max_forks_repo_licenses": ["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.2374100719, "max_line_length": 167, "alphanum_fraction": 0.5629312396, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7531376559889417}}
{"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# | \ud835\udf06\u2217 | -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 \u2248 [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": "using QuasiCopula, Random, Statistics, Test, LinearAlgebra, StatsFuns\nusing LinearAlgebra: BlasReal, copytri!\n### MVN only\n@testset \"Generate a 3 element random vector each with Y1, Y2, Y3 ~ Normal(5, 0.2). First we check the conditional mean and variance of Y2 | Y1 and then for Y3 | Y1, Y2. \" begin\nRandom.seed!(12345)\nmean_normal = 5\nvar_normal = 0.2\nd1 = Normal(mean_normal, var_normal)\nd2 = Normal(mean_normal, var_normal)\nd3 = Normal(mean_normal, var_normal)\n\nvecd = [d1, d2, d3]\nvariance_component_1 = 0.1\n\u0393 = variance_component_1 * ones(3, 3)\n\nnonmixed_multivariate_dist = NonMixedMultivariateDistribution(vecd, \u0393)\n\n#### Testing if the second element in the bivariate poisson follows correct mean and variance\n# preallocate Y and res to simulate and store\nn = 3\nY = Vector{Float64}(undef, n)\nres = Vector{Float64}(undef, n)\n\n# simulate Y1 first\ni = 1\n# form constants for Y1 pdf\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n# simulate Y1 and store it to Y[1]\nRandom.seed!(12345)\nY[i] = rand(nonmixed_multivariate_dist.gc_obs[i])\n# update residuals res[1] using Y[1] and the mean and variance (lambda for Poisson) using GLM package\nres[i] = update_res!(Y[i], res[i], nonmixed_multivariate_dist.gc_obs[i])\n\n# next, for conditional density of Y2 | Y1, form the constants for pdf\ni = 2\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n\n# pre allocate for sampling nsample times from conditional density\nRandom.seed!(12345)\nnsample = 10_000\n@info \"sample $nsample points for the conditional Normal distribution\"\ns = Vector{Float64}(undef, nsample)\nRandom.seed!(12345)\nrand!(nonmixed_multivariate_dist.gc_obs[i], s) # compile\nRandom.seed!(12345)\n@time rand!(nonmixed_multivariate_dist.gc_obs[i], s) # get time\n# 0.032922 seconds (1 allocation: 32 bytes)\nprintln(\"sample mean = $(Statistics.mean(s)); theoretical mean = $(mean(nonmixed_multivariate_dist.gc_obs[i]))\")\nprintln(\"sample var = $(Statistics.var(s)); theoretical var = $(var(nonmixed_multivariate_dist.gc_obs[i]))\")\n\n\n\n# conditional mean and variance of Y2 given Y1\n# sample mean = 5.005900458369502; theoretical mean = 5.002996732265867\n# sample var = 0.04316391761735573; theoretical var = 0.04362288747145726\n\n## now testing conditional Y3 given Y1, Y2\n# simulate Y2 first\ni = 2\n# form constants for Y1 pdf\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n# simulate Y1 and store it to Y[1]\nRandom.seed!(12345)\nY[i] = rand(nonmixed_multivariate_dist.gc_obs[i])\n# update residuals res[2] using Y[2] and the mean and variance (lambda for Poisson) using GLM package\nres[i] = update_res!(Y[i], res[i], nonmixed_multivariate_dist.gc_obs[i])\n\n# next, for conditional density of Y2 | Y1, form the constants for pdf\ni = 3\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n# pre allocate for sampling nsample times from conditional density\nRandom.seed!(12345)\nnsample = 10_000\n@info \"sample $nsample points for the conditional Normal distribution\"\ns = Vector{Float64}(undef, nsample)\nRandom.seed!(12345)\nrand!(nonmixed_multivariate_dist.gc_obs[i], s) # compile\nRandom.seed!(12345)\n@time rand!(nonmixed_multivariate_dist.gc_obs[i], s) # get time\n# 0.040553 seconds (1 allocation: 32 bytes)\nprintln(\"sample mean = $(Statistics.mean(s)); theoretical mean = $(mean(nonmixed_multivariate_dist.gc_obs[i]))\")\nprintln(\"sample var = $(Statistics.var(s)); theoretical var = $(var(nonmixed_multivariate_dist.gc_obs[i]))\")\n# conditional mean and variance of Y3 given Y1, Y2\n# sample mean = 5.006034080584214; theoretical mean = 5.003125498930692\n# sample var = 0.04331760554438279; theoretical var = 0.043778156954903835\n# rand(mvn_dist, Y, res)\nend\n\n### Poisson only\n@testset \"Generate a 3 element random vector each with Y1, Y2, Y3 ~ Poisson(5). First we check the conditional mean and variance of Y2 | Y1 and then for Y3 | Y1, Y2. \" begin\n# variance components\nRandom.seed!(12345)\n# simulate desired variance components (coefficients of covariance matrices V[k] for k in 1:m)\nmean1 = 5\nn = 3\nd1 = Poisson(mean1)\nd2 = Poisson(mean1)\nd3 = Poisson(mean1)\n\nvecd = [d1, d2, d3]\nrandom_intercept_1 = 0.1\n\u0393 = random_intercept_1 * ones(n, n)\n\nnonmixed_multivariate_dist = NonMixedMultivariateDistribution(vecd, \u0393)\n\n#### Testing if the second element in the bivariate poisson follows correct mean and variance\n# preallocate Y and res to simulate and store\nY = Vector{Float64}(undef, n)\nres = Vector{Float64}(undef, n)\n\n# simulate Y1 first\ni = 1\n# form constants for Y1 pdf\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n# simulate Y1 and store it to Y[1]\nRandom.seed!(12345)\nY[i] = rand(nonmixed_multivariate_dist.gc_obs[i])\n# update residuals res[1] using Y[1] and the mean and variance (lambda for Poisson) using GLM package\nres[i] = update_res!(Y[i], res[i], nonmixed_multivariate_dist.gc_obs[i])\n\n# next, for conditional density of Y2 | Y1, form the constants for pdf\ni = 2\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n\n# pre allocate for sampling nsample times from conditional density\nRandom.seed!(12345)\nnsample = 10_000\n@info \"sample $nsample points for the conditional Poisson distribution\"\ns = Vector{Int64}(undef, nsample)\nRandom.seed!(12345)\nrand!(nonmixed_multivariate_dist.gc_obs[i], s) # compile\nRandom.seed!(12345)\n@time rand!(nonmixed_multivariate_dist.gc_obs[i], s) # get time\n# 0.019684 seconds (50.00 k allocations: 12.207 MiB)\nprintln(\"sample mean = $(Statistics.mean(s)); theoretical mean = $(mean(nonmixed_multivariate_dist.gc_obs[i]))\")\nprintln(\"sample var = $(Statistics.var(s)); theoretical var = $(var(nonmixed_multivariate_dist.gc_obs[i]))\")\n# conditional mean and variance of Y2 given Y1\n# sample mean = 5.2485; theoretical mean = 5.219298245614036\n# sample var = 5.689716721672168; theoretical var = 5.6098030163127035\n\n## now testing conditional Y3 given Y1, Y2\n# simulate Y2 first\ni = 2\n# form constants for Y1 pdf\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n# simulate Y1 and store it to Y[1]\nRandom.seed!(12345)\nY[i] = rand(nonmixed_multivariate_dist.gc_obs[i])\n# update residuals res[2] using Y[2] and the mean and variance (lambda for Poisson) using GLM package\nres[i] = update_res!(Y[i], res[i], nonmixed_multivariate_dist.gc_obs[i])\n\n# next, for conditional density of Y2 | Y1, form the constants for pdf\ni = 3\nnonmixed_multivariate_dist.gc_obs[i] = pdf_constants(nonmixed_multivariate_dist.\u0393, res, i, nonmixed_multivariate_dist.vecd[i])\n# pre allocate for sampling nsample times from conditional density\nRandom.seed!(12345)\nnsample = 10_000\n@info \"sample $nsample points for the conditional Poisson distribution\"\ns = Vector{Int64}(undef, nsample)\nRandom.seed!(12345)\nrand!(nonmixed_multivariate_dist.gc_obs[i], s) # compile\nRandom.seed!(12345)\n@time rand!(nonmixed_multivariate_dist.gc_obs[i], s) # get time\n# 0.024654 seconds (50.00 k allocations: 12.207 MiB)\nprintln(\"sample mean = $(Statistics.mean(s)); theoretical mean = $(mean(nonmixed_multivariate_dist.gc_obs[i]))\")\nprintln(\"sample var = $(Statistics.var(s)); theoretical var = $(var(nonmixed_multivariate_dist.gc_obs[i]))\")\n# conditional mean and variance of Y3 given Y1, Y2\n# sample mean = 5.2381; theoretical mean = 5.206611570247935\n# sample var = 5.658774267426744; theoretical var = 5.577146369783474\nend\n\n@testset \"Form mixtures of different discrete and cts distributions. Generate 3 element vector: Y1 ~ Normal(5, 0.2), Y2 ~ Exponential(1/5), Y3 ~ Poisson(5) \" begin\nRandom.seed!(12345)\nmean_normal = -5\nvar_normal = 0.2\n\nd1 = Normal(mean_normal, var_normal)\nd2 = Exponential(-1/mean_normal)\nd3 = Poisson(exp(mean_normal))\n\nvc = 0.1\n\u0393 = vc * ones(3, 3)\n\nvecd = [d1, d2, d3]\nmixed_multivariate_dist = MultivariateMix(vecd, \u0393)\n\n# Y = Vector{Float64}(undef, n)\n# res = Vector{Float64}(undef, n)\n# rand(mixed_multivariate_dist, Y, res)\n#### Testing if the second element in the bivariate poisson follows correct mean and variance\n# preallocate Y and res to simulate and store\nn = 3\nY = Vector{Float64}(undef, n)\nres = Vector{Float64}(undef, n)\n\n# simulate Y1 first\ni = 1\n# form constants for Y1 pdf\nmixed_multivariate_dist.gc_obs[i] = pdf_constants(mixed_multivariate_dist.\u0393, res, i, mixed_multivariate_dist.vecd[i])\n# simulate Y1 and store it to Y[1]\nRandom.seed!(12345)\nY[i] = rand(mixed_multivariate_dist.gc_obs[i])\n# update residuals res[1] using Y[1] and the mean and variance (lambda for Poisson) using GLM package\nres[i] = update_res!(Y[i], res[i], mixed_multivariate_dist.gc_obs[i])\n\n# next, for conditional density of Y2 | Y1, form the constants for pdf\ni = 2\nmixed_multivariate_dist.gc_obs[i] = pdf_constants(mixed_multivariate_dist.\u0393, res, i, mixed_multivariate_dist.vecd[i])\n\n# pre allocate for sampling nsample times from conditional density\nRandom.seed!(12345)\nnsample = 10_000\n@info \"sample $nsample points for the conditional Exponential distribution\"\ns = Vector{Float64}(undef, nsample)\nRandom.seed!(12345)\nrand!(mixed_multivariate_dist.gc_obs[i], s) # compile\nRandom.seed!(12345)\n@time rand!(mixed_multivariate_dist.gc_obs[i], s) # get time\n# 0.030101 seconds (50.00 k allocations: 12.207 MiB)\nprintln(\"sample mean = $(Statistics.mean(s)); theoretical mean = $(mean(mixed_multivariate_dist.gc_obs[i]))\")\nprintln(\"sample var = $(Statistics.var(s)); theoretical var = $(var(mixed_multivariate_dist.gc_obs[i]))\")\n# conditional mean and variance of Y2 given Y1\n# sample mean = 0.2235739008006706; theoretical mean = 0.22115607164570328\n# sample var = 0.056128853458491966; theoretical var = 0.05527858504273324\n\n## now testing conditional Y3 given Y1, Y2\n# simulate Y2 first\ni = 2\n# form constants for Y1 pdf\nmixed_multivariate_dist.gc_obs[i] = pdf_constants(mixed_multivariate_dist.\u0393, res, i, mixed_multivariate_dist.vecd[i])\n# simulate Y2 and store it to Y[2]\nRandom.seed!(12345)\nY[i] = rand(mixed_multivariate_dist.gc_obs[i])\n# update residuals res[2] using Y[2] and the mean and variance (1/5 for Exponential) using GLM package\nres[i] = update_res!(Y[i], res[i], mixed_multivariate_dist.gc_obs[i])\n\n# next, for conditional density of Y2 | Y1, form the constants for pdf\ni = 3\nmixed_multivariate_dist.gc_obs[i] = pdf_constants(mixed_multivariate_dist.\u0393, res, i, mixed_multivariate_dist.vecd[i])\n# pre allocate for sampling nsample times from conditional density\nRandom.seed!(12345)\nnsample = 10_000\n@info \"sample $nsample points for the conditional Poisson distribution\"\ns = Vector{Int64}(undef, nsample)\nRandom.seed!(12345)\nrand!(mixed_multivariate_dist.gc_obs[i], s) # compile\nRandom.seed!(12345)\n@time rand!(mixed_multivariate_dist.gc_obs[i], s) # get time\n# 0.024654 seconds (50.00 k allocations: 12.207 MiB)\nprintln(\"sample mean = $(Statistics.mean(s)); theoretical mean = $(mean(mixed_multivariate_dist.gc_obs[i]))\")\nprintln(\"sample var = $(Statistics.var(s)); theoretical var = $(var(mixed_multivariate_dist.gc_obs[i]))\")\n# conditional mean and variance of Y3 given Y1, Y2\n# sample mean = 0.0562; theoretical mean = 0.05564357782888464\n# sample var = 0.053646924692469226; theoretical var = 0.0538934802364384\n#####\n\n\n### bivariate Poisson correlation and covariance\nmean1 = 5\nmean2 = 5\nd1 = Poisson(mean1)\nd2 = Poisson(mean2)\n\nvecd = [d1, d2]\n\u03931 = 0.1 * ones(2, 2)\n\u03932 = [0.1 -0.1; -0.1 0.1]\n\ngc_vec1 = NonMixedMultivariateDistribution(vecd, \u03931)\ngc_vec2 = NonMixedMultivariateDistribution(vecd, \u03932)\n\n\nnsample = 10_000\n@info \"sample $nsample independent vectors for the bivariate Poisson distribution\"\n# compile\nY_nsample1 = simulate_nobs_independent_vectors(gc_vec1, nsample)\nY_nsample2 = simulate_nobs_independent_vectors(gc_vec2, nsample)\n\nY_11 = [Y_nsample1[i, 1][1] for i in 1:nsample]\nY_12 = [Y_nsample1[i, 1][2] for i in 1:nsample]\nStatistics.cov(Y_11, Y_12)\n\n@show Statistics.cor(Y_11, Y_12)\n\nY_21 = [Y_nsample2[i, 1][1] for i in 1:nsample]\nY_22 = [Y_nsample2[i, 1][2] for i in 1:nsample]\nStatistics.cov(Y_21, Y_22)\n\n@show Statistics.cor(Y_21, Y_22)\n\n@test QuasiCopula.cov(gc_vec1, 1, 2) == -QuasiCopula.cov(gc_vec2, 1, 2)\n@test QuasiCopula.cor(gc_vec1, 1, 2) == -QuasiCopula.cor(gc_vec2, 1, 2)\n\n###\n# bivariate mixed normal and poisson with theoretical correlation ~\n##\nmean_normal = 5\nvar_normal = 0.2\n\nmean_poisson = 7\n\nd1 = Normal(mean_normal, var_normal)\nd2 = Poisson(mean_poisson)\n\nvc = 0.1\n\u03931 = [0.1 0.1; 0.1 0.1]\n\u03932 = [0.1 -0.1; -0.1 0.1]\n\nvecd = [d1, d2]\ngc_vec1 = MultivariateMix(vecd, \u03931)\ngc_vec2 = MultivariateMix(vecd, \u03932)\n\nnsample = 10_000\n@info \"sample $nsample independent vectors for the normal and poisson\"\n# compile\nY_nsample1 = simulate_nobs_independent_vectors(gc_vec1, nsample)\nY_nsample2 = simulate_nobs_independent_vectors(gc_vec2, nsample)\n\nY_11 = [Y_nsample1[i, 1][1] for i in 1:nsample]\nY_12 = [Y_nsample1[i, 1][2] for i in 1:nsample]\nStatistics.cov(Y_11, Y_12)\n\n@show Statistics.cor(Y_11, Y_12)\nQuasiCopula.cov(gc_vec1, 1, 2)\nQuasiCopula.cor(gc_vec1, 1, 2)\nprintln(\"sample cor = $(Statistics.cor(Y_11, Y_12)); theoretical cor = $(QuasiCopula.cor(gc_vec1, 1, 2))\")\nprintln(\"sample cov = $(Statistics.cov(Y_11, Y_12)); theoretical var = $(QuasiCopula.cov(gc_vec1, 1, 2))\")\n\n\nY_21 = [Y_nsample2[i, 1][1] for i in 1:nsample]\nY_22 = [Y_nsample2[i, 1][2] for i in 1:nsample]\nStatistics.cov(Y_21, Y_22)\n\n@show Statistics.cor(Y_21, Y_22)\n\nQuasiCopula.cov(gc_vec2, 1, 2)\nQuasiCopula.cor(gc_vec2, 1, 2)\nprintln(\"sample cor = $(Statistics.cor(Y_21, Y_22)); theoretical cor = $(QuasiCopula.cor(gc_vec2, 1, 2))\")\nprintln(\"sample cov = $(Statistics.cov(Y_21, Y_22)); theoretical var = $(QuasiCopula.cov(gc_vec2, 1, 2))\")\n\n\n@test QuasiCopula.cov(gc_vec1, 1, 2) == -QuasiCopula.cov(gc_vec2, 1, 2)\n@test QuasiCopula.cor(gc_vec1, 1, 2) == -QuasiCopula.cor(gc_vec2, 1, 2)\n####\n# mixed with normal and 0, 1\nmean_normal = 5\nvar_normal = 0.2\n\nmean_bernoulli = 0.5\n\nd1 = Normal(mean_normal, var_normal)\nd2 = Bernoulli(mean_bernoulli)\n\nvc = 0.1\n\u03931 = [0.1 0.1; 0.1 0.1]\n\u03932 = [0.1 -0.1; -0.1 0.1]\n\nvecd = [d1, d2]\ngc_vec1 = MultivariateMix(vecd, \u03931)\ngc_vec2 = MultivariateMix(vecd, \u03932)\n\nnsample = 10_000\n@info \"sample $nsample independent vectors for the mixed normal and binary bivariate\"\n# compile\nY_nsample1 = simulate_nobs_independent_vectors(gc_vec1, nsample)\nY_nsample2 = simulate_nobs_independent_vectors(gc_vec2, nsample)\n\nY_11 = [Y_nsample1[i, 1][1] for i in 1:nsample]\nY_12 = [Y_nsample1[i, 1][2] for i in 1:nsample]\n# @show Statistics.cov(Y_11, Y_12)\n\n# @show Statistics.cor(Y_11, Y_12)\n# @show QuasiCopula.cov(gc_vec1, 1, 2)\n# @show QuasiCopula.cor(gc_vec1, 1, 2)\nprintln(\"sample cor = $(Statistics.cor(Y_11, Y_12)); theoretical cor = $(QuasiCopula.cor(gc_vec1, 1, 2))\")\nprintln(\"sample cov = $(Statistics.cov(Y_11, Y_12)); theoretical var = $(QuasiCopula.cov(gc_vec1, 1, 2))\")\n\n\nY_21 = [Y_nsample2[i, 1][1] for i in 1:nsample]\nY_22 = [Y_nsample2[i, 1][2] for i in 1:nsample]\n# @show Statistics.cov(Y_21, Y_22)\n\n# @show Statistics.cor(Y_21, Y_22)\n\n# @show QuasiCopula.cov(gc_vec2, 1, 2)\n# @show QuasiCopula.cor(gc_vec2, 1, 2)\nprintln(\"sample cor = $(Statistics.cor(Y_21, Y_22)); theoretical cor = $(QuasiCopula.cor(gc_vec2, 1, 2))\")\nprintln(\"sample cov = $(Statistics.cov(Y_21, Y_22)); theoretical var = $(QuasiCopula.cov(gc_vec2, 1, 2))\")\n#\n\n@test QuasiCopula.cov(gc_vec1, 1, 2) == -QuasiCopula.cov(gc_vec2, 1, 2)\n@test QuasiCopula.cor(gc_vec1, 1, 2) == -QuasiCopula.cor(gc_vec2, 1, 2)\n\n\n# mixed with normal and 0, 1 with more noise in normal\nmean_normal = 5\nsd_normal = 0.2\n\nmean_bernoulli = 0.5\n\nd1 = Bernoulli(mean_bernoulli)\nd2 = Normal(mean_normal, sd_normal)\n\nvc = 0.1\n\u03931 = [0.1 0.1; 0.1 0.1]\n\u03932 = [0.1 -0.1; -0.1 0.1]\n\nvecd = [d1, d2]\ngc_vec1 = MultivariateMix(vecd, \u03931)\ngc_vec2 = MultivariateMix(vecd, \u03932)\n\nnsample = 10_000\n@info \"sample $nsample independent vectors for the mixed normal and binary bivariate\"\n# compile\nY_nsample1 = simulate_nobs_independent_vectors(gc_vec1, nsample)\nY_nsample2 = simulate_nobs_independent_vectors(gc_vec2, nsample)\n\nY_11 = [Y_nsample1[i, 1][1] for i in 1:nsample]\nY_12 = [Y_nsample1[i, 1][2] for i in 1:nsample]\n# @show Statistics.cov(Y_11, Y_12)\n\n# @show Statistics.cor(Y_11, Y_12)\n# @show QuasiCopula.cov(gc_vec1, 1, 2)\n# @show QuasiCopula.cor(gc_vec1, 1, 2)\nprintln(\"sample cor = $(Statistics.cor(Y_11, Y_12)); theoretical cor = $(QuasiCopula.cor(gc_vec1, 1, 2))\")\nprintln(\"sample cov = $(Statistics.cov(Y_11, Y_12)); theoretical cov = $(QuasiCopula.cov(gc_vec1, 1, 2))\")\n\n\nY_21 = [Y_nsample2[i, 1][1] for i in 1:nsample]\nY_22 = [Y_nsample2[i, 1][2] for i in 1:nsample]\n# @show Statistics.cov(Y_21, Y_22)\n\n# @show Statistics.cor(Y_21, Y_22)\n\n# @show QuasiCopula.cov(gc_vec2, 1, 2)\n# @show QuasiCopula.cor(gc_vec2, 1, 2)\nprintln(\"sample cor = $(Statistics.cor(Y_21, Y_22)); theoretical cor = $(QuasiCopula.cor(gc_vec2, 1, 2))\")\nprintln(\"sample cov = $(Statistics.cov(Y_21, Y_22)); theoretical cov = $(QuasiCopula.cov(gc_vec2, 1, 2))\")\n#\n\n@test QuasiCopula.cov(gc_vec1, 1, 2) == -QuasiCopula.cov(gc_vec2, 1, 2)\n@test QuasiCopula.cor(gc_vec1, 1, 2) == -QuasiCopula.cor(gc_vec2, 1, 2)\n\nend\n", "meta": {"hexsha": "89d11b04ee4cc3921bbbad16d2979cfa58f500be", "size": 17278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unit_test/generate_random_deviates/rand_multivariate.jl", "max_stars_repo_name": "OpenMendel/QuasiCopula.jl", "max_stars_repo_head_hexsha": "3addff703c63b158fcadff3ca52575b3b486b321", "max_stars_repo_licenses": ["MIT"], "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/unit_test/generate_random_deviates/rand_multivariate.jl", "max_issues_repo_name": "OpenMendel/QuasiCopula.jl", "max_issues_repo_head_hexsha": "3addff703c63b158fcadff3ca52575b3b486b321", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-17T20:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T20:44:08.000Z", "max_forks_repo_path": "test/unit_test/generate_random_deviates/rand_multivariate.jl", "max_forks_repo_name": "OpenMendel/QuasiCopula.jl", "max_forks_repo_head_hexsha": "3addff703c63b158fcadff3ca52575b3b486b321", "max_forks_repo_licenses": ["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.9144144144, "max_line_length": 177, "alphanum_fraction": 0.7440676004, "num_tokens": 5664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7531220177671318}}
{"text": "@inline function two_sum(a::T, b::T) where T<:AbstractFloat\n    ab =  a + b\n    B  = ab - a\n    \u03b5  = (a - (ab - B)) + (b - B)\n    return ab, \u03b5\nend\n\n@inline function two_diff(a::T, b::T) where T<:AbstractFloat\n    ab =  a - b\n    B  = ab - a\n    \u03b5  = (a - (ab - B)) + (b - B)\n    return ab, \u03b5\nend\n\n\n\"\"\"\n    fast_two_sum(x, y)::(a, b)\n\n{ ab  =  a + b,  \u03b5  = (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     \u03b5  =  b - B\n     return ab, \u03b5\nend\n\n\"\"\"\n    fast_two_diff(x, y)::(a, b)\n\n{ ab  =  a - b,  \u03b5  = (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     \u03b5  =  B - b\n     return ab, \u03b5\nend\n\n@inline function two_prod(a::T, b::T) where T<:AbstractFloat\n    ab =  a * b\n    \u03b5  = fma(a, b, -ab)\n    return ab, \u03b5\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\u2013242, 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\u2095\u1d62 = z - (z - x)\n    z\u2097\u2092 = x - z\u2095\u1d62\n    return z\u2095\u1d62, z\u2097\u2092\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": "@testset \"partial\" begin\n\n@testset \"create_\u2202 and apply_\u2202!, 1D\" begin\n    N = (10,)\n    M = prod(N)\n\n    Fu = rand(N...)\n    Gv = similar(Fu)\n    gv = zeros(M)\n\n    Mask = similar(Fu)  # masking array\n    for nw = 1:1\n        sub = Vector{Int}(undef, 1)\n        sub\u2032 = Vector{Int}(undef, 1)\n\n        Nw = N[nw]\n        \u2206w\u207b\u00b9 = rand(Nw)\n\n        for ns = (-1,1), isbloch = (true,false)  # (backward,forward difference), (Bloch,symmetric)\n            \u2202ws = spzeros(M,M)\n\n            for ind = 1:M\n                sub .= CartesianIndices(N)[ind].I  # subscripts of diagonal entry\n                indw = sub[nw]\n                \u2206w\u1d62\u207b\u00b9 = \u2206w\u207b\u00b9[indw]\n                \u2202ws[ind,ind] = -ns * \u2206w\u1d62\u207b\u00b9  # diagonal entries\n\n                # Calculate the column index of the off-diagonal entry in the row `ind`.\n                sub\u2032 .= sub  # subscripts of off-diagonal entry\n                if ns == 1  # forward difference\n                    if sub\u2032[nw] == Nw\n                        sub\u2032[nw] = 1\n                    else\n                        sub\u2032[nw] += 1\n                    end\n                else  # backward difference\n                    if sub\u2032[nw] == 1\n                        sub\u2032[nw] = Nw\n                    else\n                        sub\u2032[nw] -= 1\n                    end\n                end\n\n                ind\u2032 = LinearIndices(N)[sub\u2032...]\n                \u2202ws[ind, ind\u2032] += ns * \u2206w\u1d62\u207b\u00b9  # off-diagonal entry\n            end\n\n            if !isbloch  # symmetry boundary\n                # Initialize the masking array.\n                Mask .= 1\n                Mask[Base.setindex(axes(Mask), 1, nw)...] = 0  # not .= 0 unlike code for 2D and 3D\n                if ns == 1  # forward difference\n                    # The input fields at the symmetry boundary should be zero, so apply the\n                    # mask to the input field.\n                    \u2202ws = \u2202ws * spdiagm(0=>Mask[:])\n                else  # backward difference\n                    # The output fields at the symmetry boundary should be zero, so apply\n                    # mask to the output field.\n                    \u2202ws = spdiagm(0=>Mask[:]) * \u2202ws\n                end\n            end\n\n            # Test create_\u2202.\n            @test create_\u2202(nw, ns==1, [N...], \u2206w\u207b\u00b9, isbloch) == \u2202ws\n\n            # Test apply_\u2202!.\n            fu = Fu[:]\n            mul!(gv, \u2202ws, fu)\n            apply_\u2202!(Gv, Fu, Val(:(=)), nw, ns==1, \u2206w\u207b\u00b9, isbloch)\n            @test Gv[:] \u2248 gv\n\n            # print(\"matrix: \"); @btime mul!($gv, $\u2202ws, $fu)\n            # print(\"matrix-free: \"); @btime apply_\u2202!($Gv, $Fu, $nw, $ns==1, $\u2206w\u207b\u00b9)\n            # println()\n        end\n    end\nend  # @testset \"create_\u2202 and apply_\u2202!, 1D\"\n\n@testset \"create_\u2202 and apply_\u2202!, 2D\" begin\n    N = (8,9)\n    M = prod(N)\n\n    Fu = rand(N...)\n    Gv = similar(Fu)\n    gv = zeros(M)\n\n    Mask = similar(Fu)  # masking array\n    for nw = 1:2\n        sub = Vector{Int}(undef, 2)\n        sub\u2032 = Vector{Int}(undef, 2)\n\n        Nw = N[nw]\n        \u2206w\u207b\u00b9 = rand(Nw)\n\n        for ns = (-1,1), isbloch = (true,false)  # (backward,forward difference), (Bloch,symmetric)\n            \u2202ws = spzeros(M,M)\n\n            for ind = 1:M\n                sub .= CartesianIndices(N)[ind].I  # subscripts of diagonal entry\n                indw = sub[nw]\n                \u2206w\u1d62\u207b\u00b9 = \u2206w\u207b\u00b9[indw]\n                \u2202ws[ind,ind] = -ns * \u2206w\u1d62\u207b\u00b9  # diagonal entries\n\n                # Calculate the column index of the off-diagonal entry in the row `ind`.\n                sub\u2032 .= sub  # subscripts of off-diagonal entry\n                if ns == 1  # forward difference\n                    if sub\u2032[nw] == Nw\n                        sub\u2032[nw] = 1\n                    else\n                        sub\u2032[nw] += 1\n                    end\n                else  # backward difference\n                    if sub\u2032[nw] == 1\n                        sub\u2032[nw] = Nw\n                    else\n                        sub\u2032[nw] -= 1\n                    end\n                end\n\n                ind\u2032 = LinearIndices(N)[sub\u2032...]\n                \u2202ws[ind, ind\u2032] += ns * \u2206w\u1d62\u207b\u00b9  # off-diagonal entry\n            end\n\n            if !isbloch  # symmetry boundary\n                # Initialize the masking array.\n                Mask .= 1\n                Mask[Base.setindex(axes(Mask), 1, nw)...] .= 0\n                if ns == 1  # forward difference\n                    # The input fields at the symmetry boundary should be zero, so apply the\n                    # mask to the input field.\n                    \u2202ws = \u2202ws * spdiagm(0=>Mask[:])\n                else  # backward difference\n                    # The output fields at the symmetry boundary should be zero, so apply\n                    # mask to the output field.\n                    \u2202ws = spdiagm(0=>Mask[:]) * \u2202ws\n                end\n            end\n\n            # Test create_\u2202.\n            @test create_\u2202(nw, ns==1, [N...], \u2206w\u207b\u00b9, isbloch) == \u2202ws\n\n            # Test apply_\u2202!.\n            fu = Fu[:]\n            mul!(gv, \u2202ws, fu)\n            apply_\u2202!(Gv, Fu, Val(:(=)), nw, ns==1, \u2206w\u207b\u00b9, isbloch)\n            @test Gv[:] \u2248 gv\n\n            # print(\"matrix: \"); @btime mul!($gv, $\u2202ws, $fu)\n            # print(\"matrix-free: \"); @btime apply_\u2202!($Gv, $Fu, $nw, $ns==1, $\u2206w\u207b\u00b9)\n            # println()\n        end\n    end\nend  # @testset \"create_\u2202 and apply_\u2202!, 2D\"\n\n@testset \"create_\u2202 and apply_\u2202!, 3D\" begin\n    N = (8,9,10)\n    M = prod(N)\n\n    Fu = rand(N...)\n    Gv = similar(Fu)\n    gv = zeros(M)\n\n    Mask = similar(Fu)  # masking array\n    for nw = 1:3\n        sub = Vector{Int}(undef, 3)\n        sub\u2032 = Vector{Int}(undef, 3)\n\n        Nw = N[nw]\n        \u2206w\u207b\u00b9 = rand(Nw)\n\n        for ns = (-1,1), isbloch = (true,false)  # (backward,forward difference), (Bloch,symmetric)\n            \u2202ws = spzeros(M,M)\n\n            for ind = 1:M\n                sub .= CartesianIndices(N)[ind].I  # subscripts of diagonal entry\n                indw = sub[nw]\n                \u2206w\u1d62\u207b\u00b9 = \u2206w\u207b\u00b9[indw]\n                \u2202ws[ind,ind] = -ns * \u2206w\u1d62\u207b\u00b9  # diagonal entries\n\n                # Calculate the column index of the off-diagonal entry in the row `ind`.\n                sub\u2032 .= sub  # subscripts of off-diagonal entry\n                if ns == 1  # forward difference\n                    if sub\u2032[nw] == Nw\n                        sub\u2032[nw] = 1\n                    else\n                        sub\u2032[nw] += 1\n                    end\n                else  # backward difference\n                    if sub\u2032[nw] == 1\n                        sub\u2032[nw] = Nw\n                    else\n                        sub\u2032[nw] -= 1\n                    end\n                end\n\n                ind\u2032 = LinearIndices(N)[sub\u2032...]\n                \u2202ws[ind, ind\u2032] += ns * \u2206w\u1d62\u207b\u00b9  # off-diagonal entry\n            end\n\n            if !isbloch  # symmetry boundary\n                # Initialize the masking array.\n                Mask .= 1\n                Mask[Base.setindex(axes(Mask), 1, nw)...] .= 0\n                if ns == 1  # forward difference\n                    # The input fields at the symmetry boundary should be zero, so apply the\n                    # mask to the input field.\n                    \u2202ws = \u2202ws * spdiagm(0=>Mask[:])\n                else  # backward difference\n                    # The output fields at the symmetry boundary should be zero, so apply\n                    # mask to the output field.\n                    \u2202ws = spdiagm(0=>Mask[:]) * \u2202ws\n                end\n            end\n\n            # Test create_\u2202.\n            @test create_\u2202(nw, ns==1, [N...], \u2206w\u207b\u00b9, isbloch) == \u2202ws\n\n            # Test apply_\u2202!.\n            fu = Fu[:]\n            mul!(gv, \u2202ws, fu)\n            apply_\u2202!(Gv, Fu, Val(:(=)), nw, ns==1, \u2206w\u207b\u00b9, isbloch)\n            @test Gv[:] \u2248 gv\n\n            # print(\"matrix: \"); @btime mul!($gv, $\u2202ws, $fu)\n            # print(\"matrix-free: \"); @btime apply_\u2202!($Gv, $Fu, $nw, $ns==1, $\u2206w\u207b\u00b9)\n            # println()\n        end\n    end\nend  # @testset \"create_\u2202 and apply_\u2202!, 3D\"\n\nend  # @testset \"differential\"\n", "meta": {"hexsha": "01468f559cf9f7d9b775c0a4b1f4b4509127f73a", "size": 7918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/partial.jl", "max_stars_repo_name": "wsshin/StaggeredGridCalculus.jl", "max_stars_repo_head_hexsha": "c9530e1c3e7dc32d67642eb140e1bb58df8d3ca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-11-03T23:16:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:07:22.000Z", "max_issues_repo_path": "test/partial.jl", "max_issues_repo_name": "wsshin/StaggeredGridCalculus.jl", "max_issues_repo_head_hexsha": "c9530e1c3e7dc32d67642eb140e1bb58df8d3ca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-02T02:05:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T16:02:20.000Z", "max_forks_repo_path": "test/partial.jl", "max_forks_repo_name": "wsshin/StaggeredGridCalculus.jl", "max_forks_repo_head_hexsha": "c9530e1c3e7dc32d67642eb140e1bb58df8d3ca5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-01T20:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:07:27.000Z", "avg_line_length": 34.1293103448, "max_line_length": 99, "alphanum_fraction": 0.4184137408, "num_tokens": 2340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "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": "# Quadratic Costs\nn,m = 3,2\nQ = Diagonal(@SVector fill(0.1, n))\nR = Diagonal(@SVector fill(0.01, m))\nQf = Diagonal(@SVector fill(10., n))\nxf = @SVector ones(n)\n\nquadcost = QuadraticCost(Q,R)\n@test quadcost.Q == Q\n@test quadcost.q == zeros(n)\n@test quadcost.R == R\n@test quadcost.r == zeros(m)\n@test quadcost.c == 0\n@test state_dim(quadcost) == n\n@test control_dim(quadcost) == m\n\nquadcost = LQRCost(Q,R,xf)\n@test quadcost.Q == Q\n@test quadcost.q == -Q*xf\n@test quadcost.R == R\n@test quadcost.r == zeros(m)\n@test quadcost.c == 0.5*xf'Q*xf\n\nquadcost = TO.LQRCostTerminal(Q,xf)\n@test quadcost.Q == Q\n@test quadcost.q == -Q*xf\n@test isempty(quadcost.R)\n@test isempty(quadcost.r)\n@test quadcost.c == 0.5*xf'Q*xf\n\nq = @SVector rand(n)\nquadcost = QuadraticCost(Q,q,0.5)\n@test quadcost.Q == Q\n@test quadcost.q == q\n@test isempty(quadcost.R)\n@test isempty(quadcost.r)\n@test quadcost.c == 0.5\n\nQ2 = Diagonal(@SVector [-1, 0.1, 0.2])\nR2 = Diagonal(@SVector [0, 0.1])\n@test_throws ArgumentError QuadraticCost(Q2,R)\n@test_logs (:warn, \"R is not positive definite\") QuadraticCost(Q,R2)\n", "meta": {"hexsha": "bf7031416026dc83c80c50865ac0fe0a2ab3f653", "size": 1072, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cost_tests.jl", "max_stars_repo_name": "VladimirIvan/TrajectoryOptimization.jl", "max_stars_repo_head_hexsha": "cd767261f6d3060057d8d780d2ec87b6cd09b11f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-24T16:40:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T16:40:30.000Z", "max_issues_repo_path": "test/cost_tests.jl", "max_issues_repo_name": "VladimirIvan/TrajectoryOptimization.jl", "max_issues_repo_head_hexsha": "cd767261f6d3060057d8d780d2ec87b6cd09b11f", "max_issues_repo_licenses": ["MIT"], "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/cost_tests.jl", "max_forks_repo_name": "VladimirIvan/TrajectoryOptimization.jl", "max_forks_repo_head_hexsha": "cd767261f6d3060057d8d780d2ec87b6cd09b11f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-24T16:40:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-24T16:40:35.000Z", "avg_line_length": 24.9302325581, "max_line_length": 68, "alphanum_fraction": 0.677238806, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7530558389457316}}
{"text": "using DiffEqBayes, OrdinaryDiffEq, ParameterizedFunctions,\n      RecursiveArrayTools, Distributions, Test\n\nprintln(\"One parameter case\")\nf1 = @ode_def 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,p)\nsol = solve(prob1,Tsit5())\nt = collect(range(1,stop=10,length=50))\nrandomized = VectorOfArray([(sol(t[i]) + .01randn(2)) for i in 1:length(t)])\ndata = convert(Array,randomized)\npriors = [truncated(Normal(1.5,0.1),1.0,1.8)]\n\nbayesian_result = stan_inference(prob1,t,data,priors;num_samples=300,\n                                 num_warmups=500,likelihood=Normal)\n\n@test mean(get(bayesian_result.chains,:theta_1)[1]) \u2248 1.5 atol=3e-1\n\n# Test norecompile\nbayesian_result2 = stan_inference(prob1,t,data,priors,bayesian_result.model;\n                                  num_samples=300,num_warmups=500,likelihood=Normal)\n\n@test mean(get(bayesian_result2.chains,:theta_1)[1]) \u2248 1.5 atol=3e-1\n\npriors = [truncated(Normal(1.,0.01),0.5,2.0),truncated(Normal(1.,0.01),0.5,2.0),truncated(Normal(1.5,0.01),1.0,2.0)]\nbayesian_result = stan_inference(prob1,t,data,priors;num_samples=300,\n                                 num_warmups=500,likelihood=Normal,sample_u0=true)\n\n@test mean(get(bayesian_result.chains,:theta_1)[1]) \u2248 1. atol=3e-1\n@test mean(get(bayesian_result.chains,:theta_2)[1]) \u2248 1. atol=3e-1\n@test mean(get(bayesian_result.chains,:theta_3)[1]) \u2248 1.5 atol=3e-1\n\nsol = solve(prob1,Tsit5(),save_idxs=[1])\nrandomized = VectorOfArray([(sol(t[i]) + .01 * randn(1)) for i in 1:length(t)])\ndata = convert(Array,randomized)\npriors = [truncated(Normal(1.5,0.1),0.5,2)]\nbayesian_result = stan_inference(prob1,t,data,priors;num_samples=300,\n                                 num_warmups=500,likelihood=Normal,save_idxs=[1])\n\n@test mean(get(bayesian_result.chains,:theta_1)[1]) \u2248 1.5 atol=3e-1\n\n\npriors = [truncated(Normal(1.,0.01),0.5,2),truncated(Normal(1.5,0.01),0.5,2)]\nbayesian_result = stan_inference(prob1,t,data,priors;num_samples=300,\n                                 num_warmups=500,likelihood=Normal,save_idxs=[1],sample_u0=true)\n\n@test mean(get(bayesian_result.chains,:theta_1)[1]) \u2248 1. atol=3e-1\n@test mean(get(bayesian_result.chains,:theta_2)[1]) \u2248 1.5 atol=3e-1\n\nprintln(\"Four parameter case\")\nf1 = @ode_def begin\n  dx = a*x - b*x*y\n  dy = -c*y + d*x*y\nend a b c d\nu0 = [1.0,1.0]\ntspan = (0.0,10.0)\np = [1.5,1.0,3.0,1.0]\nprob1 = ODEProblem(f1,u0,tspan,p)\nsol = solve(prob1,Tsit5())\nt = collect(range(1,stop=10,length=50))\nrandomized = VectorOfArray([(sol(t[i]) + .01randn(2)) for i in 1:length(t)])\ndata = convert(Array,randomized)\npriors = [truncated(Normal(1.5,0.01),0.5,2),truncated(Normal(1.0,0.01),0.5,1.5),\n          truncated(Normal(3.0,0.01),0.5,4),truncated(Normal(1.0,0.01),0.5,2)]\n\nbayesian_result = stan_inference(prob1,t,data,priors;num_samples=100,num_warmups=500,vars =(DiffEqBayes.StanODEData(),InverseGamma(4,1)))\n@test mean(get(bayesian_result.chains,:theta_1)[1]) \u2248 1.5 atol=1e-1\n@test mean(get(bayesian_result.chains,:theta_2)[1]) \u2248 1.0 atol=1e-1\n@test mean(get(bayesian_result.chains,:theta_3)[1]) \u2248 3.0 atol=1e-1\n@test mean(get(bayesian_result.chains,:theta_4)[1]) \u2248 1.0 atol=1e-1\n", "meta": {"hexsha": "5cdf2ffc8a98366f5472cf05bee8b313bf0d6d0e", "size": 3176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/stan.jl", "max_stars_repo_name": "JuliaDiffEq/BayesDiffEq.jl", "max_stars_repo_head_hexsha": "3f1da73c0e999e3198bb7e59f31ef2e1771bddf4", "max_stars_repo_licenses": ["MIT"], "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/stan.jl", "max_issues_repo_name": "JuliaDiffEq/BayesDiffEq.jl", "max_issues_repo_head_hexsha": "3f1da73c0e999e3198bb7e59f31ef2e1771bddf4", "max_issues_repo_licenses": ["MIT"], "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/stan.jl", "max_forks_repo_name": "JuliaDiffEq/BayesDiffEq.jl", "max_forks_repo_head_hexsha": "3f1da73c0e999e3198bb7e59f31ef2e1771bddf4", "max_forks_repo_licenses": ["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.7894736842, "max_line_length": 137, "alphanum_fraction": 0.6772670025, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7530558336486511}}
{"text": "\"\"\"\n    eom_var1(x, p, n) -> Function\n\nEquations of motion for a vector autoregressive system where X\u2081 \u2192 X\u2082 \u2192 X\u2083.\n\"\"\"\nfunction eom_var1(x, p, n)\n    \u03c3\u2081, \u03c3\u2082, \u03c3\u2083 = p[1], p[2], p[3]\n    x\u2081, x\u2082, x\u2083 = x[1], x[2], x[3]\n    \u03b8 = rand(Normal(0, \u03c3\u2081))\n    \u03b7 = rand(Normal(0, \u03c3\u2082))\n    \u03f5 = rand(Normal(0, \u03c3\u2083))\n\n    dx\u2081 = \u03b8\n    dx\u2082 = x\u2081 * \u03b7\n    dx\u2083 = 0.5*x\u2083 * x\u2082 + \u03f5\n    return SVector{3}(dx\u2081, dx\u2082, dx\u2083)\nend\n\nfunction var1(u\u1d62, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083)\n    p = [\u03c3\u2081, \u03c3\u2082, \u03c3\u2083]\n    DiscreteDynamicalSystem(eom_var1, u\u1d62, p)\nend\n\n\"\"\"\n    var1(x, p, n) -> DiscreteDynamicalSystem\n\nInitialise a discrete vector autoregressive system where X\u2081 \u2192 X\u2082 \u2192 X\u2083.\n\"\"\"\nvar1(;u\u1d62 = rand(3), \u03c3\u2081 = 1.0, \u03c3\u2082 = 0.2, \u03c3\u2083 = 0.3) = var1(u\u1d62, \u03c3\u2081, \u03c3\u2082, \u03c3\u2083)\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    \ud835\udfd9 \u2297 \ud835\udfd9 \u2297 ... \u2297 op_i \u2297 \ud835\udfd9 \u2297 ... \u2297 op_j \u2297 \ud835\udfd9 \u2297 ... \u2297 \ud835\udfd9\n\nexample: spin-spin correlation function\n\nwe can construct \u27e8\u03c3\u1dbb\u1d62\u03c3\u1dbb\u2c7c\u27e9 on a 12 site lattice as\n    \u03c3\u1dbb = [1 0; 0 -1]\n    two_point_correlator(i=>\u03c3\u1dbb, j=>\u03c3\u1dbb, 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": "using Random\n\n# TODO: use Macros and Symbols\n\nfunction divide_on_feature(x, idx, threshold)\n    \"\"\"\n    Divide dataset based on if sample value on feature index is larger than\n    the given threshold\n    \"\"\"\n\n    x1, x2 = [], []\n\n    for i in 1:size(x, 1)\n        if x[i, idx] >= threshold\n            push!(x1, x[i,:]')\n        else\n            push!(x2, x[i,:]')\n        end\n    end\n\n    return vcat(x1...), vcat(x2...)\n\nend\n\nfunction sample(data::Array{T,2}, n::Int64; seed=123::Int64) where T <: Any\n    # TODO: accept seed!\n    n_samples = size(data, 1)\n\n    # Shuffle data\n    idx = shuffle(MersenneTwister(seed), 1:n_samples)\n    data = data[idx, :]\n\n    data[1:n, :]\nend\n\nfunction split_data(data, fraction)\n    n_samples = size(data, 1)\n\n    # Suffle data\n    shuffle!(data)\n\n    s = round(Integer, n_samples * fraction)\n\n    return data[1:s, :], data[s:end, :]\nend\n\n# From https://bit.ly/2QnEacc\n\nfunction entropy(y::AbstractArray)\n    \"\"\" Calculate the entropy of label array y \"\"\"\n    unique_labels = unique(y)\n    e = 0\n    n = length(y)\n\n    for label in unique_labels\n        c = length(filter(x-> x==label, y))\n        p = c / n\n        e += -p * log2(p)\n    end\n\n    return e\nend\n\n\nfunction gini_index(y::AbstractArray)\n    \"\"\" Calculate the Gini index of label array y \"\"\"\n    unique_labels = unique(y)\n    e = 0\n    n = length(y)\n\n    for label in unique_labels\n        c = length(filter(x-> x==label, y))\n        p = c / n\n        e += p^2\n    end\n\n    return 1 - e\nend\n\nfunction classification_error(y::AbstractArray)\n    \"\"\" Calculate the Classification Error of label array y \"\"\"\n    unique_labels = unique(y)\n    pp = []\n    n = length(y)\n\n    for label in unique_labels\n        c = length(filter(x-> x==label, y))\n        p = c / n\n        push!(pp, p)\n    end\n\n    return 1 - max(pp)\nend\n\n\nfunction modes(values)\n    # From https://rosettacode.org/wiki/Averages/Mode#Julia\n    dict = Dict() # Values => Number of repetitions\n    modesArray = typeof(values[1])[] # Array of the modes so far\n    max = 0 # Max of repetitions so far\n\n    for v in values\n        # Add one to the dict[v] entry (create one if none)\n        if v in keys(dict)\n            dict[v] += 1\n        else\n            dict[v] = 1\n        end\n\n        # Update modesArray if the number of repetitions\n        # of v reaches or surpasses the max value\n        if dict[v] >= max\n            if dict[v] > max\n                empty!(modesArray)\n                max += 1\n            end\n            append!(modesArray, [v])\n        end\n    end\n\n    return modesArray\nend\n\nfunction count_distinct(seq)\n    dict = Dict{Any, Int64}();\n    for item in seq\n        if !haskey(dict, item)\n            dict[item] = 0;\n        end\n        dict[item] += 1\n    end\n\n    dict\nend\n", "meta": {"hexsha": "5ffdcd005ad6cd93124d5f75a117293a03eb0d19", "size": 2759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "leferrad/Ensemblearn.jl", "max_stars_repo_head_hexsha": "323bd2d8b8d2636ca4137745ba785ad55a7f3e2a", "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": "leferrad/Ensemblearn.jl", "max_issues_repo_head_hexsha": "323bd2d8b8d2636ca4137745ba785ad55a7f3e2a", "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": "leferrad/Ensemblearn.jl", "max_forks_repo_head_hexsha": "323bd2d8b8d2636ca4137745ba785ad55a7f3e2a", "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.437037037, "max_line_length": 75, "alphanum_fraction": 0.5549111997, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7530509314271925}}
{"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": "using Test\n\n@testset \"Dirichlet0 Boundary Conditions\" begin\n    N = 100\n    h_inv = 1/(N-1)\n    d_order = 2\n    approx_order = 2\n    x = collect(1:h_inv:N).^2\n    A = DerivativeOperator{Float64}(2,2,1/99,length(x),:Dirichlet0,:Dirichlet0,BC=(0.0,0.0))\n    boundary_points = A.boundary_point_count\n    res = A*x\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 2.0*ones(N - sum(boundary_points));\n\n    N = 1000\n    d_order = 4\n    approx_order = 10\n    y = collect(1:1.0:N).^4 .- 2*collect(1:1.0:N).^3 .+ collect(1:1.0:N).^2;\n    A = DerivativeOperator{Float64}(d_order,approx_order,1.0,N,:Dirichlet0,:Dirichlet0,BC=(0.0,0.0))\n    boundary_points = A.boundary_point_count\n    res = A*y\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 24.0*ones(N - sum(boundary_points)) atol=10.0^-1; # Float64 is less stable\n\n    A = DerivativeOperator{BigFloat}(d_order,approx_order,one(BigFloat),N,:Dirichlet0,:Dirichlet0,BC=(0.0,0.0))\n    y = convert(Array{BigFloat, 1}, y)\n    res = A*y\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 24.0*ones(N - sum(boundary_points)) atol=10.0^(-approx_order);\nend\n\n\n\n@testset \"Dirichlet0 Boundary Conditions irregular grid\" begin\n    # tests as for DerivativeOperator, but with arbitrary grid (increasing step size):\n    N = 1000\n    d_order = 2\n    approx_order = 2\n    x = (1.:1.:N)*2.0 #erf.(linspace(-2,2,N))*N/2;\n    dx = diff(x)\n    y = x.^2\n\n    A = FiniteDifference{Float64}(2,2,dx,length(x),:Dirichlet0,:Dirichlet0,BC=(0.0,0.0))\n    boundary_points = A.boundary_point_count\n    res = A*y\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 2.0*ones(N - sum(boundary_points));\n\n    # N = 1000\n    d_order = 4\n    approx_order = 10\n    # dx = rand(N)\n    # x = [0.0; cumsum(dx)]\n    y = @. x.^4 - 2*x.^3 + x.^2\n    A = FiniteDifference{Float64}(d_order,approx_order,dx,N,:Dirichlet0,:Dirichlet0,BC=(0.0,0.0))\n    boundary_points = A.boundary_point_count\n    res = A*y\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 24.0*ones(N - sum(boundary_points)) atol=10.0^(-1); # Float64 is less stable\n\n    A = FiniteDifference{BigFloat}(d_order,approx_order,BigFloat.(dx),N,:Dirichlet0,:Dirichlet0,BC=(0.0,0.0))\n    y = convert(Array{BigFloat, 1}, y)\n    res = A*y\n    @test res[boundary_points[1] + 1: N - boundary_points[2]] \u2248 24.0*ones(N - sum(boundary_points)) atol=10.0^(-approx_order);\n\n\n\nend\n", "meta": {"hexsha": "af81c3a72d6f004778f47cccfe8476f4f2614b43", "size": 2398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dirichlet.jl", "max_stars_repo_name": "npbarnes/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a74ffa8b353c9c4857374e8016b4599eea5ce0c0", "max_stars_repo_licenses": ["MIT"], "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/dirichlet.jl", "max_issues_repo_name": "npbarnes/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a74ffa8b353c9c4857374e8016b4599eea5ce0c0", "max_issues_repo_licenses": ["MIT"], "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/dirichlet.jl", "max_forks_repo_name": "npbarnes/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a74ffa8b353c9c4857374e8016b4599eea5ce0c0", "max_forks_repo_licenses": ["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.46875, "max_line_length": 140, "alphanum_fraction": 0.6451209341, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7530071423217546}}
{"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\u00b2::Real) = exp(-d\u00b2 / 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(; \u03b3::Real=2.0)\n\n\u03b3-exponential kernel with parameter `\u03b3`.\n\n# Definition\n\nFor inputs ``x, x' \\\\in \\\\mathbb{R}^d``, the \u03b3-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\u03b3<:Real} <: SimpleKernel\n    \u03b3::Vector{T\u03b3}\n    function GammaExponentialKernel(; gamma::Real=2.0, \u03b3::Real=gamma)\n        @check_args(GammaExponentialKernel, \u03b3, zero(\u03b3) < \u03b3 \u2264 2, \"\u03b3 \u2208 (0, 2]\")\n        return new{typeof(\u03b3)}([\u03b3])\n    end\nend\n\n@functor GammaExponentialKernel\n\nkappa(\u03ba::GammaExponentialKernel, d::Real) = exp(-d^first(\u03ba.\u03b3))\n\nmetric(::GammaExponentialKernel) = Euclidean()\n\niskroncompatible(::GammaExponentialKernel) = true\n\nfunction Base.show(io::IO, \u03ba::GammaExponentialKernel)\n    return print(io, \"Gamma Exponential Kernel (\u03b3 = \", first(\u03ba.\u03b3), \")\")\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(-\u03bc))`.\n\"\"\"\nmutable struct CloglogLink  <: Link01 end\n\n\"\"\"\n    IdentityLink\n\nThe canonical [`Link`](@ref) for the `Normal` distribution, defined as `\u03b7 = \u03bc`.\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 `\u03b7 = inv(\u03bc)`.\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 `\u03b7 = inv(abs2(\u03bc))`.\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 `\u03b7 = log(\u03bc)`.\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 `\u03b7 = log(\u03bc/(\u03bc+\u03b8))`.\nThe shape parameter \u03b8 has to be fixed for the distribution to belong to the exponential family.\n\"\"\"\nmutable struct NegativeBinomialLink  <: Link\n    \u03b8::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 `\u03b7 = \u221a\u03bc`\n\"\"\"\nmutable struct SqrtLink <: Link end\n\n\"\"\"\n    linkfun(L::Link, \u03bc)\n\nReturn `\u03b7`, the value of the linear predictor for link `L` at mean `\u03bc`.\n\n# Examples\n```jldoctest\njulia> \u03bc = inv(10):inv(5):1\n0.1:0.2:0.9\n\njulia> show(linkfun.(LogitLink(), \u03bc))\n[-2.19722, -0.847298, 0.0, 0.847298, 2.19722]\n\n```\n\"\"\"\nfunction linkfun end\n\n\"\"\"\n    linkinv(L::Link, \u03b7)\n\nReturn `\u03bc`, the mean value, for link `L` at linear predictor value `\u03b7`.\n\n# Examples\n```jldoctest\njulia> \u03bc = 0.1:0.2:1\n0.1:0.2:0.9\n\njulia> \u03b7 = logit.(\u03bc);\n\njulia> linkinv.(LogitLink(), \u03b7) \u2248 \u03bc\ntrue\n```\n\"\"\"\nfunction linkinv end\n\n\"\"\"\n    mueta(L::Link, \u03b7)\n\nReturn the derivative of [`linkinv`](@ref), `d\u03bc/d\u03b7`, for link `L` at linear predictor value `\u03b7`.\n\n# Examples\n```jldoctest\njulia> mueta(LogitLink(), 0.0)\n0.25\n\njulia> mueta(CloglogLink(), 0.0) \u2248 0.36787944117144233\ntrue\n\njulia> mueta(LogLink(), 2.0) \u2248 7.38905609893065\ntrue\n```\n\"\"\"\nfunction mueta end\n\n\"\"\"\n    inverselink(L::Link, \u03b7)\n\nReturn a 3-tuple of the inverse link, the derivative of the inverse link, and when appropriate, the variance function `\u03bc*(1 - \u03bc)`.\n\nThe variance function is returned as NaN unless the range of \u03bc is (0, 1)\n\n# Examples\n```jldoctest\njulia> inverselink(LogitLink(), 0.0)\n(0.5, 0.25, 0.25)\n\njulia> \u03bc, oneminus\u03bc, variance = inverselink(CloglogLink(), 0.0);\n\njulia> \u03bc + oneminus\u03bc \u2248 1\ntrue\n\njulia> \u03bc*(1 - \u03bc) \u2248 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, \u03bc) = tan(pi * (\u03bc - oftype(\u03bc, 1/2)))\nlinkinv(::CauchitLink, \u03b7) = oftype(\u03b7, 1/2) + atan(\u03b7) / pi\nmueta(::CauchitLink, \u03b7) = one(\u03b7) / (pi * (one(\u03b7) + abs2(\u03b7)))\nfunction inverselink(::CauchitLink, \u03b7)\n    \u03bclower = atan(-abs(\u03b7)) / \u03c0\n    \u03bclower += oftype(\u03bclower, 1/2)\n    \u03b7 > 0 ? 1 - \u03bclower : \u03bclower, inv(\u03c0 * (1 + abs2(\u03b7))), \u03bclower * (1 - \u03bclower)\nend\n\nlinkfun(::CloglogLink, \u03bc) = log(-log1p(-\u03bc))\nfunction linkinv(::CloglogLink, \u03b7::T) where T<:Real\n    clamp(-expm1(-exp(\u03b7)), eps(T), one(T) - eps(T))\nend\nfunction mueta(::CloglogLink, \u03b7::T) where T<:Real\n    max(eps(T), exp(\u03b7) * exp(-exp(\u03b7)))\nend\nfunction inverselink(::CloglogLink, \u03b7)\n    exp\u03b7 = exp(\u03b7)\n    \u03bc = -expm1(-exp\u03b7)\n    om\u03bc = exp(-exp\u03b7)   # the complement, 1 - \u03bc\n    \u03bc, max(floatmin(\u03bc), exp\u03b7 * om\u03bc), max(floatmin(\u03bc), \u03bc * om\u03bc)\nend\n\nlinkfun(::IdentityLink, \u03bc) = \u03bc\nlinkinv(::IdentityLink, \u03b7) = \u03b7\nmueta(::IdentityLink, \u03b7) = one(\u03b7)\ninverselink(::IdentityLink, \u03b7) = \u03b7, one(\u03b7), oftype(\u03b7, NaN)\n\nlinkfun(::InverseLink, \u03bc) = inv(\u03bc)\nlinkinv(::InverseLink, \u03b7) = inv(\u03b7)\nmueta(::InverseLink, \u03b7) = -inv(abs2(\u03b7))\nfunction inverselink(::InverseLink, \u03b7)\n    \u03bc = inv(\u03b7)\n    \u03bc, -abs2(\u03bc), oftype(\u03bc, NaN)\nend\n\nlinkfun(::InverseSquareLink, \u03bc) = inv(abs2(\u03bc))\nlinkinv(::InverseSquareLink, \u03b7) = inv(sqrt(\u03b7))\nmueta(::InverseSquareLink, \u03b7) = -inv(2\u03b7*sqrt(\u03b7))\nfunction inverselink(::InverseSquareLink, \u03b7)\n    \u03bc = inv(sqrt(\u03b7))\n    \u03bc, -\u03bc / (2\u03b7), oftype(\u03bc, NaN)\nend\n\nlinkfun(::LogitLink, \u03bc) = logit(\u03bc)\nlinkinv(::LogitLink, \u03b7) = logistic(\u03b7)\nfunction mueta(::LogitLink, \u03b7)\n    expabs = exp(-abs(\u03b7))\n    denom = 1 + expabs\n    (expabs / denom) / denom\nend\nfunction inverselink(::LogitLink, \u03b7)\n    expabs = exp(-abs(\u03b7))\n    opexpabs = 1 + expabs\n    deriv = (expabs / opexpabs) / opexpabs\n    \u03b7 \u2264 0 ? expabs / opexpabs : inv(opexpabs), deriv, deriv\nend\n\nlinkfun(::LogLink, \u03bc) = log(\u03bc)\nlinkinv(::LogLink, \u03b7) = exp(\u03b7)\nmueta(::LogLink, \u03b7) = exp(\u03b7)\nfunction inverselink(::LogLink, \u03b7)\n    \u03bc = exp(\u03b7)\n    \u03bc, \u03bc, oftype(\u03bc, NaN)\nend\n\nlinkfun(nbl::NegativeBinomialLink, \u03bc) = log(\u03bc / (\u03bc + nbl.\u03b8))\nlinkinv(nbl::NegativeBinomialLink, \u03b7) = \u212f^\u03b7 * nbl.\u03b8 / (1-\u212f^\u03b7)\nmueta(nbl::NegativeBinomialLink, \u03b7) = \u212f^\u03b7 * nbl.\u03b8 / (1-\u212f^\u03b7)\nfunction inverselink(nbl::NegativeBinomialLink, \u03b7)\n    \u03bc = \u212f^\u03b7 * nbl.\u03b8 / (1-\u212f^\u03b7)\n    deriv = \u03bc * (1 + \u03bc / nbl.\u03b8)\n    \u03bc, deriv, oftype(\u03bc, NaN)\nend\n\nlinkfun(::ProbitLink, \u03bc) = -sqrt2 * erfcinv(2\u03bc)\nlinkinv(::ProbitLink, \u03b7) = erfc(-\u03b7 / sqrt2) / 2\nmueta(::ProbitLink, \u03b7) = exp(-abs2(\u03b7) / 2) / sqrt2\u03c0\nfunction inverselink(::ProbitLink, \u03b7)\n    \u03bclower = erfc(abs(\u03b7) / sqrt2) / 2\n    \u03bcupper = 1 - \u03bclower\n    \u03b7 < 0 ? \u03bclower : \u03bcupper, exp(-abs2(\u03b7) / 2 ) / sqrt2\u03c0, \u03bclower * \u03bcupper\nend\n\nlinkfun(::SqrtLink, \u03bc) = sqrt(\u03bc)\nlinkinv(::SqrtLink, \u03b7) = abs2(\u03b7)\nmueta(::SqrtLink, \u03b7) = 2\u03b7\ninverselink(::SqrtLink, \u03b7) = abs2(\u03b7), 2\u03b7, oftype(\u03b7, 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, \u03bc)\n\nReturn the value of the variance function for `D` at `\u03bc`\n\nThe variance of `D` at `\u03bc` is the product of the dispersion parameter, \u03d5, which does not\ndepend on `\u03bc` and the value of `glmvar`.  In other words `glmvar` returns the factor of the\nvariance that depends on `\u03bc`.\n\n# Examples\n```jldoctest\njulia> \u03bc = 1/6:1/3:1;\n\njulia> glmvar.(Normal(), \u03bc)    # constant for Normal()\n3-element Array{Float64,1}:\n 1.0\n 1.0\n 1.0\n\njulia> glmvar.(Bernoulli(), \u03bc) \u2248 \u03bc .* (1 .- \u03bc)\ntrue\n\njulia> glmvar.(Poisson(), \u03bc) == \u03bc\ntrue\n```\n\"\"\"\nfunction glmvar end\n\nglmvar(::Union{Bernoulli,Binomial}, \u03bc) = \u03bc * (1 - \u03bc)\nglmvar(::Gamma, \u03bc) = abs2(\u03bc)\nglmvar(::InverseGaussian, \u03bc) = \u03bc^3\nglmvar(d::NegativeBinomial, \u03bc) = \u03bc * (1 + \u03bc/d.r)\nglmvar(::Normal, \u03bc) = one(\u03bc)\nglmvar(::Poisson, \u03bc) = \u03bc\n\n\"\"\"\n    mustart(D::Distribution, y, wt)\n\nReturn a starting value for \u03bc.\n\nFor some distributions it is appropriate to set `\u03bc = y` to initialize the IRLS algorithm but\nfor others, notably the Bernoulli, the values of `y` are not allowed as values of `\u03bc` and\nmust be modified.\n\n# Examples\n```jldoctest\njulia> mustart(Bernoulli(), 0.0, 1) \u2248 1/4\ntrue\n\njulia> mustart(Bernoulli(), 1.0, 1) \u2248 3/4\ntrue\n\njulia> mustart(Binomial(), 0.0, 10) \u2248 1/22\ntrue\n\njulia> mustart(Normal(), 0.0, 1) \u2248 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, \u03bc)\n\nReturn the squared deviance residual of `\u03bc` 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 - \u03bc) * sqrt(devresid(D, y, \u03bc))\n```\n\n# Examples\n```jldoctest\njulia> devresid(Normal(), 0, 0.25) \u2248 abs2(0.25)\ntrue\n\njulia> devresid(Bernoulli(), 1, 0.75) \u2248 -2*log(0.75)\ntrue\n\njulia> devresid(Bernoulli(), 0, 0.25) \u2248 -2*log1p(-0.25)\ntrue\n```\n\"\"\"\nfunction devresid end\n\nfunction devresid(::Bernoulli, y, \u03bc)\n    if y == 1\n        return -2 * log(\u03bc)\n    elseif y == 0\n        return -2 * log1p(-\u03bc)\n    end\n    throw(ArgumentError(\"y should be 0 or 1 (got $y)\"))\nend\nfunction devresid(::Binomial, y, \u03bc)\n    if y == 1\n        return -2 * log(\u03bc)\n    elseif y == 0\n        return -2 * log1p(-\u03bc)\n    else\n        return 2 * (y * (log(y) - log(\u03bc)) + (1 - y)*(log1p(-y) - log1p(-\u03bc)))\n    end\nend\ndevresid(::Gamma, y, \u03bc) = -2 * (log(y / \u03bc) - (y - \u03bc) / \u03bc)\ndevresid(::InverseGaussian, y, \u03bc) = abs2(y - \u03bc) / (y * abs2(\u03bc))\nfunction devresid(d::NegativeBinomial, y, \u03bc)\n    \u03b8 = d.r\n    v = 2 * (xlogy(y, y / \u03bc) + xlogy(y + \u03b8, (\u03bc + \u03b8)/(y + \u03b8)))\n    return \u03bc == 0 ? oftype(v, NaN) : v\nend\ndevresid(::Normal, y, \u03bc) = abs2(y - \u03bc)\ndevresid(::Poisson, y, \u03bc) = 2 * (xlogy(y, y / \u03bc) - (y - \u03bc))\n\n\"\"\"\n    dispersion_parameter(D)  # not exported\n\nDoes distribution `D` have a separate dispersion parameter, \u03d5?\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, \u03bc, wt, \u03d5)  # not exported\n\nReturns `wt * logpdf(D(\u03bc, \u03d5), y)` where the parameters of `D` are derived from `\u03bc` and `\u03d5`.\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 `\u03bc` 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, \u03bc, wt, \u03d5) = wt*logpdf(Bernoulli(\u03bc), y)\nloglik_obs(::Binomial, y, \u03bc, wt, \u03d5) = logpdf(Binomial(Int(wt), \u03bc), Int(y*wt))\nloglik_obs(::Gamma, y, \u03bc, wt, \u03d5) = wt*logpdf(Gamma(inv(\u03d5), \u03bc*\u03d5), y)\nloglik_obs(::InverseGaussian, y, \u03bc, wt, \u03d5) = wt*logpdf(InverseGaussian(\u03bc, inv(\u03d5)), y)\nloglik_obs(::Normal, y, \u03bc, wt, \u03d5) = wt*logpdf(Normal(\u03bc, sqrt(\u03d5)), y)\nloglik_obs(::Poisson, y, \u03bc, wt, \u03d5) = wt*logpdf(Poisson(\u03bc), y)\n# We use the following parameterization for the Negative Binomial distribution:\n#    (\u0393(\u03b8+y) / (\u0393(\u03b8) * y!)) * \u03bc^y * \u03b8^\u03b8 / (\u03bc+\u03b8)^{\u03b8+y}\n# The parameterization of NegativeBinomial(r=\u03b8, p) in Distributions.jl is\n#    \u0393(\u03b8+y) / (y! * \u0393(\u03b8)) * p^\u03b8(1-p)^y\n# Hence, p = \u03b8/(\u03bc+\u03b8)\nloglik_obs(d::NegativeBinomial, y, \u03bc, wt, \u03d5) = wt*logpdf(NegativeBinomial(d.r, d.r/(\u03bc+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": "function isprime(n)\n    if n == 1\n        return false\n    end\n    if n == 2 || n == 3\n        return true\n    end  \n\n    for i in 2:isqrt(n)\n        if n%i == 0\n            return false\n        else\n            if i == 2\n                i += 1\n            else\n                i += 2\n            end\n        end\n    end\n    return true\nend", "meta": {"hexsha": "eec678a43056796b14adff415c1e72a54ae17ecd", "size": 340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "task_7_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_7_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_7_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": 16.1904761905, "max_line_length": 24, "alphanum_fraction": 0.3529411765, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7530071324182517}}
{"text": "using GeometricAlgebra\nconst ga = GeometricAlgebra\nusing Test\n\n@basis \"---+\"\ninclude(\"definitions.jl\")\ninclude(\"../operators.jl\")\n", "meta": {"hexsha": "a164331c2da7c24d844e3d430fe621232c356038", "size": 130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/algebras/spacetime.jl", "max_stars_repo_name": "serenity4/ConformalGeometry.jl", "max_stars_repo_head_hexsha": "70ec88954d0d0acfb9d480e17a45593305333c04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-07T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T21:07:36.000Z", "max_issues_repo_path": "test/algebras/spacetime.jl", "max_issues_repo_name": "serenity4/GeometricAlgebra.jl", "max_issues_repo_head_hexsha": "4489ec9e3e37541f891f29c3ee69d9295d5cdeac", "max_issues_repo_licenses": ["MIT"], "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/algebras/spacetime.jl", "max_forks_repo_name": "serenity4/GeometricAlgebra.jl", "max_forks_repo_head_hexsha": "4489ec9e3e37541f891f29c3ee69d9295d5cdeac", "max_forks_repo_licenses": ["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.25, "max_line_length": 27, "alphanum_fraction": 0.7384615385, "num_tokens": 34, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7529675682814404}}
{"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 \u2250 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 \u2250 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 \u2250 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 \u2250 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 \u2250 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 \u2250 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 \u2250 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": "using jInv.Mesh\nusing jInv.LinearSolvers\nusing Test\nusing KrylovMethods\nusing Multigrid\nusing LinearAlgebra\nusing SparseArrays\n\nprintln(\"===  Example 2D DivSigGrad ====\");\n\ndomain = [0.0, 1.0, 0.0, 1.0];\nn      = [50,50];\nMr     = getRegularMesh(domain,n)\nG      = getNodalGradientMatrix(Mr);\nAr     = G'*G;\nAr     = Ar + 1e-2*norm(Ar,1)*sparse(1.0I,size(Ar,2),size(Ar,2));\nN      = size(Ar,2); \nB      = Ar*rand(N,4);\n\nlevels      = 5;\nnumCores \t= 8; \nmaxIter     = 15;\nrelativeTol = 1e-2;\nrelaxType   = \"SPAI\";\nrelaxParam  = 1.0;\nrelaxPre \t= 2;\nrelaxPost   = 2;\ncycleType   ='V';\ncoarseSolveType = \"Julia\";\n\nMG = getMGparam(Float64,Int64,levels,numCores,maxIter,relativeTol,relaxType,relaxParam,relaxPre,relaxPost,cycleType,coarseSolveType);\n\nsMGPCG   = getMGsolver(MG,Mr, 1,\"GMRES\",out=1);\nX,  = solveLinearSystem(Ar,B,sMGPCG);\n@test norm(Ar*X-B)/norm(B) < sMGPCG.tol\n\nsMGPCG   = getMGsolver(MG,Mr, 1,\"PCG\",out=1);\nX,  = solveLinearSystem(Ar,B,sMGPCG);\n@test norm(Ar*X-B)/norm(B) < sMGPCG.tol", "meta": {"hexsha": "9f0f1d609d8a92feff1dcce2f7c9eee7d4161964", "size": 995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Multigrid/testLinSolveMGWrapper.jl", "max_stars_repo_name": "JuliaInv/Multigrid.jl", "max_stars_repo_head_hexsha": "4b759b92eb609d59115e3537b7eb88ba05699fdc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-05-20T04:24:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T13:45:27.000Z", "max_issues_repo_path": "test/Multigrid/testLinSolveMGWrapper.jl", "max_issues_repo_name": "JuliaInv/Multigrid.jl", "max_issues_repo_head_hexsha": "4b759b92eb609d59115e3537b7eb88ba05699fdc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-10-25T10:52:03.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-07T13:35:27.000Z", "max_forks_repo_path": "test/Multigrid/testLinSolveMGWrapper.jl", "max_forks_repo_name": "JuliaInv/Multigrid.jl", "max_forks_repo_head_hexsha": "4b759b92eb609d59115e3537b7eb88ba05699fdc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-19T02:30:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:57.000Z", "avg_line_length": 25.5128205128, "max_line_length": 133, "alphanum_fraction": 0.6603015075, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7529675535823891}}
{"text": "using NumericalIntegration\nusing Test\nusing InteractiveUtils # for subtypes\nusing StaticArrays\nusing HCubature # for testing n-dimensional integration\n\n@testset \"compare with analytic result\" begin\n    x = collect(-\u03c0 : 2*\u03c0/2048 : \u03c0)\n    y = sin.(x)\n    p = collect(0 : \u03c0/1024 : \u03c0)\n    q = sin.(p)\n    for M in subtypes(IntegrationMethod)\n        for T in [Float32, Float64, BigFloat]\n            for (xs,ys,val,atol) in [\n                                     (x,y,0,1e-4),\n                                     (p,q,2,1e-4),\n                                  ]\n                result = @inferred integrate(T.(xs), T.(ys),M())\n                @test isapprox(result, val, atol=atol)\n                @test typeof(result) == T\n            end\n        end\n    end\nend\n\n@testset \"cumulative integration\" begin\n    x = collect(-\u03c0 : 2*\u03c0/2048 : \u03c0)\n    y = sin.(x)\n    exact = @. -cos(x) + cos(-\u03c0)\n    for M in subtypes(IntegrationMethod)\n        hasmethod(cumul_integrate, Tuple{AbstractVector, AbstractVector, M}) || continue\n        for T in [Float32, Float64, BigFloat]\n            result = @inferred cumul_integrate(T.(x), T.(y), M())\n            @test typeof(result) == Vector{T}\n            @test all(isapprox.(result, exact, atol=1e-4))\n        end\n    end\nend\n\n@testset \"n-dimensional integration testing\" begin\n    X = range(0,stop=2\u03c0,length=10)\n    Y = range(-\u03c0,stop=\u03c0,length=10)\n    Z = range(0,stop=2,length=10)\n\n    A = Array{Float64}(undef,length(X),length(Y),length(Z))\n    f(x) = sin(x[1]) + cos(x[2]) + 2x[3]\n\n    for (k,z) in enumerate(Z)\n        for (j,y) in enumerate(Y)\n            for (i,x) in enumerate(X)\n                A[i,j,k] = f([x,y,z])\n            end\n        end\n    end\n\n    @test isapprox(integrate((X,Y,Z),A), hcubature(f,[0,-\u03c0,0],[2\u03c0,\u03c0,2])[1], atol=1e-4)\nend\n\n@testset \"SVector\" begin\n    xs = range(0, stop=1, length=9)\n    ys1 = randn(9)\n    ys2 = randn(9)\n    ys = map(SVector, ys1, ys2)\n    for M in subtypes(IntegrationMethod)\n        m = M()\n        res1 = integrate(xs,ys1,m)\n        res2 = integrate(xs,ys2,m)\n        res = @inferred integrate(xs,ys,m)\n        @test res \u2248 @SVector [res1, res2]\n    end\nend\n\n@testset \"Raising Warnings\" begin\n    xs = collect(-1.0 : 0.5 : 1.0)\n    ys = xs.^2\n    m = RombergEven()\n    expwarn = \"RombergEven :: final step reached, but accuracy not: 1.3333333333333335 > 1.0e-12\"\n    @test_logs (:warn, expwarn) integrate(xs, ys, m)\nend\n\nusing Unitful\n\n@testset \"Unitful compatibility\" begin\n    x = LinRange(1u\"s\", 10u\"s\", 9)\n    y = rand(9)*u\"m/s\"\n    for M in subtypes(IntegrationMethod)\n        @test typeof(integrate(x,y,M())) == typeof(1.0u\"m\")\n        if hasmethod(cumul_integrate, Tuple{AbstractVector, AbstractVector, M})\n            @test typeof(cumul_integrate(x,y,M())) == Vector{typeof(1.0u\"m\")}\n        end\n    end\nend\n", "meta": {"hexsha": "e0c0a2eea6764623eb12659c374ae834f5cf1836", "size": 2799, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "pengwyn/NumericalIntegration.jl", "max_stars_repo_head_hexsha": "2aadf262fa5cb6f70c13800616626ab6d3e9d488", "max_stars_repo_licenses": ["MIT"], "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": "pengwyn/NumericalIntegration.jl", "max_issues_repo_head_hexsha": "2aadf262fa5cb6f70c13800616626ab6d3e9d488", "max_issues_repo_licenses": ["MIT"], "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": "pengwyn/NumericalIntegration.jl", "max_forks_repo_head_hexsha": "2aadf262fa5cb6f70c13800616626ab6d3e9d488", "max_forks_repo_licenses": ["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.0967741935, "max_line_length": 97, "alphanum_fraction": 0.5584137192, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317888, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7529620374615957}}
{"text": "export Associative, Nonassociative, associativity\n\n\"\"\"\nTrait to indicate that a binary operation \u2022 is associative over set S. Only\nmethods of \u2022 with the signature \u2022(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 \u2022 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 \u2022.\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(\u03b7, \u03bb)\n\nCanonical parametrisation of the Normal distribution with canonical parameters `\u03b7` and `\u03bb`.\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    \u03b7::T       # \u03c3^(-2) * \u03bc\n    \u03bb::T       # \u03c3^(-2)\n    \u03bc::T       # \u03bc\n\n    function NormalCanon{T}(\u03b7, \u03bb; check_args::Bool=true) where T\n        check_args && @check_args(NormalCanon, \u03bb > zero(\u03bb))\n        new{T}(\u03b7, \u03bb, \u03b7 / \u03bb)\n    end\nend\n\nNormalCanon(\u03b7::T, \u03bb::T; check_args::Bool=true) where {T<:Real} = NormalCanon{typeof(\u03b7/\u03bb)}(\u03b7, \u03bb; check_args=check_args)\nNormalCanon(\u03b7::Real, \u03bb::Real; check_args::Bool=true) = NormalCanon(promote(\u03b7, \u03bb)...; check_args=check_args)\nNormalCanon(\u03b7::Integer, \u03bb::Integer; check_args::Bool=true) = NormalCanon(float(\u03b7), float(\u03bb); 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}}, \u03b7::S, \u03bb::S) where {T <: Real, S <: Real} = NormalCanon(T(\u03b7), T(\u03bb))\nconvert(::Type{NormalCanon{T}}, d::NormalCanon{S}) where {T <: Real, S <: Real} = NormalCanon(T(d.\u03b7), T(d.\u03bb); check_args=false)\n\n## conversion between Normal and NormalCanon\n\nconvert(::Type{Normal}, d::NormalCanon) = Normal(d.\u03bc, 1 / sqrt(d.\u03bb))\nconvert(::Type{NormalCanon}, d::Normal) = (\u03bb = 1 / d.\u03c3^2; NormalCanon(\u03bb * d.\u03bc, \u03bb))\nmeanform(d::NormalCanon) = convert(Normal, d)\ncanonform(d::Normal) = convert(NormalCanon, d)\n\n\n#### Parameters\n\nparams(d::NormalCanon) = (d.\u03b7, d.\u03bb)\n@inline partype(d::NormalCanon{T}) where {T<:Real} = T\n\n#### Statistics\n\nmean(d::NormalCanon) = d.\u03bc\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.\u03bb\nstd(d::NormalCanon) = sqrt(var(d))\n\nentropy(d::NormalCanon) = (-log(d.\u03bb) + log2\u03c0 + 1) / 2\n\nlocation(d::NormalCanon) = mean(d)\nscale(d::NormalCanon) = std(d)\n\n#### Evaluation\n\npdf(d::NormalCanon, x::Real) = (sqrt(d.\u03bb) / sqrt2\u03c0) * exp(-d.\u03bb * abs2(x - d.\u03bc)/2)\nlogpdf(d::NormalCanon, x::Real) = (log(d.\u03bb) - log2\u03c0 - d.\u03bb * abs2(x - d.\u03bc))/2\n\nzval(d::NormalCanon, x::Real) = (x - d.\u03bc) * sqrt(d.\u03bb)\nxval(d::NormalCanon, z::Real) = d.\u03bc + z / sqrt(d.\u03bb)\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.\u03bc + randn(rng) / sqrt(cf.\u03bb)\n\n#### Affine transformations\n\nfunction Base.:+(d::NormalCanon, c::Real)\n    \u03b7, \u03bb = params(d)\n    return NormalCanon(\u03b7 + c * \u03bb, \u03bb)\nend\nBase.:*(c::Real, d::NormalCanon) = NormalCanon(d.\u03b7 / c, d.\u03bb / 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": "@testset \"Test the 2-by-2 symmetric positive definite matrices\" begin\nusing Random: seed!\n# explicitly compute an easy exp\nM = SymmetricPositiveDefinite(2)\nx = SPDPoint([1.0 0.0; 0.0 1.0])\n\u03be = SPDTVector([1.0 0.0; 0.0 0.0])\n\u03b7 = SPDTVector([1.0 0.0; 0.0 1.0])\ny = exp(M,x,\u03be)\n@test norm( getValue(y) - [\u212f 0;0 1.0]) \u2248 0 atol=10.0^(-16)\n# check that with base the base must mach.\nz = SPDPoint([1.0 0.0; 0.0 0.1])\n\u03beE = TVectorE(\u03be,x);\n@test_throws DomainError exp(M,z,\u03beE)\n# check that log is the inverse of exp and stores the base point correctly\n# if that's activated\nxT = MPointE(x);\n\u03beT2 = log(M,x,y)\n@test norm( getValue(\u03be) - getValue(\u03beT2) ) \u2248 0 atol=10.0^(-16)\n@test distance(M, getBasePoint(\u03beE), x) \u2248 0 atol=10.0^(-16)\n# test norm\n@test norm(M,x,\u03be) \u2248 distance(M,x,y) atol=10.0^(-16)\n# test parallel transport\n@test norm(getValue( parallelTransport(M,y,x,log(M,y,x)) ) + getValue(\u03be) ) \u2248 0 atol=3*10.0^(-16)\n@test parallelTransport(M,x,x,\u03be) == \u03be\n# random\nseed!(42)\n@test validateMPoint(M,randomMPoint(M))\n@test validateTVector(M,x, randomTVector(M,x))\n@test validateTVector(M,x, randomTVector(M,x, :Gaussian))\n@test validateTVector(M,x, randomTVector(M,x, :Rician))\n#\n# Test tangent ONB\n#\nn = 4\nM2 = SymmetricPositiveDefinite(n)\nx2 = SPDPoint(one(zeros(n,n)))\n\u03be2 = SPDTVector(getValue(x2))\ny2 = exp(M2,x2,\u03be2)\n\u039e,\u03ba = tangentONB(M2,x2,\u03be2)\n# test orthogonality\n@test all([ dot(M2,x2,\u039e[i],\u039e[j]) for i=1:length(\u039e) for j=i+1:length(\u039e) ] .== 0)\n# test normality\n@test all( [1-dot(M2,x2,\u039e[i],\u039e[i]) for i=1:length(\u039e)] .< 3*10^(-16) )\n\u039e2,\u03ba2 = tangentONB(M2,x2,y2)\n@test sum( norm.(Ref(M2),Ref(x2), \u039e .- \u039e2) ) \u2248 0\n@test sum(\u03ba - \u03ba2) \u2248 0\n#\n# test types\n@test typeofTVector(x) == SPDTVector{Float64}\n@test typeofTVector(SPDPoint{Float64}) == SPDTVector{Float64}\n@test typeofMPoint(\u03be) == SPDPoint{Float64}\n@test typeofMPoint(SPDTVector{Float64}) == SPDPoint{Float64}\n#\n@test typicalDistance(M) \u2248 sqrt(3)\n#\n@test_throws DomainError validateMPoint(M2,x)\n@test_throws DomainError validateMPoint(M, SPDPoint([0. 1.;-1. 0.])) \n@test_throws DomainError validateMPoint(M, SPDPoint([0. 0.;0. 0.]))\n@test_throws DomainError validateTVector(M,x,\u03be2)\n@test_throws DomainError validateTVector(M,x,SPDTVector([0. 1.; -2. 0.]) )\n#\n@test norm(getValue(zeroTVector(M,x))) == 0\n@test validateTVector(M,x,zeroTVector(M,x))\n# show\n@test \"$M\" == \"The Manifold of 2-by-2 symmetric positive definite matrices\"\n@test \"$x\" == \"SPD($(getValue(x)))\"\n@test \"$\u03be\" == \"SPDT($(getValue(\u03be)))\"\n# Test Matrix trait\n@test getValue(x+y) == getValue(x)+getValue(y)\n@test getValue(x-y) == getValue(x)-getValue(y)\n@test getValue(x*y) == getValue(x)*getValue(y)\n@test getValue(\u03be+\u03b7) == getValue(\u03be)+getValue(\u03b7) \n@test getValue(\u03be-\u03b7) == getValue(\u03be)-getValue(\u03b7) \n@test getValue(\u03be*\u03b7) == getValue(\u03be)*getValue(\u03b7)\n@test transpose(x) == SPDPoint(Matrix(transpose(getValue(x))))\n@test transpose(\u03be) == SPDTVector(Matrix(transpose(getValue(\u03be))))\nend", "meta": {"hexsha": "fcba2d5c6c46dee264db198eb3b3e042abab4035", "size": 2876, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/manifolds/testSPD.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": "test/manifolds/testSPD.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": "test/manifolds/testSPD.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": 37.3506493506, "max_line_length": 96, "alphanum_fraction": 0.6828929068, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7529620279850071}}
{"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, \u03b3) = kernel\n            sum += weight * exp(-\u03b3*(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    \u03c32 = inv(d.J.value)\n    (q * log(2\u03c0 * \u03c32) + \u03c32 * vecnorm(h)^2) * 0.5\nend\n\nimmutable IsoNormalCanonSuffStats\n    h::Vector{Float64}  # add to h\n    \u03ba::Float64          # add to \u03ba\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.\u03ba)\nend\n\n\n##\n# Gaussian likelihood model\n#\n#  x ~ N(\u03b8, \u03c3^2)\n#\nimmutable IsoGaussModel <: LikelihoodModel\n    \u03c3::Float64    # the standard dev of observations\nend\n\nwithparams(g::IsoGaussModel, \u03bc::Vector{Float64}) =\n    MvNormal(\u03bc, g.\u03c3)\n\nfunction suffstats(g::IsoGaussModel, X::AbstractMatrix, inds::AbstractVector{Int})\n    d, n = size(X)\n    h = zeros(d)\n    c = 1.0 / g.\u03c3^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 OptimTools\nusing Base.Test\n\n# test exact line search for quadratic\nQ = 10*speye(40)\nf(x)    = 0.5*dot(x,Q*x)\ndf(x)   = Q*x\nd2f(x)  = Q\nx0 = randn(40)\n\nexactLS  = (f,df,fk,dfk,xk,pk)-> (-dot(pk,dfk)/dot(pk,Q*pk),1)\ngoldenLSf = (f,df,dk,dfk,xk,pk) -> goldenLS(f,xk,pk,0.0,5.0)\n\nprintln(\"Test SD,NLCG,BFGS with exact line search \")\n# steepest descent\nx1,flag1,his1 = sd(f,df,x0,maxIter=1000,atol=1e-6,out=0,lineSearch=exactLS)\n@test norm(x1)<1e-6*norm(x0)\nx2,flag2,his2 = sd(f,df,x0,maxIter=1000,atol=1e-6,out=0, lineSearch=exactLS)\n@test norm(x2)<1e-6\n@test size(his2,1)==2 #should converge in one iteration\n\n# nlcg\nx1,flag1,his1 = nlcg(f,df,x0,maxIter=1000,atol=1e-6,out=0)\n@test norm(x1)<1e-6*norm(x0)\nx2,flag2,his2 = nlcg(f,df,x0,maxIter=1000,atol=1e-6,out=0, lineSearch=exactLS)\n@test norm(x2)<1e-6\n@test size(his2,1)==2 #should converge in one iteration\n\n# bfgs\nx1,flag1,his1 = bfgs(f,df,x0,maxIter=1000,atol=1e-6,out=0)\n@test norm(x1)<1e-6*norm(x0)\nx2,flag2,his2 = bfgs(f,df,x0,maxIter=1000,atol=1e-6,out=0, lineSearch=exactLS)\n@test norm(x2)<1e-6\n@test size(his2,1)==2 #should converge in one iteration\n\nprintln(\"Done!\")\n\nprintln(\"Test SD,NLCG,BFGS with golden line search \")\n# steepest descent\nx1,flag1,his1 = sd(f,df,x0,maxIter=1000,atol=1e-6,out=0,lineSearch=goldenLSf)\n@test norm(x1)<1e-6*norm(x0)\nx2,flag2,his2 = sd(f,df,x0,maxIter=1000,atol=1e-6,out=0, lineSearch=goldenLSf)\n@test norm(x2)<1e-6\n\n# nlcg\nx1,flag1,his1 = nlcg(f,df,x0,maxIter=1000,atol=1e-6,out=0)\n@test norm(x1)<1e-6*norm(x0)\nx2,flag2,his2 = nlcg(f,df,x0,maxIter=1000,atol=1e-6,out=0, lineSearch=goldenLSf)\n@test norm(x2)<1e-6\n\n# bfgs\nx1,flag1,his1 = bfgs(f,df,x0,maxIter=1000,atol=1e-6,out=0)\n@test norm(x1)<1e-6*norm(x0)\nx2,flag2,his2 = bfgs(f,df,x0,maxIter=1000,atol=1e-6,out=0, lineSearch=goldenLSf)\n@test norm(x2)<1e-6\n\nprintln(\"Done!\")\n", "meta": {"hexsha": "056010ae7e8305473e890ac77a76b27688bdbe71", "size": 1824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testLineSearch.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": "test/testLineSearch.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": "test/testLineSearch.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": 31.4482758621, "max_line_length": 80, "alphanum_fraction": 0.7012061404, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7529620262014682}}
{"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, \u03bc, \u03c3) = begin\n    @assert all(\u03c3 .> 0)\nend\n#Differentiable versions.\nlogpdf(::Type{Normal}, x, \u03bc, \u03c3) = begin\n    #valid(Normal, x, \u03bc, \u03c3)\n    \u03c32 = \u03c3.*\u03c3\n    diff = x-\u03bc\n    -(log(2*pi*\u03c32) + diff.*diff ./ \u03c32)/2\nend\ntest(Normal, 1, 2, 3)\n\n\n#MvNormal\nvalid(::Type{MvNormal}, x::Vector, \u03bc::Vector, \u03a3::Matrix) = begin\n    @assert isposdef(\u03a3)\nend\n#Differentiable versions.\nlogpdf(::Type{MvNormal}, x::Vector, \u03bc::Vector, \u03a3::Matrix) = begin\n    #valid(MvNormal, x, \u03bc, \u03a3)\n    diff = x-\u03bc\n    -(length(x)*log(2*pi) + logdet(\u03a3) + (diff'/\u03a3)*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\u0393(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\u0393(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, \u03b1, \u03b2) = begin\n    @assert all(\u03b1 .> 0)\n    @assert all(\u03b2 .> 0)\n    @assert all(0 .<= x .<= 1)\nend\nlogB(\u03b1, \u03b2) = log\u0393(\u03b1) + log\u0393(\u03b2) - log\u0393(\u03b1 + \u03b2)\nlogpdf(::Type{Beta}, x, \u03b1, \u03b2) = begin\n    #valid(Beta, x, \u03b1, \u03b2)\n    (\u03b1-1).*log(x) + (\u03b2-1).*log(1-x) - logB(\u03b1, \u03b2)\nend\ntest(Beta, 0.6, 1.3, 1.5)\n\n\n#Dirichlet\nvalid(::Type{Dirichlet}, x, \u03b1::Vector{Float64}) = begin\n    @assert all(0 .<= x)\n    @assert all(0 .<= \u03b1)\nend\nlogB(\u03b1) = sum(log\u0393(\u03b1)) - log\u0393(sum(\u03b1))\nlogpdf(::Type{Dirichlet}, x, \u03b1) = begin\n    #valid(Dirichlet, x, \u03b1)\n    sum((\u03b1-1).*log(x)) - logB(\u03b1)\nend\ntest(Dirichlet, [1.2, 1.6, 1.3], [1.3, 1.6, 1.3])\n    \n\n#Poisson\nvalid(::Type{Poisson}, k, \u03bb) = begin\n    @assert all(k .>= 0)\n    @assert all(\u03bb .>= 0)\nend\nlogpdf(::Type{Poisson}, k, \u03bb) = begin\n    #valid(Poisson, k, \u03bb)\n    k*log(\u03bb) - log(factorial(k)) - \u03bb\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": "using Base.Test\n\nN = 10\n\nC = rand(N, N)\nA = C - C'\n\nT, Z, \u03bb = schur(A)\n@test Z*T*Z' \u2248 A\n\n##########################\n\nA = Antisymmetric(A)\nT, Z, \u03bb = schur(A)\n\n@test Z*T*Z' \u2248 A\n\n#############################\n\nA = AntisymTridiagonal(rand(N))\n@show A\n\nT, Z, \u03bb = schur(A)\n@test Z*T*Z' \u2248 A\n\n\n", "meta": {"hexsha": "e2cd62f6ad31ba172409e66652295c6a716681f9", "size": 286, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/antisymmetric.jl", "max_stars_repo_name": "braydenware/AntisymmetricMatrices.jl", "max_stars_repo_head_hexsha": "5fc14ad0d5c4fd8ca556f212a4249d4b16bb8dd2", "max_stars_repo_licenses": ["MIT"], "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/antisymmetric.jl", "max_issues_repo_name": "braydenware/AntisymmetricMatrices.jl", "max_issues_repo_head_hexsha": "5fc14ad0d5c4fd8ca556f212a4249d4b16bb8dd2", "max_issues_repo_licenses": ["MIT"], "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/antisymmetric.jl", "max_forks_repo_name": "braydenware/AntisymmetricMatrices.jl", "max_forks_repo_head_hexsha": "5fc14ad0d5c4fd8ca556f212a4249d4b16bb8dd2", "max_forks_repo_licenses": ["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.5925925926, "max_line_length": 31, "alphanum_fraction": 0.4230769231, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7529620137334796}}
{"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": "using FinancialToolbox, DualNumbers, FinancialFFT, FinancialMonteCarlo\n\nA = 600.0;\nN = 20000;\n\nmethod = LewisMethod(A, N);\nS0 = 100.0;\nK = 100.0;\nr = dual(0.02, 1.0);\n#r=0.02;\nT = 1.0;\nd = 0.0;\n#sigma=dual(0.2,1.0);\nsigma = 0.2;\nmu1 = 0.03;\nsigma1 = 0.02;\np = 0.3;\nlam = 5.0;\nlamp = 30.0;\nlamm = 20.0;\nzero_rate = ZeroRate(r);\n\n#Model = MertonProcess(sigma, lam, mu1, sigma1, Underlying(S0, d));\nModel = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));\n#Model = BlackScholesProcess(sigma, Underlying(S0, d));\n# Model = VarianceGammaProcess(sigma, 0.01, 0.01, Underlying(S0, d));\n#Model = NormalInverseGaussianProcess(sigma, 0.01, 0.01, Underlying(S0, d));\n\nEUData = EuropeanOption(T, K)\nNsim = 10_000;\nNstep = 30;\nmc = MonteCarloConfiguration(Nsim, Nstep);\n\n@time @show pricer(Model, zero_rate, method, EUData);\n@time @show pricer(Model, zero_rate, mc, EUData);\n#typeof(Model) <: BlackScholesProcess ? @time(@show(blsprice(S0, K, r, T, sigma, d))) : nothing;\n", "meta": {"hexsha": "853dde5ef4d988475f0fb88cc9d504ec2a13db79", "size": 968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_lewis.jl", "max_stars_repo_name": "rcalxrc08/FinancialFFT.jl", "max_stars_repo_head_hexsha": "d539b706bb8dd567172fa98c0850526325edd4f1", "max_stars_repo_licenses": ["MIT"], "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_lewis.jl", "max_issues_repo_name": "rcalxrc08/FinancialFFT.jl", "max_issues_repo_head_hexsha": "d539b706bb8dd567172fa98c0850526325edd4f1", "max_issues_repo_licenses": ["MIT"], "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_lewis.jl", "max_forks_repo_name": "rcalxrc08/FinancialFFT.jl", "max_forks_repo_head_hexsha": "d539b706bb8dd567172fa98c0850526325edd4f1", "max_forks_repo_licenses": ["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.1621621622, "max_line_length": 96, "alphanum_fraction": 0.6745867769, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7528141433596028}}
{"text": "# MIT License                                                                    #src\n#                                                                                #src\n# Copyright (c) 2020 Fran\u00e7ois 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\u00e7ois 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, \u03bb)\n    n, p = size(X)\n    model = Model()\n    @variable(model, \u03b8[1:p])\n    @variable(model, t[1:n])\n    for i in 1:n\n        u = - (X[i, :]' * \u03b8) * y[i]\n        softplus(model, t[i], u)\n    end\n    ## Add \u21132 regularization\n    @variable(model, 0.0 <= reg)\n    @constraint(model, [reg; \u03b8] in MOI.SecondOrderCone(p+1))\n    ## Define objective\n    @objective(model, Min, sum(t) + \u03bb * 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\u03bb = 10.0\nmodel = build_logit_model(X, y, \u03bb)\nset_optimizer(model, SCS.Optimizer)\nJuMP.optimize!(model)\n\n#-\n\n\u03b8\u266f = JuMP.value.(model[:\u03b8])\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, \u03bb)\n    n, p = size(X)\n    model = Model()\n    @variable(model, \u03b8[1:p])\n    @variable(model, t[1:n])\n    for i in 1:n\n        u = - (X[i, :]' * \u03b8) * y[i]\n        softplus(model, t[i], u)\n    end\n    ## Add \u21131 regularization\n    @variable(model, 0.0 <= reg)\n    @constraint(model, [reg; \u03b8] in MOI.NormOneCone(p+1))\n    ## Define objective\n    @objective(model, Min, sum(t) + \u03bb * 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\u03bb = 10.0\nsparse_model = build_sparse_logit_model(X, y, \u03bb)\nset_optimizer(sparse_model, SCS.Optimizer)\nJuMP.optimize!(sparse_model)\n\n#-\n\n\u03b8\u266f = JuMP.value.(sparse_model[:\u03b8])\nprintln(\"Number of non-zero components: \", count_nonzero(\u03b8\u266f),\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(\u03b1, dx, dt, xStart, xEnd, n, \u03ba, 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(\u03b1, dx, dt, xStart, xEnd, n, \u03ba, u0t, uendt, u0, ::FiniteDiffEx)\n    x = collect(0:dx:xEnd)\n    t = collect(0:dt:n)\n    S = \u03ba*((dt^\u03b1)/(dx^2))\n    S_bar = gamma(3-\u03b1)*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, \u03b1)\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, \u03b1)\n    c = zeros(length(k))\n    for i=1:length(k)\n        if maximum(k) < 2\n            @. c = (k+1)^(1-\u03b1) - k^(1-\u03b1)\n        else\n            @. c = (k+1)^(2-\u03b1) - k^(2-\u03b1)\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 \u2297 B)\u00d7vec(X) = vec(BXA\u1d40)\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, \u03b1, \u03b2)\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, \u03b1, \u03b2)\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, \u03b1, \u03b2)\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": "using CombUtils\n\n\nfunction main()\n    f1 = big(1)\n    f2 = big(1)\n    index = 2\n    num_digits = 1\n    while num_digits < 1000\n        index += 1\n        tmp = f2\n        f2 += f1\n        f1 = tmp\n        num_digits = ndigits(f2)\n    end\n    @printf(\"The first index where the nth fib has 1000 digits is %d\\n\", index)\nend\n\nmain()\n", "meta": {"hexsha": "cda4b9c1e00189681d52d773ad674a271841dcc1", "size": 330, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem_025.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_025.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_025.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": 16.5, "max_line_length": 79, "alphanum_fraction": 0.5393939394, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7527788208249172}}
{"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, _ , _ , \u03c8 , d\u03c8 = get_fields(fname,i)\n        \n        #Gradient term\n        Psi  = reshape(\u03c8, rnodes*thnodes)\n        dPsi = reshape(d\u03c8, 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": "export L1ball\n\nstruct L1ball{T <: Real} <: ConvexSet\n    center::Vector{T}\n    radius::T\nend\n\n\"\"\"\n    \n    L1ball(c, r)\n\nA ball with center `c` and radius `r`.\n\"\"\"\n\nfunction project!(s::L1ball{T}, v::Vector{T}, y::Vector{T}) where {T <: Real}\n    n = length(y)\n    z = sum(abs, y-s.center)\n   if z <= s.radius\n      v = y\n   else\n      w = project(Projections.Simplex(s.radius),y)\n      sgn = zeros(n)\n      d = y-s.center\n      for i in 1:n\n            if d[i] > 0\n                sgn[i] = 1\n            elseif d[i] == 0\n                sgn[i] = 0\n            else\n                sgn[i] = -1\n            end\n      end\n        v = s.center .+ sgn .* w \n   end\nend\n\nfunction project(s::L1ball{<:Real}, y::Vector{<:Real})\n    project!(s, similar(y), y)\nend\n", "meta": {"hexsha": "2fdc8b4285fa5aca3e3c3adbfeb5d136a398bc2f", "size": 756, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/l1ball.jl", "max_stars_repo_name": "Xueying-Liu/Projections.jl", "max_stars_repo_head_hexsha": "7e2ff375d2e990c8d959cc9333d0af724fe9352a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/l1ball.jl", "max_issues_repo_name": "Xueying-Liu/Projections.jl", "max_issues_repo_head_hexsha": "7e2ff375d2e990c8d959cc9333d0af724fe9352a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/l1ball.jl", "max_forks_repo_name": "Xueying-Liu/Projections.jl", "max_forks_repo_head_hexsha": "7e2ff375d2e990c8d959cc9333d0af724fe9352a", "max_forks_repo_licenses": ["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.9, "max_line_length": 77, "alphanum_fraction": 0.4722222222, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7527788179361771}}
{"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\u03c0*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 Penopt\r\nusing LinearAlgebra: norm\r\nusing Test\r\n\r\nf(x) = norm(x).^2\r\nc(x) = x - 20 * ones(length(x))\r\n@testset \"Penopt.jl\" begin  \r\n    xopt,fxopt = penopt(f,c,ones(2),[0 1 2 4 8 16 32 64])\r\n    @test  xopt \u2248 [0,0] atol = 0.0001\r\n    @test fxopt \u2248 0.0   atol = 0.001\r\nend\r\n", "meta": {"hexsha": "db9a3056f07d0ee1e085e3d10849be33e950fe9c", "size": 278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "julianschnidder/Penopt.jl", "max_stars_repo_head_hexsha": "52a0079dc7533ae36e63a2668c4b4e0ac4839805", "max_stars_repo_licenses": ["MIT"], "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": "julianschnidder/Penopt.jl", "max_issues_repo_head_hexsha": "52a0079dc7533ae36e63a2668c4b4e0ac4839805", "max_issues_repo_licenses": ["MIT"], "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": "julianschnidder/Penopt.jl", "max_forks_repo_head_hexsha": "52a0079dc7533ae36e63a2668c4b4e0ac4839805", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-07T03:37:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T03:37:41.000Z", "avg_line_length": 23.1666666667, "max_line_length": 58, "alphanum_fraction": 0.5755395683, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7527431553315984}}
{"text": "using ChaoticEncryption\nusing TestImages\nusing Test\n\n@testset \"ChaoticEncryption.jl\" begin\n\n    @testset \"Logistic Map\" begin\n        @test typeof(logistic_key(0.01, 3.97, 20)) == Array{Int64, 1}\n        @test length(logistic_key(0.01, 3.97, 20)) == 20\n    end\n\n    @testset \"Lorenz System of Differential Equations\" begin\n        @test typeof(lorenz_key(0.01, 0.02, 0.03, 20)) == Tuple{Array{Int64, 1}, Array{Int64, 1}, Array{Int64, 1}}\n        @test length(lorenz_key(0.01, 0.02, 0.03, 20)) == 3\n        @test length(lorenz_key(0.01, 0.02, 0.03, 20)[1]) == 20\n        @test length(lorenz_key(0.01, 0.02, 0.03, 20)[2]) == 20\n        @test length(lorenz_key(0.01, 0.02, 0.03, 20)[3]) == 20\n    end\n\n    @testset \"Substitution Encryption\" begin\n        img = testimage(\"mandrill\")\n        height, width = size(img)\n        keys = logistic_key(0.01, 3.97, height * width)\n        substitution_encryption(img, keys; path_for_result=\"../test_images/encrypted.png\")\n        @test isfile(\"../test_images/encrypted.png\")\n\n        keys = logistic_key(0.01, 3.97, 20)\n        @test_throws ArgumentError(\"Number of keys must be equal to height * width of image.\") substitution_encryption(img, keys; path_for_result=\"../test_images/encrypted.png\")\n    end\n\n    @testset \"Substitution Decryption\" begin\n        img = testimage(\"mandrill\")\n        height, width = size(img)\n        keys = logistic_key(0.01, 3.97, height * width)\n\n        substitution_decryption(\"../test_images/encrypted.png\", keys; path_for_result=\"../test_images/decrypted.png\")\n        @test isfile(\"../test_images/decrypted.png\")\n\n        substitution_decryption(img, keys; path_for_result=\"../test_images/decrypted.png\")\n        @test isfile(\"../test_images/decrypted.png\")\n\n        @test_throws ArgumentError(\"image must be of the type ::String or ::Array{RGB{N0f8},2}\") substitution_decryption(5, keys; path_for_result=\"../test_images/decrypted.png\")\n\n        keys = logistic_key(0.01, 3.97, 20)\n        @test_throws ArgumentError(\"Number of keys must be equal to height * width of image.\") substitution_decryption(img, keys; path_for_result=\"../test_images/decrypted.png\")\n\n        rm(\"../test_images\", recursive=true)\n    end\nend\n", "meta": {"hexsha": "6217436595455bbd0a8d1bcea8d436c2b8ca4382", "size": 2194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_chaotic_encryption.jl", "max_stars_repo_name": "gitter-badger/ChaoticEncryption.jl", "max_stars_repo_head_hexsha": "f994303c554c43e207421e6d70d74e6f29eb966f", "max_stars_repo_licenses": ["MIT"], "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_chaotic_encryption.jl", "max_issues_repo_name": "gitter-badger/ChaoticEncryption.jl", "max_issues_repo_head_hexsha": "f994303c554c43e207421e6d70d74e6f29eb966f", "max_issues_repo_licenses": ["MIT"], "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_chaotic_encryption.jl", "max_forks_repo_name": "gitter-badger/ChaoticEncryption.jl", "max_forks_repo_head_hexsha": "f994303c554c43e207421e6d70d74e6f29eb966f", "max_forks_repo_licenses": ["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.88, "max_line_length": 177, "alphanum_fraction": 0.6590701914, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7527431515255122}}
{"text": "include(\"../functions/Functions.jl\")\ninclude(\"../evaluate/Evaluate.jl\")\ninclude(\"../opt/GradientDescent.jl\")\ninclude(\"../data/data.jl\")\n\n\nX, y = getOldData()\n\nlambda = 0.00001\niter = 1000\n\nx0 = zeros(size(X,2),1)\n\nf = f_logreg(X,y,x0,lambda)\ng = g_logreg(X,y,x0,lambda)\n\n\n#f = f_svm(X,y,x0,lambda)\n#g = sub_g_svm()\n\n@time (theta, status,vals1,stops1 ) = qn(x0,f,g,1e-12,iter,20,20,1e-4,.9,\"bt\",\"gd\")\n\ngrad = g(theta)\ngrad_norm = norm(grad, Inf)\n@printf(\"Inf-Norm of gradient is %f.\\n\",grad_norm)\nprintln(evaluate(X,y,theta,\"logreg\",false))\n", "meta": {"hexsha": "e7af3cb52e029463a5c8c0b31e452bf26618deb1", "size": 540, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test/gd_test.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/test/gd_test.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/test/gd_test.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.0, "max_line_length": 83, "alphanum_fraction": 0.6611111111, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7527431495075176}}
{"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(; \u03bb, \u03b5) = SellmeierFit.read(path)\n\n# Fit the loaded data to the Sellmeier equation.\n(; mdl, err) = fit_sellmeier(\u03bb, \u03b5)\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(\"\u221aC (\u00b5m) = $(mdl.\u03bbres ./ micro)\")\nprintln(\"Error between data and fit = $err\")\n\n# Visualize the measured data and fit Sellmeier equation; note that n = \u221a\u03b5.\nfontsize = 20\nfig = Figure(; fontsize)\nAxis(fig[1,1], title=\"Refractive Index of SiO\u2082\", xlabel=\"\u03bb (meter)\", ylabel=\"n\")\nscatter!(\u03bb, .\u221a\u03b5, label=\"Measurement\", color=:black)\nlines!(\u03bb, .\u221amdl.(\u03bb), 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": "@testset \"TSP\" begin\n\nusing STMO.TSP\n\nX = [1 1; 1 3; 2 2; 2 1]\n\ntsp = TravelingSalesmanProblem(X)\n\n@test tsp isa TravelingSalesmanProblem{Int}\n\ntour = [4, 1, 2, 3]\n\nn = length(tour)\n\n@test n == 4\n\n@test Set(cities(tsp)) == Set(tour)\n\n@test isvalid(tsp, tour)\n@test !isvalid(tsp, [1, 2, 3])\n@test !isvalid(tsp, [1, 2, 3, 4, 5])\n@test !isvalid(tsp, [3, 1, 2, 3])\n\n@test dist(tsp, 2, 3) \u2248 sqrt(2)\n@test computecost(tsp, tour) \u2248 2 + sqrt(2) + 1 + 1\n\n@testset \"swapping\" begin\n    cost = computecost(tsp, tour)\n\n    for i in 1:n\n        for j in 1:n\n            \u0394c = deltaswapcost(tsp, tour, i, j)\n            swap!(tour, i, j)\n            @test computecost(tsp, tour) \u2248 cost + \u0394c\n            swap!(tour, i, j)\n        end\n    end\nend\n\n@testset \"flipping\" begin\n    cost = computecost(tsp, tour)\n\n    for i in 1:n\n        for j in 1:n\n            \u0394c = deltaflipcost(tsp, tour, i, j)\n            flip!(tour, i, j)\n            @test computecost(tsp, tour) \u2248 cost + \u0394c\n            flip!(tour, i, j)\n        end\n    end\nend\n\nend\n", "meta": {"hexsha": "98f196544f97c53c63823faf1a58cd6712397c4a", "size": 1020, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/tsp.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": "test/tsp.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": "test/tsp.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": 18.8888888889, "max_line_length": 52, "alphanum_fraction": 0.5392156863, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7527372805189644}}
{"text": "# Testing:\n#\n#  - computation of sufficient statistics\n#  - distribution fitting (i.e. estimation)\n#\n\nusing Distributions\nusing Test, Random, LinearAlgebra\n\n\nn0 = 100\nN = 10^5\n\nw = rand(n0)\n\n# DiscreteUniform\n\nx = rand(DiscreteUniform(10, 15), n0)\nd = fit(DiscreteUniform, x)\n@test isa(d, DiscreteUniform)\n@test minimum(d) == minimum(x)\n@test maximum(d) == maximum(x)\n\nd = fit(DiscreteUniform, rand(DiscreteUniform(10, 15), N))\n@test minimum(d) == 10\n@test maximum(d) == 15\n\n\n# Bernoulli\n\nx = rand(Bernoulli(0.7), n0)\n\nss = suffstats(Bernoulli, x)\n@test isa(ss, Distributions.BernoulliStats)\n@test ss.cnt0 == n0 - count(t->t != 0, x)\n@test ss.cnt1 == count(t->t != 0, x)\n\nss = suffstats(Bernoulli, x, w)\n@test isa(ss, Distributions.BernoulliStats)\n@test ss.cnt0 \u2248 sum(w[x .== 0])\n@test ss.cnt1 \u2248 sum(w[x .== 1])\n\nd = fit(Bernoulli, x)\np = count(t->t != 0, x) / n0\n@test isa(d, Bernoulli)\n@test mean(d) \u2248 p\n\nd = fit(Bernoulli, x, w)\np = sum(w[x .== 1]) / sum(w)\n@test isa(d, Bernoulli)\n@test mean(d) \u2248 p\n\nd = fit(Bernoulli, rand(Bernoulli(0.7), N))\n@test isa(d, Bernoulli)\n@test isapprox(mean(d), 0.7, atol=0.01)\n\n\n# Beta\n\nd = fit(Beta, rand(Beta(1.3, 3.7), N))\n@test isa(d, Beta)\n@test isapprox(d.\u03b1, 1.3, atol=0.1)\n@test isapprox(d.\u03b2, 3.7, atol=0.1)\n\n\n# Binomial\n\nx = rand(Binomial(100, 0.3), n0)\n\nss = suffstats(Binomial, (100, x))\n@test isa(ss, Distributions.BinomialStats)\n@test ss.ns \u2248 sum(x)\n@test ss.ne == n0\n@test ss.n == 100\n\nss = suffstats(Binomial, (100, x), w)\n@test isa(ss, Distributions.BinomialStats)\n@test ss.ns \u2248 dot(Float64[xx for xx in x], w)\n@test ss.ne \u2248 sum(w)\n@test ss.n == 100\n\nd = fit(Binomial, (100, x))\n@test isa(d, Binomial)\n@test ntrials(d) == 100\n@test succprob(d) \u2248 sum(x) / (n0 * 100)\n\nd = fit(Binomial, (100, x), w)\n@test isa(d, Binomial)\n@test ntrials(d) == 100\n@test succprob(d) \u2248 dot(x, w) / (sum(w) * 100)\n\nd = fit(Binomial, 100, rand(Binomial(100, 0.3), N))\n@test isa(d, Binomial)\n@test ntrials(d) == 100\n@test isapprox(succprob(d), 0.3, atol=0.01)\n\n\n# Categorical\n\np = [0.2, 0.5, 0.3]\nx = rand(Categorical(p), n0)\n\nss = suffstats(Categorical, (3, x))\nh = Float64[count(v->v == i, x) for i = 1 : 3]\n@test isa(ss, Distributions.CategoricalStats)\n@test ss.h \u2248 h\n\nd = fit(Categorical, (3, x))\n@test isa(d, Categorical)\n@test d.K == 3\n@test probs(d) \u2248 h / sum(h)\n\nd2 = fit(Categorical, x)\n@test isa(d2, Categorical)\n@test probs(d2) == probs(d)\n\nss = suffstats(Categorical, (3, x), w)\nh = Float64[sum(w[x .== i]) for i = 1 : 3]\n@test isa(ss, Distributions.CategoricalStats)\n@test ss.h \u2248 h\n\nd = fit(Categorical, (3, x), w)\n@test isa(d, Categorical)\n@test probs(d) \u2248 h / sum(h)\n\nd = fit(Categorical, suffstats(Categorical, 3, x, w))\n@test isa(d, Categorical)\n@test probs(d) \u2248 (h / sum(h))\n\nd = fit(Categorical, rand(Categorical(p), N))\n@test isa(d, Categorical)\n@test isapprox(probs(d), p, atol=0.01)\n\n\n# Cauchy\n\n@test fit(Cauchy, collect(-4.0:4.0)) === Cauchy(0.0, 2.0)\n\n\n# Exponential\n\nx = rand(Exponential(0.5), n0)\n\nss = suffstats(Exponential, x)\n@test isa(ss, Distributions.ExponentialStats)\n@test ss.sx \u2248 sum(x)\n@test ss.sw == n0\n\nss = suffstats(Exponential, x, w)\n@test isa(ss, Distributions.ExponentialStats)\n@test ss.sx \u2248 dot(x, w)\n@test ss.sw == sum(w)\n\nd = fit(Exponential, x)\n@test isa(d, Exponential)\n@test scale(d) \u2248 mean(x)\n\nd = fit(Exponential, x, w)\n@test isa(d, Exponential)\n@test scale(d) \u2248 dot(x, w) / sum(w)\n\nd = fit(Exponential, rand(Exponential(0.5), N))\n@test isa(d, Exponential)\n@test isapprox(scale(d), 0.5, atol=0.01)\n\n\n# Normal\n\n\u03bc = 11.3\n\u03c3 = 3.2\n\nx = rand(Normal(\u03bc, \u03c3), n0)\n\nss = suffstats(Normal, x)\n@test isa(ss, Distributions.NormalStats)\n@test ss.s  \u2248 sum(x)\n@test ss.m  \u2248 mean(x)\n@test ss.s2 \u2248 sum((x .- ss.m).^2)\n@test ss.tw \u2248 n0\n\nss = suffstats(Normal, x, w)\n@test isa(ss, Distributions.NormalStats)\n@test ss.s  \u2248 dot(x, w)\n@test ss.m  \u2248 dot(x, w) / sum(w)\n@test ss.s2 \u2248 dot((x .- ss.m).^2, w)\n@test ss.tw \u2248 sum(w)\n\nd = fit(Normal, x)\n@test isa(d, Normal)\n@test d.\u03bc \u2248 mean(x)\n@test d.\u03c3 \u2248 sqrt(mean((x .- d.\u03bc).^2))\n\nd = fit(Normal, x, w)\n@test isa(d, Normal)\n@test d.\u03bc \u2248 dot(x, w) / sum(w)\n@test d.\u03c3 \u2248 sqrt(dot((x .- d.\u03bc).^2, w) / sum(w))\n\nd = fit(Normal, rand(Normal(\u03bc, \u03c3), N))\n@test isa(d, Normal)\n@test isapprox(d.\u03bc, \u03bc, atol=0.1)\n@test isapprox(d.\u03c3, \u03c3, atol=0.1)\n\nimport Distributions.NormalKnownMu, Distributions.NormalKnownSigma\n\nss = suffstats(NormalKnownMu(\u03bc), x)\n@test isa(ss, Distributions.NormalKnownMuStats)\n@test ss.\u03bc == \u03bc\n@test ss.s2 \u2248 sum(abs2.(x .- \u03bc))\n@test ss.tw \u2248 n0\n\nss = suffstats(NormalKnownMu(\u03bc), x, w)\n@test isa(ss, Distributions.NormalKnownMuStats)\n@test ss.\u03bc == \u03bc\n@test ss.s2 \u2248 dot((x .- \u03bc).^2, w)\n@test ss.tw \u2248 sum(w)\n\nd = fit_mle(Normal, x; mu=\u03bc)\n@test isa(d, Normal)\n@test d.\u03bc == \u03bc\n@test d.\u03c3 \u2248 sqrt(mean((x .- d.\u03bc).^2))\n\nd = fit_mle(Normal, x, w; mu=\u03bc)\n@test isa(d, Normal)\n@test d.\u03bc == \u03bc\n@test d.\u03c3 \u2248 sqrt(dot((x .- d.\u03bc).^2, w) / sum(w))\n\n\nss = suffstats(NormalKnownSigma(\u03c3), x)\n@test isa(ss, Distributions.NormalKnownSigmaStats)\n@test ss.\u03c3 == \u03c3\n@test ss.sx \u2248 sum(x)\n@test ss.tw \u2248 n0\n\nss = suffstats(NormalKnownSigma(\u03c3), x, w)\n@test isa(ss, Distributions.NormalKnownSigmaStats)\n@test ss.\u03c3 == \u03c3\n@test ss.sx \u2248 dot(x, w)\n@test ss.tw \u2248 sum(w)\n\nd = fit_mle(Normal, x; sigma=\u03c3)\n@test isa(d, Normal)\n@test d.\u03c3 == \u03c3\n@test d.\u03bc \u2248 mean(x)\n\nd = fit_mle(Normal, x, w; sigma=\u03c3)\n@test isa(d, Normal)\n@test d.\u03c3 == \u03c3\n@test d.\u03bc \u2248 dot(x, w) / sum(w)\n\n\n# Uniform\n\nx = rand(Uniform(1.2, 5.8), n0)\nd = fit(Uniform, x)\n@test isa(d, Uniform)\n@test 1.2 <= minimum(d) <= maximum(d) <= 5.8\n@test minimum(d) == minimum(x)\n@test maximum(d) == maximum(x)\n\nd = fit(Uniform, rand(Uniform(1.2, 5.8), N))\n@test 1.2 <= minimum(d) <= maximum(d) <= 5.8\n@test isapprox(minimum(d), 1.2, atol=0.02)\n@test isapprox(maximum(d), 5.8, atol=0.02)\n\n\n# Gamma\n\nx = rand(Gamma(3.9, 2.1), n0)\n\nss = suffstats(Gamma, x)\n@test isa(ss, Distributions.GammaStats)\n@test ss.sx    \u2248 sum(x)\n@test ss.slogx \u2248 sum(log.(x))\n@test ss.tw    \u2248 n0\n\nss = suffstats(Gamma, x, w)\n@test isa(ss, Distributions.GammaStats)\n@test ss.sx    \u2248 dot(x, w)\n@test ss.slogx \u2248 dot(log.(x), w)\n@test ss.tw    \u2248 sum(w)\n\nd = fit(Gamma, rand(Gamma(3.9, 2.1), N))\n@test isa(d, Gamma)\n@test isapprox(shape(d), 3.9, atol=0.1)\n@test isapprox(scale(d), 2.1, atol=0.2)\n\n\n# Geometric\n\nx = rand(Geometric(0.3), n0)\n\nss = suffstats(Geometric, x)\n@test isa(ss, Distributions.GeometricStats)\n@test ss.sx \u2248 sum(x)\n@test ss.tw \u2248 n0\n\nss = suffstats(Geometric, x, w)\n@test isa(ss, Distributions.GeometricStats)\n@test ss.sx \u2248 dot(x, w)\n@test ss.tw \u2248 sum(w)\n\nd = fit(Geometric, x)\n@test isa(d, Geometric)\n@test succprob(d) \u2248 inv(1. + mean(x))\n\nd = fit(Geometric, x, w)\n@test isa(d, Geometric)\n@test succprob(d) \u2248 inv(1. + dot(x, w) / sum(w))\n\nd = fit(Geometric, rand(Geometric(0.3), N))\n@test isa(d, Geometric)\n@test isapprox(succprob(d), 0.3, atol=0.01)\n\n\n# Laplace\n\nd = fit(Laplace, rand(Laplace(5.0, 3.0), N))\n@test isa(d, Laplace)\n@test isapprox(location(d), 5.0, atol=0.1)\n@test isapprox(scale(d)   , 3.0, atol=0.2)\n\n# Pareto\n\nx = rand(Pareto(3., 7.), N)\nd = fit(Pareto, x)\n\n@test isa(d, Pareto)\n@test isapprox(shape(d), 3., atol=0.1)\n@test isapprox(scale(d), 7., atol=0.1)\n\n# Poisson\n\nx = rand(Poisson(8.2), n0)\n\nss = suffstats(Poisson, x)\n@test isa(ss, Distributions.PoissonStats)\n@test ss.sx \u2248 sum(x)\n@test ss.tw \u2248 n0\n\nss = suffstats(Poisson, x, w)\n@test isa(ss, Distributions.PoissonStats)\n@test ss.sx \u2248 dot(x, w)\n@test ss.tw \u2248 sum(w)\n\nd = fit(Poisson, x)\n@test isa(d, Poisson)\n@test mean(d) \u2248 mean(x)\n\nd = fit(Poisson, x, w)\n@test isa(d, Poisson)\n@test mean(d) \u2248 dot(Float64[xx for xx in x], w) / sum(w)\n\nd = fit(Poisson, rand(Poisson(8.2), N))\n@test isa(d, Poisson)\n@test isapprox(mean(d), 8.2, atol=0.2)\n", "meta": {"hexsha": "2de66cbd689eee89cdac0dd56d5e1364c0465b15", "size": 7606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/fit.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": "test/fit.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": "test/fit.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": 21.3651685393, "max_line_length": 66, "alphanum_fraction": 0.6305548251, "num_tokens": 2885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7527372792492045}}
{"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\u00e1nchez\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\u00e1nchez \")\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": "using LocallyCompetitive\nusing Test\nusing Random\nusing Statistics\n\n# Testing params\nM = 100\nN = 100\n\nk = 10\n\nRandom.seed!(0)\n\n# Dictionary\nbasis = randn(M,N)\n\n# Make k sparse signal\nvals  = rand(M)\nvals[sortperm(rand(M))[k+1:end]] .= 0\n\n# Input signal with k sparse structure\nsig = basis*vals\n\n# Learn 'vals' based upon sig and the basis\nout = LocallyCompetitive.lca(sig, basis)\n\nrecon = basis*out\n\nsparse_orig = vals .!= 0\nsparse_new  = out  .!= 0\n\nsse_orig  = mean(recon.^2)\nsse_new   = mean(sig.^2)\nsse_diff  = mean((sig.-recon).^2)\n\n# Same sparsity found in output\n@test sparse_orig == sparse_new\n\n# Reconstruction models data\n@test sse_orig*0.01 > sse_diff\n@test sse_new *0.01 > sse_diff\n", "meta": {"hexsha": "ab4ba173a55e18982707497f03b240307a60e22c", "size": 693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirror/LocallyCompetitive.jl-86bb8979-40af-4c14-b177-a78efc84e952", "max_stars_repo_head_hexsha": "d4a8cc5578c762a35c7497a4dc00ac1fed1ae83c", "max_stars_repo_licenses": ["MIT"], "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/LocallyCompetitive.jl-86bb8979-40af-4c14-b177-a78efc84e952", "max_issues_repo_head_hexsha": "d4a8cc5578c762a35c7497a4dc00ac1fed1ae83c", "max_issues_repo_licenses": ["MIT"], "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/LocallyCompetitive.jl-86bb8979-40af-4c14-b177-a78efc84e952", "max_forks_repo_head_hexsha": "d4a8cc5578c762a35c7497a4dc00ac1fed1ae83c", "max_forks_repo_licenses": ["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": 43, "alphanum_fraction": 0.7027417027, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7526843189925906}}
{"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\u22121,k}`` between successive \ntime steps ``t_{k\u22121}`` and ``t_k``.\n``\u03b7 = {\u03b71,\u03b72,... ,\u03b7K}`` 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, ``\u03b7_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``. ``\u03b5 = {\u03b51, \u03b52, . . . , \u03b5k}`` is an\nindependent and identically distributed process representing the observation \nerrors; ``\u03b5_k`` is assumed\nGaussian with zero mean and covariance matrix ``R``. Finally, the\nprocesses ``\u03b7`` and ``\u03b5`` 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": "\nusing DomainSets: \u00d7\n\n\"Does `z` agree with `val` up to the given `threshold`?\"\nisaccurate(z, val, threshold = 1e-5) = abs(z-val) < threshold\n\nfunction test_readme_examples()\n    # Examples of README.md\n    threshold = 1e-5\n    @test isaccurate(integral(cos, 0..1.0), 0.8414709848078965)\n    @test isaccurate(integral(x -> exp(x[1]+x[2]), (0..1.0)^2), 2.9524924420120535)\n    @test isaccurate(quadrature(cos, UnionDomain(0..1, 2..3))[1], 0.07329356604208204)\n    @test isaccurate(integral(t -> sin(log(abs(t))), -1..1, LogPointSingularity(0.0)), -1.0000000021051316)\n    @test isaccurate(integral( x -> exp(log(abs(x[1]-x[2]))), (2..3) \u00d7 (1..4), DiagonalSingularity()),\n2.333333333333333)\n    @test isaccurate(integral(cos, ChebyshevTMeasure()), 2.403939430634413)\n    @test isaccurate(integral(t -> cos(t)*1/sqrt(1-t^2), -1.0..1.0), 2.403939410869398)\n    @test isaccurate(quadrature(QuadAdaptive(atol=1e-3, rtol = 1e-3), t->cos(t^2), 0..10)[1], 0.6011251848111901, 1e-3)\n    @test isaccurate(integral(Q_GaussLaguerre(10), cos), 0.5000005097999486)\n    @test isaccurate(integral(t -> cos(t)*exp(-t), HalfLine()), 0.5)\nend\n\nfunction test_some_integrals()\n    z1 = sin(1.0)\n    @test abs(integral(cos, 0..1.0) - z1) < 1e-8\n    I, E = quadrature(cos, 0..1.0)\n    @test abs(I-z1) < 1e-8\n    @test E < 1e-8\n\n    f2 = x -> exp(x[1]+x[2])\n    z2 = hcubature(f2, (0,0), (1,1))[1]\n    @test abs(integral(f2, (0..1)^2) - z2) < 1e-6\nend\n\nfunction test_integrals()\n    test_some_integrals()\n    test_readme_examples()\nend\n", "meta": {"hexsha": "c1f361560a1000b97b7dbf598e31eec50898cc23", "size": 1510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_integrals.jl", "max_stars_repo_name": "GeorgAUT/DomainIntegrals.jl", "max_stars_repo_head_hexsha": "d58303eb9e33d42479e10f95677f639d3b505c25", "max_stars_repo_licenses": ["MIT"], "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_integrals.jl", "max_issues_repo_name": "GeorgAUT/DomainIntegrals.jl", "max_issues_repo_head_hexsha": "d58303eb9e33d42479e10f95677f639d3b505c25", "max_issues_repo_licenses": ["MIT"], "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_integrals.jl", "max_forks_repo_name": "GeorgAUT/DomainIntegrals.jl", "max_forks_repo_head_hexsha": "d58303eb9e33d42479e10f95677f639d3b505c25", "max_forks_repo_licenses": ["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.7179487179, "max_line_length": 119, "alphanum_fraction": 0.6443708609, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7526843119192329}}
{"text": "using FinancialMonteCarlo, Distributions, Test;\n@show \"Test Parameters\"\nS0 = 100.0;\nr = 0.02;\nd = 0.01;\nT = 1.0;\nNsim = 100;\nNstep = 30;\n\nsigma = 0.2;\n\nMcConfig = MonteCarloConfiguration(Nsim, Nstep);\nmc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());\nrfCurve = ZeroRate(r);\nrfCurve2 = ZeroRate([0.00, 0.02], T);\n\n@show \"Test Subordinated Brownian Motion Parameters\"\ndrift = 0.0;\n@test_throws(ErrorException, SubordinatedBrownianMotion(-sigma, drift, InverseGaussian(1.0, 1.0)))\n@test_throws(ErrorException, SubordinatedBrownianMotion(-sigma, rfCurve2.r, InverseGaussian(1.0, 1.0)))\n", "meta": {"hexsha": "9fb6e0d57fdf7db272d0b96149879a141daf180a", "size": 612, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_sub_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": "test/test_sub_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": "test/test_sub_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.1428571429, "max_line_length": 103, "alphanum_fraction": 0.7467320261, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7526843116123736}}
{"text": "function fahrenheit_to_celsius(temp_f)\n    temp_c = (temp_f - 32.0) * (5.0/9.0)\n    return temp_c\nend\n\ntemp_c = fahrenheit_to_celsius(100.0)\nprintln(temp_c)\n", "meta": {"hexsha": "a95ed1ae5c2e8bc65f0ee813d7248d07601eb182", "size": 157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/code/julia/fahrenheit_to_celsius_pure.jl", "max_stars_repo_name": "transferorbit/coderefinery_testing", "max_stars_repo_head_hexsha": "b1011345cd6ed614e702b372bd2d987521bba130", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-03-11T12:36:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T00:32:11.000Z", "max_issues_repo_path": "content/code/julia/fahrenheit_to_celsius_pure.jl", "max_issues_repo_name": "transferorbit/coderefinery_testing", "max_issues_repo_head_hexsha": "b1011345cd6ed614e702b372bd2d987521bba130", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 126, "max_issues_repo_issues_event_min_datetime": "2016-12-13T11:12:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:17:17.000Z", "max_forks_repo_path": "content/code/julia/fahrenheit_to_celsius_pure.jl", "max_forks_repo_name": "transferorbit/coderefinery_testing", "max_forks_repo_head_hexsha": "b1011345cd6ed614e702b372bd2d987521bba130", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2016-12-13T11:00:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T13:53:07.000Z", "avg_line_length": 19.625, "max_line_length": 40, "alphanum_fraction": 0.7197452229, "num_tokens": 56, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7526843069985683}}
{"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 \u03a3\nfunction minvolw(\u03bc, z, \u03a3, \u03a3inv = \u03a3\\I)\n  K= length(z)\n  some1s = ones(K)\n\n  A = some1s' * \u03a3inv * some1s\n  B = some1s' * \u03a3inv * z\n  C = z' * \u03a3inv * z\n\n  \u03bb =(\u03bc * B - C) /(B^2 - A*C)\n  \u03b3 = (\u03bc * A - B) /(A*C -B^2)\n\n\n  w = \u03bb * \u03a3inv * some1s .+ \u03b3 * \u03a3inv * z\n\n  return w\nend\n\n#same as before but acquires the solution numerically\nfunction nminvolw(\u03bc, z, \u03a3)\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', -\u03bc, COSMO.ZeroSet)\n  COSMO.assemble!(m, \u03a3, 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, \u0394=0.001)\n  Erm = 0.08 #expected market reutn\n  rf = 0.02 #risk free rate\n  \u03c3m = 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, \u03c3m), N) #the market returns\n  noise = reduce(hcat, (\u03c3e->rand(Normal(0, \u03c3e), N)).(ivol))\n  r = rm .* beta' .+ noise\n\n  z = mean(r, dims=1) |> vec\n  \u03a3 = cov(r)\n\n  #sanity check\n  \u03a3inv = \u03a3\\I\n  w = minvolw(0.1, z, \u03a3, \u03a3inv)\n  nw = nminvolw(0.1, z, \u03a3)\n  @assert w \u2248 nw\n\n  minvol\u03c3(\u03bc) = minvolw(\u03bc, z, \u03a3, \u03a3inv) |> (w)->(w'*\u03a3*w)^0.5\n  nminvol\u03c3(\u03bc) = nminvolw(\u03bc, z, \u03a3) |> (w)->(w'*\u03a3*w)^0.5\n\n  #compute the minimum variance frontier\n  \u03bcs = 0.01:\u0394:0.2 |> collect\n  \u03c3s = similar(\u03bcs)\n  Threads.@threads for i \u2208 1:length(\u03bcs)\n    \u03c3s[i] = minvol\u03c3(\u03bcs[i])\n  end\n\n  #compute global min var portfolio\n  some1s = ones(K)\n  A = some1s' * \u03a3inv * some1s\n  B = some1s' * \u03a3inv * z\n\n  wg = \u03a3inv * some1s / A\n  \u03c3g = (wg'*\u03a3*wg)^(0.5)\n  rg = z' * wg\n\n  #compute the tangency portfolio\n  wt = \u03a3inv * (z .- some1s .* rf) ./ (B-rf*A)\n  rt = z'*wt\n  \u03c3t = (wt'*\u03a3*wt)^(0.5)\n\n  pth = \"C:\\\\Users\\\\Clinton\\\\Dropbox\\\\AAtawork\\\\ChernovInvestments\\\\Investments\\\\2020\\\\Exams\\\\final\"\n  p = plot(\u03c3s, \u03bcs,\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; \u03c3t; \u03c3s[\u03bcs .> rt]], [rf; rt; \u03bcs[\u03bcs .> rt]],\n    linestyle=:dash, seriestype=:path, linecolor=:black, linewidth=4,\n    annotations=(\u03c3t*1.5, rt*1.2,\n    Plots.text(\"min var frontier\\n (rf asset, no borrowing)\", :left, 7,)))\n  plot!(pans, [0.0; \u03c3t; \u03c3t*10], [rf; rt; (rt-rf)*10],\n    linestyle=:solid, seriestype=:path, linecolor=:black, linewidth=2,\n    annotations=(\u03c3t*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, [\u03c3t], [rt], markersize=6,\n    annotations=(\u03c3t+0.005, rt-0.0025, Plots.text(\"tangency portfolio\", :left, 7,)))\n  scatter!(pans, [\u03c3g], [rg],markersize=6,\n    annotations=(\u03c3g+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": "using OrdinaryDiffEq, Distributions,\r\n      DiffEqUncertainty, Test, Quadrature, Cubature\r\n\r\nfunction f(du,u,p,t)\r\n  @inbounds begin\r\n    du[1] = dx = p[1]*u[1] - u[1]*u[2]\r\n    du[2] = dy = -3*u[2] + u[1]*u[2]\r\n  end\r\n  nothing\r\nend\r\n\r\nu0 = [1.0;1.0]\r\ntspan = (0.0,10.0)\r\np = [1.5]\r\nprob = ODEProblem(f,u0,tspan,p)\r\nsol = solve(remake(prob,u0=u0),Tsit5())\r\ncost(sol) = sum(max(x[1]-6,0) for x in sol.u)\r\nu0s = [Uniform(0.25,5.5),Uniform(0.25,5.5)]\r\nps  = [Uniform(0.5,2.0)]\r\n@time sol = koopman_expectation(cost,u0s,ps,prob,Tsit5();iabstol=1e-3,ireltol=1e-3,maxiters=1000,saveat=0.1)\r\nc1, e1 = sol.u, sol.resid\r\n@time sol = koopman_expectation(cost,u0s,ps,prob,Tsit5(),EnsembleThreads();quadalg=CubatureJLh(),\r\n                         batch=1000,iabstol=1e-3,ireltol=1e-3,\r\n                         maxiters=2000,saveat=0.1)\r\nc2, e2 = sol.u, sol.resid\r\n@test abs(c1 - c2) < 0.1\r\n\r\n@time c3 = montecarlo_expectation(cost,u0s,ps,prob,Tsit5(),EnsembleThreads();trajectories=100000,saveat=0.1)\r\n@test abs(c1 - c3) < 0.1\r\n\r\n#=\r\nusing DiffEqGPU\r\n@time sol = koopman_expectation(cost,u0s,ps,prob,Tsit5(),EnsembleGPUArray();quadalg=CubatureJLh(),\r\n                         batch=1000,iabstol=1e-3,ireltol=1e-3,\r\n                         maxiters=2000,saveat=0.1)\r\nc2, e2 = sol.u, sol.resid\r\n@test abs(c1 - c2) < 0.1\r\n\r\n@time c3 = montecarlo_expectation(cost,u0s,ps,prob,Tsit5(),EnsembleGPUArray();trajectories=100000,saveat=0.1)\r\n@test abs(c1 - c3) < 0.1\r\n=#\r\n", "meta": {"hexsha": "2bb52927dbe9e33c078bad42ca76cf02331bb50d", "size": 1454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/koopman.jl", "max_stars_repo_name": "JuliaTagBot/DiffEqUncertainty.jl", "max_stars_repo_head_hexsha": "2df821f777499267015002cf1df7abb9b3b26973", "max_stars_repo_licenses": ["MIT"], "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/koopman.jl", "max_issues_repo_name": "JuliaTagBot/DiffEqUncertainty.jl", "max_issues_repo_head_hexsha": "2df821f777499267015002cf1df7abb9b3b26973", "max_issues_repo_licenses": ["MIT"], "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/koopman.jl", "max_forks_repo_name": "JuliaTagBot/DiffEqUncertainty.jl", "max_forks_repo_head_hexsha": "2df821f777499267015002cf1df7abb9b3b26973", "max_forks_repo_licenses": ["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.619047619, "max_line_length": 110, "alphanum_fraction": 0.6176066025, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7526127237119423}}
{"text": "\nimport JuLIP.Potentials: @pot, @D, evaluate, evaluate_d, PairPotential, @analytic\n\n@pot type Morseold <: PairPotential\n   e0::Float64\n   A::Float64\n   r0::Float64\nend\nevaluate(p::Morseold, r) = p.e0 * (exp(-2*p.A*(r/p.r0-1.0)) - 2.0*exp(-p.A*(r/p.r0-1.0)))\nevaluate_d(p::Morseold, r) = -2.0*p.e0*p.A/p.r0*(exp(-2*p.A*(r/p.r0-1.0)) - exp(-p.A*(r/p.r0-1.0)))\n\nconst e0 = 0.99\nconst r0 = 1.05\nconst A = 4.1\n\nmorse = @analytic( r -> e0 * (exp(-2*A*(r/r0-1.0)) - 2.0*exp(-A*(r/r0-1.0))) )\n@show typeof(morse)\nmorseold = Morseold(e0, A, r0)\n\nrr = collect(linspace(0.9, 2.1, 100))\nmorse_r = morse.(rr)\nmorseold_r = morseold.(rr)\ndmorse_r = [(@D morse(r)) for r in rr]\ndmorseold_r = [ (@D morseold(r)) for r in rr ]\n\nprintln(\"Check consistency of hand-coded and analytic Morse potentials...\")\n@test vecnorm(morse_r - morseold_r, Inf) < 1e-12\n@test vecnorm(dmorse_r - dmorseold_r, Inf) < 1e-12\n\nfunction test(N, p)\n   r = 1.234\n   s = 0.0\n   for n = 1:N\n      s += p(r)\n   end\n   return s\nend\n\nfunction testgrad(N, p)\n   r = 1.234\n   s = 0.0\n   for n = 1:N\n      s += @D p(r)\n   end\n   return s\nend\n\ntest(10, morse);\ntest(10, morseold);\ntestgrad(10, morse);\ntestgrad(10, morseold);\n\nprintln(\"1M evaluations of Analytic Potential\")\n@time test(1_000_000, morse)\nprintln(\"1M evaluations of old Potential\")\n@time test(1_000_000, morseold)\nprintln(\"1M \u2207 evaluations of Analytic Potential\")\n@time testgrad(1_000_000, morse)\nprintln(\"1M \u2207 evaluations of old Potential\")\n@time testgrad(1_000_000, morseold)\n", "meta": {"hexsha": "bb07d6627bb38c6bbb5b89e64c3cf34ca7643458", "size": 1491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testanalyticpotential.jl", "max_stars_repo_name": "hlwang0717/JuLIP.jl", "max_stars_repo_head_hexsha": "c8d325191b99be5c545a0fdb2b8fe11581c125fe", "max_stars_repo_licenses": ["MIT"], "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/testanalyticpotential.jl", "max_issues_repo_name": "hlwang0717/JuLIP.jl", "max_issues_repo_head_hexsha": "c8d325191b99be5c545a0fdb2b8fe11581c125fe", "max_issues_repo_licenses": ["MIT"], "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/testanalyticpotential.jl", "max_forks_repo_name": "hlwang0717/JuLIP.jl", "max_forks_repo_head_hexsha": "c8d325191b99be5c545a0fdb2b8fe11581c125fe", "max_forks_repo_licenses": ["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.4426229508, "max_line_length": 99, "alphanum_fraction": 0.6452045607, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7526127237119423}}
{"text": "@safetestset \"CanonicalSymplecticMatrix\" begin\n    using PoincareInvariants: CanonicalSymplecticMatrix\n    using LinearAlgebra: dot\n\n    @test CanonicalSymplecticMatrix{Int}(2) == [0 -1; 1 0]\n    @test CanonicalSymplecticMatrix{Int}(4) == [0 0 -1 0; 0 0 0 -1; 1 0 0 0; 0 1 0 0]\n    @test CanonicalSymplecticMatrix{Int}(6) == [0  0  0 -1  0  0;\n                                                0  0  0  0 -1  0;\n                                                0  0  0  0  0 -1;\n                                                1  0  0  0  0  0;\n                                                0  1  0  0  0  0;\n                                                0  0  1  0  0  0]\n\n    function test_canonicalmatrix(mat, n, ::Type{T}) where T\n        mid = n \u00f7 2\n\n        for i in 1:n, j in 1:n\n            if i == j - mid\n                mat[i, j] === T(-1) || return false\n            elseif i - mid == j\n                mat[i, j] === T(1) || return false\n            else\n                mat[i, j] === T(0) || return false\n            end\n        end\n\n        return true\n    end\n\n    @testset \"CanonicalSymplecticMatrix{$T}($n)\" for T in [Int, Float64], n in [10, 100, 1000]\n        @test CanonicalSymplecticMatrix(n) === CanonicalSymplecticMatrix{Int}(n)\n\n        C = CanonicalSymplecticMatrix{T}(n)\n        @test size(C) == (n, n)\n        @test eltype(C) == T\n\n        mid = n \u00f7 2\n\n        @test test_canonicalmatrix(C, n, T)\n\n        @test C * collect(1:n) == [(-mid-1:-1:-n)..., 1:mid...]\n\n        @test dot(ones(n), C, ones(n)) == 0\n\n        @test_throws ArgumentError CanonicalSymplecticMatrix{T}(n + 1)\n    end\nend\n", "meta": {"hexsha": "f6966249c27e8415960e57883c15fe72ffb8333a", "size": 1619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_CanonicalSymplecticStructures.jl", "max_stars_repo_name": "Luapulu/PoincareInvariants.jl", "max_stars_repo_head_hexsha": "759f889ce7508a1afeabcd16bca6312e3a5801b3", "max_stars_repo_licenses": ["MIT"], "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_CanonicalSymplecticStructures.jl", "max_issues_repo_name": "Luapulu/PoincareInvariants.jl", "max_issues_repo_head_hexsha": "759f889ce7508a1afeabcd16bca6312e3a5801b3", "max_issues_repo_licenses": ["MIT"], "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_CanonicalSymplecticStructures.jl", "max_forks_repo_name": "Luapulu/PoincareInvariants.jl", "max_forks_repo_head_hexsha": "759f889ce7508a1afeabcd16bca6312e3a5801b3", "max_forks_repo_licenses": ["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.7291666667, "max_line_length": 94, "alphanum_fraction": 0.4484249537, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7526127182067686}}
{"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": "#*******************************************************/\n#* Copyright(c) 2018 by Artelys                        */\n#* This source code is subject to the terms of the     */\n#* MIT Expat License (see LICENSE.md)                  */\n#*******************************************************/\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#  This example demonstrates how to use Knitro to solve the following\n#  simple quadratically constrained quadratic programming problem(QCQP).\n#\n#  min   1000 - x0^2 - 2 x1^2 - x2^2 - x0 x1 - x0 x2 #  s.t.  8 x0 + 14 x1 + 7 x2 = 56\n#        x0^2 + x1^2 + x2^2 >= 25\n#        x0 >= 0, x1 >= 0, x2 >= 0\n#\n#  The start point(2, 2, 2) converges to the minimum at(0, 0, 8),\n#  with final objective = 936.0.  From a different start point,\n#  Knitro may converge to an alternate local solution at(7, 0, 0),\n#  with objective = 951.0.\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nusing KNITRO\nusing Test\n\nfunction example_qcqp1(; verbose=true)\n    # Create a new Knitro solver instance.\n    kc = KNITRO.KN_new()\n\n    # Illustrate how to override default options by reading from\n    # the knitro.opt file.\n    options = joinpath(dirname(@__FILE__), \"..\", \"examples\", \"knitro.opt\")\n    KNITRO.KN_load_param_file(kc, options)\n    kn_outlev = verbose ? KNITRO.KN_OUTLEV_ITER : KNITRO.KN_OUTLEV_NONE\n    KNITRO.KN_set_param(kc, KNITRO.KN_PARAM_OUTLEV, kn_outlev)\n\n    # Initialize Knitro with the problem definition.\n\n    # Add the variables and set their bounds and initial values.\n    # Note: unset bounds assumed to be infinite.\n    KNITRO.KN_add_vars(kc, 3)\n    KNITRO.KN_set_var_lobnds_all(kc, [0.0, 0.0, 0.0])\n    KNITRO.KN_set_var_primal_init_values_all(kc, [2.0, 2.0, 2.0])\n\n    # Add the constraints and set their bounds.\n    KNITRO.KN_add_cons(kc, 2)\n    KNITRO.KN_set_con_eqbnd(kc, 0, 56.0)\n    KNITRO.KN_set_con_lobnd(kc, 1, 25.0)\n\n    # Add coefficients for linear constraint.\n    lconIndexVars = Int32[0, 1, 2]\n    lconCoefs = [8.0, 14.0, 7.0]\n    KNITRO.KN_add_con_linear_struct_one(kc, 3, 0, lconIndexVars, lconCoefs)\n\n    # Add coefficients for quadratic constraint\n    qconIndexVars1 = Int32[0, 1, 2]\n    qconIndexVars2 = Int32[0, 1, 2]\n    qconCoefs = [1.0, 1.0, 1.0]\n    KNITRO.KN_add_con_quadratic_struct_one(\n        kc,\n        3,\n        1,\n        qconIndexVars1,\n        qconIndexVars2,\n        qconCoefs,\n    )\n\n    # Set minimize or maximize(if not set, assumed minimize)\n    KNITRO.KN_set_obj_goal(kc, KNITRO.KN_OBJGOAL_MINIMIZE)\n\n    # Add constant value to the objective.\n    KNITRO.KN_add_obj_constant(kc, 1000.0)\n\n    # Set quadratic objective structure.\n    qobjIndexVars1 = Int32[0, 1, 2, 0, 0]\n    qobjIndexVars2 = Int32[0, 1, 2, 1, 2]\n    qobjCoefs = [-1.0, -2.0, -1.0, -1.0, -1.0]\n\n    KNITRO.KN_add_obj_quadratic_struct(kc, 5, qobjIndexVars1, qobjIndexVars2, qobjCoefs)\n\n    # Solve the problem.\n    #\n    # Return status codes are defined in \"knitro.h\" and described\n    # in the Knitro manual.\n    nStatus = KNITRO.KN_solve(kc)\n    nStatus, objSol, x, lambda_ = KNITRO.KN_get_solution(kc)\n\n    # An example of obtaining solution information.\n    if verbose\n        println(\"Knitro converged with final status = \", nStatus)\n        println(\"  optimal objective value  = \", objSol)\n        println(\"  optimal primal values x  = \", x)\n        println(\"  feasibility violation    = \", KNITRO.KN_get_abs_feas_error(kc))\n        println(\"  KKT optimality violation = \", KNITRO.KN_get_abs_opt_error(kc))\n    end\n\n    # Delete the Knitro solver instance.\n    KNITRO.KN_free(kc)\n\n    @testset \"Example QCQP1\" begin\n        @test nStatus == 0\n        @test objSol \u2248 936.0\n        @test x \u2248 [0.0, 0.0, 8.0]\n    end\nend\n\nexample_qcqp1(; verbose=isdefined(Main, :KN_VERBOSE) ? KN_VERBOSE : true)\n", "meta": {"hexsha": "87cfc2bc22e1c470bb63672e906b699673394cc7", "size": 3796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/qcqp1.jl", "max_stars_repo_name": "JuliaOpt/KNITRO.jl", "max_stars_repo_head_hexsha": "460d60ac1f8bb51ad68c8ccc8a27b906ce060279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2015-02-15T16:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T01:06:10.000Z", "max_issues_repo_path": "examples/qcqp1.jl", "max_issues_repo_name": "JuliaOpt/KNITRO.jl", "max_issues_repo_head_hexsha": "460d60ac1f8bb51ad68c8ccc8a27b906ce060279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2015-01-07T14:50:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T21:54:32.000Z", "max_forks_repo_path": "examples/qcqp1.jl", "max_forks_repo_name": "JuliaOpt/KNITRO.jl", "max_forks_repo_head_hexsha": "460d60ac1f8bb51ad68c8ccc8a27b906ce060279", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2015-01-07T14:47:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T13:44:10.000Z", "avg_line_length": 35.8113207547, "max_line_length": 88, "alphanum_fraction": 0.6093256059, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7525949785022724}}
{"text": "\nimport JuLIP.Potentials: @pot, @D, evaluate!, evaluate_d!, PairPotential, @analytic\nusing LinearAlgebra: norm\nusing BenchmarkTools\nusing JuLIP, Test\n\nh3(\"generate hand-coded morse potential\")\n\nmutable struct Morseold <: PairPotential\n   e0::Float64\n   A::Float64\n   r0::Float64\nend\n\n@pot Morseold\n\nevaluate!(tmp, p::Morseold, r::Number) =\n      p.e0 * (exp(-2*p.A*(r/p.r0-1.0)) - 2.0*exp(-p.A*(r/p.r0-1.0)))\nevaluate_d!(tmp, p::Morseold, r::Number) =\n      -2.0*p.e0*p.A/p.r0*(exp(-2*p.A*(r/p.r0-1.0)) - exp(-p.A*(r/p.r0-1.0)))\n\nA = 4.1\ne0 = 0.99\nr0 = 1.05\n\nmorseold = Morseold(e0, A, r0)\n\nh3(\"generate AD morse potential\")\n\nmorse1 = let A = A, e0 = e0, r0 = r0\n   @analytic( r -> e0 * (exp(-2*A*(r/r0-1.0)) - 2.0*exp(-A*(r/r0-1.0))) )\nend\n@show typeof(morse1)\n\n\nh3(\"Check consistency of hand-coded and analytic Morse potentials...\")\nrr = collect(range(0.9, stop=2.1, length=100))\nmorse_r = morse1.(rr)\nmorseold_r = morseold.(rr)\ndmorse_r = [(@D morse1(r)) for r in rr]\ndmorseold_r = [ (@D morseold(r)) for r in rr ]\n\nprintln(@test norm(morse_r - morseold_r, Inf) < 1e-12)\nprintln(@test norm(dmorse_r - dmorseold_r, Inf) < 1e-12)\n\nfunction runn(f, x, N)\n   s = 0.0\n   for n = 1:N\n      x += 0.0001\n      s += f(x)\n   end\n   return s\nend\n\nfunction runn_d(f, x, N)\n   s = 0.0\n   for n = 1:N\n      x += 0.0001\n      s += @D f(x)\n   end\n   return s\nend\n\n\nh2(\"Performance tests: @analytic vs hand-coded\")\nx = 1.0+rand()\nprintln(\"Evaluations of @analytic Potential\")\n@btime runn($morse1, $x, 1_000)\nprintln(\"Evaluations hand-coded Potential\")\n@btime runn($morseold, $x, 1_000)\nprintln(\"Grad of @analytic Potential\")\n@btime runn_d($morse1, $x, 1_000)\nprintln(\"Grad of hand-coded Potential\")\n@btime runn_d($morseold, $x, 1_000)\n", "meta": {"hexsha": "0e3991dc3a9c9cdb492c809912c394f347d7e7ac", "size": 1721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testanalyticpotential.jl", "max_stars_repo_name": "casv2/JuLIP.jl", "max_stars_repo_head_hexsha": "c206e6295f61e4dc8798f79b2f9ccdf0042001e4", "max_stars_repo_licenses": ["MIT"], "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/testanalyticpotential.jl", "max_issues_repo_name": "casv2/JuLIP.jl", "max_issues_repo_head_hexsha": "c206e6295f61e4dc8798f79b2f9ccdf0042001e4", "max_issues_repo_licenses": ["MIT"], "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/testanalyticpotential.jl", "max_forks_repo_name": "casv2/JuLIP.jl", "max_forks_repo_head_hexsha": "c206e6295f61e4dc8798f79b2f9ccdf0042001e4", "max_forks_repo_licenses": ["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.9466666667, "max_line_length": 83, "alphanum_fraction": 0.634514817, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7525949757985361}}
{"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, \u03bb::Real, args::Real...)\n    \u0394args = gradient(f, args...)\n    args .- \u03bb .* \u0394args\nend\n\nfunction minimize(f::Function, args::T...; niters=20, \u03bb=0.01) where T<:Real\n    paths = ntuple(_->Vector{T}(undef,niters), length(args))\n    for i in 1:niters\n        args = descend(f, \u03bb, 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, \u03bb=0.2, niters=34)\nxs2, ys2 = minimize(g, 1.8, -2.4, \u03bb=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, [-\u03c0/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.\u2208, Base.\u2209, Plots.Shape, Base.insert!\n\n    export BaryTree, Point, insert!, \u2208, \u2209, 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\u2081::Point\n        r\u2082::Point\n        r\u2083::Point\n    end\n\n    function BaryCentric2Cartesian(\u03bb\u2081,\u03bb\u2082,\u03bb\u2083,p::BaryCentric)\n        return Point(\n            \u03bb\u2081*p.r\u2081[1]+\u03bb\u2082*p.r\u2082[1]+\u03bb\u2083*p.r\u2083[1],\n            \u03bb\u2081*p.r\u2081[2]+\u03bb\u2082*p.r\u2082[2]+\u03bb\u2083*p.r\u2083[2],\n        )\n    end\n\n    function Cartesian2BaryCentric(p::Point,b::BaryCentric)\n        x,y = p\n        x1,x2,x3 = b.r\u2081[1],b.r\u2082[1],b.r\u2083[1]\n        y1,y2,y3 = b.r\u2081[2],b.r\u2082[2],b.r\u2083[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 \u2208(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\u2081,\n                a.b.r\u2082,\n                a.b.r\u2083\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 \u2208 b\n                return true\n            end\n        end\n        return false\n    end\n\n    \u2209(p::Point,t::AxisAlignedTriangle)::Bool = !\u2208(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\u2081,m3,m1),\n            BaryCentric(m3,m2,m1),\n            BaryCentric(m3,t.b.r\u2082,m2),\n            BaryCentric(m1,m2,t.b.r\u2083)\n        ])\n\n    end\n\n    \u2208(p::Point,q::BaryTree)::Bool = \u2208(p,q.boundary)\n    \u2209(p::Point,q::BaryTree)::Bool = \u2209(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 \u2209 q)\n            return false\n        end\n\n        if isempty(q) && q.t == nothing\n            subdivide!(q)\n            if p \u2208 q.t\n                q.t.point = p\n            end\n\n            if p \u2208 q.c\n                q.c.point = p\n            end\n            if p \u2208 q.l\n                q.l.point = p\n            end\n            if p \u2208 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\u2081[1],a.b.r\u2082[1],a.b.r\u2083[1]],[a.b.r\u2081[2],a.b.r\u2082[2],a.b.r\u2083[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 \u2208 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    \u03b1::Float64 = 33.3333         # infiltration rate in vegetated soil\n    f::Float64 = 0.1             # infiltration contrast\n    \u03b7::Float64 = 3.5             # root augmentation\n    \u03b3::Float64 = 16.6667         # soil water consumption rate\n    \u03c1::Float64 = 0.95            # shading parameter\n    \u03bd::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; \u03b4::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 \u2208 (0,1)),\nand \u03b4 the degree increment between points.\n\"\"\"\nfunction belief_ellipse(b::GaussianBelief, P::Number=0.95; \u03b4::Number=5)\n    @assert 0<P<1\n    @assert 0<\u03b4<360\n\n    \u03b8 = (pi/180)*collect(0:\u03b4:360)\n    rad_w = (-2*log(1-P))^0.5\n\n    w1 = rad_w*cos.(\u03b8)\n    w2 = rad_w*sin.(\u03b8)\n\n    Sig12 = cholesky(b.\u03a3)\n    x=Sig12.L*[w1 w2]' .+ b.\u03bc\n    return x[1,:], x[2,:]\nend\n\n\"\"\"\n    belief_ellipse(\u03bc::AbstractVector, \u03a3::AbstractMatrix, P::Float=0.95; \u03b4::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 \u2208 (0,1)),\nand \u03b4 the degree increment between points.\n\"\"\"\n\nfunction belief_ellipse(\u03bc::AbstractVector, \u03a3::AbstractMatrix, P::Number=0.95; \u03b4::Number=5)\n    @assert 0<P<1\n    @assert 0<\u03b4<360\n\n    \u03b8 = (pi/180)*collect(0:\u03b4:360)\n    rad_w = (-2*log(1-P))^0.5\n\n    w1 = rad_w*cos.(\u03b8)\n    w2 = rad_w*sin.(\u03b8)\n\n    Sig12 = cholesky(\u03a3)\n    x = Sig12.L*[w1 w2]' .+ \u03bc\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": "export add_gate, gate, gate_help\n\n\n# These are tables of the gates and their descriptions\ngate_table = Dict{Symbol, Matrix{CC}}()\ngate_descr = Dict{Symbol,String}()\n\n\"\"\"\n`add_gate(S::Symbol, M::Matrix, descr::String)` adds a new gate to the \nlibrary of gates. \n* `S` is the symbol associated with this gate.\n* `M` is the matrix for this gate.\n* `descr` is a description of the action of the gate.\n\"\"\"\nfunction add_gate(S::Symbol, M::Matrix, descr::String=\"No description available\")\n    gate_table[S] = M\n    gate_descr[S] = descr \nend\n\n\"\"\"\n`gate(S::Symbol)` returns the gate associated with the symbol `S`.\n\"\"\"\nfunction gate(S::Symbol)\n    if haskey(gate_table,S)\n        return gate_table[S]\n    end \n    throw(error(\"No such gate, $S\"))\nend \n\n\"\"\"\n`gate_help(S::Symbol)` prints a short help message describing gate `S`.\n\"\"\"\nfunction gate_help(S::Symbol)\n    if haskey(gate_descr,S)\n        println(\":$S\\t\",gate_descr[S])\n        return\n    end\n    println(\"Unknown gate, $S\")\nend\n\nadd_gate(:I, [1 0; 0 1], \"Identity (nop) gate\")\nadd_gate(:X, [0 1; 1 0], \"Qubit swap (Pauli X)\")\nadd_gate(:H, [1 1; 1 -1]/sqrt(2), \"Hadammard gate\")\n", "meta": {"hexsha": "da0e9a3094d8a30570c68421451d03ec348df729", "size": 1132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gate.jl", "max_stars_repo_name": "scheinerman/SimpleQuantum.jl", "max_stars_repo_head_hexsha": "0d105582f942b54ec5e2a6dab3449e05a5a28b14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-05T01:56:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-05T01:56:54.000Z", "max_issues_repo_path": "src/gate.jl", "max_issues_repo_name": "scheinerman/SimpleQuantum.jl", "max_issues_repo_head_hexsha": "0d105582f942b54ec5e2a6dab3449e05a5a28b14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gate.jl", "max_forks_repo_name": "scheinerman/SimpleQuantum.jl", "max_forks_repo_head_hexsha": "0d105582f942b54ec5e2a6dab3449e05a5a28b14", "max_forks_repo_licenses": ["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": 81, "alphanum_fraction": 0.6581272085, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7525811054186597}}
{"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    \u03b2 = p.\u03b2\n    c = p.c\n    \u03b3 = p.\u03b3\n    \u03b4t = p.\u03b4t\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(\u03b2*c*I0/N,\u03b4t))\n    I_R ~ Binomial(I0, rate_to_proportion(\u03b3,\u03b4t))\n\n    # Updated state\n    t = t0 + \u03b4t\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\u03b4t = 0.1\nnsteps = 400\ntmax = nsteps*\u03b4t;\n\n\nu0 = (t=0.0, S=990, I=10, R=0); # t,S,I,R\n\n\np = (\u03b2=0.05, c=10.0, \u03b3=0.25, \u03b4t=\u03b4t);\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": "using BSplineFit, Plots\n\nknots = [0.0,1.0,2.0,4.0,7.0]\ndata_x = sort(rand(100)*7)\ndata_y = rand(100)*0.1 .+ 0.5 .+ sin.(data_x)./2\n\nplts = []\nfor order \u2208 1:3\n    p = scatter(data_x, data_y, label=\"\", title=\"Fit with BSpline of order $(order).\")\n    for id \u2208 1:length(knots)+order\n        b = BSplineFit.BSpline1DBasis(order, knots, id)\n        plot!(t->b(t), 0, 7, lw=2, ls=:dash, label=\"\")\n    end\n    \n    bf = fit(data_x, data_y, order, knots)\n    plot!(t->bf(t), 0, 7, lc=:black, lw=2, label=\"\", ylims=(-0.5,1.5))\n        \n    push!(plts, p)\nend\n\np = plot(plts..., layout=grid(3,1), size=(800,800))\n\nsavefig(p, \"examples/fit.svg\")\n", "meta": {"hexsha": "f0d0fa4a643a4fa7a09f9ebb59f9767b6a0279bb", "size": 635, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fit.jl", "max_stars_repo_name": "jleugeri/BSplineFit.jl", "max_stars_repo_head_hexsha": "25538c329f11a110e7f7b5ba46638657775f9aba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-06T12:07:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-06T12:07:58.000Z", "max_issues_repo_path": "examples/fit.jl", "max_issues_repo_name": "jleugeri/BSplineFit.jl", "max_issues_repo_head_hexsha": "25538c329f11a110e7f7b5ba46638657775f9aba", "max_issues_repo_licenses": ["MIT"], "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/fit.jl", "max_forks_repo_name": "jleugeri/BSplineFit.jl", "max_forks_repo_head_hexsha": "25538c329f11a110e7f7b5ba46638657775f9aba", "max_forks_repo_licenses": ["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.4583333333, "max_line_length": 86, "alphanum_fraction": 0.568503937, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7525344384385434}}
{"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 \u2208 [-5, 5], for all i = 1, \u2026, 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": "using MLDatasets, JLD\n\nfunction sigmoid(x)\n    return 1 / (1 + exp(-x))\nend\n\nfunction softmax(a)\n    c = maximum(a)\n    exp_a = exp.(a .- c)  # \u30aa\u30fc\u30d0\u30fc\u30d5\u30ed\u30fc\u5bfe\u7b56\n    sum_exp_a = sum(exp_a)\n    y = exp_a ./ sum_exp_a\n\n    return y\nend\n\nfunction get_data()\n    # x_train, t_train = MNIST.traindata()\n    x_test, t_test = MNIST.testdata()\n    x_test = reshape(x_test, (784, :))\n    return x_test, t_test\nend\n\nfunction init_network()\n    network = load(\"sample_weight.jld\")\n    return network\nend\n\nfunction predict(network, x)\n    W1, W2, W3 = network[\"W1\"], network[\"W2\"], network[\"W3\"]\n    b1, b2, b3 = network[\"b1\"], network[\"b2\"], network[\"b3\"]\n\n    a1 = W1 * x .+ b1\n    z1 = sigmoid.(a1)\n    a2 = W2 * z1 .+ b2\n    z2 = sigmoid.(a2)\n    a3 = W3 * z2 .+ b3\n    y = softmax(a3)\n\n    return y\nend\n\nfunction main()\n    x, t = get_data()\n    network = init_network()\n\n    accuracy_cnt = 0\n    for i in 1:length(t)\n        y = predict(network, x[:,i])\n        p = argmax(y) - 1\n        if p == t[i]\n            accuracy_cnt += 1\n        end\n    end\n    accuracy = accuracy_cnt / length(t)\n    println(\"Accuracy: $accuracy\")  # 0.9352\nend\n\nmain()\n", "meta": {"hexsha": "8495d8a4ed55f9441377a74c153c09e61bdd452d", "size": 1134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/ch03/neuralnet_mnist.jl", "max_stars_repo_name": "Loliver1224/DLFS", "max_stars_repo_head_hexsha": "730030c60b582091cc9d623c7a9cba46e81bf697", "max_stars_repo_licenses": ["MIT"], "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/ch03/neuralnet_mnist.jl", "max_issues_repo_name": "Loliver1224/DLFS", "max_issues_repo_head_hexsha": "730030c60b582091cc9d623c7a9cba46e81bf697", "max_issues_repo_licenses": ["MIT"], "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/ch03/neuralnet_mnist.jl", "max_forks_repo_name": "Loliver1224/DLFS", "max_forks_repo_head_hexsha": "730030c60b582091cc9d623c7a9cba46e81bf697", "max_forks_repo_licenses": ["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.2203389831, "max_line_length": 60, "alphanum_fraction": 0.5679012346, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7525344372230137}}
{"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": "# Test cornerfeatures.jl\n\nprintln(\"testing cornerfeatures\")\n\nusing ImageProjectiveGeometry\nusing Base.Test\n\ntol = 1;\n\n# structuretensor, harris, noble, shi_tomasi, coherence\n# hessianfeatures\n# fastradial\n# nonmaxsuppts\n\n# Create an image with an isolated point\nimg = zeros(100,100)\nr0 = 20;\nc0 = 40;\nimg[r0,c0] = 10\n\n(cimg, r, c) = harris(img, N=1,radius=5,subpixel=false)\n@test abs(r[1]-r0) < tol && abs(c[1]-c0) < tol\n\n(cimg, r, c) = noble(img, N=1,radius=5,subpixel=false)\n@test abs(r[1]-r0) < tol && abs(c[1]-c0) < tol\n\n(cimg, r, c) = shi_tomasi(img, N=1,radius=5,subpixel=false)\n@test abs(r[1]-r0) < tol && abs(c[1]-c0) < tol\n\nhdet = hessianfeatures(img, 1)\n(r,c) = nonmaxsuppts(hdet, radius=5, N=1)\n@test abs(r[1]-r0) < tol && abs(c[1]-c0) < tol\n\n(S,So) = fastradial(img, [1, 3, 5])\n(r,c) = nonmaxsuppts(S, radius=5, thresh=maximum(S)/2);\n@test abs(r[1]-r0) < tol && abs(c[1]-c0) < tol\n\n# Check nonmaxsuppts does subpixel precision. Create a 2x2 block of\n# pixels in the image and locate the centre of that\nimg[r0:r0+1, c0:c0+1] = 10\n(cimg, r, c) = shi_tomasi(img, N=1,radius=5,subpixel=true)\ntol = 0.1\n@test abs(r[1]-(r0+0.5)) < tol && abs(c[1]-(c0+0.5)) < tol\n", "meta": {"hexsha": "a5229901fe257a725fafa6616cb126cea1b9ca93", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_cornerfeatures.jl", "max_stars_repo_name": "JuliaPackageMirrors/ImageProjectiveGeometry.jl", "max_stars_repo_head_hexsha": "5d31c1bc3d45178121b846f85d0b28fe0c517174", "max_stars_repo_licenses": ["MIT"], "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_cornerfeatures.jl", "max_issues_repo_name": "JuliaPackageMirrors/ImageProjectiveGeometry.jl", "max_issues_repo_head_hexsha": "5d31c1bc3d45178121b846f85d0b28fe0c517174", "max_issues_repo_licenses": ["MIT"], "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_cornerfeatures.jl", "max_forks_repo_name": "JuliaPackageMirrors/ImageProjectiveGeometry.jl", "max_forks_repo_head_hexsha": "5d31c1bc3d45178121b846f85d0b28fe0c517174", "max_forks_repo_licenses": ["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.5681818182, "max_line_length": 67, "alphanum_fraction": 0.6509837468, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7524915253521576}}
{"text": "doc\"\"\"\n    Exponential(\u03b8)\n\nThe *Exponential distribution* with scale parameter `\u03b8` 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    \u03b8::T\t\t# note: scale not rate\n\n    Exponential(\u03b8::Real) = (@check_args(Exponential, \u03b8 > zero(\u03b8)); new(\u03b8))\nend\n\nExponential{T<:Real}(\u03b8::T) = Exponential{T}(\u03b8)\nExponential(\u03b8::Integer) = Exponential(Float64(\u03b8))\nExponential() = Exponential(1.0)\n\n@distr_support Exponential 0.0 Inf\n\n### Conversions\nconvert{T <: Real, S <: Real}(::Type{Exponential{T}}, \u03b8::S) = Exponential(T(\u03b8))\nconvert{T <: Real, S <: Real}(::Type{Exponential{T}}, d::Exponential{S}) = Exponential(T(d.\u03b8))\n\n\n#### Parameters\n\nscale(d::Exponential) = d.\u03b8\nrate(d::Exponential) = 1 / d.\u03b8\n\nparams(d::Exponential) = (d.\u03b8,)\n@inline partype{T<:Real}(d::Exponential{T}) = T\n\n\n#### Statistics\n\nmean(d::Exponential) = d.\u03b8\nmedian(d::Exponential) = logtwo * d.\u03b8\nmode{T<:Real}(d::Exponential{T}) = zero(T)\n\nvar(d::Exponential) = d.\u03b8^2\nskewness{T<:Real}(d::Exponential{T}) = T(2)\nkurtosis{T<:Real}(d::Exponential{T}) = T(6)\n\nentropy(d::Exponential) = 1 + log(d.\u03b8)\n\n\n#### Evaluation\n\nzval(d::Exponential, x::Real) = x / d.\u03b8\nxval(d::Exponential, z::Real) = z * d.\u03b8\n\npdf(d::Exponential, x::Real) = (\u03bb = rate(d); x < 0 ? zero(\u03bb) : \u03bb * exp(-\u03bb * x))\nfunction logpdf{T<:Real}(d::Exponential{T}, x::Real)\n    (\u03bb = rate(d); x < 0 ? -T(Inf) : log(\u03bb) - \u03bb * 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": "# This test case is copied from http://hakank.org/julia/constraints/monks_and_doors.jl\n# which is a website by H\u00e5kan Kjellerstrand\n# please check it out :)\n\n@testset \"Monks & Doors\" begin\n    all_solutions = true\n    model = Model(optimizer_with_attributes(CS.Optimizer,   \n        \"all_solutions\"=> all_solutions,\n        # \"all_optimal_solutions\"=>all_solutions, \n        \"logging\"=>[],\n\n        \"traverse_strategy\"=>:BFS,\n        \"branch_split\"=>:InHalf,\n\n        \"branch_strategy\" => :IMPS, # default\n    ))\n\n    num_doors = 4\n    num_monks = 8\n    @variable(model, doors[1:num_doors], Bin)\n    da,db,dc,dd = doors \n    door_names = [\"A\",\"B\",\"C\",\"D\"]\n\n    @variable(model, monks[1:num_monks], Bin)\n    m1,m2,m3,m4,m5,m6,m7,m8 = monks\n\n    # Monk 1: Door A is the exit.\n    # M1 #= A (Picat constraint)\n    @constraint(model, m1 == da)\n\n    #  Monk 2: At least one of the doors B and C is the exit.\n    # M2 #= 1 #<=> (B #\\/ C)\n    @constraint(model, m2 := { db == 1 || dc == 1})\n\n    #  Monk 3: Monk 1 and Monk 2 are telling the truth.\n    # M3 #= 1 #<=> (M1 #/\\ M2)\n    @constraint(model, m3 := { m1 == 1 && m2 == 1})\n\n    #  Monk 4: Doors A and B are both exits.\n    # M4 #= 1 #<=> (A #/\\ B)\n    @constraint(model, m4 := { da == 1 && db == 1})\n\n    #  Monk 5: Doors A and C are both exits.\n    # M5 #= 1 #<=> (A #/\\ C)\n    @constraint(model, m5 := { da == 1 && dc == 1})\n\n    #  Monk 6: Either Monk 4 or Monk 5 is telling the truth.\n    # M6 #= 1 #<=> (M4 #\\/ M5)\n    @constraint(model, m6 := { m4 == 1|| m5 == 1})\n\n    #  Monk 7: If Monk 3 is telling the truth, so is Monk 6.\n    # M7 #= 1 #<=> (M3 #=> M6)\n    @constraint(model, m7 := { m3 => {m6 == 1}})\n\n    #  Monk 8: If Monk 7 and Monk 8 are telling the truth, so is Monk 1.\n    # M8 #= 1 #<=> ((M7 #/\\ M8) #=> (M1))\n    b1 = @variable(model, binary=true)\n    @constraint(model, b1 := {m7 == 1 && m8 == 1})\n    @constraint(model, m8 := {b1 => {m1 == 1}})\n\n    # Exactly one door is an exit.\n    # (A + B + C + D) #= 1\n    @constraint(model, da + db + dc + dd == 1)\n\n    # Solve the problem\n    optimize!(model)\n\n    status = JuMP.termination_status(model)\n    # println(\"status:$status\")\n    num_sols = 0\n    @test status == MOI.OPTIMAL\n    num_sols = MOI.get(model, MOI.ResultCount())\n    @test num_sols == 1\n    doors_val = convert.(Integer,JuMP.value.(doors))\n    monks_val = convert.(Integer,JuMP.value.(monks))\n    # exit door is A\n    @test doors_val[1] == 1\n    @test sum(doors_val) == 1\n    @test sum(monks_val) == 3\n    # monks 1,7,8 are the only ones who tell the truth\n    @test monks_val[1] == monks_val[7] == monks_val[8] == 1\nend", "meta": {"hexsha": "08afe27af51266243e81d52a3b1c2244bd47d261", "size": 2605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/monks_and_doors.jl", "max_stars_repo_name": "Wikunia/ConstraintSolver.jl", "max_stars_repo_head_hexsha": "2d857b27e6006e587afbd5f337974c82646f0301", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 120, "max_stars_repo_stars_event_min_datetime": "2019-09-05T23:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:04:40.000Z", "max_issues_repo_path": "test/monks_and_doors.jl", "max_issues_repo_name": "Wikunia/ConstraintSolver.jl", "max_issues_repo_head_hexsha": "2d857b27e6006e587afbd5f337974c82646f0301", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 273, "max_issues_repo_issues_event_min_datetime": "2019-09-05T11:20:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:57:00.000Z", "max_forks_repo_path": "test/monks_and_doors.jl", "max_forks_repo_name": "Wikunia/ConstraintSolver.jl", "max_forks_repo_head_hexsha": "2d857b27e6006e587afbd5f337974c82646f0301", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-09-13T08:36:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T18:08:03.000Z", "avg_line_length": 31.7682926829, "max_line_length": 86, "alphanum_fraction": 0.554318618, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7524915205168136}}
{"text": "using StatsBase\nusing Test\n\nX = Float64[1 0; 2 1; 3 0; 4 1; 5 10]\n\nx1 = X[:,1]\nx2 = X[:,2]\ny = [5, 3, 4, 2, 5]\n\n# corspearman\n\n@test corspearman(x1, y) \u2248 -0.102597835208515\n@test corspearman(x2, y) \u2248 -0.081110710565381\n\n@test corspearman(X, y) \u2248 [-0.102597835208515, -0.081110710565381]\n@test corspearman(y, X) \u2248 [-0.102597835208515 -0.081110710565381]\n\nc11 = corspearman(x1, x1)\nc12 = corspearman(x1, x2)\nc22 = corspearman(x2, x2)\n@test c11 \u2248 1.0\n@test c22 \u2248 1.0\n@test corspearman(X, X) \u2248 [c11 c12; c12 c22]\n@test corspearman(X)    \u2248 [c11 c12; c12 c22]\n\n\n# corkendall\n\n@test corkendall(x1, y) \u2248 -0.105409255338946\n@test corkendall(x2, y) \u2248 -0.117851130197758\n\n@test corkendall(X, y) \u2248 [-0.105409255338946, -0.117851130197758]\n@test corkendall(y, X) \u2248 [-0.105409255338946 -0.117851130197758]\n\nc11 = corkendall(x1, x1)\nc12 = corkendall(x1, x2)\nc22 = corkendall(x2, x2)\n\n@test c11 \u2248 1.0\n@test c22 \u2248 1.0\n@test corkendall(X, X) \u2248 [c11 c12; c12 c22]\n@test corkendall(X)    \u2248 [c11 c12; c12 c22]\n", "meta": {"hexsha": "e5505c2a0e1dde2f968b2d542bba1721d21809c1", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rankcorr.jl", "max_stars_repo_name": "logankilpatrick/StatsBase.jl", "max_stars_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "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": "test/rankcorr.jl", "max_issues_repo_name": "logankilpatrick/StatsBase.jl", "max_issues_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-11-09T21:20:29.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-12T11:48:53.000Z", "max_forks_repo_path": "test/rankcorr.jl", "max_forks_repo_name": "logankilpatrick/StatsBase.jl", "max_forks_repo_head_hexsha": "c5328b186f721f9e320928356fb69cf579035240", "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.0, "max_line_length": 66, "alphanum_fraction": 0.6653185035, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7524915149966175}}
{"text": "\"\"\"\nGraph Laplacian of a `m\u00d7n` 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 Distributions\nusing GaussianMixtureTest\nusing Test\n\nmu_true = [-2.0858,-1.4879]\nwi_true = [0.0828,0.9172]\nsigmas_true = [0.6735,0.2931]\n\nm = MixtureModel(map((u, v) -> Normal(u, v), mu_true, sigmas_true), wi_true)\nx = rand(m, 1000);\n\nwi, mu, sigmas, ml = gmm(x, 2)\nmhat = MixtureModel(map((u, v) -> Normal(u, v), mu, sigmas), wi)\n@test loglikelihood(mhat, x) >= loglikelihood(m, x)\n\nasymptoticdistribution(x, wi_true, mu_true, sigmas_true);\nT, p = kstest(x, 2)\n\n@test T >= 0\n# write your own tests here\n", "meta": {"hexsha": "ca081f05d523d87834deb48180e7d049807ad49a", "size": 509, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GaussianMixtureTest.jl-435c3d8c-e5f4-5f7f-83ee-d96dcc9b5a11", "max_stars_repo_head_hexsha": "e5d864720dbee09e7a6552267498496225816a05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-02-10T02:34:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-28T20:18:46.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GaussianMixtureTest.jl-435c3d8c-e5f4-5f7f-83ee-d96dcc9b5a11", "max_issues_repo_head_hexsha": "e5d864720dbee09e7a6552267498496225816a05", "max_issues_repo_licenses": ["MIT"], "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": "UnofficialJuliaMirrorSnapshots/GaussianMixtureTest.jl-435c3d8c-e5f4-5f7f-83ee-d96dcc9b5a11", "max_forks_repo_head_hexsha": "e5d864720dbee09e7a6552267498496225816a05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:13:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T00:20:44.000Z", "avg_line_length": 24.2380952381, "max_line_length": 76, "alphanum_fraction": 0.6777996071, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.752491512921372}}
{"text": "fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)\n", "meta": {"hexsha": "e78d961c1555ce77b7e8c10e8a29c4283fe631e3", "size": 41, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/fibonacci-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/fibonacci-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/fibonacci-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": 20.5, "max_line_length": 40, "alphanum_fraction": 0.4146341463, "num_tokens": 22, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7524915042917553}}
{"text": "using DifferentialEquations\nusing Plots\nplotlyjs()\n\n#constants\nm = 1.0                             # mass[Kg]\ng = 9.81                            # gravitational acceleration [m/s\u00b2]\n\n#function to compute the ODEs\nfunction pendulum!(du,u,p,t)\n    r,v,\u03b8,\u03c9=u\n    du[1]=dr=v                   \n    du[2]=dv=r*\u03c9^2+g*cos(\u03b8)\n    du[3]=d\u03b8=\u03c9                    \n    du[4] =d\u03c9=-(g\\r)*sin(\u03b8) - (2*v*\u03c9)/r  \nend\n\n#initial conditions\nr\u2080=4                            #initial radial distance\nv\u2080=-0.1                          #initial radial velocity \n\u03b8\u2080 = 1\u03c0/18                        # initial angular deflection [rad]\n\u03c9\u2080 = 1                       # initial angular velocity [rad/s]\nu\u2080 = [r\u2080,v\u2080,\u03b8\u2080, \u03c9\u2080]                   # initial state vector\ntspan = (0.0,5.0)             # time interval\n\n#defining the problem and solving\nprob = ODEProblem(pendulum!,u\u2080,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=\"\u03b8\",\n    color=\"green\", xaxis=\"t (s)\", yaxis=\"\u03b8 (rad)\")\np4=plot(sol,vars=(0,4),label=\"\u03c9\",\n    color=\"orange\", xaxis=\"t (s)\", yaxis=\"\u03c9 (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,\u03b8,\u03c9)=[U[x,:] for x in 1:size(U,1)]\nx=r.*sin.(\u03b8)\ny=zeros(size(t))\nz=r.*cos.(\u03b8)\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, \u03c4, char=[], siegel=true, \u03f5=1.0e-12)\n\nCompute the hessian matrix of the theta function at inputs z and \u03c4, 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}, \u03c4::Array{<:Number}, char::Array{}=[]; siegel::Bool=true, \u03f5::Real=1.0e-12)\n    R = RiemannMatrix(\u03c4, siegel=siegel, \u03f5=\u03f5, 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(\u03c4, 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(\u03c4::Array{<:Number}, tol::Real=1.0e-8)\n    R = RiemannMatrix(\u03c4, \u03f5=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\u00f72;    n2 = n1 + N%2      # Indices used for flipping trick.\n\n    k  = collect(0:N-1)             # Compute theta vector.\n    th = k * \u03c0/(N-1)\n\n    temp = collect(N-1:-2:1-N)\n    x  = sin.(\u03c0*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\u00f72;  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(\u03b1::Real, \u03b2::Real, \u03b3::Real)\n\nReturns the rotation matrix A based on rotation along the euler angles \u03b1, \u03b2 and \u03b3 corresponding to rotations around the x, y, and z-axis respectively.\n\"\"\"\nfunction euler_matrix(\u03b1::Real, \u03b2::Real, \u03b3::Real)\n    [\n        (cos(\u03b2)*cos(\u03b3))                         (-cos(\u03b2)*sin(\u03b3))                        sin(\u03b2)\n        (cos(\u03b1)*sin(\u03b3) + cos(\u03b3)*sin(\u03b1)*sin(\u03b2))  (cos(\u03b1)*cos(\u03b3) - sin(\u03b1)*sin(\u03b2)*sin(\u03b3))  (-cos(\u03b2)*sin(\u03b1))\n        (sin(\u03b1)*sin(\u03b3) - cos(\u03b1)*cos(\u03b3)*sin(\u03b2))  (cos(\u03b3)*sin(\u03b2) + cos(\u03b1)*sin(\u03b2)*sin(\u03b3))  (cos(\u03b1)*cos(\u03b2))\n\n    ]\nend\n\n\n\"\"\"\n    rotate_3D_quantity(x, \u03b1, \u03b2, \u03b3)\n\nRotates a 3D vector along the x-axis with angle \u03b1, y-axis with angle \u03b2 and z-axis with angle \u03b3.\n\"\"\"\nfunction rotate_3D_quantity(x::Array{<:Real}, \u03b1::Real, \u03b2::Real, \u03b3::Real)\n\n    A = euler_matrix(\u03b1, \u03b2, \u03b3)\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 \u03b1, \u03b2 and \u03b3 corresponding to rotations around the x, y, and z-axis respectively.\n\u03b1, \u03b2 and \u03b3 need to be given in degrees.\n\"\"\"\nfunction rotate_3D(x::Array{<:Real}, alpha::Real, beta::Real, gamma::Real)\n\n    \u03b1 = deg2rad(alpha)\n    \u03b2 = deg2rad(beta)\n    \u03b3 = 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], \u03b1, \u03b2, \u03b3)\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 \u03b1, \u03b2 and \u03b3 corresponding to rotations around the x, y, and z-axis respectively.\n\u03b1, \u03b2 and \u03b3 need to be given in degrees.\n\"\"\"\nfunction rotate_3D!(x::Array{<:Real}, alpha::Real, beta::Real, gamma::Real)\n\n    \u03b1 = deg2rad(alpha)\n    \u03b2 = deg2rad(beta)\n    \u03b3 = deg2rad(gamma)\n\n    @threads for i = 1:size(x,2)\n        @inbounds x[:,i] = rotate_3D_quantity(x[:,i], \u03b1, \u03b2, \u03b3)\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 \u2208 {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 \u2208 {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 \u2208 {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 \u03b8\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,\u03b8)) ~ Dxx(u(x,y,t,\u03b8)) + Dyy(u(x,y,t,\u03b8))\n# Initial and boundary conditions\nbcs = [u(x,y,0,\u03b8) ~ exp(x+y)*cos(x+y) ,\n      # u(x,y,2,\u03b8) ~ exp(x+y)*cos(x+y+4*2) ,\n      u(0,y,t,\u03b8) ~ exp(y)*cos(y+4t),\n      u(2,y,t,\u03b8) ~ exp(2+y)*cos(2+y+4t) ,\n      u(x,0,t,\u03b8) ~ exp(x)*cos(x+4t),\n      u(x,2,t,\u03b8) ~ exp(x+2)*cos(x+2+4t)]\n# Space and time domains\ndomains = [x \u2208 IntervalDomain(0.0,2.0),\n          y \u2208 IntervalDomain(0.0,2.0),\n          t \u2208 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.\u03c3),FastDense(16,16,Flux.\u03c3),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 \u2248 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 \u03b8\n@variables p(..)\n@derivatives Dx'~x\n@derivatives Dxx''~x\n\n#2D PDE\n\u03b1 = 0.3\n\u03b2 = 0.5\n_\u03c3 = 0.5\n# Discretization\ndx = 0.05\n# here we use normalization condition: dx*p(x,\u03b8) ~ 1, in order to get non-zero solution.\neq  = [(\u03b1 - 3*\u03b2*x^2)*p(x,\u03b8) + (\u03b1*x - \u03b2*x^3)*Dx(p(x,\u03b8)) ~ (_\u03c3^2/2)*Dxx(p(x,\u03b8)),\n       dx*p(x,\u03b8) ~ 1.]\n\n# Initial and boundary conditions\nbcs = [p(-2.2,\u03b8) ~ 0. ,p(2.2,\u03b8) ~ 0. , p(-2.2,\u03b8) ~ p(2.2,\u03b8)]\n\n# Space and time domains\ndomains = [x \u2208 IntervalDomain(-2.2,2.2)]\n\n# Neural network\nchain = FastChain(FastDense(1,12,Flux.\u03c3),FastDense(12,12,Flux.\u03c3),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*_\u03c3^2))*(2*\u03b1*x^2 - \u03b2*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 \u2248 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": "using GalerkinSparseGrids\nusing Base.Test\nusing Cubature\n\n#---------------------------------------\n# Testing regular hier DG reconstruction\n#---------------------------------------\n\nprint(\"Testing full discontinuous Galerkin (DG) reconstruction 1-D... \")\n\nfor k in 1:5\n    for l in 1:6\n        dict = coeffs_DG(1, k, l, x->sin(4*x[1]); scheme=\"full\")\n        err = x->(reconstruct_DG(dict, [x])-sin(4*x))^2\n        @test hquadrature(err, 0, 1; abstol=1.0e-10)[1] < 1/(1<<(l+k-1))\n    end\nend\n\nfor k in 1:5\n    for l in 1:6\n        dict = coeffs_DG(1, k, l, x->sin(4*x[1]); scheme=\"sparse\")\n        err = x->(reconstruct_DG(dict, [x])-sin(4*x))^2\n        @test hquadrature(err, 0, 1; abstol=1.0e-10)[1] < 1/(1<<(l+k-1))\n    end\nend\n\nprintln(\"Test Passed.\")\n\n# Sparsification should be trivial in 1D\n\nprint(\"Testing that both reconstructions are equivalent... \")\n\nfor k in 1:5\n    for l in 1:6\n        full_coeffs = coeffs_DG(1, k, l, x->sin(4*x[1]); scheme=\"full\")\n        sparse_coeffs = coeffs_DG(1, k, l, x->sin(4*x[1]); scheme=\"full\")\n        diff_full = x->(reconstruct_DG(full_coeffs, [x])-sin(4*x))^2\n        diff_sparse = x->(reconstruct_DG(sparse_coeffs, [x])-sin(4*x))^2\n        diff_both = x->(reconstruct_DG(full_coeffs, [x])-reconstruct_DG(sparse_coeffs, [x]))^2\n\n        @test abs(hquadrature(diff_full,0,1;abstol=1.0e-9)[1]-\n                  hquadrature(diff_sparse,0,1;abstol=1.0e-9)[1]) < 1.0e-14\n        @test hquadrature(diff_both,0,1;abstol=1.0e-9)[1] < 1.0e-14\n    end\nend\n\nprintln(\"Test Passed.\")\n\n# Testing sparse DG reconstruction in multidimensional space:\n\nprint(\"Testing sparse DG basis reconstruction 2-D... \")\n\nfor k in 1:5\n    for l in 1:6\n        dict = coeffs_DG(2, k, l, x->sin(4*x[1]+x[2]))\n        err = x->(reconstruct_DG(dict, [x[1],x[2]])-sin(4*x[1]+x[2]))^2\n        @test hcubature(err, [0,0], [1,1]; abstol=1.0e-10, maxevals=500)[1] < 1/(1<<(l+k-2))\n    end\nend\n\nprintln(\"Test Passed.\")\n", "meta": {"hexsha": "5e832bb181472f83a2b9901d9d64e14a70267c5d", "size": 1927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/hier_DG.jl", "max_stars_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_stars_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_stars_repo_licenses": ["MIT"], "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/hier_DG.jl", "max_issues_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_issues_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_issues_repo_licenses": ["MIT"], "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/hier_DG.jl", "max_forks_repo_name": "miguelraz/GalerkinSparseGrids.jl", "max_forks_repo_head_hexsha": "1d89ce5a19d8a13e25d155123ea7ebf0bfcd72a9", "max_forks_repo_licenses": ["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.0806451613, "max_line_length": 94, "alphanum_fraction": 0.5796574987, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7524557450991065}}
{"text": "\nfunction L2norm(x)\n    local l2::eltype(x) = 0\n    for x\u1d62 in x\n        l2 += x\u1d62^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\u03b1tan(T) = 0.5 - 0.2*tanh((T-263)/4)\ndTdt(T, \u03b5 = 0.65, \u03b1=\u03b1tan, s= 1.0) = s*(1 - \u03b1(T)) - 1.6e-10 * \u03b5 * T^4\ndTdt(T; \u03b5 = 0.65, \u03b1=\u03b1tan, s = 1.0) = dTdt(T, \u03b5, \u03b1, 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": "# Jonas August, 2/2022\n\n#=\nThis problem was asked by Microsoft.\n\nA number is considered perfect if its digits sum up to exactly 10.\n\nGiven a positive integer n, return the n-th perfect number.\n\nFor example, given 1, you should return 19. Given 2, you should return 28.\n=#\n\n\" Returns n-th perfect number. \"\nfunction perfect10(n::Int)::Int\n    @assert n > 0\n    i = 0   # number being checked\n    m = 0   # current count of perfect numbers \u2264 i CHECK\n    while m < n \n        i += 1\n        # Convert number to digits by converting to string and then converting each digit to Int individually.\n        s = 0  # sum of the converted digits\n        for digit in string(i)\n            s += parse(Int, digit)\n        end\n        if s == 10\n            m += 1\n        end\n    end\n    i\nend\n\n\nusing Test\n@test perfect10(1) == 19\n@test perfect10(2) == 28\n\nfor n in 1:100\n    @show n, perfect10(n)\nend\n", "meta": {"hexsha": "46c48eba3db4e90cb30c4e3a5398f3e99e6fc9d5", "size": 891, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Perfect number - Problem 70.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": "Perfect number - Problem 70.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": "Perfect number - Problem 70.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": 22.275, "max_line_length": 110, "alphanum_fraction": 0.6184062851, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.8791467722591729, "lm_q1q2_score": 0.7524187733905773}}
{"text": "# ---\n# layout: post\n# title: \"\u03c0 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 \u03c0 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 \u03c0 day on 14/3 along with everyone else!\n\n# >I set myself a challenge at the beginning of March: make a \u03c0-related image using Julia and the Luxor.jl package every day until \u03c0 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 \u03c0 shape appear, the code creates a path:\n\n#md fontsize(480)\n#md textoutlines(\"\u03c0\", O, :path, halign=:center, valign=:middle)\n#md \u03c0outline = first(pathtopoly())\n\n# then checks whether each circle's centerpoint is inside or outside the outline of the \u03c0 shape:\n\n#md isinside(pt, \u03c0outline)\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\u00e9zier splodges that are supposed to be splashes...\n\n# ![image label](IMAGEFOLDER/pi-reds-balls-wet-800.png)\n\n# ### Day 3: \u03c0 packing\n\n# This is \u03c0 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 \u03c0 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 \u03c0.\n\n# ![image label](IMAGEFOLDER/digits-of-pi-avenir-800.png)\n\n# To generate the digits of \u03c0, 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 \u00f7 b, a1 \u00f7 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 \u00f7 b, a1 \u00f7 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 \u03c0, 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 \u03c0 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 \u03c0 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 \u03c0 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\u00e9zier 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 \u03c0 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 \u03c0 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 \u03c0, 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 \u03c0 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\u2014competition in this category is fierce, even if sometimes the contestants are unwilling participants.\n\n# Happy \u03c0 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# \u2554\u2550\u2561 57ed2d88-970d-4b8d-9f36-7115f50622de\nbegin\n\tusing LinearAlgebra # for the norm and dot function\n\tusing ForwardDiff # for automatic differentiation\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0efbf532-66cb-41fd-98a5-6df89e364b84\nmd\"\"\"## Gradient decent with backtracking line search\n\nWrite a function `gradient_decent(f, x0, \u03b1, \u03b2)` 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# \u2554\u2550\u2561 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 \u0394x = \u2207f(x).\n \tLine search: Choose a step size t > 0.\n    Update: x = x + t * \u0394x\n\n \tStopping criterium: \u2016 \u2207f(x) \u2016\u00b2 < \u03b5\nend\n```\n\"\"\"\n\n# \u2554\u2550\u2561 a5e2ee29-8de1-41be-8b05-8427b1a65bce\nmd\"\"\"\n```julia\nBacktracking line search:\ngiven x, f, \u0394x, \u03b1, \u03b2\n\nt = 1\nrepeat until f(x + t \u0394x) < f(x) + \u03b1 t dot( \u2207f(x), \u0394x )\n \tUdate: t = \u03b2 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# \u2554\u2550\u2561 304398ad-f680-4f8c-8a76-5768c0fbfa5e\n\n\n# \u2554\u2550\u2561 2c48c94e-7d31-450c-b3c7-0194894c38b7\nfunction linesearch(f, \u0394x, x, \u03b1, \u03b2; t_min = 1e-5)\n\tt = 1\n\tfx = f(x)\n\tm = norm(\u0394x)\n\twhile t > t_min\n\t\tif f(x .+ t*\u0394x) <= fx + \u03b1 * t * m^2\n\t\t\treturn t\n\t\tend\n\t\tt = t*\u03b2\n\t\tcond || return t\n\tend\n\n\treturn NaN\nend\n\n# \u2554\u2550\u2561 ae9e20b2-4f88-4c28-8856-ce61368445a3\nfunction gradientdecent(f, x0, \u03b1, \u03b2, \u03b5; max_steps = 1e4)\n\tx = copy(x0)\n\ti = 0\n\t\u2207f = similar(x0)\n\n\t@assert \u03b2 < 1\n\t@assert \u03b1 < 0.5\n\n\twhile i < max_steps\n\t\tForwardDiff.gradient!(\u2207f, f, x)\n\t\t\u0394x = -\u2207f\n\t\tif norm(\u2207f)^2 < \u03b5\n\t\t\treturn x\n\t\tend\n\n\t\tt = linesearch(f, \u0394x, x, \u03b1, \u03b2)\n\t\tx .+= t * \u0394x\n\n\t\ti += 1\n\tend\n\n\treturn NaN\nend\n\n# \u2554\u2550\u2561 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\u03b1 = 0.25\n\t\u03b2 = 0.5\n\t\u03b5 = 1e-8\n\tx0 = [0.0, 0.0]\n\n\tgradientdecent(f, x0, \u03b1, \u03b2, \u03b5)\nend\n\n# \u2554\u2550\u2561 7a5cfa1b-9b47-4741-8656-210a3515b6f3\n\n\n# \u2554\u2550\u2561 81361eb6-092c-4cd1-96a0-eb9e167dfd3f\n\n\n# \u2554\u2550\u2561 b04a090b-e9d7-4032-b956-1238fac26f94\nmd\"## Array interpolation\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 641f85f8-368a-45eb-9912-284eca29d83b\nx = [5.0, 7.0, 5.0]\n\n# \u2554\u2550\u2561 9f62d306-25f2-4b8f-a691-7a0fa3f4aa03\n# x[1.5]\n\n# \u2554\u2550\u2561 61eaf1c1-f033-4e36-8171-19ff6621cc82\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25003b36fb00-833f-11ec-0d4d-451fa6f0aaee\n# \u255f\u25000efbf532-66cb-41fd-98a5-6df89e364b84\n# \u255f\u250067ab9ac3-93e0-4d9a-84aa-131aaf543198\n# \u255f\u2500a5e2ee29-8de1-41be-8b05-8427b1a65bce\n# \u255f\u2500304398ad-f680-4f8c-8a76-5768c0fbfa5e\n# \u2560\u255057ed2d88-970d-4b8d-9f36-7115f50622de\n# \u2560\u25502c48c94e-7d31-450c-b3c7-0194894c38b7\n# \u2560\u2550ae9e20b2-4f88-4c28-8856-ce61368445a3\n# \u2560\u2550e331926f-6e11-434c-a7d3-02d0e9f0f269\n# \u255f\u25007a5cfa1b-9b47-4741-8656-210a3515b6f3\n# \u255f\u250081361eb6-092c-4cd1-96a0-eb9e167dfd3f\n# \u255f\u2500b04a090b-e9d7-4032-b956-1238fac26f94\n# \u255f\u25003413f532-50ec-47f5-9547-4e9474be174e\n# \u2560\u2550641f85f8-368a-45eb-9912-284eca29d83b\n# \u2560\u25509f62d306-25f2-4b8f-a691-7a0fa3f4aa03\n# \u255f\u250061eaf1c1-f033-4e36-8171-19ff6621cc82\n# \u255f\u250084c50e3b-b836-477f-81bb-121a2e5d055f\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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  \u03c9 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    \u03c9  :: 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.\u03c9[1] = parse(Int, readline(f) )\n    momkp.\u03c9[2] = parse(Int, readline(f) )\n    !verbose ? nothing : println(\"\u03c9[1]=\",momkp.\u03c9[1])\n    !verbose ? nothing : println(\"\u03c9[2]=\",momkp.\u03c9[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 \u2208 n \u00f7 3 + 1:n \u00f7 2\n        s = c * c - n * n + 2n * c\n        if s > 0\n            t = trunc(Int, \u221as)\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": "using LinearAlgebra\nusing LDLFactorizations\nusing SparseArrays\nusing BenchmarkTools\n\nn = 3\nA = zeros(3,3)\nA[1,1] = 9.0\n\nB = 9.0*Matrix(I,n,n)\n\n@benchmark cholesky($B)\n\nfunction get_svd_sqrt(A::AbstractMatrix)\n    x = svd(A)\n    return Diagonal(sqrt.(x.S))*x.V'\nend\n\nfunction get_eig_sqrt(A::AbstractMatrix)\n    x = eigen(A)\n    return Diagonal(sqrt.(x.values))*x.vectors'\nend\n\n@benchmark get_svd_sqrt($B)\n@benchmark get_eig_sqrt($B)\n@benchmark ldlt(sparse($B); shift = 0.0, check = true, perm=Int[])\n\n\n\n\ncholesky(B).U\nC = SparseMatrixCSC(B)\nD = sparse(B)\nE = sparse(A)\n\nF = ldlt(sparse(B); shift = 0.0, check = true, perm=Int[])\n\n\nArray(sparse(cholesky(C)))\n\n:\n", "meta": {"hexsha": "49f1c3b76add4957097d9f8c4127d31a11c932c2", "size": 661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "development/matrix_factorizations.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/matrix_factorizations.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/matrix_factorizations.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": 15.7380952381, "max_line_length": 66, "alphanum_fraction": 0.6792738275, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.752296404738925}}
{"text": "using Test\n\ninclude(\"../src/RSA.jl\")\n\nusing .RSA\n\n@testset \"Secondary functions\" begin\n\n    @test RSA.exp!(2, 47) == 199807\n    @test RSA.exp!(3, 51, 678) == 93\n\n    @test RSA.inverse(2, 5) == 3\n    @test RSA.inverse(17, 39) == 23\n    @test_throws ErrorException RSA.inverse(2, 4)\n\n    @test RSA.seive(1) == []\n    @test RSA.seive(13) == [2, 3, 5, 7, 11, 13]\n\n    @test RSA.phi!(10) == 4\n    @test RSA.phi!(7) == 6\n    @test RSA.phi!(33500000) == 13200000\n\n    @test RSA.get_random_int(3) <= 7\n    @test RSA.get_random_int(8) <= 255\n\n    @test RSA.jacobi!(1001, 9907) == -1\n    @test RSA.jacobi!(19, 45) == 1\n    @test RSA.jacobi!(8,21) == -1\n    @test RSA.jacobi!(3, 15) == 0\n    @test_throws ErrorException RSA.jacobi!(13, 28)\n    @test RSA.jacobi!(28, 13) == -1\nend\n\n@testset \"Primality functions\" begin\n\n    @test RSA.miller_rabin(561) == false\n    @test RSA.miller_rabin(29) == true\n    @test RSA.miller_rabin(221) == false\n\n    @test RSA.solovay_strassen(561) == false\n    @test RSA.solovay_strassen(29) == true\n    @test RSA.solovay_strassen(221) == false\n\n    @test RSA.fermat_test(5) == true\n    @test RSA.fermat_test(4) == false\n    @test RSA.fermat_test(341) == false\nend\n\n@testset \"Processing\" begin\n\n    a =\"\"\n    @test RSA.recover_string!(RSA.process_string!(a)) == a\n    a =\"123\"\n    @test RSA.recover_string!(RSA.process_string!(a)) == a\n    a = \"1234567890\"\n    @test RSA.recover_string!(RSA.process_string!(a)) == a\nend\n\n@testset \"Encryption\" begin\n    B = RSASystem()\n    a = \"ABCDEFG\"\n    @test decrypt!(B, encrypt!(a, B.public_key)) == a\n    a = \"AB\"\n    @test decrypt!(B, encrypt!(a, B.public_key)) == a\n    a = \"ABABABABABABABABABABABABABABABAB123\"\n    @test decrypt!(B, encrypt!(a, B.public_key)) == a\nend", "meta": {"hexsha": "deae18a3e96dadacdcc29de1db628eb195b7d559", "size": 1729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 25.8059701493, "max_line_length": 58, "alphanum_fraction": 0.6101792944, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7522963921381932}}
{"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\u03b4x  \u211d^3 -> \u211d^2\n\njulia> FiniteDiff((3,4),2)\n\u03b4y  \u211d^(3, 4) -> \u211d^(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} = \"\u03b4x\"\nfun_name(L::FiniteDiff{T,N,2}) where  {T,N} = \"\u03b4y\"\nfun_name(L::FiniteDiff{T,N,3}) where  {T,N} = \"\u03b4z\"\nfun_name(L::FiniteDiff{T,N,D}) where {T,N,D}  = \"\u03b4x$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                \u2207\u03d5a = shape_gradient(fe_values, q_point, a)\n                \u2207\u03d5b = shape_gradient(fe_values, q_point, b)\n                Ke_e = dotdot(\u2207\u03d5a, C, \u2207\u03d5b) * 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    \u025b = [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            \u025b[i] = symmetric(shape_gradient(fe_values, q_point, i)) \n        end\n        d\u03a9 = getdetJdV(fe_values, q_point)\n        for i in 1:n_basefuncs\n            \u025bC = \u025b[i] \u22a1 C\n            for j in 1:n_basefuncs\n                Ke[i, j] += (\u025bC \u22a1 \u025b[j]) * d\u03a9\n            end\n        end\n    end\n    return Ke\nend;\n\nE = 200e9\n\u03bd = 0.3\n\u03bb = E*\u03bd / ((1 + \u03bd) * (1 - 2\u03bd))\n\u03bc = E / (2(1 + \u03bd))\n\u03b4(i,j) = i == j ? 1.0 : 0.0\ng(i,j,k,l) = \u03bb*\u03b4(i,j)*\u03b4(k,l) + \u03bc*(\u03b4(i,k)*\u03b4(j,l) + \u03b4(i,l)*\u03b4(j,k))\n\nC = SymmetricTensor{4, 3}(g)\n\n\nM = \u03bb/\u03bd * (1 - \u03bd)\n\nCmat = [ M      \u03bb      \u03bb    0.0    0.0   0.0;\n         \u03bb      M      \u03bb    0.0    0.0   0.0;\n         \u03bb      \u03bb      M    0.0    0.0   0.0;\n        0.0    0.0    0.0    \u03bc     0.0   0.0;\n        0.0    0.0    0.0   0.0     \u03bc    0.0;\n        0.0    0.0    0.0   0.0    0.0    \u03bc]\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) \u2265 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)\u00b2),\n    #  but it should be possible to do it in linear time.\n    #  However, the A \\ Y step is also O(mn\u00b2), 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) \u00d7 $(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\u03bc, T\u03a3}\n    \"mean\"\n    \u03bc::T\u03bc\n    \"variance\"\n    \u03a3::T\u03a3\n    @doc \"\"\"\n        MvNormalParams(\u03bc, \u03a3)\n\n    Parameters for the multivariate normal model ``x \u223c MvNormal(\u03bc, \u03a3)``.\n\n    !!! usage\n\n        Construct using [`MLE(::MvNormalModel, ::MvNormalData)`](@ref).\n    \"\"\" ->                      # FIXME workaround, remove -> in v0.7\n    function MvNormalParams(\u03bc::T\u03bc, \u03a3::T\u03a3) where {T\u03bc, T\u03a3}\n        @argcheck is_conformable_square(\u03bc, \u03a3)\n        new{T\u03bc, T\u03a3}(\u03bc, \u03a3)\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 \u03bc, \u03a3 = params\n    K = length(m)\n    @argcheck length(\u03bc) == K\n    C = cholfact(\u03a3)\n    d = m-\u03bc\n    -W/2*(K*log(2*\u03c0) + logdet(C) + dot(vec(S) + vec(d * d'), vec(inv(\u03a3))))\nend\n\nvec_parameters(\u03d5::MvNormalParams) = vec_parameters((\u03d5.\u03bc, \u03d5.\u03a3))\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 \u22c5 v) / (v \u22c5 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    \u03d5 = sample_basis(rng, kernel, input_dims, feature_dims)\n    p_w = MvNormal(Diagonal(Fill(1., feature_dims)))\n    return \u03d5, 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\u03c9, T\u03c4, Tsample}\n    inner_weights::Tinner  # lengthscale\n    outer_weights::Touter  # variance (scaled)\n    \u03c9::T\u03c9  # Sampled frequencies;               size(\u03c9): (input_dims, num_features)\n    \u03c4::T\u03c4  # Sampled phases;                    size(\u03c4): (num_features,)\n    sample_params::Tsample  # Returns a new sample of \u03c9 & \u03c4\nend\n\nfunction (\u03d5::RFFBasis)(x)\n    # \u03d5: R^{input_dims} -> R^{num_features}\n    x_ = x ./ \u03d5.inner_weights\n    \u03c9t_x = \u03d5.\u03c9'x_\n    return \u03d5.outer_weights * cos.(\u03c9t_x .+ \u03d5.\u03c4)\nend\n\nfunction resample!(\u03d5::RFFBasis)\n    \u03c9, \u03c4 = \u03d5.sample_params()\n    \u03d5.\u03c9 .= \u03c9\n    \u03d5.\u03c4 .= \u03c4\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 * \u221a(2/num_features)\n    p_\u03c9 = spectral_distribution(kernel, input_dims)\n\n    function sample_params()\n        \u03c9 = rand(rng, p_\u03c9, num_features)  #\n        \u03c4 = rand(rng, Uniform(0, 2\u03c0), num_features)  #\n        return \u03c9, \u03c4\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    \u03c3\u00b2 = only(k.\u03c3\u00b2)\n    inner, outer = spectral_weights(k.kernel)\n    return inner, outer * \u221a\u03c3\u00b2\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, \u03b1=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 ))^\u03b1\n        end\n    end\n    return A\nend\n\nfunction nemirovski2(n, \u03b1=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 ))^\u03b1\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 StrainRecon\nusing Base.Test\n\n @testset \"findw\" begin\n\nn    = 2\nR     = StrainRecon.sdiag(5*ones(2))\nM     = BitArray(eye(2))\nData  = ones(2)\n\nparamGauss = getStrainReconParam(Data,n,R=R,pwr=2.0)\n#paramLaplace = getStrainReconParam(Data,n,R=R,pwr=1.0)\n#param = paramLaplace\nfor param=[paramGauss]\n\t@testset \"findw pwr=$(param.pwr)\" begin\n\t\ta     = findw(param,M)\n\n\t\t@test norm(a-[.5;.5])<1e-10\n\n\t\tparam.d = ones(2)\n\t\ta    = findw(param,M)\n\t\t@test norm(a-[.5;.5])<1e-10\n\n\t\tparam.d = [190;0]\n\t\ta    = findw(param,M)\n\t\t@test norm(a-[1;0])<1e-10\n\n\t\tparam.d = [0;20]\n\t\ta    = findw(param,M)\n\t\t@test norm(a-[.5;.5])<1e-10\n\n\t\tM    = BitArray([1.0 0; 0 0])\n\t\tparam.d = ones(2)\n\t\ta    = findw(param,M)\n\t\t@test norm(a-[1;0])<1e-10\n\tend\nend\n\n    n    = 2\n    R     = StrainRecon.sdiag(5*ones(2))\n    M     = BitArray([1 0; 1 0])\n    Data  = ones(2)\n    paramLaplace = getStrainReconParam(Data,n,R=R,pwr=1.0)\n\nfor param=[paramLaplace]\n        @testset \"findw pwr=$(param.pwr)\" begin\n            a     = findw(param,M)\n            # println(\"a = $a\")\n            @test norm(a-[1;0])<1e-10\n\n            param.d = zeros(2)\n            a    = findw(param,M)\n            # println(\"a = $a\")\n            @test norm(a-[0.5;0.5])<1e-10\n\n            M    = BitArray([1.0 0; 0 0])\n            param.d = ones(2)\n            a    = findw(param,M)\n            # println(\"a = $a\")\n            @test norm(a-[1;0])<1e-10\n\n            m = 24\n            for n = 2:5\n                param.R = StrainRecon.sdiag(5*ones(m))\n                param.n = n\n                # srand(s)\n                M = rand([0,1], m, n)\n                atrue = randomw(n)\n                param.d = M*atrue\n                M = BitArray(M)\n                a    = findw(param,M)\n                # println(\"a = $a , atrue = $atrue\")\n                @test norm(a-atrue)<1e-10\n            end\n\n        end\n    end\nend\n", "meta": {"hexsha": "809858d50119ee53dd82842dcedd6e9ec7a0b58f", "size": 1865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testFindw.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": "test/testFindw.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": "test/testFindw.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": 23.6075949367, "max_line_length": 58, "alphanum_fraction": 0.4697050938, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7522308652082684}}
{"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 \u2208 0:.05:0.5)\n0.017945395966538547\n\njulia> maximum(abs, exp(x) - fit(RationalFunction, ex, 1,2)(x) for x \u2208 0:.05:0.5)\n0.0016624471707165078\n\njulia> maximum(abs, exp(x) - fit(RationalFunction, ex, 2,1)(x) for x \u2208 0:.05:0.5)\n0.001278729299871717\n\njulia> maximum(abs, exp(x) - fit(RationalFunction, ex, 2,2)(x) for x \u2208 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 \u2265 m + n`, find a rational function `p/q` with\n`degree(p) \u2264 m`, `degree(q) \u2264 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 \u2208 1:n, i \u2208 0:n]\n    \n    qs\u2032 = cs[:, 2:end] \\ cs[:,1]\n    qs = vcat(1, -qs\u2032)\n\n    cs = [c[0 + j - i] for j \u2208 0:m, i\u22080: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": "using Newton\nusing Test\n\n\nf1(x)=x^3\nf1_prime(x)=3*x^2\n\nf2(x) = sin(x)\nf2_prime(x) = cos(x)\n\nf3(x) = log(x)\nf3_prime(x) = 1//x\n\n\nfs=[f1,f2,f3]\nf_primes=[f1_prime,f2_prime,f3_prime]\nf_nc(x) = 2+ x^2\nf_nc_prime(x) = 2*x\n\n@testset \"Newton.jl\" begin\n    \n    for (f,f_prime) in zip(fs,f_primes) # Several test for the root of a known function,given f and analytical f\u2032\n        @test newtonroot(f,x\u2080=1).x\u2248newtonroot(f,f_prime,x\u2080=1).x \n    end\n\n    for (f,f_prime) in zip(fs,f_primes)\n        for i in 1:200:1000 # test to ensure that maxiter is working\n            @test  newtonroot(f,f_prime,x\u2080=1, maxiter=i)===nothing || newtonroot(f,f_prime,x\u2080=1, maxiter=i).iteration <= i\n        end\n    end\n\n    for (f,f_prime) in zip(fs,f_primes)\n        for i in 1:200:1000 # test to ensure that maxiter is working\n            @test  newtonroot(f,f_prime,x\u2080=1, maxiter=i)===nothing || newtonroot(f,f_prime,x\u2080=1, maxiter=i).iteration <= i\n        end\n    end\n\n    @test newtonroot(f_nc,x\u2080=1) === nothing # Test of non-convergence\n    @test newtonroot(f_nc,f_nc_prime,x\u2080=1)=== nothing # Test of non-convergence\n\n    @test newtonroot(f1,f1_prime,x\u2080=BigFloat(1)).x |> typeof == BigFloat # BigFloat roots\n    @test newtonroot(f1,x\u2080=BigFloat(1)).x |> typeof == BigFloat # BigFloat roots\n\n    @test newtonroot(f1,x\u2080=1) == nothing ? true : newtonroot(f1,x\u2080=1).norm_dif <=1E-5\n    @test newtonroot(f1,f1_prime, x\u2080=1) == nothing ? true : newtonroot(f1,x\u2080=1).norm_dif <=1E-5\n\nend\n", "meta": {"hexsha": "5843d35b19e6b61b5d68d1084247040c24b0e90c", "size": 1454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 30.2916666667, "max_line_length": 122, "alphanum_fraction": 0.6492434663, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7522308516114186}}
{"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    \u03c1,I,\u03c3,\u03c4 = estimate_img_properties(img)\r\n    \u03bb = smoothness\r\n    return retrieve_surface(DiscreteShapeBound(), img, \u03c1, I, iterations, smoothness=\u03bb)\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    \u03c1 = 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(\u03c1, 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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.16\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.16\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u2550beee83e0-2162-11eb-10f1-7f63ce3708d2\n# \u2560\u2550beeeb36a-2162-11eb-0698-5fc29070f3ee\n# \u255f\u250070182cd8-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 Bilevel\nusing ForwardDiff\nusing Bilevel: svd, svd_finite\nusing LinearAlgebra\nusing BenchmarkTools\n\nA = rand(3,3)\nd = svd(A)\n# d.S[3] = d.S[2]\nA = d.U*Diagonal(d.S)*d.V'\nz0 = A[:]\n# z0 = rand(4)*200. .- 100.\n\nfunction f(a)\n    n = Int(sqrt(length(a)))\n    A = reshape(a,n,n) .* 2.\n    # if eltype(A) <: ForwardDiff.Dual\n        # U,s,V = svd_finite(A)\n    # else\n        U,s,V = svd(A)\n    # end\n    return vcat(U[:],s[:],V[:])\nend\n\n# sol = f(z0)\n\n# autodiff\nJ_auto = ForwardDiff.jacobian(f,z0)\n\n# # # numerical\n# \u03f5 = sqrt(eps(1.))\n# J_num = zeros(size(J_auto))\n# for i = 1:length(z0)\n#     \u03b4 = zeros(length(z0))\n#     \u03b4[i] = \u03f5\n#     J_num[:,i] = (f(z0 + \u03b4) .- sol)/\u03f5\n# end\n#\n# display(sol)\n# println(\"\")\n# println(\"Auto\")\n# display(J_auto)\n# println(\"\")\n# display(maximum(abs.(J_auto)))\n# println(\"\")\n# println(\"\")\n# println(\"Finite diff\")\n# display(J_num)\n# println(\"\")\n# display(maximum(abs.(J_num)))\n# println(\"\")\n# println(\"\")\n#\n# err = maximum(abs.(J_auto .- J_num))\n# display(err)\n# println(\"\")\n#\n# err = sort(abs.(J_auto .- J_num)[:])\n# display(err)\n# println(\"\")\n", "meta": {"hexsha": "a44d7a6849608b6af0425e484ddb843c223c6ce2", "size": 1077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_svd.jl", "max_stars_repo_name": "blandry/Bilevel.jl", "max_stars_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-03-14T01:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T19:15:50.000Z", "max_issues_repo_path": "test/test_svd.jl", "max_issues_repo_name": "blandry/Bilevel.jl", "max_issues_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-07T15:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T16:17:26.000Z", "max_forks_repo_path": "test/test_svd.jl", "max_forks_repo_name": "blandry/Bilevel.jl", "max_forks_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-27T10:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T07:00:49.000Z", "avg_line_length": 17.6557377049, "max_line_length": 39, "alphanum_fraction": 0.5636025998, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7522216265079502}}
{"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 .\u2265 0)\n        w = v\n    else\n        u = sort(v, rev=true)\n        cssv = cumsum(u)\n        \u03c1 = findall(>(0), u .* Array((1:n)) .> (cssv .- s))[end]\n        \u03b8 = (cssv[\u03c1] - s) / (\u03c1)\n        w = max.(v .- \u03b8, 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 .\u2265 0)\n        x = y\n    else\n        let \u03c4\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                    \u03c4 = (cumsum_u - a) / k\n                else\n                    break\n                end\n            end\n            x = max.(y .- \u03c4, 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 .\u2265 0)\n        return y\n    else\n        \u03c4 = 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                \u03c4 = (cumsum_u - a) / k\n            else\n                break\n            end\n        end\n        y = max.(y .- \u03c4, 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 .\u2265 0)\n        x = y\n    else\n        \u03c4 = 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                \u03c4 = (cumsum_u - a) / k\n            else\n                break\n            end\n        end\n        x = max.(y .- \u03c4, 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 .\u2265 0)\n        x = y\n    else\n        \u03c4 = 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                \u03c4 = (cumsum_u - a) / k\n            else\n                break\n            end\n        end\n        x = max.(y .- \u03c4, 0.)\n    end\n    return x\nend\n\n\"\"\"\nFrom Condat \u201cFast projection onto the simplex and the l_1 ball\u201d. In: Mathematical Programming 158.1\n(2016), pp. 575\u2013585\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    \u03c1 = y[1] - a\n    for n in 2:N\n        yn = y[n]\n        if yn > \u03c1\n            \u03c1 += (yn - \u03c1) / (length(v) + 1)\n            if \u03c1 > yn - a\n                append!(v, y[n])\n            else\n                append!(v_tilde, v)\n                v = [yn]\n                \u03c1 = yn - a\n            end\n        end\n    end\n\n    if !isempty(v_tilde)\n        for yi in v_tilde\n            if yi > \u03c1\n                append!(v, yi)\n                \u03c1 += (yi - \u03c1) / 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 \u2264 \u03c1\n                deleteat!(v, i)\n                \u03c1 += (\u03c1 - yi) / length(v)\n                flag = true\n            end\n        end\n    end\n    \u03c4 = \u03c1\n    x = max.(y .- \u03c4, 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    \u03c1 = 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 - (\u03c1 + drho) * v[k] < z\n            s += ds\n            \u03c1 += drho\n            U = L\n        else\n            U = G\n        end\n    end\n    theta = (s - z) / \u03c1\n    return max.(v .- theta, 0.)\n\nend\n\n\n\n\nfunction proj_simplex4(v, z=1., \u03c4=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 < \u03c4 && 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": "using Base.Test\nusing MathProgBase\nusing MathProgBase.SolverInterface\nusing Xpress\n\nfunction quadprogtest(solver=MathProgBase.defaultQPsolver)\n    println(\"Testing quadprog with solver \", string(typeof(solver)))\n\n    sol = quadprog([0., 0., 0.],[2. 1. 0.; 1. 2. 1.; 0. 1. 2.],[1. 2. 3.; 1. 1. 0.],'>',[4., 1.],-Inf,Inf,solver)\n    \n    @test sol.status == :Optimal\n    @test_approx_eq_eps sol.objval 130/70 1e-5\n    @test_approx_eq_eps norm(sol.sol[1:3] - [0.5714285714285715,0.4285714285714285,0.8571428571428572]) 0.0 1e-4\n    println(\"prs 1\")\n    let\n    m = LinearQuadraticModel(solver)\n    loadproblem!(m, [1. 2. 3.; 1. 1. 0.],[-Inf,-Inf,-Inf],[Inf,Inf,Inf],[0.,0.,0.],[4., 1.],[Inf,Inf], :Min)\n\n    setquadobj!(m,diagm([10.0,10.0,10.0]))\n    rows = [1, 2, 2, 2, 3, 3, 3]\n    cols = [1, 1, 1, 2, 2, 3, 3]\n    vals = Float64[2, 0.5, 0.5, 2, 1, 1, 1]\n    setquadobj!(m,rows,cols,vals)\n    optimize!(m)\n    stat = status(m)\n    @test stat == :Optimal\n    @test_approx_eq_eps getobjval(m) 130/70 1e-5\n    @test_approx_eq_eps norm(getsolution(m) - [0.5714285714285715,0.4285714285714285,0.8571428571428572]) 0.0 1e-4\n    end\n    println(\"prb 2\")\n\n    let\n    m = LinearQuadraticModel(solver)\n    loadproblem!(m, [-1. 1.; 1. 1.], [0.,0.], [Inf,Inf], [1.,1.], [0.,0.], [Inf,Inf], :Max)\n    addquadconstr!(m, [2], [1.], [1], [1], [1.], '<', 2)\n    optimize!(m)\n    stat = status(m)\n    @test stat == :Optimal\n    @test_approx_eq_eps getobjval(m) 2.25 1e-4\n    @test_approx_eq_eps norm(getsolution(m) - [0.5,1.75]) 0.0 1e-3\n    end\n    println(\"Done\")\nend\nquadprogtest(XpressSolver(OPTIMALITYTOL = 1e-8)) ", "meta": {"hexsha": "97788073b4cd78ca759f69437bc2f3033bf8efc8", "size": 1601, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/xprs_test03.jl", "max_stars_repo_name": "JuliaPackageMirrors/Xpress.jl", "max_stars_repo_head_hexsha": "165739426e00b6c5e22f006fc9c7fc1d30458cb3", "max_stars_repo_licenses": ["MIT"], "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/xprs_test03.jl", "max_issues_repo_name": "JuliaPackageMirrors/Xpress.jl", "max_issues_repo_head_hexsha": "165739426e00b6c5e22f006fc9c7fc1d30458cb3", "max_issues_repo_licenses": ["MIT"], "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/xprs_test03.jl", "max_forks_repo_name": "JuliaPackageMirrors/Xpress.jl", "max_forks_repo_head_hexsha": "165739426e00b6c5e22f006fc9c7fc1d30458cb3", "max_forks_repo_licenses": ["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.3863636364, "max_line_length": 114, "alphanum_fraction": 0.6077451593, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7522216223511314}}
{"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\u00f72+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 = \u00b1Inf`.\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\u00dfian quadrature\n\n\"\"\"\n    change_interval!(xs, ws, x, w[, a=0, b=1, \u03b3=1])\n\nTransform the Gau\u00dfian quadrature roots `x` and weights `w` on the\nelementary interval `[-1,1]` to the interval `[\u03b3*a,\u03b3*b]` and store the\nresult in `xs` and `ws`, respectively. `\u03b3` 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), \u03b3=one(T)) where T\n    xs .= lerp.(\u03b3*a, \u03b3*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), \u03b3::U=one(T)) where {T,U} =\n    change_interval!(similar(x,U), similar(w), x, w, a, b)\n\n# * Gau\u00df\u2013Legendre quadrature\n\n\"\"\"\n    num_quadrature_points(k, k\u2032)\n\nThe number of quadrature points needed to exactly compute the matrix\nelements of an operator of polynomial order `k\u2032` with respect to a\nbasis of order `k`.\n\"\"\"\nfunction num_quadrature_points(k, k\u2032)\n    N2 = 2*(k-1) + k\u2032\n    N2>>1 + N2&1\nend\n\n\"\"\"\n    lgwt(t, N) -> (x,w)\n\nGenerate the `N` Gau\u00df\u2013Legendre 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 \u2265 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\u00df\u2013Lobatto\n\nfunction element_grid(order, a::T, b::T, c::T=zero(T), ei\u03d5=one(T)) where T\n    x,w = gausslobatto(order)\n    xs,ws = change_interval(x, w, a-c, b-c, ei\u03d5)\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": "@testset \"Map, reduce, mapreduce, broadcast\" begin\n    @testset \"map and map!\" begin\n        v1 = @SVector [2,4,6,8]\n        v2 = @SVector [4,3,2,1]\n        mv = MVector{4, Int}()\n\n        normal_v1 = [2,4,6,8]\n        normal_v2 = [4,3,2,1]\n\n        @test map(-, v1) === @SVector [-2, -4, -6, -8]\n        @test map(+, v1, v2) === @SVector [6, 7, 8, 9]\n        @test map(+, normal_v1, v2) === @SVector [6, 7, 8, 9]\n        @test map(+, v1, normal_v2) === @SVector [6, 7, 8, 9]\n\n        map!(+, mv, v1, v2)\n        @test mv == @MVector [6, 7, 8, 9]\n    end\n\n    @testset \"reduce\" begin\n        v1 = @SVector [2,4,6,8]\n        @test reduce(+, v1) === 20\n        @test reduce(+, 0, v1) === 20\n    end\n\n    @testset \"mapreduce\" begin\n        v1 = @SVector [2,4,6,8]\n        v2 = @SVector [4,3,2,1]\n        @test mapreduce(-, +, v1) === -20\n        @test mapreduce(-, +, 0, v1) === -20\n        @test mapreduce(*, +, v1, v2) === 40\n        @test mapreduce(*, +, 0, v1, v2) === 40\n    end\n\n    @testset \"broadcast and broadcast!\" begin\n        c = 2\n        v1 = @SVector [2,4,6,8]\n        v2 = @SVector [4,3,2,1]\n        mv = MVector{4, Int}()\n        mm = MMatrix{4, 2, Int}()\n        M = @SMatrix [1 2; 3 4; 5 6; 7 8]\n\n        @test broadcast(-, v1) === map(-, v1)\n\n        @test broadcast(+, v1, c) === @SVector [4, 6, 8, 10]\n        @test broadcast(+, v1, v2) === map(+, v1, v2)\n        @test broadcast(+, v1, M) === @SMatrix [3 4; 7 8; 11 12; 15 16]\n\n        broadcast!(-, mv, v1)\n        @test mv == @MVector [-2, -4, -6, -8]\n\n        broadcast!(+, mv, v1, v2)\n        @test mv == @MVector [6, 7, 8, 9]\n\n        broadcast!(+, mm, v1, M)\n        @test mm == @MMatrix [3 4; 7 8; 11 12; 15 16]\n    end\nend\n", "meta": {"hexsha": "00e64d44cd766846f3b8d24393a7c0c2a0607326", "size": 1702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/mapreduce.jl", "max_stars_repo_name": "JuliaPackageMirrors/StaticArrays.jl", "max_stars_repo_head_hexsha": "c453f137c163fa435659b263d8af8e6f87f07d42", "max_stars_repo_licenses": ["MIT"], "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/mapreduce.jl", "max_issues_repo_name": "JuliaPackageMirrors/StaticArrays.jl", "max_issues_repo_head_hexsha": "c453f137c163fa435659b263d8af8e6f87f07d42", "max_issues_repo_licenses": ["MIT"], "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/mapreduce.jl", "max_forks_repo_name": "JuliaPackageMirrors/StaticArrays.jl", "max_forks_repo_head_hexsha": "c453f137c163fa435659b263d8af8e6f87f07d42", "max_forks_repo_licenses": ["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.3448275862, "max_line_length": 71, "alphanum_fraction": 0.4459459459, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7522216207847114}}
{"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\u00f6ssler [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\u00f6ssler, 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\u00e9'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`\u03b8` to be the first, and the angular momentum `p` to be the second, while\nboth variables\nare always taken modulo 2\u03c0 (the mapping is on the [0,2\u03c0)\u00b2 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), \u0393 = 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 `\u0393`\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\u2013133 (1988)\n\"\"\"\nfunction coupledstandardmaps end\nusing SparseArrays\nfunction coupledstandardmaps(M::Int, u0 = 0.001rand(2M);\n    ks = ones(M), \u0393 = 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 \u2202/\u2202p 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, \u0393)\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, \u0393 = p\n    @inbounds for i in f.idxs\n\n        xnew[i+N] = mod2pi(\n            x[i+N] + ks[i]*sin(x[i]) -\n            \u0393*(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, \u0393 = p\n    # x[i] \u2261 \u03b8\u1d62\n    # x[[idxsp1[i]]] \u2261 \u03b8\u1d62+\u2081\n    # x[[idxsm1[i]]] \u2261 \u03b8\u1d62-\u2081\n    @inbounds for i in f.idxs\n        cos\u03b8 = cos(x[i])\n        cos\u03b8p= cos(x[f.idxsp1[i]] - x[i])\n        cos\u03b8m= cos(x[f.idxsm1[i]] - x[i])\n        J[i+M, i] = ks[i]*cos\u03b8 + \u0393*(cos\u03b8p + cos\u03b8m)\n        J[i+M, f.idxsm1[i]] = - \u0393*cos\u03b8m\n        J[i+M, f.idxsp1[i]] = - \u0393*cos\u03b8p\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\u00e9non map is a two-dimensional mapping due to H\u00e9non [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\u00e9non, 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 \u2264 x \u2264 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 \u2264 x \u2264 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": "function contour_mesh(f::Function,\n                      bounds::HyperRectangle,\n                      isosurface_value::Number=0.0,\n                      resolution::Real=maximum(widths(bounds))/20.0)\n    \n    # Extract an isosurface from a vector-input function in 3 dimensions and\n    # return it as a mesh.\n    window_width = widths(bounds)\n    sdf = SignedDistanceField(x -> f(SVector{3, Float64}(x[1], x[2], x[3])),\n                              bounds,\n                              resolution)\n    mesh = HomogenousMesh(sdf, MarchingTetrahedra(isosurface_value))\nend\n\ncontour_mesh(f::Function,\n             lower_bound::Vec,\n             upper_bound::Vec,\n             isosurface_value::Number=0.0,\n             resolution::Real=maximum(upper_bound - lower_bound)/20.0) = (\n    contour_mesh(f,\n                 HyperRectangle(lower_bound, upper_bound - lower_bound),\n                 isosurface_value,\n                 resolution))\n\ncontour_mesh(f::Function,\n             lower_bound::AbstractVector,\n             upper_bound::AbstractVector,\n             isosurface_value::Number=0.0,\n             resolution::Real=maximum(upper_bound - lower_bound)/20.0) = (\n    contour_mesh(f,\n                 Vec{3, Float64}(lower_bound[1], lower_bound[2], lower_bound[3]),\n                 Vec{3, Float64}(upper_bound[1], upper_bound[2], upper_bound[3]),\n                 isosurface_value,\n                 resolution))\n", "meta": {"hexsha": "85938aa14756a1ccae2e84931794292f985e42ec", "size": 1418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/contour_meshes.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DrakeVisualizer.jl-49c7015b-b8db-5bc5-841b-fcb31c578176", "max_stars_repo_head_hexsha": "7b2bfa484a9bc891cf82efe4a097696866cfcbd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2016-04-15T14:42:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-22T19:19:45.000Z", "max_issues_repo_path": "src/contour_meshes.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DrakeVisualizer.jl-49c7015b-b8db-5bc5-841b-fcb31c578176", "max_issues_repo_head_hexsha": "7b2bfa484a9bc891cf82efe4a097696866cfcbd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2016-04-15T20:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-03T05:06:55.000Z", "max_forks_repo_path": "src/contour_meshes.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DrakeVisualizer.jl-49c7015b-b8db-5bc5-841b-fcb31c578176", "max_forks_repo_head_hexsha": "7b2bfa484a9bc891cf82efe4a097696866cfcbd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2016-04-15T19:55:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:51:42.000Z", "avg_line_length": 40.5142857143, "max_line_length": 81, "alphanum_fraction": 0.5677009873, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8221891283434876, "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": "module BackwardKernel\n\ninclude(\"../Misc.jl\")\nusing .Misc\n\nusing Distributions, SpecialFunctions\nimport DataStructures: PriorityQueue, peek, enqueue!, dequeue!\nimport Base: iterate, length, sum, eltype\nimport Base.Iterators: product\n\nexport EventQueue, sum, length, eltype, iterate\n\nmutable struct EventQueue{\u211c<:Real, N}\n    T::Int\n    X::Array{\u211c,N}\n    pq::PriorityQueue{NTuple{N,Int},Float64,Base.Order.ForwardOrdering}\n    function EventQueue(X::Array{\u211c,N}) where {\u211c<:Real,N}\n        I = size(X)\n        T::Int = Int(round(sum(X)))\n        pq = PriorityQueue([i => rand(Dirichlet([1.0,X[i...]]))[1] \n                           for i \u2208 product(map(I\u2099 -> 1:I\u2099, I)...) if X[i...]>0])\n        return new{\u211c,N}(T,copy(X),pq)\n    end\nend\n\nBase.sum(L::EventQueue) = sum(L.X)\nBase.length(L::EventQueue) = L.T\nBase.eltype(L::EventQueue{\u211c,N}) where {\u211c<:Real, N} = NTuple{N,Integer}\nBase.size(L::EventQueue) = size(L.X)\n\nfunction Base.iterate(L::EventQueue, state::\u01b5=1) where {\u01b5<:Integer}\n    if L.T < state\n        return nothing\n    end\n    \n    t = peek(L.pq)[2]\n    i = dequeue!(L.pq)\n    \n    L.X[i...] -= 1\n    if L.X[i...] > 0.0\n        L.pq[i] = t + (1.0 - t)*rand(Dirichlet([1.0, L.X[i...]]))[1]\n    end\n\n    return i, state+1\nend\n\nend", "meta": {"hexsha": "1572d3af254476f4882f1510fad83e3406ab818b", "size": 1234, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NCP/BackwardKernel.jl", "max_stars_repo_name": "mehmetburakkurutmaz/bam", "max_stars_repo_head_hexsha": "eb2583edf5037dec95d5a22d22f2dff7f00f4291", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-07T18:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-26T12:43:14.000Z", "max_issues_repo_path": "src/NCP/BackwardKernel.jl", "max_issues_repo_name": "mehmetburakkurutmaz/bam", "max_issues_repo_head_hexsha": "eb2583edf5037dec95d5a22d22f2dff7f00f4291", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-22T16:52:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-22T16:52:56.000Z", "max_forks_repo_path": "src/NCP/BackwardKernel.jl", "max_forks_repo_name": "atcemgil/bam", "max_forks_repo_head_hexsha": "dadaae493e52e38a421dbe0359d94fe23adb297c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-20T14:45:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-29T13:51:39.000Z", "avg_line_length": 26.2553191489, "max_line_length": 80, "alphanum_fraction": 0.5972447326, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7521964883919166}}
{"text": "function harmonic_oscillator(; X=Universe(2))\n    A = [0.0 1.0; -1.0 0.0]\n    prob = @ivp(x' = Ax, x(0) \u2208 Singleton([1.0, 0.0]), x \u2208 X)\n    tspan = (0.0, 20.0)\n    return prob, tspan\nend\n\nfunction harmonic_oscillator_homog_RFEM()\n    A = [0 1; -(4\u03c0)^2 0]\n    X0 = Hyperrectangle([1.0, 0.0], [0.1, 0.1])\n    prob = @ivp(x' = A*x, x(0) \u2208 X0)\n    tspan = (0.0, 2.0)\n    return prob, tspan\nend\n\nfunction harmonic_oscillator_forced_RFEM()\n    A = [0 1; -(4\u03c0)^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) \u00d7 Interval(0.8, 1.2)\n    prob = @ivp(x' = A*x + B*u, x(0) \u2208 X0, x \u2208 X, u \u2208 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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Distributions, Random, StatsBase, DataFrames, Plots\n\tRandom.seed!(1)\nend;\n\n# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.29\"\n\n# \u2554\u2550\u2561 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nZ() = sqrt(-2*log(rand()))*cos(2*pi*rand())\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.29\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u25500000b90c-21c2-11eb-2426-fdbaf4727f0c\n# \u255f\u250070182cd8-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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 eedb4bf8-19a9-11eb-106b-69b047d4118e\nmd\"\"\"\n## Reading data\n\"\"\"\n\n# \u2554\u2550\u2561 dfa5fbf0-18e7-11eb-391b-1d878b9c96f0\nfile = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00560/SeoulBikeData.csv\"\n\n# \u2554\u2550\u2561 aed964bc-18e7-11eb-11f1-a3d9957a45f5\ndf = DataFrame(CSV.File(download(file); dateformats = Dict(:Date => \"dd/mm/yyyy\")));\n\n# \u2554\u2550\u2561 4d4a9158-18ec-11eb-2fb0-c178637f903a\nmd\"\"\"\n## Data wrangling\n\"\"\"\n\n# \u2554\u2550\u2561 09577b1e-19aa-11eb-3e6c-175705b4b951\nmd\"\"\"\nLet's quickly examine the data frame and its columns.\n\"\"\"\n\n# \u2554\u2550\u2561 c5b4e26a-18e7-11eb-2bef-2d937faa252d\ndescribe(df, :eltype, :min, :mean, :max, :nmissing)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 16c31048-19b6-11eb-2ad8-1f984acfb06f\nmd\"\"\"\n## Correlation analysis\n\"\"\"\n\n# \u2554\u2550\u2561 9564ab04-19b4-11eb-3c4c-815fe8a6031a\nnames(df)\n\n# \u2554\u2550\u2561 3084d7a6-19b5-11eb-1fa5-9b9f7cd482f4\nlet \n\tcols = 3:11\n\tcolnames = names(df)[cols]\n\t\u03a3 = cor(Matrix(df[:, cols]))\n\theatmap(colnames, colnames, \u03a3; xrotation = 45, seriescolor = :PiYG_4)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 32cd8006-18ec-11eb-221a-d38281aadffb\nplot(df.Date, df.RentedBikeCount; \n\tlegend = :none, \n\tylabel = \"Rented Bike Count\")\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 79056460-19b6-11eb-1c5c-bf9224a0b18e\ndf.Hour2 = df.Hour\n\n# \u2554\u2550\u2561 9506548a-19b6-11eb-02dc-ad2832999a5b\ncategorical!(df, :Hour2);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c18fa04e-19a5-11eb-2f5c-0bdba322a26f\nhour_model = @formula(RentedBikeCount ~ 1 + Hour2)\n\n# \u2554\u2550\u2561 558893b4-19a6-11eb-3e84-ef27b2749b80\nmd\"\"\"\nTo fit the model, we can use the `lm` function.\n\"\"\"\n\n# \u2554\u2550\u2561 66b6f680-19a6-11eb-2d2f-afe8d206ee5f\nols = lm(hour_model, df)\n\n# \u2554\u2550\u2561 a46a544a-19a6-11eb-3de3-87dcf7bf431f\nmd\"\"\"\nWe can now use the fitted model to predict bike demand.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1de7c9b2-19b4-11eb-2085-7b7383899819\nmd\"\"\"\nThat's great! The RMSD is now further reduced although not by a whole lot.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250002eb9d36-18e8-11eb-24a9-db6f58080189\n# \u255f\u2500eedb4bf8-19a9-11eb-106b-69b047d4118e\n# \u2560\u255081915028-18e7-11eb-0aed-57a75839d4a7\n# \u2560\u2550dfa5fbf0-18e7-11eb-391b-1d878b9c96f0\n# \u2560\u2550aed964bc-18e7-11eb-11f1-a3d9957a45f5\n# \u255f\u25004d4a9158-18ec-11eb-2fb0-c178637f903a\n# \u255f\u250009577b1e-19aa-11eb-3e6c-175705b4b951\n# \u2560\u2550c5b4e26a-18e7-11eb-2bef-2d937faa252d\n# \u255f\u25006ddeb944-18ec-11eb-05c7-b51e7b01578e\n# \u2560\u2550ebc9c09a-18e9-11eb-1f56-ef92258af11f\n# \u255f\u250016c31048-19b6-11eb-2ad8-1f984acfb06f\n# \u2560\u25509564ab04-19b4-11eb-3c4c-815fe8a6031a\n# \u2560\u25503084d7a6-19b5-11eb-1fa5-9b9f7cd482f4\n# \u255f\u25002ef9d8a6-19b6-11eb-0cc5-e1831ce6c40a\n# \u255f\u25007deee71e-18ec-11eb-113d-fb0cdc6e07ef\n# \u2560\u255032cd8006-18ec-11eb-221a-d38281aadffb\n# \u255f\u2500a9f3aeda-18ec-11eb-2cb9-9f12fd001d88\n# \u255f\u250069199458-18ef-11eb-1a46-7d71379a4c04\n# \u2560\u25505de23772-18ed-11eb-1105-85661397bcd3\n# \u255f\u25008789d48e-18ef-11eb-2b87-2337472759c7\n# \u2560\u25505ef37b5a-18eb-11eb-3f75-cfb5947950fb\n# \u255f\u25003dc1127e-19a4-11eb-2c09-4f2624f479ac\n# \u255f\u2500716cb212-19b1-11eb-190a-7702595f6bab\n# \u2560\u255079056460-19b6-11eb-1c5c-bf9224a0b18e\n# \u2560\u25509506548a-19b6-11eb-02dc-ad2832999a5b\n# \u255f\u25007553988e-19a5-11eb-3549-bfd4ea98b2fd\n# \u2560\u2550c18fa04e-19a5-11eb-2f5c-0bdba322a26f\n# \u255f\u2500558893b4-19a6-11eb-3e84-ef27b2749b80\n# \u2560\u255066b6f680-19a6-11eb-2d2f-afe8d206ee5f\n# \u255f\u2500a46a544a-19a6-11eb-3de3-87dcf7bf431f\n# \u2560\u2550bfe39e20-19a6-11eb-1b9c-b95be62dadb5\n# \u255f\u2500079fe824-19a7-11eb-3f1d-b3aa9c9b0f33\n# \u2560\u255041fb7ff4-19a7-11eb-0945-017db54aa411\n# \u255f\u2500e3615da0-19a7-11eb-3dc7-d734a6da4420\n# \u255f\u2500ab20e2f6-19a9-11eb-09cd-eff9e75608ee\n# \u2560\u25501accea7a-19a8-11eb-2e37-b943977ad801\n# \u255f\u250061eb2598-19a8-11eb-055d-b166da58fa50\n# \u2560\u255066967c54-19b3-11eb-1b13-856ef40132fa\n# \u255f\u25001de7c9b2-19b4-11eb-2085-7b7383899819\n# \u255f\u250034be34aa-19b4-11eb-1a17-e1253c48b050\n# \u255f\u2500544e7ac0-19b2-11eb-3931-8f7f10c23212\n# \u255f\u25007c1251d4-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 ComplexPhasePortrait, Colors\nusing Test\n\nnx = 1000\nx = range(-1, stop=1, length=nx)\nZ = x' .+ reverse(x)*im\n\nf = z -> (z - 0.5im)^2 * (z + 0.5+0.5im)/z\nfz = f.(Z)\n\nimg = portrait(fz)\n@test img[1,5] \u2248 RGB{Float64}(0.11686143572621054,1.0,0.0)\n\nimg = portrait(fz, ctype=\"nist\")\n@test img[1,5] \u2248 RGB{Float64}(0.4916573971078975,1.0,0.0)\n\nimg = portrait(fz, PTstepphase)\n@test img[1,5] \u2248 RGB{Float64}(0.09621043816546014,0.8232864637301505,0.0)\n\nimg = portrait(fz, PTstepmod)\n@test img[1,5] \u2248 RGB{Float64}(0.10275080341985139,0.8792533035498697,0.0)\n\nimg = portrait(fz, PTcgrid)\n@test img[1,5] \u2248 RGB{Float64}(0.08803468544171197,0.7533253797083627,0.0)\n", "meta": {"hexsha": "0f29d9f56b099f57022816e8356dc6c8315f0632", "size": 655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaTagBot/ComplexPhasePortrait.jl", "max_stars_repo_head_hexsha": "7c78c270460d2f24d3778a2782ad2d71f24de821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-01-04T05:49:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T13:42:07.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "JuliaTagBot/ComplexPhasePortrait.jl", "max_issues_repo_head_hexsha": "7c78c270460d2f24d3778a2782ad2d71f24de821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-10-19T18:38:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-09T19:43:30.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "JuliaTagBot/ComplexPhasePortrait.jl", "max_forks_repo_head_hexsha": "7c78c270460d2f24d3778a2782ad2d71f24de821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-01-04T05:49:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T00:31:06.000Z", "avg_line_length": 26.2, "max_line_length": 73, "alphanum_fraction": 0.6839694656, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7521063195394887}}
{"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": "\"\"\"\n    randomIntegerGenerator(rng::Random.AbstractRNG, genotypeSize::Integer,\n                           min::Integer, max::Integer)::IntegerGenotype\n\nGenerates an integer individual with genes generated randomly within **min** and **max**, both included.\n\n`Selfprovided Arguments` are already provided by the library, so, only `User Arguments` must be provided.\n\n# Selfprovided Arguments\n- `rng::Random.AbstractRNG`: random number generator for random number consistency along an experiment.\n\n# User Arguments\n- `genotypeSize::Integer`: number of genes.\n- `min::Integer`: lower limit for random generation.\n- `max::Integer`: upper limit for random generation.\n\"\"\"\nfunction randomIntegerGenerator(rng::Random.AbstractRNG, genotypeSize::Integer,\n                                min::Integer, max::Integer)::IntegerGenotype\n\n    # Checks if user introduce correctly the bounds\n    if min > max\n        min, max = max, min\n    end\n    # Memory reserve\n    genotype = Array{Integer}(undef, genotypeSize)\n    # Range for remainder\n    range = max - min + 1\n    # For each gen\n    for i = eachindex(genotype)\n        # Generates a number within range\n        genotype[i] = (rand(rng, UInt)%range)+min\n    end\n\n    return IntegerGenotype{Int64}(genotype)\nend # function\n", "meta": {"hexsha": "feea706d509e726d90efdb13ed48e41a629476f6", "size": 1264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/GeneticAlgorithms/IntegerGenotype/initialization.jl", "max_stars_repo_name": "SergioGmezM/GeneticJulia", "max_stars_repo_head_hexsha": "b9d6113a0e9746688b05a3ef1c394bddcb82b1fd", "max_stars_repo_licenses": ["MIT"], "max_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/GeneticAlgorithms/IntegerGenotype/initialization.jl", "max_issues_repo_name": "SergioGmezM/GeneticJulia", "max_issues_repo_head_hexsha": "b9d6113a0e9746688b05a3ef1c394bddcb82b1fd", "max_issues_repo_licenses": ["MIT"], "max_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/GeneticAlgorithms/IntegerGenotype/initialization.jl", "max_forks_repo_name": "SergioGmezM/GeneticJulia", "max_forks_repo_head_hexsha": "b9d6113a0e9746688b05a3ef1c394bddcb82b1fd", "max_forks_repo_licenses": ["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.1111111111, "max_line_length": 105, "alphanum_fraction": 0.6867088608, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7521063115501321}}
{"text": "using LinearAlgebra\nusing GEMPIC\nusing ParticleInCell\nusing Test\n\ninclude(\"test_poisson_1d.jl\")\ninclude(\"test_landau_damping.jl\")\ninclude(\"test_push.jl\")\ninclude(\"test_fdtd.jl\")\ninclude(\"test_deposition.jl\")\ninclude(\"test_particles.jl\")\ninclude(\"test_particle_group.jl\")\ninclude(\"test_splitting.jl\")\ninclude(\"test_poisson_2d.jl\")\ninclude(\"test_particle_mesh_coupling_spline_2d.jl\")\ninclude(\"test_spline_pp.jl\")\ninclude(\"test_particle_mesh_coupling_spline_1d.jl\")\ninclude(\"test_maxwell_1d_fem.jl\")\n", "meta": {"hexsha": "becfe12a9a9f19c35af8d48d00f58b7e70bc7508", "size": 497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_stars_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-16T04:53:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T17:21:12.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_issues_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_issues_repo_licenses": ["MIT"], "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": "JuliaVlasov/ParticleInCell.jl", "max_forks_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_forks_repo_licenses": ["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.1578947368, "max_line_length": 51, "alphanum_fraction": 0.8249496982, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7521063099538545}}
{"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])) \u2260 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 \u2260 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 \u2265 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 \u2265 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": "using SatisfiabilityInterface\nusing Symbolics\n\ndifferent_neighbours(E, c) = [c[i] \u2260 c[j] for (i, j) in E]\n\n\"Set up a graph colouring problem for a graph \nwith vertex set `V`, edge set `E` (a vector of edges (i, j)),\nwith `k` colours\"\nfunction graph_colouring_problem(V, E, k=3)\n\n    colours = [:red, :green, :yellow, :blue, :black][1:k]\n\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] \u2208 colours for i in 1:length(V)]\n        \n        [c[i] \u2260 c[j] for (i, j) in E]  #  different_colours(E, c)\n    ]\n\n    return DiscreteCSP(constraints)\nend\n\n\n@testset \"Graph colouring\" begin\n            \n    V = [1, 2, 3]  # vertices\n    E = [(1, 2), (2, 3)]  # edges\n\n    prob = graph_colouring_problem(V, E, 2)\n    status, results = solve(prob)\n\n    @test status==:sat\n\n    ks = sort(collect(keys(prob.varmap)))\n    colours = [results[k] for k in ks]\n\n    @test all(different_neighbours(E, colours))\nend\n\n@testset \"Ring graph\" begin\n\n    function 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\n    end\n\n    V, E = ring_graph(11)\n\n    prob = graph_colouring_problem(V, E, 2)\n    status, results = solve(prob)\n    @test status==:unsat\n\n    prob = graph_colouring_problem(V, E, 3)\n    status, results = solve(prob)\n    @test status==:sat\n\n    ks = sort(collect(keys(prob.varmap)))\n    colours = [results[k] for k in ks]\n    \n    @test all(different_neighbours(E, colours))\n\nend", "meta": {"hexsha": "c5eb23a5f65b0ec72065d03bd48f1b8c3c0d56a5", "size": 1525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 22.4264705882, "max_line_length": 74, "alphanum_fraction": 0.5862295082, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7520903492262155}}
{"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\u2081, x\u2082)\n    \u03b1 ~ Normal(0, 10)\n    \u03b2p ~ Normal(0, 10)\n    \u03b2pC ~ Normal(0, 10)\n\n    logits = \u03b1 .+ (\u03b2p .+ \u03b2pC * x\u2081) .* x\u2082\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": "import PipeLayout: linecoefs, pwl_ineqs, pwl_inverse\n\n@testset \"linear interpolation of 2d points\" begin\n    # simple line through origin\n    s, o = linecoefs(0, 0, 1, 2)\n    @test s \u2248 2\n    @test o \u2248 0\n\n    # order of points doesn't matter\n    s, o = linecoefs(1, 2, 0, 0)\n    @test s \u2248 2\n    @test o \u2248 0\n\n    # neg. slope with offset\n    s, o = linecoefs(2, 2, 4, 1)\n    @test s \u2248 -0.5\n    @test o \u2248 3\nend\n\n@testset \"inequalities for convex PWL function\" begin\n    # symmetric quadratic, with flat segment in the middle\n    xs = [-5, -3, -1, 1, 3, 5]\n    ineqs = pwl_ineqs(xs, xs.^2)\n    @test size(ineqs) == (5, 3)\n    @test ineqs[1,:] ./ ineqs[end,:]   \u2248 [-1, 1, 1]\n    @test ineqs[2,:] ./ ineqs[end-1,:] \u2248 [-1, 1, 1]\n    @test ineqs[3,:] ./ ineqs[3,2]     \u2248 [ 0, 1, 1]\nend\n\n@testset \"inverses from monotoneous PWL functions\" begin\n    @testset \"monotoneous increasing\" begin\n        xs = Float64[1, 2, 3, 4]\n        ys = xs.^2\n        @test_throws AssertionError pwl_inverse(xs, ys, 0.5)\n        @test pwl_inverse(xs, ys, 1.0) \u2248 1.0\n        @test pwl_inverse(xs, ys, 2.5) \u2248 1.5\n        @test pwl_inverse(xs, ys, 16.0) \u2248 4.0\n        @test_throws AssertionError pwl_inverse(xs, ys, 16.5)\n    end\n\n    @testset \"monotoneous decreasing\" begin\n        xs = Float64[1, 2, 3, 4]\n        ys = -xs.^2\n        @test_throws AssertionError pwl_inverse(xs, ys, -0.5)\n        @test pwl_inverse(xs, ys, -1.0) \u2248 1.0\n        @test pwl_inverse(xs, ys, -2.5) \u2248 1.5\n        @test pwl_inverse(xs, ys, -16.0) \u2248 4.0\n        @test_throws AssertionError pwl_inverse(xs, ys, -16.5)\n    end\n\n    @testset \"with constant pieces\" begin\n        xs = Float64[1, 2, 3]\n        ys = Float64[1, 1, 5]\n        @test_throws AssertionError pwl_inverse(xs, ys, 0.5)\n        @test pwl_inverse(xs, ys, 1) \u2248 1.0\n        @test pwl_inverse(xs, ys, 3) \u2248 2.5\n        @test pwl_inverse(xs, ys, 5) \u2248 3.0\n        @test_throws AssertionError pwl_inverse(xs, ys, 5.5)\n    end\nend\n", "meta": {"hexsha": "ebe2134edb63f6e5103582886005f257ff5165a2", "size": 1935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/pwl.jl", "max_stars_repo_name": "robertschwarz/PipeLayout.jl", "max_stars_repo_head_hexsha": "2792b702aca532fe7cdae89de0232bfb914b7683", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-11-23T17:18:22.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-15T20:07:49.000Z", "max_issues_repo_path": "test/pwl.jl", "max_issues_repo_name": "robertschwarz/PipeLayout.jl", "max_issues_repo_head_hexsha": "2792b702aca532fe7cdae89de0232bfb914b7683", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-01-19T15:57:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T18:05:49.000Z", "max_forks_repo_path": "test/pwl.jl", "max_forks_repo_name": "robertschwarz/PipeLayout.jl", "max_forks_repo_head_hexsha": "2792b702aca532fe7cdae89de0232bfb914b7683", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-19T16:38:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-19T16:38:52.000Z", "avg_line_length": 31.7213114754, "max_line_length": 62, "alphanum_fraction": 0.5726098191, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7520903355916362}}
{"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` \u2013 a real-valued matrix A of size mxn\n* `p` \u2013 an integer p in min { m, n }\n\n# Output\n* `U` \u2013 an orthonormal matrix of size mxp\n* `V` \u2013 an orthonormal matrix of size nxp\n* `S` \u2013 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, \u03be, 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        \u03bextGrad = \u03be*xtGrad\n        return pxHess - \u03bextGrad\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        \u0394_bar=4*sqrt(2*p),\n        debug = [:Iteration, \" \", :Cost, \" | \", DebugEntry(:\u0394), \"\\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; \u03c3\u00b2::Float64=1.0, x\u2080::Float64=0.0) =\n    simulate_bm(t; \u03c3\u00b2=fill(\u03c3\u00b2, k), x\u2080=fill(x\u2080, k))\n\n\"\"\"\n    simulate_bm(t::Tree, k::Int, \u03c3::Vector{Float64} = ones(k), x\u2080::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 `\u03c3\u00b2` as the vector of diffusion coeffients of the traits (all 1.0 by default), and `x\u2080` as the vector of trait values at the root (all 0.0 by default).\n\"\"\"\nfunction simulate_bm(\n    t::Tree;\n    \u03c3\u00b2::Union{Float64, Vector{Float64}} = 1.0,\n    x\u2080::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 \u03c3\u00b2 isa Float64 && x\u2080 isa Float64\n        \u03c3\u00b2 = [\u03c3\u00b2]\n        x\u2080 = [x\u2080]\n    elseif \u03c3\u00b2 isa Float64 && x\u2080 isa Vector{Float64}\n        \u03c3\u00b2 = fill(\u03c3\u00b2, length(x\u2080))\n    elseif \u03c3\u00b2 isa Vector{Float64} && x\u2080 isa Float64\n        x\u2080 = fill(x\u2080, length(\u03c3\u00b2))\n    elseif length(\u03c3\u00b2) \u2260 length(x\u2080)\n        msg = \"the vectors `\u03c3\u00b2` and `x\u2080` must both have `k` number of elements.\"\n        throw(ArgumentError(msg))\n    end\n\n    k = length(x\u2080)\n    \u03c3 = .\u221a(\u03c3\u00b2)\n\n    return _simulate_bm_species(t, k, \u03c3, x\u2080)\nend\n\n\nfunction _simulate_bm_species(t::Tree, k::Int, \u03c3::Vector{Float64}, x\u2080::Vector{Float64})::SpeciesDataMatrix{Float64}\n    x = SpeciesDataMatrix{Float64}(t.dir, k)\n    for p \u2208 neighbours(t.origin)\n        _simulate_bm!(x, p, t.origin, k, \u03c3, x\u2080)\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    \u03c3::Vector{Float64},\n    x\u2080::Vector{Float64}\n    )\n    x\u209a = x\u2080 .+ \u03c3 .* \u221a(brlength(q, p)) .* randn(k)\n    if p.species > 0 && p.species \u2208 x.dir\n        x[p.species,:] = x\u209a\n    end\n    for r in neighbours(p)\n        r == q && continue\n        _simulate_bm!(x, r, p, k, \u03c3, x\u209a)\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 Rubin\nusing Tests\nusing Elliptic\nusing HypergeometricFunctions\nusing Polylogarithms\nusing SpecialFunctions\n\n@test integrate((a+b*sin(x))^-1*(A+B*cos(x)), x) == :(B*b^-1*log(a+b*sin(x))+2*A*(a^2+-1*b^2)^-1//2*arctan((a^2+-1*b^2)^-1//2*(b+a*tan((1/2)*x))))\n@test integrate((1+sin(x))^-1*(A+B*cos(x)), x) == :(B*log(1+sin(x))+-1*A*(1+sin(x))^-1*cos(x))\n@test integrate((1+-1*sin(x))^-1*(A+B*cos(x)), x) == :(-1*B*log(1+-1*sin(x))+A*(1+-1*sin(x))^-1*cos(x))\n@test integrate((a+b*sin(x))^-1*(b+c+cos(x)), x) == :(b^-1*log(a+b*sin(x))+(a^2+-1*b^2)^-1//2*(2b+2c)*arctan((a^2+-1*b^2)^-1//2*(b+a*tan((1/2)*x))))\n@test integrate((a+-1*b*sin(x))^-1*(b+c+cos(x)), x) == :(-1*b^-1*log(a+-1*b*sin(x))+-1*(a^2+-1*b^2)^-1//2*(2b+2c)*arctan((a^2+-1*b^2)^-1//2*(b+-1*a*tan((1/2)*x))))\n@test integrate((a+b*sin(x))^-1*(A+B*tan(x)), x) == :(-1*B*(-2b+2a)^-1*log(1+sin(x))+-1*B*(2a+2b)^-1*log(1+-1*sin(x))+2*A*(a^2+-1*b^2)^-1//2*arctan((a^2+-1*b^2)^-1//2*(b+a*tan((1/2)*x)))+B*a*(a^2+-1*b^2)^-1*log(a+b*sin(x)))\n@test integrate((a+b*sin(x))^-1*(A+B*cot(x)), x) == :(B*a^-1*log(sin(x))+-1*B*a^-1*log(a+b*sin(x))+2*A*(a^2+-1*b^2)^-1//2*arctan((a^2+-1*b^2)^-1//2*(b+a*tan((1/2)*x))))\n@test integrate((a+b*sin(x))^-1*(A+B*sec(x)), x) == :(B*(-2b+2a)^-1*log(1+sin(x))+-1*B*(2a+2b)^-1*log(1+-1*sin(x))+2*A*(a^2+-1*b^2)^-1//2*arctan((a^2+-1*b^2)^-1//2*(b+a*tan((1/2)*x)))+-1*B*b*(a^2+-1*b^2)^-1*log(a+b*sin(x)))\n@test integrate((a+b*sin(x))^-1*(A+B*csc(x)), x) == :(-1*B*a^-1*arctanh(cos(x))+a^-1*(a^2+-1*b^2)^-1//2*(-2*B*b+2*A*a)*arctan((a^2+-1*b^2)^-1//2*(b+a*tan((1/2)*x))))\n", "meta": {"hexsha": "68b202066a4c4a518a13256dae77a0d8b2213fae", "size": 1556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/4 Trig functions/4.1 Sine/4.1.8 (a+b sin)^m (c+d trig)^n.jl", "max_stars_repo_name": "bradeneliason/Rubin.jl", "max_stars_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-13T03:00:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T03:00:21.000Z", "max_issues_repo_path": "test/4 Trig functions/4.1 Sine/4.1.8 (a+b sin)^m (c+d trig)^n.jl", "max_issues_repo_name": "bradeneliason/Rubin.jl", "max_issues_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_issues_repo_licenses": ["MIT"], "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/4 Trig functions/4.1 Sine/4.1.8 (a+b sin)^m (c+d trig)^n.jl", "max_forks_repo_name": "bradeneliason/Rubin.jl", "max_forks_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 91.5294117647, "max_line_length": 223, "alphanum_fraction": 0.501285347, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.752089200729263}}
{"text": "#=\n# ReLU layer\n\nIn this example we look at what the ReLU layer hidden units look like,\nfor different parameter values.\n=#\n\n#=\nFirst load some packages.\n=#\n\nimport RestrictedBoltzmannMachines as RBMs\nusing CairoMakie, Statistics\nnothing #hide\n\n#=\nNow initialize our ReLU layer, with unit parameters spanning an interesting range.\n=#\n\n\u03b8s = [0; 10]\n\u03b3s = [5; 10]\nlayer = RBMs.ReLU([\u03b8 for \u03b8 in \u03b8s, \u03b3 in \u03b3s], [\u03b3 for \u03b8 in \u03b8s, \u03b3 in \u03b3s])\nnothing #hide\n\n#=\nNow we sample our layer to collect some data.\n=#\n\ndata = RBMs.sample_from_inputs(layer, zeros(size(layer)..., 10^6))\nnothing #hide\n\n#=\nLet's plot the resulting histogram of the activations of each unit.\nWe also overlay the analytical PDF.\n=#\n\nfig = Figure(resolution=(700,500))\nax = Axis(fig[1,1])\nxs = repeat(reshape(range(minimum(data), maximum(data), 100), 1, 1, 100), size(layer)...)\nps = exp.(RBMs.free_energies(layer) .- RBMs.energies(layer, xs))\nfor (i\u03b8, \u03b8) in enumerate(\u03b8s), (i\u03b3, \u03b3) in enumerate(\u03b3s)\n    hist!(ax, data[i\u03b8, i\u03b3, :], normalization=:pdf, label=\"\u03b8=$\u03b8, \u03b3=$\u03b3\")\n    lines!(xs[i\u03b8, i\u03b3, :], ps[i\u03b8, i\u03b3, :], linewidth=2)\nend\naxislegend(ax)\nfig\n", "meta": {"hexsha": "1a6a17b6e26fb2b071c5d56f7bee3319af337075", "size": 1104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/literate/layers/ReLU.jl", "max_stars_repo_name": "cossio/RestrictedBoltzmannMachines.jl", "max_stars_repo_head_hexsha": "557193f64fcefc6ac504c43a3a683e0201024138", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-09T07:58:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:49:00.000Z", "max_issues_repo_path": "docs/src/literate/layers/ReLU.jl", "max_issues_repo_name": "cossio/RestrictedBoltzmannMachines.jl", "max_issues_repo_head_hexsha": "557193f64fcefc6ac504c43a3a683e0201024138", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-12-06T23:13:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T13:08:22.000Z", "max_forks_repo_path": "docs/src/literate/layers/ReLU.jl", "max_forks_repo_name": "cossio/RestrictedBoltzmannMachines.jl", "max_forks_repo_head_hexsha": "557193f64fcefc6ac504c43a3a683e0201024138", "max_forks_repo_licenses": ["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.4893617021, "max_line_length": 89, "alphanum_fraction": 0.6865942029, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.752089200729263}}
{"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    \u03bds = [kernel_moment(kernel, Val(j)) for j = 0:3]\n    \u03c0s = [squared_kernel_moment(kernel, Val(j)) for j = 0:3]\n    C1 = 1 / 4 * abs2((abs2(\u03bds[3]) - \u03bds[2] * \u03bds[4]) / (\u03bds[3] * \u03bds[1] - abs2(\u03bds[2])))\n    C2_num = abs2(\u03bds[3]) * \u03c0s[1] - 2 * \u03bds[2] * \u03bds[3] * \u03c0s[2] + abs2(\u03bds[2]) * \u03c0s[3]\n    C2_denom = abs2(\u03bds[3] * \u03bds[1] - abs2(\u03bds[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\u2081 = 1.84 * Statistics.std(ZsR.Zs) * N^(-1 / 5)\n\n    interval_h\u2081 = Interval{:closed,:closed}(cutoff-h\u2081, cutoff+h\u2081)\n\n    ZsR_untreated_h\u2081 = ZsR_untreated[interval_h\u2081]\n    ZsR_treated_h\u2081 = ZsR_treated[interval_h\u2081]\n\n    N_h\u2081_untreated = nobs(ZsR_untreated_h\u2081)\n    N_h\u2081_treated = nobs(ZsR_treated_h\u2081)\n\n    Y\u0304_h\u2081_untreated = mean(ZsR_untreated_h\u2081.Ys)\n    sd_Y_h\u2081_untreated = Statistics.std(ZsR_untreated_h\u2081.Ys)\n    Y\u0304_h\u2081_treated = mean(ZsR_treated_h\u2081.Ys)\n    sd_Y_h\u2081_treated = Statistics.std(ZsR_treated_h\u2081.Ys)\n\n    f\u0302\u2080 = (N_h\u2081_untreated + N_h\u2081_treated) / 2 / N / h\u2081\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\u0302\u2080_triple_prime = 6 * coef(global_cubic_lm)[5]\n\n    h\u2082_untreated = 3.56 * (sd_Y_h\u2081_untreated^2 / f\u0302\u2080 / m\u0302\u2080_triple_prime^2)^(1 / 7) * N_untreated^(-1 / 7)\n    h\u2082_treated =\n        3.56 * (sd_Y_h\u2081_treated^2 / f\u0302\u2080 / m\u0302\u2080_triple_prime^2)^(1 / 7) * N_treated^(-1 / 7)\n\n\n    ZsR_untreated_h\u2082 = ZsR_untreated[Interval{:closed,:closed}(cutoff-h\u2082_untreated, cutoff+h\u2082_untreated)]\n    ZsR_treated_h\u2082 = ZsR_treated[Interval{:closed,:closed}(cutoff-h\u2082_treated, cutoff+h\u2082_treated)]\n\n    N_h\u2082_untreated = nobs(ZsR_untreated_h\u2082)\n    N_h\u2082_treated = nobs(ZsR_treated_h\u2082)\n\n\n    quadratic_fit_untreated = lm(@formula(Ys ~ 1 + ZsC + ZsC^2), ZsR_untreated_h\u2082)\n    m\u0302\u2080_double_prime_untreated = 2 * last(coef(quadratic_fit_untreated))\n\n    quadratic_fit_treated = lm(@formula(Ys~ 1 + ZsC + ZsC^2), ZsR_treated_h\u2082)\n    m\u0302\u2080_double_prime_treated  = 2 * last(coef(quadratic_fit_treated ))\n\n    # Step 3: Calculation of regularization terms\n\n    r\u0302_untreated = 2160 * sd_Y_h\u2081_untreated^2 / N_h\u2082_untreated/ h\u2082_untreated^4\n    r\u0302_treated = 2160 * sd_Y_h\u2081_treated^2 / N_h\u2082_treated / h\u2082_treated^4\n\n    Ckernel = kernel_constant(ik, kernel)# 3.4375\n\n    regularized_squared_diff =\n        abs2(m\u0302\u2080_double_prime_treated - m\u0302\u2080_double_prime_untreated) + r\u0302_untreated + r\u0302_treated\n    h\u0302_IK =\n        Ckernel *\n        ((sd_Y_h\u2081_untreated^2 + sd_Y_h\u2081_treated^2) / f\u0302\u2080 / regularized_squared_diff)^(1 / 5) *\n        N^(-1 / 5)\n    h\u0302_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": "using BackwardAutodiff\nusing Test: @test, @testset\n\n@testset \"FowardAutodiff.jl tests\" begin\n    @testset \"Basic arithmetic\" begin\n        x = randn()\n        y = randn()\n        z = randn()\n\n        @test isapprox(D(x->2*x)(x), 2)\n    end\n\n    @testset \"Transcendental Functions\" begin\n        x = randn()\n        @test isapprox(D(exp)(x), exp(x))\n        @test isapprox(D(sin)(x), cos(x))\n        @test isapprox(D(cos)(x), -sin(x))\n        @test isapprox(D(tan)(x), sec(x)*sec(x))\n    end\n\n    @testset \"sqrt\" begin\n        x = randn()\n\n        # We need to be in the complex domain explicitly, or sqrt(x < 0) will error out\n        @test isapprox(D(sqrt)(x + 0im), 1/(2*sqrt(x + 0im)))\n    end\n\n    @testset \"compound function bits\" begin\n        x = randn()\n        y = randn()\n        @test isapprox(D(x -> x*y)(x), y)\n        @test isapprox(D(x -> x/y)(x), 1/y)\n        @test isapprox(D(y -> x/y)(y), -x/(y*y))\n        @test isapprox(D(x -> exp(x/y))(x), exp(x/y)/y)\n        @test isapprox(D(x -> sin(x*y))(x), y*cos(x*y))\n        @test isapprox(D(x -> cos(x*y))(x), -y*sin(x*y))\n        @test isapprox(D(x -> x-y)(x), 1)\n        @test isapprox(D(y -> x-y)(y), -1)\n        @test isapprox(D(y -> x*y)(y), x)\n        @test isapprox(D(x -> -x)(x), -1)\n        @test isapprox(D(x -> exp(-x/pi))(x), -exp(-x/pi)/pi)\n        @test isapprox(D(x -> sin(2*pi*sqrt(2)*x))(x), 2*pi*sqrt(2)*cos(2*pi*sqrt(2)*x))\n        @test isapprox(D(x -> exp(-x/pi))(3.0), -exp(-3/pi)/pi)\n        @test isapprox(D(x -> exp(-x)*sin(x))(x), -exp(-x)*sin(x) + exp(-x)*cos(x))\n        @test isapprox(D(x -> exp(-x))(x), -exp(-x))\n        @test isapprox(D(x -> x*x)(x), 2*x)\n    end\n\n    @testset \"compound function\" begin\n        freq = sqrt(2)\n        A = randn()\n        B = randn()\n\n        a = A/sqrt(A*A + B*B)\n        b = B/sqrt(A*A + B*B)\n        phi = atan(b, a)\n\n        x = randn()\n\n        function f(x)\n            return exp(-x/pi)*(b*cos(2*pi*freq*x) + a*sin(2*pi*freq*x))\n        end\n        fprime = D(f)\n\n        function laborious_fprime(x)\n            return exp(-x/pi)*(2*pi*freq*cos(2*pi*freq*x + phi) - sin(2*pi*freq*x + phi)/pi)\n        end\n\n        @test isapprox(fprime(x), laborious_fprime(x))\n    end\n\n    @testset \"partials of simple function\" begin\n        function linear(x, m, b)\n            return m*x+b\n        end\n        dldx = D(1, linear)\n        dldslope = D(2, linear)\n        dldintercept = D(3, linear)\n\n        x = randn()\n        m = randn()\n        b = randn()\n        @test isapprox(dldx(x,m,b), m)\n        @test isapprox(dldslope(x,m,b), x)\n        @test isapprox(dldintercept(x,m,b), 1)\n    end\n\n    @testset \"gradient of many-arg and vector function\" begin\n        function linear(x, m, b)\n            m*x + b\n        end\n\n        function vlinear(xmb)\n            linear(xmb...)\n        end\n\n        g = D(linear)\n        vg = D(vlinear)\n\n        x = randn()\n        m = randn()\n        b = randn()\n\n        @test isapprox(g(x, m, b), [m, x, 1])\n        @test isapprox(vg([x,m,b]), [m, x, 1])\n    end\n\n    @testset \"multivariate polynomial\" begin\n        coeffs = randn(5)\n        function p(x,y,z)\n            coeffs[1] + x*(coeffs[2] + y*(coeffs[3] + z*(coeffs[4] + x*coeffs[5])))\n        end\n\n        function gp(x,y,z)\n            [coeffs[2] + y*(coeffs[3] + z*(coeffs[4] + x*coeffs[5])) + x*y*z*coeffs[5],\n             x*(coeffs[3] + z*(coeffs[4] + x*coeffs[5])),\n             x*y*(coeffs[4] + x*coeffs[5])]\n         end\n\n         x,y,z = randn(3)\n\n         @test isapprox(D(p)(x,y,z), gp(x,y,z))\n    end\n\n    @testset \"log derivative\" begin\n        x = rand()\n        @test isapprox(D(log)(x), 1/x)\n\n        @test isapprox(D(x -> log(exp(x)))(x), 1.0)\n    end\nend\n", "meta": {"hexsha": "57ff2cf5850331c1379f498c0b1f0f64f4207630", "size": 3696, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Farr-PHY-604/BackwardAutodiff.jl", "max_stars_repo_head_hexsha": "011fa3eb35d180dcad205921a5fe1abfc061383a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:38:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T00:38:28.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "Farr-PHY-604/BackwardAutodiff.jl", "max_issues_repo_head_hexsha": "011fa3eb35d180dcad205921a5fe1abfc061383a", "max_issues_repo_licenses": ["MIT"], "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": "Farr-PHY-604/BackwardAutodiff.jl", "max_forks_repo_head_hexsha": "011fa3eb35d180dcad205921a5fe1abfc061383a", "max_forks_repo_licenses": ["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": 92, "alphanum_fraction": 0.4807900433, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7520891873127892}}
{"text": "using FractionalDiffEq\nusing Test\nusing MittagLeffler\n\n\n@testset \"Test Diethelm PECE algorithms\" begin\n    fun(x, y) = 1-y\n    prob=FDEProblem(fun, 1.8, 0, 5, 0.01)\n    result=solve(prob, PECE())\n    tspan=collect(0:0.01:5)\n\n    target = []\n\n    for i in 0:0.01:5\n        push!(target, i^1.8*mittleff(1.8, 2.8,-i^1.8))\n    end\n\n    @test isapprox(result, target; atol=1)\nend", "meta": {"hexsha": "8b115100fdfead0de5d2224a3702d7ef8c3bdd7a", "size": 374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test.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": "test/test.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": "test/test.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": 19.6842105263, "max_line_length": 54, "alphanum_fraction": 0.6229946524, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7520891839609971}}
{"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 = \u03c3*(y-x)\n  dy = x*(\u03c1-z) - y\n  dz = x*y - \u03b2*z\nend \u03c3 \u03c1 \u03b2\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# \u2554\u2550\u2561 9d996162-d41c-11ea-09b4-994ed99dd014\n\n\n# \u2554\u2550\u2561 9d3661fc-d41c-11ea-1997-175b6d9a4095\n\n\n# \u2554\u2550\u2561 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\u00edstica com Pluto.jl\n\t\n\tVamos explorar um pouco as distribui\u00e7\u00f5es e fun\u00e7\u00f5es estat\u00edsticas no Julia. A primeira coisa a notar \u00e9 que o Julia b\u00e1sico cont\u00e9m o [pacote](https://docs.julialang.org/en/v1/stdlib/Statistics/) `Statistics`, com opera\u00e7\u00f5es bem simples como `mean()` e `cov()`, e o [pacote](https://docs.julialang.org/en/v1/stdlib/Random/) `Random`, para a gera\u00e7\u00e3o de n\u00fameros (pseudo)aleat\u00f3rios. No entanto, h\u00e1 todo um ambiente de computa\u00e7\u00e3o estat\u00edstica em desenvolvimento para a linguagem. Vamos utilizar o [meta-pacote](https://github.com/JuliaStats/StatsKit.jl) `StatsKit` que importa alguns dos principais pacotes estat\u00edsticos.\n\t\n\tInicialmente, vamos explorar algumas fun\u00e7\u00f5es e visualiza\u00e7\u00f5es de interesse para a Estat\u00edstica por meio das distribuic\u00f5es univariadas do pacote [Distributions](https://juliastats.org/Distributions.jl/stable/univariate/).\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 61be6a20-d41c-11ea-0eee-654e9ec43f39\nbegin\n\tmd\"\"\"\n\tVamos brincar um pouco com uma distribui\u00e7\u00e3o Normal na qual escolheremos os par\u00e2metros \u03bc e \u03c3\u00b2, comparando o seu gr\u00e1fico com o da Normal Padr\u00e3o.\n\t\n\t**Selecione o par\u00e2metro \u03bc da Normal**:\n\t\n\t$(@bind \u03bc Slider(-50.0:0.1:50.0, 0)) \n\t\n\t**Selecione o par\u00e2metro \u03c3\u00b2 da Normal**:\n\t\n\t$(@bind \u03c3\u00b2 Slider(1:0.01:50.0))\n\t\n\tAcima podemos conferir o resultado, em que a Normal Padr\u00e3o est\u00e1 em azul escuro e a nossa Normal est\u00e1 em vermelho. Note que o valor inicial de \u03bc \u00e9 `0` e o \u03c3\u00b2 \u00e9 `1`, logo as curvas est\u00e3o sobrepostas.\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 517a652c-d41c-11ea-2118-fdbf45828452\nmd\"\"\"### Distribui\u00e7\u00e3o Normal\n**Valor de \u03bc**: $\u03bc\n\n**Valor de \u03c3\u00b2**: $\u03c3\u00b2\n\"\"\"\n\n# \u2554\u2550\u2561 57bc858e-d41c-11ea-392b-f1c840845820\n#Visualiza\u00e7\u00e3o das distribui\u00e7\u00f5es\nbegin\n\tPlots.plot(Normal(\u03bc, \u03c3\u00b2), 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# \u2554\u2550\u2561 664c20be-d41c-11ea-1467-e1c670479af6\nbegin\n\t\n\tx = rand(Normal(\u03bc, \u03c3\u00b2), 100)\n\t\n\tmd\"\"\"\n\tVamos agora gerar uma amostra aleat\u00f3ria de tamanho 100 da distribui\u00e7\u00e3o da nossa Normal(\u03bc, \u03c3\u00b2) usando o pacote `Random`. O comando est\u00e1 abaixo.\n\t\n\t\n\t\n\t\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 acc667f8-d59c-11ea-0805-41b21640540b\nbegin\n\tmd\"\"\"\n\tAgora vejamos a distribui\u00e7\u00e3o LogNormal.\n\t\n\t**Selecione o par\u00e2metro \u03bc\u2097 da LogNormal**:\n\t\n\t$(@bind \u03bc\u2097 Slider(0.0:0.1:25.0)) \n\t\n\t**Selecione o par\u00e2metro \u03c3\u00b2\u2097 da LogNormal**:\n\t\n\t$(@bind \u03c3\u00b2\u2097 Slider(0.01:0.01:5.0))\n\t\n\tNote que o valor inicial de \u03bc\u2097 \u00e9 `1.0` e o \u03c3\u00b2\u2097 \u00e9 `0.01`.\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 a3dc9324-d59c-11ea-3787-39b6dc720a4b\nmd\"\"\"### Distribui\u00e7\u00e3o LogNormal\n**Valor de \u03bc\u2097**: $\u03bc\u2097\n\n**Valor de \u03c3\u00b2\u2097**: $\u03c3\u00b2\u2097\n\"\"\"\n\n# \u2554\u2550\u2561 a651c700-d59c-11ea-029c-1d55b204a41c\n#Visualiza\u00e7\u00e3o da distribui\u00e7\u00e3o\nPlots.plot(LogNormal(\u03bc\u2097, sqrt(\u03c3\u00b2\u2097)), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# \u2554\u2550\u2561 6ebf2016-d41c-11ea-1a8d-6566e98d1f34\nbegin\n\tmd\"\"\"\n\tAgora vejamos a distribui\u00e7\u00e3o Gamma e o seu formato de acordo com os par\u00e2metros k e \u03b8, onde \u03b8 \u00e9 o par\u00e2metro de escala. Note que nesta parametriza\u00e7\u00e3o, temos que a fun\u00e7\u00e3o de densidade \u00e9 dada por\n\t\n\t\\begin{equation}\n\tf(x| k, \\theta) = \\frac{x^{k-1} e^{-x/\u03b8}}{\\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\u00e2metro k da Gamma**:\n\t\n\t$(@bind k Slider(1.0:0.1:25.0)) \n\t\n\t**Selecione o par\u00e2metro \u03b8 da Gamma**:\n\t\n\t$(@bind \u03b8 Slider(0.1:0.1:25.0))\n\t\n\tNovamente podemos conferir o resultado. Note que o valor inicial de k \u00e9 `1.0` e o \u03b8 \u00e9 `0.1`.\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 6a7b3bf2-d41c-11ea-014e-8b94632190ff\nmd\"\"\"### Distribui\u00e7\u00e3o Gamma\n**Valor de k**: $k\n\n**Valor de \u03b8**: $\u03b8\n\"\"\"\n\n# \u2554\u2550\u2561 6e2923fe-d41c-11ea-03d2-0956b986677c\n#Visualiza\u00e7\u00e3o da distribui\u00e7\u00e3o\nPlots.plot(Gamma(k, \u03b8), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# \u2554\u2550\u2561 801c622e-d41c-11ea-0441-e300c24904ae\nbegin\n\tmd\"\"\"\n\tAgora a distribui\u00e7\u00e3o mais vers\u00e1til de todas: a distribui\u00e7\u00e3o Beta e o seu formato de acordo com os par\u00e2metros \u03b1 e \u03b2. \n\t\n\t**Selecione o par\u00e2metro \u03b1 da Beta**:\n\t\n\t$(@bind \u03b1 Slider(0.1:0.1:10.0)) \n\t\n\t**Selecione o par\u00e2metro \u03b2 da Beta**:\n\t\n\t$(@bind \u03b2 Slider(0.1:0.1:10.0))\n\t\n\tOs valores iniciais de \u03b1 e de \u0392 s\u00e3o ambos `0.1`.\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 6f79fbca-d41c-11ea-0c49-3ffd9d1d5ab2\nmd\"\"\"### Distribui\u00e7\u00e3o Beta\n**Valor de \u03b1**: $\u03b1\n\n**Valor de \u03b2**: $\u03b2\n\"\"\"\n\n# \u2554\u2550\u2561 80571608-d41c-11ea-2e72-b7f20192a991\n#Visualiza\u00e7\u00e3o da distribui\u00e7\u00e3o\nPlots.plot(Beta(\u03b1, \u03b2), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# \u2554\u2550\u2561 70188128-d41c-11ea-1e8f-5371e257a3bf\nbegin\n\tmd\"\"\"\n\tVemos agora a distribui\u00e7\u00e3o que ningu\u00e9m se lembra como \u00e9 a fun\u00e7\u00e3o de densidade: a distribui\u00e7\u00e3o \u03a7\u00b2 e o seu formato de acordo com o par\u00e2metro \u03bd de graus de liberdade.\n\t\n\t**Selecione o par\u00e2metro \u03bd da Chi-Quadrado**:\n\t\n\t$(@bind \u03bd Slider(1:50)) \n\t\n\tO valor inicial de \u03bd \u00e9 `1` e s\u00f3 assume valores inteiros positivos.\n\t\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 7fd8c4ce-d41c-11ea-0790-f7afc7a1a84d\n#Verificando o valor do par\u00e2metro\nmd\"\"\"\n### Distribui\u00e7\u00e3o Chi-Quadrado\n**Valor de \u03bd**: $\u03bd\n\"\"\"\n\n# \u2554\u2550\u2561 7f661988-d41c-11ea-3167-753a433c34e3\n#Visualiza\u00e7\u00e3o da distribui\u00e7\u00e3o\nPlots.plot(Chisq(\u03bd), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# \u2554\u2550\u2561 9dcde59a-d41c-11ea-36ec-db54e9680172\nbegin\n\tmd\"\"\"\n\tComo **com certeza** algu\u00e9m disse na anterior que sabe sim a forma da fun\u00e7\u00e3o de densidade da \u03a7\u00b2, ent\u00e3o agora sim a distribui\u00e7\u00e3o cuja fun\u00e7\u00e3o de densidade que **ningu\u00e9m** se lembra. Algum desafiante?\n\t\n\t**Selecione o par\u00e2metro d\u2081 da F-Snedecor**:\n\t\n\t$(@bind d\u2081 Slider(1:50)) \n\t\n\t**Selecione o par\u00e2metro d\u2082 da F-Snedecor**:\n\t\n\t$(@bind d\u2082 Slider(1:50)) \n\t\n\tOs valores iniciais de d\u2081 e d\u2082 s\u00e3o ambos `1`, e s\u00f3 assumem valores inteiros positivos.\n\t\"\"\"\nend\n\n# \u2554\u2550\u2561 9bcc9a70-d41c-11ea-3235-0ffa6ccc0bd5\n#Verificando o valor dos par\u00e2metros\nmd\"\"\"\n### Distribui\u00e7\u00e3o F-Snedecor\n**Valor de d\u2081**: $d\u2081\n\n**Valor de d\u2082**: $d\u2082\n\"\"\"\n\n# \u2554\u2550\u2561 9dfe153a-d41c-11ea-2a80-79631819f1ac\n#Visualiza\u00e7\u00e3o da distribui\u00e7\u00e3o\nPlots.plot(FDist(d\u2081, d\u2082), color = :red, lw = 2, legend = false, fill = (0, :red), fillalpha = 0.5)\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550d5eaa180-d41b-11ea-32f6-6ff398c3e4c2\n# \u255f\u2500517a652c-d41c-11ea-2118-fdbf45828452\n# \u255f\u250057bc858e-d41c-11ea-392b-f1c840845820\n# \u255f\u250061be6a20-d41c-11ea-0eee-654e9ec43f39\n# \u255f\u2500664c20be-d41c-11ea-1467-e1c670479af6\n# \u255f\u2500a3dc9324-d59c-11ea-3787-39b6dc720a4b\n# \u255f\u2500a651c700-d59c-11ea-029c-1d55b204a41c\n# \u255f\u2500acc667f8-d59c-11ea-0805-41b21640540b\n# \u255f\u25006a7b3bf2-d41c-11ea-014e-8b94632190ff\n# \u255f\u25006e2923fe-d41c-11ea-03d2-0956b986677c\n# \u255f\u25006ebf2016-d41c-11ea-1a8d-6566e98d1f34\n# \u255f\u25006f79fbca-d41c-11ea-0c49-3ffd9d1d5ab2\n# \u255f\u250080571608-d41c-11ea-2e72-b7f20192a991\n# \u255f\u2500801c622e-d41c-11ea-0441-e300c24904ae\n# \u255f\u25007fd8c4ce-d41c-11ea-0790-f7afc7a1a84d\n# \u2560\u25507f661988-d41c-11ea-3167-753a433c34e3\n# \u255f\u250070188128-d41c-11ea-1e8f-5371e257a3bf\n# \u255f\u25009bcc9a70-d41c-11ea-3235-0ffa6ccc0bd5\n# \u255f\u25009dfe153a-d41c-11ea-2a80-79631819f1ac\n# \u255f\u25009dcde59a-d41c-11ea-36ec-db54e9680172\n# \u2560\u25509d996162-d41c-11ea-09b4-994ed99dd014\n# \u2560\u25509d3661fc-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": "\n@block PietroVertechi [statsmakie] begin\n    @cell \"StatsMakie\" [Group, Style, scatter, plot, wireframe, statistics] begin\n        using StatsMakie\n        using DataFrames, RDatasets\n        using StatsMakie: linear, smooth\n        N = 1000\n        a = rand(1:2, N) # a discrete variable\n        b = rand(1:2, N) # a discrete variable\n        x = randn(N) # a continuous variable\n        y = @. x * a + 0.8*randn() # a continuous variable\n        z = x .+ y # a continuous variable\n        @substep\n\n        scatter(x, y, markersize = 0.2)\n        @substep\n\n        scatter(Group(a), x, y, markersize = 0.2)\n        @substep\n\n        scatter(Group(a), x, y, color = [:black, :red], markersize = 0.2)\n        @substep\n\n        scatter(Group(marker = a), x, y, markersize = 0.2)\n        @substep\n\n        scatter(Group(marker = a, color = b), x, y, markersize = 0.2)\n        @substep\n\n        scatter(Group(marker = a), Style(color = z), x, y)\n        @substep\n\n        scatter(Group(color = a), x, y, Style(markersize = z ./ 10))\n        @substep\n\n        plot(linear, x, y)\n        @substep\n\n        plot(linear, Group(a), x, y)\n        @substep\n\n        scatter(Group(a), x, y, markersize = 0.2)\n        plot!(linear, Group(a), x, y)\n        @substep\n\n        plot(linear, Group(linestyle = a), x, y)\n        @substep\n\n        N = 200\n        x = 10 .* rand(N)\n        a = rand(1:2, N)\n        y = sin.(x) .+ 0.5 .* rand(N) .+ cos.(x) .* a\n        @substep\n\n        scatter(Group(a), x, y)\n        plot!(smooth, Group(a), x, y)\n        @substep\n\n        plot(histogram, y)\n        @substep\n\n        plot(histogram, x, y)\n        @substep\n\n        plot(histogram(nbins = 30), x, y)\n        @substep\n\n        wireframe(histogram(nbins = 30), x, y)\n        @substep\n\n        iris = RDatasets.dataset(\"datasets\", \"iris\")\n        scatter(Data(iris), Group(:Species), :SepalLength, :SepalWidth)\n        @substep\n        # use Position.stack to signal that you want bars stacked vertically rather than superimposed\n        plot(Position.stack, histogram, Data(iris), Group(:Species), :SepalLength)\n        @substep\n\n        wireframe(\n            density(trim=true),\n            Data(iris), Group(:Species), :SepalLength, :SepalWidth,\n            transparency = true, linewidth = 0.1\n        )\n        @substep\n\n        scatter(\n            Data(iris),\n            Group(marker = :Species, color = bycolumn),\n            :SepalLength, (:PetalLength, :PetalWidth)\n        )\n        @substep\n\n        barplot([\"hi\", \"ima\", \"string\"], rand(3))\n        @substep\n\n    end\n\n    @cell \"Analysis\"  [Group, Style, scatter, plot, wireframe, statistics] begin\n\n        ## setup\n\n        using StatsMakie\n        using DataFrames, RDatasets # for data\n        using StatsMakie: smooth, linear\n\n        mtcars = dataset(\"datasets\", \"mtcars\")    # load dataset of car statistics\n        iris = dataset(\"datasets\", \"iris\")\n\n        disallowmissing!.([mtcars, iris])  # convert columns from Union{T, Missing} to T\n        # We can use this because the dataset has no missing values.\n\n        @substep\n\n        # kde\n\n        plot(\n            density,           # the type of analysis\n            Data(mtcars),\n            :MPG,\n            Group(color = :Cyl)\n        )\n\n        @substep\n\n        # histogram\n\n        plot(\n            histogram,         # the type of analysis\n            Data(mtcars),\n            :MPG,\n            Group(color = :Cyl)\n        )\n\n        @substep\n\n        # frequency analysis\n\n        using Distributions\n        d = rand(Poisson(), 1000)\n        plot(frequency, d)\n\n        @substep\n\n        xs = 10 .* rand(100)\n        ys = sin.(xs) .+ 0.5 .* rand.()\n        scatter(xs, ys)\n        plot!(smooth, xs, ys)\n\n        @substep\n\n        scatter(xs, ys)\n        plot!(linear, xs, ys)\n    end\n\n    @cell \"Box plot\" [boxplot, statistics] begin\n\n        using RDatasets, StatsMakie\n\n        d = dataset(\"Ecdat\",\"Fatality\")\n        boxplot(Data(d), :Year, :Perinc)\n\n    end\n\n    @cell \"Violin plot\" [violin, statistics] begin\n\n        using RDatasets, StatsMakie\n\n        d = dataset(\"Ecdat\", \"Fatality\");\n\n        violin(Data(d), :Year, :Perinc)\n\n    end\n\n    @cell \"Violin and box plot\" [boxplot, violin, statistics] begin\n\n        using RDatasets, StatsMakie\n\n        d = dataset(\"Ecdat\",\"Fatality\");\n\n        violin(d.Year, d.Perinc, color = :gray)\n        boxplot!(d.Year, d.Perinc, color = :black)\n\n    end\n\n    @cell \"Errorbar\" [errorbar] begin\n        using StatsMakie\n        x = [1:4;]\n        y =  [1:4;]\n        \u0394x = fill(0.25, 4)\n        \u0394y = fill(0.25, 4)\n        p = errorbar(x,y,\u0394x,\u0394y,xcolor=:green, ycolor=:red)\n    end\nend\n", "meta": {"hexsha": "c5792eda0fa6f46026e8c72550285ae14b0ef00c", "size": 4651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/statsmakie.jl", "max_stars_repo_name": "Akshat-mehrotra/MakieGallery.jl", "max_stars_repo_head_hexsha": "b4c4b6829498f91c3f1fc07606b019e7831f838e", "max_stars_repo_licenses": ["MIT"], "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/statsmakie.jl", "max_issues_repo_name": "Akshat-mehrotra/MakieGallery.jl", "max_issues_repo_head_hexsha": "b4c4b6829498f91c3f1fc07606b019e7831f838e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2020-03-25T01:00:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-25T01:32:14.000Z", "max_forks_repo_path": "examples/statsmakie.jl", "max_forks_repo_name": "Akshat-mehrotra/MakieGallery.jl", "max_forks_repo_head_hexsha": "b4c4b6829498f91c3f1fc07606b019e7831f838e", "max_forks_repo_licenses": ["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.0984455959, "max_line_length": 101, "alphanum_fraction": 0.5213932488, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7520107718739285}}
{"text": "# indicator of a generic box\n\n\"\"\"\n  IndBox(lb, ub)\n\nReturns the function `g = ind{x : lb \u2a7d x \u2a7d 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)) \u2a7d r}` for `r \u2a7e 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 \u21a6 0 if all(lb \u2a7d x \u2a7d ub), +\u221e 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": "# ---\n# title: 478. Generate Random Point in a Circle\n# id: problem478\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math, Random, Rejection Sampling\n# link: <https://leetcode.com/problems/generate-random-point-in-a-circle/description/>\n# hidden: true\n# ---\n# \n# Given the radius and x-y positions of the center of a circle, write a function\n# `randPoint` which generates a uniform random point in the circle.\n# \n# Note:\n# \n#   1. input and output values are in [floating-point](https://www.webopedia.com/TERM/F/floating_point_number.html).\n#   2. radius and x-y position of the center of the circle is passed into the class constructor.\n#   3. a point on the circumference of the circle is considered to be in the circle.\n#   4. `randPoint` returns a size 2 array containing x-position and y-position of the random point, in that order.\n# \n# **Example 1:**\n# \n#     \n#     \n#     Input: [\"Solution\",\"randPoint\",\"randPoint\",\"randPoint\"]\n#     [[1,0,0],[],[],[]]\n#     Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]\n#     \n# \n# **Example 2:**\n# \n#     \n#     \n#     Input: [\"Solution\",\"randPoint\",\"randPoint\",\"randPoint\"]\n#     [[10,5,-7.5],[],[],[]]\n#     Output: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]\n# \n# **Explanation of Input Syntax:**\n# \n# The input is two lists: the subroutines called and their arguments.\n# `Solution`'s constructor has three arguments, the radius, x-position of the\n# center, and y-position of the center of the circle. `randPoint` has no\n# arguments. Arguments are always wrapped with a list, even if there aren't any.\n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "8afaa597e95fecf383ebb3caa606ef2f368c5fa0", "size": 1709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/478.generate-random-point-in-a-circle.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/478.generate-random-point-in-a-circle.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/478.generate-random-point-in-a-circle.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": 32.8653846154, "max_line_length": 116, "alphanum_fraction": 0.6647162083, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7520107618577141}}
{"text": "emp_var = empirical_var(measures-states,n,k)\nepsilon = 5*r/\u221a(n*k)\n@test abs(emp_var-r) < epsilon ", "meta": {"hexsha": "915f98abee0bb9a34e831a2c16bb06c326f7b048", "size": 97, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/observer_test.jl", "max_stars_repo_name": "mlelarge/KalmanAD.jl", "max_stars_repo_head_hexsha": "234a9bb477f7552c22856d66aa5b23b08cc41646", "max_stars_repo_licenses": ["MIT"], "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/observer_test.jl", "max_issues_repo_name": "mlelarge/KalmanAD.jl", "max_issues_repo_head_hexsha": "234a9bb477f7552c22856d66aa5b23b08cc41646", "max_issues_repo_licenses": ["MIT"], "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/observer_test.jl", "max_forks_repo_name": "mlelarge/KalmanAD.jl", "max_forks_repo_head_hexsha": "234a9bb477f7552c22856d66aa5b23b08cc41646", "max_forks_repo_licenses": ["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": 44, "alphanum_fraction": 0.7113402062, "num_tokens": 32, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7520019140863263}}
{"text": "module TestIsevenperm\n\nusing ConicHulls.Common.isevenperm, ConicHulls.Dets.det\n\nfor n=1:5\n    eyerows = [int(1:n .== k) for k=1:n]\n    for p in permutations(1:n)\n        even = isevenperm(p)\n        d = det(eyerows[p]...)\n        @assert even ? d == 1 : d == -1\n    end\nend\n\nend # module\n", "meta": {"hexsha": "902499a6fb908d7cc006b770724b6b1e6a77cddf", "size": 288, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_isevenperm.jl", "max_stars_repo_name": "toivoh/ConicHulls.jl", "max_stars_repo_head_hexsha": "38015f1cdfa2f5d1ad18db1629f08048dfd7ace7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-04-04T11:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-04T11:56:43.000Z", "max_issues_repo_path": "test/test_isevenperm.jl", "max_issues_repo_name": "toivoh/ConicHulls.jl", "max_issues_repo_head_hexsha": "38015f1cdfa2f5d1ad18db1629f08048dfd7ace7", "max_issues_repo_licenses": ["MIT"], "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_isevenperm.jl", "max_forks_repo_name": "toivoh/ConicHulls.jl", "max_forks_repo_head_hexsha": "38015f1cdfa2f5d1ad18db1629f08048dfd7ace7", "max_forks_repo_licenses": ["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.2, "max_line_length": 55, "alphanum_fraction": 0.5868055556, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.80563219364797, "lm_q1q2_score": 0.7520019089244806}}
{"text": "### A Pluto.jl notebook ###\n# v0.18.4\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8dc3dee2-a7d2-4afd-94b1-63154910a54c\nt = 0:0.1:5\n\n# \u2554\u2550\u2561 4c8163a1-1206-47dc-bc58-1d642663a22e\nfunction model(t,p)\n\treturn p[1] .* exp.(-t/p[2])\nend\n\n# \u2554\u2550\u2561 38284326-0524-43cd-8fbe-3d228aac9bf4\nbegin\n\tdata_err = 0.5\n\td = di.Normal(0,data_err)\nend\n\n# \u2554\u2550\u2561 a0add249-405b-4f30-a667-c791d155d5ca\nampl_range = 2:0.1:5\n\n# \u2554\u2550\u2561 c5f1d281-fc40-4fdb-ae25-664ff7c99332\ndecay_range = 1:0.1:3\n\n# \u2554\u2550\u2561 2288748b-9ae9-4032-a371-b2de8712cd88\ny = 3.0 .* exp.(-t/2.0) + rand(d,length(t))\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8948ee55-fa92-4ac5-9836-ff2640a541db\nfit = curve_fit(model, t, y, [1.0,1.0])\n\n# \u2554\u2550\u2561 eb879e89-7277-4804-952b-19048874ced5\nfit.param\n\n# \u2554\u2550\u2561 3a803151-2291-4798-b1f4-15e6bd1189fb\ncov = estimate_covar(fit)\n\n# \u2554\u2550\u2561 7cbfb55e-8984-4bee-9848-dcaacdfb1282\nconf = confidence_interval(fit, 0.1)\n\n# \u2554\u2550\u2561 bf29e446-1cd4-4c2d-8f1f-0b91f39aa450\nexp_dist = di.MvNormal(fit.param,cov)\n\n# \u2554\u2550\u2561 3449f76f-9dbe-4c07-898e-5b944174b374\nfunction f(x,y)\n\treturn di.pdf(exp_dist,[x,y])\nend\n\n# \u2554\u2550\u2561 d977a512-3085-4a87-a95d-7d3041402e0a\ncontourf(ampl_range,decay_range,f)\n\n# \u2554\u2550\u2561 fc76af35-ac05-418a-993d-a382c41b036f\nbegin\n\tmy_normal = di.Normal(1,2)\n\tmy_sample = rand(my_normal,200)\nend\n\n# \u2554\u2550\u2561 2dacbdf4-dbf2-42c9-9529-007fff009c12\nmean(my_sample)\n\n# \u2554\u2550\u2561 1d360be7-43a1-4a75-8d09-e229917ff815\nstd(my_sample)\n\n# \u2554\u2550\u2561 923e8ca4-8f66-47b8-a2b1-b7b384416163\n@model function my_fit(data)\n\t\u03bc ~ Uniform(-10,10)\n\t\u03c3 ~ Uniform(0,20)\n\tfor i in 1:length(data)\n\t\tdata[i] ~ Normal(\u03bc,\u03c3)\n\tend\nend\n\n# \u2554\u2550\u2561 b2c73bae-7a71-49b6-8ea0-3c57dd7843ae\nmodel1 = my_fit(my_sample)\n\n# \u2554\u2550\u2561 46e1c786-6abc-4f82-a1a8-04e0394aa005\nchain = sample(model1,NUTS(0.65),1000)\n\n# \u2554\u2550\u2561 39dc3dae-105b-490c-a5af-b8cfdc059bc0\nStatsPlots.plot(chain)\n\n# \u2554\u2550\u2561 7241b49c-b5d9-438a-950a-8ffcfa3d301b\ndescribe(chain)\n\n# \u2554\u2550\u2561 c17062e7-42dc-4b49-8b54-2a61adf6396b\nx = 0:10\n\n# \u2554\u2550\u2561 fee857c0-cbb4-4a49-ab9e-59c58b92cb63\nfunction lin_model(x,p)\n\treturn p[1] .+ (p[2] .* x)\nend\n\n# \u2554\u2550\u2561 7bb4d1f9-bfa7-4aef-b88e-96cb6bef96ee\nfunction quad_model(x,p)\n\treturn p[1] .+ (p[2] .* x) .+ (p[3] .* x .^ 2)\nend\n\n# \u2554\u2550\u2561 974540df-328a-4855-a954-028c19f1ea56\nbegin\n\tdlin_error = 2.0\n\tdlin = di.Normal(0,dlin_error)\nend\n\n# \u2554\u2550\u2561 029632a7-e923-448b-86b9-21e5c9c6acd6\nyy = 2.0 .+ (3.0 .* x) .+ 0.1 .* x .^ 2 .+ rand(dlin,length(x))\n\n# \u2554\u2550\u2561 a56ca084-6366-4148-b600-56f797d3927e\nfit_lin = curve_fit(lin_model,x,yy,[2.0,3.0])\n\n# \u2554\u2550\u2561 57f154a5-d32c-47f0-9dec-a136b3fd44a7\nfit_lin.param\n\n# \u2554\u2550\u2561 89f26e4b-f10e-47e2-a032-b3848ec618f2\nyy_fit = fit_lin.param[1] .+ fit_lin.param[2] .* x\n\n# \u2554\u2550\u2561 07174e20-8292-441b-ae92-51800f641e64\nyy_quadfit = curve_fit(quad_model, x,yy,[3.0,2.0,0.0])\n\n# \u2554\u2550\u2561 4b4cf4ee-27b8-4d25-a926-0c4e311c980f\nyy_quadfit.param\n\n# \u2554\u2550\u2561 08e5fe39-a598-4f06-9c5c-aa8e7ac3c4b9\nyy_quad = yy_quadfit.param[1] .+ (yy_quadfit.param[2] .* x) .+ (yy_quadfit.param[3] .* x .^ 2)\n\n# \u2554\u2550\u2561 89a7fbc5-ea56-4e8d-b50d-63456484dca0\ncov_quad = estimate_covar(yy_quadfit)\n\n# \u2554\u2550\u2561 461b0327-1278-4c99-90f9-b8c1b6e1a5c6\ndelta_quad = sqrt(cov_quad[3,3])\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0246ae6c-974f-4e4e-a16f-6dce6a0cddfa\nchi_quad = sum(yy_quadfit.resid .^ 2 /dlin_error^2)\n\n# \u2554\u2550\u2561 838f4345-c865-4712-8d39-b52777ab986d\nchi_lin = sum(fit_lin.resid .^ 2 /dlin_error^2)\n\n# \u2554\u2550\u2561 44503a57-a47c-46dd-9882-c97c568b4bc7\nexp(-chi_lin)/exp(-chi_quad)*1.0/sqrt(cov_quad[3,3])/sqrt(2*\u03c0)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550ae47661e-95a2-11ec-119b-8194fe27f96e\n# \u2560\u25508dc3dee2-a7d2-4afd-94b1-63154910a54c\n# \u2560\u25504c8163a1-1206-47dc-bc58-1d642663a22e\n# \u2560\u255038284326-0524-43cd-8fbe-3d228aac9bf4\n# \u2560\u25507abe92c4-3081-429d-88b0-fd1d367fb3df\n# \u2560\u25508948ee55-fa92-4ac5-9836-ff2640a541db\n# \u2560\u2550eb879e89-7277-4804-952b-19048874ced5\n# \u2560\u25503a803151-2291-4798-b1f4-15e6bd1189fb\n# \u2560\u25507cbfb55e-8984-4bee-9848-dcaacdfb1282\n# \u2560\u2550bf29e446-1cd4-4c2d-8f1f-0b91f39aa450\n# \u2560\u2550a0add249-405b-4f30-a667-c791d155d5ca\n# \u2560\u2550c5f1d281-fc40-4fdb-ae25-664ff7c99332\n# \u2560\u25503449f76f-9dbe-4c07-898e-5b944174b374\n# \u2560\u2550d977a512-3085-4a87-a95d-7d3041402e0a\n# \u2560\u25502288748b-9ae9-4032-a371-b2de8712cd88\n# \u2560\u2550fc76af35-ac05-418a-993d-a382c41b036f\n# \u2560\u25502dacbdf4-dbf2-42c9-9529-007fff009c12\n# \u2560\u25501d360be7-43a1-4a75-8d09-e229917ff815\n# \u2560\u2550923e8ca4-8f66-47b8-a2b1-b7b384416163\n# \u2560\u2550b2c73bae-7a71-49b6-8ea0-3c57dd7843ae\n# \u2560\u255046e1c786-6abc-4f82-a1a8-04e0394aa005\n# \u2560\u255039dc3dae-105b-490c-a5af-b8cfdc059bc0\n# \u2560\u25507241b49c-b5d9-438a-950a-8ffcfa3d301b\n# \u2560\u2550c17062e7-42dc-4b49-8b54-2a61adf6396b\n# \u2560\u2550029632a7-e923-448b-86b9-21e5c9c6acd6\n# \u2560\u2550afb2e5ef-3d4c-439a-8574-443a09eb850d\n# \u2560\u2550fee857c0-cbb4-4a49-ab9e-59c58b92cb63\n# \u2560\u2550a56ca084-6366-4148-b600-56f797d3927e\n# \u2560\u255057f154a5-d32c-47f0-9dec-a136b3fd44a7\n# \u2560\u255089f26e4b-f10e-47e2-a032-b3848ec618f2\n# \u2560\u25507bb4d1f9-bfa7-4aef-b88e-96cb6bef96ee\n# \u2560\u255007174e20-8292-441b-ae92-51800f641e64\n# \u2560\u25504b4cf4ee-27b8-4d25-a926-0c4e311c980f\n# \u2560\u255008e5fe39-a598-4f06-9c5c-aa8e7ac3c4b9\n# \u2560\u255089a7fbc5-ea56-4e8d-b50d-63456484dca0\n# \u2560\u2550461b0327-1278-4c99-90f9-b8c1b6e1a5c6\n# \u2560\u25500246ae6c-974f-4e4e-a16f-6dce6a0cddfa\n# \u2560\u2550838f4345-c865-4712-8d39-b52777ab986d\n# \u2560\u255044503a57-a47c-46dd-9882-c97c568b4bc7\n# \u2560\u2550974540df-328a-4855-a954-028c19f1ea56\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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, \u0393)\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- `\u0393`: budget, or the amount of uncertainty, which can be allocated to the second stage costs\n\"\"\"\nfunction initialScenario(c, d, \u0393)\n    calculateDelta(c, d, m) = collect(max(min(d[i], m - c[i]), 0) for i in 1:length(c))\n\n    \u03f5 = 0.001\n    l = 0\n    m = 0\n    r = maximum(map((t) -> sum(t), zip(c, d)))\n\n    \u03b4 = []\n    while abs(l - r) >= \u03f5\n        m = (l + r) / 2.0\n        \u03b4 = calculateDelta(c, d, m)\n        if sum(\u03b4) > \u0393\n            r = m\n        else\n            l = m\n        end\n    end\n\n    \u03b4 = reshape(calculateDelta(c, d, m), size(c))\n    return c + \u03b4\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": "using Cbc, MathProgBase, SimpleGraphs, SimpleGraphAlgorithms, Test\n\nfunction old_max_matching(G::SimpleGraph)\n    m = NE(G)\n    if m == 0\n      T = vertex_type(G)\n      S = Tuple{T,T}\n      return Set{S}()\n    end\n    A = incidence(G,false)\n    c = ones(m)\n\n    X = mixintprog(-c,A,'<',1,:Int,0,1,CbcSolver())\n\n    indices = findall(x->x!=0,round.(Int,X.sol))\n    EE = elist(G)\n    result = Set(EE[indices])\n    # cache_save(G,:max_matching,result)\n    return result\nend\n\nfunction old_max_indep_set(G::SimpleGraph)\n    if NV(G)==0\n      T = vertex_type(G)\n      return Set{T}()\n    end\n    # if cache_check(G,:max_indep_set)\n    #   return cache_recall(G,:max_indep_set)\n    # end\n    n = NV(G)\n    A = incidence(G,false)'\n    c = ones(n)\n\n    X = mixintprog(-c,A,'<',1,:Int,0,1,CbcSolver())\n\n    indices = findall(x->x!=0,round.(Int,X.sol))\n    VV = vlist(G)\n    result = Set(VV[indices])\n    # cache_save(G,:max_indep_set,result)\n    return result\nend\n\n\nfunction old_min_edge_cover(G::SimpleGraph)\n    # if cache_check(G,:min_edge_cover)\n    #   return cache_recall(G,:min_edge_cover)\n    # end\n\n    if NV(G) == 0\n      T = vertex_type(G)\n      S = Tuple{T,T}\n      return Set{S}()\n    end\n\n    if minimum(deg(G))==0\n        error(\"Graph has an isolated vertex; no minimum edge cover exists.\")\n    end\n    m = NE(G)\n    M = incidence(G,false)\n    c = ones(m)\n\n    X = mixintprog(c,M,'>',1,:Int,0,1,CbcSolver())\n\n    indices = findall(x->x!=0,round.(Int,X.sol))\n    EE = elist(G)\n    result = Set(EE[indices])\n    # cache_save(G,:min_edge_cover,result)\n    return result\nend\n\n\nfunction old_min_dom_set(G::SimpleGraph)\n    # if cache_check(G,:min_dom_set)\n    #   return cache_recall(G,:min_dom_set)\n    # end\n    n = NV(G)\n    if n==0\n      T = vertex_type(G)\n      return Set{T}()\n    end\n\n    # A = adjacency(G)+eye(Int,n)\n\n    A = adjacency(G)\n    for j=1:n\n        A[j,j] = 1\n    end\n    c = ones(n)\n\n    X = mixintprog(c,A,'>',1,:Int,0,1,CbcSolver())\n\n    indices = findall(x->x!=0,round.(Int,X.sol))\n    VV = vlist(G)\n    result = Set(VV[indices])\n    # cache_save(G,:min_dom_set,result)\n    return result\nend\n\nfunction func_test(G::SimpleGraph, old_f::Function, new_f::Function)::Bool\n    A = old_f(G)\n    B = new_f(G)\n    return length(A)==length(B)\nend\n\nfunction quad_test(G::SimpleGraph)\n    func_test(G,max_matching,old_max_matching) &&\n    func_test(G,max_indep_set,old_max_indep_set) &&\n    func_test(G,old_min_edge_cover,min_edge_cover) &&\n    func_test(G,old_min_dom_set,min_dom_set)\nend\n\n@test quad_test(BuckyBall())\n@test quad_test(Paley(17))\n@test quad_test(RandomTree(20))\n@test quad_test(RandomRegular(20,3))\n", "meta": {"hexsha": "36ef3c7297118941b0009eea9bb48e07768a71da", "size": 2630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_new.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_stars_repo_head_hexsha": "e84bcc3237478c5a44e280b1d0d6631b61b659fc", "max_stars_repo_licenses": ["MIT"], "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_new.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_issues_repo_head_hexsha": "e84bcc3237478c5a44e280b1d0d6631b61b659fc", "max_issues_repo_licenses": ["MIT"], "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_new.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimpleGraphAlgorithms.jl-41400c72-0c58-5c16-8579-4ecbce768449", "max_forks_repo_head_hexsha": "e84bcc3237478c5a44e280b1d0d6631b61b659fc", "max_forks_repo_licenses": ["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.6724137931, "max_line_length": 76, "alphanum_fraction": 0.6148288973, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7519995913609678}}
{"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    \u03b2max = node.act(output + deviation)\r\n    \u03b2min = node.act(output - deviation)\r\n    return ((\u03b2max + \u03b2min)/2, (\u03b2max - \u03b2min)/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": "@testset \"Poisson 1D\" begin\n\n    alpha = 0.1\n    kx = 0.5\n    xmin, xmax = 0.0, 2\u03c0 / kx\n    nx = 64\n\n    mesh = OneDGrid( xmin, xmax, nx )\n\n    rho = zeros(nx)\n    expected_ex = zeros(nx)\n\n    for i in 1:nx\n        rho[i] = alpha * cos(kx * mesh.x[i])\n        expected_ex[i] = alpha / kx * sin(kx * mesh.x[i])\n    end\n\n    poisson = OneDPoisson( mesh )\n    \n    computed_ex = zero(expected_ex)\n\n    ParticleInCell.compute_e_from_rho!( computed_ex, poisson, rho )\n\n    @show maximum(abs.( computed_ex .- expected_ex ))\n\n    @test computed_ex \u2248 expected_ex\n\n\nend\n", "meta": {"hexsha": "2581587770eaa9bf486b8bf3f06adc2b7fce0b6e", "size": 561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_poisson_1d.jl", "max_stars_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_stars_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-16T04:53:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T17:21:12.000Z", "max_issues_repo_path": "test/test_poisson_1d.jl", "max_issues_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_issues_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_issues_repo_licenses": ["MIT"], "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_poisson_1d.jl", "max_forks_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_forks_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_forks_repo_licenses": ["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.7, "max_line_length": 67, "alphanum_fraction": 0.5846702317, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.751999584093954}}
{"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 \u03bb 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 / \u03bb.^5 / (exp(h*c_0/\u03bb/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\u00e4nge [nm]\",\n        ylabel=\"Intensit\u00e4t [W/m\u00b3]\",\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 Mods\nusing Primes\n\nstruct PrimeGroup <: CyclicGroup \n    G::Mod\n    q::Integer\n    t::Int # security of the group\n    function PrimeGroup(G,q,t)\n        @assert isprime(G.mod)\n        # I could also test by calculating Euler totient\n        new(G,q,t)\n    end\nend\n\nPrimeGroup(g,p,q,t) = PrimeGroup(Mod(g,p),q,t)\nPrimeGroup(val::Integer,G::PrimeGroup) = PrimeGroup(val,G.G.mod,G.q,G.t)\n\nvalue(G::PrimeGroup) = G.G.val\norder(G::PrimeGroup) = G.q\nsecurity(G::PrimeGroup) = G.t\n\nimport Base.*\nfunction *(X::PrimeGroup,Y::PrimeGroup)\n    # Parametrizing group with p and q is not an option as that would recompile the code. \n    qx,qy = order(X), order(Y)\n    px,py = X.G.mod, Y.G.mod\n    \n    if px!=py || qx!=qy\n        error(\"Groups are not equal\")\n    else\n        G = X.G * Y.G\n        return PrimeGroup(G,X.q,X.t)\n    end\nend\n\nimport Base.==\nfunction ==(X::PrimeGroup,Y::PrimeGroup)\n    qx,qy = order(X), order(Y)\n    px,py = X.G.mod, Y.G.mod\n    \n    if px!=py || qx!=qy\n        error(\"Groups are not equal\")\n    else\n        return X.G==Y.G\n    end\nend\n\n### Some prime group generation algorithms. References:\n# + https://crypto.stackexchange.com/questions/820/how-does-one-calculate-a-primitive-root-for-diffie-hellman\n# + https://math.stackexchange.com/questions/124408/finding-a-primitive-root-of-a-prime-number\n\n### I could manage to get 512 security\nfunction SophieGermainGroup(rng::AbstractRNG,g::Integer,t::Int)\n    @assert g!=1\n    while true\n        q = rngprime(rng,2*t)\n        p = 2*q + 1\n        if g!=p-1 && isprime(p)\n            return PrimeGroup(g,p,2*q,t)\n        end\n    end\nend\n\nfunction generateqp(rng::AbstractRNG,t)\n    while true\n        q = rngprime(rng,t)\n        r = rngint(rng,t)\n\n        p = q*r + 1\n        if isprime(p)\n            return q,p\n        end\n    end\nend\n\nfunction DSAStandartGroup(rng::AbstractRNG,tp::Int,tg::Int)\n    q,p = generateqp(rng,2*tp)\n    while true\n        u = Mod(rngint(rng,tg),p)\n        g = u^div((p-1),q)\n        if g.val!=1 || g.val!=0\n            return PrimeGroup(g,q,tp)\n        end\n    end\nend\n", "meta": {"hexsha": "5a8d68042aa3ca856a03d44eb9d0faaa43f99719", "size": 2069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/primegroup.jl", "max_stars_repo_name": "UnofficialJuliaMirror/CryptoGroups.jl-bc997328-bedd-407e-bcd3-5758e064a52d", "max_stars_repo_head_hexsha": "781233123135514590e61cc9ed625e2376a7ca98", "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/primegroup.jl", "max_issues_repo_name": "UnofficialJuliaMirror/CryptoGroups.jl-bc997328-bedd-407e-bcd3-5758e064a52d", "max_issues_repo_head_hexsha": "781233123135514590e61cc9ed625e2376a7ca98", "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/primegroup.jl", "max_forks_repo_name": "UnofficialJuliaMirror/CryptoGroups.jl-bc997328-bedd-407e-bcd3-5758e064a52d", "max_forks_repo_head_hexsha": "781233123135514590e61cc9ed625e2376a7ca98", "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.0581395349, "max_line_length": 109, "alphanum_fraction": 0.6007733204, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7519995817610615}}
{"text": "using MultivariateStats\nusing Base.Test\n\nsrand(34568)\n\n## data\n\nm = 9\nn = 6\nn2 = 3\n\nX = randn(m, n)\nA = randn(n, n2)\nXt = X'\n\nb = randn(1, n2)\n\nE = randn(m, n2) * 0.1\nY0 = X * A + E\nY1 = X * A .+ b + E\n\ny0 = Y0[:,1]\ny1 = Y1[:,1]\n\n## llsq\n\nA = llsq(X, Y0; trans=false, bias=false)\nA_r = copy(A)\n@test size(A) == (n, n2)\n@test_approx_eq X'Y0 X'X * A\n\na = llsq(X, y0; trans=false, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nA = llsq(Xt, Y0; trans=true, bias=false)\n@test size(A) == (n, n2)\n@test_approx_eq A A_r\n\na = llsq(Xt, y0; trans=true, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nAa = llsq(X, Y1; trans=false, bias=true)\nAa_r = copy(Aa)\n@test size(Aa) == (n+1, n2)\nA, b = Aa[1:end-1,:], Aa[end,:]\n@test_approx_eq X' * (Y1 .- b) X'X * A\n\naa = llsq(X, y1; trans=false, bias=true)\n@test_approx_eq aa Aa[:,1]\n\nAa = llsq(Xt, Y1; trans=true, bias=true)\n@test_approx_eq Aa Aa_r\n\naa = llsq(Xt, y1; trans=true, bias=true)\n@test_approx_eq aa Aa[:,1]\n\n\n## ridge (with Real r)\n\nr = 0.1\n\nA = ridge(X, Y0, r; trans=false, bias=false)\nA_r = copy(A)\n@test size(A) == (n, n2)\n@test_approx_eq X'Y0 (X'X + r * eye(n)) * A\n\na = ridge(X, y0, r; trans=false, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nA = ridge(Xt, Y0, r; trans=true, bias=false)\n@test size(A) == (n, n2)\n@test_approx_eq A A_r\n\na = ridge(Xt, y0, r; trans=true, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nAa = ridge(X, Y1, r; trans=false, bias=true)\nAa_r = copy(Aa)\n@test size(Aa) == (n+1, n2)\nA, b = Aa[1:end-1,:], Aa[end,:]\n@test_approx_eq X' * (Y1 .- b) (X'X + r * eye(n)) * A\n\naa = ridge(X, y1, r; trans=false, bias=true)\n@test_approx_eq aa Aa[:,1]\n\nAa = ridge(Xt, Y1, r; trans=true, bias=true)\n@test_approx_eq Aa Aa_r\n\naa = ridge(Xt, y1, r; trans=true, bias=true)\n@test_approx_eq aa Aa[:,1]\n\n\n## ridge (with diagonal r)\n\nr = 0.05 + 0.1 * rand(n)\n\nA = ridge(X, Y0, r; trans=false, bias=false)\nA_r = copy(A)\n@test size(A) == (n, n2)\n@test_approx_eq X'Y0 (X'X + diagm(r)) * A\n\na = ridge(X, y0, r; trans=false, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nA = ridge(Xt, Y0, r; trans=true, bias=false)\n@test size(A) == (n, n2)\n@test_approx_eq A A_r\n\na = ridge(Xt, y0, r; trans=true, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nAa = ridge(X, Y1, r; trans=false, bias=true)\nAa_r = copy(Aa)\n@test size(Aa) == (n+1, n2)\nA, b = Aa[1:end-1,:], Aa[end,:]\n@test_approx_eq X' * (Y1 .- b) (X'X + diagm(r)) * A\n\naa = ridge(X, y1, r; trans=false, bias=true)\n@test_approx_eq aa Aa[:,1]\n\nAa = ridge(Xt, Y1, r; trans=true, bias=true)\n@test_approx_eq Aa Aa_r\n\naa = ridge(Xt, y1, r; trans=true, bias=true)\n@test_approx_eq aa Aa[:,1]\n\n\n## ridge (with qudratic r matrix)\n\nQ = qr(randn(n, n))[1]\nr = Q' * diagm(r) * Q\n\nA = ridge(X, Y0, r; trans=false, bias=false)\nA_r = copy(A)\n@test size(A) == (n, n2)\n@test_approx_eq X'Y0 (X'X + r) * A\n\na = ridge(X, y0, r; trans=false, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nA = ridge(Xt, Y0, r; trans=true, bias=false)\n@test size(A) == (n, n2)\n@test_approx_eq A A_r\n\na = ridge(Xt, y0, r; trans=true, bias=false)\n@test size(a) == (n,)\n@test_approx_eq a A[:,1]\n\nAa = ridge(X, Y1, r; trans=false, bias=true)\nAa_r = copy(Aa)\n@test size(Aa) == (n+1, n2)\nA, b = Aa[1:end-1,:], Aa[end,:]\n@test_approx_eq X' * (Y1 .- b) (X'X + r) * A\n\naa = ridge(X, y1, r; trans=false, bias=true)\n@test_approx_eq aa Aa[:,1]\n\nAa = ridge(Xt, Y1, r; trans=true, bias=true)\n@test_approx_eq Aa Aa_r\n\naa = ridge(Xt, y1, r; trans=true, bias=true)\n@test_approx_eq aa Aa[:,1]\n\n", "meta": {"hexsha": "f09ac4b1e32bcdc9d37451437fb2e7822be389bb", "size": 3526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 20.6198830409, "max_line_length": 53, "alphanum_fraction": 0.5986954056, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7519995738437404}}
{"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\u03bb = 9\n\nfunction K(t)\n    return 2\u03bb*t / (1-2t) - p / 2 * log(1-2t)\nend\n\nfunction D1K(t)\n    return ( 4\u03bb*t ) / (1-2t)^2 + ( 2\u03bb + p ) / ( 1 - 2t )\nend\n\nfunction D2K(t)\n    return 2(p*(1-2t) + 4\u03bb) / (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\u03bb * 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": "using Rubin\nusing Tests\nusing Elliptic\nusing HypergeometricFunctions\nusing Polylogarithms\nusing SpecialFunctions\n\n@test integrate(x^2*SpecialFunctions.zeta(2,a+b*x), x) == :(2*b^-3*SpecialFunctions.polygamma(-2,x)+b^-1*x^2*SpecialFunctions.polygamma(0,x)+-2*x*b^-2*loggamma(a+b*x))\n@test integrate(x*SpecialFunctions.zeta(2,a+b*x), x) == :(-1*b^-2*loggamma(a+b*x)+x*b^-1*SpecialFunctions.polygamma(0,x))\n@test integrate(SpecialFunctions.zeta(2,a+b*x), x) == :(b^-1*SpecialFunctions.polygamma(0,x))\n@test integrate(x^-2*SpecialFunctions.zeta(2,a+b*x)+-1*b*x^-1*SpecialFunctions.polygamma(2,x), x) == :(-1*x^-1*SpecialFunctions.polygamma(1,x))\n@test integrate(x*SpecialFunctions.zeta(s,a+b*x), x) == :(x*b^-1*(1+-1s)^-1*SpecialFunctions.zeta(-1+s,a+b*x)+-1*b^-2*(1+-1s)^-1*(2+-1s)^-1*SpecialFunctions.zeta(-2+s,a+b*x))\n@test integrate(SpecialFunctions.zeta(s,a+b*x), x) == :(b^-1*(1+-1s)^-1*SpecialFunctions.zeta(-1+s,a+b*x))\n@test integrate(x^-2*SpecialFunctions.zeta(s,a+b*x)+b*s*x^-1*SpecialFunctions.zeta(1+s,a+b*x), x) == :(-1*x^-1*SpecialFunctions.zeta(s,a+b*x))\n", "meta": {"hexsha": "d747d7c200e90fbe65115584a8bb7db975004614", "size": 1067, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/8 Special functions/8.7 Zeta function.jl", "max_stars_repo_name": "bradeneliason/Rubin.jl", "max_stars_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-13T03:00:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T03:00:21.000Z", "max_issues_repo_path": "test/8 Special functions/8.7 Zeta function.jl", "max_issues_repo_name": "bradeneliason/Rubin.jl", "max_issues_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_issues_repo_licenses": ["MIT"], "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/8 Special functions/8.7 Zeta function.jl", "max_forks_repo_name": "bradeneliason/Rubin.jl", "max_forks_repo_head_hexsha": "4becf75a5b265aced3ecd4e2bc8e7473c68c4840", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.1333333333, "max_line_length": 174, "alphanum_fraction": 0.6935332709, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7519870007184407}}
{"text": "@testset \"Matrices\" begin\n  # tests with Aitchson's definitions\n  d = 10\n  D = d+1\n  @test J(d) == ones(d, d)\n  @test F(d) == [I(d) -ones(d)]\n  @test G(D) \u2248 I(D) - J(D)/ D\n  @test H(d) == I(d) + J(d)\n\n  # tests of multiplications\n  for M in [J G H]\n    @test M * [1:d...] \u2248 M(d) * [1:d...]\n    @test [1:d...]' * M \u2248 [1:d...]' * M(d)\n  end\n\n  # tests of F (d x D)\n  @test F * [1:D...] == F(d) * [1:D...]\n  @test [1:d...]' * F == [1:d...]' * F(d)\nend\n", "meta": {"hexsha": "8b39e6891972cf525f60151ec766b846e90df263", "size": 449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/matrices.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": "test/matrices.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": "test/matrices.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.45, "max_line_length": 42, "alphanum_fraction": 0.429844098, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.94815453335022, "lm_q2_score": 0.7931059438487662, "lm_q1q2_score": 0.7519869960872128}}
{"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": "# First-order irreversible series reaction\r\nid = :Sahlodin2011a\r\n\r\npL = [-1.0]\r\npU = [1.0]\r\nSahlodin2011a_x0(p::Vector{T}) where T = T[9.0*one(T)]\r\nfunction Sahlodin2011a_f!(du::Vector{T}, u::Vector{T}, p::Vector{T}, t) where T\r\n    du[1] = -u[1]^2 + p[1]\r\n    return\r\nend\r\ntspan = (0.0, 1.0)\r\n\r\nprob = ODERelaxProb(Sahlodin2011a_f!, tspan, Sahlodin2011a_x0, pL, pU)\r\nurl = \"https://www.sciencedirect.com/science/article/abs/pii/S0168927411000316\"\r\nsource = \"Sahlodin2011\"\r\ndesc = \"First-order irreversible series reaction\"\r\n", "meta": {"hexsha": "aad1588b3cb1478af6f6e906b65f041b50300cdb", "size": 525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/library/pODEs/Sahlodin2011a.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/Sahlodin2011a.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/Sahlodin2011a.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": 30.8823529412, "max_line_length": 80, "alphanum_fraction": 0.6761904762, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7519275086490848}}
{"text": "module HoltsLinearTrendTests\n\nusing Test\n\nusing TSeriesForecast: HLT, loss, fit, forecast\n\n\u03f5 = 0.1\n\n### Data\n\nobservations = [17.5534, 21.8601, 23.8866, 26.9293, 26.8885, 28.8314, 30.0751, 30.9535, 30.1857, 31.5797, 32.577569, 33.477398, \n39.021581, 41.386432, 41.596552, 44.657324, 46.951775, 48.728837, 51.488427,50.026967, 60.640913, 63.3603103378, \n66.355274, 68.197955, 68.1232376693, 69.7793454797, 72.597700806]\n\n### Parameters\n\n\u03b1 = 0.830216559778346\n\u03b2 = 0.000100014855685128\nl\u2080 = 15.5715222051655\nb\u2080 = 2.10171710376136\nh = 5\n\n### Expected values\n\ny_expected = [74.6013036045367, 76.7030432818444, 78.8047829591522, 80.90652263646, 83.0082623137678]\n\n### Tests\n\n@testset \"Holts Linear Trend\" begin\n    @testset \"HLT struct\" begin\n        \n        @testset \"HLT default constructor\" begin\n            model = HLT()\n            @test model.\u03b1 \u2248 0\n            @test model.\u03b2 \u2248 0\n            @test model.l\u2080 \u2248 0\n            @test model.b\u2080 \u2248 0\n        end\n\n        @testset \"HLT parametric constructor\" begin\n            \u03b1 = 0.5\n            \u03b2 = 0.2\n            l\u2080 = 130.9\n            b\u2080 = 20.3\n            model = HLT(\u03b1, \u03b2, l\u2080, b\u2080)\n            @test model.\u03b1 \u2248 \u03b1\n            @test model.\u03b2 \u2248 \u03b2\n            @test model.l\u2080 \u2248 l\u2080\n            @test model.b\u2080 \u2248 b\u2080\n        end\n\n        @testset \"HLT parametric constructor takes any Number type\" begin\n            \u03b1 = Float32(0.2341)\n            \u03b2 = BigFloat(0.1112)\n            l\u2080 = 345\n            b\u2080 = 54.\n            model = HLT(\u03b1, \u03b2, l\u2080, b\u2080)\n            @test model.\u03b1 \u2248 \u03b1\n            @test model.\u03b2 \u2248 \u03b2\n            @test model.l\u2080 \u2248 l\u2080\n            @test model.b\u2080 \u2248 b\u2080\n        end\n    end\n\n    @testset \"loss\" begin\n        # taken from R\n        expected_mse = 4.76261989118118\n        model = HLT(\u03b1, \u03b2, l\u2080, b\u2080)\n        @test isapprox(loss(model, observations)/length(observations), expected_mse; atol=\u03f5)\n    end\n\n    @testset \"fit\" begin\n        y = observations\n\n        starting_point = HLT()\n        optimal_model = fit(starting_point, y)\n\n        @test isapprox(optimal_model.\u03b1, \u03b1; atol=0.1)\n        @test isapprox(optimal_model.\u03b2, \u03b2; atol=1)\n        @test isapprox(optimal_model.l\u2080, l\u2080; atol=1)\n        @test isapprox(optimal_model.b\u2080, b\u2080; atol=0.1)\n    end\n\n    @testset \"forecast\" begin\n        model = HLT(\u03b1, \u03b2, l\u2080, b\u2080)\n        @testset \"The forecast is correct\" begin\n            @test isapprox(forecast(model, observations, h), y_expected; atol=\u03f5)\n        end\n\n        @testset \"forecast returns an array of length `h`\" begin\n            @test length(forecast(model, observations, 5)) == 5\n        end\n    end\nend\n\nend\n", "meta": {"hexsha": "5b9f0412fd8f85d6177b641cf8176358ba61e556", "size": 2573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TSeriesForecast/test/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/test/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/test/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": 26.5257731959, "max_line_length": 128, "alphanum_fraction": 0.5709288768, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7519275049370309}}
{"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\u03b8_opt = 3.78\nfunction logistic_f(x_next, x, k, \u03b8)\n    x_next .=  \u03b8*x - \u03b8*x.^2\n    return\nend\nfunction logistic_g(y, x, k, \u03b8)\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), (\u03b8_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) = \u03b81*x - \u03b81*x^2\n@everywhere function f(y, dx, d\u03b8, x, k, \u03b8)\n    y .= \u03b8[1]*x - \u03b8[1]*x.^2\n    dx .= \u03b8[1] - 2*\u03b8[1]*x\n    d\u03b8 .=  x-x.^2\n    return\nend\n# g(x) = x\n@everywhere function g(y, dx, d\u03b8, x, k, \u03b8)\n    y .= x\n    dx .= 1\n    d\u03b8 .= 0\n    return\nend\n\n\u03b8 = 0\nmultiple_shoot = ms.MultipleShooting(f, g, x0_list,\n                                     y, k0_list, \u03b8,\n                                     list_procs)\nms.cost_function(multiple_shoot)\n\n# Get cost function\n\u03b8_min = 2.0\n\u03b8_delta = 0.01\n\u03b8_max = 4.0\n\u03b8_range = \u03b8_min:\u03b8_delta:\u03b8_max\nnpoints = length(\u03b8_range)\ncost = Vector{Float64}(npoints)\ni = 1\nfor \u03b8 = \u03b8_range\n    ms.new_simulation!(multiple_shoot, x0_list, [\u03b8])\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    \u03c3 = 0.005\n    x0_list_modified = copy(x0_list)\n    for i = 1:M\n        x0_list_modified .+= \u03c3*randn()\n    end\n    i = 1\n    for \u03b8 = \u03b8_range\n        ms.new_simulation!(multiple_shoot, x0_list_modified, [\u03b8])\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\u03b8_list = Float64[]\ncost_list = Float64[]\nres_list = []\nfor \u03b8p = 3.2:0.05:3.9\n    \u03c3 = 0.002\n    x0_list_modified = copy(x0_list)\n    for i = 1:M\n        x0_list_modified .+= \u03c3*randn()\n    end\n    \u03b80 = [\u03b8p]\n    opt = ms.OptimizationProblem(f, g, x0_list_modified, y,\n                                 k0_list, \u03b80, list_procs)\n\n    res = ms.solve(opt, options=Dict(\"gtol\" => 1e-10,\n                                     \"xtol\" => 1e-10,\n                                     \"maxiter\" => 2000))\n    \u03b8_est = res[\"x\"][1]\n    cost_est = res[\"fun\"]\n\n    push!(\u03b8_list, \u03b8_est)\n    push!(cost_list, cost_est)\n    push!(res_list, res)\nend\n\nplot(\u03b8_range, cost, color=:black, lw=2, legend=false, grid=false,\n     xlims=[\u03b8_min, \u03b8_max], xguide=L\"\\theta\", yguide=L\"V(\\theta)\")\nplot!(\u03b8_range, cost_matrix, color=:blue, linealpha=0.2)\nscatter!(\u03b8_list, cost_list, marker=:c, color=:green, markersize=5)\nvline!([\u03b8_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": "using Printf\r\nusing LinearAlgebra\r\nusing CSV\r\nusing StatsBase\r\nimport Base.*, Base.+\r\n\r\n\r\ndn_source = dirname(Base.source_path())\r\npush!(LOAD_PATH, dn_source)\r\nusing DL\r\n\r\n# \u95a2\u6570\u306e\u5408\u6210\r\n\u2218(f::Function, g::Function) = x::Tensor-> f(g(x::Tensor))\r\n\r\n# Array\u3092\u30b7\u30e3\u30c3\u30d5\u30eb\u3059\u308b\u95a2\u6570\r\nfunction shuffle(vx)\r\n    n = length(vx)\r\n    return sample(vx, n, replace=false)\r\nend\r\n\r\nfunction main()\r\n    filename = \"iris.csv\"\r\n    data = CSV.read(filename)\r\n    n_data, n_type = size(data)\r\n    # n_train = 150 * 0.8 = 120\r\n    n_train::Int64 = n_data * 0.8\r\n    # n_test = 150 - 120  = 30\r\n    n_test::Int64 = n_data - n_train\r\n\r\n\r\n    # \u82b1\u306e\u540d\u524d -> Onehot\r\n    # iris\u30c7\u30fc\u30bf\u30bb\u30c3\u30c8\u3067\u306f3\u7a2e\u985e\u306e\u82b1\u306e\u540d\u524d\u304c\u3042\u308b\r\n    \u82b1\u306e\u540d\u524ds = unique(data[end])\r\n    # n_hana = 3\r\n    n_hana = length(\u82b1\u306e\u540d\u524ds)\r\n    vid2onehot = function(x::Int64)\r\n        onehot = zeros(n_hana, 1)\r\n        onehot[x, 1] = 1.0\r\n        return onehot\r\n    end\r\n    # \u82b1\u306e\u540d\u524d\u3092onehot\u5f62\u5f0f\u306b\u5909\u63db\u3059\u308b\r\n    \u82b1toOnehot = x::String -> vid2onehot(findfirst(\u82b1\u306e\u540d\u524ds .== x))\r\n    # argmax(onehot)\u3092\u82b1\u306e\u540d\u524d\u306b\u5909\u3048\u308b\r\n    id2name = x -> \u82b1\u306e\u540d\u524ds[x]\r\n\r\n    # \u5165\u529b\u306e\u6b21\u5143\r\n    in_features = n_type - 1\r\n    # \u51fa\u529b\u306e\u6b21\u5143\r\n    out_features = n_hana\r\n\r\n    data = map(i -> [data[i, :]...], 1:n_data)\r\n    # \u30c7\u30fc\u30bf\u3092shuffle\r\n    data = shuffle(data)\r\n    # \u5b66\u7fd2\u30c7\u30fc\u30bf\r\n    vtrain_x = map(i -> Float64.(data[i][1:in_features]), 1:n_train)\r\n    vtrain_y = map(i -> data[i][n_type], 1:n_train)\r\n    vtrain_y = map(\u82b1toOnehot, vtrain_y)\r\n    traindataset = collect(zip(vtrain_x, vtrain_y))\r\n    # \u30c6\u30b9\u30c8\u30c7\u30fc\u30bf\r\n    vtest_x = map(i -> Float64.(data[i][1:in_features]), n_train+1:n_data)\r\n    vtest_y = map(i -> data[i][n_type], n_train+1:n_data)\r\n    vtest_y = map(\u82b1toOnehot, vtest_y)\r\n    testdataset = collect(zip(vtest_x, vtest_y))\r\n\r\n\r\n    # \u5c64\r\n    W1 = VariableTensor(randn(32, in_features)/sqrt(32*in_features))\r\n    b1 = VariableTensor(zeros(32, 1))\r\n    W2 = VariableTensor(randn(out_features, 32)/sqrt(out_features*32))\r\n    b2 = VariableTensor(zeros(out_features, 1))\r\n    l1 = x -> W1 * x + b1\r\n    l2 = x -> W2 * x + b2\r\n    # \u30e2\u30c7\u30eb\r\n    model = l2 \u2218 ReLU \u2218 l1\r\n    # \u640d\u5931\u95a2\u6570\r\n    loss_func = (predict::Tensor, data::Tensor) -> MSE(predict, data)\r\n    # \u6700\u9069\u5316\u95a2\u6570\r\n    optimizer = SGD(1e-4)\r\n\r\n    f = open(\"loss.dat\", \"w\")\r\n    for epoch in 1:1000\r\n        # train\r\n        @show epoch\r\n        train_loss::Float64 = 0\r\n        # traindataset\u3092\u30b7\u30e3\u30c3\u30d5\u30eb\u3059\u308b\r\n        traindataset = shuffle(traindataset)\r\n        for (batch_idx, (x, y)) in enumerate(traindataset)\r\n            x = ConstantTensor(x)\r\n            y = ConstantTensor(y)\r\n            predict = model(x)\r\n            loss = loss_func(predict, y)\r\n            train_loss += loss.x\r\n            # W1.grad, W2.grad, b1.grad, b2.grad\u306b\u5fae\u5206\u3092\u8db3\u3057\u3053\u3093\u3067\u3044\u304f\r\n            backward(loss)\r\n\r\n            # .grad\u3092\u4f7f\u3063\u3066W1.x, W2.x, b1.x, b2.x\u3092\u66f4\u65b0\u3059\u308b\r\n            # batch_size = 30\u3067\u5b66\u7fd2\u3059\u308b. \r\n            if batch_idx % 30 == 0 || batch_idx == n_train\r\n                optimizer(loss)\r\n                # .grad\u30920\u306b\u3059\u308b\r\n                zero_grad(loss)\r\n            end\r\n        end\r\n\r\n        @show train_loss\r\n\r\n        # test\r\n        \u6b63\u89e3\u6570::Int64 = 0\r\n        for (x, y) in testdataset\r\n            # \u5165\u529b\r\n            x = ConstantTensor(x)\r\n            # \u6559\u5e2b\u30c7\u30fc\u30bf\r\n            y = ConstantTensor(y)\r\n            p = model(x)\r\n            pname = id2name(argmax(p.x))\r\n            name = id2name(argmax(y.x))\r\n            \u6b63\u89e3\u6570 += pname == name\r\n        end\r\n        @printf(f, \"%d, % .3e, %.3f\\n\", epoch, train_loss, \u6b63\u89e3\u6570 / n_test)\r\n\r\n    end\r\n    close(f)\r\nend\r\n\r\n\r\nmain()", "meta": {"hexsha": "63ec5a58844b6f0934415602e69b184a9666d149", "size": 3417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ayame.jl", "max_stars_repo_name": "Soyukke/julia-ayame-machine-learning", "max_stars_repo_head_hexsha": "4e072c403edbd37c213bbad5917c9ab76ea413e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ayame.jl", "max_issues_repo_name": "Soyukke/julia-ayame-machine-learning", "max_issues_repo_head_hexsha": "4e072c403edbd37c213bbad5917c9ab76ea413e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ayame.jl", "max_forks_repo_name": "Soyukke/julia-ayame-machine-learning", "max_forks_repo_head_hexsha": "4e072c403edbd37c213bbad5917c9ab76ea413e5", "max_forks_repo_licenses": ["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.119047619, "max_line_length": 75, "alphanum_fraction": 0.5419959028, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7519067658702442}}
{"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.\u03b1 + successes\n  b = prior.\u03b2 + 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\u2083 = 0, n\u2085 = 0, n\u2087 = 0)\n    if K > N\n        return 0\n    else\n        result = (n\u2083 > 0 && n\u2085 > 0 && n\u2087 > 0) +\n            f753(N, 10K + 3, n\u2083 + 1, n\u2085, n\u2087) + \n            f753(N, 10K + 5, n\u2083, n\u2085 + 1, n\u2087) + \n            f753(N, 10K + 7, n\u2083, n\u2085, n\u2087 + 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": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 8ae7bb38-5803-41d0-98e3-6d9dc4936406\nusing StatsPlots\n\n# \u2554\u2550\u2561 03eb200d-c3b4-43d6-b86f-017f5454bc86\nusing Random\n\n# \u2554\u2550\u2561 50cd5676-cdba-425d-84d3-7ad6fe21a2d5\nmd\"\"\"\nThe code in this notebook accompanies the essay \"Riding the Covid Coaster,\" by Brian Hayes, published 17 August 2021 at [http://bit-player.org/2021/riding-the-covid-coaster](http://bit-player.org/2021/riding-the-covid-coaster). It explores various approaches to understanding the trajectory of the Covid-19 epidemic in the United States during its first 18 months.\n\nThis is one of three notebooks with code for the project:\n\n* covidcurve.jl covers the reconstruction of the Covid-19 incidence curve and attempts to apply Fourier methods, looking for periodic signals in the data. Also a look at time derivatives. Includes code for figures 1, 3, 4, 5, 6, 7, 8, 9, 12.\n\n* SIR_model.jl deals with exponential growth in epidemic processes, and models based on that idea. Figures 10, 11, 13, 14, 16, 17, 18, 19, 20, 21, 23, 24.\n\n* us_states_data.jl breaks down the national Covid data set into records for inividual states and regions. Code for Figure 22.\n\nThe underlying data for most of this work was collected and curated by _The New York Times_. The archive is available at [https://github.com/nytimes/covid-19-data](https://github.com/nytimes/covid-19-data). The version I used in the code below, including data from 21 January 2020 through 20 July 2021, is commit c3ab8c1beba1f4728d284c7b1e58d7074254aff8. You can access the identical set of files at [https://github.com/nytimes/covid-19-data/tree/c3ab8c1beba1f4728d284c7b1e58d7074254aff8](https://github.com/nytimes/covid-19-data/tree/c3ab8c1beba1f4728d284c7b1e58d7074254aff8). But you should probably get the most up-to-date version, with the latest data.\n\nWithin the _Times_ archive I have used the files within a folder named \"rolling-averages,\" which has daily new cases rather than cumulative cases, and has precomputed the seven-day trailing average of the data sequences.\n\nThe code is written in the [Julia programming language](https://julialang.org/) and organized in [Pluto.jl notebooks](https://github.com/fonsp/Pluto.jl).\n\nInstructions:\n\n1. You'll need a working installation of Julia with the Pluto.jl package installed. Version 0.15.1 or later is needed to automatically find, load, and install packages.\n\n2. In a terminal window, cd to the directory where you have stored this file. Start Julia, then at the \"julia>\" prompt, type \"using Pluto; Pluto.run('SIRmodel.jl')\".\n\n3. A browser window will open with this notebook displayed. Pluto will then download all the necessary packages and their dependencies, and will evaluate the cells in the proper order. This can take several minutes, and it can rev up your CPU fan. But then you're done.\n\n\"\"\"\n\n# \u2554\u2550\u2561 035ad037-d231-4a7b-a451-213085be2eb4\n# Figure 10\n\n# Plot exponential growth of R^t for various values of R\n\nexp_log_plot =\nbegin\n\txs = 0:0.05:20\n\tplot(xs,\n\t\t[[0.8^x for x in xs],\n\t\t [1.0^x for x in xs],\n\t\t [1.25^x for x in xs],\n\t\t [2.0^x for x in xs],\n\t\t [3.0^x for x in xs]],\n\t\tylims = [0.01, 1e10],\n\t\tyscale = :log10,\n\t\tyticks = [0.01, 1.0, 1e2, 1e4, 1e6, 1e8, 1e10],\n\t\tlinewidth = 2.0,\n\t\txlabel = \"serial passage times\",\n\t\tylabel = \"number of new cases\",\n\t\tfontfamily = \"helvetica\",\n\t\tlegend = false)\nend\n\n# \u2554\u2550\u2561 243d8dbd-0f8f-4604-bdb9-9c9078e906be\nmd\"\"\"\n#### SIR Models\n\nThis is a home-brewed discrete-time implementation of a SIR (susceptible-infective-recovered) model of epidemic dynamics. There are lots and lots of other implementations out there, mostly based on continuous-time differential equations.\n\nJust within the Julia world, Simon Frost has written or collected more than two dozen versions at [https://github.com/epirecipes/sir-julia](https://github.com/epirecipes/sir-julia). And Roberto Alain Berwa has an implementation tuned specifically for Covid-19 at [https://nextjournal.com/berwa/sir-model-for-covid-19-estimating-R_o](https://nextjournal.com/berwa/sir-model-for-covid-19-estimating-R_o).\n\"\"\"\n\n# \u2554\u2550\u2561 7fa5fed0-63a9-4332-a808-95e2b7bcf09d\n# The basic model\n\n# The population variables ss, ii, and rr are all floats in the interval\n# [0, 1], with the condition that ss + ii + rr == 1.0 at all times. The\n# initial infective density i0 is also a float in this range. \u03b2 and \u03b3 are\n# the infection and recovery constants. tmax is the total time span of the\n# simulation measured in multiples of the serial passage time--the average\n# time between acquiring an infection and infecting someone else. dt is the\n# simulation time step; we start at tt = 0 and increment by dt until we\n# reach tmax.\n\nfunction sir(i0, \u03b2, \u03b3, dt, tmax)\n\tsteps = floor(Int, tmax / dt)\n\n\ttimes = zeros(steps)\n\tsusceptibles = zeros(steps)\n\tinfectives = zeros(steps)\n\trecovereds = zeros(steps)\n\t\n\ttt = 0.0        # time variable, in steps of dt\n\tss = 1.0 - i0   # susceptible population as a function of tt\n\tii = i0         # infective population as a function of tt\n\trr = 0.0        # recovered population as a function of tt\n\t\n\tfor count in 1:steps  # loop tmax/dt times\n\t\t\n\t\ttimes[count] = tt          # record current values in four vectors\n\t\tsusceptibles[count] = ss\n\t\tinfectives[count] = ii\n\t\trecovereds[count] = rr\n\t\t\t\t\n\t\tnew_infections = dt * \u03b2 * ss * ii  # calc infections and recoveries\n\t\trecoveries = dt * \u03b3 * ii\n\t\t\n\t\tss = ss - new_infections              # update population numbers\n\t\tii = ii + new_infections - recoveries\n\t\trr = rr + recoveries\n\t\ttt = tt + dt                          # increment time\n\tend\n\treturn (times, [susceptibles, infectives, recovereds])\nend\n\n\n# \u2554\u2550\u2561 b1f928d8-7175-4bd3-9adc-9cb93b0dbb40\n# Figure 11 -- output of the basic SIR model\n\nsir_graph = \nplot(sir(0.000001, 0.6, 0.2, 0.1, 100),\n\tlinecolor = [:green \"#4100eb\" \"#dd4411\"],\n\tlinewidth = [2.0 3.5 2.0],\n\tlabel = false,\n\tannotationfontsize = 10,\n\tannotationhalign = :left,\n\tannotations = [(9, 0.90, \"susceptibles\"),\n\t\t\t\t   (44, 0.65, \"recovereds\"),\n\t\t\t\t   (45, 0.20, \"infectives\")],\n\txticks = 0:20:100,\n\tyticks = 0.0:0.20:1.0,\n\txlabel = \"serial passage times\",\n\tylabel = \"proportion of population\"\n\t) \n\n# \u2554\u2550\u2561 ad7091a0-399f-49ee-b273-4976ecb1b75e\n# savefig(sir_graph, \"SIR_model.svg\")\n\n# \u2554\u2550\u2561 13abedaa-7df4-48c6-8d61-d81c8d585be8\n# \"SIR with fear\" -- exploring feedback as a source of oscillatory\n#  behavior in epidemic dynamics.\n\n# We add two features to the basic SIR model. Negative feedback suppresses\n# all new infections whenever the infection rate rises above a threshold. But\n# the feedback may take effect only after a delay.\n\nfunction sirf(i0, \u03b2, \u03b3, threshold, delay, dt, tmax)\n\tsteps = floor(Int, tmax / dt)\n\n\ttimes = zeros(steps)\n\tsusceptibles = zeros(steps)\n\tinfectives = zeros(steps)\n\trecovereds = zeros(steps)\n\tthresholds = fill(threshold, steps)\n\t\n\ttt = 0.0\n\tss = 1.0 - i0\n\tii = i0\n\trr = 0.0\n\t\u03d5  = 1.0\n\t\n\tfor count in 1:steps\n\t\t\n\t\ttimes[count] = tt\n\t\tsusceptibles[count] = ss\n\t\tinfectives[count] = ii\n\t\trecovereds[count] = rr\n\t\t\n\t\tif count <= delay\n\t\t\t\u03d5 = 1.0\n\t\telse  \n\t\t\t\u03d5 = infectives[count - delay] < threshold ? 1.0 : 0.0\n\t\tend\n\t\t\t\t\n\t\tnew_infections = dt * \u03b2 * \u03d5 * ss * ii\n\t\trecoveries = dt * \u03b3 * ii\n\t\tss = ss - new_infections\n\t\tii = ii + new_infections - recoveries\n\t\trr = rr + recoveries\n\t\ttt = tt + dt\n\tend\n\treturn (times, [susceptibles, infectives, recovereds, thresholds])\nend\n\n\n# \u2554\u2550\u2561 ef8592b6-7474-410c-9171-187893239151\nsirf_result_no_delay = sirf(0.000001, 0.6, 0.2, 0.05, 0, 0.1, 100)\n\n# \u2554\u2550\u2561 e3a0e0c3-1a96-4a9d-bbe3-a25061b1ee12\n# Figure 13 -- SIR with feedback but no delay. Oscillations are too\n# small in period and amplitude to be perceived.\n\nsirf_graph_no_delay = \nplot(sirf_result_no_delay,\n\tlinecolor = [:green \"#4100eb\" \"#dd4411\" :black],\n\tlinewidth = [2.0 2.5 2.0 0.75],\n\tlinestyle = [:solid :solid :solid :dash],\n\tlabel = false,\n\tannotationfontsize = 10,\n\tannotationhalign = :left,\n\tannotations = [(33, 0.90, \"susceptibles\"),\n\t\t\t\t   (75, 0.69, \"recovereds\"),\n\t\t\t\t   (53, 0.09, \"infectives\"),\n\t\t\t\t   (3,  0.08, \"threshold\")],\n\txticks = 0:20:100,\n\tyticks = 0.0:0.20:1.0,\n\txlabel = \"serial passage times\",\n\tylabel = \"proportion of population\"\n\t)\n\n# \u2554\u2550\u2561 228a6067-bddf-4e6e-b3d8-2a6ac47d3904\nsavefig(sirf_graph_no_delay, \"SIR_model_with_feedback.svg\")\n\n# \u2554\u2550\u2561 08be5eef-4bdc-4ee6-8e5e-507c8055c07e\nsirf_result = sirf(0.000001, 0.6, 0.2, 0.05, 30, 0.1, 100)\n\n# \u2554\u2550\u2561 890fe7ce-d6cd-49c2-b888-421971118d8d\n# Figure 14 -- SIR model with both feedback and delay.\n\nsirf_graph = \nplot(sirf_result,\n\tlinecolor = [:green \"#4100eb\" \"#dd4411\" :black],\n\tlinewidth = [2.0 2.5 2.0 0.75],\n\tlinestyle = [:solid :solid :solid :dash],\n\tlabel = false,\n\tannotationfontsize = 10,\n\tannotationhalign = :left,\n\tannotations = [(30, 0.90, \"susceptibles\"),\n\t\t\t\t   (75, 0.69, \"recovereds\"),\n\t\t\t\t   (45, 0.12, \"infectives\"),\n\t\t\t\t   (3,  0.08, \"threshold\")],\n\txticks = 0:20:100,\n\tyticks = 0.0:0.20:1.0,\n\txlabel = \"serial passage times\",\n\tylabel = \"proportion of population\"\n\t)\n\n# \u2554\u2550\u2561 7ba339f1-b03e-49d7-9821-bd731ffe664d\n# savefig(sirf_graph, \"SIR_model_with_oscillations.svg\")\n\n# \u2554\u2550\u2561 e8657ff4-4c7f-401c-a3e7-5098a90d99e5\n# The basic SIR model uses exponential decay as well as exponential growth. \n# Calculate the exponential falloff in infective numbers after new infections\n# cease.\n\nfunction decline(n, \u03b3, reps)\n\tvec = [n]\n\tfor i in 1:reps\n\t\tn -= n * \u03b3\n\t\tpush!(vec, n)\n\tend\n\tvec\nend\n\n# \u2554\u2550\u2561 798a62d7-700b-400e-9bc9-efbe0b7758bc\n# Figure 16\n\nexponential_decline_bargraph =\nplot(decline(1.0, 0.2, 10), \n\tseriestype = :bar,\n\txticks = (1.0:1.0:11.0, 0:1:10),\n\tyticks = (0:0.2:1.0),\n\tsize = [350, 200],\n\tfontfamily = \"helvetica\",\n\tguidefontsize = 10,\n\tfillcolor = \"#4100eb\",\n\txlabel = \"serial passage times\",\n\tylabel = \"fraction remaining\",\n\tlegend = false\n)\n\n# \u2554\u2550\u2561 cb4c6cbb-5e44-49da-b82f-3551a1b3abbf\n# savefig(exponential_decline_bargraph, \"exponential_decline_bargraph.svg\")\n\n# \u2554\u2550\u2561 235956e8-e4d6-49bc-b175-d7c2aed732a8\n# Instead of exponential decay in infective numbers, we assign\n# the infectious period a fixed duration. At each time step the\n# newly recruited infectives enter a queue of length q, and\n# progress through it at one place per time step. After q steps\n# they reach the head of the q and are transformed into recovereds.\n\nfunction sirq(i0, \u03b2, q, dt, tmax)\n\tsteps = floor(Int, tmax / dt)\n\n\ttimes = zeros(steps)\n\tsusceptibles = zeros(steps)\n\tinfectives = zeros(steps)\n\trecovereds = zeros(steps)\n\tQ = zeros(Int(ceil(q / dt)))\n\t\n\ttt = 0\n\tss = 1 - i0\n\tii = i0\n\trr = 0\n\t\n\tfor count in 1:steps\n\t\t\n\t\ttimes[count] = tt\n\t\tsusceptibles[count] = ss\n\t\tinfectives[count] = ii\n\t\trecovereds[count] = rr\n\t\t\t\t\n\t\tnew_infections = dt * \u03b2 * ss * ii\n\t\trecoveries = pop!(Q)\n\t\tss = ss - new_infections\n\t\tii = ii + new_infections - recoveries\n\t\trr = rr + recoveries\n\t\ttt = tt + dt\n\t\tpushfirst!(Q, new_infections)\n\tend\n\treturn (times, [susceptibles, infectives, recovereds])\nend\n\n# \u2554\u2550\u2561 3e2cd644-1f53-4f51-891b-c54ae816f557\n# Figure 17 -- SIR model with infectious period equal to 3 serial\n# passage times.\n\nsirq_graph_3p0 = \nplot(sirq(0.000001, 0.6, 3.0, 0.1, 100),\n\tlinecolor = [:green \"#4100eb\" \"#dd4411\"],\n\tlinewidth = [2.0 3.5 2.0],\n\tlabel = false,\n\tfontfamily = \"helvetica\",\n\tannotationfontsize = 10,\n\tannotationhalign = :left,\n\tannotations = [(0, 0.97, \"susceptibles\"),\n\t\t\t\t   (60, 0.79, \"recovereds\"),\n\t\t\t\t   (12, 0.18, \"infectives\"),\n\t\t\t\t   (75, 0.97, \"duration = 3.0 TSP\")],\n\txticks = 0:20:100,\n\tyticks = 0.0:0.20:1.0,\n\txlabel = \"serial passage times\",\n\tylabel = \"proportion of population\"\n\t)\n\n# \u2554\u2550\u2561 7cc0d1e9-3cab-48cc-b873-181e006a620e\n# savefig(sirq_graph_3p0, \"sirq_0p000001_0p6_3p0_0p1_100.svg\")\n\n# \u2554\u2550\u2561 462e8b4d-5bf1-4153-b9d5-46b74f308721\n# Figure 18 -- SIR model with infectious period equal to 2 serial\n# passage times.\n\nsirq_graph_2p0 = \nplot(sirq(0.000001, 0.6, 2.0, 0.1, 100),\n\tlinecolor = [:green \"#4100eb\" \"#dd4411\"],\n\tlinewidth = [2.0 3.5 2.0],\n\tlabel = false,\n\tfontfamily = \"helvetica\",\n\tannotationfontsize = 10,\n\tannotationhalign = :left,\n\tannotations = [(0, 0.97, \"susceptibles\"),\n\t\t\t\t   (85, 0.35, \"recovereds\"),\n\t\t\t\t   (62, 0.05, \"infectives\"),\n\t\t\t\t   (75, 0.97, \"duration = 2.0 SPT\")],\n\txticks = 0:20:100,\n\tyticks = 0.0:0.20:1.0,\n\txlabel = \"serial passage times\",\n\tylabel = \"proportion of population\"\n\t)\n\n# \u2554\u2550\u2561 bff6a040-8d4a-4f00-a4e9-9f8147a21b41\n# savefig(sirq_graph_2p0, \"sirq_0p000001_0p6_2p0_0p1_100.svg\")\n\n# \u2554\u2550\u2561 f24f1556-cf68-4f54-bb35-7ac9b01d0a85\n# SIR model with vaccination\n\n\nfunction sirv(i0, \u03b2, \u03b3, v, v_date, dt, tmax)\n\tsteps = floor(Int, tmax / dt)\n\n\ttimes = zeros(steps)\n\tsusceptibles = zeros(steps)\n\tinfectives = zeros(steps)\n\trecovereds = zeros(steps)\n\tvaccinateds = zeros(steps)\n\t\n\ttt = 0\n\tss = 1 - i0\n\tii = i0\n\trr = 0\n\tvv = 0\n\t\n\tfor count in 1:steps\n\t\t\n\t\ttimes[count] = tt\n\t\tsusceptibles[count] = ss\n\t\tinfectives[count] = ii\n\t\trecovereds[count] = rr\n\t\tvaccinateds[count] = vv\n\t\t\t\t\n\t\tnew_infections = dt * \u03b2 * ss * ii\n\t\trecoveries = dt * \u03b3 * ii\n\t\tnew_vaccinations = (vv == 0 && tt > v_date) ? v : 0\n\t\t\n\t\tvv = vv + new_vaccinations\n\t\tss = ss - new_infections - new_vaccinations\n\t\tii = ii + new_infections - recoveries\n\t\trr = rr + recoveries\n\t\ttt = tt + dt\n\tend\n\treturn (times, [susceptibles, infectives, recovereds, vaccinateds])\nend\n\n\n# \u2554\u2550\u2561 4ae90a2a-67f1-4dc9-b6ed-d2e2e85aadd7\n# Figure 23\n\nsirv_graph_0p6_0p2_0p5_0 = \nplot(sirv(0.000001, 0.6, 0.2, 0.5, 0, 0.1, 100),\n\tlinecolor = [:green \"#4100eb\" \"#dd4411\" :orange],\n\tlinewidth = [3.5 3.5 2.0 2.0],\n\t# label = false,\n\tlabel = [\"susceptibles\" \"infectives\" \"recovereds\" \"vaccinateds\"],\n\tannotationfontsize = 10,\n\tannotationhalign = :left,\n\t# annotations = [(3, 0.96, \"susceptibles\"),\n\t\t\t\t   # (62, 0.61, \"recovereds\"),\n\t\t\t\t   # (17, 0.18, \"infectives\"),\n\t\t\t\t   # (62, 0.37, \"vaccinateds\")],\n\txticks = 0:20:100,\n\tyticks = 0.0:0.20:1.0,\n\txlabel = \"serial passage times\",\n\tylabel = \"proportion of population\"\n\t)\n\n# \u2554\u2550\u2561 09f9e4c9-315f-4433-b021-08150d6ce413\n# savefig(sirv_graph_0p6_0p2_0p5_0, \"sirv_graph_0p6_0p2_0p5_0.svg\")\n\n# \u2554\u2550\u2561 f0e6437c-609e-48f9-abc8-f3d325f35ec3\n# Figure 24\n\nsirv_graph_0p6_0p1_0p5_0 = \nplot(sirv(0.000001, 0.6, 0.1, 0.5, 0, 0.1, 100),\n\tlinecolor = [:green \"#4100eb\" \"#dd4411\" :orange],\n\tlinewidth = [3.5 3.5 2.0 2.0],\n\t# label = false,\n\tlabel = [\"susceptibles\" \"infectives\" \"recovereds\" \"vaccinateds\"],\n\tannotationfontsize = 10,\n\tannotationhalign = :left,\n\t# annotations = [(3, 0.96, \"susceptibles\"),\n\t\t\t\t   # (62, 0.61, \"recovereds\"),\n\t\t\t\t   # (17, 0.18, \"infectives\"),\n\t\t\t\t   # (62, 0.37, \"vaccinateds\")],\n\txticks = 0:20:100,\n\tyticks = 0.0:0.20:1.0,\n\txlabel = \"serial passage times\",\n\tylabel = \"proportion of population\"\n\t)\n\n# \u2554\u2550\u2561 cb0c1428-5146-4402-93ef-27c3cd4fd9d4\n# savefig(sirv_graph_0p6_0p1_0p5_0, \"sirv_graph_0p6_0p1_0p5_0.svg\")\n\n# \u2554\u2550\u2561 3438d796-9efc-44d0-9c08-a6c90305dee0\nmd\"\"\"\n#### Random mini-epidemics\n\nThe last topic to be taken up here is the possibility that the observed profile of the Covid incidence curve might be the result of summing many small, randomly timed mini-epidemics.\n\"\"\"\n\n# \u2554\u2550\u2561 e8139300-8097-4ba0-96e3-5135047c70d7\n# Generate a standard SIR curve with a specified starting time\n# 0 \u2264 tstart \u2264 tmax.\n\nfunction asynchSIR(i0, \u03b2, \u03b3, dt, tmax, tstart)\n\tsteps = floor(Int, tmax / dt)\n\n\ttimes = zeros(steps)\n\tsusceptibles = zeros(steps)\n\tinfectives = zeros(steps)\n\trecovereds = zeros(steps)\n\t\n\ttt = 0.0\n\tss = 1.0 - i0\n\tii = i0\n\trr = 0.0\n\t\n\tfor count in 1:steps\n\t\t\n\t\ttimes[count] = tt\n\t\ttt += dt\n\t\t\n\t\tif tt >= tstart\t\t\n\t\t\tsusceptibles[count] = ss\n\t\t\tinfectives[count] = ii\n\t\t\trecovereds[count] = rr\n\n\t\t\tnew_infections = dt * \u03b2 * ss * ii\n\t\t\trecoveries = dt * \u03b3 * ii\n\t\t\tss = ss - new_infections\n\t\t\tii = ii + new_infections - recoveries\n\t\t\trr = rr + recoveries\n\t\tend\n\tend\n\treturn infectives\nend\n\n\n# \u2554\u2550\u2561 8103f855-a617-438b-8cb9-8fa0e7fde319\n# Generate N SIR curves with start times chosen uniformly at\n# random from the interval 0 \u2264 tstart \u2264 0.8 * tmax. The parameter\n# \u03b2 is also allowed to vary around the specied value by an amount\n# drawn from a normal distribution with mean 0 and sdev 0.1.\n\n\nfunction multiSIR(N, i0, \u03b2, \u03b3, dt, tmax)\n\tsteps = floor(Int, tmax / dt)\n\tcurves = zeros(steps, N)\n\ttimes = collect(0.0:dt:tmax-dt)\n\t\n\tfor i in 1:N\n\t\ttstart = rand() * (0.8 * tmax)\n\t\trand_\u03b2 = \u03b2 + (randn() * 0.1)\n\t\tthis_curve = asynchSIR(i0, rand_\u03b2, \u03b3, dt, tmax, tstart)\n\t\tcurves[1:end, i] .= this_curve\n\tend\n\t\n\tsumcurve = zeros(steps)\n\tfor j in 1:steps\n\t\tsumcurve[j] = sum(curves[j, 1:end])\n\tend\n\t\n\tscale_factor = 1 / maximum(sumcurve)\n\tsumcurve .= sumcurve * scale_factor\n\tcurves .= curves * scale_factor\n\t\n\treturn ((times, curves), (times, sumcurve))\nend\n\n# \u2554\u2550\u2561 3fdd5a77-45df-494e-9786-c8aa22daa82e\n# Figure 19 -- Draw N randomly timed SIR curves and their sum curve.\n# The published figure shows results with N = 6 and N = 50. Because of\n# the randomness involved, rerunning this procedure will not replicate\n# the published figure, but the character of the result should be\n# the same.\n\nasynch_sir_graph = \nbegin\n\tthe_curves = multiSIR(20, 0.001, 0.6, 0.2, 0.1, 100)\n\tplot(the_curves[1],\n\t\tlinecolor = [\"#dd4411\"],\n\t\tlinewidth = 1.0,\n\t\tlabel = false,\n\t\txticks = 0:20:100,\n\t\tyticks = 0.0:0.20:1.0,\n\t\txlabel = \"serial passage times\",\n\t\tylabel = \"proportion of population\")\n\tplot!(the_curves[2],\n\t\tlinecolor = [\"#4100eb\"],\n\t\tlinewidth = 3.0,\n\t\tlabel = false,\n\t\tlegend = false)\nend\n\n# \u2554\u2550\u2561 341c32a3-3fae-472b-8771-c7f9fbaf4704\n# savefig(asynch_sir_graph, \"miltiSIR_12.svg\")\n\n# \u2554\u2550\u2561 0bb71f07-9381-4e77-9fe3-1c59854d18f5\n# Figure 20. -- Generate multiSIR plots, without scales, but\n# with a label indicating the number of component curves.\n\n\nfunction multiSIRplot(N, i0, \u03b2, \u03b3, dt, tmax, filename_prefix)\n\tresults = multiSIR(N, i0, \u03b2, \u03b3, dt, tmax)\n\tfilename = filename_prefix * \"_\" * \"$N\" *\".svg\"\n\t\n\tp =\tplot(results[1],\n\t\t\tlinecolor = [\"#dd4411\"],\n\t\t\tlinewidth = 1.0,\n\t\t\tlabel = false,\n\t\t\tframestyle = :box,\n\t\t\tannotationfontsize = 10,\n\t\t\tannotationhalign = :left,\n\t\t\tannotations = (0.0, 0.90, \"N = $N\"),\n\t\t\txticks = false,\n\t\t\tyticks = false)\n\t\t\t# xticks = 0:20:100,\n\t\t\t# yticks = 0.0:0.20:1.0,\n\t\t\t# xlabel = \"serial passage times\",\n\t\t\t# ylabel = \"proportion of population\")\n\tplot!(p, results[2],\n\t\t\tlinecolor = [\"#4100eb\"],\n\t\t\tlinewidth = 3.0,\n\t\t\tlabel = false,\n\t\t\tlegend = false)\n\tsavefig(p, filename)\n\treturn p\nend\n\n# \u2554\u2550\u2561 20fd7570-5c1f-4316-87f3-b972a1a0364f\nmultiSIRplot(12, 0.001, 0.6, 0.2, 0.1, 100, \"multiSIRplot\") \n\n# \u2554\u2550\u2561 8bfed4f2-724c-44ea-b6f4-02c836391be7\n# Figure 20 -- create a tableau of multiple multiSIR graphs.\n\nmultiSIR_tableau =\n[multiSIRplot(N, 0.001, 0.6, 0.2, 0.1, 100, \"multiSIR_tableau_A\") for N in [3, 4, 5, 6, 8, 10, 15, 20, 30, 40, 50, 60, 100]]\n\n# \u2554\u2550\u2561 64460f92-6dd3-4c13-b3b9-bb2660436b40\n# for i in 1:length(multiSIR_tableau)\n# \tsavefig(multiSIR_tableau[i], \"multiSIR_tableau_A_$i.svg\")\n# end\n\n# \u2554\u2550\u2561 7b8a3922-21a9-4905-84ad-e2d8edf51cce\n# Written to gather some statistics on the number of peaks and\n# troughs in a curve representing the sum of N mini-epidemics.\n\nfunction count_peaks_and_troughs(curve)\n\tderiv = diff(curve)\n\tcrossings = map(sign, deriv)\n\tpeaks = 0\n\ttroughs = 0\n\ti = 1\n\twhile crossings[i] == 0\n\t\ti += 1\n\tend\n\tprevious = crossings[i]\n\tfor j in i+1:length(crossings)\n\t\tif crossings[j] == -previous\n\t\t\tif crossings[j] < 0\n\t\t\t\tpeaks += 1\n\t\t\telse\n\t\t\t\ttroughs += 1\n\t\t\tend\n\t\t\tprevious = -previous\n\t\tend\n\tend\n\treturn (peaks, troughs)\nend\n\n# \u2554\u2550\u2561 bbf05eef-188d-4e31-ae40-f85a8269a3b6\n\nfunction collect_peak_counts(N, reps)\n\tcounts = zeros(Int, 20)\n\tfor i in 1:reps\n\t\tmultiSIRrecord = multiSIR(N, 0.001, 0.6, 0.2, 0.1, 100)\n\t\tpeaks, troughs = count_peaks_and_troughs(multiSIRrecord[2][2])\n\t\tcounts[peaks+1] += 1\n\tend\n\treturn counts\nend\n\n# \u2554\u2550\u2561 16e5e214-d5b7-480e-8243-9cbf36ababf8\npeak_data = [collect_peak_counts(n, 1000) for n in [4, 5, 6, 8, 10, 15, 30, 50, 100]]\n\n# \u2554\u2550\u2561 e252ca21-48d3-49f4-9bee-649a5610240a\n# Figure 21\n\n\npeak_data_plot =\nplot(peak_data, \n\tseriestype = :bar,\n\tlayout = (9, 1),\n\tsize = (400, 600),\n\tfillcolor = \"#4100eb\",\n\tframestyle = :grid,\n\txlims = [1, 12],\n\t# xticks = (1:1:12, [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\"]),\n\txticks = false,\n\tlegend = false,\n\tyticks = false)\n\n# \u2554\u2550\u2561 933d49c9-31fc-4d02-9b83-d523bf828476\n# savefig(peak_data_plot, \"peak_numbers_bar_graph.svg\")\n\n# \u2554\u2550\u2561 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\n\n[compat]\nStatsPlots = \"~0.14.26\"\n\"\"\"\n\n# \u2554\u2550\u2561 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[[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[[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[[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[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f53ca8d41e4753c41cdafa6ec5f7ce914b34be54\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"0.10.13\"\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\", \"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[[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[[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[[Distributions]]\ndeps = [\"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\"]\ngit-tree-sha1 = \"3889f646423ce91dd1055a76317e9a1d3a23fff1\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.11\"\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[[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[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8c8eac2af06ce35973c3eadb4ab3243076a408e7\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.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 = \"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 = \"9f473cdf6e2eb360c576f9822e7c765dd9d26dbc\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.58.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 = \"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 = \"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[[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[[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[[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[[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[[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[[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[[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[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"8d958ff1854b166003238fe191ec34b9d592860a\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.8.0\"\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[[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 = \"4f825c6da64aebaa22cc058ecfceed1ab9af1c7e\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.3\"\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[[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[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"94bf17e83a0e4b20c8d77f6af8ffe8cc3b386c0a\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.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 = \"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[[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[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"35927c2c11da0a86bcd482464b93dadd09ce420f\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.5\"\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\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"508822dca004bf62e210609148511ad03ce8f1d8\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.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[[StatsFuns]]\ndeps = [\"LogExpFunctions\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"30cd8c360c54081f806b1ee14d2eecbef3c04c49\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.8\"\n\n[[StatsPlots]]\ndeps = [\"Clustering\", \"DataStructures\", \"DataValues\", \"Distributions\", \"Interpolations\", \"KernelDensity\", \"LinearAlgebra\", \"MultivariateStats\", \"Observables\", \"Plots\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"StatsBase\", \"TableOperations\", \"Tables\", \"Widgets\"]\ngit-tree-sha1 = \"e7d1e79232310bd654c7cef46465c537562af4fe\"\nuuid = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nversion = \"0.14.26\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"000e168f5cc9aded17b6999a560b7c11dda69095\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.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 = \"a7cf690d0ac3f5b53dd09b5d613540b230233647\"\nuuid = \"ab02a1b2-a7df-11e8-156e-fb1833f50b87\"\nversion = \"1.0.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 = \"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[[Widgets]]\ndeps = [\"Colors\", \"Dates\", \"Observables\", \"OrderedCollections\"]\ngit-tree-sha1 = \"eae2fbbc34a79ffd57fb4c972b08ce50b8f6a00d\"\nuuid = \"cc8bc4a8-27d6-5769-a93b-9d913e69aa62\"\nversion = \"0.6.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_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# \u2554\u2550\u2561 Cell order:\n# \u2560\u255050cd5676-cdba-425d-84d3-7ad6fe21a2d5\n# \u2560\u25508ae7bb38-5803-41d0-98e3-6d9dc4936406\n# \u2560\u255003eb200d-c3b4-43d6-b86f-017f5454bc86\n# \u2560\u2550035ad037-d231-4a7b-a451-213085be2eb4\n# \u255f\u2500243d8dbd-0f8f-4604-bdb9-9c9078e906be\n# \u2560\u25507fa5fed0-63a9-4332-a808-95e2b7bcf09d\n# \u2560\u2550b1f928d8-7175-4bd3-9adc-9cb93b0dbb40\n# \u2560\u2550ad7091a0-399f-49ee-b273-4976ecb1b75e\n# \u2560\u255013abedaa-7df4-48c6-8d61-d81c8d585be8\n# \u2560\u2550ef8592b6-7474-410c-9171-187893239151\n# \u2560\u2550e3a0e0c3-1a96-4a9d-bbe3-a25061b1ee12\n# \u2560\u2550228a6067-bddf-4e6e-b3d8-2a6ac47d3904\n# \u2560\u255008be5eef-4bdc-4ee6-8e5e-507c8055c07e\n# \u2560\u2550890fe7ce-d6cd-49c2-b888-421971118d8d\n# \u2560\u25507ba339f1-b03e-49d7-9821-bd731ffe664d\n# \u2560\u2550e8657ff4-4c7f-401c-a3e7-5098a90d99e5\n# \u2560\u2550798a62d7-700b-400e-9bc9-efbe0b7758bc\n# \u2560\u2550cb4c6cbb-5e44-49da-b82f-3551a1b3abbf\n# \u2560\u2550235956e8-e4d6-49bc-b175-d7c2aed732a8\n# \u2560\u25503e2cd644-1f53-4f51-891b-c54ae816f557\n# \u2560\u25507cc0d1e9-3cab-48cc-b873-181e006a620e\n# \u2560\u2550462e8b4d-5bf1-4153-b9d5-46b74f308721\n# \u2560\u2550bff6a040-8d4a-4f00-a4e9-9f8147a21b41\n# \u2560\u2550f24f1556-cf68-4f54-bb35-7ac9b01d0a85\n# \u2560\u25504ae90a2a-67f1-4dc9-b6ed-d2e2e85aadd7\n# \u2560\u255009f9e4c9-315f-4433-b021-08150d6ce413\n# \u2560\u2550f0e6437c-609e-48f9-abc8-f3d325f35ec3\n# \u2560\u2550cb0c1428-5146-4402-93ef-27c3cd4fd9d4\n# \u255f\u25003438d796-9efc-44d0-9c08-a6c90305dee0\n# \u2560\u2550e8139300-8097-4ba0-96e3-5135047c70d7\n# \u2560\u25508103f855-a617-438b-8cb9-8fa0e7fde319\n# \u2560\u25503fdd5a77-45df-494e-9786-c8aa22daa82e\n# \u2560\u2550341c32a3-3fae-472b-8771-c7f9fbaf4704\n# \u2560\u255020fd7570-5c1f-4316-87f3-b972a1a0364f\n# \u2560\u25500bb71f07-9381-4e77-9fe3-1c59854d18f5\n# \u2560\u25508bfed4f2-724c-44ea-b6f4-02c836391be7\n# \u2560\u255064460f92-6dd3-4c13-b3b9-bb2660436b40\n# \u2560\u25507b8a3922-21a9-4905-84ad-e2d8edf51cce\n# \u2560\u2550bbf05eef-188d-4e31-ae40-f85a8269a3b6\n# \u2560\u255016e5e214-d5b7-480e-8243-9cbf36ababf8\n# \u2560\u2550e252ca21-48d3-49f4-9bee-649a5610240a\n# \u2560\u2550933d49c9-31fc-4d02-9b83-d523bf828476\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "5902c1d91c8f2b1f4ee5ec4cd9362ac3c97e3e6a", "size": 56644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SIR_model.jl", "max_stars_repo_name": "bit-player/Covidcurve", "max_stars_repo_head_hexsha": "6780ea081bcc9b09c8724649998bdb38da3549f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SIR_model.jl", "max_issues_repo_name": "bit-player/Covidcurve", "max_issues_repo_head_hexsha": "6780ea081bcc9b09c8724649998bdb38da3549f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SIR_model.jl", "max_forks_repo_name": "bit-player/Covidcurve", "max_forks_repo_head_hexsha": "6780ea081bcc9b09c8724649998bdb38da3549f2", "max_forks_repo_licenses": ["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.4979919679, "max_line_length": 656, "alphanum_fraction": 0.7199879952, "num_tokens": 24908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7518940134287349}}
{"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\u00d73 LinearAlgebra.Diagonal{Int64, Vector{Int64}}:\n 2  \u22c5  \u22c5\n \u22c5  1  \u22c5\n \u22c5  \u22c5  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\u03c4 have to be read and written (dHd\u03c4 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\u00b3s\u207b\u00b2\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\u0394t = 1  # seconds\ntotal_time = 1*24*60*60  # seconds\nt_range = Array(0:\u0394t:total_time);\nmin_elevation = 10  # degrees\n\n# GPS\na = 26_560e3;  # m\nplane_num = 6;\nsat_per_plane = 4;\nincl = 56;\n\u0394\u03a9 = 360/plane_num;\n\u0394f_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2\u03c0*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                                           \u0394\u03a9=\u0394\u03a9,\n                                           \u0394f_per_plane=\u0394f_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\u2091+780*1000;  # meters\nplane_num = 6;\nsat_per_plane = 11;\nincl = 86;\n\u0394\u03a9 = 360/plane_num/2;\n\u0394f_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2\u03c0*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                                            \u0394\u03a9=\u0394\u03a9,\n                                            \u0394f_per_plane=\u0394f_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\u2091+550*1000;  # meters\nplane_num = 24;\nsat_per_plane = 66;\nincl = 53;\n\u0394\u03a9 = 360/plane_num;\n\u0394f_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2\u03c0*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                                            \u0394\u03a9=\u0394\u03a9,\n                                            \u0394f_per_plane=\u0394f_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\u2091+1200*1000;  # meters\nplane_num = 18;\nsat_per_plane = 36;\nincl = 87.9;  # degrees\n\u0394\u03a9 = 360/plane_num/2;\n\u0394f_per_plane = 360/sat_per_plane/2;  # degrees\norbital_period = 2\u03c0*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                                            \u0394\u03a9=\u0394\u03a9,\n                                            \u0394f_per_plane=\u0394f_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    \ud835\udca2(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\ud835\udca2(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\u00f72\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\u00f72\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}, \u03ba::Int) where T\n    M, N = size(A)\n    m, n = M, N\u00f72\n    C = zeros(T, m, 2n+1)\n    @inbounds for i = 1:m\n        C[i,1] = binomial(m+\u03ba-i, m-i)/binomial(m+\u03ba-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        \u0394 = [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] + \u0394[1]\n        x_interp = x[xi,yi] + \u0394[2]\n    elseif edge == E\n        \u0394 = [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] + \u0394[1]\n        x_interp = x[xi+1,yi] + \u0394[2]\n    elseif edge == N\n        \u0394 = [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] + \u0394[1]\n        x_interp = x[xi,yi+1] + \u0394[2]\n    elseif edge == S\n        \u0394 = [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] + \u0394[1]\n        x_interp = x[xi,yi] + \u0394[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\u209c 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  \u03b2, 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 \u2208 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  \u03b2 = inv(x'x)*(x'y)\n  \u03f5 = y - x*\u03b2\n  yhat = x*\u03b2\n  sse = \u03f5'\u03f5\n  \u03c32_y = sse/(T-k)\n  \u03a3\u2093 = inv(x'x)\n  \u03a3\u1d66 = \u03c32_y.*\u03a3\u2093\n  t_stat = \u03b2./sqrt.(diag(\u03a3\u1d66))\n  bic = (T-k).*log(sse./(T-k)) .+ k.*log(T-k)\n  resid = y - x*\u03b2\n  return \u03b2, 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-\u03b1\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  \u03bc = (X+z^2/2)/m\n\n  ## Bounds calculation\n  \u03c3 = sqrt(q*(1-q)/m)\n  lower = \u03bc-z*\u03c3\n  upper = \u03bc+z*\u03c3\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  \u03b1 = 1-confidence\n  lower = quantile(Beta(x+1/2, n-X+1/2), \u03b1/2)\n  upper = quantile(Beta(x+1/2, n-X+1/2), 1-\u03b1/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": "using SpecialFunctions\n\n\n\"\"\"\n    mc_volume(i, xs, nmc, searcher)\n\nEstimate the area and volume of the `i`-th Voronoi cell from the Voronoi Diagram generated by `xs`\nby a Monte Carlo estimate from random rays\n\"\"\"\nfunction mc_volume(i, xs, nmc=1000, searcher = Raycast(xs))\n    y, \u03b4y, V, A = mc_integrate(x->1, i, xs, nmc, 0, searcher)\n    A, V\nend\n\n\"\"\"\n    mc_volumes(xs::Points, nmc=1000)\n\nEstimate the areas and volumes of the Voronoi Cells generated by `xs` using `nmc` Monte Carlo samples.\n\n# Returns\n- `SparseMatrix`: the areas of the common boundaries of two cells\n- `Vector`: the volumes of each cell\n\"\"\"\nfunction mc_volumes(xs::Points, nmc=1000)\n    V = zeros(length(xs))\n    A = spzeros(length(xs), length(xs))\n\n    searcher = Raycast(xs)\n\n    for i in 1:length(xs)\n        a, v = mc_volume(i, xs, nmc, searcher)\n        V[i] = v\n        A[:, i] = a\n    end\n    #A = (A + A') / 2\n    A, V\nend\n\n\"\"\"\n    mc_volumes(sig::Vertices, xs::Points, nmc=1000)\n\nIn the case when the simplicial complex is already known this information can be used\nto speed up the Monte-Carlo sampling by restricting the search space\n\"\"\"\nfunction mc_volumes(\u03c3::Vertices, xs::Points, nmc=1000)\n    V = zeros(length(xs))\n    A = spzeros(length(xs), length(xs))\n\n    searcher = Raycast(xs)\n    neigh = neighbors(\u03c3)\n\n    for i in 1:length(xs)\n        ix = [i; neigh[i]]\n        a, v = mc_volume(1, xs[ix], nmc, RaycastBruteforce())\n        V[i] = v\n        A[ix, i] = a\n    end\n    #A = (A + A') / 2\n    A, V\nend\n\n\"\"\"\n    neighbors(sig::Vertices) --> Dict{Int, Vector{Int}}\nCompute the neighbors of all generators.\n\"\"\"\nneighbors(\u03c3::Vertices) = neighbors(keys(\u03c3))\nfunction neighbors(\u03c3)\n    d = Dict{Int, Vector{Int}}()\n    for s in \u03c3\n        for i in s\n            v = get!(d, i, Vector{Int}())\n            append!(v, s)\n        end\n    end\n    for i in keys(d)\n        unique!(d[i])\n        filter!(x->x != i, d[i])\n    end\n    return d\nend\n\n\"\"\"\n    mc_integrate(f::Function, i::Int, xs::Points, nmc=1000, nmc2=1000, searcher=Raycast(xs))\nIntegrate function `f` over cell `i` and its boundary using `nmc` rays per cell and `nmc2` points per ray for the volume integral.\n\n# Returns:\n- `Vf::Real`: the volume integral of `f`\n- `Af::SparseVector`: Af[j] is the surface integral of `f` over the intersection between cells i and j.\n- `V::Real`: the volume of cell `i`\n- `A::SparseVector`: A[j] is the surface area of the intersection between cells i and j.\n\"\"\"\nfunction mc_integrate(f::Function, i::Int, xs::Vector, nmc=1000, nmc2=1000, searcher = Raycast(xs))\n    x = xs[i]\n    d = length(x)\n\n    # volume/area computations are basically for free, leaving them commented for now\n    V = 0.\n    A = spzeros(length(xs))\n\n    y = 0.\n    \u03b4y = spzeros(length(xs))\n\n    for _ in 1:nmc\n        u = normalize(randn(d))\n        (j, t) = raycast([i], x, u, xs, searcher)\n\n        V += t^d\n        for _ in 1:nmc2\n            r = t * rand()\n            x\u2032 = x + u * r\n            y += f(x\u2032) * r^(d-1) * t\n        end\n\n        if t < Inf\n            j = j[1] == i ? j[2] : j[1]\n            normal = normalize(xs[j] - xs[i])\n            dA = t ^ (d-1) / abs(dot(normal, u))\n            A[j] += dA\n            \u03b4y[j] += dA * f(x + t*u)\n        end\n    end\n\n    c_vol = pi^(d/2) / gamma(d/2 + 1)\n    c_area = d * c_vol\n\n    V *= c_vol / nmc\n    A *= c_area / nmc\n\n    y *= c_area / nmc / nmc2\n    \u03b4y *= c_area / nmc\n\n    y, \u03b4y, V, A\nend\n\nfunction mc_integrate(f, \u03c3::Vertices, xs::Points, nmc, nmc2)\n    return mc_integrate_i((x,i)->f(x), \u03c3, xs, nmc, nmc2)\nend\n\n# MC integration using f(x, i) function which is also passed the index of the cell\nfunction mc_integrate_i(f, \u03c3::Vertices, xs::Points, nmc, nmc2)\n    n = length(xs)\n    ys = zeros(n)\n    \u2202ys = zeros(n)\n\n    neigh = neighbors(\u03c3)\n\n    for i in 1:n\n        ix = [i; neigh[i]]\n        y, \u2202y, V, A = mc_integrate(x->f(x, i), 1, xs[ix], nmc, nmc2, RaycastBruteforce())\n        ys[i] = y\n        \u2202ys[i] = sum(\u2202y)\n    end\n    return ys, \u2202ys\nend\n", "meta": {"hexsha": "5cdc33942f195af419cf8e0e0a7056811d89f7b5", "size": 3954, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/montecarlo.jl", "max_stars_repo_name": "axsk/VoronoiGraph.jl", "max_stars_repo_head_hexsha": "5ac0d75489a814bd7ab6fb6c5a667ecf0977517c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/montecarlo.jl", "max_issues_repo_name": "axsk/VoronoiGraph.jl", "max_issues_repo_head_hexsha": "5ac0d75489a814bd7ab6fb6c5a667ecf0977517c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-19T09:06:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T14:09:03.000Z", "max_forks_repo_path": "src/montecarlo.jl", "max_forks_repo_name": "axsk/VoronoiGraph.jl", "max_forks_repo_head_hexsha": "5ac0d75489a814bd7ab6fb6c5a667ecf0977517c", "max_forks_repo_licenses": ["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.5096774194, "max_line_length": 130, "alphanum_fraction": 0.5720789074, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7518762591556996}}
{"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, \u201cA new method for gray-level picture thresholding using the entropy of the histogram,\u201d *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    \u03a8\u2098\u2090\u2093 = 0\n    H\u209b = H(pdf)\n    H\u2099 = -1*H\u209b[nbins]\n    P\u209b = cumsum(pdf)\n    # P\u209b might exceed 1 for float-point numerical stability issue (issue #35)\n    P\u209b = _maybe_inplace_clamp01(P\u209b)\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\u1d62 = P\u209b[i]\n        H\u1d62 = -1*H\u209b[i]\n        \u03a8\u1d62 = log(P\u1d62*(1-P\u1d62)) + (H\u1d62/P\u1d62) + ((H\u2099-H\u1d62)/(1-P\u1d62))\n        if \u03a8\u1d62 > \u03a8\u2098\u2090\u2093\n            \u03a8\u2098\u2090\u2093 = \u03a8\u1d62\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 Test\nusing ForwardDiff;\nusing FinancialToolbox\nDual_ = ForwardDiff.Dual\nprint_colored(\"Starting Forward Diff Dual Numbers Test\\n\", :green)\n\n#Test Parameters\ntestToll = 1e-14;\nspot = 10;\nK = 10;\nr = 0.02;\nT = 2.0;\nsigma = 0.2;\nd = 0.01;\nassert_(value, toll) = @test abs(value) < toll\n#EuropeanCall Option\nPriceCall = blsprice(spot, K, r, T, sigma, d);\nDeltaCall = blsdelta(spot, K, r, T, sigma, d);\nThetaCall = blstheta(spot, K, r, T, sigma, d);\nRhoCall = blsrho(spot, K, r, T, sigma, d);\nLambdaCall = blslambda(spot, K, r, T, sigma, d);\nVannaCall = blsvanna(spot, K, r, T, sigma, d);\n\n#EuropeanPut Option\nPricePut = blsprice(spot, K, r, T, sigma, d, false);\nDeltaPut = blsdelta(spot, K, r, T, sigma, d, false);\nThetaPut = blstheta(spot, K, r, T, sigma, d, false);\nRhoPut = blsrho(spot, K, r, T, sigma, d, false);\nLambdaPut = blslambda(spot, K, r, T, sigma, d, false);\nVannaPut = blsvanna(spot, K, r, T, sigma, d, false);\n\n#Equals for both Options\nGamma = blsgamma(spot, K, r, T, sigma, d);\nVega = blsvega(spot, K, r, T, sigma, d);\n\n########DUAL NUMBERS\nDerToll = 1e-13;\n#Function definition\n#Call\nFcallDual(spot) = blsprice(spot, K, r, T, sigma, d);\nGcallDual(r) = blsprice(spot, K, r, T, sigma, d);\nHcallDual(T) = blsprice(spot, K, r, T, sigma, d);\nLcallDual(sigma) = blsprice(spot, K, r, T, sigma, d);\nPcallDual(spot) = blsprice(spot, K, r, T, sigma, d) * spot.value / blsprice(spot.value, K, r, T, sigma, d);\nVcallDual(sigma) = blsdelta(spot, K, r, T, sigma, d);\n#Put\nFputDual(spot) = blsprice(spot, K, r, T, sigma, d, false);\nGputDual(r) = blsprice(spot, K, r, T, sigma, d, false);\nHputDual(T) = blsprice(spot, K, r, T, sigma, d, false);\nPputDual(spot) = blsprice(spot, K, r, T, sigma, d, false) * spot.value / blsprice(spot.value, K, r, T, sigma, d, false);\nVPutDual(sigma) = blsdelta(spot, K, r, T, sigma, d, false);\n#Input\nSpotDual = Dual_(spot, 1.0);\nrDual = Dual_(r, 1.0);\nTDual = Dual_(T, 1.0);\nSigmaDual = Dual_(sigma, 1.0);\n\n#Automatic Differentiation Test\n#TEST\nprint_colored(\"--- European Call Sensitivities: DualNumbers\\n\", :yellow)\nprint_colored(\"-----Testing Delta\\n\", :blue);\nassert_(FcallDual(SpotDual).partials[1] - DeltaCall, DerToll)\nprint_colored(\"-----Testing Rho\\n\", :blue);\nassert_(GcallDual(rDual).partials[1] - RhoCall, DerToll)\nprint_colored(\"-----Testing Theta\\n\", :blue);\nassert_(-HcallDual(TDual).partials[1] - ThetaCall, DerToll)\nprint_colored(\"-----Testing Lambda\\n\", :blue);\nassert_(PcallDual(SpotDual).partials[1] - LambdaCall, DerToll)\nprint_colored(\"-----Testing Vanna\\n\", :blue);\nassert_(VcallDual(SigmaDual).partials[1] - VannaCall, DerToll)\n#TEST\nprint_colored(\"--- European Put Sensitivities: DualNumbers\\n\", :yellow)\nprint_colored(\"-----Testing Delta\\n\", :blue);\nassert_(FputDual(SpotDual).partials[1] - DeltaPut, DerToll)\nprint_colored(\"-----Testing Rho\\n\", :blue);\nassert_(GputDual(rDual).partials[1] - RhoPut, DerToll)\nprint_colored(\"-----Testing Theta\\n\", :blue);\nassert_(-HputDual(TDual).partials[1] - ThetaPut, DerToll)\nprint_colored(\"-----Testing Lambda\\n\", :blue);\nassert_(PputDual(SpotDual).partials[1] - LambdaPut, DerToll)\nprint_colored(\"-----Testing Vanna\\n\", :blue);\nassert_(VPutDual(SigmaDual).partials[1] - VannaPut, DerToll)\n\nprint_colored(\"-----Testing Vega\\n\", :blue);\nassert_(LcallDual(SigmaDual).partials[1] - Vega, DerToll)\nprint_colored(\"Dual Numbers Test Passed\\n\", :green)\nprintln(\"\")\n\n#TEST OF INPUT VALIDATION\nprint_colored(\"Starting Input Validation Test Dual\\n\", :magenta)\nprint_colored(\"----Testing Negative  Spot Price \\n\", :cyan)\n@test_throws(ErrorException, blsprice(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blkprice(-SpotDual, K, r, T, sigma))\n@test_throws(ErrorException, blsdelta(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blsgamma(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blstheta(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blsrho(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blspsi(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blslambda(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blsvanna(-SpotDual, K, r, T, sigma, d))\n@test_throws(ErrorException, blsvega(-SpotDual, K, r, T, sigma, d))\n\nprint_colored(\"----Testing Negative  Strike Price \\n\", :cyan)\nKK = Dual_(K, 0);\n@test_throws(ErrorException, blsprice(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blkprice(spot, -KK, r, T, sigma))\n@test_throws(ErrorException, blsdelta(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blsgamma(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blstheta(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blsrho(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blspsi(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blslambda(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blsvanna(spot, -KK, r, T, sigma, d))\n@test_throws(ErrorException, blsvega(spot, -KK, r, T, sigma, d))\n\nprint_colored(\"----Testing Negative  Time to Maturity \\n\", :cyan)\n@test_throws(ErrorException, blsprice(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blkprice(spot, K, r, -TDual, sigma))\n@test_throws(ErrorException, blsdelta(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blsgamma(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blstheta(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blsrho(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blspsi(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blslambda(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blsvanna(spot, K, r, -TDual, sigma, d))\n@test_throws(ErrorException, blsvega(spot, K, r, -TDual, sigma, d))\n\nprint_colored(\"----Testing Negative  Volatility \\n\", :cyan)\n@test_throws(ErrorException, blsprice(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blkprice(spot, K, r, T, -SigmaDual))\n@test_throws(ErrorException, blsdelta(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blsgamma(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blstheta(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blsrho(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blspsi(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blslambda(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blsvanna(spot, K, r, T, -SigmaDual, d))\n@test_throws(ErrorException, blsvega(spot, K, r, T, -SigmaDual, d))\n\nprint_colored(\"Dual Input Validation Test Passed\\n\", :magenta)", "meta": {"hexsha": "74c865966945e44510ad417229401ff5be0b8a51", "size": 6484, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testForwardDiff.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": "test/testForwardDiff.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": "test/testForwardDiff.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": 46.3142857143, "max_line_length": 120, "alphanum_fraction": 0.7031153609, "num_tokens": 2251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7518762573550767}}
{"text": "include(\"linear_regressor.jl\")\ninclude(\"ridge_regressor.jl\")\ninclude(\"bayesian_regressor.jl\")\ninclude(\"empirical_bayesian_regressor.jl\")\n", "meta": {"hexsha": "e88e145a2693a7f904131bf1077aaddba49100db", "size": 137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear/linear.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.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.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": 27.4, "max_line_length": 42, "alphanum_fraction": 0.8248175182, "num_tokens": 37, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7518762550679706}}
{"text": "struct FEMProblem\n    s # system\n    coords\n    connec\n    neumdofs\n    fixeddofs\n    b # Forcing term\n    Fnotzerocoord\nend\n\n_homogeneize(p::FEMProblem) = _homogeneize(p.s.M, p.s.K, p.b)\n\n# nodes of interest:\n#    nodeidx_hor = 3\n#    nodeidx_ver = 4\nfunction load_lambs(; mesh=1,\n                      file_matrices=joinpath(@__DIR__, \"mesh$mesh\", \"matrices.mat\"),\n                      file_mesh=joinpath(@__DIR__, \"mesh$mesh\", \"mesh.mat\"),\n                      file_loads=joinpath(@__DIR__, \"mesh$mesh\", \"loads.mat\"))\n\n    # load matrices\n    d = matread(file_matrices)\n    K = d[\"KTred\"]\n    M = d[\"massMatred\"]\n    @assert isdiag(M)\n    M = Diagonal(M) # it is diagonal\n    n = size(K, 1)\n    C = spzeros(n, n)\n    sys = SecondOrderLinearContinuousSystem(M, C, K)\n\n    neumdofs = d[\"neumdofs\"]\n    neumdofs = Int.(neumdofs)[:]\n\n    # load mesh\n    mesh = matread(file_mesh)\n    coords = mesh[\"mesh\"][\"nodesCoords\"]\n    connec = mesh[\"mesh\"][\"conecCell\"]\n    connec = Int.(connec)\n\n    # fixed degrees of freedom\n    fixeddofs = setdiff(1:6*size(coords, 1), neumdofs)\n\n    # load external force definition\n    df = matread(file_loads)\n    F = df[\"factorLoadsFextCell\"][1, 3][:]\n    F = F[neumdofs]\n    Fnotzerocoord = findall(!iszero, F)\n\n    return FEMProblem(sys, coords, connec, neumdofs, fixeddofs, F, Fnotzerocoord)\nend\n\n# ======================\n# Funciones de carga\n# ======================\n\nHeaviside(t) = t >= 0 ? 1 : 0\n\n# funcion auxiliar que devuelve el factor de carga aplicado en la coordenada coord\nfunction factor_de_carga(m, NSTEPS; T=1.0, coord=5, func=Heaviside)\n    tiempos = range(0.0, T, length=NSTEPS)\n\n    F = Vector{Vector{Float64}}(undef, NSTEPS)\n    for i in 1:NSTEPS\n        aux = zeros(m)\n        aux[coord] .= func(tiempos[i])\n\n        F[i] = aux\n    end\n    return F\nend\n\nfunction step_size_lamb(p, \u03b4tfac)\n    nElem = sum(p.connec[:, 2] .== 3) # number of triangular elements\n    CFL = 0.125\n    cP  = 3200\n    h   = sqrt(2*3200^2 / nElem) * \u03b4tfac\n    \u03b4t = CFL * h / cP\nend\n", "meta": {"hexsha": "480b1096ffb3bebfe68e8164918a0a0ca88f7a48", "size": 2009, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LambsWave/lambs_modelo.jl", "max_stars_repo_name": "JuliaReach/SetPropagation-FEM-Examples", "max_stars_repo_head_hexsha": "8ee58bdbc1e253b9ca2ddb60973a6b6f1e82cd94", "max_stars_repo_licenses": ["MIT"], "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/LambsWave/lambs_modelo.jl", "max_issues_repo_name": "JuliaReach/SetPropagation-FEM-Examples", "max_issues_repo_head_hexsha": "8ee58bdbc1e253b9ca2ddb60973a6b6f1e82cd94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-26T18:32:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T23:33:44.000Z", "max_forks_repo_path": "examples/LambsWave/lambs_modelo.jl", "max_forks_repo_name": "JuliaReach/SetPropagation-FEM-Examples", "max_forks_repo_head_hexsha": "8ee58bdbc1e253b9ca2ddb60973a6b6f1e82cd94", "max_forks_repo_licenses": ["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.4303797468, "max_line_length": 84, "alphanum_fraction": 0.5953210553, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7518762489363773}}
{"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": "@testset \"ClosestVector.jl\" begin\n    #=\n    The quadratic triple QT = [Q, L, c] is an n-dimensional ellipsoid with rational coefficients.\n    Where,\n    Q is an nxn symmetric matrix of the quadratic form , \n    L is a rational column vector of length n &\n    c is a rational number\n    =#\n    Q = matrix(QQ,3,3,[1 0 0; 0 1 0; 0 0 1]);\n    L = matrix(QQ,3,1,[1,0,0]);\n    c = fmpq(2//5);\n    Lat = Zlattice(gram = matrix(QQ,3,3,[1,0,0,0,1,0,0,0,1]));\n    v = convert(Array{Union{RingElem, AbstractFloat, Integer, Rational},1},[-1,0,0]);\n    u = fmpq(3//5);\n    @test Hecke.closest_vectors(Q,L,c)[1] == Hecke.closest_vectors(Lat, v, u)[1]\n\n    function compare_functions(Q::MatrixElem, K::MatrixElem, d::RingElement)\n        List1 = Hecke.closest_vectors(Q, K, d);\n        L, v, c = Hecke.convert_type(Q, K, d)\n        List2 = Hecke.closest_vectors(L, v, c);\n        for i in 1:length(List1)\n            if List1[i] == List2[i]\n                return true\n            else\n                error(\"$i-th entry of the two lists don't match.\")\n            end\n        end\n    end\n  \n    function compare_functions(L::ZLat, v::Vector{RingElement} , upperbound::RingElement)\n        List1 = Hecke.closest_vectors(L, v, upperbound);\n        Q, K, d = Hecke.convert_type(L, v, upperbound);\n        List2 = Hecke.closest_vectors(Q, K, d);\n        for i in 1:length(List1)\n            if List1[i] == List2[i]\n                return true\n            else\n                error(\"$i-th entry of the two lists don't match.\")\n            end\n        end\n    end\n  \n    #EXAMPLE 1a: 3-dimensional sphere\n    Q1 = matrix(QQ,3,3,[1 0 0; 0 1 0; 0 0 1]);\n    L1 = matrix(QQ,3,1,[1,1,1]);\n    c1 = 1;\n\n    #EXAMPLE 1b: 4-dimensional sphere\n    Q2 = matrix(QQ, 4,4,[1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]);\n    L2 = matrix(QQ, 4, 1 ,[1,1,1,1]);\n    c2 = 3;\n\n    #EXAMPLE 1c: 6-dimensional sphere\n    Q3 = matrix(QQ,6,6,[1 0 0 0 0 0; 0 1 0 0 0 0; 0 0 1 0 0 0; 0 0 0 1 0 0; 0 0 0 0 1 0; 0 0 0 0 0 1]);\n    L3 = matrix(QQ,6,1,[1,0,1,0,2,0]);\n    c3 = fmpq(4//3);\n\n    #-----------------------------------------------------------------------------\n\n    #Examples for closest_vectors()\n    #Example 1:\n    Lat1 = Zlattice(gram = matrix(QQ,3,3,[1,0,0,0,1,0,0,0,1]));\n    v1 = convert(Array{Union{RingElem, AbstractFloat, Integer, Rational},1},[-1,0,0]);\n    u1 = fmpq(3//5);\n\n    #Example 1:\n    Lat2 = Zlattice(gram = matrix(QQ,4,4,[1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]));\n    v2 = convert(Array{Union{RingElem, AbstractFloat, Integer, Rational},1},[-1,-1,-1,-1]);\n    u2 = fmpq(41//11);\n\n    #Example 1:\n    Lat3 = Zlattice(gram = matrix(QQ,6,6,[1,0,0,0,0,0, 0,1,0,0,0,0, 0,0,1,0,0,0, 0,0,0,1,0,0, 0,0,0,0,1,0, 0,0,0,0,0,1]));\n    v3 = convert(Array{Union{RingElem, AbstractFloat, Integer, Rational},1},[-1,0,-1,0,-2,0]);\n    u3 = fmpq(14//3);\n\n    @testset \"Comparing closest_vectors(Q, K, d) to closest_vectors(Lat, vec, upperbound) list\" begin\n        @test compare_functions(Q1, L1, c1) == true\n        @test compare_functions(Q2, L2, c2) == true\n        @test compare_functions(Q3, L3, c3) == true\n    end\n\n    @testset \"Comparing closest_vectors(Lat, vec, upperbound) list to closest_vectors(Q, K, d)\" begin\n        @test compare_functions(Lat1, v1, u1) == true\n        @test compare_functions(Lat2, v2, u2) == true\n        @test compare_functions(Lat3, v3, u3) == true\n    end\n\n\n    @testset \"Conversion from Quadratic Triple set to Closest Vector Enumeration input parameters\" begin\n        Q3 = matrix(QQ,6,6,[1 0 0 0 0 0; 0 1 0 0 0 0; 0 0 1 0 0 0; 0 0 0 1 0 0; 0 0 0 0 1 0; 0 0 0 0 0 1]);\n        L3 = matrix(QQ,6,1,[1,0,1,0,2,0]);\n        c3 = fmpq(4//3);\n        cvp = Hecke.convert_type(Q3,L3,c3);\n        @test  det(basis_matrix(cvp[1])) == 1\n        @test cvp[2] == [-1, 0, -1, 0, -2, 0]\n        @test cvp[3] == 14//3\n    end\n      \n    @testset \"Conversion from Closest Vector Enumeration to Quadratic Triple set input parameters\" begin\n        Lat = Zlattice(gram = matrix(QQ,3,3,[1,0,0,0,1,0,0,0,1]));\n        vec = convert(Array{Union{RingElem, AbstractFloat, Integer, Rational},1},[-1,-1,-1]);\n        upbound = 2;\n        qt = Hecke.convert_type(Lat, vec, upbound);\n        @test qt[1] == matrix(QQ,3,3,[1 0 0; 0 1 0; 0 0 1])\n        @test qt[2] == matrix(QQ,3,1,[1,1,1])\n        @test qt[3] == 1\n    end\n  \n  @testset \"Quadratic Triple Tests\" begin\n      @testset \"Projective Quadratic Triple\" begin\n            Q = matrix(QQ, 4,4,[1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]);\n            L = matrix(QQ, 4, 1 ,[1,1,1,1]);\n            c = 3;          \n            @test Hecke.pojective_quadratic_triple(Q, L, c, 1) == (Q[1:1, 1:1], L[1:1,1:1], 0)\n            @test Hecke.pojective_quadratic_triple(Q, L, c, 4) == (Q, L, c)\n        end\n    \n        @testset \"Finite set of integers for a 1-dimensional quadratic triple\" begin\n            Q = matrix(QQ, 4,4,[1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]);\n            L = matrix(QQ, 4, 1 ,[1,1,1,1]);\n            c = 3;\n            Q1 = Hecke.pojective_quadratic_triple(Q, L, c, 1)[1];\n            L1 = Hecke.pojective_quadratic_triple(Q, L, c, 1)[2];\n            c1 = Hecke.pojective_quadratic_triple(Q, L, c, 1)[3];\n            @test Hecke.range_ellipsoid_dim1(Q1, L1, c1) == -2:0\n        end\n    \n        @testset \"Different Types of Extended Quadratic Triple\" begin\n            @testset \"Quadratic triple extension from a 1-dimensional quadratic triple\" begin\n                Q = matrix(QQ, 4,4,[1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]);\n                L = matrix(QQ, 4, 1 ,[1,1,1,1]);\n                c = 3;\n                @test Hecke.positive_quadratic_triple(fmpz(1), Q, L, c)[1] == Q[2:4, 2:4]\n                @test Hecke.positive_quadratic_triple(fmpz(1), Q, L, c)[2] == L[2:4,1:1]\n                @test Hecke.positive_quadratic_triple(fmpz(1), Q, L, c)[3] == 6\n            end\n\n            @testset \"Quadratic triple extension from a m-dimensional quadratic triple to m+n-1 quadratic triple\" begin\n                Q = matrix(QQ, 4,4,[1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]);\n                L = matrix(QQ, 4, 1 ,[1,1,1,1]);\n                c = 3;\n                @test Hecke.positive_quadratic_triple2(fmpz[-2,0,1], Q,L,c)[1][1] == 1  \n                @test Hecke.positive_quadratic_triple2(fmpz[-2,0,1], Q,L,c)[2][1] == 1\n                @test Hecke.positive_quadratic_triple2(fmpz[-2,0,1], Q,L,c)[3] == 6\n            end\n        end \n    end\n\n    @testset \"Finite set tests\" begin\n        Q = matrix(QQ, 4,4,[1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]);\n        Q1 = -Q;\n        L = matrix(QQ, 4, 1 ,[1,1,1,1]);\n        c = 3;\n        @test Hecke.closest_vectors(Q, L, c)[1] == [-2, -1, -1, -1]\n        @test size(Hecke.closest_vectors(Q, L, c), 1) == 9 \n        @test Hecke.closest_vectors(Q, L, c)[1] == Hecke.closest_vectors(Q1,L,c)[1]\n\n        x = matrix(QQ, 4, 1, Hecke.closest_vectors(Q, L, c)[5]);\n        xt = transpose(matrix(QQ, 4, 1, Hecke.closest_vectors(Q, L, c)[5]));\n        R = xt * Q * x + 2 * xt * L + c;\n        @test  R[1] <= 0 \n\n        y = matrix(QQ, 4, 1, Hecke.closest_vectors(Q1, L, c)[5]);\n        yt = transpose(matrix(QQ, 4, 1, Hecke.closest_vectors(Q1, L, c)[5]));\n        S = yt * Q * y + 2 * yt * L + c;\n        @test  S[1] <= 0 \n    end\nend\n", "meta": {"hexsha": "60a774f206280613173225b7e5df9fb90b12ad9c", "size": 7195, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/QuadForm/ClosestVector.jl", "max_stars_repo_name": "albinahlback/Hecke.jl", "max_stars_repo_head_hexsha": "728be6098a8dbfe2589fca77e57f10950cefe9e7", "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": "test/QuadForm/ClosestVector.jl", "max_issues_repo_name": "albinahlback/Hecke.jl", "max_issues_repo_head_hexsha": "728be6098a8dbfe2589fca77e57f10950cefe9e7", "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": "test/QuadForm/ClosestVector.jl", "max_forks_repo_name": "albinahlback/Hecke.jl", "max_forks_repo_head_hexsha": "728be6098a8dbfe2589fca77e57f10950cefe9e7", "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": 42.573964497, "max_line_length": 122, "alphanum_fraction": 0.5317581654, "num_tokens": 2796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793113, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.751872814519122}}
{"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": "using ODEInterfaceDiffEq, DiffEqProblemLibrary, DiffEqBase\nusing Test\n\njac_called = false\n\nfunction Lotka(du,u,p,t)\n  du[1] = u[1] - u[1] * u[2] # REPL[7], line 3:\n  du[2] = -3 * u[2] + 1 * u[1] * u[2]\n  nothing\nend\n\nfunction Lotka_jac(J,u,p,t)\n  global jac_called\n  jac_called = true\n  J[1,1] = 1.0 - u[2]\n  J[1,2] = -u[1]\n  J[2,1] = 1 * u[2]\n  J[2,2] = -3 + u[1]\n  nothing\nend\n\nprob = ODEProblem(ODEFunction(Lotka,jac=Lotka_jac),ones(2),(0.0,2.0))\n\nsol =solve(prob,radau5();dt=1//2^(4))\n\n@test jac_called == true\n", "meta": {"hexsha": "44e0f4a7354bf173d9430acc19ff486d9287afa3", "size": 515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/jac_tests.jl", "max_stars_repo_name": "AnasAbdelR/ODEInterfaceDiffEq.jl", "max_stars_repo_head_hexsha": "490c25fe96e379a313c660423f1eec2d1e8f758b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-04-08T18:57:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-25T03:03:27.000Z", "max_issues_repo_path": "test/jac_tests.jl", "max_issues_repo_name": "AnasAbdelR/ODEInterfaceDiffEq.jl", "max_issues_repo_head_hexsha": "490c25fe96e379a313c660423f1eec2d1e8f758b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2017-05-10T18:26:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-22T22:14:06.000Z", "max_forks_repo_path": "test/jac_tests.jl", "max_forks_repo_name": "AnasAbdelR/ODEInterfaceDiffEq.jl", "max_forks_repo_head_hexsha": "490c25fe96e379a313c660423f1eec2d1e8f758b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2016-12-14T03:45:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:37:11.000Z", "avg_line_length": 19.0740740741, "max_line_length": 69, "alphanum_fraction": 0.6058252427, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7518728073199311}}
{"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\u2013218\n\n> Meila, Marina (2003). *Comparing Clusterings by the Variation of\n> Information.* Learning Theory and Kernel Machines: 173\u2013187.\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\u2080::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\u2080<:Real,Tp<:AbstractVector} <:\n       Distributions.DiscreteMultivariateDistribution\n    x\u2080::Tx\u2080\n    p::Tp\n    function NegativeMultinomial(x\u2080::Real, p::AbstractVector)\n        x\u2080 > 0 || throw(ArgumentError(\"x\u2080 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\u2080),typeof(p)}(x\u2080, p)\n    end\nend\n\n_p\u2080(d::NegativeMultinomial) = 1 - sum(d.p)\n\nDistributions.params(d::NegativeMultinomial) = (d.x\u2080, 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\u2080 = _p\u2080(d)\n    \u03b8 = rand(rng, Gamma(d.x\u2080, inv(p\u2080) - 1))\n    \u03bb = d.p * \u03b8 / (1 - p\u2080) # convert parameters to the scaled Poisson ones\n    for i in eachindex(x)\n        x[i] = rand(rng, Poisson(\u03bb[i]))\n    end\n    return x\nend\n\nfunction Distributions._logpdf(d::NegativeMultinomial, x::AbstractVector)\n    return loggamma(d.x\u2080 + sum(x)) + d.x\u2080 * log(_p\u2080(d)) - loggamma(d.x\u2080) +\n           mapreduce(+, d.p, x) do p\u1d62, x\u1d62\n        x\u1d62 * log(p\u1d62) - logfactorial(x\u1d62)\n    end\nend\n\nDistributions.mean(d::NegativeMultinomial) = d.x\u2080 / _p\u2080(d) * d.p\n\nfunction Distributions.var(d::NegativeMultinomial)\n    p\u2080 = _p\u2080(d)\n    x\u2080 = d.x\u2080\n    return x\u2080 / p\u2080^2 * abs2.(d.p) + x\u2080 / p\u2080 * p\nend\n\nfunction Distributions.cov(d::NegativeMultinomial)\n    p\u2080 = _p\u2080(d)\n    x\u2080 = d.x\u2080\n    return x\u2080 / p\u2080^2 * d.p * d.p' + x\u2080 / p\u2080 * Diagonal(d.p)\nend\n\nfunction Distributions.mgf(d::NegativeMultinomial, t::AbstractVector)\n    return (_p\u2080(d) / (1 - dot(d.p, exp.(t))))^d.x\u2080\nend\n\nfunction Distributions.kldivergence(p::NegativeMultinomial, q::NegativeMultinomial)\n    p\u2080 = _p\u2080(p)\n    x\u2080 = p.x\u2080\n    x\u2080 == q.x\u2080 || error(\n        \"KL divergence cannot be computed with different x\u208d\", \"p: $(p.x\u2080), q: $(q.x\u2080)\"\n    )\n    return x\u2080 * log(p\u2080) - x\u2080 * log(_p\u2080(q)) +\n           x\u2080 / p\u2080 * 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": "using Distributions\nusing ConjugatePriors\n\nusing Random: seed!\n\nusing ConjugatePriors: NormalGamma, NormalInverseGamma, NormalInverseChisq\nusing ConjugatePriors: posterior, posterior_rand, posterior_mode, posterior_randmodel, fit_map\n\nn = 100\nw = rand(100)\n\n@testset \"Conjugates for normal distribution\" begin\n\n    @testset \"\u039dormal - \u039dormal (known sigma)\" begin\n\n        pri = Normal(1.0, 5.0)\n\n        x = rand(Normal(2.0, 3.0), n)\n        p = posterior((pri, 3.0), Normal, x)\n        @test isa(p, Normal)\n        @test mean(p) \u2248 (mean(pri) / var(pri) + sum(x) / 9.0) / (1.0 / var(pri) + n / 9.0)\n        @test var(p) \u2248 inv(1.0 / var(pri) + n / 9.0)\n\n        r = posterior_mode((pri, 3.0), Normal, x)\n        @test r \u2248 mode(p)\n\n        f = fit_map((pri, 3.0), Normal, x)\n        @test isa(f, Normal)\n        @test f.\u03bc == r\n        @test f.\u03c3 == 3.0\n\n        p = posterior((pri, 3.0), Normal, x, w)\n        @test isa(p, Normal)\n        @test mean(p) \u2248  (mean(pri) / var(pri) + dot(x, w) / 9.0) / (1.0 / var(pri) + sum(w) / 9.0)\n        @test var(p) \u2248 inv(1.0 / var(pri) + sum(w) / 9.0)\n\n        r = posterior_mode((pri, 3.0), Normal, x, w)\n        @test r \u2248 mode(p)\n\n        f = fit_map((pri, 3.0), Normal, x, w)\n        @test isa(f, Normal)\n        @test f.\u03bc == r\n        @test f.\u03c3 == 3.0\n\n    end\n\n    @testset \"\u0399nverseGamma - \u039dormal (known mu)\" begin\n\n        pri = InverseGamma(1.5, 0.5)\n\n        x = rand(Normal(2.0, 3.0), n)\n        p = posterior((2.0, pri), Normal, x)\n        @test isa(p, InverseGamma)\n        @test shape(p) \u2248 shape(pri) + n / 2\n        @test scale(p) \u2248 scale(pri) + sum(abs2.(x .- 2.0)) / 2\n\n        r = posterior_mode((2.0, pri), Normal, x)\n        @test r \u2248 mode(p)\n\n        f = fit_map((2.0, pri), Normal, x)\n        @test isa(f, Normal)\n        @test f.\u03bc == 2.0\n        @test abs2(f.\u03c3) \u2248 r\n\n        p = posterior((2.0, pri), Normal, x, w)\n        @test isa(p, InverseGamma)\n        @test shape(p) \u2248 shape(pri) + sum(w) / 2\n        @test scale(p) \u2248 scale(pri) + dot(w, abs2.(x .- 2.0)) / 2\n\n        r = posterior_mode((2.0, pri), Normal, x, w)\n        @test r \u2248 mode(p)\n\n        f = fit_map((2.0, pri), Normal, x, w)\n        @test isa(f, Normal)\n        @test f.\u03bc == 2.0\n        @test abs2(f.\u03c3) \u2248 r\n\n    end\n\n    @testset \"Gamma - \u039dormal (known mu)\" begin\n\n        pri = Gamma(1.5, 2.0)\n\n        x = rand(Normal(2.0, 3.0), n)\n        p = posterior((2.0, pri), Normal, x)\n        @test isa(p, Gamma)\n        @test shape(p) \u2248 shape(pri) + n / 2\n        @test scale(p) \u2248 scale(pri) + sum(abs2.(x .- 2.0)) / 2\n\n        r = posterior_mode((2.0, pri), Normal, x)\n        @test r \u2248 mode(p)\n\n        f = fit_map((2.0, pri), Normal, x)\n        @test isa(f, Normal)\n        @test f.\u03bc == 2.0\n        @test abs2(f.\u03c3) \u2248 inv(r)\n\n        p = posterior((2.0, pri), Normal, x, w)\n        @test isa(p, Gamma)\n        @test shape(p) \u2248 shape(pri) + sum(w) / 2\n        @test scale(p) \u2248 scale(pri) + dot(w, abs2.(x .- 2.0)) / 2\n\n        r = posterior_mode((2.0, pri), Normal, x, w)\n        @test r \u2248 mode(p)\n\n        f = fit_map((2.0, pri), Normal, x, w)\n        @test isa(f, Normal)\n        @test f.\u03bc == 2.0\n        @test abs2(f.\u03c3) \u2248 inv(r)\n\n    end\n\n    @testset \"NormalInverseGamma - Normal\" begin\n\n        mu_true = 2.\n        sig2_true = 3.\n        x = rand(Normal(mu_true, sig2_true), n)\n\n        mu0 = 2.\n        v0 = 3.\n        shape0 = 5.\n        scale0 = 2.\n        pri = NormalInverseGamma(mu0, v0, shape0, scale0)\n\n        post = posterior(pri, Normal, x)\n        @test isa(post, NormalInverseGamma)\n\n        @test post.mu \u2248 (mu0/v0 + n*mean(x))/(1.0/v0 + n)\n        @test post.v0 \u2248 1.0/(1.0/v0 + n)\n        @test post.shape \u2248 shape0 + 0.5*n\n        @test post.scale \u2248 scale0 + 0.5*(n-1)*var(x) + n./v0./(n + 1.0/v0)*0.5*(mean(x)-mu0).^2\n\n        ps = posterior_randmodel(pri, Normal, x)\n\n        @test isa(ps, Normal)\n        @test insupport(ps,ps.\u03bc) && ps.\u03c3 > zero(ps.\u03c3)\n\n        for shape in [0.1, 1., 10.]\n            d = NormalInverseGamma(mu0, v0, scale0, shape)\n            \u03bc, \u03c32 = mode(d)\n            @test pdf(d, \u03bc, \u03c32) > pdf(d, \u03bc, \u03c32 + 0.001)\n            @test pdf(d, \u03bc, \u03c32) > pdf(d, \u03bc, \u03c32 - 0.001)\n        end\n\n    end\n\n    @testset \"NormalInverseChisq - Normal\" begin\n\n        mu_true = 2.\n        sig2_true = 3.\n        x = rand(Normal(mu_true, sig2_true), n)\n\n        \u03bc0 = 2.0\n        \u03c320 = 2.0/5.0\n        \u03ba0 = 1.0/3.0\n        \u03bd0 = 10.0\n\n        pri = NormalInverseChisq(\u03bc0, \u03c320, \u03ba0, \u03bd0)\n        pri2 = convert(NormalInverseGamma, pri)\n\n        @test convert(NormalInverseChisq, pri2) == pri\n\n        @test mode(pri2) == mode(pri)\n        @test mean(pri2) == mean(pri)\n        @test pdf(pri, mu_true, sig2_true) == pdf(pri2, mu_true, sig2_true)\n        \n        @test (seed!(1); rand(pri)) == (seed!(1); rand(pri2))\n\n        # check that updating is consistent between NI\u03c72 and NIG\n        post = posterior(pri, Normal, x)\n        post2 = posterior(pri2, Normal, x)\n        @test isa(post, NormalInverseChisq)\n        @test convert(NormalInverseChisq, post2) == post\n\n        for _ in 1:10\n            x = rand(post)\n            @test pdf(post, x...) \u2248 pdf(post2, x...)\n            @test logpdf(post, x...) \u2248 logpdf(post2, x...)\n        end\n\n        for \u03bd in [0.1, 1., 10.]\n            nix = NormalInverseChisq(0., 2., 3., \u03bd)\n            \u03bc, \u03c32 = mode(nix)\n            @test pdf(nix, \u03bc, \u03c32) > pdf(nix, \u03bc, \u03c32 + 0.001)\n            @test pdf(nix, \u03bc, \u03c32) > pdf(nix, \u03bc, \u03c32 - 0.001)\n        end\n\n    end\n\n    @testset \"NormalGamma - Normal\" begin\n\n        mu_true = 2.\n        tau2_true = 3.\n        x = rand(Normal(mu_true, 1.0/tau2_true), n)\n\n        mu0 = 2.\n        nu0 = 3.\n        shape0 = 5.\n        rate0 = 2.\n        pri = NormalGamma(mu0, nu0, shape0, rate0)\n\n        post = posterior(pri, Normal, x)\n        @test isa(post, NormalGamma)\n\n        @test post.mu \u2248 (nu0*mu0 + n*mean(x))./(nu0 + n)\n        @test post.nu \u2248 nu0 + n\n        @test post.shape \u2248 shape0 + 0.5*n\n        @test post.rate \u2248 rate0 + 0.5*(n-1)*var(x) + n*nu0/(n + nu0)*0.5*(mean(x)-mu0).^2\n\n        ps = posterior_randmodel(pri, Normal, x)\n\n        @test isa(ps, Normal)\n        @test insupport(ps, ps.\u03bc) && ps.\u03c3 > zero(ps.\u03c3)\n    end\n    \nend\n", "meta": {"hexsha": "1ccb138bf99c2474416cf9931fd75f3af53bd314", "size": 6150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/conjugates_normal.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": "test/conjugates_normal.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": "test/conjugates_normal.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": 28.3410138249, "max_line_length": 99, "alphanum_fraction": 0.4982113821, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7518727996845905}}
{"text": "\"\"\"\n\tObstacle\n\nAbstract type representing obstacle.\n\"\"\"\nabstract type Obstacle end\n\n\"\"\"\n\tCircularObstacle <: Obstacle\n\nCircular obstacle with center c and radius r\n\"\"\"\nstruct CircularObstacle <: Obstacle\n    c::Vector{Float64}\n    r::Float64\nend\n\n\"\"\"\n\tControlBarrierFunction(O::CircularObstacle, \u03b1)\n\nConstruct a CBF for a ciruclar obstacle.\n\"\"\"\nfunction ControlBarrierFunction(O::CircularObstacle, \u03b1)\n    h(x) = (x[1] - O.c[1])^2 + (x[2] - O.c[2])^2 - O.r^2\n    return ControlBarrierFunction(h, \u03b1)\nend\n", "meta": {"hexsha": "04cdadb7dc820f9fd427c285b7894ba10f631ef6", "size": 502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/cbf_utils.jl", "max_stars_repo_name": "maxhcohen/CBFToolbox.jl", "max_stars_repo_head_hexsha": "8d0e4355487d96010c4ac0c77fb4c3092c6fc245", "max_stars_repo_licenses": ["MIT"], "max_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/cbf_utils.jl", "max_issues_repo_name": "maxhcohen/CBFToolbox.jl", "max_issues_repo_head_hexsha": "8d0e4355487d96010c4ac0c77fb4c3092c6fc245", "max_issues_repo_licenses": ["MIT"], "max_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/cbf_utils.jl", "max_forks_repo_name": "maxhcohen/CBFToolbox.jl", "max_forks_repo_head_hexsha": "8d0e4355487d96010c4ac0c77fb4c3092c6fc245", "max_forks_repo_licenses": ["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.5925925926, "max_line_length": 56, "alphanum_fraction": 0.6972111554, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7518696768481915}}
{"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    \u03d5deg, \u03bbdeg, h = lla.lat, lla.lon, lla.alt\n    d = datum\n\n    sin\u03d5, cos\u03d5 = sind(\u03d5deg), cosd(\u03d5deg)\n    sin\u03bb, cos\u03bb = sind(\u03bbdeg), cosd(\u03bbdeg)\n\n    N = d.a / sqrt(1 - d.e\u00b2 * sin\u03d5^2)  # Radius of curvature (meters)\n\n    x = (N + h) * cos\u03d5 * cos\u03bb\n    y = (N + h) * cos\u03d5 * sin\u03bb\n    z = (N * (1 - d.e\u00b2) + h) * sin\u03d5\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    \u03b8 = atan(z*d.a, p*d.b)\n    \u03bb = atan(y, x)\n    \u03d5 = atan(z + d.e\u2032\u00b2 * d.b * sin(\u03b8)^3, p - d.e\u00b2*d.a*cos(\u03b8)^3)\n\n    N = d.a / sqrt(1 - d.e\u00b2 * sin(\u03d5)^2)  # Radius of curvature (meters)\n    h = p / cos(\u03d5) - N\n\n    return OpenStreetMapX.LLA(rad2deg(\u03d5), rad2deg(\u03bb), 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    \u03d5deg, \u03bbdeg = lla_ref.lat, lla_ref.lon\n\n    ecef_ref = OpenStreetMapX.ECEF(lla_ref, datum)\n    \u2202x = ecef.x - ecef_ref.x\n    \u2202y = ecef.y - ecef_ref.y\n    \u2202z = ecef.z - ecef_ref.z\n\n    # Compute rotation matrix\n    sin\u03bb, cos\u03bb = sind(\u03bbdeg), cosd(\u03bbdeg)\n    sin\u03d5, cos\u03d5 = sind(\u03d5deg), cosd(\u03d5deg)\n\n    # R = [     -sin\u03bb       cos\u03bb  0.0\n    #      -cos\u03bb*sin\u03d5 -sin\u03bb*sin\u03d5 cos\u03d5\n    #       cos\u03bb*cos\u03d5  sin\u03bb*cos\u03d5 sin\u03d5]\n    #\n    # east, north, up = R * [\u2202x, \u2202y, \u2202z]\n    east  = \u2202x * -sin\u03bb      + \u2202y * cos\u03bb       + \u2202z * 0.0\n    north = \u2202x * -cos\u03bb*sin\u03d5 + \u2202y * -sin\u03bb*sin\u03d5 + \u2202z * cos\u03d5\n    up    = \u2202x * cos\u03bb*cos\u03d5  + \u2202y * sin\u03bb*cos\u03d5  + \u2202z * sin\u03d5\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    \u03d5deg, \u03bbdeg = lla_ref.lat, lla_ref.lon\n\n    ecef_ref = OpenStreetMapX.ECEF(lla_ref, datum)\n\n    # Compute rotation matrix\n    sin\u03bb, cos\u03bb = sind(\u03bbdeg), cosd(\u03bbdeg)\n    sin\u03d5, cos\u03d5 = sind(\u03d5deg), cosd(\u03d5deg)\n\n    # R = [-sin\u03bb -sin\u03d5*cos\u03bb  cos\u03d5*cos\u03bb\n    #      \tcos\u03bb -sin\u03d5*sin\u03bb  cos\u03d5*sin\u03bb\n    #        0.0       cos\u03d5       sin\u03d5]\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\u03bb*enu.east + -sin\u03d5*cos\u03bb*enu.north + cos\u03d5*cos\u03bb*enu.up + ecef_ref.x\n    y = cos\u03bb*enu.east +  -sin\u03d5*sin\u03bb*enu.north + cos\u03d5*sin\u03bb*enu.up + ecef_ref.y\n    z    = 0.0*enu.east + cos\u03d5*enu.north + sin\u03d5*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": "function rkrp2tn(U\u0303::Vector{Matrix{Float64}},\u03f5::Float64)\n    # repeated Kathti-Rao product into tensor network\n    # Source: Batselier et al.: Tensor network subspace identification of polynomial state space models, Algorithm 2\n    \n    N    = length(U\u0303);\n    M    = size(U\u0303[1],1);\n    P    = size(U\u0303[1],2);\n    U    = Vector{Array{Float64,4}}(undef,N);\n    U[1] = reshape(U\u0303[N],(1,M,P,1));\n    r1   = 1; err2 = 0;\n    \u03b4    = \u03f5 / sqrt(N-1) * norm(.*(U\u0303));\n    for i = 1:N-1\n        T = reshape(U[i],(r1*M,P));\n        Ttmp = KathriRao(U\u0303[N-i],T,2)\n\n        T = reshape(Ttmp,(r1*M,M*P));\n        F = svd!(T);\n        r2 = length(F.S);\n        sv2 = cumsum(reverse(F.S).^2);\n        tr  = findfirst(sv2 .> \u03b4^2);\n        if typeof(tr) == Nothing\n            tr = length(sv2)-1;\n        else\n            tr = Int(tr)-1;\n        end\n        if tr > 0\n            r2 = r2 - tr;\n            err2 += sv2[tr];\n        end\n\n        U[i] = reshape(F.U[:,1:r2],(r1,M,1,r2));\n        U[i+1] = reshape(diagm(F.S[1:r2])*F.Vt[1:r2,:],(r2,M,P,1));\n        r1 = r2;\n    end\n    return MPT(U), err2\nend", "meta": {"hexsha": "c860a753bbdcbc23b2bd267b03e3a1ba8a908468", "size": 1083, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions_computeTN/rkrp2tn.jl", "max_stars_repo_name": "clarazen/BigMat", "max_stars_repo_head_hexsha": "47a750c5206e4b80c1dcc82ffd24abd2ddba0a07", "max_stars_repo_licenses": ["MIT"], "max_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_computeTN/rkrp2tn.jl", "max_issues_repo_name": "clarazen/BigMat", "max_issues_repo_head_hexsha": "47a750c5206e4b80c1dcc82ffd24abd2ddba0a07", "max_issues_repo_licenses": ["MIT"], "max_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_computeTN/rkrp2tn.jl", "max_forks_repo_name": "clarazen/BigMat", "max_forks_repo_head_hexsha": "47a750c5206e4b80c1dcc82ffd24abd2ddba0a07", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 116, "alphanum_fraction": 0.4709141274, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7518696530194449}}
{"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# \u2554\u2550\u2561 c7edc362-1d55-4556-94e2-5ccae0fce152\nbegin\n\tusing LinearAlgebra\n\tusing Statistics\n\tusing PlutoUI\n\tusing Plots\n\tgr()\nend\n\n# \u2554\u2550\u2561 e91395c4-e4dd-4bf7-8efa-c48d05418bb4\nusing Polynomials\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f16d834c-67ad-11ec-05db-f726c8f8c643\nmd\"\"\" # \u6a5f\u68b0\u5b66\u7fd2\u5e33\n\u3053\u3053\u3092\u53c2\u8003\u306b\u3057\u305f.[\u6a5f\u68b0\u5b66\u7fd2\u5e33](https://chokkan.github.io/mlnote/regression/01sra.html)\n## 1. \u5358\u56de\u5e30\n### (\u7d9a\u304d)1.4. \u5e73\u5747\u4e8c\u4e57\u8aa4\u5dee\u306f$a$,$b$\u306e\u95a2\u6570\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 86db1e1c-5164-4e3f-b877-f9c6f1a535c7\nbegin\n\tN = 100\n\taa = range(-10,10, N)\n\tbb = range(-10,10, N)\nend\n\n# \u2554\u2550\u2561 c47e13d4-f0e9-46b0-b746-73563344487e\nJ = calc_msr(aa, bb', D)\n\n# \u2554\u2550\u2561 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\u0302_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# \u2554\u2550\u2561 02c50675-5c7e-4662-84fd-56cf5e34e666\nmd\"\"\" ### 1.5. \u5e73\u5747\u4e8c\u4e57\u6b8b\u5dee\u3092\u6700\u5c0f\u5316\u3059\u308b\n\u5358\u56de\u5e30\u306e\u76ee\u7684\u95a2\u6570(\u5e73\u5747\u4e8c\u4e57\u6b8b\u5dee)\u306f\n```math\nL\u0302_D(a,b) = \\frac{N}{1} \\sum_{i=1}^{N} \u03f5_i^2 = \\frac{1}{N} \\sum_{i=1}^{N} (y_i - y\u0302_i)^2 = \\frac{1}{N} \\sum_{i=1}^{N} (y_i - ax_i - b)^2\n```\n\u3067\u3042\u308b\u3002\n\u4e0a\u5f0f\u3092 $b$ \u3067\u504f\u5fae\u5206\u3059\u308b\u3068\n```math\nb = y\u0304 - ax\u0304\n```\n\u3068\u306a\u308b\u3002 \u5358\u56de\u5e30\u306e\u50be\u304d $a$ \u3092\u6c42\u3081\u308b\u5f0f\n```math\na = \\frac{ \\overline{xy} - (x\u0304)(y\u0304)}{ \\overline{x^2} - (x\u0304)^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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4765fa67-4e96-4cc0-85fa-266128fb8fae\nfunction plot_y(X, Y, colormap)\n\tscatter!(X, Y; c=colormap,  markerstrokewidth=0, label=\"\")\nend\n\n# \u2554\u2550\u2561 8f419e32-93f9-4067-9461-e0e2f69a723a\nfunction plot_y\u0302(a, b, offset, colormap)\n\n\toffset_y\u0302 = offset\n\n\ta, b = a, b\n\tf(x, a, b) = a*x + b\n\tY\u0302 = 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\u0302; 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\u0302 = [\"(x\u2081,y\u0302\u2081)\", \"(x\u2082,y\u0302\u2082)\", \"(x\u2083,y\u0302\u2083)\", \"(x\u2084,y\u0302\u2084)\"]\n\tfor i in 1:length(colormap)\n\t\tannotate!([(X[i],Y\u0302[i]+offset_y\u0302[i],text(texts_y\u0302[i], 10,\n\t\t\t:center, colormap[i]))])\n\tend\n\tplot!()\nend\n\n# \u2554\u2550\u2561 59bd7898-2dcf-4c23-815b-abf13a6954d0\nfunction plot_error(a, b, offset, colormap)\n\n\tf(x, a, b) = a*x + b\n\tY\u0302 = f.(X, a, b)\n\n\toffset_\u03f5 = offset\n\tx_\u03f5 = X + offset_\u03f5\n\ty_\u03f5 = (Y + Y\u0302) / 2\n\ttexts_\u03f5 = [\"\u03f5\u2081\", \"\u03f5\u2082\", \"\u03f5\u2083\", \"\u03f5\u2084\"]\n\t\t\n\tfor i in 1:length(colormap)\n\t\tplot!([(X[i], Y\u0302[i]), (X[i], Y[i])]; c=colormap[i], ls=:dash, label=\"\")\n\t\tannotate!([(x_\u03f5[i],y_\u03f5[i],text(texts_\u03f5[i], 10, :center, colormap[i]))])\n\tend\n\tplot!()\nend\n\n# \u2554\u2550\u2561 e776c006-777f-4a6c-8a3e-a273820a0ad8\nconst colormap = [:red, :blue, :green, :orange]\n\n# \u2554\u2550\u2561 75364a95-c8ef-40d3-8373-6176540ceaf8\nlet\n\t# \u30d1\u30e9\u30e1\u30fc\u30bf a, b \u306e\u8a08\u7b97\n\tx\u0304 = D[:,1] |> mean\n\ty\u0304 = D[:,2] |> mean\n\n\tCov_XY = 1 / length(X) * sum( (X .- x\u0304) .* (Y .- y\u0304) )\n\tVar_X =  1 / length(X) * sum( (X .- x\u0304).^2 )\n\n\ta = Cov_XY / Var_X\n\tb = y\u0304 - a* x\u0304\n\n\t# \u53ef\u8996\u5316\n\toffset_y_new = [-1., 1.8, -1.2, 0.7]\n\toffset_\u03f5_new = [0.3, -0.3, 0.3, -0.3]\n\n\tset_plot()\n\tplot_y(X, Y, colormap)\n\tplot_y\u0302(a, b, offset_y_new, colormap)\n\tplot_error(a, b, offset_\u03f5_new, colormap)\n\t\nend\n\n# \u2554\u2550\u2561 792c62f0-222b-4048-ad6a-9655db74f080\nmd\"\"\" ### 1.6. \u56de\u5e30\u76f4\u7dda\u306e\u6027\u8cea\n\"\"\"\n\n# \u2554\u2550\u2561 0f1d5e27-f04c-47f4-bcff-bc9deea6eda2\nfunction plot_means(X, Y)\n\tx\u0304 = D[:,1] |> mean\n\ty\u0304 = D[:,2] |> mean\n\n\tvline!([x\u0304]; c=:black, lw=1.5, ls=:dash, label=\"x\u0304\")\n\thline!([y\u0304]; c=:black, lw=1.5, ls=:dot, label=\"y\u0304\")\n\t\nend\n\n# \u2554\u2550\u2561 4c2841e2-2e5e-47ca-987a-0e4c5557f023\nfunction plot_regions(X, Y)\n\tx\u0304 = D[:,1] |> mean\n\ty\u0304 = 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\u0304, y\u0304), color=:red, alpha=0.1, label=\"\")\n\tplot!(rectangle(x\u0304, y\u0304, 10-x\u0304, 10-y\u0304), color=:red, alpha=0.1, label=\"\")\n\t\n\tplot!(rectangle(0, y\u0304, x\u0304, y\u0304), color=:blue, alpha=0.1, label=\"\")\n\tplot!(rectangle(x\u0304, 0, 10-x\u0304, y\u0304), color=:blue, alpha=0.1, label=\"\")\n\t\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c0a1bf99-d350-47ee-9a01-763acdcdb63a\nfunction plot_regions2(X, Y, colormap)\n\tx\u0304 = D[:,1] |> mean\n\ty\u0304 = 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\u0304, x\u0304]\n\tys = [D[1,2], D[2,2], D[3,2], y\u0304]\n\tws = [x\u0304-D[1,1], x\u0304-D[2,1], D[3,1]-x\u0304, D[4,1]-x\u0304]\n\ths = [y\u0304-D[1,2], y\u0304-D[2,2], y\u0304-D[3,2], D[4,2]-y\u0304]\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cc5a8abc-ff3e-4693-94fe-79a73aaf2a19\nmd\"\"\" #### 1.6.3. \u56de\u5e30\u76f4\u7dda\u306f\u89b3\u6e2c\u30c7\u30fc\u30bf\u306e\u91cd\u5fc3\u3092\u901a\u308b\n\"\"\"\n\n# \u2554\u2550\u2561 6da0bfa7-bd9e-4463-9057-bd40c56019eb\nfunction plot_slope(x\u0304, y\u0304, a, b)\n\n\tCov_XY = 1 / length(X) * sum( (X .- x\u0304) .* (Y .- y\u0304) )\n\tVar_X =  1 / length(X) * sum( (X .- x\u0304).^2 )\n\n\ta = Cov_XY / Var_X\n\tb = y\u0304 - a* x\u0304\n\t\n\t# horizontal\n\tplot!([0, x\u0304],[b, b]; lw=2, color=:brown, label=\"\")\n\tannotate!([(x\u0304/2,b-0.3,text(\"x\u0304\", 10, :center, color=:brown))])\n\t# vertical\n\tplot!([x\u0304, x\u0304], [b, y\u0304]; lw=2, color=:brown, label=\"\")\n\tannotate!([(x\u0304+0.3, b+(y\u0304-b)/2,text(\"ax\u0304\", 10, :center, color=:brown))])\nend\n\n# \u2554\u2550\u2561 f4215be2-c8af-4f7e-92cb-76b338714f1a\nfunction plot_y\u0302_only(a, b)\n\n\ta, b = a, b\n\tf(x, a, b) = a*x + b\n\tY\u0302 = 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# \u2554\u2550\u2561 c1635018-bff4-4245-91ff-278fda46f3a0\nlet\n\n\t# \u30d1\u30e9\u30e1\u30fc\u30bf a, b \u306e\u8a08\u7b97\n\tx\u0304 = D[:,1] |> mean\n\ty\u0304 = D[:,2] |> mean\n\n\tCov_XY = 1 / length(X) * sum( (X .- x\u0304) .* (Y .- y\u0304) )\n\tVar_X =  1 / length(X) * sum( (X .- x\u0304).^2 )\n\n\ta = Cov_XY / Var_X\n\tb = y\u0304 - a* x\u0304\n\n\t# ----- \u53ef\u8996\u5316 -----\n\t# \u521d\u671f\u5316\n\tset_plot()\n\t# \u30c7\u30fc\u30bf\u70b9\u3092\u30d7\u30ed\u30c3\u30c8\n\tplot_y(X, Y, colormap)\n\t# x\u3068y\u306e\u5e73\u5747\u306e\u76f4\u7dda\u3092\u30d7\u30ed\u30c3\u30c8\n\tplot_means(X, Y)\n\t# +(\u8d64)\u3001 -(\u9752)\u306b\u306a\u308b\u9818\u57df\u3092\u30d7\u30ed\u30c3\u30c8\n\tplot_regions(X, Y)\n\t# \u30b9\u30ed\u30fc\u30d7\u90e8\u5206(\u8336\u8272)\u3092\u30d7\u30ed\u30c3\u30c8\n\tplot_slope(x\u0304, y\u0304, a, b)\n\t# \u63a8\u5b9a\u5024 y\u0302 \u3092\u30d7\u30ed\u30c3\u30c8\n\tplot_y\u0302_only(a, b)\nend\n\n# \u2554\u2550\u2561 fcd91d11-e8e0-4419-a992-47f82b39b393\nmd\"\"\" #### 1.8. \u5358\u56de\u5e30\u306e\u5b9f\u65bd\u4f8b\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 [\u0307Degree]\", 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# \u2554\u2550\u2561 569e9185-fb79-4a0b-b32d-b6e20dee29e8\nlet\n\ty\u0302 = fit(mmt, spend, 1)\n\tx = range(0, 35, length=100)\n\tplot_temp_vs_spend()\n\tplot!(x, y\u0302.(x); lw=2, color=:red, label=\"\")\nend\n\n# \u2554\u2550\u2561 e802792b-052f-4bd5-976a-2f5983fe7e06\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500f16d832c-67ad-11ec-3474-d9f0f2241ff9\n# \u2560\u2550c7edc362-1d55-4556-94e2-5ccae0fce152\n# \u2560\u2550f16d834c-67ad-11ec-05db-f726c8f8c643\n# \u2560\u25506ce3e88a-e10d-45c2-9722-aeed933931d9\n# \u2560\u2550bc133d95-c122-49be-8789-01dd2b87ac0a\n# \u2560\u255086db1e1c-5164-4e3f-b877-f9c6f1a535c7\n# \u2560\u2550c47e13d4-f0e9-46b0-b746-73563344487e\n# \u2560\u2550f1896c70-c8ce-4d7f-832e-11a3eede0883\n# \u2560\u255002c50675-5c7e-4662-84fd-56cf5e34e666\n# \u2560\u25500367c8ba-1c50-43ea-828f-fb0cbaefe691\n# \u2560\u25504765fa67-4e96-4cc0-85fa-266128fb8fae\n# \u2560\u25508f419e32-93f9-4067-9461-e0e2f69a723a\n# \u2560\u255059bd7898-2dcf-4c23-815b-abf13a6954d0\n# \u2560\u2550e776c006-777f-4a6c-8a3e-a273820a0ad8\n# \u2560\u255075364a95-c8ef-40d3-8373-6176540ceaf8\n# \u2560\u2550792c62f0-222b-4048-ad6a-9655db74f080\n# \u2560\u25500f1d5e27-f04c-47f4-bcff-bc9deea6eda2\n# \u2560\u25504c2841e2-2e5e-47ca-987a-0e4c5557f023\n# \u2560\u2550dde67d9a-5c75-4477-bbd0-3eefc7b5ef13\n# \u2560\u2550c0a1bf99-d350-47ee-9a01-763acdcdb63a\n# \u2560\u2550407a1c1b-bb2d-4188-997b-17565ef4431d\n# \u2560\u2550cc5a8abc-ff3e-4693-94fe-79a73aaf2a19\n# \u2560\u25506da0bfa7-bd9e-4463-9057-bd40c56019eb\n# \u2560\u2550f4215be2-c8af-4f7e-92cb-76b338714f1a\n# \u2560\u2550c1635018-bff4-4245-91ff-278fda46f3a0\n# \u2560\u2550fcd91d11-e8e0-4419-a992-47f82b39b393\n# \u2560\u2550e2ae904b-c4aa-4f3c-ad18-58b0fabb6877\n# \u2560\u255037558fb1-0ea2-4aa5-bdae-d1b54d237812\n# \u2560\u2550e91395c4-e4dd-4bf7-8efa-c48d05418bb4\n# \u2560\u2550569e9185-fb79-4a0b-b32d-b6e20dee29e8\n# \u2560\u2550e802792b-052f-4bd5-976a-2f5983fe7e06\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "## Marker style\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\n## ref https://jp.mathworks.com/matlabcentral/fileexchange/35231-matlab-plot-gallery-standard-plot-markers?focused=6792907&tab=example\n\nusing SpecialFunctions\n\nx = 0:0.2:10;\ny0 = besselj.(0,x);\ny1 = besselj.(1,x);\ny2 = besselj.(2,x);\ny3 = besselj.(3,x);\ny4 = besselj.(4,x);\n\nplot(x, [y0 y1 y2 y3 y4],\n    marker=[:circle :rect :star5 :diamond :hexagon],\n    line=false)\n\n#-\n\nPlots.supported_markers()\n", "meta": {"hexsha": "868b7d3b27ad41437705f9dace313414be2960e3", "size": 464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/marker_style.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/marker_style.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/marker_style.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": 20.1739130435, "max_line_length": 134, "alphanum_fraction": 0.6853448276, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.751838775154106}}
{"text": "@testset \"Cycle Basis\" begin\n\n    function evaluate(x,y)\n        x_sorted = sort(sort.(x))\n        y_sorted = sort(sort.(y))\n        @test x_sorted == y_sorted\n    end\n\n    # No Edges\n    ex = Graph(1)\n    expected_cyclebasis = Array{Int64,1}[]\n    @testset \"no edges\" for g in testgraphs(ex)\n        ex_cyclebasis = @inferred cycle_basis(g)\n        @test isempty(ex_cyclebasis)\n    end\n\n    # Only one self-edge\n    elist = [(1,1)]\n    ex = Graph(SimpleEdge.(elist))\n    expected_cyclebasis = Array{Int64,1}[[1]]\n    @testset \"one self-edge\" for g in testgraphs(ex)\n        ex_cyclebasis = cycle_basis(g)\n        evaluate(ex_cyclebasis,expected_cyclebasis)\n    end\n\n    # Graph with one cycle\n    elist = [(1,2),(2,3),(3,4),(4,1),(1,5)]\n    ex = Graph(SimpleEdge.(elist))\n    expected_cyclebasis = Array{Int64,1}[\n        [1,2,3,4] ]\n    @testset \"one cycle\" for g in testgraphs(ex)\n        ex_cyclebasis = cycle_basis(g)\n        evaluate(ex_cyclebasis,expected_cyclebasis)\n    end    \n\n    # Graph with 2 of 3 cycles forming a basis\n    elist = [(1,2),(1,3),(2,3),(2,4),(3,4)]\n    ex = Graph(SimpleEdge.(elist))\n    expected_cyclebasis = Array{Int64,1}[\n        [2,3,4],\n        [2,1,3] ]\n    @testset \"2 of 3 cycles w/ basis\" for g in testgraphs(ex)\n        ex_cyclebasis = cycle_basis(g)\n        evaluate(ex_cyclebasis,expected_cyclebasis)\n    end\n\n    # Testing root argument\n    elist = [(1,2),(1,3),(2,3),(2,4),(3,4),(1,5),(5,6),(6,4)]\n    ex = Graph(SimpleEdge.(elist))\n    expected_cyclebasis = Array{Int64,1}[\n        [2, 4, 3],\n        [1, 5, 6, 4, 3],\n        [1, 2, 3] ]\n    @testset \"root argument\" for g in testgraphs(ex)\n        ex_cyclebasis = @inferred cycle_basis(g,3)\n        evaluate(ex_cyclebasis,expected_cyclebasis)\n    end\n\n    @testset \"two isolated cycles\" begin\n        ex = blockdiag(cycle_graph(3), cycle_graph(4))\n        expected_cyclebasis = [[1, 2, 3], [4, 5, 6, 7]]\n        for g in testgraphs(ex)\n            found_cyclebasis = @inferred cycle_basis(g)\n            evaluate(expected_cyclebasis, found_cyclebasis)\n        end\n    end\nend\n", "meta": {"hexsha": "e9e43a040b481d2ab775c349b215389a6b485089", "size": 2073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/cycles/basis.jl", "max_stars_repo_name": "pitsianis/LightGraphs.jl", "max_stars_repo_head_hexsha": "90989ef1248115c8735bff2f5d5775329b7f4eb0", "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": "test/cycles/basis.jl", "max_issues_repo_name": "pitsianis/LightGraphs.jl", "max_issues_repo_head_hexsha": "90989ef1248115c8735bff2f5d5775329b7f4eb0", "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": "test/cycles/basis.jl", "max_forks_repo_name": "pitsianis/LightGraphs.jl", "max_forks_repo_head_hexsha": "90989ef1248115c8735bff2f5d5775329b7f4eb0", "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": 30.4852941176, "max_line_length": 61, "alphanum_fraction": 0.5928605885, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7518387707428428}}
{"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    \u03b3s = scale ./10 .^(1:5)\n    err2 = []\n    err1 = []\n    f0, J = f(x0)\n    for i = 1:5\n        f1, _ = f(x0+\u03b3s[i]*v0)\n        push!(err1, norm(f1-f0))\n        # @show f1, f0, 2\u03b3s[i]*J*v0\n        push!(err2, norm(f1-f0-\u03b3s[i]*J*v0))\n        # push!(err2, norm((f1-f2)/(2\u03b3s[i])-J*v0))\n        # #@show \"test \", f1, f2, f1-f2\n    end\n    close(\"all\")\n    loglog(\u03b3s, err2, label=\"Automatic Differentiation\")\n    loglog(\u03b3s, err1, label=\"Finite Difference\")\n    loglog(\u03b3s, \u03b3s.^2 * 0.5*abs(err2[1])/\u03b3s[1]^2, \"--\",label=\"\\$\\\\mathcal{O}(\\\\gamma^2)\\$\")\n    loglog(\u03b3s, \u03b3s * 0.5*abs(err1[1])/\u03b3s[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] \u22c5 x\n        F -= cji ^ 2\n        x_new -= cji * bases[j]\n    end\n    x_new /= \u221aF\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(\u2207Cs)\n    N_C = length(\u2207Cs)\n    \u2207C_unit_new = normalize.(\u2207Cs)\n    P = I\n    @inbounds for i = 1:N_C\n        \u2207C_unit_new[i] = orthogonalize(\u2207C_unit_new[i], \u2207C_unit_new[1:i-1])\n        tmp = flatten(\u2207C_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# \u2554\u2550\u2561 8c3e21c9-6514-4f14-8b1f-325d124681f5\nusing DifferentialEquations\n\n# \u2554\u2550\u2561 ac95a2ae-5b1b-4399-8265-4b0bfb21162e\nusing ParameterizedFunctions\n\n# \u2554\u2550\u2561 2e6401b9-9c89-4b4b-8492-d0a83003579b\nusing PlutoUI,Plots, HypertextLiteral\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u2019s 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})\u00b7n +\u00b7\u00b7\u00b7\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})\u00b7n +\u00b7\u00b7\u00b7\n\\end{align*}\n```\n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 10ba443a-d7bc-40f2-b4f6-540328ce6e4b\nN=collect(0:0.1:K);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 04c14475-24cd-49c3-8a7b-83a9425664be\nA = [1 0;1 1;0 1];B = [2 0;0 2;0 0];(B-A)'\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e6f51a60-9701-4ba6-a6e6-9703f7c9ebf9\nhttps://cs.carleton.edu/faculty/awb/cs111/f19/worksheets/lotka-volterra/Lotka-Volterra%20equation.pdf\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c3828c90-0559-4686-9f56-41b5b6d48176\nbegin\n\tx\u2080=1\n\ty\u2080=1\n\tt\u2080=0.0\n\tfinal_time=10.0;\n\tprob = ODEProblem(lv!,[x\u2080,y\u2080],(t\u2080,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# \u2554\u2550\u2561 ff0c4a06-de7b-4cf2-b920-cd84ac9927ea\n[u[1] for (u,t) in tuples(sol)]\n\n\n# \u2554\u2550\u2561 f8238a6e-1e5e-4629-ac20-2c9cb964c53e\ntuples(sol)\n\n# \u2554\u2550\u2561 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\u2080*2,y\u2080*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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500279eaa4f-41ca-4168-b492-f36543bb8204\n# \u255f\u250000037d0a-8be0-4c75-94bc-23c2c639e6e8\n# \u255f\u250064dc539b-b268-43b6-a96e-2c4fa7b48474\n# \u255f\u2500f5faefd6-f496-40fb-8043-ef6b9d172ae0\n# \u255f\u250032b3bc77-c4f4-40ab-a5a9-e035022189ac\n# \u255f\u2500c70c7a06-d1aa-40a9-902b-4bd4b23a6392\n# \u2560\u255010ba443a-d7bc-40f2-b4f6-540328ce6e4b\n# \u2560\u25502cfd31c4-803a-4880-b2a4-5af6594c0975\n# \u255f\u25002170f883-1b01-4d16-907e-49c72118e224\n# \u255f\u25006c87979a-690a-400b-9ab8-7ef26b829195\n# \u2560\u255004c14475-24cd-49c3-8a7b-83a9425664be\n# \u255f\u2500919bf3e4-6aa0-440b-b76f-34a4812c6752\n# \u255f\u2500855b8530-861e-427e-b6cc-c1b0283568ca\n# \u255f\u2500c112e62c-9c38-48dc-8294-42911b02ccc5\n# \u255f\u25006c96da07-b5ea-4096-a14c-5cd8f0f47c04\n# \u255f\u2500906a0931-e86f-48f3-be11-eb692639e8cc\n# \u2560\u2550c374e1bd-ec3d-4cf7-aff1-072d6ba60b27\n# \u2560\u25502b91a06c-3803-4877-ac9a-1669fbe58d30\n# \u2560\u2550e8ca5682-cce0-4b2c-ba18-47f2e38192c7\n# \u255f\u250017e34ce6-a1fa-4193-9201-3e61a188b48f\n# \u2560\u255087df7c88-7e16-4c50-bd80-df5bfea26ee8\n# \u255f\u25009433f4d1-3abf-4dea-8107-1070ee5feb2e\n# \u2560\u2550c3828c90-0559-4686-9f56-41b5b6d48176\n# \u2560\u2550e6f51a60-9701-4ba6-a6e6-9703f7c9ebf9\n# \u255f\u25002b9e43fd-d00d-40f1-ac98-07d48c53d861\n# \u2560\u2550ff0c4a06-de7b-4cf2-b920-cd84ac9927ea\n# \u2560\u2550f8238a6e-1e5e-4629-ac20-2c9cb964c53e\n# \u2560\u2550df81eb5c-16ef-4bf6-9ad0-2cc899c44cb6\n# \u2560\u2550a5b38e90-cdbe-442f-a078-dd8598a0a4c2\n# \u2560\u25508c3e21c9-6514-4f14-8b1f-325d124681f5\n# \u2560\u2550ac95a2ae-5b1b-4399-8265-4b0bfb21162e\n# \u2560\u25503349c942-15a8-4b1e-8b4a-7f5154f48b12\n# \u2560\u2550cf72446a-a512-11ec-2b47-ef706c91c6a0\n# \u2560\u255067091261-3b6c-4a94-9a70-86519a1eed76\n# \u2560\u25502e6401b9-9c89-4b4b-8492-d0a83003579b\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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, \u03c3, that we have been using already lives within `Flux`:\n\n#nb ?\u03c3\n#jl @doc \u03c3\n\n#-\n\nplot(\u03c3, -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, \u03c3)\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\u03c3.(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, \u03c3)\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, \u03c3)\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\u221e = Inf\n\t@variables \u03b1, \u03b2, \u03c1, \u03b4, \u03c3\n\t@variables t::Integer, k(..), z(..), c(..), q(..), i(..)\n\t@variables \u03a9_1\n\tx = [k, z]\n\ty = [c, q, i]\n\tp = [\u03b1, \u03b2, \u03c1, \u03b4, \u03c3, \u03a9_1]\n\n\tH = [1 / c(t) - (\u03b2 / c(t + 1)) * (\u03b1 * exp(z(t + 1)) * k(t + 1)^(\u03b1 - 1) + (1 - \u03b4)),\n\tc(t) + k(t + 1) - (1 - \u03b4) * k(t) - q(t),\n\tq(t) - exp(z(t)) * k(t)^\u03b1,\n\tz(t + 1) - \u03c1 * z(t),\n\ti(t) - (k(t + 1) - (1 - \u03b4) * k(t))]\n\n\tsteady_states = [k(\u221e) ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1)), z(\u221e) ~ 0,\n\t\t\t\tc(\u221e) ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)) -\n\t\t\t\t\t\t\u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1)),\n\t\t\t\tq(\u221e) ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)),\n\t\t\t\ti(\u221e) ~ \u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1))]\n\n\tsteady_states_iv = [k(\u221e) ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1)), z(\u221e) ~ 0,\n\t\t\t\tc(\u221e) ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)) -\n\t\t\t\t\t\t\u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1)),\n\t\t\t\tq(\u221e) ~ (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(\u03b1 / (\u03b1 - 1)),\n\t\t\t\ti(\u221e) ~ \u03b4 * (((1 / \u03b2) - 1 + \u03b4) / \u03b1)^(1 / (\u03b1 - 1))]\n\n\tn_\u03f5 = 1\n\tn_x = length(x)\n\tn_y = length(y)\n\tn_p = length(p)\n\t\u0393 = reshape([\u03c3], n_\u03f5, n_\u03f5)\n\t\u03b7 = reshape([0; -1], n_x, n_\u03f5) # \u03b7 is n_x * n_\u03f5 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\u03a9 = [\u03a9_1, \u03a9_1]\n\t\n\treturn H, (; t, x, y, p, steady_states, steady_states_iv, \u0393, \u03b7, \u03a9, 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": "using BenchmarkTools\nusing Distributions\nusing GLM\nusing HypothesisTests\nusing LinearAlgebra\nusing Plots\nusing Random\nusing RDatasets\nusing SpecialFunctions\nusing Statistics\n\n\n\n\n# Ridge regression\n\nn = 10000\nm = 1000\n\nRandom.seed!(666)\nX = randn(n, m)\n\ny = 10*X[:,1] + X[:,2] + randn(n)\n\n# Exercise\n\n\n\n# Comparison\n\n@btime ridge_reg(X, y, 10);\n\n@btime ridge_reg(X, y, 10, Q, Q_inv, \u03bb);\n\n# Dependence on mu\n\n\u03bcs = range(0, 1000; length=50)\n\nws = hcat(ridge_reg.(Ref(X), Ref(y), \u03bcs, Ref(Q), Ref(Q_inv), Ref(\u03bb))...)\n\nplot(\u03bcs, abs.(ws');\n    label=\"\",\n    yscale=:log10,\n    xlabel=\"mu\",\n    ylabel=\"weights: log scale\",\n)\n\n# LASSO\n\nS(x, \u03b7) = max(x-\u03b7, 0) - max(-x-\u03b7, 0)\n\nfunction lasso(X, y, \u03bc, Q, Q_inv, \u03bb;        \n        max_iter = 100,\n        \u03c1 = 1e3,\n        w = zeros(size(X,2)),\n        u = zeros(size(X,2)),\n        z = zeros(size(X,2)),\n    )\n    \n    for i in 1:max_iter\n        w = Q * ( (Diagonal(1 ./ (\u03bb .+ \u03c1)) * ( Q_inv * (X'*y + \u03c1*(z-u))))) \n        z = S.(w + u, \u03bc / \u03c1)\n        u = u + w - z\n    end\n    return w, u, z  \nend\n\nws = zeros(size(X,2), length(\u03bcs))\n\nfor (i, \u03bc) in enumerate(\u03bcs)\n    global w, u, z\n    w, u, z = i > 1 ? lasso(X, y, \u03bc, Q, Q_inv, \u03bb; w, u, z) : lasso(X, y, \u03bc, Q, Q_inv, \u03bb)\n    ws[:,i] = w\nend\n\nplot(\u03bcs, abs.(ws');\n    label=\"\",\n    yscale=:log10,\n    xlabel=\"mu\",\n    ylabel=\"weights: log scale\",\n)\n\n\n\n\n\n\nplot(0:0.1:10, gamma;\n    xlabel=\"x\",\n    ylabel=\"gamma(x): log scale\",\n    label=\"\",\n    yscale=:log10,\n)\n\n# Exercise\n\n\n\n# Exercise\n\n\n\n# Volume of a ball\n\nms = 1:15\nns = Int64.([1e1; 1e3; 1e5])\n\nRandom.seed!(666)\n\nplt = plot(ms, m -> volume_true(m, 1);\n    xlabel=\"dimension\",\n    ylabel=\"unit ball volume\",\n    legend=:topleft,\n    label=\"True\",\n    line=(4,:black),\n)\n\nfor n in ns\n    plot!(plt, ms, m -> volume_monte_carlo.(m; n=n); label=\"n = $n\")\nend\n\ndisplay(plt)\n\n# Generating from the uniform distributions\n\nrand(Uniform(-1, 1), 10, 5)\n\n# Sampling from distributions\n\nd1 = Normal()\nd2 = Normal(1, 1)\nd3 = Normal(0, 0.01)\n\nf1(x) = pdf(d1, x)\nf2(x) = pdf(d2, x)\nf3(x) = pdf(d3, x)\n\nfunction plot_histogram(xs, f; kwargs...)\n    plt = histogram(xs;\n        label=\"Sampled density\",\n        xlabel = \"x\",\n        ylabel = \"pdf(x)\",\n        nbins = 85,\n        normalize = :pdf,\n        opacity = 0.5,\n        kwargs...\n    )\n\n    plot!(plt, range(minimum(xs), maximum(xs); length=100), f;\n        label=\"True density\",\n        line=(4,:black),\n    )\n\n    return plt\nend\n\nplot_histogram(rand(d1, 1000000), f1)\n\n# Exercise\n\n\n\n# Rejection sampling\n\nxlims = (-10, 10)\n\nfor (f, d) in zip((f1, f2, f3), (d1, d2, d3))\n    Random.seed!(666)\n    xs = rejection_sampling(f, f(d.\u03bc), xlims...)\n\n    pl = plot_histogram(xs, f)\n    display(pl)\nend\n\n# Exercise\n\n\n\n# Hypothesis testing\n\nRandom.seed!(666)\n\nn = 1000\nxs = randn(n)\n\n# Exercise\n\n\n\n# One-sample t-test\n\nOneSampleTTest(xs)\n\n# Linear models\n\nwages = dataset(\"plm\", \"Snmesp\")\nwages.W = 2. .^ (wages.W)\n\n\nX = Matrix(wages[:, [:N, :Y, :I, :K, :F]])\nX = hcat(ones(size(X,1)), X)\ny = wages[:, :W]\n\nw0 = (X'*X) \\ (X'*y)\n\nmodel = lm(@formula(W ~ 1 + N + Y + I + K + F), wages)\n\n# Exercise\n\n\n\n\n# Plot histograms\n\ny_hat = predict(model)\n\nplot_histogram(y_hat, x -> pdf(Normal(mean(y_hat), std(y_hat)), x))\n\nplot_histogram(y_hat, x -> pdf(fit(Normal, y_hat), x))\n\ntest_normality = ExactOneSampleKSTest(y_hat, Normal(mean(y_hat), std(y_hat)))\n\n# Generalized linear models\n\nmodel = glm(@formula(W ~ 1 + N + Y + I + K + F), wages, InverseGaussian(), SqrtLink())\n\n# Exercise\n\n\n", "meta": {"hexsha": "9afef4edf46582ff156bea502a358e41a050ef91", "size": 3453, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/lecture_11/script.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_11/script.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_11/script.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": 15.0130434783, "max_line_length": 88, "alphanum_fraction": 0.5621198957, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7516158995808577}}
{"text": "\"\"\"\n    IdentityMap\n\nAn identity map,\n\n```math\n    x \u21a6 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 \u21a6 x,\u2003x(t) \u2208 \\\\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 \u21a6 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 \u21a6 Ax,\u2003x(t) \u2208 \\\\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 \u21a6 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 \u21a6 Ax + b, x(t) \u2208 \\\\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) \u21a6 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) \u21a6 Ax + Bu, x \u2208 \\\\mathcal{X}, u \u2208 \\\\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) \u21a6 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) \u21a6 Ax + Bu + c, x \u2208 \\\\mathcal{X}, u \u2208 \\\\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 \u21a6 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 \u21a6 R(x),\u2003x \u2208 \\\\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    \u03c3::Vector{Int}\nend\n\nSn{N} = SymmetricGroup{N}\nSymmetricGroup(\u03c3::Vector{Int}) = SymmetricGroup{length(\u03c3)}(\u03c3)\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    \u03c3 = shuffle(1:N)\n    Sn(\u03c3)\nend\n\n# Defining representation\n\n@inbounds function defrep!{N, T}(M::Matrix{T}, g::Sn{N})\n    \u03c3 = g.\u03c3\n    n = size(M, 1)\n    for i in 1:n, j in 1:n\n        if i == \u03c3[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\u2081::Sn{N}, g\u2082::Sn{N})\n    Sn{N}(g\u2081.\u03c3[g\u2082.\u03c3])\nend\n\n# Inversion\nfunction inv{N}(g::Sn{N})\n    Sn{N}(indexin(1:N, g.\u03c3))\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": "@testset \"\u03b1 Filter\" begin\n\n\t@testset \"1D \u03b1 Filter\" begin\n\t\t# Input Data\n\t\tV = [ 1. 3. 2. 6. 7. 8. 12. 10. ]\n\t\tDT = AlphaShapes.delaunayTriangulation(V)\n\n\t\t# Expected Output\n\t\tVV = [[1],[2],[3],[4],[5],[6],[7],[8]]\n\t\tEV = [[1,3],[2,3],[2,4],[4,5],[5,6],[6,8],[7,8]]\n\n\t\t# Evaluation\n\t\tfilter = AlphaShapes.alphaFilter(V, DT)\n\n\t\t@test length(unique(values(filter))) == 4\n\t\t@test sort(unique(values(filter))) == [0.0, 0.5, 1.0, 1.5]\n\t\t@test length(unique(keys(filter))) == 15\n\t\t@test sort([v for v in unique(keys(filter)) if length(v) == 2]) == EV\n\tend\n\n\t@testset \"2D \u03b1 Filter\" begin\n\t\t# Input Data\n\t\tV = [\n\t\t\t0.0 1.0 0.0 2.0;\n\t\t\t0.0 0.0 1.0 2.0\n\t\t]\n\n\t\t# Expected Output\n\t\tVV = [[1],[2],[3],[4]]\n\t\tEV = [[1, 2],[1, 3],[2, 3],[2, 4],[3, 4]]\n\t\tFV = [[1, 2, 3],[2, 3, 4]]\n\n\t\t# Evaluation\n\t\tfilter = AlphaShapes.alphaFilter(V)\n\n\t\t@test length(unique(values(filter))) == 5\n\t\t@test isapprox(sort(unique(values(filter))),\n\t\t\t[0.0, 0.5, 0.7071, 1.1180, 1.1785], atol=1e-4\n\t\t)\n\t\t@test length(unique(keys(filter))) == 11\n\t\t@test sort([v for v in unique(keys(filter)) if length(v) == 1]) == VV\n\t\t@test sort([v for v in unique(keys(filter)) if length(v) == 2]) == EV\n\t\t@test sort([v for v in unique(keys(filter)) if length(v) == 3]) == FV\n\tend\n\n\t# @testset \"3D \u03b1 Filter\" begin\n\t# \tV = [\n\t# \t\t0.0 1.0 0.0 0.0 1.0 0.0;\n\t# \t\t0.0 0.0 1.0 0.0 0.0 1.0;\n\t# \t\t0.0 0.0 0.0 1.0 1.0 2.0\n\t# \t]\n\t#\n\t# \t# Expected Output\n\t# \tVV = [[1],[2],[3],[4],[5],[6]]\n\t# \tCV = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]\n\t# \t# Evaluation\n\t# \tfilter = AlphaShapes.alphaFilter(V, digits=4)\n\t#\n\t# \t@test length(unique(values(filter))) == 6\n\t# \t@test sort(unique(values(filter))) == [0.0, 0.5, 0.7071, 0.866, 1.0, 1.118]\n\t# \t@test length(unique(keys(filter))) == 31\n\t# \t@test sort([v for v in unique(keys(filter)) if length(v) == 1]) == VV\n\t# \t@test sort([v for v in unique(keys(filter)) if length(v) == 4]) == CV\n\t# end\n\nend\n\n@testset \"\u03b1 Simplices Evaluation\" begin\n\n\t@testset \"1D \u03b1 Simplex\" begin\n\t\t# Input Data\n\t\tV = [\n\t\t\t0.0 1.0 2.0 7.0 5.0 3.0 14.0 11.0\n\t\t]\n\t\tfiltration = AlphaShapes.alphaFilter(V)\n\n\t\t# \u03b1 = 0.0\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 0.0)\n\t\t@test \u03b1_simplices[1] == [[1],[2],[3],[4],[5],[6],[7],[8]]\n\t\t@test isempty(\u03b1_simplices[2])\n\t\t# \u03b1 = 0.5\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 0.5)\n\t\t@test \u03b1_simplices[2] == [[1,2],[2,3],[3,6]]\n\t\t# \u03b1 = 1.0\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 1.0)\n\t\t@test \u03b1_simplices[2] == [[1, 2], [2, 3], [3, 6], [4, 5], [5, 6]]\n\t\t# \u03b1 = 1.5\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 1.5)\n\t\t@test \u03b1_simplices[2] == [[1, 2], [2, 3], [3, 6], [4, 5], [5, 6], [7, 8]]\n\n\tend\n\n\t@testset \"2D \u03b1 Simplex\" begin\n\t\t# Input Data\n\t\tV = [\n\t\t\t0.0 1.0 0.0 2.0;\n\t\t\t0.0 0.0 1.0 0.3\n\t\t]\n\t\tfiltration = AlphaShapes.alphaFilter(V)\n\n\t\t# \u03b1 = 0.0\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 0.0)\n\t\t@test \u03b1_simplices[1] == [[1],[2],[3],[4]]\n\t\t@test isempty(\u03b1_simplices[2])\n\t\t@test isempty(\u03b1_simplices[3])\n\t\t# \u03b1 = 0.5\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 0.5)\n\t\t@test \u03b1_simplices[2] == [[1,2],[1,3]]\n\t\t@test isempty(\u03b1_simplices[3])\n\t\t# \u03b1 = 1.0\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 1.0)\n\t\t@test \u03b1_simplices[2] == [[1,2],[1,3],[2,3],[2,4]]\n\t\t@test \u03b1_simplices[3] == [[1,2,3]]\n\t\t# \u03b1 = 1.5\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 1.5)\n\t\t@test \u03b1_simplices[2] == [[1,2],[1,3],[2,3],[2,4],[3,4]]\n\t\t@test \u03b1_simplices[3] == [[1,2,3],[2,3,4]]\n\n\tend\n\n\t@testset \"3D \u03b1 Simplex\" begin\n\t\t# Input Data\n\t\tV = [\n\t\t\t0.0  1.0  0.0  0.0  2.0;\n\t\t\t0.0  0.0  1.0  0.0  2.0;\n\t\t\t0.0  0.0  0.0  1.0  2.0\n\t\t]\n\t\tfiltration = AlphaShapes.alphaFilter(V)\n\n\t\t# \u03b1 = 0.0\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 0.0)\n\t\t@test \u03b1_simplices[1] == [[1],[2],[3],[4],[5]]\n\t\t@test isempty(\u03b1_simplices[2])\n\t\t@test isempty(\u03b1_simplices[3])\n\t\t@test isempty(\u03b1_simplices[4])\n\t\t# \u03b1 = 0.5\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 0.5)\n\t\t@test \u03b1_simplices[2] == [[1,2],[1,3],[1,4]]\n\t\t@test isempty(\u03b1_simplices[3])\n\t\t@test isempty(\u03b1_simplices[4])\n\t\t# \u03b1 = 1.0\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 1.0)\n\t\t@test \u03b1_simplices[2] == [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\n\t\t@test \u03b1_simplices[3] == [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]\n\t\t@test \u03b1_simplices[4] == [[1,2,3,4]]\n\n\t\t# \u03b1 = 1.5\n\t\t\u03b1_simplices = AlphaShapes.alphaSimplex(V, filtration, 1.6)\n\t\t@test \u03b1_simplices[4] == [[1,2,3,4],[2,3,4,5]]\n\tend\n\nend\n", "meta": {"hexsha": "26afc2f9d794cc4465858c356d057126f0977ab1", "size": 4398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/alpha_complex.jl", "max_stars_repo_name": "luigibvl/AlphaShapes.jl", "max_stars_repo_head_hexsha": "f073366f8ab6b15964c9879dad5ccedddd60f2a1", "max_stars_repo_licenses": ["MIT"], "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/alpha_complex.jl", "max_issues_repo_name": "luigibvl/AlphaShapes.jl", "max_issues_repo_head_hexsha": "f073366f8ab6b15964c9879dad5ccedddd60f2a1", "max_issues_repo_licenses": ["MIT"], "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/alpha_complex.jl", "max_forks_repo_name": "luigibvl/AlphaShapes.jl", "max_forks_repo_head_hexsha": "f073366f8ab6b15964c9879dad5ccedddd60f2a1", "max_forks_repo_licenses": ["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.7450980392, "max_line_length": 79, "alphanum_fraction": 0.5698044566, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7516084019141241}}
{"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\u2080(t) = exp(-t^2)\r\n\u03c9\u2080(t) = 100\r\n\u03c6\u2080 = 0\r\n\ud835\udc36\u2080 = Tuple([a\u2080,\u03c9\u2080,\u03c6\u2080])\r\n\r\n#DEFINE 0th COMPONENT\r\n\u03c8\u2080 = AMFMcomp(\ud835\udc36\u2080)\r\n\r\n#DEFINE 1st CANONICAL TRIPLET\r\na\u2081(t) = 1\r\n\u03c9\u2081(t) = 10*t\r\n\u03c6\u2081 = \u03c0\r\n\ud835\udc36\u2081 = Tuple([a\u2081,\u03c9\u2081,\u03c6\u2081])\r\n\r\n#DEFINE 2nd CANONICAL TRIPLET\r\na\u2082(t) = 0.8*cos(2t)\r\n\u03c9\u2082(t) = 10 + 7.5*sin(t)\r\n\u03c6\u2082 = \u03c0\r\n\ud835\udc36\u2082 = Tuple([a\u2082,\u03c9\u2082,\u03c6\u2082])\r\n\r\n#DEFINE THE COMPONENT SET\r\n\ud835\udc46 = [\ud835\udc36\u2080,\ud835\udc36\u2081,\ud835\udc36\u2082]\r\n\r\n#DEFINE THE AMFM MODEL\r\nz = AMFMmodel(\ud835\udc46)\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\u03c8\u2080(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\u2096(k) = 1\r\nkInds = Vector(-10:10)\r\n\r\nz\u2080 = fourierSeries(T,a\u2096,kInds)\r\n\r\n\r\n#----------------------------\r\n# PLOTS\r\n#----------------------------\r\n\r\np1 = isaPlot3d(\ud835\udc36\u2081, t)\r\n\r\np2 = isaPlot3d(\u03c8\u2080, t)\r\n\r\np3 = isaPlot3d(z\u2080, t, FreqUnits=\"Hz\")\r\n\r\np4 = isaPlot3d(\ud835\udc46, 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\u2080<h\u2081<h\u2082`.\n`h\u2081` is the minimum, `h\u2082` is the maximum of the wave.\nAs `h\u2080 -> h\u2081`, 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\u2080<h\u2081<h\u2082` and dimensionless parameters `\u03f5` and `\u03bc`, 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`(\u03b7,u,v,mesh,param)` with\n- `\u03b7 :: 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        \u03f5 = param.\u03f5\n        \u03bc = param.\u03bc\n\n        h\u2080=param.h\u2080\n        h\u2081=param.h\u2081\n        h\u2082=param.h\u2082\n        c = sqrt(h\u2080*h\u2081*h\u2082)\n        m = sqrt((h\u2082-h\u2081)/(h\u2082-h\u2080))\n        \u03ba = sqrt(3*(h\u2082-h\u2080))/(2*c)/sqrt(\u03bc)\n        \u03bb = Elliptic.K(m^2)/\u03ba\n        mesh = Mesh((L=P*\u03bb,N=param.N))\n        formula = h\u2081 .-1 .+ (h\u2082-h\u2081)*(Jacobi.cn.(\u03ba*mesh.x,m^2).^2)\n\n        a\u2080 = h\u2080\n        a\u2081 = h\u2082 - h\u2080\n        formula2 = a\u2080 .-1 .+ a\u2081*(Jacobi.dn.(\u03ba*mesh.x,m^2).^2)\n        H\u2080= a\u2080+a\u2081*Elliptic.E(m^2)/Elliptic.K(m^2)\n        u2 = c*(1 ./ H\u2080 .- 1 ./(1 .+ formula2))\n        param = (h\u2080=h\u2080,h\u2081=h\u2081,h\u2082=h\u2082,a\u2080=a\u2080,a\u2081=a\u2081,H\u2080=H\u2080,c=c,\u03bb=\u03bb,m=m,\u03ba=\u03ba)\n\n\n        \u03b7 = formula/\u03f5\n        h = 1 .+ \u03f5*\u03b7\n        u = c*\u03b7./h\n\t\tk = mesh.k\n        Dx=  1im * k\n\t\tF\u2080 = sqrt(\u03bc)*Dx\n        DxF(v) = real.(ifft(F\u2080 .* fft(v)))\n\t\tv = u - 1/3 ./h .* (DxF(h.^3 .*DxF(u)))\n        #\n        # h2 = 1 .+ \u03f5*formula2\n        # v2 = u2 - 1/3 ./h2 .* (DxF(h2.^3 .*DxF(u2)))\n\n        return (\u03b7,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\u03b7\n\tv\n\tlabel :: String\n\tinfo  :: String\n\n\tfunction CnoidalSGN(param; P=1)\n\t\t(\u03b7,u,v,mesh,para)=CnoidalWaveSerreGreenNaghdi(param; P)\n\t\tinit = Init(mesh,\u03b7,v)\n\t\tlabel = \"Green-Naghdi cnoidal wave\"\n\t\tinfo = \"Cnoidal travelling wave for the Serre-Green-Naghdi model.\\n\\\n\t\t\u251c\u2500velocity c = $(para.c)\\n\u251c\u2500\u2500\u2500period P = $(2(para.\u03bb))\\n\\\n\t\t\u251c\u2500maximum h\u2082 = $(para.h\u2082) (from bottom)\\n\u2514\u2500minimum h\u2081 = $(para.h\u2081) (from bottom).\"\n\n\t\tnew( init.\u03b7,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": "module CDLagrangianFESpacesTests\n\nusing Test\nusing Gridap.Geometry\nusing Gridap.ReferenceFEs\nusing Gridap.FESpaces\nusing Gridap.CellData\nusing Gridap.TensorValues\nusing Gridap.Fields\n\ndomain =(0,1,0,1)\npartition = (3,3)\nmodel = CartesianDiscreteModel(domain,partition)\n\n# order = 1\norders = (2,1)\norder = 2*max(orders...)\n\n\u03a9 = Triangulation(model)\nd\u03a9 = Measure(\u03a9,order)\n\nT = VectorValue{2,Float64}\n\nV = FESpace(model,ReferenceFE(lagrangian,T,orders),conformity=CDConformity((DISC,CONT)))\ntest_single_field_fe_space(V)\nu(x) = x\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(\u222b(e\u22c5e)*d\u03a9))\n@test el2 < 1.0e-10\n\nreffe = LagrangianRefFE(T,QUAD,2)\nV = FESpace(model,ReferenceFE(lagrangian,T,2),conformity=CDConformity((CONT,DISC)))\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(\u222b(e\u22c5e)*d\u03a9))\n@test el2 < 1.0e-10\n\nV = FESpace(model,ReferenceFE(lagrangian,T,(2,0)),conformity=CDConformity((CONT,DISC)))\nu(x) = VectorValue(x[1],0.0)\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(\u222b(e\u22c5e)*d\u03a9))\n@test el2 < 1.0e-10\n\nV = FESpace(model,ReferenceFE(lagrangian,T,(2,0)),conformity=CDConformity((DISC,DISC)))\nu(x) = VectorValue(x[1],0.0)\nU = TrialFESpace(V,u)\nuh = interpolate(u,U)\ne = u - uh\nel2 = sqrt(sum(\u222b(e\u22c5e)*d\u03a9))\n@test el2 < 1.0e-10\n\n\n# # Skeleton triangulation\n# face_own_dofs = get_face_own_dofs(reffe)\n# strian = SkeletonTriangulation(model,reffe,face_own_dofs)\n# ns = get_normal_vector(strian)\n# writevtk(strian,\"strian\",cellfields=[\"normal\"=>ns])\n#\n# # Random function for visualization purposes\n# model = CartesianDiscreteModel((0,1,0,1),(10,5))\n# V = FESpace(model=model,reffe=reffe,conformity=true)\n# trian = Triangulation(model)\n# vh = FEFunction(V,rand(num_free_dofs(V)))\n# writevtk(trian,\"trian\",nsubcells=20,cellfields=[\"vh\"=>vh])\n\n#using Gridap.Visualization\n#\n#writevtk(trian,\"trian\",nsubcells=10,cellfields=[\"uh\"=>uh])\n\nend # module\n", "meta": {"hexsha": "e41b061b075fffec0f8f7fca91d97d6d1119652e", "size": 1905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FESpacesTests/CDLagrangianFESpacesTests.jl", "max_stars_repo_name": "aerappa/Gridap.jl", "max_stars_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 390, "max_stars_repo_stars_event_min_datetime": "2019-05-16T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:17.000Z", "max_issues_repo_path": "test/FESpacesTests/CDLagrangianFESpacesTests.jl", "max_issues_repo_name": "aerappa/Gridap.jl", "max_issues_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 576, "max_issues_repo_issues_event_min_datetime": "2019-05-16T20:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:21:35.000Z", "max_forks_repo_path": "test/FESpacesTests/CDLagrangianFESpacesTests.jl", "max_forks_repo_name": "aerappa/Gridap.jl", "max_forks_repo_head_hexsha": "1fb3dc9abf8c47685637901bd14a74e4355a9492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2019-12-30T23:35:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:56:24.000Z", "avg_line_length": 25.0657894737, "max_line_length": 88, "alphanum_fraction": 0.7154855643, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7516083847929422}}
{"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\u03bc_income = 50_000; # Mean income\n\u03c3_income = 12_000; # Standard deviation of income\n\ud835\udc03 = Normal(\u03bc_income, \u03c3_income)\n\n# Decider for selecting two agents to collide\n\ud835\udc14 = Uniform(1, n_pop)\n\n# vector of initial income of individual\nval_inc_ini = deepcopy(rand(\ud835\udc03, 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 \u2208 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    \u03c1 = 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 * \u03c1, total_wealth * (1 - \u03c1)\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: $(\u03bc_income); std - true: $(\u03c3_income)\")\nprintln(\"Mean: $(mean(val_inc_trc[:,end])); std: $(std(val_inc_trc[:,end]))\")\n@gif for i \u2208 1:10:n_iter\n    histogram(val_inc_trc[:,i], title = \"Iteration: $(i)\", xlims = (0,1e5))\nend every 5\n\nprintln(\"Mean - true: $(\u03bc_income); std - true: $(\u03c3_income)\")\nprintln(\"Mean: $(mean(val_inc_trc_rand[:,end])); std: $(std(val_inc_trc_rand[:,end]))\")\n@gif for i \u2208 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\u00e7\u00e3o criar um e depor retornar\nparticles2 = pso(myfunc, lb, ub, minstep=1e-3);\n\nm\u00ednimo 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": "\nusing SafeTestsets\n\n@safetestset \"Linear Solvers                                                                  \" begin include(\"linear_solvers_tests.jl\") end\n@safetestset \"Jacobians                                                                       \" begin include(\"jacobian_tests.jl\") end\n@safetestset \"Nonlinear Solvers                                                               \" begin include(\"nonlinear_solvers_tests.jl\") end\n", "meta": {"hexsha": "b289d8ae6857a1fb7cbde6690e89859b59fed4e3", "size": 441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/solvers/solvers_tests.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": "test/solvers/solvers_tests.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": "test/solvers/solvers_tests.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": 63.0, "max_line_length": 143, "alphanum_fraction": 0.4444444444, "num_tokens": 72, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8333245932423309, "lm_q1q2_score": 0.7515926831027259}}
{"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": "@testset \"790.domino-and-tromino-tiling.jl\" begin\n    let \n        res = [1, 2, 5, 11, 24, 53, 117, 258, 569, 1255]\n        for i in 1:10\n            @test num_tilings(i) == res[i]\n        end\n    end \nend", "meta": {"hexsha": "7754e35a1de36e8c804e244dde5c98453a11ed46", "size": 205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/problems/790.domino-and-tromino-tiling.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": "test/problems/790.domino-and-tromino-tiling.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": "test/problems/790.domino-and-tromino-tiling.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.625, "max_line_length": 56, "alphanum_fraction": 0.512195122, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7515926809058266}}
{"text": "\"\"\"\nPackage: Forecast\n\n    sma(x, n; center = true)\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`: centers the moving averaged values in the response.\n\n# Returns\nVector of moving average smoothed values containing `missing` values to preserve the size of the original vector.\n\n# Examples\n```julia-repl\njulia> sma(1:5,3;center=true)\n5-element Array{Any,1}:\n  missing\n 2.0\n 3.0\n 4.0\n  missing\n```\n\"\"\"\nfunction sma(x, n; center = true)\n\n    N = length(x)\n    @assert 1 <= n & n <= N\n\n    if n == 1\n        return x\n    end\n\n    res = Vector{Any}(missing,N)\n\n    # initial and final value positions\n    ivp = findfirst(!ismissing, x)\n    fvp = findlast(!ismissing, x)\n    \n    # using missing values to center ma \n    a = center ? div(n,2) : 0\n\n    # initial moving average value\n    ma = sum(x[ivp:n+ivp-1])/n\n    res[a+ivp] = ma\n    for i in 1:(N-n-ivp-(N-fvp)+1)\n        resai = ma + (x[n+ivp+i-1] - x[ivp+i-1])/n\n        # missing values are imputed\n        res[a+ivp+i] = ismissing(resai) ? ma : resai\n        ma = res[a+ivp+i]\n    end\n\n    res\n\nend\n", "meta": {"hexsha": "fe061f1068be788b9ee7eb650a979229c71fef94", "size": 1143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sma.jl", "max_stars_repo_name": "vly/Forecast.jl", "max_stars_repo_head_hexsha": "c6542049a497935938e5c6ab06d320a220025420", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sma.jl", "max_issues_repo_name": "vly/Forecast.jl", "max_issues_repo_head_hexsha": "c6542049a497935938e5c6ab06d320a220025420", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sma.jl", "max_forks_repo_name": "vly/Forecast.jl", "max_forks_repo_head_hexsha": "c6542049a497935938e5c6ab06d320a220025420", "max_forks_repo_licenses": ["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.7068965517, "max_line_length": 113, "alphanum_fraction": 0.6036745407, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7515926795850235}}
{"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\u00d7%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 \u21db 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": "#=\n    The problems are taken from http://www.hakank.org/julia/constraints/\n\n    Thanks a lot to H\u00e5kan Kjellerstrand\n=#\n\nfunction cumulative(model, start, duration, resource, limit)\n    tasks = [i for i in 1:length(start) if resource[i] > 0 && duration[i] > 0]\n    num_tasks = length(tasks)\n    times_min_a = round.(Int,[JuMP.lower_bound(start[i]) for i in tasks])\n    times_min = minimum(times_min_a)\n    times_max_a = round.(Int,[JuMP.upper_bound(start[i])+duration[i] for i in tasks])\n    times_max = maximum(times_max_a)\n    for t in times_min:times_max\n        b  = @variable(model, [1:num_tasks], Bin)\n        for i in tasks\n            # is this task active during this time t?\n            @constraint(model, b[i] := { start[i] <= t && t < start[i]+duration[i]})\n        end\n        # Check that there's no conflicts in time t\n        @constraint(model,sum(b[i]*resource[i] for i in tasks) <= limit)\n    end\nend\n\n#\n# no_overlap(model, begins,durations)\n#\n# Ensure that there is no overlap between the tasks.\n#\nfunction no_overlap(model, begins,durations)\n    n = length(begins)\n    for i in 1:n, j in i+1:n\n        b = @variable(model,[1:2], Bin)\n        @constraint(model,b[1] := {begins[i] + durations[i] <= begins[j]})\n        @constraint(model,b[2] := {begins[j] + durations[j] <= begins[i]})\n        @constraint(model, sum(b) >= 1)\n    end\nend\n\n# From: http://www.hakank.org/julia/constraints/furniture_moving.jl\nfunction furniture_moving()\n\n    model = Model(optimizer_with_attributes(CS.Optimizer,\n                                                            \"logging\"=>[],\n\n                                                            \"traverse_strategy\"=>:BFS,\n                                                            \"branch_split\"=>:InHalf, # <-\n\n                                                            # \"lp_optimizer\" => cbc_optimizer,\n                                                            # \"lp_optimizer\" => glpk_optimizer,\n                                                            # \"lp_optimizer\" => ipopt_optimizer,\n                                        ))\n\n    # Furniture moving problem\n    n = 4\n    # [piano, chair, bed, table]\n    durations = [30,10,15,15]\n    resources = [3,1,3,2] # people needed per task\n    @variable(model, 0 <= start_times[1:n] <= 60, Int)\n    @variable(model, 0 <= end_times[1:n]   <= 60, Int)\n    @variable(model, 1 <= limit <= 3, Int)\n    @variable(model, 0 <= max_time <= 60, Int)\n    @constraint(model, end_times .<= max_time)\n\n    for i in 1:n\n        @constraint(model,end_times[i] == start_times[i] + durations[i])\n    end\n    cumulative(model, start_times, durations, resources, limit)\n\n    # @objective(model,Min,max_time)\n\n    optimize!(model)\n\n    status = JuMP.termination_status(model)\n    @assert status == MOI.OPTIMAL\n    @assert JuMP.value(limit) \u2248 3\nend\n\n# from http://www.hakank.org/julia/constraints/organize_day.jl\nfunction organize_day(problem,all_solutions=true)\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                                        ))\n    tasks = problem[:tasks]\n    durations = problem[:durations]\n    precedences = problem[:precedences]\n    start_time = problem[:start_time]\n    end_time = problem[:end_time]\n\n\n    n = length(tasks)\n    @variable(model, start_time <= begins[1:n] <= end_time, Int)\n    @variable(model, start_time <= ends[1:n] <= end_time, Int)\n\n    for i in 1:n\n        @constraint(model,ends[i] == begins[i] + durations[i])\n    end\n\n    no_overlap(model,begins,durations)\n\n    # precedences\n    for (a,b) in eachrow(precedences)\n        @constraint(model, ends[a] <= begins[b])\n    end\n\n    @constraint(model,begins[1] >= 11)\n\n    # Solve the problem\n    optimize!(model)\n\n    status = JuMP.termination_status(model)\n    # println(\"status:$status\")\n    @assert status == MOI.OPTIMAL\n    if all_solutions\n        @assert MOI.get(model, MOI.ResultCount()) == 5\n    end\nend\n", "meta": {"hexsha": "dca638862da25e620334765e371ac23d7eba511d", "size": 5113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmark/scheduling/benchmark.jl", "max_stars_repo_name": "Azzaare/ConstraintSolver.jl", "max_stars_repo_head_hexsha": "feec0320d9c26e16c2ced59bf11877ac7141ce8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 120, "max_stars_repo_stars_event_min_datetime": "2019-09-05T23:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:04:40.000Z", "max_issues_repo_path": "benchmark/scheduling/benchmark.jl", "max_issues_repo_name": "Azzaare/ConstraintSolver.jl", "max_issues_repo_head_hexsha": "feec0320d9c26e16c2ced59bf11877ac7141ce8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 273, "max_issues_repo_issues_event_min_datetime": "2019-09-05T11:20:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:57:00.000Z", "max_forks_repo_path": "benchmark/scheduling/benchmark.jl", "max_forks_repo_name": "Azzaare/ConstraintSolver.jl", "max_forks_repo_head_hexsha": "feec0320d9c26e16c2ced59bf11877ac7141ce8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-09-13T08:36:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T18:08:03.000Z", "avg_line_length": 38.1567164179, "max_line_length": 147, "alphanum_fraction": 0.5237629572, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7515926758516267}}
{"text": "using CSV\nusing Plots\nusing Pkg\nusing Random\n\nconcdata = CSV.read(\"/home/puranjay/ubc/term3/SGDBabysitter.jl/test/Concrete_Data.csv\", delim=',')\n\nX = concdata[1:8]\ny = concdata[9]\nn = size(X)[1]\nidxshuffle = shuffle(1:n)\nX = X[idxshuffle, :]\ny = y[idxshuffle, :]\nsplitval=750\nxtrain = convert(Array{Float64}, X[1:splitval, :])\nytrain = convert(Array{Float64}, y[1:splitval, :])\n\nxvalid = convert(Array{Float64}, X[splitval+1:end, :])\nyvalid = convert(Array{Float64}, y[splitval+1:end, :])\n\nxtrain = [ones(splitval,1) xtrain]\n# xvalid = [ones(n-splitval,1) xvalid]\nd = size(xtrain,2)\n\ninclude(\"NeuralNet.jl\")\nnHidden = [3,3,4,3]\nnParams = NeuralNet_nParams(d,nHidden)\nw = randn(nParams,1)\n\ninclude(\"sgdfunc.jl\")\nmaxIter = 10000\n\naTest = [0.1, 0.01, 0.001, 0.0001, 0.00001]\nBTest = [1, 5, 10, 20, 100] #200 500 1000\n\nbestvalid = Inf\nbestw = []\nbestparams3 = [0,0]\nfor B in BTest\n    for a in aTest\n        global bestvalid, bestw, bestparams3\n        wb, validerr = VanillaSGD(NeuralNet_backprop, NeuralNet_predict, maxIter, nHidden, nParams, xtrain, ytrain, xvalid, yvalid, a, B)\n        if (validerr[end]<bestvalid)\n            bestvalid=validerr[end]\n            bestw=wb\n            bestparams3 = [a,B]\n        end\n    end\nend\n\n#best hyperparams found to be [0.0001, 100]\nw_vconc, valid_vconc = VanillaSGD(NeuralNet_backprop, NeuralNet_predict, maxIter, nHidden,nParams, xtrain, ytrain, xvalid, yvalid, bestparams3[1], convert(Int64, bestparams3[2]))\nsavefig(\"Vanilla_Concrete.pdf\")\nw_conc, valid_conc = SGDBabysitter(NeuralNet_backprop, NeuralNet_predict, maxIter, nHidden, nParams, xtrain, ytrain, xvalid, yvalid)\nsavefig(\"SGDB_Concrete.pdf\")\nyhat_conc = NeuralNet_predict(w_conc,[ones(size(xvalid,1)) xvalid],nHidden)\n\nyhat_vconc = NeuralNet_predict(w_vconc,[ones(size(xvalid,1)) xvalid],nHidden)\n", "meta": {"hexsha": "a09f4b826c3d416e49228bc8b75964d67cca116d", "size": 1802, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/conctest.jl", "max_stars_repo_name": "JayCata/SGDBabysitter.jl", "max_stars_repo_head_hexsha": "78a1edef47bf8c8aa5f7e7447b4bbd0e61460e5a", "max_stars_repo_licenses": ["MIT"], "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/conctest.jl", "max_issues_repo_name": "JayCata/SGDBabysitter.jl", "max_issues_repo_head_hexsha": "78a1edef47bf8c8aa5f7e7447b4bbd0e61460e5a", "max_issues_repo_licenses": ["MIT"], "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/conctest.jl", "max_forks_repo_name": "JayCata/SGDBabysitter.jl", "max_forks_repo_head_hexsha": "78a1edef47bf8c8aa5f7e7447b4bbd0e61460e5a", "max_forks_repo_licenses": ["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.5423728814, "max_line_length": 178, "alphanum_fraction": 0.7031076582, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.751592675305731}}
{"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 \u2265 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": "import Splittings: UniformMesh, advection!, BSpline\n\n@testset \"BSL advections\" begin\n  \n  p = 5\n  n1, n2 = 128, 128\n  x1min, x1max = -10, 10\n  x2min, x2max = -10, 10\n  mesh1 = UniformMesh(x1min, x1max, n1; endpoint=false)\n  mesh2 = UniformMesh(x2min, x2max, n2; endpoint=false)\n\n  f  = zeros(Complex{Float64},(n1,n2))\n  f .= exp.(-mesh1.points.^2) * transpose(exp.(-mesh2.points.^2))\n  f\u1d57 = zeros(Complex{Float64},(n2,n1))\n\n  dt =  0.5\n\n  e = ones(Float64, n1)\n  v = ones(Float64, n2)\n\n  advection!(f,  mesh1,  v, n2, dt, BSpline(p))\n  transpose!(f\u1d57, f)\n  advection!(f\u1d57, mesh2,  e, n1, dt, BSpline(p))\n  transpose!(f,  f\u1d57)\n  advection!(f,  mesh1, -v, n2, dt, BSpline(p))\n  transpose!(f\u1d57, f)\n  advection!(f\u1d57, mesh2, -e, n1, dt, BSpline(p))\n  transpose!(f,  f\u1d57)\n\n  f0 =  exp.(-mesh1.points.^2) * transpose(exp.(-mesh2.points.^2))\n  println( maximum( abs.(real(f) -f0)))\n\n  @test real(f) \u2248 f0 atol=1e-6\n\nend\n", "meta": {"hexsha": "026eabf022d82e075fa061fef32b981360c2af37", "size": 905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_bsl.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": "test/test_bsl.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": "test/test_bsl.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": 25.1388888889, "max_line_length": 66, "alphanum_fraction": 0.617679558, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455083, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7515806400531463}}
{"text": "\r\ninclude(\"../src/numint_module.jl\")\r\n\r\n\r\nmodule ntest\r\nusing ..numint\r\nusing BenchmarkTools\r\n\r\n\r\n# fcn(x) = x^3\r\n# fcn(x) = x^4 * log(x + sqrt(x^2 + 1))\r\nfcn(x) = exp(-3*x) - cos(5*pi*x)\r\n\r\n\r\ninterval = numint.Interval(0.0, 8.0)\r\n\r\n\r\nN = 10000\r\n# I = numint.trapezoidal(fcn, interval, N)\r\nbt = @benchmark I = numint.trapezoidal(fcn, interval, N)\r\nshow(stdout, MIME(\"text/plain\"), bt)\r\n\r\n\r\n\r\nintegration_options = numint.RombergOptions(abs_tol = 1e-8, rel_tol = 1e-8, N = 250)\r\nbr = @benchmark stat_romb = numint.romberg($fcn, $interval, $integration_options)\r\nshow(stdout, MIME(\"text/plain\"), br)\r\n\r\nbgk = @benchmark stat_gk = numint.gauss_kronrod($fcn, $interval)\r\nshow(stdout, MIME(\"text/plain\"), bgk)\r\n\r\n\r\nend\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "83fa9891361524a3d0faceb59b5e5876f36459ba", "size": 723, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/numint/test/test_numint.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/test/test_numint.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/test/test_numint.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.0263157895, "max_line_length": 85, "alphanum_fraction": 0.6390041494, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.751580638624714}}
{"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/\u03c0\n    return 2*\u221a\u03c0 * 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    \u03c11 = exp.(-a.*basis.^2) .* sqrt(a/\u03c0)\n    \u03c12 = exp.(-b.*basis.^2) .* sqrt(b/\u03c0)\n    \u03c9 = get_weight(basis)\n    w = diagm(\u03c9)\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 = \u03c12'*w*J*\u03c11\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 ClassicalOrthogonalPolynomials, Test\nimport ClassicalOrthogonalPolynomials: orthogonalityweight\n\n@testset \"Laguerre\" begin\n    @testset \"Laguerre weight\" begin\n        @test sum(LaguerreWeight()) \u2261 1.0\n        @test LaguerreWeight()[0.1] \u2248 orthogonalityweight(Laguerre())[0.1] \u2248 exp(-0.1)\n        @test LaguerreWeight(1/2)[0.1] \u2248 sqrt(0.1)exp(-0.1)\n    end\n\n    @testset \"Laguerre L\" begin\n        x = 0.1\n        @test laguerrel.(0:3, 0, x) \u2248 laguerrel.(0:3, x) \u2248 [1, 1-x, (2 - 4x + x^2)/2, (6 - 18x + 9x^2 - x^3)/6]\n        @test laguerrel.(0:3, 1/2, x) \u2248 [1, 3/2 - x, (15 - 20x + 4x^2)/8, (105 - 210x + 84x^2 - 8x^3)/48]\n    end\n    @testset \"Derivatives\" begin\n        L = Laguerre()\n        D = Derivative(axes(L,1))\n        x = 0.1\n        @test (D*L)[x,1:4] \u2248 [0,-1,x-2,-x^2/2 + 3x - 3]\n\n        L = Laguerre(1/2)\n        @test (D*L)[x,1:4] \u2248 [0,-1,x-20/8,-x^2/2 + 7/2*x - 35/8]\n\n        x = axes(L,1)\n        X = L \\ (x .* L)\n        @test 0.1*L[0.1,1:10]' \u2248 L[0.1,1:11]'*X[1:11,1:10]\n    end\nend", "meta": {"hexsha": "6017685d79dd0ebf0f1214e84a2f0f140e1fb70b", "size": 1010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 34.8275862069, "max_line_length": 111, "alphanum_fraction": 0.5178217822, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7515806309884128}}
{"text": "module DataWrangler\n\nusing FFTW, Optim, Smoothers, Statistics\n\ninclude(\"impute.jl\")\nexport impute, impute!\n\ninclude(\"outlie.jl\")\nexport outlie, outlie!\n\ninclude(\"normalize.jl\")\nexport normalize, normalize!\n\ninclude(\"boxcox.jl\")\ninclude(\"normality.jl\")\nexport boxcox, iboxcox\n\ninclude(\"d.jl\")\ninclude(\"p.jl\")\nexport d, p\n\nend\n\n\"\"\"\nData transformations tools for analytics. The current available methods are:\n\n    boxcox, iboxcox:         Box-Cox and inverse Box-Cox transformation\n    d, p:                    Finite lagged difference and partial difference and its inverse\n    impute, impute!:         Data imputation (loess inter/extra-polation, random local density)\n    normalize, normalize!:   Data normalization (z-score, min-max, softmax, sigmoid)\n    outlie, outlie!:         Outlier detection and removal in time series\n\n\"\"\"\nDataWrangler\n", "meta": {"hexsha": "b874cb87cee051de2e661d6caf9681e67e072c66", "size": 846, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DataWrangler.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/DataWrangler.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/DataWrangler.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": 24.1714285714, "max_line_length": 95, "alphanum_fraction": 0.7127659574, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7515806279578368}}
{"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(\u221a3/2)inch)\ndraw(img, compose(sierpinski(2), linewidth(0.1mm), fill(nothing), stroke(colorant\"black\")))\n\nimg = SVG(\"sierpinski.svg\", 4inch, 4(\u221a3/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(\u221a3/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 \u2202normalize\u2202x(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 \u2202norm\u2202x(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) \u2192 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) \u2192 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    \u03c3rmse(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\u03c3rmse(x, y) = rmse(x, y)/std(x)\r\n\r\nexport nrmse, rmse, \u03c3rmse\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": "using BenchmarkTools\n\nversioninfo(verbose=true)\n\n# ## HWloc\nusing Pkg\nPkg.add(\"Hwloc\")\n\nusing Hwloc\nHwloc.num_physical_cores()\n\n\n# ##Starting Threads\n\nusing Base.Threads\nnthreads()\n\nthreadid()\n\na=zeros(4)\nfor i in 1:nthreads()\n     a[threadid()] = threadid()\nend\na\n\n# ## The @Threads macro\n    @threads for i in 1:nthreads()\n               a[threadid()] = threadid()\n           end\n\n\n# ### Prefix sum\n\nfunction prefix_threads!(y)\n    l=length(y)\n    k=ceil(Int, log2(l))\n    for j=1:k\n        @threads for i=2^j:2^j:min(l, 2^k)\n            @inbounds y[i] = y[i-2^(j-1)] + y[i]\n        end\n    end\n    for j=(k-1):-1:1\n        @threads for i=3*2^(j-1):2^j:min(l, 2^k)\n            @inbounds y[i] = y[i-2^(j-1)] + y[i]\n        end\n    end\n    y\nend\n\n# # Thread Safety\n\n# ## Monte Carlo\nusing Random\nfunction darts_in_circle(n, rng=Random.GLOBAL_RNG)\n   inside = 0\n   for i in 1:n\n      if rand(rng)^2 + rand(rng)^2 < 1\n         inside += 1\n      end\n   end\n return inside\nend\n\nfunction pi_serial(n)\n    return 4 * darts_in_circle(n) / n\nend\n\nusing Base.Threads\n\nconst rnglist = [MersenneTwister() for i in 1:nthreads()];\n\nfunction pi_threads(n, loops)\n   inside = zeros(Int, loops)\n   @threads for i in 1:loops\n      rng = rnglist[threadid()]\n      inside[threadid()] = darts_in_circle(n, rng)\n   end\n   return 4 * sum(inside) / (n*loops)\nend\n\npi_threads(2_500_000, 4)\n\n @btime pi_serial(10_000_000)\n\n @btime pi_threads(2_500_000, 4)\n\n # ## Atomics\n\n function sum_thread_base(x)\n   r = zero(eltype(x))\n   @threads for i in eachindex(x)\n      @inbounds r += x[i]\n   end\n   return r\nend\n\na=rand(10_000_000);\n\n@btime sum($a)\n\n@btime sum_thread_base($a)\n\nfunction sum_thread_atomic(x)\n   r = Atomic{eltype(x)}(zero(eltype(x)))\n   @threads for i in eachindex(x)\n      @inbounds atomic_add!(r, x[i])\n   end\n  return r[]\nend\n\n\n @btime sum_thread_atomic($a)\n\n\n function sum_thread_split(A)\n   r = Atomic{eltype(A)}(zero(eltype(A)))\n   len, rem = divrem(length(A), nthreads())\n   #Split the array equally among the threads\n   @threads for t in 1:nthreads()\n      r[] = zero(eltype(A))\n      @simd for i in (1:len) .+ (t-1)*len\n         @inbounds r[] += A[i]\n      end\n      atomic_add!(r, r[])\n    end\n   result = r[]\n   #process up the remaining data\n   @simd for i in length(A)-rem+1:length(A)\n      @inbounds result += A[i]\n   end\n   return result\nend\n\n@btime sum_thread_split($a)\n\n@btime sum_thread_split($a)\n\n# ## Synchronisation primitives\n\nconst f = open(tempname(), \"a+\")\n\nconst mt = Base.Threads.Mutex();\n\n@threads for i in 1:50\n     r = pi_serial(10_000_000)\n     lock(mt)\n     write(f, \"From $(threadid()), pi = $r\\n\")\n     unlock(mt)\nend\n\n\nclose(f)\n\n\nconst s = Base.Semaphore(2);\n@threads for i in 1:nthreads()\n   Base.acquire(s)\n   r = pi_serial(10_000_000)\n   Core.println(\"Calculated pi = $r in Thread $(threadid())\")\n   Base.release(s)\nend\n\n# # Threaded libraries\n\na = rand(1000, 1000);\n\nb = rand(1000, 1000);\n\n@btime $a*$b;\n\n# ## Oversubscriptions\n\nfunction matmul_serial(x)\n   first_num = zeros(length(x))\n   for i in eachindex(x)\n      @inbounds first_num[i] = (x[i]'*x[i])[1]\n   end\n   return first_num\nend\n\n\nfunction matmul_thread(x)\n   first_num = zeros(length(x))\n   @threads for i in eachindex(x)\n      @inbounds first_num[i] = (x[i]'*x[i])[1]\n   end\n   return first_num\nend\n\nm = [rand(1000, 1000) for _ in 1:10];\n\n@btime matmul_serial(m);\n\n@btime matmul_thread(m);\n\nusing LinearAlgebra\nBLAS.set_num_threads(1)\n\n@btime matmul_thread(m);\n", "meta": {"hexsha": "35695311c06e184b59118a1a23684e7a71cf561b", "size": 3449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter09/Chapter09.jl", "max_stars_repo_name": "PacktPublishing/Julia-1.0-High-Performance", "max_stars_repo_head_hexsha": "a3aa79d023f53022586cb622956d99deed87afb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-08-14T03:22:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T12:27:41.000Z", "max_issues_repo_path": "Chapter09/Chapter09.jl", "max_issues_repo_name": "PacktPublishing/Julia-1.0-High-Performance", "max_issues_repo_head_hexsha": "a3aa79d023f53022586cb622956d99deed87afb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter09/Chapter09.jl", "max_forks_repo_name": "PacktPublishing/Julia-1.0-High-Performance", "max_forks_repo_head_hexsha": "a3aa79d023f53022586cb622956d99deed87afb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-09-01T15:17:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T22:56:52.000Z", "avg_line_length": 17.245, "max_line_length": 61, "alphanum_fraction": 0.6172803711, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7515605727697362}}
{"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\u00d74 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\u00d74 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\ud83d\udc22 = Turtle() # \\:turtle:\nT = \ud83d\udc22\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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8728418e-8c34-11eb-3313-c52ecadbf252\nmd\"\"\"\n\n## \u00a73 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# \u2554\u2550\u2561 9202b69e-9013-11eb-02a2-2f1c8e2fcc0c\nmd\"\"\"\n\n## \u00a73.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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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) \u00f7 2)))\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1ba8aa58-8c51-11eb-2d66-775d0fd31747\nlet N = _N1, M = _M1, \u03c3 = 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*\u03c0 * rand(M)\n\tF = f.(X) + \u03c3 * randn(length(X))\n\tc = lsqfit(X, F, N)\n\txp = range(0, 2\u03c0, 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# \u2554\u2550\u2561 3d14680a-98df-42e2-9734-8a5ba27f5f6d\n\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 e6cf2c86-9043-11eb-04a7-f1367ad64b6b\nmd\"\"\"\n## \u00a73.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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u03c0 - \u03c0/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\u0302m = fft(f.(X)) / (2M)\n\t\t# and find the subset defining \u03a0_N I_M f\n\t\tF\u0302n = [ F\u0302m[1:N+1]; F\u0302m[end-N+1:end] ]\n\tend \n\t\n\tL2err(f, F\u0302; xerr = range(0, 2\u03c0, length=31 * length(F\u0302))) = \n\t\tsqrt( sum(abs2, f.(xerr) - trigprojeval.(xerr, Ref(F\u0302))) / length(xerr) )\n\t\t\t\t\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8b7e2280-8e87-11eb-0448-9f3a5acf6032\nmd\"\"\"\n\n## \u00a73.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# \u2554\u2550\u2561 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\u2013834, 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 97a2f8fe-91e0-11eb-2721-9395f949cc48\nmd\"\"\"\nLet us again test these predictions numerically.\n\"\"\"\n\n# \u2554\u2550\u2561 b44e273a-91e0-11eb-1b99-3b20b207513d\nbegin \n\tfunction lsqfit_rand(f::Function, N::Integer, M::Integer) \n\t\tX = 2*\u03c0*rand(M)\n\t\treturn lsqfit(X, f.(X), N) \n\tend \n\n\tL2err_rand(f, N, M; xerr = range(0, 2\u03c0, length=31*M)) = \n\t\tsqrt( sum(abs2, f.(xerr) - trigprojeval.(xerr, Ref(lsqfit_rand(f, N, M)))) / (2*M) )\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d9a37ca0-9b46-42b4-84ac-e012a8ec4b1e\nmd\"\"\"\n\n## Regularisation (If we have time?)\n\n\n\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 89f791bf-c1ff-40a7-a4ce-66b5539efccd\nbegin\n\tfunction reglsqfit(X, F, N, \u0393)\n\t\tA = [ designmatrix(X, N); \u0393 ]\n\t\treturn qr(A) \\ [F; zeros(size(A, 2))]   # this performs the  R \\ (Q' * F) for us\n\tend\nend\n\n# \u2554\u2550\u2561 18c034eb-fa16-486c-8415-46858d17f274\nlet N = _Nr, M = _Mr, \u03c3 = 10.0^(_pr), \u03bb = 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*\u03c0 * rand(M)\n\tF = f.(X) + \u03c3 * randn(length(X))\n\tc = lsqfit(X, F, N)\n\tcr = reglsqfit(X, F, N, \u03bb*I)\n\t# cr = reglsqfit(X, F, N, \u03bb * Diagonal((kgridproj(N)).^2))\n\txp = range(0, 2\u03c0, 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2fcce329-1ed3-4681-b571-b5d4c544dbf5\nlet N = _Nr2, M = _Mr2, \u03c3 = 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*\u03c0 * rand(M)\n\tFtrain = f.(Xtrain) + \u03c3 * randn(M)\n\tXtest = 2*\u03c0 * rand(M)   # this is atypical, normally we have fewer test points \n\tFtest = f.(Xtest)\n\t\n\tfunction testrmse(\u03bb) \n\t\tcr = reglsqfit(Xtrain, Ftrain, N, \u03bb * 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250074479a7e-8c34-11eb-0e09-73f47f8013bb\n# \u255f\u25008728418e-8c34-11eb-3313-c52ecadbf252\n# \u255f\u25009202b69e-9013-11eb-02a2-2f1c8e2fcc0c\n# \u255f\u250073983438-8c51-11eb-3142-03410d610022\n# \u2560\u2550d08fb928-8c53-11eb-3c35-574ef188de6b\n# \u255f\u2500fc8495a6-8c50-11eb-14ac-4dbad6baa3c3\n# \u255f\u25001ba8aa58-8c51-11eb-2d66-775d0fd31747\n# \u2560\u25503d14680a-98df-42e2-9734-8a5ba27f5f6d\n# \u255f\u250048175a0c-8e87-11eb-0f42-e9ca0f676e87\n# \u255f\u2500e6cf2c86-9043-11eb-04a7-f1367ad64b6b\n# \u255f\u250082d74ec2-92a1-11eb-0d58-4bb674a8640e\n# \u255f\u2500879e9596-90a8-11eb-23d6-935e367eeb17\n# \u255f\u25003abcfea6-92a2-11eb-061a-d9752403eff8\n# \u255f\u2500c4b66e46-90a7-11eb-199e-cded424c7020\n# \u2560\u255069fa7e00-90ae-11eb-0681-2d9295ae5368\n# \u255f\u2500e3315558-90b5-11eb-3510-e327a6c2d209\n# \u2560\u25508bd7b6fe-91d1-11eb-2d14-134257fa2878\n# \u2560\u25507f9b5750-91d2-11eb-32ee-6dc5b74d9c0e\n# \u2560\u2550879bf380-91d5-11eb-0b46-85b15d8b2826\n# \u255f\u25008b7e2280-8e87-11eb-0448-9f3a5acf6032\n# \u255f\u2500d8a55fd0-91dc-11eb-033c-0b10126c5ac7\n# \u255f\u2500fb0081a6-91df-11eb-00a9-a9deb7581813\n# \u255f\u250097a2f8fe-91e0-11eb-2721-9395f949cc48\n# \u2560\u2550b44e273a-91e0-11eb-1b99-3b20b207513d\n# \u2560\u2550c479ca34-91e1-11eb-191e-2b8d5f2e8211\n# \u255f\u250096329376-91e0-11eb-0c0e-5f80723255f8\n# \u255f\u250020b6fcfe-93f2-11eb-1b8d-852aeb86d4f8\n# \u255f\u2500d9a37ca0-9b46-42b4-84ac-e012a8ec4b1e\n# \u255f\u250060c2146e-d85c-435d-9262-c5dbc52fcd00\n# \u2560\u255089f791bf-c1ff-40a7-a4ce-66b5539efccd\n# \u2560\u255018c034eb-fa16-486c-8415-46858d17f274\n# \u255f\u25004d98a913-c17d-4d9c-9708-5be743a4b944\n# \u255f\u250073e88b3f-ed14-4919-bf61-a8b77510f7f9\n# \u2560\u25502fcce329-1ed3-4681-b571-b5d4c544dbf5\n# \u255f\u250076f189b8-93f2-11eb-259d-d52fea279464\n# \u255f\u2500e611030a-93f2-11eb-3581-1b3f4b41360a\n# \u255f\u2500530b2eb6-93f5-11eb-2c54-6317369a6b21\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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": "@testset \"1588.sum-of-all-odd-length-subarrays.jl\" begin\n    @test sum_odd_length_subarrays([1, 4, 2, 5, 3]) == 58\n    @test sum_odd_length_subarrays([1, 2]) == 3\n    @test sum_odd_length_subarrays([10, 11, 12]) == 66\nend\n", "meta": {"hexsha": "61063011088048541932b3fc04e7bd9a1ede9e73", "size": 222, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/problems/1588.sum-of-all-odd-length-subarrays.jl", "max_stars_repo_name": "Moelf/LeetCode.jl", "max_stars_repo_head_hexsha": "c5a37331356060b743bc850c5255d6695d30fb57", "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": "test/problems/1588.sum-of-all-odd-length-subarrays.jl", "max_issues_repo_name": "Moelf/LeetCode.jl", "max_issues_repo_head_hexsha": "c5a37331356060b743bc850c5255d6695d30fb57", "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": "test/problems/1588.sum-of-all-odd-length-subarrays.jl", "max_forks_repo_name": "Moelf/LeetCode.jl", "max_forks_repo_head_hexsha": "c5a37331356060b743bc850c5255d6695d30fb57", "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": 37.0, "max_line_length": 57, "alphanum_fraction": 0.6711711712, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7514079163404616}}
{"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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2728 \n\"\n\n# \u2554\u2550\u2561 0ac101ba-6ecc-11eb-090e-6b5998c6bbfd\nmd\"\n## Setting up the mathematical details\n\"\n\n# \u2554\u2550\u2561 dca69d60-6e8c-11eb-3305-3fa2cedd5dac\nbegin\n\tNslide = 100\n\tL_\ud835\udefc  = [0 100 ; 0.01 20 ; 0.01 40 ; 0.1 10]\n\tL_\ud835\udf0e = [-1 -1; -1 -1; 0.1 20; 1 20]\n\tL_d_\ud835\udefc = \t(L_\ud835\udefc[:,2]-L_\ud835\udefc[:,1])/Nslide\n\tL_d_\ud835\udf0e = \t(L_\ud835\udf0e[:,2]-L_\ud835\udf0e[:,1])/Nslide\n\tmd\"\"\"**2) range of parameters**\"\"\"\nend\n\n# \u2554\u2550\u2561 1edc6c32-6e1d-11eb-2f8a-b9dd2aff7b99\nbegin\n\tL_x0 = [-25:0.5:25;]\n\tmd\"\"\" **3) pivot points** \"\"\"\nend\n\n# \u2554\u2550\u2561 21cff596-6ecc-11eb-093c-f97fac9ab7cb\nmd\"\n## Try it out! \n\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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, \ud835\udefc, sigma) = \ud835\udefc * 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, \ud835\udefc, sigma) = \ud835\udefc * min(x, y);\n\telseif kernel == \"3\"\n\t\ttxt = \"Squared exponential\";\n\t\tL_x    = L_x0;\n\t\tK(x, y, \ud835\udefc, \ud835\udf0e) = \ud835\udefc * exp(- (x - y)^2/\ud835\udf0e^2);\n\telseif kernel == \"4\"\n\t\ttxt = \"Ornstein-Uhlenbeck process\";\n\t\tL_x    = L_x0;\n\t\tK(x, y, \ud835\udf36, \ud835\udf0e) = \ud835\udf36 * exp(abs(x - y)/\ud835\udf0e);\n\telse\n\t\terror(\"$(kernel) not supported\")\n\tend\t\n\tn = length(L_x);\n\tmd\"\"\"**1) kernel definitions**\"\"\"\nend\n\n# \u2554\u2550\u2561 bc5fc60a-6e92-11eb-0003-b58331ceddcf\nik = parse(Int32,kernel);\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4fdde52e-6e8b-11eb-3199-8112d143a31a\nmd\"\"\"\nThe seed you chose: $(seed)\n\"\"\"\n\n\n# \u2554\u2550\u2561 431df5da-6eb4-11eb-11af-898fdf3601d5\n\tif L_\ud835\udf0e[ik,2] > 0\n\t\tmd\"\"\"**Choose parameters \ud835\udefc:**\n\t$(L_\ud835\udefc[ik,1]) $(@bind \ud835\udefc Slider(L_\ud835\udefc[ik,1]:L_d_\ud835\udefc[ik]:L_\ud835\udefc[ik,2])) $(L_\ud835\udefc[ik,2]) **and \ud835\udf0e:**\n\t\t$(L_\ud835\udf0e[ik,1]) $(@bind \ud835\udf0e Slider(L_\ud835\udf0e[ik,1]:L_d_\ud835\udf0e[ik]:L_\ud835\udf0e[ik,2])) $(L_\ud835\udf0e[ik,2])\n\t\t\"\"\"\n\telse\n\t\t\ud835\udf0e = L_\ud835\udf0e[ik,2]\n\t\t\t\tmd\"\"\"**Choose parameter \ud835\udefc:**\n\t$(L_\ud835\udefc[ik,1]) $(@bind \ud835\udefc Slider(L_\ud835\udefc[ik,1]:L_d_\ud835\udefc[ik]:L_\ud835\udefc[ik,2])) $(L_\ud835\udefc[ik,2]) \n\t\"\"\"\n\tend\n\n# \u2554\u2550\u2561 2506c99c-6e1d-11eb-31a2-dd1b99a80d8a\nbegin\n\tC = [K(x, y, \ud835\udefc, \ud835\udf0e) 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# \u2554\u2550\u2561 ac913758-6e27-11eb-1649-37b1be855f5b\nif L_\ud835\udf0e[ik,2] > 0\n\tmd\" \t\ud835\udefc = $(\ud835\udefc),    \ud835\udf0e = $(\ud835\udf0e)\t\t\"\nelse\n\tmd\" \t\ud835\udefc = $(\ud835\udefc)\"\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u250053b7c092-6e9b-11eb-0fa7-57fc1385457c\n# \u255f\u25000ac101ba-6ecc-11eb-090e-6b5998c6bbfd\n# \u255f\u2500c823a222-6e1c-11eb-18a8-01a1b673d7b0\n# \u255f\u25000bef3462-6e1d-11eb-08f6-e3b2c36a0721\n# \u255f\u2500dca69d60-6e8c-11eb-3305-3fa2cedd5dac\n# \u255f\u25001edc6c32-6e1d-11eb-2f8a-b9dd2aff7b99\n# \u255f\u250005d7032c-6e25-11eb-0b48-7f9a594b5b88\n# \u255f\u25002506c99c-6e1d-11eb-31a2-dd1b99a80d8a\n# \u255f\u250021cff596-6ecc-11eb-093c-f97fac9ab7cb\n# \u255f\u25002837bf6e-6eb2-11eb-2b2a-190fa3669085\n# \u255f\u2500bc5fc60a-6e92-11eb-0003-b58331ceddcf\n# \u255f\u25006be2bb7a-6eb6-11eb-2cfb-87383e68bf54\n# \u255f\u25004fdde52e-6e8b-11eb-3199-8112d143a31a\n# \u255f\u2500431df5da-6eb4-11eb-11af-898fdf3601d5\n# \u255f\u2500ac913758-6e27-11eb-1649-37b1be855f5b\n# \u255f\u2500b3e26166-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 \u00d7 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7b468c8a-ce16-11eb-3009-f9e4c79e6c17\nmd\"\"\"\n# Triangulate examples\n$(TableOfContents(title=\"\",aside=false))\n## Triangulations of point sets\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 c5a87fb5-c264-498d-aa7c-91d9e6d7bfe2\nmd\"\"\"\n## Triangulations of domains\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 9a090bba-093b-4ca4-a186-1c43b52cd4ff\nhtml\"\"\"<hr>\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d0e63ebd-9288-42d5-9735-3c94a2baa8e3\nexample_convex_hull(;n=10,raster=10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6ec811ca-e6d3-43ea-8da9-02bb05060d8d\nexample_convex_hull_with_boundary(;n=10,raster=10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 0b54833f-0458-4417-aa03-27c4fe2a873c\nexample_convex_hull_voronoi(;n=10,raster=10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4da9a598-bf59-4b3b-aea7-ee1c2721c206\n example_convex_hull_voronoi_delaunay(;n=10,raster=10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 910ce428-4989-4b08-8037-887dae5c847e\nexample_cdt(;n=10,raster=10)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 fc5264cf-b1f7-43c5-bcff-09e6274ca215\nexample_domain_cdt()\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cd007961-7f0e-4c56-9c86-1a9827a71e3e\nexample_domain_cdt_area(;maxarea=0.05)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 a0cb6060-8278-444a-a4e5-46055d98616c\nexample_domain_bcdt_area(;maxarea=0.05)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4e7dad4d-7d3c-4201-a56f-28e3df51e885\nexample_domain_qcdt_area(;maxarea=0.05,minangle=20)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3c88e5cb-5e85-4146-a6d7-3682f4b9a892\nexample_domain_localref(;minangle=20)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 58dbd0e3-b34f-44ec-905a-488c7bbd07ca\nexample_domain_regions(minangle=20)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6545d149-d4dd-4f26-8f51-5db90f6b444d\nexample_domain_holes(minangle=20,maxarea=0.05)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u25007b468c8a-ce16-11eb-3009-f9e4c79e6c17\n# \u255f\u250083f07f94-7e35-42de-9214-715c92b6dddd\n# \u2560\u2550a5f7aca5-9e40-471a-bece-34498a804bd8\n# \u2560\u2550d0e63ebd-9288-42d5-9735-3c94a2baa8e3\n# \u255f\u2500c56434f3-e0a4-462e-86d5-fcfbb6778c11\n# \u2560\u25506f3f0014-42bc-4565-a03e-208fed8b8f48\n# \u2560\u25506ec811ca-e6d3-43ea-8da9-02bb05060d8d\n# \u255f\u2500f13ad00e-a3d3-462f-93d4-ebe1fe4a7b4d\n# \u2560\u25506e2d70c4-dc0f-4672-823a-930a50114811\n# \u2560\u25500b54833f-0458-4417-aa03-27c4fe2a873c\n# \u255f\u2500852e1ebf-3f29-472a-945e-53920d7653be\n# \u2560\u25501ee0af11-96e4-4929-926e-d7143ed1f791\n# \u2560\u25504da9a598-bf59-4b3b-aea7-ee1c2721c206\n# \u255f\u2500b95859af-ab21-4c41-b095-82b3ea39724a\n# \u2560\u25500d648d22-aa03-437b-b019-59bd693bc55e\n# \u2560\u2550910ce428-4989-4b08-8037-887dae5c847e\n# \u255f\u2500c5a87fb5-c264-498d-aa7c-91d9e6d7bfe2\n# \u255f\u25007f2b4252-a827-4de4-abb6-42d1bbde44b9\n# \u2560\u2550ccd8ed8d-7991-4a19-8a05-65761adc2fee\n# \u2560\u2550fc5264cf-b1f7-43c5-bcff-09e6274ca215\n# \u255f\u25006793711b-d476-45c6-8b2b-b1d0693d8e6e\n# \u2560\u2550b71b1faf-ff3f-4404-8a2c-9de84fa498f7\n# \u2560\u2550cd007961-7f0e-4c56-9c86-1a9827a71e3e\n# \u255f\u25003f2f0b19-3c13-482d-abd5-e6325802c6e8\n# \u2560\u25508ac6cc0b-e4e7-4aa0-bc37-b22b15bf2a83\n# \u2560\u2550a0cb6060-8278-444a-a4e5-46055d98616c\n# \u255f\u250014145886-2a5f-4ae8-bf00-a5eaaa7e0568\n# \u2560\u2550a7e97f1c-e091-4555-abc0-a71abd22dd8a\n# \u2560\u25504e7dad4d-7d3c-4201-a56f-28e3df51e885\n# \u255f\u250061dc30ce-9256-4f20-9163-e8d473ac9e53\n# \u2560\u2550083b8aef-67f1-489a-8eff-b70fb6dc9da4\n# \u2560\u25503c88e5cb-5e85-4146-a6d7-3682f4b9a892\n# \u255f\u250030990760-92e1-4a26-98a5-b43be658dee7\n# \u2560\u2550f0f9922b-70ce-4866-bc41-349a26095ade\n# \u2560\u255058dbd0e3-b34f-44ec-905a-488c7bbd07ca\n# \u255f\u2500783975f5-cbab-4b23-9155-7a6276cd25df\n# \u2560\u25503dfe5acd-72f7-4510-b3a0-40364f679073\n# \u2560\u25506545d149-d4dd-4f26-8f51-5db90f6b444d\n# \u255f\u25009a090bba-093b-4ca4-a186-1c43b52cd4ff\n# \u2560\u25508af90e7a-0e5e-4a9d-b39e-f7603fc1e25e\n# \u2560\u25509447e874-22ce-4b99-9037-e0d202430ee2\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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    \u03bc::T\n    \u03c3::T\n\n    Cosine(\u03bc::T, \u03c3::T) = (@check_args(Cosine, \u03c3 > zero(\u03c3)); new(\u03bc, \u03c3))\nend\n\nCosine{T<:Real}(\u03bc::T, \u03c3::T) = Cosine{T}(\u03bc, \u03c3)\nCosine(\u03bc::Real, \u03c3::Real) = Cosine(promote(\u03bc, \u03c3)...)\nCosine(\u03bc::Integer, \u03c3::Integer) = Cosine(Float64(\u03bc), Float64(\u03c3))\nCosine(\u03bc::Real) = Cosine(\u03bc, 1.0)\nCosine() = Cosine(0.0, 1.0)\n\n@distr_support Cosine d.\u03bc - d.\u03c3 d.\u03bc + d.\u03c3\n\n#### Conversions\nfunction convert{T<:Real}(::Type{Cosine{T}}, \u03bc::Real, \u03c3::Real)\n    Cosine(T(\u03bc), T(\u03c3))\nend\nfunction convert{T <: Real, S <: Real}(::Type{Cosine{T}}, d::Cosine{S})\n    Cosine(T(d.\u03bc), T(d.\u03c3))\nend\n\n#### Parameters\n\nlocation(d::Cosine) = d.\u03bc\nscale(d::Cosine) = d.\u03c3\n\nparams(d::Cosine) = (d.\u03bc, d.\u03c3)\n@inline partype{T<:Real}(d::Cosine{T}) = T\n\n\n#### Statistics\n\nmean(d::Cosine) = d.\u03bc\n\nmedian(d::Cosine) = d.\u03bc\n\nmode(d::Cosine) = d.\u03bc\n\nvar{T<:Real}(d::Cosine{T}) = d.\u03c3^2 * (1//3 - 2/T(\u03c0)^2)\n\nskewness{T<:Real}(d::Cosine{T}) = zero(T)\n\nkurtosis{T<:Real}(d::Cosine{T}) = 6*(90-T(pi))/(5*(T(\u03c0)^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.\u03bc) / d.\u03c3\n        return (1 + cospi(z)) / (2d.\u03c3)\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.\u03bc) / d.\u03c3\n    (1 + z + sinpi(z) * inv\u03c0) / 2\nend\n\nfunction ccdf(d::Cosine, x::Real)\n    nz = (d.\u03bc - x) / d.\u03c3\n    (1 + nz + sinpi(nz) * inv\u03c0) / 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    \u03b5 = p[1];\n    N = length(x)\n    for i in 1:N\n        dx[i] = f(\u03b5*x[mod1(i-1, N)] + (1-\u03b5)*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\u03b5s = 0.0:0.01:1.0\ntes = [zeros(length(\u03b5s), 2) for j in 1:length(methods)]\n\nfor (i, \u03b5) in enumerate(\u03b5s), (j, meth) in enumerate(methods)\n    set_parameter!(ds, 1, \u03b5)\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(\u03b5s, tes[j][:, 1], color = \"C$(j-1)\", label = \"\\$r=$(rs[j])\\$\")\n    plot(\u03b5s, 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": "function residuals(A, b, shifts, x)\n  nshifts = size(shifts, 1);\n  r = [ (b - A * x[:,i] - shifts[i] * x[:,i]) for i = 1 : nshifts ];\n  return r;\nend\n\nfunction test_cg_lanczos()\n  cg_tol = 1.0e-6;\n\n  # Cubic splines matrix.\n  n = 10;\n  A = spdiagm(-1 => ones(n-1), 0 => 4*ones(n), 1 => ones(n-1))\n  b = A * [1:n;];\n  b_norm = norm(b);\n\n  (x, stats) = cg_lanczos(A, b, itmax=n);\n  resid = norm(b - A * x) / b_norm;\n  @printf(\"CG_Lanczos: Relative residual: %8.1e\\n\", resid);\n  @test(resid <= cg_tol);\n  @test(stats.solved);\n\n  # Test negative curvature detection.\n  A[n-1,n-1] = -4.0\n  (x, stats) = cg_lanczos(A, b, check_curvature=true)\n  @test(stats.status == \"negative curvature\")\n  A[n-1,n-1] = 4.0\n\n  shifts=[1:6;];\n\n  (x, stats) = cg_lanczos_shift_seq(A, b, shifts, itmax=n);\n  r = residuals(A, b, shifts, x);\n  resids = map(norm, r) / b_norm;\n  @printf(\"CG_Lanczos: Relative residuals with shifts:\");\n  for resid in resids\n    @printf(\" %8.1e\", resid);\n  end\n  @printf(\"\\n\");\n  @test(all(resids .<= cg_tol));\n  @test(stats.solved);\n\n  # Test negative curvature detection.\n  shifts = [-4; -3; 2]\n  (x, stats) = cg_lanczos_shift_seq(A, b, shifts, check_curvature=true, itmax=n);\n  @test(stats.flagged == [true, true, false])\n\n  # Code coverage.\n  (x, stats) = cg_lanczos(Matrix(A), b);\n  (x, stats) = cg_lanczos_shift_seq(Matrix(A), b, [1:6;], verbose=true);\n  show(stats);\n\n  # Test b == 0\n  (x, stats) = cg_lanczos(A, zeros(size(A,1)))\n  @test x == zeros(size(A,1))\n  @test stats.status == \"x = 0 is a zero-residual solution\"\n  (x, stats) = cg_lanczos_shift_seq(A, zeros(size(A,1)), [1:6;])\n  @test x == zeros(size(A,1), 6)\n  @test stats.status == \"x = 0 is a zero-residual solution\"\n\n  # Test integer values\n  A = ceil.(Int, A) + I\n  b = A * ones(Int, size(A,1))\n  (x, stats) = cg_lanczos(A, b)\n  @test stats.solved\nend\n\ntest_cg_lanczos()\n", "meta": {"hexsha": "5fa5283e61fe915847f650e780728f88227d819f", "size": 1846, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_cg_lanczos.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/test_cg_lanczos.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/test_cg_lanczos.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": 27.552238806, "max_line_length": 81, "alphanum_fraction": 0.5996749729, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7514078905265937}}
{"text": "\ninclude(\"../utils/functions.jl\")\ninclude(\"../optimizers/activeset.jl\")\n\nusing Gadfly\n\n## Toy example \n\nA = [1 1   1 0;\n     2 1/2 0 1]\nb = Vector{Float64}([5, 8])\nc = Vector{Float64}([-4, -2, 0, 0])\n\n#assts = [true,false,true,false]\nassts = [false,false,true,true]\n\n#x = [4.,0.,1.,0.]\nx = [0.,0.,5.,8.]\nrun_simplex(assts,x,A,b,c,2)\n#simplex_iteration(assts, x, A, b, c)\n\n# phase I of simplex \nx0 = [0.,0.,0.,0.,5.,8.] # last 2 entries are z1, z2\nA0 = [1 1   1 0    1 0;\n     2 1/2 0 1    0 1]\nc0 = [0., 0., 0., 0., 1., 1.]\n\nassts0 = [false,false,false,false,true,true]\n\nassts_start,x_start = run_simplex(assts0,x0,A0,b,c0,5)\n\nfunction run_program(m, num_iters=100)\n    n = 3*m\n    # generate random values for A\n    A = randn(m,n)\n    b = randn(m) + 1\n    c = randn(n) * 2 + 2\n    \n    return run_two_stage_simplex(A, b, c, num_iters)\nend\n\nfunction run_experiment(num_rounds, num_iters)\n    times = []\n    for m in range(10,10,num_rounds)\n        x, assts, time = run_program(m, num_iters)\n        push!(times,time)\n    end\n    return times\nend\n\ntimes = run_experiment(5,100)\n\nnum_rounds = 20\n\nlength(times)\n\n#Gadfly.plot(x=range(10,10,num_rounds), y=times, Guide.XLabel(\"m\"),\n#    Guide.YLabel(\"time (s)\"),)\n\n\n", "meta": {"hexsha": "b42a75564abb99ad652fd7881adfb5b56becc984", "size": 1212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jupyter/simplex_algorithm.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/simplex_algorithm.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/simplex_algorithm.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": 19.868852459, "max_line_length": 67, "alphanum_fraction": 0.6014851485, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.751385114546435}}
{"text": "# vanderPol winding number arnold tongues\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot\n\nfunction winding_number(ds, \u03c9, a, u0, Ttr, T)\n    period = 2\u03c0/\u03c9\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; \u0394t = period/20, Ttr)\n    tvec = 0:period/20:T\n    u1, u2 = columns(tr)\n    \u03b8 = 0.0\n    \u03b8_old = atan(u2[1], u1[1])\n    for (x, y) \u2208 zip(u1, u2)\n        \u03b8_new = atan(y, x)\n        \u03b8 += mod(\u03b8_new - \u03b8_old + \u03c0, 2\u03c0) - \u03c0\n        \u03b8_old = \u03b8_new\n    end\n    W = abs(\u03b8 / (tvec[end] * 2\u03c0/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\u03c9_min = 0.2\n\u03c9_max = 2.0\nn\u03c9 =  1000\n\u03c9_vec = LinRange(\u03c9_min, \u03c9_max, n\u03c9)\n\nds = Systems.vanderpol(; \u03bc = d)\n  \nwmat = zeros(n\u03c9,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\u03c9)\n@showprogress 1 \"Computing...\" for ia = 1:na\n    a = a_vec[ia]\n    for i\u03c9 = 1:length(\u03c9_vec)\n        \u03c9 = \u03c9_vec[i\u03c9]\n        u0, W = winding_number(ds, \u03c9, a, u0, Ttr, T)\n        wmat[i\u03c9,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(\u03c9_vec,a_vec,wmat',cmap = \"gnuplot\" )\n\nxlabel(L\"\\omega\") \nylabel(L\"a\") \n\nax = gca()\nax.set_xlim([\u03c9_min,\u03c9_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\u03c9,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\u03c9\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(\u03c9_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 * \u03c0 / 180\n    gamma = gamma * \u03c0 / 180\n    theta = theta * \u03c0 / 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 \u2264 x[1] \u2264 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    \u03c3::Float64 \n    \u03b2::Float64 \n    \u03c1::Float64 \n    \u03b3::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.\u03c3 * (x[2] - x[1]) \n    dx[2] = x[1] * (cmap.\u03c1 - x[3]) - x[2] \n    dx[3] = x[1] * x[2] - cmap.\u03b2 * 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 \u2264 x \u2264 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    \u03b1::Float64 \n    \u03b2::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.\u03b1 * (x[2] - x[1] - cmap.h(x[1]))\n    dx[2] = x[1] - x[2] + x[3] \n    dx[3] = -\u03b2 * 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": "using LinearAlgebraX, LinearAlgebra\n\nimport LinearAlgebraX: permanent, detx\nimport LinearAlgebra: det, svd\n\npermanent(G::SimpleGraph) = permanent(adjacency(G))\ndet(G::SimpleGraph) = det(adjacency(G))\ndetx(G::SimpleGraph) = detx(adjacency(G))\n\n\n\nexport det, detx, permanent\n\nmaxeig(A::Matrix) = maximum(eigvals(A))\n\n\n\"\"\"\n    maxeig(G::SimpleGraph)\n\nReturn the maximum eigenvalue of `G`'s adjacency matrix.\n\"\"\"\nmaxeig(G::SimpleGraph) = maxeig(adjacency(G))\n\nexport maxeig\n\nsvd(G::SimpleGraph) = svdvals(adjacency(G))\nexport svd\n", "meta": {"hexsha": "08b5dedd25473effff7e8ecf999797a8d29c525b", "size": 526, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/invariants.jl", "max_stars_repo_name": "scheinerman/SemiIsomorphism.jl", "max_stars_repo_head_hexsha": "1bc4aa8769eb4b6e515862d66c9b2acfd384ea62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/invariants.jl", "max_issues_repo_name": "scheinerman/SemiIsomorphism.jl", "max_issues_repo_head_hexsha": "1bc4aa8769eb4b6e515862d66c9b2acfd384ea62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/invariants.jl", "max_forks_repo_name": "scheinerman/SemiIsomorphism.jl", "max_forks_repo_head_hexsha": "1bc4aa8769eb4b6e515862d66c9b2acfd384ea62", "max_forks_repo_licenses": ["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": 56, "alphanum_fraction": 0.7376425856, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7513735426843285}}
{"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    \u03bbmax = F.values[r+1]\n    amax = F.vectors[:,r+1]\n    return \u03bbmax, amax\nend\n\nfigure(1)\n\u03be = 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, :\u03be)\n    plot(\u03be, polyval(pr, \u03be))\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": "# run from REPL\n\nusing Makie\n\n\u03c6 = 0:\u03c0/100:2\u03c0\n\n\u03b8 = 0:\u03c0/200:\u03c0\n\nx = [cos(\u03b8) * sin(\u03c6) for \u03b8 in \u03b8, \u03c6 in \u03c6]\ny = [sin(\u03b8)*sin(\u03c6) for \u03b8 in \u03b8, \u03c6 in \u03c6]\nz = [cos(\u03c6) for \u03b8 in \u03b8, \u03c6 in \u03c6]\n\nsurface(x, y, z, backgroundcolor = :black, show_axis = false)\n", "meta": {"hexsha": "afc40d411b6fe09d98e09201732907eed58f50c7", "size": 236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/draw-a-sphere-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/draw-a-sphere-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/draw-a-sphere-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": 16.8571428571, "max_line_length": 61, "alphanum_fraction": 0.5762711864, "num_tokens": 113, "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": "\"\"\"\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\u00f2 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\"; \u03b8)\n  return [\n    1 0 0           0\n    0 1 0           0\n    0 0 cos(\u03b8 / 2) -sin(\u03b8 / 2)\n    0 0 sin(\u03b8 / 2) cos(\u03b8 / 2)\n  ]\nend\n\n# CRy(\u03b8=\u03c0/2)\n\u03b8 = \u03c0 / 2\nCRy\u03b8 = op(\"CRy\", i1, i2; \u03b8)\n\n# |10\u27e9 = |Z-Z+\u27e9\nZmZp = Zm1 * Zp2\n\n# CRy\u03b8|Z-Z+\u27e9 = |Z-X+\u27e9\n@show apply(CRy\u03b8, ZmZp) \u2248 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": "# doubly periodic dipole\n# https://dx.doi.org/10.1103/PhysRevLett.112.145301\n# should be eigenstate of Hamiltonian evolution\n\nusing Test, Plots, VortexDistributions\n\n\n# Methods\nH(x) = x > 0. ? 1.0 : 0.0\nT(x,xi) = x - xi\ntans(x,xk) = tan((T(x,xk) - \u03c0)*0.5)\ntanhs(x,xk,j) = tanh((T(x,xk) + 2*\u03c0*j)*0.5)\n\nfunction Krow(x,y,xp,yp,xn,yn,j)\n    return atan(tanhs(y,yn,j)*tans(x,xn)) -\n    atan(tanhs(y,yp,j)*tans(x,xp))\nend\n\n# Dimensionless form\nfunction \u03b8d(x,y,dip)\n    vp,vn = dip\n    xp,yp,_ = rawData(vp)\n    xn,yn,_ = rawData(vn)\n    s = 0.0\n    for j = -5:5\n        s += Krow(x,y,xp,yp,xn,yn,j)\n    end\n    return s + \u03c0*(H(T(x,xp)) - H(T(x,xn))) - y*(xp - xn)/(2*\u03c0)\nend\n\n# Now for arbitrary domains and dipole sizes:\nfunction thetad(x,y,xp,yp,xn,yn)\n    s = 0.0\n    for j = -5:5\n        s += Krow(x,y,xp,yp,xn,yn,j)\n    end\n    s += \u03c0*(H(T(x,xp)) - H(T(x,xn))) - y*(xp - xn)/(2*\u03c0)\n    return s - x*H(abs(yp - yn) - \u03c0) + y*H(abs(xp - xn) - \u03c0)\nend\n\nfunction Thetad(x,y,xp,yp,xn,yn)\n    Lx = x[end]-x[1]\n    Ly = y[end]-y[1]\n    return @. angle(exp(im*thetad.(x*2*pi/Lx,y'*2*pi/Ly,xp*2*pi/Lx,yp*2*pi/Ly,xn*2*pi/Lx,yn*2*pi/Ly)))\nend\n\n# Sukla's parameters\ng=0.1\n\u03bc=15.\nn0 = \u03bc/g\n\u03b3=0.01\nx = LinRange(-50,50,1024)\ny = LinRange(-50,50,1024)\n\n# dipole\nxp = 0.\nyp = 5\n\nxn = 0.\nyn = -5\n\nvp = PointVortex(xp,yp,1)\nvn = PointVortex(xn,yn,-1)\n\u03be = sqrt(1/\u03bc)\ndip = ScalarVortex(\u03be,[vp;vn])\n\nphase_periodic = Thetad(x,y,xp,yp,xn,yn)\nheatmap(x,y,phase_periodic,transpose=true)\n\n# make dipole wavefunction\npsi = Torus(sqrt(n0)*one.(x*y'),x,y)\nvortex!(psi,dip)\n\npsip = @. abs(psi.\u03c8)*exp(im*phase_periodic)\n\nheatmap(x,y,abs2.(psip),transpose=true)\nheatmap(x,y,angle.(psip),transpose=true)\n\nusing FourierGPE\n\nN = (1024,1024)\nL = (100,100)\nsim = Sim(L,N)\n@unpack X,K = sim\n\nphi = kspace(psip,sim) |> fftshift\n\nDX,DK = dfftall(X,K)\nkx,ky = K .|> fftshift\n\ndata = @. log(abs2(phi)+eps())\nheatmap(kx,ky,data)\n\n# define polar coordinates\nNkx = length(kx)\nNk = Nkx/2 |> Int\nN\u03b8k = 2*Nkx\nk = LinRange(0,last(kx),Nk)'\n\u03b8k = LinRange(0,2*pi,N\u03b8k+1)[1:N\u03b8k]\n\nN = 100\n\u03c9 = .3\nplot(kx,hermite.(kx,N,\u03c9))\nhx,hy = init_polar(x,N,\u03c9)\nphiP = polar(psi.\u03c8,kx,\u03c9,hx,hy)\n\ndensFP = abs2.(phiP)\nheatmap(\u03b8k,k',densFP,transpose=true)\nxlabel!(L\"\\theta_k\");ylabel!(L\"k\")\n\ndk = k[2] - k[1]\nd\u03b8k = \u03b8k[2] - \u03b8k[1]\n\ndensk = sum(densFP;dims=1)'*d\u03b8k\n\nplot(k',densk)\n", "meta": {"hexsha": "8db7408bf647ecc03a00423534e0c3141de5c73b", "size": 2298, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_research/dipole_polar.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/dipole_polar.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": "2020-02-02T19:28:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T03:51:08.000Z", "max_forks_repo_path": "_research/dipole_polar.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": 19.641025641, "max_line_length": 102, "alphanum_fraction": 0.6005221932, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7512458071544371}}
{"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\u03c0*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    \u03bb = max.(-s, 0)\n    s = max.(s, 0)\n    x\u0302 = rand(n)\n    A = rand(m, n)\n    b = A * x\u0302 .+ s\n    c = -A' * \u03bb\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\u0302 = 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\u0302 + rand(m)\n    A = rand(p, n)\n    b = A * x\u0302\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": "\nG = [0 1 0 0 1 0 ;\n         1 0 1 0 1 0 ;\n         0 1 0 1 0 0 ;\n         0 0 1 0 1 1 ;\n         1 1 0 1 0 0 ;\n         0 0 0 1 0 0 ;\n        ]\n\nL = [2 -1 0 0 -1 0;\n        -1 3 -1 0 -1 0 ;\n        0 -1 2 -1 0 0;\n        0 0 -1 3 -1 -1;\n        -1 -1 0 -1 3 0;\n        0 0 0 -1 0 1]\n\n\nD = Diagonal([2,3,2,3,3,1])\n\nL_norm = (D^-0.5)*L*(D^-0.5)\n\n@testset \"graphs\" begin\n        @test degree(G) == D\n        @test laplacian(G) == L\n        @test norm_laplacian(G) \u2248 L_norm\nend\n", "meta": {"hexsha": "00b8e208664b548d31acb2fc7c46951e182eee83", "size": 475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/BO_test/graph_test.jl", "max_stars_repo_name": "SamDier/BOMoD", "max_stars_repo_head_hexsha": "f83f10a24dd63413df2987fc17420e5113052158", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-11-20T21:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T21:30:08.000Z", "max_issues_repo_path": "test/BO_test/graph_test.jl", "max_issues_repo_name": "SamDier/BOMoD", "max_issues_repo_head_hexsha": "f83f10a24dd63413df2987fc17420e5113052158", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-20T20:03:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T13:54:28.000Z", "max_forks_repo_path": "test/BO_test/graph_test.jl", "max_forks_repo_name": "SamDier/BOMoD", "max_forks_repo_head_hexsha": "f83f10a24dd63413df2987fc17420e5113052158", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-31T14:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T14:37:11.000Z", "avg_line_length": 17.5925925926, "max_line_length": 40, "alphanum_fraction": 0.3684210526, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7512419583617064}}
{"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": "using Test\nusing LinearAlgebra\nusing Nystrom\n\n@testset \"Area/volume\" begin\n    @testset \"Cube\" begin\n        # generate a mesh\n        (lx,ly,lz) = widths = (1.,1.,2.)\n        \u03a9,M = @gmsh begin\n            Geometry.clear_entities!()\n            gmsh.model.occ.addBox(0,0,0,lx,ly,lz)\n            gmsh.model.occ.synchronize()\n            gmsh.model.mesh.generate(3)\n            \u03a9 = GmshSDK.domain(dim=3)\n            M = GmshSDK.meshgen(\u03a9,dim=3)\n            return \u03a9,M\n        end\n        \u2202\u03a9 = boundary(\u03a9)\n        mesh  = NystromMesh(view(M,\u2202\u03a9),order=1)\n        A     = 2*(lx*ly + lx*lz + ly*lz)\n        @test A \u2248 sum(qweights(mesh))\n        # generate a Nystrom mesh for volume\n        mesh  = NystromMesh(view(M,\u03a9),order=1)\n        V     = prod(widths)\n        # sum only weights corresponding to tetras\n        @test V \u2248 sum(qweights(mesh))\n    end\n    @testset \"Sphere\" begin\n        # create a mesh using GmshSDK package\n        r = 0.5\n        Geometry.clear_entities!()\n        \u03a9,M   = @gmsh begin\n            GmshSDK.set_meshsize(0.1)\n            Geometry.clear_entities!()\n            gmsh.model.occ.addSphere(0,0,0,r)\n            gmsh.model.occ.synchronize()\n            gmsh.model.mesh.generate(3)\n            \u03a9 = GmshSDK.domain(dim=3)\n            M = GmshSDK.meshgen(\u03a9,dim=3)\n            return \u03a9,M\n        end\n        \u0393     = boundary(\u03a9)\n        nmesh = NystromMesh(M,\u0393,order=4) # NystromMesh of surface \u0393\n        area  = sum(qweights(nmesh))\n        @test isapprox(area,4*\u03c0*r^2,atol=5e-2)\n        nmesh = NystromMesh(M,\u03a9,order=4) # Nystrom mesh of volume \u03a9\n        volume  = sum(qweights(nmesh))\n        @test isapprox(volume,4/3*\u03c0*r^3,atol=1e-2)\n        # create a mesh using ParametricSurfaces package\n        Geometry.clear_entities!()\n        ent   = ParametricSurfaces.Sphere(radius=r)\n        \u03a9     = Geometry.Domain(ent)\n        \u0393     = boundary(\u03a9)\n        M     = ParametricSurfaces.meshgen(\u0393,(4,4))\n        nmesh = NystromMesh(view(M,\u0393),order=5)\n        area   = sum(qweights(nmesh))\n        @test isapprox(area,4*\u03c0*r^2,atol=1e-5)\n    end\n    @testset \"Circle\" begin\n        r = rx = ry = 0.5\n        Geometry.clear_entities!()\n        \u03a9,M = @gmsh begin\n            Geometry.clear_entities!()\n            gmsh.model.occ.addDisk(0,0,0,rx,ry)\n            gmsh.model.occ.synchronize()\n            gmsh.model.mesh.generate(2)\n            \u03a9 = GmshSDK.domain(dim=2)\n            M = GmshSDK.meshgen(\u03a9,dim=2)\n            return \u03a9,M\n        end\n        \u0393    = boundary(\u03a9)\n        mesh = NystromMesh(view(M,\u03a9),order=2)\n        A    = \u03c0*r^2\n        # test area\n        @test isapprox(A,sum(qweights(mesh));atol=1e-2)\n        # test perimeter\n        mesh = NystromMesh(view(M,\u0393),order=2)\n        P    = 2\u03c0*r\n        @test isapprox(P,sum(qweights(mesh));atol=1e-2)\n        Geometry.clear_entities!()\n        geo   = ParametricSurfaces.Circle(radius=r)\n        \u03a9     = Geometry.Domain(geo)\n        \u0393     = boundary(\u03a9)\n        M     = ParametricSurfaces.meshgen(\u0393,(100,))\n        nmesh = NystromMesh(M,\u0393,order=5)\n        @test isapprox(sum(qweights(nmesh)),\u03c0,atol=1e-10)\n    end\nend\n", "meta": {"hexsha": "8fe00399b34faf23eb9708214464556ed05e585f", "size": 3089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/nystrommesh_test.jl", "max_stars_repo_name": "WaveProp/Nystrom", "max_stars_repo_head_hexsha": "a4a6084651942d6b96f04baa42c875d53d0e0011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-24T21:31:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-24T21:31:39.000Z", "max_issues_repo_path": "test/nystrommesh_test.jl", "max_issues_repo_name": "WaveProp/Nystrom", "max_issues_repo_head_hexsha": "a4a6084651942d6b96f04baa42c875d53d0e0011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-28T16:34:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T15:19:39.000Z", "max_forks_repo_path": "test/nystrommesh_test.jl", "max_forks_repo_name": "WaveProp/Nystrom", "max_forks_repo_head_hexsha": "a4a6084651942d6b96f04baa42c875d53d0e0011", "max_forks_repo_licenses": ["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.7078651685, "max_line_length": 67, "alphanum_fraction": 0.5422466818, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.751232988863743}}
{"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, \u03ba[, Z=1])\n\nReturns the relativistic energy of a hydrogen orbital with principal\nquantum number ``n`` and \"angular momentum\" quantum number ``\u03ba`` (and\nan effective nuclear charge ``Z``) according to\n\n```math\n\\begin{equation}\n\\tag{BS14.29*}\nE_{n\u03ba} =\nc^2\\left[\n-1+\n\\frac{1}{\\sqrt{1 +\n\\left(\n\\frac{Z\u03b1}{n - \\abs{\u03ba} + \\sqrt{\u03ba^2-Z^2\u03b1^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, \u03ba, Z=1)\n    r = Z*\u03b1/(n-abs(\u03ba)+\u221a(\u03ba^2-Z^2*\u03b1^2))\n    -c^2*(1-inv(\u221a(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.\u03ba)\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\u00d73 LinearAlgebra.Diagonal{Float64,Array{Float64,1}}:\n 0.0   \u22c5      \u22c5\n  \u22c5   0.375   \u22c5\n  \u22c5    \u22c5     0.375\n\njulia> atomic_hamiltonian(ros\"1[s] 2[s-p]\")\n4\u00d74 LinearAlgebra.Diagonal{Float64,Array{Float64,1}}:\n 0.0   \u22c5         \u22c5         \u22c5\n  \u22c5   0.375005   \u22c5         \u22c5\n  \u22c5    \u22c5        0.375005   \u22c5\n  \u22c5    \u22c5         \u22c5        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(\u03b8, rndseed=1234)\n    n = 1000\n    \u03bc1, \u03bc2, \u03c31, \u03c32, prob = \u03b8\n    d1=randn(n).*\u03c31 .+ \u03bc1\n    d2=randn(n).*(\u03c31+\u03c32) .+ (\u03bc1 - \u03bc2) # 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(\u03b8, reps)\n    auxstat.([MNmodel(\u03b8, 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    \u03b8 = (ub-lb).*rand(size(lb,1)) + lb\nend    \n\nfunction InSupport(\u03b8)\n    lb,ub = PriorSupport()\n    all(\u03b8 .>= lb) & all(\u03b8 .<= 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    \u03b2::Float64\n    window::AbstractSpatialWindow{Float64}\nend\n\nfunction Base.show(io::IO, pp::HomogeneousPoissonPointProcess{T}) where {T}\n    print(io, \"HomogeneousPoissonPointProcess{$T}\\n- \u03b2 = $(pp.\u03b2)\\n- window = $(pp.window)\")\nend\n\n@doc raw\"\"\"\n    HomogeneousPoissonPointProcess(\n        \u03b2::Real,\n        window::Union{Nothin,AbstractSpatialWindow}=nothing\n    )\n\nConstruct a [`PRS.HomogeneousPoissonPointProcess`](@ref) with intensity `\u03b2` restricted to `window`.\n\nDefault window (`window=nothing`) is [`PRS.SquareWindow`](@ref)`()`.\n\n```jldoctest; output = true\nusing PartialRejectionSampling\n\n\u03b2 = 40\nwin = PRS.SquareWindow(zeros(2), 1)\nPRS.HomogeneousPoissonPointProcess(\u03b2, win)\n\n# output\n\nHomogeneousPoissonPointProcess{Array{Float64,1}}\n- \u03b2 = 40.0\n- window = SquareWindow [0.0, 1.0]^2\n```\n\"\"\"\nfunction HomogeneousPoissonPointProcess(\n    \u03b2::Real,\n    window::Union{Nothing,AbstractSpatialWindow}=nothing\n)\n    @assert \u03b2 > 0\n    win = isnothing(window) ? SquareWindow() : window\n    return HomogeneousPoissonPointProcess{Vector{Float64}}(\u03b2, win)\nend\n\n\"\"\"\n    intensity(pp::HomogeneousPoissonPointProcess) = pp.\u03b2\n\"\"\"\nintensity(pp::HomogeneousPoissonPointProcess) = pp.\u03b2\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.\u03b2 * 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        \u03b2::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(\u03b2) on ``\\bigcup_{i} B(c_i, r)`` (union of balls centered at ``c_i`` with the same radius ``r``).\n\nIf `win \u2242\u0338 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(\u03b2) on ``B(c_1, r)``,\n    - Sample from Poisson(\u03b2) on ``B(c_2, r) \\setminus B(c_1, r)``,\n    - Sample from Poisson(\u03b2) 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    \u03b2::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    \ud835\udcab = Distributions.Poisson(\u03b2 * volume(BallWindow(zeros(d), radius)))\n    points = Matrix{Float64}(undef, d, 0)\n    for (i, c) in enumerate(eachcol(centers))\n        n = rand(rng, \ud835\udcab)\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    \u03b2::Real,\n    centers::Matrix,\n    radius::Real,\n    win::Union{Nothing,AbstractWindow}=nothing\n)\n    generate_sample_poisson_union_balls(Random.default_rng(), \u03b2, 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\u2014V: 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#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\n#                                                                             #\n#   ~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~~\u00a4~  #\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    \u03b1    :: 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            \u03b1       :: Real    = 2.,\n            n       :: Int     = ceil(Int, 2*\u03b1)-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 `\u03b1` and `n` currently apply only for slepian\nmulti-tapering (*discrete prolate spheroidal sequences*):\n\n`\u03b1` 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 `\u03b1` 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*\u03b1)-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, \u03b1=4, n=7))\n\n```\n\"\"\"\nfunction taper( kind :: TaperKind,\n                wl   :: Int;  # wl is the window length\n            \u03b1        :: Real    = 2.,    # only for splepians;\n            n        :: Int     = ceil(Int, 2*\u03b1)-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 \u2209 (rectangular, slepian)\n            wl\u208b\u2081     = wl-1\n            wl\u208b\u2081\u00bd    = wl\u208b\u2081/2\n            c(i::Int) = cos(2\u03c0*(i-1)/wl\u208b\u2081)\n            c(i::Int, j::Int) = cos(2\u03c0*j*(i-1)/wl\u208b\u2081)\n    end\n\n    if      kind == rectangular v = ones(type, wl)\n    elseif  kind == triangular  v = Vector{type}([1 - abs(2*(i-1)-wl\u208b\u2081)/wl\u208b\u2081 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\u208b\u2081\u00bd)/wl\u208b\u2081\u00bd)^2 for i=1:wl])\n    elseif  kind == parzen\n            v=Vector{type}(undef, wl)\n            wl\u00bd, wl\u00bc= wl\u00f72, wl\u00f74\n            for i=1:wl\u00bc        v[i] = 2*((1 - (abs(i-wl\u00bd)/wl\u00bd))^3) end\n            for i=wl\u00bc+1:wl\u00bd    v[i] = 1 - 6*(abs(i-wl\u00bd)/wl\u00bd )^2 + 6*(abs(i-wl\u00bd)/wl\u00bd)^3 end\n            for i=wl\u00bd+1:wl-wl\u00bc v[i] = 1 - 6*(abs(i-1-wl\u00bd)/wl\u00bd)^2 + 6*(abs(i-1-wl\u00bd)/wl\u00bd)^3 end\n            for i=wl-wl\u00bc+1:wl  v[i] = 2*((1 - (abs(i-1-wl\u00bd)/wl\u00bd))^3) end\n    elseif  kind == slepian    v    = Matrix{type}(dpss(wl, \u03b1, 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 \u2209 (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 \u2209 (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]./= \u221ai*(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, \u03b1, 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 `\u03b1` used in the DSP package and in the\nuniversal [Taper](@ref) constructor is set as\n\n        `\u03b1=(bandwidth/2)*wl/sr`.\n\nThe optimal number of dpss is heuristically set to\n\n        `n=max(1, trunc(Int, 2*\u03b1)-trunc(Int, log(2*\u03b1)))`.\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    \u03b1=(bandwidth/2)*wl/sr # \u03b1 parameter\n    # heuristic to eliminate eigenfunctions with small eigenvalues\n    n=max(1, trunc(Int, 2*\u03b1)-trunc(Int, log(2*\u03b1)))\n    return taper(slepian, wl, \u03b1=\u03b1, 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, ``\u03b1`` (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.\u03b1), n=$(taper.n))\" :\n                           string(taper.kind)\n\n\n# ++++++++++++++++++++  Show override  +++++++++++++++++++ # (REPL output)\nfunction Base.show(io::IO, ::MIME{Symbol(\"text/plain\")}, \ud835\udf0f::Taper)\nprintln(io, titleFont, \"\u2353 Taper type; $(size(\ud835\udf0f.y, 1))-samples\")\n#println(io, \"\u25a1  \u25a1    \u25a1      \u25a1        \u25a1           \u25a1\", defaultFont)\nprintln(io, separatorFont, \"\u2b52  \u2b52    \u2b52      \u2b52        \u2b52           \u2b52\", defaultFont)\nprintln(io, \"taper kind   (.kind): \", string(\ud835\udf0f.kind))\nprintln(io, \"half-bandwidth  (.\u03b1): $(\ud835\udf0f.\u03b1)\")\nprintln(io, \"number of tapers(.n): $(\ud835\udf0f.n)\")\n\ud835\udf0f.kind==slepian ? println(io, \"data            (.y): $(size(\ud835\udf0f.y, 1))x$(size(\ud835\udf0f.y, 2))-\", typeof(\ud835\udf0f.y)) :\n                 println(io, \"data            (.y): $(length(\ud835\udf0f.y))-\", typeof(\ud835\udf0f.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": "using Flux, Statistics, DelimitedFiles\nusing Flux: Params, gradient\nusing Flux.Optimise: update!\nusing DelimitedFiles, Statistics\nusing Parameters: @with_kw\n\n# This replicates the housing data example from the Knet.jl readme. Although we\n# could have reused more of Flux (see the mnist example), the library's\n# abstractions are very lightweight and don't force you into any particular\n# strategy.\n\n# Struct to define hyperparameters\n@with_kw mutable struct Hyperparams\n    lr::Float64 = 0.1\t\t# learning rate\n    split_ratio::Float64 = 0.1\t# Train Test split ratio, define percentage of data to be used as Test data\nend\n\nfunction get_processed_data(args)\n\n    isfile(\"housing.data\") ||\n        download(\"https://raw.githubusercontent.com/MikeInnes/notebooks/master/housing.data\",\n            \"housing.data\")\n\n    rawdata = readdlm(\"housing.data\")'\n\n    # The last feature is our target -- the price of the house.\n    split_ratio = args.split_ratio # For the train test split\n\n    x = rawdata[1:13,:]\n    y = rawdata[14:14,:]\n\n    # Normalise the data\n    x = (x .- mean(x, dims = 2)) ./ std(x, dims = 2)\n\n    # Split into train and test sets\n    split_index = floor(Int,size(x,2)*split_ratio)\n    x_train = x[:,1:split_index]\n    y_train = y[:,1:split_index]\n    x_test = x[:,split_index+1:size(x,2)]\n    y_test = y[:,split_index+1:size(x,2)]\n\n    train_data = (x_train, y_train)\n    test_data = (x_test, y_test)\n\n    return train_data,test_data\nend\n\n# Struct to define model\nmutable struct model\n    W::AbstractArray\n    b::AbstractVector\nend\n\n# Function to predict output from given parameters\npredict(x, m) = m.W*x .+ m.b\n\n# Mean Squared Error\nmeansquarederror(y\u0302, y) = sum((y\u0302 .- y).^2)/size(y, 2)\n    \nfunction train(; kws...)\n    # Initialize the Hyperparamters\n    args = Hyperparams(; kws...)\n    \n    # Load the data\n    (x_train,y_train),(x_test,y_test) = get_processed_data(args)\n    \n    # The model\n    m = model((randn(1,13)),[0.])\n    \n    loss(x, y) = meansquarederror(predict(x, m), y)\n\n    ## Training\n    \u03b7 = args.lr\n    \u03b8 = params([m.W, m.b])\n\n    for i = 1:500\n      g = gradient(() -> loss(x_train, y_train), \u03b8)\n      for x in \u03b8\n        update!(x, -g[x]*\u03b7)\n      end\n      if i%100==0\n          @show loss(x_train, y_train)\n        end\n    end\n    \n    # Predict the RMSE on the test set\n    err = meansquarederror(predict(x_test, m),y_test)\n    println(err)\nend\n\ncd(@__DIR__)\ntrain()\n", "meta": {"hexsha": "a978471de9d387b9439b395265593d4619b9a619", "size": 2407, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "other/housing/housing.jl", "max_stars_repo_name": "thomascherickal/model-zoo", "max_stars_repo_head_hexsha": "377c61980c368d19c3ec4dc2fd19dca74c7c383e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-22T11:34:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T11:34:16.000Z", "max_issues_repo_path": "other/housing/housing.jl", "max_issues_repo_name": "thomascherickal/model-zoo", "max_issues_repo_head_hexsha": "377c61980c368d19c3ec4dc2fd19dca74c7c383e", "max_issues_repo_licenses": ["MIT"], "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/housing/housing.jl", "max_forks_repo_name": "thomascherickal/model-zoo", "max_forks_repo_head_hexsha": "377c61980c368d19c3ec4dc2fd19dca74c7c383e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-08T01:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T05:31:41.000Z", "avg_line_length": 25.8817204301, "max_line_length": 106, "alphanum_fraction": 0.6501869547, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7512149181329003}}
{"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, \u03b1::Real, \u03b2::Real)\n\nCompute the quadratic expansion of an interval matrix, ``\u03b1A + \u03b2A^2``, using\ninterval arithmetics.\n\n### Input\n\n- `A` -- interval matrix\n- `\u03b1` -- linear coefficient\n- `\u03b2` -- quadratic coefficient\n\n### Output\n\nAn interval matrix that encloses ``B := \u03b1A + \u03b2A^2``.\n\n### Algorithm\n\nThis a variation of the algorithm in [1, Section 6]. If ``A = (a\u1d62\u2c7c)`` and\n``B := \u03b1A + \u03b2A^2 = (b\u1d62\u2c7c)``, the idea is to compute each ``b\u1d62\u2c7c`` by factoring\nout repeated expressions (thus the term *single-use expressions*).\n\nFirst, let ``i = j``. In this case,\n\n```math\nb\u2c7c\u2c7c = \u03b2\\\\sum_\\\\{k, k \u2260 j} a_{jk} a_{kj} + (\u03b1 + \u03b2a_{jj}) a_{jj}.\n```\n\nNow consider ``i \u2260 j``. Then,\n\n```math\nb\u1d62\u2c7c = \u03b2\\\\sum_\\\\{k, k \u2260 i, k \u2260 j} a_{ik} a_{kj} + (\u03b1 + \u03b2a_{ii} + \u03b2a_{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, \u03b1::Real, \u03b2::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], \u03b1, \u03b2)\n        for k in 1:n\n            k == j && continue\n            B[j, j] += \u03b2 * (A[j, k] * A[k, j])\n        end\n    end\n\n    # case i \u2260 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] * (\u03b1 + \u03b2*(A[j, j] + A[i, i]))\n            for k in 1:n\n                (k == i || k == j) && continue\n                B[i, j] += \u03b2 * (A[i, k] * A[k, j])\n            end\n        end\n    end\n    return B\nend\n\nfunction quadratic_expansion(x::Interval, \u03b1::Real, \u03b2::Real)\n    iszero(\u03b2) && return \u03b1 * x\n\n    return ((2 * \u03b2 * x + \u03b1) ^ 2 - \u03b1 ^ 2) / (4 * \u03b2)\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\u2071 = increment!(pow)\n        S += A\u2071 * (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\u2071 = 1\n    i! = 1\n    C\u2071 = copy(C)\n    for i in 1:p\n        i! *= i\n        t\u2071 *= t\n        Q += C\u2071 * t\u2071/i!\n        C\u2071 *= C\n    end\n    M = exp(C*t)\n    Y = M - Q\n    \u0393 = IntervalMatrix(fill(zero(T)\u00b1one(T), (n, n)))\n    E = \u0393 * 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 \u2265 1 \" *\n        \"but it should be smaller than 1; try choosing a larger order\"\n    \u0393 = IntervalMatrix(fill(zero(T)\u00b1one(T), (n , n)))\n    return \u0393 * ((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\u2099 = IntervalMatrix(Interval(one(T)) * I, n)\n    H = I\u2099 + A/K\n    for i in (K-1):-1:1\n        H = I\u2099 + 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\u2071l = LA^2\n    Z = zeros(n, n)\n    RA = sup(A)\n    A\u2071r = 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\u2071l *= LA\n        Y += A\u2071l * fact\n        A\u2071r *= RA\n        Z += A\u2071r * 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(\u03be) = 2 * ( \u03be - 1/2 ) * ( \u03be - 1 )\nPsi2(\u03be) = 4 * \u03be * ( 1 - \u03be )\nPsi3(\u03be) = 2 * \u03be * ( \u03be - 1/2 )\nconst PSI = ( Psi1, Psi2, Psi3 )\n\ndPsi1(\u03be) = 4\u03be - 3\ndPsi2(\u03be) = 4 * ( 1 - 2\u03be )\ndPsi3(\u03be) = 4\u03be - 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, \u03b3::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(\u03b3) != 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] = \u03b3[k]\n    end\n    if right == Neumann\n        k += 1\n        I[k] = rightnd\n        V[k] = \u03b3[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                \u03be = k / r\n                s += Und[elm[p,m]] * PSI[p](\u03be)\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_\u2207biases!(\u2207biases::Array{Float32}, value_matrix::Array{Float32}, \u03b4::Array{Float32})\n        @avxt for i in eachindex(value_matrix)\n            \u2207biases[i] = exp(-value_matrix[i])/(1+exp(-value_matrix[i]))^2*\u03b4[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": "module TestNChisq\n\nusing Base.Test\nusing Econometrics\n\nexpOut = 0.1441868\nactOut = Econometrics.dnchisq(1.2, 3.2, 1.4)\n@test_approx_eq_eps expOut actOut 1e-6\n\nexpOut = 0.1244554\nactOut = Econometrics.pnchisq(1.2, 3.2, 1.4)\n@test_approx_eq_eps expOut actOut 1e-6\n\nexpOut = 3.039873\nactOut = Econometrics.qnchisq(0.4, 3.2, 1.4)\n@test_approx_eq_eps expOut actOut 1e-6\n\np = 0.2\nq = Econometrics.qnchisq(p, 3.2, 1.4)\np2 = Econometrics.pnchisq(q, 3.2, 1.4)\n@test_approx_eq p p2\n\nsimVals = Econometrics.rnchisq(1000, 3.2, 1.4)\nuVals = Econometrics.pnchisq(simVals, 3.2, 1.4)\nsimVals2 = Econometrics.qnchisq(uVals, 3.2, 1.4)\n@test all(abs(simVals - simVals2) .< 1e-10)\n\nend\n", "meta": {"hexsha": "e0a77d20520372343947aeb4f2054f3c7e0c158f", "size": 666, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/nchisq.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": "test/nchisq.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": "test/nchisq.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": 22.9655172414, "max_line_length": 48, "alphanum_fraction": 0.7312312312, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7512144003399952}}
{"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 \u2260 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 \u2260 1 && x \u2260 n - 1\n            return true\n        end\n        x = y\n    end\n    x \u2260 1\nend\n\n#=\nMiller-Rabin probabilistic primality test: the chance of being wrong is \u2248 1/4 each pass through\nthe loop.\n=#\n\nfunction isPrime(n, k)\n    if n < 2 || (n \u2260 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^\u2013100 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] \u2248 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 \u2013 1.  Since p is safe prime, there are only two:\n2 and (p \u2013 1) / 2. The number of such generators is \ud835\udf11(p \u2013 1).\n=#\n\nfunction generator(n, p)\n    g = n\n    q = (p - 1) \u00f7 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 \u220a {(p \u2013 1)/2, ..., p \u2212 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) \u00f7 2:p - 1)\n    b = powerMod(r, a, p)\n    ((p, a), (p, r, b))\nend\n\n#=\nChoose a random k \u220a {1, ..., p \u2013 2}\n\nCompute \ud835\udefe = r^k (mod p)\n\nCompute \ud835\udeff = m b^k (mod p)\n\nThe encrypted message is (\ud835\udefe, \ud835\udeff)\n=#\n\nfunction encrypt(m, key)\n    (p, r, b) = key\n    k = rand(1:p - 2)\n    \ud835\udefe = powerMod(r, k, p)\n    \ud835\udeff = mod(m * powerMod(b, k, p), p)\n    (\ud835\udefe, \ud835\udeff)\nend\n\n#=\nThe decrypted message is \ud835\udeff \ud835\udefe^(p \u2013 1 \u2013 a) (mod p)\n=#\n\nfunction decrypt(m, key)\n    (p, a) = key\n    (\ud835\udefe, \ud835\udeff) = m\n    mod((powerMod(\ud835\udefe, p - 1 - a, p) * \ud835\udeff), 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 \u00f7= 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 \u22c5 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": "using OrthogonalPolynomialsQuasi, ContinuumArrays, DomainSets, FillArrays, Test\nimport OrthogonalPolynomialsQuasi: jacobimatrix\n\n@testset \"Hermite\" begin\n    H = Hermite()\n    @test axes(H) == (Inclusion(\u211d), Base.OneTo(\u221e))\n    x = axes(H,1)\n    X = jacobimatrix(H)\n\n    w = HermiteWeight()\n    wH = w.*H\n    M = H'* ( w.*H)\n    S = Diagonal(M.diag .^ (-1/2))\n    Si = Diagonal(M.diag .^ (1/2))\n    J = Si*X*S\n\n    (J - im*Eye(\u221e)) \\ [1;zeros(\u221e)]\n\n    @test H[0.1,1] === 1.0 # equivalent to H_0(0.1) == 1.0\n    D = Derivative(x)\n    \n    h = 0.000001\n    @test (D*H)[0.1,1:5] \u2248 (H[0.1+h,1:5] - H[0.1,1:5])/h atol=100h\nend", "meta": {"hexsha": "3c5b6861b6e44efeb4c28fde7f06c301c9899fe5", "size": 619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_hermite.jl", "max_stars_repo_name": "putianyi889/OrthogonalPolynomialsQuasi.jl", "max_stars_repo_head_hexsha": "6221d1720f9f66f889e7590bb809894f1251b1bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-08-26T19:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:06:02.000Z", "max_issues_repo_path": "test/test_hermite.jl", "max_issues_repo_name": "putianyi889/OrthogonalPolynomialsQuasi.jl", "max_issues_repo_head_hexsha": "6221d1720f9f66f889e7590bb809894f1251b1bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-11-22T10:34:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-21T19:06:33.000Z", "max_forks_repo_path": "test/test_hermite.jl", "max_forks_repo_name": "putianyi889/OrthogonalPolynomialsQuasi.jl", "max_forks_repo_head_hexsha": "6221d1720f9f66f889e7590bb809894f1251b1bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-11-09T17:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T14:44:56.000Z", "avg_line_length": 25.7916666667, "max_line_length": 79, "alphanum_fraction": 0.5557350565, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7512143968372162}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mos\u00e8 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\u00b0, longitude: 0\u00b0, 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\u00b0, -24.32\u00b0, 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 \u2209 part1 && dst \u2209 queue]\n        append!(queue, dests)\n    end\n    part2 = [node for node in 1:Graphs.nv(flow_graph) if node \u2209 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]*(\u03c0/180))\n      y = points[end,2] + sin(points[end,3]*(\u03c0/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": "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# %%\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    # \u03b1 ~ Normal(100, 10)\n    # w ~ filldist(Normal(0, 10), size(B, 2))\n    w ~ filldist(Normal(100, 10), size(B, 2))\n    \u03c3 ~ Exponential(1)\n    \u03bc = B * w\n    doy ~ MvNormal(\u03bc, \u03c3)\nend\n\nqspl = quap(spline(d2.doy))\n\n# %%\nw_str = [\"w[$i]\" for i in 1:length(basis)]\npost = DataFrame(rand(qspl.distr, 1000)', [w_str; \"\u03c3\"])\n\nsmu = B * Array(post[!, w_str])'\nsmu_m, smu_lower, smu_upper = meanlowerupper(smu)\n\nscatter(d2.year, d.doy, alpha = 0.3)\nplot!(d2.year, smu_m, ribbon = (smu_m .- smu_lower, smu_upper .- smu_m))\n\n# %%\n\"\"\"\nNot sure what he means by \"The first basis functions could substitute for the intercept\".\nIf I'm not mistaken I need to add the intercept to all of the basis functions since the\nfirst one doesn't reach to the end?\n\"\"\"\n", "meta": {"hexsha": "cfdef3fea46091d89b3c784ca50aabe41fdbf898", "size": 1303, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch04/4H8.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/4H8.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/4H8.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.1296296296, "max_line_length": 89, "alphanum_fraction": 0.6761320031, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.751204685507793}}
{"text": "using Test\nusing Example2018\n\n#Tests\n# Polynomials form a ring\n# 1. addition is associative\n# 2. addition is identity\n# 3. additive inverse\n# 4. addition commutes \n# 5. multiplication is ...\n\n@testset \"Polynomials form a ring\" begin \n# test commands\n\n\tz = Polynomial([0])\n\tfor  n in 1:100\n\t\t#degree\n\t\tdeg = rand(0:100)\n\t\tp = Polynomial(rand(-1000:1000,deg+1))\n\n\t\t@test z + p == p\n\t\t@test p + z == p\n\t\t@test p + (-p) == z\n\tend\nend\n#test set \n\n#@show Polynomial([1,2,3])\n#@show evaluate(Polynomial([1,2,3]), 2)\n#@show Polynomial([1,2,3]) + Polynomial([4,5]) \n#@show 3*Polynomial([1,2,3]) \n#@show deriv(Polynomial([0,0,1,0]))\n\n\n# \n", "meta": {"hexsha": "38ecb6b9dc0220fea27c1fd4a06abeac4643857c", "size": 628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "dgutierrez10/Example2018", "max_stars_repo_head_hexsha": "d14150664f7c1c050fba56c514aa02887bcc3afa", "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/runtests.jl", "max_issues_repo_name": "dgutierrez10/Example2018", "max_issues_repo_head_hexsha": "d14150664f7c1c050fba56c514aa02887bcc3afa", "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/runtests.jl", "max_forks_repo_name": "dgutierrez10/Example2018", "max_forks_repo_head_hexsha": "d14150664f7c1c050fba56c514aa02887bcc3afa", "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.4444444444, "max_line_length": 47, "alphanum_fraction": 0.6337579618, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7512046830166189}}
{"text": "\"\"\"\n    gsdec(sys; job = \"finite\", smarg, fast = true,  atol = 0,  atol1 = atol, atol2 = atol, rtol = n\u03f5) -> (sys1, sys2)\n\nCompute for the descriptor system `sys = (A-\u03bbE,B,C,D)` with the transfer function matrix\n`G(\u03bb)`, the additive spectral decomposition `G(\u03bb) = G1(\u03bb) + G2(\u03bb)` such that `G1(\u03bb)`, \nthe transfer function matrix of the descriptor system `sys1 = (A1-\u03bbE1,B1,C1,D1)`, \nhas only poles in a certain domain of interest `Cg` of the complex plane and `G2(\u03bb)`, \nthe transfer function matrix of the descriptor system `sys2 = (A2-\u03bbE2,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-\u03bbE`, 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(\u03f5)`, for a continuous-time system, and `smarg = 1-sqrt(\u03f5)`, \nfor a discrete-time system), where `\u03f5` 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*\u03f5`, where `\u03f5` 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,\u03bb::Number,V::AbstractVecOrMat,a::Vector)= compute_Mlincomb(nep.spmf,\u03bb,V,a);\ncompute_Mlincomb(nep::ChebPEP,\u03bb::Number,V::AbstractVecOrMat)= compute_Mlincomb(nep.spmf,\u03bb,V);\ncompute_Mder(nep::ChebPEP,\u03bb::Number)=compute_Mder(nep.spmf,\u03bb,0)\ncompute_Mder(nep::ChebPEP,\u03bb::Number,der::Integer)=compute_Mder(nep.spmf,\u03bb,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(\u03bb)= B_0T_0(\u03bb)+\u22ef+B_{k-1}T_{k-1}(\u03bb)\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": "import VoronoiCells: LEFT, RIGHT, LOWER, UPPER\nusing VoronoiDelaunay\n\n@testset \"Area of polygons\" begin\n\t# Area of square\n\tS = [Point2D(LEFT, LOWER) ; Point2D(RIGHT, LOWER) ; Point2D(RIGHT, UPPER) ; Point2D(LEFT, UPPER)]\n\t@test polyarea(S) \u2248 1.0\n\n\t# Area of triangle\n\tT1 = [Point2D(LEFT, LOWER) ; Point2D(RIGHT, LOWER) ; 0.5*(Point2D(RIGHT, UPPER) + Point2D(LEFT, UPPER))]\n\t@test polyarea(T1) \u2248 0.5\n\n\tT2 = [Point2D(LEFT, LOWER) ; Point2D(LEFT+0.5, LOWER) ;\n\tPoint2D(LEFT, LOWER+0.5)]\n\t@test polyarea(T2) \u2248 0.5^3\nend\n\n", "meta": {"hexsha": "90984608497470d04da809f5e6d79dd53629edd5", "size": 517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Polyarea.jl", "max_stars_repo_name": "UnofficialJuliaMirror/VoronoiCells.jl-e3e34ffb-84e9-5012-9490-92c94d0c60a4", "max_stars_repo_head_hexsha": "e1e0e280863b50fb0f5b0c127bc05ee08403622a", "max_stars_repo_licenses": ["MIT"], "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/Polyarea.jl", "max_issues_repo_name": "UnofficialJuliaMirror/VoronoiCells.jl-e3e34ffb-84e9-5012-9490-92c94d0c60a4", "max_issues_repo_head_hexsha": "e1e0e280863b50fb0f5b0c127bc05ee08403622a", "max_issues_repo_licenses": ["MIT"], "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/Polyarea.jl", "max_forks_repo_name": "UnofficialJuliaMirror/VoronoiCells.jl-e3e34ffb-84e9-5012-9490-92c94d0c60a4", "max_forks_repo_head_hexsha": "e1e0e280863b50fb0f5b0c127bc05ee08403622a", "max_forks_repo_licenses": ["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": 105, "alphanum_fraction": 0.6789168279, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7512046804129354}}
{"text": "################################################################################\n#\n#   Calculates integer coordinates in \u2124\u207f 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    \u03b4cs = [ 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\u2092, c, g)\n        hw = R\u2092 / 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                \u03b4cn = (ng - c[g])\n                nc = c[1:g-1] - \u03b4cs[g] * \u03b4cn\n                nsqR\u2092 = R\u2092^2 - (Tgg[g] * \u03b4cn)^2\n                nsqR\u2092 > 0. && _innerpoints(sqrt(nsqR\u2092), 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\u2092 = radius / sqrt(\u03c0) + padding * Tgg[n]\n    _innerpoints(padded_R\u2092, 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, \u03b2)\n\n    Y = zeros(N + 1)\n    Y[1] = y0\n    Y\n\nend\n\nfunction defineY(N, y0::Vector{<:Real}, \u03b2)\n\n    if size(y0) == size(\u03b2)\n\n        Y = zeros(N + 1, length(\u03b2))\n        Y[1, :] .= y0\n        Y\n\n    elseif size(y0) != size(\u03b2)\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}, \u03b2)\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, \u03b2, m) = y0\n\nfunction taylor_expansion(t0, t, y0::Vector{<:Real}, \u03b2, m)\n\n    if size(y0) == size(\u03b2)\n\n        return y0\n\n    elseif size(y0) != size(\u03b2)\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}, \u03b2, m) = sum([(t - t0) ^ k / factorial(k) * y0[:, k + 1] for k in 0:m - 1])\n\n## function \u03d5 ##\nfunction Phi(y, F, \u03b2, t, n, par...)\n\n    alpha = zeros(n - 1)\n    fun = zeros(n - 1)\n\n    alpha = map((x) -> \u03b1(x, \u03b2), n - 1:-1:1)\n    fun = map((x) -> F(t, x, \u03b2, y, par...), 2:n)\n\n    a_n0(n, \u03b2) .* F(t, 1, \u03b2, y, par...) .+ sum([alpha[i] .* fun[i] for i in 1:n - 1])\n\nend\n\na_n0(n, \u03b2) = ((n - 1) .^ (\u03b2 .+ 1) .- n .^ \u03b2 .* (n .- \u03b2 .- 1)) ./ \u0393(\u03b2 .+ 2)\n\n## function \u03b1 ##\nfunction \u03b1(n, \u03b2)\n\n    if n == 0\n\n        return 1 ./ \u0393(\u03b2 .+ 2)\n\n    else\n\n        return ((n .- 1) .^ (\u03b2 .+ 1) .- 2 .* n .^ (\u03b2 .+ 1) .+ (n .+ 1) .^ (\u03b2 .+ 1)) ./ \u0393(\u03b2 .+ 2)\n\n    end\n\nend\n\n## Gamma function for vectors ##\n\u0393(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": "# rmsd100\n# root mean-squared difference between two arrays in %\n\nexport rmsd100\n\nusing Test: @test, @test_throws, @inferred\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\n\n\"\"\"\n    rmsd100(:test)\nself test\n\"\"\"\nfunction rmsd100(x::Symbol)\n    x != :test && throw(\"Invalid symbol; use :test for testing functions.\")\n    a = [1 2; 4 5; 7 8]\n    b = [3 2; 4 6; 8 7]\n    c = [false true; true false; false false] #avg. 0\n    d = [false false; false false; false true] #avg. 1\n    e = [true true; true true; true false] # average 1,0,1,0,4 = sqrt(6/5)\n    tests = cat(c, d, e, dims = 3)\n    pred = [0, 100, 100*sqrt(6/5)]\n    for i in 1:size(tests,1)\n        @test rmsd100(a, b ; mask=tests[:,:,i]) == pred[i]\n    end\n    @test rmsd100([1, 0], [0, 1]) == 100 # no mask test\n\n#=  not important to support or test.  user can pass mask=ig.mask if needed\n    a = ones(300,400)\n    b = ones(300,400)\n    b[100:200,100:200] .= 0\n    #so there's a blot of zeros from 100,100 to 200,200\n    b[200:250,300:320] .= 3\n    #and a blot of threes over here\n    ig1 = image_geom(nx = 300,ny = 400,dx = 1,dy = 1)\n    @test my_rmse(a,b,ig1) > 20\n=#        \n    return true\nend\n", "meta": {"hexsha": "9639bf41debca71d1a7b142eca1aef25d17e08b0", "size": 1658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utility/rmsd100.jl", "max_stars_repo_name": "StevenWhitaker/MIRT.jl", "max_stars_repo_head_hexsha": "49adc00293ecbe9ce9ca8ca45c02911c0a794316", "max_stars_repo_licenses": ["MIT"], "max_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": "StevenWhitaker/MIRT.jl", "max_issues_repo_head_hexsha": "49adc00293ecbe9ce9ca8ca45c02911c0a794316", "max_issues_repo_licenses": ["MIT"], "max_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": "StevenWhitaker/MIRT.jl", "max_forks_repo_head_hexsha": "49adc00293ecbe9ce9ca8ca45c02911c0a794316", "max_forks_repo_licenses": ["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.1803278689, "max_line_length": 89, "alphanum_fraction": 0.6049457177, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.751201114925213}}
{"text": "function mergesort(arr::Vector)\n    if length(arr) \u2264 1 return arr end\n    mid = length(arr) \u00f7 2\n    lpart = mergesort(arr[1:mid])\n    rpart = mergesort(arr[mid+1:end])\n    rst = similar(arr)\n    i = ri = li = 1\n    @inbounds while li \u2264 length(lpart) && ri \u2264 length(rpart)\n        if lpart[li] \u2264 rpart[ri]\n            rst[i] = lpart[li]\n            li += 1\n        else\n            rst[i] = rpart[ri]\n            ri += 1\n        end\n        i += 1\n    end\n    if li \u2264 length(lpart)\n        copy!(rst, i, lpart, li)\n    else\n        copy!(rst, i, rpart, ri)\n    end\n    return rst\nend\n\nv = rand(-10:10, 10)\nprintln(\"# unordered: $v\\n -> ordered: \", mergesort(v))\n", "meta": {"hexsha": "ef0de570e0685accb9e58ddeb211b023e7c0634c", "size": 661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sorting-algorithms-merge-sort.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/sorting-algorithms-merge-sort.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/sorting-algorithms-merge-sort.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.6071428571, "max_line_length": 60, "alphanum_fraction": 0.502269289, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7512011135005183}}
{"text": "#=\nGeometry in 2d euclidean space\n=#\n\n\"\"\"\ndeltaangle(a::Real, b::Real)\n\nReturn the minimum \u03b4 such that\n    a + \u03b4 = mod(b, 2\u03c0)\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.\u03b8), cos(reference.\u03b8)\n    \u0394x = point.x - reference.x\n    \u0394y = point.y - reference.y\n    VecE2(c*\u0394x + s*\u0394y, c*\u0394y - s*\u0394x)\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.\u03b8), cos(reference.\u03b8)\n    \u0394x = point.x - reference.x\n    \u0394y = point.y - reference.y\n    VecSE2(c*\u0394x + s*\u0394y, c*\u0394y - s*\u0394x, point.\u03b8 - reference.\u03b8)\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.\u03b8), sin(reference.\u03b8)\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.\u03b8), sin(reference.\u03b8)\n    VecSE2(c*point.x -s*point.y + reference.x, s*point.x +c*point.y + reference.y, reference.\u03b8 + point.\u03b8)\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 \u21a6 0 if x[1] >= ||x[2:end]||, +\u221e 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 \u2a7d 2pq, p \u2a7e 0, q \u2a7e 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 \u21a6 0 if x[1] \u2a7e 0, x[2] \u2a7e 0, norm(x[3:end])\u00b2 \u2a7d 2*x[1]*x[2], +\u221e 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 EngEconomics\n\n# Given\ni = 0.08\nN = 20\ng = 0.05\nA1 = 1000\nA_13_20 = 2000\nm = 12\n\n# Find.\n# How much should be invested now so that the interest pays after all this can\n# pay off everything?\n\n# First Find ic\nic = i / m\nNc = 20\n\n# First figure out how much in total this guy owes in present money\nowe = (A1 * presentWorthConversionFactorGeometric(g, ic, 11) + A_13_20 * seriesPresentAmountFactor(ic, 8) * presentWorthFactor(ic, 11))\npayNow = owe * presentWorthFactor(ic, 1)\n", "meta": {"hexsha": "9edba53592e7ccfd29825f399704d579a36574a8", "size": 477, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/quiz1/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/quiz1/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/quiz1/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": 21.6818181818, "max_line_length": 135, "alphanum_fraction": 0.714884696, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7511697558966209}}
{"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\u00e1rik, 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": "using Test\n\n#Arithmetic library imports\nusing IntervalArithmetic\nusing IntervalContractors\n\n#Preamble\nsetprecision(53)\nsetprecision(Interval, Float64)\n\n# Using approximate checks for validaty update later?\nimport Base.isapprox\nisapprox(x::Interval,y::Interval) = isapprox(x.lo,y.lo,atol=1E-4) && isapprox(x.hi,y.hi,atol=1E-4)\n\n@testset \"max_rev_test\" begin\n    @test max_rev(\u2205, entireinterval(Float64),entireinterval(Float64))[2] == Interval(-\u221e, \u221e)\n    @test max_rev(Interval(0.0, 1.0), \u2205,Interval(-2.0, -1.0))[2] == \u2205\n    @test max_rev(\u2205, Interval(0.0, 1.0),Interval(-2.0, -1.0))[2] == \u2205\n    @test max_rev(Interval(-2.0, -1.0), entireinterval(Float64),Interval(-3.0, -2.0))[2] == Interval(-\u221e, -1.0)\n    @test isapprox(max_rev(Interval(1.0, 1.0), entireinterval(Float64),Interval(-2.0, -1.0))[2], Interval(-\u221e, 1))\n    @test max_rev(entireinterval(Float64), Interval(-2.0, -1.0), Interval(-3.0, -2.0))[2] == Interval(-2.0, -1.0)\n    @test max_rev(Interval(-Inf, 0.0), entireinterval(Float64),Interval(-3.0, -2.0))[2] == Interval(-\u221e, 0.0)\nend\n\n@testset \"min_rev_test\" begin\n    @test min_rev(\u2205, entireinterval(Float64),entireinterval(Float64))[2] == Interval(-\u221e, \u221e)\n    @test min_rev(Interval(0.0, 1.0), \u2205,Interval(-2.0, -1.0))[2] == \u2205                             # should return empty?\n    @test min_rev(\u2205, Interval(0.0, 1.0),Interval(-2.0, -1.0))[2] == \u2205\n    @test min_rev(Interval(-2.0, -1.0), entireinterval(Float64),Interval(-3.0, -2.0))[2] == Interval(-\u221e, -2.0)\n    @test isapprox(min_rev(Interval(1.0, 1.0), entireinterval(Float64),Interval(-2.0, -1.0))[2], Interval(-\u221e, -1.0))\n    @test min_rev(entireinterval(Float64), Interval(-2.0, -1.0), Interval(-3.0, -2.0))[2] == Interval(-3.0, -2.0)\n    @test min_rev(Interval(-Inf, 0.0), entireinterval(Float64),Interval(-3.0, -2.0))[2] == Interval(-\u221e, -2.0)\nend\n", "meta": {"hexsha": "0b59d786defb6a2e518684bb5e618e2db801d37e", "size": 1811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Non1788tests/extrema.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": "test/Non1788tests/extrema.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": "test/Non1788tests/extrema.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": 53.2647058824, "max_line_length": 120, "alphanum_fraction": 0.6377691883, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.751165135365237}}
{"text": "# write your own tests here\nN = 30\nph = discrete_phs(N, 0, 1); \neigval, eigvec = eigen(ph);\nnum_freq = frequencies(eigval)\nexact_freq = pi/2*collect(1:2:2*N);\nerr = exact_freq - num_freq;\n\n@test abs(err[2]) < 1e-13\n\n@test abs(minimum(damp(ph)[:,1])-pi/2)<1e-13\n", "meta": {"hexsha": "8e5e31ab1fd9d5eaff76222fd664bdae4630d3c1", "size": 261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ph_discretization.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": "test/ph_discretization.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": "test/ph_discretization.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": 21.75, "max_line_length": 44, "alphanum_fraction": 0.662835249, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7511651276066162}}
{"text": "using FractionalCalculus\nusing SymbolicUtils\nusing Test\n\nmacro eqtest(expr)\n    @assert expr.head == :call && expr.args[1] in [:(==), :(!=)]\n    if expr.args[1] == :(==)\n        :(@test isequal($(expr.args[2]), $(expr.args[3])))\n    else\n        :(@test !isequal($(expr.args[2]), $(expr.args[3])))\n    end |> esc\nend\n\n@testset \"Test DIFF CONSTANT AND POWERS\" begin\n    @syms x\n    @eqtest semidiff(x^2) == gamma(3)/gamma(2.5)*(x^1.5)\n    @eqtest semidiff(log(x)) == log(4*x) / sqrt(\u03c0*x)\n    #@eqtest semidiff(sqrt(1+x)) == 1/sqrt(pi*x)+atan(sqrt(x))/sqrt(pi)\n    #@eqtest semidiff(sqrt(1-x)) == 1/sqrt(pi*x)-atanh(sqrt(x))/sqrt(pi)\n    @eqtest semidiff(1/sqrt(1+x)) == 1/(sqrt(pi*x)*(1+x))\n    #@eqtest semidiff(1/sqrt(1-x)) == 1/(sqrt(pi*x)*(1-x))\n    @eqtest semidiff(1/(1+x)) == (sqrt(1+x)-sqrt(x)*asinh(sqrt(x)))/(sqrt(pi*x)*(1+x)^(3/2))\n    #@eqtest semidiff(1/(1-x)) == (sqrt(1-x)+sqrt(x)*asinh(sqrt(x)))/(sqrt(pi*x)*(1-x)^(3/2))\n    #@eqtest semidiff(1/(1+x)^(3/2)) == (1-x)/(sqrt(pi*x)*(1+x)^2)\n    #@eqtest semidiff(1/(1-x)^(3/2)) == (1+x)/(sqrt(pi*x)*(1-x)^2)\nend", "meta": {"hexsha": "62176af1c79a3cb8699b75ae60fb8d514802428b", "size": 1073, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SymbolicDiffTests.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": "test/SymbolicDiffTests.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": "test/SymbolicDiffTests.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": 41.2692307692, "max_line_length": 93, "alphanum_fraction": 0.5507921715, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7511651276066162}}
{"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(\u03c0/2+0.001im);\n@show real(v) #f(x)\n@show imag(v)/0.001 #f'(x)\n@show sin(pi/2*pi/2), \u03c0*cos(\u03c0^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": "using DynamicalSystemsBase\nusing DelayEmbeddings\nusing Test\nimport Peaks\n\nprintln(\"\\nTesting garcia_almeida.jl...\")\n@testset \"Garcia & Almeida method\" begin\n\nlo = Systems.lorenz()\n\ntr = trajectory(lo, 80; \u0394t = 0.01, Ttr = 10)\n\nx = tr[:, 1]\nY = Dataset(x)\nY = standardize(Y)\n\n@testset \"N-statistic\" begin\n    \u03c4s = 0:100\n    N , NN_distances = n_statistic(Y, x, w=0, T=1, \u03c4s = \u03c4s)\n\n    T = 17\n    N2 , NN_distances2 = n_statistic(Y, x, w=0, T=T, \u03c4s = \u03c4s)\n\n    # check whether the `d_E1`-statistic is the same\n    @test NN_distances[1][1:50] == NN_distances2[1][1:50]\n    @test NN_distances[5][1:100] == NN_distances2[5][1:100]\n\n    min_dist = 12\n    (max_1_idx,_) = Peaks.findmaxima(N,min_dist)\n    (max_2_idx,_) = Peaks.findmaxima(N2,min_dist)\n\n    @test 30 \u2264 max_1_idx[1] \u2264 35\n    @test 30 \u2264 max_2_idx[1] \u2264 35\n    @test 69 \u2264 max_1_idx[2] \u2264 75\n    @test 69 \u2264 max_2_idx[2] \u2264 75\n\n    # # plot N-Statistic for the Lorenz system as in Fig. 2(a) in [^Garcia2005a]\n    # using Plots\n    # plot(N,linewidth = 2, label = \"T=1 (as in the Paper)\", xaxis=:log)\n    # plot!(N2,linewidth = 2, label = \"T=$T\", xaxis=:log)\n    # plot!(N,seriestype = :scatter, label = \"\",xaxis=:log)\n    # plot!(N2,seriestype = :scatter, label = \"\",xaxis=:log)\n    # plot!(title = \"Lorenz System as in Fig. 2(a) in the Paper\")\n    # xlabel!(\"\u03c4\")\n    # ylabel!(\"N-Statistic\")\nend\n\n@testset \"garcia_embed univariate\" begin\n    Y_act, \u03c4_vals, ts_vals, FNNs, NS = garcia_almeida_embedding(x; \u03c4s=0:100,  w = 17, T = 17)\n    Y_act2, \u03c4_vals2, ts_vals2, FNNs2, NS2 = garcia_almeida_embedding(x; \u03c4s=0:100,  w = 1, T = 1)\n\n    @test size(Y_act,2) == 2\n    @test size(Y_act2,2) == 3\n    @test 10 \u2264 \u03c4_vals[2] \u2264 18\n    @test 1 \u2264 \u03c4_vals2[2] \u2264 3\n    @test FNNs[end]<=0.05\n    @test FNNs2[end]>FNNs2[end-1]\n\n    # using Plots\n    # plot3d(Y_act[:,1],Y_act[:,2],Y_act[:,3], marker=2, camera = (6, 4))\n    # plot!(title = \"Reconstruction of Lorenz attractor using Garcia&Almeida univariate embedding\")\n    #\n    # plot3d(Y_act2[:,1],Y_act2[:,2],Y_act2[:,3], marker=2, camera = (6, 4))\n    # plot!(title = \"Reconstruction of Lorenz attractor using Garcia&Almeida univariate embedding as in the paper\")\nend\n\n\n@testset \"garcia_embed multivariate\" begin\n    Y_act, \u03c4_vals, ts_vals, FNNs, NS = garcia_almeida_embedding(tr; \u03c4s=0:100,  w = 17, T = 17)\n    Y_act2, \u03c4_vals2, ts_vals2, FNNs2, NS2 = garcia_almeida_embedding(tr; \u03c4s=0:100,  w = 1, T = 1)\n\n    @test size(Y_act,2) == size(Y_act2,2) == 3\n    @test ts_vals[1] == ts_vals2[1] == ts_vals2[2] == ts_vals2[3] ==1\n    @test ts_vals[2] == 2\n    @test ts_vals[3] == 3\n    @test 10 \u2264 \u03c4_vals[3] \u2264 18\n    @test 1 \u2264 \u03c4_vals2[3] \u2264 3\n\n    # try to reproduce Fig.2a in [^Garcia2005b]\n    tra = Dataset(hcat(tr[:,1], tr[:,3]))\n    tra = standardize(tra)\n    taus = 0:100\n\n    N , _ = n_statistic(tra, tra[:,1], w=17, T=17, \u03c4s = taus)\n    N2 , _ = n_statistic(tra, tra[:,2], w=17, T=17, \u03c4s = taus)\n\n    _, minis2 = findmin(N2)\n\n    @test 20 \u2264 taus[minis2] \u2264 30\n\n    # using Plots\n    # NN = hcat(N,N2)\n    # plot(NN, xaxis=:log)\n    # plot(NN)\n\nend\n\n\nend\n", "meta": {"hexsha": "c1bf1f36a37c6d04796ec082833ff9f91d26b483", "size": 3039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/unified/test_garcia.jl", "max_stars_repo_name": "JuliaDynamics/DelayEmbeddings.jl", "max_stars_repo_head_hexsha": "a266a80222059fd612632989c7dd59c786ee69b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-11-21T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T14:24:47.000Z", "max_issues_repo_path": "test/unified/test_garcia.jl", "max_issues_repo_name": "JuliaDynamics/DelayEmbeddings.jl", "max_issues_repo_head_hexsha": "a266a80222059fd612632989c7dd59c786ee69b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2018-11-09T12:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T14:06:10.000Z", "max_forks_repo_path": "test/unified/test_garcia.jl", "max_forks_repo_name": "JuliaDynamics/DelayEmbeddings.jl", "max_forks_repo_head_hexsha": "a266a80222059fd612632989c7dd59c786ee69b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-05-01T19:08:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T15:58:14.000Z", "avg_line_length": 30.39, "max_line_length": 115, "alphanum_fraction": 0.6094109905, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7511651237273059}}
{"text": "using SmoothedSpectralAbscissa ; const SSA=SmoothedSpectralAbscissa\nusing LinearAlgebra, Random\nusing Roots,Calculus\nusing Test\nRandom.seed!(0)\n\n\n\"\"\"\n    lyap_simple!(A::AbstractMatrix)\nreturns the naive implementation of the Lyapunov objective function and its\nderivative. Can be used for testing, plotting, etc\n\"\"\"\nfunction lyap_simple!(A::AbstractMatrix)\n    function  myf(s::Float64)::Float64\n        P = lyap(A - UniformScaling(s),one(A))\n        tr(P)\n    end\n    function d_myf(s::Float64)::Float64\n        sc,Id = UniformScaling(s), one(A)\n        P =  lyap(A - sc,Id)\n        Q = lyap(A' - sc,Id)\n        -2.0tr(P*Q)\n    end\n    myf,d_myf\nend\n\n\"\"\"\n    ssa_test(A::Matrix{Float64})\n\nThis is the easiest implementation\nfor testing and benchmarking.\n\"\"\"\nfunction ssa_test(A::Matrix{Float64} ; ssa_eps=nothing)\n    myf,d_myf = lyap_simple!(A)\n    ssa_eps = something(ssa_eps,SSA.default_eps_ssa(A))\n    myg(s)= 1.0 / myf(s) - ssa_eps\n    d_myg(s) = - d_myf(s) / myf(s)^2\n    sa = SSA.spectral_abscissa(A)\n    ssa_start = sa + 0.5*ssa_eps\n    find_zero( (myg,d_myg),ssa_start, Roots.Newton())\nend\n\n\nfunction f_for_gradient(vmat)\n    n = sqrt(length(vmat))\n    @assert isinteger(n)\n    n = Int64(n)\n    mat = copy(reshape(vmat,(n,n)))\n    return SSA.ssa(mat)\nend\n\n#\n\n@testset \"SA and SSA\" begin\n    # check SA\n    n = 100\n    mat = randn(n,n) + 1.4517I\n    alloc = SSA.SSAAlloc(n)\n    @test begin\n        sa1 = maximum(real.(eigvals(mat)))\n        SSA.PQ_init!(alloc,mat)\n        sa2 = SSA.spectral_abscissa(alloc)\n        sa3 = SSA.spectral_abscissa(mat)\n        isapprox(sa1,sa2 ; rtol=1E-4) && isapprox(sa1,sa3 ; rtol=1E-4)\n    end\n    # now test SSA against simpler version\n    ssa1 = ssa_test(mat)\n    ssa2 = SSA.ssa(mat)\n    @test isapprox(ssa1,ssa2 ; rtol=1E-4)\n    # same , but with a different epsilon\n    mat = randn(n,n) + 1.456I\n    \u03b5 = 0.31313131\n    ssa1 = ssa_test(mat; ssa_eps=\u03b5)\n    ssa2 = SSA.ssa(mat,\u03b5)\n    @test isapprox(ssa1,ssa2 ; rtol=1E-4)\nend\n\n@testset \"SSA Vs Lyapunov eq\" begin\n    # when the epsilon of the ssa is the inverse of the energy integral\n    # (computed by the lyap eq) , then the SSA is zero\n    n = 130\n    idm =diagm(0=>fill(1.0,n))\n    matd = diagm(0=>fill(-0.05,n))\n    fval=tr(lyap(matd,idm))\n    ssa=SSA.ssa!(matd,nothing,SSA.SSAAlloc(n),inv(fval))\n    @test isapprox(ssa,0.0;atol=1E-6)\n    matrand=randn(n,n) ./ sqrt(n) - 1.1I\n    fval=tr(lyap(matrand,idm))\n    ssa = SSA.ssa!(matrand,nothing,SSA.SSAAlloc(n),inv(fval))\n    @test isapprox(ssa,0.0;atol=1E-6)\n    matrand2 = matrand + 1.234I\n    ssa = SSA.ssa!(matrand2,nothing,SSA.SSAAlloc(n),inv(fval))\n    @test isapprox(ssa,1.234;atol=1E-6)\nend\n\n@testset \"SSA Newton method\" begin\n    n = 50\n    matrand=randn(n,n) ./ sqrt(n)\n    alloc=SSA.SSAAlloc(n)\n    SSA.PQ_init!(alloc,matrand)\n    sa_mat = SSA.spectral_abscissa(matrand)\n    eps_ssa = SSA.default_eps_ssa(matrand)\n    fungrad(s) = SSA.ssa_simple_obj_newton(s,alloc,eps_ssa,sa_mat)[1]\n    stests=range(sa_mat+0.01,3sa_mat;length=100)\n    grad_num = map(s->Calculus.gradient(fungrad,s),stests)\n    grad_an = let  vv = map(s->SSA.ssa_simple_obj_newton(s,alloc,eps_ssa,sa_mat),stests)\n        map(v-> v[1]/v[2],vv)\n    end\n    @test all(isapprox.(grad_num,grad_an;atol=1E-5))\n    ssa = SSA.ssa_simple!(matrand,nothing,alloc)\n    ssa_ntw =  SSA.ssa!(matrand,nothing,alloc;optim_method=SSA.OptimNewton)\n    @test isapprox(ssa,ssa_ntw;atol=1E-5)\nend\n\n\n@testset \"SSA gradient\" begin\n    n = 26\n    mat = rand(n,n) + UniformScaling(2.222)\n    @test begin\n        ssa1 = ssa_test(mat)\n        ssa2 = SSA.ssa(mat)\n        isapprox(ssa1,ssa2 ; rtol=1E-4)\n    end\n    @test begin\n        ssa,grad_an = SSA.ssa_withgradient(mat)\n        grad_num = Calculus.gradient(f_for_gradient,mat[:])\n        all(isapprox.(grad_an[:],grad_num ; rtol=1E-3) )\n    end\nend\n", "meta": {"hexsha": "9cee6a401c47d14f3c9cd50eae9e12a0810c3eed", "size": 3803, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.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": "test/runtests.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": "test/runtests.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": 29.2538461538, "max_line_length": 88, "alphanum_fraction": 0.6444911912, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7511651197419282}}
{"text": "function trap_rule(xarr::Vector{T},farr::Vector{T}) where T\n    N = length(xarr)\n\n    \u0394x = 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*\u0394x\n\n    return quad\nend\n\n# return J. Compares how well particle field (represented by \u03b8) \n# approximates F(y)\nfunction cost(\u03b8,y,F)\n    x,s,h = decompose_theta(\u03b8)\n    G = get_gauss_field(\u03b8,y)\n    f = (G - F).^2\n    J = trap_rule(y,f)\n    return J\nend\n\nfunction grad_cost(\u03b8,y,F)\n    dJdx = compute_dJdx(\u03b8,y,F)\n    dJds = compute_dJds(\u03b8,y,F)\n    dJdh = compute_dJdh(\u03b8,y,F)\n    dJd\u03b8 = vcat(dJdx,dJds,dJdh)\n\n    return dJd\u03b8\nend\n\nfunction compute_dJdx(\u03b8,y,F)\n    x,s,h = decompose_theta(\u03b8)\n    G = get_gauss_field(\u03b8,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(\u03b8,y,F)\n    x,s,h = decompose_theta(\u03b8)\n    G = get_gauss_field(\u03b8,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(\u03b8,y,F)\n    x,s,h = decompose_theta(\u03b8)\n    G = get_gauss_field(\u03b8,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(\u03b8,y,F)\n    n_temp = length(\u03b8)\n    N = Int((n_temp-1)/2)\n\n    \u0394x = 0.01*(maximum(y) -minimum(y))\n    \u0394s = 0.01*maximum(F)\n    \u0394h = \u0394x\n    dJdx = zeros(N)\n    dJds = zeros(N)\n    dJdh = 0.0\n    \n    # compute dJdx\n    for ti=1:N\n        \u03b8temp = copy(\u03b8)\n        \u03b8temp[ti] = \u03b8temp[ti] + \u0394x\n        J1 = cost(\u03b8temp,y,F)\n        J0 = cost(\u03b8,y,F)\n        dJdx[ti] = (J1 - J0)/\u0394x\n    end\n\n    # compute dJds\n    for ti=1:N\n        \u03b8temp = copy(\u03b8)\n        \u03b8temp[ti+N] = \u03b8temp[ti+N] + \u0394s\n        J1 = cost(\u03b8temp,y,F)\n        J0 = cost(\u03b8,y,F)\n        dJds[ti] = (J1 - J0)/\u0394s\n    end\n\n    # compute dJdh\n    \u03b8temp = copy(\u03b8)\n    \u03b8temp[2N+1] = \u03b8temp[2N+1] + \u0394h\n    J1 = cost(\u03b8temp,y,F)\n    J0 = cost(\u03b8,y,F)\n    dJdh = (J1 - J0)/\u0394h\n\n    dJd\u03b8 = vcat(dJdx,dJds,dJdh)\n    return dJd\u03b8\nend\n\nfunction plot_fields(\u03b8,y,F;iter=-1)\n    x,s,h = decompose_theta(\u03b8)\n\n    G = get_gauss_field(\u03b8,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(\u03b8,y)\n    # decompose theta\n    x,s,h = decompose_theta(\u03b8)\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    \u03b5 = 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,\u03b5,x,y,s,W)\n    return G\nend\n\nfunction gradient_descent_step!(\u03b8,\u2207f,\u03b1)\n    N = length(\u03b8)\n    for ti=1:N\n        \u03b8[ti] -= \u03b1*\u2207f[ti]\n    end\n    nothing\nend\n\nfunction gradient_descent(\u03b80,y,F;NiterMAX=100,TOL=1e-10,pause=false)\n    error = 100.0\n    \u03b1 = 0.2\n\n    iter = 1\n    \u03b8 = \u03b80\n    Jtemp = 100.0\n    while iter<NiterMAX && error > TOL\n        println(\"\\riteration \",iter,\"          \")        \n        plot_fields(\u03b8,y,F;iter=iter)\n\n        J = cost(\u03b8,y,F)\n        error = abs(J - Jtemp)\n\n        #\u2207J = grad_cost_FD(\u03b8,y,F)\n        \u2207J = grad_cost(\u03b8,y,F)\n        \n        gradient_descent_step!(\u03b8,\u2207J,\u03b1)\n                \n        if pause; readline(); end\n\n        Jtemp = J\n\n        iter += 1\n    end\n\n    return \u03b8\nend\n\nfunction compose_theta(x,s,h)\n    N = length(x)\n    \u03b8 = zeros(2N+1)\n    for ti=1:N\n        \u03b8[ti] = x[ti]\n        \u03b8[ti+N] = s[ti]\n    end\n    \u03b8[2N+1] = h\n    return \u03b8\nend\n\nfunction decompose_theta(\u03b8)\n    n_temp = length(\u03b8)\n    N = Int((n_temp-1)/2)\n    x = zeros(N)\n    s = zeros(N)\n    for ti=1:N\n        x[ti] = \u03b8[ti]\n        s[ti] = \u03b8[ti+N]\n    end\n    h = \u03b8[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    \u03c3old = 1\n    \u03c3new = 1\n    while (norm(sqrt(\u03c3old)-sqrt(\u03c3new))/norm(sqrt(\u03c3old)) > tol || i < itermin) && i < itmax\n        \u03c3old = \u03c3new\n        w = mat*v\n        x = adjoint(mat)*w\n        \u03c3new = norm(x)\n        v = x/norm(x)\n        i += 1\n    end\n    return sqrt(\u03c3new)\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    \u03c3old = 1\n    \u03c3new = 1\n    while norm(sqrt(\u03c3old)-sqrt(\u03c3new))/norm(sqrt(\u03c3old)) > tol || i < itermin\n        \u03c3old = \u03c3new\n        w = hmat*v - refmat*v\n        x = adjoint(hmat)*w - adjoint(refmat)*w\n        \u03c3new = 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(\u03c3new)/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": "@testset \"Statistics\" begin\n  # half sample mode\n  d = LogNormal(0,1)\n  rs = rand(d,1000)\n  @test GeoStatsBase.hsm_mode([1,2,2,3]) == 2.0\n  @test GeoStatsBase.hsm_mode([1,2,2,3,5]) == 2.0\n  @test GeoStatsBase.hsm_mode(rs) < mean(rs)\n  @test GeoStatsBase.hsm_mode(rs) < median(rs)\n  d = MixtureModel([Normal(), Normal(3, 0.2)], [0.7, 0.3])\n  rs = rand(d, 1000)\n  @test GeoStatsBase.hsm_mode(rs) < mean(rs)\n  @test GeoStatsBase.hsm_mode(rs) < median(rs)\n\n  # load data with bias towards large values (gold mine)\n  sdata = georef(CSV.File(joinpath(datadir,\"clustered.csv\")), (:x,:y))\n\n  # spatial mean\n  \u03bcn = mean(sdata[:Au])\n  \u03bcs = mean(sdata, :Au)\n  @test abs(\u03bcn - 0.5) > abs(\u03bcs - 0.5)\n  @test mean(sdata)[:Au] \u2248 \u03bcs\n\n  # spatial variance\n  \u03c3n = var(sdata[:Au])\n  \u03c3s = var(sdata, :Au)\n  @test isapprox(\u03c3n, \u03c3s, atol=1e-2)\n  @test var(sdata)[:Au] \u2248 \u03c3s\n\n  # spatial quantile\n  qn = quantile(sdata[:Au], 0.5)\n  qs = quantile(sdata, :Au, 0.5)\n  @test qn \u2265 qs\n  @test quantile(sdata, 0.5)[:Au] \u2248 qs\nend\n", "meta": {"hexsha": "33f66f12dae724eaea0f3dc8f0ae003a433aa445", "size": 995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/statistics.jl", "max_stars_repo_name": "juliohm/GeoStatsBase.jl", "max_stars_repo_head_hexsha": "e288b0d864d29f9eea93fb55a1f34b910411b236", "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": "test/statistics.jl", "max_issues_repo_name": "juliohm/GeoStatsBase.jl", "max_issues_repo_head_hexsha": "e288b0d864d29f9eea93fb55a1f34b910411b236", "max_issues_repo_licenses": ["ISC"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-11-19T12:28:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-29T14:42:37.000Z", "max_forks_repo_path": "test/statistics.jl", "max_forks_repo_name": "juliohm/GeoStatsBase.jl", "max_forks_repo_head_hexsha": "e288b0d864d29f9eea93fb55a1f34b910411b236", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-09-03T10:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-03T19:06:12.000Z", "avg_line_length": 28.4285714286, "max_line_length": 70, "alphanum_fraction": 0.624120603, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.751148396357168}}
{"text": "using FuzzySets, Test\n\nstep_size = 0.005\nlevels = collect(0:step_size:1)\n\nA = TriangularFuzzyNumber(levels; number=0.0, width=0.5)\n@test A.levels == levels\n@test A.grades[1] == Interval(-0.5, 0.5)\n@test A[1] == Interval(-0.5, 0.5)\n@test support(A) == Interval(-0.5, 0.5)\n@test core(A) == Interval(0) == Interval(0.0)\n@test height(A) == 1.0\n@test A(-0.2) == 0.6\n@test A(0) == 1.0\n@test A(0.2) == 0.6\n@test A(0.5) == 0.0\n@test A(1) == 0.0\n@test length(A) == 201\n@test round(centroid(A, step=0.01), digits=2) \u2248 0.0\n\nB = TriangularFuzzyNumber(levels, number=5.0, width=0.5)\n@test B.levels == levels\n@test support(B) == Interval(4.5, 5.5)\n@test core(B) == Interval(5.0)\n@test height(B) == 1\n\nC = TriangularFuzzyNumber(levels, number=5.0, width=0.5)\n@test B == C\n@test A != C\n\nD = SingletonFuzzyNumber(levels, number=0)\n@test support(D) == Interval(0)\n@test D.grades == repeat([Interval(0)], length(levels)) # TODO: check with all(...)\n\nA = TriangularFuzzyNumber(levels, number=1, width=0.5)\nFuzzySets.vertical_cut!(A, \u03b1=0.2)\n@test A.grades[1] == A.grades[41]\n@test A.grades[2] == A.grades[41]\n@test A.grades[40] == A.grades[41]\nB = FuzzySets.vertical_cut(A, \u03b1=0.2)\n@test B.grades[1] == B.grades[41]\n@test B.grades[2] == B.grades[41]\n@test B.grades[40] == B.grades[41]\n\nA = SingletonFuzzyNumber(levels, number=5)\nB = TriangularFuzzyNumber(levels, number=5)\n@test FuzzySets.isSingleton(A) == true\n@test FuzzySets.isSingleton(B) == false\n\np = 6\nw_l = 2\nw_r = 2\na = 2\n@test FuzzySets.trapezoid(0; p, w_l, w_r, a) == Interval(2, 10)\n@test FuzzySets.trapezoid(0.5; p, w_l, w_r, a) == Interval(3, 9)\n@test FuzzySets.trapezoid(1.0; p, w_l, w_r, a) == Interval(4, 8)\n@test_throws ErrorException FuzzySets.trapezoid(1.5; p, w_l, w_r, a)\nA = TrapezoidalFuzzyNumber(levels; number=p, w_l, w_r, a)\n@test A.grades[1] == Interval(2, 10)\n@test A.grades[101] == Interval(3, 9)\n@test A.grades[end] == Interval(4, 8)\n@test round(centroid(A, step=0.01), digits=2) \u2248 p\n\n\u03bc = 0\n\u03c3 = 1\nA = GaussianFuzzyNumber(levels; \u03bc=\u03bc, \u03c3=\u03c3)\n@test A.grades[1] == A.grades[2]\n@test A.grades[1].left == -A.grades[1].right\n@test A.grades[101].left == -A.grades[101].right\n@test A.levels[101] == 0.5\n@test A.grades[101] == Interval(-1.1774100225154747, 1.1774100225154747)\n@test A.grades[end] == Interval(\u03bc)\n\n# Specificity\nA = TriangularFuzzyNumber(levels, number=0.5, width=0.5)\n@test FuzzySets.specificity(A) == 0.5\n@test FuzzySets.u_uncertainty(A) == 1\n\nB = TriangularFuzzyNumber(levels, number=0.5, width=0.2)\n@test FuzzySets.specificity(B) \u2248 0.8\n\nC = TriangularFuzzyNumber(levels, number=8.0, width=1.0)\n@test FuzzySets.specificity(C) \u2248 0.8\n\nS = SingletonFuzzyNumber(levels, number=4.0)\n@test FuzzySets.specificity(S) \u2248 1.0\n@test FuzzySets.u_uncertainty(S) \u2248 0\n\nstep_size = 0.0001\nlevels = collect(0:step_size:1)\n\na = 0\nb = 5\nBoxFuzzyNumber = FuzzySets.BoxFuzzyNumber(levels, a=a, b=b)\nw = b - a\n@test round(FuzzySets.u_uncertainty(BoxFuzzyNumber), digits=3) \u2248 round(log(1+w), digits=3)\n\nA1 = TriangularFuzzyNumber(levels, number=2, width=2.0)\n@test round(FuzzySets.u_uncertainty(A1), digits=3) \u2248 1.012\n\nA2 = TriangularFuzzyNumber(levels, number=2, width=1.0)\n@test round(FuzzySets.u_uncertainty(A2), digits=3) \u2248 0.648\n\n# A3 = TriangularFuzzyNumber(levels, number=2, width=2.0)\n# middle = Int((length(A3.levels) + 1)/2)\n# A3.grades[1:middle] = A3.grades[middle:end]\n# for i = middle+1:length(A3.levels)\n#     A3.grades[i] = Interval(NaN)\n# end\n# @test round(FuzzySets.u_uncertainty(A3) * 2, digits=3) \u2248 0.648\n\nA4 = TriangularFuzzyNumber(levels, number=2, width=0.5)\n@test round(FuzzySets.u_uncertainty(A4), digits=3) \u2248 0.386 # not sure", "meta": {"hexsha": "87f76d9bcf88029c9ec431780a227df53fcae339", "size": 3592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FuzzyNumbers.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": "test/FuzzyNumbers.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": "test/FuzzyNumbers.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": 31.7876106195, "max_line_length": 90, "alphanum_fraction": 0.6823496659, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7511483946657737}}
{"text": "fejer_plan1(\u03bc) = FFTW.plan_r2r!(\u03bc, FFTW.REDFT01)\nfejer_plan2(\u03bc) = FFTW.plan_r2r!(\u03bc, FFTW.RODFT00)\n\n\"\"\"\nCompute nodes and weights of Fejer's first quadrature rule with a Jacobi weight.\n\"\"\"\nfejer1{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T) = fejer1(N,\u03b1,\u03b2,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,\u03b1::T,\u03b2::T) = fejer2(N,\u03b1,\u03b2,fejer_plan2(zeros(T,N)))\n\nfejer1{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T,plan) = T[sinpi((N-2k-one(T))/2N) for k=0:N-1],fejerweights1(N,\u03b1,\u03b2,plan)\nfejer2{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T,plan) = T[cospi((k+one(T))/(N+one(T))) for k=0:N-1],fejerweights2(N,\u03b1,\u03b2,plan)\n\n\n\"\"\"\nCompute weights of Fejer's first quadrature rule with a Jacobi weight.\n\"\"\"\nfejerweights1{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T) = fejerweights1(N,\u03b1,\u03b2,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,\u03b1::T,\u03b2::T) = fejerweights2(N,\u03b1,\u03b2,fejer_plan2(zeros(T,N)))\n\nfunction fejerweights1{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T,plan)\n    \u03bc = chebyshevjacobimoments1(N,\u03b1,\u03b2)\n    scale!(\u03bc,inv(T(N)))\n    return plan*\u03bc\nend\n\nfunction fejerweights2{T<:AbstractFloat}(N::Int,\u03b1::T,\u03b2::T,plan)\n    \u03bc = chebyshevjacobimoments2(N,\u03b1,\u03b2)\n    Np1 = N+one(T)\n    scale!(\u03bc,inv(Np1))\n    plan*\u03bc\n    @inbounds for i=1:N \u03bc[i] = sinpi(i/Np1)*\u03bc[i] end\n    return \u03bc\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, \u03c0\u209a::AbstractVector)\n    s = Vector{Int}(undef, n)\n    sampleMarkovChain!(s, n, P, \u03c0\u209a)\nend\n\nfunction sampleMarkovChain!(s, n::Int, P::AbstractMatrix, \u03c0\u209a::AbstractVector)\n    s[1] = rand(Categorical(\u03c0\u209a))\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": "n = rand(1:10)\n\nA = rand(n,n)\n\nr = polarfact(A, alg =:hybrid);\n\n\n# Test unitary matrix U\n\nU = r.U\nH = r.H\n\n@test_approx_eq_eps U'*U eye(n) 1e-7\n\n# Test Hermitian positive semifefinite matrix H\n\n@test issym(H)\n \nfor i in eigvals(H)\n    @test i >= 0.\nend\n\n@test_approx_eq_eps A U*H 1e-7\n\nprintln(\"Hybrid method passed test...\")\n", "meta": {"hexsha": "c1b3386a5ff2f172a13144f0a60b5cf3bf503ba4", "size": 326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_hybrid.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_stars_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_stars_repo_licenses": ["MIT"], "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_hybrid.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_issues_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_issues_repo_licenses": ["MIT"], "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_hybrid.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PolarFact.jl-bbb2afaa-4236-5b45-a0c2-54a75cfbee5c", "max_forks_repo_head_hexsha": "08358827492d4135568250c6045b442cd5cad3b2", "max_forks_repo_licenses": ["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.5384615385, "max_line_length": 47, "alphanum_fraction": 0.6503067485, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.75111216888821}}
{"text": "\ufeffM(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    \u29b8(d\u2081, d\u2082[, d\u209b...])\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\u2082,a\u2084,a\u2081,a\u2083\" \u29b8 \r\n       ranking\"a\u2081,a\u2083\u223ca\u2084,a\u2082\" \u29b8\r\n       ranking\"a\u2082\u223ca\u2083,a\u2084,a\u2081\" \u29b8 \r\n       ranking\"a\u2083,a\u2082,a\u2081\u223ca\u2084\"\r\n4\u00d74 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> \u29b8(ranking\"123\",ranking\"231\",ranking\"312\")\r\n3\u00d73 Array{Int64,2}:\r\n  0  -1   1\r\n  1   0  -1\r\n -1   1   0\r\n```\r\n\"\"\"\r\nfunction  \u29b8(d\u2081::Dict{String,Int}, d\u2082::Dict{String,Int}, d\u209b::Dict{String,Int}...)\r\n    @assert length(d\u2081) == length(d\u2082)\r\n    @assert sort([keys(d\u2081)...]) == sort([keys(d\u2082)...])\r\n    R =  -M(preference(d\u2081))-M(preference(d\u2082))\r\n    for d \u2208 d\u209b \r\n        @assert size(R)[1] == size(R)[2] == length(d)\r\n        @assert sort([keys(d\u2081)...]) == sort([keys(d)...])\r\n        R = \u29b8(R, d)\r\n    end\r\n    return R\r\nend\r\n\r\n\u29b8(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": "using PoissonBox\nusing Test\nusing IterativeSolvers\nimport PoissonBox as PB\nusing Random: MersenneTwister\n\n\n@testset \"laplace eqn operator\" begin\n    forward = PoissonBox.forward\n    @testset \"1d\" begin\n        @test forward(1:5) \u2248 [1,0,0,0,5]\n        @test forward([0,0,1,0,0]) \u2248 [0,0.5,-1,0.5,0]\n    end\n    @testset \"2d\" begin\n        @test forward(\n            [0 0 0 0 0\n                 0 0 0 0 0\n                 0 0 1 0 0\n                 0 0 0 0 0 \n                 0 0 0 0 0 \n                ]) \u2248 [\n                 0 0    0    0    0\n                 0 0    0.25 0    0\n                 0 0.25 -1   0.25 0\n                 0 0    0.25 0    0 \n                 0 0    0    0    0 \n                ]\n    end\n    @testset \"3d\" begin\n        arr = fill(0, (5,5,5))\n        arr[3,3,3] = 1\n        expected = fill(0.0,(5,5,5))\n        expected[3,3,3] = -1\n        expected[2,3,3] = 1/6\n        expected[4,3,3] = 1/6\n        expected[3,2,3] = 1/6\n        expected[3,4,3] = 1/6\n        expected[3,3,2] = 1/6\n        expected[3,3,4] = 1/6\n        @test forward(arr) \u2248 expected\n    end\n    @testset \"3d bdry\" begin\n        arr = randn(3,4,5)\n        out = forward(arr)\n        expected = copy(arr)\n        expected[2:2, 2:3, 2:4] .= 0\n        out[2:2, 2:3, 2:4] .= 0\n        @test expected \u2248 out\n    end\nend\n\n@testset \"solve\" begin\n    solve = PoissonBox.solve\n    y = Float64[1, 0, 0, 0, 5]\n    @test solve(y) \u2248 1:5\n    for shape in [(5,),\n                  (4,3),\n                  (5,4),\n                  (4,3,4),\n                 ]\n        y = rand(MersenneTwister(0), shape...)\n        x = solve(y)\n        @test PB.forward(x) \u2248 y rtol=1e-3\n    end\nend\n\n@testset \"solve low level\" begin\n    op, v = PB.poisson_problem([1, 0, 0, 0, 5])\n    sol = bicgstabl(op, v, 2)\n    u = PB.reshape_solution(op, sol)\n    @test u \u2248 1:5\nend\n", "meta": {"hexsha": "66de5933d4c05dd13f702192945e740cb55b9f00", "size": 1830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "jw3126/PoissonBox.jl", "max_stars_repo_head_hexsha": "f63a941909afa4ef054d68dcd38cebb3eddb9500", "max_stars_repo_licenses": ["MIT"], "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": "jw3126/PoissonBox.jl", "max_issues_repo_head_hexsha": "f63a941909afa4ef054d68dcd38cebb3eddb9500", "max_issues_repo_licenses": ["MIT"], "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": "jw3126/PoissonBox.jl", "max_forks_repo_head_hexsha": "f63a941909afa4ef054d68dcd38cebb3eddb9500", "max_forks_repo_licenses": ["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.0684931507, "max_line_length": 53, "alphanum_fraction": 0.4355191257, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7511121633925364}}
{"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    \u03bc = mean(X, dims=1)\n    \u03c3 = std(X, dims=1)\n\n    X_norm = (X .- \u03bc) ./ \u03c3\n\n    return (X_norm, \u03bc, \u03c3)\nend\n\n\n\"\"\"\n    transform_features(X, \u03bc, \u03c3)\n\nThis functions uses the mean and standard deviation values users pass to\nnormalise a new design matrix.\n\"\"\"\nfunction transform_features(X, \u03bc, \u03c3)\n    X_norm = (X .- \u03bc) ./ \u03c3\n    return X_norm\nend\n\n# Scale training features and get artificats for future use\nX_train_scaled, \u03bc, \u03c3 = scale_features(X_train)\n\n# Transform the testing features by using the learned artifacts\nX_test_scaled = transform_features(X_test, \u03bc, \u03c3)\n\n\n\"\"\"\n    mean_squared_cost(X, y, \u03b8)\n\nThis function computes the batch cost based on the values of the design matrix (X),\ntarget vector (y), and the weights (\u03b8) passed to it.\n\"\"\"\nfunction mean_squared_cost(X, y, \u03b8)\n    # Sample size\n    m = size(X)[1]\n\n    # Vectorised Prediction loss\n    preds = X * \u03b8\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, \u03b1, fit_intercept=true, n_iter=1000)\n\nThis function uses gradient descent algorithm to find the best weights (\u03b8)\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 (\u03b8)\nand a history of loss at each iteration (\ud835\udc09) is returned.\n\"\"\"\nfunction lin_reg_grad_descent(X, y, \u03b1, 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 \u03b8 vector\n    n = size(X)[2]\n    \u03b8 = zeros(n)\n\n    # Initialise the cost vector based on the number of iterations\n    \ud835\udc09 = zeros(n_iter)\n\n    for iter in range(1, stop=n_iter)\n        pred = X * \u03b8\n\n        # Calcaluate the cost for each iter\n        \ud835\udc09[iter] = mean_squared_cost(X, y, \u03b8)\n\n        # Update the theta \u03b8 at each iter\n        \u03b8 = \u03b8 - ((\u03b1/m) * X') * (pred - y);\n    end\n    return (\u03b8, \ud835\udc09)\nend\n\n\n\u03b8, \ud835\udc09 = lin_reg_grad_descent(X_train_scaled, y_train, 0.05, true, 3000)\n\nplot(\ud835\udc09,\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, \u03b8, fit_intercept=true)\n\nThis function uses the learned weights (\u03b8) 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, \u03b8, 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 * \u03b8\n\n    return predictions\nend\n\n\n# Make predictions for both training and testing datasets\ntrain_preds = predict(X_train_scaled, \u03b8)\ntest_preds = predict(X_test_scaled, \u03b8)\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\u00b2 = errors .^ 2\n    mse = mean(errors\u00b2)\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    \u2211 = sum\n    \u03bc = mean\n\n    # Compute sum of explained variance (SST) and sum of squares of residuals\n    sst = \u2211(((y_true .- \u03bc(y_true)) .^ 2))\n    ssr = \u2211(((y_pred .- y_true) .^ 2))\n\n    r\u00b2 = 1 - (ssr / sst)\n\n    return r\u00b2\nend\n\n\n# Get the r-squared score for training and test datasets\ntrain_r\u00b2 = r_squared_score(train_preds, y_train)\ntest_r\u00b2 = r_squared_score(test_preds, y_test)\n\n\nprintln(\"Training R\u00b2 score for test sets: \", train_r\u00b2)\nprintln(\"Testing R\u00b2 score for test sets: \", test_r\u00b2)\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, \u03b2; kwargs)\n\nSimulate SI spreading on network `g` using the Gillespie algorithm.\n\n`g` is an `AbstractSimpleGraph{<:Integer}`, `\u03b2` 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, \u03b2::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] = \u03b2*l# probability of k recieving infection is \u03b2 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*\u03b2\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        \u03c4 = log(1/rand())/a0\n        k = rand_categorical(a, a0) # which node gets infected\n        X[k] = true\n        #nreactions -= Int(floor(a[k]/\u03b2))\n        a[k] = 0.0\n        for i in Iterators.filter(j->!X[j],outneighbors(g,k))\n            a[i] += \u03b2\n            #nreactions += 1\n        end\n        if sampling_method == :sparse\n            SparseArrays.dropstored!(a,k) # O(1) cost?\n        end\n        #a0 = \u03b2*nreactions\n        a0 = sum(a)\n        t += \u03c4\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, \u03b2; 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. `\u03b2` 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, \u03b2::Real; tmax=100.0, saveat=[])\n    A = adjacency_matrix(g)\n    u0 = float(Xi)\n    f! = function(du,u,p,t)\n        du .= \u03b2*(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, \u03b2; 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, \u03b2::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, \u03b2, 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            \u0394n = Xn - X_sum[k]/(n>1 ? n-1 : 1)\n            X_sum[k] += Xn\n            M_sum[k] += \u0394n*(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 \u00b11.\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, \u03b2, 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 \u00d7 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 \u00b7 r I - r \u00b7 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(\u03c8_dot, \u03b1, \u03b2, tas, \u03b3[, g])\n\nCalculate roll angle (\u03d5) [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- `\u03c8_dot`: turn rate (rad/s).\n- `\u03b1`: angle of attack (rad).\n- `\u03b2`: angle of sideslip (rad).\n- `tas`: true air speed (m/s).\n- `\u03b3`: flight path angle (rad).\n- `g`: gravity (m/s\u00b2). Optional. Default value is `gD`.\n\"\"\"\nfunction coordinated_turn_bank(\u03c8_dot, \u03b1, \u03b2, tas, \u03b3, g=gD)\n    G = \u03c8_dot * tas / g\n\n    if abs(\u03b3) < 1e-8\n        \u03d5 = G * cos(\u03b2) / (cos(\u03b1) - G * sin(\u03b1) * sin(\u03b2))\n        \u03d5 = atan(\u03d5)\n    else\n        a = 1 - G * tan(\u03b1) * sin(\u03b2)\n        b = sin(\u03b3) / cos(\u03b2)\n        c = 1 + G^2 * cos(\u03b2)^2\n\n        sq = sqrt(c * (1 - b^2) + G^2 * sin(\u03b2)^2)\n\n        num = (a - b^2) + b * tan(\u03b1) * sq\n        den = a ^ 2 - b^2 * (1 + c * tan(\u03b1)^2)\n\n        \u03d5 = atan(G * cos(\u03b2) / cos(\u03b1) * num / den)\n    end\n    return \u03d5\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": "# @testset \"Savitzky-Golay definition\" begin\n#     sg=SavitzkyGolay_Filter(rand(11))\n#     @test offset(sg) == 5\n#     @test range(sg) == -5:5\n#     @test length(sg) == 11\n# end\n\n@testset \"Savitzky-Golay\" begin\n\n    m=SG_Filter(Float64,halfWidth=2,degree=0)\n\n    @test filter(m,derivativeOrder=0) \u2248 [1/5; 1/5; 1/5; 1/5; 1/5]\n\n    m=SG_Filter(Float64,halfWidth=3,degree=2)\n\n    @test filter(m,derivativeOrder=1) \u2248 [-(3/28); -(1/14); -(1/28); 0;  (1/28); (1/14); (3/28)]\n    @test filter(m,derivativeOrder=2) \u2248 [5/42; 0; -(1/14); -(2/21); -(1/14); 0; 5/42]\n\n    @test maxDerivativeOrder(m) == 2\n    @test length(m) == 2*3+1\n    @test polynomialOrder(m) == 2\nend\n", "meta": {"hexsha": "fef1a66853014c1446fa68d17c4eabb63f861dce", "size": 660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SG_Filter.jl", "max_stars_repo_name": "vincent-picaud/DirectConvolution", "max_stars_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-04-20T20:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T12:33:45.000Z", "max_issues_repo_path": "test/SG_Filter.jl", "max_issues_repo_name": "vincent-picaud/DirectConvolution", "max_issues_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-11T04:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-17T09:58:07.000Z", "max_forks_repo_path": "test/SG_Filter.jl", "max_forks_repo_name": "vincent-picaud/DirectConvolution", "max_forks_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-01T03:11:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:27:26.000Z", "avg_line_length": 28.6956521739, "max_line_length": 95, "alphanum_fraction": 0.5878787879, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7510503231476676}}
{"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": "include(\"getdigit_n.jl\")\ninclude(\"myprintf.jl\")\nusing Printf\nusing .GetDigit_n\nusing .MyPrintf\n\nconst DIGIT = 5\nconst MAXN = 500000\n\nfunction wallis(n)\n    res = BigFloat(1)\n    for i = 1:div(n, 2)\n        res *= BigFloat(4) * BigFloat(i * i) / (BigFloat(4) * BigFloat(i * i) - BigFloat(1))\n    end\n\n    return BigFloat(2) * res\nend\n\nfunction main()\n    n = GetDigit_n.getn_even(wallis, MAXN, DIGIT, true)\n    precision = GetDigit_n.getdigit(wallis, n, DIGIT, true)\n    precision = GetDigit_n.getdigit_2(wallis, n, DIGIT, precision)\n\n    setprecision(precision)\n    MyPrintf.myprintf(\"\u03c0\uff08\u8a08\u7b97\u5024\uff09 = \", DIGIT, wallis(n))\n    MyPrintf.myprintf(\"\u03c0\uff08\u53b3\u5bc6\u5024\uff09 = \", DIGIT, BigFloat(\u03c0))\n    @printf(\"n = %d, \u8a08\u7b97%d\u6841\u3067\u3001%d\u6841\u6c42\u307e\u308a\u307e\u3057\u305f\\n\", n, precision, DIGIT)\nend\n\nmain()\n", "meta": {"hexsha": "001e65964ee1e96828bdfa908eb30c837d52223e", "size": 745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "wallis.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": "wallis.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": "wallis.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": 24.0322580645, "max_line_length": 92, "alphanum_fraction": 0.6536912752, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7510503199889906}}
{"text": "## this generates data from the simple supply-demand model\n#  q = \u03b11 + \u03b12*p + \u03b13*m + e1\n#  q = \u03b21 + \u03b22*p +        e2\n## setup\nusing Econometrics, Plots, DelimitedFiles\n# number of obsn\nn = 500\n# model parameters\n\u03b11 = 100.0\n\u03b12 = -1.0\n\u03b13 = 1.0\n\u03b21 = 20.0\n\u03b22 = 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\u03f51 = 1.0*randn(n)\n\u03f52 = 1.0*randn(n)\n# rf shocks\n\u03bd1 = (\u03b22*\u03f51-\u03b12*\u03f52)/(\u03b22-\u03b12)\n\u03bd2 = (\u03f51-\u03f52)/(\u03b22-\u03b12)\n# rf coefs\n\u03c011 = (\u03b22*\u03b11-\u03b12*\u03b21)/(\u03b22-\u03b12)\n\u03c021 = \u03b22*\u03b13/(\u03b22-\u03b12)\n\u03c012 = (\u03b11-\u03b21)/(\u03b22-\u03b12)\n\u03c022 = \u03b13/(\u03b22-\u03b12)\n\n##  generate endog variables computed from rf\nq = \u03c011 .+ \u03c021*m + \u03bd1\np = \u03c012 .+ \u03c022*m + \u03bd2\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": "# transmcp.jl\n# translated by Changhyun Kwon from transmcp.gms\n# http://www.gams.com/modlib/libhtml/transmcp.htm\n#\n# Transportation model as equilibrium problem (TRANSMCP,SEQ=126)\n#\n#    Dantzig's original transportation model (TRNSPORT) is\n#    reformulated as a linear complementarity problem.  We first\n#    solve the model with fixed demand and supply quantities, and\n#    then we incorporate price-responsiveness on both sides of the\n#    market.\n#\n#\n# Dantzig, G B, Chapter 3.3. In Linear Programming and Extensions.\n# Princeton University Press, Princeton, New Jersey, 1963.\n\nusing Complementarity\nusing Test\n\n@testset \"transmcp_numeric.jl 1\" begin\n\n    # plants = [\"seattle\", \"san-diego\"]\n    plants = 1:2\n    # markets = [\"new-york\", \"chicago\", \"topeka\"]\n    markets = 1:3\n\n    capacity = [350, 600]\n    a = Dict(zip(plants, capacity))\n\n    demand = [325, 300, 275]\n    b = Dict(zip(markets, demand))\n\n    elasticity = [1.5, 1.2, 2.0]\n    esub = Dict(zip(markets, elasticity))\n\n    distance = [ 2.5 1.7 1.8 ;\n                 2.5 1.8 1.4  ]\n    d = Dict()\n    for i in 1:length(plants), j in 1:length(markets)\n        d[plants[i], markets[j]] = distance[i,j]\n    end\n\n    f = 90\n\n    m = MCPModel()\n    @variable(m, w[i in plants] >= 0)\n    @variable(m, p[j in markets] >= 0)\n    @variable(m, x[i in plants, j in markets] >= 0)\n\n    @NLexpression(m, c[i in plants, j in markets], f * d[i,j] / 1000)\n    @mapping(m, profit[i in plants, j in markets],    w[i] + c[i,j] - p[j])\n    @mapping(m, supply[i in plants],                  a[i] - sum(x[i,j] for j in markets))\n    @mapping(m, fxdemand[j in markets],               sum(x[i,j] for i in plants) - b[j])\n\n    @complementarity(m, profit, x)\n    @complementarity(m, supply, w)\n    @complementarity(m, fxdemand, p)\n\n    status = solveMCP(m; convergence_tolerance=1e-8, output=\"yes\", time_limit=3600)\n\n    @show result_value.(x)\n    @show result_value.(w)\n    @show result_value.(p)\n\n    @show status\n    @test status == :Solved\n    @test isapprox(result_value(x[1,2]), 300.0)\n    @test isapprox(result_value(p[3]),  0.126)\n\nend\n\n\n\n@testset \"transmcp_numeric.jl 2\" begin\n\n    # plants = [\"seattle\", \"san-diego\"]\n    plants = 1:2\n    # markets = [\"new-york\", \"chicago\", \"topeka\"]\n    markets = 1:3\n\n    capacity = [350, 600]\n    a = Dict(zip(plants, capacity))\n\n    demand = [325, 300, 275]\n    b = Dict(zip(markets, demand))\n\n    elasticity = [1.5, 1.2, 2.0]\n    esub = Dict(zip(markets, elasticity))\n\n    distance = [ 2.5 1.7 1.8 ;\n                 2.5 1.8 1.4  ]\n    d = Dict()\n    for i in 1:length(plants), j in 1:length(markets)\n        d[plants[i], markets[j]] = distance[i,j]\n    end\n\n    f = 90\n\n    m = MCPModel()\n    @variable(m, w[1:2] >= 0)\n    @variable(m, p[1:3] >= 0)\n    @variable(m, x[1:2, 1:3] >= 0)\n\n    @NLexpression(m, c[i in 1:2, j in 1:3], f * d[i,j] / 1000)\n    @mapping(m, profit[i in 1:2, j in 1:3], w[i] + c[i,j] - p[j])\n    @mapping(m, supply[i in 1:2], a[i] - sum(x[i,j] for j in markets))\n    @mapping(m, fxdemand[j in 1:3], sum(x[i,j] for i in plants) - b[j])\n\n    @complementarity(m, profit, x)\n    @complementarity(m, supply, w)\n    @complementarity(m, fxdemand, p)\n\n    status = solveMCP(m; convergence_tolerance=1e-8, output=\"yes\", time_limit=3600)\n\n\n    @show result_value.(x)\n    @show result_value.(w)\n    @show result_value.(p)\n\n    @show status\n    @test status == :Solved\n    @test isapprox(result_value(x[1,2]), 300.0)\n    @test isapprox(result_value(p[3]),  0.126)\n\nend\n", "meta": {"hexsha": "3ac4eba55a83e9e9917769929319f1ee9af1e5ae", "size": 3470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/transmcp_numeric.jl", "max_stars_repo_name": "davidanthoff/Complementarity.jl", "max_stars_repo_head_hexsha": "dcaa38ef54787f7488d6cb5da202f5af63931de8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2016-06-10T11:28:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:42:15.000Z", "max_issues_repo_path": "test/transmcp_numeric.jl", "max_issues_repo_name": "davidanthoff/Complementarity.jl", "max_issues_repo_head_hexsha": "dcaa38ef54787f7488d6cb5da202f5af63931de8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2016-04-28T19:47:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T11:26:12.000Z", "max_forks_repo_path": "test/transmcp_numeric.jl", "max_forks_repo_name": "davidanthoff/Complementarity.jl", "max_forks_repo_head_hexsha": "dcaa38ef54787f7488d6cb5da202f5af63931de8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:12:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T11:47:38.000Z", "avg_line_length": 27.5396825397, "max_line_length": 90, "alphanum_fraction": 0.5971181556, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7510503152509747}}
{"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, \u03f5 = 1f-5)\n\n\t\tSplits x horizontally into two equal parts and use softplus to the lower part.\n\t\t\u03f5 is added to the soft-plus to prevent underflow and improve the numerical stability\n\n\"\"\"\nhsplitsoftp(x,\u03f5 = 1f-5) = x[1:size(x, 1) \u00f7 2, :], softplus.(x[size(x, 1) \u00f7 2 + 1 : 2 * (size(x, 1) \u00f7 2), :] .+ \u03f5)\nhsplit1softp(x,\u03f5 = 1f-5) = x[1:size(x, 1) - 1, :], softplus.(x[end, :] .+ \u03f5)\n\n\"\"\"\n\t\tkldiv(\u03bc,\u03c32)\n\n\t\tkl-divergence of a Gaussian min mean `\u03bc` and diagonal variance `\u03c3^2`\n\t\tto N(0,I)\n\"\"\"\nkldiv(\u03bc,\u03c32) = - mean(sum((@.log(\u03c32) - \u03bc^2 - \u03c32), dims = 1))\n\nlog_normal(x) = - sum((x.^2), dims = 1) ./ 2 .- size(x, 1) * log(2f0 * \u03c0) / 2\nlog_normal(x, \u03bc) = log_normal(x - \u03bc)\nlog_normal(x, \u03bc, \u03c32::Vector{T}) where {T<:Number} = - sum((x - \u03bc) .^ 2 ./ \u03c32' .+ log.(\u03c32' .* 2\u03c0), dims = 1) / 2\nlog_normal(x, \u03bc, \u03a3::Matrix{T}) where {T<:Number} = - (log(det(\u03a3)) + (x - \u03bc)' * inv(\u03a3) * (x - \u03bc) + size(\u03a3, 1) * log(2\u03c0)) / 2\n\n\"\"\"\n\tvmfentropy(m, \u03ba)\n\n\tEntropy of Von Mises-Fisher distribution\n\"\"\"\nvmfentropy(m, \u03ba) = .-\u03ba .* besselix(m / 2, \u03ba) ./ besselix(m / 2 - 1, \u03ba) .- ((m ./ 2 .- 1) .* log.(\u03ba) .- (m ./ 2) .* log(2\u03c0) .- (\u03ba .+ log.(besselix(m / 2 - 1, \u03ba))))\n\n\"\"\"\n\thuentropy(m)\n\n\tEntropy of Hyperspherical Uniform distribution\n\"\"\"\nhuentropy(m) = m / 2 * log(\u03c0) + 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, \u03ba) = \u03ba ^ (p / 2 - 1) / ((2\u03c0) ^ (p / 2) * besseli(p / 2 - 1, \u03ba))\n\n# log likelihood of one sample under the VMF dist with given parameters\nlog_vmf_c(x, \u03bc, \u03ba) = \u03ba * \u03bc' * x .+ log(c(length(\u03bc), \u03ba))\nlog_vmf_c(x::AbstractMatrix, \u03bc::AbstractMatrix, \u03ba::T) where {T <: Number} = [log_vmf_c(x[:, i], \u03bc[:, i], \u03ba) for i in size(x, 2)] \nlog_vmf_c(x::AbstractMatrix, \u03bc::AbstractMatrix, \u03ba::AbstractVector) = [log_vmf_c(x[:, i], \u03bc[:, i], \u03ba[i]) for i in size(x, 2)] \nlog_vmf_wo_c(x, \u03bc, \u03ba) = \u03ba * \u03bc' * 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(\u03bc, \u03c32)\n\t\u03f5 = randn!(similar(\u03bc,size(\u03bc)))\n\t\u03bc .+ sqrt.(\u03c32) .* \u03f5\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": "using Distributions\nusing JuliaWebAPI\nusing Logging\nLogging.configure(level=DEBUG)\n\nf(u) = exp(-u^2/2)/\u221a(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::Int)\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\nsimulate(num::String) = simulate(parseint(num))\n\n#process([(simulate,false), (simulateTime,false)], \"tcp://127.0.0.1:9999\"; bind=true)", "meta": {"hexsha": "a200b24fc3c6e7e992f3332b61c5b6a482e906a9", "size": 606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaInXL/resources/sim.jl", "max_stars_repo_name": "JuliaComputing/JuliaInXL", "max_stars_repo_head_hexsha": "018a1f729e9ef95a8086f49046353b3476f761d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-03T08:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T03:24:12.000Z", "max_issues_repo_path": "JuliaInXL/resources/sim.jl", "max_issues_repo_name": "JuliaComputing/JuliaInXL", "max_issues_repo_head_hexsha": "018a1f729e9ef95a8086f49046353b3476f761d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JuliaInXL/resources/sim.jl", "max_forks_repo_name": "JuliaComputing/JuliaInXL", "max_forks_repo_head_hexsha": "018a1f729e9ef95a8086f49046353b3476f761d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-07T23:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T20:13:24.000Z", "avg_line_length": 17.8235294118, "max_line_length": 85, "alphanum_fraction": 0.6336633663, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7510503088069148}}
{"text": "\"\"\"\n    hilbert_transform(signal::Vector{Float64})\n\nCompute the Hilbert transform using the DFT approximation.\n\"\"\"\nfunction hilbert_transform(signal::Vector{Float64})\n    fourier = AbstractFFTs.fft(signal)\n    n = length(fourier)\n    h = zeros(n)\n\n    for i in eachindex(h)\n        if i == 1 || i == (n/2)+1\n            h[i] = 1\n        elseif 2 <= i <= (n/2)\n            h[i] = 2\n        else\n            h[i] == 0\n        end\n    end\n\n    dtft_hilbert = fourier .* h\n    return AbstractFFTs.ifft(dtft_hilbert)\nend\n\n\"\"\"\n    compute_instantaneous(signal::Vector{Float64}, imfs::Array{Float64, 2})\n\nReturn the instantaneous energy and instantaneous frequencies of the IMFS in the signal.\n\"\"\"\nfunction compute_instantaneous(signal::Vector{Float64}, imfs::Matrix{Float64})\n    n = length(signal)\n    analytic_signal = zeros(n)\n    theta = zeros(n)\n    imf_inst_energy = zeros(n, size(imfs, 1))\n    imf_inst_freq = zeros(n, size(imfs, 1))\n    r = zeros(n)\n    time = collect(1:n)\n\n    for j=1:size(imfs, 1)\n        analytic_signal = signal + im*hilbert_transform(imfs[:, j])\n\n        for i in eachindex(analytic_signal)\n            theta[i] = angle(analytic_signal[i])\n            imf_inst_energy[i, j] = abs2(analytic_signal[i])\n        end\n\n        spl = Spline1D(time, theta)\n\n        g = x -> ForwardDiff.gradient(spl, time)\n\n\n        for i in eachindex(analytic_signal)\n            imf_inst_freq[i, j] = g(time[i])\n        end\n    end\n\n    return imf_inst_energy, imf_inst_freq\nend\n\n\"\"\"\n    hht(signal::Vector{Float64}, s::EMDSetting)\n\nReturn the instantaneous energies and frequencies of the IMFS computed via the\nHilbert-Huang transform with EMD settings specified.\n\"\"\"\nfunction hht(signal::Vector{Float64}, s::EMDSetting)\n    imfs = emd(signal, s)\n    return compute_instantaneous(input, imfs)\nend\n\n\"\"\"\n    hht(signal::Vector{Float64}, s::EEMDSetting)\n\nReturn the instantaneous energies and frequencies of the IMFS computed via the\nHilbert-Huang transform with EEMD settings specified.\n\"\"\"\nfunction hht(signal::Vector{Float64}, s::EEMDSetting)\n    imfs = eemd(signal, s)\n    return compute_instantaneous(input, imfs)\nend\n", "meta": {"hexsha": "67fdd3214eaf604b7b8f0fb70eb074be3dc51525", "size": 2125, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/extras/hilbert.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalModeDecomposition.jl-6a34a51b-2f4a-4636-bd3c-e47519ebd0d9", "max_stars_repo_head_hexsha": "706f65c0a2a28271e2d31979ce5c1478d40ec43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-21T14:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T14:21:37.000Z", "max_issues_repo_path": "src/extras/hilbert.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalModeDecomposition.jl-6a34a51b-2f4a-4636-bd3c-e47519ebd0d9", "max_issues_repo_head_hexsha": "706f65c0a2a28271e2d31979ce5c1478d40ec43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-08-28T04:56:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-05T09:14:18.000Z", "max_forks_repo_path": "src/extras/hilbert.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalModeDecomposition.jl-6a34a51b-2f4a-4636-bd3c-e47519ebd0d9", "max_forks_repo_head_hexsha": "706f65c0a2a28271e2d31979ce5c1478d40ec43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:06.000Z", "avg_line_length": 26.2345679012, "max_line_length": 88, "alphanum_fraction": 0.6536470588, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7510503076695522}}
{"text": "function interp2D( x1Vec0, x2Vec0, yMat, x1Val, x2Val )\r\n#UNTITLED Summary of this function goes here\r\n#   Detailed explanation goes here\r\n\r\nx1Vec=vec(x1Vec0)\r\nx2Vec=vec(x2Vec0)\r\n\r\n#Check that both x1Vec and x2Vec are n_i * 1 vectors\r\nsizex1Vec = size(x1Vec);\r\nsizex2Vec = size(x2Vec);\r\nsizeyMat = size(yMat);\r\n\r\n\r\n#println(\"Enter $sizex1Vec and $sizex2Vec and $sizeyMat\")\r\n\r\n# if (sizex1Vec[1]<=1) || (sizex2Vec[1]<=1) || (sizex1Vec[2]!=1) || (sizex2Vec[2]!=1)\r\n#     error(\"Both x1Vec and x2Vec need to be n_i by 1 vectors. The length of the vectors may differ\")\r\n# end\r\n\r\n#Check whether x1Vec and x2Vec are monotonic\r\n# isx1VecMonotone = all(diff[x1Vec]>=0);\r\n# isx2VecMonotone = all(diff[x2Vec]>=0);\r\n\r\n# if (isx1VecMonotone*isx2VecMonotone == 0)\r\n#     error(\"One of x1Vec or x2Vec is non-monotonic\");\r\n# end\r\n\r\nn1 = sizex1Vec[1];\r\n\r\nfunction nonNeg(args)\r\n    return args>=0\r\nend\r\n\r\n#Find where x1val fits into x1Vec and pick out the vectors in yMat\r\n#conditional on these values\r\nif (x1Val<=x1Vec[1])\r\n    x1LowerIndex = 1; \r\n    x1UpperIndex = 2;        \r\nelseif (x1Val>=x1Vec[n1])\r\n    x1UpperIndex = n1;\r\n    x1LowerIndex = n1 - 1;\r\nelse #x1Val is between the lower and the upper components of x1Vec\r\n    #Get a vect\r\n    x1VecLessX1Val = x1Vec - x1Val;\r\n\r\n    # Get the smallest non-negative \r\n    posI=find(nonNeg, x1VecLessX1Val)\r\n    (a,b)=findmin(x1VecLessX1Val[posI],1)\r\n    x1UpperIndex=posI[b];\r\n    x1LowerIndex = x1UpperIndex - 1.;\r\nend\r\n\r\nnewYMatAfterInterpOnX2 = Array(Float64,2, 1);\r\n\r\nyMatCondOnx1Lower = yMat[x1LowerIndex, :];\r\nyMatCondOnx1Upper = yMat[x1UpperIndex, :];\r\n\r\nintfL  = InterpIrregular(vec(x2Vec),vec(yMatCondOnx1Lower), BCnil, InterpLinear);\r\nintfH  = InterpIrregular(vec(x2Vec),vec(yMatCondOnx1Upper), BCnil, InterpLinear);\r\n\r\n# The last bit of interpolation!\r\n\r\nnewYMatAfterInterpOnX2[1]  =interp1extra(vec(x2Vec),vec(yMatCondOnx1Lower),x2Val,intfL);\r\nnewYMatAfterInterpOnX2[2]  =interp1extra(vec(x2Vec),vec(yMatCondOnx1Upper),x2Val,intfH);\r\n\r\nnewX1VecShort=[x1Vec[x1LowerIndex] x1Vec[x1UpperIndex] ]'\r\n\r\nintfF  = InterpIrregular(vec(newX1VecShort),vec(newYMatAfterInterpOnX2), BCnil, InterpLinear); \r\nyVal   = interp1extra(vec(newX1VecShort),vec(newYMatAfterInterpOnX2),x1Val,intfF); #  intfF[x1Val];\r\n\r\nreturn yVal\r\n    \r\nend\r\n\r\n", "meta": {"hexsha": "cdbeecff73539f1e8d157883d6c3f621f5419c40", "size": 2272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LifecycleCostaDias/v5_julia/code_numericTools/interp2D.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/interp2D.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/interp2D.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": 30.2933333333, "max_line_length": 102, "alphanum_fraction": 0.701584507, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7510101262682144}}
{"text": "# repeat can be useful to expand a grid\n# as in R's expand.grid() function:\n\n# <hide>\nfunction printsum(a)\n    println(summary(a), \": \", repr(a))\nend\n# </hide>\n\nm1 = hcat(repeat([1,2],inner=[1],outer=[3*2]),\n\t\t  repeat([1,2,3],inner=[2],outer=[2]),\n\t\t  repeat([1,2,3,4],inner=[3],outer=[1]))\nprintsum(m1)\n#> 12\u00d73 Array{Int64,2}: [1 1 1; 2 1 1; 1 2 1; 2 2 2; 1 3 2; 2 3 2; 1 1 3; 2 1 3;\n#> \t1 2 3; 2 2 4; 1 3 4; 2 3 4]\n\n# for simple repetitions of arrays,\n# use repeat\nm2 = repeat(m1,1,2) \t# replicate a9 once into dim1 and twice into dim2\nprintln(\"size: \", size(m2))\n#> size: (12, 6)\n\nm3 = repeat(m1,2,1) \t# replicate a9 twice into dim1 and once into dim2\nprintln(\"size: \", size(m3))\n#> size: (24, 3)\n\n# Julia comprehensions are another way to easily create\n# multidimensional arrays\n\nm4 = [i+j+k for i=1:2, j=1:3, k=1:2]\t# creates a 2x3x2 array of Int64\nm5 = [\"Hi Im # $(i+2*(j-1 + 3*(k-1)))\" for i=1:2, j=1:3, k=1:2]\n# expressions are very flexible\n# you can specify the type of the array by just\n# placing it in front of the expression\n\nimport LegacyStrings\nm5 = LegacyStrings.ASCIIString[\"Hi Im element # $(i+2*(j-1 + 3*(k-1)))\" for i=1:2, j=1:3, k=1:2]\nprintsum(m5)\n#> 2\u00d73\u00d72 Array{LegacyStrings.ASCIIString,3}: LegacyStrings.ASCIIString[\n#> \t\"Hi Im element # 1\" \"Hi Im element # 3\" \"Hi Im element # 5\";\n#> \t\"Hi Im element # 2\" \"Hi Im element # 4\" \"Hi Im element # 6\"]\n#>\n#> LegacyStrings.ASCIIString[\"Hi Im element # 7\" \"Hi Im element # 9\"\n#> \t\"Hi Im element # 11\"; \"Hi Im element # 8\" \"Hi Im element # 10\" \"Hi Im element # 12\"]\n\n# Array reductions\n# many functions in Julia have an array method\n# to be applied to specific dimensions of an array:\n\nsum(m4, dims=3)\t\t# takes the sum over the third dimension\nsum(m4, dims=(1,3))\t# sum over first and third dim\n\nmaximum(m4, dims=2)\t# find the max elt along dim 2\nfindmax(m4, dims=3)\t# find the max elt and its index along dim 3\n\t\t\t\t\t# (available only in very recent Julia versions)\n\n# Broadcasting\n# when you combine arrays of different sizes in an operation,\n# an attempt is made to \"spread\" or \"broadcast\" the smaller array\n# so that the sizes match up. broadcast operators are preceded by a dot:\n\nm4 .+ 3\t\t# add 3 to all elements\nm4 .+ [1,2]\t\t# adds vector [1,2] to all elements along first dim\n\n# slices and views\nm4=m4[:,:,1]\t# holds dim 3 fixed\nm4[:,2,:]\t# that's a 2x1x2 array. not very intuititive to look at\n\n# get rid of dimensions with size 1:\ndropdims(m4[:,2,:], dims=2)\t# that's better\n\n# assign new values to a certain view\nm4[:,:,1] = rand(1:6,2,3)\nprintsum(m4)\n#> 2\u00d73 Array{Int64,2}: [3 5 3; 1 3 5]\n\n# (for more examples of try, catch see Error Handling above)\ntry\n\t# this will cause an error, you have to assign the correct type\n\tm4[:,:,1] = rand(2,3)\ncatch err\n\tprintln(err)\nend\n#> InexactError(:Int64, Int64, 0.7603891754678744)\n\ntry\n\t# this will cause an error, you have to assign the right shape\n\tm4[:,:,1] = rand(1:6,3,2)\ncatch err\n\tprintln(err)\nend\n#> DimensionMismatch(\"tried to assign 3\u00d72 array to 2\u00d73\u00d71 destination\")\n", "meta": {"hexsha": "24193bcef99e27498bd7f6af134a9848163da541", "size": 2995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multiarrays.jl", "max_stars_repo_name": "talgatomarov/JuliaByExample", "max_stars_repo_head_hexsha": "9fc5516b7f6d03bd2f340b7a9bb52a06fedb7458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 281, "max_stars_repo_stars_event_min_datetime": "2015-02-01T01:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T19:51:35.000Z", "max_issues_repo_path": "src/multiarrays.jl", "max_issues_repo_name": "talgatomarov/JuliaByExample", "max_issues_repo_head_hexsha": "9fc5516b7f6d03bd2f340b7a9bb52a06fedb7458", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-04-10T04:23:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T12:32:59.000Z", "max_forks_repo_path": "src/multiarrays.jl", "max_forks_repo_name": "talgatomarov/JuliaByExample", "max_forks_repo_head_hexsha": "9fc5516b7f6d03bd2f340b7a9bb52a06fedb7458", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 101, "max_forks_repo_forks_event_min_datetime": "2015-03-24T20:45:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:24:46.000Z", "avg_line_length": 32.2043010753, "max_line_length": 96, "alphanum_fraction": 0.6614357262, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7510101258886372}}
{"text": "module Perceptron\r\nexport fit\r\nusing Random\r\nfunction fit(x,y,rate)\r\n    a,b=size(x)\r\n    arrOne=Array{Float64,2}(undef,a,1)\r\n    fill!(arrOne,1)\r\n    NewarrX=hcat(x,arrOne)\r\n    w=Array{Float64,2}(undef,1,b+1)\r\n    while true\r\n        i=rand(1:a)\r\n        if y[i]*(w*NewarrX[i,:])<=[0]\r\n            w=w+(rate.*y[i].*NewarrX[i,:])'\r\n            continue\r\n        end\r\n        pre=sgn(NewarrX,w)\r\n        # println(w)\r\n        # println(isequal(pre,y))\r\n        if isequalm(pre,y)\r\n            break\r\n        end\r\n\r\n    end\r\n    return w\r\nend\r\nfunction isequalm(x,y)\r\n    for i =1:length(x)\r\n        if x[i]!=y[i]\r\n            return false\r\n\r\n        end\r\n    end\r\n    return true\r\nend\r\nfunction sgn(x,w)\r\n    a,b=size(x)\r\n    p=Array{Float64,2}(undef,a,1)\r\n    for i =1:a\r\n        c=w*x[i,:]\r\n        # print(c)\r\n        if c[1]>0\r\n            c[1]=1\r\n        else c[1]<0\r\n            c[1]=-1\r\n        end\r\n        p[i]=c[1]\r\n    end\r\n    # print(typeof(p))\r\n    return p\r\nend\r\n\r\n# k=[3 3;4 3;1 1]\r\n# kkk=[1.0;1.0;-1.0]\r\n# r=1\r\n# fit(k,kkk,r)\r\nend  # module Perceptron\r\n", "meta": {"hexsha": "1e437d45692f8547b52a55a116738420bfda656d", "size": 1070, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Perceptron.jl", "max_stars_repo_name": "milanmi123/Perceptron-Julia", "max_stars_repo_head_hexsha": "fbaf345af01189323eb58d2e2e68c30a757aa366", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-02T03:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T03:14:17.000Z", "max_issues_repo_path": "Perceptron.jl", "max_issues_repo_name": "milanmi123/Perceptron-Julia", "max_issues_repo_head_hexsha": "fbaf345af01189323eb58d2e2e68c30a757aa366", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Perceptron.jl", "max_forks_repo_name": "milanmi123/Perceptron-Julia", "max_forks_repo_head_hexsha": "fbaf345af01189323eb58d2e2e68c30a757aa366", "max_forks_repo_licenses": ["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.7719298246, "max_line_length": 44, "alphanum_fraction": 0.4551401869, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7510101243538819}}
{"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 \u2208 invariant, u \u2208 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 \u2208 invariant, u \u2208 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 (-\u03c1(sparsevec([1], [-1.0], 10), sol) > dmin) &&\n           (-\u03c1(sparsevec([4], [-1.0], 10), sol) > dmin) &&\n           (-\u03c1(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": "#######################################################################################################################################################################################################\n#\n# Changes to this function\n# General\n#     2021-Aug-04: add this function to acoid NaN calculations\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", "meta": {"hexsha": "ff93d747c4549c57655d037880e01175e215d00c", "size": 812, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/statistics.jl", "max_stars_repo_name": "Yujie-W/Smaragdus.jl", "max_stars_repo_head_hexsha": "b8adf2826f8c8fca3e94afaa96979560ba550bf5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-05T19:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T19:09:27.000Z", "max_issues_repo_path": "src/utils/statistics.jl", "max_issues_repo_name": "Yujie-W/Smaragdus.jl", "max_issues_repo_head_hexsha": "b8adf2826f8c8fca3e94afaa96979560ba550bf5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-19T22:13:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-19T22:13:04.000Z", "max_forks_repo_path": "src/utils/statistics.jl", "max_forks_repo_name": "Yujie-W/Emerald.jl", "max_forks_repo_head_hexsha": "b8adf2826f8c8fca3e94afaa96979560ba550bf5", "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.0, "max_line_length": 199, "alphanum_fraction": 0.3177339901, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.750989516616594}}
{"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    \u03b1, \u03b2 = d.alpha, d.beta\n    num = 6.0 * ((\u03b1 - \u03b2)^2 * (\u03b1 + \u03b2 + 1.0) - \u03b1 * \u03b2 * (\u03b1 + \u03b2 + 2.0))\n    den = \u03b1 * \u03b2 * (\u03b1 + \u03b2 + 2.0) * (\u03b1 + \u03b2 + 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    \u03b1, \u03b2 = d.alpha, d.beta\n    if \u03b1 >= 1.0\n        if \u03b2 > 1.0\n            (\u03b1 - 1.0) / (\u03b1 + \u03b2 - 2.0)\n        elseif \u03b1 == 1.0 && \u03b2 == 1.0\n            # Uniform[0,1]: what should be returned?\n            0.5\n        else\n            1.0\n        end\n    else\n        if \u03b2 >= 1.0\n            0.0\n        else\n            # not unique: return largest\n            \u03b1 > \u03b2 ? 1.0 : 0.0\n        end\n    end\nend\n\nfunction modes(d::Beta)\n    \u03b1, \u03b2 = d.alpha, d.beta\n    if \u03b1 >= 1.0\n        if \u03b2 > 1.0\n            [(\u03b1 - 1.0) / (\u03b1 + \u03b2 - 2.0)]\n        elseif \u03b1 == 1.0 && \u03b2 == 1.0\n            # Uniform[0,1]: what should be returned?\n            Float64[]\n        else\n            [1.0]\n        end\n    else\n        if \u03b2 >= 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    \u03b1 = x_bar * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    \u03b2 = (1.0 - x_bar) * (((x_bar * (1.0 - x_bar)) / v_bar) - 1.0)\n    Beta(\u03b1, \u03b2)\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": "# This file was generated, do not modify it.\n\nusing HTTP, CSV, MLJ, StatsBase, PyPlot\nreq = HTTP.get(\"https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data\")\ndata = CSV.read(req.body,\n                header=[\"Class\", \"Alcool\", \"Malic acid\",\n                        \"Ash\", \"Alcalinity of ash\", \"Magnesium\",\n                        \"Total phenols\", \"Flavanoids\",\n                        \"Nonflavanoid phenols\", \"Proanthcyanins\",\n                        \"Color intensity\", \"Hue\",\n                        \"OD280/OD315 of diluted wines\", \"Proline\"])\n# the target is the Class column, everything else is a feature\ny, X = unpack(data, ==(:Class), colname->true);\n\nscitype(y)\n\nyc = coerce(y, OrderedFactor);\n\nscitype(X)\n\nsch = schema(X)\nprintln(rpad(\" Name\", 28), \"| Scitype\")\nprintln(\"-\"^45)\nfor (name, scitype) in zip(sch.names, sch.scitypes)\n    println(rpad(\"$name\", 30), scitype)\nend\n\nX[1:5, :Proline]\n\nXc = coerce(X, :Proline=>Continuous, :Magnesium=>Continuous);\n\ndescribe(Xc, :mean, :std)\n\n@load KNNClassifier pkg=\"NearestNeighbors\"\n@load MultinomialClassifier pkg=\"MLJLinearModels\";\n\n@pipeline KnnPipe(std=Standardizer(), clf=KNNClassifier()) is_probabilistic=true\n@pipeline MnPipe(std=Standardizer(), clf=MultinomialClassifier()) is_probabilistic=true\n\ntrain, test = partition(eachindex(yc), 0.8, shuffle=true, rng=111)\nXtrain = selectrows(Xc, train)\nXtest = selectrows(Xc, test)\nytrain = selectrows(yc, train)\nytest = selectrows(yc, test);\n\nknn = machine(KnnPipe(), Xtrain, ytrain)\nmulti = machine(MnPipe(), Xtrain, ytrain)\n\nopts = (resampling=Holdout(fraction_train=0.9), measure=cross_entropy)\nres = evaluate!(knn; opts...)\nround(res.measurement[1], sigdigits=3)\n\nres = evaluate!(multi; opts...)\nround(res.measurement[1], sigdigits=3)\n\nmcr_k = misclassification_rate(predict_mode(knn, Xtrain), ytrain)\nmcr_m = misclassification_rate(predict_mode(multi, Xtrain), ytrain)\nprintln(rpad(\"KNN mcr:\", 10), round(mcr_k, sigdigits=3))\nprintln(rpad(\"MNC mcr:\", 10), round(mcr_m, sigdigits=3))\n\n# @pipeline PCAPipe(std=Standardizer(), t=PCA(maxoutdim=2))\n# pca = machine(PCAPipe(), Xtrain)\n# fit!(pca, Xtrain)\n# W = transform(pca, Xtrain)\n\n@load PCA\n\npca = Xc |> Standardizer() |> PCA(maxoutdim=2)\nfit!(pca)\nW = pca(rows=train);\n\nx1 = W.x1\nx2 = W.x2\n\nmask_1 = ytrain .== 1\nmask_2 = ytrain .== 2\nmask_3 = ytrain .== 3\n\nfigure(figsize=(8, 6))\nplot(x1[mask_1], x2[mask_1], linestyle=\"none\", marker=\"o\", color=\"red\")\nplot(x1[mask_2], x2[mask_2], linestyle=\"none\", marker=\"o\", color=\"blue\")\nplot(x1[mask_3], x2[mask_3], linestyle=\"none\", marker=\"o\", color=\"magenta\")\n\nxlabel(\"PCA dimension 1\", fontsize=14)\nylabel(\"PCA dimension 2\", fontsize=14)\nlegend([\"Class 1\", \"Class 2\", \"Class 3\"], fontsize=12)\nxticks(fontsize=12)\nyticks(fontsize=12)\n\nsavefig(\"assets/literate/EX-wine-pca.svg\") # hide\n\nperf_k = misclassification_rate(predict_mode(knn, Xtest), ytest)\nperf_m = misclassification_rate(predict_mode(multi, Xtest), ytest)\nprintln(rpad(\"KNN mcr:\", 10), round(perf_k, sigdigits=3))\nprintln(rpad(\"MNC mcr:\", 10), round(perf_m, sigdigits=3))\n\n", "meta": {"hexsha": "d2d7fe1ebf464b22cca4b78b0482c6c7fe26db23", "size": 3051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_assets/literate/EX-wine_script.jl", "max_stars_repo_name": "giordano/DataScienceTutorials.jl", "max_stars_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-08-09T11:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T06:20:43.000Z", "max_issues_repo_path": "_assets/literate/EX-wine_script.jl", "max_issues_repo_name": "giordano/DataScienceTutorials.jl", "max_issues_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-10-22T00:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T14:38:09.000Z", "max_forks_repo_path": "_assets/literate/EX-wine_script.jl", "max_forks_repo_name": "giordano/DataScienceTutorials.jl", "max_forks_repo_head_hexsha": "8284298842e0d77061cf8ee767d0899fb7d051ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-11-20T16:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T11:55:15.000Z", "avg_line_length": 31.4536082474, "max_line_length": 90, "alphanum_fraction": 0.6794493609, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.750986934759501}}
{"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": "@testset \"Manifold Newton\" begin\n    function f_1(x::Vector)\n        (x[1] - 5.0)^4\n    end\n\n    function g!_1(storage::Vector, x::Vector)\n        storage[1] = 4.0 * (x[1] - 5.0)^3\n    end\n\n    function h!_1(storage::Matrix, x::Vector)\n        storage[1, 1] = 12.0 * (x[1] - 5.0)^2\n    end\n    initial_x = [0.0]\n\n    retract_flat!(x) = x\n    method = ManifoldNewton(retract_flat!)\n    Optim.optimize(NonDifferentiable(f_1, initial_x), [0.0], method)\n    Optim.optimize(OnceDifferentiable(f_1, g!_1, initial_x), [0.0], method)\n\n    options = Optim.Options(store_trace = false, show_trace = false,\n                            extended_trace = true)\n    results = Optim.optimize(f_1, g!_1, h!_1, [0.0], method, options)\n    @test_throws ErrorException Optim.x_trace(results)\n    @test Optim.g_converged(results)\n    @test norm(Optim.minimizer(results) - [5.0]) < 0.01\n\n    eta = 0.9\n\n    function f_2(x::Vector)\n      (1.0 / 2.0) * (x[1]^2 + eta * x[2]^2)\n    end\n\n    function g!_2(storage::Vector, x::Vector)\n      storage[1] = x[1]\n      storage[2] = eta * x[2]\n    end\n\n    function h!_2(storage::Matrix, x::Vector)\n      storage[1, 1] = 1.0\n      storage[1, 2] = 0.0\n      storage[2, 1] = 0.0\n      storage[2, 2] = eta\n    end\n\n    results = Optim.optimize(f_2, g!_2, h!_2, [127.0, 921.0], method)\n    @test_throws ErrorException Optim.x_trace(results)\n    @test Optim.g_converged(results)\n    @test norm(Optim.minimizer(results) - [0.0, 0.0]) < 0.01\n    @test summary(results) == \"Manifold Newton's Method\"\nend\n", "meta": {"hexsha": "14fc82c3b5fec30b69a9786e2cf460cf6447443f", "size": 1514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/multivariate/solvers/second_order/manifold_newton.jl", "max_stars_repo_name": "hcarlsso/Optim.jl", "max_stars_repo_head_hexsha": "4e69b2f347350874f224ec17c392a88047f41aa4", "max_stars_repo_licenses": ["MIT"], "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/multivariate/solvers/second_order/manifold_newton.jl", "max_issues_repo_name": "hcarlsso/Optim.jl", "max_issues_repo_head_hexsha": "4e69b2f347350874f224ec17c392a88047f41aa4", "max_issues_repo_licenses": ["MIT"], "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/multivariate/solvers/second_order/manifold_newton.jl", "max_forks_repo_name": "hcarlsso/Optim.jl", "max_forks_repo_head_hexsha": "4e69b2f347350874f224ec17c392a88047f41aa4", "max_forks_repo_licenses": ["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.6862745098, "max_line_length": 75, "alphanum_fraction": 0.5924702774, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7509869321843876}}
{"text": "\"\"\"\n    function hamming_distance(s1::String, s2::String)\n\nIn information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. \nIn other words, it measures the minimum number of substitutions required to change one string into the other, or the minimum number of errors that could have transformed one string into the other. \nIn a more general context, the Hamming distance is one of several string metrics for measuring the edit distance between two sequences. It is named after the American mathematician Richard Hamming.\n\nReference (https://en.wikipedia.org/wiki/Hamming_distance)\n\n# Arguments:\n- `s1`: First string to compare\n- `s2`: Second string to compare\n\n# Examples/Tests \n```julia\njulia> hamming_distance(\"karolin\", \"kathrin\")\n3\n\njulia> hamming_distance(\"0000\", \"1111\")\n4\n\njulia> hamming_distance(\"ABCDEFG\", \"AZCDWGM\")\n4\n```\n\n# Contributors:\n- [Sedat Aybars Nazlica](https://github.com/saybarsnazlica)\n\"\"\"\n\nfunction hamming_distance(s1::String, s2::String)\n    @assert length(s1) == length(s2) \"String lengths must be the same\"\n\n    distance = 0\n\n    for i in 1:length(s1)\n        if s1[i] != s2[i]\n            distance += 1\n        end\n    end\n    return distance\nend\n", "meta": {"hexsha": "903a2ce4f81b3e0e7fcd248502541ccc681881e7", "size": 1268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/strings/hamming_distance.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/strings/hamming_distance.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/strings/hamming_distance.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": 30.1904761905, "max_line_length": 197, "alphanum_fraction": 0.7318611987, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.750986930467645}}
{"text": "\nmonicderivative(p, i::Int) = derivative(p, degree(p)-i)*factorial(i)/factorial(degree(p))\n\nisapproxreal(x::Real) = true\nisapproxreal(x::Complex{T}; atol::Real=1e-7) where {T} = abs(imag(x)) < atol\nrealroots(poly) = real.(filter(isapproxreal, _ROOTS[](poly)))\n\n# define a function that returns a Plots.Shape\n# code from https://discourse.julialang.org/t/how-to-draw-a-rectangular-region-with-plots-jl/1719/4\nrectangle(x1, y1, x2, y2) = ([x1,x2,x2,x1], [y1,y1,y2,y2])\nfunction ithrectangles(sortrealroots, i;\n                       mininf=-5, inf=5, w=.5)\n    xs = [mininf; sortrealroots]\n    xs2 = [sortrealroots; inf]\n    return [rectangle(x1, i-w, x2, i+w) for (x1,x2) in zip(xs, xs2)]\nend\n\nfunction ithcolors(_iseven::Bool, nboxes, gray, black)\n    grays = _iseven ? iseven.(1:nboxes) : isodd.(1:nboxes)\n    blacks = (!).(grays)\n    return gray*grays + black*blacks\nend\n\nfunction find_bounds(allsortvectors)\n    nonempty_vectors = filter((!)\u2218isempty, allsortvectors)\n    mins, maxs = first.(nonempty_vectors), last.(nonempty_vectors)\n    return minimum(mins), maximum(maxs)\nend\n", "meta": {"hexsha": "e9d22e443ab89d3c6b7192b2631c7310452bd4d3", "size": 1081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BudanTablesBase.jl", "max_stars_repo_name": "LauraBMo/BudanTables.jl", "max_stars_repo_head_hexsha": "7dd5442b4d922a3ca4d3ff916b327674788f0334", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-07T09:50:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T13:46:53.000Z", "max_issues_repo_path": "src/BudanTablesBase.jl", "max_issues_repo_name": "LauraBMo/BudanTables.jl", "max_issues_repo_head_hexsha": "7dd5442b4d922a3ca4d3ff916b327674788f0334", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BudanTablesBase.jl", "max_forks_repo_name": "LauraBMo/BudanTables.jl", "max_forks_repo_head_hexsha": "7dd5442b4d922a3ca4d3ff916b327674788f0334", "max_forks_repo_licenses": ["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.275862069, "max_line_length": 99, "alphanum_fraction": 0.6808510638, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7509869270649878}}
{"text": "@testset \"$(rpad(\"Gau\u00df-Legendre\",80))\" begin\n\n    for s in 1:10\n        @test GaussLegendreQuadrature(s) \u2248  GaussLegendreQuadrature(s; fast=true)\n        @test GaussLegendreQuadrature(s) == GaussLegendreQuadrature(Float64, s)\n\n        @test sum(weights(GaussLegendreQuadrature(s))) \u2248 1\n    end\n\nend\n", "meta": {"hexsha": "f10241964ea48f2a807e52d155340442be52026a", "size": 299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gauss_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": "test/test_gauss_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": "test/test_gauss_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": 27.1818181818, "max_line_length": 81, "alphanum_fraction": 0.6789297659, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7509260080518955}}
{"text": "#\n\nfunction jet(N::Integer)\n\tcm = RGB{Float64}[\n\t    RGB(\n\t        clamp(min(4x - 1.5, -4x + 4.5) ,0.0,1.0),\n\t        clamp(min(4x - 0.5, -4x + 3.5) ,0.0,1.0),\n\t        clamp(min(4x + 0.5, -4x + 2.5) ,0.0,1.0))  \n\t    for x in linspace(0.0,1.0,N)]\n\tend\n\njet() = jet(64);\n\naccess_dict[\"jet\"] = jet\n\n", "meta": {"hexsha": "18649800f9718b7c60f6741b227b43ebec0fa0d3", "size": 298, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/named_maps.jl", "max_stars_repo_name": "lobingera/ColorMaps", "max_stars_repo_head_hexsha": "5cef787f63c4f2a35ff79bde4e5903c104148ad5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-07T19:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-07T19:03:40.000Z", "max_issues_repo_path": "src/named_maps.jl", "max_issues_repo_name": "lobingera/ColorMaps.jl", "max_issues_repo_head_hexsha": "5cef787f63c4f2a35ff79bde4e5903c104148ad5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/named_maps.jl", "max_forks_repo_name": "lobingera/ColorMaps.jl", "max_forks_repo_head_hexsha": "5cef787f63c4f2a35ff79bde4e5903c104148ad5", "max_forks_repo_licenses": ["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.625, "max_line_length": 52, "alphanum_fraction": 0.4731543624, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7509259991470272}}
{"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": "module Constants\n\nexport \u03bc\u2080, \u03f5\u2080, c\u2080, \u03b7\u2080, twopi, fourpi, tol, dbmin, tdigits\n\n\"Permeability of free space [H/m]\"\nconst \u03bc\u2080 = 1.25663706212*1e-6\n\n\"Speed of light [m/s]\"\nconst c\u2080 = 299792458.0\n\n\"Permeability of free space [F/m]\"\nconst \u03f5\u2080 = 1/(\u03bc\u2080*c\u2080^2)\n\n\"Intrinsic impedance of free space [F/m]\"\nconst \u03b7\u2080 = sqrt(\u03bc\u2080/\u03f5\u2080)\n\nconst twopi = 2\u03c0\nconst fourpi = 4\u03c0\nconst tol = 1e-4\n\n\"Minimum modal attenuation\"\nconst dbmin = 30.0\n\n\"Min. elect. length for a layer to not be included in a `GBLOCK`\"\nconst min_elength = twopi * 0.1 \n\n\"Number of digits to use in printing elapsed time\"\nconst tdigits = 4\n\nend\n\n\n\n\n", "meta": {"hexsha": "fac65ce3a20fdfce18d2c7ead2e7560ee2aac18f", "size": 594, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Constants.jl", "max_stars_repo_name": "mortenpi/PSSFSS.jl", "max_stars_repo_head_hexsha": "9a3a6503d9266eee57771612a47a3e9b77bc9a2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-05-21T15:44:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T17:29:19.000Z", "max_issues_repo_path": "src/Constants.jl", "max_issues_repo_name": "mortenpi/PSSFSS.jl", "max_issues_repo_head_hexsha": "9a3a6503d9266eee57771612a47a3e9b77bc9a2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-10-08T22:20:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T01:01:09.000Z", "max_forks_repo_path": "src/Constants.jl", "max_forks_repo_name": "mortenpi/PSSFSS.jl", "max_forks_repo_head_hexsha": "9a3a6503d9266eee57771612a47a3e9b77bc9a2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-20T13:58:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T09:16:48.000Z", "avg_line_length": 16.9714285714, "max_line_length": 65, "alphanum_fraction": 0.6986531987, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7509259447247605}}
{"text": "using StatsDiscretizations\nusing Test\nusing Infinity\n\n@test cdf(Binomial(5,0.5), Interval{:open,:closed}(0, \u221e)) == 1.0\n@test cdf(Binomial(5,0.7), Interval{:open,:closed}(-\u221e,0)) \u2248 pdf(Binomial(5,0.7), 0)\n\n#pdf(Normal(), NormalSample(IntervalSets.Interval(0.0,Inf),1.0))\n", "meta": {"hexsha": "b4ac903c6c970607c05c7e8b358a370a74109530", "size": 269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_distributions_intervals.jl", "max_stars_repo_name": "nignatiadis/StatsDiscretizations.jl", "max_stars_repo_head_hexsha": "984b1e5937fcc68bf03776ee0d75e192d947d24c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-01T04:57:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T04:57:11.000Z", "max_issues_repo_path": "test/test_distributions_intervals.jl", "max_issues_repo_name": "nignatiadis/StatsDiscretizations.jl", "max_issues_repo_head_hexsha": "984b1e5937fcc68bf03776ee0d75e192d947d24c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-14T00:29:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-09T04:40:48.000Z", "max_forks_repo_path": "test/test_distributions_intervals.jl", "max_forks_repo_name": "nignatiadis/StatsDiscretizations.jl", "max_forks_repo_head_hexsha": "984b1e5937fcc68bf03776ee0d75e192d947d24c", "max_forks_repo_licenses": ["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.8888888889, "max_line_length": 83, "alphanum_fraction": 0.6914498141, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7509259430077251}}
{"text": "include(\"../functions/Functions.jl\")\ninclude(\"../evaluate/Evaluate.jl\")\ninclude(\"../opt/SAG.jl\")\ninclude(\"../data/data.jl\")\n\nX, y = getFullData()\n\n# init initial point x_0\nx0 = zeros(size(X,2),1)\n \nlambda = 5\n\niter = 250\nstep =0.01\n\nf = f_logreg(X,y,x0,lambda)\ng = sub_g_logreg()\n\n#f = f_svm(X,y,x0,lambda)\n#g = sub_g_svm()\n\n\n@time (theta, strings, iter) = SAG(X,y,x0,f,g,1e-8,lambda,iter,step,size(X,1))\n\ngrad = g_logreg(X,y,theta,lambda)(theta)\ngrad_norm = norm(grad, Inf)\n@printf(\"Inf-Norm of gradient is %f.\\n\",grad_norm)\nprintln(evaluate(X,y,theta,\"logreg\",false))\n\n# Lippschitz = largest eigenvalue of Hessian*Hessian'\n", "meta": {"hexsha": "4624d8fad56fd7da540b8ac3231363ac26e7e63b", "size": 625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/test/sag_test.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/test/sag_test.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/test/sag_test.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.1612903226, "max_line_length": 78, "alphanum_fraction": 0.6768, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897558991952, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7509259415334004}}
{"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, \u03b8::Real, x::Number) = 1 / (gamma(k) * \u03b8^k) * x^(k - 1) * exp(-x / \u03b8)\n\n# logpdf for numbers with generic types\ngammalogpdf(k::Real, \u03b8::Real, x::Number) = -loggamma(k) - k * log(\u03b8) + (k - 1) * log(x) - x / \u03b8\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, \u03bb)\n    p = minimize(\u03bb * risk - (1 - \u03bb) * 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!(\u2207f, x)\n    theta_x = theta(x)\n\n    if !(\u2207f==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        \u2207f[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        \u2207f[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        \u2207f[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": "using Distributions\nusing Random\n\nstruct SpreadingParams\n  dist::Truncated{Pareto{Float64},Continuous,Float64}\n  spreading::Vector{Float32}\nend\n\nfunction SpreadingParams(rng::AbstractRNG, N::Integer; alpha::Real, x0::Real=1, truncation::Real=Inf)\n  dist=truncated(Pareto(alpha, x0), x0, truncation)\n  spreading = Vector{Float32}(undef, N)\n  rand!(rng, dist, spreading)\n  SpreadingParams(dist, spreading)\nend\n\nfunction saveparams(dict, p::SpreadingParams, prefix::AbstractString=\"\")\n  dict[prefix*\"dist\"] = params(p.dist)\n  dict[prefix*\"values\"] = p.spreading\n  nothing\nend\n\nfunction show(io::IO, p::SpreadingParams)\n  print(io, \"Spreading params for \", numindividuals(p), \" individuals, distribution=\", p.dist)\nend\n\nspreading(p::SpreadingParams, source_id::Integer) = Float64(p.spreading[source_id])\n\n", "meta": {"hexsha": "c9502984ad6f66378c1ddaa1023a9eff079483a0", "size": 801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/params/spreading.jl", "max_stars_repo_name": "MOCOS-COVID19/MocosSim", "max_stars_repo_head_hexsha": "00df328853513a4f92560b316e79995868bb3712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-29T08:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T19:20:16.000Z", "max_issues_repo_path": "src/params/spreading.jl", "max_issues_repo_name": "MOCOS-COVID19/MocosSim", "max_issues_repo_head_hexsha": "00df328853513a4f92560b316e79995868bb3712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:24:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:26:49.000Z", "max_forks_repo_path": "src/params/spreading.jl", "max_forks_repo_name": "MOCOS-COVID19/MocosSim", "max_forks_repo_head_hexsha": "00df328853513a4f92560b316e79995868bb3712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-24T18:12:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-24T18:12:35.000Z", "avg_line_length": 28.6071428571, "max_line_length": 101, "alphanum_fraction": 0.7515605493, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7508781865432052}}
{"text": "using Test, DiscreteExteriorCalculus\nusing LinearAlgebra: norm, det\nusing StaticArrays: SVector\n\n@testset \"norm, wedge, and volume\" begin\n    m = Metric(3)\n    @test norm(m, SVector{3, Float64}([1,2,3])) == norm([1,2,3])\n    a1, a2 = 3.4, 2.8\n    b1, b2 = -2.4, 20.3\n    s = Simplex(Point(0, 0, 0), Point(a1, a2, 0), Point(b1, b2, 0))\n    @test volume(m, s) \u2248 det([[a1, a2] [b1, b2]])/2\n    a1, a2, a3 = 3.4, 2.8, 3.9\n    b1, b2, b3 = -2.4, 20.3, -3.2\n    c1, c2, c3 = .1, -49.2, 12.0\n    s = Simplex(Point(0, 0, 0), Point(a1, a2, a3), Point(b1, b2, b3), Point(c1, c2, c3))\n    @test volume(m, s) \u2248 det([[a1, a2, a3] [b1, b2, b3] [c1, c2, c3]])/6\n    m = Metric(2)\n    s = Simplex(Point(1,2))\n    volume(m, s) == 1.0\nend\n", "meta": {"hexsha": "3535ccab90aa984111a713beb39e5b8f6237cf1e", "size": 721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_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": "test/test_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": "test/test_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": 34.3333333333, "max_line_length": 88, "alphanum_fraction": 0.5381414702, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731083722525, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7508781848726094}}
{"text": "function counting_sort_letters(A, position)\n\tc = Array{Int, 1}(undef, 26)\n    for i in 1:26\n        c[i] = 0\n    end\n\tfor i in A\n        c[abs(Int(i[position]) - 97) % 26 + 1] += 1\n\tend\n\tfor i in 2:26\n\t\tc[i] += c[i - 1]\n\tend\n\tret = Array{String, 1}(undef, length(A))\n\tfor i in length(A) : -1 : 1\n        ret[c[abs(Int(A[i][position]) - 97) % 26 + 1]] = A[i]\n        c[abs(Int(A[i][position]) - 97) % 26 + 1] -= 1\n\tend\n\treturn ret\nend\n\nfunction counting_sort_length(A::Array)\n\tmax_len = 0\n\tfor i in A\n\t\tif max_len < length(i)\n\t\t\tmax_len = length(i)\n\t\tend\n\tend\n\tc = Array{Int, 1}(undef, max_len + 1)\n\tfor i in 1 : max_len + 1\n\t\tc[i] = 0\n\tend\n\n\tfor i in A\n\t\tc[length(i) + 1] += 1\n\tend\n\n\tfor i in 2 : max_len + 1\n\t\tc[i] += c[i - 1]\n\tend\n\n\tret = Array{String, 1}(undef, length(A))\n\n\tfor i in length(A) : -1 : 1\n\t\tret[c[length(A[i]) + 1]] = A[i]\n\t\tc[length(A[i]) + 1] -= 1\n\tend\n\treturn ret\nend\n\nfunction copy_into!(to, from, p, r)\n\tfor i in p : r\n\t\tto[i] = from[i - p + 1]\n\tend\nend\n\n\nfunction flexradix(A::Array, max_len)\n\tA = counting_sort_length(A)\n\n\tnum_empty = 0\n\n\tfor i in A\n\t\tif length(i) == 0\n\t\t\tnum_empty += 1\n\t\tend\n\t\tif max_len < length(i)\n\t\t\tmax_len = length(i)\n\t\tend\n\tend\n\n\tif max_len == 0\n\t\treturn A\n\tend\n\n\tc = zeros(Int, max_len + 1)\n\n\tfor i in A\n\t\tc[length(i) + 1] += 1\n\tend\n\n\tfor i in max_len : -1 : 1\n\t\tc[i] += c[i + 1]\n\tend\n\n\tr = length(A)\n\t\n    for cur_len in (max_len + 1) : -1 : 2\n\t\tp = r - c[cur_len] + 1\n\n\t\tif r - p > 0\n\t\t\tcopy_into!(A, counting_sort_letters(A[p : r], cur_len - 1), p, r)\n\t\tend\n\tend\n\t\n\tcopy_into!(A, counting_sort_letters(A[(num_empty + 1) : r], 1), (num_empty + 1), r)\n\n\treturn A\nend\n", "meta": {"hexsha": "f01f3135c9647424f840ac41d37aecde43eb8093", "size": 1618, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "18Host/TDT4120/Kok/Oving4.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/Kok/Oving4.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/Kok/Oving4.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": 16.5102040816, "max_line_length": 84, "alphanum_fraction": 0.5556242274, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7507667084529321}}
{"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": "# Copyright (c) 2013: Iain Dunning, Miles Lubin, and contributors\n#\n# Use of this source code is governed by an MIT-style license that can be found\n# in the LICENSE.md file or at https://opensource.org/licenses/MIT.\n\nmodule TestCWrapper\n\nusing Ipopt\nusing Test\n\nfunction test_hs071()\n    # hs071\n    # min x1 * x4 * (x1 + x2 + x3) + x3\n    # st  x1 * x2 * x3 * x4 >= 25\n    #     x1^2 + x2^2 + x3^2 + x4^2 = 40\n    #     1 <= x1, x2, x3, x4 <= 5\n    # Start at (1,5,5,1)\n    # End at (1.000..., 4.743..., 3.821..., 1.379...)\n\n    function eval_f(x::Vector{Float64})\n        return x[1] * x[4] * (x[1] + x[2] + x[3]) + x[3]\n    end\n\n    function eval_g(x::Vector{Float64}, g::Vector{Float64})\n        # Bad: g    = zeros(2)  # Allocates new array\n        # OK:  g[:] = zeros(2)  # Modifies 'in place'\n        g[1] = x[1] * x[2] * x[3] * x[4]\n        return g[2] = x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2\n    end\n\n    function eval_grad_f(x::Vector{Float64}, grad_f::Vector{Float64})\n        # Bad: grad_f    = zeros(4)  # Allocates new array\n        # OK:  grad_f[:] = zeros(4)  # Modifies 'in place'\n        grad_f[1] = x[1] * x[4] + x[4] * (x[1] + x[2] + x[3])\n        grad_f[2] = x[1] * x[4]\n        grad_f[3] = x[1] * x[4] + 1\n        return grad_f[4] = x[1] * (x[1] + x[2] + x[3])\n    end\n\n    function eval_jac_g(\n        x::Vector{Float64},\n        rows::Vector{Int32},\n        cols::Vector{Int32},\n        values::Union{Nothing,Vector{Float64}},\n    )\n        if values === nothing\n            # Constraint (row) 1\n            rows[1] = 1\n            cols[1] = 1\n            rows[2] = 1\n            cols[2] = 2\n            rows[3] = 1\n            cols[3] = 3\n            rows[4] = 1\n            cols[4] = 4\n            # Constraint (row) 2\n            rows[5] = 2\n            cols[5] = 1\n            rows[6] = 2\n            cols[6] = 2\n            rows[7] = 2\n            cols[7] = 3\n            rows[8] = 2\n            cols[8] = 4\n        else\n            # Constraint (row) 1\n            values[1] = x[2] * x[3] * x[4]  # 1,1\n            values[2] = x[1] * x[3] * x[4]  # 1,2\n            values[3] = x[1] * x[2] * x[4]  # 1,3\n            values[4] = x[1] * x[2] * x[3]  # 1,4\n            # Constraint (row) 2\n            values[5] = 2 * x[1]  # 2,1\n            values[6] = 2 * x[2]  # 2,2\n            values[7] = 2 * x[3]  # 2,3\n            values[8] = 2 * x[4]  # 2,4\n        end\n        return\n    end\n\n    function eval_h(\n        x::Vector{Float64},\n        rows::Vector{Int32},\n        cols::Vector{Int32},\n        obj_factor::Float64,\n        lambda::Vector{Float64},\n        values::Union{Nothing,Vector{Float64}},\n    )\n        if values === nothing\n            # Symmetric matrix, fill the lower left triangle only\n            idx = 1\n            for row in 1:4\n                for col in 1:row\n                    rows[idx] = row\n                    cols[idx] = col\n                    idx += 1\n                end\n            end\n        else\n            # Again, only lower left triangle\n            # Objective\n            values[1] = obj_factor * (2 * x[4])  # 1,1\n            values[2] = obj_factor * (x[4])  # 2,1\n            values[3] = 0                      # 2,2\n            values[4] = obj_factor * (x[4])  # 3,1\n            values[5] = 0                      # 3,2\n            values[6] = 0                      # 3,3\n            values[7] = obj_factor * (2 * x[1] + x[2] + x[3])  # 4,1\n            values[8] = obj_factor * (x[1])  # 4,2\n            values[9] = obj_factor * (x[1])  # 4,3\n            values[10] = 0                     # 4,4\n\n            # First constraint\n            values[2] += lambda[1] * (x[3] * x[4])  # 2,1\n            values[4] += lambda[1] * (x[2] * x[4])  # 3,1\n            values[5] += lambda[1] * (x[1] * x[4])  # 3,2\n            values[7] += lambda[1] * (x[2] * x[3])  # 4,1\n            values[8] += lambda[1] * (x[1] * x[3])  # 4,2\n            values[9] += lambda[1] * (x[1] * x[2])  # 4,3\n\n            # Second constraint\n            values[1] += lambda[2] * 2  # 1,1\n            values[3] += lambda[2] * 2  # 2,2\n            values[6] += lambda[2] * 2  # 3,3\n            values[10] += lambda[2] * 2  # 4,4\n        end\n        return\n    end\n\n    n = 4\n    x_L = [1.0, 1.0, 1.0, 1.0]\n    x_U = [5.0, 5.0, 5.0, 5.0]\n\n    m = 2\n    g_L = [25.0, 40.0]\n    g_U = [2.0e19, 40.0]\n\n    prob = Ipopt.CreateIpoptProblem(\n        n,\n        x_L,\n        x_U,\n        m,\n        g_L,\n        g_U,\n        8,\n        10,\n        eval_f,\n        eval_g,\n        eval_grad_f,\n        eval_jac_g,\n        eval_h,\n    )\n\n    prob.x = [1.0, 5.0, 5.0, 1.0]\n    solvestat = Ipopt.IpoptSolve(prob)\n\n    @test solvestat == 0\n    @test prob.x[1] \u2248 1.0000000000000000 atol = 1e-5\n    @test prob.x[2] \u2248 4.7429996418092970 atol = 1e-5\n    @test prob.x[3] \u2248 3.8211499817883077 atol = 1e-5\n    @test prob.x[4] \u2248 1.3794082897556983 atol = 1e-5\n    @test prob.obj_val \u2248 17.014017145179164 atol = 1e-5\n\n    # This tests callbacks.\n    function intermediate(\n        alg_mod::Cint,\n        iter_count::Cint,\n        obj_value::Float64,\n        inf_pr::Float64,\n        inf_du::Float64,\n        mu::Float64,\n        d_norm::Float64,\n        regularization_size::Float64,\n        alpha_du::Float64,\n        alpha_pr::Float64,\n        ls_trials::Cint,\n    )\n        return iter_count < 1  # Interrupts after one iteration.\n    end\n\n    Ipopt.SetIntermediateCallback(prob, intermediate)\n\n    solvestat = Ipopt.IpoptSolve(prob)\n\n    @test solvestat == 5\n\n    # Test setting some options\n    # String option\n    println(\"\\nString option\")\n    Ipopt.AddIpoptStrOption(prob, \"hessian_approximation\", \"exact\")\n    @test_throws(\n        ErrorException,\n        Ipopt.AddIpoptStrOption(prob, \"hessian_approximation\", \"badoption\"),\n    )\n    println(\"\\nInt option\")\n    # Int option\n    @test Ipopt.AddIpoptIntOption(prob, \"file_print_level\", 3) === nothing\n    @test_throws(\n        ErrorException,\n        Ipopt.AddIpoptIntOption(prob, \"file_print_level\", -1),\n    )\n    # Double option\n    println(\"\\nFloat option\")\n    Ipopt.AddIpoptNumOption(prob, \"derivative_test_tol\", 0.5)\n    @test_throws(\n        ErrorException,\n        Ipopt.AddIpoptNumOption(prob, \"derivative_test_tol\", -1.0),\n    )\n\n    # Test opening an output file\n    Ipopt.OpenIpoptOutputFile(prob, \"blah.txt\", 5)\n    finalize(prob) # Needed before the `rm` on Windows.\n    # unlink the output file\n    rm(\"blah.txt\")\n    return\nend\n\nend  # TestCWrapper\n\nruntests(TestCWrapper)\n", "meta": {"hexsha": "8bb74e47f072a85199f91d56e51fc8aaf789a98f", "size": 6462, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/C_wrapper.jl", "max_stars_repo_name": "JuliaOpt/Ipopt.jl", "max_stars_repo_head_hexsha": "a1502e6bc410ee4531e07cc792932a7b0453e73b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58, "max_stars_repo_stars_event_min_datetime": "2015-08-21T01:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-31T12:05:55.000Z", "max_issues_repo_path": "test/C_wrapper.jl", "max_issues_repo_name": "JuliaOpt/Ipopt.jl", "max_issues_repo_head_hexsha": "a1502e6bc410ee4531e07cc792932a7b0453e73b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 152, "max_issues_repo_issues_event_min_datetime": "2015-01-06T02:06:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T02:59:12.000Z", "max_forks_repo_path": "test/C_wrapper.jl", "max_forks_repo_name": "JuliaOpt/Ipopt.jl", "max_forks_repo_head_hexsha": "a1502e6bc410ee4531e07cc792932a7b0453e73b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2015-04-14T07:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-13T10:50:42.000Z", "avg_line_length": 29.3727272727, "max_line_length": 79, "alphanum_fraction": 0.4749303621, "num_tokens": 2317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7507666954704166}}
{"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 BenchmarkTools\nusing Distributions\nimport Cubature\nimport HCubature\nimport QuadGK\n\np(x::Float64) = exp(-0.5 * x^2) / \u221a(2\u03c0)\np1(x) = p(x[1])\np2(xy) = p(xy[1]) * p(xy[2])\np3(xyz) = p(xyz[1]) * p(xyz[2]) * p(xyz[3])\np4(xyzw) = p(xyzw[1]) * p(xyzw[2]) * p(xyzw[3]) * p(xyzw[4])\n\nfunction mybench(m::Module)\n    @info \"start bench $m\"\n    # 1 \u6b21\u5143\u7528\u306e\u30eb\u30fc\u30c1\u30f3\n    @btime $m.hquadrature(p, -10, 10)[1]\n    # \u591a\u6b21\u5143\u7528\u306e\u30eb\u30fc\u30c1\u30f3\u3067\u8a66\u3059\n    @btime $m.hcubature(p1, [-10], [10])[1]\n    @btime $m.hcubature(p2, [-10, -10], [10, 10])[1]\n    @btime $m.hcubature(p3, [-10, -10, -10], [10, 10, 10])[1]\n    @btime $m.hcubature(p4, [-10, -10, -10, -10], [10, 10, 10, 10])[1]\n    @info \"end bench $m\"\nend\n\nmybench(Cubature)\nmybench(HCubature)\n@info \"Appendix QuadGK\"\n# one-dimensional numerical integration\n@btime QuadGK.quadgk(p, -10, 10)[1]\n", "meta": {"hexsha": "2b0c18c8852d8ffc56ffa85738300134cc1f8a57", "size": 809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "integralExer/integral.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": "integralExer/integral.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": "integralExer/integral.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": 26.9666666667, "max_line_length": 70, "alphanum_fraction": 0.5920889988, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7507496423151374}}
{"text": "function jt11c()\n#\n#  test polynomial suggested by Jenkins and Traub\n#\n    m = 25;\n    y = exp.((im*pi) .*  (1-m:m-1) ./ (2*m))\n    z = 0.9*exp.((im*pi) .* (m:3*m) ./ (2*m))\n    u = [y; z]\n    p = poly(u)\n    z = [u ones(length(u))]\n    p, PolyZeros(z)\nend\n", "meta": {"hexsha": "3b830b61794e112463b31bcbb312e00f7067e039", "size": 257, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsuit/jt11c.m.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": "test/testsuit/jt11c.m.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": "test/testsuit/jt11c.m.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.7692307692, "max_line_length": 49, "alphanum_fraction": 0.4708171206, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7507496335994113}}
{"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\u00d73 Symmetric{Int64,Array{Int64,2}}:\n 1  2  3\n 2  5  6\n 3  6  9\n3\u00d73 Hermitian{Int64,Array{Int64,2}}:\n 1  2  3\n 2  5  6\n 3  6  9\n3\u00d73 UpperTriangular{Int64,Array{Int64,2}}:\n 1  2  3\n \u22c5  5  6\n \u22c5  \u22c5  9\n3\u00d73 LowerTriangular{Int64,Array{Int64,2}}:\n 1  \u22c5  \u22c5\n 4  5  \u22c5\n 7  8  9\n3\u00d73 Tridiagonal{Int64,Array{Int64,1}}:\n 1  2  \u22c5\n 4  5  6\n \u22c5  8  9\n3\u00d73 Diagonal{Int64,Array{Int64,1}}:\n 1  \u22c5  \u22c5\n \u22c5  5  \u22c5\n \u22c5  \u22c5  9\n3\u00d73 SymTridiagonal{Int64,Array{Int64,1}}:\n 1  5  \u22c5\n 5  2  6\n \u22c5  6  3\n3\u00d73 Bidiagonal{Int64,Array{Int64,1}}:\n 1  5  \u22c5\n \u22c5  2  6\n \u22c5  \u22c5  3\n3\u00d73 Bidiagonal{Int64,Array{Int64,1}}:\n 1  \u22c5  \u22c5\n 5  2  \u22c5\n \u22c5  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": "function toh01()\n#\n#  generalization of K.C. Toh and L. N. Trefethen\n# \n    k = [(-10:9)...]\n    z = 2.0 .* (k .+ 0.5) ./ 19 + im .* sin.((2*pi) .* (k .+ 0.5) ./ 19)\n    p = poly(z)\n    z = [z ones(20)]\n\n    p, PolyZeros(z)\nend\n", "meta": {"hexsha": "22d74b580d5eaf8093eb8ee4cb34b84d0acbbfd6", "size": 228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsuit/toh01.m.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": "test/testsuit/toh01.m.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": "test/testsuit/toh01.m.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.0, "max_line_length": 72, "alphanum_fraction": 0.4429824561, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7507496314792311}}
{"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 * \u221a(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, \u00c2,\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*\u00c2)*w - (c2*\u00c2)*v) / ((1f0+c3*\u00c2+c4)*\u00c2)\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*\u03c0/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        \u00c2 = 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, $\u00c2,\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(\u00c2); 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*\u03c0/N); epsn = Float32(h * 3); C = Float32(2/epsn); tau = Float32(epsn * h)\n    k = [0:N/2; -N/2+1:-1]\n    \u00c2 = 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) .* \u00c2) .* w .- (c2 .* \u00c2) .* v) ./ ((1f0 + c3 .* \u00c2 .+ c4) .* \u00c2)\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\u2c7c, t\u1d62) 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": "@testset \"cg\" begin\n\n#test cg.jl\n\n#positive semidefinite matrix\nA=randn(200,100);  A=A'*A;\nxt=randn(100)\nb=A*xt\n\n#inexact\n(x,flag,relres,iter1) = cg(A,b,tol=1e-5,maxIter=1000,out=0);\n@test norm(A*x-b)/norm(b) <= 1e-5\n\n#test if very accurate solution can be achieved\n(x,flag,relres,iter) = cg(A,b,tol=1e-14,maxIter=1000,out=0);\n@test norm(A*x-b)/norm(b) <= 1.01e-14\n\n#test with very good initial guess\nx=deepcopy(xt) .+ eps();\n(x,flag,relres,iter2) = cg(A,b,tol=1e-5,maxIter=1000,x=x,out=0);\n@test norm(A*x-b)/norm(b) <= 1e-5\n@test iter2<iter1 #test if the very good initial guess reduced the number of iterations\n\n#test if the output is the input when the initial guess is the true solution\nx=deepcopy(xt);\n(x,flag,relres,iter2) = cg(A,b,tol=1e-14,maxIter=1000,x=x,out=0);\n@test norm(A*x-b)/norm(b) <= 1e-14\n@test iter2==1\n@test x==xt\n\n#test if simple preconditioner reduces the number of iterations\nA=diagm(0 => (1:1:100))\n(x1,flag,relres1,iter1) = cg(A,b,tol=1e-12,maxIter=1000,out=0); #unpreconditioned cg\nPrec(input) = input./diag(A); #Jacobi preconditioner\n(x2,flag,relres2,iter2) = cg(A,b,tol=1e-12,maxIter=1000,M=Prec,out=0);\n@test iter2<iter1\n\nend\n", "meta": {"hexsha": "7a759ce0d25f9beb67a0e3bfa27d179726c7bdf6", "size": 1156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_cg.jl", "max_stars_repo_name": "slimgroup/SetIntersectionProjection", "max_stars_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "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": "test/test_cg.jl", "max_issues_repo_name": "slimgroup/SetIntersectionProjection", "max_issues_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "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": "test/test_cg.jl", "max_forks_repo_name": "slimgroup/SetIntersectionProjection", "max_forks_repo_head_hexsha": "d7dd8cf018bb960fa626e761e62b865e2725b466", "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.641025641, "max_line_length": 87, "alphanum_fraction": 0.6980968858, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7507494061778782}}
{"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# \u2554\u2550\u2561 6b359fc5-ec8d-47ec-89ec-b1b214a37a82\nbegin\n\tusing PlutoUI # user-interface do Pluto.jl\n\tusing Plots  # Julia package para gr\u00e1ficos \n\tusing Dierckx  # Julia package para interpola\u00e7\u00e3o/extrapola\u00e7\u00e3o de dados\nend\n\n# \u2554\u2550\u2561 c7838496-100f-4901-abcf-0d4e59fbc4a9\nhtml\"<button onclick='present()'>present</button>\"\n\n# \u2554\u2550\u2561 44201f7b-84df-4b8d-aeec-0f142ac2008b\nmd\"\"\"\n# M\u00e1quinas de corrente cont\u00ednua (Ex. 7)\nMotores de corrente cont\u00ednua, exerc\u00edcio 7:\n\"\"\"\n\n# \u2554\u2550\u2561 ed4846d5-70d2-4deb-9a4a-41cdc8c99bdd\nmd\"\"\"\n**Considere um motor de corrente cont\u00ednua, com a seguinte chapa de caracter\u00edsticas:**\n\"\"\"\n\n# \u2554\u2550\u2561 1301d1ad-89e8-4282-ab35-1a6b8214bea0\n(P\u1d64, U\u2099, n\u2099, \u03b7\u2099, R\u1d62, R\u209b, Ns, Rd, Nd)=(17e3, 250, 1200, 0.85, 0.6, 0.1, 12, 200, 3000)\n\n# \u2554\u2550\u2561 1a427cf6-b2d3-4d9b-9cb5-4682d5f49869\nbegin\n\tnmag=1200 # velocidade angular da caracter\u00edstica magn\u00e9tica, 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\u2080=[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\u2080, title=\"E\u2080=f(I\u2091\u2093), n=1200rpm\", xlabel = \"I\u2091\u2093 (A)\", ylabel=\"E\u2080 (V)\", ylims=(0,300), framestyle = :origin, minorticks=10, label=:none, linewidth=2)\nend\n\n# \u2554\u2550\u2561 e2fc78d6-480b-4fe0-b844-0d4329c0d572\nmd\"\"\"\n## Influ\u00eancia de $$\u0394E$$ \ud83d\udcbb\n\"\"\"\n\n# \u2554\u2550\u2561 8bde3ad9-2d03-4557-ab50-a89ac8e834a3\nmd\"\"\"\n!!! nota\n\tNo enunciado original n\u00e3o \u00e9 considerada a exist\u00eancia de reac\u00e7\u00e3o magn\u00e9tica do induzido, $$(\u0394E=0\\rm V)$$.  \n\tNo entanto, na vers\u00e3o *notebook* para que se possa verificar a influ\u00eancia de $$\u0394E$$, nas caracter\u00edsticas de funcionamento do motor DC, para os diferentes tipos de excita\u00e7\u00e3o, uma curva de $$\u0394E=f(I_i)$$ \u00e9 considerada como uma op\u00e7\u00e3o de an\u00e1lise.\"\"\"\n\n# \u2554\u2550\u2561 61238dc4-3c9d-4b59-9486-501988806c27\n\"Com \u0394E?\", @bind z CheckBox()\n\n# \u2554\u2550\u2561 c4d5e3f9-7808-48f6-8d33-05607d8e5a4e\nbegin\n\tI\u1d62=[0.0:15:120;]\n\t#I\u1d62=[0.0, 15, 30, 45, 60, 75, 90, 105, 120]\n\t\u0394E=[0.0, 1.5, 4, 7.5, 12, 17, 23, 30.5, 40]*z\n\tplot(I\u1d62, \u0394E, title=\"\u0394E=f(I\u1d62)\", xlabel = \"I\u1d62 (A)\", ylabel=\"\u0394E (V)\", xlims=(0,120), ylims=(0,40), framestyle = :origin, minorticks=5, label=:none, linewidth=2)\nend\n\n# \u2554\u2550\u2561 f6fcec56-b080-4016-baf0-0ab728f255f3\nmd\"\"\"\n## **a) $$R_c$$ para condi\u00e7\u00f5es nominais**\n**Com o motor em excita\u00e7\u00e3o deriva\u00e7\u00e3o, determine o valor do re\u00f3stato de campo, nas\ncondi\u00e7\u00f5es nominais $$(U_n, I_n, n_n)$$**;\n\"\"\"\n\n# \u2554\u2550\u2561 d9e431c5-be62-40c8-b5d6-59d5808e4436\nmd\"\"\"\nPara se ter a informa\u00e7\u00e3o completa das condi\u00e7\u00f5es nominais do motor, falta determinar o valor da corrente nominal, $$I_n$$.\\\nDa chapa de caracter\u00edsticas do motor conhecem-se a pot\u00eancia \u00fatil (pot\u00eancia mec\u00e2nica) e rendimento nominais, $$P_u$$ e $$\\eta_n$$, respectivamente, o que permite obter a pot\u00eancia absorvida, $$P_{ab}=U_nI_n$$. Assim: \n\"\"\"\n\n# \u2554\u2550\u2561 cde4847b-6c38-4bc6-a869-514774630c89\nmd\"\"\"\n$$I_n=\\frac{P_n}{\\eta U_n}$$\n\"\"\"\n\n# \u2554\u2550\u2561 1c70002d-e3fb-4d81-b0f9-ed00d69173ff\nI\u2099=P\u1d64/(\u03b7\u2099*U\u2099);\n\n# \u2554\u2550\u2561 5b4c1912-126d-4fe8-87c5-f65b299f3642\nmd\"\"\"\nCalculando obt\u00e9m-se $$I_n=$$ $(I\u2099)A\n\"\"\"\n\n# \u2554\u2550\u2561 d8d6a6e9-df8d-47d2-832a-0d2126ce760e\nmd\"\"\"\nA velocidade, $$n$$, \u00e9 dependente do fluxo magn\u00e9tico, $$k\u03d5_0$$, que por sua vez depende da corrente de excita\u00e7\u00e3o, $$I_d$$ e da caracter\u00edstica magn\u00e9tica da m\u00e1quina.\\\nAssim, a imagem do fluxo magn\u00e9tico presente na m\u00e1quina \u00e9 dada pela a for\u00e7a contra-electromotriz de vazio do motor, $$E_0^{'}$$:\n\"\"\"\n\n# \u2554\u2550\u2561 0ff562ff-7af2-4749-87f5-8766cb695893\nmd\"\"\"\n$$E_0^{'}=E^{'}+\u0394E$$\nSendo a  a for\u00e7a contra-electromotriz efectiva, $$E^{'}$$, dada por:\\\n\"\"\"\n\n# \u2554\u2550\u2561 cf0f089a-1901-4ad1-8fe9-b9028679b109\nmd\"\"\"\n$$E^{'}=U-R_iI_i$$\n\"\"\"\n\n# \u2554\u2550\u2561 de954f1d-a3ac-4830-acd0-85e64afdf0cd\n# forma computacional de consultar a curva de \u0394E(Ii), por interpola\u00e7\u00e3o dos dados atrav\u00e9s do Pkg Dierckx.jl\nbegin\n\t\u0394E_int=Spline1D(I\u1d62,\u0394E)  \n\t\u0394E\u2099=\u0394E_int(I\u2099)\n\t\u0394E\u2099=round(\u0394E\u2099, digits=1)\nend;\n\n# \u2554\u2550\u2561 68969be8-0bee-4cca-85de-7a8d2aa35ee2\nmd\"\"\"\nO valor de $$\u0394E$$ para $$I_n$$, consultando a sua curva de q.d.t \u00e9: $$\u0394E=$$ $(\u0394E\u2099)V.  \n\"\"\"\n\n\n# \u2554\u2550\u2561 8f5b0bd5-7a65-4ba3-bdd1-7cc3128fa8d8\nE=U\u2099-R\u1d62*I\u2099;\n\n# \u2554\u2550\u2561 7d6a01a4-4876-42dc-ab66-f7f736d41a32\nE\u2080\u2099=E+\u0394E\u2099;\n\n# \u2554\u2550\u2561 0a35c6dc-0967-4f8a-9fff-904f9062eeab\nmd\"\"\"\nCalculando as f.c.e.m., obt\u00eam-se $$E^{'}=$$ $(E)V e $$E_0^{'}=$$ $(E\u2080\u2099)V.\n\"\"\"\n\n# \u2554\u2550\u2561 9d82a20f-3a14-4796-88e9-e27720632bbd\nmd\"\"\"\n\nNote que tomou-se a corrente do rotor aproximadamente igual \u00e0 corrente absorvida, $$I_i\\simeq I_n$$, sendo no entanto, $$I_i=I_n+I_d$$. Contudo, n\u00e3o se est\u00e1 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\u00e1lculo de $$E_0^{'}$$ e uma vez que $$I_d$$ ainda n\u00e3o est\u00e1 calculada.\n\"\"\"\n\n# \u2554\u2550\u2561 04b517f9-ed9f-4a5d-929b-82b10de843b9\nmd\"\"\"\nA caracter\u00edstica magn\u00e9tica foi obtida \u00e0 mesma velocidade inscrita na chapa de caracter\u00edsticas da m\u00e1quina, $$n_n$$, por conseguinte, obt\u00e9m-se dela directamente a corrente de campo, $$I_d$$.\n\"\"\"\n\n# \u2554\u2550\u2561 cfc7844e-3974-46ef-a53a-ee6a1a85d7f3\n# forma computacional de consultar a caracter\u00edstica magn\u00e9tica, por interpola\u00e7\u00e3o dos dados atrav\u00e9s do Pkg Dierckx.jl\nbegin\n\tId_int=Spline1D(E\u2080,Iex)  \n\tId=Id_int(E\u2080\u2099)\n\tId=round(Id, digits=2)\nend;\n\n# \u2554\u2550\u2561 71356175-ffe4-4c3a-a895-8a4be8713a44\nmd\"\"\"\nConsultando a caracter\u00edstica magn\u00e9tica a 1200rpm, verifica-se para $$E\u2080=$$ $(E\u2080\u2099)V $$\\Rightarrow$$ $$I_d=$$ $(Id)A.\n\"\"\"\n\n# \u2554\u2550\u2561 d85a5505-1ab5-43d0-97ad-a0cb4a220c06\nmd\"\"\"\nAssim, o reostato de campo para colocar o motor *shunt* nas condi\u00e7\u00f5es nominais \u00e9 dado por:\n\"\"\"\n\n# \u2554\u2550\u2561 7c572ab7-2292-423c-b611-68573b289265\nmd\"\"\"\n$$R_c=\\frac{U_n}{I_d}-R_d$$\n\"\"\"\n\n# \u2554\u2550\u2561 14ad0875-e27a-442e-81e9-29d1abaeac17\nbegin\n\tRc=U\u2099/Id-Rd\n\tRc=round(Rc, digits=1)\nend;\n\n# \u2554\u2550\u2561 50022e39-c2f4-455f-8d26-7c9246190b11\nmd\"\"\"\nCalculando, obt\u00e9m-se $$R_c=$$ $(Rc)\u2126\n\"\"\"\n\n# \u2554\u2550\u2561 4bac08e5-7a7a-496f-8d67-aa2bc4b10236\nmd\"\"\"\n> Poder\u00e1 ent\u00e3o observar as diferen\u00e7as de c\u00e1lculo relativas \u00e0 presen\u00e7a de q.d.t. devido \u00e0 reac\u00e7\u00e3o magn\u00e9tica do induzido, ou seja, uma m\u00e1quina com p\u00f3los auxiliares (caso mais frequente), conduz a $$\u0394E \\neq 0$$V, vari\u00e1vel em fun\u00e7\u00e3o da corrente do induzido. No caso de uma m\u00e1quina com p\u00f3los auxiliares e enrolamentos de compensa\u00e7\u00e3o, a reac\u00e7\u00e3o magn\u00e9tica do induzido estar\u00e1 compensada e assim tem-se:\n\"\"\"\n\n# \u2554\u2550\u2561 5abe64cf-9291-48d6-bf60-7335551ee791\nmd\"\"\"\n$$\u0394E=0 \\Rightarrow E_0^{'}=E^{'}$$\n\"\"\"\n\n# \u2554\u2550\u2561 ac32afe0-e30f-402e-995e-8b0cacf8af10\n\n\n# \u2554\u2550\u2561 4989ff81-ac16-446c-8d8a-e3cb9e5950b6\nmd\"\"\"\n## **b) Motor shunt**\n**Utilizando o re\u00f3stato de campo calculado na al\u00ednea anterior, determine as caracter\u00edsticas de velocidade, bin\u00e1rio e mec\u00e2nica deste motor (excita\u00e7\u00e3o deriva\u00e7\u00e3o);**\n\"\"\"\n\n# \u2554\u2550\u2561 1d458a5a-545f-4ab6-900b-9d84ebbaf51d\nmd\"\"\"\n> Na resolu\u00e7\u00e3o computacional para o **motor de excita\u00e7\u00e3o deriva\u00e7\u00e3o**, as grandezas calculadas est\u00e3o identificadas como: k$$\u03d5$$\u2080\u2081, n\u2081, E\u2081, \u03c9\u2081, Td\u2081\n\"\"\"\n\n# \u2554\u2550\u2561 d25759bf-6e81-439c-a2c9-c19704379437\nbegin\n\tk\u03d5\u2080\u2081=E\u2080\u2099/nmag\n\tk\u03d5\u2080\u2081=round(k\u03d5\u2080\u2081, digits=3)\nend;\n\n# \u2554\u2550\u2561 4652d9e4-e2c6-47c4-93d1-1e360ffb7e57\nmd\"\"\"\nTomando o valor calculado de $$R_c=$$ $(Rc)\u2126, resulta $$I_d=$$ $(Id)A, o que permite calcular o fluxo magn\u00e9tico da m\u00e1quina em vazio, $$k\u03d5\u2080$$, que no motor de excita\u00e7\u00e3o deriva\u00e7\u00e3o permanece constante.  \nAssim, $$k\u03d5\u2080=$$ $(k\u03d5\u2080\u2081)V/rpm\n\"\"\"\n\n# \u2554\u2550\u2561 4629c049-8882-4823-bdea-93e3d70cc901\nmd\"\"\"\nA determina\u00e7\u00e3o da caracter\u00edstica de velocidade $$n=f(I)$$ ou $$n=f(I_i)$$, uma vez que $$I_i\\simeq I$$, consiste em sucessivamente realizar o c\u00e1lculo da velocidade do motor para diferentes valores de corrente:  \n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 6030b931-51a0-42fc-9b74-5635b590e6f5\n# Caracter\u00edstica de velocidade:\nbegin\n\tI=0:1:1.5*I\u2099\n\tIi=I.-Id\n\t\u0394E\u1d62=\u0394E_int(Ii)\n\tn\u2081=(U\u2099.-R\u1d62*Ii.+\u0394E\u1d62)/k\u03d5\u2080\u2081\nend;\n\n# \u2554\u2550\u2561 d47a90f0-f8bc-44d0-b71c-c0bc59d0d23c\nmd\"\"\"\nSimilarmente, a caracter\u00edstica de bin\u00e1rio, $$T=f(I)$$ ou $$T=f(I_i)$$, podendo $$T$$ ser o bin\u00e1rio desenvolvido, $$T_d$$, ou o bin\u00e1rio \u00fatil, $$T_u$$, atendendo que: $$T_d=T_u+T_p$$, consiste em sucessivamente realizar o c\u00e1lculo do bin\u00e1rio para diferentes valores de corrente:  \n\"\"\"\n\n# \u2554\u2550\u2561 3c921729-6534-4eac-abb0-4eb362295b91\nmd\"\"\"\n$$T_d=\\frac{E^{'}}{\u03c9}I_i\\:\\:\\:;\\:\\:\\:\u03c9=\\frac{2\u03c0n}{60}$$ com $$\u03c9$$ em rad/s.\n\"\"\"\n\n# \u2554\u2550\u2561 4da7f391-e3bf-4e12-aa6b-a7ef5e45d3b9\n# Caracter\u00edstica de bin\u00e1rio:\nbegin\n\tE\u2081=U\u2099.-R\u1d62*Ii\n\t\u03c9\u2081=2\u03c0.*n\u2081/60\n\tTd\u2081=(E\u2081./\u03c9\u2081).*Ii\nend;\n\n# \u2554\u2550\u2561 df3609ef-80f2-464a-b522-f289ea9344b4\n\n\n# \u2554\u2550\u2561 f499659c-b042-4002-bb27-980daf8502d4\nmd\"\"\"\n## **c) Motor excita\u00e7\u00e3o composta** \n**Idem, com excita\u00e7\u00e3o composta em longa deriva\u00e7\u00e3o aditiva e subtrativa. Representar as caracter\u00edsticas nos mesmos gr\u00e1ficos para compara\u00e7\u00e3o;**\n\"\"\"\n\n# \u2554\u2550\u2561 72a079e6-0c41-4c50-9ee2-838d5cc60c85\nmd\"\"\"\nNo motor de excita\u00e7\u00e3o composta, o fluxo magn\u00e9tico depende da contribui\u00e7\u00e3o das for\u00e7as magnetomotrizes de ambos os enrolamentos de excita\u00e7\u00e3o e da forma como estes est\u00e3o ligados entre si (de forma aditiva ou subtractiva):\n\"\"\"\n\n# \u2554\u2550\u2561 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\u00e7\u00e3o s\u00e9rie.\n\"\"\"\n\n# \u2554\u2550\u2561 f305c434-9d0c-497d-8335-bf25aa80e915\nmd\"\"\"\nAssim, $$I_{ex}$$ \u00e9 a corrente de campo que representa o fluxo total da m\u00e1quina, sendo obtida por:\n\"\"\"\n\n# \u2554\u2550\u2561 0ce81a6e-965c-4dc0-b9f3-f8c09143460e\nmd\"\"\"\n$$I_{ex}=I_d \\pm \\frac{N_s}{N_d}I_s$$\n\"\"\"\n\n# \u2554\u2550\u2561 1cd42258-7583-4288-9c6d-4d47facb69e1\nmd\"\"\"\nAssim, a caracter\u00edstica de velocidade para o motor de excita\u00e7\u00e3o composta em longa deriva\u00e7\u00e3o \u00e9 obtida por c\u00e1lculo sucessivo da velocidade do motor para diferentes valores de corrente, atrav\u00e9s de:  \n\"\"\"\n\n# \u2554\u2550\u2561 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\u00e9s da caracter\u00edstica magn\u00e9tica da m\u00e1quina.\n\"\"\"\n\n# \u2554\u2550\u2561 6aae7842-4889-4be6-bd1d-eab44c610af8\n\n\n# \u2554\u2550\u2561 7ad852d3-e3b8-4799-8aae-a52c1ebe34ac\nmd\"\"\"\n> Na resolu\u00e7\u00e3o computacional para o **motor de excita\u00e7\u00e3o composta aditiva**, as grandezas calculadas est\u00e3o identificadas como: `Iex\u2082`, `E\u2080\u2082`, `k\u03d5\u2080\u2082`, `n\u2082`, `E\u2082`, `\u03c9\u2082`, `Td\u2082`\n\"\"\"\n\n# \u2554\u2550\u2561 b4e5cbd1-c1c1-47e1-a8aa-8fc2ef628e87\nbegin\n\tIex\u2082=Id.+(Ns/Nd)*Ii\n\tE\u2080_int1=Spline1D(Iex, E\u2080)  # fun\u00e7\u00e3o de interpola\u00e7\u00e3o para a caract. magn\u00e9tica\n\tE\u2080\u2082=E\u2080_int1(Iex\u2082) # fem que cont\u00e9m os fluxos deriva\u00e7\u00e3o + s\u00e9rie\n\tk\u03d5\u2080\u2082=E\u2080\u2082/nmag\n\tn\u2082=(U\u2099.-(R\u1d62+R\u209b)*Ii.+\u0394E\u1d62)./k\u03d5\u2080\u2082\n\tE\u2082=U\u2099.-(R\u1d62+R\u209b)*Ii\n\t\u03c9\u2082=2\u03c0.*n\u2082/60\n\tTd\u2082=(E\u2082./\u03c9\u2082).*Ii\nend;\n\n# \u2554\u2550\u2561 55397202-48ae-4a3d-a053-9f46e6638560\n\n\n# \u2554\u2550\u2561 1a154f27-cd9a-4de8-b850-599b5e810811\nmd\"\"\"\n> Na resolu\u00e7\u00e3o computacional para o **motor de excita\u00e7\u00e3o composta subractiva**, as grandezas calculadas est\u00e3o identificadas como: `Iex\u2083`, `E\u2080\u2083`, `k\u03d5\u2080\u2083`, `n\u2083`, `\u03c9\u2083`, `Td\u2083`\n\"\"\"\n\n# \u2554\u2550\u2561 626c5cab-64e2-446c-9d38-f01dde099d3e\nbegin\n\tIex\u2083=Id.-(Ns/Nd)*Ii\n\tE\u2080\u2083=E\u2080_int1(Iex\u2083) #fem que cont\u00e9m os fluxos deriva\u00e7\u00e3o - s\u00e9rie\n\tk\u03d5\u2080\u2083=E\u2080\u2083/nmag\n\tn\u2083=(U\u2099.-(R\u1d62+R\u209b)*Ii.+\u0394E\u1d62)./k\u03d5\u2080\u2083\n\t\u03c9\u2083=2\u03c0.*n\u2083/60\n\tTd\u2083=(E\u2082./\u03c9\u2083).*Ii\nend;\n\n# \u2554\u2550\u2561 1c659ae6-1b29-43a5-92f7-30b1f24c3696\n\n\n# \u2554\u2550\u2561 426c40b4-5fa1-4d8a-b03c-11f3008484f6\nmd\"\"\"\n## **d) Motor s\u00e9rie**\n**Determinar as curvas caracter\u00edsticas com o circuito de deriva\u00e7\u00e3o desligado (motor s\u00e9rie). Representar as caracter\u00edsticas nos mesmos gr\u00e1ficos para compara\u00e7\u00e3o;**\n\"\"\"\n\n# \u2554\u2550\u2561 8dfd7146-2e55-4ea0-8cf2-3557d89e96e1\nmd\"\"\"\n> Na resolu\u00e7\u00e3o computacional para o **motor de excita\u00e7\u00e3o s\u00e9rie**, as grandezas calculadas est\u00e3o identificadas como: Iex\u2084, E\u2080\u2084, k$$\u03d5$$\u2080\u2084, n\u2084, \u03c9\u2084, Td\u2084\n\"\"\"\n\n# \u2554\u2550\u2561 4e4469c8-994d-42c6-b373-8f295768b8b0\nbegin\n\tIex\u2084=(Ns/Nd)*Ii\n\tE\u2080\u2084=E\u2080_int1(Iex\u2084) #fem que cont\u00e9m apenas fluxo s\u00e9rie\n\tk\u03d5\u2080\u2084=E\u2080\u2084/nmag\n\tn\u2084=(U\u2099.-(R\u1d62+R\u209b)*Ii.+\u0394E\u1d62)./k\u03d5\u2080\u2084\n\t\u03c9\u2084=2\u03c0.*n\u2084/60\n\tTd\u2084=(E\u2082./\u03c9\u2084).*Ii\nend;\n\n# \u2554\u2550\u2561 a45ad7c2-2f83-4e04-bdaf-8dcc30a150f5\n# Caracter\u00edsticas de velocidade, plots:\nbegin\n\tplot(I, n\u2081, linewidth=2, title=\"Caracter\u00edsticas de velocidade\", xlabel = \"I (A)\", ylabel=\"n (rpm)\",  framestyle = :origin, minorticks=5, label=\"shunt\")\n\tplot!(I,n\u2082, linewidth=2, label=\"comp. aditivo\")\n\tplot!(I,n\u2083, linewidth=2, label=\"comp. subtractivo\", legend=:bottomleft)\n\tplot!(I,n\u2084, linewidth=2, label=\"s\u00e9rie\", xlims=(0,120), ylims=(0,3000))\nend\n\n# \u2554\u2550\u2561 5b866db3-ddd6-4bfd-b027-761c07d6755c\n# Caracter\u00edsticas de bin\u00e1rio, plots:\nbegin\n\tplot(I, Td\u2081, linewidth=2, title=\"Caracter\u00edsticas de bin\u00e1rio\", xlabel = \"I (A)\", ylabel=\"Td (Nm)\",  framestyle = :origin, minorticks=5, label=\"shunt\")\n\tplot!(I,Td\u2082, linewidth=2, label=\"comp. aditivo\")\n\tplot!(I,Td\u2083, linewidth=2, label=\"comp. subtractivo\", legend=:topleft)\n\tplot!(I,Td\u2084, linewidth=2, label=\"s\u00e9rie\", xlims=(0,120), ylims=(0,250))\nend\n\n# \u2554\u2550\u2561 326135bd-24e3-492d-a7d5-1a14f065e80f\n# Caracter\u00edsticas mec\u00e2nicas, plots:\nbegin\n\tplot(Td\u2081, n\u2081, linewidth=2, title=\"Caracter\u00edsticas mec\u00e2nicas\", ylabel = \"n (rpm)\", xlabel=\"Td (Nm)\",  framestyle = :origin, minorticks=5, label=\"shunt\")\n\tplot!(Td\u2082, n\u2082, linewidth=2, label=\"comp. aditivo\")\n\tplot!(Td\u2083, n\u2083, linewidth=2, label=\"comp. subtractivo\", legend=:topright)\n\tplot!(Td\u2084, n\u2084, linewidth=2, label=\"s\u00e9rie\", xlims=(0,250), ylims=(0,3000))\nend\n\n# \u2554\u2550\u2561 66e32f84-8b2a-4a3d-81fe-16437ecc3c18\n\n\n# \u2554\u2550\u2561 60db00b7-c78b-4c26-9530-c62fcfd1bfd2\nmd\"\"\"\n## **e) MI: varia\u00e7\u00e3o $$n=f(I)$$ \ud83d\udcbb**\n**Considere o motor com excita\u00e7\u00e3o independente (MI), Uexc = 240V , com o re\u00f3stato de campo calculado na al\u00ednea a). Explicite a varia\u00e7\u00e3o da caracter\u00edstica de velocidade nas situa\u00e7\u00f5es:**\n1. **aumento de tens\u00e3o do induzido;**\n2. **diminui\u00e7\u00e3o do re\u00f3stato de campo;**\n3. **aumento da resist\u00eancia adicional.**\n\"\"\"\n\n# \u2554\u2550\u2561 4fdea2ae-3bf8-42cd-bf6f-411eaf8223c3\nmd\"\"\"\n> Na resolu\u00e7\u00e3o computacional para o **motor de excita\u00e7\u00e3o separada**, as grandezas calculadas est\u00e3o identificadas como: `Ui`, `Iex5`, `E\u2080\u2085`, `k\u03d5\u2080\u2085`, `\u0394E\u1d62\u1d62`, `n\u2085`, `\u03c9\u2085`, `Td\u2085`\n\"\"\"\n\n# \u2554\u2550\u2561 36295cf6-19ba-4240-9806-745ec0bfdccd\nbegin\n\tH1=(\"Tens\u00e3o 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\u00eancia adicional, Rad\", @bind Rad PlutoUI.Slider(0:0.1:1.5, default=0.0, show_value=true))\n\tH1, H2, H3\nend\n\n# \u2554\u2550\u2561 e648310c-8172-4cf0-ab72-f40229ba2577\nbegin\n\tUexc=240\n\tIex\u2085=Uexc/(Rc1+Rd)\n\tE\u2080\u2085=E\u2080_int1(Iex\u2085) #fem para excita\u00e7\u00e3o separada\n\tk\u03d5\u2080\u2085=E\u2080\u2085/nmag\n\t\u0394E\u1d62\u1d62=\u0394E_int(I)\n\tn\u2085=(Ui.-(R\u1d62+Rad)*I.+\u0394E\u1d62\u1d62)./k\u03d5\u2080\u2085\n\tE\u2085=Ui.-(R\u1d62+Rad)*I\n\t\u03c9\u2085=2\u03c0.*n\u2085/60\n\tTd\u2085=(E\u2085./\u03c9\u2085).*Ii\nend;\n\n# \u2554\u2550\u2561 4919a95d-cd66-401c-af76-6155087462a3\n# Caracter\u00edstica de velocidade vs. varia\u00e7\u00e3o de Ui, Rc1 ou Rad; plots:\nbegin\n\tplot(I, n\u2085, ylims=(0,3000),linewidth=2, framestyle = :origin, title=\"Varia\u00e7\u00e3o da caracter\u00edstica de velocidade\", label=:none, xlabel = \"I (A)\", ylabel=\"n (rpm)\", minorticks=5, xlims=(0,120))\nend\n\n# \u2554\u2550\u2561 8ad59666-3801-44a3-b26a-197a8f60db02\nmd\"\"\"\n!!! nota\n\t**Apresenta-se uma al\u00ednea f) id\u00eantica \u00e0 al\u00ednea anterior, mas considerando a caracter\u00edstica de bin\u00e1rio:**  \n\"\"\"\n\n# \u2554\u2550\u2561 babc5b0b-3263-47d5-bd33-56917ece1e6b\nmd\"\"\"\n## **f) MI: varia\u00e7\u00e3o $$T=f(I)$$ \ud83d\udcbb**\n**Considere o motor com excita\u00e7\u00e3o independente (MI), Uexc = 240V , com o re\u00f3stato de campo calculado na al\u00ednea a). Explicite a varia\u00e7\u00e3o da caracter\u00edstica de bin\u00e1rio nas situa\u00e7\u00f5es:**\n1. **aumento de tens\u00e3o do induzido;**\n2. **diminui\u00e7\u00e3o do re\u00f3stato de campo;**\n3. **aumento da resist\u00eancia adicional.**\n\"\"\"\n\n# \u2554\u2550\u2561 49cc56bc-bd1e-4e07-9d9c-0ccfaa92e7b0\n# Caracter\u00edstica de bin\u00e1rio vs. varia\u00e7\u00e3o de Ui, Rc1 ou Rad; plots:\nbegin\n\tplot(I, Td\u2085, ylims=(0,250),linewidth=2, framestyle = :origin, title=\"Varia\u00e7\u00e3o da caracter\u00edstica de bin\u00e1rio\", label=:none, xlabel = \"I (A)\", ylabel=\"Td (Nm)\", minorticks=5, xlims=(0,120))\nend\n\n# \u2554\u2550\u2561 0bda0726-fcf9-491d-ad24-301521cb5892\n\n\n# \u2554\u2550\u2561 f34820a6-bd96-463f-b747-2b910914d152\nmd\"\"\"\n# Setup\n\"\"\"\n\n# \u2554\u2550\u2561 50588330-7af4-4c41-af8d-ffbb4c074394\nTableOfContents(title=\"\ud83d\udcda \u00cdndice, Exerc\u00edcio 7\")\n\n# \u2554\u2550\u2561 e99f40c0-1752-4096-8fc9-c4550ae86168\nmd\"\"\"\n!!! info\n\tNo \u00edndice deste *notebook*, os t\u00f3picos assinalados com \"\ud83d\udcbb\" permitem interac\u00e7\u00e3o com o utilizador.\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 80c412ed-1cc3-42c0-acf6-56248b5aa327\nmd\"\"\"\n!!! info\n\t## Programa\u00e7\u00e3o _Julia_ e _notebooks Pluto_\n\tSaber mais sobre: [_Julia_/_Pluto_](https://github.com/Ricardo-Luis/notebooks/blob/main/ME2/README.md)\n\"\"\"\n\n# \u2554\u2550\u2561 e88b50d7-bd66-4e3c-8740-b1c5e36b6b5f\nversion=VERSION;\n\n# \u2554\u2550\u2561 a7d43c39-1780-446a-928a-1bc5cf841390\nmd\"\"\"\n## _Notebook_\n\n*Notebook* realizado em linguagem de programa\u00e7\u00e3o *Julia* vers\u00e3o $(version) para a unidade curricular de M\u00e1quinas El\u00e9tricas 2 (ISEL\\LEE) \\\n**Ricardo Lu\u00eds** (Professor Adjunto, ISEL\\DEEEA\\GDME) \\\nISEL, 23/Out/2021\n\"\"\"\n\n# \u2554\u2550\u2561 bfc8ce5b-3b3e-4448-bd60-23ed853a9ed9\nmd\"\"\"\nEste conte\u00fado possui licen\u00e7a [![](https://img.shields.io/badge/License-CC%20BY--SA%204.0-lightgrey.svg)](http://creativecommons.org/licenses/by-sa/4.0/).\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500c7838496-100f-4901-abcf-0d4e59fbc4a9\n# \u255f\u250044201f7b-84df-4b8d-aeec-0f142ac2008b\n# \u255f\u2500ed4846d5-70d2-4deb-9a4a-41cdc8c99bdd\n# \u2560\u25501301d1ad-89e8-4282-ab35-1a6b8214bea0\n# \u255f\u25001a427cf6-b2d3-4d9b-9cb5-4682d5f49869\n# \u255f\u2500e2fc78d6-480b-4fe0-b844-0d4329c0d572\n# \u255f\u25008bde3ad9-2d03-4557-ab50-a89ac8e834a3\n# \u255f\u250061238dc4-3c9d-4b59-9486-501988806c27\n# \u255f\u2500c4d5e3f9-7808-48f6-8d33-05607d8e5a4e\n# \u255f\u2500f6fcec56-b080-4016-baf0-0ab728f255f3\n# \u255f\u2500d9e431c5-be62-40c8-b5d6-59d5808e4436\n# \u255f\u2500cde4847b-6c38-4bc6-a869-514774630c89\n# \u255f\u25005b4c1912-126d-4fe8-87c5-f65b299f3642\n# \u2560\u25501c70002d-e3fb-4d81-b0f9-ed00d69173ff\n# \u255f\u2500d8d6a6e9-df8d-47d2-832a-0d2126ce760e\n# \u255f\u25000ff562ff-7af2-4749-87f5-8766cb695893\n# \u255f\u2500cf0f089a-1901-4ad1-8fe9-b9028679b109\n# \u255f\u250068969be8-0bee-4cca-85de-7a8d2aa35ee2\n# \u2560\u2550de954f1d-a3ac-4830-acd0-85e64afdf0cd\n# \u255f\u25000a35c6dc-0967-4f8a-9fff-904f9062eeab\n# \u2560\u25508f5b0bd5-7a65-4ba3-bdd1-7cc3128fa8d8\n# \u2560\u25507d6a01a4-4876-42dc-ab66-f7f736d41a32\n# \u255f\u25009d82a20f-3a14-4796-88e9-e27720632bbd\n# \u255f\u250004b517f9-ed9f-4a5d-929b-82b10de843b9\n# \u255f\u250071356175-ffe4-4c3a-a895-8a4be8713a44\n# \u2560\u2550cfc7844e-3974-46ef-a53a-ee6a1a85d7f3\n# \u255f\u2500d85a5505-1ab5-43d0-97ad-a0cb4a220c06\n# \u255f\u25007c572ab7-2292-423c-b611-68573b289265\n# \u255f\u250050022e39-c2f4-455f-8d26-7c9246190b11\n# \u2560\u255014ad0875-e27a-442e-81e9-29d1abaeac17\n# \u255f\u25004bac08e5-7a7a-496f-8d67-aa2bc4b10236\n# \u255f\u25005abe64cf-9291-48d6-bf60-7335551ee791\n# \u255f\u2500ac32afe0-e30f-402e-995e-8b0cacf8af10\n# \u255f\u25004989ff81-ac16-446c-8d8a-e3cb9e5950b6\n# \u255f\u25001d458a5a-545f-4ab6-900b-9d84ebbaf51d\n# \u255f\u25004652d9e4-e2c6-47c4-93d1-1e360ffb7e57\n# \u2560\u2550d25759bf-6e81-439c-a2c9-c19704379437\n# \u255f\u25004629c049-8882-4823-bdea-93e3d70cc901\n# \u255f\u2500ea81ca51-dccc-4187-b788-7ed64716e698\n# \u2560\u25506030b931-51a0-42fc-9b74-5635b590e6f5\n# \u255f\u2500d47a90f0-f8bc-44d0-b71c-c0bc59d0d23c\n# \u255f\u25003c921729-6534-4eac-abb0-4eb362295b91\n# \u2560\u25504da7f391-e3bf-4e12-aa6b-a7ef5e45d3b9\n# \u255f\u2500a45ad7c2-2f83-4e04-bdaf-8dcc30a150f5\n# \u255f\u25005b866db3-ddd6-4bfd-b027-761c07d6755c\n# \u255f\u2500326135bd-24e3-492d-a7d5-1a14f065e80f\n# \u255f\u2500df3609ef-80f2-464a-b522-f289ea9344b4\n# \u255f\u2500f499659c-b042-4002-bb27-980daf8502d4\n# \u255f\u250072a079e6-0c41-4c50-9ee2-838d5cc60c85\n# \u255f\u250058e9df34-7471-4942-ac06-2505f52875f2\n# \u255f\u2500f305c434-9d0c-497d-8335-bf25aa80e915\n# \u255f\u25000ce81a6e-965c-4dc0-b9f3-f8c09143460e\n# \u255f\u25001cd42258-7583-4288-9c6d-4d47facb69e1\n# \u255f\u2500facb1900-1093-46c7-97b2-187b67e21294\n# \u255f\u25006aae7842-4889-4be6-bd1d-eab44c610af8\n# \u255f\u25007ad852d3-e3b8-4799-8aae-a52c1ebe34ac\n# \u2560\u2550b4e5cbd1-c1c1-47e1-a8aa-8fc2ef628e87\n# \u255f\u250055397202-48ae-4a3d-a053-9f46e6638560\n# \u255f\u25001a154f27-cd9a-4de8-b850-599b5e810811\n# \u2560\u2550626c5cab-64e2-446c-9d38-f01dde099d3e\n# \u255f\u25001c659ae6-1b29-43a5-92f7-30b1f24c3696\n# \u255f\u2500426c40b4-5fa1-4d8a-b03c-11f3008484f6\n# \u255f\u25008dfd7146-2e55-4ea0-8cf2-3557d89e96e1\n# \u2560\u25504e4469c8-994d-42c6-b373-8f295768b8b0\n# \u255f\u250066e32f84-8b2a-4a3d-81fe-16437ecc3c18\n# \u255f\u250060db00b7-c78b-4c26-9530-c62fcfd1bfd2\n# \u255f\u25004fdea2ae-3bf8-42cd-bf6f-411eaf8223c3\n# \u2560\u2550e648310c-8172-4cf0-ab72-f40229ba2577\n# \u255f\u250036295cf6-19ba-4240-9806-745ec0bfdccd\n# \u255f\u25004919a95d-cd66-401c-af76-6155087462a3\n# \u255f\u25008ad59666-3801-44a3-b26a-197a8f60db02\n# \u255f\u2500babc5b0b-3263-47d5-bd33-56917ece1e6b\n# \u255f\u250049cc56bc-bd1e-4e07-9d9c-0ccfaa92e7b0\n# \u2560\u25500bda0726-fcf9-491d-ad24-301521cb5892\n# \u255f\u2500f34820a6-bd96-463f-b747-2b910914d152\n# \u2560\u255050588330-7af4-4c41-af8d-ffbb4c074394\n# \u255f\u2500e99f40c0-1752-4096-8fc9-c4550ae86168\n# \u255f\u25008e683ba6-fe89-41d5-8f0a-5e3e59ca747c\n# \u2560\u25506b359fc5-ec8d-47ec-89ec-b1b214a37a82\n# \u255f\u250080c412ed-1cc3-42c0-acf6-56248b5aa327\n# \u255f\u2500a7d43c39-1780-446a-928a-1bc5cf841390\n# \u255f\u2500e88b50d7-bd66-4e3c-8740-b1c5e36b6b5f\n# \u255f\u2500bfc8ce5b-3b3e-4448-bd60-23ed853a9ed9\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-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 GlobalOptimizer, Test\n\n@testset \"Solve Ackley Function\" begin\n    # Define an objective function (using Ackley function here as an example)\n    function ackley(x::AbstractVector{T}) where T<:Real\n        arg1 = 0.0\n        arg2 = 0.0\n        dims = length(x)\n        @inbounds for i in eachindex(x)\n            arg1 += abs2(x[i])\n            arg2 += cospi(2.0 * x[i])\n        end\n        arg1  = 0.2 * sqrt(arg1 / dims)\n        arg2 /= dims\n        return -20.0 * exp(-arg1) - exp(arg2) + \u212f + 20.0\n    end\n\n    nd  = 15\n    lb  = ntuple(i -> -32.0, nd) # lower bounds\n    ub  = ntuple(i -> +32.0, nd) # upper bounds\n    obj = minimizer(nd)          # create an object for the optimization\n    minimize!(obj, ackley, lb, ub, avgtimes=3)\n    @test obj.xsol \u2248 zeros(Float64, nd) atol=1e-12\nend\n", "meta": {"hexsha": "814e33d8db5ded8774898055eeff907247ce270d", "size": 797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "brianyjtai1994/GlobalOptimizer.jl", "max_stars_repo_head_hexsha": "4086d52155f41d0d4fd5f57b11daf76966771073", "max_stars_repo_licenses": ["MIT"], "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": "brianyjtai1994/GlobalOptimizer.jl", "max_issues_repo_head_hexsha": "4086d52155f41d0d4fd5f57b11daf76966771073", "max_issues_repo_licenses": ["MIT"], "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": "brianyjtai1994/GlobalOptimizer.jl", "max_forks_repo_head_hexsha": "4086d52155f41d0d4fd5f57b11daf76966771073", "max_forks_repo_licenses": ["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.88, "max_line_length": 77, "alphanum_fraction": 0.5633626098, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.75074243007801}}
{"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(\u03bc=10.0, \u03c3=1.5)\r\nparams(n1) # (10.0,1.5)\r\nfieldnames(n1) # 2-element Array{Symbol,1}:  :\u03bc :\u03c3\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  \u2026  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(\u0394t, flux, mesh, w)\n    c = zero(eltype(\u0394t))\n    for i_face in inner_faces(mesh)\n        c = max(c, courant(\u0394t, flux, mesh, w, i_face))\n    end\n    return c\nend\n\nfunction courant(\u0394t, 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    \u03bb = eigvals(flux, w_mean, n)\n    max\u03bb = maximum(abs.(\u03bb))\n    return max\u03bb * \u0394t * face_area(mesh, i_face) / min(cell_volume(mesh, i_cell_1), cell_volume(mesh, i_cell_2))\nend\n\nfunction courant(\u0394t, flux::AdvectionFlux, mesh, w, i_face)\n    v = LinearAdvectionFlux(flux.velocity_at_face(mesh, i_face))\n    return FiniteVolumes.courant(\u0394t, v, mesh, w, i_face)\nend\n\n# function courant(\u0394t, flux::LinearAdvectionFlux, mesh::AbstractCartesianMesh{1}, w)\n#     return abs(flux.velocity[1]) * \u0394t / FiniteVolumes.CartesianMeshes.dx(mesh)[1]\n# end\n\n# function courant(\u0394t, flux::LinearAdvectionFlux, mesh::PeriodicRegularMesh2D, w)\n#     vx, vy = model.velocity\n#     return max(abs(vx) * \u0394t / dx(mesh), abs(vy) * \u0394t / 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": "using Test\nusing PETSc, MPI, LinearAlgebra, SparseArrays\nPETSc.initialize()\n\n@testset \"Tests\" begin\n  m,n = 20,20\n  x = randn(n)\n  V = PETSc.VecSeq(x)\n\n\n  @test norm(x) \u2248 norm(V) rtol=10eps()\n\n  S = sprand(m,n,0.1) + I\n  M = PETSc.MatSeqAIJ(S)\n\n  @test norm(S) \u2248 norm(M) rtol=10eps()\n\n  w = M*x\n  @test w \u2248 S*x\n\n  ksp = PETSc.KSP(M; ksp_rtol=1e-8, pc_type=\"jacobi\", ksp_monitor=nothing)\n  #PETSc.settolerances!(ksp; rtol=1e-8)\n\n  @test PETSc.gettype(ksp) == \"gmres\" # default\n\n  pc = PETSc.PC(ksp)\n  @test PETSc.nrefs(pc) == 2\n  @test PETSc.gettype(pc) == \"jacobi\"\n\n  # create an extra handle, check ref count is incremented\n  pc_extra = PETSc.PC(ksp)\n  @test PETSc.nrefs(pc) == 3\n  # destroy extra handle, check ptr is set to null, ref count is decremented\n  PETSc.destroy(pc_extra)\n  @test pc_extra.ptr == C_NULL\n  @test PETSc.nrefs(pc) == 2\n\n  # safe to call destroy on null pointer\n  PETSc.destroy(pc_extra)\n\n  # set new pc, check ref counts are modified by ksp\n  pc_new = PETSc.PC{Float64}(MPI.COMM_SELF)\n  @test PETSc.nrefs(pc_new) == 1\n  PETSc.setpc!(ksp, pc_new)\n  @test PETSc.nrefs(pc_new) == 2\n  @test PETSc.nrefs(pc) == 1\n\n  PETSc.setpc!(ksp, pc)\n  @test PETSc.nrefs(pc_new) == 1\n  @test PETSc.nrefs(pc) == 2\n\n\n  y = ksp \\ w\n  @test S*y \u2248 w  rtol=1e-8\n\n\n  w = M'*x\n  @test w \u2248 S'*x\n\n  y = ksp' \\ w\n  @test S'*y \u2248 w rtol=1e-8\n\n\n  f!(y,x) = y .= 2 .*x\n\n  M = PETSc.MatShell{Float64}(f!,10,10)\n\n  x = rand(10)\n\n  @test M*x \u2248 2x\n  @test PETSc.KSP(M) \\ x \u2248 x/2\n\n\n  function F!(cfx, cx, a)\n    x = PETSc.unsafe_localarray(Float64,cx)\n    fx = PETSc.unsafe_localarray(Float64,cfx)\n    fx[1] = x[1]^2 + x[1]*x[2] - 3\n    fx[2] = x[1]*x[2] + x[2]^2 - 6\n    Base.finalize(x)\n    Base.finalize(fx)\n  end\n\n  J = zeros(2,2)\n  PJ = PETSc.MatSeqDense(J)\n  function updateJ!(cx, args...)\n    x = PETSc.unsafe_localarray(Float64,cx)\n    J[1,1] = 2x[1] + x[2]\n    J[1,2] = x[1]\n    J[2,1] = x[2]\n    J[2,2] = x[1] + 2x[2]\n    Base.finalize(x)\n  end\n\n  S = PETSc.SNES{Float64}(MPI.COMM_SELF; ksp_rtol=1e-4, pc_type=\"none\")\n  PETSc.setfunction!(S, F!, PETSc.VecSeq(zeros(2)))\n  PETSc.setjacobian!(S, updateJ!, PJ, PJ)\n  @test PETSc.solve!([2.0,3.0], S) \u2248 [1.0,2.0] rtol=1e-4\nend\n\n", "meta": {"hexsha": "29b41e53a9a7a8c50639dcbab232b3135b5fa0ee", "size": 2171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/old_test.jl", "max_stars_repo_name": "psanan/PETSc.jl", "max_stars_repo_head_hexsha": "ff709d1267b258ff5df1860155a5973137a4a755", "max_stars_repo_licenses": ["MIT"], "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/old_test.jl", "max_issues_repo_name": "psanan/PETSc.jl", "max_issues_repo_head_hexsha": "ff709d1267b258ff5df1860155a5973137a4a755", "max_issues_repo_licenses": ["MIT"], "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/old_test.jl", "max_forks_repo_name": "psanan/PETSc.jl", "max_forks_repo_head_hexsha": "ff709d1267b258ff5df1860155a5973137a4a755", "max_forks_repo_licenses": ["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.71, "max_line_length": 76, "alphanum_fraction": 0.6057116536, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.7507180384662892}}
{"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": "using AffineArithmetic, IntervalArithmetic, Polynomials, StaticArrays\nusing Test\n\nusing AffineArithmetic: Aff\n\n@testset \"Construction from intervals\" begin\n    X = 1..3\n    X_a = Affine(X)\n    X_a isa Affine\n\n    Y = 2..4\n    Y_a = Affine(Y)\n    @test Y_a.range == 2..4\n    @test Y_a.affine == Aff(3.0, SVector{1, Float64}(1.0), 0..0)\n\n    sum_a = X_a + Y_a\n    @test sum_a.range == 3..7\n    @test sum_a.affine == Aff(5.0, SVector{1, Float64}(2.0), 0..0)\n\n    prod_a = X_a * Y_a\n    @test prod_a.range == 2..12\n    @test prod_a.affine == Aff(6.0, SVector{1, Float64}(5.0), 0..1)\nend\n\n@testset \"Small powers and range\" begin\n    X = 1..3\n    Y = Affine(X)\n\n    f(x) = x^2 - x + 1\n\n    @test range(f(X)) == -1..9\n    @test range(f(Y)) == 0..7   # affine is a little better\n\n\n    g(x) = (x - 1)^3\n\n    @test range(g(X)) == 0..8\n    @test range(g(Y)) == 0..8   # affine gives the same\nend\n\nreset_affine_index()\n\n@testset \"Matrix multiplication\" begin\n    A = 0.5 * [1 2; -1 1]\n\n    X = Affine(-1..1)\n    Y = Affine(-1..1)\n\n    XX = [X, Y]\n    @test XX == [Affine(Aff(0.0, SVector{1, Float64}(1.0), 0..0), -1..1),\n                 Affine(Aff(0.0, SVector{1, Float64}(1.0), 0..0), -1..1)]\n\n    @test A * XX == [Affine(Aff(0.0, SVector{1, Float64}(1.5), 0..0), -1.5 .. 1.5),\n                     Affine(Aff(0.0, SVector{1, Float64}(0.0), 0..0), 0..0)]\nend\n\nreset_affine_index()\n\n@testset \"Range of polynomial\" begin\n    # example from Rump 2015\n    p = Polynomial([-3, 1])   # x - 3\n    p2 = p^8\n\n    x = 4 \u00b1 1e-4\n    y = Affine(x)\n\n    @test (-70..70) \u2286 range(p2(x))\n    @test range(p2(y)) \u2286 0.998..1.002   # affine is extremely much better!\nend\n\n@testset \"Constructors with intervals\" begin\n    X = Affine(1..2)\n    @test X isa Affine\n    @test X - X == Affine(0..0)\n\n    x, y = affine(1..2, 3..4)\n    @test interval(x + y - x - y) == 0..0\nend\n", "meta": {"hexsha": "b5f4ba9093f8adc75227d5202e6ed5eed70eaf29", "size": 1839, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "dpsanders/AffineArithmetic", "max_stars_repo_head_hexsha": "b7ef40e0b7ed75da6747e10a37588162b51ffcd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-04-18T21:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T20:28:55.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "dpsanders/AffineArithmetic", "max_issues_repo_head_hexsha": "b7ef40e0b7ed75da6747e10a37588162b51ffcd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-07-31T14:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T14:40:48.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "dpsanders/AffineArithmetic", "max_forks_repo_head_hexsha": "b7ef40e0b7ed75da6747e10a37588162b51ffcd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-07-31T08:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T17:53:42.000Z", "avg_line_length": 23.2784810127, "max_line_length": 83, "alphanum_fraction": 0.5454051115, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7507180335215692}}
{"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": "function  poisson(theta, y, x)\n\tlambda = exp.(x*theta)\n    n = size(y,1)\n    c = zeros(n)\n    for i = 1:n\n        c[i] = logabsgamma(y[i])[1]\n    end    \n    logdensity = y .* (x*theta) .- lambda .- c\nend\n", "meta": {"hexsha": "9fd0a6a5544f662ed383dc81ad5586735bcb178d", "size": 205, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ML/Likelihoods/poisson.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/poisson.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/poisson.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": 20.5, "max_line_length": 46, "alphanum_fraction": 0.5024390244, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.7506940821504379}}
{"text": "module DMatTest\nusing Base.Test \nusing Quantum\n\nxb = basis(:X,[1:3])\nxbplus = basis(:X,[1:4])\nxbminus = basis(:X,[0:3])\n\nd = dmat(eye(3), xb)\n@test d==d''\n@test d[:,:]==d.coeffs\n@test d*ket(:X,2) == dvec([0.0,1.0,0.0], xb)\n\n@test d+ket(:X,4)*bra(:X,4) == dmat(eye(4),xbplus)\n@test d+ket(:X,4)*bra(:X,3) == dmat([eye(3), [0 0 1]],xbplus, xb')\n@test d+ket(:X,3)*bra(:X,4) == dmat([eye(3) [0,0,1]],xb, xbplus')\n@test d+ket(:X,3)*bra(:X,3) == dmat((coeff=eye(3); coeff[3,3]=2.0; coeff),xb)\n\n@test ket(:X,0)*bra(:X,0)+d == dmat(eye(4),xbminus)\n@test ket(:X,0)*bra(:X,1)+d == dmat([[1 0 0], eye(3)],xbminus, xb')\n@test ket(:X,1)*bra(:X,0)+d == dmat([[1,0,0] eye(3)],xb, xbminus')\n@test ket(:X,1)*bra(:X,1)+d == dmat((coeff=eye(3); coeff[1,1]=2.0; coeff),xb)\n\n@test d+d==2*d\n@test isdual(d,d')\n@test map(x->x*2, d)==d+d\n@test commutator(d,d)==dmat(zeros(3,3), xb)\n\nend", "meta": {"hexsha": "efad0da44649208f63094bf004eff7c18368852b", "size": 861, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/dmattest.jl", "max_stars_repo_name": "acroy/Quantum.jl", "max_stars_repo_head_hexsha": "055ca14de09367e0795a8b109cac9584b73707b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-02-15T19:08:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:25:50.000Z", "max_issues_repo_path": "test/dmattest.jl", "max_issues_repo_name": "acroy/Quantum.jl", "max_issues_repo_head_hexsha": "055ca14de09367e0795a8b109cac9584b73707b5", "max_issues_repo_licenses": ["MIT"], "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/dmattest.jl", "max_forks_repo_name": "acroy/Quantum.jl", "max_forks_repo_head_hexsha": "055ca14de09367e0795a8b109cac9584b73707b5", "max_forks_repo_licenses": ["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.6896551724, "max_line_length": 77, "alphanum_fraction": 0.556329849, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603538, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7506940733395201}}
{"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": "using DataFrames\nusing CSV\nusing Plots\n#%%\ndata_rk = open(\"rk_error.dat\")\ndata_rk4 = open(\"rk4_error.dat\")\ndata_eu = open(\"eu_error.dat\")\n\n\ndf_rk=CSV.read(data_rk, header=false, delim=\" \")\ndf_rk4=CSV.read(data_rk4, header=false, delim=\" \")\ndf_eu=CSV.read(data_eu, header=false, delim=\" \")\n#%%\nx_=4:2048\neu=x_.^-1\nrk=x_.^-2\nrk4=x_.^-4\n#%%\nplot(df_rk[1],df_rk[2], label=\"Runge-Kutta\", color=\"black\", dpi=600)\nplot!(x_,rk, label=\"y=x^-2\", color=\"black\", line=(:dash))\n\nplot!(df_rk4[1],df_rk4[2], label=\"RK 4th order\", color=\"red\")\nplot!(x_,rk4, label=\"y=x^-4\", color=\"red\" , line=(:dash))\n\nplot!(df_eu[1],df_eu[2], label=\"Euler\", color=\"blue\")\nplot!(x_,eu, label=\"y=x^-1\",color=\"blue\", line=(:dash))\n\n\n\n\n\nxaxis!(:log10, xlims=(4,2048))\nyaxis!(:log10, ylims=(1e-15,Inf))\ntitle!(\"error as a function of n_steps\")\nxlabel!(\"n_steps\")\nylabel!(\"error\")\nplot!(legend=:bottom)\nsavefig(\"errors.png\")\n", "meta": {"hexsha": "c5ba12bbfeb45222a2383b6758134a3f08b1a9eb", "size": 888, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lezione11/plot_error.jl", "max_stars_repo_name": "aurelio-amerio/corso-cpp", "max_stars_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:54:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T20:36:39.000Z", "max_issues_repo_path": "lezione11/plot_error.jl", "max_issues_repo_name": "rydeen2045/corso-cpp", "max_issues_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lezione11/plot_error.jl", "max_forks_repo_name": "rydeen2045/corso-cpp", "max_forks_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-08T08:29:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T20:37:12.000Z", "avg_line_length": 22.7692307692, "max_line_length": 68, "alphanum_fraction": 0.6554054054, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7506576569900579}}
{"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 \u2264 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 \u00d7 w)\n\tv = w \u00d7 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    \u03c4 = [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 \u03c4-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(\u03c4) = sum( h.left(\u03c4).*x_left ) + sum( h.right(\u03c4).*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, :\u03c4) ]\n                right = [ Poly([ 0,   1 ]//1, :\u03c4) ]\n            elseif degree == 3\n                left  = [\n                    Poly([ 1,   0,  -3,   2 ]//1, :\u03c4)\n                    Poly([ 0,   1,  -2,   1 ]//1, :\u03c4)\n                ]\n                right = [\n                    Poly([ 0,   0,   3,  -2 ]//1, :\u03c4)\n                    Poly([ 0,   0,  -1,   1 ]//1, :\u03c4)\n                ]\n            elseif degree == 5\n                left  = [\n                    Poly([ 1,   0,   0, -10,  15,  -6 ]//1, :\u03c4)\n                    Poly([ 0,   1,   0,  -6,   8,  -3 ]//1, :\u03c4)\n                    Poly([ 0,   0,   1,  -3,   3,  -1 ]//2, :\u03c4)\n                ]\n                right = [\n                    Poly([ 0,   0,   0,  10, -15,   6 ]//1, :\u03c4)\n                    Poly([ 0,   0,   0,  -4,   7,  -3 ]//1, :\u03c4)\n                    Poly([ 0,   0,   0,   1,  -2,   1 ]//2, :\u03c4)\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        \u03c4 = (qr.locations + 1)/2  # Maps [-1,1] => [0,1]\n        \u03c4_scaling = 1/2\n\n        # Compute unit-interval interp matrices\n        HL_unit = \u03c4_scaling * polyval.( hb.left,  \u03c4' )\n        HR_unit = \u03c4_scaling * polyval.( hb.right, \u03c4' )\n\n        # Apply interval scaling to interp matrices\n        \u0394t = diff(time_points)\n        scale_factors(\u0394t) = [ \u0394t^(q+1) for q = 0:n_dof-1 ]\n        for i = 1:n_interval\n            S = scale_factors(\u0394t[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        \u0394t = diff(time_points)\n        scale_factors(\u0394t) = [ \u0394t^-(p*q+1) for p=0:n_dof-1, q=0:n_dof-1 ]\n        for i = 1:n_interval\n            S = scale_factors(\u0394t[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(\u0394t[ 1 ]) .* BL\n        K[end,end] -= scale_factors(\u0394t[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\"`, /\u0251/ as `\"aa\"`, and /u/ as `\"uw\"`, using values for men as `\"m\"` and women as `\"w\"`. One observation was dropped from the women /\u0251/ 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": "using Gen, Genify\nusing Distributions: Normal\n\n##  Define model of noisy weighing scale in Julia\n\nfunction scale(n::Int)\n    mass = rand(Normal(5, 1))\n    obs = measure(mass, n)\nend\n\nfunction measure(mass::Real, n::Int)\n    obs = Float64[]\n    for i in 1:n\n        m = rand(Normal(mass, 2))\n        push!(obs, m)\n    end\n    return obs\nend\n\n## Genify the model\n\ngenscale = genify(scale, Int)\n\n## Construct choicemap of noisy measurements\n\nobservations = choicemap(((:obs => :m => i, 4) for i in 1:10)...)\n\n## Perform importance sampling to estimate the true mass\n\ntrs, ws, _ = importance_sampling(genscale, (10,), observations, 100)\nmass_est = sum(tr[:mass] * exp(w) for (tr, w) in zip(trs, ws))\n", "meta": {"hexsha": "7e46ab24f56aac6699d964089f783dd1b1b76e39", "size": 696, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/scale/example.jl", "max_stars_repo_name": "probcomp/Genify.jl", "max_stars_repo_head_hexsha": "786fe04a6ef857d489ea8bf277cc0a7e29c2ce39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2020-11-04T17:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T03:57:52.000Z", "max_issues_repo_path": "examples/scale/example.jl", "max_issues_repo_name": "probcomp/Genify.jl", "max_issues_repo_head_hexsha": "786fe04a6ef857d489ea8bf277cc0a7e29c2ce39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-03T19:45:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-17T17:35:05.000Z", "max_forks_repo_path": "examples/scale/example.jl", "max_forks_repo_name": "probcomp/Genify.jl", "max_forks_repo_head_hexsha": "786fe04a6ef857d489ea8bf277cc0a7e29c2ce39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T11:37:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:37:23.000Z", "avg_line_length": 21.75, "max_line_length": 68, "alphanum_fraction": 0.650862069, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7505821283204381}}
{"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\u2032! = JopTanh_df\u2032!, s = (c=T(c),))\nexport JopTanh\n\nJopTanh_f!(d::AbstractArray, m::AbstractArray; c) = d .= tanh.(c .* m)\n\nJopTanh_df!(\u03b4d::AbstractArray, \u03b4m::AbstractArray; m\u2092, c) = \u03b4d .= c .* (1 .- tanh.(c .* m\u2092).^2) .* \u03b4m\n\nJopTanh_df\u2032!(\u03b4d::AbstractArray, \u03b4m::AbstractArray; m\u2092, c) = \u03b4d .= conj.(c .* (1 .- tanh.(c .* m\u2092).^2)) .* \u03b4m\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": "#=\nWe can determine how \"out of order\" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.\n\nGiven an array, count the number of inversions it has. Do this faster than O(N^2) time.\n\nYou may assume each element in the array is distinct.\n\nFor example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion.\n=#\n\nfunction inversions(A::Array{Int, 1})\n    B = copy(A)\n    number_of_inversions = 0\n    while length(B) != 1\n        if findmin(B)[2] != 1\n            number_of_inversions = number_of_inversions + sum(B[1] .> B[2:end])\n        end\n        B = B[2:end]\n    end\n    return number_of_inversions\nend\n", "meta": {"hexsha": "67dc2d329b3dda4fbd14749ae46933586ff51282", "size": 882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem44_count_inversions.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/problem44_count_inversions.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/problem44_count_inversions.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": 40.0909090909, "max_line_length": 224, "alphanum_fraction": 0.6621315193, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818985, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7505240266150213}}
{"text": "immutable Rayleigh <: ContinuousUnivariateDistribution\n    \u03c3::Float64\n\n    function Rayleigh(\u03c3::Real)\n        \u03c3 > zero(\u03c3) || error(\"Rayleigh: \u03c3 must be positive\")\n        @compat new(Float64(\u03c3))\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.\u03c3\nparams(d::Rayleigh) = (d.\u03c3,)\n\n\n#### Statistics\n\nmean(d::Rayleigh) = sqrthalf\u03c0 * d.\u03c3\nmedian(d::Rayleigh) = 1.177410022515474691 * d.\u03c3   # sqrt(log(4.0)) = 1.177410022515474691\nmode(d::Rayleigh) = d.\u03c3\n\nvar(d::Rayleigh) = 0.429203673205103381 * d.\u03c3^2   # (2.0 - \u03c0 / 2) = 0.429203673205103381\nstd(d::Rayleigh) = 0.655136377562033553 * d.\u03c3\n\nskewness(d::Rayleigh) = 0.631110657818937138\nkurtosis(d::Rayleigh) = 0.245089300687638063\n\nentropy(d::Rayleigh) = 0.942034242170793776 + log(d.\u03c3)\n\n\n#### Evaluation\n\nfunction pdf(d::Rayleigh, x::Float64)\n\t\u03c32 = d.\u03c3^2\n\tx > 0.0 ? (x / \u03c32) * exp(- (x^2) / (2.0 * \u03c32)) : 0.0\nend\n\nfunction logpdf(d::Rayleigh, x::Float64)\n\t\u03c32 = d.\u03c3^2\n\tx > 0.0 ? log(x / \u03c32) - (x^2) / (2.0 * \u03c32) : -Inf\nend\n\nlogccdf(d::Rayleigh, x::Float64) = - (x^2) / (2.0 * d.\u03c3^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.\u03c3^2 * log1p(-p))\n\n\n#### Sampling\n\nrand(d::Rayleigh) = d.\u03c3 * 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\u0302[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\u0302[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 \u03c41 and \u03c42\");\n\u03c41 = Float64[];\n\u03c42 = Float64[];\nfor a in [1:5]\n  corra = autocorrelation(N1, v1, a, ns);\n  corra /= corra[1];                          # Normalize\n  push!(\u03c41,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!(\u03c42,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\u03c4\u03021v$i:\\t$(\u03c41[i])\");\nend\nprintln(\"\\n\\tEstimated Autocorrelation Times for N2 = $N2:\\n\");\nfor i in [1:5]\n  println(\"\\t\\t\u03c4\u03022v$i:\\t$(\u03c42[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": "using Distributions\nusing Base.Test\n\nd = Kolmogorov()\n# compare to Smirnov's tabulated values\n@test round(cdf(d,0.28),6) == .000_001\n@test round(cdf(d,0.50),6) == .036_055\n@test round(cdf(d,0.99),6) == .719_126\n@test round(cdf(d,1.00),6) == .730_000\n@test round(cdf(d,1.01),6) == .740_566\n# @test round(cdf(d,1.04),6) == .770_434 # table value appears to be wrong\n@test round(cdf(d,1.50),6) == .977_782\n@test round(cdf(d,2.00),6) == .999_329\n@test round(cdf(d,2.50),7) == .999_992_5\n@test round(cdf(d,3.00),8) == .999_999_97\n", "meta": {"hexsha": "c63fdacf32d9b0dced5babab31a02db9799c507b", "size": 525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/kolmogorov.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": "2021-01-15T02:57:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T02:57:22.000Z", "max_issues_repo_path": "test/kolmogorov.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": "test/kolmogorov.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": 32.8125, "max_line_length": 74, "alphanum_fraction": 0.6571428571, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.750481718065937}}
{"text": "# Soft thresholding function\n@inline soft_threshold(x, \u03f5) = max(x - \u03f5, 0) + min(x + \u03f5, 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                          \u03c1::Float64=1.5,\n                          verbose::Bool=false,\n                          nonnegativeA::Bool=false,\n                          nonnegativeE::Bool=false)\n    M, N = size(D)\n    \u03bb = sparseness\n\n    A\u2070, E\u2070 = zeros(M, N), zeros(M, N)\n\n    # initialize\n    Y\u2070 = copy(D)\n    norm\u00b2 = svdvals(Y\u2070)[1] # can be tuned\n    norm\u221e = norm(vec(Y\u2070), Inf) / \u03bb\n    dual_norm = max(norm\u00b2, norm\u221e)\n    d_norm = norm(D)\n    Y\u2070 /= dual_norm\n\n    \u03bc\u2070 = 1.25 / norm\u00b2\n    \u03bc\u0304 = \u03bc\u2070 * 1.0e+7\n\n    converged::Bool = false\n    k = 0\n    sv\u2070 = 10\n\n    Y\u1d4f, A\u1d4f, E\u1d4f, \u03bc\u1d4f, sv\u1d4f = Y\u2070, A\u2070, E\u2070, \u03bc\u2070, sv\u2070\n    while !converged\n        # update sparse matrix E\n        E\u1d4f = soft_threshold(D - A\u1d4f + 1/\u03bc\u1d4f * Y\u1d4f, \u03bb * 1/\u03bc\u1d4f)\n        # force non-negative (heuristic)\n        if nonnegativeE\n            E\u1d4f = max(E\u1d4f, 0)\n        end\n\n        U, S, V = svd(D - E\u1d4f + \u03bc\u1d4f^-1 * Y\u1d4f)\n\n        # trancate dimention\n        svp\u1d4f = trunc(Int, sum(S .> \u03bc\u1d4f^-1))\n        if svp\u1d4f < sv\u1d4f\n            sv\u1d4f = min(svp\u1d4f + 1, N)\n        else\n            sv\u1d4f = min(svp\u1d4f + round(0.05 * N), N)\n        end\n\n        # update row-rank matrix A\n        A\u1d4f = U[:,1:svp\u1d4f] * diagm(S[1:svp\u1d4f] - 1/\u03bc\u1d4f) * V[:,1:svp\u1d4f]'\n        # force non-negative (heuristic)\n        if nonnegativeA\n            A\u1d4f = max(A\u1d4f, 0)\n        end\n\n        Z = D - A\u1d4f - E\u1d4f\n\n        Y\u1d4f = Y\u1d4f + \u03bc\u1d4f * Z\n        \u03bc\u1d4f = min(\u03bc\u1d4f * \u03c1, \u03bc\u0304)\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\u1d4f, E\u1d4f\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 \u03b7_karnik(u::Matrix{FuzzyNumber}, d2::Matrix{FuzzyNumber}; m::Real=2.0)\n\tm > 1 || error(\"fuzzifier m \u2208 (1, \u221e), got $m\")\n\tlevels = u[1, 1].levels\n\tnum_levels = length(levels)\n\tN, c = size(u)\n\n\t\u03b7 = Vector{FuzzyNumber}(undef, c)\n\tfor i = 1:c\n\t\tgrades = Vector{Interval}(undef, num_levels)\n\t\tfor (lvl, \u03b1) in enumerate(levels)\n\t\t\tu_cut = cut(FuzzyVector(u[:, i]), \u03b1)\n\t\t\td2_cut = cut(FuzzyVector(d2[:, i]), \u03b1)\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\u03b7[i] = FuzzyNumber(levels, grades)\n\tend\n\t\u03b7\nend\n\nfunction u_lpcm(X\u20d7::FuzzyVector, C\u20d7::FuzzyVector, \u03b7::Real; m::Real=2.0)\n\tm > 1 || error(\"fuzzifier m \u2208 (1, \u221e), got $m\")\n\t\u03b7 > 0 || error(\"\u03b7 must be suitable positive number\")\n\tlevels = X\u20d7[1].levels\n\tnum_levels = length(levels)\n\n\tgrades = Vector{Interval}(undef, num_levels)\n\tD2 = FuzzySets.d_interval(X\u20d7, C\u20d7, squared=true)\n\tfor (lvl, \u03b1) in enumerate(levels)\n\t\tD2_cut = cut(D2, \u03b1)\n\t\tgrades[lvl] = u_lpcm(D2_cut, \u03b7; m=m)\n\tend\n\tu = FuzzyNumber(levels, grades)\n\tu\nend\n\nfunction u_lpcm(d2::Interval, \u03b7::Real; m::Real=2.0)\n\tm > 1 || error(\"fuzzifier m \u2208 (1, \u221e)\")\n\t\u03b7 > 0 || error(\"\u03b7 must be suitable positive number\")\n\tpower = 1 / (m - 1)\n\n\tu = Interval(1) / (Interval(1) + (d2 / \u03b7)^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, \u03b1, \u03b2, N::Integer)\n\nEvaluate the Hahn polynomial with parameters `\u03b1`, `\u03b2`, `N` of degree `p` at `x`\nusing the three term recursion [\u00d6ffner, Zweidimensionale klassische und diskrete\northogonale Polynome, Chapter 5].\n\"\"\"\nfunction hahn(x, p::Integer, \u03b1, \u03b2, N)\n    T = typeof( (\u03b1+\u03b2+2)*x/(N*(\u03b1+1)) )\n    a = one(T)\n    b = 1 - (\u03b1+\u03b2+2)*x/(N*(\u03b1+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+\u03b1+\u03b2)*(n+\u03b1)*(N-n+1) ) / ( (2n-1+\u03b1+\u03b2)*(2n+\u03b1+\u03b2) )\n        Cn = T( (n-1)*(n+\u03b1+\u03b2+N)*(n-1+\u03b2) ) / ( (2n-2+\u03b1+\u03b2)*(2n-1+\u03b1+\u03b2) )\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(\u03bc,\u03b8)\n\nThe *Logistic distribution* with location `\u03bc` and scale `\u03b8` 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    \u03bc::T\n    \u03b8::T\n    Logistic{T}(\u00b5::T, \u03b8::T) where {T} = new{T}(\u00b5, \u03b8)\nend\n\n\nfunction Logistic(\u03bc::T, \u03b8::T; check_args=true) where {T <: Real}\n    check_args && @check_args(Logistic, \u03b8 > zero(\u03b8))\n    return Logistic{T}(\u03bc, \u03b8)\nend\n\nLogistic(\u03bc::Real, \u03b8::Real) = Logistic(promote(\u03bc, \u03b8)...)\nLogistic(\u03bc::Integer, \u03b8::Integer) = Logistic(float(\u03bc), float(\u03b8))\nLogistic(\u03bc::T) where {T <: Real} = Logistic(\u03bc, 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}}, \u03bc::S, \u03b8::S) where {T <: Real, S <: Real}\n    Logistic(T(\u03bc), T(\u03b8))\nend\nfunction convert(::Type{Logistic{T}}, d::Logistic{S}) where {T <: Real, S <: Real}\n    Logistic(T(d.\u03bc), T(d.\u03b8), check_args=false)\nend\n\n#### Parameters\n\nlocation(d::Logistic) = d.\u03bc\nscale(d::Logistic) = d.\u03b8\n\nparams(d::Logistic) = (d.\u03bc, d.\u03b8)\n@inline partype(d::Logistic{T}) where {T<:Real} = T\n\n\n#### Statistics\n\nmean(d::Logistic) = d.\u03bc\nmedian(d::Logistic) = d.\u03bc\nmode(d::Logistic) = d.\u03bc\n\nstd(d::Logistic) = \u03c0 * d.\u03b8 / sqrt3\nvar(d::Logistic) = (\u03c0 * d.\u03b8)^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.\u03b8) + 2\n\n\n#### Evaluation\n\nzval(d::Logistic, x::Real) = (x - d.\u03bc) / d.\u03b8\nxval(d::Logistic, z::Real) = d.\u03bc + z * d.\u03b8\n\npdf(d::Logistic, x::Real) = (lz = logistic(-abs(zval(d, x))); lz*(1-lz)/d.\u03b8)\nlogpdf(d::Logistic, x::Real) = (u = -abs(zval(d, x)); u - 2*log1pexp(u) - log(d.\u03b8))\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.\u03b8\nend\n\nmgf(d::Logistic, t::Real) = exp(t * d.\u03bc) / sinc(d.\u03b8 * t)\n\nfunction cf(d::Logistic, t::Real)\n    a = (\u03c0 * t) * d.\u03b8\n    a == zero(a) ? complex(one(a)) : cis(t * d.\u03bc) * (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": "# Test Sherman-Morrison inverse\nA = rand(2, 2)\nAinv = inv(A)\nu = rand(2, 1)\nB = A + u * u'\n@test NonlinearBandits.sherman_morrison_inv(Ainv, u, u) \u2248 inv(B)\n@test_throws(\n    DimensionMismatch(\"u and v have mismatched dimensions\"),\n    NonlinearBandits.sherman_morrison_inv(Ainv, u, zeros(3, 1))\n)\n@test_throws(\n    ArgumentError(\"u and v should have exactly one column\"),\n    NonlinearBandits.sherman_morrison_inv(Ainv, zeros(2, 2), zeros(2, 2))\n)\n@test_throws(\n    DimensionMismatch(\"size of A does not match u/v\"),\n    NonlinearBandits.sherman_morrison_inv(Ainv, zeros(3, 1), zeros(3, 1))\n)\n\n## Test Bayesian linear model fitting procedure\nd, n, \u03c3 = 2, 10000, 2\n\u03b2 = rand(Normal(0, 10), d, 1)\nf(x) = \u03b2' * x\nX, y = NonlinearBandits.gaussian_data(d, n, f; \u03c3=\u03c3)\nshape0, scale0 = 0.001, 0.001\n\nlm = BayesLM(d; shape0=shape0, scale0=scale0)\n@test_throws(\n    ArgumentError(\"normal-inverse-gamma has undefined mean for shape \u2264 1\"), std(lm)\n)\nfit!(lm, X, y)\n\nprediction_mae = mae(lm(X), mapslices(f, X; dims=1))\n\u03b2_mae = mae(lm.\u03b2, \u03b2)\n@test \u03b2_mae < 0.5\n@test prediction_mae < 0.5\n@test lm.shape == shape0 + n / 2\n@test isapprox(std(lm), \u03c3; atol=0.5)\n\n# Check that sequential updates lead to the same results\nsequential_lm = BayesLM(d; shape0=shape0, scale0=scale0)\nfor i in 1:n\n    fit!(sequential_lm, X[:, i:i], y[:, i:i])\nend\n\n@test sequential_lm.\u03b2 \u2248 lm.\u03b2\n@test sequential_lm.\u03a3 \u2248 lm.\u03a3\n@test sequential_lm.shape == shape0 + (n / 2)\n@test sequential_lm.scale \u2248 lm.scale\n\n# Check errors\n@test_throws(\n    ArgumentError(\"d, shape0 and scale0 must be strictly positive\"),\n    BayesLM(0; shape0=0.0, scale0=0.0)\n)\n@test_throws(ArgumentError(\"y should have exactly 1 row\"), fit!(lm, X, y'))\n@test_throws(\n    DimensionMismatch(\"X and y don't match in dimension 2\"), fit!(lm, X[:, 1:2], y)\n)\n@test_throws(\n    DimensionMismatch(\"X does not have the same number of predictors as the model\"),\n    fit!(lm, X[1:1, :], y)\n)\n@test_throws(\n    DimensionMismatch(\"X does not have the same number of predictors as the model\"),\n    lm(X[1:1, :])\n)\n", "meta": {"hexsha": "687a68654fb4c9273be1a1f5c50775b640d1c3d7", "size": 2025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_BayesLM.jl", "max_stars_repo_name": "dfcorbin/NonlinearBandits.jl", "max_stars_repo_head_hexsha": "11ec5b0f33552d5d3acc17c21d93fa4955c22ed9", "max_stars_repo_licenses": ["MIT"], "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_BayesLM.jl", "max_issues_repo_name": "dfcorbin/NonlinearBandits.jl", "max_issues_repo_head_hexsha": "11ec5b0f33552d5d3acc17c21d93fa4955c22ed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-14T14:36:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T20:45:33.000Z", "max_forks_repo_path": "test/test_BayesLM.jl", "max_forks_repo_name": "dfcorbin/NonlinearBandits.jl", "max_forks_repo_head_hexsha": "11ec5b0f33552d5d3acc17c21d93fa4955c22ed9", "max_forks_repo_licenses": ["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.7794117647, "max_line_length": 84, "alphanum_fraction": 0.6819753086, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7504336322092271}}
{"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_\u03b2 = ((1 + \u03b2^2) * PPV * TPR)/ (\u03b2^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": "function distributeCandies(nums::Array{Int64})\n    a = Set(nums)\n    if length(a) > length(nums)/2\n        length(nums) / 2\n    else\n        length(a)\n    end\nend\n\nusing Test\n@test distributeCandies([1,1,2,2,3,3]) == 3\n@test distributeCandies([1,1,2,3]) == 2\n", "meta": {"hexsha": "ed99602d615265931c286374a783f8fee0c841fb", "size": 259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Distribute-Candies/DC.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": "Distribute-Candies/DC.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": "Distribute-Candies/DC.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": 19.9230769231, "max_line_length": 46, "alphanum_fraction": 0.61003861, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7504336251745753}}
{"text": "wall = Lar.svg2lar(\"./test/svg/assembly/wall.svg\", flag=false);\nopenings = Lar.svg2lar(\"./test/svg/assembly/svg/openings.svg\", flag=false);\nrectangle = Lar.svg2lar(\"./test/svg/assembly/rectangle.svg\", flag=false);\nbox = Lar.svg2lar(\"./test/svg/assembly/box.svg\", flag=false);\n\nassembly = Lar.Struct([wall, openings, rectangle, box]);\nV,EV = Lar.struct2lar(assembly);\nif todisplay  GL.VIEW([ GL.GLGrid(V,EV, GL.COLORS[1],1), GL.GLFrame2 ]);  end\n\nmodel = CAGD.Model(V);\nCAGD.addModelCells!(model, 1, EV);\n\nA_model = CAGD.planar_arrangement(model);\n\nA_model.G\nMatrix(A_model.T[1])\nMatrix(A_model.T[2])\n\n# Display Models\n\nif todisplay\n    VV = [[k] for k=1:size(A_model.G, 2)];\n    triangulated_faces = CAGD.triangulate2D(A_model);\n    FVs = convert(Array{Lar.Cells}, triangulated_faces);\n\n    GL.VIEW(GL.GLExplode(A_model.G, FVs, 1.0, 1.0, 1.0, 99, 1));\n    GL.VIEW(GL.GLExplode(A_model.G, FVs, 4.0, 4.0, 4.0, 99, 1));\nend\n\ninnerpoints = Lar.internalpoints2d(A_model.G', A_model.T[1], A_model.T[2][1:end, :])\n# associate internal points to 2-cells\nlistOfModels = Lar.evalStruct(assembly)\ninputfacenumbers = [length(listOfModels[k][2]) for k=1:length(listOfModels)];\n# test input data for containment of reference points\nboolmatrix = sparse(BitArray(undef, length(innerpoints), length(listOfModels)));\ncontainmenttest = Lar.testinternalpoint2d(listOfModels);\nfor (k,point) in enumerate(innerpoints) # k runs on columns\n    cells = containmenttest(point); # contents of columns\n    #println(k,\" \",faces)\n    for l in cells\n        boolmatrix[k,l] = 1;\n    end\nend\n\nboolmatrix = sparse(Bool[\n    true  false false true\n    true  false true  true\n    false false false true\n    true  true  false true\n    false true  false true\n    false false false true\n    true  true  false true\n    false false false true\n    false true  false false\n    false false true  true\n    true  false false true\n    false true  false true\n    true  false false true\n    true  false false true\n    false true  false true\n    false false  true  true\n    false false true  false\n]);\n\nMatrix(boolmatrix)\n\nwall = boolmatrix[:, 1]\nLshape = boolmatrix[:, 2]\nrect = boolmatrix[:, 3]\nbox = boolmatrix[:, 4]\n\nGL.VIEW(GL.GLExplode(A_model.G, FVs[wall.nzind],   1.0, 1.0, 1.0, 99, 1));\nGL.VIEW(GL.GLExplode(A_model.G, FVs[Lshape.nzind], 1.0, 1.0, 1.0, 99, 1));\nGL.VIEW(GL.GLExplode(A_model.G, FVs[rect.nzind],   1.0, 1.0, 1.0, 99, 1));\nGL.VIEW(GL.GLExplode(A_model.G, FVs[box.nzind],    1.0, 1.0, 1.0, 99, 1));\n\nshells = Array{SparseVector{Bool,Int64},1}()\npush!(shells, .|(wall, Lshape, rect));\npush!(shells, .&(wall, .!Lshape, .!rect));\npush!(shells, .&(box, .!shells[2]))\n\nif todisplay\n    for i = 1 : length(shells)\n    GL.VIEW(GL.GLExplode(A_model.G, FVs[shells[i].nzind], 1.0, 1.0, 1.0, 1, 1));\n    GL.VIEW(GL.GLExplode(A_model.G, FVs[shells[i].nzind], 1.0, 1.0, 1.0, 99, 1));\n    end\nend\n", "meta": {"hexsha": "170fab932c2e084932517753743bc361454a94d3", "size": 2856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CAGD.jl/paper/examples/planar_algebra_2D.jl", "max_stars_repo_name": "grace-harper-ibm/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "b4bb4fc5259eb8667af3074124738e6221ed5ce2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CAGD.jl/paper/examples/planar_algebra_2D.jl", "max_issues_repo_name": "grace-harper-ibm/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "b4bb4fc5259eb8667af3074124738e6221ed5ce2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CAGD.jl/paper/examples/planar_algebra_2D.jl", "max_forks_repo_name": "grace-harper-ibm/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "b4bb4fc5259eb8667af3074124738e6221ed5ce2", "max_forks_repo_licenses": ["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.4545454545, "max_line_length": 84, "alphanum_fraction": 0.6736694678, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.750433622168532}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing DataFrames, CSV, Dates, StatsBase, Plots, TimeSeries\nend\n\n# \u2554\u2550\u2561 ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.20\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.20\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# \u2560\u2550e077ab16-22e5-11eb-15ed-5f0654bf7328\n# \u2560\u2550e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# \u2560\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u255056bc1334-250c-11eb-3c15-f98b6097c3a6\n# \u255f\u2500475ff888-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": "using Test\nusing JuliaEuler\nusing Lazy\n\n@testset \"helper\" begin\n    # Write your tests here.\n    @testset \"Fib\" begin\n        @test fib(;under=90) |> collect |> Vector{Int} == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n        @test fib(;terms=11) |> collect |> Vector{Int} == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n        @test take(11, fibs) |> collect |> Vector{Int} == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n        @test takewhile(x-> x < 90,fibs) |> collect |> Vector{Int} == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n        @test take(11,fibs) |> collect |> Vector{Int} == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n    end\n    @testset \"Prime\" begin\n        @test primes(20) == [2,3,5,7,11,13,17,19]\n        @test primes(2) == [2]\n        @test primes(5) == [2,3,5]\n        @test factors(2309125) == [(5,3), (7,2), (13,1), (29,1)]\n        @test factors(2) == [(2,1)]\n        @test factors(5) == [(5,1)]\n        @test primes_of_num(13195) == [5,7,13,29]\n        @test primes_of_num(2) == [2]\n        @test primes_of_num(5) == [5]\n\n    end\n\n    @testset \"ProperDivisors\" begin\n        @test proper_divisors(220) == [1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110]\n        @test proper_divisors(284) == [1, 2, 4, 71, 142]\n    end\n\n    @testset \"Permutations\" begin\n        @test Set(permutations([1,2,3], 2)) == Set([(1,2), (1,3), (2,1), (2,3), (3,1),(3,2)])\n        @test Set(permutations([1,2,3], 3)) == Set([(1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1)\n            ])\n\n    end\n\n    @testset \"Product\" begin\n        @test Set(product([1,2,3], 2)) == Set([(1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3)])\n        @test Set(product([1,2,3], 3)) == Set([\n            (1,1,1), (1,1,2), (1,1,3), (1,2,1), (1,2,2), (1,2,3), (1,3,1), (1,3,2), (1,3,3),\n            (2,1,1), (2,1,2), (2,1,3), (2,2,1), (2,2,2), (2,2,3), (2,3,1), (2,3,2), (2,3,3),\n            (3,1,1), (3,1,2), (3,1,3), (3,2,1), (3,2,2), (3,2,3), (3,3,1), (3,3,2), (3,3,3)\n            ])\n    end\n\n    @testset \"combinations\" begin\n        @test Set(combinations([1,2,3], 2)) == Set([(1,2), (1,3), (2,3)])\n        @test Set(combinations([1,2,3], 2;with_replacement=true)) == Set([(1,1), (1,2), (1,3), (2,2), (2,3), (3,3)])\n        @test Set(combinations([1,2,3], 3)) == Set([(1,2,3)])\n        @test Set(combinations([1,2,3], 3;with_replacement=true)) == Set([\n            (1,1,1), (1,1,2), (1,1,3), (1,2,2), (1,2,3), (1,3,3),\n            (2,2,2), (2,2,3), (2,3,3),\n            (3,3,3)\n    ])\n    end\n\n    @testset \"unique_sorted\" begin\n        @test JuliaEuler.unique_sorted([1,2,3]) == true\n        @test JuliaEuler.unique_sorted([1,2, 2,3]) == false\n    end\nend\n", "meta": {"hexsha": "f3efa086a257693d7eb68aec00e3f0f87380dea4", "size": 2634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/helper.jl", "max_stars_repo_name": "binnisb/JuliaEuler", "max_stars_repo_head_hexsha": "6d4684749e6fa6082d262bb12ba3659b01362948", "max_stars_repo_licenses": ["MIT"], "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/helper.jl", "max_issues_repo_name": "binnisb/JuliaEuler", "max_issues_repo_head_hexsha": "6d4684749e6fa6082d262bb12ba3659b01362948", "max_issues_repo_licenses": ["MIT"], "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/helper.jl", "max_forks_repo_name": "binnisb/JuliaEuler", "max_forks_repo_head_hexsha": "6d4684749e6fa6082d262bb12ba3659b01362948", "max_forks_repo_licenses": ["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.15625, "max_line_length": 116, "alphanum_fraction": 0.4597570235, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7504336139916566}}
{"text": "using SparseDiffTools\nusing DiffEqDiffTools: finite_difference_jacobian, finite_difference_jacobian!\nusing SparsityDetection\n\nusing LinearAlgebra, SparseArrays, Test\n\nfcalls = 0\n\nfunction f(x)\n  global fcalls += 1\n  dx = similar(x)\n  for i in 2:length(x)-1\n    dx[i] = x[i-1] - 2x[i] + x[i+1]\n  end\n  dx[1] = -2x[1] + x[2]\n  dx[end] = x[end-1] - 2x[end]\n  dx\nend\n\nfunction f(dx,x)\n  global fcalls += 1\n  for i in 2:length(x)-1\n    dx[i] = x[i-1] - 2x[i] + x[i+1]\n  end\n  dx[1] = -2x[1] + x[2]\n  dx[end] = x[end-1] - 2x[end]\n  nothing\nend\n\nfunction second_derivative_stencil(N)\n  A = zeros(N,N)\n  for i in 1:N, j in 1:N\n      (j-i==-1 || j-i==1) && (A[i,j]=1)\n      j-i==0 && (A[i,j]=-2)\n  end\n  A\nend\n\noutput = ones(30); input = ones(30)\nsparsity_pattern = sparsity!(f,output,input)\ntrue_jac = Float64.(sparse(sparsity_pattern))\ncolors = matrix_colors(true_jac)\n@test colors == repeat(1:3,10)\n\n#Jacobian computed without coloring vector\nfcalls = 0\nJ = finite_difference_jacobian(f, rand(30))\n@test J \u2248 second_derivative_stencil(30)\n@test fcalls == 31\n\n#Jacobian computed with coloring vectors\nfcalls = 0\n_J = similar(true_jac)\nfinite_difference_jacobian!(_J, f, rand(30), colorvec = colors)\n@test fcalls == 4\n@test _J \u2248 J\n\nfcalls = 0\n_J = similar(true_jac)\n_denseJ = collect(_J)\nfinite_difference_jacobian!(_denseJ, f, rand(30), colorvec = colors, sparsity=_J)\n@test fcalls == 4\n@test _denseJ \u2248 J\n", "meta": {"hexsha": "df06c566f76e675778d739031ba34e19ecea56f4", "size": 1397, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_integration.jl", "max_stars_repo_name": "devmotion/SparseDiffTools.jl", "max_stars_repo_head_hexsha": "7dc407ad10b0a0e82627ea7d9dfcd2490fdf45a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-05-09T19:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-27T13:36:11.000Z", "max_issues_repo_path": "test/test_integration.jl", "max_issues_repo_name": "devmotion/SparseDiffTools.jl", "max_issues_repo_head_hexsha": "7dc407ad10b0a0e82627ea7d9dfcd2490fdf45a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-05-09T19:30:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T15:08:37.000Z", "max_forks_repo_path": "test/test_integration.jl", "max_forks_repo_name": "devmotion/SparseDiffTools.jl", "max_forks_repo_head_hexsha": "7dc407ad10b0a0e82627ea7d9dfcd2490fdf45a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-05-27T14:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-24T16:52:22.000Z", "avg_line_length": 21.828125, "max_line_length": 81, "alphanum_fraction": 0.6664280601, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7504336099032188}}
{"text": "import LinearAlgebra\n\nfunction close_to_zero(value::T) where {T<:AbstractFloat}\n    return abs(value) < 1e-2\nend\n\nfunction se3_inv(T::Matrix{<:AbstractFloat})\n    C = T[1:3, 1:3]\n    d = T[1:3, 4]\n    return [C' -C'*d; 0 0 0 1]\nend\n\n# function skew(x::Vector{<:AbstractFloat})\n#     return [\n#         0 -x[3] x[2]\n#         x[3] 0 -x[1]\n#         -x[2] x[1] 0\n#     ]\n# end\n\nfunction so3_wedge(\u03d5::Vector{<:AbstractFloat})\n    return [\n        0 -\u03d5[3] \u03d5[2]\n        \u03d5[3] 0 -\u03d5[1]\n        -\u03d5[2] \u03d5[1] 0\n    ]\nend\n\nfunction so3_exp(psi::Vector{<:AbstractFloat})\n    angle = norm(psi, 2)\n    axis = psi / angle\n    s = sin(angle)\n    c = cos(angle)\n    return c * I(3) + (1 - c) * axis .* axis' - s * so3_wedge(axis)\nend\n\nfunction so3_vee(C::Matrix{<:AbstractFloat})\n    return [C[3, 2], C[1, 3], C[2, 1]]\nend\n\nfunction so3_log(C::Matrix{<:AbstractFloat})\n\n    cos_angle = 0.5 * tr(C) - 0.5\n    cos_angle = clamp(cos_angle, -1.0, 1.0)\n    angle = acos(cos_angle)\n\n    if close_to_zero(angle)\n        tmp = C - I\n    else\n        tmp = (angle / (2 * sin(angle))) * (C - C')\n    end\n\n    return so3_vee(tmp)\nend\n\nfunction so3_jacobian(psi::Vector{<:AbstractFloat})\n    angle = norm(psi)\n\n    if close_to_zero(angle)\n        return I + 0.5 * so3_wedge(psi)\n    end\n\n    axis = psi / angle\n    s = sin(angle)\n    c = cos(angle)\n\n    return (s / angle) * I(3) + (1 - s / angle) * axis * axis' + (1 - c) / angle * so3_wedge(axis)\nend\n\nfunction so3_inv_left_jacobian(phi::Vector{<:AbstractFloat})\n    dof = 3\n    angle = norm(phi)\n\n    # Near phi==0, use first order Taylor expansion\n    if close_to_zero(angle)\n        return I(3) - 0.5 * so3_wedge(phi)\n    end\n\n    axis = phi / angle\n    half_angle = 0.5 * angle\n    cot_half_angle = 1.0 / tan(half_angle)\n\n    return half_angle * cot_half_angle * I(dof) + (1 - half_angle * cot_half_angle) * (axis * axis') - half_angle * so3_wedge(axis)\n\nend\n\n# Might have to update this\nfunction se3_exp(d::Vector{<:AbstractFloat}, psi::Vector{<:AbstractFloat})\n    J = so3_jacobian(psi)\n    C = so3_exp(psi)\n    return [C J*d; 0 0 0 1]\nend\n\nfunction se3_log(T::Matrix{<:AbstractFloat})\n    psi = so3_log(T[1:3, 1:3])\n\n    J = so3_inv_left_jacobian(psi)\n    r = inv(J) * T[1:3, 4]\n\n    return [r; psi]\nend\n\n# Functions taken from the python liegroups packages\n\nfunction se3_wedge(\u03be::Vector{<:AbstractFloat})\n    dim = 4\n    \u039e = zeors(size(\u03be, 1), dim, dim)\n    \u039e[:, 1:3, 1:3] = so3_wedge(\u03be[:, 4:6])\n    \u039e[:, 0:3, 3] = \u03be[:, 1:3]\n    return \u039e\nend\n\nfunction se3_odot(p::Vector{<:AbstractFloat})\n    dim = 4\n    dof = 6\n\n    result = zeros(size(p, 1), dof)\n\n    if size(p, 1) == dim - 1\n        result[1:3, 1:3] = I(3)\n        result[1:3, 4:6] = so3_wedge(-p)\n    else\n        result[1:3, 1:3] = I(3)\n        result[1:3, 4:6] = so3_wedge(-p)\n    end\n\n    return result\nend\n\nfunction se3_adjoint(T::Matrix{<:AbstractFloat})\n    C = T[1:3, 1:3]\n    r = T[1:3, 4]\n    return [\n        C so3_wedge(r)*C\n        zeros(3, 3) C\n    ]\nend", "meta": {"hexsha": "15a29573ba5c7fd5c9415377f07834116687788f", "size": 2951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lie_groups.jl", "max_stars_repo_name": "jandaa/state-estimation", "max_stars_repo_head_hexsha": "9e0ecc18ee2f02940c2f4fee47ac7c5e1318546a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lie_groups.jl", "max_issues_repo_name": "jandaa/state-estimation", "max_issues_repo_head_hexsha": "9e0ecc18ee2f02940c2f4fee47ac7c5e1318546a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lie_groups.jl", "max_forks_repo_name": "jandaa/state-estimation", "max_forks_repo_head_hexsha": "9e0ecc18ee2f02940c2f4fee47ac7c5e1318546a", "max_forks_repo_licenses": ["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.5401459854, "max_line_length": 131, "alphanum_fraction": 0.5672653338, "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7504171944488568}}
{"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 \u2297 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(\u03c3::AbstractVector) = PDiagMat(abs2(\u03c3))\nnormalize(\u03a3::AbstractMatrix) = PDMat(\u03a3)\nnormalize(\u03a3::AbstractPDMat) = \u03a3\nnormalize(d::Int, \u03c3::Real) = PDScalMat(d, abs2(\u03c3))\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\u03c0)\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      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    3 \u2502\\.                     ./\u2502    1 \u2502            \u250c------------\u2502\n      \u2502 '\\.                 ./' \u2502      \u2502            |            \u2502\n      \u2502   \\.               ./   \u2502      \u2502            |            \u2502\n      \u2502    '\\.           ./'    \u2502      \u2502_           |           _\u2502\n    L \u2502      \\.         ./      \u2502   L' \u2502            |            \u2502\n      \u2502       '\\.     ./'       \u2502      \u2502            |            \u2502\n      \u2502         \\.   ./         \u2502      \u2502            |            \u2502\n    0 \u2502          '\\./'          \u2502   -1 \u2502------------\u2518            \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -3                        3      -3                        3\n                 y\u0302 - y                            y\u0302 - 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      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    9 \u2502\\                       /\u2502    3 \u2502                   .r/   \u2502\n      \u2502\".                     .\"\u2502      \u2502                 .r'     \u2502\n      \u2502 \".                   .\" \u2502      \u2502              _./'       \u2502\n      \u2502  \".                 .\"  \u2502      \u2502_           .r/         _\u2502\n    L \u2502   \".               .\"   \u2502   L' \u2502         _:/'            \u2502\n      \u2502    '\\.           ./'    \u2502      \u2502       .r'               \u2502\n      \u2502      \\.         ./      \u2502      \u2502     .r'                 \u2502\n    0 \u2502        \"-.___.-\"        \u2502   -3 \u2502  _/r'                   \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -3                        3      -2                        2\n                 y\u0302 - y                            y\u0302 - 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\u03c0/circumference\n    function PeriodicLoss{T}(circ::T) where T\n        circ > 0 || error(\"circumference should be strictly positive\")\n        new{T}(convert(T, 2\u03c0/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      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    2 \u2502                         \u2502    1 \u2502                .+-------\u2502\n      \u2502                         \u2502      \u2502              ./'        \u2502\n      \u2502\\.                     ./\u2502      \u2502             ./          \u2502\n      \u2502 '.                   .' \u2502      \u2502_           ./          _\u2502\n    L \u2502   \\.               ./   \u2502   L' \u2502           /'            \u2502\n      \u2502     \\.           ./     \u2502      \u2502          /'             \u2502\n      \u2502      '.         .'      \u2502      \u2502        ./'              \u2502\n    0 \u2502        '-.___.-'        \u2502   -1 \u2502-------+'                \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -2                        2      -2                        2\n                 y\u0302 - y                            y\u0302 - 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 ``\u03f5``-insensitive loss. Typically used in linear support vector\nregression. It ignores deviances smaller than ``\u03f5``, 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 (\u03f5=1)               Derivative\n      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    2 \u2502\\                       /\u2502    1 \u2502                  \u250c------\u2502\n      \u2502 \\                     / \u2502      \u2502                  |      \u2502\n      \u2502  \\                   /  \u2502      \u2502                  |      \u2502\n      \u2502   \\                 /   \u2502      \u2502_      ___________!     _\u2502\n    L \u2502    \\               /    \u2502   L' \u2502      |                  \u2502\n      \u2502     \\             /     \u2502      \u2502      |                  \u2502\n      \u2502      \\           /      \u2502      \u2502      |                  \u2502\n    0 \u2502       \\_________/       \u2502   -1 \u2502------\u2518                  \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -3                        3      -2                        2\n                 y\u0302 - y                            y\u0302 - y\n```\n\"\"\"\nstruct L1EpsilonInsLoss{T<:AbstractFloat} <: DistanceLoss\n    \u03b5::T\n\n    function L1EpsilonInsLoss{T}(\u025b::T) where T\n        \u025b > 0 || error(\"\u025b must be strictly positive\")\n        new{T}(\u025b)\n    end\nend\nconst EpsilonInsLoss = L1EpsilonInsLoss\n@inline L1EpsilonInsLoss(\u03b5::T) where {T<:AbstractFloat} = L1EpsilonInsLoss{T}(\u03b5)\n@inline L1EpsilonInsLoss(\u03b5::Number) = L1EpsilonInsLoss{Float64}(Float64(\u03b5))\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.\u03b5)\nend\nfunction deriv(loss::L1EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    abs(difference) <= loss.\u03b5 ? 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.\u03b5\nistwicedifferentiable(::L1EpsilonInsLoss) = false\nistwicedifferentiable(loss::L1EpsilonInsLoss, at) = abs(at) != loss.\u03b5\nislipschitzcont(::L1EpsilonInsLoss) = true\nisconvex(::L1EpsilonInsLoss) = true\nisstrictlyconvex(::L1EpsilonInsLoss) = false\nisstronglyconvex(::L1EpsilonInsLoss) = false\n\n# ===========================================================\n\n@doc doc\"\"\"\n    L2EpsilonInsLoss <: DistanceLoss\n\nThe quadratic ``\u03f5``-insensitive loss.\nTypically used in linear support vector regression.\nIt ignores deviances smaller than ``\u03f5``, 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 (\u03f5=0.5)             Derivative\n      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    8 \u2502                         \u2502    1 \u2502                  /      \u2502\n      \u2502:                       :\u2502      \u2502                 /       \u2502\n      \u2502'.                     .'\u2502      \u2502                /        \u2502\n      \u2502 \\.                   ./ \u2502      \u2502_         _____/        _\u2502\n    L \u2502  \\.                 ./  \u2502   L' \u2502         /               \u2502\n      \u2502   \\.               ./   \u2502      \u2502        /                \u2502\n      \u2502    '\\.           ./'    \u2502      \u2502       /                 \u2502\n    0 \u2502      '-._______.-'      \u2502   -1 \u2502      /                  \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -3                        3      -2                        2\n                 y\u0302 - y                            y\u0302 - y\n```\n\"\"\"\nstruct L2EpsilonInsLoss{T<:AbstractFloat} <: DistanceLoss\n    \u03b5::T\n\n    function L2EpsilonInsLoss{T}(\u025b::T) where T\n        \u025b > 0 || error(\"\u025b must be strictly positive\")\n        new{T}(\u025b)\n    end\nend\nL2EpsilonInsLoss(\u03b5::T) where {T<:AbstractFloat} = L2EpsilonInsLoss{T}(\u03b5)\nL2EpsilonInsLoss(\u03b5) = L2EpsilonInsLoss{Float64}(Float64(\u03b5))\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.\u03b5))\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.\u03b5 ? zero(T) : convert(T,2)*sign(difference)*(absr - loss.\u03b5)\nend\nfunction deriv2(loss::L2EpsilonInsLoss{T1}, difference::T2) where {T1,T2<:Number}\n    T = promote_type(T1,T2)\n    abs(difference) <= loss.\u03b5 ? 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.\u03b5\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      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    2 \u2502                         \u2502    1 \u2502                   _--'''\u2502\n      \u2502\\                       /\u2502      \u2502                ./'      \u2502\n      \u2502 \\.                   ./ \u2502      \u2502              ./         \u2502\n      \u2502  '.                 .'  \u2502      \u2502_           ./          _\u2502\n    L \u2502   '.               .'   \u2502   L' \u2502           ./            \u2502\n      \u2502     \\.           ./     \u2502      \u2502         ./              \u2502\n      \u2502      '.         .'      \u2502      \u2502       ./                \u2502\n    0 \u2502        '-.___.-'        \u2502   -1 \u2502___.-''                  \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -3                        3      -4                        4\n                 y\u0302 - y                            y\u0302 - 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 \u03c4-quantiles.\nIt is Lipschitz continuous and convex, but not strictly convex.\nFurthermore it is symmetric if and only if `\u03c4 = 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 (\u03c4=0.7)             Derivative\n      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    2 \u2502'\\                       \u2502  0.3 \u2502            \u250c------------\u2502\n      \u2502  \\.                     \u2502      \u2502            |            \u2502\n      \u2502   '\\                    \u2502      \u2502_           |           _\u2502\n      \u2502     \\.                  \u2502      \u2502            |            \u2502\n    L \u2502      '\\              ._-\u2502   L' \u2502            |            \u2502\n      \u2502        \\.         ..-'  \u2502      \u2502            |            \u2502\n      \u2502         '.     _r/'     \u2502      \u2502            |            \u2502\n    0 \u2502           '_./'         \u2502 -0.7 \u2502------------\u2518            \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -3                        3      -3                        3\n                 y\u0302 - y                            y\u0302 - y\n```\n\"\"\"\nstruct QuantileLoss{T <: AbstractFloat} <: DistanceLoss\n    \u03c4::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.\u03c4)\nend\nfunction deriv(loss::QuantileLoss{T1}, diff::T2) where {T1, T2 <: Number}\n    T = promote_type(T1, T2)\n    convert(T,diff > 0) - loss.\u03c4\nend\nderiv2(::QuantileLoss{T1}, diff::T2) where {T1, T2 <: Number} = zero(promote_type(T1, T2))\n\nissymmetric(loss::QuantileLoss) = loss.\u03c4 == 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      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n  2.5 \u2502\\                       /\u2502    1 \u2502                 .-------\u2502\n      \u2502\".                     .\"\u2502      \u2502                |        \u2502\n      \u2502 \".                   .\" \u2502      \u2502               /         \u2502\n      \u2502  \".                 .\"  \u2502      \u2502_           . \"         _\u2502\n    L \u2502   \".               .\"   \u2502   L' \u2502         /\"              \u2502\n      \u2502    '\\.           ./'    \u2502      \u2502       .\"                \u2502\n      \u2502      \\.         ./      \u2502      \u2502       |                 \u2502\n    0 \u2502        \"-. _ .-\"        \u2502   -1 \u2502------\"                  \u2502\n      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n      -3                        3      -3                        3\n                 y\u0302 - y                            y\u0302 - 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), \u201cA New Criterion for Automatic Multilevel Thresholding\u201d, 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\u2080\u2081 = 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\u2080\u2081[i] = img[i] < t ? 0 : 1\r\n  end\r\n  img\u2080\u2081\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": "@testset \"CIC\" begin\n\n    nx = 64 # nombre de pts suivant x\n    ny = 16   # nombre de pts suivant y\n\n    alpha = 0.1\n    kx = 0.5\n    dimx = 2 * pi / kx\n    dimy = 1\n\n    mesh = TwoDGrid(dimx, nx, dimy, ny)\n\n    dx = mesh.dx\n    dy = mesh.dy\n\n    rho = zeros(nx, ny)\n\n    for i = 1:nx\n        aux2 = alpha * cos(kx * mesh.x[i])\n        for j = 1:ny\n            rho[i, j] = aux2\n        end\n    end\n\n    nbpart = 1000 * nx * ny\n\n    p = ParticleGroup{2,2}(nbpart, charge = 1.0, mass = 1.0, n_weights = 1)\n\n    sampler = LandauDamping(alpha, kx)\n\n    ParticleInCell.sample!(p, mesh, sampler)\n\n    kernel = CloudInCell()\n\n    \u03c1 = compute_rho(p, kernel, mesh)\n\n    @test \u03c1 \u2248 rho atol=1e-2\n\nend\n\n\n", "meta": {"hexsha": "02ea2108cbc411f26e5ac415dd813802f06e1380", "size": 692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_particles.jl", "max_stars_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_stars_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-16T04:53:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T17:21:12.000Z", "max_issues_repo_path": "test/test_particles.jl", "max_issues_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_issues_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_issues_repo_licenses": ["MIT"], "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_particles.jl", "max_forks_repo_name": "JuliaVlasov/ParticleInCell.jl", "max_forks_repo_head_hexsha": "31074236e7bcc238b17c2994e56195d6d031c6f6", "max_forks_repo_licenses": ["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.4761904762, "max_line_length": 75, "alphanum_fraction": 0.5260115607, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491797, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7504171857788114}}
{"text": "using NURBS\nusing Base.Test\n\n@testset \"Order Increasing\" begin\n    \n    @testset \"From order 2 to 3\" begin\n        x = knot(4,2)\n        b = [1. 2 3 4;1 2 2 1;1 1 1 1]\n        @test typeof(raise23(b,x,4)) == Tuple{Array{Float64,2},Int64}\n        @test raise23(b,x,4)[1] == [1 1.5 2 2.5 3 3.5 4; 1 1.5 2 2 2 1.5 1; 1 1 1 1 1 1 1]\n        @test raise23(b,x,4)[2] == 7\n        x = [0, 0., 1, 1, 2, 2]\n        @test typeof(raise23(b,x,4)) == Tuple{Array{Float64,2},Int64}\n        @test raise23(b,x,4)[1] == [1 1.5 2 3 3.5 4; 1 1.5 2 2 1.5 1; 1 1 1 1 1 1]\n        @test raise23(b,x,4)[2] == 6\n        x = knotu(4,2)\n        @test typeof(raise23(b,x,4)) == Tuple{Array{Float64,2},Int64}\n        @test raise23(b,x,4)[1] == [0.5 1 1.5 2 2.5 3 3.5 4 2;0.5 1 1.5 2 2 2 1.5 1 0.5;0.5 1 1 1 1 1 1 1 0.5]\n        @test raise23(b,x,4)[2] == 9\n    end\n    \n    @testset \"From order 4 to 5\" begin\n        x = knot(4,4)\n        b = [1. 2 3 4 ; 1 2 2 1 ; 1 1 1 1]\n        @test typeof(raise45(b,x,4)) == Tuple{Array{Float64,2},Int64}\n        @test raise45(b,x,4)[1] == [1 1.75 2.5 3.25 4; 1 1.75 2 1.75 1; 1 1 1 1 1]\n        @test raise45(b,x,4)[2] == 5\n        x = knot(5,4)\n        b = [1. 2 3 4 5; 1 2 2 1 0; 1 1 1 1 1]\n        @test typeof(raise45(b,x,5)) == Tuple{Array{Float64,2},Int64}\n        @test raise45(b,x,5)[1] == [1 1.75 2.25 3 3.75 4.25 5; 1 1.75 2 1.875 1.25 0.75 0.0; 1 1 1 1 1 1 1]\n        @test raise45(b,x,5)[2] == 7\n        x = knot(6,4)\n        b = [1. 2 3 4 5 6; 1 2 2 1 0 0; 1 1 1 1 1 1]\n        @test typeof(raise45(b,x,6)) == Tuple{Array{Float64,2},Int64}\n        @test isapprox(raise45(b,x,6)[1], [1 1.75 2.25 2.95833 3.5 4.04167 4.75 5.25 6; 1 1.75 2 1.91667 1.5 0.958333 0.25 0.0 0.0; 1 1 1 1 1 1 1 1 1], atol=5e-4)\n        @test raise45(b,x,6)[2] == 9\n        x = knot(7,4)\n        b = [1. 2 3 4 5 6 7; 1 2 2 1 0 0 1; 1 1 1 1 1 1 1]\n        @test typeof(raise45(b,x,7)) == Tuple{Array{Float64,2},Int64}\n        @test isapprox(raise45(b,x,7)[1], [1 1.75 2.25 2.95833 3.5 4 4.5 5.04167 5.75 6.25 7; 1 1.75 2 1.91667 1.5 1 0.5 0.08333 0 0.25 1; 1 1 1 1 1 1 1 1 1 1 1]; atol=1e-5)\n        @test raise45(b,x,7)[2] == 11\n    end\nend\n", "meta": {"hexsha": "0d3f7041276834818bdcfdec5c061b7114af8f5c", "size": 2140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/raise.jl", "max_stars_repo_name": "eOnofri04/IN480", "max_stars_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-06T17:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:30:18.000Z", "max_issues_repo_path": "test/raise.jl", "max_issues_repo_name": "TheChoice04/IN480", "max_issues_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-11-22T18:10:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-07T16:32:36.000Z", "max_forks_repo_path": "test/raise.jl", "max_forks_repo_name": "TheChoice04/IN480", "max_forks_repo_head_hexsha": "3128bfd990925e8926065e075b309cb9bda1355c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-13T14:02:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-13T14:02:03.000Z", "avg_line_length": 47.5555555556, "max_line_length": 173, "alphanum_fraction": 0.5009345794, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7504171841299101}}
{"text": "module TestFunctions\n\nstruct Rosenbrock\n    f\n    \u2207f\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": "###############################################################################\n#\n# Linear regression of Y~X, test slope\n#\n###############################################################################\n\"\"\"\n    test_slope(xs::Array,\n               ys::Array;\n               slope::Number = 0,\n               intercept::Bool = true\n    )\n\nMake linear regression and return the p value of whether the regression slope\n    differs from the given slope, given\n- `xs` Array of x, can be NaN\n- `ys` Array of y, can be NaN\n- `slope` Slope to test\n- `intercept` Optional: if true use intercept in the fitting\n\"\"\"\nfunction test_slope(\n            xs::Array,\n            ys::Array;\n            slope::Number = 0,\n            intercept::Bool = true\n)\n    # filter out NaN from the lists\n    new_x = Float64[];\n    new_y = Float64[];\n    for (x,y) in zip(xs, ys)\n        if ~isnan(x) && ~isnan(y)\n            push!(new_x, x);\n            push!(new_y, y - slope*x);\n        end\n    end\n\n    # put new_x and new_y into a DataFrame\n    df = DataFrame(X=new_x, Y=new_y);\n\n    # run the fitting\n    lr = linear_df_xy(df, intercept);\n\n    # calculate the p value\n    if intercept\n        _slope_p = coeftable(lr).cols[4][2];\n    else\n        _slope_p = coeftable(lr).cols[4][1];\n    end\n\n    return _slope_p\nend\n", "meta": {"hexsha": "51fa91513c19e6f71bdb61d3c35642d53836b8b0", "size": 1294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics/slope.jl", "max_stars_repo_name": "Yujie-W/PlotPlants.jl", "max_stars_repo_head_hexsha": "8ad793bfccb2f1158d39724d930c69451acb8534", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-05T21:20:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T21:20:06.000Z", "max_issues_repo_path": "src/statistics/slope.jl", "max_issues_repo_name": "Yujie-W/PlotPlants.jl", "max_issues_repo_head_hexsha": "8ad793bfccb2f1158d39724d930c69451acb8534", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2020-10-01T01:51:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T15:30:06.000Z", "max_forks_repo_path": "src/statistics/slope.jl", "max_forks_repo_name": "Yujie-W/PlotPlants.jl", "max_forks_repo_head_hexsha": "8ad793bfccb2f1158d39724d930c69451acb8534", "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.3725490196, "max_line_length": 79, "alphanum_fraction": 0.4930448223, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7504171748800863}}
{"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\u00e9 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\u00e9-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) \u00f7 2 + 1\n  if modes <= N\n    throw(ArgumentError(\"Cannot perform a Fourier-Pad\u00e9 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\u00e9 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": "include(\"../../src/MutualInformation/mutual-information.jl\")\ninclude(\"reader_MI_tests.jl\")\n\nfunction get_layer_bins_vector(vector; neuron_nbins = 5, nbins = 5, lower_lim=-1, upper_lim=1)\n    columns = separate_columns(vector)\n    hists = create_bin_histogram.(columns, [neuron_nbins], [lower_lim], [upper_lim])\n    bounds = (get_weights_length.(hists)...,)\n    indices = [getindex.(get_bin.(hists, v),1) for v in vector]\n    indices = [correct_upper_bounds(ind, bounds) for ind in indices]\n    combination_values = get_bin_from_indices.(indices, [bounds])\n    max_value = foldr(*, bounds)\n    create_bin_vector(combination_values, nbins, 1, max_value)\nend\n\nfunction calculate_joint_probability_MI(X, Y, lim_X, lim_Y, nbins)\n    number_neurons_X = length(X[1])\n    bins_X = nbins^(number_neurons_X)\n    if number_neurons_X > 1\n        linearized_X = get_layer_bins_vector(X, neuron_nbins=bins_X, nbins=nbins, lower_lim=lim_X[1], upper_lim=lim_X[2])\n        limits_X = (minimum(linearized_X), maximum(linearized_X))\n    else\n        linearized_X = getindex.(X, 1)\n        limits_X = lim_X\n    end\n\n    number_neurons_Y = length(Y[1])\n    bins_Y = nbins^(number_neurons_Y)\n    if number_neurons_Y > 1\n        linearized_Y = get_layer_bins_vector(Y, neuron_nbins=nbins, nbins=bins_Y, lower_lim=lim_Y[1], upper_lim=lim_Y[2])\n        limits_Y = (minimum(linearized_Y), maximum(linearized_Y))\n    else\n        linearized_Y = getindex.(Y, 1)\n        limits_Y = lim_Y\n    end\n\n    calculate_joint_probability(linearized_X, linearized_Y, limits_X, limits_Y, (bins_X+1, round(Int, (bins_Y))))\nend\n\nfunction get_layer_probabilities(vector; neuron_nbins = 5, nbins = 5, lower_lim=-1, upper_lim=1)\n    columns = separate_columns(vector)\n    hists = create_bin_histogram.(columns, [neuron_nbins], [lower_lim], [upper_lim])\n    probabilities = map(h -> h.weights/sum(h.weights), hists)\n    probability = fit(Histogram, (colunms...), nbins = neuron_nbins)\nend\n\n#mutual_information(calculate_joint_probability()...)\n\n# dt2 = get_numerical_dataset_test2()\n#p2 = calculate_joint_probability_MI(dt2[1], dt2[2], (-2, 1.5), (-1, 1), 3)\n#MI = mutual_information(p2...)\n\n#=\nC\u00e1lculo da informa\u00e7\u00e3o m\u00fatua (caso 1):\n-> Valor te\u00f3rico calculado: I(X;T) = 0.047056227\n-> Valor obtido pela aproxima\u00e7\u00e3o: I(X;T) = 0.04700065437122643 (3 bins)\n-> Valor obtido pela aproxima\u00e7\u00e3o: I(X;T) = 0.04510842519666598 (2 bins)\n\n\nC\u00e1lculo da informa\u00e7\u00e3o m\u00fatua utilizando os valores te\u00f3ricos (caso 2):\n-> Valor te\u00f3rico calculado: I(X;T) = 0.1685846799340601\n-> Valor calculado pela aproxima\u00e7\u00e3o: I(X;T) = 0.16843457465541672 (9 bins)\n-> Valor calculado pela aproxima\u00e7\u00e3o: I(X;T) = 0.05633855652784133 (4 bins)\n=#\n", "meta": {"hexsha": "1363f9c254e1938dab1427ad94e52204d0d753d1", "size": 2660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Mutual Information/mutual_information_test.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": "test/Mutual Information/mutual_information_test.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": "test/Mutual Information/mutual_information_test.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": 41.5625, "max_line_length": 121, "alphanum_fraction": 0.7146616541, "num_tokens": 815, "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    @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\u2080/z + c\u2080/v\u2098\u00b2`\n\nThe algorithm initially uses as an initial guess only the b\u2080 virial \ncoefficient. Then it uses a Newton-Raphson algorithm to compute the\ncompressibility factor\n\n * `b0` b\u2080 parameter of the virial equation\n * `c0` c\u2080 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": "using RedBlackGraph\nusing LinearAlgebra\nusing Test\n\n@testset \"Avus Linear Algebra Tests\" begin\n    r = red_one(1)\n    o = one(r)\n\n    # test dot product of myself and father\n    u = [r, 2, 3, 0, 0]\n    v = [2, r, 0, 0, 0]\n    @test u \u22c5 v == 2\n\n    # test dot product of myself and mother\n    u = [r, 2, 3, 0, 0]\n    v = [3, 0, o, 0, 0]\n    @test u \u22c5 v == 3\n\n    # sample from docs\n    u = [2, 0, 0, 0, r]\n    v = [3, 0, r, 0, 0]\n    @test u \u22c5 v == 5\n\n    # test dot product of my daughter and my father\n    u = [2, 0, 0, 0, o]\n    v = [2, r, 0, 0, 0]\n    @test u \u22c5 v == 4\n\n\n    A = [r 2 3 0 0;\n         0 r 0 2 0;\n         0 0 1 0 0;\n         0 0 0 r 0;\n         2 0 0 0 1]\n    expected_result =  [r 2 3 4 0;\n                        0 r 0 2 0;\n                        0 0 1 0 0;\n                        0 0 0 r 0;\n                        2 4 5 0 1]\n    result = A * A\n    @test result == expected_result\n\n    expected_result =  [r 2 3 4 0;\n                        0 r 0 2 0;\n                        0 0 1 0 0;\n                        0 0 0 r 0;\n                        2 4 5 8 1]\n    result = A * result\n    @test result == expected_result\n\n    A =  [r 2 3 4 0;\n          0 r 0 2 0;\n          0 0 1 0 0;\n          0 0 0 r 0;\n          2 4 5 0 1]\n    u = [2 0 0 0 0]\n    v = [0, 3, 0, 0, 0]\n\n    result = u * A\n    u_lambda = [2 4 5 8 0]\n    @test result == u_lambda\n\n    result = A * v\n    v_lambda = [5; 3; 0; 0; 9]\n    @test result == v_lambda\n\n    A = [r 2 3 0 0;\n         0 r 0 2 0;\n         0 0 1 0 0;\n         0 0 0 r 0;\n         2 0 0 0 1]\n    @test A == A * I\n\nend\n", "meta": {"hexsha": "4c9ddc2f7467d7379630798e35db724944114ae1", "size": 1573, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/linalg_test.jl", "max_stars_repo_name": "rappdw/RedBlackGraph.jl", "max_stars_repo_head_hexsha": "ac4e902b0d889c0dcbf79d5962c5e09f4bb9538d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-21T18:16:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T19:52:50.000Z", "max_issues_repo_path": "test/linalg_test.jl", "max_issues_repo_name": "rappdw/RedBlackGraph.jl", "max_issues_repo_head_hexsha": "ac4e902b0d889c0dcbf79d5962c5e09f4bb9538d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-12-21T19:24:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T01:23:31.000Z", "max_forks_repo_path": "test/linalg_test.jl", "max_forks_repo_name": "rappdw/RedBlackGraph.jl", "max_forks_repo_head_hexsha": "ac4e902b0d889c0dcbf79d5962c5e09f4bb9538d", "max_forks_repo_licenses": ["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.9733333333, "max_line_length": 51, "alphanum_fraction": 0.3884297521, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7504161716708232}}
{"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    \u03bc::Float64 \n    \u03c3::Float64\n    r::Float64\n    \u03c1::Float64  \n    \u03b3::Float64 \n    \u03c8::Float64\n    wmax::Float64\nend\n\nfunction WangWangYangModel(;\u03bc = 0.015, \u03c3 = 0.1, r = 0.035, \u03c1 = 0.04, \u03b3 = 3, \u03c8 = 1.1, wmax = 5000.0)\n    WangWangYangModel(\u03bc, \u03c3, r, \u03c1, \u03b3, \u03c8, 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    \u03bc = m.\u03bc ;  \u03c3 = m.\u03c3 ;  r = m.r ;  \u03c1 = m.\u03c1 ;  \u03b3 = m.\u03b3 ;  \u03c8 = m.\u03c8 ; wmax = m.wmax\n    w = state.w\n    p, pw, pww = y.p, y.pw, y.pww\n    c = (r + \u03c8 * (\u03c1 - r)) * p * pw^(-\u03c8)\n    \u03bcw = (r - \u03bc + \u03c3^2) * w + 1 - c\n    # One only needs a ghost node if \u03bcw <= 0 (since w^2p_ww = 0). In this case, we obtain a formula for pw so that c <= 1\n    if w \u2248 0.0 && \u03bcw <= 0.0\n       pw = ((r + \u03c8 * (\u03c1 - r)) * p)^(1 / \u03c8)\n       c = (r + \u03c8 * (\u03c1 - r)) * p * pw^(-\u03c8)\n       \u03bcw = (r - \u03bc + \u03c3^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 + \u03c8 * (\u03c1 - r)) * pw^(1 - \u03c8) - \u03c8 * \u03c1) / (\u03c8 - 1) + \u03bc - \u03b3 * \u03c3^2 / 2) * p + ((r - \u03bc + \u03b3 * \u03c3^2) * w + 1) * pw + \u03c3^2 * w^2 / 2  * (pww - \u03b3 * pw^2 / p)\n    \u03bcw = 1 + (r - \u03bc + \u03c3^2) * w - c\n    return (pt,), (\u03bcw,), (w = w, p = p, pw = pw, pww = pww, \u03bcw = \u03bcw, 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 \u223c X\u03b2 + \u03f5``, where ``\u03f5 \u223c N(0, \u03c3\u00b2)`` IID.\nFlat prior for `\u03b2`, half-T for `\u03c3`.\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((\u03b2 = as(Array, size(model.x, 2)), \u03c3 = as\u211d\u208a))\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)(\u03b8)\n    @unpack y, x, v = model   # extract data\n    @unpack \u03b2, \u03c3 = \u03b8                 # extract parameters\n    loglikelihood(Normal(0, \u03c3), y .- x*\u03b2) + logpdf(TDist(v), \u03c3)\nend\n\n# Evaluate at model function at some initial valuues\n\nprintln()\nmodel((\u03b2 = [1.0, 2.0, 3.0], \u03c3 = 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\u2207P = ADgradient(:ForwardDiff, P);\n\n# Tune and sample.\n\nresults = mcmc_with_warmup(Random.GLOBAL_RNG, \u2207P, 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 NumericalMethodsforEngineers\nusing Test\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) * \u03a8(x)\n      #\n      # F(x_) := 2*x^2 - x\n      # C(a_) := -4a\n      # \u03a8(x_) := x^2 - x\n      #\n      #Y(x_) := F(x) + C(a)*\u03a8(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    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# For now I will continue to use the E.7.13.jl approach.\n#\n\n", "meta": {"hexsha": "e79aa2e1204702bce3bd600c0afa4eec367f3bd0", "size": 2309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/WRM/Ex.7.13.function.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.13.function.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.13.function.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": 29.2278481013, "max_line_length": 92, "alphanum_fraction": 0.5920311823, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7503975412145627}}
{"text": "include(\"misc.jl\")\r\n\r\nfunction rbfBasis(X1, X2, sigma)\r\n  return exp.(-distancesSquared(X1,X2)/(2*sigma^2))\r\nend\r\n\r\nfunction leastSquaresRBFL2(X, y, l, sigma)\r\n\t# Make RBF basis\r\n\tn = size(X,1)\r\n\tZ = rbfBasis(X, X, sigma)\r\n\r\n\t# Find regression weights minimizing squared error with L2 regularization\r\n\tw = (Z'*Z + eye(size(Z,2))*l)\\(Z'*y)\r\n\r\n\tdisplay(size(w))\r\n\r\n\t# Make linear prediction function\r\n\tpredict(Xtilde) = rbfBasis(Xtilde, X, sigma)*w\r\n\r\n\t# Return model\r\n\treturn LinearModel(predict,w)\r\nend\r\n", "meta": {"hexsha": "eb7227398dbd93da247fe8cc815d7a15bc956619", "size": 504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a1sol/leastSquaresRBFL2.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/leastSquaresRBFL2.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/leastSquaresRBFL2.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.9130434783, "max_line_length": 75, "alphanum_fraction": 0.6666666667, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.750390641002582}}
{"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": "@testset \"Utils\" begin\n    @testset \"sec2rad\" begin\n        # Radians <-> arcseconds\n        @test sec2rad(3600) == deg2rad(1)\n        @test rad2sec(1) == rad2deg(1) * 3600\n    end\n    @testset \"normalize_angle\" begin\n        @testset for a = -15.0:0.1:15.0, b = -15.0:0.2:15.0\n            c = normalize_angle(a, b)\n            @test (b - \u03c0) <= c\n            @test c <= (b + \u03c0)\n            two_k = round((a - c) / \u03c0)\n            @test c \u2248 a - two_k * \u03c0 atol=1.0e-14\n        end\n    end\nend\n", "meta": {"hexsha": "6a6206e022202ca54c579682c5416f3ed70e586e", "size": 490, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/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": "test/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": "test/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": 28.8235294118, "max_line_length": 59, "alphanum_fraction": 0.4755102041, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.750308371839037}}
{"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 \u00d7 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\u1d40Ax + B\u1d40x + 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\u00b2 + 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": "const Prime = UInt64\n\nstruct Primes\n    rangei :: Int64\n    primebits :: BitArray{1}\n    function Primes(n :: Int64)\n        if n < 3\n          if n < 2 return new(-1, falses(0)) # no elements\n          else return new((0, trues(0))) end # n = 2: meaning is 1 element of 2\n        end\n        limi :: Int = (n - 1) \u00f7 2 # calculate the required array size\n        isprimes :: BitArray = trues(limi)\n        @inbounds(\n        for i in 1:limi\n            p = i + i + 1\n            start = (p * p - 1) >>> 1 # shift/divide if LLVM doesn't optimize\n            if start > limi\n                return new(limi, isprimes)\n            end\n            if isprimes[i]\n                for j in start:p:limi\n                  isprimes[j] = false\n                end\n            end\n        end)\n    end\nend\n\nBase.eltype(::Type{Primes}) = Prime\n\nfunction Base.length(P::Primes)::Int64\n    if P.rangei < 0 return 0 end\n    return 1 + count(P.primebits)\nend\n\nfunction Base.iterate(P::Primes, state::Int = 0)::\n                                        Union{Tuple{Prime, Int}, Nothing}\n    lmt = P.rangei\n    if state > lmt return nothing end\n    if state <= 0 return (UInt64(2), 1) end\n    let\n        prmbts = P.primebits\n        i = state\n        @inbounds(\n        while i <= lmt && !prmbts[i] i += 1 end)\n        if i > lmt return nothing end\n        return (i + i + 1, i + 1)\n    end\nend\n", "meta": {"hexsha": "c647ce93f95c2ad4b55a49fe1b028870b77373e8", "size": 1378, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sieve-of-eratosthenes-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/sieve-of-eratosthenes-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/sieve-of-eratosthenes-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": 27.56, "max_line_length": 79, "alphanum_fraction": 0.5021770682, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7503083680258905}}
{"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": "@testset \"Boltzmann\" begin\n    @test RTFOOL.boltzmann(1.0, 1.0) == e^-1.00\n    @test RTFOOL.boltzmann(1.0, 2.0) == e^-2.00\n    @test RTFOOL.boltzmann(0.5, 1.5) == e^-0.75\n\n    @test RTFOOL.boltzmann(1.0, [1.0]) == [1.0]\n    @test RTFOOL.boltzmann(1.0, [2.0]) == [1.0]\n    @test RTFOOL.boltzmann(1.0, [1.0, 1.0]) == [0.5, 0.5]\n    @test RTFOOL.boltzmann(1.0, [1.0, 2.0]) == [e/(1+e), 1/(1+e)]\n    @test RTFOOL.boltzmann(0.5, [0.5, 1.5]) \u2248 [e/(e + \u221ae), \u221ae/(e + \u221ae)]\n    @test RTFOOL.boltzmann(1/3, [1, 2, 3]) ==\n        [e^-(1/3), e^-(2/3), e^-1] / (e^-(1/3) + e^-(2/3) + e^-1)\n\n    @test RTFOOL.boltzmann(1.0, [1.0], [2]) == [1.0]\n    @test RTFOOL.boltzmann(1.0, [2.0], [3]) == [1.0]\n    @test RTFOOL.boltzmann(2.0, [1.0, 1.0], [1, 2]) == [1.0/3, 2.0/3]\n    @test RTFOOL.boltzmann(1.0, [1.0, 2.0], [2, 1]) == [2e/(1+2e), 1/(1+2e)]\n    @test RTFOOL.boltzmann(0.5, [0.5, 1.5], [2, 3]) \u2248 [2e/(2e + 3*\u221ae), 3*\u221ae/(2e + 3*\u221ae)]\n    @test RTFOOL.boltzmann(1/3, [1, 2, 3], [1, 2, 3]) ==\n        [e^-(1/3), 2e^-(2/3), 3e^-1] / (e^-(1/3) + 2e^-(2/3) + 3e^-1)\n\n    let space = StateSpace{1}([(1,)], [1.0], BigInt[2])\n        @test RTFOOL.boltzmann(1.0, space) == [1.0]\n    end\n    let space = StateSpace{1}([(1,)], [2.0], BigInt[3])\n        @test RTFOOL.boltzmann(1.0, [2.0], [3]) == [1.0]\n    end\n    let space = StateSpace{2}([(1,1), (2,2)], [1.0, 1.0], BigInt[1,2])\n        @test RTFOOL.boltzmann(2.0, space) == [1.0/3, 2.0/3]\n    end\n    let space = StateSpace{2}([(1,1),(2,2)], [1.0, 2.0], BigInt[2,1])\n        @test RTFOOL.boltzmann(1.0, space) == [2e/(1+2e), 1/(1+2e)]\n    end\n    let space = StateSpace{2}([(1,1),(2,2)], [0.5, 1.5], BigInt[2,3])\n        @test RTFOOL.boltzmann(0.5, space) \u2248 [2e/(2e + 3*\u221ae), 3*\u221ae/(2e + 3*\u221ae)]\n    end\n    let space = StateSpace{3}([(1,1,1), (1,1,2), (1,2,2)], [1,2,3], BigInt[1,2,3])\n        @test RTFOOL.boltzmann(1/3, space) \u2248\n            [e^-(1/3), 2e^-(2/3), 3e^-1] / (e^-(1/3) + 2e^-(2/3) + 3e^-1)\n    end\nend\n", "meta": {"hexsha": "dd448d0f96d15b3da480b10b469fb02cb241335a", "size": 1942, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/boltzmann.jl", "max_stars_repo_name": "ELIFE-ASU/RTFOOL.jl", "max_stars_repo_head_hexsha": "85d7de2fd4190d105505ab002c8937592e0dec02", "max_stars_repo_licenses": ["MIT"], "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/boltzmann.jl", "max_issues_repo_name": "ELIFE-ASU/RTFOOL.jl", "max_issues_repo_head_hexsha": "85d7de2fd4190d105505ab002c8937592e0dec02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-06-12T03:41:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-12T03:42:39.000Z", "max_forks_repo_path": "test/boltzmann.jl", "max_forks_repo_name": "ELIFE-ASU/RTFOOL.jl", "max_forks_repo_head_hexsha": "85d7de2fd4190d105505ab002c8937592e0dec02", "max_forks_repo_licenses": ["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.2380952381, "max_line_length": 88, "alphanum_fraction": 0.4732234809, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7502264139077477}}
{"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\u03c0)/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\u00f3n para pasar avanzar en la construcci\u00f3n de la T\n\"\"\"\nmacro SiguienteT(\u00df, T)\n    quote\n        $(esc(T))  / (1 + $(esc(\u00df))*$(esc(T)))\n    end \nend \n\n\"\"\"\n    Expresi\u00f3n para calcular la beta \n\"\"\"\nmacro calcula\u00df(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    \u00b5 = 0.3\n    M = 15000/maximo_vecinos\n\n    # inicializaciones\n    w = rand(numero_atributos) # vector de tama\u00f1o 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 = \u00b5 * F_w / -log(probabilidad_aceptar_peor)\n    \u00df = (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            \u00df = @calcula\u00df(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(\u00df, 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\u00eddea. \nEse vector de pesos se ha obtenido a partir de un algoritmo de b\u00fasqueda local \n\"\"\"\nfunction EnfriamientoSimulado_LearnerOneNN(data::Matrix{<:Real}, labels)\n    # Creamos funci\u00f3n 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\u00e1metros 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\u00f2 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 \u03b1, \u03b2 = -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 \u03b1, \u03b2 = 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, \u03d5=0, value::Number=1)\n    Gauss2(center::NTuple{2,RealU}, width::NTuple{2,RealU}=(1,1), \u03d5::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(-\u03c0 ((x - cx) / sx)^2)`\nwhere `sx = fwhm2spread(w) = w * sqrt(\u03c0 / log(16))`,\nwhich, for `cx=0`,  has 1D FT `G(\u03bd) = sx^2 exp(\u03c0 (sx \u03bdx)^2)`.\n\"\"\"\nfunction Gauss2(\n    cx::RealU,\n    cy::RealU,\n    wx::RealU,\n    wy::RealU = wx,\n    \u03d5::RealU = 0,\n    value::Number = 1,\n)\n    (cx, cy, wx, wy) = promote(cx, cy, wx, wy)\n    Object(Gauss2(), (cx,cy), (wx,wy), \u03d5, value)\nend\n\nfunction Gauss2(\n    center::NTuple{2,RealU},\n    width::NTuple{2,RealU} = (1,1) .* oneunit(center[1]),\n    \u03d5::RealU = 0,\n    value::Number = 1,\n)\n    Gauss2(center..., width..., \u03d5, 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(-\u03c0 (x/s)^2)``.\n`exp(-\u03c0 (fwhm/2/s)^2) = 1/2` means\n`fwhm/2/s) = sqrt(log(2)/\u03c0)`\n`2s/fwhm = sqrt(\u03c0/log(2))`\n`2s = fwhm * sqrt(\u03c0/log(2))`\n`s = fwhm * sqrt(\u03c0 / log(16))`\n\"\"\"\n@inline fwhm2spread(w) = w * sqrt(\u03c0 / 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(-\u03c0 * sum(abs2.(coords(ob, x, y))) / fwhm2spread(1)^2)\nend\n\n\n\"\"\"\n    radon_gauss2(r, \u03d5, cx, cy, wx, wy, \u03b8)\nRadon transform at `(r,\u03d5)` of 2D Gaussian.\n\"\"\"\nfunction radon_gauss2(r, \u03d5, cx, cy, wx, wy, \u03b8)\n    (sx, sy) = fwhm2spread.((wx, wy))\n    (sin\u03d5, cos\u03d5) = sincos(\u03d5)\n    r -= cx * cos\u03d5 + cy * sin\u03d5 # Radon translation property\n    (sin\u03d5, cos\u03d5) = sincos(\u03d5 - \u03b8) # Radon rotation property\n    s = sqrt(abs2(sx * cos\u03d5) + abs2(sy * sin\u03d5)) # by Fourier-slice Thm.\n    return sx * sy / s * exp(-\u03c0 * abs2(r / s))\nend\n\n\n\"\"\"\n    radon(ob::Object2d{Gauss2})\nReturns function of `(r,\u03d5)` for making a sinogram.\n\"\"\"\nradon(ob::Object2d{Gauss2}) = (r,\u03d5) -> ob.value *\n    radon_gauss2(r, \u03d5, ob.center..., ob.width..., ob.angle[1])\n\n\nfunction spectrum_gauss2(fx, fy, cx, cy, wx, wy, \u03b8)\n    (sx, sy) = fwhm2spread.((wx, wy))\n    (kx, ky) = rotate2d(fx, fy, \u03b8) # rotate first, then translate\n    return sx * exp(-2im*\u03c0*fx*cx) *\n           sy * exp(-2im*\u03c0*fy*cy) * exp(-\u03c0 * (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, \u039b)\n\nCalculate the continuous wavelet transform of a signal given filter bank \u039b.\n\n# Arguments\n - `signal::Vector{Float64}`: Time series.\n - `\u039b::Array{Float64, 2}`: Fourier transformed filters arranged by [frequency, scale].\n\"\"\"\nfunction cwt(signal::Vector{Float64}, \u039b::Array{Float64,2})\n    signal_ft = fft(signal, 1)\n    W = ifft(signal_ft.*\u039b, 1)\n    return W\nend\n\n\"\"\"\n    cwt(signal, \u039b, \u03c90, \u03b4t, \u03b4j)\n\nConvenience method for cwt that constructs the filter bank \u039b 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.\u039b)\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\u20135596\n\nimport Combinatorics: combinations\n\n#### HLLE type\nstruct HLLE{T <: AbstractFloat} <: SpectralResult\n    k::Int\n    \u03bb::AbstractVector{T}\n    proj::Projection{T}\n\n    HLLE{T}(k::Int, \u03bb::AbstractVector{T}, proj::Projection{T}) where T = new(k, \u03bb, proj)\nend\n\n## properties\noutdim(M::HLLE) = size(M.proj, 1)\nprojection(M::HLLE) = M.proj\n\neigvals(M::HLLE) = M.\u03bb\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.\u03bb), 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        \u03bc = mean(X[:,I[:,i]], dims=2)\n        N = X[:,I[:,i]] .- \u03bc\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    \u03bb, V = decompose(transpose(W)*W, d)\n    return HLLE{T}(k, \u03bb, 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    \u03b2::Float64              = 0.9948                        # discount factor \n    \u03b2_mon::Float64          = 1.0/(1.0 + r_mon)             # monthly depreciation rate \n    \u03b3::Float64              = 1.0                           # curvature of utility function \n    \u03bb::Float64              = 0.02                          # exogenous separation rate \n    b::Float64              = 0.4                           # UI benefits \n    B::Float64              = 0.15                          # utility from leisure \n    \u03ba::Float64              = 0.522                         # vacancy posting cost with log utility \n    \u03b8::Float64              = 1.0                           # labor market tightness, v/u, normalized to 1\n    \u03b1::Float64              = 0.5                           # power term in the matching function \n    \u03b7::Float64              = 0.3133                        # scale parameter in the matching function\n    p_\u03b8::Float64            = \u03b7*\u03b8^\u03b1                         # unemployed worker matching rate  \n    q_\u03b8::Float64            = \u03b7*\u03b8^(\u03b1-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    \u03c1_x::Float64            = 0.97                          # persistence of idiosyncratic productivity ln(x)\n    \u03c3_x::Float64            = 0.13                          # std. dev. of innovation to ln(x) \n    \u03c0_x                     = TauchenApprox(9, \u03c1_x, \u03c3_x).distribution           # probability weights on ln(x) \n    xgrid                   = exp.(TauchenApprox(9, \u03c1_x, \u03c3_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    \u03b3 = para.\u03b3 # Store risk-aversion parameter\n\n    # Define the utility mapping \n    # condition on the input `c`\n    if c > 0 \n        if \u03b3 == 1\n          return log(c) # if \u03c3 = 1, CRRA utility is log\n        else\n          return (c^(1-\u03b3)-1)/(1-\u03b3) # if \u03c3 != 1, regular specification\n        end\n    else\n        return -Inf # infinite disutility if c\u2208(-\u221e,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\u00d7X\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 \u03b8\n    @unpack \u03b8, basis_AX, nodes_AX = para\n    \n    # Map all (a,x) to \u03b8*0.9 = 0.9\n    f2d = x -> x[1]^0 * x[2]^0 * \u03b8 * 0.9\n    fvals = [f2d(nodes_AX[i,:]) for i in 1:size(nodes_AX,1)]\n\n    # Interpolate wage schedule over A\u00d7X\n    wage_init = Interpoland(basis_AX, fvals);\n\n    # Return basis for A\u00d7X \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 \u03c1_x, \u03c3_x = para  \n\n    distr = LogNormal(0, \u03c3_x/sqrt(1-\u03c1_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, \u03c0_x, \u03b2, b, B, p_\u03b8, 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\u2032) = (1+r)*ax[1] + wage(ax) - a\u2032 \n        obj_emp     = tmap(a\u2032 -> (1)*(u(c_emp(a\u2032)) + \u03b2 * sum( \u03c0_x[i]*max.(W_old(vec([a\u2032 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\u2032 \n        W_new[i], optimal_a\u2032 = findmax(obj_emp)\n        emp_policy[i] = nodes_A[optimal_a\u2032]\n\n        # If x equals E[x], then \n        # start solving for max. U(a) \n        # and maximizing a\u2032\n        if ax[2] \u2248 1.0 \n            # Update index for U(a) \n            k = k + 1\n            # Create Bellman mapping under unemployment \n            c_unemp(a\u2032) = (1+r)*ax[1] + b - a\u2032\n            obj_unemp   = tmap( a\u2032 -> u(c_unemp(a\u2032)) + B + \u03b2*(1-p_\u03b8)*U_old(ax[1]) .+ \u03b2*(p_\u03b8)*W_old(ax), nodes_A)\n            # Solve for maximum W(a,x) \n            # and maximizing a\u2032\n            U_new[k], optimal_a\u2032 = findmax(obj_unemp)\n            unemp_policy[k] = nodes_A[optimal_a\u2032]\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, \u03f5=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 > \u03f5\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 SymPy\nif VERSION >= v\"0.5.0-dev+7720\"\n    using Base.Test\nelse\n    using BaseTestNext\n    const Test = BaseTestNext\nend\n\n\n@testset \"Matrix\" begin\n    ## matrices\n    (x,) = @syms x\n    A = [x 1; 1 x]\n    b = [x, 2]\n\n\n    ## These fail for older installations of SymPy\n    @test simplify(det(A)) == x^2 - 1\n\n    ## we use inverse for A[:inv]()\n    inv(A) # aliased to use inverse\n    @test simplify((A[:inv]() - inv(A))[1,1]) == 0\n    \n    adjoint(A)\n    dual(A)\n    cholesky(A)\n    ## other functions, could wrap\n    b = subs(A, x, 2)\n    QRdecomposition(b)\n\n    # is_lower, is_square, is_symmetric much slower than julia only counterparts. May deprecate, but for now they are here\n    @test is_lower(A) == istril(A)\n    @test is_square(A) == true\n    @compat @test is_symmetric(A) == issymmetric(A)\n    @test Set(eigvals(A)) == Set([x-1, x+1])\n\n\n    A = [1 0 0; 0 1 0; 0 0 x]\n    evecs = eigvecs(A)\n    @test evecs[1] == [1, 0, 0]\n\n\n    ##\n    M = Sym[1 2 3; 3 6 2; 2 0 1]\n    q,r = QRdecomposition(M)\n    @test (q * r - M)[1,1] == 0\n    if VERSION >= v\"0.5\"\n        L = [Sym[2,3,5], Sym[3,6,2], Sym[8,3,6]]\n        out = GramSchmidt(L)\n    end\n    A = Sym[4 3; 6 3]\n    L, U, _ = LUdecomposition(A)\n    @test L == Sym[1 0; 3//2 1]\n\n    \nend\n", "meta": {"hexsha": "4d3156e57090f67246637821e779f4aa1705fcaf", "size": 1249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-matrix.jl", "max_stars_repo_name": "tkoolen/SymPy.jl", "max_stars_repo_head_hexsha": "8a1bea113344fdc7119547b863e1e0d3ee410919", "max_stars_repo_licenses": ["MIT"], "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-matrix.jl", "max_issues_repo_name": "tkoolen/SymPy.jl", "max_issues_repo_head_hexsha": "8a1bea113344fdc7119547b863e1e0d3ee410919", "max_issues_repo_licenses": ["MIT"], "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-matrix.jl", "max_forks_repo_name": "tkoolen/SymPy.jl", "max_forks_repo_head_hexsha": "8a1bea113344fdc7119547b863e1e0d3ee410919", "max_forks_repo_licenses": ["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.9122807018, "max_line_length": 122, "alphanum_fraction": 0.5428342674, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7502167157040042}}
{"text": "using LinearAlgebra\n\nfunction Cn(v, n::Integer)\n    \u03b8 = 2*\u03c0 / n\n    return rotation_matrix(v, \u03b8)\nend\n\n\"\"\"\n    Molecules.rotation_matrix(v, \u03b8::AbstractFloat)\n\nReturns a rotation matrix by \u03b8 about a rotation axis v\n\"\"\"\nfunction rotation_matrix(V, \u03b8::AbstractFloat)\n    cos\u03b8 = cos(\u03b8)\n    sin\u03b8 = sin(\u03b8)\n    v = normalize(V)\n    a = [1,2,3]\n    O = zeros(eltype(v), (3,3))\n    O .+= 1 - cos\u03b8\n    for i = 1:3, j = 1:3\n        if i == j\n            O[i,i] *= v[i]^2\n            O[i,i] += cos\u03b8\n        else\n            O[i,j] *= v[i]*v[j]\n            b = [i,j]\n            C = [i for i in a if i \u2209 b][1]\n            if i < j\n                O[i,j] += (-1)^(i+j) * v[C]*sin\u03b8\n            else\n                O[i,j] += (-1)^(i+j-1) * v[C]*sin\u03b8\n            end\n        end\n    end\n    return O\nend\n\nfunction rotation_matrixd(v, \u03b8::AbstractFloat)\n    r = deg2rad(\u03b8)\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 \u03c3(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) * \u03c3(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": "      function percentile(perc::Float64,p::Array{Float64,2})\n      \n      sig::Float64=0.0\n      sig0::Float64=0.0\n      sig1::Float64=0.0\n      dsig::Float64=0.0\n      pmin::Float64=0.0\n      delta::Float64=0.0\n      nvec::Int64= size(p,1)*size(p,2)\n      nsig::Int64= Int64(floor(nvec/2)) \n      itnwt::Int64=0\n\n      phi::Float64=0.0\n      phi0::Float64=0.0\n      phi1::Float64=0.0\n      dphi::Float64=0.0\n      TOL::Float64 = 0.000001\n      #\n      pmin=p[1,1]\n      delta=pmin\n      for i2=1:size(p,2)\n          for i1=1:size(p,1)\n              delta=max(delta,p[i1,i2])\n              pmin=min(pmin,p[i1,i2])\n          end\n      end\n      delta=delta-pmin\n      if delta <= 0.0 \n          println(\"Null interval \")\n          return nothing\n      end\n\n      sig0=0.0\n      phi0=0.0\n      for i2=1:size(p,2)\n          for i1=1:size(p,1)\n              if (p[i1,i2]-pmin) >= sig0 \n                 phi0 += 1.0\n              end       \n          end\n      end\n      phi0 = perc - phi0/Float64(nvec)\n      sig1=delta\n      phi1=0.0\n      for i2=1:size(p,2)\n          for i1=1:size(p,1)\n              if (p[i1,i2]-pmin) >= sig1 \n                 phi1+=1.0\n              end       \n          end\n      end\n      \n      phi1=perc - phi1/Float64(nvec)\n      dsig=-phi0*(sig1-sig0)/(phi1-phi0)\n      sig = sig0+dsig\n\n      for itnwt=1:99\n      phi=0.0\n      for i2=1:size(p,2)\n          for i1=1:size(p,1)\n              if (p[i1,i2]-pmin) >= sig \n                 phi=phi+1.0\n              end       \n          end\n      end\n      phi = perc - phi/Float64(nvec)\n\n      if phi*phi0 < 0.0\n         sig1 = sig\n         phi1 = phi\n      else \n         sig0 = sig\n         phi0 = phi\n      end\n      dsig=-phi0*(sig1-sig0)/(phi1-phi0)\n      sig = sig0+dsig\n\n      if  abs(phi) < TOL || abs(dsig) < 1.e-16*delta\n          println(\"iter = \",itnwt)\n          break\n      end \n      end\n\n      sig=sig+pmin\n      println(\"sig = \",sig, \" phi = \",phi, \" dsig = \",dsig)\n\n      return nothing \n      end # function\n       \n\n", "meta": {"hexsha": "c3ae053b8d9b2073cc7be19114c56ac674d262e7", "size": 2005, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/percentile.jl", "max_stars_repo_name": "jesseufpa/afd2d_jl", "max_stars_repo_head_hexsha": "6fc8e93a57fefa8e19a3186846de78d5f7755e85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/percentile.jl", "max_issues_repo_name": "jesseufpa/afd2d_jl", "max_issues_repo_head_hexsha": "6fc8e93a57fefa8e19a3186846de78d5f7755e85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/percentile.jl", "max_forks_repo_name": "jesseufpa/afd2d_jl", "max_forks_repo_head_hexsha": "6fc8e93a57fefa8e19a3186846de78d5f7755e85", "max_forks_repo_licenses": ["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.032967033, "max_line_length": 60, "alphanum_fraction": 0.442394015, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7502167135583684}}
{"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(\"\u03c0\uff08\u8a08\u7b97\u5024\uff09 = \", DIGIT, viete(n))\n    MyPrintf.myprintf(\"\u03c0\uff08\u53b3\u5bc6\u5024\uff09 = \", DIGIT, BigFloat(\u03c0))\n    @printf(\"n = %d, \u8a08\u7b97%d\u6841\u3067\u3001%d\u6841\u6c42\u307e\u308a\u307e\u3057\u305f\\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": "\nfunction u_test(x, y, \u03c3)\n    exp( - ( (x-\u03c0)^2 + (y-\u03c0)^2 ) / (2\u03c3^2) )\nend\n\nfunction testTrapezoidalQuadrature()\n    M = 64\n    N = 64\n\n    \u03c3 = 0.5\n\n    grid = Grid2d(M,N)\n    u    = get_field(grid)\n\n    for i in 1:M\n        for j in 1:N\n            u[i,j]  = u_test(grid.x[i], grid.y[j], \u03c3)\n        end\n    end\n\n    uint = trapezoidal_quadrature(u, u, grid)\n\n    @test uint - \u03c0*\u03c3^2 \u2248 zero(eltype(u)) atol=1E-14\nend\n\n\ntestTrapezoidalQuadrature()\n", "meta": {"hexsha": "83c20f300f592999764b7d5e72ba437910072499", "size": 445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_trapezoidal_quadrature.jl", "max_stars_repo_name": "DDMGNI/VortexCollisions.jl", "max_stars_repo_head_hexsha": "255dce610cd51246cb3249b1524e9be62f5f2245", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-17T15:46:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:08:25.000Z", "max_issues_repo_path": "test/test_trapezoidal_quadrature.jl", "max_issues_repo_name": "DDMGNI/VortexCollisions.jl", "max_issues_repo_head_hexsha": "255dce610cd51246cb3249b1524e9be62f5f2245", "max_issues_repo_licenses": ["MIT"], "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_trapezoidal_quadrature.jl", "max_forks_repo_name": "DDMGNI/VortexCollisions.jl", "max_forks_repo_head_hexsha": "255dce610cd51246cb3249b1524e9be62f5f2245", "max_forks_repo_licenses": ["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.8928571429, "max_line_length": 53, "alphanum_fraction": 0.5258426966, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "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\" => \"\u03bc\", \"sigma\" => \"\u03c3\"))\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": "using ProximalOperators\nusing ProximalAlgorithms\n\n### this test includes two tests\n\n## 1-testing combinations with two terms: Lasso\n\nA = [  1.0  -2.0   3.0  -4.0  5.0;\n       2.0  -1.0   0.0  -1.0  3.0;\n      -1.0   0.0   4.0  -3.0  2.0;\n      -1.0  -1.0  -1.0   1.0  3.0]\nb = [1.0, 2.0, 3.0, 4.0]\n\nm, n = size(A)\n\nf = Translate(SqrNormL2(), -b)\nf2 = LeastSquares(A, b)\nlam = 0.1*norm(A'*b, Inf)\ng = NormL1(lam)\n\nx_star = [-3.877278911564627e-01, 0, 0, 2.174149659863943e-02, 6.168435374149660e-01]\n\n\nstuff = [\n  Dict( \"theta\"      => 2,\n        \"mu\"         => 0,\n        \"it\"         => (70,135,100),\n      ),\n  Dict( \"theta\"      => 1,\n        \"mu\"         => 1,\n        \"it\"         => (80,130,15),\n      ),\n  Dict( \"theta\"      => 0,\n        \"mu\"         => 1,\n        \"it\"         => (90,345,120),\n      ),\n  Dict( \"theta\"      => 0,\n        \"mu\"         => 0,\n        \"it\"         => (80,170,180),\n      ),\n  Dict( \"theta\"      => 1,\n        \"mu\"         => 0,\n        \"it\"         => (90,130,230),\n      )\n  ]\n\nRandom.seed!(0)\n\nfor i = 1:length(stuff)\n\ntheta = stuff[i][\"theta\"]\nmu    = stuff[i][\"mu\"]\nitnum = stuff[i][\"it\"]\n\nx0 = randn(n)\n\n# h\\equiv 0 (FBS)\ny0 = randn(n)\n@time it, x, y, sol = ProximalAlgorithms.AFBA(x0, y0; g=g, f=f2, betaQ =opnorm(A'*A), theta=theta, mu=mu)\nprintln(\"      nnz(x)    = $(norm(sol.x, 2))\")\n@test norm(x - x_star, Inf) <= 1e-4\n@test it <=itnum[1]\nprintln(sol)\n\n@time it, (x, y) = ProximalAlgorithms.run!(sol)\n\n# f=\\equiv 0 (Chambolle-Pock)\ny0 = randn(m)\n@time it, x, y, sol = ProximalAlgorithms.AFBA(x0, y0; g=g, h=f, L=A, theta=theta, mu=mu)\n@test norm(x - x_star, Inf) <= 1e-4\n@test it <=itnum[2]\nprintln(sol)\n\n# g\\equiv 0\ny0 = randn(n) # since L= Identity\n@time it, x, y, sol = ProximalAlgorithms.AFBA(x0, y0; h=g, f=f2, betaQ=opnorm(A'*A), theta=theta, mu=mu)\n@test norm(x - x_star, Inf) <= 1e-4\n@test it <=itnum[3]\nprintln(sol)\n\nend\n\n## 2- testing with three terms: 1/2\\|Ax-b\\|^2+ \u03bb\\|x\\|_1 + + \u03bb_2*\\|x\\|^2\n\nlam2= 1;\n\n\nx0 = randn(n)\ny0 = randn(n)\nitnum= ((130,130),(40,40),(90,90),(150,150),(170,170)); # the number of iterations\n\nfor i = 1:length(stuff)\ntheta = stuff[i][\"theta\"]\nmu    = stuff[i][\"mu\"]\n@time it, x, y, sol = ProximalAlgorithms.AFBA(x0,y0; g=g,f=f2, h = SqrNormL2(lam2), betaQ =opnorm(A'*A), theta=theta, mu=mu)\nprintln(\"      nnz(x)    = $(norm(sol.x, 2))\")\n\n # the optimality conditions\ntemp = lam*sign.(x) + A'*(A*x-b) + lam2*x\nind= findall(x -> abs.(x)<1e-8,x)\nt1= length(findall((temp[ind] .<= lam .* temp[ind] .>=-lam)==false))\nt2= length(findall((abs.(deleteat!(temp,ind)) .<1e-8)==false))\n@test t1+t2 == 0\n@test it <=itnum[i][1]\nprintln(sol)\n\n\n@time it, x, y, sol = ProximalAlgorithms.AFBA(x0,y0; h=g,f=f2, g = SqrNormL2(lam2), betaQ =opnorm(A'*A), theta=theta, mu=mu)\nprintln(\"      nnz(x)    = $(norm(sol.x, 2))\")\n # the optimality conditions\ntemp = lam*sign.(x) + A'*(A*x-b) + lam2*x\nind= findall(x -> abs.(x)<1e-8,x)\nt1= length(findall((temp[ind] .<= lam .* temp[ind] .>=-lam)==false))\nt2= length(findall((abs.(deleteat!(temp,ind)) .<1e-8)==false))\n@test t1+t2 == 0\n@test it <=itnum[i][2]\nprintln(sol)\n\nend\n\n# TODO: add test including function l\n", "meta": {"hexsha": "698d662c928325a7cac04ca0b29f58bf753e6364", "size": 3122, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_afba.jl", "max_stars_repo_name": "nantonel/ProximalAlgorithms.jl", "max_stars_repo_head_hexsha": "29629f31ccd179ad581bdf514f6969e5e28d1b92", "max_stars_repo_licenses": ["MIT"], "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_afba.jl", "max_issues_repo_name": "nantonel/ProximalAlgorithms.jl", "max_issues_repo_head_hexsha": "29629f31ccd179ad581bdf514f6969e5e28d1b92", "max_issues_repo_licenses": ["MIT"], "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_afba.jl", "max_forks_repo_name": "nantonel/ProximalAlgorithms.jl", "max_forks_repo_head_hexsha": "29629f31ccd179ad581bdf514f6969e5e28d1b92", "max_forks_repo_licenses": ["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.5901639344, "max_line_length": 124, "alphanum_fraction": 0.5371556694, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7502167055551164}}
{"text": "#=\n@author : Spencer Lyon <spencer.lyon@nyu.edu>\n          Victoria Gregory <victoria.gregory@nyu.edu>\n\nReferences\n----------\nBased off the original python file binom_df.py\n=#\n\nusing Plots\npyplot()\nusing Distributions\nusing LaTeXStrings\n\nsrand(42)  # reproducible results\nns = [1, 2, 4, 8]\ndom = 1:9\n\npdfs = []\ntitles = []\nfor n in ns\n    b = Binomial(n, 0.5)\n    push!(pdfs, pdf(b, dom))\n    t = LaTeXString(\"\\$n = $n\\$\")\n    push!(titles, t)\nend\n\nbar(dom, pdfs, layout=4, alpha=0.6, xlims=(-0.5, 8.5), ylims=(0, 0.55),\n    xticks=dom, yticks=[0.0, 0.2, 0.4], legend=:none, title=titles')\n", "meta": {"hexsha": "a296c1d2252c5f574c6bcfda407c69831abec219", "size": 590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lln_clt/binom_df.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": "lln_clt/binom_df.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": "lln_clt/binom_df.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": 19.6666666667, "max_line_length": 71, "alphanum_fraction": 0.6169491525, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7502167044651455}}
{"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 \u03b5 = 1e-8\n\n\"\"\"\n    Descent(\u03b7=0.1)\nBasic gradient descent optimizer with learning rate `\u03b7`.\n\n# Parameters\n- learning rate : `\u03b7`\n\n# Example\n\n\"\"\"\nstruct Descent\n    eta::Float64\nend\n\nDescent(;\u03b7::Float64 = 0.1) = Descent(\u03b7)\n\napply!(opt::Descent, x::Array, \u0394::Array) = opt.eta .* \u0394\n\n\"\"\"\n    Momentum(\u03b7=0.01, \u03b1=0.9, velocity)\nMomentum gradient descent optimizer with learning rate `\u03b7` and parameter of velocity `\u03b1`.\n\n# Parameters\n- learning rate : `\u03b7`\n- parameter of velocity : `\u03b1`\n\n# Example\n\n\"\"\"\nstruct Momentum\n    eta::Float64\n    alpha::Float64\n    velocity::Dict\nend\n\nMomentum(\u03b7 = 0.01, \u03b1 = 0.9) = Momentum(\u03b7, \u03b1, Dict())\n\nfunction apply!(opt::Momentum, x::Array, \u0394::Array)\n    \u03b7, \u03b1 = opt.eta, opt.alpha\n    v = get!(() -> zero(x), opt.velocity, x)::typeof(x) #get!() function returns a view.\n    @. v = (\u03b1*v - \u03b7*\u0394)\n    @. \u0394 = -v\nend\n\n\"\"\"\n    AdaGrad(\u03b7 = 0.01)\nGradient descent optimizer with learning rate attenuation.\n\n# Parameters\n- \u03b7 : initial learning rate\n\n# Examples\n\n\"\"\"\nstruct AdaGrad\n    eta::Float64\n    h::Dict\nend\n\nAdaGrad(\u03b7 = 0.01) = AdaGrad(\u03b7, Dict())\n\nfunction apply!(opt::AdaGrad, x::Array, \u0394::Array)\n    \u03b7 = opt.eta\n    h = get!(() -> zero(x), opt.h, x)::typeof(x)\n    @. h += \u0394^2\n    @. \u0394 *= \u03b7 / (\u221ah + \u03b5)\n    return \u0394\nend\n\n\"\"\"\n    Adam(\u03b7=0.01, \u03b2=(0.9, 0.99))\nGradient descent adaptive moment estimation optimizer.\n\n# Parameters\n- \u03b7 : learning rate\n- \u03b2 : Decay of momentums\n\n# Examples\n\n\"\"\"\nstruct Adam\n    eta::Float64\n    beta::Tuple{Float64, Float64}\n    recode::Dict\nend\n\nAdam(\u03b7 = 0.01, \u03b2 = (0.9, 0.99)) = Adam(\u03b7, \u03b2, Dict())\n\nfunction apply!(opt::Adam, x::Array, \u0394::Array)\n    \u03b7, \u03b2 = opt.eta, opt.beta\n    mt, vt , \u03b2p = get!(opt.recode, x) do\n        (zero(x), zero(x), Float64[\u03b2[1], \u03b2[2]])\n    end::Tuple{typeof(x),typeof(x),Vector{Float64}}\n    @. mt = \u03b2[1] * mt + (1 - \u03b2[1]) * \u0394\n    @. vt = \u03b2[2] * vt + (1 - \u03b2[2]) * \u0394^2\n    @. \u0394 =  mt / (1 - \u03b2p[1]) / (\u221a(vt / (1 - \u03b2p[2])) + \u03b5) * \u03b7\n    \u03b2p .= \u03b2p .* \u03b2    \n    return \u0394\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": "using EmpiricalCDFs\n\n# Create an empirical cdf with 10^6 normally distributed samples\ncdf = EmpiricalCDF(randn(10^6))\n\n# add another sample\npush!(cdf, randn())\n\n# add 10^6 more samples\nappend!(cdf, randn(10^6))\n\n# sort the cdf before using it\nsort!(cdf)\n\n# Pick a random sample from the distribution approximated by `cdf`\nrand(cdf)\n\n# The normal distribution is symmetric, so this should be about 0.5\ncdf(0)\n\n# This should be approximately zero\ngetinverse(cdf,.5)\n\n", "meta": {"hexsha": "9215a5949d4c44ca8f59912370ffc160c8e19fda", "size": 465, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/example.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalCDFs.jl-0dcf7749-4f9f-5e13-9c57-506664207bbc", "max_stars_repo_head_hexsha": "dafe5a77a159823b413ba7ab9219424219f73434", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-05-09T16:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T07:46:20.000Z", "max_issues_repo_path": "example/example.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalCDFs.jl-0dcf7749-4f9f-5e13-9c57-506664207bbc", "max_issues_repo_head_hexsha": "dafe5a77a159823b413ba7ab9219424219f73434", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-12-13T08:43:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-21T08:46:00.000Z", "max_forks_repo_path": "example/example.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/EmpiricalCDFs.jl-0dcf7749-4f9f-5e13-9c57-506664207bbc", "max_forks_repo_head_hexsha": "dafe5a77a159823b413ba7ab9219424219f73434", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-05-21T17:48:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:17.000Z", "avg_line_length": 19.375, "max_line_length": 67, "alphanum_fraction": 0.7440860215, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7502166996631942}}
{"text": "\"\"\"\n    fill_nans(x, intp::Linear)\n\nFill `NaN` values in `x` using linear interpolation. `NaN`s at \nthe left or right edges of `x` are not interpolated, but left\nas they are. See also [`fill_nans!`](@ref).\n\n## Example \n\n```julia\nx = [NaN, 1.4, 5.6, NaN, 4.3, 3.1, NaN, NaN, 5.6, NaN]\nfill_nans(x, Linear())\n```\n\"\"\"\nfunction fill_nans(x, intp::Linear)\n    if isnan(x[1]) && isnan(x[end])\n        nan_chunks = findall_nan_chunks(x)[2:end-1]\n    elseif isnan(x[1])\n        nan_chunks = findall_nan_chunks(x)[2:end]\n    elseif isnan(x[end])\n        nan_chunks = findall_nan_chunks(x)[1:end-1]\n    else\n        nan_chunks = findall_nan_chunks(x)\n    end\n    \n    x_filled = copy(x)\n    \n    for (start_idx, stop_idx) in nan_chunks\n        x1 = start_idx - 1\n        x2 = stop_idx + 1\n        \n        y1 = x[start_idx - 1]\n        y2 = x[stop_idx + 1]\n\n        slope = (y2 - y1) / (x2 - x1)\n        \n        intcpt = y1 - slope*x1\n        \n        for (i, idx) in enumerate(start_idx:stop_idx)\n            x_filled[idx] = y1 + i*slope\n        end\n    end\n    \n    return x_filled\nend\n\n\"\"\"\n    fill_nans!(x, intp::Linear)\n\nFill `NaN` values in `x` in-place using linear interpolation. `NaN`s at \nthe left or right edges of `x` are not interpolated, but left\nas they are. See also [`fill_nans`](@ref).\n\n## Example \n\n```julia\nx = [NaN, 1.4, 5.6, NaN, 4.3, 3.1, NaN, NaN, 5.6, NaN]\nfill_nans!(x, Linear())\n```\n\"\"\"\nfunction fill_nans!(x, intp::Linear)\n    if isnan(x[1]) && isnan(x[end])\n        nan_chunks = findall_nan_chunks(x)[2:end-1]\n    elseif isnan(x[1])\n        nan_chunks = findall_nan_chunks(x)[2:end]\n    elseif isnan(x[end])\n        nan_chunks = findall_nan_chunks(x)[1:end-1]\n    else\n        nan_chunks = findall_nan_chunks(x)\n    end\n        \n    for (start_idx, stop_idx) in nan_chunks\n        x1 = start_idx - 1\n        x2 = stop_idx + 1\n        \n        y1 = x[start_idx - 1]\n        y2 = x[stop_idx + 1]\n\n        slope = (y2 - y1) / (x2 - x1)\n        \n        intcpt = y1 - slope*x1\n        \n        for (i, idx) in enumerate(start_idx:stop_idx)\n            x[idx] = y1 + i*slope\n        end\n    end\n    \n    return x\nend\n\n\nexport fill_nans, fill_nans!", "meta": {"hexsha": "cd21f3b5b72aeb4af083cc302d3d5855c10de88c", "size": 2162, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolation_and_binning/fill_nans.jl", "max_stars_repo_name": "JuliaTagBot/UncertainData.jl", "max_stars_repo_head_hexsha": "4d9dc513b97f04a1d761e0a94eab3e3b11cc4c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-01-04T10:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T01:11:13.000Z", "max_issues_repo_path": "src/interpolation_and_binning/fill_nans.jl", "max_issues_repo_name": "JuliaTagBot/UncertainData.jl", "max_issues_repo_head_hexsha": "4d9dc513b97f04a1d761e0a94eab3e3b11cc4c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 78, "max_issues_repo_issues_event_min_datetime": "2018-12-17T20:12:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T20:46:04.000Z", "max_forks_repo_path": "src/interpolation_and_binning/fill_nans.jl", "max_forks_repo_name": "JuliaTagBot/UncertainData.jl", "max_forks_repo_head_hexsha": "4d9dc513b97f04a1d761e0a94eab3e3b11cc4c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-01-22T23:05:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T12:21:02.000Z", "avg_line_length": 23.5, "max_line_length": 72, "alphanum_fraction": 0.5605920444, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7501951072333014}}
{"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\u0393y = noise_level * Matrix(I, n_obs, n_obs) \nnoise = MvNormal(zeros(n_obs), \u0393y)\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, \u0393y, 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, \u0393y, 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": "function MatrixTest(game_type)\r\n    ## RPS\r\n    RPS = game_type([\r\n        (0,0) (-1,1) (1,-1);\r\n        (1,-1) (0,0) (-1,1);\r\n        (-1,1) (1,-1) (0,0)\r\n    ])\r\n    init_strategy = [0.1,0.2,0.7]\r\n    p1 = player(RPS, 1, init_strategy); p2 = player(RPS, 2, init_strategy)\r\n    train_both!(p1, p2, 100_000)\r\n    # p = plot(p1, p2, lw=2);\r\n    # title!(p, \"RM RPS NE\")\r\n    # display(p)\r\n\r\n    RPS_NE_strat = fill(1/3,3)\r\n    @test isapprox(p1.strategy, RPS_NE_strat, atol=0.01)\r\n    @test isapprox(p2.strategy, RPS_NE_strat, atol=0.01)\r\n\r\n    p1 = player(RPS, 1, init_strategy)\r\n    p2 = player(RPS, 2, init_strategy)\r\n    train_one!(p1, p2, 10_000)\r\n    # p = plot(p1,p2, lw=2);\r\n    # title!(p, \"RM RPS Exploitative\")\r\n    # display(p)\r\n\r\n    @test isapprox(p1.strategy, Float64[1,0,0], atol=0.01)\r\n    @test p2.strategy == init_strategy\r\n\r\n\r\n    ## Prisoners Dilemma\r\n    PD = game_type([\r\n        (-1,-1) (-3,0);\r\n        (0,-3) (-2,-2)\r\n    ])\r\n    p1 = player(PD, 1)\r\n    p2 = player(PD, 2)\r\n\r\n    train_both!(p1,p2, 10_000)\r\n    # p = plot(p1,p2, lw=2);\r\n    # title!(p, \"RM Prisoner's Dilemma\")\r\n    # display(p)\r\n\r\n    PD_NE_strat = Float64[0,1]\r\n    @test isapprox(p1.strategy, PD_NE_strat, atol=0.01)\r\n    @test isapprox(p2.strategy, PD_NE_strat, atol=0.01)\r\n\r\n\r\n    # https://sites.math.northwestern.edu/~clark/364/handouts/bimatrix-mixed.pdf\r\n    game = game_type([\r\n        (1,1) (0,0) (0,0);\r\n        (0,0) (0,2) (3,0);\r\n        (0,0) (2,0) (0,3);\r\n    ])\r\n    p1 = player(game, 1)\r\n    p2 = player(game, 2)\r\n    train_both!(p1,p2, 100_000)\r\n    NEs = [[6/11,3/11,2/11], [0,3/5,2/5], [1,0,0]]\r\n    s1 = p1.strategy; s2 = p2.strategy\r\n    @test begin\r\n        \u2248(s1, NEs[1], atol=0.01) ||\r\n        \u2248(s1, NEs[2], atol=0.01) ||\r\n        \u2248(s1, NEs[3], atol=0.01)\r\n    end\r\n    @test begin\r\n        \u2248(s2, NEs[1], atol=0.01) ||\r\n        \u2248(s2, NEs[2], atol=0.01) ||\r\n        \u2248(s2, NEs[3], atol=0.01)\r\n    end\r\n\r\n    v = evaluate(p1,p2)\r\n    @test begin\r\n        all( .\u2248(v,(6/5,6/5), atol=0.01)) ||\r\n        all( .\u2248(v,(6/11,6/11), atol=0.01)) ||\r\n        all( .\u2248(v,(1,1), atol=0.01))\r\n    end\r\nend\r\n\r\n@testset \"RM Matrix\" begin MatrixTest(MatrixGame) end\r\n\r\n@testset \"CFR Matrix\" begin MatrixTest(SimpleIIGame) end\r\n", "meta": {"hexsha": "e426e9aa0826e88dc0275685e5c86b8f0e1d7835", "size": 2223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testMatrix.jl", "max_stars_repo_name": "WhiffleFish/HelloCFR", "max_stars_repo_head_hexsha": "326c485584224a708f62c7a4b2893aebceadeeda", "max_stars_repo_licenses": ["MIT"], "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/testMatrix.jl", "max_issues_repo_name": "WhiffleFish/HelloCFR", "max_issues_repo_head_hexsha": "326c485584224a708f62c7a4b2893aebceadeeda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-17T22:53:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T23:14:32.000Z", "max_forks_repo_path": "test/testMatrix.jl", "max_forks_repo_name": "WhiffleFish/HelloCFR", "max_forks_repo_head_hexsha": "326c485584224a708f62c7a4b2893aebceadeeda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T18:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T18:04:56.000Z", "avg_line_length": 27.4444444444, "max_line_length": 81, "alphanum_fraction": 0.5083220873, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580401, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7501950953970368}}
{"text": "function newton(f::Function,x::Array{T,1},tol::T,maxiters::S) where {T<: AbstractFloat, S<: Int}\n\n  n = length(x)\n  x_new = similar(x)\n\n  iter = 0\n  len = Inf\n  while len > tol\n\n    g = derivative(f,x)\n  \tupdate = g\\f(x)\n  \tfor i = 1:n\n  \t  x_new[i] = x[i] - update[i]\n  \tend\n\n    len = maximum(abs,x_new-x)\n    x = copy(x_new)\n\n    iter += 1\n    if iter >= maxiters\n      break\n    end\n\n  end\n\n  return x_new, f(x_new), iter\n\nend\n", "meta": {"hexsha": "bd7d54c94538d05fff7e6e1a8dfe9ed6b5e2f6a5", "size": 431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.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/newton.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/newton.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": 14.8620689655, "max_line_length": 96, "alphanum_fraction": 0.5545243619, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7501950953670418}}
{"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 \u03b1\nfor alpha in [0.1, 0.3, 0.5, 0.7, 0.9]\n    \n    push!(models, RheoModel(FractS_Maxwell, (c\u2090 = 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 \u03b2\nfor beta in [0.1, 0.3, 0.5, 0.7, 0.9]\n    \n    push!(models, RheoModel(FractD_Maxwell, (\u03b7 = 10, c\u1d66= 1.0, \u03b2 = 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, (\u03b7 = 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(\u03c72 | 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 \u03c72 \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 \u0394(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 \u0394(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": "\"\"\"\nPollard's rho algorithm (https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm)\n\"\"\"\nmodule PollardRho\n\n#=\nAccording to <https://stackoverflow.com/a/48208795>, Pollard's rho algorithm does not always find\nthe factors of perfect powers.\n=#\n\nfunction squared_plus_1(n::Integer)\n    function f(a::Integer)::Integer\n        a2 = powermod(a, 2, n)\n        mod(a2 + 1, n)\n    end\nend\n\nfunction pollard_rho_factor(n::Integer, f::Function=squared_plus_1(n))::Integer\n    # Brent's cycle detection algorithm\n    l = 0\n    tortoise = hare = 2  # the smallest prime\n    cycle_len = 2  # prime gap\n    factor = 1\n    while factor == 1\n        if l == cycle_len\n            tortoise = hare\n            cycle_len *= 2\n            l = 0\n        end\n        hare = f(hare)\n        l += 1\n        factor = gcd(hare - tortoise, n)\n    end\n    factor\nend\n\n# Unit tests\nusing Test\n\nfunction check_prime(n::Integer)::Bool\n    factor = pollard_rho_factor(n)\n    n == factor\nend\n\nfunction check_composite(n::Integer)::Bool\n    factor = pollard_rho_factor(n)\n    1 < factor < n && n % factor == 0\nend\n\n@testset \"PollardRho\" begin\n    prime_list = [7, 4567, 15960005471, 1238926361552897]\n    composite_list = [\n        101 * 103, 1009 * 1013, 10007 * 10009,\n        1234567,\n        12389263_66_1552897,\n    ]\n    @test check_prime.(prime_list) |> all\n    @test check_composite.(composite_list) |> all\nend\n\nend  # module\n", "meta": {"hexsha": "b85de7de865d7778619ac51b09a5fab436aad401", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PollardRho/PollardRho.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": "PollardRho/PollardRho.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": "PollardRho/PollardRho.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.6129032258, "max_line_length": 97, "alphanum_fraction": 0.6269614836, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.750195091451615}}
{"text": "using ModelingToolkit, OrdinaryDiffEq, Test, LinearAlgebra\n\n@parameters t \u03c3 \u03c1 \u03b2\n@variables x(t) y(t) z(t) k(t)\nD = Differential(t)\n\neqs = [D(D(x)) ~ \u03c3 * (y - x),\n    D(y) ~ x * (\u03c1 - z) - y,\n    D(z) ~ x * y - \u03b2 * z]\n\n@named sys\u2032 = ODESystem(eqs)\nsys = ode_order_lowering(sys\u2032)\n\neqs2 = [0 ~ x * y - k,\n    D(D(x)) ~ \u03c3 * (y - x),\n    D(y) ~ x * (\u03c1 - z) - y,\n    D(z) ~ x * y - \u03b2 * z]\n@named sys2 = ODESystem(eqs2, t, [x, y, z, k], parameters(sys\u2032))\nsys2 = ode_order_lowering(sys2)\n# test equation/varible ordering\nModelingToolkit.calculate_massmatrix(sys2) == Diagonal([1, 1, 1, 1, 0])\n\nu0 = [D(x) => 2.0,\n    x => 1.0,\n    y => 0.0,\n    z => 0.0]\n\np = [\u03c3 => 28.0,\n    \u03c1 => 10.0,\n    \u03b2 => 8 / 3]\n\ntspan = (0.0, 100.0)\nprob = ODEProblem(sys, u0, tspan, p, jac = true)\nprobexpr = ODEProblemExpr(sys, u0, tspan, p, jac = true)\nsol = solve(prob, Tsit5())\nsolexpr = solve(eval(prob), Tsit5())\n@test all(x -> x == 0, Array(sol - solexpr))\n#using Plots; plot(sol,vars=(:x,:y))\n\n@parameters t \u03c3 \u03c1 \u03b2\n@variables x(t) y(t) z(t)\nD = Differential(t)\n\neqs = [D(x) ~ \u03c3 * (y - x),\n    D(y) ~ x * (\u03c1 - z) - y,\n    D(z) ~ x * y - \u03b2 * z]\n\nlorenz1 = ODESystem(eqs, name = :lorenz1)\nlorenz2 = ODESystem(eqs, name = :lorenz2)\n\n@variables \u03b1(t)\n@parameters \u03b3\nconnections = [0 ~ lorenz1.x + lorenz2.y + \u03b1 * \u03b3]\n@named connected = ODESystem(connections, t, [\u03b1], [\u03b3], systems = [lorenz1, lorenz2])\n\nu0 = [lorenz1.x => 1.0,\n    lorenz1.y => 0.0,\n    lorenz1.z => 0.0,\n    lorenz2.x => 0.0,\n    lorenz2.y => 1.0,\n    lorenz2.z => 0.0,\n    \u03b1 => 2.0]\n\np = [lorenz1.\u03c3 => 10.0,\n    lorenz1.\u03c1 => 28.0,\n    lorenz1.\u03b2 => 8 / 3,\n    lorenz2.\u03c3 => 10.0,\n    lorenz2.\u03c1 => 28.0,\n    lorenz2.\u03b2 => 8 / 3,\n    \u03b3 => 2.0]\n\ntspan = (0.0, 100.0)\nprob = ODEProblem(connected, u0, tspan, p)\nsol = solve(prob, Rodas5())\n@test maximum(sol[2, :] + sol[6, :] + 2sol[1, :]) < 1e-12\n#using Plots; plot(sol,vars=(:\u03b1,Symbol(lorenz1.x),Symbol(lorenz2.y)))\n", "meta": {"hexsha": "543f5bdab350eb4f336ea39cb8863775f2cb9fda", "size": 1894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/lowering_solving.jl", "max_stars_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146, "max_stars_repo_stars_event_min_datetime": "2018-03-18T19:25:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-21T16:11:30.000Z", "max_issues_repo_path": "test/lowering_solving.jl", "max_issues_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 198, "max_issues_repo_issues_event_min_datetime": "2018-03-18T17:03:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T08:15:41.000Z", "max_forks_repo_path": "test/lowering_solving.jl", "max_forks_repo_name": "ArnoStrouwen/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "57564bf8bbf966c062ba45a60a17c2ccde921c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-03-26T14:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T18:41:19.000Z", "avg_line_length": 24.5974025974, "max_line_length": 84, "alphanum_fraction": 0.5469904963, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7501950875061932}}
{"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\u20261), L (0\u20261: 0 am Schwarzpunkt, 1 am Wei\u00dfpunkt) \tBerechnung\n# Umrechnung von Luminanz L in die nichtlineare Y \tY = 1,055 \u00b7 L ^ (1/2,4) - 0,055 , falls L > 0,0031306684425, sonst Y = 12,92 \u00b7 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\u00b2 Gesamthelligkeit aller Prim\u00e4rvalenzen\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 \u2013 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 \u2013 Decomposition\n#   Maximum decomposition:\n#   Gray = Max(Red, Green, Blue)\n#\n#   Minimum decomposition:\n#   Gray = Min(Red, Green, Blue)\n#\n# Method 5 \u2013 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 \u2013 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\u2019*A)*(A\u2019*b)\n\t- xhat = pinv(A)*b\n\t- Q,R = qr(A); xhat = inv(R)*(Q\u2019*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(\u03bb_1|Ax = b|^2+\u03bb_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) || \u2207selu!(y.data, y.grad, x.data, x.grad)\nend\n\nfunction \u2207selu!(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 ``\u211d^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 \u2264 i \u2264 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\u1d63,n\u2093,n\u2083 = u\r\n    k\u2081,k\u208b\u2081,k\u2082,k\u208b\u2082 = cons\r\n    m\u1d63,m\u2097,m\u2093,A = dens\r\n    z = L(u,p)\r\n    # model\r\n    du[1] = dn\u1d63 = A*k\u2081*m\u1d63*m\u2097 - k\u208b\u2081*n\u1d63 - z[1] + z[2]\r\n    du[2] = dn\u2093 = A*k\u2082*m\u2093*m\u2097 - k\u208b\u2082*n\u2093 - z[3] + z[4]\r\n    du[3] = dn\u2083 = 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\u1d63,n\u2093,n\u2083 = u\r\n    k\u2081,k\u208b\u2081,k\u2082,k\u208b\u2082 = cons\r\n    m\u1d63,m\u2097,m\u2093,A = dens\r\n    z = L(u,p)\r\n    # model\r\n    du[1] = dn\u1d63 = A*k\u2081*m\u1d63*m\u2097 - k\u208b\u2081*n\u1d63 + z[1] - z[2]\r\n    du[2] = dn\u2093 = A*k\u2082*m\u2093*m\u2097 - k\u208b\u2082*n\u2093 + z[3] - z[4]\r\n    du[3] = dn\u2083 = 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\u2099 = n_tc1 #load data\r\nX\u2099 = [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(\u03b8)\r\n\r\n    tmp_prob = remake(prob_nn,u0=u0,p=\u03b8)\r\n    tmp_sol =  solve(tmp_prob, VCABM(), saveat = t,\r\n                  abstol=1e-5, reltol=1e-5)\r\n                  # backsolve=true)\r\n    \u03a3_sol = sum(Array(tmp_sol),dims=1) # Note: this returns a row vector!\r\nend\r\n\r\nfunction loss(\u03b8)\r\n    pred = predict(\u03b8)\r\n    # sum(abs2, (X\u2099 .- pred') .* t), pred\r\n    sum(abs2, (X\u2099 .- pred')), pred\r\nend\r\n\r\n# Test\r\n@time loss(p)\r\n\r\nlosses = []\r\n\r\ncallback(\u03b8,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\u2099)\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\u2099)\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 (\"-\u03c0\" -pi, \"-\u03c0/2\" -pi/2, 0, \"\u03c0/2\" pi/2, \"\u03c0\" 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": "# # [How to port rules generated by SparseADRules to Zygote](@id power_method)\n#\n# In this demo we'll show how to insert SparseADRules's sparse gradient implementation to boost Zygote's gradient.\nusing Zygote\nusing SparseArrays, LinearAlgebra\nusing BenchmarkTools\n\n# find max eigenvalue by power method\nfunction power_max_eigen(A, x, target; niter=100)\n    for i=1:niter\n        x = A * x\n        x /= norm(x)\n    end\n    return abs(x' * target)\nend\n\n# find min eigenvalue by shift power method\nfunction power_min_eigen(A, x, target, \u03bb; niter=100)\n    A = \u03bb*I - A \n    for i=1:niter\n        x = A * x\n        x /= norm(x)\n    end\n    return abs(x' * target)\nend\n\n# generate test data\nA = sprand(5000, 5000, 0.1)\nx = randn(5000)\ntarget = randn(5000)\n\u03bb = 2\n\n# Zygote is able to generate correct gradient for sparse matrix and dense vectors\n# in computation form of dense arrays  \n@btime max_ga_z, max_gx_z, max_gt_z = Zygote.gradient(power_max_eigen, $A, $x, $target) #12.954 s (4272 allocations: 27.91 GiB)\n@btime min_ga_z, min_gx_z, min_gt_z = Zygote.gradient(power_min_eigen, $A, $x, $target, \u03bb) # 12.343 s (4349 allocations: 28.00 GiB)\nmax_ga_z, max_gx_z, max_gt_z = Zygote.gradient(power_max_eigen, A, x, target)\nmin_ga_z, min_gx_z, min_gt_z = Zygote.gradient(power_min_eigen, A, x, target, \u03bb)\n\nusing SparseADRules\n# The gradient generated by SparseADRules is much faster\n# since it keeps the orginal type in computation process \n@btime max_ga, max_gx, max_gt = Zygote.gradient(power_max_eigen, $A, $x, $target) # 6.180 s (5072 allocations: 16.75 GiB)\n@btime min_ga, min_gx, min_gt = Zygote.gradient(power_min_eigen, $A, $x, $target, \u03bb) #  7.289 s (5149 allocations: 16.86 GiB)\nmax_ga, max_gx, max_gt = Zygote.gradient(power_max_eigen, A, x, target)\nmin_ga, min_gx, min_gt = Zygote.gradient(power_min_eigen, A, x, target, \u03bb)\n\nusing Test\n\n# check the results generated by Zygote and SparseADRules are consistent\n@testset begin\n    @testset \"power method for max eigenvalue\" begin\n        @test max_ga_z \u2248 max_ga\n        @test max_gx_z \u2248 max_gx\n        @test max_gt_z \u2248 max_gt\n    end\n    @testset \"power method for min eigenvalue\" begin\n        @test min_ga_z \u2248 min_ga\n        @test min_gx_z \u2248 min_gx\n        @test min_gt_z \u2248 min_gt\n    end\nend", "meta": {"hexsha": "9987a8a7241d958a881609e3ff45f372d4fe8dc1", "size": 2246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/power_method.jl", "max_stars_repo_name": "jieli-matrix/SparseADRules.jl", "max_stars_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-10-01T14:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T11:56:47.000Z", "max_issues_repo_path": "examples/power_method.jl", "max_issues_repo_name": "jieli-matrix/SparseADRules.jl", "max_issues_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-03T07:23:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T07:23:55.000Z", "max_forks_repo_path": "examples/power_method.jl", "max_forks_repo_name": "jieli-matrix/SparseArraysAD.jl", "max_forks_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T00:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:59:17.000Z", "avg_line_length": 36.2258064516, "max_line_length": 131, "alphanum_fraction": 0.7061442565, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.7501802182689664}}
{"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) \u00f7\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 Folly\n\nfunction matmul!(A, B, C)\n    for i in 1:size(A, 1)\n        for j in 1:size(A, 2)\n            A[i, j] = zero(eltype(A))\n            for k in 1:size(B, 2)\n                A[i, j] += B[i, k] * C[k, j]\n            end \n        end \n    end \nend\n\nloopnest = Loop(\n    :i, [\n        Loop(\n            :j, [\n                :(A[i, j] = zero(eltype(A))),\n                Loop(:k, [\n                    :(A[i, j] += B[i, k] * C[k, j])\n                ])])\n        ]\n    )\nindvars = [\n    IndVar(:i, Outer(), :(i += 1), 1, :(size(A, 1))),\n    IndVar(:j, Outer(), :(j += 1), 1, :(size(A, 2))),\n    IndVar(:k, Inner(), :(k += 1), 1, :(size(B, 2))),\n]\n\nmatmul2! = Folly.compile(Native(), loopnest, indvars, [:A, :B, :C])\nmatmul_ka! = Folly.compile(KATarget(CPU()), loopnest, indvars, [:A, :B, :C])\n\nusing Test\n\nB = rand(64, 32)\nC = rand(32, 64)\nA = zeros(64, 64)\n\nmatmul!(A, B, C) \n@test A \u2248 B*C\n\nA = zeros(64, 64)\nmatmul2!(A, B, C) \n@test A \u2248 B*C\n\nA = zeros(64, 64)\nevent = matmul_ka!(A, B, C)\nwait(event)\n@test A \u2248 B*C\n", "meta": {"hexsha": "3917b44f46b1aade9ad848b5c2822e8515d16a71", "size": 1022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/matmul.jl", "max_stars_repo_name": "vchuravy/Folly.jl", "max_stars_repo_head_hexsha": "d74f8542bb20b2c152fd5dfa1de142e3afee89b8", "max_stars_repo_licenses": ["MIT"], "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/matmul.jl", "max_issues_repo_name": "vchuravy/Folly.jl", "max_issues_repo_head_hexsha": "d74f8542bb20b2c152fd5dfa1de142e3afee89b8", "max_issues_repo_licenses": ["MIT"], "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/matmul.jl", "max_forks_repo_name": "vchuravy/Folly.jl", "max_forks_repo_head_hexsha": "d74f8542bb20b2c152fd5dfa1de142e3afee89b8", "max_forks_repo_licenses": ["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.44, "max_line_length": 76, "alphanum_fraction": 0.4236790607, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7501422548838435}}
{"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) \u2248 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 \u03c6-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 = [\u03d50(H)e \u03d51(H)e ... \u03d5k(H)e]\n  lmul!(beta, mul!(w, @view(V[:, 1:m]), C2)) # f(A) \u2248 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] \u2248 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 \u03c6-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] \u2248 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 \u03c6-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)/\u212f)^(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 \u03d5p(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 \u03d5p(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": "import Distributions.pdf, Distributions.logpdf, Random.rand, Base.length\n\nstruct MixedSupport <: ValueSupport; end\n\n\"\"\"\n    Factored{N} <: Distribution{Multivariate, MixedSupport}\n\na `Distribution` type that can be used to combine multiple `UnivariateDistribution`'s and sample from them.\n\nExample: it can be used as `prior = Factored(Normal(0,1), Uniform(-1,1))`\n\"\"\"\nstruct Factored{N}<:Distribution{Multivariate,MixedSupport}\n    p::NTuple{N,UnivariateDistribution}\n    Factored(args::UnivariateDistribution...) = new{length(args)}(args)\nend\n\"\"\"\n    pdf(d::Factored, x) = begin\n\nFunction to evaluate the pdf of a `Factored` distribution object\n\"\"\"\nfunction pdf(d::Factored{N},x) where N\n    s=pdf(d.p[1],x[1])\n    for i in 2:N\n        s*=pdf(d.p[i],x[i])\n    end\n    s\nend\n\n\"\"\"\n    logpdf(d::Factored, x) = begin\n\nFunction to evaluate the logpdf of a `Factored` distribution object\n\"\"\"\nfunction logpdf(d::Factored{N},x) where N\n    s=logpdf(d.p[1],x[1])\n    for i in 2:N\n        s+=logpdf(d.p[i],x[i])\n    end\n    s\nend\n\n\"\"\"\n    rand(rng::AbstractRNG, factoreddist::Factored)\n\nfunction to sample one element from a `Factored` object\n\"\"\"\nrand(rng::AbstractRNG,factoreddist::Factored{N}) where N = ntuple(i->rand(rng,factoreddist.p[i]),Val(N))\n\n\"\"\"\n    length(p::Factored) = begin\n\nreturns the number of distributions contained in `p`.\n\"\"\"\nlength(p::Factored{N}) where N = N\n\nexport Factored\n", "meta": {"hexsha": "68a5b245e28ac014726ff00603999873418c9db2", "size": 1392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/priors.jl", "max_stars_repo_name": "JuliaApproxInference/ApproxInferenceBase.jl", "max_stars_repo_head_hexsha": "d1df1c176a7bb27994d4eee43022adbc0df5c69f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/priors.jl", "max_issues_repo_name": "JuliaApproxInference/ApproxInferenceBase.jl", "max_issues_repo_head_hexsha": "d1df1c176a7bb27994d4eee43022adbc0df5c69f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-18T11:33:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T14:25:32.000Z", "max_forks_repo_path": "src/priors.jl", "max_forks_repo_name": "JuliaApproxInference/ApproxInferenceBase.jl", "max_forks_repo_head_hexsha": "d1df1c176a7bb27994d4eee43022adbc0df5c69f", "max_forks_repo_licenses": ["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.4210526316, "max_line_length": 107, "alphanum_fraction": 0.6824712644, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7501422519049499}}
{"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\u0394x = 1.0           # Discretized space interval\n\u0394t = 1.0           # Discretized time interval\n\u03b1  = 0.25          # Thermal diffusivity\n\u03c9  = inv(nD*\u0394t*\u03b1/\u0394x^2 + 0.5)  # Relaxation coefficient\nTotalTime = 400.   # Total simulation time\nnT = Int(TotalTime/\u0394t)        # 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   \u03c1  = 1.0        # Density\n   C  = 1.0        # Heat capacity\n   source = qg/(\u03c1*C) # Source term. Note that \u03b1=k/(\u03c1C)\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-\u03c9).*f[iw,:,:] .+ \u03c9.*feq[iw,:,:]\n   end\n   if UseSource\n      for iw = 1:nw\n         f[iw,:,:] .+= \u0394t*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*\u0394x/k_thermal\n      #f[2,nx,:] = f[2,nx-1,:] .- heatflux*\u0394x/k_thermal\n   end\n\n   # Calculate macroscopic T\n   T .= sum(f, dims=1)\n\n   t += \u0394t\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": "export fractional_matching\n\n\"\"\"\n`fractional_matching(G)` returns a maximum fractional matching in the form of \na dictionary mapping edges of `G` to rational values. These values are \nin the set `{0, 1/2, 1}`.\n\"\"\"\nfunction fractional_matching(G::SimpleGraph{T}) where {T}\n\n    if cache_check(G, :fractional_matching)\n        return cache_recall(G, :fractional_matching)\n    end\n\n    m = Model(get_solver())\n    @variable(m, w[G.E], Int)\n\n    for e in G.E\n        @constraint(m, 0 <= w[e] <= 2)\n    end\n\n    for v in G.V\n        star = [e for e in G.E if e[1] == v || e[2] == v]\n        @constraint(m, sum(w[e] for e in star) <= 2)\n    end\n\n    @objective(m, Max, sum(w[e] for e in G.E))\n    optimize!(m)\n    wts = Int.(value.(w))\n\n    d = Dict{Tuple{T,T},Rational{Int}}()\n    for e in G.E\n        d[e] = wts[e] // 2\n    end\n\n    cache_save(G, :fractional_matching, d)\n    return d\nend\n", "meta": {"hexsha": "1f6eb31eba10e5d361a44178599cc039f93958d6", "size": 884, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fmatch.jl", "max_stars_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_stars_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-10-12T17:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T08:06:06.000Z", "max_issues_repo_path": "src/fmatch.jl", "max_issues_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_issues_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-10-19T04:03:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T12:08:27.000Z", "max_forks_repo_path": "src/fmatch.jl", "max_forks_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_forks_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T20:58:22.000Z", "avg_line_length": 23.2631578947, "max_line_length": 78, "alphanum_fraction": 0.5904977376, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7501212019484415}}
{"text": "function rosenbrock_init!(x0::Array{T,1}) where {T<:Real}\n  x0[1:2:end] .= -1.2\n  x0[2:2:end] .=  1.0\n  return nothing\nend\n\nfunction rosenbrock_fg!(x::Array{T,1}, gx::Array{T,1}) where {T<:Real}\n  local c1::T = 1\n  local c2::T = 2\n  local c10::T = 10\n  local c200::T = 200\n  x1 = x[1:2:end]\n  x2 = x[2:2:end]\n  t1 = c1 .- x1\n  t2 = c10*(x2 - x1.*x1)\n  g2 = c200*(x2 - x1.*x1)\n  gx[1:2:end] = -c2*(x1 .* g2 + t1)\n  gx[2:2:end] = g2\n  return sum(t1.*t1) + sum(t2.*t2)\nend\n\nfunction rosenbrock_test(n::Integer=20, m::Integer=3; single::Bool=false)\n  T = (single ? Float32 : Float64)\n  x0 = Array{T}(undef, n)\n  rosenbrock_init!(x0)\n  lbfgs(rosenbrock_fg!, x0, m, verb=VERBOSE)\nend\n\nfunction run_tests(::Type{T}, n::Integer=20) where {T}\n    prec = (T <: Float64 ? \"double\" : \"single\")\n    x0 = Array{T}(undef, n)\n    xsol = ones(T,n)\n    atol = 1e-3\n    rosenbrock_init!(x0)\n\n    @printf(\"\\nTesting NLCG in %s precision\\n\", prec)\n    x1 = nlcg(rosenbrock_fg!, x0, verb=VERBOSE)\n    err = maximum(abs.(x1 .- xsol))\n    @printf(\"Maximum absolute error: %.3e\\n\", err)\n    @test err < atol\n\n    @printf(\"\\nTesting VMLMB in %s precision with Oren & Spedicato scaling\\n\", prec)\n    x2 = vmlmb(rosenbrock_fg!, x0, verb=VERBOSE)\n    #scaling=OptimPack.SCALING_OREN_SPEDICATO)\n    err = maximum(abs.(x2 .- xsol))\n    @printf(\"Maximum absolute error: %.3e\\n\", err)\n    @test err < atol\n\n    @printf(\"\\nTesting VMLMB in %s precision with Oren & Spedicato scaling\\n\", prec)\n    x3 = vmlmb(rosenbrock_fg!, x0, verb=VERBOSE, mem=15)\n    #scaling=OptimPack.SCALING_OREN_SPEDICATO)\n    err = maximum(abs.(x3 .- xsol))\n    @printf(\"Maximum absolute error: %.3e\\n\", err)\n    @test err < atol\n\n    @printf(\"\\nTesting VMLMB in %s precision with nonnegativity\\n\", prec)\n    x4 = vmlmb(rosenbrock_fg!, x0, verb=VERBOSE, lower=0)\n    err = maximum(abs.(x4 .- xsol))\n    @printf(\"Maximum absolute error: %.3e\\n\", err)\n    @test err < atol\n\n    #@printf(\"\\nTesting VMLM in %s precision with Barzilai & Borwein scaling\\n\", prec)\n    #x5 = vmlmb(rosenbrock_fg!, x0, verb=VERBOSE,\n    #           scaling=OptimPack.SCALING_BARZILAI_BORWEIN)\n    #err = maximum(abs.(x5 .- xsol))\n    #@printf(\"Maximum absolute error: %.3e\\n\", err)\n    #@test err < atol\nend\n\n# Run tests in double and single precisions.\nrun_tests(Float32)\nrun_tests(Float64)\n", "meta": {"hexsha": "45941fca22186ba721acc0a3620f114cdb7579b6", "size": 2309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/rosenbrock.jl", "max_stars_repo_name": "emmt/OptimPack.jl", "max_stars_repo_head_hexsha": "b72734861c397f1d5f80ade42dd0ba150e10f03c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-03T21:19:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-29T22:15:58.000Z", "max_issues_repo_path": "test/rosenbrock.jl", "max_issues_repo_name": "stjordanis/OptimPack.jl", "max_issues_repo_head_hexsha": "041dcb9d683c68940264b0806c8e8dd7987ec377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2016-07-04T14:16:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T16:02:53.000Z", "max_forks_repo_path": "test/rosenbrock.jl", "max_forks_repo_name": "stjordanis/OptimPack.jl", "max_forks_repo_head_hexsha": "041dcb9d683c68940264b0806c8e8dd7987ec377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-29T14:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:09:43.000Z", "avg_line_length": 31.6301369863, "max_line_length": 86, "alphanum_fraction": 0.6288436553, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7501212016161766}}
{"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||\u2082  st  0 \u2264 x \u2264 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) \u2208  Rn\u208a x (Qn\u208a)\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": "\nusing GridArrays , LinearAlgebra, Test\n\n@testset \"gauss\" begin\n    x1,w1 = GridArrays.gausschebyshev(10)\n    x2,w2 = GridArrays.gausschebyshev(BigFloat,10)\n    @test norm(x1-x2)+norm(w1-w2) < 1e-12\n\n    x1,w1 = GridArrays.gausschebyshevu(10)\n    x2,w2 = GridArrays.gausschebyshevu(BigFloat,10)\n    @test norm(x1-x2)+norm(w1-w2) < 1e-12\n\n    x1,w1 = GridArrays.gausslegendre(10)\n    x2,w2 = GridArrays.gausslegendre(BigFloat,10)\n    @test norm(x1-x2)+norm(w1-w2) < 1e-12\n\n    a = rand()\n    x1,w1 = GridArrays.gausslaguerre(10, a)\n    x2,w2 = GridArrays.gausslaguerre(10, big(a))\n    @test norm(x1-x2)+norm(w1-w2) < 1e-12\n\n    x1,w1 = GridArrays.gausshermite(10)\n    x2,w2 = GridArrays.gausshermite(10)\n    @test norm(x1-x2)+norm(w1-w2) < 1e-12\n\n    a= rand();b=rand()\n    x1,w1 = GridArrays.gaussjacobi(10,a,b)\n    x2,w2 = GridArrays.gaussjacobi(10,big(a),big(b))\n    @test norm(x1-x2)+norm(w1-w2) < 1e-12\n\n    a= -.5\n    x1,w1 = GridArrays.gaussjacobi(10,a,a)\n    x2,w2 = GridArrays.gaussjacobi(10,big(a),big(a))\n    x,w = GridArrays.gausschebyshev(10)\n    @test w\u2248w1\n    @test x\u2248x1\n    x,w = GridArrays.gausschebyshev(BigFloat,10)\n    @test x\u2248x2\n    @test w\u2248w2\n\n    a= .5\n    x1,w1 = GridArrays.gaussjacobi(10,a,a)\n    x2,w2 = GridArrays.gaussjacobi(10,big(a),big(a))\n    x,w = GridArrays.gausschebyshevu(10)\n    @test w\u2248w1\n    @test x\u2248x1\n    x,w = GridArrays.gausschebyshevu(BigFloat,10)\n    @test x\u2248x2\n    @test w\u2248w2\nend\n", "meta": {"hexsha": "94d0b35c328b132f8a2448da2c0ee1b37e59e50c", "size": 1426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_gauss.jl", "max_stars_repo_name": "UnofficialJuliaMirror/GridArrays.jl-356ae075-8bc9-5ef9-a342-46c9ba26438c", "max_stars_repo_head_hexsha": "956022d9403afd65912f8d3d51d3e6ed090ddf62", "max_stars_repo_licenses": ["MIT"], "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_gauss.jl", "max_issues_repo_name": "UnofficialJuliaMirror/GridArrays.jl-356ae075-8bc9-5ef9-a342-46c9ba26438c", "max_issues_repo_head_hexsha": "956022d9403afd65912f8d3d51d3e6ed090ddf62", "max_issues_repo_licenses": ["MIT"], "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_gauss.jl", "max_forks_repo_name": "UnofficialJuliaMirror/GridArrays.jl-356ae075-8bc9-5ef9-a342-46c9ba26438c", "max_forks_repo_head_hexsha": "956022d9403afd65912f8d3d51d3e6ed090ddf62", "max_forks_repo_licenses": ["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.9607843137, "max_line_length": 52, "alphanum_fraction": 0.6423562412, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7501211956874091}}
{"text": "using Manopt, Manifolds, Plots\n#\n# Settings\nresultsFolder = \"examples/Total_Variation/S1_TV/\"\nexperimentName = \"S1_TV12\"\nplotAndExportResult = true\n\nn = 500\n\u03c3 = 0.2\n\u03b1 = 0.5\n\u03b2 = 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), \u03c3))\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        [-\u03c0, -\u03c0/2, 0, \u03c0/2, \u03c0],\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, \u03b1, \u03b2, x)\nproxes = [\n    (\u03bb, x) -> prox_distance(N, \u03bb, data, x,2),\n    (\u03bb, x) -> prox_TV(N, \u03b1 * \u03bb, x),\n    (\u03bb, x) -> prox_TV2(N, \u03b2 * \u03bb, x),\n]\n\no = cyclic_proximal_point(\n    N,\n    F,\n    proxes,\n    data;\n    \u03bb = i -> \u03c0 / (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        [-\u03c0, -\u03c0/2, 0, \u03c0/2, \u03c0],\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\u039b, V = eigen(M)\n\u039b, W = eigen(M')\n\n# Right eigenvectors\nV\u00b3 = round.(V[:, 1] ./ V[1, 1])\nV\u00b2 = round.(V[:, 2] ./ V[1, 2])\nV\u00b9 = round.(V[:, 3] ./ V[1, 3])\n\n# Left eigenvectors\nW\u00b3 = round.(W[:, 1] ./ W[1, 1])\nW\u00b2 = round.(W[:, 2] ./ W[1, 2])\nW\u00b9 = round.(W[:, 3] ./ W[1, 3])\n\nW[:, 1] .= W\u00b9\nW[:, 2] .= -W\u00b2\nW[:, 3] .= W\u00b3\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\u03c0)\n\n\u03b3 = 1.0 # 1/ \u03b3 is the eddy timescale\nU = 1.0\n\u03ba = 1.0\n\nfluxkernel =\n    -U * inv(\u03ba .* D^2 - \u03b3 * I - U * D * inv(\u03ba .* D^2 - 2 * \u03b3 * I) * U * D) * U\n\u03bb = eigvals(fluxkernel)\n\u03c3 = 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\"] = \u03bb\nfile[\"singularvalues\"] = \u03c3\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": "@testset \"Knapsack\" begin\n\n@testset \"Knapsack: ZeroOnePack!\" begin\n    dp=zeros(Int,30)\n    @test ZeroOnePack!(20,[1,3,11],[2,5,30],dp) == 37\n    dp=zeros(Int,30)\n    @test ZeroOnePack!(10,[1,3,11],[20,5,80],dp) == 25\nend\n\n@testset \"Knapsack: CompletePack!\" begin\n    dp=zeros(Int,30)\n    @test CompletePack!(20,[1,2,9],[1,3,20],dp) == 43\n    dp=zeros(Int,30)\n    @test CompletePack!(10,[1,3,11],[20,5,80],dp) == 200\nend\n\nend\n", "meta": {"hexsha": "e4c0b3b40bbe1c31a38bec98469989e547fee15f", "size": 426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/knapsack.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": "test/knapsack.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": "test/knapsack.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": 23.6666666667, "max_line_length": 56, "alphanum_fraction": 0.6103286385, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7501206228418338}}
{"text": "\n\nfunction create_MPC(N)\n    nx = 6\n    nu = 3\n    # N= 20\n    xg = [-1;-2;-3;0;0;0]\n    nz=(N*nx) + (N-1)*nu\n    Ac = Array([zeros(3,3) I(3);zeros(3,6)])\n    Bc = Array([zeros(3,3);I(3)])\n\n    dt = 0.2\n    H = exp(dt*[Ac Bc; zeros(3,9)])\n    Ad = sparse(H[1:nx,1:nx])\n    Bd = sparse(H[1:nx,nx+1:end])\n\n    xi = [(nu+nx)*(i-1) .+ (1:nx)  for i = 1:N]\n\n    ui = [(nu+nx)*(i-1) .+ (nx .+ (1:nu))  for i = 1:N-1]\n    ci = [(nx)*(i-1) .+ (1:nx)  for i = 1:N]\n\n    # cost function\n    Qc = 10*I(nx)\n    Rc = I(nu)\n    Q = spzeros(nz,nz)\n    q = zeros(nz)\n    for i = 1:N\n        if i<N\n            Q[xi[i],xi[i]] = Qc\n            q[xi[i]] = -Qc*xg\n            Q[ui[i],ui[i]] = Rc\n        else\n            Q[xi[i],xi[i]] = Qc\n            q[xi[i]] = -Qc*xg\n        end\n    end\n\n\n    A = spzeros(N*nx,nz)\n    for i = 1:N-1\n        # xkp1 - axk - buk\n        A[ci[i],xi[i+1]] = I(nx)\n        A[ci[i],xi[i]] = -Ad\n        A[ci[i],ui[i]] = -Bd\n    end\n    A[ci[end],xi[1]] = I(nx)\n    b = zeros((N*nx))\n    b[ci[end]] = [1;4;-8;.1;.2;-.3]\n\n    G_up = spzeros(nz,nz)\n    gi = [(nu)*(i-1) .+ (1:nu)  for i = 1:N-1]\n    for i = 1:N-1\n        G_up[gi[i],ui[i]] = I(nu)\n    end\n    G = [G_up;-G_up]\n    h = 2*ones(2*nz)\n\n\n\n    return Q,q,A,b,G,h\nend\n\n\n# here is a feasible QP\nfor N = 5:5:150\n    local z, iters = CPEG.quadprog(create_MPC(N)...)\n    @test typeof(z) == Vector{Float64}\n    @test iters >= 1\n    @test iters <= ev.qp_solver_opts.max_iters\nend\n\n# for N = 10:10:100\n#     Q,q,A,b,G,h = create_MPC(N)\n#     nx = 6\n#     nu = 3\n#     nz=(N*nx) + (N-1)*nu\n#     h = [2*ones(nz);-3*ones(nz)]  # set this to zero and make it impossible to solve\n#     @test_throws ErrorException CPEG.quadprog(Q,q,A,b,G,h)\n# end\n", "meta": {"hexsha": "1a3cbf021ab808c3bf1b028411f0e8a12b7c6eaf", "size": 1703, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/qptest.jl", "max_stars_repo_name": "kevin-tracy/CPEG.jl", "max_stars_repo_head_hexsha": "b24b14823c34aab533960aa39db6534b1de6587c", "max_stars_repo_licenses": ["MIT"], "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/qptest.jl", "max_issues_repo_name": "kevin-tracy/CPEG.jl", "max_issues_repo_head_hexsha": "b24b14823c34aab533960aa39db6534b1de6587c", "max_issues_repo_licenses": ["MIT"], "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/qptest.jl", "max_forks_repo_name": "kevin-tracy/CPEG.jl", "max_forks_repo_head_hexsha": "b24b14823c34aab533960aa39db6534b1de6587c", "max_forks_repo_licenses": ["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.2875, "max_line_length": 86, "alphanum_fraction": 0.4421608925, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.750120619649616}}
{"text": "include(\"naive_bayes.jl\")\ninclude(\"bernoulli_nb.jl\")\n\nd = GaussianNaiveBayes([0.0 10.0;\n\t                    0.0 2.0],\n\t                   [1.0 1.0;\n\t                    1.0 1.0],\n\t                   [0.25, 0.75])\n\nX, c = rand(d, 10_000)\n\nd = fit(GaussianNaiveBayes, X, c)\n\npredict(d, X)\n\nloglikelihood(d, X, c)\n\nlogpdf(d, X[:, 1], c[1])\nlogpdf(d, X, c)\n\nmean(d)\n\nfit(GaussianNaiveBayes, rand(d, 1_000)...)\n\ncor(X[:, c .== 1]')\ncor(X[:, c .== 2]')\n\n#\n\nd = BernoulliNaiveBayes([0.1 0.9;\n\t                     0.9 0.1],\n\t                    [0.25, 0.75])\n\nX, c = rand(d, 10_000)\n\nd = fit(BernoulliNaiveBayes, X, c)\n\npredict(d, X)\n\nloglikelihood(d, X, c)\n\nlogpdf(d, X[:, 1], c[1])\nlogpdf(d, X, c)\n\nmean(d)\n\nfit(BernoulliNaiveBayes, rand(d, 1_000)...)\n\ncor(X[:, c .== 1]')\ncor(X[:, c .== 2]')\n", "meta": {"hexsha": "7da720e94bff8c89847f55d8662f4475ec6afad0", "size": 789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/demo.jl", "max_stars_repo_name": "alexmorley/NaiveBayes.jl", "max_stars_repo_head_hexsha": "f294df8c7367d1bdf3ad20861b9aaacf317fb5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/demo.jl", "max_issues_repo_name": "alexmorley/NaiveBayes.jl", "max_issues_repo_head_hexsha": "f294df8c7367d1bdf3ad20861b9aaacf317fb5c2", "max_issues_repo_licenses": ["MIT"], "max_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.jl", "max_forks_repo_name": "alexmorley/NaiveBayes.jl", "max_forks_repo_head_hexsha": "f294df8c7367d1bdf3ad20861b9aaacf317fb5c2", "max_forks_repo_licenses": ["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.4705882353, "max_line_length": 43, "alphanum_fraction": 0.4803548796, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7501206149137614}}
{"text": "using Plots\nusing Zygote\nusing LaTeXStrings\n\n\nvecindario(;x\u2080, \u03f5=2.0, \u0394=0.05) = x\u2080 - \u03f5:\u0394:x\u2080 + \u03f5\n\nf(x) = sin(5x) - cos(3x)\n\nx\u2080 = 10\nx = vecindario(x\u2080=x\u2080);\n\nf\u2081 = f'(x\u2080)\nf\u2082 = f''(x\u2080)\n\ny = f.(x);\ny = hcat(y, ones(length(y)) .* f(x\u2080))\ny = hcat(y, @. y[:, end] + (x - x\u2080) * f\u2081)\ny = hcat(y, @. y[:, end] + (x - x\u2080)^2 * f\u2082)\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\u2080], [f(x\u2080)], mark=:cirle, label=L\"x_0\")\ntitle!(\"Aproximaci\u00f3n 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 \u2208 \u211c^(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 \u2208 \u211c^(size of xy_to \u00d7 size of xy_from \u00d7 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": "@testset \"Boykov Kolmogorov\" begin\n  @testset \"Lattice graph\" begin\n    # image size\n    sz = (9, 9)\n\n    # number of pixels\n    npix = prod(sz)\n\n    # lattice graph\n    G = DiGraph(npix+2)\n    C = spzeros(npix+2, npix+2)\n\n    # connect all pixels in the 9x9 image\n    # with its immediate 4 neighbors\n    for i in 1:sz[1]-1, j in 1:sz[2]\n      u = LinearIndices(sz)[i,j]\n      v = LinearIndices(sz)[i+1,j]\n      add_edge!(G, u, v)\n      add_edge!(G, v, u)\n    end\n    for i in 1:sz[1], j in 1:sz[2]-1\n      u = LinearIndices(sz)[i,j]\n      v = LinearIndices(sz)[i,j+1]\n      add_edge!(G, u, v)\n      add_edge!(G, v, u)\n    end\n\n    # create capacity for flow in the 4x4\n    # subimage located at the top left\n    for i in 1:3, j in 1:4\n      u = LinearIndices(sz)[i,j]\n      v = LinearIndices(sz)[i+1,j]\n      C[u,v] = C[v,u] = 1\n    end\n    for i in 1:4, j in 1:3\n      u = LinearIndices(sz)[i,j]\n      v = LinearIndices(sz)[i,j+1]\n      C[u,v] = C[v,u] = 1\n    end\n\n    # create capacity for flow in the 4x4\n    # subimage located at the bottom right\n    for i in 6:8, j in 6:9\n      u = LinearIndices(sz)[i,j]\n      v = LinearIndices(sz)[i+1,j]\n      C[u,v] = C[v,u] = 1\n    end\n    for i in 6:9, j in 6:8\n      u = LinearIndices(sz)[i,j]\n      v = LinearIndices(sz)[i,j+1]\n      C[u,v] = C[v,u] = 1\n    end\n\n    # create source node and connect it to the\n    # leftmost column of the image\n    # create target node and connect it to the\n    # rightmost column of the image\n    s = npix + 1\n    t = npix + 2\n    for i in 1:sz[1]\n      u = LinearIndices(sz)[i,1]\n      add_edge!(G, s, u)\n      C[s,u] = C[u,s] = Inf\n    end\n    for i in 1:sz[1]\n      u = LinearIndices(sz)[i,sz[2]]\n      add_edge!(G, u, t)\n      C[u,t] = C[t,u] = Inf\n    end\n\n    # now we are ready to start the flow\n    flow, _, labels = maximum_flow(G, s, t, C, algorithm=BoykovKolmogorovAlgorithm())\n\n    # because the two subimages are not connected\n    # we must have zero flow from source to target\n    @test flow == 0\n\n    # the final cut represents the two disconnected\n    # subimages filled with water of different color\n    COLOR = reshape(labels[1:end-2], sz)\n    @test COLOR == [\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  0  0  0  0  0  0  0  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2 \n    ]\n\n    # now let's create a bridge connecting the two\n    # subimages to allow flow from source to target\n    for (I1, I2) in [[(4,4), (5,4)], [(5,4), (5,5)],\n                    [(5,5), (5,6)], [(5,6), (6,6)]]\n      u = LinearIndices(sz)[I1...]\n      v = LinearIndices(sz)[I2...]\n      C[u,v] = C[v,u] = 1\n    end\n\n    flow, _, labels = maximum_flow(G, s, t, C, algorithm=BoykovKolmogorovAlgorithm())\n\n    # because there is only one bridge,\n    # the maximum flow allowed is one unit\n    @test flow == 1\n\n    # the final cut is unchanged compared to the previous one\n    COLOR = reshape(labels[1:end-2], sz)\n    @test COLOR == [\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  0  0  0  0  0  0  0  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2 \n    ]\n\n    # finally let's create a second bridge to increase\n    # the maximum flow from one to two units\n    for (I1, I2) in [[(4,4), (4,5)], [(4,5), (5,5)],\n                    [(5,5), (6,5)], [(6,5), (6,6)]]\n      u = LinearIndices(sz)[I1...]\n      v = LinearIndices(sz)[I2...]\n      C[u,v] = C[v,u] = 1\n    end\n\n    flow, _, labels = maximum_flow(G, s, t, C, algorithm=BoykovKolmogorovAlgorithm())\n\n    # the maximum flow is now doubled\n    @test flow == 2\n\n    # the final cut is slightly different\n    # near the corners of the two subimages\n    COLOR = reshape(labels[1:end-2], sz)\n    @test COLOR == [\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  1  1  1  0  0  0  0  2\n      1  1  1  0  0  0  0  0  2\n      1  0  0  0  0  0  0  0  2\n      1  0  0  0  0  0  2  2  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2\n      1  0  0  0  0  2  2  2  2 \n    ]\n  end\n\n  @testset \"Find path\" begin\n    # construct graph\n    gg = lg.DiGraph(3)\n    lg.add_edge!(gg, 1, 2)\n    lg.add_edge!(gg, 2, 3)\n\n    # source and sink terminals\n    source, target = 1, 3\n\n    for g in testdigraphs(gg)\n      # default capacity\n      capacity_matrix = LightGraphsFlows.DefaultCapacity(g)\n      residual_graph = @inferred(LightGraphsFlows.residual(g))\n      T = eltype(g)\n      flow_matrix = zeros(T, 3, 3)\n      TREE = zeros(T, 3)\n      TREE[source] = T(1)\n      TREE[target] = T(2)\n      PARENT = zeros(T, 3)\n      A = [T(source), T(target)]\n      path = LightGraphsFlows.find_path!(\n        residual_graph, source, target, flow_matrix,\n        capacity_matrix, PARENT, TREE, A)\n\n      @test path == [1, 2, 3]\n    end\n  end\nend\n", "meta": {"hexsha": "1d880c147a8c9546ae4e448140959ec4eb56e89d", "size": 5034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/boykov_kolmogorov.jl", "max_stars_repo_name": "mathieu17g/LightGraphsFlows.jl", "max_stars_repo_head_hexsha": "0ada2085163430fc4cba68444fd28d9d200371b3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2018-01-05T17:35:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T16:38:36.000Z", "max_issues_repo_path": "test/boykov_kolmogorov.jl", "max_issues_repo_name": "mathieu17g/LightGraphsFlows.jl", "max_issues_repo_head_hexsha": "0ada2085163430fc4cba68444fd28d9d200371b3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2018-01-04T19:26:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T08:51:43.000Z", "max_forks_repo_path": "test/boykov_kolmogorov.jl", "max_forks_repo_name": "mathieu17g/LightGraphsFlows.jl", "max_forks_repo_head_hexsha": "0ada2085163430fc4cba68444fd28d9d200371b3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-08-27T02:42:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T16:52:42.000Z", "avg_line_length": 27.9666666667, "max_line_length": 85, "alphanum_fraction": 0.5143027414, "num_tokens": 2172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.7500857242578333}}
{"text": "using Diagonalizations, LinearAlgebra, PosDefManifold, Test\n\n# Method (1) real\nn, t=10, 100\nX=genDataMatrix(n, t)\nY=genDataMatrix(n, t)\nCx=Symmetric((X*X')/t)\nCy=Symmetric((Y*Y')/t)\nCxy=(X*Y')/t\ncC=cca(Cx, Cy, Cxy, simple=true)\n@test cC.F[1]'*Cx*cC.F[1]\u2248I\n@test cC.F[2]'*Cy*cC.F[2]\u2248I\nD=cC.F[1]'*Cxy*cC.F[2]\n@test norm(D-Diagonal(D))+1. \u2248 1.\n\n# Method (1) complex\nXc=genDataMatrix(ComplexF64, n, t)\nYc=genDataMatrix(ComplexF64, n, t)\nCxc=Hermitian((Xc*Xc')/t)\nCyc=Hermitian((Yc*Yc')/t)\nCxyc=(Xc*Yc')/t\ncCc=cca(Cxc, Cyc, Cxyc, simple=true)\n@test cCc.F[1]'*Cxc*cCc.F[1]\u2248I\n@test cCc.F[2]'*Cyc*cCc.F[2]\u2248I\nDc=cCc.F[1]'*Cxyc*cCc.F[2]\n@test norm(Dc-Diagonal(Dc))+1. \u2248 1.\n\n\n# Method (2) real\ncXY=cca(X, Y, simple=true)\n@test cXY.F[1]'*Cx*cXY.F[1]\u2248I\n@test cXY.F[2]'*Cy*cXY.F[2]\u2248I\nD=cXY.F[1]'*Cxy*cXY.F[2]\n@test norm(D-Diagonal(D))+1. \u2248 1.\n@test cXY==cC\n\n# Method (2) complex\ncXYc=cca(Xc, Yc, simple=true)\n@test cXYc.F[1]'*Cxc*cXYc.F[1]\u2248I\n@test cXYc.F[2]'*Cyc*cXYc.F[2]\u2248I\nDc=cXYc.F[1]'*Cxyc*cXYc.F[2]\n@test norm(Dc-Diagonal(Dc))+1. \u2248 1.\n@test cXYc==cCc\n\n\n# Method (3) real\n# canonical correlation analysis of the average covariance and cross-covariance\nk=10\nXset=[genDataMatrix(n, t) for i=1:k]\nYset=[genDataMatrix(n, t) for i=1:k]\n\nc=cca(Xset, Yset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.9\nc=cca(Xset, Yset; eVar=0.9)\n\n# ... subtracting the mean from the matrices in Xset and Yset\nc=cca(Xset, Yset; meanX=nothing, meanY=nothing, eVar=0.9)\n\n# cca on the average of the covariance and cross-covariance matrices\n# computed along dims 1\nc=cca(Xset, Yset; dims=1, eVar=0.9)\n\n# name of the filter\nc.name\n\nusing Plots\n# plot regularized accumulated eigenvalues\nplot(c.arev)\n\n# plot the original covariance and cross-covariance matrices\n# and their transformed counterpart\n CxyMax=maximum(abs.(Cxy));\n h1 = heatmap(Cxy, clim=(-CxyMax, CxyMax), title=\"Cxy\", yflip=true, c=:bluesreds);\n D=cC.F[1]'*Cxy*cC.F[2];\n Dmax=maximum(abs.(D));\n h2 = heatmap(D, clim=(0, Dmax), title=\"F1'CxyF2\", yflip=true, c=:amp);\n CxMax=maximum(abs.(Cx));\n h3 = heatmap(Cx, clim=(-CxMax, CxMax), title=\"Cx\", yflip=true, c=:bluesreds);\n h4 = heatmap(cC.F[1]'*Cx*cC.F[1], clim=(0, 1), title=\"F1'CxF1\", yflip=true, c=:amp);\n CyMax=maximum(abs.(Cy));\n h5 = heatmap(Cy, clim=(-CyMax, CyMax), title=\"Cy\", yflip=true, c=:bluesreds);\n h6 = heatmap(cC.F[2]'*Cy*cC.F[2], clim=(0, 1), title=\"F2'CyF2\", yflip=true, c=:amp);\n \ud83d\udcc8=plot(h3, h5, h1, h4, h6, h2, size=(800,400))\n# savefig(\ud83d\udcc8, homedir()*\"\\\\Documents\\\\Code\\\\julia\\\\Diagonalizations\\\\docs\\\\src\\\\assets\\\\FigCCA.png\")\n\n# Method (3) complex\n# canonical correlation analysis of the average covariance and cross-covariance\nk=10\nXcset=[genDataMatrix(ComplexF64, n, t) for i=1:k]\nYcset=[genDataMatrix(ComplexF64, n, t) for i=1:k]\n\ncc=cca(Xcset, Ycset)\n\n# ... selecting subspace dimension allowing an explained variance = 0.9\ncc=cca(Xcset, Ycset; eVar=0.9)\n\n# ... subtracting the mean from the matrices in Xset and Yset\ncc=cca(Xcset, Ycset; meanX=nothing, meanY=nothing, eVar=0.9)\n\n# cca on the average of the covariance and cross-covariance matrices\n# computed along dims 1\ncc=cca(Xcset, Ycset; dims=1, eVar=0.9)\n\n# name of the filter\ncc.name\n", "meta": {"hexsha": "108ade8471071f2103283defc7ea2049ddec0f94", "size": 3170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/CCA.jl", "max_stars_repo_name": "ericphanson/Diagonalizations.jl", "max_stars_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/CCA.jl", "max_issues_repo_name": "ericphanson/Diagonalizations.jl", "max_issues_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": "examples/CCA.jl", "max_forks_repo_name": "ericphanson/Diagonalizations.jl", "max_forks_repo_head_hexsha": "74d69d96a3df129482ddd3bc566beda06f1996c6", "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": 29.6261682243, "max_line_length": 99, "alphanum_fraction": 0.6804416404, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7500857206543012}}
{"text": "L = 200\nlabels = rand(Bool, L);\nscores = add_noise.(labels, 0.6)\n\nB = BinaryMetrics(labels, scores)\nprintln(B)\n\nBinaryMetrics([0;1], [0.4;0.1])\n@test_throws ErrorException BinaryMetrics([-1;1], [0.4;0.1])\n@test_throws ErrorException BinaryMetrics([0;1;1], [0.4;0.1])\n\nB = BinaryMetrics([0;0;1;1], [0.4;0.7;0.4;1])\n@test tp(B,0.5) == 1\n@test tn(B,0.5) == 1\n@test fp(B,0.5) == 1\n@test fn(B,0.5) == 1\n@test cm(B,0.5) == ones(2,2)\n\nL = 200\nlabels = rand(Bool, L);\nscores = add_noise.(labels, 0.6)\nB = BinaryMetrics(labels, scores)\nOP = [0.2;0.5;0.7]\ntps = tp(B, OP)\ntns = tn(B, OP)\nfps = fp(B, OP)\nfns = fn(B, OP)\n@test cm(B,OP) == (tps, fps, fns, tns)\n\n@test isapprox(tpr(B, OP) , 1 .- fnr(B,OP); atol=1e-8)\n@test isapprox(tpr(B, OP) , tps./(tps.+fns); atol=1e-8)\n@test isapprox(tnr(B, OP) , 1 .- fpr(B,OP); atol=1e-8)\n@test isapprox(tnr(B, OP) , tns./(tns.+fps); atol=1e-8)\n@test isapprox(fnr(B, OP) , 1 .- tpr(B,OP); atol=1e-8)\n@test isapprox(fnr(B, OP) , fns./(fns.+tps); atol=1e-8)\n@test isapprox(fpr(B, OP) , 1 .- tnr(B,OP); atol=1e-8)\n@test isapprox(fpr(B, OP) , fps./(fps.+tns); atol=1e-8)\n@test isapprox(ppv(B, OP) , 1 .- fdr(B, OP); atol=1e-8)\n@test isapprox(npv(B, OP) , 1 .- false_omission_rate(B, OP); atol=1e-8)\n@test csi(B, OP) == tp(B,OP) ./ (tp(B,OP) + fn(B,OP) +fp(B,OP)) \n@test acc(B, OP) == (tp(B,OP)+tn(B,OP)) ./ ( tp(B,OP) + tn(B,OP) \n                                            +fp(B,OP) + fn(B,OP) ) \nF1 = (2 .* tp(B,OP)) ./ (2 .* tp(B,OP) .+ fp(B,OP) .+ fn(B,OP))\n@test isapprox(f1(B,OP), F1 ; atol=1e-8)\nMCC = (tp(B,OP).*tn(B,OP).-fp(B,OP).*fn(B,OP))./ # <- determinant of CM\nsqrt.((tp(B,OP).+fp(B,OP)).*(tp(B,OP).+fn(B,OP)).*(tn(B,OP).+fp(B,OP)).*(tn(B,OP).+fn(B,OP)))\n@test mcc(B,OP) == MCC \n@test eer(B) == (0.17,100)  \n", "meta": {"hexsha": "274bccf2afa6927a5c674ed9d9f7cd17cd75162d", "size": 1745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/binarymetrics.jl", "max_stars_repo_name": "nantonel/ROC.jl", "max_stars_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_stars_repo_licenses": ["MIT"], "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/binarymetrics.jl", "max_issues_repo_name": "nantonel/ROC.jl", "max_issues_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_issues_repo_licenses": ["MIT"], "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/binarymetrics.jl", "max_forks_repo_name": "nantonel/ROC.jl", "max_forks_repo_head_hexsha": "9a1c98fdfe14bfee7c8be17b0d3a651978faa6bc", "max_forks_repo_licenses": ["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.612244898, "max_line_length": 93, "alphanum_fraction": 0.5535816619, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7500857183121273}}
{"text": "## Pendulum\n# https://github.com/HarvardAgileRoboticsLab/unscented-dynamic-programming/blob/master/pendulum_dynamics.m\nfunction pendulum_dynamics!(x\u0307::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\u0307[1] = x[2]\n    x\u0307[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\u0307::AbstractVector{T},x::AbstractVector{T},u::AbstractVector{T}) where T\n    x\u0307[1] = x[2];\n    x\u0307[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\u0307,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\u0307[1] = x[2]\n    x\u0307[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\u0394t = 0.01   # sampling time \ntvec = 0:\u0394t: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, \u03bc = d)\n    tr = trajectory(ds, tattr, y_0; \u0394t, 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# \u2554\u2550\u2561 4fb1c47c-8d70-11eb-3d5c-01c5bb7190fe\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 3562c0e2-8d70-11eb-0f89-9d039fe996b9\nmd\" ## Clip-11-01-05s.jl\"\n\n# \u2554\u2550\u2561 07c85e9e-8d95-11eb-295d-63a99f7aa921\nmd\" ##### Fig 10.7.\"\n\n# \u2554\u2550\u2561 9bfd33fc-8d70-11eb-3a9c-bb9a990cbcf9\nx = collect(-1.0:0.01:1.0);\n\n# \u2554\u2550\u2561 ee25cbe6-8d8c-11eb-3323-c521a67b10f0\nbegin\n\t\u03b1 = 0.0\n\t\u03b2 = 2.0\n\t\n\t# p = exp.(\u03b1 .+ \u03b2 .* x) ./ (1 .+ exp.(\u03b1 .+ \u03b2 .* x))\n\t\n\tp = logistic.(\u03b1 .+ \u03b2 .* x)\nend\n\n# \u2554\u2550\u2561 1cba8970-8d91-11eb-01d8-09d8d076dc73\nbegin\n\todds = p ./ (1 .- p)\n\tlogodds = log.(odds)\nend\n\n# \u2554\u2550\u2561 6b96d95e-8d91-11eb-25ac-75f21ee9c98e\nlogistic.(x)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1404a820-8d95-11eb-27d2-531cea578fda\nmd\" ##### Fig 10.8.\"\n\n# \u2554\u2550\u2561 c859986c-8d93-11eb-1211-db9c435de034\nlogsig = exp.(\u03b1 .+ \u03b2 .* x)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 7e069492-8d70-11eb-2093-8375b07f4099\nmd\" ## End of clip-11-01-05s.jl\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u25503562c0e2-8d70-11eb-0f89-9d039fe996b9\n# \u2560\u25504fb1c47c-8d70-11eb-3d5c-01c5bb7190fe\n# \u2560\u25505838d806-8d70-11eb-2a78-fb586f056012\n# \u255f\u250007c85e9e-8d95-11eb-295d-63a99f7aa921\n# \u2560\u25509bfd33fc-8d70-11eb-3a9c-bb9a990cbcf9\n# \u2560\u2550ee25cbe6-8d8c-11eb-3323-c521a67b10f0\n# \u2560\u25501cba8970-8d91-11eb-01d8-09d8d076dc73\n# \u2560\u25506b96d95e-8d91-11eb-25ac-75f21ee9c98e\n# \u2560\u255015dcde1e-8d8c-11eb-0964-d9c5f616e59c\n# \u255f\u25001404a820-8d95-11eb-27d2-531cea578fda\n# \u2560\u2550c859986c-8d93-11eb-1211-db9c435de034\n# \u2560\u2550f3bac6a4-8d93-11eb-2614-1572443e3415\n# \u255f\u25007e069492-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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 83e01f80-884a-11eb-1ef7-e9cb5ab3ed20\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 4c951444-8869-11eb-0b88-55a9fb9e51e6\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# \u2554\u2550\u2561 8c87c3b8-884a-11eb-10c8-73e2dab560ea\nmd\"\"\"\n### Context\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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\u209b = 0:0.5:10\n  y\u209b = 0:-.45:-9\n  z\u209b = f.(x\u209b, y\u209b)\n  scatter!(x\u209b, y\u209b, z\u209b, marker=:v, markersize=4, color=:steelblue, legend=false)\nend\n\n# \u2554\u2550\u2561 221734fe-8869-11eb-331a-b5810d0b784c\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1859c082-8853-11eb-18f6-2bc7a180b4a2\nbegin\n  const AF =  AbstractFloat\n  const VT = Vector{T} where T <: AbstractFloat\nend\n\n# \u2554\u2550\u2561 d27feefa-884c-11eb-3b84-1f529d7f6410\nbegin\n  function diff_quotient(f::Function, x::AF, \u0394::AF)::AF\n    (f(x + \u0394) - f(x)) / \u0394\n  end\n\n  diff_quotient(f::Function, v::Vector{AF}, \u0394::AF) = diff_quotient.(f, v, \u0394)\nend\n\n# \u2554\u2550\u2561 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 + \u0394, f (x + \u0394)) . As \u0394 gets tends to 0,, the almost-tangent line gets closer and closer to the tangent line.\n\"\"\"\n\n# \u2554\u2550\u2561 55fab426-8853-11eb-01f8-cbde45c7de9c\n# TODO figure\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 d25d8eac-884c-11eb-2063-27413f8aba04\nmd\"\"\"\nWhat if we cannot? Weel we can estimate the derivative by evaluating the difference quotient for very small \u0394. For example:\n\"\"\"\n\n# \u2554\u2550\u2561 480f7b18-8854-11eb-2898-8d876317ebe2\nbegin\n  x\u1d63 = -10.:10.\n  \u0394 = 1e-3\n\n  y\u1d63 = square.(collect(x\u1d63));\n  dy\u1d63 = deriv_square.(x\u1d63);\n  dy\u0302\u1d63 = diff_quotient.(square, x\u1d63, \u0394);\nend\n\n# \u2554\u2550\u2561 47ee8cb4-8854-11eb-252b-852fd56aa40f\nbegin\n  plot(x\u1d63, y\u1d63, label=\"Square\", marker=:o, color=:green)\n  scatter!(x\u1d63, dy\u1d63, label=\"Actual\", marker=:o, color=:salmon)\n  scatter!(x\u1d63, dy\u0302\u1d63, label=\"Estimate\", marker=:x, color=:darkslateblue,\n    markersize=5, title=\"Actual derivatives vs Estimates\")\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 f5980b54-8856-11eb-3e30-89c3f188ca8d\nbegin\n  function \u2202_diff_quotient(f::Function, v::VT, i::Integer, \u0394::AF)::AF\n    \"\"\"\n    Returns the i-th partial difference quotient of f at v\n    \"\"\"\n    w = copy(v)\n    w[i] += \u0394\n    (f.(w...) - f.(v...)) / \u0394\n  end\n\n  \u2202_diff_quotient(f::Function, v::Vector{AF}, \u0394::AF)::AF =\n    \u2202_diff_quotient.(f, Tuple(v), 1:length(v), \u0394)\nend\n\n# \u2554\u2550\u2561 f57b16b6-8856-11eb-3409-47f7b438f491\nmd\"\"\"\nWith this definition we can then estimate the gradient.\n\"\"\"\n\n# \u2554\u2550\u2561 f55dd09c-8856-11eb-1823-290fcb200662\nfunction estimate_\u2207(f::Function, v::VT, \u0394::AF)::VT\n  [\u2202_diff_quotient(f, v, i, \u0394) for i in 1:length(v)]\nend\n\n# \u2554\u2550\u2561 33df0458-885c-11eb-2635-371a9590d833\nbegin\n  fn(u::AF, v::AF) = u^2 + v\n\n  \u2202fn\u1d64(u::AF, _v::AF) = 2. * u  # \u2202fn w.r.t u\n  \u2202fn\u1d65(_u::AF, v::AF) = 1       # \u2202fn w.r.t v\nend\n\n# \u2554\u2550\u2561 e76a5b58-885c-11eb-0067-010ba1d4c9b5\nbegin\n  Base.:\u2248(x::AF, y::AF; \u03f5=1e-4) = abs(x - y) \u2264 \u03f5\n\n  Base.:\u2248(u::Vector{T}, v::Vector{T}; \u03f5=1e-4) where T <: AF = abs.(u - v) .\u2264 \u03f5\nend\n\n# \u2554\u2550\u2561 e783d618-8858-11eb-0c0b-b57e54bd3757\nbegin\n  \u0394\u2081 = 1e-6\n  vm = Float64[1., 2.]\n  ix = 1\n  @test \u2202fn\u1d64(vm...) \u2248 \u2202_diff_quotient(fn, vm, ix, \u0394\u2081)\nend\n\n# \u2554\u2550\u2561 e767c1bc-8858-11eb-1b29-596a25a4fea4\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# \u2554\u2550\u2561 e747b052-8858-11eb-3c50-5355fef542c9\nmd\"\"\"\n### Using the Gradient\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 cbfa193c-885d-11eb-3a48-97b26377b4fb\nfunction \u2207_step(v::VT, \u2207::VT, \u03b7::AF)::VT\n  @assert length(v) == length(\u2207)\n  v + \u03b7 * \u2207\nend\n\n# \u2554\u2550\u2561 cbe180fe-885d-11eb-1307-7f3ac4897441\n\u2207_sum_of_square(v::VT) = deriv_square(v)\n\n# \u2554\u2550\u2561 d21bb0fe-884c-11eb-224f-216a811365a8\nfunction gradient_descent(fn;range=1000, rng=MersenneTwister(42), \u03b7=1e-2)\n  v = rand(rng, 3)\n  for epoch \u2208 1:range\n    \u2207 = fn(v)\n    v = \u2207_step(v, \u2207, -\u03b7) ## take a step in negative direction of the gradient\n    epoch % 100 == 0 && println(\"$(epoch) => v: $(v)\")\n  end\n  v\nend\n\n# \u2554\u2550\u2561 de2e6604-8863-11eb-3a27-8f8e8b55e5d8\nwith_terminal() do\n  gradient_descent(\u2207_sum_of_square)\nend\n\n# \u2554\u2550\u2561 3082d12e-8864-11eb-06bc-cdf9202cd20a\nbegin\n  @test all(Base.:\u2248(gradient_descent(\u2207_sum_of_square), zeros(Float64, 3); \u03f5=1.e-7))\n  @test all(gradient_descent(\u2207_sum_of_square) \u2248 zeros(Float64, 3))\nend9.93698\n\n-1.0823\n\n# \u2554\u2550\u2561 306b8d52-8864-11eb-1cbd-1341afcd52ff\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8c4d28fc-884a-11eb-0de2-b58988dc7422\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 89ebdac6-8869-11eb-25ac-2dac6a4b20aa\nbegin\n  rng = MersenneTwister(42)\n  data = [[x, 10x + 5. + 40. * randn(rng, 1)[1]] for x \u2208 -50.:50.]\n  # linear pattern with some (Normally distributed) noise\nend\n\n# \u2554\u2550\u2561 89d1728a-8869-11eb-0001-875c2a452cf8\nscatter(map(x -> x[1], data), map(y -> y[2], data), legend=false)\n\n# \u2554\u2550\u2561 c0cc67c8-888b-11eb-272c-05a727c634ea\ntypeof(data)\n\n# \u2554\u2550\u2561 4bf3d986-886d-11eb-3ea8-7926f5babce0\nfunction linear_\u2207(x::AF, y::AF, \u03b8::VT)::VT\n  slope, intercept = \u03b8\n  y\u0302 = slope * x + intercept   # prediction model\n  \u0394err = (y\u0302 - y)\n  # squared_\u0394err = \u0394err^2\n  [2. * \u0394err * x, 2. * \u0394err]\nend\n\n# \u2554\u2550\u2561 d8f972a0-8881-11eb-2be8-db89fb95a9f1\nmd\"\"\"\nWe are going to:\n  1. Start with random initialisation of the parameters (\u03b8)\n  1. Compute the mean of the gradient\n  1. Adjust \u03b8\n  1. Repeat\n\"\"\"\n\n# \u2554\u2550\u2561 1b26337a-8882-11eb-2439-e106cdb884f5\nfunction \u2207_descent(inputs::Vector{Vector{T}};\n    \u03b7=1e-5, nepochs=5_000) where T <: AF\n  u = Uniform(-1., 1.)\n  \u03b8 = [rand(u) for _ \u2208 1:2]\n\n  for epoch \u2208 1:nepochs\n    \u2207 = \u03bc([linear_\u2207(x, y, \u03b8) for (x, y) \u2208 inputs])\n    \u03b8 = \u2207_step(\u03b8, \u2207, -\u03b7)\n    epoch % 100 == 0 && println(\"$(epoch) => \u03b8: $(\u03b8)\")\n  end\n\n  (slope, intercept) = \u03b8\nend\n\n# \u2554\u2550\u2561 1b09cc9e-8882-11eb-0efc-630028d87217\nbegin\n  slope, intercept = \u2207_descent(data; nepochs=1_000)\n  @test 9.90 \u2264 slope \u2264 10.1\n  @test abs(intercept) \u2264 1.0\nend\n\n# \u2554\u2550\u2561 28b44b3c-88f8-11eb-23dd-bbfe325d70d3\nmd\"\"\"\nLet's plot our result:\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 1ad358e4-8882-11eb-0559-bd43867dacfd\nhtml\"\"\"\n<hr />\n\"\"\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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 \u2264 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 \u2265 length(iter.ds) && return (batch, (nothing, ix))\n\t\t## otherwise\n\t\tjx = ix\n\t\tix += iter.bsize\n\t\tix = ix \u2265 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# \u2554\u2550\u2561 714137c2-8900-11eb-3b4b-57abc5409bd2\nlet _ix = 0, bsz = 15\n\tfor batch \u2208 MiniBatch{Float64}(data, bsz)\n\t\t@assert length(batch) == bsz || 0 \u2264 length(batch) \u2264 bsz\n\t\t_ix += 1\n\tend\n\t@test _ix == 7\nend\n\n# \u2554\u2550\u2561 7125e906-8900-11eb-3cd5-69755931c32d\nlet _ix = 0, bsz = 12\n\tfor batch \u2208 MiniBatch{Float64}(data, bsz)\n\t\t@assert length(batch) == bsz || 0 \u2264 length(batch) \u2264 bsz\n\t\t_ix += 1\n\tend\n\t@test _ix == 9\nend\n\n# \u2554\u2550\u2561 401f3d8e-8904-11eb-1065-1de6c9bf32be\nmd\"\"\"\nlet's rewrite our gradient(\u2207) descent with min-batch:\n\"\"\"\n\n# \u2554\u2550\u2561 70eef976-8900-11eb-3a03-af04f8dea9cc\nfunction minibatch_\u2207_descent(inputs::Vector{Vector{T}};\n    \u03b7=1e-5, nepochs=5_000, bsize=10) where T <: AF\n  u = Uniform(-1., 1.)\n  \u03b8 = [rand(u) for _ \u2208 1:2]\n\n  for epoch \u2208 1:nepochs\n\t\tfor batch \u2208 MiniBatch{eltype(inputs[1][1])}(inputs, bsize)\n\t\t\t\u2207 = \u03bc([linear_\u2207(x, y, \u03b8) for (x, y) \u2208 inputs])\n    \t\t\u03b8 = \u2207_step(\u03b8, \u2207, -\u03b7)\n\t\tend\n    epoch % 100 == 0 && println(\"$(epoch) => \u03b8: $(\u03b8)\")\n  end\n\n  (slope, intercept) = \u03b8\nend\n\n# \u2554\u2550\u2561 70d67f74-8900-11eb-0174-f5c05571848e\nbegin\n  slope\u2082, intercept\u2082 = minibatch_\u2207_descent(data; nepochs=100) ## only 100 epochs \n  @test 9.90 \u2264 slope\u2082 \u2264 10.1\n  @test abs(intercept\u2082) \u2264 1.0\nend\n\n# \u2554\u2550\u2561 8d33a0f4-8906-11eb-3690-ddd49fc6cee1\nbegin\n  # x_\u2082 = [-50.0, 50.0]\n  y_\u2082 = slope .* x_ .+ intercept\n  #\n  scatter(map(x -> x[1], data), map(y -> y[2], data), legend=false)\n  plot!(x_, y_\u2082, lw=3, color=:darkred)\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500380c26d0-881d-11eb-0461-f339488ea81e\n# \u2560\u2550e03dd22c-884c-11eb-2432-3dc04b0cf286\n# \u255f\u250083e01f80-884a-11eb-1ef7-e9cb5ab3ed20\n# \u255f\u2500853ab02c-884a-11eb-01bf-1712dc177ffb\n# \u255f\u25004c951444-8869-11eb-0b88-55a9fb9e51e6\n# \u255f\u25008c87c3b8-884a-11eb-10c8-73e2dab560ea\n# \u255f\u25008c6ba818-884a-11eb-23e0-2f1c297d88f5\n# \u2560\u2550d2d18b22-884c-11eb-1f93-037453c5395b\n# \u255f\u2500221734fe-8869-11eb-331a-b5810d0b784c\n# \u255f\u2500d297fa06-884c-11eb-294e-85992f901be1\n# \u2560\u25501859c082-8853-11eb-18f6-2bc7a180b4a2\n# \u2560\u2550d27feefa-884c-11eb-3b84-1f529d7f6410\n# \u255f\u25005618fb40-8853-11eb-3d2f-032437d22a09\n# \u2560\u255055fab426-8853-11eb-01f8-cbde45c7de9c\n# \u255f\u250055e3efea-8853-11eb-0821-c5c580bc8fc5\n# \u2560\u255055c56cc8-8853-11eb-04f4-3be84a352808\n# \u255f\u2500d25d8eac-884c-11eb-2063-27413f8aba04\n# \u2560\u2550480f7b18-8854-11eb-2898-8d876317ebe2\n# \u2560\u255047ee8cb4-8854-11eb-252b-852fd56aa40f\n# \u255f\u250047d2c2cc-8854-11eb-35f9-952876481d02\n# \u2560\u2550f5980b54-8856-11eb-3e30-89c3f188ca8d\n# \u255f\u2500f57b16b6-8856-11eb-3409-47f7b438f491\n# \u2560\u2550f55dd09c-8856-11eb-1823-290fcb200662\n# \u2560\u255033df0458-885c-11eb-2635-371a9590d833\n# \u2560\u2550e76a5b58-885c-11eb-0067-010ba1d4c9b5\n# \u2560\u2550e783d618-8858-11eb-0c0b-b57e54bd3757\n# \u255f\u2500e767c1bc-8858-11eb-1b29-596a25a4fea4\n# \u255f\u2500e747b052-8858-11eb-3c50-5355fef542c9\n# \u255f\u2500cc17413a-885d-11eb-1629-47fc5220529e\n# \u2560\u2550cbfa193c-885d-11eb-3a48-97b26377b4fb\n# \u2560\u2550cbe180fe-885d-11eb-1307-7f3ac4897441\n# \u2560\u2550d21bb0fe-884c-11eb-224f-216a811365a8\n# \u2560\u2550de2e6604-8863-11eb-3a27-8f8e8b55e5d8\n# \u2560\u25503082d12e-8864-11eb-06bc-cdf9202cd20a\n# \u255f\u2500306b8d52-8864-11eb-1cbd-1341afcd52ff\n# \u255f\u2500304ff894-8864-11eb-1449-b71da9112247\n# \u255f\u25008c4d28fc-884a-11eb-0de2-b58988dc7422\n# \u255f\u25008a07d906-8869-11eb-0bae-2582b352c05c\n# \u2560\u255089ebdac6-8869-11eb-25ac-2dac6a4b20aa\n# \u2560\u255089d1728a-8869-11eb-0001-875c2a452cf8\n# \u2560\u2550c0cc67c8-888b-11eb-272c-05a727c634ea\n# \u2560\u25504bf3d986-886d-11eb-3ea8-7926f5babce0\n# \u255f\u2500d8f972a0-8881-11eb-2be8-db89fb95a9f1\n# \u2560\u25501b26337a-8882-11eb-2439-e106cdb884f5\n# \u2560\u25501b09cc9e-8882-11eb-0efc-630028d87217\n# \u255f\u250028b44b3c-88f8-11eb-23dd-bbfe325d70d3\n# \u2560\u25501c89f188-88f6-11eb-026c-e59bb08ac7ac\n# \u255f\u25001ad358e4-8882-11eb-0559-bd43867dacfd\n# \u255f\u2500d8d3bb0a-8881-11eb-35b2-8f486d6cc094\n# \u2560\u2550cd7c444a-8893-11eb-2409-f161ebc287b5\n# \u2560\u2550714137c2-8900-11eb-3b4b-57abc5409bd2\n# \u2560\u25507125e906-8900-11eb-3cd5-69755931c32d\n# \u255f\u2500401f3d8e-8904-11eb-1065-1de6c9bf32be\n# \u2560\u255070eef976-8900-11eb-3a03-af04f8dea9cc\n# \u2560\u255070d67f74-8900-11eb-0174-f5c05571848e\n# \u2560\u25508d33a0f4-8906-11eb-3690-ddd49fc6cee1\n# \u255f\u25000a1acf66-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": "module TotalVariation\n\nusing BenchmarkTools\nusing StructuredOptimization\nusing AbstractOperators\nusing Images\nusing ImageView\nusing TestImages\n\nfunction set_up()\n\tsrand(123)\n\timg = testimage(\"cameraman\")\n\n\tX = convert(Array{Float64},img) # convert image to array\n\tXt = X.+sqrt(0.006*vecnorm(X,Inf))*randn(size(X)) # add noise\n\tXt[Xt .< 0] .= 0. #make sure pixels are in range\n\tXt[Xt .> 1] .= 1.\n\n\tV = Variation(size(X)) # linear mapping operator\n\tlambda = 0.07          # level of regularization\n\n\tY = Variable(size(V,1)...) # dual variables\n\treturn V, Y, Xt, X, lambda\nend\n\nfunction run_demo()\n\tLf  = 8                # Lipschitz constant\n\tslv = PANOC(tol = 1e-3, gamma = 1/Lf, adaptive = false)\n\tsetup = set_up()\n\t@time solve_problem!(slv,setup...)\n\treturn setup\nend\n\nfunction solve_problem!(slv,V, Y, Xt, X, lambda)\n\tit,  = @minimize ls(-V'*Y+Xt)+conj(lambda*norm(Y,2,1,2)) with slv\n\treturn it\nend\n\nfunction benchmark(;verb = 0, samples = 5, seconds = 100, tol = 1e-3, maxit = 50000 )\n\n\tsuite = BenchmarkGroup()\n\n\tsolvers = [\"ZeroFPR\",\n               \"PANOC\",\n               \"FPG\",\n               \"PG\"]\n\tslv_opt = [\"(verbose = $verb, tol = $tol, gamma = 1/8, maxit = $maxit)\", \n               \"(verbose = $verb, tol = $tol, gamma = 1/8, maxit = $maxit)\",\n               \"(verbose = $verb, tol = $tol, gamma = 1/8, maxit = $maxit)\",\n               \"(verbose = $verb, tol = $tol, gamma = 1/8, maxit = $maxit)\"]\n\n\tits = Dict([(sol,0.) for sol in solvers])\n\tfor i in eachindex(solvers)\n\n\t\tsetup = set_up()\n\t\tsolver = eval(parse(solvers[i]*slv_opt[i]))\n\n\t\tsuite[solvers[i]] = \n\t\t@benchmarkable(it = solve_problem!(solver, setup...), \n\t\t\t       setup = ( \n\t\t\t\t\tit = 0;\n\t\t\t\t\tsetup = deepcopy($setup); \n\t\t\t\t\tsolver = deepcopy($solver) ), \n\t\t\t       teardown = (\n\t\t\t\t\t  $its[$solvers[$i]] = it;\n\t\t\t\t\t  ), \n\t\t\t       evals = 1, samples = samples, seconds = seconds)\n\tend\n\n\tresults = run(suite, verbose = (verb != 0))\n\tprintln(\"TotalVariation its\")\n\tprintln(its)\n\treturn results\nend\n\nfunction show_results(V, Y, Xt, X, lambda)\n\tXd = Xt-V'*(~Y)\n\timshow(X)\n\timshow(Xt)\n\timshow(Xd)\nend\n\nend\n", "meta": {"hexsha": "883404055fc94a02ee1aa24ac4ecaaa196947c98", "size": 2080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/TotalVariation.jl", "max_stars_repo_name": "JuliaDocsForks/StructuredOptimization.jl", "max_stars_repo_head_hexsha": "0c9295c23e30e26940c84eaaf499cc8722698635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2018-03-08T13:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T20:29:36.000Z", "max_issues_repo_path": "benchmarks/TotalVariation.jl", "max_issues_repo_name": "JuliaDocsForks/StructuredOptimization.jl", "max_issues_repo_head_hexsha": "0c9295c23e30e26940c84eaaf499cc8722698635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-03-16T01:06:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T21:39:30.000Z", "max_forks_repo_path": "benchmarks/TotalVariation.jl", "max_forks_repo_name": "JuliaDocsForks/StructuredOptimization.jl", "max_forks_repo_head_hexsha": "0c9295c23e30e26940c84eaaf499cc8722698635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-11T14:10:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T09:08:24.000Z", "avg_line_length": 24.7619047619, "max_line_length": 85, "alphanum_fraction": 0.5971153846, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7500382338638717}}
{"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\u0394x,\u0394t = 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\u03c3x = 0.5\n\u03c3y = 0.1\ngauss = SpatialGaussian(\u03c3x,\u03c3y,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\u03c3t = 0.1\npparams = PulseParams(gauss,t0,\u03c3t);\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,\u0394x,xlim,ylim,\u0394t,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,\u0394x,xlim,ylim,\u0394t,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(\u03bb=1.0)\n\nWith a nonnegative scalar `\u03bb`, returns the function\n```math\nf(x) = \u03bb\\\\|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 \u03bb 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": "using Test\nusing SPGBox\n\n@testset \"simple polynomial\" begin\n\n  f(x) = x[1]^2 + (x[2]-1.)^2\n  \n  function g!(g,x) \n    g[1] = 2*x[1]\n    g[2] = 2*(x[2]-1.)\n  end\n  \n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x)\n  @test R.f \u2248 0.\n  @test R.x \u2248 [0.,1.]\n  \n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x,lower=[2,-Inf])\n  @test R.f \u2248 4. \n  @test R.x \u2248 [2.,1.]\n  \n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x,lower=[-Inf,2.])\n  @test R.f \u2248 1.\n  @test R.x \u2248 [0.,2.]\n  \n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x,upper=[+Inf,-2])\n  @test R.f \u2248 9. \n  @test R.x \u2248 [0.,-2.]\n  \n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x,upper=[-2,+Inf])\n  @test R.f \u2248 4. \n  @test R.x \u2248 [-2.,1.]\n\n  # just testing the interface\n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x,lower=[-Inf,2.])\n  @test R.f \u2248 1.\n  @test R.x \u2248 [0.,2.]\n  \n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x,upper=[-2,+Inf])\n  @test R.f \u2248 4.\n  @test R.x \u2248 [-2.,1.]\n\n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,x,lower=[-Inf,-2.],upper=[+Inf,2])\n  @test R.f \u2248 0.\n  @test R.x \u2248 [0.,1.]\n  \n  x = [ 10. , 18. ]\n  R = spgbox!(f,g!,[-Inf,-2.],[+Inf,2],x)\n  @test R.f \u2248 0.\n  @test R.x \u2248 [0.,1.]\n  \n  # Test the mutating call  \n  x = [ 10. , 18. ]\n  R = spgbox(f,g!,[-Inf,-2.],[+Inf,2],x)\n  @test x == [ 10. , 18. ]\n  @test R.f \u2248 0.\n  @test R.x \u2248 [0.,1.]\n  \n  x = [ 10. , 18. ]\n  R = spgbox(f,g!,x,lower=[-Inf,-2.],upper=[+Inf,2])\n  @test x == [ 10. , 18. ]\n  @test R.f \u2248 0.\n  @test R.x \u2248 [0.,1.]\n  \nend\n\n\n\n\n\n\n\n", "meta": {"hexsha": "2628a8b3431697e17df45cedb8cb7bda86ce1ffa", "size": 1412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "longemen3000/SPGBox.jl", "max_stars_repo_head_hexsha": "43b0b82f2c7ea4000ba53a313bbbe1ce58ab2bd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-05-15T04:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:27:10.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "longemen3000/SPGBox.jl", "max_issues_repo_head_hexsha": "43b0b82f2c7ea4000ba53a313bbbe1ce58ab2bd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-04-24T00:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T14:47:11.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "longemen3000/SPGBox.jl", "max_forks_repo_head_hexsha": "43b0b82f2c7ea4000ba53a313bbbe1ce58ab2bd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-12T02:15:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T02:15:12.000Z", "avg_line_length": 17.65, "max_line_length": 53, "alphanum_fraction": 0.4114730878, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7500191872047645}}
{"text": "using Test\nusing jInvVis\nusing jInv.Mesh\nusing Plots\n\n# tests for regular mesh\ndomain = [0 1.1 0 1.0 ]\nn      = [8 5 ]\nMr    = getRegularMesh(domain,n)\nI     = randn(tuple(n...))\nxc    = getCellCenteredGrid(Mr)\n\nprintln(\"=== test viewImage2D  ===\")\n\n\nviewImage2D(xc[:,1],Mr)\nxlabel!(\"intensity increases -->\")\nylabel!(\"constant intensity\")\n# subplot(1,2,2)\nviewImage2D(xc[:,2],Mr)\nylabel!(\"intensity increases -->\")\nxlabel!(\"constant intensity\")\n# println(\"==== all passed === \")\n", "meta": {"hexsha": "78d45ff998076a9d4f1511c5086b317c90d9fb56", "size": 480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testViewImage2D.jl", "max_stars_repo_name": "JuliaInv/jInvVis.jl", "max_stars_repo_head_hexsha": "49b3a041734b043ed945ee06e41a3988052554f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-29T20:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-29T20:52:09.000Z", "max_issues_repo_path": "test/testViewImage2D.jl", "max_issues_repo_name": "JuliaInv/jInvVis.jl", "max_issues_repo_head_hexsha": "49b3a041734b043ed945ee06e41a3988052554f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-04-04T09:18:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-15T04:43:24.000Z", "max_forks_repo_path": "test/testViewImage2D.jl", "max_forks_repo_name": "JuliaInv/jInvVis.jl", "max_forks_repo_head_hexsha": "49b3a041734b043ed945ee06e41a3988052554f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-03-31T15:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:48.000Z", "avg_line_length": 20.0, "max_line_length": 36, "alphanum_fraction": 0.6458333333, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7500096479802998}}
{"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 \u00f7= 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\u2081,\u2026,f\u2096)\n\nGiven functions `f\u2081` to `f\u2096`, returns their sum\n\n```math\ng(x) = \u2211_{i=1}^k f_i(x).\n```\n\nThe functions `f\u1d62` should all have the same domain, which will be the domain of\nthe result. If all `f\u1d62` 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 \u21a6 f\u2081(x) + \u2026 + f\u2096(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# \u2554\u2550\u2561 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.7\"\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 8f60b2f6-20f9-11eb-0a66-771e655035a3\nmgf(s) = 4(1+(s-1)*MathConstants.e^s)*(MathConstants.e^s-1-s)/s^4\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 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# \u2554\u2550\u2561 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.7\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# \u2560\u25506fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# \u2560\u25506ffe2628-1ea1-11eb-24ea-57f985146a72\n# \u2560\u255070179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# \u2560\u25508f60b2f6-20f9-11eb-0a66-771e655035a3\n# \u2560\u25508f61044a-20f9-11eb-1485-d145145c4c57\n# \u2560\u25508f6181a4-20f9-11eb-3eae-6dc331b9a88a\n# \u255f\u250070182cd8-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# \u2554\u2550\u2561 1c7e914c-03c9-11eb-11cf-0d9346305a53\nbegin\n\tusing Pkg\n\tcd(joinpath(dirname(@__FILE__),\"..\"))\n    Pkg.activate(pwd())\n\tusing NLopt\nend\n\n# \u2554\u2550\u2561 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# \u2554\u2550\u2561 2121e5be-03c9-11eb-2b8b-a10cb146216d\nret\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u25501c7e914c-03c9-11eb-11cf-0d9346305a53\n# \u2560\u25501866ec44-03c9-11eb-0a21-416587e4e0e0\n# \u2560\u25502121e5be-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": "using Test\nusing UnivariateGaussianProcess\n\nglobal atol = 1e-8\n\n@testset \"Acquisition function optimization\" begin\n    @test UnivariateGaussianProcess.find_local_opt(x -> x^2, -1., 1.)[1] \u2248 0. atol=atol\n    @test UnivariateGaussianProcess.find_local_opt(x -> -sin(x), 0., \u03c0)[1] \u2248 \u03c0/2 atol=atol\nend\n\n@testset \"Kernel computation\" begin\n    cov_func = (x1,x2) -> abs(x2 - x1)\n    data_x = [1., 2., 3.]\n    noise = 0.\n    @test UnivariateGaussianProcess.create_kernel(cov_func, data_x; noise) \u2248 [\n        0. 1. 2.\n        1. 0. 1.\n        2. 1. 0.\n    ] atol=atol\n    \n    cov_func = (x1,x2) -> abs(x2 - x1)\n    data_x = [1., 2., 3.]\n    noise = 0.1\n    @test UnivariateGaussianProcess.create_kernel(cov_func, data_x; noise) \u2248 [\n        0.01 1. 2.\n        1. 0.01 1.\n        2. 1. 0.01\n    ] atol=atol\n\n    cov_func = (x1,x2) -> abs(x2 - x1)\n    K = [0.01 1. 2.\n         1. 0.01 1.\n         2. 1. 0.01]\n    old_data_x = [1., 2., 3.]\n    new_x = 5.\n    noise = 0.1\n    @test UnivariateGaussianProcess.update_kernel(cov_func, K, old_data_x, new_x; noise) \u2248 [\n        0.01 1. 2. 4.\n        1. 0.01 1. 3.\n        2. 1. 0.01 2.\n        4. 3. 2. 0.01\n    ] atol=atol\nend\n", "meta": {"hexsha": "db1f0c5c753e917600986d19f314610661a69756", "size": 1162, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Sheld5/UnivariateGaussianProcess", "max_stars_repo_head_hexsha": "8ee5b6cb4cf91b46ca4995294c14e3d1a9fc41f2", "max_stars_repo_licenses": ["MIT"], "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": "Sheld5/UnivariateGaussianProcess", "max_issues_repo_head_hexsha": "8ee5b6cb4cf91b46ca4995294c14e3d1a9fc41f2", "max_issues_repo_licenses": ["MIT"], "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": "Sheld5/UnivariateGaussianProcess", "max_forks_repo_head_hexsha": "8ee5b6cb4cf91b46ca4995294c14e3d1a9fc41f2", "max_forks_repo_licenses": ["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.4090909091, "max_line_length": 92, "alphanum_fraction": 0.5542168675, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7500096278015984}}
{"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n    Center()\n\nThe transform that removes the mean of the variables.\n\"\"\"\nstruct Center <: Colwise end\n\nassertions(::Type{Center}) = [assert_continuous]\n\nisrevertible(::Type{Center}) = true\n\ncolcache(::Center, x) = mean(x)\n\ncolapply(::Center, x, \u03bc)  = @. x - \u03bc\n\ncolrevert(::Center, y, \u03bc) = @. y + \u03bc", "meta": {"hexsha": "c6e1ffd29ad3ced0461ce0d9ae6c06d7991e9ae4", "size": 506, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/center.jl", "max_stars_repo_name": "Omar-Elrefaei/TableTransforms.jl", "max_stars_repo_head_hexsha": "8c330eb6473228b61c9977d05480afb88d4f5c79", "max_stars_repo_licenses": ["MIT"], "max_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/center.jl", "max_issues_repo_name": "Omar-Elrefaei/TableTransforms.jl", "max_issues_repo_head_hexsha": "8c330eb6473228b61c9977d05480afb88d4f5c79", "max_issues_repo_licenses": ["MIT"], "max_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/center.jl", "max_forks_repo_name": "Omar-Elrefaei/TableTransforms.jl", "max_forks_repo_head_hexsha": "8c330eb6473228b61c9977d05480afb88d4f5c79", "max_forks_repo_licenses": ["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.3, "max_line_length": 68, "alphanum_fraction": 0.4822134387, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.75000962596296}}
{"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 \u2208 1:n\n\t\tq[i, 1] = y[i];\n\tend\n\tfor i \u2208 2:n\n\t\tfor j \u2208 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}}
{"text": "# Check of handedness\n@test CMBSim.rotationmatrix_normalized(CMBSim.qrotation_x(\u03c0/2)) * [0, 1, 0] \u2248 [0, 0, 1]\n@test CMBSim.rotationmatrix_normalized(CMBSim.qrotation_y(\u03c0/2)) * [1, 0, 0] \u2248 [0, 0, -1]\n@test CMBSim.rotationmatrix_normalized(CMBSim.qrotation_z(\u03c0/2)) * [1, 0, 0] \u2248 [0, 1, 0]\n\n# Simple composition of rotations\n@test CMBSim.qrotation_x(\u03c0/3) * CMBSim.qrotation_x(\u03c0/3) \u2248 CMBSim.qrotation_x(2\u03c0/3)\n@test CMBSim.qrotation_y(\u03c0/3) * CMBSim.qrotation_y(\u03c0/3) \u2248 CMBSim.qrotation_y(2\u03c0/3)\n@test CMBSim.qrotation_z(\u03c0/3) * CMBSim.qrotation_z(\u03c0/3) \u2248 CMBSim.qrotation_z(2\u03c0/3)\n\n# More complex compositions\ncomp = CMBSim.qrotation_y(\u03c0/2) * CMBSim.qrotation_x(\u03c0/2)\n@test CMBSim.rotationmatrix_normalized(comp) * [0, 1, 0] \u2248 [1, 0, 0]\n\ncomp = CMBSim.qrotation_z(\u03c0/2) * CMBSim.qrotation_y(\u03c0/2)\n@test CMBSim.rotationmatrix_normalized(comp) * [0, 0, 1] \u2248 [0, 1, 0]\n", "meta": {"hexsha": "407f0bb7307d5e4784275cb5cc2bef036375c82c", "size": 853, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_quaternions.jl", "max_stars_repo_name": "JuliaTagBot/CMBMissionSimOld.jl", "max_stars_repo_head_hexsha": "8ccfa75d2722683e3c7a3cc33b4b6bdf9018a317", "max_stars_repo_licenses": ["MIT"], "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_quaternions.jl", "max_issues_repo_name": "JuliaTagBot/CMBMissionSimOld.jl", "max_issues_repo_head_hexsha": "8ccfa75d2722683e3c7a3cc33b4b6bdf9018a317", "max_issues_repo_licenses": ["MIT"], "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_quaternions.jl", "max_forks_repo_name": "JuliaTagBot/CMBMissionSimOld.jl", "max_forks_repo_head_hexsha": "8ccfa75d2722683e3c7a3cc33b4b6bdf9018a317", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:21:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:21:44.000Z", "avg_line_length": 50.1764705882, "max_line_length": 88, "alphanum_fraction": 0.7127784291, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7500027343926384}}
